Skip to content

Policy step reference

This page lists what a policy step can declare. It also lists what each stage gives a step through ctx, and what an exporter is given. Use it while you write a step. Write a policy step walks through one from start to finish.

A policy package’s main.lua returns a table of steps. Each step is a table with these parts:

Part
stageWhere it runs (the stages). Required.
windowFor allocate and accrue: day (the default), week or period. It can also be a repeating window of whole days, { every = "2w", starts = "2026-01-05" }. For allocate only, it can be 24h. A window parameter in the policy overrides it.
only_where_window_endsFor an allocate step on a window of days. true runs the step only in the pay period that holds the window’s last day. There it sees the whole window (a window longer than a pay period).
looks_backFor an allocate step that reads the weeks before its pay period. It is how far back the step looks. Give it as a number of days or as a function of the parameters, function(p) return 7 * p.back end (averages of weeks).
reads_balancesFor an allocate step: true lets it read ctx:balance(category) (balances in an allocate step). Publishing refuses it on a step of another stage.
paramsThe parameters it takes (parameters).
check(p)Optional. It says what the parameters must hold together. It returns nil, or words saying what is wrong: "it takes over and to, or tiers, not both".
reasonsThe words for its rules, by name: { over = "over {over} in the {window}" } (reasons).
run(ctx, p)The step. ctx is what its stage gives it. p is its parameters with every default filled in. p is read only. A step that changes it fails.

Steps of one stage run in the order the policy gives them. A side parameter says which side the step works out (pay and bill). Without one, it is pay.

A step only asks for changes through ctx. The engine makes each one. The engine stamps it with the step’s id and the layers that gave it. After every step, the engine checks that the step kept to its stage’s rules. A step that errors, or asks for what cannot be done, stops the ledger. The error starts with the step’s id and what it uses: step explode (broken/explode): ... kaboom.

A policy step whose uses names an exporter is refused: step csv uses standard/csv: an exporter, not a policy step.

Each entry of params is a type’s name (max = "duration") or a table:

Key
typeA type’s name, or a list of names any of which will do.
requiredThe policy must give it.
defaultIts value when the policy gives none.
one_ofThe values it may be.
ofThe type of each item of a list, or each value of a map.
fieldsA record’s fields, each declared the same way.

These are the types:

  • string, integer, number and boolean.
  • duration: for example "7h 30m". It is never negative.
  • wall_time: for example "19:00".
  • date.
  • month_day: for example "01-31".
  • weekday: for example "monday".
  • period: a period.
  • list, map, record and any.
params = {
over = { type = "duration", required = true },
to = { type = "string", default = "overtime" },
tiers = { type = "list", of = { type = "record", fields = {
over = { type = "duration", required = true },
to = { type = "string", required = true },
} } },
},

Parameters are checked when a layer is added and when a package is published. Take a step with params. A parameter it does not declare, a value of the wrong type, or a combination its check refuses is rejected. The rejection names the step, the layers that gave it and the parameter. A step with no params takes whatever parameters it is given. An empty params = {} takes none but window and side, which every step takes. A ledger checks them again before it runs the step.

A step that asks for a change names the rule that fired, { rule = "over" }. It can add any values of its own ({ rule = "past", scheduled = ms }). The engine words it from the step’s reasons. Each {name} is filled from the values given, then the step’s parameters, then the window’s kind. {name:duration} shows milliseconds as a duration. A step may pass its own words as text instead.

A stamp reads <step id> [<layers>]: <what was done>: <the reason>, for example weekly [company rev 1]: moved 1h from work to overtime: over 40h in the week.

Beside its words, every reason carries a stable key and the values that fill it in. An app can use them to show the reason in the person’s own language, from its own wording of each key. A step’s key is <package>/<step>.<rule>. The rule over of plant/long_day is plant/long_day.over. Its values are those its words name, each as the step gave it or as its parameter is written. A value shown as a duration is milliseconds. window is the window’s code: day, week, period, 24h, or a repeating window’s length, 2w. A step that passes its own words as text has no key. The same key and values come with a refused leave request, a subject an approve step blocked, and an exception raised by the rule of a step.

Time is whole milliseconds. Instants are milliseconds since 1970, and durations are milliseconds. A value that is not a whole number of milliseconds is an error.

