assignment-user-matcher 1.16.1 → 1.22.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 (153) hide show
  1. package/README.md +290 -8
  2. package/dist/escalation/policy.d.ts +11 -0
  3. package/dist/escalation/policy.d.ts.map +1 -1
  4. package/dist/escalation/policy.js +22 -1
  5. package/dist/forecasting/backtest.d.ts +52 -0
  6. package/dist/forecasting/backtest.d.ts.map +1 -0
  7. package/dist/forecasting/backtest.js +195 -0
  8. package/dist/forecasting/calendar.d.ts +44 -0
  9. package/dist/forecasting/calendar.d.ts.map +1 -0
  10. package/dist/forecasting/calendar.js +85 -0
  11. package/dist/forecasting/cover.d.ts +69 -0
  12. package/dist/forecasting/cover.d.ts.map +1 -0
  13. package/dist/forecasting/cover.js +103 -0
  14. package/dist/forecasting/days.d.ts +17 -0
  15. package/dist/forecasting/days.d.ts.map +1 -0
  16. package/dist/forecasting/days.js +35 -0
  17. package/dist/forecasting/distributions.d.ts +31 -0
  18. package/dist/forecasting/distributions.d.ts.map +1 -0
  19. package/dist/forecasting/distributions.js +154 -0
  20. package/dist/forecasting/effects.d.ts +88 -0
  21. package/dist/forecasting/effects.d.ts.map +1 -0
  22. package/dist/forecasting/effects.js +303 -0
  23. package/dist/forecasting/erlang.d.ts +31 -0
  24. package/dist/forecasting/erlang.d.ts.map +1 -0
  25. package/dist/forecasting/erlang.js +86 -0
  26. package/dist/forecasting/forecast.d.ts +7 -0
  27. package/dist/forecasting/forecast.d.ts.map +1 -0
  28. package/dist/forecasting/forecast.js +221 -0
  29. package/dist/forecasting/index.d.ts +18 -0
  30. package/dist/forecasting/index.d.ts.map +1 -0
  31. package/dist/forecasting/index.js +54 -0
  32. package/dist/forecasting/model.d.ts +145 -0
  33. package/dist/forecasting/model.d.ts.map +1 -0
  34. package/dist/forecasting/model.js +583 -0
  35. package/dist/forecasting/nowcast.d.ts +26 -0
  36. package/dist/forecasting/nowcast.d.ts.map +1 -0
  37. package/dist/forecasting/nowcast.js +92 -0
  38. package/dist/forecasting/simulation.d.ts +91 -0
  39. package/dist/forecasting/simulation.d.ts.map +1 -0
  40. package/dist/forecasting/simulation.js +478 -0
  41. package/dist/forecasting/spikes.d.ts +6 -0
  42. package/dist/forecasting/spikes.d.ts.map +1 -0
  43. package/dist/forecasting/spikes.js +73 -0
  44. package/dist/forecasting/staffing.d.ts +64 -0
  45. package/dist/forecasting/staffing.d.ts.map +1 -0
  46. package/dist/forecasting/staffing.js +765 -0
  47. package/dist/forecasting/stats.d.ts +11 -0
  48. package/dist/forecasting/stats.d.ts.map +1 -0
  49. package/dist/forecasting/stats.js +45 -0
  50. package/dist/forecasting/types.d.ts +299 -0
  51. package/dist/forecasting/types.d.ts.map +1 -0
  52. package/dist/forecasting/types.js +8 -0
  53. package/dist/index.d.ts +3 -2
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +8 -1
  56. package/dist/learning/auto-weights.d.ts +1 -5
  57. package/dist/learning/auto-weights.d.ts.map +1 -1
  58. package/dist/learning/auto-weights.js +0 -3
  59. package/dist/lua/book-slot.lua +84 -0
  60. package/dist/lua/claim-queued.lua +47 -0
  61. package/dist/managers/DecisionTraceManager.d.ts +15 -0
  62. package/dist/managers/DecisionTraceManager.d.ts.map +1 -1
  63. package/dist/managers/DecisionTraceManager.js +117 -11
  64. package/dist/managers/LearningManager.d.ts +12 -0
  65. package/dist/managers/LearningManager.d.ts.map +1 -1
  66. package/dist/managers/LearningManager.js +21 -7
  67. package/dist/managers/ReliabilityManager.d.ts +1 -2
  68. package/dist/managers/ReliabilityManager.d.ts.map +1 -1
  69. package/dist/managers/ReliabilityManager.js +1 -1
  70. package/dist/managers/TelemetryManager.d.ts.map +1 -1
  71. package/dist/managers/TelemetryManager.js +9 -3
  72. package/dist/managers/WorkflowManager.d.ts.map +1 -1
  73. package/dist/managers/WorkflowManager.js +3 -4
  74. package/dist/matcher.class.d.ts +319 -4
  75. package/dist/matcher.class.d.ts.map +1 -1
  76. package/dist/matcher.class.js +1428 -102
  77. package/dist/queries/lane-stats.d.ts +51 -0
  78. package/dist/queries/lane-stats.d.ts.map +1 -0
  79. package/dist/queries/lane-stats.js +78 -0
  80. package/dist/schedule/recurrence.d.ts +11 -0
  81. package/dist/schedule/recurrence.d.ts.map +1 -1
  82. package/dist/schedule/recurrence.js +19 -2
  83. package/dist/schedule/slot.d.ts +60 -0
  84. package/dist/schedule/slot.d.ts.map +1 -0
  85. package/dist/schedule/slot.js +86 -0
  86. package/dist/scheduling/constraints/availability.d.ts +2 -14
  87. package/dist/scheduling/constraints/availability.d.ts.map +1 -1
  88. package/dist/scheduling/constraints/availability.js +14 -15
  89. package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -1
  90. package/dist/scheduling/constraints/employee-scope.js +10 -2
  91. package/dist/scheduling/constraints/support.d.ts +4 -8
  92. package/dist/scheduling/constraints/support.d.ts.map +1 -1
  93. package/dist/scheduling/constraints/support.js +23 -2
  94. package/dist/scheduling/constraints/weekly-rest.d.ts +28 -0
  95. package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -1
  96. package/dist/scheduling/constraints/weekly-rest.js +108 -21
  97. package/dist/scheduling/engine/construction.d.ts.map +1 -1
  98. package/dist/scheduling/engine/construction.js +33 -4
  99. package/dist/scheduling/engine/objective.d.ts +0 -1
  100. package/dist/scheduling/engine/objective.d.ts.map +1 -1
  101. package/dist/scheduling/engine/objective.js +45 -3
  102. package/dist/scheduling/engine/search.d.ts +4 -0
  103. package/dist/scheduling/engine/search.d.ts.map +1 -1
  104. package/dist/scheduling/engine/search.js +2 -1
  105. package/dist/scheduling/engine/state.d.ts +14 -0
  106. package/dist/scheduling/engine/state.d.ts.map +1 -1
  107. package/dist/scheduling/engine/state.js +7 -0
  108. package/dist/scheduling/engine/timeline.d.ts +9 -1
  109. package/dist/scheduling/engine/timeline.d.ts.map +1 -1
  110. package/dist/scheduling/engine/timeline.js +52 -27
  111. package/dist/scheduling/engine/verdicts.d.ts +40 -1
  112. package/dist/scheduling/engine/verdicts.d.ts.map +1 -1
  113. package/dist/scheduling/engine/verdicts.js +177 -17
  114. package/dist/scheduling/index.d.ts +3 -2
  115. package/dist/scheduling/index.d.ts.map +1 -1
  116. package/dist/scheduling/index.js +7 -1
  117. package/dist/scheduling/model.d.ts +2 -3
  118. package/dist/scheduling/model.d.ts.map +1 -1
  119. package/dist/scheduling/model.js +30 -12
  120. package/dist/scheduling/operations.d.ts +174 -2
  121. package/dist/scheduling/operations.d.ts.map +1 -1
  122. package/dist/scheduling/operations.js +513 -15
  123. package/dist/scheduling/preference-report.d.ts +15 -0
  124. package/dist/scheduling/preference-report.d.ts.map +1 -0
  125. package/dist/scheduling/preference-report.js +111 -0
  126. package/dist/scheduling/preferences.d.ts +30 -0
  127. package/dist/scheduling/preferences.d.ts.map +1 -0
  128. package/dist/scheduling/preferences.js +85 -0
  129. package/dist/scheduling/resilience.d.ts +46 -0
  130. package/dist/scheduling/resilience.d.ts.map +1 -0
  131. package/dist/scheduling/resilience.js +45 -0
  132. package/dist/scheduling/scheduler.class.d.ts +12 -1
  133. package/dist/scheduling/scheduler.class.d.ts.map +1 -1
  134. package/dist/scheduling/scheduler.class.js +28 -4
  135. package/dist/scheduling/time.d.ts +28 -6
  136. package/dist/scheduling/time.d.ts.map +1 -1
  137. package/dist/scheduling/time.js +59 -17
  138. package/dist/scheduling/types.d.ts +107 -1
  139. package/dist/scheduling/types.d.ts.map +1 -1
  140. package/dist/scoring/fair-arbitration.d.ts.map +1 -1
  141. package/dist/scoring/fair-arbitration.js +2 -1
  142. package/dist/tracing/decision-trace.d.ts +5 -0
  143. package/dist/tracing/decision-trace.d.ts.map +1 -1
  144. package/dist/tracing/decision-trace.js +3 -0
  145. package/dist/types/matcher.d.ts +369 -2
  146. package/dist/types/matcher.d.ts.map +1 -1
  147. package/dist/updates/assignment-update.d.ts +93 -0
  148. package/dist/updates/assignment-update.d.ts.map +1 -0
  149. package/dist/updates/assignment-update.js +91 -0
  150. package/dist/utils/keys.d.ts +10 -0
  151. package/dist/utils/keys.d.ts.map +1 -1
  152. package/dist/utils/keys.js +43 -0
  153. package/package.json +15 -2
