assignment-user-matcher 1.7.0 → 1.9.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 (42) hide show
  1. package/README.md +230 -14
  2. package/dist/index.d.ts +3 -2
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +5 -1
  5. package/dist/learning/auto-weights.d.ts +18 -8
  6. package/dist/learning/auto-weights.d.ts.map +1 -1
  7. package/dist/learning/auto-weights.js +120 -18
  8. package/dist/learning/features.d.ts +2 -2
  9. package/dist/learning/features.d.ts.map +1 -1
  10. package/dist/learning/features.js +10 -2
  11. package/dist/managers/LearningManager.d.ts +7 -0
  12. package/dist/managers/LearningManager.d.ts.map +1 -1
  13. package/dist/managers/LearningManager.js +85 -11
  14. package/dist/managers/WorkflowManager.d.ts +2 -0
  15. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  16. package/dist/managers/WorkflowManager.js +3 -2
  17. package/dist/matcher.class.d.ts +121 -3
  18. package/dist/matcher.class.d.ts.map +1 -1
  19. package/dist/matcher.class.js +967 -16
  20. package/dist/queries/pagination.d.ts +5 -1
  21. package/dist/queries/pagination.d.ts.map +1 -1
  22. package/dist/queries/pagination.js +14 -3
  23. package/dist/schedule/policy.d.ts +35 -0
  24. package/dist/schedule/policy.d.ts.map +1 -0
  25. package/dist/schedule/policy.js +62 -0
  26. package/dist/scoring/match-score.d.ts +6 -0
  27. package/dist/scoring/match-score.d.ts.map +1 -1
  28. package/dist/scoring/match-score.js +15 -2
  29. package/dist/sla/policy.d.ts +49 -0
  30. package/dist/sla/policy.d.ts.map +1 -0
  31. package/dist/sla/policy.js +96 -0
  32. package/dist/tracing/decision-trace.d.ts.map +1 -1
  33. package/dist/tracing/decision-trace.js +4 -2
  34. package/dist/types/matcher.d.ts +422 -2
  35. package/dist/types/matcher.d.ts.map +1 -1
  36. package/dist/utils/keys.d.ts +10 -0
  37. package/dist/utils/keys.d.ts.map +1 -1
  38. package/dist/utils/keys.js +28 -0
  39. package/dist/validation/assignment-lint.d.ts +24 -0
  40. package/dist/validation/assignment-lint.d.ts.map +1 -0
  41. package/dist/validation/assignment-lint.js +132 -0
  42. package/package.json +2 -1
