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.).
Installation
Section titled “Installation”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.
Global options
Section titled “Global options”--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).
Settings flags
Section titled “Settings flags”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:
| Flag | Values | Default | Commands |
|---|---|---|---|
--mise-en-place | per-section, upfront, per-day | per-section | view, print, export, plan, cook |
--rests | shortest, balanced, longest | shortest | view, print, export, plan, cook |
--comments | show, hide | show | view, print, export, plan |
--nutrition-basis | auto, total, per-portion, per-100g | auto | view, print, export |
--bakers-math-only | on or off | off | view, print, export |
--step-quantities | show, hide | show | view, print, export |
--clock v1.5.0 | auto, 12h, 24h | auto | print, export, plan |
Analyzer computation settings (all enabled by default; use --no-<flag> to disable):
| Flag | What it does | Commands |
|---|---|---|
--bakers-math | Computes 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-standardization | Standardizes quantities to grams using the ingredient database. | same |
--yield-calculation | Accounts for preparation waste (peels, pits, trim), adjusting required purchasing quantities relative to net culinary weights. | same |
--nutrition-estimation | Estimates nutritional values across the recipe. | same |
--mise-en-placecontrols when prep runs (per-section,upfront, orper-day), updating total and idle times in headers (and placing a “Mise en place” heading in HTML). See When the mise en place happens.--restsresolves elastic passive ranges (~_{12-24h}) toshortest,balanced(midpoint), orlongest; exact durations and active timers are unaffected.--commentsshows 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 (autoshows per 100 g of raw assembled mixture and per portion side by side; see Nutritional Estimation).--step-quantities(alias--no-step-qtyforhide) controls whether quantities and standardized masses (flour (250 ml, ~148 g)) are repeated inside step prose. Section ingredient lists always show them.--clockchooses how the run sheet and the serving time suggestions write the time of day:12h(1:00 PM),24h(13:00), orauto, which follows the region of your system’s locale (LC_ALL, thenLC_TIME, thenLANG), not the language of the recipe; a locale that names no region (C,en) reads 24 hours. Without the flag, theclocksetting 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.
Core commands
Section titled “Core commands”Project management & developer workflow
Section titled “Project management & developer workflow”gram init
Section titled “gram init”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
enorfr). - Interactively configures your preferred AI provider and model.
- Generates or updates a
.envfile for your AI API keys. - Generates a documented starter
ingredients.yamlingredient database at.gram/ingredients.yaml. - Generates a
.gitignoreto prevent committing sensitive keys.
gram upgrade
Section titled “gram upgrade”Checks npm for a newer @gram-lang/cli release and offers to install it.
- 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.
gram check [pattern]
Section titled “gram check [pattern]”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.yamldatabase 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
--strictto treat every warning as a hard error (ideal for CI pipelines). - Options:
--db <path>,--skip-db,--strict.
gram build [pattern]
Section titled “gram build [pattern]”Compiles your .gram recipes into the final, minified JSON format.
- By default, outputs pure JSON directly to
stdoutfor 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: becausebuildprocesses files in batches, reproducible output must not depend on reading one specific file’s shopping list first. Usegram vieworgram scaleto determine your factor, then pass that numeric multiplier tobuild.- 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-modulesto build them anyway. - Options:
--output/-o <dir>,--pretty,--scale <factor>,--db <path>,--skip-db,--include-modules, and the analyzer’s settings flags.
gram view <file>
Section titled “gram view <file>”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.
- Supports automatic paging for long recipes (
--no-pagerdisables it). - Displays calculated nutrition, timings, and ingredient checklists; common fractions such as
1/4 tspremain fractions in the shopping list. - Passing
--scaleadjusts 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 planbelow. - Options:
--scale <factor|ref>,--no-pager,--skip-db,--db,--bakers-reference <id>, plus all settings flags.
gram import <source>
Section titled “gram import <source>”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.
Supported sources:
- Web page URLs: automatically fetches the page and extracts structured
application/ld+jsonrecipe metadata (Schema.orgRecipe). - 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
languageconfiguration. -
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/-yto deliberately accept writing. -
Nothing is written if the import result exhibits major defects. Two strict verification checks are enforced:
- Lost content detection — every
@ingredientpresent 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
--forceto write the file despite warnings, or retry with a higher-capability--model. - Lost content detection — every
-
source:andauthor: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 inconfig.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), andsource:(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.
gram shop [pattern]
Section titled “gram shop [pattern]”Compiles a consolidated shopping list across multiple recipes.
- Aggregates quantities intelligently using reference densities (volume → grams when density is known).
- Groups ingredients by their
categoryfield (culinary families: Produce, Dairy, Grains, etc.). - Alias consolidation: if two recipes use different names for the same ingredient (e.g.
butterandbeurre), 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, anddrop(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-modulesto 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 byqty(3.9for"unit": "kg"), always using a dot decimal;nullif the ingredient has no quantity or mixes incompatible units.unit: canonical unit (tbspfortablespoonsorc. à s.), ornullfor counts (@eggs{4}). Compatible scales add up in the smallest unit written (2 cup + 3 tbspgives"amount": 35, "unit": "tbsp").range:{ min, max }bounds when the item is a range (amountholds the midpoint).parts: array of{ amount, unit }entries when incompatible units cannot be summed (1 1/2 cups + 70 ggives[{ "amount": 1.5, "unit": "cup" }, { "amount": 70, "unit": "g" }]).unresolved: unresolvable portions such as(2% of dough ❓), excluded fromamount.
gram cook <file>
Section titled “gram cook <file>”Launches an interactive step-by-step cooking guide directly in the terminal.
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:
-
Mise en place: comprehensive aggregated ingredient list for the entire recipe (Space to start).
-
Section intro: ingredient summary for the upcoming section (shown before each section begins).
-
Cooking steps: progressive one-step-at-a-time view in a two-column layout: required ingredients on the left, instructions on the right.
-
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
Tto 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.
QorEsctriggers a quit-confirmation prompt to avoid accidentally interrupting an active timer.
Keyboard shortcuts:
| Key | Action |
|---|---|
Space / Enter | Next step |
B | Previous step |
T | Start a timer |
Q / Esc | Quit (asks for confirmation if a timer is running) |
- Options:
--scale <factor|ref>,--skip-db,--db.
gram diff <file> [file-b]
Section titled “gram diff <file> [file-b]”Displays a semantic diff of a recipe — comparing the logical structure of ingredients, timings, sections, and temperatures rather than raw text differences.
The diff spans seven distinct axes:
-
Ingredients — added, removed, or modified quantities, with
percentChangecalculated when units match. -
Timings —
totalTime,idleTime,activeTime,preparationTimein minutes. Total and passive times reflect the default schedule (mise en place immediately before each section), matchinggram view. -
Sections — added or removed sections and step-count changes.
-
Frontmatter — changes to
portions,description, and other metadata fields. Atitlechange 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 —
@useimports 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
gitis unavailable on the system. -
A section spliced in from an
@useimport 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 diffdoes not resolve@userecursively: 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>.
gram scale <file>
Section titled “gram scale <file>”Displays a before/after comparison table of ingredient quantities for a given scaling target.
- 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=1kgagainst a recipe written in500g). Crossing mass ↔ volume (e.g.water=150gagainst a recipe inml) is supported whenever a density is known (viagram db enrichor adensities: ["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.
gram watch [dir]
Section titled “gram watch [dir]”Watches a directory for .gram file modifications and automatically re-runs gram check upon saving.
- Displays a timestamped result line per event:
[12:34:01] ✓ brioche.gramor✗ 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.
gram suggest
Section titled “gram suggest”Finds recipes across your project that can be prepared with a given set of ingredients.
- Scans all
.gramfiles 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-matchto filter out low-scoring matches. --withoutimmediately 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.
gram print <file>
Section titled “gram print <file>”Generates a print-ready HTML document and opens it in the default web browser.
- The HTML document is written to a temporary file (
gram_print_<timestamp>.htmlin the OS temp directory) and opened via the system default handler (openon macOS,xdg-openon Linux,cmd /c starton 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 likegram 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.
gram export <file>
Section titled “gram export <file>”Exports a recipe to Markdown, print-ready HTML or plain text.
--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 matchinggram view(orgram planfor 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--nowoptions asgram 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.
gram plan <file>
Section titled “gram plan <file>”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.
--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: thetimezonesetting 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(or8am-10pmv1.5.0) applies to all days; a day-of-week prefix (fri=18:00-22:00, frommontosun) restricts the rule to that day; a specific date prefix (2026-10-09=none) overrides a calendar date (noneindicating 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 witham/pm, in any case and with or without spaces (8:30 am - 10:00 pm,fri=6PM-11PM);12amis midnight and12pmnoon, and12amat the end of an interval is the end of the day (6pm-12amis18:00-24:00). A bare hour (8) is refused. Without the flag, theavailabilitysetting 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:00or12:30pm,8pm) (default: value frommealTimesconfig, otherwise12: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 (defaulttext).jsonoutputs the structured{ plan, runSheet }object (orrunSheetonly alongside theearliestfield 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 tostderr, 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).
gram format [pattern]
Section titled “gram format [pattern]”Auto-formats .gram files in-place applying 13 canonical rules from @gram-lang/format.
13 canonical rules applied:
- Frontmatter formatting — delimiter normalization and whitespace cleanup
- Section header titles — single space after
## - Step indexing — normalized step prefixes (
1.) - Action blocks — normalized action prefixes (
[Mix]) - Ingredient tokens —
@ingredient{qty}spacing and bracket syntax - Cookware tokens —
#cookware{qty}spacing and bracket syntax - Timer tokens —
~timer{duration}active and~_timer{duration}passive spacing - Temperature tokens —
^temp{value}formatting - Intermediate declarations & references —
->&doughand&doughcanonical spacing - Composite syntax —
<@parentcomposite ingredient syntax - Trailing decimal zeros — numerical cleanup
{500.0g}→{500g},{1.50g}→{1.5g} - Comment formatting — clean spacing after comment sigils (
//) - 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.
Configuration
Section titled “Configuration”Commands nested under gram config to inspect and modify local project settings or global user configuration.
gram config list
Section titled “gram config list”Displays all configuration values from both the local project config and the global config.
gram config get <key>
Section titled “gram config get <key>”Prints a single configuration value to standard output.
gram config set <key> <value>
Section titled “gram config set <key> <value>”Sets a configuration parameter value.
- Values are written to
.gram/config.yamlby default; pass--globalto target~/.config/gram/config.yaml. - Sensitive keys (
ai.apiKey) are always written to the project.envfile. 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).
gram config unset <key>
Section titled “gram config unset <key>”Removes a configuration parameter.
Database management
Section titled “Database management”Commands nested under gram db to manage your ingredients.yaml repository.
-
Section titled “gram db sync [pattern]”gram db sync [pattern]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>.
-
Section titled “gram db lint”gram db lintUses 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'oliveandhuile-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.
- Detects cross-language duplicates (e.g.
-
Section titled “gram db enrich”gram db enrichUses 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, andtagsfields in batches (unit_weightis filled alongsidedensity).categorydenotes a culinary family (e.g. Vegetables, Dairy, Grains) — distinct from free-formtags. nutritioncovers every nutrient accepted by the database schema, including fat subtypes (sat_fat,mono_fat,poly_fat) andalcohol.categoryandtagsare applied automatically;density,unit_weight, andnutritionare 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]iningredients.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(defaultall),--yes/-y(skip manual review and accept all — for automated scripts),--report/-r(preview proposals without writing),--db <path>, plus the shared AI options.
- Proposes
gram db validate
Section titled “gram db validate”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).
gram db search [query]
Section titled “gram db search [query]”Searches and displays ingredient entries in full detail.
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>.
gram db merge <source.yaml>
Section titled “gram db merge <source.yaml>”Merges an external ingredient database into your local repository.
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(defaultlocal),--dry-run,--only-new,--db <path>.
Configuration file details
Section titled “Configuration file details”The CLI merges configuration from ~/.config/gram/config.yaml (global level) and .gram/config.yaml (project level).
Choosing the AI model
Section titled “Choosing the AI model”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:
--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/--modelinstead.
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.
Cascading AI configuration
Section titled “Cascading AI configuration”Gram uses a cascading fallback hierarchy for sensitive API credentials:
- Environment Variables: The variable assigned to the active provider —
GEMINI_API_KEY,OPENAI_API_KEY, orANTHROPIC_API_KEY(from the system environment or a.envfile) — takes absolute precedence. This is the recommended way to store secrets locally and in CI/CD pipelines. config.yamlFallback: If that variable is missing, Gram falls back to theai.apiKeyfield inconfig.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.
config.yaml settings
Section titled “config.yaml settings”Here is the complete reference of all available settings in config.yaml: