rouse-context/docs/agent-quickstart.md
monkopedia-coder cca459a34b
Some checks failed
Android CI / test (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build & Test (push) Waiting to run
Deploy docs to GitHub Pages / build (push) Has been cancelled
Deploy docs to GitHub Pages / deploy (push) Has been cancelled
ci: verify the Roborazzi goldens, and prove the check can go red (#628) (#629)
* ci: verify the Roborazzi goldens, and prove the check can go red (#628)

No workflow ran any Roborazzi task. `testDebugUnitTest` executes the
screenshot tests in Roborazzi's DEFAULT mode, which renders each
composable and passes without ever comparing it against the committed
PNG, so #490 and #508 both shipped stale goldens fully green for ~2 and
~9 weeks; the drift surfaced only because an unrelated PR happened to
run a record task.

Adds `:app:verifyRoborazziDebug :notifications:verifyRoborazziDebug` to
android-ci.yml's `test` job -- `:notifications` had the identical hole
for its own 40 goldens -- and uploads the comparison images on failure.

Placement is measured, not assumed. Verify mode is a task INPUT: a plain
`:app:testDebugUnitTest -Pgoogle` re-executes after a bare verify run
instead of reporting UP-TO-DATE, so a verify step above `Coverage report
(Kover)` would falsify that step's documented reuse and add a full suite
re-run inside its 10-minute cap. The verify run also overwrites
`app/build/reports/tests/`, so above `Upload test reports` it would
clobber a failing run's report with its own -- #626's
artifact-that-omits-the-failure. Hence: last.

The upload carries `outputs/roborazzi/` (the `_actual`/`_compare` PNGs),
`reports/roborazzi/` (the HTML index, whose <img> tags are repo-relative
links INTO outputs/, so both trees must ship together with paths intact)
and `test-results/roborazzi/`, with `if-no-files-found: error` so a moved
path goes red rather than producing an empty artifact.

`scripts/check-roborazzi-coverage.sh` is the positive control: Roborazzi
prints BUILD SUCCESSFUL both when it compared 129 goldens and when it
compared zero, which is the state CI was already in. The script asserts
the tally Roborazzi writes equals the number of golden PNGs committed,
derived from the filesystem rather than hardcoded.

Closes #628

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

* ci: close the vacuity hole in the Roborazzi coverage control (#628)

The control added in 3c3380d1 asserts that Roborazzi's own tally equals
the number of golden PNGs committed. An equality check has a vacuous
solution -- zero goldens on disk against zero images compared -- and
`0 -eq 0` is a pass. Verified: with app/screenshots and the fastlane
tree emptied and the summary reporting total 0, the control printed
"OK [app]: verified 0 goldens" and exited 0. That is the defect it was
written to catch, one level up.

Each module must now find a NON-ZERO number of goldens. A renamed tree,
a moved directory, or a `*.png` glob that stops matching takes the
goldens and the comparison out together, and that is a red flag rather
than a clean run.

Adds scripts/tests/check-roborazzi-coverage-test.sh, matching the
harness shape of the #577/#590/#594 gate self-tests: a throwaway tree,
the REAL script run end-to-end, nine cases covering both zero-glob
shapes (deleted / renamed), understated and overstated totals, drift
confined to the fastlane tree, per-module attribution, a missing
summary and an unparseable one. Red cases must also SAY what is wrong,
not merely exit nonzero.

The self-test is not vacuous either: with the new guard removed, it
fails on exactly the zero_glob case and names it. Wired into the `test`
job beside the other gate self-tests -- no JDK, under a second -- so a
regression in the control reports in seconds instead of surviving
because the thing it guards was healthy that day (#597).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

* ci: count distinct goldens, and gate the step order (#628 review)

Two review findings, both real.

1. The coverage control asserted on `summary.total`, which counts
   comparisons PERFORMED. `:app` applies the test-retry plugin, so each
   genuinely drifted image is compared up to 3x. Measured on one
   deliberately flipped pixel: total 131, distinct goldens 129, goldens
   on disk 129 -- and the control fired

     FAIL [app]: Roborazzi compared 131 images, but 129 golden PNGs ...

   alongside the real drift. So it misdiagnosed every actual drift as a
   coverage problem, and was correct only on fully-green runs, which is
   when it has nothing to catch. It now de-duplicates
   `results[].golden_file_path`, which is per-image rather than
   per-execution; against the same retry-inflated summary it reports
   "129 distinct goldens" and stays quiet, leaving the drift to the
   verify task alone.

   Two self-test cases pin it: 7 comparisons over 5 distinct goldens
   must pass, and retries must not paper over a golden that was never
   compared (4 distinct where 5 are committed must still fail).

2. The step ordering was documented in a comment but ungated, and the
   reviewer was right that ~15 lines of parsing covers it.
   scripts/check-roborazzi-step-order.sh asserts the verify step stays
   after "Upload test reports" (above it, the re-run overwrites
   app/build/reports/tests/ before that upload collects it -- #626's
   exact live failure mode) and after "Coverage report (Kover)" (verify
   mode is a task input; above it, that step's documented UP-TO-DATE
   reuse is falsified). A missing or renamed step is a failure, not a
   vacuous pass.

Both new scripts hit the same `set -euo pipefail` trap -- grep exits 1
on no match, which propagated out of a command substitution and killed
each script before it could print its finding, exiting 1 with NO output.
Both self-tests caught it, because they assert the red cases SAY what is
wrong rather than merely exiting nonzero.

21 self-test cases across the two gates, all green. The step-order gate
reports positions among NAMED steps, since bare `- uses:` steps carry no
name; only relative order is asserted.

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>
2026-08-28 08:01:25 -04:00

9.3 KiB

Agent quickstart

Distilled commands and paths agents reach for repeatedly. Pre-loading saves grep-then-discover cycles.

JSON construction (mandatory)

Tools that return structured data MUST use @Serializable data classes plus Json.encodeToString (or Json.encodeToJsonElement if a tree is preferable). Manual template literals — """{"field":"$value"}""" — are NOT permitted in production code.

Why

#417 shipped malformed JSON to user testing because a template-literal error helper interpolated a raw exception message containing quotes, producing output the connector proxy refused to parse. The @Serializable + encodeToString path escapes embedded quotes / backslashes / control characters automatically; the manual path does not.

Two enforcement gates

  1. Test harness — McpToolTestHarness at integrations/src/test/kotlin/com/rousecontext/integrations/testing/ parse-asserts every CallToolResult body returned through it. Any tool whose result body fails Json.parseToJsonElement causes the test to fail with the offending tool name and body content.
  2. Static check — scripts/check-no-manual-json.sh runs in the Android CI workflow. Greps for """{ in */src/main/*.kt and fails the build on unallowlisted matches.

The // allow-manual-json marker

For the rare case where a template literal is genuinely safe (e.g. a @Preview-only Compose fixture with hard-coded literals that never see runtime input), append a marker comment to the line:

val sample = """{"steps":7000}""" // allow-manual-json: @Preview fixture, no interpolation

The reason text after the colon should describe why this isn't a runtime risk — typically because no user-controlled value flows into the template. A reviewer should treat the absence of a clear reason as a blocker.

AuditDetailScreen.kt is implicitly allowlisted in the script because its preview fixtures exist purely for IDE rendering; new files should use the inline marker rather than expanding the file allowlist.

Test harness usage

When writing or refactoring an *McpProvider*Test, use McpToolTestHarness rather than hand-rolling the mockk capture pattern:

private val harness = McpToolTestHarness()
private val fakeConnection: ClientConnection = mockk(relaxed = true)

@Before fun setUp() {
    val server = harness.createMockServer()
    MyMcpProvider(...).register(server)
}

@Test fun `tool does the thing`() = runBlocking {
    val result = harness.callTool(
        name = "my_tool",
        arguments = buildJsonObject { put("x", JsonPrimitive(1)) },
        connection = fakeConnection
    )
    // Body is guaranteed JSON-parseable; assert further as needed.
}

Pass expectJsonBody = false only for tools whose contract specifies a plain-text body (rare). Document the reason inline if you do.

Module → path map

:app                       app/
:core:tunnel               core/tunnel/
:core:mcp                  core/mcp/
:core:bridge               core/bridge/
:core:testfixtures         core/testfixtures/
:api                       api/
:integrations              integrations/
:notifications             notifications/
:work                      work/
:device-tests              device-tests/
:e2e                       e2e/
relay (Rust)               relay/

Source-of-truth for the module list is settings.gradle.kts:25-35.

Build & test recipes

All Gradle commands need JAVA_HOME=/usr/lib/jvm/java-21-openjdk.

# Build a debug APK. Distribution is a build flag, not a flavor (#467):
#   bare      = FOSS (Firebase-free; no google-services.json required)
#   -Pgoogle  = Firebase/FCM/Crashlytics (needs app/google-services.json)
./gradlew :app:assembleDebug
# → app/build/outputs/apk/debug/app-debug.apk  (FOSS)
./gradlew :app:assembleDebug -Pgoogle
# → app/build/outputs/apk/debug/app-debug.apk  (Google; overwrites the above)

# Build a release APK (shipping build is the Google distribution)
./gradlew :app:assembleRelease -Pgoogle
# → app/build/outputs/apk/release/app-release.apk

# Unit tests for one module
./gradlew :core:mcp:jvmTest                       # KMP/JVM
./gradlew :app:testDebugUnitTest                  # Android-only (FOSS)
./gradlew :app:testDebugUnitTest -Pgoogle         # Android-only (Google)
./gradlew :integrations:testDebugUnitTest         # Android-only

# Tunnel integration tests (against real relay binary)
./gradlew :core:tunnel:integrationTest --tests '*OAuthEndToEndTest*'

# E2E (against a real device — requires adb host + serial)
./gradlew :e2e:e2eTest -Dadb.host=adolin -Dadb.serial=1B151FDEE008EY

# Lint & analysis (whole tree)
./gradlew ktlintCheck detekt

# Format
./gradlew ktlintFormat

Screenshot goldens (Roborazzi)

:app and :notifications commit golden PNGs and compare against them in CI (#628). testDebugUnitTest alone does NOT compare — it renders and passes — so a UI change that reflows a shared component looks green locally and goes red on the Screenshot goldens match the committed PNGs step. That is expected: the goldens need re-recording as part of the change that caused the drift.

# Compare against the committed PNGs (what CI runs). --continue so a mismatch
# in one module still reports the other's.
./gradlew :app:verifyRoborazziDebug :notifications:verifyRoborazziDebug --continue

# On a mismatch: <name>_actual.png and <name>_compare.png land in
# app/build/outputs/roborazzi/, and an HTML index in
# app/build/reports/roborazzi/debug/index.html. CI uploads both as the
# `roborazzi-screenshot-diffs` artifact.

# Re-record after an intended UI change, then EYEBALL the diff before committing
./gradlew :app:recordRoborazziDebug
./gradlew :notifications:recordRoborazziDebug

Golden locations: app/screenshots/ (the browsable gallery), fastlane/metadata/android/en-US/images/phoneScreenshots/ (the F-Droid store listing, written by ListingScreenshotTest), notifications/screenshots/.

Relay (Rust)

cd relay
cargo test
cargo clippy --all-targets --all-features -- -D warnings
cargo fmt

NEVER build the relay on the GCP VPS. The PR-to-main triggers .github/workflows/relay-deploy.yml (or similar) which cross-compiles + deploys.

GitHub CLI patterns

# Concise CI status
gh pr checks NNN --json name,state --jq '.[] | "\(.name)\t\(.state)"'

# Open PR
gh pr create --title "..." --body "..."

# Merge + delete branch (squash)
gh pr merge NNN --squash --delete-branch

# Issue management
gh issue create --title "..." --body "..." --label in-progress
gh issue edit NNN --add-label in-progress
gh issue edit NNN --remove-label in-progress
gh issue close NNN --comment "..."

# Just the body of a comment thread
gh issue view NNN --comments --json comments --jq '.comments[].body'

Local-branch-deletion gotcha

If gh pr merge --delete-branch fails because another worktree has the branch checked out:

cd /home/jmonk/git/rouse-context && git checkout --detach origin/main && git branch -d <branch>

adb via SSH (test device)

# adolin Pixel 6 Pro (agent-controlled)
ADB="ANDROID_SERIAL=1B151FDEE008EY /opt/android-sdk/platform-tools/adb"
ssh adolin "$ADB <command>"

# Common operations
ssh adolin "$ADB shell pidof com.rousecontext.debug"
ssh adolin "$ADB shell pm clear com.rousecontext.debug"
ssh adolin "$ADB shell am start -n com.rousecontext.debug/com.rousecontext.app.MainActivity"
ssh adolin "$ADB shell run-as com.rousecontext.debug ls files/"
ssh adolin "$ADB logcat -d -s 'Onboarding:*' 'TunnelClient:*' '*:S'"   # filter at logcat level

# Kill app cleanly (NOT am force-stop — that disables FCM until manual relaunch).
# Use cmd activity stop-app: kills the process including foreground services
# but leaves FCM reachable. See #394.
ssh adolin "$ADB shell cmd activity stop-app com.rousecontext.debug"

# Install
scp app-debug.apk adolin:/tmp/
ssh adolin "$ADB install -r /tmp/app-debug.apk"

UI automation on device

Drive Android UI via uiautomator dump XML, NOT screencap PNGs (resolution blows up context). See /tmp/drive_onboard.sh for the pattern (extract bounds via regex on text="..."[^>]*bounds="[x1,y1][x2,y2]").

Relay over gcloud

gcloud compute ssh relay --zone=us-central1-a --command='sudo journalctl -u rouse-relay -f'
gcloud compute ssh relay --zone=us-central1-a --command='systemctl status rouse-relay | head -5'

Common files to know

  • core/tunnel/src/jvmMain/.../OnboardingFlow.kt — canonical onboarding sequence
  • app/src/main/.../OnboardingViewModel.kt — canonical VM (post-#392 single-VM invariant)
  • app/src/main/.../navigation/AppNavigation.kt + Routes.kt — nav graph + routes
  • core/tunnel/src/jvmMain/.../TunnelClientImpl.kt — tunnel client
  • core/tunnel/src/jvmMain/.../MuxFrame.kt / MuxDemux.kt — mux protocol
  • relay/src/api/ — relay HTTP/WS endpoints
  • relay/src/passthrough.rs — TLS-passthrough decision + FCM wake
  • relay/src/rate_limit.rs — rate limiters (FcmWakeThrottle, etc.)
  • docs/design/relay-api.md — endpoint catalog (kept current as of #410)
  • docs/design/android-app.md — module map + dep graph (kept current as of #408)
  • docs/design/overall.md — system overview (kept current as of #409)
  • docs/ux-decisions.md — UX flow decisions log

When in doubt

  • Code is the source of truth over docs.
  • A .claude/rules/* rule is the source of truth over a memory entry.
  • The user's most recent in-session direction overrides everything else.