assignment-user-matcher 1.10.0 → 1.12.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 +106 -13
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -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 +84 -3
- package/dist/matcher.class.d.ts.map +1 -1
- package/dist/matcher.class.js +498 -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/schedule/recurrence.d.ts +82 -0
- package/dist/schedule/recurrence.d.ts.map +1 -0
- package/dist/schedule/recurrence.js +145 -0
- package/dist/scheduling/constraints/availability.d.ts +0 -1
- package/dist/scheduling/constraints/availability.d.ts.map +1 -1
- package/dist/scheduling/constraints/availability.js +27 -4
- package/dist/scheduling/constraints/contract.d.ts.map +1 -1
- package/dist/scheduling/constraints/contract.js +17 -3
- package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -1
- package/dist/scheduling/constraints/daily-rest.js +7 -2
- package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -1
- package/dist/scheduling/constraints/hour-budget.js +7 -1
- package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -1
- package/dist/scheduling/constraints/in-shift-breaks.js +4 -2
- package/dist/scheduling/constraints/min-rest.d.ts.map +1 -1
- package/dist/scheduling/constraints/min-rest.js +8 -19
- package/dist/scheduling/constraints/night-work.js +17 -1
- package/dist/scheduling/constraints/no-overlap.d.ts +5 -1
- package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -1
- package/dist/scheduling/constraints/no-overlap.js +11 -12
- package/dist/scheduling/constraints/weekly-rest.js +12 -1
- package/dist/scheduling/engine/construction.d.ts.map +1 -1
- package/dist/scheduling/engine/construction.js +7 -0
- package/dist/scheduling/model.d.ts.map +1 -1
- package/dist/scheduling/model.js +1 -0
- package/dist/scheduling/time.d.ts +6 -0
- package/dist/scheduling/time.d.ts.map +1 -1
- package/dist/scheduling/time.js +20 -9
- package/dist/scheduling/types.d.ts +6 -0
- package/dist/scheduling/types.d.ts.map +1 -1
- package/dist/types/matcher.d.ts +197 -5
- package/dist/types/matcher.d.ts.map +1 -1
- package/dist/utils/keys.d.ts +3 -0
- package/dist/utils/keys.d.ts.map +1 -1
- package/dist/utils/keys.js +17 -0
- 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()`.
|
|
@@ -465,7 +503,7 @@ Semantics worth knowing:
|
|
|
465
503
|
- **The offer deadline never extends.** `notAfter` is absolute, so rejection requeues carry the same deadline — a re-offered assignment can still miss.
|
|
466
504
|
- **Fire-once, replica-safe.** Sweep entries are claimed with a `ZREM` before acting, so concurrent replicas can run the sweep in parallel.
|
|
467
505
|
- **Sweep granularity.** Schedule clocks fire on the maintenance tick (`processScheduledAssignments()`), not at the exact millisecond.
|
|
468
|
-
- **
|
|
506
|
+
- **One policy, one window.** Repeating work is a [recurring assignment](#recurring-assignments-addrecurringassignment): a standing template whose sweep materializes each occurrence as an ordinary scheduled assignment carrying a derived policy. (Hand-materializing occurrences from your own scheduler still works — re-adding an existing id never resets its clocks, so materialization is idempotent — and the [`scheduling` module](#shift-scheduling-scheduling-module) produces dated occurrences you can feed straight in.)
|
|
469
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.
|
|
470
508
|
- **Unparking.** `unparkAssignment(id, { resetSchedule: true })` strips the schedule policy; without it a miss-parked assignment misses again on the next sweep.
|
|
471
509
|
|
|
@@ -475,18 +513,62 @@ Lifecycle events: `scheduleActivated` (`{ taskId, at }`) and `scheduleMissed` (`
|
|
|
475
513
|
|
|
476
514
|
**Learning integration.** Misses feed the contextual bandit as `expire` outcomes — a pending-state miss penalizes the user who sat on the offer, so automatic routing-weight vetoes pick up chronic missers with no extra configuration.
|
|
477
515
|
|
|
516
|
+
### Recurring assignments (`addRecurringAssignment`)
|
|
517
|
+
|
|
518
|
+
A recurring assignment is a **standing template**, never itself matchable: the recurrence sweep cuts each occurrence from it as an ordinary assignment whose `schedule` is derived from the policy (`notBefore` = the slot's open time, `notAfter` = open + `windowMs`). Everything else the template carries — tags, priority, SLA, escalation, vetoes, geo — is inherited by every occurrence.
|
|
519
|
+
|
|
520
|
+
```ts
|
|
521
|
+
await matcher.addRecurringAssignment({
|
|
522
|
+
id: 'blog-draft',
|
|
523
|
+
tags: ['blog'],
|
|
524
|
+
recurrence: {
|
|
525
|
+
everyMs: 14 * 24 * 3600_000, // biweekly
|
|
526
|
+
startAt: Date.parse('2026-09-07T09:00:00Z'), // first window opens here (default: now)
|
|
527
|
+
windowMs: 3 * 24 * 3600_000, // each occurrence offered for 3 days
|
|
528
|
+
onMiss: 'park', // an unserved window parks the occurrence for inspection
|
|
529
|
+
},
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
matcher.startMaintenance(); // the recurrence sweep rides the maintenance tick
|
|
533
|
+
```
|
|
534
|
+
|
|
535
|
+
| Field | Meaning | Default |
|
|
536
|
+
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------- |
|
|
537
|
+
| `everyMs` | Interval between window opens. Minimum 1000 | required |
|
|
538
|
+
| `startAt` | Epoch ms the first window opens | now |
|
|
539
|
+
| `windowMs` | Offer window per occurrence (`schedule.notAfter = open + windowMs`). Omitted: occurrences never expire off the offer clock | none |
|
|
540
|
+
| `onMiss` | Per-occurrence miss policy, as in `SchedulePolicy` | `'park'` |
|
|
541
|
+
| `until` | No occurrence opens after this epoch ms; the template retires | none |
|
|
542
|
+
| `maxOccurrences` | Retire after this many occurrences materialized | none |
|
|
543
|
+
| `catchUp` | Downtime policy: `'skip'` materializes only slots whose window is still open; `'all'` materializes every elapsed slot (audit trail) | `'skip'` |
|
|
544
|
+
|
|
545
|
+
Semantics worth knowing:
|
|
546
|
+
|
|
547
|
+
- **Occurrence ids are deterministic** — `<templateId>@<openEpochMs>` — so a crashed sweep re-materializing a slot is an idempotent re-add, and any occurrence traces back to its template with no extra state.
|
|
548
|
+
- **Slots never drift.** They align to `startAt + k × everyMs` whatever the sweep cadence; the tick decides when a slot is _noticed_, never where it sits.
|
|
549
|
+
- **One occurrence ahead.** The sweep materializes each occurrence one interval before its window opens, so upcoming work is already visible in the scheduled store (`getScheduledAssignments()`, `getQueueStats().scheduled`).
|
|
550
|
+
- **Skipped slots are free.** Under `catchUp: 'skip'`, slots that fully elapsed during downtime never existed: they don't count against `maxOccurrences` and don't flood the queue on revival. Under `'all'` they materialize and are immediately missed by the schedule sweep (parked/dropped per `onMiss`) — the audit-trail reading of a dead interval.
|
|
551
|
+
- **Re-adding updates the template, not the clock.** Occurrences already cut and the next slot are facts about the past; remove and re-add to restart.
|
|
552
|
+
- **Removal is forward-looking.** `removeRecurringAssignment(id)` stops future occurrences; already-materialized ones live on as ordinary assignments. `{ dropScheduled: true }` additionally clears occurrences still held un-activated in the scheduled store — never queued, pending, or accepted work.
|
|
553
|
+
- **Fire-once, replica-safe, self-healing.** Sweep claims are one-shot `ZREM`s like the scheduled sweep; the due index is re-derived from the template store at the top of every pass, so a crashed sweep can strand nothing.
|
|
554
|
+
|
|
555
|
+
API: `addRecurringAssignment(template)` · `removeRecurringAssignment(id, { dropScheduled? })` · `getRecurringAssignment(id)` / `listRecurringAssignments()` (each returns `{ template, nextAt, occurrences }`) · `processRecurringAssignments()` (manual sweep; also runs on the maintenance tick as `recurrence`, default on).
|
|
556
|
+
|
|
557
|
+
Lifecycle events: `recurrenceMaterialized` (`{ taskId, recurringId, occurrence, opensAt, at }` — hosts that keep per-task context copy it template → occurrence on this event) and `recurrenceRetired` (`{ recurringId, reason, occurrences, at }`).
|
|
558
|
+
|
|
478
559
|
### `startMaintenance(options?)` / `stopMaintenance()` / `runMaintenanceOnce(options?)`
|
|
479
560
|
|
|
480
561
|
Deadlines are not self-firing — something has to sweep them. `startMaintenance()` runs every enabled sweep on one tick:
|
|
481
562
|
|
|
482
|
-
- `
|
|
563
|
+
- `recurrence` (default on) — recurring-assignment materialization. Runs first so a due-now occurrence flows recurrence → schedule → queue inside one tick.
|
|
564
|
+
- `scheduled` (default on) — schedule activations and offer-window misses (`schedule.notBefore` / `schedule.notAfter`). Runs before the deadline sweeps so a just-activated assignment's other clocks start from the same tick.
|
|
483
565
|
- `responseDeadlines` (default on) — expiry, escalation, parking.
|
|
484
566
|
- `completionDeadlines` (default on) — SLA completion deadlines (`sla.completeWithinMs`).
|
|
485
567
|
- `slaExpiries` (default on) — SLA freshness TTLs (`sla.expireAfterMs`).
|
|
486
568
|
- `workflowStepTimeouts` (default on when `enableWorkflows`) — the step-timeout index. **Note:** `startOrchestrator()` consumes the event stream but does not sweep step timeouts; without maintenance, `timeoutMs` on a workflow step never fires.
|
|
487
569
|
- `idleUsers` (default on when `idleUserTimeoutMs` is set).
|
|
488
570
|
|
|
489
|
-
`runMaintenanceOnce()` does one pass and returns a `MaintenanceReport` (`expiredMatches`, `escalations`, `parked`, `completionBreaches`, `slaExpiries`, `scheduleActivations`, `scheduleMisses`, `expiredSteps`, `releasedIdleUsers`, `tookMs`) — use it from a host that already owns a tick (a multi-tenant worker, a serverless schedule) instead of holding a timer per matcher. `startAutoReleaseInterval()` remains as a deprecated alias that sweeps response deadlines only.
|
|
571
|
+
`runMaintenanceOnce()` does one pass and returns a `MaintenanceReport` (`expiredMatches`, `escalations`, `parked`, `completionBreaches`, `slaExpiries`, `scheduleActivations`, `scheduleMisses`, `recurrenceMaterializations`, `recurrenceRetirements`, `expiredSteps`, `releasedIdleUsers`, `tookMs`) — use it from a host that already owns a tick (a multi-tenant worker, a serverless schedule) instead of holding a timer per matcher. `startAutoReleaseInterval()` remains as a deprecated alias that sweeps response deadlines only.
|
|
490
572
|
|
|
491
573
|
### `getQueueStats(): Promise<QueueStats>`
|
|
492
574
|
|
|
@@ -998,11 +1080,11 @@ bandit policy.
|
|
|
998
1080
|
|
|
999
1081
|
- `policy: 'ucb1'` (default): high-mean tags get high weights, an exploration
|
|
1000
1082
|
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
|
|
1002
|
-
|
|
1003
|
-
|
|
1083
|
+
- `policy: 'confidence'`: uses upper-confidence-bound for the weight and for
|
|
1084
|
+
the veto decision — a tag is hard-vetoed only when the whole confidence
|
|
1085
|
+
interval sits below the threshold, so uncertainty alone never excludes.
|
|
1004
1086
|
- `policy: 'thompson'`: samples from the per-tag posterior when mapping to a
|
|
1005
|
-
weight.
|
|
1087
|
+
weight; the veto decision uses the deterministic mean, never the draw.
|
|
1006
1088
|
|
|
1007
1089
|
**Guardrails (all opt-in):**
|
|
1008
1090
|
|
|
@@ -1013,8 +1095,11 @@ bandit policy.
|
|
|
1013
1095
|
- `maxDeltaPerSync`: clamps how far any single learned weight can move per
|
|
1014
1096
|
sync, avoiding oscillation.
|
|
1015
1097
|
- `minTotalSamples`: skip users whose total evidence is still too thin.
|
|
1016
|
-
- `decayHalfLifeMs`: exponentially decay older observations
|
|
1017
|
-
|
|
1098
|
+
- `decayHalfLifeMs`: exponentially decay older observations so stale history
|
|
1099
|
+
cannot veto a user's improving skills. The decay is applied at write time
|
|
1100
|
+
(old mass is rescaled before each new outcome lands, atomically in Redis)
|
|
1101
|
+
and continues on read, so a single fresh outcome re-weights the stats
|
|
1102
|
+
toward recent behavior instead of resurrecting decayed history.
|
|
1018
1103
|
- `terminalOnlyTagStats`: when `true`, only terminal outcomes
|
|
1019
1104
|
(complete/reject/expire/fail plus manual rewards/feedback) feed tag stats;
|
|
1020
1105
|
the non-terminal `accept` update is skipped.
|
|
@@ -1061,6 +1146,14 @@ const wouldBe = await matcher.syncLearnedRoutingWeights('user-1', { dryRun: true
|
|
|
1061
1146
|
await matcher.revertLearnedRoutingWeights('user-1');
|
|
1062
1147
|
```
|
|
1063
1148
|
|
|
1149
|
+
Two safety properties of the sync: a user's **declared tags always stay
|
|
1150
|
+
matchable** — a declared tag with no recorded outcomes gets the exploration
|
|
1151
|
+
prior rather than silently dropping out of the installed `routingWeights` —
|
|
1152
|
+
and the pre-sync state is always restorable: a user who had no
|
|
1153
|
+
`routingWeights` at all is snapshotted as such (`routingWeightsSnapshot:
|
|
1154
|
+
null`), so `revertLearnedRoutingWeights()` returns them to plain tag-based
|
|
1155
|
+
matching.
|
|
1156
|
+
|
|
1064
1157
|
Synthesis happens outside the matching hot path — matching itself reads the
|
|
1065
1158
|
user's stored `routingWeights` exactly as before, so the per-match cost is
|
|
1066
1159
|
unchanged. The last-applied learned map is stored on the user as
|
|
@@ -1561,7 +1654,7 @@ const result = solveSchedule({
|
|
|
1561
1654
|
|
|
1562
1655
|
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
1656
|
|
|
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.
|
|
1657
|
+
`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
1658
|
|
|
1566
1659
|
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
1660
|
|
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, RecurrencePolicy, RecurringAssignment, RecurringAssignmentRecord, RecurrenceSweepResult, 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';
|
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,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,gBAAgB,EAChB,mBAAmB,EACnB,yBAAyB,EACzB,qBAAqB,EACrB,mBAAmB,EACnB,qBAAqB,EACrB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AK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EACxB,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,KAAK,kBAAkB,EACvB,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,WAAW,EAChB,KAAK,QAAQ,EACb,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,GACxB,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,QAAQ,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtH,OAAO,EAAE,2BAA2B,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAGhG,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAExF,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
|
|
@@ -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,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGjD,eAAO,MAAM,wBAAwB,EAAE,eAMtC,CAAC;AAKF,MAAM,WAAW,sBAAsB;IACnC,uCAAuC;IACvC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,sDAAsD;IACtD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,6EAA6E;IAC7E,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,0EAA0E;IAC1E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,4CAA4C;IAC5C,OAAO,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;IACnC,+DAA+D;IAC/D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,6EAA6E;IAC7E,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,mFAAmF;IACnF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,0FAA0F;IAC1F,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,oDAAoD;IACpD,WAAW,CAAC,EAAE,yBAAyB,CAAC;CAC3C;
|
|
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,MAAM,wBAAwB,EAAE,eAMtC,CAAC;AAKF,MAAM,WAAW,sBAAsB;IACnC,uCAAuC;IACvC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,sDAAsD;IACtD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,6EAA6E;IAC7E,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,0EAA0E;IAC1E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,4CAA4C;IAC5C,OAAO,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;IACnC,+DAA+D;IAC/D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,6EAA6E;IAC7E,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,mFAAmF;IACnF,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,0FAA0F;IAC1F,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,oDAAoD;IACpD,WAAW,CAAC,EAAE,yBAAyB,CAAC;CAC3C;AA2BD,qBAAa,eAAe;IAapB,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,IA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
|
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,OAAO,mCAAuB,CAAC;AAE9C,MAAM,WAAW,YAAY;IACzB,aAAa,CAAC,UAAU,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IAC3D,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IACpD,kBAAkB,CAAC,CAAC,IAAI,EAAE;QACtB,QAAQ,EAAE,gBAAgB,CAAC;QAC3B,IAAI,EAAE,YAAY,CAAC;QACnB,UAAU,EAAE,kBAAkB,CAAC;KAClC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;IACxC,2GAA2G;IAC3G,UAAU,CAAC,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC9C,kHAAkH;IAClH,gBAAgB,CAA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