Skip to content

Commit 529ed7d

Browse files
fix(scenarios): keep a working-day card's dates on working days on every run date (#33999)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9KP2AnyfX9ZJYh48bUsyqbo)_ Fixes #33793 Clause-②: yes (widening) — new optional key `ScenarioCardSchema.workingDays` (`.`) Metadata-protocol: none ## 维护者速读 - 改了什么:场景卡可以声明 `workingDays: true`;运行器平移这种卡的日期时,今天仍落在运行当天,其余日期按整工作日平移,不再按整天。请假卡 `leave_balances` 声明了它,并把 31 条落在周末的审批日期挪到下一个工作日。 - 为什么改:上一个 PR 按整天平移后,7 个运行日里有 6 天会把请假日落到周末(最多 126/307 条),应用只算周一到周五,于是 6 条真值和余额跟卡上的数字对不上,问句里的「周三」也会变成「周日」。 - 风险与回滚:只动 `packages/qa/scenarios`(运行器、加载器、卡格式多一个可选键,属放宽)和这张卡;别的 6 张带日期的卡不声明,行为不变。回滚即 revert 本 PR。 - 先看:`packages/qa/scenarios/src/runner/run-date.ts` 的 `moveFor`(两种平移的分叉点),`src/loader.ts` 的 `checkWorkingDays`,卡里 31 行 `decided_on`。 - 两分钟验证:`pnpm --filter @objectstack/scenarios exec vitest run test/runner/run-date.test.ts`,34 项全过;其中连续 7 个运行日(2026-11-15 到 11-21)各一项。 - 需要你做的:无,席位落地。 ## What changes **Step 1, measured first.** On `origin/main` (895783a), over seven consecutive run dates 2026-11-15 (a Sunday) to 11-21, the whole-day rebase puts this card's working days on weekends on six of the seven: only 11-18 (delta 49, whole weeks) is clean. When a working day lands on a weekend, the meaning changes in three places: - **Request days.** The card's prompt has the app sum a request's day lines "Monday to Friday only". Read that way over the moved seed, 60 to 84 of the 120 requests no longer have the seeded `days`. - **Balances and truths.** 17 to 22 balances' `used_days` move with them, and 6 of the 10 truths change: `approved_days`, `top_annual_takers`, `approved_days_last_month`, `annual_days_by_department`, `remaining_annual_by_department`, `lowest_annual_remaining`. The persona truths change too. Only the two approval-step questions, the medical-note count and the unanswerable one hold. - **Asks.** `file_and_submit_from_text` asks for weekend leave on 3 of the 7 dates ("Sunday 13 December" on 11-15). `half_day_on_draft` targets a line that falls on a Saturday or Sunday on 2 of the 7, and its request has a weekend line on a third. The other dated cards: the open library has 7 dated cards, not 9 (`crm_account_with_contacts` and `project_with_tasks` have no `asOf`). Searching the 6 others for weekday names, `weekday`/`weekend`/`working day`/`business day`, `周X`, `工作日` and `周末` gives **0 hits**. Their seeds already hold 2 to 256 weekend dates each, so none keeps to working days. `leave_balances` is the only one, with 12 hits. **Step 2, the fix.** Three ways to fix this, with the measured reason for the choice: - **A whole-week delta** is ruled out by the card. It keeps weekdays only by putting the prompt's today up to three days off the run date. - **Snapping each moved date to its nearest working day** breaks multi-day leave. On the same seven dates, 36 to 62 requests get two day lines on one date (0 only on 11-18). - **Moving the card by whole working days** keeps every Monday-to-Friday span intact. This is the one shipped. Changes: - **The card format** (`src/schema.ts`): an optional card key, `workingDays: true`, declared by the author, never inferred. It widens what `ScenarioCardSchema` (exported from `.`) accepts, hence `Clause-②: yes (widening)`. The new helpers in `run-date.ts` (`shiftWorkingDays`, `workingDaysBetween`, `onWorkingDay`) reach no `exports` subpath: `run-date.ts` is imported only by `src/runner/cli.ts`, and the built `index`, `runner`, `score`, `score-full` and `export` declarations hold none of them (`ScenarioCardSchema` found in `index.d.ts` as the positive control). - **The loader** (`src/loader.ts`, `checkWorkingDays`) refuses such a card in two cases: - it has no `asOf`; - `asOf`, or any ISO date under `run` or `iterate`, falls on a Saturday or Sunday. The refusal names the path and the weekday. A weekend `asOf` would be counted as the Friday before it, so that Friday and `asOf` would both move onto the run date. - **The rebase** (`src/runner/run-date.ts`, `moveFor`). A card without the key moves exactly as before. A card with it moves like this: - `asOf` goes onto the run date itself, so the prompt's today is still the run date. The rebase also refuses a weekend `asOf` on such a card (it throws) rather than map two dates onto one. - Every other date moves by `workingDaysBetween(asOf, runDate)` whole working days (`shiftWorkingDays`). A weekend run date is read as the Friday before it. - So a date before the card's today lands before the run date, and a date after it lands after the run date. Consecutive working days stay consecutive, and N working days between two dates stay N. - Ask-text dates move the same way, and their weekday names are written again (`shiftTextDates` now takes either a day count or the card's move). - Truths are recomputed over the moved seed, as before. `scopeFigures` still stay, because the move maps distinct dates to distinct dates. - **`docs/qa/scenarios/leave_balances.json`:** - It declares `workingDays: true`. - The seed rule said "decided the day after submission" and "two days after", which put 31 approval decisions on a Saturday or Sunday. It now says "the working day after" and "two working days after". - Exactly those 31 `decided_on` values move. A recomputation of every step from its request's `submitted_on` changes no other row, and no truth reads `decided_on`. - **The two READMEs:** - `docs/qa/scenarios/README.md`, the card authors' guide, gains a paragraph. The runner moves a card's dates onto the run date, so an author must not rely on a fixed calendar date or a weekday name. A card on working days declares `workingDays`. - `packages/qa/scenarios/README.md`: its run-date bullet stated the old limit ("keeps to them only when the delta is whole weeks"). It now states the contract. - `.changeset/33793-working-day-rebase.md`: `@objectstack/scenarios` patch. ## Tests `packages/qa/scenarios/test/runner/run-date.test.ts`, 34 tests (was 18). **New: whole working days.** These check `shiftWorkingDays` and `workingDaysBetween`: - across a weekend, a month end, a leap day and a year boundary, and around the epoch week; - each against an independent walk over the calendar, one day at a time. **New: `leave_balances` on seven consecutive run dates (2026-11-15 to 11-21).** For each date: - `asOf` is the run date. - Every moved date, apart from a value that is the card's today, is a working day. - A date before the card's today lands before the run date, and a date after it lands after. - Each request's Monday-to-Friday day lines, read independently over the moved seed, sum to its `days`. Each balance's `used_days` equals its approved requests' days. - Every non-calendar truth and every persona truth equals the card's own figure. - The English and Chinese asks name working days only. Each named weekday is that date's own, and the dates are the ones the operation's values and expected day lines carry. - The half day the draft's ask names is the date of the line it targets. **New: loader refusals.** A copy of the card with one leave day on Saturday 2026-07-04 is refused once, at `run.seed.leave_day[0].leave_date`. The same copy without `workingDays` is not refused for it. A copy whose `asOf` is Saturday 2026-10-03 is refused once, at `asOf`. A copy without `asOf` is refused. **New: a weekend `asOf` counterexample.** A copy with `asOf` Saturday 2026-11-14 and a leave day on Friday 2026-11-13, run on Wednesday 2026-11-18: counted from that Friday, the Friday itself would move onto 11-18 with `asOf`. The rebase throws on it (`asOf 2026-11-14 is a weekend`), and the loader refuses the same card once, at `asOf`. **Forced edits to existing tests**, named: - `every dated card, rebased onto each run date › run on DATE` (nine tests). The leaf check and the calendar-window reading-back used one whole-day delta for every card. They now read each card's move independently: whole days, or for a `workingDays` card a walk over working days. Only the title words changed otherwise. - `the asks that write a date say the moved one…`: the leave pins were the defect. On 2026-11-15 they now read "Friday 11 December and the morning of Monday 14 December" (was Sunday 13) and "(3 December)" (was 5 December). **Ablations**, each through `scripts/ablation-replace.mjs`, each restored with blob equal to HEAD and an empty `git diff HEAD`: - The loader's `asOf` check deleted: 2 of 34 red, the two loader refusals of a weekend `asOf`. - The rebase's weekend-`asOf` guard disabled: 1 of 34 red, the rebase counterexample. - At the first round's head, with `moveFor` forced to the whole-day branch, 16 of the 31 tests went red. Those were the 9 every-dated-card runs, the ask pins, and 6 of the 7 seven-day runs; 11-18 stayed green, as the measurement predicts (blob 500440c to 2899d999). ## Deviations - `packages/qa/scenarios/src/schema.ts` is outside the claim's file surface. The card-level flag the claim allows can only live there, because the card is a strict object the loader parses against that schema (+6 lines, one optional key). The seat accepted this. - The key's name, `workingDays: true`, was proposed here with `rebase: "working_days"` and `dates: "working_days"` as alternatives. The seat chose `workingDays`. ## Acceptance notes - **Weekend run dates.** On a Saturday or Sunday run, the card's other dates move as they would for the Friday before it. So 11-20 and 11-21 seed identically, and the moved data ends up to two days nearer the run date than the card wrote it. Nothing seeded before the card's today moves past the run date, which is #33753's invariant. - **Hire dates still move.** The rebase moves `hire_date` (whole days before, working days now). `leave_year` (`2026/27`) and the 1 July service rule live in the prompt and the strings, which are not moved. On a run date about nine months or more after `asOf`, the moved leave falls into the next leave year while the balances still say 2026/27. This was the same before this change and is a property of the shipped rebase, not of the weekday defect. Noted, not filed. - The `$comment` seed rule ("working day … of July") still describes the card's own dates. Like the prompt, it is never moved. ## Verification <details><summary>Step 1 readings (origin/main 895783a, then this head)</summary> Measured with a throwaway script over `loadScenarios` + `rebaseScenario`, not committed. ```text origin/main, whole-day rebase: 2026-11-15 Sun delta=46 leave_day_weekend=126/307 req_days_changed=84 balances_changed=20 truths_changed=6 weekend_ask=file_and_submit_from_text 2026-11-16 Mon delta=47 leave_day_weekend=123/307 req_days_changed=82 balances_changed=22 truths_changed=6 2026-11-17 Tue delta=48 leave_day_weekend=60/307 req_days_changed=60 balances_changed=19 truths_changed=6 2026-11-18 Wed delta=49 leave_day_weekend=0/307 req_days_changed=0 balances_changed=0 truths_changed=0 2026-11-19 Thu delta=50 leave_day_weekend=60/307 req_days_changed=60 balances_changed=17 truths_changed=6 2026-11-20 Fri delta=51 leave_day_weekend=121/307 req_days_changed=81 balances_changed=20 truths_changed=6 weekend_ask=file_and_submit_from_text 2026-11-21 Sat delta=52 leave_day_weekend=124/307 req_days_changed=83 balances_changed=20 truths_changed=6 weekend_ask=file_and_submit_from_text per-date nearest-working-day snap, requests with two lines on one date: 62 39 39 0 36 37 62 this head, working-day rebase: every one of the seven reads 0 / 0 / 0 / 0 / 0, no weekend ask other dated cards (weekday words · weekend dates in the seed): asset_lifecycle 0·216, invoice_with_line_items 0·2, order_to_cash 0·133, requisition_to_receipt 0·147, service_desk 0·172, travel_expense 0·256 ``` </details> Head `6588d4fe1` merges `origin/main` b4ce310 (clean, merge not rebase) on top of patch round 1 (`977f6bf6e`). The earlier merge, `1b082ce44`, took in `origin/main` b8ac0e2 cleanly after PR #33872 landed; that PR also edits `packages/qa/scenarios/README.md`. - At `6588d4fe1`, after `pnpm install --frozen-lockfile` (the merge moved `pnpm-lock.yaml`) and a rebuild of `@objectstack/scenarios` with its dependency closure: `vitest run` 34 files, 881 tests, exit 0; `tsc --noEmit` exit 0. - At `977f6bf6e`, derived by `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` on this diff (the same 65 families at every head): `dispatch-gates --ran` 65 derived, 65 run, 0 NOT-MEASURED, every one exit 0. The full `pnpm build` (119/119 tasks) was done at `1b082ce44`. At `bc00b2a13`, two families had first answered exit 3 (prerequisite not met) and passed once it was built: `check-plugin-teardown-shape.mjs --self-test` after `git fetch --unshallow`, and `pnpm check:dual-build-cjs-loads` after the full build. - `pnpm exec eslint` on `run-date.ts`, `loader.ts`, `schema.ts` and `run-date.test.ts`: exit 0 (no diff of these since `977f6bf6e`). - CI families are read off this PR's check runs by the seat. Full record: `/mnt/project-files/devx-seat1/33793-gates-ran.txt`. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (the card key is a Zod field in `packages/qa/scenarios/src/schema.ts`; `packages/spec` not touched) - [x] 2. Every name I added uses the casing for its kind. (`workingDays` card key and `shiftWorkingDays`, `workingDaysBetween`, `onWorkingDay`: camelCase) - [x] 3. No formatter ran; `pnpm lint` passes. (eslint on the four touched source and test files: exit 0; the repo-wide run is CI's) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. (`.changeset/33793-working-day-rebase.md`, `@objectstack/scenarios` patch) - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (the 维护者速读 block is the seat's required Chinese summary) - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmRWUrXgua6hAwuKweu)_ <!-- signed: domain:devx#2 · os-steve · session_01ADHkmQTVjryTSkqydKVS6z --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e71ecc1 commit 529ed7d

8 files changed

Lines changed: 463 additions & 70 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/scenarios': patch
3+
---
4+
5+
fix(scenarios): a card that keeps to working days stays on working days on every run date
6+
7+
Clause-②: yes (widening) — new optional key `ScenarioCardSchema.workingDays` (`.`)
8+
Metadata-protocol: none
9+
10+
A scenario card can declare `workingDays: true`. The run-date rebase then moves its `asOf` onto the run
11+
date and every other date by whole working days instead of whole days, so a Monday-to-Friday leave day,
12+
and the weekday an ask names, stays on a working day however far from `asOf` the card runs (a weekend run
13+
date moves them as for the Friday before it). The loader refuses such a card when its `asOf` or any other date
14+
it holds falls on a weekend, or it has no `asOf`. The `leave_balances` card declares it, so its request days,
15+
balances and truths keep their meaning on every run date.

‎docs/qa/scenarios/README.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,20 @@ Chinese and an English title, and every reader picks one of the two explicitly.
4848
unique across the library. The app lives in the namespace `demo` + code (`democrm`) wherever
4949
it is built, scored or exported, and every item it declares carries that prefix.
5050

51+
**The run moves the card's dates.** `asOf` is the card's today as written, not the day it runs on.
52+
Before a card runs, the runner moves its dates onto the run date: `asOf` becomes the run date, and
53+
every ISO date under `run` and `iterate`, and every date an `ask` writes in its text, moves with it
54+
(one whole-day delta, so every interval between two dates is kept; truths over a calendar window
55+
are computed again over the moved seed). An author therefore must not rely on a fixed calendar
56+
date or on the day of the week: a date written as a Wednesday may run as a Sunday, an ask's weekday
57+
name is written again for the moved date, and a `this_month` window holds whatever the moved seed
58+
puts in it. A card whose dates keep to working days (leave taken Monday to Friday, a day count that
59+
skips weekends) declares `"workingDays": true`: `asOf` and every other date it holds must then fall
60+
on a Monday to Friday, or the card is refused, and the run moves those dates by whole working days
61+
instead, so a working day stays a working day on every run date and N working days between two
62+
dates stay N (a weekend run date moves them as for the Friday before it). Public holidays are out
63+
of scope either way.
64+
5165
**Counts.** The default band is 8–10 questions and 4–6 operations. A card below 8 questions
5266
or 4 operations states why in `run.countsReason`, or it is refused; a `starter` or `delivery`
5367
card has no such excuse ([Tiers](#tiers)).

‎docs/qa/scenarios/leave_balances.json‎

Lines changed: 33 additions & 32 deletions
Large diffs are not rendered by default.

‎packages/qa/scenarios/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,9 @@ npx @objectstack/scenarios help # the comma
344344
in its text (ISO, English `[Weekday] D Month`, Chinese `M 月 D 日(周X)`, weekdays written again); the truths are
345345
computed again over the moved seed. The prompt's "today", the seeded rows, the timestamps the app's real clock
346346
stamps and the grader's expectations then agree, however long after `asOf` the run is. The card file is not
347-
changed. A card on working days keeps to them only when the delta is whole weeks.
347+
changed. A card that declares `workingDays: true` (the loader refuses one whose `asOf` or any other date falls on a
348+
weekend) moves by whole working days instead: `asOf` onto the run date, every other date by the working days
349+
from `asOf` to the run date (a weekend run date read as the Friday before it), so its weekdays stay weekdays.
348350
- **Namespaces** (`namespace.ts`): every card's app is in the namespace `demo` + the card's `code` (`democrm`): scratch
349351
mode scaffolds the project under that name, and template mode installs a template declaring it into a host named
350352
`host<code>` (the unmanaged copy keeps its namespace, and the install refuses one the host owns). The card's names are

‎packages/qa/scenarios/src/loader.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,37 @@ function checkGalleryFloor(card: ScenarioCard, refuse: Refuse) {
477477
}
478478
}
479479

480+
/**
481+
* A card declaring `workingDays` needs `asOf`, and `asOf` and every ISO date value under `run` and `iterate`
482+
* on a Monday to Friday: the run-date rebase moves such a card by whole working days, which a weekend date
483+
* has no place in. A weekend `asOf` would be counted as the Friday before it, so it and that Friday would
484+
* move onto the same run date.
485+
*/
486+
function checkWorkingDays(card: ScenarioCard, refuse: Refuse) {
487+
if (card.asOf === undefined) {
488+
refuse(['workingDays'], '`workingDays` needs `asOf`: the working days are counted from the card\'s today');
489+
return;
490+
}
491+
const check = (v: string, at: IssuePath): void => {
492+
const m = /^(\d{4})-(\d{2})-(\d{2})(?=$|T)/.exec(v);
493+
if (!m) return;
494+
const t = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
495+
if (t.getUTCMonth() !== Number(m[2]) - 1 || t.getUTCDate() !== Number(m[3])) return;
496+
const w = t.getUTCDay();
497+
if (w === 0 || w === 6) {
498+
refuse(at, `\`${v}\` is a ${w === 0 ? 'Sunday' : 'Saturday'}, but the card declares \`workingDays\`: move it to a working day, or drop \`workingDays\` if the card does not keep to them`);
499+
}
500+
};
501+
check(card.asOf, ['asOf']);
502+
const walk = (v: unknown, at: IssuePath): void => {
503+
if (typeof v === 'string') check(v, at);
504+
else if (Array.isArray(v)) v.forEach((x, i) => walk(x, [...at, i]));
505+
else if (v !== null && typeof v === 'object') for (const [k, x] of Object.entries(v)) if (k !== '$comment') walk(x, [...at, k]);
506+
};
507+
walk(card.run, ['run']);
508+
walk(card.iterate, ['iterate']);
509+
}
510+
480511
function duplicates<T>(items: readonly T[], keyOf: (t: T) => string, at: IssuePath, what: string, refuse: Refuse) {
481512
const seen = new Set<string>();
482513
items.forEach((item, i) => {
@@ -539,6 +570,9 @@ function checkCard(
539570
);
540571
}
541572

573+
// ── working days: a card that declares them holds no weekend date but its today ──
574+
if (card.workingDays === true) checkWorkingDays(card, refuse);
575+
542576
// ── expect: internal consistency ──
543577
const objects = new Set(expect.objects);
544578
const dashboards = new Set(expect.dashboards ?? []);

‎packages/qa/scenarios/src/runner/run-date.ts‎

Lines changed: 97 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,21 @@
2020
* (`this_month`, `previous_month`, …) is re-read around the new `asOf`: the
2121
* truths are computed again over the moved seed ({@link truthsOver}), so the
2222
* figure the grader holds is the one the moved data gives. Weekday names in
23-
* an ask are written again for the moved date; a card whose seed keeps to
24-
* working days does not keep to them after a delta that is not whole weeks.
23+
* an ask are written again for the moved date.
24+
*
25+
* Working days: a whole-day delta that is not whole weeks puts a Monday-to-
26+
* Friday date on a weekend, so a leave request's days, the balances they come
27+
* off and an ask that names "Wednesday" change meaning. A card that declares
28+
* `workingDays: true` keeps every date it holds, its today included, on a
29+
* working day (the loader refuses one that does not), and moves them by whole
30+
* WORKING days instead ({@link shiftWorkingDays}): `asOf` still lands on the
31+
* run date itself, a date before it lands before the run date and a date after
32+
* it after the run date, consecutive working days stay consecutive, and N
33+
* working days between two dates stay N. The run date may be a weekend: the
34+
* card's other dates then move as they would for the Friday before it, and only
35+
* `asOf` lands on the weekend day itself. A whole-week
36+
* delta would keep the weekdays too, but only by putting the prompt's today up
37+
* to three days off the run date, the very mismatch this rebase removes.
2538
*
2639
* What moves: `asOf`; every value under `run` and `iterate` that is an ISO date
2740
* (`YYYY-MM-DD`) or starts with one (an ISO date-time keeps its time); and the
@@ -73,6 +86,46 @@ export function shiftDate(date: string, days: number): string {
7386
return ymd(new Date(dayOf(date).getTime() + days * DAY_MS)) + date.slice(10);
7487
}
7588

89+
/** Whether `t` (UTC midnight) is a working day, Monday to Friday; public holidays are out of scope. */
90+
function isWorkingDay(t: Date): boolean {
91+
const w = t.getUTCDay();
92+
return w !== 0 && w !== 6;
93+
}
94+
95+
/** Whether `date` (`YYYY-MM-DD`, or an ISO date-time) falls on a working day, Monday to Friday. */
96+
export function onWorkingDay(date: string): boolean {
97+
return isWorkingDay(dayOf(date));
98+
}
99+
100+
// Working days are counted from Monday 1969-12-29, the Monday before the epoch (a Thursday).
101+
/** The working-day number of `t`, or of the working day before it when `t` is a weekend. */
102+
function workingDayNumber(t: Date): number {
103+
const n = Math.round(t.getTime() / DAY_MS) + 3; // days since Monday 1969-12-29
104+
const week = Math.floor(n / 7);
105+
return week * 5 + Math.min(n - week * 7, 4);
106+
}
107+
108+
/** The working day numbered `k` ({@link workingDayNumber}). */
109+
function workingDay(k: number): Date {
110+
const week = Math.floor(k / 5);
111+
return new Date((week * 7 + (k - week * 5) - 3) * DAY_MS);
112+
}
113+
114+
/** Whole working days from `from` to `to`, each read as the working day on or before it. */
115+
export function workingDaysBetween(from: string, to: string): number {
116+
return workingDayNumber(dayOf(to)) - workingDayNumber(dayOf(from));
117+
}
118+
119+
/** `date`, a working day (`YYYY-MM-DD`, or an ISO date-time whose time is kept), moved by `days` whole working days. */
120+
export function shiftWorkingDays(date: string, days: number): string {
121+
const t = dayOf(date);
122+
if (!isWorkingDay(t)) throw new Error(`not a working day: ${JSON.stringify(date)}`);
123+
return ymd(workingDay(workingDayNumber(t) + days)) + date.slice(10);
124+
}
125+
126+
/** How a card's dates move: a day (UTC midnight) to the day it becomes. */
127+
type Move = (t: Date) => Date;
128+
76129
/** Whether a card value is a date the rebase moves. */
77130
function isDateValue(v: string): boolean {
78131
const m = ISO_DATE.exec(v);
@@ -92,14 +145,18 @@ function nearestYear(m: number, d: number, anchor: Date): Date | undefined {
92145
const EN_WEEKDAY = `(?:(${EN_WEEKDAYS.join('|')}),? )?`;
93146
const EN_MONTH = `(${EN_MONTHS.join('|')})`;
94147

95-
/** An ask's text with every date it writes moved by `days`, read around the card's `asOf`. */
96-
export function shiftTextDates(text: string, days: number, asOf: string): string {
148+
/**
149+
* An ask's text with every date it writes moved, read around the card's `asOf`: by `move` whole days, or by
150+
* the card's own {@link Move} (the working-day rebase).
151+
*/
152+
export function shiftTextDates(text: string, move: number | Move, asOf: string): string {
97153
const anchor = dayOf(asOf);
98-
const moved = (t: Date) => new Date(t.getTime() + days * DAY_MS);
154+
const moved: Move = typeof move === 'number' ? (t) => new Date(t.getTime() + move * DAY_MS) : move;
155+
const shift = (iso: string) => ymd(moved(dayOf(iso))) + iso.slice(10);
99156

100157
// ISO dates.
101158
let out = text.replace(/\b(\d{4})-(\d{2})-(\d{2})\b/g, (all, y: string, m: string, d: string) =>
102-
parseDay(Number(y), Number(m), Number(d)) ? shiftDate(all, days) : all,
159+
parseDay(Number(y), Number(m), Number(d)) ? shift(all) : all,
103160
);
104161

105162
// English "[Weekday] D Month [YYYY]" and "[Weekday, ]Month D[, YYYY]", in one pass so no date moves twice.
@@ -146,35 +203,56 @@ export function shiftTextDates(text: string, days: number, asOf: string): string
146203
}
147204

148205
/** `value` with every date in it moved; an `ask` object's texts are rewritten, every other string only when it IS a date. */
149-
function shiftTree(value: unknown, days: number, asOf: string, key?: string): unknown {
150-
if (typeof value === 'string') return isDateValue(value) ? shiftDate(value, days) : value;
151-
if (Array.isArray(value)) return value.map((v) => shiftTree(v, days, asOf));
206+
function shiftTree(value: unknown, move: Move, asOf: string, key?: string): unknown {
207+
if (typeof value === 'string') return isDateValue(value) ? ymd(move(dayOf(value))) + value.slice(10) : value;
208+
if (Array.isArray(value)) return value.map((v) => shiftTree(v, move, asOf));
152209
if (value === null || typeof value !== 'object') return value;
153210
const out: Record<string, unknown> = {};
154211
for (const [k, v] of Object.entries(value)) {
155212
if (k === '$comment') out[k] = v;
156-
else if (key === 'ask' && typeof v === 'string') out[k] = shiftTextDates(v, days, asOf);
157-
else out[k] = shiftTree(v, days, asOf, k);
213+
else if (key === 'ask' && typeof v === 'string') out[k] = shiftTextDates(v, move, asOf);
214+
else out[k] = shiftTree(v, move, asOf, k);
158215
}
159216
return out;
160217
}
161218

219+
/**
220+
* How a card's dates move so `asOf` is `runDate`: by one whole-day delta, or, on a card that declares
221+
* `workingDays`, `asOf` onto `runDate` and every other date by whole working days ({@link shiftWorkingDays}).
222+
*/
223+
function moveFor(card: LoadedScenario['card'], asOf: string, runDate: string): Move {
224+
if (card.workingDays !== true) {
225+
const days = daysBetween(asOf, runDate);
226+
return (t) => new Date(t.getTime() + days * DAY_MS);
227+
}
228+
const [from, to] = [dayOf(asOf), dayOf(runDate)];
229+
// A weekend asOf would count as the Friday before it, and that Friday would move onto the run date too.
230+
if (!isWorkingDay(from)) throw new Error(`card declares workingDays but its asOf ${asOf} is a weekend`);
231+
const days = workingDaysBetween(asOf, runDate);
232+
return (t) => {
233+
if (t.getTime() === from.getTime()) return to;
234+
if (!isWorkingDay(t)) throw new Error(`card declares workingDays but holds ${ymd(t)}, a weekend`);
235+
return workingDay(workingDayNumber(t) + days);
236+
};
237+
}
238+
162239
/**
163240
* `scenario` with its card's dates moved so `asOf` is `runDate`, and its truths
164241
* computed again over the moved seed. A card with no `asOf`, or one already on
165-
* `runDate`, is returned as it is. `scopeFigures` stay: a whole-day shift maps
166-
* distinct dates to distinct dates, so no count it holds moves.
242+
* `runDate`, is returned as it is. `scopeFigures` stay: both moves map distinct
243+
* dates to distinct dates (the working-day move takes working days to distinct
244+
* working days, and `asOf`, itself a working day, alone onto the run date), so
245+
* no count it holds moves.
167246
*/
168247
export function rebaseScenario(scenario: LoadedScenario, runDate: string): LoadedScenario {
169248
const { asOf } = scenario.card;
170-
if (asOf === undefined) return scenario;
171-
const days = daysBetween(asOf, runDate);
172-
if (days === 0) return scenario;
249+
if (asOf === undefined || daysBetween(asOf, runDate) === 0) return scenario;
250+
const move = moveFor(scenario.card, asOf, runDate);
173251
const card = {
174252
...scenario.card,
175-
asOf: shiftDate(asOf, days),
176-
run: shiftTree(scenario.card.run, days, asOf) as LoadedScenario['card']['run'],
177-
iterate: shiftTree(scenario.card.iterate, days, asOf) as LoadedScenario['card']['iterate'],
253+
asOf: ymd(move(dayOf(asOf))),
254+
run: shiftTree(scenario.card.run, move, asOf) as LoadedScenario['card']['run'],
255+
iterate: shiftTree(scenario.card.iterate, move, asOf) as LoadedScenario['card']['iterate'],
178256
};
179257
return { ...scenario, card, ...truthsOver(card, card.run.seed) };
180258
}

‎packages/qa/scenarios/src/schema.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,12 @@ export const ScenarioCardSchema = z.strictObject({
578578
expect: ExpectSchema,
579579
/** The fixed "today" relative windows are computed against (`YYYY-MM-DD`). */
580580
asOf: z.iso.date().optional(),
581+
/**
582+
* The card's dates keep to working days, Monday to Friday: `asOf` and every ISO date under `run` and
583+
* `iterate` fall on one (the loader refuses a weekend), and the run-date rebase moves them by whole
584+
* working days instead of whole days, so a weekday stays a weekday on every run date. Needs `asOf`.
585+
*/
586+
workingDays: z.literal(true).optional(),
581587
capabilities: z.array(CapabilityTagSchema).min(1),
582588
businessFunctions: BusinessFunctionsSchema,
583589
run: z.strictObject({

0 commit comments

Comments
 (0)