assignment-user-matcher 1.2.3 → 1.3.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.
- package/LICENCE +21 -53
- package/README.md +184 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/managers/DecisionTraceManager.d.ts +34 -0
- package/dist/managers/DecisionTraceManager.d.ts.map +1 -0
- package/dist/managers/DecisionTraceManager.js +74 -0
- package/dist/managers/WorkflowManager.d.ts +6 -0
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +10 -0
- package/dist/matcher.class.d.ts +216 -2
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +1056 -77
- package/dist/scoring/fair-arbitration.d.ts +68 -0
- package/dist/scoring/fair-arbitration.d.ts.map +1 -0
- package/dist/scoring/fair-arbitration.js +151 -0
- package/dist/scoring/match-score.d.ts +17 -1
- package/dist/scoring/match-score.d.ts.map +1 -1
- package/dist/scoring/match-score.js +81 -1
- package/dist/tracing/decision-trace.d.ts +48 -0
- package/dist/tracing/decision-trace.d.ts.map +1 -0
- package/dist/tracing/decision-trace.js +152 -0
- package/dist/types/matcher.d.ts +324 -0
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +6 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +10 -0
- package/package.json +58 -57
package/LICENCE
CHANGED
|
@@ -1,53 +1,21 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
- any other equitable or legal relief available, including injunctive and declaratory relief.
|
|
23
|
-
- The remedies in this Section are cumulative, not exclusive, and shall not limit other remedies at law or in equity. Owner need not post a bond to obtain injunctive relief.
|
|
24
|
-
|
|
25
|
-
5. Indemnity
|
|
26
|
-
- Recipient shall indemnify, defend, and hold Owner harmless from and against any and all claims, liabilities, losses, damages, costs and expenses (including reasonable attorneys' fees) arising from any unauthorized Use, Modification, distribution, or other breach of this License.
|
|
27
|
-
|
|
28
|
-
6. Termination and Return
|
|
29
|
-
- Owner may terminate this License immediately upon written notice if Recipient commits any breach, including any Infringing Act. Upon termination, Recipient shall immediately cease all Use of the Software and destroy or return all copies of the Software and related materials and certify such destruction or return in writing to Owner.
|
|
30
|
-
|
|
31
|
-
7. Preservation of Notices
|
|
32
|
-
- Recipient shall not remove, alter, or obscure any copyright, trademark, patent, or other proprietary notices, legends, or labels contained in or on the Software.
|
|
33
|
-
|
|
34
|
-
8. Warranty Disclaimer
|
|
35
|
-
- THE SOFTWARE IS PROVIDED "AS IS" AND OWNER DISCLAIMS ALL WARRANTIES, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NONINFRINGEMENT. THIS DISCLAIMER DOES NOT AFFECT OWNER'S RIGHT TO SEEK EQUITABLE RELIEF OR DAMAGES FOR UNAUTHORIZED USE.
|
|
36
|
-
|
|
37
|
-
9. Limitation of Liability
|
|
38
|
-
- EXCEPT FOR OWNER'S RIGHTS AND REMEDIES FOR UNAUTHORIZED USE (WHICH ARE PRESERVED), IN NO EVENT SHALL OWNER BE LIABLE TO RECIPIENT FOR ANY INDIRECT, INCIDENTAL, CONSEQUENTIAL, SPECIAL, PUNITIVE, OR EXEMPLARY DAMAGES ARISING OUT OF OR RELATED TO THIS LICENSE OR THE SOFTWARE, WHETHER IN CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY, OR OTHERWISE.
|
|
39
|
-
|
|
40
|
-
10. Governing Law and Venue
|
|
41
|
-
- This License shall be governed by and construed in accordance with the laws of [INSERT STATE/PROVINCE/COUNTRY], without regard to its conflicts of laws rules. The exclusive venue and jurisdiction for any dispute arising out of or related to this License shall be the state and federal courts located in [INSERT CITY, STATE/PROVINCE/COUNTRY]. Recipient consents to personal jurisdiction in those courts.
|
|
42
|
-
|
|
43
|
-
11. Severability; Waiver; Entire Agreement
|
|
44
|
-
- If any provision of this License is held to be invalid or unenforceable, the remainder of this License shall remain in full force and effect. No waiver by Owner of any breach shall be deemed a waiver of any other or subsequent breach. This License constitutes the entire agreement between the parties regarding the subject matter hereof.
|
|
45
|
-
|
|
46
|
-
12. Effective Date 21/05/2025 or since intiial commit of this repository
|
|
47
|
-
- Effective Date: the date Recipient first receives, accesses, or uses the Software.
|
|
48
|
-
- Owner: Viljar Võidula
|
|
49
|
-
- Contact: viljar@forgemaster.ai
|
|
50
|
-
|
|
51
|
-
Footnote — Non-Commercial Fair Use
|
|
52
|
-
- As a limited exception to Sections 2 and 3, non-commercial fair use (e.g., academic evaluation, internal demonstrations, code review excerpts) is permitted provided that, prior to any such use, Recipient contacts the Owner at viljar@forgemaster.ai and receives written confirmation authorizing the specific use.
|
|
53
|
-
- Any such authorization is non-exclusive, non-transferable, revocable at any time, and may be conditioned on additional terms. All other provisions of this License remain in full force and effect unless explicitly modified in the written confirmation.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 Viljar Võidula
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -75,6 +75,10 @@ await assignmentMatcher.addUser({
|
|
|
75
75
|
Note: `usingDefaultMatchScore` is an internal implementation detail and is **not** a public option.
|
|
76
76
|
Configure hard veto behavior only through `routingWeights` values.
|
|
77
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).
|
|
81
|
+
|
|
78
82
|
3. **Prioritization Engine:**
|
|
79
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.
|
|
80
84
|
|
|
@@ -269,6 +273,7 @@ Adds or updates a user in the system.
|
|
|
269
273
|
- `user`: An object representing the user.
|
|
270
274
|
- `id: string`: Unique identifier for the user.
|
|
271
275
|
- `tags: string[]`: Array of tags associated with the user.
|
|
276
|
+
- `maxBacklogSize?: number`: Optional per-user backlog cap overriding the matcher-wide `maxUserBacklogSize` in every matching path (`0` = receive nothing; negative or non-numeric values are ignored). The fairness rolling-window auto-cap derivation stays team-level and keeps using the global value.
|
|
272
277
|
|
|
273
278
|
### `addAssignment(assignment: Assignment): Promise<void>`
|
|
274
279
|
|
|
@@ -279,10 +284,11 @@ Adds a new assignment to be matched.
|
|
|
279
284
|
- `tags: string[]`: Array of tags required for the assignment.
|
|
280
285
|
- `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`.
|
|
281
286
|
- `priority?: number | string`: Optional explicit priority. If `prioritizationFunction` is used, this might be an input to it.
|
|
287
|
+
- `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.
|
|
282
288
|
|
|
283
289
|
### `matchUsersAssignments(): Promise<void>`
|
|
284
290
|
|
|
285
|
-
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.
|
|
291
|
+
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'`).
|
|
286
292
|
|
|
287
293
|
### `getCurrentAssignmentsForUser(userId: string): Promise<Assignment[]>`
|
|
288
294
|
|
|
@@ -300,6 +306,26 @@ Retrieves current pending assignments, including who owns each assignment and ho
|
|
|
300
306
|
- `pendingSince`: Unix timestamp (ms) when the assignment entered pending state.
|
|
301
307
|
- `expiresAt`: Unix timestamp (ms) when pending expiration is scheduled.
|
|
302
308
|
|
|
309
|
+
### `pauseUser(userId: string): Promise<boolean>` / `resumeUser(userId: string): Promise<boolean>`
|
|
310
|
+
|
|
311
|
+
Operator availability controls. A paused user stops receiving new assignments in every matching path but keeps their pending backlog and can still accept, complete, or reject work they already hold. Paused users are exempt from idle auto-removal (`idleUserTimeoutMs`) — pausing is deliberate absence, not idleness. `pauseUser` returns `false` when the user is not in the pool; `resumeUser` returns `false` when the user was not paused, and records activity (resets the idle clock) when it succeeds. Inspect state with `isUserPaused(userId)` and `getPausedUsers()`.
|
|
312
|
+
|
|
313
|
+
When decision traces are enabled, paused users appear struck out in traces with a `paused` reason, and `explainMatch()` reports them as ineligible.
|
|
314
|
+
|
|
315
|
+
### `assignToUser(assignmentId: string, userId: string, options?: { force?: boolean }): Promise<{ previousOwnerId: string | null }>`
|
|
316
|
+
|
|
317
|
+
Operator override: hand an assignment directly to a user, bypassing tag/weight selection. Works on queued assignments and on pending assignments held by another user (the previous owner's backlog slot is released and the expiry clock restarts). Idempotent when the user already owns the assignment.
|
|
318
|
+
|
|
319
|
+
Hard rules still apply unless `force: true`: the user must not be paused, must have backlog headroom, must not be vetoed on the assignment, and must not have previously rejected it. The learning layer is never fed by manual assignments. When tracing is active the override is recorded as a decision trace with mode `'manual'`, so supervisor actions land in the same audit trail as organic matches.
|
|
320
|
+
|
|
321
|
+
### `getQueueStats(): Promise<QueueStats>`
|
|
322
|
+
|
|
323
|
+
Live operational snapshot for dashboards:
|
|
324
|
+
|
|
325
|
+
- `queued` / `pending`: assignment counts by state.
|
|
326
|
+
- `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.
|
|
327
|
+
- `perUser`: every user's `backlog` depth, effective `maxBacklogSize` cap, and `paused` state.
|
|
328
|
+
|
|
303
329
|
### `removeUser(userId: string): Promise<void>`
|
|
304
330
|
|
|
305
331
|
Removes a user from the system and clears their assignment backlog.
|
|
@@ -360,6 +386,54 @@ type Options = {
|
|
|
360
386
|
// the check periodically. Disabled when undefined (default).
|
|
361
387
|
idleUserTimeoutMs?: number; // Default: undefined (disabled)
|
|
362
388
|
|
|
389
|
+
// Who wins when several users are eligible for the same assignment
|
|
390
|
+
// during bulk matching (matchUsersAssignments() with no userId)?
|
|
391
|
+
// 'first-come' - whoever's claim reaches Redis first (fastest; the
|
|
392
|
+
// winner is arbitrary). This is the default.
|
|
393
|
+
// 'best-match' - the highest-scoring eligible user, deterministically.
|
|
394
|
+
// 'balanced' - best match wins, but near-ties (within ~5% of the
|
|
395
|
+
// typical candidate score) go to whoever has less work.
|
|
396
|
+
// 'spread-work' - work is spread as evenly as skills allow: every
|
|
397
|
+
// assignment already on someone's plate discounts their
|
|
398
|
+
// next bid by half the typical candidate score, so
|
|
399
|
+
// finishing work fast never just means drowning in more.
|
|
400
|
+
// The numbers behind 'balanced' / 'spread-work' are derived automatically
|
|
401
|
+
// from each matching pass's candidate scores - nothing to calibrate. Both
|
|
402
|
+
// also include an hourly guardrail by default: nobody receives at more
|
|
403
|
+
// than double the team's average grant rate (see fairnessMaxPerWindow).
|
|
404
|
+
// Switchable at runtime via `setFairness(mode)` / `getFairness()`, or
|
|
405
|
+
// retune every fairness knob below at once with
|
|
406
|
+
// `setFairnessConfig(partial)` / `getFairnessConfig()` - changes apply on
|
|
407
|
+
// the next `matchUsersAssignments()` call, no reconstruction needed.
|
|
408
|
+
fairness?: 'first-come' | 'best-match' | 'balanced' | 'spread-work'; // Default: 'first-come'
|
|
409
|
+
|
|
410
|
+
// Hard ceiling on how many assignments one user can be *granted* within a
|
|
411
|
+
// rolling time window, in any fairness mode other than 'first-come'. The
|
|
412
|
+
// backlog cap alone can't protect diligent users: fast workers keep
|
|
413
|
+
// freeing backlog slots and keep winning, so speed is rewarded with ever
|
|
414
|
+
// more work. This counts grants regardless of how quickly they were
|
|
415
|
+
// cleared; at the cap, contested work spills to the next-best eligible
|
|
416
|
+
// user (or stays queued) until the window rolls. Workflow-targeted
|
|
417
|
+
// assignments are direct handoffs and bypass the cap.
|
|
418
|
+
// Left undefined, the 'balanced' / 'spread-work' presets default it to a
|
|
419
|
+
// team-relative guardrail - max(maxUserBacklogSize, 2x the team's average
|
|
420
|
+
// grants in the window), recomputed each pass, so it adapts to any
|
|
421
|
+
// deployment's volume. Set a number to pin the ceiling, or Infinity to
|
|
422
|
+
// disable the window cap entirely.
|
|
423
|
+
fairnessMaxPerWindow?: number; // Default: auto for 'balanced'/'spread-work', else disabled
|
|
424
|
+
fairnessWindowMs?: number; // Default: 3600000 (one hour)
|
|
425
|
+
|
|
426
|
+
// Expert alternative to `fairness` - the raw switches behind it:
|
|
427
|
+
// enableFairTiebreaker is exactly `fairness: 'best-match'` when true;
|
|
428
|
+
// fairnessLoadPenalty is an absolute score discount per assignment
|
|
429
|
+
// already on a user's backlog, and fairnessTieBand treats scores in the
|
|
430
|
+
// same band-sized bucket as tied (less-loaded user wins). Explicit values
|
|
431
|
+
// here override what a `fairness` preset would derive. Runtime toggles:
|
|
432
|
+
// `setFairTiebreaker(enabled)` / `isFairTiebreakerEnabled()`.
|
|
433
|
+
enableFairTiebreaker?: boolean; // Default: false
|
|
434
|
+
fairnessLoadPenalty?: number; // Default: 0 (off)
|
|
435
|
+
fairnessTieBand?: number; // Default: 0 (off)
|
|
436
|
+
|
|
363
437
|
// A custom function to determine the priority of an assignment.
|
|
364
438
|
// The function receives assignment objects (or undefined if fewer than 3 are available for comparison)
|
|
365
439
|
// and should return a numerical priority score. Higher scores mean higher priority.
|
|
@@ -384,6 +458,27 @@ type Options = {
|
|
|
384
458
|
assignmentId?: string,
|
|
385
459
|
) => Promise<[number, number]>;
|
|
386
460
|
|
|
461
|
+
// ========== Decision Traces & Explainability ==========
|
|
462
|
+
|
|
463
|
+
// Persist an auditable decision trace for every routing decision. Each
|
|
464
|
+
// matched assignment gets a MatchDecisionTrace — winner, arbitration mode,
|
|
465
|
+
// and every evaluated candidate with score breakdown and exclusion
|
|
466
|
+
// reasons — appended to a capped Redis stream and queryable via
|
|
467
|
+
// getDecisionTraces(). Captured while the decision happens, never
|
|
468
|
+
// reconstructed. Toggleable at runtime via setDecisionTraces(enabled).
|
|
469
|
+
enableDecisionTraces?: boolean; // Default: false
|
|
470
|
+
|
|
471
|
+
// Retention (entry count) for the trace stream, and how many candidates
|
|
472
|
+
// are stored per trace (the chosen candidate is always kept).
|
|
473
|
+
decisionTraceMaxEntries?: number; // Default: 1000
|
|
474
|
+
decisionTraceMaxCandidates?: number; // Default: 25
|
|
475
|
+
|
|
476
|
+
// Real-time hook invoked with each MatchDecisionTrace as decisions are
|
|
477
|
+
// made (e.g. push to a websocket). Setting it activates capture even when
|
|
478
|
+
// enableDecisionTraces is false — traces then stream to the callback only
|
|
479
|
+
// and are not persisted. Callback errors never affect matching.
|
|
480
|
+
onMatchDecision?: (trace: MatchDecisionTrace) => void;
|
|
481
|
+
|
|
387
482
|
// ========== Reinforcement Learning Options ==========
|
|
388
483
|
|
|
389
484
|
// Enable the adaptive learning layer (contextual bandit re-ranking).
|
|
@@ -426,6 +521,93 @@ type Options = {
|
|
|
426
521
|
};
|
|
427
522
|
```
|
|
428
523
|
|
|
524
|
+
## Decision Traces & Explainability
|
|
525
|
+
|
|
526
|
+
Every routing decision the engine makes can be explained and audited. Two
|
|
527
|
+
complementary tools cover the two questions teams actually ask:
|
|
528
|
+
|
|
529
|
+
- **"Why did this assignment go to that user?"** — decision traces, the
|
|
530
|
+
auditable record captured _while the decision was made_.
|
|
531
|
+
- **"Who could receive this assignment right now, and why (not)?"** —
|
|
532
|
+
`explainMatch()`, an on-demand evaluation against live state.
|
|
533
|
+
|
|
534
|
+
### Decision traces (`enableDecisionTraces`)
|
|
535
|
+
|
|
536
|
+
```typescript
|
|
537
|
+
const matcher = new AssignmentMatcher(redisClient, {
|
|
538
|
+
enableDecisionTraces: true,
|
|
539
|
+
// Optional real-time feed (dashboards, sockets). Works even without
|
|
540
|
+
// persistence: setting only onMatchDecision streams traces to the
|
|
541
|
+
// callback and skips storage.
|
|
542
|
+
onMatchDecision: (trace) => io.emit('match:decision', trace),
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
await matcher.matchUsersAssignments();
|
|
546
|
+
|
|
547
|
+
const [trace] = await matcher.getDecisionTraces({ assignmentId: 'ticket-42' });
|
|
548
|
+
// {
|
|
549
|
+
// assignmentId: 'ticket-42',
|
|
550
|
+
// chosenUserId: 'alice',
|
|
551
|
+
// mode: 'best-match', // how the winner was arbitrated
|
|
552
|
+
// matchedAt: 1752404712345,
|
|
553
|
+
// candidates: [
|
|
554
|
+
// { userId: 'alice', eligible: true, chosen: true, score: 101,
|
|
555
|
+
// effectivePriority: 201, reasons: [ { kind: 'tagWeight', tag: 'english', weight: 100 }, ... ] },
|
|
556
|
+
// { userId: 'bob', eligible: false, chosen: false, score: 0,
|
|
557
|
+
// effectivePriority: 0, reasons: [ { kind: 'veto', tag: 'german', pattern: 'german' } ] },
|
|
558
|
+
// ],
|
|
559
|
+
// }
|
|
560
|
+
```
|
|
561
|
+
|
|
562
|
+
Traces are appended to a capped Redis stream (`decisionTraceMaxEntries`,
|
|
563
|
+
default 1000), so the audit record survives restarts and is shared across
|
|
564
|
+
replicas. Query with `getDecisionTraces({ assignmentId?, userId?, limit? })`
|
|
565
|
+
(newest first), wipe with `clearDecisionTraces()`, and toggle at runtime with
|
|
566
|
+
`setDecisionTraces(enabled)` / `isDecisionTracesEnabled()`.
|
|
567
|
+
|
|
568
|
+
What a trace contains:
|
|
569
|
+
|
|
570
|
+
- The winner, the arbitration mode (`'first-come'`, `'best-match'`,
|
|
571
|
+
`'balanced'`, `'spread-work'`, `'direct'` for per-user matching, or
|
|
572
|
+
`'workflow'` for deterministic workflow-targeted handoffs), and the moment
|
|
573
|
+
of the decision.
|
|
574
|
+
- Every candidate evaluated in that matching pass with its full score
|
|
575
|
+
breakdown: matched routing weights (`tagWeight`, wildcard `pattern`
|
|
576
|
+
included), the implicit `defaultTag`, `tagOverlap` for unweighted users,
|
|
577
|
+
`geoDistance`/`geoBoost`, `learningBoost` (with `shadowMode` flag),
|
|
578
|
+
`skillThreshold` failures, `cidrMismatch`, and `customScore` when a custom
|
|
579
|
+
`matchingFunction` owns scoring.
|
|
580
|
+
- Users excluded before scoring by hard rules — zero-weight `veto` entries,
|
|
581
|
+
`assignmentVeto` (the assignment's `vetoedUsers`), and `rejectedPreviously` —
|
|
582
|
+
are struck out in the trace even though the Redis-side prefilter kept them
|
|
583
|
+
out of the scoring pass entirely.
|
|
584
|
+
|
|
585
|
+
Honesty notes: in the default `'first-come'` mode users evaluate and claim in
|
|
586
|
+
parallel, so a candidate whose snapshot read happened after the winner's claim
|
|
587
|
+
may be absent from the trace (they never evaluated it); fair modes evaluate
|
|
588
|
+
everyone read-only first and always capture the full candidate field. Reason
|
|
589
|
+
kinds are additive over time — treat unknown `kind` values as forward
|
|
590
|
+
compatibility, not errors.
|
|
591
|
+
|
|
592
|
+
### On-demand explanations (`explainMatch`)
|
|
593
|
+
|
|
594
|
+
```typescript
|
|
595
|
+
const explanation = await matcher.explainMatch('ticket-42');
|
|
596
|
+
// { assignmentId, status: 'queued' | 'pending' | 'accepted' | 'completed' | 'not_found',
|
|
597
|
+
// ownerId, evaluatedAt, candidates: MatchCandidateTrace[] }
|
|
598
|
+
|
|
599
|
+
// Or scope to specific users:
|
|
600
|
+
await matcher.explainMatch('ticket-42', { userIds: ['alice', 'bob'] });
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
`explainMatch()` recomputes eligibility for every user (or the given ids)
|
|
604
|
+
against the assignment's current state using the engine's own scoring
|
|
605
|
+
internals — vetoes, prior rejections, backlog, thresholds, CIDR, geo, weight
|
|
606
|
+
breakdown, learning influence — and works in any lifecycle state (for matched
|
|
607
|
+
assignments the current owner is flagged `chosen`). Because it evaluates _now_
|
|
608
|
+
rather than at decision time, use it for support tooling and dry-runs
|
|
609
|
+
("who would get this?"), and decision traces for the compliance-grade record.
|
|
610
|
+
|
|
429
611
|
## Adaptive Matching with Reinforcement Learning
|
|
430
612
|
|
|
431
613
|
The matcher includes an opt-in, Redis-backed contextual bandit that learns from
|
|
@@ -1032,4 +1214,4 @@ Consumers can `import AssignmentMatcher from 'assignment-user-matcher'` or `cons
|
|
|
1032
1214
|
|
|
1033
1215
|
## License
|
|
1034
1216
|
|
|
1035
|
-
|
|
1217
|
+
[MIT](./LICENCE) — free for commercial and non-commercial use.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import AssignmentMatcher from './matcher.class';
|
|
2
|
-
export type { Assignment, MatcherOptions, options, Stats, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, } from './matcher.class';
|
|
2
|
+
export type { Assignment, MatcherOptions, options, Stats, QueueStats, UserLoadInfo, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, FairnessMode, FairnessConfig, MatchTraceReason, MatchCandidateTrace, MatchDecisionTrace, MatchDecisionMode, MatchExplanation, DecisionTraceQuery, } from './matcher.class';
|
|
3
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
|
+
export { explainMatchScore, type MatchScoreExplanation } from './scoring/match-score';
|
|
4
5
|
export { extractMatchFeatures, cosineSimilarity } from './learning/features';
|
|
5
6
|
export { synthesizeRoutingWeights, DEFAULT_AUTO_WEIGHTS_OPTIONS } from './learning/auto-weights';
|
|
6
7
|
export { WorkflowBuilder, WorkflowStepBuilder, workflow, linearWorkflow, approvalWorkflow } from './workflow-builder';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,
|
|
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,kBAAkB,GACrB,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,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,12 @@ 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 = 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 = void 0;
|
|
21
21
|
const matcher_class_1 = __importDefault(require("./matcher.class"));
|
|
22
22
|
exports.AssignmentMatcher = matcher_class_1.default;
|
|
23
|
+
// Decision-trace scoring explainer (same numbers as calculateMatchScore, plus reasons)
|
|
24
|
+
var match_score_1 = require("./scoring/match-score");
|
|
25
|
+
Object.defineProperty(exports, "explainMatchScore", { enumerable: true, get: function () { return match_score_1.explainMatchScore; } });
|
|
23
26
|
// Learning feature helpers (for custom feature extractors)
|
|
24
27
|
var features_1 = require("./learning/features");
|
|
25
28
|
Object.defineProperty(exports, "extractMatchFeatures", { enumerable: true, get: function () { return features_1.extractMatchFeatures; } });
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decision trace persistence and querying.
|
|
3
|
+
*
|
|
4
|
+
* Traces are appended to a capped Redis stream (keys.decisionTraces()) so the
|
|
5
|
+
* audit record survives process restarts and is shared across replicas.
|
|
6
|
+
* Assembly of the traces themselves is pure and lives in
|
|
7
|
+
* src/tracing/decision-trace.ts; this manager only handles I/O and the
|
|
8
|
+
* real-time onDecision hook.
|
|
9
|
+
*/
|
|
10
|
+
import type { DecisionTraceQuery, MatchDecisionTrace, RedisClientType } from '../types/matcher';
|
|
11
|
+
import type { KeyBuilders } from '../utils/keys';
|
|
12
|
+
export interface DecisionTraceManagerOptions {
|
|
13
|
+
/** Maximum entries retained in the trace stream */
|
|
14
|
+
maxEntries: number;
|
|
15
|
+
/** Real-time hook invoked per recorded trace; errors are swallowed */
|
|
16
|
+
onDecision?: (trace: MatchDecisionTrace) => void;
|
|
17
|
+
}
|
|
18
|
+
export declare class DecisionTraceManager {
|
|
19
|
+
private redisClient;
|
|
20
|
+
private keys;
|
|
21
|
+
private options;
|
|
22
|
+
constructor(redisClient: RedisClientType, keys: KeyBuilders, options: DecisionTraceManagerOptions);
|
|
23
|
+
get hasDecisionHook(): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Persist traces (when `persist`) and emit each to the onDecision hook.
|
|
26
|
+
* Consumer callback errors never propagate into the matching pass.
|
|
27
|
+
*/
|
|
28
|
+
record(traces: MatchDecisionTrace[], persist: boolean): Promise<void>;
|
|
29
|
+
/** Query recorded traces, newest first. */
|
|
30
|
+
getTraces(query?: DecisionTraceQuery): Promise<MatchDecisionTrace[]>;
|
|
31
|
+
/** Delete every stored trace. Returns 1 when the stream existed. */
|
|
32
|
+
clear(): Promise<number>;
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=DecisionTraceManager.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DecisionTraceManager.d.ts","sourceRoot":"","sources":["../../src/managers/DecisionTraceManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAChG,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAEjD,MAAM,WAAW,2BAA2B;IACxC,mDAAmD;IACnD,UAAU,EAAE,MAAM,CAAC;IACnB,sEAAsE;IACtE,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,kBAAkB,KAAK,IAAI,CAAC;CACpD;AAED,qBAAa,oBAAoB;IAEzB,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,IAAI;IACZ,OAAO,CAAC,OAAO;gBAFP,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,2BAA2B;IAGhD,IAAI,eAAe,IAAI,OAAO,CAE7B;IAED;;;OAGG;IACG,MAAM,CAAC,MAAM,EAAE,kBAAkB,EAAE,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAwB3E,2CAA2C;IACrC,SAAS,CAAC,KAAK,CAAC,EAAE,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC;IAyB1E,oEAAoE;IAC9D,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;CAGjC"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DecisionTraceManager = void 0;
|
|
4
|
+
class DecisionTraceManager {
|
|
5
|
+
constructor(redisClient, keys, options) {
|
|
6
|
+
this.redisClient = redisClient;
|
|
7
|
+
this.keys = keys;
|
|
8
|
+
this.options = options;
|
|
9
|
+
}
|
|
10
|
+
get hasDecisionHook() {
|
|
11
|
+
return typeof this.options.onDecision === 'function';
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Persist traces (when `persist`) and emit each to the onDecision hook.
|
|
15
|
+
* Consumer callback errors never propagate into the matching pass.
|
|
16
|
+
*/
|
|
17
|
+
async record(traces, persist) {
|
|
18
|
+
if (traces.length === 0)
|
|
19
|
+
return;
|
|
20
|
+
if (persist) {
|
|
21
|
+
const streamKey = this.keys.decisionTraces();
|
|
22
|
+
const multi = this.redisClient.multi();
|
|
23
|
+
for (const trace of traces) {
|
|
24
|
+
multi.xAdd(streamKey, '*', { trace: JSON.stringify(trace) });
|
|
25
|
+
}
|
|
26
|
+
multi.xTrim(streamKey, 'MAXLEN', this.options.maxEntries);
|
|
27
|
+
await multi.exec();
|
|
28
|
+
}
|
|
29
|
+
if (this.options.onDecision) {
|
|
30
|
+
for (const trace of traces) {
|
|
31
|
+
try {
|
|
32
|
+
this.options.onDecision(trace);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// The hook is observability, not control flow.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Query recorded traces, newest first. */
|
|
41
|
+
async getTraces(query) {
|
|
42
|
+
const limit = query?.limit ?? 50;
|
|
43
|
+
if (limit <= 0)
|
|
44
|
+
return [];
|
|
45
|
+
const filtered = Boolean(query?.assignmentId || query?.userId);
|
|
46
|
+
// Unfiltered reads only need `limit` entries; filtered reads scan the
|
|
47
|
+
// whole (capped) stream, which is bounded by maxEntries.
|
|
48
|
+
const count = filtered ? this.options.maxEntries : limit;
|
|
49
|
+
const entries = await this.redisClient.xRevRange(this.keys.decisionTraces(), '+', '-', { COUNT: count });
|
|
50
|
+
const results = [];
|
|
51
|
+
for (const entry of entries) {
|
|
52
|
+
let trace;
|
|
53
|
+
try {
|
|
54
|
+
trace = JSON.parse(entry.message.trace);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (query?.assignmentId && trace.assignmentId !== query.assignmentId)
|
|
60
|
+
continue;
|
|
61
|
+
if (query?.userId && trace.chosenUserId !== query.userId)
|
|
62
|
+
continue;
|
|
63
|
+
results.push(trace);
|
|
64
|
+
if (results.length >= limit)
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
return results;
|
|
68
|
+
}
|
|
69
|
+
/** Delete every stored trace. Returns 1 when the stream existed. */
|
|
70
|
+
async clear() {
|
|
71
|
+
return this.redisClient.del(this.keys.decisionTraces());
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
exports.DecisionTraceManager = DecisionTraceManager;
|
|
@@ -64,6 +64,12 @@ export declare class WorkflowManager {
|
|
|
64
64
|
registerWorkflow(definition: WorkflowDefinitionInput | WorkflowDefinition): Promise<WorkflowDefinition>;
|
|
65
65
|
getWorkflowDefinition(id: string): Promise<WorkflowDefinition | null>;
|
|
66
66
|
listWorkflowDefinitions(): Promise<WorkflowDefinitionSummary[]>;
|
|
67
|
+
/**
|
|
68
|
+
* Delete a workflow definition and its listing entry. Running instances keep
|
|
69
|
+
* their own `definitionSnapshot`, so in-flight workflows are unaffected.
|
|
70
|
+
* Returns `false` if no definition with that id existed.
|
|
71
|
+
*/
|
|
72
|
+
deleteWorkflowDefinition(id: string): Promise<boolean>;
|
|
67
73
|
startWorkflow(workflowDefinitionId: string, userId: string, initialContext?: Record<string, any>): Promise<WorkflowInstance>;
|
|
68
74
|
getWorkflowInstance(instanceId: string): Promise<WorkflowInstance | null>;
|
|
69
75
|
getWorkflowInstanceWithSnapshot(instanceId: string): Promise<WorkflowInstanceWithSnapshot | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WorkflowManager.d.ts","sourceRoot":"","sources":["../../src/managers/WorkflowManager.ts"],"names":[],"mappings":"AACA,OAAO,EACH,eAAe,EACf,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,YAAY,EACZ,aAAa,EAEb,UAAU,EACV,4BAA4B,EAE5B,qBAAqB,EACxB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD,eAAO,MAAQ,OAAO,mCAAuB,CAAC;AAE9C,MAAM,WAAW,YAAY;IACzB,aAAa,CAAC,UAAU,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IAC3D,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IACpD,kBAAkB,CAAC,CAAC,IAAI,EAAE;QACtB,QAAQ,EAAE,gBAAgB,CAAC;QAC3B,IAAI,EAAE,YAAY,CAAC;QACnB,UAAU,EAAE,kBAAkB,CAAC;KAClC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;CAC3C;AAED,mFAAmF;AACnF,MAAM,MAAM,kBAAkB,GAAG,CAAC,IAAI,EAAE;IACpC,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,IAAI,EAAE,YAAY,CAAC;IACnB,UAAU,EAAE,kBAAkB,CAAC;CAClC,KAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;AAE1C,qBAAa,eAAe;IAWpB,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
return Object.entries(definitions).map(([id, name]) => ({ id, name }));
|
|
74
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* Delete a workflow definition and its listing entry. Running instances keep
|
|
77
|
+
* their own `definitionSnapshot`, so in-flight workflows are unaffected.
|
|
78
|
+
* Returns `false` if no definition with that id existed.
|
|
79
|
+
*/
|
|
80
|
+
async deleteWorkflowDefinition(id) {
|
|
81
|
+
const removed = await this.redisClient.del(this.keys.workflowDefinition(id));
|
|
82
|
+
await this.redisClient.hDel(this.keys.workflowDefinitions(), id);
|
|
83
|
+
return removed > 0;
|
|
84
|
+
}
|
|
75
85
|
async startWorkflow(workflowDefinitionId, userId, initialContext) {
|
|
76
86
|
if (!workflowDefinitionId.trim()) {
|
|
77
87
|
throw new Error('Workflow definition ID is required');
|