Spec: hAPI v1 #72

Open
opened 2026-11-27 16:10:52 -05:00 by bobby · 0 comments
Owner

Problem Statement

The Household's personal data and automations are scattered. Finances live in a hand-filled spreadsheet the Owner maintains. Lifting is logged on paper. Home and vehicle upkeep is tracked from memory. There's no way to queue an action for Home Assistant from outside the house. Nothing ties these together. No API exists that the Owner's scripts, iOS Shortcuts, cron jobs, or Home Assistant can call to read and write this data safely from anywhere.

The data is personal (finances, body measurements), so whatever replaces this has to assume a hostile internet. It has to keep each Person's Personal data private, even from the Owner. And it has to stay small enough for one operator to run, patch, back up, and recover.

Solution

hAPI v1 is a cloud-hosted FastAPI modular monolith. It runs on a self-managed Talos Kubernetes cluster on Linode (us-iad) and is backed by Linode Managed PostgreSQL 18. It serves the one Household through a single public HTTPS surface, hapi.bobbypalko.com, gated only by hAPI's own per-Principal Tokens. It ships four domains at MVP depth:

  • Finance: a ledger of Transactions per Financial Account plus a zero-based Budget per owner. The Household's joint Accounts are filled automatically every 6 hours by an in-cluster SimpleFIN Bot.
  • Fitness: hand-logged Workouts (Sets or cardio efforts against a shared Exercise catalog) and body Measurements, as Personal data.
  • Maintenance: Household Assets with optional meters and Readings, recurring Tasks (floating, fixed-calendar, and/or usage-based) whose due state is computed on read, and Services recording work done.
  • Smart home: one-shot Jobs that Home Assistant polls for, runs as allowlisted hapi_* scripts, and reports results back on.

Every record is Personal data or Household data (ADR-0001). Row-level security enforces ownership, Household grants, Bindings, and Scopes in the database as well as in the app (ADR-0004, ADR-0005). The Owner administers Principals only through a CLI inside the pod (ADR-0002). Scheduled work runs as Kubernetes CronJobs of the same image (ADR-0012). It writes durable Notifications that one deliver job publishes to ntfy (ADR-0013). Code reaches the cluster through Flux pulling digest bumps that CI commits (ADR-0007). Secrets are SOPS-encrypted in this public repo (ADR-0008). Observability, backups, and hardening follow ADR-0009, ADR-0014, and ADR-0015.

This spec is the destination of the wayfinder map #44. Everything below is already decided in ADR-0001 through ADR-0015 and the domain resolutions on #51, #59, #60, #61, #62, and #67. This issue gathers them into one buildable whole.

User Stories

Access: Principals, Tokens, Scopes, Bindings

  1. As the Owner, I want to create Persons and Bots from an admin CLI inside the hAPI pod, so that no HTTP route can ever create a Principal.
  2. As the Owner, I want to issue a Token for any Principal from the CLI, with a 365-day default lifetime and a configurable one, so that every credential expires unless I decide otherwise.
  3. As the Owner, I want --no-expiry to be allowed only for Bot Tokens and listed in a warning, so that non-expiring credentials stay visible and rare.
  4. As the Owner, I want hapi token list to flag Tokens near expiry or unused for 90 days, so that I can clean up stale credentials.
  5. As the Owner, I want to give a Bot a Household grant of a Scope (<domain>:read|write or health) from the CLI, so that it can act on that domain's Household data and nothing else.
  6. As the Owner, I want to mark a Person as a Household member (or not) from the CLI, so that friends can use hAPI for their own Personal data without seeing Household data.
  7. As the Owner, I want to deactivate a Principal, which revokes all its Tokens and makes its grants and Bindings inert, so that offboarding is one step and Recorded by never dangles.
  8. As the Owner, I want ownership transfer to need the current Owner's confirmation, and the Owner never to be deactivatable, so that hAPI always has exactly one Owner.
  9. As the Owner, I want an on-demand CLI command that exports and then explicitly deletes a removed Person's Personal data, running per Person under RLS, so that removal is complete and auditable.
  10. As a Person, I want to authenticate with a bearer Token of the form hapi_<public-id>_<secret>, so that scripts, HTTP clients, and Shortcuts need nothing more than curl.
  11. As a Person, I want to list and revoke my own Tokens through the API (but not mint them), so that I can rotate (issue via the Owner, swap, revoke) and kill a leaked Token immediately.
  12. As a Person, I want to list Bots (id, name, description), so that I know what I can bind.
  13. As a Person, I want to grant, list, change, and revoke a Binding that lets a specific Bot act on my Personal data in one domain up to a Scope, so that I control which automation sees my data.
  14. As a Person, I want the Owner to be unable to create a Binding on my behalf, or to read my Personal data, so that my privacy doesn't depend on trusting the Owner.
  15. As any Principal, I want a missing, malformed, unknown, expired, or revoked Token to get the same 401 with WWW-Authenticate: Bearer, so that responses leak nothing about which case applied.
  16. As a Bot, I want a missing Scope or Binding to return a clean 403, and a record I can't see to return 404, so that failures are unambiguous without revealing data.
  17. As the Owner, I want every auth decision and every change to Tokens, grants, and Bindings logged as a structured audit event (without secrets), so that I can investigate misuse.
  18. As a security-minded Owner, I want Token secrets stored only as SHA-256 hashes and looked up on every request, so that revocation takes effect instantly and a database leak yields no usable Tokens.
  19. As a Person who isn't a Household member, I want to see only my own Personal data, so that being a Principal doesn't make me part of the Household.

Ownership and records

  1. As a Person, I want every record to expose owner (a Person id or household) and recorded_by, so that I always know whose a record is and who last touched it.
  2. As a Person, I want lists to accept ?owner=me|household|<person-id> and, unfiltered, to return everything I may see, so that I can scope views without one call per owner.
  3. As a Person, I want owner to default to me on Personal types and to the Household on Household types, so that I rarely have to set it.
  4. As a Bot writing Personal data, I want owner to be required, so that I can never write into the wrong Person's data by accident.
  5. As a Person, I want to move my own Personal record to the Household (one way) where the record type allows it, so that things I start privately can become shared.
  6. As a Person, I want each record to keep one stable URI (/v1/<domain>/<things>/{id}) even after it moves to the Household, so that links and scripts don't break.
  7. As a client developer, I want RFC 9457 Problem Details errors with code and request_id, cursor pagination ({items, next_cursor}, limit capped at 100), UUIDv7 ids, and RFC 3339 timestamps, so that every endpoint behaves predictably.

