Grocery receipt text extraction
rhea AGENTS.md
9.2 kB · 167 lines
Markdown
at main

AGENTS.md #

Reference doc for any coding agent or new contributor working in this repo. For Claude-Code-specific working conventions (things learned the hard way, kept as guardrails), see CLAUDE.md — read both before making non-trivial changes.

Archived. Rhea was a deliberate experiment in AI-assisted software development. It was designed, specified, and written primarily through conversation with Claude. The code is functional but rough — it's a case study, not a product. No further development is planned.

What this is #

Rhea is a native macOS SwiftUI app for turning scanned grocery-receipt PDFs into structured, analyzable data:

  1. Import a PDF (or drop several at once).
  2. The app renders each receipt's first page and queues it.
  3. A local vision-capable LLM (via an OpenAI-compatible endpoint — LM Studio, oMLX, etc.) extracts merchant, totals, and line items as JSON.
  4. The user reviews/edits the extraction side-by-side with the source image and confirms it.
  5. Confirmed receipts export to CSV or upsert into Postgres for downstream analysis (e.g. price tracking across stores over time).

Everything runs locally — no cloud calls, no telemetry, no bundled dependencies. The LLM endpoint is whatever local server the user points it at.

Stack #

  • Swift 5 language mode, SwiftUI, macOS 14+ only.
  • Plain Xcode App target generated by XcodeGen from project.yml — the .xcodeproj is not committed and must be regenerated after any project.yml edit.
  • Zero third-party runtime dependencies. Apple frameworks only: SwiftUI, AppKit, PDFKit, Foundation, Observation. XcodeGen itself is a build-time tool (Homebrew), not a dependency of the app.
  • Bundle ID net.danieldaum.rhea, product name Rhea.

Build #

brew install xcodegen        # one-time
xcodegen generate            # writes Rhea.xcodeproj from project.yml
xcodebuild -project Rhea.xcodeproj -scheme Rhea -configuration Debug build

Or open Rhea.xcodeproj in Xcode and hit Run. project.yml is currently set to ad-hoc "sign to run locally" (CODE_SIGN_IDENTITY = -); a Developer ID + notarization is required for a distributable, Gatekeeper-clean .dmg (see Distribution below).

Keep the build green after every change — there's no test suite, so xcodebuild build is the correctness bar.

Architecture #

MVVM, single source of truth. Views are intentionally dumb.

  • ReceiptsViewModel (@Observable @MainActor) owns all state: the receipt array, sidebar/filter selection, extraction + Postgres config, and export status. Every mutation goes through it and is persisted immediately.
  • Views read the view model and call its methods; they hold no independent state beyond local UI concerns (hover, disclosure groups, etc.).
  • Services are stateless (or actor-isolated) workers the view model calls into: extraction, PDF rendering, local persistence, CSV/Postgres export.
Rhea/
├── RheaApp.swift              @main entry, NSApplicationDelegateAdaptor for activation policy
├── Models/
│   ├── Receipt.swift           Receipt, ExtractedReceipt, LineItem, ReceiptStatus (+ lenient Codable)
│   ├── ReceiptKeys.swift       publicID / naturalKey / stableKey derivation
│   ├── LenientDecoding.swift   String/number/null coercion helpers for model output
│   └── AppEnums.swift          SidebarItem, ReceiptFilter
├── ViewModels/
│   └── ReceiptsViewModel.swift state, import, sequential processing queue, confirm, delete, export
├── Services/
│   ├── LocalStore.swift        durable on-disk vault (Application Support)
│   ├── ExtractionService.swift OpenAI-compatible vision call + prompt + JSON parsing
│   ├── PDFService.swift        renders a PDF's first page to PNG
│   ├── PersistenceStore.swift  storage protocol
│   ├── CSVExporter.swift / CSVStore.swift          CSV export
│   └── PostgresStore.swift / PostgresSQLExporter.swift  Postgres export via `psql` + schema DDL
└── Views/
    ├── ReceiptListView.swift    Table of receipts, filters, status pills, context menu
    ├── ReceiptDetailView.swift  source image + edit form (or status banner / error pane)
    ├── ReceiptEditForm.swift    review/edit surface — NOT a SwiftUI Form, see gotchas
    ├── SidebarView.swift        Receipts / Settings nav, queue badge
    ├── SettingsView.swift       extraction endpoint, Postgres config, export actions
    └── ResizableSplitView.swift custom draggable split divider

