assignment-user-matcher 1.2.5 → 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 CHANGED
@@ -1,53 +1,21 @@
1
- This Strict Commercial License ("License") is a legal agreement between the Owner identified below ("Owner") and any natural person or legal entity that receives, accesses, or uses the Software ("Recipient"). By receiving, accessing, or using the Software, Recipient acknowledges and agrees to the terms below. All capitalized terms not otherwise defined herein have the meanings given in Section 1.
2
-
3
- 1. Definitions
4
- - "Software" means the source code, binaries, documentation, designs, examples, data, configuration, and any other materials provided by Owner.
5
- - "Use" means to copy, execute, run, display, distribute, host, provide as a service, sublicense, or otherwise employ the Software.
6
- - "Modify" means to alter, adapt, translate, create derivative works of, reverse engineer, decompile, disassemble, or otherwise change the Software.
7
-
8
- 2. No Grant
9
- - Except for a specific, express, written license signed by Owner, no rights, licenses, or permissions are granted to Recipient, whether by implication, estoppel, or otherwise. Owner expressly reserves all rights in the Software.
10
-
11
- 3. Prohibited Acts
12
- - Without Owner's prior written permission, Recipient shall not, directly or indirectly, Use, copy, publish, distribute, sublicense, make available, or Modify the Software in whole or in part.
13
- - Recipient shall not remove, alter, or obscure any proprietary, copyright, or other notices in or on the Software, nor attempt to bypass technological restrictions or authentication controls.
14
-
15
- 4. Remedies; Liquidated Damages; Fees
16
- - Each unauthorized Use or Modification of the Software (each an "Infringing Act") shall constitute a material breach and an actionable wrong.
17
- - For each Infringing Act, Recipient agrees that Owner shall be entitled to recover liquidated damages in the amount of USD 250,000 (Two Hundred Fifty Thousand United States Dollars) per Infringing Act, which the parties agree is a reasonable pre-estimate of damages and not a penalty. In addition, Owner may recover:
18
- - disgorgement of all profits and revenues derived from the Infringing Act;
19
- - statutory damages available under applicable law (if greater than the liquidated damages amount);
20
- - pre-judgment and post-judgment interest at the highest lawful rate;
21
- - Owner's reasonable attorneys' fees, costs, and expenses incurred to investigate or enforce this License; and
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
@@ -273,6 +273,7 @@ Adds or updates a user in the system.
273
273
  - `user`: An object representing the user.
274
274
  - `id: string`: Unique identifier for the user.
275
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.
276
277
 
277
278
  ### `addAssignment(assignment: Assignment): Promise<void>`
278
279
 
@@ -305,6 +306,26 @@ Retrieves current pending assignments, including who owns each assignment and ho
305
306
  - `pendingSince`: Unix timestamp (ms) when the assignment entered pending state.
306
307
  - `expiresAt`: Unix timestamp (ms) when pending expiration is scheduled.
307
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
+
308
329
  ### `removeUser(userId: string): Promise<void>`
309
330
 
310
331
  Removes a user from the system and clears their assignment backlog.
@@ -437,6 +458,27 @@ type Options = {
437
458
  assignmentId?: string,
438
459
  ) => Promise<[number, number]>;
439
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
+
440
482
  // ========== Reinforcement Learning Options ==========
441
483
 
442
484
  // Enable the adaptive learning layer (contextual bandit re-ranking).
@@ -479,6 +521,93 @@ type Options = {
479
521
  };
480
522
  ```
481
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
+
482
611
  ## Adaptive Matching with Reinforcement Learning
483
612
 
484
613
  The matcher includes an opt-in, Redis-backed contextual bandit that learns from
@@ -1085,4 +1214,4 @@ Consumers can `import AssignmentMatcher from 'assignment-user-matcher'` or `cons
1085
1214
 
1086
1215
  ## License
1087
1216
 