package/README.md CHANGED
@@ -385,22 +385,109 @@ The wait clock always survives an escalation: requeues go through `addAssignment
385
385
 
386
386
  Subscribe via `onAssignmentLifecycle` for `escalated` (`{ fromWorkerId, level, blockedPreviousOwner }`) and `escalationExhausted` (`{ level, parked }`) events; `expired` is still emitted first, so existing consumers are unaffected. Parked assignments are reachable with `getParkedAssignments()`, returned to the queue with `unparkAssignment(id, { resetEscalation? })`, and report `_status: 'parked'` from `getAssignment()` — they never read as "not found". `getEscalationLevel(id)` reports how far an assignment has climbed.
387
387
 
388
+ ### SLA policies (`Assignment.sla`)
389
+
390
+ Escalation owns the _response_ side (how long a matched user has to accept). `SlaPolicy` owns everything after that: how long the accepting user has to finish, how many times the work may be refused before it is pulled from rotation, and an absolute freshness cutoff after which the work is moot.
391
+
392
+ ```ts
393
+ await matcher.addAssignment({
394
+ id: 'order-42',
395
+ tags: ['fulfillment'],
396
+ sla: {
397
+ completeWithinMs: 30 * 60_000, // finish within 30 min of accepting
398
+ onCompletionBreach: 'requeue', // take it back if they don't
399
+ maxRejections: 3, // after 3 refusals, stop offering it
400
+ expireAfterMs: 24 * 3600_000, // moot after 24h no matter what
401
+ },
402
+ });
403
+
404
+ matcher.startMaintenance(); // SLA clocks are swept by the maintenance tick
405
+ ```
406
+
407
+ | Field | Meaning | Default |
408
+ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- |
409
+ | `completeWithinMs` | Completion deadline, measured from `acceptAssignment()`. Swept by `processCompletionDeadlines()` | none |
410
+ | `expireAfterMs` | Absolute freshness cutoff from **first enqueue** — survives requeues and applies in every state (queued, pending, accepted). Swept by `processSlaExpiries()` | none |
411
+ | `maxRejections` | Refusal budget. Explicit `rejectAssignment()` calls **and** blocking no-response expiries (`escalation.onNoResponse: 'block'`) count; idle/operator releases don't | none |
412
+ | `onCompletionBreach` | `'notify'` (event only, worker keeps it) / `'requeue'` (take back, block breacher) / `'fail'` / `'park'` | `'notify'` |
413
+ | `onMaxRejections` | `'park'` / `'fail'` / `'keep'` (keep offering; budget becomes measurement-only) | `'park'` |
414
+ | `onExpire` | `'drop'` (remove entirely) / `'park'` (retain for inspection) | `'drop'` |
415
+
416
+ Semantics worth knowing:
417
+
418
+ - **Fire-once.** A breached completion deadline is removed from the deadline index before the action runs, so a `'notify'` breach doesn't re-fire every tick; a requeued-after-breach assignment gets a fresh completion clock only on its next accept.
419
+ - **The TTL never extends.** Rejection ping-pong re-adds the same JSON, whose `_enqueuedAt` keeps the original first-enqueue time — the freshness cutoff is a hard wall, not a sliding window.
420
+ - **Rejection budget outranks escalation.** Once `maxRejections` is exhausted the assignment is parked/failed instead of climbing further tiers.
421
+ - **Sweep granularity.** Like response deadlines, SLA clocks fire on the maintenance tick, not at the exact deadline.
422
+ - **Unparking.** `unparkAssignment(id, { resetSla: true })` clears the first-enqueue clock and rejection counter; without it an unparked TTL-expired item simply expires again on the next sweep.
423
+
424
+ Lifecycle events: `completionBreached` (`{ workerId, action }`), `slaExpired` (`{ ownerId, action }`), `rejectionBudgetExhausted` (`{ rejections, action }`).
425
+
426
+ **SLO measurement.** `getSlaStats(tag?)` returns aggregate attainment counters — global, or for one tag: `offers`, `acceptedInTime`, `acceptanceBreaches`, `completionBreaches`, `ttlExpiries`, `rejectionParked`, plus `meanAcceptLatencyMs` (matched→accepted) and `meanCompleteLatencyMs` (accepted→completed). Counters are best-effort `HINCRBY`s piggybacking paths that already touch Redis; only SLA-bearing assignments are measured.
427
+
428
+ **Learning integration.** Breach outcomes flow into the contextual bandit as ordinary rewards (TTL expiry and completion breach → `expire`; completion breach with `'fail'` → `fail`), so per-user/per-tag stats and the automatic routing-weight vetoes pick up chronic breachers with no extra configuration. The default feature extractor also emits `sla:hasDeadline` and `sla:tightness` (normalized against `learningSlaTightnessReferenceMs`, default 1h) for assignments with a completion deadline, letting the model learn that tight-deadline work needs fast finishers. Custom feature extractors are unaffected.
429
+
430
+ ### Scheduled assignments (`Assignment.schedule`)
431
+
432
+ Escalation owns the response clock and `SlaPolicy` owns the post-accept contract; `SchedulePolicy` owns the **offer window**: when the work becomes visible to matching at all (`notBefore`), and how long an offer may go un-accepted before it is pulled (`notAfter`). Acceptance ends the schedule's authority — completion pressure is `sla.completeWithinMs`'s job.
433
+
434
+ ```ts
435
+ await matcher.addAssignment({
436
+ id: 'callback-42',
437
+ tags: ['callbacks'],
438
+ schedule: {
439
+ notBefore: Date.parse('2026-08-07T09:00:00Z'), // invisible to matching until 9:00
440
+ notAfter: Date.parse('2026-08-07T11:00:00Z'), // parked if nobody accepted by 11:00
441
+ onMiss: 'park', // or 'drop'
442
+ },
443
+ });
444
+
445
+ matcher.startMaintenance(); // schedule clocks are swept by the maintenance tick
446
+ ```
447
+
448
+ | Field | Meaning | Default |
449
+ | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
450
+ | `notBefore` | Epoch ms. Held in a dedicated scheduled store — no matching, no workflow targeting, no wait clock — until the scheduled sweep enqueues it | none |
451
+ | `notAfter` | Epoch ms. Absolute offer deadline; applies only while un-accepted (scheduled, queued, or pending). Valid without `notBefore`. Must be `> notBefore` when both are set | none |
452
+ | `onMiss` | `'park'` (retain for inspection) / `'drop'` (remove entirely) when `notAfter` elapses un-accepted | `'park'` |
453
+
454
+ Semantics worth knowing:
455
+
456
+ - **Clocks anchor at activation.** A held assignment has no wait clock and no SLA freshness stamp; both start when the sweep (or a forced early assign) enqueues it. `getQueueStats().oldestWaitingMs` never counts held work.
457
+ - **Acceptance kills the offer clock.** Once accepted, a passing `notAfter` is a non-event — late completion is governed by `sla.completeWithinMs` alone.
458
+ - **A miss beats activation.** When one sweep finds both timestamps in the past, the assignment parks/drops directly; it never transits the queue or emits `scheduleActivated`.
459
+ - **The offer deadline never extends.** `notAfter` is absolute, so rejection requeues carry the same deadline — a re-offered assignment can still miss.
460
+ - **Fire-once, replica-safe.** Sweep entries are claimed with a `ZREM` before acting, so concurrent replicas can run the sweep in parallel.
461
+ - **Sweep granularity.** Schedule clocks fire on the maintenance tick (`processScheduledAssignments()`), not at the exact millisecond.
462
+ - **Recurrence is out of scope.** Materialize each occurrence as its own assignment from your scheduler/shift tool; re-adding an existing id never resets its clocks, so materialization is idempotent.
463
+ - **Operator override.** `assignToUser(id, userId)` refuses held assignments; `{ force: true }` early-activates (clocks anchor there). If the user then rejects and `notBefore` is still in the future, the assignment returns to the scheduled store.
464
+ - **Unparking.** `unparkAssignment(id, { resetSchedule: true })` strips the schedule policy; without it a miss-parked assignment misses again on the next sweep.
465
+
466
+ Lifecycle events: `scheduleActivated` (`{ taskId, at }`) and `scheduleMissed` (`{ ownerId, state, action, assignment }` — the snapshot is the last surviving copy on the `'drop'` path).
467
+
468
+ **Introspection.** Held assignments are listed by `getScheduledAssignments()`, read as `_status: 'scheduled'` from `getAssignment()`, and counted separately in `getAssignmentCounts().scheduled` and `getQueueStats().scheduled` (excluded from `total` and pagination, like parked items). Misses bump the `scheduleMisses` counter in `getSlaStats(tag?)`.
469
+
470
+ **Learning integration.** Misses feed the contextual bandit as `expire` outcomes — a pending-state miss penalizes the user who sat on the offer, so automatic routing-weight vetoes pick up chronic missers with no extra configuration.
471
+
388
472
  ### `startMaintenance(options?)` / `stopMaintenance()` / `runMaintenanceOnce(options?)`
389
473
 
390
474
  Deadlines are not self-firing — something has to sweep them. `startMaintenance()` runs every enabled sweep on one tick:
391
475
 
476
+ - `scheduled` (default on) — schedule activations and offer-window misses (`schedule.notBefore` / `schedule.notAfter`). Runs first in the pass so a just-activated assignment's other clocks start from the same tick.
392
477
  - `responseDeadlines` (default on) — expiry, escalation, parking.
478
+ - `completionDeadlines` (default on) — SLA completion deadlines (`sla.completeWithinMs`).
479
+ - `slaExpiries` (default on) — SLA freshness TTLs (`sla.expireAfterMs`).
393
480
  - `workflowStepTimeouts` (default on when `enableWorkflows`) — the step-timeout index. **Note:** `startOrchestrator()` consumes the event stream but does not sweep step timeouts; without maintenance, `timeoutMs` on a workflow step never fires.
394
481
  - `idleUsers` (default on when `idleUserTimeoutMs` is set).
395
482
 
396
- `runMaintenanceOnce()` does one pass and returns a `MaintenanceReport` (`expiredMatches`, `escalations`, `parked`, `expiredSteps`, `releasedIdleUsers`, `tookMs`) — use it from a host that already owns a tick (a multi-tenant worker, a serverless schedule) instead of holding a timer per matcher. `startAutoReleaseInterval()` remains as a deprecated alias that sweeps response deadlines only.
483
+ `runMaintenanceOnce()` does one pass and returns a `MaintenanceReport` (`expiredMatches`, `escalations`, `parked`, `completionBreaches`, `slaExpiries`, `scheduleActivations`, `scheduleMisses`, `expiredSteps`, `releasedIdleUsers`, `tookMs`) — use it from a host that already owns a tick (a multi-tenant worker, a serverless schedule) instead of holding a timer per matcher. `startAutoReleaseInterval()` remains as a deprecated alias that sweeps response deadlines only.
397
484
 
398
485
  ### `getQueueStats(): Promise<QueueStats>`
399
486
 
400
487
  Live operational snapshot for dashboards:
401
488
 
402
- - `queued` / `pending`: assignment counts by state.
403
- - `oldestWaitingMs`: age of the longest-waiting unaccepted assignment, or `null`. The wait clock starts at first enqueue and survives reject/expiry requeues; it stops when a user accepts the assignment or it is removed.
489
+ - `queued` / `pending` / `scheduled`: assignment counts by state (`scheduled` = held by `schedule.notBefore`, not yet in the queue).
490
+ - `oldestWaitingMs`: age of the longest-waiting unaccepted assignment, or `null`. The wait clock starts at first enqueue and survives reject/expiry requeues; it stops when a user accepts the assignment or it is removed. Held (scheduled) assignments have no wait clock yet.
404
491
  - `perUser`: every user's `backlog` depth, effective `maxBacklogSize` cap, and `paused` state.
405
492
 
406
493
  ### `removeUser(userId: string): Promise<void>`
@@ -585,6 +672,10 @@ type Options = {
585
672
  // tag-overlap-ratio and embedding-similarity features.
586
673
  learningFeatureExtractor?: (user: User, assignment: { id: string; tags: string[] }) => Record<string, number>;
587
674
 
675
+ // Reference duration (ms) used to normalize the `sla:tightness` feature
676
+ // emitted by the default extractor for assignments with sla.completeWithinMs.
677
+ learningSlaTightnessReferenceMs?: number; // Default: 3600000 (1 hour)
678
+
588
679
  // TTL for stored decision contexts in ms.
589
680
  learningDecisionTtlMs?: number; // Default: 604800000 (7 days)
590
681
 
@@ -658,6 +749,11 @@ What a trace contains:
658
749
  `assignmentVeto` (the assignment's `vetoedUsers`), and `rejectedPreviously` —
659
750
  are struck out in the trace even though the Redis-side prefilter kept them
660
751
  out of the scoring pass entirely.
752
+ - Where a veto came from. For users carrying `learnedRoutingWeights`, each
753
+ `veto` reason also has `source: 'learned' | 'manual'`, separating a veto the
754
+ automatic routing-weight sync synthesized from one an operator configured.
755
+ The field is absent for users with no learned weights, so traces are
756
+ unchanged when the learning layer is off.
661
757
 
662
758
  Honesty notes: in the default `'first-come'` mode users evaluate and claim in
663
759
  parallel, so a candidate whose snapshot read happened after the winner's claim
@@ -704,6 +800,86 @@ const preview = await matcher.previewMatch(
704
800
  Use it for autosuggestion UIs: render the ranked best-fit workers with score
705
801
  breakdowns and blocked reasons before the operator commits the task.
706
802
 
803
+ ### Pre-flight checks (`lintAssignment` / `checkAssignmentReadiness`)
804
+
805
+ The runtime is deliberately forgiving — an invalid schedule window or an
806
+ unusable SLA object normalizes away silently, and an assignment whose tags no
807
+ user carries just sits queued. The pre-flight helpers surface those problems
808
+ _before_ `addAssignment()`:
809
+
810
+ ```typescript
811
+ import { lintAssignment } from 'assignment-user-matcher';
812
+
813
+ // Pure and Redis-free — run it host-side, in a form validator, anywhere:
814
+ const issues = lintAssignment(assignment, { matchExpirationMs: 60000 });
815
+ // [{ severity: 'error', code: 'schedule-window-inverted', message: '...' }, ...]
816
+
817
+ // Live version: same lint plus checks against the current user pool:
818
+ const report = await matcher.checkAssignmentReadiness(assignment);
819
+ // {
820
+ // issues, // lint + live findings, each { severity, code, message, tag? }
821
+ // eligibleUserCount, // who could take it right now (same rules as previewMatch)
822
+ // uncoveredTags, // tags no active (non-paused) user can serve
823
+ // evaluatedAt,
824
+ // }
825
+ ```
826
+
827
+ Static codes (from `lintAssignment`): `no-tags`, `schedule-window-inverted`,
828
+ `schedule-ignored`, `schedule-window-elapsed`, `schedule-notbefore-past`,
829
+ `offer-window-tight` (offer window shorter than one response deadline),
830
+ `schedule-notafter-shadowed-by-sla-ttl` (the freshness TTL fires first, so
831
+ `notAfter` never does), `sla-ignored`, `escalation-ignored`.
832
+
833
+ Live codes (from `checkAssignmentReadiness`): `duplicate-id` (re-adding keeps
834
+ the original wait/TTL clocks), `tag-uncovered` (per tag; paused users don't
835
+ count as coverage), `no-eligible-users`.
836
+
837
+ Tag coverage mirrors the matching semantics exactly: users with
838
+ `routingWeights` cover a tag when the effective weight is positive (wildcards
839
+ honored, weight `0` is a veto); users without them cover it via tag
840
+ membership. `checkAssignmentReadiness()` is read-only and safe to call from
841
+ dashboards or admission pipelines; it never claims or records anything.
842
+
843
+ ### Queue overlook (`auditQueue`)
844
+
845
+ When work sits in the queue and nobody knows why, `auditQueue()` answers both
846
+ of the usual questions at once — _who is blocked by what_ and _is anything
847
+ sweeping the clocks_:
848
+
849
+ ```typescript
850
+ const audit = await matcher.auditQueue({ minWaitingMs: 60_000 });
851
+ // {
852
+ // scanned, // queued assignments examined (longest-waiting first)
853
+ // entries: [{ // assignments nobody can take right now
854
+ // assignmentId, tags, waitingMs,
855
+ // eligibleUserCount, // 0 for stuck work
856
+ // uncoveredTags, // tags no active user can serve
857
+ // blockers, // reason -> blocked-user count, e.g.
858
+ // }], // { backlogFull: 3, paused: 1, rejectedPreviously: 1, noTagMatch: 4 }
859
+ // sweepBacklog: { // past-due entries sitting unswept in each deadline index
860
+ // scheduleActivations, scheduleMisses,
861
+ // responseDeadlines, completionDeadlines, slaExpiries,
862
+ // },
863
+ // }
864
+ ```
865
+
866
+ - **`blockers`** tallies the hard-rule reasons across ineligible users, using
867
+ the same `MatchTraceReason` kinds as decision traces (`paused`,
868
+ `backlogFull`, `rejectedPreviously`, `assignmentVeto`, `cidrMismatch`,
869
+ `skillThreshold`, `geoDistance`, …). Users excluded by plain tag/weight
870
+ mismatch are counted as `noTagMatch`.
871
+ - **`sweepBacklog`** counts deadline-index entries already in the past.
872
+ Values that stay nonzero across calls are the classic "assignments never
873
+ process" cause: no maintenance tick is running — start one with
874
+ `startMaintenance()` or call `runMaintenanceOnce()` from your own tick.
875
+ - Note that with `enableDefaultMatching` on (the default), tag-mismatched
876
+ work is still routable through the injected `default` tag, so stuckness
877
+ then comes from paused users, full backlogs, vetoes, and rejections rather
878
+ than tag gaps.
879
+ - Options: `limit` (default 100, longest-waiting first), `minWaitingMs`
880
+ (ignore fresh work), `includeHealthy` (also report matchable entries).
881
+ Read-only, O(scanned × users) — a diagnostic, not a hot path.
882
+
707
883
  ## Adaptive Matching with Reinforcement Learning
708
884
 
709
885
  The matcher includes an opt-in, Redis-backed contextual bandit that learns from
@@ -809,26 +985,53 @@ Beyond re-ranking, the learning layer can fully automate `routingWeights`
809
985
  authoring. With `enableAutoRoutingWeights: true` (requires `enableLearning`),
810
986
  every reward observation also updates per-user, per-tag statistics in Redis
811
987
  (atomic `HINCRBY`/`HINCRBYFLOAT` — O(tags) per outcome, no scans, no
812
- read-modify-write), and weights are synthesized on demand with a UCB1 bandit
813
- policy:
814
-
815
- - tags with a high mean reward get proportionally high weights (UCB
816
- exploration bonus favors less-sampled tags),
817
- - tags with a mean reward at/below `vetoThreshold` (after `minSamples`
818
- observations) get weight `0` — the matcher's hard-veto semantics,
819
- - under-sampled or unobserved known tags get an optimistic `priorWeight` so
820
- the system keeps exploring them.
988
+ read-modify-write), and weights are synthesized on demand with a configurable
989
+ bandit policy.
990
+
991
+ **Policies:**
992
+
993
+ - `policy: 'ucb1'` (default): high-mean tags get high weights, an exploration
994
+ bonus favors less-sampled tags, and bad tags are hard-vetoed at weight `0`.
995
+ - `policy: 'confidence'`: uses upper-confidence-bound for the weight and a
996
+ conservative lower-confidence-bound for the veto decision, so uncertainty
997
+ works against exclusion.
998
+ - `policy: 'thompson'`: samples from the per-tag posterior when mapping to a
999
+ weight.
1000
+
1001
+ **Guardrails (all opt-in):**
1002
+
1003
+ - `minSamplesForVeto`: a learned weight-0 may only override a _manual_
1004
+ (non-learned) weight after this many observations, preventing a few bad
1005
+ rolls from silently starving a user. Defaults to `minSamples` (5) for
1006
+ backward compatibility; 20 is a reasonable production floor.
1007
+ - `maxDeltaPerSync`: clamps how far any single learned weight can move per
1008
+ sync, avoiding oscillation.
1009
+ - `minTotalSamples`: skip users whose total evidence is still too thin.
1010
+ - `decayHalfLifeMs`: exponentially decay older observations on read so stale
1011
+ history cannot veto a user's improving skills.
1012
+ - `terminalOnlyTagStats`: when `true`, only terminal outcomes
1013
+ (complete/reject/expire/fail plus manual rewards/feedback) feed tag stats;
1014
+ the non-terminal `accept` update is skipped.
821
1015
 
822
1016
  ```typescript
