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.
Files changed (54) hide show
  1. package/README.md +106 -13
  2. package/dist/index.d.ts +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/learning/auto-weights.d.ts +7 -4
  5. package/dist/learning/auto-weights.d.ts.map +1 -1
  6. package/dist/learning/auto-weights.js +7 -6
  7. package/dist/lua/workflow-transition.lua +8 -2
  8. package/dist/managers/LearningManager.d.ts.map +1 -1
  9. package/dist/managers/LearningManager.js +47 -0
  10. package/dist/managers/WorkflowManager.d.ts +7 -1
  11. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  12. package/dist/managers/WorkflowManager.js +85 -12
  13. package/dist/matcher.class.d.ts +84 -3
  14. package/dist/matcher.class.d.ts.map +1 -1
  15. package/dist/matcher.class.js +498 -76
  16. package/dist/queries/users.d.ts +34 -0
  17. package/dist/queries/users.d.ts.map +1 -0
  18. package/dist/queries/users.js +227 -0
  19. package/dist/schedule/recurrence.d.ts +82 -0
  20. package/dist/schedule/recurrence.d.ts.map +1 -0
  21. package/dist/schedule/recurrence.js +145 -0
  22. package/dist/scheduling/constraints/availability.d.ts +0 -1
  23. package/dist/scheduling/constraints/availability.d.ts.map +1 -1
  24. package/dist/scheduling/constraints/availability.js +27 -4
  25. package/dist/scheduling/constraints/contract.d.ts.map +1 -1
  26. package/dist/scheduling/constraints/contract.js +17 -3
  27. package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -1
  28. package/dist/scheduling/constraints/daily-rest.js +7 -2
  29. package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -1
  30. package/dist/scheduling/constraints/hour-budget.js +7 -1
  31. package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -1
  32. package/dist/scheduling/constraints/in-shift-breaks.js +4 -2
  33. package/dist/scheduling/constraints/min-rest.d.ts.map +1 -1
  34. package/dist/scheduling/constraints/min-rest.js +8 -19
  35. package/dist/scheduling/constraints/night-work.js +17 -1
  36. package/dist/scheduling/constraints/no-overlap.d.ts +5 -1
  37. package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -1
  38. package/dist/scheduling/constraints/no-overlap.js +11 -12
  39. package/dist/scheduling/constraints/weekly-rest.js +12 -1
  40. package/dist/scheduling/engine/construction.d.ts.map +1 -1
  41. package/dist/scheduling/engine/construction.js +7 -0
  42. package/dist/scheduling/model.d.ts.map +1 -1
  43. package/dist/scheduling/model.js +1 -0
  44. package/dist/scheduling/time.d.ts +6 -0
  45. package/dist/scheduling/time.d.ts.map +1 -1
  46. package/dist/scheduling/time.js +20 -9
  47. package/dist/scheduling/types.d.ts +6 -0
  48. package/dist/scheduling/types.d.ts.map +1 -1
  49. package/dist/types/matcher.d.ts +197 -5
  50. package/dist/types/matcher.d.ts.map +1 -1
  51. package/dist/utils/keys.d.ts +3 -0
  52. package/dist/utils/keys.d.ts.map +1 -1
  53. package/dist/utils/keys.js +17 -0
  54. package/package.json +1 -1
