assignment-user-matcher 1.10.0 → 1.11.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 (51) hide show
  1. package/README.md +59 -10
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/learning/auto-weights.d.ts +7 -4
  5. package/dist/learning/auto-weights.d.ts.map +1 -1
  6. package/dist/learning/auto-weights.js +7 -6
  7. package/dist/lua/workflow-transition.lua +8 -2
  8. package/dist/managers/LearningManager.d.ts.map +1 -1
  9. package/dist/managers/LearningManager.js +47 -0
  10. package/dist/managers/WorkflowManager.d.ts +7 -1
  11. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  12. package/dist/managers/WorkflowManager.js +85 -12
  13. package/dist/matcher.class.d.ts +35 -3
  14. package/dist/matcher.class.d.ts.map +1 -1
  15. package/dist/matcher.class.js +308 -76
  16. package/dist/queries/users.d.ts +34 -0
  17. package/dist/queries/users.d.ts.map +1 -0
  18. package/dist/queries/users.js +227 -0
  19. package/dist/scheduling/constraints/availability.d.ts +0 -1
  20. package/dist/scheduling/constraints/availability.d.ts.map +1 -1
  21. package/dist/scheduling/constraints/availability.js +27 -4
  22. package/dist/scheduling/constraints/contract.d.ts.map +1 -1
  23. package/dist/scheduling/constraints/contract.js +17 -3
  24. package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -1
  25. package/dist/scheduling/constraints/daily-rest.js +7 -2
  26. package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -1
  27. package/dist/scheduling/constraints/hour-budget.js +7 -1
  28. package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -1
  29. package/dist/scheduling/constraints/in-shift-breaks.js +4 -2
  30. package/dist/scheduling/constraints/min-rest.d.ts.map +1 -1
  31. package/dist/scheduling/constraints/min-rest.js +8 -19
  32. package/dist/scheduling/constraints/night-work.js +17 -1
  33. package/dist/scheduling/constraints/no-overlap.d.ts +5 -1
  34. package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -1
  35. package/dist/scheduling/constraints/no-overlap.js +11 -12
  36. package/dist/scheduling/constraints/weekly-rest.js +12 -1
  37. package/dist/scheduling/engine/construction.d.ts.map +1 -1
  38. package/dist/scheduling/engine/construction.js +7 -0
  39. package/dist/scheduling/model.d.ts.map +1 -1
  40. package/dist/scheduling/model.js +1 -0
  41. package/dist/scheduling/time.d.ts +6 -0
  42. package/dist/scheduling/time.d.ts.map +1 -1
  43. package/dist/scheduling/time.js +20 -9
  44. package/dist/scheduling/types.d.ts +6 -0
  45. package/dist/scheduling/types.d.ts.map +1 -1
  46. package/dist/types/matcher.d.ts +71 -2
  47. package/dist/types/matcher.d.ts.map +1 -1
  48. package/dist/utils/keys.d.ts +1 -0
  49. package/dist/utils/keys.d.ts.map +1 -1
  50. package/dist/utils/keys.js +6 -0
  51. package/package.json +1 -1
package/README.md CHANGED
@@ -241,6 +241,8 @@ Registration rejects an escalation target that doesn't exist, a step escalating
241
241
 
242
242
  Targeting matters: `targetUser({ tag: '…' })` routes the step's assignment through ordinary tag matching (so fairness, backlog caps, and the rolling-window grant cap all apply), while `targetUser('<userId>')` makes it workflow-targeted and therefore exempt from the fairness window cap. For tiered escalation you almost always want the tag form.
243
243
 
244
+ A workflow-targeted assignment is claimed queued→pending for its target through the same atomic claim gate as organic matching, whether or not the worker's tags/weights would ever have matched it — so `acceptAssignment`/`completeAssignment` work identically and the workflow advances. A worker who rejects a targeted assignment is not re-granted it (the standard rejection contract); the step then runs its response-deadline/escalation machinery.
245
+
244
246
  Plain object workflow definitions are also accepted. The library now fills in sensible defaults:
245
247
 
246
248
  - `version` defaults to `1`
@@ -302,7 +304,7 @@ Adds or updates a user in the system.
302
304
  - `user`: An object representing the user.
303
305
  - `id: string`: Unique identifier for the user.
304
306
  - `tags: string[]`: Array of tags associated with the user.
305
- - `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.
307
+ - `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 cap bounds the user's **total** pending backlog: a user already holding work is only topped up to the cap, never past it. The fairness rolling-window auto-cap derivation stays team-level and keeps using the global value.
306
308
 
307
309
  ### `addAssignment(assignment: Assignment): Promise<void>`
308
310
 
@@ -325,9 +327,9 @@ Retrieves the current list of assignments that a user is tentatively matched wit
325
327
 
326
328
  - `userId: string`: The ID of the user.
327
329
 
328
- ### `getPendingAssignmentsWithAge(): Promise<PendingAssignmentInfo[]>`
330
+ ### `getPendingAssignmentsWithAge(options?: { limit?: number }): Promise<PendingAssignmentInfo[]>`
329
331
 
330
- Retrieves current pending assignments, including who owns each assignment and how long it has been pending.
332
+ Retrieves current pending assignments, including who owns each assignment and how long it has been pending. Reads are bounded (the pending hash is paged with `HSCAN` and each page's lookups are batched), and corrupt entries are skipped. Pass `{ limit }` (clamped to 1000) to hydrate only the top-N longest-pending assignments instead of every one; without options the behavior is unchanged.
331
333
 
332
334
  - `assignment`: The assignment payload.
333
335
  - `ownerId`: The current owner user ID, or `null` if missing.
@@ -335,6 +337,42 @@ Retrieves current pending assignments, including who owns each assignment and ho
335
337
  - `pendingSince`: Unix timestamp (ms) when the assignment entered pending state.
336
338
  - `expiresAt`: Unix timestamp (ms) when pending expiration is scheduled.
337
339
 
340
+ ### User status & workload queries
341
+
342
+ Three bounded APIs answer "who is in the pool and how loaded are they?" without materializing whole Redis structures:
343
+
344
+ #### `getUsersPaginated(options?: UserQueryOptions): Promise<UserQueryResult>`
345
+
346
+ Paginated user scan with composable filters (logical AND):
347
+
348
+ ```ts
349
+ const page = await matcher.getUsersPaginated({
350
+ status: 'active', // 'all' | 'active' | 'paused' | 'idle'
351
+ idleForMs: 10 * 60_000, // last touchUser() older than this
352
+ hasBacklog: true, // pending backlog non-empty
353
+ atCapacity: true, // backlog reached the effective cap
354
+ limit: 100, // clamped to [1, 1000]
355
+ includeAssignments: true, // also return pending/accepted ids
356
+ includeTotal: true, // also return the unfiltered pool size
357
+ cursor: null, // pass nextCursor verbatim to continue
358
+ });
359
+ ```
360
+
361
+ Each `UserSummary` carries `userId`, the stored `user` record, `paused`, `lastActiveAt`, `backlog`, `acceptedCount`, the effective `maxBacklogSize` (per-user override honored), and `atCapacity`. `status: 'idle'` without an explicit `idleForMs` falls back to the matcher's `idleUserTimeoutMs` (and matches nobody when neither is set). Two pagination caveats, both consequences of paging the users hash with `HSCAN`: a scan page is never split, so a returned page may exceed `limit` by less than one scan page; and filters are applied during the scan, so a page may return fewer than `limit` users while `hasMore` is still true. Loop on `hasMore` until it is false. With `includeAssignments`, the returned `acceptedAssignmentIds` come straight from the per-user index and are not verified against the accepted store — a rare stale id can appear; `getActiveAssignmentsForUser()` is the verified (and self-healing) read.
362
+
363
+ #### `getUserSummaries(userIds: string[]): Promise<UserSummary[]>`
364
+
365
+ Order-preserving batch version for a known set of ids (chunked pipelined reads). Missing or corrupt user records are omitted.
366
+
367
+ #### `getActiveAssignmentsForUser(userId: string): Promise<ActiveAssignmentInfo[]>`
368
+
369
+ A user's accepted (in-progress) assignments, newest first, each with its `acceptedAt` timestamp — the complement to `getCurrentAssignmentsForUser()`'s pending backlog. Backed by a per-user accepted index (`user:{id}:accepted`) maintained on accept and on every terminal transition (complete/fail/remove/SLA sweeps). Two freshness notes:
370
+
371
+ - The index is maintained from the version that introduced it: accepted work that predates upgrading (or that is in flight during a rolling upgrade) appears only after it cycles.
372
+ - A stale member can survive `removeAssignment` on a non-SLA accepted assignment (only SLA records carry their owner); reads verify ids against the accepted store and self-heal, so results stay correct.
373
+
374
+ **Crash-safety note.** `getUsers()` (and `getQueueStats()`'s internal user scan) now skip a corrupt user record instead of throwing on it — the same precedent `getAllAssignmentsFromStores` already set. One malformed entry can no longer take down a dashboard endpoint.
375
+
338
376
  ### `pauseUser(userId: string): Promise<boolean>` / `resumeUser(userId: string): Promise<boolean>`
339
377
 
340
378
  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()`.
@@ -998,11 +1036,11 @@ bandit policy.
998
1036
 
999
1037
  - `policy: 'ucb1'` (default): high-mean tags get high weights, an exploration
1000
1038
  bonus favors less-sampled tags, and bad tags are hard-vetoed at weight `0`.
1001
- - `policy: 'confidence'`: uses upper-confidence-bound for the weight and a
1002
- conservative lower-confidence-bound for the veto decision, so uncertainty
1003
- works against exclusion.
1039
+ - `policy: 'confidence'`: uses upper-confidence-bound for the weight and for
1040
+ the veto decision — a tag is hard-vetoed only when the whole confidence
1041
+ interval sits below the threshold, so uncertainty alone never excludes.
1004
1042
  - `policy: 'thompson'`: samples from the per-tag posterior when mapping to a
1005
- weight.
1043
+ weight; the veto decision uses the deterministic mean, never the draw.
1006
1044
 
1007
1045
  **Guardrails (all opt-in):**
1008
1046
 
@@ -1013,8 +1051,11 @@ bandit policy.
1013
1051
  - `maxDeltaPerSync`: clamps how far any single learned weight can move per
1014
1052
  sync, avoiding oscillation.
1015
1053
  - `minTotalSamples`: skip users whose total evidence is still too thin.
1016
- - `decayHalfLifeMs`: exponentially decay older observations on read so stale
1017
- history cannot veto a user's improving skills.
1054
+ - `decayHalfLifeMs`: exponentially decay older observations so stale history
1055
+ cannot veto a user's improving skills. The decay is applied at write time
1056
+ (old mass is rescaled before each new outcome lands, atomically in Redis)
1057
+ and continues on read, so a single fresh outcome re-weights the stats
1058
+ toward recent behavior instead of resurrecting decayed history.
1018
1059
  - `terminalOnlyTagStats`: when `true`, only terminal outcomes
1019
1060
  (complete/reject/expire/fail plus manual rewards/feedback) feed tag stats;
1020
1061
  the non-terminal `accept` update is skipped.
@@ -1061,6 +1102,14 @@ const wouldBe = await matcher.syncLearnedRoutingWeights('user-1', { dryRun: true
1061
1102
  await matcher.revertLearnedRoutingWeights('user-1');
1062
1103
  ```
1063
1104
 
1105
+ Two safety properties of the sync: a user's **declared tags always stay
1106
+ matchable** — a declared tag with no recorded outcomes gets the exploration
1107
+ prior rather than silently dropping out of the installed `routingWeights` —
1108
+ and the pre-sync state is always restorable: a user who had no
1109
+ `routingWeights` at all is snapshotted as such (`routingWeightsSnapshot:
1110
+ null`), so `revertLearnedRoutingWeights()` returns them to plain tag-based
1111
+ matching.
1112
+
1064
1113
  Synthesis happens outside the matching hot path — matching itself reads the
1065
1114
  user's stored `routingWeights` exactly as before, so the per-match cost is
1066
1115
  unchanged. The last-applied learned map is stored on the user as
@@ -1561,7 +1610,7 @@ const result = solveSchedule({
1561
1610
 
1562
1611
  Rules cover: daily rest (rolling window, reduction allowances, clock-band containment), weekly rest (two-level floor plus average), rolling working-time averages with absence neutralisation, overtime (ordinary-vs-overtime split, consent, per-day and per-window caps, time-off-in-lieu), duty-type volume quotas, night work (configurable band, per-shift cap, averaging, hazardous absolute cap, volume quotas, prohibited bands), in-shift breaks, consecutive days and nights, forbidden shift successions, minimum start interval, Sunday and holiday rules, minimum engagement, publication and change notice, availability and preferences, date-valid qualifications, group composition, statutory protections, contract limits, and fairness.
1563
1612
 
1564
- `Employee.rules` overrides the global set per person — that is how age classes, individual opt-outs and hazardous-work status are expressed. `Employee.personId` aggregates several contracts onto one natural person, which rest and window rules require.
1613
+ `Employee.rules` overrides the global set per person — that is how age classes, individual opt-outs and hazardous-work status are expressed. `Employee.personId` aggregates several contracts onto one natural person, which rest and window rules require: overlap (`no-overlap`) and inter-assignment rest (`min-rest`, `dailyRest`) are judged on the person timeline — spanning sibling contracts and supplied `history` — so two contracts cannot double-book a person or dodge a rest floor at the period boundary. Contract hour/day **maxima** are the opposite: per employee record, like the minimum and the `timeOffInLieu` ledger — one contract's cap is never consumed by a sibling's hours. Rolling volume windows (night-shift quotas, weekly-rest averaging) probe true rolling windows anchored on entry boundaries, never a day grid. Declared `available` windows are credited as a **union**: a shift spanning two contiguous windows is inside the declaration.
1565
1614
 
1566
1615
  Break entitlements are checked against shift design: `unpaidBreakMinutes` (deducted from working time) and `paidBreakMinutes` (working time, and the only thing that discharges a `paid: true` break rule). Deadline arithmetic that needs a "now" — notably whether a cancellation of a published assignment fell inside `notice.cancellationDeadlineMinutes` — is anchored by the optional `asOf` input; without it every cancellation is treated as late, the conservative reading.
1567
1616
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
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, CompletionDeadlineSweepResult, SlaExpirySweepResult, SlaPolicy, SlaStats, SchedulePolicy, ScheduleSweepResult, AssignmentLintIssue, AssignmentLintContext, AssignmentReadinessReport, QueueAuditOptions, QueueAuditEntry, QueueAuditReport, MaintenanceOptions, MaintenanceReport, } 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, UserStatusFilter, UserQueryOptions, UserSummary, UserQueryResult, ActiveAssignmentInfo, } from './matcher.class';
3
3
  export { lintAssignment, userCoversTag } from './validation/assignment-lint';
4
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';
5
5
  export { explainMatchScore, type MatchScoreExplanation } from './scoring/match-score';
@@ -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,6BAA6B,EAC7B,oBAAoB,EACpB,SAAS,EACT,QAAQ,EACR,cAAc,EACd,mB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,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
@@ -5,11 +5,14 @@
5
5
  *
6
6
  * - 'ucb1' (default): mean reward plus an exploration bonus that shrinks as
7
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.
8
+ * - 'confidence': upper-confidence-bound for the weight AND for the veto
9
+ * decision — a tag is hard-vetoed only when the whole confidence interval
10
+ * sits below the threshold, so vetoes are conservative: uncertainty alone
11
+ * never vetoes.
11
12
  * - 'thompson': sample from the per-tag posterior (Gaussian approximation)
12
- * when mapping to a weight.
13
+ * when mapping to a weight. The veto decision uses the deterministic mean,
14
+ * never the draw — a random sample must not flicker good tags into hard
15
+ * vetoes.
13
16
  *
14
17
  * Scores map onto the conventional 0-100 routing-weight scale:
15
18
  *
@@ -1 +1 @@
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"}
1
+ {"version":3,"file":"auto-weights.d.ts","sourceRoot":"","sources":["../../src/learning/auto-weights.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;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;AAuIF;;;;;;;;;;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,CAkDxB"}
@@ -34,14 +34,11 @@ function resolveOptions(options) {
34
34
  function isManualTag(tag, existingWeights) {
35
35
  return !!existingWeights && tag in existingWeights;
36
36
  }
37
- function canVeto(policy, stat, vetoScore, lcb, opts, existingWeights) {
37
+ function canVeto(policy, stat, vetoScore, opts, existingWeights) {
38
38
  const manual = isManualTag(stat.tag, existingWeights);
39
39
  const effectiveMinSamples = manual ? opts.minSamplesForVeto : opts.minSamples;
40
40
  if (stat.count < effectiveMinSamples)
41
41
  return false;
42
- if (policy === 'confidence') {
43
- return lcb <= opts.vetoThreshold;
44
- }
45
42
  return vetoScore <= opts.vetoThreshold;
46
43
  }
47
44
  function tagScore(policy, stat, totalCount, opts) {
@@ -140,8 +137,12 @@ function synthesizeRoutingWeights(stats, options, knownTags, existingWeights) {
140
137
  }
141
138
  const { ucb, lcb, sample } = tagScore(opts.policy, stat, totalCount, opts);
142
139
  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)) {
140
+ // Veto decisions are deterministic and conservative: 'confidence'
141
+ // requires the WHOLE interval below the threshold (ucb), 'thompson'
142
+ // and 'ucb1' judge the raw mean — never a random draw, never an
143
+ // uncertainty-widened lower bound.
144
+ const vetoScore = opts.policy === 'confidence' ? ucb : stat.meanReward;
145
+ if (canVeto(opts.policy, stat, vetoScore, opts, existingWeights)) {
145
146
  weights[stat.tag] = 0;
146
147
  continue;
147
148
  }
@@ -1,9 +1,13 @@
1
1
  -- workflow-transition.lua
2
2
  -- Atomic workflow state transition with optimistic locking (CAS)
3
- --
3
+ --
4
4
  -- KEYS[1] = workflow instance key
5
+ -- KEYS[2] = (optional) processed-event marker key, set atomically with the
6
+ -- transition so a replay of the same event after a crash between
7
+ -- "state written" and "marker written" is recognized as processed
5
8
  -- ARGV[1] = expected version
6
9
  -- ARGV[2] = new data (JSON string)
10
+ -- ARGV[3] = (optional) marker TTL in ms, required when KEYS[2] is present
7
11
  --
8
12
  -- Returns:
9
13
  -- {ok = true} on success
@@ -25,5 +29,7 @@ if parsed.version ~= expected_version then
25
29
  end
26
30
 
27
31
  redis.call('HSET', key, 'data', new_data)
32
+ if KEYS[2] and ARGV[3] then
33
+ redis.call('SET', KEYS[2], '1', 'PX', tonumber(ARGV[3]))
34
+ end
28
35
  return cjson.encode({ok = true})
29
-
@@ -1 +1 @@
1
- {"version":3,"file":"LearningManager.d.ts","sourceRoot":"","sources":["../../src/managers/LearningManager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EACR,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,aAAa,EACb,eAAe,EACf,yBAAyB,EAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGjD,eAAO,MA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EAAE,EACpB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACzC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAMlC,oCAAoC;IAC9B,QAAQ,IAAI,OAAO,CAAC,aAAa,CAAC;IAaxC,mEAAmE;IAC7D,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;CAcpC"}
@@ -11,6 +11,30 @@ exports.DEFAULT_LEARNING_REWARDS = {
11
11
  };
12
12
  /** Outcomes that end an assignment's learning episode (decision record is removed) */
13
13
  const TERMINAL_OUTCOMES = new Set(['complete', 'reject', 'expire', 'fail']);
14
+ /**
15
+ * Atomic decayed tag-outcome update: rescale the stored count/reward/rewardSq
16
+ * sums by the elapsed half-life factor since the tag's last write, add the new
17
+ * outcome at full weight, and stamp the write time — an exponentially-weighted
18
+ * aggregate, exact per observation. KEYS: counts, rewards, rewardSq, ts
19
+ * hashes. ARGV: tag, now (ms), halfLife (ms), reward.
20
+ */
21
+ const DECAYED_TAG_OUTCOME_LUA = `
22
+ local tag = ARGV[1]
23
+ local now = tonumber(ARGV[2])
24
+ local halfLife = tonumber(ARGV[3])
25
+ local reward = tonumber(ARGV[4])
26
+ local ts = tonumber(redis.call('HGET', KEYS[4], tag))
27
+ local f = 1
28
+ if ts and halfLife > 0 and now > ts then f = 2 ^ (-(now - ts) / halfLife) end
29
+ local count = (tonumber(redis.call('HGET', KEYS[1], tag)) or 0) * f + 1
30
+ local sum = (tonumber(redis.call('HGET', KEYS[2], tag)) or 0) * f + reward
31
+ local sq = (tonumber(redis.call('HGET', KEYS[3], tag)) or 0) * f + reward * reward
32
+ redis.call('HSET', KEYS[1], tag, count)
33
+ redis.call('HSET', KEYS[2], tag, sum)
34
+ redis.call('HSET', KEYS[3], tag, sq)
35
+ redis.call('HSET', KEYS[4], tag, now)
36
+ return 1
37
+ `;
14
38
  class LearningManager {
15
39
  constructor(redisClient, keys, options) {
16
40
  this.redisClient = redisClient;
@@ -230,6 +254,29 @@ class LearningManager {
230
254
  return;
231
255
  const needVariance = this.needsVarianceTracking();
232
256
  const now = Date.now();
257
+ const halfLife = this.autoWeights.decayHalfLifeMs ?? 0;
258
+ if (halfLife > 0) {
259
+ // With decay configured, the stored sums must be rescaled to "as of
260
+ // now" BEFORE the new outcome is added, atomically per tag. Plain
261
+ // increments plus a timestamp reset would (a) never change the
262
+ // mean (count and sum decay identically) and (b) resurrect fully
263
+ // decayed history the moment one fresh outcome landed.
264
+ for (const tag of tags) {
265
+ if (!tag)
266
+ continue;
267
+ await this.redisClient.eval(DECAYED_TAG_OUTCOME_LUA, {
268
+ keys: [
269
+ this.keys.learningUserTagCounts(userId),
270
+ this.keys.learningUserTagRewards(userId),
271
+ this.keys.learningUserTagRewardSq(userId),
272
+ this.keys.learningUserTagTs(userId),
273
+ ],
274
+ arguments: [tag, String(now), String(halfLife), String(reward)],
275
+ });
276
+ }
277
+ await this.redisClient.sAdd(this.keys.learningUsers(), userId);
278
+ return;
279
+ }
233
280
  const multi = this.redisClient.multi();
234
281
  for (const tag of tags) {
235
282
  if (!tag)
@@ -34,6 +34,12 @@ export declare class WorkflowManager {
34
34
  private subscriberClient;
35
35
  private subscriberReconnectAttempts;
36
36
  private luaScriptSha;
37
+ /** Script source, kept so a NOSCRIPT after a Redis restart can re-load it. */
38
+ private luaScriptSource;
39
+ /** Event id being applied right now — saveInstance stamps its idempotency
40
+ * marker atomically with the CAS write. Safe as an ambient field: events
41
+ * are processed sequentially within one manager. */
42
+ private processingEventId;
37
43
  private machineHandlers;
38
44
  private throttleWindowStart;
39
45
  private throttleTokensUsed;
@@ -68,7 +74,7 @@ export declare class WorkflowManager {
68
74
  init(): Promise<void>;
69
75
  private initStreamConsumerGroup;
70
76
  private isNoGroupError;
71
- setLuaScriptSha(sha: string): void;
77
+ setLuaScriptSha(sha: string, source?: string): void;
72
78
  /**
73
79
  * Register a machine task handler by name. Machine steps whose
74
80
  * machineTask.handler matches the name run through this handler.
@@ -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M,CAAA;KAAE,CAAC;CAgB3E"}
@@ -19,6 +19,12 @@ class WorkflowManager {
19
19
  this.subscriberClient = null;
20
20
  this.subscriberReconnectAttempts = 0;
21
21
  this.luaScriptSha = null;
22
+ /** Script source, kept so a NOSCRIPT after a Redis restart can re-load it. */
23
+ this.luaScriptSource = null;
24
+ /** Event id being applied right now — saveInstance stamps its idempotency
25
+ * marker atomically with the CAS write. Safe as an ambient field: events
26
+ * are processed sequentially within one manager. */
27
+ this.processingEventId = null;
22
28
  this.machineHandlers = new Map();
23
29
  this.throttleWindowStart = 0;
24
30
  this.throttleTokensUsed = 0;
@@ -60,8 +66,10 @@ class WorkflowManager {
60
66
  const message = err instanceof Error ? err.message : String(err ?? '');
61
67
  return message.includes('NOGROUP');
62
68
  }
63
- setLuaScriptSha(sha) {
69
+ setLuaScriptSha(sha, source) {
64
70
  this.luaScriptSha = sha;
71
+ if (source !== undefined)
72
+ this.luaScriptSource = source;
65
73
  }
66
74
  /**
67
75
  * Register a machine task handler by name. Machine steps whose
@@ -224,11 +232,17 @@ class WorkflowManager {
224
232
  });
225
233
  if (!ids.length)
226
234
  break;
235
+ const ghosts = [];
227
236
  for (const { value: id, score } of ids) {
228
237
  const instance = await this.getWorkflowInstance(id);
229
238
  lastScore = score;
230
- if (!instance)
239
+ if (!instance) {
240
+ // Retention expired the instance hash after the terminal
241
+ // transition removed its registry entry, so nothing else
242
+ // can ever clean this member — self-heal on read.
243
+ ghosts.push(id);
231
244
  continue;
245
+ }
232
246
  if (query.status && instance.status !== query.status)
233
247
  continue;
234
248
  if (query.workflowDefinitionId && instance.workflowDefinitionId !== query.workflowDefinitionId)
@@ -237,6 +251,9 @@ class WorkflowManager {
237
251
  if (instances.length >= limit)
238
252
  break;
239
253
  }
254
+ if (ghosts.length > 0) {
255
+ await this.redisClient.zRem(byTimeKey, ghosts);
256
+ }
240
257
  if (ids.length < scanBatchSize)
241
258
  break; // index exhausted
242
259
  upperBound = `(${lastScore}`;
@@ -904,7 +921,15 @@ class WorkflowManager {
904
921
  });
905
922
  try {
906
923
  const maxAttempts = 3;
924
+ this.processingEventId = event.eventId;
907
925
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
926
+ // Re-checked each attempt: a concurrent duplicate delivery loses
927
+ // the CAS race, retries here with fresh state, and must see
928
+ // the winner's marker (written atomically with the winning
929
+ // transition) instead of applying the same event twice.
930
+ if (attempt > 0 && (await this.reliability.isEventProcessed(event.eventId))) {
931
+ break;
932
+ }
908
933
  const instance = await this.getWorkflowInstance(event.workflowInstanceId);
909
934
  if (!instance || instance.status !== 'active') {
910
935
  break;
@@ -913,6 +938,19 @@ class WorkflowManager {
913
938
  if (!definition) {
914
939
  break;
915
940
  }
941
+ // Consume-time relevance guard, mirroring the publish-time one
942
+ // in processExpiredWorkflowSteps: a stale event for a step the
943
+ // run has moved past (an EXPIRED consumed after an on-time
944
+ // COMPLETED advanced the run, or a late COMPLETED after an
945
+ // escalation) must not fail, escalate, or re-advance the run.
946
+ if (event.stepId) {
947
+ const isCurrentStep = instance.currentStepId === event.stepId;
948
+ const isPendingBranch = instance.parallelBranches?.some((b) => b.stepId === event.stepId && b.status === 'pending') ??
949
+ false;
950
+ if (!isCurrentStep && !isPendingBranch) {
951
+ break;
952
+ }
953
+ }
916
954
  try {
917
955
  switch (event.type) {
918
956
  case 'COMPLETED':
@@ -944,6 +982,9 @@ class WorkflowManager {
944
982
  endSpan();
945
983
  throw err;
946
984
  }
985
+ finally {
986
+ this.processingEventId = null;
987
+ }
947
988
  }
948
989
  async handleStepCompletion(instance, definition, event) {
949
990
  const stepId = event.stepId;
@@ -1057,6 +1098,18 @@ class WorkflowManager {
1057
1098
  assignmentId: event.assignmentId,
1058
1099
  payload: { ...event.payload, willRetry },
1059
1100
  });
1101
+ // Pull the superseded assignment before retrying or failing the run —
1102
+ // the same removal the escalation path does. The matcher's expiry
1103
+ // sweep requeues an expired workflow assignment, so a retry would
1104
+ // otherwise run TWO live copies of the step, and a failed run would
1105
+ // leave matchable work for a dead workflow.
1106
+ const supersededId = event.assignmentId || instance.currentAssignmentId;
1107
+ if (supersededId && this.host.removeAssignment) {
1108
+ await this.host.removeAssignment(supersededId).catch(() => {
1109
+ /* already gone (completed, cancelled, swept) — nothing to supersede */
1110
+ });
1111
+ await this.redisClient.del(this.keys.workflowAssignmentLink(supersededId));
1112
+ }
1060
1113
  if (willRetry) {
1061
1114
  instance.retryCount += 1;
1062
1115
  await this.executeWorkflowStep(instance, stepId, definition);
@@ -1171,12 +1224,14 @@ class WorkflowManager {
1171
1224
  }
1172
1225
  }
1173
1226
  async reclaimOrphanedMessages() {
1174
- if (!this.subscriberClient?.isOpen)
1175
- return 0;
1227
+ // Sweep-mode hosts have no subscriber client, but a crashed consumer's
1228
+ // delivered-unacked entries still need recovering — XAUTOCLAIM is
1229
+ // non-blocking, so the main client serves when no subscriber exists.
1230
+ const client = this.subscriberClient?.isOpen ? this.subscriberClient : this.redisClient;
1176
1231
  const streamKey = this.keys.eventStream();
1177
1232
  let totalReclaimed = 0;
1178
1233
  try {
1179
- const result = await this.subscriberClient.xAutoClaim(streamKey, this.options.streamConsumerGroup, this.options.streamConsumerName, this.options.reclaimMinIdleMs ?? this.options.reclaimIntervalMs, '0-0', { COUNT: 100 });
1234
+ const result = await client.xAutoClaim(streamKey, this.options.streamConsumerGroup, this.options.streamConsumerName, this.options.reclaimMinIdleMs ?? this.options.reclaimIntervalMs, '0-0', { COUNT: 100 });
1180
1235
  if (result && result.messages && result.messages.length > 0) {
1181
1236
  for (const message of result.messages) {
1182
1237
  if (!message)
@@ -1184,20 +1239,20 @@ class WorkflowManager {
1184
1239
  const event = this.parseStreamMessage(message);
1185
1240
  try {
1186
1241
  if (await this.reliability.isEventProcessed(event.eventId)) {
1187
- await this.subscriberClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
1242
+ await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
1188
1243
  continue;
1189
1244
  }
1190
1245
  const retryKey = this.keys.eventRetryCount(event.eventId);
1191
1246
  const retryCount = Number(await this.redisClient.get(retryKey)) || 0;
1192
1247
  if (retryCount >= this.reliability.options.workflowMaxRetries) {
1193
1248
  await this.reliability.moveToDeadLetter(event, 'Max retries exceeded');
1194
- await this.subscriberClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
1249
+ await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
1195
1250
  }
1196
1251
  else {
1197
1252
  try {
1198
1253
  await this.processWorkflowEvent(event);
1199
1254
  await this.reliability.markEventProcessed(event.eventId);
1200
- await this.subscriberClient.xAck(streamKey, this.options.streamConsumerGroup, message.id);
1255
+ await client.xAck(streamKey, this.options.streamConsumerGroup, message.id);
1201
1256
  totalReclaimed++;
1202
1257
  }
1203
1258
  catch (err) {
@@ -1228,10 +1283,28 @@ class WorkflowManager {
1228
1283
  instance.updatedAt = Date.now();
1229
1284
  const newData = JSON.stringify(instance);
1230
1285
  if (this.luaScriptSha) {
1231
- const result = (await this.redisClient.evalSha(this.luaScriptSha, {
1232
- keys: [instanceKey],
1233
- arguments: [String(expectedVersion), newData],
1234
- }));
1286
+ // The idempotency marker rides in the same atomic script as the
1287
+ // CAS write: a crash after the transition but before a separate
1288
+ // marker write would otherwise re-apply the event on redelivery.
1289
+ const markerTtl = this.reliability.options.workflowIdempotencyTtlMs;
1290
+ const keys = this.processingEventId && markerTtl
1291
+ ? [instanceKey, this.keys.processedEvent(this.processingEventId)]
1292
+ : [instanceKey];
1293
+ const args = keys.length === 2
1294
+ ? [String(expectedVersion), newData, String(markerTtl)]
1295
+ : [String(expectedVersion), newData];
1296
+ let result;
1297
+ try {
1298
+ result = (await this.redisClient.evalSha(this.luaScriptSha, { keys, arguments: args }));
1299
+ }
1300
+ catch (err) {
1301
+ // A Redis restart/failover empties the script cache; without a
1302
+ // reload every transition fails NOSCRIPT until process restart.
1303
+ if (!String(err?.message ?? err).includes('NOSCRIPT') || !this.luaScriptSource)
1304
+ throw err;
1305
+ this.luaScriptSha = await this.redisClient.scriptLoad(this.luaScriptSource);
1306
+ result = (await this.redisClient.evalSha(this.luaScriptSha, { keys, arguments: args }));
1307
+ }
1235
1308
  const parsed = JSON.parse(result);
1236
1309
  if (parsed.err) {
1237
1310
  throw new Error(`Workflow transition failed: ${parsed.err}`);
@@ -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, QueueStats, MatcherOptions, WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowEvent, AssignmentResult, DeadLetterEntry, AuditEntry, WorkflowInstanceWithSnapshot, WorkflowInstanceQuery, WorkflowInstancePage, LearningSignals, LearningSample, LearningStats, LearningTagStat, ReliabilityMetrics, CircuitBreakerState, WorkflowEngineMetrics, FairnessMode, FairnessConfig, MatchDecisionTrace, MatchExplanation, MatchPreview, MatchPreviewInput, DecisionTraceQuery, EscalationSweepResult, CompletionDeadlineSweepResult, SlaExpirySweepResult, ScheduleSweepResult, MaintenanceOptions, MaintenanceReport, SlaStats, AssignmentReadinessReport, QueueAuditOptions, QueueAuditReport } 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, MatchPreview, MatchPreviewInput, DecisionTraceQuery, AssignmentLifecycleEvent, EscalationPolicy, EscalationSweepResult, CompletionDeadlineSweepResult, SlaExpirySweepResult, ScheduleSweepResult, MaintenanceOptions, MaintenanceReport, SlaPolicy, SlaStats, SchedulePolicy, AssignmentLintIssue, AssignmentLintContext, AssignmentReadinessReport, QueueAuditOptions, QueueAuditEntry, QueueAuditReport, } from './types/matcher';
3
+ import type { RedisClientType, User, Assignment, Stats, PendingAssignmentInfo, QueueStats, MatcherOptions, WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowEvent, AssignmentResult, DeadLetterEntry, AuditEntry, WorkflowInstanceWithSnapshot, WorkflowInstanceQuery, WorkflowInstancePage, LearningSignals, LearningSample, LearningStats, LearningTagStat, ReliabilityMetrics, CircuitBreakerState, WorkflowEngineMetrics, FairnessMode, FairnessConfig, MatchDecisionTrace, MatchExplanation, MatchPreview, MatchPreviewInput, DecisionTraceQuery, EscalationSweepResult, CompletionDeadlineSweepResult, SlaExpirySweepResult, ScheduleSweepResult, MaintenanceOptions, MaintenanceReport, SlaStats, AssignmentReadinessReport, QueueAuditOptions, QueueAuditReport, UserQueryOptions, UserSummary, UserQueryResult, ActiveAssignmentInfo } 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, MatchPreview, MatchPreviewInput, DecisionTraceQuery, AssignmentLifecycleEvent, EscalationPolicy, EscalationSweepResult, CompletionDeadlineSweepResult, SlaExpirySweepResult, ScheduleSweepResult, MaintenanceOptions, MaintenanceReport, SlaPolicy, SlaStats, SchedulePolicy, AssignmentLintIssue, AssignmentLintContext, AssignmentReadinessReport, QueueAuditOptions, QueueAuditEntry, QueueAuditReport, UserStatusFilter, UserQueryOptions, UserSummary, UserQueryResult, ActiveAssignmentInfo, } from './types/matcher';
5
5
  export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowStep, 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, WorkflowEngineMetrics, } from './types/matcher';
6
6
  export type { MachineTaskHandler, WorkflowHost } from './managers/WorkflowManager';
7
7
  export type { AssignmentStatus, PaginationOptions, PaginationResult, AssignmentCounts } from './queries/pagination';
@@ -377,6 +377,33 @@ export default class AssignmentMatcher implements WorkflowHost {
377
377
  userExists(userId: string): Promise<boolean>;
378
378
  /** All stored users. The pool is small by design; for load metadata see getQueueStats(). */
379
379
  getUsers(): Promise<User[]>;
380
+ /**
381
+ * Paginated user query with composable status/workload filters
382
+ * (`status`, `idleForMs`, `hasBacklog`, `atCapacity`). All reads are
383
+ * bounded: the users hash is paged with HSCAN and per-page metadata is
384
+ * batched into one multi(). A scan page is never split, so a page may
385
+ * exceed `limit` by less than one scan page, and filtered scans may
386
+ * return short pages with `hasMore: true` — keep consuming until
387
+ * `hasMore` is false. `status: 'idle'` without an explicit `idleForMs`
388
+ * falls back to the matcher's `idleUserTimeoutMs` (matches nobody when
389
+ * that is not configured either).
390
+ */
391
+ getUsersPaginated(options?: UserQueryOptions): Promise<UserQueryResult>;
392
+ /**
393
+ * Order-preserving workload summaries for a known set of user ids
394
+ * (chunked pipelined reads). Missing or corrupt user records are omitted.
395
+ */
396
+ getUserSummaries(userIds: string[]): Promise<UserSummary[]>;
397
+ /**
398
+ * A user's accepted (in-progress) assignments, newest first, backed by
399
+ * the per-user accepted index. Verified against the accepted store, so
400
+ * stale index members (e.g. left by a `removeAssignment` on a non-SLA
401
+ * assignment, or by an older library version) are dropped and self-healed.
402
+ *
403
+ * Note: the index is maintained from the version that introduced it —
404
+ * accepted work that predates it appears only after it cycles.
405
+ */
406
+ getActiveAssignmentsForUser(userId: string): Promise<ActiveAssignmentInfo[]>;
380
407
  /**
381
408
  * Pause a user: they stop receiving new assignments in every matching path
382
409
  * until resumed, but keep their pending backlog and can still accept,
@@ -445,8 +472,13 @@ export default class AssignmentMatcher implements WorkflowHost {
445
472
  getQueueStats(): Promise<QueueStats>;
446
473
  /**
447
474
  * Get all pending assignments with owner and pending duration metadata.
475
+ * Reads are bounded: the pending hash is paged with HSCAN and each page's
476
+ * owner/expiry lookups are batched. Pass `{ limit }` (clamped to 1000) to
477
+ * hydrate only the top-N longest-pending assignments instead of every one.
448
478
  */
449
- getPendingAssignmentsWithAge(): Promise<PendingAssignmentInfo[]>;
479
+ getPendingAssignmentsWithAge(options?: {
480
+ limit?: number;
481
+ }): Promise<PendingAssignmentInfo[]>;
450
482
  /** Default match score implementation using extracted scoring module */
451
483
  private defaultMatchScore;
452
484
  private matchScore;