projects

rheaarchived

A grocery receipt scanning application

AGENTS.md 9.0 KB · 167 lines Raw
# AGENTS.mdReference doc for any coding agent or new contributor working in this repo. ForClaude-Code-specific working conventions (things learned the hard way, kept asguardrails), 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 isRhea is a native macOS SwiftUI app for turning scanned grocery-receipt PDFs intostructured, 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. TheLLM 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-timexcodegen generate            # writes Rhea.xcodeproj from project.ymlxcodebuild -project Rhea.xcodeproj -scheme Rhea -configuration Debug build```Or open `Rhea.xcodeproj` in Xcode and hit Run. `project.yml` is currently set toad-hoc "sign to run locally" (`CODE_SIGN_IDENTITY = -`); a Developer ID + notarizationis required for a distributable, Gatekeeper-clean `.dmg` (see Distribution below).Keep the build green after every change — there's no test suite, so `xcodebuildbuild` is the correctness bar.## ArchitectureMVVM, 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 visionmodels drift on types (numeric fields as strings, quoted decimals, nulls inunexpected places) — one bad field must never fail the whole receipt.## Key flows**Import + processing queue** — importing (toolbar or drag-and-drop) copies each PDFinto the vault, renders its page, and queues it. `ReceiptsViewModel.processQueue()`is reentrancy-guarded and drains `queued` receipts **one at a time**, in submissionorder, 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) → userclicks 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`). Atomicwrites; 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 perline item. CSV goes to `~/Documents/Rhea/receipts.csv`. Postgres upserts via `psql`into `receipts` + `receipt_line_items`, using `ALTER TABLE ... ADD COLUMN IF NOTEXISTS` 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 `TextField`s 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.## DistributionNot the Mac App Store — direct-download `.dmg` builds/releases via a self-hostedGitea 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 anysigning change is a fast way to confirm the right identity is picked up beforescripting a Gitea Actions/CI release job around it.App icon: `Rhea/Assets.xcassets/AppIcon.appiconset`, generated via `sips` from the1024px master at `Packaging/AppIcon.png` — regenerate sizes there if the masterchanges, don't hand-edit the appiconset.