FunctionReturns
time.duration(text)A duration as milliseconds: time.duration("7h 30m"), "15m", "40h".
time.hours(h), time.minutes(m)h hours or m minutes as milliseconds.
time.money(ms, per_hour)Minor units for that much time at that hourly amount. The part below one is dropped.

Give duration parameters as text (over = "40h") and read them with time.duration.

A ledger runs the stages in this order. Without a step in a stage, the engine does what the last column says. A stage with no step costs nothing. The standard steps have a step for each stage, and the cookbook has a recipe for each.

StageDecidesWithout a step
holidayWhich day each holiday is observed on.As each holiday’s observed setting says.
leaveWhether a leave request can be approved, and who approves it.A request stands as its approvals have it.
pairWhich punches count, and their direction, before pairing.Every effective punch as it is.
matchWhich scheduled shift each segment is of.The first shift work starts within, or up to shifts.early before.
assignWhich assignment work goes to when several fit.assignment_ambiguous.
attributeWhich workday a shift’s time belongs to.The workday it starts in.
timeEffective start and end times (rounding).Raw times.
rateWhich of several equally close rates applies.rate_ambiguous, and no rate.
allocateMoving time between categories; counts and money.Lines stay in their kind’s category.
accrueTime off earned and forfeited.Nothing earned.
exceptionsExceptions about each workday.None but the engine’s own.
lateWhether each change to a closed period is adjusted or refused. Runs outside a ledger.close.late_changes, for every change alike.
approveWhat blocks a subject’s approval, and who approves each stage. Runs outside a ledger.The approval rule’s blocked_by_exceptions and approvers.

No policy changes how time becomes decimal hours. Each line’s fraction is carried forward to the next, over the whole period, in the order lines are paid. A policy chooses only the number of decimals (0 to 9). Every threshold is decided on exact time, never on decimal hours.

These are available in every stage:

ctx.windowThe window the step runs on. It has kind (day, week, period, 24h), and first and last (dates, "2026-10-05"). For a 24h window it also has start and end, its instants. It has applies when the step’s layer applies on only some of the window’s days. Then applies is the set of dates the layer applies on (layers apply day by day). applies is absent when the layer applies on every day. Give it as a filter’s days to count only those days.
ctx:day(date)The workday’s schedule. It is nil outside the ledger’s calendar. It has date, and start (when the workday starts). It has off: off, leave or holiday where an override took the day off. It has holidays (each id and name) and shifts (each id, start, end, values). It has scheduled, the time of the shifts, in milliseconds. It has leave: each leave request for the day that is not cancelled. Each has request, category, time and state (approved, rejected or pending). See schedules.
ctx:person(date)The person that day (people). It has employed, hired (the latest hire on or before the day), first_hired, terminated (if after the latest hire), on_leave_since and days_employed (from the latest hire, while employed). Its dates are text. attributes holds exempt, state, and whatever the tenant records. It has unlinked (unlinked people), and employer and worker (employers). orgs gives, by hierarchy, the organization they are in. It has id, name, labels, external_ids and metadata, with its chain. The chain has the organization itself first and the root last, as the tree was that day. location has id, name, zone, jurisdiction, values, labels, external_ids and metadata (where a person is). What is not known is nil.
ctx:other_records(first, last)The worker’s other records in the tenant, each with its time over those days as last worked out. Each has person, employer, time (by category, in milliseconds) and total. It is for rules across employers (workers). The time is read with the record’s own facts, from the same cut. A step that asks for days before it has them read again from there.
ctx:tenant()The tenant’s metadata (tenants), such as a contract’s terms. A scenario sets it under [tenant].
ctx:at(date, "19:00")The instant of a wall time on a date, in the zone in force that day.
ctx:weekday(date), ctx:add_days(date, n)ctx:weekday gives a date’s day of the week. ctx:add_days gives the date n days after (or before) it.
ctx:period(spec, at)A period as of at. at is a date or an instant in milliseconds (default the window’s first day). It is nil where the period cannot exist (an anniversary year before any hire). spec is any value in the Periods table there. Its methods are in periods in a step.
ctx:shifts_as_of(date, at)The shifts of the workday date (each id, start, end, values) as the schedule stood at the instant at, in milliseconds. Only the overrides stored by then count. A rule can tell what a notice period began with from what the schedule says now.
ctx:schedule_changes(date)The overrides of that workday, in the order they were stored (ties by id). It is empty where there are none. Each has id, kind (off, leave, holiday, replace or extra), stored (the instant it was stored, in milliseconds), by and reason.
ctx:exception(kind, id, detail)Every stage but holiday, rate, late and approve. It raises an exception named kind. The exception is about segment id in time and exceptions, line id in allocate and accrue, or the day (id 0). It is listed with the ledger like the engine’s own. It can be followed up. It goes away when the facts no longer make the step raise it.

