Skip to content

refactor(mobile-e2e): simplified runbook, scripted stub setup, load-tolerant flows - #4960

Merged
iscekic merged 31 commits into
mainfrom
mobile-e2e-ste
Aug 3, 2026
Merged

iscekic merged 31 commits into
mainfrom
mobile-e2e-ste

Conversation

@iscekic

@iscekic iscekic commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

Summary

Refactors the mobile E2E harness so weak agent models can run it without misreading anything, and removes the flakiness found in a full-load test (two parallel dual-platform bundles: 2 dev stacks, 2 iOS simulators, 2 Android emulators).

  • e2e/AGENTS.md rewritten in strict simplified technical English: task-structured, one instruction per sentence, 410 → ~215 lines. Everything mechanical now defers to scripts; the runbook keeps only rules and judgment.
  • New e2e/github-stub.sh start|status|stop: the PR-review GitHub stub setup was a three-step manual ritual (env-file edit, next-auth fake-login curl dance to seed the token row, hand-started tmux server). It is now one command each way, with the env line tagged and removed on stop.
  • emulator-start --wait now applies the launch/GPU retry policy itself (one automatic relaunch: boot-envelope timeout keeps the GPU, every other failure switches to software rendering). The runbook's 40-line decision table is gone; callers just read the error after the second failure.
  • Load-tolerance fixes from the full-load test: iOS cold-launch and settle budgets were 30s/15s (Android already had 420s/300s) and timed out under parallel load; both are now 120s. The waits return as soon as a state renders, so healthy runs pay nothing.
  • Simulator claims record originalDeviceName in the initial claim write, so a claim that dies between rename and the full record write can still restore the device's real name on release (found a simulator carrying a stale Kilo E2E - … label from exactly this window).

Verification

  • Full-load campaign, five rounds: two sections in parallel, each bundle <avd> (stack + iOS simulator + Android emulator — both machine slots full), real e2e-verifier sessions executing launch scenarios on all four devices. Final round with these fixes: both sections VERIFICATION PASSED, teardown clean (no leaked slots, devices, emulators, or stacks) in all five rounds. The campaign is what surfaced the iOS launch budgets, the ANR misjudgment, the hierarchy context-dump, and the claim-flag loss this PR fixes.
  • github-stub.sh exercised end to end against a live worktree stack: start (server up, env line written, token row seeded through fake-login), fixture served over HTTP, status, stop (env line removed, session gone), plus the failure path (missing user) cleaning up after itself.
  • Runbook comprehension: 10 scenario drills against fresh weak-model (kilo-auto/efficient) sessions, 10/10 correct (emulator double-failure handling, selector discipline, stub setup, keyboard dead zones, cleanup ordering, port rules, recording segmentation, foreign-data triage).
  • pnpm typecheck, pnpm lint, pnpm format green. pnpm test: web suite green (8814 passed / 3 skipped); the two dev/local/tmux.test.ts failures reproduce identically on origin/main on this machine (pre-existing, unrelated).

Visual Changes

N/A

Reviewer Notes

  • The emulator retry lives in dev/local/mobile-android.ts (emulator-start handler); stopAndroidEmulator is already safe to call with no record, which is what makes the blind stop-then-retry correct.
  • github-stub.sh refuses to overwrite a GITHUB_API_BASE_URL line it did not write (marker comment).

…olerant flows

- rewrite e2e/AGENTS.md in simplified technical English: task-structured,
  scripts own the mechanics, 410 -> ~215 lines
- new e2e/github-stub.sh: PR-review stub server + env line + token seed
  as one reversible command pair; failed starts clean up after themselves
- emulator-start --wait retries a failed launch once itself (boot-envelope
  timeout keeps the GPU, other failures switch to software rendering);
  the runbook's manual GPU decision table is gone
- appium.sh hierarchy writes to a file and prints the path; a raw XML dump
  into an agent session is large enough to kill it silently
- raise iOS cold-launch/settle budgets to 120s (timed out under parallel
  dual-bundle load); document ANR-under-load handling
- simulator claims record originalDeviceName and bootedByClaim intent in
  the initial write, so a lost post-boot rewrite can no longer leak a
  renamed or still-booted device on release
@iscekic iscekic self-assigned this Aug 1, 2026
Comment thread dev/local/mobile-android.ts Resolved
Comment thread apps/mobile/e2e/github-stub.sh Resolved
Comment thread apps/mobile/e2e/github-stub.sh Resolved
@kilo-code-bot

kilo-code-bot Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Summary

Status: No Issues Found | Recommendation: Merge

Executive Summary

The readback now asserts the account holds exactly the installation it wrote (githubApps.listIntegrations), which removes the ordering ambiguity the previous review flagged; no new issues in this increment.

Verification performed

  • githubApps.listIntegrations exists as a baseProcedure.query with optionalOrgInput (z.object({organizationId}).optional()), so the script's GET with no input parameter validates (apps/web/src/routers/github-apps-router.ts:38-44).
  • It returns full platform_integrations rows filtered to platform = 'github' for the resolved owner, with no LIMIT and no ordering (apps/web/src/lib/integrations/github-apps-service.ts:31-42), so the node filter's rows.map(row => row.platform_installation_id) matches the serialized column name in packages/db/src/schema.ts:3981. The table has no soft-delete column, so no deleted rows can inflate the set.
  • The exactly-one-row assertion resolves the earlier forceRefresh:false concern: the unordered readers (getIntegrationForOwner, apps/web/src/lib/integrations/db/platform-integrations.ts:457-478) now have a single candidate, so a silent backfill can no longer mask a wrong row.
  • Dropping the previous installed=true check loses nothing: upsertPlatformIntegrationForOwner sets integration_status = active and clears auth_invalid_at/auth_invalid_reason on the row the mutation just wrote (apps/web/src/lib/integrations/db/platform-integrations.ts:593-628), so the row is healthy by construction at readback time.
  • Shell safety under set -euo pipefail: curl ... || fail, the case $CODE guards, and ${LIVE_IDS:-none} keep an empty or absent node output on the fail readback path rather than tripping unbound-variable errors; the empty-array and non-array cases both surface as [none].

Resolved since the previous review

  • github-installation.sh:108 (forceRefresh:false self-healing readback could pass with a second valid github row): addressed — the script now requires the account to hold exactly the written installation before the repository readback, so the unordered reader has only one row to pick.

Notes and assumptions

  • Static review only; nothing was executed, per read-only mode.
  • Incremental scope: apps/mobile/e2e/AGENTS.md and apps/mobile/e2e/github-installation.sh only. Earlier threads on github-stub.sh, appium.sh, dev/local/mobile-android.ts, and unchanged lines of this script are outside this increment and were not re-evaluated.
  • The summary comment body could not be read directly (that endpoint form is blocked); the trusted comment ID was verified through the paginated issue-comments list and starts with the <!-- kilo-review --> marker.
Files Reviewed (2 files)
  • apps/mobile/e2e/github-installation.sh
  • apps/mobile/e2e/AGENTS.md
Previous Review Summaries (8 snapshots, latest commit 22f6b81)

Current summary above is authoritative. Previous snapshots are kept for context only.

Previous review (commit 22f6b81)

Status: 1 Issue Found | Recommendation: Address before merge

Executive Summary

The new repository readback in github-installation.sh now hits the unordered reader the cloud-agent flow actually uses, but with forceRefresh:false that reader backfills whichever row it picked from live GitHub, so a wrong-but-valid second installation row still passes the check.

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 1
Issue Details (click to expand)

SUGGESTION

File Line Issue
apps/mobile/e2e/github-installation.sh 108 forceRefresh:false makes the repository readback self-healing: an empty cache on the winning row triggers a live GitHub fetch plus write-back, and the response carries no installation id, so another valid github row can win the unordered read and still pass

Verification performed

  • Endpoint exists and matches the script's usage: cloudAgentNext.listGitHubRepositories is a baseProcedure.query taking { forceRefresh?: boolean } and returning { repositories, integrationInstalled, syncedAt, errorMessage } (apps/web/src/routers/cloud-agent-next-router.ts:455-479), so the -G --data-urlencode 'input={"forceRefresh":false}' GET and the integrationInstalled/repositories fields the node filter reads all resolve. No superjson transformer is configured for this router, so the plain result.data fallback is the live shape.
  • Reader claim in the new comment is correct: apps/mobile/src/app/(app)/agent-chat/new.tsx:140-146 is the mobile new-session screen and it queries cloudAgentNext.listGitHubRepositories; that handler resolves the row through the unordered getIntegrationForOwner (apps/web/src/lib/integrations/db/platform-integrations.ts:457-479).
  • Backfill path traced: with forceRefresh false and empty cached repositories, fetchGitHubRepositoriesForUser fetches from GitHub and calls updateRepositoriesForIntegration before returning (apps/web/src/lib/cloud-agent/github-integration-helpers.ts:171-216), which is the basis of the reported finding. A revoked installation instead raises TRPCError → non-2xx, which line 101 catches.
  • Shell safety of the new block under set -euo pipefail: the curl ... || fail, case $CODE and ${REPO_COUNT:-0} guards keep an empty or absent node output on the fail repo-readback path rather than tripping unbound-variable or arithmetic errors.

Resolved since the previous review

  • github-installation.sh:82 (readback used only the ordered githubApps.getInstallation reader): addressed — the script now additionally asserts the unordered cloud-agent repository reader.
  • apps/mobile/e2e/AGENTS.md:49 ("every reader takes one row without ordering"): addressed — the sentence now distinguishes the ordered installation-screen reader from the unordered cloud-agent repository reader.

Notes and assumptions

  • Static review only; nothing was executed, per read-only mode.
  • Incremental scope: apps/mobile/e2e/AGENTS.md and apps/mobile/e2e/github-installation.sh only. Earlier threads on github-stub.sh, appium.sh, and dev/local/mobile-android.ts are outside this increment and were not re-evaluated.
  • The summary comment body could not be re-read before updating (permission denied for that read); the comment ID supplied by the review prompt was treated as authoritative.
Files Reviewed (2 files)
  • apps/mobile/e2e/github-installation.sh - 1 issue
  • apps/mobile/e2e/AGENTS.md - 0 issues

Fix these issues in Kilo Cloud

Previous review (commit eaa4bfb)

Status: 2 Issues Found | Recommendation: Address before merge

Executive Summary

The new readback in github-installation.sh closes most of the previously reported multi-row hazard, but it asserts against githubApps.getInstallation (ordered by health then updated_at DESC) rather than the unordered getIntegrationForOwner reader the cloud-agent repository list actually uses, so a pass is weaker than the script comment and runbook claim.

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 2
Issue Details (click to expand)

SUGGESTION

File Line Issue
apps/mobile/e2e/github-installation.sh 80 Readback uses the ordered githubApps.getInstallation reader, not the unordered getIntegrationForOwner path the repo list and token lookups use; the just-bumped updated_at biases the ordered read toward returning the row the script wrote
apps/mobile/e2e/AGENTS.md 49 "every reader takes one row without ordering" is inaccurate for the readback endpoint and the organization helper, both of which order by health then updated_at DESC

Verification performed

  • githubApps.getInstallation exists, takes optionalOrgInput (.optional()), and returns { installed, installation: { installationId, repositories, ... } } (apps/web/src/routers/github-apps-router.ts:91-132), so the input-less GET and the installationId/repositories/installed fields the script parses all resolve.
  • Row selection traced end to end: githubAppsService.getInstallation orders by health then updated_at DESC (github-apps-service.ts:48-62); getIntegrationForOwner is a bare .limit(1) (platform-integrations.ts:472-476) and is what devAddInstallation re-reads before writing repositories (github-apps-router.ts:363-368) and what fetchGitHubRepositoriesForUser reads for the mobile repo list (cloud-agent/github-integration-helpers.ts:171-175). The upsert bumps updated_at on its update branch (platform-integrations.ts:595-610).
  • Shell behaviour of the new block checked against set -euo pipefail: the here-string always yields a line, so read succeeds and leaves the three variables empty when the node filter prints nothing or exits non-zero; the ${LIVE_ID:-none} / ${REPO_COUNT:-0} guards then produce a fail readback rather than an unbound-variable or arithmetic error, and the [ ... ] && [ ... ] || fail chain is set -e-safe.
  • The node filter handles both superjson (result.data.json) and plain (result.data) shapes and guards repositories with Array.isArray, so a null repository list yields 0 instead of a throw.

Resolved since the previous review

  • The previous "success":true finding (github-installation.sh:72) is now largely addressed: when the mutation writes the repository list onto the account's other github row, the readback returns the just-written row with zero repositories and fails. The residual gap is the reader mismatch reported above.

Notes and assumptions

  • Static review only; nothing was executed, per read-only mode.
  • Incremental scope: apps/mobile/e2e/AGENTS.md and apps/mobile/e2e/github-installation.sh only. Findings on files outside this increment were not carried forward; earlier threads on github-stub.sh, appium.sh, and dev/local/mobile-android.ts are unaffected.
  • The summary comment body could not be re-read before updating (permission denied for that read); the comment ID from the review prompt was used as authoritative.
Files Reviewed (2 files)
  • apps/mobile/e2e/github-installation.sh - 1 issue
  • apps/mobile/e2e/AGENTS.md - 1 issue

Fix these issues in Kilo Cloud

Previous review (commit b45a153)

Status: 1 Issue Found | Recommendation: Address before merge

Executive Summary

The increment (96200a3e0..b45a153f1) replaces the app:github-integration-copy seed with a new apps/mobile/e2e/github-installation.sh that drives the dev-only githubApps.devAddInstallation mutation; the only issue found is that the script's "success":true gate cannot distinguish the case where the fetched repository list is written to a different github integration row than the one it just upserted.

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 1
Issue Details (click to expand)

SUGGESTION

File Line Issue
apps/mobile/e2e/github-installation.sh 72 "success":true does not prove the repository list landed on the upserted row when the account holds a second github integration row (the documented <installation-id> override creates one)

Verification performed

  • githubApps.devAddInstallation exists and returns { success: true } (apps/web/src/routers/github-apps-router.ts:326-371), is gated on NODE_ENV === 'development', and needs an authenticated ctx.user, so the fake-login step is required. The plain-JSON, non-batched tRPC POST shape matches the established github-stub.sh call.
  • Port discovery matches cmdStatus (dev/local/cli.ts:898-960): service name nextjs, statuses up/down, and a port field, so the --json filter resolves and the empty result is caught by the [ -n "$API_PORT" ] guard.
  • The set -euo pipefail interaction on grep -q ... && fail ... (line 71) is safe: the failing command precedes the final &&, matching the existing pattern at github-stub.sh:128.
  • Documentation claims checked against code: GITHUB_API_BASE_URL is read only by the PR-review client (apps/web/src/lib/github-pr-review/client.ts:12-17), while the integration adapter uses default-baseUrl Octokit (apps/web/src/lib/integrations/platforms/github/adapter.ts:106-229), so "always reads real api.github.com, even while the stub runs" holds; PR review reads only user_github_app_tokens, so the installation and github-stub.sh genuinely do not conflict.
  • Deletion of dev/seed/app/github-integration-copy.ts is clean: no remaining reference to the file, its exports, or the app:github-integration-copy command anywhere in the repository, and the runbook text that described it was removed in the same commit.
  • Re-running with the default installation id is idempotent (upsertPlatformIntegrationForOwner update branch, platform-integrations.ts:558-610), which is the basis for narrowing the finding above to the multi-row case.

Notes and assumptions

  • Static review only; nothing was executed, per read-only mode.
  • Incremental scope: apps/mobile/e2e/AGENTS.md, apps/mobile/e2e/github-installation.sh, and the deletion of dev/seed/app/github-integration-copy.ts. Findings on files outside this diff were not carried forward; earlier inline threads on github-stub.sh, appium.sh, and dev/local/mobile-android.ts are unaffected by this increment.
  • The two previous AGENTS.md inline threads are now outdated on GitHub (line: null), consistent with their resolutions in 96200a3e0.
  • Whether the shared dev installation 144771093 is a standard (not lite) App installation could not be verified without network access to GitHub; the mutation defaults to standard.
Files Reviewed (3 files)
  • apps/mobile/e2e/github-installation.sh - 1 issue
  • apps/mobile/e2e/AGENTS.md
  • dev/seed/app/github-integration-copy.ts (deleted)

Fix these issues in Kilo Cloud

Previous review (commit 96200a3)

Status: No Issues Found | Recommendation: Merge

Executive Summary

The increment (df4aac264..96200a3e0) rewrites the two apps/mobile/e2e/AGENTS.md lines flagged in the previous review; both new jq examples were verified against the actual command output shapes and no new issues were found.

Previous findings resolved in this increment

File Line Previous finding Resolution
apps/mobile/e2e/AGENTS.md 26 tail -c 2000 was prescribed for --json diagnostics, yielding unparseable JSON Bounding rule is now scoped: tail -c for log-like output only; JSON is field-selected with jq
apps/mobile/e2e/AGENTS.md 91 Warned against a non-existent doctor --json flag and implied bare doctor was bounded Now states doctor takes no flags and always dumps the full environment; the example bounds it with jq

Verification performed

  • pnpm -s dev:status --json | jq -r '.services[] | "\(.name) \(.status)"' — checked against cmdStatus in dev/local/cli.ts:898-952. The payload is { session, portOffset, services: [{ name, port, status, group }] }, so both selected fields exist on every element, including the empty-services cases at :906 and :921.
  • pnpm -s dev:mobile:android doctor | jq -r '.sdkRoot, .avds[]' — checked against dev/local/mobile-android.ts:621-629. doctor prints { ...env, avds, worktree }; sdkRoot comes from AndroidEnvironment (:18-25, populated at :129-136) and avds is a string array, so both filters resolve. The "takes no flags" claim matches if (command === 'doctor' || command === undefined) with no args validation, and the PATH-inclusion claim matches path: process.env.PATH at :139-141.
  • jq was already an established dependency of this runbook (AGENTS.md:98), so the new examples add no new tooling assumption.
  • No contradictions remain between line 26 and the other dev:status --json / tail references (lines 22, 31, 57, 67, 70, 215).

Notes and assumptions

  • Static review only; nothing was executed, per read-only mode.
  • Incremental scope: one file, 6 changed lines. Findings on files outside this diff were not re-verified or carried forward; several earlier inline threads on apps/mobile/e2e/github-stub.sh, apps/mobile/e2e/appium.sh, and dev/seed/app/github-integration-copy.ts remain open on GitHub and are unaffected by this increment.
Files Reviewed (1 file)
  • apps/mobile/e2e/AGENTS.md

Previous review (commit df4aac2)

Status: 2 Issues Found | Recommendation: Address before merge

Executive Summary

The new doctor guidance in apps/mobile/e2e/AGENTS.md warns against a --json flag that does not exist and mislabels bare doctor as bounded, so the runbook now teaches the opposite of what the code does.

Overview

Severity Count
CRITICAL 0
WARNING 1
SUGGESTION 1
Issue Details (click to expand)

WARNING

File Line Issue
apps/mobile/e2e/AGENTS.md 90 doctor ignores all arguments and always prints the full env including PATH, so doctor --json is byte-identical to doctor; the line marks the unbounded command as the safe one

SUGGESTION

File Line Issue
apps/mobile/e2e/AGENTS.md 26 tail -c 2000 applied to --json diagnostics yields unparseable JSON, contradicting line 22 and the stack-start steps that require parsing pnpm dev:status --json

Verified in this increment

  • Line 26 (new bullet): the tail -c 2000 pattern itself is fine for logs and Appium output, and it is consistent with the existing bounded-tail example on lines 29-32. Only the --json scope is problematic.
  • Line 90 (doctor sentence): checked against dev/local/mobile-android.ts. main() destructures const [command, ...args] = process.argv.slice(2); the doctor branch (:621) has no args.length guard and prints JSON.stringify({ ...env, avds, worktree }, null, 2) (:628). AndroidEnvironment (:18-25) includes path, populated from process.env.PATH in environment() (:139-141). No global flag preprocessing exists.
  • The rest of the sentence ("the wrappers resolve the SDK themselves", "prints resolved paths and AVDs") is accurate.

Notes and assumptions

  • Static reading only; nothing was executed, so the actual byte size of doctor output was not measured. The finding does not depend on the size claim, only on --json being a no-op.
  • Incremental scope: f752367e2..df4aac264 touches one file with 2 changed lines. Findings from files outside this diff were not carried forward.
  • No pre-existing inline comments exist on apps/mobile/e2e/AGENTS.md, so neither finding duplicates prior review state.
Files Reviewed (1 file)
  • apps/mobile/e2e/AGENTS.md - 2 issues

Fix these issues in Kilo Cloud

Previous review (commit f752367)

Status: No Issues Found | Recommendation: Merge

Executive Summary

Incremental review of f752367e2 (1 file, 19 changed lines in dev/seed/app/github-integration-copy.ts): the extracted usableUntilMs helper and the new post-probe usable-window re-assertion are behavior-preserving and correct; high confidence.

Verified in this increment

  • usableUntilMs helper (lines 49-54): the 5-minute subtraction matches EXPIRY_BUFFER_MS = 5 * 60 * 1000 in services/git-token-service/src/github-user-authorization-service.ts:48, which gates both the refresh decision (:220) and selectUserAuthorization (:111), so "usable until the refresh buffer opens" remains accurate.
  • New donor re-check (lines 331-336): usableUntilMs(row.access_token_expires_at) - Date.now() < 30 * 60 * 1000 is exactly consistent with the SQL margin access_token_expires_at > now() + interval '35 minutes' (:281) — 35 minutes of expiry margin is 30 usable minutes — so the two guards cannot drift or contradict each other. The continue keeps accessToken/source unassigned, so a fully skipped candidate list still falls through to the BLOCKED throw at :341 rather than copying a stale token.
  • usableUntil return (line 421): new Date(usableUntilMs(source.access_token_expires_at)).toISOString() is semantically identical to the removed inline computation; the value stays a flat string, satisfying the SeedResult contract in dev/seed/AGENTS.md.
  • Column nullability: access_token_expires_at is timestamp({ withTimezone: true, mode: 'string' }).notNull() (packages/db/src/schema.ts:4090), so the helper's string parameter cannot receive null and cannot produce NaN from a missing value.

Notes and assumptions

  • Static reading only; nothing was executed. new Date(<pg timestamptz string>) was not run here — the identical new Date(authorization.access_token_expires_at).getTime() pattern on this same column already ships in github-user-authorization-service.ts:220/483, so it is treated as established.
  • The new re-check runs after the up-to-15s GitHub probe, so with at most 10 candidates it can only ever reclaim a couple of minutes of drift; it is defensive rather than load-bearing, which is what the comment claims.
  • Under --json the per-candidate skip message is suppressed by the runner, so an all-skipped run prints only the generic BLOCKED error. That behavior predates this commit (the probe.ok skip has the same shape) and was not treated as a new finding.
  • Findings from files outside this incremental diff were not carried forward.
Files Reviewed (1 file)
  • dev/seed/app/github-integration-copy.ts

Previous review (commit 36f3437)

Status: No Issues Found | Recommendation: Merge

Executive Summary

Incremental review of 36f34377f (3 files, ~66 changed lines): every previous finding is resolved, and the new copy-lifetime documentation now matches what git-token-service actually does.

Verified in this increment

  • Copy lifetime wording (dev/seed/app/github-integration-copy.ts 344-350, 58-63, AGENTS.md 45-47): the docs no longer claim the expired dummy refresh token prevents a refresh. getUserAccessToken refreshes once access_token_expires_at - now < EXPIRY_BUFFER_MS (github-user-authorization-service.ts:220), GitHub's bad_refresh_token body matches RefreshErrorResponseSchema so refreshAuthorization returns terminal_rejection (:522), and revokeCurrentGeneration sets revoked_at/github_token_rejected on the copy row only (:697). "Reads as revoked, not expired" is accurate, and the row keeps its synthetic id, so the upsert's setWhere re-claims it on the next run as the comment says.
  • 35-minute donor margin (:274) and usableUntil (:406-408): EXPIRY_BUFFER_MS is 5 minutes for both the fetch path and selectUserAuthorization, and no GitHub path uses a larger minimum validity (only Bitbucket has a 55-minute cloud-agent bound), so expiry - 5min is the correct usable boundary and the 35-minute filter really does leave >= 30 usable minutes.
  • --remove reporting (:199-216): the delete now uses .returning() and reports removedRows from the result; a row replaced between the SELECT and the DELETE reports 0 and says so. Previous SUGGESTION resolved.
  • Unused or import (:9): removed. Previous SUGGESTION resolved.
  • --wait 900 (apps/mobile/e2e/github-stub.sh 39-46): the longest lock-held curl chain is csrf + fake-login + trpc-seed + getUserAuthorization at --max-time 120 each = 480s, so the ~8 minute claim holds and 900s clears it. process-lock.ts maps --wait 900 to 900 one-second retries, and the holder refreshes the lockfile every 10s against a 30s stale window, so a queued stop/seed waits instead of failing.
  • Removed SeedResult keys: nothing in the repo consumes accessTokenExpiresAt or refreshable from this topic, so dropping them breaks no caller.
  • AGENTS.md: prose only; no images, HTML tags, or links introduced.
Files Reviewed (3 files)
  • dev/seed/app/github-integration-copy.ts
  • apps/mobile/e2e/github-stub.sh
  • apps/mobile/e2e/AGENTS.md

Notes and assumptions

  • Static reading only; nothing was executed. node is unavailable in this environment, so new Date(<pg timestamptz string>) was not run — the same new Date(access_token_expires_at).getTime() pattern is already used on this column in github-user-authorization-service.ts:220/251 and bitbucket-authorization-service.ts:245, so it is treated as established.
  • nextjs_port() runs pnpm -s dev:status --json inside the lock without an explicit timeout, so the "about 8 minutes" bound covers the curl calls rather than literally every command; with --wait 900 this is not a practical regression and the framing predates this commit.
  • Findings from files outside this incremental diff were not carried forward.

Previous review (commit 66b7904)

Status: 4 Issues Found | Recommendation: Address before merge

Executive Summary

The copy's "already-expired dummy refresh token" does not actually prevent a refresh: git-token-service gates refreshes on the access token's expiry alone, so the bogus token is POSTed to GitHub and the copy row ends up revoked instead of merely expired.

Overview

Severity Count
CRITIC

[Snapshot truncated.]

Additional previous summary content was truncated to keep this comment within platform limits.


Reviewed by claude-opus-5 · Input: 40 · Output: 8K · Cached: 1M

Review guidance: REVIEW.md from base branch main

- emulator-start retry: rethrow the already-exists guard (a retry would
  tear down a live emulator) and keep attempt 1's error when the interim
  teardown itself fails
- github-stub: curl transport failures now route through seed_fail, so a
  failed start still rolls back the session and env line
- github-stub: guard against a .env.local without a trailing newline
  before appending, so the marker line can never merge into (and later
  delete) an existing variable
@iscekic
iscekic enabled auto-merge (squash) August 2, 2026 00:38
- tmux targets use exact-match (=name): bare -t prefix-matches, so a sibling
  worktree whose slug extends ours could be probed or killed in its place
- simulator claims write atomically (temp + rename/link): in-place truncation
  let an unlocked reader see a partial file, judge it corrupt, and delete a
  live claim
- a claim abandoned after its boot (rename failure) now powers the device
  off, or keeps the claim when even that fails
- simctl bootstatus is bounded (15 min) so a wedged CoreSimulator cannot
  block a claim forever
- emulator-start tears down after a failed second attempt too
- github-stub start claims its port machine-globally and verifies its own
  session survived, so two worktrees cannot share one stub silently; stop
  releases the claim
- appium: driver install re-checks inside the install lock; server startup
  verifies port ownership before adopting a listener; stop escalates to
  SIGKILL instead of orphaning a live server
- record.sh serializes start/stop per device with the shared process lock
- open-app consumes its launch budget in 30s slices so an ANR dialog is
  answered promptly instead of after the full wait
- login.sh matches the recipient literally, not as a regex
- hierarchy mktemp template puts Xs last (BSD mktemp leaves embedded Xs
  literal, making every bare call after the first fail)
- AGENTS.md: per-platform mixed fixtures, pull-and-grep for ADB dumps,
  stub-stop token residue note
- mobile-workflow tests updated for the raised launch/settle budgets
Comment thread apps/mobile/e2e/github-stub.sh Resolved
iscekic added 3 commits August 2, 2026 03:06
- appium: the recorded-server fast path now verifies the recorded pid owns
  the listener before adopting (a recycled pid plus a sibling's server on
  the same port answered /status and got adopted)
- github-stub: seeding extracted into seed_token; new 'seed <email>'
  subcommand adds a token row for a second signed-in account (the other
  platform's verifier) without touching the running stub
- github-stub: the port claim covers only the choose-to-bind window and an
  EXIT trap releases it, so an interrupted start cannot leak claims and
  erode the port range
- github-stub: githubUserId carries the pid — concurrent seeds in the same
  second cannot collide on the unique github_user_id
- AGENTS.md: the ADB dump example creates its own mktemp file instead of
  assuming $SCRATCH
devSeedUserGithubToken can answer 200 with success:false (row not
upserted); the status code alone reported a seed that never landed.
A process that survives even SIGKILL kept its state file removed and the
stop reported success; the caller then released device claims over a live
server. stop now fails and keeps the state in that case.
Comment thread apps/mobile/e2e/github-stub.sh Resolved
Comment thread apps/mobile/e2e/appium.sh Resolved
- claim_port reaps an orphaned port claim (older than 120s with nothing
  listening) and the start path traps INT/TERM/HUP besides EXIT, so a
  killed start can no longer shrink the port pool permanently
- githubUserId derives deterministically from the account email: the
  upsert's setWhere only updates a matching row, so the fresh random id
  made every re-seed of an already-seeded account report success:false
  and tear the stub down with a misleading hint
- lsof ownership probes tolerate no-match exits; pipefail otherwise killed
  appium.sh before the fresh-start fallback could run
Comment thread apps/mobile/e2e/github-stub.sh Resolved
Comment thread apps/mobile/e2e/github-stub.sh Resolved
iscekic added 2 commits August 2, 2026 03:37
…ling

- appium startup adopts a port only on proven ownership (listener pid equals
  ours); an empty lsof keeps polling instead of adopting a vanished or
  foreign server
- github-stub signal traps exit instead of continuing a start that just
  released its port claim
- success:false with 200 and no error means an account seeded under an older
  random id — keep that usable row instead of tearing the stub down
success:false can come from an older random-id seed or from a real GitHub
connection on the dev account; the keep-message now says so instead of
implying only legacy seeds, and notes the stub accepts any token.
Comment thread apps/mobile/e2e/github-stub.sh Resolved
Comment thread apps/mobile/e2e/github-stub.sh Resolved
Comment thread apps/mobile/e2e/appium.sh Resolved
…lback

- a kept token row is verified to be the stub's (getUserAuthorization
  githubLogin == kilo-stub-user); a real GitHub connection row fails with a
  drop-the-row hint — under the stub its refresh bypasses
  GITHUB_API_BASE_URL, hits real github.com, and revokes itself
- start rolls back everything (session, env line, state, port claim) via one
  EXIT trap when it dies before the final state write, so an aborted start
  no longer blocks the next one behind 'session already runs'
- appium ownership checks degrade to pid+status when lsof is missing or
  cannot attribute the socket, instead of killing healthy servers across 50
  port blocks
Comment thread apps/mobile/e2e/github-stub.sh Resolved
Comment thread apps/mobile/e2e/github-stub.sh Resolved
Comment thread apps/mobile/e2e/appium.sh Resolved
- the row probe checks HTTP status and error envelope before advising: a
  failed probe reports 'could not determine the existing row' instead of
  confidently telling the operator to delete a row it never examined; a
  kept row must also be connected (a revoked stub row gets the drop hint)
- start's rollback undoes only what this run did (session-created and
  env-added flags), so a start losing the session-creation race cannot kill
  the winner's session, env line, or state
- the recorded-server reuse path applies the same blind-lsof rule as the
  start loop: adopt on pid+status after three blind probes instead of
  orphaning a healthy server and consuming a port block per invocation
- drop dead SEED_FAIL_MODE and the stale random-id comment
Comment thread apps/mobile/e2e/appium.sh Resolved
Comment thread apps/mobile/e2e/github-stub.sh Resolved
Comment thread apps/mobile/e2e/github-stub.sh Resolved
- github-stub creates its session under a pid-unique name armed before the
  create and renames to claim the canonical one: a signal at any instant
  tears down only our own session, and a lost rename race touches nothing
  but our port claim; the env-added flag arms before the append for the
  same reason
- the appium reuse probe rechecks pid liveness and /status on every pass,
  so a server dying mid-probe is cleaned up (stop_server) instead of
  adopted; a foreign listener still only drops our state
Comment thread apps/mobile/e2e/github-stub.sh Resolved
iscekic added 2 commits August 2, 2026 04:11
…windows

Concurrent stub commands raced over the session name, env line, and state
dir; each guard narrowed the window without closing it. The shared
process-lock (the appium.sh pattern) removes the class: one stub command per
worktree at a time, so the entry check is authoritative, the rollback flags
only order against signals, and the unique-name rename dance goes away.
Both row branches run after the account answered the seed call, so the
sign-in hint contradicted what the script had just proved.
@iscekic
iscekic disabled auto-merge August 2, 2026 02:15
Comment thread apps/mobile/e2e/github-stub.sh Resolved
- every network call under the stub lock carries --max-time 30, so a hung
  local API cannot hold the lock to its 300s wait bound; status runs
  unlocked (read-only) and answers during a long start
- a failed session create (a survivor of a SIGKILLed lock wrapper got there
  first) resets the created flag before exiting, so cleanup cannot touch
  the survivor's session
- align the env-append comment with the lock (the rename step it cited is
  gone)
Comment thread apps/mobile/e2e/github-stub.sh Resolved
Comment thread apps/mobile/e2e/github-stub.sh Resolved
pnpm dev:seed app:github-integration-copy <email> finds the newest real
integration in the shared dev database (fakes excluded: kilo-stub* logins
and far-future expiries — a real refresh token expires within months),
decrypts it with git-token-service's local dev key, re-encrypts for the
target account under a synthetic github_user_id (the pair index is unique),
and upserts. Scenarios that need a real integration (cloud agents) run
against the copy; with no valid donor the command fails with an explicit
BLOCKED message, and the runbook tells verifiers to report VERIFICATION
BLOCKED rather than fake or silently skip. Verified against the dev db:
copy mechanics end to end, and the blocked path on a database holding only
seeded rows.
iscekic added a commit that referenced this pull request Aug 2, 2026
The e2e harness changes belong to #4960.
iscekic added a commit that referenced this pull request Aug 2, 2026
The assertions pin apps/mobile/e2e content that #4960 owns.
Point the seed help text at the stub that exists on main.
iscekic added a commit that referenced this pull request Aug 2, 2026
The e2e harness changes belong to #4960.
iscekic added a commit that referenced this pull request Aug 2, 2026
The assertions pin apps/mobile/e2e content that #4960 owns.
Point the seed help text at the stub that exists on main.
iscekic added a commit that referenced this pull request Aug 2, 2026
The e2e harness changes belong to #4960.
iscekic added a commit that referenced this pull request Aug 2, 2026
The assertions pin apps/mobile/e2e content that #4960 owns.
iscekic added a commit that referenced this pull request Aug 2, 2026
PR #4960 carries these changes and merges first. This branch keeps no copy.

- dev/local/mobile-android.ts
- dev/local/mobile-simulator.ts
- dev/local/tmux.ts
- dev/seed/app/github-integration-copy.ts
iscekic added a commit that referenced this pull request Aug 2, 2026
PR #4960 carries these changes and merges first. This branch keeps no copy.

- dev/local/mobile-android.ts
- dev/local/mobile-simulator.ts
- dev/local/tmux.ts
- dev/seed/app/github-integration-copy.ts
iscekic added a commit that referenced this pull request Aug 2, 2026
PR #4960 carries these changes and merges first. This branch keeps no copy.

- dev/local/mobile-android.ts
- dev/local/mobile-simulator.ts
- dev/local/tmux.ts
- dev/seed/app/github-integration-copy.ts
iscekic added a commit that referenced this pull request Aug 2, 2026
PR #4960 carries these changes and merges first. This branch keeps no copy.

- dev/local/mobile-android.ts
- dev/local/mobile-simulator.ts
- dev/local/tmux.ts
- dev/seed/app/github-integration-copy.ts

Drop dev/local/github-integration-copy.test.ts. It imports the reverted seed
file.
iscekic added 2 commits August 3, 2026 00:10
…ents

Cloud-agent scenarios need a real GitHub App installation on the account,
which the PR-review stub cannot provide and the token copy does not write.
github-installation.sh adds the shared dev installation to any account
through the dev-only githubApps.devAddInstallation mutation.

The runbook now separates the two rows: the installation drives cloud
agents, the user token drives PR review against real GitHub.
The copy existed to give cloud-agent scenarios a real GitHub integration,
but cloud agents authenticate with the App installation, which
github-installation.sh now writes directly. The copy only wrote the user
OAuth token row, which PR review takes from the hermetic stub, and it
carried the donor developer's grant with it.

The runbook now states that no real user token is available, so a scenario
needing one is blocked instead of borrowing a developer's authorization.
Comment thread apps/mobile/e2e/github-installation.sh Resolved
devAddInstallation upserts on the installation id, so a second id gives the
account a second github row, and every reader takes one row with no ordering.
success:true then hides a repository list written to the row the app does not
read. The script now reads the integration back and requires the expected
installation with at least one repository.
Comment thread apps/mobile/e2e/github-installation.sh Resolved
Comment thread apps/mobile/e2e/AGENTS.md Resolved
githubApps.getInstallation orders by health and recency, so the row the
script just wrote wins that read even when a second row exists. The repo
count now comes from cloudAgentNext.listGitHubRepositories, the unordered
reader the mobile new-session screen calls, and the runbook states the
difference instead of calling every reader unordered.
Comment thread apps/mobile/e2e/github-installation.sh Resolved
The repository readback backfills whichever row the unordered reader picked,
so a second valid installation could serve the list and pass. The script now
lists the account's github rows and requires exactly the installation it
wrote, which is what makes every reader resolve the same one.

Verified against the local stack: a second row injected in postgres fails the
readback with both ids, and the single-row account reports 15 repositories.
@iscekic
iscekic merged commit 86de680 into main Aug 3, 2026
22 checks passed
@iscekic
iscekic deleted the mobile-e2e-ste branch August 3, 2026 01:24
iscekic added a commit that referenced this pull request Aug 3, 2026
* feat(mobile): add pinch zoom to table viewer

* fix(mobile): inline table zoom clamp in worklets

* chore(e2e): revert apps/mobile/e2e to base

The e2e harness changes belong to #4960.
iscekic added a commit that referenced this pull request Aug 3, 2026
main moved the mobile E2E harness to the kilo-workflow repo (#4968) and
merged the harness refactor (#4960). This branch still carried both. Accept
main's deletions:

- apps/mobile/e2e/** — every change is already in kilo-workflow's mobile_e2e.
- dev/local/mobile-simulator.ts — kilo-workflow's copy is ahead of this one.
- dev/local/mobile-workflow.test.ts — keep main's non-e2e tests only.
- dev/seed/app/github-integration-copy.ts — kilo-workflow's
  github-installation.sh replaced it with the githubApps.devAddInstallation
  mutation main already ships.

What remains is the composer wrap fix plus one process-lock test.
iscekic added a commit that referenced this pull request Aug 3, 2026
* fix(mobile): measure composer text width accurately

* refactor(mobile-e2e): simplified runbook, scripted stub setup, load-tolerant flows

- rewrite e2e/AGENTS.md in simplified technical English: task-structured,
  scripts own the mechanics, 410 -> ~215 lines
- new e2e/github-stub.sh: PR-review stub server + env line + token seed
  as one reversible command pair; failed starts clean up after themselves
- emulator-start --wait retries a failed launch once itself (boot-envelope
  timeout keeps the GPU, other failures switch to software rendering);
  the runbook's manual GPU decision table is gone
- appium.sh hierarchy writes to a file and prints the path; a raw XML dump
  into an agent session is large enough to kill it silently
- raise iOS cold-launch/settle budgets to 120s (timed out under parallel
  dual-bundle load); document ANR-under-load handling
- simulator claims record originalDeviceName and bootedByClaim intent in
  the initial write, so a lost post-boot rewrite can no longer leak a
  renamed or still-booted device on release

* fix(mobile-e2e): address review findings on retry and stub rollback

- emulator-start retry: rethrow the already-exists guard (a retry would
  tear down a live emulator) and keep attempt 1's error when the interim
  teardown itself fails
- github-stub: curl transport failures now route through seed_fail, so a
  failed start still rolls back the session and env line
- github-stub: guard against a .env.local without a trailing newline
  before appending, so the marker line can never merge into (and later
  delete) an existing variable

* fix(mobile-e2e): close concurrency races found in adversarial review

- tmux targets use exact-match (=name): bare -t prefix-matches, so a sibling
  worktree whose slug extends ours could be probed or killed in its place
- simulator claims write atomically (temp + rename/link): in-place truncation
  let an unlocked reader see a partial file, judge it corrupt, and delete a
  live claim
- a claim abandoned after its boot (rename failure) now powers the device
  off, or keeps the claim when even that fails
- simctl bootstatus is bounded (15 min) so a wedged CoreSimulator cannot
  block a claim forever
- emulator-start tears down after a failed second attempt too
- github-stub start claims its port machine-globally and verifies its own
  session survived, so two worktrees cannot share one stub silently; stop
  releases the claim
- appium: driver install re-checks inside the install lock; server startup
  verifies port ownership before adopting a listener; stop escalates to
  SIGKILL instead of orphaning a live server
- record.sh serializes start/stop per device with the shared process lock
- open-app consumes its launch budget in 30s slices so an ANR dialog is
  answered promptly instead of after the full wait
- login.sh matches the recipient literally, not as a regex
- hierarchy mktemp template puts Xs last (BSD mktemp leaves embedded Xs
  literal, making every bare call after the first fail)
- AGENTS.md: per-platform mixed fixtures, pull-and-grep for ADB dumps,
  stub-stop token residue note
- mobile-workflow tests updated for the raised launch/settle budgets

* fix(mobile-e2e): adversarial-review round 2

- appium: the recorded-server fast path now verifies the recorded pid owns
  the listener before adopting (a recycled pid plus a sibling's server on
  the same port answered /status and got adopted)
- github-stub: seeding extracted into seed_token; new 'seed <email>'
  subcommand adds a token row for a second signed-in account (the other
  platform's verifier) without touching the running stub
- github-stub: the port claim covers only the choose-to-bind window and an
  EXIT trap releases it, so an interrupted start cannot leak claims and
  erode the port range
- github-stub: githubUserId carries the pid — concurrent seeds in the same
  second cannot collide on the unique github_user_id
- AGENTS.md: the ADB dump example creates its own mktemp file instead of
  assuming $SCRATCH

* fix(mobile-e2e): seed verifies the endpoint's success flag

devSeedUserGithubToken can answer 200 with success:false (row not
upserted); the status code alone reported a seed that never landed.

* fix(mobile-e2e): server stop verifies death before dropping state

A process that survives even SIGKILL kept its state file removed and the
stop reported success; the caller then released device claims over a live
server. stop now fails and keeps the state in that case.

* fix(mobile-e2e): address stub-claim, re-seed, and lsof review findings

- claim_port reaps an orphaned port claim (older than 120s with nothing
  listening) and the start path traps INT/TERM/HUP besides EXIT, so a
  killed start can no longer shrink the port pool permanently
- githubUserId derives deterministically from the account email: the
  upsert's setWhere only updates a matching row, so the fresh random id
  made every re-seed of an already-seeded account report success:false
  and tear the stub down with a misleading hint
- lsof ownership probes tolerate no-match exits; pipefail otherwise killed
  appium.sh before the fresh-start fallback could run

* fix(mobile-e2e): tighten adoption, signal exits, and legacy-seed handling

- appium startup adopts a port only on proven ownership (listener pid equals
  ours); an empty lsof keeps polling instead of adopting a vanished or
  foreign server
- github-stub signal traps exit instead of continuing a start that just
  released its port claim
- success:false with 200 and no error means an account seeded under an older
  random id — keep that usable row instead of tearing the stub down

* fix(mobile-e2e): name both sources of an existing token row

success:false can come from an older random-id seed or from a real GitHub
connection on the dev account; the keep-message now says so instead of
implying only legacy seeds, and notes the stub accepts any token.

* fix(mobile-e2e): stub row verification, self-cleaning start, lsof fallback

- a kept token row is verified to be the stub's (getUserAuthorization
  githubLogin == kilo-stub-user); a real GitHub connection row fails with a
  drop-the-row hint — under the stub its refresh bypasses
  GITHUB_API_BASE_URL, hits real github.com, and revokes itself
- start rolls back everything (session, env line, state, port claim) via one
  EXIT trap when it dies before the final state write, so an aborted start
  no longer blocks the next one behind 'session already runs'
- appium ownership checks degrade to pid+status when lsof is missing or
  cannot attribute the socket, instead of killing healthy servers across 50
  port blocks

* fix(mobile-e2e): honest row probe, race-safe rollback, blind-lsof reuse

- the row probe checks HTTP status and error envelope before advising: a
  failed probe reports 'could not determine the existing row' instead of
  confidently telling the operator to delete a row it never examined; a
  kept row must also be connected (a revoked stub row gets the drop hint)
- start's rollback undoes only what this run did (session-created and
  env-added flags), so a start losing the session-creation race cannot kill
  the winner's session, env line, or state
- the recorded-server reuse path applies the same blind-lsof rule as the
  start loop: adopt on pid+status after three blind probes instead of
  orphaning a healthy server and consuming a port block per invocation
- drop dead SEED_FAIL_MODE and the stale random-id comment

* fix(mobile-e2e): close the last rollback and adoption windows

- github-stub creates its session under a pid-unique name armed before the
  create and renames to claim the canonical one: a signal at any instant
  tears down only our own session, and a lost rename race touches nothing
  but our port claim; the env-added flag arms before the append for the
  same reason
- the appium reuse probe rechecks pid liveness and /status on every pass,
  so a server dying mid-probe is cleaned up (stop_server) instead of
  adopted; a foreign listener still only drops our state

* fix(mobile-e2e): serialize the stub per worktree instead of guarding windows

Concurrent stub commands raced over the session name, env line, and state
dir; each guard narrowed the window without closing it. The shared
process-lock (the appium.sh pattern) removes the class: one stub command per
worktree at a time, so the entry check is authoritative, the rollback flags
only order against signals, and the unique-name rename dance goes away.

* fix(mobile-e2e): row-probe failures skip the missing-user hint

Both row branches run after the account answered the seed call, so the
sign-in hint contradicted what the script had just proved.

* fix(mobile-e2e): bound the lock's hold time and the survivor edge

- every network call under the stub lock carries --max-time 30, so a hung
  local API cannot hold the lock to its 300s wait bound; status runs
  unlocked (read-only) and answers during a long start
- a failed session create (a survivor of a SIGKILLed lock wrapper got there
  first) resets the created flag before exiting, so cleanup cannot touch
  the survivor's session
- align the env-append comment with the lock (the rename step it cited is
  gone)

* feat(mobile-e2e): copy a real GitHub integration onto an e2e account

pnpm dev:seed app:github-integration-copy <email> finds the newest real
integration in the shared dev database (fakes excluded: kilo-stub* logins
and far-future expiries — a real refresh token expires within months),
decrypts it with git-token-service's local dev key, re-encrypts for the
target account under a synthetic github_user_id (the pair index is unique),
and upserts. Scenarios that need a real integration (cloud agents) run
against the copy; with no valid donor the command fails with an explicit
BLOCKED message, and the runbook tells verifiers to report VERIFICATION
BLOCKED rather than fake or silently skip. Verified against the dev db:
copy mechanics end to end, and the blocked path on a database holding only
seeded rows.

* fix(mobile-e2e): copies never donate or collide with the stub

- donor filter excludes 13-digit synthetic github_user_ids (stub seeds and
  earlier copies): revocation lands only on the real row, so a surviving
  copy could hand out dead credentials as a fresh success
- app:github-integration-copy --remove <email> deletes the account's token
  row, so an account can return to stub use; runbook and usage text now
  require separate accounts for stub and integration scenarios
- verified live: remove clears the copied row and is idempotent

* docs(mobile-e2e): STE pass over the runbook additions

One instruction per sentence in the integration and stub sections; no rule
changed meaning.

* fix(mobile-e2e): copies validate the donor live and can never refresh

- the donor's access token is checked against api.github.com before the
  copy: database metadata cannot prove a rotated or GitHub-revoked token
  dead, so silent dead-credential copies reported success
- the copy row carries a dummy, already-expired refresh token: GitHub
  refresh tokens rotate on use, so a refreshing copy would kill the donor's
  stored refresh token and poison every later copy
- usage and runbook text updated to the access-token-only contract

* fix(mobile-e2e): guard the integration copy's blast radius

The copy relocates real credentials, so every destructive path is now
guarded and every shared-grant hazard is stated:

- assertLocalDatabaseTarget: USE_PRODUCTION_DB=true and non-loopback hosts
  are refused, making the dev-only claim enforceable (verified live)
- --remove deletes only a synthetic row (copy or stub seed) and names what
  it removed; a real connection is refused with instructions
- a copy refuses to overwrite a real connection on the target account
- donor lookup also matches google_user_email (normalized_email is nullable)
- usage and runbook state the real blast radius: the copy shares the donor's
  OAuth grant, so disconnect on a copied account revokes the DONOR's
  authorization and no re-copy repairs it — disconnect scenarios are blocked
  on copied accounts; commit attribution carries a synthetic id
- stub status reports 'starting' when a session has no state yet, instead of
  claiming up for a stub that is not usable
- lock-bounded curls raised to 120s (30s was the budget this PR already
  found too small under full parallel load)
- a failed tmux create distinguishes a concurrent session from a tmux error

* fix(mobile-e2e): env failures in the copy tool name their own fix

A dead database dumped a driver AggregateError stack trace, and a dead
network read as 'no valid donor'. Both now fail with one line naming the
command that fixes them, so an agent does not spend a round guessing at
ECONNREFUSED output or chasing a false BLOCKED. Verified live with postgres
stopped.

* fix(mobile-e2e): make the copy's guards atomic and expiry-safe

- the synthetic-only rule is re-asserted in the upsert's setWhere, so a real
  OAuth callback landing between the pre-check and the write cannot be
  overwritten; zero updated rows reports that explicitly (postgres predicate
  verified against synthetic and real id shapes)
- donors need >10 minutes of access-token life (twice git-token-service's
  5-minute refresh buffer): a token inside the buffer passes the live probe,
  then triggers a refresh the copy cannot perform
- the target lookup tries the exact sign-in email before the normalized
  fallback, since normalized_email is not unique

* fix(mobile-e2e): state the copy's real lifetime and align the lock budget

- the 'can never refresh' claim was wrong: git-token-service gates refresh on
  the ACCESS token's expiry, so the dummy refresh token IS sent and the copy
  ends up revoked. Docs, usage text and the runbook now describe that end
  state, the tool reports usableUntil, and donors need 35 minutes of access
  life so a copy is usable for at least 30
- --remove reports what actually went away (.returning()), so a row replaced
  mid-command cannot read as removed
- stub lock --wait raised to 900s, above the ~8 minute worst-case hold the
  120s per-call budgets allow, so a queued stop or seed waits instead of
  failing
- drop the now-unused 'or' import

* fix(mobile-e2e): re-assert the usable window after the live probes

The 35-minute SQL margin is measured before up to ten 15-second GitHub
probes, so a copy could return with less than the promised 30 usable
minutes. The selected donor is now re-checked against the clock after its
probe, and one helper owns the usable-until arithmetic the filter, the
check, and the report all share.

* docs(mobile-e2e): bound big outputs, never doctor --json

A campaign verifier died with no sentinel right after a doctor --json dump
(the whole environment, PATH included). The runbook now states the general
rule — bound anything that can print a lot — and names --json diagnostics
alongside the Appium and hierarchy cases it already covered.

* chore: retrigger review

* chore: retrigger review

* fix(mobile-e2e): preserve emulator on launch lock

* fix(mobile-e2e): harden GitHub test setup

* fix(mobile-e2e): continue after Appium cleanup failure

* fix(mobile-e2e): preserve stub env permissions portably

* test(mobile-e2e): clean up Appium test server

* fix(mobile-e2e): harden test cleanup portability

* docs(mobile-e2e): doctor is always a full JSON dump; never tail JSON

Two review corrections, both verified against dev/local/mobile-android.ts:
doctor ignores flags and always prints the whole environment (PATH
included), so the runbook's 'plain doctor is safe' advice pointed at the
unsafe form; and tail on JSON leaves an unparseable fragment while the
runbook requires parsing dev:status --json. The bounded form is a jq field
selector, shown inline for both cases.

* chore(e2e): revert apps/mobile/e2e to base

The e2e harness changes belong to #4960.

* fix(dev): drop test assertions for the reverted e2e harness

The assertions pin apps/mobile/e2e content that #4960 owns.
Point the seed help text at the stub that exists on main.

* chore(dev): revert shared e2e harness files

PR #4960 carries these changes and merges first. This branch keeps no copy.

- dev/local/mobile-android.ts
- dev/local/mobile-simulator.ts
- dev/local/tmux.ts
- dev/seed/app/github-integration-copy.ts

* test(dev): move lock contention test to process-lock

The reverted e2e harness removed the emulator-start retry guard, so the test
name in mobile-android.test.ts was wrong. The test covers process-lock, not
Android. Move it to process-lock.test.ts and rename it.

* chore(e2e): restore the mobile-e2e-ste harness after the merge

* fix(mobile): stub the table viewer's new native modules in its test

#4959 gave markdown-table.tsx gesture-handler, reanimated and worklets
imports, and rewrote it onto useRef, useCallback and useEffect. The test
still stubbed only react's useState plus react-native, so the three new
entry points reached the node vitest project as Flow source and the suite
died on `SyntaxError: Unexpected token 'typeof'`. main is red for this.

Stub the three modules and the extra react hooks. One self-returning Proxy
answers RNGH's whole builder chain, so a new Gesture call in the component
needs no new stub.
iscekic added a commit that referenced this pull request Aug 3, 2026
* fix(mobile): refresh GitHub repositories after connect

* feat(mobile): add step-based new sessions

* test(mobile): cover new session step contracts

* fix(mobile): recover new session flow from paused queries

* fix(mobile): preserve new session navigation

* fix(mobile): resolve Homebrew android-commandlinetools adb in record.sh

Cherry-pick of cloud#4949 adb path only so Android E2E recorder works
before that PR merges.

* chore: retrigger review

* refactor(mobile-e2e): simplified runbook, scripted stub setup, load-tolerant flows

- rewrite e2e/AGENTS.md in simplified technical English: task-structured,
  scripts own the mechanics, 410 -> ~215 lines
- new e2e/github-stub.sh: PR-review stub server + env line + token seed
  as one reversible command pair; failed starts clean up after themselves
- emulator-start --wait retries a failed launch once itself (boot-envelope
  timeout keeps the GPU, other failures switch to software rendering);
  the runbook's manual GPU decision table is gone
- appium.sh hierarchy writes to a file and prints the path; a raw XML dump
  into an agent session is large enough to kill it silently
- raise iOS cold-launch/settle budgets to 120s (timed out under parallel
  dual-bundle load); document ANR-under-load handling
- simulator claims record originalDeviceName and bootedByClaim intent in
  the initial write, so a lost post-boot rewrite can no longer leak a
  renamed or still-booted device on release

* fix(mobile-e2e): address review findings on retry and stub rollback

- emulator-start retry: rethrow the already-exists guard (a retry would
  tear down a live emulator) and keep attempt 1's error when the interim
  teardown itself fails
- github-stub: curl transport failures now route through seed_fail, so a
  failed start still rolls back the session and env line
- github-stub: guard against a .env.local without a trailing newline
  before appending, so the marker line can never merge into (and later
  delete) an existing variable

* fix(mobile-e2e): close concurrency races found in adversarial review

- tmux targets use exact-match (=name): bare -t prefix-matches, so a sibling
  worktree whose slug extends ours could be probed or killed in its place
- simulator claims write atomically (temp + rename/link): in-place truncation
  let an unlocked reader see a partial file, judge it corrupt, and delete a
  live claim
- a claim abandoned after its boot (rename failure) now powers the device
  off, or keeps the claim when even that fails
- simctl bootstatus is bounded (15 min) so a wedged CoreSimulator cannot
  block a claim forever
- emulator-start tears down after a failed second attempt too
- github-stub start claims its port machine-globally and verifies its own
  session survived, so two worktrees cannot share one stub silently; stop
  releases the claim
- appium: driver install re-checks inside the install lock; server startup
  verifies port ownership before adopting a listener; stop escalates to
  SIGKILL instead of orphaning a live server
- record.sh serializes start/stop per device with the shared process lock
- open-app consumes its launch budget in 30s slices so an ANR dialog is
  answered promptly instead of after the full wait
- login.sh matches the recipient literally, not as a regex
- hierarchy mktemp template puts Xs last (BSD mktemp leaves embedded Xs
  literal, making every bare call after the first fail)
- AGENTS.md: per-platform mixed fixtures, pull-and-grep for ADB dumps,
  stub-stop token residue note
- mobile-workflow tests updated for the raised launch/settle budgets

* fix(mobile-e2e): adversarial-review round 2

- appium: the recorded-server fast path now verifies the recorded pid owns
  the listener before adopting (a recycled pid plus a sibling's server on
  the same port answered /status and got adopted)
- github-stub: seeding extracted into seed_token; new 'seed <email>'
  subcommand adds a token row for a second signed-in account (the other
  platform's verifier) without touching the running stub
- github-stub: the port claim covers only the choose-to-bind window and an
  EXIT trap releases it, so an interrupted start cannot leak claims and
  erode the port range
- github-stub: githubUserId carries the pid — concurrent seeds in the same
  second cannot collide on the unique github_user_id
- AGENTS.md: the ADB dump example creates its own mktemp file instead of
  assuming $SCRATCH

* fix(mobile-e2e): seed verifies the endpoint's success flag

devSeedUserGithubToken can answer 200 with success:false (row not
upserted); the status code alone reported a seed that never landed.

* fix(mobile-e2e): server stop verifies death before dropping state

A process that survives even SIGKILL kept its state file removed and the
stop reported success; the caller then released device claims over a live
server. stop now fails and keeps the state in that case.

* fix(mobile-e2e): address stub-claim, re-seed, and lsof review findings

- claim_port reaps an orphaned port claim (older than 120s with nothing
  listening) and the start path traps INT/TERM/HUP besides EXIT, so a
  killed start can no longer shrink the port pool permanently
- githubUserId derives deterministically from the account email: the
  upsert's setWhere only updates a matching row, so the fresh random id
  made every re-seed of an already-seeded account report success:false
  and tear the stub down with a misleading hint
- lsof ownership probes tolerate no-match exits; pipefail otherwise killed
  appium.sh before the fresh-start fallback could run

* fix(mobile-e2e): tighten adoption, signal exits, and legacy-seed handling

- appium startup adopts a port only on proven ownership (listener pid equals
  ours); an empty lsof keeps polling instead of adopting a vanished or
  foreign server
- github-stub signal traps exit instead of continuing a start that just
  released its port claim
- success:false with 200 and no error means an account seeded under an older
  random id — keep that usable row instead of tearing the stub down

* fix(mobile-e2e): name both sources of an existing token row

success:false can come from an older random-id seed or from a real GitHub
connection on the dev account; the keep-message now says so instead of
implying only legacy seeds, and notes the stub accepts any token.

* fix(mobile-e2e): stub row verification, self-cleaning start, lsof fallback

- a kept token row is verified to be the stub's (getUserAuthorization
  githubLogin == kilo-stub-user); a real GitHub connection row fails with a
  drop-the-row hint — under the stub its refresh bypasses
  GITHUB_API_BASE_URL, hits real github.com, and revokes itself
- start rolls back everything (session, env line, state, port claim) via one
  EXIT trap when it dies before the final state write, so an aborted start
  no longer blocks the next one behind 'session already runs'
- appium ownership checks degrade to pid+status when lsof is missing or
  cannot attribute the socket, instead of killing healthy servers across 50
  port blocks

* fix(mobile-e2e): honest row probe, race-safe rollback, blind-lsof reuse

- the row probe checks HTTP status and error envelope before advising: a
  failed probe reports 'could not determine the existing row' instead of
  confidently telling the operator to delete a row it never examined; a
  kept row must also be connected (a revoked stub row gets the drop hint)
- start's rollback undoes only what this run did (session-created and
  env-added flags), so a start losing the session-creation race cannot kill
  the winner's session, env line, or state
- the recorded-server reuse path applies the same blind-lsof rule as the
  start loop: adopt on pid+status after three blind probes instead of
  orphaning a healthy server and consuming a port block per invocation
- drop dead SEED_FAIL_MODE and the stale random-id comment

* fix(mobile-e2e): close the last rollback and adoption windows

- github-stub creates its session under a pid-unique name armed before the
  create and renames to claim the canonical one: a signal at any instant
  tears down only our own session, and a lost rename race touches nothing
  but our port claim; the env-added flag arms before the append for the
  same reason
- the appium reuse probe rechecks pid liveness and /status on every pass,
  so a server dying mid-probe is cleaned up (stop_server) instead of
  adopted; a foreign listener still only drops our state

* fix(mobile-e2e): serialize the stub per worktree instead of guarding windows

Concurrent stub commands raced over the session name, env line, and state
dir; each guard narrowed the window without closing it. The shared
process-lock (the appium.sh pattern) removes the class: one stub command per
worktree at a time, so the entry check is authoritative, the rollback flags
only order against signals, and the unique-name rename dance goes away.

* fix(mobile-e2e): row-probe failures skip the missing-user hint

Both row branches run after the account answered the seed call, so the
sign-in hint contradicted what the script had just proved.

* fix(mobile-e2e): bound the lock's hold time and the survivor edge

- every network call under the stub lock carries --max-time 30, so a hung
  local API cannot hold the lock to its 300s wait bound; status runs
  unlocked (read-only) and answers during a long start
- a failed session create (a survivor of a SIGKILLed lock wrapper got there
  first) resets the created flag before exiting, so cleanup cannot touch
  the survivor's session
- align the env-append comment with the lock (the rename step it cited is
  gone)

* feat(mobile-e2e): copy a real GitHub integration onto an e2e account

pnpm dev:seed app:github-integration-copy <email> finds the newest real
integration in the shared dev database (fakes excluded: kilo-stub* logins
and far-future expiries — a real refresh token expires within months),
decrypts it with git-token-service's local dev key, re-encrypts for the
target account under a synthetic github_user_id (the pair index is unique),
and upserts. Scenarios that need a real integration (cloud agents) run
against the copy; with no valid donor the command fails with an explicit
BLOCKED message, and the runbook tells verifiers to report VERIFICATION
BLOCKED rather than fake or silently skip. Verified against the dev db:
copy mechanics end to end, and the blocked path on a database holding only
seeded rows.

* fix(mobile-e2e): copies never donate or collide with the stub

- donor filter excludes 13-digit synthetic github_user_ids (stub seeds and
  earlier copies): revocation lands only on the real row, so a surviving
  copy could hand out dead credentials as a fresh success
- app:github-integration-copy --remove <email> deletes the account's token
  row, so an account can return to stub use; runbook and usage text now
  require separate accounts for stub and integration scenarios
- verified live: remove clears the copied row and is idempotent

* docs(mobile-e2e): STE pass over the runbook additions

One instruction per sentence in the integration and stub sections; no rule
changed meaning.

* fix(mobile-e2e): copies validate the donor live and can never refresh

- the donor's access token is checked against api.github.com before the
  copy: database metadata cannot prove a rotated or GitHub-revoked token
  dead, so silent dead-credential copies reported success
- the copy row carries a dummy, already-expired refresh token: GitHub
  refresh tokens rotate on use, so a refreshing copy would kill the donor's
  stored refresh token and poison every later copy
- usage and runbook text updated to the access-token-only contract

* fix(mobile-e2e): guard the integration copy's blast radius

The copy relocates real credentials, so every destructive path is now
guarded and every shared-grant hazard is stated:

- assertLocalDatabaseTarget: USE_PRODUCTION_DB=true and non-loopback hosts
  are refused, making the dev-only claim enforceable (verified live)
- --remove deletes only a synthetic row (copy or stub seed) and names what
  it removed; a real connection is refused with instructions
- a copy refuses to overwrite a real connection on the target account
- donor lookup also matches google_user_email (normalized_email is nullable)
- usage and runbook state the real blast radius: the copy shares the donor's
  OAuth grant, so disconnect on a copied account revokes the DONOR's
  authorization and no re-copy repairs it — disconnect scenarios are blocked
  on copied accounts; commit attribution carries a synthetic id
- stub status reports 'starting' when a session has no state yet, instead of
  claiming up for a stub that is not usable
- lock-bounded curls raised to 120s (30s was the budget this PR already
  found too small under full parallel load)
- a failed tmux create distinguishes a concurrent session from a tmux error

* fix(mobile-e2e): env failures in the copy tool name their own fix

A dead database dumped a driver AggregateError stack trace, and a dead
network read as 'no valid donor'. Both now fail with one line naming the
command that fixes them, so an agent does not spend a round guessing at
ECONNREFUSED output or chasing a false BLOCKED. Verified live with postgres
stopped.

* fix(mobile-e2e): make the copy's guards atomic and expiry-safe

- the synthetic-only rule is re-asserted in the upsert's setWhere, so a real
  OAuth callback landing between the pre-check and the write cannot be
  overwritten; zero updated rows reports that explicitly (postgres predicate
  verified against synthetic and real id shapes)
- donors need >10 minutes of access-token life (twice git-token-service's
  5-minute refresh buffer): a token inside the buffer passes the live probe,
  then triggers a refresh the copy cannot perform
- the target lookup tries the exact sign-in email before the normalized
  fallback, since normalized_email is not unique

* fix(mobile-e2e): state the copy's real lifetime and align the lock budget

- the 'can never refresh' claim was wrong: git-token-service gates refresh on
  the ACCESS token's expiry, so the dummy refresh token IS sent and the copy
  ends up revoked. Docs, usage text and the runbook now describe that end
  state, the tool reports usableUntil, and donors need 35 minutes of access
  life so a copy is usable for at least 30
- --remove reports what actually went away (.returning()), so a row replaced
  mid-command cannot read as removed
- stub lock --wait raised to 900s, above the ~8 minute worst-case hold the
  120s per-call budgets allow, so a queued stop or seed waits instead of
  failing
- drop the now-unused 'or' import

* fix(mobile-e2e): re-assert the usable window after the live probes

The 35-minute SQL margin is measured before up to ten 15-second GitHub
probes, so a copy could return with less than the promised 30 usable
minutes. The selected donor is now re-checked against the clock after its
probe, and one helper owns the usable-until arithmetic the filter, the
check, and the report all share.

* docs(mobile-e2e): bound big outputs, never doctor --json

A campaign verifier died with no sentinel right after a doctor --json dump
(the whole environment, PATH included). The runbook now states the general
rule — bound anything that can print a lot — and names --json diagnostics
alongside the Appium and hierarchy cases it already covered.

* refactor(mobile): unify new-session configure form

* refactor(mobile): remove superseded cloud form

* fix(mobile): harden new-session E2E support

* chore: format mobile workflow test

* fix(e2e): preserve cleanup ownership state

* fix(e2e): retain cleanup state on conflicts

* fix(e2e): keep appium port bump recovery

* chore: retrigger review

* fix(e2e): keep stale appium recovery nonfatal

* fix(e2e): preserve stale appium state

* fix(e2e): recover from foreign appium listeners

* fix(e2e): retain appium conflict diagnostics

* docs(mobile-e2e): doctor is always a full JSON dump; never tail JSON

Two review corrections, both verified against dev/local/mobile-android.ts:
doctor ignores flags and always prints the whole environment (PATH
included), so the runbook's 'plain doctor is safe' advice pointed at the
unsafe form; and tail on JSON leaves an unparseable fragment while the
runbook requires parsing dev:status --json. The bounded form is a jq field
selector, shown inline for both cases.

* chore(e2e): revert apps/mobile/e2e to base

The e2e harness changes belong to #4960.

* fix(dev): drop test assertions for the reverted e2e harness

The assertions pin apps/mobile/e2e content that #4960 owns.
Point the seed help text at the stub that exists on main.

* chore(dev): revert shared e2e harness files

PR #4960 carries these changes and merges first. This branch keeps no copy.

- dev/local/mobile-android.ts
- dev/local/mobile-simulator.ts
- dev/local/tmux.ts
- dev/seed/app/github-integration-copy.ts

Drop dev/local/github-integration-copy.test.ts. It imports the reverted seed
file.

* chore(mobile-e2e): restore the #4960 harness under the new base

* refactor(mobile): one new-session screen for every entry point

* fix(mobile): name new-session attachment handlers

* chore: retrigger review

* chore: retrigger review

* feat(mobile): add share delivery helpers

* feat(mobile): carry drafts through remote spawn

* feat(mobile): auto-send delivered remote shares

* style(mobile): format spawn dispatch test

* fix(mobile): guard remote share auto-send

* fix(mobile): require CLI file capability

* Drop the github-integration-copy seed tool

`mobile_e2e/github-installation.sh` in the kilo-workflow repo covers this case
through `githubApps.devAddInstallation`, which already exists here. The seed
tool was the second mechanism for the same job, and its only runbook lived in
the `apps/mobile/e2e/AGENTS.md` that moved out with the harness.

`dev/seed/index.ts` discovers commands by filename, so the file alone exposed
`pnpm dev:seed app:github-integration-copy`. Nothing else referenced it.
iscekic added a commit that referenced this pull request Aug 3, 2026
* fix(mobile): simplify PR review file scrolling

* test(mobile): add PR review file fixtures

* fix(mobile): align PR fixture metadata

* chore(e2e): revert apps/mobile/e2e to base

The e2e harness changes belong to #4960.
iscekic added a commit that referenced this pull request Aug 3, 2026
* test(mobile): add PR review image fixtures

* feat(mobile): render markdown images

* fix(mobile): satisfy strict parser tests

* fix(mobile): resolve test lint violations

* refactor(mobile-e2e): simplified runbook, scripted stub setup, load-tolerant flows

- rewrite e2e/AGENTS.md in simplified technical English: task-structured,
  scripts own the mechanics, 410 -> ~215 lines
- new e2e/github-stub.sh: PR-review stub server + env line + token seed
  as one reversible command pair; failed starts clean up after themselves
- emulator-start --wait retries a failed launch once itself (boot-envelope
  timeout keeps the GPU, other failures switch to software rendering);
  the runbook's manual GPU decision table is gone
- appium.sh hierarchy writes to a file and prints the path; a raw XML dump
  into an agent session is large enough to kill it silently
- raise iOS cold-launch/settle budgets to 120s (timed out under parallel
  dual-bundle load); document ANR-under-load handling
- simulator claims record originalDeviceName and bootedByClaim intent in
  the initial write, so a lost post-boot rewrite can no longer leak a
  renamed or still-booted device on release

* fix(mobile-e2e): address review findings on retry and stub rollback

- emulator-start retry: rethrow the already-exists guard (a retry would
  tear down a live emulator) and keep attempt 1's error when the interim
  teardown itself fails
- github-stub: curl transport failures now route through seed_fail, so a
  failed start still rolls back the session and env line
- github-stub: guard against a .env.local without a trailing newline
  before appending, so the marker line can never merge into (and later
  delete) an existing variable

* fix(mobile-e2e): close concurrency races found in adversarial review

- tmux targets use exact-match (=name): bare -t prefix-matches, so a sibling
  worktree whose slug extends ours could be probed or killed in its place
- simulator claims write atomically (temp + rename/link): in-place truncation
  let an unlocked reader see a partial file, judge it corrupt, and delete a
  live claim
- a claim abandoned after its boot (rename failure) now powers the device
  off, or keeps the claim when even that fails
- simctl bootstatus is bounded (15 min) so a wedged CoreSimulator cannot
  block a claim forever
- emulator-start tears down after a failed second attempt too
- github-stub start claims its port machine-globally and verifies its own
  session survived, so two worktrees cannot share one stub silently; stop
  releases the claim
- appium: driver install re-checks inside the install lock; server startup
  verifies port ownership before adopting a listener; stop escalates to
  SIGKILL instead of orphaning a live server
- record.sh serializes start/stop per device with the shared process lock
- open-app consumes its launch budget in 30s slices so an ANR dialog is
  answered promptly instead of after the full wait
- login.sh matches the recipient literally, not as a regex
- hierarchy mktemp template puts Xs last (BSD mktemp leaves embedded Xs
  literal, making every bare call after the first fail)
- AGENTS.md: per-platform mixed fixtures, pull-and-grep for ADB dumps,
  stub-stop token residue note
- mobile-workflow tests updated for the raised launch/settle budgets

* fix(mobile-e2e): adversarial-review round 2

- appium: the recorded-server fast path now verifies the recorded pid owns
  the listener before adopting (a recycled pid plus a sibling's server on
  the same port answered /status and got adopted)
- github-stub: seeding extracted into seed_token; new 'seed <email>'
  subcommand adds a token row for a second signed-in account (the other
  platform's verifier) without touching the running stub
- github-stub: the port claim covers only the choose-to-bind window and an
  EXIT trap releases it, so an interrupted start cannot leak claims and
  erode the port range
- github-stub: githubUserId carries the pid — concurrent seeds in the same
  second cannot collide on the unique github_user_id
- AGENTS.md: the ADB dump example creates its own mktemp file instead of
  assuming $SCRATCH

* fix(mobile-e2e): seed verifies the endpoint's success flag

devSeedUserGithubToken can answer 200 with success:false (row not
upserted); the status code alone reported a seed that never landed.

* fix(mobile-e2e): server stop verifies death before dropping state

A process that survives even SIGKILL kept its state file removed and the
stop reported success; the caller then released device claims over a live
server. stop now fails and keeps the state in that case.

* fix(mobile-e2e): address stub-claim, re-seed, and lsof review findings

- claim_port reaps an orphaned port claim (older than 120s with nothing
  listening) and the start path traps INT/TERM/HUP besides EXIT, so a
  killed start can no longer shrink the port pool permanently
- githubUserId derives deterministically from the account email: the
  upsert's setWhere only updates a matching row, so the fresh random id
  made every re-seed of an already-seeded account report success:false
  and tear the stub down with a misleading hint
- lsof ownership probes tolerate no-match exits; pipefail otherwise killed
  appium.sh before the fresh-start fallback could run

* fix(mobile-e2e): tighten adoption, signal exits, and legacy-seed handling

- appium startup adopts a port only on proven ownership (listener pid equals
  ours); an empty lsof keeps polling instead of adopting a vanished or
  foreign server
- github-stub signal traps exit instead of continuing a start that just
  released its port claim
- success:false with 200 and no error means an account seeded under an older
  random id — keep that usable row instead of tearing the stub down

* fix(mobile-e2e): name both sources of an existing token row

success:false can come from an older random-id seed or from a real GitHub
connection on the dev account; the keep-message now says so instead of
implying only legacy seeds, and notes the stub accepts any token.

* fix(mobile-e2e): stub row verification, self-cleaning start, lsof fallback

- a kept token row is verified to be the stub's (getUserAuthorization
  githubLogin == kilo-stub-user); a real GitHub connection row fails with a
  drop-the-row hint — under the stub its refresh bypasses
  GITHUB_API_BASE_URL, hits real github.com, and revokes itself
- start rolls back everything (session, env line, state, port claim) via one
  EXIT trap when it dies before the final state write, so an aborted start
  no longer blocks the next one behind 'session already runs'
- appium ownership checks degrade to pid+status when lsof is missing or
  cannot attribute the socket, instead of killing healthy servers across 50
  port blocks

* fix(mobile-e2e): honest row probe, race-safe rollback, blind-lsof reuse

- the row probe checks HTTP status and error envelope before advising: a
  failed probe reports 'could not determine the existing row' instead of
  confidently telling the operator to delete a row it never examined; a
  kept row must also be connected (a revoked stub row gets the drop hint)
- start's rollback undoes only what this run did (session-created and
  env-added flags), so a start losing the session-creation race cannot kill
  the winner's session, env line, or state
- the recorded-server reuse path applies the same blind-lsof rule as the
  start loop: adopt on pid+status after three blind probes instead of
  orphaning a healthy server and consuming a port block per invocation
- drop dead SEED_FAIL_MODE and the stale random-id comment

* fix(mobile-e2e): close the last rollback and adoption windows

- github-stub creates its session under a pid-unique name armed before the
  create and renames to claim the canonical one: a signal at any instant
  tears down only our own session, and a lost rename race touches nothing
  but our port claim; the env-added flag arms before the append for the
  same reason
- the appium reuse probe rechecks pid liveness and /status on every pass,
  so a server dying mid-probe is cleaned up (stop_server) instead of
  adopted; a foreign listener still only drops our state

* fix(mobile-e2e): serialize the stub per worktree instead of guarding windows

Concurrent stub commands raced over the session name, env line, and state
dir; each guard narrowed the window without closing it. The shared
process-lock (the appium.sh pattern) removes the class: one stub command per
worktree at a time, so the entry check is authoritative, the rollback flags
only order against signals, and the unique-name rename dance goes away.

* fix(mobile-e2e): row-probe failures skip the missing-user hint

Both row branches run after the account answered the seed call, so the
sign-in hint contradicted what the script had just proved.

* fix(mobile-e2e): bound the lock's hold time and the survivor edge

- every network call under the stub lock carries --max-time 30, so a hung
  local API cannot hold the lock to its 300s wait bound; status runs
  unlocked (read-only) and answers during a long start
- a failed session create (a survivor of a SIGKILLed lock wrapper got there
  first) resets the created flag before exiting, so cleanup cannot touch
  the survivor's session
- align the env-append comment with the lock (the rename step it cited is
  gone)

* feat(mobile-e2e): copy a real GitHub integration onto an e2e account

pnpm dev:seed app:github-integration-copy <email> finds the newest real
integration in the shared dev database (fakes excluded: kilo-stub* logins
and far-future expiries — a real refresh token expires within months),
decrypts it with git-token-service's local dev key, re-encrypts for the
target account under a synthetic github_user_id (the pair index is unique),
and upserts. Scenarios that need a real integration (cloud agents) run
against the copy; with no valid donor the command fails with an explicit
BLOCKED message, and the runbook tells verifiers to report VERIFICATION
BLOCKED rather than fake or silently skip. Verified against the dev db:
copy mechanics end to end, and the blocked path on a database holding only
seeded rows.

* fix(mobile-e2e): copies never donate or collide with the stub

- donor filter excludes 13-digit synthetic github_user_ids (stub seeds and
  earlier copies): revocation lands only on the real row, so a surviving
  copy could hand out dead credentials as a fresh success
- app:github-integration-copy --remove <email> deletes the account's token
  row, so an account can return to stub use; runbook and usage text now
  require separate accounts for stub and integration scenarios
- verified live: remove clears the copied row and is idempotent

* docs(mobile-e2e): STE pass over the runbook additions

One instruction per sentence in the integration and stub sections; no rule
changed meaning.

* fix(mobile-e2e): copies validate the donor live and can never refresh

- the donor's access token is checked against api.github.com before the
  copy: database metadata cannot prove a rotated or GitHub-revoked token
  dead, so silent dead-credential copies reported success
- the copy row carries a dummy, already-expired refresh token: GitHub
  refresh tokens rotate on use, so a refreshing copy would kill the donor's
  stored refresh token and poison every later copy
- usage and runbook text updated to the access-token-only contract

* fix(mobile-e2e): guard the integration copy's blast radius

The copy relocates real credentials, so every destructive path is now
guarded and every shared-grant hazard is stated:

- assertLocalDatabaseTarget: USE_PRODUCTION_DB=true and non-loopback hosts
  are refused, making the dev-only claim enforceable (verified live)
- --remove deletes only a synthetic row (copy or stub seed) and names what
  it removed; a real connection is refused with instructions
- a copy refuses to overwrite a real connection on the target account
- donor lookup also matches google_user_email (normalized_email is nullable)
- usage and runbook state the real blast radius: the copy shares the donor's
  OAuth grant, so disconnect on a copied account revokes the DONOR's
  authorization and no re-copy repairs it — disconnect scenarios are blocked
  on copied accounts; commit attribution carries a synthetic id
- stub status reports 'starting' when a session has no state yet, instead of
  claiming up for a stub that is not usable
- lock-bounded curls raised to 120s (30s was the budget this PR already
  found too small under full parallel load)
- a failed tmux create distinguishes a concurrent session from a tmux error

* fix(mobile-e2e): env failures in the copy tool name their own fix

A dead database dumped a driver AggregateError stack trace, and a dead
network read as 'no valid donor'. Both now fail with one line naming the
command that fixes them, so an agent does not spend a round guessing at
ECONNREFUSED output or chasing a false BLOCKED. Verified live with postgres
stopped.

* fix(mobile-e2e): make the copy's guards atomic and expiry-safe

- the synthetic-only rule is re-asserted in the upsert's setWhere, so a real
  OAuth callback landing between the pre-check and the write cannot be
  overwritten; zero updated rows reports that explicitly (postgres predicate
  verified against synthetic and real id shapes)
- donors need >10 minutes of access-token life (twice git-token-service's
  5-minute refresh buffer): a token inside the buffer passes the live probe,
  then triggers a refresh the copy cannot perform
- the target lookup tries the exact sign-in email before the normalized
  fallback, since normalized_email is not unique

* fix(mobile-e2e): state the copy's real lifetime and align the lock budget

- the 'can never refresh' claim was wrong: git-token-service gates refresh on
  the ACCESS token's expiry, so the dummy refresh token IS sent and the copy
  ends up revoked. Docs, usage text and the runbook now describe that end
  state, the tool reports usableUntil, and donors need 35 minutes of access
  life so a copy is usable for at least 30
- --remove reports what actually went away (.returning()), so a row replaced
  mid-command cannot read as removed
- stub lock --wait raised to 900s, above the ~8 minute worst-case hold the
  120s per-call budgets allow, so a queued stop or seed waits instead of
  failing
- drop the now-unused 'or' import

* fix(mobile-e2e): re-assert the usable window after the live probes

The 35-minute SQL margin is measured before up to ten 15-second GitHub
probes, so a copy could return with less than the promised 30 usable
minutes. The selected donor is now re-checked against the clock after its
probe, and one helper owns the usable-until arithmetic the filter, the
check, and the report all share.

* docs(mobile-e2e): bound big outputs, never doctor --json

A campaign verifier died with no sentinel right after a doctor --json dump
(the whole environment, PATH included). The runbook now states the general
rule — bound anything that can print a lot — and names --json diagnostics
alongside the Appium and hierarchy cases it already covered.

* fix(mobile): gate markdown image sources on the HTML scheme allowlist

* fix(mobile): anchor HTML image attribute regexes to name boundaries

* fix(mobile): validate tags-only tokens; strip comments to a fixed point

* perf(mobile): mount the markdown image viewer only while open

* style(mobile-e2e): format the GitHub API stub server

* test(mobile): satisfy image renderer test type checks

* test(mobile): satisfy image renderer lint checks

* chore: retrigger review

* chore: retrigger review

* fix(dev): distinguish aliased GitHub seed identities

* fix(dev): preserve Android launch lock contention

* fix(mobile-e2e): preserve env file on grep errors

* docs(mobile-e2e): doctor is always a full JSON dump; never tail JSON

Two review corrections, both verified against dev/local/mobile-android.ts:
doctor ignores flags and always prints the whole environment (PATH
included), so the runbook's 'plain doctor is safe' advice pointed at the
unsafe form; and tail on JSON leaves an unparseable fragment while the
runbook requires parsing dev:status --json. The bounded form is a jq field
selector, shown inline for both cases.

* chore(e2e): revert apps/mobile/e2e to base

The e2e harness changes belong to #4960.

* fix(dev): drop test assertions for the reverted e2e harness

The assertions pin apps/mobile/e2e content that #4960 owns.
Point the seed help text at the stub that exists on main.

* chore(dev): revert shared e2e harness files

PR #4960 carries these changes and merges first. This branch keeps no copy.

- dev/local/mobile-android.ts
- dev/local/mobile-simulator.ts
- dev/local/tmux.ts
- dev/seed/app/github-integration-copy.ts

* test(mobile-e2e): restore the PR-review image fixtures

* fix(mobile): keep inline images out of text

* fix(mobile): preserve image link behavior

* fix(mobile): preserve linked image safety
iscekic added a commit that referenced this pull request Aug 17, 2026
* fix(mobile): bump app version to 1.0.4

* refactor(mobile-e2e): simplified runbook, scripted stub setup, load-tolerant flows

- rewrite e2e/AGENTS.md in simplified technical English: task-structured,
  scripts own the mechanics, 410 -> ~215 lines
- new e2e/github-stub.sh: PR-review stub server + env line + token seed
  as one reversible command pair; failed starts clean up after themselves
- emulator-start --wait retries a failed launch once itself (boot-envelope
  timeout keeps the GPU, other failures switch to software rendering);
  the runbook's manual GPU decision table is gone
- appium.sh hierarchy writes to a file and prints the path; a raw XML dump
  into an agent session is large enough to kill it silently
- raise iOS cold-launch/settle budgets to 120s (timed out under parallel
  dual-bundle load); document ANR-under-load handling
- simulator claims record originalDeviceName and bootedByClaim intent in
  the initial write, so a lost post-boot rewrite can no longer leak a
  renamed or still-booted device on release

* fix(mobile-e2e): address review findings on retry and stub rollback

- emulator-start retry: rethrow the already-exists guard (a retry would
  tear down a live emulator) and keep attempt 1's error when the interim
  teardown itself fails
- github-stub: curl transport failures now route through seed_fail, so a
  failed start still rolls back the session and env line
- github-stub: guard against a .env.local without a trailing newline
  before appending, so the marker line can never merge into (and later
  delete) an existing variable

* fix(mobile-e2e): close concurrency races found in adversarial review

- tmux targets use exact-match (=name): bare -t prefix-matches, so a sibling
  worktree whose slug extends ours could be probed or killed in its place
- simulator claims write atomically (temp + rename/link): in-place truncation
  let an unlocked reader see a partial file, judge it corrupt, and delete a
  live claim
- a claim abandoned after its boot (rename failure) now powers the device
  off, or keeps the claim when even that fails
- simctl bootstatus is bounded (15 min) so a wedged CoreSimulator cannot
  block a claim forever
- emulator-start tears down after a failed second attempt too
- github-stub start claims its port machine-globally and verifies its own
  session survived, so two worktrees cannot share one stub silently; stop
  releases the claim
- appium: driver install re-checks inside the install lock; server startup
  verifies port ownership before adopting a listener; stop escalates to
  SIGKILL instead of orphaning a live server
- record.sh serializes start/stop per device with the shared process lock
- open-app consumes its launch budget in 30s slices so an ANR dialog is
  answered promptly instead of after the full wait
- login.sh matches the recipient literally, not as a regex
- hierarchy mktemp template puts Xs last (BSD mktemp leaves embedded Xs
  literal, making every bare call after the first fail)
- AGENTS.md: per-platform mixed fixtures, pull-and-grep for ADB dumps,
  stub-stop token residue note
- mobile-workflow tests updated for the raised launch/settle budgets

* fix(mobile-e2e): adversarial-review round 2

- appium: the recorded-server fast path now verifies the recorded pid owns
  the listener before adopting (a recycled pid plus a sibling's server on
  the same port answered /status and got adopted)
- github-stub: seeding extracted into seed_token; new 'seed <email>'
  subcommand adds a token row for a second signed-in account (the other
  platform's verifier) without touching the running stub
- github-stub: the port claim covers only the choose-to-bind window and an
  EXIT trap releases it, so an interrupted start cannot leak claims and
  erode the port range
- github-stub: githubUserId carries the pid — concurrent seeds in the same
  second cannot collide on the unique github_user_id
- AGENTS.md: the ADB dump example creates its own mktemp file instead of
  assuming $SCRATCH

* fix(mobile-e2e): seed verifies the endpoint's success flag

devSeedUserGithubToken can answer 200 with success:false (row not
upserted); the status code alone reported a seed that never landed.

* fix(mobile-e2e): server stop verifies death before dropping state

A process that survives even SIGKILL kept its state file removed and the
stop reported success; the caller then released device claims over a live
server. stop now fails and keeps the state in that case.

* fix(mobile-e2e): address stub-claim, re-seed, and lsof review findings

- claim_port reaps an orphaned port claim (older than 120s with nothing
  listening) and the start path traps INT/TERM/HUP besides EXIT, so a
  killed start can no longer shrink the port pool permanently
- githubUserId derives deterministically from the account email: the
  upsert's setWhere only updates a matching row, so the fresh random id
  made every re-seed of an already-seeded account report success:false
  and tear the stub down with a misleading hint
- lsof ownership probes tolerate no-match exits; pipefail otherwise killed
  appium.sh before the fresh-start fallback could run

* fix(mobile-e2e): tighten adoption, signal exits, and legacy-seed handling

- appium startup adopts a port only on proven ownership (listener pid equals
  ours); an empty lsof keeps polling instead of adopting a vanished or
  foreign server
- github-stub signal traps exit instead of continuing a start that just
  released its port claim
- success:false with 200 and no error means an account seeded under an older
  random id — keep that usable row instead of tearing the stub down

* fix(mobile-e2e): name both sources of an existing token row

success:false can come from an older random-id seed or from a real GitHub
connection on the dev account; the keep-message now says so instead of
implying only legacy seeds, and notes the stub accepts any token.

* fix(mobile-e2e): stub row verification, self-cleaning start, lsof fallback

- a kept token row is verified to be the stub's (getUserAuthorization
  githubLogin == kilo-stub-user); a real GitHub connection row fails with a
  drop-the-row hint — under the stub its refresh bypasses
  GITHUB_API_BASE_URL, hits real github.com, and revokes itself
- start rolls back everything (session, env line, state, port claim) via one
  EXIT trap when it dies before the final state write, so an aborted start
  no longer blocks the next one behind 'session already runs'
- appium ownership checks degrade to pid+status when lsof is missing or
  cannot attribute the socket, instead of killing healthy servers across 50
  port blocks

* fix(mobile-e2e): honest row probe, race-safe rollback, blind-lsof reuse

- the row probe checks HTTP status and error envelope before advising: a
  failed probe reports 'could not determine the existing row' instead of
  confidently telling the operator to delete a row it never examined; a
  kept row must also be connected (a revoked stub row gets the drop hint)
- start's rollback undoes only what this run did (session-created and
  env-added flags), so a start losing the session-creation race cannot kill
  the winner's session, env line, or state
- the recorded-server reuse path applies the same blind-lsof rule as the
  start loop: adopt on pid+status after three blind probes instead of
  orphaning a healthy server and consuming a port block per invocation
- drop dead SEED_FAIL_MODE and the stale random-id comment

* fix(mobile-e2e): close the last rollback and adoption windows

- github-stub creates its session under a pid-unique name armed before the
  create and renames to claim the canonical one: a signal at any instant
  tears down only our own session, and a lost rename race touches nothing
  but our port claim; the env-added flag arms before the append for the
  same reason
- the appium reuse probe rechecks pid liveness and /status on every pass,
  so a server dying mid-probe is cleaned up (stop_server) instead of
  adopted; a foreign listener still only drops our state

* fix(mobile-e2e): serialize the stub per worktree instead of guarding windows

Concurrent stub commands raced over the session name, env line, and state
dir; each guard narrowed the window without closing it. The shared
process-lock (the appium.sh pattern) removes the class: one stub command per
worktree at a time, so the entry check is authoritative, the rollback flags
only order against signals, and the unique-name rename dance goes away.

* fix(mobile-e2e): row-probe failures skip the missing-user hint

Both row branches run after the account answered the seed call, so the
sign-in hint contradicted what the script had just proved.

* fix(mobile-e2e): bound the lock's hold time and the survivor edge

- every network call under the stub lock carries --max-time 30, so a hung
  local API cannot hold the lock to its 300s wait bound; status runs
  unlocked (read-only) and answers during a long start
- a failed session create (a survivor of a SIGKILLed lock wrapper got there
  first) resets the created flag before exiting, so cleanup cannot touch
  the survivor's session
- align the env-append comment with the lock (the rename step it cited is
  gone)

* feat(mobile-e2e): copy a real GitHub integration onto an e2e account

pnpm dev:seed app:github-integration-copy <email> finds the newest real
integration in the shared dev database (fakes excluded: kilo-stub* logins
and far-future expiries — a real refresh token expires within months),
decrypts it with git-token-service's local dev key, re-encrypts for the
target account under a synthetic github_user_id (the pair index is unique),
and upserts. Scenarios that need a real integration (cloud agents) run
against the copy; with no valid donor the command fails with an explicit
BLOCKED message, and the runbook tells verifiers to report VERIFICATION
BLOCKED rather than fake or silently skip. Verified against the dev db:
copy mechanics end to end, and the blocked path on a database holding only
seeded rows.

* fix(mobile-e2e): copies never donate or collide with the stub

- donor filter excludes 13-digit synthetic github_user_ids (stub seeds and
  earlier copies): revocation lands only on the real row, so a surviving
  copy could hand out dead credentials as a fresh success
- app:github-integration-copy --remove <email> deletes the account's token
  row, so an account can return to stub use; runbook and usage text now
  require separate accounts for stub and integration scenarios
- verified live: remove clears the copied row and is idempotent

* docs(mobile-e2e): STE pass over the runbook additions

One instruction per sentence in the integration and stub sections; no rule
changed meaning.

* fix(mobile-e2e): copies validate the donor live and can never refresh

- the donor's access token is checked against api.github.com before the
  copy: database metadata cannot prove a rotated or GitHub-revoked token
  dead, so silent dead-credential copies reported success
- the copy row carries a dummy, already-expired refresh token: GitHub
  refresh tokens rotate on use, so a refreshing copy would kill the donor's
  stored refresh token and poison every later copy
- usage and runbook text updated to the access-token-only contract

* fix(mobile-e2e): guard the integration copy's blast radius

The copy relocates real credentials, so every destructive path is now
guarded and every shared-grant hazard is stated:

- assertLocalDatabaseTarget: USE_PRODUCTION_DB=true and non-loopback hosts
  are refused, making the dev-only claim enforceable (verified live)
- --remove deletes only a synthetic row (copy or stub seed) and names what
  it removed; a real connection is refused with instructions
- a copy refuses to overwrite a real connection on the target account
- donor lookup also matches google_user_email (normalized_email is nullable)
- usage and runbook state the real blast radius: the copy shares the donor's
  OAuth grant, so disconnect on a copied account revokes the DONOR's
  authorization and no re-copy repairs it — disconnect scenarios are blocked
  on copied accounts; commit attribution carries a synthetic id
- stub status reports 'starting' when a session has no state yet, instead of
  claiming up for a stub that is not usable
- lock-bounded curls raised to 120s (30s was the budget this PR already
  found too small under full parallel load)
- a failed tmux create distinguishes a concurrent session from a tmux error

* fix(mobile-e2e): env failures in the copy tool name their own fix

A dead database dumped a driver AggregateError stack trace, and a dead
network read as 'no valid donor'. Both now fail with one line naming the
command that fixes them, so an agent does not spend a round guessing at
ECONNREFUSED output or chasing a false BLOCKED. Verified live with postgres
stopped.

* fix(mobile-e2e): make the copy's guards atomic and expiry-safe

- the synthetic-only rule is re-asserted in the upsert's setWhere, so a real
  OAuth callback landing between the pre-check and the write cannot be
  overwritten; zero updated rows reports that explicitly (postgres predicate
  verified against synthetic and real id shapes)
- donors need >10 minutes of access-token life (twice git-token-service's
  5-minute refresh buffer): a token inside the buffer passes the live probe,
  then triggers a refresh the copy cannot perform
- the target lookup tries the exact sign-in email before the normalized
  fallback, since normalized_email is not unique

* fix(mobile-e2e): state the copy's real lifetime and align the lock budget

- the 'can never refresh' claim was wrong: git-token-service gates refresh on
  the ACCESS token's expiry, so the dummy refresh token IS sent and the copy
  ends up revoked. Docs, usage text and the runbook now describe that end
  state, the tool reports usableUntil, and donors need 35 minutes of access
  life so a copy is usable for at least 30
- --remove reports what actually went away (.returning()), so a row replaced
  mid-command cannot read as removed
- stub lock --wait raised to 900s, above the ~8 minute worst-case hold the
  120s per-call budgets allow, so a queued stop or seed waits instead of
  failing
- drop the now-unused 'or' import

* fix(mobile-e2e): re-assert the usable window after the live probes

The 35-minute SQL margin is measured before up to ten 15-second GitHub
probes, so a copy could return with less than the promised 30 usable
minutes. The selected donor is now re-checked against the clock after its
probe, and one helper owns the usable-until arithmetic the filter, the
check, and the report all share.

* docs(mobile-e2e): bound big outputs, never doctor --json

A campaign verifier died with no sentinel right after a doctor --json dump
(the whole environment, PATH included). The runbook now states the general
rule — bound anything that can print a lot — and names --json diagnostics
alongside the Appium and hierarchy cases it already covered.

* chore: retrigger Kilobot

* fix(seed): avoid synthetic GitHub ID collisions

* chore(e2e): revert apps/mobile/e2e to base

The e2e harness changes belong to #4960.

* fix(dev): drop test assertions for the reverted e2e harness

The assertions pin apps/mobile/e2e content that #4960 owns.

* chore(dev): revert shared e2e harness files

PR #4960 carries these changes and merges first. This branch keeps no copy.

- dev/local/mobile-android.ts
- dev/local/mobile-simulator.ts
- dev/local/tmux.ts
- dev/seed/app/github-integration-copy.ts
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.

2 participants