Skip to content

Command line interface (CLI)

The official Gram CLI (@gram-lang/cli) is the primary tool for validating, compiling, and managing your recipe collections locally. It acts as the bridge between your .gram files and the rest of your technical stack (SSG, Next.js, mobile apps, etc.).

npm install -g @gram-lang/cli

The CLI runs equally well on Node.js (>=22, automatically loading .env files via process.loadEnvFile) and Bun — no runtime-specific APIs are required, so both environments behave identically.

When a newer version is published on npm, gram prints a short notice after any command finishes (skipped in CI environments and non-interactive runs). Run gram upgrade to check and install updates on demand, or silence the passive notice with gram config set updateCheck false — or, for a single invocation, via the GRAM_NO_UPDATE_CHECK environment variable.

  • --verbose / --debug: usable with any command, prints a full stack trace on error instead of just the terse message.
  • --stock <specifiers>: treats specified imported module paths as already on hand (skips their timeline cooking steps and collapses them into a single purchasable product on shopping lists). Accepts comma-separated paths (@bases/shortcrust.gram,./sauces/bechamel.gram).

Recipe settings are uniform across all interfaces: CLI flags, gram.* configuration keys in the VS Code extension, and options in the playground all share the same names, values, and defaults. Each CLI flag corresponds to its underlying setting and is accepted by every command affected by it.

View presentation settings:

FlagValuesDefaultCommands
--mise-en-placeper-section, upfront, per-dayper-sectionview, print, export, plan, cook
--restsshortest, balanced, longestshortestview, print, export, plan, cook
--commentsshow, hideshowview, print, export, plan
--nutrition-basisauto, total, per-portion, per-100gautoview, print, export
--bakers-math-onlyon or offoffview, print, export
--step-quantitiesshow, hideshowview, print, export
--clock v1.5.0auto, 12h, 24hautoprint, export, plan

Analyzer computation settings (all enabled by default; use --no-<flag> to disable):

FlagWhat it doesCommands
--bakers-mathComputes baker’s percentages from the ingredient marked with * or specified via --bakers-reference. When provided without an explicit reference, it also warns if the recipe declares none.view, print, export, cook, build, watch, shop
--mass-standardizationStandardizes quantities to grams using the ingredient database.same
--yield-calculationAccounts for preparation waste (peels, pits, trim), adjusting required purchasing quantities relative to net culinary weights.same
--nutrition-estimationEstimates nutritional values across the recipe.same
  • --mise-en-place controls when prep runs (per-section, upfront, or per-day), updating total and idle times in headers (and placing a “Mise en place” heading in HTML). See When the mise en place happens.
  • --rests resolves elastic passive ranges (~_{12-24h}) to shortest, balanced (midpoint), or longest; exact durations and active timers are unaffected.
  • --comments shows or hides recipe comments (// like this): numbered footnotes in recipe views, discreet muted text in the run sheet.
  • --nutrition-basis (alias --nutrition) chooses the displayed nutrition basis (auto shows per 100 g of raw assembled mixture and per portion side by side; see Nutritional Estimation).
  • --step-quantities (alias --no-step-qty for hide) controls whether quantities and standardized masses (flour (250 ml, ~148 g)) are repeated inside step prose. Section ingredient lists always show them.
  • --clock chooses how the run sheet and the serving time suggestions write the time of day: 12h (1:00 PM), 24h (13:00), or auto, which follows the region of your system’s locale (LC_ALL, then LC_TIME, then LANG), not the language of the recipe; a locale that names no region (C, en) reads 24 hours. Without the flag, the clock setting of the project (or global config) applies. The JSON output and the times of the iCalendar events, written in UTC, are unaffected.
  • Supplying an unsupported value halts execution with an error listing accepted options.

Scaffolds a new Gram environment in the current directory.

  • Creates a .gram/ directory.
  • Generates a plain, uncommented config.yaml.
  • Interactively configures your preferred recipe language (currently en or fr).
  • Interactively configures your preferred AI provider and model.
  • Generates or updates a .env file for your AI API keys.
  • Generates a documented starter ingredients.yaml ingredient database at .gram/ingredients.yaml.
  • Generates a .gitignore to prevent committing sensitive keys.

Checks npm for a newer @gram-lang/cli release and offers to install it.

gram upgrade
  • Always performs a fresh lookup against the npm registry — independent of the passive background check.
  • Prints a comparison of the installed and latest versions, then asks for confirmation before executing npm install -g @gram-lang/cli@latest.
  • Performs no changes (beyond reporting status) when already up to date.

Validates your .gram files for syntax errors, structural integrity, and undefined ingredients.

  • Runs the Ohm.js parser to catch syntax errors.
  • Runs the Kitchen compiler to catch structural errors (e.g. cyclic dependencies).
  • Connects to your ingredients.yaml database to flag undocumented ingredients.
  • Warnings (nutritional estimation gaps, incomplete-but-valid annotations) do not fail the command by default — only structural errors (undefined references, scope conflicts) trigger a non-zero exit code. Pass --strict to treat every warning as a hard error (ideal for CI pipelines).
  • Options: --db <path>, --skip-db, --strict.

Compiles your .gram recipes into the final, minified JSON format.

gram build "**/*.gram" --output ./dist
gram build brioche.gram --pretty
gram build brioche.gram --scale 2 --output ./dist-doubled
  • By default, outputs pure JSON directly to stdout for easy piping into downstream tools.
  • Automatically calculates nutritional data and physical mass standardization via the database.
  • --scale <factor> bakes the scaling factor directly into the JSON output. Reference mode (e.g. flour=300g) is intentionally unavailable here: because build processes files in batches, reproducible output must not depend on reading one specific file’s shopping list first. Use gram view or gram scale to determine your factor, then pass that numeric multiplier to build.
  • When a glob or multiple files are supplied, files imported (via @use) by other recipes in the same batch are excluded by default, preventing their ingredients from being double-counted (both standalone and composed into the host recipe). Pass --include-modules to build them anyway.
  • Options: --output/-o <dir>, --pretty, --scale <factor>, --db <path>, --skip-db, --include-modules, and the analyzer’s settings flags.

Displays a recipe directly in the terminal: a box with the title, the servings and the times, then the shopping list, the cookware, each section (its ingredients, then its numbered steps), the notes and the nutrition. It is the text format of the recipe view, the same text as gram export --format text, in colors, in the language of your project.

gram view brioche.gram                      # Default view
gram view brioche.gram --scale 2            # Scaled to double quantities
gram view brioche.gram --scale flour=300g   # Scaled to flour = 300g
  • Supports automatic paging for long recipes (--no-pager disables it).
  • Displays calculated nutrition, timings, and ingredient checklists; common fractions such as 1/4 tsp remain fractions in the shopping list.
  • Passing --scale adjusts all ingredient quantities (both in the shopping list and in-step references).
  • The recipe view shows no schedule: it reads the same at any time. For when to come and what to take out, see gram plan below.
  • Options: --scale <factor|ref>, --no-pager, --skip-db, --db, --bakers-reference <id>, plus all settings flags.

Imports a recipe from a web page URL, a local JSON-LD file, or a YouTube video / Short, and converts it into valid Gram syntax using AI.

gram import "https://example.com/recipe"          # Web page with Schema.org / JSON-LD
gram import recipe.json                            # Local JSON / JSON-LD file
gram import "https://www.youtube.com/watch?v=…"   # YouTube video
gram import "https://www.youtube.com/shorts/…"    # YouTube Short (automatically normalized)
gram import recipe.json -o brioche.gram -y         # Direct export without interactive confirmation

Supported sources:

  • Web page URLs: automatically fetches the page and extracts structured application/ld+json recipe metadata (Schema.org Recipe).
  • Local JSON / JSON-LD files: parses exported JSON-LD schemas directly from disk.
  • YouTube videos & Shorts: analyzes cooking videos directly using Gemini native multimodal video understanding (without requiring third-party transcript scrapers).

Workflow & guardrails:

  • Translates and formats the recipe into valid Gram syntax, respecting the language configuration.

  • Requires an AI provider to be configured (see Configure AI Provider).

  • Before writing to --output, the converted recipe is presented for interactive review and confirmation. In non-interactive runs, the review is skipped with a warning — pass --yes/-y to deliberately accept writing.

  • Nothing is written if the import result exhibits major defects. Two strict verification checks are enforced:

    • Lost content detection — every @ingredient present in the source text is verified against what the compiler actually registered. A mismatch indicates that text was swallowed (most commonly by a // comment dropped mid-sentence that hid the remainder of the line). Such a file would compile without error while missing critical ingredients.
    • Unresolved error handling — the AI engine is granted two autonomous repair attempts to resolve syntax issues. If errors survive, they are reported in the terminal and file writing is canceled.

    Pass --force to write the file despite warnings, or retry with a higher-capability --model.

  • source: and author: are extracted directly from source metadata (or YouTube video details), and are omitted when missing — the model never invents them.

  • Ingredients returned without an explicit quantity are counted and listed by line number. This is not a syntax error — @salt{} is idiomatic for “to taste” —, but it provides the clearest objective measure of how complete the recipe is, highlighting lines for manual review. An ingredient quantified on its first appearance and simply referenced later is not counted as unmeasured.

  • When an ingredient database is present, the analyzer also reports unresolvable items (unknown ingredients, units lacking a known density). These reflect gaps in your local database rather than import failures, so they never block the command.

YouTube video import specifics:

  • Google / Gemini provider required: Gemini is the only provider that natively processes YouTube video URLs. With any other provider, the import halts immediately.
  • Token consumption scales with duration, at roughly 100 input tokens per second of video: a Short uses a few thousand tokens, 10 minutes uses around 60,000 tokens, and 26 minutes uses around 158,000 tokens. Videos exceeding 20 minutes are rejected by default; raise the ceiling via --max-duration <minutes>.
  • Pre-execution cost estimation requires YOUTUBE_API_KEY: a standard YouTube Data API key, read strictly from environment variables (never stored in config.yaml). In its absence, the import still executes, but without the ability to determine length upfront or enforce limits beforehand.
  • Video quantity expectations: cooking videos convey far fewer explicit measurements than written recipes. The system prompt instructs the model to leave brackets {} empty rather than guess arbitrary figures. Expect to fill in certain measurements manually.
  • title:, author: (channel name), and source: (URL) are retrieved directly from YouTube metadata and used verbatim.
  • Options: --output/-o <file>, --yes/-y, --force, --max-duration <minutes>, plus the shared AI options.

Compiles a consolidated shopping list across multiple recipes.

gram shop "**/*.gram"                 # All recipes
gram shop brioche.gram --scale 2      # Double all quantities
gram shop "menus/*.gram" --scale 4    # Batch cooking × 4
  • Aggregates quantities intelligently using reference densities (volume → grams when density is known).
  • Groups ingredients by their category field (culinary families: Produce, Dairy, Grains, etc.).
  • Alias consolidation: if two recipes use different names for the same ingredient (e.g. butter and beurre), they are merged under their canonical key via database aliases.
  • Ingredients without quantities (e.g. @salt{}) are listed alongside their main entry rather than segregated into a separate section.
  • Full support for small units: pinch, dash, and drop (along with localized variants) aggregate cleanly.
  • --scale <factor> applies a uniform numeric multiplier to all recipes (global factor only — reference-based scaling is not supported for multi-file batches).
  • When a glob or multiple files are provided, files imported (via @use) by other recipes in the batch are excluded by default to avoid duplicate shopping list entries. Pass --include-modules to include them.
  • Options: --format terminal|md|json, --output/-o <file>, --scale <factor>, --db, --skip-db, --include-modules, and the analyzer’s settings flags.

With --format json, each item keeps the human-readable qty string (2 cup + 3 tbsp, 3,9 kg) alongside structured numeric fields for scripts v1.5.0:

  • amount: plain number in the unit shown by qty (3.9 for "unit": "kg"), always using a dot decimal; null if the ingredient has no quantity or mixes incompatible units.
  • unit: canonical unit (tbsp for tablespoons or c. à s.), or null for counts (@eggs{4}). Compatible scales add up in the smallest unit written (2 cup + 3 tbsp gives "amount": 35, "unit": "tbsp").
  • range: { min, max } bounds when the item is a range (amount holds the midpoint).
  • parts: array of { amount, unit } entries when incompatible units cannot be summed (1 1/2 cups + 70 g gives [{ "amount": 1.5, "unit": "cup" }, { "amount": 70, "unit": "g" }]).
  • unresolved: unresolvable portions such as (2% of dough ❓), excluded from amount.
{ "id": "salt", "name": "salt", "qty": "3 g + (2% of dough ❓)", "amount": 3, "unit": "g", "unresolved": ["(2% of dough ❓)"], "isEstimate": false, "category": "Spices", "recipes": ["brioche"] }

Launches an interactive step-by-step cooking guide directly in the terminal.

gram cook brioche.gram
gram cook carbonara.gram --skip-db

The total time displayed on the summary screen, and the duration of each timer, respect --mise-en-place and --rests just like gram view, and the analyzer’s settings flags apply to displayed masses.

Flow:

  1. Mise en place: comprehensive aggregated ingredient list for the entire recipe (Space to start).

  2. Section intro: ingredient summary for the upcoming section (shown before each section begins).

  3. Cooking steps: progressive one-step-at-a-time view in a two-column layout: required ingredients on the left, instructions on the right.

  4. Summary screen: total elapsed time spent cooking.

Ingredients are aggregated per section: repeated uses of the same ingredient within a single section are combined into one entry preserving individual amounts (e.g. 200g butter followed by 50g butter is displayed as 200g + 50g butter, rather than arithmetically summed). The ingredient panel provides all necessary quantities for that section at a single glance.

Timers — timers declared in the recipe (~label{30min}) appear in the step view:

  • Press T to start a timer; if multiple timers are available, a selection menu appears.
  • Timers run in the background and remain visible as you advance through steps.
  • A terminal bell rings and the timer display switches to a static “done” state when it reaches zero.
  • Q or Esc triggers a quit-confirmation prompt to avoid accidentally interrupting an active timer.

Keyboard shortcuts:

KeyAction
Space / EnterNext step
BPrevious step
TStart a timer
Q / EscQuit (asks for confirmation if a timer is running)
  • Options: --scale <factor|ref>, --skip-db, --db.

Displays a semantic diff of a recipe — comparing the logical structure of ingredients, timings, sections, and temperatures rather than raw text differences.

gram diff brioche.gram                        # Working tree vs HEAD (most common)
gram diff brioche.gram --ref HEAD~2           # Compare against a specific commit
gram diff brioche.gram --ref v1.2             # Compare against a git tag
gram diff brioche-v1.gram brioche-v2.gram     # Compare two explicit files (no git dependency)

The diff spans seven distinct axes:

  • Ingredients — added, removed, or modified quantities, with percentChange calculated when units match.

  • Timings — totalTime, idleTime, activeTime, preparationTime in minutes. Total and passive times reflect the default schedule (mise en place immediately before each section), matching gram view.

  • Sections — added or removed sections and step-count changes.

  • Frontmatter — changes to portions, description, and other metadata fields. A title change is tracked separately and displayed above the frontmatter block.

  • Preparations — modified preparation methods per ingredient (e.g. “diced” → “sliced”).

  • Temperatures & timers — temperature targets and timer durations added, removed, or modified per section.

  • Modules — @use imports added, removed, re-bound to a different name, or rescaled to a different factor.

  • Operates on compiled objects produced by the Kitchen compiler. Syntactic reformatting (whitespace, line breaks) produces no semantic diff.

  • Git mode requires the file to be tracked. An explicit error is returned if git is unavailable on the system.

  • A section spliced in from an @use import never counts toward the Sections/Preparations/Temperatures/Timers axes of the host recipe — otherwise adding one import would give the false impression that every other section had moved. The Modules axis reports the import itself. gram diff does not resolve @use recursively: each side is compiled standalone, so a change inside an imported base will not appear here — diff the base file directly for that.

  • Options: --ref <git-ref>.

Displays a before/after comparison table of ingredient quantities for a given scaling target.

gram scale brioche.gram --scale 2            # Double all quantities
gram scale brioche.gram --scale 0.5          # Halve all quantities
gram scale brioche.gram --scale flour=300g   # Scale so that flour = 300g
gram scale brioche.gram --scale eggs=3       # Scale so that eggs = 3
  • Displays a comparison table: original quantities (dimmed) versus recalculated quantities (highlighted).
  • Quantities that cannot be scaled (qualitative values like “1 pinch”) are listed separately.
  • Warns on extreme factors (below ×0.1 or above ×20) and reminds that cooking times are never adjusted arithmetically.
  • Reference mode (id=value) computes the factor from the nominal quantity of the targeted ingredient (the ID must match the ingredient’s canonical key). Units in the same family convert automatically (e.g. flour=1kg against a recipe written in 500g). Crossing mass ↔ volume (e.g. water=150g against a recipe in ml) is supported whenever a density is known (via gram db enrich or a densities: ["water:1.0"] frontmatter override).
  • Not every ingredient can be used as a reference target: fixed (@=) ingredients, relative proportions (70% @&flour), ingredients used exclusively inside a sub-recipe (their composite parent is the valid reference instead), ingredients inside alternative groups, and ingredients split across incompatible units are rejected with a clear explanation. See Deep Dive: Scaling for the full list of constraints.
  • Options: --scale <factor|ref>, --skip-db, --db.

Watches a directory for .gram file modifications and automatically re-runs gram check upon saving.

gram watch                              # Watch project root
gram watch recipes/                     # Watch a specific directory
gram watch --build --output ./dist      # Also compile changed files to JSON
  • Displays a timestamped result line per event: [12:34:01] ✓ brioche.gram or ✗ brioche.gram — 1 error.
  • Errors are displayed inline directly below the filename. The watch process never terminates upon a validation error.
  • A 150 ms debounce delay prevents redundant executions when editors save files in multiple chunks.
  • Saving an imported base recipe also re-checks every file under the watched directory that imports it via @use (directly or transitively). A → rechecking N dependent file(s) message indicates how many files were affected.
  • Options: --build, --output/-o <dir>, --skip-db, --db, and the analyzer’s settings flags.

Finds recipes across your project that can be prepared with a given set of ingredients.

gram suggest --with "butter, eggs"
gram suggest --with "chicken" --without "cream"
gram suggest --with "lemon, garlic" --top 5 --min-match 50
gram suggest --with "beurre" --json           # Alias-aware: beurre → butter
  • Scans all .gram files in parallel using only the parser (without full pipeline compilation), providing fast results across large collections.
  • Alias-aware matching: if a database is configured, ingredient names are resolved through the alias index. Searching for "beurre" will match recipes containing @butter.
  • Scores each recipe by match percentage (matched / total with-terms). Use --min-match to filter out low-scoring matches.
  • --without immediately excludes any recipe containing one of those ingredients.
  • Options: --with/-w <csv>, --without <csv>, --top/-n <n> (default 10), --min-match <0–100> (default 1), --pattern <glob>, --db, --skip-db, --json.

Generates a print-ready HTML document and opens it in the default web browser.

gram print brioche.gram                   # Generate and open
gram print brioche.gram --scale 2         # Print at double quantities
gram print brioche.gram --no-open         # Generate only, print file path to stdout
  • The HTML document is written to a temporary file (gram_print_<timestamp>.html in the OS temp directory) and opened via the system default handler (open on macOS, xdg-open on Linux, cmd /c start on Windows).
  • Output matches gram export --format html — designed for browser print dialogs (Ctrl+P / Cmd+P) to produce an A4 PDF.
  • --view <recipe|run-sheet> selects the view to print: the recipe (default) or its run sheet (formatted one day per page with checkboxes). In run sheet mode, scheduling options (--serve, --tz, --available, --now) work just like gram plan; without --serve, the plan uses relative countdown days (D-2, D-1, Day D).
  • Options: --no-open, --view <recipe|run-sheet>, --scale <factor|ref>, --skip-db, --db, --bakers-reference <id>, plus all settings flags.

Exports a recipe to Markdown, print-ready HTML or plain text.

gram export brioche.gram --format md                   # Generates brioche.md alongside the source
gram export brioche.gram --format html -o ~/print.html # Explicit destination path
gram export brioche.gram --format html --scale 2       # Export at double quantities
gram export brioche.gram --format text                 # Generates brioche.txt
  • --format md — standard Markdown formatted with a shopping list, equipment inventory, and numbered steps.
  • --format html — standalone A4-ready HTML document with embedded CSS for printing and inline Lucide SVG icons (imports Courier Prime and Inter from Google Fonts via CSS @import).
  • --format text — plain text matching gram view (or gram plan for the run sheet). Each view offers only the formats it supports; asking for another lists the valid ones.
  • --view <recipe|run-sheet> selects the view to export: the recipe (default, written alongside the source with .md, .html, or .txt) or its run sheet (default filename <recipe>.run-sheet.md / .html / .txt, accepting the same --serve, --tz, --available, and --now options as gram plan).
  • Options: --format md|html|text, --view <recipe|run-sheet>, --output <path>, --scale <factor|ref>, --skip-db, --db, --bakers-reference <id>, plus all settings flags.

Computes the operational schedule of a recipe: daily breakdown, active kitchen visits, items to take out, and tasks to perform. With --serve, the backward schedule is calculated from meal time against your availability. Without a serving time, the schedule is presented in relative days (D-2, D-1, Day D) and indicates the earliest possible serving time starting immediately.

gram plan bread.gram --serve "2026-10-11 13:00" --tz Europe/Paris --available 08:00-22:00
gram plan bread.gram --serve "2026-10-11 13:00" --available 08:00-22:00 --available sat=09:00-23:00 --available 2026-10-09=none
gram plan bread.gram --serve "2026-10-11 13:00" --format md        # Markdown output instead of text
gram plan bread.gram --serve "2026-10-11 13:00" --ics bread.ics    # Also generates an iCalendar file
gram plan bread.gram                                                # Relative schedule and earliest serving time
gram plan bread.gram --find 2026-10-10/2026-10-14 --available 08:00-22:00   # Find viable serving times
  • --serve "<date> <time>": target serving time in the configured time zone, in 24 or 12 hours ("2026-10-11 13:00" or "2026-10-11 1:00 pm") v1.5.0. Optional: without it, the schedule is displayed in relative days (D-2, D-1, Day D) without calendar dates, concluding with the earliest serving time calculated across a 14-day window from --now.
  • --tz <zone>: an IANA time zone identifier (e.g. Europe/Paris). Default: the timezone setting of your project (or global config), falling back to the system time zone. Used to interpret serving times, evaluate availability intervals, and handle daylight saving shifts.
  • --available <range>, repeatable: defines working availability windows for active kitchen tasks. 08:00-22:00 (or 8am-10pm v1.5.0) applies to all days; a day-of-week prefix (fri=18:00-22:00, from mon to sun) restricts the rule to that day; a specific date prefix (2026-10-09=none) overrides a calendar date (none indicating complete unavailability). Multiple intervals can follow a single key separated by commas (sat=08:00-09:00,18:00-22:00), and an interval whose end time precedes its start time spans across midnight. Times can be written in 24 hours or in 12 hours with am/pm, in any case and with or without spaces (8:30 am - 10:00 pm, fri=6PM-11PM); 12am is midnight and 12pm noon, and 12am at the end of an interval is the end of the day (6pm-12am is 18:00-24:00). A bare hour (8) is refused. Without the flag, the availability setting of your project (or global config) applies in the same syntax; without either, availability is treated as continuous (24/7). A flag replaces the setting rather than adding to it.
  • --find <from>/<to>: scans a time range (e.g. 2026-10-12/2026-10-15, dates or full timestamps, a time in 24 or 12 hours: 2026-10-12 6pm/2026-10-15) to identify viable meal times, ranked by preference (best options first), explaining the blocking constraints for each rejected slot. Formats: text, md, json. Incompatible with --serve.
  • --meal-times <HH:MM,HH:MM>: candidate meal times evaluated by --find, in 24 or 12 hours (12:30,20:00 or 12:30pm,8pm) (default: value from mealTimes config, otherwise 12:30,20:00).
  • Range-based passive timers (~_{8-16h}) are automatically adjusted (extended or shortened) by the scheduler to align active tasks within your availability windows; the schedule documents all adjustments made and lists any unresolved constraints. See Planning and run sheets.
  • --format text|md|html|json: output format (default text). json outputs the structured { plan, runSheet } object (or runSheet only alongside the earliest field when no serving time is given, or candidate and rejection lists with --find). See the run sheet.
  • --ics <file>: generates an iCalendar (.ics) file with one event per kitchen visit (timestamped in UTC and automatically displayed in your local time zone by your calendar client), a 10-minute reminder alarm, and the checklists in its description. Requires --serve. The confirmation message is printed to stderr, keeping piping via --format json --ics … fully usable.
  • --now <instant> sets the reference time (default: current execution time) used to raise a warning if the initial visit should already have started in the past.
  • Also accepts --scale, --stock, and the relevant settings flags (--mise-en-place, --rests, --comments).

Auto-formats .gram files in-place applying 13 canonical rules from @gram-lang/format.

gram format                              # Format all *.gram files
gram format brioche.gram                 # Format a single file
gram format "recipes/**/*.gram" --check  # CI check — exit code 1 if any file requires formatting

13 canonical rules applied:

  1. Frontmatter formatting — delimiter normalization and whitespace cleanup
  2. Section header titles — single space after ##
  3. Step indexing — normalized step prefixes (1. )
  4. Action blocks — normalized action prefixes ([Mix])
  5. Ingredient tokens — @ingredient{qty} spacing and bracket syntax
  6. Cookware tokens — #cookware{qty} spacing and bracket syntax
  7. Timer tokens — ~timer{duration} active and ~_timer{duration} passive spacing
  8. Temperature tokens — ^temp{value} formatting
  9. Intermediate declarations & references — ->&dough and &dough canonical spacing
  10. Composite syntax — <@parent composite ingredient syntax
  11. Trailing decimal zeros — numerical cleanup {500.0g} → {500g}, {1.50g} → {1.5g}
  12. Comment formatting — clean spacing after comment sigils (//)
  13. Whitespace cleanup & single trailing EOF newline

Output per file: ✔ brioche.gram 2 IDs lowercased · 1 trailing zero removed The formatter is strictly idempotent: running it repeatedly produces no further alterations after the first run.

  • Options: --check.

Commands nested under gram config to inspect and modify local project settings or global user configuration.

Displays all configuration values from both the local project config and the global config.

gram config list

Prints a single configuration value to standard output.

gram config get ai.provider      # → google
gram config get database         # → .gram/ingredients.yaml
gram config get ai.provider --global

Sets a configuration parameter value.

gram config set database ./my-db.yaml
gram config set ai.provider google
gram config set ai.apiKey AIza...           # Writes GEMINI_API_KEY to .env
gram config set database ./global-db.yaml --global
  • Values are written to .gram/config.yaml by default; pass --global to target ~/.config/gram/config.yaml.
  • Sensitive keys (ai.apiKey) are always written to the project .env file. The environment variable name is derived from the active provider (e.g. google → GEMINI_API_KEY).
  • Numeric and boolean strings are coerced automatically ("2" → 2, "true" → true).

Removes a configuration parameter.

gram config unset ai.model
gram config unset ai.apiKey         # Removes the API key environment variable from .env

Commands nested under gram db to manage your ingredients.yaml repository.

  1. Scans your recipes to identify undocumented ingredients and adds them to the database.

    • Interactive fuzzy matching (Levenshtein distance) helps prevent duplicates from typos and plural forms.
    • Options: --dry-run/-n (preview without writing), --db <path>.
  2. Uses AI to detect and resolve semantic duplicates and plural forms in your database.

    • Detects cross-language duplicates (e.g. sucre / sugar) and plural forms (e.g. eggs → egg).
    • For each conflict, you decide which canonical key to keep. The discarded term is automatically retained as an alias.
    • Displays a targeted nutrition diff (only differing fields) when conflicting nutritional data exists, enabling informed arbitration.
    • Flags ingredients whose names or aliases would collide once normalized (e.g. Huile d'olive and huile-dolive), ensuring no recipe silently resolves to the wrong entry.
    • Options: --report/-r (display issues without writing fixes), --db <path>, plus the shared AI options.
  3. Uses AI to propose missing data across your database, walking you through an interactive review before writing changes to disk.

    • Proposes density, unit_weight, nutrition, category, and tags fields in batches (unit_weight is filled alongside density). category denotes a culinary family (e.g. Vegetables, Dairy, Grains) — distinct from free-form tags.
    • nutrition covers every nutrient accepted by the database schema, including fat subtypes (sat_fat, mono_fat, poly_fat) and alcohol.
    • category and tags are applied automatically; density, unit_weight, and nutrition are reviewed entry-by-entry (accept, edit, or skip) because they depend on the specific physical products in your kitchen.
    • Values accepted without edits are tagged # [LLM] in ingredients.yaml, distinguishing unreviewed AI estimates from human-verified entries.
    • Safely re-runnable: only fields that remain vacant are submitted for enrichment.
    • Options: --ingredient <slug> (enrich a single entry), --field density|nutrition|tags|category|all (default all), --yes/-y (skip manual review and accept all — for automated scripts), --report/-r (preview proposals without writing), --db <path>, plus the shared AI options.

Validates the structural integrity of your ingredients.yaml file.

  • Checks for schema errors, duplicate aliases, and incoherent values (e.g. density > 2.5).
  • A malformed entry does not stop validation: every record is evaluated independently, and the final report summarizes all issues in a single pass.
  • Options: --strict (exit code 1 on warnings, suited for CI).

Searches and displays ingredient entries in full detail.

gram db search butter            # Partial match on id, name, or alias
gram db search --tag dairy       # Ingredients tagged 'dairy'
gram db search --category Grains # Ingredients in the Grains category
gram db search --missing nutrition  # Entries lacking nutritional data
gram db search --exact butter --count  # Print only the match count

Every field is displayed for each match: name, aliases, tags, category, complete nutrition (calories, protein, carbohydrates, fats, saturated/monounsaturated/polyunsaturated fats, sugar, fiber, sodium, alcohol per 100g) and physical metrics (density, yield, unit weight).

  • Options: --tag <tag>, --category/-c <category>, --missing nutrition|physical|aliases, --exact, --count, --json, --db <path>.

Merges an external ingredient database into your local repository.

gram db merge ~/shared-ingredients.yaml          # Interactive conflict resolution
gram db merge community.yaml --prefer remote     # Always prefer remote values upon conflict
gram db merge community.yaml --only-new          # Add new entries only, skip conflict resolution

The merge is alias-aware: if your database contains butter with alias beurre, and the source file contains beurre, they are recognized as referring to the same ingredient.

  • Options: --prefer local|remote (default local), --dry-run, --only-new, --db <path>.

The CLI merges configuration from ~/.config/gram/config.yaml (global level) and .gram/config.yaml (project level).

Every AI-backed command — gram import, gram db lint, and gram db enrich — accepts the same options and prints the targeted model before running, ensuring that no unexpected token consumption occurs:

gram import recipe.json --model gemini-3.1-pro   # This run only
gram db enrich --provider anthropic              # This run only
gram db lint --pick-model                        # Interactive menu
  • --model <name> — use a specific model for this execution without altering the provider.
  • --provider <google|openai|anthropic|ollama> — select a specific provider for this execution. The provider is never guessed from the model name.
  • --pick-model — pick provider and model from an interactive menu. Requires a terminal; in automated scripts, use --provider/--model instead.

Neither flag writes anything to your configuration files. To change defaults permanently, use gram config set ai.model <name> or re-run gram init.

When --provider (or --pick-model) selects a provider not declared in your configuration, the model, apiKey, and baseUrl parameters under ai: are not carried over: they belong strictly to the provider they were written for. Gram will request the new provider’s dedicated environment variable. This holds whether your ai: block names a different provider or none at all: a block without provider: belongs to whichever provider Gram would have auto-detected, not to the one specified manually via CLI flags.

Gram uses a cascading fallback hierarchy for sensitive API credentials:

  1. Environment Variables: The variable assigned to the active provider — GEMINI_API_KEY, OPENAI_API_KEY, or ANTHROPIC_API_KEY (from the system environment or a .env file) — takes absolute precedence. This is the recommended way to store secrets locally and in CI/CD pipelines.
  2. config.yaml Fallback: If that variable is missing, Gram falls back to the ai.apiKey field in config.yaml — but only when it was defined for the provider being called.

An API key is never forwarded across different providers. If you configured provider: openai and only GEMINI_API_KEY is present, Gram stops and requests OPENAI_API_KEY rather than sending your Google key to OpenAI. The same isolation applies across configuration layers: a global ai: block is ignored entirely if the local project selects a different provider.

Here is the complete reference of all available settings in config.yaml:

version: 1                     # Reserved for future config schema migrations — currently unused
database: ".gram/ingredients.yaml" # Relative or absolute path to the database file
language: "en"                 # Target language for all AI-generated content (categories, tags, imported recipes)
                               # Supported: en, fr, de, es, it, pt, nl, ja, zh — default: en
timezone: "Europe/Paris"       # IANA time zone of your kitchen: default for `gram plan --tz` (default: machine time zone)
                               # Only read by `gram plan`, and by `export` and `print` with --view run-sheet. Update via: `gram config set timezone <zone>`
availability: ["08:00-22:00", "sat=09:00-23:00"] # When you can cook, in the syntax of `--available`: default for `gram plan --available` (default: all day)
                               # One entry or a list. Read by `gram plan`, `export` and `print` with --view run-sheet, and the language server. Update via: `gram config set availability 08:00-22:00`
mealTimes: ["12:30", "20:00"]  # Candidate meal times evaluated by `gram plan --find` (default: 12:30 and 20:00)
                               # Times in 24 or 12 hours, here and in availability: ["12:30pm", "8pm"], "8am-10pm"
clock: "auto"                  # How the run sheet writes the time: auto (your system's region), 12h (1:00 PM) or 24h (13:00)
                               # Default for `--clock`; also used by the language server when `gram.clock` is auto. Update via: `gram config set clock 12h`
updateCheck: true             # Set to false to silence the update notice printed after each command

# Named `@use` specifier aliases — `@use "@bases/shortcrust.gram"` resolves to
# "<project root>/shared/bases/shortcrust.gram". See the Module Imports reference.
paths:
  bases: "./shared/bases"

# AI settings for `gram import`, `gram db enrich` and `gram db lint`
ai:
  # Supported providers: "google", "openai", "anthropic", "ollama"
  provider: "google"

  # Specific model identifier (defaults to 'gemini-3.5-flash' for google,
  # 'gpt-4.1-nano' for openai, 'claude-haiku-4-5-20251001' for anthropic, 'llama4' for ollama)
  model: "gemini-3.5-flash"

  # API key. Always prefer the dedicated environment variable:
  # GEMINI_API_KEY (google), OPENAI_API_KEY (openai), ANTHROPIC_API_KEY (anthropic).
  # This field is only read for the provider declared above — it is ignored under
  # the --provider flag or when another provider is selected. Ollama requires no key.
  # WARNING: Prefer using a .env file instead of committing keys in this file.
  apiKey: "YOUR_API_KEY"

  # Custom base URL — read exclusively for the "ollama" provider.
  # Defaults to "http://localhost:11434/v1" (or the OLLAMA_BASE_URL env var) when unset.
  baseUrl: "http://localhost:11434/v1"