assignment-user-matcher 1.2.0 → 1.2.2

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 CHANGED
@@ -51,6 +51,29 @@ 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.
59
+
60
+ Hard veto configuration example:
61
+
62
+ ```ts
63
+ await assignmentMatcher.addUser({
64
+ id: 'agent_1',
65
+ tags: [],
66
+ routingWeights: {
67
+ 'support:*': 100, // eligible
68
+ 'lang:*': 0, // hard veto for all language-tagged assignments
69
+ default: 0, // hard veto for default matching fallback
70
+ },
71
+ });
72
+ ```
73
+
74
+ Note: `usingDefaultMatchScore` is an internal implementation detail and is **not** a public option.
75
+ Configure hard veto behavior only through `routingWeights` values.
76
+
54
77
  3. **Prioritization Engine:**
55
78
  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.
56
79
 
@@ -143,6 +166,53 @@ async function runExample() {
143
166
  runExample().catch(console.error);
144
167
  ```
145
168
 
169
+ ### 3. Workflow Quick Start
170
+
171
+ Workflows are easiest to use with the builder helpers and the `executeWorkflow()` convenience method.
172
+
173
+ ```typescript
174
+ import AssignmentMatcher, { workflow } from 'assignment-user-matcher';
175
+
176
+ const matcher = new AssignmentMatcher(redisClient, {
177
+ enableWorkflows: true,
178
+ redisPrefix: 'exampleApp:',
179
+ });
180
+
181
+ // Optional if your Redis client is already connected.
182
+ // Useful when the matcher is created with a closed client.
183
+ await matcher.waitUntilReady();
184
+
185
+ const onboardingWorkflow = workflow('onboarding', 'Onboarding')
186
+ .step('profile')
187
+ .name('Complete profile')
188
+ .assignment({ tags: ['profile'], title: 'Complete your profile' })
189
+ .targetUser('initiator')
190
+ .defaultNext('review')
191
+ .done()
192
+ .step('review')
193
+ .name('Manager review')
194
+ .assignment({ tags: ['review'], title: 'Review onboarding' })
195
+ .targetUser({ tag: 'managers' })
196
+ .defaultNext(null)
197
+ .done()
198
+ .build();
199
+
200
+ // Registers the definition if needed, then starts the workflow instance.
201
+ const instance = await matcher.executeWorkflow(onboardingWorkflow, 'agent_007', {
202
+ source: 'signup',
203
+ });
204
+
205
+ console.log(instance.id, instance.currentStepId);
206
+ ```
207
+
208
+ You can still call `registerWorkflow()` and `startWorkflow()` separately if you want explicit lifecycle control.
209
+
210
+ Plain object workflow definitions are also accepted. The library now fills in sensible defaults:
211
+
212
+ - `version` defaults to `1`
213
+ - `initialStepId` defaults to the first step ID
214
+ - invalid definitions fail early during registration with clear validation errors
215
+
146
216
  ## API Reference
147
217
 
148
218
  The main class provided is `AssignmentMatcher`.
@@ -182,6 +252,16 @@ Retrieves the current list of assignments that a user is tentatively matched wit
182
252
 
183
253
  - `userId: string`: The ID of the user.
184
254
 
255
+ ### `getPendingAssignmentsWithAge(): Promise<PendingAssignmentInfo[]>`
256
+
257
+ Retrieves current pending assignments, including who owns each assignment and how long it has been pending.
258
+
259
+ - `assignment`: The assignment payload.
260
+ - `ownerId`: The current owner user ID, or `null` if missing.
261
+ - `pendingForMs`: Elapsed pending time in milliseconds.
262
+ - `pendingSince`: Unix timestamp (ms) when the assignment entered pending state.
263
+ - `expiresAt`: Unix timestamp (ms) when pending expiration is scheduled.
264
+
185
265
  ### `removeUser(userId: string): Promise<void>`
186
266
 
187
267
  Removes a user from the system and clears their assignment backlog.
@@ -194,6 +274,17 @@ Removes a specific assignment from the system. Requires tags to efficiently loca
194
274
 
195
275
  Marks an assignment as completed by a user, removing it from their backlog and potentially making them available for new assignments.
196
276
 
277
+ ### `waitUntilReady(): Promise<AssignmentMatcher>`
278
+
279
+ Waits for the matcher to finish connecting and initializing internal Redis and workflow resources.
280
+
281
+ ### `executeWorkflow(workflowOrId, userId, initialContext?): Promise<WorkflowInstance>`
282
+
283
+ The simplest workflow entrypoint.
284
+
285
+ - Pass a workflow ID to start an already-registered workflow.
286
+ - Pass a workflow definition or builder-produced definition to register it and start it in one call.
287
+
197
288
  ## Options
198
289
 
199
290
  You can pass an options object to the `AssignmentMatcher` constructor:
@@ -213,10 +304,24 @@ type Options = {
213
304
  // until some are completed or removed.
214
305
  maxUserBacklogSize?: number; // Default: 9
215
306
 
216
- // Whether to enable the default tag-based matching logic.
217
- // If set to false, you MUST provide a custom `matchingFunction`.
307
+ // Whether to enable default tag injection/matching behavior.
308
+ // Notes for built-in weighted matching (`routingWeights`):
309
+ // - only weights > 0 are eligible
310
+ // - weight 0 is a hard veto (exact and suffix wildcard)
311
+ // - if no positive weights exist, no assignment is pulled from queue
312
+ // If set to false, you should provide a custom `matchingFunction`.
218
313
  enableDefaultMatching?: boolean; // Default: true
219
314
 
315
+ // Opt-in idle user auto-rejection. When set, users holding pending
316
+ // (not yet accepted/rejected) assignments with no activity for this many
317
+ // milliseconds are removed from the matching pool by `processIdleUsers()`,
318
+ // and their pending assignments are requeued for other users.
319
+ // Activity is recorded automatically on addUser/acceptAssignment/rejectAssignment,
320
+ // or explicitly via `touchUser(userId)` as a heartbeat.
321
+ // Use `startIdleUserInterval(intervalMs)` / `stopIdleUserInterval()` to run
322
+ // the check periodically. Disabled when undefined (default).
323
+ idleUserTimeoutMs?: number; // Default: undefined (disabled)
324
+
220
325
  // A custom function to determine the priority of an assignment.
221
326
  // The function receives assignment objects (or undefined if fewer than 3 are available for comparison)
222
327
  // and should return a numerical priority score. Higher scores mean higher priority.
@@ -228,6 +333,8 @@ type Options = {
228
333
  // If `enableDefaultMatching` is true, this function can augment or override the default logic.
229
334
  // If `enableDefaultMatching` is false, this function is solely responsible for matching.
230
335
  // It should return a tuple: `[matchRank, userCost]`.
336
+ // Important: built-in hard-veto/positive-only weighted semantics apply to the
337
+ // built-in matcher. With a custom matchingFunction, you own final scoring logic.
231
338
  // - `matchRank`: A score indicating the quality of the match (higher is better).
232
339
  // A rank of 0 or less means no match.
233
340
  // - `userCost`: A score indicating the "cost" of assigning this task to this user
@@ -238,9 +345,419 @@ type Options = {
238
345
  assignmentPriority: number | string, // This is the score from prioritizationFunction or createdAt
239
346
  assignmentId?: string,
240
347
  ) => Promise<[number, number]>;
348
+
349
+ // ========== Reinforcement Learning Options ==========
350
+
351
+ // Enable the adaptive learning layer (contextual bandit re-ranking).
352
+ enableLearning?: boolean; // Default: false
353
+
354
+ // SGD learning rate for online model updates.
355
+ learningRate?: number; // Default: 0.1
356
+
357
+ // Epsilon-greedy exploration rate in [0, 1]. With this probability, a random
358
+ // jitter is added to candidate scores so the model keeps gathering data on
359
+ // under-served candidates.
360
+ learningExplorationRate?: number; // Default: 0.05
361
+
362
+ // Shadow mode: record decisions and learn from outcomes, but never alter
363
+ // ranking. Useful for safely evaluating the model before going live.
364
+ learningShadowMode?: boolean; // Default: false
365
+
366
+ // Multiplier applied to the predicted reward when re-ranking candidates.
367
+ // Higher values let the learned model dominate over base priority.
368
+ learningBoostFactor?: number; // Default: 1
369
+
370
+ // Override rewards per lifecycle outcome (merged with defaults):
371
+ // { accept: 0.3, complete: 1, reject: -0.6, expire: -0.3, fail: -0.8 }
372
+ learningRewards?: Partial<Record<'accept' | 'complete' | 'reject' | 'expire' | 'fail', number>>;
373
+
374
+ // Custom feature extractor. Defaults to tag-match, normalized skill-weight,
375
+ // tag-overlap-ratio and embedding-similarity features.
376
+ learningFeatureExtractor?: (user: User, assignment: { id: string; tags: string[] }) => Record<string, number>;
377
+
378
+ // TTL for stored decision contexts in ms.
379
+ learningDecisionTtlMs?: number; // Default: 604800000 (7 days)
380
+
381
+ // Weights applied to named external feedback signals when computing rewards.
382
+ // Signals not listed here default to weight 1. Negative weights turn a
383
+ // signal into a penalty (e.g. { errorRate: -2 }).
384
+ learningSignalWeights?: Record<string, number>;
385
+
386
+ // TTL for archived episodes awaiting late external feedback in ms.
387
+ learningFeedbackTtlMs?: number; // Default: 604800000 (7 days)
241
388
  };
242
389
  ```
243
390
 
391
+ ## Adaptive Matching with Reinforcement Learning
392
+
393
+ The matcher includes an opt-in, Redis-backed contextual bandit that learns from
394
+ assignment outcomes and re-ranks candidates automatically. Hard matching rules
395
+ (tags, `routingWeights`, vetoes, CIDR, `skillThresholds`) always apply first —
396
+ the learned model only reorders assignments that are already eligible.
397
+
398
+ How it works:
399
+
400
+ 1. When a user is matched, a sparse feature vector is extracted for each
401
+ eligible candidate (tag matches, normalized skill weights, tag overlap, and
402
+ optional `embedding` cosine similarity if both user and assignment carry an
403
+ `embedding: number[]` field).
404
+ 2. Candidates are ranked by `combinedPriority + boostFactor * predictedReward`.
405
+ 3. The decision context is stored, and lifecycle outcomes (`accept`,
406
+ `complete`, `reject`, `expire`, `fail`) feed rewards back into the model via
407
+ online SGD updates — fully automatic, no training pipeline needed.
408
+
409
+ ```typescript
410
+ const matcher = new AssignmentMatcher(redisClient, {
411
+ enableLearning: true,
412
+ // Start safe: observe without affecting ranking
413
+ learningShadowMode: true,
414
+ // Optional reward shaping
415
+ learningRewards: { complete: 2, reject: -1 },
416
+ });
417
+
418
+ // ... normal addUser / addAssignment / matchUsersAssignments usage ...
419
+
420
+ // Inspect what the model has learned
421
+ const model = await matcher.getLearningModel(); // { 'tag:english': '0.42', ... }
422
+ const stats = await matcher.getLearningStats(); // { decisions, rewards, totalReward, averageReward }
423
+
424
+ // Manual reward shaping for a matched assignment (e.g. CSAT score arrived later)
425
+ await matcher.recordLearningReward('assignment-123', 1.5);
426
+
427
+ // Start over
428
+ await matcher.resetLearningModel();
429
+ ```
430
+
431
+ ### Feeding External Data into the Model
432
+
433
+ Matchmaking quality signals often arrive after an assignment is closed — QA
434
+ audits, accuracy reviews, customer satisfaction scores, handle-time analysis.
435
+ The learning layer supports three external feed paths:
436
+
437
+ **1. Named feedback signals (post-processing per assignment).** When an
438
+ assignment reaches a terminal state, its feature context is archived as an
439
+ *episode* (kept for `learningFeedbackTtlMs`). External pipelines can attribute
440
+ late signals to it at any point within that window:
441
+
442
+ ```typescript
443
+ const matcher = new AssignmentMatcher(redisClient, {
444
+ enableLearning: true,
445
+ // Reward = sum(signalValue * signalWeight); unlisted signals default to 1
446
+ learningSignalWeights: {
447
+ accuracy: 2, // accuracy audits matter most
448
+ csat: 1, // customer satisfaction
449
+ handleTimePenalty: -0.5, // longer handling reduces reward
450
+ },
451
+ });
452
+
453
+ // ...assignment is matched, accepted, completed...
454
+
455
+ // Hours/days later, the QA pipeline reports back:
456
+ await matcher.recordLearningFeedback('assignment-123', {
457
+ accuracy: 0.95,
458
+ csat: 0.8,
459
+ handleTimePenalty: 0.3,
460
+ });
461
+ // reward = 0.95*2 + 0.8*1 + 0.3*-0.5 = 2.55, applied to the episode's features
462
+ ```
463
+
464
+ **2. Raw reward shaping.** `recordLearningReward(assignmentId, reward)` applies
465
+ an explicit numeric reward against an assignment's decision context when you
466
+ want full control over the value.
467
+
468
+ **3. Offline batch training.** `trainLearningSamples(samples)` updates the
469
+ model directly from raw `(features, reward)` pairs — no live decision context
470
+ needed. Use it to bootstrap the model from historical data or to run scheduled
471
+ imports from a data warehouse:
472
+
473
+ ```typescript
474
+ await matcher.trainLearningSamples([
475
+ { features: { bias: 1, 'tag:english': 1, 'skill:english': 0.8 }, reward: 1.2 },
476
+ { features: { bias: 1, 'tag:billing': 1 }, reward: -0.4 },
477
+ ]);
478
+ ```
479
+
480
+ Feature names are arbitrary strings — as long as your
481
+ `learningFeatureExtractor` produces the same names at match time, externally
482
+ trained weights apply immediately to live ranking.
483
+
484
+ Rollout recommendation: enable with `learningShadowMode: true` first, watch
485
+ `getLearningStats()` and `getLearningModel()`, then flip shadow mode off and
486
+ tune `learningBoostFactor` / `learningExplorationRate` for your workload. For
487
+ domain-specific setups (custom embeddings, business features), supply a
488
+ `learningFeatureExtractor`.
489
+
490
+ ### RL Scalability & Redis Constraints
491
+
492
+ The RL layer adds controlled overhead: decision recording, outcome archival,
493
+ and weight updates. Because these operations are write-heavy and per-assignment,
494
+ scalability depends primarily on Redis memory, write throughput, and feature
495
+ cardinality — not on learning math itself.
496
+
497
+ #### Redis Workload Breakdown
498
+
499
+ Each matched assignment now costs:
500
+ 1. **Decision record** (live): ~300 bytes for features + metadata; expires in 7 days (configurable).
501
+ 2. **Episode archive** (terminal): ~400 bytes; kept until feedback arrives, expires in 7 days.
502
+ 3. **Model updates**: One hash increment per feature per outcome (typically 5–15 features).
503
+ 4. **Stats tracking**: Shared atomic increments.
504
+
505
+ Matching a single assignment typically involves:
506
+ - 1–2 Redis reads (model + candidate details).
507
+ - 3–5 Redis writes per matched assignment (decision, model updates, stats).
508
+ - Pipelined to reduce round trips.
509
+
510
+ #### Memory Estimation
511
+
512
+ Assume:
513
+ - **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).
518
+
519
+ - **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.
525
+
526
+ - **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.
532
+
533
+ #### Configuration Guidelines
534
+
535
+ **Small (10–50 users, <10K assignments/day):**
536
+
537
+ ```typescript
538
+ const matcher = new AssignmentMatcher(redisClient, {
539
+ enableLearning: true,
540
+ learningShadowMode: true, // Observe first; no ranking impact
541
+ learningRate: 0.1,
542
+ learningExplorationRate: 0, // No exploration overhead
543
+ learningDecisionTtlMs: 604800000, // 7 days
544
+ learningFeedbackTtlMs: 604800000, // 7 days
545
+ });
546
+ // Safe: no performance issues. Monitor model size weekly.
547
+ ```
548
+
549
+ **Medium (50–500 users, 10K–100K assignments/day):**
550
+
551
+ ```typescript
552
+ const matcher = new AssignmentMatcher(redisClient, {
553
+ enableLearning: true,
554
+ 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)
559
+ learningFeedbackTtlMs: 259200000,
560
+ learningSignalWeights: { accuracy: 1, csat: 0.5, errorRate: -1 },
561
+ });
562
+ // Recommended: batch external feedback imports off-peak.
563
+ // Monitor: Redis memory growth, write latency, decision key count.
564
+ ```
565
+
566
+ **High-throughput (500+ users, 100K+ assignments/day):**
567
+
568
+ ```typescript
569
+ const matcher = new AssignmentMatcher(redisClient, {
570
+ enableLearning: true,
571
+ 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
578
+ // Consider sampling outcomes if traffic is extreme:
579
+ // Only learn from 10% of low-priority assignments.
580
+ });
581
+ // Monitoring critical: set up Redis memory alerts, track write amplification.
582
+ // Consider a separate Redis instance for RL state if main matcher instance is saturated.
583
+ ```
584
+
585
+ #### Safety Guardrails
586
+
587
+ 1. **Keep hard rules outside RL.** Eligibility, vetoes, backlog limits, and lifecycle state remain deterministic. RL only adjusts ranking of already-eligible candidates.
588
+ 2. **Start shadow mode.** Always enable `learningShadowMode: true` for the first week, then migrate to live mode with guardrails in place.
589
+ 3. **Cap exploration.** Set `learningExplorationRate ≤ 0.05` (5%). Exploration is important for learning but creates churn and can impact user experience.
590
+ 4. **Aggressive TTL.** Never leave decision records for more than 7 days. Episodes (feedback-waiting) should expire in 3–7 days depending on your feedback SLA.
591
+ 5. **Batch feedback imports.** Run external QA/accuracy signal imports as background jobs during low-traffic windows, not inline with matching.
592
+ 6. **Monitor key counts.** Use `redis-cli info keyspace` or equivalent to watch key cardinality. If decision keys grow unbounded, TTL is broken or Redis is out of memory.
593
+ 7. **Separate concerns.** If your matcher handles 1M+ assignments/day, use a dedicated Redis instance for RL state, separate from the main queue data.
594
+
595
+ #### Monitoring & Diagnostics
596
+
597
+ Key metrics to track:
598
+
599
+ - **Model size**: `(await matcher.getLearningModel()).length` — should be stable (5–50 features). If growing > 100, your feature extractor is leaking.
600
+ - **Decision cardinality**: `DBSIZE` and filter for `learning:decision:*` — should stay < 2× your `maxUserBacklogSize × numUsers`.
601
+ - **Learning stats**: `getLearningStats()` — watch `averageReward` drift and `decisions` growth rate. If `averageReward` is always zero or NaN, your reward signals are malformed.
602
+ - **Redis memory**: Keep below 70% of instance limit. Set memory alerts.
603
+ - **Write latency**: Track Redis command latencies (`latency latest`). Spikes indicate contention; consider sharding or a larger instance.
604
+ - **Model convergence**: Periodically log `getLearningModel()` weights and compare week-over-week. Sharp weight changes suggest concept drift or noisy rewards.
605
+
606
+ #### Recommended Production Workflow
607
+
608
+ 1. Deploy with `learningShadowMode: true` and `learningExplorationRate: 0` for 1–2 weeks.
609
+ 2. Validate that `getLearningStats()` shows growing reward without ranking instability.
610
+ 3. Switch to live mode with low `learningExplorationRate` (0.01–0.02).
611
+ 4. Set up external feedback pipeline (QA, CSAT, etc.) and test with a small sample.
612
+ 5. Gradually increase `boostFactor` and `explorationRate` based on business metrics (completion rate, SLA, re-open rate).
613
+ 6. Monitor weekly; roll back or reduce `boostFactor` if metrics degrade.
614
+
615
+ ### Learning Benchmark Simulation
616
+
617
+ Use the built-in simulation benchmark to compare baseline routing vs learning shadow mode vs live learning mode on the same deterministic workload.
618
+
619
+ Run with defaults:
620
+
621
+ ```bash
622
+ pnpm benchmark:learning
623
+ ```
624
+
625
+ Run with custom scale:
626
+
627
+ ```bash
628
+ pnpm benchmark:learning -- 300 8000 10 20260611
629
+ # arguments: <users> <assignmentsPerRound> <rounds> <seed>
630
+ ```
631
+
632
+ Output includes:
633
+
634
+ 1. Per-mode throughput and latency (`baseline`, `learning-shadow`, `learning-live`)
635
+ 2. Acceptance/completion/rejection/failure rates
636
+ 3. A normalized quality score for quick comparisons
637
+ 4. Top learned model weights
638
+ 5. Delta summary vs baseline (throughput, completion rate, quality)
639
+
640
+ ### Configuration Playbook (How To Choose)
641
+
642
+ Use this quick guide based on your primary goal.
643
+
644
+ #### Throughput-first (minimal latency impact)
645
+
646
+ ```typescript
647
+ 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,
657
+ });
658
+ ```
659
+
660
+ When to use:
661
+ 1. You have tight p95/p99 latency SLOs.
662
+ 2. Even a 2-5% throughput drop is expensive.
663
+
664
+ #### Balanced (recommended starting point)
665
+
666
+ ```typescript
667
+ 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,
677
+ });
678
+ ```
679
+
680
+ When to use:
681
+ 1. You want measurable quality lift with moderate performance cost.
682
+ 2. You can tolerate small throughput swings while tuning.
683
+
684
+ #### Quality-first (maximize learning impact)
685
+
686
+ ```typescript
687
+ 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,
697
+ });
698
+ ```
699
+
700
+ When to use:
701
+ 1. Completion/quality metrics matter more than raw throughput.
702
+ 2. You have enough headroom in Redis and CPU.
703
+
704
+ ### How To Tune It (Step by Step)
705
+
706
+ 1. Start with **shadow mode** and exploration off:
707
+
708
+ ```typescript
709
+ learningShadowMode: true,
710
+ learningExplorationRate: 0,
711
+ ```
712
+
713
+ 2. Run baseline benchmark and record metrics:
714
+
715
+ ```bash
716
+ pnpm benchmark:learning -- 100 1000 10 42
717
+ ```
718
+
719
+ 3. Move to live mode with conservative values:
720
+
721
+ ```typescript
722
+ learningShadowMode: false,
723
+ learningBoostFactor: 20,
724
+ learningExplorationRate: 0.005,
725
+ ```
726
+
727
+ 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.
731
+
732
+ 5. If throughput regresses too much:
733
+ - Reduce `learningBoostFactor`.
734
+ - Reduce `learningExplorationRate`.
735
+ - Reduce `relevantBatchSize`.
736
+ - Shorten `learningDecisionTtlMs` / `learningFeedbackTtlMs`.
737
+
738
+ 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`.
742
+
743
+ ### Reading Benchmark Deltas Quickly
744
+
745
+ Example:
746
+
747
+ ```text
748
+ Throughput delta: -5.11%
749
+ Completion rate delta: +4.80pp
750
+ Quality score delta: +0.0274
751
+ ```
752
+
753
+ Interpretation:
754
+ 1. You traded some speed (`-5.11%`) for better outcomes.
755
+ 2. Completion improved by **4.80 percentage points** (`pp`, not percent).
756
+ 3. Quality improved overall (`+0.0274`).
757
+
758
+ Choose the config where business utility is highest for your constraints.
759
+ If throughput is the hard constraint, keep throughput delta near zero and accept smaller quality gains.
760
+
244
761
  ## Detailed Example & Performance Insights
245
762
 
246
763
  The following example demonstrates adding multiple users and assignments and then measures the performance of the matching process.
@@ -408,6 +925,10 @@ The npm package only ships the compiled artifacts in `dist/`. Before publishing:
408
925
  2. Build the library: `pnpm run build`
409
926
  3. (Optional) Inspect the publish payload: `pnpm pack --dry-run`
410
927
 
928
+ For version bump + tag release flow (including patch releases), see `RELEASE.md`.
929
+ If you prefer a local helper, copy `scripts/release-patch-local.sh.example` to
930
+ `scripts/release-patch-local.sh` and run it.
931
+
411
932
  Consumers can `import AssignmentMatcher from 'assignment-user-matcher'` or `const { AssignmentMatcher } = require('assignment-user-matcher')` without running TypeScript themselves.
412
933
 
413
934
  ## License
package/dist/index.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import AssignmentMatcher from './matcher.class';
2
2
  export type { Assignment, options, Stats, User } from './matcher.class';
3
- export type { WorkflowDefinition, WorkflowInstance, WorkflowStep, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, } 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';
4
+ export { extractMatchFeatures, cosineSimilarity } from './learning/features';
4
5
  export { WorkflowBuilder, WorkflowStepBuilder, workflow, linearWorkflow, approvalWorkflow, } from './workflow-builder';
6
+ export { normalizeWorkflowDefinition, validateWorkflowDefinition } from './workflow-validation';
5
7
  export * from './utils/cidr';
6
8
  export { createKeyBuilders, type KeyBuilders, type RedisKeyConfig } from './utils/keys';
7
9
  export { 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,gBAAgB,EAChB,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,4BAA4B,GAC/B,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACH,eAAe,EACf,mBAAmB,EACnB,QAAQ,EACR,cAAc,EACd,gBAAgB,GACnB,MAAM,oBAAoB,CAAC;AAG5B,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,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"}
package/dist/index.js CHANGED
@@ -17,9 +17,13 @@ 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.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = void 0;
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;
21
21
  const matcher_class_1 = __importDefault(require("./matcher.class"));
22
22
  exports.AssignmentMatcher = matcher_class_1.default;
23
+ // Learning feature helpers (for custom feature extractors)
24
+ var features_1 = require("./learning/features");
25
+ Object.defineProperty(exports, "extractMatchFeatures", { enumerable: true, get: function () { return features_1.extractMatchFeatures; } });
26
+ Object.defineProperty(exports, "cosineSimilarity", { enumerable: true, get: function () { return features_1.cosineSimilarity; } });
23
27
  // Workflow builder DSL
24
28
  var workflow_builder_1 = require("./workflow-builder");
25
29
  Object.defineProperty(exports, "WorkflowBuilder", { enumerable: true, get: function () { return workflow_builder_1.WorkflowBuilder; } });
@@ -27,6 +31,9 @@ Object.defineProperty(exports, "WorkflowStepBuilder", { enumerable: true, get: f
27
31
  Object.defineProperty(exports, "workflow", { enumerable: true, get: function () { return workflow_builder_1.workflow; } });
28
32
  Object.defineProperty(exports, "linearWorkflow", { enumerable: true, get: function () { return workflow_builder_1.linearWorkflow; } });
29
33
  Object.defineProperty(exports, "approvalWorkflow", { enumerable: true, get: function () { return workflow_builder_1.approvalWorkflow; } });
34
+ var workflow_validation_1 = require("./workflow-validation");
35
+ Object.defineProperty(exports, "normalizeWorkflowDefinition", { enumerable: true, get: function () { return workflow_validation_1.normalizeWorkflowDefinition; } });
36
+ Object.defineProperty(exports, "validateWorkflowDefinition", { enumerable: true, get: function () { return workflow_validation_1.validateWorkflowDefinition; } });
30
37
  // Utility exports for advanced usage
31
38
  __exportStar(require("./utils/cidr"), exports);
32
39
  var keys_1 = require("./utils/keys");
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Default feature extraction for the learning (contextual bandit) layer.
3
+ *
4
+ * Produces a sparse feature vector describing how well a user matches an
5
+ * assignment. All features are normalized to roughly [0, 1] so learned
6
+ * weights stay comparable across feature families.
7
+ */
8
+ import type { User, LearningFeatures, LearningAssignmentContext } from '../types/matcher';
9
+ /**
10
+ * Cosine similarity between two numeric vectors.
11
+ * Returns 0 for mismatched lengths or zero-magnitude vectors.
12
+ */
13
+ export declare function cosineSimilarity(a: number[], b: number[]): number;
14
+ /**
15
+ * Default feature extractor: tag matches, normalized skill weights,
16
+ * tag-overlap ratio, and optional embedding similarity.
17
+ */
18
+ export declare function extractMatchFeatures(user: User, assignment: LearningAssignmentContext): LearningFeatures;
19
+ //# sourceMappingURL=features.d.ts.map
@@ -0,0 +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"}