1088
- This library is proprietary, commercially-licensed software — see [`LICENCE`](./LICENCE) for the full terms. No use, copying, modification, or distribution is permitted without the Owner's prior written permission (the LICENCE file's non-commercial fair-use footnote covers limited evaluation/academic use with written confirmation from the Owner). Contact viljar@forgemaster.ai for licensing.
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, FairnessMode, FairnessConfig, } 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';
@@ -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,EAChB,YAAY,EACZ,cAAc,GACjB,MAAM,iBAAiB,CAAC;AAGzB,YAAY,EACR,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,4BAA4B,EAC5B,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,yBAAyB,EACzB,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,eAAe,EACf,yBAAyB,EACzB,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,YAAY,EACZ,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,GACnB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE7E,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,yBAAyB,CAAC;AAGjG,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,QAAQ,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtH,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAGhG,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAExF,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
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,OAA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OAAO,CAAC,MAAM,CAAC;IA4C9C;;;OAGG;IACG,uBAAuB,IAAI,OAAO,CAAC,MAAM,CAAC;IAyBhD;;;;OAIG;IACG,sBAAsB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAkClE;;OAEG;IACG,kBAAkB,IAAI,OAAO,CAAC,qBAAqB,CAAC;IA8BpD,wBAAwB,CAC1B,UAAU,EAAE,MAAM,EAClB,eAAe,EAAE,MAAM,EACvB,SAAS,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EACrC,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACnC,YAAY,CAAC,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAC9C,OAAO,CAAC;QAAE,EAAE,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,EAAE,gBAAgB,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAgB3E"}
@@ -72,6 +72,16 @@ class WorkflowManager {
72
72
  const definitions = await this.redisClient.hGetAll(this.keys.workflowDefinitions());
73
73
  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');
@@ -1,7 +1,7 @@
1
1
  import { type PaginationOptions, type PaginationResult, type AssignmentCounts } from './queries/pagination';
2
2
  import { type WorkflowHost, type MachineTaskHandler } from './managers/WorkflowManager';
3
- import type { RedisClientType, User, Assignment, Stats, PendingAssignmentInfo, MatcherOptions, WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowEvent, AssignmentResult, DeadLetterEntry, AuditEntry, WorkflowInstanceWithSnapshot, LearningSignals, LearningSample, LearningStats, LearningTagStat, ReliabilityMetrics, CircuitBreakerState, WorkflowEngineMetrics, FairnessMode, FairnessConfig } from './types/matcher';
4
- export type { RedisClientType, User, Assignment, Stats, PendingAssignmentInfo, MatcherOptions, options, FairnessMode, FairnessConfig, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, WorkflowInstanceStatus, WorkflowRouting, } from './types/matcher';
3
+ import type { RedisClientType, User, Assignment, Stats, PendingAssignmentInfo, QueueStats, MatcherOptions, WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowEvent, AssignmentResult, DeadLetterEntry, AuditEntry, WorkflowInstanceWithSnapshot, LearningSignals, LearningSample, LearningStats, LearningTagStat, ReliabilityMetrics, CircuitBreakerState, WorkflowEngineMetrics, FairnessMode, FairnessConfig, MatchDecisionTrace, MatchExplanation, DecisionTraceQuery } from './types/matcher';
4
+ export type { RedisClientType, User, Assignment, Stats, PendingAssignmentInfo, QueueStats, UserLoadInfo, MatcherOptions, options, FairnessMode, FairnessConfig, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, WorkflowInstanceStatus, WorkflowRouting, MatchTraceReason, MatchCandidateTrace, MatchDecisionTrace, MatchDecisionMode, MatchExplanation, DecisionTraceQuery, } from './types/matcher';
5
5
  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, LearningTagStat, AutoRoutingWeightsOptions, WorkflowEngineMetrics, } from './types/matcher';
6
6
  export type { MachineTaskHandler, WorkflowHost } from './managers/WorkflowManager';
7
7
  export type { AssignmentStatus, PaginationOptions, PaginationResult, AssignmentCounts } from './queries/pagination';