Whether a day of leave, or being exempt, changes anything is the policy’s to say. The standard no_show step skips a day with approved leave. A step of your own can read employment:

M.daily_nonexempt = {
stage = "allocate", window = "day",
run = function(ctx, p)
if ctx:person(ctx.window.first).attributes.exempt then return end
local over = ctx:time_in({ worked = true }) - time.duration("8h")
if over > 0 then ctx:move_latest(over, { worked = true }, "overtime", "over 8h, not exempt") end
end,
}

ctx:period(spec, at) works a period out as of a date or an instant in milliseconds, in a step of any stage. A step takes a period as a parameter (type = "period") and passes its value to ctx:period, or builds a spec itself. The kinds of period are in the Periods table.

start, finishThe period’s first and last instant, in milliseconds.
first, lastThe first and last dates it holds any of.
:stretches()Each stretch of it: start, finish, first, last.
:dates()The dates it holds any of.
:contains(date or instant)Whether it holds that date or instant.
:overlap(start, finish)What it holds between two instants.
:union(q), :intersect(q), :minus(q)Combined with another period.
:next(), :previous(), :shift(n)For a repeating period or one of the engine’s calendars. They give the occurrence after, the one before, or n occurrences on.
local year = ctx:period({ every = "1y", starts = "01-01" }, ctx.request.first)
local days = #ctx:period({ ranges = { { from = first, to = last } } }):dates()

ctx:attestation(date), in allocate and exceptions steps, gives the break attestation for a workday of the window, or nil when the day has none. A date outside the window stops the step with an error. Its breaks list the breaks not taken as due. Each has break (meal or rest), number, issue (missed, short, late or waived) and reason. The standard attested_break_premium, attested_meal_waiver and attestation_required steps read it. The break attestation recipe shows one.

ctx:shifts_as_of(date, at) reads the schedule as it stood at an instant. So a rule on notice can compare a day’s shifts then with its shifts now. The predictive scheduling recipe does so.

Runs once per ledger, before anything reads the calendar.

ctx.holidaysEach holiday on the ledger’s calendar days or a week either side. Each has id, holiday, name, date, weekday, and observed (where its own setting puts it).
ctx:observe(id, date, why)Observes it on date (within a week of the day), or not at all (nil).

Use it for: a Saturday holiday observed on the Friday before, or not at all, as a contract says, from one holiday list.

Runs once per ledger on each standing leave request with a day near the period.

ctx.requestid, category, days (each date and time), first, last, time, recorded, by, comment, values, state, stage.
ctx:balance(category)The pay side’s balance at the start of the pay period of the request’s first day (ctx.balance_on).
ctx:refuse(why)Its approval cannot pass: state refused.
ctx:exception(kind, 0, detail)An exception about the request, at its first day’s start.
ctx:route(stage, approver, why)Sends a stage to another approver.

A leave step asks for what it needs. Nothing is handed to it that it does not ask for. These calls read balances and the person’s other requests through the engine. period is a value from ctx:period (periods in a step):