Finance

  1. As a Household member, I want Household Financial Accounts (e.g. the joint card and checking) whose Transactions are Household data, so that we both see shared spending.
  2. As a Person, I want Personal Financial Accounts whose Transactions only I (and Bots I bind) can see, so that my own spending stays private.
  3. As a Person, I want to create, edit, and archive Financial Accounts with type, institution, currency (USD), tracked_from, and tracked_until, so that hAPI knows which window of each Account to track.
  4. As a Person bringing a card into the Household, I want to end my Personal Account with tracked_until and start a new Household Account with tracked_from on the same date, so that past spending stays with whoever spent it and the Accounts are never linked.
  5. As an importer Bot, I want POST /v1/finance/transactions/ingest to accept bounded batches of {external_id, amount_minor, occurred_on?, posted_on, payee_raw} for one Account, so that I can push what the bank reports.
  6. As an importer Bot, I want each ingested item to report created | duplicate | dismissed | outside_tracked_window, so that I can log exactly what happened.
  7. As a Person, I want a re-import of a known external_id to be ignored, never updated, so that my edits are never overwritten.
  8. As a Person, I want ingest to drop Transactions outside the Account's tracked window, so that handed-over or pre-tracking history doesn't pollute Budgets.
  9. As a Person, I want ingest to fill occurred_on from posted_on (dated_by = posted) when the source gives no purchase date, so that every Transaction has a best-known date.
  10. As a Person, I want to correct occurred_on on an imported Transaction within posted_on − 31 d … posted_on (setting dated_by = manual), so that a purchase lands in the right budget month.
  11. As a Person, I want Transactions with dated_by = posted and posted_on on days 1–5 of a month flagged for date_review, filterable on the list and counted in the previous month's summary, so that I catch purchases that probably belong to last month.
  12. As a Person, I want a PATCH (even one re-sending the same date) to clear date_review, so that confirming a date is one call.
  13. As a Person, I want to create, edit, and delete manual Transactions freely, so that cash and corrections fit in the ledger.
  14. As a Person, I want only the Category, note, and (within the window) occurred_on editable on imported Transactions, so that source facts stay trustworthy.
  15. As a Person, I want deleting an imported Transaction to dismiss it (hidden from Budgets, external_id kept), so that a re-import never brings it back.
  16. As a Person, I want Categories of kind expense | income | transfer, as Household or Personal, with create, rename, archive, merge, and promote, so that I can reshape my Categories as my budget matures.
  17. As a Household member, I want Household Categories to be usable on my Personal Transactions too, so that shared Categories like Groceries work everywhere.
  18. As a Person, I want categorizing a Transaction by hand to create or update my Payee mapping, and ingest to apply mappings (Personal first, then Household, for Personal Accounts), so that categorization learns from me.
  19. As a Person, I want categorized_by = manual | learned on each Transaction, and filters for uncategorized and learned, so that I can review what hAPI guessed.
  20. As a Person, I want to list and delete Payee mappings, so that I can undo a bad lesson.
  21. As a Person, I want one Budget per owner (the Household's over Household Accounts, mine over my Personal Accounts) with a standing expected income, so that each owner plans its own money.
  22. As a Person, I want Targets per Category (monthly, quarterly, or annual, effective from a month, with old Targets kept), so that past months recompute correctly after I change a Target.
  23. As a Person, I want Categories with a longer-than-monthly Target to be Banked, carrying unspent Allocations forward (optionally from an opening banked balance) and going visibly negative when overdrawn, so that annual bills are saved for month by month.
  24. As a Person, I want to record Moves between Categories within a month without changing the month's total, so that I can rebalance mid-month.
  25. As a Person, I want budgets/{id}/months/{YYYY-MM} to show, per Category, the Allocation, spent, remaining, and banked balance, plus unassigned, expected vs actual income, and a rebalance hint, so that one call tells me where the month stands.
  26. As a Person, I want unassigned money reported but never enforced, so that a half-finished rebalance never errors.
  27. As a Person, I want positive amounts in expense Categories to offset spending, and transfer Transactions to be excluded from spending, so that refunds, reimbursements, and card payoffs don't distort the Budget.
  28. As a Person, I want months never locked and summaries recomputed on read, so that late posts land in the right month automatically.

SimpleFIN importer Bot

  1. As the Owner, I want a SimpleFIN Bot that runs every 6 hours in-cluster over a 14-day window and ingests the joint Capital One and Fulton Accounts, so that the Household ledger fills itself.
  2. As the Owner, I want the Bot to map SimpleFIN account ids to Financial Account ids from its SOPS secret and skip unmapped accounts with a warning, so that a newly linked bank account can't leak into the wrong Account.
  3. As the Owner, I want the Bot to exit non-zero on a SimpleFIN transport error, a non-2xx, a non-empty errors array, or a failed ingest, so that a broken run is never silent.
  4. As the Owner, I want a clean run to ping a Kuma push monitor (13 h window), so that I hear about imports stopping even if the whole cluster is down.
  5. As the Owner, I want the Bot to talk to hAPI only over HTTP through the in-cluster Service with its own Token (Household grant finance:write), so that it's an ordinary Bot and an edge outage doesn't stop imports.

Fitness

  1. As a Person, I want to log a whole Workout (date, optional start and duration, note, ordered entries of Sets or one cardio effort) in one POST, so that a Shortcut or script can record a session in one call.
  2. As a Person, I want Sets with reps, load_g, duration_s, optional RPE, and a warmup flag, so that I can record strength, bodyweight, and timed work faithfully.
  3. As a runner, I want a run to be a Workout with one cardio entry (duration_s, optional distance_m and avg_hr_bpm, with pace computed on read), so that cardio needs no separate model.
  4. As a Person on flaky gym wifi, I want Workout and Measurement POSTs with a repeated external_id to return 200 with the existing record, so that retries never double-log.
  5. As a Person, I want to replace a Workout whole with PUT, patch its top-level fields, or hard-delete it, so that fixing a transcription error is simple.
  6. As a Person, I want to list Workouts filtered by date range and Exercise, sorted by performed_on then started_at, so that I can review my training.
  7. As a Household member, I want a shared Household Exercise catalog (seeded by migration) plus my own Personal Exercises, so that we share common movements but I can add my own.
  8. As a Person, I want Exercise kinds (strength | bodyweight | timed | cardio) frozen once used, merge limited to the same kind, promote one-way to Household, and hard delete only while unused, so that history never becomes inconsistent.
  9. As a Person, I want exercises/{id}/history to show my past Sets or efforts and my best non-warmup Set by load and by reps, computed on read, so that I can see progress without stored records going stale.
  10. As a Person, I want to record Measurements (body weight, body fat %, waist, chest, arm, thigh) as SI integers with a date, list them by kind and date range, and patch or delete them, so that I can track my body over time.
  11. As a Person, I want all my Workouts and Measurements to be Personal data, invisible to the Owner and to other Household members, so that body data stays private.

Maintenance

  1. As a Household member, I want Assets (name, location, make, model, serial/VIN, installed, warranty, notes) for the home, its equipment, vehicles, and digital systems such as the hAPI cluster, so that we have one record of what we keep up.
  2. As a Household member, I want an optional meter (distance or duration) on an Asset, settable only while it has no Readings, and Readings with a date and SI value, so that usage-based upkeep (oil every 5,000 mi) works.
  3. As a Household member, I want recurring Tasks that are floating (an interval after the last Service) or fixed (a restricted RRULE with a start date), with an optional usage interval, so that every kind of upkeep rhythm fits.
  4. As a Household member, I want each Task response to carry computed due_on, due_at_meter, and status: ok | due | overdue | snoozed, due on whichever comes first, so that "what's due" is always current without stored state.
  5. As a Household member, I want GET /tasks?due_before=…&status=…, so that one call answers "what needs doing".
  6. As a Household member, I want to snooze a Task without moving its schedule, archive it to stop it coming due, and delete it only while it has no Services, so that history is never lost.
  7. As a Household member, I want to record a Service (done on a date, optionally fulfilling a Task and/or concerning an Asset, with done_by, note, cost in cents, meter value), so that the work history is complete and floating Tasks reset.
  8. As a Household member, I want one-off past work to be a standalone Service, and no future one-off to-dos to exist, so that Maintenance never drifts into a to-do list.
  9. As a future HA Bot, I want Services and Readings to accept an external_id (unique per Household) for idempotent creation, so that automated Readings can be retried safely.
  10. As a Person who isn't a Household member, I want no access to Maintenance, so that Household property stays Household business.

Smart home

  1. As a Household member or Bot with smart_home:write, I want to create a Job naming a hapi_* HA script plus variables (≤16 KB), optionally with not_before and expires_at (default 1 h), so that I can queue a house action from anywhere.
  2. As a client, I want an optional external_id, unique per creating Principal, to make Job creation idempotent (200 on repeat), so that retries don't run an action twice.
  3. As Home Assistant, I want GET /v1/smart_home/jobs/next to hand me the oldest eligible Job (FIFO by not_before or creation time) under a 2-minute lease, so that I can poll every 15–30 s with a built-in rest sensor.
  4. As Home Assistant, I want a Job delivered 3 times without a result to become failed (no_result), so that one broken Job can't stall the queue.
  5. As Home Assistant or a Household member, I want POST /jobs/{id}/result with {status, error?, response?} to be the single way to finish a pending Job (first result wins, later ones get 409), so that a Job can be closed by HA or by hand, with Recorded by showing who.
  6. As a Household member, I want to list Jobs newest first, filtered by status, script, recorded_by, and created-at range, and to get one with its result and attempt count, so that I can see what the house did.
  7. As a Household member, I want to cancel a pending Job (no PATCH; cancel and recreate instead), so that a queued action can be withdrawn.
  8. As a Household member, I want a query Job's response to carry state back from HA, so that I can read house state through hAPI with ~30 s latency.
  9. As the Owner, I want hAPI to record HA's last poll, so that a stalled bridge shows up in health and metrics.
  10. As the Owner, I want a reference HA package (rest sensor, automation, rest_command) kept in this repo, so that wiring HA to hAPI is copy-paste.

Scheduled work and Notifications

  1. As the Owner, I want hapi jobs sweep every 15 minutes to mark past-expiry pending Jobs expired, purge finished Jobs after 90 days, and purge delivered Notifications after 180 days, with reads deriving expired in the meantime, so that correctness never depends on the sweep's timing.
  2. As a Household member, I want a Household Notification once when a Task enters its lead_days and once when it goes overdue, per due occurrence, so that upkeep isn't forgotten and I'm not nagged.
  3. As a Household member, I want a Household Notification when a Job ends failed or expired, so that I know a queued action didn't happen.
  4. As a Household member, I want a Household Notification when a Household Budget Category goes into the red (for a Banked Category, when its banked balance goes negative), refiring only after it recovers, so that overspending is caught within the hour.
  5. As a Person, I want a Notification 30 and 7 days before my Token expires (the Owner gets them for Bot Tokens), so that nothing breaks silently at expiry.
  6. As a Person, I want Notifications to carry only a short title and a link, never amounts, balances, or Measurements, so that push providers see nothing sensitive.
  7. As the Owner, I want checks to only write Notifications and a single hapi notify deliver (every 2 min) to publish them, using the Notification id as ntfy's sequence id and giving up after 24 h, so that an ntfy outage loses nothing and never double-pushes.
  8. As the Owner, I want Household scheduled work to run as a built-in, tokenless scheduler Bot with Owner-given Household grants, and Personal work to run per Person and read-only, so that scheduling never needs elevated credentials.
  9. As the Owner, I want calendar-based CronJobs to use the Household timezone from one setting, so that "daily at 08:00" means local time.

Platform: network, delivery, secrets

  1. As anyone on the internet, I want to reach only hapi.bobbypalko.com:443 (TLS 1.3, IPv4), so that the attack surface is one authenticated API.
  2. As the Owner, I want Envoy Gateway to enforce edge limits (1 MiB bodies, ~20 req/s per IP, ~50 connections per IP, header and timeout limits, HSTS), so that the only shield in front of hAPI is strong.
  3. As the Owner, I want certificates issued by Let's Encrypt over DNS-01 through a delegated acme.bobbypalko.com zone and pinned by CAA to our ACME account, so that a leaked DNS token can neither touch the main zone nor get certificates for us.
  4. As the Owner, I want Kubernetes and Talos APIs, Grafana, metrics, the database, and :8081 reachable only over the management tailnet or the VPC, so that nothing administrative is public.
  5. As the Owner, I want every green merge to main to build, scan, push a digest-pinned image, and commit the digest so Flux deploys it within a minute, so that shipping is merging.
  6. As the Owner, I want migrations to run as a digest-named Job the app waits on, forward-only and backward-compatible, so that a failed migration stops the rollout while old pods keep serving.
  7. As the Owner, I want rollback to be git revert of the digest bump, so that recovery uses the same path as deployment.
  8. As the Owner, I want all cluster secrets SOPS+age-encrypted in git, mounted as files (never env vars), with gitleaks and a SOPS check in CI, so that the public repo never holds a plaintext secret.
  9. As the Owner, I want hapi_app (DML only, subject to RLS), hapi_migrator (owner), and hapi_backup (read-only BYPASSRLS) as separate credentials mounted only where needed, so that a compromised app pod can't change the schema or bypass RLS.
  10. As the Owner, I want hapi db bootstrap to idempotently create the database and roles from the SOPS passwords, with the akmadmin password pasted in at run time, so that the database can be recreated from git plus one secret.
  11. As the Owner, I want hapi db breakglass --reason to publish a priority-5 Household alert first (refusing to start if the alert fails) and log every statement, so that emergency access is never invisible.

Observability, backup, hardening

  1. As Uptime Kuma (a Bot with the health Scope), I want GET /v1/health to report ok | degraded | down with only check names (db, schema critical; ha_bridge, job_backlog non-critical), so that I can alert on reachability and health without leaking detail.
  2. As the kubelet, I want unauthenticated /livez, /readyz, and /metrics on an internal :8081 that the Gateway never routes, so that probes work without breaking "no anonymous public endpoints".
  3. As the Owner, I want structured JSON logs (with request_id and principal_id, Personal data redacted) and Prometheus metrics (no principal_id labels) collected into in-cluster VictoriaLogs and VictoriaMetrics, so that I can debug without data leaving the cluster.
  4. As the Owner, I want each failure mode to have exactly one alerting owner (Kuma, Flux, vmalert, Watchdog) publishing to Owner-only ops / ops-urgent ntfy topics, so that platform alerts work even when hAPI is down.
  5. As the Owner, I want a daily hapi db backup that verifies the dump's table of contents, encrypts it to a backup-only age recipient, and uploads it to an Object Lock (compliance, 35 d) bucket, so that a compromised cluster can neither read nor delete backups.
  6. As the Owner, I want an off-account puller (on my PC for now) that copies backups immutably and prunes to 90 dailies, 3 years of monthlies, and 1 year of audit exports, so that losing the Linode account doesn't lose the data.
  7. As the Owner, I want hapi db restore to run in a pod with the backup key pasted in at run time, so that restores work against a VPC-only database without the key ever being stored.
  8. As the Owner, I want default-deny network policies, Pod Security restricted, admission rules (images from Gitea's registry or pinned by digest; read-only rootfs and no SA token in hapi/bots), and Kubernetes audit logs kept 1 year with an alert on exec or a human Secret read, so that the cluster is hardened with built-ins only.
  9. As the Owner, I want a "hAPI cluster" Maintenance Asset carrying a monthly "Upgrade the cluster" Task and a 6-monthly "Rehearse disaster recovery" Task, so that hAPI reminds me to keep hAPI healthy.
  10. As the Owner, I want a full disaster-recovery drill (rebuild the cluster from code in an empty project, then restore from a pulled dump) before go-live, so that recovery is proven, not assumed.

Developer experience

  1. As a developer, I want just dev/test/lint/migrate recipes with the app on the host and Postgres 18 in Docker Compose, so that local dev mirrors prod's database.
  2. As a developer, I want pre-commit and CI to run Ruff, pyright strict, import-linter, and gitleaks, so that style, types, module boundaries, and secrets are checked before review.
  3. As a developer, I want OpenAPI docs off in prod but exported as a CI artifact, with each route's required Scope visible in it, so that clients have a contract without exposing docs publicly.

Implementation Decisions

Application shape (#51)

  • Python 3.14 + uv, one pyproject.toml, Ruff (including DTZ) + pyright strict, just, pre-commit, Renovate (auto-merges dev tooling only).
  • Async end to end: async SQLAlchemy 2 with typed Mapped[], separate Pydantic v2 API schemas, async outbound HTTP.
  • Modules: a shared platform package (config, db/session with principal context, auth, errors, logging, pagination, health, metrics, CLI scaffolding, Notifications) and one package per domain: finance, fitness, maintenance, smart_home. The domain is named Maintenance, superseding the home_maintenance name in #51. Each domain has models / schemas / service / router. Domains may import platform and only other domains' public service API. import-linter enforces this, and also forbids bots/ from importing hapi.*.
  • One Postgres database hapi, one schema per domain (plus a platform schema for Principals, Tokens, grants, Bindings, Notifications). There is a single linear Alembic history with a strict constraint naming convention, run only by hapi migrate.
  • Owner mixin: every domain table carries owner (a Person id or the Household) plus Recorded by (created-by and last-changed-by Principal). Principals are never hard-deleted.
  • Config: pydantic-settings, HAPI_ prefix, secrets read from a mounted secrets_dir (never env vars), fail fast at startup. The Household timezone is one setting.
  • Runtime: one uvicorn process per pod serving the API on :8000 and probes/metrics on :8081 in the same event loop. uvicorn trusts X-Forwarded-For only from the Gateway pod range. Graceful shutdown: /readyz fails first, then a ~5 s drain.
  • Image: multi-stage uv builder → python:3.14-slim pinned by digest, non-root, read-only rootfs, amd64, with postgresql-client-18 for dump/restore/breakglass.
  • API conventions: /v1/<domain>/<things>/{id} flat resources; RFC 9457 errors with code + request_id; UUIDv7 ids generated in the app; timestamptz in UTC with RFC 3339 offsets; calendar concepts as date interpreted in the Household timezone; cursor pagination {items, next_cursor} with limit default-capped at 100; idempotent creates via external_id returning 201 on create and 200 with the existing record on repeat. OpenAPI UI and JSON are disabled in prod and exported in CI. #51 also mentioned unversioned /healthz and /readyz; ADR-0009 supersedes that with :8081 /livez and /readyz plus authenticated /v1/health.

Auth and authorization (ADR-0005, ADR-0004 as amended)

  • Credential: opaque Token hapi_<public-id>_<secret> with a 256-bit secret, stored as SHA-256, looked up per request on the request's pooled connection. Credentials carry kind = api_token, so a future session kind changes nothing else. Expiry defaults to 365 d, and --no-expiry is for Bots only. last_used_at is written at most about once an hour.
  • Principal context: each request transaction runs SET LOCAL hapi.principal_id to the authenticated Principal (Person or Bot). RLS policies read it as nullif(current_setting('hapi.principal_id', true), '').
  • RLS (ENABLE, not FORCE) on every owner-mixin table:
    • Personal tables allow the owner, or a Bot holding an active Binding from the owner for that domain.
    • Household tables allow an active Household member, or a Bot with a Household grant for that domain.
    • USING checks the read Scope and WITH CHECK checks the write Scope.
    • Finance's cross-owner rule (Household Categories usable on members' Personal Transactions) and Fitness's (Household Exercises referenced from Personal Workouts) are expressed as reads of Household rows, not as writes across owners.
  • App-level guard: routes declare require_scope(...), so a missing Scope is a clean 403 and appears in OpenAPI. A record the caller can't see is 404. All Token failures get an identical 401.
  • Scopes: finance|fitness|maintenance|smart_home × read|write (write implies read), plus health.
  • Public API for Persons: own Tokens (list, revoke), Bindings (grant, list, change, revoke), and Bots (list). Nothing else about Principals is on HTTP.
  • Audit: auth decisions and grant/Binding/Token changes are structured log events. Secrets are never logged.
  • Built-in scheduler Bot: created by migration, can never hold a Token, and receives Household grants from the Owner like any Bot.

Admin CLI (hapi)

One Typer-style entry point in the app image, run in-pod. It is the only path for Owner administration:

  • principal (create Person or Bot, deactivate, set Household membership, transfer ownership)
  • token (issue, list, revoke)
  • grant (Household grants)
  • person remove (export, then delete Personal data, per Person under RLS)
  • migrate
  • db bootstrap | breakglass | backup | restore
  • jobs sweep
  • notify tasks | jobs | budget | tokens | deliver

The app-side commands connect as hapi_app. migrate, bootstrap, breakglass, and restore use migrator credentials mounted only into their pods. backup uses hapi_backup. Each housekeeping run uses a connection pool of 1.

Finance (#59, amended by #67)

  • Entities:
    • Financial Account: name, type checking|savings|credit_card|cash, institution, currency (USD only), owner, tracked_from, tracked_until, archived. No balances.
    • Transaction: account, signed amount_minor, occurred_on, posted_on, payee_raw + normalized payee, external_id unique per Account, Category, categorized_by manual|learned, dated_by source|posted|manual, note, dismissed, Recorded by. Posted Transactions only, no pending.
    • Category: name, kind expense|income|transfer, owner, archived.
    • Budget: one per owner, expected income.
    • Target: Budget × Category, amount, period monthly|quarterly|annual, effective-from month, optional opening banked balance. History is kept.
    • Move: Budget, month, from, to, amount.
    • Payee mapping: owner, normalized payee → Category.
  • Ownership: Transactions inherit their Account's owner. Financial Accounts and Transactions never change owner (this narrows ADR-0001's one-way move). Categories can be promoted. The Household Budget counts Household Accounts only, and a Person's Budget counts that Person's Personal Accounts only.
  • Ingest: POST /v1/finance/transactions/ingest with {financial_account_id, transactions[]}, batch size capped by the app. Per item:
    • The result is one of created|duplicate|dismissed|outside_tracked_window.
    • A known external_id is ignored, never updated.
    • If occurred_on is absent, it's copied from posted_on with dated_by = posted.
    • Payee mappings are applied (Personal Accounts check Personal mappings, then Household ones; Household Accounts check only Household ones).
    • Bots never set Categories.
  • Editing:
    • Manual Transactions are fully editable and deletable.
    • On imported Transactions, only Category, note, and occurred_on (within posted_on − 31 d … posted_on) are editable. Deleting one dismisses it.
    • Manual categorization creates or updates the owner's Payee mapping.
    • date_review is derived: dated_by = posted and posted_on falls on days 1–5. Any PATCH clears it.
  • Budget math (computed on read, months never locked, month decided by occurred_on):
    • Allocation = the Target's monthly share ± Moves.
    • Unassigned = expected income − Σ Allocations, reported but not enforced.
    • Positive amounts in expense Categories offset spending, and transfer Categories are excluded.
    • Ordinary leftovers don't carry. Banked balances accrue and may go negative.
    • The rebalance hint is set when at least one Category is in the red and another still holds money.
    • The month summary also carries expected vs actual income and the previous month's date_review count.
  • Endpoints:
    • accounts: CRUD, archive.
    • transactions: list with filters (account, owner, month, Category, uncategorized, categorized_by, date_review), create, PATCH, DELETE/dismiss; transactions/ingest.
    • categories: CRUD, archive, merge, promote.
    • payee-mappings: list, delete.
    • budgets: per owner, with targets, moves, and months/{YYYY-MM}.

Fitness (#60)

  • Entities:
    • Exercise: name, owner, archived, kind strength|bodyweight|timed|cardio.
    • Workout: performed_on, started_at?, duration_s?, note, external_id? unique per Person, ordered entries. Each entry has exercise_id and either sets[] (reps, load_g, duration_s, rpe?, warmup) or cardio{duration_s, distance_m?, avg_hr_bpm?}, matching the Exercise kind.
    • Measurement: kind from a fixed enum, integer value in base SI units, measured_on, measured_at?, external_id?.
  • Ownership: Workouts and Measurements are Personal data. Exercises are Household (seeded by a data migration) or Personal. Non-members see only their own Personal Exercises.
  • Rules:
    • An Exercise's kind is frozen once used.
    • Merge only within one kind: entries move, then the source is archived.
    • A Person can't merge another Person's Personal Exercise.
    • Promotion is one-way.
    • Hard delete only while unused.
    • Pace and bests are computed on read. Warmups are excluded from bests.
  • Endpoints:
    • exercises: CRUD, archive, merge, promote, history.
    • workouts: list (date range, Exercise filters), whole-body create, GET, PUT (full replace), PATCH (top-level), DELETE (hard).
    • measurements: list (kind, date range), create, PATCH, DELETE.

Maintenance (#61, amended by ADR-0015)

  • Everything is Household data. Non-members have no access.
  • Entities:
    • Asset: name, location?, make?, model?, serial?, installed_on?, warranty_until?, notes, archived, optional meter unit distance|duration. The meter is settable only while the Asset has no Readings.
    • Reading: Asset, read_on, value (m or s), external_id?.
    • Task: title, asset_id?, note, lead_days?, archived, snoozed_until?; schedule = floating (interval count + unit) or fixed (restricted RRULE + start date); optional usage interval.
    • Service: done_on, task_id?, asset_id?, title (required without a Task), done_by? (a Person), note, cost_cents?, meter_value?, external_id?.
    • external_id is unique per Household on Services and Readings.
  • Restricted RRULE: FREQ, INTERVAL, BYMONTH, BYMONTHDAY, BYDAY with ordinals, and BYSETPOS only. No COUNT or UNTIL. Evaluated with dateutil.rrule.
  • Due computation (on read, nothing stored):
    • Due on whichever comes first: the calendar date or the usage threshold (judged against the latest Reading, no projection).
    • The first due date comes from the latest Service if one exists, otherwise creation date + one interval. A fixed Task's first due date is the rule's next occurrence.
    • Status is ok|due|overdue|snoozed, with "due" starting lead_days before the due date.
    • Snooze hides the Task without moving the schedule.
  • Endpoints:
    • assets: CRUD, archive, nested readings (list, create, PATCH, DELETE).
    • tasks: CRUD, archive, snooze, plus ?due_before=&status=.
    • services: list (Task, Asset, date range), create, PATCH, DELETE.
  • Seed data: none for the domain in general. The "hAPI cluster" Asset with its "Upgrade the cluster" (monthly) and "Rehearse disaster recovery" (6-monthly, fixed RRULE) Tasks is created by the Owner during go-live, not by a migration.

Smart home (ADR-0006, #62)

  • Job: Household data.
    • Fields: script (must match hapi_[a-z0-9_]+), variables (≤16 KB JSON), not_before?, expires_at (default not_before or creation + 1 h), external_id? unique per creating Principal, status pending|succeeded|failed|expired|cancelled, attempts, lease-until, result {status, error?, response?}, Recorded by.
    • expired is derived from expires_at until the sweep persists it.
  • Delivery:
    • GET /v1/smart_home/jobs/next returns the oldest eligible Job (FIFO by not_before or creation time, not leased, not expired) and leases it for 2 minutes, incrementing attempts.
    • A Job leased 3 times with no result becomes failed with no_result.
    • Every call records HA's last-poll time.
  • Finishing:
    • POST /jobs/{id}/result is accepted from any Household member or any Bot with smart_home:write while the Job is pending, leased or not.
    • The first result wins, and later ones get 409.
    • Finished Jobs are immutable.
  • Other endpoints: list (newest first; status, script, recorded_by, and created-at filters), GET, and cancel on pending Jobs. There's no PATCH.
  • Scopes: smart_home:write both creates and consumes Jobs. A Bot needs smart_home:read to read them. HA is the Bot home-assistant, with a Household grant of smart_home:write.
  • Internal API: the module exposes an internal create_job service function for future domain use. Nothing calls it in v1.
  • HA reference package: rest sensor, automation, and rest_command, kept in this repo and copied into HA by hand. The hapi_* scripts live in the HA config repo.

Notifications (ADR-0012, ADR-0013)

  • Record:

    • Fields: recipient (Person or Household), kind, dedupe_key (unique with kind), title, body, priority 1–5, link?, created_at, delivered_at, attempts.
    • Content carries no domain values.
    • Visibility follows ownership: a Person's Notification is Personal data, the Household's is Household data.
    • There is no Notifications API in v1.
  • Checks (all run as scheduler, write-only, reading Household and platform data):

    Check Recipient Fires when Schedule
    tasks Household once on entering lead_days, once on overdue, per due occurrence daily 08:00
    jobs Household a Job ends failed or expired every 15 min
    budget Household a Household Budget Category goes into the red this month (Banked: its banked balance goes negative); refires only after it recovers hourly
    tokens the Token's Person, or the Owner for Bot Tokens 30 and 7 days before expiry daily
  • Delivery:

    • hapi notify deliver runs every 2 min and publishes pending Notifications oldest first to hapi-p-<person-id> or hapi-household on notify.bobbypalko.com, using hAPI's publish-only ntfy token.
    • The Notification id is ntfy's sequence id, so retries don't double-push.
    • It gives up after 24 h, and vmalert alerts on Notifications that old.
  • Priorities:

    • 4: Task overdue.
    • 3: Job failed or expired; Token expiring in 7 days.
    • 2: Task due soon; budget overspend; Token expiring in 30 days.
    • 5: breakglass, published synchronously by hapi db breakglass before the session opens. It fails closed.

Health and metrics (ADR-0009)

  • :8081:
    • /livez is constant.
    • /readyz passes after startup and fails on SIGTERM. It never checks the DB.
    • /metrics comes from prometheus-client: requests by route template, method, and status; latency; DB pool usage; Job depth, age, and failures; seconds since HA's last poll; auth failures by reason. No principal_id labels.
  • GET /v1/health needs the health Scope.
    • Critical checks: db (SELECT 1 through the app pool) and schema (at the expected Alembic head). Any failure means down with HTTP 503.
    • Non-critical checks: ha_bridge (no poll for 5 min) and job_backlog (oldest pending Job too old). Any failure means degraded with HTTP 200.
    • Bodies carry only check names and ok/fail.

SimpleFIN Bot (ADR-0011, #67)

  • A separate package and image in the repo, with no hapi.* imports. It's a CronJob in bots every 6 h with concurrencyPolicy: Forbid.
  • Each run fetches accounts with start-date = now − 14 d and ingests each mapped account, one batch per account.
  • Field mapping: external_id = SimpleFIN id, posted_on = posted as a UTC date, amount_minor from the decimal amount, payee_raw = description. It never sends occurred_on.
  • Exit status:
    • Non-zero on a transport error, a non-2xx, a non-empty errors array, or any failed ingest.
    • Unmapped accounts are only a warning.
    • A clean run pings the Kuma push URL.
  • Config: one SOPS secret bot-simplefin (Token, Access URL, account mapping, Kuma push URL), mounted as files.
  • Calls: the in-cluster hAPI Service. Principal simplefin-importer with a Household grant of finance:write.
  • To check during the build: SimpleFIN's daily request quota.

Infrastructure and delivery (ADR-0002, ADR-0003, ADR-0007, ADR-0008, ADR-0010, ADR-0014, ADR-0015)

  • Cluster: OpenTofu (encrypted state in Object Storage) provisions Talos in us-iad:
    • 1 control-plane node + 2 g6-standard-2 workers in a spread placement group, joined to the VPC.
    • Nodes have public IPv4 with a deny-all Cloud Firewall except Tailscale UDP 41641 and the VPC.
    • Talos LUKS on STATE and EPHEMERAL. Every node joins the management tailnet (Tailnet Lock on) with pre-signed keys.
    • Tofu installs only Cilium (WireGuard, tunnel mode, gatewayAPI.enabled=false) and the Linode CCM, with its own narrow token.
    • Tofu also owns the reserved IPv4, the NodeBalancer firewall (443 only), the DNS records (A, the _acme-challenge CNAME, the acme. delegation, CAA), the backup bucket (Object Lock), the Managed DB, and the CI runner VM.
  • Database: Managed PG 18, Shared 2 GB, 1 node, VPC-only allowlist, verify-full, scram-sha-256.
    • Roles: hapi_migrator, hapi_app, hapi_backup.
    • Connection budget: app pods (with surge) × 10 + concurrent CronJobs × 1 + ~6 ≤ 46.
  • Edge:
    • CCM NodeBalancer in TCP mode with Proxy Protocol v2 and throttle: 20 → Envoy Gateway (2 replicas, PDB).
    • Envoy enforces TLS 1.3, h2 and http/1.1, 16 KiB headers, ~50 connections per IP, 30 s request and 60 s idle timeouts, ~20 req/s burst 100 per IP, 1 MiB bodies, and HSTS.
    • One Gateway and one HTTPRoute to :8000.
    • cert-manager with Let's Encrypt over DNS-01, using the Linode webhook with cnameStrategy: Follow and a restricted-user token on acme.bobbypalko.com only. The ACME account key is in SOPS. CAA is pinned to accounturi.
  • Delivery:
    • Gitea Actions on a dedicated runner VM. PRs run lint, pyright, import-linter, tests, the image build, a smoke test, the OpenAPI export, Trivy, gitleaks, and the SOPS check.
    • On main, CI pushes the image to Gitea's registry and commits the digest. Bump commits are path-filtered.
    • Flux polls anonymously every minute with prune and drift correction.
    • The repo layout is deploy/clusters/prod, deploy/infrastructure, and deploy/apps/hapi.
    • The hapi-migrate Kustomization (digest-named Job) is something the app dependsOn.
    • The app runs 2 replicas with surge 1 and unavailable 0, a PDB minAvailable: 1, and spread across workers.
    • Failure notifications go to ntfy ops.
  • Secrets:
    • SOPS + age with a single offline prod key. .sops.yaml encrypts only data/stringData in deploy/**/*.sops.yaml.
    • Secrets are mounted as files. hapi-db-app and hapi-db-migrator are split, and the backup role has its own secret.
    • No workload ServiceAccount can read Secrets. Owner roots live in Vaultwarden plus an offline copy.
  • Observability:
    • VictoriaMetrics and VictoriaLogs (30 d), vmagent, a Vector DaemonSet, an event exporter, Grafana (login required, port-forward only), and vmalert.
    • Breakglass and Kubernetes audit events are kept 1 year and exported daily with backups.
    • A Watchdog pushes to Kuma.
    • One generic vmalert rule fires when any CronJob hasn't succeeded within twice its interval.
  • Backups:
    • hapi db backup runs daily at 03:00 Household time: pg_dump -Fc → pg_restore --list check → age (backup-only recipient) → the Object Lock bucket (35 d), plus the previous day's audit export.
    • The off-account puller script (rclone copy --immutable plus pruning, with a just recipe) runs as a systemd user timer on the Owner's PC.
    • Kuma push monitors: 26 h for the backup job, 8 d for the puller.
    • hapi db restore supports path A (PITR fork) and path B (restore from our own dump).
  • Hardening:
    • Default-deny CiliumNetworkPolicies in every owned namespace (hapi, bots, gateway, envoy-gateway-system, monitoring, monitoring-node, cert-manager, flux-system), with toFQDNs and toCIDR allows next to each component.
    • PSA restricted everywhere except monitoring-node (privileged).
    • Two ValidatingAdmissionPolicies, set to Deny.
    • Kubernetes audit policy at Metadata level, with an ops alert on pods/exec or a human reading a Secret.
    • Versions pinned in infra/, Renovate PRs, security patches within 14 days, and a cluster-upgrade runbook.
  • Runbooks to write during the build: Flux install, DB bootstrap and password rotation, breakglass, ntfy user management (including offboarding), restore (paths A and B), and cluster upgrade.

Testing Decisions

  • What makes a good test: it drives the system only through an external seam and asserts on what that seam returns or makes observable (HTTP responses, CLI exit codes and output, rows visible through the API, outbound HTTP calls to faked external systems). Tests don't reach into service internals, ORM models, or private helpers. Refactoring inside a module must never break a test. The database is never mocked. Only external systems (ntfy, SimpleFIN, Kuma, HA, which is just another HTTP client) are faked, at their HTTP boundary.
  • Seam 1: the public HTTP API.
    • pytest + pytest-asyncio drive the ASGI app through httpx.AsyncClient + ASGITransport against real Postgres 18 via testcontainers.
    • The database is created by the same hapi db bootstrap and hapi migrate as prod. The app connects as hapi_app with RLS on, and each test rolls back its own transaction.
    • This seam covers every domain endpoint plus auth, Tokens, Bindings, health, idempotency, pagination, and error shapes.
    • Every endpoint gets a wrong-Principal test (wrong Person, wrong Bot, non-member, revoked Binding, read-only Scope attempting a write, deactivated Principal), asserting 401/403/404 as ADR-0005 specifies.
    • Computed-on-read behaviour (Budget month summaries, Banked carry-forward, date_review, Task due state and RRULE edge cases, Exercise history and bests, Job lease/attempt/expiry) is asserted through the API with controlled dates. The app takes a clock dependency that tests can pin.
  • Seam 2: the hapi CLI.
    • The CLI entry point is invoked in-process against the same Postgres, asserting on exit codes, output, and effects visible through Seam 1.
    • Covered: principal, token, grant, and member management; deactivation; ownership transfer; Person removal (export, then delete); jobs sweep; each notify <check> (correct recipient, dedupe, refire-after-recovery, no domain values in content); notify deliver against a fake ntfy (sequence id, retry, 24 h give-up); and db breakglass refusing to start when the alert publish fails.
    • db backup and db restore get a round-trip test against the test container (dump → list check → encrypt with a test age key → restore into a fresh database → same Alembic revision and row counts), with Object Storage faked.
  • Seam 3: the SimpleFIN Bot's run entry point.
    • SimpleFIN and hAPI are both faked at HTTP.
    • Asserted: field mapping (no occurred_on, UTC posted date, decimal → minor units), unmapped-account warning, non-zero exit on each failure class, and the Kuma ping only on a clean run.
    • One contract test runs the Bot against the real hAPI app from Seam 1, proving ingest results end to end.
  • Static and structural checks in CI (not seams, but required):
    • Ruff, pyright strict, import-linter (domain boundaries; bots/ has no hapi.* imports), gitleaks, the SOPS-encryption check, and Trivy.
    • An RLS coverage check: every owner-mixin table has relrowsecurity set and is owned by hapi_migrator, never hapi_app.
    • The OpenAPI export.
  • Infrastructure (Tofu, Talos, Flux, network policies, admission policies) has no unit seam. It's verified by the CI image smoke test, by the build-time checks ADR-0010 and ADR-0014 list (restricted DNS token cannot edit the main zone; delegated subzone resolves; CCM copies annotations; akmadmin can create a BYPASSRLS role; the bucket key can't delete a locked version), and by the go-live disaster-recovery drill: rebuild in an empty Linode project, then restore path B from a pulled dump.
  • Prior art: none in the repo yet (greenfield). The conventions above come from the #51 resolution and ADR-0004's CI isolation rule. The first implementation issue should land the test harness (testcontainers + bootstrap + migrate + principal factories + a pinned clock) so every later issue inherits it.

Out of Scope

  • A frontend, mobile apps, interactive login (passkeys, OIDC), cookies/CSRF/CORS.
  • Public signups, third-party OAuth, sharing outside the Household, guest access, and roles within the Household.
  • A staging environment, distributed tracing, and app-level or per-Principal rate limiting.
  • Deploying or backing up Uptime Kuma, ntfy, Home Assistant, or Gitea. HA config beyond the job bridge reference package and the hapi_* scripts in the HA config repo.
  • Finance: splits, balances and net worth, transfer-leg linking, ML categorization, a rule editor, pending Transactions, bill-due reminders, finer Finance Scopes (a v2 priority), multi-currency (never), spreadsheet migration, backfill, file (OFX/QFX/CSV) importers, Personal Account import (including Apple Card), and Personal-domain notification checks.
  • Fitness: templates, programs, goals, 1RM and PR feeds, wearable or historical import, daily aggregates, reminders, drop sets, supersets, tempo. Nutrition as a domain.
  • Maintenance: attachments, Finance cost linking, an HA runtime-Reading Bot, HA completing Tasks, and future one-off to-dos.
  • Smart home: a house-state store, hAPI-side automations and scenes, typed control endpoints, a script catalogue, recurring Jobs, domain-created Jobs, MQTT, and restricting results to the leasing Bot.
  • Notifications: preferences, read state, a Notifications API or inbox, channels other than ntfy, and quiet hours.
  • Platform: a worker Deployment, a task queue, or an outbox; PgBouncer; HA etcd or three control-plane nodes; IPv6; a backup ACME CA; commit and image signing; Kyverno; runtime detection; Trivy Operator; CIS scanning; the Cilium host firewall; least-privilege kubeconfigs; per-Person encryption; and etcd backups.

Further Notes

  • This spec is the destination of the wayfinder map #44, and ADR-0001 through ADR-0015 are the authoritative record for platform decisions. Where this spec and an ADR disagree, the ADR wins and this spec should be corrected.
  • Domain detail comes from the resolutions on #51 (skeleton), #59 + #67 (Finance and the importer), #60 (Fitness), #61 (Maintenance, amended by ADR-0015), and #62 (Smart home).
  • Suggested build order for slicing into issues:
    1. App skeleton and test harness.
    2. Principals, Tokens, auth, and RLS.
    3. Admin CLI.
    4. Each domain, in any order. Smart home and Maintenance have no cross-domain dependencies. Finance ingest precedes the SimpleFIN Bot.
    5. Health and metrics.
    6. Notifications and CronJobs.
    7. Infrastructure: Tofu/Talos, then Flux, edge, secrets, observability, backups, and hardening.
    8. Go-live: the DR drill, then creating the "hAPI cluster" Asset and its two Tasks.
  • Infrastructure work is mostly ready-for-human when sliced. It touches the Owner's Linode account, Vaultwarden, DNS, and the management tailnet. App and Bot code is AFK-friendly.
  • Verify-during-build items that can force a decision change: the DNS-01 restricted token and subzone delegation (fallback: acme-dns), the CCM annotation passthrough, BYPASSRLS role creation on the managed DB, the locked-version delete test, and SimpleFIN's daily quota.

🤖 Generated with Claude Code

## Problem Statement The Household's personal data and automations are scattered. Finances live in a hand-filled spreadsheet the Owner maintains. Lifting is logged on paper. Home and vehicle upkeep is tracked from memory. There's no way to queue an action for Home Assistant from outside the house. Nothing ties these together. No API exists that the Owner's scripts, iOS Shortcuts, cron jobs, or Home Assistant can call to read and write this data safely from anywhere. The data is personal (finances, body measurements), so whatever replaces this has to assume a hostile internet. It has to keep each Person's Personal data private, even from the Owner. And it has to stay small enough for one operator to run, patch, back up, and recover. ## Solution hAPI v1 is a cloud-hosted **FastAPI modular monolith**. It runs on a self-managed **Talos Kubernetes cluster on Linode** (`us-iad`) and is backed by **Linode Managed PostgreSQL 18**. It serves the one Household through a single public HTTPS surface, `hapi.bobbypalko.com`, gated only by hAPI's own per-Principal Tokens. It ships four domains at MVP depth: - **Finance**: a ledger of Transactions per Financial Account plus a zero-based Budget per owner. The Household's joint Accounts are filled automatically every 6 hours by an in-cluster **SimpleFIN Bot**. - **Fitness**: hand-logged Workouts (Sets or cardio efforts against a shared Exercise catalog) and body Measurements, as Personal data. - **Maintenance**: Household Assets with optional meters and Readings, recurring Tasks (floating, fixed-calendar, and/or usage-based) whose due state is computed on read, and Services recording work done. - **Smart home**: one-shot **Jobs** that Home Assistant polls for, runs as allowlisted `hapi_*` scripts, and reports results back on. Every record is Personal data or Household data (ADR-0001). Row-level security enforces ownership, Household grants, Bindings, and Scopes in the database as well as in the app (ADR-0004, ADR-0005). The Owner administers Principals only through a CLI inside the pod (ADR-0002). Scheduled work runs as Kubernetes CronJobs of the same image (ADR-0012). It writes durable **Notifications** that one deliver job publishes to ntfy (ADR-0013). Code reaches the cluster through Flux pulling digest bumps that CI commits (ADR-0007). Secrets are SOPS-encrypted in this public repo (ADR-0008). Observability, backups, and hardening follow ADR-0009, ADR-0014, and ADR-0015. This spec is the destination of the wayfinder map #44. Everything below is already decided in ADR-0001 through ADR-0015 and the domain resolutions on #51, #59, #60, #61, #62, and #67. This issue gathers them into one buildable whole. ## User Stories ### Access: Principals, Tokens, Scopes, Bindings 1. As the Owner, I want to create Persons and Bots from an admin CLI inside the hAPI pod, so that no HTTP route can ever create a Principal. 2. As the Owner, I want to issue a Token for any Principal from the CLI, with a 365-day default lifetime and a configurable one, so that every credential expires unless I decide otherwise. 3. As the Owner, I want `--no-expiry` to be allowed only for Bot Tokens and listed in a warning, so that non-expiring credentials stay visible and rare. 4. As the Owner, I want `hapi token list` to flag Tokens near expiry or unused for 90 days, so that I can clean up stale credentials. 5. As the Owner, I want to give a Bot a Household grant of a Scope (`<domain>:read|write` or `health`) from the CLI, so that it can act on that domain's Household data and nothing else. 6. As the Owner, I want to mark a Person as a Household member (or not) from the CLI, so that friends can use hAPI for their own Personal data without seeing Household data. 7. As the Owner, I want to deactivate a Principal, which revokes all its Tokens and makes its grants and Bindings inert, so that offboarding is one step and Recorded by never dangles. 8. As the Owner, I want ownership transfer to need the current Owner's confirmation, and the Owner never to be deactivatable, so that hAPI always has exactly one Owner. 9. As the Owner, I want an on-demand CLI command that exports and then explicitly deletes a removed Person's Personal data, running per Person under RLS, so that removal is complete and auditable. 10. As a Person, I want to authenticate with a bearer Token of the form `hapi_<public-id>_<secret>`, so that scripts, HTTP clients, and Shortcuts need nothing more than `curl`. 11. As a Person, I want to list and revoke my own Tokens through the API (but not mint them), so that I can rotate (issue via the Owner, swap, revoke) and kill a leaked Token immediately. 12. As a Person, I want to list Bots (id, name, description), so that I know what I can bind. 13. As a Person, I want to grant, list, change, and revoke a Binding that lets a specific Bot act on my Personal data in one domain up to a Scope, so that I control which automation sees my data. 14. As a Person, I want the Owner to be unable to create a Binding on my behalf, or to read my Personal data, so that my privacy doesn't depend on trusting the Owner. 15. As any Principal, I want a missing, malformed, unknown, expired, or revoked Token to get the same `401` with `WWW-Authenticate: Bearer`, so that responses leak nothing about which case applied. 16. As a Bot, I want a missing Scope or Binding to return a clean `403`, and a record I can't see to return `404`, so that failures are unambiguous without revealing data. 17. As the Owner, I want every auth decision and every change to Tokens, grants, and Bindings logged as a structured audit event (without secrets), so that I can investigate misuse. 18. As a security-minded Owner, I want Token secrets stored only as SHA-256 hashes and looked up on every request, so that revocation takes effect instantly and a database leak yields no usable Tokens. 19. As a Person who isn't a Household member, I want to see only my own Personal data, so that being a Principal doesn't make me part of the Household. ### Ownership and records 20. As a Person, I want every record to expose `owner` (a Person id or `household`) and `recorded_by`, so that I always know whose a record is and who last touched it. 21. As a Person, I want lists to accept `?owner=me|household|<person-id>` and, unfiltered, to return everything I may see, so that I can scope views without one call per owner. 22. As a Person, I want `owner` to default to me on Personal types and to the Household on Household types, so that I rarely have to set it. 23. As a Bot writing Personal data, I want `owner` to be required, so that I can never write into the wrong Person's data by accident. 24. As a Person, I want to move my own Personal record to the Household (one way) where the record type allows it, so that things I start privately can become shared. 25. As a Person, I want each record to keep one stable URI (`/v1/<domain>/<things>/{id}`) even after it moves to the Household, so that links and scripts don't break. 26. As a client developer, I want RFC 9457 Problem Details errors with `code` and `request_id`, cursor pagination (`{items, next_cursor}`, `limit` capped at 100), UUIDv7 ids, and RFC 3339 timestamps, so that every endpoint behaves predictably. ### Finance 27. As a Household member, I want Household Financial Accounts (e.g. the joint card and checking) whose Transactions are Household data, so that we both see shared spending. 28. As a Person, I want Personal Financial Accounts whose Transactions only I (and Bots I bind) can see, so that my own spending stays private. 29. As a Person, I want to create, edit, and archive Financial Accounts with type, institution, currency (USD), `tracked_from`, and `tracked_until`, so that hAPI knows which window of each Account to track. 30. As a Person bringing a card into the Household, I want to end my Personal Account with `tracked_until` and start a new Household Account with `tracked_from` on the same date, so that past spending stays with whoever spent it and the Accounts are never linked. 31. As an importer Bot, I want `POST /v1/finance/transactions/ingest` to accept bounded batches of `{external_id, amount_minor, occurred_on?, posted_on, payee_raw}` for one Account, so that I can push what the bank reports. 32. As an importer Bot, I want each ingested item to report `created | duplicate | dismissed | outside_tracked_window`, so that I can log exactly what happened. 33. As a Person, I want a re-import of a known `external_id` to be ignored, never updated, so that my edits are never overwritten. 34. As a Person, I want ingest to drop Transactions outside the Account's tracked window, so that handed-over or pre-tracking history doesn't pollute Budgets. 35. As a Person, I want ingest to fill `occurred_on` from `posted_on` (`dated_by = posted`) when the source gives no purchase date, so that every Transaction has a best-known date. 36. As a Person, I want to correct `occurred_on` on an imported Transaction within `posted_on − 31 d … posted_on` (setting `dated_by = manual`), so that a purchase lands in the right budget month. 37. As a Person, I want Transactions with `dated_by = posted` and `posted_on` on days 1–5 of a month flagged for `date_review`, filterable on the list and counted in the previous month's summary, so that I catch purchases that probably belong to last month. 38. As a Person, I want a PATCH (even one re-sending the same date) to clear `date_review`, so that confirming a date is one call. 39. As a Person, I want to create, edit, and delete manual Transactions freely, so that cash and corrections fit in the ledger. 40. As a Person, I want only the Category, note, and (within the window) `occurred_on` editable on imported Transactions, so that source facts stay trustworthy. 41. As a Person, I want deleting an imported Transaction to dismiss it (hidden from Budgets, `external_id` kept), so that a re-import never brings it back. 42. As a Person, I want Categories of kind `expense | income | transfer`, as Household or Personal, with create, rename, archive, merge, and promote, so that I can reshape my Categories as my budget matures. 43. As a Household member, I want Household Categories to be usable on my Personal Transactions too, so that shared Categories like Groceries work everywhere. 44. As a Person, I want categorizing a Transaction by hand to create or update my Payee mapping, and ingest to apply mappings (Personal first, then Household, for Personal Accounts), so that categorization learns from me. 45. As a Person, I want `categorized_by = manual | learned` on each Transaction, and filters for uncategorized and learned, so that I can review what hAPI guessed. 46. As a Person, I want to list and delete Payee mappings, so that I can undo a bad lesson. 47. As a Person, I want one Budget per owner (the Household's over Household Accounts, mine over my Personal Accounts) with a standing expected income, so that each owner plans its own money. 48. As a Person, I want Targets per Category (monthly, quarterly, or annual, effective from a month, with old Targets kept), so that past months recompute correctly after I change a Target. 49. As a Person, I want Categories with a longer-than-monthly Target to be Banked, carrying unspent Allocations forward (optionally from an opening banked balance) and going visibly negative when overdrawn, so that annual bills are saved for month by month. 50. As a Person, I want to record Moves between Categories within a month without changing the month's total, so that I can rebalance mid-month. 51. As a Person, I want `budgets/{id}/months/{YYYY-MM}` to show, per Category, the Allocation, spent, remaining, and banked balance, plus unassigned, expected vs actual income, and a rebalance hint, so that one call tells me where the month stands. 52. As a Person, I want unassigned money reported but never enforced, so that a half-finished rebalance never errors. 53. As a Person, I want positive amounts in expense Categories to offset spending, and transfer Transactions to be excluded from spending, so that refunds, reimbursements, and card payoffs don't distort the Budget. 54. As a Person, I want months never locked and summaries recomputed on read, so that late posts land in the right month automatically. ### SimpleFIN importer Bot 55. As the Owner, I want a SimpleFIN Bot that runs every 6 hours in-cluster over a 14-day window and ingests the joint Capital One and Fulton Accounts, so that the Household ledger fills itself. 56. As the Owner, I want the Bot to map SimpleFIN account ids to Financial Account ids from its SOPS secret and skip unmapped accounts with a warning, so that a newly linked bank account can't leak into the wrong Account. 57. As the Owner, I want the Bot to exit non-zero on a SimpleFIN transport error, a non-2xx, a non-empty `errors` array, or a failed ingest, so that a broken run is never silent. 58. As the Owner, I want a clean run to ping a Kuma push monitor (13 h window), so that I hear about imports stopping even if the whole cluster is down. 59. As the Owner, I want the Bot to talk to hAPI only over HTTP through the in-cluster Service with its own Token (Household grant `finance:write`), so that it's an ordinary Bot and an edge outage doesn't stop imports. ### Fitness 60. As a Person, I want to log a whole Workout (date, optional start and duration, note, ordered entries of Sets or one cardio effort) in one POST, so that a Shortcut or script can record a session in one call. 61. As a Person, I want Sets with reps, `load_g`, `duration_s`, optional RPE, and a warmup flag, so that I can record strength, bodyweight, and timed work faithfully. 62. As a runner, I want a run to be a Workout with one cardio entry (`duration_s`, optional `distance_m` and `avg_hr_bpm`, with pace computed on read), so that cardio needs no separate model. 63. As a Person on flaky gym wifi, I want Workout and Measurement POSTs with a repeated `external_id` to return `200` with the existing record, so that retries never double-log. 64. As a Person, I want to replace a Workout whole with PUT, patch its top-level fields, or hard-delete it, so that fixing a transcription error is simple. 65. As a Person, I want to list Workouts filtered by date range and Exercise, sorted by `performed_on` then `started_at`, so that I can review my training. 66. As a Household member, I want a shared Household Exercise catalog (seeded by migration) plus my own Personal Exercises, so that we share common movements but I can add my own. 67. As a Person, I want Exercise kinds (`strength | bodyweight | timed | cardio`) frozen once used, merge limited to the same kind, promote one-way to Household, and hard delete only while unused, so that history never becomes inconsistent. 68. As a Person, I want `exercises/{id}/history` to show my past Sets or efforts and my best non-warmup Set by load and by reps, computed on read, so that I can see progress without stored records going stale. 69. As a Person, I want to record Measurements (body weight, body fat %, waist, chest, arm, thigh) as SI integers with a date, list them by kind and date range, and patch or delete them, so that I can track my body over time. 70. As a Person, I want all my Workouts and Measurements to be Personal data, invisible to the Owner and to other Household members, so that body data stays private. ### Maintenance 71. As a Household member, I want Assets (name, location, make, model, serial/VIN, installed, warranty, notes) for the home, its equipment, vehicles, and digital systems such as the hAPI cluster, so that we have one record of what we keep up. 72. As a Household member, I want an optional meter (distance or duration) on an Asset, settable only while it has no Readings, and Readings with a date and SI value, so that usage-based upkeep (oil every 5,000 mi) works. 73. As a Household member, I want recurring Tasks that are floating (an interval after the last Service) or fixed (a restricted RRULE with a start date), with an optional usage interval, so that every kind of upkeep rhythm fits. 74. As a Household member, I want each Task response to carry computed `due_on`, `due_at_meter`, and `status: ok | due | overdue | snoozed`, due on whichever comes first, so that "what's due" is always current without stored state. 75. As a Household member, I want `GET /tasks?due_before=…&status=…`, so that one call answers "what needs doing". 76. As a Household member, I want to snooze a Task without moving its schedule, archive it to stop it coming due, and delete it only while it has no Services, so that history is never lost. 77. As a Household member, I want to record a Service (done on a date, optionally fulfilling a Task and/or concerning an Asset, with `done_by`, note, cost in cents, meter value), so that the work history is complete and floating Tasks reset. 78. As a Household member, I want one-off past work to be a standalone Service, and no future one-off to-dos to exist, so that Maintenance never drifts into a to-do list. 79. As a future HA Bot, I want Services and Readings to accept an `external_id` (unique per Household) for idempotent creation, so that automated Readings can be retried safely. 80. As a Person who isn't a Household member, I want no access to Maintenance, so that Household property stays Household business. ### Smart home 81. As a Household member or Bot with `smart_home:write`, I want to create a Job naming a `hapi_*` HA script plus variables (≤16 KB), optionally with `not_before` and `expires_at` (default 1 h), so that I can queue a house action from anywhere. 82. As a client, I want an optional `external_id`, unique per creating Principal, to make Job creation idempotent (`200` on repeat), so that retries don't run an action twice. 83. As Home Assistant, I want `GET /v1/smart_home/jobs/next` to hand me the oldest eligible Job (FIFO by `not_before` or creation time) under a 2-minute lease, so that I can poll every 15–30 s with a built-in `rest` sensor. 84. As Home Assistant, I want a Job delivered 3 times without a result to become `failed (no_result)`, so that one broken Job can't stall the queue. 85. As Home Assistant or a Household member, I want `POST /jobs/{id}/result` with `{status, error?, response?}` to be the single way to finish a pending Job (first result wins, later ones get `409`), so that a Job can be closed by HA or by hand, with Recorded by showing who. 86. As a Household member, I want to list Jobs newest first, filtered by status, script, `recorded_by`, and created-at range, and to get one with its result and attempt count, so that I can see what the house did. 87. As a Household member, I want to cancel a pending Job (no PATCH; cancel and recreate instead), so that a queued action can be withdrawn. 88. As a Household member, I want a query Job's `response` to carry state back from HA, so that I can read house state through hAPI with ~30 s latency. 89. As the Owner, I want hAPI to record HA's last poll, so that a stalled bridge shows up in health and metrics. 90. As the Owner, I want a reference HA package (rest sensor, automation, rest_command) kept in this repo, so that wiring HA to hAPI is copy-paste. ### Scheduled work and Notifications 91. As the Owner, I want `hapi jobs sweep` every 15 minutes to mark past-expiry pending Jobs `expired`, purge finished Jobs after 90 days, and purge delivered Notifications after 180 days, with reads deriving `expired` in the meantime, so that correctness never depends on the sweep's timing. 92. As a Household member, I want a Household Notification once when a Task enters its `lead_days` and once when it goes overdue, per due occurrence, so that upkeep isn't forgotten and I'm not nagged. 93. As a Household member, I want a Household Notification when a Job ends `failed` or `expired`, so that I know a queued action didn't happen. 94. As a Household member, I want a Household Notification when a Household Budget Category goes into the red (for a Banked Category, when its banked balance goes negative), refiring only after it recovers, so that overspending is caught within the hour. 95. As a Person, I want a Notification 30 and 7 days before my Token expires (the Owner gets them for Bot Tokens), so that nothing breaks silently at expiry. 96. As a Person, I want Notifications to carry only a short title and a link, never amounts, balances, or Measurements, so that push providers see nothing sensitive. 97. As the Owner, I want checks to only write Notifications and a single `hapi notify deliver` (every 2 min) to publish them, using the Notification id as ntfy's sequence id and giving up after 24 h, so that an ntfy outage loses nothing and never double-pushes. 98. As the Owner, I want Household scheduled work to run as a built-in, tokenless `scheduler` Bot with Owner-given Household grants, and Personal work to run per Person and read-only, so that scheduling never needs elevated credentials. 99. As the Owner, I want calendar-based CronJobs to use the Household timezone from one setting, so that "daily at 08:00" means local time. ### Platform: network, delivery, secrets 100. As anyone on the internet, I want to reach only `hapi.bobbypalko.com:443` (TLS 1.3, IPv4), so that the attack surface is one authenticated API. 101. As the Owner, I want Envoy Gateway to enforce edge limits (1 MiB bodies, ~20 req/s per IP, ~50 connections per IP, header and timeout limits, HSTS), so that the only shield in front of hAPI is strong. 102. As the Owner, I want certificates issued by Let's Encrypt over DNS-01 through a delegated `acme.bobbypalko.com` zone and pinned by CAA to our ACME account, so that a leaked DNS token can neither touch the main zone nor get certificates for us. 103. As the Owner, I want Kubernetes and Talos APIs, Grafana, metrics, the database, and `:8081` reachable only over the management tailnet or the VPC, so that nothing administrative is public. 104. As the Owner, I want every green merge to `main` to build, scan, push a digest-pinned image, and commit the digest so Flux deploys it within a minute, so that shipping is merging. 105. As the Owner, I want migrations to run as a digest-named Job the app waits on, forward-only and backward-compatible, so that a failed migration stops the rollout while old pods keep serving. 106. As the Owner, I want rollback to be `git revert` of the digest bump, so that recovery uses the same path as deployment. 107. As the Owner, I want all cluster secrets SOPS+age-encrypted in git, mounted as files (never env vars), with gitleaks and a SOPS check in CI, so that the public repo never holds a plaintext secret. 108. As the Owner, I want `hapi_app` (DML only, subject to RLS), `hapi_migrator` (owner), and `hapi_backup` (read-only `BYPASSRLS`) as separate credentials mounted only where needed, so that a compromised app pod can't change the schema or bypass RLS. 109. As the Owner, I want `hapi db bootstrap` to idempotently create the database and roles from the SOPS passwords, with the `akmadmin` password pasted in at run time, so that the database can be recreated from git plus one secret. 110. As the Owner, I want `hapi db breakglass --reason` to publish a priority-5 Household alert first (refusing to start if the alert fails) and log every statement, so that emergency access is never invisible. ### Observability, backup, hardening 111. As Uptime Kuma (a Bot with the `health` Scope), I want `GET /v1/health` to report `ok | degraded | down` with only check names (`db`, `schema` critical; `ha_bridge`, `job_backlog` non-critical), so that I can alert on reachability and health without leaking detail. 112. As the kubelet, I want unauthenticated `/livez`, `/readyz`, and `/metrics` on an internal `:8081` that the Gateway never routes, so that probes work without breaking "no anonymous public endpoints". 113. As the Owner, I want structured JSON logs (with `request_id` and `principal_id`, Personal data redacted) and Prometheus metrics (no `principal_id` labels) collected into in-cluster VictoriaLogs and VictoriaMetrics, so that I can debug without data leaving the cluster. 114. As the Owner, I want each failure mode to have exactly one alerting owner (Kuma, Flux, vmalert, Watchdog) publishing to Owner-only `ops` / `ops-urgent` ntfy topics, so that platform alerts work even when hAPI is down. 115. As the Owner, I want a daily `hapi db backup` that verifies the dump's table of contents, encrypts it to a backup-only age recipient, and uploads it to an Object Lock (compliance, 35 d) bucket, so that a compromised cluster can neither read nor delete backups. 116. As the Owner, I want an off-account puller (on my PC for now) that copies backups immutably and prunes to 90 dailies, 3 years of monthlies, and 1 year of audit exports, so that losing the Linode account doesn't lose the data. 117. As the Owner, I want `hapi db restore` to run in a pod with the backup key pasted in at run time, so that restores work against a VPC-only database without the key ever being stored. 118. As the Owner, I want default-deny network policies, Pod Security `restricted`, admission rules (images from Gitea's registry or pinned by digest; read-only rootfs and no SA token in `hapi`/`bots`), and Kubernetes audit logs kept 1 year with an alert on exec or a human Secret read, so that the cluster is hardened with built-ins only. 119. As the Owner, I want a "hAPI cluster" Maintenance Asset carrying a monthly "Upgrade the cluster" Task and a 6-monthly "Rehearse disaster recovery" Task, so that hAPI reminds me to keep hAPI healthy. 120. As the Owner, I want a full disaster-recovery drill (rebuild the cluster from code in an empty project, then restore from a pulled dump) before go-live, so that recovery is proven, not assumed. ### Developer experience 121. As a developer, I want `just dev/test/lint/migrate` recipes with the app on the host and Postgres 18 in Docker Compose, so that local dev mirrors prod's database. 122. As a developer, I want pre-commit and CI to run Ruff, pyright strict, import-linter, and gitleaks, so that style, types, module boundaries, and secrets are checked before review. 123. As a developer, I want OpenAPI docs off in prod but exported as a CI artifact, with each route's required Scope visible in it, so that clients have a contract without exposing docs publicly. ## Implementation Decisions ### Application shape (#51) - **Python 3.14 + uv**, one `pyproject.toml`, Ruff (including `DTZ`) + pyright strict, `just`, pre-commit, Renovate (auto-merges dev tooling only). - **Async end to end:** async SQLAlchemy 2 with typed `Mapped[]`, separate Pydantic v2 API schemas, async outbound HTTP. - **Modules:** a shared `platform` package (config, db/session with principal context, auth, errors, logging, pagination, health, metrics, CLI scaffolding, Notifications) and one package per domain: `finance`, `fitness`, `maintenance`, `smart_home`. The domain is named **Maintenance**, superseding the `home_maintenance` name in #51. Each domain has models / schemas / service / router. Domains may import `platform` and only other domains' public `service` API. import-linter enforces this, and also forbids `bots/` from importing `hapi.*`. - **One Postgres database `hapi`, one schema per domain** (plus a platform schema for Principals, Tokens, grants, Bindings, Notifications). There is a single linear Alembic history with a strict constraint naming convention, run only by `hapi migrate`. - **Owner mixin:** every domain table carries `owner` (a Person id or the Household) plus Recorded by (created-by and last-changed-by Principal). Principals are never hard-deleted. - **Config:** pydantic-settings, `HAPI_` prefix, secrets read from a mounted `secrets_dir` (never env vars), fail fast at startup. The Household timezone is one setting. - **Runtime:** one uvicorn process per pod serving the API on `:8000` and probes/metrics on `:8081` in the same event loop. uvicorn trusts `X-Forwarded-For` only from the Gateway pod range. Graceful shutdown: `/readyz` fails first, then a ~5 s drain. - **Image:** multi-stage uv builder → `python:3.14-slim` pinned by digest, non-root, read-only rootfs, amd64, with `postgresql-client-18` for dump/restore/breakglass. - **API conventions:** `/v1/<domain>/<things>/{id}` flat resources; RFC 9457 errors with `code` + `request_id`; UUIDv7 ids generated in the app; `timestamptz` in UTC with RFC 3339 offsets; calendar concepts as `date` interpreted in the Household timezone; cursor pagination `{items, next_cursor}` with `limit` default-capped at 100; idempotent creates via `external_id` returning `201` on create and `200` with the existing record on repeat. OpenAPI UI and JSON are disabled in prod and exported in CI. #51 also mentioned unversioned `/healthz` and `/readyz`; ADR-0009 supersedes that with `:8081` `/livez` and `/readyz` plus authenticated `/v1/health`. ### Auth and authorization (ADR-0005, ADR-0004 as amended) - **Credential:** opaque Token `hapi_<public-id>_<secret>` with a 256-bit secret, stored as SHA-256, looked up per request on the request's pooled connection. Credentials carry `kind = api_token`, so a future `session` kind changes nothing else. Expiry defaults to 365 d, and `--no-expiry` is for Bots only. `last_used_at` is written at most about once an hour. - **Principal context:** each request transaction runs `SET LOCAL hapi.principal_id` to the authenticated Principal (Person or Bot). RLS policies read it as `nullif(current_setting('hapi.principal_id', true), '')`. - **RLS (`ENABLE`, not `FORCE`) on every owner-mixin table:** - Personal tables allow the owner, or a Bot holding an active Binding from the owner for that domain. - Household tables allow an active Household member, or a Bot with a Household grant for that domain. - `USING` checks the read Scope and `WITH CHECK` checks the write Scope. - Finance's cross-owner rule (Household Categories usable on members' Personal Transactions) and Fitness's (Household Exercises referenced from Personal Workouts) are expressed as reads of Household rows, not as writes across owners. - **App-level guard:** routes declare `require_scope(...)`, so a missing Scope is a clean `403` and appears in OpenAPI. A record the caller can't see is `404`. All Token failures get an identical `401`. - **Scopes:** `finance|fitness|maintenance|smart_home` × `read|write` (write implies read), plus `health`. - **Public API for Persons:** own Tokens (list, revoke), Bindings (grant, list, change, revoke), and Bots (list). Nothing else about Principals is on HTTP. - **Audit:** auth decisions and grant/Binding/Token changes are structured log events. Secrets are never logged. - **Built-in `scheduler` Bot:** created by migration, can never hold a Token, and receives Household grants from the Owner like any Bot. ### Admin CLI (`hapi`) One Typer-style entry point in the app image, run in-pod. It is the only path for Owner administration: - `principal` (create Person or Bot, deactivate, set Household membership, transfer ownership) - `token` (issue, list, revoke) - `grant` (Household grants) - `person remove` (export, then delete Personal data, per Person under RLS) - `migrate` - `db bootstrap | breakglass | backup | restore` - `jobs sweep` - `notify tasks | jobs | budget | tokens | deliver` The app-side commands connect as `hapi_app`. `migrate`, `bootstrap`, `breakglass`, and `restore` use migrator credentials mounted only into their pods. `backup` uses `hapi_backup`. Each housekeeping run uses a connection pool of 1. ### Finance (#59, amended by #67) - **Entities:** - Financial Account: name, type `checking|savings|credit_card|cash`, institution, currency (USD only), owner, `tracked_from`, `tracked_until`, archived. No balances. - Transaction: account, signed `amount_minor`, `occurred_on`, `posted_on`, `payee_raw` + normalized payee, `external_id` unique per Account, Category, `categorized_by manual|learned`, `dated_by source|posted|manual`, note, `dismissed`, Recorded by. Posted Transactions only, no pending. - Category: name, kind `expense|income|transfer`, owner, archived. - Budget: one per owner, expected income. - Target: Budget × Category, amount, period `monthly|quarterly|annual`, effective-from month, optional opening banked balance. History is kept. - Move: Budget, month, from, to, amount. - Payee mapping: owner, normalized payee → Category. - **Ownership:** Transactions inherit their Account's owner. Financial Accounts and Transactions never change owner (this narrows ADR-0001's one-way move). Categories can be promoted. The Household Budget counts Household Accounts only, and a Person's Budget counts that Person's Personal Accounts only. - **Ingest:** `POST /v1/finance/transactions/ingest` with `{financial_account_id, transactions[]}`, batch size capped by the app. Per item: - The result is one of `created|duplicate|dismissed|outside_tracked_window`. - A known `external_id` is ignored, never updated. - If `occurred_on` is absent, it's copied from `posted_on` with `dated_by = posted`. - Payee mappings are applied (Personal Accounts check Personal mappings, then Household ones; Household Accounts check only Household ones). - Bots never set Categories. - **Editing:** - Manual Transactions are fully editable and deletable. - On imported Transactions, only Category, note, and `occurred_on` (within `posted_on − 31 d … posted_on`) are editable. Deleting one dismisses it. - Manual categorization creates or updates the owner's Payee mapping. - `date_review` is derived: `dated_by = posted` and `posted_on` falls on days 1–5. Any PATCH clears it. - **Budget math (computed on read, months never locked, month decided by `occurred_on`):** - Allocation = the Target's monthly share ± Moves. - Unassigned = expected income − Σ Allocations, reported but not enforced. - Positive amounts in expense Categories offset spending, and transfer Categories are excluded. - Ordinary leftovers don't carry. Banked balances accrue and may go negative. - The rebalance hint is set when at least one Category is in the red and another still holds money. - The month summary also carries expected vs actual income and the previous month's `date_review` count. - **Endpoints:** - `accounts`: CRUD, archive. - `transactions`: list with filters (account, owner, month, Category, uncategorized, `categorized_by`, `date_review`), create, PATCH, DELETE/dismiss; `transactions/ingest`. - `categories`: CRUD, archive, `merge`, `promote`. - `payee-mappings`: list, delete. - `budgets`: per owner, with `targets`, `moves`, and `months/{YYYY-MM}`. ### Fitness (#60) - **Entities:** - Exercise: name, owner, archived, kind `strength|bodyweight|timed|cardio`. - Workout: `performed_on`, `started_at?`, `duration_s?`, note, `external_id?` unique per Person, ordered entries. Each entry has `exercise_id` and either `sets[]` (`reps`, `load_g`, `duration_s`, `rpe?`, `warmup`) or `cardio{duration_s, distance_m?, avg_hr_bpm?}`, matching the Exercise kind. - Measurement: kind from a fixed enum, integer value in base SI units, `measured_on`, `measured_at?`, `external_id?`. - **Ownership:** Workouts and Measurements are Personal data. Exercises are Household (seeded by a data migration) or Personal. Non-members see only their own Personal Exercises. - **Rules:** - An Exercise's kind is frozen once used. - Merge only within one kind: entries move, then the source is archived. - A Person can't merge another Person's Personal Exercise. - Promotion is one-way. - Hard delete only while unused. - Pace and bests are computed on read. Warmups are excluded from bests. - **Endpoints:** - `exercises`: CRUD, archive, `merge`, `promote`, `history`. - `workouts`: list (date range, Exercise filters), whole-body create, GET, PUT (full replace), PATCH (top-level), DELETE (hard). - `measurements`: list (kind, date range), create, PATCH, DELETE. ### Maintenance (#61, amended by ADR-0015) - **Everything is Household data.** Non-members have no access. - **Entities:** - Asset: name, location?, make?, model?, serial?, `installed_on?`, `warranty_until?`, notes, archived, optional meter unit `distance|duration`. The meter is settable only while the Asset has no Readings. - Reading: Asset, `read_on`, `value` (m or s), `external_id?`. - Task: title, `asset_id?`, note, `lead_days?`, archived, `snoozed_until?`; schedule = floating (interval count + unit) or fixed (restricted RRULE + start date); optional usage interval. - Service: `done_on`, `task_id?`, `asset_id?`, title (required without a Task), `done_by?` (a Person), note, `cost_cents?`, `meter_value?`, `external_id?`. - `external_id` is unique per Household on Services and Readings. - **Restricted RRULE:** `FREQ`, `INTERVAL`, `BYMONTH`, `BYMONTHDAY`, `BYDAY` with ordinals, and `BYSETPOS` only. No `COUNT` or `UNTIL`. Evaluated with `dateutil.rrule`. - **Due computation (on read, nothing stored):** - Due on whichever comes first: the calendar date or the usage threshold (judged against the latest Reading, no projection). - The first due date comes from the latest Service if one exists, otherwise creation date + one interval. A fixed Task's first due date is the rule's next occurrence. - Status is `ok|due|overdue|snoozed`, with "due" starting `lead_days` before the due date. - Snooze hides the Task without moving the schedule. - **Endpoints:** - `assets`: CRUD, archive, nested `readings` (list, create, PATCH, DELETE). - `tasks`: CRUD, archive, snooze, plus `?due_before=&status=`. - `services`: list (Task, Asset, date range), create, PATCH, DELETE. - **Seed data:** none for the domain in general. The "hAPI cluster" Asset with its "Upgrade the cluster" (monthly) and "Rehearse disaster recovery" (6-monthly, fixed RRULE) Tasks is created by the Owner during go-live, not by a migration. ### Smart home (ADR-0006, #62) - **Job:** Household data. - Fields: `script` (must match `hapi_[a-z0-9_]+`), `variables` (≤16 KB JSON), `not_before?`, `expires_at` (default `not_before` or creation + 1 h), `external_id?` unique per creating Principal, status `pending|succeeded|failed|expired|cancelled`, attempts, lease-until, result `{status, error?, response?}`, Recorded by. - `expired` is derived from `expires_at` until the sweep persists it. - **Delivery:** - `GET /v1/smart_home/jobs/next` returns the oldest eligible Job (FIFO by `not_before` or creation time, not leased, not expired) and leases it for 2 minutes, incrementing attempts. - A Job leased 3 times with no result becomes `failed` with `no_result`. - Every call records HA's last-poll time. - **Finishing:** - `POST /jobs/{id}/result` is accepted from any Household member or any Bot with `smart_home:write` while the Job is pending, leased or not. - The first result wins, and later ones get `409`. - Finished Jobs are immutable. - **Other endpoints:** list (newest first; status, script, `recorded_by`, and created-at filters), GET, and `cancel` on pending Jobs. There's no PATCH. - **Scopes:** `smart_home:write` both creates and consumes Jobs. A Bot needs `smart_home:read` to read them. HA is the Bot `home-assistant`, with a Household grant of `smart_home:write`. - **Internal API:** the module exposes an internal `create_job` service function for future domain use. Nothing calls it in v1. - **HA reference package:** rest sensor, automation, and rest_command, kept in this repo and copied into HA by hand. The `hapi_*` scripts live in the HA config repo. ### Notifications (ADR-0012, ADR-0013) - **Record:** - Fields: recipient (Person or Household), `kind`, `dedupe_key` (unique with `kind`), `title`, `body`, priority 1–5, link?, `created_at`, `delivered_at`, `attempts`. - Content carries no domain values. - Visibility follows ownership: a Person's Notification is Personal data, the Household's is Household data. - There is no Notifications API in v1. - **Checks** (all run as `scheduler`, write-only, reading Household and platform data): | Check | Recipient | Fires when | Schedule | |---|---|---|---| | `tasks` | Household | once on entering `lead_days`, once on overdue, per due occurrence | daily 08:00 | | `jobs` | Household | a Job ends `failed` or `expired` | every 15 min | | `budget` | Household | a Household Budget Category goes into the red this month (Banked: its banked balance goes negative); refires only after it recovers | hourly | | `tokens` | the Token's Person, or the Owner for Bot Tokens | 30 and 7 days before expiry | daily | - **Delivery:** - `hapi notify deliver` runs every 2 min and publishes pending Notifications oldest first to `hapi-p-<person-id>` or `hapi-household` on `notify.bobbypalko.com`, using hAPI's publish-only ntfy token. - The Notification id is ntfy's sequence id, so retries don't double-push. - It gives up after 24 h, and vmalert alerts on Notifications that old. - **Priorities:** - 4: Task overdue. - 3: Job failed or expired; Token expiring in 7 days. - 2: Task due soon; budget overspend; Token expiring in 30 days. - 5: breakglass, published synchronously by `hapi db breakglass` before the session opens. It fails closed. ### Health and metrics (ADR-0009) - **`:8081`:** - `/livez` is constant. - `/readyz` passes after startup and fails on SIGTERM. It never checks the DB. - `/metrics` comes from prometheus-client: requests by route template, method, and status; latency; DB pool usage; Job depth, age, and failures; seconds since HA's last poll; auth failures by reason. No `principal_id` labels. - **`GET /v1/health`** needs the `health` Scope. - Critical checks: `db` (`SELECT 1` through the app pool) and `schema` (at the expected Alembic head). Any failure means `down` with HTTP 503. - Non-critical checks: `ha_bridge` (no poll for 5 min) and `job_backlog` (oldest pending Job too old). Any failure means `degraded` with HTTP 200. - Bodies carry only check names and `ok`/`fail`. ### SimpleFIN Bot (ADR-0011, #67) - A separate package and image in the repo, with no `hapi.*` imports. It's a CronJob in `bots` every 6 h with `concurrencyPolicy: Forbid`. - Each run fetches accounts with `start-date = now − 14 d` and ingests each mapped account, one batch per account. - **Field mapping:** `external_id` = SimpleFIN `id`, `posted_on` = `posted` as a UTC date, `amount_minor` from the decimal `amount`, `payee_raw` = `description`. It never sends `occurred_on`. - **Exit status:** - Non-zero on a transport error, a non-2xx, a non-empty `errors` array, or any failed ingest. - Unmapped accounts are only a warning. - A clean run pings the Kuma push URL. - **Config:** one SOPS secret `bot-simplefin` (Token, Access URL, account mapping, Kuma push URL), mounted as files. - **Calls:** the in-cluster hAPI Service. Principal `simplefin-importer` with a Household grant of `finance:write`. - **To check during the build:** SimpleFIN's daily request quota. ### Infrastructure and delivery (ADR-0002, ADR-0003, ADR-0007, ADR-0008, ADR-0010, ADR-0014, ADR-0015) - **Cluster:** OpenTofu (encrypted state in Object Storage) provisions Talos in `us-iad`: - 1 control-plane node + 2 `g6-standard-2` workers in a spread placement group, joined to the VPC. - Nodes have public IPv4 with a deny-all Cloud Firewall except Tailscale UDP 41641 and the VPC. - Talos LUKS on STATE and EPHEMERAL. Every node joins the management tailnet (Tailnet Lock on) with pre-signed keys. - Tofu installs only Cilium (WireGuard, tunnel mode, `gatewayAPI.enabled=false`) and the Linode CCM, with its own narrow token. - Tofu also owns the reserved IPv4, the NodeBalancer firewall (443 only), the DNS records (`A`, the `_acme-challenge` CNAME, the `acme.` delegation, CAA), the backup bucket (Object Lock), the Managed DB, and the CI runner VM. - **Database:** Managed PG 18, Shared 2 GB, 1 node, VPC-only allowlist, `verify-full`, scram-sha-256. - Roles: `hapi_migrator`, `hapi_app`, `hapi_backup`. - Connection budget: app pods (with surge) × 10 + concurrent CronJobs × 1 + ~6 ≤ 46. - **Edge:** - CCM NodeBalancer in TCP mode with Proxy Protocol v2 and `throttle: 20` → Envoy Gateway (2 replicas, PDB). - Envoy enforces TLS 1.3, h2 and http/1.1, 16 KiB headers, ~50 connections per IP, 30 s request and 60 s idle timeouts, ~20 req/s burst 100 per IP, 1 MiB bodies, and HSTS. - One Gateway and one HTTPRoute to `:8000`. - cert-manager with Let's Encrypt over DNS-01, using the Linode webhook with `cnameStrategy: Follow` and a restricted-user token on `acme.bobbypalko.com` only. The ACME account key is in SOPS. CAA is pinned to `accounturi`. - **Delivery:** - Gitea Actions on a dedicated runner VM. PRs run lint, pyright, import-linter, tests, the image build, a smoke test, the OpenAPI export, Trivy, gitleaks, and the SOPS check. - On `main`, CI pushes the image to Gitea's registry and commits the digest. Bump commits are path-filtered. - Flux polls anonymously every minute with prune and drift correction. - The repo layout is `deploy/clusters/prod`, `deploy/infrastructure`, and `deploy/apps/hapi`. - The `hapi-migrate` Kustomization (digest-named Job) is something the app `dependsOn`. - The app runs 2 replicas with surge 1 and unavailable 0, a PDB `minAvailable: 1`, and spread across workers. - Failure notifications go to ntfy `ops`. - **Secrets:** - SOPS + age with a single offline prod key. `.sops.yaml` encrypts only `data`/`stringData` in `deploy/**/*.sops.yaml`. - Secrets are mounted as files. `hapi-db-app` and `hapi-db-migrator` are split, and the backup role has its own secret. - No workload ServiceAccount can read Secrets. Owner roots live in Vaultwarden plus an offline copy. - **Observability:** - VictoriaMetrics and VictoriaLogs (30 d), vmagent, a Vector DaemonSet, an event exporter, Grafana (login required, port-forward only), and vmalert. - Breakglass and Kubernetes audit events are kept 1 year and exported daily with backups. - A Watchdog pushes to Kuma. - One generic vmalert rule fires when any CronJob hasn't succeeded within twice its interval. - **Backups:** - `hapi db backup` runs daily at 03:00 Household time: `pg_dump -Fc` → `pg_restore --list` check → age (backup-only recipient) → the Object Lock bucket (35 d), plus the previous day's audit export. - The off-account puller script (`rclone copy --immutable` plus pruning, with a `just` recipe) runs as a systemd user timer on the Owner's PC. - Kuma push monitors: 26 h for the backup job, 8 d for the puller. - `hapi db restore` supports path A (PITR fork) and path B (restore from our own dump). - **Hardening:** - Default-deny CiliumNetworkPolicies in every owned namespace (`hapi`, `bots`, `gateway`, `envoy-gateway-system`, `monitoring`, `monitoring-node`, `cert-manager`, `flux-system`), with `toFQDNs` and `toCIDR` allows next to each component. - PSA `restricted` everywhere except `monitoring-node` (`privileged`). - Two ValidatingAdmissionPolicies, set to Deny. - Kubernetes audit policy at Metadata level, with an `ops` alert on `pods/exec` or a human reading a Secret. - Versions pinned in `infra/`, Renovate PRs, security patches within 14 days, and a cluster-upgrade runbook. - **Runbooks to write during the build:** Flux install, DB bootstrap and password rotation, breakglass, ntfy user management (including offboarding), restore (paths A and B), and cluster upgrade. ## Testing Decisions - **What makes a good test:** it drives the system only through an external seam and asserts on what that seam returns or makes observable (HTTP responses, CLI exit codes and output, rows visible through the API, outbound HTTP calls to faked external systems). Tests don't reach into service internals, ORM models, or private helpers. Refactoring inside a module must never break a test. The database is never mocked. Only external systems (ntfy, SimpleFIN, Kuma, HA, which is just another HTTP client) are faked, at their HTTP boundary. - **Seam 1: the public HTTP API.** - pytest + pytest-asyncio drive the ASGI app through `httpx.AsyncClient` + `ASGITransport` against **real Postgres 18** via testcontainers. - The database is created by the same `hapi db bootstrap` and `hapi migrate` as prod. The app connects as `hapi_app` with RLS on, and each test rolls back its own transaction. - This seam covers every domain endpoint plus auth, Tokens, Bindings, health, idempotency, pagination, and error shapes. - **Every endpoint gets a wrong-Principal test** (wrong Person, wrong Bot, non-member, revoked Binding, read-only Scope attempting a write, deactivated Principal), asserting `401`/`403`/`404` as ADR-0005 specifies. - Computed-on-read behaviour (Budget month summaries, Banked carry-forward, `date_review`, Task due state and RRULE edge cases, Exercise history and bests, Job lease/attempt/expiry) is asserted through the API with controlled dates. The app takes a clock dependency that tests can pin. - **Seam 2: the `hapi` CLI.** - The CLI entry point is invoked in-process against the same Postgres, asserting on exit codes, output, and effects visible through Seam 1. - Covered: principal, token, grant, and member management; deactivation; ownership transfer; Person removal (export, then delete); `jobs sweep`; each `notify <check>` (correct recipient, dedupe, refire-after-recovery, no domain values in content); `notify deliver` against a fake ntfy (sequence id, retry, 24 h give-up); and `db breakglass` refusing to start when the alert publish fails. - `db backup` and `db restore` get a round-trip test against the test container (dump → list check → encrypt with a test age key → restore into a fresh database → same Alembic revision and row counts), with Object Storage faked. - **Seam 3: the SimpleFIN Bot's run entry point.** - SimpleFIN and hAPI are both faked at HTTP. - Asserted: field mapping (no `occurred_on`, UTC posted date, decimal → minor units), unmapped-account warning, non-zero exit on each failure class, and the Kuma ping only on a clean run. - One contract test runs the Bot against the real hAPI app from Seam 1, proving ingest results end to end. - **Static and structural checks in CI** (not seams, but required): - Ruff, pyright strict, import-linter (domain boundaries; `bots/` has no `hapi.*` imports), gitleaks, the SOPS-encryption check, and Trivy. - An **RLS coverage check**: every owner-mixin table has `relrowsecurity` set and is owned by `hapi_migrator`, never `hapi_app`. - The OpenAPI export. - **Infrastructure** (Tofu, Talos, Flux, network policies, admission policies) has no unit seam. It's verified by the CI image smoke test, by the build-time checks ADR-0010 and ADR-0014 list (restricted DNS token cannot edit the main zone; delegated subzone resolves; CCM copies annotations; `akmadmin` can create a `BYPASSRLS` role; the bucket key can't delete a locked version), and by the **go-live disaster-recovery drill**: rebuild in an empty Linode project, then restore path B from a pulled dump. - **Prior art:** none in the repo yet (greenfield). The conventions above come from the #51 resolution and ADR-0004's CI isolation rule. The first implementation issue should land the test harness (testcontainers + bootstrap + migrate + principal factories + a pinned clock) so every later issue inherits it. ## Out of Scope - A frontend, mobile apps, interactive login (passkeys, OIDC), cookies/CSRF/CORS. - Public signups, third-party OAuth, sharing outside the Household, guest access, and roles within the Household. - A staging environment, distributed tracing, and app-level or per-Principal rate limiting. - Deploying or backing up Uptime Kuma, ntfy, Home Assistant, or Gitea. HA config beyond the job bridge reference package and the `hapi_*` scripts in the HA config repo. - **Finance:** splits, balances and net worth, transfer-leg linking, ML categorization, a rule editor, pending Transactions, bill-due reminders, finer Finance Scopes (a v2 priority), multi-currency (never), spreadsheet migration, backfill, file (OFX/QFX/CSV) importers, Personal Account import (including Apple Card), and Personal-domain notification checks. - **Fitness:** templates, programs, goals, 1RM and PR feeds, wearable or historical import, daily aggregates, reminders, drop sets, supersets, tempo. Nutrition as a domain. - **Maintenance:** attachments, Finance cost linking, an HA runtime-Reading Bot, HA completing Tasks, and future one-off to-dos. - **Smart home:** a house-state store, hAPI-side automations and scenes, typed control endpoints, a script catalogue, recurring Jobs, domain-created Jobs, MQTT, and restricting results to the leasing Bot. - **Notifications:** preferences, read state, a Notifications API or inbox, channels other than ntfy, and quiet hours. - **Platform:** a worker Deployment, a task queue, or an outbox; PgBouncer; HA etcd or three control-plane nodes; IPv6; a backup ACME CA; commit and image signing; Kyverno; runtime detection; Trivy Operator; CIS scanning; the Cilium host firewall; least-privilege kubeconfigs; per-Person encryption; and etcd backups. ## Further Notes - This spec is the destination of the wayfinder map #44, and ADR-0001 through ADR-0015 are the authoritative record for platform decisions. Where this spec and an ADR disagree, the ADR wins and this spec should be corrected. - Domain detail comes from the resolutions on #51 (skeleton), #59 + #67 (Finance and the importer), #60 (Fitness), #61 (Maintenance, amended by ADR-0015), and #62 (Smart home). - **Suggested build order** for slicing into issues: 1. App skeleton and test harness. 2. Principals, Tokens, auth, and RLS. 3. Admin CLI. 4. Each domain, in any order. Smart home and Maintenance have no cross-domain dependencies. Finance ingest precedes the SimpleFIN Bot. 5. Health and metrics. 6. Notifications and CronJobs. 7. Infrastructure: Tofu/Talos, then Flux, edge, secrets, observability, backups, and hardening. 8. Go-live: the DR drill, then creating the "hAPI cluster" Asset and its two Tasks. - **Infrastructure work is mostly `ready-for-human` when sliced.** It touches the Owner's Linode account, Vaultwarden, DNS, and the management tailnet. App and Bot code is AFK-friendly. - **Verify-during-build items** that can force a decision change: the DNS-01 restricted token and subzone delegation (fallback: acme-dns), the CCM annotation passthrough, `BYPASSRLS` role creation on the managed DB, the locked-version delete test, and SimpleFIN's daily quota. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
bobby added the ready-for-agent label 2026-11-27 16:10:52 -05:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: bobby/hapi#72