assignment-user-matcher 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +106 -1
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +19 -1
  5. package/dist/matcher.class.d.ts.map +1 -1
  6. package/dist/matcher.class.js +11 -0
  7. package/dist/scheduling/constraints/availability.d.ts +44 -0
  8. package/dist/scheduling/constraints/availability.d.ts.map +1 -0
  9. package/dist/scheduling/constraints/availability.js +142 -0
  10. package/dist/scheduling/constraints/consecutive.d.ts +25 -0
  11. package/dist/scheduling/constraints/consecutive.d.ts.map +1 -0
  12. package/dist/scheduling/constraints/consecutive.js +215 -0
  13. package/dist/scheduling/constraints/constraint.d.ts +35 -0
  14. package/dist/scheduling/constraints/constraint.d.ts.map +1 -0
  15. package/dist/scheduling/constraints/constraint.js +97 -0
  16. package/dist/scheduling/constraints/contract.d.ts +21 -0
  17. package/dist/scheduling/constraints/contract.d.ts.map +1 -0
  18. package/dist/scheduling/constraints/contract.js +106 -0
  19. package/dist/scheduling/constraints/cost.d.ts +18 -0
  20. package/dist/scheduling/constraints/cost.d.ts.map +1 -0
  21. package/dist/scheduling/constraints/cost.js +65 -0
  22. package/dist/scheduling/constraints/daily-rest.d.ts +22 -0
  23. package/dist/scheduling/constraints/daily-rest.d.ts.map +1 -0
  24. package/dist/scheduling/constraints/daily-rest.js +118 -0
  25. package/dist/scheduling/constraints/duty-quota.d.ts +20 -0
  26. package/dist/scheduling/constraints/duty-quota.d.ts.map +1 -0
  27. package/dist/scheduling/constraints/duty-quota.js +95 -0
  28. package/dist/scheduling/constraints/engagement-floor.d.ts +28 -0
  29. package/dist/scheduling/constraints/engagement-floor.d.ts.map +1 -0
  30. package/dist/scheduling/constraints/engagement-floor.js +79 -0
  31. package/dist/scheduling/constraints/fairness.d.ts +34 -0
  32. package/dist/scheduling/constraints/fairness.d.ts.map +1 -0
  33. package/dist/scheduling/constraints/fairness.js +149 -0
  34. package/dist/scheduling/constraints/group-composition.d.ts +19 -0
  35. package/dist/scheduling/constraints/group-composition.d.ts.map +1 -0
  36. package/dist/scheduling/constraints/group-composition.js +92 -0
  37. package/dist/scheduling/constraints/hour-budget.d.ts +13 -0
  38. package/dist/scheduling/constraints/hour-budget.d.ts.map +1 -0
  39. package/dist/scheduling/constraints/hour-budget.js +59 -0
  40. package/dist/scheduling/constraints/in-shift-breaks.d.ts +24 -0
  41. package/dist/scheduling/constraints/in-shift-breaks.d.ts.map +1 -0
  42. package/dist/scheduling/constraints/in-shift-breaks.js +97 -0
  43. package/dist/scheduling/constraints/intervals.d.ts +5 -0
  44. package/dist/scheduling/constraints/intervals.d.ts.map +1 -0
  45. package/dist/scheduling/constraints/intervals.js +17 -0
  46. package/dist/scheduling/constraints/max-shift-duration.d.ts +7 -0
  47. package/dist/scheduling/constraints/max-shift-duration.d.ts.map +1 -0
  48. package/dist/scheduling/constraints/max-shift-duration.js +38 -0
  49. package/dist/scheduling/constraints/min-rest.d.ts +22 -0
  50. package/dist/scheduling/constraints/min-rest.d.ts.map +1 -0
  51. package/dist/scheduling/constraints/min-rest.js +60 -0
  52. package/dist/scheduling/constraints/min-staffing.d.ts +14 -0
  53. package/dist/scheduling/constraints/min-staffing.d.ts.map +1 -0
  54. package/dist/scheduling/constraints/min-staffing.js +59 -0
  55. package/dist/scheduling/constraints/night-work.d.ts +24 -0
  56. package/dist/scheduling/constraints/night-work.d.ts.map +1 -0
  57. package/dist/scheduling/constraints/night-work.js +163 -0
  58. package/dist/scheduling/constraints/no-overlap.d.ts +7 -0
  59. package/dist/scheduling/constraints/no-overlap.d.ts.map +1 -0
  60. package/dist/scheduling/constraints/no-overlap.js +36 -0
  61. package/dist/scheduling/constraints/notice.d.ts +44 -0
  62. package/dist/scheduling/constraints/notice.d.ts.map +1 -0
  63. package/dist/scheduling/constraints/notice.js +140 -0
  64. package/dist/scheduling/constraints/one-shift-per-day.d.ts +7 -0
  65. package/dist/scheduling/constraints/one-shift-per-day.d.ts.map +1 -0
  66. package/dist/scheduling/constraints/one-shift-per-day.js +35 -0
  67. package/dist/scheduling/constraints/overtime.d.ts +47 -0
  68. package/dist/scheduling/constraints/overtime.d.ts.map +1 -0
  69. package/dist/scheduling/constraints/overtime.js +149 -0
  70. package/dist/scheduling/constraints/protections.d.ts +21 -0
  71. package/dist/scheduling/constraints/protections.d.ts.map +1 -0
  72. package/dist/scheduling/constraints/protections.js +93 -0
  73. package/dist/scheduling/constraints/qualification.d.ts +18 -0
  74. package/dist/scheduling/constraints/qualification.d.ts.map +1 -0
  75. package/dist/scheduling/constraints/qualification.js +78 -0
  76. package/dist/scheduling/constraints/rest-days.d.ts +30 -0
  77. package/dist/scheduling/constraints/rest-days.d.ts.map +1 -0
  78. package/dist/scheduling/constraints/rest-days.js +133 -0
  79. package/dist/scheduling/constraints/rolling-hours.d.ts +24 -0
  80. package/dist/scheduling/constraints/rolling-hours.d.ts.map +1 -0
  81. package/dist/scheduling/constraints/rolling-hours.js +147 -0
  82. package/dist/scheduling/constraints/start-interval.d.ts +20 -0
  83. package/dist/scheduling/constraints/start-interval.d.ts.map +1 -0
  84. package/dist/scheduling/constraints/start-interval.js +53 -0
  85. package/dist/scheduling/constraints/support.d.ts +48 -0
  86. package/dist/scheduling/constraints/support.d.ts.map +1 -0
  87. package/dist/scheduling/constraints/support.js +97 -0
  88. package/dist/scheduling/constraints/time-off.d.ts +7 -0
  89. package/dist/scheduling/constraints/time-off.d.ts.map +1 -0
  90. package/dist/scheduling/constraints/time-off.js +42 -0
  91. package/dist/scheduling/constraints/weekly-rest.d.ts +22 -0
  92. package/dist/scheduling/constraints/weekly-rest.d.ts.map +1 -0
  93. package/dist/scheduling/constraints/weekly-rest.js +92 -0
  94. package/dist/scheduling/cost.d.ts +56 -0
  95. package/dist/scheduling/cost.d.ts.map +1 -0
  96. package/dist/scheduling/cost.js +120 -0
  97. package/dist/scheduling/engine/construction.d.ts +22 -0
  98. package/dist/scheduling/engine/construction.d.ts.map +1 -0
  99. package/dist/scheduling/engine/construction.js +97 -0
  100. package/dist/scheduling/engine/explain.d.ts +12 -0
  101. package/dist/scheduling/engine/explain.d.ts.map +1 -0
  102. package/dist/scheduling/engine/explain.js +24 -0
  103. package/dist/scheduling/engine/objective.d.ts +73 -0
  104. package/dist/scheduling/engine/objective.d.ts.map +1 -0
  105. package/dist/scheduling/engine/objective.js +164 -0
  106. package/dist/scheduling/engine/prng.d.ts +5 -0
  107. package/dist/scheduling/engine/prng.d.ts.map +1 -0
  108. package/dist/scheduling/engine/prng.js +24 -0
  109. package/dist/scheduling/engine/propagation.d.ts +19 -0
  110. package/dist/scheduling/engine/propagation.d.ts.map +1 -0
  111. package/dist/scheduling/engine/propagation.js +40 -0
  112. package/dist/scheduling/engine/search.d.ts +50 -0
  113. package/dist/scheduling/engine/search.d.ts.map +1 -0
  114. package/dist/scheduling/engine/search.js +127 -0
  115. package/dist/scheduling/engine/state.d.ts +28 -0
  116. package/dist/scheduling/engine/state.d.ts.map +1 -0
  117. package/dist/scheduling/engine/state.js +96 -0
  118. package/dist/scheduling/engine/timeline.d.ts +179 -0
  119. package/dist/scheduling/engine/timeline.d.ts.map +1 -0
  120. package/dist/scheduling/engine/timeline.js +416 -0
  121. package/dist/scheduling/engine/verdicts.d.ts +18 -0
  122. package/dist/scheduling/engine/verdicts.d.ts.map +1 -0
  123. package/dist/scheduling/engine/verdicts.js +74 -0
  124. package/dist/scheduling/index.d.ts +10 -0
  125. package/dist/scheduling/index.d.ts.map +1 -0
  126. package/dist/scheduling/index.js +29 -0
  127. package/dist/scheduling/model.d.ts +53 -0
  128. package/dist/scheduling/model.d.ts.map +1 -0
  129. package/dist/scheduling/model.js +379 -0
  130. package/dist/scheduling/operations.d.ts +134 -0
  131. package/dist/scheduling/operations.d.ts.map +1 -0
  132. package/dist/scheduling/operations.js +376 -0
  133. package/dist/scheduling/provenance.d.ts +33 -0
  134. package/dist/scheduling/provenance.d.ts.map +1 -0
  135. package/dist/scheduling/provenance.js +70 -0
  136. package/dist/scheduling/rules.d.ts +23 -0
  137. package/dist/scheduling/rules.d.ts.map +1 -0
  138. package/dist/scheduling/rules.js +37 -0
  139. package/dist/scheduling/scheduler.class.d.ts +24 -0
  140. package/dist/scheduling/scheduler.class.d.ts.map +1 -0
  141. package/dist/scheduling/scheduler.class.js +150 -0
  142. package/dist/scheduling/time.d.ts +132 -0
  143. package/dist/scheduling/time.d.ts.map +1 -0
  144. package/dist/scheduling/time.js +256 -0
  145. package/dist/scheduling/types.d.ts +932 -0
  146. package/dist/scheduling/types.d.ts.map +1 -0
  147. package/dist/scheduling/types.js +19 -0
  148. package/dist/types/matcher.d.ts +15 -0
  149. package/dist/types/matcher.d.ts.map +1 -1
  150. package/package.json +4 -2
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ /**
3
+ * Qualifications, valid on the day of the shift.
4
+ *
5
+ * The bug this exists to prevent: a static `Set<string>` of skills silently
6
+ * rosters someone onto a shift after their certificate has lapsed. In
7
+ * healthcare, aviation ground handling, food and security that is a live audit
8
+ * failure, and it is invisible in the roster — the person "has" the skill.
9
+ *
10
+ * So possession is a question about a *date*, not a fact about a person:
11
+ * `hasQualification(employee, tag, date)`, never `hasSkill(employee, tag)`.
12
+ * Tags on `Employee.tags` stay valid for the whole period; anything with an
13
+ * expiry belongs in `qualifications`.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.holds = exports.qualification = void 0;
17
+ const support_1 = require("./support");
18
+ function qualification() {
19
+ return (0, support_1.fromVerdict)({
20
+ id: 'qualification',
21
+ hardness: 'hard',
22
+ weight: 1,
23
+ prune(ctx, eligibility) {
24
+ for (const [employeeId, instances] of eligibility) {
25
+ const employee = ctx.employeeById.get(employeeId);
26
+ if (!employee)
27
+ continue;
28
+ for (const instanceId of [...instances]) {
29
+ const inst = ctx.instanceById.get(instanceId);
30
+ if (!inst?.requiredTags.length)
31
+ continue;
32
+ const missing = inst.requiredTags.filter((tag) => !holds(employee, tag, inst.date));
33
+ if (missing.length)
34
+ instances.delete(instanceId);
35
+ }
36
+ }
37
+ },
38
+ verdict(state, pair) {
39
+ const inst = (0, support_1.instanceOf)(state, pair);
40
+ const employee = state.ctx.employeeById.get(pair.employeeId);
41
+ if (!inst || !employee || !inst.requiredTags.length) {
42
+ return (0, support_1.pass)('qualification', 'no qualification requirement');
43
+ }
44
+ const missing = inst.requiredTags.filter((tag) => !holds(employee, tag, inst.date));
45
+ if (missing.length === 0) {
46
+ return (0, support_1.pass)('qualification', `holds ${inst.requiredTags.join(', ')} on ${inst.date}`);
47
+ }
48
+ // Distinguish "never had it" from "had it, expired" — they lead to
49
+ // completely different operational fixes.
50
+ const detail = missing
51
+ .map((tag) => {
52
+ const held = (employee.qualifications ?? []).find((q) => q.tag === tag);
53
+ if (held?.validUntil && held.validUntil < inst.date)
54
+ return `${tag} (expired ${held.validUntil})`;
55
+ if (held?.validFrom && held.validFrom > inst.date)
56
+ return `${tag} (valid from ${held.validFrom})`;
57
+ return tag;
58
+ })
59
+ .join(', ');
60
+ return (0, support_1.fail)('qualification', 'hard', `employee "${pair.employeeId}" lacks ${detail} for "${inst.id}"`, {
61
+ actual: inst.requiredTags.length - missing.length,
62
+ required: inst.requiredTags.length,
63
+ unit: 'count',
64
+ });
65
+ },
66
+ });
67
+ }
68
+ exports.qualification = qualification;
69
+ /** Whether the employee holds `tag` on `date`, by plain tag or dated qualification. */
70
+ function holds(employee, tag, date, minLevel) {
71
+ if (minLevel === undefined && (employee.tags ?? []).includes(tag))
72
+ return true;
73
+ return (employee.qualifications ?? []).some((q) => q.tag === tag &&
74
+ (q.validFrom === undefined || q.validFrom <= date) &&
75
+ (q.validUntil === undefined || q.validUntil >= date) &&
76
+ (minLevel === undefined || (q.level ?? 0) >= minLevel));
77
+ }
78
+ exports.holds = holds;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Sunday, public-holiday and free-Sunday rules.
3
+ *
4
+ * Three distinct shapes live here because national law mixes them freely:
5
+ *
6
+ * - **Outright bars.** Germany prohibits Sunday and holiday work altogether
7
+ * (ArbZG §9) subject to a long exception list; Belgium, Austria, Poland and
8
+ * Portugal work the same way. Whether an exception applies is the caller's
9
+ * call, expressed by leaving `sundayAllowed` unset.
10
+ * - **Free-Sunday quotas.** Germany guarantees at least 15 work-free Sundays a
11
+ * year, the Netherlands 13 per 52 weeks, Poland one in every four. These are
12
+ * counting rules over a calendar predicate, and they can only be judged
13
+ * across the whole roster — a single assignment never breaches them.
14
+ * - **Compensatory rest days.** Sunday or holiday work creates a *dated debt*:
15
+ * a substitute rest day within two weeks in Germany, eight for a holiday;
16
+ * six days either side in Poland. The obligation outlives the roster, so it
17
+ * is reported to the caller as a ledger entry rather than solved for.
18
+ */
19
+ import type { LedgerEntry, RestDayRule, SchedulingConstraint, SearchState } from '../types';
20
+ export declare const SUNDAY_CITATION = "National Sunday/holiday rest law";
21
+ export declare function restDays(rule: RestDayRule): SchedulingConstraint;
22
+ /**
23
+ * Substitute rest days owed for Sunday and public-holiday work.
24
+ *
25
+ * Returned to the caller rather than enforced: the obligation is discharged by
26
+ * granting a day off, often in a period this solve does not cover, so the
27
+ * honest output is a dated debt the operator can act on.
28
+ */
29
+ export declare function compensatoryRestLedger(state: SearchState, rule: RestDayRule | undefined): LedgerEntry[];
30
+ //# sourceMappingURL=rest-days.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rest-days.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/rest-days.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAER,WAAW,EACX,WAAW,EAEX,oBAAoB,EACpB,WAAW,EACd,MAAM,UAAU,CAAC;AAIlB,eAAO,MAAM,eAAe,qCAAqC,CAAC;AAElE,wBAAgB,QAAQ,CAAC,IAAI,EAAE,WAAW,GAAG,oBAAoB,CAgEhE;AAwBD;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,WAAW,GAAG,SAAS,GAAG,WAAW,EAAE,CAuBvG"}
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ /**
3
+ * Sunday, public-holiday and free-Sunday rules.
4
+ *
5
+ * Three distinct shapes live here because national law mixes them freely:
6
+ *
7
+ * - **Outright bars.** Germany prohibits Sunday and holiday work altogether
8
+ * (ArbZG §9) subject to a long exception list; Belgium, Austria, Poland and
9
+ * Portugal work the same way. Whether an exception applies is the caller's
10
+ * call, expressed by leaving `sundayAllowed` unset.
11
+ * - **Free-Sunday quotas.** Germany guarantees at least 15 work-free Sundays a
12
+ * year, the Netherlands 13 per 52 weeks, Poland one in every four. These are
13
+ * counting rules over a calendar predicate, and they can only be judged
14
+ * across the whole roster — a single assignment never breaches them.
15
+ * - **Compensatory rest days.** Sunday or holiday work creates a *dated debt*:
16
+ * a substitute rest day within two weeks in Germany, eight for a holiday;
17
+ * six days either side in Poland. The obligation outlives the roster, so it
18
+ * is reported to the caller as a ledger entry rather than solved for.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.compensatoryRestLedger = exports.restDays = exports.SUNDAY_CITATION = void 0;
22
+ const time_1 = require("../time");
23
+ const support_1 = require("./support");
24
+ exports.SUNDAY_CITATION = 'National Sunday/holiday rest law';
25
+ function restDays(rule) {
26
+ const constraint = (0, support_1.fromVerdict)({
27
+ id: 'rest-days',
28
+ hardness: 'hard',
29
+ weight: 1,
30
+ citation: exports.SUNDAY_CITATION,
31
+ verdict(state, pair) {
32
+ const inst = (0, support_1.instanceOf)(state, pair);
33
+ if (!inst)
34
+ return (0, support_1.pass)('rest-days', 'unknown shift');
35
+ if (rule.sundayAllowed === false && inst.isSunday) {
36
+ return (0, support_1.fail)('rest-days', 'hard', `Sunday work is not permitted, and "${inst.id}" falls on a Sunday`, {
37
+ citation: exports.SUNDAY_CITATION,
38
+ });
39
+ }
40
+ if (rule.holidayAllowed === false && inst.isPublicHoliday) {
41
+ return (0, support_1.fail)('rest-days', 'hard', `public-holiday work is not permitted, and "${inst.id}" falls on ${inst.date}`, { citation: exports.SUNDAY_CITATION });
42
+ }
43
+ return (0, support_1.pass)('rest-days', 'permitted on this calendar day', { citation: exports.SUNDAY_CITATION });
44
+ },
45
+ });
46
+ // Free-Sunday quotas are team-wide counting rules over the finished roster.
47
+ constraint.evaluate = (state) => {
48
+ const out = [];
49
+ if (!rule.minFreeSundaysPerYear && !rule.minFreeSundaysPer)
50
+ return out;
51
+ const sundays = sundaysInPeriod(state);
52
+ if (sundays.length === 0)
53
+ return out;
54
+ for (const employee of state.ctx.employees) {
55
+ const worked = new Set([...(state.byEmployee.get(employee.id) ?? [])]
56
+ .map((id) => state.ctx.instanceById.get(id))
57
+ .filter((inst) => inst?.isSunday)
58
+ .map((inst) => inst.date));
59
+ const free = sundays.filter((date) => !worked.has(date)).length;
60
+ if (rule.minFreeSundaysPer) {
61
+ // Pro-rate the rolling quota to the period actually being solved,
62
+ // so a 4-week roster is judged against its share, not a year's.
63
+ const windows = sundays.length / rule.minFreeSundaysPer.weeks;
64
+ const required = Math.floor(rule.minFreeSundaysPer.count * windows);
65
+ if (required > 0 && free < required) {
66
+ out.push(quotaViolation(employee.id, free, required, 'rolling'));
67
+ }
68
+ }
69
+ if (rule.minFreeSundaysPerYear !== undefined) {
70
+ const required = Math.floor((rule.minFreeSundaysPerYear * sundays.length) / 52);
71
+ if (required > 0 && free < required) {
72
+ out.push(quotaViolation(employee.id, free, required, 'annual'));
73
+ }
74
+ }
75
+ }
76
+ return out;
77
+ };
78
+ return constraint;
79
+ }
80
+ exports.restDays = restDays;
81
+ function quotaViolation(employeeId, free, required, kind) {
82
+ return {
83
+ constraintId: 'rest-days',
84
+ severity: 'medium',
85
+ employeeId,
86
+ message: `employee "${employeeId}" gets ${free} free Sunday(s) in this period, below the ${required} implied by the ${kind} quota`,
87
+ actual: free,
88
+ required,
89
+ unit: 'count',
90
+ citation: exports.SUNDAY_CITATION,
91
+ };
92
+ }
93
+ function sundaysInPeriod(state) {
94
+ const out = [];
95
+ for (let day = 0; day < state.ctx.periodDays; day++) {
96
+ const date = state.ctx.clock.dateAt(day);
97
+ if (state.ctx.clock.weekdayOfMinute(state.ctx.clock.dayStartMinutes(day)) === 7)
98
+ out.push(date);
99
+ }
100
+ return out;
101
+ }
102
+ /**
103
+ * Substitute rest days owed for Sunday and public-holiday work.
104
+ *
105
+ * Returned to the caller rather than enforced: the obligation is discharged by
106
+ * granting a day off, often in a period this solve does not cover, so the
107
+ * honest output is a dated debt the operator can act on.
108
+ */
109
+ function compensatoryRestLedger(state, rule) {
110
+ const within = rule?.compensatoryRestWithinDays;
111
+ if (!within)
112
+ return [];
113
+ const out = [];
114
+ for (const [instanceId, employees] of state.assignments) {
115
+ const inst = state.ctx.instanceById.get(instanceId);
116
+ if (!inst || employees.size === 0)
117
+ continue;
118
+ const deadlineDays = inst.isPublicHoliday ? within.holiday : inst.isSunday ? within.sunday : undefined;
119
+ if (deadlineDays === undefined)
120
+ continue;
121
+ for (const employeeId of employees) {
122
+ out.push({
123
+ kind: 'substituteRestDay',
124
+ employeeId,
125
+ dueBy: (0, time_1.addDays)(inst.date, deadlineDays),
126
+ reason: `worked "${inst.id}" on ${inst.isPublicHoliday ? 'a public holiday' : 'a Sunday'} (${inst.date})`,
127
+ citation: exports.SUNDAY_CITATION,
128
+ });
129
+ }
130
+ }
131
+ return out;
132
+ }
133
+ exports.compensatoryRestLedger = compensatoryRestLedger;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Working-time volume — Directive 2003/88/EC Art 6 and Art 16(b).
3
+ *
4
+ * The headline EU rule is "average working time for each seven-day period,
5
+ * including overtime, not exceeding 48 hours", averaged over a reference period
6
+ * of up to four months — extensible to six by derogation and twelve by
7
+ * collective agreement.
8
+ *
9
+ * The part that defeats a per-week hour budget: **any** seven-day period, and
10
+ * **any** four-month window. A person can sit under 48h in every calendar week
11
+ * and still average over it across week boundaries, and a fixed quarterly
12
+ * reference period hides an overrun that straddles two quarters. So every limit
13
+ * here is evaluated over rolling windows anchored on the person's own
14
+ * assignment boundaries.
15
+ *
16
+ * Art 16(b) also requires paid annual leave and sick leave to be "not included
17
+ * or neutral" in the average. Counting an absent week as zero hours would drag
18
+ * a person's average down and licence a heavier following week, so neutralised
19
+ * absence shortens the window's divisor instead.
20
+ */
21
+ import type { SchedulingConstraint, WorkingTimeLimits } from '../types';
22
+ export declare const WEEKLY_LIMIT_CITATION = "Directive 2003/88/EC Art 6(b), Art 16(b)";
23
+ export declare function rollingHours(limits: WorkingTimeLimits): SchedulingConstraint;
24
+ //# sourceMappingURL=rolling-hours.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rolling-hours.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/rolling-hours.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAe,oBAAoB,EAAe,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAIlG,eAAO,MAAM,qBAAqB,6CAA6C,CAAC;AAEhF,wBAAgB,YAAY,CAAC,MAAM,EAAE,iBAAiB,GAAG,oBAAoB,CAuE5E"}
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ /**
3
+ * Working-time volume — Directive 2003/88/EC Art 6 and Art 16(b).
4
+ *
5
+ * The headline EU rule is "average working time for each seven-day period,
6
+ * including overtime, not exceeding 48 hours", averaged over a reference period
7
+ * of up to four months — extensible to six by derogation and twelve by
8
+ * collective agreement.
9
+ *
10
+ * The part that defeats a per-week hour budget: **any** seven-day period, and
11
+ * **any** four-month window. A person can sit under 48h in every calendar week
12
+ * and still average over it across week boundaries, and a fixed quarterly
13
+ * reference period hides an overrun that straddles two quarters. So every limit
14
+ * here is evaluated over rolling windows anchored on the person's own
15
+ * assignment boundaries.
16
+ *
17
+ * Art 16(b) also requires paid annual leave and sick leave to be "not included
18
+ * or neutral" in the average. Counting an absent week as zero hours would drag
19
+ * a person's average down and licence a heavier following week, so neutralised
20
+ * absence shortens the window's divisor instead.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.rollingHours = exports.WEEKLY_LIMIT_CITATION = void 0;
24
+ const support_1 = require("./support");
25
+ exports.WEEKLY_LIMIT_CITATION = 'Directive 2003/88/EC Art 6(b), Art 16(b)';
26
+ function rollingHours(limits) {
27
+ return (0, support_1.fromVerdict)({
28
+ id: 'rolling-hours',
29
+ hardness: 'hard',
30
+ weight: 1,
31
+ citation: exports.WEEKLY_LIMIT_CITATION,
32
+ verdict(state, pair) {
33
+ const inst = (0, support_1.instanceOf)(state, pair);
34
+ if (!inst)
35
+ return (0, support_1.pass)('rolling-hours', 'unknown shift');
36
+ const timeline = (0, support_1.timelineFor)(state, pair.employeeId);
37
+ const range = (0, support_1.rangeOf)(inst);
38
+ const probe = { ...range, id: (0, support_1.entryIdOf)(pair), workingMinutes: inst.workingMinutes };
39
+ return timeline.withEntry(probe, (t) => {
40
+ if (limits.maxPerShiftMinutes !== undefined && inst.workingMinutes > limits.maxPerShiftMinutes) {
41
+ return over('shift', inst.workingMinutes, limits.maxPerShiftMinutes, pair.employeeId, inst.id);
42
+ }
43
+ // Daily cap: the ordinary limit, or the extended one when an
44
+ // averaging window is configured and still holds.
45
+ if (limits.maxPerDayMinutes !== undefined) {
46
+ const dayTotal = t.maxWorkingMinutesInAnyWindow(support_1.MINUTES_PER_DAY, windowFor(range, support_1.MINUTES_PER_DAY));
47
+ const cap = limits.maxPerDayExtendedMinutes !== undefined && dayAverageHolds(t, limits, range)
48
+ ? limits.maxPerDayExtendedMinutes
49
+ : limits.maxPerDayMinutes;
50
+ if (dayTotal > cap)
51
+ return over('day', dayTotal, cap, pair.employeeId, inst.id);
52
+ }
53
+ if (limits.maxPerWeekAbsoluteMinutes !== undefined) {
54
+ const span = 7 * support_1.MINUTES_PER_DAY;
55
+ const weekTotal = t.maxWorkingMinutesInAnyWindow(span, windowFor(range, span));
56
+ if (weekTotal > limits.maxPerWeekAbsoluteMinutes) {
57
+ return over('week', weekTotal, limits.maxPerWeekAbsoluteMinutes, pair.employeeId, inst.id);
58
+ }
59
+ }
60
+ for (const average of limits.rollingAverages ?? []) {
61
+ const span = average.windowDays * support_1.MINUTES_PER_DAY;
62
+ const breach = worstAverageBreach(state, t, pair.employeeId, average.maxMinutes, span, range, limits);
63
+ if (breach !== null) {
64
+ const label = average.label ?? `${(0, support_1.h)(average.maxMinutes)}/${average.windowDays}d`;
65
+ return (0, support_1.fail)('rolling-hours', 'hard', `employee "${pair.employeeId}" would work ${(0, support_1.h)(breach.worked)} in some ${average.windowDays}-day window, over the ${label} limit of ${(0, support_1.h)(breach.allowance)}`, {
66
+ actual: breach.worked,
67
+ required: breach.allowance,
68
+ unit: 'minutes',
69
+ citation: exports.WEEKLY_LIMIT_CITATION,
70
+ });
71
+ }
72
+ }
73
+ if (limits.maxPerPeriodMinutes !== undefined) {
74
+ const total = t.workingMinutesIn({ start: 0, end: state.ctx.periodDays * support_1.MINUTES_PER_DAY });
75
+ if (total > limits.maxPerPeriodMinutes) {
76
+ return over('period', total, limits.maxPerPeriodMinutes, pair.employeeId, inst.id);
77
+ }
78
+ }
79
+ return (0, support_1.pass)('rolling-hours', 'within every configured working-time limit', {
80
+ unit: 'minutes',
81
+ citation: exports.WEEKLY_LIMIT_CITATION,
82
+ });
83
+ });
84
+ },
85
+ });
86
+ }
87
+ exports.rollingHours = rollingHours;
88
+ function over(scope, actual, required, employeeId, instanceId) {
89
+ return (0, support_1.fail)('rolling-hours', 'hard', `employee "${employeeId}" would work ${(0, support_1.h)(actual)} per ${scope} taking "${instanceId}", over the ${(0, support_1.h)(required)} limit`, { actual, required, unit: 'minutes', citation: exports.WEEKLY_LIMIT_CITATION });
90
+ }
91
+ /** Windows overlapping `range` are the only ones the new shift can worsen. */
92
+ function windowFor(range, span) {
93
+ return { start: range.start - span, end: range.end + span };
94
+ }
95
+ /** Whether the extended daily cap is earned by the averaging window still holding. */
96
+ function dayAverageHolds(timeline, limits, range) {
97
+ if (limits.dayAverageWindowDays === undefined || limits.maxPerDayMinutes === undefined)
98
+ return false;
99
+ const span = limits.dayAverageWindowDays * support_1.MINUTES_PER_DAY;
100
+ const worst = timeline.maxWorkingMinutesInAnyWindow(span, windowFor(range, span));
101
+ return worst <= limits.maxPerDayMinutes * limits.dayAverageWindowDays;
102
+ }
103
+ /**
104
+ * Worst breach of a rolling average across the windows the new shift can worsen,
105
+ * with the allowance reduced *per window* for neutralised absence.
106
+ *
107
+ * Art 16(b) makes paid leave and sick leave neutral in the average. Treating
108
+ * them as zero-hour days would let a fortnight off buy a 96-hour week, so the
109
+ * absent time is removed from each window's allowance — but only the absence
110
+ * that actually falls inside that window: sick leave in March must not shrink a
111
+ * January week's budget.
112
+ *
113
+ * Worked minutes and neutral minutes are both piecewise-linear in the window's
114
+ * start, with breakpoints at entry and absence boundaries, so the extreme lies
115
+ * on a window whose edge touches one of those boundaries (or the probe bounds).
116
+ */
117
+ function worstAverageBreach(state, timeline, employeeId, maxMinutes, span, range, limits) {
118
+ const bounds = windowFor(range, span);
119
+ const kinds = limits.neutraliseAbsenceKinds;
120
+ const neutral = kinds?.length
121
+ ? (state.ctx.absences.get(employeeId) ?? []).filter((a) => a.kind !== undefined && kinds.includes(a.kind))
122
+ : [];
123
+ if (neutral.length === 0) {
124
+ const worked = timeline.maxWorkingMinutesInAnyWindow(span, bounds);
125
+ return worked > maxMinutes ? { worked, allowance: maxMinutes } : null;
126
+ }
127
+ const starts = new Set([bounds.start, bounds.end - span]);
128
+ for (const entry of timeline.entriesIn({ start: bounds.start - span, end: bounds.end + span })) {
129
+ starts.add(entry.start);
130
+ starts.add(entry.end - span);
131
+ }
132
+ for (const a of neutral) {
133
+ starts.add(a.start);
134
+ starts.add(a.end - span);
135
+ }
136
+ let worst = null;
137
+ for (const start of starts) {
138
+ const window = { start, end: start + span };
139
+ const worked = timeline.workingMinutesIn(window);
140
+ const neutralMinutes = neutral.reduce((sum, a) => sum + Math.max(0, Math.min(a.end, window.end) - Math.max(a.start, window.start)), 0);
141
+ const allowance = maxMinutes * (1 - Math.min(1, neutralMinutes / span));
142
+ const excess = worked - allowance;
143
+ if (excess > 0 && (worst === null || excess > worst.excess))
144
+ worst = { worked, allowance, excess };
145
+ }
146
+ return worst === null ? null : { worked: worst.worked, allowance: worst.allowance };
147
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Minimum interval between shift *starts* — Poland's *doba pracownicza*.
3
+ *
4
+ * Polish law defines a "worker's day" as the 24 consecutive hours from the
5
+ * start of work. Beginning work again inside that window counts as overtime
6
+ * regardless of how much rest was taken in between, so a person who finishes at
7
+ * 14:00 and starts again at 06:00 the next morning has had 16 hours off — well
8
+ * clear of any rest rule — and is still inside the previous *doba*.
9
+ *
10
+ * That makes it a distinct shape from `daily-rest`: it is keyed on the distance
11
+ * between two *starts*, not on the gap between an end and the next start. No
12
+ * rest-based rule can express it, which is why it gets its own constraint
13
+ * rather than a parameter on another.
14
+ */
15
+ import type { SchedulingConstraint } from '../types';
16
+ export declare const START_INTERVAL_CITATION = "PL Kodeks pracy art. 128 \u00A73 (doba pracownicza)";
17
+ export declare function startInterval(rule: {
18
+ minMinutes: number;
19
+ }): SchedulingConstraint;
20
+ //# sourceMappingURL=start-interval.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"start-interval.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/start-interval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAe,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAGlE,eAAO,MAAM,uBAAuB,wDAAmD,CAAC;AAExF,wBAAgB,aAAa,CAAC,IAAI,EAAE;IAAE,UAAU,EAAE,MAAM,CAAA;CAAE,GAAG,oBAAoB,CAsChF"}
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ /**
3
+ * Minimum interval between shift *starts* — Poland's *doba pracownicza*.
4
+ *
5
+ * Polish law defines a "worker's day" as the 24 consecutive hours from the
6
+ * start of work. Beginning work again inside that window counts as overtime
7
+ * regardless of how much rest was taken in between, so a person who finishes at
8
+ * 14:00 and starts again at 06:00 the next morning has had 16 hours off — well
9
+ * clear of any rest rule — and is still inside the previous *doba*.
10
+ *
11
+ * That makes it a distinct shape from `daily-rest`: it is keyed on the distance
12
+ * between two *starts*, not on the gap between an end and the next start. No
13
+ * rest-based rule can express it, which is why it gets its own constraint
14
+ * rather than a parameter on another.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.startInterval = exports.START_INTERVAL_CITATION = void 0;
18
+ const support_1 = require("./support");
19
+ exports.START_INTERVAL_CITATION = 'PL Kodeks pracy art. 128 §3 (doba pracownicza)';
20
+ function startInterval(rule) {
21
+ return (0, support_1.fromVerdict)({
22
+ id: 'start-interval',
23
+ hardness: 'hard',
24
+ weight: 1,
25
+ citation: exports.START_INTERVAL_CITATION,
26
+ verdict(state, pair) {
27
+ const inst = (0, support_1.instanceOf)(state, pair);
28
+ if (!inst)
29
+ return (0, support_1.pass)('start-interval', 'unknown shift');
30
+ const timeline = (0, support_1.timelineFor)(state, pair.employeeId);
31
+ const range = (0, support_1.rangeOf)(inst);
32
+ const ownId = (0, support_1.entryIdOf)(pair);
33
+ let closest = Infinity;
34
+ for (const entry of timeline.all()) {
35
+ if (entry.id === ownId)
36
+ continue;
37
+ const distance = Math.abs(entry.start - range.start);
38
+ if (distance < closest)
39
+ closest = distance;
40
+ }
41
+ if (closest < rule.minMinutes) {
42
+ return (0, support_1.fail)('start-interval', 'hard', `employee "${pair.employeeId}" would start "${inst.id}" only ${(0, support_1.h)(closest)} after another shift's start, inside the ${(0, support_1.h)(rule.minMinutes)} working day`, { actual: closest, required: rule.minMinutes, unit: 'minutes', citation: exports.START_INTERVAL_CITATION });
43
+ }
44
+ return (0, support_1.pass)('start-interval', `starts are at least ${(0, support_1.h)(rule.minMinutes)} apart`, {
45
+ actual: closest === Infinity ? undefined : closest,
46
+ required: rule.minMinutes,
47
+ unit: 'minutes',
48
+ citation: exports.START_INTERVAL_CITATION,
49
+ });
50
+ },
51
+ });
52
+ }
53
+ exports.startInterval = startInterval;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Shared helpers for the rule-driven constraints.
3
+ *
4
+ * Every constraint in this directory needs the same four things: the person
5
+ * behind an employee record, that person's timeline, the rules that apply to
6
+ * them, and a structured verdict. Centralizing them keeps each rule file about
7
+ * its rule.
8
+ */
9
+ import type { AssignmentPair, ModelContext, RuleVerdict, SchedulingConstraint, SearchState, Severity, ShiftInstance, WorkingTimeRules } from '../types';
10
+ import type { MinuteRange } from '../time';
11
+ import type { PersonTimeline } from '../engine/timeline';
12
+ export declare const MINUTES_PER_DAY = 1440;
13
+ /** The natural person behind an employee record. */
14
+ export declare function personIdFor(ctx: ModelContext, employeeId: string): string;
15
+ /** The person's timeline, including history and every contract they hold. */
16
+ export declare function timelineFor(state: SearchState, employeeId: string): PersonTimeline;
17
+ /** Rules applying to this employee, after merging their overrides over the global set. */
18
+ export declare function rulesFor(ctx: ModelContext, employeeId: string): WorkingTimeRules;
19
+ /** The elapsed span of a shift instance. */
20
+ export declare function rangeOf(inst: ShiftInstance): MinuteRange;
21
+ /** The timeline entry id a pair would occupy, so rules can exclude it from their own lookups. */
22
+ export declare function entryIdOf(pair: AssignmentPair): string;
23
+ /** Resolve a pair to its instance, or `undefined` when the id is unknown. */
24
+ export declare function instanceOf(state: SearchState, pair: AssignmentPair): ShiftInstance | undefined;
25
+ /**
26
+ * A window of `days` centred on `range`, clamped to nothing — history lives at
27
+ * negative minutes, so windows deliberately extend before the period start.
28
+ */
29
+ export declare function windowAround(range: MinuteRange, days: number): MinuteRange;
30
+ /** Build a passing verdict. */
31
+ export declare function pass(ruleId: string, message: string, extra?: Partial<RuleVerdict>): RuleVerdict;
32
+ /** Build a failing verdict. */
33
+ export declare function fail(ruleId: string, severity: Severity, message: string, extra?: Partial<RuleVerdict>): RuleVerdict;
34
+ /** Hours, to one decimal, for human-readable messages. */
35
+ export declare function h(minutes: number): string;
36
+ /**
37
+ * Wire a rule's `verdict` into the `delta`/`explain` members the engine and the
38
+ * legacy reason strings still use, so each rule file states its logic once.
39
+ *
40
+ * `magnitude` converts a failing verdict into a breach size: local search needs
41
+ * to know a rest gap is 10 minutes short rather than merely "short", or it sits
42
+ * on a plateau with no gradient to follow.
43
+ */
44
+ export declare function fromVerdict(spec: Omit<SchedulingConstraint, 'delta' | 'explain' | 'verdict'> & {
45
+ verdict(state: SearchState, pair: AssignmentPair): RuleVerdict;
46
+ magnitude?(v: RuleVerdict): number;
47
+ }): SchedulingConstraint;
48
+ //# sourceMappingURL=support.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"support.d.ts","sourceRoot":"","sources":["../../../src/scheduling/constraints/support.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EACR,cAAc,EACd,YAAY,EACZ,WAAW,EACX,oBAAoB,EACpB,WAAW,EACX,QAAQ,EACR,aAAa,EACb,gBAAgB,EACnB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGzD,eAAO,MAAM,eAAe,OAAO,CAAC;AAEpC,oDAAoD;AACpD,wBAAgB,WAAW,CAAC,GAAG,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAEzE;AAED,6EAA6E;AAC7E,wBAAgB,WAAW,CAAC,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,GAAG,cAAc,CAElF;AAED,0FAA0F;AAC1F,wBAAgB,QAAQ,CAAC,GAAG,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,GAAG,gBAAgB,CAEhF;AAED,4CAA4C;AAC5C,wBAAgB,OAAO,CAAC,IAAI,EAAE,aAAa,GAAG,WAAW,CAExD;AAED,iGAAiG;AACjG,wBAAgB,SAAS,CAAC,IAAI,EAAE,cAAc,GAAG,MAAM,CAEtD;AAED,6EAA6E;AAC7E,wBAAgB,UAAU,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,cAAc,GAAG,aAAa,GAAG,SAAS,CAE9F;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,GAAG,WAAW,CAG1E;AAED,+BAA+B;AAC/B,wBAAgB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,GAAE,OAAO,CAAC,WAAW,CAAM,GAAG,WAAW,CAEnG;AAED,+BAA+B;AAC/B,wBAAgB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,GAAE,OAAO,CAAC,WAAW,CAAM,GAAG,WAAW,CAEvH;AAED,0DAA0D;AAC1D,wBAAgB,CAAC,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEzC;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CACvB,IAAI,EAAE,IAAI,CAAC,oBAAoB,EAAE,OAAO,GAAG,SAAS,GAAG,SAAS,CAAC,GAAG;IAChE,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,cAAc,GAAG,WAAW,CAAC;IAC/D,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,GAAG,MAAM,CAAC;CACtC,GACF,oBAAoB,CActB"}
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ /**
3
+ * Shared helpers for the rule-driven constraints.
4
+ *
5
+ * Every constraint in this directory needs the same four things: the person
6
+ * behind an employee record, that person's timeline, the rules that apply to
7
+ * them, and a structured verdict. Centralizing them keeps each rule file about
8
+ * its rule.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.fromVerdict = exports.h = exports.fail = exports.pass = exports.windowAround = exports.instanceOf = exports.entryIdOf = exports.rangeOf = exports.rulesFor = exports.timelineFor = exports.personIdFor = exports.MINUTES_PER_DAY = void 0;
12
+ const state_1 = require("../engine/state");
13
+ exports.MINUTES_PER_DAY = 1440;
14
+ /** The natural person behind an employee record. */
15
+ function personIdFor(ctx, employeeId) {
16
+ return ctx.personIdOf.get(employeeId) ?? employeeId;
17
+ }
18
+ exports.personIdFor = personIdFor;
19
+ /** The person's timeline, including history and every contract they hold. */
20
+ function timelineFor(state, employeeId) {
21
+ return state.timelines.for(personIdFor(state.ctx, employeeId));
22
+ }
23
+ exports.timelineFor = timelineFor;
24
+ /** Rules applying to this employee, after merging their overrides over the global set. */
25
+ function rulesFor(ctx, employeeId) {
26
+ return ctx.rulesByEmployee.get(employeeId) ?? ctx.rules;
27
+ }
28
+ exports.rulesFor = rulesFor;
29
+ /** The elapsed span of a shift instance. */
30
+ function rangeOf(inst) {
31
+ return { start: inst.startMinute, end: inst.endMinute };
32
+ }
33
+ exports.rangeOf = rangeOf;
34
+ /** The timeline entry id a pair would occupy, so rules can exclude it from their own lookups. */
35
+ function entryIdOf(pair) {
36
+ return (0, state_1.timelineEntryId)(pair.employeeId, pair.shiftInstanceId);
37
+ }
38
+ exports.entryIdOf = entryIdOf;
39
+ /** Resolve a pair to its instance, or `undefined` when the id is unknown. */
40
+ function instanceOf(state, pair) {
41
+ return state.ctx.instanceById.get(pair.shiftInstanceId);
42
+ }
43
+ exports.instanceOf = instanceOf;
44
+ /**
45
+ * A window of `days` centred on `range`, clamped to nothing — history lives at
46
+ * negative minutes, so windows deliberately extend before the period start.
47
+ */
48
+ function windowAround(range, days) {
49
+ const span = days * exports.MINUTES_PER_DAY;
50
+ return { start: range.start - span, end: range.end + span };
51
+ }
52
+ exports.windowAround = windowAround;
53
+ /** Build a passing verdict. */
54
+ function pass(ruleId, message, extra = {}) {
55
+ return { ruleId, pass: true, severity: 'soft', message, ...extra };
56
+ }
57
+ exports.pass = pass;
58
+ /** Build a failing verdict. */
59
+ function fail(ruleId, severity, message, extra = {}) {
60
+ return { ruleId, pass: false, severity, message, ...extra };
61
+ }
62
+ exports.fail = fail;
63
+ /** Hours, to one decimal, for human-readable messages. */
64
+ function h(minutes) {
65
+ return `${(minutes / 60).toFixed(1)}h`;
66
+ }
67
+ exports.h = h;
68
+ /**
69
+ * Wire a rule's `verdict` into the `delta`/`explain` members the engine and the
70
+ * legacy reason strings still use, so each rule file states its logic once.
71
+ *
72
+ * `magnitude` converts a failing verdict into a breach size: local search needs
73
+ * to know a rest gap is 10 minutes short rather than merely "short", or it sits
74
+ * on a plateau with no gradient to follow.
75
+ */
76
+ function fromVerdict(spec) {
77
+ const magnitude = spec.magnitude ?? defaultMagnitude;
78
+ return {
79
+ ...spec,
80
+ verdict: spec.verdict,
81
+ delta(state, pair) {
82
+ const v = spec.verdict(state, pair);
83
+ return v.pass ? 0 : Math.max(1, magnitude(v));
84
+ },
85
+ explain(state, pair) {
86
+ const v = spec.verdict(state, pair);
87
+ return v.pass ? null : v.message;
88
+ },
89
+ };
90
+ }
91
+ exports.fromVerdict = fromVerdict;
92
+ /** Shortfall or excess against the bound, when both are known; 1 otherwise. */
93
+ function defaultMagnitude(v) {
94
+ if (v.actual === undefined || v.required === undefined)
95
+ return 1;
96
+ return Math.max(1, Math.abs(v.required - v.actual));
97
+ }