ctx:balance_after(category)What the request would leave of an accrual category, in milliseconds. It starts from the balance at the start of the pay period of the request’s first day. It adds the hand adjustments and hours entered dated from then through the request’s last day. It takes off the time of every standing request (not rejected or refused) recorded before this one that draws on the category, and the request’s own. What the pay period’s accrue steps make is counted too, when the step makes it whatever is decided of leave. Such a step reads none of these: the period’s lines, counts or money, the calendar’s days, or a balance moved within the period (a grant on a fixed day, a carryover limit as the period opens). A step that reads any of them, such as earning on the hours of the period, is not counted. Requests are decided in recorded order (two recorded at one instant, by id). Every ledger and the leave API decide each one the same way.
ctx:balance_changes(category, direction, amount, period)The changes dated on a day the period holds that moved the balance "below" (lowered it) or "above" (raised it) and left it beyond amount, in order. Each has date, kind (leave, adjustment, earned, forfeited, paid_out, used), id and the balance it left. A change is a fact, not a day. A three-day request is one change, dated its first day. The balance the period opens with is no change. # counts them.
ctx:requests(period)The person’s other requests with a day in the period, for a rule about overlap, each with its state. Take a request recorded before this one that starts by the end of its pay period. It has the state the policy’s leave steps decided (refused, wherever it is dated). Any other has the state its approvals give it.
ctx:leave_taken(categories, period)The leave of those pay categories on the days the period holds any of. It counts this request and every request recorded before it that stands. It gives time (milliseconds) and days (each date and time, in date order). It is what an entitlement rule counts.
ctx:earned(category, period)What accrue steps earned of an accrual category on the days the period holds any of. It counts only what was earned before the pay period of the request’s first day, as the ledgers have it. It is in milliseconds. Hand adjustments are not earned. An accrual category that earns an hour for each hour worked, and that no pay category uses, keeps the hours worked that an eligibility rule reads.

To flag a request the second time in a year that accruals take paid time off over 120 hours:

run = function(ctx, p)
local year = ctx:period({ every = "1y", starts = "01-01" }, ctx.request.first)
local over = ctx:balance_changes("pto", "above", time.duration("120h"), year)
if #over >= 2 then
ctx:exception("pto_over_120h", 0, "over 120 hours twice this year")
end
end

Use it for: no more leave than the balance, no vacation in a blackout week, notice required ahead, long leave approved by a director.

Runs on each workday with punches, before they are paired, from a week before the period to a week after.

ctx.punchesThe workday’s effective punches: id, punch, at, kind, punched, device, values, and ignored or close where marked.
ctx.before, ctx.afterThe punches either side of the workday’s.
ctx:ignore(id, why)The punch does not count (a duplicate).
ctx:direction(id, kind, why)Gives a punch its direction.
ctx:close(id, at, why)The work the punch starts ends at at, if nothing ended it before: an automatic clock-out.

The engine pairs the punches as marked and stamps each segment a mark touches. The punches stay as recorded. Use it for: duplicates within a lockout, a direction for punches of unknown direction, an automatic clock-out after the longest shift, joining an out and an in a moment apart.

Runs on each workday with segments.

ctx.segmentsEach with shift (the engine’s pick) and candidates (the shifts of its workday and the workdays either side).
ctx:match(id, shift_id, why)The segment is of that shift (nil: none), stamped where it changes.

Use it for: how early or late still counts as the shift, the nearest of two back-to-back shifts.

Runs on each workday with work that several active assignments fit and nothing names one. That work is its segments (before their context is resolved), and its labor entries and days of leave (once allocation made their lines).

ctx.segmentsEach with candidates (the assignments that fit) and its context so far.
ctx.entriesEach id, kind (entry or leave), about, workday, context, candidates.
ctx:assign(id, assignment, why)The context is resolved again with that assignment (source step: and the step’s id), stamped.

Use it for: the person’s primary assignment, an order of preference.

Runs once on the period, before the time steps, to say which workday each segment’s time belongs to where a law says so. A workweek counts hours where they are worked. A daily overtime law may count an overnight shift in the workday it starts in, or split it at the workday boundary.

ctx.segmentsThe segments that reach into the period. Each has its workday (the one it starts in), end_workday (the one its last instant is in), and the fields the time stage gives.
ctx:attribute(id, mode, why)Stamped with why. "start" is whole, to the workday it starts in. "end" is whole, to the one it ends in. "split" is cut at each workday’s start, each piece in its own workday.

Without a step, a segment belongs to the workday it starts in. The pieces of a split segment are segments from then on. Each is timed, allocated, approved and exported in its own workday. Each says where it was cut with cut_start and cut_end. A cut edge is a workday’s start, not a punch. start_kind or end_kind is nil there. A time step that tries to move it fails. The pieces always add up to the segment.

Runs on each workday of the period that has segments. It sets effective start and end times beside the raw ones. Raw times never change.

ctx.segmentsThe workday’s segments. Each has id, kind (work, lunch, break), and start and end (effective so far; end is nil while open). It has raw_start and raw_end. It has start_kind and end_kind, the kinds of the punches that started and ended it (nil at a cut). It has cut_start and cut_end. It has start_device and end_device, the devices of the punches that started and ended it (nil where none did). It has workday and context (a table of values). It has shift (id, start, end) when the segment belongs to a scheduled shift.
ctx:set_start(id, ms, why), ctx:set_end(id, ms, why)Sets a segment’s effective start or end, stamped with why (start 07:53:00 to 08:00:00: rounded to 15m). Setting the end of a segment with none is an error.
ctx:round(ms, interval, mode)An instant rounded to interval on the grid of wall times counted from its workday’s start, in the zone in force. A change of the clocks moves the grid with the wall clock. mode is "nearest", "up", "down", or a number of milliseconds. A number rounds down up to that far past a grid line, and up after (time.duration("7m")).

After the step, these are checked. No segment ends before it starts. None starts before the one before it ends. No cut was moved.

Runs before the allocate steps, on each tie. There is one tie per workday, context and kind of rate, for rates that match equally closely.

ctx.kind, ctx.context, ctx.workdayThe tie: which kind of rate, for what work, on which day.
ctx.ratesThe rates that tie: each id, amount, currency, matches.
ctx:choose(id, why)The rate ctx:rate gives for that tie.

Use it for: the higher of two rates, the job’s rate over the location’s.

Runs on each window in the period: each day, each week (from the week the period’s first day is in), the whole period, or 24 hours from when work starts. It moves time between pay categories and adds counts and money.

  • A 24h window is 24 hours from the start of the first timed line of worked time not in an earlier window. Work going on as one window ends starts the next. Lines across its ends are cut there. ctx.window.start and end are its instants. Use it for daily overtime counted from when work starts.
  • A week starting at a time of day (week_starts = "friday 12:00", a 9/80 schedule) cuts its first day at that instant. Timed lines count in the week they start in. Untimed ones count by their workday’s date.
  • Lines from before the period. A week that starts before the pay period reaches into the period before. Its lines there are given with prior = true and id 0. time_in counts them, and nothing moves them. So a weekly threshold across two pay periods counts the whole week and moves only time in this period.
ctx:lines(filter)The window’s lines the filter picks, in the order they are paid. Each has id, category, start, end, time (milliseconds) and workday. It has device (of the punch that started it) and context. It has timed (false for hours from labor entries), prior, and worked (whether its category counts as worked).
ctx:time_in(filter)The time of the lines the filter picks, in milliseconds.
ctx:move_latest(ms, filter, category, why)Moves the latest ms of the picked lines (latest ending first, skipping those already in category) to category. It splits a line at the exact instant. Returns the time moved.
ctx:move_between(from_ms, to_ms, filter, category, why)Moves the picked time between two instants to category: a meal deducted mid-shift. Returns the time moved.
ctx:move(id, category, why)Moves one line, whole: only the long breaks unpaid. Line ids are good until the next move.
ctx:move_within(period, filter, category, why)Moves the picked time inside a period to category, skipping lines already in it. The period is from ctx:period. Examples are the nights, and the weekend’s nights. The nights are { daily = { from = "22:00", to = "06:00" } }. That runs past midnight when to is at or before from. Untimed lines are never moved. Returns the time moved.
ctx:days_worked(filter)The dates with time the filter picks (default: worked time), including those before the period.
ctx:stretches(filter)The window’s own timed lines the filter picks, joined where one ends as the next starts. Each has start, end, time, workday, context and lines. It is for call-backs, split shifts and call-outs.
ctx:instant_after(ms, filter)When that much of the picked timed time has passed, gaps not counted. It is nil when there is not that much. Five hours into the day’s work is found the same way on the night the clocks go back as on any other.

A filter is a table. Every part is optional:

  • categories (a list).
  • except (categories left out).
  • worked (true or false).
  • context (values every picked line must have).
  • days (a set of workdays, as ctx.window.applies is).

No filter picks every line.

ctx:exception(kind, 0, detail) in allocate is about the window’s first day.

Counts and money:

ctx:quantities(measure, filter)The window’s count and money lines of measure (nil: any) that the filter picks. Each has id, measure, quantity, category, workday, context.
ctx:quantity_in(measure, filter)Their sum.
ctx:rate(kind, context, workday)The amount and then the currency of the rate of kind matched on context on workday (default: the window’s first day), or nil. A tie gives what a rate step chose. With none, it raises rate_ambiguous and gives nil (rates).
ctx:money_for(ms, per_hour)Minor units for that much time at that hourly amount. The part below one is dropped.
ctx:add_quantity{measure, quantity, category, context, workday, why}Adds a count or money line (a piece rate’s pay, a bonus), stamped with why. workday defaults to the window’s first day. An unknown measure is an error. So is a workday after the period’s last day. A measure is in one currency. Adding money to a measure in another currency than the rate’s fails the person’s ledger, naming the rate kind, its currency and the measure. A quantity is at most 2^40 either way. A sum that would pass it fails the ledger and never wraps.

Time not worked, such as a holiday’s pay:

ctx:add_hours{workday, time, category, context, why}Adds time (milliseconds, more than none) on a workday of the window as an untimed line in category, stamped with why. The category must be one set up as not worked: worked time only comes from punches and labor entries. A workday after the period’s last day is refused.

After the step, the window’s time is checked. It is what it was before, apart from what ctx:add_hours added. A step moves worked time. It never makes or loses any.

Take a step on a window of days that spans more than one pay period, such as a repeating window of 2w on weekly pay. By default it runs in each pay period, on the part of the window in that period. With only_where_window_ends = true it runs only in the pay period that holds the window’s last day. There it sees the whole window, including the days in earlier pay periods. Use it for a result that reads the whole window, such as hours of service over a measurement period. A step that declares it on a 24h window is refused, naming the step. A 24h window has no last day to end in.

ctx:average_week{ before, weeks, back, counts, measure, includes } answers how much time and money an average workweek before a date holds. It is in allocate steps only. It reads what the step is given: its window, and the days before it that the step asks for with looks_back. The argument is one table:

FieldShapeMeaning
beforeA date, "2026-10-05"Required. The weeks counted end before it.
weeksA whole number, 1 or moreRequired. How many workweeks to average.
backA whole number, from weeks to 520How many workweeks to look at, at most. Default weeks.
countsA list of pay category namesThe categories whose time is averaged. Default every worked category.
measureThe name of a measureWith it, the money of that measure is averaged too. A week counts when it has any of that money.
includesA list of category namesThe categories whose money of measure counts. Default every category of it. Only with measure.

A call that asks for something it cannot answer stops the step with an error. These are weeks below 1, back less than weeks or more than 520, and includes without measure. Nothing is ignored or adjusted.

It averages the last weeks workweeks ending before before that have any of what is averaged. Where a measure is given, that is the money of measure in includes. Otherwise it is the time counts picks. It looks at no more than back of them. It gives weeks (how many were counted), time, total_time, first and last. With measure, it gives money and total_money too. It gives nil where no week has any. The holiday pay on average earnings recipe uses it.

A step declares how far it looks back with looks_back:

M.average_pay = {
stage = "allocate",
looks_back = function(p) return 7 * p.back end,
params = { back = { type = "integer", default = 13 } },
run = function(ctx, p)
local a = ctx:average_week({ before = ctx.window.first, weeks = p.back, counts = { worked = true } })
if a ~= nil then
-- a.time is the average week's time, in milliseconds
end
end,
}

A step with reads_balances = true can call ctx:balance(category). It gives the balance of an accrual category as the pay period opens. The balance includes the hand adjustments and the time used in the period. It is before what the period’s accrue steps earn. In an allocate step it takes no date. A date stops the step with an error. Without the declaration the call fails. A step that declares it is worked out again when those balances change. The comp_time recipe reads its bank’s room under cap this way.

M.bank_room = {
stage = "allocate",
reads_balances = true,
params = { bank = { type = "string", required = true } },
run = function(ctx, p)
local held = ctx:balance(p.bank)
-- move overtime to the bank only while held is below a cap
end,
}

ctx:run_on(spec, filter), in allocate steps, finds work that held a whole stretch of the period spec and went on past it. It looks at the window’s timed lines the filter picks, joined where one ends as the next starts. For each such stretch of work, it returns the time from the end of that stretch of the period to the end of the work. A night worked whole and worked on past 05:00 is one such stretch. The hours after 05:00 are what it returns. Work that starts inside the period, or ends with it, runs nothing on.

