rheaarchived
- 40 commits
- 1 branch
- 0 tags
- updated
AGENTS.md
9.0 KB · 167 lines
1# AGENTS.md23Reference doc for any coding agent or new contributor working in this repo. For4Claude-Code-specific working conventions (things learned the hard way, kept as5guardrails), see `CLAUDE.md` — read both before making non-trivial changes.67> **Archived.** Rhea was a deliberate experiment in AI-assisted software development.8> It was designed, specified, and written primarily through conversation with Claude.9> The code is functional but rough — it's a case study, not a product.10> No further development is planned.1112## What this is1314Rhea is a native macOS SwiftUI app for turning scanned grocery-receipt PDFs into15structured, analyzable data:16171. Import a PDF (or drop several at once).182. The app renders each receipt's first page and queues it.193. A local vision-capable LLM (via an OpenAI-compatible endpoint — LM Studio, oMLX,20 etc.) extracts merchant, totals, and line items as JSON.214. The user reviews/edits the extraction side-by-side with the source image and22 confirms it.235. Confirmed receipts export to CSV or upsert into Postgres for downstream analysis24 (e.g. price tracking across stores over time).2526Everything runs locally — no cloud calls, no telemetry, no bundled dependencies. The27LLM endpoint is whatever local server the user points it at.2829## Stack3031- Swift 5 language mode, SwiftUI, macOS 14+ only.32- Plain Xcode **App** target generated by **XcodeGen** from `project.yml` — the33 `.xcodeproj` is not committed and must be regenerated after any `project.yml` edit.34- Zero third-party runtime dependencies. Apple frameworks only: SwiftUI, AppKit,35 PDFKit, Foundation, Observation. XcodeGen itself is a build-time tool (Homebrew),36 not a dependency of the app.37- Bundle ID `net.danieldaum.rhea`, product name `Rhea`.3839## Build4041```42brew install xcodegen # one-time43xcodegen generate # writes Rhea.xcodeproj from project.yml44xcodebuild -project Rhea.xcodeproj -scheme Rhea -configuration Debug build45```4647Or open `Rhea.xcodeproj` in Xcode and hit Run. `project.yml` is currently set to48ad-hoc "sign to run locally" (`CODE_SIGN_IDENTITY = -`); a Developer ID + notarization49is required for a distributable, Gatekeeper-clean `.dmg` (see Distribution below).5051Keep the build green after every change — there's no test suite, so `xcodebuild52build` is the correctness bar.5354## Architecture5556MVVM, single source of truth. Views are intentionally dumb.5758- **`ReceiptsViewModel`** (`@Observable @MainActor`) owns all state: the receipt59 array, sidebar/filter selection, extraction + Postgres config, and export status.60 Every mutation goes through it and is persisted immediately.61- **Views** read the view model and call its methods; they hold no independent state62 beyond local UI concerns (hover, disclosure groups, etc.).63- **Services** are stateless (or actor-isolated) workers the view model calls into:64 extraction, PDF rendering, local persistence, CSV/Postgres export.6566```67Rhea/68├── RheaApp.swift @main entry, NSApplicationDelegateAdaptor for activation policy69├── Models/70│ ├── Receipt.swift Receipt, ExtractedReceipt, LineItem, ReceiptStatus (+ lenient Codable)71│ ├── ReceiptKeys.swift publicID / naturalKey / stableKey derivation72│ ├── LenientDecoding.swift String/number/null coercion helpers for model output73│ └── AppEnums.swift SidebarItem, ReceiptFilter74├── ViewModels/75│ └── ReceiptsViewModel.swift state, import, sequential processing queue, confirm, delete, export76├── Services/77│ ├── LocalStore.swift durable on-disk vault (Application Support)78│ ├── ExtractionService.swift OpenAI-compatible vision call + prompt + JSON parsing79│ ├── PDFService.swift renders a PDF's first page to PNG80│ ├── PersistenceStore.swift storage protocol81│ ├── CSVExporter.swift / CSVStore.swift CSV export82│ └── PostgresStore.swift / PostgresSQLExporter.swift Postgres export via `psql` + schema DDL83└── Views/84 ├── ReceiptListView.swift Table of receipts, filters, status pills, context menu85 ├── ReceiptDetailView.swift source image + edit form (or status banner / error pane)86 ├── ReceiptEditForm.swift review/edit surface — NOT a SwiftUI Form, see gotchas87 ├── SidebarView.swift Receipts / Settings nav, queue badge88 ├── SettingsView.swift extraction endpoint, Postgres config, export actions89 └── ResizableSplitView.swift custom draggable split divider90```9192## Data model9394- `Receipt`: `id` (UUID), `sourceURL` (in-vault copy), `pageImage` (Data?), `status`95 (`queued`/`inProgress`/`done`/`failed`), `extracted` (`ExtractedReceipt?`),96 `confirmed` (Bool), `errorMessage`, and `submittedAt`/`startedAt`/`finishedAt`.97 - `publicID` = `rhea_receipt_id_<uuid, no dashes>`.98 - `naturalKey` = `chain_storeNumber_date_receiptNumber` (slugified); falls back to99 a UUID-derived `generatedReceiptNumber` when the model can't read one, then to100 `publicID` if chain + one other part are still missing. Used as the DB key.101- `ExtractedReceipt`: `merchant`, `chain?`, `storeNumber?`, `storeAddress?`, `date`102 (ISO-8601), `receiptNumber?`, `total`, `tax?`, `paymentMethod?`, `lineItems`,103 `overallConfidence?` (0–1, the model's confidence in the whole extraction).104- `LineItem`: `name` (as printed), `aiCommonName?` (model's normalized suggestion,105 read-only), `userCommonName?` (user's own normalized name, editable), `category?`,106 `barcode?`, `quantity?`, `unitPrice?`, `weightLbs?`, `pricePerLb?`, `listPrice?`,107 `pricePaid?`, `lineTotal?`, `confidence?` (0–1, per-line model confidence).108 - `stableKey(receiptKey:index:)` = `barcode_<barcode>` when present, else109 `<receiptKey>_itemNN`.110 - The model emits `commonName` in its JSON; decoding maps that (and legacy saved111 records) into `aiCommonName`.112113All model decoding goes through `LenientDecoding` helpers because local vision114models drift on types (numeric fields as strings, quoted decimals, nulls in115unexpected places) — one bad field must never fail the whole receipt.116117## Key flows118119**Import + processing queue** — importing (toolbar or drag-and-drop) copies each PDF120into the vault, renders its page, and queues it. `ReceiptsViewModel.processQueue()`121is reentrancy-guarded and drains `queued` receipts **one at a time**, in submission122order, calling `ExtractionService` and persisting status at each step. Items left123`inProgress` by a crash are re-queued and resumed on next launch124(`loadFromDisk()`).125126**Status lifecycle** — `queued` → `inProgress` → `done` ("Processed", blue) → user127clicks Confirm → `confirmed` (green). Fields are editable until confirmed.128129**Persistence** — `LocalStore` (an actor) is the single source of truth, under130`~/Library/Application Support/Rhea/`: `Store/<uuid>.json` (metadata + extraction,131no image bytes) and `Files/<uuid>/` (original PDF + rendered `page.png`). Atomic132writes; saved on every mutation, loaded on launch, backstopped by a save-all on133`scenePhase` leaving `.active`. No seeded data — first launch starts empty.134135**Export** — only confirmed receipts with extracted data are exported, one row per136line item. CSV goes to `~/Documents/Rhea/receipts.csv`. Postgres upserts via `psql`137into `receipts` + `receipt_line_items`, using `ALTER TABLE ... ADD COLUMN IF NOT138EXISTS` so older databases upgrade in place without a migration tool.139140## Conventions & gotchas (see `CLAUDE.md` for the full list)141142- **Never put editable line-item controls inside a SwiftUI `Form`** — on macOS it143 silently turns titled `TextField`s into fixed labeled rows and breaks144 `.frame(width:)`, which destroys column alignment. `ReceiptEditForm` is a plain145 `ScrollView` + `VStack` of cards instead.146- **Always decode model output leniently** — assume the vision model will emit the147 wrong JSON type somewhere; coerce, don't crash.148- Swift 5 language mode (not 6) is intentional, to avoid strict-concurrency noise149 around the `@MainActor`/actor boundaries used here.150- `NSApplicationDelegateAdaptor` forcing `.regular` activation is a holdover from151 when this ran as a raw SwiftPM binary; harmless as a bundled `.app` but keep it —152 it's what makes text fields accept keyboard focus if the binary is ever run153 directly.154155## Distribution156157Not the Mac App Store — direct-download `.dmg` builds/releases via a self-hosted158Gitea instance. To ship a Gatekeeper-clean build: set a real Developer ID team in159`project.yml` (`DEVELOPMENT_TEAM`, proper `CODE_SIGN_IDENTITY`), archive160(`xcodebuild archive` or Xcode's Product ▸ Archive), export, and notarize161(`xcrun notarytool` / `xcrun stapler`). `xcodebuild -showBuildSettings` after any162signing change is a fast way to confirm the right identity is picked up before163scripting a Gitea Actions/CI release job around it.164165App icon: `Rhea/Assets.xcassets/AppIcon.appiconset`, generated via `sips` from the1661024px master at `Packaging/AppIcon.png` — regenerate sizes there if the master167changes, don't hand-edit the appiconset.