assignment-user-matcher 1.9.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.
- package/README.md +164 -10
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +19 -1
- package/dist/learning/auto-weights.d.ts +7 -4
- package/dist/learning/auto-weights.d.ts.map +1 -1
- package/dist/learning/auto-weights.js +7 -6
- package/dist/lua/workflow-transition.lua +8 -2
- package/dist/managers/LearningManager.d.ts.map +1 -1
- package/dist/managers/LearningManager.js +47 -0
- package/dist/managers/WorkflowManager.d.ts +7 -1
- package/dist/managers/WorkflowManager.d.ts.map +1 -1
- package/dist/managers/WorkflowManager.js +85 -12
- package/dist/matcher.class.d.ts +35 -3
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +319 -76
- package/dist/queries/users.d.ts +34 -0
- package/dist/queries/users.d.ts.map +1 -0
- package/dist/queries/users.js +227 -0
- package/dist/scheduling/constraints/availability.d.ts +43 -0
- package/dist/scheduling/constraints/availability.d.ts.map +1 -0
- package/dist/scheduling/constraints/availability.js +165 -0
- package/dist/scheduling/constraints/consecutive.d.ts +25 -0
- package/dist/scheduling/constraints/consecutive.d.ts.map +1 -0
- package/dist/scheduling/constraints/consecutive.js +215 -0
- package/dist/scheduling/constraints/constraint.d.ts +35 -0
- package/dist/scheduling/constraints/constraint.d.ts.map +1 -0
- package/dist/scheduling/constraints/constraint.js +97 -0
- package/dist/scheduling/constraints/contract.d.ts +21 -0
- package/dist/scheduling/constraints/contract.d.ts.map +1 -0
- package/dist/scheduling/constraints/contract.js +120 -0
- package/dist/scheduling/constraints/cost.d.ts +18 -0
- package/dist/scheduling/constraints/cost.d.ts.map +1 -0
- package/dist/scheduling/constraints/cost.js +65 -0
- package/dist/scheduling/constraints/daily-rest.d.ts +22 -0
- package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -0
- package/dist/scheduling/constraints/daily-rest.js +123 -0
- package/dist/scheduling/constraints/duty-quota.d.ts +20 -0
- package/dist/scheduling/constraints/duty-quota.d.ts.map +1 -0
- package/dist/scheduling/constraints/duty-quota.js +95 -0
- package/dist/scheduling/constraints/engagement-floor.d.ts +28 -0
- package/dist/scheduling/constraints/engagement-floor.d.ts.map +1 -0
- package/dist/scheduling/constraints/engagement-floor.js +79 -0
- package/dist/scheduling/constraints/fairness.d.ts +34 -0
- package/dist/scheduling/constraints/fairness.d.ts.map +1 -0
- package/dist/scheduling/constraints/fairness.js +149 -0
- package/dist/scheduling/constraints/group-composition.d.ts +19 -0
- package/dist/scheduling/constraints/group-composition.d.ts.map +1 -0
- package/dist/scheduling/constraints/group-composition.js +92 -0
- package/dist/scheduling/constraints/hour-budget.d.ts +13 -0
- package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -0
- package/dist/scheduling/constraints/hour-budget.js +65 -0
- package/dist/scheduling/constraints/in-shift-breaks.d.ts +24 -0
- package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -0
- package/dist/scheduling/constraints/in-shift-breaks.js +99 -0
- package/dist/scheduling/constraints/intervals.d.ts +5 -0
- package/dist/scheduling/constraints/intervals.d.ts.map +1 -0
- package/dist/scheduling/constraints/intervals.js +17 -0
- package/dist/scheduling/constraints/max-shift-duration.d.ts +7 -0
- package/dist/scheduling/constraints/max-shift-duration.d.ts.map +1 -0
- package/dist/scheduling/constraints/max-shift-duration.js +38 -0
- package/dist/scheduling/constraints/min-rest.d.ts +22 -0
- package/dist/scheduling/constraints/min-rest.d.ts.map +1 -0
- package/dist/scheduling/constraints/min-rest.js +49 -0
- package/dist/scheduling/constraints/min-staffing.d.ts +14 -0
- package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -0
- package/dist/scheduling/constraints/min-staffing.js +59 -0
- package/dist/scheduling/constraints/night-work.d.ts +24 -0
- package/dist/scheduling/constraints/night-work.d.ts.map +1 -0
- package/dist/scheduling/constraints/night-work.js +179 -0
- package/dist/scheduling/constraints/no-overlap.d.ts +11 -0
- package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -0
- package/dist/scheduling/constraints/no-overlap.js +35 -0
- package/dist/scheduling/constraints/notice.d.ts +44 -0
- package/dist/scheduling/constraints/notice.d.ts.map +1 -0
- package/dist/scheduling/constraints/notice.js +140 -0
- package/dist/scheduling/constraints/one-shift-per-day.d.ts +7 -0
- package/dist/scheduling/constraints/one-shift-per-day.d.ts.map +1 -0
- package/dist/scheduling/constraints/one-shift-per-day.js +35 -0
- package/dist/scheduling/constraints/overtime.d.ts +47 -0
- package/dist/scheduling/constraints/overtime.d.ts.map +1 -0
- package/dist/scheduling/constraints/overtime.js +149 -0
- package/dist/scheduling/constraints/protections.d.ts +21 -0
- package/dist/scheduling/constraints/protections.d.ts.map +1 -0
- package/dist/scheduling/constraints/protections.js +93 -0
- package/dist/scheduling/constraints/qualification.d.ts +18 -0
- package/dist/scheduling/constraints/qualification.d.ts.map +1 -0
- package/dist/scheduling/constraints/qualification.js +78 -0
- package/dist/scheduling/constraints/rest-days.d.ts +30 -0
- package/dist/scheduling/constraints/rest-days.d.ts.map +1 -0
- package/dist/scheduling/constraints/rest-days.js +133 -0
- package/dist/scheduling/constraints/rolling-hours.d.ts +24 -0
- package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -0
- package/dist/scheduling/constraints/rolling-hours.js +147 -0
- package/dist/scheduling/constraints/start-interval.d.ts +20 -0
- package/dist/scheduling/constraints/start-interval.d.ts.map +1 -0
- package/dist/scheduling/constraints/start-interval.js +53 -0
- package/dist/scheduling/constraints/support.d.ts +48 -0
- package/dist/scheduling/constraints/support.d.ts.map +1 -0
- package/dist/scheduling/constraints/support.js +97 -0
- package/dist/scheduling/constraints/time-off.d.ts +7 -0
- package/dist/scheduling/constraints/time-off.d.ts.map +1 -0
- package/dist/scheduling/constraints/time-off.js +42 -0
- package/dist/scheduling/constraints/weekly-rest.d.ts +22 -0
- package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -0
- package/dist/scheduling/constraints/weekly-rest.js +103 -0
- package/dist/scheduling/cost.d.ts +56 -0
- package/dist/scheduling/cost.d.ts.map +1 -0
- package/dist/scheduling/cost.js +120 -0
- package/dist/scheduling/engine/construction.d.ts +22 -0
- package/dist/scheduling/engine/construction.d.ts.map +1 -0
- package/dist/scheduling/engine/construction.js +104 -0
- package/dist/scheduling/engine/explain.d.ts +12 -0
- package/dist/scheduling/engine/explain.d.ts.map +1 -0
- package/dist/scheduling/engine/explain.js +24 -0
- package/dist/scheduling/engine/objective.d.ts +73 -0
- package/dist/scheduling/engine/objective.d.ts.map +1 -0
- package/dist/scheduling/engine/objective.js +164 -0
- package/dist/scheduling/engine/prng.d.ts +5 -0
- package/dist/scheduling/engine/prng.d.ts.map +1 -0
- package/dist/scheduling/engine/prng.js +24 -0
- package/dist/scheduling/engine/propagation.d.ts +19 -0
- package/dist/scheduling/engine/propagation.d.ts.map +1 -0
- package/dist/scheduling/engine/propagation.js +40 -0
- package/dist/scheduling/engine/search.d.ts +50 -0
- package/dist/scheduling/engine/search.d.ts.map +1 -0
- package/dist/scheduling/engine/search.js +127 -0
- package/dist/scheduling/engine/state.d.ts +28 -0
- package/dist/scheduling/engine/state.d.ts.map +1 -0
- package/dist/scheduling/engine/state.js +96 -0
- package/dist/scheduling/engine/timeline.d.ts +179 -0
- package/dist/scheduling/engine/timeline.d.ts.map +1 -0
- package/dist/scheduling/engine/timeline.js +416 -0
- package/dist/scheduling/engine/verdicts.d.ts +18 -0
- package/dist/scheduling/engine/verdicts.d.ts.map +1 -0
- package/dist/scheduling/engine/verdicts.js +74 -0
- package/dist/scheduling/index.d.ts +10 -0
- package/dist/scheduling/index.d.ts.map +1 -0
- package/dist/scheduling/index.js +29 -0
- package/dist/scheduling/model.d.ts +53 -0
- package/dist/scheduling/model.d.ts.map +1 -0
- package/dist/scheduling/model.js +380 -0
- package/dist/scheduling/operations.d.ts +134 -0
- package/dist/scheduling/operations.d.ts.map +1 -0
- package/dist/scheduling/operations.js +376 -0
- package/dist/scheduling/provenance.d.ts +33 -0
- package/dist/scheduling/provenance.d.ts.map +1 -0
- package/dist/scheduling/provenance.js +70 -0
- package/dist/scheduling/rules.d.ts +23 -0
- package/dist/scheduling/rules.d.ts.map +1 -0
- package/dist/scheduling/rules.js +37 -0
- package/dist/scheduling/scheduler.class.d.ts +24 -0
- package/dist/scheduling/scheduler.class.d.ts.map +1 -0
- package/dist/scheduling/scheduler.class.js +150 -0
- package/dist/scheduling/time.d.ts +138 -0
- package/dist/scheduling/time.d.ts.map +1 -0
- package/dist/scheduling/time.js +267 -0
- package/dist/scheduling/types.d.ts +938 -0
- package/dist/scheduling/types.d.ts.map +1 -0
- package/dist/scheduling/types.js +19 -0
- package/dist/types/matcher.d.ts +86 -2
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +1 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +6 -0
- package/package.json +4 -2
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()`.
|
|
@@ -385,6 +423,12 @@ The wait clock always survives an escalation: requeues go through `addAssignment
|
|
|
385
423
|
|
|
386
424
|
Subscribe via `onAssignmentLifecycle` for `escalated` (`{ fromWorkerId, level, blockedPreviousOwner }`) and `escalationExhausted` (`{ level, parked }`) events; `expired` is still emitted first, so existing consumers are unaffected. Parked assignments are reachable with `getParkedAssignments()`, returned to the queue with `unparkAssignment(id, { resetEscalation? })`, and report `_status: 'parked'` from `getAssignment()` — they never read as "not found". `getEscalationLevel(id)` reports how far an assignment has climbed.
|
|
387
425
|
|
|
426
|
+
#### `failed` — the worker-reported outcome
|
|
427
|
+
|
|
428
|
+
`failAssignment(userId, assignmentId, reason?)` now emits `{ kind: 'failed', taskId, workerId, reason?, failedAt }`. It previously emitted nothing at all, so an explicit failure was the one terminal transition invisible to `onAssignmentLifecycle` (the workflow event stream did hear it). It is deliberately distinct from `completionBreached` with `action: 'fail'`: that is a deadline a policy acted on, this is a person reporting that the work could not be done. No `assignment` snapshot rides along — the record stays in the completed store carrying `_failedBy` / `_failureReason`, so `getAssignment()` can still answer for it.
|
|
429
|
+
|
|
430
|
+
A host that `switch`es exhaustively over `AssignmentLifecycleEvent` will see a new `kind` here; the union is additive and every existing branch keeps its shape.
|
|
431
|
+
|
|
388
432
|
### SLA policies (`Assignment.sla`)
|
|
389
433
|
|
|
390
434
|
Escalation owns the _response_ side (how long a matched user has to accept). `SlaPolicy` owns everything after that: how long the accepting user has to finish, how many times the work may be refused before it is pulled from rotation, and an absolute freshness cutoff after which the work is moot.
|
|
@@ -459,7 +503,7 @@ Semantics worth knowing:
|
|
|
459
503
|
- **The offer deadline never extends.** `notAfter` is absolute, so rejection requeues carry the same deadline — a re-offered assignment can still miss.
|
|
460
504
|
- **Fire-once, replica-safe.** Sweep entries are claimed with a `ZREM` before acting, so concurrent replicas can run the sweep in parallel.
|
|
461
505
|
- **Sweep granularity.** Schedule clocks fire on the maintenance tick (`processScheduledAssignments()`), not at the exact millisecond.
|
|
462
|
-
- **Recurrence is out of scope.** Materialize each occurrence as its own assignment from your scheduler/shift tool; re-adding an existing id never resets its clocks, so materialization is idempotent.
|
|
506
|
+
- **Recurrence is out of scope.** Materialize each occurrence as its own assignment from your scheduler/shift tool; re-adding an existing id never resets its clocks, so materialization is idempotent. The [`scheduling` module](#shift-scheduling-scheduling-module) is that shift tool if you need one — it produces dated occurrences you can feed straight in.
|
|
463
507
|
- **Operator override.** `assignToUser(id, userId)` refuses held assignments; `{ force: true }` early-activates (clocks anchor there). If the user then rejects and `notBefore` is still in the future, the assignment returns to the scheduled store.
|
|
464
508
|
- **Unparking.** `unparkAssignment(id, { resetSchedule: true })` strips the schedule policy; without it a miss-parked assignment misses again on the next sweep.
|
|
465
509
|
|
|
@@ -992,11 +1036,11 @@ bandit policy.
|
|
|
992
1036
|
|
|
993
1037
|
- `policy: 'ucb1'` (default): high-mean tags get high weights, an exploration
|
|
994
1038
|
bonus favors less-sampled tags, and bad tags are hard-vetoed at weight `0`.
|
|
995
|
-
- `policy: 'confidence'`: uses upper-confidence-bound for the weight and
|
|
996
|
-
|
|
997
|
-
|
|
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.
|
|
998
1042
|
- `policy: 'thompson'`: samples from the per-tag posterior when mapping to a
|
|
999
|
-
weight.
|
|
1043
|
+
weight; the veto decision uses the deterministic mean, never the draw.
|
|
1000
1044
|
|
|
1001
1045
|
**Guardrails (all opt-in):**
|
|
1002
1046
|
|
|
@@ -1007,8 +1051,11 @@ bandit policy.
|
|
|
1007
1051
|
- `maxDeltaPerSync`: clamps how far any single learned weight can move per
|
|
1008
1052
|
sync, avoiding oscillation.
|
|
1009
1053
|
- `minTotalSamples`: skip users whose total evidence is still too thin.
|
|
1010
|
-
- `decayHalfLifeMs`: exponentially decay older observations
|
|
1011
|
-
|
|
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.
|
|
1012
1059
|
- `terminalOnlyTagStats`: when `true`, only terminal outcomes
|
|
1013
1060
|
(complete/reject/expire/fail plus manual rewards/feedback) feed tag stats;
|
|
1014
1061
|
the non-terminal `accept` update is skipped.
|
|
@@ -1055,6 +1102,14 @@ const wouldBe = await matcher.syncLearnedRoutingWeights('user-1', { dryRun: true
|
|
|
1055
1102
|
await matcher.revertLearnedRoutingWeights('user-1');
|
|
1056
1103
|
```
|
|
1057
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
|
+
|
|
1058
1113
|
Synthesis happens outside the matching hot path — matching itself reads the
|
|
1059
1114
|
user's stored `routingWeights` exactly as before, so the per-match cost is
|
|
1060
1115
|
unchanged. The last-applied learned map is stored on the user as
|
|
@@ -1491,6 +1546,105 @@ Performance test finished.
|
|
|
1491
1546
|
|
|
1492
1547
|
This demonstrates the library's impressive performance even with large numbers of assignments and shows how subsequent matching operations can be even faster after initial assignment distribution.
|
|
1493
1548
|
|
|
1549
|
+
## Shift Scheduling (`scheduling` module)
|
|
1550
|
+
|
|
1551
|
+
A companion engine for **rostering**: generating fair, constraint-compliant timetables that assign employees to shifts over a period. Unlike the matcher, this module is **pure and Redis-free** — `solveSchedule(input)` is a synchronous in-process function; wrap it in your own queue if you need one.
|
|
1552
|
+
|
|
1553
|
+
```ts
|
|
1554
|
+
import { solveSchedule } from 'assignment-user-matcher';
|
|
1555
|
+
|
|
1556
|
+
const result = solveSchedule({
|
|
1557
|
+
period: { startDate: '2026-01-05', endDate: '2026-01-11' },
|
|
1558
|
+
employees: [
|
|
1559
|
+
{ id: 'alice', tags: ['nurse'], timeOff: [{ date: '2026-01-07' }], maxHoursForPeriod: 40 },
|
|
1560
|
+
{ id: 'bob', tags: ['nurse', 'lead'], timeOff: [] },
|
|
1561
|
+
],
|
|
1562
|
+
shifts: [
|
|
1563
|
+
{ id: 'day', name: 'Day', startTime: '08:00', endTime: '16:00', minEmployees: 1, tagRequirements: { nurse: 1 } },
|
|
1564
|
+
{ id: 'night', name: 'Night', startTime: '22:00', endTime: '06:00', minEmployees: 1 }, // overnight
|
|
1565
|
+
],
|
|
1566
|
+
objective: 'balanced', // or 'standard'
|
|
1567
|
+
seed: 42, // reproducible runs
|
|
1568
|
+
timeBudgetMs: 10_000, // improvement-loop wall clock
|
|
1569
|
+
});
|
|
1570
|
+
|
|
1571
|
+
// result.status: 'optimal' | 'feasible' | 'partial'
|
|
1572
|
+
// result.assignments: [{ shiftInstanceId: 'day@2026-01-05', employeeId, date, reasons }]
|
|
1573
|
+
// result.violations: structured report of unfilled slots, tag shortfalls, soft min-hours misses
|
|
1574
|
+
```
|
|
1575
|
+
|
|
1576
|
+
Modeling rules: every shift occurrence gets a unique **shift-instance id** (`<templateId>@<date>`), overnight shifts (`endTime <= startTime`) roll into the next day explicitly, and durations are resolved through a **DST-correct clock** — pass `period.timeZone` and a 22:00–06:00 shift is 7h on the spring transition and 9h on the autumn one, not 8h. Working time is the span less `unpaidBreakMinutes`, scaled by any duty classification, so hour budgets see 8h15 for a 9h shift with a 45-minute break.
|
|
1577
|
+
|
|
1578
|
+
Constraints are self-contained TypeScript classes behind a common interface. Override hardness/weights or register customs via `constraints: { overrides, custom }`.
|
|
1579
|
+
|
|
1580
|
+
### Working-time rules
|
|
1581
|
+
|
|
1582
|
+
The `rules` field is the labour-law layer. Every field is optional and **every value is caller-supplied** — the library ships the _shapes_ EU working-time law takes, never a jurisdiction's numbers, because those differ per member state, per sector and per collective agreement, and change without notice. This is plain JSON, so a template or an LLM can produce it and the same payload can back a public API.
|
|
1583
|
+
|
|
1584
|
+
```ts
|
|
1585
|
+
const result = solveSchedule({
|
|
1586
|
+
period: { startDate: '2026-01-05', endDate: '2026-02-01', timeZone: 'Europe/Berlin' },
|
|
1587
|
+
employees,
|
|
1588
|
+
shifts,
|
|
1589
|
+
rules: {
|
|
1590
|
+
dailyRest: { minMinutes: 660 }, // Art 3 floor; ES/RO use 720
|
|
1591
|
+
weeklyRest: { minMinutes: 2100, windowDays: 7 }, // 35h; EE uses 2880
|
|
1592
|
+
workingTime: {
|
|
1593
|
+
maxPerDayMinutes: 600, // DE ArbZG §3
|
|
1594
|
+
rollingAverages: [{ maxMinutes: 2880, windowDays: 7 }], // 48h in ANY 7 days
|
|
1595
|
+
},
|
|
1596
|
+
nightWork: { window: { from: '23:00', to: '06:00' }, maxShiftMinutes: 480 },
|
|
1597
|
+
breaks: [
|
|
1598
|
+
{ afterMinutes: 360, minMinutes: 30 },
|
|
1599
|
+
{ afterMinutes: 540, minMinutes: 45 },
|
|
1600
|
+
],
|
|
1601
|
+
consecutive: { maxWorkingDays: 6, forbiddenSuccessions: [{ fromTag: 'night', toTag: 'early' }] },
|
|
1602
|
+
fairness: [
|
|
1603
|
+
{ dimension: 'nights', weight: 2 },
|
|
1604
|
+
{ dimension: 'weekends', weight: 1 },
|
|
1605
|
+
],
|
|
1606
|
+
},
|
|
1607
|
+
history, // previous-period tail, so the 1st of the month is not non-compliant by construction
|
|
1608
|
+
});
|
|
1609
|
+
```
|
|
1610
|
+
|
|
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.
|
|
1612
|
+
|
|
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.
|
|
1614
|
+
|
|
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.
|
|
1616
|
+
|
|
1617
|
+
**Overtime** is regulated separately from total working time where national law does so. `rules.overtime` defines the ordinary baseline (`ordinaryPerDayMinutes` / `ordinaryPerWeekMinutes`; a person's `contract.weeklyMinutes` overrides the weekly figure, so a part-timer's overtime starts at their agreed hours), caps the overtime portion per rolling 24h or per rolling window, and with `requiresConsent` makes any overtime conditional on the employee's recorded `overtimeConsent`. With `compensation: 'timeOff'`, each employee's period overtime accrues a `timeOffInLieu` entry in `result.ledger`.
|
|
1618
|
+
|
|
1619
|
+
**Duty-type quotas** (`rules.dutyQuotas`) cap how much of one duty type a person may hold over a rolling window, matched on `shiftTypeTag` — e.g. "at most 30 hours of stand-by in any 28 days". `maxMinutes` counts _elapsed_ duty minutes (a stand-by cap limits clock occupation, which is exactly the time a duty classification keeps out of the working-time budget); `maxCount` caps occurrences.
|
|
1620
|
+
|
|
1621
|
+
### Labour cost
|
|
1622
|
+
|
|
1623
|
+
`Employee.cost` prices the roster: hourly rate, premium bands (`night` / `sunday` / `holiday`, stacked additively or by maximum), an overtime step (`overtimeAfterMinutes` + `overtimeMultiplier`), and a `standbyRateFraction` paying the non-working remainder of a duty-classified span (e.g. stand-by owed at 1/10 of the wage). When any employee carries a cost model, `result.cost` reports `{ totalCents, byEmployee }`.
|
|
1624
|
+
|
|
1625
|
+
Cost joins the _solve_ objective only when asked: `objectives: { costWeightPerEuro: n }` adds a soft term of `n` points per euro, so the solver prefers cheaper rosters among otherwise-equal ones — and can never trade a legal breach or an unfilled slot for a saving, because score levels are lexicographic. The same arithmetic drives `repairSchedule`'s per-candidate `marginalCostCents` (which accounts for the overtime step, so the same shift is dearer in the hands of someone already at their threshold). Objective weights are hashed into `provenance.rulesHash` alongside the rules.
|
|
1626
|
+
|
|
1627
|
+
### Operational APIs
|
|
1628
|
+
|
|
1629
|
+
```ts
|
|
1630
|
+
checkCompliance(input, roster); // validate a hand-edited or externally-produced roster
|
|
1631
|
+
explainCandidate(input, who, shift); // every rule's verdict, with numbers
|
|
1632
|
+
repairSchedule(input, disruption, published); // minimal-perturbation re-plan + ranked candidates
|
|
1633
|
+
diagnoseInfeasibility(input); // why it cannot be solved, before solving
|
|
1634
|
+
```
|
|
1635
|
+
|
|
1636
|
+
`repairSchedule` is the call-in path: everything untouched is pinned, so you get a **diff** rather than an unrecognisable new roster, plus a ranked list of who can lawfully cover, each with compliance verdicts, marginal cost and a rationale. All four share the solver's constraint set — there is deliberately no second validation path.
|
|
1637
|
+
|
|
1638
|
+
### Compliance boundary
|
|
1639
|
+
|
|
1640
|
+
Ranking uses declared qualifications, contractual availability, legal limits, cost, and fairness debt computed from **realised** assignment counts. It never consumes reliability scores, no-show prediction, acceptance history or learned per-worker behaviour, and the module is not wired to the matcher's learning layer. Under AI Act Annex III point 4(b), allocating on individual behaviour or traits is high-risk, and the Art 6(3) narrow-task filter has an absolute carve-back for profiling — so that boundary is what keeps this a constraint solver. `result.provenance` records `{ engineVersion, seed, rulesHash, profilingFree }` for audit.
|
|
1641
|
+
|
|
1642
|
+
Infeasibility is never silent: understaffed periods return a best-effort partial schedule with `status: 'partial'`, an `unfilledSlots` count, and per-slot violations; slots with zero eligible employees are reported before the search runs. Violations carry `actual`, `required`, `unit` and `citation`. Malformed input throws `ScheduleValidationError`.
|
|
1643
|
+
|
|
1644
|
+
`'optimal'` means _no known improvement_, not a proof of optimality.
|
|
1645
|
+
|
|
1646
|
+
Scale (500 employees × 31 days × 3 shifts/day, full EU rule set — `pnpm benchmark:scheduling`): first feasible ~0.4s, converged within the time budget, compliance re-check ~0.1s, repair ~0.15s.
|
|
1647
|
+
|
|
1494
1648
|
## Important Considerations (Disclaimer)
|
|
1495
1649
|
|
|
1496
1650
|
- **Optimized for a Specific Use Case:** `assignment-user-matcher` is primarily designed and optimized for scenarios with a **relatively small set of active users processing a large volume of incoming assignments** (e.g., call centers, customer support teams, back-office operations). While it might work for other scenarios, its performance characteristics are best suited for this model.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
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';
|
|
6
6
|
export { extractMatchFeatures, cosineSimilarity } from './learning/features';
|
|
7
7
|
export { synthesizeRoutingWeights, DEFAULT_AUTO_WEIGHTS_OPTIONS } from './learning/auto-weights';
|
|
8
|
+
export { ShiftScheduler, solveSchedule, ScheduleValidationError, DEFAULT_MIN_REST_MINUTES, PeriodClock, checkCompliance, explainCandidate, repairSchedule, rankCandidates, diagnoseInfeasibility, hours, days, weeklyAverageOver, type AssignmentPair, type AvailabilityRule, type ComplianceReport, type ConstraintOptions, type ConstraintViolation, type DailyRestRule, type Disruption, type DutyClassification, type DutyQuota, type Employee, type HistoricalAssignment, type InfeasibilityReport, type LedgerEntry, type ModelContext, type NightWorkRule, type ObjectiveWeights, type OvertimeRule, type RepairCandidate, type RepairResult, type RuleVerdict, type ScheduleInput, type ScheduleResult, type ScheduledAssignment, type SchedulingConstraint, type SearchState, type Severity, type ShiftInstance, type ShiftTemplate, type TimeOffEntry, type WeeklyRestRule, type WorkingTimeLimits, type WorkingTimeRules, } from './scheduling';
|
|
8
9
|
export { WorkflowBuilder, WorkflowStepBuilder, workflow, linearWorkflow, approvalWorkflow } from './workflow-builder';
|
|
9
10
|
export { normalizeWorkflowDefinition, validateWorkflowDefinition } from './workflow-validation';
|
|
10
11
|
export * from './utils/cidr';
|
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,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,EACxB,gBAAgB,EAChB,qBAAqB,EACrB,6BAA6B,EAC7B,oBAAoB,EACpB,SAAS,EACT,QAAQ,EACR,cAAc,EACd,mBAAmB,EACnB,mBAAmB,EACnB,qBAAqB,EACrB,yBAAyB,EACzB,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,
|
|
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,E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,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -17,7 +17,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
17
17
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
18
18
|
};
|
|
19
19
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
-
exports.AssignmentMatcher = exports.createKeyBuilders = exports.validateWorkflowDefinition = exports.normalizeWorkflowDefinition = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = exports.synthesizeRoutingWeights = exports.cosineSimilarity = exports.extractMatchFeatures = exports.explainMatchScore = exports.userCoversTag = exports.lintAssignment = void 0;
|
|
20
|
+
exports.AssignmentMatcher = exports.createKeyBuilders = exports.validateWorkflowDefinition = exports.normalizeWorkflowDefinition = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = exports.weeklyAverageOver = exports.days = exports.hours = exports.diagnoseInfeasibility = exports.rankCandidates = exports.repairSchedule = exports.explainCandidate = exports.checkCompliance = exports.PeriodClock = exports.DEFAULT_MIN_REST_MINUTES = exports.ScheduleValidationError = exports.solveSchedule = exports.ShiftScheduler = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = exports.synthesizeRoutingWeights = exports.cosineSimilarity = exports.extractMatchFeatures = exports.explainMatchScore = exports.userCoversTag = exports.lintAssignment = void 0;
|
|
21
21
|
const matcher_class_1 = __importDefault(require("./matcher.class"));
|
|
22
22
|
exports.AssignmentMatcher = matcher_class_1.default;
|
|
23
23
|
// Pre-flight lint (pure, Redis-free) — usable host-side before addAssignment
|
|
@@ -35,6 +35,24 @@ Object.defineProperty(exports, "cosineSimilarity", { enumerable: true, get: func
|
|
|
35
35
|
var auto_weights_1 = require("./learning/auto-weights");
|
|
36
36
|
Object.defineProperty(exports, "synthesizeRoutingWeights", { enumerable: true, get: function () { return auto_weights_1.synthesizeRoutingWeights; } });
|
|
37
37
|
Object.defineProperty(exports, "DEFAULT_AUTO_WEIGHTS_OPTIONS", { enumerable: true, get: function () { return auto_weights_1.DEFAULT_AUTO_WEIGHTS_OPTIONS; } });
|
|
38
|
+
// Shift scheduling (pure, Redis-free rostering engine)
|
|
39
|
+
var scheduling_1 = require("./scheduling");
|
|
40
|
+
Object.defineProperty(exports, "ShiftScheduler", { enumerable: true, get: function () { return scheduling_1.ShiftScheduler; } });
|
|
41
|
+
Object.defineProperty(exports, "solveSchedule", { enumerable: true, get: function () { return scheduling_1.solveSchedule; } });
|
|
42
|
+
Object.defineProperty(exports, "ScheduleValidationError", { enumerable: true, get: function () { return scheduling_1.ScheduleValidationError; } });
|
|
43
|
+
Object.defineProperty(exports, "DEFAULT_MIN_REST_MINUTES", { enumerable: true, get: function () { return scheduling_1.DEFAULT_MIN_REST_MINUTES; } });
|
|
44
|
+
Object.defineProperty(exports, "PeriodClock", { enumerable: true, get: function () { return scheduling_1.PeriodClock; } });
|
|
45
|
+
// Operational APIs: validate a hand-edited roster, explain a candidate,
|
|
46
|
+
// repair around a call-in, diagnose an impossible problem.
|
|
47
|
+
Object.defineProperty(exports, "checkCompliance", { enumerable: true, get: function () { return scheduling_1.checkCompliance; } });
|
|
48
|
+
Object.defineProperty(exports, "explainCandidate", { enumerable: true, get: function () { return scheduling_1.explainCandidate; } });
|
|
49
|
+
Object.defineProperty(exports, "repairSchedule", { enumerable: true, get: function () { return scheduling_1.repairSchedule; } });
|
|
50
|
+
Object.defineProperty(exports, "rankCandidates", { enumerable: true, get: function () { return scheduling_1.rankCandidates; } });
|
|
51
|
+
Object.defineProperty(exports, "diagnoseInfeasibility", { enumerable: true, get: function () { return scheduling_1.diagnoseInfeasibility; } });
|
|
52
|
+
// Rule-authoring arithmetic (weekly-average → rolling-window-total, etc.)
|
|
53
|
+
Object.defineProperty(exports, "hours", { enumerable: true, get: function () { return scheduling_1.hours; } });
|
|
54
|
+
Object.defineProperty(exports, "days", { enumerable: true, get: function () { return scheduling_1.days; } });
|
|
55
|
+
Object.defineProperty(exports, "weeklyAverageOver", { enumerable: true, get: function () { return scheduling_1.weeklyAverageOver; } });
|
|
38
56
|
// Workflow builder DSL
|
|
39
57
|
var workflow_builder_1 = require("./workflow-builder");
|
|
40
58
|
Object.defineProperty(exports, "WorkflowBuilder", { enumerable: true, get: function () { return workflow_builder_1.WorkflowBuilder; } });
|
|
@@ -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
|
|
9
|
-
*
|
|
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
|
|
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,
|
|
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
|
-
|
|
144
|
-
|
|
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,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AAC;IA8CjE,wDAAwD;IAClD,gBAAgB,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAI3C;;;;;;;;OAQG;IACG,wBAAwB,CAC1B,MAAM,EAAE,MAAM,EACd,SAAS,CAAC,EAAE,MAAM,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.
|
|
@@ -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,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,kBAAkB,EACrB,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,O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