The standard window_premium_run_on and shortened_hour_run_on steps use it, and the Brazil working hours recipe shows them.

Runs on each window, after the allocate steps, to earn time off (accruals).

ctx:time_in(filter), ctx:quantity_in(measure, filter)As in allocate, over the window’s lines.
ctx:balance(category, date)The balance of the accrual category, in milliseconds: from the policy’s accruals.since, with this period’s entries so far. With date, it is as that day starts.
ctx:forfeit(category, ms, why, date)A forfeited entry: a carryover limit at the year’s start.
ctx:accrue(category, ms, why)Earns ms of the accrual category, on the window’s first day. An unknown accrual category is an error.
ctx:earned(category, period)What accrue steps earned of an accrual category on the days the period holds any of. For the pay periods before, it is as their ledgers have it. For this period, it is as the steps so far earned it. It is what a yearly limit on what is earned counts.
ctx:pay_out(category, ms, pay_category, why, date)In accrue steps only. Takes ms (more than nothing) off the balance of category on date, a day of the window (default its first day). The balance goes down by a paid_out entry. The ledger has that much time, untimed, in pay_category. pay_category must be set up as not worked and used by no accrual category. A date outside the window, an ms of nothing or less, and a pay_category that is worked or used by an accrual category stop the step with an error. Payroll pays it as it pays that category. It is for what is left of a comp time bank on leaving, or a balance cashed out at the year’s end. why is a rule, { rule = "leaving" }, or text. The comp time and year end by category recipes use it.

Runs on each workday of the period that has segments or a scheduled shift, after the time is allocated, so a missed shift can be raised. It raises exceptions and changes nothing.

ctx.segmentsAs in time, with their effective times.
ctx:lines()The workday’s lines, after every allocate step.
ctx.previous_endWhen the last segment of an earlier workday of the period ended, for rules on rest between days. It is nil if none.
ctx.window.previous_endIn allocate steps: the instant, in milliseconds, that the last segment of a workday before the window’s first ended, in the period or in the period before (as punched). It is nil where there is none. It is for rules on the rest between shifts.

An exception about id 0 is about the day itself, at the workday’s start, rather than a segment. no_show is raised that way.

Runs outside a ledger, on each change to a closed period: the changes recorded on one day of the open one.

ctx.changeperiod, day, closed, time (each category, context and time), net, quantities, and balances. balances are the balance differences of the change in milliseconds by accrual category.
ctx:adjust(why), ctx:refuse(why)Takes it into the open period as an adjustment, or refuses it.

ctx.change.balances lets a step refuse or route a change that moves only a balance, such as a late punch that earns time off or leave taken late.

Use it for: small changes adjusted, large or late ones refused for review.

Runs outside a ledger, on each subject of approval as its standing is worked out.

ctx.subjectkey, kind, days, category.
ctx.ruleside, blocked_by_exceptions, stages.
ctx.exceptionsThe exceptions of its days: each kind, at, about, detail, state.
ctx:lines(), ctx:time_in(filter)Its lines.
ctx:block(why)Keeps it from approval.
ctx:route(stage, approver, why)Sends a stage to an approver.

With an approve step, the steps alone say what blocks. Use it for: only missing punches block, long overtime goes to a manager, minors go to HR.

An exporter writes a pay period’s timecards for another system (payroll export). It is an entry with stage = "export". It also has the file’s content_type and extension (default text/plain and txt), and up to three functions:

Function
header(p)Optional: written first. p is the export’s params.
person(x, p)Required: called once for each person’s timecard. What it returns is written.
footer(summary, p)Optional: written last. summary has people, lines, the paid hours, and the hours by categories and category_use, for a trailer.

x is one person’s timecard:

Field
person, attributesThe person, and their employment details on the period’s last day (a payroll id).
side, first, last, closed, approvedThe side, the period, and whether it is closed and approved. Approved is as a whole or every assignment of it (approving by assignment).
paid, worked, categories, category_usepaid is the decimal hours in paid categories. worked is the worked time as a duration ("40h"). categories is the hours by pay category (unpaid ones too). category_use is what each category is: { work = { paid = true, worked = true, code = "REG" } } (code where the setup names one).
linesEach line has workday, category, hours, paid and worked (its category’s), code (where it has one), time (milliseconds), and context. It has from: segment, entry, leave, policy, adjustment, or paid. paid means already paid for this period by a later closed one, taken off. It has approved (the period is, or the line’s assignment is). It has rates: the rate of each kind its work is at, { bill = { amount = 3000, currency = "USD" } }.
daysEach day with lines: date, paid, worked, categories.
quantitiesCounts and money: workday, measure, quantity, category, context, and approved and rates as a line’s.