@@ -46,6 +46,9 @@ export default class AssignmentMatcher implements WorkflowHost {
46
46
  private fairnessTieBand;
47
47
  private fairnessMaxPerWindow?;
48
48
  private fairnessWindowMs;
49
+ private enableDecisionTraces;
50
+ private decisionTraceMaxCandidates;
51
+ private decisionTraces;
49
52
  constructor(redisClient: RedisClientType, options?: MatcherOptions);
50
53
  /** Keys for the three assignment stores (used by pagination queries) */
51
54
  private get assignmentStoreKeys();
@@ -179,6 +182,56 @@ export default class AssignmentMatcher implements WorkflowHost {
179
182
  fairnessMaxPerWindow: number | undefined;
180
183
  fairnessWindowMs: number;
181
184
  };
185
+ /** Whether trace capture should run this pass (persistence flag or real-time hook). */
186
+ private get tracingActive();
187
+ /**
188
+ * Toggle decision-trace persistence at runtime without reconstructing the
189
+ * matcher. Takes effect on the next matching pass (a pass already in
190
+ * flight keeps the value it started with).
191
+ */
192
+ setDecisionTraces(enabled: boolean): void;
193
+ /** Current runtime decision-trace persistence state. */
194
+ isDecisionTracesEnabled(): boolean;
195
+ /**
196
+ * Query recorded decision traces, newest first. Only decisions made while
197
+ * `enableDecisionTraces` was active are stored — traces are captured as
198
+ * decisions happen, never reconstructed after the fact.
199
+ */
200
+ getDecisionTraces(query?: DecisionTraceQuery): Promise<MatchDecisionTrace[]>;
201
+ /** Delete all recorded decision traces. */
202
+ clearDecisionTraces(): Promise<number>;
203
+ /**
204
+ * Explain, from live state, which users could receive an assignment and
205
+ * why each one is or is not eligible: vetoes, prior rejections, skill
206
+ * thresholds, CIDR and geo constraints, backlog, the full score breakdown,
207
+ * and learning influence. Works for assignments in any lifecycle state;
208
+ * for matched assignments the current owner is flagged `chosen` (accepted
209
+ * assignments report `ownerId: null` because ownership metadata is
210
+ * released on acceptance — decision traces retain the full history).
211
+ *
212
+ * This is an on-demand recomputation against current state. For the
213
+ * auditable record of a decision as it actually happened, use
214
+ * `getDecisionTraces()`.
215
+ */
216
+ explainMatch(assignmentId: string, opts?: {
217
+ userIds?: string[];
218
+ }): Promise<MatchExplanation>;
219
+ /** One user's full eligibility/score evaluation for explainMatch(). */
220
+ private explainCandidate;
221
+ /** Build and record this pass's decision traces; failures never break matching. */
222
+ private recordPassTraces;
223
+ /** Exclusion sets used to enrich traces with prefiltered (vetoed/rejected/paused) users. */
224
+ private getTraceUserContexts;
225
+ /** One sMembers per pass: the user list minus currently paused users. */
226
+ private filterPausedUsers;
227
+ /**
228
+ * Workflow-targeted assignments are re-granted idempotently on every
229
+ * matching pass until actioned; only first-time grants deserve a decision
230
+ * trace. Reads membership before the sAdd that follows.
231
+ */
232
+ private filterNewWorkflowGrants;
233
+ /** Reasons for one scored candidate evaluation (trace capture only). */
234
+ private traceScoreReasons;
182
235
  /**
183
236
  * Per-user, per-tag reward statistics aggregated from learned outcomes.
184
237
  * Requires `enableLearning` and `enableAutoRoutingWeights`.
@@ -227,6 +280,34 @@ export default class AssignmentMatcher implements WorkflowHost {
227
280
  addAssignment(assignment: Assignment): Promise<Assignment>;
228
281
  removeAssignment(id: string): Promise<string>;
229
282
  removeUser(userId: string): Promise<string>;
283
+ /**
284
+ * Get one stored user as last written by addUser (including the injected
285
+ * 'default' tag when enableDefaultMatching is on), or null.
286
+ */
287
+ getUser(userId: string): Promise<User | null>;
288
+ /** All stored users. The pool is small by design; for load metadata see getQueueStats(). */
289
+ getUsers(): Promise<User[]>;
290
+ /**
291
+ * Pause a user: they stop receiving new assignments in every matching path
292
+ * until resumed, but keep their pending backlog and can still accept,
293
+ * complete, reject, or fail work they already hold. Paused users are also
294
+ * exempt from idle auto-removal (pausing is deliberate absence, not
295
+ * idleness). Idempotent.
296
+ *
297
+ * @returns false when the user is not in the pool (nothing is recorded)
298
+ */
299
+ pauseUser(userId: string): Promise<boolean>;
300
+ /**
301
+ * Resume a paused user so matching considers them again on the next pass.
302
+ * Also records activity (resets the idle clock).
303
+ *
304
+ * @returns false when the user was not paused
305
+ */
306
+ resumeUser(userId: string): Promise<boolean>;
307
+ /** Whether a user is currently paused. */
308
+ isUserPaused(userId: string): Promise<boolean>;
309
+ /** IDs of all currently paused users. */
310
+ getPausedUsers(): Promise<string[]>;
230
311
  /**
231
312
  * Get all assignments (queued, pending, and accepted).
232
313
  * For large datasets, prefer using getAssignmentsPaginated() instead.
@@ -254,6 +335,14 @@ export default class AssignmentMatcher implements WorkflowHost {
254
335
  * Get multiple assignments by IDs efficiently.
255
336
  */
256
337
  getAssignmentsByIds(ids: string[]): Promise<Assignment[]>;
338
+ /**
339
+ * Live operational snapshot for dashboards: queued/pending counts, the
340
+ * age of the longest-waiting unaccepted assignment, and every user's
341
+ * backlog depth, effective cap, and paused state. The wait clock starts
342
+ * at first enqueue and survives reject/expiry requeues; it stops on
343
+ * accept or removal.
344
+ */
345
+ getQueueStats(): Promise<QueueStats>;
257
346
  /**
258
347
  * Get all pending assignments with owner and pending duration metadata.
259
348
  */
@@ -290,6 +379,13 @@ export default class AssignmentMatcher implements WorkflowHost {
290
379
  * higher scorer should still be considered for their next-best options,
291
380
  * not left with nothing because discovery stopped early.
292
381
  */
382
+ /**
383
+ * Effective backlog cap for one user: `user.maxBacklogSize` when it is a
384
+ * valid non-negative number, else the matcher-wide `maxUserBacklogSize`.
385
+ * The fairness window auto-cap derivation (team-level) deliberately keeps
386
+ * using the global value.
387
+ */
388
+ private backlogLimitFor;
293
389
  private computeCandidatesForUser;
294
390
  /**
295
391
  * Atomically claims a set of tag-scored candidate assignments for one
@@ -328,6 +424,29 @@ export default class AssignmentMatcher implements WorkflowHost {
328
424
  private matchAllUsersFair;
329
425
  matchUsersAssignments(userId?: string): Promise<void>;
330
426
  getCurrentAssignmentsForUser(userId: string): Promise<string[]>;
427
+ /**
428
+ * Operator override: hand an assignment directly to a user, bypassing
429
+ * tag/weight selection. Works on queued assignments and on pending ones
430
+ * held by another user (the previous owner's backlog slot is released).
431
+ * Idempotent when the user already owns the assignment.
432
+ *
433
+ * Hard rules still apply unless `force`: the user must not be paused,
434
+ * their backlog must have headroom, they must not be vetoed on the
435
+ * assignment, and they must not have previously rejected it. `force`
436
+ * bypasses those checks (the user must always exist). The learning layer
437
+ * is never fed by manual assignments.
438
+ *
439
+ * When tracing is active the override is recorded as a decision trace
440
+ * with mode `'manual'`, so supervisor actions show up in the same audit
441
+ * trail as organic matches.
442
+ */
443
+ assignToUser(assignmentId: string, userId: string, options?: {
444
+ force?: boolean;
445
+ }): Promise<{
446
+ previousOwnerId: string | null;
447
+ }>;
448
+ /** Audit record for an assignToUser() override; failures never break the assignment. */
449
+ private recordManualAssignTrace;
331
450
  acceptAssignment(userId: string, assignmentId: string): Promise<boolean>;
332
451
  rejectAssignment(userId: string, assignmentId: string): Promise<boolean>;
333
452
  /**
@@ -365,6 +484,11 @@ export default class AssignmentMatcher implements WorkflowHost {
365
484
  * List all registered workflow definitions.
366
485
  */
367
486
  listWorkflowDefinitions(): Promise<WorkflowDefinitionSummary[]>;
487
+ /**
488
+ * Delete a workflow definition by ID. Running instances are unaffected
489
+ * (they carry their own snapshot). Returns `false` if it did not exist.
490
+ */
491
+ deleteWorkflowDefinition(id: string): Promise<boolean>;
368
492
  /**
369
493
  * Register and start a workflow in one call, or start an already-registered workflow by ID.
370
494
  */