Data model #

  • Receipt: id (UUID), sourceURL (in-vault copy), pageImage (Data?), status (queued/inProgress/done/failed), extracted (ExtractedReceipt?), confirmed (Bool), errorMessage, and submittedAt/startedAt/finishedAt.
    • publicID = rhea_receipt_id_<uuid, no dashes>.
    • naturalKey = chain_storeNumber_date_receiptNumber (slugified); falls back to a UUID-derived generatedReceiptNumber when the model can't read one, then to publicID if chain + one other part are still missing. Used as the DB key.
  • ExtractedReceipt: merchant, chain?, storeNumber?, storeAddress?, date (ISO-8601), receiptNumber?, total, tax?, paymentMethod?, lineItems, overallConfidence? (0–1, the model's confidence in the whole extraction).
  • LineItem: name (as printed), aiCommonName? (model's normalized suggestion, read-only), userCommonName? (user's own normalized name, editable), category?, barcode?, quantity?, unitPrice?, weightLbs?, pricePerLb?, listPrice?, pricePaid?, lineTotal?, confidence? (0–1, per-line model confidence).
    • stableKey(receiptKey:index:) = barcode_<barcode> when present, else <receiptKey>_itemNN.
    • The model emits commonName in its JSON; decoding maps that (and legacy saved records) into aiCommonName.

All model decoding goes through LenientDecoding helpers because local vision models drift on types (numeric fields as strings, quoted decimals, nulls in unexpected places) — one bad field must never fail the whole receipt.

Key flows #

Import + processing queue — importing (toolbar or drag-and-drop) copies each PDF into the vault, renders its page, and queues it. ReceiptsViewModel.processQueue() is reentrancy-guarded and drains queued receipts one at a time, in submission order, calling ExtractionService and persisting status at each step. Items left inProgress by a crash are re-queued and resumed on next launch (loadFromDisk()).

Status lifecycle — queued → inProgress → done ("Processed", blue) → user clicks Confirm → confirmed (green). Fields are editable until confirmed.

Persistence — LocalStore (an actor) is the single source of truth, under ~/Library/Application Support/Rhea/: Store/<uuid>.json (metadata + extraction, no image bytes) and Files/<uuid>/ (original PDF + rendered page.png). Atomic writes; saved on every mutation, loaded on launch, backstopped by a save-all on scenePhase leaving .active. No seeded data — first launch starts empty.

Export — only confirmed receipts with extracted data are exported, one row per line item. CSV goes to ~/Documents/Rhea/receipts.csv. Postgres upserts via psql into receipts + receipt_line_items, using ALTER TABLE ... ADD COLUMN IF NOT EXISTS so older databases upgrade in place without a migration tool.

Conventions & gotchas (see CLAUDE.md for the full list) #

  • Never put editable line-item controls inside a SwiftUI Form — on macOS it silently turns titled TextFields into fixed labeled rows and breaks .frame(width:), which destroys column alignment. ReceiptEditForm is a plain ScrollView + VStack of cards instead.
  • Always decode model output leniently — assume the vision model will emit the wrong JSON type somewhere; coerce, don't crash.
  • Swift 5 language mode (not 6) is intentional, to avoid strict-concurrency noise around the @MainActor/actor boundaries used here.
  • NSApplicationDelegateAdaptor forcing .regular activation is a holdover from when this ran as a raw SwiftPM binary; harmless as a bundled .app but keep it — it's what makes text fields accept keyboard focus if the binary is ever run directly.

Distribution #

Not the Mac App Store — direct-download .dmg builds/releases via a self-hosted Gitea instance. To ship a Gatekeeper-clean build: set a real Developer ID team in project.yml (DEVELOPMENT_TEAM, proper CODE_SIGN_IDENTITY), archive (xcodebuild archive or Xcode's Product ▸ Archive), export, and notarize (xcrun notarytool / xcrun stapler). xcodebuild -showBuildSettings after any signing change is a fast way to confirm the right identity is picked up before scripting a Gitea Actions/CI release job around it.

App icon: Rhea/Assets.xcassets/AppIcon.appiconset, generated via sips from the 1024px master at Packaging/AppIcon.png — regenerate sizes there if the master changes, don't hand-edit the appiconset.