Hours are text in the tenant’s decimals ("8.25"), carried, never rounded line by line. A line’s rates are the ones that applied to its work, or for a tie the one the policy’s rate steps chose. To bill, add a client’s time at each rate over the period and work the money out once with time.money, never line by line. With approved on each line, an invoice can bill one client’s approved hours while another’s wait. The cookbook’s staffing agency exporter does both.

csv(list) makes one CSV row, quoted where needed, with its line end. An exporter keeps nothing between people. What it writes for one person cannot depend on another. One that keeps state fails the export. Totals for a trailer are in summary. error("person 104552 has no payroll_id") stops the export and says why. The standard csv exporter is a complete example.

Policy packages run in the same sandboxed Luau as protocol packages:

  • There is no os, getfenv, setfenv, files or network. A step is pure. The same inputs always give the same output. So any ledger can be worked out again and audited.
  • The standard Luau libraries (math, string, table), time, and csv (for exporters) are available.
  • One step on one window may run for 2 seconds, and a package may use 64 MB of memory. An exporter’s calls have the same limits.
  • A step keeps nothing between calls. A step that changes what its package holds (a global, a module-level table) fails the ledger, naming the package and its steps. A package that holds a coroutine or a buffer at module level is refused when it is loaded.
  • Source that does not compile is refused, with the file and line.

A policy package is a folder:

franchise/
package.toml # name (default: the folder's), version, description,
# effective, [needs], and its [[layer]]s
main.lua # its own steps and exporters, if it has any
scenarios/*.toml # what it must come to
package.toml
name = "franchise"
version = "1.0.0"
description = "A franchisor's pay rules: weekly pay periods, and overtime past 8 hours a day, locked."
[[layer]]
id = "pay"
settings = { pay_periods = { every_days = 7, from = "2026-10-05" } }
[[layer]]
id = "overtime"
order = 10
locks = ["*"]
[[layer.step]]
id = "daily"
uses = "standard/threshold"
params = { over = "8h", to = "overtime", window = "day" }

Each [[layer]] takes the keys of a scenario’s [[layer]].

A step that reads the tenant’s setup by name needs the tenant to have set it up. The package says which in [needs]:

package.toml
[needs]
accrual_categories = ["time_account"] # earned into, taken from, or read
measures = ["wages"] # added to

The package’s scenarios run reading only what it declares. A step that reads an accrual category or a measure that is not declared fails the scenario. That fails the publication too, saying which field to add it to. In a tenant’s ledger, a step that reads one the tenant has not set up fails that person’s ledger with there is no measure wages. The person waits in pending with that reason. Adopting the package is refused until the tenant has set up everything it needs. Every missing one is listed. Removing a measure or an accrual category an adopted package needs is refused too. A step’s own name is not a need: standard/threshold reads no setup. A step is named <package>/<step>. standard/threshold is the threshold step of the built-in standard package. A package’s own are franchise/<step>.

Terminal window
hourctl attend test franchise/ # its scenarios, offline
hourctl -t acme attend pkg publish franchise/ # the tenant's own
hourctl attend pkg publish franchise/ --shared --effective 2026-11-02
hourctl -t acme attend pkg adopt franchise@1

Publishing runs the package’s scenarios on the server with the package adopted, and keeps it as the package’s next revision. A package whose scenarios fail is kept as a failed revision, with what failed, and refused (400). No tenant sees a change. A published version never changes. Other content under it is refused, and a fix is a new version. Adoption and effective days are in policy packages. The API is in the attendance API.

A scenario can also carry a package of its own, for trying a step without publishing anything:

[package.mine]
source = """
return { long_day = { stage = "exceptions", params = { max = "duration" }, run = function(ctx, p) ... end } }
"""
[[layer]]
id = "mine"
[[layer.step]]
id = "long-day"
uses = "mine/long_day"
params = { max = "12h" }