Skip to content

feat(nutrition): add nutrition#1427

Open
mvanhorn wants to merge 2 commits into
mainfrom
feat/nutrition
Open

feat(nutrition): add nutrition#1427
mvanhorn wants to merge 2 commits into
mainfrom
feat/nutrition

Conversation

@mvanhorn

@mvanhorn mvanhorn commented Jul 2, 2026

Copy link
Copy Markdown
Owner

nutrition

One agent-native CLI over USDA FoodData Central and NutritionValue.org - with cross-source enrichment, protein-density comparison, nutrient ranking, and a local SQLite cache no other nutrition tool ships.

API: nutrition | Category: food-and-dining | Press version: 4.27.1
Spec: USDA FoodData Central OpenAPI (https://fdc.nal.usda.gov/api-spec/fdc_api.json)

Publication Path

New print — combo aggregator CLI unifying two peer sources (USDA FoodData Central official API + NutritionValue.org server-rendered HTML) behind one food model, keyed on the shared FDC id.

CLI Shape

$ nutrition-pp-cli --help
Nutrition CLI — One agent-native CLI over USDA FoodData Central and NutritionValue.org - with cross-source enrichment, protein-density …

Highlights (not in the official API docs):
  • enrich   Merge NutritionValue.org's derived analytics (net carbs and omega-6/omega-3 ratio) onto a USDA food record by its shared FDC id.
  • rank   Top or bottom foods by any single nutrient, filterable by category and dataset, ingested from NutritionValue.org's precomputed ranking pages.
  • compare   Compare 2-5 foods side by side on a common basis: per 100 g, per serving, or per 100 kcal (protein density).
  • find   Find foods that satisfy multiple nutrient thresholds at once (e.g. protein >= 20 g AND kcal <= 165 per 100 g).
  • log   A persistent daily food diary with macro/micro targets, backed by local SQLite, with today/summary/progress reports.
  • meal   Total nutrition across several foods at given quantities in one stateless call (id:quantity pairs).
  • cite   Emit an APA or MLA citation for a USDA food record so agent output is verifiable and traceable to a real fdcId.

Agent mode: add --agent to any command for JSON output + non-interactive mode.
Health check: run 'nutrition-pp-cli doctor' to verify auth and connectivity.
See README.md or the bundled SKILL.md for recipes.

Usage:
  nutrition-pp-cli [command]

Available Commands:
  agent-context Emit structured JSON describing this CLI for agents
  api           Browse all API endpoints by interface name
  auth          Manage authentication for Food Data Central
  cite          Emit an APA or MLA citation for a USDA food record
  compare       Compare 2-5 foods on a common basis (100g, serving, or 100kcal)
  completion    Generate the autocompletion script for the specified shell
  doctor        Check CLI health
  enrich        Merge NutritionValue.org derived analytics onto a USDA food
  feedback      Record feedback about this CLI (local by default; upstream opt-in)
  find          Find foods meeting multiple nutrient thresholds at once
  food          Retrieves a single food item by an FDC ID. Optional format and nutrients can be specified.
  help          Help about any command
  import        Import data from JSONL file via API create/upsert calls
  log           Daily food diary with targets (local SQLite)
  meal          Total nutrition across several foods at given quantities
  profile       Named sets of flags saved for reuse
  rank          Rank foods by a single nutrient from NutritionValue.org
  search        Full-text search across synced data or live API
  sources       List the data sources this CLI aggregates
  sync          Sync API data to local SQLite for offline search and analysis
  version       Print version
  which         Find the command that implements a capability
  workflow      Compound workflows that combine multiple API operations

Flags:
      --agent                   Set all agent-friendly defaults (--json --compact --no-input --no-color --yes)
      --allow-partial-failure   Downgrade response-body partial-failure (e.g. partialFailureError) to a warning instead of a non-zero exit
      --compact                 Return only key fields (id, name, status, timestamps) for minimal token usage
      --config string           Config file path
      --csv                     Output as CSV (table and array responses)
      --data-source string      Data source for read commands: auto (live with local fallback), live (API only), local (synced data only) (default "auto")
      --deliver string          Route output to a sink: stdout (default), file:<path>, webhook:<url>
      --dry-run                 Show request without sending
  -h, --help                    help for nutrition-pp-cli
      --home string             Root directory for config, data, state, and cache files
      --human-friendly          Enable colored output and rich formatting
      --idempotent              Treat already-existing create results as a successful no-op
      --json                    Output as JSON
      --max-age duration        Maximum acceptable age of local-store data before a stderr hint suggests sync; 0 disables (default 30m0s)
      --no-cache                Bypass response cache
      --no-color                Disable colored output
      --no-input                Disable all interactive prompts (for CI/agents)
      --plain                   Output as plain tab-separated text
      --profile string          Apply values from a saved profile (see 'nutrition-pp-cli profile list')
      --quiet                   Bare output, one value per line
      --rate-limit float        Max requests per second (0 to disable)
      --select string           Comma-separated fields to include in output (e.g. --select id,name,status)
      --timeout duration        Request timeout (default 1m0s)
  -v, --version                 version for nutrition-pp-cli
      --yes                     Skip confirmation prompts (for agents and scripts)

Use "nutrition-pp-cli [command] --help" for more information about a command.

Novel Commands

Command Name Description
enrich Cross-source enrichment overlay Merge NutritionValue.org's derived analytics (net carbs and omega-6/omega-3 ratio) onto a USDA food record by its shared FDC id.
rank Nutrient ranking Top or bottom foods by any single nutrient, filterable by category and dataset, ingested from NutritionValue.org's precomputed ranking pages.
compare Common-basis comparison Compare 2-5 foods side by side on a common basis: per 100 g, per serving, or per 100 kcal (protein density).
find Compound nutrient filters Find foods that satisfy multiple nutrient thresholds at once (e.g. protein >= 20 g AND kcal <= 165 per 100 g).
log Daily intake log with targets A persistent daily food diary with macro/micro targets, backed by local SQLite, with today/summary/progress reports.
meal Meal aggregation Total nutrition across several foods at given quantities in one stateless call (id:quantity pairs).
cite Citation output Emit an APA or MLA citation for a USDA food record so agent output is verifiable and traceable to a real fdcId.

What This CLI Does

Look up any food's nutrition from USDA's ~600K-food database, then enrich it with NutritionValue.org's derived analytics (net carbs, omega-6/omega-3 ratio) that the USDA API never exposes. Compare foods on a per-100kcal protein-density basis, rank foods by any nutrient, filter by compound thresholds, and log a daily diary against targets — all offline-cached, cited, and agent-native.

Because NutritionValue.org's food ids are the same USDA FDC ids, the two sources join exactly: enrich <fdcId> returns the authoritative USDA nutrients plus NutritionValue's derived fields for the same food. USDA auth uses a free api.data.gov key (FDC_API_KEY or USDA_API_KEY), falling back to the public DEMO_KEY; NutritionValue commands need no key.

Manuscripts

Validation Results

Check Result
Manifest PASS
Phase 5 PASS
go mod tidy PASS
govulncheck (this CLI only, reachable findings) PASS
go vet PASS
go build PASS
--help PASS
--version PASS
verify-skill PASS
Manuscripts PRESENT

Publish Live Gate

Full live dogfood reran at publish time against the real USDA FoodData Central API and passed 83/83. All 7 novel commands were exercised end-to-end (enrich, rank, compare, find, meal, cite, log). Proof: Phase 5 Acceptance.

Notes

Two generator retro candidates were recorded under .printing-press-patches/ (dual x-auth-env-vars colliding toml:"api_key" tags; an unregistered auth set-token subcommand), both fixed in-tree. NutritionValue.org is accessed politely (browser User-Agent, adaptive rate limiter under 1 req/s, no bulk crawling) via a hand-authored HTML-extraction source client.

Review Response

Greptile confidence 4/5, 3 P2 findings addressed:

  • nameOverlap single-token match (hand-authored): fixed in 8d28c07 — added a minimum-2-shared-token guard to the NutritionValue.org fallback so a lone shared token can't attach the wrong food's analytics; added two focused tests.
  • 8-byte cache-key truncation in internal/cache/cache.go and internal/client/client.go (both generator-emitted, DO NOT EDIT): theoretical 64-bit collision; filed as a Printing Press generator retro candidate (widen the template cache-key hashes to 16 bytes) rather than diverging this printed CLI's generated code.

@github-actions

github-actions Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

@greptileai review

Auto-nudge from greptile-policy-gate.yml because no Greptile Review check appeared for 3e3d8a7a1d83d06af5a15e1e0366983cafefc06b after 186s. This usually means the PR is over Greptile auto-review size cap; manual triggers bypass it.

@greptile-apps

greptile-apps Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR introduces a new nutrition CLI entry to the library: a single agent-native tool that unifies USDA FoodData Central (official API) and NutritionValue.org (HTML-scraped) behind one food model, keyed on the shared FDC id. The previous round's three findings have been handled — the nameOverlap single-token trap is fixed with a minimum-two-shared-token guard, and the two cache-key truncation findings were accepted as generator-emitted and filed as generator retro candidates.

  • Seven novel commands (enrich, rank, compare, find, log, meal, cite) are all hand-authored; the remaining files are generator-emitted and marked DO NOT EDIT.
  • Cross-source enrichment (enrich) joins NutritionValue.org's derived analytics (net carbs, omega-6/omega-3 ratio) onto a USDA record by the shared FDC id, with a graceful fallback to USDA-computed net carbs when the HTML source misses.
  • Local SQLite diary (log) uses a lazy IF NOT EXISTS schema pattern to stay insulated from generator regen; all queries are parameterised.

Confidence Score: 5/5

Safe to merge; all novel commands are well-structured, the cross-source name-match fix is correct, and the handwritten SQLite layer is properly isolated from generator-emitted files.

All seven novel commands follow consistent patterns, use parameterised queries, handle partial failures gracefully, and were validated 83/83 against the live USDA API. The previous nameOverlap guard fix is correctly implemented. The remaining findings are minor usability gaps in cite, find, and log remove.

No files require special attention; internal/cli/find.go, internal/cli/log.go, and internal/cli/cite.go have small usability gaps noted in the inline comments.

Important Files Changed

Filename Overview
library/food-and-dining/nutrition/internal/source/nutritionvalue/client.go Hand-authored HTML scraper for NutritionValue.org; implements polite rate-limiting and name-overlap matching. The previously flagged single-token match vulnerability is correctly resolved with the shared < 2 guard in FoodByID.
library/food-and-dining/nutrition/internal/cli/enrich.go Cross-source enrichment command; correctly falls back to USDA-derived net carbs when NutritionValue.org misses, and annotates the source in NVNote.
library/food-and-dining/nutrition/internal/cli/find.go Compound nutrient filter that paginates the USDA list endpoint; the scanCapHit flag suppresses the explanatory note when all API pages are exhausted with no matches, leaving the user with a silent empty result.
library/food-and-dining/nutrition/internal/cli/log.go Daily food diary backed by SQLite; log remove exits 0 with {"removed": 0} when the entry id does not exist, giving no error signal to agents or scripts.
library/food-and-dining/nutrition/internal/cli/cite.go Citation generator for USDA records; MLA branch uses %q Go-string quoting for the title, which emits Go escape sequences for any description containing a double-quote character instead of plain typographic quotes.
library/food-and-dining/nutrition/internal/cli/compare.go Common-basis food comparison; correctly reports missing FDC ids omitted by the USDA batch endpoint.
library/food-and-dining/nutrition/internal/cli/meal.go Stateless meal aggregation command; partial-failure is surfaced in fetch_failures rather than aborting the whole call.
library/food-and-dining/nutrition/internal/store/nutrition_log.go Hand-authored SQLite diary extension; lazy EnsureLogSchema pattern keeps it generator-regen-safe; queries are fully parameterised.
library/food-and-dining/nutrition/internal/nutridata/nutridata.go USDA dataType normalizer; handles all four FDC response shapes and resolves energy across the Atwater fallback chain.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant U as User/Agent
    participant CLI as nutrition-pp-cli
    participant USDA as USDA FoodData Central
    participant NV as NutritionValue.org
    participant DB as Local SQLite

    Note over CLI,USDA: enrich
    U->>CLI: enrich fdcId
    CLI->>USDA: GET /v1/food/fdcId
    USDA-->>CLI: food record
    CLI->>NV: Search + FoodByID HTML scrape
    NV-->>CLI: net carbs and omega ratios
    CLI-->>U: enrichView merged JSON

    Note over CLI,USDA: compare
    U->>CLI: compare id1 id2 --basis 100kcal
    CLI->>USDA: GET /v1/foods batch
    USDA-->>CLI: food records
    CLI-->>U: compareView per-basis rows

    Note over CLI,USDA: find
    U->>CLI: "find --min protein=20 --max-kcal 165"
    loop page 1 to max-scan-pages
        CLI->>USDA: GET /v1/foods/list page N
        USDA-->>CLI: 200 abridged records
    end
    CLI-->>U: matching findMatches

    Note over CLI,DB: log add
    U->>CLI: log add fdcId --grams 150
    CLI->>USDA: GET /v1/food/fdcId
    USDA-->>CLI: food record
    CLI->>DB: INSERT log_entries
    DB-->>CLI: new entry id
    CLI-->>U: added LogEntry

    Note over CLI,NV: rank
    U->>CLI: rank potassium --order lowest
    CLI->>NV: GET ranking HTML page
    NV-->>CLI: ranked food rows
    CLI-->>U: rankView
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant U as User/Agent
    participant CLI as nutrition-pp-cli
    participant USDA as USDA FoodData Central
    participant NV as NutritionValue.org
    participant DB as Local SQLite

    Note over CLI,USDA: enrich
    U->>CLI: enrich fdcId
    CLI->>USDA: GET /v1/food/fdcId
    USDA-->>CLI: food record
    CLI->>NV: Search + FoodByID HTML scrape
    NV-->>CLI: net carbs and omega ratios
    CLI-->>U: enrichView merged JSON

    Note over CLI,USDA: compare
    U->>CLI: compare id1 id2 --basis 100kcal
    CLI->>USDA: GET /v1/foods batch
    USDA-->>CLI: food records
    CLI-->>U: compareView per-basis rows

    Note over CLI,USDA: find
    U->>CLI: "find --min protein=20 --max-kcal 165"
    loop page 1 to max-scan-pages
        CLI->>USDA: GET /v1/foods/list page N
        USDA-->>CLI: 200 abridged records
    end
    CLI-->>U: matching findMatches

    Note over CLI,DB: log add
    U->>CLI: log add fdcId --grams 150
    CLI->>USDA: GET /v1/food/fdcId
    USDA-->>CLI: food record
    CLI->>DB: INSERT log_entries
    DB-->>CLI: new entry id
    CLI-->>U: added LogEntry

    Note over CLI,NV: rank
    U->>CLI: rank potassium --order lowest
    CLI->>NV: GET ranking HTML page
    NV-->>CLI: ranked food rows
    CLI-->>U: rankView
Loading

Reviews (2): Last reviewed commit: "fix(nutrition): tighten NutritionValue n..." | Re-trigger Greptile

Comment thread library/food-and-dining/nutrition/internal/source/nutritionvalue/client.go Outdated
Comment thread library/food-and-dining/nutrition/internal/cache/cache.go
Comment thread library/food-and-dining/nutrition/internal/client/client.go
@github-actions

github-actions Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

@greptileai review

Auto-nudge from greptile-policy-gate.yml because no Greptile Review check appeared for 8d28c0769c0490409ccd7e74ed60d22b14157344 after 183s. This usually means the PR is over Greptile auto-review size cap; manual triggers bypass it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant