Three real, already-researched planning docs from round 1 (ARCHITECTURE-2026-10-23.md, PLAN-2026-10-23-DEEP.md, STRATEGY-2026-10-23.md) that were sitting uncommitted in the working tree. Read in full and confirmed current, not stale scratch — committed verbatim as a point-in-time record of that round's research (deployment risk assessment, feature/API backlog, competitive positioning and growth moves), not rewritten for round 2.
135 lines
11 KiB
Markdown
135 lines
11 KiB
Markdown
# Ration — deep build plan (2026-10-23)
|
|
|
|
Internal build spec. No web/mobile frontend exists or is planned — this
|
|
project is backend/CLI/TUI by design (README). "Screens" below = TUI tabs
|
|
+ CLI subcommands, the project's actual UI surface.
|
|
|
|
## Screens (TUI, Bubble Tea — services/tui)
|
|
|
|
### Tenants — `services/tui/internal/view/tenants.go`
|
|
- Route: tab 1, `TabBar` index 0.
|
|
- Purpose: list all tenants + live balance/headroom.
|
|
- Elements: scrollable table (id, name, tier, balance, reserve floor,
|
|
headroom); `↑/↓`/`j/k` row nav; `enter`/`→` glyph drills into Cards
|
|
tab pre-filtered to selected tenant; no text labels on nav keys, just
|
|
the arrow glyphs already rendered by Bubble Tea's default key hints.
|
|
- Data: `LedgerCore.ListTenants` + `GetBalance` per row, polled (see
|
|
`state.go`).
|
|
|
|
### Deposits — `deposits.go`
|
|
- Route: tab 2.
|
|
- Purpose: incoming/late deposits per tenant.
|
|
- Elements: table (deposit id, tenant, amount, status, received_at);
|
|
late rows rendered in the TUI's existing warn color, no emoji/text
|
|
badge.
|
|
- Data: `LedgerCore.ListDeposits` / `ListLateDeposits`.
|
|
|
|
### Cards — `cards.go`
|
|
- Route: tab 3.
|
|
- Purpose: issued cards + limits per tenant.
|
|
- Elements: table (card id, tenant, limit, status); `+` glyph row
|
|
triggers `IssueCard` flow (not yet interactive — currently read-only,
|
|
remaining work below).
|
|
- Data: `Gateway.ListCards`.
|
|
|
|
### Activity — `activity.go`
|
|
- Route: tab 4.
|
|
- Purpose: live event feed (deposits, entries, agent decisions).
|
|
- Elements: append-only scrolling log, newest at bottom, auto-scroll
|
|
unless user has scrolled up (standard pager behavior).
|
|
- Data: `Gateway.StreamActivity` (server-streaming), via `stream.go`.
|
|
|
|
**Remaining**: Cards tab is read-only — no in-TUI `IssueCard`/
|
|
`AdjustCardLimit` form yet (CLI/API only). TUI/CLI/agent still dial
|
|
`ledger-core` directly in places, bypassing gateway's tenantauth
|
|
interceptor entirely (see Known gaps below) — no UI change fixes this,
|
|
it's a call-site wiring fix.
|
|
|
|
## CLI (`services/cli/cmd/ration`)
|
|
|
|
- `ration seed` (`seed.go`) — creates 3 demo tenants (small/medium/large).
|
|
No flags beyond global `--gateway-addr`.
|
|
- `ration simulate-deposit` (`simulate_deposit.go`) — flags: `--tenant`,
|
|
`--amount`, `--mark-late`. Calls `Gateway.SimulateDeposit`.
|
|
- `ration status` (`status.go`) — flag: `--tenant`. Prints balance,
|
|
cards, recent agent decisions. Calls `Gateway.GetBalance` (via ledger
|
|
client) + `ListCards` + `ListAgentDecisions`.
|
|
|
|
**Remaining**: no `ration issue-card` / `ration adjust-limit` subcommands
|
|
— `IssueCard`/`AdjustCardLimit` are only reachable via raw gRPC/REST
|
|
today, not the operator CLI.
|
|
|
|
## APIs
|
|
|
|
### `LedgerCore` (gRPC, proto/ledger.proto, services/ledger-core)
|
|
Internal-only (no gateway auth in front of a direct dial — see Known
|
|
gaps). Auth: none at this layer; relies on network-level trust + mTLS
|
|
when `*_MTLS_ENABLED=true`.
|
|
- `CreateTenant(CreateTenantRequest{name, tier}) → Tenant{id,name,tier,reserve_floor_minor_units,currency}`
|
|
- `GetTenant(GetTenantRequest{tenant_id}) → Tenant`
|
|
- `ListTenants(ListTenantsRequest{}) → ListTenantsResponse{tenants[]}`
|
|
- `RecordDeposit(RecordDepositRequest{tenant_id,amount_minor_units,currency}) → Deposit`
|
|
- `MarkDepositReceived(MarkDepositReceivedRequest{deposit_id}) → Deposit` — idempotent, no double-credit (verified by `deposit_received_credits_balance.rs`).
|
|
- `ListDeposits` / `ListLateDeposits(ListLateDepositsRequest{tenant_id}) → ListDepositsResponse{deposits[]}`
|
|
- `ApplyEntry(ApplyEntryRequest{tenant_id,kind,amount_minor_units,idempotency_key,memo}) → ApplyEntryResponse{entry,new_balance}` — the only money-moving path; validates reserve floor for DEBIT/HOLD, idempotent on `idempotency_key`, WAL-appended then SQLite-applied.
|
|
- `GetBalance(GetBalanceRequest{tenant_id}) → Balance{available,held,reserve_floor}`
|
|
- `ListEntries(ListEntriesRequest{tenant_id,page_token}) → ListEntriesResponse{entries[],next_page_token}`
|
|
- `CheckReserveFloor(CheckReserveFloorRequest{tenant_id,kind,amount_minor_units}) → CheckReserveFloorResponse{would_breach,headroom_minor_units}`
|
|
- `RecordAgentDecision(RecordAgentDecisionRequest{tenant_id,action,rationale,...}) → AgentDecision`
|
|
- `ListAgentDecisions(ListAgentDecisionsRequest{tenant_id}) → ListAgentDecisionsResponse{decisions[]}`
|
|
|
|
### `Gateway` (gRPC + REST facade, proto/gateway.proto, services/gateway)
|
|
Auth: `tenantauth` interceptor on unary RPCs, gated behind
|
|
`RATION_GATEWAY_REQUIRE_TENANT_AUTH` (default off). When on: calls
|
|
`Auth.VerifyAPIKey`/`VerifyJWT`, rejects `tenant_id` mismatch on any RPC
|
|
whose request carries a `tenant_id` field.
|
|
- `IssueCard` / `AdjustCardLimit` / `GetCard` / `ListCards` / `RationBridgeFunding` — same shapes as `CardIssuance` below, gateway is a thin pass-through.
|
|
- `SimulateDeposit(SimulateDepositRequest{tenant_id,amount_minor_units,mark_late}) → SimulateDepositResponse{deposit}`
|
|
- `StreamActivity(StreamActivityRequest{tenant_id}) → stream ActivityEvent{...}` — tenant_id optional/empty = all tenants, **not** interceptor-checked (streaming RPCs are out of interceptor scope — Known gap).
|
|
|
|
REST facade (`services/gateway/internal/httpapi`), hand-translated,
|
|
same auth as above:
|
|
- `POST /v1/cards` → `IssueCard`
|
|
- `GET /v1/cards/{card_id}` → `GetCard`
|
|
- `PATCH /v1/cards/{card_id}/limit` → `AdjustCardLimit`
|
|
- `GET /v1/tenants/{tenant_id}/cards` → `ListCards`
|
|
- `POST /v1/tenants/{tenant_id}/bridge-funding` → `RationBridgeFunding`
|
|
- `POST /v1/tenants/{tenant_id}/deposits/simulate` → `SimulateDeposit`
|
|
- `GET /v1/activity[?tenant_id=]` → `StreamActivity`, newline-delimited JSON
|
|
|
|
### `CardIssuance` (gRPC, internal-only, services/card-issuance)
|
|
- `IssueCard(IssueCardRequest{tenant_id,initial_limit_minor_units}) → Card{id,tenant_id,limit_minor_units,status}`
|
|
- `AdjustCardLimit(AdjustCardLimitRequest{card_id,new_limit_minor_units,reason}) → Card` — keys off `card_id`, no `tenant_id` field (tenantauth bypass, Known gap).
|
|
- `GetCard(GetCardRequest{card_id}) → Card` — same bypass.
|
|
- `ListCards(ListCardsRequest{tenant_id}) → ListCardsResponse{cards[]}`
|
|
- `RationBridgeFunding(RationBridgeFundingRequest{tenant_id,requested_minor_units,reason}) → RationBridgeFundingResponse{approved,granted_minor_units}` — real money decision, backed by `internal/bridge` rationing math over `internal/airwallex` (mock always on; `live.go` never exercised against a sandbox, blocked on an org-issued Airwallex credential — owner/hackathon blocker, not code).
|
|
|
|
### `Auth` (gRPC, internal-only, services/auth)
|
|
- `IssueAPIKey` / `VerifyAPIKey` / `RevokeAPIKey` — SHA-256-hashed secret, **in-memory store only** (lost on restart — Known gap).
|
|
- `MintJWT` / `VerifyJWT`.
|
|
- `IssueServiceCert(IssueServiceCertRequest{csr_pem}) → IssueServiceCertResponse{cert_pem}` — signs against an in-process CA; CA key itself is ephemeral-in-memory or bare on-disk PEM (Known gap, no HSM/rotation).
|
|
|
|
### `TenantRegistry` (gRPC, internal-only) — thin proxy: `CreateTenant`/`GetTenant`/`ListTenants` to `LedgerCore`.
|
|
|
|
### `WebhookIngestion`
|
|
- `StreamEvents(StreamEventsRequest{}) → stream NormalizedEvent` (gRPC, internal fan-out from an in-process channel bus).
|
|
- `POST /webhooks/airwallex` (plain HTTP) — HMAC-verified (`x-signature`/`x-timestamp`, 5-min replay window), token-bucket rate-limited, parses envelope, calls `LedgerCore.MarkDepositReceived` on match, publishes onto the event bus.
|
|
|
|
### `AuditLog` (gRPC, independent hash-chained mirror)
|
|
- `Append(AppendRequest{source_service,kind,ref_id,payload}) → AppendResponse{record}` — idempotent on `(source_service,kind,ref_id)`. `source_service` is overwritten with the verified mTLS peer CN when mTLS is on; falls back to the attacker-controllable request field when mTLS is off (Known gap, documented, not fixable without mandatory mTLS).
|
|
- `ListRecords(ListRecordsRequest{page_token}) → ListRecordsResponse{records[],next_page_token}`
|
|
- `VerifyChain(VerifyChainRequest{}) → VerifyChainResponse{ok,first_broken_index}`
|
|
- standalone `verify-chain` CLI tool, same logic, no live service needed.
|
|
|
|
## Features — status + what remains
|
|
|
|
1. **Ledger core (Rust, apply_entry)** — done, real, crash-safe (WAL + SQLite index + recovery), reserve-floor-enforced, idempotent. No remaining work in this pass.
|
|
2. **Audit-mirror failure counter (this pass)** — `services/ledger-core/src/metrics.rs`, `/metrics` on `LEDGER_CORE_METRICS_ADDR` (default `localhost:9099`), counter `ledger_core_audit_mirror_spawn_append_failures_total{kind}` pre-registered at zero for `ledger_entry`/`agent_decision`/`unspecified`. Wired into `docker-compose.yml` (port `9099`) and `infra/prometheus/prometheus.yml` (job `ledger-core`). **Remaining**: no Alertmanager rule on this counter yet; no `ledger-core` entry-count vs `audit-log` record-count cross-check (this counter only catches ledger-core-side failures, not audit-log-side divergence); no per-RPC `ledger_core_grpc_server_requests_total`/`_duration_seconds` (separate, larger, already-scoped TODO per `docs/SLO.md`).
|
|
3. **Tenant-scoped authorization (gateway interceptor)** — partially done: `VerifyAPIKey`/`VerifyJWT` wired, mismatch rejection on RPCs carrying `tenant_id`. **Remaining** (`docs/THREAT-MODEL.md` gap #1, all still open): (a) `GetCard`/`AdjustCardLimit` key off `card_id`, interceptor can't check them — needs a `card_id → tenant_id` lookup added to the interceptor path before it can check these two; (b) `StreamActivity` is a streaming RPC, entirely outside interceptor scope, empty `tenant_id` means "all tenants" unchecked — needs a streaming-interceptor or in-handler check; (c) CLI/TUI/agent dial `ledger-core` directly, bypassing gateway+tenantauth entirely — needs every direct-dial call site routed through gateway, or tenantauth logic duplicated at `ledger-core`'s own gRPC layer; (d) `RATION_GATEWAY_REQUIRE_TENANT_AUTH` defaults off, and CLI/TUI never call `IssueAPIKey`/`MintJWT` — needs default flipped once (a)-(c) land, plus CLI/TUI credential bootstrap.
|
|
4. **API-key / CA key persistence** — both in-memory only today (`services/auth`). Remaining: a real store (even SQLite, matching ledger-core's own index pattern) for API keys; a persisted + rotatable CA key for `servicecertca` (file-backed at minimum, HSM for real production).
|
|
5. **audit-log `source_service` trust** — fixed for mTLS-on; open for mTLS-off (unavoidable without mandatory mTLS, documented, not re-litigated here).
|
|
6. **Encryption at rest** — none for ledger-core's WAL/SQLite or audit-log's append file. Remaining: filesystem-level encryption (LUKS/dm-crypt or cloud-disk encryption) is the realistic first step; app-level envelope encryption is a larger, separate change not started.
|
|
7. **Terminal-escape injection in TUI/CLI rationale display** — known, low-severity, unmitigated. Remaining: strip/escape C0/C1 control chars at the render boundary in `tui`'s table cells the same way `cli`'s `ecb3242`/`27015f1` already does for its own output path — not yet ported to `tui`.
|
|
8. **Agent LLM gateway production wiring** — no confirmed-reachable production Railyard Relay URL or provisioned budget/metering (Mint billing, Abacus spend caps). Owner action, not code; code path (`services/agent/internal/llm/gateway.go`) is otherwise complete against the mock/dev relay.
|
|
9. **Airwallex live mode** — written against the real API shape, never exercised against a sandbox. Owner/hackathon blocker: needs an organizer-issued sandbox client ID/API key (`docs/AIRWALLEX-SETUP.md`). Mock mode is what the whole demo runs against today and is sufficient for that purpose.
|