@@ -0,0 +1,34 @@
1
+ /**
2
+ * User status & workload query helpers: paginated user scans with
3
+ * status/backlog filters, batch summaries, and per-user accepted-work reads.
4
+ *
5
+ * All reads are bounded: the users hash is paged with HSCAN, per-page reads
6
+ * are batched into a single multi(), and JSON.parse is always guarded.
7
+ */
8
+ import type { KeyBuilders } from '../utils/keys';
9
+ import type { RedisClientType, User, ActiveAssignmentInfo, UserQueryOptions, UserQueryResult, UserSummary } from '../matcher.class';
10
+ /**
11
+ * Effective backlog cap for one user. Injected by the facade because the pure
12
+ * module cannot see the matcher-wide default (`backlogLimitFor` is private).
13
+ */
14
+ export type MaxBacklogSizeFor = (user: User) => number;
15
+ /**
16
+ * Paginated user scan with composable filters. The cursor is an opaque HSCAN
17
+ * cursor — pass `nextCursor` back verbatim. Because a scan page is never
18
+ * split mid-way, a returned page may exceed `limit` by less than one scan
19
+ * page, and filtered scans may return fewer than `limit` users while
20
+ * `hasMore` is still true; keep consuming until `hasMore` is false.
21
+ */
22
+ export declare function getUsersPaginatedFromStore(redisClient: RedisClientType, keys: KeyBuilders, options: UserQueryOptions | undefined, maxBacklogSizeFor: MaxBacklogSizeFor): Promise<UserQueryResult>;
23
+ /**
24
+ * Order-preserving batch summary read. Missing users are omitted (mirrors
25
+ * getAssignmentsByIds). Chunked multi() keeps pipelines bounded.
26
+ */
27
+ export declare function getUserSummariesBatch(redisClient: RedisClientType, keys: KeyBuilders, userIds: string[], maxBacklogSizeFor: MaxBacklogSizeFor): Promise<UserSummary[]>;
28
+ /**
29
+ * A user's accepted (in-progress) assignments, newest first. Verified against
30
+ * the accepted hash: members orphaned by a missed index removal are dropped
31
+ * from the result and self-healed with a zRem.
32
+ */
33
+ export declare function getActiveAssignmentsFromStore(redisClient: RedisClientType, keys: KeyBuilders, userId: string): Promise<ActiveAssignmentInfo[]>;
34
+ //# sourceMappingURL=users.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"users.d.ts","sourceRoot":"","sources":["../../src/queries/users.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EACR,eAAe,EACf,IAAI,EACJ,oBAAoB,EACpB,gBAAgB,EAChB,eAAe,EACf,WAAW,EACd,MAAM,kBAAkB,CAAC;AAY1B;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG,CAAC,IAAI,EAAE,IAAI,KAAK,MAAM,CAAC;AAiBvD;;;;;;GAMG;AACH,wBAAsB,0BAA0B,CAC5C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,gBAAgB,GAAG,SAAS,EACrC,iBAAiB,EAAE,iBAAiB,GACrC,OAAO,CAAC,eAAe,CAAC,CAiI1B;AAED;;;GAGG;AACH,wBAAsB,qBAAqB,CACvC,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,MAAM,EAAE,EACjB,iBAAiB,EAAE,iBAAiB,GACrC,OAAO,CAAC,WAAW,EAAE,CAAC,CAyCxB;AAED;;;;GAIG;AACH,wBAAsB,6BAA6B,CAC/C,WAAW,EAAE,eAAe,EAC5B,IAAI,EAAE,WAAW,EACjB,MAAM,EAAE,MAAM,GACf,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAuBjC"}
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getActiveAssignmentsFromStore = exports.getUserSummariesBatch = exports.getUsersPaginatedFromStore = void 0;
4
+ /** HSCAN page hint, matching the matcher-wide convention. */
5
+ const USER_SCAN_COUNT = 500;
6
+ /** Hard ceiling for a single user-query page. */
7
+ const MAX_USER_QUERY_LIMIT = 1000;
8
+ const DEFAULT_USER_QUERY_LIMIT = 100;
9
+ /** Chunk size for batched multi() reads. */
10
+ const MULTI_CHUNK_SIZE = 500;
11
+ /** Backlog set members are stored as `assignment:{id}`. */
12
+ const BACKLOG_MEMBER_PREFIX = 'assignment:';
13
+ function clampLimit(limit) {
14
+ if (typeof limit !== 'number' || !Number.isFinite(limit))
15
+ return DEFAULT_USER_QUERY_LIMIT;
16
+ return Math.max(1, Math.min(Math.floor(limit), MAX_USER_QUERY_LIMIT));
17
+ }
18
+ /**
19
+ * Paginated user scan with composable filters. The cursor is an opaque HSCAN
20
+ * cursor — pass `nextCursor` back verbatim. Because a scan page is never
21
+ * split mid-way, a returned page may exceed `limit` by less than one scan
22
+ * page, and filtered scans may return fewer than `limit` users while
23
+ * `hasMore` is still true; keep consuming until `hasMore` is false.
24
+ */
25
+ async function getUsersPaginatedFromStore(redisClient, keys, options, maxBacklogSizeFor) {
26
+ const limit = clampLimit(options?.limit);
27
+ const status = options?.status ?? 'all';
28
+ const hasBacklog = options?.hasBacklog ?? false;
29
+ const atCapacity = options?.atCapacity ?? false;
30
+ const includeAssignments = options?.includeAssignments ?? false;
31
+ // Idle predicate: needs a threshold. 'idle' status without one matches
32
+ // nobody (the facade substitutes idleUserTimeoutMs when configured).
33
+ const idleForMs = options?.idleForMs;
34
+ const idleCutoff = typeof idleForMs === 'number' && Number.isFinite(idleForMs) ? Date.now() - idleForMs : null;
35
+ const idleFilterActive = idleCutoff !== null;
36
+ const idleRequired = status === 'idle';
37
+ // The paused pool is small by design: one read per call, not per user.
38
+ const pausedMembers = new Set(await redisClient.sMembers(keys.pausedUsers()));
39
+ const matches = [];
40
+ let cursor = options?.cursor ?? '0';
41
+ do {
42
+ const { cursor: nextCursor, entries } = await redisClient.hScan(keys.users(), cursor, {
43
+ // Adapt the hint to what's still needed, floored at 100 (don't
44
+ // dribble) and capped at the scan-page convention.
45
+ COUNT: Math.max(Math.min(limit - matches.length, USER_SCAN_COUNT), 100),
46
+ });
47
+ cursor = nextCursor;
48
+ // Cheap pre-filter on fields already in hand (status), so the
49
+ // pipelined reads below only run for survivors.
50
+ const page = [];
51
+ for (const entry of entries) {
52
+ let user;
53
+ try {
54
+ user = JSON.parse(entry.value);
55
+ }
56
+ catch {
57
+ // Skip corrupt entries (same precedent as getAllAssignmentsFromStores)
58
+ continue;
59
+ }
60
+ const paused = pausedMembers.has(user.id);
61
+ if (status === 'paused' && !paused)
62
+ continue;
63
+ if (status === 'active' && paused)
64
+ continue;
65
+ page.push({ user, paused });
66
+ }
67
+ if (page.length > 0) {
68
+ // One multi() per page: backlog depth, activity score, accepted count.
69
+ const multi = redisClient.multi();
70
+ for (const { user } of page) {
71
+ multi.sCard(keys.userAssignments(user.id));
72
+ multi.zScore(keys.userActivity(), user.id);
73
+ multi.zCard(keys.userAcceptedAssignments(user.id));
74
+ }
75
+ const results = (await multi.exec());
76
+ for (let i = 0; i < page.length; i++) {
77
+ const { user, paused } = page[i];
78
+ const backlog = Number(results[i * 3] ?? 0);
79
+ const activityScore = results[i * 3 + 1];
80
+ const lastActiveAt = activityScore === null || activityScore === undefined ? null : Number(activityScore);
81
+ const acceptedCount = Number(results[i * 3 + 2] ?? 0);
82
+ const maxBacklogSize = maxBacklogSizeFor(user);
83
+ const entry = {
84
+ user,
85
+ paused,
86
+ backlog,
87
+ lastActiveAt,
88
+ acceptedCount,
89
+ maxBacklogSize,
90
+ atCapacity: backlog >= maxBacklogSize,
91
+ };
92
+ // Users with no recorded activity are not idle: idleness needs
93
+ // a reference point (addUser touches on creation, so null only
94
+ // appears for externally-written records).
95
+ const idle = entry.lastActiveAt !== null && idleCutoff !== null && entry.lastActiveAt <= idleCutoff;
96
+ if ((idleRequired || idleFilterActive) && !idle)
97
+ continue;
98
+ if (hasBacklog && entry.backlog === 0)
99
+ continue;
100
+ if (atCapacity && !entry.atCapacity)
101
+ continue;
102
+ matches.push(entry);
103
+ }
104
+ }
105
+ // A scan page is never split: stop only at a page boundary.
106
+ } while (matches.length < limit && cursor !== '0');
107
+ const hasMore = cursor !== '0';
108
+ const users = matches.map((entry) => ({
109
+ userId: entry.user.id,
110
+ user: entry.user,
111
+ paused: entry.paused,
112
+ lastActiveAt: entry.lastActiveAt,
113
+ backlog: entry.backlog,
114
+ acceptedCount: entry.acceptedCount,
115
+ maxBacklogSize: entry.maxBacklogSize,
116
+ atCapacity: entry.atCapacity,
117
+ }));
118
+ if (includeAssignments && matches.length > 0) {
119
+ // Per-user assignment ids for the returned page only, chunked.
120
+ for (let start = 0; start < matches.length; start += MULTI_CHUNK_SIZE) {
121
+ const chunk = matches.slice(start, start + MULTI_CHUNK_SIZE);
122
+ const multi = redisClient.multi();
123
+ for (const { user } of chunk) {
124
+ multi.sMembers(keys.userAssignments(user.id));
125
+ multi.zRange(keys.userAcceptedAssignments(user.id), 0, -1, { REV: true });
126
+ }
127
+ const results = (await multi.exec());
128
+ for (let i = 0; i < chunk.length; i++) {
129
+ const summary = users[start + i];
130
+ // Backlog members are `assignment:{id}`; accepted ids are raw.
131
+ // Accepted ids are NOT verified against the accepted hash here
132
+ // (a stale member may appear); getActiveAssignmentsForUser is
133
+ // the verified read.
134
+ summary.pendingAssignmentIds = (results[i * 2] ?? []).map((m) => m.slice(BACKLOG_MEMBER_PREFIX.length));
135
+ summary.acceptedAssignmentIds = results[i * 2 + 1] ?? [];
136
+ }
137
+ }
138
+ }
139
+ const result = {
140
+ users,
141
+ nextCursor: hasMore ? cursor : null,
142
+ hasMore,
143
+ };
144
+ if (options?.includeTotal) {
145
+ result.total = await redisClient.hLen(keys.users());
146
+ }
147
+ return result;
148
+ }
149
+ exports.getUsersPaginatedFromStore = getUsersPaginatedFromStore;
150
+ /**
151
+ * Order-preserving batch summary read. Missing users are omitted (mirrors
152
+ * getAssignmentsByIds). Chunked multi() keeps pipelines bounded.
153
+ */
154
+ async function getUserSummariesBatch(redisClient, keys, userIds, maxBacklogSizeFor) {
155
+ if (userIds.length === 0)
156
+ return [];
157
+ const summaries = [];
158
+ for (let start = 0; start < userIds.length; start += MULTI_CHUNK_SIZE) {
159
+ const chunk = userIds.slice(start, start + MULTI_CHUNK_SIZE);
160
+ const multi = redisClient.multi();
161
+ for (const userId of chunk) {
162
+ multi.hGet(keys.users(), userId);
163
+ multi.sIsMember(keys.pausedUsers(), userId);
164
+ multi.sCard(keys.userAssignments(userId));
165
+ multi.zCard(keys.userAcceptedAssignments(userId));
166
+ multi.zScore(keys.userActivity(), userId);
167
+ }
168
+ const results = (await multi.exec());
169
+ for (let i = 0; i < chunk.length; i++) {
170
+ const json = results[i * 5];
171
+ if (typeof json !== 'string')
172
+ continue; // missing user: omitted
173
+ let user;
174
+ try {
175
+ user = JSON.parse(json);
176
+ }
177
+ catch {
178
+ continue; // corrupt entry: omitted
179
+ }
180
+ const activityScore = results[i * 5 + 4];
181
+ const backlog = Number(results[i * 5 + 2] ?? 0);
182
+ const maxBacklogSize = maxBacklogSizeFor(user);
183
+ summaries.push({
184
+ userId: user.id,
185
+ user,
186
+ paused: Boolean(results[i * 5 + 1]),
187
+ lastActiveAt: activityScore === null || activityScore === undefined ? null : Number(activityScore),
188
+ backlog,
189
+ acceptedCount: Number(results[i * 5 + 3] ?? 0),
190
+ maxBacklogSize,
191
+ atCapacity: backlog >= maxBacklogSize,
192
+ });
193
+ }
194
+ }
195
+ return summaries;
196
+ }
197
+ exports.getUserSummariesBatch = getUserSummariesBatch;
198
+ /**
199
+ * A user's accepted (in-progress) assignments, newest first. Verified against
200
+ * the accepted hash: members orphaned by a missed index removal are dropped
201
+ * from the result and self-healed with a zRem.
202
+ */
203
+ async function getActiveAssignmentsFromStore(redisClient, keys, userId) {
204
+ const entries = await redisClient.zRangeWithScores(keys.userAcceptedAssignments(userId), 0, -1, { REV: true });
205
+ if (entries.length === 0)
206
+ return [];
207
+ const multi = redisClient.multi();
208
+ for (const entry of entries) {
209
+ multi.hGet(keys.acceptedAssignments(), entry.value);
210
+ }
211
+ const jsons = (await multi.exec());
212
+ const active = [];
213
+ const stale = [];
214
+ for (let i = 0; i < entries.length; i++) {
215
+ if (jsons[i]) {
216
+ active.push({ assignmentId: entries[i].value, acceptedAt: Number(entries[i].score) });
217
+ }
218
+ else {
219
+ stale.push(entries[i].value);
220
+ }
221
+ }
222
+ if (stale.length > 0) {
223
+ await redisClient.zRem(keys.userAcceptedAssignments(userId), stale);
224
+ }
225
+ return active;
226
+ }
227
+ exports.getActiveAssignmentsFromStore = getActiveAssignmentsFromStore;
@@ -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"}
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ /**
3
+ * Recurrence policy — pure logic.
4
+ *
5
+ * A recurring assignment is a standing template; the sweep in
6
+ * `AssignmentMatcher.processRecurringAssignments()` owns the Redis writes,
7
+ * this module owns the decisions: which slots are due, what the next clock
8
+ * state is, and when a template retires.
9
+ *
10
+ * Slots are aligned to `startAt + k × everyMs` and never drift: the sweep
11
+ * cadence decides *when* a slot is noticed, never *where* it sits. The sweep
12
+ * materializes one interval ahead (`horizon = now + everyMs`), so the next
13
+ * occurrence exists as a scheduled assignment before its window opens.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.sweepDueAt = exports.materializeOccurrence = exports.dueSlots = exports.occurrenceId = exports.normalizeRecurrencePolicy = exports.MAX_SLOTS_PER_SWEEP = exports.MIN_EVERY_MS = void 0;
17
+ /** Sub-second intervals are a runaway queue, not a schedule. */
18
+ exports.MIN_EVERY_MS = 1000;
19
+ /**
20
+ * Ceiling on slots one sweep may emit for one template. Only reachable under
21
+ * `catchUp: 'all'` after downtime spanning many intervals — the remainder
22
+ * materializes on subsequent sweeps (the state only advances past what was
23
+ * emitted), so nothing is lost, just paced.
24
+ */
25
+ exports.MAX_SLOTS_PER_SWEEP = 200;
26
+ function positiveInt(value) {
27
+ const n = Number(value);
28
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : undefined;
29
+ }
30
+ /**
31
+ * Resolve a recurrence policy, or `null` when it is unusable. Unlike
32
+ * `normalizeSchedulePolicy` (where an absent policy is the common case and
33
+ * null routes to the legacy path), a null here is a caller error —
34
+ * `addRecurringAssignment` refuses it rather than storing a template that
35
+ * can never fire.
36
+ */
37
+ function normalizeRecurrencePolicy(policy) {
38
+ if (!policy || typeof policy !== 'object')
39
+ return null;
40
+ const everyMs = positiveInt(policy.everyMs);
41
+ if (everyMs === undefined || everyMs < exports.MIN_EVERY_MS)
42
+ return null;
43
+ const startAt = positiveInt(policy.startAt);
44
+ const windowMs = positiveInt(policy.windowMs);
45
+ const until = positiveInt(policy.until);
46
+ const maxOccurrences = positiveInt(policy.maxOccurrences);
47
+ // A bound before the first slot can never admit an occurrence.
48
+ if (until !== undefined && startAt !== undefined && until < startAt)
49
+ return null;
50
+ return {
51
+ everyMs,
52
+ startAt,
53
+ windowMs,
54
+ onMiss: policy.onMiss === 'drop' ? 'drop' : 'park',
55
+ until,
56
+ maxOccurrences,
57
+ catchUp: policy.catchUp === 'all' ? 'all' : 'skip',
58
+ };
59
+ }
60
+ exports.normalizeRecurrencePolicy = normalizeRecurrencePolicy;
61
+ /**
62
+ * Deterministic occurrence id: template id + the slot's open time. What makes
63
+ * a crashed sweep's re-materialization an idempotent re-add rather than a
64
+ * duplicate, and what lets a host trace any occurrence back to its template
65
+ * without extra state.
66
+ */
67
+ function occurrenceId(recurringId, openAt) {
68
+ return `${recurringId}@${openAt}`;
69
+ }
70
+ exports.occurrenceId = occurrenceId;
71
+ /**
72
+ * Which slots one sweep should materialize, and the clock state afterwards.
73
+ *
74
+ * `retiredReason` is non-null when the template is finished *after* this
75
+ * batch — the final slots are still returned, so a `maxOccurrences: 3`
76
+ * template materializes exactly three and then retires.
77
+ */
78
+ function dueSlots(policy, state, now) {
79
+ const horizon = now + policy.everyMs;
80
+ let nextAt = state.nextAt;
81
+ let slots = [];
82
+ if (policy.catchUp === 'skip') {
83
+ // A slot is stale once its window closed; a windowless slot implicitly
84
+ // yields to its successor (window = everyMs). The jump is arithmetic
85
+ // so a host dead for a year neither loops nor floods the queue —
86
+ // stale slots simply never existed, and don't count against
87
+ // maxOccurrences.
88
+ const staleBefore = now - (policy.windowMs ?? policy.everyMs);
89
+ if (nextAt <= staleBefore) {
90
+ const behind = Math.floor((staleBefore - nextAt) / policy.everyMs) + 1;
91
+ nextAt += behind * policy.everyMs;
92
+ }
93
+ }
94
+ while (nextAt <= horizon && slots.length < exports.MAX_SLOTS_PER_SWEEP) {
95
+ if (policy.until !== undefined && nextAt > policy.until)
96
+ break;
97
+ slots.push(nextAt);
98
+ nextAt += policy.everyMs;
99
+ }
100
+ let retiredReason = null;
101
+ if (policy.maxOccurrences !== undefined) {
102
+ const room = policy.maxOccurrences - state.occurrences;
103
+ if (slots.length >= room) {
104
+ slots = slots.slice(0, Math.max(0, room));
105
+ retiredReason = 'maxOccurrences';
106
+ }
107
+ }
108
+ if (retiredReason === null && policy.until !== undefined && nextAt > policy.until) {
109
+ retiredReason = 'until';
110
+ }
111
+ return {
112
+ slots,
113
+ next: { nextAt, occurrences: state.occurrences + slots.length },
114
+ retiredReason,
115
+ };
116
+ }
117
+ exports.dueSlots = dueSlots;
118
+ /**
119
+ * Cut one occurrence from the template: everything the template carries,
120
+ * with the generated id and the slot's own offer window. A past slot's
121
+ * `notBefore` falls straight through `addAssignment`'s hold guard into the
122
+ * normal enqueue, notAfter clock intact — which is exactly what a due
123
+ * occurrence should do.
124
+ */
125
+ function materializeOccurrence(template, policy, openAt) {
126
+ const schedule = {
127
+ notBefore: openAt,
128
+ ...(policy.windowMs !== undefined ? { notAfter: openAt + policy.windowMs, onMiss: policy.onMiss } : {}),
129
+ };
130
+ // Spread + delete rather than rest-destructuring: a rest pattern over
131
+ // Assignment's index signature erases the named keys from the rest type.
132
+ const occurrence = { ...template, id: occurrenceId(template.id, openAt), schedule };
133
+ delete occurrence.recurrence;
134
+ return occurrence;
135
+ }
136
+ exports.materializeOccurrence = materializeOccurrence;
137
+ /**
138
+ * When the sweep should next act on this template: one interval before the
139
+ * next occurrence opens, so it is already sitting in the scheduled store
140
+ * (visible to hosts) when its window arrives.
141
+ */
142
+ function sweepDueAt(state, policy) {
143
+ return state.nextAt - policy.everyMs;
144
+ }
145
+ exports.sweepDueAt = sweepDueAt;
@@ -17,7 +17,6 @@
17
17
  */
18
18
  import type { AvailabilityRule, SchedulingConstraint, SearchState, ShiftInstance } from '../types';
19
19
  export declare function availability(): SchedulingConstraint;
20
- /** Minutes of `range` covered by one availability rule's clock window. */
21
20
  declare function overlapsRule(clock: {
22
21
  minutesInClockRange: (r: {
23
22
  start: number;
@@ -1 +1 @@
1
- {"version":3,"file":"availability.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/availability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAe,oBAAoB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAIhH,wBAAgB,YAAY,IAAI,oBAAoB,CAiFnD;AAED,0EAA0E;AAC1E,iBAAS,YAAY,CACjB,KAAK,EAAE;IAAE,mBAAmB,EAAE,CAAC,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,KAAK,MAAM,CAAA;CAAE,EAC9G,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,EACrC,IAAI,EAAE,gBAAgB,GACvB,MAAM,CAGR;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAW5D;AAED,uFAAuF;AACvF,wBAAgB,eAAe,CAC3B,KAAK,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,EACzC,KAAK,EAAE,gBAAgB,EAAE,GAAG,SAAS,EACrC,IAAI,EAAE,aAAa,GACpB,MAAM,CAWR"}
1
+ {"version":3,"file":"availability.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/availability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAe,oBAAoB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAIhH,wBAAgB,YAAY,IAAI,oBAAoB,CAqFnD;AAkCD,iBAAS,YAAY,CACjB,KAAK,EAAE;IAAE,mBAAmB,EAAE,CAAC,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,KAAK,MAAM,CAAA;CAAE,EAC9G,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,EACrC,IAAI,EAAE,gBAAgB,GACvB,MAAM,CAGR;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAW5D;AAED,uFAAuF;AACvF,wBAAgB,eAAe,CAC3B,KAAK,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,EACzC,KAAK,EAAE,gBAAgB,EAAE,GAAG,SAAS,EACrC,IAAI,EAAE,aAAa,GACpB,MAAM,CAWR"}
@@ -42,11 +42,11 @@ function availability() {
42
42
  // Declaring any 'available' window inverts the default: everything
43
43
  // outside every declared window is ineligible, including days no
44
44
  // window mentions — a Monday-only declaration bars Tuesdays too.
45
+ // Coverage is the UNION of the declared windows: a shift spanning
46
+ // two contiguous windows lies inside the declaration.
45
47
  const allowLists = employee.availability.filter((r) => r.kind === 'available');
46
48
  if (allowLists.length > 0) {
47
- const covered = matching
48
- .filter((r) => r.kind === 'available')
49
- .reduce((max, rule) => Math.max(max, overlapsRule(clock, range, rule)), 0);
49
+ const covered = unionCoveredMinutes(clock, range, matching.filter((r) => r.kind === 'available'));
50
50
  if (covered < span) {
51
51
  return (0, support_1.fail)('availability', 'hard', `"${inst.id}" falls outside employee "${pair.employeeId}"'s declared availability`, { actual: covered, required: span, unit: 'minutes' });
52
52
  }
@@ -93,7 +93,30 @@ function availability() {
93
93
  return constraint;
94
94
  }
95
95
  exports.availability = availability;
96
- /** Minutes of `range` covered by one availability rule's clock window. */
96
+ /**
97
+ * Minutes of `range` covered by the union of the given windows. A window with
98
+ * no `from`/`to` covers the whole range; timed windows are projected onto the
99
+ * range via the clock (same per-day band semantics as `overlapsRule`) and
100
+ * merged, so contiguous or overlapping declarations never undercount.
101
+ */
102
+ function unionCoveredMinutes(clock, range, rules) {
103
+ const intervals = [];
104
+ for (const rule of rules) {
105
+ if (rule.from === undefined || rule.to === undefined)
106
+ return range.end - range.start;
107
+ intervals.push(...clock.clockRangeIntervals(range, { from: rule.from, to: rule.to }));
108
+ }
109
+ intervals.sort((a, b) => a.start - b.start);
110
+ let covered = 0;
111
+ let cursor = range.start;
112
+ for (const interval of intervals) {
113
+ if (interval.end <= cursor)
114
+ continue;
115
+ covered += interval.end - Math.max(interval.start, cursor);
116
+ cursor = interval.end;
117
+ }
118
+ return covered;
119
+ }
97
120
  function overlapsRule(clock, range, rule) {
98
121
  if (rule.from === undefined || rule.to === undefined)
99
122
  return range.end - range.start;
@@ -1 +1 @@
1
- {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAoC,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAGvF,wBAAgB,cAAc,IAAI,oBAAoB,CAmGrD"}
1
+ {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAoC,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAGvF,wBAAgB,cAAc,IAAI,oBAAoB,CAkHrD"}
@@ -54,9 +54,19 @@ function contractLimits() {
54
54
  };
55
55
  return timeline.withEntry(probe, (t) => {
56
56
  const periodWindow = { start: 0, end: state.ctx.periodDays * support_1.MINUTES_PER_DAY };
57
+ // A contract bounds the employee *record*, not the person (the
58
+ // same per-record reading as the minimum aggregate below and the
59
+ // timeOffInLieu ledger): the person timeline also carries
60
+ // sibling contracts' entries, which must not eat this
61
+ // contract's budget. Roster entries are attributable by their
62
+ // `${employeeId}@@` prefix; history entries are not
63
+ // attributable to either record, so they count conservatively.
64
+ const ownPrefix = `${pair.employeeId}@@`;
65
+ const attributable = t
66
+ .entriesIn(periodWindow)
67
+ .filter((e) => !e.id.includes('@@') || e.id.startsWith(ownPrefix));
57
68
  if (contract.kind === 'days' && contract.maxDaysInPeriod !== undefined) {
58
- const days = new Set(t.entriesIn(periodWindow).map((e) => state.ctx.clock.dayIndexOfMinute(e.start)))
59
- .size;
69
+ const days = new Set(attributable.map((e) => state.ctx.clock.dayIndexOfMinute(e.start))).size;
60
70
  if (days > contract.maxDaysInPeriod) {
61
71
  return (0, support_1.fail)('contract', 'hard', `employee "${pair.employeeId}" would work ${days} days, over their ${contract.maxDaysInPeriod}-day contract`, { actual: days, required: contract.maxDaysInPeriod, unit: 'days' });
62
72
  }
@@ -68,7 +78,11 @@ function contractLimits() {
68
78
  });
69
79
  }
70
80
  if (contract.maxPeriodMinutes !== undefined) {
71
- const worked = t.workingMinutesIn(periodWindow);
81
+ const worked = attributable.reduce((sum, e) => {
82
+ const overlap = Math.min(e.end, periodWindow.end) - Math.max(e.start, periodWindow.start);
83
+ const span = e.end - e.start;
84
+ return sum + (span > 0 ? Math.round((e.workingMinutes * Math.max(0, overlap)) / span) : 0);
85
+ }, 0);
72
86
  if (worked > contract.maxPeriodMinutes) {
73
87
  return (0, support_1.fail)('contract', 'hard', `employee "${pair.employeeId}" would work ${(0, support_1.h)(worked)}, over their ${(0, support_1.h)(contract.maxPeriodMinutes)} contract maximum`, { actual: worked, required: contract.maxPeriodMinutes, unit: 'minutes' });
74
88
  }
@@ -1 +1 @@
1
- {"version":3,"file":"daily-rest.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/daily-rest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAe,oBAAoB,EAA+B,MAAM,UAAU,CAAC;AAG9G,eAAO,MAAM,mBAAmB,+BAA+B,CAAC;AAEhE,wBAAgB,SAAS,CAAC,IAAI,EAAE,aAAa,GAAG,oBAAoB,CA0FnE"}
1
+ {"version":3,"file":"daily-rest.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/daily-rest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAe,oBAAoB,EAA+B,MAAM,UAAU,CAAC;AAG9G,eAAO,MAAM,mBAAmB,+BAA+B,CAAC;AAEhE,wBAAgB,SAAS,CAAC,IAAI,EAAE,aAAa,GAAG,oBAAoB,CA8FnE"}
@@ -40,8 +40,13 @@ function dailyRest(rule) {
40
40
  const gap = timeline.minGapAround(range, (0, support_1.entryIdOf)(pair));
41
41
  if (gap === 0) {
42
42
  // Overlapping work is `no-overlap`'s business; reporting it here
43
- // too would double-count the same defect.
44
- return (0, support_1.pass)('daily-rest', 'overlap is handled by no-overlap');
43
+ // too would double-count the same defect. A zero gap without an
44
+ // overlap is back-to-back work, and that IS this rule's business
45
+ // — fall through to the floor check.
46
+ const own = (0, support_1.entryIdOf)(pair);
47
+ const overlapping = timeline.entriesIn(range).some((e) => e.id !== own);
48
+ if (overlapping)
49
+ return (0, support_1.pass)('daily-rest', 'overlap is handled by no-overlap');
45
50
  }
46
51
  if (gap < floor) {
47
52
  return (0, support_1.fail)('daily-rest', 'hard', `employee "${pair.employeeId}" would get ${(0, support_1.h)(gap)} rest around "${inst.id}", below the ${(0, support_1.h)(floor)} minimum`, { actual: gap, required: floor, unit: 'minutes', citation: exports.DAILY_REST_CITATION });
@@ -1 +1 @@
1
- {"version":3,"file":"hour-budget.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/hour-budget.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,YAAY,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAErG,wBAAgB,UAAU,IAAI,oBAAoB,CAwBjD;AAED,sDAAsD;AACtD,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,GAAG,mBAAmB,EAAE,CAgB9G"}
1
+ {"version":3,"file":"hour-budget.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/hour-budget.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,YAAY,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAErG,wBAAgB,UAAU,IAAI,oBAAoB,CA8BjD;AAED,sDAAsD;AACtD,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,GAAG,mBAAmB,EAAE,CAgB9G"}
@@ -24,8 +24,14 @@ function hourBudget() {
24
24
  // working time, and the budget is documented as *worked* hours, so
25
25
  // the candidate must contribute in the same unit — an unpaid break
26
26
  // or a fractional duty must not be double-counted against it.
27
+ // An already-assigned pair's shift is in the total, so it is not
28
+ // added again (the same self-exclusion `withEntry` gives the
29
+ // timeline rules): re-judging a committed roster must ask "is the
30
+ // total over the cap", not "would the cap survive this twice".
27
31
  const current = state.minutesByEmployee.get(pair.employeeId) ?? 0;
28
- return current + inst.workingMinutes > employee.maxHoursForPeriod * 60 ? 1 : 0;
32
+ const assigned = state.assignments.get(pair.shiftInstanceId)?.has(pair.employeeId) ?? false;
33
+ const total = assigned ? current : current + inst.workingMinutes;
34
+ return total > employee.maxHoursForPeriod * 60 ? 1 : 0;
29
35
  },
30
36
  explain(state, pair) {
31
37
  const employee = state.ctx.employeeById.get(pair.employeeId);
@@ -1 +1 @@
1
- {"version":3,"file":"in-shift-breaks.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/in-shift-breaks.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAoC,oBAAoB,EAAiB,MAAM,UAAU,CAAC;AAGjH,eAAO,MAAM,cAAc,+BAA+B,CAAC;AAE3D,wBAAgB,aAAa,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,oBAAoB,CA2EtE"}
1
+ {"version":3,"file":"in-shift-breaks.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/in-shift-breaks.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAoC,oBAAoB,EAAiB,MAAM,UAAU,CAAC;AAGjH,eAAO,MAAM,cAAc,+BAA+B,CAAC;AAE3D,wBAAgB,aAAa,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,oBAAoB,CA6EtE"}