Author SHA1 Message Date
nessar 221edfa5ba Merge branch 'feature/ui-ux-results' into feature/ui-ux-refresh (#353, #354, #355)
# Conflicts:
#	src/app/components/user-input/user-input.html
2026-11-13 19:03:22 +01:00
nessarandClaude Fable 5.2 8be156bff4 feat(ui): keep the configuration panel in view on wide screens (#355)
At the two-column breakpoint the panel is sticky and scrolls internally, and
the indicative wait with the Calculate button stays pinned at its bottom. The
panel is registered as a CDK scrollable so that dragging a rule still
auto-scrolls it. Single-column layouts are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 19:02:28 +01:00
nessar 95e36e8a4e Merge branch 'feature/ui-ux-empty-start' into feature/ui-ux-refresh (#356) 2026-11-13 18:59:26 +01:00
nessarandClaude Opus 5.5 55144aaf37 feat(balances): start from an empty leave-balance list instead of random defaults (#356)
An absent or unreadable saved list now starts empty; no quantity is
generated. With no leave balance and no declared non-working day there
is nothing to plan: no calculation starts on load, Calculate is disabled
with the reason exposed through aria-describedby, and the results panel
shows the planning horizon's calendar with an invitation. Declared days
alone still calculate, so earned-leave chains keep working.

ADR 0012 records the decision and supersedes the random defaults of
ADR 0005. Tests now state their balances explicitly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 18:58:31 +01:00
nessarandClaude Fable 5.2 6660e7e6bb feat(ui): show the calendar directly under the plan summary (#354)
Move the time-window, if-then and declared time-off period blocks into one
closed "applied rules detail" disclosure next to the placement explanation,
so the legend and the first row of months sit under the summary figures.
Put the status and the calculation date on the heading line.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 18:49:07 +01:00
nessarandClaude Fable 5.2 7ebc87be33 feat(ui): polish product name, statistics and calculation date (#353)
Show the product name VacOptimizer in the header, round plan statistics to one
decimal in the active locale, lay the statistics tiles out in two columns when
the dialog is wide enough, and attach the calculation date to the results
heading and status instead of a free paragraph.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 18:41:55 +01:00
nessarandClaude Fable 5.2 2dbd23230c fix(planning-duration): refit the indicative wait and calibrate it from similar calculations
CI / build (pull_request) Successful in 38s
CI / security (pull_request) Successful in 1m43s
CI / validate (push) Successful in 28s
CI / security (push) Successful in 1m43s
CI / required (push) Successful in 1s
CI / images (pull_request) Successful in 1m12s
CI / test (push) Successful in 2m58s
CI / benchmark (push) Successful in 1m21s
CI / build (push) Successful in 33s
CI / validate (pull_request) Successful in 33s
CI / test (pull_request) Successful in 3m0s
CI / benchmark (pull_request) Successful in 1m21s
CI / required (pull_request) Successful in 1s
CI / images (push) Successful in 1m14s
CI / policy (pull_request) Successful in 9s
CI / policy (push) Successful in 9s
After #321 the prior overstated requests without calendar rules. It also
understated the default rules: Samedi Malin made multi-year requests up
to four times slower than the estimate, beyond the top of the displayed
range.

- The prior is refitted to 38 planning times of one to five years on
  Bun, with and without the default calendar rules: a linear horizon
  term, a placement power of 1.4 and a weight of 4 per IF_THEN rule.
  Measured time now lies between 0.59 and 2.26 times the estimate,
  against 0.43 to 4.12.
- The current form is scaled by the median ratio of its similar past
  calculations, those with the same rule weight and an initial estimate
  within a factor of two, before falling back to the median of all
  eight. A slow configuration is therefore predicted from its own wait
  on the next calculation, where the overall median kept
  underestimating it.

The measurements are planning times in the core, not rendered waits; the
fixed 400 ms for transport and rendering is unmeasured since planning
moved to the server. Obligation weights are unchanged and remain
unreliable (#347).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 21:14:55 +01:00
nessarandClaude Fable 5.2 2dfd00175e perf(planning): reduce JavaScriptCore hotspots in candidate scoring
On Bun, the benchmark's loaded year spent 57% of its time scoring
candidate plans. Freezing a 40-element array costs about 50 times the
map that builds it, and a frozen array reads about 12 times slower.

- The lists that plan observations build per candidate plan are no
  longer frozen. Their elements stay frozen and their types readonly;
  work sequences reuse one frozen object per distinct sequence.
- An optimization is scored in one loop, without intermediate arrays.
  Balance and placement observations are built on first read, a
  TIME_WINDOW preference stops counting at its requested quantity, and
  the expiry tie-break sorts without a comparator.
- A finalized candidate's objective vector no longer counts unsatisfied
  obligations again. The retained plan's state key is built once. An
  earned entitlement's merged period is found without materializing
  every period, and its date arithmetic runs once per period.
- A candidate already worse on a protected objective is still rejected
  before finalization when a rule can earn leave, as long as finalizing
  it cannot touch an earned balance. Samedi Malin used to switch this
  pruning off.

Loaded year 6.31 s to 2.70 s, three years 3.55 s to 1.66 s, two years
1.10 s to 0.54 s. Every outcome, stable explanation and final state is
unchanged: the frozen-engine differential check passes, and 26 requests
of one to four years match the previous engine, cancelled runs included.

The benchmark budgets follow at about 1.5 times the new ratios. The
record lists four search behaviors found on the way and left as they
are (#347, #348, #349, #350).

Closes #321

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 21:14:55 +01:00
nessarandClaude Fable 5.2 5810b59284 refactor(planning): apply the findings of the branch review
CI / build (pull_request) Successful in 33s
CI / security (pull_request) Successful in 1m41s
CI / validate (push) Successful in 28s
CI / security (push) Successful in 1m56s
CI / required (push) Successful in 2s
CI / images (pull_request) Successful in 1m12s
CI / test (push) Successful in 3m30s
CI / benchmark (push) Successful in 1m50s
CI / build (push) Successful in 32s
CI / validate (pull_request) Successful in 33s
CI / test (pull_request) Successful in 3m32s
CI / benchmark (pull_request) Successful in 1m49s
CI / required (pull_request) Successful in 2s
CI / images (push) Successful in 1m16s
CI / policy (pull_request) Successful in 10s
CI / policy (push) Successful in 7s
A standards review and a spec review of the ten tickets found no blocking
defect. This applies what they did find.

- A request that is not an object reaches the planner again, which
  reports what it lacks, where the lifecycle answered that it could not
  be cloned.
- The Compare dates button moves into the date-comparison component, so
  the page reads none of its state.
- The numeric changes of a comparison are computed by one function in
  the labels module for the placement explanation and the dialog.
- The explanation error of a calculation is typed as an interruption
  reason up to the page.
- The two new components use OnPush, as every component but the page.
- The page's date helper loses its Date branch, dead since planning
  dates are strings.
- README and the verification notes describe where a calculation is
  created, what the worker entry does and which requests are answered
  before a job starts. A moved comment says planning stage, not phase.

Refs #335

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 19:08:51 +01:00
nessarandClaude Fable 5.2 98685de72f refactor(calendar-year): extract the date comparison dialog into its own component
The calendar-year component held the whole counterfactual date analysis
session: six signals, a version counter, a dialog reference, a retry
selection and about 200 template lines, mixed into its date selection.

- A date-comparison component owns the dialog and its analysis, loading,
  error and selected-date state. Its inputs are the accepted calculation
  and the selected leave placement; it emits the announcements the page
  writes to its live region. The page passes it calendar dates through
  one method and reads none of its state.
- The calculation context alone decides whether an analysis was
  superseded. The component keeps one local guard for what never reaches
  the context: closing, new inputs and destruction. The comparison of
  calculation identities is gone.
- The criteria table and raw data shared by the comparison and the
  placement explanation become a presentational component, and the rules
  both need move to one Sass partial.

No user-visible change: the dialog's labelling, focus, announcements and
the empty body after a stale result are as before.

Refs #345

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 01:54:06 +01:00
nessarandClaude Fable 5.2 1362cca280 refactor(planning): share one request shape across the lifecycle, messages and core
A planning request was described several times with every field typed
unknown: in the worker messages and twice inside the planner core, which
also read the raw request again after validating it. One request type now
serves the lifecycle, all three request-carrying messages and the core.

- The core's entry points still take an unverified value, since the
  planning server forwards client JSON. They validate and normalize it
  once and the planner reads only the result.
- Labels and identities are typed as text records.
- invalidInputFor loses its last caller and is removed.

No outcome, validation reason or reason order changes; 21 tests written
before the core change pin the handling of malformed requests and pass
unchanged. Four labelling details differ for requests the application
never sends, each stated by a test: labels given as an array no longer
match inherited properties, a balance label that is not text no longer
hides the balance name, a disabled rule no longer names an enabled rule
with the same id, and a balance type given as an array is repeated as the
balance's own type.

Refs #342

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-11 01:51:50 +01:00
nessarandClaude Fable 5.2 4ffd75eeba refactor(planning): carry planning dates as strings and snapshot requests by cloning
A planning date at the calculation interface was `string | Date`, although
production only passed strings below the form adapter, and the lifecycle
copied every request field by hand, with a per-rule-type field list, Date
branches and a date re-encoding for the socket path only.

- A planning date is a string. The form adapter stays the only place that
  converts a Date; the planner core reports a Date as invalid planning
  input through the existing reason of its field.
- The request snapshot is one deeply frozen structured clone without the
  progress callback. The job message and the public snapshot both come
  from it, so the local worker and the planning server receive the same
  request.
- A request that cannot be cloned is reported as invalid input.

Fields no list names now reach the planner, including the legacy balance
aliases the copy used to drop; the core does not read them.

Refs #341

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 22:16:22 +01:00
nessarandClaude Fable 5.2 401665080c refactor(calendar): return the calendar service to calendar projection
The calendar service carried members that have nothing to do with
projecting a calendar: the seam specs used to replace how a planning
calculation is created, a planLeave pass-through, and members only their
own spec cases used.

- The creation seam moves to the planning calculation service, the single
  owner of calculations, and takes the optional job factory. Specs replace
  it there and assert what they asserted before.
- planLeave, monthNames, monthsInYear, the Year type and SelectedDate's
  day-length method are deleted with their two spec cases.
- VacDay moves next to the user input service as LeaveBalance, the
  glossary term.

The calendar service no longer imports the planning lifecycle.

Refs #340

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 21:58:10 +01:00
nessarandClaude Fable 5.2 a81ee641c3 refactor(calendar-year): move planner label logic into a pure labels module
The calendar-year component turned planning outcomes, reasons, planning
stages and objective identifiers into text itself, so each sentence could
only be tested by mounting the whole page. That logic now lives in one
module of plain functions that take the translations and the data, tested
without TestBed. The component keeps thin calls with the same names.

- The optimization and preference identifier prefixes are parsed in one
  place outside the planner core.
- The optimization summary moves with it, since objective copy needs it;
  the translation service delegates.
- The three fixed status headings use the same outcome label as the live
  announcement. No sentence changes in any language.

Refs #344

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 21:40:32 +01:00
nessarandClaude Fable 5.2 80a3c22bba refactor(planning): type interruption reason codes and key their translations
The reason of an incomplete calculation was a plain string, so a mistyped
code or a missing translation showed English at runtime instead of failing
the build. The eight interruption codes are now a union type carried by
incomplete outcomes, the worker's error response and the translation table,
where they are required keys in every language.

A counterfactual failure in the worker now reports `worker-error` instead of
`counterfactual-error`, a code outside the union that nothing read.

Refs #343

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 21:40:32 +01:00
nessarandClaude Fable 5.2 f65f02dd5c refactor(planning): keep one calculation lifecycle
The calculation entry point had three paths: the worker path, one for a
window without a Worker, and an in-process one for no window with its own
cancellation, replacement and explanation flags. Date analysis had a
main-thread fallback too. Only the worker path remains, on the job the
caller passes or the default selection, so every rule of an incomplete
calculation is decided once.

- The lifecycle module no longer checks the window or imports the planner
  core at runtime; browsers load the core only in the worker bundle.
- One registry holds the live supersession callbacks, the latest
  calculation identity and the latest date analysis.
- A browser with a window but no Worker now reports worker-unavailable
  even for an invalid request, where it reported invalid input first.
- The build forces Angular's chunk optimization: with the lazy core chunk
  gone the build fell under Angular's three-lazy-chunk threshold and the
  initial bundle was split and grew.

Refs #339

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 21:39:56 +01:00
nessarandClaude Fable 5.2 c1b4af382b test(planning): stop choosing the planning engine by stubbing window
The remaining twelve specs that stubbed the global window to reach a
planner now say what they run. Planner behaviour specs use the in-process
job, the cancellation spec scripts a job, and the transport specs keep
their Worker and WebSocket fakes and lose only the stub.

The benchmark runner takes an optional job factory so the gate measures
the in-process job; the page still calls it without one.

Two expectations follow the production lifecycle instead of the old
non-worker path: a calculation replaced before its first checkpoint has
no explanation and a stale-calculation explanation error, and a progress
callback that throws is exercised on the planner core directly, since a
job runs that callback outside the planner.

Refs #338

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 21:00:33 +01:00
nessarandClaude Fable 5.2 a8dc58db74 test(planning): script calculation lifecycle specs through jobs
The planning calculation spec chose its engine by stubbing the global
window and scripted lifecycle behaviour with twelve hand-written fake
Worker classes. Planner behaviour tests now run on the in-process job,
lifecycle tests script a job, and the browser that cannot start a worker
is a job factory that throws.

All 170 tests remain and no expectation changed to make a test pass. The
expired-deadline test only checked the outcome kind and passed on
worker-unavailable under the default setup; it now asserts the deadline
reason.

Refs #337

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 20:41:19 +01:00
nessarandClaude Fable 5.2 62df01857c refactor(planning): run planner messages through a swappable job
Prefactoring for a single calculation lifecycle. The job that carries
planner messages becomes a parameter of the calculation entry point, and
a third implementation runs the worker's message handling on the calling
thread, so specs and non-browser callers can use the worker path without
a Worker.

- The worker's message handling moves into a handler with per-instance
  state; the worker entry binds it to its port.
- A passed job factory always takes the worker path, whatever the globals
  say, for the plan, date analyses and the checkpoint explanation.
- The lifecycle registers supersession for every job it starts, so jobs
  implemented outside the module yield to a newer calculation too.
- The in-process job lives in a module the default selection does not
  import: browsers still load the planner core only in the worker bundle.

No calculation path is deleted and no existing spec changes.

Refs #336

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 19:54:41 +01:00
nessarandClaude Opus 5.5 ea2feaf766 fix(planning): stop IF_THEN patterns at a weekday public holiday
CI / security (pull_request) Successful in 1m27s
CI / validate (push) Successful in 32s
CI / security (push) Successful in 1m17s
CI / required (push) Successful in 1s
CI / build (pull_request) Successful in 34s
CI / images (pull_request) Successful in 1m8s
CI / test (push) Successful in 3m25s
CI / build (push) Successful in 38s
CI / validate (pull_request) Successful in 30s
CI / test (pull_request) Successful in 3m25s
CI / benchmark (pull_request) Successful in 1m47s
CI / required (pull_request) Successful in 3s
CI / benchmark (push) Successful in 1m48s
CI / images (push) Successful in 1m9s
CI / policy (pull_request) Successful in 8s
CI / policy (push) Successful in 7s
Pattern days were the nearest working days on each side, so a weekday
public holiday was skipped. For Samedi Malin on Saturday 8 May 2027 the
planner therefore picked Wednesday 5 and Friday 7 May across Ascension,
a pattern the employer does not credit: the answer given at the October
2026 local representatives meeting (Thales group agreement, article 4)
keeps only "one CP day on each side" and "two CP days after" that year.

Each side now takes the nearest Monday-to-Friday dates, skipping only
weekends; a weekday public holiday ends the side, so that split is
unavailable. Fixtures that relied on Wednesday 8 May 2024 reaching across
Ascension, including the chained earned entitlements benchmark scenario,
now place their patterns on the other side of the holiday.

The frozen-engine check is unchanged: its 5,000 generated requests plan
identically, so the frozen bundle is not rebuilt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 10:37:07 +01:00
nessarandClaude Opus 5.5 cfd9a69f33 fix(i18n): translate planner messages and remaining English UI text
CI / security (pull_request) Successful in 1m5s
CI / validate (push) Successful in 42s
CI / security (push) Successful in 1m44s
CI / required (push) Successful in 1s
CI / build (pull_request) Successful in 38s
CI / images (pull_request) Successful in 1m15s
CI / build (push) Successful in 35s
CI / benchmark (push) Successful in 1m31s
CI / test (push) Successful in 2m45s
CI / validate (pull_request) Successful in 43s
CI / benchmark (pull_request) Successful in 1m42s
CI / test (pull_request) Successful in 2m58s
CI / required (pull_request) Successful in 1s
CI / images (push) Successful in 54s
CI / policy (pull_request) Successful in 11s
CI / policy (push) Successful in 6s
French (and German/Spanish) users saw English wherever the UI rendered
planning-engine reason messages or raw identifiers.

- Look up planner reasons by code in planning.reasons and
  planning.validationReasons instead of rendering reason.message; the
  engine keeps its English messages.
- Show calculation stages with their translated labels.
- Translate the Material datepicker labels and the comparison date
  placeholder; add the declared-day comparison reason.
- Keep <html lang> in sync with the loaded translation.
- Generate the registry with English first and `satisfies
  AppTranslations`, and test that every language has en.json's keys.
- Fix fr "Weekend" -> "Week-end".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 13:06:34 +01:00
nessarandClaude Opus 5.5 3175dcc55b feat(planning): report a lost server connection as connection-lost
CI / build (pull_request) Successful in 31s
CI / security (pull_request) Successful in 1m41s
CI / validate (push) Successful in 34s
CI / security (push) Successful in 56s
CI / required (push) Successful in 1s
CI / images (pull_request) Successful in 1m14s
CI / build (push) Successful in 26s
CI / benchmark (push) Successful in 1m45s
CI / test (push) Successful in 2m41s
CI / validate (pull_request) Successful in 31s
CI / benchmark (pull_request) Successful in 1m25s
CI / test (pull_request) Successful in 2m54s
CI / required (pull_request) Successful in 1s
CI / images (push) Successful in 54s
CI / policy (pull_request) Successful in 8s
CI / policy (push) Successful in 20s
A planning socket that closes after the server's first message now gives
a connection-lost incomplete calculation, shown as a warning with the
best valid plan kept, instead of the planner error alert. Closes the
server sends for a failed worker or a protocol violation (1003, 1007,
1008, 1009, 1011) and unparseable messages stay worker-error. Only the
close event decides, since an error event always precedes it and carries
no code. The liveness watchdog is unchanged.

Refs #330

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:10:45 +01:00
nessarandClaude Opus 5.5 99d1b9c2ec docs(context): keep the best valid plan for every incomplete calculation
The glossary limited the retained plan to user cancellation, while the
coordinator keeps it for every interruption and ADR 0011 keeps it after a
lost connection.

Refs #330

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:10:45 +01:00
nessarandClaude Opus 5.5 d018d5c1c3 refactor(planning): share the planning socket's job table with the server
PLANNING_JOBS in leave-planner.worker-messages.ts now lists each job
kind's follow-up messages and terminal responses, checked against
WorkerRequest and WorkerResponse. The server reads it in place of its own
TERMINAL_MESSAGES and cancel check, so a new job request type without an
entry fails the typecheck instead of closing sockets with 1008.

Refs #331

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:10:45 +01:00
nessarandClaude Opus 5.5 3044d507a2 refactor(server): name the planning terminal messages and error handler
Rename TERMINAL to TERMINAL_MESSAGES and the shared error handler to
internalError, which no longer shadows its parameter. Describe the
browser cancellation check for server planning and its local fallback.

Refs #319

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:10:45 +01:00
nessarandClaude Opus 5.5 aea16d29f2 docs(readme): state which planning socket messages close it
Refs #323

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:10:45 +01:00
nessarandClaude Opus 5.5 1df34e4acb docs: point stale planner references at ADR 0011
Mark ADR 0011 as implemented, cite it where docs/statistics.md still
named the client-side planner as a constraint, and say that development
runs calculate locally because they have no build identifier.

Refs #319

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:10:45 +01:00
nessarandClaude Opus 5.5 a12e27bfdc fix(planning): accept one job message and one cancel per planning socket
A socket could send any number of messages after its first: each extra
plan started another calculation in the same worker, and a waiting
socket buffered without limit, so one client could exhaust the server's
memory. A socket now carries its job message and, for a plan, at most
one cancel; anything else closes it with 1008. Only a plan can be
promoted by a cancel, since other jobs ignore it and would run in full
beyond PLANNING_WORKERS.

A worker that exits on its own now closes its socket with 1011 and
frees its slot instead of holding it until the client gives up.

Refs #323, #324

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:10:45 +01:00
nessarandClaude Opus 5.5 6e28939e26 feat(planning): queue server calculations beyond PLANNING_WORKERS
At most PLANNING_WORKERS jobs run at once; the others wait in arrival
order with a heartbeat every second, so the client's liveness timer
keeps running. A socket joins the line with its first message, and the
job's terminal message or the socket closing frees its slot for the
next one, so an idle open socket holds no core. Cancel or a close
removes a waiting job; a cancelled one runs at once and stops at its
first yield with the worker's own cancelled outcome.

PLANNING_WORKERS defaults to half the reported CPU threads. The
production Compose file drops the one-CPU and 512 MB limits, caps
memory at 8 GB and passes PLANNING_WORKERS through.

Closes #323

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:10:45 +01:00
nessarandClaude Opus 5.5 429b18ba64 feat(planning): limit server calculations per client IP
Each client IP, read from CF-Connecting-IP or else the socket's remote
address, may hold five admitted planning sockets. The server closes a
sixth with code 4429 before any message, so that tab calculates locally;
closing a socket frees its place. Incoming messages over 1 MB drop the
socket without running a calculation.

The README states that the limit holds only if the origin accepts
traffic from Cloudflare alone, since anyone else can forge the header.

Closes #324

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:10:45 +01:00
nessarandClaude Opus 5.5 63fc119297 feat(planning): calculate locally when client and server builds differ
`bun run build` now builds the browser and server bundles in one script
that defines a fresh PLANNING_BUILD identifier for both. The client sends
it when it opens a planning socket, and the server closes a socket from
another build, or without one, with code 4409 before any message, so a
tab opened before a deployment calculates with its own engine.

Development and test runs have no identifier: the client skips the
socket and calculates locally, and a server run from source accepts no
planning sockets.

Closes #325

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:10:45 +01:00
nessarandClaude Opus 5.5 e2a5a6f0e8 feat(planning): calculate plans on the server over a WebSocket
Each worker job (a plan, an incomplete-checkpoint explanation or a
counterfactual analysis) opens one same-origin socket at /api/planning
that carries the existing worker protocol as JSON. The Bun server runs
the unchanged planner worker in a Bun Worker per socket and terminates it
when the socket closes. The production build ships the worker as its own
entry point next to server.js.

On the client the socket is a second worker job, so liveness,
cancellation, checkpoints, explanations and supersession are unchanged.
Until the server first answers, a socket that fails, does not open
within 5 seconds or is closed falls back to a local worker and replays
the messages posted so far. A connection lost afterwards gives an
incomplete calculation with the retained plan, without a retry. Request
dates go out as Europe/Paris dates, as the core reads a Date.

Closes #320

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:10:45 +01:00
nessarandClaude Opus 5.5 dbc612336b ci: review pull requests with Claude on @claude comments
CI / security (pull_request) Successful in 1m1s
CI / validate (push) Successful in 36s
CI / security (push) Successful in 1m5s
CI / required (push) Successful in 9s
CI / build (pull_request) Successful in 38s
CI / images (pull_request) Successful in 1m16s
CI / build (push) Successful in 34s
CI / test (push) Successful in 2m36s
CI / validate (pull_request) Successful in 32s
CI / test (pull_request) Successful in 2m29s
CI / benchmark (pull_request) Successful in 1m45s
CI / required (pull_request) Successful in 1s
CI / benchmark (push) Successful in 1m49s
CI / images (push) Successful in 1m7s
CI / policy (pull_request) Successful in 12s
CI / policy (push) Successful in 18s
When the repository owner comments @claude on a PR, run Claude Code
headless with the checked-in code-review skill and post its review as a
PR comment. Claude gets read-only tools and never holds the Gitea token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 19:02:05 +01:00
nessarandClaude Opus 5.5 8326511dc9 docs(adr): plan on the server for every device
CI / security (pull_request) Successful in 1m0s
CI / validate (push) Successful in 32s
CI / security (push) Successful in 1m2s
CI / required (push) Successful in 1s
CI / build (pull_request) Successful in 25s
CI / images (pull_request) Successful in 1m22s
CI / benchmark (push) Successful in 1m19s
CI / build (push) Successful in 38s
CI / test (push) Successful in 2m27s
CI / validate (pull_request) Successful in 36s
CI / benchmark (pull_request) Successful in 1m47s
CI / test (pull_request) Successful in 1m55s
CI / required (pull_request) Successful in 3s
CI / images (push) Successful in 1m18s
CI / policy (pull_request) Successful in 18s
CI / policy (push) Successful in 13s
Record ADR 0011 for issue #319: the Bun server runs the planner over a
WebSocket carrying the existing worker protocol, with the browser engine
as a fallback. Mark ADR 0002 and ADR 0006's in-browser requirement as
superseded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 19:09:05 +01:00
nessarandClaude Opus 5.5 bc5ee50bd5 fix(planning): plan TIME_WINDOW rules on the picked calendar dates
CI / security (pull_request) Successful in 56s
CI / validate (push) Successful in 26s
CI / security (push) Successful in 55s
CI / required (push) Successful in 1s
CI / build (pull_request) Successful in 41s
CI / images (pull_request) Successful in 53s
CI / build (push) Successful in 30s
CI / benchmark (push) Successful in 1m17s
CI / test (push) Successful in 1m49s
CI / validate (pull_request) Successful in 46s
CI / benchmark (pull_request) Successful in 1m16s
CI / test (pull_request) Successful in 1m55s
CI / required (pull_request) Successful in 1s
CI / images (push) Successful in 1m13s
CI / policy (pull_request) Successful in 7s
CI / policy (push) Successful in 8s
Rule windows reached the planner as local-midnight Date objects, and the
planner read their Europe/Paris date, so east of Paris every window
started and ended one day early. Format them from local components as
YYYY-MM-DD before planning, as balances already are.

Closes #311

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:34:33 +02:00
nessarandClaude Opus 5.5 42134284e7 chore(deps): remove deprecated @angular/animations
CI / build (pull_request) Successful in 23s
CI / security (pull_request) Successful in 53s
CI / validate (push) Successful in 27s
CI / security (push) Successful in 58s
CI / required (push) Successful in 6s
CI / images (pull_request) Successful in 51s
CI / build (push) Successful in 32s
CI / benchmark (push) Successful in 1m22s
CI / test (push) Successful in 2m1s
CI / validate (pull_request) Successful in 33s
CI / benchmark (pull_request) Successful in 1m48s
CI / test (pull_request) Successful in 1m53s
CI / required (pull_request) Successful in 1s
CI / images (push) Successful in 1m12s
CI / policy (pull_request) Successful in 14s
CI / policy (push) Successful in 8s
Angular deprecated the package in favour of `animate.enter` and
`animate.leave`. Nothing in the app or in Angular Material imports it,
and `@angular/platform-browser` only lists it as an optional peer, so it
is dropped instead of migrated. Clears the Renovate dashboard warning in #56.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:09:18 +02:00
nessarandClaude Opus 5.5 f5d592ea5e chore(deps): automerge minor, patch, digest and pin Renovate updates
CI / security (pull_request) Successful in 58s
CI / validate (push) Successful in 27s
CI / security (push) Successful in 59s
CI / required (push) Successful in 1s
CI / build (pull_request) Successful in 31s
CI / images (pull_request) Successful in 1m13s
CI / build (push) Successful in 36s
CI / test (push) Successful in 1m57s
CI / validate (pull_request) Successful in 33s
CI / benchmark (pull_request) Successful in 1m17s
CI / test (pull_request) Successful in 1m54s
CI / required (pull_request) Successful in 1s
CI / benchmark (push) Successful in 1m23s
CI / images (push) Successful in 52s
CI / policy (pull_request) Successful in 13s
CI / policy (push) Successful in 7s
Renovate merges these updates with a merge commit once the required
check passes, three days after their release. Major updates stay manual.
The develop merge allowlist admits the renovate bot for this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:45:16 +02:00
renovate Bot 9e5c93e733 chore(deps): update dependency @types/jsdom to v30
CI / security (pull_request) Successful in 1m8s
CI / validate (push) Successful in 28s
CI / security (push) Successful in 1m2s
CI / required (push) Successful in 1s
CI / build (pull_request) Successful in 38s
CI / images (pull_request) Successful in 51s
CI / build (push) Successful in 40s
CI / benchmark (push) Successful in 1m16s
CI / test (push) Successful in 1m51s
CI / validate (pull_request) Successful in 24s
CI / benchmark (pull_request) Successful in 1m6s
CI / test (pull_request) Successful in 2m3s
CI / required (pull_request) Successful in 1s
CI / images (push) Successful in 51s
CI / policy (pull_request) Successful in 15s
CI / policy (push) Successful in 11s
2026-10-19 14:28:54 +02:00
nessarandClaude Opus 5.5 581c637029 ci: run push workflows only on develop, main and release tags
CI / build (pull_request) Successful in 25s
CI / security (pull_request) Successful in 1m5s
CI / validate (push) Successful in 28s
CI / security (push) Successful in 1m6s
CI / required (push) Successful in 1s
CI / images (pull_request) Successful in 1m21s
CI / build (push) Successful in 22s
CI / benchmark (push) Successful in 1m47s
CI / test (push) Successful in 2m7s
CI / validate (pull_request) Successful in 28s
CI / benchmark (pull_request) Successful in 1m30s
CI / test (pull_request) Successful in 2m31s
CI / required (pull_request) Successful in 1s
CI / images (push) Successful in 1m17s
CI / policy (pull_request) Successful in 8s
CI / policy (push) Successful in 11s
Every commit on a branch with an open PR ran the whole pipeline twice, once
for the push and once for the pull_request event, in separate concurrency
groups. Filter the push trigger to develop, main and v* tags so other
branches run CI and publish their images only through their PR. Tags are
listed explicitly because a branch filter alone stops tag pushes.

Update the trigger, benchmark and image prose in the README and the Gitea
Actions guide to match.

Refs #309

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:17:04 +02:00
nessarandClaude Opus 5.5 ff6c4d8122 fix(calendar): mark today and past days from the Europe/Paris date
CI / security (pull_request) Successful in 1m3s
CI / validate (push) Successful in 36s
CI / security (push) Successful in 1m8s
CI / required (push) Successful in 1s
CI / build (pull_request) Successful in 29s
CI / images (pull_request) Successful in 1m10s
CI / build (push) Successful in 34s
CI / test (push) Successful in 2m20s
CI / validate (pull_request) Successful in 31s
CI / test (pull_request) Successful in 2m9s
CI / required (pull_request) Successful in 1s
CI / benchmark (push) Successful in 1m39s
CI / images (push) Successful in 1m1s
CI / policy (pull_request) Successful in 8s
CI / benchmark (pull_request) Successful in 1m34s
CI / policy (push) Successful in 8s
The today marker and past styling used the device's local date while the
default planning horizon starts on the Paris date, so outside Paris time
near midnight the horizon's first day was not marked as today (CI in UTC
failed nightly). project() now takes an injectable now, derives today once
with planningDateInParis and returns it; calendar-month styles a day as
past when its date key is before that today.

Delete DateCacheService, monthsInAYearFromNow() and the default year of
getHolidays(), whose only remaining callers were their own specs.

Refs #301

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:06:52 +02:00
nessarandClaude Opus 5.5 d089c4670b docs(context): define today as the Europe/Paris calendar date
The today marker and past styling follow the same Paris date that
starts the default planning horizon (#301).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:06:52 +02:00
nessarandClaude Opus 5.5 c6af6d45ab feat(planning): warn of an overrun only past the displayed range
CI / security (pull_request) Successful in 55s
CI / validate (push) Successful in 31s
CI / security (push) Successful in 1m31s
CI / required (push) Successful in 3s
CI / build (pull_request) Successful in 34s
CI / images (pull_request) Successful in 53s
CI / build (push) Successful in 29s
CI / benchmark (push) Successful in 1m53s
CI / test (push) Successful in 2m12s
CI / validate (pull_request) Successful in 22s
CI / benchmark (pull_request) Successful in 1m9s
CI / test (pull_request) Successful in 1m45s
CI / required (pull_request) Successful in 2s
CI / images (push) Successful in 1m15s
CI / policy (pull_request) Successful in 7s
CI / policy (push) Successful in 12s
The expected wait sits near the middle of recent waits, so about half of
all runs pass it. Between the expected wait and the top of the range
shown before Calculate, the percentage now holds at 95% with no
remaining-time line; "Taking longer than expected" appears and is
announced only past that top.

Refs #300

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:45:28 +02:00
nessarandClaude Opus 5.5 58be749949 feat(planning): follow the indicative wait in calculation progress
The overlay percentage now rises linearly to 95% at the expected wait
captured at Calculate, holds there, and shows 100% only when the planner
completes. Beneath the status, one line names the current planning stage
(with the rule name for rule stages) and another shows the approximate
remaining time, or "Taking longer than expected" once the wait is
exceeded, announced once through the live status. Cancel freezes the
percentage and hides both lines.

PlanningCalculationService reports the stage and submitted request
instead of fixed per-stage percentages; PlanningDurationService owns the
wait progress on a 250 ms tick.

Closes #300

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:45:28 +02:00
nessarandClaude Opus 5.5 35a63d24c4 docs(context): define planning stage and indicative wait
Both terms are user-visible in the calculation overlay that #300
revises: the stage line names the planning stage, and the remaining
time comes from the indicative wait.

Refs #300.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:45:28 +02:00
nessarandClaude Opus 5.5 8414c02e10 chore: ignore Claude Code local files
CI / security (pull_request) Successful in 1m0s
CI / validate (push) Successful in 38s
CI / security (push) Successful in 56s
CI / required (push) Successful in 2s
CI / build (pull_request) Successful in 23s
CI / images (pull_request) Successful in 55s
CI / build (push) Successful in 36s
CI / benchmark (push) Successful in 1m16s
CI / test (push) Successful in 1m54s
CI / validate (pull_request) Successful in 27s
CI / benchmark (pull_request) Successful in 1m48s
CI / test (pull_request) Successful in 1m54s
CI / required (pull_request) Successful in 1s
CI / images (push) Successful in 52s
CI / policy (pull_request) Successful in 12s
CI / policy (push) Successful in 8s
.claude is a symlink to .agents/, so Claude Code's personal settings
and temporary worktrees land under .agents/. Ignore those paths while
keeping shared settings and skills trackable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:26:33 +02:00
nessar abfbca1d45 test(benchmark): calibrate again after the protocol and judge against the slower value
CI / validate (push) Successful in 33s
CI / security (push) Successful in 57s
CI / required (push) Successful in 2s
CI / build (push) Successful in 23s
CI / test (push) Successful in 1m49s
CI / benchmark (push) Successful in 1m49s
CI / images (push) Successful in 1m21s
CI / policy (push) Successful in 7s
See pull request #308
2026-10-19 10:24:14 +02:00
nessarandClaude Sonnet 5.5 b37101435a test(benchmark): calibrate again after the protocol and judge against the slower value
CI / validate (push) Successful in 30s
CI / security (push) Successful in 1m5s
CI / security (pull_request) Successful in 58s
CI / required (push) Successful in 1s
CI / build (push) Successful in 36s
CI / benchmark (push) Successful in 1m14s
CI / test (push) Successful in 1m54s
CI / build (pull_request) Successful in 23s
CI / images (pull_request) Successful in 1m16s
CI / validate (pull_request) Successful in 29s
CI / images (push) Successful in 56s
CI / benchmark (pull_request) Successful in 1m46s
CI / test (pull_request) Successful in 1m49s
CI / required (pull_request) Successful in 2s
CI / policy (push) Successful in 8s
CI / policy (pull_request) Successful in 8s
The relative gate calibrated once before the scenarios, so load that
started afterwards (the push and pull_request runs of one commit overlap
on the same runner, next to the test, build and image jobs) slowed the
scenarios but not the yardstick. A pull_request run failed `two years`
at 1653.1 ms against a 1648.7 ms budget this way.

The spec now repeats the calibration after the protocol and uses the
slower of the two values. The budgets can only loosen, never tighten,
and the log reprints the table with the budgets actually applied when
they change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-19 10:11:26 +02:00
nessar 7fc3457b63 perf(planning): plan from the best-ranked obligation solution and remove repeated work
CI / validate (push) Successful in 33s
CI / security (push) Successful in 56s
CI / required (push) Successful in 2s
CI / build (push) Successful in 36s
CI / benchmark (push) Successful in 1m10s
CI / test (push) Successful in 2m2s
CI / images (push) Successful in 53s
CI / policy (push) Successful in 7s
close #302

See pull request #303
2026-10-18 23:47:13 +02:00
nessarandClaude Opus 5.5 31cb4a499c fix(planning): recalibrate the duration estimate to the faster engine
CI / validate (push) Successful in 36s
CI / security (push) Successful in 1m10s
CI / build (pull_request) Successful in 23s
CI / security (pull_request) Successful in 1m0s
CI / required (push) Successful in 1s
CI / build (push) Successful in 23s
CI / benchmark (push) Successful in 1m29s
CI / test (push) Successful in 2m16s
CI / images (pull_request) Successful in 53s
CI / validate (pull_request) Successful in 25s
CI / benchmark (pull_request) Successful in 1m27s
CI / images (push) Successful in 59s
CI / test (pull_request) Successful in 2m6s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 20s
CI / policy (pull_request) Successful in 8s
Rendered waits after #302, in throttled headless Chromium, were well
below the shown ranges: two years waited 1.9 s against 3-24 s, three
years 4.5 s against 11-68 s, and the loaded year 4.0 s against 4-26 s.
The prior keeps its structure with refitted, rounded constants,
400 + 250 x (D/365.25)^0.5 x (P/30)^1.5 x R, which stays within about
1.2 times of all six measured configurations. Five years with 30 days
per year now shows 6-37 s instead of 44-265 s. Local refinement is
unchanged.

The 4x CPU throttle slows only the main thread, not the planning
worker, so phones can still wait longer than these desktop samples.

Part of #302.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 23:31:28 +02:00
nessarandClaude Opus 5.5 75320da685 docs(benchmark): compare engines by hand before each frozen-engine rebuild
A standing "no worse than the previous engine" check is not added to
CI: the differential check already fails on unintended changes, and a
fixed acceptance threshold would need renegotiating with every
deliberate change. Instead, the rebuild procedure now runs the
comparison while the frozen engine is still the previous one, and
records it with the change. The runner compares against the frozen
engine by default and takes `calibration` to reproduce the #302 record.

Part of #302.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 22:12:50 +02:00
nessarandClaude Opus 5.5 fe705fe618 fix(planning): keep counterfactual moves off the shared final plan
CI / validate (push) Successful in 46s
CI / security (push) Successful in 1m11s
CI / security (pull_request) Successful in 1m0s
CI / required (push) Successful in 1s
CI / build (push) Successful in 25s
CI / build (pull_request) Successful in 23s
CI / test (push) Successful in 2m27s
CI / images (pull_request) Successful in 54s
CI / validate (pull_request) Successful in 26s
CI / benchmark (push) Successful in 1m28s
CI / images (push) Successful in 1m0s
CI / test (pull_request) Successful in 2m6s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 28s
CI / policy (pull_request) Successful in 7s
CI / benchmark (pull_request) Successful in 1m33s
Since assigning a date shares unchanged activations with the parent
state, counterfactual analysis edited an activation it shared with the
final plan, so a later alternative date could inherit an earlier one's
dates and be judged eligible. It now replaces the moved activation.
Every counterfactual over seeds 280000-289999 matches the engine before
the sharing step again.

When every one of several obligation solutions fails earned-entitlement
chronology, the planner again reports the obligation conflict, as when
every preview failed. No seeded request reaches that path, so the
frozen engine is unchanged.

Also marks the ranking's known limit as a shortcut and fixes stale
documentation found in review.

Part of #302.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 21:49:55 +02:00
nessarandClaude Opus 5.5 676ea24410 test(benchmark): tighten the relative gate to the measured speed
After #302, the development machine's protocol takes about 41 seconds
instead of 232. The budget multipliers now add about 1.5 times headroom
to the new ratios (0.1 for typed obligations, which leaves room for
runner jitter), and the hang guard drops from 600 to 240 seconds, with
a 210-second test timeout: about three times the expected run on
srvhome, which is about 1.9 times slower than nessar-desktop.

Part of #286 and #302. The gate still needs a passing CI benchmark on
two runners.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 21:36:37 +02:00
nessarandClaude Opus 5.5 6c9ff4ae34 test(planning): rebuild the frozen engine from the obligation ranking
The frozen engine of the differential check is rebuilt from 8168137,
which plans from the best-ranked obligation solution, with the
documented build command. The check passes again, including its
cancelled asynchronous comparisons and generator-coverage assertions.
The calibration engine stays at a871f8f.

Part of #302.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 21:18:40 +02:00
nessarandClaude Opus 5.5 8168137cd5 perf(planning): plan from the best-ranked obligation solution
With several obligation solutions, the planner ran the whole preference
chain on candidate solutions as previews: every solution after a
complete enumeration, or the eight best-ranked after a truncated window
search. It now orders all solutions by the existing pre-preference
ranking (active objectives, then tie-breaks, of each obligation-only
plan; equal ranks keep enumeration order) and runs the preference
stages once, on the first. If that run ends with earned leave available
only after its final merged time-off period, the stages restart on the
next solution, so a request that planned before never becomes a
conflict.

The loaded year drops from 43 to 5.5 seconds and typed obligations from
3.3 to 0.1 seconds, with byte-identical benchmark plans. Over the 5,000
seeded requests, 23 plans become worse (9 on a real objective) and 1
better; over 50 loaded-year-sized requests, 4 become worse on a real
objective. ADR 0010 records the decision; docs/benchmark/issue-302.md
records the comparison and the opt-in runner that reproduces it.

The frozen-engine check fails until the frozen engine is rebuilt from
this commit in the next one.

Part of #302.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 21:18:06 +02:00
nessarandClaude Opus 5.5 aa6a0c6f1b perf(planning): copy only the debited balance when assigning a date
Assigning a date copied every balance and every earned activation.
Balances and activations are only edited right after a state copies
them, so the new state now shares them with its parent, except the
balance it debits. Placement copying is unchanged.

Part of #302.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 20:08:12 +02:00
nessarandClaude Opus 5.5 9d9404c3db perf(planning): validate each optimization configuration once
Every objective evaluation revalidated its optimization configuration.
Rule normalization already validates each configuration once per
calculation and keeps its own copy, the presets are constant, and the
summed variant of a valid configuration stays valid, so the core now
scores them without revalidating. evaluateOptimization still validates
for other callers.

Part of #302.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 20:03:22 +02:00
nessarandClaude Opus 5.5 b7ec411c92 perf(planning): yield between asynchronous slices without a timer
Each slice of the asynchronous adapter waited for a zero-delay timer:
about 1.1 ms in Bun, and at least 4 ms in browsers once timers nest.
Browsers now yield through a message-channel task. Bun runs port
messages ahead of timers and incoming worker messages, which starved
cancellation and heartbeats, so it yields with setImmediate. Both still
let queued cancellation and heartbeat tasks run between slices.

Part of #302.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 19:58:40 +02:00
nessarandClaude Opus 5.5 2fcba758c8 perf(planning): retain the best valid plan more cheaply
Retaining a better valid plan reconciled its optimization provenance,
which evaluated every active objective once per credited placement with
that placement released. Only the credited objectives are compared, so
the released plan now evaluates just those and skips observing the
others. Retention also stops computing quality metrics that nothing
read. The retained plan and what Cancel returns are unchanged.

Part of #302.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 19:50:58 +02:00
nessarandClaude Opus 5.5 0b0bb8f9a8 perf(planning): reuse the donor ranking across public-holiday weeks
The holiday-week stage ranked every placement as a donor once per
public-holiday week, although the ranking depends only on the plan. The
weeks of one plan now share each placement's released objectives; each
week still skips its own dates and walks the placements in the same
order with the same yields.

Part of #302.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 19:45:21 +02:00
nessarandClaude Opus 5.5 b356117263 test(benchmark): keep the a871f8f engine as a fixed calibration engine
The differential check's frozen bundle will be rebuilt for #302; the
relative gate keeps timing the unchanged a871f8f bundle so its ratios
stay comparable with the recorded history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 19:14:28 +02:00
nessar ba05fe88b3 chore(deps): update node.js to v24.22.0
CI / validate (push) Successful in 2m4s
CI / security (push) Successful in 1m33s
CI / required (push) Successful in 1s
CI / build (push) Successful in 34s
CI / benchmark (push) Successful in 4m34s
CI / test (push) Successful in 4m49s
CI / images (push) Successful in 2m19s
CI / policy (push) Successful in 10s
2026-10-18 13:32:24 +02:00
nessarandClaude Opus 5.5 cc3664454a docs(ci): note the Node 24.22.0 job containers
CI / validate (push) Successful in 32s
CI / security (push) Successful in 57s
CI / security (pull_request) Successful in 1m37s
CI / required (push) Successful in 1s
CI / test (push) Successful in 3m29s
CI / build (push) Successful in 2m57s
CI / benchmark (push) Successful in 5m4s
CI / build (pull_request) Successful in 4m55s
CI / images (pull_request) Successful in 1m23s
CI / test (pull_request) Successful in 3m26s
CI / validate (pull_request) Successful in 7m13s
CI / images (push) Successful in 1m8s
CI / benchmark (pull_request) Successful in 7m33s
CI / required (pull_request) Successful in 2s
CI / policy (push) Successful in 8s
CI / policy (pull_request) Successful in 9s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:15:53 +02:00
renovate Bot c70339972a chore(deps): update node.js to v24.22.0 2026-10-18 13:15:53 +02:00
nessar 711c9e00c3 chore(deps): update https://gitea.com/actions/checkout action to v7
CI / security (push) Successful in 1m46s
CI / validate (push) Successful in 4m19s
CI / required (push) Successful in 5s
CI / build (push) Successful in 35s
CI / test (push) Successful in 3m44s
CI / benchmark (push) Successful in 5m15s
CI / images (push) Successful in 1m25s
CI / policy (push) Successful in 8s
2026-10-18 13:15:21 +02:00
renovate Bot f56b66e10c chore(deps): update https://gitea.com/actions/checkout action to v7
CI / security (push) Successful in 1m44s
CI / validate (push) Successful in 2m25s
CI / security (pull_request) Successful in 1m4s
CI / required (push) Successful in 2s
CI / build (push) Successful in 34s
CI / test (push) Successful in 5m14s
CI / build (pull_request) Successful in 24s
CI / images (pull_request) Successful in 1m18s
CI / validate (pull_request) Successful in 55s
CI / benchmark (push) Successful in 5m43s
CI / test (pull_request) Successful in 3m30s
CI / images (push) Successful in 2m22s
CI / benchmark (pull_request) Successful in 5m56s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 9s
CI / policy (pull_request) Successful in 10s
2026-10-18 13:03:56 +02:00
nessar 5ee95fe9ca chore(deps): update https://gitea.com/actions/upload-artifact action to v7
CI / validate (push) Successful in 34s
CI / security (push) Successful in 55s
CI / required (push) Failing after 2s
CI / build (push) Successful in 3m22s
CI / test (push) Failing after 4m57s
CI / benchmark (push) Successful in 8m0s
CI / images (push) Skipped
CI / policy (push) Successful in 16s
2026-10-18 00:07:18 +02:00
renovate Bot 389f6eb7e2 chore(deps): update https://gitea.com/actions/upload-artifact action to v7
CI / validate (push) Successful in 23s
CI / security (push) Successful in 1m48s
CI / build (pull_request) Successful in 51s
CI / security (pull_request) Successful in 1m51s
CI / required (push) Successful in 2s
CI / test (push) Successful in 4m39s
CI / benchmark (push) Successful in 7m10s
CI / build (push) Successful in 10m40s
CI / images (pull_request) Successful in 2m29s
CI / validate (pull_request) Successful in 35s
CI / test (pull_request) Successful in 3m30s
CI / benchmark (pull_request) Successful in 5m4s
CI / images (push) Successful in 1m15s
CI / required (pull_request) Successful in 2s
CI / policy (push) Successful in 8s
CI / policy (pull_request) Successful in 11s
2026-10-17 23:45:07 +02:00
nessar 880efe4e90 chore(deps): update angular-cli monorepo to v22.2.3
CI / validate (push) Successful in 36s
CI / security (push) Successful in 55s
CI / required (push) Successful in 3s
CI / build (push) Successful in 6m46s
CI / benchmark (push) Successful in 7m56s
CI / test (push) Successful in 12m52s
CI / images (push) Successful in 2m4s
CI / policy (push) Successful in 17s
2026-10-17 23:44:49 +02:00
nessarandClaude Opus 5.5 c59d75e526 chore(deps): update angular-cli monorepo to v22.2.3
CI / validate (push) Successful in 49s
CI / security (push) Successful in 1m0s
CI / security (pull_request) Successful in 1m4s
CI / required (push) Successful in 3s
CI / test (push) Successful in 3m7s
CI / build (push) Successful in 4m45s
CI / build (pull_request) Successful in 1m6s
CI / benchmark (push) Successful in 7m57s
CI / images (pull_request) Successful in 2m8s
CI / validate (pull_request) Successful in 1m56s
CI / test (pull_request) Successful in 5m23s
CI / images (push) Successful in 1m17s
CI / benchmark (pull_request) Successful in 5m30s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 10s
CI / policy (pull_request) Successful in 8s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 23:31:52 +02:00
nessar b086f1ffc8 fix(deps): update angular monorepo to v22.2.3
CI / validate (push) Successful in 1m17s
CI / security (push) Successful in 1m48s
CI / required (push) Successful in 2s
CI / build (push) Successful in 33s
CI / test (push) Successful in 3m12s
CI / benchmark (push) Successful in 5m54s
CI / images (push) Successful in 1m39s
CI / policy (push) Successful in 13s
2026-10-17 23:27:45 +02:00
renovate Bot 813d9b4d7f fix(deps): update angular monorepo to v22.2.3
CI / validate (push) Successful in 37s
CI / security (push) Successful in 1m38s
CI / security (pull_request) Successful in 1m5s
CI / required (push) Successful in 2s
CI / build (push) Successful in 35s
CI / test (push) Successful in 3m53s
CI / benchmark (push) Successful in 5m15s
CI / build (pull_request) Successful in 5m47s
CI / images (pull_request) Successful in 1m17s
CI / validate (pull_request) Successful in 37s
CI / test (pull_request) Successful in 5m5s
CI / images (push) Successful in 1m59s
CI / benchmark (pull_request) Successful in 7m58s
CI / required (pull_request) Successful in 2s
CI / policy (push) Successful in 13s
CI / policy (pull_request) Successful in 7s
2026-10-17 23:07:08 +02:00
nessar 9158966982 chore(deps): update docker docker tag to v29.9.1
CI / validate (push) Successful in 1m58s
CI / security (push) Successful in 1m3s
CI / required (push) Successful in 3s
CI / build (push) Successful in 2m31s
CI / benchmark (push) Successful in 5m5s
CI / test (push) Successful in 8m8s
CI / images (push) Successful in 1m0s
CI / policy (push) Successful in 11s
2026-10-17 23:05:22 +02:00
nessarandClaude Opus 5.5 d9c7f72461 docs(ci): note the Docker 29.9.1 image
CI / security (push) Successful in 1m44s
CI / security (pull_request) Successful in 1m1s
CI / validate (push) Successful in 11m34s
CI / required (push) Successful in 5s
CI / build (push) Successful in 40s
CI / test (push) Successful in 3m6s
CI / build (pull_request) Successful in 1m33s
CI / images (pull_request) Successful in 2m42s
CI / validate (pull_request) Successful in 39s
CI / test (pull_request) Successful in 5m18s
CI / benchmark (push) Successful in 9m44s
CI / benchmark (pull_request) Successful in 7m56s
CI / required (pull_request) Successful in 1s
CI / images (push) Successful in 1m25s
CI / policy (push) Successful in 8s
CI / policy (pull_request) Successful in 10s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 21:24:11 +02:00
renovate Bot 1636355920 chore(deps): update docker docker tag to v29.9.1 2026-10-17 21:23:53 +02:00
nessar 85fc4561fd build: run the project on Bun 1.4.3
CI / validate (push) Successful in 38s
CI / security (push) Successful in 1m42s
CI / required (push) Successful in 1s
CI / build (push) Successful in 24s
CI / test (push) Successful in 2m48s
CI / benchmark (push) Successful in 4m48s
CI / images (push) Successful in 58s
CI / policy (push) Successful in 19s
close #289, close #291, close #292

See pull request #299
2026-10-17 18:28:42 +02:00
nessarandClaude Opus 5.5 282d9c6787 fix: report line-only coverage honestly and tighten Bun test helpers
CI / validate (push) Successful in 41s
CI / security (push) Successful in 1m3s
CI / build (pull_request) Successful in 23s
CI / security (pull_request) Successful in 57s
CI / required (push) Successful in 3s
CI / build (push) Successful in 36s
CI / test (push) Successful in 3m3s
CI / benchmark (push) Successful in 5m19s
CI / images (pull_request) Successful in 54s
CI / validate (pull_request) Successful in 32s
CI / test (pull_request) Successful in 3m25s
CI / benchmark (pull_request) Successful in 4m48s
CI / images (push) Successful in 1m20s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 7s
CI / policy (pull_request) Successful in 10s
The generated HTML and Cobertura reports no longer show unmeasured
branch and function coverage as 100%. Poll and waitFor deadlines use
performance.now so frozen dates cannot make them loop forever, the
malformed-configuration test covers undefined again next to the empty
array, compose health checks honor PORT, and the migration spec lists
only what is still open.

Refs #291, #292, #293

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 16:10:29 +02:00
nessarandClaude Opus 5.5 dfe6d28d2b test(planning): make the checkpoint cancellation test deterministic
The cancelled stage takes about a millisecond, so under load the worker
could finish it before the cancel message arrived and report it as
completed. The real-worker harness now holds the worker after reporting
that stage until the cancel is delivered, keeping every assertion.

Refs #291

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 15:57:33 +02:00
nessarandClaude Opus 5.5 ac69a41fc8 ci: run development, quality checks and CI on Bun 1.4.3
Pin Bun 1.4.3 with packageManager, and force every bun run script onto
the Bun runtime through bunfig so ng, ESLint and Prettier never fall
back to an installed Node. Type checking uses bun check for the
application and test projects, next to the Angular build.

CI jobs install the pinned release from a checksum-verified download
instead of npm and run project steps in a shell without Node on PATH,
which stays available only for the checkout and upload actions. The
image test's fake docker runs on Bun.

Refs #290, #293

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 14:25:46 +02:00
nessarandClaude Opus 5.5 f74d744f9b feat(server): serve the client-only build with Bun
Angular's server build needs Node loader hooks that Bun does not apply,
and every route is client-rendered, so Angular now builds a client-only
bundle and a small Bun.serve server delivers it: hashed assets with the
one-year cache, index.html revalidated, extension-less routes falling
back to index.html, missing assets 404, traversal and malformed paths
rejected, and other methods 405. Express, @angular/ssr and the unused
hydration provider are removed. Both Docker stages use the pinned
oven/bun:1.4.3-alpine image without Node, and the health checks use
Bun's fetch.

Refs #292

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 13:50:05 +02:00
nessarandClaude Opus 5.5 94d57add2c test: run the suite and benchmark with Bun's native test runner
Replace Vitest with bun test across the whole suite. A preload compiles
components through Angular's JIT transform with inlined templates, sets
up jsdom, TestBed and zoneless change detection, and a small shim covers
the Vitest APIs bun:test lacks. Files run isolated, real-worker specs
spawn the running Bun, and line coverage from lcov is converted to the
existing HTML and Cobertura reports. The CI benchmark replaces its heap
cap with a container memory limit. Vitest, Jest, Nx and their Vite
configuration are removed.

Refs #291

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 13:40:42 +02:00
nessarandClaude Opus 5.5 558c70aa24 docs(adr): record Bun 1.4.3 verification results and decisions
Stable Bun 1.4.3 runs installs, the development server, standalone type
checks, the native test runner and a Bun.serve static server. Native
lint/fmt are canary-only, and Angular's server build needs Node loader
hooks Bun does not apply, so the spec now keeps ESLint/Prettier until a
stable release, builds Angular client-only behind a Bun static server,
converts line coverage from lcov, and replaces the heap cap with a
container memory limit.

Refs #289

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 12:49:17 +02:00
nessarandClaude Opus 5.5 c949480e49 docs(adr): propose Bun runtime and native tooling
Record the proposed decision to run project-owned JavaScript under Bun
with its native test runner, linter, formatter, type checker and HTTP
server, keeping Angular's standard build pipeline, plus the development
spec for the migration tickets.

Refs #289

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 12:01:42 +02:00
nessar 752c8b7a99 refactor(planning): consolidate calculation, projection and worker ownership
CI / validate (push) Successful in 57s
CI / security (push) Successful in 1m1s
CI / required (push) Successful in 1s
CI / build (push) Successful in 57s
CI / test (push) Successful in 3m12s
CI / benchmark (push) Successful in 7m13s
CI / images (push) Successful in 1m10s
CI / policy (push) Successful in 11s
close #274, close #275, close #276, close #277

See pull request #298
2026-10-17 11:53:19 +02:00
nessarandClaude Opus 5.5 cee67ce3df refactor(calendar): drop the unused projection horizon
CI / validate (push) Successful in 1m2s
CI / security (push) Successful in 1m12s
CI / security (pull_request) Successful in 1m3s
CI / required (push) Successful in 3s
CI / build (push) Successful in 1m27s
CI / benchmark (push) Successful in 4m10s
CI / test (push) Successful in 4m19s
CI / build (pull_request) Successful in 34s
CI / images (pull_request) Successful in 1m56s
CI / validate (pull_request) Successful in 1m21s
CI / test (pull_request) Successful in 3m23s
CI / images (push) Successful in 1m34s
CI / benchmark (pull_request) Successful in 7m13s
CI / required (pull_request) Successful in 2s
CI / policy (push) Successful in 7s
CI / policy (pull_request) Successful in 11s
No caller read CalendarProjection.horizon, and with fixed months it no
longer described the listed months.

Refs #276

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 11:36:19 +02:00
nessarandClaude Opus 5.5 a472347a5e fix(calendar): keep declaration-entry months fixed while editing
Declaring a date at the edge of the planning period widened the
projection and inserted a disabled month above the grid. Declaration
entry now lists only the planning period's months, while selections
keep the connected-period widening.

Refs #276

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 11:29:31 +02:00
nessarandClaude Opus 5.5 feb651148e fix(planning): react only to calculations started by the mounted calendar
Re-mounting the calendar no longer records a duration sample or
announces the previous result, explanation or rejected explanation.
Starting a calculation during a cancellation announces loading and
keeps focus where it is. Only rejected explanation deliveries are
announced, as before. Replacement tests now replace a real plan.

Refs #275, #274

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 11:22:38 +02:00
nessarandClaude Opus 5.5 43677ff434 refactor(planning): drop the unreachable late worker message guard
release() already clears the worker handlers, so the released checks
inside them could never run. The lifetime test now states what it
checks: no handler is left for late messages.

Refs #277

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 11:22:38 +02:00
nessarandClaude Opus 5.5 502d561f6f refactor(calendar): encapsulate calendar projection and selection ranges
CalendarService.project returns the covered months together with the
projected selections, so month enumeration and selected-day rendering
share one projection horizon. SelectedDates is built once from the
complete range list and groups connected periods internally, exposing
read-only selection, boundary and day-type queries.

In declaration entry, months reached by adjacent declared or
non-working days are now shown, matching the projected selections.

Refs #276

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 11:18:33 +02:00
nessarandClaude Opus 5.5 5cb0b93339 refactor(planning): give planning calculations one state owner
PlanningCalculationService now builds the submitted request, owns the
pending and accepted calculation state, and delivers explanations for
the accepted calculation only. The duration estimator reads the same
request. The calendar and leave-balance summary consume the accepted
outcome instead of coordinating writable state on the input service.

Refs #275

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 11:11:37 +02:00
nessarandClaude Opus 5.5 b69b3c3690 refactor(planning): give planning workers one lifetime owner
Planning, counterfactual analysis and checkpoint explanation now share
one internal worker-job owner for creation, handler cleanup,
termination and supersession, and one request/response message
contract between the coordinator and the worker. Job-specific progress,
checkpoint recovery and completion rules stay explicit.

Refs #277

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 11:11:37 +02:00
nessarandClaude Opus 5.5 7fc2b33587 refactor(planning): remove the unused remaining-balance mirror
The summary and details already read the displayed plan's remaining
balances, so the writable mirror, its legacy conversion and the VacDay
classification/reason fields it alone populated are removed.

Refs #274

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 11:05:51 +02:00
nessar 40a11c245a perf(planning): incremental exact scoring for the loaded year
CI / validate (push) Successful in 57s
CI / security (push) Successful in 54s
CI / required (push) Successful in 1s
CI / build (push) Successful in 1m1s
CI / test (push) Successful in 3m9s
CI / benchmark (push) Successful in 7m25s
CI / images (push) Successful in 1m10s
CI / policy (push) Successful in 6s
close #280

See pull request #287
2026-10-17 02:18:27 +02:00
nessarandClaude Opus 5.5 3bbe989eca test(benchmark): print a readable summary table
CI / validate (push) Successful in 1m5s
CI / security (push) Successful in 1m19s
CI / security (pull_request) Successful in 56s
CI / build (pull_request) Successful in 1m42s
CI / required (push) Successful in 1s
CI / build (push) Successful in 1m38s
CI / test (push) Successful in 3m29s
CI / benchmark (push) Successful in 4m13s
CI / images (pull_request) Successful in 1m11s
CI / validate (pull_request) Successful in 1m42s
CI / test (pull_request) Successful in 3m8s
CI / images (push) Successful in 1m15s
CI / benchmark (pull_request) Successful in 3m37s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 7s
CI / policy (pull_request) Successful in 10s
Print the calibration and a Markdown table with one aligned row per
scenario as soon as it finishes: both planning times, mean, budget, ratio,
multiplier, outcome, placements, determinism and budget status. Write
directly to stdout so Vitest adds no per-line headers. The complete TSV
report still follows the table.

Refs #281, #285

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 02:09:54 +02:00
nessarandClaude Opus 5.5 cfdb28c90a ci(benchmark): size the hang guard for the slowest runner
CI / validate (push) Successful in 53s
CI / security (push) Successful in 1m12s
CI / security (pull_request) Successful in 1m5s
CI / required (push) Successful in 1s
CI / build (push) Successful in 1m18s
CI / test (push) Successful in 4m6s
CI / build (pull_request) Successful in 36s
CI / images (pull_request) Successful in 1m50s
CI / validate (pull_request) Successful in 1m18s
CI / benchmark (push) Successful in 3m56s
CI / test (pull_request) Successful in 3m2s
CI / images (push) Successful in 1m15s
CI / benchmark (pull_request) Successful in 7m18s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 6s
CI / policy (pull_request) Successful in 9s
The first PR run landed on srvhome, about 1.9 times slower than
nessar-desktop. The fixed 300-second timeout killed its protocol during the
loaded year, although every completed scenario was within its relative
budget. Raise the CI timeout to 600 seconds and the test timeout to 570
seconds so they only guard against hangs, and record the first CI-runner
ratios.

Refs #285

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 01:40:41 +02:00
nessarandClaude Opus 5.5 63b50c4311 docs(benchmark): record the remaining gap to the speed target
CI / validate (push) Successful in 1m1s
CI / security (push) Successful in 1m16s
CI / security (pull_request) Successful in 1m11s
CI / required (push) Successful in 1s
CI / build (push) Successful in 1m27s
CI / benchmark (push) Successful in 4m31s
CI / test (push) Successful in 4m36s
CI / build (pull_request) Successful in 39s
CI / images (pull_request) Skipped
CI / validate (pull_request) Successful in 1m34s
CI / test (pull_request) Successful in 3m24s
CI / images (push) Successful in 1m16s
CI / benchmark (pull_request) Failing after 6m0s
CI / required (pull_request) Failing after 2s
CI / policy (push) Successful in 6s
CI / policy (pull_request) Successful in 9s
The exact optimizations bring the loaded year from 66.0 s to 44.1 s, but the
target of 10 s for the loaded year and 3 s for the other scenarios is not
reached for the loaded year, typed obligations and three years. Record the
gap and the remaining profile, keep the relative-gate multipliers and the
300-second hang guard unchanged, and note that ADR 0003's five-second target
should be revisited together with a decision on search changes.

Refs #286

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:45:28 +02:00
nessarandClaude Opus 5.5 acdb19352a ci(benchmark): gate scenario speed relative to the runner
Before the protocol, time the frozen engine on the two-year scenario, best
of three, and fail any scenario whose mean planning time exceeds its
multiplier times that calibration. Multipliers come from development-machine
ratios with about 1.5x headroom until #286 tightens them. The 300-second
timeout stays only as a hang guard. The benchmark keeps running on push and
pull_request events because the push run gates image publication.

This replaces the absolute 300-second acceptance protocol named in #78.

Refs #285

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:45:28 +02:00
nessarandClaude Opus 5.5 68a9e33de6 perf(planning): prune candidates that cannot beat the protected prefix
Finalizing a candidate never moves or retypes a placement, so preference
results and calendar optimizations already have their final values before
it, and leave-balance optimizations do too when nothing can be earned.
Reject a candidate before finalizing when the first differing such
objective of the protected prefix is worse than the baseline. Leave-placement
objectives and earning contexts stop the walk.

The frozen-engine check now also compares cancelled asynchronous runs,
including checkpoints and retained incumbents. The loaded year drops from
48.5 s to 44.3 s; outcomes, explanations and final states are unchanged.

Refs #284

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:45:28 +02:00
nessarandClaude Opus 5.5 7890a03a74 perf(planning): update plan observations incrementally
Cache an immutable occupancy per placements map and derive a candidate's
time-off period groups, holiday-week completeness and placement tie key
from its parent when one date is added or removed. The from-scratch
computation stays as the test oracle and an opt-in shadow mode. A
fast-check property test compares both after every operation.

The loaded year drops from 66.5 s to 48.5 s and the protocol from 262.0 s
to 193.7 s. Outcomes, explanations and final states stay identical.

Refs #283

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:45:28 +02:00
nessarandClaude Opus 5.5 87d72064be refactor(planning): consolidate plan observations in one module
Move time-off periods, work sequences, public-holiday weeks, balance
observations, the placement list and both tie keys into
plan-observations.ts. The code moves without behavior changes; all seven
benchmark scenarios produce byte-identical outcomes, explanations and final
states, and the frozen-engine check passes. Benchmark timings stay within
noise.

Refs #282

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 23:47:34 +02:00
nessarandClaude Opus 5.5 24c35542a8 test(benchmark): report each scenario as it finishes
Print the report header before the measured runs and each scenario's rows
as soon as its repetitions complete, so a timed-out job still shows the
finished scenarios. The final report, scenarios, warm-ups, repetitions,
assertions, heap limit and timeout are unchanged.

Refs #281

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 23:36:11 +02:00
nessarandClaude Opus 5.5 4d26e65672 test(planning): compare the engine against a frozen engine on random requests
Bundle the planning core at a871f8f (develop after PR #278) as a frozen
fixture and compare it with the current engine on 5,000 seeded random
requests. Outcomes, stable explanations, explanation errors and final-state
snapshots must be strictly deep-equal. Requests cover obligations,
preferences, IF_THEN and TIME_WINDOW rules, earned entitlements, composed
optimization rules, declared days, year boundaries and public holidays.

Refs #280

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 23:30:30 +02:00
nessar a871f8f28c add a skill
CI / validate (push) Successful in 1m3s
CI / security (push) Successful in 57s
CI / required (push) Failing after 1s
CI / build (push) Successful in 1m21s
CI / test (push) Successful in 2m22s
CI / benchmark (push) Successful in 5m10s
CI / images (push) Skipped
CI / policy (push) Failing after 9s
2026-10-16 22:47:08 +02:00
nessar a371e03462 perf(planning): restore the integrated benchmark gate
CI / validate (push) Successful in 1m17s
CI / security (push) Successful in 1m4s
CI / required (push) Failing after 2s
CI / build (push) Successful in 1m23s
CI / test (push) Successful in 2m30s
CI / benchmark (push) Failing after 5m55s
CI / images (push) Skipped
CI / policy (push) Successful in 18s
See pull request #278
2026-10-16 22:36:31 +02:00
nessarandClaude Opus 5.5 1711bc570c docs(benchmark): record PR #278 benchmark headroom
CI / validate (push) Successful in 1m13s
CI / security (push) Successful in 1m43s
CI / build (pull_request) Successful in 1m29s
CI / security (pull_request) Successful in 1m42s
CI / required (push) Failing after 2s
CI / build (push) Successful in 1m0s
CI / test (push) Successful in 3m21s
CI / benchmark (push) Failing after 5m50s
CI / images (pull_request) Successful in 1m54s
CI / validate (pull_request) Successful in 54s
CI / test (pull_request) Successful in 2m19s
CI / images (push) Skipped
CI / benchmark (pull_request) Successful in 4m58s
CI / required (pull_request) Successful in 4s
CI / policy (push) Successful in 8s
CI / policy (pull_request) Successful in 7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 22:24:22 +02:00
nessarandClaude Opus 5.5 c6610cd633 perf(planning): reject impossible mandatory moves before copying
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 22:04:28 +02:00
nessar 433a8b0ade perf(planning): reuse immutable non-working date counts 2026-10-16 21:19:58 +02:00
nessar c7e7abcd24 perf(planning): build placement date keys directly 2026-10-16 21:03:36 +02:00
nessar cbde23f572 perf(planning): restore the integrated benchmark gate
CI / validate (push) Successful in 1m23s
CI / security (push) Successful in 1m39s
CI / security (pull_request) Successful in 1m40s
CI / required (push) Failing after 2s
CI / test (push) Successful in 3m17s
CI / benchmark (push) Failing after 5m52s
CI / build (push) Successful in 1m31s
CI / build (pull_request) Successful in 1m30s
CI / images (pull_request) Skipped
CI / images (push) Skipped
CI / validate (pull_request) Successful in 1m11s
CI / test (pull_request) Successful in 3m17s
CI / benchmark (pull_request) Failing after 5m57s
CI / required (pull_request) Failing after 1s
CI / policy (push) Successful in 7s
CI / policy (pull_request) Successful in 7s
Reduce objective evaluation and calendar allocation work while preserving planner outcomes and deterministic explanations. Restore required benchmark gating and record the unchanged protocol, differential checks, and browser evidence for #78.
2026-10-16 14:01:32 +02:00
nessar 0852cd4444 test(planning): verify integrated planning after trace removal
CI / validate (push) Successful in 1m14s
CI / security (push) Successful in 1m45s
CI / required (push) Successful in 4s
CI / test (push) Successful in 3m21s
CI / benchmark (push) Failing after 5m53s
CI / build (push) Successful in 1m21s
CI / images (push) Successful in 1m53s
CI / policy (push) Successful in 7s
close #77

See pull request #273
2026-10-16 13:57:53 +02:00
nessar 26a8b076ba ci: use reachable Trivy database mirror
CI / validate (push) Successful in 1m11s
CI / security (push) Successful in 3m29s
CI / build (pull_request) Successful in 1m26s
CI / security (pull_request) Successful in 5m57s
CI / required (push) Successful in 4s
CI / test (push) Successful in 3m20s
CI / benchmark (push) Failing after 5m57s
CI / build (push) Successful in 1m20s
CI / images (pull_request) Successful in 3m25s
CI / validate (pull_request) Successful in 1m13s
CI / test (pull_request) Successful in 3m23s
CI / benchmark (pull_request) Failing after 6m10s
CI / images (push) Successful in 2m46s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 7s
CI / policy (pull_request) Successful in 7s
2026-10-15 23:23:22 +02:00
nessar 56577d23b5 test(planning): verify integrated planning after trace removal
CI / validate (push) Successful in 44s
CI / security (pull_request) Failing after 12m15s
CI / build (pull_request) Failing after 14m33s
CI / security (push) Failing after 19m29s
CI / required (push) Failing after 1s
CI / build (push) Successful in 40s
CI / test (push) Successful in 1m52s
CI / benchmark (push) Failing after 5m29s
CI / images (pull_request) Skipped
CI / validate (pull_request) Successful in 1m19s
CI / test (pull_request) Successful in 3m22s
CI / benchmark (pull_request) Failing after 17m21s
CI / images (push) Skipped
CI / required (pull_request) Failing after 1s
CI / policy (push) Successful in 6s
CI / policy (pull_request) Successful in 7s
2026-10-15 21:45:58 +02:00
nessar 2f4af14869 refactor(planning): remove the original decision trace
CI / validate (push) Successful in 48s
CI / security (push) Successful in 6m54s
CI / required (push) Successful in 1s
CI / build (push) Successful in 45s
CI / test (push) Successful in 2m10s
CI / benchmark (push) Failing after 5m49s
CI / images (push) Successful in 3m7s
CI / policy (push) Successful in 21s
close #76

See pull request #272
2026-10-15 21:26:36 +02:00
nessar d9d9befa12 refactor(planning): remove the original decision trace
CI / validate (push) Successful in 1m15s
CI / security (push) Successful in 7m6s
CI / required (push) Successful in 2s
CI / security (pull_request) Successful in 6m37s
CI / test (push) Successful in 3m18s
CI / build (push) Successful in 1m23s
CI / build (pull_request) Successful in 43s
CI / images (pull_request) Successful in 3m18s
CI / benchmark (push) Failing after 5m53s
CI / validate (pull_request) Successful in 1m9s
CI / test (pull_request) Successful in 3m19s
CI / images (push) Successful in 3m7s
CI / benchmark (pull_request) Failing after 5m28s
CI / required (pull_request) Successful in 1s
CI / policy (push) Successful in 7s
CI / policy (pull_request) Successful in 7s
2026-10-15 20:42:33 +02:00
nessar ea4256107f Merge pull request 'ci: migrate to Gitea Actions' (#271) from feature/gitea-actions into develop
CI / validate (push) Successful in 1m18s
CI / security (push) Successful in 6m51s
CI / required (push) Failing after 1s
CI / test (push) Successful in 3m42s
CI / build (push) Successful in 1m16s
CI / benchmark (push) Failing after 5m59s
CI / images (push) Skipped
CI / policy (push) Failing after 8s
Reviewed-on: #271
2026-10-15 19:55:10 +02:00
nessar d74dfb9938 ci: migrate to Gitea Actions
CI / validate (push) Successful in 1m25s
CI / security (push) Successful in 1m31s
CI / required (push) Failing after 1s
CI / security (pull_request) Successful in 1m27s
CI / test (push) Successful in 3m43s
CI / build (push) Successful in 1m20s
CI / build (pull_request) Successful in 1m5s
CI / images (pull_request) Successful in 2m24s
CI / benchmark (push) Failing after 5m52s
CI / images (push) Failing after 1m2s
CI / validate (pull_request) Successful in 1m6s
CI / test (pull_request) Successful in 3m30s
CI / benchmark (pull_request) Canceled after 3s
CI / required (pull_request) Successful in 5s
CI / policy (push) Successful in 48s
CI / policy (pull_request) Successful in 9s
2026-10-13 19:43:08 +02:00
nessar 7d60157863 docs: migrate repository guidance to Gitea 2026-10-13 19:38:32 +02:00
nessar 0d900fd72d feat(planning): make optimization rules composable
Closes #70, #71, #72, #73, and #74

See merge request nessar/vac-optimizer!189
2026-10-10 14:56:48 +00:00
nessar ae68e31575 docs: describe the advisory planning benchmark 2026-10-10 16:42:04 +02:00
nessar 98e87fecee ci: make the deferred planning benchmark non-blocking
Run the unchanged benchmark as a separate advisory job while #78 is open.
Keep functional coverage and other checks required, and retain the 2 GB heap
and 300-second protocol limit. Record #78's obligation to restore the gate.

Refs: #75, #78
2026-10-10 16:36:11 +02:00
nessar 6811142299 feat(planning): make optimization rules composable
Evaluate explicit, ordered optimization configurations through one shared
planner model. Add six editable presets, durable one-time legacy migration,
and consistent completed and cancelled plan provenance.

Include functional regressions and the agreed trace-removal and benchmark
follow-up specs. Performance acceptance remains in #78 under unchanged gates.

Refs: #70, #71, #72, #73, #74, #75, #76, #77, #78
2026-10-10 16:07:34 +02:00
nessar 209bf05f36 feat(docs): add detailed planning objectives and optimization rules documentation 2026-10-08 23:20:40 +02:00
nessar 0c266a4b9d fix(deps): update angular-cli monorepo to v22.2.2
See merge request nessar/vac-optimizer!185
2026-10-08 19:08:11 +00:00
nessar f786872a18 feat(ui): configure planning horizon alongside leave balances
See merge request nessar/vac-optimizer!183
2026-10-08 19:07:27 +00:00
nessar ad5ef69f5f docs: document GitFlow rules for agents
See merge request nessar/vac-optimizer!186
2026-10-08 08:10:35 +00:00
nessar 749348ec0d docs: document GitFlow rules for agents 2026-10-08 08:56:00 +02:00
nessar 6777cbc282 feat(ui): use Material datepickers for planning horizon 2026-10-08 06:49:06 +00:00
nessar 31d4333783 feat(ui): configure planning horizon alongside leave balances 2026-10-08 06:49:06 +00:00
renovate Bot db561a31e6 fix(deps): update angular-cli monorepo to v22.2.2 2026-10-08 06:49:01 +00:00
nessar 964abd3546 ci: enforce GitFlow and publish branch images
See merge request nessar/vac-optimizer!184
2026-10-08 06:48:18 +00:00
nessar 42f1114709 ci: serialize test workers and cap Node memory 2026-10-08 01:05:41 +02:00
nessar 8fcd53fc32 ci: allow the complete benchmark to finish on shared runners 2026-10-08 00:54:49 +02:00
nessar 6b3113de9a ci: bound the benchmark heap on shared runners 2026-10-08 00:43:21 +02:00
nessar 2a53bb6cb4 ci: enforce GitFlow and publish branch images 2026-10-08 00:09:29 +02:00
193 changed files with 31502 additions and 22866 deletions

No files matched your search

+1 -1
View File
@@ -35,7 +35,7 @@ Inspect `git status --short` and distinguish pre-existing user changes from task
Look for the originating spec, in this order:
1. The user's explicit spec, ticket, path, or acceptance criteria in the conversation. Preserve it as authoritative even when commits reference other work.
2. Issue/MR references in relevant commit messages — fetch via `docs/agents/issue-tracker.md` when no explicit source was supplied.
2. Issue/PR references in relevant commit messages — fetch via `docs/agents/issue-tracker.md` when no explicit source was supplied.
3. A PRD/spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature.
4. If nothing is found or the source is inaccessible, continue the Standards review and report the Spec coverage limitation. Ask for a source only when needed to answer the user's request; do not invent requirements or require tracker setup.
@@ -42,10 +42,11 @@ Preserve the configured tracker. For a new setup, infer a likely tracker from th
- **GitHub** — issues live in the repo's GitHub Issues (uses the `gh` CLI)
- **GitLab** — issues live in the repo's GitLab Issues (uses the [`glab`](https://gitlab.com/gitlab-org/cli) CLI)
- **Gitea** — issues live in the repo's Gitea Issues (uses `tea-cli`, or `tea` where that is the installed binary; inspect its help for supported commands)
- **Local markdown** — issues live as files under `.scratch/<feature>/` in this repo (good for solo projects or repos without a remote)
- **Other** (Jira, Linear, etc.) — ask the user to describe the workflow in one paragraph; the skill will record it as freeform prose
Record the choice in `docs/agents/issue-tracker.md`. The GitHub and GitLab templates carry a "PRs as a request surface" flag, defaulted **off** — leave it off and don't raise it; a user who wants external PRs in the triage queue can flip the flag in the file later.
Record the choice in `docs/agents/issue-tracker.md`. The GitHub, GitLab, and Gitea templates carry a "PRs as a request surface" flag, defaulted **off** — leave it off and don't raise it; a user who wants external PRs in the triage queue can flip the flag in the file later.
**Section B — Triage label vocabulary.** Skip this section entirely if the `triage` skill isn't installed (exploration told you) — an uninstalled skill needs no labels.
@@ -105,6 +106,7 @@ Then write the docs files using the seed templates in this skill folder as a sta
- [issue-tracker-github.md](./issue-tracker-github.md) — GitHub issue tracker
- [issue-tracker-gitlab.md](./issue-tracker-gitlab.md) — GitLab issue tracker
- [issue-tracker-gitea.md](./issue-tracker-gitea.md) — Gitea issue tracker
- [issue-tracker-local.md](./issue-tracker-local.md) — local-markdown issue tracker
- [triage-labels.md](./triage-labels.md) — label mapping (only if `triage` is installed)
- [domain.md](./domain.md) — domain doc consumer rules + layout
@@ -0,0 +1,48 @@
# Issue tracker: Gitea
Issues and specs for this repo live as Gitea issues. Use the [`tea`](https://gitea.com/gitea/tea) CLI, called `tea-cli` on some systems. Record the instance URL, repository owner/name, installed command version, and supported operations when adapting this template.
## Access and conventions
Use the existing configured login and infer the repository from `git remote -v`. Check the installed binary's help before selecting commands: tea 1.0 changes the command groups, authentication, flags, and output formats. The examples here use `tea-cli` 0.9.2; options precede positional issue or PR numbers.
- **Authenticate**: use the existing login; for a new login, run interactive `tea-cli login add` with the repository's instance URL.
- **Create an issue**: `tea-cli issues create --title "..." --description "..." --labels "needs-triage"`. Pass multiline descriptions as one quoted argument.
- **Read an issue**: `tea-cli issues --comments <number>`.
- **List issues**: `tea-cli issues --state open --labels "..." --fields index,title,body,state,labels,assignees,url --output yaml`. Paginate with `--page` and `--limit` until all matching issues have been read.
- **Comment**: `tea-cli comment <number> "..."`.
- **Close**: post the explanation first, then `tea-cli issues close <number>`.
- **Pull requests**: `tea-cli pulls create --base <integration-branch> --title "..." --description "..."`, `tea-cli pulls --comments <number>`, and `tea-cli pulls --state open --output yaml`.
- **Milestones**: `tea-cli milestones --state all --fields id,title --output tsv`. Verify migrated milestone IDs rather than copying source-tracker IDs.
This version has no JSON output, issue-edit command, or `api` command. Structured output flags apply to lists; detail views render for display. For unsupported operations, use the instance's `/api/swagger` explorer and `/swagger.v1.json` schema, or the Gitea UI. Authenticate API requests with an authorized token without displaying or committing it. API paths below are relative to the instance's `/api/v1`:
- Read issue details and comments with `GET /repos/<owner>/<repo>/issues/<number>` and its `/comments` endpoint; paginate comments.
- Resolve label IDs with `GET /repos/<owner>/<repo>/labels`. Add labels with `POST /repos/<owner>/<repo>/issues/<number>/labels`, body `{"labels":[<label-id>]}`; remove one with `DELETE` on `/labels/<label-id>`. Preserve unrelated labels.
- Edit a body or assignment with `PATCH /repos/<owner>/<repo>/issues/<number>`, body `{"body":"..."}` or `{"assignees":["<username>"]}`. Read current assignees before updating the list.
- Read a PR diff with `GET /repos/<owner>/<repo>/pulls/<number>.diff`.
## Pull requests as a triage surface
**PRs as a request surface: no.** _(Set to `yes` if this repo treats external pull requests as feature requests; `/triage` reads this flag.)_
When enabled, read and list with `tea-cli pulls`; keep only external requests after checking collaborator or organization membership. Use `tea-cli comment`, the issue-label API, and `tea-cli pulls close <number>` for comment / label / close operations.
Resolve bare `#<number>` references by checking the resource kind with `tea-cli issues --kind all --fields index,kind,title,url --output yaml` or the issue API's `pull_request` field. Issue URLs use `/issues/<number>`; PR URLs use `/pulls/<number>`.
## When a skill says "publish to the issue tracker"
Create a Gitea issue with `tea-cli issues create`.
## When a skill says "fetch the relevant ticket"
Run `tea-cli issues --comments <number>` and read its labels and assignees.
## Wayfinding operations
- **Map**: an issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. Create it with `tea-cli issues create --title "..." --description "..." --labels "wayfinder:map"`.
- **Child ticket**: an issue with `Part of #<map>` at the top of its description, labels `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`), and an ordered link in the map's body.
- **Blocking**: `POST /repos/<owner>/<repo>/issues/<child>/dependencies`, body `{"owner":"<owner>","repo":"<repo>","index":<blocker-number>}`. `GET` lists blockers; `DELETE` with the same body removes one. Where native dependencies are unavailable, use `Blocked by: #<n>, #<n>` at the top of the description. Every blocker must be closed before the ticket is unblocked.
- **Frontier query**: list all open children with bodies and assignees, drop assigned tickets and those with an open native or description-line blocker; first in map order wins.
- **Claim**: assign the authenticated username through the issue API or Gitea UI — the session's first write.
- **Resolve**: comment with `tea-cli comment`, close with `tea-cli issues close`, and update the map's Decisions-so-far through the issue API or Gitea UI.
@@ -0,0 +1,36 @@
---
name: tiered-verified-implement
description: Implement a spec or ticket in Claude Code by delegating the work to the cheapest Claude model that can handle each piece (Haiku for mechanical edits, Sonnet for normal work), then independently verify the final change on the orchestrator's model. Use when the user asks to implement, build, or fix work and wants it done cheaply, on a cheaper model, or with delegated implementation and a verification pass.
---
# Tiered Verified Implement
Invoke `/implement` and follow it as the baseline workflow. This skill is its cost-saving, delegated, verified variant: cheap models write the code, the orchestrator's model checks it.
## Model tiers
Pick the cheapest tier that can do each piece without guessing:
- `haiku`: mechanical work with no design decisions — renames, boilerplate, fixture or snapshot updates, wiring an existing pattern into one more place, translations, doc edits.
- `sonnet`: the default — new logic, bug fixes, tests for real behavior, anything touching several files in one seam.
- Orchestrator (yourself): only for work a cheap agent failed on twice, or that needs a consequential design call the spec leaves open. Ask the user about such calls before delegating rather than letting a cheap agent guess.
When unsure between two tiers, choose the lower one; escalation is cheaper than defaulting high.
## Workflow
1. Read the spec or ticket, repository guidance, affected flow, and existing worktree changes. Record the starting commit and task-owned scope; preserve unrelated changes.
2. Split only genuinely independent, bounded work. If the change is small or one seam owns it, use one implementation agent; do not manufacture parallelism. Assign each piece a tier.
3. Spawn each implementation agent with the Agent tool: `subagent_type: "general-purpose"` and `model` set to its tier. Never use `subagent_type: "fork"` for this — forks ignore the `model` override and run on the expensive orchestrator model. Fresh agents start cold, so the brief carries everything: exact owned files/seam, acceptance criteria, relevant file paths and existing patterns to copy, required checks (targeted tests, typecheck), and an instruction not to overwrite or revert other agents' work. A precise brief is the main cost lever: it stops the cheap agent from re-exploring the repo.
4. Wait for agents, inspect their diffs (not their whole exploration), resolve overlaps minimally, and run the checks required by `/implement`: targeted tests and typecheck during work, then the full relevant suite once.
5. If an agent's result fails checks or misses the spec, send it back once with the concrete failure (SendMessage keeps its context). If it fails again, escalate one tier: haiku → sonnet → orchestrator.
6. Spawn a fresh, read-only verification agent (`subagent_type: "general-purpose"`) with `model` set explicitly to the orchestrator's own tier (e.g. `opus` when you run on Opus). Set it explicitly rather than omitting it, since a configured default subagent model could silently downgrade the verifier. Give it the original request, starting commit, current diff, and test output, but not implementation conclusions. Ask it to check correctness, regressions, specification coverage, and test evidence, and to report findings without changing files.
7. Fix confirmed findings (delegate back to the cheap tier when the fix is mechanical), rerun affected checks, and repeat verification once if fixes were needed. Run `/code-review` on the current working result (including staged, unstaged, and new files), passing the original spec, starting commit, and task-owned scope. Follow `/implement`'s commit boundary: commit only when requested, otherwise hand off the verified diff.
In the final report, list which tier did each piece and any escalations, so the user can see where the cheap models held up.
## Delegation rules
- Keep all agents in the same workspace; assign non-overlapping ownership before they edit.
- Do not delegate secrets, production writes, destructive operations, or changes requiring new user authority.
- If subagents are unavailable, implement directly, run the same checks, and state that delegated implementation and verification were unavailable.
+1 -1
View File
@@ -19,7 +19,7 @@ A wizard is ephemeral by default — built for one run, saved to a scratch or `s
Work out every manual step the human must take and every value that gets captured along the way. Read the repo first — don't ask cold:
- For setup: configuration examples, README, compose/framework configuration, and the actual CI files (this repository uses `.gitlab-ci.yml`). Inspect secret names and references without displaying existing secret values. Include only values needed for the requested procedure, not every variable in the repository.
- For setup: configuration examples, README, compose/framework configuration, and the actual CI files. This repository is hosted on Gitea; read `.gitea/workflows/` and `docs/gitea-actions.md` for the configured workflow and owner-activation requirements. Inspect secret names and references without displaying existing secret values. Include only values needed for the requested procedure, not every variable in the repository.
- For a migration or transition: the current state, the target state, and the irreversible actions between them.
Then show the user the ordered list of stages and the values each produces, and confirm — they may add, drop, or reorder.
+11 -7
View File
@@ -3,15 +3,17 @@
All AI agents (including Cline, Antigravity, Cursor, and Copilot) must adhere to the following rules before declaring a task complete:
1. **Test Coverage (>= 80%)**:
- The overall project code coverage (Statements, Lines, and Functions) must be maintained at **80% or higher**.
- The overall project line coverage must be maintained at **80% or higher**. Bun reports line data only; statement, branch and function coverage are no longer measured.
- Verify coverage by running:
```bash
bun run test --watch=false --coverage
bun scripts/generate-langs.js
bun test --config=bunfig.coverage.toml --isolate --path-ignore-patterns='**/benchmark/**'
bun scripts/coverage-reports.mjs
```
- If your changes introduce new code or modify existing code in a way that drops the coverage below 80%, you must write appropriate unit tests in `.spec.ts` files to bring it back up.
2. **Code Formatting (Prettier)**:
- All code files must be correctly formatted according to the project's Prettier config before finishing.
- All code files, the CI scripts and the workflow must be correctly formatted according to the project's Prettier config before finishing.
- Run the formatter with:
```bash
bun run format
@@ -24,10 +26,12 @@ All AI agents (including Cline, Antigravity, Cursor, and Copilot) must adhere to
bun run build
```
4. **GitLab Pipeline Checks**:
- You must execute the local equivalent of the GitLab CI/CD pipeline steps before completing your task. All of the following commands must pass:
4. **CI Checks**:
- You must execute the local validation commands before completing your task. The Gitea workflow is `.gitea/workflows/ci.yml`; owner activation is tracked in issue #268, and local checks do not satisfy the migration gate. All of the following commands must pass:
- **Linting check**: `bun run lint` (or use `bun run lint:fix` to resolve auto-fixable issues)
- **Formatting check**: `bun run format:check`
- **TypeScript Type check**: `bunx tsc --noEmit`
- **Unit Tests and Coverage**: `bun run test --watch=false --coverage`
- **TypeScript Type check**: `bun run typecheck` (`bun check` for application and test code; it does not replace the production build, which alone checks Angular templates)
- **Unit Tests and Coverage**: generate the language registry, then run the coverage command in rule 1, matching the Gitea functional-test job.
- **CI policy and publication**: `bun scripts/ci-policy.test.mjs` and `bun scripts/ci-image.test.mjs`
- **Production Build**: `bun run build -- --configuration production`
- The separate performance benchmark is a required CI job with a relative gate: each scenario's budget is a multiple of the frozen engine's two-year calibration measured in the same run. Run it outside coverage with `timeout 600s bun test src/app/benchmark --timeout=600000` when verifying performance; see `docs/benchmark/README.md`.
Symlink
+1
View File
@@ -0,0 +1 @@
.agents/
@@ -0,0 +1,5 @@
${PullRequestTitle}
${ClosingIssues}
See pull request ${PullRequestReference}
+239
View File
@@ -0,0 +1,239 @@
name: CI
on:
push:
branches: [develop, main]
tags: ['v*']
pull_request:
types: [opened, reopened, synchronize, edited]
workflow_dispatch:
permissions:
contents: read
# Gitea's checkout and upload-artifact actions are JavaScript actions that the runner
# executes with the job container's own `node`, so those containers keep Node. Project
# commands never use it: the jobs that run them install the pinned Bun with
# scripts/install-bun.sh and run `run:` steps under a shell whose PATH has Bun but no Node.
concurrency:
group: ci-${{ github.event_name }}-${{ github.ref }}
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }}
jobs:
policy:
name: policy
runs-on: ubuntu-latest
container: node:24.22.0
defaults:
run:
shell: env PATH=/opt/bun/bin:/usr/bin:/bin bash -e {0}
outputs:
slug: ${{ steps.policy.outputs.slug }}
tag: ${{ steps.policy.outputs.tag }}
steps:
- uses: https://gitea.com/actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- name: Install Bun
run: sh scripts/install-bun.sh
- name: Policy regression tests
run: bun scripts/ci-policy.test.mjs && bun scripts/ci-image.test.mjs
- name: Validate event and commit
id: policy
run: bun scripts/ci-policy.mjs
validate:
name: validate
runs-on: ubuntu-latest
container: node:24.22.0
defaults:
run:
shell: env PATH=/opt/bun/bin:/usr/bin:/bin bash -e {0}
steps:
- uses: https://gitea.com/actions/checkout@v7
with:
persist-credentials: false
- name: Install Bun
run: sh scripts/install-bun.sh
- run: bun install --frozen-lockfile
- run: bun run lint
- run: bun run format:check
- run: bun run typecheck
test:
name: test
runs-on: ubuntu-latest
container: node:24.22.0
defaults:
run:
shell: env PATH=/opt/bun/bin:/usr/bin:/bin bash -e {0}
steps:
- uses: https://gitea.com/actions/checkout@v7
with:
persist-credentials: false
- name: Install Bun
run: sh scripts/install-bun.sh
- run: bun install --frozen-lockfile
- run: bun scripts/generate-langs.js
- name: Functional coverage
run: bun test --config=bunfig.coverage.toml --isolate --path-ignore-patterns='**/benchmark/**'
- name: Coverage report
if: ${{ always() }}
run: bun scripts/coverage-reports.mjs
- name: Upload coverage
if: ${{ always() }}
uses: https://gitea.com/actions/upload-artifact@v7
with:
name: coverage
path: coverage/
retention-days: 7
if-no-files-found: error
benchmark:
name: benchmark
runs-on: ubuntu-latest
container:
image: node:24.22.0
options: --memory=3g
defaults:
run:
shell: env PATH=/opt/bun/bin:/usr/bin:/bin bash -e {0}
steps:
- uses: https://gitea.com/actions/checkout@v7
with:
persist-credentials: false
- name: Install Bun
run: sh scripts/install-bun.sh
- run: bun install --frozen-lockfile
- run: bun scripts/generate-langs.js
- name: Benchmark protocol with relative gate
run: timeout 240s bun test src/app/benchmark --timeout=240000
build:
name: build
runs-on: ubuntu-latest
container: node:24.22.0
defaults:
run:
shell: env PATH=/opt/bun/bin:/usr/bin:/bin bash -e {0}
steps:
- uses: https://gitea.com/actions/checkout@v7
with:
persist-credentials: false
- name: Install Bun
run: sh scripts/install-bun.sh
- run: bun install --frozen-lockfile
- run: bun run build -- --configuration production
- uses: https://gitea.com/actions/upload-artifact@v7
with:
name: dist
path: dist/
retention-days: 7
if-no-files-found: error
security:
name: security
runs-on: ubuntu-latest
container: node:24.22.0
steps:
- uses: https://gitea.com/actions/checkout@v7
with:
persist-credentials: false
- name: Install scanners
run: |
apt-get update
apt-get install --yes --no-install-recommends python3-venv
python3 -m venv /tmp/semgrep
/tmp/semgrep/bin/pip install semgrep==1.180.0
case "$(uname -m)" in
x86_64) trivy_arch=64bit ;;
aarch64) trivy_arch=ARM64 ;;
*) echo 'Unsupported Trivy architecture' >&2; exit 1 ;;
esac
archive="trivy_0.75.0_Linux-${trivy_arch}.tar.gz"
curl --fail --location --silent --show-error "https://github.com/aquasecurity/trivy/releases/download/v0.75.0/${archive}" --output "/tmp/${archive}"
curl --fail --location --silent --show-error https://github.com/aquasecurity/trivy/releases/download/v0.75.0/trivy_0.75.0_checksums.txt --output /tmp/trivy-checksums.txt
(cd /tmp && sha256sum --check --ignore-missing trivy-checksums.txt)
tar -xzf "/tmp/${archive}" -C /usr/local/bin trivy
- name: JavaScript and TypeScript SAST
run: /tmp/semgrep/bin/semgrep scan --config p/javascript --config p/typescript --metrics off --sarif --output semgrep-results.sarif src scripts
- name: Dependency and secret scan
if: ${{ !cancelled() }}
run: trivy fs --db-repository public.ecr.aws/aquasecurity/trivy-db:2 --format sarif --output trivy-results.sarif --skip-dirs node_modules,dist,coverage .
- name: Security reports
if: ${{ always() }}
uses: https://gitea.com/actions/upload-artifact@v7
with:
name: security
path: '*-results.sarif'
retention-days: 7
if-no-files-found: error
images:
name: images
needs: [policy, validate, test, benchmark, build, security]
if: >-
success() &&
(github.event_name == 'push' ||
(github.event_name == 'pull_request' &&
github.event.pull_request.head.repo.full_name == github.repository))
runs-on: ubuntu-latest
container: docker:29.9.1
concurrency:
group: image-${{ needs.policy.outputs.tag != '' && 'stable' || needs.policy.outputs.slug }}
cancel-in-progress: false
services:
docker:
image: docker:29.9.1-dind
env:
DOCKER_TLS_CERTDIR: ''
options: >-
--privileged
--health-cmd "docker info"
--health-interval 5s
--health-timeout 5s
--health-retries 12
env:
DOCKER_HOST: tcp://docker:2375
DOCKER_TLS_CERTDIR: ''
defaults:
run:
shell: sh
steps:
# Alpine's nodejs package is for the checkout action only (it shares /usr/bin
# with git); Bun needs libgcc and libstdc++ and the installer needs curl.
- name: Install checkout runtime and tools
run: apk add --no-cache nodejs git curl libgcc libstdc++
- uses: https://gitea.com/actions/checkout@v7
with:
fetch-depth: 0
persist-credentials: false
- name: Install Bun
run: sh scripts/install-bun.sh
- name: Build branch images or promote a release
env:
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
run: /opt/bun/bin/bun scripts/ci-image.mjs
required:
name: required
if: ${{ always() }}
needs: [policy, validate, test, benchmark, build, security, images]
runs-on: ubuntu-latest
container: node:24.22.0
env:
CHECK_RESULTS: ${{ needs.policy.result }} ${{ needs.validate.result }} ${{ needs.test.result }} ${{ needs.benchmark.result }} ${{ needs.build.result }} ${{ needs.security.result }}
IMAGE_RESULT: ${{ needs.images.result }}
IMAGE_EXPECTED: ${{ github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) }}
steps:
- name: Require successful validation and expected publication
run: |
test "$CHECK_RESULTS" = 'success success success success success success' || exit 1
if [ "$IMAGE_EXPECTED" = 'true' ]; then
test "$IMAGE_RESULT" = 'success'
else
test "$IMAGE_RESULT" = 'skipped'
fi
+92
View File
@@ -0,0 +1,92 @@
name: Claude review
on:
issue_comment:
types: [created]
permissions:
contents: read
issues: read
pull-requests: write
# A newer @claude comment on the same PR replaces a review still running.
concurrency:
group: claude-review-${{ github.event.issue.number }}
cancel-in-progress: true
jobs:
review:
name: review
# Only the repository owner may spend the Claude credential on a PR.
if: >-
github.event.issue.pull_request &&
contains(github.event.comment.body, '@claude') &&
github.event.comment.user.login == github.repository_owner
runs-on: ubuntu-latest
container: node:24.22.0
timeout-minutes: 30
defaults:
run:
shell: bash
env:
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
PR: ${{ github.event.issue.number }}
steps:
- uses: https://gitea.com/actions/checkout@v7
with:
ref: refs/pull/${{ github.event.issue.number }}/head
fetch-depth: 0
persist-credentials: false
- name: Install tools
# shortcut: the installer script is not checksum-pinned like Bun; pin it if untrusted users can trigger this.
run: |
apt-get update
apt-get install --yes --no-install-recommends jq
curl -fsSL https://claude.ai/install.sh | bash -s 2.1.314
# Tracker reads happen here so the review step never holds the Gitea token.
- name: Collect PR and linked issues
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
curl -fsS -H "Authorization: token $TOKEN" "$API/pulls/$PR" > /tmp/pr.json
base=$(git merge-base "origin/$(jq -r .base.ref /tmp/pr.json)" HEAD)
echo "BASE=$base" >> "$GITHUB_ENV"
refs=$({ jq -r '.body // ""' /tmp/pr.json; git log --format=%B "$base..HEAD"; } | grep -oE '#[0-9]+' | tr -d '#' | sort -un || true)
: > /tmp/spec.md
for n in $refs; do
curl -fsS -H "Authorization: token $TOKEN" "$API/issues/$n" |
jq -r '"### #\(.number) \(.title)\n\n\(.body)\n"' >> /tmp/spec.md || true
done
- name: Review
env:
CLAUDE_CODE_OAUTH_TOKEN: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
DISABLE_AUTOUPDATER: '1'
REQUEST: ${{ github.event.comment.body }}
run: |
prompt="/code-review Review pull request #$PR: committed changes from merge-base $BASE to HEAD.
You run headless in CI: do not modify files, ask questions, or use tea-cli; the tracker content is below.
Your final message is posted verbatim as the PR comment, so output only the review in Markdown.
Requester's comment:
$REQUEST
PR title: $(jq -r .title /tmp/pr.json)
PR description:
$(jq -r '.body // ""' /tmp/pr.json)
Issues referenced by the PR and its commits:
$(cat /tmp/spec.md)"
"$HOME/.local/bin/claude" -p "$prompt" \
--allowedTools 'Skill' 'Agent' 'Bash(git diff:*)' 'Bash(git log:*)' 'Bash(git show:*)' \
'Bash(git status:*)' 'Bash(git rev-parse:*)' 'Bash(git merge-base:*)' 'Bash(git ls-files:*)' \
> /tmp/review.md
- name: Post review
if: ${{ !cancelled() }}
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
RUNS: ${{ github.server_url }}/${{ github.repository }}/actions?workflow=claude-review.yml
run: |
[ -s /tmp/review.md ] || echo "Claude review failed; see [the workflow runs]($RUNS)." > /tmp/review.md
jq -n --rawfile body /tmp/review.md '{body: $body}' |
curl -fsS -X POST -H "Authorization: token $TOKEN" -H 'Content-Type: application/json' \
-d @- "$API/issues/$PR/comments" > /dev/null
+6
View File
@@ -6,6 +6,8 @@
/out-tsc
/bazel-out
.scratch/
# Node
/node_modules
npm-debug.log
@@ -44,3 +46,7 @@ Thumbs.db
# Auto-generated i18n files
/src/app/i18n-registry.ts
# Claude Code local files (.claude is a symlink to .agents/)
.agents/settings.local.json
.agents/worktrees/
-115
View File
@@ -1,115 +0,0 @@
image: oven/bun:latest
stages:
- validate
- test
- build
- security
- docker
variables:
DOCKER_DRIVER: overlay2
DOCKER_TLS_CERTDIR: ''
cache:
key:
files:
- bun.lock
paths:
- .bun/
.node_setup:
before_script:
- bun install --frozen-lockfile
# -- Validate Stage --
lint:
extends: .node_setup
stage: validate
script:
- bunx eslint "src/**/*.ts"
prettier:
extends: .node_setup
stage: validate
script:
- bunx prettier --check "src/**/*.{ts,html,scss,css,json}"
type-check:
extends: .node_setup
stage: validate
script:
- bunx tsc --noEmit
# -- Test Stage --
test:
image: node:24.21.0
extends: .node_setup
stage: test
before_script:
- npm install --global bun@1.4.2
- bun install --frozen-lockfile
script:
- bun run test --watch=false --coverage
artifacts:
when: always
paths:
- coverage/
reports:
coverage_report:
coverage_format: cobertura
path: coverage/cobertura-coverage.xml
expire_in: 7 days
# -- Build Stage --
build:
image: node:24.21.0
extends: .node_setup
stage: build
before_script:
- npm install --global bun@1.4.2
- bun install --frozen-lockfile
script:
- bun run build -- --configuration production
artifacts:
paths:
- dist/
expire_in: 7 days
# -- Security Stage --
include:
- template: Security/SAST.gitlab-ci.yml
trivy_scan:
stage: security
image:
name: aquasec/trivy:latest
entrypoint: ['']
before_script: [] # override global before_script
script:
# Trivy will scan the project directory
- trivy fs --format sarif --output trivy-results.sarif .
artifacts:
reports:
sast: trivy-results.sarif
expire_in: 7 days
# -- Docker Stage --
docker-build:
stage: docker
image: docker:29.8.2
services:
- docker:29.8.2-dind
before_script:
- echo "$CI_REGISTRY_PASSWORD" | docker login $CI_REGISTRY -u $CI_REGISTRY_USER --password-stdin
script:
- docker build -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG" -t "$CI_REGISTRY_IMAGE:latest" .
- docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG"
- docker push "$CI_REGISTRY_IMAGE:latest"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
@@ -6,9 +6,9 @@
**Status:** ready-for-agent
**GitLab:** [#61](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/61)
**Gitea:** [#61](https://gitea.nessar.fr/nessar/vac-optimizer/issues/61)
Source : [issue #13](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/13), entretien et spécification de développement. Respecter le glossaire du domaine et les ADR 0002, 0005, 0006 et 0007.
Source : [issue #13](https://gitea.nessar.fr/nessar/vac-optimizer/issues/13), entretien et spécification de développement. Respecter le glossaire du domaine et les ADR 0002, 0005, 0006 et 0007.
- [ ] Un mode explicite « Saisir les jours déjà posés » présente l’horizon actuellement choisi et permet de sélectionner CP, RTT ou Autre. Autre couvre toutes les autres raisons de ne pas travailler ; ANY reste uniquement un sélecteur de règle.
- [ ] Un clic sur une date admissible ajoute le type sélectionné ; un deuxième clic avec ce type supprime la déclaration ; un clic avec un autre type la remplace. Une date porte au maximum une déclaration.
@@ -4,13 +4,13 @@
**Blocked by:**
- 01 — Saisir, sauvegarder et figer les jours déjà posés ([#61](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/61)).
- 01 — Saisir, sauvegarder et figer les jours déjà posés ([#61](https://gitea.nessar.fr/nessar/vac-optimizer/issues/61)).
**Status:** ready-for-agent
**GitLab:** [#62](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/62)
**Gitea:** [#62](https://gitea.nessar.fr/nessar/vac-optimizer/issues/62)
Source : [issue #13](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/13), entretien et spécification de développement. Respecter les définitions de période de repos, gain en jours non travaillés, séquence de travail et semaine de jour férié du glossaire, ainsi que les ADR 0006 et 0007.
Source : [issue #13](https://gitea.nessar.fr/nessar/vac-optimizer/issues/13), entretien et spécification de développement. Respecter les définitions de période de repos, gain en jours non travaillés, séquence de travail et semaine de jour férié du glossaire, ainsi que les ADR 0006 et 0007.
- [ ] Un vendredi ordinaire déclaré Autre, sans solde ni règle, produit une période vendredi–dimanche de trois jours. Cette période existe sans nouveau placement et ne provoque aucun débit.
- [ ] Les déclarations, nouveaux placements, week-ends et jours fériés adjacents forment des périodes contiguës fusionnées. Chaque date contribue une seule fois à leur durée ; l’origine et le type des déclarations restent distincts des placements.
@@ -4,13 +4,13 @@
**Blocked by:**
- 01 — Saisir, sauvegarder et figer les jours déjà posés ([#61](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/61)).
- 01 — Saisir, sauvegarder et figer les jours déjà posés ([#61](https://gitea.nessar.fr/nessar/vac-optimizer/issues/61)).
**Status:** ready-for-agent
**GitLab:** [#63](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/63)
**Gitea:** [#63](https://gitea.nessar.fr/nessar/vac-optimizer/issues/63)
Source : [issue #13](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/13), entretien et spécification de développement. Respecter les quantités, fenêtres inclusives, obligations conjointes, priorités et contributions partagées du glossaire, ainsi que l’ADR 0007.
Source : [issue #13](https://gitea.nessar.fr/nessar/vac-optimizer/issues/13), entretien et spécification de développement. Respecter les quantités, fenêtres inclusives, obligations conjointes, priorités et contributions partagées du glossaire, ainsi que l’ADR 0007.
- [ ] Dans une semaine ordinaire, avec quatre CP restants, un mercredi déclaré CP et une obligation de cinq CP du lundi au vendredi, le calcul ajoute quatre CP et débite uniquement ces quatre jours.
- [ ] Les déclarations compatibles contribuent aux obligations exactes et aux préférences demandant jusqu’à une quantité donnée, dans l’intersection entre la fenêtre inclusive de la règle et l’horizon soumis. Une déclaration extérieure à ces limites ne contribue pas à la règle.
@@ -4,14 +4,14 @@
**Blocked by:**
- 02 — Optimiser les périodes de repos autour des jours déclarés ([#62](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/62)).
- 03 — Compter les jours déclarés dans les règles de période ([#63](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/63)).
- 02 — Optimiser les périodes de repos autour des jours déclarés ([#62](https://gitea.nessar.fr/nessar/vac-optimizer/issues/62)).
- 03 — Compter les jours déclarés dans les règles de période ([#63](https://gitea.nessar.fr/nessar/vac-optimizer/issues/63)).
**Status:** ready-for-agent
**GitLab:** [#64](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/64)
**Gitea:** [#64](https://gitea.nessar.fr/nessar/vac-optimizer/issues/64)
Source : [issue #13](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/13), entretien et spécification de développement. Respecter les occurrences et modes IF_THEN, les droits acquis et l’ordre des objectifs du glossaire, ainsi que les ADR sur les artefacts du même calcul et l’ADR 0007.
Source : [issue #13](https://gitea.nessar.fr/nessar/vac-optimizer/issues/13), entretien et spécification de développement. Respecter les occurrences et modes IF_THEN, les droits acquis et l’ordre des objectifs du glossaire, ainsi que les ADR sur les artefacts du même calcul et l’ADR 0007.
- [ ] Les motifs IF_THEN utilisent les véritables jours fériés français nationaux et les modes before, after, around et auto existants. Une déclaration ne crée pas une occurrence de jour férié et ne permet pas de déplacer le motif hors de ses limites admissibles.
- [ ] Une déclaration compatible occupe sa position normale dans le motif et réduit le nombre de nouveaux placements nécessaires. Une déclaration incompatible ne peut être retypée ou déplacée, ni être sautée pour reporter la position demandée sur un jour plus éloigné. Les obligations restent obligatoires pour chaque occurrence ; les préférences conservent leur exigence de motif complet et leurs priorités.
@@ -6,9 +6,9 @@
**Status:** ready-for-agent
**GitLab:** [#65](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/65)
**Gitea:** [#65](https://gitea.nessar.fr/nessar/vac-optimizer/issues/65)
Source: the agreed Plan Statistics Popup spec for [#3](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/3) and [#29](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/29), in milestone %3: V1 stats. Follow the domain glossary and ADRs 0002, 0004, 0006, and 0007.
Source: the agreed Plan Statistics Popup spec for [#3](https://gitea.nessar.fr/nessar/vac-optimizer/issues/3) and [#29](https://gitea.nessar.fr/nessar/vac-optimizer/issues/29), in milestone V1 stats. Follow the domain glossary and ADRs 0002, 0004, 0006, and 0007.
- [ ] A labelled calendar control opens one statistics popup for the latest calculated valid plan. Opening it runs no optimization and changes no planning data.
- [ ] The popup shows the number of leave placement dates with an explicit leave-day label. Declared non-working days consume no balance and are excluded from this count. A valid plan with no placements displays 0 and still permits opening the popup.
@@ -5,13 +5,13 @@
**Blocked by:**
- 01 — Open plan statistics for calculated leave usage.
- [#62 — Optimiser les périodes de repos autour des jours déclarés](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/62), which establishes time-off periods and work sequences that include declared non-working days.
- [#62 — Optimiser les périodes de repos autour des jours déclarés](https://gitea.nessar.fr/nessar/vac-optimizer/issues/62), which establishes time-off periods and work sequences that include declared non-working days.
**Status:** ready-for-agent
**GitLab:** [#66](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/66)
**Gitea:** [#66](https://gitea.nessar.fr/nessar/vac-optimizer/issues/66)
Source: the agreed Plan Statistics Popup spec for [#3](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/3) and [#29](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/29), including [#7](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/7). The existing longest work-sequence metric from #28 is reused. Follow the domain glossary and ADRs 0004, 0006, and 0007.
Source: the agreed Plan Statistics Popup spec for [#3](https://gitea.nessar.fr/nessar/vac-optimizer/issues/3) and [#29](https://gitea.nessar.fr/nessar/vac-optimizer/issues/29), including [#7](https://gitea.nessar.fr/nessar/vac-optimizer/issues/7). The existing longest work-sequence metric from #28 is reused. Follow the domain glossary and ADRs 0004, 0006, and 0007.
- [ ] Add five labelled metrics: non-working-day gain, average work-sequence length, longest work-sequence length, average time-off period length, and longest time-off period length. Work lengths use working days; break lengths use calendar days.
- [ ] The work-sequence average includes every non-empty sequence inside the submitted horizon, including both edges. Weekends and French public holidays neither count nor split a sequence; leave placements and declared non-working days interrupt it. Consecutive days off introduce no zero-length samples.
@@ -5,13 +5,13 @@
**Blocked by:**
- 01 — Open plan statistics for calculated leave usage.
- [#64 — Appliquer les motifs IF_THEN et les droits acquis aux jours déclarés](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/64), which establishes finalized earned entitlements and the fixed Europe/Paris calculation-date cutoff.
- [#64 — Appliquer les motifs IF_THEN et les droits acquis aux jours déclarés](https://gitea.nessar.fr/nessar/vac-optimizer/issues/64), which establishes finalized earned entitlements and the fixed Europe/Paris calculation-date cutoff.
**Status:** ready-for-agent
**GitLab:** [#67](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/67)
**Gitea:** [#67](https://gitea.nessar.fr/nessar/vac-optimizer/issues/67)
Source: the agreed Plan Statistics Popup spec for [#3](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/3) and [#29](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/29), including [#8](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/8). Follow the domain glossary and ADRs 0004, 0006, and 0007.
Source: the agreed Plan Statistics Popup spec for [#3](https://gitea.nessar.fr/nessar/vac-optimizer/issues/3) and [#29](https://gitea.nessar.fr/nessar/vac-optimizer/issues/29), including [#8](https://gitea.nessar.fr/nessar/vac-optimizer/issues/8). Follow the domain glossary and ADRs 0004, 0006, and 0007.
- [ ] Display gross earned leave from every applicable generating rule, including Samedi Malin, with a per-rule breakdown whose quantities sum to the total.
- [ ] A plan earning 3 days and consuming 2 reports 3 earned days. Fully consumed earned entitlements remain included even when absent from remaining balances; generating a future entitlement does not require consuming it inside the horizon.
@@ -5,13 +5,13 @@
**Blocked by:**
- 01 — Open plan statistics for calculated leave usage.
- [#62 — Optimiser les périodes de repos autour des jours déclarés](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/62), which provides shared time-off periods including declared non-working days and adjacent context dates.
- [#62 — Optimiser les périodes de repos autour des jours déclarés](https://gitea.nessar.fr/nessar/vac-optimizer/issues/62), which provides shared time-off periods including declared non-working days and adjacent context dates.
**Status:** ready-for-agent
**GitLab:** [#68](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/68)
**Gitea:** [#68](https://gitea.nessar.fr/nessar/vac-optimizer/issues/68)
Source: the agreed Plan Statistics Popup spec for [#3](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/3) and [#29](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/29), including [#9](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/9). Follow the domain glossary and ADRs 0004, 0006, and 0007.
Source: the agreed Plan Statistics Popup spec for [#3](https://gitea.nessar.fr/nessar/vac-optimizer/issues/3) and [#29](https://gitea.nessar.fr/nessar/vac-optimizer/issues/29), including [#9](https://gitea.nessar.fr/nessar/vac-optimizer/issues/9). Follow the domain glossary and ADRs 0004, 0006, and 0007.
- [ ] Show the number of distinct Monday-to-Friday French public-holiday dates in planned time-off periods containing at least one Saturday or Sunday. Each qualifying period contains at least one leave placement or declared non-working day.
- [ ] Count direct Monday/Friday connections and connections through leave, such as a Tuesday holiday joined to a weekend by Monday off. Declared non-working days can provide the same connection without consuming a balance.
@@ -5,13 +5,13 @@
**Blocked by:**
- 01 — Open plan statistics for calculated leave usage.
- [#61 — Saisir, sauvegarder et figer les jours déjà posés](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/61), which carries fixed declared non-working days with the producing calculation and its outcomes.
- [#61 — Saisir, sauvegarder et figer les jours déjà posés](https://gitea.nessar.fr/nessar/vac-optimizer/issues/61), which carries fixed declared non-working days with the producing calculation and its outcomes.
**Status:** ready-for-agent
**GitLab:** [#69](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/69)
**Gitea:** [#69](https://gitea.nessar.fr/nessar/vac-optimizer/issues/69)
Source: the agreed Plan Statistics Popup spec for [#3](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/3) and [#29](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/29), including the clarification that working only one day in a full week is undesirable. Follow the domain glossary and ADRs 0004, 0006, and 0007.
Source: the agreed Plan Statistics Popup spec for [#3](https://gitea.nessar.fr/nessar/vac-optimizer/issues/3) and [#29](https://gitea.nessar.fr/nessar/vac-optimizer/issues/29), including the clarification that working only one day in a full week is undesirable. Follow the domain glossary and ADRs 0004, 0006, and 0007.
- [ ] Count Monday-to-Sunday calendar weeks whose five Monday-to-Friday dates all lie inside the submitted half-open horizon and that contain exactly one remaining working day after excluding French public holidays, leave placements, and declared non-working days.
- [ ] Four weekdays off and one remaining workday qualify. Weeks with zero or two remaining workdays do not qualify, including two-workday weeks containing separate one-day work sequences.
@@ -0,0 +1,25 @@
# 01 — Unifier l’évaluation et la comparaison des objectifs
**Gitea:** [#70](https://gitea.nessar.fr/nessar/vac-optimizer/issues/70)
**What to build:** Le planificateur conserve ses résultats actuels pendant une préparation qui rend les six objectifs évaluables à partir de configurations de règles. Le contrat commun permet ensuite aux règles fournies et aux règles personnelles d’utiliser les mêmes mesures, sans dépendre de leur nom ou de leur identité.
**Blocked by:** None — can start immediately.
**Status:** ready-for-agent
Préparation du remplacement décrit par l’ADR 0008, justifiée par les comparaisons aujourd’hui dispersées dans le moteur. Ouvrir une branche d’intégration consacrée à cette évolution ; la mise en service de l’ensemble dépend du ticket 06. Préserver les données utilisateur est une décision explicite du cadrage.
**Hypothèses de travail :** Pour clore les détails techniques restés ouverts dans la spécification, partir du catalogue minimal nécessaire aux six préréglages : somme, comptage et maximum, directions minimiser ou maximiser, valeur zéro sur ensemble vide. Le déficit de reprise possède un seuil entier positif, initialement cinq ; la pondération des semaines fériées reste la mesure métier existante. Les autres agrégations et filtres ne sont pas requis par ce découpage.
- [ ] Décrire le contrat composé : éléments observés, conditions applicables, mesure, agrégation et direction. Définir une table finie des combinaisons compatibles et des paramètres acceptés, avec les unités en jours travaillés ou calendaires selon la mesure. Le catalogue permet de composer des configurations, sans se réduire à six identifiants d’objectifs.
- [ ] Exprimer dans ce contrat les six préréglages : somme des soldes à risque non placés à minimiser ; somme des valeurs des semaines fériées complètes à maximiser ; gain de jours non ouvrés à maximiser ; longueur maximale des séquences de travail à minimiser ; déficit des courtes séquences internes à minimiser ; nombre de placements d’appoint à minimiser.
- [ ] Conserver les définitions exactes : pondération des fériés du lundi au vendredi de 1, 2, 3, 2, 1 ; déficit de cinq moins la longueur pour chaque séquence interne non vide de moins de cinq jours ; séquences aux bords de l’horizon incluses dans le maximum et exclues du déficit interne.
- [ ] Définir explicitement zéro pour le comptage, la somme et le maximum sur un ensemble vide, en reprenant les résultats actuels. Valider le domaine et l’unité des paramètres ; une combinaison non prise en charge est identifiable.
- [ ] Une même configuration appliquée au même plan produit la même valeur quels que soient le nom et l’identité de la règle. Vérifier aussi une configuration paramétrée distincte du préréglage, par exemple le déficit à trois jours, sans inventer une nouvelle mesure métier.
- [ ] Regrouper l’évaluation et les comparaisons nécessaires à la sélection des solutions d’obligations, aux déplacements, aux placements d’appoint, aux départages et aux explications. Remplacer les calculs dupliqués concernés ; ne pas ajouter un second moteur ou un adaptateur de compatibilité.
- [ ] Cette préparation conserve l’ordre historique pour ses scénarios de référence : prévention des pertes, préférences, semaines fériées, gain de jours non ouvrés, séquence maximale, déficit des reprises, placements d’appoint, expiration puis dates.
- [ ] Les tests existants de placements, soldes, obligations conjointes, congés gagnés et trace de qualité conservent leurs résultats observables pendant ce prefactoring. Les mesures sont également vérifiées sur des plans concrets comportant des jours déclarés et des périodes aux limites de l’horizon.
- [ ] Consigner le contrat minimal et ses cas limites pour les tickets suivants, en distinguant les décisions déjà confirmées des hypothèses techniques retenues. Les tickets suivants partagent ce contrat et cette branche d’intégration.
**Vérification de bout en bout :** Comparer les résultats et les explications des scénarios de référence avant et après la préparation ; vérifier que les six recettes et une variante paramétrée évaluent correctement les mêmes plans.
@@ -0,0 +1,24 @@
# 02 — Piloter la prévention des pertes depuis les règles
**Gitea:** [#71](https://gitea.nessar.fr/nessar/vac-optimizer/issues/71)
**What to build:** L’utilisateur crée une règle d’optimisation de prévention des pertes, l’enregistre, la déplace parmi ses préférences et constate son effet sur les congés placés et les soldes restants. La désactiver retire réellement sa priorité automatique.
**Blocked by:** 01 — Unifier l’évaluation et la comparaison des objectifs.
**Status:** ready-for-agent
Première tranche fonctionnelle du modèle commun de l’ADR 0008. Continuer la branche d’intégration du ticket 01 ; l’ajout des six préréglages aux données existantes et la mise en service sont traités au ticket 06. Les scénarios de cette tranche soumettent explicitement leurs règles.
- [ ] Proposer la famille Optimisation dans la liste existante et permettre de créer, nommer, éditer, activer, désactiver, supprimer et réordonner une règle utilisant la somme des soldes à risque non placés. Seul le mode préférence est disponible pour cette famille.
- [ ] L’édition, les résumés et les commandes utilisent le contrat du ticket 01, sont traduits et accessibles au clavier. La configuration complète est sauvegardée localement et restaurée, avec son identité, ses paramètres, son activation et sa position.
- [ ] Le calcul résout les obligations conjointement puis utilise l’ordre des préférences actives pour arbitrer les placements. Placer la prévention des pertes sous une préférence personnelle peut laisser davantage de congés à risque inutilisés ; la remonter restaure sa priorité.
- [ ] Remplacer l’exécution implicite de la prévention des pertes par l’exécution de sa configuration explicite. Mettre en place le parcours ordonné partagé des règles ; aucun objectif n’est ajouté implicitement à une requête pour compenser une règle absente ou une configuration non prise en charge.
- [ ] Une règle désactivée donne le même plan que son absence, à autres entrées identiques. Une requête sans règle active n’ajoute aucun congé, même avec des soldes à risque, et conserve les jours déclarés. Les départages par expiration et dates ne déclenchent aucun placement.
- [ ] Les quantités, disponibilités, expirations, jours éligibles et jours déclarés restent des contraintes de validité. Une configuration active incompatible ou mal formée produit une erreur d’entrée rattachable à la règle, sans devenir un conflit d’obligations ni réactiver un défaut.
- [ ] Les chemins direct et worker conservent tous les paramètres de la règle dans l’instantané du calcul. L’explication, la trace et les analyses contrefactuelles suivent le même ordre actif ; une modification ultérieure dans l’éditeur ne change pas le résultat soumis.
- [ ] Adapter les consommateurs concernés, notamment ceux qui supposent qu’une règle comporte toujours un nombre de jours à poser. L’estimation de durée reste finie et les règles existantes Si… alors… et Période restent utilisables.
- [ ] Les tests de comportement couvrent création et rechargement, déplacement au clavier, priorité inversée contre une préférence personnelle, désactivation équivalente à suppression, absence de règles, entrée invalide et passage par le worker. S’appuyer sur les suites existantes de gestion des règles, de planification et d’instantané immuable.
- [ ] Les fonctionnalités communes de cette tranche sont réutilisables par les familles des tickets 03 à 05. Ne pas conserver une exécution historique parallèle comme solution transitoire ; la série est livrée après sa validation commune.
**Vérification de bout en bout :** Avec un solde à risque et une préférence personnelle concurrente, déplacer la prévention des pertes, recalculer et comparer les placements et soldes ; désactiver ensuite toutes les règles et vérifier l’absence de nouveaux congés.
@@ -0,0 +1,23 @@
# 03 — Composer les règles de semaines fériées et de repos
**Gitea:** [#72](https://gitea.nessar.fr/nessar/vac-optimizer/issues/72)
**What to build:** L’utilisateur crée et règle les préférences « Compléter les semaines avec un jour férié » et « Profiter des week-ends et jours fériés », puis choisit laquelle prime dans le planning et dans ses explications.
**Blocked by:** 02 — Piloter la prévention des pertes depuis les règles.
**Status:** ready-for-agent
Tranche de calendrier de l’ADR 0008, sur la branche d’intégration commune. Elle utilise l’édition, la persistance, le transport et l’ordre actif introduits au ticket 02. Elle peut avancer indépendamment du ticket 04 ; la mise en service reste conditionnée au ticket 06.
- [ ] Permettre de composer, enregistrer et modifier les règles sur les semaines fériées et les périodes de repos avec les conditions, mesures et agrégations compatibles du contrat commun. Les deux préréglages sont des configurations du même modèle que les règles personnelles.
- [ ] Le préréglage des semaines fériées maximise la somme des valeurs des semaines complètes. Compter chaque férié du lundi au vendredi selon sa distance au week-end le plus proche ; additionner les contributions de plusieurs fériés dans une semaine sans compter la semaine deux fois.
- [ ] Le préréglage du gain maximise les dates distinctes de week-end et de jour férié contenues dans les périodes de repos. Les jours de congé posés ne constituent pas eux-mêmes ce gain.
- [ ] Conserver les contributions des jours déclarés et les règles d’adjacence aux limites de l’horizon. Les placements restent dans l’horizon et sur des dates éligibles ; une semaine ordinaire entièrement déclarée ne devient pas une semaine fériée.
- [ ] Les règles s’arbitrent selon leur position parmi toutes les préférences actives. Un scénario où la meilleure semaine fériée concurrence un gain de jours non ouvrés plus élevé démontre les deux ordres possibles.
- [ ] Une préférence de calendrier peut être placée avant ou après Samedi Malin et les autres préférences. Aucun ancien garde-fou ne rétablit automatiquement la priorité d’une semaine fériée ou d’une prévention des pertes désactivée.
- [ ] La recherche peut utiliser des placements d’appoint admissibles lorsque l’objectif actif les justifie et que les préférences supérieures et obligations sont préservées. Leur classification est conservée pour le ticket 05.
- [ ] La configuration éditée et sauvegardée est celle utilisée par le calcul direct, le worker, les explications, la trace et les comparaisons de dates. Les libellés et commandes sont traduits et accessibles.
- [ ] Adapter les scénarios de comportement existants sur les semaines fériées, le gain, les jours déclarés et les placements d’appoint : férié du mercredi, plusieurs fériés, horizon partiel, concurrence entre objectifs et désactivation équivalente à absence. Les requêtes de référence fournissent explicitement leurs règles.
**Vérification de bout en bout :** Créer les deux règles, inverser leur ordre sur un cas concurrent, recalculer et constater la modification du planning et du premier objectif décisif dans l’explication ; recharger et retrouver la configuration.
@@ -0,0 +1,23 @@
# 04 — Composer les règles de séquences de travail
**Gitea:** [#73](https://gitea.nessar.fr/nessar/vac-optimizer/issues/73)
**What to build:** L’utilisateur compose des préférences sur ses séquences de travail : réduire la plus longue séquence ou limiter le déficit des reprises courtes, avec un seuil configurable. Leur position parmi les autres préférences influence le planning.
**Blocked by:** 02 — Piloter la prévention des pertes depuis les règles.
**Status:** ready-for-agent
Tranche de séquences de travail de l’ADR 0008, sur la branche d’intégration commune. Elle utilise le contrat minimal et les fonctions de gestion du ticket 02 et peut avancer indépendamment du ticket 03. Le seuil initial de cinq jours reproduit le comportement existant.
- [ ] Permettre de créer, éditer, sauvegarder et réordonner une règle sur la longueur maximale des séquences de travail et une règle sur le déficit des séquences internes, à partir du même modèle composable.
- [ ] Le préréglage de la séquence maximale minimise son nombre de jours travaillés, en incluant les séquences situées aux deux bords de l’horizon. Les week-ends et jours fériés ne comptent pas et ne coupent pas une séquence.
- [ ] Le préréglage des reprises courtes minimise la somme des déficits pour les séquences internes non vides : avec le seuil initial de cinq jours, une reprise d’un jour contribue quatre et une reprise de quatre jours contribue un. Les séquences aux bords de l’horizon sont exclues de cette mesure.
- [ ] Le seuil de la mesure de déficit est un entier strictement positif, initialement cinq. Une règle personnelle utilisant un autre seuil, par exemple trois, calcule son propre déficit et peut produire un autre arbitrage ; il ne s’agit pas d’un seuil impératif de validité.
- [ ] Les conditions de sélection, mesures, unités et paramètres compatibles sont contrôlés à l’édition et à l’entrée du calcul. Une collection vide ou des séquences internes vides respectent la valeur zéro définie au ticket 01.
- [ ] Deux règles portant sur la même famille mais ayant des paramètres distincts sont évaluées séparément selon leur position. L’évaluation et les caches éventuels ne confondent pas les configurations sur la seule base du type de mesure.
- [ ] Les placements choisis respectent les obligations, les préférences supérieures et les jours déclarés. Désactiver une règle retire son influence, y compris lors de la recherche de placements d’appoint, sans conserver une protection fixe de la longueur maximale ou du déficit.
- [ ] L’interface, la restauration, le worker, l’explication, la trace et les comparaisons contrefactuelles utilisent la même configuration capturée. Les libellés distinguent jours travaillés, seuil de préférence et unité de la mesure.
- [ ] Les tests prolongent les suites de statistiques et de planification : bords de l’horizon, séquences vides, jours déclarés, seuil initial, autre seuil, deux règles paramétrées, priorité face à une règle personnelle et désactivation. Les vérifications portent sur les placements et valeurs observables, y compris après rechargement.
**Vérification de bout en bout :** Créer une préférence de reprise courte à cinq jours, constater sa mesure et le plan, puis la modifier à trois jours et recalculer un cas discriminant ; retrouver le seuil et son effet après rechargement.
@@ -0,0 +1,22 @@
# 05 — Piloter l’économie des jours d’appoint
**Gitea:** [#74](https://gitea.nessar.fr/nessar/vac-optimizer/issues/74)
**What to build:** L’utilisateur ajoute une préférence « Économiser les jours d’appoint » et décide, par sa position, jusqu’où les améliorations du planning peuvent consommer des congés qui expirent après l’horizon.
**Blocked by:** 03 — Composer les règles de semaines fériées et de repos ; 04 — Composer les règles de séquences de travail.
**Status:** ready-for-agent
Tranche d’économie des placements d’appoint de l’ADR 0008, sur la branche d’intégration commune. Les tickets 03 et 04 fournissent les objectifs qui peuvent justifier ces placements et contre lesquels cette préférence doit être vérifiée. La migration globale est réservée au ticket 06.
- [ ] Permettre de créer, éditer, activer, désactiver, supprimer, réordonner et sauvegarder une règle qui minimise le nombre de placements d’appoint selon le contrat commun.
- [ ] Compter uniquement les placements d’appoint au sens du domaine : des placements supplémentaires issus de soldes expirant après l’horizon pour améliorer le plan. Les placements explicitement demandés par une règle ne deviennent pas tous des placements d’appoint parce que leur solde expire plus tard.
- [ ] En position supérieure aux objectifs de calendrier ou de séquences de travail, cette préférence peut empêcher des ajouts d’appoint qui amélioreraient seulement ces objectifs inférieurs. En position inférieure, elle économise des placements sans dégrader les objectifs supérieurs ni les obligations.
- [ ] La suppression, le déplacement ou la réaffectation d’un placement conserve une classification et une provenance cohérentes. Les conditions chronologiques des congés gagnés et les soldes disponibles restent valides.
- [ ] Désactiver cette règle retire son critère de comparaison ; aucune étape fixe ne rétablit la minimisation du nombre de placements d’appoint. Sa désactivation ne déclenche pas à elle seule de nouveaux placements : un objectif actif doit justifier un ajout.
- [ ] Les cas à égalité sur les règles actives conservent les départages finaux par expiration puis dates. Un objectif supprimé ne réapparaît pas sous forme de départage caché.
- [ ] La gestion dans l’interface, la persistance et les commandes au clavier traversent jusqu’au calcul réel. Explications, trace et analyses contrefactuelles rendent compte de la règle active et de la contribution des placements concernés.
- [ ] Adapter les tests existants sur la conservation de provenance et l’économie des placements d’appoint. Ajouter des arbitrages vérifiables contre une amélioration de calendrier et contre une amélioration des séquences de travail, avec inversion des priorités et comparaison entre désactivation et absence.
**Vérification de bout en bout :** Comparer un plan qui ajoute des jours d’appoint pour améliorer le repos à un plan où la préférence d’économie est remontée ; montrer les jours consommés, les soldes conservés et l’objectif décisif.
@@ -0,0 +1,34 @@
# 06 — Migrer les règles sauvegardées et valider le comportement fonctionnel
**Gitea:** [#75](https://gitea.nessar.fr/nessar/vac-optimizer/issues/75)
Blocked by: #74
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.
## 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.
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.
## Acceptance criteria
- [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.
- [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.
- [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.
- [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.
- [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.
- [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.
- [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.
- [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.
- [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.
- [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.
- [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.
- [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.
**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.
## Blocked by
- #74 — Piloter l’économie des jours d’appoint
@@ -0,0 +1,29 @@
# 01 — Remove the original decision trace end to end
**Gitea:** [#76](https://gitea.nessar.fr/nessar/vac-optimizer/issues/76)
## What to build
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.
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.
## Acceptance criteria
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] Update component styles and translations across supported languages, preserving keyboard access and accessibility for retained explanations, calendar interactions and date analysis.
- [ ] 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.
- [ ] 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.
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.
## Blocked by
None — can start immediately.
@@ -0,0 +1,27 @@
# 02 — Verify integrated planning after trace removal
**Gitea:** [#77](https://gitea.nessar.fr/nessar/vac-optimizer/issues/77)
Blocked by: #76
## What to build
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.
## Acceptance criteria
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
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.
## Blocked by
- #76 — Remove the original decision trace end to end (https://gitea.nessar.fr/nessar/vac-optimizer/issues/76).
@@ -0,0 +1,39 @@
# 03 — Verify and optimize planning to meet the benchmarks from #75
**Gitea:** [#78](https://gitea.nessar.fr/nessar/vac-optimizer/issues/78)
Blocked by: #75, #77
## Parent
#75 — Performance acceptance separated from the functional migration ticket at the user's request.
## What to build
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.
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.
## Acceptance criteria
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
- [ ] 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.
## Existing evidence and scope
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.
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.
## Blocked by
- #75 — Finish the functional saved-rule migration and integrated planning validation.
- #77 — Verify integrated planning after trace removal (itself blocked by #76).
+3
View File
@@ -0,0 +1,3 @@
{
"npm.packageManager": "bun"
}
+14 -1
View File
@@ -2,7 +2,7 @@
### Issue tracker
Issues and specs live in GitLab Issues; use `glab` for tracker operations. See `docs/agents/issue-tracker.md`.
Issues and specs live in Gitea Issues; use `tea-cli` for supported tracker operations. Before tracker work, read `docs/agents/issue-tracker.md` for commands and API alternatives.
### Triage labels
@@ -11,3 +11,16 @@ Use the default canonical labels: `needs-triage`, `needs-info`, `ready-for-agent
### Domain docs
This is a single-context repo using root `CONTEXT.md` and `docs/adr/`. See `docs/agents/domain.md`.
## GitFlow
- `develop` is the default integration branch; `main` contains releases. Start `feature/*` branches from the current `origin/develop` and target their PRs to `develop`.
- Rebase working branches onto the latest `origin/develop` before opening or merging a PR. If `develop` advances, rebase and rerun the PR checks before merging.
- Integrate through PRs with successful required checks and merges restricted to designated maintainers through Gitea's merge allowlist. The `develop` allowlist also admits the `renovate` bot, which automerges minor, patch, digest, and pin updates once `required` passes; major updates stay manual. Use merge commits (`--no-ff`) with squashing disabled. Direct and forced pushes to `main` and `develop` are forbidden.
- Use Conventional Commits for new commits and PR titles.
- Create `release/X.Y.Z` from `develop` and `hotfix/X.Y.Z` from `main`. Only `release/*` and `hotfix/*` PRs target `main`. Merge each release or hotfix into both `main` and `develop`, keeping its branch until both PRs are merged.
- Use merges and back-merges for releases and hotfixes. Never rebase `main`, `develop`, or a frozen release branch.
The CI workflow is `.gitea/workflows/ci.yml`. Activation is tracked in Gitea issue #268; Actions is enabled with owner approval, and the migration gate stays required until live workflow validation and merge-message review. Before changing CI, image publication, or activation settings, read [Gitea Actions](docs/gitea-actions.md).
Before preparing a release or hotfix, creating a tag, or changing image publication, read [GitFlow and releases](README.md#gitflow-and-releases) for package versions, explicit stable tags, and image promotion.
+40 -29
View File
@@ -24,6 +24,10 @@ The unspent portion of a leave balance that expires after the planning horizon.
The category of leave in a balance or on a declared non-working day: CP (paid leave), RTT (working-time reduction leave), or Other (a user-managed catch-all, including any other reason for not working).
_Avoid_: ANY as a leave type; `ANY` is only a rule selector.
**Today**:
The current Europe/Paris calendar date, whatever the device's time zone. The calendar marks it as today and shows earlier dates as past.
_Avoid_: local date
**Planning horizon**:
The user-selected half-open date interval within which leave may be placed; its start may precede today's Europe/Paris calendar date and its duration may exceed twelve months. It defaults to today through the same date twelve months later, and explicitly selected boundaries remain unchanged as time passes, with past dates still eligible for leave placements.
@@ -83,29 +87,47 @@ The greatest number of working days in any work sequence within the planning hor
**Short work sequence**:
A work sequence of fewer than five working days between two planned time-off periods.
**Short work-sequence deficit**:
The total number of working days missing for all short work sequences to reach five working days each; empty sequences contribute zero.
**Week with one workday**:
An undesirable Monday-to-Sunday calendar week with exactly one working day remaining after excluding leave placements and declared non-working days. All five Monday-to-Friday dates must fall within the planning horizon.
**Planning rule**:
A user instruction that requests leave placements around a calendar opportunity or inside a date window. Its force is either an obligation or a preference.
A named instruction, supplied by the application or defined by the user, that guides leave placement. Only enabled rules influence the plan, and each rule's force is either an obligation or a preference.
**Optimization rule**:
A preference rule that minimizes or maximizes a measure over selected planning elements, such as leave balances, time-off periods, or work sequences.
**Optimization rule preset**:
A predefined optimization rule configuration supplied by the application that the user can use as an editable planning rule.
**Loss prevention rule**:
An optimization rule that minimizes unplaced at-risk leave.
**Obligation rule**:
A planning rule that every valid plan must satisfy. Obligation rules are resolved jointly; their order only breaks ties between valid plans.
**Obligation solution**:
One way to satisfy every obligation rule jointly, before any preference rule applies. When there are several, the planner ranks them on their obligation-only plans by the planning objective order and its final tie-breaks, and completes the planning objective order from the best-ranked one only.
**Preference rule**:
A planning rule that guides placement but may remain unsatisfied to preserve validity or prevent more at-risk leave from expiring.
A planning rule that guides placement but may remain unsatisfied to preserve validity or satisfy higher-priority preferences.
**IF_THEN rule**:
A planning rule evaluated independently for every French public holiday on its configured weekday. A preference requests a complete pattern around each occurrence when possible; an obligation requires it for every occurrence.
**IF_THEN placement mode**:
`before` and `after` fix every requested day on one side; `around` considers every split with at least one day on each side; `auto` considers every split, including the all-before and all-after extremes.
`before` and `after` fix every requested day on one side; `around` considers every split with at least one day on each side; `auto` considers every split, including the all-before and all-after extremes. Each side takes the Monday-to-Friday dates nearest the occurrence, skipping only weekends; a split whose side would reach a weekday public holiday is unavailable.
**Samedi Malin**:
The default IF_THEN preference that earns one Other day for a public holiday falling on a Saturday when CP leave placements or declared CP days surround it with at least one working day on each side, or precede or follow it with at least two. RTT and Other days do not count, and a weekday public holiday interrupts a side: in 2027, Saturday 8 May cannot be preceded by two CP days because Thursday 6 May is Ascension.
**TIME_WINDOW rule**:
A planning rule counting compatible leave placements and declared non-working days in an inclusive date window. A preference requests up to its configured quantity; an obligation requires exactly that quantity.
**Rule priority**:
The user-defined lexicographic order of preference rules. Each earlier preference is satisfied as far as possible before a later preference is considered.
The user-defined lexicographic order shared by all active preference rules, including optimization rules. Each earlier preference is satisfied as far as possible before a later preference is considered.
**Rule satisfaction**:
The relationship in which a plan fulfils a planning rule. One compatible leave placement or declared non-working day may contribute to the satisfaction of multiple rules.
@@ -120,23 +142,8 @@ The numerical summary of a calculated valid plan's leave usage, time-off periods
A stable account of why an optimization result or incomplete calculation contains its displayed leave placements, expressed through placement provenance, planning objectives, time-off periods, and remaining balances. It reports every contribution of a placement while highlighting the first planning objective that made its position decisive, and describes the displayed plan rather than the calculation history.
_Avoid_: calculation explanation
**Calculation trace**:
The complete, untruncated, ordered history of the planning decisions and candidate evaluations from the same calculation that produced a planning outcome, grouped by calculation phase. It is not reconstructed by replaying the calculation afterward; for an incomplete calculation it ends at the actual interruption point.
_Avoid_: plan explanation
**Planning decision**:
An atomic choice within a calculation phase that accepts, moves, removes, or rejects one or more related leave placements. A joint obligation decision may therefore concern several dates.
_Avoid_: calendar day, step
**Candidate evaluation**:
The comparison the planner actually performs between a possible leave-placement change and the current plan. It belongs to the calculation trace whether the candidate is accepted or rejected.
**Candidate date status**:
The historical relationship between a date and a planning decision: chosen, evaluated and rejected, not examined, or ineligible with a reason. A later counterfactual date analysis never changes this historical status.
**Counterfactual date analysis**:
An on-demand evaluation that changes only the date of one selected leave placement while preserving its leave balance, leave type, and placement provenance. The planner did not necessarily examine that date; the analysis explains a hypothetical alternative but never influences the planning outcome and is not part of the calculation trace.
_Avoid_: candidate evaluation, calculation trace
An on-demand hypothetical comparison of another date for a displayed leave placement. It uses the immutable calculation configuration and final-state snapshot, preserving the same leave entitlement, leave type, and placement provenance while keeping unrelated placements fixed. It never mutates the displayed plan.
**Conflict explanation**:
A stable account of why no plan can jointly satisfy a set of obligation rules within the planning horizon and available leave balances.
@@ -154,17 +161,19 @@ The result of a calculation: invalid input, a planning conflict, an optimization
**Stable plan explanation**:
A deterministic explanation derived from the final displayed plan. It identifies each placement's entitlement and rule provenance, contributions, full objective vector, and the first objective that distinguishes the plan with that placement restored from the same plan with only that placement removed.
**Original decision trace**:
The untruncated phase-by-phase record captured by the calculation that produced the displayed outcome, including atomic decisions, candidate statuses, and state deltas. It is historical evidence and is never recomputed from the final plan.
**Counterfactual date analysis**:
A hypothetical comparison that keeps the calculation snapshot and all unrelated placements fixed while testing one selected placement across every date in the half-open planning horizon. It neither mutates the plan nor rewrites the original trace.
**Incomplete calculation**:
A calculation stopped by user cancellation or another interruption before it completed the planning objective order. On user cancellation it exposes its best available valid plan as partial, if one exists, and never implies that the obligations conflict.
A calculation stopped before it completed the planning objective order, by user cancellation or another interruption such as a lost connection. It exposes its best available valid plan as partial, if one exists, and never implies that the obligations conflict.
**Planning stage**:
One reported step of a calculation: preparation, validation, obligations, one stage per active preference rule in rule order, expiry, then dates. Stages describe what the calculation is doing, not how far it has progressed.
_Avoid_: phase, quality stage
**Indicative wait**:
The estimated duration of a calculation, shown as a range before Calculate and as an approximate remaining time during it. It is a rough guide refined by the device's own completed calculations, never a deadline.
_Avoid_: ETA, timeout, deadline
**Planning objective order**:
The lexicographic quality order applied after joint obligation feasibility: minimize unplaced at-risk leave; satisfy each preference in user order; maximize public-holiday week value; maximize non-working-day gain; minimize the longest work sequence; minimize the total deficit of internal work sequences shorter than five days; minimize supporting placements; consume earlier-expiring balances; then prefer earlier placement dates. Complete holiday weeks therefore precede broader calendar-gain and work-sequence optimization. A lower criterion never degrades a higher one.
The lexicographic quality order applied after joint obligation feasibility, with active preference rules, including optimization rules, sharing the user-defined rule priority. A lower criterion never degrades a higher one.
**Earned leave**:
The total quantity of earned leave entitlements generated by all applicable planning rules for a plan, counted before consumption and attributed to their generating rules. Only entitlements becoming available strictly after the calculation's Europe/Paris calendar date qualify, including those becoming available after the planning horizon.
@@ -180,4 +189,6 @@ A valid deterministic plan produced after completing the planning objective orde
Any quantity left unspent by the optimization result, reported as unavoidable expiry, an unplaced at-risk balance, or a deferred balance.
**Non-placement reason**:
A concrete explanation of why a quantity of a leave balance remains unspent in the displayed plan, distinguishing a blocking condition from a decision to preserve leave for later. It includes the relevant dates, is distinct from the balance's expiry-based classification, and can be supported by recorded candidate evaluations.
A concrete explanation of why a quantity of a leave balance remains unspent in the displayed plan, distinguishing a blocking condition from a decision to preserve leave for later. It includes the relevant dates, is distinct from the balance's expiry-based classification and is derived from the displayed plan.
The original decision trace, historical date analysis, historical calendar replay, candidate statuses, and remaining-balance attempt lists were removed by issue #76. Calculations retain only the snapshots needed for outcomes, cancellation recovery, stable explanations, and displayed-placement date analysis.
+10 -28
View File
@@ -1,48 +1,30 @@
# Stage 1: Build the Angular application
FROM oven/bun:alpine AS builder
# Stage 1: Build the Angular application and the Bun static server
FROM oven/bun:1.4.3-alpine@sha256:629e17411f1f129dbec3af78d5af9c9f2a937435c80349437206c6b0b7422373 AS builder
# Install nodejs to support Angular prerendering worker threads
RUN apk add --no-cache nodejs
# Set working directory
WORKDIR /app
# Copy package files
COPY package.json bun.lock* ./
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
# Install dependencies
RUN bun install
# Copy source code
COPY . .
# Build the application for production
# bunfig.toml makes the Node-shebang Angular CLI run on Bun; the image has no Node
RUN bun run build
# Stage 2: Production image
FROM oven/bun:alpine AS production
FROM oven/bun:1.4.3-alpine@sha256:629e17411f1f129dbec3af78d5af9c9f2a937435c80349437206c6b0b7422373 AS production
# Set working directory
WORKDIR /app
# Copy package files
COPY package.json bun.lock* ./
# Install only production dependencies
RUN bun install --production
# Copy built application from builder stage
# The server is a self-contained Bun bundle that serves the browser build, so
# the runtime has no dependencies to install.
COPY --from=builder /app/dist ./dist
# Set environment to production
ENV NODE_ENV=production
# Expose port (default Express port)
EXPOSE 4000
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
CMD bun -e "require('http').get('http://localhost:4000', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"
CMD bun -e "fetch('http://localhost:' + (process.env.PORT || 4000) + '/').then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))"
# Start the application
CMD ["bun", "run", "dist/vac-optimizer/server/server.mjs"]
CMD ["bun", "dist/vac-optimizer/server/server.js"]
+121 -48
View File
@@ -2,6 +2,8 @@
VacOptimizer is a personal leave planner for turning dated leave balances into a deterministic plan around weekends and French public holidays. It handles mandatory rules, ordered preferences, earned leave, expiring balances, and interrupted calculations without relying on a backend solver.
Source code, issues, and pull requests are hosted on [Gitea](https://gitea.nessar.fr/nessar/vac-optimizer). The [issue-tracker guide](docs/agents/issue-tracker.md) documents `tea-cli` access and tracker conventions.
The planner answers these questions:
- Is the request valid?
@@ -9,20 +11,30 @@ The planner answers these questions:
- What is the best plan found by the ordered heuristic?
- If calculation stops early, what valid incumbent is available?
- Why did each displayed placement survive the objective order?
- Which alternatives were considered, and what would another date change?
- What would another date change for a displayed placement?
## Architecture
```mermaid
flowchart LR
Host["Express production host<br/>static and client assets"] -. serves .-> UI
subgraph Server
Host["Bun static server<br/>client assets + planning sockets"]
ServerWorker["Leave-planner Bun Worker"]
ServerCore["Resumable planner core"]
ServerHolidays["date-holidays<br/>French public calendar"]
Host -- "one worker per socket" --> ServerWorker
ServerWorker --> ServerCore
ServerCore --> ServerHolidays
end
subgraph Browser
UI["Angular standalone components"]
State["Signals + localStorage<br/>settings, balances, rules"]
Duration["Indicative duration<br/>session-local calibration"]
Facade["Planning calculation context<br/>immutable snapshot + async artifacts"]
Worker["Leave-planner Web Worker"]
Socket["Planning socket<br/>same-origin WebSocket"]
Worker["Leave-planner Web Worker<br/>local fallback"]
Core["Resumable planner core"]
Holidays["date-holidays<br/>French public calendar"]
@@ -31,29 +43,33 @@ flowchart LR
Duration -- "estimated wait" --> UI
UI -- "rendered-calendar timing" --> Duration
UI -- "Calculate / Cancel" --> Facade
Facade -- "request / cancellation" --> Worker
Facade -- "request / cancellation" --> Socket
Socket -- "/api/planning" --> ServerWorker
Facade -. "no socket or no early server message" .-> Worker
Worker --> Core
Core --> Holidays
Worker -- "heartbeats, progress, checkpoints, outcome" --> Facade
Worker -- "after outcome: explanation + trace batches" --> Facade
Facade -- "trace acknowledgements" --> Worker
Socket -- "heartbeats, progress, checkpoints, outcome" --> Facade
Socket -- "after outcome: stable explanation + final state" --> Facade
Worker -- "same messages as the socket" --> Facade
Facade --> UI
end
Host -. serves .-> UI
```
Leave calculation stays in the browser. The production Express process serves the generated Angular application; it does not participate in planning. Browser calculations run cooperatively in a dedicated worker. The resumable core is emitted as a separate worker/lazy chunk and retains a synchronous adapter for direct core callers. Trace delivery uses bounded batches with receiver acknowledgements; large calendars and traces can still cause UI pauses and substantial memory use, as recorded in the benchmark report.
Leave calculation runs on the server by default, for every device, so the wait does not depend on the device. The production Bun process serves the generated client-only Angular application and accepts one planning WebSocket per worker job (a plan, an incomplete-checkpoint explanation or a counterfactual analysis) at `/api/planning`; each socket runs the planner worker in a Bun Worker. If the socket cannot open, does not open within about 5 seconds, or closes before sending any message, the browser starts its own Web Worker without notice and replays the messages posted so far, including an early Cancel. Development and test runs have no build identifier, so they skip the socket and calculate locally (see [Local development](#local-development)). The resumable core is emitted as a separate worker/lazy chunk and retains a synchronous adapter for direct core callers. The original decision trace and historical analysis were removed in issue #76; immutable checkpoints and final state remain available for cancellation recovery and displayed-placement alternatives.
### Main execution path
1. `PlanningDurationService` reads the pending horizon, balances, and ordered rules to estimate the wait without running the planner.
2. On startup or an explicit Calculate action, `CalendarYear` submits those inputs through `CalendarService`, which opens one immutable planning calculation context.
3. `leave-planner.service.ts` copies the request into a canonical transport shape and starts the worker.
4. `leave-planner.worker.ts` runs the framework-free core, sends progress and valid checkpoints, publishes the outcome first, then delivers its stable explanation and original trace.
2. On startup or an explicit Calculate action, `CalendarYear` submits those inputs through `PlanningCalculationService`, which opens one immutable planning calculation context.
3. `leave-planner.service.ts` takes one frozen structured clone of the request, with the Europe/Paris calendar date it fixes, and starts a worker job. The job opens the planning socket at `/api/planning`, or starts the local Web Worker on fallback.
4. `leave-planner.worker.ts` binds the planner's message handler (`leave-planner.message-handler.ts`) to its port; the handler runs the framework-free core in the server's Bun Worker (or in the browser fallback), sends progress and valid checkpoints, publishes the outcome first, then delivers its stable explanation and final state.
5. `CalendarYear` ignores stale calculations, renders the selected dates, reports remaining balances or errors, and records successful request-to-rendered-calendar timing for duration refinement.
Calculations run until all objectives complete or the user cancels; there is no automatic elapsed-time cutoff. During preparation and optimization, Cancel interrupts the worker cooperatively and preserves its best jointly valid candidate as a cancelled, incomplete calculation. A cancellation before a valid candidate reports no plan. The final calendar is delivered before the explanation and complete original trace, whose later arrival or failure cannot change the retained plan. Worker heartbeats distinguish responsive long phases from a worker that stops responding. See [the cancellation mechanism and checks](docs/planner-cancellation.md).
Calculations run until all objectives complete or the user cancels; there is no automatic elapsed-time cutoff. During preparation and optimization, Cancel interrupts the worker cooperatively and preserves its best jointly valid candidate as a cancelled, incomplete calculation. A cancellation before a valid candidate reports no plan. The final calendar is delivered before the stable explanation, whose later arrival or failure cannot change the retained plan. Worker heartbeats distinguish responsive long phases from a worker that stops responding. A connection lost after the first server message gives an incomplete calculation with the best valid plan already received, without an automatic retry; it shows as a warning (`connection-lost`), not a planner error, and the person can calculate again. A close the server sends for a worker failure or a protocol violation (codes 1003, 1007, 1008, 1009 and 1011) stays a `worker-error`. See [the cancellation mechanism and checks](docs/planner-cancellation.md).
Technical callers may explicitly supply `deadlineMs`, a finite non-negative planning-work budget of any size. Omission means no deadline; the calendar and benchmark never supply one. This opt-in budget starts after calendar preparation and excludes trace capture, observer callbacks, and post-outcome artifact work. Expiry returns `PlanningIncomplete` with the latest valid checkpoint, if any, rather than a conflict. It is independent of worker liveness monitoring.
Technical callers may explicitly supply `deadlineMs`, a finite non-negative planning-work budget of any size. Omission means no deadline; the calendar and benchmark never supply one. This opt-in budget starts after calendar preparation and excludes observer callbacks and post-outcome explanation work. Expiry returns `PlanningIncomplete` with the latest valid checkpoint, if any, rather than a conflict. It is independent of worker liveness monitoring.
## Planning model
@@ -69,7 +85,7 @@ Rules are either:
- **obligations**, which must all be feasible in the same plan; or
- **preferences**, optimized lexicographically in user order.
`TIME_WINDOW` places a quantity inside an inclusive date window. `IF_THEN` creates before, after, around, or automatic patterns for each matching French public holiday. A completed `IF_THEN` occurrence may earn a new dated leave entitlement after its final time-off period ends.
`TIME_WINDOW` places a quantity inside an inclusive date window. `IF_THEN` creates before, after, around, or automatic patterns for each matching French public holiday, from the nearest weekdays on each side; a weekday public holiday interrupts a side. A completed `IF_THEN` occurrence may earn a new dated leave entitlement after its final time-off period ends.
The outcome is one of:
@@ -84,7 +100,7 @@ All planning dates are normalized as `YYYY-MM-DD` calendar values in the Europe/
Settings save a fixed start date and an inclusive last planning date. The planner's exclusive end is the following calendar date, so matching settings dates cover one day. Without saved dates, the default is today in Europe/Paris through the same date twelve months later, exclusive (February 29 uses February 28 in the following year). Invalid edits prevent calculation and preserve the last valid saved dates. Changes to dates, balances, and rules apply to the displayed calendar on the next explicit Calculate action.
An indicative range beside Calculate follows the current dates, balances, and rules. Completed plans refine it locally for the current browser session using request-to-rendered-calendar time; later trace delivery is excluded. The range never stops a calculation. See [the duration model and measurement contract](docs/planning-duration.md).
An indicative range beside Calculate follows the current dates, balances, and rules. Completed plans refine it locally for the current browser session using request-to-rendered-calendar time; later explanation delivery is excluded. The range never stops a calculation. See [the duration model and measurement contract](docs/planning-duration.md).
## Optimization pipeline
@@ -132,7 +148,7 @@ stateDiagram-v2
Plan --> [*]
```
`PlanningIncomplete` is reachable from every active calculation state. Cancellation retains the best available jointly valid candidate, even before a stage completes; completed stages also publish checkpoints for other interruption paths. An explicit technical deadline applies only after calendar preparation, while worker failure can interrupt any active phase. `PlanningConflict` is produced only when the obligations are valid but jointly infeasible. Outcome delivery does not wait for explanation or trace completion.
`PlanningIncomplete` is reachable from every active calculation state. Cancellation retains the best available jointly valid candidate, even before a stage completes; completed stages also publish checkpoints for other interruption paths. An explicit technical deadline applies only after calendar preparation, while worker failure can interrupt any active phase. `PlanningConflict` is produced only when the obligations are valid but jointly infeasible. Outcome delivery does not wait for explanation completion.
1. validate and normalize the request;
2. find joint obligation assignments;
@@ -148,9 +164,9 @@ stateDiagram-v2
Every placement records its source balance and all rules it satisfies. Remaining balances are classified as unavoidable expiry, at risk, or deferred.
The calendar keeps plan details and the advanced trace collapsed initially. Plan details navigate final placements chronologically, showing provenance, contributions, the first decisive objective, and the full ordered comparison including obligation validity. **Compare dates** opens an on-demand hypothetical comparison across the submitted horizon, preserving the selected balance, type, and provenance without changing the plan.
The calendar keeps plan details collapsed initially. Plan details navigate final placements chronologically, showing provenance, contributions, the first decisive objective, and the full ordered comparison including obligation validity. **Compare dates** opens an on-demand hypothetical comparison across the submitted horizon, preserving the selected balance, type, and provenance without changing the plan.
The trace explorer navigates original phases and atomic decisions, expands candidate evaluations, and shows before/after calendar states. Historical date statuses remain separate from hypothetical results. Incomplete outcomes explain the retained plan and unfinished phases; conflicts identify the reported obligations and bottleneck. Controls support keyboard navigation, labelled dates, live announcements, and text or icons alongside color. Only the latest trace is retained locally in memory.
Incomplete outcomes explain the retained plan and unfinished phases; conflicts identify the reported obligations and bottleneck. Remaining balances retain their classification, validity, earned-entitlement source and concrete displayed-plan reasons, without historical attempt lists. Controls support keyboard navigation, labelled dates, live announcements, and text or icons alongside color.
## Technical stack
@@ -158,19 +174,19 @@ The trace explorer navigates original phases and atomic decisions, expands candi
- Angular Material and CDK
- Signals for UI state and local storage for settings, edited leave balances, and rules
- TypeScript 6
- Web Workers for planner isolation
- Bun Workers on the server and Web Workers in the browser for planner isolation; the Web Worker is the local fallback
- `date-holidays` for the French public calendar
- Bun for dependency management and project scripts
- Vitest through the Angular test builder
- ESLint and Prettier
- Angular server build hosted by Express
- GitLab CI and a multi-stage Docker image
- `bun test` with jsdom and Angular TestBed (JIT)
- ESLint and Prettier, run by Bun, and `bun check` for standalone type checking
- Client-only Angular build served by a small `Bun.serve` static server (`src/server.ts`), which also accepts planning WebSockets at `/api/planning`
- Gitea repository hosting and a multi-stage Docker image
The `/benchmark` route and planner core are lazy-loaded, so the normal application does not execute the benchmark or bundle the planner core into its main entry point.
The header opens one Settings dialog for planning dates, System / Light / Dark theme selection, English / French / German / Spanish language selection, and ISO week numbers. Changes apply and save on selection; closing the dialog retains them. System follows device appearance changes.
Saved balances, including an empty list, are restored before the initial calculation. When no readable saved list exists, CP, RTT, and Other start with random quantities from 10 through 20. These defaults remain unsaved until the first balance edit; subsequent edits save the entire list with identities, order, quantities, types, and calendar dates. Invalid saved balance data is cleared without removing unrelated settings or rules.
Saved balances, including an empty list, are restored before the initial calculation. When no readable saved list exists, the list starts empty and stays unsaved until the first balance edit; every balance edit saves the entire list with identities, order, quantities, types, and calendar dates. Invalid saved balance data is cleared without removing unrelated settings or rules. An empty list shows an invitation to add a balance. With no leave balance and no declared non-working day, nothing is calculated and Calculate is disabled; the results panel shows the planning horizon's calendar with its weekends and public holidays.
## Repository layout
@@ -180,7 +196,7 @@ src/app/
├── components/ # Calendar, inputs, rules, and settings UI
├── services/
│ ├── leave-planner.service.ts # Canonical async planning boundary
│ ├── leave-planner.worker.ts # Browser worker adapter
│ ├── leave-planner.worker.ts # Worker entry: server Bun Worker and browser fallback
│ ├── leave-planner.core.ts # Framework-free planning algorithm
│ ├── calendar-service.ts # Calendar projection and UI integration
│ ├── calendar-settings-service.ts # Persisted horizon and week-number settings
@@ -197,9 +213,10 @@ CONTEXT.md # Canonical domain language and rules
## Local development
Prerequisite: [Bun](https://bun.sh/). Dependency versions are locked in `bun.lock`.
Prerequisite: [Bun](https://bun.sh/) 1.4.3, the exact version pinned by `packageManager` in `package.json` and used by CI and the Docker image. Node.js is not needed. Dependency versions are locked in `bun.lock`.
```bash
curl -fsSL https://bun.sh/install | bash -s "bun-v1.4.3"
bun install --frozen-lockfile
bun start
```
@@ -208,22 +225,31 @@ Open <http://localhost:4200>. The development server reloads when source files c
### Useful commands
| Command | Purpose |
| ----------------------------------------- | ------------------------------------------------------------ |
| `bun start` | Generate the i18n registry and start the development server. |
| `bun run test --watch=false` | Run the unit and integration suite once. |
| `bun run lint` | Run ESLint. |
| `bun run format:check` | Check Prettier formatting. |
| `bunx tsc --noEmit -p tsconfig.app.json` | Type-check application code. |
| `bunx tsc --noEmit -p tsconfig.spec.json` | Type-check tests. |
| `bun run build` | Create the optimized browser and server bundles in `dist/`. |
| `bun run serve:ssr:vac-optimizer` | Serve a completed production build on port 4000. |
| Command | Purpose |
| ------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `bun start` | Generate the i18n registry and start the development server. |
| `bun run watch` | Rebuild the development bundle when source files change. |
| `bun run test` | Run the unit, integration and benchmark suites once. |
| `bun test --isolate --path-ignore-patterns='**/benchmark/**'` | Run the functional suite only. |
| `bun test src/app/benchmark --timeout=240000` | Run the planning benchmark (no coverage). |
| `bun test --config=bunfig.coverage.toml --isolate --path-ignore-patterns='**/benchmark/**' && bun scripts/coverage-reports.mjs` | Functional coverage: text, `lcov.info`, HTML and Cobertura in `coverage/`. Line coverage only; frozen engine excluded. |
| `bun run lint` | Run ESLint (`bun run lint:fix` applies its fixes). |
| `bun run format:check` | Check Prettier formatting of the application, the CI scripts and the workflow (`bun run format` writes it). |
| `bun run typecheck` | Type-check application and test code with `bun check`. It does not check Angular templates; only the build does. |
| `bun run build` | Create the optimized browser bundle and the static server bundle in `dist/vac-optimizer/`, sharing one build id. |
| `bun run serve` | Serve a completed production build on `PORT` (default 4000). |
Only `bun run build` output has a build identifier and plans on the server. Development and test runs (`ng serve`, `bun run watch`, `bun test`) have none and always calculate locally, and a server started from source (`bun src/server.ts`) accepts no planning sockets.
Project scripts run Node-shebang tools (`ng`, `eslint`, `prettier`) on Bun even when Node is installed: `bunfig.toml` sets `[run] bun = true`, which is the `--bun` flag for every `bun run`. Start them through the scripts above. A bare `bunx` or `bun x` uses Node when it is on `PATH`; for a one-off tool, use `bun --bun x <tool>`.
Angular compiles with TypeScript 6. `bun check` is Bun's TypeScript 7 checker for standalone type errors in application and test code. Neither replaces the other: only `bun run build` (Angular's compiler) checks templates, so a passing `typecheck` does not replace the production build. ESLint and Prettier stay until a stable Bun release ships its native linter and formatter ([bun-adoption](docs/bun-adoption.md#status)).
## Performance benchmark
Build or start the application, then open `/benchmark`. The isolated harness covers a representative year, typed obligations, chained earned entitlements, a deliberate conflict, a loaded year, and two- and three-year horizons with dated annual balances. It reports preparation time, planning latency, separate trace-delivery latency, total wall time, UI timer delay, available main-thread heap measurements, outcome, last completed stage, placement count, determinism, and trace size/status.
Build or start the application, then open `/benchmark`. The isolated harness covers a representative year, typed obligations, chained earned entitlements, a deliberate conflict, a loaded year, and two- and three-year horizons with dated annual balances. It reports preparation time, planning latency, planning-work time, total wall time through explanation delivery, UI timer delay, available main-thread heap measurements, outcome, last completed stage, placement count, and determinism.
The release protocol, recorded desktop measurements, and hardware limitations are documented in [docs/benchmark/README.md](docs/benchmark/README.md). No reference-phone run or multi-year duration ceiling is established; timing measurements are release evidence, not CI assertions.
The release protocol, recorded desktop measurements, and hardware limitations are documented in [docs/benchmark/README.md](docs/benchmark/README.md). No reference-phone run or individual multi-year duration ceiling is established. CI runs the complete seven-scenario protocol with `bun test` and requires each scenario to stay within its budget relative to a frozen-engine calibration, with a 240-second hang guard. Bun measurements do not establish browser or reference-phone speedups.
## Docker
@@ -232,24 +258,71 @@ docker build -t vac-optimizer .
docker run --rm -p 4000:4000 vac-optimizer
```
The image builds the Angular application with Bun and Node, then runs the generated Express server with Bun. Set `PORT` to override the default port `4000`.
The image builds the Angular application and the server bundle with Bun alone (no Node), then runs `dist/vac-optimizer/server/server.js` with Bun. The server bundle also includes `leave-planner.worker.js` next to `server.js`, which the server starts for each planning socket. The bundle has no runtime dependencies, so the production stage only copies `dist/` and installs nothing. Set `PORT` to override the default port `4000`; the health check requests `/`.
The server answers `GET` and `HEAD` only (other methods get 405), except at `/api/planning`: a WebSocket upgrade there opens a planning socket, and any other request there gets `426 Upgrade Required`. The server serves files from `dist/vac-optimizer/browser` with `Cache-Control: public, max-age=31536000` (content-hashed assets), and returns `index.html` with `Cache-Control: no-cache` for `/index.html` and for every extension-less path, so direct navigation to client routes such as `/benchmark` works. A missing path with a file extension is a 404 rather than HTML, malformed or escaping paths are a 400, and unexpected failures are logged and answered with a plain 500.
The client sends its build identifier in the `build` query parameter; the server closes a socket from a different build (or without one) with code 4409 before sending any message, so that tab calculates locally with its own engine. Each client IP may hold five planning sockets at once. The IP is the `CF-Connecting-IP` header, or the address of the connection when the header is absent. The server closes a sixth socket from the same IP with code 4429 before sending any message, so that tab calculates locally with its own engine; closing a socket frees its place. The server also closes a socket whose incoming message exceeds about 1 MB (WebSocket code 1009, or an abnormal close) without running a calculation. The per-IP limit holds only if the origin accepts traffic from Cloudflare alone: anyone who can reach the origin directly can forge `CF-Connecting-IP` and bypass it.
At most `PLANNING_WORKERS` calculations run at once, each in its own worker; it defaults to half the CPU threads the container reports, which assumes two threads per core, so set it to the physical core count (throughput stops growing there). Other calculations wait in arrival order and the server sends a heartbeat every second so the client keeps waiting; no queue position is shown. A socket joins the line with its first message, so an idle open socket holds no worker. Closing the socket removes a waiting calculation. A waiting plan that its client cancels starts at once, even beyond `PLANNING_WORKERS`, and stops at its first yield with the worker's own cancelled outcome. A running calculation frees its place when it ends, fails or its socket closes. A client may send one job message and, for a plan, one `cancel` (`PLANNING_JOBS` in `src/app/services/leave-planner.worker-messages.ts` lists each job's follow-ups and terminal responses); any other text message before the job ends closes the socket with code 1008 (binary and invalid JSON get 1003 and 1007), and messages after it ends are ignored. Each calculation takes roughly 60 to 150 MB, and the production Compose file (`compose.prod.yml`) sets an 8 GB memory limit with no CPU limit.
Behind a reverse proxy, forward WebSocket upgrades for `/api/planning`; on Nginx Proxy Manager, enable WebSocket support for the host.
## Continuous integration
GitLab CI runs independent validation, test, build, security, and image stages:
[`.gitea/workflows/ci.yml`](.gitea/workflows/ci.yml) defines Gitea Actions validation, functional coverage, production builds, security scans, and Docker image publication. [Issue #268](https://gitea.nessar.fr/nessar/vac-optimizer/issues/268) tracks activation. Actions is enabled with owner approval; publisher credentials and live workflow validation are still pending. The [activation guide](docs/gitea-actions.md) records runner, credential, permission, and merge-gate requirements.
- ESLint, Prettier, and TypeScript checks;
- Vitest with coverage artifacts;
- an optimized production build;
- GitLab SAST and Trivy filesystem scanning;
- Docker image publication from the default branch.
The workflow runs on pushes to `develop` and `main`, `v*` tag pushes, PR opening/reopening/synchronization/edits, and manual dispatch. Other branches run CI only through their PR, so a branch without a PR gets no automatic CI or image. Manual runs validate without publishing images. Required jobs cover policy regression tests, GitFlow and Conventional Commits, ESLint, Prettier, `bun check` type checks, Bun coverage, the production build, Semgrep SAST, and Trivy dependency/secret scans. Coverage, build output, and SARIF reports are retained for seven days.
Jobs that run project commands install Bun 1.4.3 with `scripts/install-bun.sh` (a checksum-verified download, no npm) and run their steps with a `PATH` that holds Bun but no Node. The job containers keep Node only for Gitea's checkout and artifact actions, which are JavaScript actions the runner executes itself; see the [activation guide](docs/gitea-actions.md#runners-and-permissions).
Functional tests run with `bun test --isolate`; coverage is line-level only (Bun reports no branch or function data). The separate required benchmark job runs without coverage in a container limited to 3 GiB (JavaScriptCore has no heap-size flag, so this replaces the former 2 GiB Node heap cap) and keeps its 240-second hang guard, one warm-up and two measured repetitions of all seven scenarios. [#78](https://gitea.nessar.fr/nessar/vac-optimizer/issues/78) restored this gate after a complete local pass in 298.6 seconds; see [the measurements and hardware limits](docs/benchmark/issue-78.md). After [#302](docs/benchmark/issue-302.md) the local protocol takes about 41 seconds. Benchmark success is required for image publication and the aggregate `required` job. The lowered hang guard and tightened multipliers still need confirmation on the CI runners.
The `required` job aggregates successful validation and expected image publication, accepting the image job's intentional skip for fork PRs and manual runs. Image jobs require successful validation and are limited to pushes to `develop`, `main` and release tags, and same-repository PRs. Registry credentials are confined to the publishing step.
Both protected branches still require `gitlab-to-gitea/ci-conversion-required` until the owner approves the first merge message and a successful Gitea PR run, then replaces the migration gate with the actual pull-request context for `required`. Local validation does not satisfy this status. Historical CI reports and artifacts remain in administrator rollback backups; the original configuration is retained in Git history.
### GitFlow and releases
`develop` is the default integration branch. Create `feature/*` branches from it, rebase them onto the current `origin/develop` before opening or merging their PR, and merge into `develop` with a merge commit (`--no-ff`). Existing working-branch names such as `feat/*` follow the same rules. Working branches cannot merge `develop` into themselves instead of rebasing.
Create `release/X.Y.Z` from `develop` when the release scope is ready. Set `package.json` to `X.Y.Z` on this branch, stabilize it, then merge it into `main` and back into `develop`. Keep the release branch until both PRs have merged. A `hotfix/X.Y.Z` starts from `main`, changes the package version, and follows the same two-target merge process. Do not rebase `main`, `develop`, or a frozen release onto ongoing development.
Use Conventional Commits for new commits and PR titles, for example `feat(calendar): add planning periods`, `fix(planner): handle expired balances`, or `chore(release): prepare 1.6.0`. Scopes are optional; `!` marks a breaking change. The merge commit subject must preserve the validated PR title. Gitea supports a [Git-based merge-message template](https://docs.gitea.com/usage/issues-prs/merge-message-templates/) at `.gitea/default_merge_message/MERGE_TEMPLATE.md`, using `${PullRequestTitle}` and `${PullRequestReference}`. The committed template and a checked example expansion are documented in the [activation guide](docs/gitea-actions.md); legacy history is not rewritten.
The image publisher implements this tag contract in `gitea.nessar.fr/nessar/vac-optimizer`:
| Trigger | Published image tags |
| --- | --- |
| Successful push to `develop` or `main`, or same-repository PR | `branch-<normalized branch slug>` and `sha-<full commit SHA>` |
| Explicit release tag `vX.Y.Z` | `vX.Y.Z` and `latest`, using the existing SHA image |
For example, `feature/calendar` uses `branch-feature-calendar`; integration uses `branch-develop`. Preserve the previous slug normalization: lowercase the branch name, replace characters other than `a-z` and `0-9` with `-`, truncate to 63 bytes, and remove leading/trailing `-`. Choose branch names with distinct slugs. Only valid release tags can update `latest`. Automatic image publication and tag promotion begin after the owner provisions publisher credentials and validates publication permissions.
After owner activation, the PR into `main` has merged, and its full checks and SHA image publication have succeeded, tag the published main commit:
```bash
git fetch origin
git tag -a v1.6.0 origin/main -m "Release 1.6.0"
git push origin v1.6.0
```
The tag must match the tagged commit's `package.json` version, use stable `vMAJOR.MINOR.PATCH` syntax, and point to a commit reachable from `main`. Wait for the main checks and image publication before tagging: promotion requires its `sha-<commit>` image. Tags do not increment the version automatically.
The Gitea repository policy requires `develop` as the default branch and **Merge commit** as the merge method, with squash and rebase merge methods disabled. Configure [branch protection](https://docs.gitea.com/usage/access-control/protected-branches/) for `main` and `develop` to disable direct and forced pushes, restrict the merge allowlist to designated maintainers, require successful status checks, and block outdated PRs. Administrators must follow the protection rules. The `develop` allowlist also admits the `renovate` bot: [renovate.json](renovate.json) automerges minor, patch, digest, and pin updates three days after their release once the `required` check passes, and leaves major updates for manual review. After merge-message approval and a successful reviewed PR run, replace the migration gate with the reported pull-request context for the `required` job, as described in the activation guide. These are required settings; the migration does not establish that every setting has already been applied.
Only `release/*` and `hotfix/*` PRs may target `main`; working PRs target `develop`. CI validates these rules and checks working-branch rebases against the fetched integration head. If `develop` advances after validation, rebase and rerun the PR checks before merging.
Run `bun scripts/ci-policy.test.mjs` and `bun scripts/ci-image.test.mjs` locally to verify GitFlow event handling and image publication without writing to a registry. The adapter reads Gitea webhook data through the runner's `GITHUB_*` compatibility variables. Local checks do not satisfy the migration gate.
## Domain and design references
- [CONTEXT.md](CONTEXT.md) defines the project vocabulary and planner semantics.
- [ADR 0001](docs/adr/0001-ordered-heuristic-optimization.md) records the ordered heuristic decision.
- [ADR 0002](docs/adr/0002-personal-client-side-planner-for-now.md) records the client-side scope.
- [ADR 0002](docs/adr/0002-personal-client-side-planner-for-now.md) records the original client-side scope, superseded by ADR 0011.
- [ADR 0003](docs/adr/0003-constraint-first-lexicographic-planning.md) records the constraint-first planner architecture.
- [ADR 0004](docs/adr/0004-stable-explanation-original-trace-counterfactual.md) separates the outcome, stable explanation, original trace, and hypothetical analysis.
- [ADR 0005](docs/adr/0005-saved-planning-inputs-before-random-defaults.md) records saved-input restoration and random fallback behavior.
- [ADR 0004](docs/adr/0004-stable-explanation-original-trace-counterfactual.md) separates the outcome, stable explanation and displayed-placement hypothetical analysis.
- [ADR 0005](docs/adr/0005-saved-planning-inputs-before-random-defaults.md) records saved-input restoration; its random fallback is superseded by ADR 0012.
- [ADR 0006](docs/adr/0006-user-selected-horizons-and-cancellable-calculations.md) records fixed saved horizons, cancellation, duration estimation, and the removal of the automatic deadline.
- [ADR 0011](docs/adr/0011-server-side-planning-for-every-device.md) records server-side planning for every device with a local fallback.
- [ADR 0012](docs/adr/0012-empty-leave-balances-on-first-visit.md) starts from an empty leave-balance list instead of random balances.
-9
View File
@@ -29,12 +29,6 @@
"styles": [
"src/styles.scss"
],
"server": "src/main.server.ts",
"outputMode": "server",
"ssr": {
"entry": "src/server.ts"
},
"prerender": false,
"allowedCommonJsDependencies": [
"deepmerge",
"moment-timezone",
@@ -85,9 +79,6 @@
},
"extract-i18n": {
"builder": "@angular/build:extract-i18n"
},
"test": {
"builder": "@analogjs/vitest-angular:test"
}
}
}
+75 -6533
View File
File diff suppressed because it is too large. Load diff
+8
View File
@@ -0,0 +1,8 @@
[test]
preload = ["./src/test-setup.ts"]
root = "src"
coverage = true
coverageReporter = ["text", "lcov"]
coverageDir = "coverage"
coverageSkipTestFiles = true
coveragePathIgnorePatterns = ["**/frozen-engine/**", "**/testing/**", "**/test-setup.ts"]
+7
View File
@@ -0,0 +1,7 @@
[run]
# Node-shebang tools (ng, eslint, prettier) run on Bun even when Node is on PATH.
bun = true
[test]
preload = ["./src/test-setup.ts"]
root = "src"
+4 -3
View File
@@ -11,13 +11,15 @@ services:
environment:
- NODE_ENV=production
- PORT=4000
# Concurrent calculations; defaults to half the CPU threads. Set it to the physical core count.
- PLANNING_WORKERS
healthcheck:
test:
[
'CMD',
'bun',
'-e',
"require('http').get('http://localhost:4000', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})",
"fetch('http://localhost:' + (process.env.PORT || 4000) + '/').then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))",
]
interval: 30s
timeout: 10s
@@ -26,8 +28,7 @@ services:
deploy:
resources:
limits:
cpus: '1.0'
memory: 512M
memory: 8G
reservations:
cpus: '0.5'
memory: 256M
+3 -1
View File
@@ -11,13 +11,15 @@ services:
environment:
- NODE_ENV=production
- PORT=4000
# Concurrent calculations; defaults to half the CPU threads. Set it to the physical core count.
- PLANNING_WORKERS
healthcheck:
test:
[
'CMD',
'bun',
'-e',
"require('http').get('http://localhost:4000', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})",
"fetch('http://localhost:' + (process.env.PORT || 4000) + '/').then(r => process.exit(r.ok ? 0 : 1), () => process.exit(1))",
]
interval: 30s
timeout: 10s
@@ -1,3 +1,5 @@
# Personal Client-Side Planner for Now
Superseded by [ADR 0011](0011-server-side-planning-for-every-device.md): the server plans for every device, and the privacy of leave data is no longer a constraint.
VacOptimizer remains a single-person planner without accounts, backend synchronization, or employer integration for now. This keeps leave data private and setup-free at the cost of cross-device persistence and collaboration; revisit if those needs become real.
@@ -2,4 +2,8 @@
The ten-second automatic deadline is superseded by [ADR 0006](0006-user-selected-horizons-and-cancellable-calculations.md), implemented by issue #59. Technical callers can still opt into an explicit planning-work budget; the user flow has no automatic cutoff.
The five-second target is revisited by [ADR 0010](0010-rank-obligation-solutions-before-preferences.md), which sets local benchmark targets of ten seconds for the loaded year, five seconds for multi-year horizons and three seconds otherwise.
The fixed ordering between user preferences and configurable optimization objectives, including the unconditional priority for at-risk loss prevention, is superseded by [ADR 0008](0008-user-controlled-planning-objectives.md); implementation of that decision is pending.
VacOptimizer resolves obligation rules exactly and jointly, then applies deterministic heuristic stages for at-risk loss, ordered preferences, complete public-holiday weeks, calendar gain, work-sequence quality, supporting placements, balance expiry, and dates in that order; complete holiday weeks therefore precede broader calendar-gain and work-sequence optimization. A completed plan does not claim mathematical global optimality. The dependency-free planner targets five seconds, returns `PlanningIncomplete` if those stages are interrupted, and stops after ten seconds. A HiGHS WebAssembly spike missed that hard limit on representative inputs even on the development machine, so no solver dependency is accepted. This supersedes ADR 0001.
@@ -1,5 +1,7 @@
# Separate Plan Explanations from Calculation Traces
# Stable Plan Explanations Without Decision History
The automatic planning deadline referenced below is superseded by [ADR 0006](0006-user-selected-horizons-and-cancellable-calculations.md), implemented by issue #59. Technical callers can still opt into an explicit planning-work budget; the user flow has no automatic cutoff.
Issue #76 supersedes this ADR's original requirement to capture and deliver a complete calculation trace. The original decision trace, historical analysis, replay and candidate-history retention are removed end to end.
VacOptimizer provides a stable plan explanation separately from the complete, untruncated calculation trace captured during the same planning run; on-demand counterfactual date analysis is identified as hypothetical and never presented as trace history. Explanation and tracing must not alter the planning outcome, so trace instrumentation is excluded from the planner deadline and the result may appear before the latest run's in-memory trace finishes loading; this narrows ADR 0003's ten-second hard limit to planning work rather than end-to-end trace delivery. This accepts additional transient memory and wall-clock time instead of inventing scalar day scores, truncating history, or reconstructing a trace by replay.
The stable explanation describes the displayed plan, including valid incomplete incumbents: entitlement and rule provenance, contributions, the full ordered objective comparison and first decisive objective, time-off periods, remaining balances and concrete non-placement reasons. Invalid input and obligation conflicts retain their distinct explanations.
Outcomes are delivered before explanation work. Explanation failures cannot discard an available outcome. Immutable calculation, valid-incumbent and final-state snapshots remain available for cancellation recovery and hypothetical analysis; they are independent of tracing. ADR 0006's opt-in technical planning-work budget excludes observer callbacks and post-outcome explanation work. The user flow has no automatic elapsed-time cutoff.
@@ -1,11 +1,9 @@
# Stable Explanation, Original Trace, and Counterfactuals
# Stable Explanation and Displayed-Placement Counterfactuals
The automatic planning deadline referenced below is superseded by [ADR 0006](0006-user-selected-horizons-and-cancellable-calculations.md), implemented by issue #59. Technical callers can still opt into an explicit planning-work budget; the user flow has no automatic cutoff.
Issue #76 supersedes the original decision-trace and historical-counterfactual requirements of this ADR. Calculations no longer capture, retain or deliver decision history, and the UI has no trace explorer, replay, historical candidate statuses or balance-attempt lists.
VacOptimizer exposes one client-side calculation context. Its immutable submitted snapshot and planning outcome are independent from three explanation concerns:
VacOptimizer exposes one client-side calculation context with an immutable submitted configuration. Its outcome is independent from the stable explanation, which describes the final displayed plan and remains useful for complete and valid incumbent plans.
- the stable plan explanation is derived from the final displayed plan and remains useful for complete or incumbent plans;
- the calculation trace is captured while the producing run executes, grouped by phase and atomic decision, and may become ready after the outcome;
- counterfactual date analysis is an explicitly hypothetical operation that removes only the selected final placement, or starts from a selected trace decision's exact pre-decision state, and never rewrites the plan or historical trace.
Counterfactual date analysis tests a displayed placement over every date of the submitted half-open horizon. It uses the captured configuration and final-state snapshot, releases only that placement, preserves its entitlement, leave type and rule provenance, and fixes unrelated placements. Earned-entitlement chronology and all obligations still apply. The result is explicitly hypothetical and never mutates the displayed plan. Historical decisions are not selectable analysis baselines.
The public planning outcome is delivered as soon as planning work finishes. Trace capture and delivery have separate readiness/failure state, remain local to the latest calculation, and cannot turn a valid outcome into an explanation error. Counterfactual work is cancellable or ignored when its calculation identity is stale. The existing deterministic constraint-first planner and its planning-work deadline remain unchanged.
The public outcome is delivered as soon as planning work finishes. Explanation delivery failures cannot replace it. Counterfactual work is cancelled or ignored when its calculation identity is stale. Search breadth, allocation previews, user priorities, deterministic selection and ADR 0006's cancellation, liveness and technical-budget contracts remain unchanged. Workers finish after required outcome and explanation delivery without acknowledgement queues.
@@ -1,3 +1,5 @@
# Restore Saved Planning Inputs Before Generating Random Defaults
[ADR 0012](0012-empty-leave-balances-on-first-visit.md) supersedes the random initial balances below: an absent or unreadable saved list now starts empty. Restoring saved inputs, deleting unreadable data first and saving the whole list on every balance edit are unchanged.
VacOptimizer restores a single locally saved leave-balance list, including an intentionally empty list, with its quantities, leave types, availability dates, and expiry dates; planning rules retain their existing local persistence. Random initial balances are generated when the saved balance list is absent or unreadable: unreadable balance data is deleted first, and the generated list remains unsaved until the first balance edit, after which every balance edit automatically saves the entire current list. Restoring valid saved inputs before initialization prevents random defaults from overwriting user data and keeps a single dataset within the client-side scope of ADR 0002.
@@ -1,17 +1,21 @@
# User-Selected Horizons and Cancellable Calculations
Accepted for [issue #12](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/12). Fixed, saved planning horizons are implemented by [issue #57](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/57); user cancellation with a retained valid plan and original trace is implemented by [issue #58](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/58); removal of the automatic calculation deadline and heartbeat-based worker liveness are implemented by [issue #59](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/59). The indicative duration estimate is implemented by [issue #60](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/60); its initial model, session-local refinement and calendar-rendering measurement are documented in [planning-duration.md](../planning-duration.md).
Accepted for [issue #12](https://gitea.nessar.fr/nessar/vac-optimizer/issues/12). Fixed, saved planning horizons are implemented by [issue #57](https://gitea.nessar.fr/nessar/vac-optimizer/issues/57); user cancellation with a retained valid plan is implemented by [issue #58](https://gitea.nessar.fr/nessar/vac-optimizer/issues/58); removal of the automatic calculation deadline and heartbeat-based worker liveness are implemented by [issue #59](https://gitea.nessar.fr/nessar/vac-optimizer/issues/59). The indicative duration estimate is implemented by [issue #60](https://gitea.nessar.fr/nessar/vac-optimizer/issues/60); its initial model, session-local refinement and calendar-rendering measurement are documented in [planning-duration.md](../planning-duration.md).
`deadlineMs` remains an opt-in contract for technical callers: a finite non-negative planning-work budget with no ten-second cap. An omitted value is unlimited. It starts after calendar preparation and excludes trace capture, observer callbacks, and post-outcome artifact work. The calendar and benchmark omit it. A one-second worker heartbeat renews the coordinator's thirty-second inactivity timer during cooperative preparation and search; total elapsed time never triggers that timer while activity continues. Worker errors and unavailable execution retain their explicit outcomes, and monitoring ends when the outcome arrives so delayed trace delivery cannot invalidate it.
[ADR 0011](0011-server-side-planning-for-every-device.md) supersedes the requirement that calculations remain in the browser: the server plans for every device and the browser engine is a fallback. Running to completion without an automatic cutoff, the Cancel action and the retained valid plan are unchanged.
VacOptimizer accepts explicitly selected, fixed planning horizons whose start may be past and whose duration may exceed twelve months, retaining today through the same date twelve months later as the default. Calculations remain in the browser and run to completion without an automatic elapsed-time cutoff, with an indicative duration estimate and an explicit Cancel action; this accepts variable waiting time and resource use to make longer horizons usable without silently changing the user's dates. This supersedes ADR 0003's ten-second automatic planning limit and its retention in both ADR 0004 documents, while preserving the separation between the planning outcome, stable explanation, and original trace.
`deadlineMs` remains an opt-in contract for technical callers: a finite non-negative planning-work budget with no ten-second cap. An omitted value is unlimited. It starts after calendar preparation and excludes observer callbacks and post-outcome explanation work. The calendar and benchmark omit it. A one-second worker heartbeat renews the coordinator's thirty-second inactivity timer during cooperative preparation and search; total elapsed time never triggers that timer while activity continues. Worker errors and unavailable execution retain their explicit outcomes, and monitoring ends when the outcome arrives so delayed explanation delivery cannot invalidate it.
The settings' end date is the inclusive last planning date. The planner retains its half-open horizon by using the following calendar date as its exclusive end, matching the inclusive date-selection convention of TIME_WINDOW rules.
VacOptimizer accepts explicitly selected, fixed planning horizons whose start may be past and whose duration may exceed twelve months, retaining today through the same date twelve months later as the default. Calculations remain in the browser and run to completion without an automatic elapsed-time cutoff, with an indicative duration estimate and an explicit Cancel action; this accepts variable waiting time and resource use to make longer horizons usable without silently changing the user's dates. This supersedes ADR 0003's ten-second automatic planning limit and its retention in both ADR 0004 documents, while preserving the separation between the planning outcome and stable explanation.
The planning-period control in Configure your leave uses an inclusive last planning date. The planner retains its half-open horizon by using the following calendar date as its exclusive end, matching the inclusive date-selection convention of TIME_WINDOW rules.
Editing the horizon does not trigger a calculation. The user can adjust dates, balances, and rules before using the existing Calculate action; until a new calculation is requested, the displayed calendar retains its preceding outcome and horizon.
A successful calculation displays the calendar once, as soon as the full planning objective order is complete, without displaying intermediate plans during optimization. Trace delivery continues in the background and never delays or changes that final calendar. The indicative duration estimate covers elapsed time until the final calendar is usable, including any trace capture that delays the outcome, rather than the additional time to deliver the complete trace.
A successful calculation displays the calendar once, as soon as the full planning objective order is complete, without displaying intermediate plans during optimization. Stable explanation delivery follows the outcome and never changes that final calendar. The indicative duration estimate covers elapsed time until the final calendar is usable, excluding later explanation work.
Before Calculate, the estimate is shown as an approximate range in seconds or minutes based on the horizon, balances, and rules. It starts with a rough estimate and is refined using measured calculation durations on the same device; it never becomes an automatic stopping deadline.
User cancellation during optimization preserves the best valid plan already found and labels it as a cancelled, incomplete calculation. Before any valid plan exists, cancellation reports that the calculation was cancelled without presenting a plan or claiming an obligation conflict.
Issue #76 supersedes all original-trace requirements in this ADR and both ADR 0004 documents. Decision capture, historical analysis and replay are removed. Immutable calculation, valid-incumbent and final-state snapshots remain for the retained explanation, cancellation recovery and displayed-placement counterfactuals. Cancellation still preserves the best available jointly valid plan and never implies an obligation conflict.
@@ -4,7 +4,7 @@ status: accepted
# Declared Non-Working Days and Reported Leave Balances
For [issue #13](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/13), users declare fixed non-working dates among normal working days, with a CP, RTT, or Other type; Other covers every other reason for not working. Reported balances already account for booked leave, so these declarations consume no remaining balance and cannot receive another placement; they count towards compatible planning rules, including rules that earn leave.
For [issue #13](https://gitea.nessar.fr/nessar/vac-optimizer/issues/13), users declare fixed non-working dates among normal working days, with a CP, RTT, or Other type; Other covers every other reason for not working. Reported balances already account for booked leave, so these declarations consume no remaining balance and cannot receive another placement; they count towards compatible planning rules, including rules that earn leave.
Declared dates can form time-off periods without new leave placements, interrupt work sequences, and guide further optimization. Each calculation uses today's Europe/Paris calendar date, with reported balances assumed current as of that date: the planner adds only entitlements available strictly afterward, while earlier entitlements are already represented in the reported balances. This keeps existing bookings useful without debiting them again or asking users to manually add prospective gains; it relies on the user keeping reported balances current as the employer's system credits earned leave.
@@ -0,0 +1,25 @@
---
status: accepted
---
# User-Controlled Planning Objectives
VacOptimizer represents configurable plan-wide objectives as named optimization rules in the same user-controlled list as calendar-based planning rules, adding rule types where existing calendar patterns cannot express the objective. All active preference rules share one user-defined lexicographic order, so moving an optimization preference above Samedi Malin may deliberately forgo earned leave to improve that higher-priority objective. Making the displayed order authoritative supersedes the fixed ordering between user preferences and optimization objectives in [ADR 0003](0003-constraint-first-lexicographic-planning.md).
At-risk loss prevention also becomes an optimization rule, enabled in first position by default and freely disableable or reorderable. The planner follows the resulting preference order even when a higher-priority preference leaves more at-risk leave unplaced; this also supersedes ADR 0003's unconditional priority for loss prevention.
Optimization rules use preference mode. Supporting them as obligations would require explicit thresholds and additional conflict semantics, which are outside this change.
The shared model for user-created optimization rules selects planning elements and applicable conditions, a measure and its aggregation, and a direction to minimize or maximize. At minimum, the application supplies six presets expressed in that same model: loss prevention, public-holiday week value, non-working-day gain, longest work-sequence length, the deficit of internal work sequences shorter than five working days, and the number of supporting placements.
These presets retain their existing domain meanings, including the weekday-dependent value of complete public-holiday weeks and the total deficit of short work sequences rather than their count. Supporting placements are additional uses of balances expiring after the planning horizon to improve the plan. User-created rules can compose supported planning elements and measures; introducing a new domain measure requires extending the planner.
The six presets are initially enabled, ordered as loss prevention, existing calendar-based rules, then the other five optimization presets in their former engine order. Existing saved rule lists, including an empty list, receive this addition once while preserving every existing rule's identity, parameters, force, enabled state, and relative order. Subsequent loads restore the user's saved choices without reinserting deleted presets or reactivating disabled ones.
After all active rules compare equally, earlier balance expiry and then earlier placement dates remain deterministic tie-breakers.
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.
Implemented in the #70–#75 series. Saved-rule migration and functional verification
are covered by #75. Benchmark performance acceptance and any required optimization
are tracked separately in #78; the benchmark limits remain unchanged.
@@ -0,0 +1,26 @@
---
status: proposed
---
# Bun Runtime and Native Tooling
VacOptimizer will use Bun as the runtime for project-owned JavaScript in
development, CI, and production, adopting its native test runner, linter,
formatter, type checker, and HTTP server even without measured performance gains.
This deliberately accepts Bun-specific tooling and migration work while retaining
Angular's standard compiler and build pipeline, including TypeScript 6 for
Angular compilation alongside `bun check` for standalone TypeScript checking.
Verification on stable Bun 1.4.3 narrowed this: ESLint and Prettier stay,
run by Bun, until a stable release ships the native linter and formatter;
Angular builds a client-only bundle, because its server build relies on Node
loader hooks Bun does not apply, and a small `Bun.serve` server delivers it,
giving up `@angular/ssr`; coverage is line-level, converted from lcov to the
existing HTML and Cobertura reports; and the benchmark's heap cap becomes a
container memory limit.
Existing behavior, tests, lint rules, coverage reporting, and benchmark budgets
must be preserved; incompatibilities must be fixed or reported as blockers before
declaring completion, and a Node.js fallback does not meet the runtime requirement.
The [development spec](../bun-adoption.md) records the agreed boundaries,
acceptance criteria, and remaining verification.
@@ -0,0 +1,9 @@
# Rank Obligation Solutions Before Preferences
Accepted for [issue #302](https://gitea.nessar.fr/nessar/vac-optimizer/issues/302), after the analysis in [issue #288](https://gitea.nessar.fr/nessar/vac-optimizer/issues/288).
A search change may change planning outcomes when it is deliberate, isolated in one reviewed commit and recorded. The frozen engine of the [frozen-engine differential check](../benchmark/README.md#frozen-engine-differential-check) is rebuilt from that commit, in its own commit, and the benchmark documentation records a reproducible before/after comparison over the check's seeded requests, including every request that became worse on a real objective. Exact optimizations still keep every outcome, stable explanation and final-state snapshot identical to the frozen engine.
When obligation rules can be satisfied jointly in several ways, the planner orders the obligation solutions by its pre-preference ranking: the active objectives, then the tie-breaks, evaluated on the obligation-only plan. Equal ranks keep enumeration order. The planner runs the preference stages once, on the first solution, instead of previewing the preference stages on every candidate solution. This removes a cost that grew with the number of solutions, and trades away the cases where a lower-ranked solution ends better after the preferences: over the 5,000 seeded requests, 23 plans became worse, 9 of them on a real objective, and 1 became better; over 50 loaded-year-sized requests, 4 became worse on a real objective ([comparison record](../benchmark/issue-302.md#comparison-record)). If the run on the chosen solution ends in an earned-entitlement chronology conflict, the planner tries the next solution in that order, and reports a conflict only when every solution fails.
The Bun benchmark targets, measured with the benchmark protocol on the development machine, are 10 seconds for the loaded year, 5 seconds for multi-year horizons and 3 seconds for every other scenario. They are development targets, not reference-phone limits. This revisits the five-second target of [ADR 0003](0003-constraint-first-lexicographic-planning.md); [ADR 0006](0006-user-selected-horizons-and-cancellable-calculations.md) already removed its automatic cutoff and sets no validated limit for multi-year horizons.
@@ -0,0 +1,19 @@
# Server-Side Planning for Every Device
Accepted on 2026-10-28 for [issue #319](https://gitea.nessar.fr/nessar/vac-optimizer/issues/319); implemented by #320, #323, #324 and #325. This supersedes [ADR 0002](0002-personal-client-side-planner-for-now.md) and the requirement of [ADR 0006](0006-user-selected-horizons-and-cancellable-calculations.md) that calculations remain in the browser; ADR 0006's absence of an automatic cutoff, its Cancel action and its retained valid plan are unchanged.
Older phones are too slow for heavy configurations, and some crash near the end of a calculation. A Pixel 11 runs the benchmark's loaded year in about 4.6 seconds in its browser worker. The Bun server therefore runs the planner for every device, and the privacy of leave data is not a constraint. The browser engine remains a fallback. The server is not faster than a recent phone: on the development machine (Ryzen 7 7800X3D), the loaded year takes 5.3 seconds on Bun and 3.8 seconds on Node 24. It makes the wait independent of the device.
The server carries the existing `WorkerRequest`/`WorkerResponse` protocol over a same-origin WebSocket. On the client, it is a second implementation of `WorkerJob`, so heartbeats, liveness, cancellation, checkpoints, explanation delivery and counterfactual analysis keep their current behavior. Each connection runs the unchanged `leave-planner.worker.ts` in a Bun `Worker`, and the server keeps no state once the socket closes. Calculations run one per worker, up to `PLANNING_WORKERS`, which should equal the number of physical cores. Calculations beyond that limit wait in a FIFO queue that sends heartbeats. Each client IP, read from `CF-Connecting-IP`, may hold five calculations, running or queued, and there is no server-side duration limit. The container may use up to 8 GB.
The client falls back to its own engine without notice when the socket cannot open, when the server refuses the per-IP limit, or when the server's build differs from the client's. A connection lost during a calculation is an incomplete calculation with the best valid plan already received, without an automatic retry.
## Considered Options
- **Parallelism inside one calculation**: rejected. The planning objective order is sequential by design. Workers share no objects, so every improvement iteration would ship its state to every worker, and the planner core would need a rewrite under the frozen-engine determinism check. Throughput across calculations is enough: with 1, 4, 8 and 16 concurrent loaded-year calculations, each took 5.5, 7.3, 12.2 and 24.4 seconds. Throughput stops growing at the eight physical cores, and Bun's `navigator.hardwareConcurrency` reports 16. Each calculation adds roughly 60 to 150 MB, so CPU, not memory, limits concurrency.
- **Node for its faster V8 engine**: rejected. It needs a WebSocket dependency, a rewritten server and a departure from [ADR 0009](0009-bun-runtime-and-native-tooling.md). The gap comes from JavaScriptCore hotspots, such as `Object.freeze` in plan observations (about 10% of the loaded year on Bun, negligible on Node) and the iteration protocol. Reducing them is a separate performance change that also benefits Safari on iPhone.
- **HTTP with server-sent events, or one blocking request**: rejected. The first needs a second request to cancel. The second loses progress, checkpoints and the retained plan on cancellation.
## Consequences
The per-IP limit holds only if the origin accepts traffic from Cloudflare alone, and the reverse proxy must forward WebSocket upgrades. If a phone crashes while rendering the calendar rather than while planning, this decision does not fix it. A device that falls back while the server is unreachable can still crash.
@@ -0,0 +1,11 @@
---
status: accepted
---
# Empty Leave Balances on a First Visit
Accepted on 2026-11-13 for [issue #356](https://gitea.nessar.fr/nessar/vac-optimizer/issues/356). This supersedes the random initial balances of [ADR 0005](0005-saved-planning-inputs-before-random-defaults.md); restoring the saved list, including an intentionally empty one, deleting unreadable data first and saving the whole list on every balance edit are unchanged.
A first-time visitor saw a plan calculated on three random balances of 10 to 20 days that they never entered. When the saved leave-balance list is absent or unreadable, VacOptimizer now starts from an empty list, and no quantity is ever generated. The configuration panel then invites the user to add a first leave balance.
With no leave balance and no declared non-working day there is nothing to plan: no calculation starts when the page opens, Calculate is disabled with the reason given to assistive technologies, as for an invalid planning horizon, and the results panel shows the planning horizon's calendar, with its weekends and public holidays, and an invitation instead of plan figures. Declared non-working days alone still start a calculation, because they can earn leave that the plan then places ([ADR 0007](0007-declared-days-and-reported-balances.md)). A plan already on screen stays until the next calculation, as after any other edit.
+36 -25
View File
@@ -1,46 +1,57 @@
# Issue tracker: GitLab
# Issue tracker: Gitea
Issues and specs for this repo live as GitLab issues. Use the [`glab`](https://gitlab.com/gitlab-org/cli) CLI for all operations.
Issues and specs live in [nessar/vac-optimizer on Gitea](https://gitea.nessar.fr/nessar/vac-optimizer). Use the configured [`tea-cli`](https://gitea.com/gitea/tea) login for supported operations.
## Access and command version
The installed binary is `tea-cli` 0.9.2. Its commands below use the pre-1.0 interface; other installations may call the binary `tea`. Check `tea-cli --help` and subcommand help before using commands from another version. This version supports YAML, TSV, CSV, simple, and table output; it has no JSON output, issue-edit command, or `api` command.
Run inside the clone so the CLI discovers the repository and login from `origin`. Use `--repo nessar/vac-optimizer` and `--login <login-name>` when an explicit selection is needed. Options go before positional issue or PR numbers. Existing authentication can be checked with `tea-cli whoami`; for a new login, use interactive `tea-cli login add` and select `https://gitea.nessar.fr`.
## Conventions
- **Create an issue**: `glab issue create --title "..." --description "..."`. Use a heredoc for multi-line descriptions. Pass `--description -` to open an editor.
- **Read an issue**: `glab issue view <number> --comments`. Use `-F json` for machine-readable output.
- **List issues**: `glab issue list -F json` with appropriate `--label` filters.
- **Comment on an issue**: `glab issue note <number> --message "..."`. GitLab calls comments "notes".
- **Apply / remove labels**: `glab issue update <number> --label "..."` / `--unlabel "..."`. Multiple labels can be comma-separated or by repeating the flag.
- **Close**: `glab issue close <number>`. `glab issue close` does not accept a closing comment, so post the explanation first with `glab issue note <number> --message "..."`, then close.
- **Merge requests**: GitLab calls PRs "merge requests". Use `glab mr create`, `glab mr view`, `glab mr note`, etc. — the same shape as `gh pr ...` with `mr` in place of `pr` and `note`/`--message` in place of `comment`/`--body`.
- **Create an issue**: `tea-cli issues create --title "..." --description "..." --labels "needs-triage"`. Multiple labels or assignees are comma-separated. For multiline text, prepare a draft and pass its contents as one quoted description argument.
- **Read an issue**: `tea-cli issues --comments <number>`. Detail views render for display even with `--output yaml`; use list output or the REST operations below for structured data.
- **List issues**: `tea-cli issues --state open --labels "needs-triage" --fields index,title,body,state,labels,assignees,url --output yaml`. Use `--page` and `--limit` to read all pages; the server may cap the requested page size.
- **Comment**: `tea-cli comment <number> "..."`; this works for issues and PRs.
- **Apply / remove labels, edit a body, or assign**: use the Gitea UI or the REST operations below; this CLI version does not support these edits. Preserve unrelated labels and assignees.
- **Close**: post the explanation with `tea-cli comment <number> "..."`, then run `tea-cli issues close <number>`.
- **Create a pull request**: `tea-cli pulls create --base develop --title "docs: update Gitea documentation" --description "..."`. Read with `tea-cli pulls --comments <number>`; list with `tea-cli pulls --state open --output yaml`.
- **List milestones**: `tea-cli milestones --state all --fields id,title --output tsv`. Issue numbers were preserved during migration, but milestone IDs changed; V1 stats is [milestone 13](https://gitea.nessar.fr/nessar/vac-optimizer/milestone/13).
Infer the repo from `git remote -v` — `glab` does this automatically when run inside a clone.
## REST operations for CLI gaps
## Merge requests as a triage surface
The instance's [API explorer](https://gitea.nessar.fr/api/swagger) and [schema](https://gitea.nessar.fr/swagger.v1.json) describe the supported endpoints. Paths below are relative to `https://gitea.nessar.fr/api/v1`; authenticate with an existing authorized Gitea API token without displaying or committing it. Check the installed CLI help first when it is upgraded.
**MRs as a request surface: no.** _(Set to `yes` if this repo treats external merge requests as feature requests; `/triage` reads this flag.)_
- **Read full issue data or comments as JSON**: `GET /repos/nessar/vac-optimizer/issues/<number>` and `GET /repos/nessar/vac-optimizer/issues/<number>/comments`. Paginate comment lists.
- **Find label IDs**: `GET /repos/nessar/vac-optimizer/labels`; paginate and match exact names from `triage-labels.md`.
- **Add labels**: `POST /repos/nessar/vac-optimizer/issues/<number>/labels` with `{"labels":[<label-id>]}`. **Remove one label**: `DELETE /repos/nessar/vac-optimizer/issues/<number>/labels/<label-id>`. These operations preserve other labels.
- **Edit a body or assign**: `PATCH /repos/nessar/vac-optimizer/issues/<number>` with `{"body":"..."}` or `{"assignees":["<username>"]}`. Read current assignees before updating the list.
- **Read a PR diff**: `GET /repos/nessar/vac-optimizer/pulls/<number>.diff`.
When set to `yes`, MRs run through the same labels and states as issues, using the `glab mr` equivalents:
## Pull requests as a triage surface
- **Read an MR**: `glab mr view <number> --comments` and `glab mr diff <number>` for the diff.
- **List external MRs for triage**: `glab mr list -F json`, then keep only MRs whose author is not a project member/owner (a contributor's MR, not a maintainer's in-flight work).
- **Comment / label / close**: `glab mr note`, `glab mr update --label`/`--unlabel`, `glab mr close`.
**PRs as a request surface: no.** _(Set to `yes` if this repo treats external pull requests as feature requests; `/triage` reads this flag.)_
Unlike GitHub, GitLab numbers issues and MRs separately, so `#42` is unambiguous once you know which surface the maintainer means.
When enabled, use `tea-cli pulls --comments <number>` to read and `tea-cli pulls --state open --fields index,title,body,author,labels,url --output yaml` to list. Keep only external contributors' requests, checking repository collaborators or organization membership rather than guessing from the author's name. Comment with `tea-cli comment`, edit labels through the issue-label API, and close with `tea-cli pulls close <number>`.
For a bare `#<number>`, check the resource kind: `tea-cli issues --kind all --fields index,kind,title,url --output yaml`, or inspect the issue API's `pull_request` field. PR URLs use `/pulls/<number>`; issue URLs use `/issues/<number>`.
## When a skill says "publish to the issue tracker"
Create a GitLab issue.
Create a Gitea issue with `tea-cli issues create`.
## When a skill says "fetch the relevant ticket"
Run `glab issue view <number> --comments`.
Run `tea-cli issues --comments <number>` and read its labels and assignees.
## Wayfinding operations
Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets.
- **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `glab issue create --label wayfinder:map`. (On GitLab tiers with native epics, an epic may hold the map instead; a labelled issue works everywhere.)
- **Child ticket**: an issue carrying `Part of #<map>` at the top of its description and labels `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev.
- **Blocking**: GitLab's **native blocking link** — the canonical, UI-visible representation. Add it with the `/blocked_by #<n>` quick action, posted as a note (`glab issue note <child> --message "/blocked_by #<blocker>"`). Native blocking links are a Premium/Ultimate feature; on the free tier (or where unavailable) fall back to a `Blocked by: #<n>, #<n>` line at the top of the description. A ticket is unblocked when every blocker is closed.
- **Frontier query**: `glab issue list -F json` scoped to the map's children, drop any with an open blocker — a native `blocked_by` link to an open issue (`glab api projects/:id/issues/:iid/links`), or an open issue in the `Blocked by` line — or an assignee; first in map order wins.
- **Claim**: `glab issue update <n> --assignee @me` — the session's first write.
- **Resolve**: `glab issue note <n> --message "<answer>"`, then `glab issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far.
- **Map**: create an issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body, with `tea-cli issues create --title "..." --description "..." --labels "wayfinder:map"`.
- **Child ticket**: an issue carrying `Part of #<map>` at the top of its description and labels `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Maintain the ordered child links in the map's body. Once claimed, the ticket is assigned to the driving dev.
- **Blocking**: use Gitea's native dependencies. `POST /repos/nessar/vac-optimizer/issues/<child>/dependencies` with `{"owner":"nessar","repo":"vac-optimizer","index":<blocker-number>}` makes the child depend on that blocker. Read blockers with `GET` on the same path; use `DELETE` with the same body to remove a dependency. Where dependencies are unavailable, retain a `Blocked by: #<n>, #<n>` line at the top of the description. A ticket is unblocked when every blocker is closed.
- **Frontier query**: list the map's open children with `tea-cli issues --state open --fields index,title,body,assignees,labels --output yaml`, reading all pages. Drop tickets with an assignee or an open native dependency or description-line blocker; first in map order wins.
- **Claim**: assign the authenticated username through the issue `PATCH` endpoint or Gitea UI — the session's first write.
- **Resolve**: `tea-cli comment <n> "<answer>"`, then `tea-cli issues close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far through the issue `PATCH` endpoint or Gitea UI.
+360 -33
View File
@@ -1,16 +1,205 @@
# Mobile leave-planner benchmark
## Composable optimization rules: current verification status
[Issue #78](https://gitea.nessar.fr/nessar/vac-optimizer/issues/78) passes the
unchanged Node acceptance protocol on the documented development laptop:
**298.6 seconds**, including one warm-up and two measured repetitions of all
seven scenarios, without coverage, with one worker and a 2 GiB Node heap.
After [#302](issue-302.md#benchmark-protocol), the Bun protocol takes about 41
seconds, and its timeout is a 240-second hang guard (see
[Relative CI gate](#relative-ci-gate)). All expected outcomes,
placement counts, final stages and determinism checks pass. The fixture inputs
are unchanged; the test now prints its existing report.
## Relative CI gate
The relative gate replaces the 300-second acceptance protocol named in
[#78](https://gitea.nessar.fr/nessar/vac-optimizer/issues/78) as the benchmark
policy. This is an explicit policy change from #279/#285: runners differ in
speed, so a fixed wall-clock limit was flaky.
Before the protocol, in the same process, the spec times the calibration engine
(`src/app/services/frozen-engine/leave-planner.core.calibration.mjs`, the engine at
a871f8f) on the `two years` scenario, best of three, and prints the result. This
bundle never changes, so ratios stay comparable with the recorded history; the
differential check's frozen bundle can be rebuilt independently.
The spec repeats the calibration after the protocol and uses the slower of the two
values, so load that starts during the protocol slows the yardstick too; the second
value can only loosen the budgets. When it does, the log prints it and the summary
table again with the budgets actually applied.
Each scenario's budget is its multiplier times that calibration; the mean
`planningMs` of its two measured repetitions must not exceed it. A scenario
without a multiplier fails too. #286 tightened the multipliers once #302 met
the speed targets, and #321 tightened them again.
The job log shows a Markdown table with one row per scenario, printed as soon
as that scenario finishes. Each row gives both measured planning times, their
mean, the budget, the ratio to the calibration, the multiplier, the outcome,
placements, determinism and `ok`, `OVER` or `no budget`. The complete
tab-separated report follows the table.
| Scenario | Mean planning (s) | Ratio to calibration | Multiplier |
| --------------------------- | ----------------- | -------------------- | ---------- |
| representative year | 0.19 | 0.06 | 0.1 |
| typed obligations | 0.07 | 0.02 | 0.1 |
| chained earned entitlements | 0.00 | 0.00 | 0.05 |
| deliberate conflict | 0.00 | 0.00 | 0.05 |
| loaded year | 2.70 | 0.78 | 1.25 |
| two years | 0.54 | 0.16 | 0.25 |
| three years | 1.66 | 0.48 | 0.75 |
Ratios come from the development machine's Bun protocol after #321
(calibration 3.44 s, [record](issue-321.md#benchmark-protocol)); the multipliers
add roughly 1.5x headroom, rounded up, with a floor of 0.05 for the two tiny
scenarios. Typed obligations gets 0.1: its 0.07-second run would leave a 0.05
budget only about 100 ms of headroom for runner jitter. After #302, the
multipliers were 0.15, 0.1, 0.05, 0.05, 2.5, 0.5 and 1.5; before it, 0.25, 3,
0.05, 0.05, 25, 1 and 3.5. A failure lists, per
scenario, the measured mean, the budget, the multiplier and the calibration in
milliseconds.
The first CI runs of PR #287 (commit `63b50c4`) give consistent ratios on two
runners:
| Scenario | nessar-desktop | srvhome |
| --------------------------- | -------------- | ------- |
| calibration | 3.03 s | 5.71 s |
| representative year | 0.17 | 0.14 |
| typed obligations | 1.83 | 1.75 |
| chained earned entitlements | 0.011 | 0.005 |
| deliberate conflict | 0.006 | 0.003 |
| loaded year | 16.6 | killed |
| two years | 0.65 | killed |
| three years | 1.99 | killed |
srvhome is about 1.9 times slower than nessar-desktop, so its whole protocol
needs roughly 400 seconds. The original 300-second `timeout` killed it during
the loaded year, while every completed scenario was within budget. The CI
`timeout` was therefore 600 seconds and the test timeout 570 seconds. After
#302 the whole local protocol took about 41 seconds, so srvhome should need
about 80; after #321 it takes about 39 seconds locally. #286 lowered the CI `timeout` to 240 seconds and the test timeout to
210 seconds, about three times that. They are only hang guards and do not
judge speed.
The protocol now runs on Bun's test runner, outside coverage:
`timeout 240s bun test src/app/benchmark --timeout=240000`. JavaScriptCore has
no equivalent of Node's `--max-old-space-size`, so the CI benchmark job enforces
memory with a 3 GiB container limit instead of the former 2 GiB heap cap.
Scenarios, calibration, warm-up, repetitions, determinism checks and
multipliers are unchanged. One local run (Bun 1.4.3, Node unavailable) took
268 seconds and passed every scenario; the frozen-engine calibration was
3.79 s and the ratios were 0.14 (representative year), 1.43 (typed
obligations), 0.01 (chained earned entitlements), 0.00 (deliberate conflict),
17.50 (loaded year), 0.64 (two years) and 2.18 (three years). These are Bun
measurements; they do not establish browser or reference-phone speedups.
The post-removal functional integration checks, browser QA and unchanged-input
handoff for #78 are recorded in [the #77 verification report](../trace-free-planning-verification.md).
The benchmark is required again in Gitea Actions, including the image and
aggregate gates. [The #78 report](issue-78.md) records the baseline timeout,
profiling, before/after diagnostics, full protocol output, correctness checks
and browser limitations. That pass had only 1.4 seconds of external-timeout
headroom. Three later exact optimizations for PR #278 cut the Vitest duration
to **228.1 seconds** (71.9 seconds of headroom) in the most recent local run:
[direct date keys](pr-278-date-keys.md),
[immutable date counts](pr-278-immutable-date-counts.md) and
[mandatory-move prechecks](pr-278-mandatory-moves.md). Outcomes, explanations
and final states are unchanged. CI-runner performance and live workflow
validation remain unverified.
The existing migration protection stays in place under
[issue #268](https://gitea.nessar.fr/nessar/vac-optimizer/issues/268).
Before these optimizations, the trace-free integrated baseline at `2f4af14`
timed out after 300 seconds without a complete report. The #76 verification
previously passed 630 functional tests across 33 files with coverage under the
same heap setting, while its unchanged benchmark also timed out. Before the
Gitea migration, GitLab pipeline 320 passed 652 functional tests, but its
separate benchmark timed out as well. An earlier loaded-year warm-up took
184.36 seconds; that historical sample predates the final period-projection
cache and trace removal and is not a measurement of the current engine.
#75 owns functional saved-rule migration, #76 removes tracing, #77 verifies
retained behavior and #78 owns performance acceptance. No automatic elapsed-time
engine cutoff is introduced. No reference-phone run is claimed.
The measurements below describe earlier implementations and protocols. Their
trace counters and timings are historical; current evidence is in
[the #78 report](issue-78.md).
## Frozen-engine differential check
`src/app/services/frozen-engine.spec.ts` runs 5,000 seeded random planning
requests (seeds 280000 to 284999, one test per 200 seeds) through the current
engine and through a frozen copy of the engine. The copy was rebuilt for #302
from `8168137`, which plans from the best-ranked obligation solution
([comparison record](issue-302.md#comparison-record)). Until then it was the
engine at `a871f8f`, develop after PR #278, which remains the calibration
engine. For each request, the planning outcome, stable plan explanation,
explanation error and final-state snapshot must be strictly deep-equal,
including `PlanningConflict` and `InvalidInput` outcomes. Timings are not
compared.
Start dates span 2025 to 2027. About 15% of requests start in late December and
cross a year boundary, and about 15% start shortly before a weekday French
public holiday. Most horizons last 7 to 28 days; about 10% last 29 to 70 days
with optimization presets and at most one calendar rule. Requests cover
obligation and preference rules, `IF_THEN` rules with earned leave
entitlements, `TIME_WINDOW` rules, optimization presets in random order and
subsets, random composed optimization configurations, disabled rules, declared
non-working days and a few deliberately invalid requests. The last test fails
if an outcome kind, rule type, year-crossing horizon or public-holiday horizon
stops appearing. Requests stay small because candidate search grows quickly
with horizon length and balances; the slowest case takes about one second.
The generator is `src/app/services/frozen-engine/random-planning-requests.ts`.
`compare-engines.ts` beside it is an opt-in runner, outside the functional suite
and CI, that classifies how the current engine's plans differ from the frozen
engine's, or with `calibration` from the calibration engine's, over the same
seeds; [the #302 record](issue-302.md#comparison-record) shows its use.
The fixture is `src/app/services/frozen-engine/leave-planner.core.frozen.mjs`,
a generated bundle with `date-holidays` left external, and its hand-written
`leave-planner.core.frozen.d.mts`. Rebuild it only for an intended behavior
change, in its own reviewed commit, from the commit that introduces the change.
Before rebuilding, while the frozen engine is still the previous one, run the
comparison and record its counts and every request that became worse on a real
objective with the change, as [the #302 record](issue-302.md#comparison-record)
does:
```sh
bun src/app/services/frozen-engine/compare-engines.ts small 280000 5000
bun build src/app/services/leave-planner.core.ts --target=node --external date-holidays --outfile src/app/services/frozen-engine/leave-planner.core.frozen.mjs
```
The comparison is deliberately not a CI check. The differential check already
fails on any unintended change; the comparison only describes an intended one,
and a fixed acceptance threshold would have to be renegotiated with every
rebuild. The loaded-year-sized sample (`loaded-year 302000 50`) takes about an
hour and is worth running when a change targets large plans.
A failure prints the seed and the full request as JSON. To run only that seed:
```sh
FROZEN_ENGINE_SEED=<seed> bun test --isolate src/app/services/frozen-engine.spec.ts
```
The check runs in the functional suite. On the development laptop with Bun
1.4.3 it takes about 54 seconds with or without coverage
(`bun test --config=bunfig.coverage.toml --isolate src/app/services/frozen-engine.spec.ts`; coverage is line-level only).
A flipped objective direction in `compareObjectiveValues` made 26 of its tests
fail, starting at seed 280002; the change was reverted.
## Reference-phone protocol
Open the deployed application at `/benchmark` on the reference phone. Tap
**Run benchmark**, wait for the seven scenarios to finish, then tap **Copy
report** and save the tab-separated output with the date and build identifier.
The harness measures preparation, planning-to-outcome latency, later trace
delivery, and total wall time separately. It also reports planning work, trace
capture, trace materialization, and trace transfer independently, plus the
largest extra delay of a 50 ms UI heartbeat. It records the outcome, last
completed quality stage, placement count, determinism, trace status, and trace
candidate count. `PlanningIncomplete` is not a conflict: its last completed
stage and incumbent are retained.
The harness measures preparation, planning-to-outcome latency, planning work, and total wall time through stable explanation delivery. It also reports the largest extra delay of a 50 ms UI heartbeat, available main-thread heap, outcome, last completed quality stage, placement count and determinism. `PlanningIncomplete` retains its last completed stage and valid incumbent and is distinct from a conflict.
Issue #76 removes all trace timing, status and candidate-count columns, along with trace promises and delivery requirements. The seven scenarios, warm-ups, repetitions, 2 GB heap limit, 300-second timeout and performance gates are unchanged. #77 owns integrated functional verification; #78 owns performance acceptance and any necessary optimization.
## Protocol
@@ -32,24 +221,19 @@ stage and incumbent are retained.
tree until a human records it here.
The browser page uses the same `createPlanningCalculation(request)` context as
the calendar and adds no solver or backend dependency. It omits `deadlineMs`.
Trace delivery is reported separately and cannot replace a valid planning outcome.
the calendar, so it measures the path the app uses: a server calculation over
the planning WebSocket, with the local engine as fallback. It omits `deadlineMs`.
The `bun test` protocol and its budget specs keep running against the local engine.
Explanation delivery is independent of the outcome and cannot replace a valid plan.
`planning_ms` is the observed latency until the outcome is usable;
`planning_work_ms` excludes trace capture. `trace_capture_ms` accounts for
instrumentation during planning, `trace_materialization_ms` accounts for
building the stable explanation and finishing the trace after the outcome.
`trace_transfer_ms` measures worker transfer and receiver assembly work;
`trace_delivery_ms` measures elapsed time until the complete trace is ready. `max_ui_delay_ms` includes
planning, trace delivery, and report preparation. Trace readiness has no
elapsed-time ceiling and never permits truncating actual candidate evaluations.
`planning_ms` is the observed latency until the outcome is usable. `planning_work_ms` excludes observer callbacks and post-outcome explanation work. `wall_ms` includes preparation, outcome and explanation delivery. `max_ui_delay_ms` covers this entire interval; there is no decision recording, trace materialization or trace transfer.
`peak_main_thread_heap_bytes` is Chromium's available `performance.memory`
sample, taken alongside the 50 ms UI heartbeat. A blank value means this API is
unavailable. This measures the page's JS heap, excludes the worker heap, and is
not a claim about total application memory. For a browser profile, record the
isolated Chrome process-tree RSS separately during planning and subsequent
trace delivery, including the worker and renderer. State the sampling interval,
explanation delivery, including the worker and renderer. State the sampling interval,
CPU throttling, viewport, and whether a warm-up preceded each measurement.
For cancellation measurements, use the normal calendar with the same saved
@@ -57,11 +241,154 @@ two- or three-year dates and balances. Cancel during preparation and an active
optimization phase, using the keyboard in one run. Record request-to-outcome
latency separately from request-to-artifacts latency; verify the partial-plan
status or absence of a plan, one planning request, no placements before the
outcome, and continued acknowledged delivery of the original trace. Confirm
outcome, and delivery of its stable explanation. Confirm
that editing an input remains possible during active worker CPU work. These
measurements describe that device and workload; they impose no latency limit.
## Hardware status
## Indicative wait recalibration — 2026-10-18
[Issue #302](issue-302.md) made planning much faster, so the rough prior
behind the range beside **Calculate** (see
[planning-duration.md](../planning-duration.md)) overstated every request with
many obligation solutions or a multi-year horizon. These measurements refit it.
The NEW builds are the production build of `75320da` (the #302 engine); the OLD
column is the production build of `b356117`, the last commit before the #302
engine changes. Both ran in headless Chromium 149.0.7827.55 on an AMD Ryzen 7
7800X3D desktop under Debian 13 on WSL2. Emulation used 412×915 pixels, scale
2.625, touch, reduced motion and 4× CPU throttling; external font downloads
were blocked. **This is desktop emulation, not a phone measurement.**
`Emulation.setCPUThrottlingRate` slows the page's main thread but does not
throttle the dedicated planning worker, so the search ran at desktop speed.
A phone, whose worker is also slower, can wait longer than any figure here.
Every run used a fresh browser. The application's own initial calculation (one
saved day) finished first. The run then enabled any custom rules with the real
toggles and set the planning dates through the real date controls; the saved
balances, rules and dates were checked, and the calendar stayed unchanged until
one Calculate click. The wait is the time from that click to the displayed
final placements with the loading overlay gone, the endpoint described in
[planning-duration.md](../planning-duration.md). Every run returned a `Plan`
with the placement count shown. NEW has three runs per configuration; OLD has
two, and was not run for configurations 4 and 5. Configurations 1 to 3 give each
year 20 CP and 10 RTT days available January 1 and expiring December 31; every
configuration keeps the six default optimization presets, and 4 and 5 are the
benchmark's "loaded year" and "typed obligations" scenarios from
`benchmarkScenarios()`.
| # | Configuration | Placements | NEW wait, ms mean [min–max] | OLD wait, ms mean [min–max] | Range shown, old constants | Range shown, new constants |
| --- | ----------------------------------------------------- | ---------: | --------------------------- | --------------------------- | -------------------------- | -------------------------- |
| 1 | One year 2024, 20 CP + 10 RTT | 30 | 730 [716–752] | 1,014 [990–1,037] | 1–5 s | 1–3 s |
| 2 | Two years 2024–2025, 20 CP + 10 RTT per year | 60 | 1,909 [1,880–1,943] | 3,137 [3,121–3,153] | 3–24 s | 1–7 s |
| 3 | Three years 2024–2026, 20 CP + 10 RTT per year | 90 | 4,477 [4,450–4,498] | 8,250 [8,241–8,258] | 11–68 s | 2–15 s |
| 4 | Loaded year (6×12 days, 3 obligation + 2 preferences) | 72 | 4,024 [3,981–4,076] | not run | 4–26 s | 1–12 s |
| 5 | Typed obligations | 10 | 640 [599–687] | not run | 1–2 s | 1–2 s |
| 6 | One year 2024, 5 CP only | 5 | 465 [457–472] | 518 [518–518] | 1–2 s | 1–2 s |
The old ranges are the application's no-sample ranges before the change, and
the new ones were confirmed in the rebuilt application for the same six saved
configurations. The earlier 2026-10-05 references (1.74, 5.08 and about 11
seconds) came from a different build, before many engine speedups, which is why
the OLD column is lower than them.
The refit keeps the model's structure and rounds its constants:
`400 + 250 × (D / 365.25)^0.5 × (max(1, P) / 30)^1.5 × R`. With `D` the horizon
in days, `P` the placement load and `R` the rule weight, it gives:
| # | `P` | `R` | `D` | Old estimate, ms | New estimate, ms | Measured, ms | New / measured |
| --- | --- | --- | ----- | ---------------: | ---------------: | -----------: | -------------: |
| 1 | 30 | 1.9 | 366 | 1,443 | 875 | 730 | 1.20 |
| 2 | 60 | 1.9 | 731 | 7,714 | 2,301 | 1,909 | 1.21 |
| 3 | 90 | 1.9 | 1,096 | 22,444 | 4,675 | 4,477 | 1.04 |
| 4 | 72 | 3.7 | 366 | 8,574 | 3,843 | 4,024 | 0.95 |
| 5 | 10 | 2.9 | 366 | 636 | 540 | 640 | 0.84 |
| 6 | 5 | 1.9 | 366 | 378 | 432 | 465 | 0.93 |
Every measured mean lies well inside the unrounded range from half to three
times the estimate. Configurations 1, 5 and 6 finished below the displayed
minimum of 1 second, which the whole-second display cannot go under. Horizon
length and placements grew together in configurations 1 to 3, so the data does
not separate the 0.5 horizon power from the 1.5 placement power; the sum
reproduces the roughly squared growth with years above a fixed overhead. The
same prior estimates five years with 30 days per year (`P` = 150, `D` = 1,826)
at about 12 seconds, displayed as 6–37 seconds; the old constants gave
44–265 seconds. Horizons beyond three years remain unvalidated extrapolation.
These samples set a rough prior and impose no duration ceiling.
## Indicative wait recalibration — 2026-11-11
[Issue #321](issue-321.md) roughly halved planning time, and planning now runs
on the Bun server ([ADR 0011](../adr/0011-server-side-planning-for-every-device.md)).
The 2026-10-18 prior therefore overstated requests without calendar rules. It
also understated the application's default rules, which the 2026-10-18 runs
did not include: Samedi Malin, an IF_THEN preference that earns leave, made
multi-year requests up to four times slower than the estimate, beyond the top
of the displayed range.
These are **planning times, not rendered waits**: the core's asynchronous entry
point, `calculatePlanningAsyncInternal`, called in one Bun 1.4.3 process on the
development machine (AMD Ryzen 7 7800X3D, WSL2) with
`calculationDate: '2024-01-01'`, one run per configuration after one warm-up
calculation, no other workload. No browser, WebSocket or rendering is included;
the model's fixed 400 ms keeps standing for them, unmeasured since 2026-10-18.
Each configuration starts on 2024-01-01 and gives every year the stated CP and
RTT days, available January 1 and expiring December 31, as the benchmark's
multi-year scenarios do. **Presets** holds the six default optimization rules.
**Defaults** adds, after loss prevention, Samedi Malin (IF_THEN preference,
Saturday, 2 CP, `auto`, earning 1 Other day) and a Christmas window (TIME_WINDOW
preference, 2024-12-20 to 2025-01-03, 5 days of any type). `P` and `R` are the
model's placement load and rule weight; with the new weights `R` is 1.9 for
presets and 6.15 for defaults. Each cell is the planning time in milliseconds
and, in brackets, that time plus 400 ms over the new estimate.
| Years | CP + RTT per year | Presets `P` | Presets, ms | Defaults `P` | Defaults, ms |
| ----- | ----------------- | ----------: | ------------ | -----------: | ------------- |
| 1 | 5 + 0 | 5 | 31 [1.04] | 6 | 119 [1.12] |
| 1 | 25 + 0 | 25 | 99 [0.91] | 26 | 277 [0.75] |
| 1 | 20 + 10 | 30 | 157 [0.94] | 31 | 545 [0.91] |
| 1 | 25 + 12 | 37 | 234 [0.97] | 38 | 748 [0.91] |
| 1 | 25 + 20 | 45 | 630 [1.40] | 46 | 1,955 [1.55] |
| 2 | 5 + 0 | 10 | 119 [1.08] | 12 | 243 [0.87] |
| 2 | 25 + 0 | 50 | 1,652 [1.74] | 52 | 3,723 [1.35] |
| 2 | 20 + 10 | 60 | 598 [0.71] | 62 | 1,824 [0.59] |
| 2 | 25 + 12 | 74 | 891 [0.74] | 76 | 5,673 [1.23] |
| 2 | 25 + 20 | 90 | 2,403 [1.29] | 92 | 10,495 [1.73] |
| 3 | 5 + 0 | 15 | 205 [0.98] | 18 | 821 [0.94] |
| 3 | 25 + 0 | 75 | 2,238 [1.07] | 78 | 6,527 [0.93] |
| 3 | 20 + 10 | 90 | 1,609 [0.66] | 93 | 5,719 [0.65] |
| 3 | 25 + 12 | 111 | 2,262 [0.67] | 114 | 21,124 [1.74] |
| 3 | 25 + 20 | 135 | 7,055 [1.47] | not run | not run |
| 4 | 5 + 0 | 20 | 373 [0.93] | 24 | 3,108 [1.59] |
| 4 | 25 + 0 | 100 | 4,398 [1.07] | 104 | 30,370 [2.13] |
| 4 | 20 + 10 | 120 | 3,377 [0.66] | 124 | 41,039 [2.26] |
| 5 | 5 + 0 | 25 | 530 [0.82] | 30 | 1,731 [0.61] |
| 5 | 25 + 0 | 125 | 7,696 [1.09] | not run | not run |
The new prior is `400 + 100 × (D / 365.25) × (max(1, P) / 30)^1.4 × R`, with
every enabled IF_THEN rule adding 4 to `R`. Over these 38 configurations the
measured time plus 400 ms lies between 0.59 and 2.26 times the estimate, inside
the displayed range of half to three times it. The previous constants gave 0.43
to 4.12. A least-squares fit in logarithms gave a horizon power of 0.94, a
placement power of 1.40 and a factor of 3.6 between the two rule sets; the
constants are those values rounded. The same placement load can cost three times
more or less depending on how it splits between leave types (two years at 25 + 0
against 20 + 10), which no single-pass estimate sees.
The measurements predate the last #321 change, which shortens the later stages
of the Defaults column by about a third without changing its longest stage.
Obligation rules keep their 2026-10-18 weights: their cost follows the number of
obligation solutions, which the model does not count, and one obligation next
to Samedi Malin can take a hundred times the estimate
([findings](issue-321.md#findings-left-open)). The local refinement in
[planning-duration.md](../planning-duration.md) corrects such a configuration
once it has been calculated.
## Historical measurements before trace removal
The following records remain as evidence for their dated builds. Trace-related behavior and metrics below are superseded by issue #76.
### Hardware status
No reference-phone run has been recorded. The project owner elected to close
the release tickets on 2026-09-25 using the emulated run below, accepting its
@@ -90,10 +417,10 @@ and each flow sent exactly one planning request. All 1,949 and 3,956 trace
packets respectively were acknowledged, carrying 122,621 and 249,234 candidate
records without truncation. Heartbeats continued during the producing runs.
| 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 |
| --- | --- | --- | --- | --- | --- | --- |
| 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 |
| 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 |
| 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 |
| ----------- | --------------- | -------------------- | ---------- | ----------------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------- |
| 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 |
| 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 |
A 50 ms page timer measured extra event-loop delay and sampled available
main-thread JS heap. RSS was sampled every 500 ms across that isolated Chrome
@@ -111,10 +438,10 @@ completed stage. An editable input accepted focus while the worker remained
active. Both flows kept a 44 px Cancel control, fit the viewport without
horizontal overflow, and delivered the original trace after their outcome.
| Cancellation point | Request to outcome | Request to complete artifacts | Retained placements |
| --- | --- | --- | --- |
| Calendar preparation | 21.9 ms | 874.8 ms | 0 |
| Active holiday-week optimization, keyboard | 21.5 ms | 1,431.7 ms | 90 |
| Cancellation point | Request to outcome | Request to complete artifacts | Retained placements |
| ------------------------------------------ | ------------------ | ----------------------------- | ------------------- |
| Calendar preparation | 21.9 ms | 874.8 ms | 0 |
| Active holiday-week optimization, keyboard | 21.5 ms | 1,431.7 ms | 90 |
No browser errors occurred. Cancellation issued one cancel request and no
additional calculation. Separate tests cover late artifact errors and stale
@@ -151,11 +478,11 @@ at the worker's terminal artifact delivery. The application's own calibration
uses its request timestamp and `afterNextRender` endpoint as described in
[planning-duration.md](../planning-duration.md).
| Horizon | Range before Calculate (with one local sample) | Observed calendar wait | Additional trace delivery | Range after completion | Placements |
| --- | --- | --- | --- | --- | --- |
| One year | 1–4 s | 1.74 s | 1.23 s | 1–5 s | 30 |
| Two years | 2–16 s | 5.08 s | 2.88 s | 2–16 s | 60 |
| Three years | 7–44 s | 11.03 s | 5.60 s | 6–39 s | 90 |
| Horizon | Range before Calculate (with one local sample) | Observed calendar wait | Additional trace delivery | Range after completion | Placements |
| ----------- | ---------------------------------------------- | ---------------------- | ------------------------- | ---------------------- | ---------- |
| One year | 1–4 s | 1.74 s | 1.23 s | 1–5 s | 30 |
| Two years | 2–16 s | 5.08 s | 2.88 s | 2–16 s | 60 |
| Three years | 7–44 s | 11.03 s | 5.60 s | 6–39 s | 90 |
All three outcomes completed through `dates`, with no intermediate placements,
implicit deadline, extra request or date movement. The three-year result
+200
View File
@@ -0,0 +1,200 @@
# Issue #279: incremental exact scoring
Step-by-step record for [issue #279](https://gitea.nessar.fr/nessar/vac-optimizer/issues/279).
Each step keeps planning outcomes, stable explanations and final states identical
to develop after PR #278 (`a871f8f`). The
[frozen-engine differential check](README.md#frozen-engine-differential-check)
guards every step.
All measurements use Node 24.18.0, Bun 1.3.14 and Vitest 5.0.3 on the development
laptop, with no other test, build or profiling workload running alongside the
protocol. Only same-session before/after pairs are comparable.
```sh
NODE_OPTIONS=--max-old-space-size=2048 timeout 300s bunx vitest run src/app/benchmark/leave-planner-benchmark.spec.ts --maxWorkers=1
```
The per-scenario figures below are the means of the two measured calculations.
## Baseline profile
A CPU profile of the bundled core over all seven scenarios, with
`calculationDate: '2024-01-01'`, put 50.5 of 67.0 loaded-year seconds in
candidate evaluation (`evaluateRuleCandidate`). Of those, 41.3 seconds went to
active-objective evaluation: 15.6 seconds in time-off-period observations,
11.5 seconds in building observations and 7.6 seconds in sorting placement dates
for the placement tie key and the observation cache key. The asynchronous
adapter's 1 ms timer yields cost about 7% on typed obligations.
## #282: consolidate plan observations
Time-off periods, work sequences, public-holiday weeks, balance observations,
the placement list and both tie keys now live in
`src/app/services/plan-observations.ts`. The code moved without behavior
changes. All seven scenarios produce byte-identical outcomes, explanations and
final states compared with `a871f8f`.
| Measurement | Before | After |
| ------------------- | --------: | --------: |
| Vitest duration | 262.000 s | 262.030 s |
| Loaded year | 66.010 s | 66.497 s |
| Typed obligations | 4.887 s | 4.964 s |
| Two years | 2.914 s | 2.977 s |
| Three years | 10.203 s | 10.049 s |
| Representative year | 0.557 s | 0.569 s |
The differences are within run-to-run noise. The functional suite passes
666 tests across 34 files, including the frozen-engine check.
## #283: incremental plan observations
Each placements map now carries an immutable occupancy: its sorted placement
dates, time-off period groups, public-holiday-week completeness and lazily
computed calendar observations. A candidate derived from its parent by one added
or removed date, or by a copy with the same dates, updates only the affected
groups and holiday weeks. Unchanged groups keep their cached periods and
observation objects. Maps built from snapshots, maps observed against another
calendar and dates that are not in-horizon working days fall back to the
from-scratch computation.
The from-scratch computation remains the oracle. A fast-check property test
applies random add, remove and retype sequences across year boundaries, horizon
edges, declared days, weekends and public holidays, and compares every step with
it. An opt-in shadow mode (`VAC_OBSERVATION_SHADOW=1` or
`setObservationShadowMode(true)`) compares both on every observation and throws
on any mismatch. It passed across the frozen-engine check and all seven
benchmark scenarios, whose outcomes, explanations and final states stay
byte-identical.
| Measurement | Before | After |
| ------------------- | --------: | --------: |
| Vitest duration | 262.030 s | 193.680 s |
| Loaded year | 66.497 s | 48.489 s |
| Typed obligations | 4.964 s | 4.947 s |
| Two years | 2.977 s | 1.906 s |
| Three years | 10.049 s | 6.152 s |
| Representative year | 0.569 s | 0.441 s |
A fresh loaded-year CPU profile of the bundled core took 46.8 seconds. Of the
1.68 million observed placement maps, one was built from scratch; the rest were
derived. Observations now take about 4 seconds. Candidate evaluation still
dominates: 24.3 seconds in `evaluateRuleCandidate`, including 15.2 seconds of
active objectives and 6.9 seconds of candidate finalization, plus 6.2 seconds
assigning dates and about 5 seconds each of garbage collection and timer idle
time.
The functional suite passes 669 tests across 35 files.
## #284: prune candidates that cannot beat the protected prefix
Before #284, `evaluateRuleCandidate` finalized every candidate before comparing
its objectives. In the loaded year, 650,369 of 1,233,535 evaluations (53%) then
ended at a worse protected prefix. For typed obligations it was 74,336 of
273,470, and for three years 38,048 of 193,621.
Finalizing never moves or retypes a placement. It edits only rule
provenance, supporting status, earned activations and earned balances. Before
finalizing, the evaluation therefore walks the candidate's protected prefix in
objective order, using only objectives whose pre-finalize value is already their
exact final value, so the bound is tight:
- time-window and if-then preferences read only placement dates and types,
plus declared days;
- public-holiday-week, time-off-period and work-sequence optimizations read
only the placement dates;
- leave-balance optimizations are exact only when no enabled if-then rule earns
days and the candidate has no earned activation;
- leave-placement optimizations have no safe bound, because finalizing rewrites
supporting status.
The walk prunes at the first differing objective when it is worse than the
baseline. It stops without pruning at a better value or at an objective without
a safe bound. A pruned candidate would have failed finalization or returned at
the same comparison, and incumbents are retained only after the full objective
vector is built. Pruning therefore never changes which candidate wins or which
incumbent is retained.
The frozen-engine check now also runs every tenth seed through both engines'
asynchronous adapter, cancelled after a seed-derived number of steps. It
compares outcomes, artifacts, every checkpoint, the explanation and outcome
callbacks, and the step count. Of those 500 cases, 422 end incomplete and 217
of those keep an incumbent. Pruning on any differing objective breaks both
variants. Wrongly treating leave-placement or earning leave-balance objectives
as exact went undetected, because the generated requests rarely put those
objectives in a protected prefix, so their exclusion rests on the argument
above. The check now takes about 60 seconds with coverage.
| Measurement | Before | After |
| ------------------- | --------: | --------: |
| Vitest duration | 193.680 s | 180.250 s |
| Loaded year | 48.489 s | 44.287 s |
| Typed obligations | 4.947 s | 5.023 s |
| Two years | 1.906 s | 1.837 s |
| Three years | 6.152 s | 5.935 s |
| Representative year | 0.441 s | 0.400 s |
All seven scenarios keep byte-identical outcomes, explanations and final states.
The functional suite passes 684 tests across 35 files.
## #286: speed target not reached
The target is a loaded year under 10 seconds and every other scenario under 3
seconds, using the existing protocol in Node on the development laptop. The
exact optimizations of #282 to #284 do not reach it. Means from the latest
protocol run, with the #285 calibration of 2.854 seconds:
| Scenario | Target | Latest | Gap factor |
| --------------------------- | -----: | -------: | ---------: |
| Loaded year | < 10 s | 44.094 s | 4.4x |
| Typed obligations | < 3 s | 5.071 s | 1.7x |
| Three years | < 3 s | 5.887 s | 2.0x |
| Two years | < 3 s | 1.865 s | met |
| Representative year | < 3 s | 0.402 s | met |
| Chained earned entitlements | < 3 s | 0.025 s | met |
| Deliberate conflict | < 3 s | 0.013 s | met |
From develop after PR #278 to now, the loaded year went from 66.0 to 44.1
seconds (−33%), three years from 10.2 to 5.9 seconds and two years from 2.9 to
1.9 seconds. Typed obligations is unchanged at about 5 seconds. The protocol went
from 262.0 to 180.3 seconds.
Because the target is not met, the #285 multipliers stay at current speed and
the hang-guard timeout is not lowered. #286 remains open for a
separate decision on search changes.
### Remaining loaded-year profile
A fresh CPU profile of the bundled core at the #285 commit took 43.5 seconds,
with outcomes still byte-identical:
| Inclusive cost | Seconds |
| ----------------------------------------------------------------------- | ------: |
| Candidate evaluation (`evaluateRuleCandidate`) | 21.4 |
| — active objectives, including the pruning walk | 16.7 |
| — of which objective evaluation (`evaluateOptimization`) | 7.7 |
| — of which plan observations | 4.2 |
| — candidate finalization | 2.7 |
| Date assignment and release (`assignDateToBalance`, `releasePlacement`) | 8.1 |
| Garbage collection | 5.1 |
| Idle time between asynchronous slices | 4.6 |
The remaining cost is spread over about 1.2 million candidate evaluations
rather than concentrated in one computation. Further exact work could:
- yield with something cheaper than a 1 ms timer between 8 ms slices, saving up
to the 4.6 seconds of idle time;
- validate optimization configurations once instead of on every evaluation,
about 1 second;
- copy fewer balances and earned activations when assigning a date.
Together these are worth perhaps 8 to 10 seconds, still well above 10 seconds
for the loaded year. Reaching the target needs fewer candidate evaluations,
which is a search change outside #279's exactness constraint.
### ADR 0003
ADR 0003 targets five seconds for the dependency-free planner. Under composable
optimization rules, the loaded year takes about 44 seconds in Node on the
development laptop even after these exact optimizations. That target should be
revisited for the loaded year, together with the decision on search changes.
This record does not revise the ADR.
+293
View File
@@ -0,0 +1,293 @@
# Issue #302: plan from the best-ranked obligation solution
Step-by-step record for [issue #302](https://gitea.nessar.fr/nessar/vac-optimizer/issues/302).
The exact steps keep planning outcomes, stable explanations and final states
identical to the frozen engine at `a871f8f`. The
[frozen-engine differential check](README.md#frozen-engine-differential-check),
including its cancelled asynchronous comparisons, passes after every step.
That check does not compare counterfactual analyses. Code review found that the
last exact step, which shares unchanged activations between states, let
counterfactual analysis edit an activation it shared with the final plan, so a
later alternative date could inherit an earlier one's dates. A follow-up commit
replaces that activation instead of editing it. Afterwards, every
counterfactual of every plan placement for seeds 280000 to 289999, 8,750
analyses, matched the engine before that step; the same comparison found 4
differences with the step alone.
## Per-step measurements
Each step was timed against its parent in the same session, on the development
machine (AMD Ryzen 7 7800X3D, WSL2, Bun 1.4.3), with no other test, build or
profiling workload running. Both commits' cores were bundled with the
frozen-engine build command and called through `calculatePlanningAsyncInternal`
in one Bun process, with `calculationDate: '2024-01-01'`. This is the
benchmark's in-thread asynchronous path, without the planning-calculation
service. For every scenario, each engine ran one warm-up and then one measured
calculation, alternating engines. Outcomes, explanations and final states were
hashed; every pair below matched. Only same-session pairs are comparable.
### Reuse the donor ranking across public-holiday weeks
For every public-holiday week, the holiday-week stage ranked every placement as
a potential donor by releasing it and evaluating the active objectives. That
ranking depends only on the plan, so the weeks of one plan now share each
placement's released objectives. Each week still skips its own dates and walks
the placements in the same order with the same yields.
| Scenario | Before (s) | After (s) |
| --------------------------- | ---------: | --------: |
| representative year | 0.66 | 0.66 |
| typed obligations | 5.11 | 4.89 |
| chained earned entitlements | 0.02 | 0.02 |
| deliberate conflict | 0.01 | 0.01 |
| loaded year | 58.26 | 57.75 |
| two years | 2.27 | 1.82 |
| three years | 7.45 | 5.52 |
### Retain the best valid plan more cheaply
Retaining a better valid plan for cancellation reconciled its optimization
provenance. For every placement credited by an optimization rule, that
evaluated all active objectives with the placement released. Only the credited
objectives are compared, so the released plan now evaluates just those, and
the calendar observations of the other objectives are no longer computed.
Retention also no longer computes quality metrics that nothing read. An
instrumented three-year run spent 1.16 of its 1.22 retention seconds in that
reconciliation; afterwards retention took 0.26 seconds.
| Scenario | Before (s) | After (s) |
| --------------------------- | ---------: | --------: |
| representative year | 0.45 | 0.37 |
| typed obligations | 4.76 | 5.03 |
| chained earned entitlements | 0.02 | 0.02 |
| deliberate conflict | 0.01 | 0.01 |
| loaded year | 55.59 | 53.58 |
| two years | 1.68 | 1.22 |
| three years | 5.29 | 3.85 |
The typed-obligations difference is run-to-run noise; its retention cost was
22 milliseconds.
### Yield between asynchronous slices without a timer
The asynchronous adapter yields roughly every eight milliseconds. Each yield
waited for a zero-delay timer: about 1.1 ms in Bun, and at least 4 ms in
browsers once timers nest. Browsers now yield through a message-channel task.
Bun runs port messages ahead of timers and incoming worker messages, so a
message-channel yield there kept cancellation and the heartbeat from running
until the calculation ended. Bun therefore yields with `setImmediate`, which
costs about 0.01 ms and lets both run between slices.
| Scenario | Before (s) | After (s) |
| --------------------------- | ---------: | --------: |
| representative year | 0.37 | 0.31 |
| typed obligations | 4.74 | 4.02 |
| chained earned entitlements | 0.02 | 0.01 |
| deliberate conflict | 0.01 | 0.00 |
| loaded year | 53.80 | 46.90 |
| two years | 1.23 | 1.04 |
| three years | 3.86 | 3.21 |
The browser path was checked in headless Chromium 149 on the same machine, in a
dedicated worker with a 50 ms heartbeat timer, running the bundled core before
and after this step, alternating, twice each. The `three years` calculation took
3.92 and 3.89 seconds before and 2.70 and 2.66 seconds after; `representative
year` took 0.51 and 0.45 seconds before and 0.30 seconds after. The heartbeat's
largest gap stayed between 58 and 67 ms in every run. Cancelling `three years`
one second after the request returned the retained plan 3.9 to 4.0 ms after the
cancel message reached the worker, against 7.2 to 8.7 ms before. This is desktop
evidence, not a reference-phone measurement.
### Validate each optimization configuration once
Every objective evaluation revalidated its optimization configuration against
the catalog. Rule normalization already validates each configuration once per
calculation and keeps its own copy. The presets are constant, and the summed
variant of a valid configuration is valid because every catalog row accepts
the sum. The core therefore scores them without revalidating;
`evaluateOptimization` still validates for its other callers.
| Scenario | Before (s) | After (s) |
| --------------------------- | ---------: | --------: |
| representative year | 0.35 | 0.30 |
| typed obligations | 4.03 | 3.46 |
| chained earned entitlements | 0.01 | 0.01 |
| deliberate conflict | 0.00 | 0.00 |
| loaded year | 48.12 | 44.03 |
| two years | 1.04 | 0.96 |
| three years | 3.35 | 3.03 |
### Copy only the debited balance when assigning a date
Assigning a date copied every balance and every earned activation. Balances and
activations are only edited right after a state copies them, so the new state
now shares them with its parent, except the balance it debits. Placement copying
is unchanged. The benchmark scenarios have at most six balances and few earned
activations, so the gain is within run-to-run noise.
| Scenario | Before (s) | After (s) |
| --------------------------- | ---------: | --------: |
| representative year | 0.29 | 0.28 |
| typed obligations | 3.38 | 3.27 |
| chained earned entitlements | 0.01 | 0.01 |
| deliberate conflict | 0.00 | 0.00 |
| loaded year | 43.93 | 44.05 |
| two years | 0.95 | 0.92 |
| three years | 3.00 | 2.97 |
Across the five exact steps, the same harness measured three years at
7.45 seconds before the first step and 2.97 seconds after the last, two years at
2.27 and 0.92 seconds, typed obligations at 5.11 and 3.27 seconds, and the loaded
year at 58.26 and 44.05 seconds. These figures come from different sessions.
## Choosing the obligation solution
This is the one deliberate behavior change
([ADR 0010](../adr/0010-rank-obligation-solutions-before-preferences.md)).
When obligation rules can be satisfied jointly in several ways, the planner used
to run the whole preference chain on candidate solutions as previews: every
solution when their enumeration completed, or the eight best-ranked when a
window search stopped at its limit. It kept the solution whose preview scored
best and ran the preference stages again on it. The planner now orders the
solutions by the pre-preference ranking that chose those eight, the active
objectives then the tie-breaks of each obligation-only plan, with enumeration
order breaking equal ranks. It runs the preference stages once, on the first
solution. If that run ends with earned leave available only after its final
merged time-off period, the stages restart on the next solution, and a
conflict is reported only when every solution fails. With several solutions,
that is the obligation conflict the previews reported when every preview
failed.
### Timing
Measured like the exact steps, against the last exact step, with two measured
calculations per engine. All seven scenarios keep byte-identical outcomes,
explanations and final states.
| Scenario | Before (s) | After (s) |
| --------------------------- | ---------: | --------: |
| representative year | 0.26 | 0.26 |
| typed obligations | 3.26 | 0.11 |
| chained earned entitlements | 0.00 | 0.01 |
| deliberate conflict | 0.00 | 0.00 |
| loaded year | 43.09 | 5.54 |
| two years | 0.94 | 0.97 |
| three years | 3.10 | 3.06 |
### Comparison record
The opt-in runner compares the current engine with the calibration engine
(`a871f8f`, which still previews) on the frozen-engine check's 5,000 seeded
requests. It runs outside the functional suite and CI:
```sh
bun src/app/services/frozen-engine/compare-engines.ts small 280000 5000 calibration
```
| Result | Requests |
| --------------------------------- | -------: |
| Identical | 4,970 |
| Same objective values, other plan | 6 |
| Better | 1 |
| Worse | 23 |
| Changed outcome kind | 0 |
Fourteen of the worse requests differ only in a final tie-break: eight on
placement dates and six on balance expiry. The other nine are worse on a real
objective:
| Seed | Worse objective | Previews → ranking |
| ------ | --------------------------- | ------------------ |
| 280112 | longest work sequence | 2 → 3 |
| 280204 | composed optimization | 6 → 3 |
| 280686 | longest work sequence | 2 → 3 |
| 283162 | supporting placements | 0 → 1 |
| 283484 | longest work sequence | 4 → 5 |
| 283930 | `tw0` preference | 2 → 1 |
| 284628 | longest work sequence | 8 → 16 |
| 284696 | non-working-day gain | 3 → 0 |
| 284824 | short work-sequence deficit | 0 → 2 |
Seed 282254 is better: its `tw1` preference goes from 1 to 2. The runner prints
every non-identical seed with its first differing objective; a first seed and
a count of 1, such as `small 284696 1 calibration`, reproduce a single request.
Without `calibration`, the runner compares against the frozen engine, which is
rebuilt from this change and therefore matches it.
None of these 5,000 requests reaches the earned-entitlement fallback. A
separate search of seeds 200000 to 259999 with the same generator found 28
requests whose best-ranked solution earns its leave too late; all 28 plan from
a later solution, and 26 of them are identical to the calibration engine's
plan. Without the fallback, each would have become a conflict.
### Loaded-year-sized sample
The 5,000 requests last 7 to 70 days. A second generator,
`generateLoadedYearRequest`, builds one-year requests shaped like the `loaded
year` scenario: four to eight CP or RTT balances of 6 to 14 days, two to four
obligation windows of two or three days in distinct months, up to two
preference windows, and the six presets. Their window search always stops at its
solution limit, so the calibration engine previews eight solutions. Fifty of
them were compared, in five parallel runs of ten seeds:
```sh
bun src/app/services/frozen-engine/compare-engines.ts loaded-year 302000 50 calibration
```
| Result | Requests |
| ------------------------------- | -------: |
| Identical | 45 |
| Worse, placement-date tie-break | 1 |
| Worse on a real objective | 4 |
| Better or changed outcome kind | 0 |
| Seed | Worse objective | Previews → ranking |
| ------ | --------------------- | ------------------ |
| 302011 | longest work sequence | 14 → 19 |
| 302033 | public-holiday weeks | 14 → 13 |
| 302040 | `window-4` preference | 2 → 1 |
| 302049 | longest work sequence | 25 → 30 |
On these larger plans, ranking loses a real objective more often than on the
small requests: 4 in 50, against 9 in 5,000. The synchronous calibration engine
took 3,924 seconds for the 50 requests, about 78 seconds each, and the current
engine 289 seconds, about 5.8 seconds each.
## Benchmark protocol
The unchanged benchmark protocol ran on the development machine before the
first exact step (`b356117`, from a separate worktree) and after the frozen
engine rebuild, one after the other in the same session, with no other
workload:
```sh
timeout 600s bun test src/app/benchmark --timeout=600000
```
| Scenario | Before (s) | After (s) | Target (s) |
| --------------------------- | ---------: | --------: | ---------: |
| representative year | 0.45 | 0.24 | 3 |
| typed obligations | 4.70 | 0.10 | 3 |
| chained earned entitlements | 0.03 | 0.01 | 3 |
| deliberate conflict | 0.01 | 0.00 | 3 |
| loaded year | 57.25 | 5.51 | 10 |
| two years | 2.19 | 0.93 | 5 |
| three years | 7.03 | 3.11 | 5 |
| calibration (`two years`) | 3.40 | 3.30 | |
| whole test run | 232.37 | 40.78 | |
Each figure is the mean of the two measured calculations. All seven scenarios
keep their outcomes, placement counts, completed stages and determinism, and
every scenario now meets its target.
### Gate
For [#286](https://gitea.nessar.fr/nessar/vac-optimizer/issues/286), the
multipliers now add about 1.5 times headroom to these ratios:
0.15 for the representative year, 0.1 for typed obligations, 0.05 for the two
tiny scenarios, 2.5 for the loaded year, 0.5 for two years and 1.5 for three years.
srvhome is about 1.9 times slower than nessar-desktop, so it should need about
80 seconds for the protocol. The CI `timeout` is now 240 seconds and the test
timeout 210 seconds, about three times that. The CI benchmark has not yet run
on the Gitea runners with these values.
+112
View File
@@ -0,0 +1,112 @@
# Issue #321: reduce JavaScriptCore hotspots in the planner
Record for [issue #321](https://gitea.nessar.fr/nessar/vac-optimizer/issues/321).
Every change is exact: planning outcomes, stable explanations and final states
are unchanged. The
[frozen-engine differential check](README.md#frozen-engine-differential-check),
including its cancelled asynchronous comparisons, passes.
## Benchmark protocol
Development machine (AMD Ryzen 7 7800X3D, WSL2, Bun 1.4.3), no other workload,
`bun test --isolate src/app/benchmark/leave-planner-benchmark.spec.ts`. Both
runs are from 2026-11-11: before at `5810b59`, after with the changes below.
Each scenario has one warm-up and two measured repetitions; the ratio divides
the mean by the same run's frozen-engine calibration.
| Scenario | Before, mean (s) | Before, ratio | After, mean (s) | After, ratio |
| --------------------------- | ---------------: | ------------: | --------------: | -----------: |
| calibration | 3.85 | — | 3.44 | — |
| representative year | 0.26 | 0.07 | 0.19 | 0.06 |
| typed obligations | 0.11 | 0.03 | 0.07 | 0.02 |
| chained earned entitlements | 0.00 | 0.00 | 0.00 | 0.00 |
| deliberate conflict | 0.00 | 0.00 | 0.00 | 0.00 |
| loaded year | 6.31 | 1.64 | 2.70 | 0.78 |
| two years | 1.10 | 0.29 | 0.54 | 0.16 |
| three years | 3.55 | 0.92 | 1.66 | 0.48 |
Outcomes, final stages, placement counts and determinism are identical in both
runs. These are Bun measurements on a desktop; they establish no browser or
phone speedup.
## What changed
The Bun profile of the loaded year spent 57% of its time scoring candidate
plans. The causes were specific to JavaScriptCore or to intermediate
allocations, not to the search:
- **Frozen lists.** In Bun 1.4.3, `Object.freeze` on a 40-element array costs
about 50 times the `map` that builds it, and reading a frozen array is about
12 times slower than reading a plain one. The lists that plan observations
build per candidate plan (public-holiday weeks, time-off periods, work
sequences) are no longer frozen. Their elements stay frozen, their types stay
`readonly`, and the cached calendar periods, whose frozen date arrays key the
date-count cache, are unchanged. Work sequences reuse one frozen object per
distinct `(length, internal)` pair.
- **Scoring without intermediate arrays.** `evaluateValidatedOptimization`
aggregates in one loop instead of `filter`, `map` and `reduce`; observation
lists of balances and placements are built on first read; a TIME_WINDOW
preference counts its placements in place and stops at its requested
quantity; the expiry tie-break sorts without a comparator.
- **Work already done.** A finalized candidate has no unsatisfied obligation,
so its objective vector no longer counts them again. The retained plan's
state key is built once. An earned entitlement's merged period is found among
the plan's periods without materializing all of them, and the date arithmetic
of its availability runs once per distinct period.
- **Pruning with rules that earn leave.** A candidate that is already worse on
a protected objective is rejected before it is finalized. The unplaced
at-risk objective used to disable this whenever a rule could earn leave,
which the default Samedi Malin rule does. It now stays active for a candidate
whose finalization cannot touch an earned balance: no new pattern completes,
every earned entitlement keeps its pattern, and its balance already carries
its period's dates.
## Requests outside the seeded check
The seeded requests of the differential check span at most ten weeks. The
changes above were also compared with the engine at `5810b59` on 26 requests of
one to four years: the optimization presets with the default Samedi Malin and
Christmas rules, Samedi Malin alone, Samedi Malin earning two CP days, and each
of those with an obligation, with 5 to 37 days per year. Outcomes, explanations
and final states matched, as did two cancelled asynchronous runs per request
(after 2,000 and 20,000 polls) with their checkpoints. Twelve of these plans
hold earned entitlements. The working tree was about twice as fast throughout.
## Findings left open
These are search behaviors, not hotspots. Changing them can change plans, so
[ADR 0010](../adr/0010-rank-obligation-solutions-before-preferences.md)
requires a deliberate, recorded change; none is made here. Unless noted, times
are after the changes above.
- **Obligations with a rule that earns leave**
([#347](https://gitea.nessar.fr/nessar/vac-optimizer/issues/347)). When a preference IF_THEN rule
earns leave and any obligation needs a placement, every occurrence of that
rule joins the obligation search as an optional producer and the solution
limit is lifted. Three years of 5 CP with Samedi Malin and one obligation of
5 days in a four-week window take 12.8 seconds, almost all in the
`obligations` stage. The same request with an obligation that cannot be met
(10 CP required, 5 available) took 245 seconds over four years before the
conflict was reported, measured before the last three changes above. A prototype that keeps only the producers whose reward
can fund a later obligation date ran these in 0.5 and 0.2 seconds. It changes
plans: in the two-year case Samedi Malin is no longer satisfied (10
placements instead of 11), because the obligation search no longer places its
pattern ahead of higher-priority preferences. The seeded check does not see
the difference.
- **A window preference after a rule that earns leave**
([#348](https://gitea.nessar.fr/nessar/vac-optimizer/issues/348)). With the default
rules, three years of 25 CP and 12 RTT take 17 seconds, 12.6 of them in the
Christmas stage; without Samedi Malin that stage takes 6 milliseconds. The
likely cause, not verified here, is the stage's early return when every
earlier objective is at its bound, which an unsatisfied IF_THEN preference
never is.
- **Samedi Malin as the first priority**
([#349](https://gitea.nessar.fr/nessar/vac-optimizer/issues/349)). One year of 25 CP and 12 RTT with
Samedi Malin ahead of loss prevention does not finish the loss-prevention
stage in 100 seconds; with loss prevention first it takes 0.3 seconds.
- **The frozen engine differs from `5810b59` on a three-year request**
([#350](https://gitea.nessar.fr/nessar/vac-optimizer/issues/350)). With
the default rules, 5 CP per year from 2025 to 2027 and a 2025-01-01
calculation date, the two engines place four placements differently around
May 2027. The difference predates this issue and the seeded check does not
reach it.
+15
View File
@@ -0,0 +1,15 @@
scenario repetition preparation_ms planning_ms wall_ms outcome last_stage placements deterministic max_ui_delay_ms planning_work_ms peak_main_thread_heap_bytes
representative year 1 0.1 564.4 564.6 Plan dates 30 baseline 8.0 552.6 ""
representative year 2 0.0 555.0 555.1 Plan dates 30 yes 8.1 544.4 ""
typed obligations 1 0.1 5040.7 5040.8 Plan dates 10 baseline 11.3 5030.5 ""
typed obligations 2 0.1 5141.2 5141.3 Plan dates 10 yes 12.9 5131.1 ""
chained earned entitlements 1 0.1 29.0 29.1 Plan dates 3 baseline 0.0 21.6 ""
chained earned entitlements 2 0.1 24.7 24.8 Plan dates 3 yes 0.0 17.4 ""
deliberate conflict 1 0.1 13.0 13.2 PlanningConflict 0 baseline 0.0 3.1 ""
deliberate conflict 2 0.0 12.6 12.7 PlanningConflict 0 yes 0.0 2.8 ""
loaded year 1 0.1 76341.7 76341.8 Plan dates 72 baseline 16.8 76326.9 ""
loaded year 2 0.1 79093.8 79094.0 Plan dates 72 yes 16.3 79074.9 ""
two years 1 0.1 3391.7 3391.9 Plan dates 60 baseline 12.9 3375.3 ""
two years 2 0.1 3282.6 3282.8 Plan dates 60 yes 10.9 3267.1 ""
three years 1 0.1 11333.3 11333.5 Plan dates 90 baseline 13.9 11313.4 ""
three years 2 0.1 11394.2 11394.3 Plan dates 90 yes 15.7 11368.4 ""
1 scenario repetition preparation_ms planning_ms wall_ms outcome last_stage placements deterministic max_ui_delay_ms planning_work_ms peak_main_thread_heap_bytes
2 representative year 1 0.1 564.4 564.6 Plan dates 30 baseline 8.0 552.6
3 representative year 2 0.0 555.0 555.1 Plan dates 30 yes 8.1 544.4
4 typed obligations 1 0.1 5040.7 5040.8 Plan dates 10 baseline 11.3 5030.5
5 typed obligations 2 0.1 5141.2 5141.3 Plan dates 10 yes 12.9 5131.1
6 chained earned entitlements 1 0.1 29.0 29.1 Plan dates 3 baseline 0.0 21.6
7 chained earned entitlements 2 0.1 24.7 24.8 Plan dates 3 yes 0.0 17.4
8 deliberate conflict 1 0.1 13.0 13.2 PlanningConflict 0 baseline 0.0 3.1
9 deliberate conflict 2 0.0 12.6 12.7 PlanningConflict 0 yes 0.0 2.8
10 loaded year 1 0.1 76341.7 76341.8 Plan dates 72 baseline 16.8 76326.9
11 loaded year 2 0.1 79093.8 79094.0 Plan dates 72 yes 16.3 79074.9
12 two years 1 0.1 3391.7 3391.9 Plan dates 60 baseline 12.9 3375.3
13 two years 2 0.1 3282.6 3282.8 Plan dates 60 yes 10.9 3267.1
14 three years 1 0.1 11333.3 11333.5 Plan dates 90 baseline 13.9 11313.4
15 three years 2 0.1 11394.2 11394.3 Plan dates 90 yes 15.7 11368.4
+345
View File
@@ -0,0 +1,345 @@
# Issue #78: integrated planner performance
Measurements on 2026-10-15/16 (Europe/Paris), starting from the trace-free
integrated planner at `2f4af14869c47836d2c1008157136f75c9d3e98b`.
[Issue #78](https://gitea.nessar.fr/nessar/vac-optimizer/issues/78) supplies the
acceptance criteria. The original spec, baseline source, profiles, diagnostic
runners and complete local logs are retained in `/tmp/vac-issue-78`.
## Required protocol
```sh
NODE_OPTIONS=--max-old-space-size=2048 timeout 300s bunx vitest run src/app/benchmark/leave-planner-benchmark.spec.ts --maxWorkers=1
```
| Run | Result |
| --------------------------------- | ----------------------------------------------------------------------------------------------------- |
| Unmodified baseline | External timeout, exit 124, 300.008 seconds; no complete report. |
| Optimized planner | Exit 0, 298.551 seconds externally; Vitest reports 294.16 seconds, with 292.958 seconds in the test. |
| Restart-interrupted optimized run | Stopped by the agent-server restart before a result; excluded from acceptance and timing comparisons. |
The passing run includes the existing typed-obligation precheck, all seven
warm-ups, and two measured repetitions of every scenario. Coverage is disabled,
the Node heap is limited to 2048 MiB and the full command retains its 300-second
timeout. No other build, test or profiling workload ran alongside it.
[The complete 14-row report](issue-78-protocol.tsv) preserves every measured row.
Every repetition has its expected outcome, placement count and final stage;
each second repetition matches its first complete outcome. The deliberate
conflict remains a conflict with zero placements. The other scenarios complete
through `dates`, with 30, 10, 3, 72, 60 and 90 placements respectively.
The fixture module is byte-for-byte unchanged, SHA-256
`16e057fa042c898d203f71e018f183c9fbecb5cd0edbf0ce0f3f25277cb00d3a`.
The test change only prints its existing report; all correctness assertions,
configurations, quotas, horizons, warm-ups and repetition counts remain intact.
There are no trace counters, transfers or acknowledgement waits.
The passing command has only **1.449 seconds of external-timeout headroom**.
This is a local pass, not a runner-speed guarantee. Gitea Actions now requires
benchmark success before image publication and the aggregate `required` check.
A successful live PR run, publication setup and migration-gate activation remain
with [#268](https://gitea.nessar.fr/nessar/vac-optimizer/issues/268). No issue is
closed by this local verification.
## Environment and memory
AMD Ryzen 5 7640U, 12 logical CPUs, approximately 16 GiB RAM; Linux
`6.18.33.2-microsoft-standard-WSL2`. Node 24.18.0, Bun 1.3.14, Vitest 5.0.3,
TypeScript 6.0.3, Angular core 22.2.1 and date-holidays 3.30.2. The calculation
calendar date is fixed to `2024-01-01`, matching the benchmark test. Node runs
are unthrottled. These versions differ from the configured CI container's
Node 24.21.0 and Bun 1.4.2; live CI performance has not been measured here.
The passing protocol's sampled peak process-tree RSS is **1,528,056 KiB**,
sampled every 500 ms across the timeout/Bun/Vitest process tree. RSS includes
multiple processes and runtime overhead; it is not a JS-heap measurement.
Chromium's `performance.memory` is unavailable in the Node protocol, so its
`peak_main_thread_heap_bytes` cells remain blank.
## Profile and changes
A separate, explicitly interrupted 20-second loaded-year diagnostic used Node's
inspector CPU and allocation sampling. Candidate finalization, state copying,
calendar observation construction, period bounds and work-sequence scanning
were substantial costs. Allocation sampling included collected objects; its
cumulative allocation estimates are not peak live memory or protocol timings.
The diagnostic retained a valid 72-placement partial plan on cancellation.
A separate 20-second repeated-work probe observed 29 preference-pass executions
and no identical input-state revisit among cache misses. Complete obligation
previews remain in place; there is no new state-equivalence or search-budget
shortcut.
The change addresses those measured paths:
- Evaluate objectives in their actual priority order. Once a protected prefix
loses, or an admissible candidate loses to the current best candidate, lower
objective values cannot reverse that lexicographic comparison. Full vectors
remain available for retained improvements, displayed explanations and date
analysis; tied-prefix additions keep their original retention behavior.
- Build cached calendar observations only when an evaluated objective needs
them. The existing request-local, 4096-entry geometry cache retains its
boundary; balance quantities, provenance and supporting status remain outside
it. Work-sequence lengths use the prepared working-day prefixes and period
anchors instead of rebuilding every sequence's date array for scoring.
- Share existing placements for reading during a single-date assignment, while
continuing to copy balances and earned activations. Bundle and relocation
paths detach placements before changing supporting status. Snapshot,
provenance and other mutable-copy paths retain their deep copies.
- Reuse calendar-request validation during finalization instead of looking up
and scanning the same provenance again for each placement.
No candidate destinations, allocation choices, obligation previews or rule
priorities are removed. Search limits, earned-entitlement chronology, final
quality criteria and deterministic tie-breaks are unchanged. No elapsed-time
engine cutoff is introduced.
## Differential and diagnostic measurements
Complete outcomes, stable explanations and final-state snapshots are compared
with the saved baseline. The configuration matrix contains 182 cases: supported
conditions, aggregations and directions; personal objectives before and after
loss prevention; typed obligations and preferences; declarations; at-risk and
deferred balances; custom deficit thresholds; and empty/disabled rule lists.
Three permanent regression cases also pin reordered and custom objective
vectors, placement dates, provenance and first decisive objectives.
All seven completed diagnostic comparisons also match in full, including the
loaded year and both longer horizons. Table cells show **before → after**.
| Scenario | Preparation (ms) | Planning work (s) | Wall through explanation (s) | Maximum timer delay (ms) | Sampled Node heap (MiB) |
| --------------------------- | ---------------- | ----------------- | ---------------------------- | ------------------------ | ----------------------- |
| representative year | 39.7 → 37.5 | 1.261 → 0.787 | 1.302 → 0.826 | 7.7 → 8.5 | 76.5 → 90.8 |
| typed obligations | 10.9 → 9.4 | 8.563 → 5.642 | 8.574 → 5.652 | 7.8 → 11.2 | 127.7 → 115.1 |
| chained earned entitlements | 5.4 → 6.7 | 0.025 → 0.026 | 0.030 → 0.033 | 0.0 → 0.0 | — → — |
| deliberate conflict | 10.1 → 9.5 | 0.004 → 0.004 | 0.013 → 0.013 | 0.0 → 0.0 | — → — |
| loaded year | 8.8 → 9.1 | 143.648 → 72.029 | 143.664 → 72.043 | 14.6 → 16.2 | 206.1 → 177.3 |
| two years | 17.6 → 12.3 | 5.470 → 2.962 | 5.491 → 2.977 | 13.3 → 11.0 | 186.9 → 164.8 |
| three years | 16.4 → 14.4 | 19.674 → 10.287 | 19.696 → 10.310 | 15.8 → 16.1 | 289.2 → 253.5 |
The cold diagnostics run each unchanged scenario once, without warm-up or
coverage, through `calculatePlanningAsyncInternal`, with the same 2048 MiB heap
and calculation date. They are separate from the acceptance protocol. Occasional
focused/static checks ran during the baseline investigation; those diagnostic
timings are informational, not an isolated speedup estimate. The final diagnostic
run has no competing build/test workload.
Diagnostic preparation ends at the first non-preparation progress callback;
planning work comes from the core's timing artifact; wall time ends after
explanation delivery. In the protocol TSV, `preparation_ms` instead measures
request cloning, while calendar preparation is included in `planning_ms`.
Diagnostic timer delay and `process.memoryUsage().heapUsed` are sampled every
50 ms. Heap is the whole Node process, including earlier scenarios' live data
and caches. A dash means no interval sample was taken before a fast scenario
finished. These are neither allocation totals nor worker-isolated heap claims.
## Native browser checks
Production build, native Chrome 150.0.7871.186 Workers, 375×915 viewport,
device scale 1, reduced motion and 4× CPU throttling on the laptop above.
Each completion uses a new page and worker in one isolated Chrome process,
without a planner warm-up; browser/resource caches are shared between pages.
The cancellation checks use a separate isolated Chrome process. No other
build, test or profiler runs alongside these measurements.
| Scenario | Outcome usable (s) | Calendar ready (s) | Full artifact delivery (s) | Maximum page timer delay (ms) | Peak page heap (MiB) | Chrome RSS before / after outcome (MiB) |
| ------------------- | ------------------ | ------------------ | -------------------------- | ----------------------------- | -------------------- | --------------------------------------- |
| representative year | 2.070 | 2.574 | 2.158 | 886.5 | 22.8 | 1482.5 / 1488.4 |
| two years | 5.864 | 6.879 | 6.878 | 1287.9 | 22.8 | 1538.1 / 1540.3 |
| three years | 15.865 | 17.864 | 17.861 | 1987.2 | 21.1 | 1503.2 / 1506.8 |
Every completion returns `Plan` through `dates`, with 30, 60 or 90 placements,
its stable explanation and one planning request. Worker heartbeats continue
through the long calculations. There are no unexpected page exceptions or
page-level horizontal overflow at the measured viewport.
During the three-year worker calculation, keyboard editing changed the first
visible balance from 20 to 99. The captured request remained at 20, the plan
still contained 90 placements, and no second calculation was sent. Its displayed
estimate therefore followed the pending edited configuration (22–136 seconds).
The unchanged 90-day inputs in the cancellation runs retain their 11–68 second
range; cancelled outcomes add no completion calibration sample. The existing
session calibration and request-to-rendered-calendar contract are unchanged;
these samples do not justify changing the rough initial estimate.
Page heap is Chromium's main-thread `performance.memory` sample every 50 ms;
it excludes the worker heap. Chrome RSS sums the isolated browser process tree
at 500 ms intervals and outcome/artifact boundaries, including workers,
renderers and shared pages counted in each process's RSS. It is not a unique
physical-memory or worker-heap measurement. The post-outcome samples extend
through calendar readiness and artifact delivery. Calendar readiness is
observed by a 50 ms page timer after the loading overlay disappears, rather
than a physical paint measurement.
The observed page timer delays include calendar rendering and reach about
**2.0 seconds**. Inputs accept edits during worker planning; final calendar
rendering remains a visible main-thread pause.
Both cancellation flows activate Cancel with Enter and send one cancel message,
with no additional planning request:
| Cancellation point | Cancel to outcome (ms) | Cancel to artifacts (ms) | Retained placements |
| ---------------------------------------------------------- | ---------------------- | ------------------------ | ------------------- |
| Before a valid plan, controlled startup | 61.3 | 155.0 | 0 |
| Active optimization, after a valid 90-placement checkpoint | 20.6 | 1979.4 | 90 |
The preparation probe queues outgoing worker messages until the keyboard action,
then releases the plan and cancel in order. It verifies cancellation before any
valid plan, rather than ordinary startup-latency performance. It reports
`PlanningIncomplete` without an incumbent or a false conflict. The active
cancellation displays **Calculation cancelled — partial plan**, retains all 90
placements and delivers its partial-plan explanation. The first keyboard probe
omitted the Enter character event and issued no cancel; it was corrected and
excluded from cancellation evidence.
No physical reference-phone run is available. Desktop CPU throttling does not
establish phone performance or a duration ceiling. The browser reference
protocol still uses three measured repetitions; the required Node protocol uses
two. These counts are unchanged.
## Correctness, static checks and build
```sh
NODE_OPTIONS=--max-old-space-size=2048 bunx vitest run --coverage --maxWorkers=1 --exclude='src/app/benchmark/**'
bunx tsc --noEmit -p tsconfig.app.json
bunx tsc --noEmit -p tsconfig.spec.json
bun run lint
bun run format:check
bunx prettier --check 'scripts/ci-*.mjs' '.gitea/workflows/*.yml'
node scripts/ci-policy.test.mjs
node scripts/ci-image.test.mjs
bun run build
git diff --check
```
All pass. Functional coverage: **633 tests across 33 files**, 93.61% statements,
85.99% branches, 95.70% functions and 95.44% lines, in 92.05 seconds with the
existing 2 GiB Node heap. The separate benchmark also passes, as recorded above.
Coverage settings and thresholds are unchanged. The source changes were also
checked with the 266-test focused planner suite during implementation.
A local probe runs the actual aggregate shell body for 12 combinations of
benchmark and image outcomes. Failed, cancelled and skipped benchmarks block
it; successful benchmarks still preserve the intentional fork/manual image
skip. Both `images` and `required` depend on `benchmark`. The aggregate's first
failed check exits explicitly, without depending on the runner's shell flags.
The production build retains the existing warning budgets: initial bundle
2.57 MB against 2.50 MB, and calendar-year styles 12.98 kB against 8 kB. Both
remain below their unchanged error limits. Sandbox restrictions prevented the
first build/policy attempt; reruns with local socket/child-process permissions
passed. Semgrep and Trivy are not installed locally, so their security jobs,
actual image publication and a live Gitea PR run remain unverified.
## Reproduction
Use the recorded Node/Bun versions and frozen lockfile. Run the exact acceptance
command above from the integrated baseline checkout for the before measurement,
and from this working result for the after measurement. The test prints the
entire TSV report, including failures of its unchanged assertions.
For the separate cold diagnostics, `measure-core.mjs` runs the bundled baseline
or optimized core over the unchanged `benchmarkScenarios()` JSON in fixture
order. Generate that JSON in a separate process so the measured Node process
does not include Angular fixture-export overhead:
```sh
mkdir -p tmp /tmp/vac-issue-78
cat > tmp/issue78-fixtures.ts <<'TS'
import '@angular/compiler';
import { benchmarkScenarios } from '../src/app/benchmark/leave-planner-benchmark';
console.log(JSON.stringify(benchmarkScenarios()));
TS
bun build tmp/issue78-fixtures.ts --target=node --outfile /tmp/vac-issue-78/fixtures.mjs
node /tmp/vac-issue-78/fixtures.mjs > /tmp/vac-issue-78/scenarios.json
```
The diagnostic runner supplies `calculationDate: '2024-01-01'`, captures
outcome/explanation/final-state callbacks, observes preparation progress and
samples timer delay and process heap every 50 ms:
```sh
bun build src/app/services/leave-planner.core.ts --target=node --outfile /tmp/vac-issue-78/optimized-core.mjs
node --max-old-space-size=2048 /tmp/vac-issue-78/measure-core.mjs optimized
node --max-old-space-size=2048 /tmp/vac-issue-78/compare-configurations.mjs
```
The baseline bundle and complete requests, results and profiling sources are
kept beside those runners. CPU/allocation profiling and the cancelled repeated-
work probe are diagnostics only; neither counts as a completed benchmark run.
Save the following as `/tmp/vac-issue-78/measure-core.mjs` to recreate the cold
measurements and complete comparison snapshots. Build `baseline-core.mjs` from
the recorded baseline with the same `bun build` command, then run with
`baseline`; use `optimized` for this implementation.
```js
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
const engine = process.argv[2] || 'baseline';
const { calculatePlanningAsyncInternal } = await import(`./${engine}-core.mjs`);
const directory = new URL(`./${engine}-measurements/`, import.meta.url);
mkdirSync(directory, { recursive: true });
const scenarios = JSON.parse(readFileSync(new URL('./scenarios.json', import.meta.url)));
for (const scenario of scenarios.filter(
(item) => !process.argv[3] || item.name === process.argv[3],
)) {
let artifacts;
let outcomeAt;
let preparationMs;
let peakHeapUsedBytes = 0;
let maxTimerDelayMs = 0;
const start = performance.now();
let lastTick = start;
const sample = setInterval(() => {
const tick = performance.now();
maxTimerDelayMs = Math.max(maxTimerDelayMs, tick - lastTick - 50);
lastTick = tick;
peakHeapUsedBytes = Math.max(peakHeapUsedBytes, process.memoryUsage().heapUsed);
}, 50);
const outcome = await calculatePlanningAsyncInternal(
{
...scenario.request,
calculationDate: '2024-01-01',
progress: (stage) => {
if (stage !== 'preparation') preparationMs ??= performance.now() - start;
},
},
undefined,
(value) => {
artifacts = value;
},
() => {
outcomeAt = performance.now() - start;
},
);
clearInterval(sample);
const measurement = {
scenario: scenario.name,
diagnostic: true,
warmups: 0,
repetitions: 1,
preparationMs,
outcomeMs: outcomeAt,
planningWorkMs: artifacts.timings?.planningWorkMs,
wallMs: performance.now() - start,
maxTimerDelayMs,
peakHeapUsedBytes,
peakRssKiB: process.resourceUsage().maxRSS,
outcome: outcome.kind,
placements: outcome.placements?.length,
lastStage: outcome.lastCompletedStage,
};
writeFileSync(
new URL(scenario.name.replaceAll(' ', '-') + '.json', directory),
JSON.stringify({
measurement,
outcome,
explanation: artifacts.explanation,
finalState: artifacts.finalState,
}),
);
console.log(JSON.stringify(measurement));
}
```
+53
View File
@@ -0,0 +1,53 @@
# PR #278: build placement date keys directly
Measured on 2026-10-16, starting from PR #278 at `cbde23f`.
The unchanged benchmark finished in 299.372 seconds before this change, leaving
only 0.628 seconds before its 300-second timeout. A separate loaded-year CPU
profile attributed 8.27 of 66.57 seconds to `placementTieKey`, including its
callees. That function runs when looking up cached calendar observations and
when comparing final placement dates.
The one-line optimization sorts the placement map's date keys directly, using
native string sorting. It removes the intermediate placement-to-date array and
the comparison callback. Every placement map entry is keyed by its placement's
date, and native string sorting preserves the existing lexical date order, so
the resulting keys are identical. Search choices and scoring are unchanged.
## Before and after
Both runs used Node 24.18.0, Bun 1.3.14, Vitest 5.0.3, the same local machine,
and the exact command below. No other test, build or profiling workload ran
alongside either measurement.
```sh
NODE_OPTIONS=--max-old-space-size=2048 timeout 300s bunx vitest run src/app/benchmark/leave-planner-benchmark.spec.ts --maxWorkers=1
```
All seven warm-ups, fourteen measured calculations, the typed-obligation precheck,
fixtures and assertions remain unchanged. Coverage is disabled for this command.
| Measurement | Before | After |
| ---------------------------------------------- | --------: | --------: |
| Entire command, external wall time | 299.372 s | 268.573 s |
| Benchmark test | 293.620 s | 263.265 s |
| Loaded year, mean of two measured calculations | 76.649 s | 67.747 s |
| Headroom before timeout | 0.628 s | 31.427 s |
The entire command was 10.3% faster in this before-and-after pair. Both runs
completed successfully, and every repeated scenario remained deterministic.
These are local measurements; Gitea runner performance still needs confirmation.
## Correctness checks
Complete outcomes, stable explanations and final-state snapshots match the
baseline for all seven scenarios. These separate comparisons ran alongside
functional checks; their diagnostic timings are not used in the table above.
The functional coverage suite passes all 635 tests across 33 files. Application
and spec type checks, lint, source formatting and `git diff --check` also pass.
No browser timing run or live CI rerun was performed for this change.
The profiling runner and full protocol logs are retained in
`/tmp/vac-opt278-measure`. The original diagnostic reproduction is documented in
[issue-78.md](issue-78.md#reproduction).
@@ -0,0 +1,61 @@
# PR #278: reuse counts for immutable calendar dates
Measured on 2026-10-16 against `c7e7abc`, which already includes the
[direct date-key optimization](pr-278-date-keys.md).
A loaded-year CPU profile attributed 4.06 of 69.37 seconds to repeatedly counting
distinct non-working dates for time-off-period objectives. The existing calendar
cache already shares frozen date arrays between candidate plans, but each score
rebuilt a `Set` to count the same dates again.
The objective evaluator now keeps those counts in a `WeakMap` keyed by the frozen
array. Mutable arrays are recounted on every evaluation. The weak keys allow
unused arrays to be collected, and configuration validation and duplicate-date
handling remain intact. This change touches only that scoring operation.
## Before and after
Both protocol runs used Node 24.18.0, Bun 1.3.14 and Vitest 5.0.3 on the same local
machine. The baseline is the completed run recorded for `c7e7abc`; its saved core
bundle is byte-for-byte identical to a fresh bundle of that commit. No other
test, build or profiling workload ran alongside either protocol measurement.
```sh
NODE_OPTIONS=--max-old-space-size=2048 timeout 300s bunx vitest run src/app/benchmark/leave-planner-benchmark.spec.ts --maxWorkers=1
```
All seven warm-ups, fourteen measured calculations, the typed-obligation precheck,
fixtures, assertions and resource limits remain unchanged.
| Measurement | Before | After |
| ---------------------------------------------- | --------: | --------: |
| Entire command, external wall time | 268.573 s | 256.034 s |
| Benchmark test | 263.265 s | 250.652 s |
| Loaded year, mean of two measured calculations | 67.747 s | 64.360 s |
| Headroom before timeout | 31.427 s | 43.966 s |
The full command was 4.7% faster in this pair. Both runs completed successfully,
and every repeated scenario remained deterministic. Live CI performance still
needs confirmation.
An isolated check using the loaded-year plan's frozen date arrays took
551–554 ms before and 46–57 ms after for 100,000 scoring calls, following 5,000
warm-ups per run in before/after/after/before order. That result isolates the repeated
counting cost; the protocol above measures its effect on complete calculations.
## Correctness checks
Complete outcomes, stable explanations and final-state snapshots match `c7e7abc`
for all seven scenarios. These separate comparisons ran alongside functional
checks; their diagnostic timings are not used in the protocol comparison.
The functional coverage suite passes all 638 tests across 33 files. Three new
regression cases cover duplicate dates and changes to mutable arrays alongside
frozen arrays for sum, count and maximum scores. Application and spec type checks,
lint, formatting and `git diff --check` also pass.
No browser timing run or live CI rerun was performed for this change.
Diagnostic sources, profiles, bundles and full logs are retained in
`/tmp/vac-opt278-step2`. The original core diagnostic runner is documented in
[issue-78.md](issue-78.md#reproduction).
+65
View File
@@ -0,0 +1,65 @@
# PR #278: reject impossible mandatory moves before copying
Measured on 2026-10-16 against `433a8b0`, which includes the
[immutable date-count optimization](pr-278-immutable-date-counts.md).
A loaded-year CPU profile attributed 5.09 seconds to candidate assignment and
6.53 seconds to final validation out of 58.24 seconds. Generic moves and swaps
copied the candidate state before discovering that a mandatory placement's new
date or leave type could never satisfy its rule.
The shared assignment function now calls the existing `mandatoryRelocationDate`
check before copying. It checks only necessary date and type conditions. Complete
multi-day patterns and earned-entitlement chronology are still validated after
the candidate is assembled. Preferences remain movable, and valid alternatives,
objective order and deterministic tie breaks remain unchanged.
## Before and after
Both protocol runs use Node 24.18.0, Bun 1.3.14 and Vitest 5.0.3 on the same local
machine. This comparison uses a fresh baseline from this session. No other test,
build or profiling workload runs alongside either protocol measurement.
```sh
NODE_OPTIONS=--max-old-space-size=2048 timeout 300s bunx vitest run src/app/benchmark/leave-planner-benchmark.spec.ts --maxWorkers=1
```
All seven warm-ups, fourteen measured calculations, the typed-obligation precheck,
fixtures, assertions and resource limits remain unchanged.
| Measurement | Before | After |
| ---------------------------------------------------- | --------: | --------: |
| Vitest duration | 232.630 s | 228.130 s |
| Benchmark test | 231.483 s | 227.011 s |
| Loaded year, mean of two measured calculations | 59.255 s | 57.850 s |
| Typed obligations, mean of two measured calculations | 4.552 s | 4.368 s |
| Headroom before timeout (Vitest duration) | 67.370 s | 71.870 s |
The Vitest duration was 1.9% shorter in this pair. External wall time was not
recorded for these runs. Both runs completed successfully, and every repeated
scenario remained deterministic. The baseline is faster than the one recorded
for the preceding optimization, so only same-session pairs are comparable.
Live CI performance still needs confirmation.
## Correctness checks
Complete outcomes, stable explanations and final-state snapshots match the
baseline for all seven scenarios. Baseline snapshots come from the preceding
optimization's saved run, whose bundle matches a fresh build of `433a8b0` byte for
byte; the loaded-year snapshot was also regenerated in this session. Diagnostic
comparisons ran alongside functional checks, so their timings are not used for
the protocol comparison.
The functional coverage suite passes all 640 tests across 33 files. Two additional
regression cases cover obligations and lower-priority preferences when a calendar
objective competes for the same leave balance. Both cases pass before and after
the optimization. Existing tests also exercise typed reassignments, complete
multi-day patterns, earned entitlements and counterfactual explanations.
Application and spec type checks, lint, source formatting and `git diff --check`
pass.
No browser timing run or live CI rerun was performed for this change.
Diagnostic sources, profiles, bundles and full logs are retained in
`/tmp/vac-opt278-step3`. The original core diagnostic runner is documented in
[issue-78.md](issue-78.md#reproduction).
+304
View File
@@ -0,0 +1,304 @@
# Bun Runtime and Native Tooling — Development Spec
Status: the agreed decisions are amended by the verification results in #289,
recorded below. ADR 0009 remains proposed until the migration passes its final
gate.
## Status
Implementation status after #290 and the local parts of #293. "Verified locally"
means a command ran with Node unavailable (or a tripwire `node` that logs every
start); it is not a result from the live Gitea workflow.
**Done, verified locally:**
- **One pinned release.** Bun 1.4.3 is pinned by `packageManager`, the
checksum-verified `scripts/install-bun.sh` that every CI job running project
commands uses (no npm), the
`@types/bun` version and both Docker stages. The installer refuses a
`package.json` that names another version. Frozen installs leave `bun.lock`
unchanged.
- **Node-shebang tools on Bun.** `bunfig.toml` sets `[run] bun = true`, so
`start`, `build`, `watch`, `lint`, `lint:fix`, `format` and `format:check` run
`ng`, `eslint` and `prettier` on Bun even when Node is on `PATH`. CI also runs
project steps with a `PATH` that has Bun and no Node.
- **Standalone type checking.** `bun run typecheck` runs `bun check` on the
application and test projects. The production build remains the only check of
Angular templates.
- **Tests, coverage, benchmark, server, container** (#291, #292), and the policy
and image-publisher scripts with their regression tests, under Bun. The fake
`docker` fixture uses a `bun` shebang.
**Still open:**
- **Native lint and format (#290, user story 5).** Replace ESLint and Prettier in
one change when a stable Bun ships `bun lint` and `bun fmt`; today they exist
only in canary builds. Until then user story 5 and the matching #290 criteria
stay open.
- **Live Gitea validation (#293).** The custom job `shell` template, the Bun
installer, JavaScript actions beside Node-free project steps, the benchmark's
timing margin and the required checks on the final PR revision have not run on
the live runner. The `images` job still has Alpine's `nodejs` on `PATH` for the
checkout action, which the project command does not use. These and the Gitea
activation steps remain unverified until a live pull-request run.
- **ADR 0009** stays `proposed` until the final gate.
## Problem Statement
The maintainer wants VacOptimizer to use Bun as its actual JavaScript runtime and
adopt its native tooling wherever agreed, even without measurable performance
gains. Today Bun installs dependencies, generates the language registry, and runs
the deployed server, but development commands can launch Node-based CLIs, CI uses
Node containers, and the Docker build explicitly installs Node.
The toolchain is also inconsistent: the local Bun installation is 1.3.14, CI pins
1.4.2, and Docker uses a floating Bun image. Merely prefixing commands with Bun
does not establish which runtime executes their JavaScript.
## Solution
Use Bun for project-owned JavaScript in development, CI, and production. Adopt
Bun's native test runner, linter, formatter, standalone type checker, and HTTP
server. Retain Angular and its standard compiler and build pipeline, running the
JavaScript tooling under Bun.
Preserve the application's existing behavior and verification standards. The
planner remains client-side: planning horizons, planning rules, leave placements,
planning outcomes, plan statistics, and plan explanations retain their current
meaning. Browser code and Web Workers continue to run in the user's browser.
## User Stories
The following acceptance criteria define completion:
1. **Actual Bun execution.** Development serving and watch mode, production
builds, language generation, repository CI scripts, tests, and the production
server execute their project-owned JavaScript under Bun, including spawned
tools and test fixtures. A Node.js fallback does not satisfy this criterion.
2. **Reproducible setup.** Development instructions, CI, and both Docker stages
specify the same exact, verified Bun version. Frozen dependency installation
succeeds from a clean checkout without changing the lockfile, and the
production image installs only production dependencies.
3. **Native tests with preserved behavior.** All existing functional and Angular
component tests execute under `bun test`, preserving assertions, parameterized
cases, clock control, global mocks, cleanup, isolation, and real worker
integration. Tests cannot be dropped or weakened to make the migration pass.
4. **Preserved coverage.** Functional tests retain coverage reporting and CI
artifacts, including useful output when tests fail. Preserve the current
production-code coverage scope and exclusion of the frozen engine baseline;
report unsupported coverage capabilities or report formats as compatibility
gaps rather than silently removing them.
5. **Native linting and formatting.** Bun's native linter and formatter replace
ESLint and Prettier, preserving the current rule severities, type-aware checks,
unused-name exceptions, formatting options, and Angular-template formatting.
CI continues to reject violations. Checks cover the same application,
repository-script, and workflow content as before.
6. **Type checking alongside Angular.** `bun check` checks application and test
TypeScript. Angular's compiler retains its supported TypeScript 6 dependency
and continues to check templates during builds. Type errors still fail the
appropriate checks; successful standalone checking does not replace a
successful Angular build.
7. **Native HTTP serving.** `Bun.serve` replaces Express, preserving Angular's
request-handler integration, configured rendering modes, static assets and
cache behavior, configurable port, error handling, and container health check.
Development and production routes continue to work, including direct visits
to the benchmark page. The current catch-all route uses client rendering;
this migration does not enable server rendering for that route.
8. **Existing CI guarantees.** Policy and image-publication regression checks,
security scans, production builds, artifact retention, and required checks
continue to work. The separate required seven-scenario benchmark preserves
its calibration protocol, warm-up, measured repetitions, determinism checks,
timeouts, and performance budgets. A runtime change cannot justify weakening
these gates.
9. **Honest completion.** Fix incompatible required tooling before declaring the
migration complete. If a fix proves infeasible, report the failing behavior,
evidence, and remaining blocker. Local success must be distinguished from
successful live Gitea checks.
## Implementation Decisions
- **Agreed: runtime and native tools.** Bun adoption is a requirement independent
of speed gains. Use its native test runner, linter, formatter, standalone type
checker, and HTTP server. Compatible Node API imports may remain when executed
by Bun; rewriting every import is not required to satisfy the runtime goal.
- **Agreed: Angular boundary.** Keep Angular's standard compiler, bundler,
development server, and framework build support. Preserve the existing
rendering configuration and browser-based planner, consistent with ADR 0002.
- **Agreed: TypeScript coexistence.** Keep TypeScript 6 for Angular compilation
and use Bun's TypeScript 7-based checker for standalone checking. An Angular
upgrade is not required for this arrangement.
- **Agreed: tests and server integration.** Adapt the Angular test compilation
and setup, mocks, DOM environment, worker harnesses, and subprocess fixtures to
the chosen runtime and runner. Use Angular's web request API with Bun's HTTP
server, preserving its development/build handler contract and static-file
protections.
- **Migration reach.** Update package commands, test configuration and typings,
generated executable fixtures, server entry and exports, container build and
runtime stages, project-owned CI invocations, and development documentation.
Remove superseded dependencies and configuration after checking their callers.
- **Proposed implementation order.** Verify the Bun release, an Angular
production build, representative Angular component tests, and native
lint/format/type checks first. Extend that verified setup to the full suite,
server, containers, and CI before removing the replaced tools.
- **Proposed version.** Bun 1.4.3 is the initial candidate based on the researched
native-tool documentation. Select the exact version only after verifying the
required capabilities together.
## Verification Results and Decisions (#289)
Probes ran on 2026-10-17 against the stable Bun `1.4.3` release (`1.4.3+c6da4a4d3`)
from a clean checkout. "Node unavailable" means a `PATH` holding only a `bun`
executable plus `/usr/bin:/bin`, with `command -v node` failing.
**Verified:**
- **Install.** `bun install --frozen-lockfile` succeeds and leaves `bun.lock`
unchanged.
- **Runtime.** Package binaries with a `#!/usr/bin/env node` shebang (`ng`,
`eslint`, `prettier`, `tsc`) run on Bun only with `--bun`. Without it they use
Node when Node is on `PATH`, so every such command must pass `--bun`
explicitly. #290 sets it once for every `bun run` script with `[run] bun = true`
in `bunfig.toml`. Spawned build children are native executables (esbuild,
dart-sass); Angular's workers are threads of the Bun process.
- **Development server.** `bun --bun x ng serve` serves the application and
direct navigation to `/benchmark` with Node unavailable.
- **Type checking.** `bun check -p tsconfig.app.json` and
`-p tsconfig.spec.json` match `tsc` 6 on the clean tree and catch injected
application and test type errors. Only the Angular build catches template
errors, as expected.
- **Tests.** `bun test` runs the whole functional suite with a preload that
compiles components through Angular's JIT transform with inlined templates,
sets up jsdom, TestBed and zoneless change detection, plus a small shim for
the Vitest APIs Bun lacks (`stubGlobal`, `unstubAllGlobals`, `waitFor`,
`advanceTimersByTimeAsync`, `expect.poll`, `toHaveBeenCalledExactlyOnceWith`,
`setSystemTime` ordering and Date-only fake timers). Real-worker specs work
with Node unavailable. `--isolate` or `--parallel` is required for per-file
isolation. No spec uses snapshots.
- **Server.** `Bun.serve` passes route, asset, cache-header, missing-file and
path-traversal checks.
- **CI scripts.** The policy regression script passes under Bun. The image
regression script needs its fake `docker` shebang changed from `node` to
`bun`.
**Decisions taken after the probes:**
- **Linter and formatter.** Native `bun lint` and `bun fmt` exist only in canary
builds (`1.4.4-canary.1`), not in stable `1.4.3`. Pin stable `1.4.3`
everywhere and keep ESLint and Prettier, executed by Bun, until a stable
release ships them. Then replace them in one change. Until then, user story 5
stays open.
- **Client-only Angular build and a Bun static server.** Angular's production
build fails under Bun whenever a server or SSR entry is configured: route
extraction loads the server bundle through Node `module.register` loader
hooks, which Bun accepts but never applies. Every route is client-rendered
today, so the Angular build drops its server and SSR entries and a small
`Bun.serve` server delivers static assets with the same cache behavior and
falls back to `index.html`. This replaces the agreed Angular web request
handler integration and gives up `@angular/ssr`. Adding server rendering later
requires revisiting this decision.
- **Coverage.** `bun test` reports text and lcov with line data only. HTML and
Cobertura reports are generated from the lcov with the istanbul report
libraries. Branch and function coverage are no longer reported; this
reduction is accepted.
- **Benchmark memory guard.** JavaScriptCore has no `--max-old-space-size`
equivalent. The CI benchmark job enforces the limit with a container memory
limit instead of a heap-only cap.
**Platform constraints, not project commands:**
- **Gitea actions.** `actions/checkout@v4` (`node20`) and
`actions/upload-artifact@v3` (`node16`) are JavaScript actions, so the job
container must still provide `node` for the runner. Project commands must not
use it.
- **Allowed hosts.** Found while probing: the current Express server answers 400
unless `NG_ALLOWED_HOSTS` is set, and the compose files only set `PORT`. The
static Bun server removes this dependency.
## Testing Decisions
- Test observable behavior and failure outcomes, rather than configuration text
or internal adapter shapes. Reuse the existing behavior-level tests and change
harnesses only where the runtime or runner requires it.
- **Runtime and installation:** exercise clean frozen installs, development and
production commands, and project-owned subprocesses with Node unavailable to
those commands. Verify actual execution by Bun, rather than relying on a
command's name. Keep any CI-platform Node requirement separate from this check.
- **Angular and planning:** use the existing TestBed-based component and service
suites as prior art for compilation and DOM behavior. Retain the planning
integration, property-based, migration, date-sensitive, and cancellation tests
to check planning outcomes, saved inputs, and plan explanations.
- **Workers and subprocesses:** preserve the existing real-worker tests for
submitted-configuration isolation, outcome and explanation delivery, and worker
cleanup. Run policy and publisher regression scripts with Bun, keeping their
temporary Git repositories and fake Docker executable so verification remains
independent of real registry writes.
- **Lint, format, and types:** compare the current checks with the native tools.
Use small representative invalid inputs to establish that unused variables,
deprecated APIs, formatting violations, application/test type errors, and
Angular template errors still fail the intended command. Verify formatting
options and representative Angular templates without an unrelated reformat.
- **HTTP and containers:** add focused HTTP behavior checks around the native
server, since the explored test suite provides no equivalent server coverage.
Exercise configured routes, direct navigation, static JavaScript/CSS assets,
cache and content-type headers, missing assets, error responses, and traversal
protection. Smoke-test the production container and its health check.
- **Coverage and benchmark:** verify functional coverage artifacts, including
failure-path uploads, and run the existing benchmark outside coverage. Keep the
frozen-engine calibration and current budget assertions. Record Bun results as
new measurements rather than claiming browser or phone speedups from them.
- **CI:** use the existing policy/publisher regression scenarios as prior art for
push, pull-request, fork, manual, and release-event behavior. Obtain successful
required checks on the final PR revision; live publication and activation
validation remain subject to the repository's existing Gitea process.
## Out of Scope
- Replacing Angular's build pipeline with Bun's bundler, rewriting the framework,
or bypassing Angular's TypeScript support checks.
- Moving leave planning to the server, changing planning rules or objectives,
altering saved data, or adding accounts, synchronization, or backend services.
- Changing configured rendering modes or treating Bun as the browser runtime.
- Dropping tests, weakening lint rules or benchmark budgets, or silently using
Node to complete otherwise incompatible project commands.
- Replacing security scanners, changing registry publication policy, provisioning
CI credentials, modifying branch protections or activation settings, creating
releases, publishing this spec, or deploying the application.
- Rewriting compatible Node API imports solely because their names mention Node.
## Further Notes
This spec records the decisions made in the interview. The architecture record
remains proposed; the Status section lists what is implemented.
The glossary receives no new terms because the choices concern general tooling,
rather than new leave-planning concepts.
Remaining verification (everything else is recorded as verified under Status):
- Native lint and format wait for a stable Bun release that ships `bun lint` and
`bun fmt` (#290).
- Live Gitea validation (#293): the custom job `shell` template, the Bun download
in each job, the `images` job with publisher credentials, and the benchmark's
timing margin on the runners.
- The `images` job keeps Alpine's `nodejs` on `PATH` because the checkout action
needs it (a runner requirement); project commands do not use it and no Node
fallback for them is agreed.
- `src/test-setup.ts` imports Analog's internal `jitTransform` by path; replace it
when Angular or Analog exports a JIT transform.
Research checked on 2026-10-17:
- [Bun runtime selection](https://bun.sh/docs/runtime#--bun) explains why a Bun
command can still launch a Node executable.
- [Bun 1.4.3](https://bun.sh/blog/bun-v1.4.3),
[native linting](https://bun.sh/docs/lint),
[formatting](https://bun.sh/docs/format), and
[type checking](https://bun.sh/docs/runtime/check) describe the candidate tools.
- [Angular build guidance](https://angular.dev/ecosystem/custom-build-pipeline)
recommends retaining its standard CLI pipeline.
- [Angular's web request engine](https://angular.dev/api/ssr/AngularAppEngine) and
[Bun's HTTP server](https://bun.sh/docs/runtime/http/server) describe the original
server integration plan, replaced by the `Bun.serve` static server above.
- [Angular version compatibility](https://angular.dev/reference/versions) and
[compiler roadmap](https://angular.dev/roadmap) establish the current Angular
compiler boundary. [Microsoft's coexistence guidance](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#typescript-and-embedded-languages)
describes standalone TypeScript 7 checks alongside Angular-specific tooling.
+201
View File
@@ -0,0 +1,201 @@
# Gitea Actions conversion
[Issue #268](https://gitea.nessar.fr/nessar/vac-optimizer/issues/268) converts the
repository's CI to [`.gitea/workflows/ci.yml`](../.gitea/workflows/ci.yml).
The workflow and merge-message template have passed implementation review.
Repository Actions is enabled with owner approval. Publisher credentials and
live workflow validation are still pending.
The existing `gitlab-to-gitea/ci-conversion-required` status stays in place until
that review, a successful Gitea PR run, and approval of the prepared first merge
message.
## Jobs and triggers
Pushes to `develop` and `main` and `v*` tag pushes run CI. Other branches
(feature, renovate, release, hotfix) run it only through their pull request; a
branch without a PR gets no automatic CI or image, so open a draft PR to get
one. Pull requests run on opening, reopening, synchronization, and title/body
edits. Manual dispatch runs validation without publishing images. There is no
schedule or deployment job in the preserved configuration; the Compose files
remain manual deployment options.
| Job | Behavior |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `policy` | Tests the policy and publisher with Bun, then validates the checked-out commit, GitFlow, PR title, commits, and stable release version. |
| `validate` | Runs ESLint, Prettier (application, `scripts/ci-*.mjs` and workflow files) and `bun check` type checks of application and test code, all on Bun with the frozen lockfile. |
| `test` | Runs functional coverage with `bun test --isolate` (line coverage only), converts it to HTML and Cobertura, and uploads coverage for seven days even on failure. |
| `benchmark` | Required seven-scenario protocol (one warm-up, two measured repetitions) outside coverage in a container limited to 3 GiB. It times the frozen engine on `two years` (best of three) before and after the protocol, and fails any scenario whose mean planning time exceeds its multiplier times that calibration; the 240-second timeout is only a hang guard. |
| `build` | Builds the client-only Angular production bundle (the only check of Angular templates; `bun check` does not replace it) and the Bun static-server bundle, and retains `dist` for seven days. |
| `security` | Runs Semgrep JavaScript/TypeScript SAST and Trivy dependency/secret scans; retains SARIF reports for seven days. Scanner execution must succeed; findings remain reports rather than a new severity gate. The scanners are not project JavaScript, so this job installs no Bun. |
| `images` | Publishes branch/SHA images after required validation, including the benchmark, or promotes an existing SHA image for a stable tag, running the publisher with Bun. Runs only for pushes and same-repository PRs. |
| `required` | Fails on failed, cancelled, or skipped required validation, including the benchmark. Requires image publication when expected; accepts its intentional skip for fork PRs and manual dispatch. It is shell only and needs no Bun. |
The benchmark gates image publication (`images.needs` includes `benchmark`) and
the `required` aggregate. The relative gate absorbs a slower runner and load
that lasts through the whole job, because calibration runs in the same job. It
calibrates before and after the protocol and judges against the slower value,
so it also absorbs load that starts during the protocol, such as another run
sharing the runner. It does not absorb load that ends before the second
calibration; the 240-second hang guard still bounds those runs.
Because branch pushes outside `develop` and `main` do not trigger CI, a commit
on a PR branch runs only on PR events, which carry the PR title and rebase
checks. New runs cancel older runs for the same event/ref. Image jobs serialize
per branch slug; stable promotions share one group and are not cancelled in
progress.
## Runners and permissions
Every job that runs project commands uses Bun 1.4.3 with the frozen lockfile (see [Bun toolchain and Node](#bun-toolchain-and-node)). Job containers stay on Node 24.22.0. The image
job uses Docker 29.9.1 and its matching Docker-in-Docker service. Scanner
versions are Semgrep 1.180.0 and Trivy 0.75.0; Trivy downloads are checksum-checked.
Trivy downloads its vulnerability database from Aqua's public ECR mirror because
the default registries returned a missing database blob and a download timeout.
Jobs select the `ubuntu-latest` label and require Linux container-job support.
Allow at least the benchmark job's 3 GiB container memory limit plus runner overhead.
The instance currently has an online inherited runner named `srvhome`, labelled
`ubuntu-latest` and `ubuntu-24.04`. Repository runners, secrets, and variables
were empty at implementation time. The owner must verify that this runner can
run the job containers, JavaScript actions, artifact uploads, and the privileged
Docker-in-Docker service before replacing the migration gate. Use isolated runners for untrusted
contributor code; the privileged publishing service belongs to trusted runs.
The workflow requests a read-only repository token. Checkout removes persisted
credentials; publication credentials are passed only to the image step. Fork PRs
and manual dispatches cannot run that step. Gitea's job token cannot publish
container packages, so provision the two repository Actions secrets below.
See [job-token permissions](https://docs.gitea.com/usage/actions/token-permissions/)
and [package authorization](https://docs.gitea.com/usage/actions/comparison/).
| Secret | Purpose |
| ------------------- | --------------------------------------------------------------------------- |
| `REGISTRY_USERNAME` | The package publisher's Gitea username, authorized to publish for `nessar`. |
| `REGISTRY_PASSWORD` | A dedicated personal access token with `write:package` permission. |
Keep secret values in Gitea's Actions secret store. The configured tea account's
administrator token is not a CI publishing credential. No SSH or deployment
secret is required by this workflow.
## Bun toolchain and Node
Project commands run on Bun 1.4.3 only. `package.json` (`packageManager`),
`@types/bun`, both Docker stages and `scripts/install-bun.sh` carry the same
version. To upgrade, change all of them together and replace the installer's
four SHA-256 values with those of the new release's `SHASUMS256.txt`; the
installer refuses a `package.json` that names a different version, so a bump of
only one place fails CI instead of drifting.
- **Install.** `policy`, `validate`, `test`, `benchmark`, `build` and `images`
run `sh scripts/install-bun.sh`. It downloads the release zip for the
runner's architecture (x64 or aarch64) and libc (glibc, or musl on Alpine),
verifies its pinned SHA-256, and installs `/opt/bun/bin/bun`. It uses no npm.
- **Node-free project steps.** The five Debian jobs set
`defaults.run.shell: env PATH=/opt/bun/bin:/usr/bin:/bin bash -e {0}`. Every
`run:` step then sees Bun but not `/usr/local/bin`, where the `node` image keeps
`node`, `npm` and `yarn`. `bun run` additionally runs Node-shebang tools on Bun
through `bunfig.toml`. The security scanners are not project JavaScript, so
`security` has no Bun and no custom shell.
- **Why the containers keep Node.** `actions/checkout@v4` (`node20`) and
`actions/upload-artifact@v3` (`node16`) are JavaScript actions. The runner
starts them with the container's `node`; the custom shell does not affect
`uses:` steps. This is a platform requirement, not permission to run project
commands on Node.
- **`images` exception.** Alpine's `nodejs` package installs `node` into
`/usr/bin`, beside `git`, and checkout's post step needs it, so `PATH` cannot
hide it there. The project command is `/opt/bun/bin/bun scripts/ci-image.mjs`;
it starts only `process.execPath`, `docker` and `git`. Hiding Node there needs
an infrastructure decision (for example a runner image that ships Node outside
`PATH`), which this conversion does not make.
- **Needs live validation.** The custom shell template is a GitHub Actions
feature that Gitea's runner implements. A local run of the real engine
(`gitea-runner exec` v5.1.0, with the job containers above) executed it, but
only a live Gitea run confirms the instance's runner version, the checkout
action and the privileged Docker-in-Docker `images` job.
## Images and releases
Images use the [Gitea container registry](https://docs.gitea.com/usage/packages/container/)
at `gitea.nessar.fr/nessar/vac-optimizer`. Pushes to `develop` and `main` and
same-repository PRs publish `branch-<slug>` and `sha-<full commit SHA>`. Slugs
retain the previous lowercase, non-alphanumeric-to-hyphen, 63-byte
normalization; choose distinct branch slugs.
Only stable `vX.Y.Z` tags matching the tagged commit's `package.json` version
and reachable from `main` may promote images. Promotion first pulls the existing
SHA image, then publishes the version tag and `latest`; it never rebuilds.
An absent SHA image fails before either stable tag changes. Wait for the main
image job before tagging. No version increment or deployment is automatic.
## Claude review
[`.gitea/workflows/claude-review.yml`](../.gitea/workflows/claude-review.yml)
reviews a PR when the repository owner posts a PR comment containing `@claude`.
It runs Claude Code 2.1.314 headless on the PR head with the checked-in
`code-review` skill, passing the PR description, the comment, and the issues
that the PR and its commits reference as the spec. Claude may only read files
and run read-only `git` commands, and never receives the Gitea token. The job
token posts the review, or a failure link, as a PR comment. Gitea reads
`issue_comment` workflows from the default branch, so the workflow takes effect
once it is on `develop`.
| Secret | Purpose |
| ------------------------- | ---------------------------------------------------------------------------- |
| `CLAUDE_CODE_OAUTH_TOKEN` | Output of `claude setup-token`; reviews use the owner's Claude subscription. |
The workflow needs live validation of the job token's comment permission and of
the checkout of `refs/pull/<number>/head`.
## Merge messages and activation
The [merge template](../.gitea/default_merge_message/MERGE_TEMPLATE.md) translates
the previous title, closing-issue references, and review reference using
[Gitea's supported variables](https://docs.gitea.com/usage/issues-prs/merge-message-templates/).
For a PR titled `ci: migrate to Gitea Actions`, closing #268, with reference #271,
the checked expansion is:
```text
ci: migrate to Gitea Actions
close #268
See pull request #271
```
The owner has enabled Actions and approved validation before adding publisher
secrets. Complete the remaining activation checks in this order:
1. Review this workflow against the protected administrator exports for runner
requirements, triggers/schedules, permissions, secrets, publishing, and
deployment dependencies. The original CI definition is retained in Git:
`git show 0d900fd72d1a405d257f5a566c55cc0cb3d2bc61:.gitlab-ci.yml`.
2. Publish the reviewed feature branch and open its PR to register the workflow.
Once registered, manual dispatch verifies validation and artifacts without
publishing images. PR validation can also run now; its image and
aggregate checks remain blocked until publisher secrets are provisioned.
3. Verify runner isolation and Docker service support, then provision the two
publisher secrets. Review the package publisher's permissions and registry
namespace before permitting publication. Rerun the PR workflow and require a
successful **pull-request run** on the final commit, including PR title and
rebase checks, artifact handling, and actual image publication. A push run
or manual run alone does not validate the PR policy and publication.
4. Prepare and review the first PR's merge message before replacing the migration
gate. The target branch will not contain the new template until that first
merge, so explicitly use the validated PR title, closing references, and PR
reference for its merge message. Keep the migration gate throughout this
review.
5. After the successful PR run and merge-message approval, replace the migration
status requirement on both protected branches with the **actual reported
pull-request context** for the `required` job. Select it from the PR's reported
checks rather than a push run or a guessed context spelling. Fork PRs must
also be able to satisfy this check without base-repository push permissions.
Keep direct/force pushes disabled, merges restricted to maintainers, outdated
PRs blocked, and administrator protection bypass disabled. Select merge
commits and disable squash/rebase merge methods.
6. Merge the first PR using the approved message, then verify the resulting merge
commit. Subsequent merges read the committed template. No direct
integration-branch push is needed.
Historical job execution, reports, and downloadable artifacts remain in the
administrator rollback backups. They are not recreated or uploaded by this
conversion.
+20 -21
View File
@@ -1,51 +1,50 @@
# Cancelling a planning calculation
Issue [#58](https://gitlab.nessar.fr/nessar/vac-optimizer/-/work_items/58) implements the cancellation portion of ADR 0006. Issue #59 removes the automatic deadline while keeping the same cancellation and original-trace protocol. The duration estimate remains in issue #60.
Issue [#58](https://gitea.nessar.fr/nessar/vac-optimizer/issues/58) implements the cancellation portion of ADR 0006. Issue #59 removes the automatic deadline. Issue #76 removes decision tracing while preserving cancellation and valid-plan recovery. The duration estimate remains in issue #60.
`PlanningCalculationContext.cancel()` requests user cancellation once while its outcome is pending. `CalendarYear` keeps an accessible Cancel button visible during preparation, obligation search, and optimization. It announces the request, disables duplicate cancellation, and moves keyboard focus to the result heading when the outcome arrives. Cancellation never triggers Calculate. A subsequent explicit Calculate creates a fresh immutable calculation snapshot.
## Stopping CPU work
The core exposes resumable generator steps. `calculatePlanningAsyncInternal` drives those same steps in roughly eight-millisecond slices and yields to the worker event loop at phase boundaries and between preparation years. A `cancel` message sets the active run's cancellation flag; the next resume throws the cancellation signal into the suspended calculation. Recursive obligation and preference searches, quality passes, and calendar preparation unwind through their existing cleanup blocks. An individual synchronous operation, such as the holiday library's work for one year, finishes before the next pause.
The core exposes resumable generator steps. `calculatePlanningAsyncInternal` drives those same steps in roughly eight-millisecond slices and yields to the worker event loop at phase boundaries and between preparation years. Browsers yield through a message-channel task, because nested timers are clamped to at least 4 ms; Bun yields with `setImmediate`, because it runs port messages ahead of timers and incoming worker messages. A `cancel` message sets the active run's cancellation flag; the next resume throws the cancellation signal into the suspended calculation. Recursive obligation and preference searches, quality passes, and calendar preparation unwind through their existing cleanup blocks. An individual synchronous operation, such as the holiday library's work for one year, finishes before the next pause.
The synchronous `calculatePlanningInternal` adapter drains the same steps without pauses for existing direct core callers. The public non-browser calculation context uses the asynchronous driver so its cancellation method also works.
The synchronous `calculatePlanningInternal` adapter drains the same steps without pauses for existing direct core callers. Tests and callers outside a browser pass the in-process job (`leave-planner.in-process-job.ts`) to `createPlanningCalculation`; it runs the worker's message handling on the calling thread, so the same asynchronous driver, cancellation and calculation lifecycle apply as in a worker.
User cancellation is distinct from replacement by another calculation (`stale-calculation`) and isolated worker failure (`worker-error` or `worker-unavailable`). Replacement retains the existing termination and stale-response protection. User cancellation leaves the producing worker alive until its explanation and trace have been delivered.
User cancellation is distinct from replacement by another calculation (`stale-calculation`) and isolated worker failure (`worker-error` or `worker-unavailable`), and from a lost server connection (`connection-lost`). Replacement retains the existing termination and stale-response protection. User cancellation leaves the producing worker alive until its outcome and explanation data have been delivered.
## Retaining a valid plan
The asynchronous calculation retains a copied incumbent as soon as the obligation search finds a jointly valid solution, before that entire stage has completed. It also considers accepted placements and every feasible evaluated quality candidate, including candidates rejected by a stage's narrower comparator. Each candidate is reconciled for earned entitlement availability and checked against all obligation rules before retention. The existing full lexicographic comparator chooses the best available incumbent; its comparisons are recorded in the original trace.
The asynchronous calculation retains a copied incumbent as soon as the obligation search finds a jointly valid solution, before that entire stage has completed. It also considers accepted placements and every feasible evaluated quality candidate, including candidates rejected by a stage's narrower comparator. Each candidate is reconciled for earned entitlement availability and checked against all obligation rules before retention. The existing full lexicographic comparator chooses the best available incumbent.
Retention reuses quality metrics already computed for an evaluated candidate. An intermediate state with more unplaced at-risk leave, or worse preferences at equal unplaced leave, is rejected using that objective prefix alone, with the actual short-circuited comparison recorded in the trace. This avoids rescoring dominated states during large obligation previews without skipping any produced history or a candidate that could improve the retained plan.
Retention reuses the objective vector already computed for an evaluated candidate. An intermediate state with more unplaced at-risk leave, or worse preferences at equal unplaced leave, is rejected using that objective prefix alone. This avoids rescoring dominated states without skipping a candidate that could improve the retained plan.
Preference occurrence dates and patterns are calculated once for the run's immutable calendar and rules. Each comparison still checks the candidate's actual placements against those patterns; candidate scores and trace records are not cached.
Preference occurrence dates and patterns are calculated once for the run's immutable calendar and rules. Each comparison still checks the candidate's actual placements against those patterns; candidate scores are not cached.
On cancellation, the core materializes the retained state with consistent placements, balances, periods, rule provenance, and preference satisfaction. It returns `PlanningIncomplete` with reason `user-cancelled`. With an incumbent the French status is **Calcul annulé — plan partiel**; without one it is **Calcul annulé**, without a plan or an obligation conflict. Temporary search states never become the displayed incumbent.
## Preserving the original trace
## Delivering the outcome and explanation
Cancellation follows the core's normal finish path. Quality evaluations are recorded before their incumbent comparisons, and each greedy placement attempt starts its own atomic decision. The recorder closes interrupted and unexecuted phases and drains every remaining operation from that run. The worker retains staged updates, including ones not yet posted, and continues its bounded, acknowledged trace delivery after optimization has stopped. It sends `artifacts-complete` only when all queued updates have been sent and acknowledged. The facade drains its own received update queue before resolving the trace. Neither layer replays planning to reconstruct this history.
Cancellation follows the normal finish path. The stable explanation is derived from the retained state. Outcome and explanation have separate promises: delayed or failed explanation delivery cannot replace or remove an already settled valid partial plan. Repeated and late outcome messages cannot change that outcome, and calculation identities protect the UI against obsolete results and explanations.
The stable explanation is derived from the retained state. The outcome, explanation, and trace have separate promises: delayed or failed artifact delivery cannot replace or remove an already settled valid partial plan. Repeated and late outcome messages cannot change that outcome, and calculation identities protect the UI against obsolete results and artifacts.
Immutable `PlanningStateSnapshot` values preserve exact entitlement metadata, earned activations, declarations and placements for checkpoints and the final state. A worker failure retains the latest delivered valid checkpoint and can recover its stable explanation in a separate worker without rerunning planning. Displayed-placement alternatives use the captured configuration and state; no original decisions or historical baselines are retained.
If Cancel is accepted just before a queued natural result reaches the facade, the pending outcome still becomes a user cancellation. An already computed valid plan can be retained, while a queued conflict cannot become the cancellation result. Its existing explanation receives interruption metadata, and the original phase history is preserved even when the worker had already completed those phases.
If Cancel is accepted just before a queued natural result reaches the facade, the pending outcome still becomes a user cancellation. An already computed valid plan can be retained, while a queued conflict cannot become the cancellation result. Its existing explanation receives interruption metadata. The planning worker terminates after delivering the required artifacts; it never waits for trace acknowledgements.
## Verification
Run the focused checks with the project's installed Bun and Node:
Run the focused checks with the pinned Bun (Node is not needed):
```sh
bunx vitest run src/app/services/leave-planner-cancellation.spec.ts
bunx vitest run src/app/services/leave-planner.worker.spec.ts
bunx vitest run src/app/components/calendar-year/calendar-year-planning.spec.ts
bunx tsc --noEmit -p tsconfig.app.json
bunx tsc --noEmit -p tsconfig.spec.json
bun test --isolate src/app/services/leave-planner-cancellation.spec.ts
bun test --isolate src/app/services/leave-planner.worker.spec.ts
bun test --isolate src/app/components/calendar-year/calendar-year-planning.spec.ts
bun run typecheck
```
The public cancellation tests cover immediate cancellation, queued trace updates on both sides of the request, a stable partial outcome despite late completion or artifact error, distinct worker failure and replacement (including non-browser explanation metadata), and cancellation after settlement. A core regression compares the retained plan's full objective vector with every valid candidate actually evaluated before cancellation. The CalendarYear tests cover keyboard activation, translated statuses with and without an incumbent, focus, no implicit recalculation, explicit recalculation, and obsolete trace delivery.
The public cancellation tests cover immediate cancellation, a stable partial outcome despite late completion or artifact error, distinct worker failure and replacement (including the replaced calculation's explanation error on the in-process job), and cancellation after settlement. Core regressions verify retained validity, provenance, earned chronology and the best available partial plan through the existing checkpoint seam. The CalendarYear tests cover keyboard activation, translated statuses with and without an incumbent, focus, no implicit recalculation, explicit recalculation, and obsolete explanation delivery.
The real-worker suite bundles the production worker source with Bun and runs it on a separate Node worker thread. Its small host adapter maps browser worker messages to the thread's message port; the planner, CPU work, cancellation handling, and acknowledged trace protocol are real. It checks interruption after preparation has started, before the first obligation solution, during active obligation CPU work after a solution exists, and after a completed checkpoint. It also compares an uncancelled outcome with the synchronous adapter's deterministic result. These checks complement the controlled worker boundary tests.
The real-worker suite bundles the production worker source with Bun and runs it on a separate `node:worker_threads` thread of the Bun process. Its small host adapter maps browser worker messages to the thread's message port; the planner, CPU work, cancellation handling, and outcome and explanation delivery protocol are real. It checks interruption after preparation has started, before the first obligation solution, during active obligation CPU work after a solution exists, and after a completed checkpoint. It also compares an uncancelled outcome with the synchronous adapter's deterministic result. These checks complement the controlled worker boundary tests.
For a browser check, serve the production browser build and use native Chromium Web Workers with a saved annual horizon. Check cancellation during calendar preparation, a broad obligation search, and a quality pass. Confirm one planning request per Calculate, no new request on Cancel, the appropriate translated status, joint rule satisfaction and balance accounting for an incumbent, and complete trace delivery after the outcome. Also check the Cancel control with the keyboard, at 375px width, and in light and dark themes.
For a browser check, serve the production build with `bun run serve`, which plans over the server's planning socket, and repeat it after stopping the server with the page still open (or under `ng serve`, which has no build identifier) to exercise the local Web Worker; use a saved annual horizon. Check cancellation during calendar preparation, a broad obligation search, and a quality pass. Confirm one planning request per Calculate, no new request on Cancel, the appropriate translated status, joint rule satisfaction and balance accounting for an incumbent, and stable explanation delivery after the outcome. Also check the Cancel control with the keyboard, at 375px width, and in light and dark themes.
The production build was checked in native Chromium for all three interruption points, including keyboard cancellation during a 375px dark-theme obligation search and desktop light-theme checks. An editable input could still receive focus during CPU work, and focus moved to the result heading after keyboard cancellation. Each run sent one planning request and one cancellation request, displayed the appropriate French status, and completed acknowledged artifact delivery. The Cancel control was 44px high and the page had no horizontal overflow. In these sample runs, cancellation through artifact completion took under 200ms; this is measured evidence, not a latency guarantee.
Earlier browser checks before #76: the production build was checked in native Chromium for all three interruption points, including keyboard cancellation during a 375px dark-theme obligation search and desktop light-theme checks. An editable input could still receive focus during CPU work, and focus moved to the result heading after keyboard cancellation. Each run sent one planning request and one cancellation request, displayed the appropriate French status, and completed acknowledged artifact delivery. The Cancel control was 44px high and the page had no horizontal overflow. In these sample runs, cancellation through artifact completion took under 200ms; this is measured evidence, not a latency guarantee.
+80 -37
View File
@@ -13,19 +13,23 @@ horizon dates hide the estimate and retain the existing disabled Calculate
control. Other malformed inputs keep a rough fallback estimate; the planner
still performs its own validation.
The initial model is a deliberately rough engineering prior grounded in the
[browser reference measurements](benchmark/README.md): the 2026-10-03 annual
30-day scenario returned its outcome in about 0.6 seconds, and the 2026-10-05
two- and three-year calendar runs with 30 days per year took 5.08 and 10.86
seconds. These are throttled desktop measurements, not phone measurements or a
validated prediction model. The annual outcome timing does not include final
calendar rendering. The new rendered-calendar measurements below supplement
those references.
The initial model is a deliberately rough engineering prior fitted to the
planning times recorded in the
[2026-11-11 recalibration](benchmark/README.md#indicative-wait-recalibration--2026-11-11):
38 configurations of one to five years, with and without the application's
default calendar rules, timed in the planner core on the Bun runtime that
serves calculations. They were taken after the engine speedups of
[issue #321](benchmark/issue-321.md), which made the 2026-10-18 rendered waits
obsolete as grounding. They are planning times on a desktop, not rendered
waits: the request's transport and the calendar's rendering are not in them,
and a slower server or device can wait longer than the prior says. The prior is
not a validated prediction model; over those configurations the measured time
lies between 0.59 and 2.26 times the estimate.
For a half-open horizon of `D` calendar days, the model uses:
```text
initial_ms = 300 + 600 × (D / 365.25)^1.2 × (max(1, P) / 30)^1.5 × R
initial_ms = 400 + 100 × (D / 365.25) × (max(1, P) / 30)^1.4 × R
```
`P` approximates placement load. Each non-negative finite balance contributes
@@ -35,30 +39,49 @@ weight 0.25 to account for possible supporting placements. Already expired and
not-yet-available balances contribute nothing. Each enabled IF_THEN rule adds
its non-negative earned quantity times `D / 365.25` as a rough allowance.
`R` starts at 1. Each enabled rule adds `max(1, placeDays / 3)` times 0.5 for an
obligation or 0.15 for a preference. TIME_WINDOW rules wholly outside the
horizon contribute nothing. These weights approximate extra search, rather than
solving constraints or counting holiday occurrences in the form. Typed
obligations, date distribution, interacting rules, earned entitlements, device
load and browser differences can all change the actual wait substantially.
`R` starts at 1. Each enabled IF_THEN rule adds 4: a rule that can earn leave
makes the planner judge every candidate plan in full, and the default Samedi
Malin rule made the measured requests about 3.6 times slower. Every other
enabled rule adds `max(1, placeDays / 3)` times 0.5 for an obligation or 0.15
for a preference. TIME_WINDOW rules wholly outside the horizon contribute
nothing. These weights approximate extra search, rather than solving
constraints or counting holiday occurrences in the form. The obligation weight
is unmeasured since 2026-10-18: an obligation's cost follows the number of ways
to satisfy it, and one obligation beside a rule that earns leave can take a
hundred times the estimate. Date distribution, the split between leave types,
interacting rules, the order of priorities, server load and browser differences
can all change the actual wait substantially.
The powers and weights are implementation choices, not complexity guarantees
or fitted accuracy claims. With 30 available days per year, the model's search
term grows as the number of years to the power 2.7, rather than assuming a
linear increase. Horizons beyond the references are unvalidated extrapolation.
The estimate performs one pass over balances and rules and runs no planner.
The constants are a rounded least-squares fit, not derived. The fixed 400 ms
approximates request scheduling, transport, worker startup and rendering; it
comes from the 2026-10-18 rendered waits (a one-year request for 5 CP waited
465 ms) and has not been measured since planning moved to the server. One year
with 30 days and the default rules estimates about 1 second, displayed as
1–4 seconds; three years estimate about 9 seconds, displayed as 4–29 seconds;
five years estimate about 31 seconds, displayed as 15–94 seconds. Horizons
beyond five years are unvalidated extrapolation. The
estimate performs one pass over balances and rules and runs no planner.
## Local refinement and precision
After each successfully rendered `Plan`, the service retains the ratio of its
observed elapsed time to the initial model for that calculation's immutable
submitted snapshot. The median of the most recent eight ratios scales the
initial estimate for the current form. A changed form therefore does not
relabel the completed measurement as a calculation of the new configuration.
The median limits the effect of isolated unusually slow runs; it cannot remove
systematic model error or predict arbitrary obligation searches.
submitted snapshot, with that snapshot's initial estimate and rule weight `R`.
A changed form therefore does not relabel the completed measurement as a
calculation of the new configuration.
Only eight numeric ratios are retained in memory for the current application
The current form is scaled by the median ratio of its **similar** calculations
among the most recent eight: those with the same `R` and an initial estimate
within a factor of two. The planner is deterministic, so a configuration that
was just calculated, or one edited slightly, is predicted from its own wait.
The initial model misses some configurations by a large factor, and a median
over unrelated calculations kept underestimating a slow configuration until
most of the eight were its own. When no retained calculation is similar, the
median of all eight ratios applies, as before. Either median limits the effect
of isolated unusually slow runs; neither can predict an obligation search that
has not been measured.
Only these eight samples are retained in memory for the current application
session. Reloading restores the initial estimate. Nothing is persisted or sent
to a remote service, so there is no saved-measurement restoration dependency.
Storage failure does not affect this service.
@@ -71,21 +94,41 @@ duration rounding to whole milliseconds prevents floating-point noise at unit
boundaries. Very fast runs can finish before the displayed lower bound. The
range is explicitly indicative, not a confidence interval or a promise.
## During a calculation
The loading overlay's percentage follows the indicative wait, not the planning
stages completed. At Calculate, `PlanningDurationService` freezes the expected
duration `e` for the submitted snapshot, including the local refinement. On a
250 ms tick, it measures elapsed time from the same timestamp the calibration
uses. Progress rises linearly to 95% at `e`, holds there and shows 100% only
when the planner reports completion. Per-stage weights are not used, because
the costly stage depends on the configuration. Form edits and repeated stages
cannot move it backwards. On Cancel, the tick stops and the percentage freezes.
Below the status, one line names the current planning stage. For an
optimization or preference stage, it shows the rule's name. When `e` is at least
3 seconds, a second line shows "About N s left". This is in whole seconds under
10 seconds, 5-second steps under a minute and whole minutes after that. From
`e` to the top of the range shown before Calculate, the percentage holds at 95%
and that line is hidden. Because `e` sits near the middle of recent waits, about
half of all runs pass it, so it is no reason to warn the user. Past the top of
the range, for any `e`, the line reads "Taking longer than expected" and the
live status announces it once. Both lines are visible text, not live regions,
and are hidden after Cancel.
## What is timed
Manual requests capture `performance.now()` inside
`UserInputService.requestComputation`, before updating the calculation trigger.
The existing initial calculation falls back to the start of `startCalculation`.
Every request, manual or initial, captures `performance.now()` inside
`PlanningCalculationService.start`.
The endpoint is Angular's `afterNextRender` callback after the complete plan has
been projected into the calendar, its months and placements have been rendered,
and the loading overlay has been removed. This measures request scheduling,
calendar preparation, worker startup, search, trace capture that delays the
outcome, outcome transport, projection and Angular rendering. It is a DOM
calendar preparation, worker startup, search, outcome transport, projection and Angular rendering. It is a DOM
readiness endpoint, rather than a claim to measure a physical screen's paint.
Neither core `planningWorkMs` nor artifact timings supply the calibration
measurement. The callback does not wait for the explanation or trace promises;
later delivery, navigation and trace errors never add a second measurement.
measurement. The callback does not wait for the explanation promise;
later delivery, navigation and explanation errors never add a second measurement.
Cancellation (including a retained incumbent), incomplete outcomes, invalid
inputs, conflicts and calculation errors do not calibrate successful-plan
waiting time. Superseded calculations and callbacks for destroyed calendars
@@ -98,12 +141,12 @@ timer, date adjustment or new calculation. **Cancel** remains explicit.
Controlled-clock tests at the existing calendar and input seams cover initial
estimation, unsubmitted edits, minute formatting, local refinement, request
scheduling, a twenty-second calculation exceeding its initial range, a trace
that fails five minutes after calendar readiness, cancellation with and without
scheduling, a twenty-second calculation exceeding its initial range, an explanation
that arrives after calendar readiness, cancellation with and without
an incumbent, incomplete/error outcomes and superseded calculations. No timing
assertion depends on CI hardware speed. Existing settings, planner and worker
tests cover saved horizons, long calculations and original interrupted traces.
tests cover saved horizons, long calculations and interrupted-plan explanations.
Rendered annual, two-year and three-year references, with the actual displayed
range and separate later trace wait, are recorded in
range and historical artifact-delivery wait, are recorded in
[the benchmark report](benchmark/README.md).
+287
View File
@@ -0,0 +1,287 @@
# Composable planning objective contract
The common implementation for tickets #70–#75 is on `feature/optimization-rules-70-75`.
`src/app/services/planning-objectives.ts` evaluates supported configurations; rule names and
identifiers never enter the evaluator. Supplied and personal optimization rules share this
model, editor, persistence and ordered calculation pipeline.
## Configuration
`OptimizationConfiguration` contains `elements`, `conditions`, `measure`, `aggregation`,
`direction`, and, only for `work-sequence-deficit`, `thresholdDays`. Conditions are a list
of distinct selectors, combined with AND; an empty list selects every observed element.
Directions are `minimize` and `maximize`. The finite `OPTIMIZATION_CATALOG` contains the
following compatible combinations. Each row accepts any subset of its listed conditions.
| Elements | Applicable conditions | Measure | Aggregations | Measure unit | Parameters |
| ---------------------- | ----------------------- | --------------------------- | ------------------------- | --------------------- | ------------------------------------------------------ |
| `leave-balances` | `at-risk` | `unplaced-quantity` | `sum`, `count`, `maximum` | working days | none |
| `public-holiday-weeks` | `complete` | `public-holiday-week-value` | `sum`, `count`, `maximum` | calendar-day distance | none |
| `time-off-periods` | none | `non-working-day-gain` | `sum`, `count`, `maximum` | calendar days | none |
| `work-sequences` | `internal`, `non-empty` | `work-sequence-length` | `sum`, `count`, `maximum` | working days | none |
| `work-sequences` | `internal`, `non-empty` | `work-sequence-deficit` | `sum`, `count`, `maximum` | working days | `thresholdDays`: positive safe integer in working days |
| `leave-placements` | `supporting` | `placement-count` | `sum`, `count`, `maximum` | count | none |
`count` counts selected elements, including selected elements whose measured value is zero;
its unit is always count. `sum` and `maximum` aggregate the selected measured values.
All three return **zero on an empty collection**. An empty work sequence has zero deficit,
even if a configuration selects it. The maximum of an empty work-sequence collection is zero;
the existing optional average statistics keep their separate null semantics.
`validateOptimizationConfiguration(unknown)` returns `{ valid: true, configuration }` or
`{ valid: false, code, message }`. Malformed values use `invalid-optimization-configuration`;
unsupported elements/measure/condition/aggregation/parameter combinations use
`unsupported-optimization-configuration`. Unknown fields, duplicate conditions, missing,
fractional, non-positive, non-finite and unsafe thresholds are rejected. Other measures
reject `thresholdDays`. Direct and worker calculations attach each configuration error to
its rule, including malformed sparse selector lists; they never replace it with a preset.
For example, a personal rule can select internal non-empty work sequences, sum their
deficits at a threshold of three, and minimize the result. It uses the same measure as
the five-day preset. Another can maximize the longest sequence or count complete holiday
weeks; composition never dispatches by a preset identifier.
## Six supplied recipes
`OPTIMIZATION_PRESETS` provides configurations, without identities, display labels or enabled
states. `RuleService` wraps copies in named planning rules and persists the full configuration.
| Export key | Elements and conditions | Measure and aggregation | Direction |
| ---------------------- | --------------------------------------- | ---------------------------------- | --------- |
| `unplacedAtRisk` | leave balances, at risk | unplaced quantity, sum | minimize |
| `holidayWeekValue` | public-holiday weeks, complete | public-holiday week value, sum | maximize |
| `nonWorkingDayGain` | time-off periods | non-working-day gain, sum | maximize |
| `longestWorkSequence` | work sequences, including horizon edges | work-sequence length, maximum | minimize |
| `shortSequenceDeficit` | internal non-empty work sequences | deficit at `thresholdDays: 5`, sum | minimize |
| `supportingPlacements` | leave placements, supporting | placement count, count | minimize |
## Concrete observations and boundaries
`OptimizationObservations` carries collections from one concrete valid plan:
- Leave balances expose unplaced working-day quantity and the at-risk flag. Expiry on either
the horizon start or its exclusive end is at risk, preserving the existing classification;
placement dates themselves stay within the half-open horizon.
- Public-holiday weeks expose their weekday holiday value and whether every other working
date is a placement or declared non-working day. Monday through Friday contributions are
**1, 2, 3, 2, 1**; several holidays in one week are summed once in that week's observation.
Ordinary fully declared weeks never become holiday weeks. A partial horizon only admits
a week when every required date outside it is already declared, preserving the existing rule.
- Time-off periods carry distinct natural non-working dates; periods are disjoint and include
adjacent weekends, holidays and declared days at either horizon edge. Placements and declared
working days anchor periods but do not themselves contribute non-working-day gain.
- Work sequences carry a working-day length and an `internal` flag. Weekends and holidays
neither count nor split them. Both horizon-edge sequences contribute to the maximum and
are excluded by the `internal` condition. Internal zero-length observations contribute zero
deficit and are excluded by `non-empty`.
- Leave placements expose their supporting classification. Declared days are fixed observations
and do not consume balances or count as supporting placements.
`evaluateOptimization(configuration, observations)` validates the configuration and evaluates
these collections. The core's `optimizationObservations(state, context, periods?)` builds the
collections once; `evaluateStateOptimization(configuration, state, context)` is the shared core
seam for a personal rule. The preset metrics call the same evaluator, with no second engine.
## Ordered rule execution
Named `type: 'optimization'` rules contain a full `configuration` and preference-only
force. Storage, editor buffers, direct calculation snapshots and worker transport copy
the nested configuration. The core executes only explicitly submitted active rules;
it never adds presets to a request.
Obligations are solved jointly. Each active preference then runs in the displayed
rule order. Disabled rules are excluded before validation and search. A request
with no active rules preserves declared days and adds no placements, including
when balances are at risk of expiry. Statistics may still report preset metrics;
only the active configured objectives affect selection.
The shared core seams are:
- `activeObjectiveVector(state, context, throughIndex?)` evaluates active preferences
in display order, with unique `optimization:<rule-id>` and `preference:<rule-id>`
identities. Optimization measurements use their full configurations; calendar
preferences measure actual matching dates/patterns.
- `evaluateRuleCandidate(before, candidate, context, throughIndex, dates, sourceDate?,
addition?, baseline?, beforeVector?, incumbentVector?)` validates mandatory type/date/pattern memberships and earned
entitlement availability and compares the active prefix. Its comparison preserves
the source state; technical selection facts compare with the actual current best
candidate. It returns the valid state, its full vector and
optional trace evaluation. Additions must improve an active prefix objective.
- `optimizeRulePlacements(state, context, throughIndex, allowAdd, rule?)` generates
single additions/removals/moves, atomic balance reassignments and balance swaps.
`relocateForAddition` handles augmenting chains when a scarce balance needs an
occupied date. Complete typed calendar patterns are reassigned atomically too.
Coordinated family bundles can pass through `evaluateRuleCandidate` and rank through
`compareObligationPreviews(candidate, incumbent, context)` without fixed metric guards.
- `applyPreferenceStep` dispatches every optimization and calendar window through
the same kernel. Earlier preferences replay when a later rule changes their state
or creates an earned entitlement.
Earned entitlements follow actual completed active producer patterns, including patterns
already fulfilled by another rule or declared days. Shared finalization reconciles those
rights before candidate comparisons, cancellation retention and unchanged-state caching.
Availability starts after the complete merged producing period; its own reward cannot
finance a placement inside that period. Earning is a validity consequence, rather than
an extra objective that an active configuration can suppress.
`compareObjectiveValues`, `compareObjectiveLists` and `firstDifferentObjective`
serve both selection and explanation. Earlier balance expiry and placement dates
are final tie-breaks after all active objectives compare equally; they only reshape
existing placements. Equal expiry values are compared independently of arbitrary balance
identifiers, so earlier placement dates remain the next tie-break. Captured rule identities, names and configurations label the
result independently of subsequent editor changes.
Loaded plans retain the established sampling strategy for flexible move destinations
above 24 placements, including non-working-adjacent, weekly and calendar-window dates.
Excluded move destinations are recorded as `not-examined`, never as proven rejected.
There is no automatic elapsed-time cutoff. Complete holiday weeks, joined time-off
periods and work-sequence changes are compared as coordinated valid bundles.
Moves that preserve every active objective can be pruned when their final tie-breaks
cannot improve. Per-iteration vectors are reused; preset statistics are materialized
only for selected incumbents and published plans.
For large non-earned obligation searches above the existing exact-branch
threshold, the joint feasibility search retains its existing limit. When several
obligation solutions are found, they are ranked by the actual active objectives
and final ties of their obligation-only plans, with enumeration order breaking
equal ranks. The preference stages run once, on the best-ranked solution; no
solution receives a preference preview ([ADR 0010](adr/0010-rank-obligation-solutions-before-preferences.md)).
If that run ends with earned leave available only after its final merged
time-off period, the stages restart on the next solution in rank order. This
deterministic ranking has no elapsed-time cutoff or user-facing setting.
A deferred optimization addition is supporting only when it provides one of the
calendar benefits in the domain definition, rather than merely extending a period.
Holiday occurrences and eligible patterns are immutable per request and cached
independently of mutable placement states.
## Saved rules and initialization
`vacationRules` uses one versioned envelope: `{ version: 1, rules: [...] }`.
`RuleService` restores it synchronously before the first duration estimate or calculation.
A legacy array, including `[]`, receives loss prevention first, every original record in
its original relative order, then the other five presets. Each original raw record is
preserved, including names, IDs, dates, parameters, disabled state and a missing legacy
force. Getters interpret missing force as preference without rewriting that record.
Preset IDs use collision-free suffixes when a personal rule already uses a proposed ID.
New users receive the six active presets around the existing Samedi Malin and Christmas
calendar defaults.
The migration and its version are written by one synchronous `setItem`; no separate
marker can succeed while the rules fail to save. A failed write leaves the original
key intact and permits a later complete save or a fresh reload to retry. Failed reads,
malformed saved data and unsupported versions disable writes for that service instance
so later editing cannot overwrite unknown persisted user data. Storage unavailable
in the runtime leaves an in-memory configuration usable.
Every later edit, toggle, reorder or deletion saves the full versioned list. Versioned
empty lists stay empty; disabled and deleted presets stay that way. With no active
rules, eligible unused leave remains visible with its original expiry classification
and a translated explanation that the active planning rules justified no addition.
Physical availability, occupation, expiry and incomplete-calculation reasons keep
precedence where they apply. Declared days remain fixed and consume no leave.
## Search and trace limits
These are deterministic search limits, rather than claims of global optimality:
- Above 24 placements, flexible moves examine the existing non-working-adjacent,
declared-adjacent, weekly and calendar-window destinations. Other destinations
retain `not-examined` trace records.
- Non-earned obligation searches whose estimated branch count exceeds 10,000 retain
at most 4,096 feasible solutions. Every search ranks its solutions by the actual
active vector and final ties of the obligation-only plans, and the preference
stages run on the best-ranked solution only. A lower-ranked solution that would
end better after the preferences is not found.
- Calendar bundles rank original donors once by the actual active vector of the
source plan with each donor released, then retain that order during recursive
allocation. They keep the first prefix-valid allocation and collapse equivalent
donor tokens. Work-sequence bundles use the nearest center per balance and the
first accepted allocation. These choices can miss another coordinated allocation.
- When a completed specialized bundle strictly improves the current active prefix,
the kernel commits its full-vector best before scanning generic alternatives for
the old state. The old generic neighborhood is marked `not-examined`, then bundles
and generic candidates continue from the improved state. Earlier preferences replay
and the final expiry/date pass still runs. This scheduling can make a better unseen
old-state generic branch unreachable; it is an explicit heuristic rather than an
exhaustive comparison of all bundles and moves.
- Additions require a strict improvement through the current rule. A custom
maximum/minimize unplaced-quantity rule with two tied at-risk CP1 balances can
therefore keep both unused: either single addition leaves the maximum at one,
while a coordinated addition of both would reduce it to zero. This balance
plateau has no specialized bundle generator; the supplied sum/minimize loss
preset does consume both.
Earlier rules reuse their completed evaluation only when the complete
ordered incoming state matches their last output, including balance quantities and
validity, earned activations, placement insertion order, supporting status and rule
provenance. The trace records that unchanged state as `not-examined` with the earlier
decisions retained. A candidate unable to beat a valid local incumbent already
offered to cancellation retention keeps its primary comparison but avoids a duplicate
global incumbent comparison. These are exact reuse decisions, not additional sampling.
At the first explicit sum/minimize quantity preference, complete single additions can
reuse an evaluated funding score when eligible at-risk balances have the same expiry
and matching signature across every enabled time-window rule, including obligations.
The first original-order funder is preserved; later equivalent alternatives are recorded
as `not-examined` without fabricated comparisons. This applies only without active
IF_THEN rules or earned activations, without a balance maximum objective, and with a
safe combined remaining quantity. Recursive bundles and augmenting allocation retain
every funding choice: equal current scores do not prove equivalent future capacity.
A first-position sum/minimize unplaced-quantity rule finishes its preference stage when
its reconciled value reaches zero. The same bound applies to a prefix consisting of
that zero quantity followed only by fully satisfied time-window preferences or maximizing
public-holiday-week preferences at their configured upper bound. Windows are capped at
their requested quantity. A holiday maximum is evaluated from the same immutable request
weeks, marking every week complete and using its configured sum, count or maximum;
partial horizon weeks retain the existing declaration and eligibility semantics. The whole bounded stage is recorded as
`not-examined`; later preferences, replay after actual state changes and the final
full-vector expiry/date pass still run. Other configurations and preference orders
retain their search. This schedules lower priorities later; it does not claim an
exhaustive full-vector search in the bounded stage.
When every balance is exhausted and there is no active IF_THEN rule, a complete generic
iteration that finds no full-vector improvement can be reused for the identical ordered
state at a later preference. Explicit balance assignments use the same dates, validity,
provenance and configured move sampling regardless of the current rule. Rule-specific
bundles still run, and any balance, placement, supporting, provenance or activation change
invalidates reuse. Bound returns and interrupted iterations never admit a state. Reuse
is recorded as `not-examined` with the earlier sampled generic decisions retained; the
final expiry/date pass still examines its neighborhood.
Captured trace vectors, scalar facts, placements, ordered date lists and deltas are immutable detached evidence. Bounded
request-local indexes share only identical complete values and metadata; the vector
index uses recorded date keys and holds at most 65,536 entries, including variants in
one bucket. Eviction changes allocation only, with every examined candidate and its
ordered factual fields retained. Mutable candidate shells and emitted replacement
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.
Cancellation retains the best valid examined plan under the captured active vector
and its original trace. Counterfactual and explanation comparisons use that same
snapshot; later editor changes and delayed artifact delivery do not alter it.
An explicit caller-owned planning-work budget remains supported; the application
introduces no automatic duration-based stop.
## Confirmed decisions and technical assumptions
Confirmed by ADR 0008: one composable model for supplied and personal optimization rules;
preference-only force; the six recipes' existing business meanings; declared-day and horizon
semantics; user-controlled active preference order; expiry then date tie-breaks; preserving
saved user data. The integrated implementation replaces the former implicit policy
with explicit active rules and performs the one-time saved-data addition.
The supported configuration boundary is only sum/count/maximum and both directions; empty aggregate
zero; deficit threshold is a positive working-day integer, initially five; every listed
compatible condition subset and aggregation is supported; no other filters or measures.
Public-holiday weights retain the existing business definition rather than becoming a parameter.
## Verification scope
Ticket #75 covers saved-rule migration and functional integration of #70–#75.
Performance acceptance and any further optimization are tracked in #78, after
original-decision-trace removal in #76 and functional verification in #77. The
seven-scenario benchmark, its warm-up and two measured repetitions, the 2 GB heap
limit and the 300-second timeout remain unchanged. CI runs the benchmark as a
separate non-blocking job at the user's request while #78 is open; functional
tests and other checks remain required. #78 must restore the required benchmark
gate after the protocol passes. Completing the functional migration or passing
CI during this exception does not establish a passing benchmark.
+3 -3
View File
@@ -1,6 +1,6 @@
# Plan Statistics Popup
Local development draft for [issue #3](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/3) and [issue #29](https://gitlab.nessar.fr/nessar/vac-optimizer/-/issues/29), within [milestone %3: V1 stats](https://gitlab.nessar.fr/nessar/vac-optimizer/-/milestones/3). The behavior below consolidates the decisions confirmed during grill-with-docs; proposals and remaining presentation choices are identified separately.
Local development draft for [issue #3](https://gitea.nessar.fr/nessar/vac-optimizer/issues/3) and [issue #29](https://gitea.nessar.fr/nessar/vac-optimizer/issues/29), within [milestone V1 stats](https://gitea.nessar.fr/nessar/vac-optimizer/milestone/13). The behavior below consolidates the decisions confirmed during grill-with-docs; proposals and remaining presentation choices are identified separately.
## Problem Statement
@@ -79,7 +79,7 @@ Use behavior-level tests that assert returned planning facts and user-visible fi
## Further Notes
- Scope references: #3 and #29 describe the shared popup; #7 supplies the average work-sequence requirement; #8 supplies earned leave; #9 supplies public holidays connected to weekends; #28's longest work-sequence metric already exists. The discussion adds average and longest time-off period lengths and dated one-workday-week warnings. Existing planner and calculation-performance work in the milestone remains the baseline.
- Domain definitions are maintained in [CONTEXT.md](../CONTEXT.md). Relevant architectural constraints are the [personal client-side planner](adr/0002-personal-client-side-planner-for-now.md), [separate calculation outcome and trace](adr/0004-stable-explanation-original-trace-counterfactual.md), [selected horizons and cancellation](adr/0006-user-selected-horizons-and-cancellable-calculations.md), and [declared days and reported balances](adr/0007-declared-days-and-reported-balances.md).
- Domain definitions are maintained in [CONTEXT.md](../CONTEXT.md). Relevant architectural constraints are [server-side planning for every device](adr/0011-server-side-planning-for-every-device.md), which superseded the [personal client-side planner](adr/0002-personal-client-side-planner-for-now.md), [separate calculation outcome and trace](adr/0004-stable-explanation-original-trace-counterfactual.md), [selected horizons and cancellation](adr/0006-user-selected-horizons-and-cancellable-calculations.md), and [declared days and reported balances](adr/0007-declared-days-and-reported-balances.md).
- **Current integration gaps:** The inspected outcome exposes placements, periods, remaining balances, and several quality metrics, but no dedicated gross earned-leave summary or fixed calculation date. Remaining balances omit fully consumed entitlements. Declared-day support is in progress in the working tree: declarations are carried with outcomes, while the inspected period and work-sequence calculations still use placements alone. Coordinate with #13's finalized semantics before relying on those values; avoid a second conflicting calendar model in the popup.
- **Proposed empty-value convention, not explicitly confirmed:** Counts show 0 when there are no qualifying items. An average with no samples, or longest time-off period length when no periods exist, shows "—". The existing longest work-sequence length remains 0 when there are no work sequences. Empty samples should remain distinguishable from a measured zero in the underlying data.
- **Remaining presentation choices:** Exact decimal precision for averages, metric layout, and whether eligible rules with zero earnings receive breakdown rows were not decided. These do not change the agreed counting or date rules. Use existing presentation conventions and keep any selected defaults explicit during implementation.
- **Remaining presentation choices:** Metric layout and whether eligible rules with zero earnings receive breakdown rows were not decided. Statistics show at most one decimal in the active locale (#353). These do not change the agreed counting or date rules. Use existing presentation conventions and keep any selected defaults explicit during implementation.
+158
View File
@@ -0,0 +1,158 @@
# Integrated planning verification after trace removal
Functional verification for [#77](https://gitea.nessar.fr/nessar/vac-optimizer/issues/77),
run on 2026-10-15 against `2f4af14869c47836d2c1008157136f75c9d3e98b`
(`develop`, including the merged #76 implementation). The original checkout was
clean at `d9d9befa1256cd2200aa4778d28b2bc23ba141e6`; both commits have the same
tree. This verification adds two real-worker lifecycle tests and this report.
It does not change production behavior, saved data, placement expectations,
benchmark inputs, CI settings or performance limits.
## Contract audit
| Path | Verified retained contract |
| --- | --- |
| Synchronous and cooperative core | Outcomes, valid checkpoints, final-state snapshots, stable explanations and explicit cancellation; no recorder, candidate history or historical replay API. |
| Server calculation context | Immutable submitted configuration, independently delivered outcome and explanation, and displayed-placement date analysis. |
| Browser without Worker | Validation and explicit `worker-unavailable` handling; no synchronous planning or trace compatibility result. |
| Native worker and coordinator | Heartbeat, progress, checkpoint, result, explanation and final artifacts. The coordinator terminates the worker after required delivery with no acknowledgement message or queue. |
| Calendar and remaining balances | Final and valid partial calendars, placement provenance, objective comparisons, earned sources, validity dates and concrete non-placement reasons. |
| Alternative dates | Captured horizon, entitlement, type and rule provenance; unrelated placements stay fixed. Hypothetical comparisons never update the displayed plan. |
| Benchmark callers | Supported calculation outcome, explanation and timings; no trace promises, waits, counts or replacement trace metrics. |
Since #339, the calculation paths that ran the planner without a worker (no window,
or a window without `Worker`) no longer exist. Tests and callers outside a browser pass the in-process job
(`leave-planner.in-process-job.ts`), which runs the worker's message handling on the
calling thread under the same calculation lifecycle as the native worker. A browser
whose job cannot start reports `worker-unavailable` without validating the request
first; only an invalid deadline and a request that cannot be cloned, which the lifecycle
rejects before starting a job, are still reported as invalid input.
Production-source searches found no decision-trace, historical analysis,
acknowledgement or replay implementation. `PlanningArtifacts` carries actual explanation,
final-state and planning-work timing data, rather than a compatibility shell.
## Existing deterministic fixtures
The full functional suite passes without changing any existing expected placement,
balance, metric, objective, chronology or completed-stage assertion.
| Requirement | Existing regression coverage |
| --- | --- |
| Typed joint obligations and shared provenance | `leave-planner.service.spec.ts`, `leave-planner-explanation.spec.ts` and real-worker tests. |
| Earned-entitlement chains and availability | Integration, explanation, supporting-placement and real-worker tests, including declarations and cancellation. |
| Custom formulas and reordered priorities | Optimization, calendar-objective, work-sequence and supporting-placement tests, including real-worker comparisons. |
| Two- and three-year horizons | Service, calendar and worker tests retain the submitted dates and deterministic completed plans. |
| No active optimization rules | Optimization and migration tests retain declarations and remaining balances without adding placements. |
| Stable explanations and remaining reasons | Entitlements, every contributing rule, ordered objective values, first decisive objective, periods and dated non-placement reasons. |
| Cancellation and failures | Before and after a jointly valid incumbent, stale calculations and date analyses, worker liveness, technical budgets, and local explanation errors. |
| Saved settings | Existing migration and persistence tests preserve user rule choices, balances, declarations and explicitly selected horizons. |
An additional direct comparison uses the pre-removal core from `ea42561`, with
only its relative imports redirected to the unchanged calendar/date/objective
modules. Both versions receive the same cloned requests and calculation date
`2024-01-01`. Full outcomes and stable explanations are compared with deep
equality; no placement expectations or retained explanation fields are filtered.
All ten completed comparisons match for both the full outcome and stable
explanation:
| Fixture | Outcome | Placements | Last completed stage |
| --- | --- | --- | --- |
| Representative year | `Plan` | 30 | `dates` |
| Typed joint obligations | `Plan` | 10 | `dates` |
| Chained earned entitlements | `Plan` | 3 | `dates` |
| Deliberate conflict | `PlanningConflict` | 0 | — |
| Two years | `Plan` | 60 | `dates` |
| Three years | `Plan` | 90 | `dates` |
| Holiday value before non-working-day gain | `Plan` | 3 | `dates` |
| Non-working-day gain before holiday value | `Plan` | 3 | `dates` |
| Custom maximum holiday-week aggregation | `Plan` | 3 | `dates` |
| No active optimization, with a declared day | `Plan` | 0 | `dates` |
The reordered priorities retain their different placement dates: 6, 7 and 10 May
for holiday value first; 29 April, 10 May and 17 May for gain first. The zero-rule
case retains its declaration. These are correctness comparisons, not timed
benchmark repetitions. An exploratory pre-removal loaded-year replay was stopped
and is not used as passing evidence; its full protocol remains with #78.
## Correctness and static checks
Environment: Node `24.18.0`, Bun `1.3.14`, Linux under WSL2.
```sh
NODE_OPTIONS=--max-old-space-size=2048 bunx vitest run --coverage --maxWorkers=1 --exclude='src/app/benchmark/**'
bunx tsc -p tsconfig.app.json --noEmit
bunx tsc -p tsconfig.spec.json --noEmit
bun run lint
bun run format:check
bunx prettier --check 'scripts/ci-*.mjs' '.gitea/workflows/*.yml'
node scripts/ci-policy.test.mjs
node scripts/ci-image.test.mjs
bun run build
git diff --check
```
All checks pass. Functional coverage: **632 tests across 33 files**, 93.56%
statements, 85.90% branches, 95.69% functions and 95.41% lines. The full coverage
run took 95.67 seconds with the existing 2 GB Node heap setting. The focused
real-worker file passes all 15 tests, including the two added lifecycle checks.
Coverage configuration and thresholds are unchanged.
The production build retains its existing warning budgets: initial bundle
2.57 MB against the 2.50 MB warning and calendar-year styles 12.98 kB against
the 8 kB warning. Both remain below their unchanged error limits.
## Browser QA
The production build was served locally with
`NG_ALLOWED_HOSTS=localhost,127.0.0.1 PORT=4177` and exercised in headless
Chromium `149.0.7827.55`, using native module Workers, reduced motion and
375×915, 768×915 and 1440-pixel-wide viewports. The calculation date was fixed
to `2024-01-01`. This is desktop functional evidence, not a phone performance run.
| Flow | Result |
| --- | --- |
| Completed calendar and explanation | Three CP placements on 6, 7 and 10 May 2024, six gained non-working dates; keyboard disclosure, placement navigation and calendar selection work. |
| Remaining balances | Future RTT availability and unavoidable expiry show their actual dates, reasons and planning horizon without attempt/history controls. Earned-source rendering is also covered by component tests. |
| Date comparison | An alternative on 13 May is hypothetical; placements and selected calendar dates remain unchanged. Escape closes the dialog and restores focus to Compare dates. |
| Immutable settings | Persisting a current CP balance edit from 3 to 99 leaves the displayed three placements unchanged. Select another placement and verify that a new comparison request is sent after the edit; that request still contains the captured quantity 3 and original horizon. |
| Cancellation before a valid plan | At 375 px, hold the native worker script download, activate Cancel with Enter, then release startup. Result is `PlanningIncomplete` / `user-cancelled`, without an incumbent or a false conflict. This controlled startup is not latency evidence. |
| Cancellation after a valid plan | At 375 px, use the unchanged loaded-year request and cancel with Enter after a real checkpoint. All three typed obligation windows remain satisfied, placements plus remaining balances total 72, and the partial explanation is available. Inputs remain editable during planning; Cancel is at least 44 px high. |
| Delayed and stale delivery | At 375 px, hold explanation and artifact messages after a real outcome. The three-placement calendar is usable immediately. Recalculate, then release the old messages; the current result and explanation remain intact. |
| Explanation failure | At 375 px, inject explanation transport and checkpoint-explanation recovery failures. An inline error appears while the completed calendar and all three placements remain available. |
| Responsive and keyboard interaction | No page-level horizontal overflow at 375, 768 or 1440 px. Comparison dialogs fit, retain keyboard focus and restore it on dismissal. No unexpected browser page errors. |
| Removed UI | No advanced trace explorer, historical overlays, replay controls, candidate-status UI or remaining-balance attempt controls. |
Controlled-clock transport tests additionally verify that heartbeats renew the
30-second inactivity watchdog across repeated windows and that monitoring ends
at outcome delivery. Native-worker tests verify actual heartbeat delivery,
incumbent validity and retained explanations. No automatic engine cutoff is added.
## Handoff to #78
The #70 → #71 → #72 → #73 → #74 → #75 dependency order is preserved. The tracker
already reports those six tickets and #76 closed. This work verifies their
functional integration and does not close or modify any other ticket.
The benchmark source and its original correctness assertions remain unchanged
from the integrated baseline:
| File | SHA-256 |
| --- | --- |
| `src/app/benchmark/leave-planner-benchmark.ts` | `16e057fa042c898d203f71e018f183c9fbecb5cd0edbf0ce0f3f25277cb00d3a` |
| `src/app/benchmark/leave-planner-benchmark.spec.ts` | `c7b4c37b6c169b42c4d18dfc3e650b25a2ba47415c97268dafefafbfb0ee3023` |
All seven scenarios, typed and earned-chain fixtures, two-/three-year horizons,
60-/90-placement expectations, determinism comparisons and final `dates` stage
assertions remain in place. Warm-ups and measured repetitions remain unchanged.
The full 2 GB / 300-second benchmark protocol and any required optimization stay
open in [#78](https://gitea.nessar.fr/nessar/vac-optimizer/issues/78); they are not
a completion gate for #75 or #77. This run makes no performance acceptance or
trace-removal speedup claim. The separate advisory benchmark status must be
resolved by #78 under the existing limits.
Local run logs, the original spec and checkout record, comparison scripts and
browser screenshots are in `/tmp/vac-issue-77`. The source fixtures and commands
above identify the reproducible correctness checks; temporary QA controls are
not part of the application.
+24 -34
View File
@@ -1,17 +1,19 @@
{
"name": "vac-optimizer",
"version": "1.5.0",
"packageManager": "bun@1.4.3",
"scripts": {
"ng": "ng",
"start": "bun scripts/generate-langs.js && ng serve",
"build": "bun scripts/generate-langs.js && ng build",
"build": "bun scripts/generate-langs.js && bun scripts/build.mjs",
"watch": "bun scripts/generate-langs.js && ng build --watch --configuration development",
"test": "bun scripts/generate-langs.js && ng test",
"serve:ssr:vac-optimizer": "bun dist/vac-optimizer/server/server.mjs",
"test": "bun scripts/generate-langs.js && bun test --isolate",
"serve": "bun dist/vac-optimizer/server/server.js",
"typecheck": "bun scripts/generate-langs.js && bun check -p tsconfig.app.json && bun check -p tsconfig.spec.json",
"lint": "bun scripts/generate-langs.js && eslint \"src/**/*.ts\"",
"lint:fix": "bun scripts/generate-langs.js && eslint \"src/**/*.ts\" --fix",
"format": "bun scripts/generate-langs.js && prettier --write \"src/**/*.{ts,html,scss,css,json}\"",
"format:check": "bun scripts/generate-langs.js && prettier --check \"src/**/*.{ts,html,scss,css,json}\""
"format": "bun scripts/generate-langs.js && prettier --write \"src/**/*.{ts,html,scss,css,json}\" \"scripts/ci-*.mjs\" \".gitea/workflows/*.yml\"",
"format:check": "bun scripts/generate-langs.js && prettier --check \"src/**/*.{ts,html,scss,css,json}\" \"scripts/ci-*.mjs\" \".gitea/workflows/*.yml\""
},
"prettier": {
"printWidth": 100,
@@ -27,51 +29,39 @@
},
"private": true,
"dependencies": {
"@angular/animations": "22.2.1",
"@angular/cdk": "^22.0.0",
"@angular/common": "22.2.1",
"@angular/compiler": "22.2.1",
"@angular/core": "22.2.1",
"@angular/forms": "22.2.1",
"@angular/common": "22.2.3",
"@angular/compiler": "22.2.3",
"@angular/core": "22.2.3",
"@angular/forms": "22.2.3",
"@angular/material": "^22.0.0",
"@angular/platform-browser": "22.2.1",
"@angular/platform-browser-dynamic": "22.2.1",
"@angular/platform-server": "22.2.1",
"@angular/router": "22.2.1",
"@angular/ssr": "22.2.1",
"@angular/platform-browser": "22.2.3",
"@angular/platform-browser-dynamic": "22.2.3",
"@angular/router": "22.2.3",
"date-holidays": "^3.30.2",
"dayjs": "^1.11.21",
"express": "^5.2.1",
"rxjs": "~7.8.2",
"tslib": "^2.8.1"
},
"devDependencies": {
"@analogjs/platform": "^2.7.5",
"@analogjs/vite-plugin-angular": "^2.7.5",
"@analogjs/vitest-angular": "^2.7.5",
"@angular/build": "22.2.1",
"@angular/cli": "22.2.1",
"@angular/compiler-cli": "22.2.1",
"@angular/build": "22.2.3",
"@angular/cli": "22.2.3",
"@angular/compiler-cli": "22.2.3",
"@eslint/js": "^10.0.1",
"@nx/devkit": "^23.0.0",
"@nx/vite": "^23.0.0",
"@types/express": "^5.0.6",
"@types/jest": "^30.0.0",
"@types/bun": "1.4.3",
"@types/jsdom": "^30.0.0",
"@types/node": "^26.0.0",
"@vitest/coverage-istanbul": "^5.0.0",
"@vitest/coverage-v8": "^5.0.0",
"@vitest/ui": "^5.0.0",
"eslint": "^10.4.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.6",
"jest": "^30.4.2",
"jest-preset-angular": "^17.0.0",
"fast-check": "4.10.2",
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-reports": "^3.2.0",
"jsdom": "^30.0.0",
"prettier": "^3.8.3",
"typescript": "~6.0.3",
"typescript-eslint": "^8.60.0",
"vite": "^8.0.0",
"vite-tsconfig-paths": "^6.0.0",
"vitest": "^5.0.0"
"typescript-eslint": "^8.60.0"
}
}
+14 -1
View File
@@ -4,5 +4,18 @@
"config:recommended"
],
"prConcurrentLimit": 3,
"automerge": false
"automerge": false,
"automergeStrategy": "merge-commit",
"minimumReleaseAge": "3 days",
"packageRules": [
{
"matchUpdateTypes": [
"minor",
"patch",
"digest",
"pin"
],
"automerge": true
}
]
}
+27
View File
@@ -0,0 +1,27 @@
// One script builds both bundles so they share one identifier: the server refuses clients of other builds.
import { randomUUID } from 'node:crypto';
const define = JSON.stringify(randomUUID());
const args = process.argv.slice(2).filter((arg, index) => index > 0 || arg !== '--');
// `ng build` empties its output path, so the server bundle has to come after it.
const ng = Bun.spawn(
['bun', 'run', 'ng', 'build', '--define', `PLANNING_BUILD=${define}`, ...args],
{
stdio: ['inherit', 'inherit', 'inherit'],
// Angular skips its chunk optimization below three lazy chunks, which splits the initial bundle.
env: { NG_BUILD_OPTIMIZE_CHUNKS: '1', ...process.env },
},
);
const code = await ng.exited;
if (code !== 0) process.exit(code);
const result = await Bun.build({
entrypoints: ['src/server.ts', 'src/app/services/leave-planner.worker.ts'],
target: 'bun',
outdir: 'dist/vac-optimizer/server',
naming: '[name].[ext]',
define: { PLANNING_BUILD: define },
});
for (const log of result.logs) console.log(log);
if (!result.success) process.exit(1);
+35
View File
@@ -0,0 +1,35 @@
import { readFileSync } from 'node:fs';
// Gitea exposes its event payload through the GitHub-compatible runner variables.
export function readCiContext() {
const env = process.env;
const eventName = env.GITHUB_EVENT_NAME;
if (!['push', 'pull_request', 'workflow_dispatch'].includes(eventName)) {
throw new Error('Only push, pull_request and workflow_dispatch events are supported.');
}
const event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8'));
const commit = env.GITHUB_SHA;
if (!/^[a-f0-9]{40}$/.test(commit ?? '')) throw new Error('A commit SHA is required.');
const pullRequest = eventName === 'pull_request' ? event.pull_request : undefined;
if (eventName === 'pull_request' && pullRequest?.head?.sha !== commit) {
throw new Error('CI must validate the pull request head commit.');
}
const tag = env.GITHUB_REF?.startsWith('refs/tags/') ? env.GITHUB_REF.slice(10) : '';
const branch = pullRequest
? pullRequest.head.ref
: env.GITHUB_REF?.startsWith('refs/heads/')
? env.GITHUB_REF.slice(11)
: '';
if (!tag && !branch) throw new Error('A branch or tag ref is required.');
const slug = branch
.toLowerCase()
.replace(/[^a-z0-9]/g, '-')
.slice(0, 63)
.replace(/^-+|-+$/g, '');
const publish =
eventName === 'push' ||
(eventName === 'pull_request' &&
Boolean(env.GITHUB_REPOSITORY) &&
pullRequest.head.repo?.full_name === env.GITHUB_REPOSITORY);
return { commit, tag, branch, slug, publish, pullRequest, before: event.before };
}
+40
View File
@@ -0,0 +1,40 @@
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { readCiContext } from './ci-context.mjs';
try {
const { commit, tag, slug, publish } = readCiContext();
if (!publish) throw new Error('Images can only be published by pushes or same-repository PRs.');
execFileSync(process.execPath, [fileURLToPath(new URL('./ci-policy.mjs', import.meta.url))]);
const env = process.env;
if (!env.REGISTRY_USERNAME || !env.REGISTRY_PASSWORD) {
throw new Error('REGISTRY_USERNAME and REGISTRY_PASSWORD are required for publication.');
}
const registry = new URL(env.GITHUB_SERVER_URL).host;
const image = `${registry}/${env.GITHUB_REPOSITORY.toLowerCase()}`;
const shaImage = `${image}:sha-${commit}`;
const docker = (...args) => execFileSync('docker', args, { stdio: 'inherit' });
execFileSync(
'docker',
['login', registry, '--username', env.REGISTRY_USERNAME, '--password-stdin'],
{
input: env.REGISTRY_PASSWORD,
stdio: ['pipe', 'inherit', 'inherit'],
},
);
if (tag) {
docker('pull', shaImage);
docker('tag', shaImage, `${image}:${tag}`);
docker('push', `${image}:${tag}`);
docker('tag', shaImage, `${image}:latest`);
docker('push', `${image}:latest`);
} else {
const branchImage = `${image}:branch-${slug}`;
docker('build', '-t', shaImage, '-t', branchImage, '.');
docker('push', shaImage);
docker('push', branchImage);
}
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
+137
View File
@@ -0,0 +1,137 @@
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
const directory = mkdtempSync(join(tmpdir(), 'ci-image-'));
const script = fileURLToPath(new URL('./ci-image.mjs', import.meta.url));
const git = (...args) => execFileSync('git', args, { cwd: directory, encoding: 'utf8' }).trim();
const image = 'gitea.nessar.fr/nessar/vac-optimizer';
const commandsPath = join(directory, 'docker-commands.jsonl');
const bin = join(directory, 'bin');
const run = (variables = {}, expected = 0) => {
const commit = git('rev-parse', 'HEAD');
const eventName = variables.eventName ?? 'push';
const ref = variables.tag
? `refs/tags/${variables.tag}`
: eventName === 'pull_request'
? 'refs/pull/42/head'
: 'refs/heads/feature/calendar';
const event = { ref };
if (eventName === 'pull_request') {
event.pull_request = {
title: 'feat: calendar',
head: {
sha: commit,
ref: 'feature/calendar',
repo: { full_name: variables.headRepository ?? 'nessar/vac-optimizer' },
},
base: { ref: 'develop' },
};
}
writeFileSync(join(directory, 'event.json'), JSON.stringify(event));
writeFileSync(commandsPath, '');
const result = spawnSync(process.execPath, [script], {
cwd: directory,
encoding: 'utf8',
env: {
PATH: `${bin}:${process.env.PATH}`,
GITHUB_EVENT_NAME: eventName,
GITHUB_EVENT_PATH: join(directory, 'event.json'),
GITHUB_SHA: commit,
GITHUB_REF: ref,
GITHUB_REPOSITORY: 'nessar/vac-optimizer',
GITHUB_SERVER_URL: 'https://gitea.nessar.fr',
REGISTRY_USERNAME: 'publisher',
REGISTRY_PASSWORD: variables.registryPassword ?? 'test-token',
DOCKER_COMMANDS: commandsPath,
MISSING_IMAGE: variables.missingImage ? 'true' : '',
},
});
assert.equal(result.status, expected, result.stdout + result.stderr);
return readFileSync(commandsPath, 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse);
};
try {
git('init', '--initial-branch=main');
git('config', 'user.name', 'CI image test');
git('config', 'user.email', 'ci-image@example.invalid');
git('remote', 'add', 'origin', directory);
writeFileSync(join(directory, 'package.json'), '{"version":"1.5.0"}\n');
git('add', 'package.json');
git('commit', '-m', 'chore: initial release');
git('branch', 'develop');
git('switch', '-c', 'feature/calendar');
git('commit', '--allow-empty', '-m', 'feat: calendar');
mkdirSync(bin);
const docker = join(bin, 'docker');
writeFileSync(
docker,
`#!/usr/bin/env bun
import { appendFileSync, readFileSync } from 'node:fs';
const args = process.argv.slice(2);
const input = args[0] === 'login' ? readFileSync(0, 'utf8') : '';
appendFileSync(process.env.DOCKER_COMMANDS, JSON.stringify({ args, input }) + '\\n');
if (args[0] === 'pull' && process.env.MISSING_IMAGE === 'true') process.exit(1);
`,
);
chmodSync(docker, 0o755);
const commit = git('rev-parse', 'HEAD');
const commands = run();
assert.deepEqual(commands, [
{
args: ['login', 'gitea.nessar.fr', '--username', 'publisher', '--password-stdin'],
input: 'test-token',
},
{
args: [
'build',
'-t',
`${image}:sha-${commit}`,
'-t',
`${image}:branch-feature-calendar`,
'.',
],
input: '',
},
{ args: ['push', `${image}:sha-${commit}`], input: '' },
{ args: ['push', `${image}:branch-feature-calendar`], input: '' },
]);
assert.deepEqual(run({ eventName: 'pull_request' }), commands);
assert.deepEqual(
run({ eventName: 'pull_request', headRepository: 'contributor/vac-optimizer' }, 1),
[],
);
assert.deepEqual(run({ eventName: 'workflow_dispatch' }, 1), []);
assert.deepEqual(run({ registryPassword: '' }, 1), []);
assert.deepEqual(run({ tag: 'v1.5.0' }, 1), []);
git('switch', 'main');
git('tag', '-a', 'v1.5.0', '-m', 'Release 1.5.0');
const releaseCommit = git('rev-parse', 'HEAD');
assert.deepEqual(run({ tag: 'v1.5.0' }), [
{
args: ['login', 'gitea.nessar.fr', '--username', 'publisher', '--password-stdin'],
input: 'test-token',
},
{ args: ['pull', `${image}:sha-${releaseCommit}`], input: '' },
{ args: ['tag', `${image}:sha-${releaseCommit}`, `${image}:v1.5.0`], input: '' },
{ args: ['push', `${image}:v1.5.0`], input: '' },
{ args: ['tag', `${image}:sha-${releaseCommit}`, `${image}:latest`], input: '' },
{ args: ['push', `${image}:latest`], input: '' },
]);
assert.deepEqual(run({ tag: 'v1.5.0', missingImage: true }, 1), [
{
args: ['login', 'gitea.nessar.fr', '--username', 'publisher', '--password-stdin'],
input: 'test-token',
},
{ args: ['pull', `${image}:sha-${releaseCommit}`], input: '' },
]);
assert.deepEqual(run({ tag: 'v1.5.0-rc.1' }, 1), []);
assert.deepEqual(run({ tag: 'v1.6.0' }, 1), []);
console.log('CI image publication checks passed.');
} finally {
rmSync(directory, { recursive: true, force: true });
}
+87
View File
@@ -0,0 +1,87 @@
import { execFileSync, spawnSync } from 'node:child_process';
import { appendFileSync, readFileSync } from 'node:fs';
import { readCiContext } from './ci-context.mjs';
const env = process.env;
const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim();
const ancestor = (base, commit) =>
spawnSync('git', ['merge-base', '--is-ancestor', base, commit]).status === 0;
const conventional = /^[a-z]+(?:\([^()\r\n]+\))?!?: \S.*$/i;
const requirePolicy = (condition, message) => {
if (!condition) throw new Error(message);
};
try {
const { commit, tag, branch, slug, pullRequest, before } = readCiContext();
requirePolicy(commit === git('rev-parse', 'HEAD'), 'CI must validate the checked-out commit.');
git(
'fetch',
'--no-tags',
'origin',
'+refs/heads/main:refs/remotes/origin/main',
'+refs/heads/develop:refs/remotes/origin/develop',
);
if (tag) {
requirePolicy(
/^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(tag),
'Release tags must use vMAJOR.MINOR.PATCH without leading zeroes.',
);
const { version } = JSON.parse(readFileSync('package.json', 'utf8'));
requirePolicy(tag === `v${version}`, 'Release tag must match package.json.');
requirePolicy(ancestor(commit, 'origin/main'), 'Release commit must belong to main.');
} else {
const target = pullRequest
? pullRequest.base?.ref
: branch === 'main' || branch?.startsWith('hotfix/')
? 'main'
: 'develop';
requirePolicy(branch, 'A branch name is required.');
git('check-ref-format', `refs/heads/${branch}`);
requirePolicy(['main', 'develop'].includes(target), 'PRs must target main or develop.');
if (pullRequest) {
const title = pullRequest.title?.replace(
/^(?:Draft:|WIP:|\[Draft\]|\[WIP\]|\(Draft\)|\(WIP\))\s*/i,
'',
);
requirePolicy(
conventional.test(title ?? ''),
'PR title must use Conventional Commits.',
);
requirePolicy(
target !== 'main' || /^(release|hotfix)\/.+/.test(branch),
'Only release/* and hotfix/* may merge into main.',
);
if (target === 'develop' && branch !== 'main' && !/^(release|hotfix)\//.test(branch)) {
requirePolicy(
ancestor('origin/develop', commit),
'Rebase the working branch onto origin/develop before merging.',
);
requirePolicy(
!git('rev-list', '--merges', `origin/develop..${commit}`),
'Working branches must use rebase, not merge commits.',
);
}
}
const base =
!pullRequest && before && !/^0+$/.test(before) && ancestor(before, commit)
? before
: git('merge-base', `origin/${target}`, commit);
const subjects = git('log', '--format=%h %s', `${base}..${commit}`);
for (const line of subjects ? subjects.split('\n') : []) {
requirePolicy(
conventional.test(line.slice(line.indexOf(' ') + 1)),
`Commit must use Conventional Commits: ${line}`,
);
}
}
if (env.GITHUB_OUTPUT) {
appendFileSync(env.GITHUB_OUTPUT, `slug=${slug}\ntag=${tag}\n`);
}
console.log('GitFlow, version and commit policy passed.');
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
+130
View File
@@ -0,0 +1,130 @@
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
const directory = mkdtempSync(join(tmpdir(), 'ci-policy-'));
const script = fileURLToPath(new URL('./ci-policy.mjs', import.meta.url));
const git = (...args) => execFileSync('git', args, { cwd: directory, encoding: 'utf8' }).trim();
const check = (variables = {}, expected = 0) => {
const commit = git('rev-parse', 'HEAD');
const branch = variables.branch ?? 'feature/test';
const eventName = variables.eventName ?? 'push';
const ref = variables.tag
? `refs/tags/${variables.tag}`
: eventName === 'pull_request'
? 'refs/pull/42/head'
: `refs/heads/${branch}`;
const event = { ref, before: variables.before };
if (eventName === 'pull_request') {
event.pull_request = {
title: variables.title ?? 'feat(test): add policy checks',
head: {
ref: branch,
sha: variables.headSha ?? commit,
repo: { full_name: variables.headRepository ?? 'nessar/vac-optimizer' },
},
base: { ref: variables.target ?? 'develop' },
};
}
const eventPath = join(directory, 'event.json');
const outputPath = join(directory, 'outputs');
writeFileSync(eventPath, JSON.stringify(event));
writeFileSync(outputPath, '');
const result = spawnSync(process.execPath, [script], {
cwd: directory,
encoding: 'utf8',
env: {
PATH: process.env.PATH,
GITHUB_EVENT_NAME: eventName,
GITHUB_EVENT_PATH: eventPath,
GITHUB_REF: ref,
GITHUB_SHA: variables.sha ?? commit,
GITHUB_REPOSITORY: 'nessar/vac-optimizer',
GITHUB_OUTPUT: outputPath,
},
});
assert.equal(result.status, expected, result.stdout + result.stderr);
return readFileSync(outputPath, 'utf8');
};
const pr = { eventName: 'pull_request' };
try {
git('init', '--initial-branch=main');
git('config', 'user.name', 'CI policy test');
git('config', 'user.email', 'ci-policy@example.invalid');
git('remote', 'add', 'origin', directory);
writeFileSync(join(directory, 'package.json'), '{"version":"1.5.0"}\n');
git('add', 'package.json');
git('commit', '-m', 'Legacy history is allowed');
git('branch', 'develop');
git('switch', '-c', 'feature/test');
git('commit', '--allow-empty', '-m', 'feat(test)!: add checks');
check({});
check(pr);
check({ ...pr, headRepository: 'contributor/vac-optimizer' });
check({ eventName: 'workflow_dispatch' });
assert.match(check({ branch: 'Feature/My_calendar' }), /slug=feature-my-calendar\n/);
check({ ...pr, headSha: '0'.repeat(40) }, 1);
check({ eventName: 'pull_request_target' }, 1);
check({ ...pr, title: 'Draft: feat: test policy' });
check({ ...pr, title: '(Draft) feat: test policy' });
check({ ...pr, target: 'main' }, 1);
check({ ...pr, title: 'Add checks' }, 1);
check({ tag: 'v1.5.0' }, 1);
check({ sha: '0'.repeat(40) }, 1);
git('switch', 'develop');
git('commit', '--allow-empty', '-m', 'fix: another change');
git('switch', 'feature/test');
check(pr, 1);
git('rebase', 'develop');
check(pr);
const before = git('rev-parse', 'HEAD');
git('commit', '--allow-empty', '-m', 'not conventional');
check({ before: before }, 1);
check(pr, 1);
git('commit', '--amend', '--allow-empty', '-m', 'ci: fix the commit title');
check({ before: before });
git('switch', 'develop');
git('merge', '--no-ff', 'feature/test', '-m', 'feat(test): add policy checks');
git('switch', '-c', 'release/1.6.0');
writeFileSync(join(directory, 'package.json'), '{"version":"1.6.0"}\n');
git('add', 'package.json');
git('commit', '-m', 'chore(release): prepare 1.6.0');
check({
...pr,
branch: 'release/1.6.0',
target: 'main',
});
check({ ...pr, branch: 'release/1.6.0' });
git('switch', 'main');
git('merge', '--no-ff', 'release/1.6.0', '-m', 'chore(release): publish 1.6.0');
check({ tag: 'v1.6.0' });
check({ tag: 'v1.5.0' }, 1);
check({ tag: 'v01.6.0' }, 1);
check({ tag: 'v1.6.0-rc.1' }, 1);
check({ ...pr, branch: 'main' });
git('switch', '-c', 'hotfix/1.6.1');
git('commit', '--allow-empty', '-m', 'fix: production issue');
check({
...pr,
branch: 'hotfix/1.6.1',
target: 'main',
});
check({ ...pr, branch: 'hotfix/1.6.1' });
// The working branch must not pass by merging develop instead of rebasing.
git('switch', 'feature/test');
git('commit', '--allow-empty', '-m', 'feat: keep working');
git('merge', '--no-ff', 'develop', '-m', 'chore: merge develop');
check(pr, 1);
console.log('CI policy integration checks passed.');
} finally {
rmSync(directory, { recursive: true, force: true });
}
+55
View File
@@ -0,0 +1,55 @@
// Converts coverage/lcov.info (Bun) to HTML and Cobertura. Run: bun scripts/coverage-reports.mjs
// shortcut: line coverage only, Bun's lcov has no usable branch/function data; revisit if Bun adds it.
// Totals here sum lines (8351/8578); Bun's text table averages per-file percentages, so it reads lower.
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import libCoverage from 'istanbul-lib-coverage';
import libReport from 'istanbul-lib-report';
import reports from 'istanbul-reports';
const map = libCoverage.createCoverageMap({});
const loc = (line) => ({ start: { line, column: 0 }, end: { line, column: 1 } });
for (const record of readFileSync('coverage/lcov.info', 'utf8').split('end_of_record')) {
const file = /^SF:(.+)$/m.exec(record)?.[1];
if (!file) continue;
const statementMap = {};
const s = {};
for (const [, line, hits] of record.matchAll(/^DA:(\d+),(\d+)/gm)) {
statementMap[line] = loc(+line);
s[line] = +hits;
}
map.addFileCoverage({
path: resolve(file),
statementMap,
s,
fnMap: {},
f: {},
branchMap: {},
b: {},
});
}
const context = libReport.createContext({ dir: 'coverage', coverageMap: map });
for (const name of ['html', 'cobertura']) reports.create(name).execute(context);
// Istanbul reports 0 branches/functions as 100%; relabel them instead of claiming coverage.
const rewrite = (file, edit) => writeFileSync(file, edit(readFileSync(file, 'utf8')));
for (const page of readdirSync('coverage', { recursive: true }).filter((f) => f.endsWith('.html')))
rewrite(join('coverage', page), (html) =>
html
.replace(
/<span class="strong">100% <\/span>(\s*<span class="quiet">(?:Branches|Functions)<\/span>\s*<span class='fraction'>)0\/0</g,
'<span class="strong">n/a </span>$1not collected<',
)
.replace(
/<td data-value="100" class="pct \w+">100%<\/td>(\s*)<td data-value="0" class="abs \w+">0\/0<\/td>/g,
'<td data-value="0" class="pct">n/a</td>$1<td data-value="0" class="abs">not collected</td>',
),
);
rewrite('coverage/cobertura-coverage.xml', (xml) =>
xml
.replaceAll('branch-rate="1"', 'branch-rate="0"')
.replace(
'<coverage ',
'<!-- Line coverage only: bun test does not collect branch or function coverage. -->\n<coverage ',
),
);
+9 -3
View File
@@ -9,7 +9,11 @@ if (!fs.existsSync(i18nDir)) {
process.exit(1);
}
const files = fs.readdirSync(i18nDir).filter((file) => file.endsWith('.json'));
const files = fs
.readdirSync(i18nDir)
.filter((file) => file.endsWith('.json'))
// English first: TranslationService falls back to the first language.
.sort((a, b) => (b === 'en.json') - (a === 'en.json') || a.localeCompare(b));
let importStatements = '';
let registryEntries = '';
@@ -17,7 +21,7 @@ let registryEntries = '';
files.forEach((file) => {
const langCode = path.basename(file, '.json');
importStatements += `import ${langCode} from '../i18n/${file}';\n`;
registryEntries += `\t${langCode}: ${langCode} as AppTranslations,\n`;
registryEntries += `\t${langCode}: ${langCode} satisfies AppTranslations,\n`;
});
const content = `// This file is auto-generated by scripts/generate-langs.js. Do not edit directly.
@@ -30,4 +34,6 @@ export const availableLanguagesList: string[] = Object.keys(translationsMap);
`;
fs.writeFileSync(registryFile, content, 'utf8');
console.log(`Successfully generated i18n registry at ${registryFile} with ${files.length} languages.`);
console.log(
`Successfully generated i18n registry at ${registryFile} with ${files.length} languages.`,
);
+41
View File
@@ -0,0 +1,41 @@
#!/bin/sh
# Installs the pinned Bun release to /opt/bun/bin without npm, after verifying its SHA-256.
# Needs curl, unzip and sha256sum. Bun upgrades change the version, package.json and every checksum together.
set -eu
version=1.4.3
dest=${BUN_INSTALL_DIR:-/opt/bun}
grep -q "\"packageManager\": \"bun@${version}\"" package.json || {
echo "package.json packageManager must be bun@${version}." >&2
exit 1
}
case "$(uname -m)" in
x86_64) arch=x64 ;;
aarch64 | arm64) arch=aarch64 ;;
*)
echo "Unsupported Bun architecture: $(uname -m)" >&2
exit 1
;;
esac
libc=
if [ -e /etc/alpine-release ]; then libc=-musl; fi
asset="bun-linux-${arch}${libc}"
case "$asset" in
bun-linux-x64) sha256=3e730528d89775f03f87f05c06787c4df4099d0a37f3f252e7b829cb23816e18 ;;
bun-linux-x64-musl) sha256=6e9ea98554ea0d05efda5840ae292618aaa3adefd66b0853520c5c86a37eac9c ;;
bun-linux-aarch64) sha256=efa9813da5ed72423bf847f916e8d2c47c0d776add972354026a75e10da9aa21 ;;
bun-linux-aarch64-musl) sha256=8de8a0003cc2707bb555887e3d450e24e1edf3f605f491393e89ed61a8853420 ;;
esac
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
curl --fail --location --silent --show-error \
"https://github.com/oven-sh/bun/releases/download/bun-v${version}/${asset}.zip" \
--output "$work/bun.zip"
echo "${sha256} ${work}/bun.zip" | sha256sum -c -
unzip -q "$work/bun.zip" -d "$work"
mkdir -p "${dest}/bin"
install -m 0755 "${work}/${asset}/bun" "${dest}/bin/bun"
"${dest}/bin/bun" --version
+167 -109
View File
@@ -7,10 +7,12 @@ import { MatOptionHarness } from '@angular/material/core/testing';
import { MatDialogHarness } from '@angular/material/dialog/testing';
import { MatSelectHarness } from '@angular/material/select/testing';
import { MatSlideToggleHarness } from '@angular/material/slide-toggle/testing';
import { type MockInstance, vi } from 'vitest';
import { type MockInstance, vi } from '../testing/vitest-compat';
import { App } from './app';
import { CalendarService } from './services/calendar-service';
import { calculatePlanningInternal } from './services/leave-planner.core';
import { startInProcessJob } from './services/leave-planner.in-process-job';
import { createPlanningCalculation, type WorkerJobFactory } from './services/leave-planner.service';
import { PlanningCalculationService } from './services/planning-calculation.service';
describe('Application Settings', () => {
const savedBalances = JSON.stringify([
@@ -26,13 +28,13 @@ describe('Application Settings', () => {
let loader: HarnessLoader;
let opener: HTMLButtonElement;
let mediaQuery: EventTarget & { matches: boolean; media: string };
let calculate: MockInstance<CalendarService['createPlanningCalculation']>;
let calculate: MockInstance<PlanningCalculationService['createPlanningCalculation']>;
beforeEach(async () => {
localStorage.clear();
localStorage.setItem('app.language', JSON.stringify('en'));
localStorage.setItem('leaveBalances', savedBalances);
localStorage.setItem('vacationRules', '[]');
localStorage.setItem('vacationRules', '{"version":1,"rules":[]}');
localStorage.setItem('unrelated.entry', 'keep this value');
mediaQuery = Object.assign(new EventTarget(), {
matches: true,
@@ -47,12 +49,14 @@ describe('Application Settings', () => {
await createApp();
});
async function createApp(): Promise<void> {
async function createApp(startJob?: WorkerJobFactory): Promise<void> {
await TestBed.configureTestingModule({
imports: [App],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
calculate = vi.spyOn(TestBed.inject(CalendarService), 'createPlanningCalculation');
calculate = vi
.spyOn(TestBed.inject(PlanningCalculationService), 'createPlanningCalculation')
.mockImplementation((request) => createPlanningCalculation(request, startJob));
fixture = TestBed.createComponent(App);
fixture.detectChanges();
await fixture.whenStable();
@@ -96,118 +100,116 @@ describe('Application Settings', () => {
fixture.detectChanges();
}
async function revisitApp(isLight: boolean): Promise<void> {
async function revisitApp(isLight: boolean, startJob?: WorkerJobFactory): Promise<void> {
fixture.destroy();
TestBed.resetTestingModule();
mediaQuery = Object.assign(new EventTarget(), {
matches: isLight,
media: '(prefers-color-scheme: light)',
});
await createApp();
await createApp(startJob);
}
it('keeps random starting balances unsaved through calculation and restores the first edited list', async () => {
it.each([
['absent', null],
['unreadable', '{'],
])(
'starts with nothing to plan when saved balances are %s, then calculates once a balance is added',
async (_, saved) => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 9, 4, 12));
vi.spyOn(console, 'warn').mockImplementation(() => {});
if (saved === null) localStorage.removeItem('leaveBalances');
else localStorage.setItem('leaveBalances', saved);
await revisitApp(true, startInProcessJob);
const root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('app-day-input')).toBeNull();
expect(localStorage.getItem('leaveBalances')).toBeNull();
expect(localStorage.getItem('unrelated.entry')).toBe('keep this value');
expect(root.querySelector('#leave-balances-empty')?.textContent).toContain(
'No leave balance yet',
);
const button = root.querySelector<HTMLButtonElement>('.calculate-button')!;
expect(button.disabled).toBe(true);
expect(button.getAttribute('aria-describedby')).toBe('leave-balances-empty');
expect(root.querySelector('.duration-estimate')).toBeNull();
expect(calculate).not.toHaveBeenCalled();
expect(root.querySelector('.planning-status')?.textContent).toContain(
'Add your leave balances',
);
expect(root.querySelector('.plan-summary')).toBeNull();
expect(root.querySelector('.statistics-button')).toBeNull();
// The default planning horizon still shows its weekends and public holidays.
expect(root.querySelectorAll('app-calendar-month')).toHaveLength(13);
expect(
root.querySelector('button[data-date="2026-11-11"]')?.getAttribute('aria-label'),
).toContain('Public Holiday');
expect(
root.querySelector('button[data-date="2026-10-10"]')?.getAttribute('aria-label'),
).toContain('Weekend');
root.querySelector<HTMLButtonElement>('.add-day-button')!.click();
fixture.detectChanges();
await fixture.whenStable();
const added = localStorage.getItem('leaveBalances');
expect(JSON.parse(added!)).toMatchObject([
{
type: 'cp',
numberOfDays: 1,
availableDate: '2026-10-04',
expiryDate: '2027-10-04',
},
]);
expect(root.querySelector('#leave-balances-empty')).toBeNull();
expect(root.querySelector('.planning-status')).toBeNull();
expect(calculate).not.toHaveBeenCalled();
expect(button.disabled).toBe(false);
button.click();
await fixture.whenStable();
expect(calculate).toHaveBeenCalledOnce();
expect(calculate.mock.calls[0][0].balances).toMatchObject([
{ type: 'cp', quantity: 1 },
]);
await expect.poll(() => root.querySelector('.plan-summary')).not.toBeNull();
await revisitApp(true);
expect(fixture.nativeElement.querySelectorAll('app-day-input')).toHaveLength(1);
expect(calculate).toHaveBeenCalledOnce();
expect(localStorage.getItem('leaveBalances')).toBe(added);
},
);
it('restores a saved empty list without calculating, and calculates declared days on their own', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 9, 4, 12));
const random = vi
.spyOn(Math, 'random')
.mockReturnValueOnce(0)
.mockReturnValueOnce(0.5)
.mockReturnValue(1 - Number.EPSILON);
localStorage.removeItem('leaveBalances');
await revisitApp(true);
const root = fixture.nativeElement as HTMLElement;
expect(
Array.from(root.querySelectorAll<HTMLInputElement>('app-day-input input')).map(
(input) => input.value,
),
).toEqual([
'10',
'04/10/2026',
'04/10/2027',
'15',
'04/10/2026',
'04/10/2027',
'20',
'04/10/2026',
'04/10/2027',
]);
const types = await loader.getAllHarnesses(
MatSelectHarness.with({ selector: 'app-day-input mat-select' }),
);
expect(await Promise.all(types.map((type) => type.getValueText()))).toEqual([
'Paid Leave',
'RTT',
'Other',
]);
expect(calculate).toHaveBeenCalledOnce();
const initialRequest = calculate.mock.calls[0][0];
expect(initialRequest.balances.map((balance) => balance.quantity)).toEqual([10, 15, 20]);
expect(calculatePlanningInternal(initialRequest).kind).toBe('Plan');
await expect.poll(() => root.querySelector('.planning-status')).not.toBeNull();
expect(localStorage.getItem('leaveBalances')).toBeNull();
root.querySelector<HTMLButtonElement>('.calculate-button')!.click();
await fixture.whenStable();
expect(calculate).toHaveBeenCalledTimes(2);
expect(calculate.mock.calls[1][0].balances).toEqual(initialRequest.balances);
await expect.poll(() => root.querySelector('.planning-status')).not.toBeNull();
expect(localStorage.getItem('leaveBalances')).toBeNull();
const quantity = root.querySelector<HTMLInputElement>(
'app-day-input input[type="number"]',
)!;
quantity.value = '7';
quantity.dispatchEvent(new Event('input'));
await fixture.whenStable();
const saved = localStorage.getItem('leaveBalances');
expect(JSON.parse(saved!)).toMatchObject([
{ type: 'cp', numberOfDays: 7, availableDate: '2026-10-04', expiryDate: '2027-10-04' },
{
type: 'rtt',
numberOfDays: 15,
availableDate: '2026-10-04',
expiryDate: '2027-10-04',
},
{
type: 'other',
numberOfDays: 20,
availableDate: '2026-10-04',
expiryDate: '2027-10-04',
},
]);
random.mockReturnValue(0);
await revisitApp(true);
expect(
Array.from(
fixture.nativeElement.querySelectorAll('app-day-input input[type="number"]'),
(input) => (input as HTMLInputElement).value,
),
).toEqual(['7', '15', '20']);
expect(calculate).toHaveBeenCalledOnce();
expect(calculate.mock.calls[0][0].balances).toEqual(
initialRequest.balances.map((balance, index) =>
index === 0 ? { ...balance, quantity: 7 } : balance,
),
);
expect(localStorage.getItem('leaveBalances')).toBe(saved);
});
it('calculates with a saved empty balance list without generating replacement rows', async () => {
localStorage.setItem('leaveBalances', '[]');
const random = vi.spyOn(Math, 'random');
await revisitApp(true);
expect(fixture.nativeElement.querySelector('app-day-input')).toBeNull();
let root = fixture.nativeElement as HTMLElement;
expect(root.querySelector('app-day-input')).toBeNull();
expect(root.querySelector('#leave-balances-empty')).not.toBeNull();
expect(root.querySelector<HTMLButtonElement>('.calculate-button')!.disabled).toBe(true);
expect(calculate).not.toHaveBeenCalled();
expect(localStorage.getItem('leaveBalances')).toBe('[]');
localStorage.setItem(
'declaredNonWorkingDays',
JSON.stringify([{ date: '2026-10-06', type: 'cp' }]),
);
await revisitApp(true, startInProcessJob);
root = fixture.nativeElement as HTMLElement;
expect(calculate).toHaveBeenCalledOnce();
expect(calculate.mock.calls[0][0].balances).toEqual([]);
expect(calculatePlanningInternal(calculate.mock.calls[0][0]).kind).toBe('Plan');
await expect
.poll(() => fixture.nativeElement.querySelector('.planning-status'))
.not.toBeNull();
expect(random).not.toHaveBeenCalled();
expect(calculate.mock.calls[0][0].declaredDays).toEqual([
{ date: '2026-10-06', type: 'cp' },
]);
await expect.poll(() => root.querySelector('.plan-summary')).not.toBeNull();
expect(root.querySelector('.planning-status.info')).toBeNull();
expect(root.querySelector('#leave-balances-empty')).not.toBeNull();
const button = root.querySelector<HTMLButtonElement>('.calculate-button')!;
expect(button.disabled).toBe(false);
expect(button.getAttribute('aria-describedby')).toBe('planning-duration-estimate');
expect(localStorage.getItem('leaveBalances')).toBe('[]');
});
@@ -247,8 +249,16 @@ describe('Application Settings', () => {
});
it.each([
['negative quantity', { numberOfDays: -1 }, 'balance-quantity'],
['reversed dates', { availableDate: '2026-06-01' }, 'balance-dates'],
[
'negative quantity',
{ numberOfDays: -1 },
'A leave balance needs a non-negative whole number of days.',
],
[
'reversed dates',
{ availableDate: '2026-06-01' },
'A leave balance must become available on or before its expiry date.',
],
])('leaves readable saved inputs (%s) to planner validation', async (_, invalid, reason) => {
const saved = JSON.stringify([
{
@@ -261,10 +271,11 @@ describe('Application Settings', () => {
},
]);
localStorage.setItem('leaveBalances', saved);
await revisitApp(true);
// The test setup has no Worker, so the planner runs in process to validate the saved inputs.
await revisitApp(true, startInProcessJob);
await expect
.poll(() => fixture.nativeElement.querySelector('.reason-list')?.textContent)
.toContain(reason.replaceAll('-', ' '));
.toContain(reason);
expect(localStorage.getItem('leaveBalances')).toBe(saved);
});
@@ -339,6 +350,53 @@ describe('Application Settings', () => {
expect(await dialog.getAllHarnesses(MatButtonHarness)).toHaveLength(1);
});
it('saves planning dates before balances and recalculates only when Calculate is selected', async () => {
const root = fixture.nativeElement as HTMLElement;
const period = root.querySelector<HTMLElement>('app-user-input .planning-dates')!;
expect(
period.compareDocumentPosition(root.querySelector('.listOfDays')!) &
Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
expect(period.querySelector('legend')?.textContent).toBe('Planning period');
expect(period.querySelector('#planning-dates-help')?.textContent).toContain(
'Calculate plan',
);
const start = period.querySelector<HTMLInputElement>('input[name="planningStart"]')!;
const last = period.querySelector<HTMLInputElement>('input[name="lastPlanningDate"]')!;
start.value = '29/02/2024';
start.dispatchEvent(new Event('input'));
last.value = '08/03/2024';
last.dispatchEvent(new Event('input'));
await fixture.whenStable();
expect(calculate).toHaveBeenCalledOnce();
expect(JSON.parse(localStorage.getItem('calendarSettings.planningDates')!)).toEqual({
start: '2024-02-29',
lastPlanningDate: '2024-03-08',
});
root.querySelector<HTMLButtonElement>('.calculate-button')!.click();
await fixture.whenStable();
expect(calculate).toHaveBeenCalledTimes(2);
expect(calculate.mock.calls[1][0].horizon).toEqual({
start: '2024-02-29',
end: '2024-03-09',
});
const dialog = await openSettings();
expect(await dialog.getContentText()).not.toContain('Planning period');
const [, language] = await dialog.getAllHarnesses(MatSelectHarness);
await selectOption(language, 'Français');
expect(period.querySelector('legend')?.textContent).toBe('Période à planifier');
await dialog.close();
await revisitApp(true);
expect(fixture.nativeElement.querySelector('input[name="planningStart"]').value).toBe(
'29/02/2024',
);
expect(fixture.nativeElement.querySelector('input[name="lastPlanningDate"]').value).toBe(
'08/03/2024',
);
});
it('supports keyboard theme selection and moves focus into the dialog', async () => {
const dialog = await openSettings();
const [theme] = await dialog.getAllHarnesses(MatSelectHarness);
@@ -414,7 +472,7 @@ describe('Application Settings', () => {
await (await dialog.getHarness(MatSlideToggleHarness)).check();
expect(localStorage.getItem('calendarSettings.showWeekNumbers')).toBe('true');
expect(localStorage.getItem('leaveBalances')).toBe(savedBalances);
expect(localStorage.getItem('vacationRules')).toBe('[]');
expect(localStorage.getItem('vacationRules')).toBe('{"version":1,"rules":[]}');
expect(localStorage.getItem('unrelated.entry')).toBe('keep this value');
expect(fixture.nativeElement.querySelectorAll('.week-number').length).toBeGreaterThan(
0,
@@ -443,7 +501,7 @@ describe('Application Settings', () => {
TestBed.resetTestingModule();
await createApp();
expect(localStorage.getItem('leaveBalances')).toBe(savedBalances);
expect(localStorage.getItem('vacationRules')).toBe('[]');
expect(localStorage.getItem('vacationRules')).toBe('{"version":1,"rules":[]}');
expect(localStorage.getItem('unrelated.entry')).toBe('keep this value');
expect(document.body.classList.contains('dark-mode')).toBe(true);
expect(
-10
View File
@@ -1,10 +0,0 @@
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering, withRoutes } from '@angular/ssr';
import { appConfig } from './app.config';
import { serverRoutes } from './app.routes.server';
const serverConfig: ApplicationConfig = {
providers: [provideServerRendering(withRoutes(serverRoutes))],
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
-2
View File
@@ -6,13 +6,11 @@ import {
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideZonelessChangeDetection(),
provideRouter(routes),
provideClientHydration(withEventReplay()),
],
};
+5 -1
View File
@@ -22,7 +22,11 @@
</header>
<main class="planner-layout">
<section class="configuration-panel" aria-labelledby="leave-settings-title">
<section
class="configuration-panel"
cdkScrollable
aria-labelledby="leave-settings-title"
>
<app-user-input></app-user-input>
</section>
<section class="results-panel" aria-labelledby="planning-results-title">
-8
View File
@@ -1,8 +0,0 @@
import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{
path: '**',
renderMode: RenderMode.Client,
},
];
+12 -2
View File
@@ -82,7 +82,8 @@ app-calendar-year {
}
.configuration-panel {
padding: 1.25rem;
--panel-padding: 1.25rem;
padding: var(--panel-padding);
background: var(--ui-card-bg);
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-lg);
@@ -106,6 +107,15 @@ app-calendar-year {
.planner-layout {
grid-template-columns: clamp(26rem, 34%, 40rem) minmax(0, 1fr);
}
// Stays in view while the results scroll, and scrolls inside when taller than the screen.
// The 9rem leaves room for the header, which scrolls away, so that the panel fits on first load.
.configuration-panel {
position: sticky;
top: 1rem;
max-height: calc(100dvh - 9rem);
overflow-y: auto;
}
}
@media (max-width: 35rem) {
@@ -118,6 +128,6 @@ app-calendar-year {
}
.configuration-panel {
padding: 1rem;
--panel-padding: 1rem;
}
}
+27 -1
View File
@@ -1,6 +1,8 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { ScrollDispatcher } from '@angular/cdk/scrolling';
import { App } from './app';
import { TranslationService } from './services/translation-service';
describe('App', () => {
beforeEach(async () => {
@@ -10,6 +12,11 @@ describe('App', () => {
}).compileComponents();
});
afterEach(() => {
localStorage.removeItem('app.language');
document.documentElement.lang = 'en';
});
it('should create the app', () => {
const fixture = TestBed.createComponent(App);
const app = fixture.componentInstance;
@@ -20,7 +27,26 @@ describe('App', () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('vac-optimizer');
expect(compiled.querySelector('h1')?.textContent).toContain('VacOptimizer');
});
it('registers the scrolling configuration panel so that dragging a rule can auto-scroll it', () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const panel = fixture.nativeElement.querySelector('.configuration-panel') as HTMLElement;
const scrollables = TestBed.inject(ScrollDispatcher).getAncestorScrollContainers(
panel.querySelector('app-rules-panel')!,
);
expect(scrollables.map((scrollable) => scrollable.getElementRef().nativeElement)).toEqual([
panel,
]);
});
it('keeps the document language in sync with the selected language', () => {
TestBed.createComponent(App);
TestBed.inject(TranslationService).setLanguage('fr');
TestBed.tick();
expect(document.documentElement.lang).toBe('fr-FR');
});
it('does not mount the normal planner shell on the benchmark route', () => {
+23 -4
View File
@@ -1,4 +1,12 @@
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import {
ChangeDetectionStrategy,
Component,
DOCUMENT,
effect,
inject,
signal,
} from '@angular/core';
import { CdkScrollable } from '@angular/cdk/scrolling';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { provideNativeDateAdapter } from '@angular/material/core';
import { UserInput } from './components/user-input/user-input';
@@ -17,7 +25,15 @@ function isBenchmarkUrl(url: string): boolean {
@Component({
selector: 'app-root',
imports: [MatDatepickerModule, UserInput, CalendarYear, MatButton, MatIcon, RouterOutlet],
imports: [
CdkScrollable,
MatDatepickerModule,
UserInput,
CalendarYear,
MatButton,
MatIcon,
RouterOutlet,
],
templateUrl: './app.html',
styleUrl: './app.scss',
providers: [provideNativeDateAdapter()],
@@ -26,14 +42,17 @@ function isBenchmarkUrl(url: string): boolean {
export class App {
private readonly router = inject(Router);
private readonly dialog = inject(MatDialog);
protected readonly tr = inject(TranslationService).tr;
protected readonly title = signal('vac-optimizer');
private readonly document = inject(DOCUMENT);
private readonly translations = inject(TranslationService);
protected readonly tr = this.translations.tr;
protected readonly title = signal('VacOptimizer');
protected readonly showPlanner = signal(
!isBenchmarkUrl(typeof window !== 'undefined' ? window.location.pathname : this.router.url),
);
constructor() {
inject(ThemeService);
effect(() => (this.document.documentElement.lang = this.translations.locale()));
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd)
this.showPlanner.set(!isBenchmarkUrl(event.urlAfterRedirects));
@@ -0,0 +1,63 @@
import {
BenchmarkMeasurement,
benchmarkSummaryHeader,
benchmarkSummaryRow,
budgetViolations,
} from './leave-planner-benchmark';
const measure = (scenario: string, planningMs: number) =>
({ scenario, planningMs }) as BenchmarkMeasurement;
describe('benchmark budget gate', () => {
const multipliers = { a: 2 };
it('accepts a mean within multiplier x calibration', () => {
expect(budgetViolations([measure('a', 150), measure('a', 250)], 100, multipliers)).toEqual(
[],
);
});
it('reports measured time, budget, multiplier and calibration when over budget', () => {
const [message] = budgetViolations(
[measure('a', 300), measure('a', 320)],
100,
multipliers,
);
expect(message).toContain('a:');
expect(message).toContain('measured 310.0 ms');
expect(message).toContain('budget 200.0 ms');
expect(message).toContain('multiplier 2');
expect(message).toContain('calibration 100.0 ms');
});
it('fails a scenario without a multiplier', () => {
expect(budgetViolations([measure('new', 1)], 100, multipliers)).toEqual([
'new: no budget multiplier defined',
]);
});
});
describe('benchmark summary table', () => {
const runs = (planningMs: number[]) =>
planningMs.map(
(ms, index) =>
({
scenario: 'a',
planningMs: ms,
outcome: 'Plan',
lastCompletedStage: 'dates',
placements: 3,
deterministic: index ? 'yes' : 'baseline',
}) as BenchmarkMeasurement,
);
it('aligns rows with the header', () => {
const [header, separator] = benchmarkSummaryHeader().split('\n');
const row = benchmarkSummaryRow(runs([150, 250]), 100, { a: 2 });
expect(row).toHaveLength(header.length);
expect(separator).toHaveLength(header.length);
expect(row).toContain('0.15 / 0.25 s');
expect(row).toContain('Plan (dates)');
expect(row).toMatch(/\| ok +\|$/);
});
it('marks scenarios over budget or without a budget', () => {
expect(benchmarkSummaryRow(runs([300, 320]), 100, { a: 2 })).toMatch(/\| OVER +\|$/);
expect(benchmarkSummaryRow(runs([1]), 100, {})).toMatch(/\| no budget \|$/);
});
});
+112 -70
View File
@@ -1,15 +1,22 @@
import { vi } from 'vitest';
import { createPlanningCalculation } from '../services/leave-planner.service';
import { vi } from '../../testing/vitest-compat';
import { createInProcessCalculation } from '../../testing/planning-jobs';
import { calculatePlanningAsyncInternal } from '../services/frozen-engine/leave-planner.core.calibration.mjs';
import { startInProcessJob } from '../services/leave-planner.in-process-job';
import {
BENCHMARK_BUDGET_MULTIPLIERS,
type BenchmarkMeasurement,
benchmarkReport,
benchmarkScenarios,
benchmarkSummaryHeader,
benchmarkSummaryRow,
budgetViolations,
runLeavePlannerBenchmark,
} from './leave-planner-benchmark';
describe('leave planner benchmark protocol', () => {
beforeEach(() => vi.setSystemTime(new Date('2024-01-01T12:00:00Z')));
afterEach(() => vi.useRealTimers());
// Warm-up and two repetitions include complete trace delivery after planning.
// Warm-up and two repetitions include explanation delivery after planning.
it('keeps seven deterministic scenarios including two and three years and a later earned consumer', async () => {
const scenarios = benchmarkScenarios();
expect(scenarios).toHaveLength(7);
@@ -41,73 +48,108 @@ describe('leave planner benchmark protocol', () => {
String(rttRule.startDate) <= String(cpRule.endDate),
).toBe(true);
const chain = scenarios.find((scenario) => scenario.name === 'chained earned entitlements');
expect(chain?.request.rules?.map((rule) => rule.id)).toEqual([
'wednesday-holidays',
'thursday-consumer',
]);
expect(
chain?.request.rules
?.filter(({ type }) => type !== 'optimization')
.map((rule) => rule.id),
).toEqual(['wednesday-holidays', 'thursday-consumer']);
const browserWindow = globalThis.window;
vi.stubGlobal('window', undefined);
try {
const typedOutcome = await createPlanningCalculation(typedObligations!.request).outcome;
expect(typedOutcome.kind).toBe('Plan');
if (typedOutcome.kind === 'Plan') {
expect(
typedOutcome.placements.filter((placement) =>
placement.ruleIds.includes('cp-window'),
),
).toHaveLength(2);
expect(
typedOutcome.placements.filter((placement) =>
placement.ruleIds.includes('rtt-window'),
),
).toHaveLength(2);
}
const measurements = await runLeavePlannerBenchmark(2);
for (const [name, placements] of [
['two years', 60],
['three years', 90],
] as const) {
const longer = measurements.filter((measurement) => measurement.scenario === name);
expect(longer).toHaveLength(2);
expect(longer.map((item) => item.outcome)).toEqual(['Plan', 'Plan']);
expect(longer.map((item) => item.lastCompletedStage)).toEqual(['dates', 'dates']);
expect(longer.map((item) => item.placements)).toEqual([placements, placements]);
expect(longer.map((item) => item.deterministic)).toEqual(['baseline', 'yes']);
expect(longer.map((item) => item.traceStatus)).toEqual(['ready', 'ready']);
expect(longer[0].traceCandidates).toBeGreaterThan(0);
}
const chained = measurements.find(
(measurement) => measurement.scenario === 'chained earned entitlements',
);
const loaded = measurements.filter(
(measurement) => measurement.scenario === 'loaded year',
);
expect(chained?.outcome).toBe('Plan');
expect(chained?.placements).toBeGreaterThanOrEqual(3);
expect(loaded).toHaveLength(2);
expect(loaded[0].outcome).toBe('Plan');
expect(loaded[0].deterministic).toBe('baseline');
expect(loaded[1].deterministic).toBe('yes');
expect(loaded[0].planningMs).toBeGreaterThanOrEqual(0);
expect(loaded[0].traceDeliveryMs).toBeGreaterThanOrEqual(0);
expect(loaded[0].planningWorkMs).toBeGreaterThanOrEqual(0);
expect(loaded[0].planningWorkMs).toBeLessThanOrEqual(loaded[0].planningMs);
expect(loaded[0].traceCaptureMs).toBeGreaterThan(0);
expect(loaded[0].traceMaterializationMs).toBeGreaterThanOrEqual(0);
expect(loaded[0].maxUiDelayMs).toBeGreaterThanOrEqual(0);
expect(loaded[0].wallMs).toBeGreaterThanOrEqual(
loaded[0].preparationMs + loaded[0].planningMs + loaded[0].traceDeliveryMs,
);
expect(loaded[0].traceStatus).toBe('ready');
expect(loaded[0].traceCandidates).toBeGreaterThan(0);
const report = benchmarkReport(measurements);
expect(report.split('\n')).toHaveLength(15);
expect(report).toContain('planning_ms\ttrace_delivery_ms');
expect(report).toContain('planning_work_ms\ttrace_capture_ms');
expect(report).toContain('\tbaseline\t');
} finally {
vi.stubGlobal('window', browserWindow);
const typedOutcome = await createInProcessCalculation(typedObligations!.request).outcome;
expect(typedOutcome.kind).toBe('Plan');
if (typedOutcome.kind === 'Plan') {
expect(
typedOutcome.placements.filter((placement) =>
placement.ruleIds.includes('cp-window'),
),
).toHaveLength(2);
expect(
typedOutcome.placements.filter((placement) =>
placement.ruleIds.includes('rtt-window'),
),
).toHaveLength(2);
}
}, 90_000);
// Calibration engine (frozen at a871f8f) on 'two years', best of three: the runner-speed yardstick.
const calibrationRequest = scenarios.find((item) => item.name === 'two years')!.request;
const calibrate = async () => {
let best = Infinity;
for (let run = 0; run < 3; run++) {
const request = structuredClone(calibrationRequest);
const start = performance.now();
await calculatePlanningAsyncInternal({
...request,
calculationDate: '2024-01-01',
});
best = Math.min(best, performance.now() - start);
}
return best;
};
const calibrationBefore = await calibrate();
// Direct stdout writes show each row as soon as its scenario finishes.
const print = (text: string) => process.stdout.write(`${text}\n`);
print(
`\nCalibration: frozen engine on "two years", best of 3 = ${calibrationBefore.toFixed(1)} ms` +
'\nBudget = limit x calibration; ratio = mean / calibration.\n',
);
print(benchmarkSummaryHeader());
const scenarioRows: BenchmarkMeasurement[][] = [];
const measurements = await runLeavePlannerBenchmark(
2,
(rows) => {
scenarioRows.push(rows);
print(benchmarkSummaryRow(rows, calibrationBefore));
},
startInProcessJob,
);
// Load that starts after the first calibration slows the scenarios but not the yardstick;
// calibrating again and judging against the slower value absorbs it. Never tighter than before.
const calibrationAfter = await calibrate();
const calibrationMs = Math.max(calibrationBefore, calibrationAfter);
if (calibrationMs !== calibrationBefore) {
print(
`\nCalibration after the protocol = ${calibrationAfter.toFixed(1)} ms; budgets use the slower: ${calibrationMs.toFixed(1)} ms\n`,
);
print(benchmarkSummaryHeader());
for (const rows of scenarioRows) print(benchmarkSummaryRow(rows, calibrationMs));
}
for (const [name, placements] of [
['two years', 60],
['three years', 90],
] as const) {
const longer = measurements.filter((measurement) => measurement.scenario === name);
expect(longer).toHaveLength(2);
expect(longer.map((item) => item.outcome)).toEqual(['Plan', 'Plan']);
expect(longer.map((item) => item.lastCompletedStage)).toEqual(['dates', 'dates']);
expect(longer.map((item) => item.placements)).toEqual([placements, placements]);
expect(longer.map((item) => item.deterministic)).toEqual(['baseline', 'yes']);
}
const chained = measurements.find(
(measurement) => measurement.scenario === 'chained earned entitlements',
);
const loaded = measurements.filter((measurement) => measurement.scenario === 'loaded year');
expect(chained?.outcome).toBe('Plan');
expect(chained?.placements).toBeGreaterThanOrEqual(3);
expect(loaded).toHaveLength(2);
expect(loaded[0].outcome).toBe('Plan');
expect(loaded[0].deterministic).toBe('baseline');
expect(loaded[1].deterministic).toBe('yes');
expect(loaded[0].planningMs).toBeGreaterThanOrEqual(0);
expect(loaded[0].planningWorkMs).toBeGreaterThanOrEqual(0);
expect(loaded[0].planningWorkMs).toBeLessThanOrEqual(loaded[0].planningMs);
expect(loaded[0].maxUiDelayMs).toBeGreaterThanOrEqual(0);
expect(loaded[0].wallMs).toBeGreaterThanOrEqual(
loaded[0].preparationMs + loaded[0].planningMs,
);
const report = benchmarkReport(measurements);
print(`\nRaw report (TSV):\n${report}\n`);
expect(report.split('\n')).toHaveLength(15);
expect(report).toContain('planning_ms\twall_ms');
expect(report).toContain('planning_work_ms\tpeak_main_thread_heap_bytes');
expect(report).toContain('\tbaseline\t');
const violations = budgetViolations(
measurements,
calibrationMs,
BENCHMARK_BUDGET_MULTIPLIERS,
);
if (violations.length) throw new Error(`Benchmark over budget:\n${violations.join('\n')}`);
}, 210_000);
});
+133 -41
View File
@@ -2,8 +2,9 @@ import {
createPlanningCalculation,
PlanningOutcome,
PlanningRequest,
PlanningTrace,
type WorkerJobFactory,
} from '../services/leave-planner.service';
import { createOptimizationPresetRules } from '../services/rule-service';
export interface BenchmarkScenario {
name: string;
@@ -15,21 +16,15 @@ export interface BenchmarkMeasurement {
repetition: number;
preparationMs: number;
planningMs: number;
traceDeliveryMs: number;
maxUiDelayMs: number;
/** Chromium's main-thread heap only; worker memory needs a separate browser profile. */
peakMainThreadHeapBytes?: number;
planningWorkMs?: number;
traceCaptureMs?: number;
traceMaterializationMs?: number;
traceTransferMs?: number;
wallMs: number;
outcome: PlanningOutcome['kind'];
lastCompletedStage?: string;
placements: number;
deterministic: 'baseline' | 'yes' | 'no';
traceStatus: PlanningTrace['status'] | 'not-produced';
traceCandidates: number;
}
const balance = (
@@ -47,7 +42,8 @@ const balance = (
export function benchmarkScenarios(): BenchmarkScenario[] {
const horizon = { start: '2024-01-01', end: '2025-01-01' };
return [
const presets = createOptimizationPresetRules();
const scenarios: BenchmarkScenario[] = [
{
name: 'representative year',
request: {
@@ -96,7 +92,7 @@ export function benchmarkScenarios(): BenchmarkScenario[] {
dayOfWeek: 3,
placeDays: 1,
placeType: 'cp',
placement: 'after',
placement: 'before',
rewardDays: 1,
rewardType: 'rtt',
},
@@ -107,7 +103,7 @@ export function benchmarkScenarios(): BenchmarkScenario[] {
dayOfWeek: 4,
placeDays: 1,
placeType: 'rtt',
placement: 'before',
placement: 'after',
rewardDays: 0,
},
],
@@ -169,6 +165,13 @@ export function benchmarkScenarios(): BenchmarkScenario[] {
}),
),
];
return scenarios.map((scenario) => ({
...scenario,
request: {
...scenario.request,
rules: [presets[0], ...scenario.request.rules, ...presets.slice(1)],
},
}));
}
function resultSummary(outcome: PlanningOutcome): {
@@ -191,32 +194,44 @@ function resultSummary(outcome: PlanningOutcome): {
return { outcome: outcome.kind, placements: 0 };
}
export async function runLeavePlannerBenchmark(repetitions = 1): Promise<BenchmarkMeasurement[]> {
export async function runLeavePlannerBenchmark(
repetitions = 1,
onScenario?: (measurements: BenchmarkMeasurement[]) => void,
startJob?: WorkerJobFactory,
): Promise<BenchmarkMeasurement[]> {
const scenarios = benchmarkScenarios();
for (const scenario of scenarios) await warmUpScenario(scenario);
for (const scenario of scenarios) await warmUpScenario(scenario, startJob);
const measurements: BenchmarkMeasurement[] = [];
for (const scenario of scenarios) {
const scenarioMeasurements: BenchmarkMeasurement[] = [];
let baseline: string | undefined;
for (let repetition = 1; repetition <= repetitions; repetition++) {
const result = await measureRepetition(scenario, repetition, baseline);
measurements.push(result.measurement);
const result = await measureRepetition(scenario, repetition, baseline, startJob);
scenarioMeasurements.push(result.measurement);
baseline ??= result.stable;
}
measurements.push(...scenarioMeasurements);
onScenario?.(scenarioMeasurements);
}
return measurements;
}
async function warmUpScenario(scenario: BenchmarkScenario): Promise<void> {
const calculation = createPlanningCalculation(structuredClone(scenario.request));
async function warmUpScenario(
scenario: BenchmarkScenario,
startJob: WorkerJobFactory | undefined,
): Promise<void> {
const calculation = createPlanningCalculation(structuredClone(scenario.request), startJob);
await calculation.outcome;
await calculation.trace;
await calculation.explanation;
await calculation.timings;
}
async function measureRepetition(
scenario: BenchmarkScenario,
repetition: number,
baseline: string | undefined,
startJob: WorkerJobFactory | undefined,
): Promise<{ measurement: BenchmarkMeasurement; stable: string }> {
const wallStart = performance.now();
let lastTick = wallStart;
@@ -238,27 +253,14 @@ async function measureRepetition(
const request = structuredClone(scenario.request);
const preparationMs = performance.now() - preparationStart;
const calculationStart = performance.now();
const calculation = createPlanningCalculation(request);
const calculation = createPlanningCalculation(request, startJob);
const outcome = await calculation.outcome;
const planningMs = performance.now() - calculationStart;
const traceStart = performance.now();
const trace = await calculation.trace;
const traceDeliveryMs = performance.now() - traceStart;
const timings = await calculation.timings;
const summary = resultSummary(outcome);
const stable = JSON.stringify(outcome);
const deterministic =
baseline === undefined ? 'baseline' : stable === baseline ? 'yes' : 'no';
const traceCandidates =
trace?.phases.reduce(
(total, phase) =>
total +
phase.decisions.reduce(
(decisionTotal, decision) => decisionTotal + decision.candidates.length,
0,
),
0,
) ?? 0;
const wallMs = performance.now() - wallStart;
measureDelay();
return {
@@ -267,15 +269,12 @@ async function measureRepetition(
repetition,
preparationMs,
planningMs,
traceDeliveryMs,
maxUiDelayMs,
peakMainThreadHeapBytes,
...timings,
wallMs,
...summary,
deterministic,
traceStatus: trace?.status ?? 'not-produced',
traceCandidates,
},
stable,
};
@@ -286,7 +285,7 @@ async function measureRepetition(
export function benchmarkReport(measurements: BenchmarkMeasurement[]): string {
const header =
'scenario\trepetition\tpreparation_ms\tplanning_ms\ttrace_delivery_ms\twall_ms\toutcome\tlast_stage\tplacements\tdeterministic\ttrace_status\ttrace_candidates\tmax_ui_delay_ms\tplanning_work_ms\ttrace_capture_ms\ttrace_materialization_ms\ttrace_transfer_ms\tpeak_main_thread_heap_bytes';
'scenario\trepetition\tpreparation_ms\tplanning_ms\twall_ms\toutcome\tlast_stage\tplacements\tdeterministic\tmax_ui_delay_ms\tplanning_work_ms\tpeak_main_thread_heap_bytes';
return [
header,
...measurements.map((item) =>
@@ -295,21 +294,114 @@ export function benchmarkReport(measurements: BenchmarkMeasurement[]): string {
item.repetition,
item.preparationMs.toFixed(1),
item.planningMs.toFixed(1),
item.traceDeliveryMs.toFixed(1),
item.wallMs.toFixed(1),
item.outcome,
item.lastCompletedStage ?? '',
item.placements,
item.deterministic,
item.traceStatus,
item.traceCandidates,
item.maxUiDelayMs.toFixed(1),
item.planningWorkMs?.toFixed(1) ?? '',
item.traceCaptureMs?.toFixed(1) ?? '',
item.traceMaterializationMs?.toFixed(1) ?? '',
item.traceTransferMs?.toFixed(1) ?? '',
item.peakMainThreadHeapBytes ?? '',
].join('\t'),
),
].join('\n');
}
// About 1.5x the development machine's ratios to the calibration run after #321.
export const BENCHMARK_BUDGET_MULTIPLIERS: Record<string, number> = {
'representative year': 0.1,
'typed obligations': 0.1,
'chained earned entitlements': 0.05,
'deliberate conflict': 0.05,
'loaded year': 1.25,
'two years': 0.25,
'three years': 0.75,
};
/** One message per scenario whose mean planning time exceeds multiplier x calibration, or that has no multiplier. */
export function budgetViolations(
measurements: BenchmarkMeasurement[],
calibrationMs: number,
multipliers: Record<string, number> = BENCHMARK_BUDGET_MULTIPLIERS,
): string[] {
const byScenario = new Map<string, number[]>();
for (const { scenario, planningMs } of measurements)
byScenario.set(scenario, [...(byScenario.get(scenario) ?? []), planningMs]);
const violations: string[] = [];
for (const [scenario, times] of byScenario) {
const mean = average(times);
const multiplier = multipliers[scenario];
if (multiplier === undefined) {
violations.push(`${scenario}: no budget multiplier defined`);
continue;
}
const budget = multiplier * calibrationMs;
if (mean > budget)
violations.push(
`${scenario}: measured ${mean.toFixed(1)} ms > budget ${budget.toFixed(1)} ms (multiplier ${multiplier} x calibration ${calibrationMs.toFixed(1)} ms)`,
);
}
return violations;
}
function average(values: number[]): number {
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
// Fixed widths keep rows printed as each scenario finishes aligned with the header.
const SUMMARY_COLUMNS: [title: string, width: number, alignRight: boolean][] = [
['Scenario', 27, false],
['Planning (runs)', 17, true],
['Mean', 9, true],
['Budget', 9, true],
['Ratio', 6, true],
['Limit', 6, true],
['Outcome', 16, false],
['Placements', 10, true],
['Deterministic', 13, false],
['Status', 9, false],
];
function summaryLine(cells: string[]): string {
return `| ${cells
.map((cell, index) => {
const [, width, alignRight] = SUMMARY_COLUMNS[index];
return alignRight ? cell.padStart(width) : cell.padEnd(width);
})
.join(' | ')} |`;
}
/** Markdown table header for {@link benchmarkSummaryRow}. */
export function benchmarkSummaryHeader(): string {
return [
summaryLine(SUMMARY_COLUMNS.map(([title]) => title)),
`|${SUMMARY_COLUMNS.map(([, width, alignRight]) => (alignRight ? `${'-'.repeat(width + 1)}:` : `:${'-'.repeat(width + 1)}`)).join('|')}|`,
].join('\n');
}
/** One aligned table row for one scenario's measured repetitions, judged like {@link budgetViolations}. */
export function benchmarkSummaryRow(
scenarioMeasurements: BenchmarkMeasurement[],
calibrationMs: number,
multipliers: Record<string, number> = BENCHMARK_BUDGET_MULTIPLIERS,
): string {
const [first] = scenarioMeasurements;
const seconds = (ms: number) => (ms / 1000).toFixed(2);
const mean = average(scenarioMeasurements.map(({ planningMs }) => planningMs));
const multiplier = multipliers[first.scenario];
const budget = multiplier === undefined ? undefined : multiplier * calibrationMs;
return summaryLine([
first.scenario,
`${scenarioMeasurements.map(({ planningMs }) => seconds(planningMs)).join(' / ')} s`,
`${seconds(mean)} s`,
budget === undefined ? '-' : `${seconds(budget)} s`,
(mean / calibrationMs).toFixed(2),
multiplier === undefined ? '-' : String(multiplier),
first.lastCompletedStage ? `${first.outcome} (${first.lastCompletedStage})` : first.outcome,
String(first.placements),
scenarioMeasurements.slice(1).every(({ deterministic }) => deterministic === 'yes')
? 'yes'
: 'no',
budget === undefined ? 'no budget' : mean > budget ? 'OVER' : 'ok',
]);
}
@@ -0,0 +1,138 @@
// Rules shared by the planning page, the date comparison and the planning criteria. Component
// styles are encapsulated, so each of them @uses this file instead of inheriting the page's rules.
.sr-only {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
h2,
h3,
h4,
h5,
p {
margin: 0;
}
h2 {
font-size: clamp(1.5rem, 2.2vw, 2rem);
line-height: 1.2;
text-wrap: balance;
}
h3 {
font-size: 1.125rem;
}
h4 {
font-size: 1rem;
}
button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
min-width: 2.75rem;
min-height: 2.75rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--mat-sys-outline);
border-radius: var(--ui-radius-sm);
background: var(--ui-card-bg);
color: var(--mat-sys-primary);
font: inherit;
font-size: 0.875rem;
cursor: pointer;
transition: background-color 150ms ease;
&:hover:not(:disabled),
&[aria-pressed='true'] {
background: var(--ui-panel-bg);
}
&:disabled {
opacity: 0.45;
cursor: not-allowed;
}
&[aria-disabled='true'] {
opacity: 0.45;
cursor: not-allowed;
}
}
summary {
min-height: 2.75rem;
padding: 0.75rem;
font-weight: 500;
cursor: pointer;
}
summary:focus-visible {
outline: 3px solid var(--mat-sys-primary);
outline-offset: 2px;
}
.technical-details {
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-sm);
> dl,
> div {
padding: 0.75rem;
}
}
.impact-table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
font-size: 0.875rem;
th,
td {
padding: 0.75rem 0.5rem;
border-bottom: 1px solid var(--ui-border);
text-align: center;
overflow-wrap: anywhere;
}
th:first-child {
width: 52%;
text-align: start;
}
td {
font-size: 1.125rem;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
small {
display: block;
margin-top: 0.25rem;
font-size: 0.8125rem;
font-weight: 400;
color: var(--ui-text-secondary);
}
}
.inline-error {
padding: 0.75rem;
border-inline-start: 4px solid var(--ui-error-text);
background: var(--ui-error-bg);
color: var(--ui-error-text);
}
.calculation-content {
display: grid;
gap: 1.5rem;
min-width: 0;
}
.calculation-intro {
color: var(--ui-text-secondary);
font-size: 0.875rem;
}
.decisive-row {
background: var(--ui-panel-bg);
}
.decisive-label {
display: inline-block;
margin-top: 0.375rem;
padding: 0.125rem 0.375rem;
border: 1px solid var(--mat-sys-primary);
border-radius: var(--ui-radius-sm);
color: var(--mat-sys-primary);
font-size: 0.75rem;
font-weight: 600;
}
@@ -29,13 +29,12 @@
} @else {
@let dayTooltip = getDayTooltip(day);
@let dateKey = getDateKey(day);
@let status = getStatus(day);
@let declaredType = getDeclaredType(dateKey);
@let previewed = declarationPreview?.dates?.has(dateKey);
<button
type="button"
[attr.data-date]="dateKey"
[class.past]="day < getNow()"
[class.past]="dateKey < today"
[class.start]="selectedDates.isStart(day)"
[class.end]="selectedDates.isEnd(day)"
[class.selected]="selectedDates.isSelected(day)"
@@ -45,18 +44,6 @@
[class.declared]="!!declaredType"
[class.declaration-preview]="previewed"
[class.declaration-erase]="previewed && !declaredType"
[class.eligible]="status?.kind === 'eligible'"
[class.ineligible]="status?.kind === 'ineligible'"
[class.chosen]="status?.kind === 'chosen'"
[class.evaluated-rejected]="status?.kind === 'evaluated-rejected'"
[class.pruned]="status?.kind === 'pruned'"
[class.not-examined]="status?.kind === 'not-examined'"
[class.change-added]="status?.change === 'added'"
[class.change-moved-from]="status?.change === 'moved-from'"
[class.change-moved-to]="status?.change === 'moved-to'"
[class.change-removed]="status?.change === 'removed'"
[class.change-shared]="status?.change === 'shared'"
[class.change-unchanged]="status?.change === 'unchanged'"
[class]="getDayClasses(day)"
class="day number"
[disabled]="isDateDisabled(day)"
@@ -70,16 +57,6 @@
(click)="dateSelected.emit(dateKey)"
>
<span>{{ day.getDate() }}</span>
@if (status) {
<small class="status-marker" aria-hidden="true">{{
getStatusMarker(day)
}}</small>
@if (status.hypotheticalLabel) {
<small class="hypothetical-marker" aria-hidden="true">{{
getHypotheticalMarker(status)
}}</small>
}
}
</button>
}
}
@@ -108,31 +108,6 @@
}
}
.status-marker {
position: absolute;
inset-block-start: -0.35rem;
inset-inline-end: -0.2rem;
min-width: 0.85rem;
font-size: 0.65rem;
font-weight: 800;
line-height: 1;
background: var(--ui-card-bg, #fff);
border-radius: 999px;
}
.hypothetical-marker {
position: absolute;
inset-block-end: -0.35rem;
inset-inline-start: -0.2rem;
min-width: 1.25rem;
font-size: 0.55rem;
font-weight: 800;
line-height: 1;
background: var(--ui-card-bg, #fff);
border: 1px dashed currentColor;
border-radius: 999px;
}
.current {
outline: 2px solid var(--today-border-color);
outline-offset: -2px;
@@ -142,43 +117,6 @@
box-shadow: inset 0 -3px var(--today-border-color);
}
.eligible,
.chosen {
border-block-end: 3px solid var(--ui-success-text, #174d26);
}
.ineligible,
.evaluated-rejected {
text-decoration: line-through;
text-decoration-thickness: 2px;
}
.pruned {
border: 2px dotted currentColor;
}
.not-examined {
border: 2px dashed currentColor;
}
.change-added,
.change-moved-to {
box-shadow: inset 0 -3px var(--ui-success-text, #174d26);
}
.change-moved-from,
.change-removed {
box-shadow: inset 0 3px var(--ui-error-text, #8b1a1a);
}
.change-shared {
box-shadow: inset 3px 0 var(--today-border-color, #1976d2);
}
.change-unchanged {
box-shadow: inset 0 0 0 1px currentColor;
}
.selected {
cursor: pointer;
}
@@ -1,5 +1,6 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { SelectedDates } from '../../services/calendar-service';
import { CalendarMonth } from './calendar-month';
describe('CalendarMonth', () => {
@@ -20,4 +21,20 @@ describe('CalendarMonth', () => {
it('should create', () => {
expect(component).toBeTruthy();
});
it('styles only the dates before the given today as past', () => {
const monthFixture = TestBed.createComponent(CalendarMonth);
monthFixture.componentRef.setInput('monthIndex', 9);
monthFixture.componentRef.setInput('year', 2026);
monthFixture.componentRef.setInput('selectedDates', new SelectedDates());
monthFixture.componentRef.setInput('today', '2026-10-18');
monthFixture.detectChanges();
const button = (date: string) =>
(monthFixture.nativeElement as HTMLElement).querySelector(
`button[data-date="${date}"]`,
)!;
expect(button('2026-10-17').classList).toContain('past');
expect(button('2026-10-18').classList).not.toContain('past');
expect(button('2026-10-19').classList).not.toContain('past');
});
});
@@ -10,21 +10,10 @@ import {
import { CalendarService, Month, SelectedDates } from '../../services/calendar-service';
import { MatTooltip } from '@angular/material/tooltip';
import { CalendarSettingsService } from '../../services/calendar-settings-service';
import { DateCacheService } from '../../services/date-cache.service';
import { TranslationService } from '../../services/translation-service';
import { isWorkingPlanningDate } from '../../services/declared-non-working-days';
import type { LeaveType } from '../../services/leave-planner.service';
export interface CalendarDayStatus {
kind: 'eligible' | 'ineligible' | 'chosen' | 'evaluated-rejected' | 'pruned' | 'not-examined';
label: string;
reason?: string;
hypotheticalLabel?: string;
hypotheticalReason?: string;
change?: 'added' | 'moved-from' | 'moved-to' | 'removed' | 'shared' | 'unchanged';
changeLabel?: string;
}
export interface DeclarationPreview {
dates: ReadonlySet<string>;
type: LeaveType | null;
@@ -39,7 +28,6 @@ export interface DeclarationPreview {
})
export class CalendarMonth implements OnInit {
protected calendarSettingsService = inject(CalendarSettingsService);
private dateCache = inject(DateCacheService);
protected translationService = inject(TranslationService);
@Input({ required: true })
@@ -52,11 +40,6 @@ export class CalendarMonth implements OnInit {
return this.translationService.tr;
}
// Use DateCacheService instead of creating Date objects
getNow(): Date {
return this.dateCache.getNow();
}
currentMonth: Date = new Date();
weeksInAMonth: Month = [];
@@ -66,6 +49,9 @@ export class CalendarMonth implements OnInit {
@Input({ required: true })
selectedDates!: SelectedDates;
@Input({ required: true })
today!: string;
@Input()
horizonStart?: string;
@@ -112,9 +98,6 @@ export class CalendarMonth implements OnInit {
@Input()
explainedPeriod?: { start: string; end: string };
@Input()
dateStatuses: Readonly<Record<string, CalendarDayStatus>> = {};
@Output()
readonly dateSelected = new EventEmitter<string>();
@@ -134,10 +117,6 @@ export class CalendarMonth implements OnInit {
);
}
getStatus(day: Date): CalendarDayStatus | undefined {
return this.dateStatuses[this.getDateKey(day)];
}
isInExplainedPeriod(day: Date): boolean {
const date = this.getDateKey(day);
return (
@@ -147,44 +126,6 @@ export class CalendarMonth implements OnInit {
);
}
getStatusMarker(day: Date): string {
switch (this.getStatus(day)?.change) {
case 'added':
return '+';
case 'moved-from':
return '←';
case 'moved-to':
return '→';
case 'removed':
return '−';
case 'shared':
return '≈';
case 'unchanged':
return '=';
}
switch (this.getStatus(day)?.kind) {
case 'chosen':
case 'eligible':
return '✓';
case 'ineligible':
return '×';
case 'evaluated-rejected':
return '−';
case 'pruned':
return '⌁';
case 'not-examined':
return '?';
default:
return '';
}
}
getHypotheticalMarker(status: CalendarDayStatus): string {
return status.hypotheticalLabel === this.translationService.tr().planning.eligible
? '~✓'
: '~×';
}
getDayAriaLabel(day: Date, tooltip: string | null = this.getDayTooltip(day)): string {
const locale = this.translationService.locale();
if (!this.dayFormatter || locale !== this.dayFormatterLocale) {
@@ -239,33 +180,15 @@ export class CalendarMonth implements OnInit {
getDayTooltip(day: Date): string | null {
const previewed = this.declarationPreview?.dates.has(this.getDateKey(day));
const tooltips: string[] = this.selectedDates.datesSelected
.filter(
(dateSelected) =>
dateSelected.isSelected(day) &&
dateSelected.type &&
(!previewed || !['cp', 'rtt', 'other'].includes(dateSelected.type)),
)
.map((dateSelected) => this.translationService.getDayTypeLabel(dateSelected.type!));
const tooltips: string[] = this.selectedDates
.dayTypes(day)
.filter((type) => !previewed || !['cp', 'rtt', 'other'].includes(type))
.map((type) => this.translationService.getDayTypeLabel(type));
const declaredType = this.getDeclaredType(this.getDateKey(day));
if (declaredType)
tooltips.push(
`${this.tr().bookedDays.booked} (${this.declaredTypeLabel(declaredType)}). ${this.tr().bookedDays.fixed}`,
);
const status = this.getStatus(day);
if (status) {
tooltips.push(status.label);
if (status.changeLabel) tooltips.push(status.changeLabel);
if (status.reason) tooltips.push(status.reason);
if (status.hypotheticalLabel)
tooltips.push(
`${this.translationService.tr().planning.counterfactual}: ${status.hypotheticalLabel}`,
);
if (status.hypotheticalReason)
tooltips.push(
`${this.translationService.tr().planning.reason}: ${status.hypotheticalReason}`,
);
}
return tooltips.length > 0 ? tooltips.join(' + ') : null;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,17 +1,10 @@
@use '../planning-explanation';
:host {
display: block;
min-width: 0;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.calendar-year {
display: grid;
container: calendar-year / inline-size;
@@ -20,73 +13,13 @@
position: relative;
}
h2,
h3,
h4,
h5,
p {
margin: 0;
}
h2 {
font-size: clamp(1.5rem, 2.2vw, 2rem);
line-height: 1.2;
text-wrap: balance;
}
h3 {
font-size: 1.125rem;
}
h4 {
font-size: 1rem;
}
code {
font-size: 0.8em;
overflow-wrap: anywhere;
}
button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
min-width: 2.75rem;
min-height: 2.75rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--mat-sys-outline);
border-radius: var(--ui-radius-sm);
background: var(--ui-card-bg);
color: var(--mat-sys-primary);
font: inherit;
font-size: 0.875rem;
cursor: pointer;
transition: background-color 150ms ease;
&:hover:not(:disabled),
&[aria-pressed='true'] {
background: var(--ui-panel-bg);
}
&:disabled {
opacity: 0.45;
cursor: not-allowed;
}
&[aria-disabled='true'] {
opacity: 0.45;
cursor: not-allowed;
}
}
summary {
min-height: 2.75rem;
padding: 0.75rem;
font-weight: 500;
cursor: pointer;
}
summary:focus-visible {
outline: 3px solid var(--mat-sys-primary);
outline-offset: 2px;
}
.results-header,
.explanation-heading,
.replay-notice {
.explanation-heading {
display: flex;
flex-wrap: wrap;
align-items: center;
@@ -98,8 +31,14 @@ summary:focus-visible {
padding-block: 0.25rem 0.5rem;
}
.results-heading {
display: grid;
gap: 0.75rem;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1rem;
}
.calculation-date {
color: var(--ui-text-secondary);
font-size: 0.8125rem;
}
.planning-status {
display: flex;
@@ -126,6 +65,10 @@ summary:focus-visible {
background: var(--ui-error-bg);
color: var(--ui-error-text);
}
&.info {
background: var(--mat-sys-primary-container);
color: var(--mat-sys-on-primary-container);
}
}
.plan-summary {
@@ -221,12 +164,24 @@ summary:focus-visible {
}
}
.applied-rules-content {
display: grid;
gap: 0.75rem;
padding: 1rem;
}
.statistics-content {
display: grid;
gap: 1rem;
}
.statistics-summary {
grid-template-columns: minmax(0, 1fr);
grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr));
div {
padding: 0.875rem 1rem;
}
dd {
font-size: 1.75rem;
}
}
.earned-leave-breakdown {
display: grid;
@@ -249,14 +204,12 @@ summary:focus-visible {
}
.placement-explanation,
.outcome-explanation,
.trace-decisions {
.outcome-explanation {
display: grid;
gap: 1rem;
min-width: 0;
}
.placement-explanation,
.trace-layout {
.placement-explanation {
padding: 1.25rem;
}
.placement-explanation ul {
@@ -264,24 +217,14 @@ summary:focus-visible {
padding-inline-start: 1.25rem;
}
.break-story,
.outcome-explanation,
.replay-notice {
.outcome-explanation {
padding: 1rem;
border-radius: var(--ui-radius-sm);
background: var(--ui-panel-bg);
}
.technical-details {
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-sm);
> dl,
> div {
padding: 0.75rem;
}
}
.break-story,
.day-impact,
.leave-story,
.counterfactual-result {
.leave-story {
display: grid;
gap: 0.75rem;
}
@@ -303,53 +246,13 @@ summary:focus-visible {
font-variant-numeric: tabular-nums;
}
}
.impact-table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
font-size: 0.875rem;
th,
td {
padding: 0.75rem 0.5rem;
border-bottom: 1px solid var(--ui-border);
text-align: center;
overflow-wrap: anywhere;
}
th:first-child {
width: 52%;
text-align: start;
}
td {
font-size: 1.125rem;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
small {
display: block;
margin-top: 0.25rem;
font-size: 0.8125rem;
font-weight: 400;
color: var(--ui-text-secondary);
}
}
.compare-date-field {
width: 100%;
min-width: 0;
}
.compare-dates-button {
justify-self: start;
}
.placement-stepper,
.trace-toolbar,
.trace-decisions nav,
.trace-phase-stepper {
.placement-stepper {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
}
.placement-stepper button,
.trace-phase-stepper button {
.placement-stepper button {
padding: 0.375rem;
}
output {
@@ -383,19 +286,12 @@ output {
padding: 1rem 1rem 1rem 2rem;
margin: 0;
}
.inline-error,
.counterfactual-inline-error,
.conflict-explanation {
padding: 0.75rem;
border-inline-start: 4px solid var(--ui-error-text);
background: var(--ui-error-bg);
color: var(--ui-error-text);
}
.counterfactual-inline-error {
display: grid;
justify-items: start;
gap: 0.75rem;
}
.decisive-summary {
padding: 0.75rem;
border-inline-start: 3px solid var(--mat-sys-primary);
@@ -499,52 +395,6 @@ output {
box-shadow: none;
}
.trace-layout {
display: grid;
grid-template-columns: minmax(0, 0.35fr) minmax(0, 1fr);
gap: 1rem;
}
.trace-phases {
display: grid;
align-content: start;
gap: 0.5rem;
> button {
justify-content: space-between;
text-align: start;
overflow-wrap: anywhere;
}
.active {
border-inline-start: 4px solid var(--mat-sys-primary);
}
small {
color: var(--ui-text-secondary);
flex-shrink: 0;
white-space: nowrap;
}
}
.trace-phase-stepper {
justify-content: center;
}
.trace-decisions {
align-content: start;
}
.candidate-list {
display: grid;
gap: 0.5rem;
details {
padding: 0.5rem;
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-sm);
overflow-wrap: anywhere;
}
}
.trace-state-summary,
.replay-notice {
padding: 0.75rem;
border: 1px solid var(--mat-sys-primary);
border-radius: var(--ui-radius-sm);
}
.loading-overlay {
position: absolute;
inset: 0;
@@ -564,6 +414,15 @@ output {
.cancel-calculation {
min-height: 44px;
}
.calculation-detail {
display: grid;
justify-items: center;
gap: 0.25rem;
text-align: center;
p {
margin: 0;
}
}
.spinner-container {
position: relative;
}
@@ -576,18 +435,6 @@ output {
font-weight: 600;
}
@container calendar-year (max-width: 48rem) {
.trace-layout {
grid-template-columns: minmax(0, 1fr);
}
.trace-phases {
grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
}
.trace-phase-stepper {
grid-column: 1 / -1;
}
}
@container calendar-year (max-width: 35rem) {
.plan-insights {
grid-template-columns: minmax(0, 1fr);
@@ -604,8 +451,7 @@ output {
font-size: 0.75rem;
}
}
.placement-explanation,
.trace-layout {
.placement-explanation {
padding: 0.875rem;
}
.placement-stepper {
@@ -618,17 +464,11 @@ output {
}
}
.calculation-content,
.criteria-detail,
.balance-detail {
display: grid;
gap: 0.75rem;
min-width: 0;
}
.calculation-content {
gap: 1.5rem;
}
.calculation-intro,
.balance-detail > p {
color: var(--ui-text-secondary);
font-size: 0.875rem;
@@ -647,218 +487,3 @@ output {
font-weight: 600;
}
}
.criterion-help {
summary {
padding: 0;
align-content: center;
font-size: inherit;
}
p {
font-weight: 400;
font-size: 0.8125rem;
padding-block: 0.5rem;
}
}
.decisive-row {
background: var(--ui-panel-bg);
}
.decisive-label {
display: inline-block;
margin-top: 0.375rem;
padding: 0.125rem 0.375rem;
border: 1px solid var(--mat-sys-primary);
border-radius: var(--ui-radius-sm);
color: var(--mat-sys-primary);
font-size: 0.75rem;
font-weight: 600;
}
.tie-breaks {
padding: 0.75rem;
border-inline-start: 2px solid var(--ui-border);
font-size: 0.875rem;
ol {
margin: 0.5rem 0 0;
padding-inline-start: 1.25rem;
}
}
.audit-data {
border-top: 1px solid var(--ui-border);
summary {
padding-inline: 0;
color: var(--ui-text-secondary);
font-size: 0.875rem;
}
pre {
max-height: 24rem;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
padding: 0.75rem;
background: var(--ui-panel-bg);
font-size: 0.75rem;
}
}
.counterfactual-panel {
display: flex;
flex-direction: column;
max-height: calc(100dvh - 2rem);
background: var(--ui-card-bg);
color: var(--mat-sys-on-surface);
}
.comparison-heading,
.comparison-footer,
.comparison-result-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.comparison-heading {
align-items: flex-start;
padding: 1.5rem;
h2 {
font-size: 1.5rem;
}
p {
margin-top: 0.5rem;
color: var(--ui-text-secondary);
font-size: 0.875rem;
}
}
.comparison-close {
flex-shrink: 0;
padding: 0;
border-color: transparent;
}
.counterfactual-panel .comparison-content {
display: grid;
gap: 1rem;
min-height: 0;
max-height: none;
padding: 0 1.5rem 1.5rem;
color: inherit;
font: inherit;
font-size: 0.875rem;
}
.comparison-date-pair {
display: grid;
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
align-items: center;
gap: 0.75rem;
> mat-icon {
color: var(--ui-text-secondary);
}
> .original-date {
padding: 1rem;
border: 1px solid var(--ui-border);
border-radius: var(--ui-radius-sm);
}
}
.original-date {
display: grid;
gap: 0.75rem;
background: var(--ui-panel-bg);
span {
color: var(--ui-text-secondary);
}
strong {
font-size: 1.125rem;
}
}
.comparison-range {
color: var(--ui-text-secondary);
font-size: 0.8125rem;
}
.nearby-dates {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
> span {
flex-basis: 100%;
color: var(--ui-text-secondary);
}
}
.comparison-result-heading {
flex-wrap: wrap;
padding-top: 0.5rem;
}
.available-date,
.unavailable-date,
.comparison-loading {
display: flex;
align-items: center;
gap: 0.5rem;
mat-icon {
flex-shrink: 0;
}
}
.available-date {
color: var(--ui-success-text);
font-size: 0.8125rem;
}
.unavailable-date {
align-items: flex-start;
padding: 1rem;
border-radius: var(--ui-radius-sm);
background: var(--ui-warning-bg);
color: var(--ui-warning-text);
p {
margin-top: 0.5rem;
}
}
.comparison-empty {
padding: 1rem;
background: var(--ui-panel-bg);
border-radius: var(--ui-radius-sm);
}
.comparison-loading {
padding-block: 2rem;
justify-content: center;
}
.comparison-footer {
padding: 1rem 1.5rem;
border-top: 1px solid var(--ui-border);
font-size: 0.8125rem;
color: var(--ui-text-secondary);
.comparison-done {
background: var(--mat-sys-primary);
color: var(--mat-sys-on-primary);
&:hover {
background: var(--mat-sys-primary);
opacity: 0.9;
}
}
}
@media (max-width: 560px) {
.comparison-heading {
padding: 1rem;
}
.counterfactual-panel .comparison-content {
padding: 0 1rem 1rem;
}
.comparison-date-pair {
grid-template-columns: minmax(0, 1fr);
> mat-icon {
display: none;
}
> div {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
padding: 0.75rem;
}
}
.comparison-footer {
padding: 1rem;
flex-wrap: wrap;
button {
width: 100%;
}
}
}
.nearby-dates button[aria-pressed='true'] {
border-color: var(--mat-sys-primary);
}
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff. Show more