80 Commits

Author SHA1 Message Date
79a264da6a docs: cross-link Scribase/Toolgate ecosystem (Rithub discoverability pass, 2026-11-16)
Some checks failed
CI / Proto lint (push) Failing after 31s
CI / C (wal, ASan+UBSan) (push) Failing after 40s
CI / Rust (ledger-core) (push) Failing after 37s
CI / Discover Go modules (push) Failing after 31s
CI / Go (${{ matrix.module }}) (push) Has been skipped
Docker build / Discover service Dockerfiles (push) Failing after 29s
Docker build / Build ${{ matrix.service }} (push) Has been skipped
2026-11-16 14:35:26 +00:00
767ed80451 fix(near-hackathon): correct two burned-in caption typos in demo video
Some checks failed
CI / C (wal, ASan+UBSan) (push) Failing after 37s
CI / Rust (ledger-core) (push) Failing after 1m2s
CI / Discover Go modules (push) Failing after 36s
CI / Go (${{ matrix.module }}) (push) Has been skipped
CI / Proto lint (push) Failing after 29s
Docker build / Discover service Dockerfiles (push) Failing after 43s
Docker build / Build ${{ matrix.service }} (push) Has been skipped
Re-rendered docs/near-hackathon/media/ration-near-demo-2026-11-11.mp4 with
two surgical caption patches, audio/duration/resolution untouched
(-c:a copy, same 69.84s/1920x1080/-14.6 LUFS):

- t=28.05-28.88: caption read "near Tesnack." (STT mis-transcription of
  "near Testnet" that survived the builder's own QC pass) -> "near Testnet."
  Confirmed via Deepgram re-transcription of the real narration audio that
  the spoken word is "testnet", not the on-screen caption text.
- t=61.38-62.52: caption read "Rations own database." (missing possessive
  apostrophe, inconsistent with the matching on-screen slide text
  "Ration's own database.") -> "Ration's own database."

Found during an adversarial judge/release-check pass (ffprobe + ebur128 +
frame-by-frame caption review + live NEAR RPC re-verification of every
on-chain claim in the deck/video/docs — all of which checked out as real).
2026-11-11 01:38:25 +03:00
7dd0b7facb docs(near-hackathon,soonami): add narrated submission videos + pitch decks
NEAR Hackathon: replace the 4.6s demo video with a 69.8s narrated
version (Deepgram Aura-2 + burned-in captions, -14.5 LUFS / -1.9 dBTP)
covering append -> anchor -> independent raw-RPC re-read -> a real
replay attempt rejected live on-chain, recorded against a freshly
deployed NEAR Testnet account (tx 5YebAM2...ome1t, replay-rejection tx
7v6m81j...469o). Old video kept, not deleted. Adds an 11-slide pitch
deck (PITCH-DECK.md/.pdf/.pptx) mapping the submission to NEAR's own
judging criteria (technical implementation, design, impact,
originality, sustainability, confirmed live from the hackathon FAQ).

soonami Venturethon 11: adds a venture-framed pitch deck
(docs/soonami/PITCH-DECK.md/.pdf/.pptx) covering market, business
model (flagged as an unpriced hypothesis), go-to-market, honest
traction, the 10-day sprint ask, and an explicitly flagged co-founder
placeholder (soonami requires >=2 co-founders; none invented). Reuses
the NEAR demo video per plan.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-11 01:05:19 +03:00
6b0bf3d57d docs: add literal README cross-reference to Cred402, fix replay-contract claim
Judge audit found two real doc issues: (1) the hackathon's literal
eligibility rule ("each README names the other") was only satisfied
via HACKATHON.md, not README.md itself — add an explicit Cred402
cross-reference to a new NEAR Hackathon section in README.md.
(2) X-POST-DRAFT-2026-11-10.md's caption claimed the replay attempt
was tried "on a sibling contract" — per HACKATHON.md's own evidence
(tx 3sWNYB5ddbqT5BaUqQfRJXJi8EfHUSJA7k8vgwDvAzPr) the replay was
resubmitted on the same primary contract/account, not a sibling one.
Also fixed a minor internal-doc date-wording drift in
SUBMISSION-CHECKLIST.md's header.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-10 17:32:59 +03:00
e4b3212d11 docs(near-hackathon): fix stale "demo not recorded" checklist + add X post draft
SUBMISSION-CHECKLIST.md still said the demo video wasn't recorded, but
commit da8f906 already recorded and committed it. Mark it done and point
at the real artifact. Also add a ready-to-post X caption
(X-POST-DRAFT-2026-11-10.md, mirroring cred402's own draft for the same
hackathon) since none existed yet for this entry.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-10 17:05:00 +03:00
da8f906f33 docs(near-hackathon): add the real NEAR-specific demo recording
Records a real, unedited  run against a freshly
deployed NEAR Testnet account (ration-demo-23bd92e5.testnet) —
real audit-log append, real on-chain anchor tx
(z8GWsRVxDykJ55rTKgb4dbN9WTH1UGMzk4NhQfogFrt), independently
re-confirmed on-chain. The primary submission account/contract
referenced elsewhere in HACKATHON.md is untouched.
2026-11-10 09:20:21 +03:00
f6c05030f5 docs(near-hackathon): cross-reference the owner's separate cred402 NEAR entry
NEAR Hackathon requires one entrant's multiple projects to cross-reference
each other. Added a short note; no functional change.
2026-11-10 09:17:30 +03:00
cff0ed3129 feat(near-hackathon): anchor audit-log's hash-chain tip to NEAR Testnet
Adds a focused NEAR Hackathon 2026 entry built on Ration's existing,
real audit-log service rather than a Ration-on-NEAR rewrite: a minimal
NEAR smart contract (contracts-near/audit_anchor) storing/verifying
{tenant_id, chain_tip_hash, sequence, occurred_at_unix}, plus a
from-scratch Go NEAR transaction signer and CLI
(services/audit-log/internal/nearanchor, cmd/near-anchor) that reads
audit-log's real local chain tip and anchors it on-chain.

Verified live on NEAR Testnet (account ration-anchor-286ca315f1.testnet):
contract deployed and code_hash-matched, two successful on-chain
anchors, one deliberate replay correctly rejected by nearcore's own
sequence guard, and a real (non-mocked) Go integration test passing
against the live contract. Transaction encoding cross-checked
byte-for-byte against near-api-js. Zero regressions in existing Go/Rust
suites. Full detail and every tx hash in docs/near-hackathon/.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-09 14:19:33 +03:00
25a118a131 docs(submission): judge-facing SUBMISSION.md was stuck describing round 5; add rounds 6-37
The "Updates since initial submission" section stopped at round 5
(2026-10-29) while the codebase is 32 rounds past that — agent tool
tenant-pinning, mTLS actually enforced, concurrency correctness on every
money-moving path, WAL/FFI crash-safety hardening, and a cross-tenant
ledger idempotency fix all landed since, with zero mention in the one
doc judges are most likely to read end to end.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-05 18:50:16 +03:00
bd742f176d fix(card-issuance): suspendAfterFailure silently discarded the Airwallex suspend error, leaving a live card at full limit with zero operator signal
IssueCard's reserve-floor/ledger failure path calls suspendAfterFailure
to zero out the just-created Airwallex card's limit, but the call's
error was discarded with a bare `_, _ = ...`. Unlike AdjustCardLimit's
mirror (revertCardControls), which already logs loudly on failure,
this was the only cleanup path with zero visibility — and the only one
that matters, since IssueCard returns before ever adding the card to
s.cards, so there is no persisted record anywhere in this service for
a reconciliation pass to retry. A transient Airwallex outage at exactly
this moment left a real, live card at its full requested spend limit
with no ledger backing and no way for an operator to find out.

Reproduced live (repro_suspend_bug_test.go, kept as a permanent
regression test): forced SetCardControls to fail during the suspend
path, confirmed the live Airwallex-side card still carries its full
limit, and confirmed the failure is now logged with the card id so an
operator can suspend it by hand. Same logging discipline as
revertCardControls and persist() elsewhere in this file.

go test -race ./... clean across all services/card-issuance packages.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-05 18:49:03 +03:00
d3319cfb54 fix(ledger-core): ApplyEntry's idempotency_key lookup ignored tenant_id — cross-tenant replay silently no-op'd as success
idempotency_key is UNIQUE across the whole ledger_entries table, not
scoped to (tenant_id, idempotency_key). apply_entry_checked's replay
lookup returned the matched entry as Applied regardless of whether its
tenant_id matched the caller's requested tenant_id, pairing the OTHER
tenant's entry (reference/memo/amount) with THIS tenant's own
unaffected balance — reporting success for a write that never actually
happened, with no error anywhere.

Every real caller today derives idempotency_key from a CSPRNG/UUIDv4
id (idgen.New, Uuid::new_v4), so a genuine collision across tenants is
cryptographically negligible in practice — but the lookup itself never
enforced that, which matters for a platform whose hackathon track is
explicitly multi-tenant isolation. Add LedgerError::IdempotencyKeyTenantMismatch
and fail loudly instead of silently mixing tenants.

Verified: cargo build --release clean, cargo check --release --tests
clean (new test type-checks), cargo fmt --check clean on touched
files, cargo clippy --release exit 0, and a full cargo test --release
--test idempotency run (including the new
replaying_another_tenants_idempotency_key_is_rejected_not_silently_applied
regression test) completed with exit code 0 on this box despite heavy
concurrent sibling-agent load intermittently hanging repeat attempts
at process exec (unrelated amfid/syspolicyd contention, not a code
issue — confirmed via `sample` showing the test binary stuck at
dyld_start, and the same stall reproducing on the already-built,
previously-working main ledger-core binary too).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-03 00:58:12 +03:00
1f4eb729cb fix(agent): adjust_card_limit let the LLM redirect a card-limit change to any tenant's card
handleAdjustCardLimit forwarded the model-supplied card_id straight to
gateway.AdjustCardLimit with no check that the card belongs to the
tenant this decision cycle is for. BuildToolSchemas's own doc comment
claims tenant_id is deliberately never a model parameter "so the model
can never redirect an action at another tenant" — true for
ration_bridge_funding/issue_card/notify_tenant (all pass tc.TenantID
explicitly), false for adjust_card_limit, whose only tenant binding is
an indirect card_id->tenant lookup that gateway's own tenantauth
interceptor explicitly skips for an operator credential (exactly what
this agent always authenticates as). A hallucinated or
prompt-injected card_id (e.g. via the tenant-controlled TenantName
field already rendered verbatim into the prompt) could silently
tighten or loosen ANY tenant's card limit.

Reproduced live against the real bare-metal stack (ledger-core, auth,
tenant-registry, card-issuance, gateway): minted the agent's real
operator JWT, called the real exported tool handler with tenant A's
TenantID but tenant B's real card_id — tenant B's card limit dropped
from 1,000.00 EUR to 0.00 EUR and flipped to RATIONED, with zero
errors anywhere in the chain. Fix: resolve the card via gateway.GetCard
first and decline (recording a real DECLINE audit entry) when its
tenant_id doesn't match tc.TenantID. Re-ran the identical repro
post-fix: cross-tenant attempt now rejected with the card untouched;
same-tenant adjustment still succeeds normally.

go build/vet/test clean for every go.work module; 0 regressions.
2026-10-29 21:19:11 +03:00
a3326e875a fix(ledger-core): apply failure after a durable WAL append silently misreported success as failure
append_and_commit returned a plain Err whenever the SQLite apply/commit
step failed, even after inner.wal.append() had already fsynced the
event. That frame is then guaranteed to be replayed by the next
Ledger::open regardless, so a caller who saw "failed" and retried would
get a second, distinct record (every mutating RPC's id is
server-generated) once the first one also resurrected on restart - a
real duplicate-record risk for a financial ledger, most reachable via
exactly the kind of disk pressure this shared box has hit repeatedly.

Reproduced live against the real append_and_commit via a scratch
harness forcing the apply closure to fail: the "failed" tenant
materialized after a simulated restart. Fix aborts the process instead
of returning a soft error once the WAL append has already succeeded,
leaning on the already-tested replay-on-open path to reconcile state
before any other call is accepted. Verified the abort fires correctly
(SIGABRT, correct diagnostic) via an isolated cargo test invocation,
then removed the temporary repro/verification tests. Also verified live
against the real running release binary (standalone ledger-core,
tenant auth disabled): normal CreateTenant calls are unaffected.

cargo test --lib: 51/51 passed, 0 regressions. cargo build --release
clean. No new test files added.
2026-10-29 20:55:17 +03:00
56d7ae631f fix(terraform): ledger-core/audit-log's rolling-deployment config let two tasks with disjoint disks run concurrently
infra/terraform/modules/service hardcoded deployment_minimum_healthy_percent=100
and deployment_maximum_percent=200 for every service, including ledger-core and
audit-log — both explicitly documented in their own env-file comments as
"single-writer, not horizontally scaled" and backed by a local WAL/hash-chain on
Fargate ephemeral storage with no replication between tasks. That rolling config
let ECS run the old task and a brand-new, empty-disk task concurrently for the
length of every deploy's health-check window, both reachable under the same
Cloud Map service-discovery name.

Reproduced live: started two real ledger-core processes (one seeded with a real
tenant+balance simulating the pre-deploy task, one against a fresh empty data
dir simulating the new Fargate task on fresh ephemeral storage) and called
GetBalance for the identical tenant_id against both — the "old" task returned
the real balance, the "new" task returned NotFound, with no way for a caller to
tell "tenant genuinely doesn't exist" apart from "this task's disk never saw it
because it's a brand new task from this exact deploy." Any write ECS routes to
the old task in that overlap window is lost the moment the old task is stopped.

Fix: added deployment_minimum_healthy_percent/deployment_maximum_percent as
module variables (default 100/200, preserving today's rolling behavior for
stateless services), and overrode them to 0/100 ("recreate" semantics — old task
fully stopped before the new one starts) for module.ledger_core and
module.audit_log in all three envs (dev/staging/prod).

Verified: terraform validate clean for the module and all three envs;
terraform plan reaches the expected provider-auth wall (this repo's own
documented verification ceiling — no AWS credentials available) with no
configuration errors before that point; terraform fmt -check -recursive clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 20:03:00 +03:00
9d8f0564b2 fix(mtls): every internal service's dial to auth bypassed mTLS entirely, breaking the production-hardening path
6 of 7 services that mint a credential from auth (agent, card-issuance,
tenant-registry, webhook-ingestion, cli, tui) called authclient.Dial(addr)
with zero DialOptions, while loading and correctly applying mTLS creds to
every OTHER peer dial in the same binary. gateway was the only caller that
got this right (authMTLS/authDialCreds pattern).

Reproduced live: with AUTH_MTLS_ENABLED=true (generated via
infra/dev-ca/generate-dev-ca.sh, the exact production-hardening path
docs/SCALE-EXPANSION.md section 8 documents), auth's server correctly
requires and verifies a client cert (tls.RequireAndVerifyClientCert) — a
plaintext dial against it doesn't degrade gracefully, it fails the TLS
handshake outright ("error reading server preface: EOF"/connection reset).
Confirmed with the real pre-fix card-issuance binary: it crashes at startup
("mint operator JWT: ... error reading server preface: EOF") the moment
mTLS is actually turned on, for every one of the 6 affected services.

Also found and fixed a second instance of the same root cause while
checking sibling call sites: the CLI's apikey issue/revoke/list and tenant
create/list commands each dial auth directly (bypassing clients.go's
dialClients entirely) and never attached mTLS creds either; tenant
create/list's own tenant-registry dial had the identical gap. Added a
shared dialAuthClient() helper in clients.go so this bug class can't
quietly reappear a 6th time within the same CLI binary.

Verified live end-to-end against the real 8-service bare-metal stack with
mTLS fully enabled (dev-ca-generated certs for every service): auth,
card-issuance, tenant-registry, webhook-ingestion, gateway, and agent all
now mint/verify successfully over mTLS at startup; a full CLI cycle (seed,
status, apikey issue/list/revoke, tenant create/list, card issue,
simulate-deposit --late, agent auto-grant, audit-check, verify-chain) ran
clean end to end. Re-verified the default mTLS-disabled path (every prior
round's own verification baseline) is completely unaffected by re-running
the identical demo cycle with mTLS off.

go build/go vet clean across all 11 go.work members, gofmt clean on every
touched file, go test clean for every affected package (0 regressions).
2026-10-29 19:45:19 +03:00
20193a0b8d fix(agent): a real, nil-error bridge-funding decline was misclassified as a grant in the audit trail
tools.go's handleRationBridgeFunding tagged EVERY nil-error gateway
response as AGENT_ACTION_RATION_BRIDGE, even when GrantedMinorUnits was
0. bridge.Service.RationBridgeFunding has three documented paths that
return exactly that shape (below the $5 minimum-useful-grant floor —
including its own independent, ledger-entry-based velocity check
disagreeing with this agent's decision-history-based
hasOpenGrantWithinWindow — a ledger-core-rechecked reserve-floor
violation, or "deposit already received"). None of those is a Go
error, so every one of them was recorded as if money had actually
moved.

This both corrupted the audit trail (a "granted $0" decision labeled
as a bridge grant) and fed hasOpenGrantWithinWindow's wasActuallyGranted
check a false "actually executed" signal, since the snapshot map always
carries a granted_minor_units key even at 0 — permanently
velocity-capping a tenant that was never actually granted anything, the
same fund-stranding-via-misclassification failure mode round 6 fixed
via a missing deposit_id, reached here instead via a wrong action tag.

Fix: tag the decision AGENT_ACTION_DECLINE whenever
GrantedMinorUnits <= 0, regardless of error.

Reproduced live against the real running stack (real auth + ledger-core,
real RecordAgentDecision/ListAgentDecisions, a stubbed gateway forcing
the exact zero-grant/nil-error response) before fixing, and confirmed
fixed the same way afterward. New regression tests in runner_test.go
cover both the misclassification itself and its downstream
velocity-cap consequence; both fail on the pre-fix code and pass after.
2026-10-29 19:28:51 +03:00
355edeee64 fix(card-issuance): concurrent persist() calls for different cards could lose a committed limit change from disk
AdjustCardLimit/CloseCard's cardLocks deliberately let two DIFFERENT
card ids mutate concurrently, but persist() rewrites the ENTIRE cards.json
from a full map snapshot every time it runs, with no ordering relative to
any other in-flight persist() call. If one call's snapshot (taken before a
concurrent call's own update landed) finished its disk write AFTER the
other's newer, correct write, the file ended up reverting the other
call's already-"successful" limit change the moment it hit disk — a
later restart would then reload the stale value while ledger-core's real
Held balance still reflects the larger, correct amount, permanently
stranding those funds the same way round 25's cardLocks gap did, just
via a lost disk write instead of a lost in-memory update.

Reproducing this also caught a second, closely related `-race`-detected
bug: persist()'s snapshot only copied the map's bare *Card pointers, so
saveCardsFile's protojson.Marshal (run after s.mu is released) could read
a card's fields while a concurrent AdjustCardLimit/CloseCard mutated that
exact same shared object in place.

Fix: persistMu now serializes persist()'s entire snapshot-then-write
critical section, and the snapshot deep-copies each card (cloneCard,
the same proto.Clone helper already used elsewhere) instead of aliasing
the live map's pointers.

New test TestPersist_ConcurrentDifferentCardsDoesNotLoseEitherUpdate uses
a beforeSaveForTest hook to force the exact interleaving (real wall-clock
timing can't reliably do it); confirmed via falsification it fails 20/20
without the fix (lost update + data race) and passes 50/50 with it.
Verified live against the real 8-service stack: 30 concurrent
adjust-limit calls across 2 cards, on-disk state matched in-memory/ledger
state exactly, survived a real card-issuance restart.

go build/go vet/go test -race clean across all 11 go.work modules.

Round 28 of today's audit pass (plans/airwallex-hackathon.md).
2026-10-29 19:04:49 +03:00
1214dc8030 fix(ledger-core,card-issuance): bridge-funding's HOLD could land on a deposit webhook-ingestion had already settled
RationBridgeFunding reads a deposit as late, then several RPC round
trips later applies a HOLD referencing that deposit_id — with nothing
serializing that gap against webhook-ingestion's own, separate-process
handleTransactionCreated marking the SAME deposit received in between.
mark_deposit_received_with_entry only releases bridge holds that exist
at the moment it runs, so a hold created afterward is permanently
unreleasable. Round 25/26's per-tenant locks live in different OS
processes and cannot fix this.

Fixes it the same way apply_entry already re-validates the reserve
floor atomically: ApplyEntryRequest gains an optional
require_deposit_outstanding_id, checked under ledger-core's own single
mutex before any mutation (apply_entry_checked), returning
DepositAlreadyReceived instead of applying the hold. bridge.Service
now always sets this on its bridge-hold ApplyEntry call and declines
cleanly instead of stranding funds.

Reproduced the exact interleaving via a deterministic raceLedger test
(confirmed it fails without the fix, passes with it, under go test
-race). Live-reproduced the race window against the real 8-service
stack; happy path and full build/test matrix unaffected.
2026-10-29 18:51:07 +03:00
d806ec4fe3 fix(webhook-ingestion): concurrent deposit webhooks for the same tenant could both match the same deposit, stranding the other's funds
Same missing-lock/TOCTOU class round 25 fixed for card-issuance's
AdjustCardLimit/CloseCard (per-card lock) and RationBridgeFunding
(per-tenant lock), found on a third, previously-unaudited money-moving
path: handleTransactionCreated's ListDeposits -> match ->
MarkDepositReceived sequence had nothing serializing it per tenant.
Two genuinely concurrent webhook deliveries for the same tenant (e.g.
two outstanding deposits of the same amount settling close together —
Go's net/http serves each request on its own goroutine) could both
read the deposit list before either call landed, so both independently
picked the same "oldest not-yet-received" deposit. ledger-core's own
MarkDepositReceived is idempotent per deposit_id, so this never
double-credited — but the second transaction's real, already-arrived
money was then never matched to anything: its deposit stayed Expected
forever, permanently understating the tenant's available balance.

Reproduced live against the real bare-metal stack before fixing: two
concurrent signed webhook deliveries for two $750.00 deposits on the
same tenant both matched deposit bcdb1859 via amount_heuristic; the
sibling deposit d234a440 was never credited (Available stayed flat at
one deposit's worth instead of rising by both). Fixed with a per-tenant
sync.Mutex (webhookhandler.Handler.tenantLocks/lockTenant), the
identical lazily-created-never-removed pattern cardsvc.Service.lockCard
and bridge.Service.lockTenant already established, serializing the
entire check-then-act critical section per tenant_id. Re-ran the
identical live repro post-fix: the two transactions correctly matched
the two distinct deposits, and Available rose by the full $1,500.00
(both $750.00 deposits settled).

New regression test (TestHandleAirwallexWebhook_ConcurrentSameAmount-
DepositsBothSettle) uses a concurrency-aware fake ledger whose first
ListDeposits call sleeps after taking its snapshot, deterministically
widening the TOCTOU window instead of relying on real scheduling.
Confirmed it fails 20/20 on the pre-fix code and passes 20/20 with the
fix, both under `go test -race`. `go build`/`go vet`/`go test ./...`
clean across all 11 go.work members; `make build-go` clean.
2026-10-29 18:15:03 +03:00
9dc6a1f1d4 fix(card-issuance): concurrent RationBridgeFunding calls for the same tenant could both pass the velocity cap
bridge.Service.RationBridgeFunding's rule-3 velocity check
(velocityBlocked) reads recent ledger-core entries to decide whether a
tenant already has an unrepaid bridge grant, then — much later —
applies a new HOLD via ApplyEntry if not blocked. Nothing serialized
that read-then-write per tenant, so two concurrent calls for the SAME
tenant both read velocityBlocked=false before either HOLD landed, and
both got granted. ledger-core's own ApplyEntry is defense in depth for
the reserve-floor invariant only; it has no notion of "velocity cap" or
"bridge cap of this specific late deposit" — those exist purely in this
method's own check-then-act Go logic.

Reproduced live against the real running stack: seeded a tenant with a
single $10,000.00 late deposit (60% bridge cap = $6,000.00, headroom far
above that), fired two concurrent RationBridgeFunding calls for
$6,000.00 each sharing one gRPC connection — both returned
granted=$6,000.00/fully_granted=true, and the tenant's real Held balance
rose by the full $12,000.00 — 120% of the single late deposit this was
meant to cap at 60%, and two simultaneous outstanding grants where rule
3 allows at most one.

Fix: added lockTenant, a lazily-created per-tenant sync.Mutex
serializing RationBridgeFunding's entire critical section (read
velocity/headroom -> decide -> ApplyEntry -> RecordAgentDecision) for
one tenant, the same pattern card-issuance's own cardsvc.lockCard
already uses for AdjustCardLimit/CloseCard. New
TestRationBridgeFunding_ConcurrentCallsRespectVelocityCap (with its own
mutex-protected concurrencyFakeLedger that feeds applied entries back
into ListEntries, unlike the file's existing sequential-only fakeLedger)
fires two real concurrent grants and asserts total granted never exceeds
the single bridge cap — fails 20/20 runs on the pre-fix code (both
calls granted, double the cap) and passes reliably 20/20 with the fix,
clean under `go test -race`.

Verified live against the real fix: rebuilt only bin/card-issuance,
restarted that one process, re-ran the identical two-concurrent-call
repro against a fresh tenant/deposit — exactly one call granted the
full $6,000.00 cap, the other correctly declined on the velocity cap,
confirmed via `ration status` that Held rose by exactly $6,000.00, not
$12,000.00. go build/vet clean across all 11 go.work members; go test
clean for every package in all 11 modules (0 regressions). gofmt -l on
service.go matches an already-documented pre-existing import-ordering
diff (confirmed via git stash, not introduced here); service_test.go is
gofmt-clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 17:48:46 +03:00
326330357c fix(card-issuance): concurrent AdjustCardLimit/CloseCard on the same card permanently leaked held funds
AdjustCardLimit and CloseCard each read a card's current
LimitMinorUnits, called Airwallex, called ledger-core's ApplyEntry for
the delta, then wrote the card's new absolute LimitMinorUnits back —
but the initial read-then-later-write was never serialized against a
second concurrent call for the SAME card id. ledger-core's own
apply_entry is atomic and additive (two concurrent HOLDs both land
correctly on the real held balance), so the divergence was entirely in
this service's own cached field: the final write is "last writer wins"
on an absolute value, not oldLimit+delta, so one call's increase could
silently vanish from card.LimitMinorUnits while ledger-core still held
it for real.

Reproduced live against the real running stack (mock Airwallex, real
ledger-core): issued a card with a $1,000.00 limit, fired two
concurrent AdjustCardLimit calls (+$1,000.00 and +$2,000.00) sharing
one gRPC connection. Both succeeded; ledger-core's real Held balance
correctly became $4,000.00, but card.LimitMinorUnits ended at
$2,000.00 (whichever call wrote last). Closing that card then released
only $2,000.00 (CloseCard's release amount is always
card.GetLimitMinorUnits()), leaving $2,000.00 permanently stuck in the
tenant's Held balance with zero live cards referencing it — unreachable
by any code path in this repo ever again.

Added lockCard: a lazily-created per-card-id sync.Mutex serializing
AdjustCardLimit/CloseCard's full critical section (read → Airwallex →
ledger ApplyEntry → write) for one card, while leaving every other
card free to proceed concurrently. New
TestAdjustCardLimit_ConcurrentIncreasesStayConsistentWithLedger fires
two real concurrent increases and asserts card.LimitMinorUnits always
equals the sum of every HOLD/RELEASE ledger-core actually applied —
fails (both as a logical mismatch and as a go test -race data race) on
the pre-fix code in 9/10 runs, passes reliably 20/20 with the fix.

Verified live: rebuilt only bin/card-issuance, restarted that one
process (card metadata reloaded from data/cards.json), re-ran the
identical two-concurrent-increase repro against a fresh card — second
call now correctly blocks until the first commits, computes its delta
against the real current limit, and the two calls' effects compose
correctly instead of diverging. go build/vet clean across all 11
go.work members; go test -race ./... clean for every card-issuance
package. gofmt -l on the touched files matches round 21's already-
documented pre-existing import-ordering diff on service.go (confirmed
via git stash, not introduced here); service_test.go is gofmt-clean.
2026-10-29 17:38:56 +03:00
4b501667e2 fix(cli,tui): tenant Name rendered raw in status/TUI — a fourth unsanitized terminal-escape-injection call site rounds 13/16/23 never reached
ration status (the single most-run command in this repo, per round 13's
own framing)'s printTenantHeader printed tenant.Name completely raw, with
no sanitization at all. Same gap, same root cause, across the TUI: the
Tenants tab table, the Activity tab's per-row TenantName, and the card
form's tenant picker + adjust-limit infoLine all rendered a Tenant's own
Name raw too. services/tenant-registry's Create only validates name
non-emptiness, no charset check — round 16 already proved a raw ESC byte
survives into a persisted Tenant record via "tenant create --name".
Rounds 13/16/23 sanitized CardholderName, the CLI's own tenant-create
echo, and the Activity feed's Summary, but never Tenant.Name as read
back through these five separate call sites.

Reproduced live against the real bare-metal 8-service stack
(scripts/start-individually.sh): created a tenant with
--name $'Evil\x1b[31;1mINJECTED\x1b[0m Status Co', then byte-counted real
stdout — `ration status --tenant <id>` carried 2 raw ESC bytes pre-fix,
0 after. Drove the real bin/tui through a tmux pty: Tenants tab and the
card-issue form's tenant picker both rendered the literal bracket text
pre-fix verification showed was otherwise a live ANSI escape (confirmed
via `tmux capture-pane -e` byte inspection, distinguishing it from tmux/
lipgloss's own legitimate styling codes).

Fix: sanitizeControlChars(tenant.Name) in status.go's printTenantHeader;
format.SanitizedCell(t.GetName(), ...) in tui/view/tenants.go;
textsanitize.StripControlChars on ActivityRow.TenantName in
tui/view/activity.go; and on both the tenant picker's display name and
newAdjustLimitForm's tenantName param in tui/model/cardform.go — all via
the same helpers this repo's prior sanitization rounds already
established.

go build/go vet/go test clean for services/cli and services/tui (0
regressions), gofmt clean, full make build-go (10 binaries) clean.
2026-10-29 17:26:40 +03:00
bf4190f8b7 fix(tui): Activity tab rendered CardholderName/AdjustCardLimit Reason raw — a third unsanitized terminal-escape-injection call site rounds 13/16 never reached
services/gateway/internal/grpcserver/server.go's publish() calls embed
IssueCard's raw CardholderName and AdjustCardLimit's raw Reason
directly into the activity feed's Summary string, with no
sanitization anywhere upstream. Round 13 fixed this exact
vulnerability class for CLI status/card list and the TUI's Cards
tab/adjust-limit modal; round 16 fixed a sibling case on `tenant
create`'s own printout — neither ever looked at the gateway's
StreamActivity Summary field, a separate code path feeding the TUI's
Activity tab.

Reproduced live: issued a card via the real 8-service bare-metal
stack with --cardholder containing a raw ESC byte + ANSI color code,
watched the TUI's Activity tab through a real tmux pty — tmux
capture-pane -e showed a genuine, uninterpreted `^[[31mINJECTED^[[0m`
escape sequence sitting in the pane content, not literal bracket
text. Confirmed the same gap on AdjustCardLimit's --reason.

Fix: strip control characters (pkg/textsanitize.StripControlChars,
same helper decisions.go already uses) on Summary at the render
boundary in services/tui/internal/view/activity.go, covering both
call sites (and any future free-text field embedded in a published
activity Summary) with one change. Re-verified the identical live
repro for both IssueCard and AdjustCardLimit: both now render as
literal bracket text, matching the established lipgloss styling
codes elsewhere in the same pane which still show their real `^[`
prefix.

go build/go vet/go test ./... clean for services/tui (0 regressions),
gofmt -l clean. Full module-by-module build (pkg + every service +
sdk/go/ration) clean.
2026-10-29 17:10:01 +03:00
6b886fb4e5 fix(webhook-ingestion): deposit reference match ignored the real transaction amount — a short transfer still credited the full expected amount
handleTransactionCreated's tier-1 match (payload.Reference ==
deposit.ExternalRef) never checked the transaction's own amount.
MarkDepositReceived has no "amount actually transferred" field at all
(proto/ledger.proto) — it always credits the matched deposit's full
pre-recorded expected amount. Reproduced live against the real running
stack: a genuine signed webhook carrying a $5,000.00 deposit's
reference but only $1.00 in amount_minor_units would have marked that
deposit fully received and credited the tenant $5,000.00 for a $1.00
transfer.

matchDepositByReference now also requires the transaction's amount to
equal the deposit's expected amount before trusting the reference
match; a reference match that fails the amount check falls through to
the existing amount-heuristic tier instead of being treated as exact.

Verified live: rebuilt only webhook-ingestion, sent a real HMAC-signed
webhook with the correct reference but wrong amount — rejected ("no
matching expected deposit found"), deposit stayed unreceived, balance
untouched. Then sent the same reference with the correct amount —
matched_by=reference, deposit credited normally. go build/vet/test
clean across all 11 go.work members.
2026-10-29 17:06:18 +03:00
d1a98454c4 fix(card-issuance): IssueCard silently accepted a currency that could never be funded
A --currency that didn't match the tenant's own currency was only ever
caught by ledger-core's ApplyEntry CurrencyMismatch check — but a
zero-limit card never calls ApplyEntry at all, so `ration card issue
--currency EUR --limit 0` against a USD tenant succeeded and created a
real (mock) Airwallex card. The card then sat permanently stuck at a
zero limit: the very next `card adjust-limit` above zero failed with a
confusing low-level "currency mismatch: USD vs EUR" error from
ledger-core, with no way to ever fund it. Reproduced live against the
real 8-service stack before fixing.

Reject the mismatch upfront in IssueCard, before any Airwallex card is
created, with a clear actionable error. Added a regression test
covering the zero-limit path specifically (the one that previously
skipped the check entirely). go build/vet/test clean across every
workspace member; verified live against the rebuilt card-issuance
binary that the same repro now fails immediately instead of creating a
stuck card.
2026-10-29 16:55:13 +03:00
6f5cff1b57 fix(gateway): REST facade's JSON body decode had no size cap — a single unauthenticated request could balloon memory by the full body size
decodeJSONBody (IssueCard, AdjustCardLimit, RationBridgeFunding,
SimulateDeposit) read r.Body with a bare json.NewDecoder and no bound,
before any auth check ever ran. Reproduced live: one unauthenticated
300MB POST to /v1/cards drove gateway's RSS from ~20MB to ~1.3GB in
~5.6s. Capped at 1MB via http.MaxBytesReader (same limit and
justification services/webhook-ingestion's handler already uses for
the identical class of payload), mapped to a 413 instead of the
existing 400. Verified live post-fix: the same 300MB body now returns
413 in ~2.5ms with RSS flat at ~25MB; real IssueCard/AdjustCardLimit/
SimulateDeposit/RationBridgeFunding round-trips through the REST
facade with a real minted API key still succeed unchanged. go build/
go vet/go test clean for services/gateway, full make build (Rust+Go+
SDK) clean, 0 regressions.
2026-10-29 16:22:51 +03:00
31be78e465 fix(gateway): REST facade's unscoped routes shared one rate-limit bucket across every caller
GetDashboardSnapshot and StreamActivity (empty tenant_id, the documented
"all tenants" mode) carry no tenant_id/card_id, so internal/ratelimit's
gRPC-layer interceptor falls back to peer-address keying. But the REST
facade reaches gateway's own gRPC server over one single, long-lived
self-dial connection (cmd/gateway/main.go's selfConn) — so every REST
caller of GET /v1/dashboard/snapshot, GET /v1/dashboard/activity/stream,
and GET /v1/activity (no tenant_id) collapsed into ONE shared token
bucket, the opposite of "one noisy caller can't starve every other
caller" that package promises. Most exposed on the dashboard: a public,
zero-login, judge-facing page explicitly designed for multiple
simultaneous viewers.

Add a second, HTTP-layer limiter keyed by the real client's remote
address, applied only to those three call sites — every tenant/card-
scoped route keeps its existing, already-correct gRPC-level protection
untouched.

Verified live against the real bare-metal stack: a concurrent burst of
40 connections to /v1/dashboard/activity/stream now correctly splits
30 (burst) succeed / 10 rejected with 429, keyed per real client IP;
confirmed tenant-scoped /v1/activity calls are unaffected (10/10 200s).
go build/vet/test clean for services/gateway, 0 regressions.
2026-10-29 15:35:47 +03:00
97bb36c631 docs(demo-script): judge-facing demo walkthrough was stuck describing a 4-service stack; real stack is 8
docs/DEMO-SCRIPT.md (the one doc a judge actually runs commands from) still
said `make build` produces 4 Go binaries and `scripts/run-demo.sh` starts
audit-log/ledger-core/gateway/agent only — stale since the section-1 split
added auth/tenant-registry/card-issuance/webhook-ingestion, same staleness
class README.md had before today's earlier pass fixed it there. Verified
live: `make build` produces 10 Go binaries, `scripts/run-demo.sh` starts 8
services. Also added a step showing `ration tenant`/`card`/`apikey` — 3
operator command groups built across many rounds today that this doc never
mentioned at all, verified live against the real running stack.
2026-10-29 15:14:01 +03:00
fece777954 fix(scripts): start-individually.sh silently disabled audit-log mirroring; docs(readme): README's service table/diagram was stuck at phase-1 (6 of 11 services)
scripts/start-individually.sh (the committed box-contention workaround
used across rounds 6-16) plainly `source .env`'d without run-demo.sh's
already-established AUDIT_LOG_ADDR fallback, so ledger-core always saw
AUDIT_LOG_ADDR="" and silently disabled its own AuditMirror on every run
started this way. Reproduced live via `ration audit-check` (every tenant
showed real ledger entries against 0 audit entries), fixed with the same
fallback run-demo.sh already uses, re-verified live end to end (seed ->
simulate-deposit --late -> agent grant -> audit-check OK, counts matching
-> verify-chain intact).

README.md's architecture diagram and Services table were last touched at
the very first scaffold commit and never updated across 16 rounds of real
feature work since — they still described a 6-service system (wal,
ledger-core, gateway, agent, tui, cli) while the repo has grown to 11
real services (adding auth, tenant-registry, card-issuance,
webhook-ingestion, audit-log, plus the Go/Rust SDKs), none of which
appeared anywhere in the judge-facing entry point to this repo.
2026-10-29 15:05:04 +03:00
aa31e1d6a1 fix(cli): sanitize tenant name on ration tenant create's own success output
Round 13 sanitized CardholderName across card.go/status.go/tui but never
audited every other free-text field's echo path. `ration tenant create`
printed the operator-supplied --name straight back to the terminal raw,
while `ration tenant list` (same field) already sanitized it — a real
terminal-escape-injection gap on tenant onboarding's own success message.

Reproduced live: creating a tenant with an ESC-laden name produced 2 raw
ESC bytes in stdout (byte-counted, not visually inspected). Fixed by
reusing the same sanitizeControlChars helper tenant list/apikey
list/card already use. Re-verified: 0 ESC bytes post-fix, list/create
both render the literal bracket text. go build/vet/test clean for
services/cli, full make build clean, 0 regressions.
2026-10-29 14:40:06 +03:00
b4c1b965a1 fix(card-issuance): reorder AdjustCardLimit/CloseCard to call Airwallex before the ledger mutation
Round 14 found but deliberately deferred this: both methods applied
their ledger HOLD/RELEASE before calling Airwallex, with no rollback if
the Airwallex call then failed. A failing retry (e.g. a stale/orphaned
Airwallex card id) would re-apply the same ledger mutation every time,
leaking reserve-floor headroom without bound.

Reordered both to match IssueCard's existing safe pattern: Airwallex
first, ledger mutation second. AdjustCardLimit now reverts the Airwallex
limit (new revertCardControls, mirrors suspendAfterFailure) if the
follow-up ledger call fails. CloseCard's Airwallex close is terminal (no
reopen endpoint exists) so there's no symmetric revert, but the reorder
alone makes its failure mode fail-safe instead of a leak: a failed
ledger release now just leaves the hold stuck in place for a retry to
clear, rather than double-releasing it.

Reproduced live on the pre-fix bare-metal stack: a restart-orphaned
card's AdjustCardLimit leaked +1,000.00 GBP of ledger HOLD per failing
retry (3 attempts -> 1,000 -> 2,000 -> 3,000 Held) despite every call
returning an error to the client. Rebuilt with this fix and reran the
identical repro: Held stayed exactly flat across repeated failures for
both AdjustCardLimit and CloseCard. Confirmed happy-path increase,
decrease, close, and idempotent re-close still behave correctly.

go build/vet/test clean for services/card-issuance, 0 regressions.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 14:07:07 +03:00
5bb6bc92f2 fix(card-issuance): persist card metadata — a restart silently lost every issued card forever
cardsvc.Service's own `cards map[string]*cardissuancepb.Card` was the
only place this repo stores Card metadata (ledger-core's proto has no
Card message), and it was pure in-memory state with zero durability.
A card-issuance restart lost every issued card's id/cardholder/limit/
status while the ledger HOLD backing its limit lived on in ledger-core
forever, unreachable by GetCard/AdjustCardLimit/CloseCard ever again
(all three look the card up by id first). card_issuance.proto's own
service comment also claimed this service was "stateless... safe to
run as N replicas" — false given this in-memory map; corrected.

Adds a file-backed store (services/card-issuance/internal/cardsvc/
store.go): atomic write-then-fsync-then-rename JSON file, loaded on
startup via a new EnablePersistence(path) method (opt-in, so existing
unit tests that never call it are unaffected) and written after every
IssueCard/AdjustCardLimit/CloseCard. New RATION_CARD_ISSUANCE_DATA_DIR
env var (default ./data, same convention as RATION_AUDIT_LOG_DATA_DIR),
wired in main.go.

Verified live against the real bare-metal stack: issued a card,
confirmed data/cards.json held it, killed and restarted card-issuance,
and confirmed `ration card get`/`ration status` still found the card
(pre-fix this would have been NotFound). go build/vet/test clean for
card-issuance (0 regressions), full `make build` clean.

Does not make this service safe to run as N replicas (each replica
would still load/save its own independent copy of the file) — that
needs a real shared store, the same class of gap already named and
left open for services/auth's apikey.Store; documented, not attempted,
in this round.
2026-10-29 13:53:46 +03:00
143ad32a84 fix(cli,tui): sanitize CardholderName on ration status/card list and the TUI Cards tab + adjust-limit modal
CardholderName is operator-authored free text (ration card issue
--cardholder, and the TUI's own issue-card form) — the same class of
terminal-escape-injection risk already closed for Trigger/Rationale/
PolicySnapshotJson. card.go's printCard (card issue/get/adjust-limit/
close) already sanitized it, but status.go's printCards (used by both
`ration status` and `ration card list`) printed it raw, and the TUI's
Cards tab table (view/cards.go) and the adjust-limit modal's infoLine
(model/cardform.go) did too. A cardholder name containing an ANSI
escape sequence would inject into `ration status` output — the single
most commonly run command in this whole repo's demo flow — and into
the TUI dashboard a judge/operator is meant to watch live.

Fixed all three raw render sites to go through the same
sanitizeControlChars/format.SanitizedCell/textsanitize.StripControlChars
helpers already used everywhere else free text is displayed.

Verified live against the real bare-metal 8-service stack: issued a
card with a cardholder name containing a real ESC (0x1b) byte +
"[31;1mINJECTED[0m", confirmed `ration status` and `ration card list`
output now contain zero raw ESC bytes (byte-counted, not just visual),
and drove the real TUI through a tmux pty — both the Cards tab table
and the adjust-limit modal's header render the literal bracket text
with no live escape sequence. go build/go vet/go test clean for cli
and tui, gofmt clean, 0 regressions.
2026-10-29 13:36:20 +03:00
9b4e470dce feat(sdk): rust-client had no credential story at all; add CloseCard to both SDKs
services/gateway's tenantauth interceptor defaults
RATION_GATEWAY_REQUIRE_TENANT_AUTH to true, but sdk/rust/ration-client
had zero way to attach any credential — no WithAPIKey/WithBearerToken
equivalent of what sdk/go/ration got in round 3. Every RPC the Rust SDK
made against a default-config gateway failed Unauthenticated; its own
doc.go-equivalent example never worked. Added CredentialInterceptor
(tonic Interceptor) plus Client::connect_with_api_key/
connect_with_bearer_token and from_channel_with_api_key/
from_channel_with_bearer_token, mirroring the Go SDK's dial-option
pattern.

Also closed a smaller parity gap found along the way: CloseCard
(round 11) was wired into gateway.proto/CLI but never added to either
official SDK, so an external platform customer importing sdk/go/ration
or sdk/rust/ration-client had no way to shut off a leaked/offboarded
card's spending via the SDK itself. Added Client.CloseCard (Go) and
Client::close_card (Rust).

Verified live against the real bare-metal 8-service stack
(scripts/start-individually.sh): a throwaway Go program using the real
sdk/go/ration module (replace-directive to this repo) issued a card
through the gateway, closed it, confirmed idempotent re-close, confirmed
AdjustCardLimit now correctly rejects the closed card, and confirmed an
unknown card_id fails the same way GetCard/AdjustCardLimit already do.
`ration status` showed the full $100 hold released back to Available.
Separately, a throwaway Rust binary against the real ration-client
crate (path dependency) first proved the pre-fix gap live (Client::connect
with zero credential against the real auth-required gateway ->
Unauthenticated), then used connect_with_api_key to run the identical
issue/close/idempotent-close/adjust-limit-rejected/unknown-card cycle
successfully, independently confirmed via `ration status` that the
$75 hold was released.

make build (full Rust+Go+SDK), go vet across every Go module, cargo
build --release, cargo clippy, cargo fmt all clean, 0 regressions.
cargo test for ration-client remains pre-existing-broken only on its
FakeGateway test fixture missing close_card/get_dashboard_snapshot
(round 3's already-flagged, intentionally-not-fixed gap, per the
no-test-infra-work standing rule) — unaffected by this change since
make build never runs cargo test for this crate.
2026-10-29 12:19:19 +03:00
c3236f0bca feat(card-issuance,gateway,cli): add CloseCard — issued cards could never be shut off
CARD_STATUS_SUSPENDED/CLOSED have existed in common.proto since the
original build, and the Airwallex client package even defined
CardStatusSuspended/CardStatusClosed constants, but nothing in this
repo ever transitioned a stored card into either state: card-issuance's
airwallex.Client interface only exposed IssueCard/GetCard/
SetCardControls (limit/controls only, never status), so a leaked
credential, an offboarded cardholder's card, or any card that should
stop spending forever had no real operator path to close — only
"adjust-limit" to a smaller (but still nonzero-possible, still active)
limit.

Adds card_issuance.proto/gateway.proto's CloseCard RPC, a real
airwallex.Client.CloseCard on both Mock and Live (POST
/api/v1/issuing/cards/{id}/close), cardsvc.Service.CloseCard (releases
the card's full remaining ledger HOLD back to the tenant's available
balance, idempotent on an already-closed card), the gateway fan-out,
and `ration card close --card <id>`. AdjustCardLimit now rejects a
closed card instead of silently reopening a zombie hold.

tenantauth/ratelimit needed zero changes: both resolve card_id via
reflection, so CloseCardRequest's card_id field is automatically
tenant-scoped and rate-limited the same way GetCard/AdjustCardLimit
already are.

Verified live against the real bare-metal 7-service stack
(scripts/run-demo.sh): issued a real card (Held 1,000.00 USD), closed
it (status CLOSED, Held back to 0.00, Available back to 7,500.00),
re-closed it (idempotent — Available unchanged, no double-release),
confirmed adjust-limit on the closed card is rejected, and confirmed
closing an unknown card_id surfaces the same NotFound-wrapped error
GetCard/AdjustCardLimit already do. verify-chain: intact (5 records).
`go build`/`go vet` clean across every Go module (gateway,
card-issuance, cli, tui, auth, tenant-registry, webhook-ingestion,
agent, audit-log, sdk/go/ration), full `make build` (Rust+Go+SDK)
clean, 0 regressions.
2026-10-29 11:35:23 +03:00
26c3038ea8 fix(tenant-registry): require an operator credential on inbound RPCs — CreateTenant/ListTenants were reachable with zero auth
tenant-registry's own gRPC server (CreateTenant/GetTenant/ListTenants)
had no inbound auth check at all, unlike gateway's internal/tenantauth
and ledger-core's src/tenantauth.rs. Since it mints and attaches its
own pre-provisioned operator JWT to every ledger-core call it forwards
regardless of caller identity, ANY network caller to its gRPC port
(published 0.0.0.0:7011 in docker-compose.yml) could onboard unlimited
platform tenants or list every tenant's name/currency/reserve-floor
with no credential whatsoever — a real, newly-live gap since round 9
wired `ration tenant create/list` to this exact RPC surface.

Adds services/tenant-registry/internal/operatorauth (mirrors gateway's
tenantauth credential handling, simplified for the operator-only case),
gated by RATION_TENANT_REGISTRY_REQUIRE_OPERATOR_AUTH (true by
default). `ration tenant create`/`list` now mint and attach their own
operator credential, same pattern the CLI's other commands already use
for gateway/ledger-core.

Verified live against the real bare-metal stack: a throwaway gRPC
client with no credential gets Unauthenticated, a garbage bearer token
gets Unauthenticated, a valid but non-operator (tenant-scoped) API key
gets PermissionDenied, and the real `ration tenant create`/`list`
commands succeed end-to-end with their own minted operator credential.
go build/vet/test clean across tenant-registry and cli, 0 regressions.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 10:54:39 +03:00
09e0d07108 feat(cli): add ration tenant create/list — tenant-registry had zero real callers
services/tenant-registry implements real tenant CRUD (CreateTenant/
GetTenant/ListTenants, validated, delegating to ledger-core) and is
started by every demo/deploy path (run-demo.sh, start-individually.sh,
docker-compose.yml) alongside every other service — but nothing in
this repo ever dialed it. `ration seed` creates its 3 fixed demo
tenants by calling ledger-core's own CreateTenant RPC directly
(internal/demoseed), bypassing tenant-registry entirely, and no CLI/
TUI/gateway command ever called it either. An operator had no way to
onboard a new platform tenant into a running deployment without
editing demoseed.Tenants() in Go source and rebuilding.

Adds internal/tenantregistryclient (mirrors the CLI's existing
authclient Dial/Close shape) and `ration tenant create`/`ration tenant
list`, following the same tabwriter/moneyfmt conventions apikey.go and
status.go already established.

Verified live against the real 8-service bare-metal stack
(scripts/start-individually.sh): `ration tenant list` on an empty
store reports no tenants; `ration tenant create --name "Acme Platform
Payouts" --currency USD --reserve-floor-minor-units 500000` returns a
real tenant_id; it then appears in both `ration tenant list` and
`ration status --tenant <id>` (ledger-core's own independent read
path), proving tenant-registry persisted through to the same
authoritative store `ration seed` and every other command already
read from — confirmed again after running `ration seed` alongside it
(all 4 tenants listed together). Missing --name and a non-3-letter
--currency both fail fast before dialing anything. go build/go vet/go
test clean for services/cli, 0 regressions; full `make build-go`
clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 10:20:15 +03:00
972f70f6b9 feat(tui): add an interactive issue-card/adjust-limit form — Cards tab was read-only
PLAN-2026-10-23-DEEP.md's own "Remaining" note for the Cards tab was
still true: no in-TUI IssueCard/AdjustCardLimit form, CLI/API only.
Round 7 closed the CLI half of this gap; this closes the TUI half.

- New modal (services/tui/internal/model/cardform.go,
  internal/view/cardform.go): press `n` on the Cards tab to issue a
  card (tenant picker defaulting to the selected row's owner,
  cardholder/limit/interval/currency fields), `a` to adjust an
  existing card's limit (pre-filled from the selected row). Submits
  via two new client.Clients methods (IssueCard/AdjustCardLimit) that
  call the same gateway RPCs the CLI's `ration card` commands use.
  On success the form closes and triggers an immediate refresh; on
  failure (validation or a real RPC rejection) it stays open with the
  error shown and prior input preserved, so the operator can fix and
  retry without re-entering everything.
- Real bug found live, not by reading code: the field-typing handler
  only ever appended msg.Runes[0], assuming one KeyMsg per keystroke.
  bubbletea's input reader batches consecutive printable bytes read
  in one syscall into a single KeyMsg carrying multiple runes — typing
  (or pasting) a cardholder name arrived as one such batched message,
  so every character after the first was silently dropped. Fixed to
  append every rune in the batch; re-verified with multi-character
  names/limits typing correctly.

Verified live against the real bare-metal 7-service stack (audit-log,
ledger-core, auth, tenant-registry, card-issuance, webhook-ingestion,
gateway — started individually with inter-service delays, the same
round-6/7-documented workaround for this shared box's sibling-agent
load), driven through a real pty via tmux send-keys (not code reading):
seeded 3 tenants, opened the issue-card form, picked a tenant, typed
cardholder "Jane Operator", limit 250000, interval daily, submitted —
card appeared in the Cards tab and in `ration status`'s independent
CLI output (card_7816bf..., ACTIVE, $2,500.00, daily). Opened
adjust-limit on that card, backspaced/retyped the limit to 500000,
submitted — `ration status` confirmed $5,000.00 and the correct new
Held balance. Checked both error paths live: empty cardholder is
rejected client-side before any RPC; a limit request exceeding the
tenant's real reserve-floor headroom returns the actual
card-issuance rejection into the still-open form. `go build`/`go vet`/
`go test ./...` clean for services/tui; full `make build` (Rust+Go+SDK)
clean.

Also added scripts/start-individually.sh, a reusable version of the
manual individual-service-startup workaround rounds 6/7's build logs
already documented ad hoc for this box's contention — same PID-file
format as run-demo.sh, so scripts/stop-demo.sh tears it down too
(verified: it did).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 08:49:56 +03:00
a1bafb2f56 feat(cli): add ration card — issue/get/list/adjust-limit were only reachable via raw gRPC/REST
gateway.IssueCard/AdjustCardLimit/GetCard/ListCards have existed since the
original build and `ration status` already read ListCards, but no CLI
command ever called IssueCard or AdjustCardLimit — a judge or operator
running the documented demo flow had no way to actually issue a card or
change its limit from the terminal, only observe cards created as a side
effect of the agent's own RationBridgeFunding decisions. Adds `ration card
issue/get/list/adjust-limit`, following the same dialClients/tabwriter
conventions apikey.go and status.go already use.

Verified live against the real bare-metal 7-service stack (seed -> card
issue -> card get -> card list -> card adjust-limit raise -> status shows
the raised hold -> card adjust-limit lower -> status shows the released
hold), not just a build check.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 07:40:12 +03:00
b8166daecf fix(card-issuance): velocity cap stayed permanently blocked after the first real bridge grant
card-issuance's own RecordAgentDecision snapshot (recordDecision in
internal/bridge/service.go) never carried deposit_id, unlike the
agent's separate tools.go-recorded decision for the same event. The
agent's hasOpenGrantWithinWindow (services/agent/internal/loop/runner.go)
resolves every recent RATION_BRIDGE decision's deposit_id to check
whether its backing deposit has since been repaid (rule 3's "unless
fully repaid" exception) — when it can't resolve a deposit_id it fails
closed and blocks. Since card-issuance's own decision row could never
be resolved, ONE successful bridge grant, ever, permanently
velocity-capped the tenant for the rest of the decision-history
lookback window, even after that exact deposit was received and its
hold released.

Fixed by setting policySnapshot.DepositID from the matched late
deposit, same as the agent's own snapshot already does.

Verified live against the real bare-metal stack (ledger-core, auth,
tenant-registry, card-issuance, webhook-ingestion, gateway, agent):
granted and repaid (via a real signed webhook) two separate bridge
grants for one tenant, then confirmed a third late deposit still got a
real grant on its first tick. Reproduced the bug for real by rebuilding
card-issuance from the pre-fix commit: with that binary, deposit B was
declined with "velocity cap ... has not yet been repaid" on every
single tick after deposit A was repaid, and never granted at all.
go vet/go test clean for services/card-issuance and services/agent.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 04:37:12 +03:00
9972a6b846 feat(auth,cli): add ration apikey list; fix(docs): THREAT-MODEL.md was stale about its own closed gaps
`apikey issue`/`revoke` had no read side: an operator could mint or
revoke a key by key_id, but had no way to discover what key_ids exist
in the first place — only a key_id personally kept from its own
one-time `issue` output could ever be acted on. Adds auth.proto's
ListAPIKeys RPC, apikey.Store.List (sorted, tenant-filterable), the
server implementation, a CLI authclient wrapper, and `ration apikey
list [--tenant <id>]` — never returning the plaintext secret, which is
never stored anywhere after issuance.

Verified live against the real bare-metal 8-service stack
(scripts/run-demo.sh): issue -> list -> simulate-deposit --late ->
agent poll -> status (real recorded bridge-funding decision) ->
revoke -> list again (revoked: true) -> verify-chain (intact).
docker-compose rebuild was blocked by genuine host-disk exhaustion
from concurrent sibling workflows on this shared machine, not by
anything in this diff (pure proto/Go, zero compose/env changes).

Also corrects docs/THREAT-MODEL.md's "Known gaps" items 1, 6, and 7,
which still described tenant-auth, encryption-at-rest, and terminal-
injection as open/off-by-default despite rounds 2-4 actually closing
all three (RATION_GATEWAY_REQUIRE_TENANT_AUTH and
RATION_LEDGER_REQUIRE_TENANT_AUTH both default true, AES-256-GCM is
live on ledger-core's WAL/SQLite, pkg/textsanitize is wired into
cli/tui) — a judge reading the old text would see a security posture
strictly worse than what the code ships. Appends a short, honest
"Updates since initial submission" section to docs/SUBMISSION.md for
the same reason, without touching its original round-1 content.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 02:58:21 +03:00
4643906b25 feat(cli,auth): add ration apikey revoke — close the gap where issued API keys could never be turned off
services/auth already implemented the RevokeAPIKey RPC (proto/auth.proto,
backed by internal/apikey.Store.Revoke) since the section-1 split, but
nothing in this repo ever called it: `ration apikey issue` (round 3) could
mint a platform customer's sdk/go/ration credential, but there was no
operator-facing way to invalidate a leaked or rotated one. Added
RevokeAPIKey to the CLI's authclient wrapper and a `ration apikey revoke
--key-id <id>` command.

Verified live against the real bare-metal stack (scripts/run-demo.sh):
issued a real key via `ration apikey issue`, used it successfully through
the actual Go SDK (sdk/go/ration) to IssueCard against the containerless
gateway on localhost:7002, ran `ration apikey revoke --key-id <id>`, then
re-ran the identical SDK call — it now fails with
`Unauthenticated: tenantauth: invalid credential: revoked`. Also checked
idempotent re-revoke, an unknown key_id (NotFound), and the missing-flag
error path. `go build ./...` and `go vet ./...` clean across services/cli;
existing `go test ./...` for services/cli unaffected (no new test
infrastructure added, per standing rule).
2026-10-29 00:55:43 +03:00
92370eba5e feat(sdk,cli): self-serve API keys for Go SDK callers; fix(infra): docker-compose's missing AUTH_GRPC_ADDR/AUTH_ADDR broke every service but ledger-core
sdk/go/ration had no way to attach a credential, so its own README/doc.go
"Typical use" example was rejected with codes.Unauthenticated against any
default-config gateway (RATION_GATEWAY_REQUIRE_TENANT_AUTH defaults to
true) — nothing in this repo even called auth.IssueAPIKey before this.
Adds ration.WithAPIKey/WithBearerToken dial options (mirroring every
internal services/*/internal/authclient package's own interceptor
pattern) and a new `ration apikey issue` CLI command that actually mints
one via auth.IssueAPIKey. Verified live against a real running
auth+gateway+ledger-core+tenant-registry+card-issuance+webhook-ingestion
stack: no credential -> Unauthenticated, bad credential -> Unauthenticated
"invalid credential: not found", real minted credential -> IssueCard
succeeds end to end.

Also found, live, by actually running `docker compose up --build` for
real (not by reading code): gateway, card-issuance, tenant-registry,
webhook-ingestion, and agent all crash-looped forever in a plain
`docker compose up --build` — every one of them mints an operator JWT
from auth at startup and os.Exit(1)s if that fails, and none of their
compose service blocks set the env var each one's own config actually
reads (AUTH_GRPC_ADDR for all but gateway, which uniquely reads
AUTH_ADDR). Only ledger-core had this fixed previously (round 2). This
meant the entire containerized stack was non-functional end to end, not
just ledger-core's corner of it. Fixed all five; re-verified by tearing
the whole stack down and bringing it back up from scratch, seeding
tenants via `docker compose run --rm cli seed`, minting a real API key
via `docker compose run --rm cli apikey issue`, and issuing a card via
the Go SDK against the real containerized gateway on localhost:7002.

Also fixed a separate real bug in scripts/run-demo.sh's .env loader,
found live the same way: `IFS='=' read -r key value` silently drops a
single trailing IFS character, truncating any .env value ending in
exactly one '=' by one character — which is *every* `openssl rand
-base64 32` key (the exact command this repo's own docs recommend for
RATION_LEDGER_ENCRYPTION_KEY/AUTH_JWT_SIGNING_KEY), since a 32-byte
input always base64-encodes with exactly one padding '='. Reproduced
live: a real generated key crashed ledger-core at startup with
InvalidBase64(InvalidPadding) on a plain scripts/run-demo.sh run.
Switched to parameter-expansion splitting on the first '=' only;
re-verified the full run-demo.sh -> seed -> status cycle with a real
generated key, confirmed ledger.wal/ledger.db are genuine ciphertext
under the correct, untruncated key.

cargo test/go test/go vet all still pass (pre-existing, unrelated:
sdk/rust/ration-client's own #[cfg(test)] FakeGateway fixture doesn't
implement a newer Gateway trait method and fails to compile under
`cargo test` — a test-fixture-only gap, left alone per standing no-new-
test-work policy; production cargo build is unaffected).
2026-10-28 21:10:09 +03:00
353d46c164 docs: commit round-1 planning docs (architecture, deep plan, strategy)
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.
2026-10-28 02:18:41 +03:00
231c37cab9 docs: round-2 build log, RUNBOOK encryption section, demo recording script
Documents a6aad08/83916f8 in BUILD-LOG-2026-10-23.md's "Round 2 of 3"
section (SQLite column encryption + the two live bugs found closing it
out), adds a RUNBOOK.md entry for RATION_LEDGER_ENCRYPTION_KEY now that
it covers both the WAL and SQLite columns, and adds
scripts/record-demo.sh — narrates docs/DEMO-SCRIPT.md's exact sequence
with real pacing, built to be captured with `asciinema rec demo.cast -c
scripts/record-demo.sh` for the hackathon submission's video
walkthrough. Also ignores demo-video/, the gitignored output directory
that script's rendered .mp4/.cast land in (never source, never
committed).
2026-10-28 02:18:36 +03:00
83916f888a fix(infra): wire AUTH_GRPC_ADDR for ledger-core in docker-compose.yml
ledger-core's compose entry never set AUTH_GRPC_ADDR, so
src/main.rs's env_or("AUTH_GRPC_ADDR", "localhost:7010") default
resolved to the ledger-core container's own loopback, not the `auth`
service's. RATION_LEDGER_REQUIRE_TENANT_AUTH defaults to true and the
authclient channel is lazy (src/authclient.rs), so the container would
start fine but every real tenant-scoped RPC would then fail its
credential check against an address nothing listens on there — a
docker-compose-up--build deployment of this repo was silently broken
for anything beyond a health check.

scripts/run-demo.sh never hit this because every service there runs on
the same host, where localhost:7010 really is auth's bind address;
only the compose network, where each service is its own namespace,
needed the explicit service-name override every other direct
ledger-core caller already has for LEDGER_CORE_ADDR. Found while
preparing this repo for a real containerized deployment target.
2026-10-28 02:17:25 +03:00
a6aad082c6 feat(ledger-core): encrypt SQLite's free-text columns at rest
Finishes the one item round 1's build log explicitly scoped but didn't
land: column-level AES-256-GCM encryption for deposit.external_ref,
ledger_entries.reference/memo, and agent_decisions.trigger/rationale/
policy_snapshot_json, reusing the same RATION_LEDGER_ENCRYPTION_KEY
that already encrypts the WAL (wal_crypto.rs). tenant_id, amounts,
timestamps and enums stay plaintext, same as before — they're the
WHERE/ORDER BY columns every query filters or sorts on.

ledger_entries.reference is also the one column a real query filtered
on (bridge-hold-release matching by `bridge:<deposit_id>:*` LIKE +
exact-match prefix). Since AES-GCM ciphertext can't support that,
list_outstanding_bridge_holds_for_deposit now fetches by the
(unencrypted) tenant_id/entry_type pair and matches the decrypted
reference in Rust instead of in SQL — covered by a new regression test
run both with and without encryption enabled.

Also fixes a real bug found verifying this live against scripts/
run-demo.sh: RATION_LEDGER_ENCRYPTION_KEY set to an empty string (the
exact value .env.example documents, and the exact value run-demo.sh's
load_env_file falls back to when the var is never set by hand) made
wal_crypto::Key::from_env() attempt to parse a zero-byte key and crash
ledger-core at startup with WrongKeyLength(0) — meaning a totally clean
`scripts/run-demo.sh` run, the default/documented judge path, could
never start. from_env() now treats empty the same as unset, matching
main.rs's own auth_grpc_addr.is_empty() convention one function away.

Verified: cargo test 70/70 (51 lib incl. 7 new encryption tests + 19
integration), cargo clippy clean, cargo fmt clean. Live against the
real demo stack with RATION_LEDGER_ENCRYPTION_KEY set: ledger.wal and
ledger.db are genuine ciphertext on disk (grep/JSON-parse both fail),
`ration status`/`ration audit-check`/`verify-chain` all read back
correctly decrypted data, and a full seed -> simulate-deposit --late ->
agent poll -> partial bridge grant -> 24h velocity-cap decline cycle
ran with zero regressions. Live again with the var unset entirely
(the previously-broken path): ledger-core now starts and the same
cycle runs correctly in plaintext mode.
2026-10-28 02:17:15 +03:00
2bbe01151f docs: build log for round 1 of 3 2026-10-23 20:07:43 +03:00
3376017032 fix(agent): velocity cap no longer blocked by a grant that never executed
processLateDeposit unconditionally records a RATION_BRIDGE-tagged
"envelope pre-check" decision before ever attempting the LLM/tool call
that would actually move money — found live while verifying the
circuit breaker (internal/llm/breaker.go): when that first LLM attempt
failed outright (e.g. the provider being transiently unreachable,
before the breaker even trips), hasOpenGrantWithinWindow treated that
pre-check recording as "an open unrepaid grant" and velocity-capped
every later attempt against the same deposit for a full 24h — even
though no money had ever actually moved and the breaker's whole point
is to execute that same envelope directly once tripped.

hasOpenGrantWithinWindow now only counts RATION_BRIDGE decisions whose
snapshot actually includes granted_minor_units (new
wasActuallyGranted helper) — the key only llm/tools.go's
handleRationBridgeFunding sets, on a real executed grant, never the
pre-check recording. Updated the two existing velocity-cap test
fixtures to include it, since a real "open prior grant" always has it
too.
2026-10-23 20:04:57 +03:00
cb87e97e5a feat(ledger-core): encrypt the WAL at rest with AES-256-GCM
docs/THREAT-MODEL.md's "Known gaps" #6: the WAL and SQLite index are
fully plaintext on local disk today.

Add src/wal_crypto.rs: AES-256-GCM envelope encryption (pure Rust, no
OpenSSL linking) keyed from RATION_LEDGER_ENCRYPTION_KEY
(base64-encoded 32 bytes — a dev stand-in for a real KMS/Secrets
Manager key, per this gap's own wording). Wire it into
append_and_commit/replay_wal_into_index so every WalEvent is encrypted
before wal_ffi::Wal::append ever sees it, and decrypted in the recovery
callback before JSON deserialization. This is the correct boundary,
not a compromise: wal_ffi's own interface already treats a payload as
an opaque &[u8], so this requires zero changes to the C WAL's frame
format, CRC, or recovery/truncation logic (services/wal/wal.c,
docs/formal's TLA+ spec).

Disabled by default (same opt-in posture as every other control here
that changes an on-disk format); Ledger::open_with_encryption's doc
comment spells out that this is not a live migration path. Verified
live: the on-disk WAL file is genuine ciphertext (no plaintext tenant
names, not valid JSON), a full seed/deposit/bridge-funding demo cycle
runs correctly against an encrypted ledger, and two new integration
tests prove a real restart-and-recover round trip plus loud failure on
a wrong key.
2026-10-23 20:04:39 +03:00