Skip to content

fix(app): one ledger, one uploader for phone audio custody - #23288

Merged
Git-on-my-level merged 14 commits into
mainfrom
unified-phone-audio-custody
Oct 22, 2026
Merged

Git-on-my-level merged 14 commits into
mainfrom
unified-phone-audio-custody

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Watch recovery files currently create one Home row per minute and use a second upload queue without the live session binding. Unify phone audio custody in LocalWalSyncImpl so one durable ledger owns uploads, job reconciliation, ownership and release. Explicit Transcribe Later stays manual; automatic phone fallback, Limitless and uncovered Watch copies drain through Sync.

Path inventory

Before After
Live websocket audio plus the WAL safety copy Live path retained; Watch safety copies are checkpointed before receipt dedupe
Device ring, multi-file, SD and flash drains each serialize/register chunks All four call the ledger's shared persistDeviceChunk, preserving bytes, filenames and collision policy
Native batch provider scans files, claims owners, uploads, polls, auto-retries and deletes Native intake admits files into wals.json; LocalRecordingsProvider is a view of holdForUser WALs with playback/share controls
localRecordingJobs and omibatch_owners.json sidecars Legacy jobs/owners migrate into WAL metadata; migration sources retire only after durable admission
Overflow foreground/background depend on the provider scan and owners file On-device overflow intake owns discovery and registers onDeviceOnly WALs before legacy ownership metadata retires

The remaining audio paths are live streaming, custody upload, and on-device transcription from custody. Pure policy and shared device persistence live in parts of the LocalWalSync library (wal_policy.dart, wal_job_reconciliation.dart, device_chunk_persistence.dart); its main file shrinks. The identity-fenced flag reader is a private part of the analytics library, and the oversized analytics manager also shrinks. No backend, firmware, native writer or Watch app changes. Native filenames remain unchanged.

Custody invariants and tests

  • One uploader: the source scan in local_recordings_auto_upload_test.dart rejects calls to SyncUploadGate.upload outside the ledger, direct upload/poll calls outside the ledger and HTTP API client, and custody endpoint strings outside the ledger and HTTP client/routing telemetry. Each of the three raw-API guard branches was mutation-tested: a temporary violating source line failed the scan, then was removed.
  • Delete only on confirmation, user action or proven Watch redundancy: existing WAL reconciliation/retention/durability suites plus watch_custody_dedupe_test.dart; queued migration retains local files.
  • Owner before use: local_recordings_owner_test.dart covers signed-out intake, account switching, committed Watch receipt ownership, corrupt legacy metadata, parked foreign WALs and overflow migration.
  • Idempotent intake and restart-safe legacy job migration: local_recordings_auto_upload_test.dart, including failed index persistence and retry; sync_poll_storm_test.dart proves migrated jobs use the same poll budget.
  • User consent: persisted holdForUser defaults false for old WALs, blocks automatic drains/orphan repair, and remains on Home while an accepted job processes. Completion clears the hold; job failure leaves it available for explicit retry. Acceptance, completion, failure, and the processing row are covered by the custody, completion, and real-page render tests.
  • Watch dedupe: owner-scoped merged coverage, seven-day expiry, 95% threshold, retained native receipts, uncovered auto custody and enabled/unknown/failed kill-switch reads in watch_custody_dedupe_test.dart. Journal v2 separates durable coverage from server-reachable coverage (conversation binding, server confirmation, or a drainable miss WAL). Unbound coverage defers the recovery copy for 30 minutes from its receipt mtime before auto admission. Tests prove deferral, later conversation binding then deletion, timeout auto admission, miss deletion, rejection of old unclassified journals, durable-file/index ordering, and session-preserving checkpoints.
  • Confirmed queued jobs publish completed conversation IDs through the ledger to the Home view; native_completion_surface_test.dart proves migrated jobs surface once and failed partial jobs do not publish completion, and a manual acceptance wakes reconciliation with auto upload disabled while keeping the Home row through processing and failure.
  • Home: phone_custody_home_render_test.dart mounts the real conversations page over mixed ledger custody, asserts one manual row, and excludes twelve Watch segments, automatic phone fallback and Limitless from Home rows.
  • Device serializer: golden bytes, original names/collision suffixes and flash naming override in local_recordings_auto_upload_test.dart; existing device durability tests exercise producer registration.
  • Geolocation and exact frame counting: native_batch_geolocation_test.dart and batch_frame_count_test.dart now test ledger intake/drain and the shared frame walker.

Migration and rollout

On for everyone, kill switch only. Missing/unknown/error flag reads remain fail-safe: keep and upload. No remote PostHog change was made by this branch.

Ramp at merge

The parent creates the PostHog watch_copy_dedupe_off flag at merge, resolving false for everyone (dedupe on). Until that happens, the missing flag keeps dedupe inactive. Rollback: set the flag true for everyone; recovery files stay and upload through the ledger.

Monitor the new registered PostHog event Native Custody Observed, counting outcome=watch_deleted, watch_deferred, and watch_uploaded by mobile namespace and build. watch_uploaded counts accepted uploads, not intake intentions; deferrals count each scan, not unique files. The checked-in native-custody-health consumer defines the query and no-data policy. The release must stay clean of unexpected deletion/upload ratios, sustained deferral growth, and duplicate-conversation reports; missing telemetry is unknown, never proof of safety. Corrupt jobs, recurring legacy owner deferrals, and directory mismatches have separate bounded outcomes, without private paths or filenames.

Contract changes in CUSTODY.md: invariant 1 also guards raw upload/poll/endpoint bypasses; invariant 3 preserves uncertain legacy ownership while admitting provably newer files and receipt-owned Watch files; invariant 4 quarantines malformed jobs once and continues; invariant 5 requires server-reachable proof, defers unbound coverage, and names the 30-minute timeout; invariant 6 keeps manual jobs on Home until completion. Directory mismatch emits telemetry and defers before indexing inaccessible audio.

Validation

Review round 1, final tree after integrating origin/main (93e8fd739bd): focused custody tests 52 passed; all three raw-API source-scan mutations failed as expected and were removed; pending/processing real-page renders 2 passed with PNG capture and visual inspection. Serial suites: unit 2,676 passed / 2 skipped; providers 1,004 passed; widgets 1,695 passed / 2 skipped; performance 25 passed; pages 253 passed. Total: 5,653 passed, 4 skipped. Flutter analyze on all 48 changed Dart files: no issues. Localization check: 49 locales, 4,241 keys. make preflight: all 29 checks passed in 88.74 seconds, including dead-code and product-file line-count ratchets. The mandatory pre-push gate also passed: 29 checks in 35.64 seconds, Flutter generated-output validation, and formatting (47 files, zero changes). The remote review branch was verified at bc6b132; no PR was opened or merged. No live backend or GCP tier used.

UI-Evidence: .agent-artifacts/ui-evidence/unified-phone-audio-custody/001-mobile-ios-phone-custody-home.png — real Flutter conversations page, synthetic data, iOS metrics and real fonts, visually inspected. One Transcribe Later row remains; automatic custody recordings do not appear as Home rows. 002-mobile-ios-phone-custody-processing.png also proves the accepted job stays visible while processing.

Home with one manual recording row

Manual recording remains visible during processing

Product invariants affected

  • INV-CAP-1: capture retains Watch audio durably even after socket sends and keeps active session identity across receipt checkpoints.
  • Audio preservation/ownership: app/lib/services/wals/CUSTODY.md invariants 1–6, tested above. Server acknowledgement and local durability remain separate facts.
  • INV-PERF-1: asynchronous directory/file operations; bounded streaming frame counting; growing migration/journal JSON uses offUiIsolate. Remove the provider's extra polling/auto-upload loops; coalesce view refreshes and invalidate Home only for user-held WAL changes. The mobile UI-isolate and dead-code ratchets pass; serial performance suite results are recorded above.
  • Existing mobile UI primitives and strings are reused. No localized strings changed.

Failure-Class: FC-split-mutation-authority

Two competing audio lifecycle owners caused duplicate conversations, divergent ownership and upload policy. The shared ledger plus the one-uploader source guard removes the competing mutation authority.

Mobile changelog: app/changelog/unreleased/20261022-unified-phone-audio-custody.json (fix; the mobile fragment schema stores only change/platforms, so no unsupported kind field is emitted): Watch recovery recordings no longer flood Home or create duplicate conversations when their audio is already held on the phone.

Open risks: dedupe intentionally keeps audio when coverage or flags are unavailable, so those copies still rely on server time binding; physical Watch transfer and app-kill behavior are not exercised by hermetic Flutter tests. Seven-day journal expiry deliberately favors keeping recovery audio. The expected PostHog kill row must resolve false for dedupe to run; no remote row was provisioned here. Potentially legacy-owned files remain deferred when ownership metadata is corrupt and need owner metadata repair; provably newer recordings continue normally. Corrupt jobs are quarantined and may cause a legacy in-flight upload to be retried; server time binding remains the dedupe fallback. Unbound Watch recovery is admitted only on a subsequent scan after the 30-minute bound.

Review

  • Independent GLM review of d3c9afe returned SHIP_WITH_FIXES with six findings (Watch dedupe trusting transport-only coverage, corrupt legacy sidecars blocking intake, a narrow uploader lint, Transcribe Later rows leaving Home at 202, a directory mismatch). All six are fixed in this PR with tests.
  • Parent review: a stale batchAudioDir (an iOS update can move the app container) originally halted intake until the next batch capture. Intake now scans the documents directory the ledger resolves against, repoints batchAudioDir, and still emits directory_mismatch (native_recording_directory_test.dart).

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

Git-on-my-level and others added 14 commits October 22, 2026 16:17
Persist user holds, migrate legacy jobs and owners, and dedupe Watch recovery copies against durable live custody. Keep overflow discovery in the on-device owner.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Preserve each drain’s existing length-prefixed bytes, filenames and collision sequence while centralizing admission and durable WAL registration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Capture synthetic iOS evidence with one manual recording row and no automatic Watch, phone-fallback or Limitless rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…itch

Keep oversized product files below their previous size by extracting ledger policies and shared persistence into library parts. Catalog Dart kill-switch constants and cover the discovery rule with a fixture.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Coalesce concurrent view refreshes and publish already-owned ledger rows even when legacy sidecars defer new admission. Cover the malformed-sidecar case and keep automatic sync updates quiet on Home.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep the user-facing custody fix in the mobile change entry; mobile fragments accept change/platforms and do not support a kind field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Avoid quota preparation and automatic progress work when only explicit Transcribe Later recordings are waiting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Publish completed-job conversation IDs from the ledger after persistence and reuse the recordings view’s existing conversation projection. Keep failed partial jobs out of the completion hook and fence account changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Distinguish server-reachable Watch coverage from transport-only copies and
defer unbound receipts for at most 30 minutes before automatic admission.
Quarantine corrupt legacy jobs, preserve uncertain owners while admitting
new recordings, and report bounded custody outcomes and directory mismatches.
Keep manual recordings visible through processing and guard raw API bypasses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Preserve both flag catalog additions and document the Watch custody ramp.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Retain the user retry wake after acceptance while the recording remains visible on Home. Exercise acceptance, processing, wake scheduling and failed-job recovery end to end with auto upload disabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An iOS update can move the app container, leaving batchAudioDir pointing at the
old absolute path. Throwing there stopped all native intake until the next batch
capture rewrote it; scan the documents directory the ledger resolves against and
repoint batchAudioDir at it, still emitting directory_mismatch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-22T11:45:13.474489Z fed928f PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Git-on-my-level
Git-on-my-level merged commit 6f411f0 into main Oct 22, 2026
62 checks passed
@Git-on-my-level
Git-on-my-level deleted the unified-phone-audio-custody branch October 22, 2026 12:15
Git-on-my-level added a commit that referenced this pull request Oct 22, 2026
…TT, customer denominator, zero-decimal currencies

Luna review rev-23289-luna.md, all 4 P1 + 6 P2:

P1 Soniox staleness: the balance series is bounded by its last covered day
(SonioxBalanceInputs.lastDay); days beyond it fall back to the dated console
constant, unmeasured and flagged — never $0 spend or a phantom baseline_reset
(reset stays reserved for an actual lower cumulative balance; a covered day
with no row is 'snapshot_gap'). A series that no longer covers the cutoff day
marks the STT estimate stale immediately and the wall text names the break.

P1 per-vendor STT: the plan-cost query keeps stt_<vendor>_measured components
separate; Deepgram combines independently (measured usage, else its own Mercury
cash) so a Soniox measurement never hides Deepgram dollars and a Deepgram-only
aggregate is never presented as Soniox.

P1 denominator: cost per paying customer uses the average of daily paying
customers over the same 30-day window as the cost (stated; window-end count
and the pre-migration item sum are labelled fallbacks). The producer counts a
customer once per plan and book-wide (paying_customers, non_usd_paying_subs:
two new nullable plan_revenue_daily columns, added to a live table by one
idempotent ALTER TABLE in the loader; old artifacts load NULL; the wall query
falls back to the legacy shape while the columns are absent).

P1 zero-decimal currencies: minor units scale by the price's currency per
Stripe's zero-/three-decimal lists (JPY is never ÷100); mrr_usd is USD only —
non-USD payers stay counted, native amounts reported per currency, wall labels
MRR partial.

P2: grafana 'STT measured' carries only measured dollars (Soniox balance/usage
+ measured Deepgram); Modulate modelled and Mercury STT cash become their own
series. Stripe fees: documented fee contract (fee positive when assessed;
refunds hand fees back via negative fee_details summing to fee — cross-checked,
disagreement is a shape error) and foreign-currency fee rows surface as a
partial label instead of silent omission. Mercury SaaS days with incomplete
annual history gate to the dated estimate (annual_complete in the wall query);
the annual flip rule is documented with the Jul-Oct ledger evidence that no
vendor qualifies. Modulate reconciliation sums Mercury cash over the whole
window, including cash-only dates. The workflow mounts the two optional
org-key secrets only when the resource exists, so a non-provisioned target
project cannot block the deploy.

CI: test_sync_silent_failure's app-source pin follows #23288's move of the
reconcile code to wal_job_reconciliation.dart (main itself is red on the old
pin).
Git-on-my-level added a commit that referenced this pull request Oct 22, 2026
…nOps-book MRR, software cost per customer (#23289)

## Round 6 (2026-10-23): Luna r3 final item — annual SaaS completeness,
auto cadence, one-time backfill

**Failure-Class: none** (round 6 fixes code introduced by this PR; no
shipped failure class).

UI-Evidence: none -- round 6 touches finops scripts, the wall lib layer,
and tests only; no UI component or visual change.

Luna r3 (rev-23289-luna-r3) resolved everything except finding 4: the
`mercury_vendor_spend_daily` ledger starts 2026-07-04 (~109 days), so it
cannot rule out yearly bills, yet `mercury_costs.py` treated an empty
manual annual set as complete. A read-only 13-month Mercury check
confirmed real once-a-year charges outside the window (Modal Group, Inc.
$12,000 on 2026-01-08; several vendors posting exactly once in 12
months).

1. **Completeness gate.** `annual_history_complete` now requires a full
preceding 365 covered days and no above-threshold uncategorized
year-window spend — independent of any configured annual vendors (the
empty-map loophole is gone). While false, the new
`annual_history_reason` column names the blocking gate
(`history_under_12_months` or `uncategorized_above_threshold`) in
`mercury_saas_daily`, and the wall's SaaS line keeps the amortized
measured value but appends the partial note (e.g. "measured SaaS
(Mercury) $X/day (partial: SaaS ledger history under 12 months; one-off
vendors amortized ÷12, estimated)"). The old behavior — dropping a
short-history day back to the dated constant — is replaced by
measured-but-labelled-partial.

2. **Automatic cadence detection** (`detect_annual_charges`) replaces
the hand-maintained `annual: true` list. A saas charge is an annual bill
when it repeats about once per 12 months (304–426-day neighbour gap),
when it is ≥5× that vendor's other-charge median (≥3 other charges), or
— for a vendor seen exactly once — as an ambiguous one-off amortized ÷12
across its service year and reported as `estimated` in the new
`annual_estimated_usd` column. The vendor map's `annual: true` remains a
manual correction; `annual: false` means auto-detect. The detector is
category-parameterized (`CADENCE_CATEGORIES`); the run-rate line
amortizes only `saas` rows so STT/LLM cash never double-counts against
its own lines.

3. **One-time backfill.** `FINOPS_MERCURY_BACKFILL_DAYS` (91..400)
widens a single job run's Mercury pull to N posted days (13 months ≈
400) — the env route exists because the Cloud Run job invokes the pull
with fixed arguments. The aggregate artifact is keyed (date, vendor,
category) with duplicate keys rejected, and the loader's per-date
delete/insert transaction replaces the window, so re-running the
backfill re-derives identical rows — idempotent on (date, vendor). The
exact one-time deploy step (gcloud job env update → execute once →
remove var) is documented in `backend/scripts/finops/README.md`. Not run
against prod by this round.

4. **Vendor categories from the 13-month check** (company names only, no
person names): `modal group` alias (the $12,000 compute wire lands
`infra_non_gcp` — compute, not SaaS — instead of falling to
uncategorized other_opex); `www deepgram com` alias (the $40,758.67
2025-09-08 STT cash wire → `stt_vendor`, previously unmapped and would
have blocked completeness after backfill); named SaaS entries for
once-a-year Software posters (`vanta` $3,500, `mintlify` $3,034.50) and
monthly `greptile` so detection reads each vendor's own series instead
of the blended `mercury_category` aggregate; `Software Costs` joins
`Software & Subscriptions` as a saas category-data rule.

**Schema note:** `mercury_saas_daily` gains two columns
(`annual_estimated_usd NUMERIC`, `annual_history_reason STRING`) via the
loader's idempotent add-columns path; old rows load NULL and the wall
query IFNULLs both.

**Backfill step for the lead (one-time, after merge):** update the
deployed job's env with `FINOPS_MERCURY_BACKFILL_DAYS=400` (full list in
the README — `--set-env-vars` replaces the whole set), execute
`finops-unit-cost-job` once, then remove the var (or redeploy from the
workflow). After ~13 months of ledger, the SaaS line may flip to
complete — subject to the uncategorized year-window gate.

**Tests:** backend `test_finops_mercury.py` 31 passed — yearly-repeat,
monthly, one-off (estimated), outlier cadence, override, <365-day and
gapped history completeness, backfill window validation + byte-identical
idempotence, new aliases. web/admin `npm run check` green
(lint/typecheck clean, 1087 tests passed).

---

## Round 5 (2026-10-23): Luna r2 re-review fixes — 1×P1 + 4×P2

**Failure-Class: none** (all five items fix code introduced by this PR;
no shipped failure class).

UI-Evidence: none -- round 5 touches wall lib code, finops scripts,
tests, and one deploy workflow's secret-mount logic; no UI component or
visual change.

**P1 gap/reset days never book Soniox as $0**
(`web/admin/lib/wall-cost.ts`). A covered day with no published spend
row (snapshot gap) or a reset row previously took `spend ?? 0`, silently
dropping Soniox spend from the all-in total and cost per customer. Both
day kinds now take the labelled fallback — the FinOps usage line when it
has the day, else the dated console constant — unmeasured and flagged
(`snapshot_gap` / `baseline_reset`); an unknown day is never added as
$0. The wall text now states the dated estimate covers the day. Tests:
`wall-cost.test.ts` — the reset day carries the constant (the usage line
wins when present), the snapshot-gap day carries the constant, and a new
all-in test proves a gap day's and a reset day's totals equal a
no-series day's total (the total does not drop) while a published row
still measures; `wall-metrics.test.ts` reset-day value/text updated to
the new contract.

**P2 UGX/ISK backward-compatibility scaling**
(`backend/scripts/finops/pull_stripe.py`). Stripe's currencies "Special
cases" table (https://docs.stripe.com/currencies#special-cases): "UGX
transitioned to a zero-decimal currency, but backwards compatibility
requires you to represent it as a two-decimal value, where the decimal
amount is always `00`. For example, to charge 5 UGX, provide an `amount`
value of `500`." — the same rule is documented for ISK; HUF's and TWD's
special cases are payout divisibility only ("you can charge two-decimal
amounts"), so charges keep the default two-decimal handling. `ugx` is
removed from `ZERO_DECIMAL_CURRENCIES`; a new
`TWO_DECIMAL_COMPAT_CURRENCIES = {isk, ugx}` set divides by 100 ahead of
the zero-decimal set, so a UGX 500 price now reports native UGX 5
(previously UGX 500, 100×; it never entered `mrr_usd`). Test
`test_backward_compat_currencies_stay_two_decimal` quotes the doc and
pins UGX/ISK ÷100 and the HUF/TWD default.

**P2 dev-deploy safety for STRIPE_READ_API_KEY.** The two bindings this
PR added:

- `gcp_finops_unit_cost_job.yml` — the workflow's environment input is
selectable (`development` is even the dispatch default), so the read-key
mount applied to a non-prod target. It is now **required only in prod**;
a development deploy mounts it **only when the secret resource exists**
in the target project (the same existence-only `gcloud secrets describe`
gate the optional vendor keys use; no payload read). An unprovisioned
dev project can no longer fail the job deploy during secret resolution;
the Stripe legs then skip as unavailable. New pin:
`test_deploy_workflow_stripe_mount_cannot_fail_a_dev_deploy`.
- `config/public-build-contract.json` (admin target) — **no non-prod
target exists to fail today**, evidence: there is no
`omi-admin-dashboard` service in based-hardware-dev (verified
2026-10-23); the repo has no `development` branch (`git ls-remote` — the
admin workflow's development push trigger cannot fire), and every admin
deploy in the workflow run history is prod from `main`. The only
theoretical path is a manual workflow_dispatch with
environment=development, which would already fail the
deploy-public-build runtime preflight on the ~24 pre-existing
`WEB_ADMIN_*` contract bindings if based-hardware-dev lacks them — this
key adds no new class of failure to an unused path. Per the review's own
bar ("scope the binding ... or establish the development secret/accessor
contract **before using those deploy paths**"), first use of that path
still requires provisioning the dev secret (round 4's deploy-time step 2
stands).

**P2 annual SaaS: no annual vendor exists — ledger evidence
re-checked.** Re-ran the cadence analysis read-only
(`based-hardware.omi_finops.mercury_vendor_spend_daily`, full window
2026-07-04..2026-10-20, vendor/day aggregate sums only, no transaction
detail): every SaaS vendor is monthly (same-day-of-month repeats —
shopify the 3rd, posthog ~the 7th, nevercode the 1st-2nd, pinecone the
2nd, figma the 18th, sentry the 14th, cognition the 23rd, github the
26th, google_workspace the 1st-2nd), usage-based within a single month
(replicate 7 postings 10-06..10-14, klaviyo 5 postings 10-01..10-20), or
a $10-scale one-off (vercel $11.25 + $9.99; perplexity $10, not SaaS).
An annual bill would be a single large posting per year; none exists in
the window. The vendor map therefore keeps zero `annual: true` entries
(pinned by the committed-evidence test, whose docstring now carries the
2026-10-23 re-check), the `annual_history_complete` gate stays, and the
test that a future annual vendor degrades to a labelled partial stays.

**P2 refund fee sign follows the documented contract.**
`fee_minor`/`aggregate_fees` no longer claim refunds carry a negative
fee (Stripe documents no such shape): `fee` is "Represented as a
positive integer when assessed"
(https://docs.stripe.com/api/balance_transactions/object), the funds
direction lives in `amount` ("A positive value represents funds charged
to another party, and a negative value represents funds sent to another
party"), and the API's own documented example of a funds-out transaction
carries `fee: 0, fee_details: []`. The fixture now uses that documented
shape (refund row: negative amount, fee 0, empty details) and a new test
pins the handling rule: a non-zero fee on any row is taken **with its
own sign** — an explicitly represented fee return stays negative, a fee
assessed on a refund stays positive; no refund-specific sign is
invented. The `fee_details`-sums-to-`fee` cross-check is unchanged.

**INV-DATA-1** (same file as rounds 2/4): round 5 edits
`.github/workflows/gcp_finops_unit_cost_job.yml` again — the Stripe
mount becomes prod-required / dev-existence-gated; no job, trigger, or
input change, so no ci-budget bump (same precedent as round 4's edit).

**Tests.** Backend via `backend/test.sh` + `BACKEND_UNIT_TEST_FILE_LIST`
over the nine finops unit files: **171 passed** (3 new — UGX/ISK compat
scaling, dev-deploy mount gate, refund-fee sign rule; the refund fixture
reshaped to the documented shape). web/admin `npm run check` (lint +
typecheck + vitest): **1086 passed | 13 skipped** across 89 files.

---

## Round 4 (2026-10-22): Stripe read vs write split — least privilege

**Failure-Class: none** (new client split on code introduced in this PR;
no shipped failure class).

UI-Evidence: none -- round 4 touches server-side API routes, lib code,
CI, and JSON config only; no UI component or visual change.

A restricted read-only Stripe live key (`STRIPE_READ_API_KEY`, Secret
Manager, project based-hardware; accessors `finops-writer@` and
`omi-admin-dashboard-runtime@`) now backs every Stripe read in both
consumers.

**FinOps job.** `gcp_finops_unit_cost_job.yml` mounts
`STRIPE_READ_API_KEY` instead of the full `STRIPE_API_KEY`;
`cloudrun.py` `SECRET_FILES` and `pull_stripe.py`'s local `.env` read
are renamed to match — the producer no longer names the full key
anywhere (local runs need `STRIPE_READ_API_KEY=` in the omi-stripe skill
`.env`). The job never needs the full key again. A backend contract test
pins the mount name and fails if a full-key Stripe mount line returns.

**Admin dashboard (omi-admin-dashboard / admin.omi.me).**
`web/admin/lib/stripe.ts` gains `getStripeRead()` /
`getOptionalStripeRead()` on `STRIPE_READ_API_KEY`, with a
**one-time-warned fallback to the full key** so a deploy that lands
before the secret binding cannot take the wall down. Every read path
moved to the read client: the wall's subscription book and live
cross-check (`lib/wall-metrics.ts`), all `stats/*` Stripe routes
(profitability, mrr-trends, subscription-trends, subscriptions, revenue,
app-subscriptions), `omi/subscriptions`, `omi/payouts`,
`omi/all-payouts`, the `organizations` routes' payment-intent lookups,
and the affiliate-payouts account verification.
`config/public-build-contract.json` binds
`STRIPE_READ_API_KEY=STRIPE_READ_API_KEY:latest` for the admin service.

**Write call sites that keep the full key (exhaustive audit of
web/admin):** exactly **one** — `stripe.transfers.create` in
`app/api/omi/affiliate-payouts/route.ts` (POST `action=transfer`, the
affiliate payout, idempotency-keyed). Every other Stripe SDK call in
web/admin is a list/retrieve (`subscriptions.list`, `accounts.retrieve`,
`paymentIntents.retrieve`, `payouts.list`); there are no direct
`api.stripe.com` calls and no other
`.create/.update/.del/.cancel/refund/invoice` Stripe calls. The read
key's scope was verified live before the switch (read-only GETs):
subscriptions, balance transactions, charges, customers, invoices,
prices, products, coupons, transfers, subscription schedules, payouts,
payment intents, and connected accounts all return 200.

**Deploy-time steps for the rollout lead:**
1. On merge, the admin deploy (triggered by the
`config/public-build-*.json` path filter) binds `STRIPE_READ_API_KEY` on
`omi-admin-dashboard`;
`omi-admin-dashboard-runtime@based-hardware.iam.gserviceaccount.com`
already holds secretAccessor. Order cannot break the wall: until the
binding lands, reads use the full key with exactly one warning line.
2. **Development env:** create `STRIPE_READ_API_KEY` in
**based-hardware-dev** (a dev-scoped read key) before the next
development-branch admin deploy — `--set-secrets` fails if the resource
is missing in the target project.
3. Re-run the FinOps deploy workflow (workflow_dispatch, prod) from main
after merge so the job's mount swaps; the next daily run reads Stripe
with the restricted key.

**Tests.** web/admin +5 in `stripe-client-split.test.ts` (read client
constructed from `STRIPE_READ_API_KEY` when set and cached separately
from the full client; silent when set; full-key fallback warns exactly
once; quiet null + `getStripeRead` error naming both envs when nothing
is set; a source-scan pinning that only `lib/stripe.ts` and the
affiliate-payouts write route reference the full-key accessors) — suite
**611 passed | 13 skipped**, lint + typecheck clean. Backend:
mount-contract test added and secret-name pins renamed in
`test_finops_cloudrun.py`; **24 passed** across the finops
cloudrun/stripe-book/stripe-fees files; `check_ci_budget.py` passes vs
origin/main (no job/trigger/matrix change); line-count ratchet OK.

## Round 3 (2026-10-22): Luna review fixes (rev-23289-luna) — all 4 P1 +
6 P2 + CI

**P1 stale Soniox series can no longer read as $0 spend or a false
reset.** The balance series is now bounded by its **last covered day**
(`SonioxBalanceInputs.lastDay`): a day beyond it falls back to the
labelled, dated console constant — unmeasured and flagged — never USD 0
and never a `baseline_reset` (that label stays reserved for an actual
lower cumulative balance, the producer's null-usd row). A covered day
with no published row is flagged `snapshot_gap`. A live series that no
longer covers the settled cutoff day marks the STT estimate **stale
immediately** (not only once the 10-16 constant ages past 14 days) and
the wall text names the break with the last covered day and as-of.
Tests: `wall-cost.test.ts` (stale series → constant+flag, never
$0/reset; snapshot_gap; series bounds; broken → estimate stale now) and
`wall-metrics.test.ts` (wall-level text + no "balance reset" claim on
uncovered days).

**P1 STT aggregation keeps every vendor separate.** The plan-cost
BigQuery query now selects the `stt_<vendor>_measured` **component**
instead of collapsing them into one `stt` sum; the wall keeps
`Record<date, Record<vendor, usd>>`. Deepgram combines
**independently**: its measured usage when the FinOps line has it, else
its own Mercury cash — a Soniox measurement can never hide Deepgram
dollars, and a Deepgram-only aggregate is never presented as Soniox.
Validated live read-only: the new query runs against prod and returns
per-component rows (`stt_soniox_measured` first row). Tests:
`wall-cost.test.ts` (both-providers day counts both; Deepgram-only day
keeps the Soniox constant), `wall-finops` parse tests.

**P1 cost per paying customer uses a payer count over the SAME window as
the cost.** Denominator = **the average of daily paying customers** from
the FinOps book inside the 30-day cost window (snapshot-day count stated
in the metric reason); the window-end snapshot count and the
pre-migration subscription-item sum are labelled fallbacks. The producer
counts a **customer once per plan and once book-wide**, never per
subscription item: `stripe_plan_mrr.json` gains `paying_customers` /
`non_usd_paying_subs` (book-wide, repeated per plan row) and
`plan_revenue_daily` gains them as **two new nullable columns**, added
to the live table by one idempotent `ALTER TABLE … ADD COLUMN IF NOT
EXISTS` in the loader (old artifacts load NULL; the wall query falls
back to the legacy column set — verified read-only against prod, where
the V2 query fails today and the fallback parses). The wall takes MAX
per snapshot day, not the plan-row sum.

**P1 zero-decimal currencies are never divided by 100.**
`monthly_amount`/coupon `amount_off` scale minor units by the
price/coupon currency per Stripe's documented zero-decimal list (JPY,
KRW, VND, …; three-decimal BHD/JOD/KWD/OMR ÷1000). `mrr_usd` is **USD
only**: a non-USD price keeps its payer counted, reports its native
monthly amount per currency (`non_usd_mrr_native`), and the wall labels
MRR **partial** with the excluded payer count. Tests:
`test_finops_stripe_book.py` (JPY/KRW/VND/KWD scaling, annual ÷12 in
native, coupon scaling, non-USD exclusion+counting, JPY ¥1,200 ≠ $12).

**P2s.** Grafana "STT measured" now carries **only measured dollars**
(Soniox balance/usage + measured Deepgram); modelled Modulate gets its
own sand-colored series (`sttModulateModelledUsd`) and Mercury STT cash
its own (`sttCashUsd`), so the stack still reconciles to the total.
Foreign-currency Stripe fee rows surface as a **partial label** ("N
foreign-currency fee rows in the 30d window counted, not converted")
instead of silent omission — per the balance-transaction docs, a charge
converted into the USD balance already arrives as a `usd` row with
`exchange_rate`, so non-USD rows are foreign-balance fees with no
conversion data of their own. Mercury SaaS days whose **annual history
is incomplete** now keep the dated estimate with the gate named in the
text (the wall query carries `annual_history_complete`; all prod days
are currently true, read-only). The Modulate reconciliation sums Mercury
cash over the **whole window, including cash-only dates**. The refund
fee test follows the documented contract (`fee` "positive when
assessed"; funds direction in `amount`; refunds hand fees back via
negative `fee_details` summing to `fee`, cross-checked — disagreement is
a shape error). The deploy workflow mounts the two optional org-key
secrets **only when the resource exists** (`gcloud secrets describe`
gate, existence only, no payload read), so a target project without them
cannot block the deploy.

**CI at ceed0ee.** Backend unit shards 3/6+4/6 failed in the runner's
`apt-get update` inside "Install native audio replay dependencies"
(5-minute step timeout, cache already restored — infrastructure stall,
unrelated to this PR). Shard 5/6 failed
`test_sync_silent_failure.py::test_app_keeps_wals_retryable_on_failed_reconcile`
because main's #23288 moved the pinned app code (`case
SyncJobFetchOutcome.notFound`) from `local_wal_sync.dart` to
`wal_job_reconciliation.dart` without updating the pin — **main's own
Backend Unit workflow is red on the same test** (runs
39776810910/39777111780); the pin now reads the file where the behavior
lives.

**Round-3 schema note:** `plan_revenue_daily` gains nullable
`paying_customers INT64` and `non_usd_paying_subs INT64` (the first
change to an existing FinOps table in this PR): added by an idempotent
loader-side ALTER before the first load that carries them; old artifacts
load NULL; the wall falls back to the legacy query until the columns
exist (both paths validated read-only against prod).

## Round 2 (2026-10-22): measured vendor STT lines on the daily FinOps
job

**Soniox — exact daily spend from prepaid-balance deltas.** The Soniox
organization key has no usage/invoice/billing API (all 404); the only
readable endpoint is `GET /v1/organization/balance`.
`pull_vendor_balance.py` (new) snapshots the parsed `used_balance_usd` /
`available_balance_usd` / `invoice_billing_enabled` each daily run —
artifact and logs carry parsed numbers only, never the key or raw
response (pinned by test). The loader writes two new dark-able tables
(Schema below) and derives the per-UTC-day rate from consecutive
snapshots: a run gap spreads the delta over the missed days and flags
them `gap_spread`; a lower cumulative value (recharge/reset) makes that
day unmeasured (`usd` NULL, flag `baseline_reset`) and takes the new
value as baseline. The whole trailing window is recomputed each run, so
the rules can change without backfilling. The wall shows Soniox as
**measured with its as-of date** once ≥2 snapshots exist; until then the
labelled dated console constant stays (STALE after 14 days, round-1
rule); a dark table is an explicit unavailable line, never a guess.
Optional by design: missing key / 401/403 / transport failure ⇒
`status=skipped`, job exits 0.

**Modulate — modelled volume line + Mercury reconciliation (no API
exists).** Every Modulate GET path probed returns 404. The line is
`modelled` by construction: `pull_prometheus.py` gains `sum by
(provider) (increase(omi_live_stt_audio_seconds_total[1d]))` (VAD speech
seconds flushed per backend provider), and `pull_modulate_modelled.py`
(new) multiplies the `modulate` series by the **committed, dated price**
from `backend/config/rate_card_v2.json` (committed 2026-10-18 @
f6a3589): **$0.06/audio-hour** — Modulate "Multilingual
Transcription" streaming WebSocket list price, platform.modulate.ai (100
credits = $1 ⇒ 6 credits/h), SKU `velma-2-stt-streaming`, not Velma
Triage. The rate card is SHA-pinned by tests; a re-price is a reviewed
commit. The wall prints the trailing-30-day reconciliation of the
modelled line against Mercury `modulate` cash (vendor map `stt_vendor`),
variance shown on the STT line; when the modelled line is unavailable
the labelled Mercury-cash fallback stays. The Modulate ORG key binding
(`FINOPS_MODULATE_ORG_KEY`) is mounted **for a future API only** — no
code calls a Modulate endpoint with it, pinned by test.

**Secret wiring (deploy workflow).** `cloudrun.py` SECRET_FILES gains
`soniox_org` (`FINOPS_SONIOX_ORG_KEY`) and `modulate_org`
(`FINOPS_MODULATE_ORG_KEY`); the deploy workflow's `--set-secrets`
mounts both (they exist in `based-hardware` Secret Manager, readable by
`finops-writer@…`). The producer image now also ships
`backend/config/rate_card_v2.json` for the committed price. Round-1's
dark-deploy rule is respected: both new pulls skip cleanly when a mount
is missing, and the snapshot/Modulate tables stay dark until the first
successful pull.

### Schema changes (round 2)

Three **new** date-partitioned BigQuery tables in
`based-hardware.omi_finops`; no existing table changes schema:

- `vendor_balance_snapshot` — `date, ts TIMESTAMP, vendor, used_usd
NUMERIC, available_usd NUMERIC, invoice_billing_enabled BOOL, run_id,
computed_at` (one row per successful pull; idempotent per date+vendor).
- `vendor_balance_spend_daily` — `date, vendor, usd NUMERIC (NULL on a
reset day), flag STRING ('' | gap_spread | baseline_reset),
interval_start, interval_end, run_id, computed_at`.
- `stt_modulate_modelled_daily` — `date, audio_seconds FLOAT64, usd
NUMERIC, price_usd_per_hour NUMERIC, price_as_of DATE, method
STRING='modelled', run_id, computed_at`.

**Deploy tolerance:** all three are created only by a first successful
pull; skipped artifacts mean no table creation/read/write and the daily
job is unaffected. The wall reads them through dedicated readers that
cannot fail the plan/STT/SaaS legs (same pattern as `stripe_fee_daily`).
**Deploy-time step for the rollout lead:** re-deploy
`finops-unit-cost-job` from this branch (the workflow adds the two
secret mounts); no other orchestration — the first daily run starts the
snapshot series, and the wall switches Soniox to measured on the second
day.

### Tests (round 2)

- backend: **+38** — `test_finops_vendor_balance.py` (new, 24: string
parsing incl. numeric-lenient + rejects negative/NaN/bool/missing;
absent-key skip; 401/403 and error skips; no-key-in-logs across
stdout/stderr/artifact; delta math — consecutive days, missing-day
spread+flag, reset→new baseline+flag, same-day snapshots, unsorted
input, decimal strings; loader dark paths + tampered artifact) and
`test_finops_modulate_modelled.py` (new, 14: committed price pin $0.06/h
as-of 2026-10-18, non-card/invalid card rejection, provider filter +
bucket→prior-day mapping, seconds×price math, ready/skip artifacts,
never-reads-the-org-key). Existing finops family re-run green (119).
- web/admin: **+12** (591 passed total) — sttLineFor
balance-delta/gap/reset/constant-below-2-snapshots/modelled-Modulate/Deepgram
rules, modulateReconciliation math, parseVendorBalance, dedicated-query
isolation, wall line text (measured as-of, reset day, 1/2-snapshots
constant, both legs unavailable in `missing`).

## Product invariants affected

- INV-DATA-1: this PR edits
`.github/workflows/gcp_finops_unit_cost_job.yml` (round 2 adds two
Secret Manager mounts for the finops Cloud Run job:
`FINOPS_SONIOX_ORG_KEY`, `FINOPS_MODULATE_ORG_KEY`; round 4 swaps the
Stripe mount to the restricted `STRIPE_READ_API_KEY`). No mobile/desktop
routing authority or retired-GKE ownership is touched; `ci-budget.yaml`
was refreshed with `check_ci_budget.py --refresh` and validates against
`origin/main` (no trigger or input widening).

## What

Makes the Omi TV cost and revenue wall accurate and (for software cost
per customer) fully automatic, per David's 2026-10-22 scoping:
**software cost per customer only** — no marketing, hardware or COGS
lines are added.

Read-only audit context:
`data/run-2026-10-12-subscription-overhaul/reports/omi-tv-reconcile-haiku.md`
(workspace). All BigQuery numbers below are read-only `ro-prod` queries
over the settled window 2026-09-21..2026-10-20, book snapshot
2026-10-21.

## The nine items

1. **Stripe fees — measured, scope-gated.** `pull_stripe.py --end` now
refreshes the trailing 90 posted UTC days of `GET
/v1/balance_transactions` into `raw/stripe_fee_daily.json`: per day the
signed `fee` sum across all transaction types (refunds carry a negative
fee, so fees are net of refunds on the refund's own day), gross
charge/payment volume, row count, and a non-USD count (counted, never
summed — no implicit FX). Aggregates only; no identifiers. The loader
writes a **new FinOps table** (see Schema below), dark while the fee
source is unavailable. The wall adds the fee leg via a dedicated reader
(`fetchStripeFeeHistory`) that is deliberately outside the plan-cost
query, so a dark fee table can never fail the plan/STT/SaaS legs; the
wall shows `Stripe fees UNAVAILABLE (finops key lacks
balance-transaction read scope)` and lists it under `missing`. **Never a
guess.**
**Exact scope needed on the finops Stripe restricted key: Read on the
"Balance" category — the permission that authorizes `GET
/v1/balance_transactions`.** Today's restricted read key appears to lack
it (403 → the skip path); granting it and letting one daily job run is
all that is needed — no code change, no backfill (the first run loads 90
days of history). Estimated size when measured: ≈$3.2k/month (audit
estimate; not used as data).
2. **Wall MRR = FinOps book.** `revenue.mrr` now uses the latest
complete-day `plan_revenue_daily` snapshot (≤ D-1): coupons applied,
annual ÷ 12, trialing excluded, with the snapshot date shown
(`dataThrough`, reason) and the producer `computed_at` as the freshness
watermark. The live Stripe read stays only as a printed cross-check (it
applies no coupons, so the delta is the coupon effect made visible); it
becomes the value only if the FinOps read fails, with that labelled.
`arpmau` follows automatically.
3. **Anthropic.** The Anthropic admin-API leg is counted in per-customer
cost **only on days it reports non-zero spend** (today: $0.00 across the
window, confirmed read-only); a zero/off leg is no longer "missing".
Mercury `anthropic` cash now maps to **SaaS** in
`mercury_vendor_map.json` — it is Claude team seats (~$1.8k/mo), not
per-customer cost.
4. **Modulate.** Mercury `modulate` → `stt_vendor` (already mapped;
verified). Round 2 supersedes the cash-as-rate treatment with the
modelled volume line above; the cash stays as fallback and monthly
reconciliation. Counted once: **Soniox Mercury cash is never added**
(prepaid auto-recharge; near-daily $100–$700 top-ups, 48 payments in the
window); Deepgram cash only counts on days with no measured line.
5. **SaaS run rate.** The amortization machinery already existed
(`bill/12` over its 12 service months); the missing piece was the
cadence map. Ledger evidence (2026-07-04..2026-10-19, read-only) shows
the audit's four suspected "single annual payments" — Shopify, PostHog,
Nevercode, Pinecone — are all **monthly** (same-day-of-month repeats),
so the committed map correctly contains no annual vendor, pinned by a
test that documents the evidence. `inputs_complete` now gates only the
30-posted-day cash window; annual-history seeding is its own
`annual_history_complete` signal, so configuring a real annual vendor
without the 400-day backfill degrades to a labelled partial instead of
dropping the measured line to the $4.8k constant.
6. **STT automation.** Round 1 kept the measured usage line and made the
console constant a **labelled, dated fallback that goes STALE after 14
days**. Round 2 replaces both with the measured balance-delta day-rate
(above) once ≥2 snapshots exist; the constant survives only for the
pre-series transition, still labelled/dated/STALE-bounded.
7. **Staleness.** Every cost line states its source and as-of: STT/SaaS
constants carry their read dates with per-line staleness thresholds (STT
14d, SaaS 35d) surfaced on the cost frames, estimates frame and
margin-status line; MRR carries its snapshot date; the fee line carries
measured-through or the unavailable reason; measured SaaS rows keep the
existing 3-day freshness gate; round 2 adds the Soniox balance as-of
date and gap/reset flags.
8. **Headline metric.** Wall stat `cost.per_customer_month` — **software
cost per paying customer**: the same 30-day all-in software cost as
cost/MAU ÷ paying customers from the same FinOps book (3,209 at snapshot
2026-10-21), with a per-plan **variable cost per customer/month**
breakdown (FinOps `variable_total` ÷ cost-active user-days × 30.44, now
pulled in the plan-cost query).
9. **MAU snapshot discrepancy — root cause: definition drift, not
window/caching.** The 10-15 "real snapshot" (7,163 for [09-13,10-13))
was generated at 09:27 UTC from a hand-built query with the six original
wire events. The shipped `qualified-v2-2026-10-15` allowlist (commit
`474c1105`, 12:19 UTC that day — ~3h later, and the file did not exist
at the snapshot's pinned commit `95460feb`) widened qualification with
the macOS UI events and the mobile tab/list/search/action-item events;
the same window under the shipped definition is 9,665 (+35%). WAU
reproduced because its reference (4,197, 10-05..10-11) was produced
under the shipped definition. Fix: a regression test pins the full v2
event inventory, requires every people-counting query to scan every
allowlisted event, and the definition-version coupling is documented at
`DEFINITION_VERSION`.

## Schema change (producer)

**Round 1:** new date-partitioned table
`based-hardware.omi_finops.stripe_fee_daily`: `date, fee_usd NUMERIC,
volume_usd NUMERIC, transaction_count INT64, foreign_transaction_count
INT64, run_id, computed_at`. **Round 2:** three further new tables
(`vendor_balance_snapshot`, `vendor_balance_spend_daily`,
`stt_modulate_modelled_daily` — see the Round 2 section). **Round 3:**
one existing table changes schema — `plan_revenue_daily` gains two
nullable columns (`paying_customers`, `non_usd_paying_subs`) via an
idempotent loader-side `ALTER TABLE … ADD COLUMN IF NOT EXISTS`; old
artifacts load NULL and the wall query falls back to the legacy column
set until they exist. **Deploy tolerance:** every new table is created
only by the first successful pull of its source; skipped sources mean no
table creation/read/write and the daily job is unaffected. Loads are
idempotent per date via the existing delete/insert transaction.

## Before / after (read-only, window 09-21..10-20, book 10-21)

| Metric | Before (shipped formula) | After (this PR) |
|---|---|---|
| 30-day all-in software cost | $82,094 (audit; GCP export net $53,682 +
OpenAI $7,011 + Anthropic $0 + STT $6,092 + SaaS $15,309) | **$82,698**
= before + Modulate cash $604.40 + Stripe fees **$0 counted**
(unavailable, listed missing until the key scope lands; audit-estimated
≈$3.2k/mo). Round 2 recomposes the STT line (Soniox balance-delta +
Modulate modelled) without changing the all-in total's sources. |
| MRR | live Stripe read, no coupon handling (size unmeasured; FinOps
book $75,610) | round 2: **$75,609.74** (book 2026-10-21). Round 3:
latest snapshot **$75,477.73** (2026-10-22, read-only) now **USD-only**
— the two JPY subscriptions' yen/100 amounts leave `mrr_usd` (native
sums reported per currency; exact figure printed by the first post-merge
run; the contamination was ≈tens of $/mo but semantically
yen-as-dollars). Wall marks MRR **partial** while non-USD payers exist.
|
| Cost per qualified MAU | $7.70 (÷ 10,666) | **$7.75** |
| Cost per paying customer | not shown; round 2 ÷ 3,209 item-count =
**$25.77** | **round 3**: ÷ the same-window average of daily paying
*customers* (item dedup applied) — measured on the first producer run
post-merge; lower bound $28.25 (÷ 2,927, the 30-day item-average, 16
snapshot days) and higher per multi-item customer. Round-2 audited
numerator $82,698 unchanged (no Deepgram cash in the window, all annual
flags true). |
| ARPMAU | live-read dependent | **$7.09** (book ÷ MAU, same-cutoff when
the book day matches) |

## Tests

- web/admin: `npm test` — **591 passed**, 13 skipped (76 files) + `npm
run typecheck` + `npm run lint` clean. Round 1: FinOps-book MRR with
live cross-check and fallback, per-customer metric with per-plan
variable breakdown, STT vendor-cash rules, fee unavailable naming,
Anthropic gating, per-line staleness thresholds, MAU definition-drift
pin. Round 2: the vendor STT line tests listed above.
- backend: `BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=...
./test.sh` — round 1: 119 passed (`test_finops_stripe_fees.py` new,
Mercury cadence/annual tests, unit-cost/stt-costs/cloudrun/auth-http
green); round 2: **+38** in the two new files listed above, with the
whole finops family re-run green (157 total across the eight files).
- The new plan-cost BigQuery query was validated read-only against prod
(dry run + shape check: plans/variable rows, stt cash by vendor, saas).

## Safety

No prod writes: no BigQuery writes/table changes outside code paths, the
FinOps job was not run against prod, all checks were read-only `ro-prod`
queries (aggregates only, no user identifiers). Fee/skip paths keep the
daily job deploy-safe, and round 2 keeps the same contract for the
balance and Modulate lines. Follow-ups for the orchestrator (no code
needed): grant the finops Stripe key Balance read; deploy the job from
this branch to mount the two new org-key secrets (the secrets and the SA
accessor grants already exist).


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/23289?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
srcset="https://cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://cubic.dev/action/auto-fix/pr/BasedHardware/omi/23289?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23289&source=description"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->



Failure-Class: none
aryanorastar added a commit that referenced this pull request Oct 23, 2026
…23280)

## Final merge acceptance — 2026-10-23

Reviewed/tested head `821c326f07846966173b6a66b70c3187094da442`. Fresh
native suites pass **24 tests / 84 assertions**. The production
recorder/view/store probe passes **7 lifecycle cases on the 40 mm Watch
SE 3 simulator / watchOS 27.0**: canceled/late permission, ABA
permission, failed activation, Stop, repeated Stop, denial and missing
owner. Permission/audio-session I/O is injected; `physicalAudio=false`.
Native screenshots confirm visible Stop and separate Retry with pending
transfers, idle Record/Retry, and visible Stop at accessibility3 with a
long recovery error. This is not real microphone, radio transfer or
paired-Watch evidence.

Aryan explicitly accepts simulator-led Omi verification and authorized
merging this PR if ready. This final acceptance supersedes the earlier
physical-device-only merge gates below; physical Watch
connectivity/audio and customer release outcomes remain explicitly
unverified follow-up, not claims of recovery. Required current-head CI
and an existing approval passed before merge. No deployment or store
release is authorized/performed in this task. `Fixes` was changed to
`Refs` so #23275 stays open for release/outcome follow-up rather than
closing on code merge alone.

---

The active Watch screen hides Stop behind the Omi logo, and recorder
teardown leaves AVAudioSession active. This adds a visible **Stop
recording** button, keeps Retry transfer separate, and shares microphone
cleanup across Stop, cancelled permission and failed startup. A delayed
permission answer cannot reactivate a cancelled recording.

Refs #23275. Follow-up to #22059.

Current main already addresses minute-by-minute Home backup clutter
through [#23288](#23288): the
shared custody ledger owns Watch copies, Offline Sync exposes automatic
work, and Home lists explicit user-held recordings. This branch now
integrates that pipeline and removes its superseded Home grouping
proposal. No additional Dart projection, retention rule, backend,
firmware or API change is introduced here. Public store release of
#23288 has not been verified.

### Verification

- Native Watch simulator probe runs the actual production
recorder/view/store with synthetic permission and audio-session I/O: **7
lifecycle cases passed**, including late/ABA permission, activation
failure, Stop, repeated Stop, denial and missing owner. It opens no
microphone.
- Existing custody, relay and presentation suites: **24 tests, 84
assertions passed** after main integration.
- Separate Personal Team-signed QA host on **physical iPhone 16 Pro /
iOS 27.0.1**, compiling unchanged production recorder/view/store: the
final approximately **70-second** capture saved **60.00 + 10.09 seconds
of validated, non-zero PCM**, stopped, successfully deactivated
AVAudioSession with zero errors, and left file sizes unchanged for two
seconds. Final result UTC: **2026-10-23T04:22:27Z**. A direct-phone
spoken test also produced non-zero audio. Aryan manually verified Stop:
the timer stopped and orange microphone indicator disappeared. Earlier
runs with the Mac device view open contained only zero PCM and are not
counted as audible capture evidence; a later start was blocked while the
phone was locked. The final run used the unlocked phone directly with
the device view closed. Retained parts include earlier QA runs, so
totals are attributed by session metadata. The battery adapter is a
no-op; this does not exercise physical watchOS, paired delivery or the
production Omi app/account.

- Native 40 mm Watch simulator renders active Stop + Retry, stopped
Record + Retry, and accessibility3/error state. The stopped-state Retry
clipping and accessibility title wrapping found during inspection are
corrected.
- Current-main analyzer ratchet, local preflight (20 selected checks;
the history-dependent guard explicitly skips on this shallow clone) and
push hooks passed. Full app suite: **7,120 passed, four skipped**, plus
**138 protected contracts passed**. All hermetic mobile journeys passed
(**23 executions, zero failures/skips**). Code Review confirms **iOS
Compile Check, Dart Analyze & Tests, Hygiene and Desktop Swift Static &
Test Contracts passed on `821c326f07846966173b6a66b70c3187094da442`**,
with no failed or running source checks at verification. Scope-skipped
lanes are not claimed as executed.

Reproduce native checks from the repository root:

```sh
ruby app/ios/test/watch_recording_recovery_test.rb
ruby app/ios/test/watch_audio_chunk_relay_test.rb
ruby app/ios/test/watch_recording_presentation_test.rb
ruby app/ios/test/watch_recording_controls_probe.rb --device <booted-watch-simulator-uuid> --output <temporary-directory>
TZ=UTC bash app/test.sh
make mobile-verify ARGS='fast --all'
make preflight
```

The SDK probe needs the CocoaPods Ruby environment (`xcodeproj`).
Private physical-run build/source hashes and result JSON are retained
locally; no microphone audio, device identifier, customer account or
signing credential is published.

### Merge gates and release

**Ready for review; do not merge until paired-Watch acceptance passes:**
press Stop and check microphone indicator with phone
reachable/unavailable, pending transfers and screen-off/resume; capture
across a minute boundary; restart/retry real WatchConnectivity
transfers; verify receipt-owned originals, playback and processing on
iPhone; confirm Home has no automatic minute-copy rows and originals
remain accessible through Offline Sync. The iPhone-host result does not
satisfy these Watch gates. Simulator file delivery is unsupported by
[Apple's WatchConnectivity
documentation](https://developer.apple.com/documentation/watchconnectivity/wcsession/transferfile(_:metadata:)).
Longer recovery qualification remains tracked in
`app/docs/apple-watch-recovery.md`.

Source checks have passed on the exact pushed head. Complete
paired-hardware acceptance and compare against David's concurrent work
before readiness; refresh affected checks if changes follow that review.
No review of unpublished changes is claimed. After acceptance, this
needs merge and a signed iPhone release containing the updated Watch
companion. This follow-up adds no backend deployment; #22059's existing
processing-backend rollout dependency remains separately tracked. No
deployment, app-store release or older-audio recovery is claimed.

### Product invariants

INV-CAP-1: preserve original recovery files, session fencing, durable
receipts and account ownership; microphone teardown does not change
custody.
INV-UI-1 / INV-UI-3: reuse native controls and existing localized Stop
labels, preserve explicit controls with pending/error state and large
text.
INV-PERF-1: no new per-frame UI work, scan, timer or uploader; main's
canonical custody pipeline remains authoritative.

### Failure class

Failure-Class: new

Root cause: recorder cleanup stopped the engine without releasing
AVAudioSession; permission checking also activated audio before
validating the original start generation. Trigger: #23275; these
lifecycle defects predate #22059, while that PR introduced the
minute-copy clutter now handled by #23288.

Prevention uses a shared `releaseCaptureResources` primitive for Stop
and failed startup, plus generation validation before session
activation. The durable guard is
`app/ios/test/watch_recording_controls_probe.rb` with
`app/ios/test/fixtures/watch_recording_controls_app.swift`, executing
the production model with synthetic OS I/O. It is an explicit
SDK/simulator lane, not a default hermetic CI or physical Watch
qualification.

### UI evidence

UI-Evidence:
.agent-artifacts/ui-evidence/watch-session-controls/evidence.json

Actual native views with synthetic state; no physical microphone or
transfer claim.

![40 mm Watch Stop and
Retry](https://raw.githubusercontent.com/BasedHardware/omi/15635a4a3bae5e94524d06994e845bf423126d4b/.agent-artifacts/ui-evidence/watch-session-controls/001-mobile-ios-watch-stop.png)
![Stopped Watch with Retry
visible](https://raw.githubusercontent.com/BasedHardware/omi/15635a4a3bae5e94524d06994e845bf423126d4b/.agent-artifacts/ui-evidence/watch-session-controls/005-mobile-ios-watch-idle-pending.png)
![Accessibility text and error
state](https://raw.githubusercontent.com/BasedHardware/omi/15635a4a3bae5e94524d06994e845bf423126d4b/.agent-artifacts/ui-evidence/watch-session-controls/006-mobile-ios-watch-accessibility-stop.png)


## 2026-10-23 maintainer review and merge gates

Reviewed the current production Stop/cleanup/generation changes and
reran the native recovery, relay and presentation suites: 24 tests / 84
assertions pass. No new blocking source finding in this bounded review.
Existing iPhone-host microphone evidence is not a paired-Watch test.
Ready for code review at Aryan's request; merge stays blocked until real
Watch Stop/microphone release, minute-boundary capture,
reachable/unreachable phone transfer retry, screen-off/resume, retained
originals/playback/processing and Home/Offline Sync behavior are
verified. No physical device was accessed in this review and no
deployment/release was performed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant