ShiftCircle

ShiftCircle — Rules Engine Design (Drools)

Status: Draft v0.5 · 2026-11-19 · replaces the custom-engine design (see ADR-012)

1. Goals

  1. A non-technical person (HR, labour relations, a senior supervisor) can read every rule in plain language and change values (limits, severity, override, effective dates) without a developer.
  2. Rules run on an established, standards-based engine: Drools (Apache KIE).
  3. A change can’t break the system or quietly weaken a safeguard. Every change is validated, tested, approved, versioned and reversible.

2. The approach in one picture

flowchart LR
    subgraph Admin["Rules screen (non-technical)"]
        G[Friendly grid per rule table<br/>labels · dropdowns · help text<br/>plain-language preview]
        X[Download / upload Excel<br/>FUTURE WORK: not built]
    end
    subgraph API["api container"]
        V[Validate values]
        C[Compile with Drools<br/>templates + rows → rules]
        T[Run regression scenarios<br/>+ dry run on current roster]
        P[Approve & publish<br/>maker / checker]
        K[(Live Drools KieBase<br/>hot-swapped)]
        F[Fact builders (Java)<br/>rest gaps · rolling hours<br/>consecutive runs · 16 h shifts · period hours]
    end
    DB[(PostgreSQL<br/>rule tables + versions)]
    G --> V --> C --> T --> P --> K
    X <--> DB
    G <--> DB
    P --> DB
    F --> K

3. Who does what

Layer Written by What it does
Fact builders (Java) Developers Build the after-change schedule and compute the derived facts a rule needs: RestGap (hours between two shifts, previous shift kind), RollingHours (hours in any 24 h / 7 d), ConsecutiveRun (days, 12 h shifts, nights), LongShiftCount (16 h shifts in 7 / 28 days), DaysOffRun, PeriodHours (hours so far in the week and pay period, for overtime). Time maths is hard to get right in rule syntax, so it lives in tested Java.
Rule templates (Drools) Developers, once per rule table The technical “when … then …” pattern for a kind of rule, e.g. when a RestGap after shift kind X is less than N hours, record a result with severity S. Hidden from non-technical users.
Decision-table rows (data) Non-technical rules admins One row = one rule. Columns are plain-language fields: After shift type · Minimum rest (hours) · Result · Override allowed · Message.

Drools is built for exactly this split: decision tables generate rules from rows of data, each row combined with a template. Each row becomes one rule, and each column is a condition, an action or another rule attribute.

4. What a non-technical admin sees

Each rule table is shown as a simple grid. Example, Rest between shifts:

Rule After this kind of shift… …the officer needs at least (hours) off If not Override Message shown
U-01 Any shift (within any 24 h) 8 Block Emergency only Less than 8 hours’ rest in 24 hours (Employment Act minimum).
U-02 Regular shift 12 Warn — Less than the 12-hour rest target between shifts.
U-03 16-hour shift 12 Block Emergency only Needs 12 hours off after a 16-hour shift. Dormant: keyed to the retired L16 template, so it never fires in the demo data (see 05-union-rules.md).
U-04 Overtime extension of 4 h or more 10 Warn — Short rest after a long overtime extension.

Under each row the screen shows a generated plain-language sentence:

“After a 16-hour shift, an officer must have at least 12 hours off before their next shift. If not, the change is blocked; a supervisor may override only in an emergency, with a reason.”

The admin can change numbers, choose from dropdowns (shift kinds, Block / Warn / Info, override options), switch a row on or off, set an effective date, and add a row (e.g. a new rest rule after a 12-hour night). They can’t edit the technical template. That’s what keeps the system safe.

Excel round-trip (future work, not built in the prototype; docs/10 §8): the design is that any table can be downloaded as a standard Drools spreadsheet decision table (.xlsx) to review with labour relations or the union, and uploaded back. Uploads go through the same validate → test → approve pipeline (§6). The spreadsheet’s technical header area (Drools’ RuleSet and RuleTable keywords) is generated and protected.

5. Rule tables

Rule table Rows (from 05-union-rules.md) Columns the admin edits
Rest between shifts U-01 to U-04 After shift kind · window · minimum hours · result · override · message
Maximum hours U-05, U-06, U-14 Window (24 h / 7 d / consecutive) · max hours · result · override
Consecutive work U-08 to U-10 What’s counted (days / 12 h shifts / nights) · max · result when scheduled · result when overtime
16-hour shifts U-11 Window (days) · max 16 h shifts · result
Days off U-12 Days off required · within how many days (the “a break of 24 h or less does not count” clause is fixed at 24 h in the fact builder)
Pay classification P-01 to P-06 Threshold window (week / pay period) · threshold hours · whether paid leave counts · rate bands (hours, pay code, multiplier) · minimum hours
Overtime ranking O-01 to O-04 Sort order (OT hours this quarter, seniority…) · skip if (rule result) · voluntary/ordered limits
Shift types L-01, S-03 Shift code · start time · length · units allowed (ADR-015)
Who can work a post (release v1.3) R-01, R-02 Post (supervisor post or officer post, from the unit’s kind) · who can work it (officers or supervisors) · acting supervisor may work it with a warning (R-01) · result · override

Staffing and qualification checks (per unit) are maintained on the facility setup screen, not in the decision tables.

5a. Publish-time validation the builders require (review F4)

Some columns are only meaningful for the values the fact builders actually produce. A row whose windowHours is 48, for example, would never fire: the builders emit 24-hour, 168-hour and pay-period facts only. A rule that can never fire is worse than a broken one, because the admin believes it is protecting people. The build step (writer: rules publish pipeline, step 11) must reject such rows with a plain-language message (“Window must be 24 or 168 hours”) before a version can be submitted, and the same validation belongs in TemplateColumns where it can be expressed there (for example, a warning level at or above the ceiling is refused).

The rest table’s minimum rest is bounded at both ends: 8 to 24 hours (8 is the legal floor; the fact builders measure rest in a 24-hour window, so a larger minimum would never fire). A list column accepts at most 16 values, and a build report lists at most 20 problems, then says how many it left out. Validation itself is total: a row whose stored value has the wrong type is reported as a row problem, never allowed to throw into an HTTP 500.

The ranges every numeric column is held to (the PUT refuses a value outside the range and the build validator refuses a stored one):

Table Column Range
Rest between shifts windowHours exactly 24
  minRestHours 8–24
  minExtensionMinutes 0–1440
Maximum hours windowHours 24 or 168
  maxHours above 0, at most 168 and at most the window
  warnAtHours 0–168 and below maxHours
Consecutive work max 1–366
16-hour shifts maxIn7Days 1–28
  maxIn28Days 1–366 and at least maxIn7Days
Days off daysOff 1–7
  withinDays exactly 7
  minBreakHours 0–24
Pay classification thresholdHours above 0, at most 168
  otRate 1.0–3.0
  ignoreUnderMinutes 0–120
Shift types allowedLengths only 8, 12, 16
  requireUnitFlagFor only 12, 16
Who can work a post postKind SUPERVISION or LINE
  allowedPositions at least one of CO, CS, and not both (a row every position may work can never fire)
  actingQualification ACTING_SUP or empty: only the supervisory qualification may soften R-01, never a common one
Every Must rule (docs/05 §3) result, override policy, on/off as published: a Block cannot become a warning and a Must rule cannot be switched off (the screen locks these controls)

6. Safe change pipeline

  1. Edit: a rules admin changes rows in a draft version (an Excel upload is future work, not built).
  2. Validate: types, ranges and sanity checks (e.g. minimum rest must be between 8 and 24 hours; a Block rule can’t be switched to Info without a reason). Errors are shown in plain language.
  3. Compile: Drools builds a staging rule base from templates plus rows. Compilation problems are translated into “row 3, column Minimum rest: must be a number”.
  4. Test: the automated regression scenarios run (the pipeline runs T1–T6 and the boundary cases; T7–T14 are API/database tests, 10-testing.md §4), plus a dry run against the current roster: “This change adds 14 warnings and 2 blocks on the published schedule.”
  5. Approve (maker/checker): a second person with the approver role reviews the before/after comparison and the impact, then publishes. One person can’t both edit and publish.
  6. Publish: the new rule base is swapped in live, with no restart. The version is stored with who, when, why and the effective date.
  7. Roll back: any earlier version can be republished through the same approval.

Baseline exception. The seed migrations publish the baseline row set directly: V2 as version 1, V6 as version 2, V12 as version 3 and the posts migration (release v1.3) as version 4, with created_by/approved_by NULL, a recorded change_reason and no audit_event row. This is the only path that skips maker/checker; every later version goes through steps 1–7. V6’s version 2 adds D12/N12 to U-02’s kind list and says U-10 is “overnight (00-12 or 19-07)” because the counter still includes A12 00–12 night-block shifts as in version 1. V12’s version 3 copies version 2 unchanged and adds U-16 (Warn, acknowledge): an 8-hour officer assigned to a night shift. The planner never makes that assignment — 8-hour officers work day or evening, nights are the 12-hour crews — so U-16 exists for a supervisor’s manual assignment. Version 2 stays in the table as history. V13 is not a rule-set version: it only retires the L16 template (active=false, ADR-029). Every 16 h rule (L-01, S-03, U-03/U-04/U-05/U-11) and the extension tests stay in the table, but U-03 and U-11 are dormant: their rows key on L16, so they never fire on a 12 h shift plus an extension (U-04 and U-05 still do). The tests stay because a “16 h shift” in the rules means a 12 h shift plus an extension.

Version 4: who can work a post (release v1.3). The V18__rule_set_v4_posts.sql migration adds a ninth table, POSTS (“Who can work a post”, template post-eligibility.drt), copies version 3 unchanged and adds R-01 (Block, no override: a supervisor post needs a supervisor; an officer who holds the ACTING_SUP qualification on the shift’s date is a Warn to acknowledge instead) and R-02 (Warn, acknowledge: a supervisor on an officer post). The fact (PostEligibilityFact) is built for the proposed shift only, from the person’s position (employee.classification), the qualifications they hold that day and the unit’s kind (SUPERVISION is a supervisor post, every other kind an officer post); it is not part of ShiftFact, so no other builder changed. The board’s rule check, the planner’s generator check, the draft edits and the commit check all pass it. Version 4 itself moved no pin (the datasets had no supervisors then); since release v1.3 S4 every dataset has supervisors on two supervisor posts, and the planner never cross-covers (S3), so neither rule fires on a generated row: they fire on a manual assignment, a draft edit or a proposal (ADR-031). Version 3 stays as history. The build’s dry run builds the same post fact for every shift on the published roster, so a POSTS edit reports what it changes before an approver sees it. The planner’s one-time lookup fails closed: a person or unit it cannot resolve reads as an unknown position on a supervisor post, which R-01 blocks.

7. Runtime evaluation

ScheduleChange ─▶ FactBuilders (Java) ─▶ insert facts into a Drools session
                                         ─▶ fire rules (decision tables)
                                         ─▶ collect RuleResult facts
                                         ─▶ API returns PASS / WARN / BLOCK + messages + evidence shifts

8. Technology and compatibility

Item Choice
Engine Drools 10.x (Apache KIE, currently incubating), embedded as libraries through the KIE API. We don’t use the KIE Spring Boot starter.
Rule authoring Rule templates plus data rows (drools-templates); spreadsheet decision table import/export (drools-decisiontables; future work, not built)
Java / Spring Java 21 LTS + Spring Boot 4.x, pending a Day 1 compatibility check (see below)

Compatibility note: the Apache KIE 10.2.0 release notes list an upgrade to Spring Boot 3.5.10 and Java 21 support. Our earlier target (Java 25 + Spring Boot 4.1) is newer than what KIE says it has tested. Because we embed Drools as plain libraries rather than through its Spring integration, Spring Boot 4.x should work, but we’ll prove it with a Day 1 spike. Fallback: Spring Boot 3.5.x, which is past its free open-source support, so that’s a governance trade-off to record.

9. Trade-offs we’re accepting