{ "CI_job_history_included": false, "approvals": [], "diff_versions": [ { "commits": [ { "authored_date": null, "commit_author_id": null, "committed_date": null, "committer_id": null, "merge_request_commits_metadata_id": 602, "merge_request_diff_id": 465, "message": null, "project_id": 35, "relative_order": 0, "sha": null, "trailers": {} } ], "files": [], "metadata": { "base_commit_sha": "209bf05f3699c72f88efab733dde207c7230a8e4", "commits_count": 1, "created_at": "2026-10-10T14:08:47.619355", "diff_type": 1, "files_count": 0, "head_commit_sha": "6811142299b21124af146ac7f8cf02a96c4d91c7", "id": 465, "merge_request_id": 286, "project_id": 35, "start_commit_sha": "209bf05f3699c72f88efab733dde207c7230a8e4", "state": "without_files", "stored_externally": null, "updated_at": "2026-10-10T15:01:51.843105" } }, { "commits": [ { "authored_date": null, "commit_author_id": null, "committed_date": null, "committer_id": null, "merge_request_commits_metadata_id": 604, "merge_request_diff_id": 467, "message": null, "project_id": 35, "relative_order": 0, "sha": null, "trailers": {} }, { "authored_date": null, "commit_author_id": null, "committed_date": null, "committer_id": null, "merge_request_commits_metadata_id": 602, "merge_request_diff_id": 467, "message": null, "project_id": 35, "relative_order": 1, "sha": null, "trailers": {} } ], "files": [], "metadata": { "base_commit_sha": "209bf05f3699c72f88efab733dde207c7230a8e4", "commits_count": 2, "created_at": "2026-10-10T14:37:28.903969", "diff_type": 1, "files_count": 0, "head_commit_sha": "98e87feceea9ba6f212ce162f61b4605fa6bde98", "id": 467, "merge_request_id": 286, "project_id": 35, "start_commit_sha": "209bf05f3699c72f88efab733dde207c7230a8e4", "state": "without_files", "stored_externally": null, "updated_at": "2026-10-10T15:01:51.850054" } }, { "commits": [ { "authored_date": null, "commit_author_id": null, "committed_date": null, "committer_id": null, "merge_request_commits_metadata_id": 606, "merge_request_diff_id": 469, "message": null, "project_id": 35, "relative_order": 0, "sha": null, "trailers": {} }, { "authored_date": null, "commit_author_id": null, "committed_date": null, "committer_id": null, "merge_request_commits_metadata_id": 604, "merge_request_diff_id": 469, "message": null, "project_id": 35, "relative_order": 1, "sha": null, "trailers": {} }, { "authored_date": null, "commit_author_id": null, "committed_date": null, "committer_id": null, "merge_request_commits_metadata_id": 602, "merge_request_diff_id": 469, "message": null, "project_id": 35, "relative_order": 2, "sha": null, "trailers": {} } ], "files": [ { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,26 +1,34 @@\n-# 06 — Migrer les règles sauvegardées et valider l’ensemble\n+# 06 — Migrer les règles sauvegardées et valider le comportement fonctionnel\n \n **GitLab:** [#75](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/75)\n \n-**What to build:** Au prochain chargement, l’utilisateur retrouve ses règles et les six anciens comportements du moteur sous forme de préréglages actifs. Il peut ensuite les modifier ou les supprimer durablement, et l’ensemble est validé avant sa mise en service.\n+Blocked by: #74\n \n-**Blocked by:** 05 — Piloter l’économie des jours d’appoint.\n+Les exigences de performance sont transférées à #78. La clôture de ce ticket dépend de la migration et de la validation fonctionnelle, pas du passage du protocole de performance. Les limites du benchmark restent inchangées. À la demande de l’utilisateur, son job CI est séparé et non bloquant tant que #78 est ouvert ; #78 doit rétablir ce contrôle obligatoire après réussite du protocole. Les tests fonctionnels et les autres contrôles CI restent obligatoires.\n \n-**Status:** ready-for-agent\n+## What to build\n \n-Livraison intégrée de l’ADR 0008 sur la branche commune aux tickets 01 à 05. La préservation des données enregistrées et la migration unique ont été explicitement approuvées : ne pas réinitialiser les données pour simplifier le changement de contrat.\n+Au prochain chargement, l’utilisateur retrouve ses règles et les six anciens comportements du moteur sous forme de préréglages actifs. Il peut ensuite les modifier ou les supprimer durablement, et l’ensemble est validé avant sa mise en service.\n \n-- [ ] À l’initialisation, fournir les six préréglages actifs avec cet ordre : prévention des pertes, règles personnelles ou règles initiales existantes dans leur ordre, semaines fériées, gain de jours non ouvrés, séquence maximale, déficit des reprises et économie des placements d’appoint.\n-- [ ] Migrer une seule fois les listes enregistrées avant cette évolution, y compris une ancienne liste vide. Préserver intégralement l’identité, le nom, les paramètres, les dates, la force, l’activation et l’ordre relatif des règles existantes.\n-- [ ] Enregistrer de façon cohérente les règles migrées et le fait que la migration a eu lieu. Ne pas considérer l’opération terminée si les règles n’ont pas été sauvegardées ; gérer les échecs de stockage sans écraser les données utilisateur valides.\n-- [ ] Les chargements suivants ne dupliquent pas les préréglages, ne rétablissent pas ceux supprimés et ne réactivent pas ceux désactivés. Une liste vidée volontairement après migration reste vide. Les nouveaux utilisateurs reçoivent directement la nouvelle configuration initiale.\n-- [ ] La restauration et la migration précèdent le premier calcul utilisant ces données. L’utilisateur peut immédiatement éditer les six configurations avec les mêmes commandes que ses règles personnelles et retrouver ses choix après rechargement.\n-- [ ] Vérifier de bout en bout les six préréglages dans l’ordre initial, leurs réordonnancements et leurs désactivations. Une configuration personnelle différente d’un préréglage traverse édition, sauvegarde, worker, calcul et explication ; les paramètres ont un effet vérifiable.\n-- [ ] La liste entièrement désactivée, la liste supprimée après migration et une requête directe sans règle active n’ajoutent aucun congé malgré des soldes à risque. Les jours déclarés, les quantités restantes et les raisons pertinentes restent cohérents.\n-- [ ] Les obligations conjointes, les conditions des congés gagnés et les contraintes de validité sont respectées pour tout ordre des préférences. Une annulation restitue le meilleur plan valide disponible et sa trace originale selon la configuration soumise.\n-- [ ] Les explications et analyses contrefactuelles utilisent le même ordre actif que le calcul. Modifier les règles durant le calcul ou pendant la livraison tardive de la trace ne change pas ses résultats. Les anciens objectifs implicites n’interviennent plus dans aucune comparaison ou protection.\n-- [ ] Les fixtures et scénarios de benchmark qui dépendaient d’une optimisation implicite demandent explicitement les préréglages nécessaires. Les tests d’absence de règles n’utilisent aucun défaut implicite pour retrouver l’ancien résultat.\n-- [ ] Exécuter les suites concernées de règles, interface, moteur, worker réel, explication, annulation et estimation de durée, ainsi que les contrôles habituels de compilation et de qualité. Vérifier les scénarios de benchmark existants, dont les horizons longs, pour le déterminisme, la réactivité et les durées, sans introduire de délai d’arrêt automatique.\n-- [ ] La vérification commune des tickets 01 à 06 est la condition de mise en service. Documenter les choix finaux du contrat composable et les limites mesurées ; ne laisser ni double moteur, ni chemin historique implicite, ni adaptateur provisoire ajouté pour rendre les étapes indépendamment livrables.\n+Livraison intégrée de l’ADR 0008 sur la branche commune aux tickets #70, #71, #72, #73, #74. La préservation des données enregistrées et la migration unique ont été explicitement approuvées : ne pas réinitialiser les données pour simplifier le changement de contrat.\n+\n+## Acceptance criteria\n+\n+- [x] À l’initialisation, fournir les six préréglages actifs avec cet ordre : prévention des pertes, règles personnelles ou règles initiales existantes dans leur ordre, semaines fériées, gain de jours non ouvrés, séquence maximale, déficit des reprises et économie des placements d’appoint.\n+- [x] Migrer une seule fois les listes enregistrées avant cette évolution, y compris une ancienne liste vide. Préserver intégralement l’identité, le nom, les paramètres, les dates, la force, l’activation et l’ordre relatif des règles existantes.\n+- [x] Enregistrer de façon cohérente les règles migrées et le fait que la migration a eu lieu. Ne pas considérer l’opération terminée si les règles n’ont pas été sauvegardées ; gérer les échecs de stockage sans écraser les données utilisateur valides.\n+- [x] Les chargements suivants ne dupliquent pas les préréglages, ne rétablissent pas ceux supprimés et ne réactivent pas ceux désactivés. Une liste vidée volontairement après migration reste vide. Les nouveaux utilisateurs reçoivent directement la nouvelle configuration initiale.\n+- [x] La restauration et la migration précèdent le premier calcul utilisant ces données. L’utilisateur peut immédiatement éditer les six configurations avec les mêmes commandes que ses règles personnelles et retrouver ses choix après rechargement.\n+- [x] Vérifier de bout en bout les six préréglages dans l’ordre initial, leurs réordonnancements et leurs désactivations. Une configuration personnelle différente d’un préréglage traverse édition, sauvegarde, worker, calcul et explication ; les paramètres ont un effet vérifiable.\n+- [x] La liste entièrement désactivée, la liste supprimée après migration et une requête directe sans règle active n’ajoutent aucun congé malgré des soldes à risque. Les jours déclarés, les quantités restantes et les raisons pertinentes restent cohérents.\n+- [x] Les obligations conjointes, les conditions des congés gagnés et les contraintes de validité sont respectées pour tout ordre des préférences. Une annulation restitue le meilleur plan valide disponible selon la configuration soumise. La suppression de la trace originale est suivie séparément dans #76.\n+- [x] Les explications et analyses contrefactuelles utilisent le même ordre actif que le calcul. Modifier les règles durant le calcul ou pendant la livraison des explications ne change pas ses résultats. Les anciens objectifs implicites n’interviennent plus dans aucune comparaison ou protection.\n+- [x] Les fixtures et scénarios de benchmark qui dépendaient d’une optimisation implicite demandent explicitement les préréglages nécessaires. Les tests d’absence de règles n’utilisent aucun défaut implicite pour retrouver l’ancien résultat.\n+- [x] Exécuter les suites fonctionnelles concernées de règles, interface, moteur, worker réel, explication, annulation et estimation de durée, ainsi que les contrôles habituels de compilation et de qualité. Préserver les assertions de résultat et de déterminisme des fixtures, y compris les horizons longs. L’exécution complète du protocole de benchmark, la réactivité mesurée, les durées, la consommation mémoire et les optimisations nécessaires relèvent de #78 et ne conditionnent plus la clôture de #75. Ne pas introduire de délai d’arrêt automatique.\n+- [x] La vérification fonctionnelle commune des tickets #70, #71, #72, #73, #74, #75 est la condition de clôture fonctionnelle de ce ticket. Documenter les choix finaux du contrat composable ; ne laisser ni double moteur, ni chemin historique implicite, ni adaptateur provisoire ajouté pour rendre les étapes indépendamment livrables. Les limites de performance mesurées et leur amélioration sont suivies dans #78 ; les tests fonctionnels et les autres contrôles CI restent obligatoires, avec la seule exception temporaire du job de benchmark décrite ci-dessus.\n \n **Vérification de bout en bout :** Partir d’une ancienne sauvegarde contenant des règles personnalisées et désactivées, charger la nouvelle version, vérifier le premier calcul, modifier ou supprimer des préréglages, recharger et constater la conservation exacte des choix.\n+\n+## Blocked by\n+\n+- #74 — Piloter l’économie des jours d’appoint\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": ".scratch/regles-optimisation/issues/06-migrer-regles-sauvegardees-et-valider-ensemble.md", "project_id": 35, "relative_order": 0, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,29 @@\n+# 01 — Remove the original decision trace end to end\n+\n+**GitLab:** [#76](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/76)\n+\n+## What to build\n+\n+Calculations no longer record, retain or deliver an original decision trace. Users receive the displayed plan, its stable explanation and remaining-balance reasons, and can still analyze an alternative date for a displayed placement. The advanced trace explorer, historical calendar replay and historical attempt lists disappear completely.\n+\n+This is one cohesive contract replacement across the planner, calculation service, workers and UI. Use a scoped integration branch containing the existing #70–#75 implementation work; #75's final verification must not be treated as a prerequisite for removing tracing. The shared functional integration verification gate is #77 — Verify integrated planning after trace removal. Benchmark performance acceptance and any required optimization are owned by #78; performance is no longer a completion gate for #75.\n+\n+## Acceptance criteria\n+\n+- [ ] Delete trace capture, materialization, candidate-history retention, replay, historical eligibility and caches or evidence pools used exclusively for tracing. Remove observational work while preserving search breadth, allocation previews, rule priority and incumbent selection.\n+- [ ] Replace trace contracts directly and update all callers in the same change. Remove trace promises, callbacks, public types, streaming messages, status indexes, acknowledgements and backpressure queues across real-worker, browser-fallback and server-side calculation paths. Do not retain debug toggles, compatibility adapters, empty trace results or replacement history.\n+- [ ] Preserve immutable calculation, valid-incumbent and final-state snapshots needed by retained behavior. Rename retained state contracts independently of tracing; do not delete cancellation or explanation data because it currently has a trace-related name.\n+- [ ] Retain stable plan explanations, including placement entitlement and rule provenance, objective contributions and the first decisive objective, time-off periods, remaining balances and concrete non-placement reasons. Preserve invalid-input and conflict explanations and incomplete-calculation behavior.\n+- [ ] Keep alternative-date analysis for a displayed placement using the captured calculation configuration, the same entitlement, leave type and provenance, and fixed unrelated placements. Remove analysis based on historical decisions; hypothetical analysis never mutates the displayed plan.\n+- [ ] Remove the advanced trace panel, replay controls, historical calendar overlays and candidate statuses. Remove remaining-balance historical attempt lists, pagination and loading state while retaining classification, validity, earned-entitlement source and truthful displayed-plan reasons. Leave no dead controls or trace-unavailable messages.\n+- [ ] Preserve explicit cancellation before and after a valid incumbent, best-valid-partial-plan recovery, heartbeat monitoring, stale-response rejection and the existing technical-budget contract. Interrupted calculations do not imply an obligation conflict. Explanation delivery failures do not discard an available outcome, and planning workers do not wait for trace acknowledgements after required delivery.\n+- [ ] Preserve completed placements, balances, objective values, joint obligation satisfaction, earned-entitlement chronology, deterministic tie-breaking, user-controlled priorities and empty-active-rule behavior. Do not reset saved entitlements, declarations or rule configurations or change the existing migration.\n+- [ ] Update component styles and translations across supported languages, preserving keyboard access and accessibility for retained explanations, calendar interactions and date analysis.\n+- [ ] Adapt existing planner, service, worker, explanation, cancellation, calendar and remaining-balance tests. Delete tests exclusively for tracing while retaining assertions for supported behavior in mixed tests. Update benchmark callers, output and assertions to remove obsolete trace requirements without reducing scenarios or changing performance gates.\n+- [ ] Supersede trace-specific requirements in the domain vocabulary and explanation/cancellation ADRs, and update benchmark documentation. Preserve the remaining planning contracts and document that the original decision trace and historical analysis are removed.\n+\n+No new dependency, replacement telemetry, optimization-quality change, allocation-preview reduction or benchmark deadline relaxation is part of this ticket. No separate prefactor is required: retained explanation and hypothetical-analysis behavior already exists.\n+\n+## Blocked by\n+\n+None — can start immediately.\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": ".scratch/remove-original-decision-trace/issues/01-remove-original-decision-trace.md", "project_id": 35, "relative_order": 1, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,27 @@\n+# 02 — Verify integrated planning after trace removal\n+\n+**GitLab:** [#77](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/77)\n+\n+Blocked by: #76\n+\n+## What to build\n+\n+Demonstrate that the integrated #70–#75 work retains its supported behavior after trace removal. Provide a functionally verified trace-free baseline for #78, which now owns benchmark performance acceptance and optimization. Benchmark performance is no longer a completion gate for #75 or this functional verification ticket.\n+\n+## Acceptance criteria\n+\n+- [ ] Review the integrated contract replacement across all calculation paths and UI callers. Confirm there is no trace recorder, trace transport, acknowledgement wait, historical replay API or retained trace-dependent control or compatibility shell.\n+- [ ] Compare completed outcomes and stable explanations against existing deterministic fixtures, including typed joint obligations, earned-entitlement chains, custom objective formulas, reordered priorities, two- and three-year horizons and no active optimization rules. Do not rewrite placement expectations to hide a behavioral regression.\n+- [ ] Verify real-worker outcome and explanation delivery, heartbeat monitoring, stale-response rejection and explanation failure handling. Exercise cancellation before any valid incumbent and after a valid incumbent, and confirm that partial outcomes remain valid without false conflicts.\n+- [ ] Verify displayed-placement alternative-date analysis and remaining-balance reasons without historical data. Check that captured settings remain immutable and hypothetical alternatives do not change the displayed plan.\n+- [ ] Run the existing full correctness, coverage, static, formatting and build checks appropriate to the integrated change, and resolve regressions within the trace-removal scope. Preserve the repository's required thresholds.\n+- [ ] Complete browser QA for the retained explanation, calendar, cancellation and alternative-date flows, including keyboard interaction and a narrow viewport. Confirm the advanced trace explorer, historical overlays and historical attempt controls are absent.\n+- [ ] Verify that benchmark callers use the supported trace-free calculation contract and retain their correctness, determinism, horizon, placement-count and completed-stage assertions. Full protocol execution, the unchanged 2 GB/300-second performance gates and any required optimization belong to #78.\n+- [ ] Hand off the functionally verified integrated baseline and unchanged benchmark inputs to #78. Verify retained outcome and explanation delivery without waiting for removed trace artifacts or inventing replacement trace counters.\n+- [ ] Keep the original #70–#75 dependency order and report the functional integration result. Apply #75’s revised functional completion criteria: a benchmark performance failure alone does not block #75 or this ticket. Outstanding benchmark requirements remain open in #78, without deadline relaxation or an automatic engine cutoff.\n+\n+The removal is agreed; its measured speedup is unresolved and is now evaluated in #78. This ticket owns functional verification after trace removal. It does not itself implement performance optimizations or close other issues.\n+\n+## Blocked by\n+\n+- #76 — Remove the original decision trace end to end (https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/76).\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": ".scratch/remove-original-decision-trace/issues/02-verify-trace-free-planning.md", "project_id": 35, "relative_order": 2, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,39 @@\n+# 03 — Verify and optimize planning to meet the benchmarks from #75\n+\n+**GitLab:** [#78](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/78)\n+\n+Blocked by: #75, #77\n+\n+## Parent\n+\n+#75 — Performance acceptance separated from the functional migration ticket at the user's request.\n+\n+## What to build\n+\n+Verify the integrated planner against the benchmark requirements originally attached to #75 and apply performance optimizations when needed until those requirements pass. Start from the functionally verified implementation after original-decision-trace removal. #75 can finish on its functional requirements; performance acceptance belongs to this ticket.\n+\n+If the measured baseline already passes, keep the engine unchanged and record the evidence. Otherwise profile the real failing path, apply the smallest complete improvement and verify both performance and retained planning behavior.\n+\n+## Acceptance criteria\n+\n+- [ ] Keep the existing seven benchmark scenarios and inputs, including the loaded year, typed joint obligations, chained earned entitlements and two- and three-year horizons. Keep explicit optimization configurations, quotas, expected outcomes, placement counts, completed-stage and determinism assertions.\n+- [ ] Run the real existing benchmark protocol: one warm-up and two measured repetitions per scenario, outside coverage instrumentation, with a 2 GB Node heap limit and the 300-second timeout for the full protocol. All scenarios and repetitions must finish and pass; a timeout, skipped scenario or partial report does not satisfy this ticket.\n+- [ ] Restore the benchmark as a required CI check after the unchanged protocol passes. While this ticket is open, the user approved a separate automatic benchmark job with `allow_failure: true` so its failure does not block functional delivery. Passing CI during this exception does not satisfy benchmark acceptance or justify closing this ticket.\n+- [ ] After #76 removes tracing and #77 verifies the retained behavior, benchmark outcome and explanation delivery without obsolete trace counters, trace transfer or trace-acknowledgement waits. Do not reintroduce tracing as profiling infrastructure.\n+- [ ] When the baseline fails, profile CPU, allocation and repeated planning work; apply optimizations and rerun the unchanged protocol until it passes. Preserve planning semantics, rule ordering, joint obligations, earned-entitlement chronology, final-plan quality and deterministic tie-breaking. Use behavior-level or differential tests to demonstrate that caching, deduplication or pruning is valid across the relevant configurations.\n+- [ ] Preserve responsive browser interaction, explicit cancellation, heartbeat monitoring and best-valid-partial-plan recovery during representative and long-horizon calculations. Keep the existing duration-estimation contract and recalibrate estimates only when measured results require it.\n+- [ ] Do not increase the benchmark timeout or heap allowance, reduce scenarios or repetitions, weaken correctness assertions, add an automatic elapsed-time engine cutoff, or reduce search breadth or planning quality to make the protocol pass.\n+- [ ] Record reproducible before/after preparation, planning, total-duration, responsiveness and available peak-heap measurements, including environment and protocol. Clearly distinguish actual completed benchmark runs from diagnostics or interrupted measurements and document any reference-hardware checks that could not be performed.\n+- [ ] Run required correctness, coverage, static and build checks after any optimization. Preserve the captured configuration, stable explanations, displayed-placement alternative-date analysis and saved-user-data behavior.\n+- [ ] Update benchmark documentation with the final measured limits and evidence. Close this ticket only after the unchanged benchmark gates pass; a failed measurement remains an open performance requirement here rather than reopening #75 for performance alone.\n+\n+## Existing evidence and scope\n+\n+The previous real protocol timed out at 300 seconds without an out-of-memory failure. The loaded-year warm-up took about 184 seconds and its first measured repetition started about 252 seconds into the protocol. Original trace recording and repeated allocation previews were observed costs; the benefit of trace removal has not yet been measured. These are starting points for profiling, not permission to change optimization quality.\n+\n+This ticket authorizes verification and implementation of performance improvements when needed. Functional migration remains in #75, trace removal in #76 and trace-removal functional verification in #77. Existing benchmark limits remain unchanged; only the benchmark job's blocking status is temporarily waived at the user's request until this ticket restores it.\n+\n+## Blocked by\n+\n+- #75 — Finish the functional saved-rule migration and integrated planning validation.\n+- #77 — Verify integrated planning after trace removal (itself blocked by #76).\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": ".scratch/remove-original-decision-trace/issues/03-verify-and-optimize-planning-benchmarks.md", "project_id": 35, "relative_order": 3, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -20,4 +20,6 @@ After all active rules compare equally, earlier balance expiry and then earlier\n \n Only active rules drive placement decisions and preference comparisons; disabled or deleted optimization rules have no residual influence through fixed optimization stages or protected metrics. With no active rules, the planner adds no leave placements, even when balances are at risk of expiring, and retains declared non-working days. Final tie-breakers cannot independently trigger new placements.\n \n-Implementation is pending.\n+Implemented in the #70–#75 series. Saved-rule migration and functional verification\n+are covered by #75. Benchmark performance acceptance and any required optimization\n+are tracked separately in #78; the benchmark limits remain unchanged.\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "docs/adr/0008-user-controlled-planning-objectives.md", "project_id": 35, "relative_order": 4, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,5 +1,36 @@\n # Mobile leave-planner benchmark\n \n+## Composable optimization rules: current verification status\n+\n+The #70–#75 implementation uses explicit active optimization configurations in\n+the benchmark fixtures. The latest full functional coverage run passes 652 tests\n+across 34 files under the 2 GB Node heap limit, excluding the separate benchmark.\n+This does not establish a passing performance protocol.\n+\n+MR pipeline 320 passed all 652 functional tests in 109.43 seconds, then the\n+seven-scenario protocol timed out at its unchanged 300-second limit without an\n+out-of-memory failure. In an earlier diagnostic run, the loaded-year warm-up took\n+184.36 seconds and its first measured repetition began about 251.78 seconds into\n+the protocol. Those diagnostic timings precede the final period-projection cache\n+and the planned original-decision-trace removal, and are not a result for either.\n+\n+At the user's request, #75 finishes on saved-rule migration and functional\n+verification. #78 owns benchmark verification and implementation of further\n+optimizations when needed, after #76 removes tracing and #77 verifies the retained\n+behavior. All seven scenarios, one warm-up and two measured repetitions per\n+scenario, the 2 GB heap limit and the 300-second timeout remain required for #78.\n+At the user's request, CI runs the benchmark in a separate job with\n+`allow_failure: true` while #78 is open. Functional coverage tests and all other\n+required checks remain blocking. #78 must restore the required benchmark gate\n+after the unchanged protocol passes. A green pipeline during this exception\n+does not establish a passing benchmark. No automatic elapsed-time planning\n+cutoff is introduced.\n+\n+The results below document earlier implementations and protocols. They are\n+historical measurements rather than the performance result for composable rules.\n+\n+## Reference-phone protocol\n+\n Open the deployed application at `/benchmark` on the reference phone. Tap\n **Run benchmark**, wait for the seven scenarios to finish, then tap **Copy\n report** and save the tab-separated output with the date and build identifier.\n@@ -90,10 +121,10 @@ and each flow sent exactly one planning request. All 1,949 and 3,956 trace\n packets respectively were acknowledged, carrying 122,621 and 249,234 candidate\n records without truncation. Heartbeats continued during the producing runs.\n \n-| Horizon | Calendar usable | Later trace delivery | Placements | Maximum UI timer delay before calendar / during trace | Peak page heap before calendar / during trace | Peak Chrome process-tree RSS before calendar / during trace |\n-| --- | --- | --- | --- | --- | --- | --- |\n-| Two years | 5.08 s | 2.55 s | 60 | 1.47 s / 0.70 s | 22.7 / 314.6 MiB | 1,143.2 / 1,606.8 MiB |\n-| Three years | 10.86 s | 4.14 s | 90 | 2.11 s / 1.48 s | 22.9 / 597.6 MiB | 1,386.8 / 2,217.8 MiB |\n+| Horizon | Calendar usable | Later trace delivery | Placements | Maximum UI timer delay before calendar / during trace | Peak page heap before calendar / during trace | Peak Chrome process-tree RSS before calendar / during trace |\n+| ----------- | --------------- | -------------------- | ---------- | ----------------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------- |\n+| Two years | 5.08 s | 2.55 s | 60 | 1.47 s / 0.70 s | 22.7 / 314.6 MiB | 1,143.2 / 1,606.8 MiB |\n+| Three years | 10.86 s | 4.14 s | 90 | 2.11 s / 1.48 s | 22.9 / 597.6 MiB | 1,386.8 / 2,217.8 MiB |\n \n A 50 ms page timer measured extra event-loop delay and sampled available\n main-thread JS heap. RSS was sampled every 500 ms across that isolated Chrome\n@@ -111,10 +142,10 @@ completed stage. An editable input accepted focus while the worker remained\n active. Both flows kept a 44 px Cancel control, fit the viewport without\n horizontal overflow, and delivered the original trace after their outcome.\n \n-| Cancellation point | Request to outcome | Request to complete artifacts | Retained placements |\n-| --- | --- | --- | --- |\n-| Calendar preparation | 21.9 ms | 874.8 ms | 0 |\n-| Active holiday-week optimization, keyboard | 21.5 ms | 1,431.7 ms | 90 |\n+| Cancellation point | Request to outcome | Request to complete artifacts | Retained placements |\n+| ------------------------------------------ | ------------------ | ----------------------------- | ------------------- |\n+| Calendar preparation | 21.9 ms | 874.8 ms | 0 |\n+| Active holiday-week optimization, keyboard | 21.5 ms | 1,431.7 ms | 90 |\n \n No browser errors occurred. Cancellation issued one cancel request and no\n additional calculation. Separate tests cover late artifact errors and stale\n@@ -151,11 +182,11 @@ at the worker's terminal artifact delivery. The application's own calibration\n uses its request timestamp and `afterNextRender` endpoint as described in\n [planning-duration.md](../planning-duration.md).\n \n-| Horizon | Range before Calculate (with one local sample) | Observed calendar wait | Additional trace delivery | Range after completion | Placements |\n-| --- | --- | --- | --- | --- | --- |\n-| One year | 1–4 s | 1.74 s | 1.23 s | 1–5 s | 30 |\n-| Two years | 2–16 s | 5.08 s | 2.88 s | 2–16 s | 60 |\n-| Three years | 7–44 s | 11.03 s | 5.60 s | 6–39 s | 90 |\n+| Horizon | Range before Calculate (with one local sample) | Observed calendar wait | Additional trace delivery | Range after completion | Placements |\n+| ----------- | ---------------------------------------------- | ---------------------- | ------------------------- | ---------------------- | ---------- |\n+| One year | 1–4 s | 1.74 s | 1.23 s | 1–5 s | 30 |\n+| Two years | 2–16 s | 5.08 s | 2.88 s | 2–16 s | 60 |\n+| Three years | 7–44 s | 11.03 s | 5.60 s | 6–39 s | 90 |\n \n All three outcomes completed through `dates`, with no intermediate placements,\n implicit deadline, extra request or date movement. The three-year result\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "docs/benchmark/README.md", "project_id": 35, "relative_order": 5, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,286 @@\n+# Composable planning objective contract\n+\n+The common implementation for tickets #70–#75 is on `feature/optimization-rules-70-75`.\n+`src/app/services/planning-objectives.ts` evaluates supported configurations; rule names and\n+identifiers never enter the evaluator. Supplied and personal optimization rules share this\n+model, editor, persistence and ordered calculation pipeline.\n+\n+## Configuration\n+\n+`OptimizationConfiguration` contains `elements`, `conditions`, `measure`, `aggregation`,\n+`direction`, and, only for `work-sequence-deficit`, `thresholdDays`. Conditions are a list\n+of distinct selectors, combined with AND; an empty list selects every observed element.\n+Directions are `minimize` and `maximize`. The finite `OPTIMIZATION_CATALOG` contains the\n+following compatible combinations. Each row accepts any subset of its listed conditions.\n+\n+| Elements | Applicable conditions | Measure | Aggregations | Measure unit | Parameters |\n+| ---------------------- | ----------------------- | --------------------------- | ------------------------- | --------------------- | ------------------------------------------------------ |\n+| `leave-balances` | `at-risk` | `unplaced-quantity` | `sum`, `count`, `maximum` | working days | none |\n+| `public-holiday-weeks` | `complete` | `public-holiday-week-value` | `sum`, `count`, `maximum` | calendar-day distance | none |\n+| `time-off-periods` | none | `non-working-day-gain` | `sum`, `count`, `maximum` | calendar days | none |\n+| `work-sequences` | `internal`, `non-empty` | `work-sequence-length` | `sum`, `count`, `maximum` | working days | none |\n+| `work-sequences` | `internal`, `non-empty` | `work-sequence-deficit` | `sum`, `count`, `maximum` | working days | `thresholdDays`: positive safe integer in working days |\n+| `leave-placements` | `supporting` | `placement-count` | `sum`, `count`, `maximum` | count | none |\n+\n+`count` counts selected elements, including selected elements whose measured value is zero;\n+its unit is always count. `sum` and `maximum` aggregate the selected measured values.\n+All three return **zero on an empty collection**. An empty work sequence has zero deficit,\n+even if a configuration selects it. The maximum of an empty work-sequence collection is zero;\n+the existing optional average statistics keep their separate null semantics.\n+\n+`validateOptimizationConfiguration(unknown)` returns `{ valid: true, configuration }` or\n+`{ valid: false, code, message }`. Malformed values use `invalid-optimization-configuration`;\n+unsupported elements/measure/condition/aggregation/parameter combinations use\n+`unsupported-optimization-configuration`. Unknown fields, duplicate conditions, missing,\n+fractional, non-positive, non-finite and unsafe thresholds are rejected. Other measures\n+reject `thresholdDays`. Direct and worker calculations attach each configuration error to\n+its rule, including malformed sparse selector lists; they never replace it with a preset.\n+\n+For example, a personal rule can select internal non-empty work sequences, sum their\n+deficits at a threshold of three, and minimize the result. It uses the same measure as\n+the five-day preset. Another can maximize the longest sequence or count complete holiday\n+weeks; composition never dispatches by a preset identifier.\n+\n+## Six supplied recipes\n+\n+`OPTIMIZATION_PRESETS` provides configurations, without identities, display labels or enabled\n+states. `RuleService` wraps copies in named planning rules and persists the full configuration.\n+\n+| Export key | Elements and conditions | Measure and aggregation | Direction |\n+| ---------------------- | --------------------------------------- | ---------------------------------- | --------- |\n+| `unplacedAtRisk` | leave balances, at risk | unplaced quantity, sum | minimize |\n+| `holidayWeekValue` | public-holiday weeks, complete | public-holiday week value, sum | maximize |\n+| `nonWorkingDayGain` | time-off periods | non-working-day gain, sum | maximize |\n+| `longestWorkSequence` | work sequences, including horizon edges | work-sequence length, maximum | minimize |\n+| `shortSequenceDeficit` | internal non-empty work sequences | deficit at `thresholdDays: 5`, sum | minimize |\n+| `supportingPlacements` | leave placements, supporting | placement count, count | minimize |\n+\n+## Concrete observations and boundaries\n+\n+`OptimizationObservations` carries collections from one concrete valid plan:\n+\n+- Leave balances expose unplaced working-day quantity and the at-risk flag. Expiry on either\n+ the horizon start or its exclusive end is at risk, preserving the existing classification;\n+ placement dates themselves stay within the half-open horizon.\n+- Public-holiday weeks expose their weekday holiday value and whether every other working\n+ date is a placement or declared non-working day. Monday through Friday contributions are\n+ **1, 2, 3, 2, 1**; several holidays in one week are summed once in that week's observation.\n+ Ordinary fully declared weeks never become holiday weeks. A partial horizon only admits\n+ a week when every required date outside it is already declared, preserving the existing rule.\n+- Time-off periods carry distinct natural non-working dates; periods are disjoint and include\n+ adjacent weekends, holidays and declared days at either horizon edge. Placements and declared\n+ working days anchor periods but do not themselves contribute non-working-day gain.\n+- Work sequences carry a working-day length and an `internal` flag. Weekends and holidays\n+ neither count nor split them. Both horizon-edge sequences contribute to the maximum and\n+ are excluded by the `internal` condition. Internal zero-length observations contribute zero\n+ deficit and are excluded by `non-empty`.\n+- Leave placements expose their supporting classification. Declared days are fixed observations\n+ and do not consume balances or count as supporting placements.\n+\n+`evaluateOptimization(configuration, observations)` validates the configuration and evaluates\n+these collections. The core's `optimizationObservations(state, context, periods?)` builds the\n+collections once; `evaluateStateOptimization(configuration, state, context)` is the shared core\n+seam for a personal rule. The preset metrics call the same evaluator, with no second engine.\n+\n+## Ordered rule execution\n+\n+Named `type: 'optimization'` rules contain a full `configuration` and preference-only\n+force. Storage, editor buffers, direct calculation snapshots and worker transport copy\n+the nested configuration. The core executes only explicitly submitted active rules;\n+it never adds presets to a request.\n+\n+Obligations are solved jointly. Each active preference then runs in the displayed\n+rule order. Disabled rules are excluded before validation and search. A request\n+with no active rules preserves declared days and adds no placements, including\n+when balances are at risk of expiry. Statistics may still report preset metrics;\n+only the active configured objectives affect selection.\n+\n+The shared core seams are:\n+\n+- `activeObjectiveVector(state, context, throughIndex?)` evaluates active preferences\n+ in display order, with unique `optimization:` and `preference:`\n+ identities. Optimization measurements use their full configurations; calendar\n+ preferences measure actual matching dates/patterns.\n+- `evaluateRuleCandidate(before, candidate, context, throughIndex, dates, sourceDate?,\n+addition?, baseline?, beforeVector?, incumbentVector?)` validates mandatory type/date/pattern memberships and earned\n+ entitlement availability and compares the active prefix. Its comparison preserves\n+ the source state; technical selection facts compare with the actual current best\n+ candidate. It returns the valid state, its full vector and\n+ optional trace evaluation. Additions must improve an active prefix objective.\n+- `optimizeRulePlacements(state, context, throughIndex, allowAdd, rule?)` generates\n+ single additions/removals/moves, atomic balance reassignments and balance swaps.\n+ `relocateForAddition` handles augmenting chains when a scarce balance needs an\n+ occupied date. Complete typed calendar patterns are reassigned atomically too.\n+ Coordinated family bundles can pass through `evaluateRuleCandidate` and rank through\n+ `compareObligationPreviews(candidate, incumbent, context)` without fixed metric guards.\n+- `applyPreferenceStep` dispatches every optimization and calendar window through\n+ the same kernel. Earlier preferences replay when a later rule changes their state\n+ or creates an earned entitlement.\n+\n+Earned entitlements follow actual completed active producer patterns, including patterns\n+already fulfilled by another rule or declared days. Shared finalization reconciles those\n+rights before candidate comparisons, cancellation retention and unchanged-state caching.\n+Availability starts after the complete merged producing period; its own reward cannot\n+finance a placement inside that period. Earning is a validity consequence, rather than\n+an extra objective that an active configuration can suppress.\n+\n+`compareObjectiveValues`, `compareObjectiveLists` and `firstDifferentObjective`\n+serve both selection and explanation. Earlier balance expiry and placement dates\n+are final tie-breaks after all active objectives compare equally; they only reshape\n+existing placements. Equal expiry values are compared independently of arbitrary balance\n+identifiers, so earlier placement dates remain the next tie-break. Captured rule identities, names and configurations label the\n+result independently of subsequent editor changes.\n+\n+Loaded plans retain the established sampling strategy for flexible move destinations\n+above 24 placements, including non-working-adjacent, weekly and calendar-window dates.\n+Excluded move destinations are recorded as `not-examined`, never as proven rejected.\n+There is no automatic elapsed-time cutoff. Complete holiday weeks, joined time-off\n+periods and work-sequence changes are compared as coordinated valid bundles.\n+Moves that preserve every active objective can be pruned when their final tie-breaks\n+cannot improve. Per-iteration vectors are reused; preset statistics are materialized\n+only for selected incumbents and published plans.\n+\n+For large non-earned window obligation searches above the existing exact-branch\n+threshold, the joint feasibility search retains its existing limit. Feasible\n+solutions are ranked by actual active objectives and final ties; the first eight\n+receive full optimization previews. Other feasible solutions are recorded as\n+`not-examined`. Small searches and earned-entitlement chains keep all previews.\n+This deterministic sampling has no elapsed-time cutoff or user-facing setting.\n+\n+A deferred optimization addition is supporting only when it provides one of the\n+calendar benefits in the domain definition, rather than merely extending a period.\n+Holiday occurrences and eligible patterns are immutable per request and cached\n+independently of mutable placement states.\n+\n+## Saved rules and initialization\n+\n+`vacationRules` uses one versioned envelope: `{ version: 1, rules: [...] }`.\n+`RuleService` restores it synchronously before the first duration estimate or calculation.\n+A legacy array, including `[]`, receives loss prevention first, every original record in\n+its original relative order, then the other five presets. Each original raw record is\n+preserved, including names, IDs, dates, parameters, disabled state and a missing legacy\n+force. Getters interpret missing force as preference without rewriting that record.\n+Preset IDs use collision-free suffixes when a personal rule already uses a proposed ID.\n+New users receive the six active presets around the existing Samedi Malin and Christmas\n+calendar defaults.\n+\n+The migration and its version are written by one synchronous `setItem`; no separate\n+marker can succeed while the rules fail to save. A failed write leaves the original\n+key intact and permits a later complete save or a fresh reload to retry. Failed reads,\n+malformed saved data and unsupported versions disable writes for that service instance\n+so later editing cannot overwrite unknown persisted user data. Storage unavailable\n+in the runtime leaves an in-memory configuration usable.\n+\n+Every later edit, toggle, reorder or deletion saves the full versioned list. Versioned\n+empty lists stay empty; disabled and deleted presets stay that way. With no active\n+rules, eligible unused leave remains visible with its original expiry classification\n+and a translated explanation that the active planning rules justified no addition.\n+Physical availability, occupation, expiry and incomplete-calculation reasons keep\n+precedence where they apply. Declared days remain fixed and consume no leave.\n+\n+## Search and trace limits\n+\n+These are deterministic search limits, rather than claims of global optimality:\n+\n+- Above 24 placements, flexible moves examine the existing non-working-adjacent,\n+ declared-adjacent, weekly and calendar-window destinations. Other destinations\n+ retain `not-examined` trace records.\n+- Non-earned obligation searches whose estimated branch count exceeds 10,000 retain\n+ at most 4,096 feasible solutions. Large window searches rank them by the actual\n+ active vector and final ties, then fully preview the first eight; the other\n+ feasible solutions are marked `not-examined`. Earned chains and small searches\n+ retain all previews.\n+- Calendar bundles rank original donors once by the actual active vector of the\n+ source plan with each donor released, then retain that order during recursive\n+ allocation. They keep the first prefix-valid allocation and collapse equivalent\n+ donor tokens. Work-sequence bundles use the nearest center per balance and the\n+ first accepted allocation. These choices can miss another coordinated allocation.\n+- When a completed specialized bundle strictly improves the current active prefix,\n+ the kernel commits its full-vector best before scanning generic alternatives for\n+ the old state. The old generic neighborhood is marked `not-examined`, then bundles\n+ and generic candidates continue from the improved state. Earlier preferences replay\n+ and the final expiry/date pass still runs. This scheduling can make a better unseen\n+ old-state generic branch unreachable; it is an explicit heuristic rather than an\n+ exhaustive comparison of all bundles and moves.\n+- Additions require a strict improvement through the current rule. A custom\n+ maximum/minimize unplaced-quantity rule with two tied at-risk CP1 balances can\n+ therefore keep both unused: either single addition leaves the maximum at one,\n+ while a coordinated addition of both would reduce it to zero. This balance\n+ plateau has no specialized bundle generator; the supplied sum/minimize loss\n+ preset does consume both.\n+\n+A completely enumerated single obligation solution has no alternative to rank, so\n+its discarded full preference preview is skipped; the real ordered execution still\n+runs in full. Earlier rules reuse their completed evaluation only when the complete\n+ordered incoming state matches their last output, including balance quantities and\n+validity, earned activations, placement insertion order, supporting status and rule\n+provenance. The trace records that unchanged state as `not-examined` with the earlier\n+decisions retained. A candidate unable to beat a valid local incumbent already\n+offered to cancellation retention keeps its primary comparison but avoids a duplicate\n+global incumbent comparison. These are exact reuse decisions, not additional sampling.\n+At the first explicit sum/minimize quantity preference, complete single additions can\n+reuse an evaluated funding score when eligible at-risk balances have the same expiry\n+and matching signature across every enabled time-window rule, including obligations.\n+The first original-order funder is preserved; later equivalent alternatives are recorded\n+as `not-examined` without fabricated comparisons. This applies only without active\n+IF_THEN rules or earned activations, without a balance maximum objective, and with a\n+safe combined remaining quantity. Recursive bundles and augmenting allocation retain\n+every funding choice: equal current scores do not prove equivalent future capacity.\n+A first-position sum/minimize unplaced-quantity rule finishes its preference stage when\n+its reconciled value reaches zero. The same bound applies to a prefix consisting of\n+that zero quantity followed only by fully satisfied time-window preferences or maximizing\n+public-holiday-week preferences at their configured upper bound. Windows are capped at\n+their requested quantity. A holiday maximum is evaluated from the same immutable request\n+weeks, marking every week complete and using its configured sum, count or maximum;\n+partial horizon weeks retain the existing declaration and eligibility semantics. The whole bounded stage is recorded as\n+`not-examined`; later preferences, replay after actual state changes and the final\n+full-vector expiry/date pass still run. Other configurations and preference orders\n+retain their search. This schedules lower priorities later; it does not claim an\n+exhaustive full-vector search in the bounded stage.\n+\n+When every balance is exhausted and there is no active IF_THEN rule, a complete generic\n+iteration that finds no full-vector improvement can be reused for the identical ordered\n+state at a later preference. Explicit balance assignments use the same dates, validity,\n+provenance and configured move sampling regardless of the current rule. Rule-specific\n+bundles still run, and any balance, placement, supporting, provenance or activation change\n+invalidates reuse. Bound returns and interrupted iterations never admit a state. Reuse\n+is recorded as `not-examined` with the earlier sampled generic decisions retained; the\n+final expiry/date pass still examines its neighborhood.\n+\n+Captured trace vectors, scalar facts, placements, ordered date lists and deltas are immutable detached evidence. Bounded\n+request-local indexes share only identical complete values and metadata; the vector\n+index uses recorded date keys and holds at most 65,536 entries, including variants in\n+one bucket. Eviction changes allocation only, with every examined candidate and its\n+ordered factual fields retained. Mutable candidate shells and emitted replacement\n+snapshots remain independent. Search never reads these sharing indexes. Calendar facts also reuse a bounded 4,096-entry request-local cache keyed by the complete occupied date set; balance quantities, earned metadata, provenance and supporting classifications are refreshed separately. Removing a placement copies the placement map without editing surviving entries; later assignment and metadata edits still detach them. Candidate locations are resolved from the latest recorded decision only when a later update or selection needs them, avoiding a permanent index for observation-only candidates.\n+\n+Cancellation retains the best valid examined plan under the captured active vector\n+and its original trace. Counterfactual and explanation comparisons use that same\n+snapshot; later editor changes and delayed artifact delivery do not alter it.\n+An explicit caller-owned planning-work budget remains supported; the application\n+introduces no automatic duration-based stop.\n+\n+## Confirmed decisions and technical assumptions\n+\n+Confirmed by ADR 0008: one composable model for supplied and personal optimization rules;\n+preference-only force; the six recipes' existing business meanings; declared-day and horizon\n+semantics; user-controlled active preference order; expiry then date tie-breaks; preserving\n+saved user data. The integrated implementation replaces the former implicit policy\n+with explicit active rules and performs the one-time saved-data addition.\n+\n+The supported configuration boundary is only sum/count/maximum and both directions; empty aggregate\n+zero; deficit threshold is a positive working-day integer, initially five; every listed\n+compatible condition subset and aggregation is supported; no other filters or measures.\n+Public-holiday weights retain the existing business definition rather than becoming a parameter.\n+\n+## Verification scope\n+\n+Ticket #75 covers saved-rule migration and functional integration of #70–#75.\n+Performance acceptance and any further optimization are tracked in #78, after\n+original-decision-trace removal in #76 and functional verification in #77. The\n+seven-scenario benchmark, its warm-up and two measured repetitions, the 2 GB heap\n+limit and the 300-second timeout remain unchanged. CI runs the benchmark as a\n+separate non-blocking job at the user's request while #78 is open; functional\n+tests and other checks remain required. #78 must restore the required benchmark\n+gate after the protocol passes. Completing the functional migration or passing\n+CI during this exception does not establish a passing benchmark.\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "docs/planning-objectives.md", "project_id": 35, "relative_order": 6, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -41,10 +41,11 @@ describe('leave planner benchmark protocol', () => {\n \t\t\t\t\tString(rttRule.startDate) <= String(cpRule.endDate),\n \t\t\t).toBe(true);\n \t\tconst chain = scenarios.find((scenario) => scenario.name === 'chained earned entitlements');\n-\t\texpect(chain?.request.rules?.map((rule) => rule.id)).toEqual([\n-\t\t\t'wednesday-holidays',\n-\t\t\t'thursday-consumer',\n-\t\t]);\n+\t\texpect(\n+\t\t\tchain?.request.rules\n+\t\t\t\t?.filter(({ type }) => type !== 'optimization')\n+\t\t\t\t.map((rule) => rule.id),\n+\t\t).toEqual(['wednesday-holidays', 'thursday-consumer']);\n \n \t\tconst browserWindow = globalThis.window;\n \t\tvi.stubGlobal('window', undefined);\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/benchmark/leave-planner-benchmark.spec.ts", "project_id": 35, "relative_order": 7, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -4,6 +4,7 @@ import {\n \tPlanningRequest,\n \tPlanningTrace,\n } from '../services/leave-planner.service';\n+import { createOptimizationPresetRules } from '../services/rule-service';\n \n export interface BenchmarkScenario {\n \tname: string;\n@@ -47,7 +48,8 @@ const balance = (\n \n export function benchmarkScenarios(): BenchmarkScenario[] {\n \tconst horizon = { start: '2024-01-01', end: '2025-01-01' };\n-\treturn [\n+\tconst presets = createOptimizationPresetRules();\n+\tconst scenarios: BenchmarkScenario[] = [\n \t\t{\n \t\t\tname: 'representative year',\n \t\t\trequest: {\n@@ -169,6 +171,13 @@ export function benchmarkScenarios(): BenchmarkScenario[] {\n \t\t\t}),\n \t\t),\n \t];\n+\treturn scenarios.map((scenario) => ({\n+\t\t...scenario,\n+\t\trequest: {\n+\t\t\t...scenario.request,\n+\t\t\trules: [presets[0], ...scenario.request.rules, ...presets.slice(1)],\n+\t\t},\n+\t}));\n }\n \n function resultSummary(outcome: PlanningOutcome): {\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/benchmark/leave-planner-benchmark.ts", "project_id": 35, "relative_order": 8, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,3 +1,4 @@\n+import { createOptimizationPresetRules } from '../../services/rule-service';\n import { provideZonelessChangeDetection } from '@angular/core';\n import { ComponentFixture, TestBed } from '@angular/core/testing';\n import { vi } from 'vitest';\n@@ -407,6 +408,8 @@ function jointTrace(): PlanningTrace {\n \t};\n }\n \n+const presets = createOptimizationPresetRules();\n+\n describe('CalendarYear planning outcome boundary', () => {\n \tbeforeEach(() => localStorage.clear());\n \tafterEach(() => {\n@@ -1342,7 +1345,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\t\t);\n \t\t\tif (outcome.kind !== 'Plan') throw new Error(`Expected Plan, got ${outcome.kind}`);\n \t\t\tlocalStorage.setItem('leaveBalances', '[]');\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tawait TestBed.configureTestingModule({\n \t\t\t\timports: [CalendarYear],\n \t\t\t\tproviders: [provideZonelessChangeDetection()],\n@@ -1421,7 +1424,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\t\t);\n \t\t\tif (outcome.kind !== 'Plan') throw new Error(`Expected Plan, got ${outcome.kind}`);\n \t\t\tlocalStorage.setItem('leaveBalances', '[]');\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tawait TestBed.configureTestingModule({\n \t\t\t\timports: [CalendarYear],\n \t\t\t\tproviders: [provideZonelessChangeDetection()],\n@@ -1496,7 +1499,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\t\t\t\t\texpiryDate: placementDate,\n \t\t\t\t\t},\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays: [\n \t\t\t\t\t{ date: '2024-08-01', type: 'cp' as const },\n \t\t\t\t\t...(fixedAnchor ? [{ date: '2024-07-31', type: 'other' as const }] : []),\n@@ -1524,7 +1527,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\t\t\t),\n \t\t\t);\n \t\t\tlocalStorage.setItem('leaveBalances', '[]');\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tawait TestBed.configureTestingModule({\n \t\t\t\timports: [CalendarYear],\n \t\t\t\tproviders: [provideZonelessChangeDetection()],\n@@ -1582,7 +1585,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \tit('previews a growing and shrinking range across months, then saves it once on release', async () => {\n \t\tlocalStorage.setItem('app.language', '\"fr\"');\n \t\tlocalStorage.setItem('leaveBalances', '[]');\n-\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\tawait TestBed.configureTestingModule({\n \t\t\timports: [CalendarYear, UserInput],\n \t\t\tproviders: [provideZonelessChangeDetection()],\n@@ -1749,7 +1752,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \n \tit('edits declarations from configuration and restores the preceding result when switched off', async () => {\n \t\tlocalStorage.setItem('app.language', '\"fr\"');\n-\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\tlocalStorage.setItem('leaveBalances', '[]');\n \t\tlocalStorage.setItem(\n \t\t\t'declaredNonWorkingDays',\n@@ -1844,7 +1847,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t});\n \n \tit('keeps the preceding calendar until a submitted snapshot returns and ignores later edits', async () => {\n-\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\tlocalStorage.setItem('leaveBalances', '[]');\n \t\tawait TestBed.configureTestingModule({\n \t\t\timports: [CalendarYear, UserInput],\n@@ -1987,7 +1990,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\tlet now = 1_000;\n \t\tconst clock = vi.spyOn(performance, 'now').mockImplementation(() => now);\n \t\ttry {\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tconst pending = deferred();\n \t\t\tconst trace = deferred();\n \t\t\tconst { calendar, calculation } = calendarFor(\n@@ -2100,7 +2103,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\tlet now = 1_000;\n \t\tconst clock = vi.spyOn(performance, 'now').mockImplementation(() => now);\n \t\ttry {\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tconst old = deferred();\n \t\t\tconst latest = deferred();\n \t\t\tconst { calendar, calculation } = calendarFor(plan);\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/components/calendar-year/calendar-year-planning.spec.ts", "project_id": 35, "relative_order": 9, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1536,6 +1536,24 @@ export class CalendarYear {\n \t}\n \n \tprotected objectiveCopy(id: string) {\n+\t\tif (id.startsWith('optimization:')) {\n+\t\t\tconst ruleId = id.slice('optimization:'.length);\n+\t\t\tconst rule = this.activeCalculation?.snapshot.rules.find(\n+\t\t\t\t(candidate) => candidate.id === ruleId,\n+\t\t\t);\n+\t\t\tconst copy = this.tr().planning.explanation.objectives['optimization'];\n+\t\t\treturn {\n+\t\t\t\t...copy,\n+\t\t\t\tlabel: copy.label\n+\t\t\t\t\t.replace('{rule}', this.ruleLabel(ruleId))\n+\t\t\t\t\t.replace(\n+\t\t\t\t\t\t'{summary}',\n+\t\t\t\t\t\trule && 'configuration' in rule\n+\t\t\t\t\t\t\t? this.translationService.optimizationSummary(rule.configuration)\n+\t\t\t\t\t\t\t: '',\n+\t\t\t\t\t),\n+\t\t\t};\n+\t\t}\n \t\tconst key = id.startsWith('preference:') ? 'preference' : id;\n \t\tconst copy = this.tr().planning.explanation.objectives[key];\n \t\tconst rule =\n@@ -1645,7 +1663,7 @@ export class CalendarYear {\n \t\tif (stage === 'validation') return 5;\n \t\tif (stage === 'obligations') return 20;\n \t\tif (stage === 'at-risk') return 35;\n-\t\tif (stage.startsWith('preference:')) return 50;\n+\t\tif (stage.startsWith('preference:') || stage.startsWith('optimization:')) return 50;\n \t\tif (stage === 'holiday-week-value') return 58;\n \t\tif (stage === 'non-working-day-gain') return 65;\n \t\tif (stage === 'longest-work-sequence') return 72;\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/components/calendar-year/calendar-year.ts", "project_id": 35, "relative_order": 10, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,241 @@\n+import { provideZonelessChangeDetection } from '@angular/core';\n+import { ComponentFixture, TestBed } from '@angular/core/testing';\n+import { By } from '@angular/platform-browser';\n+import { MatExpansionPanel } from '@angular/material/expansion';\n+import { RulesPanel } from './rules-panel';\n+import { RuleService, RuleType, type OptimizationRule } from '../../services/rule-service';\n+import { TranslationService } from '../../services/translation-service';\n+import {\n+\tOPTIMIZATION_PRESETS,\n+\ttype OptimizationConfiguration,\n+} from '../../services/planning-objectives';\n+import { calculatePlanningInternal } from '../../services/leave-planner.core';\n+\n+describe('calendar rule editing and persistence', () => {\n+\tlet fixture: ComponentFixture;\n+\tlet service: RuleService;\n+\tlet translations: TranslationService;\n+\n+\tasync function openEditor() {\n+\t\tawait TestBed.configureTestingModule({\n+\t\t\timports: [RulesPanel],\n+\t\t\tproviders: [provideZonelessChangeDetection()],\n+\t\t}).compileComponents();\n+\t\tservice = TestBed.inject(RuleService);\n+\t\ttranslations = TestBed.inject(TranslationService);\n+\t\ttranslations.setLanguage('fr');\n+\t\tfixture = TestBed.createComponent(RulesPanel);\n+\t\tfixture.detectChanges();\n+\t\tfixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open();\n+\t\tawait fixture.whenStable();\n+\t\tfixture.detectChanges();\n+\t}\n+\n+\tbeforeEach(async () => {\n+\t\tlocalStorage.clear();\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n+\t\tawait openEditor();\n+\t\tfor (const rule of service.rules) service.deleteRule(rule.id);\n+\t\tfixture.detectChanges();\n+\t});\n+\tafterEach(() => localStorage.clear());\n+\n+\tasync function select(label: string, value: string) {\n+\t\tconst fields: HTMLElement[] = Array.from(\n+\t\t\tfixture.nativeElement.querySelectorAll('mat-form-field'),\n+\t\t);\n+\t\tconst field = fields.find(\n+\t\t\t(candidate) => candidate.querySelector('mat-label')?.textContent?.trim() === label,\n+\t\t);\n+\t\tconst control = field?.querySelector('mat-select');\n+\t\tif (!control) throw new Error(`Missing labelled control: ${label}`);\n+\t\tconst labels = (control.getAttribute('aria-labelledby') ?? '')\n+\t\t\t.split(/\\s+/)\n+\t\t\t.map((id) => document.getElementById(id)?.textContent?.trim());\n+\t\texpect(labels).toContain(label);\n+\t\tcontrol.click();\n+\t\tawait fixture.whenStable();\n+\t\tconst option = Array.from(document.querySelectorAll('mat-option')).find(\n+\t\t\t(candidate) => candidate.textContent?.trim() === value,\n+\t\t);\n+\t\tif (!option) throw new Error(`Missing translated option: ${value}`);\n+\t\toption.click();\n+\t\tdocument.querySelector('.cdk-overlay-backdrop')?.click();\n+\t\tawait fixture.whenStable();\n+\t\tfixture.detectChanges();\n+\t}\n+\n+\tasync function add(name: string, configuration: OptimizationConfiguration) {\n+\t\tconst tr = translations.tr().rules;\n+\t\tconst buttons: HTMLButtonElement[] = Array.from(\n+\t\t\tfixture.nativeElement.querySelectorAll('.add-buttons button'),\n+\t\t);\n+\t\tbuttons.find((button) => button.textContent?.includes(tr.optimization.newRule))!.click();\n+\t\tawait fixture.whenStable();\n+\t\tconst nameInput: HTMLInputElement =\n+\t\t\tfixture.nativeElement.querySelector('.rule-editor input');\n+\t\tnameInput.value = name;\n+\t\tnameInput.dispatchEvent(new Event('input', { bubbles: true }));\n+\t\tawait select(\n+\t\t\ttr.optimization.elementsLabel,\n+\t\t\ttr.optimization.elements[configuration.elements],\n+\t\t);\n+\t\tfor (const condition of configuration.conditions)\n+\t\t\tawait select(tr.optimization.conditionsLabel, tr.optimization.conditions[condition]);\n+\t\tawait select(\n+\t\t\ttr.optimization.aggregationLabel,\n+\t\t\ttr.optimization.aggregations[configuration.aggregation],\n+\t\t);\n+\t\tawait select(\n+\t\t\ttr.optimization.directionLabel,\n+\t\t\ttr.optimization.directions[configuration.direction],\n+\t\t);\n+\t\tconst actions: HTMLButtonElement[] = Array.from(\n+\t\t\tfixture.nativeElement.querySelectorAll('.editor-actions button'),\n+\t\t);\n+\t\tactions.find((button) => button.textContent?.trim() === tr.add)!.click();\n+\t\tawait fixture.whenStable();\n+\t\tfixture.detectChanges();\n+\t}\n+\n+\tfunction calculate() {\n+\t\tlet objectiveValues: readonly { id: string; value: number | string }[] = [];\n+\t\tconst plan = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\tcalculationDate: '2024-04-01',\n+\t\t\t\thorizon: { start: '2024-04-29', end: '2024-05-18' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 3,\n+\t\t\t\t\t\tavailableFrom: '2024-04-29',\n+\t\t\t\t\t\texpiryDate: '2025-01-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules: service.rules,\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t({ explanation }) => {\n+\t\t\t\tif (explanation?.kind === 'PlanExplanation')\n+\t\t\t\t\tobjectiveValues = explanation.placements[0]?.objectiveVector.objectives ?? [];\n+\t\t\t},\n+\t\t);\n+\t\tif (plan.kind !== 'Plan')\n+\t\t\tthrow new Error('Expected a plan from saved editor configuration');\n+\t\treturn { plan, objectiveValues };\n+\t}\n+\n+\tit('creates both recipes, reverses their order, edits a compatible aggregation and restores it on reload', async () => {\n+\t\tawait add('Mes semaines fériées', OPTIMIZATION_PRESETS.holidayWeekValue);\n+\t\tawait add('Mes week-ends', OPTIMIZATION_PRESETS.nonWorkingDayGain);\n+\t\texpect(calculate().plan.metrics).toMatchObject({\n+\t\t\tholidayWeekValue: 5,\n+\t\t\tnonWorkingDayGain: 6,\n+\t\t});\n+\t\tconst items: HTMLElement[] = Array.from(\n+\t\t\tfixture.nativeElement.querySelectorAll('.rule-item'),\n+\t\t);\n+\t\titems[1].querySelector('.rule-actions button')!.click();\n+\t\tawait fixture.whenStable();\n+\t\tfixture.detectChanges();\n+\t\texpect(calculate().plan.metrics).toMatchObject({\n+\t\t\tholidayWeekValue: 0,\n+\t\t\tnonWorkingDayGain: 9,\n+\t\t});\n+\t\tconst holiday = service.rules.find(\n+\t\t\t(rule): rule is OptimizationRule =>\n+\t\t\t\trule.type === RuleType.OPTIMIZATION &&\n+\t\t\t\trule.configuration.elements === 'public-holiday-weeks',\n+\t\t)!;\n+\t\tfixture.componentInstance.startEdit(holiday, new Event('click'));\n+\t\tawait fixture.whenStable();\n+\t\tawait select(\n+\t\t\ttranslations.tr().rules.optimization.aggregationLabel,\n+\t\t\ttranslations.tr().rules.optimization.aggregations.count,\n+\t\t);\n+\t\tfixture.componentInstance.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\tawait expect\n+\t\t\t.poll(\n+\t\t\t\t() =>\n+\t\t\t\t\tJSON.parse(localStorage.getItem('vacationRules')!).rules[1]?.configuration\n+\t\t\t\t\t\t?.aggregation,\n+\t\t\t)\n+\t\t\t.toBe('count');\n+\t\tconst saved = service.rules;\n+\t\tTestBed.resetTestingModule();\n+\t\tawait openEditor();\n+\t\texpect(service.rules).toEqual(saved);\n+\t\texpect(calculate().plan.metrics).toMatchObject({\n+\t\t\tholidayWeekValue: 0,\n+\t\t\tnonWorkingDayGain: 9,\n+\t\t});\n+\t\tfixture.componentInstance.moveRule(1, -1, new Event('click'));\n+\t\tconst edited = calculate();\n+\t\texpect(edited.plan.metrics.holidayWeekValue).toBe(5);\n+\t\texpect(\n+\t\t\tedited.objectiveValues.find(\n+\t\t\t\t(objective) => objective.id === `optimization:${holiday.id}`,\n+\t\t\t)?.value,\n+\t\t).toBe(1);\n+\t});\n+\n+\tit('creates economy, edits its name, moves it with the focusable control and restores disable/delete choices', async () => {\n+\t\tawait add('Mes semaines fériées', OPTIMIZATION_PRESETS.holidayWeekValue);\n+\t\tawait add('Économiser les jours d’appoint', OPTIMIZATION_PRESETS.supportingPlacements);\n+\t\tconst economy = service.rules[1];\n+\t\texpect(economy).toMatchObject({\n+\t\t\tforce: 'preference',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t});\n+\t\texpect(calculate().plan.metrics.supportingPlacements).toBe(3);\n+\t\tconst move: HTMLButtonElement = fixture.nativeElement\n+\t\t\t.querySelectorAll('.rule-item')[1]\n+\t\t\t.querySelector('.rule-actions button');\n+\t\tmove.focus();\n+\t\texpect(document.activeElement).toBe(move);\n+\t\tmove.click();\n+\t\tawait fixture.whenStable();\n+\t\texpect(calculate().plan.placements).toEqual([]);\n+\n+\t\tfixture.componentInstance.startEdit(service.rules[0], new Event('click'));\n+\t\tawait fixture.whenStable();\n+\t\tconst input: HTMLInputElement = fixture.nativeElement.querySelector('.rule-editor input');\n+\t\tinput.value = 'Mes jours conservés';\n+\t\tinput.dispatchEvent(new Event('input', { bubbles: true }));\n+\t\tfixture.componentInstance.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\tconst toggle: HTMLButtonElement = fixture.nativeElement\n+\t\t\t.querySelector('.rule-item')\n+\t\t\t.querySelector('button[role=\"switch\"]');\n+\t\ttoggle.click();\n+\t\tawait fixture.whenStable();\n+\t\texpect(calculate().plan.metrics.supportingPlacements).toBe(3);\n+\t\tawait expect\n+\t\t\t.poll(() => JSON.parse(localStorage.getItem('vacationRules')!).rules[0]?.enabled)\n+\t\t\t.toBe(false);\n+\t\tconst saved = service.rules;\n+\t\tTestBed.resetTestingModule();\n+\t\tawait openEditor();\n+\t\texpect(service.rules).toEqual(saved);\n+\t\texpect(service.rules[0]).toMatchObject({ id: economy.id, name: 'Mes jours conservés' });\n+\t\texpect(calculate().plan.metrics.supportingPlacements).toBe(3);\n+\t\tfixture.componentInstance.toggleRule(economy.id);\n+\t\tawait fixture.whenStable();\n+\t\texpect(calculate().plan.placements).toEqual([]);\n+\t\tconst remove: HTMLButtonElement = fixture.nativeElement\n+\t\t\t.querySelector('.rule-item')\n+\t\t\t.querySelector(`[aria-label=\"${translations.tr().rules.deleteRule}\"]`);\n+\t\tremove.click();\n+\t\tawait fixture.whenStable();\n+\t\texpect(calculate().plan.metrics.supportingPlacements).toBe(3);\n+\t\tawait expect\n+\t\t\t.poll(() => JSON.parse(localStorage.getItem('vacationRules')!).rules.length)\n+\t\t\t.toBe(1);\n+\t\tTestBed.resetTestingModule();\n+\t\tawait openEditor();\n+\t\texpect(service.rules.map(({ id }) => id)).not.toContain(economy.id);\n+\t\texpect(calculate().plan.metrics.supportingPlacements).toBe(3);\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/components/rules-panel/calendar-rule-editor.spec.ts", "project_id": 35, "relative_order": 11, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -183,6 +183,8 @@\n \t\t\t\t\t\t\t\t\t\n \t\t\t\t\t\t\t\t\n \t\t\t\t\t\t\t\n+\t\t\t\t\t\t} @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) {\n+\t\t\t\t\t\t\t\n \t\t\t\t\t\t} @else {\n \t\t\t\t\t\t\t
\n \t\t\t\t\t\t\t\t\n@@ -239,6 +241,9 @@\n \t\t\t\t\t\t\t
\n \t\t\t\t\t\t}\n \n+\t\t\t\t\t\t@if (validationError()) {\n+\t\t\t\t\t\t\t

{{ validationError() }}

\n+\t\t\t\t\t\t}\n \t\t\t\t\t\t
\n \t\t\t\t\t\t\t
\n+\t\t\t\t\t} @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) {\n+\t\t\t\t\t\t\n \t\t\t\t\t} @else {\n \t\t\t\t\t\t
\n \t\t\t\t\t\t\t\n@@ -394,6 +401,9 @@\n \t\t\t\t\t\t
\n \t\t\t\t\t}\n \n+\t\t\t\t\t@if (validationError()) {\n+\t\t\t\t\t\t

{{ validationError() }}

\n+\t\t\t\t\t}\n \t\t\t\t\t
\n \t\t\t\t\t\t\n \t\t\t\t\t\t\n+\t\t\t\n \t\t
\n \t\n \n+\n+\n+\t@if (optimizationConfiguration; as configuration) {\n+\t\t
\n+\t\t\t\n+\t\t\t\t{{ tr().rules.optimization.elementsLabel }}\n+\t\t\t\t\n+\t\t\t\t\t@for (elements of optimizationElements; track elements) {\n+\t\t\t\t\t\t{{\n+\t\t\t\t\t\t\ttr().rules.optimization.elements[elements]\n+\t\t\t\t\t\t}}\n+\t\t\t\t\t}\n+\t\t\t\t\n+\t\t\t\n+\t\t\t\n+\t\t\t\t{{ tr().rules.optimization.measureLabel }}\n+\t\t\t\t\n+\t\t\t\t\t@for (row of optimizationMeasures; track row.measure) {\n+\t\t\t\t\t\t{{\n+\t\t\t\t\t\t\ttr().rules.optimization.measures[row.measure]\n+\t\t\t\t\t\t}}\n+\t\t\t\t\t}\n+\t\t\t\t\n+\t\t\t\n+\t\t
\n+\t\t@if (optimizationConditions.length) {\n+\t\t\t\n+\t\t\t\t{{ tr().rules.optimization.conditionsLabel }}\n+\t\t\t\t\n+\t\t\t\t\t@for (condition of optimizationConditions; track condition) {\n+\t\t\t\t\t\t{{\n+\t\t\t\t\t\t\ttr().rules.optimization.conditions[condition]\n+\t\t\t\t\t\t}}\n+\t\t\t\t\t}\n+\t\t\t\t\n+\t\t\t\n+\t\t}\n+\t\t
\n+\t\t\t\n+\t\t\t\t{{ tr().rules.optimization.aggregationLabel }}\n+\t\t\t\t\n+\t\t\t\t\t@for (aggregation of optimizationAggregations; track aggregation) {\n+\t\t\t\t\t\t{{\n+\t\t\t\t\t\t\ttr().rules.optimization.aggregations[aggregation]\n+\t\t\t\t\t\t}}\n+\t\t\t\t\t}\n+\t\t\t\t\n+\t\t\t\n+\t\t\t\n+\t\t\t\t{{ tr().rules.optimization.directionLabel }}\n+\t\t\t\t\n+\t\t\t\t\t@for (direction of optimizationDirections; track direction) {\n+\t\t\t\t\t\t{{\n+\t\t\t\t\t\t\ttr().rules.optimization.directions[direction]\n+\t\t\t\t\t\t}}\n+\t\t\t\t\t}\n+\t\t\t\t\n+\t\t\t\n+\t\t\t@if (configuration.measure === 'work-sequence-deficit') {\n+\t\t\t\t\n+\t\t\t\t\t{{ tr().rules.optimization.thresholdLabel }}\n+\t\t\t\t\t\n+\t\t\t\t\n+\t\t\t}\n+\t\t
\n+\t}\n+
\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/components/rules-panel/rules-panel.html", "project_id": 35, "relative_order": 12, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -7,6 +7,8 @@ import { By } from '@angular/platform-browser';\n import { CdkDragDrop, CdkDropList } from '@angular/cdk/drag-drop';\n import { LiveAnnouncer } from '@angular/cdk/a11y';\n import { vi } from 'vitest';\n+import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';\n+import { MatExpansionPanel } from '@angular/material/expansion';\n \n describe('RulesPanel', () => {\n \tlet component: RulesPanel;\n@@ -36,7 +38,7 @@ describe('RulesPanel', () => {\n \t});\n \n \tit('should display initial rules from service', () => {\n-\t\texpect(component.rules.length).toBe(2);\n+\t\texpect(component.rules.length).toBe(8);\n \t});\n \n \tit('should start adding new If-Then rule', () => {\n@@ -116,6 +118,69 @@ describe('RulesPanel', () => {\n \t\texpect(component.rules[0].id).toBe(secondRuleId);\n \t});\n \n+\tit('creates, edits and moves an optimization using the keyboard controls with preference-only mode', async () => {\n+\t\tfixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open();\n+\t\tcomponent.startAddNew(RuleType.OPTIMIZATION);\n+\t\tfixture.detectChanges();\n+\t\texpect(component['forceOptions'].map((option) => option.value)).toEqual(['preference']);\n+\t\texpect(fixture.nativeElement.textContent).toContain('Éléments du planning');\n+\t\tcomponent['editBuffer'].name = 'Mes pertes';\n+\t\tcomponent.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\tconst rule = component.rules.at(-1)!;\n+\t\texpect(rule).toMatchObject({\n+\t\t\tname: 'Mes pertes',\n+\t\t\ttype: RuleType.OPTIMIZATION,\n+\t\t\tforce: 'preference',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t});\n+\t\texpect(component.getRuleSummary(rule)).toContain('Quantité non placée');\n+\t\tconst announce = vi.spyOn(TestBed.inject(LiveAnnouncer), 'announce').mockResolvedValue();\n+\t\tconst buttons = fixture.nativeElement.querySelectorAll('.rule-item');\n+\t\tconst moveUp: HTMLButtonElement =\n+\t\t\tbuttons[buttons.length - 1].querySelector('.rule-actions button');\n+\t\tmoveUp.focus();\n+\t\tmoveUp.click();\n+\t\tawait fixture.whenStable();\n+\t\texpect(component.rules[7].id).toBe(rule.id);\n+\t\texpect(document.activeElement).toBe(moveUp);\n+\t\texpect(announce).toHaveBeenCalledWith('Mes pertes : position 8 sur 9.');\n+\t\tcomponent.startEdit(rule, new Event('click'));\n+\t\tcomponent['editBuffer'].name = 'Pertes modifiées';\n+\t\tcomponent.saveEdit();\n+\t\texpect(component.rules[7].name).toBe('Pertes modifiées');\n+\t\tcomponent.toggleRule(rule.id);\n+\t\texpect(component.rules[7].enabled).toBe(false);\n+\t\tcomponent.deleteRule(rule.id, new Event('click'));\n+\t\texpect(component.rules.some((candidate) => candidate.id === rule.id)).toBe(false);\n+\t});\n+\n+\tit('keeps saved optimization parameters when an edit is cancelled and reports invalid parameters', () => {\n+\t\tcomponent.startAddNew(RuleType.OPTIMIZATION);\n+\t\tcomponent.saveEdit();\n+\t\tconst rule = component.rules.at(-1)!;\n+\t\tcomponent.startEdit(rule, new Event('click'));\n+\t\tconst configuration = component['optimizationConfiguration']!;\n+\t\tconfiguration.conditions = [];\n+\t\tcomponent.cancelEdit();\n+\t\texpect(component.rules.at(-1)).toMatchObject({\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t});\n+\t\tcomponent.startEdit(rule, new Event('click'));\n+\t\tcomponent.changeOptimizationMeasure('work-sequence-deficit');\n+\t\tconst invalid = component['optimizationConfiguration'];\n+\t\tif (invalid?.measure !== 'work-sequence-deficit') throw new Error('Expected deficit');\n+\t\tinvalid.thresholdDays = 0;\n+\t\tcomponent.saveEdit();\n+\t\tfixture.detectChanges();\n+\t\texpect(fixture.nativeElement.querySelector('[role=\"alert\"]').textContent).toContain(\n+\t\t\t'seuil entier positif',\n+\t\t);\n+\t\texpect(component.rules.at(-1)).toMatchObject({\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t});\n+\t});\n+\n \tit('keeps cancelled drops unchanged and announces the position after a completed drop', () => {\n \t\tconst initialIds = component.rules.map((rule) => rule.id);\n \t\tconst movedName = component.rules[0].name;\n@@ -133,8 +198,12 @@ describe('RulesPanel', () => {\n \t\texpect(announce).not.toHaveBeenCalled();\n \n \t\tlist.dropped.emit({ ...drop, isPointerOverContainer: true });\n-\t\texpect(component.rules.map((rule) => rule.id)).toEqual([...initialIds].reverse());\n-\t\texpect(announce).toHaveBeenCalledWith(`${movedName} : position 2 sur 2.`);\n+\t\texpect(component.rules.map((rule) => rule.id)).toEqual([\n+\t\t\tinitialIds[1],\n+\t\t\tinitialIds[0],\n+\t\t\t...initialIds.slice(2),\n+\t\t]);\n+\t\texpect(announce).toHaveBeenCalledWith(`${movedName} : position 2 sur 8.`);\n \t\t// CDK restores the original DOM before emitting dropped. The new order must\n \t\t// be rendered before this callback returns, without waiting for another frame.\n \t\texpect(fixture.nativeElement.querySelectorAll('.rule-name')[1].textContent).toContain(\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/components/rules-panel/rules-panel.spec.ts", "project_id": 35, "relative_order": 13, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -11,6 +11,7 @@ import {\n \tRuleType,\n \tIfThenRule,\n \tTimeWindowRule,\n+\tOptimizationRule,\n \tVacationRule,\n \tPlacementStrategy,\n } from '../../services/rule-service';\n@@ -25,7 +26,15 @@ import { MatInputModule } from '@angular/material/input';\n import { MatSelectModule } from '@angular/material/select';\n import { MatDatepickerModule } from '@angular/material/datepicker';\n import { FormsModule } from '@angular/forms';\n+import { NgTemplateOutlet } from '@angular/common';\n import { LiveAnnouncer } from '@angular/cdk/a11y';\n+import {\n+\tOPTIMIZATION_CATALOG,\n+\tOPTIMIZATION_PRESETS,\n+\tvalidateOptimizationConfiguration,\n+\ttype OptimizationElements,\n+\ttype OptimizationMeasure,\n+} from '../../services/planning-objectives';\n \n import { DateAdapter } from '@angular/material/core';\n import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter';\n@@ -43,6 +52,7 @@ import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/d\n \t\tMatSelectModule,\n \t\tMatDatepickerModule,\n \t\tFormsModule,\n+\t\tNgTemplateOutlet,\n \t\tCdkDropList,\n \t\tCdkDrag,\n \t\tCdkDragHandle,\n@@ -74,10 +84,67 @@ export class RulesPanel {\n \tprotected readonly rewardDayTypes = Object.values(SelectableDayType).filter(\n \t\t(t) => t !== SelectableDayType.ANY,\n \t);\n-\tprotected readonly forceOptions = [\n-\t\t{ value: 'obligation' as const, label: () => this.tr().rules.obligation },\n-\t\t{ value: 'preference' as const, label: () => this.tr().rules.preference },\n+\tprotected get forceOptions() {\n+\t\tconst preference = {\n+\t\t\tvalue: 'preference' as const,\n+\t\t\tlabel: () => this.tr().rules.preference,\n+\t\t};\n+\t\treturn this.editBuffer.type === RuleType.OPTIMIZATION\n+\t\t\t? [preference]\n+\t\t\t: [\n+\t\t\t\t\t{ value: 'obligation' as const, label: () => this.tr().rules.obligation },\n+\t\t\t\t\tpreference,\n+\t\t\t\t];\n+\t}\n+\tprotected readonly optimizationElements = [\n+\t\t...new Set(OPTIMIZATION_CATALOG.map((row) => row.elements)),\n \t];\n+\tprotected get optimizationConfiguration() {\n+\t\treturn this.editBuffer.type === RuleType.OPTIMIZATION\n+\t\t\t? this.editBuffer.configuration\n+\t\t\t: undefined;\n+\t}\n+\tprotected get optimizationMeasures() {\n+\t\treturn OPTIMIZATION_CATALOG.filter(\n+\t\t\t(row) => row.elements === this.optimizationConfiguration?.elements,\n+\t\t);\n+\t}\n+\tprotected get optimizationConditions() {\n+\t\treturn (\n+\t\t\tthis.optimizationMeasures.find(\n+\t\t\t\t(row) => row.measure === this.optimizationConfiguration?.measure,\n+\t\t\t)?.conditions ?? []\n+\t\t);\n+\t}\n+\tprotected readonly optimizationAggregations = ['sum', 'count', 'maximum'] as const;\n+\tprotected readonly optimizationDirections = ['minimize', 'maximize'] as const;\n+\tprotected validationError = signal('');\n+\n+\tpublic changeOptimizationElements(elements: OptimizationElements) {\n+\t\tthis.changeOptimizationMeasure(\n+\t\t\tOPTIMIZATION_CATALOG.find((row) => row.elements === elements)!.measure,\n+\t\t);\n+\t}\n+\n+\tpublic changeOptimizationMeasure(measure: OptimizationMeasure) {\n+\t\tif (this.editBuffer.type !== RuleType.OPTIMIZATION) return;\n+\t\tconst row = OPTIMIZATION_CATALOG.find((item) => item.measure === measure)!;\n+\t\tconst previous = this.editBuffer.configuration;\n+\t\tconst conditions: readonly string[] = row.conditions;\n+\t\tthis.editBuffer.configuration = {\n+\t\t\telements: row.elements,\n+\t\t\tconditions:\n+\t\t\t\tprevious?.conditions.filter((condition) => conditions.includes(condition)) ?? [],\n+\t\t\taggregation: previous?.aggregation ?? 'sum',\n+\t\t\tdirection: previous?.direction ?? 'minimize',\n+\t\t\t...(measure === 'work-sequence-deficit'\n+\t\t\t\t? {\n+\t\t\t\t\t\tmeasure,\n+\t\t\t\t\t\tthresholdDays: previous?.measure === measure ? previous.thresholdDays : 5,\n+\t\t\t\t\t}\n+\t\t\t\t: { measure }),\n+\t\t};\n+\t}\n \n \tprotected get daysOfWeek() {\n \t\tconst tr = this.tr();\n@@ -128,9 +195,20 @@ export class RulesPanel {\n \n \tpublic moveRule(index: number, offset: -1 | 1, event: Event) {\n \t\tevent.stopPropagation();\n+\t\tconst trigger = event.currentTarget;\n \t\tconst destination = index + offset;\n-\t\tif (destination >= 0 && destination < this.rules.length)\n+\t\tif (destination >= 0 && destination < this.rules.length) {\n \t\t\tthis.reorderRule(index, destination);\n+\t\t\tthis.changeDetector.detectChanges();\n+\t\t\tif (trigger instanceof HTMLButtonElement) {\n+\t\t\t\tconst next = trigger.disabled\n+\t\t\t\t\t? trigger.parentElement?.querySelector(\n+\t\t\t\t\t\t\t'button:not([disabled])',\n+\t\t\t\t\t\t)\n+\t\t\t\t\t: trigger;\n+\t\t\t\tnext?.focus();\n+\t\t\t}\n+\t\t}\n \t}\n \n \tprivate reorderRule(from: number, to: number) {\n@@ -152,16 +230,29 @@ export class RulesPanel {\n \t\tevent.stopPropagation();\n \t\tthis.editingRuleId.set(rule.id);\n \t\tthis.isAddingNew.set(false);\n-\t\tthis.editBuffer = { ...rule };\n+\t\tthis.editBuffer = structuredClone(rule);\n+\t\tthis.validationError.set('');\n \t}\n \n \tpublic cancelEdit() {\n \t\tthis.editingRuleId.set(null);\n \t\tthis.isAddingNew.set(false);\n \t\tthis.editBuffer = {};\n+\t\tthis.validationError.set('');\n \t}\n \n \tpublic saveEdit() {\n+\t\tif (!this.editBuffer.name?.trim()) {\n+\t\t\tthis.validationError.set(this.tr().rules.optimization.nameRequired);\n+\t\t\treturn;\n+\t\t}\n+\t\tif (this.editBuffer.type === RuleType.OPTIMIZATION) {\n+\t\t\tif (!validateOptimizationConfiguration(this.editBuffer.configuration).valid) {\n+\t\t\t\tthis.validationError.set(this.tr().rules.optimization.invalidConfiguration);\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\tthis.editBuffer.force = 'preference';\n+\t\t}\n \t\tif (this.editBuffer.id) {\n \t\t\tthis.ruleService.updateRule(this.editBuffer as VacationRule);\n \t\t} else {\n@@ -183,6 +274,7 @@ export class RulesPanel {\n \t\tthis.isAddingNew.set(true);\n \t\tthis.editingRuleId.set(null);\n \t\tthis.newRuleType.set(type);\n+\t\tthis.validationError.set('');\n \n \t\tif (type === RuleType.IF_THEN) {\n \t\t\tthis.editBuffer = {\n@@ -196,6 +288,13 @@ export class RulesPanel {\n \t\t\t\trewardDays: 1,\n \t\t\t\trewardType: SelectableDayType.OTHER,\n \t\t\t} as Partial;\n+\t\t} else if (type === RuleType.OPTIMIZATION) {\n+\t\t\tthis.editBuffer = {\n+\t\t\t\tname: this.tr().rules.optimization.defaultName,\n+\t\t\t\ttype,\n+\t\t\t\tforce: 'preference',\n+\t\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),\n+\t\t\t} satisfies Partial;\n \t\t} else {\n \t\t\tthis.editBuffer = {\n \t\t\t\tname: this.tr().rules.defaultNewPeriodName,\n@@ -216,6 +315,8 @@ export class RulesPanel {\n \n \tpublic getRuleSummary(rule: VacationRule): string {\n \t\tconst tr = this.tr();\n+\t\tif (rule.type === RuleType.OPTIMIZATION)\n+\t\t\treturn this.translationService.optimizationSummary(rule.configuration);\n \t\tif (rule.type === RuleType.IF_THEN) {\n \t\t\tconst ifThen = rule as IfThenRule;\n \t\t\tconst dayLabel = this.daysOfWeek.find((d) => d.value === ifThen.dayOfWeek)?.label ?? '';\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/components/rules-panel/rules-panel.ts", "project_id": 35, "relative_order": 14, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,172 @@\n+import { provideZonelessChangeDetection } from '@angular/core';\n+import { TestBed, type ComponentFixture } from '@angular/core/testing';\n+import { By } from '@angular/platform-browser';\n+import { MatExpansionPanel } from '@angular/material/expansion';\n+import { vi } from 'vitest';\n+import { RuleService, RuleType } from '../../services/rule-service';\n+import { TranslationService } from '../../services/translation-service';\n+import { calculatePlanningInternal } from '../../services/leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';\n+import { RulesPanel } from './rules-panel';\n+\n+describe('work-sequence rule editor and reload', () => {\n+\tlet fixture: ComponentFixture;\n+\tlet component: RulesPanel;\n+\n+\tasync function choose(label: string, text: string) {\n+\t\tconst fields: HTMLElement[] = Array.from(\n+\t\t\tfixture.nativeElement.querySelectorAll('mat-form-field'),\n+\t\t);\n+\t\tconst select = fields\n+\t\t\t.find((field) => field.querySelector('mat-label')?.textContent?.trim() === label)\n+\t\t\t?.querySelector('mat-select');\n+\t\tif (!select) throw new Error(`Missing select ${label}`);\n+\t\tselect.click();\n+\t\tawait fixture.whenStable();\n+\t\tconst option = Array.from(document.querySelectorAll('mat-option')).find(\n+\t\t\t(candidate) => candidate.textContent?.trim() === text,\n+\t\t);\n+\t\tif (!option) throw new Error(`Missing option ${text}`);\n+\t\toption.click();\n+\t\tawait fixture.whenStable();\n+\t\tdocument.querySelector('.cdk-overlay-backdrop')?.click();\n+\t\tawait fixture.whenStable();\n+\t}\n+\n+\tasync function setInput(selector: string, value: string) {\n+\t\tconst input: HTMLInputElement = fixture.nativeElement.querySelector(selector);\n+\t\tinput.value = value;\n+\t\tinput.dispatchEvent(new Event('input'));\n+\t\tawait fixture.whenStable();\n+\t}\n+\n+\tbeforeEach(async () => {\n+\t\tlocalStorage.clear();\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n+\t\tvi.setSystemTime(new Date('2024-01-01T12:00:00Z'));\n+\t\tawait TestBed.configureTestingModule({\n+\t\t\timports: [RulesPanel],\n+\t\t\tproviders: [provideZonelessChangeDetection()],\n+\t\t}).compileComponents();\n+\t\tTestBed.inject(TranslationService).setLanguage('fr');\n+\t\tfixture = TestBed.createComponent(RulesPanel);\n+\t\tcomponent = fixture.componentInstance;\n+\t\tfixture.detectChanges();\n+\t\tfixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open();\n+\t});\n+\tafterEach(() => {\n+\t\tlocalStorage.clear();\n+\t\tvi.useRealTimers();\n+\t});\n+\n+\tit('creates threshold five, edits it to three, and restores its effect, order and activation after reload', async () => {\n+\t\tcomponent.startAddNew(RuleType.OPTIMIZATION);\n+\t\tawait fixture.whenStable();\n+\t\tawait setInput('input:not([type=\"number\"])', 'Mes reprises');\n+\t\tawait choose('Éléments du planning', 'Séquences de travail');\n+\t\tawait choose('Mesure', 'Déficit des séquences de travail');\n+\t\tawait choose('Conditions (toutes doivent être vérifiées)', 'Internes');\n+\t\tawait choose('Conditions (toutes doivent être vérifiées)', 'Non vides');\n+\t\tconst threshold: HTMLInputElement =\n+\t\t\tfixture.nativeElement.querySelector('input[type=\"number\"]');\n+\t\texpect(threshold.value).toBe('5');\n+\t\texpect(threshold.min).toBe('1');\n+\t\texpect(threshold.step).toBe('1');\n+\t\texpect(fixture.nativeElement.textContent).toContain('Seuil de préférence en jours ouvrés');\n+\t\tcomponent.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\tconst rule = component.rules[0];\n+\t\texpect(rule).toMatchObject({ configuration: OPTIMIZATION_PRESETS.shortSequenceDeficit });\n+\t\texpect(component.getRuleSummary(rule)).toContain(\n+\t\t\t'Déficit des séquences de travail (jours ouvrés)',\n+\t\t);\n+\t\tconst request = {\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: ['2024-01-08', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\t\t};\n+\t\texpect(calculatePlanningInternal({ ...request, rules: component.rules })).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [{ date: '2024-01-09' }, { date: '2024-01-10' }, { date: '2024-01-11' }],\n+\t\t});\n+\t\tcomponent.startEdit(rule, new Event('click'));\n+\t\tawait fixture.whenStable();\n+\t\tawait setInput('input[type=\"number\"]', '3');\n+\t\tcomponent.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\texpect(component.getRuleSummary(component.rules[0])).toContain(\n+\t\t\t'seuil de préférence : 3 jours ouvrés',\n+\t\t);\n+\t\texpect(calculatePlanningInternal({ ...request, rules: component.rules })).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [],\n+\t\t});\n+\n+\t\tcomponent.startAddNew(RuleType.OPTIMIZATION);\n+\t\tawait fixture.whenStable();\n+\t\tawait setInput('input:not([type=\"number\"])', 'Ma séquence maximale');\n+\t\tawait choose('Éléments du planning', 'Séquences de travail');\n+\t\tawait choose('Agrégation', 'Maximum');\n+\t\tcomponent.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\tconst maximum = component.rules[1];\n+\t\texpect(maximum).toMatchObject({ configuration: OPTIMIZATION_PRESETS.longestWorkSequence });\n+\t\tcomponent.toggleRule(maximum.id);\n+\t\tawait fixture.whenStable();\n+\t\tconst moveUp: HTMLButtonElement = fixture.nativeElement\n+\t\t\t.querySelectorAll('.rule-actions')[1]\n+\t\t\t.querySelector('button');\n+\t\tmoveUp.focus();\n+\t\tmoveUp.click();\n+\t\tawait fixture.whenStable();\n+\t\tconst saved = component.rules;\n+\t\tawait new Promise((resolve) => setTimeout(resolve, 350));\n+\t\tTestBed.resetTestingModule();\n+\t\tconst restored = TestBed.inject(RuleService).rules;\n+\t\texpect(restored).toEqual(saved);\n+\t\texpect(restored.map(({ id }) => id)).toEqual([maximum.id, rule.id]);\n+\t\texpect(restored[0].enabled).toBe(false);\n+\t\texpect(restored[1]).toMatchObject({\n+\t\t\tname: 'Mes reprises',\n+\t\t\tenabled: true,\n+\t\t\tconfiguration: { thresholdDays: 3 },\n+\t\t});\n+\t\texpect(calculatePlanningInternal({ ...request, rules: restored })).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [],\n+\t\t});\n+\t});\n+\n+\tit('keeps the saved threshold and shows an accessible error for fractional input', async () => {\n+\t\tcomponent.startAddNew(RuleType.OPTIMIZATION);\n+\t\tcomponent.changeOptimizationMeasure('work-sequence-deficit');\n+\t\tawait fixture.whenStable();\n+\t\tawait setInput('input[type=\"number\"]', '1.5');\n+\t\tcomponent.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\texpect(component.rules).toEqual([]);\n+\t\texpect(fixture.nativeElement.querySelector('[role=\"alert\"]').textContent).toContain(\n+\t\t\t'seuil entier positif',\n+\t\t);\n+\t\texpect(fixture.nativeElement.querySelector('input[type=\"number\"]').value).toBe('1.5');\n+\t});\n+\n+\tit('distinguishes aggregation units from the working-day threshold', () => {\n+\t\tconst translations = TestBed.inject(TranslationService);\n+\t\texpect(\n+\t\t\ttranslations.optimizationSummary(OPTIMIZATION_PRESETS.longestWorkSequence),\n+\t\t).toContain('Longueur des séquences de travail (jours ouvrés)');\n+\t\texpect(\n+\t\t\ttranslations.optimizationSummary({\n+\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\taggregation: 'count',\n+\t\t\t}),\n+\t\t).toContain('Déficit des séquences de travail (Nombre)');\n+\t\texpect(\n+\t\t\ttranslations.optimizationSummary({\n+\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\taggregation: 'count',\n+\t\t\t}),\n+\t\t).toContain('seuil de préférence : 5 jours ouvrés');\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/components/rules-panel/work-sequence-rule-editor.spec.ts", "project_id": 35, "relative_order": 15, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,3 +1,4 @@\n+import { createOptimizationPresetRules } from '../../services/rule-service';\n import { ComponentFixture, TestBed } from '@angular/core/testing';\n import { provideZonelessChangeDetection } from '@angular/core';\n import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';\n@@ -14,6 +15,8 @@ import { CalendarSettingsService } from '../../services/calendar-settings-servic\n import { createPlanningCalculation, PlanningRequest } from '../../services/leave-planner.service';\n import { TranslationService } from '../../services/translation-service';\n \n+const presets = createOptimizationPresetRules();\n+\n describe('UserInput', () => {\n \tlet component: UserInput;\n \tlet fixture: ComponentFixture;\n@@ -145,7 +148,7 @@ describe('UserInput', () => {\n \t\t\t\t},\n \t\t\t],\n \t\t\tdeclaredDays: [{ date: '2024-06-07', type: 'cp' }],\n-\t\t\trules: [],\n+\t\t\trules: [presets[3]],\n \t\t});\n \t\tconst root = fixture.nativeElement as HTMLElement;\n \t\tconst card = root.querySelector('.warning-card')!;\n@@ -162,7 +165,7 @@ describe('UserInput', () => {\n \t\tfixture.detectChanges();\n \t\texpect(root.querySelectorAll('.remaining-history > li').length).toBeGreaterThan(0);\n \t\texpect(details.textContent).toContain('Ces dates ont réellement été examinées');\n-\t\texpect(details.textContent).toContain('Maximum de jours travaillés entre congés');\n+\t\texpect(details.textContent).toContain(presets[3].name);\n \t\texpect(details.textContent).toContain('Évalué et rejeté');\n \t\texpect(JSON.stringify(userInputService.planningOutcomeSignal())).toBe(outcome);\n \t\texpect(JSON.stringify(userInputService.planningTraceSignal())).toBe(trace);\n@@ -527,7 +530,7 @@ describe('UserInput', () => {\n \t\t);\n \t\tawait rule.uncheck();\n \t\tawait expect.poll(() => localStorage.getItem('vacationRules')).not.toBeNull();\n-\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!)[0].enabled).toBe(false);\n+\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!).rules[0].enabled).toBe(false);\n \t\tfixture.nativeElement.querySelector('.calculate-button').click();\n \t\tawait fixture.whenStable();\n \n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/components/user-input/user-input.spec.ts", "project_id": 35, "relative_order": 16, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -102,7 +102,8 @@ export class UserInput {\n \t\tconst copy = this.tr().userInput;\n \t\treturn plan.remainingBalances.map((balance) => {\n \t\t\tconst code =\n-\t\t\t\tincomplete && ['preserved', 'not-established'].includes(balance.reason.code)\n+\t\t\t\tincomplete &&\n+\t\t\t\t['preserved', 'active-priorities', 'not-established'].includes(balance.reason.code)\n \t\t\t\t\t? 'calculation-incomplete'\n \t\t\t\t\t: balance.reason.code;\n \t\t\treturn {\n@@ -214,6 +215,7 @@ export class UserInput {\n \n \tprivate criterionLabel(name: string): string | undefined {\n \t\tconst id = name.replace(/^protected:/, '');\n+\t\tif (id.startsWith('optimization:')) return this.ruleName(id.slice('optimization:'.length));\n \t\tconst key =\n \t\t\tid === 'obligations'\n \t\t\t\t? 'obligation-validity'\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/components/user-input/user-input.ts", "project_id": 35, "relative_order": 17, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,225 @@\n+import { execFile } from 'node:child_process';\n+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';\n+import { tmpdir } from 'node:os';\n+import { join, resolve } from 'node:path';\n+import { promisify } from 'node:util';\n+import { Worker as NodeWorker } from 'node:worker_threads';\n+import { vi } from 'vitest';\n+import { createPlanningCalculation } from './leave-planner.service';\n+import type { OptimizationPlanningRule } from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+\n+describe('calendar objectives in the real worker', () => {\n+\tlet directory: string;\n+\tlet bundle: string;\n+\tconst threads = new Set();\n+\n+\tbeforeAll(async () => {\n+\t\tdirectory = mkdtempSync(join(tmpdir(), 'vac-calendar-worker-'));\n+\t\tbundle = join(directory, 'worker.mjs');\n+\t\tconst entry = join(directory, 'entry.ts');\n+\t\twriteFileSync(\n+\t\t\tentry,\n+\t\t\t`import { parentPort } from 'node:worker_threads';\n+globalThis.self = { postMessage: (message) => parentPort.postMessage(message) };\n+await import(${JSON.stringify(resolve('src/app/services/leave-planner.worker.ts'))});\n+parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n+`,\n+\t\t);\n+\t\tawait promisify(execFile)('bun', ['build', entry, '--target=node', '--outfile', bundle]);\n+\t});\n+\n+\tbeforeEach(() => {\n+\t\tvi.setSystemTime(new Date('2024-04-01T12:00:00Z'));\n+\t\tclass BrowserWorker {\n+\t\t\tonmessage: ((event: MessageEvent) => void) | null = null;\n+\t\t\tonerror: (() => void) | null = null;\n+\t\t\tprivate readonly thread = new NodeWorker(bundle);\n+\t\t\tconstructor() {\n+\t\t\t\tthreads.add(this.thread);\n+\t\t\t\tthis.thread.on('message', (data) => this.onmessage?.({ data } as MessageEvent));\n+\t\t\t\tthis.thread.on('error', () => this.onerror?.());\n+\t\t\t}\n+\t\t\tpostMessage(message: unknown) {\n+\t\t\t\tthis.thread.postMessage(message);\n+\t\t\t}\n+\t\t\tterminate() {\n+\t\t\t\tvoid this.thread.terminate();\n+\t\t\t}\n+\t\t}\n+\t\tvi.stubGlobal('Worker', BrowserWorker);\n+\t});\n+\n+\tafterEach(async () => {\n+\t\tawait Promise.all([...threads].map((thread) => thread.terminate()));\n+\t\tthreads.clear();\n+\t\tvi.useRealTimers();\n+\t\tvi.unstubAllGlobals();\n+\t});\n+\tafterAll(() => rmSync(directory, { recursive: true, force: true }));\n+\n+\tit.each([false, true])(\n+\t\t'retains the submitted configuration, plan and artifact order (gain first: %s)',\n+\t\tasync (gainFirst) => {\n+\t\t\tconst holiday: OptimizationPlanningRule = {\n+\t\t\t\tid: 'holiday',\n+\t\t\t\ttype: 'optimization' as const,\n+\t\t\t\tname: 'Captured holiday rule',\n+\t\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.holidayWeekValue),\n+\t\t\t};\n+\t\t\tconst gain: OptimizationPlanningRule = {\n+\t\t\t\tid: 'gain',\n+\t\t\t\ttype: 'optimization' as const,\n+\t\t\t\tname: 'Captured gain rule',\n+\t\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.nonWorkingDayGain),\n+\t\t\t};\n+\t\t\tconst rules = gainFirst ? [gain, holiday] : [holiday, gain];\n+\t\t\tconst calculation = createPlanningCalculation({\n+\t\t\t\thorizon: { start: '2024-04-29', end: '2024-05-18' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 3,\n+\t\t\t\t\t\tavailableFrom: '2024-04-29',\n+\t\t\t\t\t\texpiryDate: '2025-01-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules,\n+\t\t\t});\n+\t\t\tholiday.configuration = {\n+\t\t\t\t...holiday.configuration,\n+\t\t\t\tconditions: [],\n+\t\t\t\tdirection: 'minimize',\n+\t\t\t};\n+\t\t\tconst plan = await calculation.outcome;\n+\t\t\tif (plan.kind !== 'Plan')\n+\t\t\t\tthrow new Error(`Expected a worker plan, received ${plan.kind}`);\n+\t\t\texpect(plan.metrics).toMatchObject(\n+\t\t\t\tgainFirst\n+\t\t\t\t\t? { holidayWeekValue: 0, nonWorkingDayGain: 9 }\n+\t\t\t\t\t: { holidayWeekValue: 5, nonWorkingDayGain: 6 },\n+\t\t\t);\n+\t\t\texpect(calculation.snapshot.rules.find((rule) => rule.id === 'holiday')).toMatchObject({\n+\t\t\t\tname: 'Captured holiday rule',\n+\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t\t});\n+\t\t\tconst first = `optimization:${rules[0].id}`;\n+\t\t\tconst explanation = await calculation.explanation;\n+\t\t\tif (explanation?.kind !== 'PlanExplanation')\n+\t\t\t\tthrow new Error('Expected a worker explanation');\n+\t\t\texpect(explanation.placements[0].firstDecisiveObjective).toBe(first);\n+\t\t\texpect((await calculation.trace)?.phases.map((phase) => phase.name)).toEqual([\n+\t\t\t\t'validation',\n+\t\t\t\t'obligations',\n+\t\t\t\tfirst,\n+\t\t\t\t`optimization:${rules[1].id}`,\n+\t\t\t\t'expiry',\n+\t\t\t\t'dates',\n+\t\t\t]);\n+\t\t\tconst comparison = await calculation.analyzeCounterfactual(plan.placements[0]);\n+\t\t\tif (comparison.kind !== 'Counterfactual')\n+\t\t\t\tthrow new Error('Expected a worker comparison');\n+\t\t\texpect(\n+\t\t\t\tcomparison.results.find((result) => result.date === plan.placements[0].date)\n+\t\t\t\t\t?.comparison?.firstDecisiveObjective,\n+\t\t\t).toBe(first);\n+\t\t},\n+\t);\n+\n+\tit.each([false, true])(\n+\t\t'lets economy block or permit the complete holiday bundle in a real worker (economy first: %s)',\n+\t\tasync (economyFirst) => {\n+\t\t\tconst economy: OptimizationPlanningRule = {\n+\t\t\t\tid: 'economy',\n+\t\t\t\tname: 'Captured supporting economy',\n+\t\t\t\ttype: 'optimization',\n+\t\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.supportingPlacements),\n+\t\t\t};\n+\t\t\tconst holiday: OptimizationPlanningRule = {\n+\t\t\t\tid: 'holiday',\n+\t\t\t\ttype: 'optimization',\n+\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t\t};\n+\t\t\tconst rules = economyFirst ? [economy, holiday] : [holiday, economy];\n+\t\t\tconst calculation = createPlanningCalculation({\n+\t\t\t\thorizon: { start: '2026-11-09', end: '2026-11-14' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 2,\n+\t\t\t\t\t\tavailableFrom: '2026-11-09',\n+\t\t\t\t\t\texpiryDate: '2027-01-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\tdeclaredDays: ['2026-11-09', '2026-11-10'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules,\n+\t\t\t});\n+\t\t\teconomy.name = 'Edited later';\n+\t\t\teconomy.configuration.conditions = [];\n+\t\t\tconst outcome = await calculation.outcome;\n+\t\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a worker plan');\n+\t\t\texpect(outcome.metrics).toMatchObject(\n+\t\t\t\teconomyFirst\n+\t\t\t\t\t? { holidayWeekValue: 0, supportingPlacements: 0 }\n+\t\t\t\t\t: { holidayWeekValue: 3, supportingPlacements: 2 },\n+\t\t\t);\n+\t\t\texpect(calculation.snapshot.rules.find(({ id }) => id === 'economy')).toMatchObject({\n+\t\t\t\tname: 'Captured supporting economy',\n+\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t});\n+\t\t\tconst trace = await calculation.trace;\n+\t\t\texpect(trace?.phases.map(({ name }) => name)).toEqual([\n+\t\t\t\t'validation',\n+\t\t\t\t'obligations',\n+\t\t\t\t`optimization:${rules[0].id}`,\n+\t\t\t\t`optimization:${rules[1].id}`,\n+\t\t\t\t'expiry',\n+\t\t\t\t'dates',\n+\t\t\t]);\n+\t\t\tconst candidates = trace?.phases.flatMap(({ decisions }) =>\n+\t\t\t\tdecisions.flatMap(({ candidates }) => candidates),\n+\t\t\t);\n+\t\t\texpect(candidates).toContainEqual(\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tstatus: economyFirst ? 'evaluated-rejected' : 'chosen',\n+\t\t\t\t\tdates: ['2026-11-12', '2026-11-13'],\n+\t\t\t\t\tcomparison: expect.objectContaining({\n+\t\t\t\t\t\tfirstDecisiveObjective: economyFirst\n+\t\t\t\t\t\t\t? 'optimization:economy'\n+\t\t\t\t\t\t\t: 'optimization:holiday',\n+\t\t\t\t\t}),\n+\t\t\t\t}),\n+\t\t\t);\n+\t\t\tconst explanation = await calculation.explanation;\n+\t\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\t\tif (economyFirst) {\n+\t\t\t\texpect(outcome.placements).toEqual([]);\n+\t\t\t\texpect(outcome.remainingBalances[0]).toMatchObject({\n+\t\t\t\t\tid: 'cp',\n+\t\t\t\t\tquantity: 2,\n+\t\t\t\t\tclassification: 'deferred',\n+\t\t\t\t});\n+\t\t\t\texpect(explanation.placements).toEqual([]);\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\texpect(outcome.remainingBalances).toEqual([]);\n+\t\t\texpect(explanation.placements.every(({ supporting }) => supporting)).toBe(true);\n+\t\t\texpect(explanation.placements[0].firstDecisiveObjective).toBe('optimization:holiday');\n+\t\t\texpect(explanation.placements[0].objectiveVector.objectives).toContainEqual(\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tid: 'optimization:economy',\n+\t\t\t\t\tvalue: 2,\n+\t\t\t\t\tlabel: 'Captured supporting economy',\n+\t\t\t\t}),\n+\t\t\t);\n+\t\t\tconst analysis = await calculation.analyzeCounterfactual(outcome.placements[0]);\n+\t\t\tif (analysis.kind !== 'Counterfactual') throw new Error('Expected a counterfactual');\n+\t\t\texpect(\n+\t\t\t\tanalysis.results.find(({ date }) => date === outcome.placements[0].date)?.comparison\n+\t\t\t\t\t?.after.objectives,\n+\t\t\t).toContainEqual(expect.objectContaining({ id: 'optimization:economy', value: 2 }));\n+\t\t},\n+\t);\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/services/calendar-objectives.worker.spec.ts", "project_id": 35, "relative_order": 18, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,466 @@\n+import { describe, expect, it } from 'vitest';\n+import {\n+\tanalyzeCounterfactualInternal,\n+\tcalculatePlanningInternal,\n+\ttype OptimizationPlanningRule,\n+\ttype PlanningArtifacts,\n+\ttype PlanningRequest,\n+} from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS, type OptimizationConfiguration } from './planning-objectives';\n+\n+const holiday: OptimizationPlanningRule = {\n+\tid: 'holiday',\n+\tname: 'Complete public-holiday weeks',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+};\n+const gain: OptimizationPlanningRule = {\n+\tid: 'gain',\n+\tname: 'Enjoy weekends and public holidays',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.nonWorkingDayGain,\n+};\n+const samedi: PlanningRequest['rules'][number] = {\n+\tid: 'samedi',\n+\ttype: 'if_then',\n+\tdayOfWeek: 6,\n+\tplaceDays: 2,\n+\tplaceType: 'cp',\n+\tplacement: 'auto',\n+\trewardDays: 1,\n+\trewardType: 'other',\n+};\n+const concurrent: PlanningRequest = {\n+\thorizon: { start: '2024-04-29', end: '2024-05-18' },\n+\tbalances: [\n+\t\t{\n+\t\t\tid: 'cp',\n+\t\t\ttype: 'cp',\n+\t\t\tquantity: 3,\n+\t\t\tavailableFrom: '2024-04-29',\n+\t\t\texpiryDate: '2025-01-01',\n+\t\t},\n+\t],\n+\trules: [],\n+};\n+\n+function calculate(request: PlanningRequest, calculationDate = '2024-04-01') {\n+\tlet artifacts: PlanningArtifacts = {};\n+\tconst plan = calculatePlanningInternal(\n+\t\t{ ...request, calculationDate },\n+\t\tundefined,\n+\t\t(value) => (artifacts = value),\n+\t);\n+\tif (plan.kind !== 'Plan') throw new Error(`Expected a plan, received ${plan.kind}`);\n+\treturn { plan, artifacts };\n+}\n+\n+describe('composed calendar objectives', () => {\n+\tit('follows either displayed order when a completed holiday week competes with greater natural gain', () => {\n+\t\tconst holidayFirst = calculate({ ...concurrent, rules: [holiday, gain] }).plan;\n+\t\tconst gainFirst = calculate({ ...concurrent, rules: [gain, holiday] }).plan;\n+\t\texpect(holidayFirst.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t'2024-05-06',\n+\t\t\t'2024-05-07',\n+\t\t\t'2024-05-10',\n+\t\t]);\n+\t\texpect(holidayFirst.metrics).toMatchObject({ holidayWeekValue: 5, nonWorkingDayGain: 6 });\n+\t\texpect(gainFirst.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t'2024-04-29',\n+\t\t\t'2024-05-10',\n+\t\t\t'2024-05-17',\n+\t\t]);\n+\t\texpect(gainFirst.metrics).toMatchObject({ holidayWeekValue: 0, nonWorkingDayGain: 9 });\n+\t});\n+\n+\tit('regroups existing placements as a complete week without leaving higher-priority at-risk leave unused', () => {\n+\t\tconst loss: OptimizationPlanningRule = {\n+\t\t\tid: 'loss',\n+\t\t\ttype: 'optimization',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t};\n+\t\tconst { plan } = calculate({\n+\t\t\t...concurrent,\n+\t\t\tbalances: [{ ...concurrent.balances[0], expiryDate: '2024-05-17' }],\n+\t\t\trules: [loss, holiday, gain],\n+\t\t});\n+\t\texpect(plan.metrics).toMatchObject({\n+\t\t\tunplacedAtRisk: 0,\n+\t\t\tholidayWeekValue: 5,\n+\t\t\tnonWorkingDayGain: 6,\n+\t\t});\n+\t\texpect(plan.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t'2024-05-06',\n+\t\t\t'2024-05-07',\n+\t\t\t'2024-05-10',\n+\t\t]);\n+\t\texpect(plan.placements.every((placement) => !placement.supporting)).toBe(true);\n+\t});\n+\n+\tit('preserves an earlier preference that minimizes supporting placements', () => {\n+\t\tconst { plan } = calculate({\n+\t\t\t...concurrent,\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'economy',\n+\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t\t},\n+\t\t\t\tholiday,\n+\t\t\t],\n+\t\t});\n+\t\texpect(plan.placements).toEqual([]);\n+\t});\n+\n+\tit('uses edited holiday conditions and aggregation without dispatching by a preset identity', () => {\n+\t\tconst counted: OptimizationPlanningRule = {\n+\t\t\t...holiday,\n+\t\t\tid: 'my-complete-weeks',\n+\t\t\tconfiguration: { ...holiday.configuration, aggregation: 'count' },\n+\t\t};\n+\t\tconst { plan, artifacts } = calculate({ ...concurrent, rules: [counted] });\n+\t\texpect(plan.metrics.holidayWeekValue).toBe(5);\n+\t\tif (artifacts.explanation?.kind !== 'PlanExplanation')\n+\t\t\tthrow new Error('Expected an explanation');\n+\t\texpect(artifacts.explanation.placements[0].objectiveVector.objectives[1]).toMatchObject({\n+\t\t\tid: 'optimization:my-complete-weeks',\n+\t\t\tvalue: 1,\n+\t\t});\n+\t\tconst allWeeks = calculate({\n+\t\t\t...concurrent,\n+\t\t\trules: [{ ...counted, configuration: { ...counted.configuration, conditions: [] } }],\n+\t\t}).plan;\n+\t\texpect(allWeeks.placements).toEqual([]);\n+\t});\n+\n+\tit('attributes a coordinated holiday addition and its explanation to the active rule', () => {\n+\t\tconst { plan, artifacts } = calculate(\n+\t\t\t{\n+\t\t\t\thorizon: { start: '2026-11-09', end: '2026-11-14' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'deferred-cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 2,\n+\t\t\t\t\t\tavailableFrom: '2026-11-01',\n+\t\t\t\t\t\texpiryDate: '2027-01-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\tdeclaredDays: ['2026-11-09', '2026-11-10'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [holiday],\n+\t\t\t},\n+\t\t\t'2026-11-01',\n+\t\t);\n+\t\texpect(plan.placements).toEqual([\n+\t\t\texpect.objectContaining({ date: '2026-11-12', ruleIds: ['holiday'], supporting: true }),\n+\t\t\texpect.objectContaining({ date: '2026-11-13', ruleIds: ['holiday'], supporting: true }),\n+\t\t]);\n+\t\tif (artifacts.explanation?.kind !== 'PlanExplanation')\n+\t\t\tthrow new Error('Expected an explanation');\n+\t\tfor (const placement of artifacts.explanation.placements) {\n+\t\t\texpect(placement.firstDecisiveObjective).toBe('optimization:holiday');\n+\t\t\texpect(placement.contributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({ kind: 'rule', ruleId: 'holiday' }),\n+\t\t\t);\n+\t\t}\n+\t});\n+\n+\tit.each([\n+\t\t{ ...gain.configuration, aggregation: 'maximum' },\n+\t\t{ ...gain.configuration, aggregation: 'count', direction: 'minimize' },\n+\t])(\n+\t\t'bridges fixed periods for the personal configuration $aggregation/$direction',\n+\t\t(configuration) => {\n+\t\t\tconst { plan, artifacts } = calculate({\n+\t\t\t\thorizon: { start: '2024-01-05', end: '2024-01-13' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'rtt',\n+\t\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\t\tquantity: 4,\n+\t\t\t\t\t\tavailableFrom: '2024-01-05',\n+\t\t\t\t\t\texpiryDate: '2025-01-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\tdeclaredDays: ['2024-01-05', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\t...gain,\n+\t\t\t\t\t\tid: 'personal-maximum',\n+\t\t\t\t\t\tconfiguration,\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t});\n+\t\t\texpect(plan.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t\t'2024-01-08',\n+\t\t\t\t'2024-01-09',\n+\t\t\t\t'2024-01-10',\n+\t\t\t\t'2024-01-11',\n+\t\t\t]);\n+\t\t\texpect(plan.timeOffPeriods).toHaveLength(1);\n+\t\t\texpect(plan.timeOffPeriods[0].nonWorkingDates).toEqual([\n+\t\t\t\t'2024-01-06',\n+\t\t\t\t'2024-01-07',\n+\t\t\t\t'2024-01-13',\n+\t\t\t\t'2024-01-14',\n+\t\t\t]);\n+\t\t\texpect(plan.metrics.nonWorkingDayGain).toBe(4);\n+\t\t\texpect(\n+\t\t\t\tplan.placements.every(({ ruleIds }) => ruleIds.includes('personal-maximum')),\n+\t\t\t).toBe(true);\n+\t\t\tif (artifacts.explanation?.kind !== 'PlanExplanation')\n+\t\t\t\tthrow new Error('Expected an explanation');\n+\t\t\tfor (const placement of artifacts.explanation.placements)\n+\t\t\t\texpect(placement.contributions).toContainEqual(\n+\t\t\t\t\texpect.objectContaining({ kind: 'rule', ruleId: 'personal-maximum' }),\n+\t\t\t\t);\n+\t\t},\n+\t);\n+\n+\tit.each([false, true])(\n+\t\t'finishes a rejected bridge with an irrelevant typed rule: %s',\n+\t\t(withSamedi) => {\n+\t\t\tconst { plan } = calculate({\n+\t\t\t\thorizon: { start: '2024-01-05', end: '2024-02-06' },\n+\t\t\t\tbalances: (['cp', 'rtt', 'other'] as const).map((type) => ({\n+\t\t\t\t\tid: type,\n+\t\t\t\t\ttype,\n+\t\t\t\t\tquantity: 20,\n+\t\t\t\t\tavailableFrom: '2024-01-05',\n+\t\t\t\t\texpiryDate: '2025-01-01',\n+\t\t\t\t})),\n+\t\t\t\tdeclaredDays: ['2024-01-05', '2024-02-05'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'economy',\n+\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t...gain,\n+\t\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t\t...gain.configuration,\n+\t\t\t\t\t\t\taggregation: 'count',\n+\t\t\t\t\t\t\tdirection: 'minimize',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t},\n+\t\t\t\t\t...(withSamedi ? [samedi] : []),\n+\t\t\t\t],\n+\t\t\t\tdeadlineMs: 2_000,\n+\t\t\t});\n+\t\t\texpect(plan.placements).toEqual([]);\n+\t\t\texpect(plan.timeOffPeriods).toHaveLength(2);\n+\t\t},\n+\t);\n+\n+\tit('does not label a period-count bridge supporting when it adds no domain calendar benefit', () => {\n+\t\tconst { plan } = calculate({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-31' },\n+\t\t\tbalances: [{ ...concurrent.balances[0], quantity: 5, availableFrom: '2024-01-02' }],\n+\t\t\tdeclaredDays: ['2024-01-05', '2024-01-15'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\t...gain,\n+\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t...gain.configuration,\n+\t\t\t\t\t\taggregation: 'count',\n+\t\t\t\t\t\tdirection: 'minimize',\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(plan.timeOffPeriods).toHaveLength(1);\n+\t\texpect(plan.placements).toHaveLength(5);\n+\t\texpect(plan.placements.every((placement) => !placement.supporting)).toBe(true);\n+\t\texpect(plan.metrics.nonWorkingDayGain).toBe(4);\n+\t});\n+\n+\tit('can place the holiday preference before or after Samedi Malin', () => {\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2021-11-01', end: '2021-12-29' },\n+\t\t\tbalances: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'cp',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 4,\n+\t\t\t\t\tavailableFrom: '2021-11-01',\n+\t\t\t\t\texpiryDate: '2022-01-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t\trules: [],\n+\t\t};\n+\t\tconst first = calculate({ ...request, rules: [holiday, samedi] }, '2021-10-01').plan;\n+\t\tconst second = calculate({ ...request, rules: [samedi, holiday] }, '2021-10-01').plan;\n+\t\texpect(first.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t'2021-11-08',\n+\t\t\t'2021-11-09',\n+\t\t\t'2021-11-10',\n+\t\t\t'2021-11-12',\n+\t\t]);\n+\t\texpect(first.metrics.holidayWeekValue).toBe(2);\n+\t\texpect(first.preferences[0].satisfied).toBe(0);\n+\t\texpect(second.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t'2021-12-23',\n+\t\t\t'2021-12-24',\n+\t\t]);\n+\t\texpect(second.metrics.holidayWeekValue).toBe(0);\n+\t\texpect(second.preferences[0].satisfied).toBe(1);\n+\t\texpect(second.remainingBalances.find((balance) => balance.earned)).toMatchObject({\n+\t\t\tid: 'earned:samedi:2021-12-25',\n+\t\t\tquantity: 1,\n+\t\t});\n+\t});\n+\n+\tit.each(['obligation', 'preference'] as const)(\n+\t\t'preserves a higher %s when completing a week would take its last balance',\n+\t\t(force) => {\n+\t\t\tconst { plan } = calculate({\n+\t\t\t\t...concurrent,\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'monday',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce,\n+\t\t\t\t\t\tstartDate: '2024-04-29',\n+\t\t\t\t\t\tendDate: '2024-04-29',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t\tholiday,\n+\t\t\t\t],\n+\t\t\t});\n+\t\t\texpect(plan.placements).toMatchObject([{ date: '2024-04-29', ruleIds: ['monday'] }]);\n+\t\t\texpect(plan.metrics.holidayWeekValue).toBe(0);\n+\t\t},\n+\t);\n+\n+\tit('adds no residual loss-prevention or calendar placements when their rules are disabled', () => {\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-04-29', end: '2024-05-04' },\n+\t\t\tbalances: [{ ...concurrent.balances[0], quantity: 5, expiryDate: '2024-05-03' }],\n+\t\t\trules: [holiday],\n+\t\t};\n+\t\tconst absent = calculate(request).plan;\n+\t\tconst disabled = calculate({\n+\t\t\t...request,\n+\t\t\trules: [\n+\t\t\t\tholiday,\n+\t\t\t\t{\n+\t\t\t\t\tid: 'loss',\n+\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\tenabled: false,\n+\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t\t\t},\n+\t\t\t\t{ ...gain, enabled: false },\n+\t\t\t],\n+\t\t}).plan;\n+\t\texpect(disabled).toEqual(absent);\n+\t\texpect(absent.metrics.unplacedAtRisk).toBe(1);\n+\t\texpect(absent.metrics.holidayWeekValue).toBe(3);\n+\t\texpect(absent.placements).toHaveLength(4);\n+\t\texpect(\n+\t\t\tcalculate({ ...request, rules: [{ ...holiday, enabled: false }] }).plan.placements,\n+\t\t).toEqual([]);\n+\t});\n+\n+\tit.each([\n+\t\t{ start: '2024-05-06', end: '2024-05-11' },\n+\t\t{ start: '2024-05-10', end: '2024-05-11' },\n+\t])(\n+\t\t'uses declarations outside the horizon to complete a genuine holiday week ($start)',\n+\t\t(horizon) => {\n+\t\t\tconst { plan } = calculate({\n+\t\t\t\thorizon,\n+\t\t\t\tbalances: [{ ...concurrent.balances[0], quantity: 1, availableFrom: '2024-05-06' }],\n+\t\t\t\tdeclaredDays: ['2024-05-06', '2024-05-07'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [holiday],\n+\t\t\t});\n+\t\t\texpect(plan.placements).toMatchObject([{ date: '2024-05-10', supporting: true }]);\n+\t\t\texpect(plan.metrics).toMatchObject({ holidayWeekValue: 5, nonWorkingDayGain: 6 });\n+\t\t},\n+\t);\n+\n+\tit('cannot fill missing weekdays outside the horizon or with unavailable balances', () => {\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-05-10', end: '2024-05-11' },\n+\t\t\tbalances: [{ ...concurrent.balances[0], quantity: 1 }],\n+\t\t\trules: [holiday],\n+\t\t};\n+\t\texpect(calculate(request).plan.placements).toEqual([]);\n+\t\tconst unavailable = calculate({\n+\t\t\t...request,\n+\t\t\tbalances: [{ ...request.balances[0], availableFrom: '2024-05-11' }],\n+\t\t\tdeclaredDays: ['2024-05-06', '2024-05-07'].map((date) => ({ date, type: 'other' })),\n+\t\t}).plan;\n+\t\texpect(unavailable.placements).toEqual([]);\n+\t\texpect(unavailable.metrics.holidayWeekValue).toBe(0);\n+\t});\n+\n+\tit('measures only distinct natural dates and leaves ordinary declared weeks ordinary', () => {\n+\t\tconst christmas = calculate({\n+\t\t\thorizon: { start: '2021-12-24', end: '2021-12-25' },\n+\t\t\tbalances: [],\n+\t\t\tdeclaredDays: [{ date: '2021-12-24', type: 'other' }],\n+\t\t\trules: [holiday, gain],\n+\t\t}).plan;\n+\t\texpect(christmas.metrics).toMatchObject({ holidayWeekValue: 0, nonWorkingDayGain: 2 });\n+\t\texpect(christmas.timeOffPeriods[0].nonWorkingDates).toEqual(['2021-12-25', '2021-12-26']);\n+\t\tconst ordinary = calculate({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tbalances: [],\n+\t\t\tdeclaredDays: ['08', '09', '10', '11', '12'].map((day) => ({\n+\t\t\t\tdate: `2024-01-${day}`,\n+\t\t\t\ttype: 'other',\n+\t\t\t})),\n+\t\t\trules: [holiday],\n+\t\t}).plan;\n+\t\texpect(ordinary.metrics.holidayWeekValue).toBe(0);\n+\t});\n+\n+\tit('uses the same first calendar objective in the plan explanation, trace and date comparison', () => {\n+\t\tfor (const rules of [\n+\t\t\t[holiday, gain],\n+\t\t\t[gain, holiday],\n+\t\t]) {\n+\t\t\tconst request = { ...concurrent, rules };\n+\t\t\tconst { plan, artifacts } = calculate(request);\n+\t\t\tconst explanation = artifacts.explanation;\n+\t\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\t\tconst first = `optimization:${rules[0].id}`;\n+\t\t\texpect(explanation.placements[0].firstDecisiveObjective).toBe(first);\n+\t\t\texpect(\n+\t\t\t\texplanation.placements[0].objectiveVector.objectives.map(\n+\t\t\t\t\t(objective) => objective.id,\n+\t\t\t\t),\n+\t\t\t).toEqual([\n+\t\t\t\t'obligation-validity',\n+\t\t\t\tfirst,\n+\t\t\t\t`optimization:${rules[1].id}`,\n+\t\t\t\t'balance-expiry',\n+\t\t\t\t'placement-date',\n+\t\t\t]);\n+\t\t\tconst comparisons = artifacts.trace?.phases\n+\t\t\t\t.flatMap((phase) => phase.decisions)\n+\t\t\t\t.flatMap((decision) => decision.candidates)\n+\t\t\t\t.filter((candidate) => candidate.status === 'chosen' && candidate.comparison);\n+\t\t\texpect(\n+\t\t\t\tcomparisons?.some(\n+\t\t\t\t\t(candidate) => candidate.comparison?.firstDecisiveObjective === first,\n+\t\t\t\t),\n+\t\t\t).toBe(true);\n+\t\t\tconst placement = rules[0].id === 'holiday' ? plan.placements[1] : plan.placements[0];\n+\t\t\tconst alternative = rules[0].id === 'holiday' ? '2024-04-30' : '2024-05-02';\n+\t\t\tconst comparison = analyzeCounterfactualInternal(\n+\t\t\t\trequest,\n+\t\t\t\tplan,\n+\t\t\t\tplacement,\n+\t\t\t\tartifacts.finalState,\n+\t\t\t\t{ removeDate: placement.date, compareOriginalState: true },\n+\t\t\t);\n+\t\t\texpect(\n+\t\t\t\tcomparison.results.find((result) => result.date === alternative)?.comparison\n+\t\t\t\t\t?.firstDecisiveObjective,\n+\t\t\t).toBe(first);\n+\t\t}\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/services/leave-planner-calendar-objectives.spec.ts", "project_id": 35, "relative_order": 19, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,3 +1,4 @@\n+import { createOptimizationPresetRules } from './rule-service';\n import { vi } from 'vitest';\n import {\n \tcreatePlanningCalculation,\n@@ -14,6 +15,8 @@ const request = {\n beforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n afterEach(() => vi.useRealTimers());\n \n+const presets = createOptimizationPresetRules();\n+\n describe('user cancellation', () => {\n \tconst workers: CancellableWorker[] = [];\n \tconst currentWorker = () => workers[workers.length - 1];\n@@ -51,7 +54,7 @@ describe('user cancellation', () => {\n \t\tconst submitted = {\n \t\t\thorizon: { start: '2024-01-02', end: '2024-01-09' },\n \t\t\tbalances: [],\n-\t\t\trules: [],\n+\t\t\trules: [presets[2]],\n \t\t\tdeclaredDays: [{ date: '2024-01-05', type: 'other' as const }],\n \t\t};\n \t\tlet interrupted = false;\n@@ -60,7 +63,7 @@ describe('user cancellation', () => {\n \t\t\t{\n \t\t\t\t...submitted,\n \t\t\t\tprogress: (stage: string) => {\n-\t\t\t\t\tif (stage === 'non-working-day-gain') interrupted = true;\n+\t\t\t\t\tif (stage === 'optimization:default-non-working-day-gain') interrupted = true;\n \t\t\t\t},\n \t\t\t},\n \t\t\tundefined,\n@@ -115,14 +118,17 @@ describe('user cancellation', () => {\n \t\t\t\t{ date: '2024-01-11', type: 'rtt' as const },\n \t\t\t],\n \t\t\trules: [\n-\t\t\t\t{ id: 'exact-cp', force: 'obligation', placeDays: 2, placeType: 'cp' },\n-\t\t\t\t{ id: 'preferred-rtt', force: 'preference', placeDays: 1, placeType: 'rtt' },\n-\t\t\t].map((rule) => ({\n-\t\t\t\t...rule,\n-\t\t\t\ttype: 'time_window',\n-\t\t\t\tstartDate: '2024-01-08',\n-\t\t\t\tendDate: '2024-01-12',\n-\t\t\t})),\n+\t\t\t\tpresets[1],\n+\t\t\t\t...[\n+\t\t\t\t\t{ id: 'exact-cp', force: 'obligation', placeDays: 2, placeType: 'cp' },\n+\t\t\t\t\t{ id: 'preferred-rtt', force: 'preference', placeDays: 1, placeType: 'rtt' },\n+\t\t\t\t].map((rule) => ({\n+\t\t\t\t\t...rule,\n+\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\tstartDate: '2024-01-08',\n+\t\t\t\t\tendDate: '2024-01-12',\n+\t\t\t\t})),\n+\t\t\t],\n \t\t};\n \t\tlet interrupted = false;\n \t\tlet artifacts: import('./leave-planner.core').PlanningArtifacts = {};\n@@ -130,7 +136,7 @@ describe('user cancellation', () => {\n \t\t\t{\n \t\t\t\t...submitted,\n \t\t\t\tprogress: (stage: string) => {\n-\t\t\t\t\tif (stage === 'holiday-week-value') interrupted = true;\n+\t\t\t\t\tif (stage === 'optimization:default-holiday-week-value') interrupted = true;\n \t\t\t\t},\n \t\t\t},\n \t\t\tundefined,\n@@ -201,18 +207,22 @@ describe('user cancellation', () => {\n \t\t\t\thorizon: request.horizon,\n \t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-12-31' }],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'january',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tstartDate: '2024-01-01',\n-\t\t\t\t\t\tendDate: '2024-01-31',\n-\t\t\t\t\t\tplaceDays: 2,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'january',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tstartDate: '2024-01-01',\n+\t\t\t\t\t\t\tendDate: '2024-01-31',\n+\t\t\t\t\t\t\tplaceDays: 2,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t\tprogress: (stage: string) => {\n-\t\t\t\t\tif (stage === 'longest-work-sequence') cancelled = true;\n+\t\t\t\t\tif (stage === 'optimization:default-longest-work-sequence') cancelled = true;\n \t\t\t\t},\n \t\t\t},\n \t\t\tundefined,\n@@ -287,7 +297,7 @@ describe('user cancellation', () => {\n \t\tconst submitted = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n \t\t\tbalances: [{ id: 'cp', type: 'cp' as const, quantity: 2, expiryDate: '2024-01-31' }],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t};\n \t\tconst cancelled = await core.calculatePlanningAsyncInternal(\n \t\t\t{\n@@ -295,7 +305,7 @@ describe('user cancellation', () => {\n \t\t\t\ttraceProgress: (_: number, update: PlanningTraceUpdate) =>\n \t\t\t\t\tupdates.push(structuredClone(update)),\n \t\t\t\tprogress: (stage: string) => {\n-\t\t\t\t\tif (stage === 'non-working-day-gain') interrupted = true;\n+\t\t\t\t\tif (stage === 'optimization:default-non-working-day-gain') interrupted = true;\n \t\t\t\t},\n \t\t\t},\n \t\t\tundefined,\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner-cancellation.spec.ts", "project_id": 35, "relative_order": 20, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,3 +1,4 @@\n+import { createOptimizationPresetRules } from './rule-service';\n import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';\n import { createPlanningCalculation, applyReplayDeltas } from './leave-planner.service';\n \n@@ -15,6 +16,8 @@ afterEach(() => vi.unstubAllGlobals());\n beforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n afterEach(() => vi.useRealTimers());\n \n+const presets = createOptimizationPresetRules();\n+\n describe('planner explanation and trace seam', () => {\n \tit('replays a reported occurrence without borrowing its future balance from the final plan', async () => {\n \t\tvi.setSystemTime(new Date('2024-05-03T12:00:00Z'));\n@@ -180,7 +183,7 @@ describe('planner explanation and trace seam', () => {\n \t\t},\n \t);\n \n-\tit('removes an entitlement from the original replay when a real quality move shortens its generator into today', async () => {\n+\tit('replays an already-reported entitlement without inventing a transient earned balance under explicit priorities', async () => {\n \t\tvi.setSystemTime(new Date('2024-05-06T12:00:00Z'));\n \t\tconst core = await import('./leave-planner.core');\n \t\tlet artifacts: import('./leave-planner.core').PlanningArtifacts = {};\n@@ -201,17 +204,21 @@ describe('planner explanation and trace seam', () => {\n \t\t\t\t\t{ date: '2024-05-03', type: 'cp' },\n \t\t\t\t],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'producer',\n-\t\t\t\t\t\ttype: 'if_then',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tdayOfWeek: 3,\n-\t\t\t\t\t\tplaceDays: 2,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t\tplacement: 'after',\n-\t\t\t\t\t\trewardDays: 1,\n-\t\t\t\t\t\trewardType: 'other',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\t\tplaceDays: 2,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\t\trewardType: 'other',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t},\n \t\t\tundefined,\n@@ -226,11 +233,16 @@ describe('planner explanation and trace seam', () => {\n \t\t\tadded: false,\n \t\t});\n \t\tconst decisions = artifacts.trace.phases.flatMap(({ decisions }) => decisions);\n-\t\texpect(decisions.flatMap(({ deltas }) => deltas)).toContainEqual({\n-\t\t\tkind: 'balance-removed',\n-\t\t\tbalanceId: 'earned:producer:2024-05-01',\n-\t\t\tremainingBefore: 1,\n-\t\t});\n+\t\tconst deltas = decisions.flatMap(({ deltas }) => deltas);\n+\t\texpect(deltas).toContainEqual(\n+\t\t\texpect.objectContaining({ kind: 'balance-changed', balanceId: 'cp' }),\n+\t\t);\n+\t\texpect(deltas).not.toContainEqual(\n+\t\t\texpect.objectContaining({\n+\t\t\t\tkind: 'balance-changed',\n+\t\t\t\tbalanceId: 'earned:producer:2024-05-01',\n+\t\t\t}),\n+\t\t);\n \t\tconst initial = artifacts.trace.initialState;\n \t\tconst replay = {\n \t\t\tbalances: initial.balances.map((balance) => ({ ...balance })),\n@@ -355,14 +367,16 @@ describe('planner explanation and trace seam', () => {\n \t\tconst calculation = createPlanningCalculation({\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-08' },\n \t\t\tbalances: [balance('cp', 'cp', 2, '2024-01-07')],\n-\t\t\trules: [],\n+\t\t\trules: [presets[0]],\n \t\t});\n \t\tconst outcome = await calculation.outcome;\n \t\tconst trace = await calculation.trace;\n \t\texpect(outcome.kind).toBe('Plan');\n \t\tif (outcome.kind !== 'Plan' || !trace) return;\n \n-\t\tconst atRisk = trace.phases.find((phase) => phase.name === 'at-risk');\n+\t\tconst atRisk = trace.phases.find(\n+\t\t\t(phase) => phase.name === 'optimization:default-unplaced-at-risk',\n+\t\t);\n \t\tconst jan2 = atRisk?.decisions.find((decision) =>\n \t\t\tdecision.deltas.some(\n \t\t\t\t(delta) => delta.kind === 'placement-added' && delta.date === '2024-01-02',\n@@ -374,22 +388,17 @@ describe('planner explanation and trace seam', () => {\n \t\t\t),\n \t\t);\n \t\texpect(jan2?.candidates.some((candidate) => candidate.status === 'chosen')).toBe(true);\n-\t\texpect(jan2?.candidates[0]).toMatchObject({\n+\t\texpect(jan2?.candidates.find((candidate) => candidate.status === 'chosen')).toMatchObject({\n \t\t\ttechnicalComparison: [\n+\t\t\t\t{ name: 'obligation-validity', direction: 'minimize', before: 0, after: 0 },\n \t\t\t\t{\n-\t\t\t\t\tname: 'preference-date-conflict',\n-\t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t\tbefore: 0,\n-\t\t\t\t\tafter: 0,\n-\t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tname: 'placement-date',\n+\t\t\t\t\tname: `optimization:${presets[0].id}`,\n \t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t\tbefore: '2024-01-02',\n-\t\t\t\t\tafter: '2024-01-03',\n+\t\t\t\t\tbefore: 2,\n+\t\t\t\t\tafter: 1,\n \t\t\t\t},\n \t\t\t],\n-\t\t\tfirstDecisiveComparator: 'placement-date',\n+\t\t\tfirstDecisiveComparator: `optimization:${presets[0].id}`,\n \t\t});\n \t\texpect(jan2?.deltas).toContainEqual(\n \t\t\texpect.objectContaining({\n@@ -399,22 +408,17 @@ describe('planner explanation and trace seam', () => {\n \t\t\t}),\n \t\t);\n \t\texpect(jan3?.candidates.some((candidate) => candidate.status === 'chosen')).toBe(true);\n-\t\texpect(jan3?.candidates[0]).toMatchObject({\n+\t\texpect(jan3?.candidates.find((candidate) => candidate.status === 'chosen')).toMatchObject({\n \t\t\ttechnicalComparison: [\n+\t\t\t\t{ name: 'obligation-validity', direction: 'minimize', before: 0, after: 0 },\n \t\t\t\t{\n-\t\t\t\t\tname: 'preference-date-conflict',\n+\t\t\t\t\tname: `optimization:${presets[0].id}`,\n \t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t\tbefore: 0,\n+\t\t\t\t\tbefore: 1,\n \t\t\t\t\tafter: 0,\n \t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tname: 'placement-date',\n-\t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t\tbefore: '2024-01-03',\n-\t\t\t\t\tafter: '2024-01-04',\n-\t\t\t\t},\n \t\t\t],\n-\t\t\tfirstDecisiveComparator: 'placement-date',\n+\t\t\tfirstDecisiveComparator: `optimization:${presets[0].id}`,\n \t\t});\n \t\texpect(jan3?.deltas).toContainEqual(\n \t\t\texpect.objectContaining({\n@@ -541,29 +545,39 @@ describe('planner explanation and trace seam', () => {\n \t\t\t?.decisions.flatMap((decision) => decision.candidates)\n \t\t\t.find((item) => item.status === 'chosen' && item.date === '2024-01-03');\n \t\texpect(candidate).toMatchObject({\n-\t\t\ttechnicalComparison: [\n-\t\t\t\t{\n-\t\t\t\t\tname: 'shared-placement-type',\n-\t\t\t\t\tdirection: 'maximize',\n-\t\t\t\t\tbefore: 0,\n-\t\t\t\t\tafter: 0,\n-\t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tname: 'protected-preference-type',\n-\t\t\t\t\tdirection: 'maximize',\n-\t\t\t\t\tbefore: 1,\n-\t\t\t\t\tafter: 1,\n-\t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tname: 'balance-expiry',\n-\t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t\tbefore: '2025-01-05',\n-\t\t\t\t\tafter: '2025-01-06',\n-\t\t\t\t},\n-\t\t\t],\n-\t\t\tfirstDecisiveComparator: 'balance-expiry',\n+\t\t\tfirstDecisiveComparator: 'preference:rtt-preference',\n \t\t\tplacement: expect.objectContaining({ balanceId: 'rtt-first' }),\n \t\t});\n+\t\tconst compared = trace.phases\n+\t\t\t.find((phase) => phase.name === 'preference:any-preference')\n+\t\t\t?.decisions.flatMap((decision) => decision.candidates);\n+\t\texpect(compared).toContainEqual(\n+\t\t\texpect.objectContaining({\n+\t\t\t\tstatus: 'evaluated-rejected',\n+\t\t\t\tplacement: expect.objectContaining({ balanceId: 'rtt-second' }),\n+\t\t\t\ttechnicalComparison: expect.arrayContaining([\n+\t\t\t\t\t{\n+\t\t\t\t\t\tname: 'preference:any-preference',\n+\t\t\t\t\t\tdirection: 'maximize',\n+\t\t\t\t\t\tbefore: 1,\n+\t\t\t\t\t\tafter: 1,\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\tname: 'preference:rtt-preference',\n+\t\t\t\t\t\tdirection: 'maximize',\n+\t\t\t\t\t\tbefore: 1,\n+\t\t\t\t\t\tafter: 1,\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\tname: 'balance-expiry',\n+\t\t\t\t\t\tdirection: 'minimize',\n+\t\t\t\t\t\tbefore: '2025-01-05',\n+\t\t\t\t\t\tafter: '2025-01-06',\n+\t\t\t\t\t},\n+\t\t\t\t]),\n+\t\t\t\tfirstDecisiveComparator: 'balance-expiry',\n+\t\t\t}),\n+\t\t);\n \t});\n \n \tit('records actual IfThen leaf comparisons and selected branch identity', async () => {\n@@ -593,8 +607,8 @@ describe('planner explanation and trace seam', () => {\n \t\t\t.flatMap((decision) =>\n \t\t\t\tdecision.candidates\n \t\t\t\t\t.filter((candidate) =>\n-\t\t\t\t\t\tcandidate.technicalComparison?.some((item) =>\n-\t\t\t\t\t\t\titem.name.startsWith('complete-occurrences:if-then-preference'),\n+\t\t\t\t\t\tcandidate.technicalComparison?.some(\n+\t\t\t\t\t\t\t(item) => item.name === 'preference:if-then-preference',\n \t\t\t\t\t\t),\n \t\t\t\t\t)\n \t\t\t\t\t.map((candidate) => ({ candidate, decision })),\n@@ -605,8 +619,8 @@ describe('planner explanation and trace seam', () => {\n \t\t\t\t.find((phase) => phase.name === 'preference:if-then-preference')\n \t\t\t\t?.decisions.flatMap((decision) => decision.candidates)\n \t\t\t\t.filter((candidate) =>\n-\t\t\t\t\tcandidate.technicalComparison?.some((item) =>\n-\t\t\t\t\t\titem.name.startsWith('complete-occurrences:if-then-preference'),\n+\t\t\t\t\tcandidate.technicalComparison?.some(\n+\t\t\t\t\t\t(item) => item.name === 'preference:if-then-preference',\n \t\t\t\t\t),\n \t\t\t\t) ?? [];\n \t\texpect(preferenceLeaves.length).toBeGreaterThan(1);\n@@ -620,16 +634,14 @@ describe('planner explanation and trace seam', () => {\n \t\texpect(chosen?.candidate.technicalComparison).toEqual(\n \t\t\texpect.arrayContaining([\n \t\t\t\texpect.objectContaining({\n-\t\t\t\t\tname: 'complete-occurrences:if-then-preference',\n+\t\t\t\t\tname: 'preference:if-then-preference',\n \t\t\t\t\tdirection: 'maximize',\n \t\t\t\t}),\n-\t\t\t\texpect.objectContaining({\n-\t\t\t\t\tname: 'future-pattern-conflict-score:if-then-preference',\n-\t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t}),\n \t\t\t]),\n \t\t);\n-\t\texpect(chosen?.decision.branch?.deltas.length).toBeGreaterThan(0);\n+\t\texpect(\n+\t\t\t(chosen?.decision.branch?.deltas ?? chosen?.decision.deltas ?? []).length,\n+\t\t).toBeGreaterThan(0);\n \t\texpect(\n \t\t\tchosen?.candidate.dates?.every((date) =>\n \t\t\t\toutcome.placements.some((p) => p.date === date),\n@@ -749,46 +761,52 @@ describe('planner explanation and trace seam', () => {\n \t\t\thorizon: { start: '2024-04-25', end: '2024-05-08' },\n \t\t\tbalances: [\n \t\t\t\tbalance('cp1', 'cp', 1, '2025-12-31'),\n-\t\t\t\tbalance('cp2', 'cp', 2, '2024-05-07'),\n+\t\t\t\t{ ...balance('cp2', 'cp', 2, '2024-05-07'), availableFrom: '2024-04-26' },\n \t\t\t\tbalance('rtt', 'rtt', 0, '2026-01-01'),\n \t\t\t],\n \t\t\trules: [\n-\t\t\t\t{\n-\t\t\t\t\tid: 'anchor',\n-\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\tstartDate: '2024-04-25',\n-\t\t\t\t\tendDate: '2024-04-25',\n-\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tid: 'producer',\n-\t\t\t\t\ttype: 'if_then',\n-\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\tdayOfWeek: 3,\n-\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\tplacement: 'after',\n-\t\t\t\t\trewardDays: 1,\n-\t\t\t\t\trewardType: 'rtt',\n-\t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tid: 'consumer',\n-\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\tstartDate: '2024-05-06',\n-\t\t\t\t\tendDate: '2024-05-06',\n-\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\tplaceType: 'rtt',\n-\t\t\t\t},\n+\t\t\t\tpresets[0],\n+\t\t\t\t...[\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'anchor',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tstartDate: '2024-04-25',\n+\t\t\t\t\t\tendDate: '2024-04-25',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\trewardType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'consumer',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tstartDate: '2024-05-06',\n+\t\t\t\t\t\tendDate: '2024-05-06',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\t...presets.slice(1),\n \t\t\t],\n \t\t});\n \t\tconst outcome = await calculation.outcome;\n \t\texpect(outcome.kind).toBe('Plan');\n \t\tif (outcome.kind !== 'Plan') return;\n \t\tconst atRisk = outcome.placements.find(\n-\t\t\t(placement) => placement.balanceId === 'cp2' && !placement.ruleIds.length,\n+\t\t\t(placement) =>\n+\t\t\t\tplacement.balanceId === 'cp2' &&\n+\t\t\t\tplacement.ruleIds.every((id) => id.startsWith('default-')),\n \t\t);\n \t\texpect(atRisk?.date).toBeDefined();\n \t\tif (!atRisk) return;\n@@ -1006,7 +1024,11 @@ describe('planner explanation and trace seam', () => {\n \t\t\texpect((await calculation.explanation)?.kind).toBe('ConflictExplanation');\n \t\t\tconst trace = await calculation.trace;\n \t\t\texpect(trace?.phases.some((phase) => phase.name === 'obligations')).toBe(true);\n-\t\t\texpect(trace?.phases.some((phase) => phase.name === 'holiday-week-value')).toBe(false);\n+\t\t\texpect(\n+\t\t\t\ttrace?.phases.some(\n+\t\t\t\t\t(phase) => phase.name === 'optimization:default-holiday-week-value',\n+\t\t\t\t),\n+\t\t\t).toBe(false);\n \t\t\tif (index === 1)\n \t\t\t\texpect(\n \t\t\t\t\ttrace?.phases\n@@ -1076,9 +1098,10 @@ describe('planner explanation and trace seam', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\tbalances: [balance('cp', 'cp', 2, '2024-01-31')],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t\tprogress: (stage: string) => {\n-\t\t\t\tif (stage === 'holiday-week-value') throw new Error('interrupted after checkpoint');\n+\t\t\t\tif (stage === 'optimization:default-holiday-week-value')\n+\t\t\t\t\tthrow new Error('interrupted after checkpoint');\n \t\t\t},\n \t\t};\n \t\tconst outcome = core.calculatePlanningInternal(request, (plan, state) => {\n@@ -1128,8 +1151,8 @@ describe('planner explanation and trace seam', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-15' },\n \t\t\tbalances: [balance('cp', 'cp', 3, '2024-01-31')],\n-\t\t\trules: [],\n-\t\t\tdeadlineMs: 1_000,\n+\t\t\trules: presets,\n+\t\t\tdeadlineMs: 100_000,\n \t\t};\n \t\tconst plain = core.calculatePlanningInternal(request);\n \t\tclock = 0;\n@@ -1156,6 +1179,7 @@ describe('planner explanation and trace seam', () => {\n \t\texpect(artifacts?.trace?.status).toBe('ready');\n \t\texpect(artifacts?.timings?.planningWorkMs).toBeLessThan(request.deadlineMs);\n \t\texpect(artifacts?.timings?.traceTransferMs).toBeGreaterThanOrEqual(callbackCount * 10_000);\n+\t\texpect(artifacts?.timings?.traceTransferMs).toBeGreaterThan(request.deadlineMs);\n \t\tconst decisions = artifacts?.trace?.phases.flatMap((phase) => phase.decisions) ?? [];\n \t\tconst candidateUpdates = operations.filter((operation) => operation.kind === 'candidate');\n \t\texpect(candidateUpdates.some((operation) => operation.mode === 'replace')).toBe(true);\n@@ -1180,7 +1204,7 @@ describe('planner explanation and trace seam', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-08' },\n \t\t\tbalances: [balance('cp', 'cp', 2, '2024-01-07')],\n-\t\t\trules: [],\n+\t\t\trules: [presets[0]],\n \t\t};\n \t\tlet plainArtifacts: import('./leave-planner.core').PlanningArtifacts | undefined;\n \t\tconst plain = core.calculatePlanningInternal(request, undefined, (value) => {\n@@ -1210,6 +1234,7 @@ describe('planner explanation and trace seam', () => {\n \t\t\t\tcandidate,\n \t\t\t})),\n \t\t);\n+\t\texpect(candidates.length).toBeGreaterThan(0);\n \t\tconst candidateOperations = operations.filter(\n \t\t\t(operation): operation is Extract =>\n \t\t\t\toperation.kind === 'candidate',\n@@ -1232,7 +1257,7 @@ describe('planner explanation and trace seam', () => {\n \t\tconst early = createPlanningCalculation({\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\tbalances: [balance('cp', 'cp', 1, '2024-01-31')],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t\tdeadlineMs: 0,\n \t\t});\n \t\tconst earlyOutcome = await early.outcome;\n@@ -1247,16 +1272,18 @@ describe('planner explanation and trace seam', () => {\n \t\texpect(earlyTrace?.phases.find((phase) => phase.name === 'obligations')?.status).toBe(\n \t\t\t'interrupted',\n \t\t);\n-\t\texpect(earlyTrace?.phases.find((phase) => phase.name === 'at-risk')?.status).toBe(\n-\t\t\t'not-run',\n-\t\t);\n+\t\texpect(\n+\t\t\tearlyTrace?.phases.find(\n+\t\t\t\t(phase) => phase.name === 'optimization:default-unplaced-at-risk',\n+\t\t\t)?.status,\n+\t\t).toBe('not-run');\n \n \t\tconst quality = createPlanningCalculation({\n \t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n \t\t\tbalances: [balance('cp', 'cp', 1, '2024-01-31')],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t\tprogress: (stage) => {\n-\t\t\t\tif (stage === 'holiday-week-value') {\n+\t\t\t\tif (stage === 'optimization:default-holiday-week-value') {\n \t\t\t\t\tthrow new Error('deliberate interruption in quality phase');\n \t\t\t\t}\n \t\t\t},\n@@ -1266,13 +1293,21 @@ describe('planner explanation and trace seam', () => {\n \t\texpect(qualityOutcome.kind).toBe('PlanningIncomplete');\n \t\tif (qualityOutcome.kind !== 'PlanningIncomplete') return;\n \t\texpect(qualityOutcome.reasons[0].code).toBe('planner-error');\n-\t\texpect(qualityOutcome.completedStages).toEqual(['validation', 'obligations', 'at-risk']);\n+\t\texpect(qualityOutcome.completedStages).toEqual([\n+\t\t\t'validation',\n+\t\t\t'obligations',\n+\t\t\t'optimization:default-unplaced-at-risk',\n+\t\t]);\n \t\texpect(qualityTrace?.completedStages).toEqual(qualityOutcome.completedStages);\n \t\texpect(\n-\t\t\tqualityTrace?.phases.find((phase) => phase.name === 'holiday-week-value')?.status,\n+\t\t\tqualityTrace?.phases.find(\n+\t\t\t\t(phase) => phase.name === 'optimization:default-holiday-week-value',\n+\t\t\t)?.status,\n \t\t).toBe('interrupted');\n \t\texpect(\n-\t\t\tqualityTrace?.phases.find((phase) => phase.name === 'non-working-day-gain')?.status,\n+\t\t\tqualityTrace?.phases.find(\n+\t\t\t\t(phase) => phase.name === 'optimization:default-non-working-day-gain',\n+\t\t\t)?.status,\n \t\t).toBe('not-run');\n \t});\n });\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner-explanation.spec.ts", "project_id": 35, "relative_order": 21, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,186 @@\n+import { createOptimizationPresetRules } from './rule-service';\n+import { describe, expect, it } from 'vitest';\n+import { calculatePlanningInternal, type PlanningArtifacts } from './leave-planner.core';\n+import {\n+\tevaluateOptimization,\n+\tOPTIMIZATION_PRESETS,\n+\ttype OptimizationObservations,\n+} from './planning-objectives';\n+\n+const presets = createOptimizationPresetRules();\n+\n+describe('planning objective observations', () => {\n+\tit.each([\n+\t\t{ start: '2024-05-06', end: '2024-05-13' },\n+\t\t{ start: '2024-05-10', end: '2024-05-11' },\n+\t])(\n+\t\t'evaluates the same declared holiday week and supporting placement at horizon boundaries',\n+\t\t(horizon) => {\n+\t\t\tconst result = calculatePlanningInternal({\n+\t\t\t\thorizon,\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2024-05-06',\n+\t\t\t\t\t\texpiryDate: '2025-05-06',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules: presets,\n+\t\t\t\tdeclaredDays: ['2024-05-06', '2024-05-07'].map((date) => ({ date, type: 'other' })),\n+\t\t\t});\n+\t\t\texpect(result.kind).toBe('Plan');\n+\t\t\tif (result.kind !== 'Plan') return;\n+\t\t\texpect(result.placements).toEqual([\n+\t\t\t\t{\n+\t\t\t\t\tdate: '2024-05-10',\n+\t\t\t\t\tbalanceId: 'cp',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\truleIds: ['default-holiday-week-value'],\n+\t\t\t\t\tsupporting: true,\n+\t\t\t\t},\n+\t\t\t]);\n+\t\t\tconst observations: OptimizationObservations = {\n+\t\t\t\tleaveBalances: [{ unplacedQuantity: 0, atRisk: false }],\n+\t\t\t\tpublicHolidayWeeks: [{ value: 5, complete: true }],\n+\t\t\t\ttimeOffPeriods: result.timeOffPeriods,\n+\t\t\t\tworkSequences: [\n+\t\t\t\t\t{ length: 0, internal: false },\n+\t\t\t\t\t{ length: 0, internal: false },\n+\t\t\t\t],\n+\t\t\t\tleavePlacements: result.placements,\n+\t\t\t};\n+\t\t\texpect(\n+\t\t\t\tObject.values(OPTIMIZATION_PRESETS).map((configuration) =>\n+\t\t\t\t\tevaluateOptimization(configuration, observations),\n+\t\t\t\t),\n+\t\t\t).toEqual([0, 5, 6, 0, 0, 1]);\n+\t\t\texpect(result.metrics).toMatchObject({\n+\t\t\t\tunplacedAtRisk: 0,\n+\t\t\t\tholidayWeekValue: 5,\n+\t\t\t\tnonWorkingDayGain: 6,\n+\t\t\t\tlongestWorkSequence: 0,\n+\t\t\t\tshortSequenceDeficit: 0,\n+\t\t\t\tsupportingPlacements: 1,\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit('uses internal working-day deficits while retaining both horizon edges in the maximum', () => {\n+\t\tconst result = calculatePlanningInternal({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-18' },\n+\t\t\tbalances: [],\n+\t\t\trules: [],\n+\t\t\tdeclaredDays: ['2024-01-05', '2024-01-09'].map((date) => ({ date, type: 'other' })),\n+\t\t});\n+\t\texpect(result.kind).toBe('Plan');\n+\t\tif (result.kind !== 'Plan') return;\n+\t\texpect(result.metrics).toMatchObject({\n+\t\t\tlongestWorkSequence: 6,\n+\t\t\tshortSequenceDeficit: 4,\n+\t\t\tnonWorkingDayGain: 2,\n+\t\t});\n+\t\tconst observations: OptimizationObservations = {\n+\t\t\tleaveBalances: [],\n+\t\t\tpublicHolidayWeeks: [],\n+\t\t\ttimeOffPeriods: result.timeOffPeriods,\n+\t\t\tworkSequences: [\n+\t\t\t\t{ length: 3, internal: false },\n+\t\t\t\t{ length: 1, internal: true },\n+\t\t\t\t{ length: 6, internal: false },\n+\t\t\t],\n+\t\t\tleavePlacements: result.placements,\n+\t\t};\n+\t\texpect(evaluateOptimization(OPTIMIZATION_PRESETS.shortSequenceDeficit, observations)).toBe(\n+\t\t\t4,\n+\t\t);\n+\t\texpect(\n+\t\t\tevaluateOptimization(\n+\t\t\t\t{ ...OPTIMIZATION_PRESETS.shortSequenceDeficit, thresholdDays: 3 },\n+\t\t\t\tobservations,\n+\t\t\t),\n+\t\t).toBe(2);\n+\t});\n+\n+\tit.each([\n+\t\t['2024-01-01', '2024-01-06', ['2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'], 1],\n+\t\t['2018-04-30', '2018-05-05', ['2018-04-30', '2018-05-02', '2018-05-03', '2018-05-04'], 2],\n+\t\t['2024-04-29', '2024-05-04', ['2024-04-29', '2024-04-30', '2024-05-02', '2024-05-03'], 3],\n+\t\t['2024-08-12', '2024-08-17', ['2024-08-12', '2024-08-13', '2024-08-14', '2024-08-16'], 2],\n+\t\t['2024-10-28', '2024-11-02', ['2024-10-28', '2024-10-29', '2024-10-30', '2024-10-31'], 1],\n+\t] as const)(\n+\t\t'retains the weekday holiday weight in the completed week starting %s',\n+\t\t(start, end, dates, value) => {\n+\t\t\tconst result = calculatePlanningInternal({\n+\t\t\t\thorizon: { start, end },\n+\t\t\t\tbalances: [],\n+\t\t\t\trules: [],\n+\t\t\t\tdeclaredDays: dates.map((date) => ({ date, type: 'other' })),\n+\t\t\t});\n+\t\t\texpect(result.kind).toBe('Plan');\n+\t\t\tif (result.kind === 'Plan') expect(result.metrics.holidayWeekValue).toBe(value);\n+\t\t},\n+\t);\n+\n+\tit('keeps the historical objective order in the explanation of a jointly valid plan', () => {\n+\t\tlet artifacts: PlanningArtifacts | undefined;\n+\t\tconst result = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\thorizon: { start: '2024-01-02', end: '2024-01-18' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2024-01-02',\n+\t\t\t\t\t\texpiryDate: '2024-01-17',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules: [\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'fixed',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\t\tstartDate: '2024-01-05',\n+\t\t\t\t\t\t\tendDate: '2024-01-05',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'personal',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tstartDate: '2024-01-09',\n+\t\t\t\t\t\t\tendDate: '2024-01-09',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n+\t\t\t\t],\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\texpect(result.kind).toBe('Plan');\n+\t\texpect(artifacts?.explanation?.kind).toBe('PlanExplanation');\n+\t\tif (artifacts?.explanation?.kind !== 'PlanExplanation') return;\n+\t\tconst placement = artifacts.explanation.placements[0];\n+\t\texpect(placement.objectiveVector.objectives.map((objective) => objective.id)).toEqual([\n+\t\t\t'obligation-validity',\n+\t\t\t'optimization:default-unplaced-at-risk',\n+\t\t\t'preference:personal',\n+\t\t\t'optimization:default-holiday-week-value',\n+\t\t\t'optimization:default-non-working-day-gain',\n+\t\t\t'optimization:default-longest-work-sequence',\n+\t\t\t'optimization:default-short-sequence-deficit',\n+\t\t\t'optimization:default-supporting-placements',\n+\t\t\t'balance-expiry',\n+\t\t\t'placement-date',\n+\t\t]);\n+\t\texpect(placement.firstDecisiveObjective).toBe('obligation-validity');\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/services/leave-planner-objectives.spec.ts", "project_id": 35, "relative_order": 22, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,10 +1,116 @@\n+import { createOptimizationPresetRules } from './rule-service';\n import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';\n import { createPlanningCalculation } from './leave-planner.service';\n+import {\n+\tcalculatePlanningInternal,\n+\ttype PlanningArtifacts,\n+\ttype PlanningTraceCandidate,\n+\ttype PlanningTraceUpdate,\n+} from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n \n beforeEach(() => vi.stubGlobal('window', undefined));\n afterEach(() => vi.unstubAllGlobals());\n \n+const presets = createOptimizationPresetRules();\n+\n describe('quality calculation trace', () => {\n+\tit('keeps emitted comparison metadata unchanged when candidate snapshots are replaced', () => {\n+\t\tconst updates: PlanningTraceUpdate[] = [];\n+\t\tconst captured: string[] = [];\n+\t\tlet artifacts: PlanningArtifacts = {};\n+\t\tlet clock = 0;\n+\t\tconst clockSpy = vi.spyOn(performance, 'now').mockImplementation(() => (clock += 30));\n+\t\ttry {\n+\t\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t\t{\n+\t\t\t\t\tcalculationDate: '2026-11-01',\n+\t\t\t\t\thorizon: { start: '2026-11-03', end: '2026-11-14' },\n+\t\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2027-01-01' }],\n+\t\t\t\t\tdeclaredDays: [\n+\t\t\t\t\t\t{ date: '2026-11-09', type: 'other' },\n+\t\t\t\t\t\t{ date: '2026-11-10', type: 'other' },\n+\t\t\t\t\t],\n+\t\t\t\t\trules: [\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'holiday',\n+\t\t\t\t\t\t\tname: 'Holiday weeks',\n+\t\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\t...[3, 5].map((thresholdDays) => ({\n+\t\t\t\t\t\t\tid: `deficit-${thresholdDays}`,\n+\t\t\t\t\t\t\tname: `Deficit ${thresholdDays} days`,\n+\t\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t\t\t\tconditions: ['non-empty'],\n+\t\t\t\t\t\t\t\tthresholdDays,\n+\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t})),\n+\t\t\t\t\t],\n+\t\t\t\t\ttraceProgress: (_elapsed: number, update: PlanningTraceUpdate) => {\n+\t\t\t\t\t\tupdates.push(update);\n+\t\t\t\t\t\tcaptured.push(JSON.stringify(update));\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\texpect(outcome.kind).toBe('Plan');\n+\t\t\texpect(artifacts.trace?.status).toBe('ready');\n+\t\t\texpect(updates.map((update) => JSON.stringify(update))).toEqual(captured);\n+\t\t\tconst emitted = new Map();\n+\t\t\tlet replacements = 0;\n+\t\t\tfor (const update of updates)\n+\t\t\t\tfor (const operation of update.operations) {\n+\t\t\t\t\tif (operation.kind !== 'candidate') continue;\n+\t\t\t\t\tif (operation.mode === 'replace') replacements++;\n+\t\t\t\t\temitted.set(\n+\t\t\t\t\t\t`${operation.phaseId}/${operation.decisionId}/${operation.index}`,\n+\t\t\t\t\t\toperation.candidate,\n+\t\t\t\t\t);\n+\t\t\t\t}\n+\t\t\texpect(replacements).toBeGreaterThan(0);\n+\t\t\texpect(emitted.size).toBeGreaterThan(0);\n+\t\t\tfor (const phase of artifacts.trace!.phases)\n+\t\t\t\tfor (const decision of phase.decisions)\n+\t\t\t\t\tdecision.candidates.forEach((candidate, index) =>\n+\t\t\t\t\t\texpect(emitted.get(`${phase.id}/${decision.id}/${index}`)).toEqual(\n+\t\t\t\t\t\t\tcandidate,\n+\t\t\t\t\t\t),\n+\t\t\t\t\t);\n+\t\t\tconst comparison = [...emitted.values()].find(\n+\t\t\t\t(candidate) => candidate.comparison,\n+\t\t\t)?.comparison;\n+\t\t\texpect(comparison?.after.objectives).toEqual(\n+\t\t\t\texpect.arrayContaining([\n+\t\t\t\t\texpect.objectContaining({\n+\t\t\t\t\t\tid: 'optimization:deficit-3',\n+\t\t\t\t\t\tlabel: 'Deficit 3 days',\n+\t\t\t\t\t\tdirection: 'minimize',\n+\t\t\t\t\t}),\n+\t\t\t\t\texpect.objectContaining({\n+\t\t\t\t\t\tid: 'optimization:deficit-5',\n+\t\t\t\t\t\tlabel: 'Deficit 5 days',\n+\t\t\t\t\t\tdirection: 'minimize',\n+\t\t\t\t\t}),\n+\t\t\t\t]),\n+\t\t\t);\n+\t\t\texpect(\n+\t\t\t\t[...emitted.values()].some(({ comparison }) => {\n+\t\t\t\t\tconst values = comparison?.after.objectives;\n+\t\t\t\t\treturn (\n+\t\t\t\t\t\tvalues?.find(({ id }) => id === 'optimization:deficit-3')?.value === 0 &&\n+\t\t\t\t\t\tvalues?.find(({ id }) => id === 'optimization:deficit-5')?.value === 1\n+\t\t\t\t\t);\n+\t\t\t\t}),\n+\t\t\t).toBe(true);\n+\t\t} finally {\n+\t\t\tclockSpy.mockRestore();\n+\t\t}\n+\t});\n+\n \tit('separates source effects from the actual incumbent comparison', async () => {\n \t\tconst calculation = createPlanningCalculation({\n \t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n@@ -17,71 +123,47 @@ describe('quality calculation trace', () => {\n \t\t\t\t\texpiryDate: '2024-01-31',\n \t\t\t\t},\n \t\t\t],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t});\n-\t\tconst outcome = await calculation.outcome;\n+\t\texpect((await calculation.outcome).kind).toBe('Plan');\n \t\tconst trace = await calculation.trace;\n-\t\texpect(outcome.kind).toBe('Plan');\n \t\texpect(trace?.status).toBe('ready');\n-\t\tif (outcome.kind !== 'Plan' || !trace) return;\n-\n-\t\tconst phase = trace.phases.find((item) => item.name === 'non-working-day-gain');\n-\t\tconst jan3Decision = phase?.decisions.find((decision) =>\n-\t\t\tdecision.candidates.some((candidate) => candidate.sourceDate === '2024-01-03'),\n-\t\t);\n-\t\tconst jan2Decision = phase?.decisions.find((decision) =>\n-\t\t\tdecision.candidates.some((candidate) => candidate.sourceDate === '2024-01-02'),\n+\t\tconst phase = trace?.phases.find(({ name }) => name === `optimization:${presets[0].id}`);\n+\t\tconst decision = phase?.decisions.find(({ candidates }) =>\n+\t\t\tcandidates.some(({ status, date }) => status === 'chosen' && date === '2024-01-02'),\n \t\t);\n-\t\tconst jan5 = jan3Decision?.candidates.find(\n-\t\t\t(candidate) => candidate.sourceDate === '2024-01-03' && candidate.date === '2024-01-05',\n+\t\tconst rejected = decision?.candidates.find(\n+\t\t\t({ date, comparison }) => date === '2024-01-05' && comparison,\n \t\t);\n-\t\tconst jan8 = jan3Decision?.candidates.find(\n-\t\t\t(candidate) => candidate.sourceDate === '2024-01-03' && candidate.date === '2024-01-08',\n-\t\t);\n-\n-\t\texpect(jan2Decision).toBeDefined();\n-\t\texpect(jan3Decision).toBeDefined();\n-\t\texpect(jan3Decision).not.toBe(jan2Decision);\n-\t\texpect(jan3Decision?.dates).toEqual(['2024-01-03', '2024-01-05']);\n-\t\texpect(jan5?.status).toBe('chosen');\n-\t\texpect(jan8?.status).toBe('evaluated-rejected');\n-\t\texpect(jan3Decision?.deltas).toContainEqual(\n+\t\texpect(rejected?.status).toBe('evaluated-rejected');\n+\t\tconst sourceValue = (state: 'before' | 'after', id: string) =>\n+\t\t\trejected?.comparison?.[state].objectives.find((objective) => objective.id === id)\n+\t\t\t\t?.value;\n+\t\texpect(sourceValue('before', `optimization:${presets[0].id}`)).toBe(2);\n+\t\texpect(sourceValue('after', `optimization:${presets[0].id}`)).toBe(1);\n+\t\texpect(sourceValue('before', `optimization:${presets[2].id}`)).toBe(0);\n+\t\texpect(sourceValue('after', `optimization:${presets[2].id}`)).toBe(2);\n+\t\texpect(rejected?.comparison?.firstDecisiveObjective).toBe(`optimization:${presets[0].id}`);\n+\t\t// The January 2 candidate already gains three natural non-working days.\n+\t\t// January 5 improves its source state, but loses to that current best candidate.\n+\t\texpect(rejected?.technicalComparison).toContainEqual({\n+\t\t\tname: `optimization:${presets[2].id}`,\n+\t\t\tdirection: 'maximize',\n+\t\t\tbefore: 3,\n+\t\t\tafter: 2,\n+\t\t});\n+\t\texpect(\n+\t\t\trejected?.technicalComparison?.some(\n+\t\t\t\t({ name }) => name === `optimization:${presets[3].id}`,\n+\t\t\t),\n+\t\t).toBe(false);\n+\t\texpect(rejected?.firstDecisiveComparator).toBe(`optimization:${presets[2].id}`);\n+\t\texpect(rejected?.reason?.message).toContain('did not improve the current best result');\n+\t\texpect(decision?.deltas).toContainEqual(\n \t\t\texpect.objectContaining({\n-\t\t\t\tkind: 'placement-moved',\n-\t\t\t\tfromDate: '2024-01-03',\n-\t\t\t\ttoDate: '2024-01-05',\n+\t\t\t\tkind: 'placement-added',\n+\t\t\t\tdate: '2024-01-02',\n \t\t\t}),\n \t\t);\n-\n-\t\tconst sourceValue = (\n-\t\t\tcandidate: typeof jan5,\n-\t\t\tstate: 'before' | 'after',\n-\t\t\tobjective: string,\n-\t\t) => candidate?.comparison?.[state].objectives.find((item) => item.id === objective)?.value;\n-\t\texpect(sourceValue(jan5, 'before', 'non-working-day-gain')).toBe(3);\n-\t\texpect(sourceValue(jan5, 'after', 'non-working-day-gain')).toBe(5);\n-\t\texpect(sourceValue(jan5, 'before', 'longest-work-sequence')).toBe(20);\n-\t\texpect(sourceValue(jan5, 'after', 'longest-work-sequence')).toBe(18);\n-\t\texpect(sourceValue(jan8, 'before', 'non-working-day-gain')).toBe(3);\n-\t\texpect(sourceValue(jan8, 'after', 'non-working-day-gain')).toBe(5);\n-\t\texpect(sourceValue(jan8, 'before', 'longest-work-sequence')).toBe(20);\n-\t\texpect(sourceValue(jan8, 'after', 'longest-work-sequence')).toBe(17);\n-\t\texpect(jan8?.comparison?.firstDecisiveObjective).toBe('non-working-day-gain');\n-\n-\t\texpect(jan8?.technicalComparison).toEqual(\n-\t\t\texpect.arrayContaining([\n-\t\t\t\texpect.objectContaining({\n-\t\t\t\t\tname: 'non-working-day-gain',\n-\t\t\t\t\tdirection: 'maximize',\n-\t\t\t\t\tbefore: 5,\n-\t\t\t\t\tafter: 5,\n-\t\t\t\t}),\n-\t\t\t]),\n-\t\t);\n-\t\texpect(\n-\t\t\tjan8?.technicalComparison?.some((item) => item.name === 'longest-work-sequence'),\n-\t\t).toBe(false);\n-\t\texpect(jan8?.firstDecisiveComparator).toBeUndefined();\n-\t\texpect(jan8?.reason?.message).toContain('did not improve the current best result');\n \t});\n });\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner-quality-trace.spec.ts", "project_id": 35, "relative_order": 23, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,823 @@\n+import { vi } from 'vitest';\n+import {\n+\tcalculatePlanningAsyncInternal,\n+\tcalculatePlanningInternal,\n+\ttype OptimizationPlanningRule,\n+\ttype PlanOutcome,\n+\ttype PlanningArtifacts,\n+\ttype PlanningRequest,\n+\ttype PlanningTraceUpdate,\n+} from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+import { applyReplayDeltas, createPlanningCalculation } from './leave-planner.service';\n+\n+const economy: OptimizationPlanningRule = {\n+\tid: 'economy',\n+\tname: 'Économiser les jours d’appoint',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+};\n+const gain: OptimizationPlanningRule = {\n+\tid: 'gain',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.nonWorkingDayGain,\n+};\n+const requested: PlanningRequest['rules'][number] = {\n+\tid: 'requested',\n+\ttype: 'time_window',\n+\tstartDate: '2024-01-05',\n+\tendDate: '2024-01-05',\n+\tplaceDays: 1,\n+\tplaceType: 'cp',\n+};\n+const weekend: PlanningRequest = {\n+\thorizon: { start: '2024-01-05', end: '2024-01-10' },\n+\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2025-01-01' }],\n+\trules: [],\n+};\n+const bundles: {\n+\tname: string;\n+\trule: OptimizationPlanningRule;\n+\trequest: PlanningRequest;\n+\tdates: string[];\n+}[] = [\n+\t{\n+\t\tname: 'complete public-holiday week',\n+\t\trule: {\n+\t\t\tid: 'holiday',\n+\t\t\ttype: 'optimization',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t},\n+\t\trequest: {\n+\t\t\thorizon: { start: '2026-11-09', end: '2026-11-14' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2027-01-01' }],\n+\t\t\tdeclaredDays: ['2026-11-09', '2026-11-10'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [],\n+\t\t},\n+\t\tdates: ['2026-11-12', '2026-11-13'],\n+\t},\n+\t{\n+\t\tname: 'non-working-day gain',\n+\t\trule: gain,\n+\t\trequest: weekend,\n+\t\tdates: ['2024-01-05'],\n+\t},\n+\t{\n+\t\tname: 'maximum non-working gain of a joined period',\n+\t\trule: {\n+\t\t\t...gain,\n+\t\t\tconfiguration: { ...gain.configuration, aggregation: 'maximum' },\n+\t\t},\n+\t\trequest: {\n+\t\t\thorizon: { start: '2024-01-05', end: '2024-01-13' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 4, expiryDate: '2025-01-01' }],\n+\t\t\tdeclaredDays: ['2024-01-05', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [],\n+\t\t},\n+\t\tdates: ['2024-01-08', '2024-01-09', '2024-01-10', '2024-01-11'],\n+\t},\n+\t{\n+\t\tname: 'complete short internal work sequence',\n+\t\trule: {\n+\t\t\tid: 'deficit',\n+\t\t\ttype: 'optimization',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t},\n+\t\trequest: {\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: ['2024-01-08', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [],\n+\t\t},\n+\t\tdates: ['2024-01-09', '2024-01-10', '2024-01-11'],\n+\t},\n+\t{\n+\t\tname: 'tied longest work sequences',\n+\t\trule: {\n+\t\t\tid: 'longest',\n+\t\t\ttype: 'optimization',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.longestWorkSequence,\n+\t\t},\n+\t\trequest: {\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: [{ date: '2024-01-10', type: 'other' }],\n+\t\t\trules: [],\n+\t\t},\n+\t\tdates: ['2024-01-08', '2024-01-11'],\n+\t},\n+];\n+\n+function plan(request: PlanningRequest): PlanOutcome {\n+\tconst outcome = calculatePlanningInternal(request);\n+\tif (outcome.kind !== 'Plan') throw new Error(`Expected a plan, got ${outcome.kind}`);\n+\treturn outcome;\n+}\n+\n+describe('supporting placement economy and provenance', () => {\n+\tbeforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n+\tafterEach(() => vi.useRealTimers());\n+\n+\tit.each(bundles)(\n+\t\t'compares the whole $name bundle against economy in either order',\n+\t\t({ rule, request, dates }) => {\n+\t\t\tconst improve = plan({ ...request, rules: [rule, economy] });\n+\t\t\tconst preserve = plan({ ...request, rules: [economy, rule] });\n+\t\t\texpect(improve.placements.map(({ date }) => date)).toEqual(dates);\n+\t\t\texpect(improve.placements.every(({ supporting }) => supporting)).toBe(true);\n+\t\t\texpect(improve.metrics.supportingPlacements).toBe(dates.length);\n+\t\t\texpect(improve.remainingBalances).toEqual([]);\n+\t\t\texpect(preserve.placements).toEqual([]);\n+\t\t\texpect(preserve.metrics.supportingPlacements).toBe(0);\n+\t\t\texpect(preserve.remainingBalances[0]).toMatchObject({\n+\t\t\t\tid: 'cp',\n+\t\t\t\tquantity: request.balances[0].quantity,\n+\t\t\t\tclassification: 'deferred',\n+\t\t\t\treason: { code: 'preserved' },\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit.each(bundles)(\n+\t\t'makes disabled economy identical to absence for the $name bundle',\n+\t\t({ rule, request }) => {\n+\t\t\tconst absent = plan({ ...request, rules: [rule] });\n+\t\t\tfor (const rules of [\n+\t\t\t\t[{ ...economy, enabled: false }, rule],\n+\t\t\t\t[rule, { ...economy, enabled: false }],\n+\t\t\t])\n+\t\t\t\texpect(plan({ ...request, rules })).toEqual(absent);\n+\t\t},\n+\t);\n+\n+\tit('does not add placements merely because economy is disabled or removed', () => {\n+\t\tfor (const rules of [[], [economy], [{ ...economy, enabled: false }]]) {\n+\t\t\tconst outcome = plan({ ...weekend, rules });\n+\t\t\texpect(outcome.placements).toEqual([]);\n+\t\t\texpect(outcome.remainingBalances[0].quantity).toBe(1);\n+\t\t}\n+\t});\n+\n+\tit('credits an earlier supporting placement to a later explicit window without counting an extra day', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...weekend,\n+\t\t\trules: [gain, economy, requested],\n+\t\t});\n+\t\texpect(outcome.placements).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2024-01-05',\n+\t\t\t\tbalanceId: 'cp',\n+\t\t\t\truleIds: ['gain', 'requested'],\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t]);\n+\t\texpect(outcome.metrics).toMatchObject({ nonWorkingDayGain: 2, supportingPlacements: 0 });\n+\t\texpect(outcome.preferences[0].satisfied).toBe(1);\n+\t});\n+\n+\tit('exempts only the requested window quantity, including fixed declared days', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...weekend,\n+\t\t\thorizon: { start: '2024-01-05', end: '2024-01-20' },\n+\t\t\tbalances: [{ ...weekend.balances[0], quantity: 3 }],\n+\t\t\tdeclaredDays: [{ date: '2024-01-09', type: 'cp' }],\n+\t\t\trules: [gain, economy, { ...requested, endDate: '2024-01-19', placeDays: 2 }],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date, supporting }) => ({ date, supporting }))).toEqual([\n+\t\t\t{ date: '2024-01-05', supporting: false },\n+\t\t\t{ date: '2024-01-12', supporting: true },\n+\t\t\t{ date: '2024-01-19', supporting: true },\n+\t\t]);\n+\t\texpect(outcome.metrics.supportingPlacements).toBe(2);\n+\t\texpect(outcome.timeWindowContributions?.[0]).toMatchObject({\n+\t\t\trequested: 2,\n+\t\t\tdeclaredDays: [{ date: '2024-01-09', type: 'cp' }],\n+\t\t\tplacementDates: ['2024-01-05'],\n+\t\t});\n+\t});\n+\n+\tit.each([false, true])(\n+\t\t'bounds explicit calendar credit before accepting further window improvements (declared: %s)',\n+\t\t(declared) => {\n+\t\t\tconst windowRule = { ...requested, endDate: '2024-01-19' };\n+\t\t\tconst request: PlanningRequest = {\n+\t\t\t\t...weekend,\n+\t\t\t\thorizon: { start: '2024-01-05', end: '2024-01-20' },\n+\t\t\t\tbalances: [{ ...weekend.balances[0], quantity: 4 }],\n+\t\t\t\tdeclaredDays: declared ? [{ date: '2024-01-09', type: 'cp' }] : [],\n+\t\t\t\trules: [economy, gain, windowRule],\n+\t\t\t};\n+\t\t\tconst preserve = plan(request);\n+\t\t\texpect(preserve.placements).toEqual(\n+\t\t\t\tdeclared\n+\t\t\t\t\t? []\n+\t\t\t\t\t: [\n+\t\t\t\t\t\t\texpect.objectContaining({\n+\t\t\t\t\t\t\t\tdate: '2024-01-05',\n+\t\t\t\t\t\t\t\truleIds: ['requested'],\n+\t\t\t\t\t\t\t\tsupporting: false,\n+\t\t\t\t\t\t\t}),\n+\t\t\t\t\t\t],\n+\t\t\t);\n+\t\t\texpect(preserve.metrics.supportingPlacements).toBe(0);\n+\t\t\texpect(preserve.preferences[0].satisfied).toBe(1);\n+\t\t\texpect(preserve.remainingBalances[0]).toMatchObject({\n+\t\t\t\tid: 'cp',\n+\t\t\t\tquantity: declared ? 4 : 3,\n+\t\t\t});\n+\t\t\tconst improve = plan({ ...request, rules: [gain, economy, windowRule] });\n+\t\t\texpect(improve.placements.map(({ date }) => date)).toEqual([\n+\t\t\t\t'2024-01-05',\n+\t\t\t\t'2024-01-12',\n+\t\t\t\t'2024-01-19',\n+\t\t\t]);\n+\t\t\texpect(\n+\t\t\t\timprove.placements.filter(({ ruleIds }) => ruleIds.includes('requested')),\n+\t\t\t).toHaveLength(declared ? 0 : 1);\n+\t\t\texpect(improve.metrics.supportingPlacements).toBe(declared ? 3 : 2);\n+\t\t\texpect(\n+\t\t\t\tplan({ ...request, rules: [{ ...economy, enabled: false }, gain, windowRule] }),\n+\t\t\t).toEqual(plan({ ...request, rules: [gain, windowRule] }));\n+\t\t},\n+\t);\n+\n+\tit('restores supporting classification when a moved placement loses its explicit calendar request', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...weekend,\n+\t\t\thorizon: { start: '2024-01-05', end: '2024-01-20' },\n+\t\t\tbalances: [{ ...weekend.balances[0], quantity: 4 }],\n+\t\t\trules: [\n+\t\t\t\tgain,\n+\t\t\t\t{ ...requested, startDate: '2024-01-08', endDate: '2024-01-09' },\n+\t\t\t\tbundles[4].rule,\n+\t\t\t\teconomy,\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.metrics).toMatchObject({\n+\t\t\tnonWorkingDayGain: 6,\n+\t\t\tlongestWorkSequence: 3,\n+\t\t\tsupportingPlacements: 3,\n+\t\t});\n+\t\texpect(outcome.placements.filter(({ supporting }) => !supporting)).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2024-01-08',\n+\t\t\t\truleIds: ['gain', 'requested'],\n+\t\t\t}),\n+\t\t]);\n+\t});\n+\n+\tit.each(['preference', 'obligation'] as const)(\n+\t\t'keeps explicitly requested deferred days outside economy (%s)',\n+\t\t(force) => {\n+\t\t\tconst outcome = plan({ ...weekend, rules: [economy, { ...requested, force }, gain] });\n+\t\t\texpect(outcome.placements).toEqual([\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tdate: '2024-01-05',\n+\t\t\t\t\truleIds: ['requested'],\n+\t\t\t\t\tsupporting: false,\n+\t\t\t\t}),\n+\t\t\t]);\n+\t\t\texpect(outcome.metrics).toMatchObject({\n+\t\t\t\tnonWorkingDayGain: 2,\n+\t\t\t\tsupportingPlacements: 0,\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit('credits the complete explicit IF_THEN pattern without treating its deferred day as support', () => {\n+\t\tconst outcome = plan({\n+\t\t\thorizon: { start: '2024-05-06', end: '2024-05-11' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2025-01-01' }],\n+\t\t\trules: [\n+\t\t\t\tgain,\n+\t\t\t\teconomy,\n+\t\t\t\t{\n+\t\t\t\t\tid: 'thursday',\n+\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\tdayOfWeek: 4,\n+\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\trewardDays: 0,\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2024-05-10',\n+\t\t\t\truleIds: ['gain', 'thursday'],\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t]);\n+\t\texpect(outcome.metrics.supportingPlacements).toBe(0);\n+\t\texpect(outcome.preferences[0].satisfied).toBe(1);\n+\t});\n+\n+\tit.each(['preference', 'obligation'] as const)(\n+\t\t'limits IF_THEN credit to its declared producer pattern when another complete pattern improves rest (%s)',\n+\t\t(force) => {\n+\t\t\tconst request: PlanningRequest = {\n+\t\t\t\thorizon: { start: '2024-05-06', end: '2024-05-11' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 4, expiryDate: '2025-01-01' }],\n+\t\t\t\tdeclaredDays: [{ date: '2024-05-07', type: 'cp' }],\n+\t\t\t\trules: [\n+\t\t\t\t\teconomy,\n+\t\t\t\t\tgain,\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\tforce,\n+\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\tplacement: 'auto',\n+\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\trewardType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t};\n+\t\t\tconst preserve = plan(request);\n+\t\t\texpect(preserve.placements).toEqual([]);\n+\t\t\texpect(preserve.metrics.supportingPlacements).toBe(0);\n+\t\t\texpect(preserve.remainingBalances).toEqual([\n+\t\t\t\texpect.objectContaining({ id: 'cp', quantity: 4 }),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tid: 'earned:producer:2024-05-08',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2024-05-10',\n+\t\t\t\t}),\n+\t\t\t]);\n+\t\t\texpect(preserve.ifThenContributions?.[0]).toMatchObject({\n+\t\t\t\tdeclaredDays: [{ date: '2024-05-07', type: 'cp' }],\n+\t\t\t\tplacementDates: [],\n+\t\t\t\tearnedEntitlement: { availableFrom: '2024-05-10', added: true },\n+\t\t\t});\n+\t\t\tconst improve = plan({ ...request, rules: [gain, economy, request.rules[2]] });\n+\t\t\texpect(improve.placements).toEqual([\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tdate: '2024-05-06',\n+\t\t\t\t\truleIds: ['gain'],\n+\t\t\t\t\tsupporting: true,\n+\t\t\t\t}),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tdate: '2024-05-10',\n+\t\t\t\t\truleIds: ['gain'],\n+\t\t\t\t\tsupporting: true,\n+\t\t\t\t}),\n+\t\t\t]);\n+\t\t\texpect(improve.metrics).toMatchObject({\n+\t\t\t\tnonWorkingDayGain: 6,\n+\t\t\t\tsupportingPlacements: 2,\n+\t\t\t});\n+\t\t\texpect(improve.remainingBalances).toEqual([\n+\t\t\t\texpect.objectContaining({ id: 'cp', quantity: 2 }),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tid: 'earned:producer:2024-05-08',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2024-05-13',\n+\t\t\t\t}),\n+\t\t\t]);\n+\t\t\texpect(improve.ifThenContributions?.[0]).toMatchObject({\n+\t\t\t\tdeclaredDays: [{ date: '2024-05-07', type: 'cp' }],\n+\t\t\t\tplacementDates: [],\n+\t\t\t\tearnedEntitlement: { availableFrom: '2024-05-13', added: true },\n+\t\t\t});\n+\t\t\texpect(\n+\t\t\t\tplan({\n+\t\t\t\t\t...request,\n+\t\t\t\t\trules: [{ ...economy, enabled: false }, gain, request.rules[2]],\n+\t\t\t\t}),\n+\t\t\t).toEqual(plan({ ...request, rules: [gain, request.rules[2]] }));\n+\t\t},\n+\t);\n+\n+\tit('uses expiry then dates when active rules tie, without restoring a removed gain objective', () => {\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-01-09', end: '2024-01-13' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'later', type: 'cp', quantity: 1, expiryDate: '2024-03-01' },\n+\t\t\t\t{ id: 'earlier', type: 'cp', quantity: 1, expiryDate: '2024-02-01' },\n+\t\t\t],\n+\t\t\trules: [economy, { ...requested, startDate: '2024-01-09', endDate: '2024-01-12' }],\n+\t\t};\n+\t\tconst outcome = plan(request);\n+\t\texpect(outcome.placements).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2024-01-09',\n+\t\t\t\tbalanceId: 'earlier',\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t]);\n+\t\texpect(outcome.metrics.nonWorkingDayGain).toBe(0);\n+\t\texpect(\n+\t\t\tplan({ ...request, rules: [{ ...gain, enabled: false }, ...request.rules] }),\n+\t\t).toEqual(outcome);\n+\t});\n+\n+\tit('reclassifies a deferred support addition when an eligible earlier-expiring balance replaces it', () => {\n+\t\tlet artifacts: PlanningArtifacts | undefined;\n+\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\thorizon: { start: '2024-05-06', end: '2024-05-11' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{ id: 'deferred', type: 'cp', quantity: 3, expiryDate: '2025-01-01' },\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'at-risk',\n+\t\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2024-05-07',\n+\t\t\t\t\t\texpiryDate: '2024-05-07',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules: [bundles[0].rule, economy],\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a plan');\n+\t\texpect(\n+\t\t\toutcome.placements.map(({ date, balanceId, supporting }) => ({\n+\t\t\t\tdate,\n+\t\t\t\tbalanceId,\n+\t\t\t\tsupporting,\n+\t\t\t})),\n+\t\t).toEqual([\n+\t\t\t{ date: '2024-05-06', balanceId: 'deferred', supporting: true },\n+\t\t\t{ date: '2024-05-07', balanceId: 'at-risk', supporting: false },\n+\t\t\t{ date: '2024-05-10', balanceId: 'deferred', supporting: true },\n+\t\t]);\n+\t\texpect(outcome.metrics.supportingPlacements).toBe(2);\n+\t\texpect(outcome.remainingBalances[0]).toMatchObject({ id: 'deferred', quantity: 1 });\n+\t\texpect(\n+\t\t\tartifacts?.trace?.phases.flatMap(({ decisions }) =>\n+\t\t\t\tdecisions.flatMap(({ deltas }) => deltas),\n+\t\t\t),\n+\t\t).toContainEqual(\n+\t\t\texpect.objectContaining({\n+\t\t\t\tkind: 'placement-updated',\n+\t\t\t\tpreviousPlacement: expect.objectContaining({\n+\t\t\t\t\tbalanceId: 'deferred',\n+\t\t\t\t\tsupporting: true,\n+\t\t\t\t}),\n+\t\t\t\tplacement: expect.objectContaining({ balanceId: 'at-risk', supporting: false }),\n+\t\t\t}),\n+\t\t);\n+\t});\n+\n+\tit('compares new deferred support when at-risk holiday placements relocate into an explicit window', async () => {\n+\t\tconst holiday = bundles[0].rule;\n+\t\tconst early: PlanningRequest['rules'][number] = {\n+\t\t\tid: 'early',\n+\t\t\ttype: 'time_window',\n+\t\t\tstartDate: '2026-11-02',\n+\t\t\tendDate: '2026-11-03',\n+\t\t\tplaceDays: 2,\n+\t\t\tplaceType: 'cp',\n+\t\t};\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2026-11-02', end: '2026-11-14' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'at-risk', type: 'cp', quantity: 2, expiryDate: '2026-11-13' },\n+\t\t\t\t{\n+\t\t\t\t\tid: 'deferred',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 2,\n+\t\t\t\t\tavailableFrom: '2026-11-12',\n+\t\t\t\t\texpiryDate: '2027-01-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t\tdeclaredDays: ['2026-11-09', '2026-11-10'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [],\n+\t\t};\n+\t\tconst economyFirst = plan({ ...request, rules: [holiday, economy, early] });\n+\t\tlet artifacts: PlanningArtifacts | undefined;\n+\t\tconst updates: { update: PlanningTraceUpdate; snapshot: string }[] = [];\n+\t\tconst windowFirst = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\t...request,\n+\t\t\t\trules: [holiday, early, economy],\n+\t\t\t\ttraceProgress: (_time: number, update: PlanningTraceUpdate) =>\n+\t\t\t\t\tupdates.push({ update, snapshot: JSON.stringify(update) }),\n+\t\t\t},\n+\t\t\t(checkpoint, state) => expect(state?.placements).toEqual(checkpoint.placements),\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\tif (windowFirst.kind !== 'Plan') throw new Error('Expected a plan');\n+\t\texpect(economyFirst.placements).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-12',\n+\t\t\t\tbalanceId: 'at-risk',\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-13',\n+\t\t\t\tbalanceId: 'at-risk',\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t]);\n+\t\texpect(economyFirst.metrics.supportingPlacements).toBe(0);\n+\t\texpect(economyFirst.preferences[0].satisfied).toBe(0);\n+\t\texpect(economyFirst.remainingBalances[0]).toMatchObject({ id: 'deferred', quantity: 2 });\n+\t\texpect(windowFirst.placements).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-02',\n+\t\t\t\tbalanceId: 'at-risk',\n+\t\t\t\truleIds: ['early'],\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-03',\n+\t\t\t\tbalanceId: 'at-risk',\n+\t\t\t\truleIds: ['early'],\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-12',\n+\t\t\t\tbalanceId: 'deferred',\n+\t\t\t\truleIds: ['holiday'],\n+\t\t\t\tsupporting: true,\n+\t\t\t}),\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-13',\n+\t\t\t\tbalanceId: 'deferred',\n+\t\t\t\truleIds: ['holiday'],\n+\t\t\t\tsupporting: true,\n+\t\t\t}),\n+\t\t]);\n+\t\texpect(windowFirst.metrics.supportingPlacements).toBe(2);\n+\t\texpect(windowFirst.preferences[0].satisfied).toBe(2);\n+\t\texpect(windowFirst.metrics.holidayWeekValue).toBe(3);\n+\t\tif (\n+\t\t\tartifacts?.explanation?.kind !== 'PlanExplanation' ||\n+\t\t\t!artifacts.finalState ||\n+\t\t\t!artifacts.trace\n+\t\t)\n+\t\t\tthrow new Error('Expected matching explanation and trace artifacts');\n+\t\texpect(artifacts.finalState.placements).toEqual(windowFirst.placements);\n+\t\texpect(artifacts.explanation.placements.map(({ placement }) => placement)).toEqual(\n+\t\t\twindowFirst.placements,\n+\t\t);\n+\t\tfor (const placement of artifacts.explanation.placements) {\n+\t\t\tconst contribution = expect.objectContaining({ kind: 'rule', ruleId: 'holiday' });\n+\t\t\tif (placement.supporting) {\n+\t\t\t\texpect(placement.ruleIds).toEqual(['holiday']);\n+\t\t\t\texpect(placement.contributions).toContainEqual(contribution);\n+\t\t\t\texpect(placement.firstDecisiveObjective).toBe('optimization:holiday');\n+\t\t\t} else {\n+\t\t\t\texpect(placement.ruleIds).toEqual(['early']);\n+\t\t\t\texpect(placement.contributions).not.toContainEqual(contribution);\n+\t\t\t}\n+\t\t}\n+\t\tconst replay = {\n+\t\t\tbalances: artifacts.trace.initialState.balances.map((balance) => ({ ...balance })),\n+\t\t\tplacements: new Map(\n+\t\t\t\tartifacts.trace.initialState.placements.map((placement) => [\n+\t\t\t\t\tplacement.date,\n+\t\t\t\t\tplacement,\n+\t\t\t\t]),\n+\t\t\t),\n+\t\t\tearnedActivations: [...artifacts.trace.initialState.earnedActivations],\n+\t\t};\n+\t\tfor (const decision of artifacts.trace.phases.flatMap(({ decisions }) => decisions))\n+\t\t\tapplyReplayDeltas(replay, decision.deltas, artifacts.finalState);\n+\t\texpect(\n+\t\t\t[...replay.placements.values()].sort((a, b) => a.date.localeCompare(b.date)),\n+\t\t).toEqual(windowFirst.placements);\n+\t\texpect(\n+\t\t\tartifacts.trace.phases\n+\t\t\t\t.filter(({ name }) => name === 'preference:early')\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates)),\n+\t\t).toContainEqual(\n+\t\t\texpect.objectContaining({\n+\t\t\t\tstatus: 'chosen',\n+\t\t\t\tplacement: expect.objectContaining({ date: '2026-11-03', ruleIds: ['early'] }),\n+\t\t\t}),\n+\t\t);\n+\t\texpect(updates.length).toBeGreaterThan(0);\n+\t\tfor (const { update, snapshot } of updates) expect(JSON.stringify(update)).toBe(snapshot);\n+\t\tlet cancelled = false;\n+\t\tlet cancelledArtifacts: PlanningArtifacts | undefined;\n+\t\tlet published: PlanOutcome | undefined;\n+\t\tconst partial = await calculatePlanningAsyncInternal(\n+\t\t\t{\n+\t\t\t\t...request,\n+\t\t\t\trules: [holiday, early, economy],\n+\t\t\t\tprogress: (stage: string) => {\n+\t\t\t\t\tif (stage === 'optimization:economy') cancelled = true;\n+\t\t\t\t},\n+\t\t\t\ttraceProgress: (_time: number, update: PlanningTraceUpdate) =>\n+\t\t\t\t\tupdates.push({ update, snapshot: JSON.stringify(update) }),\n+\t\t\t},\n+\t\t\t(checkpoint, state) => {\n+\t\t\t\texpect(state?.placements).toEqual(checkpoint.placements);\n+\t\t\t\tif (checkpoint.lastCompletedStage === 'preference:early') published = checkpoint;\n+\t\t\t},\n+\t\t\t(value) => (cancelledArtifacts = value),\n+\t\t\tundefined,\n+\t\t\tundefined,\n+\t\t\t() => cancelled,\n+\t\t);\n+\t\tif (\n+\t\t\tpartial.kind !== 'PlanningIncomplete' ||\n+\t\t\t!partial.incumbent ||\n+\t\t\tcancelledArtifacts?.explanation?.kind !== 'PlanExplanation'\n+\t\t)\n+\t\t\tthrow new Error('Expected an explained cancelled incumbent');\n+\t\texpect(partial.reasons[0].code).toBe('user-cancelled');\n+\t\texpect(partial.incumbent.placements).toEqual(windowFirst.placements);\n+\t\texpect(partial.incumbent.placements).toEqual(published?.placements);\n+\t\texpect(partial.incumbent.preferences).toMatchObject([{ ruleId: 'early', satisfied: 2 }]);\n+\t\texpect(cancelledArtifacts.finalState?.placements).toEqual(partial.incumbent.placements);\n+\t\texpect(cancelledArtifacts.explanation.placements.map(({ placement }) => placement)).toEqual(\n+\t\t\tpartial.incumbent.placements,\n+\t\t);\n+\t\tfor (const placement of cancelledArtifacts.explanation.placements.slice(0, 2)) {\n+\t\t\texpect(placement.ruleIds).toEqual(['early']);\n+\t\t\texpect(placement.contributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({ kind: 'rule', ruleId: 'early' }),\n+\t\t\t);\n+\t\t}\n+\t\tfor (const { update, snapshot } of updates) expect(JSON.stringify(update)).toBe(snapshot);\n+\t});\n+\n+\tit('keeps established maximum credit when a later earned period masks its local contribution', () => {\n+\t\tlet artifacts: PlanningArtifacts | undefined;\n+\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\thorizon: { start: '2024-05-01', end: '2024-05-11' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-05-03' }],\n+\t\t\t\trules: [\n+\t\t\t\t\t{ ...gain, configuration: { ...gain.configuration, aggregation: 'maximum' } },\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\trewardDays: 2,\n+\t\t\t\t\t\trewardType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\tif (outcome.kind !== 'Plan' || artifacts?.explanation?.kind !== 'PlanExplanation')\n+\t\t\tthrow new Error('Expected an explained plan');\n+\t\texpect(outcome.placements).toMatchObject([\n+\t\t\t{ date: '2024-05-02', ruleIds: ['gain', 'producer'], supporting: false },\n+\t\t\t{ date: '2024-05-03', ruleIds: ['gain'], supporting: false },\n+\t\t\t{ date: '2024-05-10', ruleIds: ['gain'], supporting: true },\n+\t\t]);\n+\t\tfor (const placement of artifacts.explanation.placements.slice(0, 2)) {\n+\t\t\texpect(placement.comparison.delta).toContainEqual(\n+\t\t\t\texpect.objectContaining({ id: 'optimization:gain', value: 0 }),\n+\t\t\t);\n+\t\t\texpect(placement.contributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({ kind: 'rule', ruleId: 'gain' }),\n+\t\t\t);\n+\t\t}\n+\t});\n+\n+\tit('counts reverse deferred reassignment for an edited optimization without explicit calendar credit', () => {\n+\t\tconst request = bundles[0].request;\n+\t\tconst forgoAtRisk: OptimizationPlanningRule = {\n+\t\t\tid: 'forgo',\n+\t\t\ttype: 'optimization',\n+\t\t\tconfiguration: { ...OPTIMIZATION_PRESETS.unplacedAtRisk, direction: 'maximize' },\n+\t\t};\n+\t\tconst outcome = plan({\n+\t\t\t...request,\n+\t\t\tbalances: [\n+\t\t\t\t{ ...request.balances[0], id: 'at-risk', expiryDate: '2026-11-13' },\n+\t\t\t\t{ ...request.balances[0], id: 'deferred' },\n+\t\t\t],\n+\t\t\trules: [bundles[0].rule, forgoAtRisk, economy],\n+\t\t});\n+\t\texpect(\n+\t\t\toutcome.placements.map(({ balanceId, supporting }) => ({ balanceId, supporting })),\n+\t\t).toEqual([\n+\t\t\t{ balanceId: 'deferred', supporting: true },\n+\t\t\t{ balanceId: 'deferred', supporting: true },\n+\t\t]);\n+\t\texpect(outcome.metrics).toMatchObject({\n+\t\t\tholidayWeekValue: 3,\n+\t\t\tunplacedAtRisk: 2,\n+\t\t\tsupportingPlacements: 2,\n+\t\t});\n+\t});\n+\n+\tit('records the calendar credit and classification change in the original calendar-rule phase', () => {\n+\t\tlet artifacts: PlanningArtifacts | undefined;\n+\t\tcalculatePlanningInternal(\n+\t\t\t{ ...weekend, rules: [gain, economy, requested] },\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\tconst changes = artifacts?.trace?.phases\n+\t\t\t.find(({ name }) => name === 'preference:requested')\n+\t\t\t?.decisions.flatMap(({ deltas }) => deltas);\n+\t\texpect(changes).toContainEqual(\n+\t\t\texpect.objectContaining({\n+\t\t\t\tkind: 'placement-updated',\n+\t\t\t\tpreviousPlacement: expect.objectContaining({ supporting: true }),\n+\t\t\t\tplacement: expect.objectContaining({\n+\t\t\t\t\truleIds: ['gain', 'requested'],\n+\t\t\t\t\tsupporting: false,\n+\t\t\t\t}),\n+\t\t\t}),\n+\t\t);\n+\t});\n+\n+\tit('keeps earned support chronological and preserves the captured economy rule in explanations and counterfactuals', async () => {\n+\t\tvi.stubGlobal('window', undefined);\n+\t\ttry {\n+\t\t\tconst capturedEconomy = structuredClone(economy);\n+\t\t\tconst request: PlanningRequest = {\n+\t\t\t\thorizon: { start: '2024-04-29', end: '2024-05-08' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2025-01-01' }],\n+\t\t\t\trules: [\n+\t\t\t\t\tgain,\n+\t\t\t\t\tcapturedEconomy,\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\trewardType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t};\n+\t\t\tconst calculation = createPlanningCalculation(request);\n+\t\t\tcapturedEconomy.configuration.conditions = [];\n+\t\t\tcapturedEconomy.name = 'Changed later';\n+\t\t\tconst outcome = await calculation.outcome;\n+\t\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a plan');\n+\t\t\texpect(outcome.placements).toEqual([\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tdate: '2024-05-02',\n+\t\t\t\t\truleIds: ['producer'],\n+\t\t\t\t\tsupporting: false,\n+\t\t\t\t}),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tdate: '2024-05-06',\n+\t\t\t\t\tbalanceId: 'earned:producer:2024-05-01',\n+\t\t\t\t\tsupporting: true,\n+\t\t\t\t}),\n+\t\t\t]);\n+\t\t\texpect(outcome.metrics).toMatchObject({\n+\t\t\t\tnonWorkingDayGain: 3,\n+\t\t\t\tsupportingPlacements: 1,\n+\t\t\t});\n+\t\t\texpect(calculation.snapshot.rules[1]).toMatchObject({\n+\t\t\t\tname: 'Économiser les jours d’appoint',\n+\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t});\n+\t\t\tconst explanation = await calculation.explanation;\n+\t\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\t\tconst supporting = explanation.placements.find(({ supporting }) => supporting)!;\n+\t\t\texpect(supporting.firstDecisiveObjective).toBe('optimization:gain');\n+\t\t\texpect(supporting.objectiveVector.objectives.map(({ id }) => id)).toEqual([\n+\t\t\t\t'obligation-validity',\n+\t\t\t\t'optimization:gain',\n+\t\t\t\t'optimization:economy',\n+\t\t\t\t'balance-expiry',\n+\t\t\t\t'placement-date',\n+\t\t\t]);\n+\t\t\texpect(supporting.contributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({ kind: 'supporting' }),\n+\t\t\t);\n+\t\t\tconst trace = await calculation.trace;\n+\t\t\texpect(trace?.phases.map(({ name }) => name)).toEqual([\n+\t\t\t\t'validation',\n+\t\t\t\t'obligations',\n+\t\t\t\t'optimization:gain',\n+\t\t\t\t'optimization:economy',\n+\t\t\t\t'expiry',\n+\t\t\t\t'dates',\n+\t\t\t]);\n+\t\t\tconst analysis = await calculation.analyzeCounterfactual(outcome.placements[1]);\n+\t\t\tif (analysis.kind !== 'Counterfactual') throw new Error('Expected a counterfactual');\n+\t\t\texpect(analysis.results.find(({ date }) => date === '2024-05-03')).toMatchObject({\n+\t\t\t\tstatus: 'ineligible',\n+\t\t\t\treason: { code: 'unavailable' },\n+\t\t\t});\n+\t\t\texpect(\n+\t\t\t\tanalysis.results.find(({ date }) => date === '2024-05-06')?.comparison?.after\n+\t\t\t\t\t.objectives,\n+\t\t\t).toContainEqual(expect.objectContaining({ id: 'optimization:economy', value: 1 }));\n+\t\t\texpect(\n+\t\t\t\tanalysis.results.find(({ date }) => date === '2024-05-07')?.comparison?.after\n+\t\t\t\t\t.objectives,\n+\t\t\t).toContainEqual(expect.objectContaining({ id: 'optimization:economy', value: 1 }));\n+\t\t\texpect(outcome.placements[1]).toMatchObject({ date: '2024-05-06', supporting: true });\n+\t\t} finally {\n+\t\t\tvi.unstubAllGlobals();\n+\t\t}\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/services/leave-planner-supporting-placements.spec.ts", "project_id": 35, "relative_order": 24, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,465 @@\n+import { vi } from 'vitest';\n+import {\n+\tcalculatePlanningInternal,\n+\ttype OptimizationPlanningRule,\n+\ttype PlanOutcome,\n+\ttype PlanningRequest,\n+} from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+import { createPlanningCalculation } from './leave-planner.service';\n+\n+const deficit: OptimizationPlanningRule = {\n+\tid: 'deficit',\n+\tname: 'Internal work-sequence deficit',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+};\n+const longest: OptimizationPlanningRule = {\n+\tid: 'longest',\n+\tname: 'Longest work sequence',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.longestWorkSequence,\n+};\n+const gap: PlanningRequest = {\n+\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-02-01' }],\n+\tdeclaredDays: ['2024-01-08', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\trules: [deficit],\n+};\n+\n+function plan(request: PlanningRequest): PlanOutcome {\n+\tconst outcome = calculatePlanningInternal(request);\n+\tif (outcome.kind !== 'Plan') throw new Error(`Expected a plan, got ${outcome.kind}`);\n+\treturn outcome;\n+}\n+\n+describe('composed work-sequence preferences', () => {\n+\tbeforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n+\tafterEach(() => vi.useRealTimers());\n+\n+\tit('fills a complete internal sequence despite the worse deficit of partial additions', () => {\n+\t\tconst outcome = plan(gap);\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual([\n+\t\t\t'2024-01-09',\n+\t\t\t'2024-01-10',\n+\t\t\t'2024-01-11',\n+\t\t]);\n+\t\texpect(outcome.placements.every(({ supporting }) => supporting)).toBe(true);\n+\t\texpect(outcome.declaredDays).toEqual(gap.declaredDays);\n+\t\texpect(outcome.metrics.shortSequenceDeficit).toBe(0);\n+\t\texpect(outcome.remainingBalances).toEqual([]);\n+\t});\n+\n+\tit('splits tied longest sequences together when neither single addition improves the maximum', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...gap,\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: [{ date: '2024-01-10', type: 'other' }],\n+\t\t\trules: [longest],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual(['2024-01-08', '2024-01-11']);\n+\t\texpect(outcome.metrics.longestWorkSequence).toBe(1);\n+\t});\n+\n+\tit('leaves a three-day internal sequence intact at threshold three instead of filling it at five', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...gap,\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\t...deficit,\n+\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t\tthresholdDays: 3,\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements).toEqual([]);\n+\t\texpect(outcome.remainingBalances[0].quantity).toBe(3);\n+\t\texpect(outcome.metrics.shortSequenceDeficit).toBe(2);\n+\t});\n+\n+\tit('counts selected internal sequences even when their measured deficit is zero', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...gap,\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\t...deficit,\n+\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t\tthresholdDays: 3,\n+\t\t\t\t\t\taggregation: 'count',\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual([\n+\t\t\t'2024-01-09',\n+\t\t\t'2024-01-10',\n+\t\t\t'2024-01-11',\n+\t\t]);\n+\t});\n+\n+\tit('evaluates two parameterized configurations separately and follows their order', () => {\n+\t\tconst maximizeThree: OptimizationPlanningRule = {\n+\t\t\t...deficit,\n+\t\t\tid: 'three',\n+\t\t\tconfiguration: {\n+\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\tthresholdDays: 3,\n+\t\t\t\tdirection: 'maximize',\n+\t\t\t},\n+\t\t};\n+\t\tconst fiveFirst = plan({ ...gap, rules: [deficit, maximizeThree] });\n+\t\tconst threeFirst = plan({ ...gap, rules: [maximizeThree, deficit] });\n+\t\texpect(fiveFirst.placements.map(({ date }) => date)).toEqual([\n+\t\t\t'2024-01-09',\n+\t\t\t'2024-01-10',\n+\t\t\t'2024-01-11',\n+\t\t]);\n+\t\texpect(threeFirst.placements.map(({ date }) => date)).toEqual(['2024-01-10']);\n+\t\texpect(threeFirst.metrics.shortSequenceDeficit).toBe(8);\n+\t});\n+\n+\tit('obeys the order between the longest-sequence preference and a personal window', () => {\n+\t\tconst personal = {\n+\t\t\tid: 'personal',\n+\t\t\ttype: 'time_window' as const,\n+\t\t\tstartDate: '2024-01-08',\n+\t\t\tendDate: '2024-01-08',\n+\t\t\tplaceDays: 1,\n+\t\t\tplaceType: 'cp',\n+\t\t};\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-20' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2024-02-01' }],\n+\t\t\trules: [],\n+\t\t};\n+\t\tconst longestFirst = plan({ ...request, rules: [longest, personal] });\n+\t\tconst personalFirst = plan({ ...request, rules: [personal, longest] });\n+\t\texpect(longestFirst.placements.map(({ date }) => date)).toEqual(['2024-01-12']);\n+\t\texpect(longestFirst.metrics.longestWorkSequence).toBe(5);\n+\t\texpect(personalFirst.placements.map(({ date }) => date)).toEqual(['2024-01-08']);\n+\t\texpect(personalFirst.metrics.longestWorkSequence).toBe(9);\n+\t});\n+\n+\tit('keeps obligations and earlier preferences when a complete gap would consume their balance', () => {\n+\t\tconst personal = {\n+\t\t\tid: 'personal',\n+\t\t\ttype: 'time_window' as const,\n+\t\t\tstartDate: '2024-01-15',\n+\t\t\tendDate: '2024-01-15',\n+\t\t\tplaceDays: 1,\n+\t\t\tplaceType: 'cp',\n+\t\t};\n+\t\tconst request = { ...gap, horizon: { start: '2024-01-08', end: '2024-01-16' } };\n+\t\texpect(\n+\t\t\tplan({ ...request, rules: [deficit, personal] }).placements.map(({ date }) => date),\n+\t\t).toEqual(['2024-01-09', '2024-01-10', '2024-01-11']);\n+\t\tfor (const force of ['preference', 'obligation'] as const) {\n+\t\t\tconst outcome = plan({ ...request, rules: [{ ...personal, force }, deficit] });\n+\t\t\texpect(outcome.placements.map(({ date }) => date)).toEqual(['2024-01-15']);\n+\t\t\texpect(outcome.metrics.shortSequenceDeficit).toBe(2);\n+\t\t}\n+\t});\n+\n+\tit('uses only eligible balance dates when completing the entire gap', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...gap,\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'early', type: 'rtt', quantity: 1, expiryDate: '2024-01-09' },\n+\t\t\t\t{\n+\t\t\t\t\tid: 'late',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 2,\n+\t\t\t\t\tavailableFrom: '2024-01-10',\n+\t\t\t\t\texpiryDate: '2024-02-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date, balanceId }) => ({ date, balanceId }))).toEqual([\n+\t\t\t{ date: '2024-01-09', balanceId: 'early' },\n+\t\t\t{ date: '2024-01-10', balanceId: 'late' },\n+\t\t\t{ date: '2024-01-11', balanceId: 'late' },\n+\t\t]);\n+\t\texpect(outcome.placements.map(({ supporting }) => supporting)).toEqual([false, true, true]);\n+\t\tconst unavailable = plan({\n+\t\t\t...gap,\n+\t\t\tbalances: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'late',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 3,\n+\t\t\t\t\tavailableFrom: '2024-01-10',\n+\t\t\t\t\texpiryDate: '2024-02-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(unavailable.placements).toEqual([]);\n+\t});\n+\n+\tit('adds no neutral placement when the budget cannot split all tied maxima', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...gap,\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: [{ date: '2024-01-10', type: 'other' }],\n+\t\t\trules: [longest],\n+\t\t});\n+\t\texpect(outcome.placements).toEqual([]);\n+\t\texpect(outcome.metrics.longestWorkSequence).toBe(2);\n+\t});\n+\n+\tit('splits tied sequences at eligible dates when their centers are unavailable', () => {\n+\t\tconst outcome = plan({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-19' },\n+\t\t\tdeclaredDays: [{ date: '2024-01-12', type: 'other' }],\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'early', type: 'cp', quantity: 1, expiryDate: '2024-01-08' },\n+\t\t\t\t{\n+\t\t\t\t\tid: 'late',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2024-01-18',\n+\t\t\t\t\texpiryDate: '2024-02-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t\trules: [longest],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual(['2024-01-08', '2024-01-18']);\n+\t\texpect(outcome.metrics.longestWorkSequence).toBe(3);\n+\t});\n+\n+\tit('coordinates scarce balances when individually eligible centers cannot be funded together', () => {\n+\t\tconst outcome = plan({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-19' },\n+\t\t\tdeclaredDays: [{ date: '2024-01-12', type: 'other' }],\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'early', type: 'cp', quantity: 1, expiryDate: '2024-01-08' },\n+\t\t\t\t{ id: 'flexible', type: 'cp', quantity: 1, expiryDate: '2024-02-01' },\n+\t\t\t],\n+\t\t\trules: [longest],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual(['2024-01-08', '2024-01-15']);\n+\t\texpect(outcome.metrics.longestWorkSequence).toBe(3);\n+\t});\n+\n+\tit('eliminates tied maximum deficits as one complete gap bundle', () => {\n+\t\tconst outcome = plan({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-17' },\n+\t\t\tdeclaredDays: ['2024-01-08', '2024-01-11', '2024-01-16'].map((date) => ({\n+\t\t\t\tdate,\n+\t\t\t\ttype: 'other',\n+\t\t\t})),\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 4, expiryDate: '2024-02-01' }],\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\t...deficit,\n+\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t\taggregation: 'maximum',\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual([\n+\t\t\t'2024-01-09',\n+\t\t\t'2024-01-10',\n+\t\t\t'2024-01-12',\n+\t\t\t'2024-01-15',\n+\t\t]);\n+\t\texpect(outcome.metrics.shortSequenceDeficit).toBe(0);\n+\t});\n+\n+\tit('includes both horizon edges in the maximum while excluding them from the deficit', () => {\n+\t\tconst outcome = plan({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-25' },\n+\t\t\tbalances: [],\n+\t\t\tdeclaredDays: ['2024-01-11', '2024-01-15', '2024-01-22'].map((date) => ({\n+\t\t\t\tdate,\n+\t\t\t\ttype: 'other',\n+\t\t\t})),\n+\t\t\trules: [longest, deficit],\n+\t\t});\n+\t\texpect(outcome.metrics).toMatchObject({ longestWorkSequence: 4, shortSequenceDeficit: 5 });\n+\t});\n+\n+\tit.each([\n+\t\t{ horizon: { start: '2024-05-06', end: '2024-05-15' }, dates: [], longest: 5 },\n+\t\t{\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-11' },\n+\t\t\tdates: ['2024-01-08', '2024-01-09', '2024-01-10'],\n+\t\t\tlongest: 0,\n+\t\t},\n+\t\t{ horizon: { start: '2024-01-06', end: '2024-01-08' }, dates: [], longest: 0 },\n+\t\t{\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tdates: ['2024-01-09', '2024-01-10'],\n+\t\t\tlongest: 2,\n+\t\t},\n+\t])(\n+\t\t'keeps holiday/weekend continuity and zero for empty sequences: $horizon.start',\n+\t\t({ horizon, dates, longest: expected }) => {\n+\t\t\tconst outcome = plan({\n+\t\t\t\thorizon,\n+\t\t\t\tbalances: [],\n+\t\t\t\tdeclaredDays: dates.map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [longest, deficit],\n+\t\t\t});\n+\t\t\texpect(outcome.metrics.longestWorkSequence).toBe(expected);\n+\t\t\texpect(outcome.metrics.shortSequenceDeficit).toBe(0);\n+\t\t},\n+\t);\n+\n+\tit('disabling work-sequence rules removes their influence even with deferred balances', () => {\n+\t\tconst absent = plan({ ...gap, rules: [] });\n+\t\tconst disabled = plan({\n+\t\t\t...gap,\n+\t\t\trules: [\n+\t\t\t\t{ ...deficit, enabled: false },\n+\t\t\t\t{ ...longest, enabled: false },\n+\t\t\t],\n+\t\t});\n+\t\texpect(disabled).toEqual(absent);\n+\t\tconst personal = {\n+\t\t\tid: 'personal',\n+\t\t\ttype: 'time_window' as const,\n+\t\t\tstartDate: '2024-01-09',\n+\t\t\tendDate: '2024-01-09',\n+\t\t\tplaceDays: 1,\n+\t\t\tplaceType: 'cp',\n+\t\t};\n+\t\tconst requested = plan({ ...gap, rules: [{ ...deficit, enabled: false }, personal] });\n+\t\texpect(requested.placements.map(({ date }) => date)).toEqual(['2024-01-09']);\n+\t\texpect(requested.metrics.shortSequenceDeficit).toBe(3);\n+\t});\n+\n+\tit('finishes a rejected tied-sequence bundle without retrying equivalent balance allocations', () => {\n+\t\tconst outcome = plan({\n+\t\t\tdeadlineMs: 1500,\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-02-10' },\n+\t\t\tdeclaredDays: [\n+\t\t\t\t'2024-01-08',\n+\t\t\t\t'2024-01-10',\n+\t\t\t\t'2024-01-12',\n+\t\t\t\t'2024-01-16',\n+\t\t\t\t'2024-01-18',\n+\t\t\t\t'2024-01-22',\n+\t\t\t\t'2024-01-24',\n+\t\t\t\t'2024-01-26',\n+\t\t\t\t'2024-01-30',\n+\t\t\t\t'2024-02-01',\n+\t\t\t\t'2024-02-05',\n+\t\t\t\t'2024-02-07',\n+\t\t\t\t'2024-02-09',\n+\t\t\t].map((date) => ({ date, type: 'other' })),\n+\t\t\tbalances: ['cp', 'rtt', 'other'].map((type) => ({\n+\t\t\t\tid: type,\n+\t\t\t\ttype,\n+\t\t\t\tquantity: 12,\n+\t\t\t\texpiryDate: '2024-03-01',\n+\t\t\t})),\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'support',\n+\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t\t},\n+\t\t\t\tlongest,\n+\t\t\t\t{\n+\t\t\t\t\tid: 'typed',\n+\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\tstartDate: '2024-01-09',\n+\t\t\t\t\tendDate: '2024-01-09',\n+\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual(['2024-01-09']);\n+\t\texpect(outcome.metrics.longestWorkSequence).toBe(1);\n+\t\texpect(outcome.metrics.supportingPlacements).toBe(0);\n+\t});\n+\n+\tit.each([0, -1, 1.5, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1])(\n+\t\t'rejects an invalid preference threshold %s at the planning boundary',\n+\t\t(thresholdDays) => {\n+\t\t\tconst outcome = calculatePlanningInternal({\n+\t\t\t\t...gap,\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\t...deficit,\n+\t\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t\t\tthresholdDays,\n+\t\t\t\t\t\t},\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t});\n+\t\t\texpect(outcome).toMatchObject({\n+\t\t\t\tkind: 'InvalidInput',\n+\t\t\t\treasons: [\n+\t\t\t\t\texpect.objectContaining({\n+\t\t\t\t\t\tcode: 'invalid-optimization-configuration',\n+\t\t\t\t\t\truleIds: ['deficit'],\n+\t\t\t\t\t}),\n+\t\t\t\t],\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit('captures distinct threshold values in explanations, atomic trace and counterfactual comparisons', async () => {\n+\t\tvi.stubGlobal('window', undefined);\n+\t\ttry {\n+\t\t\tconst five = structuredClone(deficit);\n+\t\t\tconst three: OptimizationPlanningRule = {\n+\t\t\t\t...deficit,\n+\t\t\t\tid: 'three',\n+\t\t\t\tconfiguration: { ...OPTIMIZATION_PRESETS.shortSequenceDeficit, thresholdDays: 3 },\n+\t\t\t};\n+\t\t\tconst calculation = createPlanningCalculation({ ...gap, rules: [three, five] });\n+\t\t\tif (five.configuration.measure !== 'work-sequence-deficit')\n+\t\t\t\tthrow new Error('Expected deficit');\n+\t\t\tfive.configuration.thresholdDays = 1;\n+\t\t\tconst outcome = await calculation.outcome;\n+\t\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a plan');\n+\t\t\texpect(outcome.placements).toHaveLength(3);\n+\t\t\texpect(\n+\t\t\t\tcalculation.snapshot.rules.map((rule) =>\n+\t\t\t\t\t'configuration' in rule ? rule.configuration : undefined,\n+\t\t\t\t),\n+\t\t\t).toMatchObject([{ thresholdDays: 3 }, { thresholdDays: 5 }]);\n+\t\t\tconst explanation = await calculation.explanation;\n+\t\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\t\texpect(\n+\t\t\t\texplanation.placements[0].comparison.before.objectives\n+\t\t\t\t\t.filter(({ id }) => id.startsWith('optimization:'))\n+\t\t\t\t\t.map(({ value }) => value),\n+\t\t\t).toEqual([2, 4]);\n+\t\t\tconst trace = await calculation.trace;\n+\t\t\tconst chosen = trace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t.find(\n+\t\t\t\t\t(candidate) => candidate.status === 'chosen' && candidate.dates?.length === 3,\n+\t\t\t\t);\n+\t\t\texpect(\n+\t\t\t\tchosen?.comparison?.before.objectives\n+\t\t\t\t\t.filter(({ id }) => id.startsWith('optimization:'))\n+\t\t\t\t\t.map(({ value }) => value),\n+\t\t\t).toEqual([0, 2]);\n+\t\t\texpect(chosen?.comparison?.firstDecisiveObjective).toBe('optimization:deficit');\n+\t\t\tconst counterfactual = await calculation.analyzeCounterfactual(outcome.placements[0]);\n+\t\t\tif (counterfactual.kind !== 'Counterfactual')\n+\t\t\t\tthrow new Error('Expected a counterfactual');\n+\t\t\texpect(\n+\t\t\t\tcounterfactual.baseline.objectives\n+\t\t\t\t\t.filter(({ id }) => id.startsWith('optimization:'))\n+\t\t\t\t\t.map(({ id, value }) => ({ id, value })),\n+\t\t\t).toEqual([\n+\t\t\t\t{ id: 'optimization:three', value: 2 },\n+\t\t\t\t{ id: 'optimization:deficit', value: 4 },\n+\t\t\t]);\n+\t\t} finally {\n+\t\t\tvi.unstubAllGlobals();\n+\t\t}\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/services/leave-planner-work-sequences.spec.ts", "project_id": 35, "relative_order": 25, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -5,6 +5,16 @@ import {\n \tisWorkingPlanningDate,\n } from './declared-non-working-days';\n import { addPlanningYears, isPlanningDate, planningDateInParis } from './planning-date';\n+import {\n+\tcompareObjectiveLists,\n+\tcompareObjectiveValues,\n+\tevaluateOptimization,\n+\tfirstDifferentObjective,\n+\tOPTIMIZATION_PRESETS,\n+\tvalidateOptimizationConfiguration,\n+\ttype OptimizationConfiguration,\n+\ttype OptimizationObservations,\n+} from './planning-objectives';\n export type { DeclaredNonWorkingDay } from './declared-non-working-days';\n \n /** Date-only values are serialized as YYYY-MM-DD at the planning boundary. */\n@@ -55,7 +65,16 @@ export interface IfThenPlanningRule {\n \trewardType?: LeaveType | string;\n }\n \n-export type PlanningRule = TimeWindowPlanningRule | IfThenPlanningRule;\n+export interface OptimizationPlanningRule {\n+\tid: string;\n+\tname?: string;\n+\ttype: 'optimization';\n+\tenabled?: boolean;\n+\tforce?: 'preference';\n+\tconfiguration: OptimizationConfiguration;\n+}\n+\n+export type PlanningRule = TimeWindowPlanningRule | IfThenPlanningRule | OptimizationPlanningRule;\n \n export interface PlanningRequest {\n \thorizon: PlanningHorizon;\n@@ -154,6 +173,7 @@ export type PlanningObjectiveId =\n \t| 'obligation-validity'\n \t| 'unplaced-at-risk'\n \t| `preference:${string}`\n+\t| `optimization:${string}`\n \t| 'holiday-week-value'\n \t| 'non-working-day-gain'\n \t| 'longest-work-sequence'\n@@ -509,12 +529,15 @@ interface NormalizedBalance {\n \tsourceRuleId?: string;\n }\n \n-interface NormalizedRule {\n+interface NormalizedBaseRule {\n \tid: string;\n \tname: string;\n-\ttype: 'time_window' | 'if_then';\n \tenabled: boolean;\n \tforce: RuleForce;\n+}\n+\n+interface NormalizedCalendarRule extends NormalizedBaseRule {\n+\ttype: 'time_window' | 'if_then';\n \tplaceDays: number;\n \tplaceType: LeaveSelector;\n \tstartDate?: string;\n@@ -525,6 +548,14 @@ interface NormalizedRule {\n \trewardType?: LeaveType;\n }\n \n+interface NormalizedOptimizationRule extends NormalizedBaseRule {\n+\ttype: 'optimization';\n+\tforce: 'preference';\n+\tconfiguration: OptimizationConfiguration;\n+}\n+\n+type NormalizedRule = NormalizedCalendarRule | NormalizedOptimizationRule;\n+\n interface InternalBalance extends NormalizedBalance {\n \tremaining: number;\n }\n@@ -593,10 +624,11 @@ interface RuntimeRecord {\n \tplacement?: unknown;\n \trewardDays?: unknown;\n \trewardType?: unknown;\n+\tconfiguration?: unknown;\n }\n \n interface Requirement {\n-\trule: NormalizedRule;\n+\trule: NormalizedCalendarRule;\n \trequiredPlacements: number;\n \tanchor: string;\n \tindex: number;\n@@ -607,8 +639,26 @@ interface Requirement {\n }\n \n const obligationRequirementCache = new WeakMap();\n+const occurrenceCache = new WeakMap>();\n+const calendarPatternCache = new WeakMap>();\n const preferencePatternCache = new WeakMap>();\n const declaredWindowCache = new WeakMap>();\n+type CalendarOptimizationObservations = Pick<\n+\tOptimizationObservations,\n+\t'publicHolidayWeeks' | 'timeOffPeriods' | 'workSequences'\n+>;\n+const calendarObservationCache = new WeakMap<\n+\tSearchContext,\n+\tMap\n+>();\n+interface CalendarPeriod {\n+\tstart: string;\n+\tend: string;\n+\tduration: number;\n+\tnonWorkingDates: readonly string[];\n+\tdeclaredDates: readonly string[];\n+}\n+const calendarPeriodCache = new WeakMap>();\n \n type MutableTraceCandidate = PlanningTraceCandidate & { candidates?: never };\n type MutableTraceDecision = {\n@@ -638,15 +688,37 @@ class TraceRecorder {\n \tprivate readonly nonWorkingDates: readonly Readonly<{ date: string; reason: PlanningReason }>[];\n \tprivate phase: MutableTracePhase | undefined;\n \tprivate sequence = 0;\n-\tprivate readonly evaluationLocations = new WeakMap<\n-\t\tMutableTraceCandidate,\n-\t\t{ phase: MutableTracePhase; decision: MutableTraceDecision; index: number }\n-\t>();\n+\n \tprivate pendingOperations: PlanningTraceOperation[] = [];\n \tprivate readonly pendingCandidateOperations = new Map<\n \t\tPlanningTraceCandidate,\n \t\tExtract\n \t>();\n+\t// Keep repeated scalar evidence shared while candidate identities remain independent.\n+\tprivate readonly objectiveValues = new Map();\n+\tprivate readonly objectiveVectors = new WeakMap<\n+\t\tPlanningObjectiveVector,\n+\t\tPlanningObjectiveVector\n+\t>();\n+\tprivate readonly comparisonDeltas = new Map();\n+\tprivate readonly repeatedVectors = new Map();\n+\tprivate repeatedVectorCount = 0;\n+\tprivate readonly tieValues = new Map();\n+\tprivate readonly placements = new Map();\n+\tprivate readonly dates = new Map();\n+\tprivate readonly identifiers = new Map();\n+\tprivate readonly comparisons = new WeakMap<\n+\t\tPlanningObjectiveVector,\n+\t\tWeakMap\n+\t>();\n+\tprivate readonly technicalValues = new Map<\n+\t\tstring,\n+\t\tNonNullable\n+\t>();\n+\tprivate readonly technicalEntries = new Map<\n+\t\tstring,\n+\t\tNonNullable[number]\n+\t>();\n \tprivate initialStateSent = false;\n \tprivate previousPlacements = new Map();\n \tprivate previousEarned = new Set();\n@@ -675,6 +747,206 @@ class TraceRecorder {\n \t\t);\n \t}\n \n+\tprivate capturePlacement(placement: LeavePlacement | undefined): LeavePlacement | undefined {\n+\t\tif (!placement || Object.isFrozen(placement)) return placement;\n+\t\tconst key = JSON.stringify(placement);\n+\t\tconst shared = this.placements.get(key);\n+\t\tif (shared) return shared;\n+\t\tconst ruleIds = [...placement.ruleIds];\n+\t\tObject.freeze(ruleIds);\n+\t\tconst snapshot = Object.freeze({ ...placement, ruleIds });\n+\t\tif (this.placements.size < 8192) this.placements.set(key, snapshot);\n+\t\treturn snapshot;\n+\t}\n+\n+\tprivate captureDates(dates: readonly string[] | undefined): readonly string[] | undefined {\n+\t\tif (!dates || Object.isFrozen(dates)) return dates;\n+\t\tconst key = JSON.stringify(dates);\n+\t\tconst shared = this.dates.get(key);\n+\t\tif (shared) return shared;\n+\t\tconst snapshot = Object.freeze([...dates]);\n+\t\tif (this.dates.size < 16384) this.dates.set(key, snapshot);\n+\t\treturn snapshot;\n+\t}\n+\n+\tprivate captureIdentifier(identifier: string): string {\n+\t\tconst shared = this.identifiers.get(identifier);\n+\t\tif (shared !== undefined) return shared;\n+\t\tif (this.identifiers.size < 4096) this.identifiers.set(identifier, identifier);\n+\t\treturn identifier;\n+\t}\n+\n+\tprivate captureTieValue(value: number | string): number | string {\n+\t\tif (typeof value !== 'string') return value;\n+\t\tconst shared = this.tieValues.get(value);\n+\t\tif (shared !== undefined) {\n+\t\t\tthis.tieValues.delete(value);\n+\t\t\tthis.tieValues.set(shared, shared);\n+\t\t\treturn shared;\n+\t\t}\n+\t\t// Bound the index; eviction changes only sharing, never the recorded scalar value.\n+\t\tif (this.tieValues.size >= 8192) this.tieValues.delete(this.tieValues.keys().next().value!);\n+\t\tthis.tieValues.set(value, value);\n+\t\treturn value;\n+\t}\n+\n+\tprivate captureVector(vector: PlanningObjectiveVector): PlanningObjectiveVector {\n+\t\tconst captured = this.objectiveVectors.get(vector);\n+\t\tif (captured) return captured;\n+\t\t// Use a retained tie value as the index rather than duplicating complete vectors as JSON keys.\n+\t\tconst dateValue = vector.objectives.find(({ id }) => id === 'placement-date')?.value;\n+\t\tconst key = typeof dateValue === 'string' ? dateValue : undefined;\n+\t\tconst bucket = key === undefined ? undefined : this.repeatedVectors.get(key);\n+\t\tconst shared = bucket?.find(\n+\t\t\t(candidate) =>\n+\t\t\t\tcandidate.objectives.length === vector.objectives.length &&\n+\t\t\t\tcandidate.objectives.every((objective, index) => {\n+\t\t\t\t\tconst other = vector.objectives[index];\n+\t\t\t\t\treturn (\n+\t\t\t\t\t\tobjective.id === other.id &&\n+\t\t\t\t\t\tobjective.direction === other.direction &&\n+\t\t\t\t\t\tobjective.label === other.label &&\n+\t\t\t\t\t\tObject.hasOwn(objective, 'label') === Object.hasOwn(other, 'label') &&\n+\t\t\t\t\t\tObject.is(objective.value, other.value)\n+\t\t\t\t\t);\n+\t\t\t\t}),\n+\t\t);\n+\t\tif (shared) {\n+\t\t\tconst recordedKey = shared.objectives.find(({ id }) => id === 'placement-date')?.value;\n+\t\t\tif (typeof recordedKey === 'string') {\n+\t\t\t\tthis.repeatedVectors.delete(recordedKey);\n+\t\t\t\tthis.repeatedVectors.set(recordedKey, bucket!);\n+\t\t\t}\n+\t\t\tthis.objectiveVectors.set(vector, shared);\n+\t\t\treturn shared;\n+\t\t}\n+\t\tconst objectives = vector.objectives.map((objective) => {\n+\t\t\tconst shareable =\n+\t\t\t\t(objective.id === 'balance-expiry' && typeof objective.value === 'string') ||\n+\t\t\t\t(typeof objective.value === 'number' &&\n+\t\t\t\t\tNumber.isFinite(objective.value) &&\n+\t\t\t\t\t!Object.is(objective.value, -0));\n+\t\t\tif (!shareable)\n+\t\t\t\treturn Object.freeze({\n+\t\t\t\t\t...objective,\n+\t\t\t\t\tvalue: this.captureTieValue(objective.value),\n+\t\t\t\t});\n+\t\t\tconst key = JSON.stringify(objective);\n+\t\t\tconst shared = this.objectiveValues.get(key);\n+\t\t\tif (shared) return shared;\n+\t\t\tconst value = Object.freeze({\n+\t\t\t\t...objective,\n+\t\t\t\tvalue: this.captureTieValue(objective.value),\n+\t\t\t});\n+\t\t\tif (this.objectiveValues.size < 4096) this.objectiveValues.set(key, value);\n+\t\t\treturn value;\n+\t\t});\n+\t\tconst result = Object.freeze({ objectives: Object.freeze(objectives) });\n+\t\tthis.objectiveVectors.set(vector, result);\n+\t\tconst recordedKey = result.objectives.find(({ id }) => id === 'placement-date')?.value;\n+\t\tif (typeof recordedKey === 'string') {\n+\t\t\tif (this.repeatedVectorCount >= 65536) {\n+\t\t\t\tconst oldest = this.repeatedVectors.keys().next().value!;\n+\t\t\t\tthis.repeatedVectorCount -= this.repeatedVectors.get(oldest)!.length;\n+\t\t\t\tthis.repeatedVectors.delete(oldest);\n+\t\t\t}\n+\t\t\tconst retained = this.repeatedVectors.get(recordedKey) ?? [];\n+\t\t\tretained.push(result);\n+\t\t\tthis.repeatedVectors.delete(recordedKey);\n+\t\t\tthis.repeatedVectors.set(recordedKey, retained);\n+\t\t\tthis.repeatedVectorCount++;\n+\t\t}\n+\t\treturn result;\n+\t}\n+\n+\tprivate captureComparison(\n+\t\tcomparison: PlanningObjectiveComparison,\n+\t): PlanningObjectiveComparison {\n+\t\tconst before = this.captureVector(comparison.before);\n+\t\tconst after = this.captureVector(comparison.after);\n+\t\tlet alternatives = this.comparisons.get(before);\n+\t\tconst shared = alternatives?.get(after);\n+\t\tif (shared) return shared;\n+\t\tif (!alternatives) {\n+\t\t\talternatives = new WeakMap();\n+\t\t\tthis.comparisons.set(before, alternatives);\n+\t\t}\n+\t\t// Every recorded comparison comes from objectiveComparison of these complete vectors.\n+\t\tconst result = Object.freeze({\n+\t\t\t...comparison,\n+\t\t\tbefore,\n+\t\t\tafter,\n+\t\t\tfirstDecisiveObjective: after.objectives.find(\n+\t\t\t\t({ id }) => id === comparison.firstDecisiveObjective,\n+\t\t\t)?.id,\n+\t\t\tdelta: this.captureDeltas(comparison.delta),\n+\t\t});\n+\t\talternatives.set(after, result);\n+\t\treturn result;\n+\t}\n+\n+\tprivate captureDeltas(\n+\t\tdeltas: readonly PlanningObjectiveDelta[],\n+\t): readonly PlanningObjectiveDelta[] {\n+\t\tconst shareable = deltas.every(\n+\t\t\t({ value }) => value === null || (Number.isFinite(value) && !Object.is(value, -0)),\n+\t\t);\n+\t\tconst key = shareable ? JSON.stringify(deltas) : undefined;\n+\t\tconst shared = key === undefined ? undefined : this.comparisonDeltas.get(key);\n+\t\tif (shared) return shared;\n+\t\tconst result = Object.freeze(deltas.map((delta) => Object.freeze({ ...delta })));\n+\t\tif (key !== undefined && this.comparisonDeltas.size < 4096)\n+\t\t\tthis.comparisonDeltas.set(key, result);\n+\t\treturn result;\n+\t}\n+\n+\tprivate captureTechnicalValues(\n+\t\tvalues: PlanningTraceCandidate['technicalComparison'],\n+\t): PlanningTraceCandidate['technicalComparison'] {\n+\t\tif (!values || Object.isFrozen(values)) return values;\n+\t\tconst shareable = values.every(\n+\t\t\t({ before, after }) =>\n+\t\t\t\ttypeof before === 'number' &&\n+\t\t\t\ttypeof after === 'number' &&\n+\t\t\t\tNumber.isFinite(before) &&\n+\t\t\t\tNumber.isFinite(after) &&\n+\t\t\t\t!Object.is(before, -0) &&\n+\t\t\t\t!Object.is(after, -0),\n+\t\t);\n+\t\tconst key = shareable ? JSON.stringify(values) : undefined;\n+\t\tconst shared = key === undefined ? undefined : this.technicalValues.get(key);\n+\t\tif (shared) return shared;\n+\t\tconst result = Object.freeze(\n+\t\t\tvalues.map((value) => {\n+\t\t\t\tconst shareable =\n+\t\t\t\t\t(value.name === 'balance-expiry' &&\n+\t\t\t\t\t\ttypeof value.before === 'string' &&\n+\t\t\t\t\t\ttypeof value.after === 'string') ||\n+\t\t\t\t\t(typeof value.before === 'number' &&\n+\t\t\t\t\t\ttypeof value.after === 'number' &&\n+\t\t\t\t\t\tNumber.isFinite(value.before) &&\n+\t\t\t\t\t\tNumber.isFinite(value.after) &&\n+\t\t\t\t\t\t!Object.is(value.before, -0) &&\n+\t\t\t\t\t\t!Object.is(value.after, -0));\n+\t\t\t\tconst key = shareable ? JSON.stringify(value) : undefined;\n+\t\t\t\tconst shared = key === undefined ? undefined : this.technicalEntries.get(key);\n+\t\t\t\tif (shared) return shared;\n+\t\t\t\tconst result = Object.freeze({\n+\t\t\t\t\t...value,\n+\t\t\t\t\tname: this.captureIdentifier(value.name),\n+\t\t\t\t\tbefore: this.captureTieValue(value.before),\n+\t\t\t\t\tafter: this.captureTieValue(value.after),\n+\t\t\t\t});\n+\t\t\t\tif (key !== undefined && this.technicalEntries.size < 4096)\n+\t\t\t\t\tthis.technicalEntries.set(key, result);\n+\t\t\t\treturn result;\n+\t\t\t}),\n+\t\t);\n+\t\tif (key !== undefined && this.technicalValues.size < 4096)\n+\t\t\tthis.technicalValues.set(key, result);\n+\t\treturn result;\n+\t}\n+\n \tstartPhase(name: string): void {\n \t\tif (this.phase?.name === name) return;\n \t\tif (this.phase) {\n@@ -736,12 +1008,10 @@ class TraceRecorder {\n \t\tif (!this.streaming) return;\n \t\tconst snapshot = {\n \t\t\t...candidate,\n-\t\t\tdates: candidate.dates ? [...candidate.dates] : undefined,\n+\t\t\tdates: this.captureDates(candidate.dates),\n \t\t\treason: candidate.reason ? { ...candidate.reason } : undefined,\n-\t\t\ttechnicalComparison: candidate.technicalComparison?.map((item) => ({ ...item })),\n-\t\t\tplacement: candidate.placement\n-\t\t\t\t? { ...candidate.placement, ruleIds: [...candidate.placement.ruleIds] }\n-\t\t\t\t: undefined,\n+\t\t\ttechnicalComparison: this.captureTechnicalValues(candidate.technicalComparison),\n+\t\t\tplacement: this.capturePlacement(candidate.placement),\n \t\t};\n \t\tconst pending = this.pendingCandidateOperations.get(candidate);\n \t\tif (pending) {\n@@ -776,6 +1046,16 @@ class TraceRecorder {\n \t\tdecision: MutableTraceDecision,\n \t\tcandidate: MutableTraceCandidate,\n \t): number {\n+\t\tif (candidate.comparison) {\n+\t\t\tcandidate.comparison = this.captureComparison(candidate.comparison);\n+\t\t}\n+\t\tcandidate.technicalComparison = this.captureTechnicalValues(candidate.technicalComparison);\n+\t\tif (candidate.firstDecisiveComparator !== undefined)\n+\t\t\tcandidate.firstDecisiveComparator = this.captureIdentifier(\n+\t\t\t\tcandidate.firstDecisiveComparator,\n+\t\t\t);\n+\t\tif (candidate.placement) candidate.placement = this.capturePlacement(candidate.placement);\n+\t\tif (candidate.dates) candidate.dates = this.captureDates(candidate.dates);\n \t\tconst index = decision.candidates.push(candidate) - 1;\n \t\tthis.recordCandidateUpdate(this.phase!, decision, index, 'append', candidate);\n \t\treturn index;\n@@ -869,18 +1149,13 @@ class TraceRecorder {\n \t\tconst mutable = copy\n \t\t\t? {\n \t\t\t\t\t...candidate,\n-\t\t\t\t\tdates: candidate.dates ? [...candidate.dates] : undefined,\n+\t\t\t\t\tdates: this.captureDates(candidate.dates),\n \t\t\t\t\treason: candidate.reason ? { ...candidate.reason } : undefined,\n-\t\t\t\t\ttechnicalComparison: candidate.technicalComparison?.map((item) => ({\n-\t\t\t\t\t\t...item,\n-\t\t\t\t\t})),\n-\t\t\t\t\tplacement: candidate.placement\n-\t\t\t\t\t\t? { ...candidate.placement, ruleIds: [...candidate.placement.ruleIds] }\n-\t\t\t\t\t\t: undefined,\n+\t\t\t\t\ttechnicalComparison: this.captureTechnicalValues(candidate.technicalComparison),\n+\t\t\t\t\tplacement: this.capturePlacement(candidate.placement),\n \t\t\t\t}\n \t\t\t: (candidate as MutableTraceCandidate);\n-\t\tconst index = this.recordNewCandidate(decision, mutable);\n-\t\tthis.evaluationLocations.set(mutable, { phase: this.phase!, decision, index });\n+\t\tthis.recordNewCandidate(decision, mutable);\n \t\treturn mutable;\n \t}\n \n@@ -900,8 +1175,7 @@ class TraceRecorder {\n \t\t}\n \t\tif (!candidate) return undefined;\n \t\tconst mutable = candidate as MutableTraceCandidate;\n-\t\tconst index = this.recordNewCandidate(decision, mutable);\n-\t\tthis.evaluationLocations.set(mutable, { phase: this.phase!, decision, index });\n+\t\tthis.recordNewCandidate(decision, mutable);\n \t\treturn mutable;\n \t}\n \n@@ -912,7 +1186,7 @@ class TraceRecorder {\n \t\tcandidate?: MutableTraceCandidate,\n \t): string {\n \t\tconst decision = candidate\n-\t\t\t? (this.evaluationLocations.get(candidate)?.decision ?? this.decision('choose', dates))\n+\t\t\t? (this.evaluationLocation(candidate)?.decision ?? this.decision('choose', dates))\n \t\t\t: this.decision('choose', dates);\n \t\tdecision.branch = {\n \t\t\tparentDecisionId,\n@@ -923,20 +1197,44 @@ class TraceRecorder {\n \t\treturn decision.id;\n \t}\n \n+\tprivate evaluationLocation(\n+\t\tcandidate: MutableTraceCandidate,\n+\t): { phase: MutableTracePhase; decision: MutableTraceDecision; index: number } | undefined {\n+\t\t// Immediate updates find the newest candidate first; late handles need no permanent index.\n+\t\tfor (let phaseIndex = this.phases.length - 1; phaseIndex >= 0; phaseIndex--) {\n+\t\t\tconst phase = this.phases[phaseIndex];\n+\t\t\tfor (\n+\t\t\t\tlet decisionIndex = phase.decisions.length - 1;\n+\t\t\t\tdecisionIndex >= 0;\n+\t\t\t\tdecisionIndex--\n+\t\t\t) {\n+\t\t\t\tconst decision = phase.decisions[decisionIndex];\n+\t\t\t\tconst index = decision.candidates.lastIndexOf(candidate);\n+\t\t\t\tif (index >= 0) return { phase, decision, index };\n+\t\t\t}\n+\t\t}\n+\t\treturn undefined;\n+\t}\n+\n \tdecisionIdFor(candidate: MutableTraceCandidate): string | undefined {\n-\t\treturn this.evaluationLocations.get(candidate)?.decision.id;\n+\t\treturn this.evaluationLocation(candidate)?.decision.id;\n \t}\n \n \trecordEvaluation(candidate: MutableTraceCandidate): void {\n \t\tconst decision = this.candidateDecision(\n \t\t\tcandidate.dates ?? (candidate.date ? [candidate.date] : []),\n \t\t);\n-\t\tconst index = this.recordNewCandidate(decision, candidate);\n-\t\tthis.evaluationLocations.set(candidate, { phase: this.phase!, decision, index });\n+\t\tthis.recordNewCandidate(decision, candidate);\n \t}\n \n \tupdateEvaluation(candidate: MutableTraceCandidate): void {\n-\t\tconst location = this.evaluationLocations.get(candidate);\n+\t\tif (candidate.placement) candidate.placement = this.capturePlacement(candidate.placement);\n+\t\tcandidate.technicalComparison = this.captureTechnicalValues(candidate.technicalComparison);\n+\t\tif (candidate.firstDecisiveComparator !== undefined)\n+\t\t\tcandidate.firstDecisiveComparator = this.captureIdentifier(\n+\t\t\t\tcandidate.firstDecisiveComparator,\n+\t\t\t);\n+\t\tconst location = this.evaluationLocation(candidate);\n \t\tif (location)\n \t\t\tthis.recordCandidateUpdate(\n \t\t\t\tlocation.phase,\n@@ -1014,7 +1312,7 @@ class TraceRecorder {\n \t\t\t...updated.map(([date]) => date),\n \t\t];\n \t\tconst decision =\n-\t\t\t(acceptedCandidate && this.evaluationLocations.get(acceptedCandidate)?.decision) ||\n+\t\t\t(acceptedCandidate && this.evaluationLocation(acceptedCandidate)?.decision) ||\n \t\t\tthis.decision(action, dates);\n \t\tdecision.action = action;\n \t\tdecision.dates = dates;\n@@ -1145,9 +1443,8 @@ class TraceRecorder {\n \t\t\t\tdecisions: phase.decisions.map((decision) => ({\n \t\t\t\t\t...decision,\n \t\t\t\t\tdates: [...decision.dates],\n-\t\t\t\t\tcandidates: decision.candidates.map((candidate) => ({\n-\t\t\t\t\t\t...candidate,\n-\t\t\t\t\t})),\n+\t\t\t\t\t// Search is complete; later stream drains only emit detached snapshots.\n+\t\t\t\t\tcandidates: [...decision.candidates],\n \t\t\t\t\tdeltas: decision.deltas.map((delta) => ({ ...delta })),\n \t\t\t\t})),\n \t\t\t})),\n@@ -1187,11 +1484,17 @@ interface SearchContext {\n \ttraceReportedTime: number;\n \tobserverTime: number;\n \tobligationSolutionBranches: WeakMap;\n+\tcompletedPreferenceStates: Map;\n+\tcompletedGenericState?: string;\n \ttraceBranchParentId?: string;\n \ttraceBranchActive?: boolean;\n \ttraceError?: PlanningReason;\n \t/** Supplied metrics were evaluated after reconciling earned entitlement dates. */\n-\tretain?: (state: State, finalizedMetrics?: PlanningMetrics) => void;\n+\tretain?: (\n+\t\tstate: State,\n+\t\tfinalizedMetrics?: PlanningMetrics,\n+\t\tvector?: PlanningObjectiveVector,\n+\t) => void;\n }\n \n type PlanningCalendar = Pick<\n@@ -1320,6 +1623,7 @@ const DAY_MS = 86_400_000;\n // that this ceiling misses a better lexicographic assignment.\n const OBLIGATION_SOLUTION_LIMIT = 4096;\n const EXACT_OBLIGATION_BRANCH_LIMIT = 10_000;\n+const WINDOW_OBLIGATION_PREVIEW_LIMIT = 8;\n const VALID_TYPES = new Set(['cp', 'rtt', 'other']);\n const VALID_SELECTORS = new Set(['cp', 'rtt', 'other', 'any']);\n const VALID_MODES = new Set(['before', 'after', 'around', 'auto']);\n@@ -1442,19 +1746,6 @@ function holidayWeekCandidates(context: SearchContext): HolidayWeekCandidate[] {\n \t);\n }\n \n-function holidayWeekValue(state: State, context: SearchContext): number {\n-\treturn context.holidayWeeks.reduce(\n-\t\t(value, candidate) =>\n-\t\t\tvalue +\n-\t\t\t(candidate.dates.every(\n-\t\t\t\t(date) => state.placements.has(date) || context.declaredDates.has(date),\n-\t\t\t)\n-\t\t\t\t? candidate.value\n-\t\t\t\t: 0),\n-\t\t0,\n-\t);\n-}\n-\n function reason(code: string, message: string, ruleIds?: string[]): PlanningReason {\n \treturn ruleIds?.length ? { code, message, ruleIds } : { code, message };\n }\n@@ -1657,6 +1948,9 @@ function retainAndRecordBranchMutation(\n ): string | undefined {\n \tlet decisionId: string | undefined;\n \tobserveTrace(context, (trace) => {\n+\t\tconst placement = candidate?.placement && after.placements.get(candidate.placement.date);\n+\t\tif (candidate && placement)\n+\t\t\tcandidate.placement = { ...placement, ruleIds: [...placement.ruleIds].sort() };\n \t\tdecisionId = trace.recordBranchTransition(\n \t\t\tdates,\n \t\t\tparentDecisionId,\n@@ -1668,42 +1962,6 @@ function retainAndRecordBranchMutation(\n \treturn decisionId;\n }\n \n-function retainAndRecordAtRiskBranchMutation(\n-\tcontext: SearchContext,\n-\tafter: State,\n-\tparentDecisionId: string | undefined,\n-\tcandidate: MutableTraceCandidate | undefined,\n-\tdate: string,\n-\tbalanceId: string,\n-\tremainingBefore: number,\n-): string | undefined {\n-\tlet decisionId: string | undefined;\n-\tobserveTrace(context, (trace) => {\n-\t\tconst placement = after.placements.get(date);\n-\t\tconst balance = after.balances.find((item) => item.id === balanceId);\n-\t\tif (!placement || !balance) return;\n-\t\tconst deltas: PlanningTraceDelta[] = [\n-\t\t\t{\n-\t\t\t\tkind: 'placement-added',\n-\t\t\t\tdate,\n-\t\t\t\tbalanceId,\n-\t\t\t\tplacement: { ...placement, ruleIds: [...placement.ruleIds].sort() },\n-\t\t\t},\n-\t\t];\n-\t\tif (remainingBefore !== balance.remaining)\n-\t\t\tdeltas.push({\n-\t\t\t\tkind: 'balance-changed',\n-\t\t\t\tbalanceId,\n-\t\t\t\tremainingBefore,\n-\t\t\t\tremainingAfter: balance.remaining,\n-\t\t\t\tbalance: { ...balance },\n-\t\t\t});\n-\t\tdecisionId = trace.recordBranchTransition([date], parentDecisionId, deltas, candidate);\n-\t});\n-\tcontext.retain?.(after);\n-\treturn decisionId;\n-}\n-\n function retainAndRecordState(\n \tcontext: SearchContext,\n \tstate: State,\n@@ -1711,6 +1969,10 @@ function retainAndRecordState(\n ): void {\n \tobserveTrace(context, (trace) => {\n \t\tconst snapshot = planningTraceState(state, context);\n+\t\tconst placement =\n+\t\t\tacceptedCandidate?.placement && state.placements.get(acceptedCandidate.placement.date);\n+\t\tif (acceptedCandidate && placement)\n+\t\t\tacceptedCandidate.placement = { ...placement, ruleIds: [...placement.ruleIds].sort() };\n \t\tif (acceptedCandidate) trace.chooseEvaluation(acceptedCandidate);\n \t\ttrace.recordPlan(\n \t\t\tsnapshot.placements,\n@@ -1739,9 +2001,11 @@ function normalizeForce(value: unknown): RuleForce | null {\n \treturn null;\n }\n \n-function normalizeRuleType(value: unknown): 'time_window' | 'if_then' | null {\n+function normalizeRuleType(value: unknown): NormalizedRule['type'] | null {\n \tconst normalized = String(value ?? '').toLowerCase();\n-\treturn normalized === 'time_window' || normalized === 'if_then' ? normalized : null;\n+\treturn normalized === 'time_window' || normalized === 'if_then' || normalized === 'optimization'\n+\t\t? normalized\n+\t\t: null;\n }\n \n function normalizeMode(value: unknown): PlacementMode | null {\n@@ -1872,6 +2136,26 @@ function normalizeRules(request: RuntimePlanningRequest): {\n \t\t\treasons.push(reason('rule-type', `Planning rule \"${id}\" has an unsupported type.`));\n \t\t\tcontinue;\n \t\t}\n+\t\tif (type === 'optimization') {\n+\t\t\tconst validated = validateOptimizationConfiguration(value?.configuration);\n+\t\t\tif (forceValue !== 'preference')\n+\t\t\t\treasons.push(\n+\t\t\t\t\treason('rule-force', 'Optimization rules support preference mode only.', [id]),\n+\t\t\t\t);\n+\t\t\tif (!validated.valid) {\n+\t\t\t\treasons.push(reason(validated.code, validated.message, [id]));\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\trules.push({\n+\t\t\t\tid,\n+\t\t\t\tname: typeof value?.name === 'string' ? value.name : id,\n+\t\t\t\ttype,\n+\t\t\t\tenabled: true,\n+\t\t\t\tforce: 'preference',\n+\t\t\t\tconfiguration: structuredClone(validated.configuration),\n+\t\t\t});\n+\t\t\tcontinue;\n+\t\t}\n \t\tconst placeDays = asInteger(value?.placeDays);\n \t\tconst placeType = normalizeSelector(value?.placeType);\n \t\tif (placeDays === null || placeDays < 0) {\n@@ -2050,7 +2334,7 @@ function futurePreferenceProtection(\n \tcontext.anyPreferenceDemandByDate = new Map();\n \tconst futureRules = rules.slice(startIndex);\n \tfor (const [offset, rule] of futureRules.entries()) {\n-\t\tif (!rule.enabled || rule.force !== 'preference') continue;\n+\t\tif (!rule.enabled || rule.force !== 'preference' || rule.type === 'optimization') continue;\n \t\tif (\n \t\t\trule.type === 'time_window' &&\n \t\t\tdeclaredWindowDays(rule, context).length >= rule.placeDays\n@@ -2097,9 +2381,24 @@ function futurePreferenceProtection(\n \n function occurrences(rule: NormalizedRule, context: SearchContext): string[] {\n \tif (rule.type !== 'if_then') return [];\n-\treturn dateRange(context.horizon.start, context.horizon.end).filter((date) => {\n-\t\treturn context.holidays.has(date) && utcDate(date).getUTCDay() === rule.dayOfWeek;\n-\t});\n+\tlet cached = occurrenceCache.get(context);\n+\tif (!cached) {\n+\t\tcached = new Map();\n+\t\toccurrenceCache.set(context, cached);\n+\t}\n+\tlet dates = cached.get(rule.id);\n+\tif (!dates) {\n+\t\tdates = [...context.holidays]\n+\t\t\t.filter(\n+\t\t\t\t(date) =>\n+\t\t\t\t\tdate >= context.horizon.start &&\n+\t\t\t\t\tdate < context.horizon.end &&\n+\t\t\t\t\tutcDate(date).getUTCDay() === rule.dayOfWeek,\n+\t\t\t)\n+\t\t\t.sort(compareDate);\n+\t\tcached.set(rule.id, dates);\n+\t}\n+\treturn dates;\n }\n \n function workingNeighbors(\n@@ -2126,7 +2425,19 @@ function workingNeighbors(\n \treturn result;\n }\n \n-function patternsFor(rule: NormalizedRule, holiday: string, context: SearchContext): string[][] {\n+function patternsFor(\n+\trule: NormalizedCalendarRule,\n+\tholiday: string,\n+\tcontext: SearchContext,\n+): string[][] {\n+\tlet cached = calendarPatternCache.get(context);\n+\tif (!cached) {\n+\t\tcached = new Map();\n+\t\tcalendarPatternCache.set(context, cached);\n+\t}\n+\tconst key = `${rule.id}:${holiday}`;\n+\tconst existing = cached.get(key);\n+\tif (existing) return existing;\n \tconst count = rule.placeDays;\n \tconst make = (before: number, after: number) =>\n \t\t[\n@@ -2141,7 +2452,7 @@ function patternsFor(rule: NormalizedRule, holiday: string, context: SearchConte\n \t} else {\n \t\tfor (let before = 0; before <= count; before++) patterns.push(make(before, count - before));\n \t}\n-\treturn patterns\n+\tconst eligible = patterns\n \t\t.filter(\n \t\t\t(pattern) =>\n \t\t\t\tpattern.length === count &&\n@@ -2152,6 +2463,8 @@ function patternsFor(rule: NormalizedRule, holiday: string, context: SearchConte\n \t\t\t\t),\n \t\t)\n \t\t.sort(compareDateLists);\n+\tcached.set(key, eligible);\n+\treturn eligible;\n }\n \n function buildRequirements(\n@@ -2166,7 +2479,7 @@ function buildRequirements(\n \tconst requirements: Requirement[] = [];\n \tlet index = 0;\n \tfor (const rule of rules) {\n-\t\tif (!rule.enabled || rule.force !== force) continue;\n+\t\tif (!rule.enabled || rule.force !== force || rule.type === 'optimization') continue;\n \t\tif (rule.type === 'time_window') {\n \t\t\tconst start =\n \t\t\t\tcompareDate(rule.startDate!, context.horizon.start) < 0\n@@ -2306,28 +2619,31 @@ function declaredPatternDay(date: string, selector: LeaveSelector, context: Sear\n \n function patternDateSatisfied(\n \tdate: string,\n-\trule: NormalizedRule,\n+\trule: NormalizedCalendarRule,\n \tstate: State,\n \tcontext: SearchContext,\n ): boolean {\n \treturn Boolean(\n \t\tdeclaredPatternDay(date, rule.placeType, context) ||\n-\t\tstate.placements.get(date)?.ruleIds.has(rule.id),\n+\t\t(state.placements.has(date) &&\n+\t\t\tselectorMatches(rule.placeType, state.placements.get(date)!.type)),\n \t);\n }\n \n-function assignDate(\n+function selectedOccurrencePattern(\n+\trule: NormalizedCalendarRule,\n+\toccurrence: string,\n \tstate: State,\n-\tdate: string,\n-\tselector: LeaveSelector,\n-\truleId: string,\n \tcontext: SearchContext,\n-\tselectedEvaluation?: (candidate: MutableTraceCandidate | undefined) => void,\n-): State | null {\n-\treturn (\n-\t\tassignDateVariants(state, date, selector, ruleId, context, true, selectedEvaluation)[0] ??\n-\t\tnull\n+): string[] | undefined {\n+\tconst activation = state.earnedActivations.find(\n+\t\t(item) => item.ruleId === rule.id && item.occurrence === occurrence,\n \t);\n+\treturn activation?.dates.every((date) => patternDateSatisfied(date, rule, state, context))\n+\t\t? activation.dates\n+\t\t: patternsFor(rule, occurrence, context).find((pattern) =>\n+\t\t\t\tpattern.every((date) => patternDateSatisfied(date, rule, state, context)),\n+\t\t\t);\n }\n \n function rejectDeclaredDate(context: SearchContext, date: string): boolean {\n@@ -2347,8 +2663,6 @@ function assignDateVariants(\n \tselector: LeaveSelector,\n \truleId: string,\n \tcontext: SearchContext,\n-\tfirstOnly = false,\n-\tselectedEvaluation?: (candidate: MutableTraceCandidate | undefined) => void,\n ): State[] {\n \tcontext.check();\n \tif (rejectDeclaredDate(context, date)) return [];\n@@ -2383,7 +2697,7 @@ function assignDateVariants(\n \t\t}\n \t\tconst result = cloneState(state);\n \t\tif (ruleId) result.placements.get(date)!.ruleIds.add(ruleId);\n-\t\tconst evaluation = recordTraceCandidate(context, {\n+\t\trecordTraceCandidate(context, {\n \t\t\tstatus: 'evaluated-rejected',\n \t\t\tdate,\n \t\t\tplacement: {\n@@ -2391,7 +2705,6 @@ function assignDateVariants(\n \t\t\t\truleIds: [...result.placements.get(date)!.ruleIds],\n \t\t\t},\n \t\t});\n-\t\tselectedEvaluation?.(evaluation);\n \t\treturn [result];\n \t}\n \tconst balances = state.balances\n@@ -2433,49 +2746,6 @@ function assignDateVariants(\n \t\t\t\t'No compatible leave balance can fund this candidate date.',\n \t\t\t),\n \t\t});\n-\tif (firstOnly && balances.length) {\n-\t\tconst first = balances[0];\n-\t\tconst selectionFacts = firstCompatibleBalanceSelectionFacts(\n-\t\t\tselector,\n-\t\t\tdate,\n-\t\t\tfirst,\n-\t\t\tbalances[1],\n-\t\t\tcontext,\n-\t\t);\n-\t\tconst result = cloneState(state);\n-\t\tresult.balances.find((item) => item.id === first.id)!.remaining--;\n-\t\tresult.placements.set(date, {\n-\t\t\tdate,\n-\t\t\tbalanceId: first.id,\n-\t\t\ttype: first.type,\n-\t\t\truleIds: ruleId ? new Set([ruleId]) : new Set(),\n-\t\t\tsupporting: false,\n-\t\t});\n-\t\tfor (const [index, balance] of balances.entries()) {\n-\t\t\tconst evaluation = recordTraceCandidate(context, {\n-\t\t\t\tstatus: index === 0 ? 'evaluated-rejected' : 'not-examined',\n-\t\t\t\tdate,\n-\t\t\t\t...(index === 0 ? selectionFacts : {}),\n-\t\t\t\t...(index === 0\n-\t\t\t\t\t? {}\n-\t\t\t\t\t: {\n-\t\t\t\t\t\t\treason: reason(\n-\t\t\t\t\t\t\t\t'first-compatible-balance',\n-\t\t\t\t\t\t\t\t'This balance was not examined after the first compatible balance was selected.',\n-\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t}),\n-\t\t\t\tplacement: {\n-\t\t\t\t\tdate,\n-\t\t\t\t\tbalanceId: balance.id,\n-\t\t\t\t\ttype: balance.type,\n-\t\t\t\t\truleIds: ruleId ? [ruleId] : [],\n-\t\t\t\t\tsupporting: false,\n-\t\t\t\t},\n-\t\t\t});\n-\t\t\tif (index === 0) selectedEvaluation?.(evaluation);\n-\t\t}\n-\t\treturn [result];\n-\t}\n \treturn balances.map((balance) => {\n \t\tconst result = cloneState(state);\n \t\tconst target = result.balances.find((item) => item.id === balance.id)!;\n@@ -2561,71 +2831,9 @@ function assignDateToBalance(\n \treturn result;\n }\n \n-function assignDateToBalanceInPlace(\n-\tstate: State,\n-\tdate: string,\n-\tbalanceId: string,\n-\tcontext: SearchContext,\n-\truleIds = new Set(),\n-\tselectedEvaluation?: (candidate: MutableTraceCandidate | undefined) => void,\n-\tbeforeMutation?: (state: State) => void,\n-\tselectionFacts?: Pick<\n-\t\tPlanningTraceCandidate,\n-\t\t'technicalComparison' | 'firstDecisiveComparator'\n-\t>,\n-): boolean {\n-\tcontext.check();\n-\tif (rejectDeclaredDate(context, date)) return false;\n-\tif (state.placements.has(date)) {\n-\t\trecordTraceCandidate(context, {\n-\t\t\tstatus: 'ineligible',\n-\t\t\tdate,\n-\t\t\treason: reason('occupied', 'Another placement already uses this date.'),\n-\t\t});\n-\t\treturn false;\n-\t}\n-\tconst balance = state.balances.find((item) => item.id === balanceId);\n-\tif (\n-\t\t!balance ||\n-\t\tbalance.remaining <= 0 ||\n-\t\tcompareDate(balance.availableFrom, date) > 0 ||\n-\t\tcompareDate(date, balance.expiryDate) > 0\n-\t) {\n-\t\trecordTraceCandidate(context, {\n-\t\t\tstatus: 'evaluated-rejected',\n-\t\t\tdate,\n-\t\t\treason: reason(\n-\t\t\t\t'balance-unavailable',\n-\t\t\t\t'The selected leave balance cannot fund this date.',\n-\t\t\t),\n-\t\t});\n-\t\treturn false;\n-\t}\n-\tbeforeMutation?.(state);\n-\tbalance.remaining--;\n-\tstate.placements.set(date, {\n-\t\tdate,\n-\t\tbalanceId,\n-\t\ttype: balance.type,\n-\t\truleIds: new Set(ruleIds),\n-\t\tsupporting: false,\n-\t});\n-\tconst evaluation = recordTraceCandidate(context, {\n-\t\tstatus: 'evaluated-rejected',\n-\t\tdate,\n-\t\t...selectionFacts,\n-\t\tplacement: {\n-\t\t\t...state.placements.get(date)!,\n-\t\t\truleIds: [...state.placements.get(date)!.ruleIds],\n-\t\t},\n-\t});\n-\tselectedEvaluation?.(evaluation);\n-\treturn true;\n-}\n-\n function addEarnedBalance(\n \tstate: State,\n-\trule: NormalizedRule,\n+\trule: NormalizedCalendarRule,\n \toccurrence: string,\n \tdates: string[],\n \tcontext: SearchContext,\n@@ -2682,8 +2890,26 @@ function earnedPeriodBounds(\n * period.\n */\n function finalizeEarnedState(state: State, context: SearchContext): State | null {\n-\tif (!state.earnedActivations.length) return state;\n-\tlet result = cloneState(state);\n+\tlet reconciled = state;\n+\t// Earning follows actual completed patterns, including those another rule already placed.\n+\t// Both comparison sides must contain these rights before an objective can rank them.\n+\tfor (const rule of context.rules) {\n+\t\tif (rule.type !== 'if_then' || !rule.rewardDays) continue;\n+\t\tfor (const occurrence of occurrences(rule, context)) {\n+\t\t\tif (\n+\t\t\t\treconciled.earnedActivations.some(\n+\t\t\t\t\t(activation) =>\n+\t\t\t\t\t\tactivation.ruleId === rule.id && activation.occurrence === occurrence,\n+\t\t\t\t)\n+\t\t\t)\n+\t\t\t\tcontinue;\n+\t\t\tconst pattern = selectedOccurrencePattern(rule, occurrence, reconciled, context);\n+\t\t\tif (pattern)\n+\t\t\t\treconciled = addEarnedBalance(reconciled, rule, occurrence, pattern, context);\n+\t\t}\n+\t}\n+\tif (!reconciled.earnedActivations.length) return reconciled;\n+\tlet result = cloneState(reconciled);\n \tfor (const activation of result.earnedActivations) {\n \t\tcontext.check();\n \t\tconst bounds = earnedPeriodBounds(result, activation, context);\n@@ -2699,7 +2925,10 @@ function finalizeEarnedState(state: State, context: SearchContext): State | null\n \t\t}\n \t\tlet balance = result.balances.find((item) => item.id === activation.id);\n \t\tif (!balance) {\n-\t\t\tconst rule = context.rules.find((rule) => rule.id === activation.ruleId);\n+\t\t\tconst rule = context.rules.find(\n+\t\t\t\t(rule): rule is NormalizedCalendarRule =>\n+\t\t\t\t\trule.type === 'if_then' && rule.id === activation.ruleId,\n+\t\t\t);\n \t\t\tif (!rule) return null;\n \t\t\tresult = addEarnedBalance(\n \t\t\t\tresult,\n@@ -2728,7 +2957,7 @@ function finalizeEarnedState(state: State, context: SearchContext): State | null\n function* assignDatesVariants(\n \tstate: State,\n \tdates: string[],\n-\trule: NormalizedRule,\n+\trule: NormalizedCalendarRule,\n \tcontext: SearchContext,\n ): PlanningSteps {\n \tif (!dates.length) return [state];\n@@ -2767,7 +2996,7 @@ function* satisfyObligations(\n \tyield;\n \tcontext.check();\n \tif (index >= requirements.length) {\n-\t\tconst finalized = finalizeEarnedState(state, context);\n+\t\tconst finalized = finalizeRuleCandidate(state, context, state);\n \t\tif (!finalized)\n \t\t\trecordTraceCandidate(context, {\n \t\t\t\tstatus: 'pruned',\n@@ -3000,213 +3229,1325 @@ function chooseObligationBranches(state: State, context: SearchContext): void {\n \t}\n }\n \n-function* placeAtRisk(state: State, context: SearchContext): PlanningSteps {\n-\t// At-risk placement is a greedy pass over one state. Clone it once, then\n-\t// mutate that private copy; cloning the whole placement map for every day is\n-\t// quadratic for a loaded year and does not change the observable result.\n-\tconst canMutate = state.earnedActivations.length === 0;\n-\tlet result = canMutate ? cloneState(state) : state;\n-\tconst balances = result.balances\n-\t\t.filter(\n-\t\t\t(balance) =>\n-\t\t\t\tcompareDate(balance.expiryDate, context.horizon.start) >= 0 &&\n-\t\t\t\tcompareDate(balance.expiryDate, context.horizon.end) <= 0,\n-\t\t)\n-\t\t.sort((a, b) => compareDate(a.expiryDate, b.expiryDate) || compareText(a.id, b.id));\n-\tfor (const balance of balances) {\n-\t\tyield;\n-\t\tconst availableDates = [...context.workingDays].sort(\n-\t\t\t(a, b) =>\n-\t\t\t\tpreferenceDateConflictScore(balance.type, a, context) -\n-\t\t\t\t\tpreferenceDateConflictScore(balance.type, b, context) || compareDate(a, b),\n-\t\t);\n-\t\twhile (true) {\n-\t\t\tyield;\n-\t\t\tcontext.check();\n-\t\t\tconst current = result.balances.find((item) => item.id === balance.id)!;\n-\t\t\tif (current.remaining <= 0) break;\n-\t\t\tlet nextState: State | null = null;\n-\t\t\tlet nextEvaluation: MutableTraceCandidate | undefined;\n-\t\t\tfor (const [candidateIndex, candidate] of availableDates.entries()) {\n-\t\t\t\tyield;\n-\t\t\t\tcontext.check();\n-\t\t\t\tif (\n-\t\t\t\t\t!result.placements.has(candidate) &&\n-\t\t\t\t\tcompareDate(current.availableFrom, candidate) <= 0 &&\n-\t\t\t\t\tcompareDate(candidate, current.expiryDate) <= 0\n-\t\t\t\t) {\n-\t\t\t\t\tconst nextDate = availableDates\n-\t\t\t\t\t\t.slice(candidateIndex + 1)\n-\t\t\t\t\t\t.find(\n-\t\t\t\t\t\t\t(date) =>\n-\t\t\t\t\t\t\t\t!result.placements.has(date) &&\n-\t\t\t\t\t\t\t\tcompareDate(current.availableFrom, date) <= 0 &&\n-\t\t\t\t\t\t\t\tcompareDate(date, current.expiryDate) <= 0,\n-\t\t\t\t\t\t);\n-\t\t\t\t\tconst selectionFacts = nextDate\n-\t\t\t\t\t\t? atRiskDateSelectionFacts(balance.type, candidate, nextDate, context)\n-\t\t\t\t\t\t: undefined;\n-\t\t\t\t\trecordTraceDecision(context, [candidate]);\n-\t\t\t\t\tlet remainingBeforeTransition = current.remaining;\n-\t\t\t\t\tlet evaluation: MutableTraceCandidate | undefined;\n-\t\t\t\t\tconst assigned = canMutate\n-\t\t\t\t\t\t? assignDateToBalanceInPlace(\n-\t\t\t\t\t\t\t\tresult,\n-\t\t\t\t\t\t\t\tcandidate,\n-\t\t\t\t\t\t\t\tcurrent.id,\n-\t\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\t\tnew Set(),\n-\t\t\t\t\t\t\t\t(candidateTrace) => (evaluation = candidateTrace),\n-\t\t\t\t\t\t\t\t(before) =>\n-\t\t\t\t\t\t\t\t\t(remainingBeforeTransition =\n-\t\t\t\t\t\t\t\t\t\tbefore.balances.find((item) => item.id === current.id)\n-\t\t\t\t\t\t\t\t\t\t\t?.remaining ?? remainingBeforeTransition),\n-\t\t\t\t\t\t\t\tselectionFacts,\n-\t\t\t\t\t\t\t)\n-\t\t\t\t\t\t\t? result\n-\t\t\t\t\t\t\t: null\n-\t\t\t\t\t\t: assignDateToBalance(\n-\t\t\t\t\t\t\t\tresult,\n-\t\t\t\t\t\t\t\tcandidate,\n-\t\t\t\t\t\t\t\tcurrent.id,\n-\t\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\t\tnew Set(),\n-\t\t\t\t\t\t\t\t(candidateTrace) => (evaluation = candidateTrace),\n-\t\t\t\t\t\t\t\tselectionFacts,\n-\t\t\t\t\t\t\t);\n-\t\t\t\t\tconst feasible = assigned ? finalizeEarnedState(assigned, context) : null;\n-\t\t\t\t\tif (feasible) {\n-\t\t\t\t\t\tnextState = feasible;\n-\t\t\t\t\t\tnextEvaluation = evaluation;\n-\t\t\t\t\t\tif (context.traceBranchActive) {\n-\t\t\t\t\t\t\tconst parent = canMutate\n-\t\t\t\t\t\t\t\t? retainAndRecordAtRiskBranchMutation(\n-\t\t\t\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\t\t\t\tfeasible,\n-\t\t\t\t\t\t\t\t\t\tcontext.traceBranchParentId,\n-\t\t\t\t\t\t\t\t\t\tevaluation,\n-\t\t\t\t\t\t\t\t\t\tcandidate,\n-\t\t\t\t\t\t\t\t\t\tcurrent.id,\n-\t\t\t\t\t\t\t\t\t\tremainingBeforeTransition,\n-\t\t\t\t\t\t\t\t\t)\n-\t\t\t\t\t\t\t\t: retainAndRecordBranchMutation(\n-\t\t\t\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\t\t\t\tresult,\n-\t\t\t\t\t\t\t\t\t\tfeasible,\n-\t\t\t\t\t\t\t\t\t\tcontext.traceBranchParentId,\n-\t\t\t\t\t\t\t\t\t\tevaluation,\n-\t\t\t\t\t\t\t\t\t\t[candidate],\n-\t\t\t\t\t\t\t\t\t);\n-\t\t\t\t\t\t\tcontext.traceBranchParentId = parent ?? context.traceBranchParentId;\n-\t\t\t\t\t\t}\n-\t\t\t\t\t\tbreak;\n-\t\t\t\t\t}\n-\t\t\t\t}\n-\t\t\t}\n-\t\t\tif (!nextState) break;\n-\t\t\tresult = nextState;\n-\t\t\tif (!context.traceBranchActive) retainAndRecordState(context, result, nextEvaluation);\n-\t\t}\n-\t}\n+function releasePlacement(state: State, date: string): State {\n+\t// Removing a slot never edits surviving placements. Later assignments and\n+\t// metadata reconciliation still detach their placements before changing them.\n+\tconst result: State = {\n+\t\tbalances: state.balances.map((balance) => ({ ...balance })),\n+\t\tplacements: new Map(state.placements),\n+\t\tearnedActivations: state.earnedActivations.map((activation) => ({\n+\t\t\t...activation,\n+\t\t\tdates: [...activation.dates],\n+\t\t})),\n+\t};\n+\tconst placement = result.placements.get(date)!;\n+\tresult.placements.delete(date);\n+\tresult.balances.find((balance) => balance.id === placement.balanceId)!.remaining++;\n \treturn result;\n }\n \n-function* preferenceTimeWindow(\n+function reconcileOptimizationProvenance(\n \tstate: State,\n-\trule: NormalizedRule,\n \tcontext: SearchContext,\n-): PlanningSteps<{ state: State; count: number }> {\n-\tconst start =\n-\t\tcompareDate(rule.startDate!, context.horizon.start) < 0\n-\t\t\t? context.horizon.start\n-\t\t\t: rule.startDate!;\n-\tconst end =\n-\t\tcompareDate(rule.endDate!, context.horizon.end) >= 0\n-\t\t\t? addDays(context.horizon.end, -1)\n-\t\t\t: rule.endDate!;\n-\tif (compareDate(start, end) > 0) return { state, count: 0 };\n+\tbefore: State,\n+\tobjectives: readonly PlanningObjective[] = activeObjectiveVector(state, context),\n+): State {\n+\tconst optimizations = objectives.filter(({ id }) => id.startsWith('optimization:'));\n+\tif (!optimizations.length) return state;\n \tlet result = state;\n-\tlet count = declaredWindowDays(rule, context).length;\n-\tconst shareableDates = new Set(\n-\t\t[...state.placements.values()]\n-\t\t\t.filter((placement) => selectorMatches(rule.placeType, placement.type))\n-\t\t\t.map((placement) => placement.date),\n-\t);\n-\tconst candidates = context.workingDays\n-\t\t.filter(\n-\t\t\t(item) =>\n-\t\t\t\t!context.declaredDates.has(item) &&\n-\t\t\t\tcompareDate(item, start) >= 0 &&\n-\t\t\t\tcompareDate(item, end) <= 0,\n+\tlet observations: OptimizationObservations | undefined;\n+\tfor (const placement of state.placements.values()) {\n+\t\tconst previous = before.placements.get(placement.date);\n+\t\tconst creditedIds = new Set([...placement.ruleIds, ...(previous?.ruleIds ?? [])]);\n+\t\tconst credits = optimizations.filter(({ id }) =>\n+\t\t\tcreditedIds.has(id.slice('optimization:'.length)),\n+\t\t);\n+\t\tif (!credits.length) continue;\n+\t\tconst withoutState = releasePlacement(state, placement.date);\n+\t\tconst withoutPlacement = activeObjectiveVector(withoutState, context);\n+\t\tconst ruleIds = new Set(\n+\t\t\t[...placement.ruleIds].filter(\n+\t\t\t\t(id) => !credits.some((objective) => objective.id === `optimization:${id}`),\n+\t\t\t),\n+\t\t);\n+\t\tfor (const objective of credits) {\n+\t\t\tconst without = withoutPlacement.find(({ id }) => id === objective.id)!;\n+\t\t\tconst id = objective.id.slice('optimization:'.length);\n+\t\t\tconst rule = context.rules.find(\n+\t\t\t\t(rule): rule is NormalizedOptimizationRule =>\n+\t\t\t\t\trule.id === id && rule.type === 'optimization',\n+\t\t\t)!;\n+\t\t\tconst compared = compareObjectiveValues(\n+\t\t\t\tobjective.direction,\n+\t\t\t\tobjective.value,\n+\t\t\t\twithout.value,\n+\t\t\t);\n+\t\t\tlet contributes = compared < 0;\n+\t\t\tif (compared === 0 && rule.configuration.aggregation === 'maximum') {\n+\t\t\t\t// Another tied maximum can mask a placement's improvement to its own element.\n+\t\t\t\tobservations ??= optimizationObservations(state, context);\n+\t\t\t\tconst withoutObservations = optimizationObservations(withoutState, context);\n+\t\t\t\tconst summed = { ...rule.configuration, aggregation: 'sum' as const };\n+\t\t\t\tconst summedComparison = compareObjectiveValues(\n+\t\t\t\t\tobjective.direction,\n+\t\t\t\t\tevaluateOptimization(summed, observations),\n+\t\t\t\t\tevaluateOptimization(summed, withoutObservations),\n+\t\t\t\t);\n+\t\t\t\tcontributes =\n+\t\t\t\t\tsummedComparison < 0 ||\n+\t\t\t\t\t(summedComparison === 0 &&\n+\t\t\t\t\t\trule.configuration.elements === 'time-off-periods' &&\n+\t\t\t\t\t\tobjective.direction === 'maximize' &&\n+\t\t\t\t\t\tobservations.timeOffPeriods.length <\n+\t\t\t\t\t\t\twithoutObservations.timeOffPeriods.length);\n+\t\t\t}\n+\t\t\tif (contributes) ruleIds.add(id);\n+\t\t}\n+\t\tif (\n+\t\t\truleIds.size === placement.ruleIds.size &&\n+\t\t\t[...ruleIds].every((id) => placement.ruleIds.has(id))\n \t\t)\n-\t\t.sort((a, b) => {\n-\t\t\treturn (\n-\t\t\t\tNumber(!shareableDates.has(a)) - Number(!shareableDates.has(b)) ||\n-\t\t\t\tpreferenceDateConflictScore(rule.placeType, a, context) -\n-\t\t\t\t\tpreferenceDateConflictScore(rule.placeType, b, context) ||\n-\t\t\t\tcompareDate(a, b)\n+\t\t\tcontinue;\n+\t\tif (result === state) result = cloneState(state);\n+\t\tresult.placements.get(placement.date)!.ruleIds = ruleIds;\n+\t}\n+\treturn result;\n+}\n+\n+function supportingCalendarBenefit(\n+\tbefore: OptimizationObservations,\n+\tafter: State,\n+\tcontext: SearchContext,\n+): boolean {\n+\tconst observations = optimizationObservations(after, context);\n+\treturn (\n+\t\tevaluateOptimization(OPTIMIZATION_PRESETS.holidayWeekValue, observations) >\n+\t\t\tevaluateOptimization(OPTIMIZATION_PRESETS.holidayWeekValue, before) ||\n+\t\tevaluateOptimization(OPTIMIZATION_PRESETS.nonWorkingDayGain, observations) >\n+\t\t\tevaluateOptimization(OPTIMIZATION_PRESETS.nonWorkingDayGain, before) ||\n+\t\tevaluateOptimization(OPTIMIZATION_PRESETS.longestWorkSequence, observations) <\n+\t\t\tevaluateOptimization(OPTIMIZATION_PRESETS.longestWorkSequence, before) ||\n+\t\tevaluateOptimization(OPTIMIZATION_PRESETS.shortSequenceDeficit, observations) <\n+\t\t\tevaluateOptimization(OPTIMIZATION_PRESETS.shortSequenceDeficit, before)\n+\t);\n+}\n+\n+function mandatoryRelocationDate(\n+\tdate: string,\n+\tbalance: InternalBalance,\n+\truleIds: ReadonlySet,\n+\tcontext: SearchContext,\n+): boolean {\n+\treturn [...ruleIds].every((id) => {\n+\t\tconst rule = context.rules.find((item) => item.id === id);\n+\t\tif (rule?.force !== 'obligation') return true;\n+\t\tif (!selectorMatches(rule.placeType, balance.type)) return false;\n+\t\treturn rule.type === 'time_window'\n+\t\t\t? date >= rule.startDate! && date <= rule.endDate!\n+\t\t\t: occurrences(rule, context).some((occurrence) =>\n+\t\t\t\t\tpatternsFor(rule, occurrence, context).some((pattern) =>\n+\t\t\t\t\t\tpattern.includes(date),\n+\t\t\t\t\t),\n+\t\t\t\t);\n+\t});\n+}\n+\n+/** Optimistic reachability ignores preference values and complete-pattern validity. */\n+function relocationCanReachFree(\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tbalanceId: string,\n+\truleIds: ReadonlySet,\n+\tvisited: ReadonlySet,\n+\tfailed: Set,\n+): boolean {\n+\tconst key = JSON.stringify([balanceId, [...ruleIds].sort(), [...visited].sort()]);\n+\tif (failed.has(key)) return false;\n+\tconst queue = [{ balanceId, ruleIds }];\n+\tconst seen = new Set();\n+\tfor (let index = 0; index < queue.length; index++) {\n+\t\tconst entry = queue[index];\n+\t\tconst identity = JSON.stringify([entry.balanceId, [...entry.ruleIds].sort()]);\n+\t\tif (seen.has(identity)) continue;\n+\t\tseen.add(identity);\n+\t\tconst balance = state.balances.find((item) => item.id === entry.balanceId)!;\n+\t\tfor (const date of context.workingDays) {\n+\t\t\tcontext.check();\n+\t\t\tif (\n+\t\t\t\tvisited.has(date) ||\n+\t\t\t\tcontext.declaredDates.has(date) ||\n+\t\t\t\tdate < balance.availableFrom ||\n+\t\t\t\tdate > balance.expiryDate ||\n+\t\t\t\t!mandatoryRelocationDate(date, balance, entry.ruleIds, context)\n+\t\t\t)\n+\t\t\t\tcontinue;\n+\t\t\tconst placement = state.placements.get(date);\n+\t\t\tif (!placement) return true;\n+\t\t\tqueue.push({ balanceId: placement.balanceId, ruleIds: placement.ruleIds });\n+\t\t}\n+\t}\n+\tfailed.add(key);\n+\treturn false;\n+}\n+\n+/** Relocate occupied dates along an augmenting path and validate only the complete addition. */\n+function* relocateForAddition(\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tdate: string,\n+\tbalanceId: string,\n+\truleIds: Set,\n+\tsupporting: boolean,\n+\taccept: (candidate: State, dates: string[]) => boolean,\n+\tvisited = new Set(),\n+\tpath: string[] = [],\n+\tfailedReachability = new Set(),\n+\tfailedSearches = new Set(),\n+): PlanningSteps {\n+\tyield;\n+\tcontext.check();\n+\tif (visited.has(date) || context.declaredDates.has(date)) return false;\n+\tconst existing = state.placements.get(date);\n+\tif (\n+\t\texisting?.balanceId === balanceId &&\n+\t\texisting.supporting === supporting &&\n+\t\texisting.ruleIds.size === ruleIds.size &&\n+\t\t[...existing.ruleIds].every((id) => ruleIds.has(id))\n+\t)\n+\t\treturn false;\n+\tconst key = JSON.stringify([\n+\t\tdate,\n+\t\tbalanceId,\n+\t\t[...ruleIds].sort(),\n+\t\tsupporting,\n+\t\t[...visited].sort(),\n+\t\tstate.balances.map((balance) => [balance.id, balance.remaining]),\n+\t\t[...state.placements.values()]\n+\t\t\t.sort((a, b) => compareDate(a.date, b.date))\n+\t\t\t.map((placement) => [\n+\t\t\t\tplacement.date,\n+\t\t\t\tplacement.balanceId,\n+\t\t\t\t[...placement.ruleIds].sort(),\n+\t\t\t\tplacement.supporting,\n+\t\t\t]),\n+\t]);\n+\tif (failedSearches.has(key)) {\n+\t\trecordTraceCandidate(context, {\n+\t\t\tstatus: 'pruned',\n+\t\t\tdate,\n+\t\t\tsourceDate: path[0],\n+\t\t\treason: reason(\n+\t\t\t\t'duplicate-relocation-state',\n+\t\t\t\t'This identical relocation state was already examined without a valid improving endpoint.',\n+\t\t\t),\n+\t\t});\n+\t\treturn false;\n+\t}\n+\tconst assigned = assignDateToBalance(\n+\t\texisting ? releasePlacement(state, date) : state,\n+\t\tdate,\n+\t\tbalanceId,\n+\t\tcontext,\n+\t\truleIds,\n+\t);\n+\tif (!assigned) return false;\n+\tassigned.placements.get(date)!.supporting = supporting;\n+\tconst dates = [...path, date];\n+\tif (!existing) {\n+\t\tconst accepted = accept(assigned, dates);\n+\t\tif (!accepted) failedSearches.add(key);\n+\t\treturn accepted;\n+\t}\n+\tconst displaced = assigned.balances.find((balance) => balance.id === existing.balanceId)!;\n+\tconst nextVisited = new Set([...visited, date]);\n+\tif (\n+\t\t!relocationCanReachFree(\n+\t\t\tassigned,\n+\t\t\tcontext,\n+\t\t\texisting.balanceId,\n+\t\t\texisting.ruleIds,\n+\t\t\tnextVisited,\n+\t\t\tfailedReachability,\n+\t\t)\n+\t)\n+\t\treturn false;\n+\tfor (const destination of context.workingDays) {\n+\t\tyield;\n+\t\tif (destination < displaced.availableFrom || destination > displaced.expiryDate) continue;\n+\t\tif (!mandatoryRelocationDate(destination, displaced, existing.ruleIds, context)) continue;\n+\t\tif (\n+\t\t\tyield* relocateForAddition(\n+\t\t\t\tassigned,\n+\t\t\t\tcontext,\n+\t\t\t\tdestination,\n+\t\t\t\texisting.balanceId,\n+\t\t\t\texisting.ruleIds,\n+\t\t\t\texisting.supporting,\n+\t\t\t\taccept,\n+\t\t\t\tnextVisited,\n+\t\t\t\tdates,\n+\t\t\t\tfailedReachability,\n+\t\t\t\tfailedSearches,\n+\t\t\t)\n+\t\t)\n+\t\t\treturn true;\n+\t}\n+\tfailedSearches.add(key);\n+\treturn false;\n+}\n+\n+function finalizeRuleCandidate(state: State, context: SearchContext, before: State): State | null {\n+\tlet result = state;\n+\tconst windowCredits = new Map();\n+\tconst patternCredits = new Map>();\n+\tfor (const placement of state.placements.values()) {\n+\t\tlet lostCalendarRequest = false;\n+\t\tfor (const id of placement.ruleIds) {\n+\t\t\tconst rule = context.rules.find((item) => item.id === id);\n+\t\t\tconst valid = counterfactualRuleValid(\n+\t\t\t\tplacement.date,\n+\t\t\t\tplacement.type,\n+\t\t\t\t[id],\n+\t\t\t\tcontext,\n+\t\t\t\tstate,\n \t\t\t);\n+\t\t\tconst credited = windowCredits.get(id) ?? 0;\n+\t\t\tlet withinRequest = true;\n+\t\t\tif (rule?.type === 'time_window')\n+\t\t\t\twithinRequest =\n+\t\t\t\t\tcredited <\n+\t\t\t\t\tMath.max(0, rule.placeDays - declaredWindowDays(rule, context).length);\n+\t\t\telse if (rule?.type === 'if_then') {\n+\t\t\t\tif (!patternCredits.has(id))\n+\t\t\t\t\tpatternCredits.set(\n+\t\t\t\t\t\tid,\n+\t\t\t\t\t\tnew Set(\n+\t\t\t\t\t\t\toccurrences(rule, context).flatMap(\n+\t\t\t\t\t\t\t\t(occurrence) =>\n+\t\t\t\t\t\t\t\t\tselectedOccurrencePattern(rule, occurrence, state, context) ??\n+\t\t\t\t\t\t\t\t\t[],\n+\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t),\n+\t\t\t\t\t);\n+\t\t\t\twithinRequest = patternCredits.get(id)!.has(placement.date);\n+\t\t\t}\n+\t\t\tif (valid && withinRequest) {\n+\t\t\t\tif (rule?.type === 'time_window') windowCredits.set(id, credited + 1);\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\tif (!valid && rule?.force === 'obligation') return null;\n+\t\t\tif (result === state) result = cloneState(state);\n+\t\t\tresult.placements.get(placement.date)!.ruleIds.delete(id);\n+\t\t\tlostCalendarRequest ||= rule?.type !== 'optimization';\n+\t\t}\n+\t\tconst current = result.placements.get(placement.date)!;\n+\t\tconst hasCalendarRequest = [...current.ruleIds].some((id) =>\n+\t\t\tcontext.rules.some((rule) => rule.id === id && rule.type !== 'optimization'),\n+\t\t);\n+\t\tconst previous = before.placements.get(placement.date);\n+\t\tlet supporting = current.supporting;\n+\t\tif (hasCalendarRequest) supporting = false;\n+\t\telse if (\n+\t\t\tlostCalendarRequest ||\n+\t\t\t(previous &&\n+\t\t\t\t(previous.balanceId !== placement.balanceId ||\n+\t\t\t\t\tprevious.supporting !== current.supporting))\n+\t\t) {\n+\t\t\tconst balance = result.balances.find((item) => item.id === placement.balanceId)!;\n+\t\t\tsupporting =\n+\t\t\t\t!isAtRisk(balance, context) &&\n+\t\t\t\t(current.supporting ||\n+\t\t\t\t\t(previous?.balanceId === placement.balanceId && previous.supporting) ||\n+\t\t\t\t\tsupportingCalendarBenefit(\n+\t\t\t\t\t\toptimizationObservations(releasePlacement(result, placement.date), context),\n+\t\t\t\t\t\tresult,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t));\n+\t\t}\n+\t\tif (supporting !== current.supporting) {\n+\t\t\tif (result === state) result = cloneState(state);\n+\t\t\tresult.placements.get(placement.date)!.supporting = supporting;\n+\t\t}\n+\t}\n+\tfor (const activation of state.earnedActivations) {\n+\t\tconst rule = context.rules.find(\n+\t\t\t(item): item is NormalizedCalendarRule =>\n+\t\t\t\titem.type === 'if_then' && item.id === activation.ruleId,\n+\t\t)!;\n+\t\tif (activation.dates.every((date) => patternDateSatisfied(date, rule, state, context)))\n+\t\t\tcontinue;\n+\t\tif (\n+\t\t\t[...state.placements.values()].some(\n+\t\t\t\t(placement) => placement.balanceId === activation.id,\n+\t\t\t)\n+\t\t)\n+\t\t\treturn null;\n+\t\tresult = cloneState(result);\n+\t\tresult.earnedActivations = result.earnedActivations.filter(\n+\t\t\t(item) => item.id !== activation.id,\n+\t\t);\n+\t\tresult.balances = result.balances.filter((balance) => balance.id !== activation.id);\n+\t}\n+\tconst finalized = finalizeEarnedState(result, context);\n+\treturn finalized && !unsatisfiedObligationCount(finalized, context) ? finalized : null;\n+}\n+\n+function recordRuleEvaluation(\n+\tafter: State,\n+\tcontext: SearchContext,\n+\tdates: string[],\n+\tbeforeVector: PlanningObjectiveVector,\n+\tafterVector: PlanningObjectiveVector,\n+\tsourceDate?: string,\n+\tincumbentVector = beforeVector,\n+): MutableTraceCandidate | undefined {\n+\tlet evaluation: MutableTraceCandidate | undefined;\n+\tobserveTrace(context, (trace) => {\n+\t\tconst facts = objectiveComparisonFacts(beforeVector.objectives, afterVector.objectives);\n+\t\tconst placement = after.placements.get(dates[dates.length - 1]);\n+\t\tevaluation = {\n+\t\t\tstatus: 'evaluated-rejected',\n+\t\t\tdates,\n+\t\t\tdate: dates[dates.length - 1],\n+\t\t\tsourceDate,\n+\t\t\tcomparison: objectiveComparison(beforeVector, afterVector),\n+\t\t\ttechnicalComparison: facts.values,\n+\t\t\tfirstDecisiveComparator: facts.firstDecisiveComparator,\n+\t\t\t...(placement\n+\t\t\t\t? { placement: { ...placement, ruleIds: [...placement.ruleIds].sort() } }\n+\t\t\t\t: {}),\n+\t\t};\n+\t\ttrace.recordEvaluation(evaluation);\n+\t});\n+\t// The global retained plan has already examined this valid local incumbent.\n+\t// Candidates that cannot beat it do not need a duplicate global comparison.\n+\tif (compareObjectiveLists(afterVector.objectives, incumbentVector.objectives) < 0)\n+\t\tcontext.retain?.(after, undefined, afterVector);\n+\treturn evaluation;\n+}\n+\n+function typedCalendarDates(context: SearchContext): Set {\n+\tconst typedDates = new Set();\n+\tfor (const rule of context.rules) {\n+\t\tif (rule.type === 'optimization' || rule.placeType === 'any') continue;\n+\t\tconst dates =\n+\t\t\trule.type === 'time_window'\n+\t\t\t\t? context.workingDays.filter(\n+\t\t\t\t\t\t(date) => rule.startDate! <= date && date <= rule.endDate!,\n+\t\t\t\t\t)\n+\t\t\t\t: occurrences(rule, context).flatMap((occurrence) =>\n+\t\t\t\t\t\tpatternsFor(rule, occurrence, context).flat(),\n+\t\t\t\t\t);\n+\t\tfor (const date of dates) typedDates.add(date);\n+\t}\n+\treturn typedDates;\n+}\n+\n+function* calendarPlacementCandidates(\n+\tstate: State,\n+\ttargetDates: string[],\n+\truleId: string,\n+\tcontext: SearchContext,\n+\taccept: (candidate: State, dates: string[], sourceDate?: string, addition?: boolean) => boolean,\n+): PlanningSteps {\n+\tconst missing = targetDates.filter(\n+\t\t(date) => !state.placements.has(date) && !context.declaredDates.has(date),\n+\t);\n+\tif (!missing.length) return false;\n+\tconst before = optimizationObservations(state, context);\n+\tconst typedDates = typedCalendarDates(context);\n+\tconst failed = new Set();\n+\tconst rankedDonors: { date: string; objectives: PlanningObjective[] }[] = [];\n+\tfor (const placement of state.placements.values()) {\n+\t\tyield;\n+\t\tcontext.check();\n+\t\tif (targetDates.includes(placement.date)) continue;\n+\t\trankedDonors.push({\n+\t\t\tdate: placement.date,\n+\t\t\tobjectives: activeObjectiveVector(releasePlacement(state, placement.date), context),\n \t\t});\n-\tfor (const date of candidates) {\n+\t}\n+\t// shortcut: recursion retains the original donor ranking; rerank when a measured bundle misses a better allocation.\n+\trankedDonors.sort(\n+\t\t(a, b) => compareObjectiveLists(a.objectives, b.objectives) || compareDate(b.date, a.date),\n+\t);\n+\tconst fill = function* (\n+\t\tindex: number,\n+\t\tcurrent: State,\n+\t\tsources: string[] = [],\n+\t\tadditions: string[] = [],\n+\t): PlanningSteps {\n \t\tyield;\n \t\tcontext.check();\n-\t\tif (count >= rule.placeDays) break;\n-\t\trecordTraceDecision(context, [date]);\n-\t\tconst before = result;\n-\t\tlet evaluation: MutableTraceCandidate | undefined;\n-\t\tconst next = assignDate(\n-\t\t\tresult,\n-\t\t\tdate,\n-\t\t\trule.placeType,\n-\t\t\trule.id,\n-\t\t\tcontext,\n-\t\t\t(candidate) => (evaluation = candidate),\n+\t\tconst key = JSON.stringify([\n+\t\t\tindex,\n+\t\t\tcurrent.balances.map((balance) => [balance.id, balance.remaining]),\n+\t\t\t[...current.placements.values()]\n+\t\t\t\t.sort((a, b) => compareDate(a.date, b.date))\n+\t\t\t\t.map((placement) => [\n+\t\t\t\t\tplacement.date,\n+\t\t\t\t\ttargetDates.includes(placement.date)\n+\t\t\t\t\t\t? typedDates.has(placement.date)\n+\t\t\t\t\t\t\t? placement.type\n+\t\t\t\t\t\t\t: null\n+\t\t\t\t\t\t: placement.type,\n+\t\t\t\t\ttargetDates.includes(placement.date) &&\n+\t\t\t\t\t!current.balances.find((balance) => balance.id === placement.balanceId)!.earned\n+\t\t\t\t\t\t? null\n+\t\t\t\t\t\t: placement.balanceId,\n+\t\t\t\t\t[...placement.ruleIds].sort(),\n+\t\t\t\t\tplacement.supporting,\n+\t\t\t\t\tadditions.includes(placement.date),\n+\t\t\t\t]),\n+\t\t]);\n+\t\tif (failed.has(key)) return false;\n+\t\tif (index === missing.length) {\n+\t\t\tconst benefit = supportingCalendarBenefit(before, current, context);\n+\t\t\tfor (const date of additions) {\n+\t\t\t\tconst placement = current.placements.get(date)!;\n+\t\t\t\tconst balance = current.balances.find((item) => item.id === placement.balanceId)!;\n+\t\t\t\tplacement.supporting = benefit && !isAtRisk(balance, context);\n+\t\t\t}\n+\t\t\tconst accepted = accept(current, missing, sources[0], additions.length > 0);\n+\t\t\tif (!accepted) failed.add(key);\n+\t\t\treturn accepted;\n+\t\t}\n+\t\tconst date = missing[index];\n+\t\tfor (const balance of current.balances) {\n+\t\t\tif (balance.remaining <= 0 || date < balance.availableFrom || date > balance.expiryDate)\n+\t\t\t\tcontinue;\n+\t\t\tconst assigned = assignDateToBalance(\n+\t\t\t\tcurrent,\n+\t\t\t\tdate,\n+\t\t\t\tbalance.id,\n+\t\t\t\tcontext,\n+\t\t\t\tnew Set([ruleId]),\n+\t\t\t);\n+\t\t\tif (!assigned) continue;\n+\t\t\tif (yield* fill(index + 1, assigned, sources, [...additions, date])) return true;\n+\t\t}\n+\t\tconst donors = new Set();\n+\t\tfor (const donor of rankedDonors) {\n+\t\t\tyield;\n+\t\t\tconst source = current.placements.get(donor.date);\n+\t\t\tif (!source) continue;\n+\t\t\tconst balance = current.balances.find((item) => item.id === source.balanceId)!;\n+\t\t\tif (\n+\t\t\t\tdate < balance.availableFrom ||\n+\t\t\t\tdate > balance.expiryDate ||\n+\t\t\t\t!mandatoryRelocationDate(date, balance, source.ruleIds, context)\n+\t\t\t)\n+\t\t\t\tcontinue;\n+\t\t\tconst without = releasePlacement(current, source.date);\n+\t\t\tconst identity = JSON.stringify([\n+\t\t\t\tsource.balanceId,\n+\t\t\t\t[...source.ruleIds].sort(),\n+\t\t\t\tsource.supporting,\n+\t\t\t\tactiveObjectiveVector(without, context),\n+\t\t\t]);\n+\t\t\t// shortcut: equivalent donor tokens share one deterministic source; expand coordinated donor choices if a measured plan needs them.\n+\t\t\tif (donors.has(identity)) continue;\n+\t\t\tdonors.add(identity);\n+\t\t\tconst assigned = assignDateToBalance(\n+\t\t\t\twithout,\n+\t\t\t\tdate,\n+\t\t\t\tsource.balanceId,\n+\t\t\t\tcontext,\n+\t\t\t\tsource.ruleIds,\n+\t\t\t);\n+\t\t\tif (!assigned) continue;\n+\t\t\tassigned.placements.get(date)!.supporting = source.supporting;\n+\t\t\tif (yield* fill(index + 1, assigned, [...sources, source.date], additions)) return true;\n+\t\t}\n+\t\tfailed.add(key);\n+\t\treturn false;\n+\t};\n+\treturn yield* fill(0, state);\n+}\n+\n+function* holidayWeekPlacementCandidates(\n+\tstate: State,\n+\truleId: string,\n+\tcontext: SearchContext,\n+\taccept: (candidate: State, dates: string[], sourceDate?: string, addition?: boolean) => boolean,\n+): PlanningSteps {\n+\tfor (const week of context.holidayWeeks)\n+\t\tyield* calendarPlacementCandidates(state, week.dates, ruleId, context, accept);\n+}\n+\n+function* timeOffPeriodPlacementCandidates(\n+\tstate: State,\n+\truleId: string,\n+\tcontext: SearchContext,\n+\taccept: (candidate: State, dates: string[], sourceDate?: string, addition?: boolean) => boolean,\n+): PlanningSteps {\n+\tconst periods = periodData(state, context);\n+\tfor (let index = 1; index < periods.length; index++) {\n+\t\tconst dates = context.workingDays.filter(\n+\t\t\t(date) => date > periods[index - 1].end && date < periods[index].start,\n \t\t);\n-\t\t// A later preference can extend the generating period of an earned\n-\t\t// entitlement. Reject that candidate immediately instead of allowing an\n-\t\t// optional preference to turn the final plan into a conflict.\n-\t\tconst feasible = next ? finalizeEarnedState(next, context) : null;\n-\t\tif (feasible) {\n-\t\t\tif (context.traceBranchActive) {\n-\t\t\t\tconst parent = retainAndRecordBranchMutation(\n+\t\tif (dates.length > 1)\n+\t\t\tyield* calendarPlacementCandidates(state, dates, ruleId, context, accept);\n+\t}\n+}\n+\n+function evaluateRuleCandidate(\n+\tbefore: State,\n+\tcandidate: State | null,\n+\tcontext: SearchContext,\n+\tthroughIndex: number,\n+\tdates: string[],\n+\tsourceDate?: string,\n+\taddition = false,\n+\tbaseline = activeObjectiveVector(before, context, throughIndex),\n+\tbeforeVector = objectiveVector(before, context),\n+\tincumbentVector = beforeVector,\n+):\n+\t| { state: State; vector: PlanningObjectiveVector; evaluation?: MutableTraceCandidate }\n+\t| undefined {\n+\tif (!candidate) return undefined;\n+\tconst state = finalizeRuleCandidate(candidate, context, before);\n+\tif (!state) return undefined;\n+\tconst active = activeObjectiveVector(state, context);\n+\tconst comparison = compareObjectiveLists(active.slice(0, throughIndex + 1), baseline);\n+\tconst vector = objectiveVector(state, context, active);\n+\tconst evaluation = recordRuleEvaluation(\n+\t\tstate,\n+\t\tcontext,\n+\t\tdates,\n+\t\tbeforeVector,\n+\t\tvector,\n+\t\tsourceDate,\n+\t\tincumbentVector,\n+\t);\n+\t// shortcut: single additions cannot cross equal-value plateaus; add coordinated balance bundles when a measured configuration needs them.\n+\tif (comparison > 0 || (addition && comparison === 0)) return undefined;\n+\treturn { state, vector, evaluation };\n+}\n+\n+/** Only the complete sequence change is compared; a partial gap fill can worsen the deficit. */\n+function* workSequencePlacementCandidates(\n+\tstate: State,\n+\trule: NormalizedOptimizationRule,\n+\tcontext: SearchContext,\n+\tconsider: (candidate: State, dates: string[]) => boolean,\n+): PlanningSteps {\n+\tconst configuration = rule.configuration;\n+\tif (configuration.direction !== 'minimize') return;\n+\tconst sequences = workSequenceDates(state, context).filter(\n+\t\t({ dates, internal }) =>\n+\t\t\tdates.length > 0 && (!configuration.conditions.includes('internal') || internal),\n+\t);\n+\tconst bundles: string[][][] = [];\n+\tif (configuration.aggregation === 'count')\n+\t\tbundles.push(...sequences.map(({ dates }) => dates.map((date) => [date])));\n+\telse if (configuration.measure === 'work-sequence-deficit') {\n+\t\tconst short = sequences.filter(({ dates }) => dates.length < configuration.thresholdDays);\n+\t\tif (configuration.aggregation === 'maximum') {\n+\t\t\tconst shortest = Math.min(...short.map(({ dates }) => dates.length));\n+\t\t\tbundles.push(\n+\t\t\t\tshort\n+\t\t\t\t\t.filter(({ dates }) => dates.length === shortest)\n+\t\t\t\t\t.flatMap(({ dates }) => dates.map((date) => [date])),\n+\t\t\t);\n+\t\t} else bundles.push(...short.map(({ dates }) => dates.map((date) => [date])));\n+\t} else if (\n+\t\tconfiguration.measure === 'work-sequence-length' &&\n+\t\tconfiguration.aggregation === 'maximum'\n+\t) {\n+\t\tconst maximum = Math.max(0, ...sequences.map(({ dates }) => dates.length));\n+\t\tconst tied = sequences.filter(({ dates }) => dates.length === maximum);\n+\t\tif (tied.length > 1) {\n+\t\t\tfor (const offset of [0, 1]) {\n+\t\t\t\tconst bundle: string[][] = [];\n+\t\t\t\tfor (const { dates } of tied) {\n+\t\t\t\t\tconst middle = Math.floor((dates.length - 1 + offset) / 2);\n+\t\t\t\t\tconst centered = dates\n+\t\t\t\t\t\t.map((date, index) => ({ date, index }))\n+\t\t\t\t\t\t.sort(\n+\t\t\t\t\t\t\t(a, b) =>\n+\t\t\t\t\t\t\t\tMath.abs(a.index - middle) - Math.abs(b.index - middle) ||\n+\t\t\t\t\t\t\t\tcompareDate(a.date, b.date),\n+\t\t\t\t\t\t);\n+\t\t\t\t\tconst eligible = [\n+\t\t\t\t\t\t...new Set(\n+\t\t\t\t\t\t\tstate.balances\n+\t\t\t\t\t\t\t\t.filter((balance) => balance.remaining > 0)\n+\t\t\t\t\t\t\t\t.map(\n+\t\t\t\t\t\t\t\t\t(balance) =>\n+\t\t\t\t\t\t\t\t\t\tcentered.find(\n+\t\t\t\t\t\t\t\t\t\t\t({ date }) =>\n+\t\t\t\t\t\t\t\t\t\t\t\tbalance.availableFrom <= date &&\n+\t\t\t\t\t\t\t\t\t\t\t\tdate <= balance.expiryDate,\n+\t\t\t\t\t\t\t\t\t\t)?.date,\n+\t\t\t\t\t\t\t\t)\n+\t\t\t\t\t\t\t\t.filter((date): date is string => date !== undefined),\n+\t\t\t\t\t\t),\n+\t\t\t\t\t];\n+\t\t\t\t\tif (!eligible.length) break;\n+\t\t\t\t\tbundle.push(\n+\t\t\t\t\t\teligible.sort(\n+\t\t\t\t\t\t\t(a, b) =>\n+\t\t\t\t\t\t\t\tcentered.findIndex(({ date }) => date === a) -\n+\t\t\t\t\t\t\t\tcentered.findIndex(({ date }) => date === b),\n+\t\t\t\t\t\t),\n+\t\t\t\t\t);\n+\t\t\t\t}\n+\t\t\t\tif (bundle.length === tied.length) bundles.push(bundle);\n+\t\t\t}\n+\t\t}\n+\t}\n+\tconst before = optimizationObservations(state, context);\n+\tconst available = state.balances.reduce((total, balance) => total + balance.remaining, 0);\n+\tconst typedDates = typedCalendarDates(context);\n+\tconst failedAssignments = new Set();\n+\tfunction* assignBundle(\n+\t\tcandidate: State,\n+\t\tslots: string[][],\n+\t\tdates: string[] = [],\n+\t): PlanningSteps {\n+\t\tyield;\n+\t\tcontext.check();\n+\t\t// Equivalent rejected allocations differ only in non-earned balance provenance.\n+\t\tconst key = JSON.stringify([\n+\t\t\tslots,\n+\t\t\tdates,\n+\t\t\tcandidate.balances.map(({ id, remaining }) => [id, remaining]),\n+\t\t\tdates.map((date) => {\n+\t\t\t\tconst placement = candidate.placements.get(date)!;\n+\t\t\t\tconst balance = candidate.balances.find((item) => item.id === placement.balanceId)!;\n+\t\t\t\treturn [\n+\t\t\t\t\ttypedDates.has(date) ? placement.type : undefined,\n+\t\t\t\t\tbalance.earned ? balance.id : undefined,\n+\t\t\t\t];\n+\t\t\t}),\n+\t\t]);\n+\t\tif (failedAssignments.has(key)) return false;\n+\t\tif (dates.length === slots.length) {\n+\t\t\tconst supporting = supportingCalendarBenefit(before, candidate, context);\n+\t\t\tfor (const date of dates) {\n+\t\t\t\tconst placement = candidate.placements.get(date)!;\n+\t\t\t\tconst balance = candidate.balances.find((item) => item.id === placement.balanceId)!;\n+\t\t\t\tplacement.supporting = supporting && !isAtRisk(balance, context);\n+\t\t\t}\n+\t\t\tconst accepted = consider(candidate, dates);\n+\t\t\tif (!accepted) failedAssignments.add(key);\n+\t\t\treturn accepted;\n+\t\t}\n+\t\tfor (const date of slots[dates.length]) {\n+\t\t\tfor (const next of assignDateVariants(candidate, date, 'any', rule.id, context))\n+\t\t\t\tif (yield* assignBundle(next, slots, [...dates, date])) return true;\n+\t\t}\n+\t\tfailedAssignments.add(key);\n+\t\treturn false;\n+\t}\n+\t// shortcut: bundles keep the first accepted allocation and nearest center per balance; extend when a measured case needs another coordinated allocation.\n+\tconst examined = new Set();\n+\tfor (const slots of bundles) {\n+\t\tyield;\n+\t\tconst key = JSON.stringify(slots);\n+\t\tif (slots.length <= 1 || slots.length > available || examined.has(key)) continue;\n+\t\texamined.add(key);\n+\t\tyield* assignBundle(state, slots);\n+\t}\n+}\n+\n+/** Candidate additions need an active rule improvement; expiry and date ties only reshape existing placements. */\n+function* optimizeRulePlacements(\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tthroughIndex: number,\n+\tallowAdd: boolean,\n+\trule?: NormalizedRule,\n+): PlanningSteps {\n+\tlet result = state;\n+\tconst addingBalanceQuantity =\n+\t\tallowAdd &&\n+\t\trule?.type === 'optimization' &&\n+\t\trule.configuration.elements === 'leave-balances' &&\n+\t\trule.configuration.measure === 'unplaced-quantity' &&\n+\t\trule.configuration.aggregation === 'sum' &&\n+\t\trule.configuration.direction === 'minimize';\n+\tconst equivalentAdditionFunding =\n+\t\taddingBalanceQuantity &&\n+\t\tthroughIndex === 0 &&\n+\t\t!context.rules.some((item) => item.enabled && item.type === 'if_then') &&\n+\t\tcontext.rules.every(\n+\t\t\t(item) =>\n+\t\t\t\t!item.enabled ||\n+\t\t\t\titem.type !== 'optimization' ||\n+\t\t\t\titem.configuration.elements !== 'leave-balances' ||\n+\t\t\t\titem.configuration.aggregation !== 'maximum',\n+\t\t);\n+\tconst fundingWindows = context.rules.filter(\n+\t\t(item): item is NormalizedCalendarRule => item.enabled && item.type === 'time_window',\n+\t);\n+\tconst preferencePrefix = context.rules\n+\t\t.filter((item) => item.enabled && item.force === 'preference')\n+\t\t.slice(0, throughIndex + 1);\n+\tconst prefixBounds = preferencePrefix.map((item, index): number | undefined => {\n+\t\tif (index === 0)\n+\t\t\treturn item.type === 'optimization' &&\n+\t\t\t\titem.configuration.elements === 'leave-balances' &&\n+\t\t\t\titem.configuration.measure === 'unplaced-quantity' &&\n+\t\t\t\titem.configuration.aggregation === 'sum' &&\n+\t\t\t\titem.configuration.direction === 'minimize'\n+\t\t\t\t? 0\n+\t\t\t\t: undefined;\n+\t\tif (item.type === 'time_window') return item.placeDays;\n+\t\tif (\n+\t\t\titem.type === 'optimization' &&\n+\t\t\titem.configuration.elements === 'public-holiday-weeks' &&\n+\t\t\titem.configuration.measure === 'public-holiday-week-value' &&\n+\t\t\titem.configuration.direction === 'maximize'\n+\t\t)\n+\t\t\treturn evaluateOptimization(item.configuration, {\n+\t\t\t\tleaveBalances: [],\n+\t\t\t\tpublicHolidayWeeks: context.holidayWeeks.map(({ value }) => ({\n+\t\t\t\t\tvalue,\n+\t\t\t\t\tcomplete: true,\n+\t\t\t\t})),\n+\t\t\t\ttimeOffPeriods: [],\n+\t\t\t\tworkSequences: [],\n+\t\t\t\tleavePlacements: [],\n+\t\t\t});\n+\t\treturn undefined;\n+\t});\n+\tconst dateInvariantObjectives = context.rules\n+\t\t.filter((item) => item.force === 'preference')\n+\t\t.every(\n+\t\t\t(item) =>\n+\t\t\t\titem.type === 'optimization' &&\n+\t\t\t\t(item.configuration!.elements === 'leave-balances' ||\n+\t\t\t\t\titem.configuration!.elements === 'leave-placements'),\n+\t\t);\n+\twhile (true) {\n+\t\tyield;\n+\t\tcontext.check();\n+\t\tconst active = activeObjectiveVector(result, context);\n+\t\tconst baseline = active.slice(0, throughIndex + 1);\n+\t\tconst beforeVector = objectiveVector(result, context, active);\n+\t\tcontext.retain?.(result, undefined, beforeVector);\n+\t\tif (\n+\t\t\tallowAdd &&\n+\t\t\tprefixBounds.length > 0 &&\n+\t\t\tprefixBounds.every(\n+\t\t\t\t(bound, index) => bound !== undefined && active[index].value === bound,\n+\t\t\t)\n+\t\t) {\n+\t\t\trecordTraceCandidate(context, {\n+\t\t\t\tstatus: 'not-examined',\n+\t\t\t\treason: reason(\n+\t\t\t\t\tthroughIndex === 0\n+\t\t\t\t\t\t? 'quantity-prefix-lower-bound'\n+\t\t\t\t\t\t: preferencePrefix.some(\n+\t\t\t\t\t\t\t\t\t(item) =>\n+\t\t\t\t\t\t\t\t\t\titem.type === 'optimization' &&\n+\t\t\t\t\t\t\t\t\t\titem.configuration.elements === 'public-holiday-weeks',\n+\t\t\t\t\t\t\t )\n+\t\t\t\t\t\t\t? 'satisfied-holiday-prefix-bound'\n+\t\t\t\t\t\t\t: 'satisfied-window-prefix-bound',\n+\t\t\t\t\t'The active quantity, window and holiday-week prefix has reached every configured bound; later preference stages and final tie-breaks remain to be evaluated.',\n+\t\t\t\t\tpreferencePrefix.map(({ id }) => id),\n+\t\t\t\t),\n+\t\t\t});\n+\t\t\treturn result;\n+\t\t}\n+\t\tconst genericStateKey =\n+\t\t\tallowAdd &&\n+\t\t\tresult.balances.every(({ remaining }) => remaining === 0) &&\n+\t\t\t!context.rules.some((item) => item.enabled && item.type === 'if_then')\n+\t\t\t\t? preferenceStateKey(result)\n+\t\t\t\t: undefined;\n+\t\tconst reuseGeneric =\n+\t\t\tgenericStateKey !== undefined && context.completedGenericState === genericStateKey;\n+\t\tconst compareEquivalentFunding =\n+\t\t\tequivalentAdditionFunding &&\n+\t\t\tresult.earnedActivations.length === 0 &&\n+\t\t\tNumber.isSafeInteger(\n+\t\t\t\tresult.balances.reduce((sum, balance) => sum + balance.remaining, 0),\n+\t\t\t);\n+\t\tlet beforeCalendar: OptimizationObservations | undefined;\n+\t\tlet best = result;\n+\t\tlet bestVector = beforeVector;\n+\t\tlet bestEvaluation: MutableTraceCandidate | undefined;\n+\t\tlet bestDates: string[] = [];\n+\t\tconst consider = (\n+\t\t\tcandidate: State | null,\n+\t\t\tdates: string[],\n+\t\t\tsourceDate?: string,\n+\t\t\taddition = false,\n+\t\t): boolean => {\n+\t\t\tconst evaluated = evaluateRuleCandidate(\n+\t\t\t\tresult,\n+\t\t\t\tcandidate,\n+\t\t\t\tcontext,\n+\t\t\t\tthroughIndex,\n+\t\t\t\tdates,\n+\t\t\t\tsourceDate,\n+\t\t\t\taddition,\n+\t\t\t\tbaseline,\n+\t\t\t\tbeforeVector,\n+\t\t\t\tbestVector,\n+\t\t\t);\n+\t\t\tif (!evaluated) return false;\n+\t\t\tconst compared = compareObjectiveLists(\n+\t\t\t\tevaluated.vector.objectives,\n+\t\t\t\tbestVector.objectives,\n+\t\t\t);\n+\t\t\tif (evaluated.evaluation) {\n+\t\t\t\tconst facts = objectiveComparisonFacts(\n+\t\t\t\t\tbestVector.objectives,\n+\t\t\t\t\tevaluated.vector.objectives,\n+\t\t\t\t);\n+\t\t\t\tevaluated.evaluation.technicalComparison = facts.values;\n+\t\t\t\tevaluated.evaluation.firstDecisiveComparator = facts.firstDecisiveComparator;\n+\t\t\t\tif (compared >= 0)\n+\t\t\t\t\tevaluated.evaluation.reason = reason(\n+\t\t\t\t\t\t'incumbent-comparison',\n+\t\t\t\t\t\t'This candidate did not improve the current best result.',\n+\t\t\t\t\t);\n+\t\t\t\tobserveTrace(context, (trace) => trace.updateEvaluation(evaluated.evaluation!));\n+\t\t\t}\n+\t\t\tif (compared >= 0) return true;\n+\t\t\tbest = evaluated.state;\n+\t\t\tbestVector = evaluated.vector;\n+\t\t\tbestEvaluation = evaluated.evaluation;\n+\t\t\tbestDates = dates;\n+\t\t\treturn true;\n+\t\t};\n+\t\tconst dates = [...context.workingDays].sort(\n+\t\t\t(a, b) => Number(result.placements.has(a)) - Number(result.placements.has(b)),\n+\t\t);\n+\t\t// shortcut: loaded plans sample flexible move destinations, upgrade to interval search when a measured case misses a better plan.\n+\t\tconst moveDates =\n+\t\t\tresult.placements.size <= 24\n+\t\t\t\t? context.workingDays\n+\t\t\t\t: context.workingDays.filter(\n+\t\t\t\t\t\t(date, index) =>\n+\t\t\t\t\t\t\t!isWorking(addDays(date, -1), context.holidays) ||\n+\t\t\t\t\t\t\t!isWorking(addDays(date, 1), context.holidays) ||\n+\t\t\t\t\t\t\tcontext.declaredDates.has(addDays(date, -1)) ||\n+\t\t\t\t\t\t\tcontext.declaredDates.has(addDays(date, 1)) ||\n+\t\t\t\t\t\t\tindex % 7 === 0 ||\n+\t\t\t\t\t\t\tcontext.rules.some(\n+\t\t\t\t\t\t\t\t(item) =>\n+\t\t\t\t\t\t\t\t\titem.type === 'time_window' &&\n+\t\t\t\t\t\t\t\t\tdate >= item.startDate! &&\n+\t\t\t\t\t\t\t\t\tdate <= item.endDate!,\n+\t\t\t\t\t\t\t),\n+\t\t\t\t\t);\n+\t\tif (\n+\t\t\tallowAdd &&\n+\t\t\trule?.type === 'optimization' &&\n+\t\t\trule.configuration.elements === 'work-sequences'\n+\t\t)\n+\t\t\tyield* workSequencePlacementCandidates(result, rule, context, (candidate, dates) =>\n+\t\t\t\tconsider(candidate, dates, undefined, true),\n+\t\t\t);\n+\t\tif (\n+\t\t\tallowAdd &&\n+\t\t\trule?.type === 'optimization' &&\n+\t\t\trule.configuration.elements === 'public-holiday-weeks' &&\n+\t\t\trule.configuration.conditions.includes('complete') &&\n+\t\t\trule.configuration.direction === 'maximize'\n+\t\t)\n+\t\t\tyield* holidayWeekPlacementCandidates(result, rule.id, context, consider);\n+\t\tif (\n+\t\t\tallowAdd &&\n+\t\t\trule?.type === 'optimization' &&\n+\t\t\trule.configuration.elements === 'time-off-periods' &&\n+\t\t\t((rule.configuration.aggregation === 'maximum' &&\n+\t\t\t\trule.configuration.direction === 'maximize') ||\n+\t\t\t\t(rule.configuration.aggregation === 'count' &&\n+\t\t\t\t\trule.configuration.direction === 'minimize'))\n+\t\t)\n+\t\t\tyield* timeOffPeriodPlacementCandidates(result, rule.id, context, consider);\n+\t\t// shortcut: commit a strict bundle prefix improvement before exploring old-state\n+\t\t// generic alternatives; upgrade to a combined frontier if measured cases need it.\n+\t\tconst deferGeneric =\n+\t\t\tallowAdd &&\n+\t\t\tbest !== result &&\n+\t\t\tcompareObjectiveLists(bestVector.objectives.slice(1, throughIndex + 2), baseline) < 0;\n+\t\tif (deferGeneric)\n+\t\t\trecordTraceCandidate(context, {\n+\t\t\t\tstatus: 'not-examined',\n+\t\t\t\treason: reason(\n+\t\t\t\t\t'strict-prefix-bundle-progress',\n+\t\t\t\t\t'A finalized rule-specific bundle strictly improved the active prefix; generic alternatives for the previous state were deferred before continuing from that improvement.',\n+\t\t\t\t\trule ? [rule.id] : undefined,\n+\t\t\t\t),\n+\t\t\t});\n+\t\tif (reuseGeneric)\n+\t\t\trecordTraceCandidate(context, {\n+\t\t\t\tstatus: 'not-examined',\n+\t\t\t\treason: reason(\n+\t\t\t\t\t'unchanged-generic-state',\n+\t\t\t\t\t'The configured sampled generic neighborhood was already exhausted for this unchanged state; rule-specific bundles were examined separately.',\n+\t\t\t\t),\n+\t\t\t});\n+\t\tfor (const date of reuseGeneric || deferGeneric ? [] : dates) {\n+\t\t\tyield;\n+\t\t\tcontext.check();\n+\t\t\tif (context.declaredDates.has(date)) continue;\n+\t\t\tconst existing = result.placements.get(date);\n+\t\t\tif (!existing && allowAdd) {\n+\t\t\t\tif (\n+\t\t\t\t\trule?.type === 'time_window' &&\n+\t\t\t\t\t(date < rule.startDate! || date > rule.endDate!)\n+\t\t\t\t)\n+\t\t\t\t\tcontinue;\n+\t\t\t\tconst evaluatedFunding = new Set();\n+\t\t\t\tfor (const balance of result.balances) {\n+\t\t\t\t\tyield;\n+\t\t\t\t\tif (\n+\t\t\t\t\t\trule?.type === 'time_window' &&\n+\t\t\t\t\t\t!selectorMatches(rule.placeType, balance.type)\n+\t\t\t\t\t)\n+\t\t\t\t\t\tcontinue;\n+\t\t\t\t\tif (\n+\t\t\t\t\t\tbalance.remaining <= 0 ||\n+\t\t\t\t\t\tbalance.availableFrom > date ||\n+\t\t\t\t\t\tbalance.expiryDate < date\n+\t\t\t\t\t)\n+\t\t\t\t\t\tcontinue;\n+\t\t\t\t\t// Complete single additions with equal expiry/window scores cannot beat the\n+\t\t\t\t\t// first evaluated funder. Recursive bundles still need every funding choice.\n+\t\t\t\t\tconst fundingKey =\n+\t\t\t\t\t\tcompareEquivalentFunding && isAtRisk(balance, context)\n+\t\t\t\t\t\t\t? `${balance.expiryDate}:${fundingWindows\n+\t\t\t\t\t\t\t\t\t.map((window) =>\n+\t\t\t\t\t\t\t\t\t\tNumber(\n+\t\t\t\t\t\t\t\t\t\t\tdate >= window.startDate! &&\n+\t\t\t\t\t\t\t\t\t\t\t\tdate <= window.endDate! &&\n+\t\t\t\t\t\t\t\t\t\t\t\tselectorMatches(window.placeType, balance.type),\n+\t\t\t\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t\t\t\t)\n+\t\t\t\t\t\t\t\t\t.join('')}`\n+\t\t\t\t\t\t\t: undefined;\n+\t\t\t\t\tif (fundingKey !== undefined && evaluatedFunding.has(fundingKey)) {\n+\t\t\t\t\t\trecordTraceCandidate(context, {\n+\t\t\t\t\t\t\tstatus: 'not-examined',\n+\t\t\t\t\t\t\tdate,\n+\t\t\t\t\t\t\tplacement: {\n+\t\t\t\t\t\t\t\tdate,\n+\t\t\t\t\t\t\t\tbalanceId: balance.id,\n+\t\t\t\t\t\t\t\ttype: balance.type,\n+\t\t\t\t\t\t\t\tsupporting: false,\n+\t\t\t\t\t\t\t\truleIds: [rule!.id],\n+\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\treason: reason(\n+\t\t\t\t\t\t\t\t'equivalent-date-funding',\n+\t\t\t\t\t\t\t\t'An earlier valid finalized funder has identical active objective values and final ties for this date.',\n+\t\t\t\t\t\t\t\t[rule!.id],\n+\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t});\n+\t\t\t\t\t\tcontinue;\n+\t\t\t\t\t}\n+\t\t\t\t\tconst assigned = assignDateToBalance(\n+\t\t\t\t\t\tresult,\n+\t\t\t\t\t\tdate,\n+\t\t\t\t\t\tbalance.id,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\trule ? new Set([rule.id]) : new Set(),\n+\t\t\t\t\t);\n+\t\t\t\t\tif (assigned && rule?.type === 'optimization' && !isAtRisk(balance, context)) {\n+\t\t\t\t\t\tbeforeCalendar ??= optimizationObservations(result, context);\n+\t\t\t\t\t\tassigned.placements.get(date)!.supporting = supportingCalendarBenefit(\n+\t\t\t\t\t\t\tbeforeCalendar,\n+\t\t\t\t\t\t\tassigned,\n+\t\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\t);\n+\t\t\t\t\t}\n+\t\t\t\t\tconst evaluated = consider(assigned, [date], undefined, true);\n+\t\t\t\t\tif (evaluated && fundingKey !== undefined) evaluatedFunding.add(fundingKey);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif (!existing || (addingBalanceQuantity && best !== result)) continue;\n+\t\t\tconst without = releasePlacement(result, date);\n+\t\t\tconsider(without, [date], date);\n+\t\t\tfor (const balance of without.balances) {\n+\t\t\t\tyield;\n+\t\t\t\tif (\n+\t\t\t\t\tbalance.id === existing.balanceId ||\n+\t\t\t\t\tbalance.remaining <= 0 ||\n+\t\t\t\t\tbalance.availableFrom > date ||\n+\t\t\t\t\tbalance.expiryDate < date\n+\t\t\t\t)\n+\t\t\t\t\tcontinue;\n+\t\t\t\tconst reassigned = assignDateToBalance(\n+\t\t\t\t\twithout,\n+\t\t\t\t\tdate,\n+\t\t\t\t\tbalance.id,\n \t\t\t\t\tcontext,\n-\t\t\t\t\tbefore,\n-\t\t\t\t\tfeasible,\n-\t\t\t\t\tcontext.traceBranchParentId,\n-\t\t\t\t\tevaluation,\n-\t\t\t\t\t[date],\n+\t\t\t\t\texisting.ruleIds,\n \t\t\t\t);\n-\t\t\t\tcontext.traceBranchParentId = parent ?? context.traceBranchParentId;\n-\t\t\t} else retainAndRecordState(context, feasible, evaluation);\n-\t\t\tresult = feasible;\n-\t\t\tcount++;\n+\t\t\t\tif (reassigned)\n+\t\t\t\t\treassigned.placements.get(date)!.supporting =\n+\t\t\t\t\t\texisting.supporting && !isAtRisk(balance, context);\n+\t\t\t\tconsider(reassigned, [date], date);\n+\t\t\t}\n+\t\t\tfor (const destination of moveDates) {\n+\t\t\t\tyield;\n+\t\t\t\tcontext.check();\n+\t\t\t\tif (destination === date || context.declaredDates.has(destination)) continue;\n+\t\t\t\tconst other = without.placements.get(destination);\n+\t\t\t\tif (other) {\n+\t\t\t\t\tif (other.balanceId === existing.balanceId) continue;\n+\t\t\t\t\tconst swapped = releasePlacement(without, destination);\n+\t\t\t\t\tconst first = assignDateToBalance(\n+\t\t\t\t\t\tswapped,\n+\t\t\t\t\t\tdestination,\n+\t\t\t\t\t\texisting.balanceId,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\texisting.ruleIds,\n+\t\t\t\t\t);\n+\t\t\t\t\tconst second =\n+\t\t\t\t\t\tfirst &&\n+\t\t\t\t\t\tassignDateToBalance(first, date, other.balanceId, context, other.ruleIds);\n+\t\t\t\t\tif (second) {\n+\t\t\t\t\t\tsecond.placements.get(destination)!.supporting = existing.supporting;\n+\t\t\t\t\t\tsecond.placements.get(date)!.supporting = other.supporting;\n+\t\t\t\t\t}\n+\t\t\t\t\tconsider(second, [date, destination], date);\n+\t\t\t\t} else {\n+\t\t\t\t\tconst moved = assignDateToBalance(\n+\t\t\t\t\t\twithout,\n+\t\t\t\t\t\tdestination,\n+\t\t\t\t\t\texisting.balanceId,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\texisting.ruleIds,\n+\t\t\t\t\t);\n+\t\t\t\t\tif (moved) moved.placements.get(destination)!.supporting = existing.supporting;\n+\t\t\t\t\tif (\n+\t\t\t\t\t\tmoved &&\n+\t\t\t\t\t\tdateInvariantObjectives &&\n+\t\t\t\t\t\tcompareObjectiveLists(\n+\t\t\t\t\t\t\ttieBreakObjectives(moved),\n+\t\t\t\t\t\t\tbeforeVector.objectives.slice(-2),\n+\t\t\t\t\t\t) >= 0\n+\t\t\t\t\t) {\n+\t\t\t\t\t\trecordTraceCandidate(context, {\n+\t\t\t\t\t\t\tstatus: 'pruned',\n+\t\t\t\t\t\t\tdate: destination,\n+\t\t\t\t\t\t\tsourceDate: date,\n+\t\t\t\t\t\t\treason: reason(\n+\t\t\t\t\t\t\t\t'unchanged-objective-tie-bound',\n+\t\t\t\t\t\t\t\t'The move preserves every active rule value and cannot improve the final tie-breaks.',\n+\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t});\n+\t\t\t\t\t\tcontinue;\n+\t\t\t\t\t}\n+\t\t\t\t\tconsider(moved, [destination], date);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif (moveDates.length < context.workingDays.length) {\n+\t\t\t\tconst examined = new Set(moveDates);\n+\t\t\t\tfor (const destination of context.workingDays) {\n+\t\t\t\t\tif (examined.has(destination)) continue;\n+\t\t\t\t\trecordTraceCandidate(context, {\n+\t\t\t\t\t\tstatus: 'not-examined',\n+\t\t\t\t\t\tdate: destination,\n+\t\t\t\t\t\tsourceDate: date,\n+\t\t\t\t\t\treason: reason(\n+\t\t\t\t\t\t\t'loaded-plan-sampling',\n+\t\t\t\t\t\t\t'This move destination was not examined in a loaded plan.',\n+\t\t\t\t\t\t),\n+\t\t\t\t\t});\n+\t\t\t\t}\n+\t\t\t}\n \t\t}\n+\t\tif (\n+\t\t\tallowAdd &&\n+\t\t\t(addingBalanceQuantity ||\n+\t\t\t\t(rule?.type === 'time_window' &&\n+\t\t\t\t\tNumber(active[throughIndex].value) < rule.placeDays)) &&\n+\t\t\tcompareObjectiveLists(bestVector.objectives.slice(1, throughIndex + 2), baseline) === 0\n+\t\t) {\n+\t\t\tfor (const balance of result.balances) {\n+\t\t\t\tif (balance.remaining <= 0) continue;\n+\t\t\t\tfor (const date of result.placements.keys()) {\n+\t\t\t\t\tyield;\n+\t\t\t\t\tif (date < balance.availableFrom || date > balance.expiryDate) continue;\n+\t\t\t\t\tconst sourceRuleApplies =\n+\t\t\t\t\t\trule?.type !== 'time_window' ||\n+\t\t\t\t\t\t(date >= rule.startDate! &&\n+\t\t\t\t\t\t\tdate <= rule.endDate! &&\n+\t\t\t\t\t\t\tselectorMatches(rule.placeType, balance.type));\n+\t\t\t\t\tyield* relocateForAddition(\n+\t\t\t\t\t\tresult,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\tdate,\n+\t\t\t\t\t\tbalance.id,\n+\t\t\t\t\t\trule && sourceRuleApplies ? new Set([rule.id]) : new Set(),\n+\t\t\t\t\t\tfalse,\n+\t\t\t\t\t\t(candidate, dates) => {\n+\t\t\t\t\t\t\tif (rule?.type === 'optimization' && !isAtRisk(balance, context)) {\n+\t\t\t\t\t\t\t\tbeforeCalendar ??= optimizationObservations(result, context);\n+\t\t\t\t\t\t\t\tcandidate.placements.get(date)!.supporting =\n+\t\t\t\t\t\t\t\t\tsupportingCalendarBenefit(beforeCalendar, candidate, context);\n+\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\treturn consider(candidate, dates, date, true);\n+\t\t\t\t\t\t},\n+\t\t\t\t\t);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t}\n+\t\tif (best === result) {\n+\t\t\t// Admit only a completed fixed point, after both bundles and the generic scan.\n+\t\t\tif (genericStateKey !== undefined) context.completedGenericState = genericStateKey;\n+\t\t\treturn result;\n+\t\t}\n+\t\tbest = reconcileOptimizationProvenance(best, context, result, bestVector.objectives);\n+\t\tif (context.traceBranchActive) {\n+\t\t\tconst parent = retainAndRecordBranchMutation(\n+\t\t\t\tcontext,\n+\t\t\t\tresult,\n+\t\t\t\tbest,\n+\t\t\t\tcontext.traceBranchParentId,\n+\t\t\t\tbestEvaluation,\n+\t\t\t\tbestDates,\n+\t\t\t);\n+\t\t\tcontext.traceBranchParentId = parent ?? context.traceBranchParentId;\n+\t\t} else retainAndRecordState(context, best, bestEvaluation);\n+\t\tresult = best;\n \t}\n-\treturn { state: result, count };\n+}\n+\n+function associateCalendarPreference(\n+\tstate: State,\n+\trule: NormalizedCalendarRule,\n+\tcontext: SearchContext,\n+): State {\n+\tconst result = cloneState(state);\n+\tconst dates =\n+\t\trule.type === 'time_window'\n+\t\t\t? [...result.placements.values()]\n+\t\t\t\t\t.filter(\n+\t\t\t\t\t\t(placement) =>\n+\t\t\t\t\t\t\tplacement.date >= rule.startDate! &&\n+\t\t\t\t\t\t\tplacement.date <= rule.endDate! &&\n+\t\t\t\t\t\t\tselectorMatches(rule.placeType, placement.type),\n+\t\t\t\t\t)\n+\t\t\t\t\t.sort((a, b) => Number(b.ruleIds.has(rule.id)) - Number(a.ruleIds.has(rule.id)))\n+\t\t\t\t\t.slice(\n+\t\t\t\t\t\t0,\n+\t\t\t\t\t\tMath.max(0, rule.placeDays - declaredWindowDays(rule, context).length),\n+\t\t\t\t\t)\n+\t\t\t\t\t.map((placement) => placement.date)\n+\t\t\t: occurrences(rule, context).flatMap(\n+\t\t\t\t\t(occurrence) =>\n+\t\t\t\t\t\tselectedOccurrencePattern(rule, occurrence, result, context) ?? [],\n+\t\t\t\t);\n+\tfor (const date of dates) {\n+\t\tconst placement = result.placements.get(date);\n+\t\tif (!placement) continue;\n+\t\tplacement.ruleIds.add(rule.id);\n+\t\tplacement.supporting = false;\n+\t}\n+\treturn result;\n+}\n+\n+/** Complete the entire typed pattern before checking the ordered objectives. */\n+function* preferencePatternVariants(\n+\tstate: State,\n+\tpattern: string[],\n+\trule: NormalizedCalendarRule,\n+\tcontext: SearchContext,\n+): PlanningSteps {\n+\tlet variants = [state];\n+\tfor (const date of pattern) {\n+\t\tyield;\n+\t\tconst next: State[] = [];\n+\t\tfor (const current of variants) {\n+\t\t\tyield;\n+\t\t\tconst existing = current.placements.get(date);\n+\t\t\tif (!existing || selectorMatches(rule.placeType, existing.type)) {\n+\t\t\t\tif (declaredPatternDay(date, rule.placeType, context)) next.push(current);\n+\t\t\t\telse\n+\t\t\t\t\tnext.push(\n+\t\t\t\t\t\t...assignDateVariants(current, date, rule.placeType, rule.id, context),\n+\t\t\t\t\t);\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\tconst without = releasePlacement(current, date);\n+\t\t\tfor (const balance of without.balances) {\n+\t\t\t\tyield;\n+\t\t\t\tif (!selectorMatches(rule.placeType, balance.type)) continue;\n+\t\t\t\tconst reassigned = assignDateToBalance(\n+\t\t\t\t\twithout,\n+\t\t\t\t\tdate,\n+\t\t\t\t\tbalance.id,\n+\t\t\t\t\tcontext,\n+\t\t\t\t\tnew Set([rule.id]),\n+\t\t\t\t);\n+\t\t\t\tif (reassigned) next.push(reassigned);\n+\t\t\t}\n+\t\t\tfor (const other of without.placements.values()) {\n+\t\t\t\tyield;\n+\t\t\t\tif (pattern.includes(other.date) || !selectorMatches(rule.placeType, other.type))\n+\t\t\t\t\tcontinue;\n+\t\t\t\tconst released = releasePlacement(without, other.date);\n+\t\t\t\tconst first = assignDateToBalance(\n+\t\t\t\t\treleased,\n+\t\t\t\t\tdate,\n+\t\t\t\t\tother.balanceId,\n+\t\t\t\t\tcontext,\n+\t\t\t\t\tnew Set([...other.ruleIds, rule.id]),\n+\t\t\t\t);\n+\t\t\t\tconst swapped =\n+\t\t\t\t\tfirst &&\n+\t\t\t\t\tassignDateToBalance(\n+\t\t\t\t\t\tfirst,\n+\t\t\t\t\t\tother.date,\n+\t\t\t\t\t\texisting.balanceId,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\texisting.ruleIds,\n+\t\t\t\t\t);\n+\t\t\t\tif (!swapped) continue;\n+\t\t\t\tswapped.placements.get(date)!.supporting = other.supporting;\n+\t\t\t\tswapped.placements.get(other.date)!.supporting = existing.supporting;\n+\t\t\t\tnext.push(swapped);\n+\t\t\t}\n+\t\t}\n+\t\tvariants = next;\n+\t\tif (!variants.length) break;\n+\t}\n+\treturn variants;\n }\n \n function* preferenceIfThen(\n \tstate: State,\n-\trule: NormalizedRule,\n+\trule: NormalizedCalendarRule,\n \tcontext: SearchContext,\n+\tpreferenceIndex: number,\n ): PlanningSteps<{ state: State; count: number }> {\n \tconst matchingOccurrences = occurrences(rule, context);\n \tlet bestState = state;\n \tlet bestCount = 0;\n-\tlet bestFutureScore = Number.POSITIVE_INFINITY;\n-\tlet bestMetrics: PlanningMetrics | undefined;\n+\tconst baseline = activeObjectiveVector(state, context, preferenceIndex);\n \tlet bestBranch: ObligationBranchReference | undefined;\n \tlet bestEvaluation: MutableTraceCandidate | undefined;\n-\tconst search = function* (\n-\t\tindex: number,\n-\t\tcurrent: State,\n-\t\tcount: number,\n-\t\tfutureScore: number,\n-\t): PlanningSteps {\n+\tconst search = function* (index: number, current: State, count: number): PlanningSteps {\n \t\tyield;\n \t\tcontext.check();\n \t\tconst maximumCount = count + matchingOccurrences.length - index;\n-\t\tif (maximumCount < bestCount) {\n+\t\tif (\n+\t\t\tmaximumCount < bestCount &&\n+\t\t\tbaseline.slice(0, preferenceIndex).every((objective) => {\n+\t\t\t\tif (objective.direction === 'minimize') return objective.value === 0;\n+\t\t\t\tconst earlier = context.rules.find(\n+\t\t\t\t\t(item) => `preference:${item.id}` === objective.id,\n+\t\t\t\t);\n+\t\t\t\treturn (\n+\t\t\t\t\tearlier &&\n+\t\t\t\t\tobjective.value ===\n+\t\t\t\t\t\t(earlier.type === 'time_window'\n+\t\t\t\t\t\t\t? earlier.placeDays\n+\t\t\t\t\t\t\t: occurrences(earlier, context).length)\n+\t\t\t\t);\n+\t\t\t})\n+\t\t) {\n \t\t\tconst comparator = `complete-occurrences:${rule.id}`;\n \t\t\trecordTraceCandidate(context, {\n \t\t\t\tstatus: 'pruned',\n@@ -3228,7 +4569,7 @@ function* preferenceIfThen(\n \t\t\treturn;\n \t\t}\n \t\tif (index >= matchingOccurrences.length) {\n-\t\t\tconst finalized = finalizeEarnedState(current, context);\n+\t\t\tconst finalized = finalizeRuleCandidate(current, context, state);\n \t\t\tif (!finalized) {\n \t\t\t\trecordTraceCandidate(context, {\n \t\t\t\t\tstatus: 'pruned',\n@@ -3240,23 +4581,20 @@ function* preferenceIfThen(\n \t\t\t\t});\n \t\t\t\treturn;\n \t\t\t}\n-\t\t\tconst metrics = qualityMetrics(finalized, context, []);\n-\t\t\tcontext.retain?.(finalized, metrics);\n-\t\t\tconst betterTie =\n-\t\t\t\tfutureScore < bestFutureScore ||\n-\t\t\t\t(futureScore === bestFutureScore &&\n-\t\t\t\t\tbestMetrics !== undefined &&\n-\t\t\t\t\t(compareMetrics(metrics, bestMetrics) < 0 ||\n-\t\t\t\t\t\t(compareMetrics(metrics, bestMetrics) === 0 &&\n-\t\t\t\t\t\t\tcompareText(placementTieKey(finalized), placementTieKey(bestState)) <\n-\t\t\t\t\t\t\t\t0)));\n-\t\t\tconst better = count > bestCount || (count === bestCount && betterTie);\n+\t\t\tif (\n+\t\t\t\tunsatisfiedObligationCount(finalized, context) ||\n+\t\t\t\tcompareObjectiveLists(\n+\t\t\t\t\tactiveObjectiveVector(finalized, context, preferenceIndex),\n+\t\t\t\t\tbaseline,\n+\t\t\t\t) > 0\n+\t\t\t)\n+\t\t\t\treturn;\n+\t\t\tcontext.retain?.(finalized);\n+\t\t\tconst better =\n+\t\t\t\tcompareObligationPreviews({ state: finalized }, { state: bestState }, context) < 0;\n \t\t\tlet branch: ObligationBranchReference | undefined;\n \t\t\tlet evaluation: MutableTraceCandidate | undefined;\n \t\t\tif (context.trace) {\n-\t\t\t\tconst beforeCount = bestCount;\n-\t\t\t\tconst beforeFutureScore = bestFutureScore;\n-\t\t\t\tconst beforeMetrics = bestMetrics;\n \t\t\t\tconst beforeState = bestState;\n \t\t\t\tconst candidateDates = () =>\n \t\t\t\t\t[...finalized.placements.values()]\n@@ -3267,16 +4605,10 @@ function* preferenceIfThen(\n \t\t\t\t\t\t)\n \t\t\t\t\t\t.map((placement) => placement.date);\n \t\t\t\tconst comparison = () =>\n-\t\t\t\t\tpreferenceIfThenComparisonFacts(\n-\t\t\t\t\t\trule.id,\n-\t\t\t\t\t\tcount,\n-\t\t\t\t\t\tfutureScore,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\tbeforeCount,\n-\t\t\t\t\t\tbeforeFutureScore,\n-\t\t\t\t\t\tbeforeMetrics,\n-\t\t\t\t\t\tfinalized,\n-\t\t\t\t\t\tbeforeState,\n+\t\t\t\t\tobligationPreviewComparisonFacts(\n+\t\t\t\t\t\t{ state: finalized },\n+\t\t\t\t\t\t{ state: beforeState },\n+\t\t\t\t\t\tcontext,\n \t\t\t\t\t);\n \t\t\t\tif (context.traceBranchActive)\n \t\t\t\t\tbranch = recordTraceBranchDecision(\n@@ -3292,22 +4624,20 @@ function* preferenceIfThen(\n \t\t\tif (better) {\n \t\t\t\tbestCount = count;\n \t\t\t\tbestState = finalized;\n-\t\t\t\tbestFutureScore = futureScore;\n-\t\t\t\tbestMetrics = metrics;\n \t\t\t\tbestBranch = branch;\n \t\t\t\tbestEvaluation = evaluation;\n \t\t\t}\n \t\t\treturn;\n \t\t}\n \t\tconst occurrence = matchingOccurrences[index];\n-\t\tconst patterns = patternsFor(rule, occurrence, context).sort(\n+\t\tconst patterns = [...patternsFor(rule, occurrence, context)].sort(\n \t\t\t(a, b) =>\n \t\t\t\tpatternConflictScore(rule.placeType, a, context) -\n \t\t\t\t\tpatternConflictScore(rule.placeType, b, context) || compareDateLists(a, b),\n \t\t);\n \t\tfor (const pattern of patterns) {\n \t\t\tyield;\n-\t\t\tconst variants = yield* assignDatesVariants(current, pattern, rule, context);\n+\t\t\tconst variants = yield* preferencePatternVariants(current, pattern, rule, context);\n \t\t\tfor (const variant of variants) {\n \t\t\t\tyield;\n \t\t\t\tconst finalized = finalizeEarnedState(\n@@ -3315,112 +4645,22 @@ function* preferenceIfThen(\n \t\t\t\t\tcontext,\n \t\t\t\t);\n \t\t\t\tif (!finalized) continue;\n-\t\t\t\tyield* search(\n-\t\t\t\t\tindex + 1,\n-\t\t\t\t\tfinalized,\n-\t\t\t\t\tcount + 1,\n-\t\t\t\t\tfutureScore + patternConflictScore(rule.placeType, pattern, context),\n-\t\t\t\t);\n-\t\t\t}\n-\t\t}\n-\t\t// A preference may leave an occurrence unplaced. Exploring this branch after\n-\t\t// complete patterns keeps the result deterministic while still maximizing the\n-\t\t// number of complete occurrences.\n-\t\tyield* search(index + 1, current, count, futureScore);\n-\t};\n-\tyield* search(0, state, 0, 0);\n-\tif (bestBranch) {\n-\t\tobserveTrace(context, (trace) => trace.chooseEvaluation(bestBranch!.candidate));\n-\t\tcontext.traceBranchParentId = bestBranch.decisionId;\n-\t} else if (!context.traceBranchActive) {\n-\t\tretainAndRecordState(context, bestState, bestEvaluation);\n-\t}\n-\treturn { state: bestState, count: bestCount };\n-}\n-\n-function preferenceIfThenComparisonFacts(\n-\truleId: string,\n-\tcount: number,\n-\tfutureScore: number,\n-\tmetrics: PlanningMetrics,\n-\tbestCount: number,\n-\tbestFutureScore: number,\n-\tbestMetrics: PlanningMetrics | undefined,\n-\tstate: State,\n-\tbestState: State,\n-): {\n-\tvalues: NonNullable;\n-\tfirstDecisiveComparator?: string;\n-} {\n-\tconst values: NonNullable[number][] = [];\n-\tconst countName = `complete-occurrences:${ruleId}`;\n-\tconst countEqual = count === bestCount;\n-\tvalues.push({ name: countName, direction: 'maximize', before: bestCount, after: count });\n-\tconst scoreName = `future-pattern-conflict-score:${ruleId}`;\n-\tconst scoreBefore = Number.isFinite(bestFutureScore) ? bestFutureScore : '∞';\n-\tvalues.push({\n-\t\tname: scoreName,\n-\t\tdirection: 'minimize',\n-\t\tbefore: scoreBefore,\n-\t\tafter: futureScore,\n-\t});\n-\tlet firstDecisiveComparator = !countEqual ? countName : undefined;\n-\tif (countEqual && futureScore !== bestFutureScore) firstDecisiveComparator = scoreName;\n-\n-\tif (futureScore === bestFutureScore && bestMetrics) {\n-\t\tconst metricComparators = [\n-\t\t\t{\n-\t\t\t\tname: 'unplaced-at-risk',\n-\t\t\t\tdirection: 'minimize' as const,\n-\t\t\t\tbefore: bestMetrics.unplacedAtRisk,\n-\t\t\t\tafter: metrics.unplacedAtRisk,\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\tname: 'holiday-week-value',\n-\t\t\t\tdirection: 'maximize' as const,\n-\t\t\t\tbefore: bestMetrics.holidayWeekValue,\n-\t\t\t\tafter: metrics.holidayWeekValue,\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\tname: 'non-working-day-gain',\n-\t\t\t\tdirection: 'maximize' as const,\n-\t\t\t\tbefore: bestMetrics.nonWorkingDayGain,\n-\t\t\t\tafter: metrics.nonWorkingDayGain,\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\tname: 'longest-work-sequence',\n-\t\t\t\tdirection: 'minimize' as const,\n-\t\t\t\tbefore: bestMetrics.longestWorkSequence,\n-\t\t\t\tafter: metrics.longestWorkSequence,\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\tname: 'short-sequence-deficit',\n-\t\t\t\tdirection: 'minimize' as const,\n-\t\t\t\tbefore: bestMetrics.shortSequenceDeficit,\n-\t\t\t\tafter: metrics.shortSequenceDeficit,\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\tname: 'supporting-placements',\n-\t\t\t\tdirection: 'minimize' as const,\n-\t\t\t\tbefore: bestMetrics.supportingPlacements,\n-\t\t\t\tafter: metrics.supportingPlacements,\n-\t\t\t},\n-\t\t];\n-\t\tfor (const comparator of metricComparators) {\n-\t\t\tvalues.push(comparator);\n-\t\t\tif (comparator.before !== comparator.after) {\n-\t\t\t\tfirstDecisiveComparator ??= comparator.name;\n-\t\t\t\tbreak;\n+\t\t\t\tyield* search(index + 1, finalized, count + 1);\n \t\t\t}\n \t\t}\n-\t\tif (metricComparators.every((comparator) => comparator.before === comparator.after)) {\n-\t\t\tconst before = placementTieKey(bestState);\n-\t\t\tconst after = placementTieKey(state);\n-\t\t\tvalues.push({ name: 'placement-date', direction: 'minimize', before, after });\n-\t\t\tif (before !== after) firstDecisiveComparator ??= 'placement-date';\n-\t\t}\n+\t\t// A preference may leave an occurrence unplaced. Exploring this branch after\n+\t\t// complete patterns keeps the result deterministic while still maximizing the\n+\t\t// number of complete occurrences.\n+\t\tyield* search(index + 1, current, count);\n+\t};\n+\tyield* search(0, state, 0);\n+\tif (bestBranch) {\n+\t\tobserveTrace(context, (trace) => trace.chooseEvaluation(bestBranch!.candidate));\n+\t\tcontext.traceBranchParentId = bestBranch.decisionId;\n+\t} else if (!context.traceBranchActive) {\n+\t\tretainAndRecordState(context, bestState, bestEvaluation);\n \t}\n-\treturn { values, firstDecisiveComparator };\n+\treturn { state: bestState, count: bestCount };\n }\n \n function preferenceDateConflictScore(\n@@ -3442,89 +4682,6 @@ function preferenceDateConflictScore(\n \treturn demand ? -demand : 0;\n }\n \n-function atRiskDateSelectionFacts(\n-\tselector: LeaveSelector,\n-\tselectedDate: string,\n-\tnextDate: string,\n-\tcontext: SearchContext,\n-): Pick {\n-\tconst selectedScore = preferenceDateConflictScore(selector, selectedDate, context);\n-\tconst nextScore = preferenceDateConflictScore(selector, nextDate, context);\n-\tconst technicalComparison: NonNullable<\n-\t\tPlanningTraceCandidate['technicalComparison']\n-\t>[number][] = [\n-\t\t{\n-\t\t\tname: 'preference-date-conflict',\n-\t\t\tdirection: 'minimize',\n-\t\t\tbefore: selectedScore,\n-\t\t\tafter: nextScore,\n-\t\t},\n-\t];\n-\tif (selectedScore !== nextScore)\n-\t\treturn { technicalComparison, firstDecisiveComparator: 'preference-date-conflict' };\n-\ttechnicalComparison.push({\n-\t\tname: 'placement-date',\n-\t\tdirection: 'minimize',\n-\t\tbefore: selectedDate,\n-\t\tafter: nextDate,\n-\t});\n-\treturn { technicalComparison, firstDecisiveComparator: 'placement-date' };\n-}\n-\n-function firstCompatibleBalanceSelectionFacts(\n-\tselector: LeaveSelector,\n-\tdate: string,\n-\tfirst: InternalBalance,\n-\tsecond: InternalBalance | undefined,\n-\tcontext: SearchContext,\n-): Pick {\n-\tif (!second) return {};\n-\tconst values: NonNullable[number][] = [];\n-\tlet firstDecisiveComparator: string | undefined;\n-\tconst add = (\n-\t\tname: string,\n-\t\tdirection: 'minimize' | 'maximize',\n-\t\tbefore: number | string,\n-\t\tafter: number | string,\n-\t): boolean => {\n-\t\tvalues.push({ name, direction, before, after });\n-\t\tif (before !== after) firstDecisiveComparator ??= name;\n-\t\treturn before === after;\n-\t};\n-\tif (selector === 'any') {\n-\t\tconst sharedTypes = context.sharedTypesByDate.get(date) ?? new Set();\n-\t\tlet equal = add(\n-\t\t\t'shared-placement-type',\n-\t\t\t'maximize',\n-\t\t\tNumber(sharedTypes.has(first.type)),\n-\t\t\tNumber(sharedTypes.has(second.type)),\n-\t\t);\n-\t\tconst protectedTypes = context.protectedTypesByDate.get(date) ?? new Set();\n-\t\tif (equal && protectedTypes.size)\n-\t\t\tequal = add(\n-\t\t\t\t'protected-preference-type',\n-\t\t\t\t'maximize',\n-\t\t\t\tNumber(protectedTypes.has(first.type)),\n-\t\t\t\tNumber(protectedTypes.has(second.type)),\n-\t\t\t);\n-\t\tif (\n-\t\t\tequal &&\n-\t\t\tcontext.reservedTypes.has(first.type) !== context.reservedTypes.has(second.type)\n-\t\t)\n-\t\t\tadd(\n-\t\t\t\t'reserved-type',\n-\t\t\t\t'minimize',\n-\t\t\t\tNumber(context.reservedTypes.has(first.type)),\n-\t\t\t\tNumber(context.reservedTypes.has(second.type)),\n-\t\t\t);\n-\t}\n-\tif (!firstDecisiveComparator) {\n-\t\tconst equal = add('balance-expiry', 'minimize', first.expiryDate, second.expiryDate);\n-\t\tif (equal) add('balance-id', 'minimize', first.id, second.id);\n-\t}\n-\treturn { technicalComparison: values, firstDecisiveComparator };\n-}\n-\n function patternConflictScore(\n \tselector: LeaveSelector,\n \tpattern: string[],\n@@ -3537,7 +4694,7 @@ function patternConflictScore(\n }\n \n function preferenceReason(\n-\trule: NormalizedRule,\n+\trule: NormalizedCalendarRule,\n \tcount: number,\n \tcontext: SearchContext,\n \tstate: State,\n@@ -3584,1323 +4741,308 @@ function preferenceReason(\n \t\t\t\t\tplacement.balanceId === balance.id &&\n \t\t\t\t\t[...placement.ruleIds].some((id) => {\n \t\t\t\t\t\tconst index = context.rules.findIndex((item) => item.id === id);\n-\t\t\t\t\t\treturn index >= 0 && index < currentRuleIndex;\n+\t\t\t\t\t\treturn (\n+\t\t\t\t\t\t\tindex >= 0 &&\n+\t\t\t\t\t\t\t(context.rules[index].force === 'obligation' ||\n+\t\t\t\t\t\t\t\tindex < currentRuleIndex)\n+\t\t\t\t\t\t);\n \t\t\t\t\t}),\n \t\t\t),\n \t);\n-\tconst consumedByAtRisk = matchingBalances.some(\n-\t\t(balance) =>\n-\t\t\tbalance.remaining === 0 &&\n-\t\t\tisAtRisk(balance, context) &&\n-\t\t\t[...state.placements.values()].some(\n-\t\t\t\t(placement) => placement.balanceId === balance.id && placement.ruleIds.size === 0,\n-\t\t\t),\n-\t);\n-\tconst freeEligibleDate = candidateDates.some(\n-\t\t(date) =>\n-\t\t\t!state.placements.has(date) &&\n-\t\t\tstate.balances.some(\n-\t\t\t\t(balance) =>\n-\t\t\t\t\tbalance.remaining > 0 &&\n-\t\t\t\t\tselectorMatches(rule.placeType, balance.type) &&\n-\t\t\t\t\tcompareDate(balance.availableFrom, date) <= 0 &&\n-\t\t\t\t\tcompareDate(date, balance.expiryDate) <= 0,\n-\t\t\t),\n-\t);\n-\tconst compatibleExisting = candidateDates.some((date) => {\n-\t\tconst placement = state.placements.get(date);\n-\t\treturn placement && selectorMatches(rule.placeType, placement.type);\n-\t});\n-\tconst blockedByHigherPriority = candidateDates.some((date) => {\n-\t\tconst placement = state.placements.get(date);\n-\t\tconst sourceBalance = placement\n-\t\t\t? state.balances.find((balance) => balance.id === placement.balanceId)\n-\t\t\t: undefined;\n-\t\treturn (\n-\t\t\tplacement &&\n-\t\t\t!selectorMatches(rule.placeType, placement.type) &&\n-\t\t\t((sourceBalance ? isAtRisk(sourceBalance, context) : false) ||\n-\t\t\t\t[...placement.ruleIds].some((id) => {\n-\t\t\t\t\tconst index = context.rules.findIndex((item) => item.id === id);\n-\t\t\t\t\treturn index >= 0 && index < currentRuleIndex;\n-\t\t\t\t}))\n-\t\t);\n-\t});\n-\tlet code: string;\n-\tif (blockedByHigherPriority && !freeEligibleDate && !compatibleExisting)\n-\t\tcode = 'higher-priority';\n-\telse if (!matchingBalances.length && !compatibleExisting) code = 'type';\n-\telse if (!availableBalances.length) code = 'availability';\n-\telse if (\n-\t\t(consumedByHigherPriority || consumedByAtRisk) &&\n-\t\t!freeEligibleDate &&\n-\t\t!compatibleExisting\n-\t)\n-\t\tcode = 'higher-priority';\n-\telse code = 'capacity';\n-\treturn reason(code, `Preference \"${rule.name}\" could not be completely satisfied.`, [rule.id]);\n-}\n-\n-function* applyPreferenceRules(\n-\tstate: State,\n-\tpreferenceRules: NormalizedRule[],\n-\tcontext: SearchContext,\n-): PlanningSteps<{ state: State; preferences: PreferenceResult[] }> {\n-\tlet result = state;\n-\tconst preferences: PreferenceResult[] = [];\n-\tfor (let preferenceIndex = 0; preferenceIndex < preferenceRules.length; preferenceIndex++) {\n-\t\tyield;\n-\t\tresult = yield* applyPreferenceStep(\n-\t\t\tresult,\n-\t\t\tpreferenceRules,\n-\t\t\tpreferenceIndex,\n-\t\t\tpreferences,\n-\t\t\tcontext,\n-\t\t);\n-\t}\n-\treturn { state: result, preferences };\n-}\n-\n-function* applyPreferenceStep(\n-\tstate: State,\n-\tpreferenceRules: NormalizedRule[],\n-\tpreferenceIndex: number,\n-\tpreferences: PreferenceResult[],\n-\tcontext: SearchContext,\n-): PlanningSteps {\n-\tlet result = state;\n-\tconst applied = yield* applyPreferenceRule(\n-\t\tresult,\n-\t\tpreferenceRules[preferenceIndex],\n-\t\tpreferenceRules,\n-\t\tpreferenceIndex,\n-\t\tcontext,\n-\t);\n-\tresult = applied.state;\n-\tpreferences[preferenceIndex] = applied.preference;\n-\t// A lower-priority rule can be the producer for an entitlement needed by\n-\t// an earlier rule. Replay incomplete preferences left-to-right until no\n-\t// satisfaction improves, preserving lexicographic priority across a chain.\n-\tlet remainingImprovements = preferences\n-\t\t.slice(0, preferenceIndex + 1)\n-\t\t.reduce((total, preference) => total + preference.requested, 0);\n-\twhile (remainingImprovements > 0) {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tlet improved = false;\n-\t\tfor (let retryIndex = 0; retryIndex <= preferenceIndex; retryIndex++) {\n-\t\t\tyield;\n-\t\t\tcontext.check();\n-\t\t\tconst previous = preferences[retryIndex];\n-\t\t\tif (previous.satisfied >= previous.requested) continue;\n-\t\t\tconst retried = yield* applyPreferenceRule(\n-\t\t\t\tresult,\n-\t\t\t\tpreferenceRules[retryIndex],\n-\t\t\t\tpreferenceRules,\n-\t\t\t\tretryIndex,\n-\t\t\t\tcontext,\n-\t\t\t);\n-\t\t\tif (retried.preference.satisfied <= previous.satisfied) continue;\n-\t\t\tremainingImprovements -= retried.preference.satisfied - previous.satisfied;\n-\t\t\tresult = retried.state;\n-\t\t\tpreferences[retryIndex] = retried.preference;\n-\t\t\timproved = true;\n-\t\t}\n-\t\tif (!improved) break;\n-\t}\n-\treturn result;\n-}\n-\n-function* applyPreferenceRule(\n-\tstate: State,\n-\trule: NormalizedRule,\n-\tpreferenceRules: NormalizedRule[],\n-\tpreferenceIndex: number,\n-\tcontext: SearchContext,\n-): PlanningSteps<{ state: State; preference: PreferenceResult }> {\n-\tyield;\n-\tcontext.check();\n-\tcontext.reservedTypes = new Set(\n-\t\tpreferenceRules\n-\t\t\t.slice(preferenceIndex + 1)\n-\t\t\t.filter((rule) =>\n-\t\t\t\tbuildRequirements([rule], context, rule.force).some(\n-\t\t\t\t\t(requirement) => requirement.requiredPlacements > 0,\n-\t\t\t\t),\n-\t\t\t)\n-\t\t\t.map((item) => item.placeType)\n-\t\t\t.filter((selector): selector is LeaveType => selector !== 'any'),\n-\t);\n-\tcontext.protectedTypesByDate = futurePreferenceProtection(\n-\t\tpreferenceRules,\n-\t\tpreferenceIndex + 1,\n-\t\tcontext,\n-\t);\n-\tconst applied =\n-\t\trule.type === 'time_window'\n-\t\t\t? yield* preferenceTimeWindow(state, rule, context)\n-\t\t\t: yield* preferenceIfThen(state, rule, context);\n-\tconst requested =\n-\t\trule.type === 'time_window' ? rule.placeDays : occurrences(rule, context).length;\n-\treturn {\n-\t\tstate: applied.state,\n-\t\tpreference: {\n-\t\t\truleId: rule.id,\n-\t\t\trequested,\n-\t\t\tsatisfied: applied.count,\n-\t\t\tcompleteOccurrences: rule.type === 'if_then' ? applied.count : 0,\n-\t\t\treason: preferenceReason(rule, applied.count, context, applied.state),\n-\t\t},\n-\t};\n-}\n-\n-function placementTieKey(state: State): string {\n-\treturn [...state.placements.values()]\n-\t\t.sort((a, b) => compareDate(a.date, b.date) || compareText(a.balanceId, b.balanceId))\n-\t\t.map((placement) => `${placement.date}:${placement.balanceId}`)\n-\t\t.join('|');\n-}\n-\n-function expiryTieKey(state: State): string {\n-\treturn [...state.placements.values()]\n-\t\t.sort((a, b) => compareDate(a.date, b.date) || compareText(a.balanceId, b.balanceId))\n-\t\t.map((placement) => {\n-\t\t\tconst balance = state.balances.find((item) => item.id === placement.balanceId);\n-\t\t\treturn `${balance?.expiryDate ?? ''}:${placement.balanceId}`;\n-\t\t})\n-\t\t.join('|');\n-}\n-\n-function comparePreferenceVectors(a: readonly number[], b: readonly number[]): number {\n-\tfor (let index = 0; index < Math.max(a.length, b.length); index++) {\n-\t\tconst left = a[index] ?? 0;\n-\t\tconst right = b[index] ?? 0;\n-\t\tif (left !== right) return right - left;\n-\t}\n-\treturn 0;\n-}\n-\n-/** Compare complete previews so obligation DFS does not commit to its first feasible branch. */\n-function compareObligationPreviews(\n-\ta: { state: State; preferences: PreferenceResult[]; metrics: PlanningMetrics },\n-\tb: { state: State; preferences: PreferenceResult[]; metrics: PlanningMetrics },\n-): number {\n-\tif (a.metrics.unplacedAtRisk !== b.metrics.unplacedAtRisk)\n-\t\treturn a.metrics.unplacedAtRisk - b.metrics.unplacedAtRisk;\n-\tconst preferenceComparison = comparePreferenceVectors(\n-\t\ta.metrics.preferenceSatisfaction,\n-\t\tb.metrics.preferenceSatisfaction,\n-\t);\n-\tif (preferenceComparison) return preferenceComparison;\n-\tconst metrics = compareMetrics(\n-\t\t{ ...a.metrics, unplacedAtRisk: 0 },\n-\t\t{ ...b.metrics, unplacedAtRisk: 0 },\n-\t);\n-\tif (metrics) return metrics;\n-\tconst expiry = compareText(expiryTieKey(a.state), expiryTieKey(b.state));\n-\tif (expiry) return expiry;\n-\treturn compareText(placementTieKey(a.state), placementTieKey(b.state));\n-}\n-\n-function obligationPreviewComparisonFacts(\n-\ta: { state: State; preferences: PreferenceResult[]; metrics: PlanningMetrics },\n-\tb: { state: State; preferences: PreferenceResult[]; metrics: PlanningMetrics },\n-): {\n-\tvalues: NonNullable;\n-\tfirstDecisiveComparator?: string;\n-} {\n-\tconst values: NonNullable[number][] = [];\n-\tconst add = (\n-\t\tname: string,\n-\t\tdirection: 'minimize' | 'maximize',\n-\t\tbefore: number | string,\n-\t\tafter: number | string,\n-\t) => {\n-\t\tvalues.push({ name, direction, before, after });\n-\t\treturn before === after;\n-\t};\n-\tlet equal = add(\n-\t\t'unplaced-at-risk',\n-\t\t'minimize',\n-\t\tb.metrics.unplacedAtRisk,\n-\t\ta.metrics.unplacedAtRisk,\n-\t);\n-\tif (!equal) return { values, firstDecisiveComparator: 'unplaced-at-risk' };\n-\tfor (let index = 0; index < a.metrics.preferenceSatisfaction.length; index++) {\n-\t\tconst before = b.metrics.preferenceSatisfaction[index] ?? 0;\n-\t\tconst after = a.metrics.preferenceSatisfaction[index] ?? 0;\n-\t\tconst ruleId =\n-\t\t\ta.preferences[index]?.ruleId ?? b.preferences[index]?.ruleId ?? String(index);\n-\t\tequal = add(`preference:${ruleId}`, 'maximize', before, after);\n-\t\tif (!equal) return { values, firstDecisiveComparator: `preference:${ruleId}` };\n-\t}\n-\tconst metrics = [\n-\t\t{\n-\t\t\tname: 'holiday-week-value',\n-\t\t\tdirection: 'maximize' as const,\n-\t\t\tbefore: b.metrics.holidayWeekValue,\n-\t\t\tafter: a.metrics.holidayWeekValue,\n-\t\t},\n-\t\t{\n-\t\t\tname: 'non-working-day-gain',\n-\t\t\tdirection: 'maximize' as const,\n-\t\t\tbefore: b.metrics.nonWorkingDayGain,\n-\t\t\tafter: a.metrics.nonWorkingDayGain,\n-\t\t},\n-\t\t{\n-\t\t\tname: 'longest-work-sequence',\n-\t\t\tdirection: 'minimize' as const,\n-\t\t\tbefore: b.metrics.longestWorkSequence,\n-\t\t\tafter: a.metrics.longestWorkSequence,\n-\t\t},\n-\t\t{\n-\t\t\tname: 'short-sequence-deficit',\n-\t\t\tdirection: 'minimize' as const,\n-\t\t\tbefore: b.metrics.shortSequenceDeficit,\n-\t\t\tafter: a.metrics.shortSequenceDeficit,\n-\t\t},\n-\t\t{\n-\t\t\tname: 'supporting-placements',\n-\t\t\tdirection: 'minimize' as const,\n-\t\t\tbefore: b.metrics.supportingPlacements,\n-\t\t\tafter: a.metrics.supportingPlacements,\n-\t\t},\n-\t];\n-\tfor (const metric of metrics) {\n-\t\tequal = add(metric.name, metric.direction, metric.before, metric.after);\n-\t\tif (!equal) return { values, firstDecisiveComparator: metric.name };\n-\t}\n-\tconst beforeExpiry = expiryTieKey(b.state);\n-\tconst afterExpiry = expiryTieKey(a.state);\n-\tequal = add('balance-expiry', 'minimize', beforeExpiry, afterExpiry);\n-\tif (!equal) return { values, firstDecisiveComparator: 'balance-expiry' };\n-\tconst beforeDates = placementTieKey(b.state);\n-\tconst afterDates = placementTieKey(a.state);\n-\tequal = add('placement-date', 'minimize', beforeDates, afterDates);\n-\treturn { values, firstDecisiveComparator: equal ? undefined : 'placement-date' };\n-}\n-\n-type QualityTraceDetails = Pick<\n-\tPlanningTraceCandidate,\n-\t'technicalComparison' | 'firstDecisiveComparator' | 'reason'\n->;\n-\n-type QualityTraceComparator = NonNullable[number];\n-\n-function addQualityComparator(\n-\tvalues: QualityTraceComparator[],\n-\tname: string,\n-\tdirection: QualityTraceComparator['direction'],\n-\tbefore: number | string,\n-\tafter: number | string,\n-): boolean {\n-\tvalues.push({ name, direction, before, after });\n-\treturn before === after;\n-}\n-\n-function recordTraceIncumbentBound(\n-\tcontext: SearchContext,\n-\tincumbentMetrics: PlanningMetrics,\n-\tunplacedAtRisk: number,\n-\tpreferences: readonly PreferenceResult[] = [],\n-): void {\n-\tobserveTrace(context, (trace) => {\n-\t\tconst values: QualityTraceComparator[] = [];\n-\t\tlet equal = addQualityComparator(\n-\t\t\tvalues,\n-\t\t\t'unplaced-at-risk',\n-\t\t\t'minimize',\n-\t\t\tincumbentMetrics.unplacedAtRisk,\n-\t\t\tunplacedAtRisk,\n-\t\t);\n-\t\tfor (let index = 0; equal && index < preferences.length; index++) {\n-\t\t\tconst preference = preferences[index];\n-\t\t\tequal = addQualityComparator(\n-\t\t\t\tvalues,\n-\t\t\t\t`preference:${preference.ruleId}`,\n-\t\t\t\t'maximize',\n-\t\t\t\tincumbentMetrics.preferenceSatisfaction[index] ?? 0,\n-\t\t\t\tpreference.satisfied,\n-\t\t\t);\n-\t\t}\n-\t\ttrace.recordCandidate(\n-\t\t\t{\n-\t\t\t\tstatus: 'pruned',\n-\t\t\t\ttechnicalComparison: values,\n-\t\t\t\tfirstDecisiveComparator: values[values.length - 1].name,\n-\t\t\t\treason: reason(\n-\t\t\t\t\t'incumbent-bound',\n-\t\t\t\t\t'This state cannot improve the incumbent on the first differing planning objective.',\n-\t\t\t\t),\n-\t\t\t},\n-\t\t\tfalse,\n-\t\t);\n-\t});\n-}\n-\n-function movableProtectionTraceDetails(\n-\tbaseline: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tpreferences: readonly PreferenceResult[],\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst reject = (name: string, message: string): QualityTraceDetails => ({\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: name,\n-\t\treason: reason('quality-protected-objective', message),\n-\t});\n-\tconst atRiskEqual = addQualityComparator(\n-\t\tvalues,\n-\t\t'protected:unplaced-at-risk',\n-\t\t'minimize',\n-\t\tbaseline.unplacedAtRisk,\n-\t\tcandidate.unplacedAtRisk,\n-\t);\n-\tif (!atRiskEqual)\n-\t\treturn reject(\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'This move changes the amount of unplaced at-risk leave protected by the quality pass.',\n-\t\t);\n-\taddQualityComparator(\n-\t\tvalues,\n-\t\t'protected:holiday-week-value',\n-\t\t'maximize',\n-\t\tbaseline.holidayWeekValue,\n-\t\tcandidate.holidayWeekValue,\n-\t);\n-\tif (candidate.holidayWeekValue < baseline.holidayWeekValue)\n-\t\treturn reject(\n-\t\t\t'protected:holiday-week-value',\n-\t\t\t'This move reduces public-holiday week value protected by the quality pass.',\n-\t\t);\n-\tif (candidate.preferenceSatisfaction.length !== baseline.preferenceSatisfaction.length) {\n-\t\tconst name = 'protected:preference-count';\n-\t\taddQualityComparator(\n-\t\t\tvalues,\n-\t\t\tname,\n-\t\t\t'maximize',\n-\t\t\tbaseline.preferenceSatisfaction.length,\n-\t\t\tcandidate.preferenceSatisfaction.length,\n-\t\t);\n-\t\treturn reject(\n-\t\t\tname,\n-\t\t\t'This move changes the preference result protected by the quality pass.',\n-\t\t);\n-\t}\n-\tfor (let index = 0; index < baseline.preferenceSatisfaction.length; index++) {\n-\t\tconst name = `protected:preference:${preferences[index]?.ruleId ?? index}`;\n-\t\tconst before = baseline.preferenceSatisfaction[index];\n-\t\tconst after = candidate.preferenceSatisfaction[index];\n-\t\tif (!addQualityComparator(values, name, 'maximize', before, after))\n-\t\t\treturn reject(\n-\t\t\t\tname,\n-\t\t\t\t'This move changes a preference result protected by the quality pass.',\n-\t\t\t);\n-\t}\n-\treturn { technicalComparison: values };\n-}\n-\n-function movableIncumbentTraceDetails(\n-\tstage: 'non-working-day-gain' | 'longest-work-sequence' | 'short-sequence-deficit' | 'dates',\n-\tincumbent: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tincumbentDate: string,\n-\tcandidateDate: string,\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst add = (\n-\t\tname: string,\n-\t\tdirection: QualityTraceComparator['direction'],\n-\t\tbefore: number | string,\n-\t\tafter: number | string,\n-\t) => addQualityComparator(values, name, direction, before, after);\n-\tconst finishIfDifferent = (name: string, equal: boolean): QualityTraceDetails | undefined =>\n-\t\tequal ? undefined : { technicalComparison: values, firstDecisiveComparator: name };\n-\n-\tlet equal = add(\n-\t\t'holiday-week-value',\n-\t\t'maximize',\n-\t\tincumbent.holidayWeekValue,\n-\t\tcandidate.holidayWeekValue,\n-\t);\n-\tlet decisive = finishIfDifferent('holiday-week-value', equal);\n-\tif (decisive) return decisive;\n-\tif (stage === 'non-working-day-gain') {\n-\t\tequal = add(\n-\t\t\t'non-working-day-gain',\n-\t\t\t'maximize',\n-\t\t\tincumbent.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain,\n-\t\t);\n-\t\treturn finishIfDifferent('non-working-day-gain', equal) ?? { technicalComparison: values };\n-\t}\n-\tequal = add(\n-\t\t'non-working-day-gain',\n-\t\t'maximize',\n-\t\tincumbent.nonWorkingDayGain,\n-\t\tcandidate.nonWorkingDayGain,\n-\t);\n-\tdecisive = finishIfDifferent('non-working-day-gain', equal);\n-\tif (decisive) return decisive;\n-\tif (stage === 'longest-work-sequence') {\n-\t\tequal = add(\n-\t\t\t'longest-work-sequence',\n-\t\t\t'minimize',\n-\t\t\tincumbent.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence,\n-\t\t);\n-\t\treturn finishIfDifferent('longest-work-sequence', equal) ?? { technicalComparison: values };\n-\t}\n-\tequal = add(\n-\t\t'longest-work-sequence',\n-\t\t'minimize',\n-\t\tincumbent.longestWorkSequence,\n-\t\tcandidate.longestWorkSequence,\n-\t);\n-\tdecisive = finishIfDifferent('longest-work-sequence', equal);\n-\tif (decisive) return decisive;\n-\tif (stage === 'short-sequence-deficit') {\n-\t\tequal = add(\n-\t\t\t'short-sequence-deficit',\n-\t\t\t'minimize',\n-\t\t\tincumbent.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit,\n-\t\t);\n-\t\treturn (\n-\t\t\tfinishIfDifferent('short-sequence-deficit', equal) ?? { technicalComparison: values }\n-\t\t);\n-\t}\n-\tequal = add(\n-\t\t'short-sequence-deficit',\n-\t\t'minimize',\n-\t\tincumbent.shortSequenceDeficit,\n-\t\tcandidate.shortSequenceDeficit,\n-\t);\n-\tdecisive = finishIfDifferent('short-sequence-deficit', equal);\n-\tif (decisive) return decisive;\n-\tif (stage === 'dates') {\n-\t\tconst dateEqual = add('placement-date', 'minimize', incumbentDate, candidateDate);\n-\t\treturn finishIfDifferent('placement-date', dateEqual) ?? { technicalComparison: values };\n-\t}\n-\treturn { technicalComparison: values };\n-}\n-\n-function recordTraceDecision(context: SearchContext, dates: readonly string[]): void {\n-\tobserveTrace(context, (trace) => trace.recordDecision('choose', dates));\n-}\n-\n-function updateTraceEvaluationReason(\n-\tcontext: SearchContext,\n-\tevaluation: MutableTraceCandidate | undefined,\n-\tevaluationReason: PlanningReason,\n-): void {\n-\tif (!evaluation) return;\n-\tobserveTrace(context, (trace) => {\n-\t\tevaluation.reason = evaluationReason;\n-\t\ttrace.updateEvaluation(evaluation);\n-\t});\n-}\n-\n-function retainAndRecordEvaluation(\n-\tcontext: SearchContext,\n-\tbeforeState: State,\n-\tafterState: State,\n-\tpreferences: readonly PreferenceResult[],\n-\tbeforeMetrics: PlanningMetrics,\n-\tafterMetrics: PlanningMetrics,\n-\tdates: readonly string[],\n-\tsourceDate?: string,\n-\tqualityDetails?: () => QualityTraceDetails,\n-): MutableTraceCandidate | undefined {\n-\tlet evaluation: MutableTraceCandidate | undefined;\n-\tobserveTrace(context, (trace) => {\n-\t\tconst date = dates[dates.length - 1];\n-\t\tconst placement = date ? afterState.placements.get(date) : undefined;\n-\t\tconst details = qualityDetails?.();\n-\t\tevaluation = {\n-\t\t\tstatus: 'evaluated-rejected',\n-\t\t\tsourceDate,\n-\t\t\tdate,\n-\t\t\tdates: [...dates],\n-\t\t\treason: details?.reason,\n-\t\t\tcomparison: objectiveComparison(\n-\t\t\t\tobjectiveVector(beforeMetrics, preferences, beforeState, context),\n-\t\t\t\tobjectiveVector(afterMetrics, preferences, afterState, context),\n-\t\t\t),\n-\t\t\ttechnicalComparison: details?.technicalComparison,\n-\t\t\tfirstDecisiveComparator: details?.firstDecisiveComparator,\n-\t\t\tplacement: placement\n-\t\t\t\t? { ...placement, ruleIds: [...placement.ruleIds].sort() }\n-\t\t\t\t: undefined,\n-\t\t};\n-\t\ttrace.recordEvaluation(evaluation);\n-\t});\n-\tcontext.retain?.(afterState, afterMetrics);\n-\treturn context.trace ? evaluation : undefined;\n-}\n-\n-function holidayWeekProtectionTraceDetails(\n-\tbaseline: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tpreferences: readonly PreferenceResult[],\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst reject = (name: string, message: string): QualityTraceDetails => ({\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: name,\n-\t\treason: reason('quality-protected-objective', message),\n-\t});\n-\taddQualityComparator(\n-\t\tvalues,\n-\t\t'protected:unplaced-at-risk',\n-\t\t'minimize',\n-\t\tbaseline.unplacedAtRisk,\n-\t\tcandidate.unplacedAtRisk,\n-\t);\n-\tif (candidate.unplacedAtRisk > baseline.unplacedAtRisk)\n-\t\treturn reject(\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'This completion leaves more at-risk leave unplaced.',\n-\t\t);\n-\tfor (\n-\t\tlet index = 0;\n-\t\tindex <\n-\t\tMath.max(baseline.preferenceSatisfaction.length, candidate.preferenceSatisfaction.length);\n-\t\tindex++\n-\t) {\n-\t\tconst name = `protected:preference:${preferences[index]?.ruleId ?? index}`;\n-\t\tconst before = baseline.preferenceSatisfaction[index] ?? 0;\n-\t\tconst after = candidate.preferenceSatisfaction[index] ?? 0;\n-\t\tif (!addQualityComparator(values, name, 'maximize', before, after))\n-\t\t\treturn reject(name, 'This completion changes a higher-priority preference result.');\n-\t}\n-\taddQualityComparator(\n-\t\tvalues,\n-\t\t'protected:holiday-week-value',\n-\t\t'maximize',\n-\t\tbaseline.holidayWeekValue,\n-\t\tcandidate.holidayWeekValue,\n+\tconst freeEligibleDate = candidateDates.some(\n+\t\t(date) =>\n+\t\t\t!state.placements.has(date) &&\n+\t\t\tstate.balances.some(\n+\t\t\t\t(balance) =>\n+\t\t\t\t\tbalance.remaining > 0 &&\n+\t\t\t\t\tselectorMatches(rule.placeType, balance.type) &&\n+\t\t\t\t\tcompareDate(balance.availableFrom, date) <= 0 &&\n+\t\t\t\t\tcompareDate(date, balance.expiryDate) <= 0,\n+\t\t\t),\n \t);\n-\tif (candidate.holidayWeekValue <= baseline.holidayWeekValue)\n-\t\treturn reject(\n-\t\t\t'protected:holiday-week-value',\n-\t\t\t'This completion does not increase public-holiday week value.',\n+\tconst compatibleExisting = candidateDates.some((date) => {\n+\t\tconst placement = state.placements.get(date);\n+\t\treturn placement && selectorMatches(rule.placeType, placement.type);\n+\t});\n+\tconst blockedByHigherPriority = candidateDates.some((date) => {\n+\t\tconst placement = state.placements.get(date);\n+\t\treturn (\n+\t\t\tplacement &&\n+\t\t\t!selectorMatches(rule.placeType, placement.type) &&\n+\t\t\t[...placement.ruleIds].some((id) => {\n+\t\t\t\tconst index = context.rules.findIndex((item) => item.id === id);\n+\t\t\t\treturn (\n+\t\t\t\t\tindex >= 0 &&\n+\t\t\t\t\t(context.rules[index].force === 'obligation' || index < currentRuleIndex)\n+\t\t\t\t);\n+\t\t\t})\n \t\t);\n-\treturn { technicalComparison: values };\n+\t});\n+\tlet code: string;\n+\tif (blockedByHigherPriority && !freeEligibleDate && !compatibleExisting)\n+\t\tcode = 'higher-priority';\n+\telse if (!matchingBalances.length && !compatibleExisting) code = 'type';\n+\telse if (!availableBalances.length) code = 'availability';\n+\telse if (consumedByHigherPriority && !freeEligibleDate && !compatibleExisting)\n+\t\tcode = 'higher-priority';\n+\telse code = 'capacity';\n+\treturn reason(code, `Preference \"${rule.name}\" could not be completely satisfied.`, [rule.id]);\n }\n \n-function qualityMetricTraceDetails(\n-\tincumbent: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst comparators = [\n-\t\t['unplaced-at-risk', 'minimize', incumbent.unplacedAtRisk, candidate.unplacedAtRisk],\n-\t\t['holiday-week-value', 'maximize', incumbent.holidayWeekValue, candidate.holidayWeekValue],\n-\t\t[\n-\t\t\t'non-working-day-gain',\n-\t\t\t'maximize',\n-\t\t\tincumbent.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain,\n-\t\t],\n-\t\t[\n-\t\t\t'longest-work-sequence',\n-\t\t\t'minimize',\n-\t\t\tincumbent.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence,\n-\t\t],\n-\t\t[\n-\t\t\t'short-sequence-deficit',\n-\t\t\t'minimize',\n-\t\t\tincumbent.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit,\n-\t\t],\n-\t\t[\n-\t\t\t'supporting-placements',\n-\t\t\t'minimize',\n-\t\t\tincumbent.supportingPlacements,\n-\t\t\tcandidate.supportingPlacements,\n-\t\t],\n-\t] as const;\n-\tfor (const [name, direction, before, after] of comparators) {\n-\t\tif (!addQualityComparator(values, name, direction, before, after))\n-\t\t\treturn { technicalComparison: values, firstDecisiveComparator: name };\n+function* applyPreferenceRules(\n+\tstate: State,\n+\tpreferenceRules: NormalizedRule[],\n+\tcontext: SearchContext,\n+): PlanningSteps<{ state: State; preferences: PreferenceResult[] }> {\n+\tlet result = state;\n+\tconst preferences: PreferenceResult[] = [];\n+\tfor (let preferenceIndex = 0; preferenceIndex < preferenceRules.length; preferenceIndex++) {\n+\t\tyield;\n+\t\tresult = yield* applyPreferenceStep(\n+\t\t\tresult,\n+\t\t\tpreferenceRules,\n+\t\t\tpreferenceIndex,\n+\t\t\tpreferences,\n+\t\t\tcontext,\n+\t\t);\n \t}\n-\treturn { technicalComparison: values };\n-}\n-\n-function qualityMetricTieTraceDetails(\n-\tincumbent: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tincumbentState: State,\n-\tcandidateState: State,\n-): QualityTraceDetails {\n-\tconst comparison = qualityMetricTraceDetails(incumbent, candidate);\n-\tif (comparison.firstDecisiveComparator) return comparison;\n-\tconst values = [...(comparison.technicalComparison ?? [])];\n-\tconst equal = addQualityComparator(\n-\t\tvalues,\n-\t\t'placement-date',\n-\t\t'minimize',\n-\t\tplacementTieKey(incumbentState),\n-\t\tplacementTieKey(candidateState),\n-\t);\n-\treturn {\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: equal ? undefined : 'placement-date',\n-\t};\n+\treturn { state: result, preferences };\n }\n \n-function* optimizeMovablePlacements(\n+function* applyPreferenceStep(\n \tstate: State,\n-\tcontext: SearchContext,\n+\tpreferenceRules: NormalizedRule[],\n+\tpreferenceIndex: number,\n \tpreferences: PreferenceResult[],\n-\tstage: 'non-working-day-gain' | 'longest-work-sequence' | 'short-sequence-deficit' | 'dates',\n+\tcontext: SearchContext,\n ): PlanningSteps {\n \tlet result = state;\n-\t// Small plans are common and can be searched exhaustively. Keep the fixed\n-\t// sparse calendar candidates for loaded years so quality work stays within\n-\t// the mobile budget without making ordinary scenarios depend on sampling.\n-\t// ponytail: loaded plans sample non-working-adjacent and weekly dates; upgrade\n-\t// to interval branch-and-bound if a mobile benchmark shows a missed quality tie.\n-\tconst exhaustive = result.placements.size <= 24;\n-\tconst movableWindowDates = new Set(\n-\t\t[...result.placements.values()]\n-\t\t\t.filter((placement) => isMovableTimeWindow(placement, context))\n-\t\t\t.flatMap((placement) =>\n-\t\t\t\t[...placement.ruleIds]\n-\t\t\t\t\t.map((id) => context.rules.find((rule) => rule.id === id))\n-\t\t\t\t\t.filter(\n-\t\t\t\t\t\t(\n-\t\t\t\t\t\t\trule,\n-\t\t\t\t\t\t): rule is NormalizedRule & {\n-\t\t\t\t\t\t\ttype: 'time_window';\n-\t\t\t\t\t\t\tstartDate: string;\n-\t\t\t\t\t\t\tendDate: string;\n-\t\t\t\t\t\t} => rule?.type === 'time_window',\n-\t\t\t\t\t)\n-\t\t\t\t\t.flatMap((rule) =>\n-\t\t\t\t\t\tcontext.workingDays.filter(\n-\t\t\t\t\t\t\t(date) =>\n-\t\t\t\t\t\t\t\tcompareDate(date, rule.startDate) >= 0 &&\n-\t\t\t\t\t\t\t\tcompareDate(date, rule.endDate) <= 0,\n-\t\t\t\t\t\t),\n-\t\t\t\t\t),\n-\t\t\t),\n-\t);\n-\tconst candidateDates = context.workingDays.filter((date, index) => {\n-\t\tif (exhaustive) return true;\n-\t\tconst touchesNonWorking =\n-\t\t\t!isWorking(addDays(date, -1), context.holidays) ||\n-\t\t\t!isWorking(addDays(date, 1), context.holidays) ||\n-\t\t\tcontext.declaredDates.has(addDays(date, -1)) ||\n-\t\t\tcontext.declaredDates.has(addDays(date, 1));\n-\t\treturn touchesNonWorking || index % 7 === 0;\n-\t});\n-\tif (!exhaustive) {\n-\t\tconst sampled = new Set(candidateDates);\n-\t\tfor (const date of context.workingDays) {\n-\t\t\tyield;\n-\t\t\tif (sampled.has(date)) continue;\n+\tconst apply = function* (index: number): PlanningSteps {\n+\t\tconst rule = preferenceRules[index];\n+\t\tcontext.protectedTypesByDate = futurePreferenceProtection(\n+\t\t\tpreferenceRules,\n+\t\t\tindex + 1,\n+\t\t\tcontext,\n+\t\t);\n+\t\tif (context.completedPreferenceStates.get(index) === preferenceStateKey(result)) {\n \t\t\trecordTraceCandidate(context, {\n \t\t\t\tstatus: 'not-examined',\n-\t\t\t\tdate,\n \t\t\t\treason: reason(\n-\t\t\t\t\t'loaded-plan-sampling',\n-\t\t\t\t\t'This date was not examined because of loaded-plan quality sampling.',\n+\t\t\t\t\t'unchanged-rule-state',\n+\t\t\t\t\t`Rule \"${rule.name}\" already evaluated this unchanged state; its earlier decisions apply.`,\n+\t\t\t\t\t[rule.id],\n \t\t\t\t),\n \t\t\t});\n+\t\t\treturn;\n \t\t}\n-\t}\n-\tfor (const original of [...result.placements.values()]\n-\t\t.filter(\n-\t\t\t(placement) => placement.ruleIds.size === 0 || isMovableTimeWindow(placement, context),\n-\t\t)\n-\t\t.sort((a, b) => compareDate(a.date, b.date) || compareText(a.balanceId, b.balanceId))) {\n-\t\tyield;\n-\t\tconst current = result.placements.get(original.date);\n-\t\tif (!current || (current.ruleIds.size > 0 && !isMovableTimeWindow(current, context)))\n-\t\t\tcontinue;\n-\t\tconst balance = result.balances.find((item) => item.id === current.balanceId);\n-\t\tif (\n-\t\t\t!balance ||\n-\t\t\t(!current.ruleIds.size && !isAtRisk(balance, context) && !current.supporting)\n-\t\t)\n-\t\t\tcontinue;\n-\t\trecordTraceDecision(context, [original.date]);\n-\t\tconst baseline = qualityMetrics(result, context, preferences);\n-\t\tconst without = cloneState(result);\n-\t\twithout.placements.delete(original.date);\n-\t\twithout.balances.find((item) => item.id === current.balanceId)!.remaining++;\n-\t\tlet best = result;\n-\t\tlet bestMetrics = baseline;\n-\t\tlet bestDate = original.date;\n-\t\tlet bestEvaluation: MutableTraceCandidate | undefined;\n-\t\tconst placementCandidates =\n-\t\t\tcurrent.ruleIds.size > 0\n-\t\t\t\t? context.workingDays.filter((date) => movableWindowDates.has(date))\n-\t\t\t\t: candidateDates;\n-\t\tfor (const date of placementCandidates) {\n-\t\t\tyield;\n-\t\t\tif (date === original.date) continue;\n-\t\t\tif (!compatibleWithRules(date, current.type, current.ruleIds, context)) {\n-\t\t\t\trecordTraceIneligible(\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tdate,\n-\t\t\t\t\t'rule-invalid',\n-\t\t\t\t\t'The date does not preserve the placement rules.',\n-\t\t\t\t\t[...current.ruleIds],\n-\t\t\t\t);\n-\t\t\t\tcontinue;\n-\t\t\t}\n-\t\t\tif (\n-\t\t\t\t!assignDateToBalanceInPlace(\n-\t\t\t\t\twithout,\n-\t\t\t\t\tdate,\n-\t\t\t\t\tcurrent.balanceId,\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tcurrent.ruleIds,\n-\t\t\t\t)\n-\t\t\t)\n-\t\t\t\tcontinue;\n-\t\t\ttry {\n-\t\t\t\tconst feasibleCandidate = finalizeEarnedState(without, context);\n-\t\t\t\tif (!feasibleCandidate) continue;\n-\t\t\t\tfeasibleCandidate.placements.get(date)!.supporting = current.supporting;\n-\t\t\t\tconst metrics = qualityMetrics(feasibleCandidate, context, preferences);\n-\t\t\t\tif (metrics.unplacedAtRisk !== baseline.unplacedAtRisk) {\n-\t\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tresult,\n-\t\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t[date],\n-\t\t\t\t\t\tcurrent.date,\n-\t\t\t\t\t\t() => movableProtectionTraceDetails(baseline, metrics, preferences),\n-\t\t\t\t\t);\n-\t\t\t\t\tcontinue;\n-\t\t\t\t}\n-\t\t\t\tif (metrics.holidayWeekValue < baseline.holidayWeekValue) {\n-\t\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tresult,\n-\t\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t[date],\n-\t\t\t\t\t\tcurrent.date,\n-\t\t\t\t\t\t() => movableProtectionTraceDetails(baseline, metrics, preferences),\n-\t\t\t\t\t);\n-\t\t\t\t\tcontinue;\n-\t\t\t\t}\n-\t\t\t\tif (\n-\t\t\t\t\tmetrics.preferenceSatisfaction.length !==\n-\t\t\t\t\t\tbaseline.preferenceSatisfaction.length ||\n-\t\t\t\t\tmetrics.preferenceSatisfaction.some(\n-\t\t\t\t\t\t(value, index) => value !== baseline.preferenceSatisfaction[index],\n-\t\t\t\t\t)\n-\t\t\t\t) {\n-\t\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tresult,\n-\t\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t[date],\n-\t\t\t\t\t\tcurrent.date,\n-\t\t\t\t\t\t() => movableProtectionTraceDetails(baseline, metrics, preferences),\n-\t\t\t\t\t);\n-\t\t\t\t\tcontinue;\n-\t\t\t\t}\n-\t\t\t\tconst better =\n-\t\t\t\t\tmetrics.holidayWeekValue > bestMetrics.holidayWeekValue ||\n-\t\t\t\t\t(metrics.holidayWeekValue === bestMetrics.holidayWeekValue &&\n-\t\t\t\t\t\t(stage === 'non-working-day-gain'\n-\t\t\t\t\t\t\t? metrics.nonWorkingDayGain > bestMetrics.nonWorkingDayGain\n-\t\t\t\t\t\t\t: stage === 'longest-work-sequence'\n-\t\t\t\t\t\t\t\t? metrics.nonWorkingDayGain === bestMetrics.nonWorkingDayGain &&\n-\t\t\t\t\t\t\t\t\tmetrics.longestWorkSequence < bestMetrics.longestWorkSequence\n-\t\t\t\t\t\t\t\t: stage === 'short-sequence-deficit'\n-\t\t\t\t\t\t\t\t\t? metrics.nonWorkingDayGain === bestMetrics.nonWorkingDayGain &&\n-\t\t\t\t\t\t\t\t\t\tmetrics.longestWorkSequence ===\n-\t\t\t\t\t\t\t\t\t\t\tbestMetrics.longestWorkSequence &&\n-\t\t\t\t\t\t\t\t\t\tmetrics.shortSequenceDeficit <\n-\t\t\t\t\t\t\t\t\t\t\tbestMetrics.shortSequenceDeficit\n-\t\t\t\t\t\t\t\t\t: metrics.nonWorkingDayGain === bestMetrics.nonWorkingDayGain &&\n-\t\t\t\t\t\t\t\t\t\tmetrics.longestWorkSequence ===\n-\t\t\t\t\t\t\t\t\t\t\tbestMetrics.longestWorkSequence &&\n-\t\t\t\t\t\t\t\t\t\tmetrics.shortSequenceDeficit ===\n-\t\t\t\t\t\t\t\t\t\t\tbestMetrics.shortSequenceDeficit &&\n-\t\t\t\t\t\t\t\t\t\tdate < bestDate));\n-\t\t\t\tconst evaluation = retainAndRecordEvaluation(\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tresult,\n-\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\tpreferences,\n-\t\t\t\t\tbaseline,\n-\t\t\t\t\tmetrics,\n-\t\t\t\t\t[date],\n-\t\t\t\t\tcurrent.date,\n-\t\t\t\t\t() => {\n-\t\t\t\t\t\tconst protectedDetails = movableProtectionTraceDetails(\n-\t\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\t);\n-\t\t\t\t\t\tconst incumbentDetails = movableIncumbentTraceDetails(\n-\t\t\t\t\t\t\tstage,\n-\t\t\t\t\t\t\tbestMetrics,\n-\t\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t\tbestDate,\n-\t\t\t\t\t\t\tdate,\n-\t\t\t\t\t\t);\n-\t\t\t\t\t\treturn {\n-\t\t\t\t\t\t\ttechnicalComparison: [\n-\t\t\t\t\t\t\t\t...(protectedDetails.technicalComparison ?? []),\n-\t\t\t\t\t\t\t\t...(incumbentDetails.technicalComparison ?? []),\n-\t\t\t\t\t\t\t],\n-\t\t\t\t\t\t\tfirstDecisiveComparator:\n-\t\t\t\t\t\t\t\tprotectedDetails.reason?.code === 'quality-protected-objective'\n-\t\t\t\t\t\t\t\t\t? protectedDetails.firstDecisiveComparator\n-\t\t\t\t\t\t\t\t\t: incumbentDetails.firstDecisiveComparator,\n-\t\t\t\t\t\t\treason: better\n-\t\t\t\t\t\t\t\t? undefined\n-\t\t\t\t\t\t\t\t: reason(\n-\t\t\t\t\t\t\t\t\t\t'quality-no-improvement',\n-\t\t\t\t\t\t\t\t\t\t`This candidate did not improve the current best result in the ${stage} pass.`,\n-\t\t\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t};\n-\t\t\t\t\t},\n-\t\t\t\t);\n-\t\t\t\tif (better) {\n-\t\t\t\t\tif (bestEvaluation)\n-\t\t\t\t\t\tupdateTraceEvaluationReason(\n-\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\tbestEvaluation,\n-\t\t\t\t\t\t\treason(\n-\t\t\t\t\t\t\t\t'quality-outperformed',\n-\t\t\t\t\t\t\t\t'A later candidate became the best result in this pass.',\n-\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t);\n-\t\t\t\t\tbest = cloneState(feasibleCandidate);\n-\t\t\t\t\tbestMetrics = metrics;\n-\t\t\t\t\tbestDate = date;\n-\t\t\t\t\tbestEvaluation = evaluation;\n-\t\t\t\t}\n-\t\t\t} finally {\n-\t\t\t\twithout.placements.delete(date);\n-\t\t\t\twithout.balances.find((item) => item.id === current.balanceId)!.remaining++;\n-\t\t\t}\n-\t\t}\n-\t\tif (best !== result) retainAndRecordState(context, best, bestEvaluation);\n-\t\tresult = best;\n-\t}\n-\treturn result;\n-}\n-\n-// ponytail: regroup only flexible placements and time-window rules; add wider\n-// rule reshaping only if a real plan needs coordinated if-then moves.\n-function* completeHolidayWeek(\n-\tstate: State,\n-\tcandidate: HolidayWeekCandidate,\n-\tcontext: SearchContext,\n-\tprotectedDates: Set,\n-): PlanningSteps {\n-\tconst targetDates = new Set(candidate.dates);\n-\tconst missing = candidate.dates.filter(\n-\t\t(date) => !state.placements.has(date) && !context.declaredDates.has(date),\n-\t);\n-\tif (!missing.length) return state;\n-\tconst canMove = (placement: InternalPlacement, current: State): boolean => {\n-\t\tconst balance = current.balances.find((item) => item.id === placement.balanceId);\n-\t\treturn (\n-\t\t\t!placement.supporting &&\n-\t\t\t!targetDates.has(placement.date) &&\n-\t\t\t!protectedDates.has(placement.date) &&\n-\t\t\t!!balance &&\n-\t\t\t(placement.ruleIds.size\n-\t\t\t\t? isMovableTimeWindow(placement, context)\n-\t\t\t\t: isAtRisk(balance, context))\n-\t\t);\n-\t};\n-\tconst search = function* (index: number, current: State): PlanningSteps {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tif (index >= missing.length) return finalizeEarnedState(current, context);\n-\t\tconst date = missing[index];\n-\t\tconst movable = [...current.placements.values()]\n-\t\t\t.filter((placement) => canMove(placement, current))\n-\t\t\t.sort(\n-\t\t\t\t(a, b) =>\n-\t\t\t\t\tcompareDate(\n-\t\t\t\t\t\tcurrent.balances.find((item) => item.id === a.balanceId)!.expiryDate,\n-\t\t\t\t\t\tcurrent.balances.find((item) => item.id === b.balanceId)!.expiryDate,\n-\t\t\t\t\t) ||\n-\t\t\t\t\tcompareText(a.balanceId, b.balanceId) ||\n-\t\t\t\t\tcompareDate(a.date, b.date),\n+\t\tif (rule.type === 'optimization')\n+\t\t\tresult = yield* optimizeRulePlacements(result, context, index, true, rule);\n+\t\telse if (rule.type === 'time_window')\n+\t\t\tresult = associateCalendarPreference(\n+\t\t\t\tyield* optimizeRulePlacements(result, context, index, true, rule),\n+\t\t\t\trule,\n+\t\t\t\tcontext,\n \t\t\t);\n-\t\tfor (const source of movable) {\n-\t\t\tyield;\n-\t\t\tif (!compatibleWithRules(date, source.type, source.ruleIds, context)) {\n-\t\t\t\trecordTraceIneligible(\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tdate,\n-\t\t\t\t\t'rule-invalid',\n-\t\t\t\t\t'The date does not preserve the placement rules.',\n-\t\t\t\t\t[...source.ruleIds],\n-\t\t\t\t);\n-\t\t\t\tcontinue;\n-\t\t\t}\n-\t\t\tconst moved = cloneState(current);\n-\t\t\tmoved.placements.delete(source.date);\n-\t\t\tconst released = moved.balances.find((item) => item.id === source.balanceId);\n-\t\t\tif (!released) continue;\n-\t\t\treleased.remaining++;\n-\t\t\tconst reassigned = assignDateToBalance(\n-\t\t\t\tmoved,\n-\t\t\t\tdate,\n-\t\t\t\tsource.balanceId,\n+\t\telse\n+\t\t\tresult = associateCalendarPreference(\n+\t\t\t\t(yield* preferenceIfThen(result, rule, context, index)).state,\n+\t\t\t\trule,\n \t\t\t\tcontext,\n-\t\t\t\tsource.ruleIds,\n \t\t\t);\n-\t\t\tif (!reassigned) continue;\n-\t\t\tconst complete = yield* search(index + 1, reassigned);\n-\t\t\tif (complete) return complete;\n-\t\t}\n-\t\tfor (const balance of current.balances\n-\t\t\t.filter((item) => item.remaining > 0)\n-\t\t\t.sort((a, b) => compareDate(a.expiryDate, b.expiryDate) || compareText(a.id, b.id))) {\n-\t\t\tyield;\n-\t\t\tconst assigned = assignDateToBalance(current, date, balance.id, context);\n-\t\t\tif (!assigned) continue;\n-\t\t\tassigned.placements.get(date)!.supporting = !isAtRisk(balance, context);\n-\t\t\tconst complete = yield* search(index + 1, assigned);\n-\t\t\tif (complete) return complete;\n-\t\t}\n-\t\treturn null;\n+\t\tcontext.completedPreferenceStates.set(index, preferenceStateKey(result));\n \t};\n-\treturn yield* search(0, state);\n-}\n-\n-function* optimizeHolidayWeeks(\n-\tstate: State,\n-\tcontext: SearchContext,\n-\tpreferences: PreferenceResult[],\n-): PlanningSteps {\n-\tlet result = state;\n-\tconst candidates = context.holidayWeeks;\n-\twhile (true) {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tif (candidates.length) recordTraceDecision(context, []);\n-\t\tconst baseline = qualityMetrics(result, context, preferences);\n-\t\tconst completed = candidates.filter((candidate) =>\n-\t\t\tcandidate.dates.every(\n-\t\t\t\t(date) => result.placements.has(date) || context.declaredDates.has(date),\n-\t\t\t),\n-\t\t);\n-\t\tlet best: State | null = null;\n-\t\tlet bestMetrics = baseline;\n-\t\tlet bestEvaluation: MutableTraceCandidate | undefined;\n-\t\tfor (const candidate of candidates) {\n+\tyield* apply(preferenceIndex);\n+\t// An earned entitlement produced later can satisfy an earlier preference.\n+\tlet previous: PlanningObjective[];\n+\tdo {\n+\t\tprevious = activeObjectiveVector(result, context);\n+\t\tconst entitlements = result.balances\n+\t\t\t.map(\n+\t\t\t\t({ id, quantity, availableFrom, expiryDate }) =>\n+\t\t\t\t\t`${id}:${quantity}:${availableFrom}:${expiryDate}`,\n+\t\t\t)\n+\t\t\t.join('|');\n+\t\tfor (let index = 0; index < preferenceIndex; index++) {\n \t\t\tyield;\n-\t\t\tcontext.check();\n-\t\t\tconst candidateDates = candidate.dates.filter(\n-\t\t\t\t(date) => !context.declaredDates.has(date),\n-\t\t\t);\n-\t\t\tconst protectedDates = new Set(\n-\t\t\t\tcompleted\n-\t\t\t\t\t.filter((week) => week.value >= candidate.value)\n-\t\t\t\t\t.flatMap((week) => week.dates),\n-\t\t\t);\n-\t\t\tconst complete = yield* completeHolidayWeek(result, candidate, context, protectedDates);\n-\t\t\tif (!complete) continue;\n-\t\t\tconst metrics = qualityMetrics(complete, context, preferences);\n-\t\t\tif (\n-\t\t\t\tmetrics.unplacedAtRisk > baseline.unplacedAtRisk ||\n-\t\t\t\tcomparePreferenceVectors(\n-\t\t\t\t\tmetrics.preferenceSatisfaction,\n-\t\t\t\t\tbaseline.preferenceSatisfaction,\n-\t\t\t\t) !== 0 ||\n-\t\t\t\tmetrics.holidayWeekValue <= baseline.holidayWeekValue\n-\t\t\t) {\n-\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tresult,\n-\t\t\t\t\tcomplete,\n-\t\t\t\t\tpreferences,\n-\t\t\t\t\tbaseline,\n-\t\t\t\t\tmetrics,\n-\t\t\t\t\tcandidateDates,\n-\t\t\t\t\tundefined,\n-\t\t\t\t\t() => holidayWeekProtectionTraceDetails(baseline, metrics, preferences),\n-\t\t\t\t);\n-\t\t\t\tcontinue;\n-\t\t\t}\n-\t\t\tconst better =\n-\t\t\t\t!best ||\n-\t\t\t\tcompareMetrics(metrics, bestMetrics) < 0 ||\n-\t\t\t\t(compareMetrics(metrics, bestMetrics) === 0 &&\n-\t\t\t\t\tplacementTieKey(complete) < placementTieKey(best));\n-\t\t\tconst evaluation = retainAndRecordEvaluation(\n+\t\t\tyield* apply(index);\n+\t\t}\n+\t\tif (\n+\t\t\tcompareObjectiveLists(activeObjectiveVector(result, context), previous) < 0 ||\n+\t\t\tresult.balances\n+\t\t\t\t.map(\n+\t\t\t\t\t({ id, quantity, availableFrom, expiryDate }) =>\n+\t\t\t\t\t\t`${id}:${quantity}:${availableFrom}:${expiryDate}`,\n+\t\t\t\t)\n+\t\t\t\t.join('|') !== entitlements\n+\t\t)\n+\t\t\tyield* apply(preferenceIndex);\n+\t} while (compareObjectiveLists(activeObjectiveVector(result, context), previous) < 0);\n+\tpreferences.splice(\n+\t\t0,\n+\t\tpreferences.length,\n+\t\t...preferenceResultsForState(result, context).map((preference) => ({\n+\t\t\t...preference,\n+\t\t\treason: preferenceReason(\n+\t\t\t\tcontext.rules.find(\n+\t\t\t\t\t(rule): rule is NormalizedCalendarRule =>\n+\t\t\t\t\t\trule.type !== 'optimization' && rule.id === preference.ruleId,\n+\t\t\t\t)!,\n+\t\t\t\tpreference.satisfied,\n \t\t\t\tcontext,\n \t\t\t\tresult,\n-\t\t\t\tcomplete,\n-\t\t\t\tpreferences,\n-\t\t\t\tbaseline,\n-\t\t\t\tmetrics,\n-\t\t\t\tcandidateDates,\n-\t\t\t\tundefined,\n-\t\t\t\t() => {\n-\t\t\t\t\tconst protectedDetails = holidayWeekProtectionTraceDetails(\n-\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t);\n-\t\t\t\t\tconst incumbentDetails = best\n-\t\t\t\t\t\t? qualityMetricTieTraceDetails(bestMetrics, metrics, best, complete)\n-\t\t\t\t\t\t: undefined;\n-\t\t\t\t\treturn {\n-\t\t\t\t\t\ttechnicalComparison: [\n-\t\t\t\t\t\t\t...(protectedDetails.technicalComparison ?? []),\n-\t\t\t\t\t\t\t...(incumbentDetails?.technicalComparison ?? []),\n-\t\t\t\t\t\t],\n-\t\t\t\t\t\tfirstDecisiveComparator: protectedDetails.reason\n-\t\t\t\t\t\t\t? protectedDetails.firstDecisiveComparator\n-\t\t\t\t\t\t\t: incumbentDetails?.firstDecisiveComparator,\n-\t\t\t\t\t\treason: better\n-\t\t\t\t\t\t\t? undefined\n-\t\t\t\t\t\t\t: reason(\n-\t\t\t\t\t\t\t\t\t'quality-no-improvement',\n-\t\t\t\t\t\t\t\t\t'This completion did not outrank the current best on its compared objectives or date tie-break.',\n-\t\t\t\t\t\t\t\t),\n-\t\t\t\t\t};\n-\t\t\t\t},\n-\t\t\t);\n-\t\t\tif (better) {\n-\t\t\t\tif (bestEvaluation)\n-\t\t\t\t\tupdateTraceEvaluationReason(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tbestEvaluation,\n-\t\t\t\t\t\treason(\n-\t\t\t\t\t\t\t'quality-outperformed',\n-\t\t\t\t\t\t\t'A later holiday-week completion became the best result in this pass.',\n-\t\t\t\t\t\t),\n-\t\t\t\t\t);\n-\t\t\t\tbest = complete;\n-\t\t\t\tbestMetrics = metrics;\n-\t\t\t\tbestEvaluation = evaluation;\n-\t\t\t}\n-\t\t}\n-\t\tif (!best) return result;\n-\t\tretainAndRecordState(context, best, bestEvaluation);\n-\t\tresult = best;\n-\t}\n+\t\t\t),\n+\t\t})),\n+\t);\n+\treturn result;\n }\n \n-function sameHigherQuality(a: PlanningMetrics, b: PlanningMetrics): boolean {\n-\treturn (\n-\t\ta.unplacedAtRisk === b.unplacedAtRisk &&\n-\t\ta.holidayWeekValue === b.holidayWeekValue &&\n-\t\ta.nonWorkingDayGain === b.nonWorkingDayGain &&\n-\t\ta.longestWorkSequence === b.longestWorkSequence &&\n-\t\ta.shortSequenceDeficit === b.shortSequenceDeficit &&\n-\t\ta.preferenceSatisfaction.length === b.preferenceSatisfaction.length &&\n-\t\ta.preferenceSatisfaction.every((value, index) => value === b.preferenceSatisfaction[index])\n-\t);\n+function preferenceStateKey(state: State): string {\n+\t// Preserve iteration order: a coordinated allocator may keep its first valid branch.\n+\treturn JSON.stringify([\n+\t\tstate.balances,\n+\t\t[...state.placements].map(([date, placement]) => [\n+\t\t\tdate,\n+\t\t\t{ ...placement, ruleIds: [...placement.ruleIds] },\n+\t\t]),\n+\t\tstate.earnedActivations,\n+\t]);\n }\n \n-function expiryProtectionTraceDetails(\n-\tbaseline: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tpreferences: readonly PreferenceResult[],\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst reject = (name: string): QualityTraceDetails => ({\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: name,\n-\t\treason: reason(\n-\t\t\t'quality-protected-objective',\n-\t\t\t`This replacement changes ${name.slice('protected:'.length).replaceAll('-', ' ')} protected by the expiry pass.`,\n-\t\t),\n-\t});\n-\tfor (const [name, direction, before, after] of [\n-\t\t[\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'minimize',\n-\t\t\tbaseline.unplacedAtRisk,\n-\t\t\tcandidate.unplacedAtRisk,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:holiday-week-value',\n-\t\t\t'maximize',\n-\t\t\tbaseline.holidayWeekValue,\n-\t\t\tcandidate.holidayWeekValue,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:non-working-day-gain',\n-\t\t\t'maximize',\n-\t\t\tbaseline.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:longest-work-sequence',\n-\t\t\t'minimize',\n-\t\t\tbaseline.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:short-sequence-deficit',\n-\t\t\t'minimize',\n-\t\t\tbaseline.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit,\n-\t\t],\n-\t] as const) {\n-\t\tif (!addQualityComparator(values, name, direction, before, after)) return reject(name);\n-\t}\n-\tif (baseline.preferenceSatisfaction.length !== candidate.preferenceSatisfaction.length) {\n-\t\tconst name = 'protected:preference-count';\n-\t\taddQualityComparator(\n-\t\t\tvalues,\n-\t\t\tname,\n-\t\t\t'maximize',\n-\t\t\tbaseline.preferenceSatisfaction.length,\n-\t\t\tcandidate.preferenceSatisfaction.length,\n-\t\t);\n-\t\treturn reject(name);\n-\t}\n-\tfor (let index = 0; index < baseline.preferenceSatisfaction.length; index++) {\n-\t\tconst name = `protected:preference:${preferences[index]?.ruleId ?? index}`;\n-\t\tif (\n-\t\t\t!addQualityComparator(\n-\t\t\t\tvalues,\n-\t\t\t\tname,\n-\t\t\t\t'maximize',\n-\t\t\t\tbaseline.preferenceSatisfaction[index],\n-\t\t\t\tcandidate.preferenceSatisfaction[index],\n-\t\t\t)\n+function placementTieKey(state: State): string {\n+\treturn [...state.placements.values()]\n+\t\t.map((placement) => placement.date)\n+\t\t.sort(compareDate)\n+\t\t.join('|');\n+}\n+\n+function expiryTieKey(state: State): string {\n+\treturn [...state.placements.values()]\n+\t\t.map(\n+\t\t\t(placement) =>\n+\t\t\t\tstate.balances.find((item) => item.id === placement.balanceId)?.expiryDate ?? '',\n \t\t)\n-\t\t\treturn reject(name);\n-\t}\n-\treturn { technicalComparison: values };\n+\t\t.sort(compareDate)\n+\t\t.join('|');\n }\n \n-function* optimizeExpiryPlacements(\n+function activeObjectiveVector(\n \tstate: State,\n \tcontext: SearchContext,\n-\tpreferences: PreferenceResult[],\n-): PlanningSteps {\n-\tlet result = state;\n-\tfor (const original of [...result.placements.values()]\n-\t\t.filter(\n-\t\t\t(placement) => placement.ruleIds.size === 0 || isMovableTimeWindow(placement, context),\n-\t\t)\n-\t\t.sort((a, b) => compareDate(a.date, b.date) || compareText(a.balanceId, b.balanceId))) {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tconst current = result.placements.get(original.date);\n-\t\tif (!current) continue;\n-\t\tconst source = result.balances.find((balance) => balance.id === current.balanceId);\n-\t\tif (!source) continue;\n-\t\trecordTraceDecision(context, [original.date]);\n-\t\tconst baseline = qualityMetrics(result, context, preferences);\n-\t\tconst without = cloneState(result);\n-\t\twithout.placements.delete(current.date);\n-\t\tconst released = without.balances.find((balance) => balance.id === source.id);\n-\t\tif (released) released.remaining++;\n-\t\tlet best = result;\n-\t\tlet bestExpiry = expiryTieKey(result);\n-\t\tlet bestEvaluation: MutableTraceCandidate | undefined;\n-\t\tfor (const replacement of without.balances\n-\t\t\t.filter(\n-\t\t\t\t(balance) =>\n-\t\t\t\t\tbalance.id !== source.id &&\n-\t\t\t\t\tbalance.type === current.type &&\n-\t\t\t\t\tbalance.remaining > 0 &&\n-\t\t\t\t\tcompareDate(balance.expiryDate, source.expiryDate) < 0 &&\n-\t\t\t\t\tcompareDate(balance.availableFrom, current.date) <= 0 &&\n-\t\t\t\t\tcompareDate(current.date, balance.expiryDate) <= 0,\n-\t\t\t)\n-\t\t\t.sort((a, b) => compareDate(a.expiryDate, b.expiryDate) || compareText(a.id, b.id))) {\n-\t\t\tyield;\n-\t\t\tconst candidate = assignDateToBalance(\n-\t\t\t\twithout,\n-\t\t\t\tcurrent.date,\n-\t\t\t\treplacement.id,\n-\t\t\t\tcontext,\n-\t\t\t\tcurrent.ruleIds,\n-\t\t\t);\n-\t\t\tif (!candidate) continue;\n-\t\t\tconst feasibleCandidate = finalizeEarnedState(candidate, context);\n-\t\t\tif (!feasibleCandidate) continue;\n-\t\t\tfeasibleCandidate.placements.get(current.date)!.supporting = current.supporting;\n-\t\t\tconst metrics = qualityMetrics(feasibleCandidate, context, preferences);\n-\t\t\tconst expiry = expiryTieKey(feasibleCandidate);\n-\t\t\tconst preservesQuality = sameHigherQuality(metrics, baseline);\n-\t\t\tconst better = preservesQuality && expiry < bestExpiry;\n-\t\t\tconst evaluation = retainAndRecordEvaluation(\n-\t\t\t\tcontext,\n-\t\t\t\tresult,\n-\t\t\t\tfeasibleCandidate,\n-\t\t\t\tpreferences,\n-\t\t\t\tbaseline,\n-\t\t\t\tmetrics,\n-\t\t\t\t[current.date],\n-\t\t\t\tcurrent.date,\n-\t\t\t\t() => {\n-\t\t\t\t\tconst protectedDetails = expiryProtectionTraceDetails(\n-\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t);\n-\t\t\t\t\tconst values = [...(protectedDetails.technicalComparison ?? [])];\n-\t\t\t\t\tlet firstDecisiveComparator = protectedDetails.firstDecisiveComparator;\n-\t\t\t\t\tlet candidateReason = protectedDetails.reason;\n-\t\t\t\t\tif (!candidateReason) {\n-\t\t\t\t\t\tconst equalExpiry = addQualityComparator(\n-\t\t\t\t\t\t\tvalues,\n-\t\t\t\t\t\t\t'balance-expiry',\n-\t\t\t\t\t\t\t'minimize',\n-\t\t\t\t\t\t\tbestExpiry,\n-\t\t\t\t\t\t\texpiry,\n-\t\t\t\t\t\t);\n-\t\t\t\t\t\tif (!equalExpiry) firstDecisiveComparator = 'balance-expiry';\n-\t\t\t\t\t\tif (!better)\n-\t\t\t\t\t\t\tcandidateReason = reason(\n-\t\t\t\t\t\t\t\t'quality-no-improvement',\n-\t\t\t\t\t\t\t\t'This replacement does not use an earlier-expiring balance than the current best.',\n-\t\t\t\t\t\t\t);\n-\t\t\t\t\t}\n-\t\t\t\t\treturn {\n-\t\t\t\t\t\ttechnicalComparison: values,\n-\t\t\t\t\t\tfirstDecisiveComparator,\n-\t\t\t\t\t\treason: candidateReason,\n-\t\t\t\t\t};\n-\t\t\t\t},\n-\t\t\t);\n-\t\t\tif (better) {\n-\t\t\t\tif (bestEvaluation)\n-\t\t\t\t\tupdateTraceEvaluationReason(\n+\tthroughIndex = Number.POSITIVE_INFINITY,\n+): PlanningObjective[] {\n+\tconst preferences = preferenceResultsForState(state, context);\n+\tlet observations: OptimizationObservations | undefined;\n+\treturn context.rules\n+\t\t.filter((rule) => rule.enabled && rule.force === 'preference')\n+\t\t.slice(0, throughIndex + 1)\n+\t\t.map((rule) => {\n+\t\t\tif (rule.type === 'optimization') {\n+\t\t\t\tobservations ??= context.rules.some(\n+\t\t\t\t\t(item) =>\n+\t\t\t\t\t\titem.type === 'optimization' &&\n+\t\t\t\t\t\titem.configuration.elements !== 'leave-balances',\n+\t\t\t\t)\n+\t\t\t\t\t? optimizationObservations(state, context)\n+\t\t\t\t\t: {\n+\t\t\t\t\t\t\tleaveBalances: optimizationBalanceObservations(state, context),\n+\t\t\t\t\t\t\tpublicHolidayWeeks: [],\n+\t\t\t\t\t\t\ttimeOffPeriods: [],\n+\t\t\t\t\t\t\tworkSequences: [],\n+\t\t\t\t\t\t\tleavePlacements: [],\n+\t\t\t\t\t\t};\n+\t\t\t\treturn {\n+\t\t\t\t\tid: `optimization:${rule.id}` as const,\n+\t\t\t\t\tdirection: rule.configuration!.direction,\n+\t\t\t\t\tvalue: evaluateStateOptimization(\n+\t\t\t\t\t\trule.configuration!,\n+\t\t\t\t\t\tstate,\n \t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tbestEvaluation,\n-\t\t\t\t\t\treason(\n-\t\t\t\t\t\t\t'quality-outperformed',\n-\t\t\t\t\t\t\t'A later replacement became the best earlier-expiry choice in this pass.',\n-\t\t\t\t\t\t),\n-\t\t\t\t\t);\n-\t\t\t\tbest = feasibleCandidate;\n-\t\t\t\tbestExpiry = expiry;\n-\t\t\t\tbestEvaluation = evaluation;\n+\t\t\t\t\t\tobservations,\n+\t\t\t\t\t),\n+\t\t\t\t\tlabel: rule.name,\n+\t\t\t\t};\n \t\t\t}\n-\t\t}\n-\t\tif (best !== result) retainAndRecordState(context, best, bestEvaluation);\n-\t\tresult = best;\n-\t}\n-\treturn result;\n+\t\t\treturn {\n+\t\t\t\tid: `preference:${rule.id}` as const,\n+\t\t\t\tdirection: 'maximize' as const,\n+\t\t\t\tvalue:\n+\t\t\t\t\tpreferences.find((preference) => preference.ruleId === rule.id)?.satisfied ?? 0,\n+\t\t\t\tlabel: rule.name,\n+\t\t\t};\n+\t\t});\n+}\n+\n+function tieBreakObjectives(state: State): PlanningObjective[] {\n+\treturn [\n+\t\t{\n+\t\t\tid: 'balance-expiry',\n+\t\t\tdirection: 'minimize',\n+\t\t\tvalue: expiryTieKey(state),\n+\t\t\tlabel: 'Balance expiry tie-break',\n+\t\t},\n+\t\t{\n+\t\t\tid: 'placement-date',\n+\t\t\tdirection: 'minimize',\n+\t\t\tvalue: placementTieKey(state),\n+\t\t\tlabel: 'Placement date tie-break',\n+\t\t},\n+\t];\n+}\n+\n+function objectiveComparisonFacts(\n+\tbefore: readonly PlanningObjective[],\n+\tafter: readonly PlanningObjective[],\n+): {\n+\tvalues: NonNullable;\n+\tfirstDecisiveComparator?: string;\n+} {\n+\tconst first = firstDifferentObjective(after, before);\n+\treturn {\n+\t\tvalues: after.slice(0, first < 0 ? after.length : first + 1).map((objective, index) => ({\n+\t\t\tname: objective.id,\n+\t\t\tdirection: objective.direction,\n+\t\t\tbefore: before[index].value,\n+\t\t\tafter: objective.value,\n+\t\t})),\n+\t\tfirstDecisiveComparator: first < 0 ? undefined : after[first].id,\n+\t};\n+}\n+\n+function obligationPreviewObjectives(\n+\tpreview: { state: State },\n+\tcontext: SearchContext,\n+): PlanningObjective[] {\n+\treturn [...activeObjectiveVector(preview.state, context), ...tieBreakObjectives(preview.state)];\n+}\n+\n+/** Compare complete previews so obligation DFS does not commit to its first feasible branch. */\n+function compareObligationPreviews(\n+\ta: { state: State },\n+\tb: { state: State },\n+\tcontext: SearchContext,\n+): number {\n+\treturn compareObjectiveLists(\n+\t\tobligationPreviewObjectives(a, context),\n+\t\tobligationPreviewObjectives(b, context),\n+\t);\n+}\n+\n+function obligationPreviewComparisonFacts(\n+\ta: { state: State },\n+\tb: { state: State },\n+\tcontext: SearchContext,\n+): {\n+\tvalues: NonNullable;\n+\tfirstDecisiveComparator?: string;\n+} {\n+\treturn objectiveComparisonFacts(\n+\t\tobligationPreviewObjectives(b, context),\n+\t\tobligationPreviewObjectives(a, context),\n+\t);\n+}\n+\n+function recordTraceDecision(context: SearchContext, dates: readonly string[]): void {\n+\tobserveTrace(context, (trace) => trace.recordDecision('choose', dates));\n }\n \n function isAtRisk(balance: InternalBalance, context: SearchContext): boolean {\n@@ -4910,36 +5052,17 @@ function isAtRisk(balance: InternalBalance, context: SearchContext): boolean {\n \t);\n }\n \n-function isMovableTimeWindow(placement: InternalPlacement, context: SearchContext): boolean {\n-\tif (!placement.ruleIds.size) return false;\n-\treturn [...placement.ruleIds].every((id) => {\n-\t\tconst rule = context.rules.find((item) => item.id === id);\n-\t\treturn rule?.enabled && rule.type === 'time_window';\n-\t});\n+function isNaturalNonWorkingDate(date: string, context: SearchContext): boolean {\n+\treturn context.calendarIndex.has(date)\n+\t\t? !context.workingCalendar.has(date)\n+\t\t: !isWorkingPlanningDate(date);\n }\n \n-function compatibleWithRules(\n-\tdate: string,\n-\ttype: LeaveType,\n-\truleIds: Set,\n-\tcontext: SearchContext,\n-): boolean {\n-\tif (!isWorking(date, context.holidays)) return false;\n-\tfor (const id of ruleIds) {\n-\t\tconst rule = context.rules.find((item) => item.id === id);\n-\t\tif (\n-\t\t\t!rule ||\n-\t\t\trule.type !== 'time_window' ||\n-\t\t\t!selectorMatches(rule.placeType, type) ||\n-\t\t\tcompareDate(date, rule.startDate!) < 0 ||\n-\t\t\tcompareDate(date, rule.endDate!) > 0\n-\t\t)\n-\t\t\treturn false;\n-\t}\n-\treturn true;\n+function calendarDateAt(index: number, context: SearchContext): string {\n+\treturn context.calendarDays[index] ?? addDays(context.calendarDays[0], index);\n }\n \n-function periodData(state: State, context: SearchContext): TimeOffPeriod[] {\n+function periodBounds(state: State, context: SearchContext) {\n \tconst dates = [...new Set([...state.placements.keys(), ...context.declaredDates])]\n \t\t.filter((date) => date >= context.horizon.start && date < context.horizon.end)\n \t\t.sort(compareDate);\n@@ -4959,89 +5082,209 @@ function periodData(state: State, context: SearchContext): TimeOffPeriod[] {\n \t\t}\n \t}\n \tgroups.push(group);\n-\tconst isNaturalNonWorkingDate = (date: string) =>\n-\t\tcontext.calendarIndex.has(date)\n-\t\t\t? !context.workingCalendar.has(date)\n-\t\t\t: !isWorkingPlanningDate(date);\n-\tconst dateAt = (index: number) =>\n-\t\tcontext.calendarDays[index] ?? addDays(context.calendarDays[0], index);\n \treturn groups.map((anchors) => {\n \t\tcontext.check();\n \t\tlet startIndex = context.calendarIndex.get(anchors[0])!;\n \t\tlet endIndex = context.calendarIndex.get(anchors[anchors.length - 1])!;\n \t\twhile (\n-\t\t\tcontext.declaredDates.has(dateAt(startIndex - 1)) ||\n-\t\t\tisNaturalNonWorkingDate(dateAt(startIndex - 1))\n+\t\t\tcontext.declaredDates.has(calendarDateAt(startIndex - 1, context)) ||\n+\t\t\tisNaturalNonWorkingDate(calendarDateAt(startIndex - 1, context), context)\n \t\t) {\n \t\t\tcontext.check();\n \t\t\tstartIndex--;\n \t\t}\n \t\twhile (\n-\t\t\tcontext.declaredDates.has(dateAt(endIndex + 1)) ||\n-\t\t\tisNaturalNonWorkingDate(dateAt(endIndex + 1))\n+\t\t\tcontext.declaredDates.has(calendarDateAt(endIndex + 1, context)) ||\n+\t\t\tisNaturalNonWorkingDate(calendarDateAt(endIndex + 1, context), context)\n \t\t) {\n \t\t\tcontext.check();\n \t\t\tendIndex++;\n \t\t}\n-\t\tconst start = dateAt(startIndex);\n-\t\tconst end = dateAt(endIndex);\n-\t\tconst allDates =\n+\t\treturn { anchors, startIndex, endIndex };\n+\t});\n+}\n+\n+function calendarPeriod(\n+\tstartIndex: number,\n+\tendIndex: number,\n+\tcontext: SearchContext,\n+): CalendarPeriod {\n+\tlet periods = calendarPeriodCache.get(context);\n+\tif (!periods) {\n+\t\tperiods = new Map();\n+\t\tcalendarPeriodCache.set(context, periods);\n+\t}\n+\tconst key = `${startIndex}:${endIndex}`;\n+\tlet period = periods.get(key);\n+\tif (period) periods.delete(key);\n+\telse {\n+\t\tconst start = calendarDateAt(startIndex, context);\n+\t\tconst end = calendarDateAt(endIndex, context);\n+\t\tconst dates =\n \t\t\tstartIndex >= 0 && endIndex < context.calendarDays.length\n \t\t\t\t? context.calendarDays.slice(startIndex, endIndex + 1)\n \t\t\t\t: dateRange(start, addDays(end, 1));\n-\t\tconst nonWorkingDates = allDates.filter(isNaturalNonWorkingDate);\n-\t\tconst declaredDates = allDates.filter((date) => context.declaredDates.has(date));\n-\t\treturn {\n+\t\tperiod = Object.freeze({\n \t\t\tstart,\n \t\t\tend,\n-\t\t\tduration: allDates.length,\n+\t\t\tduration: dates.length,\n+\t\t\tnonWorkingDates: Object.freeze(\n+\t\t\t\tdates.filter((date) => isNaturalNonWorkingDate(date, context)),\n+\t\t\t),\n+\t\t\tdeclaredDates: Object.freeze(dates.filter((date) => context.declaredDates.has(date))),\n+\t\t});\n+\t}\n+\tperiods.set(key, period);\n+\tif (periods.size > 4096) periods.delete(periods.keys().next().value!);\n+\treturn period;\n+}\n+\n+function periodData(state: State, context: SearchContext): TimeOffPeriod[] {\n+\treturn periodBounds(state, context).map(({ anchors, startIndex, endIndex }) => {\n+\t\tconst period = calendarPeriod(startIndex, endIndex, context);\n+\t\treturn {\n+\t\t\tstart: period.start,\n+\t\t\tend: period.end,\n+\t\t\tduration: period.duration,\n \t\t\tplacementDates: anchors.filter((date) => state.placements.has(date)),\n-\t\t\t...(declaredDates.length ? { declaredDates } : {}),\n-\t\t\tnonWorkingDates,\n-\t\t\tnonWorkingDayGain: nonWorkingDates.length,\n+\t\t\t...(period.declaredDates.length ? { declaredDates: [...period.declaredDates] } : {}),\n+\t\t\tnonWorkingDates: [...period.nonWorkingDates],\n+\t\t\tnonWorkingDayGain: period.nonWorkingDates.length,\n \t\t};\n \t});\n }\n \n-function unplacedAtRiskQuantity(state: State, context: SearchContext): number {\n-\treturn state.balances.reduce(\n-\t\t(total, balance) => total + (isAtRisk(balance, context) ? balance.remaining : 0),\n-\t\t0,\n-\t);\n+function optimizationBalanceObservations(state: State, context: SearchContext) {\n+\treturn state.balances.map((balance) => ({\n+\t\tunplacedQuantity: balance.remaining,\n+\t\tatRisk: isAtRisk(balance, context),\n+\t}));\n }\n \n-function qualityMetrics(\n+function optimizationObservations(\n \tstate: State,\n \tcontext: SearchContext,\n-\tpreferences: readonly PreferenceResult[],\n-): PlanningMetrics {\n-\tconst periods = periodData(state, context);\n-\tconst timeOffDates = new Set([...state.placements.keys(), ...context.declaredDates]);\n-\tconst sequences: number[] = [];\n-\tlet current = 0;\n-\tlet hasTimeOff = false;\n+\tperiods?: TimeOffPeriod[],\n+): OptimizationObservations {\n+\t// Calendar facts depend only on occupied dates within this immutable request.\n+\t// Balance quantities, provenance and supporting status stay outside this cache.\n+\tconst key = placementTieKey(state);\n+\tlet byDates = calendarObservationCache.get(context);\n+\tif (!byDates) {\n+\t\tbyDates = new Map();\n+\t\tcalendarObservationCache.set(context, byDates);\n+\t}\n+\tlet calendar = byDates.get(key);\n+\tif (calendar) byDates.delete(key);\n+\telse {\n+\t\tcalendar = Object.freeze({\n+\t\t\tpublicHolidayWeeks: Object.freeze(\n+\t\t\t\tcontext.holidayWeeks.map((week) =>\n+\t\t\t\t\tObject.freeze({\n+\t\t\t\t\t\tvalue: week.value,\n+\t\t\t\t\t\tcomplete: week.dates.every(\n+\t\t\t\t\t\t\t(date) => state.placements.has(date) || context.declaredDates.has(date),\n+\t\t\t\t\t\t),\n+\t\t\t\t\t}),\n+\t\t\t\t),\n+\t\t\t),\n+\t\t\ttimeOffPeriods: Object.freeze(\n+\t\t\t\tperiods\n+\t\t\t\t\t? periods.map((period) =>\n+\t\t\t\t\t\t\tObject.freeze({\n+\t\t\t\t\t\t\t\tnonWorkingDates: Object.freeze([...period.nonWorkingDates]),\n+\t\t\t\t\t\t\t}),\n+\t\t\t\t\t\t)\n+\t\t\t\t\t: periodBounds(state, context).map(({ startIndex, endIndex }) =>\n+\t\t\t\t\t\t\tObject.freeze({\n+\t\t\t\t\t\t\t\tnonWorkingDates: calendarPeriod(startIndex, endIndex, context)\n+\t\t\t\t\t\t\t\t\t.nonWorkingDates,\n+\t\t\t\t\t\t\t}),\n+\t\t\t\t\t\t),\n+\t\t\t),\n+\t\t\tworkSequences: Object.freeze(\n+\t\t\t\tworkSequenceDates(state, context).map(({ dates, internal }) =>\n+\t\t\t\t\tObject.freeze({ length: dates.length, internal }),\n+\t\t\t\t),\n+\t\t\t),\n+\t\t});\n+\t\tif (byDates.size >= 4096) byDates.delete(byDates.keys().next().value!);\n+\t}\n+\tbyDates.set(key, calendar);\n+\treturn {\n+\t\tleaveBalances: optimizationBalanceObservations(state, context),\n+\t\t...calendar,\n+\t\tleavePlacements: [...state.placements.values()],\n+\t};\n+}\n+\n+function workSequenceDates(state: State, context: SearchContext) {\n+\tconst sequences: string[][] = [];\n+\tlet current: string[] = [];\n+\tlet inTimeOffPeriod = false;\n \tfor (const date of context.workingDays) {\n \t\tcontext.check();\n-\t\tif (timeOffDates.has(date)) {\n-\t\t\tsequences.push(current);\n-\t\t\tcurrent = 0;\n-\t\t\thasTimeOff = true;\n-\t\t} else current++;\n+\t\tif (state.placements.has(date) || context.declaredDates.has(date)) {\n+\t\t\tif (!inTimeOffPeriod) sequences.push(current);\n+\t\t\tcurrent = [];\n+\t\t\tinTimeOffPeriod = true;\n+\t\t} else {\n+\t\t\tcurrent.push(date);\n+\t\t\tinTimeOffPeriod = false;\n+\t\t}\n \t}\n \tif (context.workingDays.length) sequences.push(current);\n-\tconst nonEmptySequences = sequences.filter((length) => length > 0);\n-\tconst internal = hasTimeOff ? sequences.slice(1, -1) : [];\n-\tconst shortSequenceDeficit = internal.reduce(\n-\t\t(sum, length) => sum + (length > 0 && length < 5 ? 5 - length : 0),\n-\t\t0,\n-\t);\n+\treturn sequences.map((dates, index) => ({\n+\t\tdates,\n+\t\tinternal: index > 0 && index < sequences.length - 1,\n+\t}));\n+}\n+\n+function evaluateStateOptimization(\n+\tconfiguration: OptimizationConfiguration,\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tobservations = optimizationObservations(state, context),\n+): number {\n+\treturn evaluateOptimization(configuration, observations);\n+}\n+\n+function qualityMetrics(\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tpreferences: readonly PreferenceResult[],\n+): PlanningMetrics {\n+\tconst periods = periodData(state, context);\n+\tconst observations = optimizationObservations(state, context, periods);\n+\tconst nonEmptySequences = observations.workSequences.filter((sequence) => sequence.length > 0);\n \treturn {\n-\t\tunplacedAtRisk: unplacedAtRiskQuantity(state, context),\n-\t\tholidayWeekValue: holidayWeekValue(state, context),\n-\t\tnonWorkingDayGain: periods.reduce((sum, period) => sum + period.nonWorkingDayGain, 0),\n-\t\tlongestWorkSequence: sequences.length ? Math.max(...sequences) : 0,\n+\t\tunplacedAtRisk: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n+\t\tholidayWeekValue: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n+\t\tnonWorkingDayGain: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.nonWorkingDayGain,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n+\t\tlongestWorkSequence: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.longestWorkSequence,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n \t\taverageWorkSequence: nonEmptySequences.length\n-\t\t\t? nonEmptySequences.reduce((sum, length) => sum + length, 0) / nonEmptySequences.length\n+\t\t\t? nonEmptySequences.reduce((sum, sequence) => sum + sequence.length, 0) /\n+\t\t\t\tnonEmptySequences.length\n \t\t\t: null,\n \t\taverageTimeOffPeriod: periods.length\n \t\t\t? periods.reduce((sum, period) => sum + period.duration, 0) / periods.length\n@@ -5049,10 +5292,18 @@ function qualityMetrics(\n \t\tlongestTimeOffPeriod: periods.length\n \t\t\t? Math.max(...periods.map((period) => period.duration))\n \t\t\t: null,\n-\t\tshortSequenceDeficit,\n-\t\tsupportingPlacements: [...state.placements.values()].filter(\n-\t\t\t(placement) => placement.supporting,\n-\t\t).length,\n+\t\tshortSequenceDeficit: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n+\t\tsupportingPlacements: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n \t\tpreferenceSatisfaction: preferences.map((preference) => preference.satisfied),\n \t};\n }\n@@ -5094,8 +5345,8 @@ function nonPlacementReason(\n \t\t\t'This balance expires after the horizon; the planner retained no additional placement under its planning priorities.',\n \t\t);\n \treturn reason(\n-\t\t'not-established',\n-\t\t'The calculation did not establish a precise reason for leaving this balance unspent.',\n+\t\t'active-priorities',\n+\t\t'The calculation retained no additional placement under the active planning rules.',\n \t);\n }\n \n@@ -5127,103 +5378,51 @@ function remainingBalances(\n \t\t});\n }\n \n-function unsatisfiedObligationCount(state: State, context: SearchContext): number {\n-\tconst placementCounts = new Map();\n-\tfor (const placement of state.placements.values())\n-\t\tfor (const ruleId of placement.ruleIds)\n-\t\t\tplacementCounts.set(ruleId, (placementCounts.get(ruleId) ?? 0) + 1);\n-\tlet unsatisfied = 0;\n-\tfor (const requirement of buildRequirements(context.rules, context, 'obligation')) {\n-\t\tif (!requirement.patterns) {\n-\t\t\tif ((placementCounts.get(requirement.rule.id) ?? 0) !== requirement.requiredPlacements)\n-\t\t\t\tunsatisfied++;\n-\t\t\tcontinue;\n-\t\t}\n-\t\tlet complete = false;\n-\t\tfor (const pattern of requirement.patterns) {\n-\t\t\tif (\n-\t\t\t\tpattern.every((date) =>\n-\t\t\t\t\tpatternDateSatisfied(date, requirement.rule, state, context),\n-\t\t\t\t)\n-\t\t\t) {\n-\t\t\t\tcomplete = true;\n-\t\t\t\tbreak;\n-\t\t\t}\n-\t\t}\n-\t\tif (!complete) unsatisfied++;\n-\t}\n-\treturn unsatisfied;\n-}\n-\n-function objectiveVector(\n-\tmetrics: PlanningMetrics,\n-\tpreferences: readonly PreferenceResult[],\n-\tstate: State,\n-\tcontext: SearchContext,\n-): PlanningObjectiveVector {\n-\tconst objectives: PlanningObjective[] = [\n-\t\t{\n-\t\t\tid: 'obligation-validity',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: unsatisfiedObligationCount(state, context),\n-\t\t\tlabel: 'Unsatisfied obligations',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'unplaced-at-risk',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: metrics.unplacedAtRisk,\n-\t\t\tlabel: 'Unplaced at-risk leave',\n-\t\t},\n-\t\t...preferences.map((preference) => ({\n-\t\t\tid: `preference:${preference.ruleId}` as const,\n-\t\t\tdirection: 'maximize' as const,\n-\t\t\tvalue: preference.satisfied,\n-\t\t\tlabel: `Preference ${preference.ruleId}`,\n-\t\t})),\n-\t\t{\n-\t\t\tid: 'holiday-week-value',\n-\t\t\tdirection: 'maximize',\n-\t\t\tvalue: metrics.holidayWeekValue,\n-\t\t\tlabel: 'Public-holiday week value',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'non-working-day-gain',\n-\t\t\tdirection: 'maximize',\n-\t\t\tvalue: metrics.nonWorkingDayGain,\n-\t\t\tlabel: 'Non-working-day gain',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'longest-work-sequence',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: metrics.longestWorkSequence,\n-\t\t\tlabel: 'Longest work sequence',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'short-sequence-deficit',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: metrics.shortSequenceDeficit,\n-\t\t\tlabel: 'Short work-sequence deficit',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'supporting-placements',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: metrics.supportingPlacements,\n-\t\t\tlabel: 'Supporting placements',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'balance-expiry',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: expiryTieKey(state),\n-\t\t\tlabel: 'Balance expiry tie-break',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'placement-date',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: placementTieKey(state),\n-\t\t\tlabel: 'Placement date tie-break',\n-\t\t},\n-\t];\n-\treturn { objectives };\n+function unsatisfiedObligationCount(state: State, context: SearchContext): number {\n+\tconst placementCounts = new Map();\n+\tfor (const placement of state.placements.values())\n+\t\tfor (const ruleId of placement.ruleIds)\n+\t\t\tplacementCounts.set(ruleId, (placementCounts.get(ruleId) ?? 0) + 1);\n+\tlet unsatisfied = 0;\n+\tfor (const requirement of buildRequirements(context.rules, context, 'obligation')) {\n+\t\tif (!requirement.patterns) {\n+\t\t\tif ((placementCounts.get(requirement.rule.id) ?? 0) !== requirement.requiredPlacements)\n+\t\t\t\tunsatisfied++;\n+\t\t\tcontinue;\n+\t\t}\n+\t\tlet complete = false;\n+\t\tfor (const pattern of requirement.patterns) {\n+\t\t\tif (\n+\t\t\t\tpattern.every((date) =>\n+\t\t\t\t\tpatternDateSatisfied(date, requirement.rule, state, context),\n+\t\t\t\t)\n+\t\t\t) {\n+\t\t\t\tcomplete = true;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n+\t\tif (!complete) unsatisfied++;\n+\t}\n+\treturn unsatisfied;\n+}\n+\n+function objectiveVector(\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tactive = activeObjectiveVector(state, context),\n+): PlanningObjectiveVector {\n+\treturn {\n+\t\tobjectives: [\n+\t\t\t{\n+\t\t\t\tid: 'obligation-validity',\n+\t\t\t\tdirection: 'minimize',\n+\t\t\t\tvalue: unsatisfiedObligationCount(state, context),\n+\t\t\t\tlabel: 'Unsatisfied obligations',\n+\t\t\t},\n+\t\t\t...active,\n+\t\t\t...tieBreakObjectives(state),\n+\t\t],\n+\t};\n }\n \n function displayLabel(value: unknown, fallback: string): string {\n@@ -5237,7 +5436,9 @@ function timeWindowContributions(state: State, context: SearchContext): TimeWind\n \t\t| Record\n \t\t| undefined;\n \treturn context.rules\n-\t\t.filter((rule) => rule.enabled && rule.type === 'time_window')\n+\t\t.filter(\n+\t\t\t(rule): rule is NormalizedCalendarRule => rule.enabled && rule.type === 'time_window',\n+\t\t)\n \t\t.flatMap((rule) => {\n \t\t\tconst declaredDays = declaredWindowDays(rule, context);\n \t\t\treturn declaredDays.length\n@@ -5266,16 +5467,12 @@ function ifThenContributions(state: State, context: SearchContext): IfThenContri\n \t\t| Record\n \t\t| undefined;\n \treturn context.rules\n-\t\t.filter((rule) => rule.enabled && rule.type === 'if_then')\n+\t\t.filter((rule): rule is NormalizedCalendarRule => rule.enabled && rule.type === 'if_then')\n \t\t.flatMap((rule) =>\n \t\t\toccurrences(rule, context).flatMap((occurrence) => {\n \t\t\t\tconst id = `earned:${rule.id}:${occurrence}`;\n \t\t\t\tconst activation = state.earnedActivations.find((item) => item.id === id);\n-\t\t\t\tconst pattern =\n-\t\t\t\t\tactivation?.dates ??\n-\t\t\t\t\tpatternsFor(rule, occurrence, context).find((dates) =>\n-\t\t\t\t\t\tdates.every((date) => patternDateSatisfied(date, rule, state, context)),\n-\t\t\t\t\t);\n+\t\t\t\tconst pattern = selectedOccurrencePattern(rule, occurrence, state, context);\n \t\t\t\tif (!pattern) return [];\n \t\t\t\tconst declaredDays = pattern.flatMap((date) => {\n \t\t\t\t\tconst day = declaredPatternDay(date, rule.placeType, context);\n@@ -5328,7 +5525,7 @@ function planExplanation(\n \tconst rawRules = Array.isArray(source.rules) ? source.rules : [];\n \tconst labels = recordValue(source.labels) as Record | undefined;\n \tconst identities = recordValue(source.identities) as Record | undefined;\n-\tconst vector = objectiveVector(metrics, preferences, state, context);\n+\tconst vector = objectiveVector(state, context);\n \tconst windowContributions = timeWindowContributions(state, context);\n \tconst patternContributions = ifThenContributions(state, context);\n \treturn {\n@@ -5367,10 +5564,8 @@ function planExplanation(\n \t\t\t\t(candidate) => candidate.id === placement.balanceId,\n \t\t\t);\n \t\t\tif (released) released.remaining++;\n-\t\t\tconst withoutPreferences = preferenceResultsForState(withoutPlacement, context);\n-\t\t\tconst withoutMetrics = qualityMetrics(withoutPlacement, context, withoutPreferences);\n \t\t\tconst comparison = objectiveComparison(\n-\t\t\t\tobjectiveVector(withoutMetrics, withoutPreferences, withoutPlacement, context),\n+\t\t\t\tobjectiveVector(withoutPlacement, context),\n \t\t\t\tvector,\n \t\t\t);\n \t\t\tconst contributions: PlacementContribution[] = [\n@@ -5527,19 +5722,17 @@ function markProgress(context: SearchContext, stage: string): void {\n \t\t);\n }\n \n+function ruleStage(rule: NormalizedRule): string {\n+\treturn `${rule.type === 'optimization' ? 'optimization' : 'preference'}:${rule.id}`;\n+}\n+\n function planningStages(context: SearchContext): string[] {\n \treturn [\n \t\t'validation',\n \t\t'obligations',\n-\t\t'at-risk',\n \t\t...context.rules\n \t\t\t.filter((rule) => rule.enabled && rule.force === 'preference')\n-\t\t\t.map((rule) => `preference:${rule.id}`),\n-\t\t'holiday-week-value',\n-\t\t'non-working-day-gain',\n-\t\t'longest-work-sequence',\n-\t\t'short-sequence-deficit',\n-\t\t'supporting-placements',\n+\t\t\t.map(ruleStage),\n \t\t'expiry',\n \t\t'dates',\n \t];\n@@ -5570,7 +5763,13 @@ function obligationConflict(\n \tconst ruleIds = [...new Set(requirements.map((requirement) => requirement.rule.id))];\n \tconst generatedTypes = new Set(\n \t\tcontext.rules\n-\t\t\t.filter((rule) => rule.enabled && (rule.rewardDays ?? 0) > 0 && rule.rewardType)\n+\t\t\t.filter(\n+\t\t\t\t(rule): rule is NormalizedCalendarRule =>\n+\t\t\t\t\trule.enabled &&\n+\t\t\t\t\trule.type === 'if_then' &&\n+\t\t\t\t\t(rule.rewardDays ?? 0) > 0 &&\n+\t\t\t\t\t!!rule.rewardType,\n+\t\t\t)\n \t\t\t.map((rule) => rule.rewardType!),\n \t);\n \tlet generatedCapacityBottleneck = false;\n@@ -5641,380 +5840,6 @@ function obligationConflict(\n \t};\n }\n \n-function supportingProtectionTraceDetails(\n-\tbaseline: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tpreferences: readonly PreferenceResult[],\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst reject = (name: string, message: string): QualityTraceDetails => ({\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: name,\n-\t\treason: reason('quality-protected-objective', message),\n-\t});\n-\tconst same = (\n-\t\tname: string,\n-\t\tdirection: QualityTraceComparator['direction'],\n-\t\ta: number,\n-\t\tb: number,\n-\t) => addQualityComparator(values, name, direction, a, b);\n-\tif (\n-\t\t!same(\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'minimize',\n-\t\t\tbaseline.unplacedAtRisk,\n-\t\t\tcandidate.unplacedAtRisk,\n-\t\t)\n-\t)\n-\t\treturn reject(\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'This supporting placement changes the amount of unplaced at-risk leave.',\n-\t\t);\n-\tif (baseline.preferenceSatisfaction.length !== candidate.preferenceSatisfaction.length) {\n-\t\tconst name = 'protected:preference-count';\n-\t\tsame(\n-\t\t\tname,\n-\t\t\t'maximize',\n-\t\t\tbaseline.preferenceSatisfaction.length,\n-\t\t\tcandidate.preferenceSatisfaction.length,\n-\t\t);\n-\t\treturn reject(name, 'This supporting placement changes a preference result.');\n-\t}\n-\tfor (let index = 0; index < baseline.preferenceSatisfaction.length; index++) {\n-\t\tconst name = `protected:preference:${preferences[index]?.ruleId ?? index}`;\n-\t\tif (\n-\t\t\t!same(\n-\t\t\t\tname,\n-\t\t\t\t'maximize',\n-\t\t\t\tbaseline.preferenceSatisfaction[index],\n-\t\t\t\tcandidate.preferenceSatisfaction[index],\n-\t\t\t)\n-\t\t)\n-\t\t\treturn reject(name, 'This supporting placement changes a preference result.');\n-\t}\n-\tfor (const [name, direction, before, after, isAllowed] of [\n-\t\t[\n-\t\t\t'protected:holiday-week-value',\n-\t\t\t'maximize',\n-\t\t\tbaseline.holidayWeekValue,\n-\t\t\tcandidate.holidayWeekValue,\n-\t\t\tcandidate.holidayWeekValue >= baseline.holidayWeekValue,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:non-working-day-gain',\n-\t\t\t'maximize',\n-\t\t\tbaseline.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain >= baseline.nonWorkingDayGain,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:longest-work-sequence',\n-\t\t\t'minimize',\n-\t\t\tbaseline.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence <= baseline.longestWorkSequence,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:short-sequence-deficit',\n-\t\t\t'minimize',\n-\t\t\tbaseline.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit <= baseline.shortSequenceDeficit,\n-\t\t],\n-\t] as const) {\n-\t\tsame(name, direction, before, after);\n-\t\tif (!isAllowed)\n-\t\t\treturn reject(\n-\t\t\t\tname,\n-\t\t\t\t`This supporting placement worsens ${name.slice('protected:'.length).replaceAll('-', ' ')}.`,\n-\t\t\t);\n-\t}\n-\treturn { technicalComparison: values };\n-}\n-\n-function supportingRemovalTraceDetails(\n-\tbaseline: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst reject = (name: string, message: string): QualityTraceDetails => ({\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: name,\n-\t\treason: reason('quality-protected-objective', message),\n-\t});\n-\tif (\n-\t\t!addQualityComparator(\n-\t\t\tvalues,\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'minimize',\n-\t\t\tbaseline.unplacedAtRisk,\n-\t\t\tcandidate.unplacedAtRisk,\n-\t\t)\n-\t)\n-\t\treturn reject(\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'Removing this supporting placement changes unplaced at-risk leave.',\n-\t\t);\n-\tfor (const [name, direction, before, after, isAllowed] of [\n-\t\t[\n-\t\t\t'protected:holiday-week-value',\n-\t\t\t'maximize',\n-\t\t\tbaseline.holidayWeekValue,\n-\t\t\tcandidate.holidayWeekValue,\n-\t\t\tcandidate.holidayWeekValue >= baseline.holidayWeekValue,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:non-working-day-gain',\n-\t\t\t'maximize',\n-\t\t\tbaseline.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain >= baseline.nonWorkingDayGain,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:longest-work-sequence',\n-\t\t\t'minimize',\n-\t\t\tbaseline.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence <= baseline.longestWorkSequence,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:short-sequence-deficit',\n-\t\t\t'minimize',\n-\t\t\tbaseline.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit <= baseline.shortSequenceDeficit,\n-\t\t],\n-\t] as const) {\n-\t\taddQualityComparator(values, name, direction, before, after);\n-\t\tif (!isAllowed)\n-\t\t\treturn reject(\n-\t\t\t\tname,\n-\t\t\t\t`Removing this supporting placement worsens ${name.slice('protected:'.length).replaceAll('-', ' ')}.`,\n-\t\t\t);\n-\t}\n-\treturn { technicalComparison: values };\n-}\n-\n-function* supportingPlacements(\n-\tstate: State,\n-\tcontext: SearchContext,\n-\tpreferences: PreferenceResult[],\n-): PlanningSteps {\n-\tlet result = state;\n-\twhile (true) {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tconst before = qualityMetrics(result, context, preferences);\n-\t\tlet best: State | null = null;\n-\t\tlet bestMetrics: PlanningMetrics | null = null;\n-\t\tlet bestEvaluation: MutableTraceCandidate | undefined;\n-\t\tfor (const balance of result.balances\n-\t\t\t.filter(\n-\t\t\t\t(item) =>\n-\t\t\t\t\tcompareDate(item.expiryDate, context.horizon.end) > 0 && item.remaining > 0,\n-\t\t\t)\n-\t\t\t.sort((a, b) => compareDate(a.expiryDate, b.expiryDate) || compareText(a.id, b.id))) {\n-\t\t\tyield;\n-\t\t\tfor (const date of context.workingDays) {\n-\t\t\t\tyield;\n-\t\t\t\tcontext.check();\n-\t\t\t\tif (\n-\t\t\t\t\tresult.placements.has(date) ||\n-\t\t\t\t\tcompareDate(balance.availableFrom, date) > 0 ||\n-\t\t\t\t\tcompareDate(date, balance.expiryDate) > 0\n-\t\t\t\t)\n-\t\t\t\t\tcontinue;\n-\t\t\t\tconst candidate = assignDateToBalance(result, date, balance.id, context);\n-\t\t\t\tif (!candidate) continue;\n-\t\t\t\tcandidate.placements.get(date)!.supporting = true;\n-\t\t\t\tconst feasibleCandidate = finalizeEarnedState(candidate, context);\n-\t\t\t\tif (!feasibleCandidate) continue;\n-\t\t\t\tconst metrics = qualityMetrics(feasibleCandidate, context, preferences);\n-\t\t\t\tconst preservesHigherMetrics =\n-\t\t\t\t\tmetrics.unplacedAtRisk === before.unplacedAtRisk &&\n-\t\t\t\t\tmetrics.preferenceSatisfaction.length ===\n-\t\t\t\t\t\tbefore.preferenceSatisfaction.length &&\n-\t\t\t\t\tmetrics.preferenceSatisfaction.every(\n-\t\t\t\t\t\t(value, index) => value === before.preferenceSatisfaction[index],\n-\t\t\t\t\t) &&\n-\t\t\t\t\tmetrics.holidayWeekValue >= before.holidayWeekValue &&\n-\t\t\t\t\tmetrics.nonWorkingDayGain >= before.nonWorkingDayGain &&\n-\t\t\t\t\tmetrics.longestWorkSequence <= before.longestWorkSequence &&\n-\t\t\t\t\tmetrics.shortSequenceDeficit <= before.shortSequenceDeficit;\n-\t\t\t\tif (!preservesHigherMetrics) {\n-\t\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tresult,\n-\t\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\tbefore,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t[date],\n-\t\t\t\t\t\tundefined,\n-\t\t\t\t\t\t() => supportingProtectionTraceDetails(before, metrics, preferences),\n-\t\t\t\t\t);\n-\t\t\t\t\tcontinue;\n-\t\t\t\t}\n-\t\t\t\tconst useful =\n-\t\t\t\t\tmetrics.holidayWeekValue > before.holidayWeekValue ||\n-\t\t\t\t\tmetrics.nonWorkingDayGain > before.nonWorkingDayGain ||\n-\t\t\t\t\tmetrics.longestWorkSequence < before.longestWorkSequence ||\n-\t\t\t\t\tmetrics.shortSequenceDeficit < before.shortSequenceDeficit;\n-\t\t\t\tif (!useful) {\n-\t\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tresult,\n-\t\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\tbefore,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t[date],\n-\t\t\t\t\t\tundefined,\n-\t\t\t\t\t\t() => ({\n-\t\t\t\t\t\t\t...supportingProtectionTraceDetails(before, metrics, preferences),\n-\t\t\t\t\t\t\treason: reason(\n-\t\t\t\t\t\t\t\t'quality-no-improvement',\n-\t\t\t\t\t\t\t\t'This supporting placement does not improve a protected quality objective.',\n-\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t}),\n-\t\t\t\t\t);\n-\t\t\t\t\tcontinue;\n-\t\t\t\t}\n-\t\t\t\tconst better = !bestMetrics || compareMetrics(metrics, bestMetrics) < 0;\n-\t\t\t\tconst evaluation = retainAndRecordEvaluation(\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tresult,\n-\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\tpreferences,\n-\t\t\t\t\tbefore,\n-\t\t\t\t\tmetrics,\n-\t\t\t\t\t[date],\n-\t\t\t\t\tundefined,\n-\t\t\t\t\t() => {\n-\t\t\t\t\t\tconst protectedDetails = supportingProtectionTraceDetails(\n-\t\t\t\t\t\t\tbefore,\n-\t\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\t);\n-\t\t\t\t\t\tconst incumbentDetails = bestMetrics\n-\t\t\t\t\t\t\t? qualityMetricTraceDetails(bestMetrics, metrics)\n-\t\t\t\t\t\t\t: undefined;\n-\t\t\t\t\t\treturn {\n-\t\t\t\t\t\t\ttechnicalComparison: [\n-\t\t\t\t\t\t\t\t...(protectedDetails.technicalComparison ?? []),\n-\t\t\t\t\t\t\t\t...(incumbentDetails?.technicalComparison ?? []),\n-\t\t\t\t\t\t\t],\n-\t\t\t\t\t\t\tfirstDecisiveComparator: incumbentDetails?.firstDecisiveComparator,\n-\t\t\t\t\t\t\treason: better\n-\t\t\t\t\t\t\t\t? undefined\n-\t\t\t\t\t\t\t\t: reason(\n-\t\t\t\t\t\t\t\t\t\t'quality-no-improvement',\n-\t\t\t\t\t\t\t\t\t\t'This candidate did not outrank the current best supporting placement.',\n-\t\t\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t};\n-\t\t\t\t\t},\n-\t\t\t\t);\n-\t\t\t\tif (better) {\n-\t\t\t\t\tif (bestEvaluation)\n-\t\t\t\t\t\tupdateTraceEvaluationReason(\n-\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\tbestEvaluation,\n-\t\t\t\t\t\t\treason(\n-\t\t\t\t\t\t\t\t'quality-outperformed',\n-\t\t\t\t\t\t\t\t'A later candidate became the best supporting placement.',\n-\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t);\n-\t\t\t\t\tbest = feasibleCandidate;\n-\t\t\t\t\tbestMetrics = metrics;\n-\t\t\t\t\tbestEvaluation = evaluation;\n-\t\t\t\t}\n-\t\t\t}\n-\t\t}\n-\t\tif (!best) return result;\n-\t\tretainAndRecordState(context, best, bestEvaluation);\n-\t\tresult = best;\n-\t}\n-}\n-\n-function* pruneRedundantSupportingPlacements(\n-\tstate: State,\n-\tcontext: SearchContext,\n-\tpreferences: PreferenceResult[],\n-): PlanningSteps {\n-\tlet result = state;\n-\tlet removed = true;\n-\twhile (removed) {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tremoved = false;\n-\t\tconst baseline = qualityMetrics(result, context, preferences);\n-\t\tfor (const placement of [...result.placements.values()].filter((item) => item.supporting)) {\n-\t\t\tyield;\n-\t\t\tcontext.check();\n-\t\t\trecordTraceDecision(context, [placement.date]);\n-\t\t\tconst candidate = cloneState(result);\n-\t\t\tcandidate.placements.delete(placement.date);\n-\t\t\tconst balance = candidate.balances.find((item) => item.id === placement.balanceId);\n-\t\t\tif (balance) balance.remaining++;\n-\t\t\tconst feasibleCandidate = finalizeEarnedState(candidate, context);\n-\t\t\tif (!feasibleCandidate) {\n-\t\t\t\trecordTraceCandidate(context, {\n-\t\t\t\t\tstatus: 'pruned',\n-\t\t\t\t\tdate: placement.date,\n-\t\t\t\t\treason: reason(\n-\t\t\t\t\t\t'earned-entitlement-order',\n-\t\t\t\t\t\t'Removing this supporting placement would invalidate earned entitlement dates.',\n-\t\t\t\t\t),\n-\t\t\t\t});\n-\t\t\t\tcontinue;\n-\t\t\t}\n-\t\t\tconst metrics = qualityMetrics(feasibleCandidate, context, preferences);\n-\t\t\tconst removesWithoutQualityLoss =\n-\t\t\t\tmetrics.unplacedAtRisk === baseline.unplacedAtRisk &&\n-\t\t\t\tmetrics.holidayWeekValue >= baseline.holidayWeekValue &&\n-\t\t\t\tmetrics.nonWorkingDayGain >= baseline.nonWorkingDayGain &&\n-\t\t\t\tmetrics.longestWorkSequence <= baseline.longestWorkSequence &&\n-\t\t\t\tmetrics.shortSequenceDeficit <= baseline.shortSequenceDeficit;\n-\t\t\tconst evaluation = retainAndRecordEvaluation(\n-\t\t\t\tcontext,\n-\t\t\t\tresult,\n-\t\t\t\tfeasibleCandidate,\n-\t\t\t\tpreferences,\n-\t\t\t\tbaseline,\n-\t\t\t\tmetrics,\n-\t\t\t\t[placement.date],\n-\t\t\t\tplacement.date,\n-\t\t\t\t() => {\n-\t\t\t\t\tconst details = supportingRemovalTraceDetails(baseline, metrics);\n-\t\t\t\t\treturn {\n-\t\t\t\t\t\t...details,\n-\t\t\t\t\t\treason: removesWithoutQualityLoss ? undefined : details.reason,\n-\t\t\t\t\t};\n-\t\t\t\t},\n-\t\t\t);\n-\t\t\tif (removesWithoutQualityLoss) {\n-\t\t\t\tretainAndRecordState(context, feasibleCandidate, evaluation);\n-\t\t\t\tresult = feasibleCandidate;\n-\t\t\t\tremoved = true;\n-\t\t\t\tbreak;\n-\t\t\t}\n-\t\t}\n-\t}\n-\treturn result;\n-}\n-\n-function compareMetrics(a: PlanningMetrics, b: PlanningMetrics): number {\n-\tif (a.unplacedAtRisk !== b.unplacedAtRisk) return a.unplacedAtRisk - b.unplacedAtRisk;\n-\tif (a.holidayWeekValue !== b.holidayWeekValue) return b.holidayWeekValue - a.holidayWeekValue;\n-\tif (a.nonWorkingDayGain !== b.nonWorkingDayGain)\n-\t\treturn b.nonWorkingDayGain - a.nonWorkingDayGain;\n-\tif (a.longestWorkSequence !== b.longestWorkSequence)\n-\t\treturn a.longestWorkSequence - b.longestWorkSequence;\n-\tif (a.shortSequenceDeficit !== b.shortSequenceDeficit)\n-\t\treturn a.shortSequenceDeficit - b.shortSequenceDeficit;\n-\treturn a.supportingPlacements - b.supportingPlacements;\n-}\n-\n export type PlanningCheckpoint = (plan: PlanOutcome, state?: PlanningTraceState) => void;\n export interface PlanningArtifacts {\n \texplanation?: PlanningExplanation;\n@@ -6215,6 +6040,7 @@ function* calculatePlanningSteps(\n \t\ttraceReportedTime: 0,\n \t\tobserverTime: 0,\n \t\tobligationSolutionBranches: new WeakMap(),\n+\t\tcompletedPreferenceStates: new Map(),\n \t} as SearchContext;\n \tconst traceStarted = now();\n \tconst traceRecorder = artifactsCallback\n@@ -6267,68 +6093,57 @@ function* calculatePlanningSteps(\n \tconst preferences: PreferenceResult[] = [];\n \tlet checkpoint: PlanOutcome | undefined;\n \tlet checkpointState: State | undefined;\n-\tlet retained: Pick | undefined;\n+\tlet retained:\n+\t\t| (Pick & {\n+\t\t\t\tvector: PlanningObjectiveVector;\n+\t\t })\n+\t\t| undefined;\n \tif (retainIncumbents)\n-\t\tcontext.retain = (candidate, finalizedMetrics) => {\n+\t\tcontext.retain = (candidate, finalizedMetrics, candidateVector) => {\n \t\t\tconst check = context.check;\n \t\t\tcontext.check = () => undefined;\n \t\t\ttry {\n-\t\t\t\tconst finalized = finalizedMetrics\n-\t\t\t\t\t? candidate\n-\t\t\t\t\t: finalizeEarnedState(candidate, context);\n+\t\t\t\tconst finalized =\n+\t\t\t\t\tfinalizedMetrics || candidateVector\n+\t\t\t\t\t\t? candidate\n+\t\t\t\t\t\t: finalizeEarnedState(candidate, context);\n \t\t\t\tif (!finalized) return;\n-\t\t\t\tconst unplacedAtRisk =\n-\t\t\t\t\tfinalizedMetrics?.unplacedAtRisk ?? unplacedAtRiskQuantity(finalized, context);\n-\t\t\t\tif (retained && unplacedAtRisk > retained.metrics.unplacedAtRisk) {\n-\t\t\t\t\trecordTraceIncumbentBound(context, retained.metrics, unplacedAtRisk);\n-\t\t\t\t\treturn;\n-\t\t\t\t}\n-\t\t\t\tconst candidatePreferences = preferenceResultsForState(finalized, context);\n-\t\t\t\tconst preferenceSatisfaction = candidatePreferences.map(\n-\t\t\t\t\t({ satisfied }) => satisfied,\n-\t\t\t\t);\n-\t\t\t\tif (\n-\t\t\t\t\tretained &&\n-\t\t\t\t\tunplacedAtRisk === retained.metrics.unplacedAtRisk &&\n-\t\t\t\t\tcomparePreferenceVectors(\n-\t\t\t\t\t\tpreferenceSatisfaction,\n-\t\t\t\t\t\tretained.metrics.preferenceSatisfaction,\n-\t\t\t\t\t) > 0\n-\t\t\t\t) {\n-\t\t\t\t\trecordTraceIncumbentBound(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tretained.metrics,\n-\t\t\t\t\t\tunplacedAtRisk,\n-\t\t\t\t\t\tcandidatePreferences,\n-\t\t\t\t\t);\n-\t\t\t\t\treturn;\n-\t\t\t\t}\n \t\t\t\tif (unsatisfiedObligationCount(finalized, context)) return;\n-\t\t\t\tif (\n-\t\t\t\t\tretained &&\n-\t\t\t\t\t!planningTraceDeltas(retained.state, finalized, [\n-\t\t\t\t\t\t...retained.state.placements.keys(),\n-\t\t\t\t\t\t...finalized.placements.keys(),\n-\t\t\t\t\t]).length\n-\t\t\t\t)\n-\t\t\t\t\treturn;\n-\t\t\t\tconst scored = {\n-\t\t\t\t\tstate: finalized,\n-\t\t\t\t\tpreferences: candidatePreferences,\n-\t\t\t\t\tmetrics: finalizedMetrics\n-\t\t\t\t\t\t? {\n-\t\t\t\t\t\t\t\t...finalizedMetrics,\n-\t\t\t\t\t\t\t\tpreferenceSatisfaction,\n-\t\t\t\t\t\t\t}\n-\t\t\t\t\t\t: qualityMetrics(finalized, context, candidatePreferences),\n-\t\t\t\t};\n-\t\t\t\tconst compared = retained ? compareObligationPreviews(scored, retained) : -1;\n+\t\t\t\tconst deltas = retained\n+\t\t\t\t\t? planningTraceDeltas(retained.state, finalized, [\n+\t\t\t\t\t\t\t...retained.state.placements.keys(),\n+\t\t\t\t\t\t\t...finalized.placements.keys(),\n+\t\t\t\t\t\t])\n+\t\t\t\t\t: [];\n+\t\t\t\tif (retained && !deltas.length) return;\n+\t\t\t\tconst vector = candidateVector ?? objectiveVector(finalized, context);\n+\t\t\t\tconst compared = retained\n+\t\t\t\t\t? compareObjectiveLists(vector.objectives, retained.vector.objectives)\n+\t\t\t\t\t: -1;\n+\t\t\t\t// Calendar association can complete provenance after the scoring candidate is retained.\n+\t\t\t\tconst provenanceRefresh =\n+\t\t\t\t\tcompared === 0 &&\n+\t\t\t\t\t!!retained &&\n+\t\t\t\t\tdeltas.every(\n+\t\t\t\t\t\t({ kind, placement, previousPlacement }) =>\n+\t\t\t\t\t\t\tkind === 'placement-updated' &&\n+\t\t\t\t\t\t\tplacement?.date === previousPlacement?.date &&\n+\t\t\t\t\t\t\tplacement?.balanceId === previousPlacement?.balanceId &&\n+\t\t\t\t\t\t\tplacement?.type === previousPlacement?.type &&\n+\t\t\t\t\t\t\tplacement?.supporting === previousPlacement?.supporting,\n+\t\t\t\t\t) &&\n+\t\t\t\t\tJSON.stringify(retained.state.earnedActivations) ===\n+\t\t\t\t\t\tJSON.stringify(finalized.earnedActivations);\n+\t\t\t\tconst chosen = compared < 0 || provenanceRefresh;\n \t\t\t\tif (retained) {\n \t\t\t\t\tobserveTrace(context, (trace) => {\n-\t\t\t\t\t\tconst facts = obligationPreviewComparisonFacts(scored, retained!);\n+\t\t\t\t\t\tconst facts = objectiveComparisonFacts(\n+\t\t\t\t\t\t\tretained!.vector.objectives,\n+\t\t\t\t\t\t\tvector.objectives,\n+\t\t\t\t\t\t);\n \t\t\t\t\t\ttrace.recordCandidate(\n \t\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t\tstatus: compared < 0 ? 'chosen' : 'evaluated-rejected',\n+\t\t\t\t\t\t\t\tstatus: chosen ? 'chosen' : 'evaluated-rejected',\n \t\t\t\t\t\t\t\tdates: [...finalized.placements.keys()],\n \t\t\t\t\t\t\t\ttechnicalComparison: facts.values,\n \t\t\t\t\t\t\t\tfirstDecisiveComparator: facts.firstDecisiveComparator,\n@@ -6336,16 +6151,38 @@ function* calculatePlanningSteps(\n \t\t\t\t\t\t\t\t\t'incumbent-comparison',\n \t\t\t\t\t\t\t\t\tcompared < 0\n \t\t\t\t\t\t\t\t\t\t? 'This valid candidate became the best available partial plan.'\n-\t\t\t\t\t\t\t\t\t\t: 'This valid candidate did not improve the best available partial plan.',\n+\t\t\t\t\t\t\t\t\t\t: provenanceRefresh\n+\t\t\t\t\t\t\t\t\t\t\t? 'This identical plan refreshed only the retained rule provenance.'\n+\t\t\t\t\t\t\t\t\t\t\t: 'This valid candidate did not improve the best available partial plan.',\n \t\t\t\t\t\t\t\t),\n \t\t\t\t\t\t\t},\n \t\t\t\t\t\t\tfalse,\n \t\t\t\t\t\t);\n \t\t\t\t\t});\n \t\t\t\t}\n-\t\t\t\tif (compared < 0) {\n+\t\t\t\tif (chosen) {\n \t\t\t\t\tconst firstValidCandidate = !retained;\n-\t\t\t\t\tretained = { ...scored, state: cloneState(finalized) };\n+\t\t\t\t\tconst candidatePreferences = preferenceResultsForState(finalized, context);\n+\t\t\t\t\tretained = {\n+\t\t\t\t\t\tstate: cloneState(\n+\t\t\t\t\t\t\treconcileOptimizationProvenance(\n+\t\t\t\t\t\t\t\tfinalized,\n+\t\t\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\t\t\tretained?.state ?? initialState,\n+\t\t\t\t\t\t\t\tvector.objectives,\n+\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t),\n+\t\t\t\t\t\tvector,\n+\t\t\t\t\t\tpreferences: candidatePreferences,\n+\t\t\t\t\t\tmetrics: finalizedMetrics\n+\t\t\t\t\t\t\t? {\n+\t\t\t\t\t\t\t\t\t...finalizedMetrics,\n+\t\t\t\t\t\t\t\t\tpreferenceSatisfaction: candidatePreferences.map(\n+\t\t\t\t\t\t\t\t\t\t({ satisfied }) => satisfied,\n+\t\t\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\t: qualityMetrics(finalized, context, candidatePreferences),\n+\t\t\t\t\t};\n \t\t\t\t\tif (firstValidCandidate && checkpointCallback)\n \t\t\t\t\t\tobserveCallback(context, () =>\n \t\t\t\t\t\t\tcheckpointCallback(\n@@ -6534,6 +6371,7 @@ function* calculatePlanningSteps(\n \t\treturn outcome;\n \t};\n \tconst publishCheckpoint = (): void => {\n+\t\tstate = reconcileOptimizationProvenance(state, context, checkpointState ?? initialState);\n \t\tcontext.retain?.(state);\n \t\tcheckpoint = makePlan(state, context, preferences, stages);\n \t\tcheckpointState = cloneState(state);\n@@ -6569,8 +6407,7 @@ function* calculatePlanningSteps(\n \t\t\t}\n \t\t\tif (state !== initialState) retainAndRecordState(context, state);\n \t\t}\n-\t\t// At-risk quantity is the first objective, but equivalent placements can\n-\t\t// still preserve later preferences by sharing their compatible dates.\n+\t\t// Equivalent obligation placements can share compatible dates with active preferences.\n \t\tcontext.protectedTypesByDate = futurePreferenceProtection(normalized.rules, 0, context);\n \t\tmarkProgress(context, 'obligations');\n \t\tyield true;\n@@ -6634,8 +6471,58 @@ function* calculatePlanningSteps(\n \t\tconst preferenceRules = normalized.rules.filter(\n \t\t\t(item) => item.enabled && item.force === 'preference',\n \t\t);\n-\t\tlet bestPreview: ObligationPreview | null = null;\n-\t\tfor (const obligationSolution of obligationSolutions) {\n+\t\tlet previewSolutions = obligationSolutions;\n+\t\tif (\n+\t\t\tobligationSolutionLimit > 0 &&\n+\t\t\tobligationRequirements.every(\n+\t\t\t\t(requirement) => requirement.rule.type === 'time_window',\n+\t\t\t) &&\n+\t\t\tobligationSolutions.length > WINDOW_OBLIGATION_PREVIEW_LIMIT\n+\t\t) {\n+\t\t\t// shortcut: large window searches preview the eight best active vectors; upgrade to shared bounded previews when a measured case misses a better plan.\n+\t\t\tconst ranked: { state: State; objectives: PlanningObjective[] }[] = [];\n+\t\t\tfor (const candidate of obligationSolutions) {\n+\t\t\t\tyield;\n+\t\t\t\tcontext.check();\n+\t\t\t\tranked.push({\n+\t\t\t\t\tstate: candidate,\n+\t\t\t\t\tobjectives: obligationPreviewObjectives({ state: candidate }, context),\n+\t\t\t\t});\n+\t\t\t}\n+\t\t\tranked.sort((a, b) => compareObjectiveLists(a.objectives, b.objectives));\n+\t\t\tpreviewSolutions = ranked\n+\t\t\t\t.slice(0, WINDOW_OBLIGATION_PREVIEW_LIMIT)\n+\t\t\t\t.map(({ state }) => state);\n+\t\t\tfor (const candidate of ranked.slice(WINDOW_OBLIGATION_PREVIEW_LIMIT)) {\n+\t\t\t\tyield;\n+\t\t\t\trecordTraceCandidate(context, {\n+\t\t\t\t\tstatus: 'not-examined',\n+\t\t\t\t\tdates: [...candidate.state.placements.keys()],\n+\t\t\t\t\treason: reason(\n+\t\t\t\t\t\t'window-obligation-preview-sampling',\n+\t\t\t\t\t\t'This feasible large-window solution did not receive an optimization preview.',\n+\t\t\t\t\t),\n+\t\t\t\t});\n+\t\t\t}\n+\t\t}\n+\t\t// A completed enumeration with one finalized solution has no alternative to rank.\n+\t\tconst soleSolution =\n+\t\t\tobligationSolutions.length === 1 &&\n+\t\t\t(obligationSolutionLimit === 0 || obligationSolutions.length < obligationSolutionLimit)\n+\t\t\t\t? obligationSolutions[0]\n+\t\t\t\t: undefined;\n+\t\tconst solePreferences = soleSolution\n+\t\t\t? preferenceResultsForState(soleSolution, context)\n+\t\t\t: [];\n+\t\tlet bestPreview: ObligationPreview | null = soleSolution\n+\t\t\t? {\n+\t\t\t\t\tobligationState: soleSolution,\n+\t\t\t\t\tstate: soleSolution,\n+\t\t\t\t\tpreferences: solePreferences,\n+\t\t\t\t\tmetrics: qualityMetrics(soleSolution, context, solePreferences),\n+\t\t\t\t}\n+\t\t\t: null;\n+\t\tfor (const obligationSolution of soleSolution ? [] : previewSolutions) {\n \t\t\tyield;\n \t\t\tcontext.check();\n \t\t\tconst obligationPath = context.obligationSolutionBranches.get(obligationSolution) ?? [];\n@@ -6644,8 +6531,11 @@ function* calculatePlanningSteps(\n \t\t\tcontext.traceBranchActive = true;\n \t\t\tcontext.traceBranchParentId = obligationPath.at(-1)?.decisionId;\n \t\t\ttry {\n-\t\t\t\tconst atRiskState = yield* placeAtRisk(cloneState(obligationSolution), context);\n-\t\t\t\tconst preview = yield* applyPreferenceRules(atRiskState, preferenceRules, context);\n+\t\t\t\tconst preview = yield* applyPreferenceRules(\n+\t\t\t\t\tcloneState(obligationSolution),\n+\t\t\t\t\tpreferenceRules,\n+\t\t\t\t\tcontext,\n+\t\t\t\t);\n \t\t\t\tconst previewState = finalizeEarnedState(preview.state, context);\n \t\t\t\tif (!previewState) continue;\n \t\t\t\tconst candidate = {\n@@ -6655,7 +6545,7 @@ function* calculatePlanningSteps(\n \t\t\t\t\tmetrics: qualityMetrics(previewState, context, preview.preferences),\n \t\t\t\t};\n \t\t\t\tconst compared: number | undefined = bestPreview\n-\t\t\t\t\t? compareObligationPreviews(candidate, bestPreview)\n+\t\t\t\t\t? compareObligationPreviews(candidate, bestPreview, context)\n \t\t\t\t\t: undefined;\n \t\t\t\tconst branch: ObligationBranchReference | undefined =\n \t\t\t\t\tcompared !== undefined\n@@ -6665,7 +6555,12 @@ function* calculatePlanningSteps(\n \t\t\t\t\t\t\t\tpreviewState,\n \t\t\t\t\t\t\t\tcontext.traceBranchParentId,\n \t\t\t\t\t\t\t\t[],\n-\t\t\t\t\t\t\t\t() => obligationPreviewComparisonFacts(candidate, bestPreview!),\n+\t\t\t\t\t\t\t\t() =>\n+\t\t\t\t\t\t\t\t\tobligationPreviewComparisonFacts(\n+\t\t\t\t\t\t\t\t\t\tcandidate,\n+\t\t\t\t\t\t\t\t\t\tbestPreview!,\n+\t\t\t\t\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\t\t\t\t),\n \t\t\t\t\t\t\t)\n \t\t\t\t\t\t: undefined;\n \t\t\t\tconst previewCandidate: ObligationPreview = {\n@@ -6690,22 +6585,10 @@ function* calculatePlanningSteps(\n \t\t\t);\n \t\tstages.push('obligations');\n \t\tpublishCheckpoint();\n-\t\tmarkProgress(context, 'at-risk');\n-\t\tyield true;\n-\t\tcontext.protectedTypesByDate = futurePreferenceProtection(normalized.rules, 0, context);\n-\t\tcontext.reservedTypes = new Set(\n-\t\t\tobligationRequirements\n-\t\t\t\t.filter((requirement) => requirement.requiredPlacements > 0)\n-\t\t\t\t.map((requirement) => requirement.rule.placeType)\n-\t\t\t\t.filter((selector): selector is LeaveType => selector !== 'any'),\n-\t\t);\n-\t\tstate = yield* placeAtRisk(state, context);\n-\t\tstages.push('at-risk');\n-\t\tpublishCheckpoint();\n \t\tfor (let preferenceIndex = 0; preferenceIndex < preferenceRules.length; preferenceIndex++) {\n \t\t\tyield;\n \t\t\tconst rule = preferenceRules[preferenceIndex];\n-\t\t\tmarkProgress(context, `preference:${rule.id}`);\n+\t\t\tmarkProgress(context, ruleStage(rule));\n \t\t\tyield true;\n \t\t\tstate = yield* applyPreferenceStep(\n \t\t\t\tstate,\n@@ -6714,64 +6597,16 @@ function* calculatePlanningSteps(\n \t\t\t\tpreferences,\n \t\t\t\tcontext,\n \t\t\t);\n-\t\t\tstages.push(`preference:${rule.id}`);\n+\t\t\tstages.push(ruleStage(rule));\n \t\t\tpublishCheckpoint();\n \t\t}\n-\t\tmarkProgress(context, 'holiday-week-value');\n-\t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeHolidayWeeks(state, context, preferences);\n-\t\tstages.push('holiday-week-value');\n-\t\tpublishCheckpoint();\n-\t\tmarkProgress(context, 'non-working-day-gain');\n-\t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeMovablePlacements(\n-\t\t\tstate,\n-\t\t\tcontext,\n-\t\t\tpreferences,\n-\t\t\t'non-working-day-gain',\n-\t\t);\n-\t\tstages.push('non-working-day-gain');\n-\t\tpublishCheckpoint();\n-\t\tmarkProgress(context, 'longest-work-sequence');\n-\t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeMovablePlacements(\n-\t\t\tstate,\n-\t\t\tcontext,\n-\t\t\tpreferences,\n-\t\t\t'longest-work-sequence',\n-\t\t);\n-\t\tstages.push('longest-work-sequence');\n-\t\tpublishCheckpoint();\n-\t\tmarkProgress(context, 'short-sequence-deficit');\n-\t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeMovablePlacements(\n-\t\t\tstate,\n-\t\t\tcontext,\n-\t\t\tpreferences,\n-\t\t\t'short-sequence-deficit',\n-\t\t);\n-\t\tstages.push('short-sequence-deficit');\n-\t\tpublishCheckpoint();\n-\t\tmarkProgress(context, 'supporting-placements');\n-\t\tyield true;\n-\t\tstate = yield* supportingPlacements(state, context, preferences);\n-\t\tstate = yield* pruneRedundantSupportingPlacements(state, context, preferences);\n-\t\tstages.push('supporting-placements');\n-\t\tpublishCheckpoint();\n \t\tmarkProgress(context, 'expiry');\n \t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeExpiryPlacements(state, context, preferences);\n+\t\tstate = yield* optimizeRulePlacements(state, context, preferenceRules.length - 1, false);\n \t\tstages.push('expiry');\n \t\tpublishCheckpoint();\n \t\tmarkProgress(context, 'dates');\n \t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeMovablePlacements(state, context, preferences, 'dates');\n \t\tstages.push('dates');\n \t\tconst finalized = finalizeEarnedState(state, context);\n \t\tif (!finalized) {\n@@ -6800,7 +6635,10 @@ function* calculatePlanningSteps(\n \t\t\tconst partialPreferences = retained.preferences.map((preference) => ({\n \t\t\t\t...preference,\n \t\t\t\treason: preferenceReason(\n-\t\t\t\t\tnormalized.rules.find((rule) => rule.id === preference.ruleId)!,\n+\t\t\t\t\tnormalized.rules.find(\n+\t\t\t\t\t\t(rule): rule is NormalizedCalendarRule =>\n+\t\t\t\t\t\t\trule.type !== 'optimization' && rule.id === preference.ruleId,\n+\t\t\t\t\t)!,\n \t\t\t\t\tpreference.satisfied,\n \t\t\t\t\tcontext,\n \t\t\t\t\tretained!.state,\n@@ -6894,6 +6732,7 @@ export function explainIncompleteCheckpoint(\n \t\t\ttraceReportedTime: 0,\n \t\t\tobserverTime: 0,\n \t\t\tobligationSolutionBranches: new WeakMap(),\n+\t\t\tcompletedPreferenceStates: new Map(),\n \t\t} as SearchContext;\n \t\tcontext.holidayWeeks = holidayWeekCandidates(context);\n \t\tconst state: State = {\n@@ -6998,6 +6837,7 @@ function counterfactualContext(\n \t\ttraceReportedTime: 0,\n \t\tobserverTime: 0,\n \t\tobligationSolutionBranches: new WeakMap(),\n+\t\tcompletedPreferenceStates: new Map(),\n \t} as SearchContext;\n \tcontext.holidayWeeks = holidayWeekCandidates(context);\n \treturn context;\n@@ -7107,13 +6947,7 @@ function objectiveComparison(\n \t\t\tlabel: objective.label,\n \t\t};\n \t});\n-\tconst first = after.objectives.findIndex(\n-\t\t(objective, index) =>\n-\t\t\t!sameObjectiveValue(\n-\t\t\t\tobjective.value,\n-\t\t\t\tbefore.objectives[index]?.value ?? objective.value,\n-\t\t\t),\n-\t);\n+\tconst first = firstDifferentObjective(after.objectives, before.objectives);\n \tconst decisive = first >= 0 ? after.objectives[first].id : undefined;\n \treturn {\n \t\tbefore,\n@@ -7139,6 +6973,7 @@ function counterfactualRuleValid(\n \tfor (const ruleId of ruleIds) {\n \t\tconst rule = context.rules.find((candidate) => candidate.id === ruleId);\n \t\tif (!rule) return false;\n+\t\tif (rule.type === 'optimization') continue;\n \t\tif (rule.type === 'time_window') {\n \t\t\tif (\n \t\t\t\t!selectorMatches(rule.placeType, type) ||\n@@ -7170,7 +7005,9 @@ function counterfactualObligationsValid(\n \tprevious: State,\n ): boolean {\n \treturn context.rules\n-\t\t.filter((rule) => rule.enabled && rule.force === 'obligation')\n+\t\t.filter(\n+\t\t\t(rule): rule is NormalizedCalendarRule => rule.enabled && rule.force === 'obligation',\n+\t\t)\n \t\t.every((rule) => {\n \t\t\tif (rule.type === 'time_window') {\n \t\t\t\tconst count = (candidate: State) =>\n@@ -7202,7 +7039,7 @@ function preferenceResultsForState(state: State, context: SearchContext): Prefer\n \t\tpatternsByRule = new Map(\n \t\t\tcontext.rules\n \t\t\t\t.filter(\n-\t\t\t\t\t(rule) =>\n+\t\t\t\t\t(rule): rule is NormalizedCalendarRule =>\n \t\t\t\t\t\trule.enabled && rule.force === 'preference' && rule.type === 'if_then',\n \t\t\t\t)\n \t\t\t\t.map((rule) => [\n@@ -7215,17 +7052,26 @@ function preferenceResultsForState(state: State, context: SearchContext): Prefer\n \t\tpreferencePatternCache.set(context, patternsByRule);\n \t}\n \treturn context.rules\n-\t\t.filter((rule) => rule.enabled && rule.force === 'preference')\n+\t\t.filter(\n+\t\t\t(rule): rule is NormalizedCalendarRule =>\n+\t\t\t\trule.enabled && rule.force === 'preference' && rule.type !== 'optimization',\n+\t\t)\n \t\t.map((rule) => {\n \t\t\tconst occurrencePatterns = patternsByRule.get(rule.id) ?? [];\n \t\t\tconst requested =\n \t\t\t\trule.type === 'time_window' ? rule.placeDays : occurrencePatterns.length;\n \t\t\tconst satisfied =\n \t\t\t\trule.type === 'time_window'\n-\t\t\t\t\t? declaredWindowDays(rule, context).length +\n-\t\t\t\t\t\t[...state.placements.values()].filter((placement) =>\n-\t\t\t\t\t\t\tplacement.ruleIds.has(rule.id),\n-\t\t\t\t\t\t).length\n+\t\t\t\t\t? Math.min(\n+\t\t\t\t\t\t\trule.placeDays,\n+\t\t\t\t\t\t\tdeclaredWindowDays(rule, context).length +\n+\t\t\t\t\t\t\t\t[...state.placements.values()].filter(\n+\t\t\t\t\t\t\t\t\t(placement) =>\n+\t\t\t\t\t\t\t\t\t\tplacement.date >= rule.startDate! &&\n+\t\t\t\t\t\t\t\t\t\tplacement.date <= rule.endDate! &&\n+\t\t\t\t\t\t\t\t\t\tselectorMatches(rule.placeType, placement.type),\n+\t\t\t\t\t\t\t\t).length,\n+\t\t\t\t\t\t)\n \t\t\t\t\t: occurrencePatterns.filter((patterns) =>\n \t\t\t\t\t\t\tpatterns.some((pattern) =>\n \t\t\t\t\t\t\t\tpattern.every((date) =>\n@@ -7305,9 +7151,7 @@ export function analyzeCounterfactualInternal(\n \tconst released = baseline.balances.find((balance) => balance.id === selected.balanceId);\n \tif (released && removed?.balanceId === selected.balanceId) released.remaining++;\n \tconst beforeState = options?.compareOriginalState ? comparisonState : baseline;\n-\tconst beforePreferences = preferenceResultsForState(beforeState, context);\n-\tconst beforeMetrics = qualityMetrics(beforeState, context, beforePreferences);\n-\tconst before = objectiveVector(beforeMetrics, beforePreferences, beforeState, context);\n+\tconst before = objectiveVector(beforeState, context);\n \tconst results: CounterfactualDateResult[] = [];\n \tfor (const date of dateRange(horizon.start, horizon.end)) {\n \t\tlet ineligible: (PlanningReason & { code: CounterfactualReasonCode }) | undefined;\n@@ -7404,9 +7248,7 @@ export function analyzeCounterfactualInternal(\n \t\t\t});\n \t\t\tcontinue;\n \t\t}\n-\t\tconst afterPreferences = preferenceResultsForState(finalized, context);\n-\t\tconst afterMetrics = qualityMetrics(finalized, context, afterPreferences);\n-\t\tconst after = objectiveVector(afterMetrics, afterPreferences, finalized, context);\n+\t\tconst after = objectiveVector(finalized, context);\n \t\tconst comparison = objectiveComparison(before, after);\n \t\tresults.push({ date, status: 'eligible', comparison });\n \t}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner.core.ts", "project_id": 35, "relative_order": 26, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,3 +1,4 @@\n+import { createOptimizationPresetRules } from './rule-service';\n import { vi } from 'vitest';\n import {\n \tapplyReplayDeltas,\n@@ -15,6 +16,18 @@ import type {\n \tPlanningTraceUpdate,\n } from './leave-planner.service';\n import type { CounterfactualBaselineOptions } from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+\n+const supportingEconomy = {\n+\tid: 'economy',\n+\ttype: 'optimization' as const,\n+\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+};\n+const nonWorkingGain = {\n+\tid: 'gain',\n+\ttype: 'optimization' as const,\n+\tconfiguration: OPTIMIZATION_PRESETS.nonWorkingDayGain,\n+};\n \n const horizon = { start: '2024-01-01', end: '2025-01-01' };\n const balance = (\n@@ -48,6 +61,8 @@ async function runInNonBrowser(request: Parameters[0]) {\n beforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n afterEach(() => vi.useRealTimers());\n \n+const presets = createOptimizationPresetRules();\n+\n describe('calculated work-sequence and time-off-period statistics', () => {\n \tit('keeps fractional work means and merges consecutive declared days across a weekend', async () => {\n \t\tconst result = isPlan(\n@@ -1292,7 +1307,7 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-01-02', end: '2024-01-06' },\n \t\t\t\tbalances: [balance('remaining-cp', 'cp', 4, '2024-01-05')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays,\n \t\t\t}),\n \t\t);\n@@ -1358,7 +1373,7 @@ describe('planLeave', () => {\n \t\t\t\tbalances: [\n \t\t\t\t\t{ ...balance('cp', 'cp', 1, '2024-05-13'), availableFrom: '2024-05-13' },\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays,\n \t\t\t}),\n \t\t);\n@@ -1438,7 +1453,7 @@ describe('planLeave', () => {\n \t\t\t\tbalances: [\n \t\t\t\t\t{ ...balance('cp', 'cp', 2, '2024-01-04'), availableFrom: '2024-01-04' },\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays,\n \t\t\t}),\n \t\t);\n@@ -1466,7 +1481,7 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: selectedHorizon,\n \t\t\t\tbalances: [],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays: declaredDays.filter(({ date }) => date !== '2024-01-03'),\n \t\t\t}),\n \t\t);\n@@ -1521,7 +1536,7 @@ describe('planLeave', () => {\n \t\t\tconst result = isPlan(\n \t\t\t\tawait runInNonBrowser({\n \t\t\t\t\thorizon: { start, end },\n-\t\t\t\t\trules: [],\n+\t\t\t\t\trules: [presets[0]],\n \t\t\t\t\tdeclaredDays,\n \t\t\t\t\tbalances: mixed\n \t\t\t\t\t\t? [{ ...balance('cp', 'cp', 1, '2024-05-10'), availableFrom: '2024-05-10' }]\n@@ -1602,7 +1617,7 @@ describe('planLeave', () => {\n \t\tconst request: PlanningRequest = {\n \t\t\thorizon: { start: '2026-11-01', end: '2026-12-01' },\n \t\t\tbalances: [balance('cp', 'cp', 2, '2026-11-30')],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t\tdeclaredDays: [\n \t\t\t\t{ date: '2026-11-09', type: 'other' },\n \t\t\t\t{ date: '2026-11-10', type: 'rtt' },\n@@ -1619,15 +1634,19 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\t...request,\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'preferred-friday',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tstartDate: '2026-11-20',\n-\t\t\t\t\t\tendDate: '2026-11-20',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'preferred-friday',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tstartDate: '2026-11-20',\n+\t\t\t\t\t\t\tendDate: '2026-11-20',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t}),\n \t\t);\n@@ -1927,7 +1946,7 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon,\n \t\t\t\tbalances: [balance('cp', 'cp', 1), balance('rtt', 'rtt', 1)],\n-\t\t\t\trules,\n+\t\t\t\trules: [presets[0], ...rules],\n \t\t\t}),\n \t\t);\n \n@@ -2015,15 +2034,18 @@ describe('planLeave', () => {\n \t\t\t\t\t},\n \t\t\t\t],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'rtt-obligation',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-01-02',\n-\t\t\t\t\t\tendDate: '2024-01-03',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'rtt',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'rtt-obligation',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\t\tstartDate: '2024-01-02',\n+\t\t\t\t\t\t\tendDate: '2024-01-03',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'rtt',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n \t\t\t\t],\n \t\t\t}),\n \t\t);\n@@ -2256,20 +2278,28 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-01-05', end: '2024-01-10' },\n \t\t\t\tbalances: [balance('cp', 'cp', 1, '2025-01-01')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [nonWorkingGain, supportingEconomy],\n \t\t\t}),\n \t\t);\n \t\tconst supporting = result.placements.find((placement) => placement.supporting);\n-\t\texpect(supporting?.ruleIds).toEqual([]);\n+\t\texpect(supporting?.ruleIds).toEqual(['gain']);\n \t\texpect(supporting?.balanceId).toBe('cp');\n \t});\n \n-\tit('does not trade a short-sequence deficit for supporting placement gain', async () => {\n+\tit('does not trade an earlier short-sequence deficit for supporting placement gain', async () => {\n \t\tconst result = isPlan(\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n \t\t\t\tbalances: [balance('cp-four', 'cp', 4, '2025-01-01')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'deficit',\n+\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t},\n+\t\t\t\t\tnonWorkingGain,\n+\t\t\t\t\tsupportingEconomy,\n+\t\t\t\t],\n \t\t\t}),\n \t\t);\n \t\texpect(result.metrics.shortSequenceDeficit).toBe(0);\n@@ -2280,7 +2310,15 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-01-29' },\n \t\t\t\tbalances: [balance('cp-six', 'cp', 6, '2025-01-01')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [\n+\t\t\t\t\tnonWorkingGain,\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'longest',\n+\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.longestWorkSequence,\n+\t\t\t\t\t},\n+\t\t\t\t\tsupportingEconomy,\n+\t\t\t\t],\n \t\t\t}),\n \t\t);\n \t\texpect(result.metrics.supportingPlacements).toBe(\n@@ -2295,19 +2333,24 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-02-01', end: '2024-03-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 2, '2024-02-29')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t}),\n \t\t);\n \t\tconst fourDayPlan = isPlan(\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-02-01', end: '2024-03-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 4, '2024-02-29')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t}),\n \t\t);\n+\t\texpect(twoDayPlan.metrics).toMatchObject({\n+\t\t\tnonWorkingDayGain: 4,\n+\t\t\tlongestWorkSequence: 9,\n+\t\t\tshortSequenceDeficit: 0,\n+\t\t});\n \t\texpect(twoDayPlan.placements.map((placement) => placement.date)).toEqual([\n-\t\t\t'2024-02-09',\n-\t\t\t'2024-02-19',\n+\t\t\t'2024-02-02',\n+\t\t\t'2024-02-16',\n \t\t]);\n \t\texpect(fourDayPlan.placements.map((placement) => placement.date)).toEqual([\n \t\t\t'2024-02-02',\n@@ -2335,7 +2378,7 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: holidayHorizon,\n \t\t\t\tbalances: [balance('cp', 'cp', 4, expiryDate)],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t}),\n \t\t);\n \n@@ -2344,7 +2387,7 @@ describe('planLeave', () => {\n \t\texpect(result.timeOffPeriods[0].duration).toBe(9);\n \t});\n \n-\t// Async calculation yields to the test timer; allow the planner's ten-second budget.\n+\t// This full configured year is measured separately; allow instrumentation overhead without a planning deadline.\n \tit('uses the 11 November and 14 July weeks in the representative default plan', async () => {\n \t\tconst result = isPlan(\n \t\t\tawait runInNonBrowser({\n@@ -2364,28 +2407,32 @@ describe('planLeave', () => {\n \t\t\t\t\t},\n \t\t\t\t],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'default-samedi-malin',\n-\t\t\t\t\t\tname: 'Samedi Malin',\n-\t\t\t\t\t\ttype: 'if_then',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tdayOfWeek: 6,\n-\t\t\t\t\t\tplaceDays: 2,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t\tplacement: 'auto',\n-\t\t\t\t\t\trewardDays: 1,\n-\t\t\t\t\t\trewardType: 'other',\n-\t\t\t\t\t},\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'default-christmas',\n-\t\t\t\t\t\tname: 'Christmas holidays',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tstartDate: '2026-12-20',\n-\t\t\t\t\t\tendDate: '2027-01-03',\n-\t\t\t\t\t\tplaceDays: 5,\n-\t\t\t\t\t\tplaceType: 'any',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'default-samedi-malin',\n+\t\t\t\t\t\t\tname: 'Samedi Malin',\n+\t\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tdayOfWeek: 6,\n+\t\t\t\t\t\t\tplaceDays: 2,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t\tplacement: 'auto',\n+\t\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\t\trewardType: 'other',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'default-christmas',\n+\t\t\t\t\t\t\tname: 'Christmas holidays',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tstartDate: '2026-12-20',\n+\t\t\t\t\t\t\tendDate: '2027-01-03',\n+\t\t\t\t\t\t\tplaceDays: 5,\n+\t\t\t\t\t\t\tplaceType: 'any',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t}),\n \t\t);\n@@ -2402,7 +2449,7 @@ describe('planLeave', () => {\n \t\t\t\t'2027-07-16',\n \t\t\t]),\n \t\t);\n-\t}, 15_000);\n+\t}, 120_000);\n \n \tit('moves a satisfied time-window preference to complete a holiday week', async () => {\n \t\tconst result = isPlan(\n@@ -2410,15 +2457,19 @@ describe('planLeave', () => {\n \t\t\t\thorizon: { start: '2027-07-01', end: '2027-08-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 4, '2027-07-31')],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'july',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tstartDate: '2027-07-01',\n-\t\t\t\t\t\tendDate: '2027-07-31',\n-\t\t\t\t\t\tplaceDays: 4,\n-\t\t\t\t\t\tplaceType: 'any',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'july',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tstartDate: '2027-07-01',\n+\t\t\t\t\t\t\tendDate: '2027-07-31',\n+\t\t\t\t\t\t\tplaceDays: 4,\n+\t\t\t\t\t\t\tplaceType: 'any',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t}),\n \t\t);\n@@ -2437,7 +2488,14 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2027-07-01', end: '2027-08-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 4, '2028-07-31')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'holiday',\n+\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t\t\t\t},\n+\t\t\t\t\tsupportingEconomy,\n+\t\t\t\t],\n \t\t\t}),\n \t\t);\n \n@@ -2456,15 +2514,19 @@ describe('planLeave', () => {\n \t\t\t\thorizon: { start: '2024-01-08', end: '2024-01-15' },\n \t\t\t\tbalances: [balance('cp', 'cp', 1)],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'window',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-01-09',\n-\t\t\t\t\t\tendDate: '2024-01-12',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'window',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\t\tstartDate: '2024-01-09',\n+\t\t\t\t\t\t\tendDate: '2024-01-12',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t}),\n \t\t);\n@@ -2749,15 +2811,19 @@ describe('planLeave', () => {\n \t\t\t\t\t},\n \t\t\t\t],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'fixed',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-05-06',\n-\t\t\t\t\t\tendDate: '2024-05-06',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'fixed',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\t\tstartDate: '2024-05-06',\n+\t\t\t\t\t\t\tendDate: '2024-05-06',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t};\n \t\t\tconst expected = isPlan(await runInNonBrowser(request));\n@@ -2767,7 +2833,8 @@ describe('planLeave', () => {\n \t\t\t\tconst outcome = await runInNonBrowser({\n \t\t\t\t\t...request,\n \t\t\t\t\tprogress: (stage) => {\n-\t\t\t\t\t\tif (stage === 'at-risk') queueMicrotask(() => (elapsed = 20_000));\n+\t\t\t\t\t\tif (stage === 'optimization:default-unplaced-at-risk')\n+\t\t\t\t\t\t\tqueueMicrotask(() => (elapsed = 20_000));\n \t\t\t\t\t},\n \t\t\t\t});\n \t\t\t\texpect(elapsed).toBeGreaterThan(10_000);\n@@ -2953,8 +3020,8 @@ describe('planLeave transport', () => {\n \t\tif (expected.kind !== 'Plan' || !checkpointState) return;\n \t\tcheckpoint = {\n \t\t\t...expected,\n-\t\t\tcompletedStages: ['validation', 'obligations', 'at-risk'],\n-\t\t\tlastCompletedStage: 'at-risk',\n+\t\t\tcompletedStages: ['validation', 'obligations', 'optimization:default-unplaced-at-risk'],\n+\t\t\tlastCompletedStage: 'optimization:default-unplaced-at-risk',\n \t\t};\n \t\tconst initialState: PlanningTraceState = {\n \t\t\thorizon: request.horizon,\n@@ -3271,7 +3338,7 @@ describe('planning calculation context', () => {\n \t\t\tconst calculation = createPlanningCalculation(submitted);\n \t\t\tsubmitted.declaredDays![0].date = '2024-01-11';\n \t\t\tsubmitted.declaredDays![0].type = 'rtt';\n-\t\t\tsubmitted.rules[0].placeDays = 4;\n+\t\t\tif ('placeDays' in submitted.rules[0]) submitted.rules[0].placeDays = 4;\n \t\t\tif ('endDate' in submitted.rules[0]) submitted.rules[0].endDate = '2024-01-19';\n \t\t\tsubmitted.horizon.end = '2024-01-11';\n \t\t\tsubmitted.labels = { exact: 'Edited later' };\n@@ -3378,7 +3445,7 @@ describe('planning calculation context', () => {\n \t\t\t\tbalances: [\n \t\t\t\t\t{ ...balance('cp', 'cp', 1, '2024-12-30'), availableFrom: '2024-12-30' },\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays,\n \t\t\t});\n \t\t\tconst outcome = isPlan(await calculation.outcome);\n@@ -3407,7 +3474,7 @@ describe('planning calculation context', () => {\n \t\t\tconst submitted: PlanningRequest = {\n \t\t\t\thorizon: { start: '2026-11-01', end: '2026-12-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 2, '2026-11-30')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t\tdeclaredDays: [\n \t\t\t\t\t{ date: '2026-11-09', type: 'other' },\n \t\t\t\t\t{ date: '2026-11-10', type: 'rtt' },\n@@ -3427,7 +3494,9 @@ describe('planning calculation context', () => {\n \t\t\tfor (const placement of explanation.placements) {\n \t\t\t\texpect(placement.timeOffPeriod).toEqual(outcome.timeOffPeriods[0]);\n \t\t\t\texpect(placement.finalMetrics).toEqual(outcome.metrics);\n-\t\t\t\texpect(placement.firstDecisiveObjective).toBe('unplaced-at-risk');\n+\t\t\t\texpect(placement.firstDecisiveObjective).toBe(\n+\t\t\t\t\t'optimization:default-unplaced-at-risk',\n+\t\t\t\t);\n \t\t\t}\n \t\t\tconst trace = await calculation.trace;\n \t\t\texpect(trace?.initialState.declaredDays).toEqual(original);\n@@ -3446,11 +3515,13 @@ describe('planning calculation context', () => {\n \t\t\t\t\t(candidate) =>\n \t\t\t\t\t\tcandidate.comparison?.after.objectives.some(\n \t\t\t\t\t\t\t(objective) =>\n-\t\t\t\t\t\t\t\tobjective.id === 'holiday-week-value' && objective.value === 3,\n+\t\t\t\t\t\t\t\tobjective.id === 'optimization:default-holiday-week-value' &&\n+\t\t\t\t\t\t\t\tobjective.value === 3,\n \t\t\t\t\t\t) &&\n \t\t\t\t\t\tcandidate.comparison.after.objectives.some(\n \t\t\t\t\t\t\t(objective) =>\n-\t\t\t\t\t\t\t\tobjective.id === 'non-working-day-gain' && objective.value === 5,\n+\t\t\t\t\t\t\t\tobjective.id === 'optimization:default-non-working-day-gain' &&\n+\t\t\t\t\t\t\t\tobjective.value === 5,\n \t\t\t\t\t\t),\n \t\t\t\t),\n \t\t\t).toBe(true);\n@@ -3463,10 +3534,16 @@ describe('planning calculation context', () => {\n \t\t\tconst alternative = analysis.results.find(({ date }) => date === '2026-11-20');\n \t\t\texpect(alternative?.status).toBe('eligible');\n \t\t\texpect(alternative?.comparison?.after.objectives).toContainEqual(\n-\t\t\t\texpect.objectContaining({ id: 'holiday-week-value', value: 0 }),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tid: 'optimization:default-holiday-week-value',\n+\t\t\t\t\tvalue: 0,\n+\t\t\t\t}),\n \t\t\t);\n \t\t\texpect(alternative?.comparison?.after.objectives).toContainEqual(\n-\t\t\t\texpect.objectContaining({ id: 'non-working-day-gain', value: 7 }),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tid: 'optimization:default-non-working-day-gain',\n+\t\t\t\t\tvalue: 7,\n+\t\t\t\t}),\n \t\t\t);\n \t\t\texpect(outcome).toEqual(before);\n \t\t} finally {\n@@ -3481,7 +3558,7 @@ describe('planning calculation context', () => {\n \t\t\tconst submitted: PlanningRequest = {\n \t\t\t\thorizon: { start: '2024-01-02', end: '2024-02-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 4, '2024-01-05')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays: [\n \t\t\t\t\t{ date: '2024-01-02', type: 'cp' },\n \t\t\t\t\t{ date: '2024-01-03', type: 'rtt' },\n@@ -3828,7 +3905,7 @@ describe('planning calculation context', () => {\n \t\t\tconst calculation = createPlanningCalculation({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\t\tbalances: [balance('cp', 'cp', 1, '2024-12-31')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[3]],\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n \t\t\texpect(outcome.kind).toBe('Plan');\n@@ -3886,7 +3963,7 @@ describe('planning calculation context', () => {\n \t\t\tif (!firstOccurrence || !secondOccurrence) return;\n \n \t\t\tconst alternateSecondDate =\n-\t\t\t\tsecondOccurrence.date === '2024-05-07' ? '2024-05-09' : '2024-05-07';\n+\t\t\t\tsecondOccurrence.date === '2024-05-07' ? '2024-05-10' : '2024-05-07';\n \t\t\tconst analysis = await calculation.analyzeCounterfactual(firstOccurrence);\n \t\t\texpect(analysis.kind).toBe('Counterfactual');\n \t\t\tif (analysis.kind !== 'Counterfactual') return;\n@@ -3976,7 +4053,7 @@ describe('planning calculation context', () => {\n \t\t\tconst calculation = createPlanningCalculation({\n \t\t\t\thorizon: { start: '2024-01-05', end: '2024-01-10' },\n \t\t\t\tbalances: [balance('cp', 'cp', 1, '2025-01-01')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [nonWorkingGain, supportingEconomy],\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n \t\t\texpect(outcome.kind).toBe('Plan');\n@@ -3991,7 +4068,7 @@ describe('planning calculation context', () => {\n \t\t\tconst restored = analysis.results.find((result) => result.date === selected.date);\n \t\t\texpect(\n \t\t\t\trestored?.comparison?.after.objectives.find(\n-\t\t\t\t\t(objective) => objective.id === 'supporting-placements',\n+\t\t\t\t\t(objective) => objective.id === 'optimization:economy',\n \t\t\t\t)?.value,\n \t\t\t).toBe(1);\n \t\t} finally {\n@@ -4097,7 +4174,7 @@ describe('planning calculation context', () => {\n \t\t\tconst older = createPlanningCalculation({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\t\tbalances: [balance('cp', 'cp', 1)],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[3]],\n \t\t\t});\n \t\t\tconst olderOutcome = await older.outcome;\n \t\t\texpect(olderOutcome.kind).toBe('Plan');\n@@ -4116,7 +4193,7 @@ describe('planning calculation context', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\tbalances: [balance('cp', 'cp', 1)],\n-\t\t\trules: [],\n+\t\t\trules: [presets[3]],\n \t\t};\n \t\tconst expected = isPlan(await runInNonBrowser(request));\n \t\tconst selected = expected.placements[0];\n@@ -4213,7 +4290,7 @@ describe('planning calculation context', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\tbalances: [balance('cp', 'cp', 1)],\n-\t\t\trules: [],\n+\t\t\trules: [presets[3]],\n \t\t};\n \t\tconst expected = isPlan(await runInNonBrowser(request));\n \t\tconst trace = {\n@@ -4343,15 +4420,18 @@ describe('planning calculation context', () => {\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 2, '2024-01-31')],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'wide',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-01-01',\n-\t\t\t\t\t\tendDate: '2024-01-31',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'wide',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\t\tstartDate: '2024-01-01',\n+\t\t\t\t\t\t\tendDate: '2024-01-31',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n \t\t\t\t],\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n@@ -4404,7 +4484,7 @@ describe('planning calculation context', () => {\n \t\t\t\t\t\tavailableFrom: '2024-01-04',\n \t\t\t\t\t},\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n \t\t\tconst trace = await calculation.trace;\n@@ -4466,7 +4546,7 @@ describe('planning calculation context', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\tbalances: [balance('cp', 'cp', 1)],\n-\t\t\trules: [],\n+\t\t\trules: [presets[3]],\n \t\t};\n \t\tconst plan = isPlan(await runInNonBrowser(request));\n \t\tconst firstPlacement = plan.placements[0];\n@@ -4745,81 +4825,98 @@ describe('planning calculation context', () => {\n \t});\n \n \tit('does not inherit unrelated rule-invalid history into a trace decision', async () => {\n+\t\tconst core = await import('./leave-planner.core');\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n+\t\t\tbalances: [balance('cp', 'cp', 1, '2024-01-10')],\n+\t\t\trules: [presets[0]],\n+\t\t};\n+\t\tlet artifacts: import('./leave-planner.core').PlanningArtifacts = {};\n+\t\tconst outcome = core.calculatePlanningInternal(\n+\t\t\trequest,\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\texpect(outcome.kind).toBe('Plan');\n+\t\tconst trace = artifacts.trace && {\n+\t\t\t...artifacts.trace,\n+\t\t\tphases: [...artifacts.trace.phases],\n+\t\t};\n+\t\tartifacts = { ...artifacts, trace };\n+\t\tif (outcome.kind !== 'Plan' || !trace)\n+\t\t\tthrow new Error('Expected an actual plan and trace.');\n+\t\tconst decision = trace.phases\n+\t\t\t.flatMap((phase) => phase.decisions)\n+\t\t\t.find((item) => item.deltas.some((delta) => delta.kind === 'placement-added'));\n+\t\tconst placement = decision?.deltas.find(\n+\t\t\t(delta) => delta.kind === 'placement-added',\n+\t\t)?.placement;\n+\t\tif (!decision || !placement) throw new Error('Expected an actual placement decision.');\n+\t\t// An unrelated decision's rejection must not become the selected decision's history.\n+\t\tconst unrelatedDate = '2024-01-04';\n+\t\tdecision.candidates = decision.candidates.filter(\n+\t\t\t(candidate) =>\n+\t\t\t\t!(candidate.dates ?? (candidate.date ? [candidate.date] : [])).includes(\n+\t\t\t\t\tunrelatedDate,\n+\t\t\t\t),\n+\t\t);\n+\t\ttrace.phases.push({\n+\t\t\tid: 'unrelated-phase',\n+\t\t\tname: 'unrelated',\n+\t\t\tcompleted: true,\n+\t\t\tstatus: 'completed',\n+\t\t\tdecisions: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'unrelated-decision',\n+\t\t\t\t\taction: 'reject',\n+\t\t\t\t\tdates: [unrelatedDate],\n+\t\t\t\t\tdeltas: [],\n+\t\t\t\t\tcandidates: [\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tstatus: 'ineligible',\n+\t\t\t\t\t\t\tdate: unrelatedDate,\n+\t\t\t\t\t\t\treason: {\n+\t\t\t\t\t\t\t\tcode: 'rule-invalid',\n+\t\t\t\t\t\t\t\tmessage: 'Another decision rejected this date.',\n+\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\tclass HistoricalTraceWorker {\n+\t\t\tonmessage: ((event: MessageEvent) => void) | null = null;\n+\t\t\tonerror: (() => void) | null = null;\n+\t\t\tpostMessage(): void {\n+\t\t\t\tqueueMicrotask(() => {\n+\t\t\t\t\tthis.onmessage?.({ data: { type: 'result', outcome } } as MessageEvent);\n+\t\t\t\t\tthis.onmessage?.({ data: { type: 'artifacts', artifacts } } as MessageEvent);\n+\t\t\t\t});\n+\t\t\t}\n+\t\t\tterminate(): void {}\n+\t\t}\n \t\tconst browserWindow = globalThis.window;\n-\t\tvi.stubGlobal('window', undefined);\n+\t\tvi.stubGlobal('window', {});\n+\t\tvi.stubGlobal('Worker', HistoricalTraceWorker);\n \t\ttry {\n-\t\t\tconst calculation = createPlanningCalculation({\n-\t\t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n-\t\t\t\tbalances: [balance('cp', 'cp', 1, '2024-01-31')],\n-\t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'early-window',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-01-02',\n-\t\t\t\t\t\tendDate: '2024-01-04',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'late-window',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-01-03',\n-\t\t\t\t\t\tendDate: '2024-01-05',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n-\t\t\t\t],\n-\t\t\t});\n-\t\t\tconst outcome = await calculation.outcome;\n-\t\t\tconst trace = await calculation.trace;\n-\t\t\texpect(outcome.kind).toBe('Plan');\n-\t\t\tif (outcome.kind !== 'Plan' || !trace) return;\n-\t\t\tconst decision = trace.phases\n-\t\t\t\t.flatMap((phase) => phase.decisions)\n-\t\t\t\t.find((candidate) =>\n-\t\t\t\t\tcandidate.deltas.some((delta) => delta.kind === 'placement-added'),\n-\t\t\t\t);\n-\t\t\tconst placement = decision?.deltas.find(\n-\t\t\t\t(delta) => delta.kind === 'placement-added',\n-\t\t\t)?.placement;\n-\t\t\texpect(decision).toBeDefined();\n-\t\t\texpect(placement).toBeDefined();\n-\t\t\tif (!decision || !placement) return;\n-\n-\t\t\tconst candidates = trace.phases.flatMap((phase) =>\n-\t\t\t\tphase.decisions.flatMap((item) => item.candidates),\n-\t\t\t);\n-\t\t\tconst decisionDates = new Set(\n-\t\t\t\tdecision.candidates.flatMap(\n-\t\t\t\t\t(candidate) => candidate.dates ?? (candidate.date ? [candidate.date] : []),\n-\t\t\t\t),\n-\t\t\t);\n-\t\t\tconst unrelatedIneligible = candidates.find(\n-\t\t\t\t(candidate) =>\n-\t\t\t\t\tcandidate.status === 'ineligible' &&\n-\t\t\t\t\tcandidate.reason?.code === 'rule-invalid' &&\n-\t\t\t\t\tcandidate.date &&\n-\t\t\t\t\t!decisionDates.has(candidate.date),\n-\t\t\t);\n-\t\t\texpect(unrelatedIneligible).toBeDefined();\n-\t\t\tif (!unrelatedIneligible?.date) return;\n-\n+\t\t\tconst calculation = createPlanningCalculation(request);\n+\t\t\tawait calculation.trace;\n+\t\t\tvi.stubGlobal('window', undefined);\n \t\t\tconst analysis = await calculation.analyzeCounterfactual({\n \t\t\t\tdecisionId: decision.id,\n \t\t\t\tplacement,\n \t\t\t});\n \t\t\texpect(analysis.kind).toBe('Counterfactual');\n \t\t\tif (analysis.kind !== 'Counterfactual') return;\n-\t\t\texpect(\n-\t\t\t\tanalysis.results.find((result) => result.date === unrelatedIneligible.date)\n-\t\t\t\t\t?.historicalStatus,\n-\t\t\t).toBe('not-examined');\n+\t\t\texpect(analysis.results.find((result) => result.date === unrelatedDate)).toMatchObject({\n+\t\t\t\thistoricalStatus: 'not-examined',\n+\t\t\t\thistoricalReason: undefined,\n+\t\t\t});\n \t\t\texpect(\n \t\t\t\tanalysis.results.find((result) => result.date === '2024-01-06')?.historicalStatus,\n \t\t\t).toBe('ineligible');\n \t\t} finally {\n+\t\t\tvi.unstubAllGlobals();\n \t\t\tvi.stubGlobal('window', browserWindow);\n \t\t}\n \t});\n@@ -4831,7 +4928,7 @@ describe('planning calculation context', () => {\n \t\t\tconst calculation = createPlanningCalculation({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 4, '2024-01-31')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n \t\t\tconst trace = await calculation.trace;\n@@ -4854,12 +4951,12 @@ describe('planning calculation context', () => {\n \t\t\texpect(trace.phases.map((phase) => phase.name)).toEqual(\n \t\t\t\texpect.arrayContaining([\n \t\t\t\t\t'obligations',\n-\t\t\t\t\t'at-risk',\n-\t\t\t\t\t'holiday-week-value',\n-\t\t\t\t\t'non-working-day-gain',\n-\t\t\t\t\t'longest-work-sequence',\n-\t\t\t\t\t'short-sequence-deficit',\n-\t\t\t\t\t'supporting-placements',\n+\t\t\t\t\t'optimization:default-unplaced-at-risk',\n+\t\t\t\t\t'optimization:default-holiday-week-value',\n+\t\t\t\t\t'optimization:default-non-working-day-gain',\n+\t\t\t\t\t'optimization:default-longest-work-sequence',\n+\t\t\t\t\t'optimization:default-short-sequence-deficit',\n+\t\t\t\t\t'optimization:default-supporting-placements',\n \t\t\t\t\t'expiry',\n \t\t\t\t\t'dates',\n \t\t\t\t]),\n@@ -4881,7 +4978,7 @@ describe('planning calculation context', () => {\n \t\t\tconst calculation = createPlanningCalculation({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-04-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 25, '2024-03-31')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t});\n \t\t\texpect((await calculation.outcome).kind).toBe('Plan');\n \t\t\tconst trace = await calculation.trace;\n@@ -4907,16 +5004,18 @@ describe('planning calculation context', () => {\n \t\t\t);\n \t\t\texpect(chosenComparisons.length).toBeGreaterThan(0);\n \t\t\tfor (const { decision, candidate: chosen } of chosenComparisons) {\n+\t\t\t\tconst changedDates = chosen.dates ?? (chosen.date ? [chosen.date] : []);\n \t\t\t\texpect(\n \t\t\t\t\tdecision.deltas.some(\n \t\t\t\t\t\t(delta) =>\n \t\t\t\t\t\t\t(delta.kind === 'placement-moved' &&\n-\t\t\t\t\t\t\t\tdelta.toDate === chosen.date &&\n-\t\t\t\t\t\t\t\tdelta.balanceId === chosen.placement?.balanceId) ||\n+\t\t\t\t\t\t\t\tchangedDates.includes(delta.toDate ?? '')) ||\n \t\t\t\t\t\t\t(delta.kind === 'placement-added' &&\n-\t\t\t\t\t\t\t\tdelta.date === chosen.date &&\n-\t\t\t\t\t\t\t\tdelta.balanceId === chosen.placement?.balanceId) ||\n-\t\t\t\t\t\t\t(delta.kind === 'placement-removed' && delta.date === chosen.date),\n+\t\t\t\t\t\t\t\tchangedDates.includes(delta.date ?? '')) ||\n+\t\t\t\t\t\t\t(delta.kind === 'placement-removed' &&\n+\t\t\t\t\t\t\t\tchangedDates.includes(delta.date ?? '')) ||\n+\t\t\t\t\t\t\t(delta.kind === 'placement-updated' &&\n+\t\t\t\t\t\t\t\tchangedDates.includes(delta.date ?? '')),\n \t\t\t\t\t),\n \t\t\t\t).toBe(true);\n \t\t\t}\n@@ -4942,7 +5041,7 @@ describe('planning calculation context', () => {\n \t\t}\n \t});\n \n-\tit('records every eligible balance when a preference keeps the first assignment', async () => {\n+\tit('evaluates every eligible balance and retains the earlier expiry for an equal preference', async () => {\n \t\tconst browserWindow = globalThis.window;\n \t\tvi.stubGlobal('window', undefined);\n \t\ttry {\n@@ -4980,10 +5079,12 @@ describe('planning calculation context', () => {\n \t\t\t\t\t\tstatus: candidate.status,\n \t\t\t\t\t\treason: candidate.reason?.code,\n \t\t\t\t\t})) ?? [];\n-\t\t\texpect(candidates.slice(0, 2)).toEqual([\n-\t\t\t\t{ balanceId: 'earlier', status: 'chosen', reason: undefined },\n-\t\t\t\t{ balanceId: 'later', status: 'not-examined', reason: 'first-compatible-balance' },\n-\t\t\t]);\n+\t\t\texpect(candidates).toEqual(\n+\t\t\t\texpect.arrayContaining([\n+\t\t\t\t\t{ balanceId: 'earlier', status: 'chosen', reason: undefined },\n+\t\t\t\t\t{ balanceId: 'later', status: 'evaluated-rejected', reason: undefined },\n+\t\t\t\t]),\n+\t\t\t);\n \t\t} finally {\n \t\t\tvi.stubGlobal('window', browserWindow);\n \t\t}\n@@ -5026,7 +5127,11 @@ describe('planning calculation context', () => {\n \t\t\t\t\t{ id: 'cp-only', label: 'Paid leave only' },\n \t\t\t\t]);\n \t\t\tconst trace = await conflictCalculation.trace;\n-\t\t\texpect(trace?.phases.some((phase) => phase.name === 'holiday-week-value')).toBe(false);\n+\t\t\texpect(\n+\t\t\t\ttrace?.phases.some(\n+\t\t\t\t\t(phase) => phase.name === 'optimization:default-holiday-week-value',\n+\t\t\t\t),\n+\t\t\t).toBe(false);\n \t\t} finally {\n \t\t\tvi.stubGlobal('window', browserWindow);\n \t\t}\n@@ -5056,28 +5161,41 @@ describe('planning calculation context', () => {\n \n \tit('explains an incomplete incumbent without reusing the expired planning deadline', async () => {\n \t\tconst core = await import('./leave-planner.core');\n-\t\tlet artifacts: import('./leave-planner.core').PlanningArtifacts | undefined;\n-\t\tconst outcome = core.calculatePlanningInternal(\n-\t\t\t{\n-\t\t\t\thorizon,\n-\t\t\t\tbalances: Array.from({ length: 12 }, (_, index) =>\n-\t\t\t\t\tbalance(`balance-${index}`, index % 2 ? 'rtt' : 'cp', 12),\n-\t\t\t\t),\n-\t\t\t\trules: [],\n-\t\t\t\tdeadlineMs: 20,\n-\t\t\t},\n-\t\t\tundefined,\n-\t\t\t(value) => (artifacts = value),\n-\t\t);\n-\t\texpect(outcome.kind).toBe('PlanningIncomplete');\n-\t\tif (outcome.kind !== 'PlanningIncomplete') return;\n-\t\texpect(outcome.incumbent).toBeDefined();\n-\t\texpect(artifacts?.explanation?.kind).toBe('PlanExplanation');\n-\t\tif (artifacts?.explanation?.kind !== 'PlanExplanation') return;\n-\t\texpect(artifacts.explanation.incomplete?.reason.code).toBe('deadline');\n-\t\texpect(artifacts.explanation.placements).toHaveLength(\n-\t\t\toutcome.incumbent?.placements.length ?? 0,\n-\t\t);\n+\t\tlet clock = 0;\n+\t\tlet expired = false;\n+\t\tconst clockSpy = vi.spyOn(performance, 'now').mockImplementation(() => {\n+\t\t\tif (expired) clock += 100;\n+\t\t\treturn clock;\n+\t\t});\n+\t\ttry {\n+\t\t\tlet artifacts: import('./leave-planner.core').PlanningArtifacts | undefined;\n+\t\t\tconst outcome = core.calculatePlanningInternal(\n+\t\t\t\t{\n+\t\t\t\t\thorizon,\n+\t\t\t\t\tbalances: Array.from({ length: 12 }, (_, index) =>\n+\t\t\t\t\t\tbalance(`balance-${index}`, index % 2 ? 'rtt' : 'cp', 12),\n+\t\t\t\t\t),\n+\t\t\t\t\trules: presets,\n+\t\t\t\t\tdeadlineMs: 20,\n+\t\t\t\t\tprogress: (stage: string) => {\n+\t\t\t\t\t\tif (stage === `optimization:${presets[0].id}`) expired = true;\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\texpect(outcome.kind).toBe('PlanningIncomplete');\n+\t\t\tif (outcome.kind !== 'PlanningIncomplete') return;\n+\t\t\texpect(outcome.incumbent).toBeDefined();\n+\t\t\texpect(artifacts?.explanation?.kind).toBe('PlanExplanation');\n+\t\t\tif (artifacts?.explanation?.kind !== 'PlanExplanation') return;\n+\t\t\texpect(artifacts.explanation.incomplete?.reason.code).toBe('deadline');\n+\t\t\texpect(artifacts.explanation.placements).toHaveLength(\n+\t\t\t\toutcome.incumbent?.placements.length ?? 0,\n+\t\t\t);\n+\t\t} finally {\n+\t\t\tclockSpy.mockRestore();\n+\t\t}\n \t});\n \n \tit('publishes the worker outcome before delayed explanation artifacts', async () => {\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner.service.spec.ts", "project_id": 35, "relative_order": 27, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -80,6 +80,7 @@ export type {\n \tTimeOffPeriod,\n \tTimeWindowContribution,\n \tTimeWindowPlanningRule,\n+\tOptimizationPlanningRule,\n \tTraceCounterfactualSelection,\n \tTraceCandidateStatus,\n } from './leave-planner.core';\n@@ -117,6 +118,7 @@ interface UntrustedRecord {\n \tplacement?: unknown;\n \trewardDays?: unknown;\n \trewardType?: unknown;\n+\tconfiguration?: unknown;\n }\n \n interface TransportSnapshot {\n@@ -238,6 +240,12 @@ function snapshotRequest(request: unknown): TransportSnapshot {\n \t\t\t\t\tenabled: value?.enabled,\n \t\t\t\t\tforce: value?.force,\n \t\t\t\t};\n+\t\t\t\tif (\n+\t\t\t\t\ttypeof value?.type === 'string' &&\n+\t\t\t\t\tvalue.type.toLowerCase() === 'optimization'\n+\t\t\t\t) {\n+\t\t\t\t\treturn { ...base, configuration: cloneUnknown(value.configuration) };\n+\t\t\t\t}\n \t\t\t\tif (typeof value?.type === 'string' && value.type.toLowerCase() === 'time_window') {\n \t\t\t\t\treturn {\n \t\t\t\t\t\t...base,\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner.service.ts", "project_id": 35, "relative_order": 28, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -15,11 +15,14 @@ import { CalendarYear } from '../components/calendar-year/calendar-year';\n import { CalendarService, SelectableDayType } from './calendar-service';\n import { CalendarSettingsService } from './calendar-settings-service';\n import { UserInputService } from './user-input-service';\n-import { RuleService, RuleType } from './rule-service';\n+import { RuleService, RuleType, createOptimizationPresetRules } from './rule-service';\n+import { OPTIMIZATION_PRESETS, type OptimizationConfiguration } from './planning-objectives';\n \n beforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n afterEach(() => vi.useRealTimers());\n \n+const presets = createOptimizationPresetRules();\n+\n describe('real planning worker cancellation', () => {\n \tlet directory: string;\n \tlet bundle: string;\n@@ -43,7 +46,7 @@ const originalNow = performance.now.bind(performance);\n if (workerData.simulateLongCalculation)\n Object.defineProperty(performance, 'now', { value: () => originalNow() + elapsed });\n globalThis.self = { postMessage: (message) => {\n- if (workerData.simulateLongCalculation && message.type === 'progress' && message.stage === 'at-risk')\n+ if (workerData.simulateLongCalculation && message.type === 'progress' && message.stage === 'optimization:default-unplaced-at-risk')\n setTimeout(() => { elapsed = 20_000; parentPort.postMessage({ type: 'test-clock', elapsed }); }, 0);\n parentPort.postMessage(message);\n } };\n@@ -109,6 +112,123 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t});\n \tafterAll(() => rmSync(directory, { recursive: true, force: true }));\n \n+\tit('preserves a complete optimization configuration and active order in the real worker snapshot', async () => {\n+\t\tconst configuration: OptimizationConfiguration = structuredClone(\n+\t\t\tOPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t);\n+\t\tconfiguration.aggregation = 'maximum';\n+\t\tconst submitted = structuredClone(configuration);\n+\t\tconst calculation = createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-05' },\n+\t\t\tbalances: [{ id: 'rtt', type: 'rtt', quantity: 1, expiryDate: '2024-01-04' }],\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'personal-loss',\n+\t\t\t\t\tname: 'Captured loss rule',\n+\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\tconfiguration,\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\tconfiguration.conditions = [];\n+\t\tconfiguration.direction = 'maximize';\n+\t\tconfiguration.aggregation = 'count';\n+\t\tconst outcome = await calculation.outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a worker plan');\n+\t\texpect(outcome.placements).toHaveLength(1);\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(calculation.snapshot.rules[0]).toMatchObject({\n+\t\t\tname: 'Captured loss rule',\n+\t\t\tconfiguration: submitted,\n+\t\t});\n+\t\tconst explanation = await calculation.explanation;\n+\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected worker explanation');\n+\t\texpect(\n+\t\t\texplanation.placements[0].objectiveVector.objectives.map((objective) => objective.id),\n+\t\t).toEqual([\n+\t\t\t'obligation-validity',\n+\t\t\t'optimization:personal-loss',\n+\t\t\t'balance-expiry',\n+\t\t\t'placement-date',\n+\t\t]);\n+\t\tconst trace = await calculation.trace;\n+\t\texpect(trace?.phases.map((phase) => phase.name)).toEqual([\n+\t\t\t'validation',\n+\t\t\t'obligations',\n+\t\t\t'optimization:personal-loss',\n+\t\t\t'expiry',\n+\t\t\t'dates',\n+\t\t]);\n+\t\tconst comparison = await calculation.analyzeCounterfactual(outcome.placements[0]);\n+\t\tif (comparison.kind !== 'Counterfactual') throw new Error('Expected worker comparison');\n+\t\texpect(comparison.baseline.objectives.map((objective) => objective.id)).toEqual([\n+\t\t\t'obligation-validity',\n+\t\t\t'optimization:personal-loss',\n+\t\t\t'balance-expiry',\n+\t\t\t'placement-date',\n+\t\t]);\n+\t});\n+\n+\tit('keeps the submitted work-sequence threshold in the real worker, trace and counterfactuals', async () => {\n+\t\tconst configuration: OptimizationConfiguration = structuredClone(\n+\t\t\tOPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t);\n+\t\tconst calculation = createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: ['2024-01-08', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'deficit',\n+\t\t\t\t\tname: 'Captured five-day preference',\n+\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\tconfiguration,\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\tconfiguration.thresholdDays = 3;\n+\t\tconfiguration.conditions = [];\n+\t\tconst outcome = await calculation.outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a worker plan');\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual([\n+\t\t\t'2024-01-09',\n+\t\t\t'2024-01-10',\n+\t\t\t'2024-01-11',\n+\t\t]);\n+\t\texpect(calculation.snapshot.rules[0]).toMatchObject({\n+\t\t\tconfiguration: { thresholdDays: 5, conditions: ['internal', 'non-empty'] },\n+\t\t});\n+\t\tconst explanation = await calculation.explanation;\n+\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\texpect(\n+\t\t\texplanation.placements[0].comparison.before.objectives.find(\n+\t\t\t\t({ id }) => id === 'optimization:deficit',\n+\t\t\t)?.value,\n+\t\t).toBe(4);\n+\t\tconst trace = await calculation.trace;\n+\t\tconst chosen = trace?.phases\n+\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t.find((candidate) => candidate.status === 'chosen' && candidate.dates?.length === 3);\n+\t\texpect(chosen?.comparison?.firstDecisiveObjective).toBe('optimization:deficit');\n+\t\texpect(\n+\t\t\tchosen?.comparison?.before.objectives.find(({ id }) => id === 'optimization:deficit')\n+\t\t\t\t?.value,\n+\t\t).toBe(2);\n+\t\tconst counterfactual = await calculation.analyzeCounterfactual(outcome.placements[0]);\n+\t\tif (counterfactual.kind !== 'Counterfactual') throw new Error('Expected a counterfactual');\n+\t\texpect(\n+\t\t\tcounterfactual.baseline.objectives.find(({ id }) => id === 'optimization:deficit')\n+\t\t\t\t?.value,\n+\t\t).toBe(4);\n+\t\texpect(\n+\t\t\tcounterfactual.results\n+\t\t\t\t.find(({ date }) => date === '2024-01-09')\n+\t\t\t\t?.comparison?.after.objectives.find(({ id }) => id === 'optimization:deficit')\n+\t\t\t\t?.value,\n+\t\t).toBe(0);\n+\t});\n+\n \tit.each([\n \t\t[false, false],\n \t\t[true, false],\n@@ -120,7 +240,7 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\tlocalStorage.clear();\n \t\t\tlocalStorage.setItem('app.language', '\"fr\"');\n \t\t\tlocalStorage.setItem('leaveBalances', '[]');\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tvi.setSystemTime(new Date('2024-05-01T21:59:59Z'));\n \t\t\tawait TestBed.configureTestingModule({\n \t\t\t\timports: [CalendarYear],\n@@ -131,6 +251,7 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\tfor (const date of ['2024-04-29', '2024-04-30']) input.toggleDeclaredDay(date, 'cp');\n \t\t\tinput.toggleDeclaredDay('2024-05-06', 'other');\n \t\t\tconst rules = TestBed.inject(RuleService);\n+\t\t\trules.addRule(presets[0]);\n \t\t\trules.addRule({\n \t\t\t\tid: 'producer',\n \t\t\t\tname: 'CP autour du férié',\n@@ -155,6 +276,7 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\t\tplaceDays: 2,\n \t\t\t\tplaceType: SelectableDayType.OTHER,\n \t\t\t});\n+\t\t\tfor (const preset of presets.slice(1)) rules.addRule(preset);\n \t\t\tconst calendar = TestBed.inject(CalendarService);\n \t\t\tconst original = calendar.createPlanningCalculation.bind(calendar);\n \t\t\tlet calculation!: PlanningCalculationContext;\n@@ -168,7 +290,10 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\t\t\t\t\t...request,\n \t\t\t\t\t\t\tprogress: (stage) => {\n \t\t\t\t\t\t\t\trequest.progress?.(stage);\n-\t\t\t\t\t\t\t\tif (cancelled && stage === 'non-working-day-gain') {\n+\t\t\t\t\t\t\t\tif (\n+\t\t\t\t\t\t\t\t\tcancelled &&\n+\t\t\t\t\t\t\t\t\tstage === 'optimization:default-non-working-day-gain'\n+\t\t\t\t\t\t\t\t) {\n \t\t\t\t\t\t\t\t\tfixture.detectChanges();\n \t\t\t\t\t\t\t\t\tfixture.nativeElement\n \t\t\t\t\t\t\t\t\t\t.querySelector('button.cancel-calculation')\n@@ -249,7 +374,10 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\texpect(dialog.textContent?.includes('Planning partiel')).toBe(cancelled);\n \t\t\tconst originalDeclarations = structuredClone(calculation.snapshot.declaredDays);\n \t\t\tinput.toggleDeclaredDay('2024-04-30', 'rtt');\n-\t\t\trules.updateRule({ ...rules.rules[0], name: 'Règle modifiée après calcul' });\n+\t\t\trules.updateRule({\n+\t\t\t\t...rules.rules.find(({ id }) => id === 'producer')!,\n+\t\t\t\tname: 'Règle modifiée après calcul',\n+\t\t\t});\n \t\t\trules.deleteRule('producer');\n \t\t\tinput.updateBalances(() => []);\n \t\t\tif (worker) {\n@@ -355,7 +483,7 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\t\tbalances: [\n \t\t\t\t\t{ id: 'cp', type: 'cp' as const, quantity: 4, expiryDate: '2024-01-05' },\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t\tdeclaredDays: [\n \t\t\t\t\t{ date: '2024-01-02', type: 'cp' as const },\n \t\t\t\t\t{ date: '2024-01-03', type: 'rtt' as const },\n@@ -370,7 +498,8 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\t\t\t\t{\n \t\t\t\t\t\t\t...submitted,\n \t\t\t\t\t\t\tprogress: (stage: string) => {\n-\t\t\t\t\t\t\t\tif (stage === 'non-working-day-gain') interruption = true;\n+\t\t\t\t\t\t\t\tif (stage === 'optimization:default-non-working-day-gain')\n+\t\t\t\t\t\t\t\t\tinterruption = true;\n \t\t\t\t\t\t\t},\n \t\t\t\t\t\t},\n \t\t\t\t\t\tundefined,\n@@ -383,7 +512,8 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\tconst calculation = createPlanningCalculation({\n \t\t\t\t...submitted,\n \t\t\t\tprogress: (stage) => {\n-\t\t\t\t\tif (cancelled && stage === 'non-working-day-gain') calculation.cancel();\n+\t\t\t\t\tif (cancelled && stage === 'optimization:default-non-working-day-gain')\n+\t\t\t\t\t\tcalculation.cancel();\n \t\t\t\t},\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n@@ -546,26 +676,30 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\thorizon: { start: '2024-01-01', end: '2025-01-01' },\n \t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-12-31' }],\n \t\t\trules: [\n-\t\t\t\t{\n-\t\t\t\t\tid: 'fixed',\n-\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\tstartDate: '2024-01-02',\n-\t\t\t\t\tendDate: '2024-01-02',\n-\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t},\n+\t\t\t\tpresets[0],\n+\t\t\t\t...[\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'fixed',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tstartDate: '2024-01-02',\n+\t\t\t\t\t\tendDate: '2024-01-02',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\t...presets.slice(1),\n \t\t\t],\n \t\t\tprogress: (stage) => {\n-\t\t\t\tif (stage === 'non-working-day-gain') calculation.cancel();\n+\t\t\t\tif (stage === 'optimization:default-non-working-day-gain') calculation.cancel();\n \t\t\t},\n \t\t});\n \t\tconst outcome = await calculation.outcome;\n \t\texpect(outcome.kind).toBe('PlanningIncomplete');\n \t\tif (outcome.kind !== 'PlanningIncomplete') return;\n \t\texpect(outcome.reasons[0].code).toBe('user-cancelled');\n-\t\texpect(outcome.completedStages).toContain('holiday-week-value');\n-\t\texpect(outcome.completedStages).not.toContain('non-working-day-gain');\n+\t\texpect(outcome.completedStages).toContain('optimization:default-holiday-week-value');\n+\t\texpect(outcome.completedStages).not.toContain('optimization:default-non-working-day-gain');\n \t\tconst incumbent = outcome.incumbent!;\n \t\texpect(incumbent.placements).toHaveLength(3);\n \t\texpect(incumbent.placements).toContainEqual({\n@@ -585,9 +719,11 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\tconst trace = await calculation.trace;\n \t\texpect(trace?.status).toBe('incomplete');\n \t\texpect(trace?.error?.code).toBe('user-cancelled');\n-\t\texpect(trace?.phases.find((phase) => phase.name === 'non-working-day-gain')?.status).toBe(\n-\t\t\t'interrupted',\n-\t\t);\n+\t\texpect(\n+\t\t\ttrace?.phases.find(\n+\t\t\t\t(phase) => phase.name === 'optimization:default-non-working-day-gain',\n+\t\t\t)?.status,\n+\t\t).toBe('interrupted');\n \t\tconst frozenOutcome = structuredClone(outcome);\n \t\tcalculation.cancel();\n \t\texpect(await calculation.outcome).toEqual(frozenOutcome);\n@@ -605,7 +741,7 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\t\t\texpiryDate: '2026-12-24',\n \t\t\t\t},\n \t\t\t],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t};\n \t\tconst { calculatePlanningInternal } = await import('./leave-planner.core');\n \t\tconst expected = calculatePlanningInternal(submitted);\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner.worker.spec.ts", "project_id": 35, "relative_order": 29, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,480 @@\n+import { describe, expect, it } from 'vitest';\n+import {\n+\tcalculatePlanningInternal,\n+\ttype PlanningArtifacts,\n+\ttype PlanningRequest,\n+} from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+import { createOptimizationPresetRules } from './rule-service';\n+\n+const presets = createOptimizationPresetRules();\n+const composedRequest: PlanningRequest & { calculationDate: string } = {\n+\tcalculationDate: '2024-04-01',\n+\thorizon: { start: '2024-05-06', end: '2024-05-18' },\n+\tbalances: [\n+\t\t{\n+\t\t\tid: 'cp',\n+\t\t\ttype: 'cp',\n+\t\t\tquantity: 3,\n+\t\t\tavailableFrom: '2024-05-06',\n+\t\t\texpiryDate: '2024-05-17',\n+\t\t},\n+\t],\n+\trules: presets,\n+};\n+\n+describe('integrated optimization and earned leave', () => {\n+\tit.each(presets)(\n+\t\t'makes disabled $name identical to its absence in the complete configuration',\n+\t\t(disabled) => {\n+\t\t\tconst absent = calculatePlanningInternal({\n+\t\t\t\t...composedRequest,\n+\t\t\t\trules: presets.filter(({ id }) => id !== disabled.id),\n+\t\t\t});\n+\t\t\tconst inactive = calculatePlanningInternal({\n+\t\t\t\t...composedRequest,\n+\t\t\t\trules: presets.map((rule) =>\n+\t\t\t\t\trule.id === disabled.id ? { ...rule, enabled: false } : rule,\n+\t\t\t\t),\n+\t\t\t});\n+\t\t\texpect(absent.kind).toBe('Plan');\n+\t\t\texpect(inactive).toEqual(absent);\n+\t\t},\n+\t);\n+\n+\tit('runs the complete configuration once after the sole obligation state and records exact reused evaluations', () => {\n+\t\tlet artifacts: PlanningArtifacts = {};\n+\t\tconst outcome = calculatePlanningInternal(\n+\t\t\tcomposedRequest,\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\texpect(outcome).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [{ date: '2024-05-06' }, { date: '2024-05-07' }, { date: '2024-05-10' }],\n+\t\t\tmetrics: { unplacedAtRisk: 0, holidayWeekValue: 5, nonWorkingDayGain: 6 },\n+\t\t});\n+\t\tconst trace = artifacts.trace;\n+\t\texpect(trace?.status).toBe('ready');\n+\t\texpect(\n+\t\t\ttrace?.phases\n+\t\t\t\t.find(({ name }) => name === 'obligations')\n+\t\t\t\t?.decisions.flatMap(({ candidates }) => candidates)\n+\t\t\t\t.some(({ comparison }) => comparison),\n+\t\t).toBe(false);\n+\t\texpect(\n+\t\t\ttrace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t.some(({ reason }) => reason?.code === 'unchanged-rule-state'),\n+\t\t).toBe(true);\n+\t\texpect(\n+\t\t\ttrace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t.some(\n+\t\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\t\tstatus === 'not-examined' && reason?.code === 'unchanged-generic-state',\n+\t\t\t\t),\n+\t\t).toBe(true);\n+\t\tif (artifacts.explanation?.kind !== 'PlanExplanation')\n+\t\t\tthrow new Error('Expected an explanation.');\n+\t\texpect(\n+\t\t\tartifacts.explanation.placements[0].objectiveVector.objectives.map(({ id }) => id),\n+\t\t).toEqual([\n+\t\t\t'obligation-validity',\n+\t\t\t'optimization:default-unplaced-at-risk',\n+\t\t\t'optimization:default-holiday-week-value',\n+\t\t\t'optimization:default-non-working-day-gain',\n+\t\t\t'optimization:default-longest-work-sequence',\n+\t\t\t'optimization:default-short-sequence-deficit',\n+\t\t\t'optimization:default-supporting-placements',\n+\t\t\t'balance-expiry',\n+\t\t\t'placement-date',\n+\t\t]);\n+\t});\n+\n+\tit('preserves the first equivalent funder while evaluating typed window alternatives', () => {\n+\t\tlet artifacts: PlanningArtifacts = {};\n+\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\t...composedRequest,\n+\t\t\t\tbalances: ['first-cp', 'second-cp', 'rtt'].map((id) => ({\n+\t\t\t\t\tid,\n+\t\t\t\t\ttype: id === 'rtt' ? 'rtt' : 'cp',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2024-05-06',\n+\t\t\t\t\texpiryDate: '2024-05-17',\n+\t\t\t\t})),\n+\t\t\t\trules: [\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'typed-window',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tstartDate: '2024-05-07',\n+\t\t\t\t\t\tendDate: '2024-05-07',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t\t...presets.slice(1),\n+\t\t\t\t],\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\texpect(outcome).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [\n+\t\t\t\t{ date: '2024-05-06', balanceId: 'second-cp' },\n+\t\t\t\t{ date: '2024-05-07', balanceId: 'rtt' },\n+\t\t\t\t{ date: '2024-05-10', balanceId: 'first-cp' },\n+\t\t\t],\n+\t\t\tpreferences: [{ ruleId: 'typed-window', satisfied: 1 }],\n+\t\t\tmetrics: { unplacedAtRisk: 0, holidayWeekValue: 5, nonWorkingDayGain: 6 },\n+\t\t});\n+\t\tconst candidates = artifacts.trace?.phases\n+\t\t\t.find(({ name }) => name === `optimization:${presets[0].id}`)\n+\t\t\t?.decisions.flatMap(({ candidates }) => candidates);\n+\t\tconst skipped = candidates?.filter(\n+\t\t\t({ reason }) => reason?.code === 'equivalent-date-funding',\n+\t\t);\n+\t\texpect(skipped?.length).toBeGreaterThan(0);\n+\t\texpect(\n+\t\t\tskipped?.every(({ status, comparison }) => status === 'not-examined' && !comparison),\n+\t\t).toBe(true);\n+\t\texpect(\n+\t\t\tskipped?.some(\n+\t\t\t\t({ date, placement }) => date === '2024-05-07' && placement?.balanceId === 'rtt',\n+\t\t\t),\n+\t\t).toBe(false);\n+\t\texpect(\n+\t\t\tcandidates?.some(\n+\t\t\t\t({ date, placement, comparison }) =>\n+\t\t\t\t\tdate === '2024-05-07' && placement?.balanceId === 'rtt' && comparison,\n+\t\t\t),\n+\t\t).toBe(true);\n+\t});\n+\n+\tit.each(['maximum', 'unsafe-total'] as const)(\n+\t\t'keeps distinct funding evaluations when equivalence cannot be proved (%s)',\n+\t\t(control) => {\n+\t\t\tlet artifacts: PlanningArtifacts = {};\n+\t\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t\t{\n+\t\t\t\t\tcalculationDate: '2024-01-01',\n+\t\t\t\t\thorizon: { start: '2024-01-02', end: '2024-01-03' },\n+\t\t\t\t\tbalances: [\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'first',\n+\t\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\t\tquantity: control === 'maximum' ? 1 : Number.MAX_SAFE_INTEGER,\n+\t\t\t\t\t\t\texpiryDate: '2024-01-02',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'second',\n+\t\t\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\t\t\tquantity: control === 'maximum' ? 2 : 1,\n+\t\t\t\t\t\t\texpiryDate: '2024-01-02',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\trules: [\n+\t\t\t\t\t\tpresets[0],\n+\t\t\t\t\t\t...(control === 'maximum'\n+\t\t\t\t\t\t\t? [\n+\t\t\t\t\t\t\t\t\t{\n+\t\t\t\t\t\t\t\t\t\tid: 'largest-balance',\n+\t\t\t\t\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t\t\t\t\t\t...OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t\t\t\t\t\t\t\t\t\taggregation: 'maximum',\n+\t\t\t\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\t\t]\n+\t\t\t\t\t\t\t: []),\n+\t\t\t\t\t],\n+\t\t\t\t},\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\texpect(outcome).toMatchObject({\n+\t\t\t\tkind: 'Plan',\n+\t\t\t\tplacements: [{ balanceId: control === 'maximum' ? 'second' : 'first' }],\n+\t\t\t});\n+\t\t\tconst candidates = artifacts.trace?.phases\n+\t\t\t\t.find(({ name }) => name === `optimization:${presets[0].id}`)\n+\t\t\t\t?.decisions.flatMap(({ candidates }) => candidates);\n+\t\t\texpect(\n+\t\t\t\tcandidates?.some(({ reason }) => reason?.code === 'equivalent-date-funding'),\n+\t\t\t).toBe(false);\n+\t\t\tfor (const balanceId of ['first', 'second'])\n+\t\t\t\texpect(\n+\t\t\t\t\tcandidates?.some(\n+\t\t\t\t\t\t({ placement, comparison }) =>\n+\t\t\t\t\t\t\tplacement?.balanceId === balanceId && comparison,\n+\t\t\t\t\t),\n+\t\t\t\t).toBe(true);\n+\t\t},\n+\t);\n+\n+\tit('finishes a renamed first quantity rule at zero and still evaluates later priorities and final ties', () => {\n+\t\tconst loss = { ...presets[0], id: 'personal-quantity', name: 'Personal quantity' };\n+\t\tconst run = (rules: PlanningRequest['rules']) => {\n+\t\t\tlet artifacts: PlanningArtifacts = {};\n+\t\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t\t{ ...composedRequest, rules },\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\treturn { outcome, trace: artifacts.trace };\n+\t\t};\n+\t\tconst window = {\n+\t\t\tid: 'already-satisfied',\n+\t\t\ttype: 'time_window',\n+\t\t\tstartDate: '2024-05-06',\n+\t\t\tendDate: '2024-05-06',\n+\t\t\tplaceDays: 1,\n+\t\t\tplaceType: 'cp',\n+\t\t};\n+\t\tconst first = run([loss, window, ...presets.slice(1)]);\n+\t\texpect(first.outcome).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [{ date: '2024-05-06' }, { date: '2024-05-07' }, { date: '2024-05-10' }],\n+\t\t\tmetrics: { unplacedAtRisk: 0, holidayWeekValue: 5, nonWorkingDayGain: 6 },\n+\t\t});\n+\t\tconst stopped = first.trace?.phases\n+\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t.filter(({ reason }) => reason?.code === 'quantity-prefix-lower-bound');\n+\t\texpect(stopped?.length).toBeGreaterThan(0);\n+\t\texpect(\n+\t\t\tstopped?.every(\n+\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\tstatus === 'not-examined' && reason?.ruleIds?.includes(loss.id),\n+\t\t\t),\n+\t\t).toBe(true);\n+\t\texpect(\n+\t\t\tfirst.trace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t.some(\n+\t\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\t\tstatus === 'not-examined' &&\n+\t\t\t\t\t\treason?.code === 'satisfied-window-prefix-bound' &&\n+\t\t\t\t\t\treason.ruleIds?.includes(window.id),\n+\t\t\t\t),\n+\t\t).toBe(true);\n+\t\tconst expiry = first.trace?.phases.find(({ name }) => name === 'expiry');\n+\t\texpect(expiry?.completed).toBe(true);\n+\t\texpect(\n+\t\t\texpiry?.decisions.some(({ candidates }) =>\n+\t\t\t\tcandidates.some(({ comparison }) => comparison),\n+\t\t\t),\n+\t\t).toBe(true);\n+\t\tconst reordered = run([presets[1], loss, ...presets.slice(2)]);\n+\t\texpect(reordered.outcome.kind).toBe('Plan');\n+\t\texpect(\n+\t\t\treordered.trace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t.some(({ reason }) => reason?.code === 'quantity-prefix-lower-bound'),\n+\t\t).toBe(false);\n+\t});\n+\n+\tit.each(['sum', 'count', 'maximum'] as const)(\n+\t\t'finishes a configured maximize holiday prefix at its evaluator bound (%s)',\n+\t\t(aggregation) => {\n+\t\t\tconst holiday = {\n+\t\t\t\t...presets[1],\n+\t\t\t\tid: 'personal-holiday',\n+\t\t\t\tconfiguration: { ...OPTIMIZATION_PRESETS.holidayWeekValue, aggregation },\n+\t\t\t};\n+\t\t\tlet artifacts: PlanningArtifacts = {};\n+\t\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t\t{ ...composedRequest, rules: [presets[0], holiday, ...presets.slice(2)] },\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\texpect(outcome).toMatchObject({\n+\t\t\t\tkind: 'Plan',\n+\t\t\t\tplacements: [\n+\t\t\t\t\t{ date: '2024-05-06' },\n+\t\t\t\t\t{ date: '2024-05-07' },\n+\t\t\t\t\t{ date: '2024-05-10' },\n+\t\t\t\t],\n+\t\t\t\tmetrics: { unplacedAtRisk: 0, holidayWeekValue: 5, nonWorkingDayGain: 6 },\n+\t\t\t});\n+\t\t\texpect(\n+\t\t\t\tartifacts.trace?.phases\n+\t\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t\t.some(\n+\t\t\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\t\t\tstatus === 'not-examined' &&\n+\t\t\t\t\t\t\treason?.code === 'satisfied-holiday-prefix-bound' &&\n+\t\t\t\t\t\t\treason.ruleIds?.includes(holiday.id),\n+\t\t\t\t\t),\n+\t\t\t).toBe(true);\n+\t\t\tconst final = artifacts.trace?.phases.find(({ name }) => name === 'expiry');\n+\t\t\texpect(final?.completed).toBe(true);\n+\t\t\texpect(\n+\t\t\t\tfinal?.decisions.some(({ candidates }) =>\n+\t\t\t\t\tcandidates.some(({ comparison }) => comparison),\n+\t\t\t\t),\n+\t\t\t).toBe(true);\n+\t\t},\n+\t);\n+\n+\tit('commits a strict holiday bundle before deferring old generic alternatives and preserves higher rules', () => {\n+\t\tlet artifacts: PlanningArtifacts = {};\n+\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\tcalculationDate: '2026-11-01',\n+\t\t\t\thorizon: { start: '2026-11-02', end: '2026-11-14' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2026-11-30' }],\n+\t\t\t\tdeclaredDays: ['2026-11-09', '2026-11-10'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'mandatory',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tstartDate: '2026-11-02',\n+\t\t\t\t\t\tendDate: '2026-11-02',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'earlier-window',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tstartDate: '2026-11-02',\n+\t\t\t\t\t\tendDate: '2026-11-02',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t\t...presets.slice(1),\n+\t\t\t\t],\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\texpect(outcome).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [{ date: '2026-11-02' }, { date: '2026-11-12' }, { date: '2026-11-13' }],\n+\t\t\tpreferences: [{ ruleId: 'earlier-window', satisfied: 1 }],\n+\t\t\tmetrics: { unplacedAtRisk: 0, holidayWeekValue: 3 },\n+\t\t});\n+\t\tconst holiday = artifacts.trace?.phases.find(\n+\t\t\t({ name }) => name === `optimization:${presets[1].id}`,\n+\t\t);\n+\t\tconst decisions = holiday?.decisions.flatMap(({ candidates }) => candidates);\n+\t\texpect(\n+\t\t\tdecisions?.some(\n+\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\tstatus === 'not-examined' && reason?.code === 'strict-prefix-bundle-progress',\n+\t\t\t),\n+\t\t).toBe(true);\n+\t\texpect(decisions?.some(({ status, comparison }) => status === 'chosen' && comparison)).toBe(\n+\t\t\ttrue,\n+\t\t);\n+\t\tconst final = artifacts.trace?.phases.find(({ name }) => name === 'expiry');\n+\t\texpect(final?.completed).toBe(true);\n+\t\texpect(\n+\t\t\tfinal?.decisions.some(({ candidates }) =>\n+\t\t\t\tcandidates.some(({ comparison }) => comparison),\n+\t\t\t),\n+\t\t).toBe(true);\n+\t});\n+\n+\tit.each([false, true])(\n+\t\t'earns an already-complete preference occurrence before comparisons (minimize every balance: %s)',\n+\t\t(minimizeEveryBalance) => {\n+\t\t\tconst request: PlanningRequest & { calculationDate: string } = {\n+\t\t\t\tcalculationDate: '2026-11-01',\n+\t\t\t\thorizon: { start: '2026-11-09', end: '2026-11-14' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2027-01-01' }],\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'mandatory',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tstartDate: '2026-11-12',\n+\t\t\t\t\t\tendDate: '2026-11-12',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t\t...(minimizeEveryBalance\n+\t\t\t\t\t\t? [\n+\t\t\t\t\t\t\t\t{\n+\t\t\t\t\t\t\t\t\tid: 'all-balances',\n+\t\t\t\t\t\t\t\t\ttype: 'optimization' as const,\n+\t\t\t\t\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t\t\t\t\t...OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t\t\t\t\t\t\t\t\tconditions: [],\n+\t\t\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\t]\n+\t\t\t\t\t\t: []),\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\trewardType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t};\n+\t\t\tlet artifacts: PlanningArtifacts = {};\n+\t\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t\trequest,\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\texpect(outcome).toMatchObject({\n+\t\t\t\tkind: 'Plan',\n+\t\t\t\tplacements: [\n+\t\t\t\t\t{ date: '2026-11-12', type: 'cp', ruleIds: ['mandatory', 'producer'] },\n+\t\t\t\t],\n+\t\t\t\tpreferences: [{ ruleId: 'producer', satisfied: 1 }],\n+\t\t\t\tremainingBalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'earned:producer:2026-11-11',\n+\t\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2026-11-13',\n+\t\t\t\t\t\texpiryDate: '2027-11-13',\n+\t\t\t\t\t\tsourceRuleId: 'producer',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t});\n+\t\t\texpect(artifacts.finalState?.earnedActivations).toEqual([\n+\t\t\t\t{\n+\t\t\t\t\tid: 'earned:producer:2026-11-11',\n+\t\t\t\t\truleId: 'producer',\n+\t\t\t\t\toccurrence: '2026-11-11',\n+\t\t\t\t\tdates: ['2026-11-12'],\n+\t\t\t\t},\n+\t\t\t]);\n+\t\t\tif (artifacts.explanation?.kind !== 'PlanExplanation')\n+\t\t\t\tthrow new Error('Expected an explanation.');\n+\t\t\texpect(artifacts.explanation.placements[0].contributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({ kind: 'rule', ruleId: 'producer' }),\n+\t\t\t);\n+\t\t\texpect(artifacts.explanation.ifThenContributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\truleId: 'producer',\n+\t\t\t\t\tearnedEntitlement: {\n+\t\t\t\t\t\tid: 'earned:producer:2026-11-11',\n+\t\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2026-11-13',\n+\t\t\t\t\t\texpiryDate: '2027-11-13',\n+\t\t\t\t\t\tadded: true,\n+\t\t\t\t\t},\n+\t\t\t\t}),\n+\t\t\t);\n+\t\t\tif (minimizeEveryBalance)\n+\t\t\t\texpect(\n+\t\t\t\t\tartifacts.explanation.placements[0].objectiveVector.objectives,\n+\t\t\t\t).toContainEqual(\n+\t\t\t\t\texpect.objectContaining({ id: 'optimization:all-balances', value: 1 }),\n+\t\t\t\t);\n+\t\t},\n+\t);\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/services/optimization-integration.spec.ts", "project_id": 35, "relative_order": 30, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,508 @@\n+import { vi } from 'vitest';\n+import { calculatePlanningInternal } from './leave-planner.core';\n+import { createPlanningCalculation } from './leave-planner.service';\n+import type { PlanningRequest } from './leave-planner.service';\n+import { OPTIMIZATION_PRESETS, type OptimizationConfiguration } from './planning-objectives';\n+\n+const loss = {\n+\tid: 'loss',\n+\tname: 'Prevent losses',\n+\ttype: 'optimization' as const,\n+\tforce: 'preference' as const,\n+\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+};\n+const personal = {\n+\tid: 'personal',\n+\tname: 'Personal CP day',\n+\ttype: 'time_window' as const,\n+\tforce: 'preference' as const,\n+\tstartDate: '2024-01-02',\n+\tendDate: '2024-01-02',\n+\tplaceDays: 1,\n+\tplaceType: 'cp' as const,\n+};\n+const concurrent: PlanningRequest = {\n+\thorizon: { start: '2024-01-02', end: '2024-01-03' },\n+\tbalances: [\n+\t\t{ id: 'risk-rtt', type: 'rtt', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t{ id: 'deferred-cp', type: 'cp', quantity: 1, expiryDate: '2024-02-01' },\n+\t],\n+\trules: [],\n+};\n+\n+describe('explicit active planning objectives', () => {\n+\tbeforeEach(() => {\n+\t\tvi.setSystemTime(new Date('2024-01-01T12:00:00Z'));\n+\t\tvi.stubGlobal('window', undefined);\n+\t});\n+\tafterEach(() => {\n+\t\tvi.useRealTimers();\n+\t\tvi.unstubAllGlobals();\n+\t});\n+\n+\tit('rejects a sparse selector list consistently at direct and calculation boundaries', async () => {\n+\t\tconst request = {\n+\t\t\t...concurrent,\n+\t\t\trules: [\n+\t\t\t\t{ ...loss, configuration: { ...loss.configuration, conditions: new Array(1) } },\n+\t\t\t],\n+\t\t};\n+\t\tconst direct = calculatePlanningInternal(request);\n+\t\tconst calculation = await createPlanningCalculation(request).outcome;\n+\t\tfor (const result of [direct, calculation])\n+\t\t\texpect(result).toMatchObject({\n+\t\t\t\tkind: 'InvalidInput',\n+\t\t\t\treasons: [{ code: 'invalid-optimization-configuration', ruleIds: ['loss'] }],\n+\t\t\t});\n+\t});\n+\n+\tit('adds no leave without active rules and retains declared days', async () => {\n+\t\tconst calculation = createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-05' },\n+\t\t\tbalances: [{ id: 'rtt', type: 'rtt', quantity: 2, expiryDate: '2024-01-04' }],\n+\t\t\trules: [],\n+\t\t\tdeclaredDays: [{ date: '2024-01-03', type: 'other' }],\n+\t\t});\n+\t\tconst outcome = await calculation.outcome;\n+\t\texpect(outcome.kind).toBe('Plan');\n+\t\tif (outcome.kind !== 'Plan') return;\n+\t\texpect(outcome.placements).toEqual([]);\n+\t\texpect(outcome.declaredDays).toEqual([{ date: '2024-01-03', type: 'other' }]);\n+\t\texpect(outcome.remainingBalances[0].quantity).toBe(2);\n+\t\texpect(outcome.remainingBalances[0]).toMatchObject({\n+\t\t\tclassification: 'at-risk',\n+\t\t\treason: { code: 'active-priorities' },\n+\t\t});\n+\t});\n+\n+\tit.each([\n+\t\t['z-early', 'a-later'],\n+\t\t['a-early', 'z-later'],\n+\t])(\n+\t\t'compares equal expirations before dates without preferring balance identity %s',\n+\t\t(earlyId, laterId) => {\n+\t\t\tconst result = calculatePlanningInternal({\n+\t\t\t\thorizon: { start: '2024-01-09', end: '2024-01-13' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: earlyId,\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2024-01-09',\n+\t\t\t\t\t\texpiryDate: '2024-02-01',\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: laterId,\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2024-01-10',\n+\t\t\t\t\t\texpiryDate: '2024-02-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules: [{ ...personal, startDate: '2024-01-09', endDate: '2024-01-12' }],\n+\t\t\t});\n+\t\t\texpect(result).toMatchObject({\n+\t\t\t\tkind: 'Plan',\n+\t\t\t\tplacements: [{ date: '2024-01-09', balanceId: earlyId }],\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit('follows the displayed order when loss prevention competes with a personal preference', async () => {\n+\t\tconst first = await createPlanningCalculation({ ...concurrent, rules: [loss, personal] })\n+\t\t\t.outcome;\n+\t\tconst second = await createPlanningCalculation({ ...concurrent, rules: [personal, loss] })\n+\t\t\t.outcome;\n+\t\tif (first.kind !== 'Plan' || second.kind !== 'Plan')\n+\t\t\tthrow new Error('Expected valid plans');\n+\t\texpect(first.placements.map((placement) => placement.balanceId)).toEqual(['risk-rtt']);\n+\t\texpect(first.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(first.preferences[0].satisfied).toBe(0);\n+\t\texpect(second.placements.map((placement) => placement.balanceId)).toEqual(['deferred-cp']);\n+\t\texpect(second.metrics.unplacedAtRisk).toBe(1);\n+\t\texpect(second.preferences[0].satisfied).toBe(1);\n+\t});\n+\n+\tit('keeps typed obligations valid when an optimization would prefer another balance', async () => {\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\t...concurrent,\n+\t\t\trules: [{ ...personal, force: 'obligation' }, loss],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.placements[0]).toMatchObject({\n+\t\t\ttype: 'cp',\n+\t\t\tbalanceId: 'deferred-cp',\n+\t\t\truleIds: ['personal'],\n+\t\t});\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(1);\n+\t});\n+\n+\tit('preserves scarce expiry dates before a lower personal preference', async () => {\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-04' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2024-01-03' },\n+\t\t\t\t{ id: 'rtt', type: 'rtt', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t\t],\n+\t\t\trules: [loss, personal],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(outcome.placements.map(({ date, type }) => ({ date, type }))).toEqual([\n+\t\t\t{ date: '2024-01-02', type: 'rtt' },\n+\t\t\t{ date: '2024-01-03', type: 'cp' },\n+\t\t]);\n+\t\texpect(outcome.preferences[0].satisfied).toBe(0);\n+\t});\n+\n+\tit('can relocate a short chain before adding a balance with a scarce date', async () => {\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-05' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2024-01-03' },\n+\t\t\t\t{\n+\t\t\t\t\tid: 'flexible',\n+\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2024-01-03',\n+\t\t\t\t\texpiryDate: '2024-01-04',\n+\t\t\t\t},\n+\t\t\t\t{ id: 'scarce', type: 'rtt', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t\t],\n+\t\t\trules: [loss, personal],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(outcome.placements.map(({ date, balanceId }) => ({ date, balanceId }))).toEqual([\n+\t\t\t{ date: '2024-01-02', balanceId: 'scarce' },\n+\t\t\t{ date: '2024-01-03', balanceId: 'cp' },\n+\t\t\t{ date: '2024-01-04', balanceId: 'flexible' },\n+\t\t]);\n+\t});\n+\n+\tit.each(['2024-01-23', '2024-01-24'])(\n+\t\t'finishes oversubscribed balances without an eligible free endpoint through %s',\n+\t\tasync (end) => {\n+\t\t\tconst outcome = await createPlanningCalculation({\n+\t\t\t\tdeadlineMs: 500,\n+\t\t\t\thorizon: { start: '2024-01-02', end },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{ id: 'cp', type: 'cp', quantity: 7, expiryDate: '2024-01-22' },\n+\t\t\t\t\t{ id: 'rtt', type: 'rtt', quantity: 8, expiryDate: '2024-01-22' },\n+\t\t\t\t\t{ id: 'other', type: 'other', quantity: 1, expiryDate: '2024-01-22' },\n+\t\t\t\t],\n+\t\t\t\trules: [loss],\n+\t\t\t}).outcome;\n+\t\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a completed valid plan');\n+\t\t\texpect(outcome.placements).toHaveLength(15);\n+\t\t\texpect(outcome.metrics.unplacedAtRisk).toBe(1);\n+\t\t},\n+\t);\n+\n+\tit('relocates repeated balance tokens across mandatory windows as a complete chain', async () => {\n+\t\tconst windows = [\n+\t\t\t['cp-first', 'cp', '2024-01-02', '2024-01-03'],\n+\t\t\t['rtt-middle', 'rtt', '2024-01-03', '2024-01-04'],\n+\t\t\t['cp-last', 'cp', '2024-01-04', '2024-01-05'],\n+\t\t].map(([id, placeType, startDate, endDate]) => ({\n+\t\t\tid,\n+\t\t\ttype: 'time_window' as const,\n+\t\t\tforce: 'obligation' as const,\n+\t\t\tplaceType,\n+\t\t\tplaceDays: 1,\n+\t\t\tstartDate,\n+\t\t\tendDate,\n+\t\t}));\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-06' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-01-05' },\n+\t\t\t\t{ id: 'rtt', type: 'rtt', quantity: 1, expiryDate: '2024-01-05' },\n+\t\t\t\t{ id: 'scarce', type: 'other', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t\t],\n+\t\t\trules: [...windows, loss],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(outcome.placements.map(({ date, type }) => ({ date, type }))).toEqual([\n+\t\t\t{ date: '2024-01-02', type: 'other' },\n+\t\t\t{ date: '2024-01-03', type: 'cp' },\n+\t\t\t{ date: '2024-01-04', type: 'rtt' },\n+\t\t\t{ date: '2024-01-05', type: 'cp' },\n+\t\t]);\n+\t});\n+\n+\tit('relocates same-balance tokens with different mandatory provenance', async () => {\n+\t\tconst calculation = createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-05' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-01-04' },\n+\t\t\t\t{ id: 'scarce', type: 'other', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t\t],\n+\t\t\trules: [\n+\t\t\t\t{ ...personal, id: 'first', force: 'obligation', endDate: '2024-01-03' },\n+\t\t\t\t{\n+\t\t\t\t\t...personal,\n+\t\t\t\t\tid: 'second',\n+\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\tstartDate: '2024-01-03',\n+\t\t\t\t\tendDate: '2024-01-04',\n+\t\t\t\t},\n+\t\t\t\tloss,\n+\t\t\t],\n+\t\t});\n+\t\tconst outcome = await calculation.outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\tconst trace = await calculation.trace;\n+\t\texpect(\n+\t\t\ttrace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions)\n+\t\t\t\t.flatMap(({ candidates }) => candidates)\n+\t\t\t\t.some(\n+\t\t\t\t\t({ sourceDate, dates }) =>\n+\t\t\t\t\t\tsourceDate === '2024-01-02' &&\n+\t\t\t\t\t\tdates?.join(',') === '2024-01-02,2024-01-03,2024-01-04',\n+\t\t\t\t),\n+\t\t).toBe(true);\n+\t});\n+\n+\tit('satisfies a lower IF_THEN pattern by reassigning its complete typed bundle', async () => {\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\thorizon: { start: '2027-12-20', end: '2027-12-28' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'A-cp', type: 'cp', quantity: 2, expiryDate: '2027-12-27' },\n+\t\t\t\t{ id: 'B-rtt', type: 'rtt', quantity: 4, expiryDate: '2027-12-27' },\n+\t\t\t],\n+\t\t\trules: [\n+\t\t\t\tloss,\n+\t\t\t\t{\n+\t\t\t\t\tid: 'samedi',\n+\t\t\t\t\tname: 'Samedi Malin',\n+\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\tdayOfWeek: 6,\n+\t\t\t\t\tplaceDays: 2,\n+\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\tplacement: 'auto',\n+\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\trewardType: 'other',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(outcome.preferences[0].satisfied).toBe(1);\n+\t\texpect(\n+\t\t\toutcome.placements.filter(({ type }) => type === 'cp').map(({ date }) => date),\n+\t\t).toEqual(['2027-12-23', '2027-12-24']);\n+\t});\n+\n+\tit('does not classify a period extension without a calendar benefit as supporting', async () => {\n+\t\tconst base: PlanningRequest = {\n+\t\t\thorizon: { start: '2026-12-28', end: '2027-01-09' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'rtt', type: 'rtt', quantity: 1, expiryDate: '2027-01-08' },\n+\t\t\t\t{\n+\t\t\t\t\tid: 'cp',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2027-01-05',\n+\t\t\t\t\texpiryDate: '2027-02-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\t...personal,\n+\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\tstartDate: '2027-01-04',\n+\t\t\t\t\tendDate: '2027-01-04',\n+\t\t\t\t\tplaceType: 'rtt',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t};\n+\t\tconst before = await createPlanningCalculation(base).outcome;\n+\t\tconst after = await createPlanningCalculation({\n+\t\t\t...base,\n+\t\t\trules: [\n+\t\t\t\t...base.rules,\n+\t\t\t\t{ ...loss, configuration: { ...loss.configuration, conditions: [] } },\n+\t\t\t],\n+\t\t}).outcome;\n+\t\tif (before.kind !== 'Plan' || after.kind !== 'Plan')\n+\t\t\tthrow new Error('Expected valid plans');\n+\t\texpect(after.placements.find(({ balanceId }) => balanceId === 'cp')).toMatchObject({\n+\t\t\tdate: '2027-01-05',\n+\t\t\tsupporting: false,\n+\t\t});\n+\t\tfor (const key of [\n+\t\t\t'holidayWeekValue',\n+\t\t\t'nonWorkingDayGain',\n+\t\t\t'longestWorkSequence',\n+\t\t\t'shortSequenceDeficit',\n+\t\t] as const)\n+\t\t\texpect(after.metrics[key]).toBe(before.metrics[key]);\n+\t\texpect(after.metrics.supportingPlacements).toBe(0);\n+\t});\n+\n+\tit('keeps joint window obligations and active priority when large previews are sampled', async () => {\n+\t\tconst obligations = [\n+\t\t\t['2024-01-02', '2024-01-15'],\n+\t\t\t['2024-01-16', '2024-01-29'],\n+\t\t\t['2024-02-01', '2024-02-14'],\n+\t\t].map(([startDate, endDate], index) => ({\n+\t\t\tid: `mandatory-${index}`,\n+\t\t\ttype: 'time_window' as const,\n+\t\t\tforce: 'obligation' as const,\n+\t\t\tstartDate,\n+\t\t\tendDate,\n+\t\t\tplaceDays: 2,\n+\t\t\tplaceType: 'any' as const,\n+\t\t}));\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-02-16' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'cp', type: 'cp', quantity: 5, expiryDate: '2024-02-15' },\n+\t\t\t\t{ id: 'scarce', type: 'rtt', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t\t\t{ id: 'deferred', type: 'cp', quantity: 1, expiryDate: '2024-05-01' },\n+\t\t\t],\n+\t\t\trules: [...obligations, loss, personal],\n+\t\t};\n+\t\tconst calculation = createPlanningCalculation(request);\n+\t\tconst outcome = await calculation.outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(outcome.preferences[0].satisfied).toBe(0);\n+\t\tfor (const rule of obligations)\n+\t\t\texpect(\n+\t\t\t\toutcome.placements.filter(({ ruleIds }) => ruleIds.includes(rule.id)),\n+\t\t\t).toHaveLength(2);\n+\t\tconst trace = await calculation.trace;\n+\t\texpect(\n+\t\t\ttrace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions)\n+\t\t\t\t.flatMap(({ candidates }) => candidates)\n+\t\t\t\t.some(\n+\t\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\t\tstatus === 'not-examined' &&\n+\t\t\t\t\t\treason?.code === 'window-obligation-preview-sampling',\n+\t\t\t\t),\n+\t\t).toBe(true);\n+\t\tconst reversed = await createPlanningCalculation({\n+\t\t\t...request,\n+\t\t\trules: [...obligations, personal, loss],\n+\t\t}).outcome;\n+\t\tif (reversed.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(reversed.preferences[0].satisfied).toBe(1);\n+\t\texpect(reversed.metrics.unplacedAtRisk).toBe(1);\n+\t}, 20_000);\n+\n+\tit('allows a lower typed preference to choose the balance when loss quantities tie', async () => {\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\t...concurrent,\n+\t\t\tbalances: concurrent.balances.map((balance) => ({\n+\t\t\t\t...balance,\n+\t\t\t\texpiryDate: '2024-01-02',\n+\t\t\t})),\n+\t\t\trules: [loss, personal],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.placements[0].type).toBe('cp');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(1);\n+\t\texpect(outcome.preferences[0].satisfied).toBe(1);\n+\t});\n+\n+\tit('makes a disabled optimization equivalent to its absence, including all-disabled requests', async () => {\n+\t\tfor (const otherRules of [[], [personal]]) {\n+\t\t\tconst absent = await createPlanningCalculation({ ...concurrent, rules: otherRules })\n+\t\t\t\t.outcome;\n+\t\t\tconst disabled = await createPlanningCalculation({\n+\t\t\t\t...concurrent,\n+\t\t\t\trules: [{ ...loss, enabled: false }, ...otherRules],\n+\t\t\t}).outcome;\n+\t\t\texpect(disabled).toEqual(absent);\n+\t\t}\n+\t});\n+\n+\tit.each([\n+\t\t{ ...OPTIMIZATION_PRESETS.unplacedAtRisk, aggregation: 'average' },\n+\t\t{ ...OPTIMIZATION_PRESETS.unplacedAtRisk, conditions: ['complete'] },\n+\t\tnull,\n+\t])(\n+\t\t'rejects incompatible or malformed active configurations without an obligation conflict: %s',\n+\t\tasync (configuration) => {\n+\t\t\tconst outcome = calculatePlanningInternal({\n+\t\t\t\t...concurrent,\n+\t\t\t\trules: [{ ...loss, configuration }],\n+\t\t\t});\n+\t\t\texpect(outcome.kind).toBe('InvalidInput');\n+\t\t\tif (outcome.kind !== 'InvalidInput') return;\n+\t\t\texpect(outcome.reasons[0].ruleIds).toEqual(['loss']);\n+\t\t\texpect(outcome.reasons[0].code).toMatch(\n+\t\t\t\t/^(invalid|unsupported)-optimization-configuration$/,\n+\t\t\t);\n+\t\t},\n+\t);\n+\n+\tit('rejects obligation mode for an optimization and ignores a malformed disabled rule', async () => {\n+\t\tconst invalid = calculatePlanningInternal({\n+\t\t\t...concurrent,\n+\t\t\trules: [{ ...loss, force: 'obligation' }],\n+\t\t});\n+\t\texpect(invalid).toMatchObject({\n+\t\t\tkind: 'InvalidInput',\n+\t\t\treasons: [expect.objectContaining({ code: 'rule-force', ruleIds: ['loss'] })],\n+\t\t});\n+\t\tconst disabled = calculatePlanningInternal({\n+\t\t\t...concurrent,\n+\t\t\trules: [{ ...loss, enabled: false, configuration: null }],\n+\t\t});\n+\t\texpect(disabled).toMatchObject({ kind: 'Plan', placements: [] });\n+\t});\n+\n+\tit('keeps direct snapshots and every explanation/comparison in the submitted active order', async () => {\n+\t\tconst configuration: OptimizationConfiguration = structuredClone(\n+\t\t\tOPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t);\n+\t\tconst rule = { ...loss, configuration };\n+\t\tconst calculation = createPlanningCalculation({ ...concurrent, rules: [rule, personal] });\n+\t\tconfiguration.conditions = [];\n+\t\tconfiguration.aggregation = 'count';\n+\t\tconfiguration.direction = 'maximize';\n+\t\trule.name = 'Edited later';\n+\t\tconst outcome = await calculation.outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a plan');\n+\t\texpect(outcome.placements[0].balanceId).toBe('risk-rtt');\n+\t\texpect(calculation.snapshot.rules[0]).toMatchObject({\n+\t\t\tname: 'Prevent losses',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t});\n+\t\texpect(Object.isFrozen(calculation.snapshot.rules[0])).toBe(true);\n+\t\tconst explanation = await calculation.explanation;\n+\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\tconst ids = [\n+\t\t\t'obligation-validity',\n+\t\t\t'optimization:loss',\n+\t\t\t'preference:personal',\n+\t\t\t'balance-expiry',\n+\t\t\t'placement-date',\n+\t\t];\n+\t\texpect(\n+\t\t\texplanation.placements[0].objectiveVector.objectives.map((objective) => objective.id),\n+\t\t).toEqual(ids);\n+\t\texpect(explanation.placements[0].objectiveVector.objectives[1].label).toBe(\n+\t\t\t'Prevent losses',\n+\t\t);\n+\t\tconst trace = await calculation.trace;\n+\t\texpect(trace?.phases.map((phase) => phase.name)).toEqual([\n+\t\t\t'validation',\n+\t\t\t'obligations',\n+\t\t\t'optimization:loss',\n+\t\t\t'preference:personal',\n+\t\t\t'expiry',\n+\t\t\t'dates',\n+\t\t]);\n+\t\tconst comparison = await calculation.analyzeCounterfactual(outcome.placements[0]);\n+\t\tif (comparison.kind !== 'Counterfactual') throw new Error('Expected comparison');\n+\t\texpect(comparison.baseline.objectives.map((objective) => objective.id)).toEqual(ids);\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/services/optimization-rule.spec.ts", "project_id": 35, "relative_order": 31, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -5,11 +5,12 @@ import { RuleService, RuleType } from './rule-service';\n import { UserInputService } from './user-input-service';\n import { createPlanningCalculation } from './leave-planner.service';\n import { PlanningDurationService } from './planning-duration.service';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n \n describe('Planning duration estimate', () => {\n \tbeforeEach(() => {\n \t\tlocalStorage.clear();\n-\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\tTestBed.inject(CalendarSettingsService).setPlanningDates('2024-01-01', '2024-12-31');\n \t\tTestBed.inject(UserInputService).updateBalances(() => [\n \t\t\t{\n@@ -34,6 +35,22 @@ describe('Planning duration estimate', () => {\n \t\texpect(TestBed.inject(RuleService).rules).toEqual([]);\n \t});\n \n+\tit('estimates and calibrates optimization rules without a requested leave quantity', () => {\n+\t\tconst rules = TestBed.inject(RuleService);\n+\t\trules.addRule({\n+\t\t\tid: 'loss',\n+\t\t\tname: 'Loss',\n+\t\t\ttype: RuleType.OPTIMIZATION,\n+\t\t\tenabled: true,\n+\t\t\tforce: 'preference',\n+\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),\n+\t\t});\n+\t\tconst duration = TestBed.inject(PlanningDurationService);\n+\t\texpect(Number.isFinite(duration.estimate()!.maximum)).toBe(true);\n+\t\tduration.recordCompletion(duration.request()!, 20_000);\n+\t\texpect(duration.estimate()).toEqual({ minimum: 10, maximum: 60, unit: 'seconds' });\n+\t});\n+\n \tit('updates for dates, balances and active rules without requesting a calculation', () => {\n \t\tconst duration = TestBed.inject(PlanningDurationService);\n \t\tconst settings = TestBed.inject(CalendarSettingsService);\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/planning-duration.service.spec.ts", "project_id": 35, "relative_order": 32, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -41,7 +41,9 @@ function initialDurationMs(request: PlanningRequest): number {\n \t\t\t(dateTime(rule.startDate) >= end || dateTime(rule.endDate) < start)\n \t\t)\n \t\t\tcontinue;\n-\t\truleWeight += (rule.force === 'obligation' ? 0.5 : 0.15) * Math.max(1, rule.placeDays / 3);\n+\t\truleWeight +=\n+\t\t\t(rule.force === 'obligation' ? 0.5 : 0.15) *\n+\t\t\tMath.max(1, 'placeDays' in rule ? rule.placeDays / 3 : 1);\n \t\tif ('rewardDays' in rule) placements += (Math.max(0, rule.rewardDays) * days) / 365.25;\n \t}\n \t// Rough prior from the browser references in docs/planning-duration.md, not a deadline.\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/planning-duration.service.ts", "project_id": 35, "relative_order": 33, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,193 @@\n+import { describe, expect, it } from 'vitest';\n+import {\n+\tcompareObjectiveLists,\n+\tcompareObjectiveValues,\n+\tevaluateOptimization,\n+\tfirstDifferentObjective,\n+\tOPTIMIZATION_PRESETS,\n+\toptimizationUnit,\n+\tvalidateOptimizationConfiguration,\n+\ttype OptimizationObservations,\n+} from './planning-objectives';\n+\n+const empty: OptimizationObservations = {\n+\tleaveBalances: [],\n+\tpublicHolidayWeeks: [],\n+\ttimeOffPeriods: [],\n+\tworkSequences: [],\n+\tleavePlacements: [],\n+};\n+\n+describe('composable planning objectives', () => {\n+\tit('evaluates each internal non-empty sequence with its own working-day threshold', () => {\n+\t\tconst observations: OptimizationObservations = {\n+\t\t\t...empty,\n+\t\t\tworkSequences: [\n+\t\t\t\t{ length: 1, internal: false },\n+\t\t\t\t{ length: 0, internal: true },\n+\t\t\t\t{ length: 1, internal: true },\n+\t\t\t\t{ length: 4, internal: true },\n+\t\t\t\t{ length: 6, internal: false },\n+\t\t\t],\n+\t\t};\n+\t\texpect(evaluateOptimization(OPTIMIZATION_PRESETS.shortSequenceDeficit, observations)).toBe(\n+\t\t\t5,\n+\t\t);\n+\t\texpect(\n+\t\t\tevaluateOptimization(\n+\t\t\t\t{ ...OPTIMIZATION_PRESETS.shortSequenceDeficit, thresholdDays: 3 },\n+\t\t\t\tobservations,\n+\t\t\t),\n+\t\t).toBe(2);\n+\t\texpect(evaluateOptimization(OPTIMIZATION_PRESETS.longestWorkSequence, observations)).toBe(\n+\t\t\t6,\n+\t\t);\n+\t});\n+\n+\tit('evaluates all six recipes from the same concrete observations', () => {\n+\t\tconst observations: OptimizationObservations = {\n+\t\t\tleaveBalances: [\n+\t\t\t\t{ unplacedQuantity: 3, atRisk: true },\n+\t\t\t\t{ unplacedQuantity: 8, atRisk: false },\n+\t\t\t],\n+\t\t\tpublicHolidayWeeks: [\n+\t\t\t\t{ value: 3, complete: true },\n+\t\t\t\t{ value: 1, complete: false },\n+\t\t\t\t{ value: 4, complete: true },\n+\t\t\t],\n+\t\t\ttimeOffPeriods: [\n+\t\t\t\t{ nonWorkingDates: ['2024-01-06', '2024-01-07'] },\n+\t\t\t\t{ nonWorkingDates: ['2024-05-08', '2024-05-09', '2024-05-09'] },\n+\t\t\t],\n+\t\t\tworkSequences: [\n+\t\t\t\t{ length: 1, internal: false },\n+\t\t\t\t{ length: 0, internal: true },\n+\t\t\t\t{ length: 1, internal: true },\n+\t\t\t\t{ length: 4, internal: true },\n+\t\t\t\t{ length: 6, internal: false },\n+\t\t\t],\n+\t\t\tleavePlacements: [{ supporting: true }, { supporting: false }, { supporting: true }],\n+\t\t};\n+\t\texpect(\n+\t\t\tObject.values(OPTIMIZATION_PRESETS).map((configuration) =>\n+\t\t\t\tevaluateOptimization(configuration, observations),\n+\t\t\t),\n+\t\t).toEqual([3, 7, 4, 6, 5, 2]);\n+\t});\n+\n+\tit.each(['sum', 'count', 'maximum'] as const)(\n+\t\t'defines empty %s as zero for every measure',\n+\t\t(aggregation) => {\n+\t\t\tfor (const configuration of Object.values(OPTIMIZATION_PRESETS)) {\n+\t\t\t\texpect(evaluateOptimization({ ...configuration, aggregation }, empty)).toBe(0);\n+\t\t\t}\n+\t\t},\n+\t);\n+\n+\tit('composes conditions, aggregation and direction independently of a rule name or identity', () => {\n+\t\tconst configuration = {\n+\t\t\t...OPTIMIZATION_PRESETS.longestWorkSequence,\n+\t\t\tconditions: ['internal', 'non-empty'] as const,\n+\t\t\taggregation: 'sum' as const,\n+\t\t\tdirection: 'maximize' as const,\n+\t\t};\n+\t\tconst observations: OptimizationObservations = {\n+\t\t\t...empty,\n+\t\t\tworkSequences: [\n+\t\t\t\t{ length: 20, internal: false },\n+\t\t\t\t{ length: 0, internal: true },\n+\t\t\t\t{ length: 2, internal: true },\n+\t\t\t\t{ length: 4, internal: true },\n+\t\t\t],\n+\t\t};\n+\t\tconst rules = [\n+\t\t\t{ id: 'provided', name: 'Original name', configuration },\n+\t\t\t{ id: 'personal', name: 'Renamed rule', configuration: structuredClone(configuration) },\n+\t\t];\n+\t\texpect(rules.map((rule) => evaluateOptimization(rule.configuration, observations))).toEqual(\n+\t\t\t[6, 6],\n+\t\t);\n+\t\texpect(evaluateOptimization({ ...configuration, aggregation: 'count' }, observations)).toBe(\n+\t\t\t2,\n+\t\t);\n+\t\texpect(\n+\t\t\tevaluateOptimization({ ...configuration, aggregation: 'maximum' }, observations),\n+\t\t).toBe(4);\n+\t\texpect(optimizationUnit(configuration)).toBe('working-days');\n+\t\texpect(optimizationUnit({ ...configuration, aggregation: 'count' })).toBe('count');\n+\t\texpect(optimizationUnit(OPTIMIZATION_PRESETS.nonWorkingDayGain)).toBe('calendar-days');\n+\t});\n+\n+\tit.each([\n+\t\t0,\n+\t\t-1,\n+\t\t1.5,\n+\t\tNumber.NaN,\n+\t\tNumber.POSITIVE_INFINITY,\n+\t\tundefined,\n+\t\t'3',\n+\t\tNumber.MAX_SAFE_INTEGER + 1,\n+\t])('rejects the invalid working-day deficit threshold %s', (thresholdDays) => {\n+\t\texpect(\n+\t\t\tvalidateOptimizationConfiguration({\n+\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\tthresholdDays,\n+\t\t\t}),\n+\t\t).toMatchObject({ valid: false, code: 'invalid-optimization-configuration' });\n+\t});\n+\n+\tit.each([\n+\t\t{ ...OPTIMIZATION_PRESETS.nonWorkingDayGain, elements: 'work-sequences' },\n+\t\t{ ...OPTIMIZATION_PRESETS.nonWorkingDayGain, conditions: ['at-risk'] },\n+\t\t{ ...OPTIMIZATION_PRESETS.longestWorkSequence, aggregation: 'average' },\n+\t\t{ ...OPTIMIZATION_PRESETS.longestWorkSequence, thresholdDays: 3 },\n+\t\t{ ...OPTIMIZATION_PRESETS.shortSequenceDeficit, thresholdUnit: 'calendar-days' },\n+\t])('identifies an unsupported composition', (configuration) => {\n+\t\texpect(validateOptimizationConfiguration(configuration)).toMatchObject({\n+\t\t\tvalid: false,\n+\t\t\tcode: 'unsupported-optimization-configuration',\n+\t\t});\n+\t});\n+\n+\tit.each([\n+\t\tnull,\n+\t\t[],\n+\t\t{ ...OPTIMIZATION_PRESETS.shortSequenceDeficit, conditions: ['internal', 'internal'] },\n+\t\t{ ...OPTIMIZATION_PRESETS.longestWorkSequence, direction: 'up' },\n+\t\t{ ...OPTIMIZATION_PRESETS.unplacedAtRisk, conditions: new Array(1) },\n+\t])('rejects malformed configurations', (configuration) => {\n+\t\texpect(validateOptimizationConfiguration(configuration)).toMatchObject({\n+\t\t\tvalid: false,\n+\t\t\tcode: 'invalid-optimization-configuration',\n+\t\t});\n+\t});\n+\n+\tit('never evaluates an unsupported configuration as a preset', () => {\n+\t\texpect(() =>\n+\t\t\tevaluateOptimization(\n+\t\t\t\t{ ...OPTIMIZATION_PRESETS.nonWorkingDayGain, elements: 'work-sequences' },\n+\t\t\t\tempty,\n+\t\t\t),\n+\t\t).toThrow('unsupported-optimization-configuration');\n+\t});\n+\n+\tit('compares ordered objectives lexicographically with the configured directions', () => {\n+\t\tconst before = [\n+\t\t\t{ id: 'first', direction: 'minimize' as const, value: 3 },\n+\t\t\t{ id: 'second', direction: 'maximize' as const, value: 100 },\n+\t\t\t{ id: 'date', direction: 'minimize' as const, value: '2024-01-10' },\n+\t\t];\n+\t\tconst earlierPriority = [{ ...before[0], value: 2 }, { ...before[1], value: 0 }, before[2]];\n+\t\texpect(compareObjectiveLists(earlierPriority, before)).toBeLessThan(0);\n+\t\texpect(firstDifferentObjective(earlierPriority, before)).toBe(0);\n+\t\tconst laterPriority = [before[0], { ...before[1], value: 101 }, before[2]];\n+\t\texpect(compareObjectiveLists(laterPriority, before)).toBeLessThan(0);\n+\t\texpect(firstDifferentObjective(laterPriority, before)).toBe(1);\n+\t\tconst earlierDate = [before[0], before[1], { ...before[2], value: '2024-01-09' }];\n+\t\texpect(compareObjectiveLists(earlierDate, before)).toBeLessThan(0);\n+\t\texpect(firstDifferentObjective(earlierDate, before)).toBe(2);\n+\t\texpect(compareObjectiveLists(before, structuredClone(before))).toBe(0);\n+\t\texpect(firstDifferentObjective(before, structuredClone(before))).toBe(-1);\n+\t\texpect(compareObjectiveValues('maximize', 0, 0)).toBe(0);\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/services/planning-objectives.spec.ts", "project_id": 35, "relative_order": 34, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,300 @@\n+export type OptimizationElements =\n+\t| 'leave-balances'\n+\t| 'public-holiday-weeks'\n+\t| 'time-off-periods'\n+\t| 'work-sequences'\n+\t| 'leave-placements';\n+export type OptimizationCondition =\n+\t| 'at-risk'\n+\t| 'complete'\n+\t| 'internal'\n+\t| 'non-empty'\n+\t| 'supporting';\n+export type OptimizationMeasure =\n+\t| 'unplaced-quantity'\n+\t| 'public-holiday-week-value'\n+\t| 'non-working-day-gain'\n+\t| 'work-sequence-length'\n+\t| 'work-sequence-deficit'\n+\t| 'placement-count';\n+export type OptimizationAggregation = 'sum' | 'count' | 'maximum';\n+export type OptimizationDirection = 'minimize' | 'maximize';\n+export type OptimizationUnit = 'working-days' | 'calendar-days' | 'count';\n+\n+interface OptimizationConfigurationBase {\n+\telements: OptimizationElements;\n+\tconditions: readonly OptimizationCondition[];\n+\taggregation: OptimizationAggregation;\n+\tdirection: OptimizationDirection;\n+}\n+\n+export type OptimizationConfiguration = OptimizationConfigurationBase &\n+\t(\n+\t\t| { measure: 'work-sequence-deficit'; thresholdDays: number }\n+\t\t| { measure: Exclude; thresholdDays?: never }\n+\t);\n+\n+/** Each row accepts any subset of its conditions and both comparison directions. */\n+export const OPTIMIZATION_CATALOG = [\n+\t{\n+\t\telements: 'leave-balances',\n+\t\tmeasure: 'unplaced-quantity',\n+\t\tconditions: ['at-risk'],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'working-days',\n+\t},\n+\t{\n+\t\telements: 'public-holiday-weeks',\n+\t\tmeasure: 'public-holiday-week-value',\n+\t\tconditions: ['complete'],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'calendar-days',\n+\t},\n+\t{\n+\t\telements: 'time-off-periods',\n+\t\tmeasure: 'non-working-day-gain',\n+\t\tconditions: [],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'calendar-days',\n+\t},\n+\t{\n+\t\telements: 'work-sequences',\n+\t\tmeasure: 'work-sequence-length',\n+\t\tconditions: ['internal', 'non-empty'],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'working-days',\n+\t},\n+\t{\n+\t\telements: 'work-sequences',\n+\t\tmeasure: 'work-sequence-deficit',\n+\t\tconditions: ['internal', 'non-empty'],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'working-days',\n+\t},\n+\t{\n+\t\telements: 'leave-placements',\n+\t\tmeasure: 'placement-count',\n+\t\tconditions: ['supporting'],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'count',\n+\t},\n+] as const;\n+\n+export type OptimizationValidation =\n+\t| { valid: true; configuration: OptimizationConfiguration }\n+\t| {\n+\t\t\tvalid: false;\n+\t\t\tcode: 'invalid-optimization-configuration' | 'unsupported-optimization-configuration';\n+\t\t\tmessage: string;\n+\t };\n+\n+export function validateOptimizationConfiguration(value: unknown): OptimizationValidation {\n+\tconst invalid = (message: string): OptimizationValidation => ({\n+\t\tvalid: false,\n+\t\tcode: 'invalid-optimization-configuration',\n+\t\tmessage,\n+\t});\n+\tconst unsupported = (message: string): OptimizationValidation => ({\n+\t\tvalid: false,\n+\t\tcode: 'unsupported-optimization-configuration',\n+\t\tmessage,\n+\t});\n+\tif (!value || typeof value !== 'object' || Array.isArray(value))\n+\t\treturn invalid('An optimization configuration must be an object.');\n+\tconst config = value as Record;\n+\tconst fields = [\n+\t\t'elements',\n+\t\t'conditions',\n+\t\t'measure',\n+\t\t'aggregation',\n+\t\t'direction',\n+\t\t'thresholdDays',\n+\t];\n+\tif (Object.keys(config).some((key) => !fields.includes(key)))\n+\t\treturn unsupported('The optimization configuration contains an unsupported field.');\n+\tif (config['direction'] !== 'minimize' && config['direction'] !== 'maximize')\n+\t\treturn invalid('The optimization direction must be minimize or maximize.');\n+\tif (\n+\t\t!Array.isArray(config['conditions']) ||\n+\t\t[...config['conditions']].some((condition) => typeof condition !== 'string') ||\n+\t\tnew Set(config['conditions']).size !== config['conditions'].length\n+\t)\n+\t\treturn invalid('Optimization conditions must be a list of distinct conditions.');\n+\tconst row = OPTIMIZATION_CATALOG.find(\n+\t\t(item) => item.elements === config['elements'] && item.measure === config['measure'],\n+\t);\n+\tif (!row) return unsupported('The planning elements and measure are not compatible.');\n+\tconst conditions: readonly string[] = row.conditions;\n+\tif (config['conditions'].some((condition) => !conditions.includes(condition)))\n+\t\treturn unsupported('A condition is not supported for these planning elements.');\n+\tconst aggregations: readonly string[] = row.aggregations;\n+\tif (typeof config['aggregation'] !== 'string' || !aggregations.includes(config['aggregation']))\n+\t\treturn unsupported('The aggregation is not supported for this measure.');\n+\tif (config['measure'] === 'work-sequence-deficit') {\n+\t\tif (!Number.isSafeInteger(config['thresholdDays']) || Number(config['thresholdDays']) <= 0)\n+\t\t\treturn invalid('The deficit threshold must be a positive integer in working days.');\n+\t} else if ('thresholdDays' in config)\n+\t\treturn unsupported('Only the work-sequence deficit accepts a working-day threshold.');\n+\treturn { valid: true, configuration: value as OptimizationConfiguration };\n+}\n+\n+export function optimizationUnit(configuration: OptimizationConfiguration): OptimizationUnit {\n+\treturn configuration.aggregation === 'count'\n+\t\t? 'count'\n+\t\t: OPTIMIZATION_CATALOG.find(\n+\t\t\t\t(row) =>\n+\t\t\t\t\trow.elements === configuration.elements &&\n+\t\t\t\t\trow.measure === configuration.measure,\n+\t\t\t)!.unit;\n+}\n+\n+export const OPTIMIZATION_PRESETS = {\n+\tunplacedAtRisk: {\n+\t\telements: 'leave-balances',\n+\t\tconditions: ['at-risk'],\n+\t\tmeasure: 'unplaced-quantity',\n+\t\taggregation: 'sum',\n+\t\tdirection: 'minimize',\n+\t},\n+\tholidayWeekValue: {\n+\t\telements: 'public-holiday-weeks',\n+\t\tconditions: ['complete'],\n+\t\tmeasure: 'public-holiday-week-value',\n+\t\taggregation: 'sum',\n+\t\tdirection: 'maximize',\n+\t},\n+\tnonWorkingDayGain: {\n+\t\telements: 'time-off-periods',\n+\t\tconditions: [],\n+\t\tmeasure: 'non-working-day-gain',\n+\t\taggregation: 'sum',\n+\t\tdirection: 'maximize',\n+\t},\n+\tlongestWorkSequence: {\n+\t\telements: 'work-sequences',\n+\t\tconditions: [],\n+\t\tmeasure: 'work-sequence-length',\n+\t\taggregation: 'maximum',\n+\t\tdirection: 'minimize',\n+\t},\n+\tshortSequenceDeficit: {\n+\t\telements: 'work-sequences',\n+\t\tconditions: ['internal', 'non-empty'],\n+\t\tmeasure: 'work-sequence-deficit',\n+\t\tthresholdDays: 5,\n+\t\taggregation: 'sum',\n+\t\tdirection: 'minimize',\n+\t},\n+\tsupportingPlacements: {\n+\t\telements: 'leave-placements',\n+\t\tconditions: ['supporting'],\n+\t\tmeasure: 'placement-count',\n+\t\taggregation: 'count',\n+\t\tdirection: 'minimize',\n+\t},\n+} as const satisfies Record;\n+\n+/** Concrete observations from one plan; they carry no rule identity or display name. */\n+export interface OptimizationObservations {\n+\tleaveBalances: readonly { unplacedQuantity: number; atRisk: boolean }[];\n+\tpublicHolidayWeeks: readonly { value: number; complete: boolean }[];\n+\ttimeOffPeriods: readonly { nonWorkingDates: readonly string[] }[];\n+\tworkSequences: readonly { length: number; internal: boolean }[];\n+\tleavePlacements: readonly { supporting: boolean }[];\n+}\n+\n+export function evaluateOptimization(\n+\tconfiguration: OptimizationConfiguration,\n+\tobservations: OptimizationObservations,\n+): number {\n+\tconst validation = validateOptimizationConfiguration(configuration);\n+\tif (!validation.valid) throw new Error(`${validation.code}: ${validation.message}`);\n+\tconst selected = (condition: OptimizationCondition) =>\n+\t\tconfiguration.conditions.includes(condition);\n+\tlet values: number[];\n+\tswitch (configuration.elements) {\n+\t\tcase 'leave-balances':\n+\t\t\tvalues = observations.leaveBalances\n+\t\t\t\t.filter((balance) => !selected('at-risk') || balance.atRisk)\n+\t\t\t\t.map((balance) => balance.unplacedQuantity);\n+\t\t\tbreak;\n+\t\tcase 'public-holiday-weeks':\n+\t\t\tvalues = observations.publicHolidayWeeks\n+\t\t\t\t.filter((week) => !selected('complete') || week.complete)\n+\t\t\t\t.map((week) => week.value);\n+\t\t\tbreak;\n+\t\tcase 'time-off-periods':\n+\t\t\tvalues = observations.timeOffPeriods.map(\n+\t\t\t\t(period) => new Set(period.nonWorkingDates).size,\n+\t\t\t);\n+\t\t\tbreak;\n+\t\tcase 'work-sequences':\n+\t\t\tvalues = observations.workSequences\n+\t\t\t\t.filter(\n+\t\t\t\t\t(sequence) =>\n+\t\t\t\t\t\t(!selected('internal') || sequence.internal) &&\n+\t\t\t\t\t\t(!selected('non-empty') || sequence.length > 0),\n+\t\t\t\t)\n+\t\t\t\t.map((sequence) =>\n+\t\t\t\t\tconfiguration.measure === 'work-sequence-deficit'\n+\t\t\t\t\t\t? sequence.length > 0\n+\t\t\t\t\t\t\t? Math.max(0, configuration.thresholdDays - sequence.length)\n+\t\t\t\t\t\t\t: 0\n+\t\t\t\t\t\t: sequence.length,\n+\t\t\t\t);\n+\t\t\tbreak;\n+\t\tcase 'leave-placements':\n+\t\t\tvalues = observations.leavePlacements\n+\t\t\t\t.filter((placement) => !selected('supporting') || placement.supporting)\n+\t\t\t\t.map(() => 1);\n+\t}\n+\tswitch (configuration.aggregation) {\n+\t\tcase 'count':\n+\t\t\treturn values.length;\n+\t\tcase 'sum':\n+\t\t\treturn values.reduce((total, value) => total + value, 0);\n+\t\tcase 'maximum':\n+\t\t\treturn values.reduce((maximum, value) => Math.max(maximum, value), 0);\n+\t}\n+}\n+\n+export interface ComparableObjective {\n+\tid: string;\n+\tdirection: OptimizationDirection;\n+\tvalue: number | string;\n+}\n+\n+/** Negative means the left candidate is preferred. Strings retain lexical tie-break ordering. */\n+export function compareObjectiveValues(\n+\tdirection: OptimizationDirection,\n+\tleft: number | string,\n+\tright: number | string,\n+): number {\n+\tif (left === right) return 0;\n+\tconst difference =\n+\t\ttypeof left === 'number' && typeof right === 'number'\n+\t\t\t? left - right\n+\t\t\t: left < right\n+\t\t\t\t? -1\n+\t\t\t\t: left > right\n+\t\t\t\t\t? 1\n+\t\t\t\t\t: 0;\n+\treturn direction === 'minimize' ? difference : -difference;\n+}\n+\n+export function firstDifferentObjective(\n+\tleft: readonly ComparableObjective[],\n+\tright: readonly ComparableObjective[],\n+): number {\n+\treturn left.findIndex((objective, index) => objective.value !== right[index]?.value);\n+}\n+\n+export function compareObjectiveLists(\n+\tleft: readonly ComparableObjective[],\n+\tright: readonly ComparableObjective[],\n+): number {\n+\tconst index = firstDifferentObjective(left, right);\n+\treturn index < 0\n+\t\t? 0\n+\t\t: compareObjectiveValues(left[index].direction, left[index].value, right[index].value);\n+}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/services/planning-objectives.ts", "project_id": 35, "relative_order": 35, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,288 @@\n+import { TestBed } from '@angular/core/testing';\n+import { RuleService, RuleType } from './rule-service';\n+import { vi } from 'vitest';\n+import { CalendarSettingsService } from './calendar-settings-service';\n+import { PlanningDurationService } from './planning-duration.service';\n+import { UserInputService } from './user-input-service';\n+import { SelectableDayType } from './calendar-service';\n+import { createPlanningCalculation } from './leave-planner.service';\n+\n+describe('saved rule migration', () => {\n+\tbeforeEach(() => localStorage.clear());\n+\tafterEach(() => {\n+\t\tvi.restoreAllMocks();\n+\t\tvi.unstubAllGlobals();\n+\t\tTestBed.resetTestingModule();\n+\t\tlocalStorage.clear();\n+\t});\n+\n+\tit('restores every legacy record unchanged between loss prevention and the other five presets', () => {\n+\t\tconst legacy = [\n+\t\t\t{\n+\t\t\t\tid: 'personal-window',\n+\t\t\t\tname: 'My fixed window',\n+\t\t\t\ttype: RuleType.TIME_WINDOW,\n+\t\t\t\tenabled: true,\n+\t\t\t\tforce: 'obligation',\n+\t\t\t\tstartDate: '2024-01-10',\n+\t\t\t\tendDate: '2024-01-12',\n+\t\t\t\tplaceDays: 2,\n+\t\t\t\tplaceType: 'cp',\n+\t\t\t},\n+\t\t\t{\n+\t\t\t\tid: 'personal-pattern',\n+\t\t\t\tname: 'My disabled pattern',\n+\t\t\t\ttype: RuleType.IF_THEN,\n+\t\t\t\tenabled: false,\n+\t\t\t\tdayOfWeek: 6,\n+\t\t\t\tplaceDays: 2,\n+\t\t\t\tplaceType: 'cp',\n+\t\t\t\tplacement: 'around',\n+\t\t\t\trewardDays: 1,\n+\t\t\t\trewardType: 'other',\n+\t\t\t},\n+\t\t];\n+\t\tlocalStorage.setItem('vacationRules', JSON.stringify(legacy));\n+\t\tconst service = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toHaveLength(8);\n+\t\texpect(service.rules.slice(1, 3).map(({ id }) => id)).toEqual([\n+\t\t\t'personal-window',\n+\t\t\t'personal-pattern',\n+\t\t]);\n+\t\tconst saved = JSON.parse(localStorage.getItem('vacationRules')!);\n+\t\texpect(saved.version).toBe(1);\n+\t\texpect(saved.rules.slice(1, 3)).toEqual(legacy);\n+\t\texpect(service.rules[2].force).toBe('preference');\n+\t\texpect(saved.rules[2]).not.toHaveProperty('force');\n+\t});\n+\n+\tit('gives fresh users the six active presets around the two existing initial rules', () => {\n+\t\tconst service = TestBed.inject(RuleService);\n+\t\texpect(service.rules.map(({ id }) => id)).toEqual([\n+\t\t\t'default-unplaced-at-risk',\n+\t\t\t'default-samedi-malin',\n+\t\t\t'default-christmas',\n+\t\t\t'default-holiday-week-value',\n+\t\t\t'default-non-working-day-gain',\n+\t\t\t'default-longest-work-sequence',\n+\t\t\t'default-short-sequence-deficit',\n+\t\t\t'default-supporting-placements',\n+\t\t]);\n+\t\tconst presets = service.rules.filter(({ type }) => type === RuleType.OPTIMIZATION);\n+\t\texpect(presets).toHaveLength(6);\n+\t\texpect(presets.every(({ enabled, force }) => enabled && force === 'preference')).toBe(true);\n+\t});\n+\n+\tit('migrates an old empty list once and retains editing, order, disabled and deleted choices immediately', () => {\n+\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlet service = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toHaveLength(6);\n+\t\tconst deficit = service.rules[4];\n+\t\tif (\n+\t\t\tdeficit.type !== RuleType.OPTIMIZATION ||\n+\t\t\tdeficit.configuration.measure !== 'work-sequence-deficit'\n+\t\t)\n+\t\t\tthrow new Error('Expected the deficit preset');\n+\t\tservice.updateRule({\n+\t\t\t...deficit,\n+\t\t\tname: 'My three-day deficit',\n+\t\t\tconfiguration: { ...deficit.configuration, thresholdDays: 3 },\n+\t\t});\n+\t\tservice.reorderRules(4, 0);\n+\t\tservice.toggleRule(deficit.id);\n+\t\tservice.deleteRule('default-holiday-week-value');\n+\t\tconst expected = service.rules;\n+\t\tTestBed.resetTestingModule();\n+\t\tservice = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toEqual(expected);\n+\t\texpect(service.rules[0]).toMatchObject({\n+\t\t\tname: 'My three-day deficit',\n+\t\t\tenabled: false,\n+\t\t\tconfiguration: { thresholdDays: 3 },\n+\t\t});\n+\t\tfor (const rule of service.rules) service.deleteRule(rule.id);\n+\t\tTestBed.resetTestingModule();\n+\t\texpect(TestBed.inject(RuleService).rules).toEqual([]);\n+\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!)).toEqual({\n+\t\t\tversion: 1,\n+\t\t\trules: [],\n+\t\t});\n+\t});\n+\n+\tit('avoids colliding with existing custom identities without replacing their records', () => {\n+\t\tconst custom = ['default-unplaced-at-risk', 'default-unplaced-at-risk-2'].map((id) => ({\n+\t\t\tid,\n+\t\t\tname: id,\n+\t\t\ttype: RuleType.IF_THEN,\n+\t\t\tenabled: false,\n+\t\t\tdayOfWeek: 6,\n+\t\t\tplaceDays: 2,\n+\t\t\tplaceType: 'cp',\n+\t\t\tplacement: 'auto',\n+\t\t\trewardDays: 1,\n+\t\t\trewardType: 'other',\n+\t\t}));\n+\t\tlocalStorage.setItem('vacationRules', JSON.stringify(custom));\n+\t\tconst rules = TestBed.inject(RuleService).rules;\n+\t\texpect(rules[0].id).toBe('default-unplaced-at-risk-3');\n+\t\texpect(new Set(rules.map(({ id }) => id)).size).toBe(8);\n+\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!).rules.slice(1, 3)).toEqual(\n+\t\t\tcustom,\n+\t\t);\n+\t});\n+\n+\tit('saves the migrated list and version in one atomic write and retries after a failed save', () => {\n+\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tvi.spyOn(console, 'warn').mockImplementation(() => undefined);\n+\t\tconst save = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {\n+\t\t\tthrow new Error('quota');\n+\t\t});\n+\t\tlet service = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toHaveLength(6);\n+\t\texpect(save).toHaveBeenCalledOnce();\n+\t\texpect(localStorage.getItem('vacationRules')).toBe('[]');\n+\t\tservice.toggleRule(service.rules[0].id);\n+\t\texpect(localStorage.getItem('vacationRules')).toBe('[]');\n+\t\tsave.mockRestore();\n+\t\tTestBed.resetTestingModule();\n+\t\tservice = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toHaveLength(6);\n+\t\texpect(service.rules[0].enabled).toBe(true);\n+\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!).version).toBe(1);\n+\t});\n+\n+\tit('keeps edits usable and saves the entire current list once storage recovers', () => {\n+\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tconst service = TestBed.inject(RuleService);\n+\t\tconst prior = localStorage.getItem('vacationRules');\n+\t\tvi.spyOn(console, 'warn').mockImplementation(() => undefined);\n+\t\tconst save = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {\n+\t\t\tthrow new Error('quota');\n+\t\t});\n+\t\tservice.toggleRule(service.rules[0].id);\n+\t\texpect(service.rules[0].enabled).toBe(false);\n+\t\texpect(localStorage.getItem('vacationRules')).toBe(prior);\n+\t\tsave.mockRestore();\n+\t\tservice.deleteRule(service.rules[1].id);\n+\t\tconst expected = service.rules;\n+\t\tTestBed.resetTestingModule();\n+\t\texpect(TestBed.inject(RuleService).rules).toEqual(expected);\n+\t});\n+\n+\tit.each(['{\"version\":2,\"rules\":[]}', '{broken', 'null', '[null]'])(\n+\t\t'preserves unsupported saved data through subsequent edits: %s',\n+\t\t(saved) => {\n+\t\t\tlocalStorage.setItem('vacationRules', saved);\n+\t\t\tvi.spyOn(console, 'warn').mockImplementation(() => undefined);\n+\t\t\tconst save = vi.spyOn(Storage.prototype, 'setItem');\n+\t\t\tconst service = TestBed.inject(RuleService);\n+\t\t\tservice.toggleRule(service.rules[0].id);\n+\t\t\texpect(save).not.toHaveBeenCalled();\n+\t\t\texpect(localStorage.getItem('vacationRules')).toBe(saved);\n+\t\t},\n+\t);\n+\n+\tit('prevents edits from overwriting unknown valid saved data after a read failure', () => {\n+\t\tconst saved = '{\"version\":1,\"rules\":[]}';\n+\t\tlocalStorage.setItem('vacationRules', saved);\n+\t\tvi.spyOn(console, 'warn').mockImplementation(() => undefined);\n+\t\tconst read = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {\n+\t\t\tthrow new Error('denied');\n+\t\t});\n+\t\tconst service = TestBed.inject(RuleService);\n+\t\tread.mockRestore();\n+\t\tconst write = vi.spyOn(Storage.prototype, 'setItem');\n+\t\tservice.toggleRule(service.rules[0].id);\n+\t\texpect(write).not.toHaveBeenCalled();\n+\t\texpect(localStorage.getItem('vacationRules')).toBe(saved);\n+\t});\n+\n+\tit('works in memory when browser storage is unavailable', () => {\n+\t\tvi.stubGlobal('localStorage', undefined);\n+\t\tconst service = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toHaveLength(8);\n+\t\tservice.toggleRule(service.rules[0].id);\n+\t\texpect(service.rules[0].enabled).toBe(false);\n+\t});\n+\n+\tit.each(['disabled', 'deleted'])(\n+\t\t'keeps a migrated %s list inactive after reload while preserving declarations and at-risk quantities',\n+\t\tasync (choice) => {\n+\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tconst service = TestBed.inject(RuleService);\n+\t\t\tfor (const rule of service.rules) {\n+\t\t\t\tif (choice === 'disabled') service.toggleRule(rule.id);\n+\t\t\t\telse service.deleteRule(rule.id);\n+\t\t\t}\n+\t\t\tconst saved = localStorage.getItem('vacationRules');\n+\t\t\tTestBed.resetTestingModule();\n+\t\t\tconst restored = TestBed.inject(RuleService).rules;\n+\t\t\texpect(restored).toHaveLength(choice === 'disabled' ? 6 : 0);\n+\t\t\texpect(restored.every(({ enabled }) => !enabled)).toBe(true);\n+\t\t\texpect(localStorage.getItem('vacationRules')).toBe(saved);\n+\t\t\tvi.stubGlobal('window', undefined);\n+\t\t\tconst calculation = createPlanningCalculation({\n+\t\t\t\thorizon: { start: '2024-01-02', end: '2024-01-05' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-01-04' }],\n+\t\t\t\tdeclaredDays: [{ date: '2024-01-03', type: 'other' }],\n+\t\t\t\trules: restored,\n+\t\t\t});\n+\t\t\tconst outcome = await calculation.outcome;\n+\t\t\texpect(outcome).toMatchObject({\n+\t\t\t\tkind: 'Plan',\n+\t\t\t\tplacements: [],\n+\t\t\t\tdeclaredDays: [{ date: '2024-01-03', type: 'other' }],\n+\t\t\t\tremainingBalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\tquantity: 2,\n+\t\t\t\t\t\tclassification: 'at-risk',\n+\t\t\t\t\t\treason: { code: 'active-priorities' },\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t});\n+\t\t\texpect((await calculation.trace)?.phases.map(({ name }) => name)).toEqual([\n+\t\t\t\t'validation',\n+\t\t\t\t'obligations',\n+\t\t\t\t'expiry',\n+\t\t\t\t'dates',\n+\t\t\t]);\n+\t\t\texpect(await calculation.explanation).toMatchObject({\n+\t\t\t\tkind: 'PlanExplanation',\n+\t\t\t\tplacements: [],\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit('migrates before the first duration request and actual calculation', async () => {\n+\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tTestBed.inject(CalendarSettingsService).setPlanningDates('2024-01-02', '2024-01-05');\n+\t\tTestBed.inject(UserInputService).updateBalances(() => [\n+\t\t\t{\n+\t\t\t\tid: 'cp',\n+\t\t\t\ttype: SelectableDayType.CP,\n+\t\t\t\tnumberOfDays: 1,\n+\t\t\t\tavailableDate: new Date('2024-01-02'),\n+\t\t\t\texpiryDate: new Date('2024-01-05'),\n+\t\t\t},\n+\t\t]);\n+\t\tconst request = TestBed.inject(PlanningDurationService).request()!;\n+\t\texpect(request.rules).toHaveLength(6);\n+\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!).version).toBe(1);\n+\t\tvi.stubGlobal('window', undefined);\n+\t\tconst calculation = createPlanningCalculation(request);\n+\t\tconst outcome = await calculation.outcome;\n+\t\texpect(outcome).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tmetrics: { unplacedAtRisk: 0 },\n+\t\t\tplacements: [{ balanceId: 'cp' }],\n+\t\t});\n+\t\texpect((await calculation.trace)?.phases.map(({ name }) => name)).toEqual([\n+\t\t\t'validation',\n+\t\t\t'obligations',\n+\t\t\t...request.rules.map(({ id }) => `optimization:${id}`),\n+\t\t\t'expiry',\n+\t\t\t'dates',\n+\t\t]);\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": true, "new_path": null, "old_path": "src/app/services/rule-migration.spec.ts", "project_id": 35, "relative_order": 36, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,6 +1,14 @@\n import { TestBed } from '@angular/core/testing';\n-import { RuleService, RuleType, IfThenRule, TimeWindowRule } from './rule-service';\n+import {\n+\tRuleService,\n+\tRuleType,\n+\tIfThenRule,\n+\tTimeWindowRule,\n+\tOptimizationRule,\n+} from './rule-service';\n import { SelectableDayType } from './calendar-service';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+import { vi } from 'vitest';\n \n describe('RuleService', () => {\n \tlet service: RuleService;\n@@ -18,9 +26,10 @@ describe('RuleService', () => {\n \n \tit('should initialize with default rules', () => {\n \t\tconst rules = service.rules;\n-\t\texpect(rules.length).toBe(2);\n-\t\texpect(rules[0].id).toBe('default-samedi-malin');\n-\t\texpect(rules[1].id).toBe('default-christmas');\n+\t\texpect(rules.length).toBe(8);\n+\t\texpect(rules[0].id).toBe('default-unplaced-at-risk');\n+\t\texpect(rules[1].id).toBe('default-samedi-malin');\n+\t\texpect(rules[2].id).toBe('default-christmas');\n \t});\n \n \tit('should parse dates correctly for TimeWindowRules', () => {\n@@ -62,9 +71,12 @@ describe('RuleService', () => {\n \t\tTestBed.configureTestingModule({});\n \t\tservice = TestBed.inject(RuleService);\n \n-\t\texpect(service.rules.map((rule) => rule.id)).toEqual(['legacy-first', 'legacy-second']);\n-\t\texpect(service.rules[0].force).toBe('preference');\n-\t\tconst first = service.rules[0] as TimeWindowRule;\n+\t\texpect(service.rules.slice(1, 3).map((rule) => rule.id)).toEqual([\n+\t\t\t'legacy-first',\n+\t\t\t'legacy-second',\n+\t\t]);\n+\t\texpect(service.rules[1].force).toBe('preference');\n+\t\tconst first = service.rules[1] as TimeWindowRule;\n \t\texpect(first.startDate.toISOString().slice(0, 10)).toBe('2024-02-01');\n \t});\n \n@@ -84,13 +96,13 @@ describe('RuleService', () => {\n \n \t\tservice.addRule(newRule);\n \t\tconst rules = service.rules;\n-\t\texpect(rules.length).toBe(3);\n+\t\texpect(rules.length).toBe(9);\n \t\texpect(rules.find((r) => r.id === 'test-rule')).toBeDefined();\n \t});\n \n \tit('should update an existing rule', () => {\n \t\tconst rules = service.rules;\n-\t\tconst targetRule = { ...rules[0] } as IfThenRule;\n+\t\tconst targetRule = { ...rules.find((rule) => rule.type === RuleType.IF_THEN)! };\n \t\ttargetRule.name = 'Updated Name';\n \n \t\tservice.updateRule(targetRule);\n@@ -107,7 +119,7 @@ describe('RuleService', () => {\n \t\tservice.deleteRule(idToDelete);\n \n \t\tconst updatedRules = service.rules;\n-\t\texpect(updatedRules.length).toBe(1);\n+\t\texpect(updatedRules.length).toBe(7);\n \t\texpect(updatedRules.find((r) => r.id === idToDelete)).toBeUndefined();\n \t});\n \n@@ -132,4 +144,42 @@ describe('RuleService', () => {\n \t\texpect(rulesAfter[0].id).toBe(secondRuleId);\n \t\texpect(rulesAfter[1].id).toBe(firstRuleId);\n \t});\n+\n+\tit('restores the full optimization identity, parameters, enabled state and position', () => {\n+\t\tvi.useFakeTimers();\n+\t\ttry {\n+\t\t\tTestBed.tick();\n+\t\t\tconst optimization: OptimizationRule = {\n+\t\t\t\tid: 'personal-loss',\n+\t\t\t\tname: 'My loss priority',\n+\t\t\t\ttype: RuleType.OPTIMIZATION,\n+\t\t\t\tenabled: true,\n+\t\t\t\tforce: 'preference',\n+\t\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),\n+\t\t\t};\n+\t\t\tservice.addRule(optimization);\n+\t\t\toptimization.configuration.conditions = [];\n+\t\t\tservice.reorderRules(\n+\t\t\t\tservice.rules.findIndex(({ id }) => id === optimization.id),\n+\t\t\t\t0,\n+\t\t\t);\n+\t\t\tservice.toggleRule('personal-loss');\n+\t\t\tconst saved = service.rules;\n+\t\t\tTestBed.tick();\n+\t\t\tvi.advanceTimersByTime(350);\n+\t\t\tTestBed.resetTestingModule();\n+\t\t\tservice = TestBed.inject(RuleService);\n+\t\t\texpect(service.rules).toEqual(saved);\n+\t\t\texpect(service.rules[0]).toMatchObject({\n+\t\t\t\tid: 'personal-loss',\n+\t\t\t\tname: 'My loss priority',\n+\t\t\t\tenabled: false,\n+\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t\t});\n+\t\t\tservice.deleteRule('personal-loss');\n+\t\t\texpect(service.rules.some((rule) => rule.id === 'personal-loss')).toBe(false);\n+\t\t} finally {\n+\t\t\tvi.useRealTimers();\n+\t\t}\n+\t});\n });\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/rule-service.spec.ts", "project_id": 35, "relative_order": 37, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,10 +1,11 @@\n-import { Injectable, WritableSignal, Injector, inject } from '@angular/core';\n+import { Injectable, WritableSignal, signal } from '@angular/core';\n import { SelectableDayType } from './calendar-service';\n-import { storedSignal } from '../shared/utils/stored-signal';\n+import { OPTIMIZATION_PRESETS, type OptimizationConfiguration } from './planning-objectives';\n \n export enum RuleType {\n \tIF_THEN = 'if_then',\n \tTIME_WINDOW = 'time_window',\n+\tOPTIMIZATION = 'optimization',\n }\n \n export type RuleForce = 'obligation' | 'preference';\n@@ -14,7 +15,7 @@ export interface BaseRule {\n \tname: string;\n \ttype: RuleType;\n \tenabled: boolean;\n-\t/** Missing force is a legacy preference and is migrated on read. */\n+\t/** Missing force is read as a legacy preference without rewriting the saved entry. */\n \tforce?: RuleForce;\n }\n \n@@ -38,29 +39,88 @@ export interface TimeWindowRule extends BaseRule {\n \tplaceType: SelectableDayType;\n }\n \n-export type VacationRule = IfThenRule | TimeWindowRule;\n+export interface OptimizationRule extends BaseRule {\n+\ttype: RuleType.OPTIMIZATION;\n+\tforce: 'preference';\n+\tconfiguration: OptimizationConfiguration;\n+}\n \n-interface SerializedRule {\n-\tid: string;\n-\tname: string;\n-\ttype: RuleType;\n-\tenabled: boolean;\n-\tforce?: RuleForce;\n-\tdayOfWeek?: number;\n-\tplaceDays: number;\n-\tplaceType: SelectableDayType;\n-\tplacement?: PlacementStrategy;\n-\trewardDays?: number;\n-\trewardType?: SelectableDayType;\n-\tstartDate?: string | Date;\n-\tendDate?: string | Date;\n+export type VacationRule = IfThenRule | TimeWindowRule | OptimizationRule;\n+\n+type SerializedRule =\n+\t| IfThenRule\n+\t| (Omit & {\n+\t\t\tstartDate: string | Date;\n+\t\t\tendDate: string | Date;\n+\t })\n+\t| (Omit & { force?: 'preference' });\n+\n+export function createOptimizationPresetRules(\n+\texistingIds: readonly string[] = [],\n+): OptimizationRule[] {\n+\tconst ids = new Set(existingIds);\n+\treturn (\n+\t\t[\n+\t\t\t['unplaced-at-risk', 'Prévention des pertes', OPTIMIZATION_PRESETS.unplacedAtRisk],\n+\t\t\t['holiday-week-value', 'Semaines fériées', OPTIMIZATION_PRESETS.holidayWeekValue],\n+\t\t\t[\n+\t\t\t\t'non-working-day-gain',\n+\t\t\t\t'Gain de jours non ouvrés',\n+\t\t\t\tOPTIMIZATION_PRESETS.nonWorkingDayGain,\n+\t\t\t],\n+\t\t\t[\n+\t\t\t\t'longest-work-sequence',\n+\t\t\t\t'Séquence de travail maximale',\n+\t\t\t\tOPTIMIZATION_PRESETS.longestWorkSequence,\n+\t\t\t],\n+\t\t\t[\n+\t\t\t\t'short-sequence-deficit',\n+\t\t\t\t'Déficit des reprises',\n+\t\t\t\tOPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t],\n+\t\t\t[\n+\t\t\t\t'supporting-placements',\n+\t\t\t\t'Économie des jours d’appoint',\n+\t\t\t\tOPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t],\n+\t\t] as const\n+\t).map(([key, name, configuration]) => {\n+\t\tconst base = `default-${key}`;\n+\t\tlet id = base;\n+\t\tlet suffix = 2;\n+\t\twhile (ids.has(id)) id = `${base}-${suffix++}`;\n+\t\tids.add(id);\n+\t\treturn {\n+\t\t\tid,\n+\t\t\tname,\n+\t\t\ttype: RuleType.OPTIMIZATION,\n+\t\t\tenabled: true,\n+\t\t\tforce: 'preference',\n+\t\t\tconfiguration: structuredClone(configuration),\n+\t\t};\n+\t});\n+}\n+\n+function isRuleList(value: unknown): value is SerializedRule[] {\n+\treturn (\n+\t\tArray.isArray(value) &&\n+\t\tvalue.every(\n+\t\t\t(rule) =>\n+\t\t\t\trule &&\n+\t\t\t\ttypeof rule === 'object' &&\n+\t\t\t\ttypeof rule.id === 'string' &&\n+\t\t\t\ttypeof rule.name === 'string' &&\n+\t\t\t\ttypeof rule.enabled === 'boolean' &&\n+\t\t\t\tObject.values(RuleType).includes(rule.type),\n+\t\t)\n+\t);\n }\n \n @Injectable({\n \tprovidedIn: 'root',\n })\n export class RuleService {\n-\tprivate readonly injector = inject(Injector);\n+\tprivate canPersist = true;\n \n \tprivate readonly defaultRules: VacationRule[] = [\n \t\t{\n@@ -92,11 +152,56 @@ export class RuleService {\n \tprivate rawRulesSignal: WritableSignal;\n \n \tconstructor() {\n-\t\tthis.rawRulesSignal = storedSignal(\n-\t\t\t'vacationRules',\n-\t\t\tthis.defaultRules as unknown as SerializedRule[],\n-\t\t\tthis.injector,\n-\t\t);\n+\t\tlet rules = this.initialRules(this.defaultRules);\n+\t\tlet migrate = true;\n+\t\ttry {\n+\t\t\tconst stored =\n+\t\t\t\ttypeof localStorage === 'undefined' ? null : localStorage.getItem('vacationRules');\n+\t\t\tif (stored !== null) {\n+\t\t\t\tconst parsed: unknown = JSON.parse(stored);\n+\t\t\t\tif (isRuleList(parsed)) rules = this.initialRules(parsed);\n+\t\t\t\telse if (\n+\t\t\t\t\tparsed &&\n+\t\t\t\t\ttypeof parsed === 'object' &&\n+\t\t\t\t\t'version' in parsed &&\n+\t\t\t\t\tparsed.version === 1 &&\n+\t\t\t\t\t'rules' in parsed &&\n+\t\t\t\t\tisRuleList(parsed.rules)\n+\t\t\t\t) {\n+\t\t\t\t\trules = parsed.rules;\n+\t\t\t\t\tmigrate = false;\n+\t\t\t\t} else throw new Error('Unsupported saved rule format.');\n+\t\t\t}\n+\t\t} catch (error) {\n+\t\t\t// A failed read must not allow a later edit to replace unknown saved rules.\n+\t\t\tthis.canPersist = false;\n+\t\t\tconsole.warn('Failed to restore planning rules from localStorage.', error);\n+\t\t}\n+\t\tthis.rawRulesSignal = signal(rules);\n+\t\tif (migrate) this.saveRules();\n+\t}\n+\n+\tprivate initialRules(existing: SerializedRule[]): SerializedRule[] {\n+\t\tconst presets = createOptimizationPresetRules(existing.map(({ id }) => id));\n+\t\treturn [presets[0], ...existing, ...presets.slice(1)];\n+\t}\n+\n+\tprivate saveRules(): void {\n+\t\tif (!this.canPersist) return;\n+\t\ttry {\n+\t\t\tif (typeof localStorage !== 'undefined')\n+\t\t\t\tlocalStorage.setItem(\n+\t\t\t\t\t'vacationRules',\n+\t\t\t\t\tJSON.stringify({ version: 1, rules: this.rawRulesSignal() }),\n+\t\t\t\t);\n+\t\t} catch (error) {\n+\t\t\tconsole.warn('Failed to save planning rules to localStorage.', error);\n+\t\t}\n+\t}\n+\n+\tprivate updateRules(update: (rules: SerializedRule[]) => SerializedRule[]): void {\n+\t\tthis.rawRulesSignal.update(update);\n+\t\tthis.saveRules();\n \t}\n \n \tpublic get rules(): VacationRule[] {\n@@ -106,46 +211,42 @@ export class RuleService {\n \t\t\t\treturn {\n \t\t\t\t\t...rule,\n \t\t\t\t\tforce: rule.force ?? 'preference',\n-\t\t\t\t\tstartDate: new Date(rule.startDate as string),\n-\t\t\t\t\tendDate: new Date(rule.endDate as string),\n-\t\t\t\t} as TimeWindowRule;\n+\t\t\t\t\tstartDate: new Date(rule.startDate),\n+\t\t\t\t\tendDate: new Date(rule.endDate),\n+\t\t\t\t};\n \t\t\t}\n-\t\t\treturn { ...rule, force: rule.force ?? 'preference' } as IfThenRule;\n+\t\t\tif (rule.type === RuleType.OPTIMIZATION)\n+\t\t\t\treturn structuredClone({ ...rule, force: rule.force ?? ('preference' as const) });\n+\t\t\treturn structuredClone({ ...rule, force: rule.force ?? 'preference' });\n \t\t});\n \t}\n \n \tpublic addRule(rule: VacationRule): void {\n-\t\tthis.rawRulesSignal.update((rules) => [\n-\t\t\t...rules,\n-\t\t\t{ ...rule, force: rule.force ?? 'preference' } as unknown as SerializedRule,\n-\t\t]);\n+\t\tconst saved = structuredClone(rule);\n+\t\tsaved.force ??= 'preference';\n+\t\tthis.updateRules((rules) => [...rules, saved]);\n \t}\n \n \tpublic updateRule(updatedRule: VacationRule): void {\n-\t\tthis.rawRulesSignal.update((rules) =>\n-\t\t\trules.map((rule) =>\n-\t\t\t\trule.id === updatedRule.id\n-\t\t\t\t\t? ({\n-\t\t\t\t\t\t\t...updatedRule,\n-\t\t\t\t\t\t\tforce: updatedRule.force ?? 'preference',\n-\t\t\t\t\t\t} as unknown as SerializedRule)\n-\t\t\t\t\t: rule,\n-\t\t\t),\n+\t\tconst saved = structuredClone(updatedRule);\n+\t\tsaved.force ??= 'preference';\n+\t\tthis.updateRules((rules) =>\n+\t\t\trules.map((rule) => (rule.id === updatedRule.id ? saved : rule)),\n \t\t);\n \t}\n \n \tpublic deleteRule(id: string): void {\n-\t\tthis.rawRulesSignal.update((rules) => rules.filter((rule) => rule.id !== id));\n+\t\tthis.updateRules((rules) => rules.filter((rule) => rule.id !== id));\n \t}\n \n \tpublic toggleRule(id: string): void {\n-\t\tthis.rawRulesSignal.update((rules) =>\n+\t\tthis.updateRules((rules) =>\n \t\t\trules.map((rule) => (rule.id === id ? { ...rule, enabled: !rule.enabled } : rule)),\n \t\t);\n \t}\n \n \tpublic reorderRules(previousIndex: number, currentIndex: number): void {\n-\t\tthis.rawRulesSignal.update((rules) => {\n+\t\tthis.updateRules((rules) => {\n \t\t\tconst updatedRules = [...rules];\n \t\t\tconst [movedRule] = updatedRules.splice(previousIndex, 1);\n \t\t\tupdatedRules.splice(currentIndex, 0, movedRule);\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/rule-service.ts", "project_id": 35, "relative_order": 38, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -3,6 +3,16 @@ import { Injectable, inject, Injector, computed } from '@angular/core';\n import { storedSignal } from '../shared/utils/stored-signal';\n import type { PlanOutcome, RemainingBalance } from './leave-planner.service';\n import { addPlanningDays } from './planning-date';\n+import {\n+\toptimizationUnit,\n+\tvalidateOptimizationConfiguration,\n+\ttype OptimizationConfiguration,\n+\ttype OptimizationElements,\n+\ttype OptimizationCondition,\n+\ttype OptimizationMeasure,\n+\ttype OptimizationAggregation,\n+\ttype OptimizationDirection,\n+} from './planning-objectives';\n \n export interface AppTranslations {\n \tlocale: string;\n@@ -77,6 +87,25 @@ export interface AppTranslations {\n \t\tinvalidHorizon: string;\n \t};\n \trules: {\n+\t\toptimization: {\n+\t\t\tnewRule: string;\n+\t\t\tdefaultName: string;\n+\t\t\telementsLabel: string;\n+\t\t\tconditionsLabel: string;\n+\t\t\tmeasureLabel: string;\n+\t\t\taggregationLabel: string;\n+\t\t\tdirectionLabel: string;\n+\t\t\tthresholdLabel: string;\n+\t\t\tthresholdSummary: string;\n+\t\t\tsummary: string;\n+\t\t\tinvalidConfiguration: string;\n+\t\t\tnameRequired: string;\n+\t\t\telements: Record;\n+\t\t\tconditions: Record;\n+\t\t\tmeasures: Record;\n+\t\t\taggregations: Record;\n+\t\t\tdirections: Record;\n+\t\t};\n \t\ttitle: string;\n \t\tsubtitle: string;\n \t\tactive: string;\n@@ -390,6 +419,29 @@ export class TranslationService {\n \t\t}\n \t}\n \n+\tpublic optimizationSummary(configuration: OptimizationConfiguration): string {\n+\t\tconst tr = this.tr().rules.optimization;\n+\t\tif (!validateOptimizationConfiguration(configuration).valid) return tr.invalidConfiguration;\n+\t\tconst unit = optimizationUnit(configuration);\n+\t\tconst unitLabel =\n+\t\t\tunit === 'count'\n+\t\t\t\t? tr.aggregations.count\n+\t\t\t\t: this.tr().planning.statistics[\n+\t\t\t\t\t\tunit === 'working-days' ? 'workingDays' : 'calendarDays'\n+\t\t\t\t\t];\n+\t\tconst conditions = configuration.conditions.map((condition) => tr.conditions[condition]);\n+\t\tif (configuration.measure === 'work-sequence-deficit')\n+\t\t\tconditions.push(\n+\t\t\t\ttr.thresholdSummary.replace('{count}', String(configuration.thresholdDays)),\n+\t\t\t);\n+\t\treturn tr.summary\n+\t\t\t.replace('{direction}', tr.directions[configuration.direction])\n+\t\t\t.replace('{aggregation}', tr.aggregations[configuration.aggregation])\n+\t\t\t.replace('{measure}', `${tr.measures[configuration.measure]} (${unitLabel})`)\n+\t\t\t.replace('{elements}', tr.elements[configuration.elements])\n+\t\t\t.replace('{conditions}', conditions.length ? ` (${conditions.join(', ')})` : '');\n+\t}\n+\n \tpublic getLanguageName(langCode: string): string {\n \t\ttry {\n \t\t\t// Using native Intl.DisplayNames to get name of language in its own language\n@@ -421,7 +473,8 @@ export class TranslationService {\n \t\tconst reasons = this.tr().planning.details.remainingReasons;\n \t\tif (!plan) return reasons['not-established'];\n \t\tconst code =\n-\t\t\tincomplete && ['preserved', 'not-established'].includes(balance.reason.code)\n+\t\t\tincomplete &&\n+\t\t\t['preserved', 'active-priorities', 'not-established'].includes(balance.reason.code)\n \t\t\t\t? 'calculation-incomplete'\n \t\t\t\t: balance.reason.code;\n \t\treturn (reasons[code] ?? reasons['not-established'])\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/services/translation-service.ts", "project_id": 35, "relative_order": 39, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -32,7 +32,7 @@ describe('Application Settings', () => {\n \t\tlocalStorage.clear();\n \t\tlocalStorage.setItem('app.language', JSON.stringify('en'));\n \t\tlocalStorage.setItem('leaveBalances', savedBalances);\n-\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\tlocalStorage.setItem('unrelated.entry', 'keep this value');\n \t\tmediaQuery = Object.assign(new EventTarget(), {\n \t\t\tmatches: true,\n@@ -461,7 +461,7 @@ describe('Application Settings', () => {\n \t\t\tawait (await dialog.getHarness(MatSlideToggleHarness)).check();\n \t\t\texpect(localStorage.getItem('calendarSettings.showWeekNumbers')).toBe('true');\n \t\t\texpect(localStorage.getItem('leaveBalances')).toBe(savedBalances);\n-\t\t\texpect(localStorage.getItem('vacationRules')).toBe('[]');\n+\t\t\texpect(localStorage.getItem('vacationRules')).toBe('{\"version\":1,\"rules\":[]}');\n \t\t\texpect(localStorage.getItem('unrelated.entry')).toBe('keep this value');\n \t\t\texpect(fixture.nativeElement.querySelectorAll('.week-number').length).toBeGreaterThan(\n \t\t\t\t0,\n@@ -490,7 +490,7 @@ describe('Application Settings', () => {\n \t\t\tTestBed.resetTestingModule();\n \t\t\tawait createApp();\n \t\t\texpect(localStorage.getItem('leaveBalances')).toBe(savedBalances);\n-\t\t\texpect(localStorage.getItem('vacationRules')).toBe('[]');\n+\t\t\texpect(localStorage.getItem('vacationRules')).toBe('{\"version\":1,\"rules\":[]}');\n \t\t\texpect(localStorage.getItem('unrelated.entry')).toBe('keep this value');\n \t\t\texpect(document.body.classList.contains('dark-mode')).toBe(true);\n \t\t\texpect(\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/app/app-settings.spec.ts", "project_id": 35, "relative_order": 40, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -133,6 +133,51 @@\n \t\t\t\"after\": \"danach\",\n \t\t\t\"around\": \"darum herum\",\n \t\t\t\"auto\": \"automatisch\"\n+\t\t},\n+\t\t\"optimization\": {\n+\t\t\t\"newRule\": \"Neue Optimierungsregel\",\n+\t\t\t\"defaultName\": \"Verluste vermeiden\",\n+\t\t\t\"elementsLabel\": \"Planungselemente\",\n+\t\t\t\"conditionsLabel\": \"Bedingungen (alle müssen erfüllt sein)\",\n+\t\t\t\"measureLabel\": \"Messgröße\",\n+\t\t\t\"aggregationLabel\": \"Aggregation\",\n+\t\t\t\"directionLabel\": \"Richtung\",\n+\t\t\t\"thresholdLabel\": \"Präferenzschwelle in Arbeitstagen\",\n+\t\t\t\"thresholdSummary\": \"Präferenzschwelle: {count} Arbeitstage\",\n+\t\t\t\"summary\": \"{direction} {aggregation}: {measure} — {elements}{conditions}.\",\n+\t\t\t\"invalidConfiguration\": \"Wählen Sie passende Elemente, Bedingungen, Messgrößen und Aggregationen sowie bei Bedarf eine positive ganzzahlige Tagesschwelle.\",\n+\t\t\t\"nameRequired\": \"Geben Sie einen Regelnamen ein.\",\n+\t\t\t\"elements\": {\n+\t\t\t\t\"leave-balances\": \"Urlaubsguthaben\",\n+\t\t\t\t\"public-holiday-weeks\": \"Feiertagswochen\",\n+\t\t\t\t\"time-off-periods\": \"Arbeitsfreie Zeiträume\",\n+\t\t\t\t\"work-sequences\": \"Arbeitsfolgen\",\n+\t\t\t\t\"leave-placements\": \"Geplante Urlaubstage\"\n+\t\t\t},\n+\t\t\t\"conditions\": {\n+\t\t\t\t\"at-risk\": \"Vom Verfall bedroht\",\n+\t\t\t\t\"complete\": \"Vollständig\",\n+\t\t\t\t\"internal\": \"Intern\",\n+\t\t\t\t\"non-empty\": \"Nicht leer\",\n+\t\t\t\t\"supporting\": \"Unterstützend\"\n+\t\t\t},\n+\t\t\t\"measures\": {\n+\t\t\t\t\"unplaced-quantity\": \"Nicht eingeplante Menge\",\n+\t\t\t\t\"public-holiday-week-value\": \"Wert der Feiertagswochen\",\n+\t\t\t\t\"non-working-day-gain\": \"Gewinn arbeitsfreier Tage\",\n+\t\t\t\t\"work-sequence-length\": \"Länge der Arbeitsfolgen\",\n+\t\t\t\t\"work-sequence-deficit\": \"Defizit der Arbeitsfolgen\",\n+\t\t\t\t\"placement-count\": \"Anzahl der Platzierungen\"\n+\t\t\t},\n+\t\t\t\"aggregations\": {\n+\t\t\t\t\"sum\": \"Summe\",\n+\t\t\t\t\"count\": \"Anzahl\",\n+\t\t\t\t\"maximum\": \"Maximum\"\n+\t\t\t},\n+\t\t\t\"directions\": {\n+\t\t\t\t\"minimize\": \"Minimieren\",\n+\t\t\t\t\"maximize\": \"Maximieren\"\n+\t\t\t}\n \t\t}\n \t},\n \t\"planning\": {\n@@ -276,7 +321,7 @@\n \t\t\t\"withoutDay\": \"Ohne diesen Tag\",\n \t\t\t\"withDay\": \"Mit diesem Tag\",\n \t\t\t\"noChange\": \"Diese Werte sind gleich. Regeln und die letzten Entscheidungskriterien (Verfall des Guthabens, dann Datum) können die Auswahl weiterhin beeinflussen.\",\n-\t\t\t\"priorityHelp\": \"Die Kriterien stehen in Prioritätsreihenfolge. Der erste Unterschied hat Vorrang vor den folgenden.\",\n+\t\t\t\"priorityHelp\": \"Verpflichtungen werden gemeinsam erfüllt. Aktive Präferenzen werden in Ihrer Regelreihenfolge verglichen. Nur diese Regeln führen zu neuen Urlaubstagen; früherer Verfall und dann frühere Daten entscheiden bei Gleichstand.\",\n \t\t\t\"tryDate\": \"Anderes Datum testen\",\n \t\t\t\"plannedDate\": \"Derzeit geplant für:\",\n \t\t\t\"currentPlan\": \"Aktueller Plan\",\n@@ -327,6 +372,10 @@\n \t\t\t\t\"placement-date\": {\n \t\t\t\t\t\"label\": \"Frühere Daten bevorzugen\",\n \t\t\t\t\t\"help\": \"Letztes Kriterium, wenn alle anderen Kriterien gleich sind.\"\n+\t\t\t\t},\n+\t\t\t\t\"optimization\": {\n+\t\t\t\t\t\"label\": \"{rule}: {summary}\",\n+\t\t\t\t\t\"help\": \"Diese Optimierungspräferenz bewertet ihre gespeicherte Konfiguration. Aktive Präferenzen werden in der angezeigten Reihenfolge verglichen; frühere haben Vorrang.\"\n \t\t\t\t}\n \t\t\t},\n \t\t\t\"stages\": {\n@@ -342,7 +391,9 @@\n \t\t\t\t\"unavailable\": \"Dieses Urlaubsguthaben kann an diesem Datum nicht verwendet werden.\",\n \t\t\t\t\"expired\": \"Dieses Datum liegt nach dem Verfall des Urlaubsguthabens.\",\n \t\t\t\t\"type-incompatible\": \"Diese Urlaubsart kann an diesem Datum nicht verwendet werden.\",\n-\t\t\t\t\"rule-invalid\": \"Dieses Datum würde eine Planungsregel verletzen.\"\n+\t\t\t\t\"rule-invalid\": \"Dieses Datum würde eine Planungsregel verletzen.\",\n+\t\t\t\t\"invalid-optimization-configuration\": \"Wählen Sie passende Elemente, Bedingungen, Messgrößen und Aggregationen sowie bei Bedarf eine positive ganzzahlige Tagesschwelle.\",\n+\t\t\t\t\"unsupported-optimization-configuration\": \"Diese Regel kombiniert unvereinbare Planungselemente und Messgrößen.\"\n \t\t\t},\n \t\t\t\"preferenceHelp\": {\n \t\t\t\t\"time_window\": \"Urlaubstage im bevorzugten Zeitraum. Mehr ist besser.\",\n@@ -373,6 +424,7 @@\n \t\t\t\t\"no-working-date\": \"Kein Arbeitstag liegt sowohl im Planungszeitraum als auch zwischen Verfügbarkeits- und Ablaufdatum.\",\n \t\t\t\t\"all-dates-occupied\": \"Alle Arbeitstage, an denen dieses Urlaubskonto nutzbar ist, sind bereits durch geplanten Urlaub oder gebuchte Tage belegt.\",\n \t\t\t\t\"preserved\": \"Für später aufbewahrt: Das Urlaubskonto läuft nach dem Planungszeitraum ab und die Berechnung hat gemäß Ihren Prioritäten keine zusätzliche Platzierung ausgewählt.\",\n+\t\t\t\t\"active-priorities\": \"Die Berechnung hat dieses Urlaubskonto gemäß Ihren aktiven Regeln ungenutzt gelassen. Ändern Sie die Regeln oder ihre Reihenfolge, um einen anderen Plan anzufordern.\",\n \t\t\t\t\"calculation-incomplete\": \"Die Berechnung wurde vor Abschluss der Planung unterbrochen. Die Nichtnutzung ist keine endgültige Entscheidung.\",\n \t\t\t\t\"not-established\": \"Diese Berechnung hat keinen genauen Grund für die Nichtnutzung ermittelt.\"\n \t\t\t}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/i18n/de.json", "project_id": 35, "relative_order": 41, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -133,6 +133,51 @@\n \t\t\t\"after\": \"After\",\n \t\t\t\"around\": \"Around\",\n \t\t\t\"auto\": \"Auto (Best choice)\"\n+\t\t},\n+\t\t\"optimization\": {\n+\t\t\t\"newRule\": \"New Optimization Rule\",\n+\t\t\t\"defaultName\": \"Loss prevention\",\n+\t\t\t\"elementsLabel\": \"Planning elements\",\n+\t\t\t\"conditionsLabel\": \"Conditions (all must match)\",\n+\t\t\t\"measureLabel\": \"Measure\",\n+\t\t\t\"aggregationLabel\": \"Aggregation\",\n+\t\t\t\"directionLabel\": \"Direction\",\n+\t\t\t\"thresholdLabel\": \"Preference threshold in working days\",\n+\t\t\t\"thresholdSummary\": \"preference threshold: {count} working days\",\n+\t\t\t\"summary\": \"{direction} {aggregation}: {measure} — {elements}{conditions}.\",\n+\t\t\t\"invalidConfiguration\": \"Choose compatible planning elements, conditions, measure and aggregation, with a positive whole-day threshold when needed.\",\n+\t\t\t\"nameRequired\": \"Enter a rule name.\",\n+\t\t\t\"elements\": {\n+\t\t\t\t\"leave-balances\": \"Leave balances\",\n+\t\t\t\t\"public-holiday-weeks\": \"Public-holiday weeks\",\n+\t\t\t\t\"time-off-periods\": \"Time-off periods\",\n+\t\t\t\t\"work-sequences\": \"Work sequences\",\n+\t\t\t\t\"leave-placements\": \"Leave placements\"\n+\t\t\t},\n+\t\t\t\"conditions\": {\n+\t\t\t\t\"at-risk\": \"At risk of expiry\",\n+\t\t\t\t\"complete\": \"Complete\",\n+\t\t\t\t\"internal\": \"Internal\",\n+\t\t\t\t\"non-empty\": \"Non-empty\",\n+\t\t\t\t\"supporting\": \"Supporting\"\n+\t\t\t},\n+\t\t\t\"measures\": {\n+\t\t\t\t\"unplaced-quantity\": \"Unplaced quantity\",\n+\t\t\t\t\"public-holiday-week-value\": \"Public-holiday week value\",\n+\t\t\t\t\"non-working-day-gain\": \"Non-working-day gain\",\n+\t\t\t\t\"work-sequence-length\": \"Work-sequence length\",\n+\t\t\t\t\"work-sequence-deficit\": \"Work-sequence deficit\",\n+\t\t\t\t\"placement-count\": \"Placement count\"\n+\t\t\t},\n+\t\t\t\"aggregations\": {\n+\t\t\t\t\"sum\": \"Sum\",\n+\t\t\t\t\"count\": \"Count\",\n+\t\t\t\t\"maximum\": \"Maximum\"\n+\t\t\t},\n+\t\t\t\"directions\": {\n+\t\t\t\t\"minimize\": \"Minimize\",\n+\t\t\t\t\"maximize\": \"Maximize\"\n+\t\t\t}\n \t\t}\n \t},\n \t\"planning\": {\n@@ -276,7 +321,7 @@\n \t\t\t\"withoutDay\": \"Without this day\",\n \t\t\t\"withDay\": \"With this day\",\n \t\t\t\"noChange\": \"These totals are unchanged. Rules and the final tie-breakers (balance expiry, then date) can still affect the choice.\",\n-\t\t\t\"priorityHelp\": \"Criteria are listed in priority order. The first difference takes precedence over later ones.\",\n+\t\t\t\"priorityHelp\": \"Obligations are satisfied together. Active preferences are compared in your rule order. Only those rules drive new placements; earlier expiry and then dates break equal results.\",\n \t\t\t\"tryDate\": \"Try another date\",\n \t\t\t\"plannedDate\": \"Currently planned for:\",\n \t\t\t\"currentPlan\": \"Current plan\",\n@@ -327,6 +372,10 @@\n \t\t\t\t\"placement-date\": {\n \t\t\t\t\t\"label\": \"Earlier dates first\",\n \t\t\t\t\t\"help\": \"Final tie-breaker when all other criteria are equal.\"\n+\t\t\t\t},\n+\t\t\t\t\"optimization\": {\n+\t\t\t\t\t\"label\": \"{rule}: {summary}\",\n+\t\t\t\t\t\"help\": \"This optimization preference evaluates its saved configuration. Active preferences follow the displayed order; earlier preferences win before later ones.\"\n \t\t\t\t}\n \t\t\t},\n \t\t\t\"stages\": {\n@@ -342,7 +391,9 @@\n \t\t\t\t\"unavailable\": \"This leave balance cannot be used on this date.\",\n \t\t\t\t\"expired\": \"This date is after the leave balance expires.\",\n \t\t\t\t\"type-incompatible\": \"This leave type cannot be used on this date.\",\n-\t\t\t\t\"rule-invalid\": \"Using this date would break a planning rule.\"\n+\t\t\t\t\"rule-invalid\": \"Using this date would break a planning rule.\",\n+\t\t\t\t\"invalid-optimization-configuration\": \"Choose compatible planning elements, conditions, measure and aggregation, with a positive whole-day threshold when needed.\",\n+\t\t\t\t\"unsupported-optimization-configuration\": \"This rule uses an unsupported combination of planning elements and measures.\"\n \t\t\t},\n \t\t\t\"preferenceHelp\": {\n \t\t\t\t\"time_window\": \"Leave days in this preferred period. More is better.\",\n@@ -373,6 +424,7 @@\n \t\t\t\t\"no-working-date\": \"No working day falls within both the planning period and its availability and expiry dates.\",\n \t\t\t\t\"all-dates-occupied\": \"All working days on which this balance can be used are already occupied by planned leave or already booked days.\",\n \t\t\t\t\"preserved\": \"Kept for later: it expires after the planning period and the calculation retained no additional placement under your priorities.\",\n+\t\t\t\t\"active-priorities\": \"The calculation kept this balance unused under your active planning rules. Change the rules or their order to request a different plan.\",\n \t\t\t\t\"calculation-incomplete\": \"The calculation was interrupted before planning finished. Leaving it unused is not a final decision.\",\n \t\t\t\t\"not-established\": \"This calculation did not establish a precise reason for leaving it unused.\"\n \t\t\t}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/i18n/en.json", "project_id": 35, "relative_order": 42, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -133,6 +133,51 @@\n \t\t\t\"after\": \"Después\",\n \t\t\t\"around\": \"Alrededor\",\n \t\t\t\"auto\": \"Auto (Mejor opción)\"\n+\t\t},\n+\t\t\"optimization\": {\n+\t\t\t\"newRule\": \"Nueva regla de Optimización\",\n+\t\t\t\"defaultName\": \"Prevención de pérdidas\",\n+\t\t\t\"elementsLabel\": \"Elementos del plan\",\n+\t\t\t\"conditionsLabel\": \"Condiciones (deben cumplirse todas)\",\n+\t\t\t\"measureLabel\": \"Medida\",\n+\t\t\t\"aggregationLabel\": \"Agregación\",\n+\t\t\t\"directionLabel\": \"Dirección\",\n+\t\t\t\"thresholdLabel\": \"Umbral de preferencia en días laborables\",\n+\t\t\t\"thresholdSummary\": \"umbral de preferencia: {count} días laborables\",\n+\t\t\t\"summary\": \"{direction} {aggregation}: {measure} — {elements}{conditions}.\",\n+\t\t\t\"invalidConfiguration\": \"Elija elementos, condiciones, medidas y agregaciones compatibles, con un umbral entero positivo cuando sea necesario.\",\n+\t\t\t\"nameRequired\": \"Introduzca un nombre para la regla.\",\n+\t\t\t\"elements\": {\n+\t\t\t\t\"leave-balances\": \"Saldos de vacaciones\",\n+\t\t\t\t\"public-holiday-weeks\": \"Semanas con festivos\",\n+\t\t\t\t\"time-off-periods\": \"Períodos sin trabajo\",\n+\t\t\t\t\"work-sequences\": \"Secuencias de trabajo\",\n+\t\t\t\t\"leave-placements\": \"Vacaciones colocadas\"\n+\t\t\t},\n+\t\t\t\"conditions\": {\n+\t\t\t\t\"at-risk\": \"En riesgo de caducar\",\n+\t\t\t\t\"complete\": \"Completas\",\n+\t\t\t\t\"internal\": \"Internas\",\n+\t\t\t\t\"non-empty\": \"No vacías\",\n+\t\t\t\t\"supporting\": \"De apoyo\"\n+\t\t\t},\n+\t\t\t\"measures\": {\n+\t\t\t\t\"unplaced-quantity\": \"Cantidad no colocada\",\n+\t\t\t\t\"public-holiday-week-value\": \"Valor de las semanas festivas\",\n+\t\t\t\t\"non-working-day-gain\": \"Ganancia de días sin trabajo\",\n+\t\t\t\t\"work-sequence-length\": \"Longitud de las secuencias de trabajo\",\n+\t\t\t\t\"work-sequence-deficit\": \"Déficit de las secuencias de trabajo\",\n+\t\t\t\t\"placement-count\": \"Número de colocaciones\"\n+\t\t\t},\n+\t\t\t\"aggregations\": {\n+\t\t\t\t\"sum\": \"Suma\",\n+\t\t\t\t\"count\": \"Cantidad\",\n+\t\t\t\t\"maximum\": \"Máximo\"\n+\t\t\t},\n+\t\t\t\"directions\": {\n+\t\t\t\t\"minimize\": \"Minimizar\",\n+\t\t\t\t\"maximize\": \"Maximizar\"\n+\t\t\t}\n \t\t}\n \t},\n \t\"planning\": {\n@@ -276,7 +321,7 @@\n \t\t\t\"withoutDay\": \"Sin este día\",\n \t\t\t\"withDay\": \"Con este día\",\n \t\t\t\"noChange\": \"Estos totales son iguales. Las reglas y los últimos criterios de desempate (vencimiento del saldo y después fecha) aún pueden influir en la elección.\",\n-\t\t\t\"priorityHelp\": \"Los criterios se muestran por prioridad. La primera diferencia prevalece sobre las siguientes.\",\n+\t\t\t\"priorityHelp\": \"Las obligaciones se resuelven conjuntamente. Las preferencias activas se comparan en el orden de sus reglas. Solo esas reglas añaden vacaciones; la caducidad y luego las fechas resuelven los empates.\",\n \t\t\t\"tryDate\": \"Probar otra fecha\",\n \t\t\t\"plannedDate\": \"Fecha prevista actualmente:\",\n \t\t\t\"currentPlan\": \"Plan actual\",\n@@ -327,6 +372,10 @@\n \t\t\t\t\"placement-date\": {\n \t\t\t\t\t\"label\": \"Primero las fechas más tempranas\",\n \t\t\t\t\t\"help\": \"Último desempate cuando los demás criterios son iguales.\"\n+\t\t\t\t},\n+\t\t\t\t\"optimization\": {\n+\t\t\t\t\t\"label\": \"{rule}: {summary}\",\n+\t\t\t\t\t\"help\": \"Esta preferencia de optimización evalúa su configuración guardada. Las preferencias activas siguen el orden mostrado; las anteriores tienen prioridad.\"\n \t\t\t\t}\n \t\t\t},\n \t\t\t\"stages\": {\n@@ -342,7 +391,9 @@\n \t\t\t\t\"unavailable\": \"Este saldo de permisos no se puede usar en esta fecha.\",\n \t\t\t\t\"expired\": \"Esta fecha es posterior al vencimiento del saldo.\",\n \t\t\t\t\"type-incompatible\": \"Este tipo de permiso no se puede usar en esta fecha.\",\n-\t\t\t\t\"rule-invalid\": \"Usar esta fecha incumpliría una regla del plan.\"\n+\t\t\t\t\"rule-invalid\": \"Usar esta fecha incumpliría una regla del plan.\",\n+\t\t\t\t\"invalid-optimization-configuration\": \"Elija elementos, condiciones, medidas y agregaciones compatibles, con un umbral entero positivo cuando sea necesario.\",\n+\t\t\t\t\"unsupported-optimization-configuration\": \"Esta regla combina elementos del plan y medidas incompatibles.\"\n \t\t\t},\n \t\t\t\"preferenceHelp\": {\n \t\t\t\t\"time_window\": \"Días de permiso dentro del período preferido. Más es mejor.\",\n@@ -373,6 +424,7 @@\n \t\t\t\t\"no-working-date\": \"Ningún día laborable está dentro del período planificado y entre sus fechas de disponibilidad y caducidad.\",\n \t\t\t\t\"all-dates-occupied\": \"Todos los días laborables en los que puede utilizarse este saldo ya están ocupados por permisos planificados o días ya reservados.\",\n \t\t\t\t\"preserved\": \"Guardado para más adelante: caduca después del período planificado y el cálculo no seleccionó ninguna colocación adicional según tus prioridades.\",\n+\t\t\t\t\"active-priorities\": \"El cálculo conservó este saldo sin utilizar según tus reglas activas. Cambia las reglas o su orden para solicitar otro plan.\",\n \t\t\t\t\"calculation-incomplete\": \"El cálculo se interrumpió antes de terminar la planificación. Su falta de uso no es una decisión definitiva.\",\n \t\t\t\t\"not-established\": \"Este cálculo no determinó un motivo preciso para dejarlo sin utilizar.\"\n \t\t\t}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/i18n/es.json", "project_id": 35, "relative_order": 43, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -133,6 +133,51 @@\n \t\t\t\"after\": \"Après\",\n \t\t\t\"around\": \"Autour\",\n \t\t\t\"auto\": \"Auto (Meilleur choix)\"\n+\t\t},\n+\t\t\"optimization\": {\n+\t\t\t\"newRule\": \"Nouvelle règle d’Optimisation\",\n+\t\t\t\"defaultName\": \"Prévention des pertes\",\n+\t\t\t\"elementsLabel\": \"Éléments du planning\",\n+\t\t\t\"conditionsLabel\": \"Conditions (toutes doivent être vérifiées)\",\n+\t\t\t\"measureLabel\": \"Mesure\",\n+\t\t\t\"aggregationLabel\": \"Agrégation\",\n+\t\t\t\"directionLabel\": \"Direction\",\n+\t\t\t\"thresholdLabel\": \"Seuil de préférence en jours ouvrés\",\n+\t\t\t\"thresholdSummary\": \"seuil de préférence : {count} jours ouvrés\",\n+\t\t\t\"summary\": \"{direction} {aggregation} : {measure} — {elements}{conditions}.\",\n+\t\t\t\"invalidConfiguration\": \"Choisissez des éléments, conditions, une mesure et une agrégation compatibles, avec un seuil entier positif si nécessaire.\",\n+\t\t\t\"nameRequired\": \"Saisissez un nom de règle.\",\n+\t\t\t\"elements\": {\n+\t\t\t\t\"leave-balances\": \"Soldes de congés\",\n+\t\t\t\t\"public-holiday-weeks\": \"Semaines avec jour férié\",\n+\t\t\t\t\"time-off-periods\": \"Périodes non travaillées\",\n+\t\t\t\t\"work-sequences\": \"Séquences de travail\",\n+\t\t\t\t\"leave-placements\": \"Congés placés\"\n+\t\t\t},\n+\t\t\t\"conditions\": {\n+\t\t\t\t\"at-risk\": \"À risque d’expiration\",\n+\t\t\t\t\"complete\": \"Complètes\",\n+\t\t\t\t\"internal\": \"Internes\",\n+\t\t\t\t\"non-empty\": \"Non vides\",\n+\t\t\t\t\"supporting\": \"D’appui\"\n+\t\t\t},\n+\t\t\t\"measures\": {\n+\t\t\t\t\"unplaced-quantity\": \"Quantité non placée\",\n+\t\t\t\t\"public-holiday-week-value\": \"Valeur des semaines fériées\",\n+\t\t\t\t\"non-working-day-gain\": \"Gain de jours non travaillés\",\n+\t\t\t\t\"work-sequence-length\": \"Longueur des séquences de travail\",\n+\t\t\t\t\"work-sequence-deficit\": \"Déficit des séquences de travail\",\n+\t\t\t\t\"placement-count\": \"Nombre de placements\"\n+\t\t\t},\n+\t\t\t\"aggregations\": {\n+\t\t\t\t\"sum\": \"Somme\",\n+\t\t\t\t\"count\": \"Nombre\",\n+\t\t\t\t\"maximum\": \"Maximum\"\n+\t\t\t},\n+\t\t\t\"directions\": {\n+\t\t\t\t\"minimize\": \"Minimiser\",\n+\t\t\t\t\"maximize\": \"Maximiser\"\n+\t\t\t}\n \t\t}\n \t},\n \t\"planning\": {\n@@ -276,7 +321,7 @@\n \t\t\t\"withoutDay\": \"Sans ce jour\",\n \t\t\t\"withDay\": \"Avec ce jour\",\n \t\t\t\"noChange\": \"Ces totaux sont identiques. Les règles et les derniers critères de départage (expiration du solde, puis date) peuvent encore influencer le choix.\",\n-\t\t\t\"priorityHelp\": \"Les critères sont classés par priorité. La première différence prime sur les suivantes.\",\n+\t\t\t\"priorityHelp\": \"Les obligations sont résolues conjointement. Les préférences actives sont comparées dans l’ordre de vos règles. Seules ces règles déclenchent des placements ; l’expiration puis les dates départagent les résultats égaux.\",\n \t\t\t\"tryDate\": \"Essayer une autre date\",\n \t\t\t\"plannedDate\": \"Date actuellement prévue :\",\n \t\t\t\"currentPlan\": \"Planning actuel\",\n@@ -327,6 +372,10 @@\n \t\t\t\t\"placement-date\": {\n \t\t\t\t\t\"label\": \"Dates les plus proches d’abord\",\n \t\t\t\t\t\"help\": \"Dernier départage lorsque tous les autres critères sont égaux.\"\n+\t\t\t\t},\n+\t\t\t\t\"optimization\": {\n+\t\t\t\t\t\"label\": \"{rule}: {summary}\",\n+\t\t\t\t\t\"help\": \"Cette préférence d’optimisation évalue sa configuration enregistrée. Les préférences actives suivent l’ordre affiché ; les premières passent avant les suivantes.\"\n \t\t\t\t}\n \t\t\t},\n \t\t\t\"stages\": {\n@@ -342,7 +391,9 @@\n \t\t\t\t\"unavailable\": \"Ce solde de congés ne peut pas être utilisé à cette date.\",\n \t\t\t\t\"expired\": \"Cette date dépasse la date d’expiration du solde.\",\n \t\t\t\t\"type-incompatible\": \"Ce type de congé ne peut pas être utilisé à cette date.\",\n-\t\t\t\t\"rule-invalid\": \"Utiliser cette date ne respecterait pas une règle du planning.\"\n+\t\t\t\t\"rule-invalid\": \"Utiliser cette date ne respecterait pas une règle du planning.\",\n+\t\t\t\t\"invalid-optimization-configuration\": \"Choisissez des éléments, conditions, une mesure et une agrégation compatibles, avec un seuil entier positif si nécessaire.\",\n+\t\t\t\t\"unsupported-optimization-configuration\": \"Cette règle combine des éléments du planning et des mesures incompatibles.\"\n \t\t\t},\n \t\t\t\"preferenceHelp\": {\n \t\t\t\t\"time_window\": \"Jours de congé dans cette période souhaitée. Plus, c’est mieux.\",\n@@ -373,6 +424,7 @@\n \t\t\t\t\"no-working-date\": \"Aucun jour ouvré ne se trouve à la fois dans la période planifiée et entre ses dates de disponibilité et d’expiration.\",\n \t\t\t\t\"all-dates-occupied\": \"Tous les jours ouvrés où ce solde est utilisable sont déjà occupés par des congés calculés ou des jours déjà posés.\",\n \t\t\t\t\"preserved\": \"Conservé pour plus tard : il expire après la période planifiée et le calcul n’a pas retenu de pose supplémentaire selon vos priorités.\",\n+\t\t\t\t\"active-priorities\": \"Le calcul a conservé ce solde inutilisé selon vos règles actives. Modifiez les règles ou leur ordre pour demander un autre planning.\",\n \t\t\t\t\"calculation-incomplete\": \"Le calcul a été interrompu avant de terminer la planification. Sa non-utilisation n’est pas une décision définitive.\",\n \t\t\t\t\"not-established\": \"La raison précise de sa non-utilisation n’a pas été établie par ce calcul.\"\n \t\t\t}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "src/i18n/fr.json", "project_id": 35, "relative_order": 44, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -85,8 +85,6 @@ test:\n - bun scripts/generate-langs.js\n # ponytail: one worker bounds peak RAM; increase concurrency after adding runner memory.\n - bunx vitest run --coverage --maxWorkers=1 --exclude='src/app/benchmark/**'\n- # Keep the complete benchmark outside coverage instrumentation.\n- - bunx vitest run src/app/benchmark/leave-planner-benchmark.spec.ts --maxWorkers=1\n artifacts:\n when: always\n paths:\n@@ -97,6 +95,15 @@ test:\n path: coverage/cobertura-coverage.xml\n expire_in: 7 days\n \n+# shortcut: benchmark failures are advisory while #78 is open; restore the gate when #78 passes.\n+benchmark:\n+ extends: test\n+ allow_failure: true\n+ script:\n+ - bun scripts/generate-langs.js\n+ - bunx vitest run src/app/benchmark/leave-planner-benchmark.spec.ts --maxWorkers=1\n+ artifacts: null\n+\n # -- Build Stage --\n \n build:\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": ".gitlab-ci.yml", "project_id": 35, "relative_order": 45, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -247,7 +247,9 @@ GitLab CI runs independent validation, test, build, security, and image stages:\n \n Pipelines switch to MR pipelines when a branch has an open MR, avoiding duplicate builds. Docker publication from MR pipelines is limited to detached pipelines within this project. Tag pipelines promote the already-built commit image instead of rebuilding it.\n \n-The test job runs Vitest directly with one worker and a 2 GiB Node heap limit. It runs application tests with coverage, then the complete benchmark protocol separately without coverage instrumentation. The benchmark uses a five-minute execution timeout to allow for shared-runner contention; all protocol assertions remain mandatory. Timing measurements are benchmark evidence, not CI performance thresholds.\n+The required `test` job runs application tests with coverage, one worker and a 2 GiB Node heap limit. A separate automatic `benchmark` job uses the same environment outside coverage instrumentation, with the unchanged five-minute timeout and protocol assertions.\n+\n+At the user's request, the benchmark job has `allow_failure: true` while #78 is open, so benchmark failure does not block functional delivery. #78 must restore the required benchmark gate after the protocol passes. A green pipeline during this exception does not establish benchmark acceptance.\n \n ### GitFlow and releases\n \n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 469, "new_file": false, "new_path": null, "old_path": "README.md", "project_id": 35, "relative_order": 46, "renamed_file": false, "too_large": false } ], "metadata": { "base_commit_sha": "209bf05f3699c72f88efab733dde207c7230a8e4", "commits_count": 3, "created_at": "2026-10-10T14:42:05.283513", "diff_type": 1, "files_count": 47, "head_commit_sha": "ae68e31575c7b6c857bb0d5d538b7c4f418887e1", "id": 469, "merge_request_id": 286, "project_id": 35, "start_commit_sha": "209bf05f3699c72f88efab733dde207c7230a8e4", "state": "collected", "stored_externally": null, "updated_at": "2026-10-10T14:42:05.354238" } }, { "commits": [ { "authored_date": null, "commit_author_id": null, "committed_date": null, "committer_id": null, "merge_request_commits_metadata_id": 607, "merge_request_diff_id": 470, "message": null, "project_id": 35, "relative_order": 0, "sha": null, "trailers": {} }, { "authored_date": null, "commit_author_id": null, "committed_date": null, "committer_id": null, "merge_request_commits_metadata_id": 606, "merge_request_diff_id": 470, "message": null, "project_id": 35, "relative_order": 1, "sha": null, "trailers": {} }, { "authored_date": null, "commit_author_id": null, "committed_date": null, "committer_id": null, "merge_request_commits_metadata_id": 604, "merge_request_diff_id": 470, "message": null, "project_id": 35, "relative_order": 2, "sha": null, "trailers": {} }, { "authored_date": null, "commit_author_id": null, "committed_date": null, "committer_id": null, "merge_request_commits_metadata_id": 602, "merge_request_diff_id": 470, "message": null, "project_id": 35, "relative_order": 3, "sha": null, "trailers": {} } ], "files": [ { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,26 +1,34 @@\n-# 06 — Migrer les règles sauvegardées et valider l’ensemble\n+# 06 — Migrer les règles sauvegardées et valider le comportement fonctionnel\n \n **GitLab:** [#75](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/75)\n \n-**What to build:** Au prochain chargement, l’utilisateur retrouve ses règles et les six anciens comportements du moteur sous forme de préréglages actifs. Il peut ensuite les modifier ou les supprimer durablement, et l’ensemble est validé avant sa mise en service.\n+Blocked by: #74\n \n-**Blocked by:** 05 — Piloter l’économie des jours d’appoint.\n+Les exigences de performance sont transférées à #78. La clôture de ce ticket dépend de la migration et de la validation fonctionnelle, pas du passage du protocole de performance. Les limites du benchmark restent inchangées. À la demande de l’utilisateur, son job CI est séparé et non bloquant tant que #78 est ouvert ; #78 doit rétablir ce contrôle obligatoire après réussite du protocole. Les tests fonctionnels et les autres contrôles CI restent obligatoires.\n \n-**Status:** ready-for-agent\n+## What to build\n \n-Livraison intégrée de l’ADR 0008 sur la branche commune aux tickets 01 à 05. La préservation des données enregistrées et la migration unique ont été explicitement approuvées : ne pas réinitialiser les données pour simplifier le changement de contrat.\n+Au prochain chargement, l’utilisateur retrouve ses règles et les six anciens comportements du moteur sous forme de préréglages actifs. Il peut ensuite les modifier ou les supprimer durablement, et l’ensemble est validé avant sa mise en service.\n \n-- [ ] À l’initialisation, fournir les six préréglages actifs avec cet ordre : prévention des pertes, règles personnelles ou règles initiales existantes dans leur ordre, semaines fériées, gain de jours non ouvrés, séquence maximale, déficit des reprises et économie des placements d’appoint.\n-- [ ] Migrer une seule fois les listes enregistrées avant cette évolution, y compris une ancienne liste vide. Préserver intégralement l’identité, le nom, les paramètres, les dates, la force, l’activation et l’ordre relatif des règles existantes.\n-- [ ] Enregistrer de façon cohérente les règles migrées et le fait que la migration a eu lieu. Ne pas considérer l’opération terminée si les règles n’ont pas été sauvegardées ; gérer les échecs de stockage sans écraser les données utilisateur valides.\n-- [ ] Les chargements suivants ne dupliquent pas les préréglages, ne rétablissent pas ceux supprimés et ne réactivent pas ceux désactivés. Une liste vidée volontairement après migration reste vide. Les nouveaux utilisateurs reçoivent directement la nouvelle configuration initiale.\n-- [ ] La restauration et la migration précèdent le premier calcul utilisant ces données. L’utilisateur peut immédiatement éditer les six configurations avec les mêmes commandes que ses règles personnelles et retrouver ses choix après rechargement.\n-- [ ] Vérifier de bout en bout les six préréglages dans l’ordre initial, leurs réordonnancements et leurs désactivations. Une configuration personnelle différente d’un préréglage traverse édition, sauvegarde, worker, calcul et explication ; les paramètres ont un effet vérifiable.\n-- [ ] La liste entièrement désactivée, la liste supprimée après migration et une requête directe sans règle active n’ajoutent aucun congé malgré des soldes à risque. Les jours déclarés, les quantités restantes et les raisons pertinentes restent cohérents.\n-- [ ] Les obligations conjointes, les conditions des congés gagnés et les contraintes de validité sont respectées pour tout ordre des préférences. Une annulation restitue le meilleur plan valide disponible et sa trace originale selon la configuration soumise.\n-- [ ] Les explications et analyses contrefactuelles utilisent le même ordre actif que le calcul. Modifier les règles durant le calcul ou pendant la livraison tardive de la trace ne change pas ses résultats. Les anciens objectifs implicites n’interviennent plus dans aucune comparaison ou protection.\n-- [ ] Les fixtures et scénarios de benchmark qui dépendaient d’une optimisation implicite demandent explicitement les préréglages nécessaires. Les tests d’absence de règles n’utilisent aucun défaut implicite pour retrouver l’ancien résultat.\n-- [ ] Exécuter les suites concernées de règles, interface, moteur, worker réel, explication, annulation et estimation de durée, ainsi que les contrôles habituels de compilation et de qualité. Vérifier les scénarios de benchmark existants, dont les horizons longs, pour le déterminisme, la réactivité et les durées, sans introduire de délai d’arrêt automatique.\n-- [ ] La vérification commune des tickets 01 à 06 est la condition de mise en service. Documenter les choix finaux du contrat composable et les limites mesurées ; ne laisser ni double moteur, ni chemin historique implicite, ni adaptateur provisoire ajouté pour rendre les étapes indépendamment livrables.\n+Livraison intégrée de l’ADR 0008 sur la branche commune aux tickets #70, #71, #72, #73, #74. La préservation des données enregistrées et la migration unique ont été explicitement approuvées : ne pas réinitialiser les données pour simplifier le changement de contrat.\n+\n+## Acceptance criteria\n+\n+- [x] À l’initialisation, fournir les six préréglages actifs avec cet ordre : prévention des pertes, règles personnelles ou règles initiales existantes dans leur ordre, semaines fériées, gain de jours non ouvrés, séquence maximale, déficit des reprises et économie des placements d’appoint.\n+- [x] Migrer une seule fois les listes enregistrées avant cette évolution, y compris une ancienne liste vide. Préserver intégralement l’identité, le nom, les paramètres, les dates, la force, l’activation et l’ordre relatif des règles existantes.\n+- [x] Enregistrer de façon cohérente les règles migrées et le fait que la migration a eu lieu. Ne pas considérer l’opération terminée si les règles n’ont pas été sauvegardées ; gérer les échecs de stockage sans écraser les données utilisateur valides.\n+- [x] Les chargements suivants ne dupliquent pas les préréglages, ne rétablissent pas ceux supprimés et ne réactivent pas ceux désactivés. Une liste vidée volontairement après migration reste vide. Les nouveaux utilisateurs reçoivent directement la nouvelle configuration initiale.\n+- [x] La restauration et la migration précèdent le premier calcul utilisant ces données. L’utilisateur peut immédiatement éditer les six configurations avec les mêmes commandes que ses règles personnelles et retrouver ses choix après rechargement.\n+- [x] Vérifier de bout en bout les six préréglages dans l’ordre initial, leurs réordonnancements et leurs désactivations. Une configuration personnelle différente d’un préréglage traverse édition, sauvegarde, worker, calcul et explication ; les paramètres ont un effet vérifiable.\n+- [x] La liste entièrement désactivée, la liste supprimée après migration et une requête directe sans règle active n’ajoutent aucun congé malgré des soldes à risque. Les jours déclarés, les quantités restantes et les raisons pertinentes restent cohérents.\n+- [x] Les obligations conjointes, les conditions des congés gagnés et les contraintes de validité sont respectées pour tout ordre des préférences. Une annulation restitue le meilleur plan valide disponible selon la configuration soumise. La suppression de la trace originale est suivie séparément dans #76.\n+- [x] Les explications et analyses contrefactuelles utilisent le même ordre actif que le calcul. Modifier les règles durant le calcul ou pendant la livraison des explications ne change pas ses résultats. Les anciens objectifs implicites n’interviennent plus dans aucune comparaison ou protection.\n+- [x] Les fixtures et scénarios de benchmark qui dépendaient d’une optimisation implicite demandent explicitement les préréglages nécessaires. Les tests d’absence de règles n’utilisent aucun défaut implicite pour retrouver l’ancien résultat.\n+- [x] Exécuter les suites fonctionnelles concernées de règles, interface, moteur, worker réel, explication, annulation et estimation de durée, ainsi que les contrôles habituels de compilation et de qualité. Préserver les assertions de résultat et de déterminisme des fixtures, y compris les horizons longs. L’exécution complète du protocole de benchmark, la réactivité mesurée, les durées, la consommation mémoire et les optimisations nécessaires relèvent de #78 et ne conditionnent plus la clôture de #75. Ne pas introduire de délai d’arrêt automatique.\n+- [x] La vérification fonctionnelle commune des tickets #70, #71, #72, #73, #74, #75 est la condition de clôture fonctionnelle de ce ticket. Documenter les choix finaux du contrat composable ; ne laisser ni double moteur, ni chemin historique implicite, ni adaptateur provisoire ajouté pour rendre les étapes indépendamment livrables. Les limites de performance mesurées et leur amélioration sont suivies dans #78 ; les tests fonctionnels et les autres contrôles CI restent obligatoires, avec la seule exception temporaire du job de benchmark décrite ci-dessus.\n \n **Vérification de bout en bout :** Partir d’une ancienne sauvegarde contenant des règles personnalisées et désactivées, charger la nouvelle version, vérifier le premier calcul, modifier ou supprimer des préréglages, recharger et constater la conservation exacte des choix.\n+\n+## Blocked by\n+\n+- #74 — Piloter l’économie des jours d’appoint\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": ".scratch/regles-optimisation/issues/06-migrer-regles-sauvegardees-et-valider-ensemble.md", "project_id": 35, "relative_order": 0, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,29 @@\n+# 01 — Remove the original decision trace end to end\n+\n+**GitLab:** [#76](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/76)\n+\n+## What to build\n+\n+Calculations no longer record, retain or deliver an original decision trace. Users receive the displayed plan, its stable explanation and remaining-balance reasons, and can still analyze an alternative date for a displayed placement. The advanced trace explorer, historical calendar replay and historical attempt lists disappear completely.\n+\n+This is one cohesive contract replacement across the planner, calculation service, workers and UI. Use a scoped integration branch containing the existing #70–#75 implementation work; #75's final verification must not be treated as a prerequisite for removing tracing. The shared functional integration verification gate is #77 — Verify integrated planning after trace removal. Benchmark performance acceptance and any required optimization are owned by #78; performance is no longer a completion gate for #75.\n+\n+## Acceptance criteria\n+\n+- [ ] Delete trace capture, materialization, candidate-history retention, replay, historical eligibility and caches or evidence pools used exclusively for tracing. Remove observational work while preserving search breadth, allocation previews, rule priority and incumbent selection.\n+- [ ] Replace trace contracts directly and update all callers in the same change. Remove trace promises, callbacks, public types, streaming messages, status indexes, acknowledgements and backpressure queues across real-worker, browser-fallback and server-side calculation paths. Do not retain debug toggles, compatibility adapters, empty trace results or replacement history.\n+- [ ] Preserve immutable calculation, valid-incumbent and final-state snapshots needed by retained behavior. Rename retained state contracts independently of tracing; do not delete cancellation or explanation data because it currently has a trace-related name.\n+- [ ] Retain stable plan explanations, including placement entitlement and rule provenance, objective contributions and the first decisive objective, time-off periods, remaining balances and concrete non-placement reasons. Preserve invalid-input and conflict explanations and incomplete-calculation behavior.\n+- [ ] Keep alternative-date analysis for a displayed placement using the captured calculation configuration, the same entitlement, leave type and provenance, and fixed unrelated placements. Remove analysis based on historical decisions; hypothetical analysis never mutates the displayed plan.\n+- [ ] Remove the advanced trace panel, replay controls, historical calendar overlays and candidate statuses. Remove remaining-balance historical attempt lists, pagination and loading state while retaining classification, validity, earned-entitlement source and truthful displayed-plan reasons. Leave no dead controls or trace-unavailable messages.\n+- [ ] Preserve explicit cancellation before and after a valid incumbent, best-valid-partial-plan recovery, heartbeat monitoring, stale-response rejection and the existing technical-budget contract. Interrupted calculations do not imply an obligation conflict. Explanation delivery failures do not discard an available outcome, and planning workers do not wait for trace acknowledgements after required delivery.\n+- [ ] Preserve completed placements, balances, objective values, joint obligation satisfaction, earned-entitlement chronology, deterministic tie-breaking, user-controlled priorities and empty-active-rule behavior. Do not reset saved entitlements, declarations or rule configurations or change the existing migration.\n+- [ ] Update component styles and translations across supported languages, preserving keyboard access and accessibility for retained explanations, calendar interactions and date analysis.\n+- [ ] Adapt existing planner, service, worker, explanation, cancellation, calendar and remaining-balance tests. Delete tests exclusively for tracing while retaining assertions for supported behavior in mixed tests. Update benchmark callers, output and assertions to remove obsolete trace requirements without reducing scenarios or changing performance gates.\n+- [ ] Supersede trace-specific requirements in the domain vocabulary and explanation/cancellation ADRs, and update benchmark documentation. Preserve the remaining planning contracts and document that the original decision trace and historical analysis are removed.\n+\n+No new dependency, replacement telemetry, optimization-quality change, allocation-preview reduction or benchmark deadline relaxation is part of this ticket. No separate prefactor is required: retained explanation and hypothetical-analysis behavior already exists.\n+\n+## Blocked by\n+\n+None — can start immediately.\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": ".scratch/remove-original-decision-trace/issues/01-remove-original-decision-trace.md", "project_id": 35, "relative_order": 1, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,27 @@\n+# 02 — Verify integrated planning after trace removal\n+\n+**GitLab:** [#77](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/77)\n+\n+Blocked by: #76\n+\n+## What to build\n+\n+Demonstrate that the integrated #70–#75 work retains its supported behavior after trace removal. Provide a functionally verified trace-free baseline for #78, which now owns benchmark performance acceptance and optimization. Benchmark performance is no longer a completion gate for #75 or this functional verification ticket.\n+\n+## Acceptance criteria\n+\n+- [ ] Review the integrated contract replacement across all calculation paths and UI callers. Confirm there is no trace recorder, trace transport, acknowledgement wait, historical replay API or retained trace-dependent control or compatibility shell.\n+- [ ] Compare completed outcomes and stable explanations against existing deterministic fixtures, including typed joint obligations, earned-entitlement chains, custom objective formulas, reordered priorities, two- and three-year horizons and no active optimization rules. Do not rewrite placement expectations to hide a behavioral regression.\n+- [ ] Verify real-worker outcome and explanation delivery, heartbeat monitoring, stale-response rejection and explanation failure handling. Exercise cancellation before any valid incumbent and after a valid incumbent, and confirm that partial outcomes remain valid without false conflicts.\n+- [ ] Verify displayed-placement alternative-date analysis and remaining-balance reasons without historical data. Check that captured settings remain immutable and hypothetical alternatives do not change the displayed plan.\n+- [ ] Run the existing full correctness, coverage, static, formatting and build checks appropriate to the integrated change, and resolve regressions within the trace-removal scope. Preserve the repository's required thresholds.\n+- [ ] Complete browser QA for the retained explanation, calendar, cancellation and alternative-date flows, including keyboard interaction and a narrow viewport. Confirm the advanced trace explorer, historical overlays and historical attempt controls are absent.\n+- [ ] Verify that benchmark callers use the supported trace-free calculation contract and retain their correctness, determinism, horizon, placement-count and completed-stage assertions. Full protocol execution, the unchanged 2 GB/300-second performance gates and any required optimization belong to #78.\n+- [ ] Hand off the functionally verified integrated baseline and unchanged benchmark inputs to #78. Verify retained outcome and explanation delivery without waiting for removed trace artifacts or inventing replacement trace counters.\n+- [ ] Keep the original #70–#75 dependency order and report the functional integration result. Apply #75’s revised functional completion criteria: a benchmark performance failure alone does not block #75 or this ticket. Outstanding benchmark requirements remain open in #78, without deadline relaxation or an automatic engine cutoff.\n+\n+The removal is agreed; its measured speedup is unresolved and is now evaluated in #78. This ticket owns functional verification after trace removal. It does not itself implement performance optimizations or close other issues.\n+\n+## Blocked by\n+\n+- #76 — Remove the original decision trace end to end (https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/76).\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": ".scratch/remove-original-decision-trace/issues/02-verify-trace-free-planning.md", "project_id": 35, "relative_order": 2, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,39 @@\n+# 03 — Verify and optimize planning to meet the benchmarks from #75\n+\n+**GitLab:** [#78](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/78)\n+\n+Blocked by: #75, #77\n+\n+## Parent\n+\n+#75 — Performance acceptance separated from the functional migration ticket at the user's request.\n+\n+## What to build\n+\n+Verify the integrated planner against the benchmark requirements originally attached to #75 and apply performance optimizations when needed until those requirements pass. Start from the functionally verified implementation after original-decision-trace removal. #75 can finish on its functional requirements; performance acceptance belongs to this ticket.\n+\n+If the measured baseline already passes, keep the engine unchanged and record the evidence. Otherwise profile the real failing path, apply the smallest complete improvement and verify both performance and retained planning behavior.\n+\n+## Acceptance criteria\n+\n+- [ ] Keep the existing seven benchmark scenarios and inputs, including the loaded year, typed joint obligations, chained earned entitlements and two- and three-year horizons. Keep explicit optimization configurations, quotas, expected outcomes, placement counts, completed-stage and determinism assertions.\n+- [ ] Run the real existing benchmark protocol: one warm-up and two measured repetitions per scenario, outside coverage instrumentation, with a 2 GB Node heap limit and the 300-second timeout for the full protocol. All scenarios and repetitions must finish and pass; a timeout, skipped scenario or partial report does not satisfy this ticket.\n+- [ ] Restore the benchmark as a required CI check after the unchanged protocol passes. While this ticket is open, the user approved a separate automatic benchmark job with `allow_failure: true` so its failure does not block functional delivery. Passing CI during this exception does not satisfy benchmark acceptance or justify closing this ticket.\n+- [ ] After #76 removes tracing and #77 verifies the retained behavior, benchmark outcome and explanation delivery without obsolete trace counters, trace transfer or trace-acknowledgement waits. Do not reintroduce tracing as profiling infrastructure.\n+- [ ] When the baseline fails, profile CPU, allocation and repeated planning work; apply optimizations and rerun the unchanged protocol until it passes. Preserve planning semantics, rule ordering, joint obligations, earned-entitlement chronology, final-plan quality and deterministic tie-breaking. Use behavior-level or differential tests to demonstrate that caching, deduplication or pruning is valid across the relevant configurations.\n+- [ ] Preserve responsive browser interaction, explicit cancellation, heartbeat monitoring and best-valid-partial-plan recovery during representative and long-horizon calculations. Keep the existing duration-estimation contract and recalibrate estimates only when measured results require it.\n+- [ ] Do not increase the benchmark timeout or heap allowance, reduce scenarios or repetitions, weaken correctness assertions, add an automatic elapsed-time engine cutoff, or reduce search breadth or planning quality to make the protocol pass.\n+- [ ] Record reproducible before/after preparation, planning, total-duration, responsiveness and available peak-heap measurements, including environment and protocol. Clearly distinguish actual completed benchmark runs from diagnostics or interrupted measurements and document any reference-hardware checks that could not be performed.\n+- [ ] Run required correctness, coverage, static and build checks after any optimization. Preserve the captured configuration, stable explanations, displayed-placement alternative-date analysis and saved-user-data behavior.\n+- [ ] Update benchmark documentation with the final measured limits and evidence. Close this ticket only after the unchanged benchmark gates pass; a failed measurement remains an open performance requirement here rather than reopening #75 for performance alone.\n+\n+## Existing evidence and scope\n+\n+The previous real protocol timed out at 300 seconds without an out-of-memory failure. The loaded-year warm-up took about 184 seconds and its first measured repetition started about 252 seconds into the protocol. Original trace recording and repeated allocation previews were observed costs; the benefit of trace removal has not yet been measured. These are starting points for profiling, not permission to change optimization quality.\n+\n+This ticket authorizes verification and implementation of performance improvements when needed. Functional migration remains in #75, trace removal in #76 and trace-removal functional verification in #77. Existing benchmark limits remain unchanged; only the benchmark job's blocking status is temporarily waived at the user's request until this ticket restores it.\n+\n+## Blocked by\n+\n+- #75 — Finish the functional saved-rule migration and integrated planning validation.\n+- #77 — Verify integrated planning after trace removal (itself blocked by #76).\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": ".scratch/remove-original-decision-trace/issues/03-verify-and-optimize-planning-benchmarks.md", "project_id": 35, "relative_order": 3, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -20,4 +20,6 @@ After all active rules compare equally, earlier balance expiry and then earlier\n \n Only active rules drive placement decisions and preference comparisons; disabled or deleted optimization rules have no residual influence through fixed optimization stages or protected metrics. With no active rules, the planner adds no leave placements, even when balances are at risk of expiring, and retains declared non-working days. Final tie-breakers cannot independently trigger new placements.\n \n-Implementation is pending.\n+Implemented in the #70–#75 series. Saved-rule migration and functional verification\n+are covered by #75. Benchmark performance acceptance and any required optimization\n+are tracked separately in #78; the benchmark limits remain unchanged.\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "docs/adr/0008-user-controlled-planning-objectives.md", "project_id": 35, "relative_order": 4, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,5 +1,36 @@\n # Mobile leave-planner benchmark\n \n+## Composable optimization rules: current verification status\n+\n+The #70–#75 implementation uses explicit active optimization configurations in\n+the benchmark fixtures. The latest full functional coverage run passes 652 tests\n+across 34 files under the 2 GB Node heap limit, excluding the separate benchmark.\n+This does not establish a passing performance protocol.\n+\n+MR pipeline 320 passed all 652 functional tests in 109.43 seconds, then the\n+seven-scenario protocol timed out at its unchanged 300-second limit without an\n+out-of-memory failure. In an earlier diagnostic run, the loaded-year warm-up took\n+184.36 seconds and its first measured repetition began about 251.78 seconds into\n+the protocol. Those diagnostic timings precede the final period-projection cache\n+and the planned original-decision-trace removal, and are not a result for either.\n+\n+At the user's request, #75 finishes on saved-rule migration and functional\n+verification. #78 owns benchmark verification and implementation of further\n+optimizations when needed, after #76 removes tracing and #77 verifies the retained\n+behavior. All seven scenarios, one warm-up and two measured repetitions per\n+scenario, the 2 GB heap limit and the 300-second timeout remain required for #78.\n+At the user's request, CI runs the benchmark in a separate job with\n+`allow_failure: true` while #78 is open. Functional coverage tests and all other\n+required checks remain blocking. #78 must restore the required benchmark gate\n+after the unchanged protocol passes. A green pipeline during this exception\n+does not establish a passing benchmark. No automatic elapsed-time planning\n+cutoff is introduced.\n+\n+The results below document earlier implementations and protocols. They are\n+historical measurements rather than the performance result for composable rules.\n+\n+## Reference-phone protocol\n+\n Open the deployed application at `/benchmark` on the reference phone. Tap\n **Run benchmark**, wait for the seven scenarios to finish, then tap **Copy\n report** and save the tab-separated output with the date and build identifier.\n@@ -90,10 +121,10 @@ and each flow sent exactly one planning request. All 1,949 and 3,956 trace\n packets respectively were acknowledged, carrying 122,621 and 249,234 candidate\n records without truncation. Heartbeats continued during the producing runs.\n \n-| Horizon | Calendar usable | Later trace delivery | Placements | Maximum UI timer delay before calendar / during trace | Peak page heap before calendar / during trace | Peak Chrome process-tree RSS before calendar / during trace |\n-| --- | --- | --- | --- | --- | --- | --- |\n-| Two years | 5.08 s | 2.55 s | 60 | 1.47 s / 0.70 s | 22.7 / 314.6 MiB | 1,143.2 / 1,606.8 MiB |\n-| Three years | 10.86 s | 4.14 s | 90 | 2.11 s / 1.48 s | 22.9 / 597.6 MiB | 1,386.8 / 2,217.8 MiB |\n+| Horizon | Calendar usable | Later trace delivery | Placements | Maximum UI timer delay before calendar / during trace | Peak page heap before calendar / during trace | Peak Chrome process-tree RSS before calendar / during trace |\n+| ----------- | --------------- | -------------------- | ---------- | ----------------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------- |\n+| Two years | 5.08 s | 2.55 s | 60 | 1.47 s / 0.70 s | 22.7 / 314.6 MiB | 1,143.2 / 1,606.8 MiB |\n+| Three years | 10.86 s | 4.14 s | 90 | 2.11 s / 1.48 s | 22.9 / 597.6 MiB | 1,386.8 / 2,217.8 MiB |\n \n A 50 ms page timer measured extra event-loop delay and sampled available\n main-thread JS heap. RSS was sampled every 500 ms across that isolated Chrome\n@@ -111,10 +142,10 @@ completed stage. An editable input accepted focus while the worker remained\n active. Both flows kept a 44 px Cancel control, fit the viewport without\n horizontal overflow, and delivered the original trace after their outcome.\n \n-| Cancellation point | Request to outcome | Request to complete artifacts | Retained placements |\n-| --- | --- | --- | --- |\n-| Calendar preparation | 21.9 ms | 874.8 ms | 0 |\n-| Active holiday-week optimization, keyboard | 21.5 ms | 1,431.7 ms | 90 |\n+| Cancellation point | Request to outcome | Request to complete artifacts | Retained placements |\n+| ------------------------------------------ | ------------------ | ----------------------------- | ------------------- |\n+| Calendar preparation | 21.9 ms | 874.8 ms | 0 |\n+| Active holiday-week optimization, keyboard | 21.5 ms | 1,431.7 ms | 90 |\n \n No browser errors occurred. Cancellation issued one cancel request and no\n additional calculation. Separate tests cover late artifact errors and stale\n@@ -151,11 +182,11 @@ at the worker's terminal artifact delivery. The application's own calibration\n uses its request timestamp and `afterNextRender` endpoint as described in\n [planning-duration.md](../planning-duration.md).\n \n-| Horizon | Range before Calculate (with one local sample) | Observed calendar wait | Additional trace delivery | Range after completion | Placements |\n-| --- | --- | --- | --- | --- | --- |\n-| One year | 1–4 s | 1.74 s | 1.23 s | 1–5 s | 30 |\n-| Two years | 2–16 s | 5.08 s | 2.88 s | 2–16 s | 60 |\n-| Three years | 7–44 s | 11.03 s | 5.60 s | 6–39 s | 90 |\n+| Horizon | Range before Calculate (with one local sample) | Observed calendar wait | Additional trace delivery | Range after completion | Placements |\n+| ----------- | ---------------------------------------------- | ---------------------- | ------------------------- | ---------------------- | ---------- |\n+| One year | 1–4 s | 1.74 s | 1.23 s | 1–5 s | 30 |\n+| Two years | 2–16 s | 5.08 s | 2.88 s | 2–16 s | 60 |\n+| Three years | 7–44 s | 11.03 s | 5.60 s | 6–39 s | 90 |\n \n All three outcomes completed through `dates`, with no intermediate placements,\n implicit deadline, extra request or date movement. The three-year result\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "docs/benchmark/README.md", "project_id": 35, "relative_order": 5, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,286 @@\n+# Composable planning objective contract\n+\n+The common implementation for tickets #70–#75 is on `feature/optimization-rules-70-75`.\n+`src/app/services/planning-objectives.ts` evaluates supported configurations; rule names and\n+identifiers never enter the evaluator. Supplied and personal optimization rules share this\n+model, editor, persistence and ordered calculation pipeline.\n+\n+## Configuration\n+\n+`OptimizationConfiguration` contains `elements`, `conditions`, `measure`, `aggregation`,\n+`direction`, and, only for `work-sequence-deficit`, `thresholdDays`. Conditions are a list\n+of distinct selectors, combined with AND; an empty list selects every observed element.\n+Directions are `minimize` and `maximize`. The finite `OPTIMIZATION_CATALOG` contains the\n+following compatible combinations. Each row accepts any subset of its listed conditions.\n+\n+| Elements | Applicable conditions | Measure | Aggregations | Measure unit | Parameters |\n+| ---------------------- | ----------------------- | --------------------------- | ------------------------- | --------------------- | ------------------------------------------------------ |\n+| `leave-balances` | `at-risk` | `unplaced-quantity` | `sum`, `count`, `maximum` | working days | none |\n+| `public-holiday-weeks` | `complete` | `public-holiday-week-value` | `sum`, `count`, `maximum` | calendar-day distance | none |\n+| `time-off-periods` | none | `non-working-day-gain` | `sum`, `count`, `maximum` | calendar days | none |\n+| `work-sequences` | `internal`, `non-empty` | `work-sequence-length` | `sum`, `count`, `maximum` | working days | none |\n+| `work-sequences` | `internal`, `non-empty` | `work-sequence-deficit` | `sum`, `count`, `maximum` | working days | `thresholdDays`: positive safe integer in working days |\n+| `leave-placements` | `supporting` | `placement-count` | `sum`, `count`, `maximum` | count | none |\n+\n+`count` counts selected elements, including selected elements whose measured value is zero;\n+its unit is always count. `sum` and `maximum` aggregate the selected measured values.\n+All three return **zero on an empty collection**. An empty work sequence has zero deficit,\n+even if a configuration selects it. The maximum of an empty work-sequence collection is zero;\n+the existing optional average statistics keep their separate null semantics.\n+\n+`validateOptimizationConfiguration(unknown)` returns `{ valid: true, configuration }` or\n+`{ valid: false, code, message }`. Malformed values use `invalid-optimization-configuration`;\n+unsupported elements/measure/condition/aggregation/parameter combinations use\n+`unsupported-optimization-configuration`. Unknown fields, duplicate conditions, missing,\n+fractional, non-positive, non-finite and unsafe thresholds are rejected. Other measures\n+reject `thresholdDays`. Direct and worker calculations attach each configuration error to\n+its rule, including malformed sparse selector lists; they never replace it with a preset.\n+\n+For example, a personal rule can select internal non-empty work sequences, sum their\n+deficits at a threshold of three, and minimize the result. It uses the same measure as\n+the five-day preset. Another can maximize the longest sequence or count complete holiday\n+weeks; composition never dispatches by a preset identifier.\n+\n+## Six supplied recipes\n+\n+`OPTIMIZATION_PRESETS` provides configurations, without identities, display labels or enabled\n+states. `RuleService` wraps copies in named planning rules and persists the full configuration.\n+\n+| Export key | Elements and conditions | Measure and aggregation | Direction |\n+| ---------------------- | --------------------------------------- | ---------------------------------- | --------- |\n+| `unplacedAtRisk` | leave balances, at risk | unplaced quantity, sum | minimize |\n+| `holidayWeekValue` | public-holiday weeks, complete | public-holiday week value, sum | maximize |\n+| `nonWorkingDayGain` | time-off periods | non-working-day gain, sum | maximize |\n+| `longestWorkSequence` | work sequences, including horizon edges | work-sequence length, maximum | minimize |\n+| `shortSequenceDeficit` | internal non-empty work sequences | deficit at `thresholdDays: 5`, sum | minimize |\n+| `supportingPlacements` | leave placements, supporting | placement count, count | minimize |\n+\n+## Concrete observations and boundaries\n+\n+`OptimizationObservations` carries collections from one concrete valid plan:\n+\n+- Leave balances expose unplaced working-day quantity and the at-risk flag. Expiry on either\n+ the horizon start or its exclusive end is at risk, preserving the existing classification;\n+ placement dates themselves stay within the half-open horizon.\n+- Public-holiday weeks expose their weekday holiday value and whether every other working\n+ date is a placement or declared non-working day. Monday through Friday contributions are\n+ **1, 2, 3, 2, 1**; several holidays in one week are summed once in that week's observation.\n+ Ordinary fully declared weeks never become holiday weeks. A partial horizon only admits\n+ a week when every required date outside it is already declared, preserving the existing rule.\n+- Time-off periods carry distinct natural non-working dates; periods are disjoint and include\n+ adjacent weekends, holidays and declared days at either horizon edge. Placements and declared\n+ working days anchor periods but do not themselves contribute non-working-day gain.\n+- Work sequences carry a working-day length and an `internal` flag. Weekends and holidays\n+ neither count nor split them. Both horizon-edge sequences contribute to the maximum and\n+ are excluded by the `internal` condition. Internal zero-length observations contribute zero\n+ deficit and are excluded by `non-empty`.\n+- Leave placements expose their supporting classification. Declared days are fixed observations\n+ and do not consume balances or count as supporting placements.\n+\n+`evaluateOptimization(configuration, observations)` validates the configuration and evaluates\n+these collections. The core's `optimizationObservations(state, context, periods?)` builds the\n+collections once; `evaluateStateOptimization(configuration, state, context)` is the shared core\n+seam for a personal rule. The preset metrics call the same evaluator, with no second engine.\n+\n+## Ordered rule execution\n+\n+Named `type: 'optimization'` rules contain a full `configuration` and preference-only\n+force. Storage, editor buffers, direct calculation snapshots and worker transport copy\n+the nested configuration. The core executes only explicitly submitted active rules;\n+it never adds presets to a request.\n+\n+Obligations are solved jointly. Each active preference then runs in the displayed\n+rule order. Disabled rules are excluded before validation and search. A request\n+with no active rules preserves declared days and adds no placements, including\n+when balances are at risk of expiry. Statistics may still report preset metrics;\n+only the active configured objectives affect selection.\n+\n+The shared core seams are:\n+\n+- `activeObjectiveVector(state, context, throughIndex?)` evaluates active preferences\n+ in display order, with unique `optimization:` and `preference:`\n+ identities. Optimization measurements use their full configurations; calendar\n+ preferences measure actual matching dates/patterns.\n+- `evaluateRuleCandidate(before, candidate, context, throughIndex, dates, sourceDate?,\n+addition?, baseline?, beforeVector?, incumbentVector?)` validates mandatory type/date/pattern memberships and earned\n+ entitlement availability and compares the active prefix. Its comparison preserves\n+ the source state; technical selection facts compare with the actual current best\n+ candidate. It returns the valid state, its full vector and\n+ optional trace evaluation. Additions must improve an active prefix objective.\n+- `optimizeRulePlacements(state, context, throughIndex, allowAdd, rule?)` generates\n+ single additions/removals/moves, atomic balance reassignments and balance swaps.\n+ `relocateForAddition` handles augmenting chains when a scarce balance needs an\n+ occupied date. Complete typed calendar patterns are reassigned atomically too.\n+ Coordinated family bundles can pass through `evaluateRuleCandidate` and rank through\n+ `compareObligationPreviews(candidate, incumbent, context)` without fixed metric guards.\n+- `applyPreferenceStep` dispatches every optimization and calendar window through\n+ the same kernel. Earlier preferences replay when a later rule changes their state\n+ or creates an earned entitlement.\n+\n+Earned entitlements follow actual completed active producer patterns, including patterns\n+already fulfilled by another rule or declared days. Shared finalization reconciles those\n+rights before candidate comparisons, cancellation retention and unchanged-state caching.\n+Availability starts after the complete merged producing period; its own reward cannot\n+finance a placement inside that period. Earning is a validity consequence, rather than\n+an extra objective that an active configuration can suppress.\n+\n+`compareObjectiveValues`, `compareObjectiveLists` and `firstDifferentObjective`\n+serve both selection and explanation. Earlier balance expiry and placement dates\n+are final tie-breaks after all active objectives compare equally; they only reshape\n+existing placements. Equal expiry values are compared independently of arbitrary balance\n+identifiers, so earlier placement dates remain the next tie-break. Captured rule identities, names and configurations label the\n+result independently of subsequent editor changes.\n+\n+Loaded plans retain the established sampling strategy for flexible move destinations\n+above 24 placements, including non-working-adjacent, weekly and calendar-window dates.\n+Excluded move destinations are recorded as `not-examined`, never as proven rejected.\n+There is no automatic elapsed-time cutoff. Complete holiday weeks, joined time-off\n+periods and work-sequence changes are compared as coordinated valid bundles.\n+Moves that preserve every active objective can be pruned when their final tie-breaks\n+cannot improve. Per-iteration vectors are reused; preset statistics are materialized\n+only for selected incumbents and published plans.\n+\n+For large non-earned window obligation searches above the existing exact-branch\n+threshold, the joint feasibility search retains its existing limit. Feasible\n+solutions are ranked by actual active objectives and final ties; the first eight\n+receive full optimization previews. Other feasible solutions are recorded as\n+`not-examined`. Small searches and earned-entitlement chains keep all previews.\n+This deterministic sampling has no elapsed-time cutoff or user-facing setting.\n+\n+A deferred optimization addition is supporting only when it provides one of the\n+calendar benefits in the domain definition, rather than merely extending a period.\n+Holiday occurrences and eligible patterns are immutable per request and cached\n+independently of mutable placement states.\n+\n+## Saved rules and initialization\n+\n+`vacationRules` uses one versioned envelope: `{ version: 1, rules: [...] }`.\n+`RuleService` restores it synchronously before the first duration estimate or calculation.\n+A legacy array, including `[]`, receives loss prevention first, every original record in\n+its original relative order, then the other five presets. Each original raw record is\n+preserved, including names, IDs, dates, parameters, disabled state and a missing legacy\n+force. Getters interpret missing force as preference without rewriting that record.\n+Preset IDs use collision-free suffixes when a personal rule already uses a proposed ID.\n+New users receive the six active presets around the existing Samedi Malin and Christmas\n+calendar defaults.\n+\n+The migration and its version are written by one synchronous `setItem`; no separate\n+marker can succeed while the rules fail to save. A failed write leaves the original\n+key intact and permits a later complete save or a fresh reload to retry. Failed reads,\n+malformed saved data and unsupported versions disable writes for that service instance\n+so later editing cannot overwrite unknown persisted user data. Storage unavailable\n+in the runtime leaves an in-memory configuration usable.\n+\n+Every later edit, toggle, reorder or deletion saves the full versioned list. Versioned\n+empty lists stay empty; disabled and deleted presets stay that way. With no active\n+rules, eligible unused leave remains visible with its original expiry classification\n+and a translated explanation that the active planning rules justified no addition.\n+Physical availability, occupation, expiry and incomplete-calculation reasons keep\n+precedence where they apply. Declared days remain fixed and consume no leave.\n+\n+## Search and trace limits\n+\n+These are deterministic search limits, rather than claims of global optimality:\n+\n+- Above 24 placements, flexible moves examine the existing non-working-adjacent,\n+ declared-adjacent, weekly and calendar-window destinations. Other destinations\n+ retain `not-examined` trace records.\n+- Non-earned obligation searches whose estimated branch count exceeds 10,000 retain\n+ at most 4,096 feasible solutions. Large window searches rank them by the actual\n+ active vector and final ties, then fully preview the first eight; the other\n+ feasible solutions are marked `not-examined`. Earned chains and small searches\n+ retain all previews.\n+- Calendar bundles rank original donors once by the actual active vector of the\n+ source plan with each donor released, then retain that order during recursive\n+ allocation. They keep the first prefix-valid allocation and collapse equivalent\n+ donor tokens. Work-sequence bundles use the nearest center per balance and the\n+ first accepted allocation. These choices can miss another coordinated allocation.\n+- When a completed specialized bundle strictly improves the current active prefix,\n+ the kernel commits its full-vector best before scanning generic alternatives for\n+ the old state. The old generic neighborhood is marked `not-examined`, then bundles\n+ and generic candidates continue from the improved state. Earlier preferences replay\n+ and the final expiry/date pass still runs. This scheduling can make a better unseen\n+ old-state generic branch unreachable; it is an explicit heuristic rather than an\n+ exhaustive comparison of all bundles and moves.\n+- Additions require a strict improvement through the current rule. A custom\n+ maximum/minimize unplaced-quantity rule with two tied at-risk CP1 balances can\n+ therefore keep both unused: either single addition leaves the maximum at one,\n+ while a coordinated addition of both would reduce it to zero. This balance\n+ plateau has no specialized bundle generator; the supplied sum/minimize loss\n+ preset does consume both.\n+\n+A completely enumerated single obligation solution has no alternative to rank, so\n+its discarded full preference preview is skipped; the real ordered execution still\n+runs in full. Earlier rules reuse their completed evaluation only when the complete\n+ordered incoming state matches their last output, including balance quantities and\n+validity, earned activations, placement insertion order, supporting status and rule\n+provenance. The trace records that unchanged state as `not-examined` with the earlier\n+decisions retained. A candidate unable to beat a valid local incumbent already\n+offered to cancellation retention keeps its primary comparison but avoids a duplicate\n+global incumbent comparison. These are exact reuse decisions, not additional sampling.\n+At the first explicit sum/minimize quantity preference, complete single additions can\n+reuse an evaluated funding score when eligible at-risk balances have the same expiry\n+and matching signature across every enabled time-window rule, including obligations.\n+The first original-order funder is preserved; later equivalent alternatives are recorded\n+as `not-examined` without fabricated comparisons. This applies only without active\n+IF_THEN rules or earned activations, without a balance maximum objective, and with a\n+safe combined remaining quantity. Recursive bundles and augmenting allocation retain\n+every funding choice: equal current scores do not prove equivalent future capacity.\n+A first-position sum/minimize unplaced-quantity rule finishes its preference stage when\n+its reconciled value reaches zero. The same bound applies to a prefix consisting of\n+that zero quantity followed only by fully satisfied time-window preferences or maximizing\n+public-holiday-week preferences at their configured upper bound. Windows are capped at\n+their requested quantity. A holiday maximum is evaluated from the same immutable request\n+weeks, marking every week complete and using its configured sum, count or maximum;\n+partial horizon weeks retain the existing declaration and eligibility semantics. The whole bounded stage is recorded as\n+`not-examined`; later preferences, replay after actual state changes and the final\n+full-vector expiry/date pass still run. Other configurations and preference orders\n+retain their search. This schedules lower priorities later; it does not claim an\n+exhaustive full-vector search in the bounded stage.\n+\n+When every balance is exhausted and there is no active IF_THEN rule, a complete generic\n+iteration that finds no full-vector improvement can be reused for the identical ordered\n+state at a later preference. Explicit balance assignments use the same dates, validity,\n+provenance and configured move sampling regardless of the current rule. Rule-specific\n+bundles still run, and any balance, placement, supporting, provenance or activation change\n+invalidates reuse. Bound returns and interrupted iterations never admit a state. Reuse\n+is recorded as `not-examined` with the earlier sampled generic decisions retained; the\n+final expiry/date pass still examines its neighborhood.\n+\n+Captured trace vectors, scalar facts, placements, ordered date lists and deltas are immutable detached evidence. Bounded\n+request-local indexes share only identical complete values and metadata; the vector\n+index uses recorded date keys and holds at most 65,536 entries, including variants in\n+one bucket. Eviction changes allocation only, with every examined candidate and its\n+ordered factual fields retained. Mutable candidate shells and emitted replacement\n+snapshots remain independent. Search never reads these sharing indexes. Calendar facts also reuse a bounded 4,096-entry request-local cache keyed by the complete occupied date set; balance quantities, earned metadata, provenance and supporting classifications are refreshed separately. Removing a placement copies the placement map without editing surviving entries; later assignment and metadata edits still detach them. Candidate locations are resolved from the latest recorded decision only when a later update or selection needs them, avoiding a permanent index for observation-only candidates.\n+\n+Cancellation retains the best valid examined plan under the captured active vector\n+and its original trace. Counterfactual and explanation comparisons use that same\n+snapshot; later editor changes and delayed artifact delivery do not alter it.\n+An explicit caller-owned planning-work budget remains supported; the application\n+introduces no automatic duration-based stop.\n+\n+## Confirmed decisions and technical assumptions\n+\n+Confirmed by ADR 0008: one composable model for supplied and personal optimization rules;\n+preference-only force; the six recipes' existing business meanings; declared-day and horizon\n+semantics; user-controlled active preference order; expiry then date tie-breaks; preserving\n+saved user data. The integrated implementation replaces the former implicit policy\n+with explicit active rules and performs the one-time saved-data addition.\n+\n+The supported configuration boundary is only sum/count/maximum and both directions; empty aggregate\n+zero; deficit threshold is a positive working-day integer, initially five; every listed\n+compatible condition subset and aggregation is supported; no other filters or measures.\n+Public-holiday weights retain the existing business definition rather than becoming a parameter.\n+\n+## Verification scope\n+\n+Ticket #75 covers saved-rule migration and functional integration of #70–#75.\n+Performance acceptance and any further optimization are tracked in #78, after\n+original-decision-trace removal in #76 and functional verification in #77. The\n+seven-scenario benchmark, its warm-up and two measured repetitions, the 2 GB heap\n+limit and the 300-second timeout remain unchanged. CI runs the benchmark as a\n+separate non-blocking job at the user's request while #78 is open; functional\n+tests and other checks remain required. #78 must restore the required benchmark\n+gate after the protocol passes. Completing the functional migration or passing\n+CI during this exception does not establish a passing benchmark.\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "docs/planning-objectives.md", "project_id": 35, "relative_order": 6, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -41,10 +41,11 @@ describe('leave planner benchmark protocol', () => {\n \t\t\t\t\tString(rttRule.startDate) <= String(cpRule.endDate),\n \t\t\t).toBe(true);\n \t\tconst chain = scenarios.find((scenario) => scenario.name === 'chained earned entitlements');\n-\t\texpect(chain?.request.rules?.map((rule) => rule.id)).toEqual([\n-\t\t\t'wednesday-holidays',\n-\t\t\t'thursday-consumer',\n-\t\t]);\n+\t\texpect(\n+\t\t\tchain?.request.rules\n+\t\t\t\t?.filter(({ type }) => type !== 'optimization')\n+\t\t\t\t.map((rule) => rule.id),\n+\t\t).toEqual(['wednesday-holidays', 'thursday-consumer']);\n \n \t\tconst browserWindow = globalThis.window;\n \t\tvi.stubGlobal('window', undefined);\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/benchmark/leave-planner-benchmark.spec.ts", "project_id": 35, "relative_order": 7, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -4,6 +4,7 @@ import {\n \tPlanningRequest,\n \tPlanningTrace,\n } from '../services/leave-planner.service';\n+import { createOptimizationPresetRules } from '../services/rule-service';\n \n export interface BenchmarkScenario {\n \tname: string;\n@@ -47,7 +48,8 @@ const balance = (\n \n export function benchmarkScenarios(): BenchmarkScenario[] {\n \tconst horizon = { start: '2024-01-01', end: '2025-01-01' };\n-\treturn [\n+\tconst presets = createOptimizationPresetRules();\n+\tconst scenarios: BenchmarkScenario[] = [\n \t\t{\n \t\t\tname: 'representative year',\n \t\t\trequest: {\n@@ -169,6 +171,13 @@ export function benchmarkScenarios(): BenchmarkScenario[] {\n \t\t\t}),\n \t\t),\n \t];\n+\treturn scenarios.map((scenario) => ({\n+\t\t...scenario,\n+\t\trequest: {\n+\t\t\t...scenario.request,\n+\t\t\trules: [presets[0], ...scenario.request.rules, ...presets.slice(1)],\n+\t\t},\n+\t}));\n }\n \n function resultSummary(outcome: PlanningOutcome): {\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/benchmark/leave-planner-benchmark.ts", "project_id": 35, "relative_order": 8, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,3 +1,4 @@\n+import { createOptimizationPresetRules } from '../../services/rule-service';\n import { provideZonelessChangeDetection } from '@angular/core';\n import { ComponentFixture, TestBed } from '@angular/core/testing';\n import { vi } from 'vitest';\n@@ -407,6 +408,8 @@ function jointTrace(): PlanningTrace {\n \t};\n }\n \n+const presets = createOptimizationPresetRules();\n+\n describe('CalendarYear planning outcome boundary', () => {\n \tbeforeEach(() => localStorage.clear());\n \tafterEach(() => {\n@@ -1342,7 +1345,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\t\t);\n \t\t\tif (outcome.kind !== 'Plan') throw new Error(`Expected Plan, got ${outcome.kind}`);\n \t\t\tlocalStorage.setItem('leaveBalances', '[]');\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tawait TestBed.configureTestingModule({\n \t\t\t\timports: [CalendarYear],\n \t\t\t\tproviders: [provideZonelessChangeDetection()],\n@@ -1421,7 +1424,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\t\t);\n \t\t\tif (outcome.kind !== 'Plan') throw new Error(`Expected Plan, got ${outcome.kind}`);\n \t\t\tlocalStorage.setItem('leaveBalances', '[]');\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tawait TestBed.configureTestingModule({\n \t\t\t\timports: [CalendarYear],\n \t\t\t\tproviders: [provideZonelessChangeDetection()],\n@@ -1496,7 +1499,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\t\t\t\t\texpiryDate: placementDate,\n \t\t\t\t\t},\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays: [\n \t\t\t\t\t{ date: '2024-08-01', type: 'cp' as const },\n \t\t\t\t\t...(fixedAnchor ? [{ date: '2024-07-31', type: 'other' as const }] : []),\n@@ -1524,7 +1527,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\t\t\t),\n \t\t\t);\n \t\t\tlocalStorage.setItem('leaveBalances', '[]');\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tawait TestBed.configureTestingModule({\n \t\t\t\timports: [CalendarYear],\n \t\t\t\tproviders: [provideZonelessChangeDetection()],\n@@ -1582,7 +1585,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \tit('previews a growing and shrinking range across months, then saves it once on release', async () => {\n \t\tlocalStorage.setItem('app.language', '\"fr\"');\n \t\tlocalStorage.setItem('leaveBalances', '[]');\n-\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\tawait TestBed.configureTestingModule({\n \t\t\timports: [CalendarYear, UserInput],\n \t\t\tproviders: [provideZonelessChangeDetection()],\n@@ -1749,7 +1752,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \n \tit('edits declarations from configuration and restores the preceding result when switched off', async () => {\n \t\tlocalStorage.setItem('app.language', '\"fr\"');\n-\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\tlocalStorage.setItem('leaveBalances', '[]');\n \t\tlocalStorage.setItem(\n \t\t\t'declaredNonWorkingDays',\n@@ -1844,7 +1847,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t});\n \n \tit('keeps the preceding calendar until a submitted snapshot returns and ignores later edits', async () => {\n-\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\tlocalStorage.setItem('leaveBalances', '[]');\n \t\tawait TestBed.configureTestingModule({\n \t\t\timports: [CalendarYear, UserInput],\n@@ -1987,7 +1990,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\tlet now = 1_000;\n \t\tconst clock = vi.spyOn(performance, 'now').mockImplementation(() => now);\n \t\ttry {\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tconst pending = deferred();\n \t\t\tconst trace = deferred();\n \t\t\tconst { calendar, calculation } = calendarFor(\n@@ -2100,7 +2103,7 @@ describe('CalendarYear planning outcome boundary', () => {\n \t\tlet now = 1_000;\n \t\tconst clock = vi.spyOn(performance, 'now').mockImplementation(() => now);\n \t\ttry {\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tconst old = deferred();\n \t\t\tconst latest = deferred();\n \t\t\tconst { calendar, calculation } = calendarFor(plan);\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/components/calendar-year/calendar-year-planning.spec.ts", "project_id": 35, "relative_order": 9, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1536,6 +1536,24 @@ export class CalendarYear {\n \t}\n \n \tprotected objectiveCopy(id: string) {\n+\t\tif (id.startsWith('optimization:')) {\n+\t\t\tconst ruleId = id.slice('optimization:'.length);\n+\t\t\tconst rule = this.activeCalculation?.snapshot.rules.find(\n+\t\t\t\t(candidate) => candidate.id === ruleId,\n+\t\t\t);\n+\t\t\tconst copy = this.tr().planning.explanation.objectives['optimization'];\n+\t\t\treturn {\n+\t\t\t\t...copy,\n+\t\t\t\tlabel: copy.label\n+\t\t\t\t\t.replace('{rule}', this.ruleLabel(ruleId))\n+\t\t\t\t\t.replace(\n+\t\t\t\t\t\t'{summary}',\n+\t\t\t\t\t\trule && 'configuration' in rule\n+\t\t\t\t\t\t\t? this.translationService.optimizationSummary(rule.configuration)\n+\t\t\t\t\t\t\t: '',\n+\t\t\t\t\t),\n+\t\t\t};\n+\t\t}\n \t\tconst key = id.startsWith('preference:') ? 'preference' : id;\n \t\tconst copy = this.tr().planning.explanation.objectives[key];\n \t\tconst rule =\n@@ -1645,7 +1663,7 @@ export class CalendarYear {\n \t\tif (stage === 'validation') return 5;\n \t\tif (stage === 'obligations') return 20;\n \t\tif (stage === 'at-risk') return 35;\n-\t\tif (stage.startsWith('preference:')) return 50;\n+\t\tif (stage.startsWith('preference:') || stage.startsWith('optimization:')) return 50;\n \t\tif (stage === 'holiday-week-value') return 58;\n \t\tif (stage === 'non-working-day-gain') return 65;\n \t\tif (stage === 'longest-work-sequence') return 72;\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/components/calendar-year/calendar-year.ts", "project_id": 35, "relative_order": 10, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,241 @@\n+import { provideZonelessChangeDetection } from '@angular/core';\n+import { ComponentFixture, TestBed } from '@angular/core/testing';\n+import { By } from '@angular/platform-browser';\n+import { MatExpansionPanel } from '@angular/material/expansion';\n+import { RulesPanel } from './rules-panel';\n+import { RuleService, RuleType, type OptimizationRule } from '../../services/rule-service';\n+import { TranslationService } from '../../services/translation-service';\n+import {\n+\tOPTIMIZATION_PRESETS,\n+\ttype OptimizationConfiguration,\n+} from '../../services/planning-objectives';\n+import { calculatePlanningInternal } from '../../services/leave-planner.core';\n+\n+describe('calendar rule editing and persistence', () => {\n+\tlet fixture: ComponentFixture;\n+\tlet service: RuleService;\n+\tlet translations: TranslationService;\n+\n+\tasync function openEditor() {\n+\t\tawait TestBed.configureTestingModule({\n+\t\t\timports: [RulesPanel],\n+\t\t\tproviders: [provideZonelessChangeDetection()],\n+\t\t}).compileComponents();\n+\t\tservice = TestBed.inject(RuleService);\n+\t\ttranslations = TestBed.inject(TranslationService);\n+\t\ttranslations.setLanguage('fr');\n+\t\tfixture = TestBed.createComponent(RulesPanel);\n+\t\tfixture.detectChanges();\n+\t\tfixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open();\n+\t\tawait fixture.whenStable();\n+\t\tfixture.detectChanges();\n+\t}\n+\n+\tbeforeEach(async () => {\n+\t\tlocalStorage.clear();\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n+\t\tawait openEditor();\n+\t\tfor (const rule of service.rules) service.deleteRule(rule.id);\n+\t\tfixture.detectChanges();\n+\t});\n+\tafterEach(() => localStorage.clear());\n+\n+\tasync function select(label: string, value: string) {\n+\t\tconst fields: HTMLElement[] = Array.from(\n+\t\t\tfixture.nativeElement.querySelectorAll('mat-form-field'),\n+\t\t);\n+\t\tconst field = fields.find(\n+\t\t\t(candidate) => candidate.querySelector('mat-label')?.textContent?.trim() === label,\n+\t\t);\n+\t\tconst control = field?.querySelector('mat-select');\n+\t\tif (!control) throw new Error(`Missing labelled control: ${label}`);\n+\t\tconst labels = (control.getAttribute('aria-labelledby') ?? '')\n+\t\t\t.split(/\\s+/)\n+\t\t\t.map((id) => document.getElementById(id)?.textContent?.trim());\n+\t\texpect(labels).toContain(label);\n+\t\tcontrol.click();\n+\t\tawait fixture.whenStable();\n+\t\tconst option = Array.from(document.querySelectorAll('mat-option')).find(\n+\t\t\t(candidate) => candidate.textContent?.trim() === value,\n+\t\t);\n+\t\tif (!option) throw new Error(`Missing translated option: ${value}`);\n+\t\toption.click();\n+\t\tdocument.querySelector('.cdk-overlay-backdrop')?.click();\n+\t\tawait fixture.whenStable();\n+\t\tfixture.detectChanges();\n+\t}\n+\n+\tasync function add(name: string, configuration: OptimizationConfiguration) {\n+\t\tconst tr = translations.tr().rules;\n+\t\tconst buttons: HTMLButtonElement[] = Array.from(\n+\t\t\tfixture.nativeElement.querySelectorAll('.add-buttons button'),\n+\t\t);\n+\t\tbuttons.find((button) => button.textContent?.includes(tr.optimization.newRule))!.click();\n+\t\tawait fixture.whenStable();\n+\t\tconst nameInput: HTMLInputElement =\n+\t\t\tfixture.nativeElement.querySelector('.rule-editor input');\n+\t\tnameInput.value = name;\n+\t\tnameInput.dispatchEvent(new Event('input', { bubbles: true }));\n+\t\tawait select(\n+\t\t\ttr.optimization.elementsLabel,\n+\t\t\ttr.optimization.elements[configuration.elements],\n+\t\t);\n+\t\tfor (const condition of configuration.conditions)\n+\t\t\tawait select(tr.optimization.conditionsLabel, tr.optimization.conditions[condition]);\n+\t\tawait select(\n+\t\t\ttr.optimization.aggregationLabel,\n+\t\t\ttr.optimization.aggregations[configuration.aggregation],\n+\t\t);\n+\t\tawait select(\n+\t\t\ttr.optimization.directionLabel,\n+\t\t\ttr.optimization.directions[configuration.direction],\n+\t\t);\n+\t\tconst actions: HTMLButtonElement[] = Array.from(\n+\t\t\tfixture.nativeElement.querySelectorAll('.editor-actions button'),\n+\t\t);\n+\t\tactions.find((button) => button.textContent?.trim() === tr.add)!.click();\n+\t\tawait fixture.whenStable();\n+\t\tfixture.detectChanges();\n+\t}\n+\n+\tfunction calculate() {\n+\t\tlet objectiveValues: readonly { id: string; value: number | string }[] = [];\n+\t\tconst plan = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\tcalculationDate: '2024-04-01',\n+\t\t\t\thorizon: { start: '2024-04-29', end: '2024-05-18' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 3,\n+\t\t\t\t\t\tavailableFrom: '2024-04-29',\n+\t\t\t\t\t\texpiryDate: '2025-01-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules: service.rules,\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t({ explanation }) => {\n+\t\t\t\tif (explanation?.kind === 'PlanExplanation')\n+\t\t\t\t\tobjectiveValues = explanation.placements[0]?.objectiveVector.objectives ?? [];\n+\t\t\t},\n+\t\t);\n+\t\tif (plan.kind !== 'Plan')\n+\t\t\tthrow new Error('Expected a plan from saved editor configuration');\n+\t\treturn { plan, objectiveValues };\n+\t}\n+\n+\tit('creates both recipes, reverses their order, edits a compatible aggregation and restores it on reload', async () => {\n+\t\tawait add('Mes semaines fériées', OPTIMIZATION_PRESETS.holidayWeekValue);\n+\t\tawait add('Mes week-ends', OPTIMIZATION_PRESETS.nonWorkingDayGain);\n+\t\texpect(calculate().plan.metrics).toMatchObject({\n+\t\t\tholidayWeekValue: 5,\n+\t\t\tnonWorkingDayGain: 6,\n+\t\t});\n+\t\tconst items: HTMLElement[] = Array.from(\n+\t\t\tfixture.nativeElement.querySelectorAll('.rule-item'),\n+\t\t);\n+\t\titems[1].querySelector('.rule-actions button')!.click();\n+\t\tawait fixture.whenStable();\n+\t\tfixture.detectChanges();\n+\t\texpect(calculate().plan.metrics).toMatchObject({\n+\t\t\tholidayWeekValue: 0,\n+\t\t\tnonWorkingDayGain: 9,\n+\t\t});\n+\t\tconst holiday = service.rules.find(\n+\t\t\t(rule): rule is OptimizationRule =>\n+\t\t\t\trule.type === RuleType.OPTIMIZATION &&\n+\t\t\t\trule.configuration.elements === 'public-holiday-weeks',\n+\t\t)!;\n+\t\tfixture.componentInstance.startEdit(holiday, new Event('click'));\n+\t\tawait fixture.whenStable();\n+\t\tawait select(\n+\t\t\ttranslations.tr().rules.optimization.aggregationLabel,\n+\t\t\ttranslations.tr().rules.optimization.aggregations.count,\n+\t\t);\n+\t\tfixture.componentInstance.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\tawait expect\n+\t\t\t.poll(\n+\t\t\t\t() =>\n+\t\t\t\t\tJSON.parse(localStorage.getItem('vacationRules')!).rules[1]?.configuration\n+\t\t\t\t\t\t?.aggregation,\n+\t\t\t)\n+\t\t\t.toBe('count');\n+\t\tconst saved = service.rules;\n+\t\tTestBed.resetTestingModule();\n+\t\tawait openEditor();\n+\t\texpect(service.rules).toEqual(saved);\n+\t\texpect(calculate().plan.metrics).toMatchObject({\n+\t\t\tholidayWeekValue: 0,\n+\t\t\tnonWorkingDayGain: 9,\n+\t\t});\n+\t\tfixture.componentInstance.moveRule(1, -1, new Event('click'));\n+\t\tconst edited = calculate();\n+\t\texpect(edited.plan.metrics.holidayWeekValue).toBe(5);\n+\t\texpect(\n+\t\t\tedited.objectiveValues.find(\n+\t\t\t\t(objective) => objective.id === `optimization:${holiday.id}`,\n+\t\t\t)?.value,\n+\t\t).toBe(1);\n+\t});\n+\n+\tit('creates economy, edits its name, moves it with the focusable control and restores disable/delete choices', async () => {\n+\t\tawait add('Mes semaines fériées', OPTIMIZATION_PRESETS.holidayWeekValue);\n+\t\tawait add('Économiser les jours d’appoint', OPTIMIZATION_PRESETS.supportingPlacements);\n+\t\tconst economy = service.rules[1];\n+\t\texpect(economy).toMatchObject({\n+\t\t\tforce: 'preference',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t});\n+\t\texpect(calculate().plan.metrics.supportingPlacements).toBe(3);\n+\t\tconst move: HTMLButtonElement = fixture.nativeElement\n+\t\t\t.querySelectorAll('.rule-item')[1]\n+\t\t\t.querySelector('.rule-actions button');\n+\t\tmove.focus();\n+\t\texpect(document.activeElement).toBe(move);\n+\t\tmove.click();\n+\t\tawait fixture.whenStable();\n+\t\texpect(calculate().plan.placements).toEqual([]);\n+\n+\t\tfixture.componentInstance.startEdit(service.rules[0], new Event('click'));\n+\t\tawait fixture.whenStable();\n+\t\tconst input: HTMLInputElement = fixture.nativeElement.querySelector('.rule-editor input');\n+\t\tinput.value = 'Mes jours conservés';\n+\t\tinput.dispatchEvent(new Event('input', { bubbles: true }));\n+\t\tfixture.componentInstance.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\tconst toggle: HTMLButtonElement = fixture.nativeElement\n+\t\t\t.querySelector('.rule-item')\n+\t\t\t.querySelector('button[role=\"switch\"]');\n+\t\ttoggle.click();\n+\t\tawait fixture.whenStable();\n+\t\texpect(calculate().plan.metrics.supportingPlacements).toBe(3);\n+\t\tawait expect\n+\t\t\t.poll(() => JSON.parse(localStorage.getItem('vacationRules')!).rules[0]?.enabled)\n+\t\t\t.toBe(false);\n+\t\tconst saved = service.rules;\n+\t\tTestBed.resetTestingModule();\n+\t\tawait openEditor();\n+\t\texpect(service.rules).toEqual(saved);\n+\t\texpect(service.rules[0]).toMatchObject({ id: economy.id, name: 'Mes jours conservés' });\n+\t\texpect(calculate().plan.metrics.supportingPlacements).toBe(3);\n+\t\tfixture.componentInstance.toggleRule(economy.id);\n+\t\tawait fixture.whenStable();\n+\t\texpect(calculate().plan.placements).toEqual([]);\n+\t\tconst remove: HTMLButtonElement = fixture.nativeElement\n+\t\t\t.querySelector('.rule-item')\n+\t\t\t.querySelector(`[aria-label=\"${translations.tr().rules.deleteRule}\"]`);\n+\t\tremove.click();\n+\t\tawait fixture.whenStable();\n+\t\texpect(calculate().plan.metrics.supportingPlacements).toBe(3);\n+\t\tawait expect\n+\t\t\t.poll(() => JSON.parse(localStorage.getItem('vacationRules')!).rules.length)\n+\t\t\t.toBe(1);\n+\t\tTestBed.resetTestingModule();\n+\t\tawait openEditor();\n+\t\texpect(service.rules.map(({ id }) => id)).not.toContain(economy.id);\n+\t\texpect(calculate().plan.metrics.supportingPlacements).toBe(3);\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/components/rules-panel/calendar-rule-editor.spec.ts", "project_id": 35, "relative_order": 11, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -183,6 +183,8 @@\n \t\t\t\t\t\t\t\t\t\n \t\t\t\t\t\t\t\t\n \t\t\t\t\t\t\t\n+\t\t\t\t\t\t} @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) {\n+\t\t\t\t\t\t\t\n \t\t\t\t\t\t} @else {\n \t\t\t\t\t\t\t
\n \t\t\t\t\t\t\t\t\n@@ -239,6 +241,9 @@\n \t\t\t\t\t\t\t
\n \t\t\t\t\t\t}\n \n+\t\t\t\t\t\t@if (validationError()) {\n+\t\t\t\t\t\t\t

{{ validationError() }}

\n+\t\t\t\t\t\t}\n \t\t\t\t\t\t
\n \t\t\t\t\t\t\t
\n+\t\t\t\t\t} @else if ($any(editBuffer).type === RuleType.OPTIMIZATION) {\n+\t\t\t\t\t\t\n \t\t\t\t\t} @else {\n \t\t\t\t\t\t
\n \t\t\t\t\t\t\t\n@@ -394,6 +401,9 @@\n \t\t\t\t\t\t
\n \t\t\t\t\t}\n \n+\t\t\t\t\t@if (validationError()) {\n+\t\t\t\t\t\t

{{ validationError() }}

\n+\t\t\t\t\t}\n \t\t\t\t\t
\n \t\t\t\t\t\t\n \t\t\t\t\t\t\n+\t\t\t\n \t\t
\n \t\n \n+\n+\n+\t@if (optimizationConfiguration; as configuration) {\n+\t\t
\n+\t\t\t\n+\t\t\t\t{{ tr().rules.optimization.elementsLabel }}\n+\t\t\t\t\n+\t\t\t\t\t@for (elements of optimizationElements; track elements) {\n+\t\t\t\t\t\t{{\n+\t\t\t\t\t\t\ttr().rules.optimization.elements[elements]\n+\t\t\t\t\t\t}}\n+\t\t\t\t\t}\n+\t\t\t\t\n+\t\t\t\n+\t\t\t\n+\t\t\t\t{{ tr().rules.optimization.measureLabel }}\n+\t\t\t\t\n+\t\t\t\t\t@for (row of optimizationMeasures; track row.measure) {\n+\t\t\t\t\t\t{{\n+\t\t\t\t\t\t\ttr().rules.optimization.measures[row.measure]\n+\t\t\t\t\t\t}}\n+\t\t\t\t\t}\n+\t\t\t\t\n+\t\t\t\n+\t\t
\n+\t\t@if (optimizationConditions.length) {\n+\t\t\t\n+\t\t\t\t{{ tr().rules.optimization.conditionsLabel }}\n+\t\t\t\t\n+\t\t\t\t\t@for (condition of optimizationConditions; track condition) {\n+\t\t\t\t\t\t{{\n+\t\t\t\t\t\t\ttr().rules.optimization.conditions[condition]\n+\t\t\t\t\t\t}}\n+\t\t\t\t\t}\n+\t\t\t\t\n+\t\t\t\n+\t\t}\n+\t\t
\n+\t\t\t\n+\t\t\t\t{{ tr().rules.optimization.aggregationLabel }}\n+\t\t\t\t\n+\t\t\t\t\t@for (aggregation of optimizationAggregations; track aggregation) {\n+\t\t\t\t\t\t{{\n+\t\t\t\t\t\t\ttr().rules.optimization.aggregations[aggregation]\n+\t\t\t\t\t\t}}\n+\t\t\t\t\t}\n+\t\t\t\t\n+\t\t\t\n+\t\t\t\n+\t\t\t\t{{ tr().rules.optimization.directionLabel }}\n+\t\t\t\t\n+\t\t\t\t\t@for (direction of optimizationDirections; track direction) {\n+\t\t\t\t\t\t{{\n+\t\t\t\t\t\t\ttr().rules.optimization.directions[direction]\n+\t\t\t\t\t\t}}\n+\t\t\t\t\t}\n+\t\t\t\t\n+\t\t\t\n+\t\t\t@if (configuration.measure === 'work-sequence-deficit') {\n+\t\t\t\t\n+\t\t\t\t\t{{ tr().rules.optimization.thresholdLabel }}\n+\t\t\t\t\t\n+\t\t\t\t\n+\t\t\t}\n+\t\t
\n+\t}\n+
\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/components/rules-panel/rules-panel.html", "project_id": 35, "relative_order": 12, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -7,6 +7,8 @@ import { By } from '@angular/platform-browser';\n import { CdkDragDrop, CdkDropList } from '@angular/cdk/drag-drop';\n import { LiveAnnouncer } from '@angular/cdk/a11y';\n import { vi } from 'vitest';\n+import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';\n+import { MatExpansionPanel } from '@angular/material/expansion';\n \n describe('RulesPanel', () => {\n \tlet component: RulesPanel;\n@@ -36,7 +38,7 @@ describe('RulesPanel', () => {\n \t});\n \n \tit('should display initial rules from service', () => {\n-\t\texpect(component.rules.length).toBe(2);\n+\t\texpect(component.rules.length).toBe(8);\n \t});\n \n \tit('should start adding new If-Then rule', () => {\n@@ -116,6 +118,69 @@ describe('RulesPanel', () => {\n \t\texpect(component.rules[0].id).toBe(secondRuleId);\n \t});\n \n+\tit('creates, edits and moves an optimization using the keyboard controls with preference-only mode', async () => {\n+\t\tfixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open();\n+\t\tcomponent.startAddNew(RuleType.OPTIMIZATION);\n+\t\tfixture.detectChanges();\n+\t\texpect(component['forceOptions'].map((option) => option.value)).toEqual(['preference']);\n+\t\texpect(fixture.nativeElement.textContent).toContain('Éléments du planning');\n+\t\tcomponent['editBuffer'].name = 'Mes pertes';\n+\t\tcomponent.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\tconst rule = component.rules.at(-1)!;\n+\t\texpect(rule).toMatchObject({\n+\t\t\tname: 'Mes pertes',\n+\t\t\ttype: RuleType.OPTIMIZATION,\n+\t\t\tforce: 'preference',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t});\n+\t\texpect(component.getRuleSummary(rule)).toContain('Quantité non placée');\n+\t\tconst announce = vi.spyOn(TestBed.inject(LiveAnnouncer), 'announce').mockResolvedValue();\n+\t\tconst buttons = fixture.nativeElement.querySelectorAll('.rule-item');\n+\t\tconst moveUp: HTMLButtonElement =\n+\t\t\tbuttons[buttons.length - 1].querySelector('.rule-actions button');\n+\t\tmoveUp.focus();\n+\t\tmoveUp.click();\n+\t\tawait fixture.whenStable();\n+\t\texpect(component.rules[7].id).toBe(rule.id);\n+\t\texpect(document.activeElement).toBe(moveUp);\n+\t\texpect(announce).toHaveBeenCalledWith('Mes pertes : position 8 sur 9.');\n+\t\tcomponent.startEdit(rule, new Event('click'));\n+\t\tcomponent['editBuffer'].name = 'Pertes modifiées';\n+\t\tcomponent.saveEdit();\n+\t\texpect(component.rules[7].name).toBe('Pertes modifiées');\n+\t\tcomponent.toggleRule(rule.id);\n+\t\texpect(component.rules[7].enabled).toBe(false);\n+\t\tcomponent.deleteRule(rule.id, new Event('click'));\n+\t\texpect(component.rules.some((candidate) => candidate.id === rule.id)).toBe(false);\n+\t});\n+\n+\tit('keeps saved optimization parameters when an edit is cancelled and reports invalid parameters', () => {\n+\t\tcomponent.startAddNew(RuleType.OPTIMIZATION);\n+\t\tcomponent.saveEdit();\n+\t\tconst rule = component.rules.at(-1)!;\n+\t\tcomponent.startEdit(rule, new Event('click'));\n+\t\tconst configuration = component['optimizationConfiguration']!;\n+\t\tconfiguration.conditions = [];\n+\t\tcomponent.cancelEdit();\n+\t\texpect(component.rules.at(-1)).toMatchObject({\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t});\n+\t\tcomponent.startEdit(rule, new Event('click'));\n+\t\tcomponent.changeOptimizationMeasure('work-sequence-deficit');\n+\t\tconst invalid = component['optimizationConfiguration'];\n+\t\tif (invalid?.measure !== 'work-sequence-deficit') throw new Error('Expected deficit');\n+\t\tinvalid.thresholdDays = 0;\n+\t\tcomponent.saveEdit();\n+\t\tfixture.detectChanges();\n+\t\texpect(fixture.nativeElement.querySelector('[role=\"alert\"]').textContent).toContain(\n+\t\t\t'seuil entier positif',\n+\t\t);\n+\t\texpect(component.rules.at(-1)).toMatchObject({\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t});\n+\t});\n+\n \tit('keeps cancelled drops unchanged and announces the position after a completed drop', () => {\n \t\tconst initialIds = component.rules.map((rule) => rule.id);\n \t\tconst movedName = component.rules[0].name;\n@@ -133,8 +198,12 @@ describe('RulesPanel', () => {\n \t\texpect(announce).not.toHaveBeenCalled();\n \n \t\tlist.dropped.emit({ ...drop, isPointerOverContainer: true });\n-\t\texpect(component.rules.map((rule) => rule.id)).toEqual([...initialIds].reverse());\n-\t\texpect(announce).toHaveBeenCalledWith(`${movedName} : position 2 sur 2.`);\n+\t\texpect(component.rules.map((rule) => rule.id)).toEqual([\n+\t\t\tinitialIds[1],\n+\t\t\tinitialIds[0],\n+\t\t\t...initialIds.slice(2),\n+\t\t]);\n+\t\texpect(announce).toHaveBeenCalledWith(`${movedName} : position 2 sur 8.`);\n \t\t// CDK restores the original DOM before emitting dropped. The new order must\n \t\t// be rendered before this callback returns, without waiting for another frame.\n \t\texpect(fixture.nativeElement.querySelectorAll('.rule-name')[1].textContent).toContain(\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/components/rules-panel/rules-panel.spec.ts", "project_id": 35, "relative_order": 13, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -11,6 +11,7 @@ import {\n \tRuleType,\n \tIfThenRule,\n \tTimeWindowRule,\n+\tOptimizationRule,\n \tVacationRule,\n \tPlacementStrategy,\n } from '../../services/rule-service';\n@@ -25,7 +26,15 @@ import { MatInputModule } from '@angular/material/input';\n import { MatSelectModule } from '@angular/material/select';\n import { MatDatepickerModule } from '@angular/material/datepicker';\n import { FormsModule } from '@angular/forms';\n+import { NgTemplateOutlet } from '@angular/common';\n import { LiveAnnouncer } from '@angular/cdk/a11y';\n+import {\n+\tOPTIMIZATION_CATALOG,\n+\tOPTIMIZATION_PRESETS,\n+\tvalidateOptimizationConfiguration,\n+\ttype OptimizationElements,\n+\ttype OptimizationMeasure,\n+} from '../../services/planning-objectives';\n \n import { DateAdapter } from '@angular/material/core';\n import { DAY_FIRST_DATE_PROVIDERS } from '../../shared/day-first-date-adapter';\n@@ -43,6 +52,7 @@ import { CdkDragDrop, CdkDropList, CdkDrag, CdkDragHandle } from '@angular/cdk/d\n \t\tMatSelectModule,\n \t\tMatDatepickerModule,\n \t\tFormsModule,\n+\t\tNgTemplateOutlet,\n \t\tCdkDropList,\n \t\tCdkDrag,\n \t\tCdkDragHandle,\n@@ -74,10 +84,67 @@ export class RulesPanel {\n \tprotected readonly rewardDayTypes = Object.values(SelectableDayType).filter(\n \t\t(t) => t !== SelectableDayType.ANY,\n \t);\n-\tprotected readonly forceOptions = [\n-\t\t{ value: 'obligation' as const, label: () => this.tr().rules.obligation },\n-\t\t{ value: 'preference' as const, label: () => this.tr().rules.preference },\n+\tprotected get forceOptions() {\n+\t\tconst preference = {\n+\t\t\tvalue: 'preference' as const,\n+\t\t\tlabel: () => this.tr().rules.preference,\n+\t\t};\n+\t\treturn this.editBuffer.type === RuleType.OPTIMIZATION\n+\t\t\t? [preference]\n+\t\t\t: [\n+\t\t\t\t\t{ value: 'obligation' as const, label: () => this.tr().rules.obligation },\n+\t\t\t\t\tpreference,\n+\t\t\t\t];\n+\t}\n+\tprotected readonly optimizationElements = [\n+\t\t...new Set(OPTIMIZATION_CATALOG.map((row) => row.elements)),\n \t];\n+\tprotected get optimizationConfiguration() {\n+\t\treturn this.editBuffer.type === RuleType.OPTIMIZATION\n+\t\t\t? this.editBuffer.configuration\n+\t\t\t: undefined;\n+\t}\n+\tprotected get optimizationMeasures() {\n+\t\treturn OPTIMIZATION_CATALOG.filter(\n+\t\t\t(row) => row.elements === this.optimizationConfiguration?.elements,\n+\t\t);\n+\t}\n+\tprotected get optimizationConditions() {\n+\t\treturn (\n+\t\t\tthis.optimizationMeasures.find(\n+\t\t\t\t(row) => row.measure === this.optimizationConfiguration?.measure,\n+\t\t\t)?.conditions ?? []\n+\t\t);\n+\t}\n+\tprotected readonly optimizationAggregations = ['sum', 'count', 'maximum'] as const;\n+\tprotected readonly optimizationDirections = ['minimize', 'maximize'] as const;\n+\tprotected validationError = signal('');\n+\n+\tpublic changeOptimizationElements(elements: OptimizationElements) {\n+\t\tthis.changeOptimizationMeasure(\n+\t\t\tOPTIMIZATION_CATALOG.find((row) => row.elements === elements)!.measure,\n+\t\t);\n+\t}\n+\n+\tpublic changeOptimizationMeasure(measure: OptimizationMeasure) {\n+\t\tif (this.editBuffer.type !== RuleType.OPTIMIZATION) return;\n+\t\tconst row = OPTIMIZATION_CATALOG.find((item) => item.measure === measure)!;\n+\t\tconst previous = this.editBuffer.configuration;\n+\t\tconst conditions: readonly string[] = row.conditions;\n+\t\tthis.editBuffer.configuration = {\n+\t\t\telements: row.elements,\n+\t\t\tconditions:\n+\t\t\t\tprevious?.conditions.filter((condition) => conditions.includes(condition)) ?? [],\n+\t\t\taggregation: previous?.aggregation ?? 'sum',\n+\t\t\tdirection: previous?.direction ?? 'minimize',\n+\t\t\t...(measure === 'work-sequence-deficit'\n+\t\t\t\t? {\n+\t\t\t\t\t\tmeasure,\n+\t\t\t\t\t\tthresholdDays: previous?.measure === measure ? previous.thresholdDays : 5,\n+\t\t\t\t\t}\n+\t\t\t\t: { measure }),\n+\t\t};\n+\t}\n \n \tprotected get daysOfWeek() {\n \t\tconst tr = this.tr();\n@@ -128,9 +195,20 @@ export class RulesPanel {\n \n \tpublic moveRule(index: number, offset: -1 | 1, event: Event) {\n \t\tevent.stopPropagation();\n+\t\tconst trigger = event.currentTarget;\n \t\tconst destination = index + offset;\n-\t\tif (destination >= 0 && destination < this.rules.length)\n+\t\tif (destination >= 0 && destination < this.rules.length) {\n \t\t\tthis.reorderRule(index, destination);\n+\t\t\tthis.changeDetector.detectChanges();\n+\t\t\tif (trigger instanceof HTMLButtonElement) {\n+\t\t\t\tconst next = trigger.disabled\n+\t\t\t\t\t? trigger.parentElement?.querySelector(\n+\t\t\t\t\t\t\t'button:not([disabled])',\n+\t\t\t\t\t\t)\n+\t\t\t\t\t: trigger;\n+\t\t\t\tnext?.focus();\n+\t\t\t}\n+\t\t}\n \t}\n \n \tprivate reorderRule(from: number, to: number) {\n@@ -152,16 +230,29 @@ export class RulesPanel {\n \t\tevent.stopPropagation();\n \t\tthis.editingRuleId.set(rule.id);\n \t\tthis.isAddingNew.set(false);\n-\t\tthis.editBuffer = { ...rule };\n+\t\tthis.editBuffer = structuredClone(rule);\n+\t\tthis.validationError.set('');\n \t}\n \n \tpublic cancelEdit() {\n \t\tthis.editingRuleId.set(null);\n \t\tthis.isAddingNew.set(false);\n \t\tthis.editBuffer = {};\n+\t\tthis.validationError.set('');\n \t}\n \n \tpublic saveEdit() {\n+\t\tif (!this.editBuffer.name?.trim()) {\n+\t\t\tthis.validationError.set(this.tr().rules.optimization.nameRequired);\n+\t\t\treturn;\n+\t\t}\n+\t\tif (this.editBuffer.type === RuleType.OPTIMIZATION) {\n+\t\t\tif (!validateOptimizationConfiguration(this.editBuffer.configuration).valid) {\n+\t\t\t\tthis.validationError.set(this.tr().rules.optimization.invalidConfiguration);\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\tthis.editBuffer.force = 'preference';\n+\t\t}\n \t\tif (this.editBuffer.id) {\n \t\t\tthis.ruleService.updateRule(this.editBuffer as VacationRule);\n \t\t} else {\n@@ -183,6 +274,7 @@ export class RulesPanel {\n \t\tthis.isAddingNew.set(true);\n \t\tthis.editingRuleId.set(null);\n \t\tthis.newRuleType.set(type);\n+\t\tthis.validationError.set('');\n \n \t\tif (type === RuleType.IF_THEN) {\n \t\t\tthis.editBuffer = {\n@@ -196,6 +288,13 @@ export class RulesPanel {\n \t\t\t\trewardDays: 1,\n \t\t\t\trewardType: SelectableDayType.OTHER,\n \t\t\t} as Partial;\n+\t\t} else if (type === RuleType.OPTIMIZATION) {\n+\t\t\tthis.editBuffer = {\n+\t\t\t\tname: this.tr().rules.optimization.defaultName,\n+\t\t\t\ttype,\n+\t\t\t\tforce: 'preference',\n+\t\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),\n+\t\t\t} satisfies Partial;\n \t\t} else {\n \t\t\tthis.editBuffer = {\n \t\t\t\tname: this.tr().rules.defaultNewPeriodName,\n@@ -216,6 +315,8 @@ export class RulesPanel {\n \n \tpublic getRuleSummary(rule: VacationRule): string {\n \t\tconst tr = this.tr();\n+\t\tif (rule.type === RuleType.OPTIMIZATION)\n+\t\t\treturn this.translationService.optimizationSummary(rule.configuration);\n \t\tif (rule.type === RuleType.IF_THEN) {\n \t\t\tconst ifThen = rule as IfThenRule;\n \t\t\tconst dayLabel = this.daysOfWeek.find((d) => d.value === ifThen.dayOfWeek)?.label ?? '';\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/components/rules-panel/rules-panel.ts", "project_id": 35, "relative_order": 14, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,172 @@\n+import { provideZonelessChangeDetection } from '@angular/core';\n+import { TestBed, type ComponentFixture } from '@angular/core/testing';\n+import { By } from '@angular/platform-browser';\n+import { MatExpansionPanel } from '@angular/material/expansion';\n+import { vi } from 'vitest';\n+import { RuleService, RuleType } from '../../services/rule-service';\n+import { TranslationService } from '../../services/translation-service';\n+import { calculatePlanningInternal } from '../../services/leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from '../../services/planning-objectives';\n+import { RulesPanel } from './rules-panel';\n+\n+describe('work-sequence rule editor and reload', () => {\n+\tlet fixture: ComponentFixture;\n+\tlet component: RulesPanel;\n+\n+\tasync function choose(label: string, text: string) {\n+\t\tconst fields: HTMLElement[] = Array.from(\n+\t\t\tfixture.nativeElement.querySelectorAll('mat-form-field'),\n+\t\t);\n+\t\tconst select = fields\n+\t\t\t.find((field) => field.querySelector('mat-label')?.textContent?.trim() === label)\n+\t\t\t?.querySelector('mat-select');\n+\t\tif (!select) throw new Error(`Missing select ${label}`);\n+\t\tselect.click();\n+\t\tawait fixture.whenStable();\n+\t\tconst option = Array.from(document.querySelectorAll('mat-option')).find(\n+\t\t\t(candidate) => candidate.textContent?.trim() === text,\n+\t\t);\n+\t\tif (!option) throw new Error(`Missing option ${text}`);\n+\t\toption.click();\n+\t\tawait fixture.whenStable();\n+\t\tdocument.querySelector('.cdk-overlay-backdrop')?.click();\n+\t\tawait fixture.whenStable();\n+\t}\n+\n+\tasync function setInput(selector: string, value: string) {\n+\t\tconst input: HTMLInputElement = fixture.nativeElement.querySelector(selector);\n+\t\tinput.value = value;\n+\t\tinput.dispatchEvent(new Event('input'));\n+\t\tawait fixture.whenStable();\n+\t}\n+\n+\tbeforeEach(async () => {\n+\t\tlocalStorage.clear();\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n+\t\tvi.setSystemTime(new Date('2024-01-01T12:00:00Z'));\n+\t\tawait TestBed.configureTestingModule({\n+\t\t\timports: [RulesPanel],\n+\t\t\tproviders: [provideZonelessChangeDetection()],\n+\t\t}).compileComponents();\n+\t\tTestBed.inject(TranslationService).setLanguage('fr');\n+\t\tfixture = TestBed.createComponent(RulesPanel);\n+\t\tcomponent = fixture.componentInstance;\n+\t\tfixture.detectChanges();\n+\t\tfixture.debugElement.query(By.directive(MatExpansionPanel)).componentInstance.open();\n+\t});\n+\tafterEach(() => {\n+\t\tlocalStorage.clear();\n+\t\tvi.useRealTimers();\n+\t});\n+\n+\tit('creates threshold five, edits it to three, and restores its effect, order and activation after reload', async () => {\n+\t\tcomponent.startAddNew(RuleType.OPTIMIZATION);\n+\t\tawait fixture.whenStable();\n+\t\tawait setInput('input:not([type=\"number\"])', 'Mes reprises');\n+\t\tawait choose('Éléments du planning', 'Séquences de travail');\n+\t\tawait choose('Mesure', 'Déficit des séquences de travail');\n+\t\tawait choose('Conditions (toutes doivent être vérifiées)', 'Internes');\n+\t\tawait choose('Conditions (toutes doivent être vérifiées)', 'Non vides');\n+\t\tconst threshold: HTMLInputElement =\n+\t\t\tfixture.nativeElement.querySelector('input[type=\"number\"]');\n+\t\texpect(threshold.value).toBe('5');\n+\t\texpect(threshold.min).toBe('1');\n+\t\texpect(threshold.step).toBe('1');\n+\t\texpect(fixture.nativeElement.textContent).toContain('Seuil de préférence en jours ouvrés');\n+\t\tcomponent.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\tconst rule = component.rules[0];\n+\t\texpect(rule).toMatchObject({ configuration: OPTIMIZATION_PRESETS.shortSequenceDeficit });\n+\t\texpect(component.getRuleSummary(rule)).toContain(\n+\t\t\t'Déficit des séquences de travail (jours ouvrés)',\n+\t\t);\n+\t\tconst request = {\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: ['2024-01-08', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\t\t};\n+\t\texpect(calculatePlanningInternal({ ...request, rules: component.rules })).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [{ date: '2024-01-09' }, { date: '2024-01-10' }, { date: '2024-01-11' }],\n+\t\t});\n+\t\tcomponent.startEdit(rule, new Event('click'));\n+\t\tawait fixture.whenStable();\n+\t\tawait setInput('input[type=\"number\"]', '3');\n+\t\tcomponent.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\texpect(component.getRuleSummary(component.rules[0])).toContain(\n+\t\t\t'seuil de préférence : 3 jours ouvrés',\n+\t\t);\n+\t\texpect(calculatePlanningInternal({ ...request, rules: component.rules })).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [],\n+\t\t});\n+\n+\t\tcomponent.startAddNew(RuleType.OPTIMIZATION);\n+\t\tawait fixture.whenStable();\n+\t\tawait setInput('input:not([type=\"number\"])', 'Ma séquence maximale');\n+\t\tawait choose('Éléments du planning', 'Séquences de travail');\n+\t\tawait choose('Agrégation', 'Maximum');\n+\t\tcomponent.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\tconst maximum = component.rules[1];\n+\t\texpect(maximum).toMatchObject({ configuration: OPTIMIZATION_PRESETS.longestWorkSequence });\n+\t\tcomponent.toggleRule(maximum.id);\n+\t\tawait fixture.whenStable();\n+\t\tconst moveUp: HTMLButtonElement = fixture.nativeElement\n+\t\t\t.querySelectorAll('.rule-actions')[1]\n+\t\t\t.querySelector('button');\n+\t\tmoveUp.focus();\n+\t\tmoveUp.click();\n+\t\tawait fixture.whenStable();\n+\t\tconst saved = component.rules;\n+\t\tawait new Promise((resolve) => setTimeout(resolve, 350));\n+\t\tTestBed.resetTestingModule();\n+\t\tconst restored = TestBed.inject(RuleService).rules;\n+\t\texpect(restored).toEqual(saved);\n+\t\texpect(restored.map(({ id }) => id)).toEqual([maximum.id, rule.id]);\n+\t\texpect(restored[0].enabled).toBe(false);\n+\t\texpect(restored[1]).toMatchObject({\n+\t\t\tname: 'Mes reprises',\n+\t\t\tenabled: true,\n+\t\t\tconfiguration: { thresholdDays: 3 },\n+\t\t});\n+\t\texpect(calculatePlanningInternal({ ...request, rules: restored })).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [],\n+\t\t});\n+\t});\n+\n+\tit('keeps the saved threshold and shows an accessible error for fractional input', async () => {\n+\t\tcomponent.startAddNew(RuleType.OPTIMIZATION);\n+\t\tcomponent.changeOptimizationMeasure('work-sequence-deficit');\n+\t\tawait fixture.whenStable();\n+\t\tawait setInput('input[type=\"number\"]', '1.5');\n+\t\tcomponent.saveEdit();\n+\t\tawait fixture.whenStable();\n+\t\texpect(component.rules).toEqual([]);\n+\t\texpect(fixture.nativeElement.querySelector('[role=\"alert\"]').textContent).toContain(\n+\t\t\t'seuil entier positif',\n+\t\t);\n+\t\texpect(fixture.nativeElement.querySelector('input[type=\"number\"]').value).toBe('1.5');\n+\t});\n+\n+\tit('distinguishes aggregation units from the working-day threshold', () => {\n+\t\tconst translations = TestBed.inject(TranslationService);\n+\t\texpect(\n+\t\t\ttranslations.optimizationSummary(OPTIMIZATION_PRESETS.longestWorkSequence),\n+\t\t).toContain('Longueur des séquences de travail (jours ouvrés)');\n+\t\texpect(\n+\t\t\ttranslations.optimizationSummary({\n+\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\taggregation: 'count',\n+\t\t\t}),\n+\t\t).toContain('Déficit des séquences de travail (Nombre)');\n+\t\texpect(\n+\t\t\ttranslations.optimizationSummary({\n+\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\taggregation: 'count',\n+\t\t\t}),\n+\t\t).toContain('seuil de préférence : 5 jours ouvrés');\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/components/rules-panel/work-sequence-rule-editor.spec.ts", "project_id": 35, "relative_order": 15, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,3 +1,4 @@\n+import { createOptimizationPresetRules } from '../../services/rule-service';\n import { ComponentFixture, TestBed } from '@angular/core/testing';\n import { provideZonelessChangeDetection } from '@angular/core';\n import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';\n@@ -14,6 +15,8 @@ import { CalendarSettingsService } from '../../services/calendar-settings-servic\n import { createPlanningCalculation, PlanningRequest } from '../../services/leave-planner.service';\n import { TranslationService } from '../../services/translation-service';\n \n+const presets = createOptimizationPresetRules();\n+\n describe('UserInput', () => {\n \tlet component: UserInput;\n \tlet fixture: ComponentFixture;\n@@ -145,7 +148,7 @@ describe('UserInput', () => {\n \t\t\t\t},\n \t\t\t],\n \t\t\tdeclaredDays: [{ date: '2024-06-07', type: 'cp' }],\n-\t\t\trules: [],\n+\t\t\trules: [presets[3]],\n \t\t});\n \t\tconst root = fixture.nativeElement as HTMLElement;\n \t\tconst card = root.querySelector('.warning-card')!;\n@@ -162,7 +165,7 @@ describe('UserInput', () => {\n \t\tfixture.detectChanges();\n \t\texpect(root.querySelectorAll('.remaining-history > li').length).toBeGreaterThan(0);\n \t\texpect(details.textContent).toContain('Ces dates ont réellement été examinées');\n-\t\texpect(details.textContent).toContain('Maximum de jours travaillés entre congés');\n+\t\texpect(details.textContent).toContain(presets[3].name);\n \t\texpect(details.textContent).toContain('Évalué et rejeté');\n \t\texpect(JSON.stringify(userInputService.planningOutcomeSignal())).toBe(outcome);\n \t\texpect(JSON.stringify(userInputService.planningTraceSignal())).toBe(trace);\n@@ -527,7 +530,7 @@ describe('UserInput', () => {\n \t\t);\n \t\tawait rule.uncheck();\n \t\tawait expect.poll(() => localStorage.getItem('vacationRules')).not.toBeNull();\n-\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!)[0].enabled).toBe(false);\n+\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!).rules[0].enabled).toBe(false);\n \t\tfixture.nativeElement.querySelector('.calculate-button').click();\n \t\tawait fixture.whenStable();\n \n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/components/user-input/user-input.spec.ts", "project_id": 35, "relative_order": 16, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -102,7 +102,8 @@ export class UserInput {\n \t\tconst copy = this.tr().userInput;\n \t\treturn plan.remainingBalances.map((balance) => {\n \t\t\tconst code =\n-\t\t\t\tincomplete && ['preserved', 'not-established'].includes(balance.reason.code)\n+\t\t\t\tincomplete &&\n+\t\t\t\t['preserved', 'active-priorities', 'not-established'].includes(balance.reason.code)\n \t\t\t\t\t? 'calculation-incomplete'\n \t\t\t\t\t: balance.reason.code;\n \t\t\treturn {\n@@ -214,6 +215,7 @@ export class UserInput {\n \n \tprivate criterionLabel(name: string): string | undefined {\n \t\tconst id = name.replace(/^protected:/, '');\n+\t\tif (id.startsWith('optimization:')) return this.ruleName(id.slice('optimization:'.length));\n \t\tconst key =\n \t\t\tid === 'obligations'\n \t\t\t\t? 'obligation-validity'\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/components/user-input/user-input.ts", "project_id": 35, "relative_order": 17, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,225 @@\n+import { execFile } from 'node:child_process';\n+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';\n+import { tmpdir } from 'node:os';\n+import { join, resolve } from 'node:path';\n+import { promisify } from 'node:util';\n+import { Worker as NodeWorker } from 'node:worker_threads';\n+import { vi } from 'vitest';\n+import { createPlanningCalculation } from './leave-planner.service';\n+import type { OptimizationPlanningRule } from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+\n+describe('calendar objectives in the real worker', () => {\n+\tlet directory: string;\n+\tlet bundle: string;\n+\tconst threads = new Set();\n+\n+\tbeforeAll(async () => {\n+\t\tdirectory = mkdtempSync(join(tmpdir(), 'vac-calendar-worker-'));\n+\t\tbundle = join(directory, 'worker.mjs');\n+\t\tconst entry = join(directory, 'entry.ts');\n+\t\twriteFileSync(\n+\t\t\tentry,\n+\t\t\t`import { parentPort } from 'node:worker_threads';\n+globalThis.self = { postMessage: (message) => parentPort.postMessage(message) };\n+await import(${JSON.stringify(resolve('src/app/services/leave-planner.worker.ts'))});\n+parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n+`,\n+\t\t);\n+\t\tawait promisify(execFile)('bun', ['build', entry, '--target=node', '--outfile', bundle]);\n+\t});\n+\n+\tbeforeEach(() => {\n+\t\tvi.setSystemTime(new Date('2024-04-01T12:00:00Z'));\n+\t\tclass BrowserWorker {\n+\t\t\tonmessage: ((event: MessageEvent) => void) | null = null;\n+\t\t\tonerror: (() => void) | null = null;\n+\t\t\tprivate readonly thread = new NodeWorker(bundle);\n+\t\t\tconstructor() {\n+\t\t\t\tthreads.add(this.thread);\n+\t\t\t\tthis.thread.on('message', (data) => this.onmessage?.({ data } as MessageEvent));\n+\t\t\t\tthis.thread.on('error', () => this.onerror?.());\n+\t\t\t}\n+\t\t\tpostMessage(message: unknown) {\n+\t\t\t\tthis.thread.postMessage(message);\n+\t\t\t}\n+\t\t\tterminate() {\n+\t\t\t\tvoid this.thread.terminate();\n+\t\t\t}\n+\t\t}\n+\t\tvi.stubGlobal('Worker', BrowserWorker);\n+\t});\n+\n+\tafterEach(async () => {\n+\t\tawait Promise.all([...threads].map((thread) => thread.terminate()));\n+\t\tthreads.clear();\n+\t\tvi.useRealTimers();\n+\t\tvi.unstubAllGlobals();\n+\t});\n+\tafterAll(() => rmSync(directory, { recursive: true, force: true }));\n+\n+\tit.each([false, true])(\n+\t\t'retains the submitted configuration, plan and artifact order (gain first: %s)',\n+\t\tasync (gainFirst) => {\n+\t\t\tconst holiday: OptimizationPlanningRule = {\n+\t\t\t\tid: 'holiday',\n+\t\t\t\ttype: 'optimization' as const,\n+\t\t\t\tname: 'Captured holiday rule',\n+\t\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.holidayWeekValue),\n+\t\t\t};\n+\t\t\tconst gain: OptimizationPlanningRule = {\n+\t\t\t\tid: 'gain',\n+\t\t\t\ttype: 'optimization' as const,\n+\t\t\t\tname: 'Captured gain rule',\n+\t\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.nonWorkingDayGain),\n+\t\t\t};\n+\t\t\tconst rules = gainFirst ? [gain, holiday] : [holiday, gain];\n+\t\t\tconst calculation = createPlanningCalculation({\n+\t\t\t\thorizon: { start: '2024-04-29', end: '2024-05-18' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 3,\n+\t\t\t\t\t\tavailableFrom: '2024-04-29',\n+\t\t\t\t\t\texpiryDate: '2025-01-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules,\n+\t\t\t});\n+\t\t\tholiday.configuration = {\n+\t\t\t\t...holiday.configuration,\n+\t\t\t\tconditions: [],\n+\t\t\t\tdirection: 'minimize',\n+\t\t\t};\n+\t\t\tconst plan = await calculation.outcome;\n+\t\t\tif (plan.kind !== 'Plan')\n+\t\t\t\tthrow new Error(`Expected a worker plan, received ${plan.kind}`);\n+\t\t\texpect(plan.metrics).toMatchObject(\n+\t\t\t\tgainFirst\n+\t\t\t\t\t? { holidayWeekValue: 0, nonWorkingDayGain: 9 }\n+\t\t\t\t\t: { holidayWeekValue: 5, nonWorkingDayGain: 6 },\n+\t\t\t);\n+\t\t\texpect(calculation.snapshot.rules.find((rule) => rule.id === 'holiday')).toMatchObject({\n+\t\t\t\tname: 'Captured holiday rule',\n+\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t\t});\n+\t\t\tconst first = `optimization:${rules[0].id}`;\n+\t\t\tconst explanation = await calculation.explanation;\n+\t\t\tif (explanation?.kind !== 'PlanExplanation')\n+\t\t\t\tthrow new Error('Expected a worker explanation');\n+\t\t\texpect(explanation.placements[0].firstDecisiveObjective).toBe(first);\n+\t\t\texpect((await calculation.trace)?.phases.map((phase) => phase.name)).toEqual([\n+\t\t\t\t'validation',\n+\t\t\t\t'obligations',\n+\t\t\t\tfirst,\n+\t\t\t\t`optimization:${rules[1].id}`,\n+\t\t\t\t'expiry',\n+\t\t\t\t'dates',\n+\t\t\t]);\n+\t\t\tconst comparison = await calculation.analyzeCounterfactual(plan.placements[0]);\n+\t\t\tif (comparison.kind !== 'Counterfactual')\n+\t\t\t\tthrow new Error('Expected a worker comparison');\n+\t\t\texpect(\n+\t\t\t\tcomparison.results.find((result) => result.date === plan.placements[0].date)\n+\t\t\t\t\t?.comparison?.firstDecisiveObjective,\n+\t\t\t).toBe(first);\n+\t\t},\n+\t);\n+\n+\tit.each([false, true])(\n+\t\t'lets economy block or permit the complete holiday bundle in a real worker (economy first: %s)',\n+\t\tasync (economyFirst) => {\n+\t\t\tconst economy: OptimizationPlanningRule = {\n+\t\t\t\tid: 'economy',\n+\t\t\t\tname: 'Captured supporting economy',\n+\t\t\t\ttype: 'optimization',\n+\t\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.supportingPlacements),\n+\t\t\t};\n+\t\t\tconst holiday: OptimizationPlanningRule = {\n+\t\t\t\tid: 'holiday',\n+\t\t\t\ttype: 'optimization',\n+\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t\t};\n+\t\t\tconst rules = economyFirst ? [economy, holiday] : [holiday, economy];\n+\t\t\tconst calculation = createPlanningCalculation({\n+\t\t\t\thorizon: { start: '2026-11-09', end: '2026-11-14' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 2,\n+\t\t\t\t\t\tavailableFrom: '2026-11-09',\n+\t\t\t\t\t\texpiryDate: '2027-01-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\tdeclaredDays: ['2026-11-09', '2026-11-10'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules,\n+\t\t\t});\n+\t\t\teconomy.name = 'Edited later';\n+\t\t\teconomy.configuration.conditions = [];\n+\t\t\tconst outcome = await calculation.outcome;\n+\t\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a worker plan');\n+\t\t\texpect(outcome.metrics).toMatchObject(\n+\t\t\t\teconomyFirst\n+\t\t\t\t\t? { holidayWeekValue: 0, supportingPlacements: 0 }\n+\t\t\t\t\t: { holidayWeekValue: 3, supportingPlacements: 2 },\n+\t\t\t);\n+\t\t\texpect(calculation.snapshot.rules.find(({ id }) => id === 'economy')).toMatchObject({\n+\t\t\t\tname: 'Captured supporting economy',\n+\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t});\n+\t\t\tconst trace = await calculation.trace;\n+\t\t\texpect(trace?.phases.map(({ name }) => name)).toEqual([\n+\t\t\t\t'validation',\n+\t\t\t\t'obligations',\n+\t\t\t\t`optimization:${rules[0].id}`,\n+\t\t\t\t`optimization:${rules[1].id}`,\n+\t\t\t\t'expiry',\n+\t\t\t\t'dates',\n+\t\t\t]);\n+\t\t\tconst candidates = trace?.phases.flatMap(({ decisions }) =>\n+\t\t\t\tdecisions.flatMap(({ candidates }) => candidates),\n+\t\t\t);\n+\t\t\texpect(candidates).toContainEqual(\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tstatus: economyFirst ? 'evaluated-rejected' : 'chosen',\n+\t\t\t\t\tdates: ['2026-11-12', '2026-11-13'],\n+\t\t\t\t\tcomparison: expect.objectContaining({\n+\t\t\t\t\t\tfirstDecisiveObjective: economyFirst\n+\t\t\t\t\t\t\t? 'optimization:economy'\n+\t\t\t\t\t\t\t: 'optimization:holiday',\n+\t\t\t\t\t}),\n+\t\t\t\t}),\n+\t\t\t);\n+\t\t\tconst explanation = await calculation.explanation;\n+\t\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\t\tif (economyFirst) {\n+\t\t\t\texpect(outcome.placements).toEqual([]);\n+\t\t\t\texpect(outcome.remainingBalances[0]).toMatchObject({\n+\t\t\t\t\tid: 'cp',\n+\t\t\t\t\tquantity: 2,\n+\t\t\t\t\tclassification: 'deferred',\n+\t\t\t\t});\n+\t\t\t\texpect(explanation.placements).toEqual([]);\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\texpect(outcome.remainingBalances).toEqual([]);\n+\t\t\texpect(explanation.placements.every(({ supporting }) => supporting)).toBe(true);\n+\t\t\texpect(explanation.placements[0].firstDecisiveObjective).toBe('optimization:holiday');\n+\t\t\texpect(explanation.placements[0].objectiveVector.objectives).toContainEqual(\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tid: 'optimization:economy',\n+\t\t\t\t\tvalue: 2,\n+\t\t\t\t\tlabel: 'Captured supporting economy',\n+\t\t\t\t}),\n+\t\t\t);\n+\t\t\tconst analysis = await calculation.analyzeCounterfactual(outcome.placements[0]);\n+\t\t\tif (analysis.kind !== 'Counterfactual') throw new Error('Expected a counterfactual');\n+\t\t\texpect(\n+\t\t\t\tanalysis.results.find(({ date }) => date === outcome.placements[0].date)?.comparison\n+\t\t\t\t\t?.after.objectives,\n+\t\t\t).toContainEqual(expect.objectContaining({ id: 'optimization:economy', value: 2 }));\n+\t\t},\n+\t);\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/services/calendar-objectives.worker.spec.ts", "project_id": 35, "relative_order": 18, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,466 @@\n+import { describe, expect, it } from 'vitest';\n+import {\n+\tanalyzeCounterfactualInternal,\n+\tcalculatePlanningInternal,\n+\ttype OptimizationPlanningRule,\n+\ttype PlanningArtifacts,\n+\ttype PlanningRequest,\n+} from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS, type OptimizationConfiguration } from './planning-objectives';\n+\n+const holiday: OptimizationPlanningRule = {\n+\tid: 'holiday',\n+\tname: 'Complete public-holiday weeks',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+};\n+const gain: OptimizationPlanningRule = {\n+\tid: 'gain',\n+\tname: 'Enjoy weekends and public holidays',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.nonWorkingDayGain,\n+};\n+const samedi: PlanningRequest['rules'][number] = {\n+\tid: 'samedi',\n+\ttype: 'if_then',\n+\tdayOfWeek: 6,\n+\tplaceDays: 2,\n+\tplaceType: 'cp',\n+\tplacement: 'auto',\n+\trewardDays: 1,\n+\trewardType: 'other',\n+};\n+const concurrent: PlanningRequest = {\n+\thorizon: { start: '2024-04-29', end: '2024-05-18' },\n+\tbalances: [\n+\t\t{\n+\t\t\tid: 'cp',\n+\t\t\ttype: 'cp',\n+\t\t\tquantity: 3,\n+\t\t\tavailableFrom: '2024-04-29',\n+\t\t\texpiryDate: '2025-01-01',\n+\t\t},\n+\t],\n+\trules: [],\n+};\n+\n+function calculate(request: PlanningRequest, calculationDate = '2024-04-01') {\n+\tlet artifacts: PlanningArtifacts = {};\n+\tconst plan = calculatePlanningInternal(\n+\t\t{ ...request, calculationDate },\n+\t\tundefined,\n+\t\t(value) => (artifacts = value),\n+\t);\n+\tif (plan.kind !== 'Plan') throw new Error(`Expected a plan, received ${plan.kind}`);\n+\treturn { plan, artifacts };\n+}\n+\n+describe('composed calendar objectives', () => {\n+\tit('follows either displayed order when a completed holiday week competes with greater natural gain', () => {\n+\t\tconst holidayFirst = calculate({ ...concurrent, rules: [holiday, gain] }).plan;\n+\t\tconst gainFirst = calculate({ ...concurrent, rules: [gain, holiday] }).plan;\n+\t\texpect(holidayFirst.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t'2024-05-06',\n+\t\t\t'2024-05-07',\n+\t\t\t'2024-05-10',\n+\t\t]);\n+\t\texpect(holidayFirst.metrics).toMatchObject({ holidayWeekValue: 5, nonWorkingDayGain: 6 });\n+\t\texpect(gainFirst.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t'2024-04-29',\n+\t\t\t'2024-05-10',\n+\t\t\t'2024-05-17',\n+\t\t]);\n+\t\texpect(gainFirst.metrics).toMatchObject({ holidayWeekValue: 0, nonWorkingDayGain: 9 });\n+\t});\n+\n+\tit('regroups existing placements as a complete week without leaving higher-priority at-risk leave unused', () => {\n+\t\tconst loss: OptimizationPlanningRule = {\n+\t\t\tid: 'loss',\n+\t\t\ttype: 'optimization',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t};\n+\t\tconst { plan } = calculate({\n+\t\t\t...concurrent,\n+\t\t\tbalances: [{ ...concurrent.balances[0], expiryDate: '2024-05-17' }],\n+\t\t\trules: [loss, holiday, gain],\n+\t\t});\n+\t\texpect(plan.metrics).toMatchObject({\n+\t\t\tunplacedAtRisk: 0,\n+\t\t\tholidayWeekValue: 5,\n+\t\t\tnonWorkingDayGain: 6,\n+\t\t});\n+\t\texpect(plan.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t'2024-05-06',\n+\t\t\t'2024-05-07',\n+\t\t\t'2024-05-10',\n+\t\t]);\n+\t\texpect(plan.placements.every((placement) => !placement.supporting)).toBe(true);\n+\t});\n+\n+\tit('preserves an earlier preference that minimizes supporting placements', () => {\n+\t\tconst { plan } = calculate({\n+\t\t\t...concurrent,\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'economy',\n+\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t\t},\n+\t\t\t\tholiday,\n+\t\t\t],\n+\t\t});\n+\t\texpect(plan.placements).toEqual([]);\n+\t});\n+\n+\tit('uses edited holiday conditions and aggregation without dispatching by a preset identity', () => {\n+\t\tconst counted: OptimizationPlanningRule = {\n+\t\t\t...holiday,\n+\t\t\tid: 'my-complete-weeks',\n+\t\t\tconfiguration: { ...holiday.configuration, aggregation: 'count' },\n+\t\t};\n+\t\tconst { plan, artifacts } = calculate({ ...concurrent, rules: [counted] });\n+\t\texpect(plan.metrics.holidayWeekValue).toBe(5);\n+\t\tif (artifacts.explanation?.kind !== 'PlanExplanation')\n+\t\t\tthrow new Error('Expected an explanation');\n+\t\texpect(artifacts.explanation.placements[0].objectiveVector.objectives[1]).toMatchObject({\n+\t\t\tid: 'optimization:my-complete-weeks',\n+\t\t\tvalue: 1,\n+\t\t});\n+\t\tconst allWeeks = calculate({\n+\t\t\t...concurrent,\n+\t\t\trules: [{ ...counted, configuration: { ...counted.configuration, conditions: [] } }],\n+\t\t}).plan;\n+\t\texpect(allWeeks.placements).toEqual([]);\n+\t});\n+\n+\tit('attributes a coordinated holiday addition and its explanation to the active rule', () => {\n+\t\tconst { plan, artifacts } = calculate(\n+\t\t\t{\n+\t\t\t\thorizon: { start: '2026-11-09', end: '2026-11-14' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'deferred-cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 2,\n+\t\t\t\t\t\tavailableFrom: '2026-11-01',\n+\t\t\t\t\t\texpiryDate: '2027-01-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\tdeclaredDays: ['2026-11-09', '2026-11-10'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [holiday],\n+\t\t\t},\n+\t\t\t'2026-11-01',\n+\t\t);\n+\t\texpect(plan.placements).toEqual([\n+\t\t\texpect.objectContaining({ date: '2026-11-12', ruleIds: ['holiday'], supporting: true }),\n+\t\t\texpect.objectContaining({ date: '2026-11-13', ruleIds: ['holiday'], supporting: true }),\n+\t\t]);\n+\t\tif (artifacts.explanation?.kind !== 'PlanExplanation')\n+\t\t\tthrow new Error('Expected an explanation');\n+\t\tfor (const placement of artifacts.explanation.placements) {\n+\t\t\texpect(placement.firstDecisiveObjective).toBe('optimization:holiday');\n+\t\t\texpect(placement.contributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({ kind: 'rule', ruleId: 'holiday' }),\n+\t\t\t);\n+\t\t}\n+\t});\n+\n+\tit.each([\n+\t\t{ ...gain.configuration, aggregation: 'maximum' },\n+\t\t{ ...gain.configuration, aggregation: 'count', direction: 'minimize' },\n+\t])(\n+\t\t'bridges fixed periods for the personal configuration $aggregation/$direction',\n+\t\t(configuration) => {\n+\t\t\tconst { plan, artifacts } = calculate({\n+\t\t\t\thorizon: { start: '2024-01-05', end: '2024-01-13' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'rtt',\n+\t\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\t\tquantity: 4,\n+\t\t\t\t\t\tavailableFrom: '2024-01-05',\n+\t\t\t\t\t\texpiryDate: '2025-01-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\tdeclaredDays: ['2024-01-05', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\t...gain,\n+\t\t\t\t\t\tid: 'personal-maximum',\n+\t\t\t\t\t\tconfiguration,\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t});\n+\t\t\texpect(plan.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t\t'2024-01-08',\n+\t\t\t\t'2024-01-09',\n+\t\t\t\t'2024-01-10',\n+\t\t\t\t'2024-01-11',\n+\t\t\t]);\n+\t\t\texpect(plan.timeOffPeriods).toHaveLength(1);\n+\t\t\texpect(plan.timeOffPeriods[0].nonWorkingDates).toEqual([\n+\t\t\t\t'2024-01-06',\n+\t\t\t\t'2024-01-07',\n+\t\t\t\t'2024-01-13',\n+\t\t\t\t'2024-01-14',\n+\t\t\t]);\n+\t\t\texpect(plan.metrics.nonWorkingDayGain).toBe(4);\n+\t\t\texpect(\n+\t\t\t\tplan.placements.every(({ ruleIds }) => ruleIds.includes('personal-maximum')),\n+\t\t\t).toBe(true);\n+\t\t\tif (artifacts.explanation?.kind !== 'PlanExplanation')\n+\t\t\t\tthrow new Error('Expected an explanation');\n+\t\t\tfor (const placement of artifacts.explanation.placements)\n+\t\t\t\texpect(placement.contributions).toContainEqual(\n+\t\t\t\t\texpect.objectContaining({ kind: 'rule', ruleId: 'personal-maximum' }),\n+\t\t\t\t);\n+\t\t},\n+\t);\n+\n+\tit.each([false, true])(\n+\t\t'finishes a rejected bridge with an irrelevant typed rule: %s',\n+\t\t(withSamedi) => {\n+\t\t\tconst { plan } = calculate({\n+\t\t\t\thorizon: { start: '2024-01-05', end: '2024-02-06' },\n+\t\t\t\tbalances: (['cp', 'rtt', 'other'] as const).map((type) => ({\n+\t\t\t\t\tid: type,\n+\t\t\t\t\ttype,\n+\t\t\t\t\tquantity: 20,\n+\t\t\t\t\tavailableFrom: '2024-01-05',\n+\t\t\t\t\texpiryDate: '2025-01-01',\n+\t\t\t\t})),\n+\t\t\t\tdeclaredDays: ['2024-01-05', '2024-02-05'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'economy',\n+\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\t...gain,\n+\t\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t\t...gain.configuration,\n+\t\t\t\t\t\t\taggregation: 'count',\n+\t\t\t\t\t\t\tdirection: 'minimize',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t},\n+\t\t\t\t\t...(withSamedi ? [samedi] : []),\n+\t\t\t\t],\n+\t\t\t\tdeadlineMs: 2_000,\n+\t\t\t});\n+\t\t\texpect(plan.placements).toEqual([]);\n+\t\t\texpect(plan.timeOffPeriods).toHaveLength(2);\n+\t\t},\n+\t);\n+\n+\tit('does not label a period-count bridge supporting when it adds no domain calendar benefit', () => {\n+\t\tconst { plan } = calculate({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-31' },\n+\t\t\tbalances: [{ ...concurrent.balances[0], quantity: 5, availableFrom: '2024-01-02' }],\n+\t\t\tdeclaredDays: ['2024-01-05', '2024-01-15'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\t...gain,\n+\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t...gain.configuration,\n+\t\t\t\t\t\taggregation: 'count',\n+\t\t\t\t\t\tdirection: 'minimize',\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(plan.timeOffPeriods).toHaveLength(1);\n+\t\texpect(plan.placements).toHaveLength(5);\n+\t\texpect(plan.placements.every((placement) => !placement.supporting)).toBe(true);\n+\t\texpect(plan.metrics.nonWorkingDayGain).toBe(4);\n+\t});\n+\n+\tit('can place the holiday preference before or after Samedi Malin', () => {\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2021-11-01', end: '2021-12-29' },\n+\t\t\tbalances: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'cp',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 4,\n+\t\t\t\t\tavailableFrom: '2021-11-01',\n+\t\t\t\t\texpiryDate: '2022-01-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t\trules: [],\n+\t\t};\n+\t\tconst first = calculate({ ...request, rules: [holiday, samedi] }, '2021-10-01').plan;\n+\t\tconst second = calculate({ ...request, rules: [samedi, holiday] }, '2021-10-01').plan;\n+\t\texpect(first.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t'2021-11-08',\n+\t\t\t'2021-11-09',\n+\t\t\t'2021-11-10',\n+\t\t\t'2021-11-12',\n+\t\t]);\n+\t\texpect(first.metrics.holidayWeekValue).toBe(2);\n+\t\texpect(first.preferences[0].satisfied).toBe(0);\n+\t\texpect(second.placements.map((placement) => placement.date)).toEqual([\n+\t\t\t'2021-12-23',\n+\t\t\t'2021-12-24',\n+\t\t]);\n+\t\texpect(second.metrics.holidayWeekValue).toBe(0);\n+\t\texpect(second.preferences[0].satisfied).toBe(1);\n+\t\texpect(second.remainingBalances.find((balance) => balance.earned)).toMatchObject({\n+\t\t\tid: 'earned:samedi:2021-12-25',\n+\t\t\tquantity: 1,\n+\t\t});\n+\t});\n+\n+\tit.each(['obligation', 'preference'] as const)(\n+\t\t'preserves a higher %s when completing a week would take its last balance',\n+\t\t(force) => {\n+\t\t\tconst { plan } = calculate({\n+\t\t\t\t...concurrent,\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'monday',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce,\n+\t\t\t\t\t\tstartDate: '2024-04-29',\n+\t\t\t\t\t\tendDate: '2024-04-29',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t\tholiday,\n+\t\t\t\t],\n+\t\t\t});\n+\t\t\texpect(plan.placements).toMatchObject([{ date: '2024-04-29', ruleIds: ['monday'] }]);\n+\t\t\texpect(plan.metrics.holidayWeekValue).toBe(0);\n+\t\t},\n+\t);\n+\n+\tit('adds no residual loss-prevention or calendar placements when their rules are disabled', () => {\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-04-29', end: '2024-05-04' },\n+\t\t\tbalances: [{ ...concurrent.balances[0], quantity: 5, expiryDate: '2024-05-03' }],\n+\t\t\trules: [holiday],\n+\t\t};\n+\t\tconst absent = calculate(request).plan;\n+\t\tconst disabled = calculate({\n+\t\t\t...request,\n+\t\t\trules: [\n+\t\t\t\tholiday,\n+\t\t\t\t{\n+\t\t\t\t\tid: 'loss',\n+\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\tenabled: false,\n+\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t\t\t},\n+\t\t\t\t{ ...gain, enabled: false },\n+\t\t\t],\n+\t\t}).plan;\n+\t\texpect(disabled).toEqual(absent);\n+\t\texpect(absent.metrics.unplacedAtRisk).toBe(1);\n+\t\texpect(absent.metrics.holidayWeekValue).toBe(3);\n+\t\texpect(absent.placements).toHaveLength(4);\n+\t\texpect(\n+\t\t\tcalculate({ ...request, rules: [{ ...holiday, enabled: false }] }).plan.placements,\n+\t\t).toEqual([]);\n+\t});\n+\n+\tit.each([\n+\t\t{ start: '2024-05-06', end: '2024-05-11' },\n+\t\t{ start: '2024-05-10', end: '2024-05-11' },\n+\t])(\n+\t\t'uses declarations outside the horizon to complete a genuine holiday week ($start)',\n+\t\t(horizon) => {\n+\t\t\tconst { plan } = calculate({\n+\t\t\t\thorizon,\n+\t\t\t\tbalances: [{ ...concurrent.balances[0], quantity: 1, availableFrom: '2024-05-06' }],\n+\t\t\t\tdeclaredDays: ['2024-05-06', '2024-05-07'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [holiday],\n+\t\t\t});\n+\t\t\texpect(plan.placements).toMatchObject([{ date: '2024-05-10', supporting: true }]);\n+\t\t\texpect(plan.metrics).toMatchObject({ holidayWeekValue: 5, nonWorkingDayGain: 6 });\n+\t\t},\n+\t);\n+\n+\tit('cannot fill missing weekdays outside the horizon or with unavailable balances', () => {\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-05-10', end: '2024-05-11' },\n+\t\t\tbalances: [{ ...concurrent.balances[0], quantity: 1 }],\n+\t\t\trules: [holiday],\n+\t\t};\n+\t\texpect(calculate(request).plan.placements).toEqual([]);\n+\t\tconst unavailable = calculate({\n+\t\t\t...request,\n+\t\t\tbalances: [{ ...request.balances[0], availableFrom: '2024-05-11' }],\n+\t\t\tdeclaredDays: ['2024-05-06', '2024-05-07'].map((date) => ({ date, type: 'other' })),\n+\t\t}).plan;\n+\t\texpect(unavailable.placements).toEqual([]);\n+\t\texpect(unavailable.metrics.holidayWeekValue).toBe(0);\n+\t});\n+\n+\tit('measures only distinct natural dates and leaves ordinary declared weeks ordinary', () => {\n+\t\tconst christmas = calculate({\n+\t\t\thorizon: { start: '2021-12-24', end: '2021-12-25' },\n+\t\t\tbalances: [],\n+\t\t\tdeclaredDays: [{ date: '2021-12-24', type: 'other' }],\n+\t\t\trules: [holiday, gain],\n+\t\t}).plan;\n+\t\texpect(christmas.metrics).toMatchObject({ holidayWeekValue: 0, nonWorkingDayGain: 2 });\n+\t\texpect(christmas.timeOffPeriods[0].nonWorkingDates).toEqual(['2021-12-25', '2021-12-26']);\n+\t\tconst ordinary = calculate({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tbalances: [],\n+\t\t\tdeclaredDays: ['08', '09', '10', '11', '12'].map((day) => ({\n+\t\t\t\tdate: `2024-01-${day}`,\n+\t\t\t\ttype: 'other',\n+\t\t\t})),\n+\t\t\trules: [holiday],\n+\t\t}).plan;\n+\t\texpect(ordinary.metrics.holidayWeekValue).toBe(0);\n+\t});\n+\n+\tit('uses the same first calendar objective in the plan explanation, trace and date comparison', () => {\n+\t\tfor (const rules of [\n+\t\t\t[holiday, gain],\n+\t\t\t[gain, holiday],\n+\t\t]) {\n+\t\t\tconst request = { ...concurrent, rules };\n+\t\t\tconst { plan, artifacts } = calculate(request);\n+\t\t\tconst explanation = artifacts.explanation;\n+\t\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\t\tconst first = `optimization:${rules[0].id}`;\n+\t\t\texpect(explanation.placements[0].firstDecisiveObjective).toBe(first);\n+\t\t\texpect(\n+\t\t\t\texplanation.placements[0].objectiveVector.objectives.map(\n+\t\t\t\t\t(objective) => objective.id,\n+\t\t\t\t),\n+\t\t\t).toEqual([\n+\t\t\t\t'obligation-validity',\n+\t\t\t\tfirst,\n+\t\t\t\t`optimization:${rules[1].id}`,\n+\t\t\t\t'balance-expiry',\n+\t\t\t\t'placement-date',\n+\t\t\t]);\n+\t\t\tconst comparisons = artifacts.trace?.phases\n+\t\t\t\t.flatMap((phase) => phase.decisions)\n+\t\t\t\t.flatMap((decision) => decision.candidates)\n+\t\t\t\t.filter((candidate) => candidate.status === 'chosen' && candidate.comparison);\n+\t\t\texpect(\n+\t\t\t\tcomparisons?.some(\n+\t\t\t\t\t(candidate) => candidate.comparison?.firstDecisiveObjective === first,\n+\t\t\t\t),\n+\t\t\t).toBe(true);\n+\t\t\tconst placement = rules[0].id === 'holiday' ? plan.placements[1] : plan.placements[0];\n+\t\t\tconst alternative = rules[0].id === 'holiday' ? '2024-04-30' : '2024-05-02';\n+\t\t\tconst comparison = analyzeCounterfactualInternal(\n+\t\t\t\trequest,\n+\t\t\t\tplan,\n+\t\t\t\tplacement,\n+\t\t\t\tartifacts.finalState,\n+\t\t\t\t{ removeDate: placement.date, compareOriginalState: true },\n+\t\t\t);\n+\t\t\texpect(\n+\t\t\t\tcomparison.results.find((result) => result.date === alternative)?.comparison\n+\t\t\t\t\t?.firstDecisiveObjective,\n+\t\t\t).toBe(first);\n+\t\t}\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/services/leave-planner-calendar-objectives.spec.ts", "project_id": 35, "relative_order": 19, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,3 +1,4 @@\n+import { createOptimizationPresetRules } from './rule-service';\n import { vi } from 'vitest';\n import {\n \tcreatePlanningCalculation,\n@@ -14,6 +15,8 @@ const request = {\n beforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n afterEach(() => vi.useRealTimers());\n \n+const presets = createOptimizationPresetRules();\n+\n describe('user cancellation', () => {\n \tconst workers: CancellableWorker[] = [];\n \tconst currentWorker = () => workers[workers.length - 1];\n@@ -51,7 +54,7 @@ describe('user cancellation', () => {\n \t\tconst submitted = {\n \t\t\thorizon: { start: '2024-01-02', end: '2024-01-09' },\n \t\t\tbalances: [],\n-\t\t\trules: [],\n+\t\t\trules: [presets[2]],\n \t\t\tdeclaredDays: [{ date: '2024-01-05', type: 'other' as const }],\n \t\t};\n \t\tlet interrupted = false;\n@@ -60,7 +63,7 @@ describe('user cancellation', () => {\n \t\t\t{\n \t\t\t\t...submitted,\n \t\t\t\tprogress: (stage: string) => {\n-\t\t\t\t\tif (stage === 'non-working-day-gain') interrupted = true;\n+\t\t\t\t\tif (stage === 'optimization:default-non-working-day-gain') interrupted = true;\n \t\t\t\t},\n \t\t\t},\n \t\t\tundefined,\n@@ -115,14 +118,17 @@ describe('user cancellation', () => {\n \t\t\t\t{ date: '2024-01-11', type: 'rtt' as const },\n \t\t\t],\n \t\t\trules: [\n-\t\t\t\t{ id: 'exact-cp', force: 'obligation', placeDays: 2, placeType: 'cp' },\n-\t\t\t\t{ id: 'preferred-rtt', force: 'preference', placeDays: 1, placeType: 'rtt' },\n-\t\t\t].map((rule) => ({\n-\t\t\t\t...rule,\n-\t\t\t\ttype: 'time_window',\n-\t\t\t\tstartDate: '2024-01-08',\n-\t\t\t\tendDate: '2024-01-12',\n-\t\t\t})),\n+\t\t\t\tpresets[1],\n+\t\t\t\t...[\n+\t\t\t\t\t{ id: 'exact-cp', force: 'obligation', placeDays: 2, placeType: 'cp' },\n+\t\t\t\t\t{ id: 'preferred-rtt', force: 'preference', placeDays: 1, placeType: 'rtt' },\n+\t\t\t\t].map((rule) => ({\n+\t\t\t\t\t...rule,\n+\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\tstartDate: '2024-01-08',\n+\t\t\t\t\tendDate: '2024-01-12',\n+\t\t\t\t})),\n+\t\t\t],\n \t\t};\n \t\tlet interrupted = false;\n \t\tlet artifacts: import('./leave-planner.core').PlanningArtifacts = {};\n@@ -130,7 +136,7 @@ describe('user cancellation', () => {\n \t\t\t{\n \t\t\t\t...submitted,\n \t\t\t\tprogress: (stage: string) => {\n-\t\t\t\t\tif (stage === 'holiday-week-value') interrupted = true;\n+\t\t\t\t\tif (stage === 'optimization:default-holiday-week-value') interrupted = true;\n \t\t\t\t},\n \t\t\t},\n \t\t\tundefined,\n@@ -201,18 +207,22 @@ describe('user cancellation', () => {\n \t\t\t\thorizon: request.horizon,\n \t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-12-31' }],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'january',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tstartDate: '2024-01-01',\n-\t\t\t\t\t\tendDate: '2024-01-31',\n-\t\t\t\t\t\tplaceDays: 2,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'january',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tstartDate: '2024-01-01',\n+\t\t\t\t\t\t\tendDate: '2024-01-31',\n+\t\t\t\t\t\t\tplaceDays: 2,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t\tprogress: (stage: string) => {\n-\t\t\t\t\tif (stage === 'longest-work-sequence') cancelled = true;\n+\t\t\t\t\tif (stage === 'optimization:default-longest-work-sequence') cancelled = true;\n \t\t\t\t},\n \t\t\t},\n \t\t\tundefined,\n@@ -287,7 +297,7 @@ describe('user cancellation', () => {\n \t\tconst submitted = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n \t\t\tbalances: [{ id: 'cp', type: 'cp' as const, quantity: 2, expiryDate: '2024-01-31' }],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t};\n \t\tconst cancelled = await core.calculatePlanningAsyncInternal(\n \t\t\t{\n@@ -295,7 +305,7 @@ describe('user cancellation', () => {\n \t\t\t\ttraceProgress: (_: number, update: PlanningTraceUpdate) =>\n \t\t\t\t\tupdates.push(structuredClone(update)),\n \t\t\t\tprogress: (stage: string) => {\n-\t\t\t\t\tif (stage === 'non-working-day-gain') interrupted = true;\n+\t\t\t\t\tif (stage === 'optimization:default-non-working-day-gain') interrupted = true;\n \t\t\t\t},\n \t\t\t},\n \t\t\tundefined,\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner-cancellation.spec.ts", "project_id": 35, "relative_order": 20, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,3 +1,4 @@\n+import { createOptimizationPresetRules } from './rule-service';\n import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';\n import { createPlanningCalculation, applyReplayDeltas } from './leave-planner.service';\n \n@@ -15,6 +16,8 @@ afterEach(() => vi.unstubAllGlobals());\n beforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n afterEach(() => vi.useRealTimers());\n \n+const presets = createOptimizationPresetRules();\n+\n describe('planner explanation and trace seam', () => {\n \tit('replays a reported occurrence without borrowing its future balance from the final plan', async () => {\n \t\tvi.setSystemTime(new Date('2024-05-03T12:00:00Z'));\n@@ -180,7 +183,7 @@ describe('planner explanation and trace seam', () => {\n \t\t},\n \t);\n \n-\tit('removes an entitlement from the original replay when a real quality move shortens its generator into today', async () => {\n+\tit('replays an already-reported entitlement without inventing a transient earned balance under explicit priorities', async () => {\n \t\tvi.setSystemTime(new Date('2024-05-06T12:00:00Z'));\n \t\tconst core = await import('./leave-planner.core');\n \t\tlet artifacts: import('./leave-planner.core').PlanningArtifacts = {};\n@@ -201,17 +204,21 @@ describe('planner explanation and trace seam', () => {\n \t\t\t\t\t{ date: '2024-05-03', type: 'cp' },\n \t\t\t\t],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'producer',\n-\t\t\t\t\t\ttype: 'if_then',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tdayOfWeek: 3,\n-\t\t\t\t\t\tplaceDays: 2,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t\tplacement: 'after',\n-\t\t\t\t\t\trewardDays: 1,\n-\t\t\t\t\t\trewardType: 'other',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\t\tplaceDays: 2,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\t\trewardType: 'other',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t},\n \t\t\tundefined,\n@@ -226,11 +233,16 @@ describe('planner explanation and trace seam', () => {\n \t\t\tadded: false,\n \t\t});\n \t\tconst decisions = artifacts.trace.phases.flatMap(({ decisions }) => decisions);\n-\t\texpect(decisions.flatMap(({ deltas }) => deltas)).toContainEqual({\n-\t\t\tkind: 'balance-removed',\n-\t\t\tbalanceId: 'earned:producer:2024-05-01',\n-\t\t\tremainingBefore: 1,\n-\t\t});\n+\t\tconst deltas = decisions.flatMap(({ deltas }) => deltas);\n+\t\texpect(deltas).toContainEqual(\n+\t\t\texpect.objectContaining({ kind: 'balance-changed', balanceId: 'cp' }),\n+\t\t);\n+\t\texpect(deltas).not.toContainEqual(\n+\t\t\texpect.objectContaining({\n+\t\t\t\tkind: 'balance-changed',\n+\t\t\t\tbalanceId: 'earned:producer:2024-05-01',\n+\t\t\t}),\n+\t\t);\n \t\tconst initial = artifacts.trace.initialState;\n \t\tconst replay = {\n \t\t\tbalances: initial.balances.map((balance) => ({ ...balance })),\n@@ -355,14 +367,16 @@ describe('planner explanation and trace seam', () => {\n \t\tconst calculation = createPlanningCalculation({\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-08' },\n \t\t\tbalances: [balance('cp', 'cp', 2, '2024-01-07')],\n-\t\t\trules: [],\n+\t\t\trules: [presets[0]],\n \t\t});\n \t\tconst outcome = await calculation.outcome;\n \t\tconst trace = await calculation.trace;\n \t\texpect(outcome.kind).toBe('Plan');\n \t\tif (outcome.kind !== 'Plan' || !trace) return;\n \n-\t\tconst atRisk = trace.phases.find((phase) => phase.name === 'at-risk');\n+\t\tconst atRisk = trace.phases.find(\n+\t\t\t(phase) => phase.name === 'optimization:default-unplaced-at-risk',\n+\t\t);\n \t\tconst jan2 = atRisk?.decisions.find((decision) =>\n \t\t\tdecision.deltas.some(\n \t\t\t\t(delta) => delta.kind === 'placement-added' && delta.date === '2024-01-02',\n@@ -374,22 +388,17 @@ describe('planner explanation and trace seam', () => {\n \t\t\t),\n \t\t);\n \t\texpect(jan2?.candidates.some((candidate) => candidate.status === 'chosen')).toBe(true);\n-\t\texpect(jan2?.candidates[0]).toMatchObject({\n+\t\texpect(jan2?.candidates.find((candidate) => candidate.status === 'chosen')).toMatchObject({\n \t\t\ttechnicalComparison: [\n+\t\t\t\t{ name: 'obligation-validity', direction: 'minimize', before: 0, after: 0 },\n \t\t\t\t{\n-\t\t\t\t\tname: 'preference-date-conflict',\n-\t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t\tbefore: 0,\n-\t\t\t\t\tafter: 0,\n-\t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tname: 'placement-date',\n+\t\t\t\t\tname: `optimization:${presets[0].id}`,\n \t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t\tbefore: '2024-01-02',\n-\t\t\t\t\tafter: '2024-01-03',\n+\t\t\t\t\tbefore: 2,\n+\t\t\t\t\tafter: 1,\n \t\t\t\t},\n \t\t\t],\n-\t\t\tfirstDecisiveComparator: 'placement-date',\n+\t\t\tfirstDecisiveComparator: `optimization:${presets[0].id}`,\n \t\t});\n \t\texpect(jan2?.deltas).toContainEqual(\n \t\t\texpect.objectContaining({\n@@ -399,22 +408,17 @@ describe('planner explanation and trace seam', () => {\n \t\t\t}),\n \t\t);\n \t\texpect(jan3?.candidates.some((candidate) => candidate.status === 'chosen')).toBe(true);\n-\t\texpect(jan3?.candidates[0]).toMatchObject({\n+\t\texpect(jan3?.candidates.find((candidate) => candidate.status === 'chosen')).toMatchObject({\n \t\t\ttechnicalComparison: [\n+\t\t\t\t{ name: 'obligation-validity', direction: 'minimize', before: 0, after: 0 },\n \t\t\t\t{\n-\t\t\t\t\tname: 'preference-date-conflict',\n+\t\t\t\t\tname: `optimization:${presets[0].id}`,\n \t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t\tbefore: 0,\n+\t\t\t\t\tbefore: 1,\n \t\t\t\t\tafter: 0,\n \t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tname: 'placement-date',\n-\t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t\tbefore: '2024-01-03',\n-\t\t\t\t\tafter: '2024-01-04',\n-\t\t\t\t},\n \t\t\t],\n-\t\t\tfirstDecisiveComparator: 'placement-date',\n+\t\t\tfirstDecisiveComparator: `optimization:${presets[0].id}`,\n \t\t});\n \t\texpect(jan3?.deltas).toContainEqual(\n \t\t\texpect.objectContaining({\n@@ -541,29 +545,39 @@ describe('planner explanation and trace seam', () => {\n \t\t\t?.decisions.flatMap((decision) => decision.candidates)\n \t\t\t.find((item) => item.status === 'chosen' && item.date === '2024-01-03');\n \t\texpect(candidate).toMatchObject({\n-\t\t\ttechnicalComparison: [\n-\t\t\t\t{\n-\t\t\t\t\tname: 'shared-placement-type',\n-\t\t\t\t\tdirection: 'maximize',\n-\t\t\t\t\tbefore: 0,\n-\t\t\t\t\tafter: 0,\n-\t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tname: 'protected-preference-type',\n-\t\t\t\t\tdirection: 'maximize',\n-\t\t\t\t\tbefore: 1,\n-\t\t\t\t\tafter: 1,\n-\t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tname: 'balance-expiry',\n-\t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t\tbefore: '2025-01-05',\n-\t\t\t\t\tafter: '2025-01-06',\n-\t\t\t\t},\n-\t\t\t],\n-\t\t\tfirstDecisiveComparator: 'balance-expiry',\n+\t\t\tfirstDecisiveComparator: 'preference:rtt-preference',\n \t\t\tplacement: expect.objectContaining({ balanceId: 'rtt-first' }),\n \t\t});\n+\t\tconst compared = trace.phases\n+\t\t\t.find((phase) => phase.name === 'preference:any-preference')\n+\t\t\t?.decisions.flatMap((decision) => decision.candidates);\n+\t\texpect(compared).toContainEqual(\n+\t\t\texpect.objectContaining({\n+\t\t\t\tstatus: 'evaluated-rejected',\n+\t\t\t\tplacement: expect.objectContaining({ balanceId: 'rtt-second' }),\n+\t\t\t\ttechnicalComparison: expect.arrayContaining([\n+\t\t\t\t\t{\n+\t\t\t\t\t\tname: 'preference:any-preference',\n+\t\t\t\t\t\tdirection: 'maximize',\n+\t\t\t\t\t\tbefore: 1,\n+\t\t\t\t\t\tafter: 1,\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\tname: 'preference:rtt-preference',\n+\t\t\t\t\t\tdirection: 'maximize',\n+\t\t\t\t\t\tbefore: 1,\n+\t\t\t\t\t\tafter: 1,\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\tname: 'balance-expiry',\n+\t\t\t\t\t\tdirection: 'minimize',\n+\t\t\t\t\t\tbefore: '2025-01-05',\n+\t\t\t\t\t\tafter: '2025-01-06',\n+\t\t\t\t\t},\n+\t\t\t\t]),\n+\t\t\t\tfirstDecisiveComparator: 'balance-expiry',\n+\t\t\t}),\n+\t\t);\n \t});\n \n \tit('records actual IfThen leaf comparisons and selected branch identity', async () => {\n@@ -593,8 +607,8 @@ describe('planner explanation and trace seam', () => {\n \t\t\t.flatMap((decision) =>\n \t\t\t\tdecision.candidates\n \t\t\t\t\t.filter((candidate) =>\n-\t\t\t\t\t\tcandidate.technicalComparison?.some((item) =>\n-\t\t\t\t\t\t\titem.name.startsWith('complete-occurrences:if-then-preference'),\n+\t\t\t\t\t\tcandidate.technicalComparison?.some(\n+\t\t\t\t\t\t\t(item) => item.name === 'preference:if-then-preference',\n \t\t\t\t\t\t),\n \t\t\t\t\t)\n \t\t\t\t\t.map((candidate) => ({ candidate, decision })),\n@@ -605,8 +619,8 @@ describe('planner explanation and trace seam', () => {\n \t\t\t\t.find((phase) => phase.name === 'preference:if-then-preference')\n \t\t\t\t?.decisions.flatMap((decision) => decision.candidates)\n \t\t\t\t.filter((candidate) =>\n-\t\t\t\t\tcandidate.technicalComparison?.some((item) =>\n-\t\t\t\t\t\titem.name.startsWith('complete-occurrences:if-then-preference'),\n+\t\t\t\t\tcandidate.technicalComparison?.some(\n+\t\t\t\t\t\t(item) => item.name === 'preference:if-then-preference',\n \t\t\t\t\t),\n \t\t\t\t) ?? [];\n \t\texpect(preferenceLeaves.length).toBeGreaterThan(1);\n@@ -620,16 +634,14 @@ describe('planner explanation and trace seam', () => {\n \t\texpect(chosen?.candidate.technicalComparison).toEqual(\n \t\t\texpect.arrayContaining([\n \t\t\t\texpect.objectContaining({\n-\t\t\t\t\tname: 'complete-occurrences:if-then-preference',\n+\t\t\t\t\tname: 'preference:if-then-preference',\n \t\t\t\t\tdirection: 'maximize',\n \t\t\t\t}),\n-\t\t\t\texpect.objectContaining({\n-\t\t\t\t\tname: 'future-pattern-conflict-score:if-then-preference',\n-\t\t\t\t\tdirection: 'minimize',\n-\t\t\t\t}),\n \t\t\t]),\n \t\t);\n-\t\texpect(chosen?.decision.branch?.deltas.length).toBeGreaterThan(0);\n+\t\texpect(\n+\t\t\t(chosen?.decision.branch?.deltas ?? chosen?.decision.deltas ?? []).length,\n+\t\t).toBeGreaterThan(0);\n \t\texpect(\n \t\t\tchosen?.candidate.dates?.every((date) =>\n \t\t\t\toutcome.placements.some((p) => p.date === date),\n@@ -749,46 +761,52 @@ describe('planner explanation and trace seam', () => {\n \t\t\thorizon: { start: '2024-04-25', end: '2024-05-08' },\n \t\t\tbalances: [\n \t\t\t\tbalance('cp1', 'cp', 1, '2025-12-31'),\n-\t\t\t\tbalance('cp2', 'cp', 2, '2024-05-07'),\n+\t\t\t\t{ ...balance('cp2', 'cp', 2, '2024-05-07'), availableFrom: '2024-04-26' },\n \t\t\t\tbalance('rtt', 'rtt', 0, '2026-01-01'),\n \t\t\t],\n \t\t\trules: [\n-\t\t\t\t{\n-\t\t\t\t\tid: 'anchor',\n-\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\tstartDate: '2024-04-25',\n-\t\t\t\t\tendDate: '2024-04-25',\n-\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tid: 'producer',\n-\t\t\t\t\ttype: 'if_then',\n-\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\tdayOfWeek: 3,\n-\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\tplacement: 'after',\n-\t\t\t\t\trewardDays: 1,\n-\t\t\t\t\trewardType: 'rtt',\n-\t\t\t\t},\n-\t\t\t\t{\n-\t\t\t\t\tid: 'consumer',\n-\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\tstartDate: '2024-05-06',\n-\t\t\t\t\tendDate: '2024-05-06',\n-\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\tplaceType: 'rtt',\n-\t\t\t\t},\n+\t\t\t\tpresets[0],\n+\t\t\t\t...[\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'anchor',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tstartDate: '2024-04-25',\n+\t\t\t\t\t\tendDate: '2024-04-25',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\trewardType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'consumer',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tstartDate: '2024-05-06',\n+\t\t\t\t\t\tendDate: '2024-05-06',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\t...presets.slice(1),\n \t\t\t],\n \t\t});\n \t\tconst outcome = await calculation.outcome;\n \t\texpect(outcome.kind).toBe('Plan');\n \t\tif (outcome.kind !== 'Plan') return;\n \t\tconst atRisk = outcome.placements.find(\n-\t\t\t(placement) => placement.balanceId === 'cp2' && !placement.ruleIds.length,\n+\t\t\t(placement) =>\n+\t\t\t\tplacement.balanceId === 'cp2' &&\n+\t\t\t\tplacement.ruleIds.every((id) => id.startsWith('default-')),\n \t\t);\n \t\texpect(atRisk?.date).toBeDefined();\n \t\tif (!atRisk) return;\n@@ -1006,7 +1024,11 @@ describe('planner explanation and trace seam', () => {\n \t\t\texpect((await calculation.explanation)?.kind).toBe('ConflictExplanation');\n \t\t\tconst trace = await calculation.trace;\n \t\t\texpect(trace?.phases.some((phase) => phase.name === 'obligations')).toBe(true);\n-\t\t\texpect(trace?.phases.some((phase) => phase.name === 'holiday-week-value')).toBe(false);\n+\t\t\texpect(\n+\t\t\t\ttrace?.phases.some(\n+\t\t\t\t\t(phase) => phase.name === 'optimization:default-holiday-week-value',\n+\t\t\t\t),\n+\t\t\t).toBe(false);\n \t\t\tif (index === 1)\n \t\t\t\texpect(\n \t\t\t\t\ttrace?.phases\n@@ -1076,9 +1098,10 @@ describe('planner explanation and trace seam', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\tbalances: [balance('cp', 'cp', 2, '2024-01-31')],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t\tprogress: (stage: string) => {\n-\t\t\t\tif (stage === 'holiday-week-value') throw new Error('interrupted after checkpoint');\n+\t\t\t\tif (stage === 'optimization:default-holiday-week-value')\n+\t\t\t\t\tthrow new Error('interrupted after checkpoint');\n \t\t\t},\n \t\t};\n \t\tconst outcome = core.calculatePlanningInternal(request, (plan, state) => {\n@@ -1128,8 +1151,8 @@ describe('planner explanation and trace seam', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-15' },\n \t\t\tbalances: [balance('cp', 'cp', 3, '2024-01-31')],\n-\t\t\trules: [],\n-\t\t\tdeadlineMs: 1_000,\n+\t\t\trules: presets,\n+\t\t\tdeadlineMs: 100_000,\n \t\t};\n \t\tconst plain = core.calculatePlanningInternal(request);\n \t\tclock = 0;\n@@ -1156,6 +1179,7 @@ describe('planner explanation and trace seam', () => {\n \t\texpect(artifacts?.trace?.status).toBe('ready');\n \t\texpect(artifacts?.timings?.planningWorkMs).toBeLessThan(request.deadlineMs);\n \t\texpect(artifacts?.timings?.traceTransferMs).toBeGreaterThanOrEqual(callbackCount * 10_000);\n+\t\texpect(artifacts?.timings?.traceTransferMs).toBeGreaterThan(request.deadlineMs);\n \t\tconst decisions = artifacts?.trace?.phases.flatMap((phase) => phase.decisions) ?? [];\n \t\tconst candidateUpdates = operations.filter((operation) => operation.kind === 'candidate');\n \t\texpect(candidateUpdates.some((operation) => operation.mode === 'replace')).toBe(true);\n@@ -1180,7 +1204,7 @@ describe('planner explanation and trace seam', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-08' },\n \t\t\tbalances: [balance('cp', 'cp', 2, '2024-01-07')],\n-\t\t\trules: [],\n+\t\t\trules: [presets[0]],\n \t\t};\n \t\tlet plainArtifacts: import('./leave-planner.core').PlanningArtifacts | undefined;\n \t\tconst plain = core.calculatePlanningInternal(request, undefined, (value) => {\n@@ -1210,6 +1234,7 @@ describe('planner explanation and trace seam', () => {\n \t\t\t\tcandidate,\n \t\t\t})),\n \t\t);\n+\t\texpect(candidates.length).toBeGreaterThan(0);\n \t\tconst candidateOperations = operations.filter(\n \t\t\t(operation): operation is Extract =>\n \t\t\t\toperation.kind === 'candidate',\n@@ -1232,7 +1257,7 @@ describe('planner explanation and trace seam', () => {\n \t\tconst early = createPlanningCalculation({\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\tbalances: [balance('cp', 'cp', 1, '2024-01-31')],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t\tdeadlineMs: 0,\n \t\t});\n \t\tconst earlyOutcome = await early.outcome;\n@@ -1247,16 +1272,18 @@ describe('planner explanation and trace seam', () => {\n \t\texpect(earlyTrace?.phases.find((phase) => phase.name === 'obligations')?.status).toBe(\n \t\t\t'interrupted',\n \t\t);\n-\t\texpect(earlyTrace?.phases.find((phase) => phase.name === 'at-risk')?.status).toBe(\n-\t\t\t'not-run',\n-\t\t);\n+\t\texpect(\n+\t\t\tearlyTrace?.phases.find(\n+\t\t\t\t(phase) => phase.name === 'optimization:default-unplaced-at-risk',\n+\t\t\t)?.status,\n+\t\t).toBe('not-run');\n \n \t\tconst quality = createPlanningCalculation({\n \t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n \t\t\tbalances: [balance('cp', 'cp', 1, '2024-01-31')],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t\tprogress: (stage) => {\n-\t\t\t\tif (stage === 'holiday-week-value') {\n+\t\t\t\tif (stage === 'optimization:default-holiday-week-value') {\n \t\t\t\t\tthrow new Error('deliberate interruption in quality phase');\n \t\t\t\t}\n \t\t\t},\n@@ -1266,13 +1293,21 @@ describe('planner explanation and trace seam', () => {\n \t\texpect(qualityOutcome.kind).toBe('PlanningIncomplete');\n \t\tif (qualityOutcome.kind !== 'PlanningIncomplete') return;\n \t\texpect(qualityOutcome.reasons[0].code).toBe('planner-error');\n-\t\texpect(qualityOutcome.completedStages).toEqual(['validation', 'obligations', 'at-risk']);\n+\t\texpect(qualityOutcome.completedStages).toEqual([\n+\t\t\t'validation',\n+\t\t\t'obligations',\n+\t\t\t'optimization:default-unplaced-at-risk',\n+\t\t]);\n \t\texpect(qualityTrace?.completedStages).toEqual(qualityOutcome.completedStages);\n \t\texpect(\n-\t\t\tqualityTrace?.phases.find((phase) => phase.name === 'holiday-week-value')?.status,\n+\t\t\tqualityTrace?.phases.find(\n+\t\t\t\t(phase) => phase.name === 'optimization:default-holiday-week-value',\n+\t\t\t)?.status,\n \t\t).toBe('interrupted');\n \t\texpect(\n-\t\t\tqualityTrace?.phases.find((phase) => phase.name === 'non-working-day-gain')?.status,\n+\t\t\tqualityTrace?.phases.find(\n+\t\t\t\t(phase) => phase.name === 'optimization:default-non-working-day-gain',\n+\t\t\t)?.status,\n \t\t).toBe('not-run');\n \t});\n });\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner-explanation.spec.ts", "project_id": 35, "relative_order": 21, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,186 @@\n+import { createOptimizationPresetRules } from './rule-service';\n+import { describe, expect, it } from 'vitest';\n+import { calculatePlanningInternal, type PlanningArtifacts } from './leave-planner.core';\n+import {\n+\tevaluateOptimization,\n+\tOPTIMIZATION_PRESETS,\n+\ttype OptimizationObservations,\n+} from './planning-objectives';\n+\n+const presets = createOptimizationPresetRules();\n+\n+describe('planning objective observations', () => {\n+\tit.each([\n+\t\t{ start: '2024-05-06', end: '2024-05-13' },\n+\t\t{ start: '2024-05-10', end: '2024-05-11' },\n+\t])(\n+\t\t'evaluates the same declared holiday week and supporting placement at horizon boundaries',\n+\t\t(horizon) => {\n+\t\t\tconst result = calculatePlanningInternal({\n+\t\t\t\thorizon,\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2024-05-06',\n+\t\t\t\t\t\texpiryDate: '2025-05-06',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules: presets,\n+\t\t\t\tdeclaredDays: ['2024-05-06', '2024-05-07'].map((date) => ({ date, type: 'other' })),\n+\t\t\t});\n+\t\t\texpect(result.kind).toBe('Plan');\n+\t\t\tif (result.kind !== 'Plan') return;\n+\t\t\texpect(result.placements).toEqual([\n+\t\t\t\t{\n+\t\t\t\t\tdate: '2024-05-10',\n+\t\t\t\t\tbalanceId: 'cp',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\truleIds: ['default-holiday-week-value'],\n+\t\t\t\t\tsupporting: true,\n+\t\t\t\t},\n+\t\t\t]);\n+\t\t\tconst observations: OptimizationObservations = {\n+\t\t\t\tleaveBalances: [{ unplacedQuantity: 0, atRisk: false }],\n+\t\t\t\tpublicHolidayWeeks: [{ value: 5, complete: true }],\n+\t\t\t\ttimeOffPeriods: result.timeOffPeriods,\n+\t\t\t\tworkSequences: [\n+\t\t\t\t\t{ length: 0, internal: false },\n+\t\t\t\t\t{ length: 0, internal: false },\n+\t\t\t\t],\n+\t\t\t\tleavePlacements: result.placements,\n+\t\t\t};\n+\t\t\texpect(\n+\t\t\t\tObject.values(OPTIMIZATION_PRESETS).map((configuration) =>\n+\t\t\t\t\tevaluateOptimization(configuration, observations),\n+\t\t\t\t),\n+\t\t\t).toEqual([0, 5, 6, 0, 0, 1]);\n+\t\t\texpect(result.metrics).toMatchObject({\n+\t\t\t\tunplacedAtRisk: 0,\n+\t\t\t\tholidayWeekValue: 5,\n+\t\t\t\tnonWorkingDayGain: 6,\n+\t\t\t\tlongestWorkSequence: 0,\n+\t\t\t\tshortSequenceDeficit: 0,\n+\t\t\t\tsupportingPlacements: 1,\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit('uses internal working-day deficits while retaining both horizon edges in the maximum', () => {\n+\t\tconst result = calculatePlanningInternal({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-18' },\n+\t\t\tbalances: [],\n+\t\t\trules: [],\n+\t\t\tdeclaredDays: ['2024-01-05', '2024-01-09'].map((date) => ({ date, type: 'other' })),\n+\t\t});\n+\t\texpect(result.kind).toBe('Plan');\n+\t\tif (result.kind !== 'Plan') return;\n+\t\texpect(result.metrics).toMatchObject({\n+\t\t\tlongestWorkSequence: 6,\n+\t\t\tshortSequenceDeficit: 4,\n+\t\t\tnonWorkingDayGain: 2,\n+\t\t});\n+\t\tconst observations: OptimizationObservations = {\n+\t\t\tleaveBalances: [],\n+\t\t\tpublicHolidayWeeks: [],\n+\t\t\ttimeOffPeriods: result.timeOffPeriods,\n+\t\t\tworkSequences: [\n+\t\t\t\t{ length: 3, internal: false },\n+\t\t\t\t{ length: 1, internal: true },\n+\t\t\t\t{ length: 6, internal: false },\n+\t\t\t],\n+\t\t\tleavePlacements: result.placements,\n+\t\t};\n+\t\texpect(evaluateOptimization(OPTIMIZATION_PRESETS.shortSequenceDeficit, observations)).toBe(\n+\t\t\t4,\n+\t\t);\n+\t\texpect(\n+\t\t\tevaluateOptimization(\n+\t\t\t\t{ ...OPTIMIZATION_PRESETS.shortSequenceDeficit, thresholdDays: 3 },\n+\t\t\t\tobservations,\n+\t\t\t),\n+\t\t).toBe(2);\n+\t});\n+\n+\tit.each([\n+\t\t['2024-01-01', '2024-01-06', ['2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'], 1],\n+\t\t['2018-04-30', '2018-05-05', ['2018-04-30', '2018-05-02', '2018-05-03', '2018-05-04'], 2],\n+\t\t['2024-04-29', '2024-05-04', ['2024-04-29', '2024-04-30', '2024-05-02', '2024-05-03'], 3],\n+\t\t['2024-08-12', '2024-08-17', ['2024-08-12', '2024-08-13', '2024-08-14', '2024-08-16'], 2],\n+\t\t['2024-10-28', '2024-11-02', ['2024-10-28', '2024-10-29', '2024-10-30', '2024-10-31'], 1],\n+\t] as const)(\n+\t\t'retains the weekday holiday weight in the completed week starting %s',\n+\t\t(start, end, dates, value) => {\n+\t\t\tconst result = calculatePlanningInternal({\n+\t\t\t\thorizon: { start, end },\n+\t\t\t\tbalances: [],\n+\t\t\t\trules: [],\n+\t\t\t\tdeclaredDays: dates.map((date) => ({ date, type: 'other' })),\n+\t\t\t});\n+\t\t\texpect(result.kind).toBe('Plan');\n+\t\t\tif (result.kind === 'Plan') expect(result.metrics.holidayWeekValue).toBe(value);\n+\t\t},\n+\t);\n+\n+\tit('keeps the historical objective order in the explanation of a jointly valid plan', () => {\n+\t\tlet artifacts: PlanningArtifacts | undefined;\n+\t\tconst result = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\thorizon: { start: '2024-01-02', end: '2024-01-18' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2024-01-02',\n+\t\t\t\t\t\texpiryDate: '2024-01-17',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules: [\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'fixed',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\t\tstartDate: '2024-01-05',\n+\t\t\t\t\t\t\tendDate: '2024-01-05',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'personal',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tstartDate: '2024-01-09',\n+\t\t\t\t\t\t\tendDate: '2024-01-09',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n+\t\t\t\t],\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\texpect(result.kind).toBe('Plan');\n+\t\texpect(artifacts?.explanation?.kind).toBe('PlanExplanation');\n+\t\tif (artifacts?.explanation?.kind !== 'PlanExplanation') return;\n+\t\tconst placement = artifacts.explanation.placements[0];\n+\t\texpect(placement.objectiveVector.objectives.map((objective) => objective.id)).toEqual([\n+\t\t\t'obligation-validity',\n+\t\t\t'optimization:default-unplaced-at-risk',\n+\t\t\t'preference:personal',\n+\t\t\t'optimization:default-holiday-week-value',\n+\t\t\t'optimization:default-non-working-day-gain',\n+\t\t\t'optimization:default-longest-work-sequence',\n+\t\t\t'optimization:default-short-sequence-deficit',\n+\t\t\t'optimization:default-supporting-placements',\n+\t\t\t'balance-expiry',\n+\t\t\t'placement-date',\n+\t\t]);\n+\t\texpect(placement.firstDecisiveObjective).toBe('obligation-validity');\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/services/leave-planner-objectives.spec.ts", "project_id": 35, "relative_order": 22, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,10 +1,116 @@\n+import { createOptimizationPresetRules } from './rule-service';\n import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';\n import { createPlanningCalculation } from './leave-planner.service';\n+import {\n+\tcalculatePlanningInternal,\n+\ttype PlanningArtifacts,\n+\ttype PlanningTraceCandidate,\n+\ttype PlanningTraceUpdate,\n+} from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n \n beforeEach(() => vi.stubGlobal('window', undefined));\n afterEach(() => vi.unstubAllGlobals());\n \n+const presets = createOptimizationPresetRules();\n+\n describe('quality calculation trace', () => {\n+\tit('keeps emitted comparison metadata unchanged when candidate snapshots are replaced', () => {\n+\t\tconst updates: PlanningTraceUpdate[] = [];\n+\t\tconst captured: string[] = [];\n+\t\tlet artifacts: PlanningArtifacts = {};\n+\t\tlet clock = 0;\n+\t\tconst clockSpy = vi.spyOn(performance, 'now').mockImplementation(() => (clock += 30));\n+\t\ttry {\n+\t\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t\t{\n+\t\t\t\t\tcalculationDate: '2026-11-01',\n+\t\t\t\t\thorizon: { start: '2026-11-03', end: '2026-11-14' },\n+\t\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2027-01-01' }],\n+\t\t\t\t\tdeclaredDays: [\n+\t\t\t\t\t\t{ date: '2026-11-09', type: 'other' },\n+\t\t\t\t\t\t{ date: '2026-11-10', type: 'other' },\n+\t\t\t\t\t],\n+\t\t\t\t\trules: [\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'holiday',\n+\t\t\t\t\t\t\tname: 'Holiday weeks',\n+\t\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\t...[3, 5].map((thresholdDays) => ({\n+\t\t\t\t\t\t\tid: `deficit-${thresholdDays}`,\n+\t\t\t\t\t\t\tname: `Deficit ${thresholdDays} days`,\n+\t\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t\t\t\tconditions: ['non-empty'],\n+\t\t\t\t\t\t\t\tthresholdDays,\n+\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t})),\n+\t\t\t\t\t],\n+\t\t\t\t\ttraceProgress: (_elapsed: number, update: PlanningTraceUpdate) => {\n+\t\t\t\t\t\tupdates.push(update);\n+\t\t\t\t\t\tcaptured.push(JSON.stringify(update));\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\texpect(outcome.kind).toBe('Plan');\n+\t\t\texpect(artifacts.trace?.status).toBe('ready');\n+\t\t\texpect(updates.map((update) => JSON.stringify(update))).toEqual(captured);\n+\t\t\tconst emitted = new Map();\n+\t\t\tlet replacements = 0;\n+\t\t\tfor (const update of updates)\n+\t\t\t\tfor (const operation of update.operations) {\n+\t\t\t\t\tif (operation.kind !== 'candidate') continue;\n+\t\t\t\t\tif (operation.mode === 'replace') replacements++;\n+\t\t\t\t\temitted.set(\n+\t\t\t\t\t\t`${operation.phaseId}/${operation.decisionId}/${operation.index}`,\n+\t\t\t\t\t\toperation.candidate,\n+\t\t\t\t\t);\n+\t\t\t\t}\n+\t\t\texpect(replacements).toBeGreaterThan(0);\n+\t\t\texpect(emitted.size).toBeGreaterThan(0);\n+\t\t\tfor (const phase of artifacts.trace!.phases)\n+\t\t\t\tfor (const decision of phase.decisions)\n+\t\t\t\t\tdecision.candidates.forEach((candidate, index) =>\n+\t\t\t\t\t\texpect(emitted.get(`${phase.id}/${decision.id}/${index}`)).toEqual(\n+\t\t\t\t\t\t\tcandidate,\n+\t\t\t\t\t\t),\n+\t\t\t\t\t);\n+\t\t\tconst comparison = [...emitted.values()].find(\n+\t\t\t\t(candidate) => candidate.comparison,\n+\t\t\t)?.comparison;\n+\t\t\texpect(comparison?.after.objectives).toEqual(\n+\t\t\t\texpect.arrayContaining([\n+\t\t\t\t\texpect.objectContaining({\n+\t\t\t\t\t\tid: 'optimization:deficit-3',\n+\t\t\t\t\t\tlabel: 'Deficit 3 days',\n+\t\t\t\t\t\tdirection: 'minimize',\n+\t\t\t\t\t}),\n+\t\t\t\t\texpect.objectContaining({\n+\t\t\t\t\t\tid: 'optimization:deficit-5',\n+\t\t\t\t\t\tlabel: 'Deficit 5 days',\n+\t\t\t\t\t\tdirection: 'minimize',\n+\t\t\t\t\t}),\n+\t\t\t\t]),\n+\t\t\t);\n+\t\t\texpect(\n+\t\t\t\t[...emitted.values()].some(({ comparison }) => {\n+\t\t\t\t\tconst values = comparison?.after.objectives;\n+\t\t\t\t\treturn (\n+\t\t\t\t\t\tvalues?.find(({ id }) => id === 'optimization:deficit-3')?.value === 0 &&\n+\t\t\t\t\t\tvalues?.find(({ id }) => id === 'optimization:deficit-5')?.value === 1\n+\t\t\t\t\t);\n+\t\t\t\t}),\n+\t\t\t).toBe(true);\n+\t\t} finally {\n+\t\t\tclockSpy.mockRestore();\n+\t\t}\n+\t});\n+\n \tit('separates source effects from the actual incumbent comparison', async () => {\n \t\tconst calculation = createPlanningCalculation({\n \t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n@@ -17,71 +123,47 @@ describe('quality calculation trace', () => {\n \t\t\t\t\texpiryDate: '2024-01-31',\n \t\t\t\t},\n \t\t\t],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t});\n-\t\tconst outcome = await calculation.outcome;\n+\t\texpect((await calculation.outcome).kind).toBe('Plan');\n \t\tconst trace = await calculation.trace;\n-\t\texpect(outcome.kind).toBe('Plan');\n \t\texpect(trace?.status).toBe('ready');\n-\t\tif (outcome.kind !== 'Plan' || !trace) return;\n-\n-\t\tconst phase = trace.phases.find((item) => item.name === 'non-working-day-gain');\n-\t\tconst jan3Decision = phase?.decisions.find((decision) =>\n-\t\t\tdecision.candidates.some((candidate) => candidate.sourceDate === '2024-01-03'),\n-\t\t);\n-\t\tconst jan2Decision = phase?.decisions.find((decision) =>\n-\t\t\tdecision.candidates.some((candidate) => candidate.sourceDate === '2024-01-02'),\n+\t\tconst phase = trace?.phases.find(({ name }) => name === `optimization:${presets[0].id}`);\n+\t\tconst decision = phase?.decisions.find(({ candidates }) =>\n+\t\t\tcandidates.some(({ status, date }) => status === 'chosen' && date === '2024-01-02'),\n \t\t);\n-\t\tconst jan5 = jan3Decision?.candidates.find(\n-\t\t\t(candidate) => candidate.sourceDate === '2024-01-03' && candidate.date === '2024-01-05',\n+\t\tconst rejected = decision?.candidates.find(\n+\t\t\t({ date, comparison }) => date === '2024-01-05' && comparison,\n \t\t);\n-\t\tconst jan8 = jan3Decision?.candidates.find(\n-\t\t\t(candidate) => candidate.sourceDate === '2024-01-03' && candidate.date === '2024-01-08',\n-\t\t);\n-\n-\t\texpect(jan2Decision).toBeDefined();\n-\t\texpect(jan3Decision).toBeDefined();\n-\t\texpect(jan3Decision).not.toBe(jan2Decision);\n-\t\texpect(jan3Decision?.dates).toEqual(['2024-01-03', '2024-01-05']);\n-\t\texpect(jan5?.status).toBe('chosen');\n-\t\texpect(jan8?.status).toBe('evaluated-rejected');\n-\t\texpect(jan3Decision?.deltas).toContainEqual(\n+\t\texpect(rejected?.status).toBe('evaluated-rejected');\n+\t\tconst sourceValue = (state: 'before' | 'after', id: string) =>\n+\t\t\trejected?.comparison?.[state].objectives.find((objective) => objective.id === id)\n+\t\t\t\t?.value;\n+\t\texpect(sourceValue('before', `optimization:${presets[0].id}`)).toBe(2);\n+\t\texpect(sourceValue('after', `optimization:${presets[0].id}`)).toBe(1);\n+\t\texpect(sourceValue('before', `optimization:${presets[2].id}`)).toBe(0);\n+\t\texpect(sourceValue('after', `optimization:${presets[2].id}`)).toBe(2);\n+\t\texpect(rejected?.comparison?.firstDecisiveObjective).toBe(`optimization:${presets[0].id}`);\n+\t\t// The January 2 candidate already gains three natural non-working days.\n+\t\t// January 5 improves its source state, but loses to that current best candidate.\n+\t\texpect(rejected?.technicalComparison).toContainEqual({\n+\t\t\tname: `optimization:${presets[2].id}`,\n+\t\t\tdirection: 'maximize',\n+\t\t\tbefore: 3,\n+\t\t\tafter: 2,\n+\t\t});\n+\t\texpect(\n+\t\t\trejected?.technicalComparison?.some(\n+\t\t\t\t({ name }) => name === `optimization:${presets[3].id}`,\n+\t\t\t),\n+\t\t).toBe(false);\n+\t\texpect(rejected?.firstDecisiveComparator).toBe(`optimization:${presets[2].id}`);\n+\t\texpect(rejected?.reason?.message).toContain('did not improve the current best result');\n+\t\texpect(decision?.deltas).toContainEqual(\n \t\t\texpect.objectContaining({\n-\t\t\t\tkind: 'placement-moved',\n-\t\t\t\tfromDate: '2024-01-03',\n-\t\t\t\ttoDate: '2024-01-05',\n+\t\t\t\tkind: 'placement-added',\n+\t\t\t\tdate: '2024-01-02',\n \t\t\t}),\n \t\t);\n-\n-\t\tconst sourceValue = (\n-\t\t\tcandidate: typeof jan5,\n-\t\t\tstate: 'before' | 'after',\n-\t\t\tobjective: string,\n-\t\t) => candidate?.comparison?.[state].objectives.find((item) => item.id === objective)?.value;\n-\t\texpect(sourceValue(jan5, 'before', 'non-working-day-gain')).toBe(3);\n-\t\texpect(sourceValue(jan5, 'after', 'non-working-day-gain')).toBe(5);\n-\t\texpect(sourceValue(jan5, 'before', 'longest-work-sequence')).toBe(20);\n-\t\texpect(sourceValue(jan5, 'after', 'longest-work-sequence')).toBe(18);\n-\t\texpect(sourceValue(jan8, 'before', 'non-working-day-gain')).toBe(3);\n-\t\texpect(sourceValue(jan8, 'after', 'non-working-day-gain')).toBe(5);\n-\t\texpect(sourceValue(jan8, 'before', 'longest-work-sequence')).toBe(20);\n-\t\texpect(sourceValue(jan8, 'after', 'longest-work-sequence')).toBe(17);\n-\t\texpect(jan8?.comparison?.firstDecisiveObjective).toBe('non-working-day-gain');\n-\n-\t\texpect(jan8?.technicalComparison).toEqual(\n-\t\t\texpect.arrayContaining([\n-\t\t\t\texpect.objectContaining({\n-\t\t\t\t\tname: 'non-working-day-gain',\n-\t\t\t\t\tdirection: 'maximize',\n-\t\t\t\t\tbefore: 5,\n-\t\t\t\t\tafter: 5,\n-\t\t\t\t}),\n-\t\t\t]),\n-\t\t);\n-\t\texpect(\n-\t\t\tjan8?.technicalComparison?.some((item) => item.name === 'longest-work-sequence'),\n-\t\t).toBe(false);\n-\t\texpect(jan8?.firstDecisiveComparator).toBeUndefined();\n-\t\texpect(jan8?.reason?.message).toContain('did not improve the current best result');\n \t});\n });\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner-quality-trace.spec.ts", "project_id": 35, "relative_order": 23, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,823 @@\n+import { vi } from 'vitest';\n+import {\n+\tcalculatePlanningAsyncInternal,\n+\tcalculatePlanningInternal,\n+\ttype OptimizationPlanningRule,\n+\ttype PlanOutcome,\n+\ttype PlanningArtifacts,\n+\ttype PlanningRequest,\n+\ttype PlanningTraceUpdate,\n+} from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+import { applyReplayDeltas, createPlanningCalculation } from './leave-planner.service';\n+\n+const economy: OptimizationPlanningRule = {\n+\tid: 'economy',\n+\tname: 'Économiser les jours d’appoint',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+};\n+const gain: OptimizationPlanningRule = {\n+\tid: 'gain',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.nonWorkingDayGain,\n+};\n+const requested: PlanningRequest['rules'][number] = {\n+\tid: 'requested',\n+\ttype: 'time_window',\n+\tstartDate: '2024-01-05',\n+\tendDate: '2024-01-05',\n+\tplaceDays: 1,\n+\tplaceType: 'cp',\n+};\n+const weekend: PlanningRequest = {\n+\thorizon: { start: '2024-01-05', end: '2024-01-10' },\n+\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2025-01-01' }],\n+\trules: [],\n+};\n+const bundles: {\n+\tname: string;\n+\trule: OptimizationPlanningRule;\n+\trequest: PlanningRequest;\n+\tdates: string[];\n+}[] = [\n+\t{\n+\t\tname: 'complete public-holiday week',\n+\t\trule: {\n+\t\t\tid: 'holiday',\n+\t\t\ttype: 'optimization',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t},\n+\t\trequest: {\n+\t\t\thorizon: { start: '2026-11-09', end: '2026-11-14' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2027-01-01' }],\n+\t\t\tdeclaredDays: ['2026-11-09', '2026-11-10'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [],\n+\t\t},\n+\t\tdates: ['2026-11-12', '2026-11-13'],\n+\t},\n+\t{\n+\t\tname: 'non-working-day gain',\n+\t\trule: gain,\n+\t\trequest: weekend,\n+\t\tdates: ['2024-01-05'],\n+\t},\n+\t{\n+\t\tname: 'maximum non-working gain of a joined period',\n+\t\trule: {\n+\t\t\t...gain,\n+\t\t\tconfiguration: { ...gain.configuration, aggregation: 'maximum' },\n+\t\t},\n+\t\trequest: {\n+\t\t\thorizon: { start: '2024-01-05', end: '2024-01-13' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 4, expiryDate: '2025-01-01' }],\n+\t\t\tdeclaredDays: ['2024-01-05', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [],\n+\t\t},\n+\t\tdates: ['2024-01-08', '2024-01-09', '2024-01-10', '2024-01-11'],\n+\t},\n+\t{\n+\t\tname: 'complete short internal work sequence',\n+\t\trule: {\n+\t\t\tid: 'deficit',\n+\t\t\ttype: 'optimization',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t},\n+\t\trequest: {\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: ['2024-01-08', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [],\n+\t\t},\n+\t\tdates: ['2024-01-09', '2024-01-10', '2024-01-11'],\n+\t},\n+\t{\n+\t\tname: 'tied longest work sequences',\n+\t\trule: {\n+\t\t\tid: 'longest',\n+\t\t\ttype: 'optimization',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.longestWorkSequence,\n+\t\t},\n+\t\trequest: {\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: [{ date: '2024-01-10', type: 'other' }],\n+\t\t\trules: [],\n+\t\t},\n+\t\tdates: ['2024-01-08', '2024-01-11'],\n+\t},\n+];\n+\n+function plan(request: PlanningRequest): PlanOutcome {\n+\tconst outcome = calculatePlanningInternal(request);\n+\tif (outcome.kind !== 'Plan') throw new Error(`Expected a plan, got ${outcome.kind}`);\n+\treturn outcome;\n+}\n+\n+describe('supporting placement economy and provenance', () => {\n+\tbeforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n+\tafterEach(() => vi.useRealTimers());\n+\n+\tit.each(bundles)(\n+\t\t'compares the whole $name bundle against economy in either order',\n+\t\t({ rule, request, dates }) => {\n+\t\t\tconst improve = plan({ ...request, rules: [rule, economy] });\n+\t\t\tconst preserve = plan({ ...request, rules: [economy, rule] });\n+\t\t\texpect(improve.placements.map(({ date }) => date)).toEqual(dates);\n+\t\t\texpect(improve.placements.every(({ supporting }) => supporting)).toBe(true);\n+\t\t\texpect(improve.metrics.supportingPlacements).toBe(dates.length);\n+\t\t\texpect(improve.remainingBalances).toEqual([]);\n+\t\t\texpect(preserve.placements).toEqual([]);\n+\t\t\texpect(preserve.metrics.supportingPlacements).toBe(0);\n+\t\t\texpect(preserve.remainingBalances[0]).toMatchObject({\n+\t\t\t\tid: 'cp',\n+\t\t\t\tquantity: request.balances[0].quantity,\n+\t\t\t\tclassification: 'deferred',\n+\t\t\t\treason: { code: 'preserved' },\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit.each(bundles)(\n+\t\t'makes disabled economy identical to absence for the $name bundle',\n+\t\t({ rule, request }) => {\n+\t\t\tconst absent = plan({ ...request, rules: [rule] });\n+\t\t\tfor (const rules of [\n+\t\t\t\t[{ ...economy, enabled: false }, rule],\n+\t\t\t\t[rule, { ...economy, enabled: false }],\n+\t\t\t])\n+\t\t\t\texpect(plan({ ...request, rules })).toEqual(absent);\n+\t\t},\n+\t);\n+\n+\tit('does not add placements merely because economy is disabled or removed', () => {\n+\t\tfor (const rules of [[], [economy], [{ ...economy, enabled: false }]]) {\n+\t\t\tconst outcome = plan({ ...weekend, rules });\n+\t\t\texpect(outcome.placements).toEqual([]);\n+\t\t\texpect(outcome.remainingBalances[0].quantity).toBe(1);\n+\t\t}\n+\t});\n+\n+\tit('credits an earlier supporting placement to a later explicit window without counting an extra day', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...weekend,\n+\t\t\trules: [gain, economy, requested],\n+\t\t});\n+\t\texpect(outcome.placements).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2024-01-05',\n+\t\t\t\tbalanceId: 'cp',\n+\t\t\t\truleIds: ['gain', 'requested'],\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t]);\n+\t\texpect(outcome.metrics).toMatchObject({ nonWorkingDayGain: 2, supportingPlacements: 0 });\n+\t\texpect(outcome.preferences[0].satisfied).toBe(1);\n+\t});\n+\n+\tit('exempts only the requested window quantity, including fixed declared days', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...weekend,\n+\t\t\thorizon: { start: '2024-01-05', end: '2024-01-20' },\n+\t\t\tbalances: [{ ...weekend.balances[0], quantity: 3 }],\n+\t\t\tdeclaredDays: [{ date: '2024-01-09', type: 'cp' }],\n+\t\t\trules: [gain, economy, { ...requested, endDate: '2024-01-19', placeDays: 2 }],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date, supporting }) => ({ date, supporting }))).toEqual([\n+\t\t\t{ date: '2024-01-05', supporting: false },\n+\t\t\t{ date: '2024-01-12', supporting: true },\n+\t\t\t{ date: '2024-01-19', supporting: true },\n+\t\t]);\n+\t\texpect(outcome.metrics.supportingPlacements).toBe(2);\n+\t\texpect(outcome.timeWindowContributions?.[0]).toMatchObject({\n+\t\t\trequested: 2,\n+\t\t\tdeclaredDays: [{ date: '2024-01-09', type: 'cp' }],\n+\t\t\tplacementDates: ['2024-01-05'],\n+\t\t});\n+\t});\n+\n+\tit.each([false, true])(\n+\t\t'bounds explicit calendar credit before accepting further window improvements (declared: %s)',\n+\t\t(declared) => {\n+\t\t\tconst windowRule = { ...requested, endDate: '2024-01-19' };\n+\t\t\tconst request: PlanningRequest = {\n+\t\t\t\t...weekend,\n+\t\t\t\thorizon: { start: '2024-01-05', end: '2024-01-20' },\n+\t\t\t\tbalances: [{ ...weekend.balances[0], quantity: 4 }],\n+\t\t\t\tdeclaredDays: declared ? [{ date: '2024-01-09', type: 'cp' }] : [],\n+\t\t\t\trules: [economy, gain, windowRule],\n+\t\t\t};\n+\t\t\tconst preserve = plan(request);\n+\t\t\texpect(preserve.placements).toEqual(\n+\t\t\t\tdeclared\n+\t\t\t\t\t? []\n+\t\t\t\t\t: [\n+\t\t\t\t\t\t\texpect.objectContaining({\n+\t\t\t\t\t\t\t\tdate: '2024-01-05',\n+\t\t\t\t\t\t\t\truleIds: ['requested'],\n+\t\t\t\t\t\t\t\tsupporting: false,\n+\t\t\t\t\t\t\t}),\n+\t\t\t\t\t\t],\n+\t\t\t);\n+\t\t\texpect(preserve.metrics.supportingPlacements).toBe(0);\n+\t\t\texpect(preserve.preferences[0].satisfied).toBe(1);\n+\t\t\texpect(preserve.remainingBalances[0]).toMatchObject({\n+\t\t\t\tid: 'cp',\n+\t\t\t\tquantity: declared ? 4 : 3,\n+\t\t\t});\n+\t\t\tconst improve = plan({ ...request, rules: [gain, economy, windowRule] });\n+\t\t\texpect(improve.placements.map(({ date }) => date)).toEqual([\n+\t\t\t\t'2024-01-05',\n+\t\t\t\t'2024-01-12',\n+\t\t\t\t'2024-01-19',\n+\t\t\t]);\n+\t\t\texpect(\n+\t\t\t\timprove.placements.filter(({ ruleIds }) => ruleIds.includes('requested')),\n+\t\t\t).toHaveLength(declared ? 0 : 1);\n+\t\t\texpect(improve.metrics.supportingPlacements).toBe(declared ? 3 : 2);\n+\t\t\texpect(\n+\t\t\t\tplan({ ...request, rules: [{ ...economy, enabled: false }, gain, windowRule] }),\n+\t\t\t).toEqual(plan({ ...request, rules: [gain, windowRule] }));\n+\t\t},\n+\t);\n+\n+\tit('restores supporting classification when a moved placement loses its explicit calendar request', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...weekend,\n+\t\t\thorizon: { start: '2024-01-05', end: '2024-01-20' },\n+\t\t\tbalances: [{ ...weekend.balances[0], quantity: 4 }],\n+\t\t\trules: [\n+\t\t\t\tgain,\n+\t\t\t\t{ ...requested, startDate: '2024-01-08', endDate: '2024-01-09' },\n+\t\t\t\tbundles[4].rule,\n+\t\t\t\teconomy,\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.metrics).toMatchObject({\n+\t\t\tnonWorkingDayGain: 6,\n+\t\t\tlongestWorkSequence: 3,\n+\t\t\tsupportingPlacements: 3,\n+\t\t});\n+\t\texpect(outcome.placements.filter(({ supporting }) => !supporting)).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2024-01-08',\n+\t\t\t\truleIds: ['gain', 'requested'],\n+\t\t\t}),\n+\t\t]);\n+\t});\n+\n+\tit.each(['preference', 'obligation'] as const)(\n+\t\t'keeps explicitly requested deferred days outside economy (%s)',\n+\t\t(force) => {\n+\t\t\tconst outcome = plan({ ...weekend, rules: [economy, { ...requested, force }, gain] });\n+\t\t\texpect(outcome.placements).toEqual([\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tdate: '2024-01-05',\n+\t\t\t\t\truleIds: ['requested'],\n+\t\t\t\t\tsupporting: false,\n+\t\t\t\t}),\n+\t\t\t]);\n+\t\t\texpect(outcome.metrics).toMatchObject({\n+\t\t\t\tnonWorkingDayGain: 2,\n+\t\t\t\tsupportingPlacements: 0,\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit('credits the complete explicit IF_THEN pattern without treating its deferred day as support', () => {\n+\t\tconst outcome = plan({\n+\t\t\thorizon: { start: '2024-05-06', end: '2024-05-11' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2025-01-01' }],\n+\t\t\trules: [\n+\t\t\t\tgain,\n+\t\t\t\teconomy,\n+\t\t\t\t{\n+\t\t\t\t\tid: 'thursday',\n+\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\tdayOfWeek: 4,\n+\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\trewardDays: 0,\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2024-05-10',\n+\t\t\t\truleIds: ['gain', 'thursday'],\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t]);\n+\t\texpect(outcome.metrics.supportingPlacements).toBe(0);\n+\t\texpect(outcome.preferences[0].satisfied).toBe(1);\n+\t});\n+\n+\tit.each(['preference', 'obligation'] as const)(\n+\t\t'limits IF_THEN credit to its declared producer pattern when another complete pattern improves rest (%s)',\n+\t\t(force) => {\n+\t\t\tconst request: PlanningRequest = {\n+\t\t\t\thorizon: { start: '2024-05-06', end: '2024-05-11' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 4, expiryDate: '2025-01-01' }],\n+\t\t\t\tdeclaredDays: [{ date: '2024-05-07', type: 'cp' }],\n+\t\t\t\trules: [\n+\t\t\t\t\teconomy,\n+\t\t\t\t\tgain,\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\tforce,\n+\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\tplacement: 'auto',\n+\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\trewardType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t};\n+\t\t\tconst preserve = plan(request);\n+\t\t\texpect(preserve.placements).toEqual([]);\n+\t\t\texpect(preserve.metrics.supportingPlacements).toBe(0);\n+\t\t\texpect(preserve.remainingBalances).toEqual([\n+\t\t\t\texpect.objectContaining({ id: 'cp', quantity: 4 }),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tid: 'earned:producer:2024-05-08',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2024-05-10',\n+\t\t\t\t}),\n+\t\t\t]);\n+\t\t\texpect(preserve.ifThenContributions?.[0]).toMatchObject({\n+\t\t\t\tdeclaredDays: [{ date: '2024-05-07', type: 'cp' }],\n+\t\t\t\tplacementDates: [],\n+\t\t\t\tearnedEntitlement: { availableFrom: '2024-05-10', added: true },\n+\t\t\t});\n+\t\t\tconst improve = plan({ ...request, rules: [gain, economy, request.rules[2]] });\n+\t\t\texpect(improve.placements).toEqual([\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tdate: '2024-05-06',\n+\t\t\t\t\truleIds: ['gain'],\n+\t\t\t\t\tsupporting: true,\n+\t\t\t\t}),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tdate: '2024-05-10',\n+\t\t\t\t\truleIds: ['gain'],\n+\t\t\t\t\tsupporting: true,\n+\t\t\t\t}),\n+\t\t\t]);\n+\t\t\texpect(improve.metrics).toMatchObject({\n+\t\t\t\tnonWorkingDayGain: 6,\n+\t\t\t\tsupportingPlacements: 2,\n+\t\t\t});\n+\t\t\texpect(improve.remainingBalances).toEqual([\n+\t\t\t\texpect.objectContaining({ id: 'cp', quantity: 2 }),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tid: 'earned:producer:2024-05-08',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2024-05-13',\n+\t\t\t\t}),\n+\t\t\t]);\n+\t\t\texpect(improve.ifThenContributions?.[0]).toMatchObject({\n+\t\t\t\tdeclaredDays: [{ date: '2024-05-07', type: 'cp' }],\n+\t\t\t\tplacementDates: [],\n+\t\t\t\tearnedEntitlement: { availableFrom: '2024-05-13', added: true },\n+\t\t\t});\n+\t\t\texpect(\n+\t\t\t\tplan({\n+\t\t\t\t\t...request,\n+\t\t\t\t\trules: [{ ...economy, enabled: false }, gain, request.rules[2]],\n+\t\t\t\t}),\n+\t\t\t).toEqual(plan({ ...request, rules: [gain, request.rules[2]] }));\n+\t\t},\n+\t);\n+\n+\tit('uses expiry then dates when active rules tie, without restoring a removed gain objective', () => {\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-01-09', end: '2024-01-13' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'later', type: 'cp', quantity: 1, expiryDate: '2024-03-01' },\n+\t\t\t\t{ id: 'earlier', type: 'cp', quantity: 1, expiryDate: '2024-02-01' },\n+\t\t\t],\n+\t\t\trules: [economy, { ...requested, startDate: '2024-01-09', endDate: '2024-01-12' }],\n+\t\t};\n+\t\tconst outcome = plan(request);\n+\t\texpect(outcome.placements).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2024-01-09',\n+\t\t\t\tbalanceId: 'earlier',\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t]);\n+\t\texpect(outcome.metrics.nonWorkingDayGain).toBe(0);\n+\t\texpect(\n+\t\t\tplan({ ...request, rules: [{ ...gain, enabled: false }, ...request.rules] }),\n+\t\t).toEqual(outcome);\n+\t});\n+\n+\tit('reclassifies a deferred support addition when an eligible earlier-expiring balance replaces it', () => {\n+\t\tlet artifacts: PlanningArtifacts | undefined;\n+\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\thorizon: { start: '2024-05-06', end: '2024-05-11' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{ id: 'deferred', type: 'cp', quantity: 3, expiryDate: '2025-01-01' },\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'at-risk',\n+\t\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2024-05-07',\n+\t\t\t\t\t\texpiryDate: '2024-05-07',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules: [bundles[0].rule, economy],\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a plan');\n+\t\texpect(\n+\t\t\toutcome.placements.map(({ date, balanceId, supporting }) => ({\n+\t\t\t\tdate,\n+\t\t\t\tbalanceId,\n+\t\t\t\tsupporting,\n+\t\t\t})),\n+\t\t).toEqual([\n+\t\t\t{ date: '2024-05-06', balanceId: 'deferred', supporting: true },\n+\t\t\t{ date: '2024-05-07', balanceId: 'at-risk', supporting: false },\n+\t\t\t{ date: '2024-05-10', balanceId: 'deferred', supporting: true },\n+\t\t]);\n+\t\texpect(outcome.metrics.supportingPlacements).toBe(2);\n+\t\texpect(outcome.remainingBalances[0]).toMatchObject({ id: 'deferred', quantity: 1 });\n+\t\texpect(\n+\t\t\tartifacts?.trace?.phases.flatMap(({ decisions }) =>\n+\t\t\t\tdecisions.flatMap(({ deltas }) => deltas),\n+\t\t\t),\n+\t\t).toContainEqual(\n+\t\t\texpect.objectContaining({\n+\t\t\t\tkind: 'placement-updated',\n+\t\t\t\tpreviousPlacement: expect.objectContaining({\n+\t\t\t\t\tbalanceId: 'deferred',\n+\t\t\t\t\tsupporting: true,\n+\t\t\t\t}),\n+\t\t\t\tplacement: expect.objectContaining({ balanceId: 'at-risk', supporting: false }),\n+\t\t\t}),\n+\t\t);\n+\t});\n+\n+\tit('compares new deferred support when at-risk holiday placements relocate into an explicit window', async () => {\n+\t\tconst holiday = bundles[0].rule;\n+\t\tconst early: PlanningRequest['rules'][number] = {\n+\t\t\tid: 'early',\n+\t\t\ttype: 'time_window',\n+\t\t\tstartDate: '2026-11-02',\n+\t\t\tendDate: '2026-11-03',\n+\t\t\tplaceDays: 2,\n+\t\t\tplaceType: 'cp',\n+\t\t};\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2026-11-02', end: '2026-11-14' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'at-risk', type: 'cp', quantity: 2, expiryDate: '2026-11-13' },\n+\t\t\t\t{\n+\t\t\t\t\tid: 'deferred',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 2,\n+\t\t\t\t\tavailableFrom: '2026-11-12',\n+\t\t\t\t\texpiryDate: '2027-01-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t\tdeclaredDays: ['2026-11-09', '2026-11-10'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [],\n+\t\t};\n+\t\tconst economyFirst = plan({ ...request, rules: [holiday, economy, early] });\n+\t\tlet artifacts: PlanningArtifacts | undefined;\n+\t\tconst updates: { update: PlanningTraceUpdate; snapshot: string }[] = [];\n+\t\tconst windowFirst = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\t...request,\n+\t\t\t\trules: [holiday, early, economy],\n+\t\t\t\ttraceProgress: (_time: number, update: PlanningTraceUpdate) =>\n+\t\t\t\t\tupdates.push({ update, snapshot: JSON.stringify(update) }),\n+\t\t\t},\n+\t\t\t(checkpoint, state) => expect(state?.placements).toEqual(checkpoint.placements),\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\tif (windowFirst.kind !== 'Plan') throw new Error('Expected a plan');\n+\t\texpect(economyFirst.placements).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-12',\n+\t\t\t\tbalanceId: 'at-risk',\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-13',\n+\t\t\t\tbalanceId: 'at-risk',\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t]);\n+\t\texpect(economyFirst.metrics.supportingPlacements).toBe(0);\n+\t\texpect(economyFirst.preferences[0].satisfied).toBe(0);\n+\t\texpect(economyFirst.remainingBalances[0]).toMatchObject({ id: 'deferred', quantity: 2 });\n+\t\texpect(windowFirst.placements).toEqual([\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-02',\n+\t\t\t\tbalanceId: 'at-risk',\n+\t\t\t\truleIds: ['early'],\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-03',\n+\t\t\t\tbalanceId: 'at-risk',\n+\t\t\t\truleIds: ['early'],\n+\t\t\t\tsupporting: false,\n+\t\t\t}),\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-12',\n+\t\t\t\tbalanceId: 'deferred',\n+\t\t\t\truleIds: ['holiday'],\n+\t\t\t\tsupporting: true,\n+\t\t\t}),\n+\t\t\texpect.objectContaining({\n+\t\t\t\tdate: '2026-11-13',\n+\t\t\t\tbalanceId: 'deferred',\n+\t\t\t\truleIds: ['holiday'],\n+\t\t\t\tsupporting: true,\n+\t\t\t}),\n+\t\t]);\n+\t\texpect(windowFirst.metrics.supportingPlacements).toBe(2);\n+\t\texpect(windowFirst.preferences[0].satisfied).toBe(2);\n+\t\texpect(windowFirst.metrics.holidayWeekValue).toBe(3);\n+\t\tif (\n+\t\t\tartifacts?.explanation?.kind !== 'PlanExplanation' ||\n+\t\t\t!artifacts.finalState ||\n+\t\t\t!artifacts.trace\n+\t\t)\n+\t\t\tthrow new Error('Expected matching explanation and trace artifacts');\n+\t\texpect(artifacts.finalState.placements).toEqual(windowFirst.placements);\n+\t\texpect(artifacts.explanation.placements.map(({ placement }) => placement)).toEqual(\n+\t\t\twindowFirst.placements,\n+\t\t);\n+\t\tfor (const placement of artifacts.explanation.placements) {\n+\t\t\tconst contribution = expect.objectContaining({ kind: 'rule', ruleId: 'holiday' });\n+\t\t\tif (placement.supporting) {\n+\t\t\t\texpect(placement.ruleIds).toEqual(['holiday']);\n+\t\t\t\texpect(placement.contributions).toContainEqual(contribution);\n+\t\t\t\texpect(placement.firstDecisiveObjective).toBe('optimization:holiday');\n+\t\t\t} else {\n+\t\t\t\texpect(placement.ruleIds).toEqual(['early']);\n+\t\t\t\texpect(placement.contributions).not.toContainEqual(contribution);\n+\t\t\t}\n+\t\t}\n+\t\tconst replay = {\n+\t\t\tbalances: artifacts.trace.initialState.balances.map((balance) => ({ ...balance })),\n+\t\t\tplacements: new Map(\n+\t\t\t\tartifacts.trace.initialState.placements.map((placement) => [\n+\t\t\t\t\tplacement.date,\n+\t\t\t\t\tplacement,\n+\t\t\t\t]),\n+\t\t\t),\n+\t\t\tearnedActivations: [...artifacts.trace.initialState.earnedActivations],\n+\t\t};\n+\t\tfor (const decision of artifacts.trace.phases.flatMap(({ decisions }) => decisions))\n+\t\t\tapplyReplayDeltas(replay, decision.deltas, artifacts.finalState);\n+\t\texpect(\n+\t\t\t[...replay.placements.values()].sort((a, b) => a.date.localeCompare(b.date)),\n+\t\t).toEqual(windowFirst.placements);\n+\t\texpect(\n+\t\t\tartifacts.trace.phases\n+\t\t\t\t.filter(({ name }) => name === 'preference:early')\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates)),\n+\t\t).toContainEqual(\n+\t\t\texpect.objectContaining({\n+\t\t\t\tstatus: 'chosen',\n+\t\t\t\tplacement: expect.objectContaining({ date: '2026-11-03', ruleIds: ['early'] }),\n+\t\t\t}),\n+\t\t);\n+\t\texpect(updates.length).toBeGreaterThan(0);\n+\t\tfor (const { update, snapshot } of updates) expect(JSON.stringify(update)).toBe(snapshot);\n+\t\tlet cancelled = false;\n+\t\tlet cancelledArtifacts: PlanningArtifacts | undefined;\n+\t\tlet published: PlanOutcome | undefined;\n+\t\tconst partial = await calculatePlanningAsyncInternal(\n+\t\t\t{\n+\t\t\t\t...request,\n+\t\t\t\trules: [holiday, early, economy],\n+\t\t\t\tprogress: (stage: string) => {\n+\t\t\t\t\tif (stage === 'optimization:economy') cancelled = true;\n+\t\t\t\t},\n+\t\t\t\ttraceProgress: (_time: number, update: PlanningTraceUpdate) =>\n+\t\t\t\t\tupdates.push({ update, snapshot: JSON.stringify(update) }),\n+\t\t\t},\n+\t\t\t(checkpoint, state) => {\n+\t\t\t\texpect(state?.placements).toEqual(checkpoint.placements);\n+\t\t\t\tif (checkpoint.lastCompletedStage === 'preference:early') published = checkpoint;\n+\t\t\t},\n+\t\t\t(value) => (cancelledArtifacts = value),\n+\t\t\tundefined,\n+\t\t\tundefined,\n+\t\t\t() => cancelled,\n+\t\t);\n+\t\tif (\n+\t\t\tpartial.kind !== 'PlanningIncomplete' ||\n+\t\t\t!partial.incumbent ||\n+\t\t\tcancelledArtifacts?.explanation?.kind !== 'PlanExplanation'\n+\t\t)\n+\t\t\tthrow new Error('Expected an explained cancelled incumbent');\n+\t\texpect(partial.reasons[0].code).toBe('user-cancelled');\n+\t\texpect(partial.incumbent.placements).toEqual(windowFirst.placements);\n+\t\texpect(partial.incumbent.placements).toEqual(published?.placements);\n+\t\texpect(partial.incumbent.preferences).toMatchObject([{ ruleId: 'early', satisfied: 2 }]);\n+\t\texpect(cancelledArtifacts.finalState?.placements).toEqual(partial.incumbent.placements);\n+\t\texpect(cancelledArtifacts.explanation.placements.map(({ placement }) => placement)).toEqual(\n+\t\t\tpartial.incumbent.placements,\n+\t\t);\n+\t\tfor (const placement of cancelledArtifacts.explanation.placements.slice(0, 2)) {\n+\t\t\texpect(placement.ruleIds).toEqual(['early']);\n+\t\t\texpect(placement.contributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({ kind: 'rule', ruleId: 'early' }),\n+\t\t\t);\n+\t\t}\n+\t\tfor (const { update, snapshot } of updates) expect(JSON.stringify(update)).toBe(snapshot);\n+\t});\n+\n+\tit('keeps established maximum credit when a later earned period masks its local contribution', () => {\n+\t\tlet artifacts: PlanningArtifacts | undefined;\n+\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\thorizon: { start: '2024-05-01', end: '2024-05-11' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-05-03' }],\n+\t\t\t\trules: [\n+\t\t\t\t\t{ ...gain, configuration: { ...gain.configuration, aggregation: 'maximum' } },\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\trewardDays: 2,\n+\t\t\t\t\t\trewardType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\tif (outcome.kind !== 'Plan' || artifacts?.explanation?.kind !== 'PlanExplanation')\n+\t\t\tthrow new Error('Expected an explained plan');\n+\t\texpect(outcome.placements).toMatchObject([\n+\t\t\t{ date: '2024-05-02', ruleIds: ['gain', 'producer'], supporting: false },\n+\t\t\t{ date: '2024-05-03', ruleIds: ['gain'], supporting: false },\n+\t\t\t{ date: '2024-05-10', ruleIds: ['gain'], supporting: true },\n+\t\t]);\n+\t\tfor (const placement of artifacts.explanation.placements.slice(0, 2)) {\n+\t\t\texpect(placement.comparison.delta).toContainEqual(\n+\t\t\t\texpect.objectContaining({ id: 'optimization:gain', value: 0 }),\n+\t\t\t);\n+\t\t\texpect(placement.contributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({ kind: 'rule', ruleId: 'gain' }),\n+\t\t\t);\n+\t\t}\n+\t});\n+\n+\tit('counts reverse deferred reassignment for an edited optimization without explicit calendar credit', () => {\n+\t\tconst request = bundles[0].request;\n+\t\tconst forgoAtRisk: OptimizationPlanningRule = {\n+\t\t\tid: 'forgo',\n+\t\t\ttype: 'optimization',\n+\t\t\tconfiguration: { ...OPTIMIZATION_PRESETS.unplacedAtRisk, direction: 'maximize' },\n+\t\t};\n+\t\tconst outcome = plan({\n+\t\t\t...request,\n+\t\t\tbalances: [\n+\t\t\t\t{ ...request.balances[0], id: 'at-risk', expiryDate: '2026-11-13' },\n+\t\t\t\t{ ...request.balances[0], id: 'deferred' },\n+\t\t\t],\n+\t\t\trules: [bundles[0].rule, forgoAtRisk, economy],\n+\t\t});\n+\t\texpect(\n+\t\t\toutcome.placements.map(({ balanceId, supporting }) => ({ balanceId, supporting })),\n+\t\t).toEqual([\n+\t\t\t{ balanceId: 'deferred', supporting: true },\n+\t\t\t{ balanceId: 'deferred', supporting: true },\n+\t\t]);\n+\t\texpect(outcome.metrics).toMatchObject({\n+\t\t\tholidayWeekValue: 3,\n+\t\t\tunplacedAtRisk: 2,\n+\t\t\tsupportingPlacements: 2,\n+\t\t});\n+\t});\n+\n+\tit('records the calendar credit and classification change in the original calendar-rule phase', () => {\n+\t\tlet artifacts: PlanningArtifacts | undefined;\n+\t\tcalculatePlanningInternal(\n+\t\t\t{ ...weekend, rules: [gain, economy, requested] },\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\tconst changes = artifacts?.trace?.phases\n+\t\t\t.find(({ name }) => name === 'preference:requested')\n+\t\t\t?.decisions.flatMap(({ deltas }) => deltas);\n+\t\texpect(changes).toContainEqual(\n+\t\t\texpect.objectContaining({\n+\t\t\t\tkind: 'placement-updated',\n+\t\t\t\tpreviousPlacement: expect.objectContaining({ supporting: true }),\n+\t\t\t\tplacement: expect.objectContaining({\n+\t\t\t\t\truleIds: ['gain', 'requested'],\n+\t\t\t\t\tsupporting: false,\n+\t\t\t\t}),\n+\t\t\t}),\n+\t\t);\n+\t});\n+\n+\tit('keeps earned support chronological and preserves the captured economy rule in explanations and counterfactuals', async () => {\n+\t\tvi.stubGlobal('window', undefined);\n+\t\ttry {\n+\t\t\tconst capturedEconomy = structuredClone(economy);\n+\t\t\tconst request: PlanningRequest = {\n+\t\t\t\thorizon: { start: '2024-04-29', end: '2024-05-08' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2025-01-01' }],\n+\t\t\t\trules: [\n+\t\t\t\t\tgain,\n+\t\t\t\t\tcapturedEconomy,\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\trewardType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t};\n+\t\t\tconst calculation = createPlanningCalculation(request);\n+\t\t\tcapturedEconomy.configuration.conditions = [];\n+\t\t\tcapturedEconomy.name = 'Changed later';\n+\t\t\tconst outcome = await calculation.outcome;\n+\t\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a plan');\n+\t\t\texpect(outcome.placements).toEqual([\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tdate: '2024-05-02',\n+\t\t\t\t\truleIds: ['producer'],\n+\t\t\t\t\tsupporting: false,\n+\t\t\t\t}),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tdate: '2024-05-06',\n+\t\t\t\t\tbalanceId: 'earned:producer:2024-05-01',\n+\t\t\t\t\tsupporting: true,\n+\t\t\t\t}),\n+\t\t\t]);\n+\t\t\texpect(outcome.metrics).toMatchObject({\n+\t\t\t\tnonWorkingDayGain: 3,\n+\t\t\t\tsupportingPlacements: 1,\n+\t\t\t});\n+\t\t\texpect(calculation.snapshot.rules[1]).toMatchObject({\n+\t\t\t\tname: 'Économiser les jours d’appoint',\n+\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t});\n+\t\t\tconst explanation = await calculation.explanation;\n+\t\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\t\tconst supporting = explanation.placements.find(({ supporting }) => supporting)!;\n+\t\t\texpect(supporting.firstDecisiveObjective).toBe('optimization:gain');\n+\t\t\texpect(supporting.objectiveVector.objectives.map(({ id }) => id)).toEqual([\n+\t\t\t\t'obligation-validity',\n+\t\t\t\t'optimization:gain',\n+\t\t\t\t'optimization:economy',\n+\t\t\t\t'balance-expiry',\n+\t\t\t\t'placement-date',\n+\t\t\t]);\n+\t\t\texpect(supporting.contributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({ kind: 'supporting' }),\n+\t\t\t);\n+\t\t\tconst trace = await calculation.trace;\n+\t\t\texpect(trace?.phases.map(({ name }) => name)).toEqual([\n+\t\t\t\t'validation',\n+\t\t\t\t'obligations',\n+\t\t\t\t'optimization:gain',\n+\t\t\t\t'optimization:economy',\n+\t\t\t\t'expiry',\n+\t\t\t\t'dates',\n+\t\t\t]);\n+\t\t\tconst analysis = await calculation.analyzeCounterfactual(outcome.placements[1]);\n+\t\t\tif (analysis.kind !== 'Counterfactual') throw new Error('Expected a counterfactual');\n+\t\t\texpect(analysis.results.find(({ date }) => date === '2024-05-03')).toMatchObject({\n+\t\t\t\tstatus: 'ineligible',\n+\t\t\t\treason: { code: 'unavailable' },\n+\t\t\t});\n+\t\t\texpect(\n+\t\t\t\tanalysis.results.find(({ date }) => date === '2024-05-06')?.comparison?.after\n+\t\t\t\t\t.objectives,\n+\t\t\t).toContainEqual(expect.objectContaining({ id: 'optimization:economy', value: 1 }));\n+\t\t\texpect(\n+\t\t\t\tanalysis.results.find(({ date }) => date === '2024-05-07')?.comparison?.after\n+\t\t\t\t\t.objectives,\n+\t\t\t).toContainEqual(expect.objectContaining({ id: 'optimization:economy', value: 1 }));\n+\t\t\texpect(outcome.placements[1]).toMatchObject({ date: '2024-05-06', supporting: true });\n+\t\t} finally {\n+\t\t\tvi.unstubAllGlobals();\n+\t\t}\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/services/leave-planner-supporting-placements.spec.ts", "project_id": 35, "relative_order": 24, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,465 @@\n+import { vi } from 'vitest';\n+import {\n+\tcalculatePlanningInternal,\n+\ttype OptimizationPlanningRule,\n+\ttype PlanOutcome,\n+\ttype PlanningRequest,\n+} from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+import { createPlanningCalculation } from './leave-planner.service';\n+\n+const deficit: OptimizationPlanningRule = {\n+\tid: 'deficit',\n+\tname: 'Internal work-sequence deficit',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+};\n+const longest: OptimizationPlanningRule = {\n+\tid: 'longest',\n+\tname: 'Longest work sequence',\n+\ttype: 'optimization',\n+\tconfiguration: OPTIMIZATION_PRESETS.longestWorkSequence,\n+};\n+const gap: PlanningRequest = {\n+\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-02-01' }],\n+\tdeclaredDays: ['2024-01-08', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\trules: [deficit],\n+};\n+\n+function plan(request: PlanningRequest): PlanOutcome {\n+\tconst outcome = calculatePlanningInternal(request);\n+\tif (outcome.kind !== 'Plan') throw new Error(`Expected a plan, got ${outcome.kind}`);\n+\treturn outcome;\n+}\n+\n+describe('composed work-sequence preferences', () => {\n+\tbeforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n+\tafterEach(() => vi.useRealTimers());\n+\n+\tit('fills a complete internal sequence despite the worse deficit of partial additions', () => {\n+\t\tconst outcome = plan(gap);\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual([\n+\t\t\t'2024-01-09',\n+\t\t\t'2024-01-10',\n+\t\t\t'2024-01-11',\n+\t\t]);\n+\t\texpect(outcome.placements.every(({ supporting }) => supporting)).toBe(true);\n+\t\texpect(outcome.declaredDays).toEqual(gap.declaredDays);\n+\t\texpect(outcome.metrics.shortSequenceDeficit).toBe(0);\n+\t\texpect(outcome.remainingBalances).toEqual([]);\n+\t});\n+\n+\tit('splits tied longest sequences together when neither single addition improves the maximum', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...gap,\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: [{ date: '2024-01-10', type: 'other' }],\n+\t\t\trules: [longest],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual(['2024-01-08', '2024-01-11']);\n+\t\texpect(outcome.metrics.longestWorkSequence).toBe(1);\n+\t});\n+\n+\tit('leaves a three-day internal sequence intact at threshold three instead of filling it at five', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...gap,\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\t...deficit,\n+\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t\tthresholdDays: 3,\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements).toEqual([]);\n+\t\texpect(outcome.remainingBalances[0].quantity).toBe(3);\n+\t\texpect(outcome.metrics.shortSequenceDeficit).toBe(2);\n+\t});\n+\n+\tit('counts selected internal sequences even when their measured deficit is zero', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...gap,\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\t...deficit,\n+\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t\tthresholdDays: 3,\n+\t\t\t\t\t\taggregation: 'count',\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual([\n+\t\t\t'2024-01-09',\n+\t\t\t'2024-01-10',\n+\t\t\t'2024-01-11',\n+\t\t]);\n+\t});\n+\n+\tit('evaluates two parameterized configurations separately and follows their order', () => {\n+\t\tconst maximizeThree: OptimizationPlanningRule = {\n+\t\t\t...deficit,\n+\t\t\tid: 'three',\n+\t\t\tconfiguration: {\n+\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\tthresholdDays: 3,\n+\t\t\t\tdirection: 'maximize',\n+\t\t\t},\n+\t\t};\n+\t\tconst fiveFirst = plan({ ...gap, rules: [deficit, maximizeThree] });\n+\t\tconst threeFirst = plan({ ...gap, rules: [maximizeThree, deficit] });\n+\t\texpect(fiveFirst.placements.map(({ date }) => date)).toEqual([\n+\t\t\t'2024-01-09',\n+\t\t\t'2024-01-10',\n+\t\t\t'2024-01-11',\n+\t\t]);\n+\t\texpect(threeFirst.placements.map(({ date }) => date)).toEqual(['2024-01-10']);\n+\t\texpect(threeFirst.metrics.shortSequenceDeficit).toBe(8);\n+\t});\n+\n+\tit('obeys the order between the longest-sequence preference and a personal window', () => {\n+\t\tconst personal = {\n+\t\t\tid: 'personal',\n+\t\t\ttype: 'time_window' as const,\n+\t\t\tstartDate: '2024-01-08',\n+\t\t\tendDate: '2024-01-08',\n+\t\t\tplaceDays: 1,\n+\t\t\tplaceType: 'cp',\n+\t\t};\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-20' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2024-02-01' }],\n+\t\t\trules: [],\n+\t\t};\n+\t\tconst longestFirst = plan({ ...request, rules: [longest, personal] });\n+\t\tconst personalFirst = plan({ ...request, rules: [personal, longest] });\n+\t\texpect(longestFirst.placements.map(({ date }) => date)).toEqual(['2024-01-12']);\n+\t\texpect(longestFirst.metrics.longestWorkSequence).toBe(5);\n+\t\texpect(personalFirst.placements.map(({ date }) => date)).toEqual(['2024-01-08']);\n+\t\texpect(personalFirst.metrics.longestWorkSequence).toBe(9);\n+\t});\n+\n+\tit('keeps obligations and earlier preferences when a complete gap would consume their balance', () => {\n+\t\tconst personal = {\n+\t\t\tid: 'personal',\n+\t\t\ttype: 'time_window' as const,\n+\t\t\tstartDate: '2024-01-15',\n+\t\t\tendDate: '2024-01-15',\n+\t\t\tplaceDays: 1,\n+\t\t\tplaceType: 'cp',\n+\t\t};\n+\t\tconst request = { ...gap, horizon: { start: '2024-01-08', end: '2024-01-16' } };\n+\t\texpect(\n+\t\t\tplan({ ...request, rules: [deficit, personal] }).placements.map(({ date }) => date),\n+\t\t).toEqual(['2024-01-09', '2024-01-10', '2024-01-11']);\n+\t\tfor (const force of ['preference', 'obligation'] as const) {\n+\t\t\tconst outcome = plan({ ...request, rules: [{ ...personal, force }, deficit] });\n+\t\t\texpect(outcome.placements.map(({ date }) => date)).toEqual(['2024-01-15']);\n+\t\t\texpect(outcome.metrics.shortSequenceDeficit).toBe(2);\n+\t\t}\n+\t});\n+\n+\tit('uses only eligible balance dates when completing the entire gap', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...gap,\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'early', type: 'rtt', quantity: 1, expiryDate: '2024-01-09' },\n+\t\t\t\t{\n+\t\t\t\t\tid: 'late',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 2,\n+\t\t\t\t\tavailableFrom: '2024-01-10',\n+\t\t\t\t\texpiryDate: '2024-02-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date, balanceId }) => ({ date, balanceId }))).toEqual([\n+\t\t\t{ date: '2024-01-09', balanceId: 'early' },\n+\t\t\t{ date: '2024-01-10', balanceId: 'late' },\n+\t\t\t{ date: '2024-01-11', balanceId: 'late' },\n+\t\t]);\n+\t\texpect(outcome.placements.map(({ supporting }) => supporting)).toEqual([false, true, true]);\n+\t\tconst unavailable = plan({\n+\t\t\t...gap,\n+\t\t\tbalances: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'late',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 3,\n+\t\t\t\t\tavailableFrom: '2024-01-10',\n+\t\t\t\t\texpiryDate: '2024-02-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(unavailable.placements).toEqual([]);\n+\t});\n+\n+\tit('adds no neutral placement when the budget cannot split all tied maxima', () => {\n+\t\tconst outcome = plan({\n+\t\t\t...gap,\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: [{ date: '2024-01-10', type: 'other' }],\n+\t\t\trules: [longest],\n+\t\t});\n+\t\texpect(outcome.placements).toEqual([]);\n+\t\texpect(outcome.metrics.longestWorkSequence).toBe(2);\n+\t});\n+\n+\tit('splits tied sequences at eligible dates when their centers are unavailable', () => {\n+\t\tconst outcome = plan({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-19' },\n+\t\t\tdeclaredDays: [{ date: '2024-01-12', type: 'other' }],\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'early', type: 'cp', quantity: 1, expiryDate: '2024-01-08' },\n+\t\t\t\t{\n+\t\t\t\t\tid: 'late',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2024-01-18',\n+\t\t\t\t\texpiryDate: '2024-02-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t\trules: [longest],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual(['2024-01-08', '2024-01-18']);\n+\t\texpect(outcome.metrics.longestWorkSequence).toBe(3);\n+\t});\n+\n+\tit('coordinates scarce balances when individually eligible centers cannot be funded together', () => {\n+\t\tconst outcome = plan({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-19' },\n+\t\t\tdeclaredDays: [{ date: '2024-01-12', type: 'other' }],\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'early', type: 'cp', quantity: 1, expiryDate: '2024-01-08' },\n+\t\t\t\t{ id: 'flexible', type: 'cp', quantity: 1, expiryDate: '2024-02-01' },\n+\t\t\t],\n+\t\t\trules: [longest],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual(['2024-01-08', '2024-01-15']);\n+\t\texpect(outcome.metrics.longestWorkSequence).toBe(3);\n+\t});\n+\n+\tit('eliminates tied maximum deficits as one complete gap bundle', () => {\n+\t\tconst outcome = plan({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-17' },\n+\t\t\tdeclaredDays: ['2024-01-08', '2024-01-11', '2024-01-16'].map((date) => ({\n+\t\t\t\tdate,\n+\t\t\t\ttype: 'other',\n+\t\t\t})),\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 4, expiryDate: '2024-02-01' }],\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\t...deficit,\n+\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t\taggregation: 'maximum',\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual([\n+\t\t\t'2024-01-09',\n+\t\t\t'2024-01-10',\n+\t\t\t'2024-01-12',\n+\t\t\t'2024-01-15',\n+\t\t]);\n+\t\texpect(outcome.metrics.shortSequenceDeficit).toBe(0);\n+\t});\n+\n+\tit('includes both horizon edges in the maximum while excluding them from the deficit', () => {\n+\t\tconst outcome = plan({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-25' },\n+\t\t\tbalances: [],\n+\t\t\tdeclaredDays: ['2024-01-11', '2024-01-15', '2024-01-22'].map((date) => ({\n+\t\t\t\tdate,\n+\t\t\t\ttype: 'other',\n+\t\t\t})),\n+\t\t\trules: [longest, deficit],\n+\t\t});\n+\t\texpect(outcome.metrics).toMatchObject({ longestWorkSequence: 4, shortSequenceDeficit: 5 });\n+\t});\n+\n+\tit.each([\n+\t\t{ horizon: { start: '2024-05-06', end: '2024-05-15' }, dates: [], longest: 5 },\n+\t\t{\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-11' },\n+\t\t\tdates: ['2024-01-08', '2024-01-09', '2024-01-10'],\n+\t\t\tlongest: 0,\n+\t\t},\n+\t\t{ horizon: { start: '2024-01-06', end: '2024-01-08' }, dates: [], longest: 0 },\n+\t\t{\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tdates: ['2024-01-09', '2024-01-10'],\n+\t\t\tlongest: 2,\n+\t\t},\n+\t])(\n+\t\t'keeps holiday/weekend continuity and zero for empty sequences: $horizon.start',\n+\t\t({ horizon, dates, longest: expected }) => {\n+\t\t\tconst outcome = plan({\n+\t\t\t\thorizon,\n+\t\t\t\tbalances: [],\n+\t\t\t\tdeclaredDays: dates.map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [longest, deficit],\n+\t\t\t});\n+\t\t\texpect(outcome.metrics.longestWorkSequence).toBe(expected);\n+\t\t\texpect(outcome.metrics.shortSequenceDeficit).toBe(0);\n+\t\t},\n+\t);\n+\n+\tit('disabling work-sequence rules removes their influence even with deferred balances', () => {\n+\t\tconst absent = plan({ ...gap, rules: [] });\n+\t\tconst disabled = plan({\n+\t\t\t...gap,\n+\t\t\trules: [\n+\t\t\t\t{ ...deficit, enabled: false },\n+\t\t\t\t{ ...longest, enabled: false },\n+\t\t\t],\n+\t\t});\n+\t\texpect(disabled).toEqual(absent);\n+\t\tconst personal = {\n+\t\t\tid: 'personal',\n+\t\t\ttype: 'time_window' as const,\n+\t\t\tstartDate: '2024-01-09',\n+\t\t\tendDate: '2024-01-09',\n+\t\t\tplaceDays: 1,\n+\t\t\tplaceType: 'cp',\n+\t\t};\n+\t\tconst requested = plan({ ...gap, rules: [{ ...deficit, enabled: false }, personal] });\n+\t\texpect(requested.placements.map(({ date }) => date)).toEqual(['2024-01-09']);\n+\t\texpect(requested.metrics.shortSequenceDeficit).toBe(3);\n+\t});\n+\n+\tit('finishes a rejected tied-sequence bundle without retrying equivalent balance allocations', () => {\n+\t\tconst outcome = plan({\n+\t\t\tdeadlineMs: 1500,\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-02-10' },\n+\t\t\tdeclaredDays: [\n+\t\t\t\t'2024-01-08',\n+\t\t\t\t'2024-01-10',\n+\t\t\t\t'2024-01-12',\n+\t\t\t\t'2024-01-16',\n+\t\t\t\t'2024-01-18',\n+\t\t\t\t'2024-01-22',\n+\t\t\t\t'2024-01-24',\n+\t\t\t\t'2024-01-26',\n+\t\t\t\t'2024-01-30',\n+\t\t\t\t'2024-02-01',\n+\t\t\t\t'2024-02-05',\n+\t\t\t\t'2024-02-07',\n+\t\t\t\t'2024-02-09',\n+\t\t\t].map((date) => ({ date, type: 'other' })),\n+\t\t\tbalances: ['cp', 'rtt', 'other'].map((type) => ({\n+\t\t\t\tid: type,\n+\t\t\t\ttype,\n+\t\t\t\tquantity: 12,\n+\t\t\t\texpiryDate: '2024-03-01',\n+\t\t\t})),\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'support',\n+\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t\t},\n+\t\t\t\tlongest,\n+\t\t\t\t{\n+\t\t\t\t\tid: 'typed',\n+\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\tstartDate: '2024-01-09',\n+\t\t\t\t\tendDate: '2024-01-09',\n+\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual(['2024-01-09']);\n+\t\texpect(outcome.metrics.longestWorkSequence).toBe(1);\n+\t\texpect(outcome.metrics.supportingPlacements).toBe(0);\n+\t});\n+\n+\tit.each([0, -1, 1.5, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER + 1])(\n+\t\t'rejects an invalid preference threshold %s at the planning boundary',\n+\t\t(thresholdDays) => {\n+\t\t\tconst outcome = calculatePlanningInternal({\n+\t\t\t\t...gap,\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\t...deficit,\n+\t\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t\t\tthresholdDays,\n+\t\t\t\t\t\t},\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t});\n+\t\t\texpect(outcome).toMatchObject({\n+\t\t\t\tkind: 'InvalidInput',\n+\t\t\t\treasons: [\n+\t\t\t\t\texpect.objectContaining({\n+\t\t\t\t\t\tcode: 'invalid-optimization-configuration',\n+\t\t\t\t\t\truleIds: ['deficit'],\n+\t\t\t\t\t}),\n+\t\t\t\t],\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit('captures distinct threshold values in explanations, atomic trace and counterfactual comparisons', async () => {\n+\t\tvi.stubGlobal('window', undefined);\n+\t\ttry {\n+\t\t\tconst five = structuredClone(deficit);\n+\t\t\tconst three: OptimizationPlanningRule = {\n+\t\t\t\t...deficit,\n+\t\t\t\tid: 'three',\n+\t\t\t\tconfiguration: { ...OPTIMIZATION_PRESETS.shortSequenceDeficit, thresholdDays: 3 },\n+\t\t\t};\n+\t\t\tconst calculation = createPlanningCalculation({ ...gap, rules: [three, five] });\n+\t\t\tif (five.configuration.measure !== 'work-sequence-deficit')\n+\t\t\t\tthrow new Error('Expected deficit');\n+\t\t\tfive.configuration.thresholdDays = 1;\n+\t\t\tconst outcome = await calculation.outcome;\n+\t\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a plan');\n+\t\t\texpect(outcome.placements).toHaveLength(3);\n+\t\t\texpect(\n+\t\t\t\tcalculation.snapshot.rules.map((rule) =>\n+\t\t\t\t\t'configuration' in rule ? rule.configuration : undefined,\n+\t\t\t\t),\n+\t\t\t).toMatchObject([{ thresholdDays: 3 }, { thresholdDays: 5 }]);\n+\t\t\tconst explanation = await calculation.explanation;\n+\t\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\t\texpect(\n+\t\t\t\texplanation.placements[0].comparison.before.objectives\n+\t\t\t\t\t.filter(({ id }) => id.startsWith('optimization:'))\n+\t\t\t\t\t.map(({ value }) => value),\n+\t\t\t).toEqual([2, 4]);\n+\t\t\tconst trace = await calculation.trace;\n+\t\t\tconst chosen = trace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t.find(\n+\t\t\t\t\t(candidate) => candidate.status === 'chosen' && candidate.dates?.length === 3,\n+\t\t\t\t);\n+\t\t\texpect(\n+\t\t\t\tchosen?.comparison?.before.objectives\n+\t\t\t\t\t.filter(({ id }) => id.startsWith('optimization:'))\n+\t\t\t\t\t.map(({ value }) => value),\n+\t\t\t).toEqual([0, 2]);\n+\t\t\texpect(chosen?.comparison?.firstDecisiveObjective).toBe('optimization:deficit');\n+\t\t\tconst counterfactual = await calculation.analyzeCounterfactual(outcome.placements[0]);\n+\t\t\tif (counterfactual.kind !== 'Counterfactual')\n+\t\t\t\tthrow new Error('Expected a counterfactual');\n+\t\t\texpect(\n+\t\t\t\tcounterfactual.baseline.objectives\n+\t\t\t\t\t.filter(({ id }) => id.startsWith('optimization:'))\n+\t\t\t\t\t.map(({ id, value }) => ({ id, value })),\n+\t\t\t).toEqual([\n+\t\t\t\t{ id: 'optimization:three', value: 2 },\n+\t\t\t\t{ id: 'optimization:deficit', value: 4 },\n+\t\t\t]);\n+\t\t} finally {\n+\t\t\tvi.unstubAllGlobals();\n+\t\t}\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/services/leave-planner-work-sequences.spec.ts", "project_id": 35, "relative_order": 25, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -5,6 +5,16 @@ import {\n \tisWorkingPlanningDate,\n } from './declared-non-working-days';\n import { addPlanningYears, isPlanningDate, planningDateInParis } from './planning-date';\n+import {\n+\tcompareObjectiveLists,\n+\tcompareObjectiveValues,\n+\tevaluateOptimization,\n+\tfirstDifferentObjective,\n+\tOPTIMIZATION_PRESETS,\n+\tvalidateOptimizationConfiguration,\n+\ttype OptimizationConfiguration,\n+\ttype OptimizationObservations,\n+} from './planning-objectives';\n export type { DeclaredNonWorkingDay } from './declared-non-working-days';\n \n /** Date-only values are serialized as YYYY-MM-DD at the planning boundary. */\n@@ -55,7 +65,16 @@ export interface IfThenPlanningRule {\n \trewardType?: LeaveType | string;\n }\n \n-export type PlanningRule = TimeWindowPlanningRule | IfThenPlanningRule;\n+export interface OptimizationPlanningRule {\n+\tid: string;\n+\tname?: string;\n+\ttype: 'optimization';\n+\tenabled?: boolean;\n+\tforce?: 'preference';\n+\tconfiguration: OptimizationConfiguration;\n+}\n+\n+export type PlanningRule = TimeWindowPlanningRule | IfThenPlanningRule | OptimizationPlanningRule;\n \n export interface PlanningRequest {\n \thorizon: PlanningHorizon;\n@@ -154,6 +173,7 @@ export type PlanningObjectiveId =\n \t| 'obligation-validity'\n \t| 'unplaced-at-risk'\n \t| `preference:${string}`\n+\t| `optimization:${string}`\n \t| 'holiday-week-value'\n \t| 'non-working-day-gain'\n \t| 'longest-work-sequence'\n@@ -509,12 +529,15 @@ interface NormalizedBalance {\n \tsourceRuleId?: string;\n }\n \n-interface NormalizedRule {\n+interface NormalizedBaseRule {\n \tid: string;\n \tname: string;\n-\ttype: 'time_window' | 'if_then';\n \tenabled: boolean;\n \tforce: RuleForce;\n+}\n+\n+interface NormalizedCalendarRule extends NormalizedBaseRule {\n+\ttype: 'time_window' | 'if_then';\n \tplaceDays: number;\n \tplaceType: LeaveSelector;\n \tstartDate?: string;\n@@ -525,6 +548,14 @@ interface NormalizedRule {\n \trewardType?: LeaveType;\n }\n \n+interface NormalizedOptimizationRule extends NormalizedBaseRule {\n+\ttype: 'optimization';\n+\tforce: 'preference';\n+\tconfiguration: OptimizationConfiguration;\n+}\n+\n+type NormalizedRule = NormalizedCalendarRule | NormalizedOptimizationRule;\n+\n interface InternalBalance extends NormalizedBalance {\n \tremaining: number;\n }\n@@ -593,10 +624,11 @@ interface RuntimeRecord {\n \tplacement?: unknown;\n \trewardDays?: unknown;\n \trewardType?: unknown;\n+\tconfiguration?: unknown;\n }\n \n interface Requirement {\n-\trule: NormalizedRule;\n+\trule: NormalizedCalendarRule;\n \trequiredPlacements: number;\n \tanchor: string;\n \tindex: number;\n@@ -607,8 +639,26 @@ interface Requirement {\n }\n \n const obligationRequirementCache = new WeakMap();\n+const occurrenceCache = new WeakMap>();\n+const calendarPatternCache = new WeakMap>();\n const preferencePatternCache = new WeakMap>();\n const declaredWindowCache = new WeakMap>();\n+type CalendarOptimizationObservations = Pick<\n+\tOptimizationObservations,\n+\t'publicHolidayWeeks' | 'timeOffPeriods' | 'workSequences'\n+>;\n+const calendarObservationCache = new WeakMap<\n+\tSearchContext,\n+\tMap\n+>();\n+interface CalendarPeriod {\n+\tstart: string;\n+\tend: string;\n+\tduration: number;\n+\tnonWorkingDates: readonly string[];\n+\tdeclaredDates: readonly string[];\n+}\n+const calendarPeriodCache = new WeakMap>();\n \n type MutableTraceCandidate = PlanningTraceCandidate & { candidates?: never };\n type MutableTraceDecision = {\n@@ -638,15 +688,37 @@ class TraceRecorder {\n \tprivate readonly nonWorkingDates: readonly Readonly<{ date: string; reason: PlanningReason }>[];\n \tprivate phase: MutableTracePhase | undefined;\n \tprivate sequence = 0;\n-\tprivate readonly evaluationLocations = new WeakMap<\n-\t\tMutableTraceCandidate,\n-\t\t{ phase: MutableTracePhase; decision: MutableTraceDecision; index: number }\n-\t>();\n+\n \tprivate pendingOperations: PlanningTraceOperation[] = [];\n \tprivate readonly pendingCandidateOperations = new Map<\n \t\tPlanningTraceCandidate,\n \t\tExtract\n \t>();\n+\t// Keep repeated scalar evidence shared while candidate identities remain independent.\n+\tprivate readonly objectiveValues = new Map();\n+\tprivate readonly objectiveVectors = new WeakMap<\n+\t\tPlanningObjectiveVector,\n+\t\tPlanningObjectiveVector\n+\t>();\n+\tprivate readonly comparisonDeltas = new Map();\n+\tprivate readonly repeatedVectors = new Map();\n+\tprivate repeatedVectorCount = 0;\n+\tprivate readonly tieValues = new Map();\n+\tprivate readonly placements = new Map();\n+\tprivate readonly dates = new Map();\n+\tprivate readonly identifiers = new Map();\n+\tprivate readonly comparisons = new WeakMap<\n+\t\tPlanningObjectiveVector,\n+\t\tWeakMap\n+\t>();\n+\tprivate readonly technicalValues = new Map<\n+\t\tstring,\n+\t\tNonNullable\n+\t>();\n+\tprivate readonly technicalEntries = new Map<\n+\t\tstring,\n+\t\tNonNullable[number]\n+\t>();\n \tprivate initialStateSent = false;\n \tprivate previousPlacements = new Map();\n \tprivate previousEarned = new Set();\n@@ -675,6 +747,206 @@ class TraceRecorder {\n \t\t);\n \t}\n \n+\tprivate capturePlacement(placement: LeavePlacement | undefined): LeavePlacement | undefined {\n+\t\tif (!placement || Object.isFrozen(placement)) return placement;\n+\t\tconst key = JSON.stringify(placement);\n+\t\tconst shared = this.placements.get(key);\n+\t\tif (shared) return shared;\n+\t\tconst ruleIds = [...placement.ruleIds];\n+\t\tObject.freeze(ruleIds);\n+\t\tconst snapshot = Object.freeze({ ...placement, ruleIds });\n+\t\tif (this.placements.size < 8192) this.placements.set(key, snapshot);\n+\t\treturn snapshot;\n+\t}\n+\n+\tprivate captureDates(dates: readonly string[] | undefined): readonly string[] | undefined {\n+\t\tif (!dates || Object.isFrozen(dates)) return dates;\n+\t\tconst key = JSON.stringify(dates);\n+\t\tconst shared = this.dates.get(key);\n+\t\tif (shared) return shared;\n+\t\tconst snapshot = Object.freeze([...dates]);\n+\t\tif (this.dates.size < 16384) this.dates.set(key, snapshot);\n+\t\treturn snapshot;\n+\t}\n+\n+\tprivate captureIdentifier(identifier: string): string {\n+\t\tconst shared = this.identifiers.get(identifier);\n+\t\tif (shared !== undefined) return shared;\n+\t\tif (this.identifiers.size < 4096) this.identifiers.set(identifier, identifier);\n+\t\treturn identifier;\n+\t}\n+\n+\tprivate captureTieValue(value: number | string): number | string {\n+\t\tif (typeof value !== 'string') return value;\n+\t\tconst shared = this.tieValues.get(value);\n+\t\tif (shared !== undefined) {\n+\t\t\tthis.tieValues.delete(value);\n+\t\t\tthis.tieValues.set(shared, shared);\n+\t\t\treturn shared;\n+\t\t}\n+\t\t// Bound the index; eviction changes only sharing, never the recorded scalar value.\n+\t\tif (this.tieValues.size >= 8192) this.tieValues.delete(this.tieValues.keys().next().value!);\n+\t\tthis.tieValues.set(value, value);\n+\t\treturn value;\n+\t}\n+\n+\tprivate captureVector(vector: PlanningObjectiveVector): PlanningObjectiveVector {\n+\t\tconst captured = this.objectiveVectors.get(vector);\n+\t\tif (captured) return captured;\n+\t\t// Use a retained tie value as the index rather than duplicating complete vectors as JSON keys.\n+\t\tconst dateValue = vector.objectives.find(({ id }) => id === 'placement-date')?.value;\n+\t\tconst key = typeof dateValue === 'string' ? dateValue : undefined;\n+\t\tconst bucket = key === undefined ? undefined : this.repeatedVectors.get(key);\n+\t\tconst shared = bucket?.find(\n+\t\t\t(candidate) =>\n+\t\t\t\tcandidate.objectives.length === vector.objectives.length &&\n+\t\t\t\tcandidate.objectives.every((objective, index) => {\n+\t\t\t\t\tconst other = vector.objectives[index];\n+\t\t\t\t\treturn (\n+\t\t\t\t\t\tobjective.id === other.id &&\n+\t\t\t\t\t\tobjective.direction === other.direction &&\n+\t\t\t\t\t\tobjective.label === other.label &&\n+\t\t\t\t\t\tObject.hasOwn(objective, 'label') === Object.hasOwn(other, 'label') &&\n+\t\t\t\t\t\tObject.is(objective.value, other.value)\n+\t\t\t\t\t);\n+\t\t\t\t}),\n+\t\t);\n+\t\tif (shared) {\n+\t\t\tconst recordedKey = shared.objectives.find(({ id }) => id === 'placement-date')?.value;\n+\t\t\tif (typeof recordedKey === 'string') {\n+\t\t\t\tthis.repeatedVectors.delete(recordedKey);\n+\t\t\t\tthis.repeatedVectors.set(recordedKey, bucket!);\n+\t\t\t}\n+\t\t\tthis.objectiveVectors.set(vector, shared);\n+\t\t\treturn shared;\n+\t\t}\n+\t\tconst objectives = vector.objectives.map((objective) => {\n+\t\t\tconst shareable =\n+\t\t\t\t(objective.id === 'balance-expiry' && typeof objective.value === 'string') ||\n+\t\t\t\t(typeof objective.value === 'number' &&\n+\t\t\t\t\tNumber.isFinite(objective.value) &&\n+\t\t\t\t\t!Object.is(objective.value, -0));\n+\t\t\tif (!shareable)\n+\t\t\t\treturn Object.freeze({\n+\t\t\t\t\t...objective,\n+\t\t\t\t\tvalue: this.captureTieValue(objective.value),\n+\t\t\t\t});\n+\t\t\tconst key = JSON.stringify(objective);\n+\t\t\tconst shared = this.objectiveValues.get(key);\n+\t\t\tif (shared) return shared;\n+\t\t\tconst value = Object.freeze({\n+\t\t\t\t...objective,\n+\t\t\t\tvalue: this.captureTieValue(objective.value),\n+\t\t\t});\n+\t\t\tif (this.objectiveValues.size < 4096) this.objectiveValues.set(key, value);\n+\t\t\treturn value;\n+\t\t});\n+\t\tconst result = Object.freeze({ objectives: Object.freeze(objectives) });\n+\t\tthis.objectiveVectors.set(vector, result);\n+\t\tconst recordedKey = result.objectives.find(({ id }) => id === 'placement-date')?.value;\n+\t\tif (typeof recordedKey === 'string') {\n+\t\t\tif (this.repeatedVectorCount >= 65536) {\n+\t\t\t\tconst oldest = this.repeatedVectors.keys().next().value!;\n+\t\t\t\tthis.repeatedVectorCount -= this.repeatedVectors.get(oldest)!.length;\n+\t\t\t\tthis.repeatedVectors.delete(oldest);\n+\t\t\t}\n+\t\t\tconst retained = this.repeatedVectors.get(recordedKey) ?? [];\n+\t\t\tretained.push(result);\n+\t\t\tthis.repeatedVectors.delete(recordedKey);\n+\t\t\tthis.repeatedVectors.set(recordedKey, retained);\n+\t\t\tthis.repeatedVectorCount++;\n+\t\t}\n+\t\treturn result;\n+\t}\n+\n+\tprivate captureComparison(\n+\t\tcomparison: PlanningObjectiveComparison,\n+\t): PlanningObjectiveComparison {\n+\t\tconst before = this.captureVector(comparison.before);\n+\t\tconst after = this.captureVector(comparison.after);\n+\t\tlet alternatives = this.comparisons.get(before);\n+\t\tconst shared = alternatives?.get(after);\n+\t\tif (shared) return shared;\n+\t\tif (!alternatives) {\n+\t\t\talternatives = new WeakMap();\n+\t\t\tthis.comparisons.set(before, alternatives);\n+\t\t}\n+\t\t// Every recorded comparison comes from objectiveComparison of these complete vectors.\n+\t\tconst result = Object.freeze({\n+\t\t\t...comparison,\n+\t\t\tbefore,\n+\t\t\tafter,\n+\t\t\tfirstDecisiveObjective: after.objectives.find(\n+\t\t\t\t({ id }) => id === comparison.firstDecisiveObjective,\n+\t\t\t)?.id,\n+\t\t\tdelta: this.captureDeltas(comparison.delta),\n+\t\t});\n+\t\talternatives.set(after, result);\n+\t\treturn result;\n+\t}\n+\n+\tprivate captureDeltas(\n+\t\tdeltas: readonly PlanningObjectiveDelta[],\n+\t): readonly PlanningObjectiveDelta[] {\n+\t\tconst shareable = deltas.every(\n+\t\t\t({ value }) => value === null || (Number.isFinite(value) && !Object.is(value, -0)),\n+\t\t);\n+\t\tconst key = shareable ? JSON.stringify(deltas) : undefined;\n+\t\tconst shared = key === undefined ? undefined : this.comparisonDeltas.get(key);\n+\t\tif (shared) return shared;\n+\t\tconst result = Object.freeze(deltas.map((delta) => Object.freeze({ ...delta })));\n+\t\tif (key !== undefined && this.comparisonDeltas.size < 4096)\n+\t\t\tthis.comparisonDeltas.set(key, result);\n+\t\treturn result;\n+\t}\n+\n+\tprivate captureTechnicalValues(\n+\t\tvalues: PlanningTraceCandidate['technicalComparison'],\n+\t): PlanningTraceCandidate['technicalComparison'] {\n+\t\tif (!values || Object.isFrozen(values)) return values;\n+\t\tconst shareable = values.every(\n+\t\t\t({ before, after }) =>\n+\t\t\t\ttypeof before === 'number' &&\n+\t\t\t\ttypeof after === 'number' &&\n+\t\t\t\tNumber.isFinite(before) &&\n+\t\t\t\tNumber.isFinite(after) &&\n+\t\t\t\t!Object.is(before, -0) &&\n+\t\t\t\t!Object.is(after, -0),\n+\t\t);\n+\t\tconst key = shareable ? JSON.stringify(values) : undefined;\n+\t\tconst shared = key === undefined ? undefined : this.technicalValues.get(key);\n+\t\tif (shared) return shared;\n+\t\tconst result = Object.freeze(\n+\t\t\tvalues.map((value) => {\n+\t\t\t\tconst shareable =\n+\t\t\t\t\t(value.name === 'balance-expiry' &&\n+\t\t\t\t\t\ttypeof value.before === 'string' &&\n+\t\t\t\t\t\ttypeof value.after === 'string') ||\n+\t\t\t\t\t(typeof value.before === 'number' &&\n+\t\t\t\t\t\ttypeof value.after === 'number' &&\n+\t\t\t\t\t\tNumber.isFinite(value.before) &&\n+\t\t\t\t\t\tNumber.isFinite(value.after) &&\n+\t\t\t\t\t\t!Object.is(value.before, -0) &&\n+\t\t\t\t\t\t!Object.is(value.after, -0));\n+\t\t\t\tconst key = shareable ? JSON.stringify(value) : undefined;\n+\t\t\t\tconst shared = key === undefined ? undefined : this.technicalEntries.get(key);\n+\t\t\t\tif (shared) return shared;\n+\t\t\t\tconst result = Object.freeze({\n+\t\t\t\t\t...value,\n+\t\t\t\t\tname: this.captureIdentifier(value.name),\n+\t\t\t\t\tbefore: this.captureTieValue(value.before),\n+\t\t\t\t\tafter: this.captureTieValue(value.after),\n+\t\t\t\t});\n+\t\t\t\tif (key !== undefined && this.technicalEntries.size < 4096)\n+\t\t\t\t\tthis.technicalEntries.set(key, result);\n+\t\t\t\treturn result;\n+\t\t\t}),\n+\t\t);\n+\t\tif (key !== undefined && this.technicalValues.size < 4096)\n+\t\t\tthis.technicalValues.set(key, result);\n+\t\treturn result;\n+\t}\n+\n \tstartPhase(name: string): void {\n \t\tif (this.phase?.name === name) return;\n \t\tif (this.phase) {\n@@ -736,12 +1008,10 @@ class TraceRecorder {\n \t\tif (!this.streaming) return;\n \t\tconst snapshot = {\n \t\t\t...candidate,\n-\t\t\tdates: candidate.dates ? [...candidate.dates] : undefined,\n+\t\t\tdates: this.captureDates(candidate.dates),\n \t\t\treason: candidate.reason ? { ...candidate.reason } : undefined,\n-\t\t\ttechnicalComparison: candidate.technicalComparison?.map((item) => ({ ...item })),\n-\t\t\tplacement: candidate.placement\n-\t\t\t\t? { ...candidate.placement, ruleIds: [...candidate.placement.ruleIds] }\n-\t\t\t\t: undefined,\n+\t\t\ttechnicalComparison: this.captureTechnicalValues(candidate.technicalComparison),\n+\t\t\tplacement: this.capturePlacement(candidate.placement),\n \t\t};\n \t\tconst pending = this.pendingCandidateOperations.get(candidate);\n \t\tif (pending) {\n@@ -776,6 +1046,16 @@ class TraceRecorder {\n \t\tdecision: MutableTraceDecision,\n \t\tcandidate: MutableTraceCandidate,\n \t): number {\n+\t\tif (candidate.comparison) {\n+\t\t\tcandidate.comparison = this.captureComparison(candidate.comparison);\n+\t\t}\n+\t\tcandidate.technicalComparison = this.captureTechnicalValues(candidate.technicalComparison);\n+\t\tif (candidate.firstDecisiveComparator !== undefined)\n+\t\t\tcandidate.firstDecisiveComparator = this.captureIdentifier(\n+\t\t\t\tcandidate.firstDecisiveComparator,\n+\t\t\t);\n+\t\tif (candidate.placement) candidate.placement = this.capturePlacement(candidate.placement);\n+\t\tif (candidate.dates) candidate.dates = this.captureDates(candidate.dates);\n \t\tconst index = decision.candidates.push(candidate) - 1;\n \t\tthis.recordCandidateUpdate(this.phase!, decision, index, 'append', candidate);\n \t\treturn index;\n@@ -869,18 +1149,13 @@ class TraceRecorder {\n \t\tconst mutable = copy\n \t\t\t? {\n \t\t\t\t\t...candidate,\n-\t\t\t\t\tdates: candidate.dates ? [...candidate.dates] : undefined,\n+\t\t\t\t\tdates: this.captureDates(candidate.dates),\n \t\t\t\t\treason: candidate.reason ? { ...candidate.reason } : undefined,\n-\t\t\t\t\ttechnicalComparison: candidate.technicalComparison?.map((item) => ({\n-\t\t\t\t\t\t...item,\n-\t\t\t\t\t})),\n-\t\t\t\t\tplacement: candidate.placement\n-\t\t\t\t\t\t? { ...candidate.placement, ruleIds: [...candidate.placement.ruleIds] }\n-\t\t\t\t\t\t: undefined,\n+\t\t\t\t\ttechnicalComparison: this.captureTechnicalValues(candidate.technicalComparison),\n+\t\t\t\t\tplacement: this.capturePlacement(candidate.placement),\n \t\t\t\t}\n \t\t\t: (candidate as MutableTraceCandidate);\n-\t\tconst index = this.recordNewCandidate(decision, mutable);\n-\t\tthis.evaluationLocations.set(mutable, { phase: this.phase!, decision, index });\n+\t\tthis.recordNewCandidate(decision, mutable);\n \t\treturn mutable;\n \t}\n \n@@ -900,8 +1175,7 @@ class TraceRecorder {\n \t\t}\n \t\tif (!candidate) return undefined;\n \t\tconst mutable = candidate as MutableTraceCandidate;\n-\t\tconst index = this.recordNewCandidate(decision, mutable);\n-\t\tthis.evaluationLocations.set(mutable, { phase: this.phase!, decision, index });\n+\t\tthis.recordNewCandidate(decision, mutable);\n \t\treturn mutable;\n \t}\n \n@@ -912,7 +1186,7 @@ class TraceRecorder {\n \t\tcandidate?: MutableTraceCandidate,\n \t): string {\n \t\tconst decision = candidate\n-\t\t\t? (this.evaluationLocations.get(candidate)?.decision ?? this.decision('choose', dates))\n+\t\t\t? (this.evaluationLocation(candidate)?.decision ?? this.decision('choose', dates))\n \t\t\t: this.decision('choose', dates);\n \t\tdecision.branch = {\n \t\t\tparentDecisionId,\n@@ -923,20 +1197,44 @@ class TraceRecorder {\n \t\treturn decision.id;\n \t}\n \n+\tprivate evaluationLocation(\n+\t\tcandidate: MutableTraceCandidate,\n+\t): { phase: MutableTracePhase; decision: MutableTraceDecision; index: number } | undefined {\n+\t\t// Immediate updates find the newest candidate first; late handles need no permanent index.\n+\t\tfor (let phaseIndex = this.phases.length - 1; phaseIndex >= 0; phaseIndex--) {\n+\t\t\tconst phase = this.phases[phaseIndex];\n+\t\t\tfor (\n+\t\t\t\tlet decisionIndex = phase.decisions.length - 1;\n+\t\t\t\tdecisionIndex >= 0;\n+\t\t\t\tdecisionIndex--\n+\t\t\t) {\n+\t\t\t\tconst decision = phase.decisions[decisionIndex];\n+\t\t\t\tconst index = decision.candidates.lastIndexOf(candidate);\n+\t\t\t\tif (index >= 0) return { phase, decision, index };\n+\t\t\t}\n+\t\t}\n+\t\treturn undefined;\n+\t}\n+\n \tdecisionIdFor(candidate: MutableTraceCandidate): string | undefined {\n-\t\treturn this.evaluationLocations.get(candidate)?.decision.id;\n+\t\treturn this.evaluationLocation(candidate)?.decision.id;\n \t}\n \n \trecordEvaluation(candidate: MutableTraceCandidate): void {\n \t\tconst decision = this.candidateDecision(\n \t\t\tcandidate.dates ?? (candidate.date ? [candidate.date] : []),\n \t\t);\n-\t\tconst index = this.recordNewCandidate(decision, candidate);\n-\t\tthis.evaluationLocations.set(candidate, { phase: this.phase!, decision, index });\n+\t\tthis.recordNewCandidate(decision, candidate);\n \t}\n \n \tupdateEvaluation(candidate: MutableTraceCandidate): void {\n-\t\tconst location = this.evaluationLocations.get(candidate);\n+\t\tif (candidate.placement) candidate.placement = this.capturePlacement(candidate.placement);\n+\t\tcandidate.technicalComparison = this.captureTechnicalValues(candidate.technicalComparison);\n+\t\tif (candidate.firstDecisiveComparator !== undefined)\n+\t\t\tcandidate.firstDecisiveComparator = this.captureIdentifier(\n+\t\t\t\tcandidate.firstDecisiveComparator,\n+\t\t\t);\n+\t\tconst location = this.evaluationLocation(candidate);\n \t\tif (location)\n \t\t\tthis.recordCandidateUpdate(\n \t\t\t\tlocation.phase,\n@@ -1014,7 +1312,7 @@ class TraceRecorder {\n \t\t\t...updated.map(([date]) => date),\n \t\t];\n \t\tconst decision =\n-\t\t\t(acceptedCandidate && this.evaluationLocations.get(acceptedCandidate)?.decision) ||\n+\t\t\t(acceptedCandidate && this.evaluationLocation(acceptedCandidate)?.decision) ||\n \t\t\tthis.decision(action, dates);\n \t\tdecision.action = action;\n \t\tdecision.dates = dates;\n@@ -1145,9 +1443,8 @@ class TraceRecorder {\n \t\t\t\tdecisions: phase.decisions.map((decision) => ({\n \t\t\t\t\t...decision,\n \t\t\t\t\tdates: [...decision.dates],\n-\t\t\t\t\tcandidates: decision.candidates.map((candidate) => ({\n-\t\t\t\t\t\t...candidate,\n-\t\t\t\t\t})),\n+\t\t\t\t\t// Search is complete; later stream drains only emit detached snapshots.\n+\t\t\t\t\tcandidates: [...decision.candidates],\n \t\t\t\t\tdeltas: decision.deltas.map((delta) => ({ ...delta })),\n \t\t\t\t})),\n \t\t\t})),\n@@ -1187,11 +1484,17 @@ interface SearchContext {\n \ttraceReportedTime: number;\n \tobserverTime: number;\n \tobligationSolutionBranches: WeakMap;\n+\tcompletedPreferenceStates: Map;\n+\tcompletedGenericState?: string;\n \ttraceBranchParentId?: string;\n \ttraceBranchActive?: boolean;\n \ttraceError?: PlanningReason;\n \t/** Supplied metrics were evaluated after reconciling earned entitlement dates. */\n-\tretain?: (state: State, finalizedMetrics?: PlanningMetrics) => void;\n+\tretain?: (\n+\t\tstate: State,\n+\t\tfinalizedMetrics?: PlanningMetrics,\n+\t\tvector?: PlanningObjectiveVector,\n+\t) => void;\n }\n \n type PlanningCalendar = Pick<\n@@ -1320,6 +1623,7 @@ const DAY_MS = 86_400_000;\n // that this ceiling misses a better lexicographic assignment.\n const OBLIGATION_SOLUTION_LIMIT = 4096;\n const EXACT_OBLIGATION_BRANCH_LIMIT = 10_000;\n+const WINDOW_OBLIGATION_PREVIEW_LIMIT = 8;\n const VALID_TYPES = new Set(['cp', 'rtt', 'other']);\n const VALID_SELECTORS = new Set(['cp', 'rtt', 'other', 'any']);\n const VALID_MODES = new Set(['before', 'after', 'around', 'auto']);\n@@ -1442,19 +1746,6 @@ function holidayWeekCandidates(context: SearchContext): HolidayWeekCandidate[] {\n \t);\n }\n \n-function holidayWeekValue(state: State, context: SearchContext): number {\n-\treturn context.holidayWeeks.reduce(\n-\t\t(value, candidate) =>\n-\t\t\tvalue +\n-\t\t\t(candidate.dates.every(\n-\t\t\t\t(date) => state.placements.has(date) || context.declaredDates.has(date),\n-\t\t\t)\n-\t\t\t\t? candidate.value\n-\t\t\t\t: 0),\n-\t\t0,\n-\t);\n-}\n-\n function reason(code: string, message: string, ruleIds?: string[]): PlanningReason {\n \treturn ruleIds?.length ? { code, message, ruleIds } : { code, message };\n }\n@@ -1657,6 +1948,9 @@ function retainAndRecordBranchMutation(\n ): string | undefined {\n \tlet decisionId: string | undefined;\n \tobserveTrace(context, (trace) => {\n+\t\tconst placement = candidate?.placement && after.placements.get(candidate.placement.date);\n+\t\tif (candidate && placement)\n+\t\t\tcandidate.placement = { ...placement, ruleIds: [...placement.ruleIds].sort() };\n \t\tdecisionId = trace.recordBranchTransition(\n \t\t\tdates,\n \t\t\tparentDecisionId,\n@@ -1668,42 +1962,6 @@ function retainAndRecordBranchMutation(\n \treturn decisionId;\n }\n \n-function retainAndRecordAtRiskBranchMutation(\n-\tcontext: SearchContext,\n-\tafter: State,\n-\tparentDecisionId: string | undefined,\n-\tcandidate: MutableTraceCandidate | undefined,\n-\tdate: string,\n-\tbalanceId: string,\n-\tremainingBefore: number,\n-): string | undefined {\n-\tlet decisionId: string | undefined;\n-\tobserveTrace(context, (trace) => {\n-\t\tconst placement = after.placements.get(date);\n-\t\tconst balance = after.balances.find((item) => item.id === balanceId);\n-\t\tif (!placement || !balance) return;\n-\t\tconst deltas: PlanningTraceDelta[] = [\n-\t\t\t{\n-\t\t\t\tkind: 'placement-added',\n-\t\t\t\tdate,\n-\t\t\t\tbalanceId,\n-\t\t\t\tplacement: { ...placement, ruleIds: [...placement.ruleIds].sort() },\n-\t\t\t},\n-\t\t];\n-\t\tif (remainingBefore !== balance.remaining)\n-\t\t\tdeltas.push({\n-\t\t\t\tkind: 'balance-changed',\n-\t\t\t\tbalanceId,\n-\t\t\t\tremainingBefore,\n-\t\t\t\tremainingAfter: balance.remaining,\n-\t\t\t\tbalance: { ...balance },\n-\t\t\t});\n-\t\tdecisionId = trace.recordBranchTransition([date], parentDecisionId, deltas, candidate);\n-\t});\n-\tcontext.retain?.(after);\n-\treturn decisionId;\n-}\n-\n function retainAndRecordState(\n \tcontext: SearchContext,\n \tstate: State,\n@@ -1711,6 +1969,10 @@ function retainAndRecordState(\n ): void {\n \tobserveTrace(context, (trace) => {\n \t\tconst snapshot = planningTraceState(state, context);\n+\t\tconst placement =\n+\t\t\tacceptedCandidate?.placement && state.placements.get(acceptedCandidate.placement.date);\n+\t\tif (acceptedCandidate && placement)\n+\t\t\tacceptedCandidate.placement = { ...placement, ruleIds: [...placement.ruleIds].sort() };\n \t\tif (acceptedCandidate) trace.chooseEvaluation(acceptedCandidate);\n \t\ttrace.recordPlan(\n \t\t\tsnapshot.placements,\n@@ -1739,9 +2001,11 @@ function normalizeForce(value: unknown): RuleForce | null {\n \treturn null;\n }\n \n-function normalizeRuleType(value: unknown): 'time_window' | 'if_then' | null {\n+function normalizeRuleType(value: unknown): NormalizedRule['type'] | null {\n \tconst normalized = String(value ?? '').toLowerCase();\n-\treturn normalized === 'time_window' || normalized === 'if_then' ? normalized : null;\n+\treturn normalized === 'time_window' || normalized === 'if_then' || normalized === 'optimization'\n+\t\t? normalized\n+\t\t: null;\n }\n \n function normalizeMode(value: unknown): PlacementMode | null {\n@@ -1872,6 +2136,26 @@ function normalizeRules(request: RuntimePlanningRequest): {\n \t\t\treasons.push(reason('rule-type', `Planning rule \"${id}\" has an unsupported type.`));\n \t\t\tcontinue;\n \t\t}\n+\t\tif (type === 'optimization') {\n+\t\t\tconst validated = validateOptimizationConfiguration(value?.configuration);\n+\t\t\tif (forceValue !== 'preference')\n+\t\t\t\treasons.push(\n+\t\t\t\t\treason('rule-force', 'Optimization rules support preference mode only.', [id]),\n+\t\t\t\t);\n+\t\t\tif (!validated.valid) {\n+\t\t\t\treasons.push(reason(validated.code, validated.message, [id]));\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\trules.push({\n+\t\t\t\tid,\n+\t\t\t\tname: typeof value?.name === 'string' ? value.name : id,\n+\t\t\t\ttype,\n+\t\t\t\tenabled: true,\n+\t\t\t\tforce: 'preference',\n+\t\t\t\tconfiguration: structuredClone(validated.configuration),\n+\t\t\t});\n+\t\t\tcontinue;\n+\t\t}\n \t\tconst placeDays = asInteger(value?.placeDays);\n \t\tconst placeType = normalizeSelector(value?.placeType);\n \t\tif (placeDays === null || placeDays < 0) {\n@@ -2050,7 +2334,7 @@ function futurePreferenceProtection(\n \tcontext.anyPreferenceDemandByDate = new Map();\n \tconst futureRules = rules.slice(startIndex);\n \tfor (const [offset, rule] of futureRules.entries()) {\n-\t\tif (!rule.enabled || rule.force !== 'preference') continue;\n+\t\tif (!rule.enabled || rule.force !== 'preference' || rule.type === 'optimization') continue;\n \t\tif (\n \t\t\trule.type === 'time_window' &&\n \t\t\tdeclaredWindowDays(rule, context).length >= rule.placeDays\n@@ -2097,9 +2381,24 @@ function futurePreferenceProtection(\n \n function occurrences(rule: NormalizedRule, context: SearchContext): string[] {\n \tif (rule.type !== 'if_then') return [];\n-\treturn dateRange(context.horizon.start, context.horizon.end).filter((date) => {\n-\t\treturn context.holidays.has(date) && utcDate(date).getUTCDay() === rule.dayOfWeek;\n-\t});\n+\tlet cached = occurrenceCache.get(context);\n+\tif (!cached) {\n+\t\tcached = new Map();\n+\t\toccurrenceCache.set(context, cached);\n+\t}\n+\tlet dates = cached.get(rule.id);\n+\tif (!dates) {\n+\t\tdates = [...context.holidays]\n+\t\t\t.filter(\n+\t\t\t\t(date) =>\n+\t\t\t\t\tdate >= context.horizon.start &&\n+\t\t\t\t\tdate < context.horizon.end &&\n+\t\t\t\t\tutcDate(date).getUTCDay() === rule.dayOfWeek,\n+\t\t\t)\n+\t\t\t.sort(compareDate);\n+\t\tcached.set(rule.id, dates);\n+\t}\n+\treturn dates;\n }\n \n function workingNeighbors(\n@@ -2126,7 +2425,19 @@ function workingNeighbors(\n \treturn result;\n }\n \n-function patternsFor(rule: NormalizedRule, holiday: string, context: SearchContext): string[][] {\n+function patternsFor(\n+\trule: NormalizedCalendarRule,\n+\tholiday: string,\n+\tcontext: SearchContext,\n+): string[][] {\n+\tlet cached = calendarPatternCache.get(context);\n+\tif (!cached) {\n+\t\tcached = new Map();\n+\t\tcalendarPatternCache.set(context, cached);\n+\t}\n+\tconst key = `${rule.id}:${holiday}`;\n+\tconst existing = cached.get(key);\n+\tif (existing) return existing;\n \tconst count = rule.placeDays;\n \tconst make = (before: number, after: number) =>\n \t\t[\n@@ -2141,7 +2452,7 @@ function patternsFor(rule: NormalizedRule, holiday: string, context: SearchConte\n \t} else {\n \t\tfor (let before = 0; before <= count; before++) patterns.push(make(before, count - before));\n \t}\n-\treturn patterns\n+\tconst eligible = patterns\n \t\t.filter(\n \t\t\t(pattern) =>\n \t\t\t\tpattern.length === count &&\n@@ -2152,6 +2463,8 @@ function patternsFor(rule: NormalizedRule, holiday: string, context: SearchConte\n \t\t\t\t),\n \t\t)\n \t\t.sort(compareDateLists);\n+\tcached.set(key, eligible);\n+\treturn eligible;\n }\n \n function buildRequirements(\n@@ -2166,7 +2479,7 @@ function buildRequirements(\n \tconst requirements: Requirement[] = [];\n \tlet index = 0;\n \tfor (const rule of rules) {\n-\t\tif (!rule.enabled || rule.force !== force) continue;\n+\t\tif (!rule.enabled || rule.force !== force || rule.type === 'optimization') continue;\n \t\tif (rule.type === 'time_window') {\n \t\t\tconst start =\n \t\t\t\tcompareDate(rule.startDate!, context.horizon.start) < 0\n@@ -2306,28 +2619,31 @@ function declaredPatternDay(date: string, selector: LeaveSelector, context: Sear\n \n function patternDateSatisfied(\n \tdate: string,\n-\trule: NormalizedRule,\n+\trule: NormalizedCalendarRule,\n \tstate: State,\n \tcontext: SearchContext,\n ): boolean {\n \treturn Boolean(\n \t\tdeclaredPatternDay(date, rule.placeType, context) ||\n-\t\tstate.placements.get(date)?.ruleIds.has(rule.id),\n+\t\t(state.placements.has(date) &&\n+\t\t\tselectorMatches(rule.placeType, state.placements.get(date)!.type)),\n \t);\n }\n \n-function assignDate(\n+function selectedOccurrencePattern(\n+\trule: NormalizedCalendarRule,\n+\toccurrence: string,\n \tstate: State,\n-\tdate: string,\n-\tselector: LeaveSelector,\n-\truleId: string,\n \tcontext: SearchContext,\n-\tselectedEvaluation?: (candidate: MutableTraceCandidate | undefined) => void,\n-): State | null {\n-\treturn (\n-\t\tassignDateVariants(state, date, selector, ruleId, context, true, selectedEvaluation)[0] ??\n-\t\tnull\n+): string[] | undefined {\n+\tconst activation = state.earnedActivations.find(\n+\t\t(item) => item.ruleId === rule.id && item.occurrence === occurrence,\n \t);\n+\treturn activation?.dates.every((date) => patternDateSatisfied(date, rule, state, context))\n+\t\t? activation.dates\n+\t\t: patternsFor(rule, occurrence, context).find((pattern) =>\n+\t\t\t\tpattern.every((date) => patternDateSatisfied(date, rule, state, context)),\n+\t\t\t);\n }\n \n function rejectDeclaredDate(context: SearchContext, date: string): boolean {\n@@ -2347,8 +2663,6 @@ function assignDateVariants(\n \tselector: LeaveSelector,\n \truleId: string,\n \tcontext: SearchContext,\n-\tfirstOnly = false,\n-\tselectedEvaluation?: (candidate: MutableTraceCandidate | undefined) => void,\n ): State[] {\n \tcontext.check();\n \tif (rejectDeclaredDate(context, date)) return [];\n@@ -2383,7 +2697,7 @@ function assignDateVariants(\n \t\t}\n \t\tconst result = cloneState(state);\n \t\tif (ruleId) result.placements.get(date)!.ruleIds.add(ruleId);\n-\t\tconst evaluation = recordTraceCandidate(context, {\n+\t\trecordTraceCandidate(context, {\n \t\t\tstatus: 'evaluated-rejected',\n \t\t\tdate,\n \t\t\tplacement: {\n@@ -2391,7 +2705,6 @@ function assignDateVariants(\n \t\t\t\truleIds: [...result.placements.get(date)!.ruleIds],\n \t\t\t},\n \t\t});\n-\t\tselectedEvaluation?.(evaluation);\n \t\treturn [result];\n \t}\n \tconst balances = state.balances\n@@ -2433,49 +2746,6 @@ function assignDateVariants(\n \t\t\t\t'No compatible leave balance can fund this candidate date.',\n \t\t\t),\n \t\t});\n-\tif (firstOnly && balances.length) {\n-\t\tconst first = balances[0];\n-\t\tconst selectionFacts = firstCompatibleBalanceSelectionFacts(\n-\t\t\tselector,\n-\t\t\tdate,\n-\t\t\tfirst,\n-\t\t\tbalances[1],\n-\t\t\tcontext,\n-\t\t);\n-\t\tconst result = cloneState(state);\n-\t\tresult.balances.find((item) => item.id === first.id)!.remaining--;\n-\t\tresult.placements.set(date, {\n-\t\t\tdate,\n-\t\t\tbalanceId: first.id,\n-\t\t\ttype: first.type,\n-\t\t\truleIds: ruleId ? new Set([ruleId]) : new Set(),\n-\t\t\tsupporting: false,\n-\t\t});\n-\t\tfor (const [index, balance] of balances.entries()) {\n-\t\t\tconst evaluation = recordTraceCandidate(context, {\n-\t\t\t\tstatus: index === 0 ? 'evaluated-rejected' : 'not-examined',\n-\t\t\t\tdate,\n-\t\t\t\t...(index === 0 ? selectionFacts : {}),\n-\t\t\t\t...(index === 0\n-\t\t\t\t\t? {}\n-\t\t\t\t\t: {\n-\t\t\t\t\t\t\treason: reason(\n-\t\t\t\t\t\t\t\t'first-compatible-balance',\n-\t\t\t\t\t\t\t\t'This balance was not examined after the first compatible balance was selected.',\n-\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t}),\n-\t\t\t\tplacement: {\n-\t\t\t\t\tdate,\n-\t\t\t\t\tbalanceId: balance.id,\n-\t\t\t\t\ttype: balance.type,\n-\t\t\t\t\truleIds: ruleId ? [ruleId] : [],\n-\t\t\t\t\tsupporting: false,\n-\t\t\t\t},\n-\t\t\t});\n-\t\t\tif (index === 0) selectedEvaluation?.(evaluation);\n-\t\t}\n-\t\treturn [result];\n-\t}\n \treturn balances.map((balance) => {\n \t\tconst result = cloneState(state);\n \t\tconst target = result.balances.find((item) => item.id === balance.id)!;\n@@ -2561,71 +2831,9 @@ function assignDateToBalance(\n \treturn result;\n }\n \n-function assignDateToBalanceInPlace(\n-\tstate: State,\n-\tdate: string,\n-\tbalanceId: string,\n-\tcontext: SearchContext,\n-\truleIds = new Set(),\n-\tselectedEvaluation?: (candidate: MutableTraceCandidate | undefined) => void,\n-\tbeforeMutation?: (state: State) => void,\n-\tselectionFacts?: Pick<\n-\t\tPlanningTraceCandidate,\n-\t\t'technicalComparison' | 'firstDecisiveComparator'\n-\t>,\n-): boolean {\n-\tcontext.check();\n-\tif (rejectDeclaredDate(context, date)) return false;\n-\tif (state.placements.has(date)) {\n-\t\trecordTraceCandidate(context, {\n-\t\t\tstatus: 'ineligible',\n-\t\t\tdate,\n-\t\t\treason: reason('occupied', 'Another placement already uses this date.'),\n-\t\t});\n-\t\treturn false;\n-\t}\n-\tconst balance = state.balances.find((item) => item.id === balanceId);\n-\tif (\n-\t\t!balance ||\n-\t\tbalance.remaining <= 0 ||\n-\t\tcompareDate(balance.availableFrom, date) > 0 ||\n-\t\tcompareDate(date, balance.expiryDate) > 0\n-\t) {\n-\t\trecordTraceCandidate(context, {\n-\t\t\tstatus: 'evaluated-rejected',\n-\t\t\tdate,\n-\t\t\treason: reason(\n-\t\t\t\t'balance-unavailable',\n-\t\t\t\t'The selected leave balance cannot fund this date.',\n-\t\t\t),\n-\t\t});\n-\t\treturn false;\n-\t}\n-\tbeforeMutation?.(state);\n-\tbalance.remaining--;\n-\tstate.placements.set(date, {\n-\t\tdate,\n-\t\tbalanceId,\n-\t\ttype: balance.type,\n-\t\truleIds: new Set(ruleIds),\n-\t\tsupporting: false,\n-\t});\n-\tconst evaluation = recordTraceCandidate(context, {\n-\t\tstatus: 'evaluated-rejected',\n-\t\tdate,\n-\t\t...selectionFacts,\n-\t\tplacement: {\n-\t\t\t...state.placements.get(date)!,\n-\t\t\truleIds: [...state.placements.get(date)!.ruleIds],\n-\t\t},\n-\t});\n-\tselectedEvaluation?.(evaluation);\n-\treturn true;\n-}\n-\n function addEarnedBalance(\n \tstate: State,\n-\trule: NormalizedRule,\n+\trule: NormalizedCalendarRule,\n \toccurrence: string,\n \tdates: string[],\n \tcontext: SearchContext,\n@@ -2682,8 +2890,26 @@ function earnedPeriodBounds(\n * period.\n */\n function finalizeEarnedState(state: State, context: SearchContext): State | null {\n-\tif (!state.earnedActivations.length) return state;\n-\tlet result = cloneState(state);\n+\tlet reconciled = state;\n+\t// Earning follows actual completed patterns, including those another rule already placed.\n+\t// Both comparison sides must contain these rights before an objective can rank them.\n+\tfor (const rule of context.rules) {\n+\t\tif (rule.type !== 'if_then' || !rule.rewardDays) continue;\n+\t\tfor (const occurrence of occurrences(rule, context)) {\n+\t\t\tif (\n+\t\t\t\treconciled.earnedActivations.some(\n+\t\t\t\t\t(activation) =>\n+\t\t\t\t\t\tactivation.ruleId === rule.id && activation.occurrence === occurrence,\n+\t\t\t\t)\n+\t\t\t)\n+\t\t\t\tcontinue;\n+\t\t\tconst pattern = selectedOccurrencePattern(rule, occurrence, reconciled, context);\n+\t\t\tif (pattern)\n+\t\t\t\treconciled = addEarnedBalance(reconciled, rule, occurrence, pattern, context);\n+\t\t}\n+\t}\n+\tif (!reconciled.earnedActivations.length) return reconciled;\n+\tlet result = cloneState(reconciled);\n \tfor (const activation of result.earnedActivations) {\n \t\tcontext.check();\n \t\tconst bounds = earnedPeriodBounds(result, activation, context);\n@@ -2699,7 +2925,10 @@ function finalizeEarnedState(state: State, context: SearchContext): State | null\n \t\t}\n \t\tlet balance = result.balances.find((item) => item.id === activation.id);\n \t\tif (!balance) {\n-\t\t\tconst rule = context.rules.find((rule) => rule.id === activation.ruleId);\n+\t\t\tconst rule = context.rules.find(\n+\t\t\t\t(rule): rule is NormalizedCalendarRule =>\n+\t\t\t\t\trule.type === 'if_then' && rule.id === activation.ruleId,\n+\t\t\t);\n \t\t\tif (!rule) return null;\n \t\t\tresult = addEarnedBalance(\n \t\t\t\tresult,\n@@ -2728,7 +2957,7 @@ function finalizeEarnedState(state: State, context: SearchContext): State | null\n function* assignDatesVariants(\n \tstate: State,\n \tdates: string[],\n-\trule: NormalizedRule,\n+\trule: NormalizedCalendarRule,\n \tcontext: SearchContext,\n ): PlanningSteps {\n \tif (!dates.length) return [state];\n@@ -2767,7 +2996,7 @@ function* satisfyObligations(\n \tyield;\n \tcontext.check();\n \tif (index >= requirements.length) {\n-\t\tconst finalized = finalizeEarnedState(state, context);\n+\t\tconst finalized = finalizeRuleCandidate(state, context, state);\n \t\tif (!finalized)\n \t\t\trecordTraceCandidate(context, {\n \t\t\t\tstatus: 'pruned',\n@@ -3000,213 +3229,1325 @@ function chooseObligationBranches(state: State, context: SearchContext): void {\n \t}\n }\n \n-function* placeAtRisk(state: State, context: SearchContext): PlanningSteps {\n-\t// At-risk placement is a greedy pass over one state. Clone it once, then\n-\t// mutate that private copy; cloning the whole placement map for every day is\n-\t// quadratic for a loaded year and does not change the observable result.\n-\tconst canMutate = state.earnedActivations.length === 0;\n-\tlet result = canMutate ? cloneState(state) : state;\n-\tconst balances = result.balances\n-\t\t.filter(\n-\t\t\t(balance) =>\n-\t\t\t\tcompareDate(balance.expiryDate, context.horizon.start) >= 0 &&\n-\t\t\t\tcompareDate(balance.expiryDate, context.horizon.end) <= 0,\n-\t\t)\n-\t\t.sort((a, b) => compareDate(a.expiryDate, b.expiryDate) || compareText(a.id, b.id));\n-\tfor (const balance of balances) {\n-\t\tyield;\n-\t\tconst availableDates = [...context.workingDays].sort(\n-\t\t\t(a, b) =>\n-\t\t\t\tpreferenceDateConflictScore(balance.type, a, context) -\n-\t\t\t\t\tpreferenceDateConflictScore(balance.type, b, context) || compareDate(a, b),\n-\t\t);\n-\t\twhile (true) {\n-\t\t\tyield;\n-\t\t\tcontext.check();\n-\t\t\tconst current = result.balances.find((item) => item.id === balance.id)!;\n-\t\t\tif (current.remaining <= 0) break;\n-\t\t\tlet nextState: State | null = null;\n-\t\t\tlet nextEvaluation: MutableTraceCandidate | undefined;\n-\t\t\tfor (const [candidateIndex, candidate] of availableDates.entries()) {\n-\t\t\t\tyield;\n-\t\t\t\tcontext.check();\n-\t\t\t\tif (\n-\t\t\t\t\t!result.placements.has(candidate) &&\n-\t\t\t\t\tcompareDate(current.availableFrom, candidate) <= 0 &&\n-\t\t\t\t\tcompareDate(candidate, current.expiryDate) <= 0\n-\t\t\t\t) {\n-\t\t\t\t\tconst nextDate = availableDates\n-\t\t\t\t\t\t.slice(candidateIndex + 1)\n-\t\t\t\t\t\t.find(\n-\t\t\t\t\t\t\t(date) =>\n-\t\t\t\t\t\t\t\t!result.placements.has(date) &&\n-\t\t\t\t\t\t\t\tcompareDate(current.availableFrom, date) <= 0 &&\n-\t\t\t\t\t\t\t\tcompareDate(date, current.expiryDate) <= 0,\n-\t\t\t\t\t\t);\n-\t\t\t\t\tconst selectionFacts = nextDate\n-\t\t\t\t\t\t? atRiskDateSelectionFacts(balance.type, candidate, nextDate, context)\n-\t\t\t\t\t\t: undefined;\n-\t\t\t\t\trecordTraceDecision(context, [candidate]);\n-\t\t\t\t\tlet remainingBeforeTransition = current.remaining;\n-\t\t\t\t\tlet evaluation: MutableTraceCandidate | undefined;\n-\t\t\t\t\tconst assigned = canMutate\n-\t\t\t\t\t\t? assignDateToBalanceInPlace(\n-\t\t\t\t\t\t\t\tresult,\n-\t\t\t\t\t\t\t\tcandidate,\n-\t\t\t\t\t\t\t\tcurrent.id,\n-\t\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\t\tnew Set(),\n-\t\t\t\t\t\t\t\t(candidateTrace) => (evaluation = candidateTrace),\n-\t\t\t\t\t\t\t\t(before) =>\n-\t\t\t\t\t\t\t\t\t(remainingBeforeTransition =\n-\t\t\t\t\t\t\t\t\t\tbefore.balances.find((item) => item.id === current.id)\n-\t\t\t\t\t\t\t\t\t\t\t?.remaining ?? remainingBeforeTransition),\n-\t\t\t\t\t\t\t\tselectionFacts,\n-\t\t\t\t\t\t\t)\n-\t\t\t\t\t\t\t? result\n-\t\t\t\t\t\t\t: null\n-\t\t\t\t\t\t: assignDateToBalance(\n-\t\t\t\t\t\t\t\tresult,\n-\t\t\t\t\t\t\t\tcandidate,\n-\t\t\t\t\t\t\t\tcurrent.id,\n-\t\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\t\tnew Set(),\n-\t\t\t\t\t\t\t\t(candidateTrace) => (evaluation = candidateTrace),\n-\t\t\t\t\t\t\t\tselectionFacts,\n-\t\t\t\t\t\t\t);\n-\t\t\t\t\tconst feasible = assigned ? finalizeEarnedState(assigned, context) : null;\n-\t\t\t\t\tif (feasible) {\n-\t\t\t\t\t\tnextState = feasible;\n-\t\t\t\t\t\tnextEvaluation = evaluation;\n-\t\t\t\t\t\tif (context.traceBranchActive) {\n-\t\t\t\t\t\t\tconst parent = canMutate\n-\t\t\t\t\t\t\t\t? retainAndRecordAtRiskBranchMutation(\n-\t\t\t\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\t\t\t\tfeasible,\n-\t\t\t\t\t\t\t\t\t\tcontext.traceBranchParentId,\n-\t\t\t\t\t\t\t\t\t\tevaluation,\n-\t\t\t\t\t\t\t\t\t\tcandidate,\n-\t\t\t\t\t\t\t\t\t\tcurrent.id,\n-\t\t\t\t\t\t\t\t\t\tremainingBeforeTransition,\n-\t\t\t\t\t\t\t\t\t)\n-\t\t\t\t\t\t\t\t: retainAndRecordBranchMutation(\n-\t\t\t\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\t\t\t\tresult,\n-\t\t\t\t\t\t\t\t\t\tfeasible,\n-\t\t\t\t\t\t\t\t\t\tcontext.traceBranchParentId,\n-\t\t\t\t\t\t\t\t\t\tevaluation,\n-\t\t\t\t\t\t\t\t\t\t[candidate],\n-\t\t\t\t\t\t\t\t\t);\n-\t\t\t\t\t\t\tcontext.traceBranchParentId = parent ?? context.traceBranchParentId;\n-\t\t\t\t\t\t}\n-\t\t\t\t\t\tbreak;\n-\t\t\t\t\t}\n-\t\t\t\t}\n-\t\t\t}\n-\t\t\tif (!nextState) break;\n-\t\t\tresult = nextState;\n-\t\t\tif (!context.traceBranchActive) retainAndRecordState(context, result, nextEvaluation);\n-\t\t}\n-\t}\n+function releasePlacement(state: State, date: string): State {\n+\t// Removing a slot never edits surviving placements. Later assignments and\n+\t// metadata reconciliation still detach their placements before changing them.\n+\tconst result: State = {\n+\t\tbalances: state.balances.map((balance) => ({ ...balance })),\n+\t\tplacements: new Map(state.placements),\n+\t\tearnedActivations: state.earnedActivations.map((activation) => ({\n+\t\t\t...activation,\n+\t\t\tdates: [...activation.dates],\n+\t\t})),\n+\t};\n+\tconst placement = result.placements.get(date)!;\n+\tresult.placements.delete(date);\n+\tresult.balances.find((balance) => balance.id === placement.balanceId)!.remaining++;\n \treturn result;\n }\n \n-function* preferenceTimeWindow(\n+function reconcileOptimizationProvenance(\n \tstate: State,\n-\trule: NormalizedRule,\n \tcontext: SearchContext,\n-): PlanningSteps<{ state: State; count: number }> {\n-\tconst start =\n-\t\tcompareDate(rule.startDate!, context.horizon.start) < 0\n-\t\t\t? context.horizon.start\n-\t\t\t: rule.startDate!;\n-\tconst end =\n-\t\tcompareDate(rule.endDate!, context.horizon.end) >= 0\n-\t\t\t? addDays(context.horizon.end, -1)\n-\t\t\t: rule.endDate!;\n-\tif (compareDate(start, end) > 0) return { state, count: 0 };\n+\tbefore: State,\n+\tobjectives: readonly PlanningObjective[] = activeObjectiveVector(state, context),\n+): State {\n+\tconst optimizations = objectives.filter(({ id }) => id.startsWith('optimization:'));\n+\tif (!optimizations.length) return state;\n \tlet result = state;\n-\tlet count = declaredWindowDays(rule, context).length;\n-\tconst shareableDates = new Set(\n-\t\t[...state.placements.values()]\n-\t\t\t.filter((placement) => selectorMatches(rule.placeType, placement.type))\n-\t\t\t.map((placement) => placement.date),\n-\t);\n-\tconst candidates = context.workingDays\n-\t\t.filter(\n-\t\t\t(item) =>\n-\t\t\t\t!context.declaredDates.has(item) &&\n-\t\t\t\tcompareDate(item, start) >= 0 &&\n-\t\t\t\tcompareDate(item, end) <= 0,\n+\tlet observations: OptimizationObservations | undefined;\n+\tfor (const placement of state.placements.values()) {\n+\t\tconst previous = before.placements.get(placement.date);\n+\t\tconst creditedIds = new Set([...placement.ruleIds, ...(previous?.ruleIds ?? [])]);\n+\t\tconst credits = optimizations.filter(({ id }) =>\n+\t\t\tcreditedIds.has(id.slice('optimization:'.length)),\n+\t\t);\n+\t\tif (!credits.length) continue;\n+\t\tconst withoutState = releasePlacement(state, placement.date);\n+\t\tconst withoutPlacement = activeObjectiveVector(withoutState, context);\n+\t\tconst ruleIds = new Set(\n+\t\t\t[...placement.ruleIds].filter(\n+\t\t\t\t(id) => !credits.some((objective) => objective.id === `optimization:${id}`),\n+\t\t\t),\n+\t\t);\n+\t\tfor (const objective of credits) {\n+\t\t\tconst without = withoutPlacement.find(({ id }) => id === objective.id)!;\n+\t\t\tconst id = objective.id.slice('optimization:'.length);\n+\t\t\tconst rule = context.rules.find(\n+\t\t\t\t(rule): rule is NormalizedOptimizationRule =>\n+\t\t\t\t\trule.id === id && rule.type === 'optimization',\n+\t\t\t)!;\n+\t\t\tconst compared = compareObjectiveValues(\n+\t\t\t\tobjective.direction,\n+\t\t\t\tobjective.value,\n+\t\t\t\twithout.value,\n+\t\t\t);\n+\t\t\tlet contributes = compared < 0;\n+\t\t\tif (compared === 0 && rule.configuration.aggregation === 'maximum') {\n+\t\t\t\t// Another tied maximum can mask a placement's improvement to its own element.\n+\t\t\t\tobservations ??= optimizationObservations(state, context);\n+\t\t\t\tconst withoutObservations = optimizationObservations(withoutState, context);\n+\t\t\t\tconst summed = { ...rule.configuration, aggregation: 'sum' as const };\n+\t\t\t\tconst summedComparison = compareObjectiveValues(\n+\t\t\t\t\tobjective.direction,\n+\t\t\t\t\tevaluateOptimization(summed, observations),\n+\t\t\t\t\tevaluateOptimization(summed, withoutObservations),\n+\t\t\t\t);\n+\t\t\t\tcontributes =\n+\t\t\t\t\tsummedComparison < 0 ||\n+\t\t\t\t\t(summedComparison === 0 &&\n+\t\t\t\t\t\trule.configuration.elements === 'time-off-periods' &&\n+\t\t\t\t\t\tobjective.direction === 'maximize' &&\n+\t\t\t\t\t\tobservations.timeOffPeriods.length <\n+\t\t\t\t\t\t\twithoutObservations.timeOffPeriods.length);\n+\t\t\t}\n+\t\t\tif (contributes) ruleIds.add(id);\n+\t\t}\n+\t\tif (\n+\t\t\truleIds.size === placement.ruleIds.size &&\n+\t\t\t[...ruleIds].every((id) => placement.ruleIds.has(id))\n \t\t)\n-\t\t.sort((a, b) => {\n-\t\t\treturn (\n-\t\t\t\tNumber(!shareableDates.has(a)) - Number(!shareableDates.has(b)) ||\n-\t\t\t\tpreferenceDateConflictScore(rule.placeType, a, context) -\n-\t\t\t\t\tpreferenceDateConflictScore(rule.placeType, b, context) ||\n-\t\t\t\tcompareDate(a, b)\n+\t\t\tcontinue;\n+\t\tif (result === state) result = cloneState(state);\n+\t\tresult.placements.get(placement.date)!.ruleIds = ruleIds;\n+\t}\n+\treturn result;\n+}\n+\n+function supportingCalendarBenefit(\n+\tbefore: OptimizationObservations,\n+\tafter: State,\n+\tcontext: SearchContext,\n+): boolean {\n+\tconst observations = optimizationObservations(after, context);\n+\treturn (\n+\t\tevaluateOptimization(OPTIMIZATION_PRESETS.holidayWeekValue, observations) >\n+\t\t\tevaluateOptimization(OPTIMIZATION_PRESETS.holidayWeekValue, before) ||\n+\t\tevaluateOptimization(OPTIMIZATION_PRESETS.nonWorkingDayGain, observations) >\n+\t\t\tevaluateOptimization(OPTIMIZATION_PRESETS.nonWorkingDayGain, before) ||\n+\t\tevaluateOptimization(OPTIMIZATION_PRESETS.longestWorkSequence, observations) <\n+\t\t\tevaluateOptimization(OPTIMIZATION_PRESETS.longestWorkSequence, before) ||\n+\t\tevaluateOptimization(OPTIMIZATION_PRESETS.shortSequenceDeficit, observations) <\n+\t\t\tevaluateOptimization(OPTIMIZATION_PRESETS.shortSequenceDeficit, before)\n+\t);\n+}\n+\n+function mandatoryRelocationDate(\n+\tdate: string,\n+\tbalance: InternalBalance,\n+\truleIds: ReadonlySet,\n+\tcontext: SearchContext,\n+): boolean {\n+\treturn [...ruleIds].every((id) => {\n+\t\tconst rule = context.rules.find((item) => item.id === id);\n+\t\tif (rule?.force !== 'obligation') return true;\n+\t\tif (!selectorMatches(rule.placeType, balance.type)) return false;\n+\t\treturn rule.type === 'time_window'\n+\t\t\t? date >= rule.startDate! && date <= rule.endDate!\n+\t\t\t: occurrences(rule, context).some((occurrence) =>\n+\t\t\t\t\tpatternsFor(rule, occurrence, context).some((pattern) =>\n+\t\t\t\t\t\tpattern.includes(date),\n+\t\t\t\t\t),\n+\t\t\t\t);\n+\t});\n+}\n+\n+/** Optimistic reachability ignores preference values and complete-pattern validity. */\n+function relocationCanReachFree(\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tbalanceId: string,\n+\truleIds: ReadonlySet,\n+\tvisited: ReadonlySet,\n+\tfailed: Set,\n+): boolean {\n+\tconst key = JSON.stringify([balanceId, [...ruleIds].sort(), [...visited].sort()]);\n+\tif (failed.has(key)) return false;\n+\tconst queue = [{ balanceId, ruleIds }];\n+\tconst seen = new Set();\n+\tfor (let index = 0; index < queue.length; index++) {\n+\t\tconst entry = queue[index];\n+\t\tconst identity = JSON.stringify([entry.balanceId, [...entry.ruleIds].sort()]);\n+\t\tif (seen.has(identity)) continue;\n+\t\tseen.add(identity);\n+\t\tconst balance = state.balances.find((item) => item.id === entry.balanceId)!;\n+\t\tfor (const date of context.workingDays) {\n+\t\t\tcontext.check();\n+\t\t\tif (\n+\t\t\t\tvisited.has(date) ||\n+\t\t\t\tcontext.declaredDates.has(date) ||\n+\t\t\t\tdate < balance.availableFrom ||\n+\t\t\t\tdate > balance.expiryDate ||\n+\t\t\t\t!mandatoryRelocationDate(date, balance, entry.ruleIds, context)\n+\t\t\t)\n+\t\t\t\tcontinue;\n+\t\t\tconst placement = state.placements.get(date);\n+\t\t\tif (!placement) return true;\n+\t\t\tqueue.push({ balanceId: placement.balanceId, ruleIds: placement.ruleIds });\n+\t\t}\n+\t}\n+\tfailed.add(key);\n+\treturn false;\n+}\n+\n+/** Relocate occupied dates along an augmenting path and validate only the complete addition. */\n+function* relocateForAddition(\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tdate: string,\n+\tbalanceId: string,\n+\truleIds: Set,\n+\tsupporting: boolean,\n+\taccept: (candidate: State, dates: string[]) => boolean,\n+\tvisited = new Set(),\n+\tpath: string[] = [],\n+\tfailedReachability = new Set(),\n+\tfailedSearches = new Set(),\n+): PlanningSteps {\n+\tyield;\n+\tcontext.check();\n+\tif (visited.has(date) || context.declaredDates.has(date)) return false;\n+\tconst existing = state.placements.get(date);\n+\tif (\n+\t\texisting?.balanceId === balanceId &&\n+\t\texisting.supporting === supporting &&\n+\t\texisting.ruleIds.size === ruleIds.size &&\n+\t\t[...existing.ruleIds].every((id) => ruleIds.has(id))\n+\t)\n+\t\treturn false;\n+\tconst key = JSON.stringify([\n+\t\tdate,\n+\t\tbalanceId,\n+\t\t[...ruleIds].sort(),\n+\t\tsupporting,\n+\t\t[...visited].sort(),\n+\t\tstate.balances.map((balance) => [balance.id, balance.remaining]),\n+\t\t[...state.placements.values()]\n+\t\t\t.sort((a, b) => compareDate(a.date, b.date))\n+\t\t\t.map((placement) => [\n+\t\t\t\tplacement.date,\n+\t\t\t\tplacement.balanceId,\n+\t\t\t\t[...placement.ruleIds].sort(),\n+\t\t\t\tplacement.supporting,\n+\t\t\t]),\n+\t]);\n+\tif (failedSearches.has(key)) {\n+\t\trecordTraceCandidate(context, {\n+\t\t\tstatus: 'pruned',\n+\t\t\tdate,\n+\t\t\tsourceDate: path[0],\n+\t\t\treason: reason(\n+\t\t\t\t'duplicate-relocation-state',\n+\t\t\t\t'This identical relocation state was already examined without a valid improving endpoint.',\n+\t\t\t),\n+\t\t});\n+\t\treturn false;\n+\t}\n+\tconst assigned = assignDateToBalance(\n+\t\texisting ? releasePlacement(state, date) : state,\n+\t\tdate,\n+\t\tbalanceId,\n+\t\tcontext,\n+\t\truleIds,\n+\t);\n+\tif (!assigned) return false;\n+\tassigned.placements.get(date)!.supporting = supporting;\n+\tconst dates = [...path, date];\n+\tif (!existing) {\n+\t\tconst accepted = accept(assigned, dates);\n+\t\tif (!accepted) failedSearches.add(key);\n+\t\treturn accepted;\n+\t}\n+\tconst displaced = assigned.balances.find((balance) => balance.id === existing.balanceId)!;\n+\tconst nextVisited = new Set([...visited, date]);\n+\tif (\n+\t\t!relocationCanReachFree(\n+\t\t\tassigned,\n+\t\t\tcontext,\n+\t\t\texisting.balanceId,\n+\t\t\texisting.ruleIds,\n+\t\t\tnextVisited,\n+\t\t\tfailedReachability,\n+\t\t)\n+\t)\n+\t\treturn false;\n+\tfor (const destination of context.workingDays) {\n+\t\tyield;\n+\t\tif (destination < displaced.availableFrom || destination > displaced.expiryDate) continue;\n+\t\tif (!mandatoryRelocationDate(destination, displaced, existing.ruleIds, context)) continue;\n+\t\tif (\n+\t\t\tyield* relocateForAddition(\n+\t\t\t\tassigned,\n+\t\t\t\tcontext,\n+\t\t\t\tdestination,\n+\t\t\t\texisting.balanceId,\n+\t\t\t\texisting.ruleIds,\n+\t\t\t\texisting.supporting,\n+\t\t\t\taccept,\n+\t\t\t\tnextVisited,\n+\t\t\t\tdates,\n+\t\t\t\tfailedReachability,\n+\t\t\t\tfailedSearches,\n+\t\t\t)\n+\t\t)\n+\t\t\treturn true;\n+\t}\n+\tfailedSearches.add(key);\n+\treturn false;\n+}\n+\n+function finalizeRuleCandidate(state: State, context: SearchContext, before: State): State | null {\n+\tlet result = state;\n+\tconst windowCredits = new Map();\n+\tconst patternCredits = new Map>();\n+\tfor (const placement of state.placements.values()) {\n+\t\tlet lostCalendarRequest = false;\n+\t\tfor (const id of placement.ruleIds) {\n+\t\t\tconst rule = context.rules.find((item) => item.id === id);\n+\t\t\tconst valid = counterfactualRuleValid(\n+\t\t\t\tplacement.date,\n+\t\t\t\tplacement.type,\n+\t\t\t\t[id],\n+\t\t\t\tcontext,\n+\t\t\t\tstate,\n \t\t\t);\n+\t\t\tconst credited = windowCredits.get(id) ?? 0;\n+\t\t\tlet withinRequest = true;\n+\t\t\tif (rule?.type === 'time_window')\n+\t\t\t\twithinRequest =\n+\t\t\t\t\tcredited <\n+\t\t\t\t\tMath.max(0, rule.placeDays - declaredWindowDays(rule, context).length);\n+\t\t\telse if (rule?.type === 'if_then') {\n+\t\t\t\tif (!patternCredits.has(id))\n+\t\t\t\t\tpatternCredits.set(\n+\t\t\t\t\t\tid,\n+\t\t\t\t\t\tnew Set(\n+\t\t\t\t\t\t\toccurrences(rule, context).flatMap(\n+\t\t\t\t\t\t\t\t(occurrence) =>\n+\t\t\t\t\t\t\t\t\tselectedOccurrencePattern(rule, occurrence, state, context) ??\n+\t\t\t\t\t\t\t\t\t[],\n+\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t),\n+\t\t\t\t\t);\n+\t\t\t\twithinRequest = patternCredits.get(id)!.has(placement.date);\n+\t\t\t}\n+\t\t\tif (valid && withinRequest) {\n+\t\t\t\tif (rule?.type === 'time_window') windowCredits.set(id, credited + 1);\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\tif (!valid && rule?.force === 'obligation') return null;\n+\t\t\tif (result === state) result = cloneState(state);\n+\t\t\tresult.placements.get(placement.date)!.ruleIds.delete(id);\n+\t\t\tlostCalendarRequest ||= rule?.type !== 'optimization';\n+\t\t}\n+\t\tconst current = result.placements.get(placement.date)!;\n+\t\tconst hasCalendarRequest = [...current.ruleIds].some((id) =>\n+\t\t\tcontext.rules.some((rule) => rule.id === id && rule.type !== 'optimization'),\n+\t\t);\n+\t\tconst previous = before.placements.get(placement.date);\n+\t\tlet supporting = current.supporting;\n+\t\tif (hasCalendarRequest) supporting = false;\n+\t\telse if (\n+\t\t\tlostCalendarRequest ||\n+\t\t\t(previous &&\n+\t\t\t\t(previous.balanceId !== placement.balanceId ||\n+\t\t\t\t\tprevious.supporting !== current.supporting))\n+\t\t) {\n+\t\t\tconst balance = result.balances.find((item) => item.id === placement.balanceId)!;\n+\t\t\tsupporting =\n+\t\t\t\t!isAtRisk(balance, context) &&\n+\t\t\t\t(current.supporting ||\n+\t\t\t\t\t(previous?.balanceId === placement.balanceId && previous.supporting) ||\n+\t\t\t\t\tsupportingCalendarBenefit(\n+\t\t\t\t\t\toptimizationObservations(releasePlacement(result, placement.date), context),\n+\t\t\t\t\t\tresult,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t));\n+\t\t}\n+\t\tif (supporting !== current.supporting) {\n+\t\t\tif (result === state) result = cloneState(state);\n+\t\t\tresult.placements.get(placement.date)!.supporting = supporting;\n+\t\t}\n+\t}\n+\tfor (const activation of state.earnedActivations) {\n+\t\tconst rule = context.rules.find(\n+\t\t\t(item): item is NormalizedCalendarRule =>\n+\t\t\t\titem.type === 'if_then' && item.id === activation.ruleId,\n+\t\t)!;\n+\t\tif (activation.dates.every((date) => patternDateSatisfied(date, rule, state, context)))\n+\t\t\tcontinue;\n+\t\tif (\n+\t\t\t[...state.placements.values()].some(\n+\t\t\t\t(placement) => placement.balanceId === activation.id,\n+\t\t\t)\n+\t\t)\n+\t\t\treturn null;\n+\t\tresult = cloneState(result);\n+\t\tresult.earnedActivations = result.earnedActivations.filter(\n+\t\t\t(item) => item.id !== activation.id,\n+\t\t);\n+\t\tresult.balances = result.balances.filter((balance) => balance.id !== activation.id);\n+\t}\n+\tconst finalized = finalizeEarnedState(result, context);\n+\treturn finalized && !unsatisfiedObligationCount(finalized, context) ? finalized : null;\n+}\n+\n+function recordRuleEvaluation(\n+\tafter: State,\n+\tcontext: SearchContext,\n+\tdates: string[],\n+\tbeforeVector: PlanningObjectiveVector,\n+\tafterVector: PlanningObjectiveVector,\n+\tsourceDate?: string,\n+\tincumbentVector = beforeVector,\n+): MutableTraceCandidate | undefined {\n+\tlet evaluation: MutableTraceCandidate | undefined;\n+\tobserveTrace(context, (trace) => {\n+\t\tconst facts = objectiveComparisonFacts(beforeVector.objectives, afterVector.objectives);\n+\t\tconst placement = after.placements.get(dates[dates.length - 1]);\n+\t\tevaluation = {\n+\t\t\tstatus: 'evaluated-rejected',\n+\t\t\tdates,\n+\t\t\tdate: dates[dates.length - 1],\n+\t\t\tsourceDate,\n+\t\t\tcomparison: objectiveComparison(beforeVector, afterVector),\n+\t\t\ttechnicalComparison: facts.values,\n+\t\t\tfirstDecisiveComparator: facts.firstDecisiveComparator,\n+\t\t\t...(placement\n+\t\t\t\t? { placement: { ...placement, ruleIds: [...placement.ruleIds].sort() } }\n+\t\t\t\t: {}),\n+\t\t};\n+\t\ttrace.recordEvaluation(evaluation);\n+\t});\n+\t// The global retained plan has already examined this valid local incumbent.\n+\t// Candidates that cannot beat it do not need a duplicate global comparison.\n+\tif (compareObjectiveLists(afterVector.objectives, incumbentVector.objectives) < 0)\n+\t\tcontext.retain?.(after, undefined, afterVector);\n+\treturn evaluation;\n+}\n+\n+function typedCalendarDates(context: SearchContext): Set {\n+\tconst typedDates = new Set();\n+\tfor (const rule of context.rules) {\n+\t\tif (rule.type === 'optimization' || rule.placeType === 'any') continue;\n+\t\tconst dates =\n+\t\t\trule.type === 'time_window'\n+\t\t\t\t? context.workingDays.filter(\n+\t\t\t\t\t\t(date) => rule.startDate! <= date && date <= rule.endDate!,\n+\t\t\t\t\t)\n+\t\t\t\t: occurrences(rule, context).flatMap((occurrence) =>\n+\t\t\t\t\t\tpatternsFor(rule, occurrence, context).flat(),\n+\t\t\t\t\t);\n+\t\tfor (const date of dates) typedDates.add(date);\n+\t}\n+\treturn typedDates;\n+}\n+\n+function* calendarPlacementCandidates(\n+\tstate: State,\n+\ttargetDates: string[],\n+\truleId: string,\n+\tcontext: SearchContext,\n+\taccept: (candidate: State, dates: string[], sourceDate?: string, addition?: boolean) => boolean,\n+): PlanningSteps {\n+\tconst missing = targetDates.filter(\n+\t\t(date) => !state.placements.has(date) && !context.declaredDates.has(date),\n+\t);\n+\tif (!missing.length) return false;\n+\tconst before = optimizationObservations(state, context);\n+\tconst typedDates = typedCalendarDates(context);\n+\tconst failed = new Set();\n+\tconst rankedDonors: { date: string; objectives: PlanningObjective[] }[] = [];\n+\tfor (const placement of state.placements.values()) {\n+\t\tyield;\n+\t\tcontext.check();\n+\t\tif (targetDates.includes(placement.date)) continue;\n+\t\trankedDonors.push({\n+\t\t\tdate: placement.date,\n+\t\t\tobjectives: activeObjectiveVector(releasePlacement(state, placement.date), context),\n \t\t});\n-\tfor (const date of candidates) {\n+\t}\n+\t// shortcut: recursion retains the original donor ranking; rerank when a measured bundle misses a better allocation.\n+\trankedDonors.sort(\n+\t\t(a, b) => compareObjectiveLists(a.objectives, b.objectives) || compareDate(b.date, a.date),\n+\t);\n+\tconst fill = function* (\n+\t\tindex: number,\n+\t\tcurrent: State,\n+\t\tsources: string[] = [],\n+\t\tadditions: string[] = [],\n+\t): PlanningSteps {\n \t\tyield;\n \t\tcontext.check();\n-\t\tif (count >= rule.placeDays) break;\n-\t\trecordTraceDecision(context, [date]);\n-\t\tconst before = result;\n-\t\tlet evaluation: MutableTraceCandidate | undefined;\n-\t\tconst next = assignDate(\n-\t\t\tresult,\n-\t\t\tdate,\n-\t\t\trule.placeType,\n-\t\t\trule.id,\n-\t\t\tcontext,\n-\t\t\t(candidate) => (evaluation = candidate),\n+\t\tconst key = JSON.stringify([\n+\t\t\tindex,\n+\t\t\tcurrent.balances.map((balance) => [balance.id, balance.remaining]),\n+\t\t\t[...current.placements.values()]\n+\t\t\t\t.sort((a, b) => compareDate(a.date, b.date))\n+\t\t\t\t.map((placement) => [\n+\t\t\t\t\tplacement.date,\n+\t\t\t\t\ttargetDates.includes(placement.date)\n+\t\t\t\t\t\t? typedDates.has(placement.date)\n+\t\t\t\t\t\t\t? placement.type\n+\t\t\t\t\t\t\t: null\n+\t\t\t\t\t\t: placement.type,\n+\t\t\t\t\ttargetDates.includes(placement.date) &&\n+\t\t\t\t\t!current.balances.find((balance) => balance.id === placement.balanceId)!.earned\n+\t\t\t\t\t\t? null\n+\t\t\t\t\t\t: placement.balanceId,\n+\t\t\t\t\t[...placement.ruleIds].sort(),\n+\t\t\t\t\tplacement.supporting,\n+\t\t\t\t\tadditions.includes(placement.date),\n+\t\t\t\t]),\n+\t\t]);\n+\t\tif (failed.has(key)) return false;\n+\t\tif (index === missing.length) {\n+\t\t\tconst benefit = supportingCalendarBenefit(before, current, context);\n+\t\t\tfor (const date of additions) {\n+\t\t\t\tconst placement = current.placements.get(date)!;\n+\t\t\t\tconst balance = current.balances.find((item) => item.id === placement.balanceId)!;\n+\t\t\t\tplacement.supporting = benefit && !isAtRisk(balance, context);\n+\t\t\t}\n+\t\t\tconst accepted = accept(current, missing, sources[0], additions.length > 0);\n+\t\t\tif (!accepted) failed.add(key);\n+\t\t\treturn accepted;\n+\t\t}\n+\t\tconst date = missing[index];\n+\t\tfor (const balance of current.balances) {\n+\t\t\tif (balance.remaining <= 0 || date < balance.availableFrom || date > balance.expiryDate)\n+\t\t\t\tcontinue;\n+\t\t\tconst assigned = assignDateToBalance(\n+\t\t\t\tcurrent,\n+\t\t\t\tdate,\n+\t\t\t\tbalance.id,\n+\t\t\t\tcontext,\n+\t\t\t\tnew Set([ruleId]),\n+\t\t\t);\n+\t\t\tif (!assigned) continue;\n+\t\t\tif (yield* fill(index + 1, assigned, sources, [...additions, date])) return true;\n+\t\t}\n+\t\tconst donors = new Set();\n+\t\tfor (const donor of rankedDonors) {\n+\t\t\tyield;\n+\t\t\tconst source = current.placements.get(donor.date);\n+\t\t\tif (!source) continue;\n+\t\t\tconst balance = current.balances.find((item) => item.id === source.balanceId)!;\n+\t\t\tif (\n+\t\t\t\tdate < balance.availableFrom ||\n+\t\t\t\tdate > balance.expiryDate ||\n+\t\t\t\t!mandatoryRelocationDate(date, balance, source.ruleIds, context)\n+\t\t\t)\n+\t\t\t\tcontinue;\n+\t\t\tconst without = releasePlacement(current, source.date);\n+\t\t\tconst identity = JSON.stringify([\n+\t\t\t\tsource.balanceId,\n+\t\t\t\t[...source.ruleIds].sort(),\n+\t\t\t\tsource.supporting,\n+\t\t\t\tactiveObjectiveVector(without, context),\n+\t\t\t]);\n+\t\t\t// shortcut: equivalent donor tokens share one deterministic source; expand coordinated donor choices if a measured plan needs them.\n+\t\t\tif (donors.has(identity)) continue;\n+\t\t\tdonors.add(identity);\n+\t\t\tconst assigned = assignDateToBalance(\n+\t\t\t\twithout,\n+\t\t\t\tdate,\n+\t\t\t\tsource.balanceId,\n+\t\t\t\tcontext,\n+\t\t\t\tsource.ruleIds,\n+\t\t\t);\n+\t\t\tif (!assigned) continue;\n+\t\t\tassigned.placements.get(date)!.supporting = source.supporting;\n+\t\t\tif (yield* fill(index + 1, assigned, [...sources, source.date], additions)) return true;\n+\t\t}\n+\t\tfailed.add(key);\n+\t\treturn false;\n+\t};\n+\treturn yield* fill(0, state);\n+}\n+\n+function* holidayWeekPlacementCandidates(\n+\tstate: State,\n+\truleId: string,\n+\tcontext: SearchContext,\n+\taccept: (candidate: State, dates: string[], sourceDate?: string, addition?: boolean) => boolean,\n+): PlanningSteps {\n+\tfor (const week of context.holidayWeeks)\n+\t\tyield* calendarPlacementCandidates(state, week.dates, ruleId, context, accept);\n+}\n+\n+function* timeOffPeriodPlacementCandidates(\n+\tstate: State,\n+\truleId: string,\n+\tcontext: SearchContext,\n+\taccept: (candidate: State, dates: string[], sourceDate?: string, addition?: boolean) => boolean,\n+): PlanningSteps {\n+\tconst periods = periodData(state, context);\n+\tfor (let index = 1; index < periods.length; index++) {\n+\t\tconst dates = context.workingDays.filter(\n+\t\t\t(date) => date > periods[index - 1].end && date < periods[index].start,\n \t\t);\n-\t\t// A later preference can extend the generating period of an earned\n-\t\t// entitlement. Reject that candidate immediately instead of allowing an\n-\t\t// optional preference to turn the final plan into a conflict.\n-\t\tconst feasible = next ? finalizeEarnedState(next, context) : null;\n-\t\tif (feasible) {\n-\t\t\tif (context.traceBranchActive) {\n-\t\t\t\tconst parent = retainAndRecordBranchMutation(\n+\t\tif (dates.length > 1)\n+\t\t\tyield* calendarPlacementCandidates(state, dates, ruleId, context, accept);\n+\t}\n+}\n+\n+function evaluateRuleCandidate(\n+\tbefore: State,\n+\tcandidate: State | null,\n+\tcontext: SearchContext,\n+\tthroughIndex: number,\n+\tdates: string[],\n+\tsourceDate?: string,\n+\taddition = false,\n+\tbaseline = activeObjectiveVector(before, context, throughIndex),\n+\tbeforeVector = objectiveVector(before, context),\n+\tincumbentVector = beforeVector,\n+):\n+\t| { state: State; vector: PlanningObjectiveVector; evaluation?: MutableTraceCandidate }\n+\t| undefined {\n+\tif (!candidate) return undefined;\n+\tconst state = finalizeRuleCandidate(candidate, context, before);\n+\tif (!state) return undefined;\n+\tconst active = activeObjectiveVector(state, context);\n+\tconst comparison = compareObjectiveLists(active.slice(0, throughIndex + 1), baseline);\n+\tconst vector = objectiveVector(state, context, active);\n+\tconst evaluation = recordRuleEvaluation(\n+\t\tstate,\n+\t\tcontext,\n+\t\tdates,\n+\t\tbeforeVector,\n+\t\tvector,\n+\t\tsourceDate,\n+\t\tincumbentVector,\n+\t);\n+\t// shortcut: single additions cannot cross equal-value plateaus; add coordinated balance bundles when a measured configuration needs them.\n+\tif (comparison > 0 || (addition && comparison === 0)) return undefined;\n+\treturn { state, vector, evaluation };\n+}\n+\n+/** Only the complete sequence change is compared; a partial gap fill can worsen the deficit. */\n+function* workSequencePlacementCandidates(\n+\tstate: State,\n+\trule: NormalizedOptimizationRule,\n+\tcontext: SearchContext,\n+\tconsider: (candidate: State, dates: string[]) => boolean,\n+): PlanningSteps {\n+\tconst configuration = rule.configuration;\n+\tif (configuration.direction !== 'minimize') return;\n+\tconst sequences = workSequenceDates(state, context).filter(\n+\t\t({ dates, internal }) =>\n+\t\t\tdates.length > 0 && (!configuration.conditions.includes('internal') || internal),\n+\t);\n+\tconst bundles: string[][][] = [];\n+\tif (configuration.aggregation === 'count')\n+\t\tbundles.push(...sequences.map(({ dates }) => dates.map((date) => [date])));\n+\telse if (configuration.measure === 'work-sequence-deficit') {\n+\t\tconst short = sequences.filter(({ dates }) => dates.length < configuration.thresholdDays);\n+\t\tif (configuration.aggregation === 'maximum') {\n+\t\t\tconst shortest = Math.min(...short.map(({ dates }) => dates.length));\n+\t\t\tbundles.push(\n+\t\t\t\tshort\n+\t\t\t\t\t.filter(({ dates }) => dates.length === shortest)\n+\t\t\t\t\t.flatMap(({ dates }) => dates.map((date) => [date])),\n+\t\t\t);\n+\t\t} else bundles.push(...short.map(({ dates }) => dates.map((date) => [date])));\n+\t} else if (\n+\t\tconfiguration.measure === 'work-sequence-length' &&\n+\t\tconfiguration.aggregation === 'maximum'\n+\t) {\n+\t\tconst maximum = Math.max(0, ...sequences.map(({ dates }) => dates.length));\n+\t\tconst tied = sequences.filter(({ dates }) => dates.length === maximum);\n+\t\tif (tied.length > 1) {\n+\t\t\tfor (const offset of [0, 1]) {\n+\t\t\t\tconst bundle: string[][] = [];\n+\t\t\t\tfor (const { dates } of tied) {\n+\t\t\t\t\tconst middle = Math.floor((dates.length - 1 + offset) / 2);\n+\t\t\t\t\tconst centered = dates\n+\t\t\t\t\t\t.map((date, index) => ({ date, index }))\n+\t\t\t\t\t\t.sort(\n+\t\t\t\t\t\t\t(a, b) =>\n+\t\t\t\t\t\t\t\tMath.abs(a.index - middle) - Math.abs(b.index - middle) ||\n+\t\t\t\t\t\t\t\tcompareDate(a.date, b.date),\n+\t\t\t\t\t\t);\n+\t\t\t\t\tconst eligible = [\n+\t\t\t\t\t\t...new Set(\n+\t\t\t\t\t\t\tstate.balances\n+\t\t\t\t\t\t\t\t.filter((balance) => balance.remaining > 0)\n+\t\t\t\t\t\t\t\t.map(\n+\t\t\t\t\t\t\t\t\t(balance) =>\n+\t\t\t\t\t\t\t\t\t\tcentered.find(\n+\t\t\t\t\t\t\t\t\t\t\t({ date }) =>\n+\t\t\t\t\t\t\t\t\t\t\t\tbalance.availableFrom <= date &&\n+\t\t\t\t\t\t\t\t\t\t\t\tdate <= balance.expiryDate,\n+\t\t\t\t\t\t\t\t\t\t)?.date,\n+\t\t\t\t\t\t\t\t)\n+\t\t\t\t\t\t\t\t.filter((date): date is string => date !== undefined),\n+\t\t\t\t\t\t),\n+\t\t\t\t\t];\n+\t\t\t\t\tif (!eligible.length) break;\n+\t\t\t\t\tbundle.push(\n+\t\t\t\t\t\teligible.sort(\n+\t\t\t\t\t\t\t(a, b) =>\n+\t\t\t\t\t\t\t\tcentered.findIndex(({ date }) => date === a) -\n+\t\t\t\t\t\t\t\tcentered.findIndex(({ date }) => date === b),\n+\t\t\t\t\t\t),\n+\t\t\t\t\t);\n+\t\t\t\t}\n+\t\t\t\tif (bundle.length === tied.length) bundles.push(bundle);\n+\t\t\t}\n+\t\t}\n+\t}\n+\tconst before = optimizationObservations(state, context);\n+\tconst available = state.balances.reduce((total, balance) => total + balance.remaining, 0);\n+\tconst typedDates = typedCalendarDates(context);\n+\tconst failedAssignments = new Set();\n+\tfunction* assignBundle(\n+\t\tcandidate: State,\n+\t\tslots: string[][],\n+\t\tdates: string[] = [],\n+\t): PlanningSteps {\n+\t\tyield;\n+\t\tcontext.check();\n+\t\t// Equivalent rejected allocations differ only in non-earned balance provenance.\n+\t\tconst key = JSON.stringify([\n+\t\t\tslots,\n+\t\t\tdates,\n+\t\t\tcandidate.balances.map(({ id, remaining }) => [id, remaining]),\n+\t\t\tdates.map((date) => {\n+\t\t\t\tconst placement = candidate.placements.get(date)!;\n+\t\t\t\tconst balance = candidate.balances.find((item) => item.id === placement.balanceId)!;\n+\t\t\t\treturn [\n+\t\t\t\t\ttypedDates.has(date) ? placement.type : undefined,\n+\t\t\t\t\tbalance.earned ? balance.id : undefined,\n+\t\t\t\t];\n+\t\t\t}),\n+\t\t]);\n+\t\tif (failedAssignments.has(key)) return false;\n+\t\tif (dates.length === slots.length) {\n+\t\t\tconst supporting = supportingCalendarBenefit(before, candidate, context);\n+\t\t\tfor (const date of dates) {\n+\t\t\t\tconst placement = candidate.placements.get(date)!;\n+\t\t\t\tconst balance = candidate.balances.find((item) => item.id === placement.balanceId)!;\n+\t\t\t\tplacement.supporting = supporting && !isAtRisk(balance, context);\n+\t\t\t}\n+\t\t\tconst accepted = consider(candidate, dates);\n+\t\t\tif (!accepted) failedAssignments.add(key);\n+\t\t\treturn accepted;\n+\t\t}\n+\t\tfor (const date of slots[dates.length]) {\n+\t\t\tfor (const next of assignDateVariants(candidate, date, 'any', rule.id, context))\n+\t\t\t\tif (yield* assignBundle(next, slots, [...dates, date])) return true;\n+\t\t}\n+\t\tfailedAssignments.add(key);\n+\t\treturn false;\n+\t}\n+\t// shortcut: bundles keep the first accepted allocation and nearest center per balance; extend when a measured case needs another coordinated allocation.\n+\tconst examined = new Set();\n+\tfor (const slots of bundles) {\n+\t\tyield;\n+\t\tconst key = JSON.stringify(slots);\n+\t\tif (slots.length <= 1 || slots.length > available || examined.has(key)) continue;\n+\t\texamined.add(key);\n+\t\tyield* assignBundle(state, slots);\n+\t}\n+}\n+\n+/** Candidate additions need an active rule improvement; expiry and date ties only reshape existing placements. */\n+function* optimizeRulePlacements(\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tthroughIndex: number,\n+\tallowAdd: boolean,\n+\trule?: NormalizedRule,\n+): PlanningSteps {\n+\tlet result = state;\n+\tconst addingBalanceQuantity =\n+\t\tallowAdd &&\n+\t\trule?.type === 'optimization' &&\n+\t\trule.configuration.elements === 'leave-balances' &&\n+\t\trule.configuration.measure === 'unplaced-quantity' &&\n+\t\trule.configuration.aggregation === 'sum' &&\n+\t\trule.configuration.direction === 'minimize';\n+\tconst equivalentAdditionFunding =\n+\t\taddingBalanceQuantity &&\n+\t\tthroughIndex === 0 &&\n+\t\t!context.rules.some((item) => item.enabled && item.type === 'if_then') &&\n+\t\tcontext.rules.every(\n+\t\t\t(item) =>\n+\t\t\t\t!item.enabled ||\n+\t\t\t\titem.type !== 'optimization' ||\n+\t\t\t\titem.configuration.elements !== 'leave-balances' ||\n+\t\t\t\titem.configuration.aggregation !== 'maximum',\n+\t\t);\n+\tconst fundingWindows = context.rules.filter(\n+\t\t(item): item is NormalizedCalendarRule => item.enabled && item.type === 'time_window',\n+\t);\n+\tconst preferencePrefix = context.rules\n+\t\t.filter((item) => item.enabled && item.force === 'preference')\n+\t\t.slice(0, throughIndex + 1);\n+\tconst prefixBounds = preferencePrefix.map((item, index): number | undefined => {\n+\t\tif (index === 0)\n+\t\t\treturn item.type === 'optimization' &&\n+\t\t\t\titem.configuration.elements === 'leave-balances' &&\n+\t\t\t\titem.configuration.measure === 'unplaced-quantity' &&\n+\t\t\t\titem.configuration.aggregation === 'sum' &&\n+\t\t\t\titem.configuration.direction === 'minimize'\n+\t\t\t\t? 0\n+\t\t\t\t: undefined;\n+\t\tif (item.type === 'time_window') return item.placeDays;\n+\t\tif (\n+\t\t\titem.type === 'optimization' &&\n+\t\t\titem.configuration.elements === 'public-holiday-weeks' &&\n+\t\t\titem.configuration.measure === 'public-holiday-week-value' &&\n+\t\t\titem.configuration.direction === 'maximize'\n+\t\t)\n+\t\t\treturn evaluateOptimization(item.configuration, {\n+\t\t\t\tleaveBalances: [],\n+\t\t\t\tpublicHolidayWeeks: context.holidayWeeks.map(({ value }) => ({\n+\t\t\t\t\tvalue,\n+\t\t\t\t\tcomplete: true,\n+\t\t\t\t})),\n+\t\t\t\ttimeOffPeriods: [],\n+\t\t\t\tworkSequences: [],\n+\t\t\t\tleavePlacements: [],\n+\t\t\t});\n+\t\treturn undefined;\n+\t});\n+\tconst dateInvariantObjectives = context.rules\n+\t\t.filter((item) => item.force === 'preference')\n+\t\t.every(\n+\t\t\t(item) =>\n+\t\t\t\titem.type === 'optimization' &&\n+\t\t\t\t(item.configuration!.elements === 'leave-balances' ||\n+\t\t\t\t\titem.configuration!.elements === 'leave-placements'),\n+\t\t);\n+\twhile (true) {\n+\t\tyield;\n+\t\tcontext.check();\n+\t\tconst active = activeObjectiveVector(result, context);\n+\t\tconst baseline = active.slice(0, throughIndex + 1);\n+\t\tconst beforeVector = objectiveVector(result, context, active);\n+\t\tcontext.retain?.(result, undefined, beforeVector);\n+\t\tif (\n+\t\t\tallowAdd &&\n+\t\t\tprefixBounds.length > 0 &&\n+\t\t\tprefixBounds.every(\n+\t\t\t\t(bound, index) => bound !== undefined && active[index].value === bound,\n+\t\t\t)\n+\t\t) {\n+\t\t\trecordTraceCandidate(context, {\n+\t\t\t\tstatus: 'not-examined',\n+\t\t\t\treason: reason(\n+\t\t\t\t\tthroughIndex === 0\n+\t\t\t\t\t\t? 'quantity-prefix-lower-bound'\n+\t\t\t\t\t\t: preferencePrefix.some(\n+\t\t\t\t\t\t\t\t\t(item) =>\n+\t\t\t\t\t\t\t\t\t\titem.type === 'optimization' &&\n+\t\t\t\t\t\t\t\t\t\titem.configuration.elements === 'public-holiday-weeks',\n+\t\t\t\t\t\t\t )\n+\t\t\t\t\t\t\t? 'satisfied-holiday-prefix-bound'\n+\t\t\t\t\t\t\t: 'satisfied-window-prefix-bound',\n+\t\t\t\t\t'The active quantity, window and holiday-week prefix has reached every configured bound; later preference stages and final tie-breaks remain to be evaluated.',\n+\t\t\t\t\tpreferencePrefix.map(({ id }) => id),\n+\t\t\t\t),\n+\t\t\t});\n+\t\t\treturn result;\n+\t\t}\n+\t\tconst genericStateKey =\n+\t\t\tallowAdd &&\n+\t\t\tresult.balances.every(({ remaining }) => remaining === 0) &&\n+\t\t\t!context.rules.some((item) => item.enabled && item.type === 'if_then')\n+\t\t\t\t? preferenceStateKey(result)\n+\t\t\t\t: undefined;\n+\t\tconst reuseGeneric =\n+\t\t\tgenericStateKey !== undefined && context.completedGenericState === genericStateKey;\n+\t\tconst compareEquivalentFunding =\n+\t\t\tequivalentAdditionFunding &&\n+\t\t\tresult.earnedActivations.length === 0 &&\n+\t\t\tNumber.isSafeInteger(\n+\t\t\t\tresult.balances.reduce((sum, balance) => sum + balance.remaining, 0),\n+\t\t\t);\n+\t\tlet beforeCalendar: OptimizationObservations | undefined;\n+\t\tlet best = result;\n+\t\tlet bestVector = beforeVector;\n+\t\tlet bestEvaluation: MutableTraceCandidate | undefined;\n+\t\tlet bestDates: string[] = [];\n+\t\tconst consider = (\n+\t\t\tcandidate: State | null,\n+\t\t\tdates: string[],\n+\t\t\tsourceDate?: string,\n+\t\t\taddition = false,\n+\t\t): boolean => {\n+\t\t\tconst evaluated = evaluateRuleCandidate(\n+\t\t\t\tresult,\n+\t\t\t\tcandidate,\n+\t\t\t\tcontext,\n+\t\t\t\tthroughIndex,\n+\t\t\t\tdates,\n+\t\t\t\tsourceDate,\n+\t\t\t\taddition,\n+\t\t\t\tbaseline,\n+\t\t\t\tbeforeVector,\n+\t\t\t\tbestVector,\n+\t\t\t);\n+\t\t\tif (!evaluated) return false;\n+\t\t\tconst compared = compareObjectiveLists(\n+\t\t\t\tevaluated.vector.objectives,\n+\t\t\t\tbestVector.objectives,\n+\t\t\t);\n+\t\t\tif (evaluated.evaluation) {\n+\t\t\t\tconst facts = objectiveComparisonFacts(\n+\t\t\t\t\tbestVector.objectives,\n+\t\t\t\t\tevaluated.vector.objectives,\n+\t\t\t\t);\n+\t\t\t\tevaluated.evaluation.technicalComparison = facts.values;\n+\t\t\t\tevaluated.evaluation.firstDecisiveComparator = facts.firstDecisiveComparator;\n+\t\t\t\tif (compared >= 0)\n+\t\t\t\t\tevaluated.evaluation.reason = reason(\n+\t\t\t\t\t\t'incumbent-comparison',\n+\t\t\t\t\t\t'This candidate did not improve the current best result.',\n+\t\t\t\t\t);\n+\t\t\t\tobserveTrace(context, (trace) => trace.updateEvaluation(evaluated.evaluation!));\n+\t\t\t}\n+\t\t\tif (compared >= 0) return true;\n+\t\t\tbest = evaluated.state;\n+\t\t\tbestVector = evaluated.vector;\n+\t\t\tbestEvaluation = evaluated.evaluation;\n+\t\t\tbestDates = dates;\n+\t\t\treturn true;\n+\t\t};\n+\t\tconst dates = [...context.workingDays].sort(\n+\t\t\t(a, b) => Number(result.placements.has(a)) - Number(result.placements.has(b)),\n+\t\t);\n+\t\t// shortcut: loaded plans sample flexible move destinations, upgrade to interval search when a measured case misses a better plan.\n+\t\tconst moveDates =\n+\t\t\tresult.placements.size <= 24\n+\t\t\t\t? context.workingDays\n+\t\t\t\t: context.workingDays.filter(\n+\t\t\t\t\t\t(date, index) =>\n+\t\t\t\t\t\t\t!isWorking(addDays(date, -1), context.holidays) ||\n+\t\t\t\t\t\t\t!isWorking(addDays(date, 1), context.holidays) ||\n+\t\t\t\t\t\t\tcontext.declaredDates.has(addDays(date, -1)) ||\n+\t\t\t\t\t\t\tcontext.declaredDates.has(addDays(date, 1)) ||\n+\t\t\t\t\t\t\tindex % 7 === 0 ||\n+\t\t\t\t\t\t\tcontext.rules.some(\n+\t\t\t\t\t\t\t\t(item) =>\n+\t\t\t\t\t\t\t\t\titem.type === 'time_window' &&\n+\t\t\t\t\t\t\t\t\tdate >= item.startDate! &&\n+\t\t\t\t\t\t\t\t\tdate <= item.endDate!,\n+\t\t\t\t\t\t\t),\n+\t\t\t\t\t);\n+\t\tif (\n+\t\t\tallowAdd &&\n+\t\t\trule?.type === 'optimization' &&\n+\t\t\trule.configuration.elements === 'work-sequences'\n+\t\t)\n+\t\t\tyield* workSequencePlacementCandidates(result, rule, context, (candidate, dates) =>\n+\t\t\t\tconsider(candidate, dates, undefined, true),\n+\t\t\t);\n+\t\tif (\n+\t\t\tallowAdd &&\n+\t\t\trule?.type === 'optimization' &&\n+\t\t\trule.configuration.elements === 'public-holiday-weeks' &&\n+\t\t\trule.configuration.conditions.includes('complete') &&\n+\t\t\trule.configuration.direction === 'maximize'\n+\t\t)\n+\t\t\tyield* holidayWeekPlacementCandidates(result, rule.id, context, consider);\n+\t\tif (\n+\t\t\tallowAdd &&\n+\t\t\trule?.type === 'optimization' &&\n+\t\t\trule.configuration.elements === 'time-off-periods' &&\n+\t\t\t((rule.configuration.aggregation === 'maximum' &&\n+\t\t\t\trule.configuration.direction === 'maximize') ||\n+\t\t\t\t(rule.configuration.aggregation === 'count' &&\n+\t\t\t\t\trule.configuration.direction === 'minimize'))\n+\t\t)\n+\t\t\tyield* timeOffPeriodPlacementCandidates(result, rule.id, context, consider);\n+\t\t// shortcut: commit a strict bundle prefix improvement before exploring old-state\n+\t\t// generic alternatives; upgrade to a combined frontier if measured cases need it.\n+\t\tconst deferGeneric =\n+\t\t\tallowAdd &&\n+\t\t\tbest !== result &&\n+\t\t\tcompareObjectiveLists(bestVector.objectives.slice(1, throughIndex + 2), baseline) < 0;\n+\t\tif (deferGeneric)\n+\t\t\trecordTraceCandidate(context, {\n+\t\t\t\tstatus: 'not-examined',\n+\t\t\t\treason: reason(\n+\t\t\t\t\t'strict-prefix-bundle-progress',\n+\t\t\t\t\t'A finalized rule-specific bundle strictly improved the active prefix; generic alternatives for the previous state were deferred before continuing from that improvement.',\n+\t\t\t\t\trule ? [rule.id] : undefined,\n+\t\t\t\t),\n+\t\t\t});\n+\t\tif (reuseGeneric)\n+\t\t\trecordTraceCandidate(context, {\n+\t\t\t\tstatus: 'not-examined',\n+\t\t\t\treason: reason(\n+\t\t\t\t\t'unchanged-generic-state',\n+\t\t\t\t\t'The configured sampled generic neighborhood was already exhausted for this unchanged state; rule-specific bundles were examined separately.',\n+\t\t\t\t),\n+\t\t\t});\n+\t\tfor (const date of reuseGeneric || deferGeneric ? [] : dates) {\n+\t\t\tyield;\n+\t\t\tcontext.check();\n+\t\t\tif (context.declaredDates.has(date)) continue;\n+\t\t\tconst existing = result.placements.get(date);\n+\t\t\tif (!existing && allowAdd) {\n+\t\t\t\tif (\n+\t\t\t\t\trule?.type === 'time_window' &&\n+\t\t\t\t\t(date < rule.startDate! || date > rule.endDate!)\n+\t\t\t\t)\n+\t\t\t\t\tcontinue;\n+\t\t\t\tconst evaluatedFunding = new Set();\n+\t\t\t\tfor (const balance of result.balances) {\n+\t\t\t\t\tyield;\n+\t\t\t\t\tif (\n+\t\t\t\t\t\trule?.type === 'time_window' &&\n+\t\t\t\t\t\t!selectorMatches(rule.placeType, balance.type)\n+\t\t\t\t\t)\n+\t\t\t\t\t\tcontinue;\n+\t\t\t\t\tif (\n+\t\t\t\t\t\tbalance.remaining <= 0 ||\n+\t\t\t\t\t\tbalance.availableFrom > date ||\n+\t\t\t\t\t\tbalance.expiryDate < date\n+\t\t\t\t\t)\n+\t\t\t\t\t\tcontinue;\n+\t\t\t\t\t// Complete single additions with equal expiry/window scores cannot beat the\n+\t\t\t\t\t// first evaluated funder. Recursive bundles still need every funding choice.\n+\t\t\t\t\tconst fundingKey =\n+\t\t\t\t\t\tcompareEquivalentFunding && isAtRisk(balance, context)\n+\t\t\t\t\t\t\t? `${balance.expiryDate}:${fundingWindows\n+\t\t\t\t\t\t\t\t\t.map((window) =>\n+\t\t\t\t\t\t\t\t\t\tNumber(\n+\t\t\t\t\t\t\t\t\t\t\tdate >= window.startDate! &&\n+\t\t\t\t\t\t\t\t\t\t\t\tdate <= window.endDate! &&\n+\t\t\t\t\t\t\t\t\t\t\t\tselectorMatches(window.placeType, balance.type),\n+\t\t\t\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t\t\t\t)\n+\t\t\t\t\t\t\t\t\t.join('')}`\n+\t\t\t\t\t\t\t: undefined;\n+\t\t\t\t\tif (fundingKey !== undefined && evaluatedFunding.has(fundingKey)) {\n+\t\t\t\t\t\trecordTraceCandidate(context, {\n+\t\t\t\t\t\t\tstatus: 'not-examined',\n+\t\t\t\t\t\t\tdate,\n+\t\t\t\t\t\t\tplacement: {\n+\t\t\t\t\t\t\t\tdate,\n+\t\t\t\t\t\t\t\tbalanceId: balance.id,\n+\t\t\t\t\t\t\t\ttype: balance.type,\n+\t\t\t\t\t\t\t\tsupporting: false,\n+\t\t\t\t\t\t\t\truleIds: [rule!.id],\n+\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\treason: reason(\n+\t\t\t\t\t\t\t\t'equivalent-date-funding',\n+\t\t\t\t\t\t\t\t'An earlier valid finalized funder has identical active objective values and final ties for this date.',\n+\t\t\t\t\t\t\t\t[rule!.id],\n+\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t});\n+\t\t\t\t\t\tcontinue;\n+\t\t\t\t\t}\n+\t\t\t\t\tconst assigned = assignDateToBalance(\n+\t\t\t\t\t\tresult,\n+\t\t\t\t\t\tdate,\n+\t\t\t\t\t\tbalance.id,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\trule ? new Set([rule.id]) : new Set(),\n+\t\t\t\t\t);\n+\t\t\t\t\tif (assigned && rule?.type === 'optimization' && !isAtRisk(balance, context)) {\n+\t\t\t\t\t\tbeforeCalendar ??= optimizationObservations(result, context);\n+\t\t\t\t\t\tassigned.placements.get(date)!.supporting = supportingCalendarBenefit(\n+\t\t\t\t\t\t\tbeforeCalendar,\n+\t\t\t\t\t\t\tassigned,\n+\t\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\t);\n+\t\t\t\t\t}\n+\t\t\t\t\tconst evaluated = consider(assigned, [date], undefined, true);\n+\t\t\t\t\tif (evaluated && fundingKey !== undefined) evaluatedFunding.add(fundingKey);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif (!existing || (addingBalanceQuantity && best !== result)) continue;\n+\t\t\tconst without = releasePlacement(result, date);\n+\t\t\tconsider(without, [date], date);\n+\t\t\tfor (const balance of without.balances) {\n+\t\t\t\tyield;\n+\t\t\t\tif (\n+\t\t\t\t\tbalance.id === existing.balanceId ||\n+\t\t\t\t\tbalance.remaining <= 0 ||\n+\t\t\t\t\tbalance.availableFrom > date ||\n+\t\t\t\t\tbalance.expiryDate < date\n+\t\t\t\t)\n+\t\t\t\t\tcontinue;\n+\t\t\t\tconst reassigned = assignDateToBalance(\n+\t\t\t\t\twithout,\n+\t\t\t\t\tdate,\n+\t\t\t\t\tbalance.id,\n \t\t\t\t\tcontext,\n-\t\t\t\t\tbefore,\n-\t\t\t\t\tfeasible,\n-\t\t\t\t\tcontext.traceBranchParentId,\n-\t\t\t\t\tevaluation,\n-\t\t\t\t\t[date],\n+\t\t\t\t\texisting.ruleIds,\n \t\t\t\t);\n-\t\t\t\tcontext.traceBranchParentId = parent ?? context.traceBranchParentId;\n-\t\t\t} else retainAndRecordState(context, feasible, evaluation);\n-\t\t\tresult = feasible;\n-\t\t\tcount++;\n+\t\t\t\tif (reassigned)\n+\t\t\t\t\treassigned.placements.get(date)!.supporting =\n+\t\t\t\t\t\texisting.supporting && !isAtRisk(balance, context);\n+\t\t\t\tconsider(reassigned, [date], date);\n+\t\t\t}\n+\t\t\tfor (const destination of moveDates) {\n+\t\t\t\tyield;\n+\t\t\t\tcontext.check();\n+\t\t\t\tif (destination === date || context.declaredDates.has(destination)) continue;\n+\t\t\t\tconst other = without.placements.get(destination);\n+\t\t\t\tif (other) {\n+\t\t\t\t\tif (other.balanceId === existing.balanceId) continue;\n+\t\t\t\t\tconst swapped = releasePlacement(without, destination);\n+\t\t\t\t\tconst first = assignDateToBalance(\n+\t\t\t\t\t\tswapped,\n+\t\t\t\t\t\tdestination,\n+\t\t\t\t\t\texisting.balanceId,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\texisting.ruleIds,\n+\t\t\t\t\t);\n+\t\t\t\t\tconst second =\n+\t\t\t\t\t\tfirst &&\n+\t\t\t\t\t\tassignDateToBalance(first, date, other.balanceId, context, other.ruleIds);\n+\t\t\t\t\tif (second) {\n+\t\t\t\t\t\tsecond.placements.get(destination)!.supporting = existing.supporting;\n+\t\t\t\t\t\tsecond.placements.get(date)!.supporting = other.supporting;\n+\t\t\t\t\t}\n+\t\t\t\t\tconsider(second, [date, destination], date);\n+\t\t\t\t} else {\n+\t\t\t\t\tconst moved = assignDateToBalance(\n+\t\t\t\t\t\twithout,\n+\t\t\t\t\t\tdestination,\n+\t\t\t\t\t\texisting.balanceId,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\texisting.ruleIds,\n+\t\t\t\t\t);\n+\t\t\t\t\tif (moved) moved.placements.get(destination)!.supporting = existing.supporting;\n+\t\t\t\t\tif (\n+\t\t\t\t\t\tmoved &&\n+\t\t\t\t\t\tdateInvariantObjectives &&\n+\t\t\t\t\t\tcompareObjectiveLists(\n+\t\t\t\t\t\t\ttieBreakObjectives(moved),\n+\t\t\t\t\t\t\tbeforeVector.objectives.slice(-2),\n+\t\t\t\t\t\t) >= 0\n+\t\t\t\t\t) {\n+\t\t\t\t\t\trecordTraceCandidate(context, {\n+\t\t\t\t\t\t\tstatus: 'pruned',\n+\t\t\t\t\t\t\tdate: destination,\n+\t\t\t\t\t\t\tsourceDate: date,\n+\t\t\t\t\t\t\treason: reason(\n+\t\t\t\t\t\t\t\t'unchanged-objective-tie-bound',\n+\t\t\t\t\t\t\t\t'The move preserves every active rule value and cannot improve the final tie-breaks.',\n+\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t});\n+\t\t\t\t\t\tcontinue;\n+\t\t\t\t\t}\n+\t\t\t\t\tconsider(moved, [destination], date);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif (moveDates.length < context.workingDays.length) {\n+\t\t\t\tconst examined = new Set(moveDates);\n+\t\t\t\tfor (const destination of context.workingDays) {\n+\t\t\t\t\tif (examined.has(destination)) continue;\n+\t\t\t\t\trecordTraceCandidate(context, {\n+\t\t\t\t\t\tstatus: 'not-examined',\n+\t\t\t\t\t\tdate: destination,\n+\t\t\t\t\t\tsourceDate: date,\n+\t\t\t\t\t\treason: reason(\n+\t\t\t\t\t\t\t'loaded-plan-sampling',\n+\t\t\t\t\t\t\t'This move destination was not examined in a loaded plan.',\n+\t\t\t\t\t\t),\n+\t\t\t\t\t});\n+\t\t\t\t}\n+\t\t\t}\n \t\t}\n+\t\tif (\n+\t\t\tallowAdd &&\n+\t\t\t(addingBalanceQuantity ||\n+\t\t\t\t(rule?.type === 'time_window' &&\n+\t\t\t\t\tNumber(active[throughIndex].value) < rule.placeDays)) &&\n+\t\t\tcompareObjectiveLists(bestVector.objectives.slice(1, throughIndex + 2), baseline) === 0\n+\t\t) {\n+\t\t\tfor (const balance of result.balances) {\n+\t\t\t\tif (balance.remaining <= 0) continue;\n+\t\t\t\tfor (const date of result.placements.keys()) {\n+\t\t\t\t\tyield;\n+\t\t\t\t\tif (date < balance.availableFrom || date > balance.expiryDate) continue;\n+\t\t\t\t\tconst sourceRuleApplies =\n+\t\t\t\t\t\trule?.type !== 'time_window' ||\n+\t\t\t\t\t\t(date >= rule.startDate! &&\n+\t\t\t\t\t\t\tdate <= rule.endDate! &&\n+\t\t\t\t\t\t\tselectorMatches(rule.placeType, balance.type));\n+\t\t\t\t\tyield* relocateForAddition(\n+\t\t\t\t\t\tresult,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\tdate,\n+\t\t\t\t\t\tbalance.id,\n+\t\t\t\t\t\trule && sourceRuleApplies ? new Set([rule.id]) : new Set(),\n+\t\t\t\t\t\tfalse,\n+\t\t\t\t\t\t(candidate, dates) => {\n+\t\t\t\t\t\t\tif (rule?.type === 'optimization' && !isAtRisk(balance, context)) {\n+\t\t\t\t\t\t\t\tbeforeCalendar ??= optimizationObservations(result, context);\n+\t\t\t\t\t\t\t\tcandidate.placements.get(date)!.supporting =\n+\t\t\t\t\t\t\t\t\tsupportingCalendarBenefit(beforeCalendar, candidate, context);\n+\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\treturn consider(candidate, dates, date, true);\n+\t\t\t\t\t\t},\n+\t\t\t\t\t);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t}\n+\t\tif (best === result) {\n+\t\t\t// Admit only a completed fixed point, after both bundles and the generic scan.\n+\t\t\tif (genericStateKey !== undefined) context.completedGenericState = genericStateKey;\n+\t\t\treturn result;\n+\t\t}\n+\t\tbest = reconcileOptimizationProvenance(best, context, result, bestVector.objectives);\n+\t\tif (context.traceBranchActive) {\n+\t\t\tconst parent = retainAndRecordBranchMutation(\n+\t\t\t\tcontext,\n+\t\t\t\tresult,\n+\t\t\t\tbest,\n+\t\t\t\tcontext.traceBranchParentId,\n+\t\t\t\tbestEvaluation,\n+\t\t\t\tbestDates,\n+\t\t\t);\n+\t\t\tcontext.traceBranchParentId = parent ?? context.traceBranchParentId;\n+\t\t} else retainAndRecordState(context, best, bestEvaluation);\n+\t\tresult = best;\n \t}\n-\treturn { state: result, count };\n+}\n+\n+function associateCalendarPreference(\n+\tstate: State,\n+\trule: NormalizedCalendarRule,\n+\tcontext: SearchContext,\n+): State {\n+\tconst result = cloneState(state);\n+\tconst dates =\n+\t\trule.type === 'time_window'\n+\t\t\t? [...result.placements.values()]\n+\t\t\t\t\t.filter(\n+\t\t\t\t\t\t(placement) =>\n+\t\t\t\t\t\t\tplacement.date >= rule.startDate! &&\n+\t\t\t\t\t\t\tplacement.date <= rule.endDate! &&\n+\t\t\t\t\t\t\tselectorMatches(rule.placeType, placement.type),\n+\t\t\t\t\t)\n+\t\t\t\t\t.sort((a, b) => Number(b.ruleIds.has(rule.id)) - Number(a.ruleIds.has(rule.id)))\n+\t\t\t\t\t.slice(\n+\t\t\t\t\t\t0,\n+\t\t\t\t\t\tMath.max(0, rule.placeDays - declaredWindowDays(rule, context).length),\n+\t\t\t\t\t)\n+\t\t\t\t\t.map((placement) => placement.date)\n+\t\t\t: occurrences(rule, context).flatMap(\n+\t\t\t\t\t(occurrence) =>\n+\t\t\t\t\t\tselectedOccurrencePattern(rule, occurrence, result, context) ?? [],\n+\t\t\t\t);\n+\tfor (const date of dates) {\n+\t\tconst placement = result.placements.get(date);\n+\t\tif (!placement) continue;\n+\t\tplacement.ruleIds.add(rule.id);\n+\t\tplacement.supporting = false;\n+\t}\n+\treturn result;\n+}\n+\n+/** Complete the entire typed pattern before checking the ordered objectives. */\n+function* preferencePatternVariants(\n+\tstate: State,\n+\tpattern: string[],\n+\trule: NormalizedCalendarRule,\n+\tcontext: SearchContext,\n+): PlanningSteps {\n+\tlet variants = [state];\n+\tfor (const date of pattern) {\n+\t\tyield;\n+\t\tconst next: State[] = [];\n+\t\tfor (const current of variants) {\n+\t\t\tyield;\n+\t\t\tconst existing = current.placements.get(date);\n+\t\t\tif (!existing || selectorMatches(rule.placeType, existing.type)) {\n+\t\t\t\tif (declaredPatternDay(date, rule.placeType, context)) next.push(current);\n+\t\t\t\telse\n+\t\t\t\t\tnext.push(\n+\t\t\t\t\t\t...assignDateVariants(current, date, rule.placeType, rule.id, context),\n+\t\t\t\t\t);\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\tconst without = releasePlacement(current, date);\n+\t\t\tfor (const balance of without.balances) {\n+\t\t\t\tyield;\n+\t\t\t\tif (!selectorMatches(rule.placeType, balance.type)) continue;\n+\t\t\t\tconst reassigned = assignDateToBalance(\n+\t\t\t\t\twithout,\n+\t\t\t\t\tdate,\n+\t\t\t\t\tbalance.id,\n+\t\t\t\t\tcontext,\n+\t\t\t\t\tnew Set([rule.id]),\n+\t\t\t\t);\n+\t\t\t\tif (reassigned) next.push(reassigned);\n+\t\t\t}\n+\t\t\tfor (const other of without.placements.values()) {\n+\t\t\t\tyield;\n+\t\t\t\tif (pattern.includes(other.date) || !selectorMatches(rule.placeType, other.type))\n+\t\t\t\t\tcontinue;\n+\t\t\t\tconst released = releasePlacement(without, other.date);\n+\t\t\t\tconst first = assignDateToBalance(\n+\t\t\t\t\treleased,\n+\t\t\t\t\tdate,\n+\t\t\t\t\tother.balanceId,\n+\t\t\t\t\tcontext,\n+\t\t\t\t\tnew Set([...other.ruleIds, rule.id]),\n+\t\t\t\t);\n+\t\t\t\tconst swapped =\n+\t\t\t\t\tfirst &&\n+\t\t\t\t\tassignDateToBalance(\n+\t\t\t\t\t\tfirst,\n+\t\t\t\t\t\tother.date,\n+\t\t\t\t\t\texisting.balanceId,\n+\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\texisting.ruleIds,\n+\t\t\t\t\t);\n+\t\t\t\tif (!swapped) continue;\n+\t\t\t\tswapped.placements.get(date)!.supporting = other.supporting;\n+\t\t\t\tswapped.placements.get(other.date)!.supporting = existing.supporting;\n+\t\t\t\tnext.push(swapped);\n+\t\t\t}\n+\t\t}\n+\t\tvariants = next;\n+\t\tif (!variants.length) break;\n+\t}\n+\treturn variants;\n }\n \n function* preferenceIfThen(\n \tstate: State,\n-\trule: NormalizedRule,\n+\trule: NormalizedCalendarRule,\n \tcontext: SearchContext,\n+\tpreferenceIndex: number,\n ): PlanningSteps<{ state: State; count: number }> {\n \tconst matchingOccurrences = occurrences(rule, context);\n \tlet bestState = state;\n \tlet bestCount = 0;\n-\tlet bestFutureScore = Number.POSITIVE_INFINITY;\n-\tlet bestMetrics: PlanningMetrics | undefined;\n+\tconst baseline = activeObjectiveVector(state, context, preferenceIndex);\n \tlet bestBranch: ObligationBranchReference | undefined;\n \tlet bestEvaluation: MutableTraceCandidate | undefined;\n-\tconst search = function* (\n-\t\tindex: number,\n-\t\tcurrent: State,\n-\t\tcount: number,\n-\t\tfutureScore: number,\n-\t): PlanningSteps {\n+\tconst search = function* (index: number, current: State, count: number): PlanningSteps {\n \t\tyield;\n \t\tcontext.check();\n \t\tconst maximumCount = count + matchingOccurrences.length - index;\n-\t\tif (maximumCount < bestCount) {\n+\t\tif (\n+\t\t\tmaximumCount < bestCount &&\n+\t\t\tbaseline.slice(0, preferenceIndex).every((objective) => {\n+\t\t\t\tif (objective.direction === 'minimize') return objective.value === 0;\n+\t\t\t\tconst earlier = context.rules.find(\n+\t\t\t\t\t(item) => `preference:${item.id}` === objective.id,\n+\t\t\t\t);\n+\t\t\t\treturn (\n+\t\t\t\t\tearlier &&\n+\t\t\t\t\tobjective.value ===\n+\t\t\t\t\t\t(earlier.type === 'time_window'\n+\t\t\t\t\t\t\t? earlier.placeDays\n+\t\t\t\t\t\t\t: occurrences(earlier, context).length)\n+\t\t\t\t);\n+\t\t\t})\n+\t\t) {\n \t\t\tconst comparator = `complete-occurrences:${rule.id}`;\n \t\t\trecordTraceCandidate(context, {\n \t\t\t\tstatus: 'pruned',\n@@ -3228,7 +4569,7 @@ function* preferenceIfThen(\n \t\t\treturn;\n \t\t}\n \t\tif (index >= matchingOccurrences.length) {\n-\t\t\tconst finalized = finalizeEarnedState(current, context);\n+\t\t\tconst finalized = finalizeRuleCandidate(current, context, state);\n \t\t\tif (!finalized) {\n \t\t\t\trecordTraceCandidate(context, {\n \t\t\t\t\tstatus: 'pruned',\n@@ -3240,23 +4581,20 @@ function* preferenceIfThen(\n \t\t\t\t});\n \t\t\t\treturn;\n \t\t\t}\n-\t\t\tconst metrics = qualityMetrics(finalized, context, []);\n-\t\t\tcontext.retain?.(finalized, metrics);\n-\t\t\tconst betterTie =\n-\t\t\t\tfutureScore < bestFutureScore ||\n-\t\t\t\t(futureScore === bestFutureScore &&\n-\t\t\t\t\tbestMetrics !== undefined &&\n-\t\t\t\t\t(compareMetrics(metrics, bestMetrics) < 0 ||\n-\t\t\t\t\t\t(compareMetrics(metrics, bestMetrics) === 0 &&\n-\t\t\t\t\t\t\tcompareText(placementTieKey(finalized), placementTieKey(bestState)) <\n-\t\t\t\t\t\t\t\t0)));\n-\t\t\tconst better = count > bestCount || (count === bestCount && betterTie);\n+\t\t\tif (\n+\t\t\t\tunsatisfiedObligationCount(finalized, context) ||\n+\t\t\t\tcompareObjectiveLists(\n+\t\t\t\t\tactiveObjectiveVector(finalized, context, preferenceIndex),\n+\t\t\t\t\tbaseline,\n+\t\t\t\t) > 0\n+\t\t\t)\n+\t\t\t\treturn;\n+\t\t\tcontext.retain?.(finalized);\n+\t\t\tconst better =\n+\t\t\t\tcompareObligationPreviews({ state: finalized }, { state: bestState }, context) < 0;\n \t\t\tlet branch: ObligationBranchReference | undefined;\n \t\t\tlet evaluation: MutableTraceCandidate | undefined;\n \t\t\tif (context.trace) {\n-\t\t\t\tconst beforeCount = bestCount;\n-\t\t\t\tconst beforeFutureScore = bestFutureScore;\n-\t\t\t\tconst beforeMetrics = bestMetrics;\n \t\t\t\tconst beforeState = bestState;\n \t\t\t\tconst candidateDates = () =>\n \t\t\t\t\t[...finalized.placements.values()]\n@@ -3267,16 +4605,10 @@ function* preferenceIfThen(\n \t\t\t\t\t\t)\n \t\t\t\t\t\t.map((placement) => placement.date);\n \t\t\t\tconst comparison = () =>\n-\t\t\t\t\tpreferenceIfThenComparisonFacts(\n-\t\t\t\t\t\trule.id,\n-\t\t\t\t\t\tcount,\n-\t\t\t\t\t\tfutureScore,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\tbeforeCount,\n-\t\t\t\t\t\tbeforeFutureScore,\n-\t\t\t\t\t\tbeforeMetrics,\n-\t\t\t\t\t\tfinalized,\n-\t\t\t\t\t\tbeforeState,\n+\t\t\t\t\tobligationPreviewComparisonFacts(\n+\t\t\t\t\t\t{ state: finalized },\n+\t\t\t\t\t\t{ state: beforeState },\n+\t\t\t\t\t\tcontext,\n \t\t\t\t\t);\n \t\t\t\tif (context.traceBranchActive)\n \t\t\t\t\tbranch = recordTraceBranchDecision(\n@@ -3292,22 +4624,20 @@ function* preferenceIfThen(\n \t\t\tif (better) {\n \t\t\t\tbestCount = count;\n \t\t\t\tbestState = finalized;\n-\t\t\t\tbestFutureScore = futureScore;\n-\t\t\t\tbestMetrics = metrics;\n \t\t\t\tbestBranch = branch;\n \t\t\t\tbestEvaluation = evaluation;\n \t\t\t}\n \t\t\treturn;\n \t\t}\n \t\tconst occurrence = matchingOccurrences[index];\n-\t\tconst patterns = patternsFor(rule, occurrence, context).sort(\n+\t\tconst patterns = [...patternsFor(rule, occurrence, context)].sort(\n \t\t\t(a, b) =>\n \t\t\t\tpatternConflictScore(rule.placeType, a, context) -\n \t\t\t\t\tpatternConflictScore(rule.placeType, b, context) || compareDateLists(a, b),\n \t\t);\n \t\tfor (const pattern of patterns) {\n \t\t\tyield;\n-\t\t\tconst variants = yield* assignDatesVariants(current, pattern, rule, context);\n+\t\t\tconst variants = yield* preferencePatternVariants(current, pattern, rule, context);\n \t\t\tfor (const variant of variants) {\n \t\t\t\tyield;\n \t\t\t\tconst finalized = finalizeEarnedState(\n@@ -3315,112 +4645,22 @@ function* preferenceIfThen(\n \t\t\t\t\tcontext,\n \t\t\t\t);\n \t\t\t\tif (!finalized) continue;\n-\t\t\t\tyield* search(\n-\t\t\t\t\tindex + 1,\n-\t\t\t\t\tfinalized,\n-\t\t\t\t\tcount + 1,\n-\t\t\t\t\tfutureScore + patternConflictScore(rule.placeType, pattern, context),\n-\t\t\t\t);\n-\t\t\t}\n-\t\t}\n-\t\t// A preference may leave an occurrence unplaced. Exploring this branch after\n-\t\t// complete patterns keeps the result deterministic while still maximizing the\n-\t\t// number of complete occurrences.\n-\t\tyield* search(index + 1, current, count, futureScore);\n-\t};\n-\tyield* search(0, state, 0, 0);\n-\tif (bestBranch) {\n-\t\tobserveTrace(context, (trace) => trace.chooseEvaluation(bestBranch!.candidate));\n-\t\tcontext.traceBranchParentId = bestBranch.decisionId;\n-\t} else if (!context.traceBranchActive) {\n-\t\tretainAndRecordState(context, bestState, bestEvaluation);\n-\t}\n-\treturn { state: bestState, count: bestCount };\n-}\n-\n-function preferenceIfThenComparisonFacts(\n-\truleId: string,\n-\tcount: number,\n-\tfutureScore: number,\n-\tmetrics: PlanningMetrics,\n-\tbestCount: number,\n-\tbestFutureScore: number,\n-\tbestMetrics: PlanningMetrics | undefined,\n-\tstate: State,\n-\tbestState: State,\n-): {\n-\tvalues: NonNullable;\n-\tfirstDecisiveComparator?: string;\n-} {\n-\tconst values: NonNullable[number][] = [];\n-\tconst countName = `complete-occurrences:${ruleId}`;\n-\tconst countEqual = count === bestCount;\n-\tvalues.push({ name: countName, direction: 'maximize', before: bestCount, after: count });\n-\tconst scoreName = `future-pattern-conflict-score:${ruleId}`;\n-\tconst scoreBefore = Number.isFinite(bestFutureScore) ? bestFutureScore : '∞';\n-\tvalues.push({\n-\t\tname: scoreName,\n-\t\tdirection: 'minimize',\n-\t\tbefore: scoreBefore,\n-\t\tafter: futureScore,\n-\t});\n-\tlet firstDecisiveComparator = !countEqual ? countName : undefined;\n-\tif (countEqual && futureScore !== bestFutureScore) firstDecisiveComparator = scoreName;\n-\n-\tif (futureScore === bestFutureScore && bestMetrics) {\n-\t\tconst metricComparators = [\n-\t\t\t{\n-\t\t\t\tname: 'unplaced-at-risk',\n-\t\t\t\tdirection: 'minimize' as const,\n-\t\t\t\tbefore: bestMetrics.unplacedAtRisk,\n-\t\t\t\tafter: metrics.unplacedAtRisk,\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\tname: 'holiday-week-value',\n-\t\t\t\tdirection: 'maximize' as const,\n-\t\t\t\tbefore: bestMetrics.holidayWeekValue,\n-\t\t\t\tafter: metrics.holidayWeekValue,\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\tname: 'non-working-day-gain',\n-\t\t\t\tdirection: 'maximize' as const,\n-\t\t\t\tbefore: bestMetrics.nonWorkingDayGain,\n-\t\t\t\tafter: metrics.nonWorkingDayGain,\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\tname: 'longest-work-sequence',\n-\t\t\t\tdirection: 'minimize' as const,\n-\t\t\t\tbefore: bestMetrics.longestWorkSequence,\n-\t\t\t\tafter: metrics.longestWorkSequence,\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\tname: 'short-sequence-deficit',\n-\t\t\t\tdirection: 'minimize' as const,\n-\t\t\t\tbefore: bestMetrics.shortSequenceDeficit,\n-\t\t\t\tafter: metrics.shortSequenceDeficit,\n-\t\t\t},\n-\t\t\t{\n-\t\t\t\tname: 'supporting-placements',\n-\t\t\t\tdirection: 'minimize' as const,\n-\t\t\t\tbefore: bestMetrics.supportingPlacements,\n-\t\t\t\tafter: metrics.supportingPlacements,\n-\t\t\t},\n-\t\t];\n-\t\tfor (const comparator of metricComparators) {\n-\t\t\tvalues.push(comparator);\n-\t\t\tif (comparator.before !== comparator.after) {\n-\t\t\t\tfirstDecisiveComparator ??= comparator.name;\n-\t\t\t\tbreak;\n+\t\t\t\tyield* search(index + 1, finalized, count + 1);\n \t\t\t}\n \t\t}\n-\t\tif (metricComparators.every((comparator) => comparator.before === comparator.after)) {\n-\t\t\tconst before = placementTieKey(bestState);\n-\t\t\tconst after = placementTieKey(state);\n-\t\t\tvalues.push({ name: 'placement-date', direction: 'minimize', before, after });\n-\t\t\tif (before !== after) firstDecisiveComparator ??= 'placement-date';\n-\t\t}\n+\t\t// A preference may leave an occurrence unplaced. Exploring this branch after\n+\t\t// complete patterns keeps the result deterministic while still maximizing the\n+\t\t// number of complete occurrences.\n+\t\tyield* search(index + 1, current, count);\n+\t};\n+\tyield* search(0, state, 0);\n+\tif (bestBranch) {\n+\t\tobserveTrace(context, (trace) => trace.chooseEvaluation(bestBranch!.candidate));\n+\t\tcontext.traceBranchParentId = bestBranch.decisionId;\n+\t} else if (!context.traceBranchActive) {\n+\t\tretainAndRecordState(context, bestState, bestEvaluation);\n \t}\n-\treturn { values, firstDecisiveComparator };\n+\treturn { state: bestState, count: bestCount };\n }\n \n function preferenceDateConflictScore(\n@@ -3442,89 +4682,6 @@ function preferenceDateConflictScore(\n \treturn demand ? -demand : 0;\n }\n \n-function atRiskDateSelectionFacts(\n-\tselector: LeaveSelector,\n-\tselectedDate: string,\n-\tnextDate: string,\n-\tcontext: SearchContext,\n-): Pick {\n-\tconst selectedScore = preferenceDateConflictScore(selector, selectedDate, context);\n-\tconst nextScore = preferenceDateConflictScore(selector, nextDate, context);\n-\tconst technicalComparison: NonNullable<\n-\t\tPlanningTraceCandidate['technicalComparison']\n-\t>[number][] = [\n-\t\t{\n-\t\t\tname: 'preference-date-conflict',\n-\t\t\tdirection: 'minimize',\n-\t\t\tbefore: selectedScore,\n-\t\t\tafter: nextScore,\n-\t\t},\n-\t];\n-\tif (selectedScore !== nextScore)\n-\t\treturn { technicalComparison, firstDecisiveComparator: 'preference-date-conflict' };\n-\ttechnicalComparison.push({\n-\t\tname: 'placement-date',\n-\t\tdirection: 'minimize',\n-\t\tbefore: selectedDate,\n-\t\tafter: nextDate,\n-\t});\n-\treturn { technicalComparison, firstDecisiveComparator: 'placement-date' };\n-}\n-\n-function firstCompatibleBalanceSelectionFacts(\n-\tselector: LeaveSelector,\n-\tdate: string,\n-\tfirst: InternalBalance,\n-\tsecond: InternalBalance | undefined,\n-\tcontext: SearchContext,\n-): Pick {\n-\tif (!second) return {};\n-\tconst values: NonNullable[number][] = [];\n-\tlet firstDecisiveComparator: string | undefined;\n-\tconst add = (\n-\t\tname: string,\n-\t\tdirection: 'minimize' | 'maximize',\n-\t\tbefore: number | string,\n-\t\tafter: number | string,\n-\t): boolean => {\n-\t\tvalues.push({ name, direction, before, after });\n-\t\tif (before !== after) firstDecisiveComparator ??= name;\n-\t\treturn before === after;\n-\t};\n-\tif (selector === 'any') {\n-\t\tconst sharedTypes = context.sharedTypesByDate.get(date) ?? new Set();\n-\t\tlet equal = add(\n-\t\t\t'shared-placement-type',\n-\t\t\t'maximize',\n-\t\t\tNumber(sharedTypes.has(first.type)),\n-\t\t\tNumber(sharedTypes.has(second.type)),\n-\t\t);\n-\t\tconst protectedTypes = context.protectedTypesByDate.get(date) ?? new Set();\n-\t\tif (equal && protectedTypes.size)\n-\t\t\tequal = add(\n-\t\t\t\t'protected-preference-type',\n-\t\t\t\t'maximize',\n-\t\t\t\tNumber(protectedTypes.has(first.type)),\n-\t\t\t\tNumber(protectedTypes.has(second.type)),\n-\t\t\t);\n-\t\tif (\n-\t\t\tequal &&\n-\t\t\tcontext.reservedTypes.has(first.type) !== context.reservedTypes.has(second.type)\n-\t\t)\n-\t\t\tadd(\n-\t\t\t\t'reserved-type',\n-\t\t\t\t'minimize',\n-\t\t\t\tNumber(context.reservedTypes.has(first.type)),\n-\t\t\t\tNumber(context.reservedTypes.has(second.type)),\n-\t\t\t);\n-\t}\n-\tif (!firstDecisiveComparator) {\n-\t\tconst equal = add('balance-expiry', 'minimize', first.expiryDate, second.expiryDate);\n-\t\tif (equal) add('balance-id', 'minimize', first.id, second.id);\n-\t}\n-\treturn { technicalComparison: values, firstDecisiveComparator };\n-}\n-\n function patternConflictScore(\n \tselector: LeaveSelector,\n \tpattern: string[],\n@@ -3537,7 +4694,7 @@ function patternConflictScore(\n }\n \n function preferenceReason(\n-\trule: NormalizedRule,\n+\trule: NormalizedCalendarRule,\n \tcount: number,\n \tcontext: SearchContext,\n \tstate: State,\n@@ -3584,1323 +4741,308 @@ function preferenceReason(\n \t\t\t\t\tplacement.balanceId === balance.id &&\n \t\t\t\t\t[...placement.ruleIds].some((id) => {\n \t\t\t\t\t\tconst index = context.rules.findIndex((item) => item.id === id);\n-\t\t\t\t\t\treturn index >= 0 && index < currentRuleIndex;\n+\t\t\t\t\t\treturn (\n+\t\t\t\t\t\t\tindex >= 0 &&\n+\t\t\t\t\t\t\t(context.rules[index].force === 'obligation' ||\n+\t\t\t\t\t\t\t\tindex < currentRuleIndex)\n+\t\t\t\t\t\t);\n \t\t\t\t\t}),\n \t\t\t),\n \t);\n-\tconst consumedByAtRisk = matchingBalances.some(\n-\t\t(balance) =>\n-\t\t\tbalance.remaining === 0 &&\n-\t\t\tisAtRisk(balance, context) &&\n-\t\t\t[...state.placements.values()].some(\n-\t\t\t\t(placement) => placement.balanceId === balance.id && placement.ruleIds.size === 0,\n-\t\t\t),\n-\t);\n-\tconst freeEligibleDate = candidateDates.some(\n-\t\t(date) =>\n-\t\t\t!state.placements.has(date) &&\n-\t\t\tstate.balances.some(\n-\t\t\t\t(balance) =>\n-\t\t\t\t\tbalance.remaining > 0 &&\n-\t\t\t\t\tselectorMatches(rule.placeType, balance.type) &&\n-\t\t\t\t\tcompareDate(balance.availableFrom, date) <= 0 &&\n-\t\t\t\t\tcompareDate(date, balance.expiryDate) <= 0,\n-\t\t\t),\n-\t);\n-\tconst compatibleExisting = candidateDates.some((date) => {\n-\t\tconst placement = state.placements.get(date);\n-\t\treturn placement && selectorMatches(rule.placeType, placement.type);\n-\t});\n-\tconst blockedByHigherPriority = candidateDates.some((date) => {\n-\t\tconst placement = state.placements.get(date);\n-\t\tconst sourceBalance = placement\n-\t\t\t? state.balances.find((balance) => balance.id === placement.balanceId)\n-\t\t\t: undefined;\n-\t\treturn (\n-\t\t\tplacement &&\n-\t\t\t!selectorMatches(rule.placeType, placement.type) &&\n-\t\t\t((sourceBalance ? isAtRisk(sourceBalance, context) : false) ||\n-\t\t\t\t[...placement.ruleIds].some((id) => {\n-\t\t\t\t\tconst index = context.rules.findIndex((item) => item.id === id);\n-\t\t\t\t\treturn index >= 0 && index < currentRuleIndex;\n-\t\t\t\t}))\n-\t\t);\n-\t});\n-\tlet code: string;\n-\tif (blockedByHigherPriority && !freeEligibleDate && !compatibleExisting)\n-\t\tcode = 'higher-priority';\n-\telse if (!matchingBalances.length && !compatibleExisting) code = 'type';\n-\telse if (!availableBalances.length) code = 'availability';\n-\telse if (\n-\t\t(consumedByHigherPriority || consumedByAtRisk) &&\n-\t\t!freeEligibleDate &&\n-\t\t!compatibleExisting\n-\t)\n-\t\tcode = 'higher-priority';\n-\telse code = 'capacity';\n-\treturn reason(code, `Preference \"${rule.name}\" could not be completely satisfied.`, [rule.id]);\n-}\n-\n-function* applyPreferenceRules(\n-\tstate: State,\n-\tpreferenceRules: NormalizedRule[],\n-\tcontext: SearchContext,\n-): PlanningSteps<{ state: State; preferences: PreferenceResult[] }> {\n-\tlet result = state;\n-\tconst preferences: PreferenceResult[] = [];\n-\tfor (let preferenceIndex = 0; preferenceIndex < preferenceRules.length; preferenceIndex++) {\n-\t\tyield;\n-\t\tresult = yield* applyPreferenceStep(\n-\t\t\tresult,\n-\t\t\tpreferenceRules,\n-\t\t\tpreferenceIndex,\n-\t\t\tpreferences,\n-\t\t\tcontext,\n-\t\t);\n-\t}\n-\treturn { state: result, preferences };\n-}\n-\n-function* applyPreferenceStep(\n-\tstate: State,\n-\tpreferenceRules: NormalizedRule[],\n-\tpreferenceIndex: number,\n-\tpreferences: PreferenceResult[],\n-\tcontext: SearchContext,\n-): PlanningSteps {\n-\tlet result = state;\n-\tconst applied = yield* applyPreferenceRule(\n-\t\tresult,\n-\t\tpreferenceRules[preferenceIndex],\n-\t\tpreferenceRules,\n-\t\tpreferenceIndex,\n-\t\tcontext,\n-\t);\n-\tresult = applied.state;\n-\tpreferences[preferenceIndex] = applied.preference;\n-\t// A lower-priority rule can be the producer for an entitlement needed by\n-\t// an earlier rule. Replay incomplete preferences left-to-right until no\n-\t// satisfaction improves, preserving lexicographic priority across a chain.\n-\tlet remainingImprovements = preferences\n-\t\t.slice(0, preferenceIndex + 1)\n-\t\t.reduce((total, preference) => total + preference.requested, 0);\n-\twhile (remainingImprovements > 0) {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tlet improved = false;\n-\t\tfor (let retryIndex = 0; retryIndex <= preferenceIndex; retryIndex++) {\n-\t\t\tyield;\n-\t\t\tcontext.check();\n-\t\t\tconst previous = preferences[retryIndex];\n-\t\t\tif (previous.satisfied >= previous.requested) continue;\n-\t\t\tconst retried = yield* applyPreferenceRule(\n-\t\t\t\tresult,\n-\t\t\t\tpreferenceRules[retryIndex],\n-\t\t\t\tpreferenceRules,\n-\t\t\t\tretryIndex,\n-\t\t\t\tcontext,\n-\t\t\t);\n-\t\t\tif (retried.preference.satisfied <= previous.satisfied) continue;\n-\t\t\tremainingImprovements -= retried.preference.satisfied - previous.satisfied;\n-\t\t\tresult = retried.state;\n-\t\t\tpreferences[retryIndex] = retried.preference;\n-\t\t\timproved = true;\n-\t\t}\n-\t\tif (!improved) break;\n-\t}\n-\treturn result;\n-}\n-\n-function* applyPreferenceRule(\n-\tstate: State,\n-\trule: NormalizedRule,\n-\tpreferenceRules: NormalizedRule[],\n-\tpreferenceIndex: number,\n-\tcontext: SearchContext,\n-): PlanningSteps<{ state: State; preference: PreferenceResult }> {\n-\tyield;\n-\tcontext.check();\n-\tcontext.reservedTypes = new Set(\n-\t\tpreferenceRules\n-\t\t\t.slice(preferenceIndex + 1)\n-\t\t\t.filter((rule) =>\n-\t\t\t\tbuildRequirements([rule], context, rule.force).some(\n-\t\t\t\t\t(requirement) => requirement.requiredPlacements > 0,\n-\t\t\t\t),\n-\t\t\t)\n-\t\t\t.map((item) => item.placeType)\n-\t\t\t.filter((selector): selector is LeaveType => selector !== 'any'),\n-\t);\n-\tcontext.protectedTypesByDate = futurePreferenceProtection(\n-\t\tpreferenceRules,\n-\t\tpreferenceIndex + 1,\n-\t\tcontext,\n-\t);\n-\tconst applied =\n-\t\trule.type === 'time_window'\n-\t\t\t? yield* preferenceTimeWindow(state, rule, context)\n-\t\t\t: yield* preferenceIfThen(state, rule, context);\n-\tconst requested =\n-\t\trule.type === 'time_window' ? rule.placeDays : occurrences(rule, context).length;\n-\treturn {\n-\t\tstate: applied.state,\n-\t\tpreference: {\n-\t\t\truleId: rule.id,\n-\t\t\trequested,\n-\t\t\tsatisfied: applied.count,\n-\t\t\tcompleteOccurrences: rule.type === 'if_then' ? applied.count : 0,\n-\t\t\treason: preferenceReason(rule, applied.count, context, applied.state),\n-\t\t},\n-\t};\n-}\n-\n-function placementTieKey(state: State): string {\n-\treturn [...state.placements.values()]\n-\t\t.sort((a, b) => compareDate(a.date, b.date) || compareText(a.balanceId, b.balanceId))\n-\t\t.map((placement) => `${placement.date}:${placement.balanceId}`)\n-\t\t.join('|');\n-}\n-\n-function expiryTieKey(state: State): string {\n-\treturn [...state.placements.values()]\n-\t\t.sort((a, b) => compareDate(a.date, b.date) || compareText(a.balanceId, b.balanceId))\n-\t\t.map((placement) => {\n-\t\t\tconst balance = state.balances.find((item) => item.id === placement.balanceId);\n-\t\t\treturn `${balance?.expiryDate ?? ''}:${placement.balanceId}`;\n-\t\t})\n-\t\t.join('|');\n-}\n-\n-function comparePreferenceVectors(a: readonly number[], b: readonly number[]): number {\n-\tfor (let index = 0; index < Math.max(a.length, b.length); index++) {\n-\t\tconst left = a[index] ?? 0;\n-\t\tconst right = b[index] ?? 0;\n-\t\tif (left !== right) return right - left;\n-\t}\n-\treturn 0;\n-}\n-\n-/** Compare complete previews so obligation DFS does not commit to its first feasible branch. */\n-function compareObligationPreviews(\n-\ta: { state: State; preferences: PreferenceResult[]; metrics: PlanningMetrics },\n-\tb: { state: State; preferences: PreferenceResult[]; metrics: PlanningMetrics },\n-): number {\n-\tif (a.metrics.unplacedAtRisk !== b.metrics.unplacedAtRisk)\n-\t\treturn a.metrics.unplacedAtRisk - b.metrics.unplacedAtRisk;\n-\tconst preferenceComparison = comparePreferenceVectors(\n-\t\ta.metrics.preferenceSatisfaction,\n-\t\tb.metrics.preferenceSatisfaction,\n-\t);\n-\tif (preferenceComparison) return preferenceComparison;\n-\tconst metrics = compareMetrics(\n-\t\t{ ...a.metrics, unplacedAtRisk: 0 },\n-\t\t{ ...b.metrics, unplacedAtRisk: 0 },\n-\t);\n-\tif (metrics) return metrics;\n-\tconst expiry = compareText(expiryTieKey(a.state), expiryTieKey(b.state));\n-\tif (expiry) return expiry;\n-\treturn compareText(placementTieKey(a.state), placementTieKey(b.state));\n-}\n-\n-function obligationPreviewComparisonFacts(\n-\ta: { state: State; preferences: PreferenceResult[]; metrics: PlanningMetrics },\n-\tb: { state: State; preferences: PreferenceResult[]; metrics: PlanningMetrics },\n-): {\n-\tvalues: NonNullable;\n-\tfirstDecisiveComparator?: string;\n-} {\n-\tconst values: NonNullable[number][] = [];\n-\tconst add = (\n-\t\tname: string,\n-\t\tdirection: 'minimize' | 'maximize',\n-\t\tbefore: number | string,\n-\t\tafter: number | string,\n-\t) => {\n-\t\tvalues.push({ name, direction, before, after });\n-\t\treturn before === after;\n-\t};\n-\tlet equal = add(\n-\t\t'unplaced-at-risk',\n-\t\t'minimize',\n-\t\tb.metrics.unplacedAtRisk,\n-\t\ta.metrics.unplacedAtRisk,\n-\t);\n-\tif (!equal) return { values, firstDecisiveComparator: 'unplaced-at-risk' };\n-\tfor (let index = 0; index < a.metrics.preferenceSatisfaction.length; index++) {\n-\t\tconst before = b.metrics.preferenceSatisfaction[index] ?? 0;\n-\t\tconst after = a.metrics.preferenceSatisfaction[index] ?? 0;\n-\t\tconst ruleId =\n-\t\t\ta.preferences[index]?.ruleId ?? b.preferences[index]?.ruleId ?? String(index);\n-\t\tequal = add(`preference:${ruleId}`, 'maximize', before, after);\n-\t\tif (!equal) return { values, firstDecisiveComparator: `preference:${ruleId}` };\n-\t}\n-\tconst metrics = [\n-\t\t{\n-\t\t\tname: 'holiday-week-value',\n-\t\t\tdirection: 'maximize' as const,\n-\t\t\tbefore: b.metrics.holidayWeekValue,\n-\t\t\tafter: a.metrics.holidayWeekValue,\n-\t\t},\n-\t\t{\n-\t\t\tname: 'non-working-day-gain',\n-\t\t\tdirection: 'maximize' as const,\n-\t\t\tbefore: b.metrics.nonWorkingDayGain,\n-\t\t\tafter: a.metrics.nonWorkingDayGain,\n-\t\t},\n-\t\t{\n-\t\t\tname: 'longest-work-sequence',\n-\t\t\tdirection: 'minimize' as const,\n-\t\t\tbefore: b.metrics.longestWorkSequence,\n-\t\t\tafter: a.metrics.longestWorkSequence,\n-\t\t},\n-\t\t{\n-\t\t\tname: 'short-sequence-deficit',\n-\t\t\tdirection: 'minimize' as const,\n-\t\t\tbefore: b.metrics.shortSequenceDeficit,\n-\t\t\tafter: a.metrics.shortSequenceDeficit,\n-\t\t},\n-\t\t{\n-\t\t\tname: 'supporting-placements',\n-\t\t\tdirection: 'minimize' as const,\n-\t\t\tbefore: b.metrics.supportingPlacements,\n-\t\t\tafter: a.metrics.supportingPlacements,\n-\t\t},\n-\t];\n-\tfor (const metric of metrics) {\n-\t\tequal = add(metric.name, metric.direction, metric.before, metric.after);\n-\t\tif (!equal) return { values, firstDecisiveComparator: metric.name };\n-\t}\n-\tconst beforeExpiry = expiryTieKey(b.state);\n-\tconst afterExpiry = expiryTieKey(a.state);\n-\tequal = add('balance-expiry', 'minimize', beforeExpiry, afterExpiry);\n-\tif (!equal) return { values, firstDecisiveComparator: 'balance-expiry' };\n-\tconst beforeDates = placementTieKey(b.state);\n-\tconst afterDates = placementTieKey(a.state);\n-\tequal = add('placement-date', 'minimize', beforeDates, afterDates);\n-\treturn { values, firstDecisiveComparator: equal ? undefined : 'placement-date' };\n-}\n-\n-type QualityTraceDetails = Pick<\n-\tPlanningTraceCandidate,\n-\t'technicalComparison' | 'firstDecisiveComparator' | 'reason'\n->;\n-\n-type QualityTraceComparator = NonNullable[number];\n-\n-function addQualityComparator(\n-\tvalues: QualityTraceComparator[],\n-\tname: string,\n-\tdirection: QualityTraceComparator['direction'],\n-\tbefore: number | string,\n-\tafter: number | string,\n-): boolean {\n-\tvalues.push({ name, direction, before, after });\n-\treturn before === after;\n-}\n-\n-function recordTraceIncumbentBound(\n-\tcontext: SearchContext,\n-\tincumbentMetrics: PlanningMetrics,\n-\tunplacedAtRisk: number,\n-\tpreferences: readonly PreferenceResult[] = [],\n-): void {\n-\tobserveTrace(context, (trace) => {\n-\t\tconst values: QualityTraceComparator[] = [];\n-\t\tlet equal = addQualityComparator(\n-\t\t\tvalues,\n-\t\t\t'unplaced-at-risk',\n-\t\t\t'minimize',\n-\t\t\tincumbentMetrics.unplacedAtRisk,\n-\t\t\tunplacedAtRisk,\n-\t\t);\n-\t\tfor (let index = 0; equal && index < preferences.length; index++) {\n-\t\t\tconst preference = preferences[index];\n-\t\t\tequal = addQualityComparator(\n-\t\t\t\tvalues,\n-\t\t\t\t`preference:${preference.ruleId}`,\n-\t\t\t\t'maximize',\n-\t\t\t\tincumbentMetrics.preferenceSatisfaction[index] ?? 0,\n-\t\t\t\tpreference.satisfied,\n-\t\t\t);\n-\t\t}\n-\t\ttrace.recordCandidate(\n-\t\t\t{\n-\t\t\t\tstatus: 'pruned',\n-\t\t\t\ttechnicalComparison: values,\n-\t\t\t\tfirstDecisiveComparator: values[values.length - 1].name,\n-\t\t\t\treason: reason(\n-\t\t\t\t\t'incumbent-bound',\n-\t\t\t\t\t'This state cannot improve the incumbent on the first differing planning objective.',\n-\t\t\t\t),\n-\t\t\t},\n-\t\t\tfalse,\n-\t\t);\n-\t});\n-}\n-\n-function movableProtectionTraceDetails(\n-\tbaseline: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tpreferences: readonly PreferenceResult[],\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst reject = (name: string, message: string): QualityTraceDetails => ({\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: name,\n-\t\treason: reason('quality-protected-objective', message),\n-\t});\n-\tconst atRiskEqual = addQualityComparator(\n-\t\tvalues,\n-\t\t'protected:unplaced-at-risk',\n-\t\t'minimize',\n-\t\tbaseline.unplacedAtRisk,\n-\t\tcandidate.unplacedAtRisk,\n-\t);\n-\tif (!atRiskEqual)\n-\t\treturn reject(\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'This move changes the amount of unplaced at-risk leave protected by the quality pass.',\n-\t\t);\n-\taddQualityComparator(\n-\t\tvalues,\n-\t\t'protected:holiday-week-value',\n-\t\t'maximize',\n-\t\tbaseline.holidayWeekValue,\n-\t\tcandidate.holidayWeekValue,\n-\t);\n-\tif (candidate.holidayWeekValue < baseline.holidayWeekValue)\n-\t\treturn reject(\n-\t\t\t'protected:holiday-week-value',\n-\t\t\t'This move reduces public-holiday week value protected by the quality pass.',\n-\t\t);\n-\tif (candidate.preferenceSatisfaction.length !== baseline.preferenceSatisfaction.length) {\n-\t\tconst name = 'protected:preference-count';\n-\t\taddQualityComparator(\n-\t\t\tvalues,\n-\t\t\tname,\n-\t\t\t'maximize',\n-\t\t\tbaseline.preferenceSatisfaction.length,\n-\t\t\tcandidate.preferenceSatisfaction.length,\n-\t\t);\n-\t\treturn reject(\n-\t\t\tname,\n-\t\t\t'This move changes the preference result protected by the quality pass.',\n-\t\t);\n-\t}\n-\tfor (let index = 0; index < baseline.preferenceSatisfaction.length; index++) {\n-\t\tconst name = `protected:preference:${preferences[index]?.ruleId ?? index}`;\n-\t\tconst before = baseline.preferenceSatisfaction[index];\n-\t\tconst after = candidate.preferenceSatisfaction[index];\n-\t\tif (!addQualityComparator(values, name, 'maximize', before, after))\n-\t\t\treturn reject(\n-\t\t\t\tname,\n-\t\t\t\t'This move changes a preference result protected by the quality pass.',\n-\t\t\t);\n-\t}\n-\treturn { technicalComparison: values };\n-}\n-\n-function movableIncumbentTraceDetails(\n-\tstage: 'non-working-day-gain' | 'longest-work-sequence' | 'short-sequence-deficit' | 'dates',\n-\tincumbent: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tincumbentDate: string,\n-\tcandidateDate: string,\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst add = (\n-\t\tname: string,\n-\t\tdirection: QualityTraceComparator['direction'],\n-\t\tbefore: number | string,\n-\t\tafter: number | string,\n-\t) => addQualityComparator(values, name, direction, before, after);\n-\tconst finishIfDifferent = (name: string, equal: boolean): QualityTraceDetails | undefined =>\n-\t\tequal ? undefined : { technicalComparison: values, firstDecisiveComparator: name };\n-\n-\tlet equal = add(\n-\t\t'holiday-week-value',\n-\t\t'maximize',\n-\t\tincumbent.holidayWeekValue,\n-\t\tcandidate.holidayWeekValue,\n-\t);\n-\tlet decisive = finishIfDifferent('holiday-week-value', equal);\n-\tif (decisive) return decisive;\n-\tif (stage === 'non-working-day-gain') {\n-\t\tequal = add(\n-\t\t\t'non-working-day-gain',\n-\t\t\t'maximize',\n-\t\t\tincumbent.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain,\n-\t\t);\n-\t\treturn finishIfDifferent('non-working-day-gain', equal) ?? { technicalComparison: values };\n-\t}\n-\tequal = add(\n-\t\t'non-working-day-gain',\n-\t\t'maximize',\n-\t\tincumbent.nonWorkingDayGain,\n-\t\tcandidate.nonWorkingDayGain,\n-\t);\n-\tdecisive = finishIfDifferent('non-working-day-gain', equal);\n-\tif (decisive) return decisive;\n-\tif (stage === 'longest-work-sequence') {\n-\t\tequal = add(\n-\t\t\t'longest-work-sequence',\n-\t\t\t'minimize',\n-\t\t\tincumbent.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence,\n-\t\t);\n-\t\treturn finishIfDifferent('longest-work-sequence', equal) ?? { technicalComparison: values };\n-\t}\n-\tequal = add(\n-\t\t'longest-work-sequence',\n-\t\t'minimize',\n-\t\tincumbent.longestWorkSequence,\n-\t\tcandidate.longestWorkSequence,\n-\t);\n-\tdecisive = finishIfDifferent('longest-work-sequence', equal);\n-\tif (decisive) return decisive;\n-\tif (stage === 'short-sequence-deficit') {\n-\t\tequal = add(\n-\t\t\t'short-sequence-deficit',\n-\t\t\t'minimize',\n-\t\t\tincumbent.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit,\n-\t\t);\n-\t\treturn (\n-\t\t\tfinishIfDifferent('short-sequence-deficit', equal) ?? { technicalComparison: values }\n-\t\t);\n-\t}\n-\tequal = add(\n-\t\t'short-sequence-deficit',\n-\t\t'minimize',\n-\t\tincumbent.shortSequenceDeficit,\n-\t\tcandidate.shortSequenceDeficit,\n-\t);\n-\tdecisive = finishIfDifferent('short-sequence-deficit', equal);\n-\tif (decisive) return decisive;\n-\tif (stage === 'dates') {\n-\t\tconst dateEqual = add('placement-date', 'minimize', incumbentDate, candidateDate);\n-\t\treturn finishIfDifferent('placement-date', dateEqual) ?? { technicalComparison: values };\n-\t}\n-\treturn { technicalComparison: values };\n-}\n-\n-function recordTraceDecision(context: SearchContext, dates: readonly string[]): void {\n-\tobserveTrace(context, (trace) => trace.recordDecision('choose', dates));\n-}\n-\n-function updateTraceEvaluationReason(\n-\tcontext: SearchContext,\n-\tevaluation: MutableTraceCandidate | undefined,\n-\tevaluationReason: PlanningReason,\n-): void {\n-\tif (!evaluation) return;\n-\tobserveTrace(context, (trace) => {\n-\t\tevaluation.reason = evaluationReason;\n-\t\ttrace.updateEvaluation(evaluation);\n-\t});\n-}\n-\n-function retainAndRecordEvaluation(\n-\tcontext: SearchContext,\n-\tbeforeState: State,\n-\tafterState: State,\n-\tpreferences: readonly PreferenceResult[],\n-\tbeforeMetrics: PlanningMetrics,\n-\tafterMetrics: PlanningMetrics,\n-\tdates: readonly string[],\n-\tsourceDate?: string,\n-\tqualityDetails?: () => QualityTraceDetails,\n-): MutableTraceCandidate | undefined {\n-\tlet evaluation: MutableTraceCandidate | undefined;\n-\tobserveTrace(context, (trace) => {\n-\t\tconst date = dates[dates.length - 1];\n-\t\tconst placement = date ? afterState.placements.get(date) : undefined;\n-\t\tconst details = qualityDetails?.();\n-\t\tevaluation = {\n-\t\t\tstatus: 'evaluated-rejected',\n-\t\t\tsourceDate,\n-\t\t\tdate,\n-\t\t\tdates: [...dates],\n-\t\t\treason: details?.reason,\n-\t\t\tcomparison: objectiveComparison(\n-\t\t\t\tobjectiveVector(beforeMetrics, preferences, beforeState, context),\n-\t\t\t\tobjectiveVector(afterMetrics, preferences, afterState, context),\n-\t\t\t),\n-\t\t\ttechnicalComparison: details?.technicalComparison,\n-\t\t\tfirstDecisiveComparator: details?.firstDecisiveComparator,\n-\t\t\tplacement: placement\n-\t\t\t\t? { ...placement, ruleIds: [...placement.ruleIds].sort() }\n-\t\t\t\t: undefined,\n-\t\t};\n-\t\ttrace.recordEvaluation(evaluation);\n-\t});\n-\tcontext.retain?.(afterState, afterMetrics);\n-\treturn context.trace ? evaluation : undefined;\n-}\n-\n-function holidayWeekProtectionTraceDetails(\n-\tbaseline: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tpreferences: readonly PreferenceResult[],\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst reject = (name: string, message: string): QualityTraceDetails => ({\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: name,\n-\t\treason: reason('quality-protected-objective', message),\n-\t});\n-\taddQualityComparator(\n-\t\tvalues,\n-\t\t'protected:unplaced-at-risk',\n-\t\t'minimize',\n-\t\tbaseline.unplacedAtRisk,\n-\t\tcandidate.unplacedAtRisk,\n-\t);\n-\tif (candidate.unplacedAtRisk > baseline.unplacedAtRisk)\n-\t\treturn reject(\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'This completion leaves more at-risk leave unplaced.',\n-\t\t);\n-\tfor (\n-\t\tlet index = 0;\n-\t\tindex <\n-\t\tMath.max(baseline.preferenceSatisfaction.length, candidate.preferenceSatisfaction.length);\n-\t\tindex++\n-\t) {\n-\t\tconst name = `protected:preference:${preferences[index]?.ruleId ?? index}`;\n-\t\tconst before = baseline.preferenceSatisfaction[index] ?? 0;\n-\t\tconst after = candidate.preferenceSatisfaction[index] ?? 0;\n-\t\tif (!addQualityComparator(values, name, 'maximize', before, after))\n-\t\t\treturn reject(name, 'This completion changes a higher-priority preference result.');\n-\t}\n-\taddQualityComparator(\n-\t\tvalues,\n-\t\t'protected:holiday-week-value',\n-\t\t'maximize',\n-\t\tbaseline.holidayWeekValue,\n-\t\tcandidate.holidayWeekValue,\n+\tconst freeEligibleDate = candidateDates.some(\n+\t\t(date) =>\n+\t\t\t!state.placements.has(date) &&\n+\t\t\tstate.balances.some(\n+\t\t\t\t(balance) =>\n+\t\t\t\t\tbalance.remaining > 0 &&\n+\t\t\t\t\tselectorMatches(rule.placeType, balance.type) &&\n+\t\t\t\t\tcompareDate(balance.availableFrom, date) <= 0 &&\n+\t\t\t\t\tcompareDate(date, balance.expiryDate) <= 0,\n+\t\t\t),\n \t);\n-\tif (candidate.holidayWeekValue <= baseline.holidayWeekValue)\n-\t\treturn reject(\n-\t\t\t'protected:holiday-week-value',\n-\t\t\t'This completion does not increase public-holiday week value.',\n+\tconst compatibleExisting = candidateDates.some((date) => {\n+\t\tconst placement = state.placements.get(date);\n+\t\treturn placement && selectorMatches(rule.placeType, placement.type);\n+\t});\n+\tconst blockedByHigherPriority = candidateDates.some((date) => {\n+\t\tconst placement = state.placements.get(date);\n+\t\treturn (\n+\t\t\tplacement &&\n+\t\t\t!selectorMatches(rule.placeType, placement.type) &&\n+\t\t\t[...placement.ruleIds].some((id) => {\n+\t\t\t\tconst index = context.rules.findIndex((item) => item.id === id);\n+\t\t\t\treturn (\n+\t\t\t\t\tindex >= 0 &&\n+\t\t\t\t\t(context.rules[index].force === 'obligation' || index < currentRuleIndex)\n+\t\t\t\t);\n+\t\t\t})\n \t\t);\n-\treturn { technicalComparison: values };\n+\t});\n+\tlet code: string;\n+\tif (blockedByHigherPriority && !freeEligibleDate && !compatibleExisting)\n+\t\tcode = 'higher-priority';\n+\telse if (!matchingBalances.length && !compatibleExisting) code = 'type';\n+\telse if (!availableBalances.length) code = 'availability';\n+\telse if (consumedByHigherPriority && !freeEligibleDate && !compatibleExisting)\n+\t\tcode = 'higher-priority';\n+\telse code = 'capacity';\n+\treturn reason(code, `Preference \"${rule.name}\" could not be completely satisfied.`, [rule.id]);\n }\n \n-function qualityMetricTraceDetails(\n-\tincumbent: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst comparators = [\n-\t\t['unplaced-at-risk', 'minimize', incumbent.unplacedAtRisk, candidate.unplacedAtRisk],\n-\t\t['holiday-week-value', 'maximize', incumbent.holidayWeekValue, candidate.holidayWeekValue],\n-\t\t[\n-\t\t\t'non-working-day-gain',\n-\t\t\t'maximize',\n-\t\t\tincumbent.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain,\n-\t\t],\n-\t\t[\n-\t\t\t'longest-work-sequence',\n-\t\t\t'minimize',\n-\t\t\tincumbent.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence,\n-\t\t],\n-\t\t[\n-\t\t\t'short-sequence-deficit',\n-\t\t\t'minimize',\n-\t\t\tincumbent.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit,\n-\t\t],\n-\t\t[\n-\t\t\t'supporting-placements',\n-\t\t\t'minimize',\n-\t\t\tincumbent.supportingPlacements,\n-\t\t\tcandidate.supportingPlacements,\n-\t\t],\n-\t] as const;\n-\tfor (const [name, direction, before, after] of comparators) {\n-\t\tif (!addQualityComparator(values, name, direction, before, after))\n-\t\t\treturn { technicalComparison: values, firstDecisiveComparator: name };\n+function* applyPreferenceRules(\n+\tstate: State,\n+\tpreferenceRules: NormalizedRule[],\n+\tcontext: SearchContext,\n+): PlanningSteps<{ state: State; preferences: PreferenceResult[] }> {\n+\tlet result = state;\n+\tconst preferences: PreferenceResult[] = [];\n+\tfor (let preferenceIndex = 0; preferenceIndex < preferenceRules.length; preferenceIndex++) {\n+\t\tyield;\n+\t\tresult = yield* applyPreferenceStep(\n+\t\t\tresult,\n+\t\t\tpreferenceRules,\n+\t\t\tpreferenceIndex,\n+\t\t\tpreferences,\n+\t\t\tcontext,\n+\t\t);\n \t}\n-\treturn { technicalComparison: values };\n-}\n-\n-function qualityMetricTieTraceDetails(\n-\tincumbent: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tincumbentState: State,\n-\tcandidateState: State,\n-): QualityTraceDetails {\n-\tconst comparison = qualityMetricTraceDetails(incumbent, candidate);\n-\tif (comparison.firstDecisiveComparator) return comparison;\n-\tconst values = [...(comparison.technicalComparison ?? [])];\n-\tconst equal = addQualityComparator(\n-\t\tvalues,\n-\t\t'placement-date',\n-\t\t'minimize',\n-\t\tplacementTieKey(incumbentState),\n-\t\tplacementTieKey(candidateState),\n-\t);\n-\treturn {\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: equal ? undefined : 'placement-date',\n-\t};\n+\treturn { state: result, preferences };\n }\n \n-function* optimizeMovablePlacements(\n+function* applyPreferenceStep(\n \tstate: State,\n-\tcontext: SearchContext,\n+\tpreferenceRules: NormalizedRule[],\n+\tpreferenceIndex: number,\n \tpreferences: PreferenceResult[],\n-\tstage: 'non-working-day-gain' | 'longest-work-sequence' | 'short-sequence-deficit' | 'dates',\n+\tcontext: SearchContext,\n ): PlanningSteps {\n \tlet result = state;\n-\t// Small plans are common and can be searched exhaustively. Keep the fixed\n-\t// sparse calendar candidates for loaded years so quality work stays within\n-\t// the mobile budget without making ordinary scenarios depend on sampling.\n-\t// ponytail: loaded plans sample non-working-adjacent and weekly dates; upgrade\n-\t// to interval branch-and-bound if a mobile benchmark shows a missed quality tie.\n-\tconst exhaustive = result.placements.size <= 24;\n-\tconst movableWindowDates = new Set(\n-\t\t[...result.placements.values()]\n-\t\t\t.filter((placement) => isMovableTimeWindow(placement, context))\n-\t\t\t.flatMap((placement) =>\n-\t\t\t\t[...placement.ruleIds]\n-\t\t\t\t\t.map((id) => context.rules.find((rule) => rule.id === id))\n-\t\t\t\t\t.filter(\n-\t\t\t\t\t\t(\n-\t\t\t\t\t\t\trule,\n-\t\t\t\t\t\t): rule is NormalizedRule & {\n-\t\t\t\t\t\t\ttype: 'time_window';\n-\t\t\t\t\t\t\tstartDate: string;\n-\t\t\t\t\t\t\tendDate: string;\n-\t\t\t\t\t\t} => rule?.type === 'time_window',\n-\t\t\t\t\t)\n-\t\t\t\t\t.flatMap((rule) =>\n-\t\t\t\t\t\tcontext.workingDays.filter(\n-\t\t\t\t\t\t\t(date) =>\n-\t\t\t\t\t\t\t\tcompareDate(date, rule.startDate) >= 0 &&\n-\t\t\t\t\t\t\t\tcompareDate(date, rule.endDate) <= 0,\n-\t\t\t\t\t\t),\n-\t\t\t\t\t),\n-\t\t\t),\n-\t);\n-\tconst candidateDates = context.workingDays.filter((date, index) => {\n-\t\tif (exhaustive) return true;\n-\t\tconst touchesNonWorking =\n-\t\t\t!isWorking(addDays(date, -1), context.holidays) ||\n-\t\t\t!isWorking(addDays(date, 1), context.holidays) ||\n-\t\t\tcontext.declaredDates.has(addDays(date, -1)) ||\n-\t\t\tcontext.declaredDates.has(addDays(date, 1));\n-\t\treturn touchesNonWorking || index % 7 === 0;\n-\t});\n-\tif (!exhaustive) {\n-\t\tconst sampled = new Set(candidateDates);\n-\t\tfor (const date of context.workingDays) {\n-\t\t\tyield;\n-\t\t\tif (sampled.has(date)) continue;\n+\tconst apply = function* (index: number): PlanningSteps {\n+\t\tconst rule = preferenceRules[index];\n+\t\tcontext.protectedTypesByDate = futurePreferenceProtection(\n+\t\t\tpreferenceRules,\n+\t\t\tindex + 1,\n+\t\t\tcontext,\n+\t\t);\n+\t\tif (context.completedPreferenceStates.get(index) === preferenceStateKey(result)) {\n \t\t\trecordTraceCandidate(context, {\n \t\t\t\tstatus: 'not-examined',\n-\t\t\t\tdate,\n \t\t\t\treason: reason(\n-\t\t\t\t\t'loaded-plan-sampling',\n-\t\t\t\t\t'This date was not examined because of loaded-plan quality sampling.',\n+\t\t\t\t\t'unchanged-rule-state',\n+\t\t\t\t\t`Rule \"${rule.name}\" already evaluated this unchanged state; its earlier decisions apply.`,\n+\t\t\t\t\t[rule.id],\n \t\t\t\t),\n \t\t\t});\n+\t\t\treturn;\n \t\t}\n-\t}\n-\tfor (const original of [...result.placements.values()]\n-\t\t.filter(\n-\t\t\t(placement) => placement.ruleIds.size === 0 || isMovableTimeWindow(placement, context),\n-\t\t)\n-\t\t.sort((a, b) => compareDate(a.date, b.date) || compareText(a.balanceId, b.balanceId))) {\n-\t\tyield;\n-\t\tconst current = result.placements.get(original.date);\n-\t\tif (!current || (current.ruleIds.size > 0 && !isMovableTimeWindow(current, context)))\n-\t\t\tcontinue;\n-\t\tconst balance = result.balances.find((item) => item.id === current.balanceId);\n-\t\tif (\n-\t\t\t!balance ||\n-\t\t\t(!current.ruleIds.size && !isAtRisk(balance, context) && !current.supporting)\n-\t\t)\n-\t\t\tcontinue;\n-\t\trecordTraceDecision(context, [original.date]);\n-\t\tconst baseline = qualityMetrics(result, context, preferences);\n-\t\tconst without = cloneState(result);\n-\t\twithout.placements.delete(original.date);\n-\t\twithout.balances.find((item) => item.id === current.balanceId)!.remaining++;\n-\t\tlet best = result;\n-\t\tlet bestMetrics = baseline;\n-\t\tlet bestDate = original.date;\n-\t\tlet bestEvaluation: MutableTraceCandidate | undefined;\n-\t\tconst placementCandidates =\n-\t\t\tcurrent.ruleIds.size > 0\n-\t\t\t\t? context.workingDays.filter((date) => movableWindowDates.has(date))\n-\t\t\t\t: candidateDates;\n-\t\tfor (const date of placementCandidates) {\n-\t\t\tyield;\n-\t\t\tif (date === original.date) continue;\n-\t\t\tif (!compatibleWithRules(date, current.type, current.ruleIds, context)) {\n-\t\t\t\trecordTraceIneligible(\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tdate,\n-\t\t\t\t\t'rule-invalid',\n-\t\t\t\t\t'The date does not preserve the placement rules.',\n-\t\t\t\t\t[...current.ruleIds],\n-\t\t\t\t);\n-\t\t\t\tcontinue;\n-\t\t\t}\n-\t\t\tif (\n-\t\t\t\t!assignDateToBalanceInPlace(\n-\t\t\t\t\twithout,\n-\t\t\t\t\tdate,\n-\t\t\t\t\tcurrent.balanceId,\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tcurrent.ruleIds,\n-\t\t\t\t)\n-\t\t\t)\n-\t\t\t\tcontinue;\n-\t\t\ttry {\n-\t\t\t\tconst feasibleCandidate = finalizeEarnedState(without, context);\n-\t\t\t\tif (!feasibleCandidate) continue;\n-\t\t\t\tfeasibleCandidate.placements.get(date)!.supporting = current.supporting;\n-\t\t\t\tconst metrics = qualityMetrics(feasibleCandidate, context, preferences);\n-\t\t\t\tif (metrics.unplacedAtRisk !== baseline.unplacedAtRisk) {\n-\t\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tresult,\n-\t\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t[date],\n-\t\t\t\t\t\tcurrent.date,\n-\t\t\t\t\t\t() => movableProtectionTraceDetails(baseline, metrics, preferences),\n-\t\t\t\t\t);\n-\t\t\t\t\tcontinue;\n-\t\t\t\t}\n-\t\t\t\tif (metrics.holidayWeekValue < baseline.holidayWeekValue) {\n-\t\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tresult,\n-\t\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t[date],\n-\t\t\t\t\t\tcurrent.date,\n-\t\t\t\t\t\t() => movableProtectionTraceDetails(baseline, metrics, preferences),\n-\t\t\t\t\t);\n-\t\t\t\t\tcontinue;\n-\t\t\t\t}\n-\t\t\t\tif (\n-\t\t\t\t\tmetrics.preferenceSatisfaction.length !==\n-\t\t\t\t\t\tbaseline.preferenceSatisfaction.length ||\n-\t\t\t\t\tmetrics.preferenceSatisfaction.some(\n-\t\t\t\t\t\t(value, index) => value !== baseline.preferenceSatisfaction[index],\n-\t\t\t\t\t)\n-\t\t\t\t) {\n-\t\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tresult,\n-\t\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t[date],\n-\t\t\t\t\t\tcurrent.date,\n-\t\t\t\t\t\t() => movableProtectionTraceDetails(baseline, metrics, preferences),\n-\t\t\t\t\t);\n-\t\t\t\t\tcontinue;\n-\t\t\t\t}\n-\t\t\t\tconst better =\n-\t\t\t\t\tmetrics.holidayWeekValue > bestMetrics.holidayWeekValue ||\n-\t\t\t\t\t(metrics.holidayWeekValue === bestMetrics.holidayWeekValue &&\n-\t\t\t\t\t\t(stage === 'non-working-day-gain'\n-\t\t\t\t\t\t\t? metrics.nonWorkingDayGain > bestMetrics.nonWorkingDayGain\n-\t\t\t\t\t\t\t: stage === 'longest-work-sequence'\n-\t\t\t\t\t\t\t\t? metrics.nonWorkingDayGain === bestMetrics.nonWorkingDayGain &&\n-\t\t\t\t\t\t\t\t\tmetrics.longestWorkSequence < bestMetrics.longestWorkSequence\n-\t\t\t\t\t\t\t\t: stage === 'short-sequence-deficit'\n-\t\t\t\t\t\t\t\t\t? metrics.nonWorkingDayGain === bestMetrics.nonWorkingDayGain &&\n-\t\t\t\t\t\t\t\t\t\tmetrics.longestWorkSequence ===\n-\t\t\t\t\t\t\t\t\t\t\tbestMetrics.longestWorkSequence &&\n-\t\t\t\t\t\t\t\t\t\tmetrics.shortSequenceDeficit <\n-\t\t\t\t\t\t\t\t\t\t\tbestMetrics.shortSequenceDeficit\n-\t\t\t\t\t\t\t\t\t: metrics.nonWorkingDayGain === bestMetrics.nonWorkingDayGain &&\n-\t\t\t\t\t\t\t\t\t\tmetrics.longestWorkSequence ===\n-\t\t\t\t\t\t\t\t\t\t\tbestMetrics.longestWorkSequence &&\n-\t\t\t\t\t\t\t\t\t\tmetrics.shortSequenceDeficit ===\n-\t\t\t\t\t\t\t\t\t\t\tbestMetrics.shortSequenceDeficit &&\n-\t\t\t\t\t\t\t\t\t\tdate < bestDate));\n-\t\t\t\tconst evaluation = retainAndRecordEvaluation(\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tresult,\n-\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\tpreferences,\n-\t\t\t\t\tbaseline,\n-\t\t\t\t\tmetrics,\n-\t\t\t\t\t[date],\n-\t\t\t\t\tcurrent.date,\n-\t\t\t\t\t() => {\n-\t\t\t\t\t\tconst protectedDetails = movableProtectionTraceDetails(\n-\t\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\t);\n-\t\t\t\t\t\tconst incumbentDetails = movableIncumbentTraceDetails(\n-\t\t\t\t\t\t\tstage,\n-\t\t\t\t\t\t\tbestMetrics,\n-\t\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t\tbestDate,\n-\t\t\t\t\t\t\tdate,\n-\t\t\t\t\t\t);\n-\t\t\t\t\t\treturn {\n-\t\t\t\t\t\t\ttechnicalComparison: [\n-\t\t\t\t\t\t\t\t...(protectedDetails.technicalComparison ?? []),\n-\t\t\t\t\t\t\t\t...(incumbentDetails.technicalComparison ?? []),\n-\t\t\t\t\t\t\t],\n-\t\t\t\t\t\t\tfirstDecisiveComparator:\n-\t\t\t\t\t\t\t\tprotectedDetails.reason?.code === 'quality-protected-objective'\n-\t\t\t\t\t\t\t\t\t? protectedDetails.firstDecisiveComparator\n-\t\t\t\t\t\t\t\t\t: incumbentDetails.firstDecisiveComparator,\n-\t\t\t\t\t\t\treason: better\n-\t\t\t\t\t\t\t\t? undefined\n-\t\t\t\t\t\t\t\t: reason(\n-\t\t\t\t\t\t\t\t\t\t'quality-no-improvement',\n-\t\t\t\t\t\t\t\t\t\t`This candidate did not improve the current best result in the ${stage} pass.`,\n-\t\t\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t};\n-\t\t\t\t\t},\n-\t\t\t\t);\n-\t\t\t\tif (better) {\n-\t\t\t\t\tif (bestEvaluation)\n-\t\t\t\t\t\tupdateTraceEvaluationReason(\n-\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\tbestEvaluation,\n-\t\t\t\t\t\t\treason(\n-\t\t\t\t\t\t\t\t'quality-outperformed',\n-\t\t\t\t\t\t\t\t'A later candidate became the best result in this pass.',\n-\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t);\n-\t\t\t\t\tbest = cloneState(feasibleCandidate);\n-\t\t\t\t\tbestMetrics = metrics;\n-\t\t\t\t\tbestDate = date;\n-\t\t\t\t\tbestEvaluation = evaluation;\n-\t\t\t\t}\n-\t\t\t} finally {\n-\t\t\t\twithout.placements.delete(date);\n-\t\t\t\twithout.balances.find((item) => item.id === current.balanceId)!.remaining++;\n-\t\t\t}\n-\t\t}\n-\t\tif (best !== result) retainAndRecordState(context, best, bestEvaluation);\n-\t\tresult = best;\n-\t}\n-\treturn result;\n-}\n-\n-// ponytail: regroup only flexible placements and time-window rules; add wider\n-// rule reshaping only if a real plan needs coordinated if-then moves.\n-function* completeHolidayWeek(\n-\tstate: State,\n-\tcandidate: HolidayWeekCandidate,\n-\tcontext: SearchContext,\n-\tprotectedDates: Set,\n-): PlanningSteps {\n-\tconst targetDates = new Set(candidate.dates);\n-\tconst missing = candidate.dates.filter(\n-\t\t(date) => !state.placements.has(date) && !context.declaredDates.has(date),\n-\t);\n-\tif (!missing.length) return state;\n-\tconst canMove = (placement: InternalPlacement, current: State): boolean => {\n-\t\tconst balance = current.balances.find((item) => item.id === placement.balanceId);\n-\t\treturn (\n-\t\t\t!placement.supporting &&\n-\t\t\t!targetDates.has(placement.date) &&\n-\t\t\t!protectedDates.has(placement.date) &&\n-\t\t\t!!balance &&\n-\t\t\t(placement.ruleIds.size\n-\t\t\t\t? isMovableTimeWindow(placement, context)\n-\t\t\t\t: isAtRisk(balance, context))\n-\t\t);\n-\t};\n-\tconst search = function* (index: number, current: State): PlanningSteps {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tif (index >= missing.length) return finalizeEarnedState(current, context);\n-\t\tconst date = missing[index];\n-\t\tconst movable = [...current.placements.values()]\n-\t\t\t.filter((placement) => canMove(placement, current))\n-\t\t\t.sort(\n-\t\t\t\t(a, b) =>\n-\t\t\t\t\tcompareDate(\n-\t\t\t\t\t\tcurrent.balances.find((item) => item.id === a.balanceId)!.expiryDate,\n-\t\t\t\t\t\tcurrent.balances.find((item) => item.id === b.balanceId)!.expiryDate,\n-\t\t\t\t\t) ||\n-\t\t\t\t\tcompareText(a.balanceId, b.balanceId) ||\n-\t\t\t\t\tcompareDate(a.date, b.date),\n+\t\tif (rule.type === 'optimization')\n+\t\t\tresult = yield* optimizeRulePlacements(result, context, index, true, rule);\n+\t\telse if (rule.type === 'time_window')\n+\t\t\tresult = associateCalendarPreference(\n+\t\t\t\tyield* optimizeRulePlacements(result, context, index, true, rule),\n+\t\t\t\trule,\n+\t\t\t\tcontext,\n \t\t\t);\n-\t\tfor (const source of movable) {\n-\t\t\tyield;\n-\t\t\tif (!compatibleWithRules(date, source.type, source.ruleIds, context)) {\n-\t\t\t\trecordTraceIneligible(\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tdate,\n-\t\t\t\t\t'rule-invalid',\n-\t\t\t\t\t'The date does not preserve the placement rules.',\n-\t\t\t\t\t[...source.ruleIds],\n-\t\t\t\t);\n-\t\t\t\tcontinue;\n-\t\t\t}\n-\t\t\tconst moved = cloneState(current);\n-\t\t\tmoved.placements.delete(source.date);\n-\t\t\tconst released = moved.balances.find((item) => item.id === source.balanceId);\n-\t\t\tif (!released) continue;\n-\t\t\treleased.remaining++;\n-\t\t\tconst reassigned = assignDateToBalance(\n-\t\t\t\tmoved,\n-\t\t\t\tdate,\n-\t\t\t\tsource.balanceId,\n+\t\telse\n+\t\t\tresult = associateCalendarPreference(\n+\t\t\t\t(yield* preferenceIfThen(result, rule, context, index)).state,\n+\t\t\t\trule,\n \t\t\t\tcontext,\n-\t\t\t\tsource.ruleIds,\n \t\t\t);\n-\t\t\tif (!reassigned) continue;\n-\t\t\tconst complete = yield* search(index + 1, reassigned);\n-\t\t\tif (complete) return complete;\n-\t\t}\n-\t\tfor (const balance of current.balances\n-\t\t\t.filter((item) => item.remaining > 0)\n-\t\t\t.sort((a, b) => compareDate(a.expiryDate, b.expiryDate) || compareText(a.id, b.id))) {\n-\t\t\tyield;\n-\t\t\tconst assigned = assignDateToBalance(current, date, balance.id, context);\n-\t\t\tif (!assigned) continue;\n-\t\t\tassigned.placements.get(date)!.supporting = !isAtRisk(balance, context);\n-\t\t\tconst complete = yield* search(index + 1, assigned);\n-\t\t\tif (complete) return complete;\n-\t\t}\n-\t\treturn null;\n+\t\tcontext.completedPreferenceStates.set(index, preferenceStateKey(result));\n \t};\n-\treturn yield* search(0, state);\n-}\n-\n-function* optimizeHolidayWeeks(\n-\tstate: State,\n-\tcontext: SearchContext,\n-\tpreferences: PreferenceResult[],\n-): PlanningSteps {\n-\tlet result = state;\n-\tconst candidates = context.holidayWeeks;\n-\twhile (true) {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tif (candidates.length) recordTraceDecision(context, []);\n-\t\tconst baseline = qualityMetrics(result, context, preferences);\n-\t\tconst completed = candidates.filter((candidate) =>\n-\t\t\tcandidate.dates.every(\n-\t\t\t\t(date) => result.placements.has(date) || context.declaredDates.has(date),\n-\t\t\t),\n-\t\t);\n-\t\tlet best: State | null = null;\n-\t\tlet bestMetrics = baseline;\n-\t\tlet bestEvaluation: MutableTraceCandidate | undefined;\n-\t\tfor (const candidate of candidates) {\n+\tyield* apply(preferenceIndex);\n+\t// An earned entitlement produced later can satisfy an earlier preference.\n+\tlet previous: PlanningObjective[];\n+\tdo {\n+\t\tprevious = activeObjectiveVector(result, context);\n+\t\tconst entitlements = result.balances\n+\t\t\t.map(\n+\t\t\t\t({ id, quantity, availableFrom, expiryDate }) =>\n+\t\t\t\t\t`${id}:${quantity}:${availableFrom}:${expiryDate}`,\n+\t\t\t)\n+\t\t\t.join('|');\n+\t\tfor (let index = 0; index < preferenceIndex; index++) {\n \t\t\tyield;\n-\t\t\tcontext.check();\n-\t\t\tconst candidateDates = candidate.dates.filter(\n-\t\t\t\t(date) => !context.declaredDates.has(date),\n-\t\t\t);\n-\t\t\tconst protectedDates = new Set(\n-\t\t\t\tcompleted\n-\t\t\t\t\t.filter((week) => week.value >= candidate.value)\n-\t\t\t\t\t.flatMap((week) => week.dates),\n-\t\t\t);\n-\t\t\tconst complete = yield* completeHolidayWeek(result, candidate, context, protectedDates);\n-\t\t\tif (!complete) continue;\n-\t\t\tconst metrics = qualityMetrics(complete, context, preferences);\n-\t\t\tif (\n-\t\t\t\tmetrics.unplacedAtRisk > baseline.unplacedAtRisk ||\n-\t\t\t\tcomparePreferenceVectors(\n-\t\t\t\t\tmetrics.preferenceSatisfaction,\n-\t\t\t\t\tbaseline.preferenceSatisfaction,\n-\t\t\t\t) !== 0 ||\n-\t\t\t\tmetrics.holidayWeekValue <= baseline.holidayWeekValue\n-\t\t\t) {\n-\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tresult,\n-\t\t\t\t\tcomplete,\n-\t\t\t\t\tpreferences,\n-\t\t\t\t\tbaseline,\n-\t\t\t\t\tmetrics,\n-\t\t\t\t\tcandidateDates,\n-\t\t\t\t\tundefined,\n-\t\t\t\t\t() => holidayWeekProtectionTraceDetails(baseline, metrics, preferences),\n-\t\t\t\t);\n-\t\t\t\tcontinue;\n-\t\t\t}\n-\t\t\tconst better =\n-\t\t\t\t!best ||\n-\t\t\t\tcompareMetrics(metrics, bestMetrics) < 0 ||\n-\t\t\t\t(compareMetrics(metrics, bestMetrics) === 0 &&\n-\t\t\t\t\tplacementTieKey(complete) < placementTieKey(best));\n-\t\t\tconst evaluation = retainAndRecordEvaluation(\n+\t\t\tyield* apply(index);\n+\t\t}\n+\t\tif (\n+\t\t\tcompareObjectiveLists(activeObjectiveVector(result, context), previous) < 0 ||\n+\t\t\tresult.balances\n+\t\t\t\t.map(\n+\t\t\t\t\t({ id, quantity, availableFrom, expiryDate }) =>\n+\t\t\t\t\t\t`${id}:${quantity}:${availableFrom}:${expiryDate}`,\n+\t\t\t\t)\n+\t\t\t\t.join('|') !== entitlements\n+\t\t)\n+\t\t\tyield* apply(preferenceIndex);\n+\t} while (compareObjectiveLists(activeObjectiveVector(result, context), previous) < 0);\n+\tpreferences.splice(\n+\t\t0,\n+\t\tpreferences.length,\n+\t\t...preferenceResultsForState(result, context).map((preference) => ({\n+\t\t\t...preference,\n+\t\t\treason: preferenceReason(\n+\t\t\t\tcontext.rules.find(\n+\t\t\t\t\t(rule): rule is NormalizedCalendarRule =>\n+\t\t\t\t\t\trule.type !== 'optimization' && rule.id === preference.ruleId,\n+\t\t\t\t)!,\n+\t\t\t\tpreference.satisfied,\n \t\t\t\tcontext,\n \t\t\t\tresult,\n-\t\t\t\tcomplete,\n-\t\t\t\tpreferences,\n-\t\t\t\tbaseline,\n-\t\t\t\tmetrics,\n-\t\t\t\tcandidateDates,\n-\t\t\t\tundefined,\n-\t\t\t\t() => {\n-\t\t\t\t\tconst protectedDetails = holidayWeekProtectionTraceDetails(\n-\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t);\n-\t\t\t\t\tconst incumbentDetails = best\n-\t\t\t\t\t\t? qualityMetricTieTraceDetails(bestMetrics, metrics, best, complete)\n-\t\t\t\t\t\t: undefined;\n-\t\t\t\t\treturn {\n-\t\t\t\t\t\ttechnicalComparison: [\n-\t\t\t\t\t\t\t...(protectedDetails.technicalComparison ?? []),\n-\t\t\t\t\t\t\t...(incumbentDetails?.technicalComparison ?? []),\n-\t\t\t\t\t\t],\n-\t\t\t\t\t\tfirstDecisiveComparator: protectedDetails.reason\n-\t\t\t\t\t\t\t? protectedDetails.firstDecisiveComparator\n-\t\t\t\t\t\t\t: incumbentDetails?.firstDecisiveComparator,\n-\t\t\t\t\t\treason: better\n-\t\t\t\t\t\t\t? undefined\n-\t\t\t\t\t\t\t: reason(\n-\t\t\t\t\t\t\t\t\t'quality-no-improvement',\n-\t\t\t\t\t\t\t\t\t'This completion did not outrank the current best on its compared objectives or date tie-break.',\n-\t\t\t\t\t\t\t\t),\n-\t\t\t\t\t};\n-\t\t\t\t},\n-\t\t\t);\n-\t\t\tif (better) {\n-\t\t\t\tif (bestEvaluation)\n-\t\t\t\t\tupdateTraceEvaluationReason(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tbestEvaluation,\n-\t\t\t\t\t\treason(\n-\t\t\t\t\t\t\t'quality-outperformed',\n-\t\t\t\t\t\t\t'A later holiday-week completion became the best result in this pass.',\n-\t\t\t\t\t\t),\n-\t\t\t\t\t);\n-\t\t\t\tbest = complete;\n-\t\t\t\tbestMetrics = metrics;\n-\t\t\t\tbestEvaluation = evaluation;\n-\t\t\t}\n-\t\t}\n-\t\tif (!best) return result;\n-\t\tretainAndRecordState(context, best, bestEvaluation);\n-\t\tresult = best;\n-\t}\n+\t\t\t),\n+\t\t})),\n+\t);\n+\treturn result;\n }\n \n-function sameHigherQuality(a: PlanningMetrics, b: PlanningMetrics): boolean {\n-\treturn (\n-\t\ta.unplacedAtRisk === b.unplacedAtRisk &&\n-\t\ta.holidayWeekValue === b.holidayWeekValue &&\n-\t\ta.nonWorkingDayGain === b.nonWorkingDayGain &&\n-\t\ta.longestWorkSequence === b.longestWorkSequence &&\n-\t\ta.shortSequenceDeficit === b.shortSequenceDeficit &&\n-\t\ta.preferenceSatisfaction.length === b.preferenceSatisfaction.length &&\n-\t\ta.preferenceSatisfaction.every((value, index) => value === b.preferenceSatisfaction[index])\n-\t);\n+function preferenceStateKey(state: State): string {\n+\t// Preserve iteration order: a coordinated allocator may keep its first valid branch.\n+\treturn JSON.stringify([\n+\t\tstate.balances,\n+\t\t[...state.placements].map(([date, placement]) => [\n+\t\t\tdate,\n+\t\t\t{ ...placement, ruleIds: [...placement.ruleIds] },\n+\t\t]),\n+\t\tstate.earnedActivations,\n+\t]);\n }\n \n-function expiryProtectionTraceDetails(\n-\tbaseline: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tpreferences: readonly PreferenceResult[],\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst reject = (name: string): QualityTraceDetails => ({\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: name,\n-\t\treason: reason(\n-\t\t\t'quality-protected-objective',\n-\t\t\t`This replacement changes ${name.slice('protected:'.length).replaceAll('-', ' ')} protected by the expiry pass.`,\n-\t\t),\n-\t});\n-\tfor (const [name, direction, before, after] of [\n-\t\t[\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'minimize',\n-\t\t\tbaseline.unplacedAtRisk,\n-\t\t\tcandidate.unplacedAtRisk,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:holiday-week-value',\n-\t\t\t'maximize',\n-\t\t\tbaseline.holidayWeekValue,\n-\t\t\tcandidate.holidayWeekValue,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:non-working-day-gain',\n-\t\t\t'maximize',\n-\t\t\tbaseline.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:longest-work-sequence',\n-\t\t\t'minimize',\n-\t\t\tbaseline.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:short-sequence-deficit',\n-\t\t\t'minimize',\n-\t\t\tbaseline.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit,\n-\t\t],\n-\t] as const) {\n-\t\tif (!addQualityComparator(values, name, direction, before, after)) return reject(name);\n-\t}\n-\tif (baseline.preferenceSatisfaction.length !== candidate.preferenceSatisfaction.length) {\n-\t\tconst name = 'protected:preference-count';\n-\t\taddQualityComparator(\n-\t\t\tvalues,\n-\t\t\tname,\n-\t\t\t'maximize',\n-\t\t\tbaseline.preferenceSatisfaction.length,\n-\t\t\tcandidate.preferenceSatisfaction.length,\n-\t\t);\n-\t\treturn reject(name);\n-\t}\n-\tfor (let index = 0; index < baseline.preferenceSatisfaction.length; index++) {\n-\t\tconst name = `protected:preference:${preferences[index]?.ruleId ?? index}`;\n-\t\tif (\n-\t\t\t!addQualityComparator(\n-\t\t\t\tvalues,\n-\t\t\t\tname,\n-\t\t\t\t'maximize',\n-\t\t\t\tbaseline.preferenceSatisfaction[index],\n-\t\t\t\tcandidate.preferenceSatisfaction[index],\n-\t\t\t)\n+function placementTieKey(state: State): string {\n+\treturn [...state.placements.values()]\n+\t\t.map((placement) => placement.date)\n+\t\t.sort(compareDate)\n+\t\t.join('|');\n+}\n+\n+function expiryTieKey(state: State): string {\n+\treturn [...state.placements.values()]\n+\t\t.map(\n+\t\t\t(placement) =>\n+\t\t\t\tstate.balances.find((item) => item.id === placement.balanceId)?.expiryDate ?? '',\n \t\t)\n-\t\t\treturn reject(name);\n-\t}\n-\treturn { technicalComparison: values };\n+\t\t.sort(compareDate)\n+\t\t.join('|');\n }\n \n-function* optimizeExpiryPlacements(\n+function activeObjectiveVector(\n \tstate: State,\n \tcontext: SearchContext,\n-\tpreferences: PreferenceResult[],\n-): PlanningSteps {\n-\tlet result = state;\n-\tfor (const original of [...result.placements.values()]\n-\t\t.filter(\n-\t\t\t(placement) => placement.ruleIds.size === 0 || isMovableTimeWindow(placement, context),\n-\t\t)\n-\t\t.sort((a, b) => compareDate(a.date, b.date) || compareText(a.balanceId, b.balanceId))) {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tconst current = result.placements.get(original.date);\n-\t\tif (!current) continue;\n-\t\tconst source = result.balances.find((balance) => balance.id === current.balanceId);\n-\t\tif (!source) continue;\n-\t\trecordTraceDecision(context, [original.date]);\n-\t\tconst baseline = qualityMetrics(result, context, preferences);\n-\t\tconst without = cloneState(result);\n-\t\twithout.placements.delete(current.date);\n-\t\tconst released = without.balances.find((balance) => balance.id === source.id);\n-\t\tif (released) released.remaining++;\n-\t\tlet best = result;\n-\t\tlet bestExpiry = expiryTieKey(result);\n-\t\tlet bestEvaluation: MutableTraceCandidate | undefined;\n-\t\tfor (const replacement of without.balances\n-\t\t\t.filter(\n-\t\t\t\t(balance) =>\n-\t\t\t\t\tbalance.id !== source.id &&\n-\t\t\t\t\tbalance.type === current.type &&\n-\t\t\t\t\tbalance.remaining > 0 &&\n-\t\t\t\t\tcompareDate(balance.expiryDate, source.expiryDate) < 0 &&\n-\t\t\t\t\tcompareDate(balance.availableFrom, current.date) <= 0 &&\n-\t\t\t\t\tcompareDate(current.date, balance.expiryDate) <= 0,\n-\t\t\t)\n-\t\t\t.sort((a, b) => compareDate(a.expiryDate, b.expiryDate) || compareText(a.id, b.id))) {\n-\t\t\tyield;\n-\t\t\tconst candidate = assignDateToBalance(\n-\t\t\t\twithout,\n-\t\t\t\tcurrent.date,\n-\t\t\t\treplacement.id,\n-\t\t\t\tcontext,\n-\t\t\t\tcurrent.ruleIds,\n-\t\t\t);\n-\t\t\tif (!candidate) continue;\n-\t\t\tconst feasibleCandidate = finalizeEarnedState(candidate, context);\n-\t\t\tif (!feasibleCandidate) continue;\n-\t\t\tfeasibleCandidate.placements.get(current.date)!.supporting = current.supporting;\n-\t\t\tconst metrics = qualityMetrics(feasibleCandidate, context, preferences);\n-\t\t\tconst expiry = expiryTieKey(feasibleCandidate);\n-\t\t\tconst preservesQuality = sameHigherQuality(metrics, baseline);\n-\t\t\tconst better = preservesQuality && expiry < bestExpiry;\n-\t\t\tconst evaluation = retainAndRecordEvaluation(\n-\t\t\t\tcontext,\n-\t\t\t\tresult,\n-\t\t\t\tfeasibleCandidate,\n-\t\t\t\tpreferences,\n-\t\t\t\tbaseline,\n-\t\t\t\tmetrics,\n-\t\t\t\t[current.date],\n-\t\t\t\tcurrent.date,\n-\t\t\t\t() => {\n-\t\t\t\t\tconst protectedDetails = expiryProtectionTraceDetails(\n-\t\t\t\t\t\tbaseline,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t);\n-\t\t\t\t\tconst values = [...(protectedDetails.technicalComparison ?? [])];\n-\t\t\t\t\tlet firstDecisiveComparator = protectedDetails.firstDecisiveComparator;\n-\t\t\t\t\tlet candidateReason = protectedDetails.reason;\n-\t\t\t\t\tif (!candidateReason) {\n-\t\t\t\t\t\tconst equalExpiry = addQualityComparator(\n-\t\t\t\t\t\t\tvalues,\n-\t\t\t\t\t\t\t'balance-expiry',\n-\t\t\t\t\t\t\t'minimize',\n-\t\t\t\t\t\t\tbestExpiry,\n-\t\t\t\t\t\t\texpiry,\n-\t\t\t\t\t\t);\n-\t\t\t\t\t\tif (!equalExpiry) firstDecisiveComparator = 'balance-expiry';\n-\t\t\t\t\t\tif (!better)\n-\t\t\t\t\t\t\tcandidateReason = reason(\n-\t\t\t\t\t\t\t\t'quality-no-improvement',\n-\t\t\t\t\t\t\t\t'This replacement does not use an earlier-expiring balance than the current best.',\n-\t\t\t\t\t\t\t);\n-\t\t\t\t\t}\n-\t\t\t\t\treturn {\n-\t\t\t\t\t\ttechnicalComparison: values,\n-\t\t\t\t\t\tfirstDecisiveComparator,\n-\t\t\t\t\t\treason: candidateReason,\n-\t\t\t\t\t};\n-\t\t\t\t},\n-\t\t\t);\n-\t\t\tif (better) {\n-\t\t\t\tif (bestEvaluation)\n-\t\t\t\t\tupdateTraceEvaluationReason(\n+\tthroughIndex = Number.POSITIVE_INFINITY,\n+): PlanningObjective[] {\n+\tconst preferences = preferenceResultsForState(state, context);\n+\tlet observations: OptimizationObservations | undefined;\n+\treturn context.rules\n+\t\t.filter((rule) => rule.enabled && rule.force === 'preference')\n+\t\t.slice(0, throughIndex + 1)\n+\t\t.map((rule) => {\n+\t\t\tif (rule.type === 'optimization') {\n+\t\t\t\tobservations ??= context.rules.some(\n+\t\t\t\t\t(item) =>\n+\t\t\t\t\t\titem.type === 'optimization' &&\n+\t\t\t\t\t\titem.configuration.elements !== 'leave-balances',\n+\t\t\t\t)\n+\t\t\t\t\t? optimizationObservations(state, context)\n+\t\t\t\t\t: {\n+\t\t\t\t\t\t\tleaveBalances: optimizationBalanceObservations(state, context),\n+\t\t\t\t\t\t\tpublicHolidayWeeks: [],\n+\t\t\t\t\t\t\ttimeOffPeriods: [],\n+\t\t\t\t\t\t\tworkSequences: [],\n+\t\t\t\t\t\t\tleavePlacements: [],\n+\t\t\t\t\t\t};\n+\t\t\t\treturn {\n+\t\t\t\t\tid: `optimization:${rule.id}` as const,\n+\t\t\t\t\tdirection: rule.configuration!.direction,\n+\t\t\t\t\tvalue: evaluateStateOptimization(\n+\t\t\t\t\t\trule.configuration!,\n+\t\t\t\t\t\tstate,\n \t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tbestEvaluation,\n-\t\t\t\t\t\treason(\n-\t\t\t\t\t\t\t'quality-outperformed',\n-\t\t\t\t\t\t\t'A later replacement became the best earlier-expiry choice in this pass.',\n-\t\t\t\t\t\t),\n-\t\t\t\t\t);\n-\t\t\t\tbest = feasibleCandidate;\n-\t\t\t\tbestExpiry = expiry;\n-\t\t\t\tbestEvaluation = evaluation;\n+\t\t\t\t\t\tobservations,\n+\t\t\t\t\t),\n+\t\t\t\t\tlabel: rule.name,\n+\t\t\t\t};\n \t\t\t}\n-\t\t}\n-\t\tif (best !== result) retainAndRecordState(context, best, bestEvaluation);\n-\t\tresult = best;\n-\t}\n-\treturn result;\n+\t\t\treturn {\n+\t\t\t\tid: `preference:${rule.id}` as const,\n+\t\t\t\tdirection: 'maximize' as const,\n+\t\t\t\tvalue:\n+\t\t\t\t\tpreferences.find((preference) => preference.ruleId === rule.id)?.satisfied ?? 0,\n+\t\t\t\tlabel: rule.name,\n+\t\t\t};\n+\t\t});\n+}\n+\n+function tieBreakObjectives(state: State): PlanningObjective[] {\n+\treturn [\n+\t\t{\n+\t\t\tid: 'balance-expiry',\n+\t\t\tdirection: 'minimize',\n+\t\t\tvalue: expiryTieKey(state),\n+\t\t\tlabel: 'Balance expiry tie-break',\n+\t\t},\n+\t\t{\n+\t\t\tid: 'placement-date',\n+\t\t\tdirection: 'minimize',\n+\t\t\tvalue: placementTieKey(state),\n+\t\t\tlabel: 'Placement date tie-break',\n+\t\t},\n+\t];\n+}\n+\n+function objectiveComparisonFacts(\n+\tbefore: readonly PlanningObjective[],\n+\tafter: readonly PlanningObjective[],\n+): {\n+\tvalues: NonNullable;\n+\tfirstDecisiveComparator?: string;\n+} {\n+\tconst first = firstDifferentObjective(after, before);\n+\treturn {\n+\t\tvalues: after.slice(0, first < 0 ? after.length : first + 1).map((objective, index) => ({\n+\t\t\tname: objective.id,\n+\t\t\tdirection: objective.direction,\n+\t\t\tbefore: before[index].value,\n+\t\t\tafter: objective.value,\n+\t\t})),\n+\t\tfirstDecisiveComparator: first < 0 ? undefined : after[first].id,\n+\t};\n+}\n+\n+function obligationPreviewObjectives(\n+\tpreview: { state: State },\n+\tcontext: SearchContext,\n+): PlanningObjective[] {\n+\treturn [...activeObjectiveVector(preview.state, context), ...tieBreakObjectives(preview.state)];\n+}\n+\n+/** Compare complete previews so obligation DFS does not commit to its first feasible branch. */\n+function compareObligationPreviews(\n+\ta: { state: State },\n+\tb: { state: State },\n+\tcontext: SearchContext,\n+): number {\n+\treturn compareObjectiveLists(\n+\t\tobligationPreviewObjectives(a, context),\n+\t\tobligationPreviewObjectives(b, context),\n+\t);\n+}\n+\n+function obligationPreviewComparisonFacts(\n+\ta: { state: State },\n+\tb: { state: State },\n+\tcontext: SearchContext,\n+): {\n+\tvalues: NonNullable;\n+\tfirstDecisiveComparator?: string;\n+} {\n+\treturn objectiveComparisonFacts(\n+\t\tobligationPreviewObjectives(b, context),\n+\t\tobligationPreviewObjectives(a, context),\n+\t);\n+}\n+\n+function recordTraceDecision(context: SearchContext, dates: readonly string[]): void {\n+\tobserveTrace(context, (trace) => trace.recordDecision('choose', dates));\n }\n \n function isAtRisk(balance: InternalBalance, context: SearchContext): boolean {\n@@ -4910,36 +5052,17 @@ function isAtRisk(balance: InternalBalance, context: SearchContext): boolean {\n \t);\n }\n \n-function isMovableTimeWindow(placement: InternalPlacement, context: SearchContext): boolean {\n-\tif (!placement.ruleIds.size) return false;\n-\treturn [...placement.ruleIds].every((id) => {\n-\t\tconst rule = context.rules.find((item) => item.id === id);\n-\t\treturn rule?.enabled && rule.type === 'time_window';\n-\t});\n+function isNaturalNonWorkingDate(date: string, context: SearchContext): boolean {\n+\treturn context.calendarIndex.has(date)\n+\t\t? !context.workingCalendar.has(date)\n+\t\t: !isWorkingPlanningDate(date);\n }\n \n-function compatibleWithRules(\n-\tdate: string,\n-\ttype: LeaveType,\n-\truleIds: Set,\n-\tcontext: SearchContext,\n-): boolean {\n-\tif (!isWorking(date, context.holidays)) return false;\n-\tfor (const id of ruleIds) {\n-\t\tconst rule = context.rules.find((item) => item.id === id);\n-\t\tif (\n-\t\t\t!rule ||\n-\t\t\trule.type !== 'time_window' ||\n-\t\t\t!selectorMatches(rule.placeType, type) ||\n-\t\t\tcompareDate(date, rule.startDate!) < 0 ||\n-\t\t\tcompareDate(date, rule.endDate!) > 0\n-\t\t)\n-\t\t\treturn false;\n-\t}\n-\treturn true;\n+function calendarDateAt(index: number, context: SearchContext): string {\n+\treturn context.calendarDays[index] ?? addDays(context.calendarDays[0], index);\n }\n \n-function periodData(state: State, context: SearchContext): TimeOffPeriod[] {\n+function periodBounds(state: State, context: SearchContext) {\n \tconst dates = [...new Set([...state.placements.keys(), ...context.declaredDates])]\n \t\t.filter((date) => date >= context.horizon.start && date < context.horizon.end)\n \t\t.sort(compareDate);\n@@ -4959,89 +5082,209 @@ function periodData(state: State, context: SearchContext): TimeOffPeriod[] {\n \t\t}\n \t}\n \tgroups.push(group);\n-\tconst isNaturalNonWorkingDate = (date: string) =>\n-\t\tcontext.calendarIndex.has(date)\n-\t\t\t? !context.workingCalendar.has(date)\n-\t\t\t: !isWorkingPlanningDate(date);\n-\tconst dateAt = (index: number) =>\n-\t\tcontext.calendarDays[index] ?? addDays(context.calendarDays[0], index);\n \treturn groups.map((anchors) => {\n \t\tcontext.check();\n \t\tlet startIndex = context.calendarIndex.get(anchors[0])!;\n \t\tlet endIndex = context.calendarIndex.get(anchors[anchors.length - 1])!;\n \t\twhile (\n-\t\t\tcontext.declaredDates.has(dateAt(startIndex - 1)) ||\n-\t\t\tisNaturalNonWorkingDate(dateAt(startIndex - 1))\n+\t\t\tcontext.declaredDates.has(calendarDateAt(startIndex - 1, context)) ||\n+\t\t\tisNaturalNonWorkingDate(calendarDateAt(startIndex - 1, context), context)\n \t\t) {\n \t\t\tcontext.check();\n \t\t\tstartIndex--;\n \t\t}\n \t\twhile (\n-\t\t\tcontext.declaredDates.has(dateAt(endIndex + 1)) ||\n-\t\t\tisNaturalNonWorkingDate(dateAt(endIndex + 1))\n+\t\t\tcontext.declaredDates.has(calendarDateAt(endIndex + 1, context)) ||\n+\t\t\tisNaturalNonWorkingDate(calendarDateAt(endIndex + 1, context), context)\n \t\t) {\n \t\t\tcontext.check();\n \t\t\tendIndex++;\n \t\t}\n-\t\tconst start = dateAt(startIndex);\n-\t\tconst end = dateAt(endIndex);\n-\t\tconst allDates =\n+\t\treturn { anchors, startIndex, endIndex };\n+\t});\n+}\n+\n+function calendarPeriod(\n+\tstartIndex: number,\n+\tendIndex: number,\n+\tcontext: SearchContext,\n+): CalendarPeriod {\n+\tlet periods = calendarPeriodCache.get(context);\n+\tif (!periods) {\n+\t\tperiods = new Map();\n+\t\tcalendarPeriodCache.set(context, periods);\n+\t}\n+\tconst key = `${startIndex}:${endIndex}`;\n+\tlet period = periods.get(key);\n+\tif (period) periods.delete(key);\n+\telse {\n+\t\tconst start = calendarDateAt(startIndex, context);\n+\t\tconst end = calendarDateAt(endIndex, context);\n+\t\tconst dates =\n \t\t\tstartIndex >= 0 && endIndex < context.calendarDays.length\n \t\t\t\t? context.calendarDays.slice(startIndex, endIndex + 1)\n \t\t\t\t: dateRange(start, addDays(end, 1));\n-\t\tconst nonWorkingDates = allDates.filter(isNaturalNonWorkingDate);\n-\t\tconst declaredDates = allDates.filter((date) => context.declaredDates.has(date));\n-\t\treturn {\n+\t\tperiod = Object.freeze({\n \t\t\tstart,\n \t\t\tend,\n-\t\t\tduration: allDates.length,\n+\t\t\tduration: dates.length,\n+\t\t\tnonWorkingDates: Object.freeze(\n+\t\t\t\tdates.filter((date) => isNaturalNonWorkingDate(date, context)),\n+\t\t\t),\n+\t\t\tdeclaredDates: Object.freeze(dates.filter((date) => context.declaredDates.has(date))),\n+\t\t});\n+\t}\n+\tperiods.set(key, period);\n+\tif (periods.size > 4096) periods.delete(periods.keys().next().value!);\n+\treturn period;\n+}\n+\n+function periodData(state: State, context: SearchContext): TimeOffPeriod[] {\n+\treturn periodBounds(state, context).map(({ anchors, startIndex, endIndex }) => {\n+\t\tconst period = calendarPeriod(startIndex, endIndex, context);\n+\t\treturn {\n+\t\t\tstart: period.start,\n+\t\t\tend: period.end,\n+\t\t\tduration: period.duration,\n \t\t\tplacementDates: anchors.filter((date) => state.placements.has(date)),\n-\t\t\t...(declaredDates.length ? { declaredDates } : {}),\n-\t\t\tnonWorkingDates,\n-\t\t\tnonWorkingDayGain: nonWorkingDates.length,\n+\t\t\t...(period.declaredDates.length ? { declaredDates: [...period.declaredDates] } : {}),\n+\t\t\tnonWorkingDates: [...period.nonWorkingDates],\n+\t\t\tnonWorkingDayGain: period.nonWorkingDates.length,\n \t\t};\n \t});\n }\n \n-function unplacedAtRiskQuantity(state: State, context: SearchContext): number {\n-\treturn state.balances.reduce(\n-\t\t(total, balance) => total + (isAtRisk(balance, context) ? balance.remaining : 0),\n-\t\t0,\n-\t);\n+function optimizationBalanceObservations(state: State, context: SearchContext) {\n+\treturn state.balances.map((balance) => ({\n+\t\tunplacedQuantity: balance.remaining,\n+\t\tatRisk: isAtRisk(balance, context),\n+\t}));\n }\n \n-function qualityMetrics(\n+function optimizationObservations(\n \tstate: State,\n \tcontext: SearchContext,\n-\tpreferences: readonly PreferenceResult[],\n-): PlanningMetrics {\n-\tconst periods = periodData(state, context);\n-\tconst timeOffDates = new Set([...state.placements.keys(), ...context.declaredDates]);\n-\tconst sequences: number[] = [];\n-\tlet current = 0;\n-\tlet hasTimeOff = false;\n+\tperiods?: TimeOffPeriod[],\n+): OptimizationObservations {\n+\t// Calendar facts depend only on occupied dates within this immutable request.\n+\t// Balance quantities, provenance and supporting status stay outside this cache.\n+\tconst key = placementTieKey(state);\n+\tlet byDates = calendarObservationCache.get(context);\n+\tif (!byDates) {\n+\t\tbyDates = new Map();\n+\t\tcalendarObservationCache.set(context, byDates);\n+\t}\n+\tlet calendar = byDates.get(key);\n+\tif (calendar) byDates.delete(key);\n+\telse {\n+\t\tcalendar = Object.freeze({\n+\t\t\tpublicHolidayWeeks: Object.freeze(\n+\t\t\t\tcontext.holidayWeeks.map((week) =>\n+\t\t\t\t\tObject.freeze({\n+\t\t\t\t\t\tvalue: week.value,\n+\t\t\t\t\t\tcomplete: week.dates.every(\n+\t\t\t\t\t\t\t(date) => state.placements.has(date) || context.declaredDates.has(date),\n+\t\t\t\t\t\t),\n+\t\t\t\t\t}),\n+\t\t\t\t),\n+\t\t\t),\n+\t\t\ttimeOffPeriods: Object.freeze(\n+\t\t\t\tperiods\n+\t\t\t\t\t? periods.map((period) =>\n+\t\t\t\t\t\t\tObject.freeze({\n+\t\t\t\t\t\t\t\tnonWorkingDates: Object.freeze([...period.nonWorkingDates]),\n+\t\t\t\t\t\t\t}),\n+\t\t\t\t\t\t)\n+\t\t\t\t\t: periodBounds(state, context).map(({ startIndex, endIndex }) =>\n+\t\t\t\t\t\t\tObject.freeze({\n+\t\t\t\t\t\t\t\tnonWorkingDates: calendarPeriod(startIndex, endIndex, context)\n+\t\t\t\t\t\t\t\t\t.nonWorkingDates,\n+\t\t\t\t\t\t\t}),\n+\t\t\t\t\t\t),\n+\t\t\t),\n+\t\t\tworkSequences: Object.freeze(\n+\t\t\t\tworkSequenceDates(state, context).map(({ dates, internal }) =>\n+\t\t\t\t\tObject.freeze({ length: dates.length, internal }),\n+\t\t\t\t),\n+\t\t\t),\n+\t\t});\n+\t\tif (byDates.size >= 4096) byDates.delete(byDates.keys().next().value!);\n+\t}\n+\tbyDates.set(key, calendar);\n+\treturn {\n+\t\tleaveBalances: optimizationBalanceObservations(state, context),\n+\t\t...calendar,\n+\t\tleavePlacements: [...state.placements.values()],\n+\t};\n+}\n+\n+function workSequenceDates(state: State, context: SearchContext) {\n+\tconst sequences: string[][] = [];\n+\tlet current: string[] = [];\n+\tlet inTimeOffPeriod = false;\n \tfor (const date of context.workingDays) {\n \t\tcontext.check();\n-\t\tif (timeOffDates.has(date)) {\n-\t\t\tsequences.push(current);\n-\t\t\tcurrent = 0;\n-\t\t\thasTimeOff = true;\n-\t\t} else current++;\n+\t\tif (state.placements.has(date) || context.declaredDates.has(date)) {\n+\t\t\tif (!inTimeOffPeriod) sequences.push(current);\n+\t\t\tcurrent = [];\n+\t\t\tinTimeOffPeriod = true;\n+\t\t} else {\n+\t\t\tcurrent.push(date);\n+\t\t\tinTimeOffPeriod = false;\n+\t\t}\n \t}\n \tif (context.workingDays.length) sequences.push(current);\n-\tconst nonEmptySequences = sequences.filter((length) => length > 0);\n-\tconst internal = hasTimeOff ? sequences.slice(1, -1) : [];\n-\tconst shortSequenceDeficit = internal.reduce(\n-\t\t(sum, length) => sum + (length > 0 && length < 5 ? 5 - length : 0),\n-\t\t0,\n-\t);\n+\treturn sequences.map((dates, index) => ({\n+\t\tdates,\n+\t\tinternal: index > 0 && index < sequences.length - 1,\n+\t}));\n+}\n+\n+function evaluateStateOptimization(\n+\tconfiguration: OptimizationConfiguration,\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tobservations = optimizationObservations(state, context),\n+): number {\n+\treturn evaluateOptimization(configuration, observations);\n+}\n+\n+function qualityMetrics(\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tpreferences: readonly PreferenceResult[],\n+): PlanningMetrics {\n+\tconst periods = periodData(state, context);\n+\tconst observations = optimizationObservations(state, context, periods);\n+\tconst nonEmptySequences = observations.workSequences.filter((sequence) => sequence.length > 0);\n \treturn {\n-\t\tunplacedAtRisk: unplacedAtRiskQuantity(state, context),\n-\t\tholidayWeekValue: holidayWeekValue(state, context),\n-\t\tnonWorkingDayGain: periods.reduce((sum, period) => sum + period.nonWorkingDayGain, 0),\n-\t\tlongestWorkSequence: sequences.length ? Math.max(...sequences) : 0,\n+\t\tunplacedAtRisk: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n+\t\tholidayWeekValue: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n+\t\tnonWorkingDayGain: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.nonWorkingDayGain,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n+\t\tlongestWorkSequence: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.longestWorkSequence,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n \t\taverageWorkSequence: nonEmptySequences.length\n-\t\t\t? nonEmptySequences.reduce((sum, length) => sum + length, 0) / nonEmptySequences.length\n+\t\t\t? nonEmptySequences.reduce((sum, sequence) => sum + sequence.length, 0) /\n+\t\t\t\tnonEmptySequences.length\n \t\t\t: null,\n \t\taverageTimeOffPeriod: periods.length\n \t\t\t? periods.reduce((sum, period) => sum + period.duration, 0) / periods.length\n@@ -5049,10 +5292,18 @@ function qualityMetrics(\n \t\tlongestTimeOffPeriod: periods.length\n \t\t\t? Math.max(...periods.map((period) => period.duration))\n \t\t\t: null,\n-\t\tshortSequenceDeficit,\n-\t\tsupportingPlacements: [...state.placements.values()].filter(\n-\t\t\t(placement) => placement.supporting,\n-\t\t).length,\n+\t\tshortSequenceDeficit: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n+\t\tsupportingPlacements: evaluateStateOptimization(\n+\t\t\tOPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\tstate,\n+\t\t\tcontext,\n+\t\t\tobservations,\n+\t\t),\n \t\tpreferenceSatisfaction: preferences.map((preference) => preference.satisfied),\n \t};\n }\n@@ -5094,8 +5345,8 @@ function nonPlacementReason(\n \t\t\t'This balance expires after the horizon; the planner retained no additional placement under its planning priorities.',\n \t\t);\n \treturn reason(\n-\t\t'not-established',\n-\t\t'The calculation did not establish a precise reason for leaving this balance unspent.',\n+\t\t'active-priorities',\n+\t\t'The calculation retained no additional placement under the active planning rules.',\n \t);\n }\n \n@@ -5127,103 +5378,51 @@ function remainingBalances(\n \t\t});\n }\n \n-function unsatisfiedObligationCount(state: State, context: SearchContext): number {\n-\tconst placementCounts = new Map();\n-\tfor (const placement of state.placements.values())\n-\t\tfor (const ruleId of placement.ruleIds)\n-\t\t\tplacementCounts.set(ruleId, (placementCounts.get(ruleId) ?? 0) + 1);\n-\tlet unsatisfied = 0;\n-\tfor (const requirement of buildRequirements(context.rules, context, 'obligation')) {\n-\t\tif (!requirement.patterns) {\n-\t\t\tif ((placementCounts.get(requirement.rule.id) ?? 0) !== requirement.requiredPlacements)\n-\t\t\t\tunsatisfied++;\n-\t\t\tcontinue;\n-\t\t}\n-\t\tlet complete = false;\n-\t\tfor (const pattern of requirement.patterns) {\n-\t\t\tif (\n-\t\t\t\tpattern.every((date) =>\n-\t\t\t\t\tpatternDateSatisfied(date, requirement.rule, state, context),\n-\t\t\t\t)\n-\t\t\t) {\n-\t\t\t\tcomplete = true;\n-\t\t\t\tbreak;\n-\t\t\t}\n-\t\t}\n-\t\tif (!complete) unsatisfied++;\n-\t}\n-\treturn unsatisfied;\n-}\n-\n-function objectiveVector(\n-\tmetrics: PlanningMetrics,\n-\tpreferences: readonly PreferenceResult[],\n-\tstate: State,\n-\tcontext: SearchContext,\n-): PlanningObjectiveVector {\n-\tconst objectives: PlanningObjective[] = [\n-\t\t{\n-\t\t\tid: 'obligation-validity',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: unsatisfiedObligationCount(state, context),\n-\t\t\tlabel: 'Unsatisfied obligations',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'unplaced-at-risk',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: metrics.unplacedAtRisk,\n-\t\t\tlabel: 'Unplaced at-risk leave',\n-\t\t},\n-\t\t...preferences.map((preference) => ({\n-\t\t\tid: `preference:${preference.ruleId}` as const,\n-\t\t\tdirection: 'maximize' as const,\n-\t\t\tvalue: preference.satisfied,\n-\t\t\tlabel: `Preference ${preference.ruleId}`,\n-\t\t})),\n-\t\t{\n-\t\t\tid: 'holiday-week-value',\n-\t\t\tdirection: 'maximize',\n-\t\t\tvalue: metrics.holidayWeekValue,\n-\t\t\tlabel: 'Public-holiday week value',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'non-working-day-gain',\n-\t\t\tdirection: 'maximize',\n-\t\t\tvalue: metrics.nonWorkingDayGain,\n-\t\t\tlabel: 'Non-working-day gain',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'longest-work-sequence',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: metrics.longestWorkSequence,\n-\t\t\tlabel: 'Longest work sequence',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'short-sequence-deficit',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: metrics.shortSequenceDeficit,\n-\t\t\tlabel: 'Short work-sequence deficit',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'supporting-placements',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: metrics.supportingPlacements,\n-\t\t\tlabel: 'Supporting placements',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'balance-expiry',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: expiryTieKey(state),\n-\t\t\tlabel: 'Balance expiry tie-break',\n-\t\t},\n-\t\t{\n-\t\t\tid: 'placement-date',\n-\t\t\tdirection: 'minimize',\n-\t\t\tvalue: placementTieKey(state),\n-\t\t\tlabel: 'Placement date tie-break',\n-\t\t},\n-\t];\n-\treturn { objectives };\n+function unsatisfiedObligationCount(state: State, context: SearchContext): number {\n+\tconst placementCounts = new Map();\n+\tfor (const placement of state.placements.values())\n+\t\tfor (const ruleId of placement.ruleIds)\n+\t\t\tplacementCounts.set(ruleId, (placementCounts.get(ruleId) ?? 0) + 1);\n+\tlet unsatisfied = 0;\n+\tfor (const requirement of buildRequirements(context.rules, context, 'obligation')) {\n+\t\tif (!requirement.patterns) {\n+\t\t\tif ((placementCounts.get(requirement.rule.id) ?? 0) !== requirement.requiredPlacements)\n+\t\t\t\tunsatisfied++;\n+\t\t\tcontinue;\n+\t\t}\n+\t\tlet complete = false;\n+\t\tfor (const pattern of requirement.patterns) {\n+\t\t\tif (\n+\t\t\t\tpattern.every((date) =>\n+\t\t\t\t\tpatternDateSatisfied(date, requirement.rule, state, context),\n+\t\t\t\t)\n+\t\t\t) {\n+\t\t\t\tcomplete = true;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n+\t\tif (!complete) unsatisfied++;\n+\t}\n+\treturn unsatisfied;\n+}\n+\n+function objectiveVector(\n+\tstate: State,\n+\tcontext: SearchContext,\n+\tactive = activeObjectiveVector(state, context),\n+): PlanningObjectiveVector {\n+\treturn {\n+\t\tobjectives: [\n+\t\t\t{\n+\t\t\t\tid: 'obligation-validity',\n+\t\t\t\tdirection: 'minimize',\n+\t\t\t\tvalue: unsatisfiedObligationCount(state, context),\n+\t\t\t\tlabel: 'Unsatisfied obligations',\n+\t\t\t},\n+\t\t\t...active,\n+\t\t\t...tieBreakObjectives(state),\n+\t\t],\n+\t};\n }\n \n function displayLabel(value: unknown, fallback: string): string {\n@@ -5237,7 +5436,9 @@ function timeWindowContributions(state: State, context: SearchContext): TimeWind\n \t\t| Record\n \t\t| undefined;\n \treturn context.rules\n-\t\t.filter((rule) => rule.enabled && rule.type === 'time_window')\n+\t\t.filter(\n+\t\t\t(rule): rule is NormalizedCalendarRule => rule.enabled && rule.type === 'time_window',\n+\t\t)\n \t\t.flatMap((rule) => {\n \t\t\tconst declaredDays = declaredWindowDays(rule, context);\n \t\t\treturn declaredDays.length\n@@ -5266,16 +5467,12 @@ function ifThenContributions(state: State, context: SearchContext): IfThenContri\n \t\t| Record\n \t\t| undefined;\n \treturn context.rules\n-\t\t.filter((rule) => rule.enabled && rule.type === 'if_then')\n+\t\t.filter((rule): rule is NormalizedCalendarRule => rule.enabled && rule.type === 'if_then')\n \t\t.flatMap((rule) =>\n \t\t\toccurrences(rule, context).flatMap((occurrence) => {\n \t\t\t\tconst id = `earned:${rule.id}:${occurrence}`;\n \t\t\t\tconst activation = state.earnedActivations.find((item) => item.id === id);\n-\t\t\t\tconst pattern =\n-\t\t\t\t\tactivation?.dates ??\n-\t\t\t\t\tpatternsFor(rule, occurrence, context).find((dates) =>\n-\t\t\t\t\t\tdates.every((date) => patternDateSatisfied(date, rule, state, context)),\n-\t\t\t\t\t);\n+\t\t\t\tconst pattern = selectedOccurrencePattern(rule, occurrence, state, context);\n \t\t\t\tif (!pattern) return [];\n \t\t\t\tconst declaredDays = pattern.flatMap((date) => {\n \t\t\t\t\tconst day = declaredPatternDay(date, rule.placeType, context);\n@@ -5328,7 +5525,7 @@ function planExplanation(\n \tconst rawRules = Array.isArray(source.rules) ? source.rules : [];\n \tconst labels = recordValue(source.labels) as Record | undefined;\n \tconst identities = recordValue(source.identities) as Record | undefined;\n-\tconst vector = objectiveVector(metrics, preferences, state, context);\n+\tconst vector = objectiveVector(state, context);\n \tconst windowContributions = timeWindowContributions(state, context);\n \tconst patternContributions = ifThenContributions(state, context);\n \treturn {\n@@ -5367,10 +5564,8 @@ function planExplanation(\n \t\t\t\t(candidate) => candidate.id === placement.balanceId,\n \t\t\t);\n \t\t\tif (released) released.remaining++;\n-\t\t\tconst withoutPreferences = preferenceResultsForState(withoutPlacement, context);\n-\t\t\tconst withoutMetrics = qualityMetrics(withoutPlacement, context, withoutPreferences);\n \t\t\tconst comparison = objectiveComparison(\n-\t\t\t\tobjectiveVector(withoutMetrics, withoutPreferences, withoutPlacement, context),\n+\t\t\t\tobjectiveVector(withoutPlacement, context),\n \t\t\t\tvector,\n \t\t\t);\n \t\t\tconst contributions: PlacementContribution[] = [\n@@ -5527,19 +5722,17 @@ function markProgress(context: SearchContext, stage: string): void {\n \t\t);\n }\n \n+function ruleStage(rule: NormalizedRule): string {\n+\treturn `${rule.type === 'optimization' ? 'optimization' : 'preference'}:${rule.id}`;\n+}\n+\n function planningStages(context: SearchContext): string[] {\n \treturn [\n \t\t'validation',\n \t\t'obligations',\n-\t\t'at-risk',\n \t\t...context.rules\n \t\t\t.filter((rule) => rule.enabled && rule.force === 'preference')\n-\t\t\t.map((rule) => `preference:${rule.id}`),\n-\t\t'holiday-week-value',\n-\t\t'non-working-day-gain',\n-\t\t'longest-work-sequence',\n-\t\t'short-sequence-deficit',\n-\t\t'supporting-placements',\n+\t\t\t.map(ruleStage),\n \t\t'expiry',\n \t\t'dates',\n \t];\n@@ -5570,7 +5763,13 @@ function obligationConflict(\n \tconst ruleIds = [...new Set(requirements.map((requirement) => requirement.rule.id))];\n \tconst generatedTypes = new Set(\n \t\tcontext.rules\n-\t\t\t.filter((rule) => rule.enabled && (rule.rewardDays ?? 0) > 0 && rule.rewardType)\n+\t\t\t.filter(\n+\t\t\t\t(rule): rule is NormalizedCalendarRule =>\n+\t\t\t\t\trule.enabled &&\n+\t\t\t\t\trule.type === 'if_then' &&\n+\t\t\t\t\t(rule.rewardDays ?? 0) > 0 &&\n+\t\t\t\t\t!!rule.rewardType,\n+\t\t\t)\n \t\t\t.map((rule) => rule.rewardType!),\n \t);\n \tlet generatedCapacityBottleneck = false;\n@@ -5641,380 +5840,6 @@ function obligationConflict(\n \t};\n }\n \n-function supportingProtectionTraceDetails(\n-\tbaseline: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-\tpreferences: readonly PreferenceResult[],\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst reject = (name: string, message: string): QualityTraceDetails => ({\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: name,\n-\t\treason: reason('quality-protected-objective', message),\n-\t});\n-\tconst same = (\n-\t\tname: string,\n-\t\tdirection: QualityTraceComparator['direction'],\n-\t\ta: number,\n-\t\tb: number,\n-\t) => addQualityComparator(values, name, direction, a, b);\n-\tif (\n-\t\t!same(\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'minimize',\n-\t\t\tbaseline.unplacedAtRisk,\n-\t\t\tcandidate.unplacedAtRisk,\n-\t\t)\n-\t)\n-\t\treturn reject(\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'This supporting placement changes the amount of unplaced at-risk leave.',\n-\t\t);\n-\tif (baseline.preferenceSatisfaction.length !== candidate.preferenceSatisfaction.length) {\n-\t\tconst name = 'protected:preference-count';\n-\t\tsame(\n-\t\t\tname,\n-\t\t\t'maximize',\n-\t\t\tbaseline.preferenceSatisfaction.length,\n-\t\t\tcandidate.preferenceSatisfaction.length,\n-\t\t);\n-\t\treturn reject(name, 'This supporting placement changes a preference result.');\n-\t}\n-\tfor (let index = 0; index < baseline.preferenceSatisfaction.length; index++) {\n-\t\tconst name = `protected:preference:${preferences[index]?.ruleId ?? index}`;\n-\t\tif (\n-\t\t\t!same(\n-\t\t\t\tname,\n-\t\t\t\t'maximize',\n-\t\t\t\tbaseline.preferenceSatisfaction[index],\n-\t\t\t\tcandidate.preferenceSatisfaction[index],\n-\t\t\t)\n-\t\t)\n-\t\t\treturn reject(name, 'This supporting placement changes a preference result.');\n-\t}\n-\tfor (const [name, direction, before, after, isAllowed] of [\n-\t\t[\n-\t\t\t'protected:holiday-week-value',\n-\t\t\t'maximize',\n-\t\t\tbaseline.holidayWeekValue,\n-\t\t\tcandidate.holidayWeekValue,\n-\t\t\tcandidate.holidayWeekValue >= baseline.holidayWeekValue,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:non-working-day-gain',\n-\t\t\t'maximize',\n-\t\t\tbaseline.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain >= baseline.nonWorkingDayGain,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:longest-work-sequence',\n-\t\t\t'minimize',\n-\t\t\tbaseline.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence <= baseline.longestWorkSequence,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:short-sequence-deficit',\n-\t\t\t'minimize',\n-\t\t\tbaseline.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit <= baseline.shortSequenceDeficit,\n-\t\t],\n-\t] as const) {\n-\t\tsame(name, direction, before, after);\n-\t\tif (!isAllowed)\n-\t\t\treturn reject(\n-\t\t\t\tname,\n-\t\t\t\t`This supporting placement worsens ${name.slice('protected:'.length).replaceAll('-', ' ')}.`,\n-\t\t\t);\n-\t}\n-\treturn { technicalComparison: values };\n-}\n-\n-function supportingRemovalTraceDetails(\n-\tbaseline: PlanningMetrics,\n-\tcandidate: PlanningMetrics,\n-): QualityTraceDetails {\n-\tconst values: QualityTraceComparator[] = [];\n-\tconst reject = (name: string, message: string): QualityTraceDetails => ({\n-\t\ttechnicalComparison: values,\n-\t\tfirstDecisiveComparator: name,\n-\t\treason: reason('quality-protected-objective', message),\n-\t});\n-\tif (\n-\t\t!addQualityComparator(\n-\t\t\tvalues,\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'minimize',\n-\t\t\tbaseline.unplacedAtRisk,\n-\t\t\tcandidate.unplacedAtRisk,\n-\t\t)\n-\t)\n-\t\treturn reject(\n-\t\t\t'protected:unplaced-at-risk',\n-\t\t\t'Removing this supporting placement changes unplaced at-risk leave.',\n-\t\t);\n-\tfor (const [name, direction, before, after, isAllowed] of [\n-\t\t[\n-\t\t\t'protected:holiday-week-value',\n-\t\t\t'maximize',\n-\t\t\tbaseline.holidayWeekValue,\n-\t\t\tcandidate.holidayWeekValue,\n-\t\t\tcandidate.holidayWeekValue >= baseline.holidayWeekValue,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:non-working-day-gain',\n-\t\t\t'maximize',\n-\t\t\tbaseline.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain,\n-\t\t\tcandidate.nonWorkingDayGain >= baseline.nonWorkingDayGain,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:longest-work-sequence',\n-\t\t\t'minimize',\n-\t\t\tbaseline.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence,\n-\t\t\tcandidate.longestWorkSequence <= baseline.longestWorkSequence,\n-\t\t],\n-\t\t[\n-\t\t\t'protected:short-sequence-deficit',\n-\t\t\t'minimize',\n-\t\t\tbaseline.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit,\n-\t\t\tcandidate.shortSequenceDeficit <= baseline.shortSequenceDeficit,\n-\t\t],\n-\t] as const) {\n-\t\taddQualityComparator(values, name, direction, before, after);\n-\t\tif (!isAllowed)\n-\t\t\treturn reject(\n-\t\t\t\tname,\n-\t\t\t\t`Removing this supporting placement worsens ${name.slice('protected:'.length).replaceAll('-', ' ')}.`,\n-\t\t\t);\n-\t}\n-\treturn { technicalComparison: values };\n-}\n-\n-function* supportingPlacements(\n-\tstate: State,\n-\tcontext: SearchContext,\n-\tpreferences: PreferenceResult[],\n-): PlanningSteps {\n-\tlet result = state;\n-\twhile (true) {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tconst before = qualityMetrics(result, context, preferences);\n-\t\tlet best: State | null = null;\n-\t\tlet bestMetrics: PlanningMetrics | null = null;\n-\t\tlet bestEvaluation: MutableTraceCandidate | undefined;\n-\t\tfor (const balance of result.balances\n-\t\t\t.filter(\n-\t\t\t\t(item) =>\n-\t\t\t\t\tcompareDate(item.expiryDate, context.horizon.end) > 0 && item.remaining > 0,\n-\t\t\t)\n-\t\t\t.sort((a, b) => compareDate(a.expiryDate, b.expiryDate) || compareText(a.id, b.id))) {\n-\t\t\tyield;\n-\t\t\tfor (const date of context.workingDays) {\n-\t\t\t\tyield;\n-\t\t\t\tcontext.check();\n-\t\t\t\tif (\n-\t\t\t\t\tresult.placements.has(date) ||\n-\t\t\t\t\tcompareDate(balance.availableFrom, date) > 0 ||\n-\t\t\t\t\tcompareDate(date, balance.expiryDate) > 0\n-\t\t\t\t)\n-\t\t\t\t\tcontinue;\n-\t\t\t\tconst candidate = assignDateToBalance(result, date, balance.id, context);\n-\t\t\t\tif (!candidate) continue;\n-\t\t\t\tcandidate.placements.get(date)!.supporting = true;\n-\t\t\t\tconst feasibleCandidate = finalizeEarnedState(candidate, context);\n-\t\t\t\tif (!feasibleCandidate) continue;\n-\t\t\t\tconst metrics = qualityMetrics(feasibleCandidate, context, preferences);\n-\t\t\t\tconst preservesHigherMetrics =\n-\t\t\t\t\tmetrics.unplacedAtRisk === before.unplacedAtRisk &&\n-\t\t\t\t\tmetrics.preferenceSatisfaction.length ===\n-\t\t\t\t\t\tbefore.preferenceSatisfaction.length &&\n-\t\t\t\t\tmetrics.preferenceSatisfaction.every(\n-\t\t\t\t\t\t(value, index) => value === before.preferenceSatisfaction[index],\n-\t\t\t\t\t) &&\n-\t\t\t\t\tmetrics.holidayWeekValue >= before.holidayWeekValue &&\n-\t\t\t\t\tmetrics.nonWorkingDayGain >= before.nonWorkingDayGain &&\n-\t\t\t\t\tmetrics.longestWorkSequence <= before.longestWorkSequence &&\n-\t\t\t\t\tmetrics.shortSequenceDeficit <= before.shortSequenceDeficit;\n-\t\t\t\tif (!preservesHigherMetrics) {\n-\t\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tresult,\n-\t\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\tbefore,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t[date],\n-\t\t\t\t\t\tundefined,\n-\t\t\t\t\t\t() => supportingProtectionTraceDetails(before, metrics, preferences),\n-\t\t\t\t\t);\n-\t\t\t\t\tcontinue;\n-\t\t\t\t}\n-\t\t\t\tconst useful =\n-\t\t\t\t\tmetrics.holidayWeekValue > before.holidayWeekValue ||\n-\t\t\t\t\tmetrics.nonWorkingDayGain > before.nonWorkingDayGain ||\n-\t\t\t\t\tmetrics.longestWorkSequence < before.longestWorkSequence ||\n-\t\t\t\t\tmetrics.shortSequenceDeficit < before.shortSequenceDeficit;\n-\t\t\t\tif (!useful) {\n-\t\t\t\t\tretainAndRecordEvaluation(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tresult,\n-\t\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\tbefore,\n-\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t[date],\n-\t\t\t\t\t\tundefined,\n-\t\t\t\t\t\t() => ({\n-\t\t\t\t\t\t\t...supportingProtectionTraceDetails(before, metrics, preferences),\n-\t\t\t\t\t\t\treason: reason(\n-\t\t\t\t\t\t\t\t'quality-no-improvement',\n-\t\t\t\t\t\t\t\t'This supporting placement does not improve a protected quality objective.',\n-\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t}),\n-\t\t\t\t\t);\n-\t\t\t\t\tcontinue;\n-\t\t\t\t}\n-\t\t\t\tconst better = !bestMetrics || compareMetrics(metrics, bestMetrics) < 0;\n-\t\t\t\tconst evaluation = retainAndRecordEvaluation(\n-\t\t\t\t\tcontext,\n-\t\t\t\t\tresult,\n-\t\t\t\t\tfeasibleCandidate,\n-\t\t\t\t\tpreferences,\n-\t\t\t\t\tbefore,\n-\t\t\t\t\tmetrics,\n-\t\t\t\t\t[date],\n-\t\t\t\t\tundefined,\n-\t\t\t\t\t() => {\n-\t\t\t\t\t\tconst protectedDetails = supportingProtectionTraceDetails(\n-\t\t\t\t\t\t\tbefore,\n-\t\t\t\t\t\t\tmetrics,\n-\t\t\t\t\t\t\tpreferences,\n-\t\t\t\t\t\t);\n-\t\t\t\t\t\tconst incumbentDetails = bestMetrics\n-\t\t\t\t\t\t\t? qualityMetricTraceDetails(bestMetrics, metrics)\n-\t\t\t\t\t\t\t: undefined;\n-\t\t\t\t\t\treturn {\n-\t\t\t\t\t\t\ttechnicalComparison: [\n-\t\t\t\t\t\t\t\t...(protectedDetails.technicalComparison ?? []),\n-\t\t\t\t\t\t\t\t...(incumbentDetails?.technicalComparison ?? []),\n-\t\t\t\t\t\t\t],\n-\t\t\t\t\t\t\tfirstDecisiveComparator: incumbentDetails?.firstDecisiveComparator,\n-\t\t\t\t\t\t\treason: better\n-\t\t\t\t\t\t\t\t? undefined\n-\t\t\t\t\t\t\t\t: reason(\n-\t\t\t\t\t\t\t\t\t\t'quality-no-improvement',\n-\t\t\t\t\t\t\t\t\t\t'This candidate did not outrank the current best supporting placement.',\n-\t\t\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t};\n-\t\t\t\t\t},\n-\t\t\t\t);\n-\t\t\t\tif (better) {\n-\t\t\t\t\tif (bestEvaluation)\n-\t\t\t\t\t\tupdateTraceEvaluationReason(\n-\t\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\t\tbestEvaluation,\n-\t\t\t\t\t\t\treason(\n-\t\t\t\t\t\t\t\t'quality-outperformed',\n-\t\t\t\t\t\t\t\t'A later candidate became the best supporting placement.',\n-\t\t\t\t\t\t\t),\n-\t\t\t\t\t\t);\n-\t\t\t\t\tbest = feasibleCandidate;\n-\t\t\t\t\tbestMetrics = metrics;\n-\t\t\t\t\tbestEvaluation = evaluation;\n-\t\t\t\t}\n-\t\t\t}\n-\t\t}\n-\t\tif (!best) return result;\n-\t\tretainAndRecordState(context, best, bestEvaluation);\n-\t\tresult = best;\n-\t}\n-}\n-\n-function* pruneRedundantSupportingPlacements(\n-\tstate: State,\n-\tcontext: SearchContext,\n-\tpreferences: PreferenceResult[],\n-): PlanningSteps {\n-\tlet result = state;\n-\tlet removed = true;\n-\twhile (removed) {\n-\t\tyield;\n-\t\tcontext.check();\n-\t\tremoved = false;\n-\t\tconst baseline = qualityMetrics(result, context, preferences);\n-\t\tfor (const placement of [...result.placements.values()].filter((item) => item.supporting)) {\n-\t\t\tyield;\n-\t\t\tcontext.check();\n-\t\t\trecordTraceDecision(context, [placement.date]);\n-\t\t\tconst candidate = cloneState(result);\n-\t\t\tcandidate.placements.delete(placement.date);\n-\t\t\tconst balance = candidate.balances.find((item) => item.id === placement.balanceId);\n-\t\t\tif (balance) balance.remaining++;\n-\t\t\tconst feasibleCandidate = finalizeEarnedState(candidate, context);\n-\t\t\tif (!feasibleCandidate) {\n-\t\t\t\trecordTraceCandidate(context, {\n-\t\t\t\t\tstatus: 'pruned',\n-\t\t\t\t\tdate: placement.date,\n-\t\t\t\t\treason: reason(\n-\t\t\t\t\t\t'earned-entitlement-order',\n-\t\t\t\t\t\t'Removing this supporting placement would invalidate earned entitlement dates.',\n-\t\t\t\t\t),\n-\t\t\t\t});\n-\t\t\t\tcontinue;\n-\t\t\t}\n-\t\t\tconst metrics = qualityMetrics(feasibleCandidate, context, preferences);\n-\t\t\tconst removesWithoutQualityLoss =\n-\t\t\t\tmetrics.unplacedAtRisk === baseline.unplacedAtRisk &&\n-\t\t\t\tmetrics.holidayWeekValue >= baseline.holidayWeekValue &&\n-\t\t\t\tmetrics.nonWorkingDayGain >= baseline.nonWorkingDayGain &&\n-\t\t\t\tmetrics.longestWorkSequence <= baseline.longestWorkSequence &&\n-\t\t\t\tmetrics.shortSequenceDeficit <= baseline.shortSequenceDeficit;\n-\t\t\tconst evaluation = retainAndRecordEvaluation(\n-\t\t\t\tcontext,\n-\t\t\t\tresult,\n-\t\t\t\tfeasibleCandidate,\n-\t\t\t\tpreferences,\n-\t\t\t\tbaseline,\n-\t\t\t\tmetrics,\n-\t\t\t\t[placement.date],\n-\t\t\t\tplacement.date,\n-\t\t\t\t() => {\n-\t\t\t\t\tconst details = supportingRemovalTraceDetails(baseline, metrics);\n-\t\t\t\t\treturn {\n-\t\t\t\t\t\t...details,\n-\t\t\t\t\t\treason: removesWithoutQualityLoss ? undefined : details.reason,\n-\t\t\t\t\t};\n-\t\t\t\t},\n-\t\t\t);\n-\t\t\tif (removesWithoutQualityLoss) {\n-\t\t\t\tretainAndRecordState(context, feasibleCandidate, evaluation);\n-\t\t\t\tresult = feasibleCandidate;\n-\t\t\t\tremoved = true;\n-\t\t\t\tbreak;\n-\t\t\t}\n-\t\t}\n-\t}\n-\treturn result;\n-}\n-\n-function compareMetrics(a: PlanningMetrics, b: PlanningMetrics): number {\n-\tif (a.unplacedAtRisk !== b.unplacedAtRisk) return a.unplacedAtRisk - b.unplacedAtRisk;\n-\tif (a.holidayWeekValue !== b.holidayWeekValue) return b.holidayWeekValue - a.holidayWeekValue;\n-\tif (a.nonWorkingDayGain !== b.nonWorkingDayGain)\n-\t\treturn b.nonWorkingDayGain - a.nonWorkingDayGain;\n-\tif (a.longestWorkSequence !== b.longestWorkSequence)\n-\t\treturn a.longestWorkSequence - b.longestWorkSequence;\n-\tif (a.shortSequenceDeficit !== b.shortSequenceDeficit)\n-\t\treturn a.shortSequenceDeficit - b.shortSequenceDeficit;\n-\treturn a.supportingPlacements - b.supportingPlacements;\n-}\n-\n export type PlanningCheckpoint = (plan: PlanOutcome, state?: PlanningTraceState) => void;\n export interface PlanningArtifacts {\n \texplanation?: PlanningExplanation;\n@@ -6215,6 +6040,7 @@ function* calculatePlanningSteps(\n \t\ttraceReportedTime: 0,\n \t\tobserverTime: 0,\n \t\tobligationSolutionBranches: new WeakMap(),\n+\t\tcompletedPreferenceStates: new Map(),\n \t} as SearchContext;\n \tconst traceStarted = now();\n \tconst traceRecorder = artifactsCallback\n@@ -6267,68 +6093,57 @@ function* calculatePlanningSteps(\n \tconst preferences: PreferenceResult[] = [];\n \tlet checkpoint: PlanOutcome | undefined;\n \tlet checkpointState: State | undefined;\n-\tlet retained: Pick | undefined;\n+\tlet retained:\n+\t\t| (Pick & {\n+\t\t\t\tvector: PlanningObjectiveVector;\n+\t\t })\n+\t\t| undefined;\n \tif (retainIncumbents)\n-\t\tcontext.retain = (candidate, finalizedMetrics) => {\n+\t\tcontext.retain = (candidate, finalizedMetrics, candidateVector) => {\n \t\t\tconst check = context.check;\n \t\t\tcontext.check = () => undefined;\n \t\t\ttry {\n-\t\t\t\tconst finalized = finalizedMetrics\n-\t\t\t\t\t? candidate\n-\t\t\t\t\t: finalizeEarnedState(candidate, context);\n+\t\t\t\tconst finalized =\n+\t\t\t\t\tfinalizedMetrics || candidateVector\n+\t\t\t\t\t\t? candidate\n+\t\t\t\t\t\t: finalizeEarnedState(candidate, context);\n \t\t\t\tif (!finalized) return;\n-\t\t\t\tconst unplacedAtRisk =\n-\t\t\t\t\tfinalizedMetrics?.unplacedAtRisk ?? unplacedAtRiskQuantity(finalized, context);\n-\t\t\t\tif (retained && unplacedAtRisk > retained.metrics.unplacedAtRisk) {\n-\t\t\t\t\trecordTraceIncumbentBound(context, retained.metrics, unplacedAtRisk);\n-\t\t\t\t\treturn;\n-\t\t\t\t}\n-\t\t\t\tconst candidatePreferences = preferenceResultsForState(finalized, context);\n-\t\t\t\tconst preferenceSatisfaction = candidatePreferences.map(\n-\t\t\t\t\t({ satisfied }) => satisfied,\n-\t\t\t\t);\n-\t\t\t\tif (\n-\t\t\t\t\tretained &&\n-\t\t\t\t\tunplacedAtRisk === retained.metrics.unplacedAtRisk &&\n-\t\t\t\t\tcomparePreferenceVectors(\n-\t\t\t\t\t\tpreferenceSatisfaction,\n-\t\t\t\t\t\tretained.metrics.preferenceSatisfaction,\n-\t\t\t\t\t) > 0\n-\t\t\t\t) {\n-\t\t\t\t\trecordTraceIncumbentBound(\n-\t\t\t\t\t\tcontext,\n-\t\t\t\t\t\tretained.metrics,\n-\t\t\t\t\t\tunplacedAtRisk,\n-\t\t\t\t\t\tcandidatePreferences,\n-\t\t\t\t\t);\n-\t\t\t\t\treturn;\n-\t\t\t\t}\n \t\t\t\tif (unsatisfiedObligationCount(finalized, context)) return;\n-\t\t\t\tif (\n-\t\t\t\t\tretained &&\n-\t\t\t\t\t!planningTraceDeltas(retained.state, finalized, [\n-\t\t\t\t\t\t...retained.state.placements.keys(),\n-\t\t\t\t\t\t...finalized.placements.keys(),\n-\t\t\t\t\t]).length\n-\t\t\t\t)\n-\t\t\t\t\treturn;\n-\t\t\t\tconst scored = {\n-\t\t\t\t\tstate: finalized,\n-\t\t\t\t\tpreferences: candidatePreferences,\n-\t\t\t\t\tmetrics: finalizedMetrics\n-\t\t\t\t\t\t? {\n-\t\t\t\t\t\t\t\t...finalizedMetrics,\n-\t\t\t\t\t\t\t\tpreferenceSatisfaction,\n-\t\t\t\t\t\t\t}\n-\t\t\t\t\t\t: qualityMetrics(finalized, context, candidatePreferences),\n-\t\t\t\t};\n-\t\t\t\tconst compared = retained ? compareObligationPreviews(scored, retained) : -1;\n+\t\t\t\tconst deltas = retained\n+\t\t\t\t\t? planningTraceDeltas(retained.state, finalized, [\n+\t\t\t\t\t\t\t...retained.state.placements.keys(),\n+\t\t\t\t\t\t\t...finalized.placements.keys(),\n+\t\t\t\t\t\t])\n+\t\t\t\t\t: [];\n+\t\t\t\tif (retained && !deltas.length) return;\n+\t\t\t\tconst vector = candidateVector ?? objectiveVector(finalized, context);\n+\t\t\t\tconst compared = retained\n+\t\t\t\t\t? compareObjectiveLists(vector.objectives, retained.vector.objectives)\n+\t\t\t\t\t: -1;\n+\t\t\t\t// Calendar association can complete provenance after the scoring candidate is retained.\n+\t\t\t\tconst provenanceRefresh =\n+\t\t\t\t\tcompared === 0 &&\n+\t\t\t\t\t!!retained &&\n+\t\t\t\t\tdeltas.every(\n+\t\t\t\t\t\t({ kind, placement, previousPlacement }) =>\n+\t\t\t\t\t\t\tkind === 'placement-updated' &&\n+\t\t\t\t\t\t\tplacement?.date === previousPlacement?.date &&\n+\t\t\t\t\t\t\tplacement?.balanceId === previousPlacement?.balanceId &&\n+\t\t\t\t\t\t\tplacement?.type === previousPlacement?.type &&\n+\t\t\t\t\t\t\tplacement?.supporting === previousPlacement?.supporting,\n+\t\t\t\t\t) &&\n+\t\t\t\t\tJSON.stringify(retained.state.earnedActivations) ===\n+\t\t\t\t\t\tJSON.stringify(finalized.earnedActivations);\n+\t\t\t\tconst chosen = compared < 0 || provenanceRefresh;\n \t\t\t\tif (retained) {\n \t\t\t\t\tobserveTrace(context, (trace) => {\n-\t\t\t\t\t\tconst facts = obligationPreviewComparisonFacts(scored, retained!);\n+\t\t\t\t\t\tconst facts = objectiveComparisonFacts(\n+\t\t\t\t\t\t\tretained!.vector.objectives,\n+\t\t\t\t\t\t\tvector.objectives,\n+\t\t\t\t\t\t);\n \t\t\t\t\t\ttrace.recordCandidate(\n \t\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t\tstatus: compared < 0 ? 'chosen' : 'evaluated-rejected',\n+\t\t\t\t\t\t\t\tstatus: chosen ? 'chosen' : 'evaluated-rejected',\n \t\t\t\t\t\t\t\tdates: [...finalized.placements.keys()],\n \t\t\t\t\t\t\t\ttechnicalComparison: facts.values,\n \t\t\t\t\t\t\t\tfirstDecisiveComparator: facts.firstDecisiveComparator,\n@@ -6336,16 +6151,38 @@ function* calculatePlanningSteps(\n \t\t\t\t\t\t\t\t\t'incumbent-comparison',\n \t\t\t\t\t\t\t\t\tcompared < 0\n \t\t\t\t\t\t\t\t\t\t? 'This valid candidate became the best available partial plan.'\n-\t\t\t\t\t\t\t\t\t\t: 'This valid candidate did not improve the best available partial plan.',\n+\t\t\t\t\t\t\t\t\t\t: provenanceRefresh\n+\t\t\t\t\t\t\t\t\t\t\t? 'This identical plan refreshed only the retained rule provenance.'\n+\t\t\t\t\t\t\t\t\t\t\t: 'This valid candidate did not improve the best available partial plan.',\n \t\t\t\t\t\t\t\t),\n \t\t\t\t\t\t\t},\n \t\t\t\t\t\t\tfalse,\n \t\t\t\t\t\t);\n \t\t\t\t\t});\n \t\t\t\t}\n-\t\t\t\tif (compared < 0) {\n+\t\t\t\tif (chosen) {\n \t\t\t\t\tconst firstValidCandidate = !retained;\n-\t\t\t\t\tretained = { ...scored, state: cloneState(finalized) };\n+\t\t\t\t\tconst candidatePreferences = preferenceResultsForState(finalized, context);\n+\t\t\t\t\tretained = {\n+\t\t\t\t\t\tstate: cloneState(\n+\t\t\t\t\t\t\treconcileOptimizationProvenance(\n+\t\t\t\t\t\t\t\tfinalized,\n+\t\t\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\t\t\tretained?.state ?? initialState,\n+\t\t\t\t\t\t\t\tvector.objectives,\n+\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t),\n+\t\t\t\t\t\tvector,\n+\t\t\t\t\t\tpreferences: candidatePreferences,\n+\t\t\t\t\t\tmetrics: finalizedMetrics\n+\t\t\t\t\t\t\t? {\n+\t\t\t\t\t\t\t\t\t...finalizedMetrics,\n+\t\t\t\t\t\t\t\t\tpreferenceSatisfaction: candidatePreferences.map(\n+\t\t\t\t\t\t\t\t\t\t({ satisfied }) => satisfied,\n+\t\t\t\t\t\t\t\t\t),\n+\t\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\t: qualityMetrics(finalized, context, candidatePreferences),\n+\t\t\t\t\t};\n \t\t\t\t\tif (firstValidCandidate && checkpointCallback)\n \t\t\t\t\t\tobserveCallback(context, () =>\n \t\t\t\t\t\t\tcheckpointCallback(\n@@ -6534,6 +6371,7 @@ function* calculatePlanningSteps(\n \t\treturn outcome;\n \t};\n \tconst publishCheckpoint = (): void => {\n+\t\tstate = reconcileOptimizationProvenance(state, context, checkpointState ?? initialState);\n \t\tcontext.retain?.(state);\n \t\tcheckpoint = makePlan(state, context, preferences, stages);\n \t\tcheckpointState = cloneState(state);\n@@ -6569,8 +6407,7 @@ function* calculatePlanningSteps(\n \t\t\t}\n \t\t\tif (state !== initialState) retainAndRecordState(context, state);\n \t\t}\n-\t\t// At-risk quantity is the first objective, but equivalent placements can\n-\t\t// still preserve later preferences by sharing their compatible dates.\n+\t\t// Equivalent obligation placements can share compatible dates with active preferences.\n \t\tcontext.protectedTypesByDate = futurePreferenceProtection(normalized.rules, 0, context);\n \t\tmarkProgress(context, 'obligations');\n \t\tyield true;\n@@ -6634,8 +6471,58 @@ function* calculatePlanningSteps(\n \t\tconst preferenceRules = normalized.rules.filter(\n \t\t\t(item) => item.enabled && item.force === 'preference',\n \t\t);\n-\t\tlet bestPreview: ObligationPreview | null = null;\n-\t\tfor (const obligationSolution of obligationSolutions) {\n+\t\tlet previewSolutions = obligationSolutions;\n+\t\tif (\n+\t\t\tobligationSolutionLimit > 0 &&\n+\t\t\tobligationRequirements.every(\n+\t\t\t\t(requirement) => requirement.rule.type === 'time_window',\n+\t\t\t) &&\n+\t\t\tobligationSolutions.length > WINDOW_OBLIGATION_PREVIEW_LIMIT\n+\t\t) {\n+\t\t\t// shortcut: large window searches preview the eight best active vectors; upgrade to shared bounded previews when a measured case misses a better plan.\n+\t\t\tconst ranked: { state: State; objectives: PlanningObjective[] }[] = [];\n+\t\t\tfor (const candidate of obligationSolutions) {\n+\t\t\t\tyield;\n+\t\t\t\tcontext.check();\n+\t\t\t\tranked.push({\n+\t\t\t\t\tstate: candidate,\n+\t\t\t\t\tobjectives: obligationPreviewObjectives({ state: candidate }, context),\n+\t\t\t\t});\n+\t\t\t}\n+\t\t\tranked.sort((a, b) => compareObjectiveLists(a.objectives, b.objectives));\n+\t\t\tpreviewSolutions = ranked\n+\t\t\t\t.slice(0, WINDOW_OBLIGATION_PREVIEW_LIMIT)\n+\t\t\t\t.map(({ state }) => state);\n+\t\t\tfor (const candidate of ranked.slice(WINDOW_OBLIGATION_PREVIEW_LIMIT)) {\n+\t\t\t\tyield;\n+\t\t\t\trecordTraceCandidate(context, {\n+\t\t\t\t\tstatus: 'not-examined',\n+\t\t\t\t\tdates: [...candidate.state.placements.keys()],\n+\t\t\t\t\treason: reason(\n+\t\t\t\t\t\t'window-obligation-preview-sampling',\n+\t\t\t\t\t\t'This feasible large-window solution did not receive an optimization preview.',\n+\t\t\t\t\t),\n+\t\t\t\t});\n+\t\t\t}\n+\t\t}\n+\t\t// A completed enumeration with one finalized solution has no alternative to rank.\n+\t\tconst soleSolution =\n+\t\t\tobligationSolutions.length === 1 &&\n+\t\t\t(obligationSolutionLimit === 0 || obligationSolutions.length < obligationSolutionLimit)\n+\t\t\t\t? obligationSolutions[0]\n+\t\t\t\t: undefined;\n+\t\tconst solePreferences = soleSolution\n+\t\t\t? preferenceResultsForState(soleSolution, context)\n+\t\t\t: [];\n+\t\tlet bestPreview: ObligationPreview | null = soleSolution\n+\t\t\t? {\n+\t\t\t\t\tobligationState: soleSolution,\n+\t\t\t\t\tstate: soleSolution,\n+\t\t\t\t\tpreferences: solePreferences,\n+\t\t\t\t\tmetrics: qualityMetrics(soleSolution, context, solePreferences),\n+\t\t\t\t}\n+\t\t\t: null;\n+\t\tfor (const obligationSolution of soleSolution ? [] : previewSolutions) {\n \t\t\tyield;\n \t\t\tcontext.check();\n \t\t\tconst obligationPath = context.obligationSolutionBranches.get(obligationSolution) ?? [];\n@@ -6644,8 +6531,11 @@ function* calculatePlanningSteps(\n \t\t\tcontext.traceBranchActive = true;\n \t\t\tcontext.traceBranchParentId = obligationPath.at(-1)?.decisionId;\n \t\t\ttry {\n-\t\t\t\tconst atRiskState = yield* placeAtRisk(cloneState(obligationSolution), context);\n-\t\t\t\tconst preview = yield* applyPreferenceRules(atRiskState, preferenceRules, context);\n+\t\t\t\tconst preview = yield* applyPreferenceRules(\n+\t\t\t\t\tcloneState(obligationSolution),\n+\t\t\t\t\tpreferenceRules,\n+\t\t\t\t\tcontext,\n+\t\t\t\t);\n \t\t\t\tconst previewState = finalizeEarnedState(preview.state, context);\n \t\t\t\tif (!previewState) continue;\n \t\t\t\tconst candidate = {\n@@ -6655,7 +6545,7 @@ function* calculatePlanningSteps(\n \t\t\t\t\tmetrics: qualityMetrics(previewState, context, preview.preferences),\n \t\t\t\t};\n \t\t\t\tconst compared: number | undefined = bestPreview\n-\t\t\t\t\t? compareObligationPreviews(candidate, bestPreview)\n+\t\t\t\t\t? compareObligationPreviews(candidate, bestPreview, context)\n \t\t\t\t\t: undefined;\n \t\t\t\tconst branch: ObligationBranchReference | undefined =\n \t\t\t\t\tcompared !== undefined\n@@ -6665,7 +6555,12 @@ function* calculatePlanningSteps(\n \t\t\t\t\t\t\t\tpreviewState,\n \t\t\t\t\t\t\t\tcontext.traceBranchParentId,\n \t\t\t\t\t\t\t\t[],\n-\t\t\t\t\t\t\t\t() => obligationPreviewComparisonFacts(candidate, bestPreview!),\n+\t\t\t\t\t\t\t\t() =>\n+\t\t\t\t\t\t\t\t\tobligationPreviewComparisonFacts(\n+\t\t\t\t\t\t\t\t\t\tcandidate,\n+\t\t\t\t\t\t\t\t\t\tbestPreview!,\n+\t\t\t\t\t\t\t\t\t\tcontext,\n+\t\t\t\t\t\t\t\t\t),\n \t\t\t\t\t\t\t)\n \t\t\t\t\t\t: undefined;\n \t\t\t\tconst previewCandidate: ObligationPreview = {\n@@ -6690,22 +6585,10 @@ function* calculatePlanningSteps(\n \t\t\t);\n \t\tstages.push('obligations');\n \t\tpublishCheckpoint();\n-\t\tmarkProgress(context, 'at-risk');\n-\t\tyield true;\n-\t\tcontext.protectedTypesByDate = futurePreferenceProtection(normalized.rules, 0, context);\n-\t\tcontext.reservedTypes = new Set(\n-\t\t\tobligationRequirements\n-\t\t\t\t.filter((requirement) => requirement.requiredPlacements > 0)\n-\t\t\t\t.map((requirement) => requirement.rule.placeType)\n-\t\t\t\t.filter((selector): selector is LeaveType => selector !== 'any'),\n-\t\t);\n-\t\tstate = yield* placeAtRisk(state, context);\n-\t\tstages.push('at-risk');\n-\t\tpublishCheckpoint();\n \t\tfor (let preferenceIndex = 0; preferenceIndex < preferenceRules.length; preferenceIndex++) {\n \t\t\tyield;\n \t\t\tconst rule = preferenceRules[preferenceIndex];\n-\t\t\tmarkProgress(context, `preference:${rule.id}`);\n+\t\t\tmarkProgress(context, ruleStage(rule));\n \t\t\tyield true;\n \t\t\tstate = yield* applyPreferenceStep(\n \t\t\t\tstate,\n@@ -6714,64 +6597,16 @@ function* calculatePlanningSteps(\n \t\t\t\tpreferences,\n \t\t\t\tcontext,\n \t\t\t);\n-\t\t\tstages.push(`preference:${rule.id}`);\n+\t\t\tstages.push(ruleStage(rule));\n \t\t\tpublishCheckpoint();\n \t\t}\n-\t\tmarkProgress(context, 'holiday-week-value');\n-\t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeHolidayWeeks(state, context, preferences);\n-\t\tstages.push('holiday-week-value');\n-\t\tpublishCheckpoint();\n-\t\tmarkProgress(context, 'non-working-day-gain');\n-\t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeMovablePlacements(\n-\t\t\tstate,\n-\t\t\tcontext,\n-\t\t\tpreferences,\n-\t\t\t'non-working-day-gain',\n-\t\t);\n-\t\tstages.push('non-working-day-gain');\n-\t\tpublishCheckpoint();\n-\t\tmarkProgress(context, 'longest-work-sequence');\n-\t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeMovablePlacements(\n-\t\t\tstate,\n-\t\t\tcontext,\n-\t\t\tpreferences,\n-\t\t\t'longest-work-sequence',\n-\t\t);\n-\t\tstages.push('longest-work-sequence');\n-\t\tpublishCheckpoint();\n-\t\tmarkProgress(context, 'short-sequence-deficit');\n-\t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeMovablePlacements(\n-\t\t\tstate,\n-\t\t\tcontext,\n-\t\t\tpreferences,\n-\t\t\t'short-sequence-deficit',\n-\t\t);\n-\t\tstages.push('short-sequence-deficit');\n-\t\tpublishCheckpoint();\n-\t\tmarkProgress(context, 'supporting-placements');\n-\t\tyield true;\n-\t\tstate = yield* supportingPlacements(state, context, preferences);\n-\t\tstate = yield* pruneRedundantSupportingPlacements(state, context, preferences);\n-\t\tstages.push('supporting-placements');\n-\t\tpublishCheckpoint();\n \t\tmarkProgress(context, 'expiry');\n \t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeExpiryPlacements(state, context, preferences);\n+\t\tstate = yield* optimizeRulePlacements(state, context, preferenceRules.length - 1, false);\n \t\tstages.push('expiry');\n \t\tpublishCheckpoint();\n \t\tmarkProgress(context, 'dates');\n \t\tyield true;\n-\t\tcontext.check();\n-\t\tstate = yield* optimizeMovablePlacements(state, context, preferences, 'dates');\n \t\tstages.push('dates');\n \t\tconst finalized = finalizeEarnedState(state, context);\n \t\tif (!finalized) {\n@@ -6800,7 +6635,10 @@ function* calculatePlanningSteps(\n \t\t\tconst partialPreferences = retained.preferences.map((preference) => ({\n \t\t\t\t...preference,\n \t\t\t\treason: preferenceReason(\n-\t\t\t\t\tnormalized.rules.find((rule) => rule.id === preference.ruleId)!,\n+\t\t\t\t\tnormalized.rules.find(\n+\t\t\t\t\t\t(rule): rule is NormalizedCalendarRule =>\n+\t\t\t\t\t\t\trule.type !== 'optimization' && rule.id === preference.ruleId,\n+\t\t\t\t\t)!,\n \t\t\t\t\tpreference.satisfied,\n \t\t\t\t\tcontext,\n \t\t\t\t\tretained!.state,\n@@ -6894,6 +6732,7 @@ export function explainIncompleteCheckpoint(\n \t\t\ttraceReportedTime: 0,\n \t\t\tobserverTime: 0,\n \t\t\tobligationSolutionBranches: new WeakMap(),\n+\t\t\tcompletedPreferenceStates: new Map(),\n \t\t} as SearchContext;\n \t\tcontext.holidayWeeks = holidayWeekCandidates(context);\n \t\tconst state: State = {\n@@ -6998,6 +6837,7 @@ function counterfactualContext(\n \t\ttraceReportedTime: 0,\n \t\tobserverTime: 0,\n \t\tobligationSolutionBranches: new WeakMap(),\n+\t\tcompletedPreferenceStates: new Map(),\n \t} as SearchContext;\n \tcontext.holidayWeeks = holidayWeekCandidates(context);\n \treturn context;\n@@ -7107,13 +6947,7 @@ function objectiveComparison(\n \t\t\tlabel: objective.label,\n \t\t};\n \t});\n-\tconst first = after.objectives.findIndex(\n-\t\t(objective, index) =>\n-\t\t\t!sameObjectiveValue(\n-\t\t\t\tobjective.value,\n-\t\t\t\tbefore.objectives[index]?.value ?? objective.value,\n-\t\t\t),\n-\t);\n+\tconst first = firstDifferentObjective(after.objectives, before.objectives);\n \tconst decisive = first >= 0 ? after.objectives[first].id : undefined;\n \treturn {\n \t\tbefore,\n@@ -7139,6 +6973,7 @@ function counterfactualRuleValid(\n \tfor (const ruleId of ruleIds) {\n \t\tconst rule = context.rules.find((candidate) => candidate.id === ruleId);\n \t\tif (!rule) return false;\n+\t\tif (rule.type === 'optimization') continue;\n \t\tif (rule.type === 'time_window') {\n \t\t\tif (\n \t\t\t\t!selectorMatches(rule.placeType, type) ||\n@@ -7170,7 +7005,9 @@ function counterfactualObligationsValid(\n \tprevious: State,\n ): boolean {\n \treturn context.rules\n-\t\t.filter((rule) => rule.enabled && rule.force === 'obligation')\n+\t\t.filter(\n+\t\t\t(rule): rule is NormalizedCalendarRule => rule.enabled && rule.force === 'obligation',\n+\t\t)\n \t\t.every((rule) => {\n \t\t\tif (rule.type === 'time_window') {\n \t\t\t\tconst count = (candidate: State) =>\n@@ -7202,7 +7039,7 @@ function preferenceResultsForState(state: State, context: SearchContext): Prefer\n \t\tpatternsByRule = new Map(\n \t\t\tcontext.rules\n \t\t\t\t.filter(\n-\t\t\t\t\t(rule) =>\n+\t\t\t\t\t(rule): rule is NormalizedCalendarRule =>\n \t\t\t\t\t\trule.enabled && rule.force === 'preference' && rule.type === 'if_then',\n \t\t\t\t)\n \t\t\t\t.map((rule) => [\n@@ -7215,17 +7052,26 @@ function preferenceResultsForState(state: State, context: SearchContext): Prefer\n \t\tpreferencePatternCache.set(context, patternsByRule);\n \t}\n \treturn context.rules\n-\t\t.filter((rule) => rule.enabled && rule.force === 'preference')\n+\t\t.filter(\n+\t\t\t(rule): rule is NormalizedCalendarRule =>\n+\t\t\t\trule.enabled && rule.force === 'preference' && rule.type !== 'optimization',\n+\t\t)\n \t\t.map((rule) => {\n \t\t\tconst occurrencePatterns = patternsByRule.get(rule.id) ?? [];\n \t\t\tconst requested =\n \t\t\t\trule.type === 'time_window' ? rule.placeDays : occurrencePatterns.length;\n \t\t\tconst satisfied =\n \t\t\t\trule.type === 'time_window'\n-\t\t\t\t\t? declaredWindowDays(rule, context).length +\n-\t\t\t\t\t\t[...state.placements.values()].filter((placement) =>\n-\t\t\t\t\t\t\tplacement.ruleIds.has(rule.id),\n-\t\t\t\t\t\t).length\n+\t\t\t\t\t? Math.min(\n+\t\t\t\t\t\t\trule.placeDays,\n+\t\t\t\t\t\t\tdeclaredWindowDays(rule, context).length +\n+\t\t\t\t\t\t\t\t[...state.placements.values()].filter(\n+\t\t\t\t\t\t\t\t\t(placement) =>\n+\t\t\t\t\t\t\t\t\t\tplacement.date >= rule.startDate! &&\n+\t\t\t\t\t\t\t\t\t\tplacement.date <= rule.endDate! &&\n+\t\t\t\t\t\t\t\t\t\tselectorMatches(rule.placeType, placement.type),\n+\t\t\t\t\t\t\t\t).length,\n+\t\t\t\t\t\t)\n \t\t\t\t\t: occurrencePatterns.filter((patterns) =>\n \t\t\t\t\t\t\tpatterns.some((pattern) =>\n \t\t\t\t\t\t\t\tpattern.every((date) =>\n@@ -7305,9 +7151,7 @@ export function analyzeCounterfactualInternal(\n \tconst released = baseline.balances.find((balance) => balance.id === selected.balanceId);\n \tif (released && removed?.balanceId === selected.balanceId) released.remaining++;\n \tconst beforeState = options?.compareOriginalState ? comparisonState : baseline;\n-\tconst beforePreferences = preferenceResultsForState(beforeState, context);\n-\tconst beforeMetrics = qualityMetrics(beforeState, context, beforePreferences);\n-\tconst before = objectiveVector(beforeMetrics, beforePreferences, beforeState, context);\n+\tconst before = objectiveVector(beforeState, context);\n \tconst results: CounterfactualDateResult[] = [];\n \tfor (const date of dateRange(horizon.start, horizon.end)) {\n \t\tlet ineligible: (PlanningReason & { code: CounterfactualReasonCode }) | undefined;\n@@ -7404,9 +7248,7 @@ export function analyzeCounterfactualInternal(\n \t\t\t});\n \t\t\tcontinue;\n \t\t}\n-\t\tconst afterPreferences = preferenceResultsForState(finalized, context);\n-\t\tconst afterMetrics = qualityMetrics(finalized, context, afterPreferences);\n-\t\tconst after = objectiveVector(afterMetrics, afterPreferences, finalized, context);\n+\t\tconst after = objectiveVector(finalized, context);\n \t\tconst comparison = objectiveComparison(before, after);\n \t\tresults.push({ date, status: 'eligible', comparison });\n \t}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner.core.ts", "project_id": 35, "relative_order": 26, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,3 +1,4 @@\n+import { createOptimizationPresetRules } from './rule-service';\n import { vi } from 'vitest';\n import {\n \tapplyReplayDeltas,\n@@ -15,6 +16,18 @@ import type {\n \tPlanningTraceUpdate,\n } from './leave-planner.service';\n import type { CounterfactualBaselineOptions } from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+\n+const supportingEconomy = {\n+\tid: 'economy',\n+\ttype: 'optimization' as const,\n+\tconfiguration: OPTIMIZATION_PRESETS.supportingPlacements,\n+};\n+const nonWorkingGain = {\n+\tid: 'gain',\n+\ttype: 'optimization' as const,\n+\tconfiguration: OPTIMIZATION_PRESETS.nonWorkingDayGain,\n+};\n \n const horizon = { start: '2024-01-01', end: '2025-01-01' };\n const balance = (\n@@ -48,6 +61,8 @@ async function runInNonBrowser(request: Parameters[0]) {\n beforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n afterEach(() => vi.useRealTimers());\n \n+const presets = createOptimizationPresetRules();\n+\n describe('calculated work-sequence and time-off-period statistics', () => {\n \tit('keeps fractional work means and merges consecutive declared days across a weekend', async () => {\n \t\tconst result = isPlan(\n@@ -1292,7 +1307,7 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-01-02', end: '2024-01-06' },\n \t\t\t\tbalances: [balance('remaining-cp', 'cp', 4, '2024-01-05')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays,\n \t\t\t}),\n \t\t);\n@@ -1358,7 +1373,7 @@ describe('planLeave', () => {\n \t\t\t\tbalances: [\n \t\t\t\t\t{ ...balance('cp', 'cp', 1, '2024-05-13'), availableFrom: '2024-05-13' },\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays,\n \t\t\t}),\n \t\t);\n@@ -1438,7 +1453,7 @@ describe('planLeave', () => {\n \t\t\t\tbalances: [\n \t\t\t\t\t{ ...balance('cp', 'cp', 2, '2024-01-04'), availableFrom: '2024-01-04' },\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays,\n \t\t\t}),\n \t\t);\n@@ -1466,7 +1481,7 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: selectedHorizon,\n \t\t\t\tbalances: [],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays: declaredDays.filter(({ date }) => date !== '2024-01-03'),\n \t\t\t}),\n \t\t);\n@@ -1521,7 +1536,7 @@ describe('planLeave', () => {\n \t\t\tconst result = isPlan(\n \t\t\t\tawait runInNonBrowser({\n \t\t\t\t\thorizon: { start, end },\n-\t\t\t\t\trules: [],\n+\t\t\t\t\trules: [presets[0]],\n \t\t\t\t\tdeclaredDays,\n \t\t\t\t\tbalances: mixed\n \t\t\t\t\t\t? [{ ...balance('cp', 'cp', 1, '2024-05-10'), availableFrom: '2024-05-10' }]\n@@ -1602,7 +1617,7 @@ describe('planLeave', () => {\n \t\tconst request: PlanningRequest = {\n \t\t\thorizon: { start: '2026-11-01', end: '2026-12-01' },\n \t\t\tbalances: [balance('cp', 'cp', 2, '2026-11-30')],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t\tdeclaredDays: [\n \t\t\t\t{ date: '2026-11-09', type: 'other' },\n \t\t\t\t{ date: '2026-11-10', type: 'rtt' },\n@@ -1619,15 +1634,19 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\t...request,\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'preferred-friday',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tstartDate: '2026-11-20',\n-\t\t\t\t\t\tendDate: '2026-11-20',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'preferred-friday',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tstartDate: '2026-11-20',\n+\t\t\t\t\t\t\tendDate: '2026-11-20',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t}),\n \t\t);\n@@ -1927,7 +1946,7 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon,\n \t\t\t\tbalances: [balance('cp', 'cp', 1), balance('rtt', 'rtt', 1)],\n-\t\t\t\trules,\n+\t\t\t\trules: [presets[0], ...rules],\n \t\t\t}),\n \t\t);\n \n@@ -2015,15 +2034,18 @@ describe('planLeave', () => {\n \t\t\t\t\t},\n \t\t\t\t],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'rtt-obligation',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-01-02',\n-\t\t\t\t\t\tendDate: '2024-01-03',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'rtt',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'rtt-obligation',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\t\tstartDate: '2024-01-02',\n+\t\t\t\t\t\t\tendDate: '2024-01-03',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'rtt',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n \t\t\t\t],\n \t\t\t}),\n \t\t);\n@@ -2256,20 +2278,28 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-01-05', end: '2024-01-10' },\n \t\t\t\tbalances: [balance('cp', 'cp', 1, '2025-01-01')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [nonWorkingGain, supportingEconomy],\n \t\t\t}),\n \t\t);\n \t\tconst supporting = result.placements.find((placement) => placement.supporting);\n-\t\texpect(supporting?.ruleIds).toEqual([]);\n+\t\texpect(supporting?.ruleIds).toEqual(['gain']);\n \t\texpect(supporting?.balanceId).toBe('cp');\n \t});\n \n-\tit('does not trade a short-sequence deficit for supporting placement gain', async () => {\n+\tit('does not trade an earlier short-sequence deficit for supporting placement gain', async () => {\n \t\tconst result = isPlan(\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n \t\t\t\tbalances: [balance('cp-four', 'cp', 4, '2025-01-01')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'deficit',\n+\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\t\t},\n+\t\t\t\t\tnonWorkingGain,\n+\t\t\t\t\tsupportingEconomy,\n+\t\t\t\t],\n \t\t\t}),\n \t\t);\n \t\texpect(result.metrics.shortSequenceDeficit).toBe(0);\n@@ -2280,7 +2310,15 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-01-29' },\n \t\t\t\tbalances: [balance('cp-six', 'cp', 6, '2025-01-01')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [\n+\t\t\t\t\tnonWorkingGain,\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'longest',\n+\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.longestWorkSequence,\n+\t\t\t\t\t},\n+\t\t\t\t\tsupportingEconomy,\n+\t\t\t\t],\n \t\t\t}),\n \t\t);\n \t\texpect(result.metrics.supportingPlacements).toBe(\n@@ -2295,19 +2333,24 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-02-01', end: '2024-03-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 2, '2024-02-29')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t}),\n \t\t);\n \t\tconst fourDayPlan = isPlan(\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2024-02-01', end: '2024-03-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 4, '2024-02-29')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t}),\n \t\t);\n+\t\texpect(twoDayPlan.metrics).toMatchObject({\n+\t\t\tnonWorkingDayGain: 4,\n+\t\t\tlongestWorkSequence: 9,\n+\t\t\tshortSequenceDeficit: 0,\n+\t\t});\n \t\texpect(twoDayPlan.placements.map((placement) => placement.date)).toEqual([\n-\t\t\t'2024-02-09',\n-\t\t\t'2024-02-19',\n+\t\t\t'2024-02-02',\n+\t\t\t'2024-02-16',\n \t\t]);\n \t\texpect(fourDayPlan.placements.map((placement) => placement.date)).toEqual([\n \t\t\t'2024-02-02',\n@@ -2335,7 +2378,7 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: holidayHorizon,\n \t\t\t\tbalances: [balance('cp', 'cp', 4, expiryDate)],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t}),\n \t\t);\n \n@@ -2344,7 +2387,7 @@ describe('planLeave', () => {\n \t\texpect(result.timeOffPeriods[0].duration).toBe(9);\n \t});\n \n-\t// Async calculation yields to the test timer; allow the planner's ten-second budget.\n+\t// This full configured year is measured separately; allow instrumentation overhead without a planning deadline.\n \tit('uses the 11 November and 14 July weeks in the representative default plan', async () => {\n \t\tconst result = isPlan(\n \t\t\tawait runInNonBrowser({\n@@ -2364,28 +2407,32 @@ describe('planLeave', () => {\n \t\t\t\t\t},\n \t\t\t\t],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'default-samedi-malin',\n-\t\t\t\t\t\tname: 'Samedi Malin',\n-\t\t\t\t\t\ttype: 'if_then',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tdayOfWeek: 6,\n-\t\t\t\t\t\tplaceDays: 2,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t\tplacement: 'auto',\n-\t\t\t\t\t\trewardDays: 1,\n-\t\t\t\t\t\trewardType: 'other',\n-\t\t\t\t\t},\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'default-christmas',\n-\t\t\t\t\t\tname: 'Christmas holidays',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tstartDate: '2026-12-20',\n-\t\t\t\t\t\tendDate: '2027-01-03',\n-\t\t\t\t\t\tplaceDays: 5,\n-\t\t\t\t\t\tplaceType: 'any',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'default-samedi-malin',\n+\t\t\t\t\t\t\tname: 'Samedi Malin',\n+\t\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tdayOfWeek: 6,\n+\t\t\t\t\t\t\tplaceDays: 2,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t\tplacement: 'auto',\n+\t\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\t\trewardType: 'other',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'default-christmas',\n+\t\t\t\t\t\t\tname: 'Christmas holidays',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tstartDate: '2026-12-20',\n+\t\t\t\t\t\t\tendDate: '2027-01-03',\n+\t\t\t\t\t\t\tplaceDays: 5,\n+\t\t\t\t\t\t\tplaceType: 'any',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t}),\n \t\t);\n@@ -2402,7 +2449,7 @@ describe('planLeave', () => {\n \t\t\t\t'2027-07-16',\n \t\t\t]),\n \t\t);\n-\t}, 15_000);\n+\t}, 120_000);\n \n \tit('moves a satisfied time-window preference to complete a holiday week', async () => {\n \t\tconst result = isPlan(\n@@ -2410,15 +2457,19 @@ describe('planLeave', () => {\n \t\t\t\thorizon: { start: '2027-07-01', end: '2027-08-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 4, '2027-07-31')],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'july',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'preference',\n-\t\t\t\t\t\tstartDate: '2027-07-01',\n-\t\t\t\t\t\tendDate: '2027-07-31',\n-\t\t\t\t\t\tplaceDays: 4,\n-\t\t\t\t\t\tplaceType: 'any',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'july',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\t\t\tstartDate: '2027-07-01',\n+\t\t\t\t\t\t\tendDate: '2027-07-31',\n+\t\t\t\t\t\t\tplaceDays: 4,\n+\t\t\t\t\t\t\tplaceType: 'any',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t}),\n \t\t);\n@@ -2437,7 +2488,14 @@ describe('planLeave', () => {\n \t\t\tawait runInNonBrowser({\n \t\t\t\thorizon: { start: '2027-07-01', end: '2027-08-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 4, '2028-07-31')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'holiday',\n+\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.holidayWeekValue,\n+\t\t\t\t\t},\n+\t\t\t\t\tsupportingEconomy,\n+\t\t\t\t],\n \t\t\t}),\n \t\t);\n \n@@ -2456,15 +2514,19 @@ describe('planLeave', () => {\n \t\t\t\thorizon: { start: '2024-01-08', end: '2024-01-15' },\n \t\t\t\tbalances: [balance('cp', 'cp', 1)],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'window',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-01-09',\n-\t\t\t\t\t\tendDate: '2024-01-12',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'window',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\t\tstartDate: '2024-01-09',\n+\t\t\t\t\t\t\tendDate: '2024-01-12',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t}),\n \t\t);\n@@ -2749,15 +2811,19 @@ describe('planLeave', () => {\n \t\t\t\t\t},\n \t\t\t\t],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'fixed',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-05-06',\n-\t\t\t\t\t\tendDate: '2024-05-06',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'fixed',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\t\tstartDate: '2024-05-06',\n+\t\t\t\t\t\t\tendDate: '2024-05-06',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\t...presets.slice(1),\n \t\t\t\t],\n \t\t\t};\n \t\t\tconst expected = isPlan(await runInNonBrowser(request));\n@@ -2767,7 +2833,8 @@ describe('planLeave', () => {\n \t\t\t\tconst outcome = await runInNonBrowser({\n \t\t\t\t\t...request,\n \t\t\t\t\tprogress: (stage) => {\n-\t\t\t\t\t\tif (stage === 'at-risk') queueMicrotask(() => (elapsed = 20_000));\n+\t\t\t\t\t\tif (stage === 'optimization:default-unplaced-at-risk')\n+\t\t\t\t\t\t\tqueueMicrotask(() => (elapsed = 20_000));\n \t\t\t\t\t},\n \t\t\t\t});\n \t\t\t\texpect(elapsed).toBeGreaterThan(10_000);\n@@ -2953,8 +3020,8 @@ describe('planLeave transport', () => {\n \t\tif (expected.kind !== 'Plan' || !checkpointState) return;\n \t\tcheckpoint = {\n \t\t\t...expected,\n-\t\t\tcompletedStages: ['validation', 'obligations', 'at-risk'],\n-\t\t\tlastCompletedStage: 'at-risk',\n+\t\t\tcompletedStages: ['validation', 'obligations', 'optimization:default-unplaced-at-risk'],\n+\t\t\tlastCompletedStage: 'optimization:default-unplaced-at-risk',\n \t\t};\n \t\tconst initialState: PlanningTraceState = {\n \t\t\thorizon: request.horizon,\n@@ -3271,7 +3338,7 @@ describe('planning calculation context', () => {\n \t\t\tconst calculation = createPlanningCalculation(submitted);\n \t\t\tsubmitted.declaredDays![0].date = '2024-01-11';\n \t\t\tsubmitted.declaredDays![0].type = 'rtt';\n-\t\t\tsubmitted.rules[0].placeDays = 4;\n+\t\t\tif ('placeDays' in submitted.rules[0]) submitted.rules[0].placeDays = 4;\n \t\t\tif ('endDate' in submitted.rules[0]) submitted.rules[0].endDate = '2024-01-19';\n \t\t\tsubmitted.horizon.end = '2024-01-11';\n \t\t\tsubmitted.labels = { exact: 'Edited later' };\n@@ -3378,7 +3445,7 @@ describe('planning calculation context', () => {\n \t\t\t\tbalances: [\n \t\t\t\t\t{ ...balance('cp', 'cp', 1, '2024-12-30'), availableFrom: '2024-12-30' },\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays,\n \t\t\t});\n \t\t\tconst outcome = isPlan(await calculation.outcome);\n@@ -3407,7 +3474,7 @@ describe('planning calculation context', () => {\n \t\t\tconst submitted: PlanningRequest = {\n \t\t\t\thorizon: { start: '2026-11-01', end: '2026-12-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 2, '2026-11-30')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t\tdeclaredDays: [\n \t\t\t\t\t{ date: '2026-11-09', type: 'other' },\n \t\t\t\t\t{ date: '2026-11-10', type: 'rtt' },\n@@ -3427,7 +3494,9 @@ describe('planning calculation context', () => {\n \t\t\tfor (const placement of explanation.placements) {\n \t\t\t\texpect(placement.timeOffPeriod).toEqual(outcome.timeOffPeriods[0]);\n \t\t\t\texpect(placement.finalMetrics).toEqual(outcome.metrics);\n-\t\t\t\texpect(placement.firstDecisiveObjective).toBe('unplaced-at-risk');\n+\t\t\t\texpect(placement.firstDecisiveObjective).toBe(\n+\t\t\t\t\t'optimization:default-unplaced-at-risk',\n+\t\t\t\t);\n \t\t\t}\n \t\t\tconst trace = await calculation.trace;\n \t\t\texpect(trace?.initialState.declaredDays).toEqual(original);\n@@ -3446,11 +3515,13 @@ describe('planning calculation context', () => {\n \t\t\t\t\t(candidate) =>\n \t\t\t\t\t\tcandidate.comparison?.after.objectives.some(\n \t\t\t\t\t\t\t(objective) =>\n-\t\t\t\t\t\t\t\tobjective.id === 'holiday-week-value' && objective.value === 3,\n+\t\t\t\t\t\t\t\tobjective.id === 'optimization:default-holiday-week-value' &&\n+\t\t\t\t\t\t\t\tobjective.value === 3,\n \t\t\t\t\t\t) &&\n \t\t\t\t\t\tcandidate.comparison.after.objectives.some(\n \t\t\t\t\t\t\t(objective) =>\n-\t\t\t\t\t\t\t\tobjective.id === 'non-working-day-gain' && objective.value === 5,\n+\t\t\t\t\t\t\t\tobjective.id === 'optimization:default-non-working-day-gain' &&\n+\t\t\t\t\t\t\t\tobjective.value === 5,\n \t\t\t\t\t\t),\n \t\t\t\t),\n \t\t\t).toBe(true);\n@@ -3463,10 +3534,16 @@ describe('planning calculation context', () => {\n \t\t\tconst alternative = analysis.results.find(({ date }) => date === '2026-11-20');\n \t\t\texpect(alternative?.status).toBe('eligible');\n \t\t\texpect(alternative?.comparison?.after.objectives).toContainEqual(\n-\t\t\t\texpect.objectContaining({ id: 'holiday-week-value', value: 0 }),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tid: 'optimization:default-holiday-week-value',\n+\t\t\t\t\tvalue: 0,\n+\t\t\t\t}),\n \t\t\t);\n \t\t\texpect(alternative?.comparison?.after.objectives).toContainEqual(\n-\t\t\t\texpect.objectContaining({ id: 'non-working-day-gain', value: 7 }),\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\tid: 'optimization:default-non-working-day-gain',\n+\t\t\t\t\tvalue: 7,\n+\t\t\t\t}),\n \t\t\t);\n \t\t\texpect(outcome).toEqual(before);\n \t\t} finally {\n@@ -3481,7 +3558,7 @@ describe('planning calculation context', () => {\n \t\t\tconst submitted: PlanningRequest = {\n \t\t\t\thorizon: { start: '2024-01-02', end: '2024-02-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 4, '2024-01-05')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t\tdeclaredDays: [\n \t\t\t\t\t{ date: '2024-01-02', type: 'cp' },\n \t\t\t\t\t{ date: '2024-01-03', type: 'rtt' },\n@@ -3828,7 +3905,7 @@ describe('planning calculation context', () => {\n \t\t\tconst calculation = createPlanningCalculation({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\t\tbalances: [balance('cp', 'cp', 1, '2024-12-31')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[3]],\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n \t\t\texpect(outcome.kind).toBe('Plan');\n@@ -3886,7 +3963,7 @@ describe('planning calculation context', () => {\n \t\t\tif (!firstOccurrence || !secondOccurrence) return;\n \n \t\t\tconst alternateSecondDate =\n-\t\t\t\tsecondOccurrence.date === '2024-05-07' ? '2024-05-09' : '2024-05-07';\n+\t\t\t\tsecondOccurrence.date === '2024-05-07' ? '2024-05-10' : '2024-05-07';\n \t\t\tconst analysis = await calculation.analyzeCounterfactual(firstOccurrence);\n \t\t\texpect(analysis.kind).toBe('Counterfactual');\n \t\t\tif (analysis.kind !== 'Counterfactual') return;\n@@ -3976,7 +4053,7 @@ describe('planning calculation context', () => {\n \t\t\tconst calculation = createPlanningCalculation({\n \t\t\t\thorizon: { start: '2024-01-05', end: '2024-01-10' },\n \t\t\t\tbalances: [balance('cp', 'cp', 1, '2025-01-01')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [nonWorkingGain, supportingEconomy],\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n \t\t\texpect(outcome.kind).toBe('Plan');\n@@ -3991,7 +4068,7 @@ describe('planning calculation context', () => {\n \t\t\tconst restored = analysis.results.find((result) => result.date === selected.date);\n \t\t\texpect(\n \t\t\t\trestored?.comparison?.after.objectives.find(\n-\t\t\t\t\t(objective) => objective.id === 'supporting-placements',\n+\t\t\t\t\t(objective) => objective.id === 'optimization:economy',\n \t\t\t\t)?.value,\n \t\t\t).toBe(1);\n \t\t} finally {\n@@ -4097,7 +4174,7 @@ describe('planning calculation context', () => {\n \t\t\tconst older = createPlanningCalculation({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\t\tbalances: [balance('cp', 'cp', 1)],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[3]],\n \t\t\t});\n \t\t\tconst olderOutcome = await older.outcome;\n \t\t\texpect(olderOutcome.kind).toBe('Plan');\n@@ -4116,7 +4193,7 @@ describe('planning calculation context', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\tbalances: [balance('cp', 'cp', 1)],\n-\t\t\trules: [],\n+\t\t\trules: [presets[3]],\n \t\t};\n \t\tconst expected = isPlan(await runInNonBrowser(request));\n \t\tconst selected = expected.placements[0];\n@@ -4213,7 +4290,7 @@ describe('planning calculation context', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\tbalances: [balance('cp', 'cp', 1)],\n-\t\t\trules: [],\n+\t\t\trules: [presets[3]],\n \t\t};\n \t\tconst expected = isPlan(await runInNonBrowser(request));\n \t\tconst trace = {\n@@ -4343,15 +4420,18 @@ describe('planning calculation context', () => {\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 2, '2024-01-31')],\n \t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'wide',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-01-01',\n-\t\t\t\t\t\tendDate: '2024-01-31',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t...[\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'wide',\n+\t\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\t\tstartDate: '2024-01-01',\n+\t\t\t\t\t\t\tendDate: '2024-01-31',\n+\t\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n \t\t\t\t],\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n@@ -4404,7 +4484,7 @@ describe('planning calculation context', () => {\n \t\t\t\t\t\tavailableFrom: '2024-01-04',\n \t\t\t\t\t},\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: [presets[0]],\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n \t\t\tconst trace = await calculation.trace;\n@@ -4466,7 +4546,7 @@ describe('planning calculation context', () => {\n \t\tconst request = {\n \t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n \t\t\tbalances: [balance('cp', 'cp', 1)],\n-\t\t\trules: [],\n+\t\t\trules: [presets[3]],\n \t\t};\n \t\tconst plan = isPlan(await runInNonBrowser(request));\n \t\tconst firstPlacement = plan.placements[0];\n@@ -4745,81 +4825,98 @@ describe('planning calculation context', () => {\n \t});\n \n \tit('does not inherit unrelated rule-invalid history into a trace decision', async () => {\n+\t\tconst core = await import('./leave-planner.core');\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n+\t\t\tbalances: [balance('cp', 'cp', 1, '2024-01-10')],\n+\t\t\trules: [presets[0]],\n+\t\t};\n+\t\tlet artifacts: import('./leave-planner.core').PlanningArtifacts = {};\n+\t\tconst outcome = core.calculatePlanningInternal(\n+\t\t\trequest,\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\texpect(outcome.kind).toBe('Plan');\n+\t\tconst trace = artifacts.trace && {\n+\t\t\t...artifacts.trace,\n+\t\t\tphases: [...artifacts.trace.phases],\n+\t\t};\n+\t\tartifacts = { ...artifacts, trace };\n+\t\tif (outcome.kind !== 'Plan' || !trace)\n+\t\t\tthrow new Error('Expected an actual plan and trace.');\n+\t\tconst decision = trace.phases\n+\t\t\t.flatMap((phase) => phase.decisions)\n+\t\t\t.find((item) => item.deltas.some((delta) => delta.kind === 'placement-added'));\n+\t\tconst placement = decision?.deltas.find(\n+\t\t\t(delta) => delta.kind === 'placement-added',\n+\t\t)?.placement;\n+\t\tif (!decision || !placement) throw new Error('Expected an actual placement decision.');\n+\t\t// An unrelated decision's rejection must not become the selected decision's history.\n+\t\tconst unrelatedDate = '2024-01-04';\n+\t\tdecision.candidates = decision.candidates.filter(\n+\t\t\t(candidate) =>\n+\t\t\t\t!(candidate.dates ?? (candidate.date ? [candidate.date] : [])).includes(\n+\t\t\t\t\tunrelatedDate,\n+\t\t\t\t),\n+\t\t);\n+\t\ttrace.phases.push({\n+\t\t\tid: 'unrelated-phase',\n+\t\t\tname: 'unrelated',\n+\t\t\tcompleted: true,\n+\t\t\tstatus: 'completed',\n+\t\t\tdecisions: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'unrelated-decision',\n+\t\t\t\t\taction: 'reject',\n+\t\t\t\t\tdates: [unrelatedDate],\n+\t\t\t\t\tdeltas: [],\n+\t\t\t\t\tcandidates: [\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tstatus: 'ineligible',\n+\t\t\t\t\t\t\tdate: unrelatedDate,\n+\t\t\t\t\t\t\treason: {\n+\t\t\t\t\t\t\t\tcode: 'rule-invalid',\n+\t\t\t\t\t\t\t\tmessage: 'Another decision rejected this date.',\n+\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\tclass HistoricalTraceWorker {\n+\t\t\tonmessage: ((event: MessageEvent) => void) | null = null;\n+\t\t\tonerror: (() => void) | null = null;\n+\t\t\tpostMessage(): void {\n+\t\t\t\tqueueMicrotask(() => {\n+\t\t\t\t\tthis.onmessage?.({ data: { type: 'result', outcome } } as MessageEvent);\n+\t\t\t\t\tthis.onmessage?.({ data: { type: 'artifacts', artifacts } } as MessageEvent);\n+\t\t\t\t});\n+\t\t\t}\n+\t\t\tterminate(): void {}\n+\t\t}\n \t\tconst browserWindow = globalThis.window;\n-\t\tvi.stubGlobal('window', undefined);\n+\t\tvi.stubGlobal('window', {});\n+\t\tvi.stubGlobal('Worker', HistoricalTraceWorker);\n \t\ttry {\n-\t\t\tconst calculation = createPlanningCalculation({\n-\t\t\t\thorizon: { start: '2024-01-01', end: '2024-01-10' },\n-\t\t\t\tbalances: [balance('cp', 'cp', 1, '2024-01-31')],\n-\t\t\t\trules: [\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'early-window',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-01-02',\n-\t\t\t\t\t\tendDate: '2024-01-04',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n-\t\t\t\t\t{\n-\t\t\t\t\t\tid: 'late-window',\n-\t\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\t\tstartDate: '2024-01-03',\n-\t\t\t\t\t\tendDate: '2024-01-05',\n-\t\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t\t},\n-\t\t\t\t],\n-\t\t\t});\n-\t\t\tconst outcome = await calculation.outcome;\n-\t\t\tconst trace = await calculation.trace;\n-\t\t\texpect(outcome.kind).toBe('Plan');\n-\t\t\tif (outcome.kind !== 'Plan' || !trace) return;\n-\t\t\tconst decision = trace.phases\n-\t\t\t\t.flatMap((phase) => phase.decisions)\n-\t\t\t\t.find((candidate) =>\n-\t\t\t\t\tcandidate.deltas.some((delta) => delta.kind === 'placement-added'),\n-\t\t\t\t);\n-\t\t\tconst placement = decision?.deltas.find(\n-\t\t\t\t(delta) => delta.kind === 'placement-added',\n-\t\t\t)?.placement;\n-\t\t\texpect(decision).toBeDefined();\n-\t\t\texpect(placement).toBeDefined();\n-\t\t\tif (!decision || !placement) return;\n-\n-\t\t\tconst candidates = trace.phases.flatMap((phase) =>\n-\t\t\t\tphase.decisions.flatMap((item) => item.candidates),\n-\t\t\t);\n-\t\t\tconst decisionDates = new Set(\n-\t\t\t\tdecision.candidates.flatMap(\n-\t\t\t\t\t(candidate) => candidate.dates ?? (candidate.date ? [candidate.date] : []),\n-\t\t\t\t),\n-\t\t\t);\n-\t\t\tconst unrelatedIneligible = candidates.find(\n-\t\t\t\t(candidate) =>\n-\t\t\t\t\tcandidate.status === 'ineligible' &&\n-\t\t\t\t\tcandidate.reason?.code === 'rule-invalid' &&\n-\t\t\t\t\tcandidate.date &&\n-\t\t\t\t\t!decisionDates.has(candidate.date),\n-\t\t\t);\n-\t\t\texpect(unrelatedIneligible).toBeDefined();\n-\t\t\tif (!unrelatedIneligible?.date) return;\n-\n+\t\t\tconst calculation = createPlanningCalculation(request);\n+\t\t\tawait calculation.trace;\n+\t\t\tvi.stubGlobal('window', undefined);\n \t\t\tconst analysis = await calculation.analyzeCounterfactual({\n \t\t\t\tdecisionId: decision.id,\n \t\t\t\tplacement,\n \t\t\t});\n \t\t\texpect(analysis.kind).toBe('Counterfactual');\n \t\t\tif (analysis.kind !== 'Counterfactual') return;\n-\t\t\texpect(\n-\t\t\t\tanalysis.results.find((result) => result.date === unrelatedIneligible.date)\n-\t\t\t\t\t?.historicalStatus,\n-\t\t\t).toBe('not-examined');\n+\t\t\texpect(analysis.results.find((result) => result.date === unrelatedDate)).toMatchObject({\n+\t\t\t\thistoricalStatus: 'not-examined',\n+\t\t\t\thistoricalReason: undefined,\n+\t\t\t});\n \t\t\texpect(\n \t\t\t\tanalysis.results.find((result) => result.date === '2024-01-06')?.historicalStatus,\n \t\t\t).toBe('ineligible');\n \t\t} finally {\n+\t\t\tvi.unstubAllGlobals();\n \t\t\tvi.stubGlobal('window', browserWindow);\n \t\t}\n \t});\n@@ -4831,7 +4928,7 @@ describe('planning calculation context', () => {\n \t\t\tconst calculation = createPlanningCalculation({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-02-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 4, '2024-01-31')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n \t\t\tconst trace = await calculation.trace;\n@@ -4854,12 +4951,12 @@ describe('planning calculation context', () => {\n \t\t\texpect(trace.phases.map((phase) => phase.name)).toEqual(\n \t\t\t\texpect.arrayContaining([\n \t\t\t\t\t'obligations',\n-\t\t\t\t\t'at-risk',\n-\t\t\t\t\t'holiday-week-value',\n-\t\t\t\t\t'non-working-day-gain',\n-\t\t\t\t\t'longest-work-sequence',\n-\t\t\t\t\t'short-sequence-deficit',\n-\t\t\t\t\t'supporting-placements',\n+\t\t\t\t\t'optimization:default-unplaced-at-risk',\n+\t\t\t\t\t'optimization:default-holiday-week-value',\n+\t\t\t\t\t'optimization:default-non-working-day-gain',\n+\t\t\t\t\t'optimization:default-longest-work-sequence',\n+\t\t\t\t\t'optimization:default-short-sequence-deficit',\n+\t\t\t\t\t'optimization:default-supporting-placements',\n \t\t\t\t\t'expiry',\n \t\t\t\t\t'dates',\n \t\t\t\t]),\n@@ -4881,7 +4978,7 @@ describe('planning calculation context', () => {\n \t\t\tconst calculation = createPlanningCalculation({\n \t\t\t\thorizon: { start: '2024-01-01', end: '2024-04-01' },\n \t\t\t\tbalances: [balance('cp', 'cp', 25, '2024-03-31')],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t});\n \t\t\texpect((await calculation.outcome).kind).toBe('Plan');\n \t\t\tconst trace = await calculation.trace;\n@@ -4907,16 +5004,18 @@ describe('planning calculation context', () => {\n \t\t\t);\n \t\t\texpect(chosenComparisons.length).toBeGreaterThan(0);\n \t\t\tfor (const { decision, candidate: chosen } of chosenComparisons) {\n+\t\t\t\tconst changedDates = chosen.dates ?? (chosen.date ? [chosen.date] : []);\n \t\t\t\texpect(\n \t\t\t\t\tdecision.deltas.some(\n \t\t\t\t\t\t(delta) =>\n \t\t\t\t\t\t\t(delta.kind === 'placement-moved' &&\n-\t\t\t\t\t\t\t\tdelta.toDate === chosen.date &&\n-\t\t\t\t\t\t\t\tdelta.balanceId === chosen.placement?.balanceId) ||\n+\t\t\t\t\t\t\t\tchangedDates.includes(delta.toDate ?? '')) ||\n \t\t\t\t\t\t\t(delta.kind === 'placement-added' &&\n-\t\t\t\t\t\t\t\tdelta.date === chosen.date &&\n-\t\t\t\t\t\t\t\tdelta.balanceId === chosen.placement?.balanceId) ||\n-\t\t\t\t\t\t\t(delta.kind === 'placement-removed' && delta.date === chosen.date),\n+\t\t\t\t\t\t\t\tchangedDates.includes(delta.date ?? '')) ||\n+\t\t\t\t\t\t\t(delta.kind === 'placement-removed' &&\n+\t\t\t\t\t\t\t\tchangedDates.includes(delta.date ?? '')) ||\n+\t\t\t\t\t\t\t(delta.kind === 'placement-updated' &&\n+\t\t\t\t\t\t\t\tchangedDates.includes(delta.date ?? '')),\n \t\t\t\t\t),\n \t\t\t\t).toBe(true);\n \t\t\t}\n@@ -4942,7 +5041,7 @@ describe('planning calculation context', () => {\n \t\t}\n \t});\n \n-\tit('records every eligible balance when a preference keeps the first assignment', async () => {\n+\tit('evaluates every eligible balance and retains the earlier expiry for an equal preference', async () => {\n \t\tconst browserWindow = globalThis.window;\n \t\tvi.stubGlobal('window', undefined);\n \t\ttry {\n@@ -4980,10 +5079,12 @@ describe('planning calculation context', () => {\n \t\t\t\t\t\tstatus: candidate.status,\n \t\t\t\t\t\treason: candidate.reason?.code,\n \t\t\t\t\t})) ?? [];\n-\t\t\texpect(candidates.slice(0, 2)).toEqual([\n-\t\t\t\t{ balanceId: 'earlier', status: 'chosen', reason: undefined },\n-\t\t\t\t{ balanceId: 'later', status: 'not-examined', reason: 'first-compatible-balance' },\n-\t\t\t]);\n+\t\t\texpect(candidates).toEqual(\n+\t\t\t\texpect.arrayContaining([\n+\t\t\t\t\t{ balanceId: 'earlier', status: 'chosen', reason: undefined },\n+\t\t\t\t\t{ balanceId: 'later', status: 'evaluated-rejected', reason: undefined },\n+\t\t\t\t]),\n+\t\t\t);\n \t\t} finally {\n \t\t\tvi.stubGlobal('window', browserWindow);\n \t\t}\n@@ -5026,7 +5127,11 @@ describe('planning calculation context', () => {\n \t\t\t\t\t{ id: 'cp-only', label: 'Paid leave only' },\n \t\t\t\t]);\n \t\t\tconst trace = await conflictCalculation.trace;\n-\t\t\texpect(trace?.phases.some((phase) => phase.name === 'holiday-week-value')).toBe(false);\n+\t\t\texpect(\n+\t\t\t\ttrace?.phases.some(\n+\t\t\t\t\t(phase) => phase.name === 'optimization:default-holiday-week-value',\n+\t\t\t\t),\n+\t\t\t).toBe(false);\n \t\t} finally {\n \t\t\tvi.stubGlobal('window', browserWindow);\n \t\t}\n@@ -5056,28 +5161,41 @@ describe('planning calculation context', () => {\n \n \tit('explains an incomplete incumbent without reusing the expired planning deadline', async () => {\n \t\tconst core = await import('./leave-planner.core');\n-\t\tlet artifacts: import('./leave-planner.core').PlanningArtifacts | undefined;\n-\t\tconst outcome = core.calculatePlanningInternal(\n-\t\t\t{\n-\t\t\t\thorizon,\n-\t\t\t\tbalances: Array.from({ length: 12 }, (_, index) =>\n-\t\t\t\t\tbalance(`balance-${index}`, index % 2 ? 'rtt' : 'cp', 12),\n-\t\t\t\t),\n-\t\t\t\trules: [],\n-\t\t\t\tdeadlineMs: 20,\n-\t\t\t},\n-\t\t\tundefined,\n-\t\t\t(value) => (artifacts = value),\n-\t\t);\n-\t\texpect(outcome.kind).toBe('PlanningIncomplete');\n-\t\tif (outcome.kind !== 'PlanningIncomplete') return;\n-\t\texpect(outcome.incumbent).toBeDefined();\n-\t\texpect(artifacts?.explanation?.kind).toBe('PlanExplanation');\n-\t\tif (artifacts?.explanation?.kind !== 'PlanExplanation') return;\n-\t\texpect(artifacts.explanation.incomplete?.reason.code).toBe('deadline');\n-\t\texpect(artifacts.explanation.placements).toHaveLength(\n-\t\t\toutcome.incumbent?.placements.length ?? 0,\n-\t\t);\n+\t\tlet clock = 0;\n+\t\tlet expired = false;\n+\t\tconst clockSpy = vi.spyOn(performance, 'now').mockImplementation(() => {\n+\t\t\tif (expired) clock += 100;\n+\t\t\treturn clock;\n+\t\t});\n+\t\ttry {\n+\t\t\tlet artifacts: import('./leave-planner.core').PlanningArtifacts | undefined;\n+\t\t\tconst outcome = core.calculatePlanningInternal(\n+\t\t\t\t{\n+\t\t\t\t\thorizon,\n+\t\t\t\t\tbalances: Array.from({ length: 12 }, (_, index) =>\n+\t\t\t\t\t\tbalance(`balance-${index}`, index % 2 ? 'rtt' : 'cp', 12),\n+\t\t\t\t\t),\n+\t\t\t\t\trules: presets,\n+\t\t\t\t\tdeadlineMs: 20,\n+\t\t\t\t\tprogress: (stage: string) => {\n+\t\t\t\t\t\tif (stage === `optimization:${presets[0].id}`) expired = true;\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\texpect(outcome.kind).toBe('PlanningIncomplete');\n+\t\t\tif (outcome.kind !== 'PlanningIncomplete') return;\n+\t\t\texpect(outcome.incumbent).toBeDefined();\n+\t\t\texpect(artifacts?.explanation?.kind).toBe('PlanExplanation');\n+\t\t\tif (artifacts?.explanation?.kind !== 'PlanExplanation') return;\n+\t\t\texpect(artifacts.explanation.incomplete?.reason.code).toBe('deadline');\n+\t\t\texpect(artifacts.explanation.placements).toHaveLength(\n+\t\t\t\toutcome.incumbent?.placements.length ?? 0,\n+\t\t\t);\n+\t\t} finally {\n+\t\t\tclockSpy.mockRestore();\n+\t\t}\n \t});\n \n \tit('publishes the worker outcome before delayed explanation artifacts', async () => {\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner.service.spec.ts", "project_id": 35, "relative_order": 27, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -80,6 +80,7 @@ export type {\n \tTimeOffPeriod,\n \tTimeWindowContribution,\n \tTimeWindowPlanningRule,\n+\tOptimizationPlanningRule,\n \tTraceCounterfactualSelection,\n \tTraceCandidateStatus,\n } from './leave-planner.core';\n@@ -117,6 +118,7 @@ interface UntrustedRecord {\n \tplacement?: unknown;\n \trewardDays?: unknown;\n \trewardType?: unknown;\n+\tconfiguration?: unknown;\n }\n \n interface TransportSnapshot {\n@@ -238,6 +240,12 @@ function snapshotRequest(request: unknown): TransportSnapshot {\n \t\t\t\t\tenabled: value?.enabled,\n \t\t\t\t\tforce: value?.force,\n \t\t\t\t};\n+\t\t\t\tif (\n+\t\t\t\t\ttypeof value?.type === 'string' &&\n+\t\t\t\t\tvalue.type.toLowerCase() === 'optimization'\n+\t\t\t\t) {\n+\t\t\t\t\treturn { ...base, configuration: cloneUnknown(value.configuration) };\n+\t\t\t\t}\n \t\t\t\tif (typeof value?.type === 'string' && value.type.toLowerCase() === 'time_window') {\n \t\t\t\t\treturn {\n \t\t\t\t\t\t...base,\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner.service.ts", "project_id": 35, "relative_order": 28, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -15,11 +15,14 @@ import { CalendarYear } from '../components/calendar-year/calendar-year';\n import { CalendarService, SelectableDayType } from './calendar-service';\n import { CalendarSettingsService } from './calendar-settings-service';\n import { UserInputService } from './user-input-service';\n-import { RuleService, RuleType } from './rule-service';\n+import { RuleService, RuleType, createOptimizationPresetRules } from './rule-service';\n+import { OPTIMIZATION_PRESETS, type OptimizationConfiguration } from './planning-objectives';\n \n beforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));\n afterEach(() => vi.useRealTimers());\n \n+const presets = createOptimizationPresetRules();\n+\n describe('real planning worker cancellation', () => {\n \tlet directory: string;\n \tlet bundle: string;\n@@ -43,7 +46,7 @@ const originalNow = performance.now.bind(performance);\n if (workerData.simulateLongCalculation)\n Object.defineProperty(performance, 'now', { value: () => originalNow() + elapsed });\n globalThis.self = { postMessage: (message) => {\n- if (workerData.simulateLongCalculation && message.type === 'progress' && message.stage === 'at-risk')\n+ if (workerData.simulateLongCalculation && message.type === 'progress' && message.stage === 'optimization:default-unplaced-at-risk')\n setTimeout(() => { elapsed = 20_000; parentPort.postMessage({ type: 'test-clock', elapsed }); }, 0);\n parentPort.postMessage(message);\n } };\n@@ -109,6 +112,123 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t});\n \tafterAll(() => rmSync(directory, { recursive: true, force: true }));\n \n+\tit('preserves a complete optimization configuration and active order in the real worker snapshot', async () => {\n+\t\tconst configuration: OptimizationConfiguration = structuredClone(\n+\t\t\tOPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t);\n+\t\tconfiguration.aggregation = 'maximum';\n+\t\tconst submitted = structuredClone(configuration);\n+\t\tconst calculation = createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-05' },\n+\t\t\tbalances: [{ id: 'rtt', type: 'rtt', quantity: 1, expiryDate: '2024-01-04' }],\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'personal-loss',\n+\t\t\t\t\tname: 'Captured loss rule',\n+\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\tforce: 'preference',\n+\t\t\t\t\tconfiguration,\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\tconfiguration.conditions = [];\n+\t\tconfiguration.direction = 'maximize';\n+\t\tconfiguration.aggregation = 'count';\n+\t\tconst outcome = await calculation.outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a worker plan');\n+\t\texpect(outcome.placements).toHaveLength(1);\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(calculation.snapshot.rules[0]).toMatchObject({\n+\t\t\tname: 'Captured loss rule',\n+\t\t\tconfiguration: submitted,\n+\t\t});\n+\t\tconst explanation = await calculation.explanation;\n+\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected worker explanation');\n+\t\texpect(\n+\t\t\texplanation.placements[0].objectiveVector.objectives.map((objective) => objective.id),\n+\t\t).toEqual([\n+\t\t\t'obligation-validity',\n+\t\t\t'optimization:personal-loss',\n+\t\t\t'balance-expiry',\n+\t\t\t'placement-date',\n+\t\t]);\n+\t\tconst trace = await calculation.trace;\n+\t\texpect(trace?.phases.map((phase) => phase.name)).toEqual([\n+\t\t\t'validation',\n+\t\t\t'obligations',\n+\t\t\t'optimization:personal-loss',\n+\t\t\t'expiry',\n+\t\t\t'dates',\n+\t\t]);\n+\t\tconst comparison = await calculation.analyzeCounterfactual(outcome.placements[0]);\n+\t\tif (comparison.kind !== 'Counterfactual') throw new Error('Expected worker comparison');\n+\t\texpect(comparison.baseline.objectives.map((objective) => objective.id)).toEqual([\n+\t\t\t'obligation-validity',\n+\t\t\t'optimization:personal-loss',\n+\t\t\t'balance-expiry',\n+\t\t\t'placement-date',\n+\t\t]);\n+\t});\n+\n+\tit('keeps the submitted work-sequence threshold in the real worker, trace and counterfactuals', async () => {\n+\t\tconst configuration: OptimizationConfiguration = structuredClone(\n+\t\t\tOPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t);\n+\t\tconst calculation = createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-08', end: '2024-01-13' },\n+\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-02-01' }],\n+\t\t\tdeclaredDays: ['2024-01-08', '2024-01-12'].map((date) => ({ date, type: 'other' })),\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\tid: 'deficit',\n+\t\t\t\t\tname: 'Captured five-day preference',\n+\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\tconfiguration,\n+\t\t\t\t},\n+\t\t\t],\n+\t\t});\n+\t\tconfiguration.thresholdDays = 3;\n+\t\tconfiguration.conditions = [];\n+\t\tconst outcome = await calculation.outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a worker plan');\n+\t\texpect(outcome.placements.map(({ date }) => date)).toEqual([\n+\t\t\t'2024-01-09',\n+\t\t\t'2024-01-10',\n+\t\t\t'2024-01-11',\n+\t\t]);\n+\t\texpect(calculation.snapshot.rules[0]).toMatchObject({\n+\t\t\tconfiguration: { thresholdDays: 5, conditions: ['internal', 'non-empty'] },\n+\t\t});\n+\t\tconst explanation = await calculation.explanation;\n+\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\texpect(\n+\t\t\texplanation.placements[0].comparison.before.objectives.find(\n+\t\t\t\t({ id }) => id === 'optimization:deficit',\n+\t\t\t)?.value,\n+\t\t).toBe(4);\n+\t\tconst trace = await calculation.trace;\n+\t\tconst chosen = trace?.phases\n+\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t.find((candidate) => candidate.status === 'chosen' && candidate.dates?.length === 3);\n+\t\texpect(chosen?.comparison?.firstDecisiveObjective).toBe('optimization:deficit');\n+\t\texpect(\n+\t\t\tchosen?.comparison?.before.objectives.find(({ id }) => id === 'optimization:deficit')\n+\t\t\t\t?.value,\n+\t\t).toBe(2);\n+\t\tconst counterfactual = await calculation.analyzeCounterfactual(outcome.placements[0]);\n+\t\tif (counterfactual.kind !== 'Counterfactual') throw new Error('Expected a counterfactual');\n+\t\texpect(\n+\t\t\tcounterfactual.baseline.objectives.find(({ id }) => id === 'optimization:deficit')\n+\t\t\t\t?.value,\n+\t\t).toBe(4);\n+\t\texpect(\n+\t\t\tcounterfactual.results\n+\t\t\t\t.find(({ date }) => date === '2024-01-09')\n+\t\t\t\t?.comparison?.after.objectives.find(({ id }) => id === 'optimization:deficit')\n+\t\t\t\t?.value,\n+\t\t).toBe(0);\n+\t});\n+\n \tit.each([\n \t\t[false, false],\n \t\t[true, false],\n@@ -120,7 +240,7 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\tlocalStorage.clear();\n \t\t\tlocalStorage.setItem('app.language', '\"fr\"');\n \t\t\tlocalStorage.setItem('leaveBalances', '[]');\n-\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\t\tvi.setSystemTime(new Date('2024-05-01T21:59:59Z'));\n \t\t\tawait TestBed.configureTestingModule({\n \t\t\t\timports: [CalendarYear],\n@@ -131,6 +251,7 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\tfor (const date of ['2024-04-29', '2024-04-30']) input.toggleDeclaredDay(date, 'cp');\n \t\t\tinput.toggleDeclaredDay('2024-05-06', 'other');\n \t\t\tconst rules = TestBed.inject(RuleService);\n+\t\t\trules.addRule(presets[0]);\n \t\t\trules.addRule({\n \t\t\t\tid: 'producer',\n \t\t\t\tname: 'CP autour du férié',\n@@ -155,6 +276,7 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\t\tplaceDays: 2,\n \t\t\t\tplaceType: SelectableDayType.OTHER,\n \t\t\t});\n+\t\t\tfor (const preset of presets.slice(1)) rules.addRule(preset);\n \t\t\tconst calendar = TestBed.inject(CalendarService);\n \t\t\tconst original = calendar.createPlanningCalculation.bind(calendar);\n \t\t\tlet calculation!: PlanningCalculationContext;\n@@ -168,7 +290,10 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\t\t\t\t\t...request,\n \t\t\t\t\t\t\tprogress: (stage) => {\n \t\t\t\t\t\t\t\trequest.progress?.(stage);\n-\t\t\t\t\t\t\t\tif (cancelled && stage === 'non-working-day-gain') {\n+\t\t\t\t\t\t\t\tif (\n+\t\t\t\t\t\t\t\t\tcancelled &&\n+\t\t\t\t\t\t\t\t\tstage === 'optimization:default-non-working-day-gain'\n+\t\t\t\t\t\t\t\t) {\n \t\t\t\t\t\t\t\t\tfixture.detectChanges();\n \t\t\t\t\t\t\t\t\tfixture.nativeElement\n \t\t\t\t\t\t\t\t\t\t.querySelector('button.cancel-calculation')\n@@ -249,7 +374,10 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\texpect(dialog.textContent?.includes('Planning partiel')).toBe(cancelled);\n \t\t\tconst originalDeclarations = structuredClone(calculation.snapshot.declaredDays);\n \t\t\tinput.toggleDeclaredDay('2024-04-30', 'rtt');\n-\t\t\trules.updateRule({ ...rules.rules[0], name: 'Règle modifiée après calcul' });\n+\t\t\trules.updateRule({\n+\t\t\t\t...rules.rules.find(({ id }) => id === 'producer')!,\n+\t\t\t\tname: 'Règle modifiée après calcul',\n+\t\t\t});\n \t\t\trules.deleteRule('producer');\n \t\t\tinput.updateBalances(() => []);\n \t\t\tif (worker) {\n@@ -355,7 +483,7 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\t\tbalances: [\n \t\t\t\t\t{ id: 'cp', type: 'cp' as const, quantity: 4, expiryDate: '2024-01-05' },\n \t\t\t\t],\n-\t\t\t\trules: [],\n+\t\t\t\trules: presets,\n \t\t\t\tdeclaredDays: [\n \t\t\t\t\t{ date: '2024-01-02', type: 'cp' as const },\n \t\t\t\t\t{ date: '2024-01-03', type: 'rtt' as const },\n@@ -370,7 +498,8 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\t\t\t\t{\n \t\t\t\t\t\t\t...submitted,\n \t\t\t\t\t\t\tprogress: (stage: string) => {\n-\t\t\t\t\t\t\t\tif (stage === 'non-working-day-gain') interruption = true;\n+\t\t\t\t\t\t\t\tif (stage === 'optimization:default-non-working-day-gain')\n+\t\t\t\t\t\t\t\t\tinterruption = true;\n \t\t\t\t\t\t\t},\n \t\t\t\t\t\t},\n \t\t\t\t\t\tundefined,\n@@ -383,7 +512,8 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\tconst calculation = createPlanningCalculation({\n \t\t\t\t...submitted,\n \t\t\t\tprogress: (stage) => {\n-\t\t\t\t\tif (cancelled && stage === 'non-working-day-gain') calculation.cancel();\n+\t\t\t\t\tif (cancelled && stage === 'optimization:default-non-working-day-gain')\n+\t\t\t\t\t\tcalculation.cancel();\n \t\t\t\t},\n \t\t\t});\n \t\t\tconst outcome = await calculation.outcome;\n@@ -546,26 +676,30 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\thorizon: { start: '2024-01-01', end: '2025-01-01' },\n \t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2024-12-31' }],\n \t\t\trules: [\n-\t\t\t\t{\n-\t\t\t\t\tid: 'fixed',\n-\t\t\t\t\ttype: 'time_window',\n-\t\t\t\t\tforce: 'obligation',\n-\t\t\t\t\tstartDate: '2024-01-02',\n-\t\t\t\t\tendDate: '2024-01-02',\n-\t\t\t\t\tplaceDays: 1,\n-\t\t\t\t\tplaceType: 'cp',\n-\t\t\t\t},\n+\t\t\t\tpresets[0],\n+\t\t\t\t...[\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'fixed',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tstartDate: '2024-01-02',\n+\t\t\t\t\t\tendDate: '2024-01-02',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\t...presets.slice(1),\n \t\t\t],\n \t\t\tprogress: (stage) => {\n-\t\t\t\tif (stage === 'non-working-day-gain') calculation.cancel();\n+\t\t\t\tif (stage === 'optimization:default-non-working-day-gain') calculation.cancel();\n \t\t\t},\n \t\t});\n \t\tconst outcome = await calculation.outcome;\n \t\texpect(outcome.kind).toBe('PlanningIncomplete');\n \t\tif (outcome.kind !== 'PlanningIncomplete') return;\n \t\texpect(outcome.reasons[0].code).toBe('user-cancelled');\n-\t\texpect(outcome.completedStages).toContain('holiday-week-value');\n-\t\texpect(outcome.completedStages).not.toContain('non-working-day-gain');\n+\t\texpect(outcome.completedStages).toContain('optimization:default-holiday-week-value');\n+\t\texpect(outcome.completedStages).not.toContain('optimization:default-non-working-day-gain');\n \t\tconst incumbent = outcome.incumbent!;\n \t\texpect(incumbent.placements).toHaveLength(3);\n \t\texpect(incumbent.placements).toContainEqual({\n@@ -585,9 +719,11 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\tconst trace = await calculation.trace;\n \t\texpect(trace?.status).toBe('incomplete');\n \t\texpect(trace?.error?.code).toBe('user-cancelled');\n-\t\texpect(trace?.phases.find((phase) => phase.name === 'non-working-day-gain')?.status).toBe(\n-\t\t\t'interrupted',\n-\t\t);\n+\t\texpect(\n+\t\t\ttrace?.phases.find(\n+\t\t\t\t(phase) => phase.name === 'optimization:default-non-working-day-gain',\n+\t\t\t)?.status,\n+\t\t).toBe('interrupted');\n \t\tconst frozenOutcome = structuredClone(outcome);\n \t\tcalculation.cancel();\n \t\texpect(await calculation.outcome).toEqual(frozenOutcome);\n@@ -605,7 +741,7 @@ parentPort.on('message', (data) => globalThis.self.onmessage({ data }));\n \t\t\t\t\texpiryDate: '2026-12-24',\n \t\t\t\t},\n \t\t\t],\n-\t\t\trules: [],\n+\t\t\trules: presets,\n \t\t};\n \t\tconst { calculatePlanningInternal } = await import('./leave-planner.core');\n \t\tconst expected = calculatePlanningInternal(submitted);\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/leave-planner.worker.spec.ts", "project_id": 35, "relative_order": 29, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,480 @@\n+import { describe, expect, it } from 'vitest';\n+import {\n+\tcalculatePlanningInternal,\n+\ttype PlanningArtifacts,\n+\ttype PlanningRequest,\n+} from './leave-planner.core';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+import { createOptimizationPresetRules } from './rule-service';\n+\n+const presets = createOptimizationPresetRules();\n+const composedRequest: PlanningRequest & { calculationDate: string } = {\n+\tcalculationDate: '2024-04-01',\n+\thorizon: { start: '2024-05-06', end: '2024-05-18' },\n+\tbalances: [\n+\t\t{\n+\t\t\tid: 'cp',\n+\t\t\ttype: 'cp',\n+\t\t\tquantity: 3,\n+\t\t\tavailableFrom: '2024-05-06',\n+\t\t\texpiryDate: '2024-05-17',\n+\t\t},\n+\t],\n+\trules: presets,\n+};\n+\n+describe('integrated optimization and earned leave', () => {\n+\tit.each(presets)(\n+\t\t'makes disabled $name identical to its absence in the complete configuration',\n+\t\t(disabled) => {\n+\t\t\tconst absent = calculatePlanningInternal({\n+\t\t\t\t...composedRequest,\n+\t\t\t\trules: presets.filter(({ id }) => id !== disabled.id),\n+\t\t\t});\n+\t\t\tconst inactive = calculatePlanningInternal({\n+\t\t\t\t...composedRequest,\n+\t\t\t\trules: presets.map((rule) =>\n+\t\t\t\t\trule.id === disabled.id ? { ...rule, enabled: false } : rule,\n+\t\t\t\t),\n+\t\t\t});\n+\t\t\texpect(absent.kind).toBe('Plan');\n+\t\t\texpect(inactive).toEqual(absent);\n+\t\t},\n+\t);\n+\n+\tit('runs the complete configuration once after the sole obligation state and records exact reused evaluations', () => {\n+\t\tlet artifacts: PlanningArtifacts = {};\n+\t\tconst outcome = calculatePlanningInternal(\n+\t\t\tcomposedRequest,\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\texpect(outcome).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [{ date: '2024-05-06' }, { date: '2024-05-07' }, { date: '2024-05-10' }],\n+\t\t\tmetrics: { unplacedAtRisk: 0, holidayWeekValue: 5, nonWorkingDayGain: 6 },\n+\t\t});\n+\t\tconst trace = artifacts.trace;\n+\t\texpect(trace?.status).toBe('ready');\n+\t\texpect(\n+\t\t\ttrace?.phases\n+\t\t\t\t.find(({ name }) => name === 'obligations')\n+\t\t\t\t?.decisions.flatMap(({ candidates }) => candidates)\n+\t\t\t\t.some(({ comparison }) => comparison),\n+\t\t).toBe(false);\n+\t\texpect(\n+\t\t\ttrace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t.some(({ reason }) => reason?.code === 'unchanged-rule-state'),\n+\t\t).toBe(true);\n+\t\texpect(\n+\t\t\ttrace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t.some(\n+\t\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\t\tstatus === 'not-examined' && reason?.code === 'unchanged-generic-state',\n+\t\t\t\t),\n+\t\t).toBe(true);\n+\t\tif (artifacts.explanation?.kind !== 'PlanExplanation')\n+\t\t\tthrow new Error('Expected an explanation.');\n+\t\texpect(\n+\t\t\tartifacts.explanation.placements[0].objectiveVector.objectives.map(({ id }) => id),\n+\t\t).toEqual([\n+\t\t\t'obligation-validity',\n+\t\t\t'optimization:default-unplaced-at-risk',\n+\t\t\t'optimization:default-holiday-week-value',\n+\t\t\t'optimization:default-non-working-day-gain',\n+\t\t\t'optimization:default-longest-work-sequence',\n+\t\t\t'optimization:default-short-sequence-deficit',\n+\t\t\t'optimization:default-supporting-placements',\n+\t\t\t'balance-expiry',\n+\t\t\t'placement-date',\n+\t\t]);\n+\t});\n+\n+\tit('preserves the first equivalent funder while evaluating typed window alternatives', () => {\n+\t\tlet artifacts: PlanningArtifacts = {};\n+\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\t...composedRequest,\n+\t\t\t\tbalances: ['first-cp', 'second-cp', 'rtt'].map((id) => ({\n+\t\t\t\t\tid,\n+\t\t\t\t\ttype: id === 'rtt' ? 'rtt' : 'cp',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2024-05-06',\n+\t\t\t\t\texpiryDate: '2024-05-17',\n+\t\t\t\t})),\n+\t\t\t\trules: [\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'typed-window',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tstartDate: '2024-05-07',\n+\t\t\t\t\t\tendDate: '2024-05-07',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t\t...presets.slice(1),\n+\t\t\t\t],\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\texpect(outcome).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [\n+\t\t\t\t{ date: '2024-05-06', balanceId: 'second-cp' },\n+\t\t\t\t{ date: '2024-05-07', balanceId: 'rtt' },\n+\t\t\t\t{ date: '2024-05-10', balanceId: 'first-cp' },\n+\t\t\t],\n+\t\t\tpreferences: [{ ruleId: 'typed-window', satisfied: 1 }],\n+\t\t\tmetrics: { unplacedAtRisk: 0, holidayWeekValue: 5, nonWorkingDayGain: 6 },\n+\t\t});\n+\t\tconst candidates = artifacts.trace?.phases\n+\t\t\t.find(({ name }) => name === `optimization:${presets[0].id}`)\n+\t\t\t?.decisions.flatMap(({ candidates }) => candidates);\n+\t\tconst skipped = candidates?.filter(\n+\t\t\t({ reason }) => reason?.code === 'equivalent-date-funding',\n+\t\t);\n+\t\texpect(skipped?.length).toBeGreaterThan(0);\n+\t\texpect(\n+\t\t\tskipped?.every(({ status, comparison }) => status === 'not-examined' && !comparison),\n+\t\t).toBe(true);\n+\t\texpect(\n+\t\t\tskipped?.some(\n+\t\t\t\t({ date, placement }) => date === '2024-05-07' && placement?.balanceId === 'rtt',\n+\t\t\t),\n+\t\t).toBe(false);\n+\t\texpect(\n+\t\t\tcandidates?.some(\n+\t\t\t\t({ date, placement, comparison }) =>\n+\t\t\t\t\tdate === '2024-05-07' && placement?.balanceId === 'rtt' && comparison,\n+\t\t\t),\n+\t\t).toBe(true);\n+\t});\n+\n+\tit.each(['maximum', 'unsafe-total'] as const)(\n+\t\t'keeps distinct funding evaluations when equivalence cannot be proved (%s)',\n+\t\t(control) => {\n+\t\t\tlet artifacts: PlanningArtifacts = {};\n+\t\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t\t{\n+\t\t\t\t\tcalculationDate: '2024-01-01',\n+\t\t\t\t\thorizon: { start: '2024-01-02', end: '2024-01-03' },\n+\t\t\t\t\tbalances: [\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'first',\n+\t\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\t\tquantity: control === 'maximum' ? 1 : Number.MAX_SAFE_INTEGER,\n+\t\t\t\t\t\t\texpiryDate: '2024-01-02',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'second',\n+\t\t\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\t\t\tquantity: control === 'maximum' ? 2 : 1,\n+\t\t\t\t\t\t\texpiryDate: '2024-01-02',\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t\trules: [\n+\t\t\t\t\t\tpresets[0],\n+\t\t\t\t\t\t...(control === 'maximum'\n+\t\t\t\t\t\t\t? [\n+\t\t\t\t\t\t\t\t\t{\n+\t\t\t\t\t\t\t\t\t\tid: 'largest-balance',\n+\t\t\t\t\t\t\t\t\t\ttype: 'optimization',\n+\t\t\t\t\t\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t\t\t\t\t\t...OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t\t\t\t\t\t\t\t\t\taggregation: 'maximum',\n+\t\t\t\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\t\t]\n+\t\t\t\t\t\t\t: []),\n+\t\t\t\t\t],\n+\t\t\t\t},\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\texpect(outcome).toMatchObject({\n+\t\t\t\tkind: 'Plan',\n+\t\t\t\tplacements: [{ balanceId: control === 'maximum' ? 'second' : 'first' }],\n+\t\t\t});\n+\t\t\tconst candidates = artifacts.trace?.phases\n+\t\t\t\t.find(({ name }) => name === `optimization:${presets[0].id}`)\n+\t\t\t\t?.decisions.flatMap(({ candidates }) => candidates);\n+\t\t\texpect(\n+\t\t\t\tcandidates?.some(({ reason }) => reason?.code === 'equivalent-date-funding'),\n+\t\t\t).toBe(false);\n+\t\t\tfor (const balanceId of ['first', 'second'])\n+\t\t\t\texpect(\n+\t\t\t\t\tcandidates?.some(\n+\t\t\t\t\t\t({ placement, comparison }) =>\n+\t\t\t\t\t\t\tplacement?.balanceId === balanceId && comparison,\n+\t\t\t\t\t),\n+\t\t\t\t).toBe(true);\n+\t\t},\n+\t);\n+\n+\tit('finishes a renamed first quantity rule at zero and still evaluates later priorities and final ties', () => {\n+\t\tconst loss = { ...presets[0], id: 'personal-quantity', name: 'Personal quantity' };\n+\t\tconst run = (rules: PlanningRequest['rules']) => {\n+\t\t\tlet artifacts: PlanningArtifacts = {};\n+\t\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t\t{ ...composedRequest, rules },\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\treturn { outcome, trace: artifacts.trace };\n+\t\t};\n+\t\tconst window = {\n+\t\t\tid: 'already-satisfied',\n+\t\t\ttype: 'time_window',\n+\t\t\tstartDate: '2024-05-06',\n+\t\t\tendDate: '2024-05-06',\n+\t\t\tplaceDays: 1,\n+\t\t\tplaceType: 'cp',\n+\t\t};\n+\t\tconst first = run([loss, window, ...presets.slice(1)]);\n+\t\texpect(first.outcome).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [{ date: '2024-05-06' }, { date: '2024-05-07' }, { date: '2024-05-10' }],\n+\t\t\tmetrics: { unplacedAtRisk: 0, holidayWeekValue: 5, nonWorkingDayGain: 6 },\n+\t\t});\n+\t\tconst stopped = first.trace?.phases\n+\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t.filter(({ reason }) => reason?.code === 'quantity-prefix-lower-bound');\n+\t\texpect(stopped?.length).toBeGreaterThan(0);\n+\t\texpect(\n+\t\t\tstopped?.every(\n+\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\tstatus === 'not-examined' && reason?.ruleIds?.includes(loss.id),\n+\t\t\t),\n+\t\t).toBe(true);\n+\t\texpect(\n+\t\t\tfirst.trace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t.some(\n+\t\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\t\tstatus === 'not-examined' &&\n+\t\t\t\t\t\treason?.code === 'satisfied-window-prefix-bound' &&\n+\t\t\t\t\t\treason.ruleIds?.includes(window.id),\n+\t\t\t\t),\n+\t\t).toBe(true);\n+\t\tconst expiry = first.trace?.phases.find(({ name }) => name === 'expiry');\n+\t\texpect(expiry?.completed).toBe(true);\n+\t\texpect(\n+\t\t\texpiry?.decisions.some(({ candidates }) =>\n+\t\t\t\tcandidates.some(({ comparison }) => comparison),\n+\t\t\t),\n+\t\t).toBe(true);\n+\t\tconst reordered = run([presets[1], loss, ...presets.slice(2)]);\n+\t\texpect(reordered.outcome.kind).toBe('Plan');\n+\t\texpect(\n+\t\t\treordered.trace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t.some(({ reason }) => reason?.code === 'quantity-prefix-lower-bound'),\n+\t\t).toBe(false);\n+\t});\n+\n+\tit.each(['sum', 'count', 'maximum'] as const)(\n+\t\t'finishes a configured maximize holiday prefix at its evaluator bound (%s)',\n+\t\t(aggregation) => {\n+\t\t\tconst holiday = {\n+\t\t\t\t...presets[1],\n+\t\t\t\tid: 'personal-holiday',\n+\t\t\t\tconfiguration: { ...OPTIMIZATION_PRESETS.holidayWeekValue, aggregation },\n+\t\t\t};\n+\t\t\tlet artifacts: PlanningArtifacts = {};\n+\t\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t\t{ ...composedRequest, rules: [presets[0], holiday, ...presets.slice(2)] },\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\texpect(outcome).toMatchObject({\n+\t\t\t\tkind: 'Plan',\n+\t\t\t\tplacements: [\n+\t\t\t\t\t{ date: '2024-05-06' },\n+\t\t\t\t\t{ date: '2024-05-07' },\n+\t\t\t\t\t{ date: '2024-05-10' },\n+\t\t\t\t],\n+\t\t\t\tmetrics: { unplacedAtRisk: 0, holidayWeekValue: 5, nonWorkingDayGain: 6 },\n+\t\t\t});\n+\t\t\texpect(\n+\t\t\t\tartifacts.trace?.phases\n+\t\t\t\t\t.flatMap(({ decisions }) => decisions.flatMap(({ candidates }) => candidates))\n+\t\t\t\t\t.some(\n+\t\t\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\t\t\tstatus === 'not-examined' &&\n+\t\t\t\t\t\t\treason?.code === 'satisfied-holiday-prefix-bound' &&\n+\t\t\t\t\t\t\treason.ruleIds?.includes(holiday.id),\n+\t\t\t\t\t),\n+\t\t\t).toBe(true);\n+\t\t\tconst final = artifacts.trace?.phases.find(({ name }) => name === 'expiry');\n+\t\t\texpect(final?.completed).toBe(true);\n+\t\t\texpect(\n+\t\t\t\tfinal?.decisions.some(({ candidates }) =>\n+\t\t\t\t\tcandidates.some(({ comparison }) => comparison),\n+\t\t\t\t),\n+\t\t\t).toBe(true);\n+\t\t},\n+\t);\n+\n+\tit('commits a strict holiday bundle before deferring old generic alternatives and preserves higher rules', () => {\n+\t\tlet artifacts: PlanningArtifacts = {};\n+\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t{\n+\t\t\t\tcalculationDate: '2026-11-01',\n+\t\t\t\thorizon: { start: '2026-11-02', end: '2026-11-14' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 3, expiryDate: '2026-11-30' }],\n+\t\t\t\tdeclaredDays: ['2026-11-09', '2026-11-10'].map((date) => ({ date, type: 'other' })),\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'mandatory',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tstartDate: '2026-11-02',\n+\t\t\t\t\t\tendDate: '2026-11-02',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t\tpresets[0],\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'earlier-window',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tstartDate: '2026-11-02',\n+\t\t\t\t\t\tendDate: '2026-11-02',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t\t...presets.slice(1),\n+\t\t\t\t],\n+\t\t\t},\n+\t\t\tundefined,\n+\t\t\t(value) => (artifacts = value),\n+\t\t);\n+\t\texpect(outcome).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tplacements: [{ date: '2026-11-02' }, { date: '2026-11-12' }, { date: '2026-11-13' }],\n+\t\t\tpreferences: [{ ruleId: 'earlier-window', satisfied: 1 }],\n+\t\t\tmetrics: { unplacedAtRisk: 0, holidayWeekValue: 3 },\n+\t\t});\n+\t\tconst holiday = artifacts.trace?.phases.find(\n+\t\t\t({ name }) => name === `optimization:${presets[1].id}`,\n+\t\t);\n+\t\tconst decisions = holiday?.decisions.flatMap(({ candidates }) => candidates);\n+\t\texpect(\n+\t\t\tdecisions?.some(\n+\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\tstatus === 'not-examined' && reason?.code === 'strict-prefix-bundle-progress',\n+\t\t\t),\n+\t\t).toBe(true);\n+\t\texpect(decisions?.some(({ status, comparison }) => status === 'chosen' && comparison)).toBe(\n+\t\t\ttrue,\n+\t\t);\n+\t\tconst final = artifacts.trace?.phases.find(({ name }) => name === 'expiry');\n+\t\texpect(final?.completed).toBe(true);\n+\t\texpect(\n+\t\t\tfinal?.decisions.some(({ candidates }) =>\n+\t\t\t\tcandidates.some(({ comparison }) => comparison),\n+\t\t\t),\n+\t\t).toBe(true);\n+\t});\n+\n+\tit.each([false, true])(\n+\t\t'earns an already-complete preference occurrence before comparisons (minimize every balance: %s)',\n+\t\t(minimizeEveryBalance) => {\n+\t\t\tconst request: PlanningRequest & { calculationDate: string } = {\n+\t\t\t\tcalculationDate: '2026-11-01',\n+\t\t\t\thorizon: { start: '2026-11-09', end: '2026-11-14' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2027-01-01' }],\n+\t\t\t\trules: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'mandatory',\n+\t\t\t\t\t\ttype: 'time_window',\n+\t\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\t\tstartDate: '2026-11-12',\n+\t\t\t\t\t\tendDate: '2026-11-12',\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t},\n+\t\t\t\t\t...(minimizeEveryBalance\n+\t\t\t\t\t\t? [\n+\t\t\t\t\t\t\t\t{\n+\t\t\t\t\t\t\t\t\tid: 'all-balances',\n+\t\t\t\t\t\t\t\t\ttype: 'optimization' as const,\n+\t\t\t\t\t\t\t\t\tconfiguration: {\n+\t\t\t\t\t\t\t\t\t\t...OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t\t\t\t\t\t\t\t\tconditions: [],\n+\t\t\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\t]\n+\t\t\t\t\t\t: []),\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'producer',\n+\t\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\t\tdayOfWeek: 3,\n+\t\t\t\t\t\tplaceDays: 1,\n+\t\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\t\tplacement: 'after',\n+\t\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\t\trewardType: 'rtt',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t};\n+\t\t\tlet artifacts: PlanningArtifacts = {};\n+\t\t\tconst outcome = calculatePlanningInternal(\n+\t\t\t\trequest,\n+\t\t\t\tundefined,\n+\t\t\t\t(value) => (artifacts = value),\n+\t\t\t);\n+\t\t\texpect(outcome).toMatchObject({\n+\t\t\t\tkind: 'Plan',\n+\t\t\t\tplacements: [\n+\t\t\t\t\t{ date: '2026-11-12', type: 'cp', ruleIds: ['mandatory', 'producer'] },\n+\t\t\t\t],\n+\t\t\t\tpreferences: [{ ruleId: 'producer', satisfied: 1 }],\n+\t\t\t\tremainingBalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'earned:producer:2026-11-11',\n+\t\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2026-11-13',\n+\t\t\t\t\t\texpiryDate: '2027-11-13',\n+\t\t\t\t\t\tsourceRuleId: 'producer',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t});\n+\t\t\texpect(artifacts.finalState?.earnedActivations).toEqual([\n+\t\t\t\t{\n+\t\t\t\t\tid: 'earned:producer:2026-11-11',\n+\t\t\t\t\truleId: 'producer',\n+\t\t\t\t\toccurrence: '2026-11-11',\n+\t\t\t\t\tdates: ['2026-11-12'],\n+\t\t\t\t},\n+\t\t\t]);\n+\t\t\tif (artifacts.explanation?.kind !== 'PlanExplanation')\n+\t\t\t\tthrow new Error('Expected an explanation.');\n+\t\t\texpect(artifacts.explanation.placements[0].contributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({ kind: 'rule', ruleId: 'producer' }),\n+\t\t\t);\n+\t\t\texpect(artifacts.explanation.ifThenContributions).toContainEqual(\n+\t\t\t\texpect.objectContaining({\n+\t\t\t\t\truleId: 'producer',\n+\t\t\t\t\tearnedEntitlement: {\n+\t\t\t\t\t\tid: 'earned:producer:2026-11-11',\n+\t\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2026-11-13',\n+\t\t\t\t\t\texpiryDate: '2027-11-13',\n+\t\t\t\t\t\tadded: true,\n+\t\t\t\t\t},\n+\t\t\t\t}),\n+\t\t\t);\n+\t\t\tif (minimizeEveryBalance)\n+\t\t\t\texpect(\n+\t\t\t\t\tartifacts.explanation.placements[0].objectiveVector.objectives,\n+\t\t\t\t).toContainEqual(\n+\t\t\t\t\texpect.objectContaining({ id: 'optimization:all-balances', value: 1 }),\n+\t\t\t\t);\n+\t\t},\n+\t);\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/services/optimization-integration.spec.ts", "project_id": 35, "relative_order": 30, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,508 @@\n+import { vi } from 'vitest';\n+import { calculatePlanningInternal } from './leave-planner.core';\n+import { createPlanningCalculation } from './leave-planner.service';\n+import type { PlanningRequest } from './leave-planner.service';\n+import { OPTIMIZATION_PRESETS, type OptimizationConfiguration } from './planning-objectives';\n+\n+const loss = {\n+\tid: 'loss',\n+\tname: 'Prevent losses',\n+\ttype: 'optimization' as const,\n+\tforce: 'preference' as const,\n+\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+};\n+const personal = {\n+\tid: 'personal',\n+\tname: 'Personal CP day',\n+\ttype: 'time_window' as const,\n+\tforce: 'preference' as const,\n+\tstartDate: '2024-01-02',\n+\tendDate: '2024-01-02',\n+\tplaceDays: 1,\n+\tplaceType: 'cp' as const,\n+};\n+const concurrent: PlanningRequest = {\n+\thorizon: { start: '2024-01-02', end: '2024-01-03' },\n+\tbalances: [\n+\t\t{ id: 'risk-rtt', type: 'rtt', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t{ id: 'deferred-cp', type: 'cp', quantity: 1, expiryDate: '2024-02-01' },\n+\t],\n+\trules: [],\n+};\n+\n+describe('explicit active planning objectives', () => {\n+\tbeforeEach(() => {\n+\t\tvi.setSystemTime(new Date('2024-01-01T12:00:00Z'));\n+\t\tvi.stubGlobal('window', undefined);\n+\t});\n+\tafterEach(() => {\n+\t\tvi.useRealTimers();\n+\t\tvi.unstubAllGlobals();\n+\t});\n+\n+\tit('rejects a sparse selector list consistently at direct and calculation boundaries', async () => {\n+\t\tconst request = {\n+\t\t\t...concurrent,\n+\t\t\trules: [\n+\t\t\t\t{ ...loss, configuration: { ...loss.configuration, conditions: new Array(1) } },\n+\t\t\t],\n+\t\t};\n+\t\tconst direct = calculatePlanningInternal(request);\n+\t\tconst calculation = await createPlanningCalculation(request).outcome;\n+\t\tfor (const result of [direct, calculation])\n+\t\t\texpect(result).toMatchObject({\n+\t\t\t\tkind: 'InvalidInput',\n+\t\t\t\treasons: [{ code: 'invalid-optimization-configuration', ruleIds: ['loss'] }],\n+\t\t\t});\n+\t});\n+\n+\tit('adds no leave without active rules and retains declared days', async () => {\n+\t\tconst calculation = createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-05' },\n+\t\t\tbalances: [{ id: 'rtt', type: 'rtt', quantity: 2, expiryDate: '2024-01-04' }],\n+\t\t\trules: [],\n+\t\t\tdeclaredDays: [{ date: '2024-01-03', type: 'other' }],\n+\t\t});\n+\t\tconst outcome = await calculation.outcome;\n+\t\texpect(outcome.kind).toBe('Plan');\n+\t\tif (outcome.kind !== 'Plan') return;\n+\t\texpect(outcome.placements).toEqual([]);\n+\t\texpect(outcome.declaredDays).toEqual([{ date: '2024-01-03', type: 'other' }]);\n+\t\texpect(outcome.remainingBalances[0].quantity).toBe(2);\n+\t\texpect(outcome.remainingBalances[0]).toMatchObject({\n+\t\t\tclassification: 'at-risk',\n+\t\t\treason: { code: 'active-priorities' },\n+\t\t});\n+\t});\n+\n+\tit.each([\n+\t\t['z-early', 'a-later'],\n+\t\t['a-early', 'z-later'],\n+\t])(\n+\t\t'compares equal expirations before dates without preferring balance identity %s',\n+\t\t(earlyId, laterId) => {\n+\t\t\tconst result = calculatePlanningInternal({\n+\t\t\t\thorizon: { start: '2024-01-09', end: '2024-01-13' },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: earlyId,\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2024-01-09',\n+\t\t\t\t\t\texpiryDate: '2024-02-01',\n+\t\t\t\t\t},\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: laterId,\n+\t\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\t\tquantity: 1,\n+\t\t\t\t\t\tavailableFrom: '2024-01-10',\n+\t\t\t\t\t\texpiryDate: '2024-02-01',\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t\trules: [{ ...personal, startDate: '2024-01-09', endDate: '2024-01-12' }],\n+\t\t\t});\n+\t\t\texpect(result).toMatchObject({\n+\t\t\t\tkind: 'Plan',\n+\t\t\t\tplacements: [{ date: '2024-01-09', balanceId: earlyId }],\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit('follows the displayed order when loss prevention competes with a personal preference', async () => {\n+\t\tconst first = await createPlanningCalculation({ ...concurrent, rules: [loss, personal] })\n+\t\t\t.outcome;\n+\t\tconst second = await createPlanningCalculation({ ...concurrent, rules: [personal, loss] })\n+\t\t\t.outcome;\n+\t\tif (first.kind !== 'Plan' || second.kind !== 'Plan')\n+\t\t\tthrow new Error('Expected valid plans');\n+\t\texpect(first.placements.map((placement) => placement.balanceId)).toEqual(['risk-rtt']);\n+\t\texpect(first.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(first.preferences[0].satisfied).toBe(0);\n+\t\texpect(second.placements.map((placement) => placement.balanceId)).toEqual(['deferred-cp']);\n+\t\texpect(second.metrics.unplacedAtRisk).toBe(1);\n+\t\texpect(second.preferences[0].satisfied).toBe(1);\n+\t});\n+\n+\tit('keeps typed obligations valid when an optimization would prefer another balance', async () => {\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\t...concurrent,\n+\t\t\trules: [{ ...personal, force: 'obligation' }, loss],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.placements[0]).toMatchObject({\n+\t\t\ttype: 'cp',\n+\t\t\tbalanceId: 'deferred-cp',\n+\t\t\truleIds: ['personal'],\n+\t\t});\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(1);\n+\t});\n+\n+\tit('preserves scarce expiry dates before a lower personal preference', async () => {\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-04' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2024-01-03' },\n+\t\t\t\t{ id: 'rtt', type: 'rtt', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t\t],\n+\t\t\trules: [loss, personal],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(outcome.placements.map(({ date, type }) => ({ date, type }))).toEqual([\n+\t\t\t{ date: '2024-01-02', type: 'rtt' },\n+\t\t\t{ date: '2024-01-03', type: 'cp' },\n+\t\t]);\n+\t\texpect(outcome.preferences[0].satisfied).toBe(0);\n+\t});\n+\n+\tit('can relocate a short chain before adding a balance with a scarce date', async () => {\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-05' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'cp', type: 'cp', quantity: 1, expiryDate: '2024-01-03' },\n+\t\t\t\t{\n+\t\t\t\t\tid: 'flexible',\n+\t\t\t\t\ttype: 'rtt',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2024-01-03',\n+\t\t\t\t\texpiryDate: '2024-01-04',\n+\t\t\t\t},\n+\t\t\t\t{ id: 'scarce', type: 'rtt', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t\t],\n+\t\t\trules: [loss, personal],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(outcome.placements.map(({ date, balanceId }) => ({ date, balanceId }))).toEqual([\n+\t\t\t{ date: '2024-01-02', balanceId: 'scarce' },\n+\t\t\t{ date: '2024-01-03', balanceId: 'cp' },\n+\t\t\t{ date: '2024-01-04', balanceId: 'flexible' },\n+\t\t]);\n+\t});\n+\n+\tit.each(['2024-01-23', '2024-01-24'])(\n+\t\t'finishes oversubscribed balances without an eligible free endpoint through %s',\n+\t\tasync (end) => {\n+\t\t\tconst outcome = await createPlanningCalculation({\n+\t\t\t\tdeadlineMs: 500,\n+\t\t\t\thorizon: { start: '2024-01-02', end },\n+\t\t\t\tbalances: [\n+\t\t\t\t\t{ id: 'cp', type: 'cp', quantity: 7, expiryDate: '2024-01-22' },\n+\t\t\t\t\t{ id: 'rtt', type: 'rtt', quantity: 8, expiryDate: '2024-01-22' },\n+\t\t\t\t\t{ id: 'other', type: 'other', quantity: 1, expiryDate: '2024-01-22' },\n+\t\t\t\t],\n+\t\t\t\trules: [loss],\n+\t\t\t}).outcome;\n+\t\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a completed valid plan');\n+\t\t\texpect(outcome.placements).toHaveLength(15);\n+\t\t\texpect(outcome.metrics.unplacedAtRisk).toBe(1);\n+\t\t},\n+\t);\n+\n+\tit('relocates repeated balance tokens across mandatory windows as a complete chain', async () => {\n+\t\tconst windows = [\n+\t\t\t['cp-first', 'cp', '2024-01-02', '2024-01-03'],\n+\t\t\t['rtt-middle', 'rtt', '2024-01-03', '2024-01-04'],\n+\t\t\t['cp-last', 'cp', '2024-01-04', '2024-01-05'],\n+\t\t].map(([id, placeType, startDate, endDate]) => ({\n+\t\t\tid,\n+\t\t\ttype: 'time_window' as const,\n+\t\t\tforce: 'obligation' as const,\n+\t\t\tplaceType,\n+\t\t\tplaceDays: 1,\n+\t\t\tstartDate,\n+\t\t\tendDate,\n+\t\t}));\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-06' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-01-05' },\n+\t\t\t\t{ id: 'rtt', type: 'rtt', quantity: 1, expiryDate: '2024-01-05' },\n+\t\t\t\t{ id: 'scarce', type: 'other', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t\t],\n+\t\t\trules: [...windows, loss],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(outcome.placements.map(({ date, type }) => ({ date, type }))).toEqual([\n+\t\t\t{ date: '2024-01-02', type: 'other' },\n+\t\t\t{ date: '2024-01-03', type: 'cp' },\n+\t\t\t{ date: '2024-01-04', type: 'rtt' },\n+\t\t\t{ date: '2024-01-05', type: 'cp' },\n+\t\t]);\n+\t});\n+\n+\tit('relocates same-balance tokens with different mandatory provenance', async () => {\n+\t\tconst calculation = createPlanningCalculation({\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-01-05' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-01-04' },\n+\t\t\t\t{ id: 'scarce', type: 'other', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t\t],\n+\t\t\trules: [\n+\t\t\t\t{ ...personal, id: 'first', force: 'obligation', endDate: '2024-01-03' },\n+\t\t\t\t{\n+\t\t\t\t\t...personal,\n+\t\t\t\t\tid: 'second',\n+\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\tstartDate: '2024-01-03',\n+\t\t\t\t\tendDate: '2024-01-04',\n+\t\t\t\t},\n+\t\t\t\tloss,\n+\t\t\t],\n+\t\t});\n+\t\tconst outcome = await calculation.outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\tconst trace = await calculation.trace;\n+\t\texpect(\n+\t\t\ttrace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions)\n+\t\t\t\t.flatMap(({ candidates }) => candidates)\n+\t\t\t\t.some(\n+\t\t\t\t\t({ sourceDate, dates }) =>\n+\t\t\t\t\t\tsourceDate === '2024-01-02' &&\n+\t\t\t\t\t\tdates?.join(',') === '2024-01-02,2024-01-03,2024-01-04',\n+\t\t\t\t),\n+\t\t).toBe(true);\n+\t});\n+\n+\tit('satisfies a lower IF_THEN pattern by reassigning its complete typed bundle', async () => {\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\thorizon: { start: '2027-12-20', end: '2027-12-28' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'A-cp', type: 'cp', quantity: 2, expiryDate: '2027-12-27' },\n+\t\t\t\t{ id: 'B-rtt', type: 'rtt', quantity: 4, expiryDate: '2027-12-27' },\n+\t\t\t],\n+\t\t\trules: [\n+\t\t\t\tloss,\n+\t\t\t\t{\n+\t\t\t\t\tid: 'samedi',\n+\t\t\t\t\tname: 'Samedi Malin',\n+\t\t\t\t\ttype: 'if_then',\n+\t\t\t\t\tdayOfWeek: 6,\n+\t\t\t\t\tplaceDays: 2,\n+\t\t\t\t\tplaceType: 'cp',\n+\t\t\t\t\tplacement: 'auto',\n+\t\t\t\t\trewardDays: 1,\n+\t\t\t\t\trewardType: 'other',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(outcome.preferences[0].satisfied).toBe(1);\n+\t\texpect(\n+\t\t\toutcome.placements.filter(({ type }) => type === 'cp').map(({ date }) => date),\n+\t\t).toEqual(['2027-12-23', '2027-12-24']);\n+\t});\n+\n+\tit('does not classify a period extension without a calendar benefit as supporting', async () => {\n+\t\tconst base: PlanningRequest = {\n+\t\t\thorizon: { start: '2026-12-28', end: '2027-01-09' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'rtt', type: 'rtt', quantity: 1, expiryDate: '2027-01-08' },\n+\t\t\t\t{\n+\t\t\t\t\tid: 'cp',\n+\t\t\t\t\ttype: 'cp',\n+\t\t\t\t\tquantity: 1,\n+\t\t\t\t\tavailableFrom: '2027-01-05',\n+\t\t\t\t\texpiryDate: '2027-02-01',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t\trules: [\n+\t\t\t\t{\n+\t\t\t\t\t...personal,\n+\t\t\t\t\tforce: 'obligation',\n+\t\t\t\t\tstartDate: '2027-01-04',\n+\t\t\t\t\tendDate: '2027-01-04',\n+\t\t\t\t\tplaceType: 'rtt',\n+\t\t\t\t},\n+\t\t\t],\n+\t\t};\n+\t\tconst before = await createPlanningCalculation(base).outcome;\n+\t\tconst after = await createPlanningCalculation({\n+\t\t\t...base,\n+\t\t\trules: [\n+\t\t\t\t...base.rules,\n+\t\t\t\t{ ...loss, configuration: { ...loss.configuration, conditions: [] } },\n+\t\t\t],\n+\t\t}).outcome;\n+\t\tif (before.kind !== 'Plan' || after.kind !== 'Plan')\n+\t\t\tthrow new Error('Expected valid plans');\n+\t\texpect(after.placements.find(({ balanceId }) => balanceId === 'cp')).toMatchObject({\n+\t\t\tdate: '2027-01-05',\n+\t\t\tsupporting: false,\n+\t\t});\n+\t\tfor (const key of [\n+\t\t\t'holidayWeekValue',\n+\t\t\t'nonWorkingDayGain',\n+\t\t\t'longestWorkSequence',\n+\t\t\t'shortSequenceDeficit',\n+\t\t] as const)\n+\t\t\texpect(after.metrics[key]).toBe(before.metrics[key]);\n+\t\texpect(after.metrics.supportingPlacements).toBe(0);\n+\t});\n+\n+\tit('keeps joint window obligations and active priority when large previews are sampled', async () => {\n+\t\tconst obligations = [\n+\t\t\t['2024-01-02', '2024-01-15'],\n+\t\t\t['2024-01-16', '2024-01-29'],\n+\t\t\t['2024-02-01', '2024-02-14'],\n+\t\t].map(([startDate, endDate], index) => ({\n+\t\t\tid: `mandatory-${index}`,\n+\t\t\ttype: 'time_window' as const,\n+\t\t\tforce: 'obligation' as const,\n+\t\t\tstartDate,\n+\t\t\tendDate,\n+\t\t\tplaceDays: 2,\n+\t\t\tplaceType: 'any' as const,\n+\t\t}));\n+\t\tconst request: PlanningRequest = {\n+\t\t\thorizon: { start: '2024-01-02', end: '2024-02-16' },\n+\t\t\tbalances: [\n+\t\t\t\t{ id: 'cp', type: 'cp', quantity: 5, expiryDate: '2024-02-15' },\n+\t\t\t\t{ id: 'scarce', type: 'rtt', quantity: 1, expiryDate: '2024-01-02' },\n+\t\t\t\t{ id: 'deferred', type: 'cp', quantity: 1, expiryDate: '2024-05-01' },\n+\t\t\t],\n+\t\t\trules: [...obligations, loss, personal],\n+\t\t};\n+\t\tconst calculation = createPlanningCalculation(request);\n+\t\tconst outcome = await calculation.outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(0);\n+\t\texpect(outcome.preferences[0].satisfied).toBe(0);\n+\t\tfor (const rule of obligations)\n+\t\t\texpect(\n+\t\t\t\toutcome.placements.filter(({ ruleIds }) => ruleIds.includes(rule.id)),\n+\t\t\t).toHaveLength(2);\n+\t\tconst trace = await calculation.trace;\n+\t\texpect(\n+\t\t\ttrace?.phases\n+\t\t\t\t.flatMap(({ decisions }) => decisions)\n+\t\t\t\t.flatMap(({ candidates }) => candidates)\n+\t\t\t\t.some(\n+\t\t\t\t\t({ status, reason }) =>\n+\t\t\t\t\t\tstatus === 'not-examined' &&\n+\t\t\t\t\t\treason?.code === 'window-obligation-preview-sampling',\n+\t\t\t\t),\n+\t\t).toBe(true);\n+\t\tconst reversed = await createPlanningCalculation({\n+\t\t\t...request,\n+\t\t\trules: [...obligations, personal, loss],\n+\t\t}).outcome;\n+\t\tif (reversed.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(reversed.preferences[0].satisfied).toBe(1);\n+\t\texpect(reversed.metrics.unplacedAtRisk).toBe(1);\n+\t}, 20_000);\n+\n+\tit('allows a lower typed preference to choose the balance when loss quantities tie', async () => {\n+\t\tconst outcome = await createPlanningCalculation({\n+\t\t\t...concurrent,\n+\t\t\tbalances: concurrent.balances.map((balance) => ({\n+\t\t\t\t...balance,\n+\t\t\t\texpiryDate: '2024-01-02',\n+\t\t\t})),\n+\t\t\trules: [loss, personal],\n+\t\t}).outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a valid plan');\n+\t\texpect(outcome.placements[0].type).toBe('cp');\n+\t\texpect(outcome.metrics.unplacedAtRisk).toBe(1);\n+\t\texpect(outcome.preferences[0].satisfied).toBe(1);\n+\t});\n+\n+\tit('makes a disabled optimization equivalent to its absence, including all-disabled requests', async () => {\n+\t\tfor (const otherRules of [[], [personal]]) {\n+\t\t\tconst absent = await createPlanningCalculation({ ...concurrent, rules: otherRules })\n+\t\t\t\t.outcome;\n+\t\t\tconst disabled = await createPlanningCalculation({\n+\t\t\t\t...concurrent,\n+\t\t\t\trules: [{ ...loss, enabled: false }, ...otherRules],\n+\t\t\t}).outcome;\n+\t\t\texpect(disabled).toEqual(absent);\n+\t\t}\n+\t});\n+\n+\tit.each([\n+\t\t{ ...OPTIMIZATION_PRESETS.unplacedAtRisk, aggregation: 'average' },\n+\t\t{ ...OPTIMIZATION_PRESETS.unplacedAtRisk, conditions: ['complete'] },\n+\t\tnull,\n+\t])(\n+\t\t'rejects incompatible or malformed active configurations without an obligation conflict: %s',\n+\t\tasync (configuration) => {\n+\t\t\tconst outcome = calculatePlanningInternal({\n+\t\t\t\t...concurrent,\n+\t\t\t\trules: [{ ...loss, configuration }],\n+\t\t\t});\n+\t\t\texpect(outcome.kind).toBe('InvalidInput');\n+\t\t\tif (outcome.kind !== 'InvalidInput') return;\n+\t\t\texpect(outcome.reasons[0].ruleIds).toEqual(['loss']);\n+\t\t\texpect(outcome.reasons[0].code).toMatch(\n+\t\t\t\t/^(invalid|unsupported)-optimization-configuration$/,\n+\t\t\t);\n+\t\t},\n+\t);\n+\n+\tit('rejects obligation mode for an optimization and ignores a malformed disabled rule', async () => {\n+\t\tconst invalid = calculatePlanningInternal({\n+\t\t\t...concurrent,\n+\t\t\trules: [{ ...loss, force: 'obligation' }],\n+\t\t});\n+\t\texpect(invalid).toMatchObject({\n+\t\t\tkind: 'InvalidInput',\n+\t\t\treasons: [expect.objectContaining({ code: 'rule-force', ruleIds: ['loss'] })],\n+\t\t});\n+\t\tconst disabled = calculatePlanningInternal({\n+\t\t\t...concurrent,\n+\t\t\trules: [{ ...loss, enabled: false, configuration: null }],\n+\t\t});\n+\t\texpect(disabled).toMatchObject({ kind: 'Plan', placements: [] });\n+\t});\n+\n+\tit('keeps direct snapshots and every explanation/comparison in the submitted active order', async () => {\n+\t\tconst configuration: OptimizationConfiguration = structuredClone(\n+\t\t\tOPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t);\n+\t\tconst rule = { ...loss, configuration };\n+\t\tconst calculation = createPlanningCalculation({ ...concurrent, rules: [rule, personal] });\n+\t\tconfiguration.conditions = [];\n+\t\tconfiguration.aggregation = 'count';\n+\t\tconfiguration.direction = 'maximize';\n+\t\trule.name = 'Edited later';\n+\t\tconst outcome = await calculation.outcome;\n+\t\tif (outcome.kind !== 'Plan') throw new Error('Expected a plan');\n+\t\texpect(outcome.placements[0].balanceId).toBe('risk-rtt');\n+\t\texpect(calculation.snapshot.rules[0]).toMatchObject({\n+\t\t\tname: 'Prevent losses',\n+\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t});\n+\t\texpect(Object.isFrozen(calculation.snapshot.rules[0])).toBe(true);\n+\t\tconst explanation = await calculation.explanation;\n+\t\tif (explanation?.kind !== 'PlanExplanation') throw new Error('Expected an explanation');\n+\t\tconst ids = [\n+\t\t\t'obligation-validity',\n+\t\t\t'optimization:loss',\n+\t\t\t'preference:personal',\n+\t\t\t'balance-expiry',\n+\t\t\t'placement-date',\n+\t\t];\n+\t\texpect(\n+\t\t\texplanation.placements[0].objectiveVector.objectives.map((objective) => objective.id),\n+\t\t).toEqual(ids);\n+\t\texpect(explanation.placements[0].objectiveVector.objectives[1].label).toBe(\n+\t\t\t'Prevent losses',\n+\t\t);\n+\t\tconst trace = await calculation.trace;\n+\t\texpect(trace?.phases.map((phase) => phase.name)).toEqual([\n+\t\t\t'validation',\n+\t\t\t'obligations',\n+\t\t\t'optimization:loss',\n+\t\t\t'preference:personal',\n+\t\t\t'expiry',\n+\t\t\t'dates',\n+\t\t]);\n+\t\tconst comparison = await calculation.analyzeCounterfactual(outcome.placements[0]);\n+\t\tif (comparison.kind !== 'Counterfactual') throw new Error('Expected comparison');\n+\t\texpect(comparison.baseline.objectives.map((objective) => objective.id)).toEqual(ids);\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/services/optimization-rule.spec.ts", "project_id": 35, "relative_order": 31, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -5,11 +5,12 @@ import { RuleService, RuleType } from './rule-service';\n import { UserInputService } from './user-input-service';\n import { createPlanningCalculation } from './leave-planner.service';\n import { PlanningDurationService } from './planning-duration.service';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n \n describe('Planning duration estimate', () => {\n \tbeforeEach(() => {\n \t\tlocalStorage.clear();\n-\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\tTestBed.inject(CalendarSettingsService).setPlanningDates('2024-01-01', '2024-12-31');\n \t\tTestBed.inject(UserInputService).updateBalances(() => [\n \t\t\t{\n@@ -34,6 +35,22 @@ describe('Planning duration estimate', () => {\n \t\texpect(TestBed.inject(RuleService).rules).toEqual([]);\n \t});\n \n+\tit('estimates and calibrates optimization rules without a requested leave quantity', () => {\n+\t\tconst rules = TestBed.inject(RuleService);\n+\t\trules.addRule({\n+\t\t\tid: 'loss',\n+\t\t\tname: 'Loss',\n+\t\t\ttype: RuleType.OPTIMIZATION,\n+\t\t\tenabled: true,\n+\t\t\tforce: 'preference',\n+\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),\n+\t\t});\n+\t\tconst duration = TestBed.inject(PlanningDurationService);\n+\t\texpect(Number.isFinite(duration.estimate()!.maximum)).toBe(true);\n+\t\tduration.recordCompletion(duration.request()!, 20_000);\n+\t\texpect(duration.estimate()).toEqual({ minimum: 10, maximum: 60, unit: 'seconds' });\n+\t});\n+\n \tit('updates for dates, balances and active rules without requesting a calculation', () => {\n \t\tconst duration = TestBed.inject(PlanningDurationService);\n \t\tconst settings = TestBed.inject(CalendarSettingsService);\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/planning-duration.service.spec.ts", "project_id": 35, "relative_order": 32, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -41,7 +41,9 @@ function initialDurationMs(request: PlanningRequest): number {\n \t\t\t(dateTime(rule.startDate) >= end || dateTime(rule.endDate) < start)\n \t\t)\n \t\t\tcontinue;\n-\t\truleWeight += (rule.force === 'obligation' ? 0.5 : 0.15) * Math.max(1, rule.placeDays / 3);\n+\t\truleWeight +=\n+\t\t\t(rule.force === 'obligation' ? 0.5 : 0.15) *\n+\t\t\tMath.max(1, 'placeDays' in rule ? rule.placeDays / 3 : 1);\n \t\tif ('rewardDays' in rule) placements += (Math.max(0, rule.rewardDays) * days) / 365.25;\n \t}\n \t// Rough prior from the browser references in docs/planning-duration.md, not a deadline.\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/planning-duration.service.ts", "project_id": 35, "relative_order": 33, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,193 @@\n+import { describe, expect, it } from 'vitest';\n+import {\n+\tcompareObjectiveLists,\n+\tcompareObjectiveValues,\n+\tevaluateOptimization,\n+\tfirstDifferentObjective,\n+\tOPTIMIZATION_PRESETS,\n+\toptimizationUnit,\n+\tvalidateOptimizationConfiguration,\n+\ttype OptimizationObservations,\n+} from './planning-objectives';\n+\n+const empty: OptimizationObservations = {\n+\tleaveBalances: [],\n+\tpublicHolidayWeeks: [],\n+\ttimeOffPeriods: [],\n+\tworkSequences: [],\n+\tleavePlacements: [],\n+};\n+\n+describe('composable planning objectives', () => {\n+\tit('evaluates each internal non-empty sequence with its own working-day threshold', () => {\n+\t\tconst observations: OptimizationObservations = {\n+\t\t\t...empty,\n+\t\t\tworkSequences: [\n+\t\t\t\t{ length: 1, internal: false },\n+\t\t\t\t{ length: 0, internal: true },\n+\t\t\t\t{ length: 1, internal: true },\n+\t\t\t\t{ length: 4, internal: true },\n+\t\t\t\t{ length: 6, internal: false },\n+\t\t\t],\n+\t\t};\n+\t\texpect(evaluateOptimization(OPTIMIZATION_PRESETS.shortSequenceDeficit, observations)).toBe(\n+\t\t\t5,\n+\t\t);\n+\t\texpect(\n+\t\t\tevaluateOptimization(\n+\t\t\t\t{ ...OPTIMIZATION_PRESETS.shortSequenceDeficit, thresholdDays: 3 },\n+\t\t\t\tobservations,\n+\t\t\t),\n+\t\t).toBe(2);\n+\t\texpect(evaluateOptimization(OPTIMIZATION_PRESETS.longestWorkSequence, observations)).toBe(\n+\t\t\t6,\n+\t\t);\n+\t});\n+\n+\tit('evaluates all six recipes from the same concrete observations', () => {\n+\t\tconst observations: OptimizationObservations = {\n+\t\t\tleaveBalances: [\n+\t\t\t\t{ unplacedQuantity: 3, atRisk: true },\n+\t\t\t\t{ unplacedQuantity: 8, atRisk: false },\n+\t\t\t],\n+\t\t\tpublicHolidayWeeks: [\n+\t\t\t\t{ value: 3, complete: true },\n+\t\t\t\t{ value: 1, complete: false },\n+\t\t\t\t{ value: 4, complete: true },\n+\t\t\t],\n+\t\t\ttimeOffPeriods: [\n+\t\t\t\t{ nonWorkingDates: ['2024-01-06', '2024-01-07'] },\n+\t\t\t\t{ nonWorkingDates: ['2024-05-08', '2024-05-09', '2024-05-09'] },\n+\t\t\t],\n+\t\t\tworkSequences: [\n+\t\t\t\t{ length: 1, internal: false },\n+\t\t\t\t{ length: 0, internal: true },\n+\t\t\t\t{ length: 1, internal: true },\n+\t\t\t\t{ length: 4, internal: true },\n+\t\t\t\t{ length: 6, internal: false },\n+\t\t\t],\n+\t\t\tleavePlacements: [{ supporting: true }, { supporting: false }, { supporting: true }],\n+\t\t};\n+\t\texpect(\n+\t\t\tObject.values(OPTIMIZATION_PRESETS).map((configuration) =>\n+\t\t\t\tevaluateOptimization(configuration, observations),\n+\t\t\t),\n+\t\t).toEqual([3, 7, 4, 6, 5, 2]);\n+\t});\n+\n+\tit.each(['sum', 'count', 'maximum'] as const)(\n+\t\t'defines empty %s as zero for every measure',\n+\t\t(aggregation) => {\n+\t\t\tfor (const configuration of Object.values(OPTIMIZATION_PRESETS)) {\n+\t\t\t\texpect(evaluateOptimization({ ...configuration, aggregation }, empty)).toBe(0);\n+\t\t\t}\n+\t\t},\n+\t);\n+\n+\tit('composes conditions, aggregation and direction independently of a rule name or identity', () => {\n+\t\tconst configuration = {\n+\t\t\t...OPTIMIZATION_PRESETS.longestWorkSequence,\n+\t\t\tconditions: ['internal', 'non-empty'] as const,\n+\t\t\taggregation: 'sum' as const,\n+\t\t\tdirection: 'maximize' as const,\n+\t\t};\n+\t\tconst observations: OptimizationObservations = {\n+\t\t\t...empty,\n+\t\t\tworkSequences: [\n+\t\t\t\t{ length: 20, internal: false },\n+\t\t\t\t{ length: 0, internal: true },\n+\t\t\t\t{ length: 2, internal: true },\n+\t\t\t\t{ length: 4, internal: true },\n+\t\t\t],\n+\t\t};\n+\t\tconst rules = [\n+\t\t\t{ id: 'provided', name: 'Original name', configuration },\n+\t\t\t{ id: 'personal', name: 'Renamed rule', configuration: structuredClone(configuration) },\n+\t\t];\n+\t\texpect(rules.map((rule) => evaluateOptimization(rule.configuration, observations))).toEqual(\n+\t\t\t[6, 6],\n+\t\t);\n+\t\texpect(evaluateOptimization({ ...configuration, aggregation: 'count' }, observations)).toBe(\n+\t\t\t2,\n+\t\t);\n+\t\texpect(\n+\t\t\tevaluateOptimization({ ...configuration, aggregation: 'maximum' }, observations),\n+\t\t).toBe(4);\n+\t\texpect(optimizationUnit(configuration)).toBe('working-days');\n+\t\texpect(optimizationUnit({ ...configuration, aggregation: 'count' })).toBe('count');\n+\t\texpect(optimizationUnit(OPTIMIZATION_PRESETS.nonWorkingDayGain)).toBe('calendar-days');\n+\t});\n+\n+\tit.each([\n+\t\t0,\n+\t\t-1,\n+\t\t1.5,\n+\t\tNumber.NaN,\n+\t\tNumber.POSITIVE_INFINITY,\n+\t\tundefined,\n+\t\t'3',\n+\t\tNumber.MAX_SAFE_INTEGER + 1,\n+\t])('rejects the invalid working-day deficit threshold %s', (thresholdDays) => {\n+\t\texpect(\n+\t\t\tvalidateOptimizationConfiguration({\n+\t\t\t\t...OPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t\tthresholdDays,\n+\t\t\t}),\n+\t\t).toMatchObject({ valid: false, code: 'invalid-optimization-configuration' });\n+\t});\n+\n+\tit.each([\n+\t\t{ ...OPTIMIZATION_PRESETS.nonWorkingDayGain, elements: 'work-sequences' },\n+\t\t{ ...OPTIMIZATION_PRESETS.nonWorkingDayGain, conditions: ['at-risk'] },\n+\t\t{ ...OPTIMIZATION_PRESETS.longestWorkSequence, aggregation: 'average' },\n+\t\t{ ...OPTIMIZATION_PRESETS.longestWorkSequence, thresholdDays: 3 },\n+\t\t{ ...OPTIMIZATION_PRESETS.shortSequenceDeficit, thresholdUnit: 'calendar-days' },\n+\t])('identifies an unsupported composition', (configuration) => {\n+\t\texpect(validateOptimizationConfiguration(configuration)).toMatchObject({\n+\t\t\tvalid: false,\n+\t\t\tcode: 'unsupported-optimization-configuration',\n+\t\t});\n+\t});\n+\n+\tit.each([\n+\t\tnull,\n+\t\t[],\n+\t\t{ ...OPTIMIZATION_PRESETS.shortSequenceDeficit, conditions: ['internal', 'internal'] },\n+\t\t{ ...OPTIMIZATION_PRESETS.longestWorkSequence, direction: 'up' },\n+\t\t{ ...OPTIMIZATION_PRESETS.unplacedAtRisk, conditions: new Array(1) },\n+\t])('rejects malformed configurations', (configuration) => {\n+\t\texpect(validateOptimizationConfiguration(configuration)).toMatchObject({\n+\t\t\tvalid: false,\n+\t\t\tcode: 'invalid-optimization-configuration',\n+\t\t});\n+\t});\n+\n+\tit('never evaluates an unsupported configuration as a preset', () => {\n+\t\texpect(() =>\n+\t\t\tevaluateOptimization(\n+\t\t\t\t{ ...OPTIMIZATION_PRESETS.nonWorkingDayGain, elements: 'work-sequences' },\n+\t\t\t\tempty,\n+\t\t\t),\n+\t\t).toThrow('unsupported-optimization-configuration');\n+\t});\n+\n+\tit('compares ordered objectives lexicographically with the configured directions', () => {\n+\t\tconst before = [\n+\t\t\t{ id: 'first', direction: 'minimize' as const, value: 3 },\n+\t\t\t{ id: 'second', direction: 'maximize' as const, value: 100 },\n+\t\t\t{ id: 'date', direction: 'minimize' as const, value: '2024-01-10' },\n+\t\t];\n+\t\tconst earlierPriority = [{ ...before[0], value: 2 }, { ...before[1], value: 0 }, before[2]];\n+\t\texpect(compareObjectiveLists(earlierPriority, before)).toBeLessThan(0);\n+\t\texpect(firstDifferentObjective(earlierPriority, before)).toBe(0);\n+\t\tconst laterPriority = [before[0], { ...before[1], value: 101 }, before[2]];\n+\t\texpect(compareObjectiveLists(laterPriority, before)).toBeLessThan(0);\n+\t\texpect(firstDifferentObjective(laterPriority, before)).toBe(1);\n+\t\tconst earlierDate = [before[0], before[1], { ...before[2], value: '2024-01-09' }];\n+\t\texpect(compareObjectiveLists(earlierDate, before)).toBeLessThan(0);\n+\t\texpect(firstDifferentObjective(earlierDate, before)).toBe(2);\n+\t\texpect(compareObjectiveLists(before, structuredClone(before))).toBe(0);\n+\t\texpect(firstDifferentObjective(before, structuredClone(before))).toBe(-1);\n+\t\texpect(compareObjectiveValues('maximize', 0, 0)).toBe(0);\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/services/planning-objectives.spec.ts", "project_id": 35, "relative_order": 34, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,300 @@\n+export type OptimizationElements =\n+\t| 'leave-balances'\n+\t| 'public-holiday-weeks'\n+\t| 'time-off-periods'\n+\t| 'work-sequences'\n+\t| 'leave-placements';\n+export type OptimizationCondition =\n+\t| 'at-risk'\n+\t| 'complete'\n+\t| 'internal'\n+\t| 'non-empty'\n+\t| 'supporting';\n+export type OptimizationMeasure =\n+\t| 'unplaced-quantity'\n+\t| 'public-holiday-week-value'\n+\t| 'non-working-day-gain'\n+\t| 'work-sequence-length'\n+\t| 'work-sequence-deficit'\n+\t| 'placement-count';\n+export type OptimizationAggregation = 'sum' | 'count' | 'maximum';\n+export type OptimizationDirection = 'minimize' | 'maximize';\n+export type OptimizationUnit = 'working-days' | 'calendar-days' | 'count';\n+\n+interface OptimizationConfigurationBase {\n+\telements: OptimizationElements;\n+\tconditions: readonly OptimizationCondition[];\n+\taggregation: OptimizationAggregation;\n+\tdirection: OptimizationDirection;\n+}\n+\n+export type OptimizationConfiguration = OptimizationConfigurationBase &\n+\t(\n+\t\t| { measure: 'work-sequence-deficit'; thresholdDays: number }\n+\t\t| { measure: Exclude; thresholdDays?: never }\n+\t);\n+\n+/** Each row accepts any subset of its conditions and both comparison directions. */\n+export const OPTIMIZATION_CATALOG = [\n+\t{\n+\t\telements: 'leave-balances',\n+\t\tmeasure: 'unplaced-quantity',\n+\t\tconditions: ['at-risk'],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'working-days',\n+\t},\n+\t{\n+\t\telements: 'public-holiday-weeks',\n+\t\tmeasure: 'public-holiday-week-value',\n+\t\tconditions: ['complete'],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'calendar-days',\n+\t},\n+\t{\n+\t\telements: 'time-off-periods',\n+\t\tmeasure: 'non-working-day-gain',\n+\t\tconditions: [],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'calendar-days',\n+\t},\n+\t{\n+\t\telements: 'work-sequences',\n+\t\tmeasure: 'work-sequence-length',\n+\t\tconditions: ['internal', 'non-empty'],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'working-days',\n+\t},\n+\t{\n+\t\telements: 'work-sequences',\n+\t\tmeasure: 'work-sequence-deficit',\n+\t\tconditions: ['internal', 'non-empty'],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'working-days',\n+\t},\n+\t{\n+\t\telements: 'leave-placements',\n+\t\tmeasure: 'placement-count',\n+\t\tconditions: ['supporting'],\n+\t\taggregations: ['sum', 'count', 'maximum'],\n+\t\tunit: 'count',\n+\t},\n+] as const;\n+\n+export type OptimizationValidation =\n+\t| { valid: true; configuration: OptimizationConfiguration }\n+\t| {\n+\t\t\tvalid: false;\n+\t\t\tcode: 'invalid-optimization-configuration' | 'unsupported-optimization-configuration';\n+\t\t\tmessage: string;\n+\t };\n+\n+export function validateOptimizationConfiguration(value: unknown): OptimizationValidation {\n+\tconst invalid = (message: string): OptimizationValidation => ({\n+\t\tvalid: false,\n+\t\tcode: 'invalid-optimization-configuration',\n+\t\tmessage,\n+\t});\n+\tconst unsupported = (message: string): OptimizationValidation => ({\n+\t\tvalid: false,\n+\t\tcode: 'unsupported-optimization-configuration',\n+\t\tmessage,\n+\t});\n+\tif (!value || typeof value !== 'object' || Array.isArray(value))\n+\t\treturn invalid('An optimization configuration must be an object.');\n+\tconst config = value as Record;\n+\tconst fields = [\n+\t\t'elements',\n+\t\t'conditions',\n+\t\t'measure',\n+\t\t'aggregation',\n+\t\t'direction',\n+\t\t'thresholdDays',\n+\t];\n+\tif (Object.keys(config).some((key) => !fields.includes(key)))\n+\t\treturn unsupported('The optimization configuration contains an unsupported field.');\n+\tif (config['direction'] !== 'minimize' && config['direction'] !== 'maximize')\n+\t\treturn invalid('The optimization direction must be minimize or maximize.');\n+\tif (\n+\t\t!Array.isArray(config['conditions']) ||\n+\t\t[...config['conditions']].some((condition) => typeof condition !== 'string') ||\n+\t\tnew Set(config['conditions']).size !== config['conditions'].length\n+\t)\n+\t\treturn invalid('Optimization conditions must be a list of distinct conditions.');\n+\tconst row = OPTIMIZATION_CATALOG.find(\n+\t\t(item) => item.elements === config['elements'] && item.measure === config['measure'],\n+\t);\n+\tif (!row) return unsupported('The planning elements and measure are not compatible.');\n+\tconst conditions: readonly string[] = row.conditions;\n+\tif (config['conditions'].some((condition) => !conditions.includes(condition)))\n+\t\treturn unsupported('A condition is not supported for these planning elements.');\n+\tconst aggregations: readonly string[] = row.aggregations;\n+\tif (typeof config['aggregation'] !== 'string' || !aggregations.includes(config['aggregation']))\n+\t\treturn unsupported('The aggregation is not supported for this measure.');\n+\tif (config['measure'] === 'work-sequence-deficit') {\n+\t\tif (!Number.isSafeInteger(config['thresholdDays']) || Number(config['thresholdDays']) <= 0)\n+\t\t\treturn invalid('The deficit threshold must be a positive integer in working days.');\n+\t} else if ('thresholdDays' in config)\n+\t\treturn unsupported('Only the work-sequence deficit accepts a working-day threshold.');\n+\treturn { valid: true, configuration: value as OptimizationConfiguration };\n+}\n+\n+export function optimizationUnit(configuration: OptimizationConfiguration): OptimizationUnit {\n+\treturn configuration.aggregation === 'count'\n+\t\t? 'count'\n+\t\t: OPTIMIZATION_CATALOG.find(\n+\t\t\t\t(row) =>\n+\t\t\t\t\trow.elements === configuration.elements &&\n+\t\t\t\t\trow.measure === configuration.measure,\n+\t\t\t)!.unit;\n+}\n+\n+export const OPTIMIZATION_PRESETS = {\n+\tunplacedAtRisk: {\n+\t\telements: 'leave-balances',\n+\t\tconditions: ['at-risk'],\n+\t\tmeasure: 'unplaced-quantity',\n+\t\taggregation: 'sum',\n+\t\tdirection: 'minimize',\n+\t},\n+\tholidayWeekValue: {\n+\t\telements: 'public-holiday-weeks',\n+\t\tconditions: ['complete'],\n+\t\tmeasure: 'public-holiday-week-value',\n+\t\taggregation: 'sum',\n+\t\tdirection: 'maximize',\n+\t},\n+\tnonWorkingDayGain: {\n+\t\telements: 'time-off-periods',\n+\t\tconditions: [],\n+\t\tmeasure: 'non-working-day-gain',\n+\t\taggregation: 'sum',\n+\t\tdirection: 'maximize',\n+\t},\n+\tlongestWorkSequence: {\n+\t\telements: 'work-sequences',\n+\t\tconditions: [],\n+\t\tmeasure: 'work-sequence-length',\n+\t\taggregation: 'maximum',\n+\t\tdirection: 'minimize',\n+\t},\n+\tshortSequenceDeficit: {\n+\t\telements: 'work-sequences',\n+\t\tconditions: ['internal', 'non-empty'],\n+\t\tmeasure: 'work-sequence-deficit',\n+\t\tthresholdDays: 5,\n+\t\taggregation: 'sum',\n+\t\tdirection: 'minimize',\n+\t},\n+\tsupportingPlacements: {\n+\t\telements: 'leave-placements',\n+\t\tconditions: ['supporting'],\n+\t\tmeasure: 'placement-count',\n+\t\taggregation: 'count',\n+\t\tdirection: 'minimize',\n+\t},\n+} as const satisfies Record;\n+\n+/** Concrete observations from one plan; they carry no rule identity or display name. */\n+export interface OptimizationObservations {\n+\tleaveBalances: readonly { unplacedQuantity: number; atRisk: boolean }[];\n+\tpublicHolidayWeeks: readonly { value: number; complete: boolean }[];\n+\ttimeOffPeriods: readonly { nonWorkingDates: readonly string[] }[];\n+\tworkSequences: readonly { length: number; internal: boolean }[];\n+\tleavePlacements: readonly { supporting: boolean }[];\n+}\n+\n+export function evaluateOptimization(\n+\tconfiguration: OptimizationConfiguration,\n+\tobservations: OptimizationObservations,\n+): number {\n+\tconst validation = validateOptimizationConfiguration(configuration);\n+\tif (!validation.valid) throw new Error(`${validation.code}: ${validation.message}`);\n+\tconst selected = (condition: OptimizationCondition) =>\n+\t\tconfiguration.conditions.includes(condition);\n+\tlet values: number[];\n+\tswitch (configuration.elements) {\n+\t\tcase 'leave-balances':\n+\t\t\tvalues = observations.leaveBalances\n+\t\t\t\t.filter((balance) => !selected('at-risk') || balance.atRisk)\n+\t\t\t\t.map((balance) => balance.unplacedQuantity);\n+\t\t\tbreak;\n+\t\tcase 'public-holiday-weeks':\n+\t\t\tvalues = observations.publicHolidayWeeks\n+\t\t\t\t.filter((week) => !selected('complete') || week.complete)\n+\t\t\t\t.map((week) => week.value);\n+\t\t\tbreak;\n+\t\tcase 'time-off-periods':\n+\t\t\tvalues = observations.timeOffPeriods.map(\n+\t\t\t\t(period) => new Set(period.nonWorkingDates).size,\n+\t\t\t);\n+\t\t\tbreak;\n+\t\tcase 'work-sequences':\n+\t\t\tvalues = observations.workSequences\n+\t\t\t\t.filter(\n+\t\t\t\t\t(sequence) =>\n+\t\t\t\t\t\t(!selected('internal') || sequence.internal) &&\n+\t\t\t\t\t\t(!selected('non-empty') || sequence.length > 0),\n+\t\t\t\t)\n+\t\t\t\t.map((sequence) =>\n+\t\t\t\t\tconfiguration.measure === 'work-sequence-deficit'\n+\t\t\t\t\t\t? sequence.length > 0\n+\t\t\t\t\t\t\t? Math.max(0, configuration.thresholdDays - sequence.length)\n+\t\t\t\t\t\t\t: 0\n+\t\t\t\t\t\t: sequence.length,\n+\t\t\t\t);\n+\t\t\tbreak;\n+\t\tcase 'leave-placements':\n+\t\t\tvalues = observations.leavePlacements\n+\t\t\t\t.filter((placement) => !selected('supporting') || placement.supporting)\n+\t\t\t\t.map(() => 1);\n+\t}\n+\tswitch (configuration.aggregation) {\n+\t\tcase 'count':\n+\t\t\treturn values.length;\n+\t\tcase 'sum':\n+\t\t\treturn values.reduce((total, value) => total + value, 0);\n+\t\tcase 'maximum':\n+\t\t\treturn values.reduce((maximum, value) => Math.max(maximum, value), 0);\n+\t}\n+}\n+\n+export interface ComparableObjective {\n+\tid: string;\n+\tdirection: OptimizationDirection;\n+\tvalue: number | string;\n+}\n+\n+/** Negative means the left candidate is preferred. Strings retain lexical tie-break ordering. */\n+export function compareObjectiveValues(\n+\tdirection: OptimizationDirection,\n+\tleft: number | string,\n+\tright: number | string,\n+): number {\n+\tif (left === right) return 0;\n+\tconst difference =\n+\t\ttypeof left === 'number' && typeof right === 'number'\n+\t\t\t? left - right\n+\t\t\t: left < right\n+\t\t\t\t? -1\n+\t\t\t\t: left > right\n+\t\t\t\t\t? 1\n+\t\t\t\t\t: 0;\n+\treturn direction === 'minimize' ? difference : -difference;\n+}\n+\n+export function firstDifferentObjective(\n+\tleft: readonly ComparableObjective[],\n+\tright: readonly ComparableObjective[],\n+): number {\n+\treturn left.findIndex((objective, index) => objective.value !== right[index]?.value);\n+}\n+\n+export function compareObjectiveLists(\n+\tleft: readonly ComparableObjective[],\n+\tright: readonly ComparableObjective[],\n+): number {\n+\tconst index = firstDifferentObjective(left, right);\n+\treturn index < 0\n+\t\t? 0\n+\t\t: compareObjectiveValues(left[index].direction, left[index].value, right[index].value);\n+}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/services/planning-objectives.ts", "project_id": 35, "relative_order": 35, "renamed_file": false, "too_large": false }, { "a_mode": "0", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -0,0 +1,288 @@\n+import { TestBed } from '@angular/core/testing';\n+import { RuleService, RuleType } from './rule-service';\n+import { vi } from 'vitest';\n+import { CalendarSettingsService } from './calendar-settings-service';\n+import { PlanningDurationService } from './planning-duration.service';\n+import { UserInputService } from './user-input-service';\n+import { SelectableDayType } from './calendar-service';\n+import { createPlanningCalculation } from './leave-planner.service';\n+\n+describe('saved rule migration', () => {\n+\tbeforeEach(() => localStorage.clear());\n+\tafterEach(() => {\n+\t\tvi.restoreAllMocks();\n+\t\tvi.unstubAllGlobals();\n+\t\tTestBed.resetTestingModule();\n+\t\tlocalStorage.clear();\n+\t});\n+\n+\tit('restores every legacy record unchanged between loss prevention and the other five presets', () => {\n+\t\tconst legacy = [\n+\t\t\t{\n+\t\t\t\tid: 'personal-window',\n+\t\t\t\tname: 'My fixed window',\n+\t\t\t\ttype: RuleType.TIME_WINDOW,\n+\t\t\t\tenabled: true,\n+\t\t\t\tforce: 'obligation',\n+\t\t\t\tstartDate: '2024-01-10',\n+\t\t\t\tendDate: '2024-01-12',\n+\t\t\t\tplaceDays: 2,\n+\t\t\t\tplaceType: 'cp',\n+\t\t\t},\n+\t\t\t{\n+\t\t\t\tid: 'personal-pattern',\n+\t\t\t\tname: 'My disabled pattern',\n+\t\t\t\ttype: RuleType.IF_THEN,\n+\t\t\t\tenabled: false,\n+\t\t\t\tdayOfWeek: 6,\n+\t\t\t\tplaceDays: 2,\n+\t\t\t\tplaceType: 'cp',\n+\t\t\t\tplacement: 'around',\n+\t\t\t\trewardDays: 1,\n+\t\t\t\trewardType: 'other',\n+\t\t\t},\n+\t\t];\n+\t\tlocalStorage.setItem('vacationRules', JSON.stringify(legacy));\n+\t\tconst service = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toHaveLength(8);\n+\t\texpect(service.rules.slice(1, 3).map(({ id }) => id)).toEqual([\n+\t\t\t'personal-window',\n+\t\t\t'personal-pattern',\n+\t\t]);\n+\t\tconst saved = JSON.parse(localStorage.getItem('vacationRules')!);\n+\t\texpect(saved.version).toBe(1);\n+\t\texpect(saved.rules.slice(1, 3)).toEqual(legacy);\n+\t\texpect(service.rules[2].force).toBe('preference');\n+\t\texpect(saved.rules[2]).not.toHaveProperty('force');\n+\t});\n+\n+\tit('gives fresh users the six active presets around the two existing initial rules', () => {\n+\t\tconst service = TestBed.inject(RuleService);\n+\t\texpect(service.rules.map(({ id }) => id)).toEqual([\n+\t\t\t'default-unplaced-at-risk',\n+\t\t\t'default-samedi-malin',\n+\t\t\t'default-christmas',\n+\t\t\t'default-holiday-week-value',\n+\t\t\t'default-non-working-day-gain',\n+\t\t\t'default-longest-work-sequence',\n+\t\t\t'default-short-sequence-deficit',\n+\t\t\t'default-supporting-placements',\n+\t\t]);\n+\t\tconst presets = service.rules.filter(({ type }) => type === RuleType.OPTIMIZATION);\n+\t\texpect(presets).toHaveLength(6);\n+\t\texpect(presets.every(({ enabled, force }) => enabled && force === 'preference')).toBe(true);\n+\t});\n+\n+\tit('migrates an old empty list once and retains editing, order, disabled and deleted choices immediately', () => {\n+\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlet service = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toHaveLength(6);\n+\t\tconst deficit = service.rules[4];\n+\t\tif (\n+\t\t\tdeficit.type !== RuleType.OPTIMIZATION ||\n+\t\t\tdeficit.configuration.measure !== 'work-sequence-deficit'\n+\t\t)\n+\t\t\tthrow new Error('Expected the deficit preset');\n+\t\tservice.updateRule({\n+\t\t\t...deficit,\n+\t\t\tname: 'My three-day deficit',\n+\t\t\tconfiguration: { ...deficit.configuration, thresholdDays: 3 },\n+\t\t});\n+\t\tservice.reorderRules(4, 0);\n+\t\tservice.toggleRule(deficit.id);\n+\t\tservice.deleteRule('default-holiday-week-value');\n+\t\tconst expected = service.rules;\n+\t\tTestBed.resetTestingModule();\n+\t\tservice = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toEqual(expected);\n+\t\texpect(service.rules[0]).toMatchObject({\n+\t\t\tname: 'My three-day deficit',\n+\t\t\tenabled: false,\n+\t\t\tconfiguration: { thresholdDays: 3 },\n+\t\t});\n+\t\tfor (const rule of service.rules) service.deleteRule(rule.id);\n+\t\tTestBed.resetTestingModule();\n+\t\texpect(TestBed.inject(RuleService).rules).toEqual([]);\n+\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!)).toEqual({\n+\t\t\tversion: 1,\n+\t\t\trules: [],\n+\t\t});\n+\t});\n+\n+\tit('avoids colliding with existing custom identities without replacing their records', () => {\n+\t\tconst custom = ['default-unplaced-at-risk', 'default-unplaced-at-risk-2'].map((id) => ({\n+\t\t\tid,\n+\t\t\tname: id,\n+\t\t\ttype: RuleType.IF_THEN,\n+\t\t\tenabled: false,\n+\t\t\tdayOfWeek: 6,\n+\t\t\tplaceDays: 2,\n+\t\t\tplaceType: 'cp',\n+\t\t\tplacement: 'auto',\n+\t\t\trewardDays: 1,\n+\t\t\trewardType: 'other',\n+\t\t}));\n+\t\tlocalStorage.setItem('vacationRules', JSON.stringify(custom));\n+\t\tconst rules = TestBed.inject(RuleService).rules;\n+\t\texpect(rules[0].id).toBe('default-unplaced-at-risk-3');\n+\t\texpect(new Set(rules.map(({ id }) => id)).size).toBe(8);\n+\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!).rules.slice(1, 3)).toEqual(\n+\t\t\tcustom,\n+\t\t);\n+\t});\n+\n+\tit('saves the migrated list and version in one atomic write and retries after a failed save', () => {\n+\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tvi.spyOn(console, 'warn').mockImplementation(() => undefined);\n+\t\tconst save = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {\n+\t\t\tthrow new Error('quota');\n+\t\t});\n+\t\tlet service = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toHaveLength(6);\n+\t\texpect(save).toHaveBeenCalledOnce();\n+\t\texpect(localStorage.getItem('vacationRules')).toBe('[]');\n+\t\tservice.toggleRule(service.rules[0].id);\n+\t\texpect(localStorage.getItem('vacationRules')).toBe('[]');\n+\t\tsave.mockRestore();\n+\t\tTestBed.resetTestingModule();\n+\t\tservice = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toHaveLength(6);\n+\t\texpect(service.rules[0].enabled).toBe(true);\n+\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!).version).toBe(1);\n+\t});\n+\n+\tit('keeps edits usable and saves the entire current list once storage recovers', () => {\n+\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tconst service = TestBed.inject(RuleService);\n+\t\tconst prior = localStorage.getItem('vacationRules');\n+\t\tvi.spyOn(console, 'warn').mockImplementation(() => undefined);\n+\t\tconst save = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {\n+\t\t\tthrow new Error('quota');\n+\t\t});\n+\t\tservice.toggleRule(service.rules[0].id);\n+\t\texpect(service.rules[0].enabled).toBe(false);\n+\t\texpect(localStorage.getItem('vacationRules')).toBe(prior);\n+\t\tsave.mockRestore();\n+\t\tservice.deleteRule(service.rules[1].id);\n+\t\tconst expected = service.rules;\n+\t\tTestBed.resetTestingModule();\n+\t\texpect(TestBed.inject(RuleService).rules).toEqual(expected);\n+\t});\n+\n+\tit.each(['{\"version\":2,\"rules\":[]}', '{broken', 'null', '[null]'])(\n+\t\t'preserves unsupported saved data through subsequent edits: %s',\n+\t\t(saved) => {\n+\t\t\tlocalStorage.setItem('vacationRules', saved);\n+\t\t\tvi.spyOn(console, 'warn').mockImplementation(() => undefined);\n+\t\t\tconst save = vi.spyOn(Storage.prototype, 'setItem');\n+\t\t\tconst service = TestBed.inject(RuleService);\n+\t\t\tservice.toggleRule(service.rules[0].id);\n+\t\t\texpect(save).not.toHaveBeenCalled();\n+\t\t\texpect(localStorage.getItem('vacationRules')).toBe(saved);\n+\t\t},\n+\t);\n+\n+\tit('prevents edits from overwriting unknown valid saved data after a read failure', () => {\n+\t\tconst saved = '{\"version\":1,\"rules\":[]}';\n+\t\tlocalStorage.setItem('vacationRules', saved);\n+\t\tvi.spyOn(console, 'warn').mockImplementation(() => undefined);\n+\t\tconst read = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {\n+\t\t\tthrow new Error('denied');\n+\t\t});\n+\t\tconst service = TestBed.inject(RuleService);\n+\t\tread.mockRestore();\n+\t\tconst write = vi.spyOn(Storage.prototype, 'setItem');\n+\t\tservice.toggleRule(service.rules[0].id);\n+\t\texpect(write).not.toHaveBeenCalled();\n+\t\texpect(localStorage.getItem('vacationRules')).toBe(saved);\n+\t});\n+\n+\tit('works in memory when browser storage is unavailable', () => {\n+\t\tvi.stubGlobal('localStorage', undefined);\n+\t\tconst service = TestBed.inject(RuleService);\n+\t\texpect(service.rules).toHaveLength(8);\n+\t\tservice.toggleRule(service.rules[0].id);\n+\t\texpect(service.rules[0].enabled).toBe(false);\n+\t});\n+\n+\tit.each(['disabled', 'deleted'])(\n+\t\t'keeps a migrated %s list inactive after reload while preserving declarations and at-risk quantities',\n+\t\tasync (choice) => {\n+\t\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\t\tconst service = TestBed.inject(RuleService);\n+\t\t\tfor (const rule of service.rules) {\n+\t\t\t\tif (choice === 'disabled') service.toggleRule(rule.id);\n+\t\t\t\telse service.deleteRule(rule.id);\n+\t\t\t}\n+\t\t\tconst saved = localStorage.getItem('vacationRules');\n+\t\t\tTestBed.resetTestingModule();\n+\t\t\tconst restored = TestBed.inject(RuleService).rules;\n+\t\t\texpect(restored).toHaveLength(choice === 'disabled' ? 6 : 0);\n+\t\t\texpect(restored.every(({ enabled }) => !enabled)).toBe(true);\n+\t\t\texpect(localStorage.getItem('vacationRules')).toBe(saved);\n+\t\t\tvi.stubGlobal('window', undefined);\n+\t\t\tconst calculation = createPlanningCalculation({\n+\t\t\t\thorizon: { start: '2024-01-02', end: '2024-01-05' },\n+\t\t\t\tbalances: [{ id: 'cp', type: 'cp', quantity: 2, expiryDate: '2024-01-04' }],\n+\t\t\t\tdeclaredDays: [{ date: '2024-01-03', type: 'other' }],\n+\t\t\t\trules: restored,\n+\t\t\t});\n+\t\t\tconst outcome = await calculation.outcome;\n+\t\t\texpect(outcome).toMatchObject({\n+\t\t\t\tkind: 'Plan',\n+\t\t\t\tplacements: [],\n+\t\t\t\tdeclaredDays: [{ date: '2024-01-03', type: 'other' }],\n+\t\t\t\tremainingBalances: [\n+\t\t\t\t\t{\n+\t\t\t\t\t\tid: 'cp',\n+\t\t\t\t\t\tquantity: 2,\n+\t\t\t\t\t\tclassification: 'at-risk',\n+\t\t\t\t\t\treason: { code: 'active-priorities' },\n+\t\t\t\t\t},\n+\t\t\t\t],\n+\t\t\t});\n+\t\t\texpect((await calculation.trace)?.phases.map(({ name }) => name)).toEqual([\n+\t\t\t\t'validation',\n+\t\t\t\t'obligations',\n+\t\t\t\t'expiry',\n+\t\t\t\t'dates',\n+\t\t\t]);\n+\t\t\texpect(await calculation.explanation).toMatchObject({\n+\t\t\t\tkind: 'PlanExplanation',\n+\t\t\t\tplacements: [],\n+\t\t\t});\n+\t\t},\n+\t);\n+\n+\tit('migrates before the first duration request and actual calculation', async () => {\n+\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tTestBed.inject(CalendarSettingsService).setPlanningDates('2024-01-02', '2024-01-05');\n+\t\tTestBed.inject(UserInputService).updateBalances(() => [\n+\t\t\t{\n+\t\t\t\tid: 'cp',\n+\t\t\t\ttype: SelectableDayType.CP,\n+\t\t\t\tnumberOfDays: 1,\n+\t\t\t\tavailableDate: new Date('2024-01-02'),\n+\t\t\t\texpiryDate: new Date('2024-01-05'),\n+\t\t\t},\n+\t\t]);\n+\t\tconst request = TestBed.inject(PlanningDurationService).request()!;\n+\t\texpect(request.rules).toHaveLength(6);\n+\t\texpect(JSON.parse(localStorage.getItem('vacationRules')!).version).toBe(1);\n+\t\tvi.stubGlobal('window', undefined);\n+\t\tconst calculation = createPlanningCalculation(request);\n+\t\tconst outcome = await calculation.outcome;\n+\t\texpect(outcome).toMatchObject({\n+\t\t\tkind: 'Plan',\n+\t\t\tmetrics: { unplacedAtRisk: 0 },\n+\t\t\tplacements: [{ balanceId: 'cp' }],\n+\t\t});\n+\t\texpect((await calculation.trace)?.phases.map(({ name }) => name)).toEqual([\n+\t\t\t'validation',\n+\t\t\t'obligations',\n+\t\t\t...request.rules.map(({ id }) => `optimization:${id}`),\n+\t\t\t'expiry',\n+\t\t\t'dates',\n+\t\t]);\n+\t});\n+});\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": true, "new_path": null, "old_path": "src/app/services/rule-migration.spec.ts", "project_id": 35, "relative_order": 36, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,6 +1,14 @@\n import { TestBed } from '@angular/core/testing';\n-import { RuleService, RuleType, IfThenRule, TimeWindowRule } from './rule-service';\n+import {\n+\tRuleService,\n+\tRuleType,\n+\tIfThenRule,\n+\tTimeWindowRule,\n+\tOptimizationRule,\n+} from './rule-service';\n import { SelectableDayType } from './calendar-service';\n+import { OPTIMIZATION_PRESETS } from './planning-objectives';\n+import { vi } from 'vitest';\n \n describe('RuleService', () => {\n \tlet service: RuleService;\n@@ -18,9 +26,10 @@ describe('RuleService', () => {\n \n \tit('should initialize with default rules', () => {\n \t\tconst rules = service.rules;\n-\t\texpect(rules.length).toBe(2);\n-\t\texpect(rules[0].id).toBe('default-samedi-malin');\n-\t\texpect(rules[1].id).toBe('default-christmas');\n+\t\texpect(rules.length).toBe(8);\n+\t\texpect(rules[0].id).toBe('default-unplaced-at-risk');\n+\t\texpect(rules[1].id).toBe('default-samedi-malin');\n+\t\texpect(rules[2].id).toBe('default-christmas');\n \t});\n \n \tit('should parse dates correctly for TimeWindowRules', () => {\n@@ -62,9 +71,12 @@ describe('RuleService', () => {\n \t\tTestBed.configureTestingModule({});\n \t\tservice = TestBed.inject(RuleService);\n \n-\t\texpect(service.rules.map((rule) => rule.id)).toEqual(['legacy-first', 'legacy-second']);\n-\t\texpect(service.rules[0].force).toBe('preference');\n-\t\tconst first = service.rules[0] as TimeWindowRule;\n+\t\texpect(service.rules.slice(1, 3).map((rule) => rule.id)).toEqual([\n+\t\t\t'legacy-first',\n+\t\t\t'legacy-second',\n+\t\t]);\n+\t\texpect(service.rules[1].force).toBe('preference');\n+\t\tconst first = service.rules[1] as TimeWindowRule;\n \t\texpect(first.startDate.toISOString().slice(0, 10)).toBe('2024-02-01');\n \t});\n \n@@ -84,13 +96,13 @@ describe('RuleService', () => {\n \n \t\tservice.addRule(newRule);\n \t\tconst rules = service.rules;\n-\t\texpect(rules.length).toBe(3);\n+\t\texpect(rules.length).toBe(9);\n \t\texpect(rules.find((r) => r.id === 'test-rule')).toBeDefined();\n \t});\n \n \tit('should update an existing rule', () => {\n \t\tconst rules = service.rules;\n-\t\tconst targetRule = { ...rules[0] } as IfThenRule;\n+\t\tconst targetRule = { ...rules.find((rule) => rule.type === RuleType.IF_THEN)! };\n \t\ttargetRule.name = 'Updated Name';\n \n \t\tservice.updateRule(targetRule);\n@@ -107,7 +119,7 @@ describe('RuleService', () => {\n \t\tservice.deleteRule(idToDelete);\n \n \t\tconst updatedRules = service.rules;\n-\t\texpect(updatedRules.length).toBe(1);\n+\t\texpect(updatedRules.length).toBe(7);\n \t\texpect(updatedRules.find((r) => r.id === idToDelete)).toBeUndefined();\n \t});\n \n@@ -132,4 +144,42 @@ describe('RuleService', () => {\n \t\texpect(rulesAfter[0].id).toBe(secondRuleId);\n \t\texpect(rulesAfter[1].id).toBe(firstRuleId);\n \t});\n+\n+\tit('restores the full optimization identity, parameters, enabled state and position', () => {\n+\t\tvi.useFakeTimers();\n+\t\ttry {\n+\t\t\tTestBed.tick();\n+\t\t\tconst optimization: OptimizationRule = {\n+\t\t\t\tid: 'personal-loss',\n+\t\t\t\tname: 'My loss priority',\n+\t\t\t\ttype: RuleType.OPTIMIZATION,\n+\t\t\t\tenabled: true,\n+\t\t\t\tforce: 'preference',\n+\t\t\t\tconfiguration: structuredClone(OPTIMIZATION_PRESETS.unplacedAtRisk),\n+\t\t\t};\n+\t\t\tservice.addRule(optimization);\n+\t\t\toptimization.configuration.conditions = [];\n+\t\t\tservice.reorderRules(\n+\t\t\t\tservice.rules.findIndex(({ id }) => id === optimization.id),\n+\t\t\t\t0,\n+\t\t\t);\n+\t\t\tservice.toggleRule('personal-loss');\n+\t\t\tconst saved = service.rules;\n+\t\t\tTestBed.tick();\n+\t\t\tvi.advanceTimersByTime(350);\n+\t\t\tTestBed.resetTestingModule();\n+\t\t\tservice = TestBed.inject(RuleService);\n+\t\t\texpect(service.rules).toEqual(saved);\n+\t\t\texpect(service.rules[0]).toMatchObject({\n+\t\t\t\tid: 'personal-loss',\n+\t\t\t\tname: 'My loss priority',\n+\t\t\t\tenabled: false,\n+\t\t\t\tconfiguration: OPTIMIZATION_PRESETS.unplacedAtRisk,\n+\t\t\t});\n+\t\t\tservice.deleteRule('personal-loss');\n+\t\t\texpect(service.rules.some((rule) => rule.id === 'personal-loss')).toBe(false);\n+\t\t} finally {\n+\t\t\tvi.useRealTimers();\n+\t\t}\n+\t});\n });\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/rule-service.spec.ts", "project_id": 35, "relative_order": 37, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -1,10 +1,11 @@\n-import { Injectable, WritableSignal, Injector, inject } from '@angular/core';\n+import { Injectable, WritableSignal, signal } from '@angular/core';\n import { SelectableDayType } from './calendar-service';\n-import { storedSignal } from '../shared/utils/stored-signal';\n+import { OPTIMIZATION_PRESETS, type OptimizationConfiguration } from './planning-objectives';\n \n export enum RuleType {\n \tIF_THEN = 'if_then',\n \tTIME_WINDOW = 'time_window',\n+\tOPTIMIZATION = 'optimization',\n }\n \n export type RuleForce = 'obligation' | 'preference';\n@@ -14,7 +15,7 @@ export interface BaseRule {\n \tname: string;\n \ttype: RuleType;\n \tenabled: boolean;\n-\t/** Missing force is a legacy preference and is migrated on read. */\n+\t/** Missing force is read as a legacy preference without rewriting the saved entry. */\n \tforce?: RuleForce;\n }\n \n@@ -38,29 +39,88 @@ export interface TimeWindowRule extends BaseRule {\n \tplaceType: SelectableDayType;\n }\n \n-export type VacationRule = IfThenRule | TimeWindowRule;\n+export interface OptimizationRule extends BaseRule {\n+\ttype: RuleType.OPTIMIZATION;\n+\tforce: 'preference';\n+\tconfiguration: OptimizationConfiguration;\n+}\n \n-interface SerializedRule {\n-\tid: string;\n-\tname: string;\n-\ttype: RuleType;\n-\tenabled: boolean;\n-\tforce?: RuleForce;\n-\tdayOfWeek?: number;\n-\tplaceDays: number;\n-\tplaceType: SelectableDayType;\n-\tplacement?: PlacementStrategy;\n-\trewardDays?: number;\n-\trewardType?: SelectableDayType;\n-\tstartDate?: string | Date;\n-\tendDate?: string | Date;\n+export type VacationRule = IfThenRule | TimeWindowRule | OptimizationRule;\n+\n+type SerializedRule =\n+\t| IfThenRule\n+\t| (Omit & {\n+\t\t\tstartDate: string | Date;\n+\t\t\tendDate: string | Date;\n+\t })\n+\t| (Omit & { force?: 'preference' });\n+\n+export function createOptimizationPresetRules(\n+\texistingIds: readonly string[] = [],\n+): OptimizationRule[] {\n+\tconst ids = new Set(existingIds);\n+\treturn (\n+\t\t[\n+\t\t\t['unplaced-at-risk', 'Prévention des pertes', OPTIMIZATION_PRESETS.unplacedAtRisk],\n+\t\t\t['holiday-week-value', 'Semaines fériées', OPTIMIZATION_PRESETS.holidayWeekValue],\n+\t\t\t[\n+\t\t\t\t'non-working-day-gain',\n+\t\t\t\t'Gain de jours non ouvrés',\n+\t\t\t\tOPTIMIZATION_PRESETS.nonWorkingDayGain,\n+\t\t\t],\n+\t\t\t[\n+\t\t\t\t'longest-work-sequence',\n+\t\t\t\t'Séquence de travail maximale',\n+\t\t\t\tOPTIMIZATION_PRESETS.longestWorkSequence,\n+\t\t\t],\n+\t\t\t[\n+\t\t\t\t'short-sequence-deficit',\n+\t\t\t\t'Déficit des reprises',\n+\t\t\t\tOPTIMIZATION_PRESETS.shortSequenceDeficit,\n+\t\t\t],\n+\t\t\t[\n+\t\t\t\t'supporting-placements',\n+\t\t\t\t'Économie des jours d’appoint',\n+\t\t\t\tOPTIMIZATION_PRESETS.supportingPlacements,\n+\t\t\t],\n+\t\t] as const\n+\t).map(([key, name, configuration]) => {\n+\t\tconst base = `default-${key}`;\n+\t\tlet id = base;\n+\t\tlet suffix = 2;\n+\t\twhile (ids.has(id)) id = `${base}-${suffix++}`;\n+\t\tids.add(id);\n+\t\treturn {\n+\t\t\tid,\n+\t\t\tname,\n+\t\t\ttype: RuleType.OPTIMIZATION,\n+\t\t\tenabled: true,\n+\t\t\tforce: 'preference',\n+\t\t\tconfiguration: structuredClone(configuration),\n+\t\t};\n+\t});\n+}\n+\n+function isRuleList(value: unknown): value is SerializedRule[] {\n+\treturn (\n+\t\tArray.isArray(value) &&\n+\t\tvalue.every(\n+\t\t\t(rule) =>\n+\t\t\t\trule &&\n+\t\t\t\ttypeof rule === 'object' &&\n+\t\t\t\ttypeof rule.id === 'string' &&\n+\t\t\t\ttypeof rule.name === 'string' &&\n+\t\t\t\ttypeof rule.enabled === 'boolean' &&\n+\t\t\t\tObject.values(RuleType).includes(rule.type),\n+\t\t)\n+\t);\n }\n \n @Injectable({\n \tprovidedIn: 'root',\n })\n export class RuleService {\n-\tprivate readonly injector = inject(Injector);\n+\tprivate canPersist = true;\n \n \tprivate readonly defaultRules: VacationRule[] = [\n \t\t{\n@@ -92,11 +152,56 @@ export class RuleService {\n \tprivate rawRulesSignal: WritableSignal;\n \n \tconstructor() {\n-\t\tthis.rawRulesSignal = storedSignal(\n-\t\t\t'vacationRules',\n-\t\t\tthis.defaultRules as unknown as SerializedRule[],\n-\t\t\tthis.injector,\n-\t\t);\n+\t\tlet rules = this.initialRules(this.defaultRules);\n+\t\tlet migrate = true;\n+\t\ttry {\n+\t\t\tconst stored =\n+\t\t\t\ttypeof localStorage === 'undefined' ? null : localStorage.getItem('vacationRules');\n+\t\t\tif (stored !== null) {\n+\t\t\t\tconst parsed: unknown = JSON.parse(stored);\n+\t\t\t\tif (isRuleList(parsed)) rules = this.initialRules(parsed);\n+\t\t\t\telse if (\n+\t\t\t\t\tparsed &&\n+\t\t\t\t\ttypeof parsed === 'object' &&\n+\t\t\t\t\t'version' in parsed &&\n+\t\t\t\t\tparsed.version === 1 &&\n+\t\t\t\t\t'rules' in parsed &&\n+\t\t\t\t\tisRuleList(parsed.rules)\n+\t\t\t\t) {\n+\t\t\t\t\trules = parsed.rules;\n+\t\t\t\t\tmigrate = false;\n+\t\t\t\t} else throw new Error('Unsupported saved rule format.');\n+\t\t\t}\n+\t\t} catch (error) {\n+\t\t\t// A failed read must not allow a later edit to replace unknown saved rules.\n+\t\t\tthis.canPersist = false;\n+\t\t\tconsole.warn('Failed to restore planning rules from localStorage.', error);\n+\t\t}\n+\t\tthis.rawRulesSignal = signal(rules);\n+\t\tif (migrate) this.saveRules();\n+\t}\n+\n+\tprivate initialRules(existing: SerializedRule[]): SerializedRule[] {\n+\t\tconst presets = createOptimizationPresetRules(existing.map(({ id }) => id));\n+\t\treturn [presets[0], ...existing, ...presets.slice(1)];\n+\t}\n+\n+\tprivate saveRules(): void {\n+\t\tif (!this.canPersist) return;\n+\t\ttry {\n+\t\t\tif (typeof localStorage !== 'undefined')\n+\t\t\t\tlocalStorage.setItem(\n+\t\t\t\t\t'vacationRules',\n+\t\t\t\t\tJSON.stringify({ version: 1, rules: this.rawRulesSignal() }),\n+\t\t\t\t);\n+\t\t} catch (error) {\n+\t\t\tconsole.warn('Failed to save planning rules to localStorage.', error);\n+\t\t}\n+\t}\n+\n+\tprivate updateRules(update: (rules: SerializedRule[]) => SerializedRule[]): void {\n+\t\tthis.rawRulesSignal.update(update);\n+\t\tthis.saveRules();\n \t}\n \n \tpublic get rules(): VacationRule[] {\n@@ -106,46 +211,42 @@ export class RuleService {\n \t\t\t\treturn {\n \t\t\t\t\t...rule,\n \t\t\t\t\tforce: rule.force ?? 'preference',\n-\t\t\t\t\tstartDate: new Date(rule.startDate as string),\n-\t\t\t\t\tendDate: new Date(rule.endDate as string),\n-\t\t\t\t} as TimeWindowRule;\n+\t\t\t\t\tstartDate: new Date(rule.startDate),\n+\t\t\t\t\tendDate: new Date(rule.endDate),\n+\t\t\t\t};\n \t\t\t}\n-\t\t\treturn { ...rule, force: rule.force ?? 'preference' } as IfThenRule;\n+\t\t\tif (rule.type === RuleType.OPTIMIZATION)\n+\t\t\t\treturn structuredClone({ ...rule, force: rule.force ?? ('preference' as const) });\n+\t\t\treturn structuredClone({ ...rule, force: rule.force ?? 'preference' });\n \t\t});\n \t}\n \n \tpublic addRule(rule: VacationRule): void {\n-\t\tthis.rawRulesSignal.update((rules) => [\n-\t\t\t...rules,\n-\t\t\t{ ...rule, force: rule.force ?? 'preference' } as unknown as SerializedRule,\n-\t\t]);\n+\t\tconst saved = structuredClone(rule);\n+\t\tsaved.force ??= 'preference';\n+\t\tthis.updateRules((rules) => [...rules, saved]);\n \t}\n \n \tpublic updateRule(updatedRule: VacationRule): void {\n-\t\tthis.rawRulesSignal.update((rules) =>\n-\t\t\trules.map((rule) =>\n-\t\t\t\trule.id === updatedRule.id\n-\t\t\t\t\t? ({\n-\t\t\t\t\t\t\t...updatedRule,\n-\t\t\t\t\t\t\tforce: updatedRule.force ?? 'preference',\n-\t\t\t\t\t\t} as unknown as SerializedRule)\n-\t\t\t\t\t: rule,\n-\t\t\t),\n+\t\tconst saved = structuredClone(updatedRule);\n+\t\tsaved.force ??= 'preference';\n+\t\tthis.updateRules((rules) =>\n+\t\t\trules.map((rule) => (rule.id === updatedRule.id ? saved : rule)),\n \t\t);\n \t}\n \n \tpublic deleteRule(id: string): void {\n-\t\tthis.rawRulesSignal.update((rules) => rules.filter((rule) => rule.id !== id));\n+\t\tthis.updateRules((rules) => rules.filter((rule) => rule.id !== id));\n \t}\n \n \tpublic toggleRule(id: string): void {\n-\t\tthis.rawRulesSignal.update((rules) =>\n+\t\tthis.updateRules((rules) =>\n \t\t\trules.map((rule) => (rule.id === id ? { ...rule, enabled: !rule.enabled } : rule)),\n \t\t);\n \t}\n \n \tpublic reorderRules(previousIndex: number, currentIndex: number): void {\n-\t\tthis.rawRulesSignal.update((rules) => {\n+\t\tthis.updateRules((rules) => {\n \t\t\tconst updatedRules = [...rules];\n \t\t\tconst [movedRule] = updatedRules.splice(previousIndex, 1);\n \t\t\tupdatedRules.splice(currentIndex, 0, movedRule);\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/rule-service.ts", "project_id": 35, "relative_order": 38, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -3,6 +3,16 @@ import { Injectable, inject, Injector, computed } from '@angular/core';\n import { storedSignal } from '../shared/utils/stored-signal';\n import type { PlanOutcome, RemainingBalance } from './leave-planner.service';\n import { addPlanningDays } from './planning-date';\n+import {\n+\toptimizationUnit,\n+\tvalidateOptimizationConfiguration,\n+\ttype OptimizationConfiguration,\n+\ttype OptimizationElements,\n+\ttype OptimizationCondition,\n+\ttype OptimizationMeasure,\n+\ttype OptimizationAggregation,\n+\ttype OptimizationDirection,\n+} from './planning-objectives';\n \n export interface AppTranslations {\n \tlocale: string;\n@@ -77,6 +87,25 @@ export interface AppTranslations {\n \t\tinvalidHorizon: string;\n \t};\n \trules: {\n+\t\toptimization: {\n+\t\t\tnewRule: string;\n+\t\t\tdefaultName: string;\n+\t\t\telementsLabel: string;\n+\t\t\tconditionsLabel: string;\n+\t\t\tmeasureLabel: string;\n+\t\t\taggregationLabel: string;\n+\t\t\tdirectionLabel: string;\n+\t\t\tthresholdLabel: string;\n+\t\t\tthresholdSummary: string;\n+\t\t\tsummary: string;\n+\t\t\tinvalidConfiguration: string;\n+\t\t\tnameRequired: string;\n+\t\t\telements: Record;\n+\t\t\tconditions: Record;\n+\t\t\tmeasures: Record;\n+\t\t\taggregations: Record;\n+\t\t\tdirections: Record;\n+\t\t};\n \t\ttitle: string;\n \t\tsubtitle: string;\n \t\tactive: string;\n@@ -390,6 +419,29 @@ export class TranslationService {\n \t\t}\n \t}\n \n+\tpublic optimizationSummary(configuration: OptimizationConfiguration): string {\n+\t\tconst tr = this.tr().rules.optimization;\n+\t\tif (!validateOptimizationConfiguration(configuration).valid) return tr.invalidConfiguration;\n+\t\tconst unit = optimizationUnit(configuration);\n+\t\tconst unitLabel =\n+\t\t\tunit === 'count'\n+\t\t\t\t? tr.aggregations.count\n+\t\t\t\t: this.tr().planning.statistics[\n+\t\t\t\t\t\tunit === 'working-days' ? 'workingDays' : 'calendarDays'\n+\t\t\t\t\t];\n+\t\tconst conditions = configuration.conditions.map((condition) => tr.conditions[condition]);\n+\t\tif (configuration.measure === 'work-sequence-deficit')\n+\t\t\tconditions.push(\n+\t\t\t\ttr.thresholdSummary.replace('{count}', String(configuration.thresholdDays)),\n+\t\t\t);\n+\t\treturn tr.summary\n+\t\t\t.replace('{direction}', tr.directions[configuration.direction])\n+\t\t\t.replace('{aggregation}', tr.aggregations[configuration.aggregation])\n+\t\t\t.replace('{measure}', `${tr.measures[configuration.measure]} (${unitLabel})`)\n+\t\t\t.replace('{elements}', tr.elements[configuration.elements])\n+\t\t\t.replace('{conditions}', conditions.length ? ` (${conditions.join(', ')})` : '');\n+\t}\n+\n \tpublic getLanguageName(langCode: string): string {\n \t\ttry {\n \t\t\t// Using native Intl.DisplayNames to get name of language in its own language\n@@ -421,7 +473,8 @@ export class TranslationService {\n \t\tconst reasons = this.tr().planning.details.remainingReasons;\n \t\tif (!plan) return reasons['not-established'];\n \t\tconst code =\n-\t\t\tincomplete && ['preserved', 'not-established'].includes(balance.reason.code)\n+\t\t\tincomplete &&\n+\t\t\t['preserved', 'active-priorities', 'not-established'].includes(balance.reason.code)\n \t\t\t\t? 'calculation-incomplete'\n \t\t\t\t: balance.reason.code;\n \t\treturn (reasons[code] ?? reasons['not-established'])\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/services/translation-service.ts", "project_id": 35, "relative_order": 39, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -32,7 +32,7 @@ describe('Application Settings', () => {\n \t\tlocalStorage.clear();\n \t\tlocalStorage.setItem('app.language', JSON.stringify('en'));\n \t\tlocalStorage.setItem('leaveBalances', savedBalances);\n-\t\tlocalStorage.setItem('vacationRules', '[]');\n+\t\tlocalStorage.setItem('vacationRules', '{\"version\":1,\"rules\":[]}');\n \t\tlocalStorage.setItem('unrelated.entry', 'keep this value');\n \t\tmediaQuery = Object.assign(new EventTarget(), {\n \t\t\tmatches: true,\n@@ -461,7 +461,7 @@ describe('Application Settings', () => {\n \t\t\tawait (await dialog.getHarness(MatSlideToggleHarness)).check();\n \t\t\texpect(localStorage.getItem('calendarSettings.showWeekNumbers')).toBe('true');\n \t\t\texpect(localStorage.getItem('leaveBalances')).toBe(savedBalances);\n-\t\t\texpect(localStorage.getItem('vacationRules')).toBe('[]');\n+\t\t\texpect(localStorage.getItem('vacationRules')).toBe('{\"version\":1,\"rules\":[]}');\n \t\t\texpect(localStorage.getItem('unrelated.entry')).toBe('keep this value');\n \t\t\texpect(fixture.nativeElement.querySelectorAll('.week-number').length).toBeGreaterThan(\n \t\t\t\t0,\n@@ -490,7 +490,7 @@ describe('Application Settings', () => {\n \t\t\tTestBed.resetTestingModule();\n \t\t\tawait createApp();\n \t\t\texpect(localStorage.getItem('leaveBalances')).toBe(savedBalances);\n-\t\t\texpect(localStorage.getItem('vacationRules')).toBe('[]');\n+\t\t\texpect(localStorage.getItem('vacationRules')).toBe('{\"version\":1,\"rules\":[]}');\n \t\t\texpect(localStorage.getItem('unrelated.entry')).toBe('keep this value');\n \t\t\texpect(document.body.classList.contains('dark-mode')).toBe(true);\n \t\t\texpect(\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/app/app-settings.spec.ts", "project_id": 35, "relative_order": 40, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -133,6 +133,51 @@\n \t\t\t\"after\": \"danach\",\n \t\t\t\"around\": \"darum herum\",\n \t\t\t\"auto\": \"automatisch\"\n+\t\t},\n+\t\t\"optimization\": {\n+\t\t\t\"newRule\": \"Neue Optimierungsregel\",\n+\t\t\t\"defaultName\": \"Verluste vermeiden\",\n+\t\t\t\"elementsLabel\": \"Planungselemente\",\n+\t\t\t\"conditionsLabel\": \"Bedingungen (alle müssen erfüllt sein)\",\n+\t\t\t\"measureLabel\": \"Messgröße\",\n+\t\t\t\"aggregationLabel\": \"Aggregation\",\n+\t\t\t\"directionLabel\": \"Richtung\",\n+\t\t\t\"thresholdLabel\": \"Präferenzschwelle in Arbeitstagen\",\n+\t\t\t\"thresholdSummary\": \"Präferenzschwelle: {count} Arbeitstage\",\n+\t\t\t\"summary\": \"{direction} {aggregation}: {measure} — {elements}{conditions}.\",\n+\t\t\t\"invalidConfiguration\": \"Wählen Sie passende Elemente, Bedingungen, Messgrößen und Aggregationen sowie bei Bedarf eine positive ganzzahlige Tagesschwelle.\",\n+\t\t\t\"nameRequired\": \"Geben Sie einen Regelnamen ein.\",\n+\t\t\t\"elements\": {\n+\t\t\t\t\"leave-balances\": \"Urlaubsguthaben\",\n+\t\t\t\t\"public-holiday-weeks\": \"Feiertagswochen\",\n+\t\t\t\t\"time-off-periods\": \"Arbeitsfreie Zeiträume\",\n+\t\t\t\t\"work-sequences\": \"Arbeitsfolgen\",\n+\t\t\t\t\"leave-placements\": \"Geplante Urlaubstage\"\n+\t\t\t},\n+\t\t\t\"conditions\": {\n+\t\t\t\t\"at-risk\": \"Vom Verfall bedroht\",\n+\t\t\t\t\"complete\": \"Vollständig\",\n+\t\t\t\t\"internal\": \"Intern\",\n+\t\t\t\t\"non-empty\": \"Nicht leer\",\n+\t\t\t\t\"supporting\": \"Unterstützend\"\n+\t\t\t},\n+\t\t\t\"measures\": {\n+\t\t\t\t\"unplaced-quantity\": \"Nicht eingeplante Menge\",\n+\t\t\t\t\"public-holiday-week-value\": \"Wert der Feiertagswochen\",\n+\t\t\t\t\"non-working-day-gain\": \"Gewinn arbeitsfreier Tage\",\n+\t\t\t\t\"work-sequence-length\": \"Länge der Arbeitsfolgen\",\n+\t\t\t\t\"work-sequence-deficit\": \"Defizit der Arbeitsfolgen\",\n+\t\t\t\t\"placement-count\": \"Anzahl der Platzierungen\"\n+\t\t\t},\n+\t\t\t\"aggregations\": {\n+\t\t\t\t\"sum\": \"Summe\",\n+\t\t\t\t\"count\": \"Anzahl\",\n+\t\t\t\t\"maximum\": \"Maximum\"\n+\t\t\t},\n+\t\t\t\"directions\": {\n+\t\t\t\t\"minimize\": \"Minimieren\",\n+\t\t\t\t\"maximize\": \"Maximieren\"\n+\t\t\t}\n \t\t}\n \t},\n \t\"planning\": {\n@@ -276,7 +321,7 @@\n \t\t\t\"withoutDay\": \"Ohne diesen Tag\",\n \t\t\t\"withDay\": \"Mit diesem Tag\",\n \t\t\t\"noChange\": \"Diese Werte sind gleich. Regeln und die letzten Entscheidungskriterien (Verfall des Guthabens, dann Datum) können die Auswahl weiterhin beeinflussen.\",\n-\t\t\t\"priorityHelp\": \"Die Kriterien stehen in Prioritätsreihenfolge. Der erste Unterschied hat Vorrang vor den folgenden.\",\n+\t\t\t\"priorityHelp\": \"Verpflichtungen werden gemeinsam erfüllt. Aktive Präferenzen werden in Ihrer Regelreihenfolge verglichen. Nur diese Regeln führen zu neuen Urlaubstagen; früherer Verfall und dann frühere Daten entscheiden bei Gleichstand.\",\n \t\t\t\"tryDate\": \"Anderes Datum testen\",\n \t\t\t\"plannedDate\": \"Derzeit geplant für:\",\n \t\t\t\"currentPlan\": \"Aktueller Plan\",\n@@ -327,6 +372,10 @@\n \t\t\t\t\"placement-date\": {\n \t\t\t\t\t\"label\": \"Frühere Daten bevorzugen\",\n \t\t\t\t\t\"help\": \"Letztes Kriterium, wenn alle anderen Kriterien gleich sind.\"\n+\t\t\t\t},\n+\t\t\t\t\"optimization\": {\n+\t\t\t\t\t\"label\": \"{rule}: {summary}\",\n+\t\t\t\t\t\"help\": \"Diese Optimierungspräferenz bewertet ihre gespeicherte Konfiguration. Aktive Präferenzen werden in der angezeigten Reihenfolge verglichen; frühere haben Vorrang.\"\n \t\t\t\t}\n \t\t\t},\n \t\t\t\"stages\": {\n@@ -342,7 +391,9 @@\n \t\t\t\t\"unavailable\": \"Dieses Urlaubsguthaben kann an diesem Datum nicht verwendet werden.\",\n \t\t\t\t\"expired\": \"Dieses Datum liegt nach dem Verfall des Urlaubsguthabens.\",\n \t\t\t\t\"type-incompatible\": \"Diese Urlaubsart kann an diesem Datum nicht verwendet werden.\",\n-\t\t\t\t\"rule-invalid\": \"Dieses Datum würde eine Planungsregel verletzen.\"\n+\t\t\t\t\"rule-invalid\": \"Dieses Datum würde eine Planungsregel verletzen.\",\n+\t\t\t\t\"invalid-optimization-configuration\": \"Wählen Sie passende Elemente, Bedingungen, Messgrößen und Aggregationen sowie bei Bedarf eine positive ganzzahlige Tagesschwelle.\",\n+\t\t\t\t\"unsupported-optimization-configuration\": \"Diese Regel kombiniert unvereinbare Planungselemente und Messgrößen.\"\n \t\t\t},\n \t\t\t\"preferenceHelp\": {\n \t\t\t\t\"time_window\": \"Urlaubstage im bevorzugten Zeitraum. Mehr ist besser.\",\n@@ -373,6 +424,7 @@\n \t\t\t\t\"no-working-date\": \"Kein Arbeitstag liegt sowohl im Planungszeitraum als auch zwischen Verfügbarkeits- und Ablaufdatum.\",\n \t\t\t\t\"all-dates-occupied\": \"Alle Arbeitstage, an denen dieses Urlaubskonto nutzbar ist, sind bereits durch geplanten Urlaub oder gebuchte Tage belegt.\",\n \t\t\t\t\"preserved\": \"Für später aufbewahrt: Das Urlaubskonto läuft nach dem Planungszeitraum ab und die Berechnung hat gemäß Ihren Prioritäten keine zusätzliche Platzierung ausgewählt.\",\n+\t\t\t\t\"active-priorities\": \"Die Berechnung hat dieses Urlaubskonto gemäß Ihren aktiven Regeln ungenutzt gelassen. Ändern Sie die Regeln oder ihre Reihenfolge, um einen anderen Plan anzufordern.\",\n \t\t\t\t\"calculation-incomplete\": \"Die Berechnung wurde vor Abschluss der Planung unterbrochen. Die Nichtnutzung ist keine endgültige Entscheidung.\",\n \t\t\t\t\"not-established\": \"Diese Berechnung hat keinen genauen Grund für die Nichtnutzung ermittelt.\"\n \t\t\t}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/i18n/de.json", "project_id": 35, "relative_order": 41, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -133,6 +133,51 @@\n \t\t\t\"after\": \"After\",\n \t\t\t\"around\": \"Around\",\n \t\t\t\"auto\": \"Auto (Best choice)\"\n+\t\t},\n+\t\t\"optimization\": {\n+\t\t\t\"newRule\": \"New Optimization Rule\",\n+\t\t\t\"defaultName\": \"Loss prevention\",\n+\t\t\t\"elementsLabel\": \"Planning elements\",\n+\t\t\t\"conditionsLabel\": \"Conditions (all must match)\",\n+\t\t\t\"measureLabel\": \"Measure\",\n+\t\t\t\"aggregationLabel\": \"Aggregation\",\n+\t\t\t\"directionLabel\": \"Direction\",\n+\t\t\t\"thresholdLabel\": \"Preference threshold in working days\",\n+\t\t\t\"thresholdSummary\": \"preference threshold: {count} working days\",\n+\t\t\t\"summary\": \"{direction} {aggregation}: {measure} — {elements}{conditions}.\",\n+\t\t\t\"invalidConfiguration\": \"Choose compatible planning elements, conditions, measure and aggregation, with a positive whole-day threshold when needed.\",\n+\t\t\t\"nameRequired\": \"Enter a rule name.\",\n+\t\t\t\"elements\": {\n+\t\t\t\t\"leave-balances\": \"Leave balances\",\n+\t\t\t\t\"public-holiday-weeks\": \"Public-holiday weeks\",\n+\t\t\t\t\"time-off-periods\": \"Time-off periods\",\n+\t\t\t\t\"work-sequences\": \"Work sequences\",\n+\t\t\t\t\"leave-placements\": \"Leave placements\"\n+\t\t\t},\n+\t\t\t\"conditions\": {\n+\t\t\t\t\"at-risk\": \"At risk of expiry\",\n+\t\t\t\t\"complete\": \"Complete\",\n+\t\t\t\t\"internal\": \"Internal\",\n+\t\t\t\t\"non-empty\": \"Non-empty\",\n+\t\t\t\t\"supporting\": \"Supporting\"\n+\t\t\t},\n+\t\t\t\"measures\": {\n+\t\t\t\t\"unplaced-quantity\": \"Unplaced quantity\",\n+\t\t\t\t\"public-holiday-week-value\": \"Public-holiday week value\",\n+\t\t\t\t\"non-working-day-gain\": \"Non-working-day gain\",\n+\t\t\t\t\"work-sequence-length\": \"Work-sequence length\",\n+\t\t\t\t\"work-sequence-deficit\": \"Work-sequence deficit\",\n+\t\t\t\t\"placement-count\": \"Placement count\"\n+\t\t\t},\n+\t\t\t\"aggregations\": {\n+\t\t\t\t\"sum\": \"Sum\",\n+\t\t\t\t\"count\": \"Count\",\n+\t\t\t\t\"maximum\": \"Maximum\"\n+\t\t\t},\n+\t\t\t\"directions\": {\n+\t\t\t\t\"minimize\": \"Minimize\",\n+\t\t\t\t\"maximize\": \"Maximize\"\n+\t\t\t}\n \t\t}\n \t},\n \t\"planning\": {\n@@ -276,7 +321,7 @@\n \t\t\t\"withoutDay\": \"Without this day\",\n \t\t\t\"withDay\": \"With this day\",\n \t\t\t\"noChange\": \"These totals are unchanged. Rules and the final tie-breakers (balance expiry, then date) can still affect the choice.\",\n-\t\t\t\"priorityHelp\": \"Criteria are listed in priority order. The first difference takes precedence over later ones.\",\n+\t\t\t\"priorityHelp\": \"Obligations are satisfied together. Active preferences are compared in your rule order. Only those rules drive new placements; earlier expiry and then dates break equal results.\",\n \t\t\t\"tryDate\": \"Try another date\",\n \t\t\t\"plannedDate\": \"Currently planned for:\",\n \t\t\t\"currentPlan\": \"Current plan\",\n@@ -327,6 +372,10 @@\n \t\t\t\t\"placement-date\": {\n \t\t\t\t\t\"label\": \"Earlier dates first\",\n \t\t\t\t\t\"help\": \"Final tie-breaker when all other criteria are equal.\"\n+\t\t\t\t},\n+\t\t\t\t\"optimization\": {\n+\t\t\t\t\t\"label\": \"{rule}: {summary}\",\n+\t\t\t\t\t\"help\": \"This optimization preference evaluates its saved configuration. Active preferences follow the displayed order; earlier preferences win before later ones.\"\n \t\t\t\t}\n \t\t\t},\n \t\t\t\"stages\": {\n@@ -342,7 +391,9 @@\n \t\t\t\t\"unavailable\": \"This leave balance cannot be used on this date.\",\n \t\t\t\t\"expired\": \"This date is after the leave balance expires.\",\n \t\t\t\t\"type-incompatible\": \"This leave type cannot be used on this date.\",\n-\t\t\t\t\"rule-invalid\": \"Using this date would break a planning rule.\"\n+\t\t\t\t\"rule-invalid\": \"Using this date would break a planning rule.\",\n+\t\t\t\t\"invalid-optimization-configuration\": \"Choose compatible planning elements, conditions, measure and aggregation, with a positive whole-day threshold when needed.\",\n+\t\t\t\t\"unsupported-optimization-configuration\": \"This rule uses an unsupported combination of planning elements and measures.\"\n \t\t\t},\n \t\t\t\"preferenceHelp\": {\n \t\t\t\t\"time_window\": \"Leave days in this preferred period. More is better.\",\n@@ -373,6 +424,7 @@\n \t\t\t\t\"no-working-date\": \"No working day falls within both the planning period and its availability and expiry dates.\",\n \t\t\t\t\"all-dates-occupied\": \"All working days on which this balance can be used are already occupied by planned leave or already booked days.\",\n \t\t\t\t\"preserved\": \"Kept for later: it expires after the planning period and the calculation retained no additional placement under your priorities.\",\n+\t\t\t\t\"active-priorities\": \"The calculation kept this balance unused under your active planning rules. Change the rules or their order to request a different plan.\",\n \t\t\t\t\"calculation-incomplete\": \"The calculation was interrupted before planning finished. Leaving it unused is not a final decision.\",\n \t\t\t\t\"not-established\": \"This calculation did not establish a precise reason for leaving it unused.\"\n \t\t\t}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/i18n/en.json", "project_id": 35, "relative_order": 42, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -133,6 +133,51 @@\n \t\t\t\"after\": \"Después\",\n \t\t\t\"around\": \"Alrededor\",\n \t\t\t\"auto\": \"Auto (Mejor opción)\"\n+\t\t},\n+\t\t\"optimization\": {\n+\t\t\t\"newRule\": \"Nueva regla de Optimización\",\n+\t\t\t\"defaultName\": \"Prevención de pérdidas\",\n+\t\t\t\"elementsLabel\": \"Elementos del plan\",\n+\t\t\t\"conditionsLabel\": \"Condiciones (deben cumplirse todas)\",\n+\t\t\t\"measureLabel\": \"Medida\",\n+\t\t\t\"aggregationLabel\": \"Agregación\",\n+\t\t\t\"directionLabel\": \"Dirección\",\n+\t\t\t\"thresholdLabel\": \"Umbral de preferencia en días laborables\",\n+\t\t\t\"thresholdSummary\": \"umbral de preferencia: {count} días laborables\",\n+\t\t\t\"summary\": \"{direction} {aggregation}: {measure} — {elements}{conditions}.\",\n+\t\t\t\"invalidConfiguration\": \"Elija elementos, condiciones, medidas y agregaciones compatibles, con un umbral entero positivo cuando sea necesario.\",\n+\t\t\t\"nameRequired\": \"Introduzca un nombre para la regla.\",\n+\t\t\t\"elements\": {\n+\t\t\t\t\"leave-balances\": \"Saldos de vacaciones\",\n+\t\t\t\t\"public-holiday-weeks\": \"Semanas con festivos\",\n+\t\t\t\t\"time-off-periods\": \"Períodos sin trabajo\",\n+\t\t\t\t\"work-sequences\": \"Secuencias de trabajo\",\n+\t\t\t\t\"leave-placements\": \"Vacaciones colocadas\"\n+\t\t\t},\n+\t\t\t\"conditions\": {\n+\t\t\t\t\"at-risk\": \"En riesgo de caducar\",\n+\t\t\t\t\"complete\": \"Completas\",\n+\t\t\t\t\"internal\": \"Internas\",\n+\t\t\t\t\"non-empty\": \"No vacías\",\n+\t\t\t\t\"supporting\": \"De apoyo\"\n+\t\t\t},\n+\t\t\t\"measures\": {\n+\t\t\t\t\"unplaced-quantity\": \"Cantidad no colocada\",\n+\t\t\t\t\"public-holiday-week-value\": \"Valor de las semanas festivas\",\n+\t\t\t\t\"non-working-day-gain\": \"Ganancia de días sin trabajo\",\n+\t\t\t\t\"work-sequence-length\": \"Longitud de las secuencias de trabajo\",\n+\t\t\t\t\"work-sequence-deficit\": \"Déficit de las secuencias de trabajo\",\n+\t\t\t\t\"placement-count\": \"Número de colocaciones\"\n+\t\t\t},\n+\t\t\t\"aggregations\": {\n+\t\t\t\t\"sum\": \"Suma\",\n+\t\t\t\t\"count\": \"Cantidad\",\n+\t\t\t\t\"maximum\": \"Máximo\"\n+\t\t\t},\n+\t\t\t\"directions\": {\n+\t\t\t\t\"minimize\": \"Minimizar\",\n+\t\t\t\t\"maximize\": \"Maximizar\"\n+\t\t\t}\n \t\t}\n \t},\n \t\"planning\": {\n@@ -276,7 +321,7 @@\n \t\t\t\"withoutDay\": \"Sin este día\",\n \t\t\t\"withDay\": \"Con este día\",\n \t\t\t\"noChange\": \"Estos totales son iguales. Las reglas y los últimos criterios de desempate (vencimiento del saldo y después fecha) aún pueden influir en la elección.\",\n-\t\t\t\"priorityHelp\": \"Los criterios se muestran por prioridad. La primera diferencia prevalece sobre las siguientes.\",\n+\t\t\t\"priorityHelp\": \"Las obligaciones se resuelven conjuntamente. Las preferencias activas se comparan en el orden de sus reglas. Solo esas reglas añaden vacaciones; la caducidad y luego las fechas resuelven los empates.\",\n \t\t\t\"tryDate\": \"Probar otra fecha\",\n \t\t\t\"plannedDate\": \"Fecha prevista actualmente:\",\n \t\t\t\"currentPlan\": \"Plan actual\",\n@@ -327,6 +372,10 @@\n \t\t\t\t\"placement-date\": {\n \t\t\t\t\t\"label\": \"Primero las fechas más tempranas\",\n \t\t\t\t\t\"help\": \"Último desempate cuando los demás criterios son iguales.\"\n+\t\t\t\t},\n+\t\t\t\t\"optimization\": {\n+\t\t\t\t\t\"label\": \"{rule}: {summary}\",\n+\t\t\t\t\t\"help\": \"Esta preferencia de optimización evalúa su configuración guardada. Las preferencias activas siguen el orden mostrado; las anteriores tienen prioridad.\"\n \t\t\t\t}\n \t\t\t},\n \t\t\t\"stages\": {\n@@ -342,7 +391,9 @@\n \t\t\t\t\"unavailable\": \"Este saldo de permisos no se puede usar en esta fecha.\",\n \t\t\t\t\"expired\": \"Esta fecha es posterior al vencimiento del saldo.\",\n \t\t\t\t\"type-incompatible\": \"Este tipo de permiso no se puede usar en esta fecha.\",\n-\t\t\t\t\"rule-invalid\": \"Usar esta fecha incumpliría una regla del plan.\"\n+\t\t\t\t\"rule-invalid\": \"Usar esta fecha incumpliría una regla del plan.\",\n+\t\t\t\t\"invalid-optimization-configuration\": \"Elija elementos, condiciones, medidas y agregaciones compatibles, con un umbral entero positivo cuando sea necesario.\",\n+\t\t\t\t\"unsupported-optimization-configuration\": \"Esta regla combina elementos del plan y medidas incompatibles.\"\n \t\t\t},\n \t\t\t\"preferenceHelp\": {\n \t\t\t\t\"time_window\": \"Días de permiso dentro del período preferido. Más es mejor.\",\n@@ -373,6 +424,7 @@\n \t\t\t\t\"no-working-date\": \"Ningún día laborable está dentro del período planificado y entre sus fechas de disponibilidad y caducidad.\",\n \t\t\t\t\"all-dates-occupied\": \"Todos los días laborables en los que puede utilizarse este saldo ya están ocupados por permisos planificados o días ya reservados.\",\n \t\t\t\t\"preserved\": \"Guardado para más adelante: caduca después del período planificado y el cálculo no seleccionó ninguna colocación adicional según tus prioridades.\",\n+\t\t\t\t\"active-priorities\": \"El cálculo conservó este saldo sin utilizar según tus reglas activas. Cambia las reglas o su orden para solicitar otro plan.\",\n \t\t\t\t\"calculation-incomplete\": \"El cálculo se interrumpió antes de terminar la planificación. Su falta de uso no es una decisión definitiva.\",\n \t\t\t\t\"not-established\": \"Este cálculo no determinó un motivo preciso para dejarlo sin utilizar.\"\n \t\t\t}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/i18n/es.json", "project_id": 35, "relative_order": 43, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -133,6 +133,51 @@\n \t\t\t\"after\": \"Après\",\n \t\t\t\"around\": \"Autour\",\n \t\t\t\"auto\": \"Auto (Meilleur choix)\"\n+\t\t},\n+\t\t\"optimization\": {\n+\t\t\t\"newRule\": \"Nouvelle règle d’Optimisation\",\n+\t\t\t\"defaultName\": \"Prévention des pertes\",\n+\t\t\t\"elementsLabel\": \"Éléments du planning\",\n+\t\t\t\"conditionsLabel\": \"Conditions (toutes doivent être vérifiées)\",\n+\t\t\t\"measureLabel\": \"Mesure\",\n+\t\t\t\"aggregationLabel\": \"Agrégation\",\n+\t\t\t\"directionLabel\": \"Direction\",\n+\t\t\t\"thresholdLabel\": \"Seuil de préférence en jours ouvrés\",\n+\t\t\t\"thresholdSummary\": \"seuil de préférence : {count} jours ouvrés\",\n+\t\t\t\"summary\": \"{direction} {aggregation} : {measure} — {elements}{conditions}.\",\n+\t\t\t\"invalidConfiguration\": \"Choisissez des éléments, conditions, une mesure et une agrégation compatibles, avec un seuil entier positif si nécessaire.\",\n+\t\t\t\"nameRequired\": \"Saisissez un nom de règle.\",\n+\t\t\t\"elements\": {\n+\t\t\t\t\"leave-balances\": \"Soldes de congés\",\n+\t\t\t\t\"public-holiday-weeks\": \"Semaines avec jour férié\",\n+\t\t\t\t\"time-off-periods\": \"Périodes non travaillées\",\n+\t\t\t\t\"work-sequences\": \"Séquences de travail\",\n+\t\t\t\t\"leave-placements\": \"Congés placés\"\n+\t\t\t},\n+\t\t\t\"conditions\": {\n+\t\t\t\t\"at-risk\": \"À risque d’expiration\",\n+\t\t\t\t\"complete\": \"Complètes\",\n+\t\t\t\t\"internal\": \"Internes\",\n+\t\t\t\t\"non-empty\": \"Non vides\",\n+\t\t\t\t\"supporting\": \"D’appui\"\n+\t\t\t},\n+\t\t\t\"measures\": {\n+\t\t\t\t\"unplaced-quantity\": \"Quantité non placée\",\n+\t\t\t\t\"public-holiday-week-value\": \"Valeur des semaines fériées\",\n+\t\t\t\t\"non-working-day-gain\": \"Gain de jours non travaillés\",\n+\t\t\t\t\"work-sequence-length\": \"Longueur des séquences de travail\",\n+\t\t\t\t\"work-sequence-deficit\": \"Déficit des séquences de travail\",\n+\t\t\t\t\"placement-count\": \"Nombre de placements\"\n+\t\t\t},\n+\t\t\t\"aggregations\": {\n+\t\t\t\t\"sum\": \"Somme\",\n+\t\t\t\t\"count\": \"Nombre\",\n+\t\t\t\t\"maximum\": \"Maximum\"\n+\t\t\t},\n+\t\t\t\"directions\": {\n+\t\t\t\t\"minimize\": \"Minimiser\",\n+\t\t\t\t\"maximize\": \"Maximiser\"\n+\t\t\t}\n \t\t}\n \t},\n \t\"planning\": {\n@@ -276,7 +321,7 @@\n \t\t\t\"withoutDay\": \"Sans ce jour\",\n \t\t\t\"withDay\": \"Avec ce jour\",\n \t\t\t\"noChange\": \"Ces totaux sont identiques. Les règles et les derniers critères de départage (expiration du solde, puis date) peuvent encore influencer le choix.\",\n-\t\t\t\"priorityHelp\": \"Les critères sont classés par priorité. La première différence prime sur les suivantes.\",\n+\t\t\t\"priorityHelp\": \"Les obligations sont résolues conjointement. Les préférences actives sont comparées dans l’ordre de vos règles. Seules ces règles déclenchent des placements ; l’expiration puis les dates départagent les résultats égaux.\",\n \t\t\t\"tryDate\": \"Essayer une autre date\",\n \t\t\t\"plannedDate\": \"Date actuellement prévue :\",\n \t\t\t\"currentPlan\": \"Planning actuel\",\n@@ -327,6 +372,10 @@\n \t\t\t\t\"placement-date\": {\n \t\t\t\t\t\"label\": \"Dates les plus proches d’abord\",\n \t\t\t\t\t\"help\": \"Dernier départage lorsque tous les autres critères sont égaux.\"\n+\t\t\t\t},\n+\t\t\t\t\"optimization\": {\n+\t\t\t\t\t\"label\": \"{rule}: {summary}\",\n+\t\t\t\t\t\"help\": \"Cette préférence d’optimisation évalue sa configuration enregistrée. Les préférences actives suivent l’ordre affiché ; les premières passent avant les suivantes.\"\n \t\t\t\t}\n \t\t\t},\n \t\t\t\"stages\": {\n@@ -342,7 +391,9 @@\n \t\t\t\t\"unavailable\": \"Ce solde de congés ne peut pas être utilisé à cette date.\",\n \t\t\t\t\"expired\": \"Cette date dépasse la date d’expiration du solde.\",\n \t\t\t\t\"type-incompatible\": \"Ce type de congé ne peut pas être utilisé à cette date.\",\n-\t\t\t\t\"rule-invalid\": \"Utiliser cette date ne respecterait pas une règle du planning.\"\n+\t\t\t\t\"rule-invalid\": \"Utiliser cette date ne respecterait pas une règle du planning.\",\n+\t\t\t\t\"invalid-optimization-configuration\": \"Choisissez des éléments, conditions, une mesure et une agrégation compatibles, avec un seuil entier positif si nécessaire.\",\n+\t\t\t\t\"unsupported-optimization-configuration\": \"Cette règle combine des éléments du planning et des mesures incompatibles.\"\n \t\t\t},\n \t\t\t\"preferenceHelp\": {\n \t\t\t\t\"time_window\": \"Jours de congé dans cette période souhaitée. Plus, c’est mieux.\",\n@@ -373,6 +424,7 @@\n \t\t\t\t\"no-working-date\": \"Aucun jour ouvré ne se trouve à la fois dans la période planifiée et entre ses dates de disponibilité et d’expiration.\",\n \t\t\t\t\"all-dates-occupied\": \"Tous les jours ouvrés où ce solde est utilisable sont déjà occupés par des congés calculés ou des jours déjà posés.\",\n \t\t\t\t\"preserved\": \"Conservé pour plus tard : il expire après la période planifiée et le calcul n’a pas retenu de pose supplémentaire selon vos priorités.\",\n+\t\t\t\t\"active-priorities\": \"Le calcul a conservé ce solde inutilisé selon vos règles actives. Modifiez les règles ou leur ordre pour demander un autre planning.\",\n \t\t\t\t\"calculation-incomplete\": \"Le calcul a été interrompu avant de terminer la planification. Sa non-utilisation n’est pas une décision définitive.\",\n \t\t\t\t\"not-established\": \"La raison précise de sa non-utilisation n’a pas été établie par ce calcul.\"\n \t\t\t}\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "src/i18n/fr.json", "project_id": 35, "relative_order": 44, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -85,8 +85,6 @@ test:\n - bun scripts/generate-langs.js\n # ponytail: one worker bounds peak RAM; increase concurrency after adding runner memory.\n - bunx vitest run --coverage --maxWorkers=1 --exclude='src/app/benchmark/**'\n- # Keep the complete benchmark outside coverage instrumentation.\n- - bunx vitest run src/app/benchmark/leave-planner-benchmark.spec.ts --maxWorkers=1\n artifacts:\n when: always\n paths:\n@@ -97,6 +95,15 @@ test:\n path: coverage/cobertura-coverage.xml\n expire_in: 7 days\n \n+# shortcut: benchmark failures are advisory while #78 is open; restore the gate when #78 passes.\n+benchmark:\n+ extends: test\n+ allow_failure: true\n+ script:\n+ - bun scripts/generate-langs.js\n+ - bunx vitest run src/app/benchmark/leave-planner-benchmark.spec.ts --maxWorkers=1\n+ artifacts: null\n+\n # -- Build Stage --\n \n build:\n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": ".gitlab-ci.yml", "project_id": 35, "relative_order": 45, "renamed_file": false, "too_large": false }, { "a_mode": "100644", "b_mode": "100644", "binary": false, "deleted_file": false, "diff": "@@ -247,7 +247,9 @@ GitLab CI runs independent validation, test, build, security, and image stages:\n \n Pipelines switch to MR pipelines when a branch has an open MR, avoiding duplicate builds. Docker publication from MR pipelines is limited to detached pipelines within this project. Tag pipelines promote the already-built commit image instead of rebuilding it.\n \n-The test job runs Vitest directly with one worker and a 2 GiB Node heap limit. It runs application tests with coverage, then the complete benchmark protocol separately without coverage instrumentation. The benchmark uses a five-minute execution timeout to allow for shared-runner contention; all protocol assertions remain mandatory. Timing measurements are benchmark evidence, not CI performance thresholds.\n+The required `test` job runs application tests with coverage, one worker and a 2 GiB Node heap limit. A separate automatic `benchmark` job uses the same environment outside coverage instrumentation, with the unchanged five-minute timeout and protocol assertions.\n+\n+At the user's request, the benchmark job has `allow_failure: true` while #78 is open, so benchmark failure does not block functional delivery. #78 must restore the required benchmark gate after the protocol passes. A green pipeline during this exception does not establish benchmark acceptance.\n \n ### GitFlow and releases\n \n", "encoded_file_path": false, "external_diff_offset": null, "external_diff_size": null, "generated": false, "merge_request_diff_id": 470, "new_file": false, "new_path": null, "old_path": "README.md", "project_id": 35, "relative_order": 46, "renamed_file": false, "too_large": false } ], "metadata": { "base_commit_sha": "209bf05f3699c72f88efab733dde207c7230a8e4", "commits_count": 4, "created_at": "2026-10-10T14:42:33.230158", "diff_type": 2, "files_count": 47, "head_commit_sha": "0cec0e4fa5bb1f0ca0169fafee97b132f46b090d", "id": 470, "merge_request_id": 286, "project_id": 35, "start_commit_sha": "209bf05f3699c72f88efab733dde207c7230a8e4", "state": "collected", "stored_externally": null, "updated_at": "2026-10-10T14:42:33.275306" } } ], "discussions": [ { "id": "505d2457bb463e77a653e3da1112106f9074d07c", "individual_note": true, "notes": [ { "author": { "avatar_url": "https://secure.gravatar.com/avatar/4657567e632c1ae9940f03534ba102a8a0321e4278100cbef34f0ff2d5e4eb72?s=80&d=identicon", "id": 8, "locked": false, "name": "nessar", "public_email": null, "state": "active", "username": "nessar", "web_url": "https://gitlab.nessar.fr/nessar" }, "body": "changed the description", "commands_changes": {}, "confidential": false, "created_at": "2026-10-10T14:23:05.733Z", "id": 2212, "imported": false, "imported_from": "none", "internal": false, "noteable_id": 286, "noteable_iid": 189, "noteable_type": "MergeRequest", "project_id": 35, "resolvable": false, "system": true, "type": null, "updated_at": "2026-10-10T14:23:05.735Z" } ], "resolvable": false }, { "id": "f11d6e25f91da1659b1f974ba29a21dc6caf1a44", "individual_note": true, "notes": [ { "author": { "avatar_url": "https://secure.gravatar.com/avatar/4657567e632c1ae9940f03534ba102a8a0321e4278100cbef34f0ff2d5e4eb72?s=80&d=identicon", "id": 8, "locked": false, "name": "nessar", "public_email": null, "state": "active", "username": "nessar", "web_url": "https://gitlab.nessar.fr/nessar" }, "body": "added 1 commit\n\n
  • 98e87fec - ci: make the deferred planning benchmark non-blocking
\n\n[Compare with previous version](/nessar/vac-optimizer/-/merge_requests/189/diffs?diff_id=467&start_sha=6811142299b21124af146ac7f8cf02a96c4d91c7)", "commands_changes": {}, "confidential": false, "created_at": "2026-10-10T14:37:29.438Z", "id": 2215, "imported": false, "imported_from": "none", "internal": false, "noteable_id": 286, "noteable_iid": 189, "noteable_type": "MergeRequest", "project_id": 35, "resolvable": false, "system": true, "type": null, "updated_at": "2026-10-10T14:37:29.439Z" } ], "resolvable": false }, { "id": "e574c97d35b5a81c365e5d177249a34eea85ad9c", "individual_note": true, "notes": [ { "author": { "avatar_url": "https://secure.gravatar.com/avatar/4657567e632c1ae9940f03534ba102a8a0321e4278100cbef34f0ff2d5e4eb72?s=80&d=identicon", "id": 8, "locked": false, "name": "nessar", "public_email": null, "state": "active", "username": "nessar", "web_url": "https://gitlab.nessar.fr/nessar" }, "body": "changed the description", "commands_changes": {}, "confidential": false, "created_at": "2026-10-10T14:38:19.989Z", "id": 2218, "imported": false, "imported_from": "none", "internal": false, "noteable_id": 286, "noteable_iid": 189, "noteable_type": "MergeRequest", "project_id": 35, "resolvable": false, "system": true, "type": null, "updated_at": "2026-10-10T14:38:19.991Z" } ], "resolvable": false }, { "id": "505af7d2fe86dbd482a13028e66791c9dcd61792", "individual_note": true, "notes": [ { "author": { "avatar_url": "https://secure.gravatar.com/avatar/4657567e632c1ae9940f03534ba102a8a0321e4278100cbef34f0ff2d5e4eb72?s=80&d=identicon", "id": 8, "locked": false, "name": "nessar", "public_email": null, "state": "active", "username": "nessar", "web_url": "https://gitlab.nessar.fr/nessar" }, "body": "added 1 commit\n\n
  • ae68e315 - docs: describe the advisory planning benchmark
\n\n[Compare with previous version](/nessar/vac-optimizer/-/merge_requests/189/diffs?diff_id=469&start_sha=98e87feceea9ba6f212ce162f61b4605fa6bde98)", "commands_changes": {}, "confidential": false, "created_at": "2026-10-10T14:42:05.679Z", "id": 2219, "imported": false, "imported_from": "none", "internal": false, "noteable_id": 286, "noteable_iid": 189, "noteable_type": "MergeRequest", "project_id": 35, "resolvable": false, "system": true, "type": null, "updated_at": "2026-10-10T14:42:05.680Z" } ], "resolvable": false }, { "id": "792b923aac6720f7fa459588dcbbb621325d9f3b", "individual_note": true, "notes": [ { "author": { "avatar_url": "https://secure.gravatar.com/avatar/4657567e632c1ae9940f03534ba102a8a0321e4278100cbef34f0ff2d5e4eb72?s=80&d=identicon", "id": 8, "locked": false, "name": "nessar", "public_email": null, "state": "active", "username": "nessar", "web_url": "https://gitlab.nessar.fr/nessar" }, "body": "mentioned in commit 0d900fd72d1a405d257f5a566c55cc0cb3d2bc61", "commands_changes": {}, "confidential": false, "created_at": "2026-10-10T14:56:51.133Z", "id": 2225, "imported": false, "imported_from": "none", "internal": false, "noteable_id": 286, "noteable_iid": 189, "noteable_type": "MergeRequest", "project_id": 35, "resolvable": false, "system": true, "type": null, "updated_at": "2026-10-10T14:56:51.134Z" } ], "resolvable": false } ], "format_version": 1, "notes": [ { "author_id": 8, "change_position": null, "commit_id": null, "confidential": null, "created_at": "2026-10-10T14:23:05.733852", "discussion_id": "505d2457bb463e77a653e3da1112106f9074d07c", "id": 2212, "imported_from": 0, "internal": false, "last_edited_at": null, "line_code": null, "namespace_id": null, "note": "changed the description", "noteable_id": 286, "noteable_type": "MergeRequest", "organization_id": null, "original_position": null, "position": null, "project_id": 35, "resolved_at": null, "resolved_by_id": null, "resolved_by_push": null, "review_id": null, "source_iid": 189, "source_item_project_id": 35, "st_diff": null, "system": true, "type": null, "updated_at": "2026-10-10T14:23:05.735139", "updated_by_id": null }, { "author_id": 8, "change_position": null, "commit_id": null, "confidential": null, "created_at": "2026-10-10T14:37:29.438668", "discussion_id": "f11d6e25f91da1659b1f974ba29a21dc6caf1a44", "id": 2215, "imported_from": 0, "internal": false, "last_edited_at": null, "line_code": null, "namespace_id": null, "note": "added 1 commit\n\n
  • 98e87fec - ci: make the deferred planning benchmark non-blocking
\n\n[Compare with previous version](/nessar/vac-optimizer/-/merge_requests/189/diffs?diff_id=467&start_sha=6811142299b21124af146ac7f8cf02a96c4d91c7)", "noteable_id": 286, "noteable_type": "MergeRequest", "organization_id": null, "original_position": null, "position": null, "project_id": 35, "resolved_at": null, "resolved_by_id": null, "resolved_by_push": null, "review_id": null, "source_iid": 189, "source_item_project_id": 35, "st_diff": null, "system": true, "type": null, "updated_at": "2026-10-10T14:37:29.439713", "updated_by_id": null }, { "author_id": 8, "change_position": null, "commit_id": null, "confidential": null, "created_at": "2026-10-10T14:38:19.989911", "discussion_id": "e574c97d35b5a81c365e5d177249a34eea85ad9c", "id": 2218, "imported_from": 0, "internal": false, "last_edited_at": null, "line_code": null, "namespace_id": null, "note": "changed the description", "noteable_id": 286, "noteable_type": "MergeRequest", "organization_id": null, "original_position": null, "position": null, "project_id": 35, "resolved_at": null, "resolved_by_id": null, "resolved_by_push": null, "review_id": null, "source_iid": 189, "source_item_project_id": 35, "st_diff": null, "system": true, "type": null, "updated_at": "2026-10-10T14:38:19.991066", "updated_by_id": null }, { "author_id": 8, "change_position": null, "commit_id": null, "confidential": null, "created_at": "2026-10-10T14:42:05.679962", "discussion_id": "505af7d2fe86dbd482a13028e66791c9dcd61792", "id": 2219, "imported_from": 0, "internal": false, "last_edited_at": null, "line_code": null, "namespace_id": null, "note": "added 1 commit\n\n
  • ae68e315 - docs: describe the advisory planning benchmark
\n\n[Compare with previous version](/nessar/vac-optimizer/-/merge_requests/189/diffs?diff_id=469&start_sha=98e87feceea9ba6f212ce162f61b4605fa6bde98)", "noteable_id": 286, "noteable_type": "MergeRequest", "organization_id": null, "original_position": null, "position": null, "project_id": 35, "resolved_at": null, "resolved_by_id": null, "resolved_by_push": null, "review_id": null, "source_iid": 189, "source_item_project_id": 35, "st_diff": null, "system": true, "type": null, "updated_at": "2026-10-10T14:42:05.680953", "updated_by_id": null }, { "author_id": 8, "change_position": null, "commit_id": null, "confidential": null, "created_at": "2026-10-10T14:56:51.133879", "discussion_id": "792b923aac6720f7fa459588dcbbb621325d9f3b", "id": 2225, "imported_from": 0, "internal": false, "last_edited_at": null, "line_code": null, "namespace_id": null, "note": "mentioned in commit 0d900fd72d1a405d257f5a566c55cc0cb3d2bc61", "noteable_id": 286, "noteable_type": "MergeRequest", "organization_id": null, "original_position": null, "position": null, "project_id": 35, "resolved_at": null, "resolved_by_id": null, "resolved_by_push": null, "review_id": null, "source_iid": 189, "source_item_project_id": 35, "st_diff": null, "system": true, "type": null, "updated_at": "2026-10-10T14:56:51.134808", "updated_by_id": null } ], "preexisting_missing_alternate_head": false, "source_assignees": [], "source_author": { "avatar_url": "https://secure.gravatar.com/avatar/4657567e632c1ae9940f03534ba102a8a0321e4278100cbef34f0ff2d5e4eb72?s=80&d=identicon", "id": 8, "locked": false, "name": "nessar", "public_email": null, "state": "active", "username": "nessar", "web_url": "https://gitlab.nessar.fr/nessar" }, "source_created_at": "2026-10-10T14:08:46.466Z", "source_discussion_locked": null, "source_id": 286, "source_iid": 189, "source_item_metadata": { "assignee": null, "assignees": [], "author": { "avatar_url": "https://secure.gravatar.com/avatar/4657567e632c1ae9940f03534ba102a8a0321e4278100cbef34f0ff2d5e4eb72?s=80&d=identicon", "id": 8, "locked": false, "name": "nessar", "public_email": null, "state": "active", "username": "nessar", "web_url": "https://gitlab.nessar.fr/nessar" }, "blocking_discussions_resolved": true, "closed_at": null, "closed_by": null, "created_at": "2026-10-10T14:08:46.466Z", "description": "Replaces fixed optimization stages with explicit, composable rules evaluated in the displayed priority order. The six supplied presets use the same configuration, editor and planner as personal rules. With no active rules, calculations preserve declared days and add no leave.\n\nMigrates legacy saved rules once into a versioned list, preserving identities, parameters, dates, force, disabled states and relative order. Deleted presets and deliberately empty lists remain deleted or empty after reload. Completed and cancelled plans retain consistent rule provenance, stable explanations and captured settings.\n\nCloses #70, #71, #72, #73 and #74. Completes the functional scope of #75, which is already closed.\n\nValidation of the committed source:\n\n- 652 functional tests in 34 files pass under a 2 GB Node heap; coverage: 92.66% statements, 84.31% branches, 94.84% functions and 94.63% lines.\n- TypeScript, Angular compilation, ESLint, formatting, CI policy self-check and production build pass.\n- 22 Chromium production-browser checks with real Web Workers pass, including migration, first calculation, persisted edits, keyboard ordering and narrow viewports; no page or console errors.\n- Independent Standards and functional Spec reviews report 0 findings. The committed production source exactly matches the tested and reviewed integrated result.\n\nPerformance acceptance remains in #78, after original decision trace removal in #76 and functional verification in #77. These follow-up specifications are included; their implementation is pending. The seven-scenario benchmark has not passed: MR pipeline 320 timed out at the unchanged 300-second limit after all 652 functional tests passed.\n\nAt the user's request, commit `98e87fe` separates the benchmark into its own automatic CI job with `allow_failure: true` while #78 is open. Functional coverage and all unrelated jobs keep their previous gating behavior. The benchmark's 2 GB heap limit, 300-second timeout, scenarios, repetitions, assertions and search-quality requirements remain unchanged. #78 must restore the required benchmark gate after the protocol passes; a green pipeline during this exception does not satisfy performance acceptance.\n\nGitLab static lint and pipeline simulation pass without warnings, and a comparison of the resolved jobs confirms every unrelated job is unchanged. Independent Standards and Spec reviews of the five-file CI/documentation change report 0 findings. Application source is unchanged from the verified implementation.\n\nExisting production build warning budgets remain exceeded (2.63 MB initial bundle and 14.11 KB calendar stylesheet); hard budgets pass. Reference-phone performance has not been measured.\n\nTargets `develop`; project merge commits and disabled squashing are retained.", "detailed_merge_status": "not_open", "discussion_locked": null, "downvotes": 0, "draft": false, "force_remove_source_branch": true, "has_conflicts": false, "id": 286, "iid": 189, "imported": false, "imported_from": "none", "labels": [], "merge_after": null, "merge_commit_sha": "0d900fd72d1a405d257f5a566c55cc0cb3d2bc61", "merge_status": "can_be_merged", "merge_user": { "avatar_url": "https://secure.gravatar.com/avatar/4657567e632c1ae9940f03534ba102a8a0321e4278100cbef34f0ff2d5e4eb72?s=80&d=identicon", "id": 8, "locked": false, "name": "nessar", "public_email": null, "state": "active", "username": "nessar", "web_url": "https://gitlab.nessar.fr/nessar" }, "merge_when_pipeline_succeeds": false, "merged_at": "2026-10-10T14:56:49.453Z", "merged_by": { "avatar_url": "https://secure.gravatar.com/avatar/4657567e632c1ae9940f03534ba102a8a0321e4278100cbef34f0ff2d5e4eb72?s=80&d=identicon", "id": 8, "locked": false, "name": "nessar", "public_email": null, "state": "active", "username": "nessar", "web_url": "https://gitlab.nessar.fr/nessar" }, "milestone": null, "prepared_at": "2026-10-10T14:09:00.274Z", "project_id": 35, "reference": "!189", "references": { "full": "nessar/vac-optimizer!189", "relative": "!189", "short": "!189" }, "reviewers": [], "sha": "ae68e31575c7b6c857bb0d5d538b7c4f418887e1", "should_remove_source_branch": true, "source_branch": "feature/optimization-rules-70-75", "source_project_id": 35, "squash": false, "squash_commit_sha": null, "squash_on_merge": false, "state": "merged", "target_branch": "develop", "target_project_id": 35, "task_completion_status": { "completed_count": 0, "count": 0 }, "time_stats": { "human_time_estimate": null, "human_total_time_spent": null, "time_estimate": 0, "total_time_spent": 0 }, "title": "feat(planning): make optimization rules composable", "updated_at": "2026-10-10T14:56:50.608Z", "upvotes": 0, "user_notes_count": 0, "web_url": "https://gitlab.nessar.fr/nessar/vac-optimizer/-/merge_requests/189", "work_in_progress": false }, "source_kind": "MergeRequest", "source_path": "nessar/vac-optimizer", "source_project_id": 35, "source_reviewers": [], "source_updated_at": "2026-10-10T14:56:50.608Z", "state_events": [ { "close_after_error_tracking_resolve": false, "close_auto_resolve_prometheus_alert": false, "created_at": "2026-10-10T14:56:49.514168+00:00", "epic_id": null, "id": 695, "imported_from": 0, "issue_id": null, "merge_request_id": 286, "namespace_id": 38, "source_commit": null, "source_merge_request_id": null, "state": 3, "user_id": 8 } ], "target_number": 267 }