Skip to content

@gram-lang/scheduler

Gram’s scheduling engine takes an agnostic task graph (the tasks field of a compiled recipe) and answers two fundamental questions: how do these tasks lay out chronologically (layout), and precisely when should each task begin, given a target serving time and cooking availability (project).

The scheduler has no knowledge of the AST or the .gram syntax, operating solely on the neutral task graph. See The scheduling engine for how its architecture works and Planning and run sheets for practical usage.

npm install @gram-lang/scheduler

The @gram-lang/kitchen compiler already re-exports layout, LayoutOptions, and the relevant choice constants (MISE_EN_PLACE_MODES, REST_CHOICES…): code that only interacts with Kitchen does not need to install this package directly.

function layout(graph: TaskGraph, options?: LayoutOptions): LayoutResult

interface LayoutOptions {
  miseEnPlace?: MiseEnPlaceMode; // "perSection" (default) | "upfront" | "perDay"
  rests?: RestChoice;            // "shortest" (default) | "balanced" | "longest"
  restOverrides?: Record<string, number>; // target passive durations in minutes, by task id (used by project())
}

interface LayoutResult {
  schedule: Schedule;
  diagnostics: SchedulingDiagnostic[];
}

Lays out the task graph on a relative timeline, measured in minutes starting from 0 (the first task).

Active work is consistently scheduled using its nominal duration regardless of the rests option. For passive durations specified as a range, the rests option selects the minimum (shortest), median (balanced), or maximum (longest) duration. Fixed passive durations and active timers remain unaffected.

Any value in restOverrides that falls outside a passive duration’s allowed range is ignored: no passive duration is ever lengthened or shortened beyond the bounds defined in the recipe.

import { compile } from '@gram-lang/kitchen';
import { layout } from '@gram-lang/scheduler';

const { tasks } = compile(ast);

const { schedule, diagnostics } = layout(tasks, {
  miseEnPlace: 'upfront',
  rests: 'longest',
});
// schedule.totalTime, schedule.blocks, schedule.days...

For default options, compiled.schedule matches layout(compiled.tasks).schedule exactly.

interface Schedule {
  miseEnPlace: MiseEnPlaceMode;
  rests: RestChoice;
  totalTime: number;       // latest end time across all blocks
  activeTime: number;      // total hands-on active work duration, excluding mise en place
  preparationTime: number; // mise en place duration (sum of `prep` tasks)
  idleTime: number;        // overall inactive time: totalTime - activeTime - preparationTime
  blocks: ScheduleBlock[]; // sorted by start time, then end time
  days: ScheduleDay[]; // one per working day, ordered from furthest day to serving day
}

type ScheduleBlock =
  | { kind: "prep"; task: string; section: number; start: number; end: number; deferred?: true; items?: MiseEnPlaceItem[] }
  | { kind: "step"; task: string; section: number; step: number; start: number; end: number }
  | { kind: "passive"; task: string; section: number; step: number; track?: string; start: number; end: number };

interface ScheduleDay {
  day: number;      // 0 = serving day (day 0), 1 = day before (day -1, ~{-1d})...
  start: number;    // start and end bounds of the working day's active work
  end: number;
  sections: number[];
}

When a prep block bundles multiple preparations that start and end together, its task field carries the identifier of the first task.

Structural diagnostics emitted by layout() as neutral data (the Kitchen compiler subsequently formats them as user warnings):

type SchedulingDiagnostic =
  | { code: "TIME_PARADOX"; section: number; pulledTo: number }
  | { code: "TRACK_CONTENTION"; section: number; trackName: string; delay: number }
  | { code: "DAY_OVERFLOW"; section: number; day: number; overflowMinutes: number };

DAY_OVERFLOW indicates that a working day’s active work starts before the 24-hour window allocated to that working day (pushed back by upstream task sequences). Only active work is counted against this threshold; passive durations spanning overnight are excluded.

interface TaskGraph {
  tasks: Task[];                // sections in order, then steps, with `prep` first in each section
  sections: TaskGraphSection[]; // parallel to the recipe's sections
}

type Task = PrepTask | StepTask | TimerTask;

interface TaskDuration {
  nominal: number; // default duration used by layout
  min?: number;    // only for passive durations defined as a range
  max?: number;
}