@@ -0,0 +1,765 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.headcountNeed = exports.rateNeed = exports.staffingNeed = exports.SERVICE_HALF_WIDTH = exports.MIN_SEEDS = exports.BACKLOG_SEEDS = exports.CARRY_TARGET_HANDLES = exports.CARRY_TARGET_MS = exports.windowFor = exports.composeTeam = exports.quantize = exports.staffingBudgetMs = exports.STAFFING_BUDGET = exports.DEFAULT_MAX_PEOPLE = exports.DEFAULT_QUANTIZE = exports.DEFAULT_OVERDISPERSION = exports.DEFAULT_SEEDS = void 0;
4
+ /**
5
+ * Volume → people (spec §7.3, as amended by the owner: no naive Erlang C).
6
+ *
7
+ * `staffingNeed` finds, per interval, the fewest people who meet every tag's
8
+ * service target in the discrete-event simulation over all seeds together —
9
+ * on average, allowing for forecast error (the expected service level Erlang C
10
+ * staffs to); the per-seed answers' p10–p90 is the range. The team for a head
11
+ * count follows the work (`composeTeam`), and says when it needs more of a
12
+ * profile than the pool has. Without patience a floor that cannot keep up with
13
+ * the arrivals is never enough, however a single hour goes. When some tag's
14
+ * target outlasts its hour (≥ 15 min, or ≥ 2 handle times), back-to-back
15
+ * intervals are simulated in sequence, each opening with what the previous one
16
+ * left queued or in progress at its likely head count. Erlang A only brackets
17
+ * the search. People on shift = working the queue ÷ (1 − shrinkage).
18
+ *
19
+ * `rateNeed` and `headcountNeed` are the two other conversions: volume ÷
20
+ * units per person-hour (warehouses, production), or the series already is
21
+ * people.
22
+ */
23
+ const distributions_1 = require("./distributions");
24
+ const erlang_1 = require("./erlang");
25
+ const simulation_1 = require("./simulation");
26
+ const stats_1 = require("./stats");
27
+ exports.DEFAULT_SEEDS = 20;
28
+ exports.DEFAULT_OVERDISPERSION = 20;
29
+ exports.DEFAULT_QUANTIZE = 0.05;
30
+ exports.DEFAULT_MAX_PEOPLE = 500;
31
+ const MINUTE = 60000;
32
+ /**
33
+ * The staffing run's wall-clock budget scales with volume: `baseMs` per `perPeakRate` arrivals an hour at
34
+ * the peak, never under `baseMs` and never over `maxMs`. Simulation cost grows with the tasks simulated, so
35
+ * a fixed budget would skip the busiest workspaces' hours.
36
+ */
37
+ exports.STAFFING_BUDGET = { baseMs: 6000, perPeakRate: 300, maxMs: 20000 };
38
+ /** `budgetMs` for a run whose busiest interval brings `peakPerHour` arrivals an hour over all tags. */
39
+ function staffingBudgetMs(peakPerHour) {
40
+ if (Number.isNaN(peakPerHour))
41
+ return exports.STAFFING_BUDGET.baseMs;
42
+ const scaled = (exports.STAFFING_BUDGET.baseMs * peakPerHour) / exports.STAFFING_BUDGET.perPeakRate;
43
+ return (0, stats_1.clamp)(scaled, exports.STAFFING_BUDGET.baseMs, exports.STAFFING_BUDGET.maxMs);
44
+ }
45
+ exports.staffingBudgetMs = staffingBudgetMs;
46
+ /** Arrivals rounded onto a relative grid, so hours with near-identical load share one simulation. */
47
+ function quantize(value, step = exports.DEFAULT_QUANTIZE) {
48
+ if (value <= 0)
49
+ return 0;
50
+ if (value < 1)
51
+ return Math.round(value * 10) / 10;
52
+ const k = Math.log(1 + step);
53
+ return Math.round(Math.exp(Math.round(Math.log(value) / k) * k) * 100) / 100;
54
+ }
55
+ exports.quantize = quantize;
56
+ /**
57
+ * Who is on for a head count of `n`. Heads follow the work, not the pool's mix:
58
+ *
59
+ * 1. Every busy tag somebody can take gets one person first (rarest tag first): nobody rosters ten people
60
+ * to get the one German speaker.
61
+ * 2. Then each next head goes to the worst-served tag — the one with the largest `shortfall(tag, heads it
62
+ * has)`; by default `1 − heads ÷ load`, and in `staffingNeed` the Erlang A service level it would have
63
+ * on its own against its target, so a small tag gets the second person it needs instead of a share.
64
+ *
65
+ * A head for a tag goes to a profile that covers it: one the pool still has people of first; among
66
+ * those, the one whose head makes the most progress towards the targets of all the short tags it covers
67
+ * (so a generalist goes where two queues are short), a specialist on a tie (generalists are kept for work
68
+ * only they can take), then the one with the most people left. A rare skill is still protected: its tag
69
+ * becomes the most short, and only its coverers can take that head.
70
+ * Past the declared pool, the head still goes to the tag that needs it, so `team[p]` can exceed
71
+ * `counts[p]` — the people to hire; `staffingNeed` reports it as `exceedsPool`. Without any work the
72
+ * pool's own mix is used.
73
+ */
74
+ function composeTeam(n, pool, counts, load, shortfall) {
75
+ const team = pool.map(() => 0);
76
+ if (n <= 0)
77
+ return team;
78
+ const coverers = (g) => pool.map((s, p) => (s[g] >= 0 ? p : -1)).filter((p) => p >= 0);
79
+ const busy = [];
80
+ for (let g = 0; g < load.length; g++)
81
+ if (load[g] > 0 && coverers(g).length > 0)
82
+ busy.push(g);
83
+ if (busy.length === 0)
84
+ return apportion(n, counts);
85
+ const short = shortfall ?? ((g, heads) => 1 - heads / load[g]);
86
+ const breadth = pool.map((s) => busy.filter((g) => s[g] >= 0).length);
87
+ const credit = new Float64Array(load.length);
88
+ let placed = 0;
89
+ /** Progress a head on profile p would make towards the targets of all the busy tags it covers. */
90
+ const gain = (p) => {
91
+ let sum = 0;
92
+ for (const g of busy) {
93
+ if (pool[p][g] < 0)
94
+ continue;
95
+ sum += Math.max(0, short(g, credit[g])) - Math.max(0, short(g, credit[g] + 1));
96
+ }
97
+ return sum;
98
+ };
99
+ /** Heads of profile p placed for tag g: which work each head is there for, so a head can be swapped. */
100
+ const placedFor = pool.map(() => new Float64Array(load.length));
101
+ const spare = (p) => counts[p] - team[p];
102
+ const add = (p, g) => {
103
+ team[p] += 1;
104
+ placedFor[p][g] += 1;
105
+ };
106
+ const place = (g) => {
107
+ const options = coverers(g);
108
+ const value = new Map(options.map((p) => [p, gain(p)]));
109
+ options.sort((a, b) => Number(spare(b) > 0) - Number(spare(a) > 0) ||
110
+ value.get(b) - value.get(a) ||
111
+ breadth[a] - breadth[b] ||
112
+ spare(b) - spare(a) ||
113
+ a - b);
114
+ credit[g] += 1;
115
+ placed += 1;
116
+ if (spare(options[0]) <= 0) {
117
+ // Nobody left in the pool who can take g. Before hiring, free one who can: a head of a profile
118
+ // covering g placed for other work that somebody else in the pool can still do.
119
+ for (const p of options) {
120
+ for (const other of busy) {
121
+ if (other === g || placedFor[p][other] < 1)
122
+ continue;
123
+ const stand = coverers(other)
124
+ .filter((q) => q !== p && spare(q) > 0)
125
+ .sort((a, b) => breadth[a] - breadth[b] || spare(b) - spare(a) || a - b)[0];
126
+ if (stand === undefined)
127
+ continue;
128
+ placedFor[p][other] -= 1;
129
+ placedFor[p][g] += 1;
130
+ add(stand, other);
131
+ return;
132
+ }
133
+ }
134
+ }
135
+ add(options[0], g);
136
+ };
137
+ const rarest = [...busy].sort((a, b) => coverers(a).length - coverers(b).length || a - b);
138
+ for (const g of rarest) {
139
+ if (placed >= n)
140
+ break;
141
+ if (!team.some((k, p) => k > 0 && pool[p][g] >= 0))
142
+ place(g);
143
+ }
144
+ while (placed < n) {
145
+ let worst = busy[0];
146
+ let most = -Infinity;
147
+ for (const g of busy) {
148
+ const v = short(g, credit[g]);
149
+ if (v > most) {
150
+ most = v;
151
+ worst = g;
152
+ }
153
+ }
154
+ place(worst);
155
+ }
156
+ return team;
157
+ }
158
+ exports.composeTeam = composeTeam;
159
+ /**
160
+ * Splits `n` in proportion to `weights` by largest remainder (ties to the lower index); never above a weight
161
+ * when n ≤ Σ weights.
162
+ */
163
+ function apportion(n, weights) {
164
+ const total = weights.reduce((a, b) => a + b, 0);
165
+ if (total <= 0)
166
+ return weights.map(() => 0);
167
+ const exact = weights.map((c) => (c / total) * n);
168
+ const out = exact.map(Math.floor);
169
+ let rest = n - out.reduce((a, b) => a + b, 0);
170
+ // Remainders compared to 1e-9, so a float tie (2.5 against 7.5000000000000001) goes to the lower index.
171
+ const byRemainder = exact
172
+ .map((e, p) => ({ p, r: Math.round((e - Math.floor(e)) * 1e9) }))
173
+ .sort((a, b) => b.r - a.r || a.p - b.p);
174
+ for (let i = 0; rest > 0; i = (i + 1) % byRemainder.length, rest--)
175
+ out[byRemainder[i].p] += 1;
176
+ return out;
177
+ }
178
+ /**
179
+ * The simulated span around one interval: a warm-up of three mean handle times (15–240 min), the
180
+ * interval, and a tail as long as the longest target, so the interval's last arrivals are judged on
181
+ * their whole wait — the run ends at target + interval length.
182
+ */
183
+ function windowFor(tags, intervalMinutes = 60) {
184
+ const meanHandle = Math.max(...tags.map((t) => (0, distributions_1.meanOf)(t.handleMs)), MINUTE);
185
+ return {
186
+ warmMs: (0, stats_1.clamp)(3 * meanHandle, 15 * MINUTE, 240 * MINUTE),
187
+ lengthMs: intervalMinutes * MINUTE,
188
+ tailMs: Math.max(...tags.map((t) => t.targetWaitMs), 0),
189
+ };
190
+ }
191
+ exports.windowFor = windowFor;
192
+ /** A target this long, or this many handle times, makes a tag's queue outlive its hour: chain the hours. */
193
+ exports.CARRY_TARGET_MS = 15 * MINUTE;
194
+ exports.CARRY_TARGET_HANDLES = 2;
195
+ /**
196
+ * Validates and prepares the inputs. Pool members with the same tags and weights are merged, and the pool
197
+ * is put in a canonical order, so no answer depends on the order the pool was declared in.
198
+ */
199
+ function prepare(tags, pool, intervalMinutes) {
200
+ const simTags = tags.map((profile) => {
201
+ (0, distributions_1.assertDistribution)(profile.handleMs, `handleMs of ${profile.tag}`);
202
+ if (profile.patienceMs)
203
+ (0, distributions_1.assertDistribution)(profile.patienceMs, `patienceMs of ${profile.tag}`);
204
+ const concurrency = Math.max(1, Math.floor(profile.concurrency ?? 1));
205
+ return { profile, cost: 1 / concurrency, priority: profile.priority ?? 0 };
206
+ });
207
+ const merged = new Map();
208
+ for (const m of pool) {
209
+ if (!(m.count > 0))
210
+ continue;
211
+ const weights = m.weights ? Object.entries(m.weights).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) : [];
212
+ const key = JSON.stringify([[...new Set(m.tags)].sort(), weights]);
213
+ const seen = merged.get(key);
214
+ if (seen)
215
+ seen.count += m.count;
216
+ else
217
+ merged.set(key, { tags: m.tags, weights: m.weights, count: m.count });
218
+ }
219
+ const members = [...merged.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([, m]) => m);
220
+ const meanHandle = simTags.map((t) => (0, distributions_1.meanOf)(t.profile.handleMs));
221
+ const long = simTags.map((t, g) => t.profile.targetWaitMs >= exports.CARRY_TARGET_MS || t.profile.targetWaitMs >= exports.CARRY_TARGET_HANDLES * meanHandle[g]);
222
+ return {
223
+ tags: simTags,
224
+ meanHandle,
225
+ pool: members.map((m) => (0, simulation_1.profileScores)(m, simTags)),
226
+ counts: members.map((m) => m.count),
227
+ window: windowFor(tags, intervalMinutes),
228
+ long,
229
+ chained: long.some(Boolean),
230
+ };
231
+ }
232
+ /** Erlang A over the interval's pooled load: only the search's starting point. */
233
+ function seedFor(expected, prep, max) {
234
+ const total = expected.reduce((a, b) => a + b, 0);
235
+ let handle = 0;
236
+ let patienceRate = 0;
237
+ let target = Infinity;
238
+ let share = 0;
239
+ prep.tags.forEach((t, g) => {
240
+ if (!expected[g])
241
+ return;
242
+ const w = expected[g] / total;
243
+ handle += w * prep.meanHandle[g] * t.cost;
244
+ if (t.profile.patienceMs)
245
+ patienceRate += w / Math.max(1, (0, distributions_1.meanOf)(t.profile.patienceMs));
246
+ target = Math.min(target, t.profile.targetWaitMs);
247
+ share = Math.max(share, t.profile.targetShare);
248
+ });
249
+ return (0, erlang_1.erlangASeed)({
250
+ lambda: total / prep.window.lengthMs,
251
+ meanHandleMs: Math.max(1, handle),
252
+ meanPatienceMs: patienceRate > 0 ? 1 / patienceRate : Infinity,
253
+ targetMs: target,
254
+ }, share, max);
255
+ }
256
+ /**
257
+ * The fewest people a seed's arrivals can be served by in steady state: more than the work that never
258
+ * leaves (tags without patience), in person-units. Below it the queue only grows, however well a single
259
+ * hour that started without a backlog seems to go; work that gives up is shed instead, so it sets no floor.
260
+ * A long-target tag's work only has to be done within its target, so its rate is scaled by `spread[g]`
261
+ * (its load averaged over the target window, relative to this hour's).
262
+ */
263
+ function stableFloor(rate, prep, tags, spread) {
264
+ let load = 0;
265
+ for (const g of tags) {
266
+ const t = prep.tags[g];
267
+ if (!t.profile.patienceMs)
268
+ load += rate[g] * (spread ? spread[g] : 1) * prep.meanHandle[g] * t.cost;
269
+ }
270
+ return Math.floor(load + 1e-9) + 1;
271
+ }
272
+ /**
273
+ * Fewest people for whom `ok` holds, at least `floor` (`ok` is taken as monotone in the head count). The
274
+ * walk starts at `start` — a good guess lands within a person or two — and gallops away from it, down while
275
+ * it still passes or up until it does, doubling its step, then bisects the last step.
276
+ */
277
+ function search(ok, start, floor, max) {
278
+ // A floor above the cap: no head count the search may try can keep up with the work.
279
+ if (floor > max)
280
+ return { n: max, capped: true };
281
+ const low = Math.max(1, floor);
282
+ /** Smallest passing head count in [lo, hi], given that hi passes. */
283
+ const bisect = (lo, hi) => {
284
+ while (lo < hi) {
285
+ const mid = Math.floor((lo + hi) / 2);
286
+ if (ok(mid))
287
+ hi = mid;
288
+ else
289
+ lo = mid + 1;
290
+ }
291
+ return hi;
292
+ };
293
+ const first = (0, stats_1.clamp)(start, low, max);
294
+ let step = 1;
295
+ if (ok(first)) {
296
+ let hi = first;
297
+ while (hi > low) {
298
+ const next = Math.max(low, hi - step);
299
+ if (!ok(next))
300
+ return { n: bisect(next + 1, hi), capped: false };
301
+ hi = next;
302
+ step *= 2;
303
+ }
304
+ return { n: hi, capped: false };
305
+ }
306
+ let lo = first;
307
+ while (lo < max) {
308
+ const next = Math.min(max, lo + step);
309
+ if (ok(next))
310
+ return { n: bisect(lo + 1, next), capped: false };
311
+ lo = next;
312
+ step *= 2;
313
+ }
314
+ return { n: max, capped: true };
315
+ }
316
+ /** Whether served counts meet every judged tag's share of arrivals (a tag with none passes). */
317
+ const meets = (served, arrived, prep, judged) => judged.every((g) => arrived[g] === 0 || served[g] / arrived[g] >= prep.tags[g].profile.targetShare - 1e-9);
318
+ /**
319
+ * Seeds for a chained hour whose work is mostly inherited backlog (carried-in work ≥ half the hour's), and
320
+ * for the two hours before it that built the backlog (re-read when the backlog shows): its service level
321
+ * hangs on rare big-backlog days, which twenty seeds mostly miss. No adaptive stop for them.
322
+ */
323
+ exports.BACKLOG_SEEDS = 80;
324
+ /** Share of an hour's work that, carried in, makes it a backlog hour. */
325
+ const BACKLOG_SHARE = 0.5;
326
+ /** Seeds every load gets before the adaptive stop may end it early. */
327
+ exports.MIN_SEEDS = 8;
328
+ /** Stop drawing seeds once every judged tag's pooled service level is known to ±this (95 %). */
329
+ exports.SERVICE_HALF_WIDTH = 0.01;
330
+ const quiet = (startMs, uncovered, method) => {
331
+ const zero = { low: 0, likely: 0, high: 0 };
332
+ return {
333
+ startMs,
334
+ productive: zero,
335
+ onShift: zero,
336
+ serviceByTag: {},
337
+ uncovered,
338
+ erlangSeed: 0,
339
+ method,
340
+ capped: false,
341
+ exceedsPool: false,
342
+ };
343
+ };
344
+ /**
345
+ * 95 % half-width of a pooled share over seeds: by the ratio estimator from the seeds' own spread, never
346
+ * below the binomial error of the arrivals it rests on (Agresti–Coull) — eight perfect hours are not proof
347
+ * that bad hours do not happen.
348
+ */
349
+ function halfWidth(served, arrived) {
350
+ const n = arrived.length;
351
+ const x = arrived.reduce((a, b) => a + b, 0);
352
+ const y = served.reduce((a, b) => a + b, 0);
353
+ const shrunk = (y + 2) / (x + 4);
354
+ const binomial = 1.96 * Math.sqrt((shrunk * (1 - shrunk)) / (x + 4));
355
+ if (x === 0)
356
+ return binomial;
357
+ const ratio = y / x;
358
+ let spread = 0;
359
+ for (let i = 0; i < n; i++)
360
+ spread += (served[i] - ratio * arrived[i]) ** 2;
361
+ return Math.max(binomial, (1.96 * Math.sqrt(spread / (n * (n - 1)))) / (x / n));
362
+ }
363
+ function staffingNeed(intervals, tags, pool, options) {
364
+ const started = Date.now();
365
+ const maxSeeds = Math.max(1, options.seeds ?? exports.DEFAULT_SEEDS);
366
+ const minSeeds = Math.min(maxSeeds, exports.MIN_SEEDS);
367
+ const baseSeed = options.seed ?? 1;
368
+ const k = options.overdispersion ?? exports.DEFAULT_OVERDISPERSION;
369
+ const step = options.quantizeStep ?? exports.DEFAULT_QUANTIZE;
370
+ const max = options.maxPeople ?? exports.DEFAULT_MAX_PEOPLE;
371
+ const shrinkage = (0, stats_1.clamp)(options.shrinkage, 0, 0.9);
372
+ const prep = prepare(tags, pool, options.intervalMinutes ?? 60);
373
+ const nTags = prep.tags.length;
374
+ const lengthMs = prep.window.lengthMs;
375
+ const memo = new Map();
376
+ const strataBy = new Map();
377
+ const strataFor = (count) => {
378
+ let strata = strataBy.get(count);
379
+ if (!strata)
380
+ strataBy.set(count, (strata = (0, distributions_1.spreadStrata)(count)));
381
+ return strata;
382
+ };
383
+ /** Expected work of an hour's new arrivals, in person-ms. */
384
+ const newWork = (arrivals) => prep.tags.reduce((sum, t, g) => sum + Math.max(0, arrivals[t.profile.tag] ?? 0) * prep.meanHandle[g] * t.cost, 0);
385
+ let simulations = 0;
386
+ let cacheHits = 0;
387
+ let incomplete = false;
388
+ /** Chained runs: each seed's leftovers at the previous interval's likely head count. */
389
+ let carries = null;
390
+ let carriedTo = Number.NaN;
391
+ /** One interval, simulated from scratch (`carryIn` null) or opening with the previous one's leftovers. */
392
+ const solve = (offered, judged, seedKey, carryIn, continues, seedCount, spread) => {
393
+ const strata = strataFor(seedCount);
394
+ // Forecast error lasts: seed s continues the leftovers of the earlier seed whose error stratum is
395
+ // nearest its own, also when the two hours were read on different numbers of seeds.
396
+ const inherit = (s) => {
397
+ if (!carryIn || carryIn.length === seedCount)
398
+ return s;
399
+ const from = strataFor(carryIn.length);
400
+ let best = 0;
401
+ for (let j = 1; j < from.length; j++) {
402
+ if (Math.abs(from[j] - strata[s]) < Math.abs(from[best] - strata[s]))
403
+ best = j;
404
+ }
405
+ return best;
406
+ };
407
+ // No adaptive stop when chained: each seed's leftovers are a trajectory the next hours read, and a
408
+ // calm hour that settles on eight seeds would hand on only eight, missing the busy days' backlogs.
409
+ const adaptive = seedCount === maxSeeds && !prep.chained;
410
+ // A chained interval opens with the last one's leftovers (no warm-up), and when another follows it
411
+ // has no tail: nobody is assumed to stay on, and work still queued at its end is judged next door.
412
+ const window = {
413
+ ...prep.window,
414
+ warmMs: carryIn ? 0 : prep.window.warmMs,
415
+ tailMs: continues ? 0 : prep.window.tailMs,
416
+ };
417
+ // Work per tag: this interval's arrivals plus what the seeds carried in on average (tasks per ms).
418
+ const rates = offered.map((v) => v / lengthMs);
419
+ if (carryIn) {
420
+ for (const carry of carryIn) {
421
+ for (let i = 0; i < carry.tag.length; i++)
422
+ rates[carry.tag[i]] += 1 / lengthMs / carryIn.length;
423
+ }
424
+ }
425
+ // Each tag's Erlang A service level with h people on it alone, against its target: the composition
426
+ // gives the next head to the tag furthest short (a small tag needs its second person, not a share).
427
+ const levels = new Map();
428
+ const shortfall = (g, h) => {
429
+ const key = g * 100000 + h;
430
+ let level = levels.get(key);
431
+ if (level === undefined) {
432
+ const t = prep.tags[g];
433
+ level = (0, erlang_1.erlangA)(h, {
434
+ lambda: rates[g],
435
+ meanHandleMs: Math.max(1, prep.meanHandle[g] * t.cost),
436
+ meanPatienceMs: t.profile.patienceMs ? (0, distributions_1.meanOf)(t.profile.patienceMs) : Infinity,
437
+ targetMs: t.profile.targetWaitMs,
438
+ }).serviceLevel;
439
+ levels.set(key, level);
440
+ }
441
+ // Below the tag's own load its service level is flat at 0, so the uncovered work itself is the
442
+ // gradient there: every head short of the load counts, as a share of it.
443
+ const load = rates[g] * prep.meanHandle[g] * prep.tags[g].cost;
444
+ return t(g) - level + (load > 0 ? Math.max(0, load - h) / load : 0);
445
+ };
446
+ const t = (g) => prep.tags[g].profile.targetShare;
447
+ const teams = new Map();
448
+ const teamOf = (n) => {
449
+ let team = teams.get(n);
450
+ if (!team)
451
+ teams.set(n, (team = composeTeam(n, prep.pool, prep.counts, rates, shortfall)));
452
+ return team;
453
+ };
454
+ const erlangSeed = seedFor(offered, prep, max);
455
+ const drawn = [];
456
+ /** Per seed: the fewest people its drawn never-abandoning work leaves able to keep up. */
457
+ const floors = [];
458
+ const runs = [];
459
+ const run = (s, n) => {
460
+ let hit = runs[s].get(n);
461
+ if (!hit) {
462
+ const out = prep.chained ? { carry: null, handOver: continues } : undefined;
463
+ const served = (0, simulation_1.simulate)(drawn[s], prep.pool, teamOf(n), prep.tags, window, undefined, out);
464
+ const arrived = Int32Array.from(drawn[s].measuredByTag);
465
+ if (out?.handedOver)
466
+ for (let g = 0; g < nTags; g++)
467
+ arrived[g] -= out.handedOver[g];
468
+ hit = { served, arrived, carry: out ? out.carry : null };
469
+ runs[s].set(n, hit);
470
+ }
471
+ return hit;
472
+ };
473
+ // The per-seed floor and the steady-state cap are for short-target work only: a long-target tag's
474
+ // overload is already in the queue the chained hours carry, and counting it again overstaffs it.
475
+ const patient = judged.filter((g) => !prep.tags[g].profile.patienceMs && !prep.long[g]);
476
+ /** Per seed: the floor of its short-target never-abandoning work alone (see `counted`). */
477
+ const shortFloors = [];
478
+ /** Seeds whose forecast error put never-abandoning work above the forecast: where the cap applies. */
479
+ const above = [];
480
+ /**
481
+ * Erlang C service level of a seed's never-abandoning work, all n people on it: the sustained hour.
482
+ *
483
+ * An approximation in a mixed pool. It pools every patient tag into one queue with the tightest
484
+ * target and the work-weighted mean handle time, and puts all n people on it — as if everybody could
485
+ * take every tag and nobody were busy with abandoning or long-target work. With partial skills, or
486
+ * with those other tags taking people, the real sustained service is lower, so the cap is generous:
487
+ * it can only fail to lower an optimistic simulated hour, never push a plan above what the simulation
488
+ * itself needs. Exact for one tag and a pool that all covers it.
489
+ */
490
+ const sustained = (s, n) => {
491
+ let lambda = 0;
492
+ let work = 0;
493
+ let target = Infinity;
494
+ for (const g of patient) {
495
+ const rate = drawn[s].rate[g];
496
+ lambda += rate;
497
+ work += rate * prep.meanHandle[g] * prep.tags[g].cost;
498
+ target = Math.min(target, prep.tags[g].profile.targetWaitMs);
499
+ }
500
+ if (lambda <= 0)
501
+ return 1;
502
+ return (0, erlang_1.erlangA)(n, { lambda, meanHandleMs: work / lambda, meanPatienceMs: Infinity, targetMs: target })
503
+ .serviceLevel;
504
+ };
505
+ /**
506
+ * What a seed counts for at n people, if its drawn rate is the rate all peak long (forecast error
507
+ * lasts longer than an hour). A seed whose never-abandoning work is at least n is a failed hour —
508
+ * at that rate the queue only grows, and the following hours inherit it. Below that, its
509
+ * never-abandoning tags count no better than the steady state at that rate when the error put it
510
+ * above the forecast: a single simulated hour opens with an empty queue, which a near-full floor
511
+ * takes hours to build, so on its own it reads a sustained peak as better served than it will be.
512
+ * (At or under the forecast the simulated hour stands: it agrees with Erlang C there.)
513
+ */
514
+ const counted = (s, n) => {
515
+ const r = run(s, n);
516
+ const served = Float64Array.from(r.served);
517
+ if (n < shortFloors[s])
518
+ for (const g of patient)
519
+ served[g] = 0;
520
+ else if (above[s]) {
521
+ const cap = sustained(s, n);
522
+ for (const g of patient)
523
+ served[g] = Math.min(served[g], cap * r.arrived[g]);
524
+ }
525
+ return { served, arrived: r.arrived };
526
+ };
527
+ const perSeed = [];
528
+ /** Each answer minus the Erlang A seed of that seed's own drawn load: how far the bracket is off. */
529
+ const offsets = [];
530
+ let capped = false;
531
+ for (let s = 0; s < seedCount; s++) {
532
+ // The seed is a function of the load (and, chained, of the interval), not of the position in the
533
+ // list: the same load always gets the same draws, so memoised and fresh answers agree.
534
+ const rand = (0, distributions_1.createPrng)(hashSeed(baseSeed, seedKey, s));
535
+ // Forecast error, stratified: seed s takes the rate factor at its own stratum of the Gamma (each
536
+ // tag's strata in a different order), so the seeds see the error's whole range instead of whatever
537
+ // as many random draws happen to give — the likely head count depends on its upper tail.
538
+ const factors = prep.tags.map((_, g) => (0, distributions_1.gammaMeanOneQuantile)(k, strata[(s + g * 7) % seedCount]));
539
+ const tasks = (0, simulation_1.drawTasks)(offered, prep.tags, window, k, rand, carryIn ? carryIn[inherit(s)] : null, factors);
540
+ drawn.push(tasks);
541
+ runs.push(new Map());
542
+ floors.push(stableFloor(tasks.rate, prep, judged, spread));
543
+ shortFloors.push(stableFloor(tasks.rate, prep, patient));
544
+ above.push(patient.some((g) => tasks.rate[g] * lengthMs > offered[g] * (1 + 1e-9)));
545
+ if (judged.every((g) => tasks.measuredByTag[g] === 0))
546
+ perSeed.push(0);
547
+ else {
548
+ // Start from Erlang A on this seed's own drawn rate (the overdispersion draw moves a seed's
549
+ // answer by far more than its arrivals' timing does), corrected by how far it was off so far.
550
+ const own = seedFor(Array.from(tasks.rate, (r) => r * lengthMs), prep, max);
551
+ const offset = offsets.length > 0 ? [...offsets].sort((a, b) => a - b)[offsets.length >> 1] : 0;
552
+ const found = search((n) => {
553
+ const r = run(s, n);
554
+ return meets(r.served, r.arrived, prep, judged);
555
+ }, own + offset, floors[s], max);
556
+ capped || (capped = found.capped);
557
+ perSeed.push(found.n);
558
+ offsets.push(found.n - own);
559
+ }
560
+ // Adaptive stop: enough seeds once the pooled service level near the answer is pinned down.
561
+ const count = s + 1;
562
+ if (adaptive && count >= minSeeds && count < seedCount && (count - minSeeds) % 4 === 0) {
563
+ const at = Math.max(1, Math.ceil((0, stats_1.quantileSorted)([...perSeed].sort((a, b) => a - b), 0.5)));
564
+ const settled = judged.every((g) => halfWidth(drawn.map((_, j) => counted(j, at).served[g]), drawn.map((_, j) => counted(j, at).arrived[g])) < exports.SERVICE_HALF_WIDTH);
565
+ if (settled)
566
+ break;
567
+ }
568
+ }
569
+ const seeds = drawn.length;
570
+ simulations += seeds;
571
+ // Likely: the fewest people who meet the target over all seeds together — on average, allowing for
572
+ // forecast error (the rate noise), which is the expected share served in time Erlang C staffs to.
573
+ // One hour's service level is skewed (a bad hour is very bad), so the median of per-seed answers
574
+ // sits a person under it even on Poisson arrivals; with the rate noised, the busier draws bring more
575
+ // arrivals too and pull further. Low and high are the seeds' own spread.
576
+ const pooled = (n) => {
577
+ const served = new Float64Array(nTags);
578
+ const arrived = new Float64Array(nTags);
579
+ for (let s = 0; s < seeds; s++) {
580
+ const one = counted(s, n);
581
+ for (const g of judged) {
582
+ served[g] += one.served[g];
583
+ arrived[g] += one.arrived[g];
584
+ }
585
+ }
586
+ return { served, arrived };
587
+ };
588
+ const anyArrivals = drawn.some((tasks) => judged.some((g) => tasks.measuredByTag[g] > 0));
589
+ const sorted = [...perSeed].sort((a, b) => a - b);
590
+ const expectedRate = offered.map((v) => v / lengthMs);
591
+ const best = anyArrivals
592
+ ? search((n) => {
593
+ const sums = pooled(n);
594
+ return meets(sums.served, sums.arrived, prep, judged);
595
+ }, Math.max(1, Math.ceil((0, stats_1.quantileSorted)(sorted, 0.5))), stableFloor(expectedRate, prep, judged, spread), max)
596
+ : { n: 0, capped: false };
597
+ capped || (capped = best.capped);
598
+ const likely = best.n;
599
+ const productive = {
600
+ low: Math.min(likely, Math.floor((0, stats_1.quantileSorted)(sorted, 0.1))),
601
+ likely,
602
+ high: Math.max(likely, Math.ceil((0, stats_1.quantileSorted)(sorted, 0.9))),
603
+ };
604
+ const atLikely = pooled(likely);
605
+ const serviceByTag = {};
606
+ for (const g of judged) {
607
+ const share = atLikely.arrived[g] > 0 ? atLikely.served[g] / atLikely.arrived[g] : 1;
608
+ serviceByTag[prep.tags[g].profile.tag] = Math.round(share * 1000) / 1000;
609
+ }
610
+ const team = teamOf(likely);
611
+ const toShift = (n) => Math.ceil(n / (1 - shrinkage) - 1e-9);
612
+ const need = {
613
+ productive,
614
+ onShift: { low: toShift(productive.low), likely: toShift(productive.likely), high: toShift(productive.high) },
615
+ serviceByTag,
616
+ uncovered: [],
617
+ erlangSeed,
618
+ method: 'simulation',
619
+ capped,
620
+ exceedsPool: team.some((heads, p) => heads > prep.counts[p]),
621
+ };
622
+ const carryOut = prep.chained ? drawn.map((_, s) => run(s, likely).carry) : null;
623
+ return { need, carryOut };
624
+ };
625
+ let chain = [];
626
+ const boosted = Math.max(maxSeeds, exports.BACKLOG_SEEDS);
627
+ const out = [];
628
+ const overBudget = () => options.budgetMs !== undefined && Date.now() - started > options.budgetMs;
629
+ const skip = (startMs, uncovered) => {
630
+ incomplete = true;
631
+ chain = [];
632
+ return quiet(startMs, uncovered, 'skipped');
633
+ };
634
+ const one = (interval, index) => {
635
+ // Chained hours never share a simulation, so they are simulated at their own load, not the grid's.
636
+ const expected = prep.tags.map((t) => {
637
+ const value = interval.arrivals[t.profile.tag] ?? 0;
638
+ return prep.chained ? (value > 0 ? Math.round(value * 1e6) / 1e6 : 0) : quantize(value, step);
639
+ });
640
+ const busy = expected.map((v, g) => (v > 0 ? g : -1)).filter((g) => g >= 0);
641
+ const uncovered = busy.filter((g) => !prep.pool.some((s) => s[g] >= 0)).map((g) => prep.tags[g].profile.tag);
642
+ // A chain holds only across back-to-back intervals.
643
+ let carryIn = carries && interval.startMs === carriedTo ? carries : null;
644
+ if (!carryIn)
645
+ chain = [];
646
+ carries = null;
647
+ carriedTo = interval.startMs + lengthMs;
648
+ const continues = prep.chained && intervals[index + 1]?.startMs === carriedTo;
649
+ // Judged here: tags with new work somebody can take, and tags with work handed over still in time.
650
+ const handed = new Set();
651
+ for (const carry of carryIn ?? [])
652
+ carry.judge.forEach((j, i) => j && handed.add(carry.tag[i]));
653
+ const judged = prep.tags
654
+ .map((_, g) => g)
655
+ .filter((g) => (busy.includes(g) && prep.pool.some((s) => s[g] >= 0)) || handed.has(g));
656
+ if (judged.length === 0) {
657
+ // Nothing to judge: whatever was left over (already past its target) runs down or gives up.
658
+ if (carryIn)
659
+ carries = carryIn.map((c) => (0, simulation_1.ageCarry)(c, lengthMs));
660
+ chain = [];
661
+ return quiet(interval.startMs, uncovered, 'none');
662
+ }
663
+ const key = expected.join(',');
664
+ if (!prep.chained) {
665
+ const hit = memo.get(key);
666
+ if (hit) {
667
+ cacheHits += 1;
668
+ return { startMs: interval.startMs, ...hit, uncovered };
669
+ }
670
+ }
671
+ if (overBudget())
672
+ return skip(interval.startMs, uncovered);
673
+ // Uncovered tags' work would only sit in a queue nobody reads: it is neither drawn nor seeded.
674
+ const offered = expected.map((v, g) => (judged.includes(g) ? v : 0));
675
+ const seedKey = prep.chained ? `${key}@${interval.startMs}` : key;
676
+ // A backlog hour — carried-in work at least half its work — hangs on rare big-backlog days, which
677
+ // twenty seeds mostly miss. It is read on more seeds, and so are the two hours that built the backlog
678
+ // (re-read now, so the backlog hour opens with as many trajectories as it has seeds).
679
+ const work = newWork(interval.arrivals);
680
+ let carried = 0;
681
+ for (const carry of carryIn ?? []) {
682
+ for (let i = 0; i < carry.tag.length; i++)
683
+ carried += carry.handle[i] * prep.tags[carry.tag[i]].cost;
684
+ }
685
+ if (carryIn)
686
+ carried /= carryIn.length;
687
+ const backlog = prep.chained && carryIn !== null && carried >= BACKLOG_SHARE * (carried + work);
688
+ if (backlog) {
689
+ const builders = chain.slice(-2).filter((e) => !e.boosted);
690
+ if (builders.length > 0) {
691
+ let feed = builders[0].carryIn;
692
+ for (const e of builders) {
693
+ // The re-read is two or three solves on the boosted seed count: checked before each one,
694
+ // so a backlog hour cannot run a nearly spent budget far past its end.
695
+ if (overBudget())
696
+ return skip(interval.startMs, uncovered);
697
+ const again = solve(e.offered, e.judged, e.seedKey, feed, e.continues, boosted, e.spread);
698
+ out[e.index] = { startMs: intervals[e.index].startMs, ...again.need, uncovered: e.uncovered };
699
+ e.carryIn = feed;
700
+ e.boosted = true;
701
+ feed = again.carryOut;
702
+ }
703
+ carryIn = feed;
704
+ if (overBudget())
705
+ return skip(interval.startMs, uncovered);
706
+ }
707
+ }
708
+ const seedCount = backlog ? boosted : maxSeeds;
709
+ // A long-target tag's floor: its load averaged over the hours its target spans (as far as the chain
710
+ // goes), not this hour's alone — work arriving now may be done in the hours after.
711
+ const spread = prep.tags.map((t, g) => {
712
+ if (!prep.long[g] || !(offered[g] > 0))
713
+ return 1;
714
+ const span = Math.max(1, Math.ceil(t.profile.targetWaitMs / lengthMs));
715
+ let sum = 0;
716
+ let count = 0;
717
+ for (let i = index; i < intervals.length && i < index + span; i++) {
718
+ if (i > index && intervals[i].startMs !== intervals[i - 1].startMs + lengthMs)
719
+ break;
720
+ sum += Math.max(0, intervals[i].arrivals[t.profile.tag] ?? 0);
721
+ count += 1;
722
+ }
723
+ return sum / count / offered[g];
724
+ });
725
+ const { need, carryOut } = solve(offered, judged, seedKey, carryIn, continues, seedCount, spread);
726
+ if (prep.chained) {
727
+ chain.push({ index, offered, judged, seedKey, carryIn, continues, uncovered, boosted: backlog, spread });
728
+ if (chain.length > 2)
729
+ chain.shift();
730
+ }
731
+ carries = carryOut;
732
+ if (!prep.chained)
733
+ memo.set(key, need);
734
+ return { startMs: interval.startMs, ...need, uncovered };
735
+ };
736
+ intervals.forEach((interval, index) => {
737
+ out[index] = one(interval, index);
738
+ });
739
+ return { intervals: out, ms: Date.now() - started, simulations, cacheHits, incomplete };
740
+ }
741
+ exports.staffingNeed = staffingNeed;
742
+ /** FNV-1a over the base seed, the load key and the seed index. */
743
+ function hashSeed(base, key, s) {
744
+ let h = 0x811c9dc5 ^ base;
745
+ const text = `${key}#${s}`;
746
+ for (let i = 0; i < text.length; i++) {
747
+ h ^= text.charCodeAt(i);
748
+ h = Math.imul(h, 0x01000193);
749
+ }
750
+ return h >>> 0;
751
+ }
752
+ /** People on shift for a volume at a fixed rate: units ÷ units per person-hour ÷ (1 − shrinkage), per hour. */
753
+ function rateNeed(unitsPerHour, unitsPerPersonHour, shrinkage) {
754
+ if (unitsPerHour <= 0)
755
+ return 0;
756
+ if (!(unitsPerPersonHour > 0))
757
+ throw new RangeError('unitsPerPersonHour must be positive');
758
+ return unitsPerHour / unitsPerPersonHour / (1 - (0, stats_1.clamp)(shrinkage, 0, 0.9));
759
+ }
760
+ exports.rateNeed = rateNeed;
761
+ /** The series already counts people. */
762
+ function headcountNeed(value) {
763
+ return Math.max(0, value);
764
+ }
765
+ exports.headcountNeed = headcountNeed;