assignment-user-matcher 1.15.0 → 1.16.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 (70) hide show
  1. package/README.md +378 -9
  2. package/dist/index.d.ts +5 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +6 -1
  5. package/dist/learning/atomic-ingestion.d.ts +11 -0
  6. package/dist/learning/atomic-ingestion.d.ts.map +1 -0
  7. package/dist/learning/atomic-ingestion.js +187 -0
  8. package/dist/learning/auto-weights.d.ts +13 -2
  9. package/dist/learning/auto-weights.d.ts.map +1 -1
  10. package/dist/learning/auto-weights.js +203 -35
  11. package/dist/learning/features.d.ts +5 -3
  12. package/dist/learning/features.d.ts.map +1 -1
  13. package/dist/learning/features.js +105 -4
  14. package/dist/learning/policy.d.ts +57 -0
  15. package/dist/learning/policy.d.ts.map +1 -0
  16. package/dist/learning/policy.js +71 -0
  17. package/dist/managers/LearningManager.d.ts +312 -35
  18. package/dist/managers/LearningManager.d.ts.map +1 -1
  19. package/dist/managers/LearningManager.js +1006 -168
  20. package/dist/matcher.class.d.ts +98 -11
  21. package/dist/matcher.class.d.ts.map +1 -1
  22. package/dist/matcher.class.js +247 -40
  23. package/dist/scheduling/constraints/cost.d.ts.map +1 -1
  24. package/dist/scheduling/constraints/cost.js +3 -2
  25. package/dist/scheduling/constraints/employee-scope.d.ts +5 -0
  26. package/dist/scheduling/constraints/employee-scope.d.ts.map +1 -0
  27. package/dist/scheduling/constraints/employee-scope.js +157 -0
  28. package/dist/scheduling/constraints/notice.d.ts.map +1 -1
  29. package/dist/scheduling/constraints/notice.js +8 -5
  30. package/dist/scheduling/constraints/rest-days.d.ts.map +1 -1
  31. package/dist/scheduling/constraints/rest-days.js +6 -6
  32. package/dist/scheduling/cost.d.ts.map +1 -1
  33. package/dist/scheduling/cost.js +2 -1
  34. package/dist/scheduling/engine/construction.d.ts +11 -3
  35. package/dist/scheduling/engine/construction.d.ts.map +1 -1
  36. package/dist/scheduling/engine/construction.js +31 -6
  37. package/dist/scheduling/engine/objective.d.ts +4 -4
  38. package/dist/scheduling/engine/objective.d.ts.map +1 -1
  39. package/dist/scheduling/engine/objective.js +12 -4
  40. package/dist/scheduling/engine/propagation.js +2 -1
  41. package/dist/scheduling/engine/search.d.ts +1 -0
  42. package/dist/scheduling/engine/search.d.ts.map +1 -1
  43. package/dist/scheduling/engine/search.js +1 -1
  44. package/dist/scheduling/engine/state.d.ts.map +1 -1
  45. package/dist/scheduling/engine/state.js +4 -0
  46. package/dist/scheduling/index.d.ts +1 -1
  47. package/dist/scheduling/index.d.ts.map +1 -1
  48. package/dist/scheduling/model.d.ts +1 -1
  49. package/dist/scheduling/model.d.ts.map +1 -1
  50. package/dist/scheduling/model.js +184 -42
  51. package/dist/scheduling/operations.d.ts +4 -0
  52. package/dist/scheduling/operations.d.ts.map +1 -1
  53. package/dist/scheduling/operations.js +36 -16
  54. package/dist/scheduling/provenance.d.ts +1 -1
  55. package/dist/scheduling/provenance.d.ts.map +1 -1
  56. package/dist/scheduling/provenance.js +16 -2
  57. package/dist/scheduling/scheduler.class.d.ts +1 -1
  58. package/dist/scheduling/scheduler.class.d.ts.map +1 -1
  59. package/dist/scheduling/scheduler.class.js +5 -3
  60. package/dist/scheduling/time.d.ts +2 -0
  61. package/dist/scheduling/time.d.ts.map +1 -1
  62. package/dist/scheduling/time.js +26 -1
  63. package/dist/scheduling/types.d.ts +78 -3
  64. package/dist/scheduling/types.d.ts.map +1 -1
  65. package/dist/types/matcher.d.ts +309 -4
  66. package/dist/types/matcher.d.ts.map +1 -1
  67. package/dist/utils/keys.d.ts +12 -2
  68. package/dist/utils/keys.d.ts.map +1 -1
  69. package/dist/utils/keys.js +35 -2
  70. package/package.json +2 -1
package/README.md CHANGED
@@ -800,6 +800,58 @@ type Options = {
800
800
 
801
801
  // TTL for archived episodes awaiting late external feedback in ms.
802
802
  learningFeedbackTtlMs?: number; // Default: 604800000 (7 days)
803
+
804
+ // SGD update rule. 'normalized' bounds the step by the active feature
805
+ // vector's squared norm; 'raw' is the pre-1.16 rule and diverges once
806
+ // several features fire at once.
807
+ learningUpdateMode?: 'normalized' | 'raw'; // Default: 'normalized'
808
+
809
+ // L2 weight decay applied per update.
810
+ learningL2?: number; // Default: 0
811
+
812
+ // Clip on the L2 norm of a single update.
813
+ learningMaxUpdateNorm?: number; // Default: 1
814
+
815
+ // Absolute cap on any single learned weight.
816
+ learningMaxWeightMagnitude?: number; // Default: 100
817
+
818
+ // Cap on the learning layer's contribution to effective priority.
819
+ // Unset = unbounded (pre-1.16 behaviour).
820
+ learningMaxBoost?: number;
821
+
822
+ // What counts as one observation for per-tag evidence.
823
+ learningRewardAccounting?: 'per-event' | 'per-attempt'; // Default: 'per-event'
824
+
825
+ // Candidate selection policy. 'epsilon-greedy' logs a recoverable
826
+ // propensity on every committed decision; 'jitter' is the pre-1.16
827
+ // unlogged score noise.
828
+ learningExplorationPolicy?: 'greedy' | 'epsilon-greedy' | 'jitter'; // Default: 'jitter'
829
+
830
+ // Random source for exploration; inject for reproducible runs.
831
+ learningRng?: () => number; // Default: Math.random
832
+
833
+ // Opt-in multi-target reward modelling.
834
+ learningTargets?: {
835
+ targets?: Array<'acceptance' | 'successGivenAcceptance' | 'quality'>;
836
+ acceptanceWeight?: number;
837
+ successWeight?: number;
838
+ qualityWeight?: number;
839
+ learningRates?: Partial<Record<'acceptance' | 'successGivenAcceptance' | 'quality', number>>;
840
+ systemFaultCountsAsFailure?: boolean; // Default: false
841
+ };
842
+
843
+ // Emit observed worker-performance features (batch-loaded once per
844
+ // worker per matching pass, never per candidate).
845
+ enableLearningPerformanceFeatures?: boolean; // Default: false
846
+ learningPerformancePriorStrength?: number; // Default: 5
847
+
848
+ // Maximum age of an outcome/feedback event relative to its attempt.
849
+ // Later events are rejected and counted as staleEvents.
850
+ learningMaxFeedbackAgeMs?: number; // Default: learningFeedbackTtlMs
851
+
852
+ // Validation bounds applied before anything is written.
853
+ learningMaxSignalMagnitude?: number; // Default: 1e6
854
+ learningMaxRewardMagnitude?: number; // Default: 100
803
855
  };
804
856
  ```
805
857
 
@@ -1007,10 +1059,29 @@ How it works:
1007
1059
  eligible candidate (tag matches, normalized skill weights, tag overlap, and
1008
1060
  optional `embedding` cosine similarity if both user and assignment carry an
1009
1061
  `embedding: number[]` field).
1010
- 2. Candidates are ranked by `combinedPriority + boostFactor * predictedReward`.
1011
- 3. The decision context is stored, and lifecycle outcomes (`accept`,
1012
- `complete`, `reject`, `expire`, `fail`) feed rewards back into the model via
1013
- online SGD updates — fully automatic, no training pipeline needed.
1062
+ 2. Candidates are ranked by `combinedPriority + boostFactor * predictedReward`
1063
+ and selected by an explicit policy.
1064
+ 3. **The decision context is committed only for the worker who actually wins
1065
+ the claim**, under a unique attempt id. Lifecycle outcomes (`accept`,
1066
+ `complete`, `reject`, `expire`, `fail`) feed rewards back into that attempt
1067
+ via online SGD updates — fully automatic, no training pipeline needed.
1068
+
1069
+ Four invariants are worth knowing, because they are what the layer's
1070
+ correctness rests on:
1071
+
1072
+ - **One decision per committed attempt.** A candidate that was scored but lost
1073
+ the assignment — to another worker under fair arbitration, or to another
1074
+ process at the claim gate — leaves no decision behind. An assignment that is
1075
+ rejected and rematched opens a *second, independent* attempt with its own id;
1076
+ feedback for the first can never reach the second.
1077
+ - **Ingestion is idempotent.** Every outcome and every feedback call is gated
1078
+ on the attempt's applied-event set, so a redelivered message applies once and
1079
+ counts as evidence once. `getLearningStats()` reports `duplicateEvents`,
1080
+ `staleEvents`, `orphanEvents`, `supersededEvents`, `ambiguousFeedback` and
1081
+ `invalidFeedback` so rejected traffic is visible rather than silent.
1082
+ - **Missing means unknown.** Absent quality feedback trains nothing; it is
1083
+ never a zero label. An empty or malformed signal map is rejected whole.
1084
+ - **Manual assignment never trains.** `assignToUser()` records no decision.
1014
1085
 
1015
1086
  ```typescript
1016
1087
  const matcher = new AssignmentMatcher(redisClient, {
@@ -1093,6 +1164,172 @@ tune `learningBoostFactor` / `learningExplorationRate` for your workload. For
1093
1164
  domain-specific setups (custom embeddings, business features), supply a
1094
1165
  `learningFeatureExtractor`.
1095
1166
 
1167
+ ### Stable Model Updates
1168
+
1169
+ The SGD rule is `learningUpdateMode`, and it defaults to `'normalized'`:
1170
+
1171
+ ```typescript
1172
+ const matcher = new AssignmentMatcher(redisClient, {
1173
+ enableLearning: true,
1174
+ learningUpdateMode: 'normalized', // default since 1.16
1175
+ learningL2: 0, // optional weight decay
1176
+ learningMaxUpdateNorm: 1, // clip on a single update
1177
+ learningMaxWeightMagnitude: 100, // absolute cap on any weight
1178
+ learningMaxBoost: 60, // cap the learning layer's ranking influence
1179
+ });
1180
+ ```
1181
+
1182
+ The pre-1.16 rule (`'raw'`, `w += lr * error * x`) is unstable once several
1183
+ features fire at once: with `k` active unit features every step overshoots by a
1184
+ factor of `k`, so the error alternates sign and grows. Twenty-two unit features
1185
+ at the default learning rate is already enough — 40 identical reward-1 samples
1186
+ drive the prediction past -1000 instead of toward 1. Normalizing by the active
1187
+ vector's squared norm makes one step land on the observation regardless of how
1188
+ many features fired, and the norm clip and weight cap bound the rest.
1189
+ `'raw'` remains available for reproducing an existing model, and is not
1190
+ recommended for new deployments.
1191
+
1192
+ `learningMaxBoost` matters for a different reason: predicted reward and
1193
+ business priority are in unrelated units, so an unbounded boost can silently
1194
+ outrank an operator's priority or an SLA band. It is unset by default (the
1195
+ pre-1.16 behaviour); set it, and the learned contribution can never leave
1196
+ `±learningMaxBoost`.
1197
+
1198
+ Model reads are bounded too — an update reads only the weights it touches
1199
+ (`HMGET` over the active features), not the whole model hash, so cost is
1200
+ `O(active features)` regardless of how large the feature space grows. Batch
1201
+ imports via `trainLearningSamples()` process in bounded chunks and re-read per
1202
+ chunk, so a long import cannot keep accumulating against a snapshot the live
1203
+ model has already moved away from.
1204
+
1205
+ ### Modelling Acceptance and Success Separately
1206
+
1207
+ A single scalar reward cannot distinguish a worker who takes everything and
1208
+ finishes nothing from one who is selective and reliable — both can average out
1209
+ the same. `learningTargets` models them apart:
1210
+
1211
+ ```typescript
1212
+ const matcher = new AssignmentMatcher(redisClient, {
1213
+ enableLearning: true,
1214
+ learningTargets: {
1215
+ targets: ['acceptance', 'successGivenAcceptance', 'quality'],
1216
+ successWeight: 1,
1217
+ qualityWeight: 0.5,
1218
+ learningRates: { quality: 0.05 },
1219
+ // A platform-side cancellation is not the worker's failure. Default
1220
+ // false: it produces no success label at all.
1221
+ systemFaultCountsAsFailure: false,
1222
+ },
1223
+ });
1224
+ ```
1225
+
1226
+ Each target gets its own model hash and its own label timing:
1227
+
1228
+ | Target | Denominator | Label | Missing data |
1229
+ | --- | --- | --- | --- |
1230
+ | `acceptance` | one per committed attempt | 1 on accept; 0 on reject or **pre-acceptance** response expiry | attempt still open |
1231
+ | `successGivenAcceptance` | one per *accepted* attempt | 1 on complete; 0 on fail or **post-acceptance** expiry | no label when flagged a system fault |
1232
+ | `quality` | one per quality observation | normalized `quality` signal, clamped to [0, 1] | **no update at all** |
1233
+
1234
+ Component predictions come back as calibrated probabilities; the combined
1235
+ utility is `acceptanceWeight * P(accept) + P(accept) * (successWeight *
1236
+ P(success|accept) + qualityWeight * E[quality])` and is deliberately *not*
1237
+ presented as a probability. Corrections revise a label rather than adding a
1238
+ second one — see `learningRewardAccounting` below.
1239
+
1240
+ When `learningTargets` is unset (the default) the layer keeps the legacy
1241
+ behaviour: one model, one scalar reward per lifecycle outcome.
1242
+
1243
+ ### Evidence Accounting
1244
+
1245
+ `learningRewardAccounting` decides what one "observation" means for the per-tag
1246
+ statistics that drive automatic routing weights:
1247
+
1248
+ - `'per-event'` (default, legacy): every lifecycle outcome and every feedback
1249
+ call is one observation. An attempt that accepts, completes and then receives
1250
+ a CSAT score counts three times.
1251
+ - `'per-attempt'`: one observation per committed attempt, written at the
1252
+ terminal outcome with the attempt's accrued reward. Late feedback *revises*
1253
+ that observation instead of adding another.
1254
+
1255
+ `'per-attempt'` is what the veto sample floors actually assume — they are
1256
+ supposed to count independent attempts, and correlated events inflating the
1257
+ count is how a tag reaches a "20 sample" bar on five real assignments.
1258
+
1259
+ ### Explicit Exploration and Propensity Logging
1260
+
1261
+ `learningExplorationPolicy` selects how candidates are picked:
1262
+
1263
+ ```typescript
1264
+ const matcher = new AssignmentMatcher(redisClient, {
1265
+ enableLearning: true,
1266
+ learningExplorationPolicy: 'epsilon-greedy',
1267
+ learningExplorationRate: 0.05,
1268
+ learningRng: seededRng(1234), // inject for reproducible tests
1269
+ });
1270
+
1271
+ const decision = await matcher.getLearningDecision('assignment-123');
1272
+ // { decisionId, userId, features, predictedReward, propensity, policy, candidateCount, ... }
1273
+ ```
1274
+
1275
+ Under `'epsilon-greedy'`, selecting `k` candidates is modelled as `k`
1276
+ sequential conditional choices over the admissible set that remains, and each
1277
+ committed decision records the probability it was actually chosen with. For a
1278
+ unique leader among `K` admissible candidates that probability is
1279
+ `1 - ε + ε/K`, and every other candidate's is `ε/K`. That number is what
1280
+ off-policy evaluation (IPS, doubly-robust) needs; the legacy `'jitter'` policy
1281
+ — independent random noise added to the score — perturbs the ranking without
1282
+ any recoverable probability, so the logs it produces cannot be evaluated
1283
+ offline at all. `'jitter'` remains the default for backward compatibility.
1284
+
1285
+ One honest caveat: under `fairness: 'best-match'` and the other fair modes,
1286
+ allocation is a constrained *joint* decision across workers, and a per-worker
1287
+ epsilon-greedy probability is not the probability of the final allocation.
1288
+ Treat fair-mode logs as needing an allocation-aware estimator or a randomized
1289
+ online comparison, not as ordinary contextual-bandit logs.
1290
+
1291
+ Exploration never widens eligibility: it chooses among candidates that already
1292
+ passed every hard rule, and it is disabled entirely in shadow mode.
1293
+
1294
+ ### Worker Performance Features
1295
+
1296
+ By default the feature vector is assignment-side plus the worker's *declared*
1297
+ tags, which means two workers with identical declared tags produce identical
1298
+ features for a given assignment — the model has nothing to learn about *who*
1299
+ should get the work. `enableLearningPerformanceFeatures` adds observed
1300
+ behaviour:
1301
+
1302
+ ```typescript
1303
+ const matcher = new AssignmentMatcher(redisClient, {
1304
+ enableLearning: true,
1305
+ enableLearningPerformanceFeatures: true,
1306
+ learningPerformancePriorStrength: 5, // shrinkage toward the team prior
1307
+ });
1308
+ ```
1309
+
1310
+ New features: `perf:accept`, `perf:success`, `perf:support`, `perf:speed`,
1311
+ `perf:speedKnown`, `load:backlog`, `difficulty`, `complexity`,
1312
+ `sla:remainingFraction`, `sla:urgency`, and the interactions
1313
+ `x:urgency*speed`, `x:difficulty*success`, `x:load*complexity`.
1314
+
1315
+ Two properties are load-bearing:
1316
+
1317
+ - Rates are **shrunk toward the team prior**, so a worker with no history reads
1318
+ as average rather than as a failure. An unjustifiably pessimistic estimate is
1319
+ how a new worker starves.
1320
+ - Aggregates are **batch-loaded once per worker per matching pass** — one
1321
+ `HGETALL` — never per candidate. Enabling the feature does not add a Redis
1322
+ round trip per candidate pair.
1323
+
1324
+ `sla:urgency` uses time actually remaining at the decision timestamp, not the
1325
+ originally configured duration: an assignment with a one-hour deadline that has
1326
+ been queued 55 minutes is urgent, and the configured duration alone cannot say
1327
+ so.
1328
+
1329
+ Enabling this option also stamps an accept timestamp on non-SLA assignments
1330
+ (handling time has to be measured from something). With it off, stored JSON is
1331
+ unchanged.
1332
+
1096
1333
  ### Automatic Routing Weights (RL-Generated Tags/Weights)
1097
1334
 
1098
1335
  Beyond re-ranking, the learning layer can fully automate `routingWeights`
@@ -1112,12 +1349,68 @@ bandit policy.
1112
1349
  - `policy: 'thompson'`: samples from the per-tag posterior when mapping to a
1113
1350
  weight; the veto decision uses the deterministic mean, never the draw.
1114
1351
 
1352
+ **Uncertainty.** Before 1.16 the standard error came straight from the observed
1353
+ moments, so five identical observations produced variance 0 and a
1354
+ zero-width confidence interval — total certainty from five samples, on which
1355
+ the `'confidence'` policy would hard-veto. The posterior is now prior-backed:
1356
+
1357
+ ```typescript
1358
+ autoRoutingWeights: {
1359
+ policy: 'confidence',
1360
+ rewardModel: 'gaussian', // or 'bernoulli' for genuine success indicators
1361
+ rewardRange: [-1, 1], // sets the default prior variance and the Bernoulli mapping
1362
+ priorStrength: 2, // pseudo-observations of prior weight
1363
+ // priorVariance defaults to ((max - min) / 4) ** 2
1364
+ }
1365
+ ```
1366
+
1367
+ `'bernoulli'` uses a Beta-Bernoulli posterior over rewards rescaled into
1368
+ [0, 1], with Thompson draws taken from the Beta itself. It is only sound when
1369
+ the reward genuinely is a success indicator — applying Bernoulli formulas to
1370
+ arbitrary continuous rewards is the error the explicit option exists to make
1371
+ visible rather than implicit.
1372
+
1373
+ **Evidence is counted in independent attempts, not observations.** With
1374
+ `decayHalfLifeMs` set, the decayed weight sum is *not* a sample size: scaling
1375
+ every weight equally leaves it looking like fewer observations than were
1376
+ actually seen. `LearningTagStat` therefore carries `attempts` (never decayed)
1377
+ and `effectiveSampleSize` (the Kish quantity `sum(w)² / sum(w²)`), and sample
1378
+ floors are judged against those, in that order of preference. Likewise
1379
+ `minTotalSamples` is judged against distinct attempts, so one assignment
1380
+ carrying five tags is one attempt, not five.
1381
+
1382
+ **Explainability.** `explainLearnedRoutingWeights(userId)` returns the same
1383
+ synthesis with its reasoning attached — posterior estimate and uncertainty,
1384
+ credible bounds, independent attempts, effective sample size, last
1385
+ observation, decay settings, and for a lapsed veto when it will be reassessed:
1386
+
1387
+ ```typescript
1388
+ const rows = await matcher.explainLearnedRoutingWeights('user-1');
1389
+ // [{ tag: 'english', weight: 0, decision: 'veto', estimate: -0.71,
1390
+ // uncertainty: 0.12, lowerBound: -0.95, upperBound: -0.47,
1391
+ // attempts: 34, lastObservedAt: 1757... }, ...]
1392
+ ```
1393
+
1394
+ `decision` is one of `'veto' | 'scored' | 'prior' | 'cooldown' |
1395
+ 'insufficient-evidence' | 'unobserved'`. The pure form is exported as
1396
+ `explainRoutingWeights`.
1397
+
1115
1398
  **Guardrails (all opt-in):**
1116
1399
 
1117
- - `minSamplesForVeto`: a learned weight-0 may only override a _manual_
1118
- (non-learned) weight after this many observations, preventing a few bad
1119
- rolls from silently starving a user. Defaults to `minSamples` (5) for
1120
- backward compatibility; 20 is a reasonable production floor.
1400
+ - `minSamplesForVeto`: a learned weight-0 requires this many independent
1401
+ attempts, preventing a few bad rolls from silently starving a user.
1402
+ Defaults to `minSamples` (5); 20 is a reasonable production floor. **Since
1403
+ 1.16 this floor applies to learned and manually-weighted tags alike** — a
1404
+ hard veto removes eligibility outright, and that consequence does not depend
1405
+ on where the previous weight came from. Set it and the bar rises for every
1406
+ tag; leave it unset and nothing changes.
1407
+ - `vetoCooldownMs`: how long after a tag's last observation a learned veto
1408
+ lapses and the tag returns at `priorWeight` for reassessment. A veto with no
1409
+ recovery path is permanent exclusion, and a worker who improved — or whose
1410
+ bad run was circumstantial — can never be re-evaluated. Prefer setting this
1411
+ over relying on decay alone.
1412
+ - `rewardModel` / `rewardRange` / `priorVariance` / `priorStrength`: the
1413
+ posterior over a tag's mean reward. See "Uncertainty" below.
1121
1414
  - `maxDeltaPerSync`: clamps how far any single learned weight can move per
1122
1415
  sync, avoiding oscillation.
1123
1416
  - `minTotalSamples`: skip users whose total evidence is still too thin.
@@ -1352,6 +1645,49 @@ Output includes:
1352
1645
  4. Top learned model weights
1353
1646
  5. Delta summary vs baseline (throughput, completion rate, quality)
1354
1647
 
1648
+ One caveat about this runner: it derives each worker's initial `routingWeights`
1649
+ directly from their latent skill, so the operator's configuration is already
1650
+ optimal and learning has little room to add anything. That is a useful
1651
+ **strong-baseline** case — a policy must not regress there — but it is not
1652
+ evidence of uplift.
1653
+
1654
+ ### Scenario Benchmark (policy comparison)
1655
+
1656
+ `benchmark:scenarios` is the runner that can actually fail a policy. It varies
1657
+ the conditions learning is supposed to help with, seeds every source of
1658
+ randomness including exploration and Thompson draws, gives every mode the
1659
+ identical workload and event-keyed outcome draws, and reports **paired**
1660
+ differences with confidence intervals rather than single-run numbers.
1661
+
1662
+ ```bash
1663
+ pnpm benchmark:scenarios -- --scenarios=cold-start,noisy-weights \
1664
+ --modes=off,legacy,corrected,confidence --seeds=5 \
1665
+ --users=40 --per-round=200 --rounds=8 --json=run.json
1666
+ ```
1667
+
1668
+ Scenarios: `accurate-weights` (strong baseline), `noisy-weights`,
1669
+ `cold-start`, `skill-drift`, `rare-specialist`, `multi-tag`,
1670
+ `delayed-feedback`, `contention`, `overload`.
1671
+
1672
+ Modes: `off`, `shadow`, `legacy` (the pre-1.16 configuration), `corrected`
1673
+ (normalized updates, per-attempt evidence, epsilon-greedy, performance
1674
+ features, multi-target), `ucb1`, `confidence`, `thompson`.
1675
+
1676
+ Reported per scenario: completed useful work per incoming task, mean quality,
1677
+ deadline misses, queue-age p50/p95/p99, allocation Gini, match latency
1678
+ p50/p95/p99 and throughput, reward observations per decision, acceptance Brier
1679
+ score and reliability bins, plus Redis commands, memory delta and model size.
1680
+ `--json` writes the raw per-run metrics along with runtime, hardware and seed
1681
+ provenance.
1682
+
1683
+ Read the results with the gates in mind: require positive paired uplift on the
1684
+ noisy/cold-start scenarios, **and** no material regression on the
1685
+ strong-baseline, deadline or overload scenarios. Materiality is a product SLO
1686
+ question, not a universal percentage. Shadow mode validates data and decisions;
1687
+ it does not establish causal uplift — that needs offline policy evaluation or a
1688
+ controlled online rollout, and because workers share queues, an experiment unit
1689
+ has to account for interference rather than assuming task-level independence.
1690
+
1355
1691
  ### Configuration Playbook (How To Choose)
1356
1692
 
1357
1693
  Use this quick guide based on your primary goal.
@@ -1695,7 +2031,22 @@ Break entitlements are checked against shift design: `unpaidBreakMinutes` (deduc
1695
2031
 
1696
2032
  **Overtime** is regulated separately from total working time where national law does so. `rules.overtime` defines the ordinary baseline (`ordinaryPerDayMinutes` / `ordinaryPerWeekMinutes`; a person's `contract.weeklyMinutes` overrides the weekly figure, so a part-timer's overtime starts at their agreed hours), caps the overtime portion per rolling 24h or per rolling window, and with `requiresConsent` makes any overtime conditional on the employee's recorded `overtimeConsent`. With `compensation: 'timeOff'`, each employee's period overtime accrues a `timeOffInLieu` entry in `result.ledger`.
1697
2033
 
1698
- **Contracted hours and part-time.** A person's contracted week is stated either as minutes (`contract.weeklyMinutes`) or as a fraction of full time (`contract.fte`, `0 < fte <= 1`, e.g. `0.5` for half-time). An `fte` resolves against `rules.contract.fullTimeWeeklyMinutes`, falling back to `rules.overtime.ordinaryPerWeekMinutes`; with neither the input is rejected rather than a working week guessed. The resolved week is read in one place (`ModelContext.contractedWeeklyMinutes`) by everything that needs it: the overtime baseline, pro-rata fairness (`proRataByContract`), and the **contract-hours objective**, which pulls every person with a contract towards `weekly × periodDays / 7` at the soft level (`objectives.contractHoursWeight`, default `1` point per hour of deviation, `0` to disable) — so a half-timer is planned half the hours of a full-timer instead of being filled to the statutory ceiling. Two optional bounds on `rules.contract`: `maxOverMinutes` (hard cap at contract plus the allowance; `0` means never over contract — omit when your `overtime` rule governs the surplus) and `maxUnderMinutes` (a shortfall beyond it is reported as a soft violation). `result.contractHours` / `ComplianceReport.contractHours` list planned against contracted minutes per person, and `rankCandidates` reports `contractDeltaMinutes` and ranks people with contract headroom ahead of those a shift would push over. Cover is a floor, not a ceiling: once every slot has its `minEmployees`, the solver keeps adding people to shifts that still have room (under `maxEmployees`, every hard rule intact) while the shift fits **inside** their contracted total, or while they are under a `minHoursForPeriod` floor — so two full-timers on a roster whose minimum cover is 56h are each planned their 40h rather than 28h. The ceiling for this pass is the contracted total **plus whatever `rules.contract.maxOverMinutes` already allows**, never a target to land nearest to: with no allowance stated, a half-timer on 15h of a 20h contract is not given a further 7.5h shift, because 2.5h over is not "closer" enough to be worth hours nobody asked for. State an allowance and the top-up plans into it, which is what lets a part-timer be filled at all when no shift is small enough to fit the room left. Set `objectives.fillToContract: false` (or a zero `contractHoursWeight`) to staff minimum cover only and let contracted hours merely distribute the demand; a `maxEmployees` on the template or a hard `maxOverMinutes` bounds the top-up either way.
2034
+ **Temporary demand.** A shift template is the standing rule; `demandOverrides` are the temporary ones — each bounded to an inclusive `from`/`to` date range (optionally to `daysOfWeek` inside it) and applied to every occurrence whose date falls in it. An override can replace `minEmployees`, `maxEmployees` (`null` removes it), `tagRequirements`, `tagMaximums` or `requiredTags`, add `extraEmployees` on top of whatever is in force, or set `runs` — whether the shift happens on those dates at all. `runs` works in **both** directions: `false` is a closure, and `true` opens the shift on dates the template's own `dates`/`daysOfWeek` excludes, so a weekday-only shift can take one weekend without widening the template and opening every weekend from then on. A date opened this way inherits the template's own shape unless the override states otherwise. Overrides fold in array order, later wins field by field, `extraEmployees` accumulates, and a minimum raised above the standing maximum lifts the maximum with it — "three at the peak" means three. The result is an ordinary `ShiftInstance` (with `demandLabel` naming the last labelled override that touched it), so the solver, `checkCompliance`, `explainCandidate`, `rankCandidates` and `expandShiftInstances` all read one headcount and none of them knows an override exists. The day after `to`, the shift is back to its standing shape without anybody editing it.
2035
+
2036
+ ```ts
2037
+ {
2038
+ id: 'till', name: 'Till', startTime: '09:00', endTime: '17:00', daysOfWeek: [1, 2, 3, 4, 5],
2039
+ minEmployees: 2, maxEmployees: 3,
2040
+ demandOverrides: [
2041
+ { from: '2026-12-14', to: '2026-12-24', label: 'Christmas peak', extraEmployees: 2 }, // 4 needed, 5 at most
2042
+ { from: '2026-12-19', to: '2026-12-19', label: 'Late opening', requiredTags: ['keyholder'] },
2043
+ { from: '2026-12-19', to: '2026-12-20', label: 'Christmas weekend', runs: true }, // Sat+Sun, this weekend only
2044
+ { from: '2026-12-25', to: '2026-12-26', label: 'Closed', runs: false },
2045
+ ],
2046
+ }
2047
+ ```
2048
+
2049
+ **Contracted hours and part-time.** A person's contracted week is stated either as minutes (`contract.weeklyMinutes`) or as a fraction of full time (`contract.fte`, `0 < fte <= 1`, e.g. `0.5` for half-time). An `fte` resolves against `rules.contract.fullTimeWeeklyMinutes`, falling back to `rules.overtime.ordinaryPerWeekMinutes`; with neither the input is rejected rather than a working week guessed. The resolved week is read in one place (`ModelContext.contractedWeeklyMinutes`) by everything that needs it: the overtime baseline, pro-rata fairness (`proRataByContract`), and the **contract-hours objective**, which pulls every person with a contract towards `weekly × periodDays / 7` at the soft level (`objectives.contractHoursWeight`, default `1` point per hour of deviation, `0` to disable) — so a half-timer is planned half the hours of a full-timer instead of being filled to the statutory ceiling. Two optional bounds on `rules.contract`: `maxOverMinutes` (hard cap at contract plus the allowance; `0` means never over contract — omit when your `overtime` rule governs the surplus) and `maxUnderMinutes` (a shortfall beyond it is reported as a soft violation). `result.contractHours` / `ComplianceReport.contractHours` list planned against contracted minutes per person, and `rankCandidates` reports `contractDeltaMinutes` and ranks people with contract headroom ahead of those a shift would push over. Cover is a floor, not a ceiling: once every slot has its `minEmployees`, the solver keeps adding people to shifts that state room for them — **room means `maxEmployees` above the minimum, and a shift that states no maximum has none** — while the shift fits **inside** their contracted total, or while they are under a `minHoursForPeriod` floor — so two full-timers on a roster whose minimum cover is 56h, with `maxEmployees: 2` on the shifts, are each planned their 40h rather than 28h. A shift asking for one person needs one person, and a second body there does not do a second body's work: without that rule a team contracted for far more hours than the period requires is planned onto every shift at once, which is lawful, useless and expensive. The ceiling for this pass is the contracted total **plus whatever `rules.contract.maxOverMinutes` already allows**, never a target to land nearest to: with no allowance stated, a half-timer on 15h of a 20h contract is not given a further 7.5h shift, because 2.5h over is not "closer" enough to be worth hours nobody asked for. State an allowance and the top-up plans into it, which is what lets a part-timer be filled at all when no shift is small enough to fit the room left. Set `objectives.fillToContract: false` (or a zero `contractHoursWeight`) to staff minimum cover only and let contracted hours merely distribute the demand; a `maxEmployees` on the template or a hard `maxOverMinutes` bounds the top-up either way.
1699
2050
 
1700
2051
  **Public holidays** are caller-supplied ISO dates in `calendar.publicHolidays`. They mark `ShiftInstance.isPublicHoliday`, which drives `restDays.holidayAllowed` and `compensatoryRestWithinDays.holiday`, the `holidays` fairness dimension and the `holiday` cost premium. The engine ships no holiday calendar — a host resolves the roster's location to dates and passes them in.
1701
2052
 
@@ -1754,6 +2105,24 @@ diagnoseInfeasibility(input); // why it cannot be solved, before solving
1754
2105
 
1755
2106
  `expandShiftInstances(input)` returns the dated planning grid a host should render before anything is assigned — the same `<templateId>@<date>` ids every other call refers to. Use it so the grid ids never drift from the instances the solver will judge.
1756
2107
 
2108
+ ### Validation and replay (engine version 3)
2109
+
2110
+ `checkCompliance` reports staffing and skill shortfalls alongside assignment violations. Its `compliant` flag means no hard breaches; `coverageComplete` means every staffing requirement is met; `publishable` requires both. The host must still handle any medium-severity obligations and publication approvals required by its workflow. Duplicate assignments are input errors and do not inflate worked hours.
2111
+
2112
+ Employee `rules` replace whole global rule families, including families absent globally. The same effective rules apply during solving, candidate checks, and compliance. Night classification uses the employee's effective night window. Rule hardness overrides also apply to returned verdicts; only hard constraints prune eligibility. Absence repair preserves published assignments outside the actual absence interval, including when a shift starts before that interval and overlaps it.
2113
+
2114
+ Date-time fields (`asOf`, publication time, absences, external commitments) accept local date-times in the roster zone or ISO instants with `Z`/`±HH:MM`. Bare absence end dates include the entire local day. Invalid dates, reversed spans, unknown absence employees, and invalid search budgets throw `ScheduleValidationError`. Leave beyond the final planning date still blocks overnight work that reaches it.
2115
+
2116
+ For repeatable optimization, use a fixed iteration count and omit `timeBudgetMs`:
2117
+
2118
+ ```ts
2119
+ const result = solveSchedule({ ...input, seed: 42, maxIterations: 500, timeBudgetMs: undefined });
2120
+ ```
2121
+
2122
+ With both limits set, search stops at whichever is reached first, so wall-clock termination can change the result. Persist the full input, engine version, and custom-rule implementations for replay. `rulesHash` includes effective employee rules and optional custom constraint `version` strings; it is a configuration fingerprint, not a complete input archive.
2123
+
2124
+ Custom `evaluate(state)` violations now influence search selection as well as final validation. These hooks must be pure and fast, and should express obligations not already scored by `delta`. Candidate checks still use pair-level hooks; implement `delta`/`verdict` for restrictions that must also block an individual cover suggestion. Search remains heuristic and does not prove optimality or infeasibility.
2125
+
1757
2126
  ### Compliance boundary
1758
2127
 
1759
2128
  Ranking uses declared qualifications, contractual availability, legal limits, cost, and fairness debt computed from **realised** assignment counts. It never consumes reliability scores, no-show prediction, acceptance history or learned per-worker behaviour, and the module is not wired to the matcher's learning layer. Under AI Act Annex III point 4(b), allocating on individual behaviour or traits is high-risk, and the Art 6(3) narrow-task filter has an absolute carve-back for profiling — so that boundary is what keeps this a constraint solver. `result.provenance` records `{ engineVersion, seed, rulesHash, profilingFree }` for audit.
package/dist/index.d.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  import AssignmentMatcher from './matcher.class';
2
2
  export type { Assignment, MatcherOptions, options, Stats, QueueStats, UserLoadInfo, User, GeoMatchResult, GeoMatchingFunction, ReliabilityMetrics, AssignmentStatus, FairnessMode, FairnessConfig, MatchTraceReason, MatchCandidateTrace, MatchDecisionTrace, MatchDecisionMode, MatchExplanation, MatchPreview, MatchPreviewInput, DecisionTraceQuery, AssignmentLifecycleEvent, EscalationPolicy, EscalationSweepResult, CompletionDeadlineSweepResult, SlaExpirySweepResult, SlaPolicy, SlaStats, SchedulePolicy, ScheduleSweepResult, RecurrencePolicy, RecurringAssignment, RecurringAssignmentRecord, RecurrenceSweepResult, RetentionSweepResult, CompletedAssignmentPage, AssignmentLintIssue, AssignmentLintContext, AssignmentReadinessReport, QueueAuditOptions, QueueAuditEntry, QueueAuditReport, MaintenanceOptions, MaintenanceReport, UserStatusFilter, UserQueryOptions, UserSummary, UserQueryResult, ActiveAssignmentInfo, } from './matcher.class';
3
3
  export { lintAssignment, userCoversTag } from './validation/assignment-lint';
4
- export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowExternalTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, WorkflowInstanceQuery, WorkflowInstancePage, WorkflowTransition, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, AutoRoutingWeightsOptions, AutoRoutingWeightsPolicy, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
4
+ export type { WorkflowDefinition, WorkflowDefinitionInput, WorkflowDefinitionSummary, WorkflowInstance, WorkflowInstanceStatus, WorkflowStep, WorkflowRouting, WorkflowTargetUser, WorkflowMachineTask, WorkflowExternalTask, WorkflowTaskType, WorkflowEvent, WorkflowEventType, AssignmentResult, ParallelBranchState, DeadLetterEntry, AuditEntry, CircuitBreakerState, WorkflowInstanceWithSnapshot, WorkflowInstanceQuery, WorkflowInstancePage, WorkflowTransition, LearningOutcome, LearningRewards, LearningFeatures, LearningAssignmentContext, LearningFeatureExtractor, LearningDecisionRecord, LearningEpisodeRecord, LearningSignals, LearningSample, LearningStats, LearningTagStat, LearningRewardTarget, LearningTargetsOptions, LearningPrediction, LearningRewardAccounting, LearningUpdateMode, LearningExplorationPolicy, LearningDecisionContext, LearningFeatureContext, LearningWorkerPerformance, AutoWeightExplanation, AutoRoutingWeightsOptions, AutoRoutingWeightsPolicy, PendingAssignmentInfo, WorkflowEngineMetrics, MachineTaskHandler, WorkflowHost, PaginationOptions, PaginationResult, AssignmentCounts, } from './matcher.class';
5
5
  export { explainMatchScore, type MatchScoreExplanation } from './scoring/match-score';
6
6
  export { extractMatchFeatures, cosineSimilarity } from './learning/features';
7
- export { synthesizeRoutingWeights, DEFAULT_AUTO_WEIGHTS_OPTIONS } from './learning/auto-weights';
8
- export { ShiftScheduler, solveSchedule, ScheduleValidationError, DEFAULT_MIN_REST_MINUTES, PeriodClock, expandShiftInstances, checkCompliance, explainCandidate, repairSchedule, rankCandidates, diagnoseInfeasibility, hours, days, weeklyAverageOver, DEFAULT_CONTRACT_HOURS_WEIGHT, contractedPeriodMinutes, fullTimeWeeklyMinutes, resolveContractedWeeklyMinutes, type AssignmentPair, type AvailabilityRule, type BreakRule, type ClockRange, type ClockRangeConfig, type ComplianceReport, type ConsecutiveRule, type ConstraintOptions, type ConstraintViolation, type DailyRestRule, type Disruption, type DutyClassification, type DutyQuota, type Employee, type EmployeeContract, type ContractHoursRule, type ContractHoursSummary, type EmployeeCost, type EmployeeProtection, type EngagementRule, type FairnessRule, type HistoricalAssignment, type InfeasibilityReport, type LedgerEntry, type MinuteRange, type ModelContext, type NightVolumeQuota, type NightWorkRule, type NoticeRule, type ObjectiveWeights, type OvertimeRule, type PersonTimeline, type Qualification, type RepairCandidate, type RepairResult, type RestDayRule, type RollingAverage, type RuleVerdict, type ScheduleInput, type ScheduleProvenance, type ScheduleResult, type ScheduledAssignment, type SchedulingConstraint, type SearchState, type Severity, type ShiftInstance, type ShiftTemplate, type Site, type SiteIndex, type TimeOffEntry, type TimelineEntry, type TimelineIndex, type WeeklyRestRule, type WorkingTimeLimits, type WorkingTimeRules, } from './scheduling';
7
+ export { synthesizeRoutingWeights, explainRoutingWeights, DEFAULT_AUTO_WEIGHTS_OPTIONS } from './learning/auto-weights';
8
+ export { epsilonGreedySelect, greedySelect } from './learning/policy';
9
+ export type { PolicyChoice, EpsilonGreedyOptions } from './learning/policy';
10
+ export { ShiftScheduler, solveSchedule, ScheduleValidationError, DEFAULT_MIN_REST_MINUTES, PeriodClock, expandShiftInstances, checkCompliance, explainCandidate, repairSchedule, rankCandidates, diagnoseInfeasibility, hours, days, weeklyAverageOver, DEFAULT_CONTRACT_HOURS_WEIGHT, contractedPeriodMinutes, fullTimeWeeklyMinutes, resolveContractedWeeklyMinutes, type AssignmentPair, type AvailabilityRule, type BreakRule, type ClockRange, type ClockRangeConfig, type ComplianceReport, type ConsecutiveRule, type ConstraintOptions, type ConstraintViolation, type DailyRestRule, type Disruption, type DutyClassification, type DutyQuota, type Employee, type EmployeeContract, type ContractHoursRule, type ContractHoursSummary, type EmployeeCost, type EmployeeProtection, type EngagementRule, type FairnessRule, type HistoricalAssignment, type InfeasibilityReport, type LedgerEntry, type MinuteRange, type ModelContext, type NightVolumeQuota, type NightWorkRule, type NoticeRule, type ObjectiveWeights, type OvertimeRule, type PersonTimeline, type Qualification, type RepairCandidate, type RepairResult, type RestDayRule, type RollingAverage, type RuleVerdict, type ScheduleInput, type ScheduleProvenance, type ScheduleResult, type ScheduledAssignment, type SchedulingConstraint, type SearchState, type Severity, type ShiftInstance, type ShiftTemplate, type ShiftDemandOverride, type Site, type SiteIndex, type TimeOffEntry, type TimelineEntry, type TimelineIndex, type WeeklyRestRule, type WorkingTimeLimits, type WorkingTimeRules, } from './scheduling';
9
11
  export { WorkflowBuilder, WorkflowStepBuilder, workflow, linearWorkflow, approvalWorkflow } from './workflow-builder';
10
12
  export { normalizeWorkflowDefinition, validateWorkflowDefinition } from './workflow-validation';
11
13
  export * from './utils/cidr';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EACR,UAAU,EACV,cAAc,EACd,OAAO,EACP,KAAK,EACL,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,EACxB,gBAAgB,EAChB,qBAAqB,EACrB,6BAA6B,EAC7B,oBAAoB,EACpB,SAAS,EACT,QAAQ,EACR,cAAc,EACd,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,EACnB,yBAAyB,EACzB,qBAAqB,EACrB,oBAAoB,EACpB,uBAAuB,EACvB,mBAAmB,EACnB,qBAAqB,EACrB,yBAAyB,EACzB,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,WAAW,EACX,eAAe,EACf,oBAAoB,GACvB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MA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AE,iBAAiB,EAAE,CAAC;AAC7B,eAAe,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,iBAAiB,MAAM,iBAAiB,CAAC;AAEhD,YAAY,EACR,UAAU,EACV,cAAc,EACd,OAAO,EACP,KAAK,EACL,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,cAAc,EACd,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,wBAAwB,EACxB,gBAAgB,EAChB,qBAAqB,EACrB,6BAA6B,EAC7B,oBAAoB,EACpB,SAAS,EACT,QAAQ,EACR,cAAc,EACd,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,EACnB,yBAAyB,EACzB,qBAAqB,EACrB,oBAAoB,EACpB,uBAAuB,EACvB,mBAAmB,EACnB,qBAAqB,EACrB,yBAAyB,EACzB,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,WAAW,EACX,eAAe,EACf,oBAAoB,GACvB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAG7E,YAAY,EACR,kBAAkB,EAClB,uBAAuB,EACvB,yBAAyB,EACzB,gBAAgB,EAChB,sBAAsB,EACtB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,oBAAoB,EACpB,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,4BAA4B,EAC5B,qBAAqB,EACrB,oBAAoB,EACpB,kBAAkB,EA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AC7B,eAAe,iBAAiB,CAAC"}
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.AssignmentMatcher = exports.createKeyBuilders = exports.validateWorkflowDefinition = exports.normalizeWorkflowDefinition = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = exports.resolveContractedWeeklyMinutes = exports.fullTimeWeeklyMinutes = exports.contractedPeriodMinutes = exports.DEFAULT_CONTRACT_HOURS_WEIGHT = exports.weeklyAverageOver = exports.days = exports.hours = exports.diagnoseInfeasibility = exports.rankCandidates = exports.repairSchedule = exports.explainCandidate = exports.checkCompliance = exports.expandShiftInstances = exports.PeriodClock = exports.DEFAULT_MIN_REST_MINUTES = exports.ScheduleValidationError = exports.solveSchedule = exports.ShiftScheduler = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = exports.synthesizeRoutingWeights = exports.cosineSimilarity = exports.extractMatchFeatures = exports.explainMatchScore = exports.userCoversTag = exports.lintAssignment = void 0;
20
+ exports.AssignmentMatcher = exports.createKeyBuilders = exports.validateWorkflowDefinition = exports.normalizeWorkflowDefinition = exports.approvalWorkflow = exports.linearWorkflow = exports.workflow = exports.WorkflowStepBuilder = exports.WorkflowBuilder = exports.resolveContractedWeeklyMinutes = exports.fullTimeWeeklyMinutes = exports.contractedPeriodMinutes = exports.DEFAULT_CONTRACT_HOURS_WEIGHT = exports.weeklyAverageOver = exports.days = exports.hours = exports.diagnoseInfeasibility = exports.rankCandidates = exports.repairSchedule = exports.explainCandidate = exports.checkCompliance = exports.expandShiftInstances = exports.PeriodClock = exports.DEFAULT_MIN_REST_MINUTES = exports.ScheduleValidationError = exports.solveSchedule = exports.ShiftScheduler = exports.greedySelect = exports.epsilonGreedySelect = exports.DEFAULT_AUTO_WEIGHTS_OPTIONS = exports.explainRoutingWeights = exports.synthesizeRoutingWeights = exports.cosineSimilarity = exports.extractMatchFeatures = exports.explainMatchScore = exports.userCoversTag = exports.lintAssignment = void 0;
21
21
  const matcher_class_1 = __importDefault(require("./matcher.class"));
22
22
  exports.AssignmentMatcher = matcher_class_1.default;
23
23
  // Pre-flight lint (pure, Redis-free) — usable host-side before addAssignment
@@ -34,7 +34,12 @@ Object.defineProperty(exports, "cosineSimilarity", { enumerable: true, get: func
34
34
  // Automatic routing-weight synthesis (UCB1 policy over learned tag stats)
35
35
  var auto_weights_1 = require("./learning/auto-weights");
36
36
  Object.defineProperty(exports, "synthesizeRoutingWeights", { enumerable: true, get: function () { return auto_weights_1.synthesizeRoutingWeights; } });
37
+ Object.defineProperty(exports, "explainRoutingWeights", { enumerable: true, get: function () { return auto_weights_1.explainRoutingWeights; } });
37
38
  Object.defineProperty(exports, "DEFAULT_AUTO_WEIGHTS_OPTIONS", { enumerable: true, get: function () { return auto_weights_1.DEFAULT_AUTO_WEIGHTS_OPTIONS; } });
39
+ // Explicit selection policies (propensity-logged exploration)
40
+ var policy_1 = require("./learning/policy");
41
+ Object.defineProperty(exports, "epsilonGreedySelect", { enumerable: true, get: function () { return policy_1.epsilonGreedySelect; } });
42
+ Object.defineProperty(exports, "greedySelect", { enumerable: true, get: function () { return policy_1.greedySelect; } });
38
43
  // Shift scheduling (pure, Redis-free rostering engine)
39
44
  var scheduling_1 = require("./scheduling");
40
45
  Object.defineProperty(exports, "ShiftScheduler", { enumerable: true, get: function () { return scheduling_1.ShiftScheduler; } });
@@ -0,0 +1,11 @@
1
+ import type { RedisClientType } from '../types/matcher';
2
+ /** Internal, deliberately limited unit of work for learning ingestion.
3
+ * Reads remain sparse. Writes are simulated in Lua before any mutation so a
4
+ * bad counter/type cannot leave an applied marker beside partially trained data.
5
+ * Read dependencies are compared inside the same script; conflicts re-plan.
6
+ */
7
+ export declare function prepareIngestion(client: RedisClientType, scripts: string[]): {
8
+ client: RedisClientType;
9
+ commit(): Promise<boolean>;
10
+ };
11
+ //# sourceMappingURL=atomic-ingestion.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"atomic-ingestion.d.ts","sourceRoot":"","sources":["../../src/learning/atomic-ingestion.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC5B,MAAM,EAAE,eAAe,EACvB,OAAO,EAAE,MAAM,EAAE,GAClB;IAAE,MAAM,EAAE,eAAe,CAAC;IAAC,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC,CAAA;CAAE,CA8EzD"}