interface PrepTask {
  id: string;
  kind: "prep";
  section: number;
  intermediate?: string; // defined for the preparation of an intermediate (&dough)
  duration: TaskDuration;
  items: MiseEnPlaceItem[];
  after: string[];       // step that produces the intermediate (when known)
}

interface StepTask {
  id: string;
  kind: "step";
  section: number;
  step: number;          // step index within the section (comments included)
  duration: TaskDuration;
  produces?: string[];   // intermediates declared in the recipe
  consumes?: string[];
  after: string[];
}

interface TimerTask {
  id: string;
  kind: "passive";
  section: number;
  step: number;
  track?: string;        // dedicated equipment track (~_oven{})
  offset: number;        // offset in minutes from step start
  duration: TaskDuration;
  after: string[];
}

interface TaskGraphSection {
  day: number;           // 0 = serving day; a day anchor initiates a new working day
  deadline?: number;     // anchor deadline in minutes before completion
  intermediate?: string; // intermediate produced by the entire section
}

Task identifiers are deterministic and human-readable: s0.prep, s1.prep.dough, s0.3, s0.3.t0.

function project(recipes: ProjectionInput[], context: ProjectionContext): ProjectedPlan

interface ProjectionInput {
  graph: TaskGraph;
  title?: string;
  options?: LayoutOptions;
}

interface ProjectionContext {
  serveAt: string;        // target local date-time ("2026-10-11T13:00") in timeZone
  timeZone: string;       // IANA time zone identifier ("Europe/Paris")
  availability: Availability;
  now?: string;           // reference ISO instant or local time for START_IN_PAST (by default, no clock check is performed)
}

interface Availability {
  daily: TimeRange[];                               // default daily availability window
  weekdays?: Partial<Record<Weekday, TimeRange[]>>; // "mon" … "sun"; [] indicates complete unavailability
  dates?: Record<string, TimeRange[]>;              // "2026-10-09"; overrides weekdays
}

interface TimeRange {
  start: string;
  end: string;            // "08:00"–"22:00"; an end time before start crosses midnight
}

Projects a recipe’s timeline onto the real calendar, aligning completion with the target serving time. Elastic passive durations are adjusted to schedule active work within the user’s availability windows.

The conflict resolution strategy is greedy and deterministic (prioritizing explainability over global optimality). While accepting a list of recipes as input, only the first recipe is scheduled in the current implementation (subsequent recipes trigger MULTI_RECIPE_UNSUPPORTED). An invalid IANA time zone or a malformed serving timestamp throws a RangeError.

const plan = project(
  [{ graph: tasks, title: 'Country bread' }],
  {
    serveAt: '2026-10-11T13:00',
    timeZone: 'Europe/Paris',
    availability: {
      daily: [{ start: '08:00', end: '22:00' }],
      weekdays: { sun: [{ start: '09:00', end: '20:00' }] },
    },
  },
);
interface ProjectedPlan {
  serveAt: string;
  timeZone: string;
  recipes: {
    title?: string;
    miseEnPlace: 'perSection' | 'upfront' | 'perDay'; // the mode this plan was made in
    blocks: ProjectedBlock[];     // scheduled blocks with start/end as ISO 8601 UTC timestamps
    days: ProjectedDay[]; // and startLocal/endLocal: local wall-clock time in the target zone ("2026-10-10T21:40")
  }[];
  adjustments: RestAdjustment[];  // adjustments applied to elastic passive durations
  unavailable: { start: string; end: string }[]; // unavailable windows overlapping the plan duration
  diagnostics: ProjectionDiagnostic[];
}

interface RestAdjustment {
  task: string;
  from: number; // minutes
  to: number;
  reason: "avoid-unavailable";
}

type ProjectionDiagnostic =
  | { code: "ACTIVE_OUTSIDE_AVAILABILITY"; task: string; local: string; rest?: string }
  | { code: "ACTIVE_BLOCK_EXCEEDS_AVAILABILITY"; tasks: string[]; minutes: number; largest: number }
  | { code: "DAY_MISMATCH"; day: number; expected: string; actual: string }
  | { code: "START_IN_PAST"; start: string; now: string }
  | { code: "MULTI_RECIPE_UNSUPPORTED"; recipes: number };

These diagnostics depend on the user’s execution context: they are included directly in the ProjectedPlan result rather than being compiler warnings. See Planning and run sheets for a detailed breakdown of each code.

function runSheet(
  source: ProjectedPlan | Schedule,
  options?: RunSheetOptions,
): RunSheet