823
1017
  const matcher = new AssignmentMatcher(redisClient, {
824
1018
  enableLearning: true,
825
1019
  enableAutoRoutingWeights: true,
1020
+ // Optional: run the guarded sync automatically on one replica.
1021
+ // A Redis lock prevents overlapping runs across replicas.
1022
+ autoRoutingWeightsSyncIntervalMs: 60_000,
826
1023
  autoRoutingWeights: {
827
1024
  minSamples: 5, // observations before a tag's stats are trusted
828
1025
  vetoThreshold: -0.5, // mean reward at/below this → weight 0 (hard veto)
829
1026
  maxWeight: 100, // top of the synthesized weight scale
830
1027
  explorationBonus: 0.5, // UCB coefficient; higher → more exploration
831
1028
  priorWeight: 50, // optimistic weight for unexplored tags
1029
+ policy: 'confidence', // or 'ucb1' (default) / 'thompson'
1030
+ confidenceZ: 1.5, // z-score for the confidence policy
1031
+ minSamplesForVeto: 20, // stricter bar for overriding manual weights
1032
+ maxDeltaPerSync: 25, // max change per sync on a single weight
1033
+ decayHalfLifeMs: 24 * 60 * 60 * 1000, // 24h half-life
1034
+ terminalOnlyTagStats: false,
832
1035
  },
833
1036
  });
834
1037
 
@@ -844,15 +1047,28 @@ await matcher.syncLearnedRoutingWeights(); // all tracked users
844
1047
 
845
1048
  // Include exploration priors for known tags the user has never seen:
846
1049
  await matcher.syncLearnedRoutingWeights('user-1', { includeUnexploredTags: true });
1050
+
1051
+ // Preview the would-be map without writing anything:
1052
+ const wouldBe = await matcher.syncLearnedRoutingWeights('user-1', { dryRun: true });
1053
+
1054
+ // Undo the last sync if the result looks wrong:
1055
+ await matcher.revertLearnedRoutingWeights('user-1');
847
1056
  ```
848
1057
 
849
1058
  Synthesis happens outside the matching hot path — matching itself reads the
850
1059
  user's stored `routingWeights` exactly as before, so the per-match cost is
851
1060
  unchanged. The last-applied learned map is stored on the user as
852
- `learnedRoutingWeights` for observability, and `resetLearningModel()` clears
853
- all per-user tag statistics. The pure synthesis function is exported as
1061
+ `learnedRoutingWeights` for observability, the previous map is snapshotted as
1062
+ `routingWeightsSnapshot` for rollback, and `resetLearningModel()` clears all
1063
+ per-user tag statistics. The pure synthesis function is exported as
854
1064
  `synthesizeRoutingWeights` for offline pipelines.
855
1065
 
1066
+ Run the regression gate to validate a new policy before shipping it:
1067
+
1068
+ ```bash
1069
+ ./node_modules/.bin/ts-node benchmark-weights.ts
1070
+ ```
1071
+
856
1072
  ### RL Scalability & Redis Constraints
857
1073
 
858
1074
  The RL layer adds controlled overhead: decision recording, outcome archival,
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import AssignmentMatcher from './matcher.class';
2
- export type { Assignment, MatcherOptions, options, Stats, QueueStats, UserLoadInfo, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, FairnessMode, FairnessConfig, MatchTraceReason, MatchCandidateTrace, MatchDecisionTrace, MatchDecisionMode, MatchExplanation, MatchPreview, MatchPreviewInput, DecisionTraceQuery, AssignmentLifecycleEvent, EscalationPolicy, EscalationSweepResult, MaintenanceOptions, MaintenanceReport, } from './matcher.class';
3
- export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowExternalTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, WorkflowInstanceQuery, WorkflowInstancePage, WorkflowTransition, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
2
+ export type { Assignment, MatcherOptions, options, Stats, QueueStats, UserLoadInfo, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, FairnessMode, FairnessConfig, MatchTraceReason, MatchCandidateTrace, MatchDecisionTrace, MatchDecisionMode, MatchExplanation, MatchPreview, MatchPreviewInput, DecisionTraceQuery, AssignmentLifecycleEvent, EscalationPolicy, EscalationSweepResult, CompletionDeadlineSweepResult, SlaExpirySweepResult, SlaPolicy, SlaStats, SchedulePolicy, ScheduleSweepResult, AssignmentLintIssue, AssignmentLintContext, AssignmentReadinessReport, QueueAuditOptions, QueueAuditEntry, QueueAuditReport, MaintenanceOptions, MaintenanceReport, } from './matcher.class';
3
+ export { lintAssignment, userCoversTag } from './validation/assignment-lint';
4
+ export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowExternalTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, WorkflowInstanceQuery, WorkflowInstancePage, WorkflowTransition, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions, AutoRoutingWeightsPolicy, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
4
5
  export { explainMatchScore, type MatchScoreExplanation } from './scoring/match-score';
5
6
  export { extractMatchFeatures, cosineSimilarity } from './learning/features';
6
7
  export { synthesizeRoutingWeights, DEFAULT_AUTO_WEIGHTS_OPTIONS } from './learning/auto-weights';
@@ -1 +1 @@
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,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,EACxB,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,EAClB,iBAAiB,GACpB,MAAM,iBAAiB,CAAC;AAGzB,YAAY,EACR,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,4BAA4B,EAC5B,qBAAqB,EACrB,oBAAoB,EACpB,kBAAkB,EAClB,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,iBAAiB,EAAE,KAAK,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAGtF,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"}
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,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,EACxB,gBAAgB,EAChB,qBAAqB,EACrB,6BAA6B,EAC7B,oBAAoB,EACpB,SAAS,EACT,QAAQ,EACR,cAAc,EACd,mBAAmB,EACnB,mBAAmB,EACnB,qBAAqB,EACrB,yBAAyB,EACzB,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,GACpB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAG7E,YAAY,EACR,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,4BAA4B,EAC5B,qBAAqB,EACrB,oBAAoB,EACpB,kBAAkB,EAClB,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,eAAe,EACf,yBAAyB,EACzB,wBAAwB,EACxB,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,GACnB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,iBAAiB,EAAE,KAAK,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAGtF,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,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.validateWorkflowDefinition = exports.normalizeWorkflowDefinition = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = exports.synthesizeRoutingWeights = exports.cosineSimilarity = exports.extractMatchFeatures = exports.explainMatchScore = 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 = exports.explainMatchScore = exports.userCoversTag = exports.lintAssignment = void 0;
21
21
  const matcher_class_1 = __importDefault(require("./matcher.class"));
22
22
  exports.AssignmentMatcher = matcher_class_1.default;
23
+ // Pre-flight lint (pure, Redis-free) — usable host-side before addAssignment
24
+ var assignment_lint_1 = require("./validation/assignment-lint");
25
+ Object.defineProperty(exports, "lintAssignment", { enumerable: true, get: function () { return assignment_lint_1.lintAssignment; } });
26
+ Object.defineProperty(exports, "userCoversTag", { enumerable: true, get: function () { return assignment_lint_1.userCoversTag; } });
23
27
  // Decision-trace scoring explainer (same numbers as calculateMatchScore, plus reasons)
24
28
  var match_score_1 = require("./scoring/match-score");
25
29
  Object.defineProperty(exports, "explainMatchScore", { enumerable: true, get: function () { return match_score_1.explainMatchScore; } });
@@ -1,26 +1,36 @@
1
1
  /**
2
2
  * Automatic routing-weight synthesis from per-user tag reward statistics.
3
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:
4
+ * Supports three policies:
7
5
  *
8
- * - tags with enough samples and a mean reward at/below `vetoThreshold` get
9
- * weight 0 (the matcher's hard-veto semantics),
6
+ * - 'ucb1' (default): mean reward plus an exploration bonus that shrinks as
7
+ * the tag is sampled more.
8
+ * - 'confidence': upper-confidence-bound for the weight, lower-confidence-bound
9
+ * for the veto decision, so vetoes are conservative and weights reflect
10
+ * uncertainty.
11
+ * - 'thompson': sample from the per-tag posterior (Gaussian approximation)
12
+ * when mapping to a weight.
13
+ *
14
+ * Scores map onto the conventional 0-100 routing-weight scale:
15
+ *
16
+ * - tags with enough samples and a sufficiently bad mean/LCB get weight 0
17
+ * (the matcher's hard-veto semantics),
10
18
  * - under-sampled or unobserved known tags get an optimistic `priorWeight`
11
19
  * so the matcher keeps exploring them,
12
- * - all other tags get a weight proportional to their UCB score, clamped to
20
+ * - all other tags get a weight proportional to their score, clamped to
13
21
  * [1, maxWeight] so eligible tags never collapse to an accidental veto.
14
22
  *
15
23
  * Pure module: no Redis access, O(number of tags) per call.
16
24
  */
17
25
  import type { AutoRoutingWeightsOptions, LearningTagStat } from '../types/matcher';
18
- export declare const DEFAULT_AUTO_WEIGHTS_OPTIONS: Required<Omit<AutoRoutingWeightsOptions, 'priorWeight'>>;
26
+ export declare const DEFAULT_AUTO_WEIGHTS_OPTIONS: Required<Omit<AutoRoutingWeightsOptions, 'priorWeight' | 'maxDeltaPerSync' | 'decayHalfLifeMs' | 'rng'>> & {
27
+ priorWeight: number;
28
+ };
19
29
  /**
20
30
  * Synthesize a routingWeights map from per-tag reward statistics.
21
31
  *
22
32
  * @param stats per-user tag reward statistics (from learned outcomes)
23
- * @param options UCB policy tuning (merged with defaults)
33
+ * @param options synthesis policy and tuning (merged with defaults)
24
34
  * @param knownTags optional tags to include even without observations;
25
35
  * unobserved known tags receive the optimistic prior weight
26
36
  * @param existingWeights optional current routingWeights of the user;
@@ -1 +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"}
1
+ {"version":3,"file":"auto-weights.d.ts","sourceRoot":"","sources":["../../src/learning/auto-weights.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,KAAK,EAAE,yBAAyB,EAA4B,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAE7G,eAAO,MAAM,4BAA4B,EAAE,QAAQ,CAC/C,IAAI,CAAC,yBAAyB,EAAE,aAAa,GAAG,iBAAiB,GAAG,iBAAiB,GAAG,KAAK,CAAC,CACjG,GAAG;IACA,WAAW,EAAE,MAAM,CAAC;CAYvB,CAAC;AA2IF;;;;;;;;;;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"}
@@ -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;