feat(cli): add gram plan and bring the rests and the plan to the editor, the diff and the playground #81

Merged
abiwab merged 6 commits from feat/schedule-consumers into main 2026-10-04 12:51:29 +02:00
41 changed files with 1633 additions and 49 deletions

View file

@ -3,4 +3,4 @@
"@gram-lang/cli": minor
---
**Analyzer / Diff**: `gram diff` now compares the total and idle times of the default schedule, with the mise en place right before each section, so the times it reports match what `gram view` shows by default; preparation and active times are compared as before
**Analyzer / Diff**: `gram diff` now compares the total and idle times of the default schedule, with the mise en place right before each section, so the times it reports match what `gram view` shows by default; the active time is the schedule's too, so changing the range of a cooking time (`~{20-25min}`, planned on its longest figure) shows in the comparison, and the preparation time is compared as before

View file

@ -5,3 +5,5 @@
**CLI / View & Export**: `gram view`, `gram export` and `gram print` accept a new `--mise-en-place <per-section|upfront|per-session>` option, to see the recipe with the mise en place planned right before each section (the default), all at the start, or at the start of each working day:
- The total and idle times shown follow the chosen option; the active and preparation times stay the same
- A new `--rests <shortest|balanced|longest>` option does the same for a rest written as a range (`~_{12-24h}`): the shortest by default, the middle or the longest
- `gram cook` accepts both options too, for the total time it shows

View file

@ -0,0 +1,10 @@
---
"@gram-lang/cli": minor
---
**CLI / Plan**: A new `gram plan <recipe> --serve "2026-10-11 13:00"` command plans a recipe backward from the time it is served, and writes a production sheet with a time for every task:
- `--tz Europe/Paris` sets the time zone (this machine's by default), and `--available` says when you can cook, as many times as needed: `08:00-22:00` for every day, `fri=18:00-22:00` for a day of the week, `2026-10-09=none` for a date (nothing means all day)
- A rest written as a range (`~_{8-16h}`) is made longer or shorter to keep your own work out of the hours you are not available, and the sheet says which one and why; what cannot be fixed is listed at the end
- `--format text|md|html|json` picks the output, and `--ics plan.ics` also writes a calendar file with an event for every task and an alarm on the ones that need your hands
- `--mise-en-place`, `--rests`, `--scale` and `--stock` work as they do in `gram view`

View file

@ -8,3 +8,5 @@
- The preview, the Gantt chart and the total time hint next to the recipe title all follow it
- Changing the setting updates every open recipe right away, and a recipe already open when the editor starts follows it too
- Changing a `gram.*` setting now reaches the language server straight away, without reloading the window (this also applies to `gram.ingredientDatabase.path`)
- A new `gram.rests` setting (`shortest` by default, `balanced` or `longest`) chooses how long a rest written as a range (`~_{12-24h}`) lasts in the same three places
- A working day pushed out of its 24 hours by a long rest is flagged on its section (the new `SESSION_OVERFLOW` warning)

View file

@ -78,6 +78,7 @@
"@gram-lang/modules": "workspace:*",
"@gram-lang/parser": "workspace:*",
"@gram-lang/renderer": "workspace:*",
"@gram-lang/scheduler": "workspace:*",
"ai": "^7.0.22",
"chalk": "^6.0.1",
"citty": "^0.2.2",
@ -116,6 +117,7 @@
"@gram-lang/modules": "workspace:*",
"@gram-lang/parser": "workspace:*",
"@gram-lang/renderer": "workspace:*",
"@gram-lang/scheduler": "workspace:*",
"astro": "^7.3.5",
"mermaid": "^12.0.0",
"shiki": "^4.3.1",

View file

@ -8,7 +8,7 @@ import type {
ShoppingListItem,
CompositeItem,
} from "@gram-lang/kitchen";
import { getNumericQty, scheduleTimes } from "@gram-lang/kitchen";
import { getNumericQty, scheduleFor, scheduleTimes } from "@gram-lang/kitchen";
// Structural, analyzer-local shapes for the module-composition metadata a
// `CompilationResult` may carry when it actually came from
@ -421,19 +421,22 @@ function diffIngredients(
return deltas;
}
// The four times a diff reports. Preparation and active time are the same in
// every mise en place schedule; total and idle time depend on the schedule, so
// they are read from the default one (preparation right before each section)
// — the same on both sides, which is all a comparison needs.
// The four times a diff reports, all read from the default timeline (mise en
// place right before each section, the shortest rests): the same on both sides,
// which is all a comparison needs. The active time is the schedule's, which
// plans a timer written as a range on its longest figure, so changing the range
// of a cooking time shows; `metrics.activeTime` (the average) is deprecated.
function timingsOf(
recipe: CompilationResult,
): Record<TimingDelta["field"], number> {
const { totalTime, idleTime } = scheduleTimes(recipe);
const schedule = scheduleFor(recipe);
return {
totalTime,
idleTime,
activeTime: recipe.metrics?.activeTime ?? 0,
preparationTime: recipe.metrics?.preparationTime ?? 0,
activeTime: schedule?.activeTime ?? recipe.metrics?.activeTime ?? 0,
preparationTime:
schedule?.preparationTime ?? recipe.metrics?.preparationTime ?? 0,
};
}

View file

@ -303,7 +303,7 @@ describe("diffRecipes — timings follow the per-section schedule", () => {
expect(idle?.to).toBe(schedulesOf(b).perSection.idleTime);
});
it("still compares preparation and active time from the metrics", () => {
it("compares the preparation time of the schedule, the sum of the mise en place", () => {
const a = compileRecipe(base);
const b = compileRecipe(base.replace("(sifted)", ""));
const { timings } = diffRecipes(a, b);
@ -320,9 +320,9 @@ describe("diffRecipes — timings follow the per-section schedule", () => {
).toEqual([]);
});
it("compares JSON stored before 1.4.0 (no schedules) through its old metrics, not as zero", () => {
it("compares JSON stored before 1.4.0 (no tasks) through its old metrics, not as zero", () => {
const current = compileRecipe(base);
const { schedules: _s, ...stored } = compileRecipe(base);
const { schedule: _s, tasks: _t, ...stored } = compileRecipe(base);
const timings = diffRecipes(current, stored as never).timings;
// Never the "150 -> 0" a missing schedule used to read as.
@ -333,3 +333,32 @@ describe("diffRecipes — timings follow the per-section schedule", () => {
expect(diffRecipes(stored as never, stored as never).timings).toEqual([]);
});
});
describe("diffRecipes — the active time is the schedule's", () => {
const cook = (range: string) =>
`## Roast\n\nRoast @chicken{1kg} for ~{${range}}.\n`;
it("shows a change of the range of a cooking time, planned on its longest figure", () => {
const a = compileRecipe(cook("40-50min"));
const b = compileRecipe(cook("40-60min"));
const active = diffRecipes(a, b).timings.find(
(t) => t.field === "activeTime",
);
expect(active).toEqual({ field: "activeTime", from: 50, to: 60 });
// The deprecated metric is the average: 45 and 50.
expect(a.metrics.activeTime).toBe(45);
});
it("falls back on the old metric for JSON stored before 1.4.0", () => {
const a = compileRecipe(cook("40-50min"));
const {
schedule: _s,
tasks: _t,
...stored
} = compileRecipe(cook("40-70min"));
const active = diffRecipes(a, stored as never).timings.find(
(t) => t.field === "activeTime",
);
expect(active).toEqual({ field: "activeTime", from: 50, to: 55 });
});
});

View file

@ -60,6 +60,7 @@
"@gram-lang/modules": "workspace:*",
"@gram-lang/parser": "workspace:*",
"@gram-lang/renderer": "workspace:*",
"@gram-lang/scheduler": "workspace:*",
"ai": "^7.0.22",
"chalk": "^6.0.1",
"citty": "^0.2.2",

View file

@ -12,6 +12,11 @@ import { loadDbSafe } from "../core/db";
import { runPipeline } from "../core/pipeline";
import { reportUnusedStock, resolveStockFromConfig } from "../core/stock";
import { reportRejectedIngredients } from "../ui/diagnostics";
import {
MISE_EN_PLACE_FLAG_DESCRIPTION,
parseMiseEnPlace,
} from "../services/mise-en-place-flag";
import { RESTS_FLAG_DESCRIPTION, parseRests } from "../services/rests-flag";
import { resolveScaleArg, getScaleWarnings } from "../services/scaler";
import { prepareRecipeData } from "../ui/cook/prepare";
import App from "../ui/cook/App";
@ -43,6 +48,14 @@ export default defineCommand({
description: "Skip ingredient database",
default: false,
},
"mise-en-place": {
type: "string",
description: MISE_EN_PLACE_FLAG_DESCRIPTION,
},
rests: {
type: "string",
description: RESTS_FLAG_DESCRIPTION,
},
stock: {
type: "string",
description:
@ -64,6 +77,8 @@ export default defineCommand({
config.language,
config.paths,
)) ?? 1;
const miseEnPlace = parseMiseEnPlace(args["mise-en-place"]);
const rests = parseRests(args.rests);
const stock = resolveStockFromConfig(args.stock, config);
const s = spinner();
@ -81,7 +96,7 @@ export default defineCommand({
stock,
});
reportUnusedStock("gram cook", "cooked", stock, [{ usedStock }]);
totalTime = scheduleTimes(compiled).totalTime;
totalTime = scheduleTimes(compiled, miseEnPlace, rests).totalTime;
const massMap: Record<string, number> = {};
for (const item of analyzed?.result?.shopping_list ?? []) {
if (item.id && typeof item.normalizedMass === "number")

View file

@ -13,6 +13,7 @@ import {
MISE_EN_PLACE_FLAG_DESCRIPTION,
parseMiseEnPlace,
} from "../services/mise-en-place-flag";
import { RESTS_FLAG_DESCRIPTION, parseRests } from "../services/rests-flag";
import {
NUTRITION_BASIS_FLAG_DESCRIPTION,
parseNutritionBasis,
@ -82,6 +83,10 @@ export default defineCommand({
type: "string",
description: MISE_EN_PLACE_FLAG_DESCRIPTION,
},
rests: {
type: "string",
description: RESTS_FLAG_DESCRIPTION,
},
stock: {
type: "string",
description:
@ -115,6 +120,7 @@ export default defineCommand({
const bakersMathOnly = args["bakers-math-only"] as boolean;
const nutritionBasis = parseNutritionBasis(args.nutrition);
const miseEnPlace = parseMiseEnPlace(args["mise-en-place"]);
const rests = parseRests(args.rests);
const stock = resolveStockFromConfig(args.stock, config);
const outputPath = args.output
@ -134,6 +140,7 @@ export default defineCommand({
bakersMathOnly,
nutritionBasis,
miseEnPlace,
rests,
lang: config.language,
paths: config.paths,
stock,

View file

@ -0,0 +1,157 @@
import { defineCommand } from "citty";
import { log } from "@clack/prompts";
import { writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { parseInstant, toUtcIso } from "@gram-lang/scheduler";
import { version } from "../../package.json";
import { loadConfig } from "../core/config";
import { resolveScaleArg } from "../services/scaler";
import { reportUnusedStock, resolveStockFromConfig } from "../core/stock";
import {
MISE_EN_PLACE_FLAG_DESCRIPTION,
parseMiseEnPlace,
} from "../services/mise-en-place-flag";
import { RESTS_FLAG_DESCRIPTION, parseRests } from "../services/rests-flag";
import {
collectFlag,
parseAvailability,
parseServe,
parseTimeZone,
} from "../services/plan-flags";
import {
PLAN_FORMATS,
type PlanFormat,
formatPlan,
planRecipe,
planToICS,
} from "../services/planner";
import { ExitCode, GramCLIError } from "../errors";
export default defineCommand({
meta: {
name: "plan",
version,
description:
"Plan a recipe backward from the time it is served: when to start each task, given when you are available",
},
args: {
file: {
type: "positional",
required: true,
description: "Path to a .gram recipe file",
},
serve: {
type: "string",
required: true,
description:
'When it is served, a local date and time (e.g. "2026-10-11 13:00")',
},
tz: {
type: "string",
description:
"IANA time zone of the serving time and of your availability (default: this machine's, e.g. Europe/Paris)",
},
available: {
type: "string",
description:
"When you are available, repeatable: 08:00-22:00 (every day), fri=18:00-22:00 (a day of the week), 2026-10-09=none (a date). Several ranges: 08:00-09:00,18:00-22:00. Default: all day",
},
format: {
type: "string",
description: `Output format: ${PLAN_FORMATS.join(" | ")} (default: text)`,
},
ics: {
type: "string",
description:
"Also write the plan as an iCalendar file (events in UTC, an alarm on every task that needs your hands)",
},
now: {
type: "string",
description:
"The present, to warn when the first task should already have started (default: now). Mostly for tests",
},
scale: {
type: "string",
description:
"Scale factor (e.g. 1.5) or reference ingredient (e.g. farine=300g)",
},
"mise-en-place": {
type: "string",
description: MISE_EN_PLACE_FLAG_DESCRIPTION,
},
rests: {
type: "string",
description: RESTS_FLAG_DESCRIPTION,
},
stock: {
type: "string",
description:
"Comma-separated @use specifiers already on hand for this plan (e.g. @bases/pate.gram,./levain.gram)",
},
},
async run({ args, rawArgs }) {
const file = resolve(args.file as string);
const config = await loadConfig();
try {
const format = String(args.format ?? "text") as PlanFormat;
if (!PLAN_FORMATS.includes(format)) {
throw new GramCLIError(
`Unknown --format value "${args.format}". Expected one of: ${PLAN_FORMATS.join(", ")}.`,
ExitCode.Error,
);
}
const serveAt = parseServe(args.serve);
const timeZone = parseTimeZone(args.tz);
const availability = parseAvailability(
collectFlag(rawArgs ?? [], "available"),
);
const miseEnPlace = parseMiseEnPlace(args["mise-en-place"]);
const rests = parseRests(args.rests);
const stock = resolveStockFromConfig(args.stock, config);
const scaleFactor =
(await resolveScaleArg(
args.scale as string | undefined,
file,
null,
config.language,
config.paths,
)) ?? 1;
const now = (args.now as string | undefined) ?? new Date().toISOString();
const result = await planRecipe(file, {
serveAt,
timeZone,
availability,
now,
miseEnPlace,
rests,
scaleFactor,
lang: config.language,
paths: config.paths,
stock,
});
reportUnusedStock("gram plan", "planned", stock, [result]);
process.stdout.write(formatPlan(result, format, config.language));
if (args.ics) {
const path = resolve(args.ics as string);
const stamp = toUtcIso(parseInstant(now, timeZone));
await writeFile(
path,
planToICS(result, stamp, config.language),
"utf-8",
);
process.stderr.write(`Calendar written to ${path}\n`);
}
process.exit(ExitCode.Ok);
} catch (err) {
if (err instanceof GramCLIError) {
log.error(err.message);
process.exit(err.exitCode);
}
throw err;
}
},
});

View file

@ -12,6 +12,7 @@ import {
MISE_EN_PLACE_FLAG_DESCRIPTION,
parseMiseEnPlace,
} from "../services/mise-en-place-flag";
import { RESTS_FLAG_DESCRIPTION, parseRests } from "../services/rests-flag";
import {
NUTRITION_BASIS_FLAG_DESCRIPTION,
parseNutritionBasis,
@ -77,6 +78,10 @@ export default defineCommand({
type: "string",
description: MISE_EN_PLACE_FLAG_DESCRIPTION,
},
rests: {
type: "string",
description: RESTS_FLAG_DESCRIPTION,
},
stock: {
type: "string",
description:
@ -104,6 +109,7 @@ export default defineCommand({
const bakersMathOnly = args["bakers-math-only"] as boolean;
const nutritionBasis = parseNutritionBasis(args.nutrition);
const miseEnPlace = parseMiseEnPlace(args["mise-en-place"]);
const rests = parseRests(args.rests);
const stock = resolveStockFromConfig(args.stock, config);
let htmlPath: string;
@ -115,6 +121,7 @@ export default defineCommand({
bakersMathOnly,
nutritionBasis,
miseEnPlace,
rests,
lang: config.language,
paths: config.paths,
stock,

View file

@ -14,6 +14,7 @@ import {
MISE_EN_PLACE_FLAG_DESCRIPTION,
parseMiseEnPlace,
} from "../services/mise-en-place-flag";
import { RESTS_FLAG_DESCRIPTION, parseRests } from "../services/rests-flag";
import {
NUTRITION_BASIS_FLAG_DESCRIPTION,
parseNutritionBasis,
@ -72,6 +73,10 @@ export default defineCommand({
type: "string",
description: MISE_EN_PLACE_FLAG_DESCRIPTION,
},
rests: {
type: "string",
description: RESTS_FLAG_DESCRIPTION,
},
stock: {
type: "string",
description:
@ -100,6 +105,7 @@ export default defineCommand({
const bakersMathOnly = args["bakers-math-only"] as boolean;
const nutritionBasis = parseNutritionBasis(args.nutrition);
const miseEnPlace = parseMiseEnPlace(args["mise-en-place"]);
const rests = parseRests(args.rests);
const stock = resolveStockFromConfig(args.stock, config);
let model;
@ -111,6 +117,7 @@ export default defineCommand({
bakersMathOnly,
nutritionBasis,
miseEnPlace,
rests,
lang: config.language,
paths: config.paths,
stock,

View file

@ -79,6 +79,7 @@ const main = defineCommand({
format: () => import("./commands/format").then((m) => m.default),
export: () => import("./commands/export").then((m) => m.default),
print: () => import("./commands/print").then((m) => m.default),
plan: () => import("./commands/plan").then((m) => m.default),
suggest: () => import("./commands/suggest").then((m) => m.default),
upgrade: () => import("./commands/upgrade").then((m) => m.default),
},

View file

@ -13,7 +13,7 @@ import type { IngredientData } from "@gram-lang/analyzer";
// forwarded to the pipeline, not into RendererOptions.
export type ExportOptions = Pick<
RendererOptions,
"hideStepQty" | "bakersMathOnly" | "nutritionBasis" | "miseEnPlace"
"hideStepQty" | "bakersMathOnly" | "nutritionBasis" | "miseEnPlace" | "rests"
> & {
bakersReference?: string;
lang?: string;

View file

@ -0,0 +1,93 @@
import type { RunSheetModel } from "@gram-lang/renderer";
const encoder = new TextEncoder();
/** Escapes a text value the way RFC 5545 asks: backslash, semicolon, comma, newline. */
const escapeText = (text: string) =>
text
.replace(/\\/g, "\\\\")
.replace(/;/g, ";")
.replace(/,/g, "\\,")
.replace(/\r?\n/g, "\\n");
/** Folds a line at 75 octets, never inside a character; a continuation starts with a space. */
function fold(line: string): string {
if (encoder.encode(line).length <= 75) return line;
const parts: string[] = [];
let current = "";
let size = 0;
for (const char of line) {
const width = encoder.encode(char).length;
const limit = parts.length === 0 ? 75 : 74;
if (size + width > limit) {
parts.push(current);
current = "";
size = 0;
}
current += char;
size += width;
}
parts.push(current);
return parts.join("\r\n ");
}
/** "2026-10-10T19:38:00Z" as "20261010T193800Z". */
const compact = (iso: string) => iso.replace(/[-:]/g, "");
export interface IcsOptions {
/** DTSTAMP of every event, an ISO instant in UTC. */
stamp: string;
/** Minutes before an active task at which its alarm rings. Default 5. */
alarmMinutes?: number;
/** Words for the alarm text of a task that is not named in a way a reminder can use. */
calendarName?: string;
}
/**
* The production sheet as an iCalendar file: one event per task, in UTC (the
* calendar shows it in its own zone), and an alarm on the tasks that need the
* cook's hands. Nothing here reads the clock: the stamp is given.
*/
export function buildICS(model: RunSheetModel, options: IcsOptions): string {
const alarm = options.alarmMinutes ?? 5;
const lines: string[] = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//Gram//gram plan//EN",
"CALSCALE:GREGORIAN",
"METHOD:PUBLISH",
`X-WR-CALNAME:${escapeText(options.calendarName ?? model.title)}`,
];
const seen = new Map<string, number>();
for (const day of model.days) {
for (const line of day.lines) {
// A merged mise en place keeps the id of its first task: two events can share one.
const n = (seen.get(line.task) ?? 0) + 1;
seen.set(line.task, n);
const description = [line.detail, line.length, line.note]
.filter(Boolean)
.join("\n");
lines.push(
"BEGIN:VEVENT",
`UID:${compact(line.start)}-${line.task}${n > 1 ? `-${n}` : ""}@gram-lang.org`,
`DTSTAMP:${compact(options.stamp)}`,
`DTSTART:${compact(line.start)}`,
`DTEND:${compact(line.end)}`,
`SUMMARY:${escapeText(line.title)}`,
`DESCRIPTION:${escapeText(description)}`,
);
if (line.active) {
lines.push(
"BEGIN:VALARM",
"ACTION:DISPLAY",
`DESCRIPTION:${escapeText(line.title)}`,
`TRIGGER:-PT${alarm}M`,
"END:VALARM",
);
}
lines.push("END:VEVENT");
}
}
lines.push("END:VCALENDAR");
return `${lines.map(fold).join("\r\n")}\r\n`;
}

View file

@ -0,0 +1,128 @@
import type { Availability, Weekday } from "@gram-lang/scheduler";
import { WEEKDAYS } from "@gram-lang/scheduler";
import { ExitCode, GramCLIError } from "../errors";
const fail = (message: string): never => {
throw new GramCLIError(message, ExitCode.Error);
};
/**
* Every value given to a flag that may be repeated (`--available a --available
* b`). citty keeps the last one of a repeated flag, so these come from the raw
* arguments, `--flag value` and `--flag=value` alike.
*/
export function collectFlag(rawArgs: string[], name: string): string[] {
const values: string[] = [];
const long = `--${name}`;
for (let i = 0; i < rawArgs.length; i++) {
const arg = rawArgs[i]!;
if (arg === long) {
const next = rawArgs[i + 1];
if (next !== undefined) values.push(next);
i++;
} else if (arg.startsWith(`${long}=`)) {
values.push(arg.slice(long.length + 1));
}
}
return values;
}
/**
* `--serve "2026-10-11 13:00"`: a local date and time, in the time zone of the
* plan. A `T` instead of the space works too.
*/
export function parseServe(value: unknown): string {
const text = String(value ?? "").trim();
const m = /^(\d{4}-\d{2}-\d{2})[T ](\d{1,2}):(\d{2})$/.exec(text);
if (!m) {
return fail(
`Expected --serve like "2026-10-11 13:00" (a local date and time), got "${text}".`,
);
}
return `${m[1]}T${m[2]!.padStart(2, "0")}:${m[3]}`;
}
/** `--tz Europe/Paris`: checked here so a typo is a clear message, not a stack trace. */
export function parseTimeZone(value: unknown): string {
const zone =
typeof value === "string" && value !== ""
? value
: Intl.DateTimeFormat().resolvedOptions().timeZone;
try {
new Intl.DateTimeFormat("en", { timeZone: zone });
} catch {
return fail(
`Unknown time zone "${zone}". Use an IANA name like Europe/Paris.`,
);
}
return zone;
}
const CLOCK = /^([01]?\d|2[0-4]):([0-5]\d)$/;
const DATE = /^\d{4}-\d{2}-\d{2}$/;
function parseRanges(
text: string,
flag: string,
): { start: string; end: string }[] {
if (text === "none") return [];
return text.split(",").map((part) => {
const [start, end, ...extra] = part.split("-");
if (
start === undefined ||
end === undefined ||
extra.length > 0 ||
!CLOCK.test(start) ||
!CLOCK.test(end)
) {
return fail(
`Expected --available ${flag} like 08:00-22:00 (several: 08:00-09:00,18:00-22:00, none for no availability), got "${part}".`,
);
}
return { start, end };
});
}
/**
* `--available` entries, each one of:
* 08:00-22:00 every day
* fri=18:00-22:00 a day of the week (mon … sun)
* 2026-10-09=none a date (none: not available at all)
* Several ranges go after one key, separated by commas, and an entry may be
* repeated to add to it. Without any entry, the cook is available all day.
*/
export function parseAvailability(entries: string[]): Availability {
if (entries.length === 0) {
return { daily: [{ start: "00:00", end: "24:00" }] };
}
const daily: { start: string; end: string }[] = [];
const weekdays: Partial<Record<Weekday, { start: string; end: string }[]>> =
{};
const dates: Record<string, { start: string; end: string }[]> = {};
for (const entry of entries) {
const eq = entry.indexOf("=");
if (eq === -1) {
daily.push(...parseRanges(entry, entry));
continue;
}
const key = entry.slice(0, eq).toLowerCase();
const ranges = parseRanges(entry.slice(eq + 1), key);
if ((WEEKDAYS as readonly string[]).includes(key)) {
weekdays[key as Weekday] = [
...(weekdays[key as Weekday] ?? []),
...ranges,
];
} else if (DATE.test(key)) {
dates[key] = [...(dates[key] ?? []), ...ranges];
} else {
fail(
`Unknown --available key "${key}": use a day of the week (${WEEKDAYS.join(", ")}) or a date like 2026-10-09.`,
);
}
}
return {
daily,
...(Object.keys(weekdays).length > 0 && { weekdays }),
...(Object.keys(dates).length > 0 && { dates }),
};
}

View file

@ -0,0 +1,110 @@
import {
describeRunSheet,
runSheetToHTML,
runSheetToMarkdown,
runSheetToText,
} from "@gram-lang/renderer";
import type {
CompilationResult,
MiseEnPlaceMode,
RestChoice,
} from "@gram-lang/kitchen";
import {
type Availability,
type ProjectedPlan,
type RunSheet,
project,
runSheet,
} from "@gram-lang/scheduler";
import { runPipeline } from "../core/pipeline";
import { buildICS } from "./ics";
export type PlanFormat = "text" | "md" | "html" | "json";
export const PLAN_FORMATS: readonly PlanFormat[] = [
"text",
"md",
"html",
"json",
];
export interface PlanOptions {
/** A local date and time, "2026-10-11T13:00". */
serveAt: string;
timeZone: string;
availability: Availability;
/** The present, for the warning about a start already behind. */
now?: string;
miseEnPlace?: MiseEnPlaceMode;
rests?: RestChoice;
scaleFactor?: number;
lang?: string;
paths?: Record<string, string>;
stock?: Set<string>;
}
export interface PlanResult {
compiled: CompilationResult;
plan: ProjectedPlan;
sheet: RunSheet;
usedStock: Set<string>;
}
/** Compiles a recipe and places it on the calendar, ending when it is served. */
export async function planRecipe(
filePath: string,
options: PlanOptions,
): Promise<PlanResult> {
const { compiled, usedStock } = await runPipeline(filePath, {
skipAnalyzer: true,
scaleFactor: options.scaleFactor,
lang: options.lang,
paths: options.paths,
stock: options.stock,
});
const plan = project(
[
{
graph: compiled.tasks,
title: compiled.title ?? undefined,
options: { miseEnPlace: options.miseEnPlace, rests: options.rests },
},
],
{
serveAt: options.serveAt,
timeZone: options.timeZone,
availability: options.availability,
...(options.now !== undefined && { now: options.now }),
},
);
return { compiled, plan, sheet: runSheet(plan), usedStock };
}
/** The sheet in one of the formats `--format` offers. */
export function formatPlan(
result: PlanResult,
format: PlanFormat,
lang?: string,
): string {
const { compiled, plan, sheet } = result;
switch (format) {
case "text":
return runSheetToText(sheet, compiled, { lang });
case "md":
return runSheetToMarkdown(sheet, compiled, { lang });
case "html":
return runSheetToHTML(sheet, compiled, { lang });
case "json":
return `${JSON.stringify({ plan, runSheet: sheet }, null, 2)}\n`;
}
}
/** The sheet as an iCalendar file, every event stamped `stamp` (an ISO instant, UTC). */
export function planToICS(
result: PlanResult,
stamp: string,
lang?: string,
): string {
return buildICS(describeRunSheet(result.sheet, result.compiled, { lang }), {
stamp,
});
}

View file

@ -0,0 +1,24 @@
import { REST_CHOICES, type RestChoice } from "@gram-lang/kitchen";
import { ExitCode, GramCLIError, reportError } from "../errors";
export const RESTS_FLAG_VALUES: readonly string[] = REST_CHOICES;
export const RESTS_FLAG_DESCRIPTION = `How long a rest written as a range (~_{12-24h}) lasts: ${RESTS_FLAG_VALUES.join(" | ")} (default: shortest). An exact rest and an active timer are not affected. Changes the total and idle times.`;
/**
* Reports and exits on an unusable value, like `parseMiseEnPlace`: an
* argument-validation failure raised before any work starts.
*/
export function parseRests(value: unknown): RestChoice | undefined {
if (value === undefined || value === null || value === "") return undefined;
if ((REST_CHOICES as readonly unknown[]).includes(value)) {
return value as RestChoice;
}
reportError(
new GramCLIError(
`Unknown --rests value "${value}". Expected one of: ${RESTS_FLAG_VALUES.join(", ")}.`,
ExitCode.Error,
),
);
return process.exit(ExitCode.Error);
}

View file

@ -11,6 +11,7 @@ import {
import {
type CompilationResult,
type MiseEnPlaceMode,
type RestChoice,
scheduleTimes,
} from "@gram-lang/kitchen";
import type { RecipeViewModel } from "../types";
@ -157,6 +158,8 @@ export async function buildViewModel(
nutritionBasis?: NutritionBasis;
/** Which timeline the total and rest times follow. Default per section. */
miseEnPlace?: MiseEnPlaceMode;
/** How long a rest written as a range lasts. Default shortest. */
rests?: RestChoice;
lang?: string;
paths?: Record<string, string>;
stock?: Set<string>;
@ -192,6 +195,7 @@ export async function buildViewModel(
const { totalTime: total, idleTime: rest } = scheduleTimes(
compiled,
opts.miseEnPlace,
opts.rests,
);
const times =
m && (total || rest || m.activeTime || m.preparationTime)

Some files were not shown because too many files have changed in this diff Show more