interface RunSheetOptions {
  graph?: TaskGraph;           // gives each timer its written range
  title?: string;              // the title of a recipe laid out without a serving time
  context?: ProjectionContext; // with `graph`, a calendar plan gets the margin of each visit
}

Generates the data structure powering the run sheet: day-by-day breakdowns for each recipe, detailing active kitchen visits and passive threads that proceed unattended.

  • A ProjectedPlan produces a concrete timestamped calendar schedule (mode: "calendar");
  • A bare Schedule produces a relative temporal structure measured in days before serving (mode: "relative").

When graph and context are provided (in calendar plans), each visit receives its calculated anticipation margin. Key terms are defined in The scheduling engine.

interface RunSheet {
  mode: "calendar" | "relative";
  serveAt?: string;            // calendar plans only
  timeZone?: string;
  recipes: { title?: string; miseEnPlace: MiseEnPlaceMode; days: RunSheetDay[]; totalWork: number }[]; // totalWork: cumulative active hands-on minutes
  adjustments: RunSheetAdjustment[]; // waits lengthened or shortened, with their section and day
  diagnostics: ProjectionDiagnostic[];
}

interface RunSheetDay {
  date?: string;               // "2026-10-10", with a target serving time
  daysBefore: number;          // 0 on serving day, 1 on the day before...
  visits: RunSheetVisit[]; // kitchen visits in chronological order
  threads: RunSheetThread[];   // passive processes continuing after a visit
  entries: RunSheetEntry[];    // all day blocks in order
}

interface RunSheetVisit {
  start: number;               // exact minutes before serving (<= 0)
  end: number;
  startLocal?: string;         // "2026-10-10T21:40", with a target serving time
  endLocal?: string;
  sections: number[];          // section indices with work in this visit, in recipe order
  worked: number[];            // sections with a step in this visit
  sectionStarts: { section: number; start: number; startLocal?: string }[];  // when each section of `worked` starts its first step in this visit
  tasks: string[];             // task IDs for prep and step blocks from graph
  window?: { advance: number; earliest: number; earliestLocal: string }; // anticipation margin (computed when >= 15 min)
  fixedBy?: RunSheetFixedBy;   // the wait that holds this visit in place
}

interface RunSheetFixedBy {
  task: string;
  section: number;
  step?: number;
  track?: string;
  planned: number;             // the planned minutes of the wait
  before: "service" | "visit"; // what the wait leads to: the service or the next visit of `sections`
  sections?: number[];
}

interface RunSheetThread {
  visit: number;             // index in the day's visits
  task: string;
  section: number;
  step?: number;
  track?: string;
  from: number;                // minutes from the service
  to: number;
  planned: number;             // minutes, adjustments included
  fromLocal?: string;
  toLocal?: string;
  range?: { min: number; max: number }; // the written range (with `graph`)
}

A day is a working day of the recipe; with a serving time, a working day that runs over several dates is told one day per date, and a visit that crosses midnight stays whole on the date it starts. RunSheetEntry is the block-level record (kind, active, from, to, minutes, startLocal, adjustment?…).

What is not here are words and layout: @gram-lang/renderer writes them (runSheetToText, runSheetToMarkdown, runSheetToHTML, runSheetToPrintHTML, describeRunSheet; see the renderer reference).

function visitWindows(sheet: RunSheet, graph: TaskGraph, context: ProjectionContext): RunSheet

Gives each visit of a calendar run sheet its anticipation margin (window), or names the wait that holds it in place (fixedBy). The margin of a visit assumes every other visit stays at its planned time, so it is always safe to use: moving several visits, or none, never breaks another margin. A margin is sometimes cautious, never wrong, and one shorter than WINDOW_MIN_MINUTES is not told.

runSheet() already calls it when you pass graph and context, so you only need it to add margins to a sheet you built without them. A relative sheet, or one with no serving time, is returned as it is.

Both are built on project(): they try serving times and keep those that can be followed. A time is rejected when the plan has an unresolved problem, a start already in the past included, and each rejection carries its reasons.

function tryServeAt(input: ProjectionInput, context: ProjectionContext, serveAt: string): ServeCandidate;

function findServeTimes(
  input: ProjectionInput,
  context: ProjectionContext,        // needs `now` to reject starts in the past
  options: FindServeOptions,
): ServeSearch;

interface FindServeOptions {
  from: string;                      // "2026-10-12" or "2026-10-12T08:00", local
  to: string;                        // a bare date means its whole day
  mealTimes?: string[];              // default DEFAULT_MEAL_TIMES = ["12:30", "20:00"]
  limit?: number;                    // default 5
}

interface ServeSearch {
  candidates: ServeCandidate[];      // feasible times, best first
  rejected: ServeCandidate[];        // every time tried and failed, with its reasons, in time order
}

function earliestServe(
  input: ProjectionInput,
  context: ProjectionContext,        // `now` required (or `options.from`)
  options?: { from?: string },
): { found?: ServeCandidate; searchedUntil: string };

interface ServeCandidate {
  serveAt: string;                   // local
  ok: boolean;
  reasons: ProjectionDiagnostic[];
  adjustments: number;               // waits made longer or shorter
  visits: number;                  // visits to the kitchen
  startsAt?: string;                 // local, first task
  plan: ProjectedPlan;
}

candidates are ranked: fewer adjustments, then fewer visits, then the earliest. earliestServe() starts at the recipe’s shortest length after the present and goes by steps of five minutes for up to EARLIEST_SERVE_HORIZON_DAYS (14). The words for both are describeServeTimes() and describeEarliestServe() of the renderer; gram plan --find is the same search.

type MiseEnPlaceMode = "perSection" | "upfront" | "perDay";
const MISE_EN_PLACE_MODES: readonly MiseEnPlaceMode[];
const DEFAULT_MISE_EN_PLACE_MODE: MiseEnPlaceMode; // "perSection"
function isMiseEnPlaceMode(value: unknown): value is MiseEnPlaceMode;

type RestChoice = "shortest" | "balanced" | "longest";
const REST_CHOICES: readonly RestChoice[];
const DEFAULT_REST_CHOICE: RestChoice; // "shortest"
function isRestChoice(value: unknown): value is RestChoice;

const WEEKDAYS: readonly ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];

const MINUTES_PER_DAY = 1440;
const VISIT_GAP_MINUTES = 60;          // a wait this long ends a visit to the kitchen
const WINDOW_MIN_MINUTES = 15;          // a margin shorter than this is not told
const DEFAULT_MEAL_TIMES: string[];     // ["12:30", "20:00"]
const EARLIEST_SERVE_HORIZON_DAYS = 14;

// Date utilities without external dependencies, based on an explicit time zone
function parseLocalIso(value: string, timeZone: string): number; // "2026-10-11T13:00" → minutes since Unix epoch (UTC)
function parseInstant(value: string, timeZone: string): number;  // ISO instant (with 'Z' or UTC offset) or local time
function toLocalIso(utcMinutes: number, timeZone: string): string; // → "2026-10-11T13:00"
function toUtcIso(utcMinutes: number): string;                    // → "2026-10-11T11:00:00Z"
function isCalendarDate(value: string): boolean;                 // "2028-02-29" → true, "2026-02-30" → false

// Times as people write them, in 24 or 12 hours (since 1.5.0): the syntax of
// `--available`, `--meal-times`, `--serve` and their settings
function parseTimeOfDay(text: string, options?: { end?: boolean }): string | null;
// "13:00", "9:30" → "09:30", "1pm", "1:00 PM", "8:30 a.m." → "08:30"; "12am" → "00:00", "12pm" → "12:00";
// with `end` (the end of a range), "12am" and "24:00" → "24:00"; "8", "13pm", "0am" → null
function parseLocalDateTime(text: string): { ok: true; local: string } | { ok: false; reason: "date" | "format"; date?: string };
// "2026-10-11 1:00 pm" → { ok: true, local: "2026-10-11T13:00" }; "2026-02-30 20:00" → { ok: false, reason: "date", date: "2026-02-30" }

parseAvailability() and parseMealTimes() read each time with parseTimeOfDay(): 8am-10pm, fri=6pm-12am (until midnight) and ["12:30pm", "8pm"] give the same values as their 24-hour form. A time is always given back as "HH:MM": the plan never depends on how it was written.

During daylight saving time transitions, an invalid local time (e.g. 02:30 when clocks spring forward) shifts to the next valid time; an ambiguous local time (occurring twice when clocks fall back) resolves to its first occurrence.

A date that does not exist (a 30th of February, a 31st of April) is refused with a RangeError rather than moved to the next month.