assignment-user-matcher 1.11.0 → 1.13.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.
@@ -13,6 +13,7 @@ const fair_arbitration_1 = require("./scoring/fair-arbitration");
13
13
  const policy_1 = require("./escalation/policy");
14
14
  const policy_2 = require("./sla/policy");
15
15
  const policy_3 = require("./schedule/policy");
16
+ const recurrence_1 = require("./schedule/recurrence");
16
17
  const assignment_lint_1 = require("./validation/assignment-lint");
17
18
  const decision_trace_1 = require("./tracing/decision-trace");
18
19
  const features_1 = require("./learning/features");
@@ -38,6 +39,10 @@ function loadLuaScript(filename) {
38
39
  }
39
40
  // Lua script for atomic workflow transitions
40
41
  const WORKFLOW_TRANSITION_LUA = loadLuaScript('workflow-transition.lua');
42
+ // Retention purges are capped per maintenance pass so enabling retention on a
43
+ // deployment with a large historical completed store drains it across ticks
44
+ // instead of one deletion storm.
45
+ const RETENTION_PURGE_BATCH = 5000;
41
46
  class AssignmentMatcher {
42
47
  constructor(redisClient, options) {
43
48
  this.redisClient = redisClient;
@@ -62,6 +67,11 @@ class AssignmentMatcher {
62
67
  this.maxUserBacklogSize = options?.maxUserBacklogSize ?? 9;
63
68
  this.matchExpirationMs = options?.matchExpirationMs ?? 60000;
64
69
  this.idleUserTimeoutMs = options?.idleUserTimeoutMs ?? null;
70
+ const completedRetentionMs = options?.completedAssignmentsRetentionMs;
71
+ this.completedAssignmentsRetentionMs =
72
+ completedRetentionMs !== undefined && Number.isFinite(completedRetentionMs) && completedRetentionMs > 0
73
+ ? completedRetentionMs
74
+ : null;
65
75
  this.pendingAssignmentsKey = this.keys.pendingAssignmentsData();
66
76
  this.pendingAssignmentsExpiryKey = this.keys.pendingAssignmentsExpiry();
67
77
  this.assignmentOwnerKey = this.keys.assignmentOwner();
@@ -72,7 +82,10 @@ class AssignmentMatcher {
72
82
  this.scheduledAssignmentsKey = this.keys.scheduledAssignments();
73
83
  this.scheduledActivateAtKey = this.keys.scheduledActivateAt();
74
84
  this.scheduleNotAfterKey = this.keys.scheduleNotAfter();
85
+ this.recurringAssignmentsKey = this.keys.recurringAssignments();
86
+ this.recurringDueAtKey = this.keys.recurringDueAt();
75
87
  this.completedAssignmentsKey = this.keys.completedAssignments();
88
+ this.completedAssignmentsAtKey = this.keys.completedAssignmentsAt();
76
89
  this.calculatePriority = options?.prioritizationFunction ?? this.calculatePriority;
77
90
  this.usingDefaultMatchScore = !options?.matchingFunction;
78
91
  this.matchScore = options?.matchingFunction ?? this.defaultMatchScore.bind(this);
@@ -142,6 +155,7 @@ class AssignmentMatcher {
142
155
  reclaimIntervalMs: options?.workflowReclaimPollIntervalMs ?? 5000,
143
156
  reclaimMinIdleMs: options?.workflowOrphanReclaimMs ?? 60000,
144
157
  retentionMs: options?.workflowInstanceRetentionMs,
158
+ autoTrimEventStream: options?.workflowEventStreamAutoTrim,
145
159
  retryBackoffMs: options?.workflowRetryBackoffMs,
146
160
  eventBatchSize: options?.workflowEventBatchSize,
147
161
  pollBlockMs: options?.workflowPollBlockMs,
@@ -1757,7 +1771,11 @@ class AssignmentMatcher {
1757
1771
  continue;
1758
1772
  const score = expiryScores[i];
1759
1773
  const expiresAt = score === null || score === undefined ? null : Number(score);
1760
- const pendingSince = expiresAt === null ? null : expiresAt - this.matchExpirationMs;
1774
+ // The expiry score was written as claimAt + the assignment's own
1775
+ // response deadline (escalation.respondWithinMs, falling back to
1776
+ // matchExpirationMs) — deriving pendingSince from anything else
1777
+ // mis-ages every escalating assignment.
1778
+ const pendingSince = expiresAt === null ? null : expiresAt - (0, policy_1.responseDeadlineFromJson)(json, this.matchExpirationMs);
1761
1779
  const pendingForMs = pendingSince === null ? null : Math.max(0, now - pendingSince);
1762
1780
  metas.push({ json, ownerId: owners[i] ?? null, pendingForMs, pendingSince, expiresAt });
1763
1781
  }
@@ -1801,6 +1819,57 @@ class AssignmentMatcher {
1801
1819
  results.sort((a, b) => (b.pendingForMs ?? -1) - (a.pendingForMs ?? -1));
1802
1820
  return results;
1803
1821
  }
1822
+ /**
1823
+ * List terminal assignments from the completed store (both completions and
1824
+ * failures — they share the store, distinguished by the `_status` stamp:
1825
+ * `_completedBy`/`_completedAt` vs `_failedBy`/`_failedAt`). Cursor-paged
1826
+ * over HSCAN. The store is pruned only when
1827
+ * `completedAssignmentsRetentionMs` is set; pagination is best-effort
1828
+ * under a concurrent purge — the cursor is a positional offset over scan
1829
+ * order, so entries deleted between pages can shift what a later page
1830
+ * returns. Loop until `hasMore` is false and re-page if completeness
1831
+ * matters.
1832
+ */
1833
+ async getCompletedAssignments(options) {
1834
+ await this.readyPromise;
1835
+ const limit = Math.max(1, Math.min(Math.floor(options?.limit ?? 100) || 100, 1000));
1836
+ const offset = Math.max(0, parseInt(options?.cursor ?? '0', 10) || 0);
1837
+ const assignments = [];
1838
+ const seen = new Set();
1839
+ let scanned = 0;
1840
+ let hasMore = false;
1841
+ let cursor = '0';
1842
+ do {
1843
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.completedAssignmentsKey, cursor, {
1844
+ COUNT: Math.max(limit, 100),
1845
+ });
1846
+ cursor = nextCursor;
1847
+ for (const entry of entries) {
1848
+ // HSCAN may repeat a field across pages under a concurrent rehash.
1849
+ if (seen.has(entry.field))
1850
+ continue;
1851
+ seen.add(entry.field);
1852
+ if (scanned < offset) {
1853
+ scanned++;
1854
+ continue;
1855
+ }
1856
+ if (assignments.length >= limit) {
1857
+ hasMore = true;
1858
+ break;
1859
+ }
1860
+ scanned++;
1861
+ try {
1862
+ const assignment = JSON.parse(entry.value);
1863
+ assignment._status = assignment._failedAt !== undefined ? 'failed' : 'completed';
1864
+ assignments.push(assignment);
1865
+ }
1866
+ catch {
1867
+ // Skip corrupt entries (same precedent as the pending listing).
1868
+ }
1869
+ }
1870
+ } while (cursor !== '0' && !hasMore);
1871
+ return { assignments, nextCursor: hasMore ? String(scanned) : null, hasMore };
1872
+ }
1804
1873
  /** Default match score implementation using extracted scoring module */
1805
1874
  defaultMatchScore(user, assignmentTags, assignmentPriority, _assignmentId, skillThresholds) {
1806
1875
  return Promise.resolve((0, match_score_1.calculateMatchScore)(user, assignmentTags, assignmentPriority, this.enableDefaultMatching, skillThresholds));
@@ -2961,6 +3030,7 @@ class AssignmentMatcher {
2961
3030
  _failedAt: now,
2962
3031
  _failureReason: `rejection-budget-exhausted:${cause}`,
2963
3032
  }));
3033
+ multi.zAdd(this.completedAssignmentsAtKey, { score: now, value: assignment.id });
2964
3034
  }
2965
3035
  await multi.exec();
2966
3036
  this.emitAssignmentLifecycle({
@@ -3008,6 +3078,8 @@ class AssignmentMatcher {
3008
3078
  _result: result,
3009
3079
  };
3010
3080
  multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(completedData));
3081
+ // Retention index: the sweep reads only entries past the window.
3082
+ multi.zAdd(this.completedAssignmentsAtKey, { score: now, value: assignmentId });
3011
3083
  await multi.exec();
3012
3084
  if (json.indexOf('"sla"') !== -1) {
3013
3085
  await this.recordSlaComplete(json, now);
@@ -3063,6 +3135,7 @@ class AssignmentMatcher {
3063
3135
  _failureReason: reason,
3064
3136
  };
3065
3137
  multi.hSet(this.completedAssignmentsKey, assignmentId, JSON.stringify(failedData));
3138
+ multi.zAdd(this.completedAssignmentsAtKey, { score: now, value: assignmentId });
3066
3139
  await multi.exec();
3067
3140
  if (this.enableLearning) {
3068
3141
  await this.learning.applyOutcome(assignmentId, 'fail');
@@ -3217,6 +3290,17 @@ class AssignmentMatcher {
3217
3290
  await this.readyPromise;
3218
3291
  return this.workflow.publishWorkflowEvent(event);
3219
3292
  }
3293
+ /**
3294
+ * Trim the workflow event stream up to the consumption frontier — every
3295
+ * entry delivered *and* acknowledged by every consumer group. Never trims
3296
+ * ahead of consumers, so no event can be lost to trimming. Runs
3297
+ * automatically after event processing and on the reclaim interval when
3298
+ * `workflowEventStreamAutoTrim` is set; callable directly otherwise.
3299
+ */
3300
+ async trimWorkflowEventStream() {
3301
+ await this.readyPromise;
3302
+ return this.workflow.trimWorkflowEventStream();
3303
+ }
3220
3304
  /**
3221
3305
  * Start the workflow orchestrator.
3222
3306
  * This listens to the event stream and processes workflow transitions.
@@ -3475,6 +3559,7 @@ class AssignmentMatcher {
3475
3559
  _failedAt: now,
3476
3560
  _failureReason: 'completion-sla-breach',
3477
3561
  }))
3562
+ .zAdd(this.completedAssignmentsAtKey, { score: now, value: id })
3478
3563
  // Terminal: the freshness TTL no longer applies.
3479
3564
  .zRem(this.assignmentsSlaExpiryKey, id);
3480
3565
  if (workerId)
@@ -3706,6 +3791,181 @@ class AssignmentMatcher {
3706
3791
  const all = await this.redisClient.hGetAll(this.scheduledAssignmentsKey);
3707
3792
  return Object.values(all).map((json) => JSON.parse(json));
3708
3793
  }
3794
+ // ============================================================================
3795
+ // Recurring assignments — standing templates the sweep cuts occurrences from
3796
+ // ============================================================================
3797
+ /**
3798
+ * Register (or update) a recurring assignment: a standing template whose
3799
+ * recurrence sweep materializes each occurrence as an ordinary scheduled
3800
+ * assignment (id `<templateId>@<openEpochMs>`, offer window derived from
3801
+ * the policy). The template itself is never matchable.
3802
+ *
3803
+ * Re-adding an existing id replaces the template but keeps its clock —
3804
+ * occurrences already materialized and the next slot are facts about the
3805
+ * past, not properties of the template. Remove and re-add to restart.
3806
+ *
3807
+ * Occurrences fire with sweep granularity: `startMaintenance()` /
3808
+ * `runMaintenanceOnce()` / `processRecurringAssignments()`.
3809
+ *
3810
+ * @throws when `recurrence` is unusable (`everyMs` missing or < 1000,
3811
+ * or `until` before `startAt`)
3812
+ */
3813
+ async addRecurringAssignment(template) {
3814
+ await this.readyPromise;
3815
+ const policy = (0, recurrence_1.normalizeRecurrencePolicy)(template.recurrence);
3816
+ if (!policy) {
3817
+ throw new Error(`addRecurringAssignment: recurrence needs everyMs >= ${recurrence_1.MIN_EVERY_MS} and a satisfiable until/startAt`);
3818
+ }
3819
+ const existingJson = await this.redisClient.hGet(this.recurringAssignmentsKey, template.id);
3820
+ const existing = existingJson ? JSON.parse(existingJson) : null;
3821
+ const record = {
3822
+ template,
3823
+ nextAt: existing?.nextAt ?? policy.startAt ?? Date.now(),
3824
+ occurrences: existing?.occurrences ?? 0,
3825
+ };
3826
+ await this.redisClient
3827
+ .multi()
3828
+ .hSet(this.recurringAssignmentsKey, template.id, JSON.stringify(record))
3829
+ .zAdd(this.recurringDueAtKey, { score: (0, recurrence_1.sweepDueAt)(record, policy), value: template.id })
3830
+ .exec();
3831
+ return template;
3832
+ }
3833
+ /**
3834
+ * Remove a recurring template: no further occurrences materialize.
3835
+ * Occurrences already cut from it are ordinary assignments and live on —
3836
+ * `dropScheduled: true` additionally removes the ones still sitting
3837
+ * un-activated in the scheduled store (never queued/pending/accepted
3838
+ * work).
3839
+ *
3840
+ * @returns false when the id was not a recurring template
3841
+ */
3842
+ async removeRecurringAssignment(id, opts) {
3843
+ await this.readyPromise;
3844
+ const [removed] = (await this.redisClient
3845
+ .multi()
3846
+ .hDel(this.recurringAssignmentsKey, id)
3847
+ .zRem(this.recurringDueAtKey, id)
3848
+ .exec());
3849
+ if (opts?.dropScheduled) {
3850
+ const prefix = `${id}@`;
3851
+ const scheduledIds = await this.redisClient.hKeys(this.scheduledAssignmentsKey);
3852
+ for (const occId of scheduledIds) {
3853
+ if (!occId.startsWith(prefix))
3854
+ continue;
3855
+ await this.redisClient
3856
+ .multi()
3857
+ .hDel(this.scheduledAssignmentsKey, occId)
3858
+ .zRem(this.scheduledActivateAtKey, occId)
3859
+ .zRem(this.scheduleNotAfterKey, occId)
3860
+ .exec();
3861
+ }
3862
+ }
3863
+ return Number(removed) === 1;
3864
+ }
3865
+ /** One recurring template with its clock, or null. */
3866
+ async getRecurringAssignment(id) {
3867
+ await this.readyPromise;
3868
+ const json = await this.redisClient.hGet(this.recurringAssignmentsKey, id);
3869
+ return json ? JSON.parse(json) : null;
3870
+ }
3871
+ /** Every recurring template with its clock, soonest next occurrence first. */
3872
+ async listRecurringAssignments() {
3873
+ await this.readyPromise;
3874
+ const all = await this.redisClient.hGetAll(this.recurringAssignmentsKey);
3875
+ return Object.values(all)
3876
+ .map((json) => JSON.parse(json))
3877
+ .sort((a, b) => a.nextAt - b.nextAt);
3878
+ }
3879
+ /**
3880
+ * Sweep the recurring templates: materialize every due slot (one interval
3881
+ * ahead of its open time, so the next occurrence is visible in the
3882
+ * scheduled store before its window opens) and retire templates whose
3883
+ * bound (`until` / `maxOccurrences`) is reached.
3884
+ *
3885
+ * Claims are one-shot zRems like the scheduled sweep, so concurrent
3886
+ * replicas skip templates another sweep already took. A crashed pass is
3887
+ * healed two ways: the due index is re-derived from the template hash at
3888
+ * the top of every sweep (missing entries re-indexed as due now, NX so a
3889
+ * live score is never clobbered), and occurrence ids are deterministic,
3890
+ * so re-materializing a slot that already landed is an idempotent re-add.
3891
+ */
3892
+ async processRecurringAssignments() {
3893
+ await this.readyPromise;
3894
+ const now = Date.now();
3895
+ let materialized = 0;
3896
+ let retired = 0;
3897
+ // Self-heal: a template whose sweep crashed between the claim and the
3898
+ // state write has no due-index entry and nothing else re-examines it.
3899
+ const [templateIds, indexedIds] = await Promise.all([
3900
+ this.redisClient.hKeys(this.recurringAssignmentsKey),
3901
+ this.redisClient.zRange(this.recurringDueAtKey, 0, -1),
3902
+ ]);
3903
+ const indexed = new Set(indexedIds);
3904
+ const orphaned = templateIds.filter((id) => !indexed.has(id));
3905
+ if (orphaned.length > 0) {
3906
+ await this.redisClient.zAdd(this.recurringDueAtKey, orphaned.map((id) => ({ score: now, value: id })), { NX: true });
3907
+ }
3908
+ const dueIds = await this.redisClient.zRangeByScore(this.recurringDueAtKey, '-inf', now);
3909
+ for (const id of dueIds) {
3910
+ const claimed = await this.redisClient.zRem(this.recurringDueAtKey, id);
3911
+ if (!claimed)
3912
+ continue;
3913
+ const json = await this.redisClient.hGet(this.recurringAssignmentsKey, id);
3914
+ // Removed since the range read: the claim was the whole cleanup.
3915
+ if (!json)
3916
+ continue;
3917
+ const record = JSON.parse(json);
3918
+ const policy = (0, recurrence_1.normalizeRecurrencePolicy)(record.template.recurrence);
3919
+ if (!policy) {
3920
+ // A stored record that no longer normalizes (hand-edited, or a
3921
+ // future field contract change): leave the hash entry readable
3922
+ // but inert rather than deleting data or looping on it.
3923
+ continue;
3924
+ }
3925
+ const { slots, next, retiredReason } = (0, recurrence_1.dueSlots)(policy, record, now);
3926
+ try {
3927
+ for (const [index, openAt] of slots.entries()) {
3928
+ await this.addAssignment((0, recurrence_1.materializeOccurrence)(record.template, policy, openAt));
3929
+ materialized++;
3930
+ this.emitAssignmentLifecycle({
3931
+ kind: 'recurrenceMaterialized',
3932
+ taskId: (0, recurrence_1.occurrenceId)(record.template.id, openAt),
3933
+ recurringId: id,
3934
+ occurrence: record.occurrences + index + 1,
3935
+ opensAt: openAt,
3936
+ at: now,
3937
+ });
3938
+ }
3939
+ }
3940
+ catch (err) {
3941
+ // The claim already consumed the only trigger and the state is
3942
+ // deliberately not advanced yet; restore the claim so the next
3943
+ // sweep retries. Slots that did land re-add idempotently.
3944
+ await this.redisClient.zAdd(this.recurringDueAtKey, { score: now, value: id });
3945
+ throw err;
3946
+ }
3947
+ if (retiredReason) {
3948
+ await this.redisClient.hDel(this.recurringAssignmentsKey, id);
3949
+ retired++;
3950
+ this.emitAssignmentLifecycle({
3951
+ kind: 'recurrenceRetired',
3952
+ recurringId: id,
3953
+ reason: retiredReason,
3954
+ occurrences: next.occurrences,
3955
+ at: now,
3956
+ });
3957
+ }
3958
+ else {
3959
+ const updated = { ...record, ...next };
3960
+ await this.redisClient
3961
+ .multi()
3962
+ .hSet(this.recurringAssignmentsKey, id, JSON.stringify(updated))
3963
+ .zAdd(this.recurringDueAtKey, { score: (0, recurrence_1.sweepDueAt)(updated, policy), value: id })
3964
+ .exec();
3965
+ }
3966
+ }
3967
+ return { materialized, retired };
3968
+ }
3709
3969
  /**
3710
3970
  * Return a parked assignment to the queue, optionally resetting its
3711
3971
  * escalation level so the ladder can run again from the top.
@@ -3752,6 +4012,73 @@ class AssignmentMatcher {
3752
4012
  const assignment = await this.getAssignment(id);
3753
4013
  return assignment ? (0, policy_1.escalationLevelOf)(assignment) : 0;
3754
4014
  }
4015
+ /**
4016
+ * Purge terminal assignments older than `completedAssignmentsRetentionMs`.
4017
+ *
4018
+ * The completed store has no expiry of its own — an accepted assignment's
4019
+ * deadlines all die at accept — so without this sweep it grows forever on
4020
+ * busy deployments. The terminal-timestamp index (`completedAssignmentsAt`,
4021
+ * written atomically with each completed hSet) keeps the steady-state pass
4022
+ * O(eligible) — the same shape as every other deadline sweep — and purges
4023
+ * are capped per pass, so enabling retention on a deployment with a large
4024
+ * historical store drains it across ticks instead of in one deletion
4025
+ * storm. The window applies retroactively: pre-existing records older
4026
+ * than it are purged too. Entries without a terminal timestamp
4027
+ * (externally injected or corrupt) are never indexed and never deleted.
4028
+ * No-op, reporting zero, when no retention window is configured.
4029
+ */
4030
+ async processCompletedAssignmentsRetention() {
4031
+ await this.readyPromise;
4032
+ const retentionMs = this.completedAssignmentsRetentionMs;
4033
+ if (retentionMs === null)
4034
+ return { purged: 0 };
4035
+ await this.backfillCompletedRetentionIndex();
4036
+ const cutoff = Date.now() - retentionMs;
4037
+ const stale = await this.redisClient.zRangeByScore(this.completedAssignmentsAtKey, '-inf', cutoff, {
4038
+ LIMIT: { offset: 0, count: RETENTION_PURGE_BATCH },
4039
+ });
4040
+ if (stale.length === 0)
4041
+ return { purged: 0 };
4042
+ await this.redisClient
4043
+ .multi()
4044
+ .hDel(this.completedAssignmentsKey, stale)
4045
+ .zRem(this.completedAssignmentsAtKey, stale)
4046
+ .exec();
4047
+ return { purged: stale.length };
4048
+ }
4049
+ /**
4050
+ * One-shot migration for entries written before the terminal-timestamp
4051
+ * index existed (same pattern as `backfillWorkflowIndexes()`): a single
4052
+ * full HSCAN pass indexes them, then the marker key makes the pass never
4053
+ * run again. Entries without a terminal timestamp stay unindexed — and
4054
+ * therefore never purgeable — by design.
4055
+ */
4056
+ async backfillCompletedRetentionIndex() {
4057
+ if (Number(await this.redisClient.exists(this.keys.completedRetentionIndexed())))
4058
+ return;
4059
+ const multi = this.redisClient.multi();
4060
+ let cursor = '0';
4061
+ do {
4062
+ const { cursor: nextCursor, entries } = await this.redisClient.hScan(this.completedAssignmentsKey, cursor, {
4063
+ COUNT: 500,
4064
+ });
4065
+ cursor = nextCursor;
4066
+ for (const entry of entries) {
4067
+ try {
4068
+ const parsed = JSON.parse(entry.value);
4069
+ const terminalAt = Number(parsed._completedAt ?? parsed._failedAt);
4070
+ if (Number.isFinite(terminalAt) && terminalAt > 0) {
4071
+ multi.zAdd(this.completedAssignmentsAtKey, { score: terminalAt, value: entry.field });
4072
+ }
4073
+ }
4074
+ catch {
4075
+ // Corrupt entries are not the sweep's to index or delete.
4076
+ }
4077
+ }
4078
+ } while (cursor !== '0');
4079
+ multi.set(this.keys.completedRetentionIndexed(), '1');
4080
+ await multi.exec();
4081
+ }
3755
4082
  /**
3756
4083
  * Run every enabled maintenance sweep once: response deadlines and
3757
4084
  * escalations, workflow step timeouts, and idle-user release.
@@ -3774,6 +4101,16 @@ class AssignmentMatcher {
3774
4101
  let slaExpiries = 0;
3775
4102
  let scheduleActivations = 0;
3776
4103
  let scheduleMisses = 0;
4104
+ let recurrenceMaterializations = 0;
4105
+ let recurrenceRetirements = 0;
4106
+ let retentionPurged = 0;
4107
+ // Recurrence before schedule: an occurrence materialized due-now is
4108
+ // then activated by the schedule sweep in this same tick.
4109
+ if (opts.recurrence) {
4110
+ const result = await this.processRecurringAssignments();
4111
+ recurrenceMaterializations = result.materialized;
4112
+ recurrenceRetirements = result.retired;
4113
+ }
3777
4114
  // Schedule first: a just-activated assignment's response/SLA clocks
3778
4115
  // then start from this same tick's state.
3779
4116
  if (opts.scheduled) {
@@ -3799,6 +4136,9 @@ class AssignmentMatcher {
3799
4136
  if (opts.idleUsers && this.idleUserTimeoutMs !== null) {
3800
4137
  releasedIdleUsers = (await this.processIdleUsers()).length;
3801
4138
  }
4139
+ if (opts.completedRetention && this.completedAssignmentsRetentionMs !== null) {
4140
+ retentionPurged = (await this.processCompletedAssignmentsRetention()).purged;
4141
+ }
3802
4142
  return {
3803
4143
  expiredMatches,
3804
4144
  escalations,
@@ -3809,6 +4149,9 @@ class AssignmentMatcher {
3809
4149
  slaExpiries,
3810
4150
  scheduleActivations,
3811
4151
  scheduleMisses,
4152
+ recurrenceMaterializations,
4153
+ recurrenceRetirements,
4154
+ retentionPurged,
3812
4155
  tookMs: Date.now() - startedAt,
3813
4156
  };
3814
4157
  }
@@ -3854,8 +4197,10 @@ class AssignmentMatcher {
3854
4197
  completionDeadlines: options?.completionDeadlines ?? true,
3855
4198
  slaExpiries: options?.slaExpiries ?? true,
3856
4199
  scheduled: options?.scheduled ?? true,
4200
+ recurrence: options?.recurrence ?? true,
3857
4201
  workflowStepTimeouts: options?.workflowStepTimeouts ?? this.enableWorkflows,
3858
4202
  idleUsers: options?.idleUsers ?? this.idleUserTimeoutMs !== null,
4203
+ completedRetention: options?.completedRetention ?? this.completedAssignmentsRetentionMs !== null,
3859
4204
  };
3860
4205
  }
3861
4206
  /** @deprecated Use `startMaintenance()`, which also sweeps workflow step timeouts. */
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Recurrence policy — pure logic.
3
+ *
4
+ * A recurring assignment is a standing template; the sweep in
5
+ * `AssignmentMatcher.processRecurringAssignments()` owns the Redis writes,
6
+ * this module owns the decisions: which slots are due, what the next clock
7
+ * state is, and when a template retires.
8
+ *
9
+ * Slots are aligned to `startAt + k × everyMs` and never drift: the sweep
10
+ * cadence decides *when* a slot is noticed, never *where* it sits. The sweep
11
+ * materializes one interval ahead (`horizon = now + everyMs`), so the next
12
+ * occurrence exists as a scheduled assignment before its window opens.
13
+ */
14
+ import type { Assignment, RecurrencePolicy, RecurringAssignment } from '../types/matcher';
15
+ /** A policy with every optional field resolved. */
16
+ export interface NormalizedRecurrencePolicy {
17
+ everyMs: number;
18
+ startAt?: number;
19
+ windowMs?: number;
20
+ onMiss: 'park' | 'drop';
21
+ until?: number;
22
+ maxOccurrences?: number;
23
+ catchUp: 'skip' | 'all';
24
+ }
25
+ /** The template's clock, as stored alongside it. */
26
+ export interface RecurrenceState {
27
+ /** Epoch ms the next occurrence's window opens */
28
+ nextAt: number;
29
+ /** Occurrences materialized so far */
30
+ occurrences: number;
31
+ }
32
+ /** Sub-second intervals are a runaway queue, not a schedule. */
33
+ export declare const MIN_EVERY_MS = 1000;
34
+ /**
35
+ * Ceiling on slots one sweep may emit for one template. Only reachable under
36
+ * `catchUp: 'all'` after downtime spanning many intervals — the remainder
37
+ * materializes on subsequent sweeps (the state only advances past what was
38
+ * emitted), so nothing is lost, just paced.
39
+ */
40
+ export declare const MAX_SLOTS_PER_SWEEP = 200;
41
+ /**
42
+ * Resolve a recurrence policy, or `null` when it is unusable. Unlike
43
+ * `normalizeSchedulePolicy` (where an absent policy is the common case and
44
+ * null routes to the legacy path), a null here is a caller error —
45
+ * `addRecurringAssignment` refuses it rather than storing a template that
46
+ * can never fire.
47
+ */
48
+ export declare function normalizeRecurrencePolicy(policy: RecurrencePolicy | undefined | null): NormalizedRecurrencePolicy | null;
49
+ /**
50
+ * Deterministic occurrence id: template id + the slot's open time. What makes
51
+ * a crashed sweep's re-materialization an idempotent re-add rather than a
52
+ * duplicate, and what lets a host trace any occurrence back to its template
53
+ * without extra state.
54
+ */
55
+ export declare function occurrenceId(recurringId: string, openAt: number): string;
56
+ /**
57
+ * Which slots one sweep should materialize, and the clock state afterwards.
58
+ *
59
+ * `retiredReason` is non-null when the template is finished *after* this
60
+ * batch — the final slots are still returned, so a `maxOccurrences: 3`
61
+ * template materializes exactly three and then retires.
62
+ */
63
+ export declare function dueSlots(policy: NormalizedRecurrencePolicy, state: RecurrenceState, now: number): {
64
+ slots: number[];
65
+ next: RecurrenceState;
66
+ retiredReason: 'until' | 'maxOccurrences' | null;
67
+ };
68
+ /**
69
+ * Cut one occurrence from the template: everything the template carries,
70
+ * with the generated id and the slot's own offer window. A past slot's
71
+ * `notBefore` falls straight through `addAssignment`'s hold guard into the
72
+ * normal enqueue, notAfter clock intact — which is exactly what a due
73
+ * occurrence should do.
74
+ */
75
+ export declare function materializeOccurrence(template: RecurringAssignment, policy: NormalizedRecurrencePolicy, openAt: number): Assignment;
76
+ /**
77
+ * When the sweep should next act on this template: one interval before the
78
+ * next occurrence opens, so it is already sitting in the scheduled store
79
+ * (visible to hosts) when its window arrives.
80
+ */
81
+ export declare function sweepDueAt(state: RecurrenceState, policy: NormalizedRecurrencePolicy): number;
82
+ //# sourceMappingURL=recurrence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recurrence.d.ts","sourceRoot":"","sources":["../../src/schedule/recurrence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,mBAAmB,EAAkB,MAAM,kBAAkB,CAAC;AAE1G,mDAAmD;AACnD,MAAM,WAAW,0BAA0B;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;IACxB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,OAAO,EAAE,MAAM,GAAG,KAAK,CAAC;CAC3B;AAED,oDAAoD;AACpD,MAAM,WAAW,eAAe;IAC5B,kDAAkD;IAClD,MAAM,EAAE,MAAM,CAAC;IACf,sCAAsC;IACtC,WAAW,EAAE,MAAM,CAAC;CACvB;AAED,gEAAgE;AAChE,eAAO,MAAM,YAAY,OAAO,CAAC;AAEjC;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,MAAM,CAAC;AAOvC;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,gBAAgB,GAAG,SAAS,GAAG,IAAI,GAAG,0BAA0B,GAAG,IAAI,CAsBxH;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAExE;AAED;;;;;;GAMG;AACH,wBAAgB,QAAQ,CACpB,MAAM,EAAE,0BAA0B,EAClC,KAAK,EAAE,eAAe,EACtB,GAAG,EAAE,MAAM,GACZ;IAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAAC,IAAI,EAAE,eAAe,CAAC;IAAC,aAAa,EAAE,OAAO,GAAG,gBAAgB,GAAG,IAAI,CAAA;CAAE,CAyC9F;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACjC,QAAQ,EAAE,mBAAmB,EAC7B,MAAM,EAAE,0BAA0B,EAClC,MAAM,EAAE,MAAM,GACf,UAAU,CAUZ;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,0BAA0B,GAAG,MAAM,CAE7F"}