On Android 13 and lower Health Connect is a separate Play app. Without it,
tapping "Grant All Health Access" launched an intent nothing handled and the
app crashed with ActivityNotFoundException.
The setup screen now checks HealthConnectClient.getSdkStatus: when Health
Connect is missing or outdated it says so and the primary action opens the
Play listing (web fallback if no store app). Every Health Connect launch
(permission request, historical-access request, settings) goes through the
same check, with an ActivityNotFoundException backstop onto the install path.
Also:
- Declare the provider package in <queries>; on Android 11+ getSdkStatus
cannot see an installed Health Connect without it.
- "Manage in Health Connect" used the Android 14 platform action, which does
nothing on 13 and lower; use the SDK's per-platform settings action.
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK
Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Both switches were stored, shown, and never read. `AppModule` built
`NotificationIntegration` with three positional arguments, so `allowActions`
took its `true` default while the UI default was `false`; `OutreachIntegration`
passed `dndEnabled = isDndPermissionGranted()`, substituting the OS grant for
the user's own toggle, captured once at construction.
Both are now resolved per tool call via a readiness-gated `LiveBooleanSetting`,
required in addition to the OS permission where there is one. Provider defaults
flip to denying, so a provider built without an explicit consent source refuses.
Closes#746
joinCaptureWork() read serviceScope's children once and joined that list.
A coroutine launched into the same scope from inside another of its
coroutines — a sibling, not a nested child — registers after that read and
was never awaited, so the three negative capture assertions would go back
to passing on an unfinished write rather than on an empty table.
Re-read the children on every pass instead. The loop is unbounded on
purpose: a test-only helper that hangs is loud, while a bounded drain
would return early and reintroduce the false green it exists to prevent.
The new test builds the sibling deterministically — the capture coroutine
parks in the DAO until a gate queued on runBlocking's event loop opens,
which cannot happen until joinCaptureWork has already inspected the scope
— and asserts a positive outcome (the sibling's write landed), because an
empty-table assertion is what a missed write looks like too.
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK
Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Three `Thread.sleep(50)` calls in `NotificationCaptureServiceTest` sat in
assertions that nothing was persisted. `.claude/rules/coroutines.md` bans
`Thread.sleep` for signaling between test coroutines, but the usual
`CompletableDeferred` swap does not apply: you cannot await a signal for a
write that by design never arrives.
The failure mode was worse than a flake. All three assert the table is
empty, and an unfinished write also leaves it empty, so a too-short sleep
made the test pass for the wrong reason and hid the bug it existed to
catch. Raising the sleep would only make that false green rarer.
Replace the sleeps with a happens-after point rather than a wait.
`launch` registers its child job with the scope synchronously, before
`onNotificationPosted` / `onNotificationRemoved` returns, so the test
thread can see any coroutine the callback started. `joinCaptureWork()`
joins those children: when it returns the launched work has completed, or
was never started. No duration is involved.
Verified by mutation. Dropping the own-package guard in
`onNotificationPosted` turns `skips own package` red; making the no-match
branch of `onNotificationRemoved` write turns `no-op when no matching
record` red; doing both turns `ignores own package` red. With a 300 ms
write added on top, the rewritten test still fails while the old
`Thread.sleep(50)` version passes — the false green, reproduced.
Also converts the two remaining `Thread.sleep` calls in the same file, in
the dao-exception tests, to the same join.
Closes#700
The "Grant historical access" button is disabled until the base Health
Connect permission lands, but the grant result navigated straight to the
integration-setup screen — so the button was never in a pressable state
and historical access was unreachable during onboarding.
SETUP mode now stays put after the grant. The primary button becomes
state-aware: "Grant All Health Access" while nothing is granted,
"Continue" once at least one record type is, and Continue performs the
navigation the grant result used to perform. SETTINGS mode, and Cancel's
label and behaviour, are unchanged.
So the post-grant state is correct on the first recomposition after the
dialog returns (no flash of the pre-grant label), onPermissionsResult now
publishes the granted record types synchronously and lets the async
refresh reconcile. The permission-to-record-type mapping it needs moves
into RecordTypeRegistry.namesForPermissions, shared with the repository
that already did the same translation inline.
Its Boolean return is dropped: nothing consumes it now that the caller no
longer branches on it.
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
* Cap Health Connect raw reads and answer spanning ranges with buckets (#545)
`queryRecords` read up to MAX_RECORDS (50,000) records in order to return
DEFAULT_MAX_RECORDS (500): the caller's `limit` was passed as `null` to the
category query and the cap was applied afterwards, by downsampling a fully
materialised range.
Both halves of the owner ruling on #545:
**Cap the read.** `RecordReader.read` takes a `maxRecords` bound that reaches
the Health Connect request itself — page size is the smaller of READ_PAGE_SIZE
and what the caller still needs — so `limit=50` costs a 50-record read instead
of the whole range. `queryRecords` reads one past the cap, enough to tell "the
range fits" from "there is more" and no more than that.
**Bucket the rest.** Capping alone would return the range's *earliest slice*
dressed up as an answer about the range. So when the range holds more than the
cap, the query is answered with per-window count/min/max/avg spanning the whole
range at the resolution the cap implies. Aggregation streams pages and folds
them as they arrive (`RecordReader.stream` + `bucketize` over a Flow), so a wide
range is never materialised — that also fixes the explicit `bucket=` path, which
previously read the entire range into a list before bucketing it. Record types
that cannot be aggregated (sessions, multi-value, cumulative) keep the even
spread across the range, never a truncation.
Health Connect's own `aggregateGroupByDuration` is deliberately not used:
connect-client 1.1.0 exposes no AggregateMetric for BloodGlucose, HRV, SpO2,
respiratory rate or either body temperature — six of the eight bucketable types,
including the CGM case that motivated this issue.
READ_PAGE_SIZE stays at 1000 and is now documented as deliberately pinning
ReadRecordsRequest's default. A Pixel 6 Pro read real Health Connect cleanly at
page sizes up to 3000, so shrinking it to chase the Binder limit would be a
speculative fix for a mechanism measured not to exist, at triple the
round-trips. PaginatedReaderTest asserts the pinning against the library's
actual default so it cannot drift back silently.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK
* Stop claiming whole-range coverage when aggregation hits its ceiling (#545)
Review of #611 found the response note asserted something provably false: the
buckets "span the whole range rather than only its earliest records". Aggregation
stops at MAX_RECORDS samples, so on a range denser than that the buckets cover
only its earliest part — measured on a 365-day/60,000-record window, the last
bucket ended 58 days short with 10,000 records absent.
The truncation itself is pre-existing (origin/main truncates identically on the
same input); what was new was the prose asserting the exact property this change
exists to establish.
- The sample ceiling moves from the record stream to the fold, where it can be
observed: `bucketize` takes `maxValues`, stops one past it, and reports
`truncated`. Applying it at the fold also makes the unit meaningful for types
whose records carry many samples each.
- `truncated` is carried through `BucketResult.Success` and `QueryResult.Buckets`
to the tool response as a field, and the note now describes the span actually
covered instead of claiming the whole range. The explicit `bucket=` path
reports it too, where it was previously silent.
- The `QueryResult.Buckets` branch of `executeRaw` had no coverage — which is
why the false note survived. `FakeHealthConnectRepository` can now return
`Buckets`, and the branch is covered in both the complete and the cap-hit case;
ablating the honest note fails the latter with the reviewer's own finding.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK
* Put a finite record ceiling back on streamed reads (#545)
Review of #611 caught a defect this PR introduced: `stream` was changed from
`pages(..., MAX_RECORDS)` to `pages(..., Int.MAX_VALUE)`, on the reasoning that
the fold's sample cap bounds it. That converts a structural bound into a
conventional one. `take(maxValues + 1)` only trips if records actually yield
values, and `HeartRate` — the one bucketable type mapping over `samples` — can
be constructed with an empty sample list, which the SDK does not reject. Such a
range trips neither bound and walks the whole thing.
Measured through `bucketRecords` with 400 pages of empty-sample records:
400 pages / 400,000 records fetched, against a bound that allows 51.
`STREAM_MAX_RECORDS` (`MAX_RECORDS + READ_PAGE_SIZE`) restores the ceiling with
one page of slack, so it cannot cut short a fold the sample cap would have
satisfied. Measured with one sample per record and an endless supply: 51 pages /
51,000 records fetched, `totalCount = 50,000`, `truncated = true` — the sample
cap still binds first everywhere real, and the empty-yield case now terminates
instead of resting on records being non-empty.
`MAX_RECORDS`'s KDoc claimed a bound it does not have over a streamed read —
the same class of defect as the response note, prose asserting an invariant that
no longer held. It and `RecordReader.stream`'s doc now say what actually bounds
each path: the sample cap counts samples and normally trips first; the record
ceiling is what makes termination structural.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
* test(outreach): pin channel-id normalization for the channel tools
`create_notification_channel` and `delete_notification_channel` hand-roll
the "prefix unless already prefixed" rule that `resolveChannelId()` already
implements, and nothing asserted what either copy does. Pin the reachable
edge cases — unprefixed, already-prefixed, empty, case-shifted, unknown —
before collapsing the copies onto the helper (#540).
Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
* refactor(outreach): route the channel tools through resolveChannelId
`create_notification_channel` and `delete_notification_channel` each
carried their own copy of the AI-channel prefixing rule that
`resolveChannelId()` already implements. Post-#539 the `id` param reads
back non-null, so the copies collapse to a single call with no `!!`.
The two implementations were compared before merging them. For every
input the `id` param can produce they are the same expression, character
for character; the helper's only extra behaviour is `null ->
CHANNEL_ID`, and `null` is unreachable here because `StringParam.extract`
treats a missing or JSON-null required arg as an error that `invoke()`
answers before `execute()` runs. No latent bug, no divergence to
preserve. The preceding commit's tests pass unchanged against both the
inline copies and the helper.
Closes#540
Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
---------
Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
Every param declared `val period by stringParam(...)` read back as
`String?`, even though `McpTool.invoke()` answers with an error before
`execute()` runs when a required param is missing. So the nullability was
fictional and 19 call sites across the four providers wrote `period!!`.
`.required()` now returns a `RequiredParam`, whose `provideDelegate`
overload hands back a `ReadOnlyProperty<McpTool, T>`. `.optional()` and
`.default(v)` are unchanged and still read back as `T?`, which is honest —
those really can be absent. The one assertion left lives in
`RequiredBinding.getValue`, at the boundary where `invoke()` enforces the
invariant.
`.required()` after `.optional()`/`.default()` throws, since it would
promise a non-null value the extractor cannot deliver.
`ParamDef.required` is renamed `isRequired`: a Boolean property named
`required` shadows a `required()` call badly enough that the compiler
resolves `param.required()` to `DeepRecursiveFunction.invoke`.
Closes#539
Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
High-volume record types (e.g. BloodGlucose from a Dexcom CGM, ~288
records/day) crashed query_health_data with a generic tool error. The read
built ReadRecordsRequest with no pageSize, so Health Connect returned a full
~1000-record page in a single Binder transaction that exceeded the ~1MB
limit and threw before serialization. This lands three related changes on a
shared paginated read:
1. Paginated read (crash fix). HealthConnectClientRecordReader now sets a
bounded pageSize (READ_PAGE_SIZE=1000) and loops over response.pageToken
until exhausted, with a MAX_RECORDS=50_000 ceiling to bound memory. read's
signature is unchanged; a PageFetcher seam makes the loop unit-testable.
2. Downsampled raw mode (default). Repository.queryRecords now returns a
QueryResult(records, totalCount, downsampled). When mapped records exceed
the cap (limit if given, else DEFAULT_MAX_RECORDS=500) it evenly downsamples
across the whole range (first and last retained) rather than trimming one
end, and the tool response gains total_count and downsampled. Real record
objects are preserved, so the wire contract is unchanged.
3. Bucketed mode (new bucket param). query_health_data takes an optional
bucket like 1m/5m/1h/1d. Bucketing is guarded BEFORE reading: if the
expected bucket count exceeds MAX_BUCKETS=1000 it errors with the count and
limit. It applies only to instantaneous scalar types via a per-type
bucketValues extractor colocated with the existing mappers in VitalsQueries
and BodyQueries (BloodGlucose, HeartRate, HRV, RestingHeartRate,
RespiratoryRate, OxygenSaturation, Body/BasalBody temperature, Weight,
Height, BodyFat, BoneMass, LeanBodyMass, Vo2Max); session/multi-value/
cumulative types (SleepSession, ExerciseSession, BloodPressure,
SkinTemperature, Steps, etc.) return a clear error. Per non-empty window it
emits {start, count, min, max, avg}.
Tool description updated to document all three behaviors. This is an MCP
tool-behavior change, not an app-UI change, so no docs/ux-decisions.md entry.
Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* Unify MCP period parsing on local zone + sliding-from-start-of-today (#496)
The usage, notification, and Health Connect MCP providers each parsed the
`period` argument differently. Health Connect was the outlier: it stamped
local-date-midnight as UTC (shifting "today" for non-UTC users) and anchored
week/month windows to `now` rather than the start of today.
Introduce a single shared PeriodParser that maps today|week|month to a
[start, now] range using the local zone and a sliding window anchored to the
start of today. All three providers delegate to it; usage keeps `yesterday`
as a local-only extra. Health Connect's ranges change accordingly (UTC ->
local, now-anchored -> start-of-today-anchored) — intended.
Document the unified semantics (zone + anchoring) in the MCP tool `period`
param descriptions so calling agents can reason about the window.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Fix DST regression in Usage 'yesterday' period (LocalDate arithmetic) — #500 review
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Make PeriodParser week/month DST-aware (LocalDate arithmetic) — #500
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Extract RecordReader.queryRecords() extension that handles read-map-sort-limit,
replacing 39 private suspend fun query*() methods across 7 category files with
inline lambdas. Zero behavior change, verified by all existing tests.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The two framework-level error paths in McpTool.invoke() (param-extraction
failure and catch-all exception handler) produced plain-text ToolResult.Error
bodies. The Anthropic connector proxy expects JSON in the TextContent text
field, causing "Invalid content from server" errors on any missing-param
or unhandled-exception path.
Add ToolErrorResponse @Serializable data class with {"success":false,"error":"..."}
shape (matching the outreachError/usageError pattern from #418), and wrap both
error sites. Remove the expectJsonBody=false bypass in UsageMcpProviderTest
that was pinned for this issue.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The actions param was read from rawArgs directly, bypassing the McpTool
param DSL so Claude couldn't discover it via tools/list. Declare it as
an optional stringParam (JSON-serialized array) and parse inside
addNotificationActions(). Also add click_url optional param that sets
the notification's contentIntent via PendingIntent with http/https
validation.
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Two gates to prevent reintroduction of the malformed-JSON bug class
that shipped in #417 (Outreach error helpers used a """{...}""" template
with raw exception text, producing unparseable bodies).
(A) Harness-level JSON parse assertion. Introduces shared
`McpToolTestHarness` (in `integrations/src/test/.../testing/`) that
wraps the duplicated mockk(Server) + addTool capture pattern previously
copy-pasted across `OutreachMcpProviderTest`, `UsageMcpProviderTest`,
`NotificationMcpToolExecutionTest`, and `NotificationMcpProviderToolsTest`.
Every `callTool(...)` invocation runs the result body through
`Json.parseToJsonElement`; parse failures throw with the offending tool
name and body content. Per-call `expectJsonBody = false` opt-out for
tools whose contract is plain text (currently only one test uses it,
referencing #427 which tracks the underlying core MCP DSL gap the
harness surfaced).
Regression test `McpToolTestHarnessTest` constructs fake tools that
return non-JSON bodies and asserts the harness throws with the tool
name + body in the message, plus a passing-case to lock down the
expectJsonBody opt-out.
(B) CI grep check. New `scripts/check-no-manual-json.sh` greps
`*/src/main/*.kt` for `"""\{` and fails the build on hits unless the
line carries a `// allow-manual-json: <reason>` marker, or matches the
explicit `AuditDetailScreen.kt` allowlist (Compose preview fixtures).
Wired into `.github/workflows/android-ci.yml` next to the existing
`check-zombie-screens.sh` step. Verified manually that the script
fires on a synthetic `"""{"x":"$bar"}"""` and clears once the marker
is added.
Documents the convention in new `docs/agent-quickstart.md`.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Three sibling instances of the cold-start async-state-not-loaded-yet race
that #416 fixed for ProviderRegistry (issue #414). Each used the same
shape: async state seeded into a StateFlow with a default value, read
synchronously by callers that fire during the cold-start window between
process spawn and the first DataStore emission.
Finding #1 (HIGH) - securityAlertCheck
The McpSession `securityAlertCheck` lambda was `() -> Boolean` reading
`alertFlag.value` from a `combine().stateIn(..., initialValue = false)`
flow. On cold-start FCM wake the very first request arrived before the
flow had emitted, so a device whose security check reported `alert`
answered the request anyway. Subsequent requests refused correctly.
Fix: introduce SecurityAlertGate (mirrors ProviderRegistry's awaitReady
shape) that suspends until the underlying combined flow has emitted
once, then exposes `suspend fun isAlerting()`. McpRouting's
`securityAlertCheck` lambda type changes to `suspend () -> Boolean`;
existing test lambdas (`{ true }` / `{ false }`) auto-cast.
Finding #2 (MEDIUM) - OutreachIntegration._directLaunchEnabled
`canLaunchDirectly` was a `() -> Boolean` reading
`_directLaunchEnabled.value` from a MutableStateFlow seeded by an
`appScope.launch{}` collector. First tool call after cold-start could
mis-route through the notification fallback even when the user had
opted into direct launch.
Fix: convert `canLaunchDirectly` to `suspend () -> Boolean` through the
chain (LaunchAppTool, OpenLinkTool, launchActivitySafely). Add
`awaitReady` / `awaitReadyBlocking` to OutreachIntegration; the lambda
becomes `{ isDirectLaunchAllowed() }` which suspends on awaitReady
before reading the flow value.
Finding #3 (MEDIUM, latent) - DeviceRegistrationStatus
Constructed with `initiallyRegistered = false` and an
`appScope.launch{ if (certStore.getSubdomain() != null) markComplete() }`.
Currently safe only because IntegrationSetupViewModel.awaitRegistrationIfNeeded
(issue #242) consults the cert store directly; future readers that add
`.complete.value` without copying the workaround re-introduce the bug.
Fix: add `DeviceRegistrationStatus.create(scope, suspend isRegistered)`
factory that runs the check in `scope` and signals `awaitReady` once it
resolves. AppModule's Koin binding switches to `create()`. The
synchronous constructor is preserved for tests; both code paths signal
readiness eagerly when the answer is known up front.
Per #419 hard rules:
- Workaround in IntegrationSetupViewModel.awaitRegistrationIfNeeded
left in place; no UX-flow files touched.
- No runBlocking added to production code.
Tests:
- SecurityAlertGateTest (new): slow-flow regression + idempotent
awaitReady + empty-first-emission ready signal.
- DeviceRegistrationStatusTest (extended): create() defers awaitReady
until check resolves; both true/false verdicts unblock.
- OutreachIntegrationTest (extended): mockk-based slow settings store
proves awaitReady waits for first emission.
- HttpRoutingTest (extended): suspend-awaiting securityAlertCheck still
rejects with 503.
Verification:
- `./gradlew :app:testDebugUnitTest :work:testDebugUnitTest :core:mcp:jvmTest :integrations:testDebugUnitTest` all green.
- `./gradlew ktlintCheck detekt` clean.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
The manual `"""{"key":"$value"}"""` pattern in five integrations files routinely
produced malformed JSON when interpolated values contained `"`, `\`, newlines,
or tabs — exactly what `Throwable.message` from Android exceptions tends to
carry. The bug surfaced as the Phone Outreach connector returning "malformed
responses through the Anthropic proxy" on any failure path.
This commit replaces every interpolated JSON template in the integration MCP
providers with `@Serializable` data classes encoded via `kotlinx.serialization`,
so user-supplied content is escaped by the serializer rather than concatenated
into a string. The wire shape (field names, types, nesting) is preserved
exactly — only the encoding step changes. Per-file `*JsonModels.kt` files
hold the new DTOs alongside a per-file `Json { encodeDefaults = true }`
instance that keeps the constant `success` defaults on the wire.
Files migrated:
- integrations/.../outreach/OutreachMcpProvider.kt (~10 sites)
- integrations/.../usage/UsageMcpProvider.kt (~10 sites)
- integrations/.../notifications/NotificationMcpProvider.kt (5 sites)
- integrations/.../health/query/VitalsQueries.kt (skin temp deltas)
- integrations/.../health/query/SleepQueries.kt (sleep stages)
The two health-query string-of-JSON fields (`deltas`, `stages`) preserved
their unusual legacy shape (`"deltas":"[{...},{...}]"`) by building the inner
arrays with `buildJsonArray` and stringifying — no wire change.
The local `escapeJson()` extensions in OutreachMcpProvider and UsageMcpProvider
became dead code and were deleted.
`AuditDetailScreen.kt` was audited: its `"""{` occurrences are only `@Preview`
fixture data, not runtime JSON construction, so no change is needed there.
Tests: each new DTO has round-trip coverage including regression cases for
`#417` — error/message strings containing `"`, `\`, `\n`, `\t` round-trip via
`Json.parseToJsonElement` without throwing. The existing
`OutreachQueryInstalledAppsTest` was updated to assert on typed fields rather
than substring-matching JSON strings (queryInstalledApps now returns
`List<InstalledApp>` instead of `List<String>`).
Cross-references: this is the broader migration referenced by closed issue
#130, which did the same work for OAuth protocol responses in McpRouting.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Three tightly-coupled bugs in the shared audit-row surfaces:
1. ListRow previously used `defaultMinSize(minHeight = 56.dp)` with no
vertical padding. Single-line rows looked right (floor set by
min-height, content centered) but multi-line content (e.g. a long
JSON `arguments` string in ToolCallRow) grew the row height and then
pressed flush against the top and bottom edges of the card. Replace
the min-height floor with `padding(vertical = 12.dp)`: single-line
rows keep a ~48 dp height which matches existing density, multi-line
rows now have breathing room. Applied to `ListRow`,
`ListRowWithIcon`, and `ListRowWithTrailing`.
2. `AuditHistoryViewModel.toHistoryEntry` fell back to the raw
`entry.argumentsJson` / `entry.resultJson` columns whenever the
FieldEncryptor was null or `decrypt()` returned null. Those columns
hold ciphertext at rest, so the fallback rendered base64-looking
blobs into the dashboard's Recent Activity teaser and the audit
detail screen. Root cause of the null-encryptor path was that
MainDashboardViewModel and IntegrationManageViewModel never received
the encryptor. Fix both:
- Remove the raw-column fallback everywhere. Render "" (empty) when
decrypt is unavailable; ciphertext is never rendered as plaintext
even if future call sites forget to wire the encryptor.
- Thread `FieldEncryptor` through MainDashboardViewModel and
IntegrationManageViewModel via Koin so production paths always
decrypt.
- Apply the same fix to `AuditDetailDestination` and to
`NotificationMcpProvider.recordToJson` (which returned ciphertext
over the MCP wire to the AI client when the encryptor was null).
3. In ToolCallRow's row 2 the outer Row was
`verticalAlignment = CenterVertically`. When a long `arguments`
string wrapped to multiple lines, the timestamp on the right floated
to the vertical center of the wrapped block while the duration
stayed pinned to the top, looking misaligned. Switch to
`Alignment.Top` so the time stays pinned alongside the duration on
the first wrapped line.
Tests:
- New AuditHistoryViewModelTest cases pin the fallback contract: with
a null FieldEncryptor or a decrypt that returns null, the resulting
AuditHistoryEntry.arguments is "" and argumentsJson / resultJson are
null, never raw ciphertext.
- New screenshot case 34b_audit_history_long_args (light + dark)
renders a multi-line JSON `arguments` block. Locks in the padding
+ top-alignment fix; regressions will show immediately as a visual
diff.
- Re-record affected goldens (08 dashboard, 17/18a integration manage,
34/36/36a audit history, 99 bottom-inset manage, quick_* preview set).
Trust-card 50* goldens intentionally NOT re-recorded (different
issue area).
- Update NotificationMcpToolExecutionTest to use a passthrough
encryptor by default so existing plaintext-round-trip tests keep
working under the stricter no-ciphertext-fallback contract.
Closes#383
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
The test's `waitForRecordCount` 10ms-polling/2s-timeout loop was flaking in
CI, surfacing real assertion failures as polling timeouts per the project's
"hangs hide broken tests" convention. Replace it with a `SignalingDao`
decorator that completes a `CompletableDeferred` from inside each write,
letting awaiters resume deterministically once the service's
`Dispatchers.IO`-launched coroutine finishes its DAO call.
Confirmed stable across 20 back-to-back runs under the same Gradle/JVM
config CI uses.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Convert snake_case MCP tool names to human-readable titles for display in
notifications (e.g. `get_steps` -> `Get Steps`, `set_dnd_state` -> `Set DND
State`). The acronym set is a simple constant that can be extended as new
tools with abbreviations land. Non-snake_case input throws
`IllegalArgumentException` so a malformed tool name surfaces loudly rather
than rendering as garbled UI copy.
The validation test dynamically enumerates every tool registered by every
`McpServerProvider` in `:integrations` (notifications, outreach with DND
enabled, usage, health) by recording `Server.addTool` calls and running
each captured name through the humanizer. A new tool landing with a
non-snake_case name will fail this guard rail before notification copy
work (#347) can rely on it.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Adds two new test files + extends NotificationDaoTest to close the
coverage gaps reported in #301:
- NotificationMcpToolExecutionTest drives every tool's execute() path
through the SDK handler (happy paths, error paths, own-package
blocking, ISO time parsing, field decryption, period ranges).
- NotificationCaptureServiceTest uses Robolectric ServiceController to
exercise onNotificationPosted / onNotificationRemoved /
onListenerConnected / onListenerDisconnected / onDestroy, plus
dao-failure swallow paths and encryption wiring.
- NotificationDaoTest gains a file-backed NotificationDatabase.create()
round-trip.
Per-class line coverage before -> after:
NotificationCaptureService 0% -> 72.3%
NotificationMcpProviderKt 0% -> 100%
DismissNotificationTool 41.2% -> 100%
GetNotificationStatsTool 16% -> 100%
ListActiveNotificationsTool 38.5% -> 100%
NotificationDatabase 50% -> 100%
PerformNotificationActionTool 42.1% -> 100%
SearchNotificationHistoryTool 41.7% -> 100%
Package total: 60.2% -> 90.6% line (462/510).
The remaining ~28% in NotificationCaptureService lives in
seedActiveNotifications, which calls the inherited
NotificationListenerService.getActiveNotifications() binder — only
reachable with a bound system service on a real device.
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Applies the `org.jetbrains.kotlinx.kover` 0.9.8 plugin to every production
module and wires the root project as the merging target, so
`./gradlew koverHtmlReport` produces one aggregated HTML + XML report across
`:app`, `:core:{tunnel,mcp,bridge}`, `:api`, `:notifications`, `:work`, and
`:integrations`.
Key pieces:
- `:core:tunnel:integrationTest` (real-relay subprocess tier) is now
registered as a `KotlinJvmTest`, not a plain `Test`. Kover's KMP locator
only auto-discovers tasks whose superclass is `KotlinJvmTest`; without
this change, coverage from integration tests (e.g.
`LazyMtlsKeyManager.chooseClientAlias`, exercised only by the real-relay
flow) would silently be dropped from the report.
- Android `testReleaseUnitTest` tasks are excluded via
`instrumentation.disabledForTestTasks`. CI only runs debug unit tests, and
some release-variant unit tests aren't configured to work (e.g. Roborazzi
screenshot tests in `:notifications`).
- Filters exclude generated code: `BuildConfig`, Compose `ComposableSingletons`
+ `*_ComposableKt`, kotlinx.serialization `$$serializer`, Room `*_Impl`,
and Hilt/Koin glue for future-proofing.
- `:app`'s release-signing check is tightened to the exact signing-triggering
task names so Kover's transitively-scheduled `packageReleaseResources` /
`packageReleaseUnitTestForUnitTest` no longer trip the fail-fast guard.
- CI runs `koverHtmlReport koverXmlReport` after the existing test steps,
uploads the HTML as `test-coverage` artifact, and writes a per-module line
coverage summary to `$GITHUB_STEP_SUMMARY` (awk over each module's XML).
No `koverVerify` rule — report-only for the first pass as specified in #248.
Verified on the aggregated XML: `LazyMtlsKeyManager.chooseClientAlias` reports
`LINE covered=1 missed=0` (was unreachable from unit tests alone).
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Shorten tool descriptions and drop redundant parameter descriptions
across all integrations to reduce per-session token cost on tools/list.
Per-integration tools/list bytes (before -> after):
- outreach: 3342 -> 2358 (-29.4%)
- usage: 1845 -> 1437 (-22.1%)
- health: 1070 -> 838 (-21.7%)
- notifications: 1848 -> 1349 (-27.0%)
Also teach the param DSL to skip emitting "description" when it's
empty, so self-evident params (e.g. a required `text` string) don't
pay for a useless description field.
No tools removed, no parameter names or types changed. Added a test
that measures tools/list byte size per integration (useful for future
audits).
Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
Two test groups covering the queryInstalledApps fix from 50ef690d:
1. Functional behavior (8 tests): ShadowPackageManager with fake apps
verifying system-app filtering, launcher-intent requirement, updated
system app passthrough, name filter, and JSON output structure.
2. Manifest assertions (3 tests): XML-parsed verification that the
integrations module manifest declares the required <queries> entries
(MAIN+LAUNCHER, ACTION_VIEW https, ACTION_VIEW http) for Android 11+
package visibility.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
"AI client wants to open Spotify" is now "Claude wants to open Spotify"
when the calling client supplied client_name during OAuth DCR. Falls
back to the generic "AI client" label when no name is set.
Plumbing:
- TokenStore gains resolveClientName(integrationId, token). Both the
in-memory and Room-backed implementations resolve from the stored
DCR label (or null when that equals the opaque clientId).
- McpRouting.handleMcp reads the name right after bearer validation
and wraps the SDK dispatch in withContext(McpClientContext(...)),
a tiny CoroutineContext.Element in :core:mcp.
- LaunchRequestNotifierApi.postLaunchApp / postOpenLink take an
optional clientName. LaunchRequestNotifier uses it to format the
notification title (%1$s wants to open %2$s).
- OutreachMcpProvider's launch_app and open_link tools read the name
from coroutineContext[McpClientContext] and pass it to the notifier
fallback.
Non-goals: this only touches the launch-app/open-link notifications.
Other user-facing prompts (auth approval, per-tool-call) already show
client identity via a different path and are unchanged.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Android 11+ package-visibility filtering makes getInstalledApplications()
and getLaunchIntentForPackage() return a very small subset unless the
caller declares <queries> or holds QUERY_ALL_PACKAGES.
OutreachMcpProvider.queryInstalledApps filters to apps that "have a
launcher" (MAIN + LAUNCHER) and launchApp invokes getLaunchIntentForPackage,
so the right shape is an <intent> query for MAIN+LAUNCHER. Also add
ACTION_VIEW queries for http/https so open_link can resolve browsers /
deep-link handlers.
Not using QUERY_ALL_PACKAGES -- Play Store policy is strict about that
permission and the targeted queries give us what the tools need.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
NotificationCaptureService created its own NotificationDatabase via
`by lazy { NotificationDatabase.create(this) }`, producing a second Room
instance against the same SQLite file as the Koin-provided singleton
used by NotificationMcpProvider. Two instances wastes memory and can
cause subtle cache inconsistencies between the writer (service) and
reader (search tool).
Switch the service to `by inject()` so it shares the NotificationDao
and FieldEncryptor singletons already bound in AppModule. Adds
koin-android to :integrations so the service can use the inject
extension.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Convert NotificationMcpProvider's five tools (list_active_notifications,
perform_notification_action, dismiss_notification,
search_notification_history, get_notification_stats) from hand-rolled
server.addTool(...) calls to McpTool subclasses registered via
server.registerTool { ... }. Provider shrinks from 412 -> 313 LOC (-24%)
and drops the previous LongMethod-sized registerPerformAction helper in
favour of a dedicated PerformNotificationActionTool subclass.
Wire format stays byte-identical for happy-path results and tool-logic
errors (own-notification guards, allowActions policy). Required-param
errors now use the framework's uniform message format.
The #151 lockdown test (asserts exactly these five tool names + schema
round-trip) continues to pass unchanged.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Converts HealthConnectMcpServer's three tools (list_record_types,
query_health_data, get_health_summary) from hand-rolled
server.addTool() calls to McpTool subclasses registered via
server.registerTool { ... }.
Wire format for success + tool-logic errors is byte-identical:
- Date parsing (accepting both ISO-8601 instants and date-only
strings) stays inside the tool logic via StringParam rather than
InstantParam, so "2026-04-01" keeps working on the happy path.
- Period validation message stays tool-logic so the existing
"Invalid period" error text is preserved.
Provider LOC drops 37% (267 -> 167).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Convert `UsageMcpProvider` from hand-rolled `server.addTool(...)` calls
to `McpTool` subclasses registered via `server.registerTool { ... }`.
Each of the four tools (`get_usage_summary`, `get_app_usage`,
`get_usage_events`, `compare_usage`) is now a dedicated class that
declares its parameters via the DSL and returns `ToolResult`. Wire
format for success and tool-logic errors is byte-identical.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Converts all ten outreach tools (launch_app, open_link, copy_to_clipboard,
send_notification, create/list/delete_notification_channel,
list_installed_apps, get/set_dnd_state) from hand-rolled addTool blocks
to McpTool subclasses registered via server.registerTool { ... }.
The provider file shrinks from 883 to 547 lines: hand-built JSON schema
builders, manual argument extraction, and the errorResult / successResult
helpers collapse into the framework. OutreachMcpProviderTest is unchanged
— the existing "expected tool count + names" assertion now serves as the
registration lockdown.
Wire format for successful calls and tool-logic errors is byte-identical
to the previous implementation; the outreachSuccess / outreachError
helpers preserve the `{"success":true,"message":...}` and
`{"success":false,"error":...}` envelopes. Framework-level parameter
validation (missing required, type mismatch, range / choice) is the only
output path whose format changed — and those paths had no test coverage
or user-facing contract.
Also suppresses ReturnCount on each ParamDef.extract to keep detekt at
baseline; those functions are intentionally a series of short-circuit
guards.
Three follow-up issues will be filed for the remaining providers
(:usage, :health, :integrations/notifications) per the migration plan
in #123.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Final consolidation commit:
- :app depends on :integrations (and :notifications) instead of the four
separate modules.
- AppModule.kt, integration registry classes, ViewModels, screens, and
destinations updated to import from the new com.rousecontext.integrations
and com.rousecontext.notifications packages.
- settings.gradle.kts drops :outreach, :usage, :health.
- outreach/, usage/, health/ directories removed (build.gradle.kts and
AndroidManifest.xml only — all sources moved in the per-subtree commits).
- CI workflow collapses the four test tasks into :integrations:testDebugUnitTest.
- README module table reflects the new layout.
- New IntegrationOrthogonalityTest enforces the "integrations must remain
independent" rule by failing if any integration source file imports from
a sibling integration package.
Behavior preserved: APK permission set is byte-identical to main (verified
via aapt2 dump permissions), Koin graph wires the same providers in the
same order, tools/list returns identical tool counts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Pure subtree relocation + package rename
(com.rousecontext.notifications.capture -> com.rousecontext.integrations.notifications).
FieldEncryptor stays in :notifications as cross-cutting infra (it is also
used by :notifications/audit/RoomAuditListener) and moves up one package
to com.rousecontext.notifications.FieldEncryptor. All callers updated.
App-side wiring (registry, Koin, ViewModels) updated in the final
consolidation commit.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Pure subtree relocation + package rename
(com.rousecontext.mcp.health -> com.rousecontext.integrations.health,
com.rousecontext.mcp.health.query -> com.rousecontext.integrations.health.query).
Internal imports inside the health tree updated; intra-health query refs
preserved. App-side wiring updated in the final consolidation commit.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Pure subtree relocation + package rename
(com.rousecontext.usage -> com.rousecontext.integrations.usage).
App-side wiring updated in the final consolidation commit.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Pure subtree relocation + package rename
(com.rousecontext.outreach -> com.rousecontext.integrations.outreach).
App-side wiring (registry, Koin) still references the old package; fixed
in the final consolidation commit.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Empty module with merged manifest (HC permissions, NotificationListener
service) and union of dependencies from :outreach, :usage, :health, and
:notifications/capture. Subsequent commits move each subtree in.