From f24f2a5e0fe626f55973283fb8ffb1065a5b8556 Mon Sep 17 00:00:00 2001 From: russellwheatley Date: Wed, 2 Dec 2026 13:06:50 +0000 Subject: [PATCH 1/5] docs(okf): route agents by change type and split testing docs Agents were loading 100+ KB of testing docs for small changes (a Jest-only change read the whole command allowlist and validation checklist, then ran the full lint, tsc, prepare and type-parity set). AGENTS.md now routes by change type to a short route per diff kind that names the work type, tier, files to load per step and exact commands, linking to the existing rule owners without adding rules. The five large testing docs are split verbatim into task-sized files under testing/commands, authoring, validation, e2e and code-coverage. Each old path stays as a catalog that keeps every old anchor, so links from code, CI, CONTRIBUTING.md and skills keep resolving. Links inside the bundle now point at the new homes; a few pre-existing broken links and fragments are fixed along the way. --- AGENTS.md | 39 +- okf-bundle/CONTEXT.md | 45 + okf-bundle/ci-workflows/android.md | 4 +- okf-bundle/ci-workflows/detox-patches.md | 6 +- okf-bundle/ci-workflows/index.md | 4 +- okf-bundle/ci-workflows/ios.md | 14 +- okf-bundle/ci-workflows/other.md | 2 +- okf-bundle/documentation-policy.md | 6 +- okf-bundle/documentation-site-maintenance.md | 8 +- okf-bundle/index.md | 14 +- .../architecture-decisions.md | 4 +- okf-bundle/monorepo-tooling/index.md | 8 +- .../monorepo-tooling/maintainer-publish.md | 2 +- .../monorepo-tooling/prepare-and-cache.md | 12 +- .../architecture-decisions.md | 58 +- okf-bundle/new-architecture/index.md | 12 +- okf-bundle/packages/app/index.md | 6 +- .../packages/auth/compare-types-triage.md | 4 +- okf-bundle/packages/auth/index.md | 2 +- okf-bundle/packages/firestore/index.md | 2 +- .../pipeline-implementation-workflow.md | 22 +- .../firestore/pipeline-sdk-support-audit.md | 4 +- okf-bundle/packages/firestore/pipelines.md | 4 +- okf-bundle/packages/messaging/index.md | 8 +- okf-bundle/routes/docs-only.md | 48 + okf-bundle/routes/e2e.md | 32 + okf-bundle/routes/expo-plugin.md | 48 + okf-bundle/routes/index.md | 49 + okf-bundle/routes/js-lib.md | 48 + okf-bundle/routes/native.md | 52 + okf-bundle/routes/okf-docs.md | 29 + okf-bundle/routes/tests-only.md | 47 + okf-bundle/testing/agent-command-policy.md | 417 +----- .../testing/android-architecture-decisions.md | 2 +- okf-bundle/testing/authoring/gates.md | 54 + .../testing/authoring/implementation.md | 82 ++ okf-bundle/testing/authoring/loop.md | 103 ++ .../testing/authoring/quality-standards.md | 52 + .../testing/authoring/review-and-commit.md | 57 + .../testing/change-authoring-workflow.md | 316 +---- .../testing/code-coverage/codecov-ci.md | 46 + .../invariants-and-troubleshooting.md | 60 + okf-bundle/testing/code-coverage/local.md | 80 ++ .../code-coverage/migration-rollback.md | 71 + okf-bundle/testing/code-coverage/native.md | 62 + okf-bundle/testing/code-coverage/pipelines.md | 129 ++ okf-bundle/testing/code-coverage/policy.md | 118 ++ .../testing/code-coverage/test-app-modules.md | 48 + okf-bundle/testing/commands/constraints.md | 41 + okf-bundle/testing/commands/core.md | 99 ++ okf-bundle/testing/commands/docs.md | 21 + okf-bundle/testing/commands/e2e.md | 52 + okf-bundle/testing/commands/fixtures.md | 91 ++ okf-bundle/testing/commands/forbidden.md | 33 + .../testing/commands/native-build-gate.md | 52 + okf-bundle/testing/commands/native.md | 75 ++ okf-bundle/testing/coverage-design.md | 547 +------- okf-bundle/testing/e2e-parallel-design.md | 64 +- okf-bundle/testing/e2e/environment.md | 70 + okf-bundle/testing/e2e/full-suite.md | 38 + okf-bundle/testing/e2e/gates.md | 137 ++ okf-bundle/testing/e2e/narrowing.md | 139 ++ .../testing/e2e/platform-troubleshooting.md | 151 +++ .../testing/e2e/preflight-host-clear.md | 98 ++ okf-bundle/testing/e2e/preflight.md | 90 ++ okf-bundle/testing/e2e/prerequisites.md | 48 + okf-bundle/testing/e2e/recovery.md | 111 ++ okf-bundle/testing/e2e/rules.md | 120 ++ okf-bundle/testing/e2e/run-loop.md | 94 ++ okf-bundle/testing/e2e/slot-devices.md | 71 + okf-bundle/testing/e2e/slot-env-variables.md | 38 + okf-bundle/testing/e2e/slotted-parallel.md | 47 + okf-bundle/testing/e2e/startup-fail-fast.md | 45 + .../testing/firebase-testing-project.md | 16 +- okf-bundle/testing/index.md | 62 +- .../testing/ios-architecture-decisions.md | 4 +- okf-bundle/testing/iteration-vocabulary.md | 14 +- .../testing/local-ios-e2e-reproduction.md | 4 +- okf-bundle/testing/running-e2e.md | 1176 +---------------- .../testing/test-app-dependency-pins.md | 8 +- okf-bundle/testing/validation-checklist.md | 280 +--- .../testing/validation/compile-and-types.md | 47 + okf-bundle/testing/validation/docs-lint.md | 32 + .../validation/evidence-and-handoff.md | 67 + .../testing/validation/fixtures-and-e2e.md | 27 + okf-bundle/testing/validation/jest.md | 35 + okf-bundle/testing/validation/lint.md | 38 + okf-bundle/testing/validation/native-unit.md | 62 + okf-bundle/testing/validation/okf-review.md | 17 + okf-bundle/testing/validation/work-types.md | 27 + 90 files changed, 3872 insertions(+), 2756 deletions(-) create mode 100644 okf-bundle/CONTEXT.md create mode 100644 okf-bundle/routes/docs-only.md create mode 100644 okf-bundle/routes/e2e.md create mode 100644 okf-bundle/routes/expo-plugin.md create mode 100644 okf-bundle/routes/index.md create mode 100644 okf-bundle/routes/js-lib.md create mode 100644 okf-bundle/routes/native.md create mode 100644 okf-bundle/routes/okf-docs.md create mode 100644 okf-bundle/routes/tests-only.md create mode 100644 okf-bundle/testing/authoring/gates.md create mode 100644 okf-bundle/testing/authoring/implementation.md create mode 100644 okf-bundle/testing/authoring/loop.md create mode 100644 okf-bundle/testing/authoring/quality-standards.md create mode 100644 okf-bundle/testing/authoring/review-and-commit.md create mode 100644 okf-bundle/testing/code-coverage/codecov-ci.md create mode 100644 okf-bundle/testing/code-coverage/invariants-and-troubleshooting.md create mode 100644 okf-bundle/testing/code-coverage/local.md create mode 100644 okf-bundle/testing/code-coverage/migration-rollback.md create mode 100644 okf-bundle/testing/code-coverage/native.md create mode 100644 okf-bundle/testing/code-coverage/pipelines.md create mode 100644 okf-bundle/testing/code-coverage/policy.md create mode 100644 okf-bundle/testing/code-coverage/test-app-modules.md create mode 100644 okf-bundle/testing/commands/constraints.md create mode 100644 okf-bundle/testing/commands/core.md create mode 100644 okf-bundle/testing/commands/docs.md create mode 100644 okf-bundle/testing/commands/e2e.md create mode 100644 okf-bundle/testing/commands/fixtures.md create mode 100644 okf-bundle/testing/commands/forbidden.md create mode 100644 okf-bundle/testing/commands/native-build-gate.md create mode 100644 okf-bundle/testing/commands/native.md create mode 100644 okf-bundle/testing/e2e/environment.md create mode 100644 okf-bundle/testing/e2e/full-suite.md create mode 100644 okf-bundle/testing/e2e/gates.md create mode 100644 okf-bundle/testing/e2e/narrowing.md create mode 100644 okf-bundle/testing/e2e/platform-troubleshooting.md create mode 100644 okf-bundle/testing/e2e/preflight-host-clear.md create mode 100644 okf-bundle/testing/e2e/preflight.md create mode 100644 okf-bundle/testing/e2e/prerequisites.md create mode 100644 okf-bundle/testing/e2e/recovery.md create mode 100644 okf-bundle/testing/e2e/rules.md create mode 100644 okf-bundle/testing/e2e/run-loop.md create mode 100644 okf-bundle/testing/e2e/slot-devices.md create mode 100644 okf-bundle/testing/e2e/slot-env-variables.md create mode 100644 okf-bundle/testing/e2e/slotted-parallel.md create mode 100644 okf-bundle/testing/e2e/startup-fail-fast.md create mode 100644 okf-bundle/testing/validation/compile-and-types.md create mode 100644 okf-bundle/testing/validation/docs-lint.md create mode 100644 okf-bundle/testing/validation/evidence-and-handoff.md create mode 100644 okf-bundle/testing/validation/fixtures-and-e2e.md create mode 100644 okf-bundle/testing/validation/jest.md create mode 100644 okf-bundle/testing/validation/lint.md create mode 100644 okf-bundle/testing/validation/native-unit.md create mode 100644 okf-bundle/testing/validation/okf-review.md create mode 100644 okf-bundle/testing/validation/work-types.md diff --git a/AGENTS.md b/AGENTS.md index 9fc7af28a4..c9e6e7a075 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,21 +2,30 @@ ## Project -- Yarn workspaces monorepo for React Native Firebase. -- Library code: `packages/**/lib`; e2e app: `tests/`. -- Contributor/review norms: `CONTRIBUTING.md`. - -## Working - -- Run from repo root; install once with `yarn`. -- **Agent shell commands:** [agent-command-policy.md](okf-bundle/testing/agent-command-policy.md) only (allowlist). E2e additionally [running-e2e.md § agent rule](okf-bundle/testing/running-e2e.md#agent-rule-read-first). -- Follow local package patterns; check `type-test.ts`, `__tests__/`, and plugin dirs before public API/platform changes. -- Start with `okf-bundle/index.md` for repo-specific implementation/testing/maintenance knowledge. -- **Change authoring:** [change-authoring-workflow.md](okf-bundle/testing/change-authoring-workflow.md) — baseline → unit-focused implementation → `documentation?` → area-focused `independent-review` → commit; [**validation evidence**](okf-bundle/testing/change-authoring-workflow.md#validation-evidence-blocking) and [**coverage evidence**](okf-bundle/testing/coverage-design.md#coverage-evidence-package) required before gates close or push. Do not add OKF / `AGENTS.md` / `CONTRIBUTING.md` after a frozen review without another `independent-review`. -- Use package indexes under `okf-bundle/packages/` for package-specific workflows and active work queues (Linear project documents; see [documentation-policy.md](okf-bundle/documentation-policy.md#work-queue-documents)). Do not create new `okf-bundle/**/*work-queue.md` files. -- Follow [documentation-policy § public vs ephemeral vs private](okf-bundle/documentation-policy.md#durable-vs-ephemeral): GitHub-public **reference** docs, this file, commits, and PR titles must not contain ephemeral **fields** or Linear issue identifiers. Gated queue state lives on Linear, not in new git files. -- Testing entry points: `okf-bundle/testing/index.md`; validation requirements: `okf-bundle/testing/validation-checklist.md`. -- Match validation to the **work type** and **validation tier** in OKF ([change authoring workflow](okf-bundle/testing/change-authoring-workflow.md); term ids in [iteration vocabulary](okf-bundle/testing/iteration-vocabulary.md)). +- Yarn workspaces monorepo for React Native Firebase. Library code: `packages/**/lib`; e2e app: `tests/`. Contributor/review norms: `CONTRIBUTING.md`. +- Run from repo root; install once with `yarn`. Repo knowledge: [okf-bundle/index.md](okf-bundle/index.md). + +## Route by change type + +Read only the route for what your diff touches. It names the work type, validation tier, files to load per step, and exact commands. Several rows match: [mixed diffs](okf-bundle/routes/index.md#mixed-diffs). + +| Diff touches | Route | +| --- | --- | +| `docs/**` only | [docs-only](okf-bundle/routes/docs-only.md) | +| `packages/*/__tests__/**` only (Jest) | [tests-only](okf-bundle/routes/tests-only.md) | +| `packages/*/lib/**` | [js-lib](okf-bundle/routes/js-lib.md) | +| `packages/*/{ios,android}/**`, podspecs, `generated/**`, codegen, `packages/app/**/*.rb` | [native](okf-bundle/routes/native.md) | +| `packages/*/e2e/**`, or any `yarn tests:*` e2e run | [e2e](okf-bundle/routes/e2e.md) | +| `packages/*/plugin/**`, `test-expo/**`, `test-rn-bare/**` | [expo-plugin](okf-bundle/routes/expo-plugin.md) | +| `okf-bundle/**`, `AGENTS.md`, `CONTRIBUTING.md` | [okf-docs](okf-bundle/routes/okf-docs.md) | +| CI, monorepo tooling, TurboModules, one package's workflow | [other areas](okf-bundle/routes/index.md#other-areas) | + +## Every change + +- **Agent shell commands:** [agent command policy](okf-bundle/testing/agent-command-policy.md#agent-rule-read-first) only (allowlist). E2e additionally [running-e2e.md § agent rule](okf-bundle/testing/running-e2e.md#agent-rule-read-first). +- **Change authoring:** [loop](okf-bundle/testing/authoring/loop.md#primary-loop): baseline → unit-focused implementation → `documentation?` → area-focused `independent-review` → commit. [Validation evidence](okf-bundle/testing/authoring/gates.md#validation-evidence-blocking) and, when required, [coverage evidence](okf-bundle/testing/code-coverage/policy.md#coverage-evidence-package) before gates close or push. Do not add OKF / `AGENTS.md` / `CONTRIBUTING.md` after a frozen review without another `independent-review`. +- Follow local package patterns; check `type-test.ts`, `__tests__/`, and plugin dirs before public API/platform changes. Package workflows: `okf-bundle/packages//index.md`. +- Follow [documentation-policy § public vs ephemeral vs private](okf-bundle/documentation-policy.md#durable-vs-ephemeral): GitHub-public **reference** docs, this file, commits, and PR titles must not contain ephemeral **fields** or Linear issue identifiers. Active work queues are Linear project documents ([work-queue documents](okf-bundle/documentation-policy.md#work-queue-documents)); do not create new `okf-bundle/**/*work-queue.md` files. ## PR instructions diff --git a/okf-bundle/CONTEXT.md b/okf-bundle/CONTEXT.md new file mode 100644 index 0000000000..c303c395db --- /dev/null +++ b/okf-bundle/CONTEXT.md @@ -0,0 +1,45 @@ +--- +type: Reference +title: okf-bundle structure +description: 'How the knowledge bundle is laid out, where a new fact goes, how to move text without breaking #anchors, and where the layout deliberately departs from ICM defaults.' +tags: [okf, structure, routes, documentation] +timestamp: 2026-12-02T00:00:00Z +--- + +# okf-bundle structure + +The bundle is the factory shelf for changing this repo: stable reference that agents load per task. The root `AGENTS.md` routes by change type to [routes/](routes/index.md); each route names the shelf files and commands for that change. [index.md](index.md) is the OKF catalog of every topic. Policy for what may be written here: [documentation-policy.md](documentation-policy.md). + +## Layout + +| Path | Job | +| --- | --- | +| `index.md` | OKF catalog (`okf_version`), one line per topic owner | +| `routes/` | One file per change type: work type, tier, files per step, exact commands, what that diff does not need. Routes link to owners and hold no rules | +| `testing/` | Testing owners. `testing/index.md` lists every file | +| `testing/commands/`, `authoring/`, `validation/`, `e2e/`, `code-coverage/` | Task-sized sections of `agent-command-policy.md`, `change-authoring-workflow.md`, `validation-checklist.md`, `running-e2e.md`, `coverage-design.md` | +| `ci-workflows/`, `monorepo-tooling/`, `new-architecture/`, `packages//` | Area owners, each with an `index.md` | +| `**/*work-queue.md` | Grandfathered ephemeral queues; never create new ones ([work-queue documents](documentation-policy.md#work-queue-documents)) | + +## Writing here + +- Every file starts with frontmatter (`type`, `title`, `description`, `tags`, `timestamp`); quote a value that contains `: `. The first heading names the file. +- One home per fact: link to the owner instead of copying. Add new topics to `index.md` (and `testing/index.md` for testing). +- Keep a file small enough that one route step loads it with its siblings in under about 8,000 tokens; split by section rather than trimming rules ([Efficiency](documentation-policy.md#efficiency)). +- Moving a section: move it verbatim, keep its heading text, and leave an `` for each of its anchors in the old file's anchor list, pointing at the new file. Files outside the bundle (code comments, CI, `CONTRIBUTING.md`, private skills) link to old paths and anchors. +- New text after a frozen review needs another `independent-review` ([OKF update contract](documentation-policy.md#okf-update-contract)). + +## Check + +The [OKF bundle review](testing/validation/okf-review.md#okf-bundle-review) during frozen `independent-review` is the check for this tree: canonical location, DRY, Efficiency, link hygiene, Durability. + +## Where this layout departs from ICM defaults + +Kept on purpose, OKF conventions win where they conflict: + +- **Catalogs are `index.md`, not `CONTEXT.md`.** OKF names folder catalogs `index.md`. Folders here are shelves of reference, not pipeline stages, so they have no Inputs / Process / Outputs contracts; the change authoring loop is the pipeline and lives in `testing/authoring/`. +- **`index.md` uses bundle-root links (`/testing/...`).** That is the existing OKF catalog style. A link checker must resolve a leading `/` against `okf-bundle/`, not the filesystem root. +- **Old paths stay as catalogs.** `agent-command-policy.md`, `change-authoring-workflow.md`, `validation-checklist.md`, `running-e2e.md` and `coverage-design.md` keep their intro, any agent rule, a file list, and an `` for every old anchor, instead of an `index.md` inside each new subfolder. External referrers keep working and each subfolder still has one catalog (its sibling file). +- **`AGENTS.md` keeps a few repo-wide rules** (command allowlist, change authoring evidence, public vs ephemeral, PR scope) as one-line links. It is the only file every agent is sure to load. +- **`testing/commands/constraints.md` restates other command rows** as one plain-text block for pasting into prompts. It predates this layout; each line's owner is a registry or trap section in `testing/commands/`. +- **`testing/code-coverage/`**, not `coverage/`: the repo `.gitignore` ignores every folder named `coverage`. diff --git a/okf-bundle/ci-workflows/android.md b/okf-bundle/ci-workflows/android.md index fd1ce25947..16e1f02a95 100644 --- a/okf-bundle/ci-workflows/android.md +++ b/okf-bundle/ci-workflows/android.md @@ -20,7 +20,7 @@ CI builds **one ABI** from `matrix.arch` via job env `ORG_GRADLE_PROJECT_reactNa 2. `tests:android:unit` — JVM unit (no emulator); produces module Jacoco `*.exec` ([AndroidTest-AD-1](../testing/android-architecture-decisions.md#androidtest-ad-1)) 3. `tests:android:test-cover --headless` — pass/fail gate 4. `tests:android:post-e2e-coverage` — poll/pull `coverage.ec`, merged **`jacocoTestReport`** (unit `*.exec` + e2e `*.ec`; best-effort, never fails the job) -5. **Codecov upload** — two flagged uploads (`e2e-ts-android`, `android-native` → `jacocoTestReport.xml`); `continue-on-error: true` on the action steps. **`codecov/project/android-native`** fails if the native flag upload is missing (see [coverage design](../testing/coverage-design.md#native-gates)). +5. **Codecov upload** — two flagged uploads (`e2e-ts-android`, `android-native` → `jacocoTestReport.xml`); `continue-on-error: true` on the action steps. **`codecov/project/android-native`** fails if the native flag upload is missing (see [coverage design](../testing/code-coverage/codecov-ci.md#native-gates)). Android native coverage is flushed in app process by `tests/app.js` Jet `after`; post-e2e pull runs after Detox exits and merges with JVM unit execution data. Full Jacoco contract: [coverage design](../testing/coverage-design.md) — do not duplicate here. @@ -74,7 +74,7 @@ Under load, Jet may run only a small prefix before mocha-remote desync, often af | Change | Location | |--------|----------| -| Defer `server.run()` until host `POST /launch-ready` on control port **8091** (`RNFB_JET_DEFER_RUN=1`) | Jet patch + `firebase.test.js` — [Jet host orchestration](../testing/running-e2e.md#jet-host-orchestration-ports-and-launch-gate) | +| Defer `server.run()` until host `POST /launch-ready` on control port **8091** (`RNFB_JET_DEFER_RUN=1`) | Jet patch + `firebase.test.js` — [Jet host orchestration](../testing/e2e/run-loop.md#jet-host-orchestration-ports-and-launch-gate) | | Inbound parse buffer + `tryDeserialize` in `serialization.js` / `parse_skip` logging | mocha-remote-server patch | | Outbound queue flushed on reconnect | mocha-remote-client patch | | `JET_PROTOCOL_ERROR_RE` → retryable Jet session (attempt 2) | `tests/e2e/firebase.test.js` | diff --git a/okf-bundle/ci-workflows/detox-patches.md b/okf-bundle/ci-workflows/detox-patches.md index 1ec33b7289..76a538a9b4 100644 --- a/okf-bundle/ci-workflows/detox-patches.md +++ b/okf-bundle/ci-workflows/detox-patches.md @@ -12,7 +12,7 @@ E2E runs on **Detox 20.51.0** (`tests/package.json`). This file inventories the `.yarn/patches/detox-npm-20.51.0-3e13b6e309.patch` -**Not this file:** iOS neutral-slot exact-base-or-fail allocation is [`tests/patches/detox+20.51.0.patch`](../../tests/patches/detox+20.51.0.patch) via `tests` `prepare` (`patch-package`). Contract: [running e2e § iOS slot simulators](../testing/running-e2e.md#ios-slot-simulators). Do not add that hunk here. +**Not this file:** iOS neutral-slot exact-base-or-fail allocation is [`tests/patches/detox+20.51.0.patch`](../../tests/patches/detox+20.51.0.patch) via `tests` `prepare` (`patch-package`). Contract: [running e2e § iOS slot simulators](../testing/e2e/slot-devices.md#ios-slot-simulators). Do not add that hunk here. Patches are in-repo. Prefer direct patch-file edits or headless workflow; `yarn patch-commit` may prompt and fail in non-interactive shells. @@ -23,14 +23,14 @@ Patches are in-repo. Prefer direct patch-file edits or headless workflow; `yarn | Disable network idling | `NetworkIdlingResource.kt` | Android | OkHttp never idle in RN Firebase tests → Detox sync timeout | | Disable timers idling | `TimersIdlingResource.kt` | Android | RN timer queue never drains → infinite idle wait | | Disable Fabric UI idling | `FabricUIManagerIdlingResources.kt` | Android | Stuck mount items on API 36+ / edge-to-edge → false busy | -| Raise Login / CurrentStatus timeouts | `src/client/actions/actions.js` | iOS, Android, macOS | Patch Login **15000ms** / CurrentStatus **30000ms** (Detox defaults 1000 / 5000). Status-query timeout under load is latency, not fail-fast. RNFB-side launch retries: [`tests/e2e/detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js) ([running e2e § slot lifecycle](../testing/running-e2e.md#slot-lifecycle)) | +| Raise Login / CurrentStatus timeouts | `src/client/actions/actions.js` | iOS, Android, macOS | Patch Login **15000ms** / CurrentStatus **30000ms** (Detox defaults 1000 / 5000). Status-query timeout under load is latency, not fail-fast. RNFB-side launch retries: [`tests/e2e/detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js) ([running e2e § slot lifecycle](../testing/e2e/environment.md#slot-lifecycle)) | | Raise ADB `pm install` spawn timeout | `ADB.js` `DEFAULT_INSTALL_OPTIONS` | Android | Detox default **60000ms** hard-kills slow installs under 9-way load (`terminated with SIGTERM`). Patched to **300000ms** (same latency class as launchApp). Contract: `androidAdbInstallTimeoutMs()` in [`detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js). **`RNFB_ANDROID_ADB_INSTALL_TIMEOUT_MS` is read by policy only** — the Detox patch hardcodes **300000** at yarn apply time; changing the env alone does not change Detox until the patch is regenerated | | Suppress emulator crash-report modal | `EmulatorExec.js` `LaunchCommand` | Android | Pass `-crash-report-mode never` so a crashed qemu cannot block unattended waves on the Google crash-report dialog. Requires Android Emulator **≥ 37** (flag confirmed present on 37.1.11.0); emulator 36.2.12.0 lacks it and `SPAWN_FAIL`s at launch — keep the emulator toolchain current instead of adding a runtime capability probe | | Buffer early `ready` | `AnonymousConnectionHandler.js` | iOS | App sends `ready` before Detox login → `launchApp` stuck | | Ignore missing adb reverse on teardown | `ADB.js` | Android | Jet WS 1006 triggers mid-run `reverse --remove` → adb exit 1 | | **2× device-registry lock stale** | `ExclusiveLockfile.js` | iOS, macOS, Android | `proper-lockfile` `ECOMPROMISED` before tests start | -Related patches: `jet`, `mocha-remote-client`, `mocha-remote-server` — WS reconnect grace, coverage handshake, client keepalive, parse buffering, reconnect assignment order, `transformFailure` Metro symbolication soft-fail; **host control HTTP on `JET_REMOTE_PORT + 1` (default 8091)** for launch defer + orchestrate phase (`RNFB_JET_DEFER_RUN`); HTTP POST `/coverage` on 8090 removed; **`fatal_disconnect` / exitOnError must `process.exit(1)` after `cleanup()`** so Detox Jest cannot sit for `testTimeout` (1h) after native crash + Jet dead disconnect. See [Jet host orchestration](../testing/running-e2e.md#jet-host-orchestration-ports-and-launch-gate), [coverage design](../testing/coverage-design.md), [iOS issues 6–8](ios.md#6-jet-websocket-disconnect-1006--1001) (incl. [6c](ios.md#6c-release-transformfailure-masks-real-errors-metro-symbolication)). +Related patches: `jet`, `mocha-remote-client`, `mocha-remote-server` — WS reconnect grace, coverage handshake, client keepalive, parse buffering, reconnect assignment order, `transformFailure` Metro symbolication soft-fail; **host control HTTP on `JET_REMOTE_PORT + 1` (default 8091)** for launch defer + orchestrate phase (`RNFB_JET_DEFER_RUN`); HTTP POST `/coverage` on 8090 removed; **`fatal_disconnect` / exitOnError must `process.exit(1)` after `cleanup()`** so Detox Jest cannot sit for `testTimeout` (1h) after native crash + Jet dead disconnect. See [Jet host orchestration](../testing/e2e/run-loop.md#jet-host-orchestration-ports-and-launch-gate), [coverage design](../testing/coverage-design.md), [iOS issues 6–8](ios.md#6-jet-websocket-disconnect-1006--1001) (incl. [6c](ios.md#6c-release-transformfailure-masks-real-errors-metro-symbolication)). ## Updating the jet patch (headless) diff --git a/okf-bundle/ci-workflows/index.md b/okf-bundle/ci-workflows/index.md index ac262f8ab6..2140052e78 100644 --- a/okf-bundle/ci-workflows/index.md +++ b/okf-bundle/ci-workflows/index.md @@ -15,7 +15,7 @@ GitHub Actions job shape, platform reliability, and artifact triage. * **Xcode ccache (`hendrikmuhs/ccache-action`)** — sticky content-hash keys with `append-timestamp: false` (no run-id/timestamp suffix). Key dimensions keep caches distinct: iOS e2e uses `buildmode` (SPM-only matrix); archive is a single SPM-only key; macOS is a single key; Expo iOS link probe uses `expo-link` (`…-expo-link-ios-v4-xcode27-…`); RN CLI bare iOS probe uses `rn-bare` / `rn-bare-dynfb` (`…-rn-bare-ios-v1-xcode27-…` / `…-rn-bare-dynfb-ios-v1-xcode27-…`). Hash inputs: e2e/macos use `yarn.lock`, `packages/*/*.podspec`, `packages/*/ios/**`, plus the platform `Podfile.lock`; Expo probe hashes `yarn.lock`, `test-expo/**`, and app-package iOS/plugin inputs; RN bare probe hashes `yarn.lock`, `test-rn-bare/**`, and app-package iOS/plugin/ruby inputs (dynfb also `packages/app/package.json`). Save on `main` only; e2e/macos further limit to `matrix.iteration == 0` (first writer wins on the exact sticky key). See [iOS](ios.md#xcode-ccache), [Other](other.md#xcode-ccache). * [Agent command policy](../testing/agent-command-policy.md) — allowlisted install/prepare/validation/e2e commands for agents; Expo documented-path iOS **link** is `yarn test-expo:ios:link` (not Detox); RN CLI prebuilt RNCore iOS **build** is `yarn test-rn-bare:ios:build` (not Detox) * [Running e2e — agent rule](../testing/running-e2e.md#agent-rule-read-first) — e2e `yarn tests:*` detail; never invoke Jet/Detox/Metro directly -* [Test-runner orchestration (log triage)](../testing/running-e2e.md#test-runner-host-orchestration-log-triage-only) — ports 8090/8091, defer-run launch gate markers +* [Test-runner orchestration (log triage)](../testing/e2e/run-loop.md#test-runner-host-orchestration-log-triage-only) — ports 8090/8091, defer-run launch gate markers * [Detox patches](detox-patches.md) — inventory, `ECOMPROMISED`, patch workflow * [Cloud API quota triage](../testing/firebase-testing-project.md#ci-triage-cloud-api-quota-pressure) — live FIS/RC pressure (all platforms) * [iOS diagnostics](ios.md#operational-notes) — `resource-monitor.sh`, `flake-summary.sh`, [CI baseload / load settle](ios.md#ci-baseload-policy-instrumentation) @@ -23,4 +23,4 @@ GitHub Actions job shape, platform reliability, and artifact triage. ## Related * [Running e2e tests](../testing/running-e2e.md) — local runbook; CI variants noted per platform -* [Coverage design](../testing/coverage-design.md) — e2e coverage, Codecov flags/gates; [iOS XCTest](../testing/ios-architecture-decisions.md#iostest-ad-1) (`yarn tests:ios:unit`); [iOS Ruby SimpleCov](../testing/coverage-design.md#ios-ruby-simplecov) (`yarn tests:ios:ruby`, flag `ios-ruby` on `tests_e2e_ios.yml` only) +* [Coverage design](../testing/coverage-design.md) — e2e coverage, Codecov flags/gates; [iOS XCTest](../testing/ios-architecture-decisions.md#iostest-ad-1) (`yarn tests:ios:unit`); [iOS Ruby SimpleCov](../testing/code-coverage/local.md#ios-ruby-simplecov) (`yarn tests:ios:ruby`, flag `ios-ruby` on `tests_e2e_ios.yml` only) diff --git a/okf-bundle/ci-workflows/ios.md b/okf-bundle/ci-workflows/ios.md index bb87cccc6a..926a6e150c 100644 --- a/okf-bundle/ci-workflows/ios.md +++ b/okf-bundle/ci-workflows/ios.md @@ -30,7 +30,7 @@ Dedicated Apple jobs use the **`xcode-27`** runner label (macOS 27 image), `maxi Archive-only and macOS-only jobs set `RNFB_CI_REQUIRE_IOS_SIM_RUNTIME=0` (Xcode major check only). Expo / bare fixture workflows run link/build plus **`yarn test-expo:ios:launch-smoke`** / **`yarn test-rn-bare:ios:launch-smoke`** on the pinned iOS 27 runtime. -**Local contributors** mirror the same Xcode / runtime / Device Hub expectations — [running e2e § Apple host toolchain](../testing/running-e2e.md#apple-host-toolchain-local). Mobile fixture versions (**RN 0.88.0-rc.3**, **Expo 58**) are in [test app dependency pins](../testing/test-app-dependency-pins.md#current-pins). +**Local contributors** mirror the same Xcode / runtime / Device Hub expectations — [running e2e § Apple host toolchain](../testing/e2e/prerequisites.md#apple-host-toolchain-local). Mobile fixture versions (**RN 0.88.0-rc.3**, **Expo 58**) are in [test app dependency pins](../testing/test-app-dependency-pins.md#current-pins). **iOS 26.5 sim runtime** (or an older Tart seed) is **not** a substitute for this ratchet: it may help explain **runtime-only** deltas (see [§ issue 5](#5-metro-unresponsive-at-launch--waitforactive-hang-active-app) `localhost` vs `127.0.0.1`), but it cannot satisfy the **Xcode 27** / **iOS 27** / UIScene launch-smoke gates. Details: [local Tart lab § iOS 26.5 not proof](../testing/local-ios-e2e-reproduction.md#ios-26-5-not-proof). @@ -50,7 +50,7 @@ On GHA macOS runners, `simctl list` can show `Booted` before the simulator is te **Pre-boot step** (`.github/workflows/scripts/boot-simulator.sh`), run via `nick-fields/retry` before Detox: -> **Not for local operators.** `boot-simulator.sh` is **CI-only** (this workflow) or invoked **internally** by `tests/e2e/firebase.test.js` on iOS test-runner retry. Local e2e: [running-e2e.md](../testing/running-e2e.md) only — [host-clear probes](../testing/running-e2e.md#host-clear-probes), [agent rule](../testing/running-e2e.md#agent-rule-read-first). Do not run `boot-simulator.sh` as operator prep. +> **Not for local operators.** `boot-simulator.sh` is **CI-only** (this workflow) or invoked **internally** by `tests/e2e/firebase.test.js` on iOS test-runner retry. Local e2e: [running-e2e.md](../testing/running-e2e.md) only — [host-clear probes](../testing/e2e/preflight-host-clear.md#host-clear-probes), [agent rule](../testing/running-e2e.md#agent-rule-read-first). Do not run `boot-simulator.sh` as operator prep. | Phase | What happens | |--------|----------------| @@ -186,11 +186,11 @@ Long `datamigrator` activity with no `io.invertase.testing` means migration/pre- Device type comes from `tests/.detoxrc.js`; boot script and Detox use it. No hard-coded UDID: in CI, Detox takes the UDID the boot step resolved ([simulator reliability](#problem)). -**Missing Detox framework cache** — if iOS `:test-cover` fails before tests with `Detox.framework could not be found`, rebuild the local cache: [running e2e § iOS Detox framework cache](../testing/running-e2e.md#ios-detox-framework-cache-blocking) (`yarn tests:ios:detox-framework-cache:rebuild`). CI restores `~/Library/Detox/ios` from Actions cache keyed by Xcode version. +**Missing Detox framework cache** — if iOS `:test-cover` fails before tests with `Detox.framework could not be found`, rebuild the local cache: [running e2e § iOS Detox framework cache](../testing/e2e/platform-troubleshooting.md#ios-detox-framework-cache) (`yarn tests:ios:detox-framework-cache:rebuild`). CI restores `~/Library/Detox/ios` from Actions cache keyed by Xcode version. ### Codecov (debug matrix only) -Debug leg: `yarn tests:ios:unit` (in-package XCTest; [IosTest-AD-1](../testing/ios-architecture-decisions.md#iostest-ad-1)) then Detox → `yarn tests:ios:test:process-coverage` + Codecov flags `e2e-ts-ios`, `ios-native`; `codecov/project/ios-native` blocks on missing native upload. **debug+spm** also runs `yarn tests:ios:ruby` and uploads Codecov flag `ios-ruby` (no `flag_management` hard gate — [coverage design § iOS Ruby](../testing/coverage-design.md#ios-ruby-simplecov)). Release skips coverage. Unit LCOV merges into `coverage/ios-native/lcov.info` — [coverage design](../testing/coverage-design.md). +Debug leg: `yarn tests:ios:unit` (in-package XCTest; [IosTest-AD-1](../testing/ios-architecture-decisions.md#iostest-ad-1)) then Detox → `yarn tests:ios:test:process-coverage` + Codecov flags `e2e-ts-ios`, `ios-native`; `codecov/project/ios-native` blocks on missing native upload. **debug+spm** also runs `yarn tests:ios:ruby` and uploads Codecov flag `ios-ruby` (no `flag_management` hard gate — [coverage design § iOS Ruby](../testing/code-coverage/local.md#ios-ruby-simplecov)). Release skips coverage. Unit LCOV merges into `coverage/ios-native/lcov.info` — [coverage design](../testing/coverage-design.md). ### E2E test app orchestration (Detox + Jet) @@ -233,11 +233,11 @@ Error: Unable to update lock within the stale threshold | Change | Location | |--------|----------| | Wait for Jet (port 8090) before `launchApp` | `tests/e2e/firebase.test.js` | -| Defer `server.run()` until host `POST /launch-ready` on control port **8091** (`RNFB_JET_DEFER_RUN=1`) | Jet patch + `firebase.test.js` — [Jet host orchestration](../testing/running-e2e.md#jet-host-orchestration-ports-and-launch-gate) | +| Defer `server.run()` until host `POST /launch-ready` on control port **8091** (`RNFB_JET_DEFER_RUN=1`) | Jet patch + `firebase.test.js` — [Jet host orchestration](../testing/e2e/run-loop.md#jet-host-orchestration-ports-and-launch-gate) | | `POST /orchestrate-state` + `[rnfb-e2e] orchestrate-state=` for launch/retry triage | `firebase.test.js` + Jet patch | | Wait for Metro (`/status`) before `launchApp` | `tests/e2e/firebase.test.js` (debug Detox configs only; release skips Metro wait) | | Bounded `launchApp` timeout / retries | [`tests/e2e/detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js) (consumed by `firebase.test.js`); release uses `RNFB_LAUNCH_APP_RELEASE_TIMEOUT_MS` from the same module; Detox Login / CurrentStatus: [detox-patches](detox-patches.md) | -| `detoxEnableSynchronization: '0'` at launch (native `equals("0")`; `'NO'` still installs Fabric idling) | `tests/e2e/firebase.test.js` — [running e2e § gray screen](../testing/running-e2e.md#android-emulator-gray-screen--quick-boot-blocking) | +| `detoxEnableSynchronization: '0'` at launch (native `equals("0")`; `'NO'` still installs Fabric idling) | `tests/e2e/firebase.test.js` — [running e2e § gray screen](../testing/e2e/platform-troubleshooting.md#android-emulator-gray-screen--quick-boot-blocking) | | `detoxURLBlacklistRegex: '.*'` | `tests/e2e/firebase.test.js` (existing) | #### 4. `waitForActive` / scene never foreground-active @@ -549,7 +549,7 @@ rg '\[rnfb-e2e\] retry-eligibility' detox-step.log | `[jet-coverage] client send coverage-ready attempt=2` | Client retry in progress | | `merged 0 file(s)` after disconnect | NYC got no JS coverage — check handshake lines above | -See also [coverage design — e2e TypeScript coverage](../testing/coverage-design.md#e2e-typescript-coverage-jet--nyc). +See also [coverage design — e2e TypeScript coverage](../testing/code-coverage/pipelines.md#e2e-typescript-coverage-jet--nyc). **Cloud API quota (Installations / Remote Config)** — platform-agnostic; see [firebase testing project — CI triage](../testing/firebase-testing-project.md#ci-triage-cloud-api-quota-pressure). diff --git a/okf-bundle/ci-workflows/other.md b/okf-bundle/ci-workflows/other.md index 7ee7cf7fad..a2ff62b54a 100644 --- a/okf-bundle/ci-workflows/other.md +++ b/okf-bundle/ci-workflows/other.md @@ -10,7 +10,7 @@ timestamp: 2026-08-26T00:00:00Z ## macOS e2e (`tests_e2e_other.yml`) -Local macOS e2e: [running e2e § Rules](../testing/running-e2e.md#rules) only. CI pipeline below mirrors `tests_e2e_other.yml` (uses `-ci` packager variants). +Local macOS e2e: [running e2e § Rules](../testing/e2e/rules.md#rules) only. CI pipeline below mirrors `tests_e2e_other.yml` (uses `-ci` packager variants). **Dual-app pins:** CI macOS stays on **`tests-macos/`** RN **0.78.3** + `react-native-macos@0.78.6`. Mobile Detox (`tests/`) is on RN **0.86.2** and owns codegen. See [test app dependency pins](../testing/test-app-dependency-pins.md). diff --git a/okf-bundle/documentation-policy.md b/okf-bundle/documentation-policy.md index acec9ae6cb..9c62e7aa7e 100644 --- a/okf-bundle/documentation-policy.md +++ b/okf-bundle/documentation-policy.md @@ -42,7 +42,7 @@ PRs are squash-merged. Maintainers or agents may amend or squash to **fix** a no ## OKF update contract -OKF markdown edits require an **independent bundle consistency pass**. That pass **is** `independent-review` when the frozen tree includes `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` — [validation-checklist § OKF bundle review](testing/validation-checklist.md#okf-bundle-review). The `documentation` work type **promotes** durable text; it does not run this scan. Loop order: [change authoring § primary loop](testing/change-authoring-workflow.md#primary-loop). +OKF markdown edits require an **independent bundle consistency pass**. That pass **is** `independent-review` when the frozen tree includes `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` — [validation-checklist § OKF bundle review](testing/validation/okf-review.md#okf-bundle-review). The `documentation` work type **promotes** durable text; it does not run this scan. Loop order: [change authoring § primary loop](testing/authoring/loop.md#primary-loop). Scan the **entire** `okf-bundle/` tree against: @@ -54,7 +54,7 @@ Scan the **entire** `okf-bundle/` tree against: | **Link hygiene** | Cross-links resolve; indexes list canonical entry points | | **Durability** | No ephemeral or private fields in GitHub-public **reference** docs, commits, or PR titles. Queue state lives on Linear (or a grandfathered repo file until pickup). Linear issue identifiers stay off GitHub | -**Report-only** during `independent-review` ([frozen tree](testing/change-authoring-workflow.md#frozen-tree)). **Fix before `git commit`**. Do not add OKF after a frozen review without another `independent-review`. Work-queue edits still follow this split. +**Report-only** during `independent-review` ([frozen tree](testing/authoring/review-and-commit.md#frozen-tree)). **Fix before `git commit`**. Do not add OKF after a frozen review without another `independent-review`. Work-queue edits still follow this split. ## Efficiency @@ -85,6 +85,6 @@ Work queues are **intentionally ephemeral**: phases, **commit subjects**, gates, **Existing repo queues:** stay the source of truth until that item is next picked up. On pickup, copy the file into a Linear project document, point the Linear issue at it (`Queue: linear-work-queue`), and delete the file in the same change. Do not dual-write. -Work queues record **gates**, **`next_work_type`**, **`validation_tier`**, and **`commit_subject`** using field names and allowed values from [iteration vocabulary](testing/iteration-vocabulary.md). Gate semantics, workflow rules, and `commit_subject` recording: [change authoring workflow](testing/change-authoring-workflow.md) (including [§ commit](testing/change-authoring-workflow.md#commit)). Public OKF owns those terms, gates, and commands. They do **not** name agent roles, dispatch instructions, or session choreography. +Work queues record **gates**, **`next_work_type`**, **`validation_tier`**, and **`commit_subject`** using field names and allowed values from [iteration vocabulary](testing/iteration-vocabulary.md). Gate semantics, workflow rules, and `commit_subject` recording: [change authoring workflow](testing/change-authoring-workflow.md) (including [§ commit](testing/authoring/review-and-commit.md#commit)). Public OKF owns those terms, gates, and commands. They do **not** name agent roles, dispatch instructions, or session choreography. Record **`commit_subject`** (the planned Conventional Commit subject line) **before** `git commit`. After commit, the subject in git and in the Linear queue document must match character-for-character ([PR title rule](#pull-requests) for single-commit PRs). Do not record SHAs. The queue document is not part of the git changeset. diff --git a/okf-bundle/documentation-site-maintenance.md b/okf-bundle/documentation-site-maintenance.md index a638bdd833..52ee033729 100644 --- a/okf-bundle/documentation-site-maintenance.md +++ b/okf-bundle/documentation-site-maintenance.md @@ -68,9 +68,9 @@ Removed packages (e.g. Dynamic Links) have no TypeDoc module — fall back to `m - [ ] `yarn reference:api` succeeds - [ ] All `docs.json` redirect targets verified (200) - [ ] New legacy paths identified and redirected or explicitly deferred with rationale -- [ ] Docs checks (`yarn lint:markdown`, `yarn lint:spellcheck`, `yarn docs:tsc:check`, `yarn docs:member:check`, `yarn lint:docs-links`) when `docs/**` or docs tooling changed: [validation checklist § lint and formatting](testing/validation-checklist.md#lint-and-formatting) (docs row and [§ docs lint gotchas](testing/validation-checklist.md#docs-lint-gotchas); OKF-only diffs do not run those). **Missing `lint:docs-links` evidence when `docs/**` was touched is serious** ([change authoring § work types](testing/change-authoring-workflow.md#work-types)) +- [ ] Docs checks (`yarn lint:markdown`, `yarn lint:spellcheck`, `yarn docs:tsc:check`, `yarn docs:member:check`, `yarn lint:docs-links`) when `docs/**` or docs tooling changed: [validation checklist § lint and formatting](testing/validation/lint.md#lint-and-formatting) (docs row and [§ docs lint gotchas](testing/validation/docs-lint.md#docs-lint-gotchas); OKF-only diffs do not run those). **Missing `lint:docs-links` evidence when `docs/**` was touched is serious** ([change authoring § work types](testing/authoring/loop.md#work-types)) -**Validation commands:** [validation checklist § API reference](testing/validation-checklist.md#api-reference-and-type-parity), [§ lint and formatting](testing/validation-checklist.md#lint-and-formatting). +**Validation commands:** [validation checklist § API reference](testing/validation/compile-and-types.md#api-reference-and-type-parity), [§ lint and formatting](testing/validation/lint.md#lint-and-formatting). ## Docs.page link check (CI) @@ -82,14 +82,14 @@ Removed packages (e.g. Dynamic Links) have no TypeDoc module — fall back to `m **Host overrides:** `docs.json` `check.severityOverrideHosts` pins `rnfirebase.io` to **error**. Matching includes subdomains, so `reference.rnfirebase.io` is covered, and the override applies to every failure — bot-gate statuses included — so a rate-limited or broken TypeDoc link cannot downgrade to a warning. Do not add `warn` overrides for first-party hosts; add an `error` entry when another first-party host must never downgrade. -What agents must fix vs may leave: [validation checklist § docs.page link check](testing/validation-checklist.md#docs-page-link-check). +What agents must fix vs may leave: [validation checklist § docs.page link check](testing/validation/docs-lint.md#docs-page-link-check). ## docs.json edits (non-TypeDoc) When adding user docs pages only (sidebar, tabs, content under `docs/`): - Add sidebar entries in `docs.json` when new pages ship. -- Run markdown/spellcheck/link check per [validation checklist](testing/validation-checklist.md#lint-and-formatting): `yarn lint:markdown`, `yarn lint:spellcheck`, `yarn lint:docs-links`. +- Run markdown/spellcheck/link check per [validation checklist](testing/validation/lint.md#lint-and-formatting): `yarn lint:markdown`, `yarn lint:spellcheck`, `yarn lint:docs-links`. - Redirect audit **not** required unless `redirects` or TypeDoc config also changed. ## Colocated TypeDoc reminder diff --git a/okf-bundle/index.md b/okf-bundle/index.md index 09ed384137..5488978ef8 100644 --- a/okf-bundle/index.md +++ b/okf-bundle/index.md @@ -6,6 +6,11 @@ okf_version: '0.1' - [Documentation/commit policy](/documentation-policy.md#durable-vs-ephemeral) — public **reference** docs vs ephemeral queue state on Linear project documents vs private items (Linear issue identifiers stay off GitHub); [Efficiency](/documentation-policy.md#efficiency); OKF consistency - [Documentation site maintenance](/documentation-site-maintenance.md) — docs.json, TypeDoc reference site, legacy `/reference/` redirect audits, docs.page link check (CI) +- [Bundle structure](/CONTEXT.md) — layout, where a new fact goes, moving text without breaking `#anchors`, deliberate departures from ICM defaults + +# Routes by change type + +- [Change routes](/routes/index.md) — per change type (docs-only, tests-only, `lib/**`, native, e2e, Expo plugin / fixtures, OKF / `AGENTS.md`): work type, tier, files to load per step, exact commands, and what that diff does not need # CI workflows @@ -13,17 +18,18 @@ okf_version: '0.1' # Testing -- [Agent command policy](/testing/agent-command-policy.md) — allowlisted shell commands for agents (install, prepare, validation, e2e, Expo example typecheck + documented-path iOS **link** + per-module duplicate ObjC class check (`yarn test-expo-fixture:ios:dupes`), RN CLI prebuilt RNCore iOS **build**; not Detox) -- [Change authoring workflow](/testing/change-authoring-workflow.md) — verified product change loop (unit-focused → `documentation?` → area-focused `independent-review` → commit); [§ validation evidence (blocking)](testing/change-authoring-workflow.md#validation-evidence-blocking); [coverage evidence package](testing/coverage-design.md#coverage-evidence-package) +- [Testing index](/testing/index.md) — every testing file, grouped by commands, authoring, validation, e2e, coverage +- [Agent command policy](/testing/agent-command-policy.md) — allowlisted shell commands for agents (install, prepare, validation, e2e, Expo example typecheck + documented-path iOS **link** + per-module duplicate ObjC class check (`yarn test-expo-fixture:ios:dupes`), RN CLI prebuilt RNCore iOS **build**; not Detox); registry split by domain under `testing/commands/` +- [Change authoring workflow](/testing/change-authoring-workflow.md) — verified product change loop (unit-focused → `documentation?` → area-focused `independent-review` → commit); [§ validation evidence (blocking)](testing/authoring/gates.md#validation-evidence-blocking); [coverage evidence package](testing/code-coverage/policy.md#coverage-evidence-package) - [Iteration vocabulary](/testing/iteration-vocabulary.md) — work type, tier, and queue field identifiers -- [Running e2e tests](/testing/running-e2e.md) — canonical e2e commands, narrowing, environment, diagnosis; [§ test-app native modules](testing/running-e2e.md#test-app-native-modules); [§ slot lifecycle](testing/running-e2e.md#slot-lifecycle) +- [Running e2e tests](/testing/running-e2e.md) — canonical e2e commands, narrowing, environment, diagnosis; [§ test-app native modules](testing/e2e/rules.md#test-app-native-modules); [§ slot lifecycle](testing/e2e/environment.md#slot-lifecycle) - [E2e parallel design](/testing/e2e-parallel-design.md) — resources, why they collide, parameterization, 9 overlapping cells, coordinator rollout - [Test app dependency pins](/testing/test-app-dependency-pins.md) — intentional RN / CLI locks (mobile + Expo/RN CLI fixtures share one line; `react-native-macos` is independent) - [Validation checklist](/testing/validation-checklist.md) — compile, Jest, lint, `compare:types`, e2e, coverage - [Published types ADR](/testing/architecture-decisions.md) — attw scope, Expo plugin checks, discarded resolutions; [Types-AD-5](/testing/architecture-decisions.md#types-ad-5--pack-ignores-nested-ios-unit-build-trees--accepted) attw allowlisted pack stage - [Android unit testing ADR](/testing/android-architecture-decisions.md#androidtest-ad-1) — JUnit-first JVM unit tests; Robolectric when Android APIs are required; omit `@Config` / `sdk` unless proven (`AndroidTest-AD-1`) - [iOS unit testing ADR](/testing/ios-architecture-decisions.md#iostest-ad-1) — macOS/host-first in-package XCTest (Foundation-only, or [stub headers](/testing/ios-architecture-decisions.md#iostest-ad-1-stub-headers) for React/Firebase/UIKit); Simulator only if UIKit required (`IosTest-AD-1`) -- [Coverage design](/testing/coverage-design.md) — unit/e2e coverage policy, native gates, Codecov; [iOS Ruby SimpleCov](/testing/coverage-design.md#ios-ruby-simplecov); [§ react-native-coverage](/testing/coverage-design.md#react-native-coverage); [§ coverage migration rollback](/testing/coverage-design.md#coverage-migration-rollback); probe vs flush — [running e2e § test-app native modules](/testing/running-e2e.md#test-app-native-modules) +- [Coverage design](/testing/coverage-design.md) — unit/e2e coverage policy, native gates, Codecov; [iOS Ruby SimpleCov](/testing/code-coverage/local.md#ios-ruby-simplecov); [§ react-native-coverage](/testing/code-coverage/test-app-modules.md#react-native-coverage); [§ coverage migration rollback](/testing/code-coverage/migration-rollback.md#coverage-migration-rollback); probe vs flush — [running e2e § test-app native modules](/testing/e2e/rules.md#test-app-native-modules) - [Firebase testing project](/testing/firebase-testing-project.md) — cloud vs emulator, live FIS/RC, helper callables, rules/indexes, deploy # Cross-cutting work diff --git a/okf-bundle/monorepo-tooling/architecture-decisions.md b/okf-bundle/monorepo-tooling/architecture-decisions.md index 5f5b1351d1..d6700d138e 100644 --- a/okf-bundle/monorepo-tooling/architecture-decisions.md +++ b/okf-bundle/monorepo-tooling/architecture-decisions.md @@ -163,7 +163,7 @@ CI PR/main jobs may restore/save `.nx/cache` via `actions/cache` (keyed on `yarn **Direction:** provide a root **`dev:watch`** that uses `nx watch` to rebuild `dist/**` on `lib/**` change. For the e2e TDD loop, drive test rerun from a **Metro bundle-ready event** (HMR `update-done` / `onBundleBuilt`), not a fixed `sleep`. Because RNFB owns the Jet test runner and its HTTP control plane (port 8091), add a control action to re-run the loaded suite on that signal. -**Bundling premise:** per [running e2e § Rules #3](../testing/running-e2e.md#rules) (canonical owner). The `lib → dist → Metro → rerun` chain is therefore a valid inner loop for iOS/Android/macOS **debug**. +**Bundling premise:** per [running e2e § Rules #3](../testing/e2e/rules.md#rules) (canonical owner). The `lib → dist → Metro → rerun` chain is therefore a valid inner loop for iOS/Android/macOS **debug**. **Why (direction):** `nx watch` runs its callback sequentially after each rebuild, but that point is upstream of Metro re-bundling. The real "bundle is live in the app" signal is Metro's HMR `update-done` message (client-observable) or `onBundleBuilt` (server callback). Keying the rerun on that event makes the loop deterministic and `sleep`-free, and the **same** Metro-ready signal is the correct driver for a future Appium-based e2e rerun. @@ -218,7 +218,7 @@ Disable Nx caching for any workspace `prepare` target whose script is `patch-pac Root `"prepare": "patch-package"` runs only via Yarn lifecycle (`postinstallDev` → `yarn prepare`), **not** through `lerna run` / Nx, so it needs no Nx override. -**Why:** `patch-package` mutates `node_modules` after install/relink. [MonoTool-AD-11](#monotool-ad-11--scope-prepare-cache-inputs-with-a-jssource-namedinput--accepted) correctly scopes bob `prepare` inputs to `jsSource`, but the e2e apps have **no** `lib/**`, so their prepare input hash is effectively stable. Yarn then re-links unpatched packages, Nx reports a prepare **cache hit**, and `patch-package` never re-runs. On **macOS 0.78** that left `fmt.podspec` at **11.0.2** despite green root `yarn`. Mobile **0.86.2** ships fmt **12.1.0** upstream, but `tests/` still needs the same no-cache rule for its remaining patches. That breaks the agent [install / patch / fmt gate](../testing/agent-command-policy.md#install-patch-fmt-gate-blocking) when macOS patches are skipped. +**Why:** `patch-package` mutates `node_modules` after install/relink. [MonoTool-AD-11](#monotool-ad-11--scope-prepare-cache-inputs-with-a-jssource-namedinput--accepted) correctly scopes bob `prepare` inputs to `jsSource`, but the e2e apps have **no** `lib/**`, so their prepare input hash is effectively stable. Yarn then re-links unpatched packages, Nx reports a prepare **cache hit**, and `patch-package` never re-runs. On **macOS 0.78** that left `fmt.podspec` at **11.0.2** despite green root `yarn`. Mobile **0.86.2** ships fmt **12.1.0** upstream, but `tests/` still needs the same no-cache rule for its remaining patches. That breaks the agent [install / patch / fmt gate](../testing/commands/native-build-gate.md#install-patch-fmt-gate-blocking) when macOS patches are skipped. This aligns with AD-11's spirit: **inputs must match what prepare consumes**. For bob packages that is JS source → cache. For `patch-package`, the meaningful "input" is the freshly linked `node_modules` tree (not hashable as a stable cache key) → **do not cache**. diff --git a/okf-bundle/monorepo-tooling/index.md b/okf-bundle/monorepo-tooling/index.md index 4392bc8035..bb4b7463f9 100644 --- a/okf-bundle/monorepo-tooling/index.md +++ b/okf-bundle/monorepo-tooling/index.md @@ -19,7 +19,7 @@ Out of scope (explicitly rejected — see [ADR](architecture-decisions.md)): Tur ## Related repository files -- [`lerna.json`](../../../lerna.json) — versioning + publish config (includes `createRelease: github` per [MonoTool-AD-2](architecture-decisions.md#monotool-ad-2--keep-lerna-for-versioning-and-publish--accepted)) -- [`package.json`](../../../package.json) — root scripts, workspaces, `lerna:prepare` -- [`tsconfig.packages.base.json`](../../../tsconfig.packages.base.json) — shared package compiler options (17 of 19 packages extend it) -- [`.github/workflows/linting.yml`](../../../.github/workflows/linting.yml) — CI lint job (target for `lint:deps` + `.nx/cache`) +- [`lerna.json`](../../lerna.json) — versioning + publish config (includes `createRelease: github` per [MonoTool-AD-2](architecture-decisions.md#monotool-ad-2--keep-lerna-for-versioning-and-publish--accepted)) +- [`package.json`](../../package.json) — root scripts, workspaces, `lerna:prepare` +- [`tsconfig.packages.base.json`](../../tsconfig.packages.base.json) — shared package compiler options (17 of 19 packages extend it) +- [`.github/workflows/linting.yml`](../../.github/workflows/linting.yml) — CI lint job (target for `lint:deps` + `.nx/cache`) diff --git a/okf-bundle/monorepo-tooling/maintainer-publish.md b/okf-bundle/monorepo-tooling/maintainer-publish.md index df6f672082..85bb6958f2 100644 --- a/okf-bundle/monorepo-tooling/maintainer-publish.md +++ b/okf-bundle/monorepo-tooling/maintainer-publish.md @@ -39,4 +39,4 @@ Do not change the dist-tag, package set, or publish command for that recovery ru | ----- | -------- | | Decision (short) | [MonoTool-AD-2](architecture-decisions.md#monotool-ad-2--keep-lerna-for-versioning-and-publish--accepted) | | API reference site maintenance | [Documentation site maintenance](../documentation-site-maintenance.md) | -| Workflow | [`.github/workflows/publish.yml`](../../../.github/workflows/publish.yml) | +| Workflow | [`.github/workflows/publish.yml`](../../.github/workflows/publish.yml) | diff --git a/okf-bundle/monorepo-tooling/prepare-and-cache.md b/okf-bundle/monorepo-tooling/prepare-and-cache.md index 7eba7c36f4..c5f964f940 100644 --- a/okf-bundle/monorepo-tooling/prepare-and-cache.md +++ b/okf-bundle/monorepo-tooling/prepare-and-cache.md @@ -106,7 +106,7 @@ Add `nx.json`; keep the `yarn lerna:prepare` entrypoint name, with `NX_NO_CLOUD` Most packages' `prepare` is bob transpile (`lib/**` → `dist/**`) and is correctly cached under [MonoTool-AD-11](architecture-decisions.md#monotool-ad-11--scope-prepare-cache-inputs-with-a-jssource-namedinput--accepted). The **tests** and **tests-macos** workspaces are different: their `prepare` script is **`patch-package`**, which mutates that app's `node_modules/**`. -- **`tests/`** (mobile RN **0.88.0-rc.3**): still runs `patch-package` for non-fmt patches (e.g. `@firebase+rules-unit-testing`, [`detox+20.51.0.patch`](../../tests/patches/detox+20.51.0.patch) — [iOS slot simulators](../testing/running-e2e.md#ios-slot-simulators)). Mobile RN ships fmt **12.1.0** upstream; there is **no** `tests/patches/react-native+*.patch` fmt bump. +- **`tests/`** (mobile RN **0.88.0-rc.3**): still runs `patch-package` for non-fmt patches (e.g. `@firebase+rules-unit-testing`, [`detox+20.51.0.patch`](../../tests/patches/detox+20.51.0.patch) — [iOS slot simulators](../testing/e2e/slot-devices.md#ios-slot-simulators)). Mobile RN ships fmt **12.1.0** upstream; there is **no** `tests/patches/react-native+*.patch` fmt bump. - **`tests-macos/`** (RN **0.78.3** + `react-native-macos@0.78.6`): applies [`tests-macos/patches/react-native+0.78.3.patch`](../../tests-macos/patches/react-native+0.78.3.patch) (fmt **12.1.0**) and the macos patch. Those targets must set **`"cache": false`** on the project-level Nx `prepare` override. Reasons: @@ -115,7 +115,7 @@ Those targets must set **`"cache": false`** on the project-level Nx `prepare` ov 2. **Yarn re-link resets the mutation.** Root `yarn` re-links packages to unpatched content, then `lerna:prepare` runs. If Nx skips `tests:prepare` / `tests-macos:prepare`, patches are never re-applied. 3. **Adding `patches/**` to inputs is not enough.** After a re-link the patch files are unchanged → still a cache hit → still skipped. -Root `prepare` is also `patch-package`, but it runs via Yarn (`postinstallDev` → `yarn prepare`) outside Nx, so only the e2e app workspaces need the override. Agent verification of fmt after install remains mandatory: [install / patch / fmt gate](../testing/agent-command-policy.md#install-patch-fmt-gate-blocking). +Root `prepare` is also `patch-package`, but it runs via Yarn (`postinstallDev` → `yarn prepare`) outside Nx, so only the e2e app workspaces need the override. Agent verification of fmt after install remains mandatory: [install / patch / fmt gate](../testing/commands/native-build-gate.md#install-patch-fmt-gate-blocking). ### Generated-file outputs (cache correctness) @@ -160,7 +160,7 @@ Only `app` produces the native version files, so they go in an `app`-scoped targ Fixtures (`vertexai-sdk-test-data*`, gitignored) download only when AI Jest tests run. -**Jest wiring:** the root [`jest.config.js`](../../../jest.config.js) is a **single flat config** (one `testMatch`, no `projects`, no `globalSetup`). A bare `globalSetup` would therefore fetch AI mocks for **every** `yarn tests:jest` run (network on all suites) — re-introducing exactly the non-determinism AD-7 removes from `prepare`. Two acceptable shapes; **gate the fetch on AI-test detection** is the lighter option: +**Jest wiring:** the root [`jest.config.js`](../../jest.config.js) is a **single flat config** (one `testMatch`, no `projects`, no `globalSetup`). A bare `globalSetup` would therefore fetch AI mocks for **every** `yarn tests:jest` run (network on all suites) — re-introducing exactly the non-determinism AD-7 removes from `prepare`. Two acceptable shapes; **gate the fetch on AI-test detection** is the lighter option: - **Gate on AI-test detection (preferred):** a `globalSetup` that no-ops unless the current run includes `packages/ai/__tests__/**` (e.g. inspect the resolved test paths / `testPathPattern`), so non-AI runs pay nothing. No jest-config restructure. - **`projects` split:** convert `jest.config.js` to a `projects` array with a dedicated `ai` project carrying its own `globalSetup`. Cleaner isolation, larger change. @@ -206,13 +206,13 @@ bob's `typescript` (tsc) target emits `.d.ts` + `.d.ts.map` beside `dist/typescr - `doNotFollow` / `exclude` for `node_modules`, `packages/*/dist/**`, `packages/*/__tests__/**`, `packages/*/e2e/**` so the built output and tests are not analysed as source. - `options.tsConfig` + `enhancedResolveOptions` so the `@react-native-firebase/*` path aliases resolve; otherwise cross-package edges are silently unresolved and the MT4 allowlist has nothing to enforce. Verify one real cross-package edge is actually detected (not skipped as unresolvable). -**Agent/CI wiring** (commands and gates): [validation checklist § lint](../testing/validation-checklist.md#lint-and-formatting), [change authoring § validation evidence](../testing/change-authoring-workflow.md#validation-evidence-blocking). Optional non-CI `lint:deps-report` (HTML) for debugging. +**Agent/CI wiring** (commands and gates): [validation checklist § lint](../testing/validation/lint.md#lint-and-formatting), [change authoring § validation evidence](../testing/authoring/gates.md#validation-evidence-blocking). Optional non-CI `lint:deps-report` (HTML) for debugging. ## Developer watch and the e2e TDD hook chain — **deferred (gap-analysis pre-phase)** > **Deferred.** No incremental dev-watch / hot-reload loop exists today. The whole watch + event-driven-rerun design is deferred to a **gap-analysis pre-phase** ([work-queue MT-WATCH](work-queue.md#mt-watch--dev-watch--e2e-rerun-gap-analysis-pre-phase--deferred)) that produces detailed, verified analysis before any implementation. The prepare/cache/graph/declaration-map/lint work below and above does **not** depend on it. The command sketches here are **inputs to that analysis, not accepted commands** — they carry known defects called out inline. -**Bundling premise:** per [running e2e § Rules #3](../testing/running-e2e.md#rules) (canonical owner). The inner loop is therefore `lib` edit → `dist` rebuild → Metro re-bundle → test rerun ([MonoTool-AD-9](architecture-decisions.md#monotool-ad-9--dev-watch-rebuilds-prepare-e2e-tdd-rerun-is-event-driven-off-metro--deferred)). +**Bundling premise:** per [running e2e § Rules #3](../testing/e2e/rules.md#rules) (canonical owner). The inner loop is therefore `lib` edit → `dist` rebuild → Metro re-bundle → test rerun ([MonoTool-AD-9](architecture-decisions.md#monotool-ad-9--dev-watch-rebuilds-prepare-e2e-tdd-rerun-is-event-driven-off-metro--deferred)). ### Tier A — prepare watch + unit TDD (sketch, to be validated) @@ -238,7 +238,7 @@ The post-nx-rebuild point is **upstream** of Metro finishing its bundle, so do n | `onBundleBuilt` callback | Metro `createConnectMiddleware` | Server-side "bundle finished" | | App-side reload hook | RNFB owns Jet; the in-app client can emit "reloaded" | In-process, precise | -Chain: `lib` edit → `nx watch` rebuilds `dist` → Metro re-bundles → **`update-done`** → host `POST`s a re-run action to the Jet control plane (HTTP on `JET_REMOTE_PORT + 1`, default **8091**; see [running e2e § test-runner orchestration](../testing/running-e2e.md#test-runner-host-orchestration-log-triage-only)) → Jet re-executes the loaded (narrowed) mocha suite in-app. +Chain: `lib` edit → `nx watch` rebuilds `dist` → Metro re-bundles → **`update-done`** → host `POST`s a re-run action to the Jet control plane (HTTP on `JET_REMOTE_PORT + 1`, default **8091**; see [running e2e § test-runner orchestration](../testing/e2e/run-loop.md#test-runner-host-orchestration-log-triage-only)) → Jet re-executes the loaded (narrowed) mocha suite in-app. RNFB owns Jet, so a `POST /rerun` control action is feasible alongside the existing `/launch-ready` / `/orchestrate-state` endpoints. Native/codegen/spec changes still require `:build`; fast-rerun may need to bypass the coverage-teardown handshake. The **same** Metro bundle-ready signal is the correct driver for a future Appium-based e2e rerun — Appium drives UI, not bundling, so Metro remains the shared "bundle ready" source regardless of runner. diff --git a/okf-bundle/new-architecture/architecture-decisions.md b/okf-bundle/new-architecture/architecture-decisions.md index f97befe962..60c5b8c66e 100644 --- a/okf-bundle/new-architecture/architecture-decisions.md +++ b/okf-bundle/new-architecture/architecture-decisions.md @@ -40,7 +40,7 @@ Codegen spec/module names use the `NativeRNFBTurbo*` prefix (`NativeRNFBTurboAut **Why:** Disambiguates from legacy `RNFB*` module names during transition; satisfies Codegen's `Native*` spec-file requirement. -**Web / macOS registration:** [`nativeModuleWeb.ts`](../../../packages/app/lib/internal/nativeModuleWeb.ts) registers JS-SDK shims by module name in the **registry object initializer** (not deferred to bottom-of-file calls) so `NativeRNFBTurbo*` keys exist before `RNFBNativeEventEmitter` instantiates during circular imports. When `APP_NATIVE_MODULE` changes, register **both** the legacy `RNFBAppModule` key and the turbo name. Missing that registration surfaces as a macOS blank window / `Native module NativeRNFBTurboApp is not registered`. +**Web / macOS registration:** [`nativeModuleWeb.ts`](../../packages/app/lib/internal/nativeModuleWeb.ts) registers JS-SDK shims by module name in the **registry object initializer** (not deferred to bottom-of-file calls) so `NativeRNFBTurbo*` keys exist before `RNFBNativeEventEmitter` instantiates during circular imports. When `APP_NATIVE_MODULE` changes, register **both** the legacy `RNFBAppModule` key and the turbo name. Missing that registration surfaces as a macOS blank window / `Native module NativeRNFBTurboApp is not registered`. --- @@ -65,7 +65,7 @@ Keep the legacy event path (`RNFBNativeEventEmitter` → app-module proxy → `R | Assertion | Primary source | |-----------|----------------| | Native emit sites do not use the messaging module bridge | iOS categories/delegates (`RNFBMessaging+AppDelegate.m`, `+UNUserNotificationCenter.m`, `+FIRMessagingDelegate.m`) call `RNFBRCTEventEmitter`; Android receiver/service/module call `ReactNativeFirebaseEventEmitter` | -| JS subscribes via the app-module proxy, not the messaging shell | `packages/messaging/lib/index.ts` — `nativeEvents` array → `RNFBNativeEventEmitter` → `NativeRNFBTurboApp` ([NewArch-AD-18 E1](architecture-decisions.md#newarch-ad-18--raw-vs-wrapped-resolver-policy--accepted)) | +| JS subscribes via the app-module proxy, not the messaging shell | `packages/messaging/lib/index.ts` — `nativeEvents` array → `RNFBNativeEventEmitter` → `NativeRNFBTurboApp` ([NewArch-AD-18 E1](#newarch-ad-18--raw-vs-wrapped-resolver-policy--accepted)) | | Android background (quit/killed) is outside the event-proxy path | `ReactNativeFirebaseMessagingHeadlessService` (`HeadlessJsTaskService`); `AppRegistry.registerHeadlessTask('ReactNativeFirebaseMessagingHeadlessTask', …)` in `packages/messaging/lib/index.ts` | | iOS background data messages couple shell method + event proxy | `RNFBMessaging+AppDelegate.m` — `signalBackgroundMessageHandlerSet` on shell, then `RNFBRCTEventEmitter` for `messaging_message_received_background` | | iOS emitter implementation is legacy bridge API (Phase C debt) | `packages/app/ios/RNFBApp/RNFBRCTEventEmitter.m` — `bridge enqueueJSCall:@"RCTDeviceEventEmitter"` | @@ -82,7 +82,7 @@ The deferral discriminator is **not** satisfied by structure alone: nothing in t **Library packages only:** `includesGeneratedCode: true`; commit Codegen output under `packages/*/android/.../generated` and `packages/*/ios/generated`, mirroring `packages/functions`. CLI `--source library`. -**Test app is not that contract.** `tests/package.json` must **not** set `includesGeneratedCode: true` — that makes CLI `--outputPath` the *final* dir and writes `tests/ios/ReactCodegen` / `tests/ios/Package.swift` while CocoaPods wants `tests/ios/build/generated/ios/ReactCodegen`. Test-app Codegen output is **build-time, not committed**. [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) `testing` entry: `--source app`; CLI `--outputPath` is the RN app *base* (`ios` / `.`) because app codegen appends `build/generated/ios` and `android/app/build/generated/source/codegen`. Wipe those derived dirs **and** scrub/gitignore dumps at `tests/ios/Package.swift`, `tests/ios/ReactCodegen/`, `tests/ios/ReactAppDependencyProvider/`. Do not flatten test-app iOS output (keep nested `ReactCodegen`). Skip `scrubAppOnlyIosArtifacts`. That entry does **not** change library codegen. +**Test app is not that contract.** `tests/package.json` must **not** set `includesGeneratedCode: true` — that makes CLI `--outputPath` the *final* dir and writes `tests/ios/ReactCodegen` / `tests/ios/Package.swift` while CocoaPods wants `tests/ios/build/generated/ios/ReactCodegen`. Test-app Codegen output is **build-time, not committed**. [`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) `testing` entry: `--source app`; CLI `--outputPath` is the RN app *base* (`ios` / `.`) because app codegen appends `build/generated/ios` and `android/app/build/generated/source/codegen`. Wipe those derived dirs **and** scrub/gitignore dumps at `tests/ios/Package.swift`, `tests/ios/ReactCodegen/`, `tests/ios/ReactAppDependencyProvider/`. Do not flatten test-app iOS output (keep nested `ReactCodegen`). Skip `scrubAppOnlyIosArtifacts`. That entry does **not** change library codegen. **Guard (NewArch-AD-17.3):** CI runs `yarn codegen:verify` — wipe-then-regen ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)) then `git diff --exit-code` on the **library generated trees named above**. Test-app generated trees are not in that check. @@ -108,7 +108,7 @@ Each package has **one** `codegenConfig` whose `name` is an **aggregate library **Gate:** every spec name appears as a `modulesProvider` key (iOS) and is registered in the package class (Android); `codegenConfig.name` matches `RNFBTurboModules`. -Reference: [`packages/app/package.json`](../../../packages/app/package.json) `codegenConfig`. +Reference: [`packages/app/package.json`](../../packages/app/package.json) `codegenConfig`. --- @@ -118,7 +118,7 @@ When wrapping or extending a native module, enumerate methods with **`for...in`* **Why:** TurboModules expose methods lazily on the **prototype**, which are non-own; `Object.keys`/spread see nothing and produce `XYZ is not a function`. Codegen methods **are** enumerable via `for...in` (confirmed), so `for...in` + `Object.create` both finds them and preserves the prototype. Reference: [RN enable-libraries § "XYZ is not a function"](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/enable-libraries.md#javascript-xyz--is-not-a-function-it-is-undefined), [facebook/react-native#43221](https://github.com/facebook/react-native/issues/43221). -Code: [`registry/nativeModule.ts`](../../../packages/app/lib/internal/registry/nativeModule.ts), [`nativeModuleAndroidIos.ts`](../../../packages/app/lib/internal/nativeModuleAndroidIos.ts). +Code: [`registry/nativeModule.ts`](../../packages/app/lib/internal/registry/nativeModule.ts), [`nativeModuleAndroidIos.ts`](../../packages/app/lib/internal/nativeModuleAndroidIos.ts). --- @@ -156,7 +156,7 @@ Multiple specs/modules in one package are **merged flat** into a single resolved ## NewArch-AD-12 — One commit per package — **Accepted** -Convert a whole package (all its legacy modules → all its specs) in one [change authoring](../testing/change-authoring-workflow.md#primary-loop) loop (`documentation?` before frozen `independent-review`); land it as one `feat()!: migrate to TurboModules` (breaking: New Architecture required). Multiple specs ≠ multiple commits — they share `codegenConfig`, generated artifacts, podspec/gradle guards, and JS wiring that only build and pass e2e together. +Convert a whole package (all its legacy modules → all its specs) in one [change authoring](../testing/authoring/loop.md#primary-loop) loop (`documentation?` before frozen `independent-review`); land it as one `feat()!: migrate to TurboModules` (breaking: New Architecture required). Multiple specs ≠ multiple commits — they share `codegenConfig`, generated artifacts, podspec/gradle guards, and JS wiring that only build and pass e2e together. --- @@ -245,7 +245,7 @@ Jest-level tests, reused across packages: ### NewArch-AD-17.1 — Jest TurboModule contract test — **Accepted** -**Canonical file:** [`packages/app/__tests__/nativeModuleContract.test.ts`](../../../packages/app/__tests__/nativeModuleContract.test.ts) +**Canonical file:** [`packages/app/__tests__/nativeModuleContract.test.ts`](../../packages/app/__tests__/nativeModuleContract.test.ts) **Describe block (grep anchor):** `TurboModule wrapper contract (NewArch-AD-17.1)` @@ -265,14 +265,14 @@ yarn tests:jest -- packages/app/__tests__/nativeModuleContract.test.ts | Single-host wrapper | Every spec method callable via `getNativeModule()` | | 2-host merge (NewArch-AD-14a) | Routing composite Proxy dispatches to the correct host per method name | -**When required:** any change to [`nativeModule.ts`](../../../packages/app/lib/internal/registry/nativeModule.ts), `withTurboConstants`, or TurboModule wrapper behavior — re-run the scoped command above before closing `implementation_gate` or `review_gate`. +**When required:** any change to [`nativeModule.ts`](../../packages/app/lib/internal/registry/nativeModule.ts), `withTurboConstants`, or TurboModule wrapper behavior — re-run the scoped command above before closing `implementation_gate` or `review_gate`. 2. **Spec↔native parity** — **Accepted.** Assert each package's spec method-name set equals the union of Android `@ReactMethod` (generated Java spec) and iOS TurboModule protocol methods (generated ObjC spec header), and (NewArch-AD-11) the union across a package's specs has no duplicate names. ### NewArch-AD-17.2 — Spec↔native parity test — **Accepted** -**Canonical file:** [`packages/app/__tests__/turboModuleSpecNativeParity.test.ts`](../../../packages/app/__tests__/turboModuleSpecNativeParity.test.ts) +**Canonical file:** [`packages/app/__tests__/turboModuleSpecNativeParity.test.ts`](../../packages/app/__tests__/turboModuleSpecNativeParity.test.ts) **Describe block (grep anchor):** `Spec↔native parity (NewArch-AD-17.2)` @@ -282,9 +282,9 @@ yarn tests:jest -- packages/app/__tests__/nativeModuleContract.test.ts yarn tests:jest -- packages/app/__tests__/turboModuleSpecNativeParity.test.ts ``` -**Helper:** [`specNativeParityHelper.ts`](../../../packages/app/__tests__/specNativeParityHelper.ts) — parses TS spec interfaces, Android generated `*Spec.java` `@ReactMethod` names, and iOS generated `@protocol NativeRNFBTurbo*Spec` method names. +**Helper:** [`specNativeParityHelper.ts`](../../packages/app/__tests__/specNativeParityHelper.ts) — parses TS spec interfaces, Android generated `*Spec.java` `@ReactMethod` names, and iOS generated `@protocol NativeRNFBTurbo*Spec` method names. -3. **Codegen-up-to-date CI** — **Accepted.** Root `yarn codegen:verify` runs [`scripts/codegen-verify.mjs`](../../../scripts/codegen-verify.mjs) (wipe-then-regen via [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) `--all`, including the test-app `testing` entry) then `git diff --exit-code` on the **library generated trees** ([NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted)). Test-app output is not committed and is not part of that diff. Wired in the CI lint job ([`.github/workflows/linting.yml`](../../../.github/workflows/linting.yml)). +3. **Codegen-up-to-date CI** — **Accepted.** Root `yarn codegen:verify` runs [`scripts/codegen-verify.mjs`](../../scripts/codegen-verify.mjs) (wipe-then-regen via [`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) `--all`, including the test-app `testing` entry) then `git diff --exit-code` on the **library generated trees** ([NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted)). Test-app output is not committed and is not part of that diff. Wired in the CI lint job ([`.github/workflows/linting.yml`](../../.github/workflows/linting.yml)). @@ -296,7 +296,7 @@ yarn tests:jest -- packages/app/__tests__/turboModuleSpecNativeParity.test.ts **Git check:** library generated trees only — [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted) (globs owned there; do not restate). -**Wipe-then-regen:** [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) (invoked by package `android:codegen` / `ios:codegen` and by [`scripts/codegen-verify.mjs`](../../../scripts/codegen-verify.mjs)) must **delete each package's configured `--outputPath`** before CLI codegen writes ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)). ResultT inject is retired on the current mobile pin ([NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--accepted) superseded). +**Wipe-then-regen:** [`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) (invoked by package `android:codegen` / `ios:codegen` and by [`scripts/codegen-verify.mjs`](../../scripts/codegen-verify.mjs)) must **delete each package's configured `--outputPath`** before CLI codegen writes ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)). ResultT inject is retired on the current mobile pin ([NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete) superseded). **Why:** The current Jest mocks are plain enumerable objects and structurally cannot reproduce the enumeration bug that already cost an iteration; these tests close that blind spot and make iterations faster and higher quality. @@ -319,16 +319,16 @@ Two resolution surfaces exist and must be used deliberately: | # | Call site | Module name | Category | Why raw (policy) | Action | |---|-----------|---------------|----------|------------------|--------| -| E1 | [`RNFBNativeEventEmitter.ts`](../../../packages/app/lib/internal/RNFBNativeEventEmitter.ts) (constructor, `addListener`, `removeAllListeners`, `removeSubscription`) | `NativeRNFBTurboApp` | **Permanent** | React Native's `NativeEventEmitter` must receive the **same raw host object** that implements `addListener` / `removeListeners` on the native side. Wrapping would break event subscription identity and the RN event-bridge contract. A typed Codegen event path is a future cutover, not a reason to wrap this site. | Keep raw; turbo name. | -| E2 | [`nativeModule.ts`](../../../packages/app/lib/internal/registry/nativeModule.ts) `initialiseNativeModule` / `getAppModule` bootstrap | any | **Infrastructure** | The wrapper factory itself must read the bare host to build the [NewArch-AD-14](#newarch-ad-14--native-module-wrapper-memoizing-lazy-proxy--accepted) Proxy/composite. Not a product bypass. | N/A | -| E3 | [`nativeModuleAndroidIos.ts`](../../../packages/app/lib/internal/nativeModuleAndroidIos.ts) unified resolver | any | **Infrastructure** | Defines `getReactNativeModule`; applies `withTurboConstants` before returning. Not a product bypass. | N/A | -| E4 | [`tests/globals.js`](../../../tests/globals.js) `NativeModules` proxy getter | `RNF*` / `NativeRNFBTurbo*` | **Infrastructure** | E2e harness routes RNFB module names through the real unified resolver so specs that read `NativeModules.NativeRNFBTurboApp` (e.g. [`events.e2e.js`](../../../packages/app/e2e/events.e2e.js)) get a live module, not a stub. Durable product wiring — not harness narrowing. | Keep; part of Phase 0. | -| E5 | [`UtilsStatics.ts`](../../../packages/app/lib/utils/UtilsStatics.ts) `FilePath` getter | `NativeRNFBTurboUtils` | **Phase 0 fix** | Reads path **constants** synchronously from the utils host without a `FirebaseModule` instance (static getter on `Utils.Statics`). Raw was acceptable pre-turbo; under [NewArch-AD-15](#newarch-ad-15--constant-memoization-scope-static-only--accepted) migrate to a dedicated wrapped utils accessor (or memoized static read via resolver) so constants are not rebuilt per access. Turbo name is already correct. | Fix in Phase 0 re-implementation. | -| E6 | [`messaging/lib/index.ts`](../../../packages/messaging/lib/index.ts) `isSupported()` | ~~`RNFBUtilsModule`~~ → `NativeRNFBTurboUtils` | **Phase 0 fix (bug)** | Cross-package read of Play Services availability. Was using **legacy module name** (returns `undefined` under turbo-only) and a **dynamic constant** (`androidPlayServices`) that can go stale. Must use turbo name + **dynamic method** `androidGetPlayServicesStatus()` per [NewArch-AD-15](#newarch-ad-15--constant-memoization-scope-static-only--accepted). | **Must-fix** in Phase 0. | -| E7 | [`app/lib/modular.ts`](../../../packages/app/lib/modular.ts) `metaGetAll`, `jsonGetAll`, `preferences*` | `NativeRNFBTurboApp` | **Not an exception — migrate** | No policy reason for raw; these are app-module method calls with no arg-prepend skip. Should use **`getAppModule()`** (wrapped) for error mapping consistency. Listed here so gap-analysis catches them. | Migrate to `getAppModule()` in Phase 0. | -| E8 | [`FirestoreStatics.ts`](../../../packages/firestore/lib/FirestoreStatics.ts) `setLogLevel` | `NativeRNFBTurboFirestore` | **Phase 1 fix** | Cross-package static helper bypasses `FirebaseModule`/`getNativeModule`. Uses turbo main host via [`getStaticFirestoreMainModule()`](../../../packages/firestore/lib/internal/staticNativeModule.ts) (NewArch-AD-18 E8). Raw access retained — no wrapped surface for static helpers. | Done — firestore Phase 1. | -| E9 | [`DatabaseSyncTree.ts`](../../../packages/database/lib/DatabaseSyncTree.ts) `native` getter | `RNFBDatabaseQueryModule` | **Deferred — Phase 4** | Internal sync listener tree calls query module directly for low-latency sync ops, bypassing the merged multi-module surface. Acceptable until database migrates; then turbo name + evaluate whether wrapped merge surface suffices. | Fix when `database` migrates. | -| E10 | [`phone-number-verification/lib/index.ts`](../../../packages/phone-number-verification/lib/index.ts) `getNativeModule()` | `RNFBPnvModule` / `NativeRNFBTurboPnv` | **Permanent (direct resolver)** | Package bypasses `createModuleNamespace` by design. Direct resolver is intentional; use the turbo name. | Keep direct; turbo name. | +| E1 | [`RNFBNativeEventEmitter.ts`](../../packages/app/lib/internal/RNFBNativeEventEmitter.ts) (constructor, `addListener`, `removeAllListeners`, `removeSubscription`) | `NativeRNFBTurboApp` | **Permanent** | React Native's `NativeEventEmitter` must receive the **same raw host object** that implements `addListener` / `removeListeners` on the native side. Wrapping would break event subscription identity and the RN event-bridge contract. A typed Codegen event path is a future cutover, not a reason to wrap this site. | Keep raw; turbo name. | +| E2 | [`nativeModule.ts`](../../packages/app/lib/internal/registry/nativeModule.ts) `initialiseNativeModule` / `getAppModule` bootstrap | any | **Infrastructure** | The wrapper factory itself must read the bare host to build the [NewArch-AD-14](#newarch-ad-14--native-module-wrapper-memoizing-lazy-proxy--accepted) Proxy/composite. Not a product bypass. | N/A | +| E3 | [`nativeModuleAndroidIos.ts`](../../packages/app/lib/internal/nativeModuleAndroidIos.ts) unified resolver | any | **Infrastructure** | Defines `getReactNativeModule`; applies `withTurboConstants` before returning. Not a product bypass. | N/A | +| E4 | [`tests/globals.js`](../../tests/globals.js) `NativeModules` proxy getter | `RNF*` / `NativeRNFBTurbo*` | **Infrastructure** | E2e harness routes RNFB module names through the real unified resolver so specs that read `NativeModules.NativeRNFBTurboApp` (e.g. [`events.e2e.js`](../../packages/app/e2e/events.e2e.js)) get a live module, not a stub. Durable product wiring — not harness narrowing. | Keep; part of Phase 0. | +| E5 | [`UtilsStatics.ts`](../../packages/app/lib/utils/UtilsStatics.ts) `FilePath` getter | `NativeRNFBTurboUtils` | **Phase 0 fix** | Reads path **constants** synchronously from the utils host without a `FirebaseModule` instance (static getter on `Utils.Statics`). Raw was acceptable pre-turbo; under [NewArch-AD-15](#newarch-ad-15--constant-memoization-scope-static-only--accepted) migrate to a dedicated wrapped utils accessor (or memoized static read via resolver) so constants are not rebuilt per access. Turbo name is already correct. | Fix in Phase 0 re-implementation. | +| E6 | [`messaging/lib/index.ts`](../../packages/messaging/lib/index.ts) `isSupported()` | ~~`RNFBUtilsModule`~~ → `NativeRNFBTurboUtils` | **Phase 0 fix (bug)** | Cross-package read of Play Services availability. Was using **legacy module name** (returns `undefined` under turbo-only) and a **dynamic constant** (`androidPlayServices`) that can go stale. Must use turbo name + **dynamic method** `androidGetPlayServicesStatus()` per [NewArch-AD-15](#newarch-ad-15--constant-memoization-scope-static-only--accepted). | **Must-fix** in Phase 0. | +| E7 | [`app/lib/modular.ts`](../../packages/app/lib/modular.ts) `metaGetAll`, `jsonGetAll`, `preferences*` | `NativeRNFBTurboApp` | **Not an exception — migrate** | No policy reason for raw; these are app-module method calls with no arg-prepend skip. Should use **`getAppModule()`** (wrapped) for error mapping consistency. Listed here so gap-analysis catches them. | Migrate to `getAppModule()` in Phase 0. | +| E8 | [`FirestoreStatics.ts`](../../packages/firestore/lib/FirestoreStatics.ts) `setLogLevel` | `NativeRNFBTurboFirestore` | **Phase 1 fix** | Cross-package static helper bypasses `FirebaseModule`/`getNativeModule`. Uses turbo main host via [`getStaticFirestoreMainModule()`](../../packages/firestore/lib/internal/staticNativeModule.ts) (NewArch-AD-18 E8). Raw access retained — no wrapped surface for static helpers. | Done — firestore Phase 1. | +| E9 | [`DatabaseSyncTree.ts`](../../packages/database/lib/DatabaseSyncTree.ts) `native` getter | `RNFBDatabaseQueryModule` | **Deferred — Phase 4** | Internal sync listener tree calls query module directly for low-latency sync ops, bypassing the merged multi-module surface. Acceptable until database migrates; then turbo name + evaluate whether wrapped merge surface suffices. | Fix when `database` migrates. | +| E10 | [`phone-number-verification/lib/index.ts`](../../packages/phone-number-verification/lib/index.ts) `getNativeModule()` | `RNFBPnvModule` / `NativeRNFBTurboPnv` | **Permanent (direct resolver)** | Package bypasses `createModuleNamespace` by design. Direct resolver is intentional; use the turbo name. | Keep direct; turbo name. | **Adding a new exception:** gap-analysis must justify why wrapping breaks (not merely "it's convenient"). Update this table and add a one-line `// NewArch-AD-18 E: ` comment at the call site. @@ -362,7 +362,7 @@ Committed generated native artifacts ([NewArch-AD-5](#newarch-ad-5--commit-gener **Context (historical):** Consumer apps on RN **0.84+** require `using ResultT = Constants;` inside each codegen `Constants::Builder` ([RN #54919](https://github.com/facebook/react-native/pull/54919)). While the mobile test app was pinned to **0.78**, committed iOS headers omitted the alias, so an interim inject script patched headers after each 0.78 codegen pass. -**Exit (CPRN-236 / NewArch-AD-20 mobile bump):** The mobile app is on **RN 0.86.2**. Upstream `@react-native/codegen@0.86.2` emits `using ResultT = …` natively. The inject script (`scripts/patch-ios-codegen-resultt.mjs`) and its `codegen:verify` hook are **removed**. Regenerate with `yarn codegen:all` ([`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) from `tests/`). +**Exit (CPRN-236 / NewArch-AD-20 mobile bump):** The mobile app is on **RN 0.86.2**. Upstream `@react-native/codegen@0.86.2` emits `using ResultT = …` natively. The inject script (`scripts/patch-ios-codegen-resultt.mjs`) and its `codegen:verify` hook are **removed**. Regenerate with `yarn codegen:all` ([`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) from `tests/`). **Do not reintroduce** the inject on the current mobile pin. macOS remains on 0.78 for the shell only and does not own codegen artifacts. @@ -372,9 +372,9 @@ Committed generated native artifacts ([NewArch-AD-5](#newarch-ad-5--commit-gener **Decision:** Before every Codegen write to a package's configured `--outputPath`, **delete that directory entirely**, then run CLI codegen. Applies to: -- [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) (mobile toolchain from `tests/`; used by each package's `android:codegen` / `ios:codegen` and by [`scripts/codegen-verify.mjs`](../../../scripts/codegen-verify.mjs)) +- [`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) (mobile toolchain from `tests/`; used by each package's `android:codegen` / `ios:codegen` and by [`scripts/codegen-verify.mjs`](../../scripts/codegen-verify.mjs)) -ResultT inject ([NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--accepted)) is **retired** on the current mobile pin (0.86 emits `ResultT` natively). Do not reintroduce `patch-ios-codegen-resultt.mjs` after wipe+regen. +ResultT inject ([NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete)) is **retired** on the current mobile pin (0.86 emits `ResultT` natively). Do not reintroduce `patch-ios-codegen-resultt.mjs` after wipe+regen. **Why:** React Native Codegen does not reliably remove obsolete generated files when specs, `codegenConfig.name`, or templates change. Incremental overwrite leaves orphan classes / wrong library trees under the same `outputPath`, which break Android (`duplicate class`) or leave stale committed artifacts that [NewArch-AD-17.3](#newarch-ad-173--codegen-verify-ci--accepted) would not catch without a wipe. Wipe-then-regen makes the committed tree match a clean emit ([NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted)). @@ -385,7 +385,7 @@ ResultT inject ([NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-withou - Wipe removes orphans **on the same path**. A **sibling** wrong tree from a prior bad `outputPath` (e.g. `src/main/java/.../generated` vs `src/reactnative/java/.../generated`) still needs a one-time manual delete. Keep **one** canonical tree; align shell imports, `build.gradle` `sourceSets`, and `cmakeListsPath`. - After a `codegenConfig.name` rename ([NewArch-AD-7](#newarch-ad-7--codegenconfigname--aggregate-library-name-one-codegenconfig-per-package--accepted)), wipe clears the old library under `outputPath`; update `cmakeListsPath` / imports only when those paths embed the old name. -**Related:** [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted), [NewArch-AD-7](#newarch-ad-7--codegenconfigname--aggregate-library-name-one-codegenconfig-per-package--accepted), [NewArch-AD-17.3](#newarch-ad-173--codegen-verify-ci--accepted), [NewArch-AD-20](#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted), [NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--accepted). +**Related:** [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted), [NewArch-AD-7](#newarch-ad-7--codegenconfigname--aggregate-library-name-one-codegenconfig-per-package--accepted), [NewArch-AD-17.3](#newarch-ad-173--codegen-verify-ci--accepted), [NewArch-AD-20](#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted), [NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete). --- @@ -411,13 +411,13 @@ ResultT inject ([NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-withou **Context:** React Native **0.89+** deprecates the `JavaTurboModule::invokeJavaMethod` overload that takes a cached `jmethodID` ([facebook/react-native#59619](https://github.com/facebook/react-native/pull/59619)). RNFB still commits library JNI under each package's `generated/jni/` for TurboModules ([NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted)). Stock codegen continues to emit the legacy call shape so builds keep working on React Native versions **before** 0.89. On 0.89+, `target_compile_reactnative_options` turns deprecation warnings into errors (`-Werror`), breaking all library codegen CMake targets. -**Decision:** After each successful **library** Android wipe-then-regen ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)), [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) post-processes `jni/CMakeLists.txt` to append `target_compile_options( PRIVATE -Wno-error=deprecated-declarations)` with a stable `# RNFB:` marker comment. Scope: **16** library packages (not `testing` app codegen). Idempotent on re-run. +**Decision:** After each successful **library** Android wipe-then-regen ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)), [`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) post-processes `jni/CMakeLists.txt` to append `target_compile_options( PRIVATE -Wno-error=deprecated-declarations)` with a stable `# RNFB:` marker comment. Scope: **16** library packages (not `testing` app codegen). Idempotent on re-run. **Why not regenerate call sites now:** The replacement `invokeJavaMethod` overload exists only from RN **0.89**; rewriting committed `.cpp` output would break the documented compatibility window for older React Native lines still supported alongside the mobile test app pin. **Exit criterion:** When RNFB's minimum supported React Native is **≥ 0.89**, run `yarn codegen:all` with a 0.89+ toolchain so upstream templates emit the new overload, commit regenerated JNI, and **remove** this CMake post-process (delete `patchAndroidJniDeprecationCMake` and the marker block from committed `CMakeLists.txt` files). -**Related:** [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted), [NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted), [agent-command-policy § TurboModule codegen](../testing/agent-command-policy.md#turbomodule-codegen). +**Related:** [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted), [NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted), [agent-command-policy § TurboModule codegen](../testing/commands/native.md#turbomodule-codegen). --- @@ -427,5 +427,5 @@ ResultT inject ([NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-withou |-------|----------| | Index | [index.md](index.md) | | Change loop, gates, tiers | [change-authoring-workflow.md](../testing/change-authoring-workflow.md) | -| E2e / codegen commands | [running-e2e.md](../testing/running-e2e.md); [agent command policy § TurboModule codegen](../testing/agent-command-policy.md#turbomodule-codegen) | +| E2e / codegen commands | [running-e2e.md](../testing/running-e2e.md); [agent command policy § TurboModule codegen](../testing/commands/native.md#turbomodule-codegen) | | Doc/commit policy | [documentation-policy.md](../documentation-policy.md) | diff --git a/okf-bundle/new-architecture/index.md b/okf-bundle/new-architecture/index.md index 779bc77886..9ce6af74d6 100644 --- a/okf-bundle/new-architecture/index.md +++ b/okf-bundle/new-architecture/index.md @@ -10,12 +10,12 @@ Durable architectural decisions for React Native Firebase TurboModules. Product ## Reference implementation -* [`packages/functions`](../../../packages/functions/) — first TurboModule package ([PR #8603](https://github.com/invertase/react-native-firebase/pull/8603); new-arch-only from v24) -* [`packages/app`](../../../packages/app/) — first multi-spec package (`NativeRNFBTurboApp` + `NativeRNFBTurboUtils`) +* [`packages/functions`](../../packages/functions) — first TurboModule package ([PR #8603](https://github.com/invertase/react-native-firebase/pull/8603); new-arch-only from v24) +* [`packages/app`](../../packages/app) — first multi-spec package (`NativeRNFBTurboApp` + `NativeRNFBTurboUtils`) ## Related repository files -* [`packages/app/lib/internal/registry/nativeModule.ts`](../../../packages/app/lib/internal/registry/nativeModule.ts) — `turboModule` flag, null encoding, module wrapping -* [`packages/app/lib/internal/nullSerialization.ts`](../../../packages/app/lib/internal/nullSerialization.ts) — iOS null sentinel for TurboModule object args -* [`packages/functions/specs/NativeRNFBTurboFunctions.ts`](../../../packages/functions/specs/NativeRNFBTurboFunctions.ts) — Codegen spec pattern -* [`packages/functions/package.json`](../../../packages/functions/package.json) — `codegenConfig`, committed generated output +* [`packages/app/lib/internal/registry/nativeModule.ts`](../../packages/app/lib/internal/registry/nativeModule.ts) — `turboModule` flag, null encoding, module wrapping +* [`packages/app/lib/internal/nullSerialization.ts`](../../packages/app/lib/internal/nullSerialization.ts) — iOS null sentinel for TurboModule object args +* [`packages/functions/specs/NativeRNFBTurboFunctions.ts`](../../packages/functions/specs/NativeRNFBTurboFunctions.ts) — Codegen spec pattern +* [`packages/functions/package.json`](../../packages/functions/package.json) — `codegenConfig`, committed generated output diff --git a/okf-bundle/packages/app/index.md b/okf-bundle/packages/app/index.md index 6617895cd6..df66cd4fb1 100644 --- a/okf-bundle/packages/app/index.md +++ b/okf-bundle/packages/app/index.md @@ -23,8 +23,8 @@ The workspace RN CLI prebuilt RNCore iOS **build** fixture (`test-rn-bare/`) is ## Related repository files * [`packages/app/firebase_spm.rb`](../../../packages/app/firebase_spm.rb) — SPM activation, embed phase, `rnfirebase_add_spm_core_to_app_target` -* [`packages/app/__tests__/`](../../../packages/app/__tests__/) — Ruby SPM unit tests +* [`packages/app/__tests__/`](../../../packages/app/__tests__) — Ruby SPM unit tests * [`packages/app/plugin/src/ios/appDelegate.ts`](../../../packages/app/plugin/src/ios/appDelegate.ts) — Expo AppDelegate `FirebaseApp.configure()` injection -* [`test-expo/`](../../../test-expo/) — workspace Expo example and documented-path iOS link closer (not Detox; closer is build-only) -* [`test-rn-bare/`](../../../test-rn-bare/) — workspace RN CLI prebuilt RNCore iOS compile fixture (not Detox) +* [`test-expo/`](../../../test-expo) — workspace Expo example and documented-path iOS link closer (not Detox; closer is build-only) +* [`test-rn-bare/`](../../../test-rn-bare) — workspace RN CLI prebuilt RNCore iOS compile fixture (not Detox) * Consumer Expo linkage: [`docs/ios-spm.mdx`](../../../docs/ios-spm.mdx) (config plugins; no agent `expo prebuild` / `xcodebuild` steps) diff --git a/okf-bundle/packages/auth/compare-types-triage.md b/okf-bundle/packages/auth/compare-types-triage.md index 852be1e1a5..c0e56fe630 100644 --- a/okf-bundle/packages/auth/compare-types-triage.md +++ b/okf-bundle/packages/auth/compare-types-triage.md @@ -14,9 +14,9 @@ Known differences between `@react-native-firebase/auth` and firebase-js-sdk modu - [`.github/scripts/compare-types/configs/auth.ts`](../../../.github/scripts/compare-types/configs/auth.ts) — machine-readable registry (`yarn compare:types auth`) - [`docs/migrating-to-v25.mdx`](../../../docs/migrating-to-v25.mdx) — user-facing migration guide (also read by agents) -- [`packages/auth/lib/modular.ts`](../../../packages/auth/lib/modular.ts) — modular API +- [`packages/auth/lib/index.ts`](../../../packages/auth/lib/index.ts) — modular API - [`packages/auth/lib/web/RNFBAuthModule.ts`](../../../packages/auth/lib/web/RNFBAuthModule.ts) — Other platform js-sdk bridge -- [`tests/local-tests/`](../../../tests/local-tests/) — mini-app exercising MFA / TOTP on Other platforms +- [`tests/local-tests/`](../../../tests/local-tests) — mini-app exercising MFA / TOTP on Other platforms --- diff --git a/okf-bundle/packages/auth/index.md b/okf-bundle/packages/auth/index.md index 43c38185bd..2743921f25 100644 --- a/okf-bundle/packages/auth/index.md +++ b/okf-bundle/packages/auth/index.md @@ -10,4 +10,4 @@ Knowledge for Auth TypeScript alignment with the firebase-js-sdk modular API (v2 * [`.github/scripts/compare-types/configs/auth.ts`](../../../.github/scripts/compare-types/configs/auth.ts) — machine-readable registry (`yarn compare:types auth`) * [`docs/migrating-to-v25.mdx`](../../../docs/migrating-to-v25.mdx) — user-facing migration guide -* [`packages/auth/lib/modular.ts`](../../../packages/auth/lib/modular.ts) — modular API implementation +* [`packages/auth/lib/index.ts`](../../../packages/auth/lib/index.ts) — modular API implementation diff --git a/okf-bundle/packages/firestore/index.md b/okf-bundle/packages/firestore/index.md index c8525d2e77..502a617d09 100644 --- a/okf-bundle/packages/firestore/index.md +++ b/okf-bundle/packages/firestore/index.md @@ -16,7 +16,7 @@ Firestore Pipelines (`pipelines` entry) and native bridge behavior. ## Related repository files -* [`packages/firestore/lib/pipelines/`](../../../packages/firestore/lib/pipelines/) — TS builders/helpers +* [`packages/firestore/lib/pipelines/`](../../../packages/firestore/lib/pipelines) — TS builders/helpers * [`packages/firestore/e2e/Pipeline.e2e.js`](../../../packages/firestore/e2e/Pipeline.e2e.js) — cross-platform e2e; primary native coverage driver * [`packages/firestore/ios/RNFBFirestore/RNFBFirestorePipelineNodeBuilder.swift`](../../../packages/firestore/ios/RNFBFirestore/RNFBFirestorePipelineNodeBuilder.swift) — iOS expression coercion/bridge * [`firestore.pipelines-e2e.rules`](../../../.github/workflows/scripts/firestore.pipelines-e2e.rules) — cloud rules for `pipelines-e2e`; not emulator diff --git a/okf-bundle/packages/firestore/pipeline-implementation-workflow.md b/okf-bundle/packages/firestore/pipeline-implementation-workflow.md index 9fca13e672..d2e3d691cc 100644 --- a/okf-bundle/packages/firestore/pipeline-implementation-workflow.md +++ b/okf-bundle/packages/firestore/pipeline-implementation-workflow.md @@ -28,14 +28,14 @@ Pipeline-specific requirements for one `.github/scripts/compare-types/configs/fi ## Pipeline hard gates -In addition to [change authoring gates](../../testing/change-authoring-workflow.md#gates): +In addition to [change authoring gates](../../testing/authoring/gates.md#gates): | Gate | Requirement | |------|-------------| | Gap analysis | Export confirmed against firebase-js-sdk; platform support verified; semantic dependencies identified | | Baseline coverage | `snapshot-pipeline-coverage.sh before-` stdout recorded | | Implementation | Public API, lowering, Jest, [serialization-testing.md](serialization-testing.md), consumer type-test, **unit-focused** e2e | -| Review coverage | `after-` snapshot; [coverage completion signal](../../testing/coverage-design.md#coverage-as-completion-signal) | +| Review coverage | `after-` snapshot; [coverage completion signal](../../testing/code-coverage/policy.md#coverage-as-completion-signal) | | Review e2e | Full `Pipeline.e2e.js` on macOS, iOS, Android — **area-focused** tier; no `.only` | | Compare-types | Remove `missingInRN` entry when RNFB shape matches firebase-js-sdk | @@ -75,18 +75,18 @@ Every documented difference must clear the [compare-types justification bar](../ - Trace patterns in `packages/firestore/lib/pipelines/`, `internal.ts`, native parsers, web bridge. - Implement public API matching firebase-js-sdk **exactly** (including lowercase string unions — native may normalize internally). - Add Jest, consumer `type-test.ts`, serialization matrix, e2e cases. -- **Unit-focused** tier per [change authoring § implementation inner loop](../../testing/change-authoring-workflow.md#implementation-inner-loop) and [pipeline area harness](#pipeline-area-harness) below. +- **Unit-focused** tier per [change authoring § implementation inner loop](../../testing/authoring/implementation.md#implementation-inner-loop) and [pipeline area harness](#pipeline-area-harness) below. ## Pipeline `independent-review` -On a **frozen tree** — full [change authoring § independent-review](../../testing/change-authoring-workflow.md#independent-review), plus: +On a **frozen tree** — full [change authoring § independent-review](../../testing/authoring/review-and-commit.md#independent-review), plus: - Full `Pipeline.e2e.js` e2e + coverage on all platforms; `after-` snapshot. - Compare coverage to baseline; touched-file coverage must rise until intractable limits or plateau → refactor. ## Pipeline area harness -Extends [change authoring § harness narrowing](../../testing/change-authoring-workflow.md#harness-narrowing). **How:** [running e2e § local harness overrides](../../testing/running-e2e.md#local-harness-overrides-harnessoverridesjs). Do **not** edit committed `tests/app.js` / `tests/globals.js` for module narrowing. Frozen `independent-review` is [report-only except revert `.only`](../../testing/change-authoring-workflow.md#frozen-tree). +Extends [change authoring § harness narrowing](../../testing/authoring/implementation.md#harness-narrowing). **How:** [running e2e § local harness overrides](../../testing/e2e/narrowing.md#local-harness-overrides-harnessoverridesjs). Do **not** edit committed `tests/app.js` / `tests/globals.js` for module narrowing. Frozen `independent-review` is [report-only except revert `.only`](../../testing/authoring/review-and-commit.md#frozen-tree). **Override values** (required for `unit-focused` and `area-focused` before `:test-cover`): @@ -97,20 +97,20 @@ module.exports = { }; ``` -**Area spec:** `packages/firestore/e2e/Pipeline.e2e.js` (committed firestore `require.context` loads it). **Area-focused** / frozen review: overrides only; no `.only`; do not replace `require.context`. **Unit-focused** may optionally narrow to that spec via [running e2e § spec loading](../../testing/running-e2e.md#local-harness-overrides-harnessoverridesjs) — **never commit**; **never** on frozen `independent-review`. +**Area spec:** `packages/firestore/e2e/Pipeline.e2e.js` (committed firestore `require.context` loads it). **Area-focused** / frozen review: overrides only; no `.only`; do not replace `require.context`. **Unit-focused** may optionally narrow to that spec via [running e2e § spec loading](../../testing/e2e/narrowing.md#local-harness-overrides-harnessoverridesjs) — **never commit**; **never** on frozen `independent-review`. -**Sanity check:** [running e2e § sanity check by platform](../../testing/running-e2e.md#local-harness-overrides-harnessoverridesjs) — ~**700** firestore-only via overrides; ~**100** only if unit-focused Pipeline spec narrowing. Pass counts in the **thousands** mean full app load — stop ([running-e2e § gate](../../testing/running-e2e.md#harness-narrowing-gate-blocking)). +**Sanity check:** [running e2e § sanity check by platform](../../testing/e2e/narrowing.md#local-harness-overrides-harnessoverridesjs) — ~**700** firestore-only via overrides; ~**100** only if unit-focused Pipeline spec narrowing. Pass counts in the **thousands** mean full app load — stop ([running-e2e § gate](../../testing/e2e/gates.md#harness-narrowing-gate-blocking)). ## Pipeline `documentation` -On the same change set **before** `independent-review` — [change authoring § primary loop](../../testing/change-authoring-workflow.md#primary-loop). This work type promotes durable text; the OKF scan is the frozen review ([§ OKF bundle review](../../testing/validation-checklist.md#okf-bundle-review)). +On the same change set **before** `independent-review` — [change authoring § primary loop](../../testing/authoring/loop.md#primary-loop). This work type promotes durable text; the OKF scan is the frozen review ([§ OKF bundle review](../../testing/validation/okf-review.md#okf-bundle-review)). **User docs** - Page or section under `docs/firestore/pipelines/` - Parity table row on pipelines overview - `docs.json` sidebar entry for new pages -- [Validation checklist § lint and formatting](../../testing/validation-checklist.md#lint-and-formatting) +- [Validation checklist § lint and formatting](../../testing/validation/lint.md#lint-and-formatting) **OKF bundle maintenance** @@ -124,9 +124,9 @@ On the same change set **before** `independent-review` — [change authoring § feat(firestore): expose pipeline ``` -**Never stage:** `tests/harness.overrides.js`, any `.only` — [change authoring § commit](../../testing/change-authoring-workflow.md#commit). +**Never stage:** `tests/harness.overrides.js`, any `.only` — [change authoring § commit](../../testing/authoring/review-and-commit.md#commit). -Before `git commit`: [validation evidence package](../../testing/validation-checklist.md#validation-evidence-package) recorded; [coverage evidence package](../../testing/coverage-design.md#coverage-evidence-package) when lib/native bridge touched ([change authoring § commit](../../testing/change-authoring-workflow.md#commit)). +Before `git commit`: [validation evidence package](../../testing/validation/evidence-and-handoff.md#validation-evidence-package) recorded; [coverage evidence package](../../testing/code-coverage/policy.md#coverage-evidence-package) when lib/native bridge touched ([change authoring § commit](../../testing/authoring/review-and-commit.md#commit)). ## Gotchas diff --git a/okf-bundle/packages/firestore/pipeline-sdk-support-audit.md b/okf-bundle/packages/firestore/pipeline-sdk-support-audit.md index e0f37bd48d..9adb333ddb 100644 --- a/okf-bundle/packages/firestore/pipeline-sdk-support-audit.md +++ b/okf-bundle/packages/firestore/pipeline-sdk-support-audit.md @@ -129,9 +129,9 @@ Probe order/gates/live status: [work queue](pipeline-coverage-work-queue.md#j0-- 1. Branch from current main; **one function or batch at a time** when bridge work is scoped. 2. Implement or fix native lowering; unify matching `Pipeline.e2e.js` assertions cross-platform. -3. Close gates via the [change authoring primary loop](../../testing/change-authoring-workflow.md#primary-loop) (`documentation?` before frozen `independent-review`). Phase J e2e/harness: [work queue Phase J](pipeline-coverage-work-queue.md#phase-j-iteration-protocol-strict). +3. Close gates via the [change authoring primary loop](../../testing/authoring/loop.md#primary-loop) (`documentation?` before frozen `independent-review`). Phase J e2e/harness: [work queue Phase J](pipeline-coverage-work-queue.md#phase-j-iteration-protocol-strict). 4. Record outcome: - - **`independent-review` pass** → `sdk-supported-bridge-ok`; close parity row; `commit` after `review_gate` closed **with** [validation/coverage evidence](../../testing/validation-checklist.md#validation-evidence-package) recorded. + - **`independent-review` pass** → `sdk-supported-bridge-ok`; close parity row; `commit` after `review_gate` closed **with** [validation/coverage evidence](../../testing/validation/evidence-and-handoff.md#validation-evidence-package) recorded. - **`invalid-argument` / pipeline execute error** → capture exact message; classify `sdk-unsupported-confirmed` or `rnfb-bridge-gap` (compare native request in debug logs). Android already runs full pipelines; macOS uses JS SDK. Probes focus on **native iOS/Android** execute paths. diff --git a/okf-bundle/packages/firestore/pipelines.md b/okf-bundle/packages/firestore/pipelines.md index 7ad7b1e23f..0364305452 100644 --- a/okf-bundle/packages/firestore/pipelines.md +++ b/okf-bundle/packages/firestore/pipelines.md @@ -184,7 +184,7 @@ Durable inventory of where live-path holes concentrate (live status and quantifi 1. **E2e per live-but-untested operator/stage** in `coerceExpressionTree` (iOS) and live Android lowering, plus remaining executor error branches. 2. **Android parsed-aggregate tail** — partially live (`coerceAliasedAggregate` from Executor); target with e2e, not deletion. -Completion standard: [coverage expectations](/testing/coverage-design.md#coverage-expectations-policy) — touched sources reach 100% or an evidence-backed intractable limit; no cost/convenience deferral. +Completion standard: [coverage expectations](/testing/code-coverage/policy.md#coverage-expectations-policy) — touched sources reach 100% or an evidence-backed intractable limit; no cost/convenience deferral. **Compare-types exports:** tracked separately from coverage expansion ([work queue](pipeline-coverage-work-queue.md)). @@ -225,4 +225,4 @@ Native bridge lowering gaps and SDK-only limitations are tracked in [Pipeline pl # Measuring native coverage -[Running e2e tests](/testing/running-e2e.md); compare-types snapshots: [Pipeline implementation workflow](pipeline-implementation-workflow.md), [Coverage design](/testing/coverage-design.md#coverage-as-completion-signal). +[Running e2e tests](/testing/running-e2e.md); compare-types snapshots: [Pipeline implementation workflow](pipeline-implementation-workflow.md), [Coverage design](/testing/code-coverage/policy.md#coverage-as-completion-signal). diff --git a/okf-bundle/packages/messaging/index.md b/okf-bundle/packages/messaging/index.md index e3e2a94cb3..398a689c62 100644 --- a/okf-bundle/packages/messaging/index.md +++ b/okf-bundle/packages/messaging/index.md @@ -5,7 +5,7 @@ Knowledge for FCM messaging native behavior: the iOS `UNUserNotificationCenter` ## Documents * [iOS UNUserNotificationCenter delegate forwarding](ios-notification-delegate-forwarding.md) — `completionHandler` exactly-once contract, delegate chaining design, regression history (#8754 → #8786 → #9049 / #9050) -* Native integration probes (`completesNonFCMRemoteNotification` / `serializeMessagingUserInfo` via `NativeRNFBTesting`; `messagingPreservesExistingDelegate` via `RNFBTestingMessaging`; `messagingStoreSupportsDisabledStorage` via `NativeRNFBTesting`) — [running e2e § test-app native modules](../../testing/running-e2e.md#test-app-native-modules); product-line hits — [coverage design § test native modules](../../testing/coverage-design.md#test-native-modules) +* Native integration probes (`completesNonFCMRemoteNotification` / `serializeMessagingUserInfo` via `NativeRNFBTesting`; `messagingPreservesExistingDelegate` via `RNFBTestingMessaging`; `messagingStoreSupportsDisabledStorage` via `NativeRNFBTesting`) — [running e2e § test-app native modules](../../testing/e2e/rules.md#test-app-native-modules); product-line hits — [coverage design § test native modules](../../testing/code-coverage/test-app-modules.md#test-native-modules) * [iOS APNs registration on Simulator](ios-apns-simulator-registration.md) — intentional ARM64 Simulator skip of UIKit register + global-queue `registration-timeout` @@ -34,16 +34,16 @@ Detox e2e runs with the FID flag **off** (`messaging.e2e.js` asserts the `messag | Layer | Location | Scope | |-------|----------|-------| | **JS (Jest)** | [`__tests__/messaging.test.ts`](../../../packages/messaging/__tests__/messaging.test.ts), [`plugin/__tests__/`](../../../packages/messaging/plugin/__tests__) | Flag-on/off mode checks and cached-FID replay in `lib/`. Expo plugin: [`androidPlugin.test.ts`](../../../packages/messaging/plugin/__tests__/androidPlugin.test.ts) covers the Android `firebase_messaging_installation_id_enabled` meta-data (written once when `true`, nothing when omitted or `false`); [`iosPlugin.test.ts`](../../../packages/messaging/plugin/__tests__/iosPlugin.test.ts) covers `plugin/src/ios/setupInstallationId.ts` (`true` writes `FirebaseMessagingInstallationIdEnabled`, omitted or `false` write nothing, existing `Info.plist` keys are preserved) and that the plugin index composes the iOS and Android steps | -| **iOS XCTest** | [`ios/RNFBMessagingUnitTests/`](../../../packages/messaging/ios/RNFBMessagingUnitTests) | Real `RNFBMessagingModule.mm` and `RNFBMessaging+FIRMessagingDelegate.m` (`register` / `unregister`, constants, `didReceiveRegistration` / `didUnregister` event emit and delegate forwarding) compiled on macOS against hand-written stub headers and test doubles for React, Firebase, and UIKit; see [stub-header projects](../../testing/ios-architecture-decisions.md#iostest-ad-1-stub-headers). Run via `yarn tests:ios:unit`; LCOV merges into `coverage/ios-native/lcov.info` ([coverage design](../../testing/coverage-design.md#ios-xctest-unit-lcov)). `RNFBMessaging.podspec` excludes `ios/*UnitTests/**/*` so nested stub headers stay out of the pod ([podspec exclude](../../testing/ios-architecture-decisions.md#iostest-ad-1-stub-headers)). | +| **iOS XCTest** | [`ios/RNFBMessagingUnitTests/`](../../../packages/messaging/ios/RNFBMessagingUnitTests) | Real `RNFBMessagingModule.mm` and `RNFBMessaging+FIRMessagingDelegate.m` (`register` / `unregister`, constants, `didReceiveRegistration` / `didUnregister` event emit and delegate forwarding) compiled on macOS against hand-written stub headers and test doubles for React, Firebase, and UIKit; see [stub-header projects](../../testing/ios-architecture-decisions.md#iostest-ad-1-stub-headers). Run via `yarn tests:ios:unit`; LCOV merges into `coverage/ios-native/lcov.info` ([coverage design](../../testing/code-coverage/pipelines.md#ios-xctest-unit-lcov)). `RNFBMessaging.podspec` excludes `ios/*UnitTests/**/*` so nested stub headers stay out of the pod ([podspec exclude](../../testing/ios-architecture-decisions.md#iostest-ad-1-stub-headers)). | | **Android JVM** | [`android/src/test/java/io/invertase/firebase/messaging/`](../../../packages/messaging/android/src/test/java/io/invertase/firebase/messaging) (`NativeRNFBTurboMessagingInstallationIdTest`, `ReactNativeFirebaseMessagingInstallationIdEventsTest`) | Manifest flag constant, `register` / `unregister`, FID event builders and service callbacks. Robolectric + Mockito per [AndroidTest-AD-1](../../testing/android-architecture-decisions.md#androidtest-ad-1); `NativeRNFBTurboMessaging.firebaseMessaging()` is the package-private test seam. Run via `yarn tests:android:unit`. | -Neither native unit layer replaces platform e2e for module load and native↔JS delivery ([platform coverage gate](../../testing/running-e2e.md#platform-coverage-gate-blocking)). +Neither native unit layer replaces platform e2e for module load and native↔JS delivery ([platform coverage gate](../../testing/e2e/gates.md#platform-coverage-gate-blocking)). ### Known coverage limits -Two maintainer-accepted [exceptions](../../testing/change-authoring-workflow.md#acceptable-exceptions) apply to the FID flag-on paths. Both stay tracked here until resolved. +Two maintainer-accepted [exceptions](../../testing/authoring/quality-standards.md#acceptable-exceptions) apply to the FID flag-on paths. Both stay tracked here until resolved. * **Generated `register` / `unregister` JSI glue (iOS).** `__hostFunction_NativeRNFBTurboMessagingSpecJSI_register` and `__hostFunction_NativeRNFBTurboMessagingSpecJSI_unregister` in [`RNFBMessagingTurboModules-generated.mm`](../../../packages/messaging/ios/generated/RNFBMessagingTurboModules/RNFBMessagingTurboModules-generated.mm) are codegen output with no hand-written logic. The e2e app runs flag-off, so these flag-on entry points never execute on device, and the native unit tests bypass JSI. The hand-written bridge they forward to (`RNFBMessagingModule.mm`) is covered by `RNFBMessagingUnitTests`. This exception covers only this module's `register` / `unregister` glue, not generated code in general. * **Flag-on paths verified against mocks only (deferral).** `register`, `unregister`, `onRegistered`, and `onUnregistered` with the flag on are verified by mocked-SDK unit tests (Jest, `RNFBMessagingUnitTests`, Android Robolectric/Mockito), not against the real Firebase SDK on a device. The shared e2e app cannot turn the flag on app-wide without breaking the existing `getToken` / `deleteToken` / `onTokenRefresh` e2e. Mocked unit coverage is accepted for now. On-device verification is manual: build a test app with the opt-in keys set ([user docs](../../../docs/messaging/server-integration.mdx#installation-id-messaging)) and exercise `register` and `onRegistered`. diff --git a/okf-bundle/routes/docs-only.md b/okf-bundle/routes/docs-only.md new file mode 100644 index 0000000000..a05b30a71d --- /dev/null +++ b/okf-bundle/routes/docs-only.md @@ -0,0 +1,48 @@ +--- +type: Reference +title: 'Route: docs-only change' +description: 'Files and commands for a diff that only touches the user docs tree docs/** (or the docs tooling scripts).' +tags: [routes, docs, lint] +timestamp: 2026-12-02T00:00:00Z +--- + +# Route: docs-only change + +**Diff:** only `docs/**` (pages, `docs.json`), or the docs tooling files (`scripts/docs-snippets-tsc.mjs`, `scripts/docs-member-check.mjs`, `scripts/lib/mdx-fences.mjs`, `eslint.docs-snippets.config.mjs`). OKF, `AGENTS.md` or `CONTRIBUTING.md` edits: [okf-docs](okf-docs.md). Anything else: [mixed diffs](index.md#mixed-diffs). + +**Work type:** `documentation`, tier none, then a frozen `independent-review` and `commit` ([work types](../testing/authoring/loop.md#work-types)). + +## Load + +1. [Docs lint](../testing/validation/docs-lint.md): what each docs command checks, its gotchas, and the `lint:docs-links` bar (fix every `error`; only bot-gate `warn` lines on external links may stay). +2. [Agent commands: docs](../testing/commands/docs.md): the allowlisted invocations and what never to use instead. +3. Only when `docs.json`, TypeDoc config or redirects change: [documentation site maintenance](../documentation-site-maintenance.md). +4. When you record evidence: [evidence template](../testing/validation/evidence-and-handoff.md#validation-evidence-package) (docs rows). + +About 4,500 tokens with this file and `AGENTS.md` (steps 1 and 2). + +## Commands + +Run in this order from the repo root ([lint by tree](../testing/validation/lint.md#lint-by-tree--by-diff), docs row): + +| Step | Command | +| --- | --- | +| Markdown, snippet ESLint, Prettier | `yarn lint:markdown` (`yarn lint:markdown:fix` applies Prettier) | +| Spelling | `yarn lint:spellcheck` | +| Snippet type-check | `yarn docs:tsc:check` (`DOCS_TSC_ALL=1` prints every failing fence) | +| Docs vs compare-types and `test-expo` screens | `yarn docs:member:check` | +| Link check (blocking, exit 0) | `yarn lint:docs-links` | + +**Evidence:** record the `lint:docs-links` exit 0 during `documentation`, with the markdown and spellcheck rows; a missing row is a **serious** review finding ([work types](../testing/authoring/loop.md#work-types), [docs.page link check](../testing/validation/docs-lint.md#docs-page-link-check)). + +## Not triggered by this diff + +| Not needed | Why (owner) | +| --- | --- | +| Full `yarn lint`, `yarn lint:js` | A docs-only diff does not require full lint; `lint:js` covers `packages/*` and `test-expo/` ([lint](../testing/validation/lint.md#lint-by-tree--by-diff)) | +| e2e, native unit, coverage evidence | Triggered by `lib/**`, native, `e2e/**` or Ruby helpers only ([gates](../testing/authoring/gates.md#gates)) | +| OKF bundle scan | Only when `okf-bundle/`, `AGENTS.md` or `CONTRIBUTING.md` are in the frozen tree ([OKF bundle review](../testing/validation/okf-review.md#okf-bundle-review)) | + +## Review and handoff + +For the reviewer pass: [independent-review](../testing/authoring/review-and-commit.md#independent-review) re-confirms `yarn lint:docs-links` exit 0 on the frozen tree and runs the docs rows check-only ([frozen review](../testing/validation/lint.md#frozen-independent-review-check-only)). The [handoff checklist](../testing/validation/evidence-and-handoff.md#handoff-checklist) also lists `yarn tsc:compile`, `yarn tsc:compile:consumer`, `yarn reference:api`, `yarn tests:jest` and `yarn compare:types` with no trigger condition; `independent-review` runs the rows that apply. diff --git a/okf-bundle/routes/e2e.md b/okf-bundle/routes/e2e.md new file mode 100644 index 0000000000..27c56288e5 --- /dev/null +++ b/okf-bundle/routes/e2e.md @@ -0,0 +1,32 @@ +--- +type: Reference +title: 'Route: e2e run or e2e spec change' +description: 'Files to load per step for any yarn tests:* e2e run, and for diffs under packages/*/e2e/**.' +tags: [routes, testing, e2e, detox, jet] +timestamp: 2026-12-02T00:00:00Z +--- + +# Route: e2e run or e2e spec change + +**Use when:** the diff touches `packages/*/e2e/**`, or another route sends you here to run `:test-cover`. An `e2e/**` diff needs area-narrowed `:test-cover` on **every** platform where that module loads, even with no native hunk for that OS ([platform coverage gate](../testing/e2e/gates.md#platform-coverage-gate-blocking)). Commands are only `yarn tests:*` ([agent rule](../testing/running-e2e.md#agent-rule-read-first)). + +**Tiers:** `unit-focused` while implementing, `area-focused` for baseline and frozen review, `full` once before merge ([e2e validation tiers](../testing/e2e/gates.md#e2e-validation-tiers-unit-focused--area-focused--full)). One unslotted `:test-cover` at a time per host ([host rule](../testing/authoring/implementation.md#host-rule)). + +Load one step at a time. Token counts include this file and `AGENTS.md`. + +| Step | Load | About | +| --- | --- | --- | +| 1. Once per checkout | [prerequisites](../testing/e2e/prerequisites.md); before any native `:build`, [install / patch / fmt gate](../testing/commands/native-build-gate.md#install-patch-fmt-gate-blocking) | 5,000 | +| 2. Rules and gates | [rules](../testing/e2e/rules.md) (packager, emulators, when to rebuild, always `:test-cover`, what not to do), [gates and tiers](../testing/e2e/gates.md) (harness narrowing, platform matrix, one run at a time) | 8,500 | +| 3. Narrow the harness | [narrowing](../testing/e2e/narrowing.md): gitignored `tests/harness.overrides.js` with `modules` and `RNFBDebug: true`; never commit it | 4,000 | +| 4. Pre-flight, before every run | [pre-flight](../testing/e2e/preflight.md) (prepare complete, services ready, checkout ownership, harness tier) and [host clear](../testing/e2e/preflight-host-clear.md) | 8,000 | +| 5. Run and watch | [running one iteration](../testing/e2e/run-loop.md), [startup fail-fast poll](../testing/e2e/startup-fail-fast.md) | 5,000 | +| 6. On failure or stall | [recovery and diagnosis](../testing/e2e/recovery.md), [platform troubleshooting](../testing/e2e/platform-troubleshooting.md), [e2e diagnosis escalation](../testing/authoring/implementation.md#e2e-diagnosis-escalation) | 8,000 | +| 7. Evidence | Platform matrix (platform, exit code, pass/fail/pending, log path) and harness statement ([harness narrowing gate](../testing/e2e/gates.md#harness-narrowing-gate-blocking)); [validation evidence package](../testing/validation/evidence-and-handoff.md#validation-evidence-package); coverage post-process when lib/native changed ([native coverage](../testing/code-coverage/native.md)) | 5,500 | + +## Only when needed + +- Slotted parallel runs: [environment and slot topology](../testing/e2e/environment.md), [slotted parallel](../testing/e2e/slotted-parallel.md), [iOS slot simulators](../testing/e2e/slot-devices.md), [slot env variables](../testing/e2e/slot-env-variables.md) (reference table). +- Full tier before merge: [before merge](../testing/e2e/gates.md#before-merge-pr-handoff) (delete overrides, all platforms) or [`yarn test:full`](../testing/e2e/full-suite.md). +- macOS App Check custom-provider specs: [helper secret recipe](../testing/commands/e2e.md#app-check-e2e-helper-secret) (capture and merge only). +- Cloud-backed suites and helper callables: [Firebase testing project](../testing/firebase-testing-project.md). diff --git a/okf-bundle/routes/expo-plugin.md b/okf-bundle/routes/expo-plugin.md new file mode 100644 index 0000000000..1e725c5b76 --- /dev/null +++ b/okf-bundle/routes/expo-plugin.md @@ -0,0 +1,48 @@ +--- +type: Reference +title: 'Route: Expo config plugin or fixture change' +description: 'Files and commands for diffs under packages/*/plugin/**, the test-expo/ example, or the test-rn-bare/ RN CLI fixture.' +tags: [routes, testing, expo, ios, attw] +timestamp: 2026-12-02T00:00:00Z +--- + +# Route: Expo config plugin or fixture change + +**Diff:** `packages/*/plugin/**` (config plugin sources and tests), `test-expo/**` (Expo example and documented-path iOS link closer), or `test-rn-bare/**` (RN CLI prebuilt RNCore iOS build fixture). None of these is Detox e2e. Package context: [packages/app](../packages/app/index.md). Other trees too: [mixed diffs](index.md#mixed-diffs). + +**Work type:** `implementation` (`unit-focused`), then frozen `independent-review` and `commit` ([work types](../testing/authoring/loop.md#work-types)). + +## Load + +1. [Agent commands: fixtures](../testing/commands/fixtures.md): registry rows, DerivedData rules, and fixture traps (stale plugin build, `@expo/ui` autolink exclude, sources under `test-expo/node_modules`). +2. [Validation: Expo, RN CLI fixtures](../testing/validation/fixtures-and-e2e.md): which command closes which fixture. +3. [Jest](../testing/validation/jest.md) and [lint and formatting](../testing/validation/lint.md). +4. When `package.json` `exports`, `plugin/build` or published types change: [published types ADR](../testing/architecture-decisions.md) (Types-AD-3, Expo plugin smoke). + +About 8,000 tokens with this file and `AGENTS.md` (steps 1 to 3). + +## Commands + +| Change | Command | Owner | +| --- | --- | --- | +| `packages/*/plugin/src` | `yarn lerna:prepare` first: the link run prebuilds from the existing `plugin/build` ([stale plugin build](../testing/commands/fixtures.md#test-expo-link-stale-plugin-build)) | [prepare must finish first](../testing/commands/core.md#prepare-must-finish-first) | +| Plugin tests | `yarn tests:jest --watchman=false packages//plugin` | [Jest](../testing/validation/jest.md#jest) | +| JS/TS lint (`packages/**`, `test-expo/**`) | `yarn lint:js` (one script; covers `test-expo/`) | [lint by tree](../testing/validation/lint.md#lint-by-tree--by-diff) | +| `test-expo/**` TS | `yarn tsc:compile:test-expo` | [core registry](../testing/commands/core.md#canonical-registry) | +| Expo documented-path iOS link (closer, build-only, needs full network) | `yarn test-expo:ios:link` | [fixtures registry](../testing/commands/fixtures.md#canonical-registry) | +| Expo iOS 27 UIScene launch smoke | `yarn test-expo:ios:launch-smoke`, only after link in the same checkout | [fixtures registry](../testing/commands/fixtures.md#canonical-registry) | +| Duplicate ObjC class check | `yarn test-expo-fixture:ios:dupes --modules [,...]` | [fixtures registry](../testing/commands/fixtures.md#canonical-registry) | +| `test-rn-bare/**` | `yarn test-rn-bare:ios:build` then `yarn test-rn-bare:ios:launch-smoke` | [RN CLI compile](../testing/validation/fixtures-and-e2e.md#rn-cli-prebuilt-rncore-ios-compile-not-e2e) | +| Exports, `plugin/build`, published types | `yarn attw:check` | [handoff checklist](../testing/validation/evidence-and-handoff.md#handoff-checklist) | +| `test-expo` screens or compare-types configs | `yarn docs:member:check` | [evidence template](../testing/validation/evidence-and-handoff.md#validation-evidence-package) | + +Never ad-hoc `expo prebuild`, `xcodebuild`, `pod`, `simctl` or `cd test-expo && ...` ([forbidden](../testing/commands/forbidden.md)). + +## Not triggered by this diff + +- `yarn tests:*` Detox e2e and the platform coverage gate (they cover `lib/**`, native and `packages/*/e2e/**`). +- `coverage_evidence` unless `lib/**`, native bridge or `packages/app/**/*.rb` is touched ([gates](../testing/authoring/gates.md#gates)). + +## Review and handoff + +For the reviewer pass: [independent-review](../testing/authoring/review-and-commit.md#independent-review) on a frozen tree with check-only lint, and the applicable [handoff checklist](../testing/validation/evidence-and-handoff.md#handoff-checklist) rows. diff --git a/okf-bundle/routes/index.md b/okf-bundle/routes/index.md new file mode 100644 index 0000000000..524e59600d --- /dev/null +++ b/okf-bundle/routes/index.md @@ -0,0 +1,49 @@ +--- +type: Reference +title: Change routes +description: 'Catalog that sends an agent, per change type, to the files and commands that change needs. Routes link to rule owners; they do not restate rules.' +tags: [routes, okf, workflow, validation] +timestamp: 2026-12-02T00:00:00Z +--- + +# Change routes + +Find the row for what your diff touches and read only that route. Each route names the work type and validation tier, the files to load per step, the exact commands, and what that diff does not need. Routes link to the owning sections and add no rules; when a route and its owner disagree, the owner wins. + +| Diff touches | Route | +| --- | --- | +| `docs/**` only (user docs, `docs.json`) | [docs-only](docs-only.md) | +| `packages/*/__tests__/**` only (Jest tests) | [tests-only](tests-only.md) | +| `packages/*/lib/**` (JS/TS runtime or types) | [js-lib](js-lib.md) | +| `packages/*/{ios,android}/**`, podspecs, committed `generated/**`, TurboModule specs, `packages/app/**/*.rb` | [native](native.md) | +| `packages/*/e2e/**`, or any `yarn tests:*` e2e run | [e2e](e2e.md) | +| `packages/*/plugin/**`, `test-expo/**`, `test-rn-bare/**` | [expo-plugin](expo-plugin.md) | +| `okf-bundle/**`, `AGENTS.md`, `CONTRIBUTING.md` | [okf-docs](okf-docs.md) | + + + +## Mixed diffs + +Load every route the diff matches and run the union of their commands; the highest validation tier wins. Example: `lib/**` plus a docs page is [js-lib](js-lib.md) plus [docs-only](docs-only.md). A diff that matches no route: follow [validation checklist § when to run what](../testing/validation/work-types.md#when-to-run-what). + + + +## Other areas + +Each area index lists its own workflow; combine it with the route for the files you touch. + +| Area | Start at | +| --- | --- | +| GitHub Actions, CI logs, Detox / Jet troubleshooting | [ci-workflows/index.md](../ci-workflows/index.md) | +| Nx cache, prepare graph, dependency-cycle linting, publish | [monorepo-tooling/index.md](../monorepo-tooling/index.md) | +| TurboModules, Codegen, New Architecture | [new-architecture/index.md](../new-architecture/index.md) | +| iOS SPM imports, RNCore podspec | [ios-spm-native-imports.md](../ios-spm-native-imports.md), [ios-rncore-podspec.md](../ios-rncore-podspec.md) | +| One package's workflow (Firestore Pipelines, Messaging, App Check, Auth, ...) | `okf-bundle/packages//index.md` via [index.md § Packages](../index.md#packages) | +| Docs site, TypeDoc, redirects | [documentation-site-maintenance.md](../documentation-site-maintenance.md) | + +## Every route assumes + +- Shell commands come only from the [agent rule](../testing/agent-command-policy.md#agent-rule-read-first) registry; anything else is [forbidden](../testing/commands/forbidden.md). +- Work types and tiers: [change authoring § work types](../testing/authoring/loop.md#work-types). Term ids: [iteration vocabulary](../testing/iteration-vocabulary.md). +- Exit codes come from zsh: use `${pipestatus[1]}` or bare `$?` ([trap](../testing/commands/core.md#agent-shell-is-zsh)). +- `implementation`, `documentation` and `independent-review` are separate passes ([frozen tree](../testing/authoring/review-and-commit.md#frozen-tree)). A route's "Review and handoff" step is for the reviewer pass, not the authoring pass. diff --git a/okf-bundle/routes/js-lib.md b/okf-bundle/routes/js-lib.md new file mode 100644 index 0000000000..e94e3579d5 --- /dev/null +++ b/okf-bundle/routes/js-lib.md @@ -0,0 +1,48 @@ +--- +type: Reference +title: 'Route: JS/TS library change' +description: 'Files and commands, step by step, for a diff under packages/*/lib/** (JS/TS runtime or published types).' +tags: [routes, testing, jest, lint, coverage, e2e] +timestamp: 2026-12-02T00:00:00Z +--- + +# Route: JS/TS library change + +**Diff:** `packages/*/lib/**`, with or without tests in `packages/*/__tests__/**` and `type-test.ts`. Native, `e2e/**`, plugin or docs too: [mixed diffs](index.md#mixed-diffs). Package workflow, if any: `okf-bundle/packages//index.md`. + +**Work types:** `implementation` (tier `unit-focused`), `documentation?` when user docs or types change, frozen `independent-review` (tier `area-focused`), `commit` ([loop](../testing/authoring/loop.md#primary-loop)). Gates: `implementation`, `coverage_evidence` (**required** for `lib/**`), `review`, `commit` ([gates](../testing/authoring/gates.md#gates)). + +Load one step at a time; each step is about 4,000 to 7,000 tokens with this file and `AGENTS.md`. + +## Step 1: build and unit loop + +Load [agent commands: core](../testing/commands/core.md) (prepare rules), [Jest](../testing/validation/jest.md), [lint and formatting](../testing/validation/lint.md). + +| Command | Rule | +| --- | --- | +| `yarn lerna:prepare` | After every `lib/**` edit, **exit 0 before any other command**, never in parallel ([prepare must finish first](../testing/commands/core.md#prepare-must-finish-first)); restart a running packager after it ([prepare completion gate](../testing/e2e/preflight.md#prepare-completion-gate-blocking)) | +| `yarn tests:jest --watchman=false ` | Focused while iterating ([Jest](../testing/validation/jest.md#jest)) | +| `yarn tsc:compile`, `yarn tsc:compile:consumer` | [Prepare and compile](../testing/validation/compile-and-types.md#prepare-and-compile) | +| `yarn lint:js`, `yarn lint:deps` | Both blocking for a `lib/**` diff ([lint by tree](../testing/validation/lint.md#lint-by-tree--by-diff)); full `yarn lint` not required for a JS-only diff | + +## Step 2: e2e on every required platform + +`lib/**` of a module that loads on native or macOS triggers the [platform coverage gate](../testing/e2e/gates.md#platform-coverage-gate-blocking): area-narrowed `:test-cover` on every platform where the module loads in committed `tests/app.js` (macOS first when the path is TS/web-only). `lib/**` alone needs prepare and a Metro restart, not a native `:build` ([rules § 3](../testing/e2e/rules.md#rules)). Follow the [e2e route](e2e.md) steps. + +## Step 3: evidence and coverage + +Load [gates and evidence](../testing/authoring/gates.md) and [coverage policy](../testing/code-coverage/policy.md); for per-file numbers, [reading coverage locally](../testing/code-coverage/local.md#reading-per-file-coverage-locally). + +- `implementation` evidence: prepare / tsc / Jest exit codes, e2e pass count per required platform with log path, lint evidence ([evidence row](../testing/authoring/gates.md#validation-evidence-blocking)). +- `coverage_evidence`: the full [coverage evidence package](../testing/code-coverage/policy.md#coverage-evidence-package) with verdict line. Jet NYC `text-summary` after a narrowed run is not coverage proof ([forbidden shortcuts](../testing/authoring/gates.md#forbidden-shortcuts)). +- Template: [validation evidence package](../testing/validation/evidence-and-handoff.md#validation-evidence-package). + +## Step 4: review and handoff (reviewer pass) + +Load [frozen review and commit](../testing/authoring/review-and-commit.md) and [compile and types](../testing/validation/compile-and-types.md). + +- Area-focused e2e on the frozen tree, check-only lint, coverage package closed. +- `yarn compare:types`: **blocking** for a package registered there; the touched package needs zero undocumented or stale differences ([type parity](../testing/validation/compile-and-types.md#api-reference-and-type-parity)). +- `yarn reference:api` when public surface changed; `yarn attw:check` when `package.json` `exports` or published types changed ([handoff checklist](../testing/validation/evidence-and-handoff.md#handoff-checklist)). +- Changing `nativeModule.ts`, `nativeModuleAndroidIos.ts` or TurboModule wrapper behaviour adds the contract test row in that checklist. +- Public API or observable behaviour change: tests, docs and types in the same PR (`AGENTS.md`). diff --git a/okf-bundle/routes/native.md b/okf-bundle/routes/native.md new file mode 100644 index 0000000000..08ef4bacea --- /dev/null +++ b/okf-bundle/routes/native.md @@ -0,0 +1,52 @@ +--- +type: Reference +title: 'Route: native change' +description: 'Files and commands, step by step, for iOS / Android bridge code, podspecs, committed generated code, TurboModule specs, and iOS Ruby helpers.' +tags: [routes, testing, ios, android, ruby, coverage, e2e] +timestamp: 2026-12-02T00:00:00Z +--- + +# Route: native change + +**Diff:** `packages/*/ios/**`, `packages/*/android/**`, podspecs, committed `packages/*/ios/generated/**` or `packages/*/android/**/generated/**`, TurboModule spec / codegen wiring, or iOS Ruby helpers (`packages/app/**/*.rb`, `packages/app/__tests__/*_test.rb`). Committed generated code and codegen wiring count as native ([rules § 3](../testing/e2e/rules.md#rules)). Other trees too: [mixed diffs](index.md#mixed-diffs). + +**Work types:** `implementation` (`unit-focused`), `documentation?`, frozen `independent-review` (`area-focused`), `commit`. `coverage_evidence` is **required** ([gates](../testing/authoring/gates.md#gates)). + +Load one step at a time; each step is about 4,000 to 7,000 tokens with this file and `AGENTS.md`. + +## Step 1: before editing + +Load [implementation pass](../testing/authoring/implementation.md): read each platform SDK's own signature and docs, null vs empty string, no defensive parity, record the reference ([platform SDK bridge contracts](../testing/authoring/implementation.md#platform-sdk-bridge-contracts)). TurboModules: [new-architecture index](../new-architecture/index.md) and [codegen commands](../testing/commands/native.md#turbomodule-codegen). + +## Step 2: native unit tests and format + +Load [native unit tests](../testing/validation/native-unit.md), [agent commands: native](../testing/commands/native.md), [lint and formatting](../testing/validation/lint.md). + +| Tree | Command | Note | +| --- | --- | --- | +| Android Java bridge / `src/test/java` | `yarn tests:android:unit` | [AndroidTest-AD-1](../testing/android-architecture-decisions.md#androidtest-ad-1) | +| iOS ObjC/C++ bridge, `*UnitTests.xcodeproj` | `yarn tests:ios:unit` | [IosTest-AD-1](../testing/ios-architecture-decisions.md#iostest-ad-1) | +| Java format | `yarn lint:android` | `implementation` only, mutates, needs JDK 21+ ([Java format](../testing/commands/native.md#android-java-format)) | +| Kotlin format | repo-root `./gradlew ktlintFormat -PinternalKtlintGitFilter=...` | `implementation` only ([Kotlin format](../testing/commands/native.md#android-kotlin-format)) | +| iOS `.h` / `.m` / `.mm` / `.cpp` | `yarn lint:ios:check` (`yarn lint:ios:fix` in `implementation`) | [lint by tree](../testing/validation/lint.md#lint-by-tree--by-diff) | +| Codegen specs | `yarn codegen:verify` | Never a substitute for platform e2e ([forbidden shortcuts](../testing/authoring/gates.md#forbidden-shortcuts)) | + +JVM and XCTest unit runs never replace platform e2e. + + + +### Ruby helpers + +`packages/app/**/*.rb` or `packages/app/__tests__/*_test.rb`: `yarn tests:ios:ruby` exit 0 plus `coverage/ios-ruby/lcov.info` is **blocking** ([iOS Ruby unit tests](../testing/validation/native-unit.md#ios-ruby-unit-tests); host Ruby, Bundler and vendor traps: [iOS Ruby](../testing/commands/native.md#ios-ruby-spm-helpers)). Coverage: [iOS Ruby SimpleCov](../testing/code-coverage/local.md#ios-ruby-simplecov); touched production Ruby lines need support in the coverage evidence package. + +## Step 3: build and e2e on every required platform + +Before any native `:build`: the [install / patch / fmt gate](../testing/commands/native-build-gate.md#install-patch-fmt-gate-blocking) (root `yarn` exit 0, fmt at least 12.1.0, `yarn tests:ios:pod:install` before an iOS build on a clean checkout). Then `yarn tests::build` and area-narrowed `:test-cover` on every platform where the module loads ([platform coverage gate](../testing/e2e/gates.md#platform-coverage-gate-blocking)). Follow the [e2e route](e2e.md). + +## Step 4: coverage and evidence + +Load [coverage policy](../testing/code-coverage/policy.md) and [native e2e coverage](../testing/code-coverage/native.md). Post-process after fresh e2e: Android `yarn tests:android:post-e2e-coverage` (merged `jacocoTestReport`), iOS `yarn tests:ios:test:process-coverage`. Close `coverage_evidence` with the [coverage evidence package](../testing/code-coverage/policy.md#coverage-evidence-package); record the [validation evidence package](../testing/validation/evidence-and-handoff.md#validation-evidence-package). + +## Step 5: review and handoff (reviewer pass) + +[Frozen review](../testing/authoring/review-and-commit.md#independent-review): area-focused e2e per platform, check-only lint (no `yarn lint:android`, `ktlintFormat` or full `yarn lint` on a frozen tree, [frozen review](../testing/validation/lint.md#frozen-independent-review-check-only)), coverage package closed, [handoff checklist](../testing/validation/evidence-and-handoff.md#handoff-checklist). diff --git a/okf-bundle/routes/okf-docs.md b/okf-bundle/routes/okf-docs.md new file mode 100644 index 0000000000..d6182ed067 --- /dev/null +++ b/okf-bundle/routes/okf-docs.md @@ -0,0 +1,29 @@ +--- +type: Reference +title: 'Route: OKF, AGENTS.md or CONTRIBUTING.md change' +description: 'Files and rules for edits to okf-bundle/**, the root AGENTS.md, or CONTRIBUTING.md.' +tags: [routes, okf, documentation, policy] +timestamp: 2026-12-02T00:00:00Z +--- + +# Route: OKF, AGENTS.md or CONTRIBUTING.md change + +**Diff:** `okf-bundle/**` reference docs, the root `AGENTS.md`, or `CONTRIBUTING.md`. User docs under `docs/**`: [docs-only](docs-only.md). + +**Work types:** `documentation` (tier none) promotes the text on the same change set **before** review; the frozen `independent-review` **is** the OKF bundle scan, report only; contract findings go back to `documentation`, then another frozen `independent-review`; `commit` closes only after a clean scan ([OKF update contract](../documentation-policy.md#okf-update-contract), [commit](../testing/authoring/review-and-commit.md#commit)). + +## Load + +1. [Documentation and commit policy](../documentation-policy.md): public vs ephemeral vs private (no Linear issue ids, no queue state), OKF update contract, Efficiency, work-queue documents (never create a new `*work-queue.md`). +2. [OKF bundle review](../testing/validation/okf-review.md): what the frozen scan checks. +3. [Bundle structure](../CONTEXT.md): where a fact belongs, the frontmatter fields, routes, anchor maps, and how to keep old `#anchors` working when you move text. + +About 4,500 tokens with this file and `AGENTS.md`. + +## Commands + +None are required. OKF-only diffs skip the docs lint rows ([lint by tree](../testing/validation/lint.md#lint-by-tree--by-diff)). Do not add OKF, `AGENTS.md` or `CONTRIBUTING.md` text after a frozen review without another `independent-review` ([frozen tree](../testing/authoring/review-and-commit.md#frozen-tree)). + +## Checks the scan applies + +Canonical location (one owning doc per topic; indexes link file and section), DRY, Efficiency (completeness beats brevity; never drop a rule, case or inbound heading id), link hygiene, and Durability ([contract table](../documentation-policy.md#okf-update-contract)). A heading rename that breaks a `#fragment` fails the scan ([Efficiency](../documentation-policy.md#efficiency)). diff --git a/okf-bundle/routes/tests-only.md b/okf-bundle/routes/tests-only.md new file mode 100644 index 0000000000..e4578cf4b4 --- /dev/null +++ b/okf-bundle/routes/tests-only.md @@ -0,0 +1,47 @@ +--- +type: Reference +title: 'Route: tests-only change' +description: 'Files and commands for a diff that only adds or edits Jest tests under packages/*/__tests__/**.' +tags: [routes, testing, jest] +timestamp: 2026-12-02T00:00:00Z +--- + +# Route: tests-only change + +**Diff:** only Jest tests under `packages/*/__tests__/**` (no `lib/**`, native, `e2e/**`, plugin or docs). Ruby tests (`packages/app/__tests__/*_test.rb`) are not Jest: take the [native route § Ruby helpers](native.md#ruby-helpers). Anything else in the diff: [mixed diffs](index.md#mixed-diffs). + +**Work type:** `implementation`, tier `unit-focused` ([work types](../testing/authoring/loop.md#work-types)). + +## Load + +1. [Jest](../testing/validation/jest.md): commands, focused coverage flag order, unhandled rejection pattern, host-dependent darwin test. +2. [Lint and formatting](../testing/validation/lint.md): run only the scripts whose tree is in the diff. +3. When you close the gate: [validation evidence (blocking)](../testing/authoring/gates.md#validation-evidence-blocking) and the [evidence template](../testing/validation/evidence-and-handoff.md#validation-evidence-package). + +About 4,000 tokens with this file and `AGENTS.md`. + +## Commands + +| Step | Command | Owner | +| --- | --- | --- | +| Iterate | `yarn tests:jest --watchman=false ` | [Jest](../testing/validation/jest.md#jest) | +| Lint (`packages/**` JS/TS tree) | `yarn lint:js` (`--fix` allowed in `implementation`) | [lint by tree](../testing/validation/lint.md#lint-by-tree--by-diff) | +| Typecheck | `yarn tsc:compile` | [compile](../testing/validation/compile-and-types.md#prepare-and-compile) | +| Gate evidence | Jest and tsc exit codes plus lint evidence (the row asks for prepare too; prepare only runs after `lib/**` edits) | [`implementation` evidence row](../testing/authoring/gates.md#validation-evidence-blocking) | + +`.only` is fine while iterating and must never be committed ([commit](../testing/authoring/review-and-commit.md#commit)). + +## Not triggered by this diff + +| Not needed | Why (owner) | +| --- | --- | +| e2e / `:test-cover` | The [platform coverage gate](../testing/e2e/gates.md#platform-coverage-gate-blocking) triggers on native, committed `generated/**`, `lib/**` or `packages/*/e2e/**` only | +| Full `yarn lint` | A JS-only diff does not require it ([lint](../testing/validation/lint.md#lint-by-tree--by-diff)) | +| `yarn lint:deps` | `packages/*/lib/**` only | +| `yarn lerna:prepare` | Only after `packages/*/lib/**` edits ([handoff checklist](../testing/validation/evidence-and-handoff.md#handoff-checklist)) | +| Coverage evidence package | `coverage_evidence` is `n/a` unless lib, native bridge or `packages/app/**/*.rb` is touched ([gates](../testing/authoring/gates.md#gates)) | +| Native unit, Ruby, attw, test-expo typecheck | Their rows are conditional on trees this diff does not touch | + +## Review and handoff + +For the reviewer pass: [independent-review](../testing/authoring/review-and-commit.md#independent-review) on a frozen tree, check-only lint. The [handoff checklist](../testing/validation/evidence-and-handoff.md#handoff-checklist) also lists full `yarn tests:jest`, `yarn tsc:compile`, `yarn tsc:compile:consumer`, `yarn reference:api` and `yarn compare:types` with no trigger condition; `independent-review` runs the rows that apply (step 3 there scopes `reference:api` to public-surface changes and `compare:types` to the touched registered package). diff --git a/okf-bundle/testing/agent-command-policy.md b/okf-bundle/testing/agent-command-policy.md index 0c3dcaa7cf..dc3c2172bb 100644 --- a/okf-bundle/testing/agent-command-policy.md +++ b/okf-bundle/testing/agent-command-policy.md @@ -3,12 +3,12 @@ type: Reference title: Agent command policy description: Canonical allowlist for agent shell commands — install, prepare, validation, e2e, Expo example typecheck, documented-path iOS link and per-module duplicate ObjC class check, RN CLI prebuilt RNCore iOS build, read-only GitHub CLI queries, and workflow-friction logging. Supersedes improvised diagnostics. tags: [testing, validation, agents, workflow, yarn] -timestamp: 2026-10-01T00:00:00Z +timestamp: 2026-12-02T00:00:00Z --- # Agent command policy -Single source for **which shell commands agents may run** in this repo. E2e `yarn tests:*` detail lives in [running e2e](running-e2e.md) ([agent rule](running-e2e.md#agent-rule-read-first)). `test-expo/` is a user-facing Expo example **and** the documented-path iOS **link** closer (not Detox; the closer is **build-only**). `test-rn-bare/` is the RN CLI prebuilt RNCore iOS **build** fixture (not Detox, not an example app). Each command is only its registry row below. Ad-hoc `pod` / `xcodebuild` stay **never-use** (with or without those rows). +Single source for **which shell commands agents may run** in this repo. E2e `yarn tests:*` detail lives in [running e2e](running-e2e.md) ([agent rule](running-e2e.md#agent-rule-read-first)). `test-expo/` is a user-facing Expo example **and** the documented-path iOS **link** closer (not Detox; the closer is **build-only**). `test-rn-bare/` is the RN CLI prebuilt RNCore iOS **build** fixture (not Detox, not an example app). Each command is only its registry row (registry files listed below). Ad-hoc `pod` / `xcodebuild` stay **never-use** (with or without those rows). > If a command is not listed here (or linked from here as canonical), **do not run it** — including “diagnostic probes” suggested by log output, package READMEs, or Yarn CLI help. @@ -17,373 +17,60 @@ Single source for **which shell commands agents may run** in this repo. E2e `yar 1. Run **only** commands in the [registry](#canonical-registry) below (repo root unless noted). -2. **`yarn` / `yarn lerna:prepare` must finish before anything else** — see [prepare must finish first](#prepare-must-finish-first). Do not parallelize install/prepare with e2e, Metro, builds, or other shell commands. -3. **Before any native `:build`:** root `yarn` exit 0 **and** patched fmt **≥ 12.1.0** — [install / patch / fmt gate](#install-patch-fmt-gate-blocking). Do **not** invent Podfile/fmt workarounds. +2. **`yarn` / `yarn lerna:prepare` must finish before anything else** — see [prepare must finish first](commands/core.md#prepare-must-finish-first). Do not parallelize install/prepare with e2e, Metro, builds, or other shell commands. +3. **Before any native `:build`:** root `yarn` exit 0 **and** patched fmt **≥ 12.1.0** — [install / patch / fmt gate](commands/native-build-gate.md#install-patch-fmt-gate-blocking). Do **not** invent Podfile/fmt workarounds. 4. When a canonical command fails: read the **full** output, fix **product code** (or re-run root `yarn` for a patch miss), re-run the **same** command. Do **not** switch invocation style. -5. Do **not** infer alternate commands from error strings (`command not found: genversion`, `Couldn't find a script named "jet"`, etc.) — see [known traps](#known-traps). -6. The [command constraints](#command-constraints) below apply to every shell session in this repo. +5. Do **not** infer alternate commands from error strings (`command not found: genversion`, `Couldn't find a script named "jet"`, etc.) — see [known traps](commands/core.md#known-traps). +6. The [command constraints](commands/constraints.md#command-constraints) apply to every shell session in this repo. ## Canonical registry -| Intent | Command | Never use instead | -| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Install / refresh deps | `yarn` (repo root; `postinstallDev` → `yarn prepare && yarn lerna:prepare && yarn ruby:install`) | `yarn workspace …`, `npm install`, `npm install` in a package, `yarn install` / `yarn` in `tests/` alone for root deps, skipping root `yarn` before e2e/build | -| Root Gemfile gems (CocoaPods, RuboCop, etc.) | `yarn ruby:install` (runs `bundle check \|\| bundle install` when `bundle` is on PATH, `ruby` on PATH is `>= 3.3.1` and `bundle --version` runs; otherwise **skips with exit 0** and one line naming why — JS-only checkouts, CI without setup-ruby, macOS system Ruby 2.6 `/usr/bin/bundle`); included in root `yarn` via `postinstallDev`. CI: `BUNDLE_FROZEN=true bundle install` **before** yarn in e2e/publish workflows | bare `bundle install` at repo root | -| Transpile `lib/**` → `dist/module/**` (all packages) | `yarn lerna:prepare` | `yarn workspace @react-native-firebase/* prepare`, `cd packages/ && yarn prepare`, `cd packages/ && yarn run build` | -| Transpile one package | `yarn lerna run prepare --scope @react-native-firebase/` | `yarn workspace @react-native-firebase/ prepare` | -| After `packages/*/lib/**` edits (Metro serves `dist/module/**`) | `yarn lerna:prepare`; Metro restart when already running ([running e2e § prepare completion gate](running-e2e.md#prepare-completion-gate-blocking)) — platform `:build` only when [running e2e § Rules #3](running-e2e.md#rules) requires native/codegen/instrumentation, not for JS alone | ad-hoc `bob`, `babel`, or package-scoped prepare | -| TS/JS validation sequence | [validation checklist](validation-checklist.md) | ad-hoc `tsc` in package dirs unless listed there | -| test-expo TypeScript check | `yarn tsc:compile:test-expo` (repo root; `tsc --project test-expo/tsconfig.json`) | `cd test-expo && tsc`; `cd test-expo && …` as a typecheck gate | -| JS lint (implementation / review gate) | `yarn lint:js`, `yarn lint:js --fix` (`eslint packages/* test-expo`; already includes `test-expo/`) | package-scoped `eslint`, `npx eslint`; a second `test-expo` lint entrypoint | -| Android Java format / lint | `yarn lint:android` (Java only; not Kotlin) | `yarn google-java-format`, bare `google-java-format`, `google-java-format -i`, `npx google-java-format`, using this script on `.kt` | -| Android Kotlin format | repo-root `./gradlew ktlintFormat` with `-PinternalKtlintGitFilter=` (newline-separated repo-root-relative `packages/*/android/**/*.kt` and, if touched, `tests/android/**/*.kt`) | `ktlint` / `npx ktlint`; yarn format scripts; `cd tests/android && ./gradlew …`; other Gradle ktlint tasks; `-PrnfbKtlintGitFilter` on the **root** wrapper | -| Docs lint | `yarn lint:markdown`, `yarn lint:markdown:fix`, `yarn lint:spellcheck`, `yarn lint:docs-links`. When and what each runs: [validation checklist § docs lint gotchas](validation-checklist.md#docs-lint-gotchas) (docs tree or docs tooling only; OKF-only skips). `:fix` is Prettier `--write`. `lint:markdown` already includes the snippet ESLint config | ad-hoc `npx @docs.page/cli`; ad-hoc prettier/eslint on single files; `eslintJs.configs.all` against doc fences; bare `eslint --config eslint.docs-snippets.config.mjs` as a second gate | -| Docs snippet type-check | `yarn docs:tsc:check` (blocking; CI Documentation job; non-zero on failure). `DOCS_TSC_ALL=1 yarn docs:tsc:check` prints every failing fence (default prints the first 10). Scope, limits, and the ignore marker: [validation checklist § docs lint gotchas](validation-checklist.md#docs-lint-gotchas) | ad-hoc `tsc` on doc fences / hand-copied snippets; treating the default first-10 output as the full list | -| Docs member check | `yarn docs:member:check` (blocking; CI Documentation job; docs vs compare-types configs and `test-expo` screens). What it checks and its guards: [validation checklist § docs lint gotchas](validation-checklist.md#docs-lint-gotchas) | inventing a second docs↔screen sync check; requiring a `vertexai` screen | -| iOS Ruby lint (RuboCop) | `yarn lint:ruby` (also runs inside `yarn tests:ios:ruby`) | ad-hoc `rubocop`, `bundle exec rubocop` without the Gemfile/config | -| Android JVM unit tests | `yarn tests:android:unit` | ad-hoc `./gradlew …` outside this yarn script; bare Robolectric/JUnit IDE-only as the agent gate | -| iOS XCTest unit tests (in-package) | `yarn tests:ios:unit` | ad-hoc `xcodebuild test`; CocoaPods `test_spec`; `tests/ios/testingTests` host UI tests | -| iOS Ruby unit tests (SPM / CocoaPods helpers) | `yarn lint:ruby` / `yarn tests:ios:ruby` (after root `yarn` or `yarn ruby:install` when gems are missing) | ad-hoc `ruby packages/app/__tests__/…_test.rb`, bare `ruby …/run_with_coverage.rb` without the yarn script as the agent gate | -| iOS CocoaPods provisioning before shared build | `yarn tests:ios:pod:install` (after root `yarn` or `yarn ruby:install` when gems are missing; required order below) | bare `pod install`, `cd tests/ios && pod install`, or assuming `yarn tests:ios:build` creates CocoaPods support files | -| Expo documented-path iOS link (workspace `test-expo/`; also the user-facing Expo example) | `yarn test-expo:ios:link` (repo root; script `.github/workflows/scripts/test-expo-ios-link.sh`). **Build-only** (`xcodebuild build`; does not launch). Builds into `RNFB_TEST_EXPO_DERIVED_DATA` (default `/tmp/test-expo-derived-data-`), wiped before every `xcodebuild`; Swift package checkouts in `RNFB_TEST_EXPO_SPM_PACKAGES` (default `/tmp/test-expo-spm-packages-`, never wiped, shared with the launch smoke and the fixture runner) — [§ Expo iOS DerivedData](#expo-ios-derived-data). Keep `expo.autolinking.exclude: ["@expo/ui"]` in `test-expo/package.json` — [gotcha](#expo-router-autolink-exclude-expo-ui). After `packages/*/plugin/src` edits run `yarn lerna:prepare` first — [gotcha](#test-expo-link-stale-plugin-build) | ad-hoc `expo prebuild` / `xcodebuild` outside that script; `cd test-expo && …` as the agent gate (link, typecheck, or launch); `yarn test-rn-bare:ios:build` as this closer; dropping the `@expo/ui` autolink exclude | -| Expo iOS 27 UIScene launch smoke (`test-expo/`; after link) | `yarn test-expo:ios:launch-smoke` (repo root; script `.github/workflows/scripts/test-expo-ios-launch-smoke.sh`). **Debug build + launch** on an iOS 27 simulator via `simctl` (runs its own Debug `xcodebuild`, which reuses `RNFB_TEST_EXPO_SPM_PACKAGES`; starts fixture Metro internally; requires prior `yarn test-expo:ios:link` in the same checkout). Simulator: `RNFB_TEST_EXPO_IOS27_DEVICE` (default `iPhone 18 Pro`) on `RNFB_TEST_EXPO_IOS27_RUNTIME` (default `iOS 27.0`); set both when the host has no such available simulator (the script exits 1). Not Detox | ad-hoc `simctl` / `xcodebuild` / `cd test-expo && expo start` outside that script; `open -a Simulator`; Device Hub | -| Expo per-module duplicate Objective-C class check (generated blank Expo app under gitignored `test-expo/.fixtures//`) | `yarn test-expo-fixture:ios:dupes --modules [,…] [--expect-duplicates N \| --report-only]` (repo root; script `.github/workflows/scripts/test-expo-fixture-ios-dupes.sh`). Generates `@react-native-firebase/app` + the listed modules with `lib/make-expo-fixture.sh` (pins from `test-expo/package.json`), prebuilds, builds Release unsigned for the iOS Simulator from an empty DerivedData (`RNFB_TEST_EXPO_FIXTURE_DERIVED_DATA`, default `/tmp/test-expo-fixture-derived-data--`; Swift package checkouts in the shared `RNFB_TEST_EXPO_SPM_PACKAGES`), then runs the shared `check-duplicate-objc-classes.sh` scan on the built `.app`. Build-only — [§ Expo iOS DerivedData](#expo-ios-derived-data). `--modules` is required; `--modules ""` builds app only; invalid, duplicate, or unpinned (not in `test-expo/package.json`) module names exit 2 before any build; `--expect-duplicates N` (default 0) passes only on exactly N duplicated classes: with 0 the `GULNetwork` canary must have exactly one owner, with N > 0 `GULNetwork` must be among the duplicates (proves the control exercised the GoogleUtilities graph); `--report-only` lists every duplicate plus the `GULNetwork` and `FIRApp` owners and exits 0 unless a scan guard fails. `--report-only` and `--expect-duplicates` are mutually exclusive; flag errors exit 2 before any build. Needs unrestricted network, like `yarn test-expo:ios:link`. Fixtures live under `test-expo/` — [gotcha](#expo-fixture-under-test-expo) | ad-hoc `expo prebuild` / `xcodebuild` / `create-expo-app` / `npm install` in the fixture; `cd test-expo/.fixtures/… && …`; reusing a DerivedData between module combinations; `yarn test-expo:ios:link` as this check | -| RN CLI prebuilt RNCore iOS build (workspace `test-rn-bare/`) | `yarn test-rn-bare:ios:build` (repo root; script `.github/workflows/scripts/test-rn-bare-ios-build.sh`). Dynamic probe (`RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1`) deletes its DerivedData before xcodebuild — [§ dynamic probe DerivedData](#dynamic-firebase-probe-derived-data) | ad-hoc `pod` / `xcodebuild`; `cd test-rn-bare && …`; `tests/` e2e / `yarn tests:*`; `yarn test-expo:ios:link` as this closer; reusing `RNFB_TEST_RN_BARE_DERIVED_DATA` to skip a clean probe | -| RN CLI iOS 27 UIScene launch smoke (`test-rn-bare/`; after build) | `yarn test-rn-bare:ios:launch-smoke` (repo root; script `.github/workflows/scripts/test-rn-bare-ios-launch-smoke.sh`). **Launch** on an iOS 27 simulator via `simctl` (requires prior `yarn test-rn-bare:ios:build` in the same checkout). Simulator: `RNFB_TEST_RN_BARE_IOS27_DEVICE` (default `iPhone 18 Pro`) on the shared `RNFB_IOS_SIM_RUNTIME` (default `iOS 27.0`); a missing device of that name is created on that runtime from `RNFB_IOS_BASE_SIMULATOR` (default `iPhone 17`), and the script exits 1 when the host has no such available runtime. Not Detox. Dynamic probe: same command with `RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1` after a probe build — [§ dynamic probe launch smoke](#dynamic-firebase-probe-launch-smoke) | ad-hoc `simctl` / `xcodebuild` / `cd test-rn-bare && …` outside that script; `open -a Simulator`; Device Hub; `yarn test-expo:ios:launch-smoke` as this closer | -| Android merged Jacoco (unit + e2e) | `yarn tests:android:post-e2e-coverage` (after e2e); `yarn tests:android:test:jacoco-report` when regenerating the merge report | `./gradlew jacocoAndroidTestReport` as Codecov path; inventing other jacoco yarn scripts | -| Native coverage presence guard (silent-empty fail) | `yarn tests:coverage:assert-presence` (also invoked from `tests:android:post-e2e-coverage` and `tests:ios:test:process-coverage`; exit **2** on empty/missing when strict) | Ignoring empty LCOV/Jacoco; treating missing `.ec` / `packagesHits=0` as soft success in CI | -| Native coverage baseline capture (repeatability) | `yarn tests:coverage:capture-baseline` (after Law `:test-cover` + process; see `tests/coverage-artifacts/README.md`) | Hand-editing `coverage-baseline.json`; inventing parallel capture scripts | -| Native coverage config generate (Gradle properties) | `yarn tests:coverage:generate-native-config` | Hand-editing generated `tests/android/coverage.properties` as the source of truth | -| E2e + coverage | [running e2e](running-e2e.md) — **only** `yarn tests:*` | `jet`, `npx jet`, `yarn jet`, `detox test`, bare `detox`, `cd tests && …`, `cd tests-macos && …`, direct Metro/emulator starts | -| iOS Detox framework cache rebuild | `yarn tests:ios:detox-framework-cache:rebuild` | `cd tests && yarn detox clean-framework-cache`, `cd tests && yarn detox build-framework-cache`, bare `detox …` | -| Host pre-flight (before each `:test-cover`) | [running e2e § pre-flight](running-e2e.md#pre-flight-is-the-host-clear-to-start) — host-clear + services ready + **[checkout ownership](running-e2e.md#services-checkout-ownership-blocking)** + harness tier. `yarn tests:e2e:check` / `yarn tests:e2e:release` ([host-clear probes](running-e2e.md#host-clear-probes)) | Port/HTTP checks alone when Metro/emulators belong to another worktree; `pgrep`/spawn probes of Jet/Detox as completion signals; ad-hoc `pgrep` / hardcoded `:8090` only; improvised kill lists; `killall` / `pkill -f` by name; `adb kill-server`; `yarn tests:e2e:release --all-slots` or `--include-unrecorded` without explicit user direction ([manual machine wipe](running-e2e.md#manual-machine-wipe)) | -| E2e slot devices (first use of a slot) | `yarn tests:e2e:setup-android-avds [count]` / `yarn tests:e2e:setup-ios-sims [count]` — **create/reuse-only** of the exact iOS neutral base; count is a strict decimal **1..8** ([slot index](running-e2e.md#e2e-slot-index)). Patched Detox reuses that base or fails when registry-taken; check/release target its exact name — [iOS slot simulators](running-e2e.md#ios-slot-simulators). Teardown of a running device is `yarn tests:e2e:release --devices` (shutdown, never delete) | Direct `xcrun simctl create/delete/erase/rename`, `avdmanager` / `sdkmanager` device commands, `simctl delete all`/`unavailable`, `simctl shutdown all`. Removing a legacy simulator is a **human-operator** step — [migration](running-e2e.md#ios-slot-simulator-migration) | -| Slotted parallel | [running e2e § slot lifecycle](running-e2e.md#slot-lifecycle) — `eval "$(yarn tests:e2e:export-slot-env N)"` then the **same** `yarn tests:packager:*` / `yarn tests:emulator:start` / `pod:install` / `:build` / `:test-cover` as serial. macOS packager is `yarn tests:macos:packager:*` (`tests-macos/`); mobile is `yarn tests:packager:*` (`tests/`) | ad-hoc port math; second lifecycle helpers as the runbook; rsync between local worktrees; host flock; Metro-after-build; disabling Swift explicit modules; Debug `RCT_NO_LAUNCH_PACKAGER` as a Metro fix; using the mobile packager for macOS Jet (or vice versa) | -| TurboModule codegen (all migrated / CI) | `yarn codegen:verify` (wipe + regen + diff); `yarn codegen:all` for local regen via package scripts | ad-hoc CLI without wipe; inventing alternate codegen yarn scripts — see [TurboModule codegen](#turbomodule-codegen) | -| Read-only GitHub state (PRs, checks, runs, issues) | `gh pr view` / `list` / `checks` / `diff`, `gh run list` / `view` (logs ok), `gh issue view` / `list`, and `gh api` with GET on read endpoints only. Prefer `--json` with `--jq` / `-q`. Needs unrestricted network (`full_network` in a sandboxed agent shell, see [sandbox / permissions](#shell-sandbox-permissions)). GitHub is authoritative for CI check state | `gh pr create` / `edit` / `merge` / `close` / `comment` / `review` / `ready`; `gh pr checkout` (mutates the local working tree); `gh run rerun` / `cancel`; `gh issue create` / `edit` / `comment` / `close`; `gh release`; `gh workflow run`; `gh repo` mutations; `gh auth`; `gh secret`; `gh api` with POST / PUT / PATCH / DELETE, `-X` other than GET, or write fields (`-f` / `-F`) | -| Workflow friction — read the inventory at item pickup; record friction met during the work | `yarn frog list` (current friction inventory); `yarn frog log` (interactive — record the friction just encountered) | Direct/global `frog`; `npx` / `yarn dlx` (and other package-runner downloads); reading, grepping, or hand-editing storage; ad-hoc friction records; inventing other `frog` subcommands or flags | -| Install App Check e2e helper secret into local harness overrides | Capture+merge recipe in [§ App Check e2e helper secret](#app-check-e2e-helper-secret) only — `functions:secrets:access` stdout is captured into `E2E_HELPER_SECRET` and merged into gitignored `tests/harness.overrides.js` (preserves `modules` / `RNFBDebug`). Repo root after `yarn`; equivalently via [`.github/workflows/scripts/firebase-cli.sh`](../../.github/workflows/scripts/firebase-cli.sh). Requires `firebase login` with access to `react-native-firebase-testing`. Field semantics: [running e2e § local harness overrides](running-e2e.md#local-harness-overrides-harnessoverridesjs) | Bare `functions:secrets:access` (prints secret into the transcript); `gcloud secrets …`; inventing other Secret Manager CLIs; `firebase functions:secrets:set` (operator/deploy only — [firebase-testing-project](firebase-testing-project.md#e2e-cloud-helper-callables)); CI-style overwrite-only write when other override fields already exist; committing `harness.overrides.js`; echoing / logging the secret | - - - -### App Check e2e helper secret (local access + merge) - -**Canonical owner** for the shell recipe that fetches `E2E_HELPER_SECRET` and installs it as `e2eHelperSecret` in gitignored `tests/harness.overrides.js`. Why / skip behavior / iOS–Android debug tokens: [running e2e § macOS App Check helper secret](running-e2e.md#macos-app-check-helper-secret). Secret Manager **set** + deploy: [firebase-testing-project § e2e cloud helper callables](firebase-testing-project.md#e2e-cloud-helper-callables). - -Repo root after `yarn`. Run **only** the capture+merge form below — never a bare `functions:secrets:access` (its stdout is the secret). Do **not** echo or log the secret; do **not** commit `tests/harness.overrides.js`. - -Merges into an existing overrides file (preserves `modules` / `RNFBDebug` / other fields). If the file exists but fails to load, exit 1 and do **not** write. Never use the CI overwrite-only write from `.github/workflows/tests_e2e_other.yml` when those fields already exist: - -```bash -E2E_HELPER_SECRET="$(./node_modules/.bin/firebase functions:secrets:access E2E_HELPER_SECRET --project react-native-firebase-testing)" \ -node -e 'const fs=require("fs"); const path=require("path"); const f="tests/harness.overrides.js"; let o={}; if(fs.existsSync(f)){ try{ o=require(path.resolve(f)); }catch(e){ console.error("failed to load "+f+": "+e.message); process.exit(1);} } if(!process.env.E2E_HELPER_SECRET){ console.error("empty secret"); process.exit(1);} o.e2eHelperSecret=process.env.E2E_HELPER_SECRET; fs.writeFileSync(f, "module.exports = " + JSON.stringify(o, null, 2) + ";\n");' -``` - -`functions:secrets:set` is **not** on this allowlist for routine agent use. - - - -### Dynamic Firebase probe DerivedData - -`yarn test-rn-bare:ios:build` with `RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1` deletes its DerivedData path before `xcodebuild`, including when `RNFB_TEST_RN_BARE_DERIVED_DATA` overrides that path. Evidence from a probe that did not start from an empty DerivedData is invalid. Do not reuse `RNFB_TEST_RN_BARE_DERIVED_DATA` to save time. A new worktree does not reset `${TMPDIR:-/tmp}` DerivedData. The normal (non-probe) build does not delete DerivedData. - - - -### Dynamic Firebase probe launch smoke - -`yarn test-rn-bare:ios:launch-smoke` does its own Debug `xcodebuild` and never reads the build script's Release DerivedData (`RNFB_TEST_RN_BARE_DERIVED_DATA`). It launches the probe graph only because the preceding probe `yarn test-rn-bare:ios:build` left a probe Pods project behind, so run it with the same `RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1` in the same checkout, right after that build. With the flag on it also: - -- fails if the Pods project is not a probe install; -- builds Debug into its own DerivedData (`RNFB_TEST_RN_BARE_LAUNCH_DERIVED_DATA`, default `${TMPDIR:-/tmp}/test-rn-bare-launch-derived-data-dynamic-firebase`), deleted first, and launches only from there; -- fails unless `RNFBFirebase.framework` is embedded in the app, the app binary (`testrnbare` or `testrnbare.debug.dylib`) has an undefined `RNFBFirebase` `AppClient` symbol (`nm -u`, so the facade is what calls configure), `RNFBFirebase.framework/RNFBFirebase` is mapped into the running process (`lsof`), and the probe-owned `RNFB_PROBE_CONFIGURE_OK` breadcrumb appears in the app log (NSLog after `RNFBFirebaseAppClient.configure()`; primary configure proof at default log level). FirebaseCore's `I-COR000001` / `Configuring the default app.` is soft-only: missing I-COR with a present breadcrumb (and passing dyld/scene checks) is insufficient to conclude configure was skipped — treat as debug-logging/capture flake (warn + diagnostics). The app is still launched with `-- -FIRDebugEnabled` after the log stream reports ready so I-COR can be observed when available. -- On CI (`test-rn-bare-ios-build-dynamic-firebase`), a failed job uploads probe launch / metro / xcodebuild logs (and optional `${APP_LOG}.retro.txt` from a retrospective `simctl … log show`) as artifact `rn-bare-dynfb-launch-smoke-logs`. - -The probe install sets the Swift compilation condition `RNFB_DYNAMIC_FIREBASE_PROBE` (next to the `RNFB_DYNAMIC_FIREBASE_PROBE=1` preprocessor define) on the `RNFBApp` pod and on the app's native targets. The undefined-symbol check above doubles as proof the condition reached the app target: if `AppDelegate.swift` compiled its `#else` branch, the binary would not reference the facade. A flag-off `pod install` removes the condition from the app project again. - -Flag off keeps the original build, app lookup, and assertions. - -The probe moves Firebase products off `RNFBApp` (onto `RNFBFirebase`), not every Swift package product: in the monorepo the `messaging` / `analytics` siblings always exist, so `RNFBApp` still declares `GULMethodSwizzler` / `GULNetwork` / `GULReachability` ([GoogleUtilities declarer](../ios-spm-native-imports.md#googleutilities-explicit-spm_dependency-lets-pods-share-one-product)). The probe's single-copy assertions are unaffected: `FIRApp` is defined once, in `RNFBFirebase`. - -A probe `pod install` rewrites the tracked `test-rn-bare/ios/testrnbare.xcodeproj/project.pbxproj`. Restore it with `git checkout -- test-rn-bare/ios/testrnbare.xcodeproj/project.pbxproj` before committing. - - - -### Expo iOS DerivedData - -`yarn test-expo:ios:link` (`RNFB_TEST_EXPO_DERIVED_DATA`, default `/tmp/test-expo-derived-data-`) and `yarn test-expo-fixture:ios:dupes` (`RNFB_TEST_EXPO_FIXTURE_DERIVED_DATA`, default `/tmp/test-expo-fixture-derived-data--`) delete their DerivedData path before every `xcodebuild`, so each run starts from an empty DerivedData. Both check the path with the shared `lib/derived-data-path.sh` before any build and exit 2 when it is empty (an override set to the empty string is not replaced by the default), has a `..` component, is `/`, `$HOME`, the repo root, or an ancestor of `$HOME` / the repo root, or its basename does not contain `derived-data` / `DerivedData`. - -`yarn test-expo:ios:link`, `yarn test-expo:ios:launch-smoke`, and `yarn test-expo-fixture:ios:dupes` share Swift package checkouts in `RNFB_TEST_EXPO_SPM_PACKAGES` (default `/tmp/test-expo-spm-packages-`, `-clonedSourcePackagesDirPath`). No runner wipes it. - -`` is the first 8 hex characters of the `shasum` (SHA-1) of the resolved (`pwd -P`) repo root (`repo_path_tag` in `lib/derived-data-path.sh`), so each worktree gets its own `/tmp` defaults. `` is the checked `--modules` list joined with `-` (`app` for `--modules ""`). - -### Prepare / transpile (detail) - -`yarn lerna:prepare` runs each package's **`prepare`** script (`build` → `compile` via react-native-builder-bob). That is what produces **`dist/module/**`** consumed by Metro in debug e2e — only **release\*\* builds pre-bundle/embed JS ([running e2e § Rules #3](running-e2e.md#rules)). - -- **`yarn compile`** (package script) is **not** a standalone agent entrypoint — it is invoked **inside** `prepare` via lerna. Do not run `cd packages/ && yarn compile` for handoff unless [validation checklist](validation-checklist.md) explicitly adds an exception (none today). -- **`yarn`** at repo root runs `postinstallDev` → `yarn prepare && yarn lerna:prepare && yarn ruby:install`; a fresh install already transpiles and installs root Gemfile gems. Re-run **`yarn lerna:prepare`** after `lib/**` edits without reinstalling. - - - -### Prepare must finish first (blocking) - -**`yarn`**, **`yarn lerna:prepare`**, and **`yarn lerna run prepare --scope …`** are **blocking foreground** commands. Wait for the shell to return **exit code 0** before starting **any** other command — including in the same agent turn via parallel tool calls. - -| Do not start until prepare exits 0 | Why | -| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -| `yarn tests:*` (e2e, packager, build) | Metro (debug JS) reads **`dist/module/**`**, not `lib/\*\*` — partial prepare → missing modules, stale bundles | -| `yarn tests:packager:jet-reset-cache` / `yarn tests:macos:packager:jet-reset-cache` | Reset after prepare, not during it. Free `:8081` first — [running e2e § packager reset-cache](running-e2e.md#packager-reset-cache-eaddrinuse). Mobile packager is `tests/`; macOS packager is `tests-macos/` | -| `yarn tsc:compile`, `yarn tsc:compile:test-expo`, Jest, `compare:types` | May read transpiled output or assume `dist/` is current | -| Another `yarn` / scoped prepare | Overlapping Nx/Lerna runs race on `dist/` | - -**Agent rule:** one prepare invocation per message batch; wait for completion; then run the next step (Metro restart if needed → pre-flight → `:test-cover`). [Running e2e § prepare completion gate](running-e2e.md#prepare-completion-gate-blocking) is the e2e-side mirror of this rule. - -**Symptoms when violated:** `Cannot find module '…/dist/module/…'`, Metro 500 on bundle, e2e failures before tests run, or green Metro `/status` while the app loads a half-written `dist/`. - - - -### Install / patch / fmt gate (blocking before native `:build`) - -**Canonical owner** for install + patch freshness before Detox native builds. E2e docs link here — do not restate this procedure elsewhere. - -**Before any** `yarn tests:ios:build`, `yarn tests:android:build`, or other Detox native build path: - -1. **Root `yarn` MUST have run and exited 0** in this checkout. Required on a fresh checkout, after deleting `node_modules`, after pulling patch changes, and whenever patches may be stale. Do **not** start native `:build` until that install finished successfully. -2. Root `yarn` applies **`.yarn/patches`** (jet, detox, mocha-remote) and workspace **`patch-package`**. **`tests/patches/detox+20.51.0.patch`** is required for slotted iOS exact-base-or-fail allocation ([running e2e § iOS slot simulators](running-e2e.md#ios-slot-simulators)) — it is **not** the Yarn Berry Detox patch. **macOS** still applies **`tests-macos/patches/react-native+0.78.3.patch`** (fmt **12.1.0**). **Mobile RN 0.86.2** ships fmt **12.1.0** upstream (no `tests/patches/react-native+*.patch` fmt bump). `tests` / `tests-macos` `prepare` is `patch-package` and must **not** be Nx-cache-skipped ([MonoTool-AD-12](../monorepo-tooling/architecture-decisions.md#monotool-ad-12--never-nx-cache-prepare-when-the-script-is-patch-package--accepted)). Without the tests Detox patch applied, an occupied neutral slot may cause stock Detox to create a suffixed device outside the slot contract. -3. **Verify** the React Native fmt podspec reports version **≥ 12.1.0** (Xcode 26 / Apple Clang 21-safe floor for this pin). **Yarn exit 0 alone is not sufficient** — always run the check below before native `:build` (a prepare cache-skip historically left fmt at **11.0.2** despite a green install): - -```bash -# Mobile toolchain (tests/) — required before ios/android :build -rg 'spec\.version|:tag' tests/node_modules/react-native/third-party-podspecs/fmt.podspec -# macOS app (tests-macos/) — required before macos :build (path may be workspace-local or hoisted) -rg 'spec\.version|:tag' tests-macos/node_modules/react-native/third-party-podspecs/fmt.podspec \ - || rg 'spec\.version|:tag' node_modules/react-native/third-party-podspecs/fmt.podspec -``` - -Expect `12.1.0` (or higher) on both `spec.version` and `:tag`. - -Before **slotted** iOS `:test-cover`, also confirm `tests/patches/detox+20.51.0.patch` landed (expect a match; missing means an occupied neutral base can trigger stock Detox clone creation / suffix escape instead of exact-base-or-fail — [iOS slot simulators](running-e2e.md#ios-slot-simulators)): - -```bash -rg 'RN_E2E_SLOT_BASE_NAME' tests/node_modules/detox/src/devices/allocation/drivers/ios/SimulatorAllocDriver.js -``` - -4. If fmt is still **11.0.2** (or anything **< 12.1.0**): **STOP**. Re-run root `yarn` / fix patch application for **macOS** (including Nx `tests-macos:prepare` cache policy — [MonoTool-AD-12](../monorepo-tooling/architecture-decisions.md#monotool-ad-12--never-nx-cache-prepare-when-the-script-is-patch-package--accepted)). On mobile 0.86+, fmt should already be ≥12.1.0 without a patch; if not, investigate the resolved `react-native` version. Do **not** invent Podfile `post_install` fmt hacks, `FMT_USE_CONSTEVAL` / `base.h` patches, c++17-for-fmt-only, or web-search workarounds. -5. **Before `yarn tests:ios:build` on a clean checkout:** run root `yarn` (which includes `yarn ruby:install`), then run **`yarn tests:ios:pod:install`** and wait for exit 0. Re-run the Pod install after `tests/ios/Podfile` / `Podfile.lock`, package podspec, or native dependency-resolution changes, and whenever `tests/ios/Pods` is absent. Root `yarn` does **not** create the CocoaPods xcconfig or file-list support files; the shared build invokes Detox/Xcode and does **not** provision them. CI installs the root bundle before yarn, then uses this same Pods-before-build order in `.github/workflows/tests_e2e_ios.yml`. - - **Expected lockfile drift:** `yarn tests:ios:pod:install` commonly rewrites the `hermes-engine` `SPEC CHECKSUMS` entry in `tests/ios/Podfile.lock` (the prebuilt Hermes podspec checksum varies by host/cache). Keep the regenerated lockfile while building and testing — reverting it mid-run fails the CocoaPods sandbox/manifest sync check. After the run, restore `tests/ios/Podfile.lock` and never stage it with unrelated changes. - -**Symptoms when violated:** Apple Clang 21 consteval errors compiling unpatched fmt **11.0.2**; missing `tests/ios/Pods` xcconfig or file-list support files; an occupied slotted iOS base causing stock Detox to create a suffixed simulator instead of failing (tests Detox patch-package skipped); agents inventing Podfile/fmt workarounds instead of re-running root `yarn` / fixing prepare cache policy. - -## When install or prepare fails - -1. Re-run from repo root: **`yarn`** or **`yarn lerna:prepare`** (full log — do not truncate). -2. Note the **first** Nx/Lerna project that failed (e.g. `@react-native-firebase/functions:prepare`). -3. Fix **product code** in that package (TypeScript errors, missing exports, etc.). -4. Re-run **`yarn lerna:prepare`** — same command, same cwd. -5. Do **not** “verify tooling” with `yarn workspace … prepare`, `yarn bin …`, or package-scoped `yarn run build` — Yarn 4 uses **different PATH** for those invocations ([genversion trap](#genversion--prepare-paths)). - -## Forbidden (always) - -| Command | Why | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | -| `yarn workspace @react-native-firebase/* prepare` (and variants) | Not canonical; breaks root devDependency binary resolution | -| `cd packages/ && yarn prepare` / `yarn run build` | Same trap; not the postinstall / lerna code path | -| `yarn google-java-format`, bare `google-java-format`, `npx google-java-format`, `google-java-format -i` | Invented format entrypoints — **only** `yarn lint:android` for **Java** | -| `ktlint`, `npx ktlint`, invented `yarn` ktlint scripts, `cd tests/android && ./gradlew ktlintFormat` | Invented Kotlin format — **only** repo-root `./gradlew ktlintFormat` | -| `npm install` (any cwd) / `yarn` / `yarn install` only in `tests/` for monorepo deps | Root `yarn` applies patches and workspace links; tests-only install is insufficient | -| Ad-hoc `./gradlew …` outside allowlisted yarn scripts (`tests:android:unit`, `tests:android:build`, `tests:android:post-e2e-coverage`, `tests:android:test:jacoco-report`, etc.) and outside repo-root `./gradlew ktlintFormat` | Wrong task / cwd / report path; invents CI that does not match Codecov | -| Ad-hoc `xcodebuild test` / CocoaPods `test_spec` / `tests/ios/testingTests` as the iOS unit gate | Misses LCOV merge — **only** `yarn tests:ios:unit` ([IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1)) | -| Ad-hoc `ruby packages/app/__tests__/…_test.rb` (or bare runner) as the validation gate | Misses SimpleCov / suite discovery — **only** `yarn tests:ios:ruby` | -| Ad-hoc `expo prebuild`, `xcodebuild`, `cd test-expo && tsc`, or `cd test-expo && …` as a test-expo link, typecheck, or launch gate | **Only** `yarn test-expo:ios:link` / `yarn tsc:compile:test-expo` from repo root — not Detox / `yarn tests:*` / `yarn test-rn-bare:ios:build` | -| Ad-hoc `pod`, `xcodebuild`, or `cd test-rn-bare && …` as the RN CLI prebuilt RNCore iOS build gate | **Only** `yarn test-rn-bare:ios:build` from repo root — not Detox / `yarn tests:*` / `yarn test-expo:ios:link`. Ad-hoc `pod` / `xcodebuild` stay never-use | -| `react-native init`, `npx @react-native-community/cli init`, `npx react-native init` | Not on the allowlist — seed checked-in RN CLI trees via [template gotcha](#react-native-community-template-checked-in-rn-cli-ios) | -| `yarn jet`, `npx jet`, `cd tests && yarn jet …` | [E2e agent rule](running-e2e.md#agent-rule-read-first) | -| `detox test`, bare `detox`, `cd tests && detox …` | E2e agent rule | -| bare `bundle install` at repo root | Use **`yarn ruby:install`** or root **`yarn`** (`postinstallDev` includes ruby:install) | -| Ad-hoc Metro / emulator start | Use `yarn tests:packager:jet` (iOS/Android) or `yarn tests:macos:packager:jet` (macOS), `yarn tests:emulator:start` ([running e2e](running-e2e.md#rules)) | -| Direct `xcrun simctl delete` / `erase` / `rename` / `create` (and `simctl delete all` / `unavailable`, `simctl shutdown all`) as e2e device management | Destroys devices other worktrees, repos, or operators may be mid-run on. Provision with `yarn tests:e2e:setup-ios-sims` (create/reuse-only), free with `yarn tests:e2e:release --devices` (shutdown only). Legacy-simulator removal is human-operator — [migration](running-e2e.md#ios-slot-simulator-migration) | -| Spawn / PATH probes to “test” Jet or genversion | Log triage only; fix product code and re-run canonical command | - -## Known traps - - - - - -### Cursor Shell sandbox / permissions - -When a Shell command returns with **no exit status** (e.g. "execution backend unavailable") under default sandbox permissions, retry the **same** canonical command with `required_permissions: ["all"]` — do **not** invent an alternate command because the sandboxed attempt failed to start. - -`yarn test-expo:ios:link` needs unrestricted network on the first attempt. Expo prebuild updates the CocoaPods repo from `cdn.cocoapods.org`, which returns 403 under the default agent sandbox. Request full network up front. A 403 is not a product failure. - -Local e2e (`yarn tests:*:test-cover`), the packager, emulator start, native builds, and host pre-flight probes that need real devices/simulators typically need unrestricted permissions on this host. A "no exit status" result on those commands is a sandbox artifact, not evidence the run failed or is incomplete — see [running e2e § running one iteration](running-e2e.md#running-one-iteration) for checking the tee log footer before concluding anything from a missing exit code. Startup-fail markers on the tee are immediate hard infra — [startup fail-fast poll](running-e2e.md#startup-fail-fast-poll) (`TELNET` / `emulator-16` / `ReactContext is null` / serial leftover `:12007`+`5554`; idle APP_STATUS is healthy; `currentStatus` / status-query timeout is latency, not a wave-kill). - - - -### Agent shell is zsh (`PIPESTATUS` is bash-only) - -`${PIPESTATUS[0]}` is **bash**. zsh spells it `${pipestatus[1]}` (1-indexed), and the bash form expands to the **empty string** — `yarn 2>&1 | tee /tmp/x.log; echo "EXIT=${PIPESTATUS[0]}"` prints `EXIT=` whether the target passed or failed. Tee-to-log is the normal pattern for long-running targets and every gate wants a per-command exit code, so a real exit 1 can be recorded as a pass and turn into a false finding. Use `${pipestatus[1]}`, or run the command bare and read `$?`. - -### genversion / prepare paths - -- **`genversion` exists** at root `node_modules/.bin` after `yarn`. -- **`yarn lerna:prepare`** (and `yarn install` → `postinstallDev`) runs prepare via Nx with root toolchain on PATH → bare `genversion` in package `"build"` scripts **works**. -- **`yarn workspace … prepare`** or **`cd packages/foo && yarn run build`** does **not** expose root-only devDependencies → `command not found: genversion`. That is **not** corrupt `node_modules`; do **not** patch scripts with `yarn run -T genversion` unless deliberately changing repo policy on `main`. - -### Jet - -- **`yarn jet --help`** working or failing in `tests/` is **not** a valid e2e or install gate. -- Jet is started **internally** by `yarn tests::test-cover`. Stale `:8090` → [pre-flight recovery](running-e2e.md#pre-flight-recovery), then re-run the same `:test-cover` command. -- Metro `EADDRINUSE` on `:8081` from `yarn tests:packager:jet-reset-cache` or `yarn tests:macos:packager:jet-reset-cache` → [packager reset-cache](running-e2e.md#packager-reset-cache-eaddrinuse) (free `:8081`, then the same yarn target). Not the `:8090` pre-flight kill. Do **not** use the mobile packager for macOS Jet (or vice versa). - - - -### Android Java format - -- There is **no** `yarn google-java-format` script. Invented `google-java-format` / `npx google-java-format` invocations are forbidden. -- **Canonical:** `yarn lint:android` (repo root) — wraps `google-java-format --set-exit-if-changed --replace` on **Java** under `packages/*/android/src` and fails if the tree would change. Outside a git work tree (for example an rsync copy of the checkout) it skips the `git diff` step and relies on the formatter exit alone. It does **not** format Kotlin. -- **Needs JDK 21+:** the bundled `google-java-format` 1.35.0 jar runs on whatever `java` is first on `PATH` (not Gradle's JDK). On JDK < 21 it fails many files, untouched ones included, with `NoClassDefFoundError: com/sun/tools/javac/tree/JCTree$JCAnyPattern`. This is a host JDK problem, not a formatting failure. Put a JDK 21 first on `PATH` for the same command, e.g. `J21="$(/usr/libexec/java_home -v 21 -F)" && PATH="$J21/bin:$PATH" yarn lint:android` (macOS; stops if no JDK 21 is found. Without `-F`, `java_home` returns another installed JDK instead of failing; a Homebrew `/opt/homebrew/opt/openjdk@21/bin` works as the `PATH` entry instead). - - - -### Android Kotlin format - -- **Canonical:** repo-root `./gradlew ktlintFormat` (the root wrapper forwards into `tests/android`). Do **not** invent a yarn wrapper, a `ktlint` CLI, or `cd tests/android && ./gradlew …`. -- Pass `-PinternalKtlintGitFilter=` with newline-separated **repo-root-relative** paths (`packages//android/**/*.kt`; `tests/android/**/*.kt` when those files are in the diff). The root wrapper remaps that property; do not pass `-PrnfbKtlintGitFilter` to **root** `./gradlew`. Omit or empty filter → **no** `.kt` files formatted. -- Other Gradle tasks stay yarn-only (`tests:android:unit` / `:build` / Jacoco rows). `ktlintFormat` is the Gradle exception, not a license to invent Gradle. - -### Android build / unit / Jacoco - -- **Do not** invent `cd tests && yarn install`, then bare `./gradlew` from an arbitrary cwd. -- Unit: **`yarn tests:android:unit`** only. Runner choice and `@Config` / `sdk` policy: [AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1). -- Merged coverage after e2e: **`yarn tests:android:post-e2e-coverage`** (Codecov path is `jacocoTestReport`, not e2e-only `jacocoAndroidTestReport`) — [coverage design](coverage-design.md). -- Optional explicit merge: **`yarn tests:android:test:jacoco-report`**. - -### iOS XCTest (in-package) - -- **Canonical:** `yarn tests:ios:unit` — discovers `packages/*/ios/*UnitTests/*.xcodeproj`, macOS destination, writes `coverage/ios-unit/lcov.info` and **merges into** `coverage/ios-native/lcov.info` ([IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1); [coverage design](coverage-design.md)). -- **Forbidden as the agent gate:** ad-hoc `xcodebuild test`, CocoaPods `test_spec`, `tests/ios/testingTests` host UI tests. - -### JS lint / Bundler vendor - - - -- `yarn lint:js` is `eslint packages/* test-expo --max-warnings=0`. That already covers `packages/app/__tests__/` and `test-expo/`. Do not invent a second lint entrypoint for `test-expo/`. `scripts/version.js` is not in it. -- After `bundle install --gemfile=packages/app/__tests__/Gemfile`, Bundler follows root `.bundle/config` `BUNDLE_PATH: vendor/bundle` and drops a gitignored tree at `packages/app/__tests__/vendor/`. ESLint `globalIgnores` does not list that path, so lint reports thousands of vendor findings. -- That is local checkout noise, not a product lint failure. CI without that tree stays green. -- Do not invent a delete-vendor command as the lint gate. Do not patch `eslint.config.mjs` to hide it. Root `yarn ruby:install` or root `yarn` is the canonical install path above. - - -### iOS Ruby (SPM helpers) - - - -- **Canonical:** `yarn tests:ios:ruby` — discovers all `packages/app/__tests__/*_test.rb`, SimpleCov → `coverage/ios-ruby/lcov.info`, Codecov flag `ios-ruby`. -- **CI home:** `tests_e2e_ios.yml` (debug + spm) only — not Jest / `tests_e2e_other.yml`. -- **Forbidden as the agent gate:** `ruby packages/app/__tests__/firebase_spm_test.rb` (or any single-suite / bare-ruby invocation). One-off debugging may use bare ruby locally; gate close / handoff evidence must cite the yarn target. -- First-time / Gemfile change: **`yarn ruby:install`** (or root `yarn`, which runs it via `postinstallDev`). Path via committed `.bundle/config`. When `bundle` is not on PATH, the `ruby` on PATH is older than 3.3.1, or `bundle --version` fails (macOS system Ruby 2.6 cannot load the lockfile's Bundler), `yarn ruby:install` **skips with exit 0** and prints one `ruby:install:` line naming why (no setup-ruby required in lint/Jest/Android CI). Host setup: [CONTRIBUTING § Ruby for iOS and macOS work](../../CONTRIBUTING.md#ruby-for-ios-and-macos-work). CI uses `BUNDLE_FROZEN=true bundle install` **before** yarn in e2e/publish workflows; after yarn, `yarn ruby:install` is a no-op (`bundle check` succeeds). Do not `gem update cocoapods xcodeproj`. -- **Host Ruby floor:** `>= 3.3.1`. Ruby **3.3.0** cannot load lockfile `simplecov` **1.1.1** (`anonymous block parameter is also used within block`, CRuby [#20090](https://bugs.ruby-lang.org/issues/20090)). Do **not** downgrade simplecov to paper over it. With rbenv, pin a newer patch (e.g. `RBENV_VERSION=3.3.3`). -- Never `bundle install --gemfile=packages/app/__tests__/Gemfile`. That writes a gitignored vendor tree under `packages/app/__tests__/vendor/` and then `yarn lint:js` explodes. See [JS lint / Bundler vendor](#js-lint-bundler-vendor). -- Blocking when Ruby sources or `*_test.rb` touched: [validation checklist § iOS Ruby](validation-checklist.md#ios-ruby-unit-tests). - -### `@react-native-community/template` (checked-in RN CLI `ios/`) - - - -- **`@react-native-community/template` is not installed by root `yarn`.** It is not a `react-native` dependency, so a green install does **not** put the community template under `node_modules`. -- Seeding or refreshing a **checked-in** RN CLI `ios/` tree (fixture app under the monorepo) after yarn **cannot** assume that package exists. The checked-in vanilla CLI compile fixture is `test-rn-bare/` (closer `yarn test-rn-bare:ios:build`). Do not re-seed it. -- **Workaround:** one-shot pin `@react-native-community/template@` on the fixture package, copy `ios/` + JS entry files from the template into the fixture, then **remove** the pin. Do not leave the template as a durable dependency. -- **Never** `react-native init` / `npx @react-native-community/cli init` / `npx react-native init` — not on the agent allowlist (see [Forbidden](#forbidden-always)). - -### expo-router autolink exclude (`@expo/ui`) - - - -`expo-router` depends on `@expo/ui`. Yarn can resolve a `@expo/ui` that does not compile against the fixture's `expo-modules-core` (`ContentOriginRegistry` / `ShadowNodeProxy`). `test-expo` does not use Expo UI. Keep `expo.autolinking.exclude: ["@expo/ui"]` in `test-expo/package.json`. Do not drop it as unused config. Dropping it makes `yarn test-expo:ios:link` fail at compile (exit 65). - -### Config plugin edits need prepare before the link run - - - -`yarn test-expo:ios:link` prebuilds from the existing `packages/*/plugin/build` and does not rebuild config plugins, so after a `packages/*/plugin/src` edit it can exit 0 on the stale build. Run `yarn lerna:prepare` first, then confirm the generated native file (e.g. `test-expo/ios/testexpo/AppDelegate.swift`) contains the plugin change. - -### Expo sources live only under `test-expo/node_modules` - - - -Root `node_modules` has no `expo`, `@expo/config-plugins` or `expo-build-properties` ([why](#expo-fixture-under-test-expo)). When checking config-plugin behaviour (mod-compiler ordering, `SceneEventForwarder`, `expo-build-properties` mods), read those sources under `test-expo/node_modules/` with read-only file tools. Do not use `node -e` / `node -p` to resolve or inspect them; neither is on the allowlist. - -### Expo fixtures live under `test-expo/` - - - -`.yarnrc.yml` sets `nmHoistingLimits: workspaces`, so the repo root `node_modules` does not hold `expo` or the RNFB symlinks, and its `react-native` is a different version than `test-expo`'s pin. A generated Expo fixture installs nothing and resolves packages by walking up to `test-expo/node_modules`. `lib/make-expo-fixture.sh` therefore refuses an `--out` outside `test-expo/`; `yarn test-expo-fixture:ios:dupes` writes to gitignored `test-expo/.fixtures//`. Do not generate fixtures at the repo root or in `/tmp`. - -### TurboModule codegen - - - -- **`cd packages/ && yarn ios:codegen`** (or `yarn android:codegen`) often fails with **`unknown command 'codegen'`** after a clean `yarn` — `@react-native-community/cli` resolves from the **test app** workspace. -- Package scripts **wipe then regen** the configured `--outputPath` ([NewArch-AD-22](../new-architecture/architecture-decisions.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)). Prefer those yarn scripts when CLI resolution works. -- **Canonical (mobile toolchain from `tests/`):** use each package's `yarn android:codegen` / `yarn ios:codegen` script, which delegates to [`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs). The shared runner wipes the configured output path and invokes the pinned mobile CLI from `tests/`; do not run the CLI manually. RN 0.86 emits `ResultT` natively, so the former inject script is retired ([NewArch-AD-21](../new-architecture/architecture-decisions.md#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--accepted)). -- **CI / library packages:** `yarn codegen:verify`. Library vs test-app codegen (committed trees, `includesGeneratedCode`, git-diff guard, test-app dump gitignore): [NewArch-AD-5](../new-architecture/architecture-decisions.md#newarch-ad-5--commit-generated-code--accepted). Test-app iOS CLI `--outputPath` is `ios` (project base); wipe is `ios/build/generated/ios` plus `tests/ios/Package.swift` and sibling app dumps. -- After **library** regen: commit the generated trees named in NewArch-AD-5, then `:build` + Metro reset-cache before `:test-cover`. - -### fmt / Apple Clang 21 (unpatched React Native) - -- Unpatched RN **0.78** ships fmt **11.0.2**. On Xcode 26 / Apple Clang 21 that fails consteval builds. -- **Canonical fix (macOS 0.78):** root `yarn` applying `tests-macos/patches/react-native+0.78.3.patch` → fmt **12.1.0**. Mobile **0.86.2** already ships fmt **12.1.0**. See [install / patch / fmt gate](#install-patch-fmt-gate-blocking). -- **Trap:** yarn exit **0** does **not** prove a macOS patch landed. If Nx cache-skips `react-native-firebase-tests-macos:prepare` (`patch-package`), fmt stays at **11.0.2**. Durable policy: [MonoTool-AD-12](../monorepo-tooling/architecture-decisions.md#monotool-ad-12--never-nx-cache-prepare-when-the-script-is-patch-package--accepted). **Always** run the fmt `rg` verification before native `:build`. -- **Never** invent Podfile `post_install` fmt hacks, `FMT_USE_CONSTEVAL`, `base.h` patches, or c++17-for-fmt-only as a substitute for a missed install/patch. - -## Command constraints - - - -```text -RNFB agent command policy: okf-bundle/testing/agent-command-policy.md ONLY. -E2e: okf-bundle/testing/running-e2e.md yarn tests:* ONLY. -Expo example + documented-path iOS link (not Detox, build-only): yarn test-expo:ios:link ONLY — never ad-hoc expo prebuild / xcodebuild / cd test-expo; never yarn test-rn-bare:ios:build as that closer. Expo iOS 27 UIScene launch smoke (not Detox): yarn test-expo:ios:launch-smoke ONLY after link in the same checkout — never ad-hoc simctl launch / open -a Simulator / Device Hub. Typecheck: yarn tsc:compile:test-expo ONLY — never cd test-expo && tsc. JS lint is yarn lint:js (already includes test-expo/). Keep test-expo/package.json expo.autolinking.exclude ["@expo/ui"] — #expo-router-autolink-exclude-expo-ui. Per-module duplicate Objective-C class check (generated blank Expo app, build-only): yarn test-expo-fixture:ios:dupes --modules [,…] [--expect-duplicates N | --report-only] ONLY (--modules required; --modules "" = app only) — never ad-hoc expo prebuild / xcodebuild / create-expo-app / npm install in test-expo/.fixtures/; --expect-duplicates N passes only on exactly N duplicates (0: GULNetwork has one owner; N > 0: GULNetwork is duplicated); --report-only excludes --expect-duplicates; flag errors and invalid/duplicate/unpinned module names exit 2 before any build. Both Expo iOS runners wipe their DerivedData before every xcodebuild and refuse empty or unsafe override paths (exit 2); test-expo link, launch smoke, and the fixture runner share RNFB_TEST_EXPO_SPM_PACKAGES (never wiped); /tmp defaults carry a per-worktree repo-path tag — #expo-ios-derived-data. -RN CLI prebuilt RNCore iOS build (not Detox): yarn test-rn-bare:ios:build ONLY — never ad-hoc pod / xcodebuild / cd test-rn-bare; never tests/ e2e; never yarn test-expo:ios:link as that closer. Ad-hoc pod / xcodebuild stay never-use. Dynamic probe (RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1) deletes its DerivedData path before xcodebuild. Evidence from a probe that did not start from an empty DerivedData is invalid. Do not reuse RNFB_TEST_RN_BARE_DERIVED_DATA to save time. A new worktree does not reset ${TMPDIR:-/tmp} DerivedData. RN CLI iOS 27 UIScene launch smoke (not Detox): yarn test-rn-bare:ios:launch-smoke ONLY after build in the same checkout — never ad-hoc simctl launch / open -a Simulator / Device Hub; never yarn test-expo:ios:launch-smoke as that closer. Dynamic probe launch smoke: run it with the same RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1 immediately after the probe build; it wipes and uses its own RNFB_TEST_RN_BARE_LAUNCH_DERIVED_DATA. After a probe, git checkout -- test-rn-bare/ios/testrnbare.xcodeproj/project.pbxproj before committing. -Never react-native init / npx @react-native-community/cli init — @react-native-community/template is not installed by root yarn; one-shot pin + copy ios/ + JS, then remove pin — #react-native-community-template-checked-in-rn-cli-ios. -Never: yarn workspace prepare, yarn jet, npx jet, cd packages/* && yarn prepare/build for diagnostics. -Never invent format/install: yarn google-java-format, bare/npx google-java-format, npm install, yarn install in tests/ alone — use root yarn first; Java format = yarn lint:android ONLY (not Kotlin). Kotlin format = repo-root ./gradlew ktlintFormat ONLY with -PinternalKtlintGitFilter= (repo-root-relative packages/*/android/**/*.kt and, if touched, tests/android/**/*.kt); never ktlint CLI / npx ktlint / invented yarn ktlint. See #android-kotlin-format. -Never invent Android Gradle: ad-hoc ./gradlew outside yarn tests:android:unit / :build / :post-e2e-coverage / :test:jacoco-report and outside repo-root ./gradlew ktlintFormat; bare detox/jet/metro. -E2e slot devices: yarn tests:e2e:setup-ios-sims / setup-android-avds (create/reuse-only of the exact iOS neutral base; count decimal 1..8). Patched Detox reuses that base or fails when registry-taken (tests/patches/detox+20.51.0.patch via tests prepare; exact slot-0..7). yarn tests:e2e:release --devices shuts down the exact base. Direct check/release --slot=N uses the same 0..effective max guard as export-slot-env. Never direct xcrun simctl create/delete/erase/rename, simctl delete all|unavailable, simctl shutdown all. Legacy RNFB E2E iOS slot-N removal is human-operator only — okf-bundle/testing/running-e2e.md#ios-slot-simulator-migration. -Prepare/install: yarn or yarn lerna:prepare must exit 0 before ANY other command — never parallelize with e2e/Metro/build. -Before native :build: root yarn exit 0 + verify tests/node_modules/react-native/third-party-podspecs/fmt.podspec (and tests-macos copy when building macOS) ≥ 12.1.0 — okf-bundle/testing/agent-command-policy.md#install-patch-fmt-gate-blocking. Before iOS build on a clean checkout: root yarn, then yarn tests:ios:pod:install exit 0. If fmt < 12.1.0: STOP and re-run yarn; never invent Podfile/FMT_USE_CONSTEVAL/c++17 fmt hacks. -Area harness: okf-bundle/testing/running-e2e.md#local-harness-overrides-harnessoverridesjs — copy harness.overrides.example.js to gitignored harness.overrides.js; set modules + RNFBDebug; delete overrides after run. macOS App Check custom-provider e2e needs e2eHelperSecret — capture+merge ONLY via #app-check-e2e-helper-secret (never bare secrets:access; never secrets:set; never CI overwrite-only when modules/RNFBDebug exist; never commit harness.overrides.js). -TurboModule contract test (NewArch-AD-17.1): packages/app/__tests__/nativeModuleContract.test.ts — yarn tests:jest -- packages/app/__tests__/nativeModuleContract.test.ts -Android JVM unit (AndroidTest-AD-1, JUnit-first; omit @Config/sdk unless proven): yarn tests:android:unit — not a substitute for platform e2e. -iOS Ruby (SPM helpers): yarn tests:ios:ruby — never ad-hoc ruby packages/app/__tests__/…_test.rb as the gate. Never bundle install --gemfile=packages/app/__tests__/Gemfile. Host Ruby >= 3.3.1 (not 3.3.0); do not downgrade simplecov. -JS lint vendor flood under packages/app/__tests__/vendor/: local Bundler tree, not product lint. Never invent delete-vendor as the lint gate. See #js-lint-bundler-vendor. -Docs snippet type-check (blocking): yarn docs:tsc:check (DOCS_TSC_ALL=1 prints every failing fence): compiles docs/**/*.mdx js, javascript, jsx, ts, typescript and tsx fences; any failed fence or fence-grammar error exits non-zero. CI Documentation job. Detail: validation-checklist.md#docs-lint-gotchas. Never invent ad-hoc tsc on doc fences instead. -Docs member check (blocking): yarn docs:member:check: compare-types extraInRN names must be mentioned under docs//** except names in DEPRECATED_EXEMPT that are verified @deprecated in package source; runtime functions the usage pages teach must be referenced by the matching test-expo screen. No vertexai screen required. Detail: validation-checklist.md#docs-lint-gotchas. Never invent a second docs↔screen sync gate. -Docs lint: yarn lint:markdown already runs the snippet ESLint config (eslint.docs-snippets.config.mjs) and Prettier over the docs tooling files. Do not point eslintJs.configs.all at doc fences. -GitHub state (read-only): gh pr view/list/checks/diff, gh run list/view, gh issue view/list, gh api GET on read endpoints ONLY (needs full_network when sandboxed; GitHub is authoritative for CI check state). Never any gh command that writes (create/edit/merge/close/comment/review/ready, pr checkout (mutates the local working tree), run rerun/cancel, workflow run, release, repo mutations, auth, secret, gh api POST/PUT/PATCH/DELETE, -X other than GET, or -f/-F write fields). -Agent shell is zsh: capture exit codes with ${pipestatus[1]} or bare $? — ${PIPESTATUS[0]} is bash-only and expands to empty. See #agent-shell-is-zsh. -On failure: fix product code (or re-run yarn for patch miss), re-run the same canonical command. -Gate close / push: return [validation evidence package](validation-checklist.md#validation-evidence-package) and [coverage evidence package](coverage-design.md#coverage-evidence-package) when lib/native/Ruby helpers touched — required before commit or publication ([change authoring § validation evidence](change-authoring-workflow.md#validation-evidence-blocking)). -``` - - - -**Physical-device runs:** builds and runs on physical iOS or Android devices are not on the allowlist; run them only with explicit user authorization. +The allowlist is one registry split by domain. A command is allowed only when it is a row in one of these files, or linked from one as canonical: + +| Intent | Registry file | +| --- | --- | +| Install, prepare, TS/JS validation, JS lint, test-expo typecheck, read-only `gh`, `yarn frog` | [core](commands/core.md#canonical-registry) | +| Docs lint, docs snippet type-check, docs member check | [docs](commands/docs.md#canonical-registry) | +| Android Java / Kotlin format, Ruby lint and unit tests, Android JVM and iOS XCTest unit tests, TurboModule codegen | [native](commands/native.md#canonical-registry) | +| `test-expo/` link, launch smoke, duplicate ObjC class check; `test-rn-bare/` build and launch smoke | [fixtures](commands/fixtures.md#canonical-registry) | +| E2e and coverage, pre-flight, slot devices, slotted parallel, coverage post-process, Detox cache, CocoaPods provisioning, App Check helper secret | [e2e](commands/e2e.md#canonical-registry) | + +Never run: [forbidden (always)](commands/forbidden.md). Before any native `:build`: [install / patch / fmt gate](commands/native-build-gate.md#install-patch-fmt-gate-blocking). + +## Files + +Content moved from this file into the files below. Headings and anchors keep their names in the new file; each old anchor sits on the line under its new home, so old `#links` still land here and point on. + +- [Agent commands: e2e and coverage](commands/e2e.md): Allowlisted e2e, pre-flight, slot, coverage post-process, Detox cache, CocoaPods provisioning, and App Check helper secret commands. + +- [Agent commands: Expo and RN CLI fixtures](commands/fixtures.md): Allowlisted test-expo link, launch smoke, duplicate ObjC class check, test-rn-bare build and launch smoke, DerivedData rules, and fixture traps. + +- [Agent commands: core](commands/core.md): Allowlisted install, prepare, TS/JS validation, JS lint, read-only GitHub CLI and friction-log commands, prepare ordering, and shell traps. + +- [Agent commands: install / patch / fmt gate](commands/native-build-gate.md): Blocking install, patch, fmt and CocoaPods checks before any native :build, and the fmt / Apple Clang 21 trap. + +- [Agent commands: forbidden (always)](commands/forbidden.md): Commands agents must never run, with the reason and the canonical replacement. + +- [Agent commands: native lint, unit tests, codegen](commands/native.md): Allowlisted Android Java/Kotlin format, iOS Ruby lint and tests, Android JVM and iOS XCTest unit tests, TurboModule codegen, and their traps. + +- [Agent commands: constraints block](commands/constraints.md): Condensed plain-text constraints block for pasting into agent prompts; each line is owned by a section of the command files. + +- [Agent commands: docs](commands/docs.md): Allowlisted docs lint, docs snippet type-check, and docs member check commands. ## Related docs -| Topic | Owner | -| --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | -| E2e commands, pre-flight, tiers | [running-e2e.md](running-e2e.md) | -| App Check e2e helper secret (local access/merge) | [§ App Check e2e helper secret](#app-check-e2e-helper-secret) — commands; field/skip semantics [running e2e § macOS App Check](running-e2e.md#macos-app-check-helper-secret); Secret Manager **set**/deploy [firebase-testing-project](firebase-testing-project.md#e2e-cloud-helper-callables) | -| Expo example + documented-path iOS **link** (not Detox, build-only) | This file — registry rows `yarn test-expo:ios:link` and `yarn tsc:compile:test-expo`; JS lint is `yarn lint:js`; [autolink exclude gotcha](#expo-router-autolink-exclude-expo-ui); app index [packages/app](../packages/app/index.md); native `RNFB*` discovery [iOS SPM § Expo precompiled linkage repair](../ios-spm-native-imports.md#expo-precompiled-module-linkage-repair) | -| RN CLI prebuilt RNCore iOS **build** (not Detox) | This file — registry row `yarn test-rn-bare:ios:build`; app index [packages/app](../packages/app/index.md) | -| Install / patch / fmt / iOS Pods before `:build` | [§ install / patch / fmt gate](#install-patch-fmt-gate-blocking) | -| Test-app RN / CLI pins (mobile + Expo/RN CLI fixtures share the mobile line; macOS separate) | [test-app-dependency-pins.md](test-app-dependency-pins.md) | -| Validation sequence | [validation-checklist.md](validation-checklist.md) | -| Android JVM unit ADR | [AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1) | -| iOS XCTest unit ADR | [IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1) | -| iOS Ruby unit / SimpleCov | [coverage design § iOS Ruby](coverage-design.md#ios-ruby-simplecov); [validation checklist § iOS Ruby](validation-checklist.md#ios-ruby-unit-tests) | -| JS lint vs local Bundler vendor | [§ JS lint / Bundler vendor](#js-lint-bundler-vendor) | -| Work types and gates | [change-authoring-workflow.md](change-authoring-workflow.md) | -| Doc / commit policy | [documentation-policy.md](../documentation-policy.md) | +| Topic | Owner | +| --- | --- | +| E2e commands, pre-flight, tiers | [running-e2e.md](running-e2e.md) | +| App Check e2e helper secret (local access/merge) | [§ App Check e2e helper secret](commands/e2e.md#app-check-e2e-helper-secret) — commands; field/skip semantics [running e2e § macOS App Check](e2e/narrowing.md#macos-app-check-helper-secret); Secret Manager **set**/deploy [firebase-testing-project](firebase-testing-project.md#e2e-cloud-helper-callables) | +| Expo example + documented-path iOS **link** (not Detox, build-only) | This file — registry rows `yarn test-expo:ios:link` and `yarn tsc:compile:test-expo`; JS lint is `yarn lint:js`; [autolink exclude gotcha](commands/fixtures.md#expo-router-autolink-exclude-expo-ui); app index [packages/app](../packages/app/index.md); native `RNFB*` discovery [iOS SPM § Expo precompiled linkage repair](../ios-spm-native-imports.md#expo-precompiled-module-linkage-repair) | +| RN CLI prebuilt RNCore iOS **build** (not Detox) | This file — registry row `yarn test-rn-bare:ios:build`; app index [packages/app](../packages/app/index.md) | +| Install / patch / fmt / iOS Pods before `:build` | [§ install / patch / fmt gate](commands/native-build-gate.md#install-patch-fmt-gate-blocking) | +| Test-app RN / CLI pins (mobile + Expo/RN CLI fixtures share the mobile line; macOS separate) | [test-app-dependency-pins.md](test-app-dependency-pins.md) | +| Validation sequence | [validation-checklist.md](validation-checklist.md) | +| Android JVM unit ADR | [AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1) | +| iOS XCTest unit ADR | [IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1) | +| iOS Ruby unit / SimpleCov | [coverage design § iOS Ruby](code-coverage/local.md#ios-ruby-simplecov); [validation checklist § iOS Ruby](validation/native-unit.md#ios-ruby-unit-tests) | +| JS lint vs local Bundler vendor | [§ JS lint / Bundler vendor](commands/core.md#js-lint-bundler-vendor) | +| Work types and gates | [change-authoring-workflow.md](change-authoring-workflow.md) | +| Doc / commit policy | [documentation-policy.md](../documentation-policy.md) | diff --git a/okf-bundle/testing/android-architecture-decisions.md b/okf-bundle/testing/android-architecture-decisions.md index af39bac9f5..0df170352c 100644 --- a/okf-bundle/testing/android-architecture-decisions.md +++ b/okf-bundle/testing/android-architecture-decisions.md @@ -59,6 +59,6 @@ java.lang.IllegalArgumentException: Package targetSdkVersion=36 > maxSdkVersion= That exception is a reason **not** to inherit test-app targetSdk on libraries — not a reason to pin `@Config(sdk = 34)` on every Robolectric class. The test **application** named `app` stays at 36 via `ext.appTargetSdkVersion` (a name `applyAndroidVersions()` does not consume). The `subprojects` overlay may still align library `compileSdk` / `minSdk` with the test app so the composite project compiles; it must **not** assign `targetSdkVersion` on those libraries. -**Not a substitute for area e2e:** JVM tests do **not** replace [platform coverage gate](running-e2e.md#platform-coverage-gate-blocking) delivery/integration e2e on platforms where the module loads. Multi-generation races may be proven **primarily** via JVM tests; e2e remains required for load, flush, and native↔JS delivery on those platforms. +**Not a substitute for area e2e:** JVM tests do **not** replace [platform coverage gate](e2e/gates.md#platform-coverage-gate-blocking) delivery/integration e2e on platforms where the module loads. Multi-generation races may be proven **primarily** via JVM tests; e2e remains required for load, flush, and native↔JS delivery on those platforms. **Formatting:** Java = **`yarn lint:android` only**; Kotlin = repo-root **`./gradlew ktlintFormat` only** — [agent command policy](agent-command-policy.md). diff --git a/okf-bundle/testing/authoring/gates.md b/okf-bundle/testing/authoring/gates.md new file mode 100644 index 0000000000..aa7925b281 --- /dev/null +++ b/okf-bundle/testing/authoring/gates.md @@ -0,0 +1,54 @@ +--- +type: Reference +title: 'Change authoring: gates and evidence' +description: 'Gate close conditions, blocking validation evidence per gate, and forbidden shortcuts.' +tags: [testing, workflow, gates, evidence] +timestamp: 2026-12-02T00:00:00Z +--- + +# Change authoring: gates and evidence + +Part of [Change authoring workflow](../change-authoring-workflow.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Gates + +| Gate | Closes when | +| --- | --- | +| `implementation` | `implementation` work type complete — code plus **unit-focused**-tier checks green on **every required platform** when native bridge, **committed `**/generated/**`**, podspec/spec/codegen wiring, macOS TS/runtime path, **or** `packages/*/e2e/**` changed ([platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking); [running e2e § Rules #3](../e2e/rules.md#rules)); [static analysis](../validation/lint.md#lint-and-formatting) green on the diff | +| `coverage_evidence` | [Coverage evidence package](../code-coverage/policy.md#coverage-evidence-package) attached with verdict line — **required** when frozen diff touches `packages/*/lib/**`, native bridge (`packages/*/{android,ios}/**`), **or** `packages/app/**/*.rb`; otherwise `n/a` | +| `review` | `independent-review` complete — **area-focused**-tier checks green on frozen tree; applicable [validation checklist](../validation-checklist.md) rows green (including static analysis); **`coverage_evidence` gate closed** when required; **OKF bundle scan** when `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` are in the frozen tree ([§ OKF bundle review](../validation/okf-review.md#okf-bundle-review)); **every review finding resolved** ([§ quality standards](quality-standards.md#quality-standards)) | +| `commit` | Durable commit exists for the item **after** `implementation`, `coverage_evidence` (when required), and `review` gates closed with [recorded evidence](#validation-evidence-blocking). When those OKF/`AGENTS.md`/`CONTRIBUTING.md` files changed, close only after the frozen scan. **Fix** OKF contract violations before **`git commit`** — the frozen scan reports only | + +**Trust rule:** Code on disk or in git with `review` still **open** is unverified until `independent-review` closes the gate. + +Follow-up **splits by what failed** ([§ frozen tree](review-and-commit.md#frozen-tree), [§ quality standards](quality-standards.md#quality-standards)): product/tests/lint → **`implementation`**; `okf-bundle/` / `AGENTS.md` / `CONTRIBUTING.md` → **`documentation`** then another frozen `independent-review`. Do not send every finding to `documentation`. + + + +### Validation evidence (blocking) + +Gates close **only** when **recorded evidence** shows the required validation tier ran and passed. Assumed green, summaries without exit codes, or "tests passed earlier" without a log path **do not** close a gate. + +| Gate | Minimum evidence (record in work-queue notes or review handoff) | +| --- | --- | +| **`implementation`** | Prepare/tsc/jest **exit codes**; when `packages/app/**/*.rb` or `packages/app/__tests__/*_test.rb` touched: **`yarn tests:ios:ruby` exit 0** + `coverage/ios-ruby/lcov.info` ([validation checklist § iOS Ruby](../validation/native-unit.md#ios-ruby-unit-tests)); when native bridge, **`packages/*/ios/generated/**` / `packages/*/android/**/generated/**`**, podspec/spec/codegen wiring, macOS runtime, **or** `packages/*/e2e/**` touched: **e2e pass count per required platform** + log path (e.g. `/tmp/rnfb-e2e-*.log`) — package e2e specs require the same [platform coverage](../e2e/gates.md#platform-coverage-gate-blocking) matrix even with no native hunk for that OS; **`yarn codegen:verify` alone does not close this**; [lint and formatting](../validation/lint.md#lint-and-formatting) evidence (by-tree scripts; exit 0) | +| **`coverage_evidence`** | When lib/native bridge **or** `packages/app/**/*.rb` touched: full [coverage evidence package](../code-coverage/policy.md#coverage-evidence-package) at `.agents/reports//coverage-evidence.md` (or work-queue notes) including **verdict line**; post-process native artifacts after fresh e2e ([coverage design § reading per-file](../code-coverage/local.md#reading-per-file-coverage-locally)); Ruby: [§ iOS Ruby SimpleCov](../code-coverage/local.md#ios-ruby-simplecov) | +| **`review`** | Frozen-tree re-run of area-focused checklist; [lint and formatting](../validation/lint.md#lint-and-formatting) evidence (check-only by-tree); **`coverage_evidence` gate closed** when required (native, **`**/generated/**`**, `packages/*/lib/**` bridge code, **or** `packages/app/**/*.rb`); **OKF bundle scan report** when `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` in the frozen tree ([§ OKF bundle review](../validation/okf-review.md#okf-bundle-review)); compare:types row for touched registered package; e2e evidence must include [services checkout ownership](../e2e/preflight.md#services-checkout-ownership-blocking) when platforms ran | +| **`commit`** | Prior gates closed **with evidence**; no `.only` / harness overrides staged; OKF contract violations **fixed before `git commit`** when those files changed (frozen scan was report-only) | +| **Publication** (`git push`, force-push, PR refresh) | **`review` gate closed on the exact commits being published**; evidence still valid (no product edits since last area-focused run) | + +**Investigate before close:** Any coverage plateau, parity asymmetry, or review finding gets **root-cause analysis** — add tests, delete dead code, or record an [acceptable exception](quality-standards.md#acceptable-exceptions) with evidence. Do not label gaps "informational" or "defensive" without wire/runtime proof. + + + +### Forbidden shortcuts + +- **`git commit`** while the current work type's validation tier is incomplete or evidence is missing — including **`coverage_evidence` gate open** when lib/native bridge touched. +- **Jet NYC `text-summary` after narrowed e2e** as coverage proof for native or `packages/*/lib/**` changes — it measures remapped TS only; use Jacoco/lcov on **changed files** ([coverage design § anti-patterns](../code-coverage/policy.md#anti-patterns-not-coverage-evidence)). +- **`git push` / force-push / PR update** claiming remediation or review-green **without** fresh area-focused evidence after the last product edit on the published commits. +- **History rewrite** (rebase, amend stack) **without** re-running validation for the rewritten scope — prior green results are **invalid**. +- **Self-accepted** parity or coverage gaps — only [acceptable exceptions](quality-standards.md#acceptable-exceptions) with user confirmation or intractability evidence in durable OKF (e.g. parity registry row). +- **`yarn codegen:verify` (or scripts/OKF-only static checks) instead of platform e2e** when committed `packages/*/ios/generated/**`, `packages/*/android/**/generated/**`, native shells, podspecs, or TurboModule specs changed — [running e2e § Rules #3](../e2e/rules.md#rules) / [platform coverage](../e2e/gates.md#platform-coverage-gate-blocking). +- **Pre-flight that only checks ports/HTTP** while Metro or Firebase emulators belong to another worktree — [services checkout ownership](../e2e/preflight.md#services-checkout-ownership-blocking). + +Publication is not a separate work type; it follows the same evidence bar as `review` + `commit`. diff --git a/okf-bundle/testing/authoring/implementation.md b/okf-bundle/testing/authoring/implementation.md new file mode 100644 index 0000000000..8bbbf8cc21 --- /dev/null +++ b/okf-bundle/testing/authoring/implementation.md @@ -0,0 +1,82 @@ +--- +type: Reference +title: 'Change authoring: implementation pass' +description: 'Host rule, implementation inner loop, platform SDK bridge contracts, e2e diagnosis escalation, and harness narrowing per tier.' +tags: [testing, workflow, implementation] +timestamp: 2026-12-02T00:00:00Z +--- + +# Change authoring: implementation pass + +Part of [Change authoring workflow](../change-authoring-workflow.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Host rule + +On a shared dev host during change authoring: + +- One unslotted `:test-cover` at a time — never overlap **unit-focused**-tier and **area-focused**-tier runs. Slotted cross-platform concurrency (distinct worktrees/ports/devices): [running e2e § parallel topology](../e2e/environment.md#parallel-e2e-topology). +- Every run starts from [running e2e § pre-flight](../e2e/preflight.md#pre-flight-is-the-host-clear-to-start) (host-clear probes, services ready, **[checkout ownership](../e2e/preflight.md#services-checkout-ownership-blocking)**, harness tier). +- Use only [canonical e2e commands](../e2e/rules.md#rules). Startup-fail markers → [startup fail-fast poll](../e2e/startup-fail-fast.md#startup-fail-fast-poll) (do not wait the full `launchApp` timeout). Stalled runs → [stalled run detection](../e2e/recovery.md#stalled-run-detection). + +## `implementation` inner loop + +```mermaid +flowchart TD + P0[Pre-flight: host clear, services, harness tier] + P1[Edit product code + tests] + P2[Jest — package or scoped paths] + P3{Native touched?} + P3 -->|no| P4[macOS e2e when TS/runtime path] + P3 -->|yes| P5["native rebuild + platform e2e"] + P4 --> P6{Green?} + P5 --> P6 + P6 -->|no| P1 + P6 -->|yes| STATIC[Static analysis — validation checklist § lint] + STATIC --> DONE([Close implementation gate]) + P0 --> P1 +``` + +**Host rule:** one `:test-cover` at a time; never overlap **unit-focused** and **area-focused** tiers on one host ([§ host rule](#host-rule)). + +**Static analysis before handoff:** Before closing the **`implementation`** gate, run the [validation checklist § lint and formatting](../validation/lint.md#lint-and-formatting) rows that match the diff. Fix violations in product code — do not hand off with lint failures. Commands live only in that section. + +Step detail: [running e2e § unit-focused iteration loop](../e2e/gates.md#unit-focused-tier-iteration-loop). + + + +### Platform SDK bridge contracts (blocking) + +Before changing native bridge code that calls a **platform SDK** (Firebase Android/iOS, OS APIs, vendor SDKs, etc.): + +1. **Read each platform's official API signature and docs independently** — do not assume Android, iOS, and Web behave the same because the RNFB bridge presents a unified JavaScript surface. +2. **Verify null vs empty string** — many SDKs treat absent values (`null`/`nil`) and empty strings (`""`) differently; map bridge fields to the SDK parameter the docs specify for "absent" values. +3. **Do not apply defensive parity** — fixing platform A does not justify the same change on platform B without checking B's contract (e.g. `@Nullable` vs `nonnull`, optional vs required). +4. **Record evidence** — link or cite the reference URL / header signature in the work queue note or triage report when the fix is native-only on one platform. + + + +### E2e diagnosis escalation + +When **`unit-focused`** e2e fails and product cause is unclear: + +1. Confirm [pre-flight](../e2e/preflight.md#pre-flight-is-the-host-clear-to-start) was complete ([prepare completion gate](../e2e/preflight.md#prepare-completion-gate-blocking) when `lib/**` changed, host-clear probes, services, harness overrides, **`RNFBDebug: true`** via overrides). +2. If the **same failure repeats** on back-to-back runs with no assertion progress and the host is known clean → **sub-suite narrow** ([running e2e § fail-fast](../e2e/narrowing.md#fail-fast-rnfbdebug-and-sub-suite-narrowing)): one spec file or `describe.only` on the failing band (e.g. aggregate `count()` / `average()` / `sum()` only). Still **unit-focused**; never commit narrowing. +3. If sub-suite runs still fail without actionable assertion text → add **temporary native instrumentation** (NSLog, `adb logcat` tags, etc.) on the code path under test; use [running e2e § diagnosing hangs](../e2e/recovery.md#diagnosing-hangs) for log commands. **Remove instrumentation before `commit`** and before **`area-focused`** gate closure on a frozen tree. +4. Do not treat Jet WS disconnect / orchestration timeout alone as product failure — [stalled run detection](../e2e/recovery.md#stalled-run-detection) and pre-flight recovery first. + +This escalation is general change authoring. Work queues record outcomes; they do not restate this loop. + +## Harness narrowing + +**Before the first `:test-cover` at `unit-focused` or `area-focused` tier:** create local [`tests/harness.overrides.js`](../../../tests/harness.overrides.example.js) even when the branch commit has full harness — [running e2e § local harness overrides](../e2e/narrowing.md#local-harness-overrides-harnessoverridesjs). Set `modules` to the package area and **`RNFBDebug: true`**. Full app load is **`full`** tier only (delete overrides file). + +| Kind | `implementation` (**unit-focused**) | `independent-review` (**area-focused**) | `pre-merge-validation` (**full**) | `commit` | +| --- | --- | --- | --- | --- | +| **Area narrowing** | Required before `:test-cover` (overrides file) | Required before `:test-cover` | Delete overrides — all modules | Never commit overrides | +| **`RNFBDebug: true`** | Required in overrides before `:test-cover` | Required in overrides before `:test-cover` | Delete overrides / `false` | Never | +| **Single-test** (`.only`) | Allowed (diagnosis) | Revert | Revert | Never | +| **Single-suite** (`describe.only` / one spec file) | Allowed (diagnosis only — [escalation](#e2e-diagnosis-escalation)) | Revert | Revert | Never | + +Package workflows define **which module/spec** to load (e.g. Firestore → [pipeline implementation workflow § narrowing](../../packages/firestore/pipeline-implementation-workflow.md#pipeline-area-harness)). + +**Sanity check:** pass counts must match loaded scope — not full-app totals ([running e2e § gate](../e2e/gates.md#harness-narrowing-gate-blocking)). diff --git a/okf-bundle/testing/authoring/loop.md b/okf-bundle/testing/authoring/loop.md new file mode 100644 index 0000000000..18b19488de --- /dev/null +++ b/okf-bundle/testing/authoring/loop.md @@ -0,0 +1,103 @@ +--- +type: Reference +title: 'Change authoring: loop, work types, tiers' +description: 'Primary change authoring loop, work type table, validation tier summary, and package extensions.' +tags: [testing, workflow, work-types] +timestamp: 2026-12-02T00:00:00Z +--- + +# Change authoring: loop, work types, tiers + +Part of [Change authoring workflow](../change-authoring-workflow.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Primary loop + +```mermaid +flowchart TD + START([Pick change scope]) --> GA{Need feasibility /
semantics check?} + GA -->|yes| GAP["gap-analysis
tier: none"] + GA -->|no| BC{Need before snapshot
or area-focused e2e baseline?} + GAP --> BC + + BC -->|yes| BASE["baseline-capture
tier: area-focused"] + BC -->|no| IMPL + BASE --> IMPL + + IMPL["implementation
tier: unit-focused
Jest + narrow e2e loop"] + IMPL --> IG{implementation gate
green?} + IG -->|no| IMPL + IG -->|yes| DOC + + DOC{User-facing or
OKF durable updates?} + DOC -->|yes| DOCS["documentation
tier: none"] + DOC -->|no| REV + DOCS --> REV + + REV["independent-review
tier: area-focused
frozen tree"] + REV --> RG{all findings
resolved?} + RG -->|product / tests / lint| IMPL + RG -->|OKF / AGENTS / CONTRIBUTING only| DOCS + RG -->|yes| COMMIT + + COMMIT["commit
tier: none"] + COMMIT --> PM{Branch ready
to merge?} + PM -->|yes| FULL["pre-merge-validation
tier: full"] + PM -->|no| END([Hand off / next item]) + FULL --> END +``` + +## Work types + +| Work type | When | Validation tier | Product edits | Commit | +| --- | --- | --- | --- | --- | +| `gap-analysis` | Unclear feasibility, export shape, platform support | none | read-only | no | +| `baseline-capture` | Need before metrics or area-focused e2e on the item | `area-focused` | harness narrow OK locally | no | +| `implementation` | Author fix/feature + tests | `unit-focused` | yes | no | +| `documentation` | Promote user docs + durable OKF + `AGENTS.md` + `CONTRIBUTING.md` on the **same change set**, **before** `independent-review`. Does **not** run the OKF scan. When `docs/**` is in the change set, record [lint:docs-links](../validation/docs-lint.md#docs-page-link-check) evidence **here** (with markdown/spellcheck) — missing that row is a **serious** review finding | none | those files only | no | +| `independent-review` | Verify frozen diff. When the frozen tree includes `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md`, this pass **is** the [OKF bundle scan](../validation/okf-review.md#okf-bundle-review). When `docs/**` is in the frozen tree, confirm [lint:docs-links](../validation/docs-lint.md#docs-page-link-check) exit **0** is in evidence — absence is **serious** | `area-focused` | no — [frozen tree](review-and-commit.md#frozen-tree) except revert `.only` | no | +| `commit` | Gates closed for the item; **staging only** | none | staging only | yes | +| `pre-merge-validation` | Branch merge gate | `full` | revert narrowing first | no | + +**Commands per work type:** [validation checklist](../validation-checklist.md) — link only; do not duplicate here. + +## Validation tiers + +Tier id strings: [iteration vocabulary § validation tier identifiers](../iteration-vocabulary.md#validation-tier-identifiers). + +```mermaid +flowchart LR + subgraph unitFocused ["unit-focused — implementation"] + F1[Area harness narrowing required] + F2[Jest + package-scoped tests] + F3[".only OK locally"] + F4[Fast e2e subset] + F5[Never commit narrowing or .only] + end + + subgraph areaFocused ["area-focused — baseline-capture / independent-review"] + A1[Area harness narrowing required] + A2[Full loaded package spec] + A3[No .only] + A4[Frozen tree for review] + end + + subgraph full ["full — pre-merge-validation"] + P1[Revert all narrowing] + P2[All modules / full app] + P3[Once per branch before merge] + end +``` + +E2e scope, pre-flight, and harness gate: [running e2e § agent rule](../running-e2e.md#agent-rule-read-first) (canonical commands only), [validation tiers](../e2e/gates.md#e2e-validation-tiers-unit-focused--area-focused--full), [harness narrowing gate](../e2e/gates.md#harness-narrowing-gate-blocking). + +**Command rule:** Agents run **only** [agent command policy](../agent-command-policy.md) allowlisted commands for install, prepare, and validation — no improvised `yarn workspace … prepare`, `yarn jet`, or package-scoped build probes. + +## Package extensions + +| Package / area | Adds to this loop | +| --- | --- | +| Firestore Pipelines | Compare-types gap pick, serialization matrix, `Pipeline.e2e.js` setup, coverage snapshots — [pipeline implementation workflow](../../packages/firestore/pipeline-implementation-workflow.md) | +| TurboModules | Durable decisions — [New Architecture ADR](../../new-architecture/architecture-decisions.md) / [index](../../new-architecture/index.md). Codegen commands: [agent command policy](../commands/native.md#turbomodule-codegen) | +| Other packages | `okf-bundle/packages//` index when a workflow exists | + +Ephemeral coordination (gate rows, `next_work_type`, `commit_subject`) lives in **work queues only** — do not paste gate rows into this file. How to stage those fields: [§ commit](review-and-commit.md#commit). diff --git a/okf-bundle/testing/authoring/quality-standards.md b/okf-bundle/testing/authoring/quality-standards.md new file mode 100644 index 0000000000..5555da329c --- /dev/null +++ b/okf-bundle/testing/authoring/quality-standards.md @@ -0,0 +1,52 @@ +--- +type: Reference +title: 'Change authoring: quality standards' +description: 'Acceptable exceptions, review findings resolution bar, and language port observable contracts.' +tags: [testing, workflow, review, quality] +timestamp: 2026-12-02T00:00:00Z +--- + +# Change authoring: quality standards + +Part of [Change authoring workflow](../change-authoring-workflow.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Quality standards + +Two exception-gated authoring standards apply to every item — [acceptable exceptions](#acceptable-exceptions) and [review findings](#review-findings--resolve-do-not-defer). Both share the same narrow exception set (the only things that may be documented and tracked instead of fixed). [Language port observable contracts](#language-port-observable-contracts) is an additional domain application rule for port work, not a third exception gate. + + + +### Acceptable exceptions + +Only two things may be documented and tracked instead of fixed. **Both require the user's explicit acceptance and confirmation plus a recorded rationale** — neither exception may be granted without that, and the item stays tracked until resolved. + +1. **Intractable-limitation bar.** The gap or firebase-js-sdk divergence is caused by an intractable technical limitation of the language, platform SDK, compiler, or toolchain, shown with evidence — e.g. a compiler/codegen-expanded branch that is provably unreachable, or a native SDK that does not expose the capability, cited by version. +2. **User-accepted deferral.** The gap is addressable, but the user explicitly defers it with a documented rationale — e.g. it needs architectural design or human review not available now, or the compute cost is not currently justified. + +Anything else is drift or a defect, never a self-justifying exception: + +- **If code can be authored, a test that exercises it can be authored** — otherwise it is dead code; delete it, do not document it. +- **A divergence with no accepted exception is drift** — align to firebase-js-sdk and remove any config entry. +- Convenience, time pressure, "harmless", "low-value", or "low-risk" carry weight **only** through an explicit user-accepted deferral (2), never on an agent's own authority. + + + +### Review findings — resolve, do not defer + +`independent-review` classifies findings **critical / serious / minor / nit**. The **`review` gate closes only when every finding — including minor and nit — is resolved by a fix**, unless the finding is covered by one of the two [acceptable exceptions](#acceptable-exceptions). Do **not** defer a finding without that exception: "green with minors" is not green, and parity, quality, and coverage gaps are cheapest to fix while the diff is fresh. + +A finding covered by an accepted exception is recorded — with evidence or the user's rationale — and tracked, not silently dropped. A finding that is neither fixed nor covered by an accepted exception follows [§ frozen tree](review-and-commit.md#frozen-tree): product/tests/lint → **`implementation`**; `okf-bundle/` / `AGENTS.md` / `CONTRIBUTING.md` → **`documentation`** then another frozen `independent-review`. + +Domain applications reference this section rather than restating it: + +- **Coverage completion:** [coverage design § expectations](../code-coverage/policy.md#coverage-expectations-policy). +- **Type parity / API drift:** [compare-types justification bar](../../../.github/scripts/compare-types/README.md#justification-bar). + + + +### Language port observable contracts + +When porting ObjC/C++/Java to Swift/Kotlin, or writing unit tests for such a port, assert **pre-port observable product contracts** — the behavior callers already relied on — not incidental Foundation/JDK return shapes or host-specific quirks. + +- Prefer key-absence and documented API/bridge behavior over platform return-shape details (for example nil vs empty dictionary) when the pre-port code never asserted that shape. +- Do not promote host XCTest/JUnit or Simulator/JVM environment quirks into product requirements. diff --git a/okf-bundle/testing/authoring/review-and-commit.md b/okf-bundle/testing/authoring/review-and-commit.md new file mode 100644 index 0000000000..9fe7cde37e --- /dev/null +++ b/okf-bundle/testing/authoring/review-and-commit.md @@ -0,0 +1,57 @@ +--- +type: Reference +title: 'Change authoring: frozen review and commit' +description: 'Frozen tree rules, independent-review steps, and the commit pass.' +tags: [testing, workflow, review, commit] +timestamp: 2026-12-02T00:00:00Z +--- + +# Change authoring: frozen review and commit + +Part of [Change authoring workflow](../change-authoring-workflow.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Frozen tree + +Required for **`independent-review`** and for any `:test-cover` run that closes the **`review`** gate: + +- **Report/check-only** except reverting `.only`. +- No edits to `packages/**`, `tests/**` (except reverting `.only`), `okf-bundle/` **reference** docs, `AGENTS.md`, or `CONTRIBUTING.md` during the run. +- Wait for or cancel in-flight runs before editing again. + +Keep **`implementation`**, **`documentation`**, and **`independent-review`** in separate passes. Do **not** add OKF / `AGENTS.md` / `CONTRIBUTING.md` after a frozen review without another `independent-review`. E2e enforcement during runs: [running e2e § rules](../e2e/rules.md#rules). + +Follow-up **splits by what failed**: + +| Failed in | Next work type | +| --- | --- | +| Product, tests, or lint | `implementation` (then `documentation?`, then frozen scan) | +| `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` | `documentation` then another frozen `independent-review` | + +Do not send every finding to `documentation`. + +## `independent-review` + +On a **frozen tree**: + +1. Revert all `.only`. +2. Keep area narrowing; run **area-focused**-tier e2e for loaded package spec(s) on [**every required platform**](../e2e/gates.md#platform-coverage-gate-blocking) (serial; pre-flight each run). +3. Run applicable [validation checklist](../validation-checklist.md) rows — **blocking:** [static analysis § lint and formatting](../validation/lint.md#lint-and-formatting) (frozen: check-only by-tree); `yarn reference:api` when public surface changed. For packages registered in `compare:types`, `yarn compare:types` is a **blocking review gate**: the touched package must have zero undocumented or stale differences before `review_gate` closes. If the global command fails on unrelated registered packages, record/fix that drift in the work queue; do not treat an unrelated failure as permission to skip the touched package's type-parity check. +4. **Coverage evidence package** — **blocking** when `packages/*/lib/**` or native bridge sources in the frozen diff: after fresh area-focused e2e, run native post-process ([coverage design § reading per-file](../code-coverage/local.md#reading-per-file-coverage-locally)); produce package per [coverage design § evidence package](../code-coverage/policy.md#coverage-evidence-package); close **`coverage_evidence` gate** with verdict line; investigate every non-100% reachable line. **Missing or stale package = serious finding** — same bar as missing e2e counts. +5. When the frozen tree includes `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md`, run the [OKF bundle scan](../validation/okf-review.md#okf-bundle-review) — **report only**. +6. Outcome closes **`review` gate** (only after **`coverage_evidence` gate** when required) or follows [§ frozen tree](#frozen-tree) split (not every finding → `documentation`). + +Keep **`implementation`**, **`documentation`**, and **`independent-review`** in separate passes ([§ frozen tree](#frozen-tree)). Do not add OKF after this pass without another `independent-review`. + +## `commit` + +- One focused commit per item when gates close. +- When `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` changed, **`commit` closes only after** the frozen [OKF bundle scan](../validation/okf-review.md#okf-bundle-review) is clean. Contract findings belong in **`documentation?`** then another frozen `independent-review` — not edits on the `commit` pass. +- **Evidence required:** [§ validation evidence](gates.md#validation-evidence-blocking) must be recorded before `commit_gate` closes; summaries without exit codes, e2e counts, and coverage tables do not substitute. +- **Never stage:** `tests/harness.overrides.js`, any `.only`, temporary sub-suite edits in `tests/app.js`, or native instrumentation ([running e2e § before merge](../e2e/gates.md#before-merge-pr-handoff), [platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking)). +- **Work queue:** before `git commit`, set the row's `commit_subject` on the Linear queue document to the commit's subject line and close `commit_gate`. Do not stage a queue file. Do not record SHAs. After commit, the git subject and the queue `commit_subject` must match character-for-character. Single-commit PR titles: [documentation-policy § pull requests](../../documentation-policy.md#pull-requests). Queues are ephemeral ([documentation policy § work-queue documents](../../documentation-policy.md#work-queue-documents)); do not copy policy here. + +```bash +git status +git diff --stat +rg '\.only\(' packages/ +``` diff --git a/okf-bundle/testing/change-authoring-workflow.md b/okf-bundle/testing/change-authoring-workflow.md index 5e113c9ba3..be395b7fef 100644 --- a/okf-bundle/testing/change-authoring-workflow.md +++ b/okf-bundle/testing/change-authoring-workflow.md @@ -3,7 +3,7 @@ type: Reference title: Change authoring workflow description: Canonical cross-package loop for verified product changes — baseline, unit-focused implementation, documentation, area-focused review, commit, and pre-merge validation. tags: [testing, validation, workflow, implementation, review] -timestamp: 2026-06-26T00:00:00Z +timestamp: 2026-12-02T00:00:00Z --- # Change authoring workflow @@ -12,305 +12,27 @@ Single source for **how to author and verify a product change** in RNFB (bug fix **Policy:** [OKF documentation and commit policy](../documentation-policy.md) — public vs ephemeral vs private; [Efficiency](../documentation-policy.md#efficiency). **Terms:** [iteration vocabulary](iteration-vocabulary.md). -## Primary loop +## Files -```mermaid -flowchart TD - START([Pick change scope]) --> GA{Need feasibility /
semantics check?} - GA -->|yes| GAP["gap-analysis
tier: none"] - GA -->|no| BC{Need before snapshot
or area-focused e2e baseline?} - GAP --> BC +Content moved from this file into the files below. Headings and anchors keep their names in the new file; each old anchor sits on the line under its new home, so old `#links` still land here and point on. - BC -->|yes| BASE["baseline-capture
tier: area-focused"] - BC -->|no| IMPL - BASE --> IMPL - - IMPL["implementation
tier: unit-focused
Jest + narrow e2e loop"] - IMPL --> IG{implementation gate
green?} - IG -->|no| IMPL - IG -->|yes| DOC - - DOC{User-facing or
OKF durable updates?} - DOC -->|yes| DOCS["documentation
tier: none"] - DOC -->|no| REV - DOCS --> REV - - REV["independent-review
tier: area-focused
frozen tree"] - REV --> RG{all findings
resolved?} - RG -->|product / tests / lint| IMPL - RG -->|OKF / AGENTS / CONTRIBUTING only| DOCS - RG -->|yes| COMMIT - - COMMIT["commit
tier: none"] - COMMIT --> PM{Branch ready
to merge?} - PM -->|yes| FULL["pre-merge-validation
tier: full"] - PM -->|no| END([Hand off / next item]) - FULL --> END -``` - -## Work types - -| Work type | When | Validation tier | Product edits | Commit | -| ---------------------- | --------------------------------------------------- | --------------- | -------------------------------- | ------ | -| `gap-analysis` | Unclear feasibility, export shape, platform support | none | read-only | no | -| `baseline-capture` | Need before metrics or area-focused e2e on the item | `area-focused` | harness narrow OK locally | no | -| `implementation` | Author fix/feature + tests | `unit-focused` | yes | no | -| `documentation` | Promote user docs + durable OKF + `AGENTS.md` + `CONTRIBUTING.md` on the **same change set**, **before** `independent-review`. Does **not** run the OKF scan. When `docs/**` is in the change set, record [lint:docs-links](validation-checklist.md#docs-page-link-check) evidence **here** (with markdown/spellcheck) — missing that row is a **serious** review finding | none | those files only | no | -| `independent-review` | Verify frozen diff. When the frozen tree includes `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md`, this pass **is** the [OKF bundle scan](validation-checklist.md#okf-bundle-review). When `docs/**` is in the frozen tree, confirm [lint:docs-links](validation-checklist.md#docs-page-link-check) exit **0** is in evidence — absence is **serious** | `area-focused` | no — [frozen tree](#frozen-tree) except revert `.only` | no | -| `commit` | Gates closed for the item; **staging only** | none | staging only | yes | -| `pre-merge-validation` | Branch merge gate | `full` | revert narrowing first | no | - -**Commands per work type:** [validation checklist](validation-checklist.md) — link only; do not duplicate here. - -## Validation tiers - -Tier id strings: [iteration vocabulary § validation tier identifiers](iteration-vocabulary.md#validation-tier-identifiers). - -```mermaid -flowchart LR - subgraph unitFocused ["unit-focused — implementation"] - F1[Area harness narrowing required] - F2[Jest + package-scoped tests] - F3[".only OK locally"] - F4[Fast e2e subset] - F5[Never commit narrowing or .only] - end - - subgraph areaFocused ["area-focused — baseline-capture / independent-review"] - A1[Area harness narrowing required] - A2[Full loaded package spec] - A3[No .only] - A4[Frozen tree for review] - end - - subgraph full ["full — pre-merge-validation"] - P1[Revert all narrowing] - P2[All modules / full app] - P3[Once per branch before merge] - end -``` - -E2e scope, pre-flight, and harness gate: [running e2e § agent rule](running-e2e.md#agent-rule-read-first) (canonical commands only), [validation tiers](running-e2e.md#e2e-validation-tiers-unit-focused-area-focused-full), [harness narrowing gate](running-e2e.md#harness-narrowing-gate-blocking). - -**Command rule:** Agents run **only** [agent command policy](agent-command-policy.md) allowlisted commands for install, prepare, and validation — no improvised `yarn workspace … prepare`, `yarn jet`, or package-scoped build probes. - -## Gates - -| Gate | Closes when | -| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `implementation` | `implementation` work type complete — code plus **unit-focused**-tier checks green on **every required platform** when native bridge, **committed `**/generated/**`**, podspec/spec/codegen wiring, macOS TS/runtime path, **or** `packages/*/e2e/**` changed ([platform coverage gate](running-e2e.md#platform-coverage-gate-blocking); [running e2e § Rules #3](running-e2e.md#rules)); [static analysis](validation-checklist.md#lint-and-formatting) green on the diff | -| `coverage_evidence` | [Coverage evidence package](coverage-design.md#coverage-evidence-package) attached with verdict line — **required** when frozen diff touches `packages/*/lib/**`, native bridge (`packages/*/{android,ios}/**`), **or** `packages/app/**/*.rb`; otherwise `n/a` | -| `review` | `independent-review` complete — **area-focused**-tier checks green on frozen tree; applicable [validation checklist](validation-checklist.md) rows green (including static analysis); **`coverage_evidence` gate closed** when required; **OKF bundle scan** when `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` are in the frozen tree ([§ OKF bundle review](validation-checklist.md#okf-bundle-review)); **every review finding resolved** ([§ quality standards](#quality-standards)) | -| `commit` | Durable commit exists for the item **after** `implementation`, `coverage_evidence` (when required), and `review` gates closed with [recorded evidence](#validation-evidence-blocking). When those OKF/`AGENTS.md`/`CONTRIBUTING.md` files changed, close only after the frozen scan. **Fix** OKF contract violations before **`git commit`** — the frozen scan reports only | - -**Trust rule:** Code on disk or in git with `review` still **open** is unverified until `independent-review` closes the gate. - -Follow-up **splits by what failed** ([§ frozen tree](#frozen-tree), [§ quality standards](#quality-standards)): product/tests/lint → **`implementation`**; `okf-bundle/` / `AGENTS.md` / `CONTRIBUTING.md` → **`documentation`** then another frozen `independent-review`. Do not send every finding to `documentation`. - - - -### Validation evidence (blocking) - -Gates close **only** when **recorded evidence** shows the required validation tier ran and passed. Assumed green, summaries without exit codes, or "tests passed earlier" without a log path **do not** close a gate. - -| Gate | Minimum evidence (record in work-queue notes or review handoff) | -| ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **`implementation`** | Prepare/tsc/jest **exit codes**; when `packages/app/**/*.rb` or `packages/app/__tests__/*_test.rb` touched: **`yarn tests:ios:ruby` exit 0** + `coverage/ios-ruby/lcov.info` ([validation checklist § iOS Ruby](validation-checklist.md#ios-ruby-unit-tests)); when native bridge, **`packages/*/ios/generated/**` / `packages/*/android/**/generated/**`**, podspec/spec/codegen wiring, macOS runtime, **or** `packages/*/e2e/**` touched: **e2e pass count per required platform** + log path (e.g. `/tmp/rnfb-e2e-*.log`) — package e2e specs require the same [platform coverage](running-e2e.md#platform-coverage-gate-blocking) matrix even with no native hunk for that OS; **`yarn codegen:verify` alone does not close this**; [lint and formatting](validation-checklist.md#lint-and-formatting) evidence (by-tree scripts; exit 0) | -| **`coverage_evidence`** | When lib/native bridge **or** `packages/app/**/*.rb` touched: full [coverage evidence package](coverage-design.md#coverage-evidence-package) at `.agents/reports//coverage-evidence.md` (or work-queue notes) including **verdict line**; post-process native artifacts after fresh e2e ([coverage design § reading per-file](coverage-design.md#reading-per-file-coverage-locally)); Ruby: [§ iOS Ruby SimpleCov](coverage-design.md#ios-ruby-simplecov) | -| **`review`** | Frozen-tree re-run of area-focused checklist; [lint and formatting](validation-checklist.md#lint-and-formatting) evidence (check-only by-tree); **`coverage_evidence` gate closed** when required (native, **`**/generated/**`**, `packages/*/lib/**` bridge code, **or** `packages/app/**/*.rb`); **OKF bundle scan report** when `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` in the frozen tree ([§ OKF bundle review](validation-checklist.md#okf-bundle-review)); compare:types row for touched registered package; e2e evidence must include [services checkout ownership](running-e2e.md#services-checkout-ownership-blocking) when platforms ran | -| **`commit`** | Prior gates closed **with evidence**; no `.only` / harness overrides staged; OKF contract violations **fixed before `git commit`** when those files changed (frozen scan was report-only) | -| **Publication** (`git push`, force-push, PR refresh) | **`review` gate closed on the exact commits being published**; evidence still valid (no product edits since last area-focused run) | - -**Investigate before close:** Any coverage plateau, parity asymmetry, or review finding gets **root-cause analysis** — add tests, delete dead code, or record an [acceptable exception](#acceptable-exceptions) with evidence. Do not label gaps "informational" or "defensive" without wire/runtime proof. - - - -### Forbidden shortcuts - -- **`git commit`** while the current work type's validation tier is incomplete or evidence is missing — including **`coverage_evidence` gate open** when lib/native bridge touched. -- **Jet NYC `text-summary` after narrowed e2e** as coverage proof for native or `packages/*/lib/**` changes — it measures remapped TS only; use Jacoco/lcov on **changed files** ([coverage design § anti-patterns](coverage-design.md#anti-patterns-not-coverage-evidence)). -- **`git push` / force-push / PR update** claiming remediation or review-green **without** fresh area-focused evidence after the last product edit on the published commits. -- **History rewrite** (rebase, amend stack) **without** re-running validation for the rewritten scope — prior green results are **invalid**. -- **Self-accepted** parity or coverage gaps — only [acceptable exceptions](#acceptable-exceptions) with user confirmation or intractability evidence in durable OKF (e.g. parity registry row). -- **`yarn codegen:verify` (or scripts/OKF-only static checks) instead of platform e2e** when committed `packages/*/ios/generated/**`, `packages/*/android/**/generated/**`, native shells, podspecs, or TurboModule specs changed — [running e2e § Rules #3](running-e2e.md#rules) / [platform coverage](running-e2e.md#platform-coverage-gate-blocking). -- **Pre-flight that only checks ports/HTTP** while Metro or Firebase emulators belong to another worktree — [services checkout ownership](running-e2e.md#services-checkout-ownership-blocking). - -Publication is not a separate work type; it follows the same evidence bar as `review` + `commit`. - -## Quality standards - -Two exception-gated authoring standards apply to every item — [acceptable exceptions](#acceptable-exceptions) and [review findings](#review-findings--resolve-do-not-defer). Both share the same narrow exception set (the only things that may be documented and tracked instead of fixed). [Language port observable contracts](#language-port-observable-contracts) is an additional domain application rule for port work, not a third exception gate. - - - -### Acceptable exceptions - -Only two things may be documented and tracked instead of fixed. **Both require the user's explicit acceptance and confirmation plus a recorded rationale** — neither exception may be granted without that, and the item stays tracked until resolved. - -1. **Intractable-limitation bar.** The gap or firebase-js-sdk divergence is caused by an intractable technical limitation of the language, platform SDK, compiler, or toolchain, shown with evidence — e.g. a compiler/codegen-expanded branch that is provably unreachable, or a native SDK that does not expose the capability, cited by version. -2. **User-accepted deferral.** The gap is addressable, but the user explicitly defers it with a documented rationale — e.g. it needs architectural design or human review not available now, or the compute cost is not currently justified. - -Anything else is drift or a defect, never a self-justifying exception: - -- **If code can be authored, a test that exercises it can be authored** — otherwise it is dead code; delete it, do not document it. -- **A divergence with no accepted exception is drift** — align to firebase-js-sdk and remove any config entry. -- Convenience, time pressure, "harmless", "low-value", or "low-risk" carry weight **only** through an explicit user-accepted deferral (2), never on an agent's own authority. - - - -### Review findings — resolve, do not defer - -`independent-review` classifies findings **critical / serious / minor / nit**. The **`review` gate closes only when every finding — including minor and nit — is resolved by a fix**, unless the finding is covered by one of the two [acceptable exceptions](#acceptable-exceptions). Do **not** defer a finding without that exception: "green with minors" is not green, and parity, quality, and coverage gaps are cheapest to fix while the diff is fresh. - -A finding covered by an accepted exception is recorded — with evidence or the user's rationale — and tracked, not silently dropped. A finding that is neither fixed nor covered by an accepted exception follows [§ frozen tree](#frozen-tree): product/tests/lint → **`implementation`**; `okf-bundle/` / `AGENTS.md` / `CONTRIBUTING.md` → **`documentation`** then another frozen `independent-review`. - -Domain applications reference this section rather than restating it: - -- **Coverage completion:** [coverage design § expectations](coverage-design.md#coverage-expectations-policy). -- **Type parity / API drift:** [compare-types justification bar](../../.github/scripts/compare-types/README.md#justification-bar). - - - -### Language port observable contracts - -When porting ObjC/C++/Java to Swift/Kotlin, or writing unit tests for such a port, assert **pre-port observable product contracts** — the behavior callers already relied on — not incidental Foundation/JDK return shapes or host-specific quirks. - -- Prefer key-absence and documented API/bridge behavior over platform return-shape details (for example nil vs empty dictionary) when the pre-port code never asserted that shape. -- Do not promote host XCTest/JUnit or Simulator/JVM environment quirks into product requirements. - -## Frozen tree - -Required for **`independent-review`** and for any `:test-cover` run that closes the **`review`** gate: - -- **Report/check-only** except reverting `.only`. -- No edits to `packages/**`, `tests/**` (except reverting `.only`), `okf-bundle/` **reference** docs, `AGENTS.md`, or `CONTRIBUTING.md` during the run. -- Wait for or cancel in-flight runs before editing again. - -Keep **`implementation`**, **`documentation`**, and **`independent-review`** in separate passes. Do **not** add OKF / `AGENTS.md` / `CONTRIBUTING.md` after a frozen review without another `independent-review`. E2e enforcement during runs: [running e2e § rules](running-e2e.md#rules). - -Follow-up **splits by what failed**: - -| Failed in | Next work type | -|-----------|----------------| -| Product, tests, or lint | `implementation` (then `documentation?`, then frozen scan) | -| `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` | `documentation` then another frozen `independent-review` | - -Do not send every finding to `documentation`. - -## Host rule - -On a shared dev host during change authoring: - -- One unslotted `:test-cover` at a time — never overlap **unit-focused**-tier and **area-focused**-tier runs. Slotted cross-platform concurrency (distinct worktrees/ports/devices): [running e2e § parallel topology](running-e2e.md#parallel-e2e-topology). -- Every run starts from [running e2e § pre-flight](running-e2e.md#pre-flight-is-the-host-clear-to-start) (host-clear probes, services ready, **[checkout ownership](running-e2e.md#services-checkout-ownership-blocking)**, harness tier). -- Use only [canonical e2e commands](running-e2e.md#rules). Startup-fail markers → [startup fail-fast poll](running-e2e.md#startup-fail-fast-poll) (do not wait the full `launchApp` timeout). Stalled runs → [stalled run detection](running-e2e.md#stalled-run-detection). - -## `implementation` inner loop - -```mermaid -flowchart TD - P0[Pre-flight: host clear, services, harness tier] - P1[Edit product code + tests] - P2[Jest — package or scoped paths] - P3{Native touched?} - P3 -->|no| P4[macOS e2e when TS/runtime path] - P3 -->|yes| P5["native rebuild + platform e2e"] - P4 --> P6{Green?} - P5 --> P6 - P6 -->|no| P1 - P6 -->|yes| STATIC[Static analysis — validation checklist § lint] - STATIC --> DONE([Close implementation gate]) - P0 --> P1 -``` - -**Host rule:** one `:test-cover` at a time; never overlap **unit-focused** and **area-focused** tiers on one host ([§ host rule](#host-rule)). - -**Static analysis before handoff:** Before closing the **`implementation`** gate, run the [validation checklist § lint and formatting](validation-checklist.md#lint-and-formatting) rows that match the diff. Fix violations in product code — do not hand off with lint failures. Commands live only in that section. - -Step detail: [running e2e § unit-focused iteration loop](running-e2e.md#unit-focused-tier-iteration-loop). - - - -### Platform SDK bridge contracts (blocking) - -Before changing native bridge code that calls a **platform SDK** (Firebase Android/iOS, OS APIs, vendor SDKs, etc.): - -1. **Read each platform's official API signature and docs independently** — do not assume Android, iOS, and Web behave the same because the RNFB bridge presents a unified JavaScript surface. -2. **Verify null vs empty string** — many SDKs treat absent values (`null`/`nil`) and empty strings (`""`) differently; map bridge fields to the SDK parameter the docs specify for "absent" values. -3. **Do not apply defensive parity** — fixing platform A does not justify the same change on platform B without checking B's contract (e.g. `@Nullable` vs `nonnull`, optional vs required). -4. **Record evidence** — link or cite the reference URL / header signature in the work queue note or triage report when the fix is native-only on one platform. - - - -### E2e diagnosis escalation - -When **`unit-focused`** e2e fails and product cause is unclear: - -1. Confirm [pre-flight](running-e2e.md#pre-flight-is-the-host-clear-to-start) was complete ([prepare completion gate](running-e2e.md#prepare-completion-gate-blocking) when `lib/**` changed, host-clear probes, services, harness overrides, **`RNFBDebug: true`** via overrides). -2. If the **same failure repeats** on back-to-back runs with no assertion progress and the host is known clean → **sub-suite narrow** ([running e2e § fail-fast](running-e2e.md#fail-fast-rnfbdebug-and-sub-suite-narrowing)): one spec file or `describe.only` on the failing band (e.g. aggregate `count()` / `average()` / `sum()` only). Still **unit-focused**; never commit narrowing. -3. If sub-suite runs still fail without actionable assertion text → add **temporary native instrumentation** (NSLog, `adb logcat` tags, etc.) on the code path under test; use [running e2e § diagnosing hangs](running-e2e.md#diagnosing-hangs) for log commands. **Remove instrumentation before `commit`** and before **`area-focused`** gate closure on a frozen tree. -4. Do not treat Jet WS disconnect / orchestration timeout alone as product failure — [stalled run detection](running-e2e.md#stalled-run-detection) and pre-flight recovery first. - -This escalation is general change authoring. Work queues record outcomes; they do not restate this loop. - -## `independent-review` - -On a **frozen tree**: - -1. Revert all `.only`. -2. Keep area narrowing; run **area-focused**-tier e2e for loaded package spec(s) on [**every required platform**](running-e2e.md#platform-coverage-gate-blocking) (serial; pre-flight each run). -3. Run applicable [validation checklist](validation-checklist.md) rows — **blocking:** [static analysis § lint and formatting](validation-checklist.md#lint-and-formatting) (frozen: check-only by-tree); `yarn reference:api` when public surface changed. For packages registered in `compare:types`, `yarn compare:types` is a **blocking review gate**: the touched package must have zero undocumented or stale differences before `review_gate` closes. If the global command fails on unrelated registered packages, record/fix that drift in the work queue; do not treat an unrelated failure as permission to skip the touched package's type-parity check. -4. **Coverage evidence package** — **blocking** when `packages/*/lib/**` or native bridge sources in the frozen diff: after fresh area-focused e2e, run native post-process ([coverage design § reading per-file](coverage-design.md#reading-per-file-coverage-locally)); produce package per [coverage design § evidence package](coverage-design.md#coverage-evidence-package); close **`coverage_evidence` gate** with verdict line; investigate every non-100% reachable line. **Missing or stale package = serious finding** — same bar as missing e2e counts. -5. When the frozen tree includes `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md`, run the [OKF bundle scan](validation-checklist.md#okf-bundle-review) — **report only**. -6. Outcome closes **`review` gate** (only after **`coverage_evidence` gate** when required) or follows [§ frozen tree](#frozen-tree) split (not every finding → `documentation`). - -Keep **`implementation`**, **`documentation`**, and **`independent-review`** in separate passes ([§ frozen tree](#frozen-tree)). Do not add OKF after this pass without another `independent-review`. - -## Harness narrowing - -**Before the first `:test-cover` at `unit-focused` or `area-focused` tier:** create local [`tests/harness.overrides.js`](../../tests/harness.overrides.example.js) even when the branch commit has full harness — [running e2e § local harness overrides](running-e2e.md#local-harness-overrides-harnessoverridesjs). Set `modules` to the package area and **`RNFBDebug: true`**. Full app load is **`full`** tier only (delete overrides file). - -| Kind | `implementation` (**unit-focused**) | `independent-review` (**area-focused**) | `pre-merge-validation` (**full**) | `commit` | -| -------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------ | --------------------------------- | ---------------------- | -| **Area narrowing** | Required before `:test-cover` (overrides file) | Required before `:test-cover` | Delete overrides — all modules | Never commit overrides | -| **`RNFBDebug: true`** | Required in overrides before `:test-cover` | Required in overrides before `:test-cover` | Delete overrides / `false` | Never | -| **Single-test** (`.only`) | Allowed (diagnosis) | Revert | Revert | Never | -| **Single-suite** (`describe.only` / one spec file) | Allowed (diagnosis only — [escalation](#e2e-diagnosis-escalation)) | Revert | Revert | Never | - -Package workflows define **which module/spec** to load (e.g. Firestore → [pipeline implementation workflow § narrowing](../packages/firestore/pipeline-implementation-workflow.md#pipeline-area-harness)). - -**Sanity check:** pass counts must match loaded scope — not full-app totals ([running e2e § gate](running-e2e.md#harness-narrowing-gate-blocking)). - -## `commit` - -- One focused commit per item when gates close. -- When `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` changed, **`commit` closes only after** the frozen [OKF bundle scan](validation-checklist.md#okf-bundle-review) is clean. Contract findings belong in **`documentation?`** then another frozen `independent-review` — not edits on the `commit` pass. -- **Evidence required:** [§ validation evidence](#validation-evidence-blocking) must be recorded before `commit_gate` closes; summaries without exit codes, e2e counts, and coverage tables do not substitute. -- **Never stage:** `tests/harness.overrides.js`, any `.only`, temporary sub-suite edits in `tests/app.js`, or native instrumentation ([running e2e § before merge](running-e2e.md#before-merge-pr-handoff), [platform coverage gate](running-e2e.md#platform-coverage-gate-blocking)). -- **Work queue:** before `git commit`, set the row's `commit_subject` on the Linear queue document to the commit's subject line and close `commit_gate`. Do not stage a queue file. Do not record SHAs. After commit, the git subject and the queue `commit_subject` must match character-for-character. Single-commit PR titles: [documentation-policy § pull requests](../documentation-policy.md#pull-requests). Queues are ephemeral ([documentation policy § work-queue documents](../documentation-policy.md#work-queue-documents)); do not copy policy here. - -```bash -git status -git diff --stat -rg '\.only\(' packages/ -``` - -## Package extensions - -| Package / area | Adds to this loop | -| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Firestore Pipelines | Compare-types gap pick, serialization matrix, `Pipeline.e2e.js` setup, coverage snapshots — [pipeline implementation workflow](../packages/firestore/pipeline-implementation-workflow.md) | -| TurboModules | Durable decisions — [New Architecture ADR](../new-architecture/architecture-decisions.md) / [index](../new-architecture/index.md). Codegen commands: [agent command policy](agent-command-policy.md#turbomodule-codegen) | -| Other packages | `okf-bundle/packages//` index when a workflow exists | - -Ephemeral coordination (gate rows, `next_work_type`, `commit_subject`) lives in **work queues only** — do not paste gate rows into this file. How to stage those fields: [§ commit](#commit). +- [Change authoring: loop, work types, tiers](authoring/loop.md): Primary change authoring loop, work type table, validation tier summary, and package extensions. + +- [Change authoring: gates and evidence](authoring/gates.md): Gate close conditions, blocking validation evidence per gate, and forbidden shortcuts. + +- [Change authoring: quality standards](authoring/quality-standards.md): Acceptable exceptions, review findings resolution bar, and language port observable contracts. + +- [Change authoring: frozen review and commit](authoring/review-and-commit.md): Frozen tree rules, independent-review steps, and the commit pass. + +- [Change authoring: implementation pass](authoring/implementation.md): Host rule, implementation inner loop, platform SDK bridge contracts, e2e diagnosis escalation, and harness narrowing per tier. + ## Related docs -| Topic | Document | -| ------------------------------- | -------------------------------------------------- | +| Topic | Document | +| --- | --- | | Term ids and queue field schema | [iteration-vocabulary.md](iteration-vocabulary.md) | -| E2e commands | [running-e2e.md](running-e2e.md) | -| Validation commands | [validation-checklist.md](validation-checklist.md) | -| Coverage policy | [coverage-design.md](coverage-design.md) | -| Android JVM unit ADR | [AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1) | +| E2e commands | [running-e2e.md](running-e2e.md) | +| Validation commands | [validation-checklist.md](validation-checklist.md) | +| Coverage policy | [coverage-design.md](coverage-design.md) | +| Android JVM unit ADR | [AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1) | diff --git a/okf-bundle/testing/code-coverage/codecov-ci.md b/okf-bundle/testing/code-coverage/codecov-ci.md new file mode 100644 index 0000000000..a6ca1bdeef --- /dev/null +++ b/okf-bundle/testing/code-coverage/codecov-ci.md @@ -0,0 +1,46 @@ +--- +type: Reference +title: 'Coverage: Codecov uploads (CI)' +description: 'Codecov flags, native gates, and CI steps before upload.' +tags: [testing, coverage, codecov, ci] +timestamp: 2026-12-02T00:00:00Z +--- + +# Coverage: Codecov uploads (CI) + +Part of [Coverage design](../coverage-design.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +# Codecov uploads (CI) + +[codecov-action](https://github.com/codecov/codecov-action) v7, explicit `files` + `flags`. Upload steps continue on error; **blocking** = `codecov.yml` status checks. + +## Flags + +Names must match in **`codecov.yml`** and workflow `flags:`. + +| Flag | Workflow | File | Blocks PR? | +| --- | --- | --- | --- | +| `jest` | `tests_jest.yml` | `coverage/lcov.info` | No | +| `ios-ruby` | `tests_e2e_ios.yml` (debug + spm) | `coverage/ios-ruby/lcov.info` | No (upload like `jest`; OKF review gate owns touched Ruby lines) | +| `e2e-ts-ios` | `tests_e2e_ios.yml` (debug) | `coverage/lcov.info` | No | +| `ios-native` | `tests_e2e_ios.yml` (debug) | `coverage/ios-native/lcov.info` | **Yes** | +| `e2e-ts-android` | `tests_e2e_android.yml` | `coverage/lcov.info` | No | +| `android-native` | `tests_e2e_android.yml` | `tests/android/app/build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml` | **Yes** | +| `e2e-ts-macos` | `tests_e2e_other.yml` | `coverage/lcov.info` | No | + +iOS release legs: no upload. macOS: TS only. + +## Native gates + +`carryforward: false`, `target: 1%` — gates **upload presence**, not % regression. Missing upload → 0% → fail. `codecov/project` overall: `informational: true`. + +## CI steps before upload + +| Workflow | Steps | +| --- | --- | +| `tests_jest.yml` | `yarn tests:jest-coverage` → Codecov `jest` | +| `tests_e2e_ios.yml` (debug) | `yarn tests:ios:unit` → Detox → `yarn tests:ios:test:process-coverage` (e2e LCOV + merge unit + presence assert; **no** `continue-on-error`; fails the job when Detox succeeded but coverage exited non-zero — same policy as Android); **debug+spm:** `yarn tests:ios:ruby` → Codecov `ios-ruby` | +| `tests_e2e_android.yml` | `yarn tests:android:build` → `yarn tests:android:unit` → Detox → `yarn tests:android:post-e2e-coverage` (merged `jacocoTestReport` + presence assert; CI script fails the job when tests passed but coverage exited non-zero) | +| `tests_e2e_other.yml` | macOS Jet e2e | + +**Paths:** JS `coverage/lcov.info`; iOS Ruby `coverage/ios-ruby/lcov.info`; iOS native `coverage/ios-native/lcov.info`; Android merged native `tests/android/app/build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml`. Uploads tab: **Processed** = good; **Unusable** = fix format/paths. diff --git a/okf-bundle/testing/code-coverage/invariants-and-troubleshooting.md b/okf-bundle/testing/code-coverage/invariants-and-troubleshooting.md new file mode 100644 index 0000000000..7a662146dd --- /dev/null +++ b/okf-bundle/testing/code-coverage/invariants-and-troubleshooting.md @@ -0,0 +1,60 @@ +--- +type: Reference +title: 'Coverage: invariants and troubleshooting' +description: 'Critical coverage invariants, troubleshooting table, and future cleanups.' +tags: [testing, coverage] +timestamp: 2026-12-02T00:00:00Z +--- + +# Coverage: invariants and troubleshooting + +Part of [Coverage design](../coverage-design.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +# Critical invariants + +| Invariant | Enforced | +| --- | --- | +| LLVM profile flags (iOS) | `Podfile` `post_install` + `ReactNativeCoverage.apply_post_install!` | +| Profile path at launch (iOS) | `react-native-coverage` constructor (`CoverageConfigureProfilePath`) | +| Jacoco instrumentation (Android) | package `rn-coverage.gradle` (`enableAndroidTestCoverage = true`, `enableUnitTestCoverage = false`) | +| Module name | `Coverage` / `react-native-coverage.flush()` | +| Flush after Mocha | Jet `after` in `tests/app.js` | +| Profraw pull before Detox teardown (iOS) | `pull-native-coverage.js` on Jet `close` in `firebase.test.js` | +| Android JVM unit before / with merge | `yarn tests:android:unit` → module `*.exec` | +| iOS XCTest unit merged into ios-native | `yarn tests:ios:unit` → `coverage/ios-unit/lcov.info` merged into `coverage/ios-native/lcov.info` | +| Android ec pull after Detox | `yarn tests:android:post-e2e-coverage` → **`jacocoTestReport`** (not e2e-only `jacocoAndroidTestReport`) | +| Codecov android-native file | `jacocoTestReport/jacocoTestReport.xml` | +| Fresh profraw processed (iOS) | `rn-coverage-ios-export.js` (package CLI) deletes after export | +| Fresh ec processed (Android) | `pull-native-coverage.js` deletes local `.ec` after successful Jacoco report | +| JVM unit ≠ e2e substitute | [AndroidTest-AD-1](../android-architecture-decisions.md#androidtest-ad-1); [platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking) still applies | +| iOS XCTest ≠ e2e substitute | [IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1); unit LCOV still merges into ios-native | + +# Troubleshooting + +| Symptom | Cause | Fix | +| --- | --- | --- | +| "Open in 'testing'?" dialog | Custom URL scheme | Native module flush only | +| No profraw; test passes | Pull in `afterAll` after cleanup, wrong module name | Pull on Jet `close`; verify export name | +| Stale profraw uploaded | Re-process without re-e2e | Process deletes profraw; exit 1 if missing next time | +| Stale Android Jacoco / collapsed native % | Re-run `post-e2e-coverage` without fresh e2e (and/or without fresh unit `*.exec`) | Post-e2e deletes `.ec` after report; run `:build` → `tests:android:unit` → `:test-cover` → `:post-e2e-coverage` | +| Coverage numbers suspect (any platform) | Leftover raw artifacts or reuse shortcuts | Full clean cycle per platform; see [Stale coverage data](local.md#stale-coverage-data) | +| No `packages/` hits in iOS export | Dynamic/SPM multi-image path incomplete | [SPM + dynamic frameworks](native.md#spm--dynamic-frameworks); rebuild `tests:ios:build` → `:test-cover`; syslog `tracked profile image` / `flush tracked image` | +| Empty Jacoco XML (~235 B) | AGP 8 path, missing `src/reactnative/java`, no ec/exec | Check post-e2e logs; confirm `jacocoTestReport` not e2e-only task | +| Uploaded e2e-only Jacoco | Wrong report task / path | Codecov must use `jacocoTestReport.xml`, not `jacocoAndroidTestReport.xml` | +| Android ec missing after pass | SIGINT before flush | `[native-coverage] flushing android coverage` in log; `MainApplication` registration | +| Jet after: coverage not enabled | Release / non-instrumented build | Use `:test-cover` debug builds | +| `swiftCompatibility56` undefined | Profile link flags on all Pods | App target only for `OTHER_LDFLAGS` | +| No `[jet-coverage] WS received` | Patches missing | `yarn install`; `.yarn/patches/` | +| WS closed on `reconnect_recovered` | Handshake on dead socket | Client retry + server pull; `JET_COVERAGE_TEARDOWN_RE` — [iOS issue 8](../../ci-workflows/ios.md#8-coverage-teardown-handshake-failure-tests-pass-nyc-00) | +| Empty NYC / lcov | Environment or patch issue during `:test-cover` | Re-run per [running e2e](../running-e2e.md) — do not invoke the test runner directly | +| `tests:ios:test:process-coverage` exits 1; NYC `concurrency` got `0` | Trailing NYC JS report failed after native LCOV write | Read `coverage/ios-native/lcov.info` — still the artifact; exit ≠ missing native coverage ([§ E2e iOS native](native.md#e2e-ios-native-llvm)) | +| Codecov missing iOS native | Wrong path/name | `coverage/ios-native/lcov.info` | +| Upload **Unusable** | Bad `SF:` paths | package `sourcePathRewrite` + `ios-native-lcov.js` | +| `ios-native` / `android-native` fail | Upload missing → 0% | Uploads tab; process/post-e2e steps | + +# Future cleanups + +- Host `rn-coverage-ios-export.js` still merges XCTest `coverage/ios-unit/lcov.info` after + package `ios export` — keep that until the package grows a unit-merge flag. +- `tests/android/app/jacoco.gradle` stays RNFB-specific (firebase module paths, + `src/reactnative/java`). Do not replace it with the package Jacoco helper. diff --git a/okf-bundle/testing/code-coverage/local.md b/okf-bundle/testing/code-coverage/local.md new file mode 100644 index 0000000000..4b193fc3c8 --- /dev/null +++ b/okf-bundle/testing/code-coverage/local.md @@ -0,0 +1,80 @@ +--- +type: Reference +title: 'Coverage: reading coverage locally' +description: 'Reading per-file coverage, iOS Ruby SimpleCov, stale coverage data, and the local iteration loop.' +tags: [testing, coverage, local] +timestamp: 2026-12-02T00:00:00Z +--- + +# Coverage: reading coverage locally + +Part of [Coverage design](../coverage-design.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Reading per-file coverage locally + +After `tests::test-cover`: + +* **JS:** `yarn tests:jest --watchman=false --coverage --coverageReporters=text '--collectCoverageFrom=packages/{,}/lib/**/*.ts'` — paths before the glob ([validation checklist § focused coverage](../validation/jest.md#jest-collect-coverage-from-order)) +* **iOS Ruby:** `yarn tests:ios:ruby` → `coverage/ios-ruby/lcov.info` (`SF:` / `DA:` lines); HTML under `coverage/ios-ruby/` — [§ iOS Ruby SimpleCov](#ios-ruby-simplecov) +* **iOS native:** `yarn tests:ios:unit` → `coverage/ios-unit/lcov.info` (merged into `coverage/ios-native/lcov.info`). After e2e: `yarn tests:ios:test:process-coverage` → e2e LLVM export **then merge unit LCOV** → `coverage/ios-native/lcov.info` (`DA:` lines). **Deletes processed `.profraw`** — re-run e2e before re-processing. Non-zero exit from the trailing NYC JS report does not mean native LCOV is missing — [§ E2e iOS native](native.md#e2e-ios-native-llvm). +* **Android native:** `yarn tests:android:unit` (produces module `*.exec`) then e2e + `yarn tests:android:post-e2e-coverage` → merged **`jacocoTestReport`** XML per `sourcefile`. **Deletes processed `emulator_coverage.ec`** after a successful report — re-run e2e before re-processing. Unit-only: `yarn tests:android:test:jacoco-report` (same merged task; needs fresh `*.exec` and any available `*.ec`). +* macOS e2e overwrites `coverage/lcov.info`; process iOS/Android native before a macOS run if you need both. + +**Baseline stability (repeatability):** after two full Law `:test-cover` (+ process) cycles, record metrics with `yarn tests:coverage:capture-baseline` → `tests/coverage-artifacts/coverage-baseline.json`. Dual-run variance and `--finalize` threshold live in `tests/coverage-artifacts/README.md` (not restated here). + + + +## iOS Ruby SimpleCov + +Minitest suites under `packages/app/__tests__/*_test.rb` cover production Ruby helpers (`packages/app/**/*.rb`, excluding `__tests__`). + +| Item | Value | +| --- | --- | +| **Command** | `yarn tests:ios:ruby` (after `yarn ruby:install` or root `yarn`; CI uses `BUNDLE_FROZEN=true bundle install`) | +| **Runner** | `packages/app/__tests__/run_with_coverage.rb` — SimpleCov starts before any production `.rb` / suite load; glob-discovers all `*_test.rb`; each suite runs in an **isolated subprocess** (mock unit vs real cocoapods/xcodeproj cannot share a process); Coverage counters are peek-merged across production `load` resets | +| **LCOV** | `coverage/ios-ruby/lcov.info` (repo-relative `SF:…/packages/app/…`) | +| **HTML** | `coverage/ios-ruby/index.html` (optional local browse) | +| **Codecov flag** | `ios-ruby` — dedicated upload from `tests_e2e_ios.yml` debug+spm cell (same regime as `jest`: flag upload, **no** `flag_management` hard gate; local OKF review gate owns the touched-line bar) | +| **CI** | `tests_e2e_ios.yml` (debug + spm): `BUNDLE_FROZEN=true bundle install` → yarn → `yarn tests:ios:ruby` → Codecov `flags: ios-ruby`. Not run on Jest or `tests_e2e_other.yml` — iOS job guarantees clang/ar/file for embed suites | +| **Gems** | Committed root `Gemfile`/`Gemfile.lock` (+ `CHECKSUMS`); Dependabot `bundler` at `/` (cooldown in dependabot.yml — not Gemfile `cooldown:`, which needs Bundler 4+) | + +**Review gate:** when the frozen diff touches `packages/app/**/*.rb` or `packages/app/__tests__/*_test.rb`, `review_gate` **cannot close** without `yarn tests:ios:ruby` exit 0 and coverage evidence that touched production Ruby lines have test support ([validation checklist § iOS Ruby](../validation/native-unit.md#ios-ruby-unit-tests)). + +## Stale coverage data + +Native artifacts (`.profraw`, `.ec`, Jacoco XML) are trustworthy only with the fresh e2e run that produced them. Re-processing leftovers can create valid-looking stale reports. + +If numbers look wrong, run the clean cycle before debugging generators — e2e steps: [running e2e § Rules](../e2e/rules.md#rules) and [typical loop](../e2e/narrowing.md#typical-loop); then post-process below (this doc owns post-e2e coverage export only). Android merge needs fresh unit `*.exec` as well — [Local iteration](#local-iteration): + +```bash +yarn tests:ios:test:process-coverage +yarn tests:ios:unit # fresh coverage/ios-unit/lcov.info merged into ios-native +yarn tests:android:unit # fresh module *.exec when Android native touched +yarn tests:android:post-e2e-coverage +``` + +Post-process deletes raw iOS `.profraw` / Android `.ec`; missing raw file means "no fresh coverage." Do not use reuse variants for native deltas ([runbook](../running-e2e.md)). + +# Local iteration + +E2e per [runbook](../running-e2e.md), Android JVM unit + native post-processing: + +```bash +yarn tests:android:unit +yarn tests:ios:unit +yarn tests:ios:test:process-coverage +yarn tests:android:post-e2e-coverage # pulls .ec then jacocoTestReport (merged) +# optional explicit merge report without pull: +yarn tests:android:test:jacoco-report +``` + +Optional Codecov CLI: + +```bash +.codecov-venv/bin/codecovcli upload-process \ + -t "$CODECOV_TOKEN" -r invertase/react-native-firebase \ + --git-service github -C "$(git rev-parse HEAD)" -B "$(git branch --show-current)" \ + -f coverage/ios-native/lcov.info -n local-ios-native --disable-search +``` + +No `:test-cover-reuse` / `:test-reuse` — stale native risk ([runbook](../running-e2e.md)). diff --git a/okf-bundle/testing/code-coverage/migration-rollback.md b/okf-bundle/testing/code-coverage/migration-rollback.md new file mode 100644 index 0000000000..45fefe675c --- /dev/null +++ b/okf-bundle/testing/code-coverage/migration-rollback.md @@ -0,0 +1,71 @@ +--- +type: Reference +title: 'Coverage: migration rollback' +description: 'What migrated means, when and how to roll back the coverage migration, and post-rollback verification.' +tags: [testing, coverage] +timestamp: 2026-12-02T00:00:00Z +--- + +# Coverage: migration rollback + +Part of [Coverage design](../coverage-design.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + + + + + +# Coverage migration rollback + +Playbook to leave published `react-native-coverage@0.2.0` and restore a known-good in-tree flush path when the cutover regresses. Prefer **git revert / checkout from the parent of the adopt cutover** over hand-edited file lists — patches rot. + +## What “migrated” means + +| Area | Migrated state | +| --- | --- | +| **Dependency** | `tests/package.json` pins published `react-native-coverage@0.2.0` (Pattern C — tests app only) | +| **Build helpers** | Package Gradle (`rn-coverage.gradle`) + CocoaPods (`ReactNativeCoverage.apply_post_install!`) wire instrumentation | +| **Flush sources** | In-tree `RNFBTestingCoverage*` (Android module/package, iOS module/profile/config) **deleted**; runtime is package `Coverage` / `flush()` | +| **Host wrappers** | Thin RNFB scripts remain (`pull-native-coverage.js`, `rn-coverage-*.js`, Jacoco merge in `tests/android/app/jacoco.gradle`) | +| **Probes** | Messaging / non-FCM probes stay on `NativeRNFBTesting` + `RNFBTestingMessaging` — not flush — [running e2e § test-app native modules](../e2e/rules.md#test-app-native-modules) | + +## When to rollback + +Treat as cutover regression only after a clean post-process cycle fails ([§ stale coverage](local.md#stale-coverage-data)). Typical signals (details in [§ Troubleshooting](invariants-and-troubleshooting.md#troubleshooting) and [SPM + dynamic frameworks](native.md#spm--dynamic-frameworks)): + +- Codecov `ios-native` / `android-native` uploads empty or **Unusable** +- Presence assert exit **2** (`yarn tests:coverage:assert-presence` / post-e2e / iOS process-coverage) +- iOS export `packagesHits=0` after dynamic multi-image flush +- Android empty Jacoco XML / missing `.ec` despite green Detox + +Do **not** rollback for TS-only Jet/NYC gaps — [§ TS e2e coverage troubleshooting](pipelines.md#ts-e2e-coverage-troubleshooting). + +## Rollback steps (high level) + +1. **Identify the cutover boundary** in git history: the commit that deletes in-tree `RNFBTestingCoverage*` and pins published `react-native-coverage@0.2.0` in `tests/package.json` (and any immediately preceding portal/link commit that only rewires the same dep). The parent of that adopt cutover is the known-good in-tree flush baseline for restore. +2. **Prefer `git revert`** of the adopt cutover (and the portal/link commit if the revert does not restore a buildable tree) on a dedicated branch. If revert conflicts, **`git checkout --`** the native flush sources and wiring paths the cutover removed/changed (in-tree `RNFBTestingCoverage*`, Podfile / Gradle / `AppDelegate` / `MainApplication` registration, related `tests/package.json` dep and lockfile hunks) — do not invent a new flusher. +3. **Pin or remove** the published package version so Yarn no longer resolves `react-native-coverage@0.2.0` as the flush owner (revert the dep hunk, or leave the package unused only if the restored tree no longer imports it). +4. **Reinstall and rebuild:** root `yarn` → (iOS only) `yarn tests:ios:pod:install` → `yarn tests::build` → `:test-cover` → native post-process ([Local iteration](local.md#local-iteration); e2e commands: [running e2e](../running-e2e.md)). +5. **Re-run presence assert** (`yarn tests:coverage:assert-presence` or the platform post-process that invokes it) — must not exit **2**. + +## What not to rollback + +Keep these even when restoring in-tree flush — they are independent of the published package: + +| Keep | Why | +| --- | --- | +| Baseline harness (`tests/coverage-artifacts/`, `yarn tests:coverage:capture-baseline`) | Repeatability metrics, not flush ownership | +| Empty-pipeline / presence guards (exit **2** on silent-empty) | CI safety for any flush implementation | +| Config-driven plumbing (`tests/react-native-coverage.config.js`, `yarn tests:coverage:generate-native-config`, `coverage.properties`) | Knobs stay useful with either flusher | +| Probe split (`NativeRNFBTesting` / `RNFBTestingMessaging`) | Product e2e probes, not coverage flush | +| RNFB Jacoco merge (`tests/android/app/jacoco.gradle`) and iOS unit→native LCOV merge | Host-owned Codecov paths | + +## Post-rollback verification + +After fresh e2e + post-process, these Codecov paths must be **non-empty** again (flags in [§ Codecov uploads](codecov-ci.md#codecov-uploads-ci)): + +| Flag | Path | +| --- | --- | +| `ios-native` | `coverage/ios-native/lcov.info` (includes `packages/*/ios/**` hits; not `packagesHits=0`) | +| `android-native` | `tests/android/app/build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml` (merged unit+e2e; not empty / e2e-only) | + +Optional: TS e2e `coverage/lcov.info` for `e2e-ts-*` is unchanged by native flush ownership. Uploads tab: **Processed**, not **Unusable**. diff --git a/okf-bundle/testing/code-coverage/native.md b/okf-bundle/testing/code-coverage/native.md new file mode 100644 index 0000000000..b05def0540 --- /dev/null +++ b/okf-bundle/testing/code-coverage/native.md @@ -0,0 +1,62 @@ +--- +type: Reference +title: 'Coverage: native e2e (Jacoco and LLVM)' +description: 'Android Jacoco unit + e2e merge and iOS LLVM native e2e coverage.' +tags: [testing, coverage, android, ios] +timestamp: 2026-12-02T00:00:00Z +--- + +# Coverage: native e2e (Jacoco and LLVM) + +Part of [Coverage design](../coverage-design.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +# Android native (Jacoco — unit + e2e merged) + +1. Package `rn-coverage.gradle` on RNFB modules (applied from `tests/android/build.gradle`): `enableAndroidTestCoverage = true` (e2e `*.ec`); `enableUnitTestCoverage = false` (parity with package helper — AGP library unit probes are empty; JVM unit `*.exec` comes from the separate unit path). +2. **JVM unit:** `yarn tests:android:unit` before or independent of Detox — produces module `*.exec`. +3. Jet `after` in `tests/app.js` → `react-native-coverage.flush()` in **app** process → `coverage.ec` in `filesDir` **before** Detox SIGINT. +4. After Detox: `yarn tests:android:post-e2e-coverage` (or `pull-native-coverage --android-post-e2e`) → `emulator_coverage.ec` → **`jacocoTestReport`** (merged unit `*.exec` + e2e `*.ec`) → **delete local `.ec`** → **presence assert** (invertase package LINE hits must be non-empty; exit **2** when strict). Missing `.ec` in strict mode (default): **exit 2** — silent empty e2e coverage must fail CI. Soft local: `--no-strict` / `RNFB_COVERAGE_STRICT=0`. Codecov upload may still use `continue-on-error`; the post-e2e yarn step itself is the blocking guard. +5. XML uploaded to Codecov: `tests/android/app/build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml` + +**Why app-process flush:** Detox SIGINT kills instrumentation after Jet; post-`Detox.runTests()` dump in `DetoxTest.java` never runs. + +**Jacoco notes:** + +- AGP 8 classes: `build/intermediates/javac/debug/compileDebugJavaWithJavac/classes` +- Sources: include `src/reactnative/java` +- Modules: `rootProject.ext.firebaseModulePaths` (`tests/android/build.gradle`) +- Tasks in `tests/android/app/jacoco.gradle`: + - **`jacocoTestReport`** — merged unit + e2e (`**/*.exec` + `**/*.ec`); **CI / Codecov `android-native` uses this** + - `jacocoUnitTestReport` — unit only (`**/*.exec`) + - `jacocoAndroidTestReport` — e2e only (`**/*.ec`); local diagnostic, **not** the Codecov upload path +- Yarn: `tests:android:post-e2e-coverage` and `tests:android:test:jacoco-report` both drive `jacocoTestReport` + + + +# E2e iOS native (LLVM) + +1. **Build:** LLVM flags in **`tests/ios/Podfile` `post_install`** (`pod install` after checkout): + - **`testing` target:** compile + link profile flags + Swift toolchain search paths (Firebase static pods on CI) + - **`RNFB*` pods:** compile-only flags — **no** `-fprofile-instr-generate` on pod `OTHER_LDFLAGS` (breaks `swiftCompatibility56` on CI) + - **Coverage pod:** `ReactNativeCoverage.apply_post_install!` (writes `CoverageConfig.h` with `RNFB` prefixes) +2. **Runtime:** `react-native-coverage` constructor + TurboModule flush → `Documents/coverage-%m.profraw` (`LLVM_PROFILE_FILE`). Jet `after` → `flush()` (tracked RNFB frameworks, then app). **No custom URL scheme** (iOS "Open in 'testing'?" dialog blocks Detox). +3. **Pull:** Jet exit 0 → `pull-native-coverage.js` → `simulator_coverage.profraw`. **Fails if missing.** Pull on Jet `close`, not `afterAll` (before Detox teardown). +4. **Export:** `yarn tests:ios:test:process-coverage` / `rn-coverage-ios-export.js`: + - delegates to `rn-coverage ios export` (llvm-cov + `SF:` rewrite + presence assert) + - **merge** `coverage/ios-unit/lcov.info` when present (`tests/scripts/ios-native-lcov.js`) so XCTest counts for 100% + - **delete processed `.profraw`** (package CLI; missing file next run = no fresh coverage) + - then `reportJsCoverage('ios')` (NYC JS report in `pull-native-coverage.js`) + +**Gotcha:** native LCOV (`coverage/ios-native/lcov.info`) is written and merged **before** the trailing NYC JS report. That report can exit non-zero (e.g. NYC `concurrency` got `0`), so the node process exits 1 even though the native file is already usable. Read `coverage/ios-native/lcov.info`; do not treat the process exit as "no native coverage." + +ObjC + Swift share this. Raw export is mostly Pods/SDK; healthy full run includes ~50–60 `packages/*/ios/**` files among ~2000 entries. + +### Accepted Clang line-counter gaps + +**2026-09-29:** In `packages/app/ios/RNFBApp/RNFBAppModule.mm` `initializeApp`, a format-stable single-line `[self completeInitializeApp:…]` call (clang-format off/on) still leaves LCOV `DA:212,0` on that call and `DA:214,0` on the `});` closing `RCTUnsafeExecuteOnMainQueueSync`, while `initializeApp` / block invoke / the preceding line / method `}` and `completeInitializeApp:` body all hit. User-accepted [intractable limitation](../authoring/quality-standards.md#acceptable-exceptions); do not reshape the call to chase those two counters. + +### SPM + dynamic frameworks + +**Tests Podfile default (dynamic):** RNFB pods stay separate `RNFB*.framework` images. Compile-only instrumentation is not enough — those frameworks must **link** the profile runtime (`link_profile: true` for `RNFB*` when `linkage == dynamic`, including `-Wl,-u,___llvm_profile_set_filename` so set_filename is not dead-stripped), flush must dump **each** loaded RNFB image, and `rn-coverage ios export` must pass every `RNFB*.framework` binary as an extra `llvm-cov -object` (`ios.frameworkNamePrefixes: ['RNFB']`). App-only export → **`packagesHits=0`**. + +**Why per-image flush (not atexit alone):** each dynamic image links its own `clang_rt.profile` copy; `__llvm_profile_write_file` in the app only dumps the app image. `LLVM_PROFILE_FILE=…/coverage-%m.profraw` (set via `setenv` in the package constructor) makes atexit dumps unique per image, but Jet pulls `Documents/*.profraw` on Jet **close** — before `terminateApp` — so atexit has not run yet. Detox SIGKILL can also skip atexit. `react-native-coverage` therefore discovers `RNFB*.framework` images at load via `_dyld_register_func_for_add_image`, resolves each image's local `___llvm_profile_write_file` through `__LINKEDIT`, flushes tracked images on Jet `after`, then writes the app image last (so flush-path counters land in the pulled app profraw). Static linkage still merges RNFB into the app binary (compile-only + app flush). Never put profile **link** flags on third-party/Firebase pods (`swiftCompatibility56`). diff --git a/okf-bundle/testing/code-coverage/pipelines.md b/okf-bundle/testing/code-coverage/pipelines.md new file mode 100644 index 0000000000..49f52d3cca --- /dev/null +++ b/okf-bundle/testing/code-coverage/pipelines.md @@ -0,0 +1,129 @@ +--- +type: Reference +title: 'Coverage: unit and TS e2e pipelines' +description: 'End-to-end coverage overview, unit coverage per platform, and Jet + NYC TypeScript e2e coverage.' +tags: [testing, coverage, e2e, jest] +timestamp: 2026-12-02T00:00:00Z +--- + +# Coverage: unit and TS e2e pipelines + +Part of [Coverage design](../coverage-design.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +# End-to-end overview + +```mermaid +flowchart LR + subgraph unit [Unit Jest] + J1[jest --coverage] --> J2[coverage/lcov.info] + end + subgraph ios_unit [Unit iOS XCTest] + U2[yarn tests:ios:unit] --> UNITLCOV["coverage/ios-unit/lcov.info"] + end + subgraph ts_e2e [E2e TypeScript] + M[Metro + inline source maps] --> A[App bundle] + A --> J[Jet --coverage] + J --> N[NYC remap] + N --> T2[coverage/lcov.info] + end + subgraph android_native [Android native Jacoco] + D1[Detox e2e] --> FLA["react-native-coverage.flush"] + FLA --> EC[coverage.ec in app filesDir] + EC --> P1[pull-native-coverage.js] + EXEC --> P1 + P1 --> JTR[jacocoTestReport] + JTR --> AX[jacocoTestReport.xml] + end + subgraph ios_native [iOS native LCOV] + D2[Detox e2e] --> FLI["react-native-coverage.flush"] + FLI --> PR[coverage.profraw in Documents] + PR --> P2[pull-native-coverage.js] + P2 --> LLVM[rn-coverage-ios-export.js] + UNITLCOV --> LLVM + LLVM --> I2[coverage/ios-native/lcov.info] + end + J2 --> C[Codecov] + T2 --> C + AX --> C + I2 --> C +``` + +# Unit coverage (Android JVM) + +```bash +yarn tests:android:unit +``` + +- Runner choice and `@Config` / `sdk` policy under `packages/*/android/src/test/java` — [AndroidTest-AD-1](../android-architecture-decisions.md#androidtest-ad-1). +- Gradle entry: `tests/android` `./gradlew rnfbDebugUnitTests` (all RNFB library `:testDebugUnitTest` tasks). +- Output: Jacoco `*.exec` under each module `build/` (and app build tree as configured). +- **Counts toward** the 100% touched-line bar when allowlisted unit tests exercise those lines. +- Not a substitute for e2e on platforms where the module loads ([platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking)). + + + +# Unit coverage (iOS XCTest) + +```bash +yarn tests:ios:unit +``` + +- Host/macOS-first in-package xcodeproj — [IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1). +- Discovers `packages/*/ios/*UnitTests/*.xcodeproj`; LLVM export → `coverage/ios-unit/lcov.info`. +- Discovery finds one project per package that ships one. Stub-header projects ([IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1-stub-headers)) report hits on the real production files they compile. +- **Merges into** `coverage/ios-native/lcov.info` (create or max-hits merge per `SF:`/`DA:`). After e2e, `rn-coverage-ios-export.js` merges the same unit file so e2e export does not drop XCTest hits. +- **Counts toward** the 100% touched-line bar when allowlisted unit tests exercise those lines. +- Not a substitute for e2e on platforms where the module loads ([platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking)). + +# Unit coverage (Jest) + +```bash +yarn tests:jest-coverage +``` + +- Jest + `coverageProvider: "babel"` (Istanbul), **not** NYC. +- Scope: `packages/**/__tests__/**` (`jest.config.js`). +- Output: `coverage/lcov.info` at repo root. +- Instruments `packages/*/lib/**` directly — no source-map remap. + +# E2e TypeScript coverage (Jet + NYC) + +**Run e2e:** [running e2e § Rules](../e2e/rules.md#rules) — canonical `:test-cover` commands only; do not duplicate them here. + +| Platform | Entry (repo root) | Notes | +| --- | --- | --- | +| macOS | `tests:macos:test-cover` | See runbook | +| iOS | `tests:ios:test-cover` | See runbook | +| Android | `tests:android:test-cover` | See runbook | + +Jet self-wraps under NYC with `--coverage`. + +**Tooling:** + +- Metro bundles `packages/*/dist/module/**` with inline source maps (`tests/.babelrc` and `tests-macos/.babelrc`: `useInlineSourceMaps: true`). +- NYC (`tests/nyc.config.js` and `tests-macos/nyc.config.js`) remaps to `packages/*/lib/**` → **`coverage/lcov.info`** (`cwd: '..'`). +- Jet re-invokes under the test-app `nyc` (checks `NYC_CONFIG`) — `tests/` for iOS/Android, `tests-macos/` for macOS. Detox/macOS need no extra `nyc` prefix; start Jet only via [running e2e](../running-e2e.md) packager commands. +- iOS/Android Jet-close also uses package `rn-coverage js pull`; their native post-processing + entrypoints run `rn-coverage js report` into `coverage/js//lcov.info`, using + `tests/nyc.config.js` for source-map remap. This supplements rather than replaces the RNFB + Jet/NYC transport and its `coverage/lcov.info` artifact. +- **Transfer:** patched test-runner/mocha-remote WS only (`coverage-ready` → `pull-coverage` → `coverage-data` → `coverage-ack`); HTTP POST `/coverage` deleted (`attachHttpServer` removed). Host launch/orchestrate control uses a **separate** HTTP server on **8091** (not the 8090 WS stack) — see [test-runner orchestration (log triage)](../e2e/run-loop.md#test-runner-host-orchestration-log-triage-only). Patches: `.yarn/patches/` (`jet`, `mocha-remote-client`, `mocha-remote-server`). See [iOS issues 6–6b](../../ci-workflows/ios.md#6-jet-websocket-disconnect-1006--1001), [issue 8](../../ci-workflows/ios.md#8-coverage-teardown-handshake-failure-tests-pass-nyc-00), [jet patch workflow](../../ci-workflows/detox-patches.md#updating-the-jet-patch-headless). + +**NYC settings:** + +```javascript +include: ['packages/*/lib/**/*.{js,ts,tsx}', 'packages/*/dist/**/*.js'], +sourceMap: true, 'exclude-after-remap': true, instrument: false, +reporter: ['lcov', 'html', 'text-summary'], +``` + +**Verify:** `coverage-ready` → `WS received N file(s)` (N > 0) → non-zero NYC; `coverage/lcov.info` has `SF:packages/...`, not only `dist/`. If `merged 0 file(s)`, see [troubleshooting](#ts-e2e-coverage-troubleshooting). + +### TS e2e coverage troubleshooting + +| Symptom | Cause | Fix | +| --- | --- | --- | +| `[jet-coverage] merged 0 file(s)` | Stale Metro bundle or missing test-runner patch | `yarn install`; macOS: restart packager per [running e2e § Rules #1](../e2e/rules.md#rules) | +| macOS bundle still has `'/coverage'` fetch | Metro resolves Jet via `"react-native": "src/index"` — patch must touch `jet/src/index.tsx`, not only `lib/` | Re-run after patch; `--reset-cache` | +| iOS/Android merged 0, macOS OK | Prebuilt app bundle predates Istanbul fix | Re-run [running e2e § Rules](../e2e/rules.md#rules) (`:build` then `:test-cover`) | +| Metro 500 on bundle | Missing babel plugins in `tests/` | `yarn install`; confirm `tests/node_modules/babel-plugin-istanbul` exists | diff --git a/okf-bundle/testing/code-coverage/policy.md b/okf-bundle/testing/code-coverage/policy.md new file mode 100644 index 0000000000..01c4f69c1b --- /dev/null +++ b/okf-bundle/testing/code-coverage/policy.md @@ -0,0 +1,118 @@ +--- +type: Reference +title: 'Coverage: goals and expectations (policy)' +description: 'Coverage goals, expectations, completion signal, coverage evidence package, anti-patterns, and platform parity.' +tags: [testing, coverage, policy, evidence] +timestamp: 2026-12-02T00:00:00Z +--- + +# Coverage: goals and expectations (policy) + +Part of [Coverage design](../coverage-design.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +# Goals + +Coverage shows exercised **TS library sources** (`packages/*/lib/**`), **native sources** (`packages/*/{android,ios}/**`), and **iOS Ruby helpers** (`packages/app/**/*.rb`, exclude `__tests__`). + +| Layer | Proves | Consumers | +| --- | --- | --- | +| **Unit (Jest)** | Package logic with mocks | Fast feedback on `lib/**` | +| **Unit (iOS Ruby)** | CocoaPods/SPM helper logic (`firebase_spm.rb`, etc.) via Minitest + SimpleCov | Fast feedback on `packages/app/**/*.rb`; LCOV `coverage/ios-ruby/lcov.info` | +| **Unit (Android JVM)** | Java state-machine / bridge logic — [AndroidTest-AD-1](../android-architecture-decisions.md#androidtest-ad-1) | Fast feedback on `packages/*/android/**`; Jacoco `*.exec` | +| **Unit (iOS XCTest)** | Native logic on macOS: Foundation-only projects, or real `.m`/`.mm` files compiled against stub headers and test doubles for React/Firebase/UIKit — [IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1) | Fast feedback on `packages/*/ios/**`; LCOV merged into `coverage/ios-native/lcov.info` | +| **E2e (Jet / Detox)** | Real app behaviour against Firebase emulators and cloud APIs | TS + native bridge integration | + +Codecov merges CI uploads. Project-level % can be noise; **file-level changed-source coverage** is signal. macOS e2e uses firebase-js-sdk only; no RNFB native coverage. + +**Android native coverage** merges JVM unit (`*.exec`) and e2e (`*.ec`) into **`jacocoTestReport`** — that merged XML is what Codecov `android-native` uploads. Lines exercised only by allowlisted Android unit tests **count** toward the 100% touched-line bar below. + +**iOS native coverage** merges in-package XCTest LCOV (`coverage/ios-unit/lcov.info` from `yarn tests:ios:unit`) and e2e LLVM export into **`coverage/ios-native/lcov.info`**. Lines exercised only by allowlisted iOS unit tests **count** toward the 100% touched-line bar — [IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1). + +# Coverage expectations (policy) + +For **new code**: + +* **Coverage only goes up** on files the change touches. +* **100% on touched TS/native/Ruby helper sources is the requirement**, not an aspiration. "Mostly covered" does not close the gate. +* **Android JVM unit Jacoco (`*.exec`)** counts toward that bar when allowlisted tests under `packages/*/android/src/test/java` exercise the touched lines — scope and e2e non-substitution: [AndroidTest-AD-1](../android-architecture-decisions.md#androidtest-ad-1); platforms where the module loads still need e2e ([platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking)). +* **iOS XCTest LCOV** counts toward that bar when allowlisted in-package tests (`yarn tests:ios:unit`) exercise touched `packages/*/ios/**` lines; unit LCOV **must merge** into `coverage/ios-native/lcov.info` — [IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1); [§ Unit coverage (iOS XCTest)](pipelines.md#ios-xctest-unit-lcov). +* **iOS Ruby SimpleCov** counts toward that bar for touched `packages/app/**/*.rb` (exclude `__tests__`) when exercised by `yarn tests:ios:ruby` — [§ iOS Ruby SimpleCov](local.md#ios-ruby-simplecov). +* **The only acceptable uncovered line is covered by an [acceptable exception](../authoring/quality-standards.md#acceptable-exceptions)** — an evidence-backed intractable limitation, quantified (e.g. "~NN% provably-unreachable Swift codegen"), or a user-accepted deferral with recorded rationale. +* **HandleMap TurboModule/Helper wiring** is a user-accepted exception to that 100% bar: lines that only delegate to a package Registry or `RNFBHandleMap` (`put` / `get` / `take` / `takeAll`) may stay uncovered. Do **not** extract a production `*Bridge` type solely so XCTest/JUnit can compile those TurboModule branches. Non-trivial lifecycle (replace = take then put, take-if-idle, take-then-abort / abort-all, unique-put collision abort) belongs on Registry or an existing holder — [IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1). +* **Every other gap is testable or dead code** — add the test (negative paths, failure branches, every reachable branch) or delete the unreachable/duplicate/superseded code. + +An uncovered line surfaced in `independent-review` is a review finding subject to [zero-deferral resolution](../authoring/quality-standards.md#review-findings--resolve-do-not-defer): fix it (add the test or delete the code) or clear it against the bar. Gap passes **add tests and remove dead code** together. + +## Coverage as completion signal + +File-level coverage, not green tests/types alone, marks completion. + +1. **Baseline** after full e2e (all relevant platforms). +2. Implement with tests. +3. **After** full e2e with single-test/suite narrowing reverted (area narrowing may persist per package workflow until pre-merge). +4. Touched files: coverage **only rises** until **intractable limits** (above). + +**Plateau below that limit → refactor**, not ship: + +* Large uncovered native blocks often mean **dormant code paths** — use coverage to find the live path, delete the rest. +* Duplicate traversal (e.g. visiting the same tree property twice) can pass tests while leaving untestable structure — simplify until coverage rises. + +Do not hand off closable gaps. Package workflows may define snapshot tooling (e.g. [pipeline scripts](../../packages/firestore/pipeline-implementation-workflow.md)). + + + +## Coverage evidence package + +**Blocking.** Required before **`review` gate** closes when the frozen diff touches `packages/*/lib/**`, native bridge sources (`packages/*/{android,ios}/**`), **or** iOS Ruby helpers (`packages/app/**/*.rb`). Jest green alone is insufficient. + +Produce after fresh e2e on every required platform (when native/lib touched), then post-process native artifacts ([§ stale coverage](local.md#stale-coverage-data)); for Ruby-only diffs, fresh `yarn tests:ios:ruby` is enough: + +| Section | Contents | +| --- | --- | +| **Artifacts** | Timestamps for `coverage/ios-native/lcov.info`, `coverage/ios-ruby/lcov.info` (when Ruby touched), Android merged `jacocoTestReport.xml` (unit `*.exec` + e2e `*.ec`), and any Jest coverage run | +| **Touched regions** | Per-file or per-function line % for changed logic (not whole-package aggregates only) | +| **Branch map** | Table: branch / input shape → test or e2e that exercises it | +| **Gaps** | Every line or branch below 100%: **fix** (test or delete dead code), or **acceptable exception** with wire/runtime evidence in durable OKF (e.g. [pipeline platform parity](../../packages/firestore/pipeline-platform-parity.md) probe row) | + +**Verdict line:** `100% on reachable touched lines` **or** `NOT 100%` with numbered gaps and disposition (fixed / intractable with evidence / user-accepted deferral). + +Record in `.agents/reports//coverage-evidence.md` (preferred) or work-queue notes. Orchestrators **must not** close `coverage_evidence_gate` or `review_gate` without this file when lib/native bridge is touched. + +Reviewers treat missing, stale, or NYC-only summaries as a **serious** finding ([change authoring § independent-review](../authoring/review-and-commit.md#independent-review)). + +### Subagent return fields (native / lib bridge touched) + +Blocking YAML (or equivalent table) before `coverage_evidence_gate` closes: + +```yaml +coverage_verdict: "100% on reachable touched lines" | "NOT 100%" +coverage_artifacts: + jacoco_xml: path # Android; use lcov path for iOS native + timestamp: ISO-8601 +touched_regions: + - file: packages/.../Foo.java + lines: "L10-L45" + line_pct: 100 +branch_map: + - branch: "onComplete when still registered" + test: "Functions.e2e.js — streaming cancel race" +gaps: [] # or numbered: disposition fixed | intractable+evidence | user-accepted deferral +``` + + + +### Anti-patterns (not coverage evidence) + +| Looks like coverage | Why it is not | +| --- | --- | +| Jet NYC `text-summary` after narrowed `:test-cover` | Remapped TS aggregate for loaded modules — does not report Jacoco/lcov on native bridge lines | +| Whole-package or whole-harness statement % | Signal is **per changed file/region** in the frozen diff | +| Stale Jacoco XML / lcov without matching e2e run | Post-process deletes raw artifacts; re-run e2e first ([§ stale coverage](local.md#stale-coverage-data)) | +| E2e pass counts alone | Proves behaviour, not line/branch coverage on touched native code | + +## Platform parity (pipeline and bridge code) + +For native-bridge features, **platform parity precedes coverage expansion**: iOS/Android/macOS behavior must match unless blocked by native SDK. RNFB bridge gaps are defects, not permanent `Platform.*` e2e branches. + +* **Policy and drift registry:** [Pipeline platform parity](../../packages/firestore/pipeline-platform-parity.md) +* **Work queue:** [Pipeline coverage and parity work queue](../../packages/firestore/pipeline-coverage-work-queue.md) diff --git a/okf-bundle/testing/code-coverage/test-app-modules.md b/okf-bundle/testing/code-coverage/test-app-modules.md new file mode 100644 index 0000000000..3b36633bc7 --- /dev/null +++ b/okf-bundle/testing/code-coverage/test-app-modules.md @@ -0,0 +1,48 @@ +--- +type: Reference +title: 'Coverage: test-app native modules and react-native-coverage' +description: 'Test-app native modules vs coverage flush, config-driven native coverage, and react-native-coverage.' +tags: [testing, coverage] +timestamp: 2026-12-02T00:00:00Z +--- + +# Coverage: test-app native modules and react-native-coverage + +Part of [Coverage design](../coverage-design.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + + + +# Test-app native modules vs coverage flush + +Do **not** conflate coverage flush with e2e probes. + +| Module | Kind | Role | +| --- | --- | --- | +| **`Coverage` (`react-native-coverage`)** | Package TurboModule | Flush only — [§ react-native-coverage](#react-native-coverage). | +| **`NativeRNFBTesting`** | Test-app TurboModule | E2e probes — [running e2e § test-app native modules](../e2e/rules.md#test-app-native-modules). | +| **`RNFBTestingMessaging`** | Test-app `RCTBridgeModule` | iOS messaging delegate probe — [running e2e § test-app native modules](../e2e/rules.md#test-app-native-modules). | + +Probe method names, product-line hits, and evidence recording: [running e2e § test-app native modules](../e2e/rules.md#test-app-native-modules) → [coverage evidence package](policy.md#coverage-evidence-package). + +# Config-driven native coverage (Pattern C) + +Native coverage knobs for the dedicated test app live in `tests/react-native-coverage.config.js` +(package-aligned shape). Node scripts load that file; Gradle copies are generated via +`yarn tests:coverage:generate-native-config` (`tests/android/coverage.properties`). LLVM +profile path and TurboModule flush come from **`react-native-coverage`**. Jacoco merge +(unit `*.exec` + e2e `*.ec`, `src/reactnative/java`) stays in `tests/android/app/jacoco.gradle`. + + + +# react-native-coverage (tests app only) + +Pattern C: only the **tests** workspace depends on published `react-native-coverage`: + +```json +"react-native-coverage": "0.2.0" +``` + +in `tests/package.json`. Host yarn scripts call package `rn-coverage` (`tests/scripts/rn-coverage-*.js`, +`pull-native-coverage.js`). Runtime flush uses the package TurboModule (`Coverage` / `flush()`). +Test-app probe modules (`NativeRNFBTesting`, `RNFBTestingMessaging`) are **not** flush — [running e2e § test-app native modules](../e2e/rules.md#test-app-native-modules). +Rollback if the cutover regresses: [§ coverage migration rollback](migration-rollback.md#coverage-migration-rollback). diff --git a/okf-bundle/testing/commands/constraints.md b/okf-bundle/testing/commands/constraints.md new file mode 100644 index 0000000000..55a53d6234 --- /dev/null +++ b/okf-bundle/testing/commands/constraints.md @@ -0,0 +1,41 @@ +--- +type: Reference +title: 'Agent commands: constraints block' +description: 'Condensed plain-text constraints block for pasting into agent prompts; each line is owned by a section of the command files.' +tags: [testing, agents, commands] +timestamp: 2026-12-02T00:00:00Z +--- + +# Agent commands: constraints block + +Part of [Agent command policy](../agent-command-policy.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Command constraints + + + +```text +RNFB agent command policy: okf-bundle/testing/agent-command-policy.md ONLY. +E2e: okf-bundle/testing/running-e2e.md yarn tests:* ONLY. +Expo example + documented-path iOS link (not Detox, build-only): yarn test-expo:ios:link ONLY — never ad-hoc expo prebuild / xcodebuild / cd test-expo; never yarn test-rn-bare:ios:build as that closer. Expo iOS 27 UIScene launch smoke (not Detox): yarn test-expo:ios:launch-smoke ONLY after link in the same checkout — never ad-hoc simctl launch / open -a Simulator / Device Hub. Typecheck: yarn tsc:compile:test-expo ONLY — never cd test-expo && tsc. JS lint is yarn lint:js (already includes test-expo/). Keep test-expo/package.json expo.autolinking.exclude ["@expo/ui"] — #expo-router-autolink-exclude-expo-ui. Per-module duplicate Objective-C class check (generated blank Expo app, build-only): yarn test-expo-fixture:ios:dupes --modules [,…] [--expect-duplicates N | --report-only] ONLY (--modules required; --modules "" = app only) — never ad-hoc expo prebuild / xcodebuild / create-expo-app / npm install in test-expo/.fixtures/; --expect-duplicates N passes only on exactly N duplicates (0: GULNetwork has one owner; N > 0: GULNetwork is duplicated); --report-only excludes --expect-duplicates; flag errors and invalid/duplicate/unpinned module names exit 2 before any build. Both Expo iOS runners wipe their DerivedData before every xcodebuild and refuse empty or unsafe override paths (exit 2); test-expo link, launch smoke, and the fixture runner share RNFB_TEST_EXPO_SPM_PACKAGES (never wiped); /tmp defaults carry a per-worktree repo-path tag — #expo-ios-derived-data. +RN CLI prebuilt RNCore iOS build (not Detox): yarn test-rn-bare:ios:build ONLY — never ad-hoc pod / xcodebuild / cd test-rn-bare; never tests/ e2e; never yarn test-expo:ios:link as that closer. Ad-hoc pod / xcodebuild stay never-use. Dynamic probe (RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1) deletes its DerivedData path before xcodebuild. Evidence from a probe that did not start from an empty DerivedData is invalid. Do not reuse RNFB_TEST_RN_BARE_DERIVED_DATA to save time. A new worktree does not reset ${TMPDIR:-/tmp} DerivedData. RN CLI iOS 27 UIScene launch smoke (not Detox): yarn test-rn-bare:ios:launch-smoke ONLY after build in the same checkout — never ad-hoc simctl launch / open -a Simulator / Device Hub; never yarn test-expo:ios:launch-smoke as that closer. Dynamic probe launch smoke: run it with the same RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1 immediately after the probe build; it wipes and uses its own RNFB_TEST_RN_BARE_LAUNCH_DERIVED_DATA. After a probe, git checkout -- test-rn-bare/ios/testrnbare.xcodeproj/project.pbxproj before committing. +Never react-native init / npx @react-native-community/cli init — @react-native-community/template is not installed by root yarn; one-shot pin + copy ios/ + JS, then remove pin — #react-native-community-template-checked-in-rn-cli-ios. +Never: yarn workspace prepare, yarn jet, npx jet, cd packages/* && yarn prepare/build for diagnostics. +Never invent format/install: yarn google-java-format, bare/npx google-java-format, npm install, yarn install in tests/ alone — use root yarn first; Java format = yarn lint:android ONLY (not Kotlin). Kotlin format = repo-root ./gradlew ktlintFormat ONLY with -PinternalKtlintGitFilter= (repo-root-relative packages/*/android/**/*.kt and, if touched, tests/android/**/*.kt); never ktlint CLI / npx ktlint / invented yarn ktlint. See #android-kotlin-format. +Never invent Android Gradle: ad-hoc ./gradlew outside yarn tests:android:unit / :build / :post-e2e-coverage / :test:jacoco-report and outside repo-root ./gradlew ktlintFormat; bare detox/jet/metro. +E2e slot devices: yarn tests:e2e:setup-ios-sims / setup-android-avds (create/reuse-only of the exact iOS neutral base; count decimal 1..8). Patched Detox reuses that base or fails when registry-taken (tests/patches/detox+20.51.0.patch via tests prepare; exact slot-0..7). yarn tests:e2e:release --devices shuts down the exact base. Direct check/release --slot=N uses the same 0..effective max guard as export-slot-env. Never direct xcrun simctl create/delete/erase/rename, simctl delete all|unavailable, simctl shutdown all. Legacy RNFB E2E iOS slot-N removal is human-operator only — okf-bundle/testing/running-e2e.md#ios-slot-simulator-migration. +Prepare/install: yarn or yarn lerna:prepare must exit 0 before ANY other command — never parallelize with e2e/Metro/build. +Before native :build: root yarn exit 0 + verify tests/node_modules/react-native/third-party-podspecs/fmt.podspec (and tests-macos copy when building macOS) ≥ 12.1.0 — okf-bundle/testing/agent-command-policy.md#install-patch-fmt-gate-blocking. Before iOS build on a clean checkout: root yarn, then yarn tests:ios:pod:install exit 0. If fmt < 12.1.0: STOP and re-run yarn; never invent Podfile/FMT_USE_CONSTEVAL/c++17 fmt hacks. +Area harness: okf-bundle/testing/running-e2e.md#local-harness-overrides-harnessoverridesjs — copy harness.overrides.example.js to gitignored harness.overrides.js; set modules + RNFBDebug; delete overrides after run. macOS App Check custom-provider e2e needs e2eHelperSecret — capture+merge ONLY via #app-check-e2e-helper-secret (never bare secrets:access; never secrets:set; never CI overwrite-only when modules/RNFBDebug exist; never commit harness.overrides.js). +TurboModule contract test (NewArch-AD-17.1): packages/app/__tests__/nativeModuleContract.test.ts — yarn tests:jest -- packages/app/__tests__/nativeModuleContract.test.ts +Android JVM unit (AndroidTest-AD-1, JUnit-first; omit @Config/sdk unless proven): yarn tests:android:unit — not a substitute for platform e2e. +iOS Ruby (SPM helpers): yarn tests:ios:ruby — never ad-hoc ruby packages/app/__tests__/…_test.rb as the gate. Never bundle install --gemfile=packages/app/__tests__/Gemfile. Host Ruby >= 3.3.1 (not 3.3.0); do not downgrade simplecov. +JS lint vendor flood under packages/app/__tests__/vendor/: local Bundler tree, not product lint. Never invent delete-vendor as the lint gate. See #js-lint-bundler-vendor. +Docs snippet type-check (blocking): yarn docs:tsc:check (DOCS_TSC_ALL=1 prints every failing fence): compiles docs/**/*.mdx js, javascript, jsx, ts, typescript and tsx fences; any failed fence or fence-grammar error exits non-zero. CI Documentation job. Detail: validation-checklist.md#docs-lint-gotchas. Never invent ad-hoc tsc on doc fences instead. +Docs member check (blocking): yarn docs:member:check: compare-types extraInRN names must be mentioned under docs//** except names in DEPRECATED_EXEMPT that are verified @deprecated in package source; runtime functions the usage pages teach must be referenced by the matching test-expo screen. No vertexai screen required. Detail: validation-checklist.md#docs-lint-gotchas. Never invent a second docs↔screen sync gate. +Docs lint: yarn lint:markdown already runs the snippet ESLint config (eslint.docs-snippets.config.mjs) and Prettier over the docs tooling files. Do not point eslintJs.configs.all at doc fences. +GitHub state (read-only): gh pr view/list/checks/diff, gh run list/view, gh issue view/list, gh api GET on read endpoints ONLY (needs full_network when sandboxed; GitHub is authoritative for CI check state). Never any gh command that writes (create/edit/merge/close/comment/review/ready, pr checkout (mutates the local working tree), run rerun/cancel, workflow run, release, repo mutations, auth, secret, gh api POST/PUT/PATCH/DELETE, -X other than GET, or -f/-F write fields). +Agent shell is zsh: capture exit codes with ${pipestatus[1]} or bare $? — ${PIPESTATUS[0]} is bash-only and expands to empty. See #agent-shell-is-zsh. +On failure: fix product code (or re-run yarn for patch miss), re-run the same canonical command. +Gate close / push: return [validation evidence package](../validation/evidence-and-handoff.md#validation-evidence-package) and [coverage evidence package](../code-coverage/policy.md#coverage-evidence-package) when lib/native/Ruby helpers touched — required before commit or publication ([change authoring § validation evidence](../authoring/gates.md#validation-evidence-blocking)). +``` diff --git a/okf-bundle/testing/commands/core.md b/okf-bundle/testing/commands/core.md new file mode 100644 index 0000000000..1102c3b889 --- /dev/null +++ b/okf-bundle/testing/commands/core.md @@ -0,0 +1,99 @@ +--- +type: Reference +title: 'Agent commands: core' +description: 'Allowlisted install, prepare, TS/JS validation, JS lint, read-only GitHub CLI and friction-log commands, prepare ordering, and shell traps.' +tags: [testing, agents, commands, yarn] +timestamp: 2026-12-02T00:00:00Z +--- + +# Agent commands: core + +Part of [Agent command policy](../agent-command-policy.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Canonical registry + +Rows of the canonical registry that this file owns. Other rows: [registry index](../agent-command-policy.md#canonical-registry). + +| Intent | Command | Never use instead | +| --- | --- | --- | +| Install / refresh deps | `yarn` (repo root; `postinstallDev` → `yarn prepare && yarn lerna:prepare && yarn ruby:install`) | `yarn workspace …`, `npm install`, `npm install` in a package, `yarn install` / `yarn` in `tests/` alone for root deps, skipping root `yarn` before e2e/build | +| Root Gemfile gems (CocoaPods, RuboCop, etc.) | `yarn ruby:install` (runs `bundle check \|\| bundle install` when `bundle` is on PATH, `ruby` on PATH is `>= 3.3.1` and `bundle --version` runs; otherwise **skips with exit 0** and one line naming why — JS-only checkouts, CI without setup-ruby, macOS system Ruby 2.6 `/usr/bin/bundle`); included in root `yarn` via `postinstallDev`. CI: `BUNDLE_FROZEN=true bundle install` **before** yarn in e2e/publish workflows | bare `bundle install` at repo root | +| Transpile `lib/**` → `dist/module/**` (all packages) | `yarn lerna:prepare` | `yarn workspace @react-native-firebase/* prepare`, `cd packages/ && yarn prepare`, `cd packages/ && yarn run build` | +| Transpile one package | `yarn lerna run prepare --scope @react-native-firebase/` | `yarn workspace @react-native-firebase/ prepare` | +| After `packages/*/lib/**` edits (Metro serves `dist/module/**`) | `yarn lerna:prepare`; Metro restart when already running ([running e2e § prepare completion gate](../e2e/preflight.md#prepare-completion-gate-blocking)) — platform `:build` only when [running e2e § Rules #3](../e2e/rules.md#rules) requires native/codegen/instrumentation, not for JS alone | ad-hoc `bob`, `babel`, or package-scoped prepare | +| TS/JS validation sequence | [validation checklist](../validation-checklist.md) | ad-hoc `tsc` in package dirs unless listed there | +| test-expo TypeScript check | `yarn tsc:compile:test-expo` (repo root; `tsc --project test-expo/tsconfig.json`) | `cd test-expo && tsc`; `cd test-expo && …` as a typecheck gate | +| JS lint (implementation / review gate) | `yarn lint:js`, `yarn lint:js --fix` (`eslint packages/* test-expo`; already includes `test-expo/`) | package-scoped `eslint`, `npx eslint`; a second `test-expo` lint entrypoint | +| Read-only GitHub state (PRs, checks, runs, issues) | `gh pr view` / `list` / `checks` / `diff`, `gh run list` / `view` (logs ok), `gh issue view` / `list`, and `gh api` with GET on read endpoints only. Prefer `--json` with `--jq` / `-q`. Needs unrestricted network (`full_network` in a sandboxed agent shell, see [sandbox / permissions](#shell-sandbox-permissions)). GitHub is authoritative for CI check state | `gh pr create` / `edit` / `merge` / `close` / `comment` / `review` / `ready`; `gh pr checkout` (mutates the local working tree); `gh run rerun` / `cancel`; `gh issue create` / `edit` / `comment` / `close`; `gh release`; `gh workflow run`; `gh repo` mutations; `gh auth`; `gh secret`; `gh api` with POST / PUT / PATCH / DELETE, `-X` other than GET, or write fields (`-f` / `-F`) | +| Workflow friction — read the inventory at item pickup; record friction met during the work | `yarn frog list` (current friction inventory); `yarn frog log` (interactive — record the friction just encountered) | Direct/global `frog`; `npx` / `yarn dlx` (and other package-runner downloads); reading, grepping, or hand-editing storage; ad-hoc friction records; inventing other `frog` subcommands or flags | + +### Prepare / transpile (detail) + +`yarn lerna:prepare` runs each package's **`prepare`** script (`build` → `compile` via react-native-builder-bob). That is what produces **`dist/module/**`** consumed by Metro in debug e2e — only **release\*\* builds pre-bundle/embed JS ([running e2e § Rules #3](../e2e/rules.md#rules)). + +- **`yarn compile`** (package script) is **not** a standalone agent entrypoint — it is invoked **inside** `prepare` via lerna. Do not run `cd packages/ && yarn compile` for handoff unless [validation checklist](../validation-checklist.md) explicitly adds an exception (none today). +- **`yarn`** at repo root runs `postinstallDev` → `yarn prepare && yarn lerna:prepare && yarn ruby:install`; a fresh install already transpiles and installs root Gemfile gems. Re-run **`yarn lerna:prepare`** after `lib/**` edits without reinstalling. + + + +### Prepare must finish first (blocking) + +**`yarn`**, **`yarn lerna:prepare`**, and **`yarn lerna run prepare --scope …`** are **blocking foreground** commands. Wait for the shell to return **exit code 0** before starting **any** other command — including in the same agent turn via parallel tool calls. + +| Do not start until prepare exits 0 | Why | +| --- | --- | +| `yarn tests:*` (e2e, packager, build) | Metro (debug JS) reads **`dist/module/**`**, not `lib/\*\*` — partial prepare → missing modules, stale bundles | +| `yarn tests:packager:jet-reset-cache` / `yarn tests:macos:packager:jet-reset-cache` | Reset after prepare, not during it. Free `:8081` first — [running e2e § packager reset-cache](../e2e/recovery.md#packager-reset-cache-eaddrinuse). Mobile packager is `tests/`; macOS packager is `tests-macos/` | +| `yarn tsc:compile`, `yarn tsc:compile:test-expo`, Jest, `compare:types` | May read transpiled output or assume `dist/` is current | +| Another `yarn` / scoped prepare | Overlapping Nx/Lerna runs race on `dist/` | + +**Agent rule:** one prepare invocation per message batch; wait for completion; then run the next step (Metro restart if needed → pre-flight → `:test-cover`). [Running e2e § prepare completion gate](../e2e/preflight.md#prepare-completion-gate-blocking) is the e2e-side mirror of this rule. + +**Symptoms when violated:** `Cannot find module '…/dist/module/…'`, Metro 500 on bundle, e2e failures before tests run, or green Metro `/status` while the app loads a half-written `dist/`. + +## When install or prepare fails + +1. Re-run from repo root: **`yarn`** or **`yarn lerna:prepare`** (full log — do not truncate). +2. Note the **first** Nx/Lerna project that failed (e.g. `@react-native-firebase/functions:prepare`). +3. Fix **product code** in that package (TypeScript errors, missing exports, etc.). +4. Re-run **`yarn lerna:prepare`** — same command, same cwd. +5. Do **not** “verify tooling” with `yarn workspace … prepare`, `yarn bin …`, or package-scoped `yarn run build` — Yarn 4 uses **different PATH** for those invocations ([genversion trap](#genversion--prepare-paths)). + +## Known traps + + + + + +### Cursor Shell sandbox / permissions + +When a Shell command returns with **no exit status** (e.g. "execution backend unavailable") under default sandbox permissions, retry the **same** canonical command with `required_permissions: ["all"]` — do **not** invent an alternate command because the sandboxed attempt failed to start. + +`yarn test-expo:ios:link` needs unrestricted network on the first attempt. Expo prebuild updates the CocoaPods repo from `cdn.cocoapods.org`, which returns 403 under the default agent sandbox. Request full network up front. A 403 is not a product failure. + +Local e2e (`yarn tests:*:test-cover`), the packager, emulator start, native builds, and host pre-flight probes that need real devices/simulators typically need unrestricted permissions on this host. A "no exit status" result on those commands is a sandbox artifact, not evidence the run failed or is incomplete — see [running e2e § running one iteration](../e2e/run-loop.md#running-one-iteration) for checking the tee log footer before concluding anything from a missing exit code. Startup-fail markers on the tee are immediate hard infra — [startup fail-fast poll](../e2e/startup-fail-fast.md#startup-fail-fast-poll) (`TELNET` / `emulator-16` / `ReactContext is null` / serial leftover `:12007`+`5554`; idle APP_STATUS is healthy; `currentStatus` / status-query timeout is latency, not a wave-kill). + + + +### Agent shell is zsh (`PIPESTATUS` is bash-only) + +`${PIPESTATUS[0]}` is **bash**. zsh spells it `${pipestatus[1]}` (1-indexed), and the bash form expands to the **empty string** — `yarn 2>&1 | tee /tmp/x.log; echo "EXIT=${PIPESTATUS[0]}"` prints `EXIT=` whether the target passed or failed. Tee-to-log is the normal pattern for long-running targets and every gate wants a per-command exit code, so a real exit 1 can be recorded as a pass and turn into a false finding. Use `${pipestatus[1]}`, or run the command bare and read `$?`. + +### genversion / prepare paths + +- **`genversion` exists** at root `node_modules/.bin` after `yarn`. +- **`yarn lerna:prepare`** (and `yarn install` → `postinstallDev`) runs prepare via Nx with root toolchain on PATH → bare `genversion` in package `"build"` scripts **works**. +- **`yarn workspace … prepare`** or **`cd packages/foo && yarn run build`** does **not** expose root-only devDependencies → `command not found: genversion`. That is **not** corrupt `node_modules`; do **not** patch scripts with `yarn run -T genversion` unless deliberately changing repo policy on `main`. + +### JS lint / Bundler vendor + + + +- `yarn lint:js` is `eslint packages/* test-expo --max-warnings=0`. That already covers `packages/app/__tests__/` and `test-expo/`. Do not invent a second lint entrypoint for `test-expo/`. `scripts/version.js` is not in it. +- After `bundle install --gemfile=packages/app/__tests__/Gemfile`, Bundler follows root `.bundle/config` `BUNDLE_PATH: vendor/bundle` and drops a gitignored tree at `packages/app/__tests__/vendor/`. ESLint `globalIgnores` does not list that path, so lint reports thousands of vendor findings. +- That is local checkout noise, not a product lint failure. CI without that tree stays green. +- Do not invent a delete-vendor command as the lint gate. Do not patch `eslint.config.mjs` to hide it. Root `yarn ruby:install` or root `yarn` is the canonical install path above. + + + +**Physical-device runs:** builds and runs on physical iOS or Android devices are not on the allowlist; run them only with explicit user authorization. diff --git a/okf-bundle/testing/commands/docs.md b/okf-bundle/testing/commands/docs.md new file mode 100644 index 0000000000..06a9ed80fe --- /dev/null +++ b/okf-bundle/testing/commands/docs.md @@ -0,0 +1,21 @@ +--- +type: Reference +title: 'Agent commands: docs' +description: 'Allowlisted docs lint, docs snippet type-check, and docs member check commands.' +tags: [testing, agents, commands, docs] +timestamp: 2026-12-02T00:00:00Z +--- + +# Agent commands: docs + +Part of [Agent command policy](../agent-command-policy.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Canonical registry + +Rows of the canonical registry that this file owns. Other rows: [registry index](../agent-command-policy.md#canonical-registry). + +| Intent | Command | Never use instead | +| --- | --- | --- | +| Docs lint | `yarn lint:markdown`, `yarn lint:markdown:fix`, `yarn lint:spellcheck`, `yarn lint:docs-links`. When and what each runs: [validation checklist § docs lint gotchas](../validation/docs-lint.md#docs-lint-gotchas) (docs tree or docs tooling only; OKF-only skips). `:fix` is Prettier `--write`. `lint:markdown` already includes the snippet ESLint config | ad-hoc `npx @docs.page/cli`; ad-hoc prettier/eslint on single files; `eslintJs.configs.all` against doc fences; bare `eslint --config eslint.docs-snippets.config.mjs` as a second gate | +| Docs snippet type-check | `yarn docs:tsc:check` (blocking; CI Documentation job; non-zero on failure). `DOCS_TSC_ALL=1 yarn docs:tsc:check` prints every failing fence (default prints the first 10). Scope, limits, and the ignore marker: [validation checklist § docs lint gotchas](../validation/docs-lint.md#docs-lint-gotchas) | ad-hoc `tsc` on doc fences / hand-copied snippets; treating the default first-10 output as the full list | +| Docs member check | `yarn docs:member:check` (blocking; CI Documentation job; docs vs compare-types configs and `test-expo` screens). What it checks and its guards: [validation checklist § docs lint gotchas](../validation/docs-lint.md#docs-lint-gotchas) | inventing a second docs↔screen sync check; requiring a `vertexai` screen | diff --git a/okf-bundle/testing/commands/e2e.md b/okf-bundle/testing/commands/e2e.md new file mode 100644 index 0000000000..46d5575265 --- /dev/null +++ b/okf-bundle/testing/commands/e2e.md @@ -0,0 +1,52 @@ +--- +type: Reference +title: 'Agent commands: e2e and coverage' +description: 'Allowlisted e2e, pre-flight, slot, coverage post-process, Detox cache, CocoaPods provisioning, and App Check helper secret commands.' +tags: [testing, agents, commands, e2e, coverage] +timestamp: 2026-12-02T00:00:00Z +--- + +# Agent commands: e2e and coverage + +Part of [Agent command policy](../agent-command-policy.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Canonical registry + +Rows of the canonical registry that this file owns. Other rows: [registry index](../agent-command-policy.md#canonical-registry). + +| Intent | Command | Never use instead | +| --- | --- | --- | +| iOS CocoaPods provisioning before shared build | `yarn tests:ios:pod:install` (after root `yarn` or `yarn ruby:install` when gems are missing; required order below) | bare `pod install`, `cd tests/ios && pod install`, or assuming `yarn tests:ios:build` creates CocoaPods support files | +| Android merged Jacoco (unit + e2e) | `yarn tests:android:post-e2e-coverage` (after e2e); `yarn tests:android:test:jacoco-report` when regenerating the merge report | `./gradlew jacocoAndroidTestReport` as Codecov path; inventing other jacoco yarn scripts | +| Native coverage presence guard (silent-empty fail) | `yarn tests:coverage:assert-presence` (also invoked from `tests:android:post-e2e-coverage` and `tests:ios:test:process-coverage`; exit **2** on empty/missing when strict) | Ignoring empty LCOV/Jacoco; treating missing `.ec` / `packagesHits=0` as soft success in CI | +| Native coverage baseline capture (repeatability) | `yarn tests:coverage:capture-baseline` (after Law `:test-cover` + process; see `tests/coverage-artifacts/README.md`) | Hand-editing `coverage-baseline.json`; inventing parallel capture scripts | +| Native coverage config generate (Gradle properties) | `yarn tests:coverage:generate-native-config` | Hand-editing generated `tests/android/coverage.properties` as the source of truth | +| E2e + coverage | [running e2e](../running-e2e.md) — **only** `yarn tests:*` | `jet`, `npx jet`, `yarn jet`, `detox test`, bare `detox`, `cd tests && …`, `cd tests-macos && …`, direct Metro/emulator starts | +| iOS Detox framework cache rebuild | `yarn tests:ios:detox-framework-cache:rebuild` | `cd tests && yarn detox clean-framework-cache`, `cd tests && yarn detox build-framework-cache`, bare `detox …` | +| Host pre-flight (before each `:test-cover`) | [running e2e § pre-flight](../e2e/preflight.md#pre-flight-is-the-host-clear-to-start) — host-clear + services ready + **[checkout ownership](../e2e/preflight.md#services-checkout-ownership-blocking)** + harness tier. `yarn tests:e2e:check` / `yarn tests:e2e:release` ([host-clear probes](../e2e/preflight-host-clear.md#host-clear-probes)) | Port/HTTP checks alone when Metro/emulators belong to another worktree; `pgrep`/spawn probes of Jet/Detox as completion signals; ad-hoc `pgrep` / hardcoded `:8090` only; improvised kill lists; `killall` / `pkill -f` by name; `adb kill-server`; `yarn tests:e2e:release --all-slots` or `--include-unrecorded` without explicit user direction ([manual machine wipe](../e2e/preflight-host-clear.md#manual-machine-wipe)) | +| E2e slot devices (first use of a slot) | `yarn tests:e2e:setup-android-avds [count]` / `yarn tests:e2e:setup-ios-sims [count]` — **create/reuse-only** of the exact iOS neutral base; count is a strict decimal **1..8** ([slot index](../e2e/environment.md#e2e-slot-index)). Patched Detox reuses that base or fails when registry-taken; check/release target its exact name — [iOS slot simulators](../e2e/slot-devices.md#ios-slot-simulators). Teardown of a running device is `yarn tests:e2e:release --devices` (shutdown, never delete) | Direct `xcrun simctl create/delete/erase/rename`, `avdmanager` / `sdkmanager` device commands, `simctl delete all`/`unavailable`, `simctl shutdown all`. Removing a legacy simulator is a **human-operator** step — [migration](../e2e/slot-devices.md#ios-slot-simulator-migration) | +| Slotted parallel | [running e2e § slot lifecycle](../e2e/environment.md#slot-lifecycle) — `eval "$(yarn tests:e2e:export-slot-env N)"` then the **same** `yarn tests:packager:*` / `yarn tests:emulator:start` / `pod:install` / `:build` / `:test-cover` as serial. macOS packager is `yarn tests:macos:packager:*` (`tests-macos/`); mobile is `yarn tests:packager:*` (`tests/`) | ad-hoc port math; second lifecycle helpers as the runbook; rsync between local worktrees; host flock; Metro-after-build; disabling Swift explicit modules; Debug `RCT_NO_LAUNCH_PACKAGER` as a Metro fix; using the mobile packager for macOS Jet (or vice versa) | +| Install App Check e2e helper secret into local harness overrides | Capture+merge recipe in [§ App Check e2e helper secret](#app-check-e2e-helper-secret) only — `functions:secrets:access` stdout is captured into `E2E_HELPER_SECRET` and merged into gitignored `tests/harness.overrides.js` (preserves `modules` / `RNFBDebug`). Repo root after `yarn`; equivalently via [`.github/workflows/scripts/firebase-cli.sh`](../../../.github/workflows/scripts/firebase-cli.sh). Requires `firebase login` with access to `react-native-firebase-testing`. Field semantics: [running e2e § local harness overrides](../e2e/narrowing.md#local-harness-overrides-harnessoverridesjs) | Bare `functions:secrets:access` (prints secret into the transcript); `gcloud secrets …`; inventing other Secret Manager CLIs; `firebase functions:secrets:set` (operator/deploy only — [firebase-testing-project](../firebase-testing-project.md#e2e-cloud-helper-callables)); CI-style overwrite-only write when other override fields already exist; committing `harness.overrides.js`; echoing / logging the secret | + + + +### App Check e2e helper secret (local access + merge) + +**Canonical owner** for the shell recipe that fetches `E2E_HELPER_SECRET` and installs it as `e2eHelperSecret` in gitignored `tests/harness.overrides.js`. Why / skip behavior / iOS–Android debug tokens: [running e2e § macOS App Check helper secret](../e2e/narrowing.md#macos-app-check-helper-secret). Secret Manager **set** + deploy: [firebase-testing-project § e2e cloud helper callables](../firebase-testing-project.md#e2e-cloud-helper-callables). + +Repo root after `yarn`. Run **only** the capture+merge form below — never a bare `functions:secrets:access` (its stdout is the secret). Do **not** echo or log the secret; do **not** commit `tests/harness.overrides.js`. + +Merges into an existing overrides file (preserves `modules` / `RNFBDebug` / other fields). If the file exists but fails to load, exit 1 and do **not** write. Never use the CI overwrite-only write from `.github/workflows/tests_e2e_other.yml` when those fields already exist: + +```bash +E2E_HELPER_SECRET="$(./node_modules/.bin/firebase functions:secrets:access E2E_HELPER_SECRET --project react-native-firebase-testing)" \ +node -e 'const fs=require("fs"); const path=require("path"); const f="tests/harness.overrides.js"; let o={}; if(fs.existsSync(f)){ try{ o=require(path.resolve(f)); }catch(e){ console.error("failed to load "+f+": "+e.message); process.exit(1);} } if(!process.env.E2E_HELPER_SECRET){ console.error("empty secret"); process.exit(1);} o.e2eHelperSecret=process.env.E2E_HELPER_SECRET; fs.writeFileSync(f, "module.exports = " + JSON.stringify(o, null, 2) + ";\n");' +``` + +`functions:secrets:set` is **not** on this allowlist for routine agent use. + +### Jet + +- **`yarn jet --help`** working or failing in `tests/` is **not** a valid e2e or install gate. +- Jet is started **internally** by `yarn tests::test-cover`. Stale `:8090` → [pre-flight recovery](../e2e/recovery.md#pre-flight-recovery), then re-run the same `:test-cover` command. +- Metro `EADDRINUSE` on `:8081` from `yarn tests:packager:jet-reset-cache` or `yarn tests:macos:packager:jet-reset-cache` → [packager reset-cache](../e2e/recovery.md#packager-reset-cache-eaddrinuse) (free `:8081`, then the same yarn target). Not the `:8090` pre-flight kill. Do **not** use the mobile packager for macOS Jet (or vice versa). diff --git a/okf-bundle/testing/commands/fixtures.md b/okf-bundle/testing/commands/fixtures.md new file mode 100644 index 0000000000..19d063f5f8 --- /dev/null +++ b/okf-bundle/testing/commands/fixtures.md @@ -0,0 +1,91 @@ +--- +type: Reference +title: 'Agent commands: Expo and RN CLI fixtures' +description: 'Allowlisted test-expo link, launch smoke, duplicate ObjC class check, test-rn-bare build and launch smoke, DerivedData rules, and fixture traps.' +tags: [testing, agents, commands, expo] +timestamp: 2026-12-02T00:00:00Z +--- + +# Agent commands: Expo and RN CLI fixtures + +Part of [Agent command policy](../agent-command-policy.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Canonical registry + +Rows of the canonical registry that this file owns. Other rows: [registry index](../agent-command-policy.md#canonical-registry). + +| Intent | Command | Never use instead | +| --- | --- | --- | +| Expo documented-path iOS link (workspace `test-expo/`; also the user-facing Expo example) | `yarn test-expo:ios:link` (repo root; script `.github/workflows/scripts/test-expo-ios-link.sh`). **Build-only** (`xcodebuild build`; does not launch). Builds into `RNFB_TEST_EXPO_DERIVED_DATA` (default `/tmp/test-expo-derived-data-`), wiped before every `xcodebuild`; Swift package checkouts in `RNFB_TEST_EXPO_SPM_PACKAGES` (default `/tmp/test-expo-spm-packages-`, never wiped, shared with the launch smoke and the fixture runner) — [§ Expo iOS DerivedData](#expo-ios-derived-data). Keep `expo.autolinking.exclude: ["@expo/ui"]` in `test-expo/package.json` — [gotcha](#expo-router-autolink-exclude-expo-ui). After `packages/*/plugin/src` edits run `yarn lerna:prepare` first — [gotcha](#test-expo-link-stale-plugin-build) | ad-hoc `expo prebuild` / `xcodebuild` outside that script; `cd test-expo && …` as the agent gate (link, typecheck, or launch); `yarn test-rn-bare:ios:build` as this closer; dropping the `@expo/ui` autolink exclude | +| Expo iOS 27 UIScene launch smoke (`test-expo/`; after link) | `yarn test-expo:ios:launch-smoke` (repo root; script `.github/workflows/scripts/test-expo-ios-launch-smoke.sh`). **Debug build + launch** on an iOS 27 simulator via `simctl` (runs its own Debug `xcodebuild`, which reuses `RNFB_TEST_EXPO_SPM_PACKAGES`; starts fixture Metro internally; requires prior `yarn test-expo:ios:link` in the same checkout). Simulator: `RNFB_TEST_EXPO_IOS27_DEVICE` (default `iPhone 18 Pro`) on `RNFB_TEST_EXPO_IOS27_RUNTIME` (default `iOS 27.0`); set both when the host has no such available simulator (the script exits 1). Not Detox | ad-hoc `simctl` / `xcodebuild` / `cd test-expo && expo start` outside that script; `open -a Simulator`; Device Hub | +| Expo per-module duplicate Objective-C class check (generated blank Expo app under gitignored `test-expo/.fixtures//`) | `yarn test-expo-fixture:ios:dupes --modules [,…] [--expect-duplicates N \| --report-only]` (repo root; script `.github/workflows/scripts/test-expo-fixture-ios-dupes.sh`). Generates `@react-native-firebase/app` + the listed modules with `lib/make-expo-fixture.sh` (pins from `test-expo/package.json`), prebuilds, builds Release unsigned for the iOS Simulator from an empty DerivedData (`RNFB_TEST_EXPO_FIXTURE_DERIVED_DATA`, default `/tmp/test-expo-fixture-derived-data--`; Swift package checkouts in the shared `RNFB_TEST_EXPO_SPM_PACKAGES`), then runs the shared `check-duplicate-objc-classes.sh` scan on the built `.app`. Build-only — [§ Expo iOS DerivedData](#expo-ios-derived-data). `--modules` is required; `--modules ""` builds app only; invalid, duplicate, or unpinned (not in `test-expo/package.json`) module names exit 2 before any build; `--expect-duplicates N` (default 0) passes only on exactly N duplicated classes: with 0 the `GULNetwork` canary must have exactly one owner, with N > 0 `GULNetwork` must be among the duplicates (proves the control exercised the GoogleUtilities graph); `--report-only` lists every duplicate plus the `GULNetwork` and `FIRApp` owners and exits 0 unless a scan guard fails. `--report-only` and `--expect-duplicates` are mutually exclusive; flag errors exit 2 before any build. Needs unrestricted network, like `yarn test-expo:ios:link`. Fixtures live under `test-expo/` — [gotcha](#expo-fixture-under-test-expo) | ad-hoc `expo prebuild` / `xcodebuild` / `create-expo-app` / `npm install` in the fixture; `cd test-expo/.fixtures/… && …`; reusing a DerivedData between module combinations; `yarn test-expo:ios:link` as this check | +| RN CLI prebuilt RNCore iOS build (workspace `test-rn-bare/`) | `yarn test-rn-bare:ios:build` (repo root; script `.github/workflows/scripts/test-rn-bare-ios-build.sh`). Dynamic probe (`RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1`) deletes its DerivedData before xcodebuild — [§ dynamic probe DerivedData](#dynamic-firebase-probe-derived-data) | ad-hoc `pod` / `xcodebuild`; `cd test-rn-bare && …`; `tests/` e2e / `yarn tests:*`; `yarn test-expo:ios:link` as this closer; reusing `RNFB_TEST_RN_BARE_DERIVED_DATA` to skip a clean probe | +| RN CLI iOS 27 UIScene launch smoke (`test-rn-bare/`; after build) | `yarn test-rn-bare:ios:launch-smoke` (repo root; script `.github/workflows/scripts/test-rn-bare-ios-launch-smoke.sh`). **Launch** on an iOS 27 simulator via `simctl` (requires prior `yarn test-rn-bare:ios:build` in the same checkout). Simulator: `RNFB_TEST_RN_BARE_IOS27_DEVICE` (default `iPhone 18 Pro`) on the shared `RNFB_IOS_SIM_RUNTIME` (default `iOS 27.0`); a missing device of that name is created on that runtime from `RNFB_IOS_BASE_SIMULATOR` (default `iPhone 17`), and the script exits 1 when the host has no such available runtime. Not Detox. Dynamic probe: same command with `RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1` after a probe build — [§ dynamic probe launch smoke](#dynamic-firebase-probe-launch-smoke) | ad-hoc `simctl` / `xcodebuild` / `cd test-rn-bare && …` outside that script; `open -a Simulator`; Device Hub; `yarn test-expo:ios:launch-smoke` as this closer | + + + +### Dynamic Firebase probe DerivedData + +`yarn test-rn-bare:ios:build` with `RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1` deletes its DerivedData path before `xcodebuild`, including when `RNFB_TEST_RN_BARE_DERIVED_DATA` overrides that path. Evidence from a probe that did not start from an empty DerivedData is invalid. Do not reuse `RNFB_TEST_RN_BARE_DERIVED_DATA` to save time. A new worktree does not reset `${TMPDIR:-/tmp}` DerivedData. The normal (non-probe) build does not delete DerivedData. + + + +### Dynamic Firebase probe launch smoke + +`yarn test-rn-bare:ios:launch-smoke` does its own Debug `xcodebuild` and never reads the build script's Release DerivedData (`RNFB_TEST_RN_BARE_DERIVED_DATA`). It launches the probe graph only because the preceding probe `yarn test-rn-bare:ios:build` left a probe Pods project behind, so run it with the same `RNFB_TEST_RN_BARE_DYNAMIC_FIREBASE=1` in the same checkout, right after that build. With the flag on it also: + +- fails if the Pods project is not a probe install; +- builds Debug into its own DerivedData (`RNFB_TEST_RN_BARE_LAUNCH_DERIVED_DATA`, default `${TMPDIR:-/tmp}/test-rn-bare-launch-derived-data-dynamic-firebase`), deleted first, and launches only from there; +- fails unless `RNFBFirebase.framework` is embedded in the app, the app binary (`testrnbare` or `testrnbare.debug.dylib`) has an undefined `RNFBFirebase` `AppClient` symbol (`nm -u`, so the facade is what calls configure), `RNFBFirebase.framework/RNFBFirebase` is mapped into the running process (`lsof`), and the probe-owned `RNFB_PROBE_CONFIGURE_OK` breadcrumb appears in the app log (NSLog after `RNFBFirebaseAppClient.configure()`; primary configure proof at default log level). FirebaseCore's `I-COR000001` / `Configuring the default app.` is soft-only: missing I-COR with a present breadcrumb (and passing dyld/scene checks) is insufficient to conclude configure was skipped — treat as debug-logging/capture flake (warn + diagnostics). The app is still launched with `-- -FIRDebugEnabled` after the log stream reports ready so I-COR can be observed when available. +- On CI (`test-rn-bare-ios-build-dynamic-firebase`), a failed job uploads probe launch / metro / xcodebuild logs (and optional `${APP_LOG}.retro.txt` from a retrospective `simctl … log show`) as artifact `rn-bare-dynfb-launch-smoke-logs`. + +The probe install sets the Swift compilation condition `RNFB_DYNAMIC_FIREBASE_PROBE` (next to the `RNFB_DYNAMIC_FIREBASE_PROBE=1` preprocessor define) on the `RNFBApp` pod and on the app's native targets. The undefined-symbol check above doubles as proof the condition reached the app target: if `AppDelegate.swift` compiled its `#else` branch, the binary would not reference the facade. A flag-off `pod install` removes the condition from the app project again. + +Flag off keeps the original build, app lookup, and assertions. + +The probe moves Firebase products off `RNFBApp` (onto `RNFBFirebase`), not every Swift package product: in the monorepo the `messaging` / `analytics` siblings always exist, so `RNFBApp` still declares `GULMethodSwizzler` / `GULNetwork` / `GULReachability` ([GoogleUtilities declarer](../../ios-spm-native-imports.md#googleutilities-explicit-spm_dependency-lets-pods-share-one-product)). The probe's single-copy assertions are unaffected: `FIRApp` is defined once, in `RNFBFirebase`. + +A probe `pod install` rewrites the tracked `test-rn-bare/ios/testrnbare.xcodeproj/project.pbxproj`. Restore it with `git checkout -- test-rn-bare/ios/testrnbare.xcodeproj/project.pbxproj` before committing. + + + +### Expo iOS DerivedData + +`yarn test-expo:ios:link` (`RNFB_TEST_EXPO_DERIVED_DATA`, default `/tmp/test-expo-derived-data-`) and `yarn test-expo-fixture:ios:dupes` (`RNFB_TEST_EXPO_FIXTURE_DERIVED_DATA`, default `/tmp/test-expo-fixture-derived-data--`) delete their DerivedData path before every `xcodebuild`, so each run starts from an empty DerivedData. Both check the path with the shared `lib/derived-data-path.sh` before any build and exit 2 when it is empty (an override set to the empty string is not replaced by the default), has a `..` component, is `/`, `$HOME`, the repo root, or an ancestor of `$HOME` / the repo root, or its basename does not contain `derived-data` / `DerivedData`. + +`yarn test-expo:ios:link`, `yarn test-expo:ios:launch-smoke`, and `yarn test-expo-fixture:ios:dupes` share Swift package checkouts in `RNFB_TEST_EXPO_SPM_PACKAGES` (default `/tmp/test-expo-spm-packages-`, `-clonedSourcePackagesDirPath`). No runner wipes it. + +`` is the first 8 hex characters of the `shasum` (SHA-1) of the resolved (`pwd -P`) repo root (`repo_path_tag` in `lib/derived-data-path.sh`), so each worktree gets its own `/tmp` defaults. `` is the checked `--modules` list joined with `-` (`app` for `--modules ""`). + +### `@react-native-community/template` (checked-in RN CLI `ios/`) + + + +- **`@react-native-community/template` is not installed by root `yarn`.** It is not a `react-native` dependency, so a green install does **not** put the community template under `node_modules`. +- Seeding or refreshing a **checked-in** RN CLI `ios/` tree (fixture app under the monorepo) after yarn **cannot** assume that package exists. The checked-in vanilla CLI compile fixture is `test-rn-bare/` (closer `yarn test-rn-bare:ios:build`). Do not re-seed it. +- **Workaround:** one-shot pin `@react-native-community/template@` on the fixture package, copy `ios/` + JS entry files from the template into the fixture, then **remove** the pin. Do not leave the template as a durable dependency. +- **Never** `react-native init` / `npx @react-native-community/cli init` / `npx react-native init` — not on the agent allowlist (see [Forbidden](forbidden.md#forbidden-always)). + +### expo-router autolink exclude (`@expo/ui`) + + + +`expo-router` depends on `@expo/ui`. Yarn can resolve a `@expo/ui` that does not compile against the fixture's `expo-modules-core` (`ContentOriginRegistry` / `ShadowNodeProxy`). `test-expo` does not use Expo UI. Keep `expo.autolinking.exclude: ["@expo/ui"]` in `test-expo/package.json`. Do not drop it as unused config. Dropping it makes `yarn test-expo:ios:link` fail at compile (exit 65). + +### Config plugin edits need prepare before the link run + + + +`yarn test-expo:ios:link` prebuilds from the existing `packages/*/plugin/build` and does not rebuild config plugins, so after a `packages/*/plugin/src` edit it can exit 0 on the stale build. Run `yarn lerna:prepare` first, then confirm the generated native file (e.g. `test-expo/ios/testexpo/AppDelegate.swift`) contains the plugin change. + +### Expo sources live only under `test-expo/node_modules` + + + +Root `node_modules` has no `expo`, `@expo/config-plugins` or `expo-build-properties` ([why](#expo-fixture-under-test-expo)). When checking config-plugin behaviour (mod-compiler ordering, `SceneEventForwarder`, `expo-build-properties` mods), read those sources under `test-expo/node_modules/` with read-only file tools. Do not use `node -e` / `node -p` to resolve or inspect them; neither is on the allowlist. + +### Expo fixtures live under `test-expo/` + + + +`.yarnrc.yml` sets `nmHoistingLimits: workspaces`, so the repo root `node_modules` does not hold `expo` or the RNFB symlinks, and its `react-native` is a different version than `test-expo`'s pin. A generated Expo fixture installs nothing and resolves packages by walking up to `test-expo/node_modules`. `lib/make-expo-fixture.sh` therefore refuses an `--out` outside `test-expo/`; `yarn test-expo-fixture:ios:dupes` writes to gitignored `test-expo/.fixtures//`. Do not generate fixtures at the repo root or in `/tmp`. diff --git a/okf-bundle/testing/commands/forbidden.md b/okf-bundle/testing/commands/forbidden.md new file mode 100644 index 0000000000..082f6009ee --- /dev/null +++ b/okf-bundle/testing/commands/forbidden.md @@ -0,0 +1,33 @@ +--- +type: Reference +title: 'Agent commands: forbidden (always)' +description: 'Commands agents must never run, with the reason and the canonical replacement.' +tags: [testing, agents, commands] +timestamp: 2026-12-02T00:00:00Z +--- + +# Agent commands: forbidden (always) + +Part of [Agent command policy](../agent-command-policy.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Forbidden (always) + +| Command | Why | +| --- | --- | +| `yarn workspace @react-native-firebase/* prepare` (and variants) | Not canonical; breaks root devDependency binary resolution | +| `cd packages/ && yarn prepare` / `yarn run build` | Same trap; not the postinstall / lerna code path | +| `yarn google-java-format`, bare `google-java-format`, `npx google-java-format`, `google-java-format -i` | Invented format entrypoints — **only** `yarn lint:android` for **Java** | +| `ktlint`, `npx ktlint`, invented `yarn` ktlint scripts, `cd tests/android && ./gradlew ktlintFormat` | Invented Kotlin format — **only** repo-root `./gradlew ktlintFormat` | +| `npm install` (any cwd) / `yarn` / `yarn install` only in `tests/` for monorepo deps | Root `yarn` applies patches and workspace links; tests-only install is insufficient | +| Ad-hoc `./gradlew …` outside allowlisted yarn scripts (`tests:android:unit`, `tests:android:build`, `tests:android:post-e2e-coverage`, `tests:android:test:jacoco-report`, etc.) and outside repo-root `./gradlew ktlintFormat` | Wrong task / cwd / report path; invents CI that does not match Codecov | +| Ad-hoc `xcodebuild test` / CocoaPods `test_spec` / `tests/ios/testingTests` as the iOS unit gate | Misses LCOV merge — **only** `yarn tests:ios:unit` ([IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1)) | +| Ad-hoc `ruby packages/app/__tests__/…_test.rb` (or bare runner) as the validation gate | Misses SimpleCov / suite discovery — **only** `yarn tests:ios:ruby` | +| Ad-hoc `expo prebuild`, `xcodebuild`, `cd test-expo && tsc`, or `cd test-expo && …` as a test-expo link, typecheck, or launch gate | **Only** `yarn test-expo:ios:link` / `yarn tsc:compile:test-expo` from repo root — not Detox / `yarn tests:*` / `yarn test-rn-bare:ios:build` | +| Ad-hoc `pod`, `xcodebuild`, or `cd test-rn-bare && …` as the RN CLI prebuilt RNCore iOS build gate | **Only** `yarn test-rn-bare:ios:build` from repo root — not Detox / `yarn tests:*` / `yarn test-expo:ios:link`. Ad-hoc `pod` / `xcodebuild` stay never-use | +| `react-native init`, `npx @react-native-community/cli init`, `npx react-native init` | Not on the allowlist — seed checked-in RN CLI trees via [template gotcha](fixtures.md#react-native-community-template-checked-in-rn-cli-ios) | +| `yarn jet`, `npx jet`, `cd tests && yarn jet …` | [E2e agent rule](../running-e2e.md#agent-rule-read-first) | +| `detox test`, bare `detox`, `cd tests && detox …` | E2e agent rule | +| bare `bundle install` at repo root | Use **`yarn ruby:install`** or root **`yarn`** (`postinstallDev` includes ruby:install) | +| Ad-hoc Metro / emulator start | Use `yarn tests:packager:jet` (iOS/Android) or `yarn tests:macos:packager:jet` (macOS), `yarn tests:emulator:start` ([running e2e](../e2e/rules.md#rules)) | +| Direct `xcrun simctl delete` / `erase` / `rename` / `create` (and `simctl delete all` / `unavailable`, `simctl shutdown all`) as e2e device management | Destroys devices other worktrees, repos, or operators may be mid-run on. Provision with `yarn tests:e2e:setup-ios-sims` (create/reuse-only), free with `yarn tests:e2e:release --devices` (shutdown only). Legacy-simulator removal is human-operator — [migration](../e2e/slot-devices.md#ios-slot-simulator-migration) | +| Spawn / PATH probes to “test” Jet or genversion | Log triage only; fix product code and re-run canonical command | diff --git a/okf-bundle/testing/commands/native-build-gate.md b/okf-bundle/testing/commands/native-build-gate.md new file mode 100644 index 0000000000..ebbeff1f7f --- /dev/null +++ b/okf-bundle/testing/commands/native-build-gate.md @@ -0,0 +1,52 @@ +--- +type: Reference +title: 'Agent commands: install / patch / fmt gate' +description: 'Blocking install, patch, fmt and CocoaPods checks before any native :build, and the fmt / Apple Clang 21 trap.' +tags: [testing, agents, commands, ios, build] +timestamp: 2026-12-02T00:00:00Z +--- + +# Agent commands: install / patch / fmt gate + +Part of [Agent command policy](../agent-command-policy.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + + + +### Install / patch / fmt gate (blocking before native `:build`) + +**Canonical owner** for install + patch freshness before Detox native builds. E2e docs link here — do not restate this procedure elsewhere. + +**Before any** `yarn tests:ios:build`, `yarn tests:android:build`, or other Detox native build path: + +1. **Root `yarn` MUST have run and exited 0** in this checkout. Required on a fresh checkout, after deleting `node_modules`, after pulling patch changes, and whenever patches may be stale. Do **not** start native `:build` until that install finished successfully. +2. Root `yarn` applies **`.yarn/patches`** (jet, detox, mocha-remote) and workspace **`patch-package`**. **`tests/patches/detox+20.51.0.patch`** is required for slotted iOS exact-base-or-fail allocation ([running e2e § iOS slot simulators](../e2e/slot-devices.md#ios-slot-simulators)) — it is **not** the Yarn Berry Detox patch. **macOS** still applies **`tests-macos/patches/react-native+0.78.3.patch`** (fmt **12.1.0**). **Mobile RN 0.86.2** ships fmt **12.1.0** upstream (no `tests/patches/react-native+*.patch` fmt bump). `tests` / `tests-macos` `prepare` is `patch-package` and must **not** be Nx-cache-skipped ([MonoTool-AD-12](../../monorepo-tooling/architecture-decisions.md#monotool-ad-12--never-nx-cache-prepare-when-the-script-is-patch-package--accepted)). Without the tests Detox patch applied, an occupied neutral slot may cause stock Detox to create a suffixed device outside the slot contract. +3. **Verify** the React Native fmt podspec reports version **≥ 12.1.0** (Xcode 26 / Apple Clang 21-safe floor for this pin). **Yarn exit 0 alone is not sufficient** — always run the check below before native `:build` (a prepare cache-skip historically left fmt at **11.0.2** despite a green install): + +```bash +# Mobile toolchain (tests/) — required before ios/android :build +rg 'spec\.version|:tag' tests/node_modules/react-native/third-party-podspecs/fmt.podspec +# macOS app (tests-macos/) — required before macos :build (path may be workspace-local or hoisted) +rg 'spec\.version|:tag' tests-macos/node_modules/react-native/third-party-podspecs/fmt.podspec \ + || rg 'spec\.version|:tag' node_modules/react-native/third-party-podspecs/fmt.podspec +``` + +Expect `12.1.0` (or higher) on both `spec.version` and `:tag`. + +Before **slotted** iOS `:test-cover`, also confirm `tests/patches/detox+20.51.0.patch` landed (expect a match; missing means an occupied neutral base can trigger stock Detox clone creation / suffix escape instead of exact-base-or-fail — [iOS slot simulators](../e2e/slot-devices.md#ios-slot-simulators)): + +```bash +rg 'RN_E2E_SLOT_BASE_NAME' tests/node_modules/detox/src/devices/allocation/drivers/ios/SimulatorAllocDriver.js +``` + +4. If fmt is still **11.0.2** (or anything **< 12.1.0**): **STOP**. Re-run root `yarn` / fix patch application for **macOS** (including Nx `tests-macos:prepare` cache policy — [MonoTool-AD-12](../../monorepo-tooling/architecture-decisions.md#monotool-ad-12--never-nx-cache-prepare-when-the-script-is-patch-package--accepted)). On mobile 0.86+, fmt should already be ≥12.1.0 without a patch; if not, investigate the resolved `react-native` version. Do **not** invent Podfile `post_install` fmt hacks, `FMT_USE_CONSTEVAL` / `base.h` patches, c++17-for-fmt-only, or web-search workarounds. +5. **Before `yarn tests:ios:build` on a clean checkout:** run root `yarn` (which includes `yarn ruby:install`), then run **`yarn tests:ios:pod:install`** and wait for exit 0. Re-run the Pod install after `tests/ios/Podfile` / `Podfile.lock`, package podspec, or native dependency-resolution changes, and whenever `tests/ios/Pods` is absent. Root `yarn` does **not** create the CocoaPods xcconfig or file-list support files; the shared build invokes Detox/Xcode and does **not** provision them. CI installs the root bundle before yarn, then uses this same Pods-before-build order in `.github/workflows/tests_e2e_ios.yml`. + - **Expected lockfile drift:** `yarn tests:ios:pod:install` commonly rewrites the `hermes-engine` `SPEC CHECKSUMS` entry in `tests/ios/Podfile.lock` (the prebuilt Hermes podspec checksum varies by host/cache). Keep the regenerated lockfile while building and testing — reverting it mid-run fails the CocoaPods sandbox/manifest sync check. After the run, restore `tests/ios/Podfile.lock` and never stage it with unrelated changes. + +**Symptoms when violated:** Apple Clang 21 consteval errors compiling unpatched fmt **11.0.2**; missing `tests/ios/Pods` xcconfig or file-list support files; an occupied slotted iOS base causing stock Detox to create a suffixed simulator instead of failing (tests Detox patch-package skipped); agents inventing Podfile/fmt workarounds instead of re-running root `yarn` / fixing prepare cache policy. + +### fmt / Apple Clang 21 (unpatched React Native) + +- Unpatched RN **0.78** ships fmt **11.0.2**. On Xcode 26 / Apple Clang 21 that fails consteval builds. +- **Canonical fix (macOS 0.78):** root `yarn` applying `tests-macos/patches/react-native+0.78.3.patch` → fmt **12.1.0**. Mobile **0.86.2** already ships fmt **12.1.0**. See [install / patch / fmt gate](#install-patch-fmt-gate-blocking). +- **Trap:** yarn exit **0** does **not** prove a macOS patch landed. If Nx cache-skips `react-native-firebase-tests-macos:prepare` (`patch-package`), fmt stays at **11.0.2**. Durable policy: [MonoTool-AD-12](../../monorepo-tooling/architecture-decisions.md#monotool-ad-12--never-nx-cache-prepare-when-the-script-is-patch-package--accepted). **Always** run the fmt `rg` verification before native `:build`. +- **Never** invent Podfile `post_install` fmt hacks, `FMT_USE_CONSTEVAL`, `base.h` patches, or c++17-for-fmt-only as a substitute for a missed install/patch. diff --git a/okf-bundle/testing/commands/native.md b/okf-bundle/testing/commands/native.md new file mode 100644 index 0000000000..cb991a8d63 --- /dev/null +++ b/okf-bundle/testing/commands/native.md @@ -0,0 +1,75 @@ +--- +type: Reference +title: 'Agent commands: native lint, unit tests, codegen' +description: 'Allowlisted Android Java/Kotlin format, iOS Ruby lint and tests, Android JVM and iOS XCTest unit tests, TurboModule codegen, and their traps.' +tags: [testing, agents, commands, android, ios] +timestamp: 2026-12-02T00:00:00Z +--- + +# Agent commands: native lint, unit tests, codegen + +Part of [Agent command policy](../agent-command-policy.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Canonical registry + +Rows of the canonical registry that this file owns. Other rows: [registry index](../agent-command-policy.md#canonical-registry). + +| Intent | Command | Never use instead | +| --- | --- | --- | +| Android Java format / lint | `yarn lint:android` (Java only; not Kotlin) | `yarn google-java-format`, bare `google-java-format`, `google-java-format -i`, `npx google-java-format`, using this script on `.kt` | +| Android Kotlin format | repo-root `./gradlew ktlintFormat` with `-PinternalKtlintGitFilter=` (newline-separated repo-root-relative `packages/*/android/**/*.kt` and, if touched, `tests/android/**/*.kt`) | `ktlint` / `npx ktlint`; yarn format scripts; `cd tests/android && ./gradlew …`; other Gradle ktlint tasks; `-PrnfbKtlintGitFilter` on the **root** wrapper | +| iOS Ruby lint (RuboCop) | `yarn lint:ruby` (also runs inside `yarn tests:ios:ruby`) | ad-hoc `rubocop`, `bundle exec rubocop` without the Gemfile/config | +| Android JVM unit tests | `yarn tests:android:unit` | ad-hoc `./gradlew …` outside this yarn script; bare Robolectric/JUnit IDE-only as the agent gate | +| iOS XCTest unit tests (in-package) | `yarn tests:ios:unit` | ad-hoc `xcodebuild test`; CocoaPods `test_spec`; `tests/ios/testingTests` host UI tests | +| iOS Ruby unit tests (SPM / CocoaPods helpers) | `yarn lint:ruby` / `yarn tests:ios:ruby` (after root `yarn` or `yarn ruby:install` when gems are missing) | ad-hoc `ruby packages/app/__tests__/…_test.rb`, bare `ruby …/run_with_coverage.rb` without the yarn script as the agent gate | +| TurboModule codegen (all migrated / CI) | `yarn codegen:verify` (wipe + regen + diff); `yarn codegen:all` for local regen via package scripts | ad-hoc CLI without wipe; inventing alternate codegen yarn scripts — see [TurboModule codegen](#turbomodule-codegen) | + + + +### Android Java format + +- There is **no** `yarn google-java-format` script. Invented `google-java-format` / `npx google-java-format` invocations are forbidden. +- **Canonical:** `yarn lint:android` (repo root) — wraps `google-java-format --set-exit-if-changed --replace` on **Java** under `packages/*/android/src` and fails if the tree would change. Outside a git work tree (for example an rsync copy of the checkout) it skips the `git diff` step and relies on the formatter exit alone. It does **not** format Kotlin. +- **Needs JDK 21+:** the bundled `google-java-format` 1.35.0 jar runs on whatever `java` is first on `PATH` (not Gradle's JDK). On JDK < 21 it fails many files, untouched ones included, with `NoClassDefFoundError: com/sun/tools/javac/tree/JCTree$JCAnyPattern`. This is a host JDK problem, not a formatting failure. Put a JDK 21 first on `PATH` for the same command, e.g. `J21="$(/usr/libexec/java_home -v 21 -F)" && PATH="$J21/bin:$PATH" yarn lint:android` (macOS; stops if no JDK 21 is found. Without `-F`, `java_home` returns another installed JDK instead of failing; a Homebrew `/opt/homebrew/opt/openjdk@21/bin` works as the `PATH` entry instead). + + + +### Android Kotlin format + +- **Canonical:** repo-root `./gradlew ktlintFormat` (the root wrapper forwards into `tests/android`). Do **not** invent a yarn wrapper, a `ktlint` CLI, or `cd tests/android && ./gradlew …`. +- Pass `-PinternalKtlintGitFilter=` with newline-separated **repo-root-relative** paths (`packages//android/**/*.kt`; `tests/android/**/*.kt` when those files are in the diff). The root wrapper remaps that property; do not pass `-PrnfbKtlintGitFilter` to **root** `./gradlew`. Omit or empty filter → **no** `.kt` files formatted. +- Other Gradle tasks stay yarn-only (`tests:android:unit` / `:build` / Jacoco rows). `ktlintFormat` is the Gradle exception, not a license to invent Gradle. + +### Android build / unit / Jacoco + +- **Do not** invent `cd tests && yarn install`, then bare `./gradlew` from an arbitrary cwd. +- Unit: **`yarn tests:android:unit`** only. Runner choice and `@Config` / `sdk` policy: [AndroidTest-AD-1](../android-architecture-decisions.md#androidtest-ad-1). +- Merged coverage after e2e: **`yarn tests:android:post-e2e-coverage`** (Codecov path is `jacocoTestReport`, not e2e-only `jacocoAndroidTestReport`) — [coverage design](../coverage-design.md). +- Optional explicit merge: **`yarn tests:android:test:jacoco-report`**. + +### iOS XCTest (in-package) + +- **Canonical:** `yarn tests:ios:unit` — discovers `packages/*/ios/*UnitTests/*.xcodeproj`, macOS destination, writes `coverage/ios-unit/lcov.info` and **merges into** `coverage/ios-native/lcov.info` ([IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1); [coverage design](../coverage-design.md)). +- **Forbidden as the agent gate:** ad-hoc `xcodebuild test`, CocoaPods `test_spec`, `tests/ios/testingTests` host UI tests. + +### iOS Ruby (SPM helpers) + + + +- **Canonical:** `yarn tests:ios:ruby` — discovers all `packages/app/__tests__/*_test.rb`, SimpleCov → `coverage/ios-ruby/lcov.info`, Codecov flag `ios-ruby`. +- **CI home:** `tests_e2e_ios.yml` (debug + spm) only — not Jest / `tests_e2e_other.yml`. +- **Forbidden as the agent gate:** `ruby packages/app/__tests__/firebase_spm_test.rb` (or any single-suite / bare-ruby invocation). One-off debugging may use bare ruby locally; gate close / handoff evidence must cite the yarn target. +- First-time / Gemfile change: **`yarn ruby:install`** (or root `yarn`, which runs it via `postinstallDev`). Path via committed `.bundle/config`. When `bundle` is not on PATH, the `ruby` on PATH is older than 3.3.1, or `bundle --version` fails (macOS system Ruby 2.6 cannot load the lockfile's Bundler), `yarn ruby:install` **skips with exit 0** and prints one `ruby:install:` line naming why (no setup-ruby required in lint/Jest/Android CI). Host setup: [CONTRIBUTING § Ruby for iOS and macOS work](../../../CONTRIBUTING.md#ruby-for-ios-and-macos-work). CI uses `BUNDLE_FROZEN=true bundle install` **before** yarn in e2e/publish workflows; after yarn, `yarn ruby:install` is a no-op (`bundle check` succeeds). Do not `gem update cocoapods xcodeproj`. +- **Host Ruby floor:** `>= 3.3.1`. Ruby **3.3.0** cannot load lockfile `simplecov` **1.1.1** (`anonymous block parameter is also used within block`, CRuby [#20090](https://bugs.ruby-lang.org/issues/20090)). Do **not** downgrade simplecov to paper over it. With rbenv, pin a newer patch (e.g. `RBENV_VERSION=3.3.3`). +- Never `bundle install --gemfile=packages/app/__tests__/Gemfile`. That writes a gitignored vendor tree under `packages/app/__tests__/vendor/` and then `yarn lint:js` explodes. See [JS lint / Bundler vendor](core.md#js-lint-bundler-vendor). +- Blocking when Ruby sources or `*_test.rb` touched: [validation checklist § iOS Ruby](../validation/native-unit.md#ios-ruby-unit-tests). + +### TurboModule codegen + + + +- **`cd packages/ && yarn ios:codegen`** (or `yarn android:codegen`) often fails with **`unknown command 'codegen'`** after a clean `yarn` — `@react-native-community/cli` resolves from the **test app** workspace. +- Package scripts **wipe then regen** the configured `--outputPath` ([NewArch-AD-22](../../new-architecture/architecture-decisions.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)). Prefer those yarn scripts when CLI resolution works. +- **Canonical (mobile toolchain from `tests/`):** use each package's `yarn android:codegen` / `yarn ios:codegen` script, which delegates to [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs). The shared runner wipes the configured output path and invokes the pinned mobile CLI from `tests/`; do not run the CLI manually. RN 0.86 emits `ResultT` natively, so the former inject script is retired ([NewArch-AD-21](../../new-architecture/architecture-decisions.md#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete)). +- **CI / library packages:** `yarn codegen:verify`. Library vs test-app codegen (committed trees, `includesGeneratedCode`, git-diff guard, test-app dump gitignore): [NewArch-AD-5](../../new-architecture/architecture-decisions.md#newarch-ad-5--commit-generated-code--accepted). Test-app iOS CLI `--outputPath` is `ios` (project base); wipe is `ios/build/generated/ios` plus `tests/ios/Package.swift` and sibling app dumps. +- After **library** regen: commit the generated trees named in NewArch-AD-5, then `:build` + Metro reset-cache before `:test-cover`. diff --git a/okf-bundle/testing/coverage-design.md b/okf-bundle/testing/coverage-design.md index 20076bf141..df60dd38b7 100644 --- a/okf-bundle/testing/coverage-design.md +++ b/okf-bundle/testing/coverage-design.md @@ -3,532 +3,31 @@ type: Reference title: Coverage design description: Goals and implementation details for unit and e2e test coverage across platforms. tags: [testing, coverage, codecov, e2e, jest] -timestamp: 2026-10-01T00:00:00Z +timestamp: 2026-12-02T00:00:00Z --- -# Goals - -Coverage shows exercised **TS library sources** (`packages/*/lib/**`), **native sources** (`packages/*/{android,ios}/**`), and **iOS Ruby helpers** (`packages/app/**/*.rb`, exclude `__tests__`). - -| Layer | Proves | Consumers | -|-------|--------|-----------| -| **Unit (Jest)** | Package logic with mocks | Fast feedback on `lib/**` | -| **Unit (iOS Ruby)** | CocoaPods/SPM helper logic (`firebase_spm.rb`, etc.) via Minitest + SimpleCov | Fast feedback on `packages/app/**/*.rb`; LCOV `coverage/ios-ruby/lcov.info` | -| **Unit (Android JVM)** | Java state-machine / bridge logic — [AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1) | Fast feedback on `packages/*/android/**`; Jacoco `*.exec` | -| **Unit (iOS XCTest)** | Native logic on macOS: Foundation-only projects, or real `.m`/`.mm` files compiled against stub headers and test doubles for React/Firebase/UIKit — [IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1) | Fast feedback on `packages/*/ios/**`; LCOV merged into `coverage/ios-native/lcov.info` | -| **E2e (Jet / Detox)** | Real app behaviour against Firebase emulators and cloud APIs | TS + native bridge integration | - -Codecov merges CI uploads. Project-level % can be noise; **file-level changed-source coverage** is signal. macOS e2e uses firebase-js-sdk only; no RNFB native coverage. - -**Android native coverage** merges JVM unit (`*.exec`) and e2e (`*.ec`) into **`jacocoTestReport`** — that merged XML is what Codecov `android-native` uploads. Lines exercised only by allowlisted Android unit tests **count** toward the 100% touched-line bar below. - -**iOS native coverage** merges in-package XCTest LCOV (`coverage/ios-unit/lcov.info` from `yarn tests:ios:unit`) and e2e LLVM export into **`coverage/ios-native/lcov.info`**. Lines exercised only by allowlisted iOS unit tests **count** toward the 100% touched-line bar — [IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1). - -# Coverage expectations (policy) - -For **new code**: - -* **Coverage only goes up** on files the change touches. -* **100% on touched TS/native/Ruby helper sources is the requirement**, not an aspiration. "Mostly covered" does not close the gate. -* **Android JVM unit Jacoco (`*.exec`)** counts toward that bar when allowlisted tests under `packages/*/android/src/test/java` exercise the touched lines — scope and e2e non-substitution: [AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1); platforms where the module loads still need e2e ([platform coverage gate](running-e2e.md#platform-coverage-gate-blocking)). -* **iOS XCTest LCOV** counts toward that bar when allowlisted in-package tests (`yarn tests:ios:unit`) exercise touched `packages/*/ios/**` lines; unit LCOV **must merge** into `coverage/ios-native/lcov.info` — [IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1); [§ Unit coverage (iOS XCTest)](#ios-xctest-unit-lcov). -* **iOS Ruby SimpleCov** counts toward that bar for touched `packages/app/**/*.rb` (exclude `__tests__`) when exercised by `yarn tests:ios:ruby` — [§ iOS Ruby SimpleCov](#ios-ruby-simplecov). -* **The only acceptable uncovered line is covered by an [acceptable exception](change-authoring-workflow.md#acceptable-exceptions)** — an evidence-backed intractable limitation, quantified (e.g. "~NN% provably-unreachable Swift codegen"), or a user-accepted deferral with recorded rationale. -* **HandleMap TurboModule/Helper wiring** is a user-accepted exception to that 100% bar: lines that only delegate to a package Registry or `RNFBHandleMap` (`put` / `get` / `take` / `takeAll`) may stay uncovered. Do **not** extract a production `*Bridge` type solely so XCTest/JUnit can compile those TurboModule branches. Non-trivial lifecycle (replace = take then put, take-if-idle, take-then-abort / abort-all, unique-put collision abort) belongs on Registry or an existing holder — [IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1). -* **Every other gap is testable or dead code** — add the test (negative paths, failure branches, every reachable branch) or delete the unreachable/duplicate/superseded code. - -An uncovered line surfaced in `independent-review` is a review finding subject to [zero-deferral resolution](change-authoring-workflow.md#review-findings--resolve-do-not-defer): fix it (add the test or delete the code) or clear it against the bar. Gap passes **add tests and remove dead code** together. - -## Coverage as completion signal - -File-level coverage, not green tests/types alone, marks completion. - -1. **Baseline** after full e2e (all relevant platforms). -2. Implement with tests. -3. **After** full e2e with single-test/suite narrowing reverted (area narrowing may persist per package workflow until pre-merge). -4. Touched files: coverage **only rises** until **intractable limits** (above). - -**Plateau below that limit → refactor**, not ship: - -* Large uncovered native blocks often mean **dormant code paths** — use coverage to find the live path, delete the rest. -* Duplicate traversal (e.g. visiting the same tree property twice) can pass tests while leaving untestable structure — simplify until coverage rises. - -Do not hand off closable gaps. Package workflows may define snapshot tooling (e.g. [pipeline scripts](../packages/firestore/pipeline-implementation-workflow.md)). - - - -## Coverage evidence package - -**Blocking.** Required before **`review` gate** closes when the frozen diff touches `packages/*/lib/**`, native bridge sources (`packages/*/{android,ios}/**`), **or** iOS Ruby helpers (`packages/app/**/*.rb`). Jest green alone is insufficient. - -Produce after fresh e2e on every required platform (when native/lib touched), then post-process native artifacts ([§ stale coverage](#stale-coverage-data)); for Ruby-only diffs, fresh `yarn tests:ios:ruby` is enough: - -| Section | Contents | -|---------|----------| -| **Artifacts** | Timestamps for `coverage/ios-native/lcov.info`, `coverage/ios-ruby/lcov.info` (when Ruby touched), Android merged `jacocoTestReport.xml` (unit `*.exec` + e2e `*.ec`), and any Jest coverage run | -| **Touched regions** | Per-file or per-function line % for changed logic (not whole-package aggregates only) | -| **Branch map** | Table: branch / input shape → test or e2e that exercises it | -| **Gaps** | Every line or branch below 100%: **fix** (test or delete dead code), or **acceptable exception** with wire/runtime evidence in durable OKF (e.g. [pipeline platform parity](../packages/firestore/pipeline-platform-parity.md) probe row) | - -**Verdict line:** `100% on reachable touched lines` **or** `NOT 100%` with numbered gaps and disposition (fixed / intractable with evidence / user-accepted deferral). - -Record in `.agents/reports//coverage-evidence.md` (preferred) or work-queue notes. Orchestrators **must not** close `coverage_evidence_gate` or `review_gate` without this file when lib/native bridge is touched. - -Reviewers treat missing, stale, or NYC-only summaries as a **serious** finding ([change authoring § independent-review](change-authoring-workflow.md#independent-review)). - -### Subagent return fields (native / lib bridge touched) - -Blocking YAML (or equivalent table) before `coverage_evidence_gate` closes: - -```yaml -coverage_verdict: "100% on reachable touched lines" | "NOT 100%" -coverage_artifacts: - jacoco_xml: path # Android; use lcov path for iOS native - timestamp: ISO-8601 -touched_regions: - - file: packages/.../Foo.java - lines: "L10-L45" - line_pct: 100 -branch_map: - - branch: "onComplete when still registered" - test: "Functions.e2e.js — streaming cancel race" -gaps: [] # or numbered: disposition fixed | intractable+evidence | user-accepted deferral -``` - - - -### Anti-patterns (not coverage evidence) - -| Looks like coverage | Why it is not | -|---------------------|---------------| -| Jet NYC `text-summary` after narrowed `:test-cover` | Remapped TS aggregate for loaded modules — does not report Jacoco/lcov on native bridge lines | -| Whole-package or whole-harness statement % | Signal is **per changed file/region** in the frozen diff | -| Stale Jacoco XML / lcov without matching e2e run | Post-process deletes raw artifacts; re-run e2e first ([§ stale coverage](#stale-coverage-data)) | -| E2e pass counts alone | Proves behaviour, not line/branch coverage on touched native code | - -## Platform parity (pipeline and bridge code) - -For native-bridge features, **platform parity precedes coverage expansion**: iOS/Android/macOS behavior must match unless blocked by native SDK. RNFB bridge gaps are defects, not permanent `Platform.*` e2e branches. - -* **Policy and drift registry:** [Pipeline platform parity](../packages/firestore/pipeline-platform-parity.md) -* **Work queue:** [Pipeline coverage and parity work queue](../packages/firestore/pipeline-coverage-work-queue.md) - -## Reading per-file coverage locally - -After `tests::test-cover`: - -* **JS:** `yarn tests:jest --watchman=false --coverage --coverageReporters=text '--collectCoverageFrom=packages/{,}/lib/**/*.ts'` — paths before the glob ([validation checklist § focused coverage](validation-checklist.md#jest-collect-coverage-from-order)) -* **iOS Ruby:** `yarn tests:ios:ruby` → `coverage/ios-ruby/lcov.info` (`SF:` / `DA:` lines); HTML under `coverage/ios-ruby/` — [§ iOS Ruby SimpleCov](#ios-ruby-simplecov) -* **iOS native:** `yarn tests:ios:unit` → `coverage/ios-unit/lcov.info` (merged into `coverage/ios-native/lcov.info`). After e2e: `yarn tests:ios:test:process-coverage` → e2e LLVM export **then merge unit LCOV** → `coverage/ios-native/lcov.info` (`DA:` lines). **Deletes processed `.profraw`** — re-run e2e before re-processing. Non-zero exit from the trailing NYC JS report does not mean native LCOV is missing — [§ E2e iOS native](#e2e-ios-native-llvm). -* **Android native:** `yarn tests:android:unit` (produces module `*.exec`) then e2e + `yarn tests:android:post-e2e-coverage` → merged **`jacocoTestReport`** XML per `sourcefile`. **Deletes processed `emulator_coverage.ec`** after a successful report — re-run e2e before re-processing. Unit-only: `yarn tests:android:test:jacoco-report` (same merged task; needs fresh `*.exec` and any available `*.ec`). -* macOS e2e overwrites `coverage/lcov.info`; process iOS/Android native before a macOS run if you need both. - -**Baseline stability (repeatability):** after two full Law `:test-cover` (+ process) cycles, record metrics with `yarn tests:coverage:capture-baseline` → `tests/coverage-artifacts/coverage-baseline.json`. Dual-run variance and `--finalize` threshold live in `tests/coverage-artifacts/README.md` (not restated here). - - - -## iOS Ruby SimpleCov - -Minitest suites under `packages/app/__tests__/*_test.rb` cover production Ruby helpers (`packages/app/**/*.rb`, excluding `__tests__`). - -| Item | Value | -|------|-------| -| **Command** | `yarn tests:ios:ruby` (after `yarn ruby:install` or root `yarn`; CI uses `BUNDLE_FROZEN=true bundle install`) | -| **Runner** | `packages/app/__tests__/run_with_coverage.rb` — SimpleCov starts before any production `.rb` / suite load; glob-discovers all `*_test.rb`; each suite runs in an **isolated subprocess** (mock unit vs real cocoapods/xcodeproj cannot share a process); Coverage counters are peek-merged across production `load` resets | -| **LCOV** | `coverage/ios-ruby/lcov.info` (repo-relative `SF:…/packages/app/…`) | -| **HTML** | `coverage/ios-ruby/index.html` (optional local browse) | -| **Codecov flag** | `ios-ruby` — dedicated upload from `tests_e2e_ios.yml` debug+spm cell (same regime as `jest`: flag upload, **no** `flag_management` hard gate; local OKF review gate owns the touched-line bar) | -| **CI** | `tests_e2e_ios.yml` (debug + spm): `BUNDLE_FROZEN=true bundle install` → yarn → `yarn tests:ios:ruby` → Codecov `flags: ios-ruby`. Not run on Jest or `tests_e2e_other.yml` — iOS job guarantees clang/ar/file for embed suites | -| **Gems** | Committed root `Gemfile`/`Gemfile.lock` (+ `CHECKSUMS`); Dependabot `bundler` at `/` (cooldown in dependabot.yml — not Gemfile `cooldown:`, which needs Bundler 4+) | - -**Review gate:** when the frozen diff touches `packages/app/**/*.rb` or `packages/app/__tests__/*_test.rb`, `review_gate` **cannot close** without `yarn tests:ios:ruby` exit 0 and coverage evidence that touched production Ruby lines have test support ([validation checklist § iOS Ruby](validation-checklist.md#ios-ruby-unit-tests)). - -## Stale coverage data - -Native artifacts (`.profraw`, `.ec`, Jacoco XML) are trustworthy only with the fresh e2e run that produced them. Re-processing leftovers can create valid-looking stale reports. - -If numbers look wrong, run the clean cycle before debugging generators — e2e steps: [running e2e § Rules](running-e2e.md#rules) and [typical loop](running-e2e.md#typical-loop); then post-process below (this doc owns post-e2e coverage export only). Android merge needs fresh unit `*.exec` as well — [Local iteration](#local-iteration): - -```bash -yarn tests:ios:test:process-coverage -yarn tests:ios:unit # fresh coverage/ios-unit/lcov.info merged into ios-native -yarn tests:android:unit # fresh module *.exec when Android native touched -yarn tests:android:post-e2e-coverage -``` - -Post-process deletes raw iOS `.profraw` / Android `.ec`; missing raw file means "no fresh coverage." Do not use reuse variants for native deltas ([runbook](running-e2e.md)). - -# End-to-end overview - -```mermaid -flowchart LR - subgraph unit [Unit Jest] - J1[jest --coverage] --> J2[coverage/lcov.info] - end - subgraph ios_unit [Unit iOS XCTest] - U2[yarn tests:ios:unit] --> UNITLCOV["coverage/ios-unit/lcov.info"] - end - subgraph ts_e2e [E2e TypeScript] - M[Metro + inline source maps] --> A[App bundle] - A --> J[Jet --coverage] - J --> N[NYC remap] - N --> T2[coverage/lcov.info] - end - subgraph android_native [Android native Jacoco] - D1[Detox e2e] --> FLA["react-native-coverage.flush"] - FLA --> EC[coverage.ec in app filesDir] - EC --> P1[pull-native-coverage.js] - EXEC --> P1 - P1 --> JTR[jacocoTestReport] - JTR --> AX[jacocoTestReport.xml] - end - subgraph ios_native [iOS native LCOV] - D2[Detox e2e] --> FLI["react-native-coverage.flush"] - FLI --> PR[coverage.profraw in Documents] - PR --> P2[pull-native-coverage.js] - P2 --> LLVM[rn-coverage-ios-export.js] - UNITLCOV --> LLVM - LLVM --> I2[coverage/ios-native/lcov.info] - end - J2 --> C[Codecov] - T2 --> C - AX --> C - I2 --> C -``` - -# Unit coverage (Android JVM) - -```bash -yarn tests:android:unit -``` - -- Runner choice and `@Config` / `sdk` policy under `packages/*/android/src/test/java` — [AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1). -- Gradle entry: `tests/android` `./gradlew rnfbDebugUnitTests` (all RNFB library `:testDebugUnitTest` tasks). -- Output: Jacoco `*.exec` under each module `build/` (and app build tree as configured). -- **Counts toward** the 100% touched-line bar when allowlisted unit tests exercise those lines. -- Not a substitute for e2e on platforms where the module loads ([platform coverage gate](running-e2e.md#platform-coverage-gate-blocking)). - - - -# Unit coverage (iOS XCTest) - -```bash -yarn tests:ios:unit -``` - -- Host/macOS-first in-package xcodeproj — [IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1). -- Discovers `packages/*/ios/*UnitTests/*.xcodeproj`; LLVM export → `coverage/ios-unit/lcov.info`. -- Discovery finds one project per package that ships one. Stub-header projects ([IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1-stub-headers)) report hits on the real production files they compile. -- **Merges into** `coverage/ios-native/lcov.info` (create or max-hits merge per `SF:`/`DA:`). After e2e, `rn-coverage-ios-export.js` merges the same unit file so e2e export does not drop XCTest hits. -- **Counts toward** the 100% touched-line bar when allowlisted unit tests exercise those lines. -- Not a substitute for e2e on platforms where the module loads ([platform coverage gate](running-e2e.md#platform-coverage-gate-blocking)). - -# Unit coverage (Jest) - -```bash -yarn tests:jest-coverage -``` - -- Jest + `coverageProvider: "babel"` (Istanbul), **not** NYC. -- Scope: `packages/**/__tests__/**` (`jest.config.js`). -- Output: `coverage/lcov.info` at repo root. -- Instruments `packages/*/lib/**` directly — no source-map remap. - -# E2e TypeScript coverage (Jet + NYC) - -**Run e2e:** [running e2e § Rules](running-e2e.md#rules) — canonical `:test-cover` commands only; do not duplicate them here. - -| Platform | Entry (repo root) | Notes | -|----------|-------------------|-------| -| macOS | `tests:macos:test-cover` | See runbook | -| iOS | `tests:ios:test-cover` | See runbook | -| Android | `tests:android:test-cover` | See runbook | - -Jet self-wraps under NYC with `--coverage`. - -**Tooling:** - -- Metro bundles `packages/*/dist/module/**` with inline source maps (`tests/.babelrc` and `tests-macos/.babelrc`: `useInlineSourceMaps: true`). -- NYC (`tests/nyc.config.js` and `tests-macos/nyc.config.js`) remaps to `packages/*/lib/**` → **`coverage/lcov.info`** (`cwd: '..'`). -- Jet re-invokes under the test-app `nyc` (checks `NYC_CONFIG`) — `tests/` for iOS/Android, `tests-macos/` for macOS. Detox/macOS need no extra `nyc` prefix; start Jet only via [running e2e](running-e2e.md) packager commands. -- iOS/Android Jet-close also uses package `rn-coverage js pull`; their native post-processing - entrypoints run `rn-coverage js report` into `coverage/js//lcov.info`, using - `tests/nyc.config.js` for source-map remap. This supplements rather than replaces the RNFB - Jet/NYC transport and its `coverage/lcov.info` artifact. -- **Transfer:** patched test-runner/mocha-remote WS only (`coverage-ready` → `pull-coverage` → `coverage-data` → `coverage-ack`); HTTP POST `/coverage` deleted (`attachHttpServer` removed). Host launch/orchestrate control uses a **separate** HTTP server on **8091** (not the 8090 WS stack) — see [test-runner orchestration (log triage)](running-e2e.md#test-runner-host-orchestration-log-triage-only). Patches: `.yarn/patches/` (`jet`, `mocha-remote-client`, `mocha-remote-server`). See [iOS issues 6–6b](../ci-workflows/ios.md#6-jet-websocket-disconnect-1006--1001), [issue 8](../ci-workflows/ios.md#8-coverage-teardown-handshake-failure-tests-pass-nyc-00), [jet patch workflow](../ci-workflows/detox-patches.md#updating-the-jet-patch-headless). - -**NYC settings:** - -```javascript -include: ['packages/*/lib/**/*.{js,ts,tsx}', 'packages/*/dist/**/*.js'], -sourceMap: true, 'exclude-after-remap': true, instrument: false, -reporter: ['lcov', 'html', 'text-summary'], -``` - -**Verify:** `coverage-ready` → `WS received N file(s)` (N > 0) → non-zero NYC; `coverage/lcov.info` has `SF:packages/...`, not only `dist/`. If `merged 0 file(s)`, see [troubleshooting](#ts-e2e-coverage-troubleshooting). - -### TS e2e coverage troubleshooting - -| Symptom | Cause | Fix | -|---------|-------|-----| -| `[jet-coverage] merged 0 file(s)` | Stale Metro bundle or missing test-runner patch | `yarn install`; macOS: restart packager per [running e2e § Rules #1](running-e2e.md#rules) | -| macOS bundle still has `'/coverage'` fetch | Metro resolves Jet via `"react-native": "src/index"` — patch must touch `jet/src/index.tsx`, not only `lib/` | Re-run after patch; `--reset-cache` | -| iOS/Android merged 0, macOS OK | Prebuilt app bundle predates Istanbul fix | Re-run [running e2e § Rules](running-e2e.md#rules) (`:build` then `:test-cover`) | -| Metro 500 on bundle | Missing babel plugins in `tests/` | `yarn install`; confirm `tests/node_modules/babel-plugin-istanbul` exists | - -# Android native (Jacoco — unit + e2e merged) - -1. Package `rn-coverage.gradle` on RNFB modules (applied from `tests/android/build.gradle`): `enableAndroidTestCoverage = true` (e2e `*.ec`); `enableUnitTestCoverage = false` (parity with package helper — AGP library unit probes are empty; JVM unit `*.exec` comes from the separate unit path). -2. **JVM unit:** `yarn tests:android:unit` before or independent of Detox — produces module `*.exec`. -3. Jet `after` in `tests/app.js` → `react-native-coverage.flush()` in **app** process → `coverage.ec` in `filesDir` **before** Detox SIGINT. -4. After Detox: `yarn tests:android:post-e2e-coverage` (or `pull-native-coverage --android-post-e2e`) → `emulator_coverage.ec` → **`jacocoTestReport`** (merged unit `*.exec` + e2e `*.ec`) → **delete local `.ec`** → **presence assert** (invertase package LINE hits must be non-empty; exit **2** when strict). Missing `.ec` in strict mode (default): **exit 2** — silent empty e2e coverage must fail CI. Soft local: `--no-strict` / `RNFB_COVERAGE_STRICT=0`. Codecov upload may still use `continue-on-error`; the post-e2e yarn step itself is the blocking guard. -5. XML uploaded to Codecov: `tests/android/app/build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml` - -**Why app-process flush:** Detox SIGINT kills instrumentation after Jet; post-`Detox.runTests()` dump in `DetoxTest.java` never runs. - -**Jacoco notes:** - -- AGP 8 classes: `build/intermediates/javac/debug/compileDebugJavaWithJavac/classes` -- Sources: include `src/reactnative/java` -- Modules: `rootProject.ext.firebaseModulePaths` (`tests/android/build.gradle`) -- Tasks in `tests/android/app/jacoco.gradle`: - - **`jacocoTestReport`** — merged unit + e2e (`**/*.exec` + `**/*.ec`); **CI / Codecov `android-native` uses this** - - `jacocoUnitTestReport` — unit only (`**/*.exec`) - - `jacocoAndroidTestReport` — e2e only (`**/*.ec`); local diagnostic, **not** the Codecov upload path -- Yarn: `tests:android:post-e2e-coverage` and `tests:android:test:jacoco-report` both drive `jacocoTestReport` - - - -# E2e iOS native (LLVM) - -1. **Build:** LLVM flags in **`tests/ios/Podfile` `post_install`** (`pod install` after checkout): - - **`testing` target:** compile + link profile flags + Swift toolchain search paths (Firebase static pods on CI) - - **`RNFB*` pods:** compile-only flags — **no** `-fprofile-instr-generate` on pod `OTHER_LDFLAGS` (breaks `swiftCompatibility56` on CI) - - **Coverage pod:** `ReactNativeCoverage.apply_post_install!` (writes `CoverageConfig.h` with `RNFB` prefixes) -2. **Runtime:** `react-native-coverage` constructor + TurboModule flush → `Documents/coverage-%m.profraw` (`LLVM_PROFILE_FILE`). Jet `after` → `flush()` (tracked RNFB frameworks, then app). **No custom URL scheme** (iOS "Open in 'testing'?" dialog blocks Detox). -3. **Pull:** Jet exit 0 → `pull-native-coverage.js` → `simulator_coverage.profraw`. **Fails if missing.** Pull on Jet `close`, not `afterAll` (before Detox teardown). -4. **Export:** `yarn tests:ios:test:process-coverage` / `rn-coverage-ios-export.js`: - - delegates to `rn-coverage ios export` (llvm-cov + `SF:` rewrite + presence assert) - - **merge** `coverage/ios-unit/lcov.info` when present (`tests/scripts/ios-native-lcov.js`) so XCTest counts for 100% - - **delete processed `.profraw`** (package CLI; missing file next run = no fresh coverage) - - then `reportJsCoverage('ios')` (NYC JS report in `pull-native-coverage.js`) - -**Gotcha:** native LCOV (`coverage/ios-native/lcov.info`) is written and merged **before** the trailing NYC JS report. That report can exit non-zero (e.g. NYC `concurrency` got `0`), so the node process exits 1 even though the native file is already usable. Read `coverage/ios-native/lcov.info`; do not treat the process exit as "no native coverage." - -ObjC + Swift share this. Raw export is mostly Pods/SDK; healthy full run includes ~50–60 `packages/*/ios/**` files among ~2000 entries. - -### Accepted Clang line-counter gaps - -**2026-09-29:** In `packages/app/ios/RNFBApp/RNFBAppModule.mm` `initializeApp`, a format-stable single-line `[self completeInitializeApp:…]` call (clang-format off/on) still leaves LCOV `DA:212,0` on that call and `DA:214,0` on the `});` closing `RCTUnsafeExecuteOnMainQueueSync`, while `initializeApp` / block invoke / the preceding line / method `}` and `completeInitializeApp:` body all hit. User-accepted [intractable limitation](change-authoring-workflow.md#acceptable-exceptions); do not reshape the call to chase those two counters. - -### SPM + dynamic frameworks - -**Tests Podfile default (dynamic):** RNFB pods stay separate `RNFB*.framework` images. Compile-only instrumentation is not enough — those frameworks must **link** the profile runtime (`link_profile: true` for `RNFB*` when `linkage == dynamic`, including `-Wl,-u,___llvm_profile_set_filename` so set_filename is not dead-stripped), flush must dump **each** loaded RNFB image, and `rn-coverage ios export` must pass every `RNFB*.framework` binary as an extra `llvm-cov -object` (`ios.frameworkNamePrefixes: ['RNFB']`). App-only export → **`packagesHits=0`**. - -**Why per-image flush (not atexit alone):** each dynamic image links its own `clang_rt.profile` copy; `__llvm_profile_write_file` in the app only dumps the app image. `LLVM_PROFILE_FILE=…/coverage-%m.profraw` (set via `setenv` in the package constructor) makes atexit dumps unique per image, but Jet pulls `Documents/*.profraw` on Jet **close** — before `terminateApp` — so atexit has not run yet. Detox SIGKILL can also skip atexit. `react-native-coverage` therefore discovers `RNFB*.framework` images at load via `_dyld_register_func_for_add_image`, resolves each image's local `___llvm_profile_write_file` through `__LINKEDIT`, flushes tracked images on Jet `after`, then writes the app image last (so flush-path counters land in the pulled app profraw). Static linkage still merges RNFB into the app binary (compile-only + app flush). Never put profile **link** flags on third-party/Firebase pods (`swiftCompatibility56`). - -# Codecov uploads (CI) - -[codecov-action](https://github.com/codecov/codecov-action) v7, explicit `files` + `flags`. Upload steps continue on error; **blocking** = `codecov.yml` status checks. - -## Flags - -Names must match in **`codecov.yml`** and workflow `flags:`. - -| Flag | Workflow | File | Blocks PR? | -|------|----------|------|------------| -| `jest` | `tests_jest.yml` | `coverage/lcov.info` | No | -| `ios-ruby` | `tests_e2e_ios.yml` (debug + spm) | `coverage/ios-ruby/lcov.info` | No (upload like `jest`; OKF review gate owns touched Ruby lines) | -| `e2e-ts-ios` | `tests_e2e_ios.yml` (debug) | `coverage/lcov.info` | No | -| `ios-native` | `tests_e2e_ios.yml` (debug) | `coverage/ios-native/lcov.info` | **Yes** | -| `e2e-ts-android` | `tests_e2e_android.yml` | `coverage/lcov.info` | No | -| `android-native` | `tests_e2e_android.yml` | `tests/android/app/build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml` | **Yes** | -| `e2e-ts-macos` | `tests_e2e_other.yml` | `coverage/lcov.info` | No | - -iOS release legs: no upload. macOS: TS only. - -## Native gates - -`carryforward: false`, `target: 1%` — gates **upload presence**, not % regression. Missing upload → 0% → fail. `codecov/project` overall: `informational: true`. - -## CI steps before upload - -| Workflow | Steps | -|----------|-------| -| `tests_jest.yml` | `yarn tests:jest-coverage` → Codecov `jest` | -| `tests_e2e_ios.yml` (debug) | `yarn tests:ios:unit` → Detox → `yarn tests:ios:test:process-coverage` (e2e LCOV + merge unit + presence assert; **no** `continue-on-error`; fails the job when Detox succeeded but coverage exited non-zero — same policy as Android); **debug+spm:** `yarn tests:ios:ruby` → Codecov `ios-ruby` | -| `tests_e2e_android.yml` | `yarn tests:android:build` → `yarn tests:android:unit` → Detox → `yarn tests:android:post-e2e-coverage` (merged `jacocoTestReport` + presence assert; CI script fails the job when tests passed but coverage exited non-zero) | -| `tests_e2e_other.yml` | macOS Jet e2e | - -**Paths:** JS `coverage/lcov.info`; iOS Ruby `coverage/ios-ruby/lcov.info`; iOS native `coverage/ios-native/lcov.info`; Android merged native `tests/android/app/build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml`. Uploads tab: **Processed** = good; **Unusable** = fix format/paths. - -# Local iteration - -E2e per [runbook](running-e2e.md), Android JVM unit + native post-processing: - -```bash -yarn tests:android:unit -yarn tests:ios:unit -yarn tests:ios:test:process-coverage -yarn tests:android:post-e2e-coverage # pulls .ec then jacocoTestReport (merged) -# optional explicit merge report without pull: -yarn tests:android:test:jacoco-report -``` - -Optional Codecov CLI: - -```bash -.codecov-venv/bin/codecovcli upload-process \ - -t "$CODECOV_TOKEN" -r invertase/react-native-firebase \ - --git-service github -C "$(git rev-parse HEAD)" -B "$(git branch --show-current)" \ - -f coverage/ios-native/lcov.info -n local-ios-native --disable-search -``` - -No `:test-cover-reuse` / `:test-reuse` — stale native risk ([runbook](running-e2e.md)). - - - -# Test-app native modules vs coverage flush - -Do **not** conflate coverage flush with e2e probes. - -| Module | Kind | Role | -|--------|------|------| -| **`Coverage` (`react-native-coverage`)** | Package TurboModule | Flush only — [§ react-native-coverage](#react-native-coverage). | -| **`NativeRNFBTesting`** | Test-app TurboModule | E2e probes — [running e2e § test-app native modules](running-e2e.md#test-app-native-modules). | -| **`RNFBTestingMessaging`** | Test-app `RCTBridgeModule` | iOS messaging delegate probe — [running e2e § test-app native modules](running-e2e.md#test-app-native-modules). | - -Probe method names, product-line hits, and evidence recording: [running e2e § test-app native modules](running-e2e.md#test-app-native-modules) → [coverage evidence package](#coverage-evidence-package). - -# Config-driven native coverage (Pattern C) - -Native coverage knobs for the dedicated test app live in `tests/react-native-coverage.config.js` -(package-aligned shape). Node scripts load that file; Gradle copies are generated via -`yarn tests:coverage:generate-native-config` (`tests/android/coverage.properties`). LLVM -profile path and TurboModule flush come from **`react-native-coverage`**. Jacoco merge -(unit `*.exec` + e2e `*.ec`, `src/reactnative/java`) stays in `tests/android/app/jacoco.gradle`. - - - -# react-native-coverage (tests app only) - -Pattern C: only the **tests** workspace depends on published `react-native-coverage`: - -```json -"react-native-coverage": "0.2.0" -``` - -in `tests/package.json`. Host yarn scripts call package `rn-coverage` (`tests/scripts/rn-coverage-*.js`, -`pull-native-coverage.js`). Runtime flush uses the package TurboModule (`Coverage` / `flush()`). -Test-app probe modules (`NativeRNFBTesting`, `RNFBTestingMessaging`) are **not** flush — [running e2e § test-app native modules](running-e2e.md#test-app-native-modules). -Rollback if the cutover regresses: [§ coverage migration rollback](#coverage-migration-rollback). - - - -# Coverage migration rollback - -Playbook to leave published `react-native-coverage@0.2.0` and restore a known-good in-tree flush path when the cutover regresses. Prefer **git revert / checkout from the parent of the adopt cutover** over hand-edited file lists — patches rot. - -## What “migrated” means - -| Area | Migrated state | -|------|----------------| -| **Dependency** | `tests/package.json` pins published `react-native-coverage@0.2.0` (Pattern C — tests app only) | -| **Build helpers** | Package Gradle (`rn-coverage.gradle`) + CocoaPods (`ReactNativeCoverage.apply_post_install!`) wire instrumentation | -| **Flush sources** | In-tree `RNFBTestingCoverage*` (Android module/package, iOS module/profile/config) **deleted**; runtime is package `Coverage` / `flush()` | -| **Host wrappers** | Thin RNFB scripts remain (`pull-native-coverage.js`, `rn-coverage-*.js`, Jacoco merge in `tests/android/app/jacoco.gradle`) | -| **Probes** | Messaging / non-FCM probes stay on `NativeRNFBTesting` + `RNFBTestingMessaging` — not flush — [running e2e § test-app native modules](running-e2e.md#test-app-native-modules) | - -## When to rollback - -Treat as cutover regression only after a clean post-process cycle fails ([§ stale coverage](#stale-coverage-data)). Typical signals (details in [§ Troubleshooting](#troubleshooting) and [SPM + dynamic frameworks](#spm--dynamic-frameworks)): - -- Codecov `ios-native` / `android-native` uploads empty or **Unusable** -- Presence assert exit **2** (`yarn tests:coverage:assert-presence` / post-e2e / iOS process-coverage) -- iOS export `packagesHits=0` after dynamic multi-image flush -- Android empty Jacoco XML / missing `.ec` despite green Detox - -Do **not** rollback for TS-only Jet/NYC gaps — [§ TS e2e coverage troubleshooting](#ts-e2e-coverage-troubleshooting). - -## Rollback steps (high level) - -1. **Identify the cutover boundary** in git history: the commit that deletes in-tree `RNFBTestingCoverage*` and pins published `react-native-coverage@0.2.0` in `tests/package.json` (and any immediately preceding portal/link commit that only rewires the same dep). The parent of that adopt cutover is the known-good in-tree flush baseline for restore. -2. **Prefer `git revert`** of the adopt cutover (and the portal/link commit if the revert does not restore a buildable tree) on a dedicated branch. If revert conflicts, **`git checkout --`** the native flush sources and wiring paths the cutover removed/changed (in-tree `RNFBTestingCoverage*`, Podfile / Gradle / `AppDelegate` / `MainApplication` registration, related `tests/package.json` dep and lockfile hunks) — do not invent a new flusher. -3. **Pin or remove** the published package version so Yarn no longer resolves `react-native-coverage@0.2.0` as the flush owner (revert the dep hunk, or leave the package unused only if the restored tree no longer imports it). -4. **Reinstall and rebuild:** root `yarn` → (iOS only) `yarn tests:ios:pod:install` → `yarn tests::build` → `:test-cover` → native post-process ([Local iteration](#local-iteration); e2e commands: [running e2e](running-e2e.md)). -5. **Re-run presence assert** (`yarn tests:coverage:assert-presence` or the platform post-process that invokes it) — must not exit **2**. - -## What not to rollback - -Keep these even when restoring in-tree flush — they are independent of the published package: - -| Keep | Why | -|------|-----| -| Baseline harness (`tests/coverage-artifacts/`, `yarn tests:coverage:capture-baseline`) | Repeatability metrics, not flush ownership | -| Empty-pipeline / presence guards (exit **2** on silent-empty) | CI safety for any flush implementation | -| Config-driven plumbing (`tests/react-native-coverage.config.js`, `yarn tests:coverage:generate-native-config`, `coverage.properties`) | Knobs stay useful with either flusher | -| Probe split (`NativeRNFBTesting` / `RNFBTestingMessaging`) | Product e2e probes, not coverage flush | -| RNFB Jacoco merge (`tests/android/app/jacoco.gradle`) and iOS unit→native LCOV merge | Host-owned Codecov paths | - -## Post-rollback verification - -After fresh e2e + post-process, these Codecov paths must be **non-empty** again (flags in [§ Codecov uploads](#codecov-uploads-ci)): - -| Flag | Path | -|------|------| -| `ios-native` | `coverage/ios-native/lcov.info` (includes `packages/*/ios/**` hits; not `packagesHits=0`) | -| `android-native` | `tests/android/app/build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml` (merged unit+e2e; not empty / e2e-only) | - -Optional: TS e2e `coverage/lcov.info` for `e2e-ts-*` is unchanged by native flush ownership. Uploads tab: **Processed**, not **Unusable**. - -# Critical invariants - -| Invariant | Enforced | -|-----------|----------| -| LLVM profile flags (iOS) | `Podfile` `post_install` + `ReactNativeCoverage.apply_post_install!` | -| Profile path at launch (iOS) | `react-native-coverage` constructor (`CoverageConfigureProfilePath`) | -| Jacoco instrumentation (Android) | package `rn-coverage.gradle` (`enableAndroidTestCoverage = true`, `enableUnitTestCoverage = false`) | -| Module name | `Coverage` / `react-native-coverage.flush()` | -| Flush after Mocha | Jet `after` in `tests/app.js` | -| Profraw pull before Detox teardown (iOS) | `pull-native-coverage.js` on Jet `close` in `firebase.test.js` | -| Android JVM unit before / with merge | `yarn tests:android:unit` → module `*.exec` | -| iOS XCTest unit merged into ios-native | `yarn tests:ios:unit` → `coverage/ios-unit/lcov.info` merged into `coverage/ios-native/lcov.info` | -| Android ec pull after Detox | `yarn tests:android:post-e2e-coverage` → **`jacocoTestReport`** (not e2e-only `jacocoAndroidTestReport`) | -| Codecov android-native file | `jacocoTestReport/jacocoTestReport.xml` | -| Fresh profraw processed (iOS) | `rn-coverage-ios-export.js` (package CLI) deletes after export | -| Fresh ec processed (Android) | `pull-native-coverage.js` deletes local `.ec` after successful Jacoco report | -| JVM unit ≠ e2e substitute | [AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1); [platform coverage gate](running-e2e.md#platform-coverage-gate-blocking) still applies | -| iOS XCTest ≠ e2e substitute | [IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1); unit LCOV still merges into ios-native | - -# Troubleshooting - -| Symptom | Cause | Fix | -|---------|-------|-----| -| "Open in 'testing'?" dialog | Custom URL scheme | Native module flush only | -| No profraw; test passes | Pull in `afterAll` after cleanup, wrong module name | Pull on Jet `close`; verify export name | -| Stale profraw uploaded | Re-process without re-e2e | Process deletes profraw; exit 1 if missing next time | -| Stale Android Jacoco / collapsed native % | Re-run `post-e2e-coverage` without fresh e2e (and/or without fresh unit `*.exec`) | Post-e2e deletes `.ec` after report; run `:build` → `tests:android:unit` → `:test-cover` → `:post-e2e-coverage` | -| Coverage numbers suspect (any platform) | Leftover raw artifacts or reuse shortcuts | Full clean cycle per platform; see [Stale coverage data](#stale-coverage-data) | -| No `packages/` hits in iOS export | Dynamic/SPM multi-image path incomplete | [SPM + dynamic frameworks](#spm--dynamic-frameworks); rebuild `tests:ios:build` → `:test-cover`; syslog `tracked profile image` / `flush tracked image` | -| Empty Jacoco XML (~235 B) | AGP 8 path, missing `src/reactnative/java`, no ec/exec | Check post-e2e logs; confirm `jacocoTestReport` not e2e-only task | -| Uploaded e2e-only Jacoco | Wrong report task / path | Codecov must use `jacocoTestReport.xml`, not `jacocoAndroidTestReport.xml` | -| Android ec missing after pass | SIGINT before flush | `[native-coverage] flushing android coverage` in log; `MainApplication` registration | -| Jet after: coverage not enabled | Release / non-instrumented build | Use `:test-cover` debug builds | -| `swiftCompatibility56` undefined | Profile link flags on all Pods | App target only for `OTHER_LDFLAGS` | -| No `[jet-coverage] WS received` | Patches missing | `yarn install`; `.yarn/patches/` | -| WS closed on `reconnect_recovered` | Handshake on dead socket | Client retry + server pull; `JET_COVERAGE_TEARDOWN_RE` — [iOS issue 8](../ci-workflows/ios.md#8-coverage-teardown-handshake-failure-tests-pass-nyc-00) | -| Empty NYC / lcov | Environment or patch issue during `:test-cover` | Re-run per [running e2e](running-e2e.md) — do not invoke the test runner directly | -| `tests:ios:test:process-coverage` exits 1; NYC `concurrency` got `0` | Trailing NYC JS report failed after native LCOV write | Read `coverage/ios-native/lcov.info` — still the artifact; exit ≠ missing native coverage ([§ E2e iOS native](#e2e-ios-native-llvm)) | -| Codecov missing iOS native | Wrong path/name | `coverage/ios-native/lcov.info` | -| Upload **Unusable** | Bad `SF:` paths | package `sourcePathRewrite` + `ios-native-lcov.js` | -| `ios-native` / `android-native` fail | Upload missing → 0% | Uploads tab; process/post-e2e steps | - -# Future cleanups - -- Host `rn-coverage-ios-export.js` still merges XCTest `coverage/ios-unit/lcov.info` after - package `ios export` — keep that until the package grows a unit-merge flag. -- `tests/android/app/jacoco.gradle` stays RNFB-specific (firebase module paths, - `src/reactnative/java`). Do not replace it with the package Jacoco helper. +# Coverage design + +## Files + +Content moved from this file into the files below. Headings and anchors keep their names in the new file; each old anchor sits on the line under its new home, so old `#links` still land here and point on. + +- [Coverage: goals and expectations (policy)](code-coverage/policy.md): Coverage goals, expectations, completion signal, coverage evidence package, anti-patterns, and platform parity. + +- [Coverage: reading coverage locally](code-coverage/local.md): Reading per-file coverage, iOS Ruby SimpleCov, stale coverage data, and the local iteration loop. + +- [Coverage: unit and TS e2e pipelines](code-coverage/pipelines.md): End-to-end coverage overview, unit coverage per platform, and Jet + NYC TypeScript e2e coverage. + +- [Coverage: native e2e (Jacoco and LLVM)](code-coverage/native.md): Android Jacoco unit + e2e merge and iOS LLVM native e2e coverage. + +- [Coverage: Codecov uploads (CI)](code-coverage/codecov-ci.md): Codecov flags, native gates, and CI steps before upload. + +- [Coverage: test-app native modules and react-native-coverage](code-coverage/test-app-modules.md): Test-app native modules vs coverage flush, config-driven native coverage, and react-native-coverage. + +- [Coverage: migration rollback](code-coverage/migration-rollback.md): What migrated means, when and how to roll back the coverage migration, and post-rollback verification. + +- [Coverage: invariants and troubleshooting](code-coverage/invariants-and-troubleshooting.md): Critical coverage invariants, troubleshooting table, and future cleanups. + # Citations diff --git a/okf-bundle/testing/e2e-parallel-design.md b/okf-bundle/testing/e2e-parallel-design.md index ebae27d9e2..10fd2584df 100644 --- a/okf-bundle/testing/e2e-parallel-design.md +++ b/okf-bundle/testing/e2e-parallel-design.md @@ -8,7 +8,7 @@ timestamp: 2026-08-20T00:00:00Z # E2e parallel execution and host coordination -Architecture and lifecycle for running Android, iOS, and macOS e2e in parallel (within a worktree and across worktrees). **Commands** live in [running e2e](running-e2e.md) ([slot lifecycle](running-e2e.md#slot-lifecycle), [parallel topology](running-e2e.md#parallel-e2e-topology), [infrastructure change bar](running-e2e.md#e2e-infrastructure-change-bar)); this doc explains *why* resources collide, how parameterization isolates them, and how Mellifera / Tart relate. +Architecture and lifecycle for running Android, iOS, and macOS e2e in parallel (within a worktree and across worktrees). **Commands** live in [running e2e](running-e2e.md) ([slot lifecycle](e2e/environment.md#slot-lifecycle), [parallel topology](e2e/environment.md#parallel-e2e-topology), [infrastructure change bar](e2e/rules.md#e2e-infrastructure-change-bar)); this doc explains *why* resources collide, how parameterization isolates them, and how Mellifera / Tart relate. **Policy:** [OKF documentation and commit policy](../documentation-policy.md) — public vs ephemeral vs private; [Efficiency](../documentation-policy.md#efficiency). **Coverage:** [coverage design](coverage-design.md). @@ -28,10 +28,10 @@ After the `tests-macos/` split, **iOS/Android** Metro (`yarn tests:packager:*`, | **Firebase emulator suite** | auth / database / firestore / functions / storage / hub / logging | `:9099` / `:9000` / `:8080` / `:5001` / `:9199` / `:4400` / `:4500` | | **Emulator aux ports** | Firestore websocket, Eventarc, Cloud Tasks (Firebase Tools still binds these) | `:9150` / `:9299` / `:9499` (collide if two suites share a host) | | **Android** | AVD + adb serial | Serial: `TestingAVD` / `emulator-5554` (yarn tests:* pin `RNFB_ANDROID_CONSOLE_PORT=5554`). Slotted: `TestingAVD-{n}` (incl. `-0`) + console `5556+2n` (`emulator-5556/5558/5560`, …). Detox must not pick FreePortFinder **10000–20000**; check/release treat those leftover serials as BUSY / kill | -| **iOS** | Simulator device name | Serial: `iPhone 17` (stock Detox). Slotted: exact `RN E2E iOS slot-{n}` base; patched Detox reuses it or fails when registry-taken ([running e2e § iOS slot simulators](running-e2e.md#ios-slot-simulators); [slot index](running-e2e.md#e2e-slot-index)) | +| **iOS** | Simulator device name | Serial: `iPhone 17` (stock Detox). Slotted: exact `RN E2E iOS slot-{n}` base; patched Detox reuses it or fails when registry-taken ([running e2e § iOS slot simulators](e2e/slot-devices.md#ios-slot-simulators); [slot index](e2e/environment.md#e2e-slot-index)) | | **macOS** | Process / `PRODUCT_NAME` (+ derived bundle id) | `io.invertase.testing` | -| **Coverage paths** | NYC / coverage — `tests/` (iOS/Android) and `tests-macos/` (macOS); see [coverage design § e2e TS](coverage-design.md#e2e-typescript-coverage-jet--nyc) | Fixed per worktree (same-platform parallel overwrites) | -| **CocoaPods CDN cache** | Trunk spec CDN under `~/.cocoapods` | **Not** parameterized. Overlapping `yarn tests:ios:pod:install` can miss trunk specs (`SocketRocket (~> 0.7.1)`) while siblings succeed. Serialize Apple `pod:install` before overlapping `:build`/`:test-cover` ([running e2e § slot lifecycle](running-e2e.md#slot-lifecycle)). `:build` does not run pod install. | +| **Coverage paths** | NYC / coverage — `tests/` (iOS/Android) and `tests-macos/` (macOS); see [coverage design § e2e TS](code-coverage/pipelines.md#e2e-typescript-coverage-jet--nyc) | Fixed per worktree (same-platform parallel overwrites) | +| **CocoaPods CDN cache** | Trunk spec CDN under `~/.cocoapods` | **Not** parameterized. Overlapping `yarn tests:ios:pod:install` can miss trunk specs (`SocketRocket (~> 0.7.1)`) while siblings succeed. Serialize Apple `pod:install` before overlapping `:build`/`:test-cover` ([running e2e § slot lifecycle](e2e/environment.md#slot-lifecycle)). `:build` does not run pod install. | One worktree also has **one** `tests-macos/macos/build` (and iOS/Android build product tree) — not safe for two same-platform `:test-cover`s in that tree. @@ -42,7 +42,7 @@ One worktree also has **one** `tests-macos/macos/build` (and iOS/Android build p - **Shared emulator DB** — Firestore `wipe()` and auth/storage state are global per emulator process. - **One derived-data / build tree per worktree** — two same-platform runs race native products and coverage files. - **One CocoaPods CDN cache per host** — overlapping Apple `pod:install` races trunk spec downloads; serialize `yarn tests:ios:pod:install` / `yarn tests:macos:pod:install` across worktrees. Do not disable Swift explicit modules to paper over that. -- **OKF serial default** still assumes the table above ([running e2e § Rules #6](running-e2e.md#rules)): correct for gate closure, slow for iteration (~15m macOS + ~45–60m iOS + ~45–60m Android wall-clock if run one after another). +- **OKF serial default** still assumes the table above ([running e2e § Rules #6](e2e/rules.md#rules)): correct for gate closure, slow for iteration (~15m macOS + ~45–60m iOS + ~45–60m Android wall-clock if run one after another). ### 3. How parameterization fixes it @@ -52,7 +52,7 @@ One worktree also has **one** `tests-macos/macos/build` (and iOS/Android build p - **Worktree topology:** at most **`1× android ∥ 1× ios ∥ 1× macos`** per worktree (same slot index, three port blocks). Same-platform scale-out = more worktrees (`macos-slot-N` + `io.invertase.testing.sN`, not a host-global `macos-global` lock). - **macOS build:** `yarn tests:macos:build` uses `RNFB_MACOS_PRODUCT_NAME_SUFFIX` in the pbxproj — never pass global `PRODUCT_NAME=` on the `xcodebuild` CLI. -Commands for clear → start → build → test → free: [running e2e § slot lifecycle](running-e2e.md#slot-lifecycle). +Commands for clear → start → build → test → free: [running e2e § slot lifecycle](e2e/environment.md#slot-lifecycle). ## Goals @@ -67,11 +67,11 @@ Commands for clear → start → build → test → free: [running e2e § slot l | Capability | Status | Canonical | |------------|--------|-----------| -| Per-platform prefixed ports + full carry-in | **Shipped** | [running e2e § configurable env](running-e2e.md#configurable-e2e-environment) | -| Worktree topology (`1× android ∥ 1× ios ∥ 1× macos` per tree) | **Shipped** | [parallel topology](running-e2e.md#parallel-e2e-topology) | -| Slot env + serial `yarn tests:*` | **Shipped** — `export-slot-env` then the same commands as [running e2e § Rules](running-e2e.md#rules) | [slot lifecycle](running-e2e.md#slot-lifecycle) | -| Concurrent macOS via `PRODUCT_NAME` | **Shipped** (e.g. `io.invertase.testing.s0`…`sN`) | [macOS process identity](running-e2e.md#macos-process-identity-concurrency) | -| Host check/release (`yarn tests:e2e:check` / `release`) | **Shipped** — serial default; slot via env; release frees only what the run recorded and fails fast on other owners; `--all-slots` is a manual machine wipe; Mellifera maps reservations to `RNFB_*` then calls these yarn targets (no JSON feed) | [host-clear probes](running-e2e.md#host-clear-probes), [run record](running-e2e.md#run-record) | +| Per-platform prefixed ports + full carry-in | **Shipped** | [running e2e § configurable env](e2e/environment.md#configurable-e2e-environment) | +| Worktree topology (`1× android ∥ 1× ios ∥ 1× macos` per tree) | **Shipped** | [parallel topology](e2e/environment.md#parallel-e2e-topology) | +| Slot env + serial `yarn tests:*` | **Shipped** — `export-slot-env` then the same commands as [running e2e § Rules](e2e/rules.md#rules) | [slot lifecycle](e2e/environment.md#slot-lifecycle) | +| Concurrent macOS via `PRODUCT_NAME` | **Shipped** (e.g. `io.invertase.testing.s0`…`sN`) | [macOS process identity](e2e/slot-devices.md#macos-process-identity-concurrency) | +| Host check/release (`yarn tests:e2e:check` / `release`) | **Shipped** — serial default; slot via env; release frees only what the run recorded and fails fast on other owners; `--all-slots` is a manual machine wipe; Mellifera maps reservations to `RNFB_*` then calls these yarn targets (no JSON feed) | [host-clear probes](e2e/preflight-host-clear.md#host-clear-probes), [run record](e2e/preflight-host-clear.md#run-record) | | Coordinator / lease queue (Mellifera) | **WIP** — co-developed out-of-tree (not part of the contention PR) | Optional local `mellifera/` when present — consumes RNFB slots; does not own the runbook ([§ layers](#rnfb-mellifera-tart-layers)) | @@ -97,12 +97,12 @@ Commands for clear → start → build → test → free: [running e2e § slot l 1. **Per worktree:** max **1 Android + 1 iOS + 1 macOS** e2e run at a time. 2. **Per host:** same-platform parallel needs **one worktree per instance**. macOS isolation key is **`PRODUCT_NAME` / process name** (`RNFB_MACOS_PRODUCT_NAME`), not a single global lock. -3. **Firebase emulators:** parallel platform runs **must not share one emulator process** — Firestore `wipe()` and auth/storage state are global per emulator instance ([`packages/firestore/e2e/helpers.js`](../../packages/firestore/e2e/helpers.js)). Full aux-port isolation (websocket / eventarc / tasks) required — see [running e2e](running-e2e.md#configurable-e2e-environment). +3. **Firebase emulators:** parallel platform runs **must not share one emulator process** — Firestore `wipe()` and auth/storage state are global per emulator instance ([`packages/firestore/e2e/helpers.js`](../../packages/firestore/e2e/helpers.js)). Full aux-port isolation (websocket / eventarc / tasks) required — see [running e2e](e2e/environment.md#configurable-e2e-environment). 4. **Backward compatibility:** unset slotted env preserves serial defaults (ports `:8081` / `:8090` / …, process `io.invertase.testing`). -5. **Local slotted e2e is the serial runbook plus slot env.** Same commands as [running e2e § Rules](running-e2e.md#rules). The **only** required difference is selecting the slot’s ports + device identities (`yarn tests:e2e:export-slot-env` / `RNFB_*`). No second workflow (no rsync, no cloning trees, no host flock, no Metro-after-build). A 3×3 wave is **9 overlapping cells** (android + ios + macos `:test-cover`, qemu included). Do not serialize Android. Tolerate CI-like latency with higher Detox/launch timeouts rather than shrinking concurrency ([running e2e § slot lifecycle](running-e2e.md#slot-lifecycle)). +5. **Local slotted e2e is the serial runbook plus slot env.** Same commands as [running e2e § Rules](e2e/rules.md#rules). The **only** required difference is selecting the slot’s ports + device identities (`yarn tests:e2e:export-slot-env` / `RNFB_*`). No second workflow (no rsync, no cloning trees, no host flock, no Metro-after-build). A 3×3 wave is **9 overlapping cells** (android + ios + macos `:test-cover`, qemu included). Do not serialize Android. Tolerate CI-like latency with higher Detox/launch timeouts rather than shrinking concurrency ([running e2e § slot lifecycle](e2e/environment.md#slot-lifecycle)). 6. **Each concurrent instance is a normal git checkout / git worktree.** Populate it with `git worktree add` (or clone) + `yarn` in **that** tree. Mutagen/rsync is **remote worker snapshot only** (laptop → worker) — **not** local same-Mac slot trees. 7. **Watchman:** packager start **conditionally** `watch-del`s **this Metro project root** (skips when a sibling Metro/react-native process already owns that cwd — so android∥ios dual `tests/` packagers on distinct ports stay alive; `RNFB_METRO_FORCE_WATCHMAN_RESET=1` forces del) and always `watch-project`s an **allowlist** of trees Metro would reload. Never `watch-del` the repo root. Not a blocklist over a whole-monorepo watch. Tolerance lives in packager `/status` wait, not a parallel-only recipe. -8. **Apple `:build` stays representative.** iOS → `tests/ios/build`; macOS → `tests-macos/macos/build`. Do not set `SWIFT_ENABLE_EXPLICIT_MODULES=NO` (or similar) for e2e. If PCM races return, isolate the **actual** shared module-cache directory with [negative + positive tests](running-e2e.md#e2e-infrastructure-change-bar). +8. **Apple `:build` stays representative.** iOS → `tests/ios/build`; macOS → `tests-macos/macos/build`. Do not set `SWIFT_ENABLE_EXPLICIT_MODULES=NO` (or similar) for e2e. If PCM races return, isolate the **actual** shared module-cache directory with [negative + positive tests](e2e/rules.md#e2e-infrastructure-change-bar). ## Resource inventory (detail) @@ -110,7 +110,7 @@ Serial defaults and conflict modes are summarized in [§ How parallel e2e works] ### Slot lifecycle -The numbered recipe lives in [running e2e § slot lifecycle](running-e2e.md#slot-lifecycle). Do not duplicate those commands here. Order is the serial runbook (packager → emulator → pod → build → test-cover) after slot env is set. A cell helper, if kept, only chooses env vars then calls those commands. +The numbered recipe lives in [running e2e § slot lifecycle](e2e/environment.md#slot-lifecycle). Do not duplicate those commands here. Order is the serial runbook (packager → emulator → pod → build → test-cover) after slot env is set. A cell helper, if kept, only chooses env vars then calls those commands. ## Resource model @@ -130,7 +130,7 @@ The numbered recipe lives in [running e2e § slot lifecycle](running-e2e.md#slot └─────────────────────────────────────────────────────────────┘ ``` -Same-platform scale-out: **N worktrees × slot 0..N-1** (e.g. `3× android + 3× ios + 3× macos`). Slot index, effective max (**min(configured, hard 7)**), setup count **1..8**, and `eval`/check/release fail-before-action: [running e2e § slot index](running-e2e.md#e2e-slot-index). +Same-platform scale-out: **N worktrees × slot 0..N-1** (e.g. `3× android + 3× ios + 3× macos`). Slot index, effective max (**min(configured, hard 7)**), setup count **1..8**, and `eval`/check/release fail-before-action: [running e2e § slot index](e2e/environment.md#e2e-slot-index). ### Metro per worktree and per slot @@ -141,7 +141,7 @@ After the `tests-macos/` split, **iOS/Android** Metro lives in `tests/` and **ma | Mode | Metro | When | |------|-------|------| | **Serial default** | One Metro on `:8081` **per packager root** — mobile (`tests/`) **or** macOS (`tests-macos/`), not both at once | Unslotted local iteration | -| **Proven slotted** | **Distinct Metro listen port per platform×slot** (`RNFB_{PLATFORM}_METRO_PORT`, process-local `RCT_METRO_PORT`). A full slot that runs android/ios **and** macos starts **three** Metros: two `yarn tests:packager:jet` on `tests/` (android + ios ports) plus `yarn tests:macos:packager:jet` on `tests-macos/`. Dual `tests/` is safe because packager **skips** `watch-del` when a sibling owns that root ([running e2e § packager](running-e2e.md#packager-reset-cache-eaddrinuse)) | Parallel waves / multi-worktree — avoids babel/cache contention and matches `export-slot-env` | +| **Proven slotted** | **Distinct Metro listen port per platform×slot** (`RNFB_{PLATFORM}_METRO_PORT`, process-local `RCT_METRO_PORT`). A full slot that runs android/ios **and** macos starts **three** Metros: two `yarn tests:packager:jet` on `tests/` (android + ios ports) plus `yarn tests:macos:packager:jet` on `tests-macos/`. Dual `tests/` is safe because packager **skips** `watch-del` when a sibling owns that root ([running e2e § packager](e2e/recovery.md#packager-reset-cache-eaddrinuse)) | Parallel waves / multi-worktree — avoids babel/cache contention and matches `export-slot-env` | Cross-worktree: two worktrees **must not** share one Metro (different `packages/**` / harness). @@ -154,9 +154,9 @@ Cross-worktree: two worktrees **must not** share one Metro (different `packages/ | **Devices / macOS process** | One AVD, one sim UDID, one `PRODUCT_NAME` per concurrent instance | | **Jet control HTTP** | Paired 1:1 with each Jet instance | -**Port formula (proven):** `BASE = 12000 + slot×1000`; android offset `0`, ios `+100`, macos `+200`; within a platform block firestore…logging = `BLK+0..6`, metro `+7`, jet `+10`, jet-control `+11`. Emulator aux: firestore websocket / eventarc / tasks = `FS+8/+9/+12` via `yarn tests:emulator:start`. Slot 0 Metro listen: android **12007**, ios **12107**, macos **12207**. Commands: [running e2e § slot lifecycle](running-e2e.md#slot-lifecycle). +**Port formula (proven):** `BASE = 12000 + slot×1000`; android offset `0`, ios `+100`, macos `+200`; within a platform block firestore…logging = `BLK+0..6`, metro `+7`, jet `+10`, jet-control `+11`. Emulator aux: firestore websocket / eventarc / tasks = `FS+8/+9/+12` via `yarn tests:emulator:start`. Slot 0 Metro listen: android **12007**, ios **12107**, macos **12207**. Commands: [running e2e § slot lifecycle](e2e/environment.md#slot-lifecycle). -**Babel carry-in:** every Metro/Jest process for a slot must receive the **full** `RNFB_{ANDROID,IOS,MACOS}_*` set — port selection uses `Platform.*` / Detox, not `RNFB_E2E_PLATFORM` ([running e2e](running-e2e.md#configurable-e2e-environment)). +**Babel carry-in:** every Metro/Jest process for a slot must receive the **full** `RNFB_{ANDROID,IOS,MACOS}_*` set — port selection uses `Platform.*` / Detox, not `RNFB_E2E_PLATFORM` ([running e2e](e2e/environment.md#configurable-e2e-environment)). ### Platform bundle (per host slot) @@ -171,7 +171,7 @@ Each **android-slot** / **ios-slot** / **macos-slot** is a fixed **port block** | iOS | `iPhone 17` | exact `.detoxrc` base `RN E2E iOS slot-{n}` (incl. `slot-0`); occupied bases fail allocation; Detox `ios.sim.debug.slot{n}` | | macOS | `io.invertase.testing` | **`io.invertase.testing.s{n}`** via `RNFB_MACOS_PRODUCT_NAME` | -**macOS (proven):** no `macos-global` lock. Concurrent macOS = distinct `PRODUCT_NAME` (+ derived bundle id for Metro `app=`). Build uses `RNFB_MACOS_PRODUCT_NAME_SUFFIX` in pbxproj — **never** pass global `PRODUCT_NAME=` on the `xcodebuild` CLI (renames Pods / breaks linking). Details: [running e2e § macOS process identity](running-e2e.md#macos-process-identity-concurrency). +**macOS (proven):** no `macos-global` lock. Concurrent macOS = distinct `PRODUCT_NAME` (+ derived bundle id for Metro `app=`). Build uses `RNFB_MACOS_PRODUCT_NAME_SUFFIX` in pbxproj — **never** pass global `PRODUCT_NAME=` on the `xcodebuild` CLI (renames Pods / breaks linking). Details: [running e2e § macOS process identity](e2e/slot-devices.md#macos-process-identity-concurrency). ### Worktree-internal parallelism @@ -191,11 +191,11 @@ eval "$(bash scripts/e2e/export-slot-env.sh n)" # then canonical ya ### Teardown (required) -macOS `:test-cover` must not leave the test app running — a stale process on a shared Jet port breaks later Android runs ([running e2e § Android app reset](running-e2e.md#android-app-reset-blocking)). +macOS `:test-cover` must not leave the test app running — a stale process on a shared Jet port breaks later Android runs ([running e2e § Android app reset](e2e/preflight-host-clear.md#android-app-reset-blocking)). [`tests-macos/.jetrc.js`](../../tests-macos/.jetrc.js) macOS target: -- `before`: kill this run's own app pids, fail fast if a same-name app it did not start is still running, prefetch Metro bundle (`app=` = bundle id), spawn binary path from `RNFB_MACOS_PRODUCT_NAME`, and record the spawned pid ([run record](running-e2e.md#run-record)). +- `before`: kill this run's own app pids, fail fast if a same-name app it did not start is still running, prefetch Metro bundle (`app=` = bundle id), spawn binary path from `RNFB_MACOS_PRODUCT_NAME`, and record the spawned pid ([run record](e2e/preflight-host-clear.md#run-record)). - `after` / exit handlers: SIGTERM then SIGKILL the pids this run spawned; never `killall` by name. - App stdio detached (`ignore`) so `| tee` pipes close when Jet exits. @@ -403,10 +403,10 @@ Deliverables: |------|-------| | dflockd (or resleased) + coordinator | Docker-compose or brew-style one-liner for dev hosts | | `run-worktree-parallel.sh` | **Three Metros** when android+ios+macos are in the wave (two on `tests/` + one on `tests-macos/`), distinct listen port per platform×slot (+ Jet/emulators); sibling-safe Watchman skip-del; three `:test-cover` parallel | -| Future coordinator client | Reserve → [slot lifecycle](running-e2e.md#slot-lifecycle) `yarn tests:*` → release (EXIT trap). Not a second e2e runbook. | +| Future coordinator client | Reserve → [slot lifecycle](e2e/environment.md#slot-lifecycle) `yarn tests:*` → release (EXIT trap). Not a second e2e runbook. | | Pre-flight | Per-platform scoped probes | -**Done when:** a coordinator client uses reserve/release around the [slot lifecycle](running-e2e.md#slot-lifecycle) Law; Android + iOS + macOS run concurrently on one worktree via HTTP API; `GET /v1/capacity` shows worker slots. +**Done when:** a coordinator client uses reserve/release around the [slot lifecycle](e2e/environment.md#slot-lifecycle) Law; Android + iOS + macOS run concurrently on one worktree via HTTP API; `GET /v1/capacity` shows worker slots. ### Phase 2 — Multi-worktree + multi-slot hosts + sync @@ -487,7 +487,7 @@ sequenceDiagram CO->>LS: release tokens ``` -Phase 1 without a coordinator: operators `eval "$(yarn tests:e2e:export-slot-env N)"` then run the same canonical `yarn tests:*` Law as serial ([running e2e § slot lifecycle](running-e2e.md#slot-lifecycle)). +Phase 1 without a coordinator: operators `eval "$(yarn tests:e2e:export-slot-env N)"` then run the same canonical `yarn tests:*` Law as serial ([running e2e § slot lifecycle](e2e/environment.md#slot-lifecycle)). Phase 1 with coordinator uses `checkout_mode: local` and omits the sync branch. @@ -522,16 +522,16 @@ See [§ Lease store](#lease-store-reuse-vs-build-scope) for the build-vs-reuse d ### Builds -- **Cross-worktree Apple builds:** each tree uses its own `derivedDataPath` (`tests/ios/build` vs `tests-macos/macos/build`). Do **not** disable Swift explicit modules. If `.pcm` races return, prove the shared cache path and isolate **that** directory ([infrastructure change bar](running-e2e.md#e2e-infrastructure-change-bar)). +- **Cross-worktree Apple builds:** each tree uses its own `derivedDataPath` (`tests/ios/build` vs `tests-macos/macos/build`). Do **not** disable Swift explicit modules. If `.pcm` races return, prove the shared cache path and isolate **that** directory ([infrastructure change bar](e2e/rules.md#e2e-infrastructure-change-bar)). - **Do not** run two overlapping multi-slot waves against the **same** worktrees — shared `ios/build` / `macos/build` is not multi-writer-safe. -- **Android Gradle home:** concurrent slotted Android `:build` **shares** `~/.gradle`. Do **not** isolate `GRADLE_USER_HOME`. Historical path poisoning was **rsync**, not Gradle ([running e2e § Environment](running-e2e.md#environment)). +- **Android Gradle home:** concurrent slotted Android `:build` **shares** `~/.gradle`. Do **not** isolate `GRADLE_USER_HOME`. Historical path poisoning was **rsync**, not Gradle ([running e2e § Environment](e2e/environment.md#environment)). ## Documentation and policy updates (by phase) | Phase | Docs | |-------|------| | 1 | [running e2e](running-e2e.md) slot lifecycle (Law); [agent command policy](agent-command-policy.md) allowlists `yarn tests:*` only | -| 2 | This doc § coordinator CLI; [change authoring § host rule](change-authoring-workflow.md#host-rule) → per-slot | +| 2 | This doc § coordinator CLI; [change authoring § host rule](authoring/implementation.md#host-rule) → per-slot | | 3 | `capacity.json` schema; operator guide for `host-status` | Work-queue rows for implementation are ephemeral — not duplicated here per [documentation policy](../documentation-policy.md). @@ -545,13 +545,13 @@ Work-queue rows for implementation are ephemeral — not duplicated here per [do | Stale leases after agent crash | TTL + pid check + `cleanup-stale` | | Operator confusion (wrong PRODUCT_NAME / slot) | `host-status` shows leased `macos-slot-N` + product name; check names `owner=unrecorded` holders and a free slot; `--all-slots` recover is manual, at explicit user direction only | | Coverage merge complexity | Per-worktree artifacts; merge script optional for local dev | -| Passing `PRODUCT_NAME=` on xcodebuild CLI | Forbidden — use suffix env only ([running e2e](running-e2e.md#macos-process-identity-concurrency)) | +| Passing `PRODUCT_NAME=` on xcodebuild CLI | Forbidden — use suffix env only ([running e2e](e2e/slot-devices.md#macos-process-identity-concurrency)) | | Concurrent Apple `:build` PCM races | Isolate real module-cache dir if reproduced; never `SWIFT_ENABLE_EXPLICIT_MODULES=NO` | ## Open questions 1. **AVD strategy:** **decided** — clone `TestingAVD-0`…`TestingAVD-N` for slotted runs; serial keeps `TestingAVD` (`create-android-avds.sh`). -2. **iOS simulators:** **decided** — dedicated exact devices `RN E2E iOS slot-0`…`slot-7`, so a shared Mac can run other RN e2e stacks (Detox or Appium) against the same slots; serial keeps `iPhone 17` (`create-ios-simulators.sh`, create/reuse-only). Patched Detox reuses the exact base or fails on ownership conflict. Naming and host migration: [running e2e § iOS slot simulators](running-e2e.md#ios-slot-simulators). +2. **iOS simulators:** **decided** — dedicated exact devices `RN E2E iOS slot-0`…`slot-7`, so a shared Mac can run other RN e2e stacks (Detox or Appium) against the same slots; serial keeps `iPhone 17` (`create-ios-simulators.sh`, create/reuse-only). Patched Detox reuses the exact base or fails on ownership conflict. Naming and host migration: [running e2e § iOS slot simulators](e2e/slot-devices.md#ios-slot-simulators). 3. **Shared build artifacts:** single `tests/ios/build` / `tests-macos/macos/build` per worktree (serial build within tree) — confirmed OK; same-platform parallel ⇒ multiple worktrees. 4. **Coordinator language:** Node (matches repo / mellifera) vs Go (matches dflockd) for the thin HTTP layer? 5. **Tart:** a Mellifera-published slot **may** run inside a Tart VM; Tart is not the RNFB e2e product ([layers](#rnfb-mellifera-tart-layers)). @@ -561,10 +561,10 @@ Work-queue rows for implementation are ephemeral — not duplicated here per [do ## Related docs -* [Running e2e tests](running-e2e.md) — canonical commands, change bar, [slot lifecycle](running-e2e.md#slot-lifecycle), [slot index](running-e2e.md#e2e-slot-index) +* [Running e2e tests](running-e2e.md) — canonical commands, change bar, [slot lifecycle](e2e/environment.md#slot-lifecycle), [slot index](e2e/environment.md#e2e-slot-index) * [Coverage design](coverage-design.md) — per-platform artifact policy * [Firebase testing project](firebase-testing-project.md) — emulator vs cloud * Mellifera coordinator — co-developed out-of-tree; see [§ RNFB e2e, Mellifera, and Tart](#rnfb-mellifera-tart-layers) (not shipped in the contention PR) * [scripts/tart/README.md](../../scripts/tart/README.md) — separate VM system -* [Change authoring workflow § host rule](change-authoring-workflow.md#host-rule) — serial default; slotted exception via running-e2e +* [Change authoring workflow § host rule](authoring/implementation.md#host-rule) — serial default; slotted exception via running-e2e * [Agent command policy](agent-command-policy.md) — allowlisted `yarn tests:*` \ No newline at end of file diff --git a/okf-bundle/testing/e2e/environment.md b/okf-bundle/testing/e2e/environment.md new file mode 100644 index 0000000000..82afa8bad3 --- /dev/null +++ b/okf-bundle/testing/e2e/environment.md @@ -0,0 +1,70 @@ +--- +type: Reference +title: 'E2e: environment and slot topology' +description: 'Devices and stale-process environment notes, configurable e2e environment, parallel topology, slot lifecycle, and slot index.' +tags: [testing, e2e, environment, slots] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: environment and slot topology + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Environment + +- **Devices** — Serial iOS/Android: Detox boots `iPhone 17` / `TestingAVD`. Slotted Android: `TestingAVD-N`. Slotted iOS: `.detoxrc` names `RN E2E iOS slot-N`; patched Detox boots that exact base or fails when it is registry-taken — [iOS slot simulators](slot-devices.md#ios-slot-simulators). iOS `:test-cover` should preflight with `yarn tests:e2e:check --platform=ios`, which fails when the identity's own simulator is already booted — see [global device scoping](slotted-parallel.md#global-device-scoping). macOS auto-starts app. +- **adb empty** — `adb devices` should list no emulator this run did not start. `adb kill-server` restarts the shared server for every owner: explicit user direction only ([manual machine wipe](preflight-host-clear.md#manual-machine-wipe)). +- **Stale processes (serial default)** — one Metro (`:8081`) per packager project (`tests/` for iOS/Android, `tests-macos/` for macOS), one emulator set (`:8080`, `:9099`, `:9000`, `:4400`, `:5001`, …). Stray listener on `:8090` after a run → [pre-flight recovery](recovery.md#pre-flight-recovery), then restart background services with [Rules §1–2](rules.md#rules) (`yarn tests:packager:jet` or `yarn tests:macos:packager:jet`, `yarn tests:emulator:start`). Reset-cache `EADDRINUSE` on `:8081` → [packager reset-cache](recovery.md#packager-reset-cache-eaddrinuse). Slotted runs: [configurable e2e environment](#configurable-e2e-environment). +- **Android Gradle home** — leave `GRADLE_USER_HOME` unset so Gradle uses the host default (`~/.gradle`). Slotted `export-slot-env` does **not** isolate a per-slot Gradle home; independent git worktrees share `~/.gradle` by design (Gradle’s user home is built for concurrent CI). If a host does not default there, optionally set `GRADLE_USER_HOME=$HOME/.gradle` as host setup — not slot isolation. Historical “cross-worktree Gradle race” (`bundleLibRuntimeToDirDebug` resolving another tree’s absolute `node_modules` paths) was **rsync path poisoning** (stale `autolinking.json` / config-cache worktree roots), not a Gradle cache concurrency bug. + + + +### Configurable e2e environment + +Serial e2e uses committed defaults (Metro `:8081`, Jet `:8090`, emulators `:8080` / `:9099` / …). Slotted parallel runs export **per-platform prefixed** ports (e.g. `RNFB_ANDROID_JET_PORT`, `RNFB_IOS_METRO_PORT`) **before** Metro/native build and `:test-cover`. Unset vars keep legacy serial behaviour. + + + + +**Parallel e2e topology (worktrees):** same-platform parallel needs **one git worktree per concurrent instance** of that platform. Populate each instance with `git worktree add` (or clone) + `yarn` in **that** tree — never `rsync` sources between local slot worktrees. A single worktree may run **at most** `1× android ∥ 1× ios ∥ 1× macos` (distinct Metro/Jet/emulator blocks + distinct AVD/sim + distinct macOS `PRODUCT_NAME`). Example: `3× android + 3× ios + 3× macos` ⇒ three worktrees. Do **not** launch two of the same platform from one worktree — native products, Detox configs, coverage, and (macOS) one `macos/build` tree are not multi-instance-safe. Why: [e2e parallel design](../e2e-parallel-design.md). iOS derived data is `tests/ios/build`; macOS is `tests-macos/macos/build`. Do **not** change Swift explicit-module (or other) xcodebuild settings to paper over concurrent builds — [infrastructure change bar](rules.md#e2e-infrastructure-change-bar). + +**The Law — same runbook as serial:** load slot env in this shell, then use the [Rules §1–4](rules.md#rules) yarn scripts. On a shared host, load that env before the first packager or emulator start. iOS is one order: `yarn tests:ios:pod:install`, then `yarn tests:ios:build` (compiles only; does not install pods), then host-clear, then `yarn tests:emulator:start` and `yarn tests:packager:jet`, then [services ready](preflight.md#2-services-ready) (Metro status contains `packager-status:running` after the build), then `yarn tests:ios:test-cover`. The agent emulator command is `yarn tests:emulator:start` (`yarn tests:emulator:start-ci` is CI-only). The agent test command is `yarn tests:ios:test-cover`. `yarn tests:ios:test` is a different script. `:test-cover` does not build; the native app has to exist first. + +```bash +# iOS +eval "$(yarn tests:e2e:clear-slot-env)" # serial only: drop leftover export-slot-env +eval "$(yarn tests:e2e:export-slot-env ios N)" # omit for serial defaults; N is the slot index +yarn tests:ios:pod:install # separate prior step; :build does not install pods; serialize across worktrees +yarn tests:ios:build # compiles only; does not run tests +yarn tests:e2e:check --platform=ios # host-clear +yarn tests:emulator:start # long-running; not the CI-only -ci script +yarn tests:packager:jet # long-running; status body contains packager-status:running +# services-ready (that status check after the build), then: +yarn tests:ios:test-cover # does not build +yarn tests:e2e:release [--devices] # optional +``` + +Android and macOS keep slot env, then packager, emulator, `:build`, and `:test-cover`. macOS `pod:install` stays a separate prior step before `yarn tests:macos:build`. That block is not the iOS order. + +```bash +# Android or macOS +eval "$(yarn tests:e2e:clear-slot-env)" # serial only: drop leftover export-slot-env +eval "$(yarn tests:e2e:export-slot-env N)" # android or macos; omit for serial defaults +yarn tests:e2e:check # optional; default = serial-only; slotted = env from the line above +yarn tests:packager:jet # macos: yarn tests:macos:packager:jet +yarn tests:emulator:start +yarn tests:macos:pod:install # macOS, when needed — serialize across worktrees (shared CocoaPods CDN) +yarn tests::build # compiles only; does not invoke pod install +yarn tests::test-cover +yarn tests:e2e:release [--devices] # optional +``` + +No second lifecycle (no host flock, no Metro-after-build, no slotted packager/test-cover yarn aliases, no `clean-slot-build-artifacts`). Collision control is **slot identity + check/release**. Mellifera leases slots; Tart may host a slot VM — [layers](../e2e-parallel-design.md#rnfb-mellifera-tart-layers). + + + +**Slot index (`N`):** decimal integer **0..effective max**, where effective max is **min(configured `E2E_SLOTTED_MAX`, hard 7)**. The same guard applies to `yarn tests:e2e:export-slot-env` (and apply) and to canonical `yarn tests:e2e:check --slot=N` / `release --slot=N`. Invalid or out-of-range fails **before any export, probe, or release action** (`eval "$(…)"` cannot apply a partial env). Lowering `E2E_SLOTTED_MAX` is honored; raising it cannot exceed Detox slot **7**. Preferred lifecycle selector remains `eval "$(yarn tests:e2e:export-slot-env …)"` then check/release. + +**`--all-slots` sweeps** (ports, Android AVDs, exact iOS neutral bases, macOS `.sN`, check/release) use that same effective max. The release sweep is the [manual machine wipe](preflight-host-clear.md#manual-machine-wipe). + +**Setup count:** `yarn tests:e2e:setup-android-avds [count]` / `yarn tests:e2e:setup-ios-sims [count]` accept a strict decimal integer **1..8** (default **1**). `count=8` provisions indices **0..7**. Invalid values and **9+** fail **before any inventory or device command**. Setup count is the hard Detox inventory bound, independent of a lowered sweep ceiling. diff --git a/okf-bundle/testing/e2e/full-suite.md b/okf-bundle/testing/e2e/full-suite.md new file mode 100644 index 0000000000..ef0a580759 --- /dev/null +++ b/okf-bundle/testing/e2e/full-suite.md @@ -0,0 +1,38 @@ +--- +type: Reference +title: 'E2e: full suite orchestrator' +description: 'yarn test:full flags, deterministic release, overlapping verify / Jest, and scratch paths.' +tags: [testing, e2e, full] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: full suite orchestrator + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + + + +### Full suite orchestrator (`yarn test:full`) + +`scripts/run-full-tests.sh` is the **prescribed full gate** for pre-merge validation in a single worktree. It runs install → Apple pods (ios ∥ macos) → parallel verify (builds, tsc, attw, lint, jest, android/ios unit) → `:test-cover` e2e with coverage post-process. attw ∥ ios unit: [Types-AD-5](../architecture-decisions.md#types-ad-5--pack-ignores-nested-ios-unit-build-trees--accepted). + + + +**Overlapping verify / Jest:** when several worktrees run `yarn test:full` (or the verify phase) concurrently while Apple `:build` writes under `tests/ios/build` / `tests-macos/macos/build`, a Jest walk that recurses those trees can hit ENOENT (live SPM extracts) or SIGSEGV under multi-worker verify. Committed-harness scans skip `build` / `Pods` / `DerivedData` (and similar) directories — [`packages/app/__tests__/harnessCommittedDefaults.test.ts`](../../../packages/app/__tests__/harnessCommittedDefaults.test.ts). If verify still flakes under heavy overlap, retry that worktree’s verify (or the full command) once; do not treat a single ENOENT/SIGSEGV under sibling `:build` as product failure. + +**Deterministic by default:** every run performs scoped `yarn tests:e2e:release --devices` + check before e2e, and the same release after (pass or fail). That release clears the Metro, Jet, Firebase emulator suite, test apps, and AVD/sims this checkout's runs [recorded](preflight-host-clear.md#run-record) — `--devices` adds device teardown on top of the port release, not instead of it ([release script default](../../../scripts/e2e/release-e2e-resources.sh)). A port held by another owner fails the pre-flight check instead of being killed. `yarn test:full` never wipes the machine; the old `--clear-whole-host` flag now exits 2 and points to the [manual machine wipe](preflight-host-clear.md#manual-machine-wipe). Fast reuse / tight edit loops use the decomposed `yarn tests:*` commands in this doc — not `yarn test:full`. + +```bash +yarn test:full # serial unslotted e2e (ios → android → macos; Metro switch) +yarn test:full --slot 3 # slotted parallel e2e (1× android ∥ 1× ios ∥ 1× macos) +yarn test:full --verbose # stream output (default: compact status + LOGDIR logs) +``` + +| Flag | Default | Purpose | +| --- | --- | --- | +| `--slot N` | off (serial) | Parallel slotted e2e in this worktree. `N` must be a [slot index](environment.md#e2e-slot-index) `export-slot-env` would accept. Each platform subprocess gets its own `eval "$(yarn tests:e2e:export-slot-env N)"` — **never** one android export for all three. | +| `--verbose` | off | Stream step output. Default prints one status line per phase; full logs under `${TMPDIR:-/tmp}/rnfb-full-*` (preserved on failure). | + + + +**Scratch paths:** RNFB's e2e and fixture scripts write logs and scratch files outside the checkout only under `${TMPDIR:-/tmp}`: the `yarn test:full` LOGDIR, the release recheck output (one file per run, removed on exit), the Metro log, the Firebase emulator log (`RNFB_EMULATOR_LOG`), and the test-expo / test-rn-bare logs and DerivedData. A caller that points `TMPDIR` at a per-run directory removes all of them by deleting it. The Metro cache is separate ([packager start](recovery.md#packager-start)): point `RNFB_METRO_CACHE_ROOT` into the same directory to include it. Explicit path overrides (`RNFB_*_LOG`, `RNFB_TEST_RN_BARE_*`, `RNFB_TEST_EXPO_*`) still win; CI workflows pin the paths they upload as artifacts. diff --git a/okf-bundle/testing/e2e/gates.md b/okf-bundle/testing/e2e/gates.md new file mode 100644 index 0000000000..28e776247c --- /dev/null +++ b/okf-bundle/testing/e2e/gates.md @@ -0,0 +1,137 @@ +--- +type: Reference +title: 'E2e: gates and validation tiers' +description: 'Harness narrowing gate, platform coverage gate, unit-focused loop, one :test-cover at a time, e2e validation tiers, and before-merge.' +tags: [testing, e2e, gates, tiers] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: gates and validation tiers + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +### Harness narrowing gate (blocking) + +**Both `unit-focused` and `area-focused` tiers require area narrowing before the first `:test-cover`.** The only difference between those tiers is whether `.only` is allowed and whether the full package-area spec loads — not whether the harness stays at full app load. + +**Primary mechanism:** create a local **`tests/harness.overrides.js`** (gitignored) from [`tests/harness.overrides.example.js`](../../../tests/harness.overrides.example.js). Committed `tests/app.js` and `tests/globals.js` stay at full harness — do **not** edit them for module narrowing or `RNFBDebug`. See [local harness overrides](narrowing.md#local-harness-overrides-harnessoverridesjs). + +| Mistake | Symptom | Gate impact | +| --- | --- | --- | +| Run `:test-cover` with no overrides (full harness) during `implementation` or `independent-review` | macOS/iOS/Android pass counts in the **hundreds or thousands** (all modules via `require.context`) | Run is **invalid** — does not close `implementation_gate` or `review_gate` | +| Edit only one platform block in `tests/app.js` (legacy pattern) while the other still pushes full list | macOS ~700 firestore tests pass; iOS/Android logs show `database`, `crashlytics`, etc. | Run is **invalid** on iOS/Android — use [overrides file](narrowing.md#local-harness-overrides-harnessoverridesjs) instead | +| Correct area harness via overrides | Pass counts match loaded module/spec scope ([sanity table](narrowing.md#sanity-check-by-platform)) | Expected | + +**Apply locally before every `:test-cover` at unit-focused or area-focused tier** — even when git shows the full push harness. **Remove** `tests/harness.overrides.js` (or export `{}`) after the run when the branch keeps full harness (typical until **full** / pre-merge). Never commit `harness.overrides.js`. + +**Validation report must state:** harness narrowed (yes/no), override file used (yes/no), which module/spec loads, whether pass counts match area scope, and **which platforms ran** with exit codes. A green full-app run is not a substitute. + + + +### Platform coverage gate (blocking — no shortcuts) + +**Both `unit-focused` (implementation) and `area-focused` (baseline-capture, independent-review) require e2e on every platform where the changed module loads in the committed harness** — not a subset for convenience. + +Determine required platforms from committed [`tests/app.js`](../../../tests/app.js) platform blocks (use **committed** lists when deciding macOS vs native requirement, not a narrowed local harness): + +| Platform class | When required | +| --- | --- | +| **macOS** (`Platform.other`) | Module appears in the committed `if (Platform.other)` list (or overrides `modules` includes it) | +| **iOS** and **Android** | Module appears in the committed `if (!Platform.other)` list (or overrides `modules` includes it) | + +**What in the frozen diff triggers this gate** + +| Frozen-diff touch | Required platforms | +| --- | --- | +| Native bridge / podspec / TurboModule spec / **committed** `packages/*/ios/generated/**` or `…/android/**/generated/**` | Every platform where the module loads (table above); rebuild per [Rules §3](rules.md#rules) before `:test-cover` | +| `packages/*/lib/**` (JS/TS runtime of a module that loads on native or macOS) | Same platform matrix as above for that module | +| **`packages/*/e2e/**`** (Detox/Jet specs for a package module) | **Same platform matrix** — area-narrowed `:test-cover` on **every** platform where that module loads, **even when the frozen diff has no native hunk for that OS** | + +E2e-only diffs still exercise the same host/native clients as product code. Skipping Android because “only iOS sources changed” (or the reverse) is an **invalid shortcut** when `packages//e2e/**` is in the frozen tree and the module is on that platform’s harness list. Authoring evidence note: [change authoring § validation evidence](../authoring/gates.md#validation-evidence-blocking). + +**Area-focused (`baseline-capture`, `independent-review`) — closes `review_gate` / baseline only when:** + +1. Full loaded package spec(s) with [area narrowing](#harness-narrowing-gate-blocking) (no `.only`). +2. **Serial** `:test-cover` on **each required platform** above — pre-flight before **every** run. +3. Native platforms: `yarn tests::build` before first `:test-cover` when native changed ([Rules §3](rules.md#rules)). +4. Validation handoff includes a **platform matrix**: platform, exit code, pass/fail/pending counts, log path. + +**Invalid shortcuts (do not close gates):** + +- “macOS + iOS minimum”; skipping **Android** when the module loads on Android. +- “Skip Android if time tight” or “Android fallback only if iOS failures look env-related” without a fresh Android run. +- Skipping a platform because the frozen diff has **no native sources for that OS** while `packages/*/e2e/**` (or `lib/**`) for a module that loads there **is** in the frozen tree. +- Substituting a prior implementer log for `independent-review` on the frozen tree. +- Treating **`yarn codegen:verify`** (or scripts/OKF-only Jest) as enough when `packages/*/ios/generated/**`, `packages/*/android/**/generated/**`, native shells, podspecs, or specs changed — those still need iOS + Android `:test-cover` ([Rules §3](rules.md#rules)). +- Closing pre-flight on port/HTTP checks alone when Metro/emulators are owned by another worktree ([checkout ownership](preflight.md#services-checkout-ownership-blocking)). + +**Module-specific skip:** only when the module is **absent** from that platform’s harness list (e.g. `messaging` is not on macOS). Record in the work-queue **Notes** — not an oral exception. + +**Unit-focused (`implementation`) — native or package e2e touched:** macOS first when the path is TS/web-only; when the module loads on iOS **and** Android, run **both** before closing `implementation_gate` (same narrowing; `.only` OK locally; never commit). Package `e2e/**` edits follow the same matrix as native for that module. + +See also: [coverage design § platform parity](../code-coverage/policy.md#coverage-expectations-policy), [validation checklist § handoff](../validation/evidence-and-handoff.md#handoff-checklist). + +**Checklist (copy before first run):** + +1. `tests/harness.overrides.js` exists with correct `modules` (almost always include `'app'`) and `RNFBDebug: true`. +2. Overrides `modules` lists only the package under change (e.g. `['app', 'firestore']`). +3. Spec load uses direct `require` of the area spec — not `require.context` for all packages — when sub-suite narrowing applies; otherwise full package `require.context` is OK when the module list is narrowed. +4. No `.only` when tier is **area-focused**; `.only` optional when tier is **unit-focused**. +5. Grep log: pass count consistent with area scope ([sanity table](narrowing.md#sanity-check-by-platform)), not a full-app load (hundreds or thousands of tests across unrelated modules). + +### Unit-focused-tier iteration loop + +For `implementation` work type — validation tier **unit-focused** ([change authoring workflow](../authoring/implementation.md#implementation-inner-loop)): + +1. [Pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start) — [prepare completion gate](preflight.md#prepare-completion-gate-blocking) when `lib/**` changed, [host-clear probes](preflight-host-clear.md#host-clear-probes), services ready, **harness overrides in place** (step 3), **`RNFBDebug: true`** via overrides; if probes fail, [pre-flight recovery](recovery.md#pre-flight-recovery) first. +2. Edit e2e/spec; add `.only` if needed; never commit overrides or `.only`. +3. macOS first when TS-only: `yarn tests:macos:test-cover 2>&1 | tee /tmp/rnfb-e2e-macos.log` — wait for exit code ([stalled run](recovery.md#stalled-run-detection) if markers stop). +4. If macOS green and native touched: `yarn tests::build && yarn tests::test-cover 2>&1 | tee /tmp/rnfb-e2e-.log`; one platform at a time. +5. Grep log tail → fix → repeat from step 1. +6. When `implementation_gate` closes, next work type is `documentation?` then `independent-review` at **area-focused** tier — [change authoring § primary loop](../authoring/loop.md#primary-loop); [frozen tree](../authoring/review-and-commit.md#frozen-tree); no `.only`; area narrowing per package workflow. + + + +### One `:test-cover` at a time + +**Serial default** for gate closure and unslotted hosts — see [host rule](../authoring/implementation.md#host-rule). Slotted exception: [parallel e2e topology](environment.md#parallel-e2e-topology) + [configurable e2e environment](environment.md#configurable-e2e-environment). + +| Rule | Requirement | +| --- | --- | +| **One unslotted e2e at a time** | Wait for prior shell exit code + short log summary (unless each run has distinct slotted ports/devices per [parallel e2e topology](environment.md#parallel-e2e-topology)) | +| **No overlapping tiers** | Never run unit-focused-tier and area-focused-tier `:test-cover` concurrently on one host | +| **Clean pre-flight every run** | [Pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start) — [host-clear probes](preflight-host-clear.md#host-clear-probes), services, harness tier | +| **Phase J e2e** | Same serial `:test-cover` rule. Authoring loop: [change authoring primary loop](../authoring/loop.md#primary-loop) (`documentation?` before frozen `independent-review`). Harness: [pipeline area harness](../../packages/firestore/pipeline-implementation-workflow.md#pipeline-area-harness) | + +Tier scope table: [E2e validation tiers](#e2e-validation-tiers-unit-focused--area-focused--full). + +Each run owns its blocking `:test-cover` and returns summaries only. + +## E2e validation tiers (unit-focused / area-focused / full) + +All tiers use [canonical commands](rules.md#rules), [host rule](../authoring/implementation.md#host-rule), and clean [pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start). Tier names describe **scope** — see [iteration vocabulary](../iteration-vocabulary.md#validation-tier-identifiers). Public OKF owns the terms, gates, and commands. + +| Validation tier | E2e scope | Narrowing allowed | Typical work type | +| --- | --- | --- | --- | +| **Unit-focused** | Fast loop while product code is changing | `harness.overrides.js` + optional `.only` / sub-suite `require` in `tests/app.js` — **never commit** | `implementation` | +| **Area-focused** | Full loaded spec(s) for the package/area under change | **`harness.overrides.js`** required; **no** `.only` | `baseline-capture`, `independent-review` | +| **Full** | Unfocused — all modules, all platforms | Delete overrides file — committed full harness only | `pre-merge-validation` | + +**Universal rules:** + +- **Serial default** for gate closure — one unslotted `:test-cover` at a time. Slotted cross-platform concurrency only per [parallel e2e topology](environment.md#parallel-e2e-topology) (still never two of the **same** platform from one worktree). +- Every run starts from **verified [pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start)**; if probes fail, [pre-flight recovery](recovery.md#pre-flight-recovery) before another run. +- Use **only** canonical commands from this doc. +- Never overlap unit-focused-tier and area-focused-tier `:test-cover` on one host. + +See also: [unit-focused-tier loop](#unit-focused-tier-iteration-loop), [one :test-cover at a time](#one-test-cover-at-a-time), [pre-merge](#before-merge-pr-handoff). + +## Before merge (PR handoff) + +Pre-merge applies once to the branch commit stream before merge/push intended for merge, not after every commit. + +1. Remove all narrowing ([full tier](#e2e-validation-tiers-unit-focused--area-focused--full)): delete `tests/harness.overrides.js` (or `{}`), revert any temporary `require.context` → single `require` edits in `tests/app.js`, remove all `.only`, remove native instrumentation. Committed `tests/globals.js` / `tests/app.js` stay at full harness defaults — do not revert durable product wiring (e.g. `NativeRNFBTurbo*` proxy). +2. [Pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start) — [host-clear probes](preflight-host-clear.md#host-clear-probes) pass before each platform run. +3. Rebuild when needed (`tests::build`; `yarn lerna:prepare` for `lib/**`). After TurboModule codegen or native bridge edits, see [TurboModule stale toolchain](platform-troubleshooting.md#turbomodule-stale-toolchain-blocking). +4. Full unfocused suite with coverage on **iOS, Android, macOS** — one platform at a time, all green. +5. Record [validation evidence package](../validation/evidence-and-handoff.md#validation-evidence-package) and [coverage evidence package](../code-coverage/policy.md#coverage-evidence-package) when lib/native touched — required before merge or push ([change authoring § validation evidence](../authoring/gates.md#validation-evidence-blocking)). diff --git a/okf-bundle/testing/e2e/narrowing.md b/okf-bundle/testing/e2e/narrowing.md new file mode 100644 index 0000000000..f669896705 --- /dev/null +++ b/okf-bundle/testing/e2e/narrowing.md @@ -0,0 +1,139 @@ +--- +type: Reference +title: 'E2e: typical loop and test narrowing' +description: 'Typical loop, local harness overrides, spec loading, sanity counts, and RNFBDebug fail-fast / sub-suite narrowing.' +tags: [testing, e2e, narrowing] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: typical loop and test narrowing + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Typical loop + +iOS is one order. On a shared host, slot env is loaded before the packager or emulator. `yarn tests:ios:pod:install` is a separate prior step. `yarn tests:ios:build` compiles only and does not install pods. `yarn tests:ios:test-cover` does not build. The agent emulator command is `yarn tests:emulator:start` (`yarn tests:emulator:start-ci` is CI-only). The agent test command is `yarn tests:ios:test-cover` (`yarn tests:ios:test` is a different script). After the packager starts, its status body contains `packager-status:running`, then [services ready](preflight.md#2-services-ready) repeats that check after the build. + +```bash +# iOS +yarn tests:ios:pod:install +yarn tests:ios:build +yarn tests:e2e:check --platform=ios # host-clear +yarn tests:emulator:start # long-running +yarn tests:packager:jet # long-running; status body contains packager-status:running +# services-ready, then: +yarn tests:ios:test-cover + +# Android / macOS. Apple :build compiles only — pod:install is a separate prior step (skip for Android). +yarn tests:emulator:start +yarn tests:packager:jet +# yarn tests:macos:packager:jet # when running macOS Jet instead +yarn tests:android:build && yarn tests:android:test-cover +yarn tests:macos:pod:install +yarn tests:macos:build && yarn tests:macos:test-cover +``` + +## Fast iteration: test narrowing + +Full e2e loads every package. Narrow locally; **never commit** narrowing. + +| Kind | Mechanism | Scope | +| --- | --- | --- | +| **Area narrowing** | [`tests/harness.overrides.js`](#local-harness-overrides-harnessoverridesjs) | Which modules load (filter `platformSupportedModules` on all platforms) | +| **Sub-suite narrowing** | Temporary edit to `tests/app.js` (`require` one spec instead of `require.context`) | Which spec files load within a module — **unit-focused diagnosis only** | +| **Single-test narrowing** | `it.only(...)` | One case in a loaded file | +| **Single-suite narrowing** | `describe.only(...)` | One block in a loaded file | + +**Area narrowing** = overrides file for modules + `RNFBDebug`; not test-runner `--grep` or packager `--target`. + + + +### Local harness overrides (`harness.overrides.js`) + +**Canonical owner** for module narrowing and fail-fast debug. Package workflows name **which module/spec**; this section defines **how** to focus the harness without editing committed files. + +#### Setup + +```bash +cp tests/harness.overrides.example.js tests/harness.overrides.js +``` + +Edit `tests/harness.overrides.js` (gitignored — never commit). Shape: + +| Field | Purpose | +| --- | --- | +| `modules?: string[]` | After each platform block builds its list, filter to only these module names (works on macOS **and** iOS/Android — no dual-block edits) | +| `RNFBDebug?: boolean` | `true` = verbose RNFB logging + disabled test retries ([§ fail-fast](#fail-fast-rnfbdebug-and-sub-suite-narrowing)) | +| `e2eHelperSecret?: string` | Shared secret for live `fetchAppCheckTokenV2` ([§ macOS App Check helper secret](#macos-app-check-helper-secret)) | + +**Example — app package only, debug on:** + +```javascript +module.exports = { + RNFBDebug: true, + modules: ['app'], +}; +``` + +Omit a field or export `{}` to keep committed defaults for that field. + + + +#### macOS App Check helper secret + +macOS ("other") App Check **custom-provider** e2e calls live `fetchAppCheckTokenV2`, which requires `data.secret` matching Secret Manager `E2E_HELPER_SECRET`. Tests read `harnessOverrides.e2eHelperSecret` via `FirebaseHelpers.hasAppCheckHelperSecret()` / `fetchAppCheckToken()` in `tests/globals.js` and `this.skip()` when it is absent (same as fork CI without the GitHub secret). + +- **Local install:** fetch + merge commands — [agent command policy § App Check e2e helper secret](../commands/e2e.md#app-check-e2e-helper-secret) (merge preserves `modules` / `RNFBDebug`; never commit `harness.overrides.js`). +- **Secret Manager set / deploy / CI GitHub secret:** [firebase-testing-project § e2e cloud helper callables](../firebase-testing-project.md#e2e-cloud-helper-callables). +- **iOS / Android** App Check e2e use **debug tokens** and do **not** need `e2eHelperSecret`. + +#### How it works + +Committed [`tests/app.js`](../../../tests/app.js) still builds full `platformSupportedModules` per platform block. If `harness.overrides.js` exists, [`tests/globals.js`](../../../tests/globals.js) reads `RNFBDebug` and `tests/app.js` filters the module list **after** the platform block runs — so one overrides file applies on every platform. + +#### Spec loading (optional second narrowing) + +Module specs load in `loadTests()` via `platformSupportedModules.includes('')` — usually `require.context('../packages//e2e', …)`. + +| Goal | Change | +| --- | --- | +| Full package area | Overrides `modules` only — leave `require.context` as-is | +| Single spec file | **Temporarily** replace `require.context` for that module with `require('../packages//e2e/.e2e.js')` in `tests/app.js` — **never commit** ([sub-suite](#fail-fast-rnfbdebug-and-sub-suite-narrowing); unit-focused diagnosis only unless package workflow says otherwise) | + +#### Revert before `full` tier or commit + +1. Delete `tests/harness.overrides.js` or set `module.exports = {}`. +2. Revert any temporary `require.context` → single `require` edits in `tests/app.js`. +3. Remove all `.only` and native instrumentation. + +Do **not** revert durable product wiring in committed `tests/globals.js` (e.g. `NativeRNFBTurbo*` proxy routing — [NewArch-AD-13](../../new-architecture/architecture-decisions.md#newarch-ad-13--test-harness-committed-defaults--gitignored-local-overrides--accepted)). + +#### Sanity check by platform + +| Platform | Narrowed firestore-only (full `packages/firestore/e2e`) | Pipeline-only (`Pipeline.e2e.js`) | +| --- | --- | --- | +| macOS | ~**700** passing | ~**100** passing | +| iOS / Android | Same order of magnitude as macOS for the same spec scope | ~**100** passing | + +Pass counts in the **thousands** or unrelated suites (`database`, `crashlytics`, …) in the log → confirm overrides file exists with correct `modules` and re-run. + +**Area example:** `modules: ['app', 'firestore']` + full firestore specs via existing `require.context`. + +Package-specific spec names: [Firestore pipeline harness](../../packages/firestore/pipeline-implementation-workflow.md#pipeline-area-harness). Area narrowing otherwise: [§ local harness overrides](#local-harness-overrides-harnessoverridesjs). + + + +### Fail-fast (`RNFBDebug`) and sub-suite narrowing + +**`RNFBDebug`:** for **`unit-focused`** and **`area-focused`** tiers, set **`RNFBDebug: true`** in `tests/harness.overrides.js` **before the first `:test-cover`** — not optional. It prints per-case start/finish and **disables Mocha retry/backoff**, so failures surface immediately instead of burning time on retries. Committed `tests/globals.js` default stays `false`. Remove overrides (or set `RNFBDebug: false`) before **`full`** tier or commit ([§ before merge](gates.md#before-merge-pr-handoff)). + +| Kind | Mechanism | When | +| --- | --- | --- | +| **Sub-suite narrowing** | `describe.only` / `require` one e2e file (e.g. `Aggregate/count.e2e.js` only) | **Unit-focused diagnosis only** — after [pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start) is clean and the **same failure repeats** on back-to-back runs without assertion progress. Never for **`area-focused`** gate closure (no `.only`). Never commit. | +| **Single-test narrowing** | `it.only(...)` | Same as sub-suite — unit-focused diagnosis only | + +Package workflows may name default area specs (e.g. [Firestore pipeline harness](../../packages/firestore/pipeline-implementation-workflow.md#pipeline-area-harness)); sub-suite narrowing is **tighter** than area narrowing for iteration speed. + +**E2e diagnosis escalation** (cross-package): [change authoring § implementation inner loop](../authoring/implementation.md#e2e-diagnosis-escalation). + +Package workflows may further restrict narrowing per [validation tier](gates.md#e2e-validation-tiers-unit-focused--area-focused--full). diff --git a/okf-bundle/testing/e2e/platform-troubleshooting.md b/okf-bundle/testing/e2e/platform-troubleshooting.md new file mode 100644 index 0000000000..b42b678690 --- /dev/null +++ b/okf-bundle/testing/e2e/platform-troubleshooting.md @@ -0,0 +1,151 @@ +--- +type: Reference +title: 'E2e: platform troubleshooting' +description: 'Android emulator gray screen, Detox launch ANR / ABI mismatch, iOS Detox framework cache, and TurboModule stale toolchain.' +tags: [testing, e2e, android, ios, troubleshooting] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: platform troubleshooting + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + + + +### Android emulator gray screen / Quick Boot (blocking) + +Detox's default emulator launch **restores the AVD Quick Boot snapshot** unless told otherwise. On `TestingAVD` that can leave the device **`offline` on a gray screen** — `adb devices` shows `emulator-XXXX offline` and Detox hangs on `wait-for-device`. + +**Root cause:** warm boot paths — Quick Boot snapshot restore on Detox launch, and (pre-fix) `adb reboot` on Jet retry — skip a full cold boot. + +**Fix (committed):** [`tests/.detoxrc.js`](../../../tests/.detoxrc.js) sets `bootArgs: '-no-snapshot-load -no-snapshot-save'` on the `TestingAVD` device. Jet retry in [`tests/e2e/firebase.test.js`](../../../tests/e2e/firebase.test.js) cold-restarts the same emulator (kill + relaunch with the same args) instead of `adb reboot`. + +**Detect:** + +```bash +adb devices -l # emulator-XXXX offline +pgrep -fl "$(node -e "console.log(require('./tests/e2e/androidAdbRange').qemuAvdPgrepPattern('TestingAVD'))")" +rg 'SPAWN_CMD.*@TestingAVD' /tmp/rnfb-e2e-android.log # no -no-snapshot-load → stale runbook / config +``` + +**Recovery before `:test-cover`:** + +```bash +# Frees the emulator this checkout's run recorded (or one a recorded process spawned): +# adb -s emu kill once emu avd name matches, plus a signal to that exact qemu +# pid. Never a kill by AVD name; never restarts the shared adb server. +yarn tests:e2e:release --platform=android --devices +yarn tests:e2e:check --platform=android # must exit 0 +# If gray screen persists after cold-boot config, wipe Quick Boot snapshots: +# rm -rf ~/.android/avd/TestingAVD.avd/snapshots +``` + +`adb kill-server` disconnects every owner's emulators; run it only at explicit user direction ([manual machine wipe](preflight-host-clear.md#manual-machine-wipe)). + +Then rerun [pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start) and `yarn tests:android:test-cover`. Cold boot adds ~30–60s to the first Android launch vs Quick Boot — expected. + +**Local settle/load stays skipped** (not CI). Serial local runs log `android-ready: skipping settle/load (not CI)` then `launchApp complete`. Forcing local settle/load without that bar can fail in ~3s with Fabric `ReactContext is null!` while Metro prefetch succeeds. + +**Android `detoxEnableSynchronization` must be `0`.** Detox native `LaunchArgs.shouldDisableSynchronization()` is `enableSynchronization.equals("0")`. Passing `'NO'` still registers Fabric idling resources (`FabricDetoxIdlingResourceFactoryStrategy` → `getCurrentReactContextSafe`). Negative: `am instrument … -e detoxEnableSynchronization NO` then `ReactContext is null!` at that factory. Positive: launch args `'0'` so idling is not installed before RN has a context. `ReactContext is null` is also retryable at launch/Jet level. After FAIL, Detox Jest `forceExit: true` plus killing the yarn/jet process tree so `:test-cover` cannot hang on open handles. + +If Detox launches then ANRs (~6s) with logcat ABI mismatch, that is **not** this path — [Android Detox launch ANR](#android-detox-launch-anr-abi-mismatch). + + + +### Android Detox launch ANR / ABI mismatch + +Sibling of [gray screen / Quick Boot](#android-emulator-gray-screen--quick-boot-blocking) — different failure. Offline-emulator / Quick Boot snapshot recovery does **not** cover this path. Do **not** treat this as an AsyncStorage product failure (`NativeModule: AsyncStorage is null` is a Metro singleton issue — [pins § AsyncStorage](../test-app-dependency-pins.md#asyncstorage-dual-pin--metro-singleton)). + +**Detect:** `yarn tests:android:test-cover` Detox `am instrument` starts `com.invertase.testing`; ActivityManager **ANR ~6s**; instrumentation crashes. Logcat: `Package uses different ABI(s) than its instrumentation` (app `arm64-v8a`, test apk `null`). After FAIL, Jest prints `did not exit` and `:test-cover` **hangs until killed**. Metro Android bundle may still be HTTP 200. + +**Recovery:** + +1. Stop this run's hung `:test-cover` — the run will **not** self-exit. Stop the Shell that started it (or `kill` its exact pid). Do not `pkill -f` by command line: that matches other worktrees' runs. + +2. Then the same scoped teardown as gray-screen (emulator kill only — **not** snapshot wipe): + +```bash +yarn tests:e2e:release --platform=android --devices +yarn tests:e2e:check --platform=android # must exit 0 +``` + +3. Re-run [pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start) and `yarn tests:android:test-cover`. + +### iOS Detox framework cache + +Detox injects a prebuilt **`Detox.framework`** and XCUITest runner from a versioned cache under **`~/Library/Detox/ios/`** (hashed by Xcode version). iOS `:test-cover` / `:build` **fail before any test runs** if that cache is missing or stale (common after Xcode upgrade, first checkout, or a failed Detox postinstall). + +**Detect (from a failed iOS run log):** + +```bash +rg 'Detox\.framework could not be found' /tmp/rnfb-e2e-ios.log +``` + +Typical error (Detox prints the fix inline): + +```text +DetoxRuntimeError: .../Library/Detox/ios/framework//Detox.framework could not be found, +this means either you changed a version of Xcode or Detox postinstall script was unsuccessful. +To attempt a fix try running 'detox clean-framework-cache && detox build-framework-cache' +``` + +**Detect (proactive, before `:test-cover`):** + +```bash +test -d ~/Library/Detox/ios/framework/*/Detox.framework && echo "Detox framework cache: OK" || echo "Detox framework cache: MISSING" +``` + +**Fix (canonical — repo root):** + +```bash +yarn tests:ios:detox-framework-cache:rebuild +``` + +This runs Detox's `rebuild-framework-cache` (clean + build of both the injected Detox library and the XCUITest runner) from the `tests/` workspace. Expect ~10–30s on a warm machine; first build after Xcode change may take longer. + +**Verify cache present after rebuild:** + +```bash +ls ~/Library/Detox/ios/framework/*/Detox.framework +ls ~/Library/Detox/ios/xcuitest-runner/*/ +``` + +Then resume the iOS order in [Typical loop](narrowing.md#typical-loop). + +CI restores the same tree from `~/Library/Detox/ios` keyed by Xcode version ([iOS workflow § Detox Framework Cache Restore](../../ci-workflows/ios.md)). Local developers must rebuild when the cache is missing — it is not committed to git. + + + +### TurboModule migration — stale JS/native toolchain (blocking) + +During TurboModule work, three different **`undefined`** / load failures are easy to confuse: + +| Symptom | Likely cause | Fix (escalate in order) | +| --- | --- | --- | +| `this.native.isFoo` is **`undefined`** in JS | Spec/native **constants** chain incomplete (`getConstants`, `getTypedExportedConstants`, iOS typed constants) | [NewArch-AD-15](../../new-architecture/architecture-decisions.md#newarch-ad-15--constant-memoization-scope-static-only--accepted); spec must declare `getConstants` when JS reads native constants | +| Android `Proxy target must be an Object` | JNI not linked / **stale autolinking cache** | Delete `tests/android/build/generated/autolinking/autolinking.json` + `*.sha`, `:build` | +| Metro redbox **`Requiring unknown module "undefined"`** at app load | **Stale Metro and/or partial native refresh** after codegen / `lib/**` / podspec changes | Steps below; then [full refresh](#turbomodule-full-toolchain-refresh) if needed | + +**Detect:** app redbox before `Jet client connected`; `curl` of `index.bundle` may still return 200 — that does **not** rule out staleness. + +**Routine fix** (try first after codegen, podspec, or `packages/*/lib/**` edits): + +1. [Prepare completion gate](preflight.md#prepare-completion-gate-blocking) — `yarn lerna:prepare` exit 0. +2. Regenerate codegen if specs changed — [agent command policy § TurboModule codegen](../commands/native.md#turbomodule-codegen) (wipe configured `outputPath`, then package `android:codegen` / `ios:codegen`). +3. **`yarn tests::build`** — iOS and macOS **compile only**. Full e2e / test process **requires** `yarn tests:ios:pod:install` / `yarn tests:macos:pod:install` as a **separate prior step** before the matching `:build` (after codegen / podspec / native Apple changes). A bare `:build` without pod install is allowed when pods are already installed and you only need a compile. Android `:build` does not use CocoaPods. +4. Matching packager reset-cache (Metro was running during the edits) — [packager reset-cache](recovery.md#packager-reset-cache-eaddrinuse). +5. [Pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start) → **`yarn tests::test-cover`**. + + + +**Full toolchain refresh** — when the routine fix still shows `Requiring unknown module "undefined"` or you wiped `node_modules` mid-migration: + +1. [Pre-flight recovery](recovery.md#pre-flight-recovery) — stop Metro, Jet, Detox; scoped sim/AVD release via `yarn tests:e2e:release --devices` when needed. +2. Remove **all** `node_modules` (repo root, `tests/`, and under `packages/*` if present). +3. **`yarn`** at repo root (wait for exit 0 — includes `lerna:prepare`, root Gemfile gems via `yarn ruby:install`, and patches). +4. Confirm [install / patch / fmt gate](../commands/native-build-gate.md#install-patch-fmt-gate-blocking) (fmt **≥ 12.1.0**) before any native `:build`. +5. Regenerate **all** touched packages' codegen from `tests/` ([agent command policy § TurboModule codegen](../commands/native.md#turbomodule-codegen)). +6. **iOS/macOS:** `yarn tests::pod:install` then `yarn tests::build` as two commands (`:build` compiles only). Required after codegen / podspec / native Apple changes. A bare `:build` is allowed when pods are already installed. Android skips `pod:install`. +7. Matching packager reset-cache ([packager reset-cache](recovery.md#packager-reset-cache-eaddrinuse)) → pre-flight → `:test-cover`. + +Do **not** treat this redbox as a missing TurboModule registration until the refresh sequence has been run once on a clean tree. diff --git a/okf-bundle/testing/e2e/preflight-host-clear.md b/okf-bundle/testing/e2e/preflight-host-clear.md new file mode 100644 index 0000000000..f4c81a1ce7 --- /dev/null +++ b/okf-bundle/testing/e2e/preflight-host-clear.md @@ -0,0 +1,98 @@ +--- +type: Reference +title: 'E2e: pre-flight step 1, host clear' +description: 'Host-clear table, Android app reset, host-clear probes, run record, and manual machine wipe.' +tags: [testing, e2e, pre-flight] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: pre-flight step 1, host clear + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +#### 1. Host clear + +No in-flight test run on the target platform: + +| Platform | Clear when | +| --- | --- | +| **Android** | [Android app reset](#android-app-reset-blocking) + `yarn tests:e2e:check --platform=android` pass | +| **iOS** | `yarn tests:e2e:check --platform=ios` passes — the identity's own simulator (`iPhone 17` serial, or the slot base) is not booted and no stray listener is on `:8090`. Other booted simulators are reported as INFO and do not fail the check. Detox boots `iPhone 17` from `tests/.detoxrc.js`; do not pre-boot or leave it running. The `test-expo` / `test-rn-bare` `ios:launch-smoke` scripts boot their simulator (default `iPhone 18 Pro`) and do not shut it down; it is never recorded, so release leaves it alone, and it does not block this check (it is not the identity's device). Shutting it down is a human-operator step. Plain [host-clear probes](#host-clear-probes) without `--platform=ios` intentionally do **not** fail on an unrelated booted simulator — see [global device scoping](slotted-parallel.md#global-device-scoping). | +| **macOS** | [Host-clear probes](#host-clear-probes) pass (no macOS test app process — default `io.invertase.testing`, or `RNFB_MACOS_PRODUCT_NAME` when set) | + +Also wait for any visible unfinished `yarn tests:*:test-cover`. + +A Jet port that accepts loopback connections but has no listener `lsof` can attribute to this user (likely another user's server, such as a root service in a cloud guest image) is BUSY with `owner=unrecorded` in `yarn tests:e2e:check`; release cannot stop it, so free the port from its owner or use a free slot. `tests/e2e/firebase.test.js` likewise fails its pre-spawn Android Jet host-clear and its retry drain after about 2 s of such accepts, instead of waiting 30 s for the port to close. Neither treats a missing or unresponsive `lsof` as a foreign listener. + + + +**Android app reset (blocking)** — run **before every** Android `:test-cover`, not only after a failed run: + +```bash +ANDROID_SERIAL="${ANDROID_SERIAL:-emulator-5554}" +adb -s "$ANDROID_SERIAL" shell am force-stop com.invertase.testing +adb -s "$ANDROID_SERIAL" shell am force-stop com.invertase.testing.test +# Or via generic release (also clears Jet/Metro per env): +# yarn tests:e2e:release --only android-apps,jet +``` + +The main app (`com.invertase.testing`) can sit on **“waiting for jet to start tests…”** while the [host-clear probe](#host-clear-probes) still passes (it only checks `com.invertase.testing.test`). A stale main app then connects as a **second Jet client** after Detox launches a fresh run → `Received a message from the client, but server wasn't running` and no Mocha summary. Force-stop **both** packages, then re-run the probe. + +On **darwin** hosts, also clear the macOS test app before Android `:test-cover` when they share a Jet port (serial default `:8090`, or the same `JET_REMOTE_PORT` / platform Jet in slotted runs). Alternating macOS and Android without killing the macOS app leaves a stale macOS Jet client → duplicate clients and `server wasn't running`. + +```bash +MACOS_APP="${RNFB_MACOS_PRODUCT_NAME:-io.invertase.testing}" +! pgrep -x "$MACOS_APP" >/dev/null 2>&1 +# or: yarn tests:e2e:release --only macos-app,jet +# Release stops only the macOS app pid this checkout's run recorded (never killall by name). +``` + +(`firebase.test.js` runs this automatically via `ensureAndroidJetHostClear` before spawning Android Jet; use the probe manually when prepping from the runbook.) + + + +**Host-clear probes** — `yarn tests:e2e:check` / `yarn tests:e2e:release` (scripts under `scripts/e2e/`). They resolve [configurable e2e environment](environment.md#configurable-e2e-environment) first, else **serial defaults only**. **Exit 0 = clear.** Mellifera does **not** feed these commands a JSON file — it exports the same `RNFB_*` env, then calls these yarn targets ([e2e parallel design § layers](../e2e-parallel-design.md#rnfb-mellifera-tart-layers)). + +`yarn tests:e2e:check` **default** reports Jet + apps + simulators — not Metro/emulator ports (those are [services ready](preflight.md#2-services-ready)). Pass `--services` to treat Metro/emulator as BUSY. `--platform=android|ios|macos` scopes devices ([global device scoping](slotted-parallel.md#global-device-scoping)). Android host-clear also reports **stray `emulator-*` serials** (console ports outside serial **5554** and slotted **5556+2n**, e.g. Detox FreePortFinder **10000–20000** guests `emulator-16xxx`). A stray this checkout's run recorded, or that a recorded process spawned, is BUSY, and default `yarn tests:e2e:release --devices` frees it. A stray whose qemu runs from this checkout on **this identity's AVD** (`owner=this-checkout-unrecorded`, any port including FreePortFinder) is also BUSY — same as an allocated-serial cold-boot respawn — and default `--devices` stops it. Any other stray is INFO with its owner, qemu cwd and AVD: strays are host-global, so another owner's stray would otherwise fail every identity's check, and no slot move clears it. A stray on another identity's AVD that traces to this checkout stays INFO — stop it from the shell that started it, or manually with `yarn tests:e2e:release --include-unrecorded --devices --only android-emulator` in that identity's env. Only the manual `--all-slots` wipe stops another owner's stray. + +**Default (no args, no slot env):** serial ports/devices only. Do **not** wipe leftover `TestingAVD-N` / slot sims / slotted `12xxx` ports. Preferred slot scope is `eval "$(yarn tests:e2e:export-slot-env …)"` then check/release; direct `--slot=N` uses the same **0..effective max** guard and fails before probes or release. iOS device scope targets the exact neutral base name — [iOS slot simulators](slot-devices.md#ios-slot-simulators). + + + +**Run record (release scope).** An e2e run may only perturb what it started and works with. Each start records what it owns under `.e2e-run//` (override the base with `RNFB_E2E_RUN_RECORD_DIR`; git-ignored): Metro (`yarn tests:packager:*`), the Firebase emulator suite (`yarn tests:emulator:start`), the Jet listeners and macOS app (`:test-cover`), and the Android emulator / iOS simulator **instance** the run booted or worked with. Pids are recorded at spawn (Metro, the emulator suite, and Jet; on macOS, Jet records itself from `tests-macos/.jetrc.js` `before()`, before it opens its ports), so an interrupted start is still freed. Pid entries carry the process start time (`/proc` on Linux, `ps lstart` in `LC_ALL=C TZ=UTC` elsewhere) and are named per process instance, so a reused pid never counts. A listener counts as owned when it, or an ancestor, is a recorded pid. Device entries carry an instance token — the qemu pid + start time (Android, serial taken from qemu `-port`) or the `launchd_sim` pid + start time (iOS) — recorded at test start, after every harness reboot (the Android cold boot and iOS simulator reboot in both the `launchApp` retry and the Jet-attempt retry, even when the reboot throws), and when Detox setup booted the device but the test never started. The harness cold boot stops only this run's emulator — its recorded instance, or the qemu on its own console port that traces to this checkout, with `emu kill` sent only when one was selected and `emu avd name` matches — never by AVD name, so another owner's `-read-only` emulator on the same AVD (even on this console port) keeps running; it re-records only this checkout's qemu on the serial it spawned. An unrecorded emulator on the identity's AVD that traces to this checkout (`owner=this-checkout-unrecorded`, e.g. Detox/harness cold-boot respawn after the recorded qemu died) is BUSY, and default `yarn tests:e2e:release --devices` stops it — otherwise release/check could report CLEAR while `TestingAVD-N` / the slot serial stayed up. Another owner's emulator on the identity's own serial is BUSY instead (this run's Detox would attach to it), with its owner, cwd and the first free slot. Release leaves that foreign instance running and therefore exits non-zero; move the run to the named slot. Release acts on a recorded device only while that exact instance is alive; a device another owner has since rebooted is left alone, and the entry is pruned once its instance is gone. + +**Kill policy:** default `yarn tests:e2e:release` frees **recorded resources** — SIGTERM then SIGKILL of recorded listener PIDs on in-scope ports, `kill` of the recorded macOS app pid (never `killall` by name), `simctl shutdown ` of the recorded simulator instance, and with `--devices` `adb -s emu kill` (only once `emu avd name` matches) plus a signal to the recorded qemu pid, a qemu a recorded process spawned, or this checkout's unrecorded qemu on the identity's AVD (`owner=this-checkout-unrecorded`, cwd in this repo — cold-boot respawns). It never stops the shared adb server. Anything else on the identity's ports is another owner's: release prints `owner=… left running`, the holder's command and cwd, and exits non-zero if the port stays busy. No process-group / starter-shell assumptions. CI launch-smoke scripts (`test-expo` / `test-rn-bare` `ios:launch-smoke`) follow the same rule: they fail fast if their Metro port is held and stop only the Metro tree they spawned; `simulator-logging.sh` restarts only its own UDID's log streams unless on a single-tenant runner (`CI=true` or `RNFB_SIM_UI_RESET=1`). + +**Fail fast, never take over:** `yarn tests:e2e:check` annotates each busy port, app, and device with an owner. `owner=this-checkout` is recorded (release frees it). `owner=this-checkout-unrecorded` runs from this checkout but no run recorded it; for Metro/Jet/macOS/apps/non-identity devices check prints the exact manual command, e.g. `yarn tests:e2e:release --include-unrecorded --only metro`. For this identity's AVD qemu (any port), the BUSY line names default `yarn tests:e2e:release --devices` instead — that path does not need `--include-unrecorded`. `owner=unrecorded` is another owner: check names the first free slot (ports, `TestingAVD-N` qemu and slot simulator all idle) and the override `eval "$(yarn tests:e2e:export-slot-env N)"`. Move the run there, or free the holder from its owner. Scripts never pick a slot for you and never kill another owner. Harness fail-fast messages (Metro, Jet, macOS app) show the same owner, cwd, and hint. + +**One-time upgrade note.** Processes started before the run record existed (a Metro, emulator suite, or booted device from an older checkout of this branch) are unrecorded, so the first check after upgrading can report them `owner=this-checkout-unrecorded` (an emulator by its qemu cwd, which is under `tests/` when Detox booted it). An unrecorded qemu on **this identity's AVD** (allocated serial or FreePortFinder stray) is BUSY and default `yarn tests:e2e:release --devices` stops it; an unrecorded stray on another identity's AVD stays INFO. A simulator's `launchd_sim` is a child of launchd running from `/`, so an unrecorded simulator cannot be traced to a checkout and shows `owner=unrecorded`; shut it down yourself if it is yours (`xcrun simctl shutdown `). For ports/apps still needing the manual flag, run the printed `yarn tests:e2e:release --include-unrecorded --only ` once in that identity's env; later runs record what they start. + + + +**Manual machine wipe (explicit user direction only).** General scripts, `yarn test:full`, Mellifera, and CI never pass these flags: + +| Flag | Scope | +| --- | --- | +| `--include-unrecorded` | Also kill unrecorded holders on **this identity's** ports and the macOS app by name, and force-stop the test apps on the configured serial when that emulator traces to this checkout. With `--devices`, default release already stops this checkout's unrecorded emulator on the identity's AVD; this flag still covers that path plus other unrecorded device holders and the identity's simulator when it traces to this checkout. Another owner's device and its apps are reported and left running. | +| `--all-slots` (implies the above) | Whole machine through **effective max** (default/cap **7**; [slot index](environment.md#e2e-slot-index)): every slot's ports, `TestingAVD-N`, slot sims, macOS `.sN`, plus stray `emulator-*` serials. It kills other owners' live runs, so only use it when the user says the machine is theirs. | + +```bash +yarn tests:e2e:check +yarn tests:e2e:check --services +yarn tests:e2e:check --platform=ios +yarn tests:e2e:release +# yarn tests:e2e:release --only jet,android-apps +# yarn tests:e2e:release --devices +# Manual, explicit user direction only (kills every owner): +# yarn tests:e2e:release --all-slots --devices +``` + +Manual one-liners (defaults only — use when debugging without the scripts): + +```bash +JET_PORT="${JET_REMOTE_PORT:-${RNFB_ANDROID_JET_PORT:-${RNFB_IOS_JET_PORT:-${RNFB_MACOS_JET_PORT:-8090}}}}" +test -z "$(lsof -nP -iTCP:${JET_PORT} -sTCP:LISTEN -t 2>/dev/null || true)" +ANDROID_SERIAL="${ANDROID_SERIAL:-emulator-5554}" +! adb -s "$ANDROID_SERIAL" shell pidof com.invertase.testing.test >/dev/null 2>&1 +! pgrep -x "${RNFB_MACOS_PRODUCT_NAME:-io.invertase.testing}" >/dev/null 2>&1 +``` diff --git a/okf-bundle/testing/e2e/preflight.md b/okf-bundle/testing/e2e/preflight.md new file mode 100644 index 0000000000..38690d2278 --- /dev/null +++ b/okf-bundle/testing/e2e/preflight.md @@ -0,0 +1,90 @@ +--- +type: Reference +title: 'E2e: pre-flight' +description: 'Pre-flight steps before every :test-cover: prepare complete, services ready, checkout ownership, and harness tier. Host-clear detail is a separate file.' +tags: [testing, e2e, pre-flight] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: pre-flight + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +### Pre-flight: is the host clear to start? + +**Canonical owner** for host-clear probes, recovery after abort, and service checks. Other OKF docs link here by reference — do not duplicate commands or probes elsewhere. + +Run **all four** steps before every `:test-cover`. After an [interrupted run](recovery.md#interrupted-run-abort-killed-terminal-eaddrinuse-on-8090), run [pre-flight recovery](recovery.md#pre-flight-recovery) and re-run the probes. + + + +#### 0. Prepare complete (when `packages/*/lib/**` changed) + +If product code under `packages/*/lib/**` was edited in this session, **`yarn lerna:prepare`** (or scoped `yarn lerna run prepare --scope …`) must have **fully finished with exit code 0** before pre-flight steps 1–3 or any `:test-cover` / `:build`. + +- **Wait** for the prepare shell to return — do not batch prepare in parallel with Metro restart, pre-flight probes, or e2e in the same agent turn. +- **Then** restart Metro when it was already running: [packager reset-cache](recovery.md#packager-reset-cache-eaddrinuse) (matching iOS/Android vs macOS packager — not interchangeable). +- **Then** continue with host-clear probes and service checks below. + +Skipping this gate causes missing or half-written `dist/module/**` while Metro `/status` still returns 200 — a common source of bundle-load and module-not-found failures that look like product bugs. + +Owner for install/prepare serialization: [agent command policy § prepare must finish first](../commands/core.md#prepare-must-finish-first). + +**Stale install after a merge or pull (blocking).** A merge or pull that changes React Native or native dependency versions (or the Apple app lifecycle) leaves `node_modules`, `tests/ios/Pods`, and the native builds on the old version. Symptom: `:test-cover` fails before any Mocha test runs (iOS app killed shortly after launch, `NoSceneLifecycleAdoption` / `AppWillTerminateWithError` / `waitForActive`; Android `No instrumentation runner found` after a cold boot). Treat this as a stale install first, not a host, Simulator, or Metro fault. Re-run the [install / patch / fmt gate](../commands/native-build-gate.md#install-patch-fmt-gate-blocking) (root `yarn`), then `yarn tests:ios:pod:install` (if it fails on stale Pods or hermes-engine podspec drift, delete the gitignored `tests/ios/Pods` and re-run it), then `yarn tests:ios:build` / `yarn tests:android:build`, then one `:test-cover` per platform. + +#### 2. Services ready + +Metro and emulators must be **running and responsive** — do not assume from a prior session or background start. This is the **opposite** of [host-clear](preflight-host-clear.md#host-clear-probes) (clear = nothing listening; ready = packager/emulators up). + +```bash +METRO_PORT="${RCT_METRO_PORT:-${RNFB_METRO_PORT:-8081}}" +FIRESTORE_PORT="${RNFB_ANDROID_EMULATOR_FIRESTORE_PORT:-${RNFB_IOS_EMULATOR_FIRESTORE_PORT:-${RNFB_MACOS_EMULATOR_FIRESTORE_PORT:-8080}}}" +FUNCTIONS_PORT="${RNFB_ANDROID_EMULATOR_FUNCTIONS_PORT:-${RNFB_IOS_EMULATOR_FUNCTIONS_PORT:-${RNFB_MACOS_EMULATOR_FUNCTIONS_PORT:-5001}}}" +curl -sf "http://127.0.0.1:${METRO_PORT}/status" +curl -sf "http://127.0.0.1:${FIRESTORE_PORT}" >/dev/null +test -n "$(lsof -nP -iTCP:${FUNCTIONS_PORT} -sTCP:LISTEN -t 2>/dev/null || true)" # Functions emulator — listener only +``` + +**Metro alive or dead (blocking, last check before `:test-cover`).** Run the Metro `curl` again after `:build` and read the body. Do not discard it. **Alive:** body contains `packager-status:running`. **Dead:** `curl` fails, or the body does not contain that string. A port listener with any other HTTP success is dead. If dead, start `yarn tests:packager:jet` (iOS/Android) or `yarn tests:macos:packager:jet` (macOS) again and require alive. Do not start `:test-cover` while Metro is dead. Metro can pass this check before `:build` and be dead after it. Slotted android∥ios may share one `tests/` root on distinct ports (sibling-safe `watch-del`); re-start only the dead port. + +If Metro or Firestore checks fail: start `yarn tests:packager:jet` (iOS/Android) or `yarn tests:macos:packager:jet` (macOS) and `yarn tests:emulator:start` (background) from **this checkout's repo root**; re-check until both pass. After **`yarn lerna:prepare` has finished** (step [0](#prepare-completion-gate-blocking)) or test-runner patch edits, restart the packager via [packager start](recovery.md#packager-reset-cache-eaddrinuse) — never restart Metro while prepare is still running. + +A listener on the Metro/Firestore ports (or Functions) alone is **not** sufficient for Metro/Firestore — their HTTP checks must succeed. **Functions:** verify the listener is up; `curl -sf` of the Functions root path exits non-zero (**404**) — expected, not a service failure. + +`yarn tests:emulator:start` honors the active platform’s `RNFB_*_EMULATOR_*` ports (serial `firebase.json` defaults when unset), including Firebase Tools aux binds (websocket / eventarc / tasks). Ready-check uses **those** ports, never a hardcoded `:8080` / `:5001`. Interactive `--no-daemon` may stay foreground; CI / background callers wait until the suite is ready then return — same implementation, two invocation modes. + + + +**Checkout ownership (blocking on multi-worktree hosts)** — HTTP/port checks can pass while Metro or Firebase emulators belong to a **different** RNFB worktree (shared `:8081` / `:8080` / `:5001` / `:9099`). That is **not** services-ready for this checkout. + +After the curls above succeed, verify listener **cwd** paths are under **this** repo root (`$REPO_ROOT`): + +```bash +# REPO_ROOT = absolute path to this worktree (pwd at monorepo root) +listen_cwd() { # usage: listen_cwd + local pid + pid="$(lsof -nP -iTCP:"$1" -sTCP:LISTEN -t 2>/dev/null | head -1)" + test -n "$pid" || return 1 + lsof -a -p "$pid" -d cwd 2>/dev/null | awk '/cwd/ {print $NF; exit}' +} +metro_cwd="$(listen_cwd 8081)" +fs_cwd="$(listen_cwd 8080)" +case "$metro_cwd" in "$REPO_ROOT"|"$REPO_ROOT"/*) ;; *) echo "Metro cwd not this checkout: $metro_cwd"; false ;; esac +case "$fs_cwd" in "$REPO_ROOT"|"$REPO_ROOT"/*) ;; *) echo "Firestore emulator cwd not this checkout: $fs_cwd"; false ;; esac +``` + +Expected shapes when started via this checkout's `yarn tests:*`: Metro cwd ends with `/tests` (iOS/Android packager) or `/tests-macos` (macOS packager); Firestore/Auth/Functions cwd ends with `/.github/workflows/scripts`. A full parallel slot that runs android/ios **and** macos has **three** Metro listeners (android + ios share `tests/` on distinct ports; macos on `tests-macos/`) — verify **each**. Two `tests/` Metros are OK because packager start **skips** `watch-del` when a sibling owns that root ([packager start](recovery.md#packager-reset-cache-eaddrinuse)). If ownership fails: stop the foreign listeners (or finish that worktree's run), then start `yarn tests:packager:jet` and/or `yarn tests:macos:packager:jet` plus `yarn tests:emulator:start` from **this** `$REPO_ROOT` and re-check curls **and** cwd. Do not proceed to `:test-cover` on a foreign-owned stack. + +#### 3. Harness matches validation tier + +Confirm local harness overrides (or committed files for **full** tier only) match the item's **`validation_tier`** ([iteration vocabulary](../iteration-vocabulary.md#work-queue-fields)), **not** the branch's committed harness alone. + +| Tier | Harness before `:test-cover` | +| --- | --- | +| **Unit-focused** (`implementation`) | **Area narrowing required** — [`tests/harness.overrides.js`](narrowing.md#local-harness-overrides-harnessoverridesjs) with `modules` + `RNFBDebug: true`; `.only` OK locally. | +| **Area-focused** (`independent-review`, `baseline-capture`) | **Area narrowing required** — same overrides file; load **full** spec file(s) for the package area; **no** `.only`; `RNFBDebug: true`. | +| **Full** (`pre-merge-validation`) | **No** `harness.overrides.js` (delete or `{}`); full app in committed `tests/app.js`; `RNFBDebug: false`. | + +Committed full harness on the branch does **not** override **unit-focused** or **area-focused** tier for local runs. Package workflows define **which module/spec** (e.g. [pipelines § area harness](../../packages/firestore/pipeline-implementation-workflow.md#pipeline-area-harness)). **How:** [local harness overrides](narrowing.md#local-harness-overrides-harnessoverridesjs). Never commit `harness.overrides.js`. + +See [Harness narrowing gate (blocking)](gates.md#harness-narrowing-gate-blocking) — a run that skips step 3 does **not** close `implementation_gate` or `review_gate`. diff --git a/okf-bundle/testing/e2e/prerequisites.md b/okf-bundle/testing/e2e/prerequisites.md new file mode 100644 index 0000000000..51253386d7 --- /dev/null +++ b/okf-bundle/testing/e2e/prerequisites.md @@ -0,0 +1,48 @@ +--- +type: Reference +title: 'E2e: prerequisites and Apple host toolchain' +description: 'Once-per-checkout e2e prerequisites, Apple host toolchain expectations, and physical device signing.' +tags: [testing, e2e, ios, setup] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: prerequisites and Apple host toolchain + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Prerequisites (once per checkout) + +```bash +yarn # repo root — exit 0 required. Applies .yarn/patches (jet, mocha-remote-*, detox) and tests/tests-macos patch-package (incl. tests/patches/detox+20.51.0.patch) — [install / patch / fmt gate](../commands/native-build-gate.md#install-patch-fmt-gate-blocking) +``` + +**Ruby `>= 3.3.1` with Bundler on `PATH`** for iOS and macOS work (CocoaPods and `yarn tests:ios:ruby`). macOS's system Ruby 2.6 is too old; root `yarn` then skips the gems with one `ruby:install:` line and still exits 0. Setup: [CONTRIBUTING § Ruby for iOS and macOS work](../../../CONTRIBUTING.md#ruby-for-ios-and-macos-work). + +**Before `yarn tests:ios:build` / `yarn tests:android:build`:** [install / patch / fmt gate](../commands/native-build-gate.md#install-patch-fmt-gate-blocking) (root `yarn` exit 0 + fmt **≥ 12.1.0**). + +**Keep host toolchains current.** Android Studio / emulator and Xcode / CocoaPods are expected to track upstream, not be pinned indefinitely. A stale Android Emulator (e.g. 36.2.12.0) can lack CLI flags newer Detox patches rely on (`-crash-report-mode`, requires **≥ 37**, see [detox-patches.md](../../ci-workflows/detox-patches.md)) and fail at spawn rather than at test time. When a patch or e2e step breaks only on your host, update the toolchain first — don't reach for a runtime capability probe as the default fix. + +**JDK 21+ on `PATH`** for `yarn tests:emulator:start`: `firebase-tools` refuses older Java (`firebase-tools no longer supports Java version before 21`). Same host fix as [`yarn lint:android` § needs JDK 21+](../commands/native.md#android-java-format). + + + +### Apple host toolchain (local) + +Align the Mac with [iOS CI workflows § Apple CI toolchain](../../ci-workflows/ios.md#apple-ci-toolchain-xcode-27) and [test app dependency pins](../test-app-dependency-pins.md#current-pins): + +| Expectation | Local default | +| --- | --- | +| **Xcode** | **27** stable (beta fails CI gate; match `xcodebuild -version` major to CI) | +| **iOS Simulator runtime** | **`iOS 27.0`** — export `RNFB_IOS_SIM_RUNTIME` if your install uses a different label; `yarn tests:e2e:setup-ios-sims` creates devices on that runtime | +| **Simulator device type** | **`iPhone 17`** (serial device and slot base). If the runtime does not support it (`simctl create` fails `Incompatible device`), export `RNFB_IOS_BASE_SIMULATOR` to a device type that runtime lists as supported, for setup and the Detox run alike | +| **`xcbeautify`** | Required on `PATH`: Detox iOS `build` pipes `xcodebuild` through it (`xcbeautify: command not found` otherwise). CI version/install: [iOS CI § pinned Homebrew utilities](../../ci-workflows/ios.md#pinned-homebrew-utilities) | +| **Simulator UI** | **Device Hub** from the selected Xcode bundle (`…/Applications/DeviceHub.app`). Do not use `open -a Simulator` / `open -a Device Hub` for CI-parity boot paths — see [iOS CI § simulator reliability](../../ci-workflows/ios.md#simulator-reliability) | +| **Mobile e2e fixtures** | **RN 0.88.0-rc.3**, **Expo 58** (`test-expo/`), same RN line in `tests/` / `test-rn-bare/` — test-fixture pins only; do not document higher consumer Xcode/RN floors than product metadata | + +**iOS 26.5** simulators or hosts are **runtime-differential context only** (e.g. Metro hostname quirks in [iOS CI § issue 5](../../ci-workflows/ios.md#5-metro-unresponsive-at-launch--waitforactive-hang-active-app)). They do **not** replace **iOS 27** for UIScene launch-smoke gates or Xcode 27 closure — [local Tart lab § not proof](../local-ios-e2e-reproduction.md#ios-26-5-not-proof). + + + +**Physical iOS device builds need the Invertase Apple team.** `tests/ios/testing.xcodeproj` uses automatic signing with `DEVELOPMENT_TEAM = YYX2P3XVJ7` and paid-team entitlements (push, Sign in with Apple, associated domains, keychain group), so a device build on a host without that team fails with `No Account for Team "YYX2P3XVJ7"` / `No profiles for 'io.invertase.testing' were found`. Simulators are unaffected. Options: add an Apple ID that belongs to team `YYX2P3XVJ7` in Xcode → Settings → Accounts, or apply a local-only, never-committed bundle-id/team override (needs a matching `GoogleService-Info.plist` and stripped entitlements). Physical-device runs: [agent command policy § physical-device runs](../commands/core.md#physical-device-runs). + +**Tart VM lab** (`scripts/tart/`) is [temporarily suspended](../local-ios-e2e-reproduction.md#status-suspended); use this runbook, not `run-ephemeral.sh`, for contributor e2e. diff --git a/okf-bundle/testing/e2e/recovery.md b/okf-bundle/testing/e2e/recovery.md new file mode 100644 index 0000000000..328c34cfcd --- /dev/null +++ b/okf-bundle/testing/e2e/recovery.md @@ -0,0 +1,111 @@ +--- +type: Reference +title: 'E2e: recovery and diagnosis' +description: 'Pre-flight recovery, packager start and reset-cache, stalled run detection, interrupted runs, and diagnosing hangs.' +tags: [testing, e2e, recovery] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: recovery and diagnosis + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + + + +**Pre-flight recovery (serial)** — when probes fail **after** [Android app reset](preflight-host-clear.md#android-app-reset-blocking), abort, kill, or `EADDRINUSE` on the Jet port. Canonical recovery uses the env-aware scripts below. `EADDRINUSE` on **`:8081`** (or a slotted Metro port) during packager restart is a different path — [packager reset-cache](#packager-reset-cache-eaddrinuse) (this block does **not** free Metro). + +```bash +yarn tests:e2e:release +# If AVD/sim must go down too: +yarn tests:e2e:release --devices +yarn tests:e2e:check # must exit 0 +``` + +If release reports `owner=unrecorded`, another owner holds the identity: move to the free slot that check names. Do not reach for the [manual machine wipe](preflight-host-clear.md#manual-machine-wipe) unless the user directs it. + +**Functions build lock.** `yarn tests:emulator:start` takes `.github/workflows/scripts/functions/.build.lock.d` while the functions package builds. A killed start used to leave that directory behind, and the next start waited 300s. A lock whose holder pid is gone is removed automatically. `yarn tests:e2e:release` does not clear it. If a start still fails with `timed out waiting for functions build lock` and no emulator start is running: + +```bash +rm -rf .github/workflows/scripts/functions/.build.lock.d +``` + +Do **not** use `boot-simulator.sh` or `simctl shutdown all` as routine prep ([what not to do](rules.md#what-not-to-do)). + + + +**Packager start** — `yarn tests:packager:jet` / `jet-reset-cache` (and macOS variants). Honor `RCT_METRO_PORT`. Kill this checkout's **recorded** listener on that port (SIGTERM then SIGKILL — [run record](preflight-host-clear.md#run-record)), then start clean and record the new Metro. If a listener this checkout did not record still holds the port, fail fast naming its pid and the slot override — another worktree's live Metro is never killed. On a host with other RNFB worktrees, load the [slot env](environment.md#slot-lifecycle) before the first packager/emulator start. Metro's `TMPDIR` (its cache) is per listen port: `${RNFB_METRO_CACHE_ROOT:-$HOME/.metro}/rnfb-${RCT_METRO_PORT}`. The Metro log defaults to the caller's `${TMPDIR:-/tmp}/rnfb-metro-${RCT_METRO_PORT}.log` (`RNFB_METRO_LOG` overrides), read before `TMPDIR` is repointed at the cache. Wait until `http://127.0.0.1:${RCT_METRO_PORT}/status` contains `packager-status:running` (long documented timeout), then succeed or **fail** — no hidden restart inside `:test-cover`. Before start, **conditionally** `watchman watch-del` for **this Metro project root** (skip when a sibling Metro already owns that root — see below), then always `watch-project` the allowlist trees Metro would reload — not the whole monorepo plus native `*/build`. Never `watch-del` the repo root. Hard Watchman reset when alone, or with `RNFB_METRO_FORCE_WATCHMAN_RESET=1` when no sibling must survive. + +**Slotted dual `tests/` packagers:** `yarn test:full --slot N` (and manual android∥ios) starts **two** `yarn tests:packager:jet` processes against the same `tests/` root on distinct `RCT_METRO_PORT` values, plus macOS on `tests-macos/` — **three** Metros total. After killing **this** port only, `scripts/e2e/start-packager.sh` **skips** `watchman watch-del` when a sibling Metro already owns `$METRO_ROOT`: a live process with Metro/react-native cmdline and cwd equal to that root (LISTEN not required — covers cold dual-start before either port binds). Emulator listeners (qemu/netsimd) with cwd under `tests/` do **not** count. Always runs the `watch-project` allowlist; never `watch-del` the repo root. Force a hard reset only with `RNFB_METRO_FORCE_WATCHMAN_RESET=1` when no sibling must survive. Same-platform parallel still needs separate worktrees ([parallel topology](environment.md#parallel-e2e-topology)). + + + +**Packager restart (`jet-reset-cache`)** — same kill-then-start as above (port from env, default `:8081`). Matching packager only — iOS/Android (`tests/`) vs macOS (`tests-macos/`); not interchangeable. + +```bash +yarn tests:packager:jet-reset-cache +# yarn tests:macos:packager:jet-reset-cache +``` + +### Stalled run detection + +See also [startup fail-fast poll](startup-fail-fast.md#startup-fail-fast-poll) (check immediately for launch-fail markers; do not wait this 5-minute window first). + +Completion = shell exit code + log markers — not open-ended log tailing. + +| Platform | Early markers (≈2–3 min) | Done | +| --- | --- | --- | +| **macOS** | `Jet client connected` | Jest `N passing` / `N failing`, preferably **and** `[jet-coverage] merged … before NYC shutdown` | +| **iOS/Android** | Detox launch done, `Jet client connected` | Same | + +`✨ Tests Complete ✨` is **optional** if present — it is not always emitted on local macOS runs; treat it as a bonus signal, never a required one. + +**If stalled** — no new markers for **5 minutes**, or past tier budget (~15m macOS, ~45–60m iOS/Android) without a Jest summary (`N passing`/`N failing`) or `[jet-coverage] merged … before NYC shutdown`: treat as [interrupted run](#interrupted-run-abort-killed-terminal-eaddrinuse-on-8090). Do not gate the stall decision on emoji `Tests Complete` alone. Run [pre-flight recovery](#pre-flight-recovery), confirm [host-clear probes](preflight-host-clear.md#host-clear-probes) and [services ready](preflight.md#2-services-ready), retry. Do not keep watching flat tee output. Launch-time failures are [startup fail-fast poll](startup-fail-fast.md#startup-fail-fast-poll), not this window. + +Android `:test-cover` that **FAIL**s then Jest `did not exit` is a hang, not a stall to wait out — kill hung yarn/jest/detox PIDs, then [Android Detox launch ANR](platform-troubleshooting.md#android-detox-launch-anr-abi-mismatch) if logcat showed ANR / ABI mismatch, otherwise [interrupted run](#interrupted-run-abort-killed-terminal-eaddrinuse-on-8090). + +- macOS bundle/Metro hangs → [ci-workflows/other.md § bundle load hang](../../ci-workflows/other.md#ci-failure-bundle-load-hang--could-not-connect-to-development-server) +- iOS Metro at launch → [ci-workflows/ios.md § Metro unresponsive](../../ci-workflows/ios.md) + +Do not poll `pgrep`, process names, or `:8090` for _completion_ ([above](run-loop.md#how-a-platform-run-is-structured-androidios)). Stall detection uses **missing progress markers**, not exit polling. + +### Interrupted run (abort, killed terminal, EADDRINUSE on :8090) + +**Serial recovery.** Check the log before recovering. After a STOP/abort or a Shell tool interruption that leaves the exit status unknown, read the `/tmp/rnfb-e2e-.log` footer **first** — before `pkill`, [pre-flight recovery](#pre-flight-recovery), or any other kill/recovery step: + +```bash +rg '^\s*\d+ (passing|failing)' /tmp/rnfb-e2e-.log | tail -2 +rg 'jet-coverage.*merged .* before NYC' /tmp/rnfb-e2e-.log | tail -1 +``` + +- **Done footers present** (Jest `N passing`/`N failing`, preferably with `[jet-coverage] merged … before NYC shutdown`) → treat the run as **complete**. Record pass/fail from the log; report exit as `unknown (tool aborted); log footer green|red` — do not conclude failure or incomplete just because the Shell tool gave no exit status. +- **Log shows incomplete or stalled** (no done footers, matches [stalled run detection](#stalled-run-detection)) → only then run [pre-flight recovery](#pre-flight-recovery), confirm [host-clear probes](preflight-host-clear.md#host-clear-probes) pass, then rerun from repo root: `yarn tests::build && yarn tests::test-cover` (foreground; tee if logging). Keep one `:test-cover` active at a time on a host. + + + +#### macOS: done footer green but `tee`/shell never returns + +**Failure mode (fixed):** the Jest summary and `[jet-coverage] merged … before NYC shutdown` footer print, but the foreground `| tee /tmp/rnfb-e2e-macos*.log` shell never exits — Agent Shell looks idle/hung forever. Root cause was spawning `io.invertase.testing` with `stdio: ['ignore', 'inherit', 'inherit']`: the app inherited the write end of the tee pipe, so the pipe never saw EOF even after the suite finished. Fixed by detaching macOS app stdio (`stdio: ['ignore', 'ignore', 'ignore']`) and hardening `killMacOsTestApp()` (soft kill → wait → SIGKILL → verify, on the pids this run spawned and recorded only) in [`tests-macos/.jetrc.js`](../../../tests-macos/.jetrc.js). + +If this recurs: `yarn tests:e2e:release --only macos-app` in the run's slot env stops the recorded app pid so the tee pipe can close (`pgrep -x "$RNFB_MACOS_PRODUCT_NAME"` shows whether it is still alive); the anchored log footer ([done footers](#stalled-run-detection)) is still the authoritative completion signal, not the shell exit code alone. The recommended tee command (`yarn tests:macos:test-cover 2>&1 | tee /tmp/rnfb-e2e-macos.log` — [running one iteration](run-loop.md#running-one-iteration)) is unchanged by this fix. + +`:test-cover` FAIL followed by Jest `did not exit` will **not** self-exit — kill the hung yarn/jest/detox PIDs, then recover. If Android logcat showed ANR / `Package uses different ABI(s) than its instrumentation`, use [Android Detox launch ANR](platform-troubleshooting.md#android-detox-launch-anr-abi-mismatch) (not gray-screen snapshot wipe alone). Packager `EADDRINUSE` on `:8081` is [packager reset-cache](#packager-reset-cache-eaddrinuse), not this `:8090` block. + +## Diagnosing hangs + +**Local stalls** — see [stalled run detection](#stalled-run-detection) first (Metro `/status`, `Jet client connected` markers). + +**Native / device logs** (remove instrumentation before merge): + +- **macOS** — `log show --predicate 'process == "io.invertase.testing"' --last 10m --style compact`; filter `com.facebook.react.log:javascript` for bundle errors. **Blank window / Jet never connects:** often `Native module NativeRNFBTurboApp is not registered` — [NewArch-AD-2](../../new-architecture/architecture-decisions.md#newarch-ad-2--naming-nativernfbturbo--accepted) (web/macOS registry must include turbo keys). Other bundle errors → [other.md](../../ci-workflows/other.md) +- **iOS** — `xcrun simctl spawn booted log stream --level debug --style compact --predicate 'process == "testing"'`; silent hangs: `sample ` on `testing`. Metro redbox **`Requiring unknown module "undefined"`** → [TurboModule stale toolchain](platform-troubleshooting.md#turbomodule-stale-toolchain-blocking). +- **Android** — `adb logcat` (filter your tags) + +**Crashlytics on-disk report inspection (iOS / Android):** + +- **iOS** — pending reports live under the app container's `Library/Caches/com.crashlytics.data//v5/reports/active//` (`custom_exception_{a,b}.clsrecord`, `user_incremental_kv.clsrecord`). String fields such as the exception `reason` are **hex-encoded**, so a plain-text grep for the error message gives false negatives — hex-decode, or also match the hex form (e.g. `printf '%s' "$MSG" | xxd -p | tr -d '\n'`). The SDK processes and removes `active/` reports on the next app launch, so inspect before relaunching. +- **Android** — pending events are **plain JSON** at `files/.crashlytics.v3//open-sessions//event<10 digits>`, with custom keys in that session's `keys` file. The next launch — including a background restart by datatransport `JobInfoSchedulerService` — can finalize sessions into `reports/`, so inspect before any relaunch and diff the whole `.crashlytics.v3/` tree rather than one path. +- **Android `run-as` access** — `adb shell run-as com.invertase.testing` needs a debuggable APK. Making the `tests/android` release build debuggable (to keep the embedded JS bundle without Metro) flips `BuildConfig.DEBUG`, which enables React Native developer support and makes the app expect Metro; also override `getUseDeveloperSupport()` → `false` in `tests/android` `MainApplication`. Both changes are local-only and never committed. Physical-device runs: [agent command policy § physical-device runs](../commands/core.md#physical-device-runs). + +**Benign noise:** iOS Detox `EXEC_FAIL "xcrun simctl terminate … io.invertase.testing" … found nothing to terminate` — app wasn't running; ignore. + +**Cloud API pressure** — Installations / Remote Config failures with FIS 503 or “Too many server requests” are live-project quota on **any** platform, not emulator issues. See [Firebase testing project — CI triage](../firebase-testing-project.md#ci-triage-cloud-api-quota-pressure). diff --git a/okf-bundle/testing/e2e/rules.md b/okf-bundle/testing/e2e/rules.md new file mode 100644 index 0000000000..fb6d4f1cc2 --- /dev/null +++ b/okf-bundle/testing/e2e/rules.md @@ -0,0 +1,120 @@ +--- +type: Reference +title: 'E2e: rules' +description: 'Canonical e2e command rules (packager, emulators, rebuild, coverage), test-app native modules, infrastructure change bar, and what not to do.' +tags: [testing, e2e, rules] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: rules + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Rules + +1. **Packager** (background): + +```bash +# iOS / Android +yarn tests:packager:jet + +# macOS (Metro from tests-macos/, shared JS harness under tests/) +yarn tests:macos:packager:jet +``` + +Do **not** use the mobile packager for macOS Jet (or vice versa): each app has its own Metro project root after the `tests-macos/` split. + + + +**Backgrounding (agents):** a trailing `&` inside a single shell call does **not** survive that call returning — the command prints a PID and the process is gone (observed twice with `yarn tests:macos:packager:jet`: one `watchman watch-del` line in the log, nothing listening on `:8081`). Start the packager as a properly backgrounded long-running job instead. The packager script **exits 0 after daemonizing Metro**, so a *completed* job is the success case, not a crash — confirm with the `/status` check in [services ready](preflight.md#2-services-ready) rather than restarting it. + +2. **Emulators** (background, always): + +```bash +yarn tests:emulator:start +``` + +3. **Rebuild when needed** + - **Before any native `:build`:** [install / patch / fmt gate](../commands/native-build-gate.md#install-patch-fmt-gate-blocking) — root `yarn` exit 0 + fmt podspec **≥ 12.1.0**. Missing this gate → Apple Clang 21 consteval failures on unpatched fmt **11.0.2**. + - Native changed → `yarn tests:ios:build` / `yarn tests:android:build` before e2e. macOS uses firebase-js-sdk only — no native rebuild. + - **Apple `:build` compiles only.** `yarn tests:ios:build` / `yarn tests:macos:build` do not run CocoaPods. Full e2e / test process **requires** `yarn tests:ios:pod:install` or `yarn tests:macos:pod:install` as a **separate prior step** before the matching `:build` (after codegen / podspec / native Apple changes, and in [slot lifecycle](environment.md#slot-lifecycle) / `run-full-tests.sh` / CI). A bare `:build` without pod install is allowed when pods are already installed and you only need a compile. + - **Committed codegen / generated native artifacts count as native** — any change under `packages/*/ios/generated/**` or `packages/*/android/**/generated/**` (including wipe-then-regen orphan deletions), or TurboModule **codegen / spec / podspec / native shell**, is a native change: rebuild + [platform coverage](gates.md#platform-coverage-gate-blocking) e2e on iOS and Android. **`yarn codegen:verify` is not a substitute** for `:test-cover` ([change authoring § forbidden shortcuts](../authoring/gates.md#forbidden-shortcuts)). + - `packages/*/lib/**` changed → **`yarn lerna:prepare` must run to completion (exit 0) before anything else** — Metro serves `dist/module/**`, not `lib/**`. See [prepare completion gate](preflight.md#prepare-completion-gate-blocking) and [agent command policy § prepare must finish first](../commands/core.md#prepare-must-finish-first). After prepare finishes, restart the **matching** packager when Metro was already running ([packager reset-cache](recovery.md#packager-reset-cache-eaddrinuse)). + - TurboModule **codegen / spec / podspec / native shell** changed → same as native changed, plus regen codegen ([agent command policy § TurboModule codegen](../commands/native.md#turbomodule-codegen); wipe-then-regen [NewArch-AD-22](../../new-architecture/architecture-decisions.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)) when specs changed; if app loads with Metro redbox `Requiring unknown module "undefined"`, see [TurboModule stale toolchain](platform-troubleshooting.md#turbomodule-stale-toolchain-blocking). + - **JS bundle (debug):** all platforms (iOS, Android, macOS) load JS from Metro; only **release** builds pre-bundle/embed JS. `lib/**` edits alone do not require `:build` — use the [prepare completion gate](preflight.md#prepare-completion-gate-blocking) and Metro restart above. + - **TS coverage:** run `:build` before `:test-cover` on iOS/Android so Istanbul + patched test-runner coverage instrumentation is in the debug native app (bundle still from Metro). After test-runner patch changes, restart the packager with `yarn tests:packager:jet-reset-cache` ([packager reset-cache](recovery.md#packager-reset-cache-eaddrinuse)). + +4. **Always run with coverage:** + +```bash +yarn tests:ios:test-cover +yarn tests:android:test-cover +yarn tests:macos:test-cover +``` + +Clean `:build` + `:test-cover` each time — not reuse variants. + +5. **Report locations** — [Coverage design](../coverage-design.md). Android CI also runs `yarn tests:android:unit` (JVM) before Detox; post-e2e produces merged **`jacocoTestReport`** (unit + e2e) — details there, not duplicated here. + +6. **One e2e at a time (default)** — never overlap `:test-cover` runs on one host unless each run uses a distinct port/device slot via [configurable e2e environment](environment.md#configurable-e2e-environment). Serial runs share Metro `:8081` and the test-runner WebSocket port (default **8090**); parallel runs race on coverage/device/emulator state without slotted env. Every run starts after [clean pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start). Log triage for port/orchestration markers: [test-runner host orchestration](run-loop.md#test-runner-host-orchestration-log-triage-only). + +7. **No source edits during e2e** — wait/cancel cleanly before editing `packages/**`, `tests/**`, or bundle-affecting OKF docs. Saves can hot reload/rebundle and invalidate tests/coverage. + + + +## Test-app native modules (do not conflate) + +Coverage flush is **package-owned**. Test-app modules are **integration probes only** — do not call them for flush. + +| Module | Kind | Purpose | Owner | +| --- | --- | --- | --- | +| `Coverage` (`react-native-coverage`) | Package TurboModule | `flush()` from Jet `after` only | [coverage design § react-native-coverage](../code-coverage/test-app-modules.md#react-native-coverage) | +| `NativeRNFBTesting` | Test-app TurboModule | E2e probes (e.g. `completesNonFCMRemoteNotification`) | **this section** | +| `RNFBTestingMessaging` | Test-app `RCTBridgeModule` | iOS messaging delegate probe (`messagingPreservesExistingDelegate`) | **this section** | + +**`NativeRNFBTesting` (this section)** + +- **Spec:** `tests/specs/NativeRNFBTesting.ts` +- **iOS:** `tests/ios/testing/RNFBTestingTurboModule.{h,mm}` +- **Android:** `tests/android/app/src/main/java/com/invertase/testing/NativeRNFBTesting.kt` — unsupported methods **resolve `false`** +- **JS:** `getRNFBTesting()` in `packages/app/e2e/helpers.js` via `TurboModuleRegistry.get('NativeRNFBTesting')` +- **Probes:** `completesNonFCMRemoteNotification` (iOS); `serializeMessagingUserInfo` (iOS — `RNFBMessagingSerializer`); `messagingStoreSupportsDisabledStorage` (Android). Cross-platform methods resolve `false` / empty map on the unsupported platform. iOS `messagingPreservesExistingDelegate` lives on `RNFBTestingMessaging` (below), not this TurboModule. +- Production packages must **not** ship this TurboModule (test-app only). + +**`RNFBTestingMessaging` (this section)** + +- **iOS:** `tests/ios/testing/RNFBTestingMessagingModule.m` — `NativeModules.RNFBTestingMessaging.messagingPreservesExistingDelegate()` +- Standalone so the coverage TurboModule stays product-neutral ([coverage design § react-native-coverage](../code-coverage/test-app-modules.md#react-native-coverage)). + +**Probe hits in native coverage:** Messaging e2e `getRNFBTesting().completesNonFCMRemoteNotification()`, `getRNFBTesting().serializeMessagingUserInfo(...)`, and `NativeModules.RNFBTestingMessaging.messagingPreservesExistingDelegate()` exercise product sources (for example `RNFBMessaging+AppDelegate.m` non-FCM `completionHandler`, `RNFBMessagingSerializer.m`). Android e2e `getRNFBTesting().messagingStoreSupportsDisabledStorage()` exercises `ReactNativeFirebaseMessagingStoreImpl` disabled-storage paths. After iOS `:test-cover` and `yarn tests:ios:test:process-coverage`, iOS probe lines appear as hits in `coverage/ios-native/lcov.info` (Android probe hits land in Jacoco). Record them in the [coverage evidence package](../code-coverage/policy.md#coverage-evidence-package); passing probes are not a substitute for that artifact. Test-app vs library codegen (not committed; wipe derived `tests/ios/build/generated/ios`; gitignore `tests/ios/Package.swift` and sibling app dumps): [NewArch-AD-5](../../new-architecture/architecture-decisions.md#newarch-ad-5--commit-generated-code--accepted). + + + +## E2e infrastructure change bar + +Permanent e2e-harness / runbook / host-script changes need **reproduced causation**, not a guessed flag. + +| Term | Meaning | +| --- | --- | +| **Negative test** | With the change **absent**, the failure mode **reproduces reliably** (same command, same log signature). | +| **Positive test** | With the change **present**, that failure is gone (or gated). | +| **Non-slot test** | Unslotted serial defaults still work (`:8081` / `:8090` / `:8080`…, `TestingAVD`, `iPhone 17`, `io.invertase.testing`). | + +Also required: **one owner** — behavior lives in the canonical `yarn tests:*` command in this doc, not a parallel helper lifecycle. + +Unproven “maybe flake” ideas go on the **ephemeral work queue** only. Do not land them in product until they pass this bar. Do not change native **build settings** (for example Swift explicit modules) to paper over host races — e2e `:build` must stay representative of a real app build. + +### What not to do + +- Do not invoke the test runner (Jet), Detox, Metro, or emulators except through repo-root `yarn tests:*` commands in this doc — see [agent rule](../running-e2e.md#agent-rule-read-first). +- Do not run `:test-cover`, `:build`, Metro restart, or pre-flight while **`yarn` / `yarn lerna:prepare` is still in progress** — wait for exit 0 first ([prepare completion gate](preflight.md#prepare-completion-gate-blocking)). +- Do not run native `:build` until [install / patch / fmt gate](../commands/native-build-gate.md#install-patch-fmt-gate-blocking) is satisfied (fmt **≥ 12.1.0**). +- Do not background `:test-cover` and poll `pgrep`, `detox`, or process names for **completion**. Do poll the **tee log** for [startup-fail markers](startup-fail-fast.md#startup-fail-fast-poll) (immediately, then ~5s for ~60s). Do not wait the full `launchApp` timeout after a marker. +- Do not use `:test-cover-reuse`, `:test-cover-and-process`, or `:test-reuse` when measuring coverage or closing review gates. +- Do not use `:8090` listening as “e2e still running” without the platform active signal above. +- Do not start unslotted iOS/Android/macOS `:test-cover` concurrently on one host (same Metro/Jet/emulator defaults). Slotted cross-platform concurrency only per [parallel e2e topology](environment.md#parallel-e2e-topology). +- Do not edit source while a tee'd run is still in progress. +- Do not passively tail tee output when progress markers stop — follow [stalled run detection](recovery.md#stalled-run-detection). +- Do not run **full** harness (`require.context`, all modules) for **unit-focused**/**area-focused** tier — match [harness to tier](preflight.md#3-harness-matches-validation-tier). +- Do not run `.github/workflows/scripts/boot-simulator.sh`, `simctl shutdown all`, or `kill -9` on `:8090` or Metro `:8081` as prep. `boot-simulator.sh` is CI-only or internal to iOS test-runner retry. +- Do not wait out Android `:test-cover` FAIL + Jest `did not exit` — kill hung PIDs ([Android Detox launch ANR](platform-troubleshooting.md#android-detox-launch-anr-abi-mismatch)). Do not treat that ANR/ABI log as an AsyncStorage product failure. diff --git a/okf-bundle/testing/e2e/run-loop.md b/okf-bundle/testing/e2e/run-loop.md new file mode 100644 index 0000000000..e838ea591e --- /dev/null +++ b/okf-bundle/testing/e2e/run-loop.md @@ -0,0 +1,94 @@ +--- +type: Reference +title: 'E2e: running one iteration' +description: 'Serialized e2e loops, how a platform run is structured, test-runner host orchestration log triage, and running one iteration.' +tags: [testing, e2e] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: running one iteration + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Serialized e2e loops (shared dev host) + +Use [validation tiers](gates.md#e2e-validation-tiers-unit-focused--area-focused--full): **unit-focused**, **area-focused**, **full**. Match tier to [work type](../authoring/loop.md#work-types). **Serial default:** one unslotted `:test-cover` from clean [pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start). Slotted cross-platform concurrency: [parallel e2e topology](environment.md#parallel-e2e-topology). Log long output; upstream gets exit code + short summary. + +**Policy:** [OKF documentation and commit policy](../../documentation-policy.md) — public vs ephemeral vs private; [Efficiency](../../documentation-policy.md#efficiency). **Terms:** [iteration vocabulary](../iteration-vocabulary.md). + +### How a platform run is structured (Android/iOS) + +**Internal only — do not invoke sub-commands.** Wait on the single repo-root `:test-cover` command; Detox/Jest and the test runner start automatically. + +```text +yarn tests:android:test-cover # only command you run + └─ (internal) detox → jest → firebase.test.js → test runner on :8090 → app +``` + +macOS: `yarn tests:macos:test-cover` only — same `:8090` transport, no Detox. + +**Do not poll `pgrep`, `detox`, process names, or `:8090` for completion.** They match stale wrappers, orphans, zombies, and contention. Tee-log [startup fail-fast](startup-fail-fast.md#startup-fail-fast-poll) is required — that is log-marker polling, not process polling. + + + + +#### Test-runner host orchestration (log triage only) + +**No commands to run from this section** — for interpreting `:test-cover` logs and CI artifacts only. Patch workflow: [detox-patches.md](../../ci-workflows/detox-patches.md#updating-the-jet-patch-headless). CI triage: [iOS orchestration](../../ci-workflows/ios.md#e2e-test-app-orchestration-detox--jet). + +| Port | Protocol | Role | +| --- | --- | --- | +| **8090** (default `JET_REMOTE_PORT`) | WebSocket (`mocha-remote-*`) | App ↔ host test transport; drives Mocha in the app | +| **8091** (default `JET_REMOTE_PORT + 1`, override `RNFB_JET_CONTROL_PORT`) | HTTP POST only | Host ↔ test-runner **control plane** — not used by the app | + +**Why two ports** — Port 8090 is a WebSocket server (`ws` library). Plain HTTP `POST` to that socket (e.g. `/launch-ready`) gets **426 Upgrade Required** and can crash the runner with `ERR_HTTP_HEADERS_SENT` if a control handler shares the same HTTP stack. Control endpoints therefore live on a **separate** small HTTP server (`startControlHttpServer` in the test-runner patch). + +**Launch gate (orchestration race fix)** — `firebase.test.js` starts the test runner with `RNFB_JET_DEFER_RUN=1`. It listens on 8090 and **defers** `server.run()` until the host signals launch success: + +1. On Android, host force-stops both test packages and clears any stray **8090** listener before spawning Jet. +2. Host waits for TCP **8090**, then Metro (debug) if needed, then `launchAppWithRetry`. +3. Host `POST`s **`/orchestrate-state`** (`{ "phase": "launch-pending" | "launch-ok" | … }`) to the control port (best-effort diagnostics). +4. After `launchApp` succeeds, host `POST`s **`/launch-ready`** → test runner calls `server.run()` and the app may receive the mocha-remote `run` action. +5. Mocha tests must not start during a stuck or retried `launchApp`; on inner launch retry the host may kill and respawn the test runner before `terminateApp`/simulator reboot. +6. After `launch-ready`, `awaitJetExitWithStallGuard` aborts if Jet has not exited within `RNFB_JET_AWAIT_EXIT_STALL_MS` (default 20m). That stall is **retryable once** via Jet attempt 2 (iOS sim reboot); orchestrate state `stall-kill-jet`. + +**Log markers** — `[rnfb-e2e] orchestrate-state=…`, `[jet-control] deferring server.run until POST /launch-ready`, `[jet-control] launch-ready received`, `[jet-control] server.run starting`, `[jet-control] listening on http://…:8091`, `[jet-coverage] …`, `Jet client connected`, `orchestrate-state=stall-kill-jet`. + +**Pre-flight** — [Host-clear probes](preflight-host-clear.md#host-clear-probes) check **8090 only** (stray test-runner WS listener). **8091** may be open during a run; do not treat it as a stale-process signal by itself. + +#### CI iOS instrumentation (not local) + +GitHub Actions **Testing E2E iOS** adds CI-only steps local `:test-cover` does not run: pre-boot (`boot-simulator.sh`), one filtered **`sim-app.log`** stream, **`wait-for-load-settle.sh`** (threshold **20**) immediately before Detox, and optional video when `record_screens: true`. Host syslog and unfiltered simulator logs are **disabled** to reduce runner baseload. + +**Canonical owner:** [iOS CI baseload policy](../../ci-workflows/ios.md#ci-baseload-policy-instrumentation). Artifact names and triage: [simulator logging and video](../../ci-workflows/ios.md#simulator-logging-and-video-troubleshooting). + +### Running one iteration + +See also [startup fail-fast poll](startup-fail-fast.md#startup-fail-fast-poll) and [stalled run detection](recovery.md#stalled-run-detection). + +1. [Pre-flight](preflight.md#pre-flight-is-the-host-clear-to-start); if [host-clear probes](preflight-host-clear.md#host-clear-probes) fail, [pre-flight recovery](recovery.md#pre-flight-recovery) first. +2. One `:test-cover` Shell command. Prefer `block_until_ms` large enough for a **healthy** run (~15m macOS, ~45–60m iOS/Android). `block_until_ms: 0` is OK **if** you then poll the **tee file** (or `notify_on_output` / AwaitShell `pattern`) per [startup fail-fast poll](startup-fail-fast.md#startup-fail-fast-poll). Do **not** poll `pgrep`, Detox, process names, or `:8090` for **completion**. If the Shell tool returns no exit status under default sandbox permissions, see [agent command policy § Shell sandbox / permissions](../commands/core.md#shell-sandbox-permissions) before retrying or concluding failure. +3. From repo root, tee the canonical command to a **unique** path (`/tmp/rnfb-e2e--.log`). **Never** overwrite a known-good 1×3 log. The short `/tmp/rnfb-e2e-.log` name is a human convenience only — agents must not reuse it across diagnostic items. + +```bash +yarn tests:android:test-cover 2>&1 | tee /tmp/rnfb-e2e-android-.log +yarn tests:ios:test-cover 2>&1 | tee /tmp/rnfb-e2e-ios-.log +yarn tests:macos:test-cover 2>&1 | tee /tmp/rnfb-e2e-macos-.log +``` + +Do not substitute other entrypoints — see [agent rule](../running-e2e.md#agent-rule-read-first). + +4. Completion — **prefer shell exit code** when the Shell tool returns one: `0` finished; non-zero failed/aborted. If the Shell tool is **aborted, interrupted, or returns no exit status**, do **not** conclude failure or incomplete from that alone — check the tee log footer for [done markers](recovery.md#stalled-run-detection) before deciding; see [interrupted run](recovery.md#interrupted-run-abort-killed-terminal-eaddrinuse-on-8090). +5. Parse log tail with **anchored** patterns; do not infer from processes. Do **not** use bare `rg 'passing|failing'` — it matches mid-suite test titles too (e.g. `accepts passing in…`), not just the Jest summary line: + +```bash +rg '^\s*\d+ (passing|failing)' /tmp/rnfb-e2e-.log | tail -2 +rg '^\s+\d+\)' /tmp/rnfb-e2e-.log # failure blocks, if any +rg 'jet-coverage.*merged .* before NYC' /tmp/rnfb-e2e-.log | tail -1 +rg 'Tests Complete' /tmp/rnfb-e2e-.log | tail -1 # optional, see below +``` + +**Done footers** (either is sufficient; both together is strongest): Jest summary `N passing` / `N failing`, **and** — on the coverage path — `[jet-coverage] merged … before NYC shutdown`. `✨ Tests Complete ✨` is **optional** — it is not always emitted on local macOS runs; never require it alone as the done signal. Other markers: `[rnfb-e2e] orchestrate-state=`, `[jet-control] launch-ready received`. + +6. Return only platform, exit code (or `unknown (tool aborted); log footer green|red` when the Shell tool gave no exit status — [interrupted run](recovery.md#interrupted-run-abort-killed-terminal-eaddrinuse-on-8090)), pass/fail line, failing tests, log path, optional coverage-gap line. No full log upstream. +7. **Waiting on output:** during the first ~60s, `notify_on_output` / AwaitShell `pattern` **must** be the [startup-fail notify pattern](startup-fail-fast.md#startup-fail-fast-poll) (`E2E_STARTUP_FAILFAST_NOTIFY_PATTERN` in [`scripts/e2e/lib/e2e-startup-failfast.sh`](../../../scripts/e2e/lib/e2e-startup-failfast.sh) — hard infra only, not `currentStatus` / status-query timeout). After a healthy launch, never pattern bare `passing` or bare `APP_STATUS` — use an anchored pattern such as `^\s*\d+ (passing|failing)` or `jet-coverage.*merged .* before NYC`. Prefer the Shell tool's own exit code when it returns normally after launch is healthy. diff --git a/okf-bundle/testing/e2e/slot-devices.md b/okf-bundle/testing/e2e/slot-devices.md new file mode 100644 index 0000000000..7ef3cf85e5 --- /dev/null +++ b/okf-bundle/testing/e2e/slot-devices.md @@ -0,0 +1,71 @@ +--- +type: Reference +title: 'E2e: iOS slot simulators and macOS process identity' +description: 'Exact neutral iOS slot simulator contract, legacy migration (human operator only), and macOS process identity.' +tags: [testing, e2e, ios, macos, slots] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: iOS slot simulators and macOS process identity + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + + + +#### iOS slot simulators (exact neutral base or fail) + +Slotted iOS devices use a **repo-neutral base name**: **`RN E2E iOS slot-N`**, with `N` a [slot index](environment.md#e2e-slot-index). [`tests/.detoxrc.js`](../../../tests/.detoxrc.js) `ios.sim.debug.slotN` sets `device.name` to that **base**. The name is deliberately not RNFB-specific so one Mac can host other React Native e2e stacks — Detox or Appium — on the same slot devices; on such a host RNFB's reserved index is **slot 3** (the `yarn test:full --slot 3` example above). Serial unslotted iOS stays **`iPhone 17`** and Android stays `TestingAVD` / `TestingAVD-N`. + +| Surface | Name / owner | +| --- | --- | +| `.detoxrc` `device.name` for `ios.sim.debug.slotN` | `RN E2E iOS slot-N` — the **base** | +| `yarn tests:e2e:setup-ios-sims` | create/reuse of the **base** only | +| Device that runs slotted iOS | exact **`RN E2E iOS slot-N`** base | +| `RNFB_IOS_SIMULATOR` from `export-slot-env` | the exact base used by Detox, check, and release | +| Serial `ios.sim.debug` | stock Detox allocates **`iPhone 17`**, on `RNFB_IOS_SIM_RUNTIME` when set; CI pins the booted UDID instead ([ios.md § simulator reliability](../../ci-workflows/ios.md#simulator-reliability)) | + +**Stock Detox is not sufficient for this contract.** Detox 20.51.0 reuses a free matching base, but when every match is registry-taken it calls `AppleSimUtils.create()` and creates a suffixed simulator. [`tests/patches/detox+20.51.0.patch`](../../../tests/patches/detox+20.51.0.patch) (`patch-package` via `tests` `prepare`) preserves free exact-base reuse for `RN E2E iOS slot-0`…`slot-7`, but fails before creation when the base is taken. The error directs the operator to confirm Mellifera/manual ownership, release the owner, and inspect the Detox device registry only when no owner is active. Serial `iPhone 17` and unrelated simulator configurations keep stock allocation behavior. Apply the patch with root `yarn` — [install / patch / fmt gate](../commands/native-build-gate.md#install-patch-fmt-gate-blocking). This is **not** the Yarn Berry Detox patch under `.yarn/patches/` ([detox-patches.md](../../ci-workflows/detox-patches.md)). + +**Setup is create/reuse-only.** `yarn tests:e2e:setup-ios-sims [count]` creates a missing base and reports an existing one as `exists`. It never deletes, renames, erases, shuts down, or re-creates a device. + +**An occupied base is a hard ownership conflict.** Detox must not escape a Mellifera/manual slot lease by creating another simulator. Release the owning run, or resolve a stale registry entry only after confirming no owner is active. + +**Check/release are exact-name scoped.** After [export](environment.md#e2e-slot-index) (or a range-validated `--slot=N`), `yarn tests:e2e:check` reports BUSY when the selected slot's exact base is booted; `yarn tests:e2e:release --devices` issues `simctl shutdown ` for the simulator that slot's run [recorded](preflight-host-clear.md#run-record) (shutdown only — release never deletes a simulator). Matching is whole-name, so `slot-1` never picks up `slot-10` or any suffixed name. The manual `--include-unrecorded` shuts down the exact base only when it traces to this checkout, which in practice means recorded: an unrecorded simulator's `launchd_sim` runs from `/`, so it is left running — shut it down with `xcrun simctl shutdown `. Only `--all-slots` shuts down by name, every exact base through **effective max** plus serial `iPhone 17` ([manual machine wipe](preflight-host-clear.md#manual-machine-wipe)). + + + +##### Migrating a host off legacy `RNFB E2E iOS slot-N` (human operator only) + +Hosts provisioned before the neutral base still hold `RNFB E2E iOS slot-N` devices (and their `-Detox` clones). Nothing in the runbook selects them, so they are inert; the only reason to remove them is reclaiming disk on a host that is about to run a slotted iOS wave. + +This is a **human-operator** procedure. Agents must not run it — `xcrun simctl delete` is not in the [agent command registry](../agent-command-policy.md#canonical-registry), and unregistered direct `simctl` device commands are [forbidden](../commands/forbidden.md#forbidden-always). An agent that needs the migration asks the operator to run it. + +For the **one** slot `N` being migrated (shown for `N=3`): + +```bash +xcrun simctl delete 'RNFB E2E iOS slot-3' # exact legacy base +xcrun simctl delete 'RNFB E2E iOS slot-3-Detox' # exact legacy Detox clone +yarn tests:e2e:setup-ios-sims 4 # recreate neutral bases 0..3 (create/reuse-only) +``` + +| Safety rule | Why | +| --- | --- | +| Delete **only** the two exact legacy names for the selected `N` | A broader match can destroy a device another worktree, repo, or operator is mid-run on | +| Never prefix/glob delete (`RNFB E2E iOS*`), `simctl delete all`, `simctl delete unavailable`, or `simctl shutdown all` | Not scoped to this migration; also [what not to do](rules.md#what-not-to-do) | +| Never delete a neutral `RN E2E iOS slot-N` base | It is the live slot device, shared with any other e2e stack on this host | +| Never delete, rename, or erase serial **`iPhone 17`** | Serial unslotted e2e and CI depend on it | +| Recreate only via `yarn tests:e2e:setup-ios-sims` | A hand-rolled `simctl create` can pick a different device type or runtime than the setup script resolves | + + + +#### macOS process identity (concurrency) + +| Surface | Default | Concurrent macOS | +| --- | --- | --- | +| **Process / `PRODUCT_NAME`** | `io.invertase.testing` | Set `RNFB_MACOS_PRODUCT_NAME` (e.g. `io.invertase.testing.s1`) — required for isolation | +| App path | `…/${PRODUCT_NAME}.app/Contents/MacOS/${PRODUCT_NAME}` | Follows product name | +| `CFBundleIdentifier` | `org.reactjs.native.io-invertase-testing` | `RNFB_MACOS_BUNDLE_IDENTIFIER` or derived `org.reactjs.native.${PRODUCT_NAME with dots→hyphens}` | +| Metro `app=` query | matches bundle ID | [`tests-macos/.jetrc.js`](../../../tests-macos/.jetrc.js) reads the same env | +| Firebase / GoogleService | **None on macOS target** | No cloud re-registration for JS/Other e2e | + +`yarn tests:macos:build` exports `RNFB_MACOS_PRODUCT_NAME_SUFFIX` into the xcodebuild environment (pbxproj expansion only). Check uses `RNFB_MACOS_PRODUCT_NAME` for `pgrep`; release and the Jet harness stop only the app pid the run spawned and [recorded](preflight-host-clear.md#run-record) under that name (`killall` by name is only in the manual `--include-unrecorded` path). Same-platform parallel still needs **one worktree per macOS instance** ([parallel topology](environment.md#parallel-e2e-topology)). Mild residual: shared `io.invertase.firebase` preferences suite across apps. diff --git a/okf-bundle/testing/e2e/slot-env-variables.md b/okf-bundle/testing/e2e/slot-env-variables.md new file mode 100644 index 0000000000..310342b482 --- /dev/null +++ b/okf-bundle/testing/e2e/slot-env-variables.md @@ -0,0 +1,38 @@ +--- +type: Reference +title: 'E2e: slot environment variables' +description: 'Reference table of every RNFB e2e port, device, and timeout environment variable.' +tags: [testing, e2e, slots, environment] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: slot environment variables + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +| Variable | Purpose | +| --- | --- | +| `RCT_METRO_PORT`, `RNFB_METRO_PORT` | Metro bundler **listen** port for this process. Slotted: matches the **active** platform×slot (`export-slot-env`), e.g. ios slot 0 = **12107**, android slot 0 = **12007** — never reuse android’s port for iOS | +| `RNFB_{ANDROID,IOS,MACOS}_METRO_PORT` | Per-platform Metro port (in-app / host selection via self-detection). Formula + slot-0 worked example: [e2e parallel design § Metro](../e2e-parallel-design.md#metro-per-worktree-and-per-slot) | +| `JET_REMOTE_PORT`, `JET_METRO_PORT` | Process-local Jet / Metro hints (global fallback) | +| `RNFB_{ANDROID,IOS,MACOS}_JET_PORT` | Per-platform Jet WebSocket port | +| `RNFB_{ANDROID,IOS,MACOS}_JET_CONTROL_PORT` | Per-platform Jet HTTP control (preferred); `RNFB_JET_CONTROL_PORT` remains a process-local fallback | +| `RNFB_JET_CONTROL_PORT` | Process-local Jet HTTP control plane fallback (default `JET_REMOTE_PORT + 1`) | +| `RNFB_{ANDROID,IOS,MACOS}_EMULATOR_{FIRESTORE,AUTH,DATABASE,FUNCTIONS,STORAGE,HUB,LOGGING}_PORT` | Per-platform Firebase emulator suite (in-app + host). `yarn tests:emulator:start` also derives Firestore `websocketPort` / Eventarc / Tasks from the firestore port | +| `RNFB_DETOX_ANDROID_CONFIG`, `RNFB_DETOX_IOS_CONFIG` | Detox configuration name (e.g. `android.emu.debug.slot0`, `ios.sim.debug.slot1`). Honoured on **slotted** runs only: serial `yarn tests:*` (no `RNFB_E2E_SLOT` / `RNFB_E2E_HOST_SLOT`) unsets these and the device overrides via `e2e_sanitize_serial_env`, so e.g. `RNFB_DETOX_ANDROID_CONFIG=android.att.debug` is silently ignored and serial always targets `TestingAVD` / `iPhone 17` | +| `RNFB_DETOX_STATUS_QUERY_TIMEOUT_MS`, `RNFB_DETOX_LOGIN_TIMEOUT_MS`, `RNFB_DETOX_DEBUG_SYNCHRONIZATION_MS`, `RNFB_LAUNCH_APP_TIMEOUT_MS`, `RNFB_LAUNCH_APP_RELEASE_TIMEOUT_MS`, `RNFB_LAUNCH_APP_MAX_ATTEMPTS` | Load-latency knobs. **Defaults live in** [`tests/e2e/detoxLatencyPolicy.js`](../../../tests/e2e/detoxLatencyPolicy.js). Detox Login / CurrentStatus floors also require the yarn patch ([detox-patches](../../ci-workflows/detox-patches.md)). Do not copy timeout numbers elsewhere | +| `RNFB_ANDROID_ADB_INSTALL_TIMEOUT_MS` | Android Detox `pm install` spawn timeout (policy default **300000ms**). **Defaults live in** [`tests/e2e/detoxLatencyPolicy.js`](../../../tests/e2e/detoxLatencyPolicy.js). Detox `ADB.js` patch hardcodes the same value at yarn apply time — env override does not reach Detox without patch regen ([detox-patches](../../ci-workflows/detox-patches.md)) | +| `RNFB_JET_AWAIT_EXIT_STALL_MS` | After `launch-ready`, abort if Jet has not exited within this window (policy default **1200000ms**). Stall sets `retryableAtJetLevel` so Jet **attempt 2** (+ iOS sim reboot) runs once. Log state `stall-kill-jet`. **Defaults live in** [`tests/e2e/detoxLatencyPolicy.js`](../../../tests/e2e/detoxLatencyPolicy.js) | +| `RNFB_E2E_SLOT` | Slot index for orchestration / AVD / sim naming. Set by `export-slot-env` — [slot index](environment.md#e2e-slot-index) | +| `GRADLE_USER_HOME` | Optional host setup only. Leave unset for the Gradle default (`~/.gradle`); slotted `export-slot-env` does not set or isolate it. If the host does not default to `$HOME/.gradle`, you may set `GRADLE_USER_HOME=$HOME/.gradle` — not a per-slot override | +| `RNFB_E2E_PLATFORM` | Optional orchestration label only — **not** used for port selection (prefer unset in slotted multi-platform launches) | +| `RNFB_ANDROID_AVD`, `RNFB_IOS_SIMULATOR`, `RNFB_ANDROID_EMULATOR_BOOT_ARGS` | Device selection overrides. Slotted helpers set `TestingAVD-{n}` / exact `RN E2E iOS slot-{n}` (including `n=0`; patched Detox reuses that iOS base or fails when registry-taken, see [iOS slot simulators](slot-devices.md#ios-slot-simulators)); serial defaults stay `TestingAVD` / `iPhone 17`. `RNFB_ANDROID_EMULATOR_BOOT_ARGS` is snapshot flags only — never include `-port` | +| `RNFB_ANDROID_CONSOLE_PORT`, `ANDROID_SERIAL` | Android qemu console port and adb serial. **Serial** `e2e_sanitize_serial_env` pins `5554` / `emulator-5554` (`TestingAVD`). **Slotted** helpers pin `5556+2×slot` / `emulator-${port}` (adb-safe **[5554, 5584]**, skipping 5554 so unslotted `emulator-5554` can coexist). Detox patch uses this instead of FreePortFinder 10000–20000 | +| `RNFB_MACOS_PRODUCT_NAME` | macOS `PRODUCT_NAME` / process name (default `io.invertase.testing`). Required distinct per concurrent macOS slot. Slotted helpers set `io.invertase.testing.s`; override via `RNFB_MACOS_PRODUCT_NAME_OVERRIDE` | +| `RNFB_MACOS_BUNDLE_IDENTIFIER` | macOS `CFBundleIdentifier` (default derived from product name). Metro `app=` follows this. Slotted override: `RNFB_MACOS_BUNDLE_IDENTIFIER_OVERRIDE` | +| `ORG_GRADLE_PROJECT_reactNativeDevServerPort` | Android Gradle Metro port baked into the APK's `react_native_dev_server_port` resource at build time. **Set automatically** by `yarn tests:android:build` (`RNFB_ANDROID_METRO_PORT` → `RCT_METRO_PORT` → `RNFB_METRO_PORT` → `JET_METRO_PORT` → `8081`) — only export it yourself when building Android outside that script (e.g. `detox build` invoked directly). Detox's `reversePorts` (`tests/.detoxrc.js`) already forwards the same slotted Metro port; this var makes the APK actually _ask_ for that port. `yarn tests:android:test-cover` asserts that baked integer matches the active Metro port after `e2e_sanitize_serial_env` (serial **8081**, slotted `RNFB_ANDROID_METRO_PORT`). A slot-baked **12007** APK plus serial host wait/reverse **8081** is APP_STATUS `currentStatus` / `isReady` hang — host Metro prefetch of `:8081` still succeeds. Re-`:build` in the same env; do not skip `:build` after a slotted APK in this worktree. | +| `SIMCTL_CHILD_RCT_METRO_PORT` | iOS simulator child Metro port | +| `RNFB_E2E_DEBUG` | Verbose `[rnfb-e2e]` port resolution logging in app helpers | +| `RNFB_MELLIFERA` | Mellifera-only. Must **not** change RNFB `yarn tests:e2e:check` / `release` behavior. Mellifera maps a reservation to `RNFB_*` env, then calls those yarn targets | + +See [host-clear probes](preflight-host-clear.md#host-clear-probes) (`yarn tests:e2e:check` / `yarn tests:e2e:release`). diff --git a/okf-bundle/testing/e2e/slotted-parallel.md b/okf-bundle/testing/e2e/slotted-parallel.md new file mode 100644 index 0000000000..16666a5433 --- /dev/null +++ b/okf-bundle/testing/e2e/slotted-parallel.md @@ -0,0 +1,47 @@ +--- +type: Reference +title: 'E2e: slotted parallel operation' +description: 'Slotted mode readiness, first use of a slot, carry-in, check/release, waves, overlapping pods, and global device scoping.' +tags: [testing, e2e, slots, parallel] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: slotted parallel operation + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +Slotted mode: no e2e retries (fail-fast). Serial mode: up to 3 `:test-cover` attempts per platform. Slotted e2e uses distinct Metro listeners (`tests/` for android+ios, `tests-macos/` for macos) and **three Firebase emulator suites** (one `yarn tests:emulator:start` per platform subshell after `export-slot-env N`) — no serial Metro switch. + +**Readiness (orchestrator):** follow [§2 Services ready](preflight.md#2-services-ready) — Metro `curl /status` with `packager-status:running`; emulator ready = `yarn tests:emulator:start` exit 0 (Functions port via `e2e_port_listening` inside that script). No fixed `sleep` for readiness; poll or delegate to canonical `yarn tests:*`. + +**First use of a slot:** `yarn tests:e2e:setup-android-avds [count]` / `yarn tests:e2e:setup-ios-sims [count]` — [setup count](environment.md#e2e-slot-index). Both scripts are **create/reuse-only** — an existing device is reported and reused; neither deletes, renames, or erases anything. Serial unslotted devices stay `TestingAVD` / `iPhone 17`. iOS simulators are created on **`RNFB_IOS_SIM_RUNTIME`** (default `iOS 27.0`); CI/Jet reboot paths use **UDID** + selected-Xcode **Device Hub** — see [iOS CI simulator reliability](../../ci-workflows/ios.md#simulator-reliability). Naming and host migration: [iOS slot simulators](slot-devices.md#ios-slot-simulators). + +**Base `TestingAVD` prerequisite (Android):** `yarn tests:e2e:setup-android-avds` does **not** create the serial `TestingAVD`; [`scripts/e2e/create-android-avds.sh`](../../../scripts/e2e/create-android-avds.sh) only clones an existing base (`RNFB_ANDROID_BASE_AVD`, default `TestingAVD`) into `TestingAVD-N` and fails with `base AVD 'TestingAVD' not found` otherwise. A human creates it once in Android Studio Device Manager; CI uses API **36**, `google_apis`, `x86_64` ([`tests_e2e_android.yml`](../../../.github/workflows/tests_e2e_android.yml) matrix). If the script reports it missing, agents stop and ask the user — `avdmanager` is not on the [agent allowlist](../agent-command-policy.md). Match the CI API level: the readiness probe in [`tests/e2e/firebase.test.js`](../../../tests/e2e/firebase.test.js) runs `adb shell cmd package wait-for-handler`, which API 33 does not support (`Unknown command: wait-for-handler`), so an older image stalls retrying `android-ready package handler wait` until `RNFB_REBOOT_ANDROID_EMULATOR_TIMEOUT_MS` (default 5 min) and the app never launches. + +Keep exported env in the **same shell**. `export-slot-env` loads full `RNFB_{ANDROID,IOS,MACOS}_*` carry-in, `ANDROID_SERIAL=emulator-$((5556+2*N))`, `RNFB_ANDROID_CONSOLE_PORT` (Detox must not FreePortFinder **10000–20000**), `RNFB_MACOS_PRODUCT_NAME=io.invertase.testing.sN`. Does not set `GRADLE_USER_HOME`. + +**Serial leftover env + Jest transform cache:** `tests/.babelrc` / `tests-macos/.babelrc` `babel-plugin-transform-inline-environment-variables` inlines `RNFB_*` at transform time. Jest’s transform cache does **not** include those env values, so a prior slotted shell can make serial `:test-cover` wait on android slot-0 Metro **`:12007`**. Mitigations: `eval "$(yarn tests:e2e:clear-slot-env)"` before a serial Law run; `e2e_sanitize_serial_env` inside packager / emulator / `:build` / `:test-cover` when `RNFB_E2E_SLOT` is unset (then **pins** `RNFB_ANDROID_CONSOLE_PORT=5554` / `ANDROID_SERIAL=emulator-5554` so Detox does not FreePortFinder **10000–20000**); `cache: false` in `tests/e2e/jest.config.js` so Detox Jest cannot replay a slotted transform. Host Metro wait is not the only leftover: a **slot-baked APK** (`react_native_dev_server_port=12007`) on serial `:test-cover` still launches `TestingAVD`/`emulator-5554` then fails Detox `isReady` / APP_STATUS — `e2e_assert_android_apk_metro_port` fail-fasts that mismatch. + +**Check/release with slot env loaded:** all three platform port blocks for that slot (ports+apps; `--devices` for AVD/sims). Mid-wave free of one platform: `--platform=`. `--platform=` never selects a slot. No slot env → serial defaults only (not leftover slots). Release frees only [recorded](preflight-host-clear.md#run-record) resources in that scope. Direct `--slot=N` is the same [slot index](environment.md#e2e-slot-index) guard; preferred lifecycle is still export then check/release. `--slot=N` re-applies slot N's env (ports, `TestingAVD-N` / `emulator-<5556+2N>`, `RN E2E iOS slot-N`, `io.invertase.testing.sN`), so a bare `--slot=N` never falls back to the serial emulator or simulator; a caller `RNFB_E2E_PLATFORM` or `--platform=` still narrows it. It exits 2 before any probe or release when a different slot's env is loaded. `--all-slots` skips the re-apply. + +**Infra failures:** hub/port taken, suite busy, Detox `TELNET_ERROR` / leftover `emulator-16xxx`, wrong-owner Metro, **`yarn tests:ios:pod:install` / `yarn tests:macos:pod:install` / `:build` failure** → **abort the wave**. On the first infra fail: stop remaining platform×slot cells (do **not** wait for them to finish), then scoped `yarn tests:e2e:release` in each cell's slot env. That frees only what each cell recorded, so it is safe while other owners are live. The [manual machine wipe](preflight-host-clear.md#manual-machine-wipe) is never part of wave handling. `:test-cover` does not restart Metro. + +**Overlapping Apple `pod:install`:** CocoaPods trunk CDN (`source 'https://cdn.cocoapods.org/'` in `tests/ios/Podfile`, shared `~/.cocoapods`) is a **host-global** cache. Concurrent `yarn tests:ios:pod:install` (which deletes `ios/Podfile.lock` then resolves) can miss trunk specs (`Unable to find a specification for SocketRocket (~> 0.7.1)`) while sibling worktrees succeed. macOS SocketRocket is a **local** `react-native-macos` podspec, so that miss is iOS CDN/spec — not a missing git repo and not Swift explicit modules. **Serialize** all Apple `yarn tests::pod:install` across worktrees **before** overlapping `:build` / `:test-cover`. `:build` still must not invoke pod install. + +**Wave operator checklist (before N×3 cells):** scoped recovery per slot, then serialized Apple pods. **Pre-wave:** in each slot's env, `yarn tests:e2e:release --devices` + `yarn tests:e2e:check` must be CLEAR. A slot that stays BUSY with `owner=unrecorded` belongs to another owner — use a free slot, or ask the user before any [manual machine wipe](preflight-host-clear.md#manual-machine-wipe). Then serialize `yarn tests:ios:pod:install` and `yarn tests:macos:pod:install` across all worktrees (one platform×slot at a time — **not** a host flock). Run ios then macos for **each configured slot** (`0..N-1`, one worktree per slot) before overlapping `:build` / `:test-cover`. Do **not** launch concurrent Apple `pod:install` across worktrees. Pre-wave release stops only the emulator/simulator instances each slot's runs recorded (leftovers from other owners stay BUSY); it does **not** dismiss an already-visible Android Emulator crash-report modal. That dialog is the **emulator binary’s** Google crash reporter (not Android Studio IDE settings, not macOS ReportCrash). Detox spawns `emulator` from CLI — use `emulator -crash-report-mode never` (see `emulator -help`; requires Android Emulator **≥ 37**, confirmed on 37.1.11.0 — older emulators lack the flag and `SPAWN_FAIL` at launch, so update the emulator rather than working around it) or set macOS `com.android.Emulator` `set.crashReportPreference` to `2` (Never; `0`=Ask, `1`=Always per AOSP `qt-settings.h`). The UI control **When to send crash reports** lives only under the **standalone** emulator window: Extended controls → Settings → General ([Android docs](https://developer.android.com/studio/run/emulator-extended-controls)); it is unavailable when the emulator runs embedded in Android Studio or headless from Detox. + +**Overlapping 3×3 is 9 cells at once.** After serialized Apple `pod:install` (CDN only), launch android + ios + macos `:test-cover` on all three worktrees together — qemu included while Apple Jets are live. Do **not** serialize Android. Do **not** wait for Apple `:test-cover` to finish before qemu. Do **not** treat Detox `currentStatus` / status-query timeout latency as host-capacity proof or as a reason to run fewer than 9 cells. Latency is tolerated: raise Detox ready/status timeouts and launch retries ([`tests/e2e/detoxLatencyPolicy.js`](../../../tests/e2e/detoxLatencyPolicy.js), [Detox yarn patch](../../ci-workflows/detox-patches.md)) so CI-like slowness waits instead of flakes. Hard infra still aborts ([startup fail-fast poll](startup-fail-fast.md#startup-fail-fast-poll)). Metro `/status` can be `packager-status:running` before `:build` and dead at `:test-cover` — start `yarn tests:packager:*` kill-then-start again immediately before `:test-cover` (same `RCT_METRO_PORT` / `${RNFB_METRO_CACHE_ROOT:-$HOME/.metro}/rnfb-${port}` / `/status` re-gate). Jet launch-retry/drain leftover listen PIDs this run owns (SIGTERM then SIGKILL; a foreign holder fails fast); macOS bundle wait fail-fast if `/status` is not `packager-status:running` within 120s. Same-platform 3× still needs **three worktrees**. Do **not** use host flock, Metro-after-build, per-slot `GRADLE_USER_HOME`, or `setsid`. + +**Slotted device identities (including slot 0):** `TestingAVD-N`, exact `RN E2E iOS slot-N` ([iOS slot simulators](slot-devices.md#ios-slot-simulators)), Detox `*.slotN`, `io.invertase.testing.sN`. Console `5556+2N` (never `5554` for slotted 0). Detox `LaunchCommand` already prepends `-port`; do not add `-port` to `bootArgs`. Apple `:build` compiles only — `pod:install` is a prior step when pods may be stale. + +**Parallel / multi-platform carry-in:** every Metro/Jest/Detox process for a slot gets the **full** `RNFB_{ANDROID,IOS,MACOS}_*` set (`tests/.babelrc` / `tests-macos/.babelrc` inline static `process.env.RNFB_*`). Do not use `RNFB_E2E_PLATFORM` to choose ports. In-app: `getE2eEmulatorPort(…)` — never hardcode serial emulator ports. + +**Firebase emulator suites:** one suite per platform×slot; `yarn tests:emulator:start` pins auth/database/firestore/functions/storage/hub/logging **and** Firestore websocket / Eventarc / Tasks (`FS+8/+9/+12`). Abort if those ports are busy. Ready = Functions port listening. Serialize `scripts/functions` yarn/build across concurrent starts. + +**macOS:** `yarn tests:macos:build` derives `RNFB_MACOS_PRODUCT_NAME_SUFFIX` for pbxproj — never pass global `PRODUCT_NAME=` on the xcodebuild CLI. See [macOS process identity](slot-devices.md#macos-process-identity-concurrency). + + + +**Global device scoping** — with no `--platform`, no `RNFB_E2E_PLATFORM`, and no per-platform port env set, check/release use **serial defaults only**. They probe android app state on the default serial and the macOS default process name, but do **not** escalate a booted serial `iPhone 17` to BUSY (INFO only). Even with `--platform=ios`, only the identity's exact simulator is BUSY; any other booted simulator is another owner's and stays INFO. Pass `--platform=ios` when iOS is about to run ([host clear](preflight-host-clear.md#1-host-clear)). `--platform=` does **not** load a slot — see [slot lifecycle](environment.md#slot-lifecycle). `--all-slots` is the only unscoped leftover-slot wipe, and it is [manual only](preflight-host-clear.md#manual-machine-wipe). + +Setup: `yarn tests:e2e:setup-android-avds [count]` / `yarn tests:e2e:setup-ios-sims [count]` (create/reuse-only; [setup count](environment.md#e2e-slot-index), [iOS slot simulators](slot-devices.md#ios-slot-simulators)). diff --git a/okf-bundle/testing/e2e/startup-fail-fast.md b/okf-bundle/testing/e2e/startup-fail-fast.md new file mode 100644 index 0000000000..3e15e42ecb --- /dev/null +++ b/okf-bundle/testing/e2e/startup-fail-fast.md @@ -0,0 +1,45 @@ +--- +type: Reference +title: 'E2e: startup fail-fast poll' +description: 'Startup fail-fast markers, poll cadence, and hard-infra vs latency classification.' +tags: [testing, e2e, fail-fast] +timestamp: 2026-12-02T00:00:00Z +--- + +# E2e: startup fail-fast poll + +Part of [Running e2e tests](../running-e2e.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + + + + +### Startup fail-fast poll + +Startup failures are **immediate**. After a startup-fail marker, do **not** wait for `launchApp` (timeouts in [`tests/e2e/detoxLatencyPolicy.js`](../../../tests/e2e/detoxLatencyPolicy.js)) or the 5-minute [stalled run](recovery.md#stalled-run-detection) window. + +This is **tee-log monitoring**, not process polling. It complements [running one iteration](run-loop.md#running-one-iteration) and [stalled run detection](recovery.md#stalled-run-detection); it does not change Detox flags ([infrastructure change bar](rules.md#e2e-infrastructure-change-bar)). + +After starting `:test-cover` teed to a **unique** path (`/tmp/rnfb-e2e--.log`): + +1. Check the tee **immediately**, then every **~5s for ~60s** (or `notify_on_output` / AwaitShell `pattern` with the markers below). +2. On **any** marker: **STOP** the run, scoped [pre-flight recovery](recovery.md#pre-flight-recovery) / `yarn tests:e2e:release`, and return YAML. Do not AwaitShell the full `launchApp` timeout. +3. After a **healthy** launch (`Jet client connected` / `launch-ready received`), use existing stalled-run / done-footer rules. + +**Startup-fail markers** (abort immediately; do not wait the full `launchApp` timeout): + +| Match | Do not match | +| --- | --- | +| `ReactContext is null` (dead Fabric launch that does not recover) | Detox `ws-client:APP_STATUS The app seems to be idle` (healthy idle after `launch-ready`) | +| `TELNET_ERROR` / `Cannot connect` | Load-induced `ws-client:APP_STATUS` + `currentStatus` / status-query timeout (`response within …ms timeout`) — latency, not hard infra; do not serialize Android or kill a 9-cell wave for it | +| serial leftover: `waiting for Metro on port 12007` **and** `emulator-5554` | slotted android slot-0 `waiting for Metro on port 12007` with `emulator-5556` (healthy) | +| `emulator-16` in the adb list | — | +| `Jest did not exit` | — | +| `Could not connect to development server` / `No script URL provided` | — | +| `Detox.framework could not be found` | — | +| `Package uses different ABI(s) than its instrumentation` | — | +| `Received a message from the client, but server wasn't running` | — | +| `[rnfb-e2e] launchApp timed out after` | In-process `launchApp` retry still running (max 2; logs `launchApp failure reason=` first) | + +**notify_on_output / AwaitShell `pattern`:** `ReactContext is null\|TELNET_ERROR\|Cannot connect\|emulator-16\|Jest did not exit` — same string as `E2E_STARTUP_FAILFAST_NOTIFY_PATTERN`. **Must not** use bare `APP_STATUS`, bare `currentStatus`, bare `…ms timeout`, or bare `waiting for Metro on port 12007` (slot-0 Metro is `:12007`). Serial leftover `:12007` is `waiting for Metro on port 12007` **together with** `emulator-5554`. + +First infra fail on a wave (`pod:install` / `:build` / preflight / startup-fail marker): abort remaining cells (do not wait), then scoped release in each cell's slot env (the [manual machine wipe](preflight-host-clear.md#manual-machine-wipe) only at explicit user direction). `yarn tests::pod:install` or `:build` failure is infra (stop the wave) — not a product mocha fail to wait out. diff --git a/okf-bundle/testing/firebase-testing-project.md b/okf-bundle/testing/firebase-testing-project.md index 5336639ebf..82278b2b23 100644 --- a/okf-bundle/testing/firebase-testing-project.md +++ b/okf-bundle/testing/firebase-testing-project.md @@ -52,7 +52,7 @@ flowchart TB # Where configuration lives -Config root: [`.github/workflows/scripts/`](../../.github/workflows/scripts/) (`firebase.json` cwd for Firebase CLI). Emulator start: [running e2e § Rules #2](running-e2e.md#rules). +Config root: [`.github/workflows/scripts/`](../../.github/workflows/scripts) (`firebase.json` cwd for Firebase CLI). Emulator start: [running e2e § Rules #2](e2e/rules.md#rules). | File | Purpose | |------|---------| @@ -64,7 +64,7 @@ Config root: [`.github/workflows/scripts/`](../../.github/workflows/scripts/) (` | [`firestore.pipelines-e2e.indexes.json`](../../.github/workflows/scripts/firestore.pipelines-e2e.indexes.json) | Indexes (incl. vector) for **`pipelines-e2e`** | | [`database.rules`](../../.github/workflows/scripts/database.rules) | Realtime Database rules (emulator) | | [`storage.rules`](../../.github/workflows/scripts/storage.rules) | Storage rules (emulator) | -| [`functions/`](../../.github/workflows/scripts/functions/) | Cloud Functions used by some e2e (e.g. Vertex AI mock) | +| [`functions/`](../../.github/workflows/scripts/functions) | Cloud Functions used by some e2e (e.g. Vertex AI mock) | | [`deploy-firestore.sh`](../../.github/workflows/scripts/deploy-firestore.sh) | Deploy Firestore rules + indexes to cloud | | [`deploy-e2e-cloud-functions.sh`](../../.github/workflows/scripts/deploy-e2e-cloud-functions.sh) | Deploy live e2e helper callables (metrics, App Check, RC admin) | | [`sync-firestore-indexes.sh`](../../.github/workflows/scripts/sync-firestore-indexes.sh) | Pull indexes from cloud into repo (non-interactive) | @@ -82,7 +82,7 @@ Runtime wiring: ## Started locally -Foreground/background emulator start: [running e2e § Rules #2](running-e2e.md#rules). +Foreground/background emulator start: [running e2e § Rules #2](e2e/rules.md#rules). Runs from `.github/workflows/scripts/`: @@ -128,7 +128,7 @@ See also [Firestore Pipelines design](/packages/firestore/pipelines.md) for brid |---------|------------------|----------------| | **Installations** (`getId`, `getToken`) | **No** | Live `firebaseinstallations.googleapis.com` on shared project | | **Remote Config** (`fetch`, `activate`, `getValue`) | **No** | Live RC; depends on FIS token from Installations | -| **App Check** | **No** | iOS/Android: debug tokens (no `e2eHelperSecret`). macOS custom-provider: live `fetchAppCheckTokenV2` when `e2eHelperSecret` is set; skip when absent — [running e2e § macOS App Check](running-e2e.md#macos-app-check-helper-secret) | +| **App Check** | **No** | iOS/Android: debug tokens (no `e2eHelperSecret`). macOS custom-provider: live `fetchAppCheckTokenV2` when `e2eHelperSecret` is set; skip when absent — [running e2e § macOS App Check](e2e/narrowing.md#macos-app-check-helper-secret) | | **RC template admin** | **No** | Live callable `testFunctionRemoteConfigUpdateV2` | **Parallel CI load** — All e2e matrix legs (iOS debug/release, Android, macOS Other when RC/App Check modules load) share one FIS project and the same live helper callables. Duplicate namespaced + modular suites doubled token traffic; prefer **modular-only** coverage while namespaced APIs are removed (`xdescribe` v8 blocks per package). @@ -199,7 +199,7 @@ Summary query needs Cloud Logging read on the functions runtime SA (`roles/loggi `fetchAppCheckTokenV2` needs its secret before deploy: `firebase functions:secrets:set E2E_HELPER_SECRET --project react-native-firebase-testing` (enables Secret Manager on first use), and the same value stored as the `E2E_HELPER_SECRET` GitHub Actions secret. -**Local access / install** into gitignored `tests/harness.overrides.js` (`e2eHelperSecret`): [running e2e § macOS App Check helper secret](running-e2e.md#macos-app-check-helper-secret) (why / skip) and [agent command policy § App Check e2e helper secret](agent-command-policy.md#app-check-e2e-helper-secret) (allowlisted access + merge). Do not restate those commands here; `functions:secrets:set` remains operator/deploy only. +**Local access / install** into gitignored `tests/harness.overrides.js` (`e2eHelperSecret`): [running e2e § macOS App Check helper secret](e2e/narrowing.md#macos-app-check-helper-secret) (why / skip) and [agent command policy § App Check e2e helper secret](commands/e2e.md#app-check-e2e-helper-secret) (allowlisted access + merge). Do not restate those commands here; `functions:secrets:set` remains operator/deploy only. **Triage** — Cloud Console → Logging, filter `jsonPayload.message="[rnfb-e2e-metrics]"`. CI Detox log on quota failure: `rg 'cloud-pressure-analysis' detox-step.log`. Retrospective aggregate: POST `e2eCloudMetricsSummaryV2` with `{"data":{"lookbackHours":24}}`. @@ -212,7 +212,7 @@ Functions **e2e** callables run on the **emulator** (`:5001`). Under CI load, cl | **Client** (`functions.e2e.js`) | `e2eCallableTimeoutOptions()` → 120s | `{ timeout: 1000 }` only | | **Server** (`functions/src/*.ts`) | `E2E_TEST_FUNCTION_TIMEOUT_SECONDS` (120) via `e2eCallOptions.ts` | `sleeperV2` unchanged (intentional hang) | -Restart emulator after rebuilding `functions/` — [running e2e § Rules #2](running-e2e.md#rules). +Restart emulator after rebuilding `functions/` — [running e2e § Rules #2](e2e/rules.md#rules). # Cloud project: deploy rules and indexes @@ -225,7 +225,7 @@ Firebase CLI must be authenticated for `react-native-firebase-testing`. Scripts | Surface | Location | |---------|----------| | JS `firebase-tools` | Repo root `package.json`, `tests/package.json`, `.github/workflows/scripts/functions/package.json` — run `yarn` at repo root and `yarn` in `functions/` | -| JS Firebase SDK (compare-types) | Repo root `firebase` dependency — [`.github/scripts/compare-types/`](../../.github/scripts/compare-types/) does **not** declare `firebase-tools`; it uses root `node_modules/firebase` for SDK types only | +| JS Firebase SDK (compare-types) | Repo root `firebase` dependency — [`.github/scripts/compare-types/`](../../.github/scripts/compare-types) does **not** declare `firebase-tools`; it uses root `node_modules/firebase` for SDK types only | | Native test apps | `tests/android/build.gradle`, `tests/android/app/build.gradle`, `tests/ios/Podfile`, `tests-macos/macos/Podfile` | Verify CLI: `node_modules/.bin/firebase --version`. @@ -267,7 +267,7 @@ Post-deploy verification: `./verify-firestore-indexes.sh` (optional env: `FIREST GHA e2e: -1. Emulator — [running e2e § Rules #2](running-e2e.md#rules) (`tests:emulator:start-ci` in CI) +1. Emulator — [running e2e § Rules #2](e2e/rules.md#rules) (`tests:emulator:start-ci` in CI) 2. Build + Detox run — [running e2e](running-e2e.md) (needs network for `pipelines-e2e` cloud) 3. Emulator cache under `~/.cache/firebase/emulators` — key/saver policy: [CI workflows index](/ci-workflows/index.md) diff --git a/okf-bundle/testing/index.md b/okf-bundle/testing/index.md index bdddb8c764..d9244b45c4 100644 --- a/okf-bundle/testing/index.md +++ b/okf-bundle/testing/index.md @@ -1,14 +1,62 @@ # Testing -* [Agent command policy](agent-command-policy.md) — **read before any shell command** (install, prepare, validation, e2e, Expo example typecheck + documented-path iOS **link** + per-module duplicate ObjC class check (`yarn test-expo-fixture:ios:dupes`), RN CLI prebuilt RNCore iOS **build**; not Detox); **`yarn` / `yarn lerna:prepare` must exit 0 before any other command**; [install / patch / fmt gate](agent-command-policy.md#install-patch-fmt-gate-blocking) before native `:build` +Owner of every testing topic in the bundle. Pick a file by task; to pick by change type, start at [routes](../routes/index.md). Each split doc's old path (for example `running-e2e.md`) stays as a short catalog that keeps every old `#anchor`. + * [Documentation/commit policy](../documentation-policy.md) — public vs ephemeral vs private, OKF scan, [Efficiency](../documentation-policy.md#efficiency) -* [Change authoring workflow](change-authoring-workflow.md) — verified product change loop (unit-focused → `documentation?` → area-focused `independent-review` → commit); [§ gates](change-authoring-workflow.md#gates); [§ frozen tree](change-authoring-workflow.md#frozen-tree); [§ quality standards](change-authoring-workflow.md#quality-standards); [§ validation evidence (blocking)](change-authoring-workflow.md#validation-evidence-blocking); [§ commit](change-authoring-workflow.md#commit); [coverage evidence package](coverage-design.md#coverage-evidence-package) -* [compare-types justification bar](../../.github/scripts/compare-types/README.md#justification-bar) — firebase-js-sdk type/API drift justification * [Iteration vocabulary](iteration-vocabulary.md) — work type, tier, and queue field identifiers -* [Running e2e tests](running-e2e.md) — canonical e2e commands; start here for `:test-cover`; [§ agent rule (read first)](running-e2e.md#agent-rule-read-first); [§ test-app native modules](running-e2e.md#test-app-native-modules) (`NativeRNFBTesting` / `RNFBTestingMessaging` probes vs package `Coverage` flush); [§ platform coverage gate](running-e2e.md#platform-coverage-gate-blocking); [§ slot lifecycle](running-e2e.md#slot-lifecycle); [§ slot index](running-e2e.md#e2e-slot-index); [§ iOS slot simulators](running-e2e.md#ios-slot-simulators) (exact `.detoxrc` base or fail; [migration](running-e2e.md#ios-slot-simulator-migration)); [§ infrastructure change bar](running-e2e.md#e2e-infrastructure-change-bar); [§ startup fail-fast poll](running-e2e.md#startup-fail-fast-poll) -* [E2e parallel design](e2e-parallel-design.md) — why resources collide, parameterization, coordinator rollout (commands stay in running-e2e) -* [Validation checklist](validation-checklist.md) — validation command sequence; [§ OKF bundle review](validation-checklist.md#okf-bundle-review) (frozen `independent-review` when those files are in the tree) -* [Coverage design](coverage-design.md) — coverage policy, Codecov/native gates (merged Android `jacocoTestReport`; iOS unit + e2e LCOV); [§ coverage expectations (policy)](coverage-design.md#coverage-expectations-policy); [§ evidence package](coverage-design.md#coverage-evidence-package); [§ react-native-coverage](coverage-design.md#react-native-coverage) (package `flush()`; probe modules in [running e2e](running-e2e.md#test-app-native-modules)); [§ coverage migration rollback](coverage-design.md#coverage-migration-rollback); [iOS Ruby SimpleCov](coverage-design.md#ios-ruby-simplecov) (`yarn tests:ios:ruby`, flag `ios-ruby`) +* [compare-types justification bar](../../.github/scripts/compare-types/README.md#justification-bar) — firebase-js-sdk type/API drift justification + +## Agent commands: [agent-command-policy.md](agent-command-policy.md) + +**Read the [agent rule](agent-command-policy.md#agent-rule-read-first) before any shell command.** **`yarn` / `yarn lerna:prepare` must exit 0 before any other command.** Registry split by domain: + +* [core](commands/core.md) — install, prepare ([§ prepare must finish first](commands/core.md#prepare-must-finish-first)), TS/JS validation, `yarn lint:js`, test-expo typecheck, read-only `gh`, `yarn frog`; shell traps ([§ agent shell is zsh](commands/core.md#agent-shell-is-zsh)) +* [docs](commands/docs.md) — docs lint, docs snippet type-check, docs member check +* [native](commands/native.md) — Android Java / Kotlin format, Ruby lint and tests, JVM / XCTest unit tests, [TurboModule codegen](commands/native.md#turbomodule-codegen) +* [native build gate](commands/native-build-gate.md) — [install / patch / fmt gate](commands/native-build-gate.md#install-patch-fmt-gate-blocking) before native `:build` +* [fixtures](commands/fixtures.md) — Expo example + documented-path iOS **link**, launch smoke, per-module duplicate ObjC class check (`yarn test-expo-fixture:ios:dupes`), RN CLI prebuilt RNCore iOS **build** (not Detox) +* [e2e](commands/e2e.md) — `yarn tests:*`, pre-flight, slots, coverage post-process, [App Check e2e helper secret](commands/e2e.md#app-check-e2e-helper-secret) +* [forbidden (always)](commands/forbidden.md) · [constraints block](commands/constraints.md#command-constraints) (condensed, for prompts) + +## Change authoring: [change-authoring-workflow.md](change-authoring-workflow.md) + +Verified product change loop (unit-focused → `documentation?` → area-focused `independent-review` → commit). + +* [loop, work types, tiers](authoring/loop.md) — [§ primary loop](authoring/loop.md#primary-loop), [§ work types](authoring/loop.md#work-types) +* [gates and evidence](authoring/gates.md) — [§ gates](authoring/gates.md#gates); [§ validation evidence (blocking)](authoring/gates.md#validation-evidence-blocking); [§ forbidden shortcuts](authoring/gates.md#forbidden-shortcuts) +* [quality standards](authoring/quality-standards.md) — acceptable exceptions, review findings, language port contracts +* [implementation pass](authoring/implementation.md) — host rule, inner loop, [platform SDK bridge contracts](authoring/implementation.md#platform-sdk-bridge-contracts), [e2e diagnosis escalation](authoring/implementation.md#e2e-diagnosis-escalation), harness narrowing +* [frozen review and commit](authoring/review-and-commit.md) — [§ frozen tree](authoring/review-and-commit.md#frozen-tree); [§ independent-review](authoring/review-and-commit.md#independent-review); [§ commit](authoring/review-and-commit.md#commit) + +## Validation: [validation-checklist.md](validation-checklist.md) + +* [when to run what](validation/work-types.md) · [prepare, compile, types](validation/compile-and-types.md) · [Jest](validation/jest.md) · [native unit tests](validation/native-unit.md) +* [lint and formatting](validation/lint.md) (blocking, by tree) · [docs lint](validation/docs-lint.md) ([§ docs.page link check](validation/docs-lint.md#docs-page-link-check)) +* [Expo, RN CLI fixtures and e2e](validation/fixtures-and-e2e.md) · [OKF bundle review](validation/okf-review.md#okf-bundle-review) (frozen `independent-review` when those files are in the tree) +* [evidence package and handoff checklist](validation/evidence-and-handoff.md) — [§ validation evidence package](validation/evidence-and-handoff.md#validation-evidence-package) + +## E2e: [running-e2e.md](running-e2e.md) + +Canonical e2e commands; start here for `:test-cover`. [§ agent rule (read first)](running-e2e.md#agent-rule-read-first). + +* Before the first run: [prerequisites](e2e/prerequisites.md) · [rules](e2e/rules.md) ([§ test-app native modules](e2e/rules.md#test-app-native-modules): `NativeRNFBTesting` / `RNFBTestingMessaging` probes vs package `Coverage` flush; [§ infrastructure change bar](e2e/rules.md#e2e-infrastructure-change-bar)) · [gates and tiers](e2e/gates.md) ([§ harness narrowing gate](e2e/gates.md#harness-narrowing-gate-blocking); [§ platform coverage gate](e2e/gates.md#platform-coverage-gate-blocking)) · [narrowing and harness overrides](e2e/narrowing.md) +* Every run: [pre-flight](e2e/preflight.md) + [host clear](e2e/preflight-host-clear.md) · [running one iteration](e2e/run-loop.md) · [startup fail-fast poll](e2e/startup-fail-fast.md#startup-fail-fast-poll) +* On failure: [recovery and diagnosis](e2e/recovery.md) ([§ stalled run detection](e2e/recovery.md#stalled-run-detection)) · [platform troubleshooting](e2e/platform-troubleshooting.md) +* Parallel and full: [environment and slot topology](e2e/environment.md) ([§ slot lifecycle](e2e/environment.md#slot-lifecycle); [§ slot index](e2e/environment.md#e2e-slot-index)) · [slotted parallel](e2e/slotted-parallel.md) · [slot env variables](e2e/slot-env-variables.md) · [iOS slot simulators](e2e/slot-devices.md#ios-slot-simulators) (exact `.detoxrc` base or fail; [migration](e2e/slot-devices.md#ios-slot-simulator-migration)) · [full suite](e2e/full-suite.md) +* [E2e parallel design](e2e-parallel-design.md) — why resources collide, parameterization, coordinator rollout (commands stay in the e2e files) + +## Coverage: [coverage-design.md](coverage-design.md) + +Policy, Codecov / native gates (merged Android `jacocoTestReport`; iOS unit + e2e LCOV). The folder is `code-coverage/` because the repo `.gitignore` ignores every folder named `coverage`. + +* [policy](code-coverage/policy.md) — [§ coverage expectations (policy)](code-coverage/policy.md#coverage-expectations-policy); [§ evidence package](code-coverage/policy.md#coverage-evidence-package) +* [reading coverage locally](code-coverage/local.md) — [iOS Ruby SimpleCov](code-coverage/local.md#ios-ruby-simplecov) (`yarn tests:ios:ruby`, flag `ios-ruby`) +* [unit and TS e2e pipelines](code-coverage/pipelines.md) · [native e2e (Jacoco, LLVM)](code-coverage/native.md) · [Codecov (CI)](code-coverage/codecov-ci.md) +* [test-app modules](code-coverage/test-app-modules.md) — [§ react-native-coverage](code-coverage/test-app-modules.md#react-native-coverage) (package `flush()`; probe modules in [e2e rules](e2e/rules.md#test-app-native-modules)) +* [migration rollback](code-coverage/migration-rollback.md#coverage-migration-rollback) · [invariants and troubleshooting](code-coverage/invariants-and-troubleshooting.md) + +## Decisions and environment + * [Android unit testing ADR](android-architecture-decisions.md#androidtest-ad-1) — JUnit-first; Robolectric when Android APIs are required; omit `@Config` / `sdk` unless proven (`AndroidTest-AD-1`) * [iOS unit testing ADR](ios-architecture-decisions.md#iostest-ad-1) — macOS/host-first in-package XCTest (Foundation-only, or [stub headers](ios-architecture-decisions.md#iostest-ad-1-stub-headers) for React/Firebase/UIKit); Simulator only if UIKit required (`IosTest-AD-1`) * [Published types ADR](architecture-decisions.md) — attw / Expo plugin decisions (`Types-AD-*`); [Types-AD-5](architecture-decisions.md#types-ad-5--pack-ignores-nested-ios-unit-build-trees--accepted) (attw allowlisted pack stage) diff --git a/okf-bundle/testing/ios-architecture-decisions.md b/okf-bundle/testing/ios-architecture-decisions.md index 1bb8f5b8d3..b2b1803b13 100644 --- a/okf-bundle/testing/ios-architecture-decisions.md +++ b/okf-bundle/testing/ios-architecture-decisions.md @@ -45,7 +45,7 @@ Prefer a tiny **in-package xcodeproj** that compiles the real production sources **Why:** Detox/Jet e2e cannot reliably drive lock-only pointer maps, unique-put collisions, `takeAll` invalidate paths, or native paths gated behind a flag the test app leaves off. Host XCTest proves those contracts without a simulator. CocoaPods `test_spec` would pull the real React/Firebase pods into the unit graph; the Detox test app is an integration host, not a package unit harness. -**Do not** add a production `*Bridge` type solely so those tests can compile TurboModule collision/invalidate branches. Registry/HandleMap-style projects stay Foundation-only. TurboModule/Helper lines that only call Registry/HandleMap may stay uncovered — [coverage design](coverage-design.md#coverage-expectations-policy) (user-accepted exception). +**Do not** add a production `*Bridge` type solely so those tests can compile TurboModule collision/invalidate branches. Registry/HandleMap-style projects stay Foundation-only. TurboModule/Helper lines that only call Registry/HandleMap may stay uncovered — [coverage design](code-coverage/policy.md#coverage-expectations-policy) (user-accepted exception). @@ -66,7 +66,7 @@ A package whose logic lives in TurboModule or delegate files (not a separable Re Example: `RNFBMessagingUnitTests`, see [messaging index](../packages/messaging/index.md#unit-tests). -**Not a substitute for area e2e:** In-package XCTest does **not** replace [platform coverage gate](running-e2e.md#platform-coverage-gate-blocking) delivery/integration e2e on platforms where the module loads. +**Not a substitute for area e2e:** In-package XCTest does **not** replace [platform coverage gate](e2e/gates.md#platform-coverage-gate-blocking) delivery/integration e2e on platforms where the module loads. **Podspec:** Exclude `ios/*UnitTests/**/*` from package `source_files` so XCTest sources (and nested trees such as `HostStubs/`) are not compiled into the production pod. CocoaPods `FileList` uses `FNM_PATHNAME`; the shallower `ios/*UnitTests/**` glob does **not** match nested paths under the unit-test directory. diff --git a/okf-bundle/testing/iteration-vocabulary.md b/okf-bundle/testing/iteration-vocabulary.md index 61f4110a68..756c437972 100644 --- a/okf-bundle/testing/iteration-vocabulary.md +++ b/okf-bundle/testing/iteration-vocabulary.md @@ -32,7 +32,7 @@ Glossary of **string identifiers** and **work-queue field names** used across OK | `commit` | Stage and create one commit | | `pre-merge-validation` | Branch-wide merge gate | -When to use each work type, validation tier, edit policy, and commit rules: [change authoring § work types](change-authoring-workflow.md#work-types). +When to use each work type, validation tier, edit policy, and commit rules: [change authoring § work types](authoring/loop.md#work-types). ## Validation tier identifiers @@ -42,7 +42,7 @@ When to use each work type, validation tier, edit policy, and commit rules: [cha | `area-focused` | Full loaded package spec(s) for the change area | | `full` | Unfocused — all modules and platforms | -E2e scope, narrowing, and harness rules: [change authoring § validation tiers](change-authoring-workflow.md#validation-tiers), [running e2e § validation tiers](running-e2e.md#e2e-validation-tiers-unit-focused-area-focused-full). +E2e scope, narrowing, and harness rules: [change authoring § validation tiers](authoring/loop.md#validation-tiers), [running e2e § validation tiers](e2e/gates.md#e2e-validation-tiers-unit-focused--area-focused--full). ## Gate identifiers @@ -51,13 +51,13 @@ Work queues use these **field names** (values: `open` | `closed`): | Field | Tracks | |-------|--------| | `implementation_gate` | `implementation` work type complete | -| `coverage_evidence_gate` | [Coverage evidence package](coverage-design.md#coverage-evidence-package) complete with verdict line when lib/native bridge touched; otherwise `n/a` (treat as closed) | +| `coverage_evidence_gate` | [Coverage evidence package](code-coverage/policy.md#coverage-evidence-package) complete with verdict line when lib/native bridge touched; otherwise `n/a` (treat as closed) | | `review_gate` | `independent-review` work type complete | -| `commit_gate` | Durable commit exists for the item **after** prior gates closed with [validation evidence](change-authoring-workflow.md#validation-evidence-blocking) | +| `commit_gate` | Durable commit exists for the item **after** prior gates closed with [validation evidence](authoring/gates.md#validation-evidence-blocking) | -What closes each gate, trust rules, and loop transitions: [change authoring § gates](change-authoring-workflow.md#gates). `commit_subject` match and staging: [change authoring § commit](change-authoring-workflow.md#commit). +What closes each gate, trust rules, and loop transitions: [change authoring § gates](authoring/gates.md#gates). `commit_subject` match and staging: [change authoring § commit](authoring/review-and-commit.md#commit). -`commit_gate` closes when a durable commit exists whose subject matches the row's `commit_subject`, **after** `implementation_gate`, `coverage_evidence_gate` (when required), and `review_gate` closed with [validation evidence](change-authoring-workflow.md#validation-evidence-blocking). +`commit_gate` closes when a durable commit exists whose subject matches the row's `commit_subject`, **after** `implementation_gate`, `coverage_evidence_gate` (when required), and `review_gate` closed with [validation evidence](authoring/gates.md#validation-evidence-blocking). Items may also be marked **`blocked`** when a dependency gate is open elsewhere. @@ -74,7 +74,7 @@ Ephemeral work queues may record: | `coverage_evidence_gate` | `open` \| `closed` \| `n/a` | | `review_gate` | `open` \| `closed` | | `commit_gate` | `open` \| `closed` | -| `commit_subject` | Planned or landed **first line** of the item's focused commit (Conventional Commits subject). Staging, match, and no-SHA rules: [change authoring § commit](change-authoring-workflow.md#commit). | +| `commit_subject` | Planned or landed **first line** of the item's focused commit (Conventional Commits subject). Staging, match, and no-SHA rules: [change authoring § commit](authoring/review-and-commit.md#commit). | | `blocked` | Item or dependency blocked until named gate closes | Queues record **state** (gate fields and `next_work_type`). Public OKF owns the terms, gates, and commands. diff --git a/okf-bundle/testing/local-ios-e2e-reproduction.md b/okf-bundle/testing/local-ios-e2e-reproduction.md index 6f0e0ac0ad..0234142ce4 100644 --- a/okf-bundle/testing/local-ios-e2e-reproduction.md +++ b/okf-bundle/testing/local-ios-e2e-reproduction.md @@ -42,7 +42,7 @@ An **iOS 26.5** simulator runtime (or Tart images seeded with **Xcode 26.5**) ma It does **not** satisfy: - CI **`configure-apple-ci.sh`** gates (stable **Xcode major 27**, default **iOS 27.0** runtime when required). -- **`yarn test-expo:ios:launch-smoke`** / **`yarn test-rn-bare:ios:launch-smoke`** UIScene gates on the pinned **iOS 27** runtime ([agent command policy](agent-command-policy.md); [validation checklist § bare](validation-checklist.md#rn-cli-prebuilt-rncore-ios-compile-not-e2e)). +- **`yarn test-expo:ios:launch-smoke`** / **`yarn test-rn-bare:ios:launch-smoke`** UIScene gates on the pinned **iOS 27** runtime ([agent command policy](agent-command-policy.md); [validation checklist § bare](validation/fixtures-and-e2e.md#rn-cli-prebuilt-rncore-ios-compile-not-e2e)). Do not cite “green on iOS 26.5” as closure for Xcode 27 / iOS 27 / UIScene work. @@ -61,4 +61,4 @@ Manifest pins: `scripts/tart/manifests/golden-expected.json` (expected) vs `gold ## Related - [E2e parallel design § Tart layers](e2e-parallel-design.md#rnfb-mellifera-tart-layers) — Tart is not the RNFB e2e product -- [Running e2e § Apple host toolchain](running-e2e.md#apple-host-toolchain-local) — local Xcode 27 + Device Hub expectations +- [Running e2e § Apple host toolchain](e2e/prerequisites.md#apple-host-toolchain-local) — local Xcode 27 + Device Hub expectations diff --git a/okf-bundle/testing/running-e2e.md b/okf-bundle/testing/running-e2e.md index 1373098933..78c9e16c79 100644 --- a/okf-bundle/testing/running-e2e.md +++ b/okf-bundle/testing/running-e2e.md @@ -3,1154 +3,56 @@ type: Reference title: Running e2e tests description: The canonical, minimal command set for running React Native Firebase e2e tests on every platform. tags: [testing, e2e, detox, jet, ios, android, macos, coverage] -timestamp: 2026-09-10T00:00:00Z +timestamp: 2026-12-02T00:00:00Z --- # Running e2e tests Canonical local e2e commands. Use **only** these commands. `-ci` variants are CI-only. Avoid `:test-cover-reuse`, `:test-cover-and-process`, `:test-reuse` (stale native risk). If another doc disagrees, this wins. -> All e2e how-to lives here; other docs link here — they do **not** define alternate entrypoints or commands. +> All e2e how-to lives here and in the `e2e/` files listed below; other docs link here — they do **not** define alternate entrypoints or commands. ## Agent rule (read first) -**Never invoke the test runner (Jet), Detox, Metro, or emulators directly.** Use **only** the repo-root `yarn tests:*` commands defined in this document (for example `yarn tests:packager:jet`, `yarn tests:emulator:start`, `yarn tests::test-cover`). Do not run `jet`, `npx jet`, `yarn jet`, `detox test`, `cd tests && …`, or ad-hoc Metro/emulator start commands. When another doc mentions e2e, Jet, Detox, or pre-flight, follow the link to this runbook — do not infer commands from log output or implementation details. - -Install, prepare, validation, the workspace Expo example / documented-path iOS **link** closer (`yarn test-expo:ios:link`), and the RN CLI prebuilt RNCore iOS **build** fixture (`yarn test-rn-bare:ios:build`) are **not** in this doc — they live in [agent command policy](agent-command-policy.md). Those commands are **not** Detox e2e. E2e stays exclusively `yarn tests:*`. **Before any native `:build`:** [install / patch / fmt gate](agent-command-policy.md#install-patch-fmt-gate-blocking) (root `yarn` exit 0 + fmt **≥ 12.1.0**). - -## Prerequisites (once per checkout) - -```bash -yarn # repo root — exit 0 required. Applies .yarn/patches (jet, mocha-remote-*, detox) and tests/tests-macos patch-package (incl. tests/patches/detox+20.51.0.patch) — [install / patch / fmt gate](agent-command-policy.md#install-patch-fmt-gate-blocking) -``` - -**Ruby `>= 3.3.1` with Bundler on `PATH`** for iOS and macOS work (CocoaPods and `yarn tests:ios:ruby`). macOS's system Ruby 2.6 is too old; root `yarn` then skips the gems with one `ruby:install:` line and still exits 0. Setup: [CONTRIBUTING § Ruby for iOS and macOS work](../../CONTRIBUTING.md#ruby-for-ios-and-macos-work). - -**Before `yarn tests:ios:build` / `yarn tests:android:build`:** [install / patch / fmt gate](agent-command-policy.md#install-patch-fmt-gate-blocking) (root `yarn` exit 0 + fmt **≥ 12.1.0**). - -**Keep host toolchains current.** Android Studio / emulator and Xcode / CocoaPods are expected to track upstream, not be pinned indefinitely. A stale Android Emulator (e.g. 36.2.12.0) can lack CLI flags newer Detox patches rely on (`-crash-report-mode`, requires **≥ 37**, see [detox-patches.md](../ci-workflows/detox-patches.md)) and fail at spawn rather than at test time. When a patch or e2e step breaks only on your host, update the toolchain first — don't reach for a runtime capability probe as the default fix. - -**JDK 21+ on `PATH`** for `yarn tests:emulator:start`: `firebase-tools` refuses older Java (`firebase-tools no longer supports Java version before 21`). Same host fix as [`yarn lint:android` § needs JDK 21+](agent-command-policy.md#android-java-format). - - - -### Apple host toolchain (local) - -Align the Mac with [iOS CI workflows § Apple CI toolchain](../ci-workflows/ios.md#apple-ci-toolchain-xcode-27) and [test app dependency pins](test-app-dependency-pins.md#current-pins): - -| Expectation | Local default | -|-------------|----------------| -| **Xcode** | **27** stable (beta fails CI gate; match `xcodebuild -version` major to CI) | -| **iOS Simulator runtime** | **`iOS 27.0`** — export `RNFB_IOS_SIM_RUNTIME` if your install uses a different label; `yarn tests:e2e:setup-ios-sims` creates devices on that runtime | -| **Simulator device type** | **`iPhone 17`** (serial device and slot base). If the runtime does not support it (`simctl create` fails `Incompatible device`), export `RNFB_IOS_BASE_SIMULATOR` to a device type that runtime lists as supported, for setup and the Detox run alike | -| **`xcbeautify`** | Required on `PATH`: Detox iOS `build` pipes `xcodebuild` through it (`xcbeautify: command not found` otherwise). CI version/install: [iOS CI § pinned Homebrew utilities](../ci-workflows/ios.md#pinned-homebrew-utilities) | -| **Simulator UI** | **Device Hub** from the selected Xcode bundle (`…/Applications/DeviceHub.app`). Do not use `open -a Simulator` / `open -a Device Hub` for CI-parity boot paths — see [iOS CI § simulator reliability](../ci-workflows/ios.md#simulator-reliability) | -| **Mobile e2e fixtures** | **RN 0.88.0-rc.3**, **Expo 58** (`test-expo/`), same RN line in `tests/` / `test-rn-bare/` — test-fixture pins only; do not document higher consumer Xcode/RN floors than product metadata | - -**iOS 26.5** simulators or hosts are **runtime-differential context only** (e.g. Metro hostname quirks in [iOS CI § issue 5](../ci-workflows/ios.md#5-metro-unresponsive-at-launch--waitforactive-hang-active-app)). They do **not** replace **iOS 27** for UIScene launch-smoke gates or Xcode 27 closure — [local Tart lab § not proof](local-ios-e2e-reproduction.md#ios-26-5-not-proof). - - - -**Physical iOS device builds need the Invertase Apple team.** `tests/ios/testing.xcodeproj` uses automatic signing with `DEVELOPMENT_TEAM = YYX2P3XVJ7` and paid-team entitlements (push, Sign in with Apple, associated domains, keychain group), so a device build on a host without that team fails with `No Account for Team "YYX2P3XVJ7"` / `No profiles for 'io.invertase.testing' were found`. Simulators are unaffected. Options: add an Apple ID that belongs to team `YYX2P3XVJ7` in Xcode → Settings → Accounts, or apply a local-only, never-committed bundle-id/team override (needs a matching `GoogleService-Info.plist` and stripped entitlements). Physical-device runs: [agent command policy § physical-device runs](agent-command-policy.md#physical-device-runs). - -**Tart VM lab** (`scripts/tart/`) is [temporarily suspended](local-ios-e2e-reproduction.md#status-suspended); use this runbook, not `run-ephemeral.sh`, for contributor e2e. - -## Rules - -1. **Packager** (background): - -```bash -# iOS / Android -yarn tests:packager:jet - -# macOS (Metro from tests-macos/, shared JS harness under tests/) -yarn tests:macos:packager:jet -``` - -Do **not** use the mobile packager for macOS Jet (or vice versa): each app has its own Metro project root after the `tests-macos/` split. - - - -**Backgrounding (agents):** a trailing `&` inside a single shell call does **not** survive that call returning — the command prints a PID and the process is gone (observed twice with `yarn tests:macos:packager:jet`: one `watchman watch-del` line in the log, nothing listening on `:8081`). Start the packager as a properly backgrounded long-running job instead. The packager script **exits 0 after daemonizing Metro**, so a *completed* job is the success case, not a crash — confirm with the `/status` check in [services ready](#2-services-ready) rather than restarting it. - -2. **Emulators** (background, always): - -```bash -yarn tests:emulator:start -``` - -3. **Rebuild when needed** - - **Before any native `:build`:** [install / patch / fmt gate](agent-command-policy.md#install-patch-fmt-gate-blocking) — root `yarn` exit 0 + fmt podspec **≥ 12.1.0**. Missing this gate → Apple Clang 21 consteval failures on unpatched fmt **11.0.2**. - - Native changed → `yarn tests:ios:build` / `yarn tests:android:build` before e2e. macOS uses firebase-js-sdk only — no native rebuild. - - **Apple `:build` compiles only.** `yarn tests:ios:build` / `yarn tests:macos:build` do not run CocoaPods. Full e2e / test process **requires** `yarn tests:ios:pod:install` or `yarn tests:macos:pod:install` as a **separate prior step** before the matching `:build` (after codegen / podspec / native Apple changes, and in [slot lifecycle](#slot-lifecycle) / `run-full-tests.sh` / CI). A bare `:build` without pod install is allowed when pods are already installed and you only need a compile. - - **Committed codegen / generated native artifacts count as native** — any change under `packages/*/ios/generated/**` or `packages/*/android/**/generated/**` (including wipe-then-regen orphan deletions), or TurboModule **codegen / spec / podspec / native shell**, is a native change: rebuild + [platform coverage](#platform-coverage-gate-blocking) e2e on iOS and Android. **`yarn codegen:verify` is not a substitute** for `:test-cover` ([change authoring § forbidden shortcuts](change-authoring-workflow.md#forbidden-shortcuts)). - - `packages/*/lib/**` changed → **`yarn lerna:prepare` must run to completion (exit 0) before anything else** — Metro serves `dist/module/**`, not `lib/**`. See [prepare completion gate](#prepare-completion-gate-blocking) and [agent command policy § prepare must finish first](agent-command-policy.md#prepare-must-finish-first). After prepare finishes, restart the **matching** packager when Metro was already running ([packager reset-cache](#packager-reset-cache-eaddrinuse)). - - TurboModule **codegen / spec / podspec / native shell** changed → same as native changed, plus regen codegen ([agent command policy § TurboModule codegen](agent-command-policy.md#turbomodule-codegen); wipe-then-regen [NewArch-AD-22](../new-architecture/architecture-decisions.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)) when specs changed; if app loads with Metro redbox `Requiring unknown module "undefined"`, see [TurboModule stale toolchain](#turbomodule-stale-toolchain-blocking). - - **JS bundle (debug):** all platforms (iOS, Android, macOS) load JS from Metro; only **release** builds pre-bundle/embed JS. `lib/**` edits alone do not require `:build` — use the [prepare completion gate](#prepare-completion-gate-blocking) and Metro restart above. - - **TS coverage:** run `:build` before `:test-cover` on iOS/Android so Istanbul + patched test-runner coverage instrumentation is in the debug native app (bundle still from Metro). After test-runner patch changes, restart the packager with `yarn tests:packager:jet-reset-cache` ([packager reset-cache](#packager-reset-cache-eaddrinuse)). - -4. **Always run with coverage:** - -```bash -yarn tests:ios:test-cover -yarn tests:android:test-cover -yarn tests:macos:test-cover -``` - -Clean `:build` + `:test-cover` each time — not reuse variants. - -5. **Report locations** — [Coverage design](coverage-design.md). Android CI also runs `yarn tests:android:unit` (JVM) before Detox; post-e2e produces merged **`jacocoTestReport`** (unit + e2e) — details there, not duplicated here. - -6. **One e2e at a time (default)** — never overlap `:test-cover` runs on one host unless each run uses a distinct port/device slot via [configurable e2e environment](#configurable-e2e-environment). Serial runs share Metro `:8081` and the test-runner WebSocket port (default **8090**); parallel runs race on coverage/device/emulator state without slotted env. Every run starts after [clean pre-flight](#pre-flight-is-the-host-clear-to-start). Log triage for port/orchestration markers: [test-runner host orchestration](#test-runner-host-orchestration-log-triage-only). - -7. **No source edits during e2e** — wait/cancel cleanly before editing `packages/**`, `tests/**`, or bundle-affecting OKF docs. Saves can hot reload/rebundle and invalidate tests/coverage. - - - -## Test-app native modules (do not conflate) - -Coverage flush is **package-owned**. Test-app modules are **integration probes only** — do not call them for flush. - -| Module | Kind | Purpose | Owner | -|--------|------|---------|-------| -| `Coverage` (`react-native-coverage`) | Package TurboModule | `flush()` from Jet `after` only | [coverage design § react-native-coverage](coverage-design.md#react-native-coverage) | -| `NativeRNFBTesting` | Test-app TurboModule | E2e probes (e.g. `completesNonFCMRemoteNotification`) | **this section** | -| `RNFBTestingMessaging` | Test-app `RCTBridgeModule` | iOS messaging delegate probe (`messagingPreservesExistingDelegate`) | **this section** | - -**`NativeRNFBTesting` (this section)** - -- **Spec:** `tests/specs/NativeRNFBTesting.ts` -- **iOS:** `tests/ios/testing/RNFBTestingTurboModule.{h,mm}` -- **Android:** `tests/android/app/src/main/java/com/invertase/testing/NativeRNFBTesting.kt` — unsupported methods **resolve `false`** -- **JS:** `getRNFBTesting()` in `packages/app/e2e/helpers.js` via `TurboModuleRegistry.get('NativeRNFBTesting')` -- **Probes:** `completesNonFCMRemoteNotification` (iOS); `serializeMessagingUserInfo` (iOS — `RNFBMessagingSerializer`); `messagingStoreSupportsDisabledStorage` (Android). Cross-platform methods resolve `false` / empty map on the unsupported platform. iOS `messagingPreservesExistingDelegate` lives on `RNFBTestingMessaging` (below), not this TurboModule. -- Production packages must **not** ship this TurboModule (test-app only). - -**`RNFBTestingMessaging` (this section)** - -- **iOS:** `tests/ios/testing/RNFBTestingMessagingModule.m` — `NativeModules.RNFBTestingMessaging.messagingPreservesExistingDelegate()` -- Standalone so the coverage TurboModule stays product-neutral ([coverage design § react-native-coverage](coverage-design.md#react-native-coverage)). - -**Probe hits in native coverage:** Messaging e2e `getRNFBTesting().completesNonFCMRemoteNotification()`, `getRNFBTesting().serializeMessagingUserInfo(...)`, and `NativeModules.RNFBTestingMessaging.messagingPreservesExistingDelegate()` exercise product sources (for example `RNFBMessaging+AppDelegate.m` non-FCM `completionHandler`, `RNFBMessagingSerializer.m`). Android e2e `getRNFBTesting().messagingStoreSupportsDisabledStorage()` exercises `ReactNativeFirebaseMessagingStoreImpl` disabled-storage paths. After iOS `:test-cover` and `yarn tests:ios:test:process-coverage`, iOS probe lines appear as hits in `coverage/ios-native/lcov.info` (Android probe hits land in Jacoco). Record them in the [coverage evidence package](coverage-design.md#coverage-evidence-package); passing probes are not a substitute for that artifact. Test-app vs library codegen (not committed; wipe derived `tests/ios/build/generated/ios`; gitignore `tests/ios/Package.swift` and sibling app dumps): [NewArch-AD-5](../new-architecture/architecture-decisions.md#newarch-ad-5--commit-generated-code--accepted). - - - -## E2e infrastructure change bar - -Permanent e2e-harness / runbook / host-script changes need **reproduced causation**, not a guessed flag. - -| Term | Meaning | -| ----------------- | ----------------------------------------------------------------------------------------------------------------------- | -| **Negative test** | With the change **absent**, the failure mode **reproduces reliably** (same command, same log signature). | -| **Positive test** | With the change **present**, that failure is gone (or gated). | -| **Non-slot test** | Unslotted serial defaults still work (`:8081` / `:8090` / `:8080`…, `TestingAVD`, `iPhone 17`, `io.invertase.testing`). | - -Also required: **one owner** — behavior lives in the canonical `yarn tests:*` command in this doc, not a parallel helper lifecycle. - -Unproven “maybe flake” ideas go on the **ephemeral work queue** only. Do not land them in product until they pass this bar. Do not change native **build settings** (for example Swift explicit modules) to paper over host races — e2e `:build` must stay representative of a real app build. - -## Serialized e2e loops (shared dev host) - -Use [validation tiers](#e2e-validation-tiers-unit-focused-area-focused-full): **unit-focused**, **area-focused**, **full**. Match tier to [work type](change-authoring-workflow.md#work-types). **Serial default:** one unslotted `:test-cover` from clean [pre-flight](#pre-flight-is-the-host-clear-to-start). Slotted cross-platform concurrency: [parallel e2e topology](#parallel-e2e-topology). Log long output; upstream gets exit code + short summary. - -**Policy:** [OKF documentation and commit policy](../documentation-policy.md) — public vs ephemeral vs private; [Efficiency](../documentation-policy.md#efficiency). **Terms:** [iteration vocabulary](iteration-vocabulary.md). - -### How a platform run is structured (Android/iOS) - -**Internal only — do not invoke sub-commands.** Wait on the single repo-root `:test-cover` command; Detox/Jest and the test runner start automatically. - -```text -yarn tests:android:test-cover # only command you run - └─ (internal) detox → jest → firebase.test.js → test runner on :8090 → app -``` - -macOS: `yarn tests:macos:test-cover` only — same `:8090` transport, no Detox. - -**Do not poll `pgrep`, `detox`, process names, or `:8090` for completion.** They match stale wrappers, orphans, zombies, and contention. Tee-log [startup fail-fast](#startup-fail-fast-poll) is required — that is log-marker polling, not process polling. - - - - -#### Test-runner host orchestration (log triage only) - -**No commands to run from this section** — for interpreting `:test-cover` logs and CI artifacts only. Patch workflow: [detox-patches.md](../ci-workflows/detox-patches.md#updating-the-jet-patch-headless). CI triage: [iOS orchestration](../ci-workflows/ios.md#e2e-test-app-orchestration-detox--jet). - -| Port | Protocol | Role | -| -------------------------------------------------------------------------- | ---------------------------- | ---------------------------------------------------------- | -| **8090** (default `JET_REMOTE_PORT`) | WebSocket (`mocha-remote-*`) | App ↔ host test transport; drives Mocha in the app | -| **8091** (default `JET_REMOTE_PORT + 1`, override `RNFB_JET_CONTROL_PORT`) | HTTP POST only | Host ↔ test-runner **control plane** — not used by the app | - -**Why two ports** — Port 8090 is a WebSocket server (`ws` library). Plain HTTP `POST` to that socket (e.g. `/launch-ready`) gets **426 Upgrade Required** and can crash the runner with `ERR_HTTP_HEADERS_SENT` if a control handler shares the same HTTP stack. Control endpoints therefore live on a **separate** small HTTP server (`startControlHttpServer` in the test-runner patch). - -**Launch gate (orchestration race fix)** — `firebase.test.js` starts the test runner with `RNFB_JET_DEFER_RUN=1`. It listens on 8090 and **defers** `server.run()` until the host signals launch success: - -1. On Android, host force-stops both test packages and clears any stray **8090** listener before spawning Jet. -2. Host waits for TCP **8090**, then Metro (debug) if needed, then `launchAppWithRetry`. -3. Host `POST`s **`/orchestrate-state`** (`{ "phase": "launch-pending" | "launch-ok" | … }`) to the control port (best-effort diagnostics). -4. After `launchApp` succeeds, host `POST`s **`/launch-ready`** → test runner calls `server.run()` and the app may receive the mocha-remote `run` action. -5. Mocha tests must not start during a stuck or retried `launchApp`; on inner launch retry the host may kill and respawn the test runner before `terminateApp`/simulator reboot. -6. After `launch-ready`, `awaitJetExitWithStallGuard` aborts if Jet has not exited within `RNFB_JET_AWAIT_EXIT_STALL_MS` (default 20m). That stall is **retryable once** via Jet attempt 2 (iOS sim reboot); orchestrate state `stall-kill-jet`. - -**Log markers** — `[rnfb-e2e] orchestrate-state=…`, `[jet-control] deferring server.run until POST /launch-ready`, `[jet-control] launch-ready received`, `[jet-control] server.run starting`, `[jet-control] listening on http://…:8091`, `[jet-coverage] …`, `Jet client connected`, `orchestrate-state=stall-kill-jet`. - -**Pre-flight** — [Host-clear probes](#host-clear-probes) check **8090 only** (stray test-runner WS listener). **8091** may be open during a run; do not treat it as a stale-process signal by itself. - -#### CI iOS instrumentation (not local) - -GitHub Actions **Testing E2E iOS** adds CI-only steps local `:test-cover` does not run: pre-boot (`boot-simulator.sh`), one filtered **`sim-app.log`** stream, **`wait-for-load-settle.sh`** (threshold **20**) immediately before Detox, and optional video when `record_screens: true`. Host syslog and unfiltered simulator logs are **disabled** to reduce runner baseload. - -**Canonical owner:** [iOS CI baseload policy](../ci-workflows/ios.md#ci-baseload-policy-instrumentation). Artifact names and triage: [simulator logging and video](../ci-workflows/ios.md#simulator-logging-and-video-troubleshooting). - -### Running one iteration - -See also [startup fail-fast poll](#startup-fail-fast-poll) and [stalled run detection](#stalled-run-detection). - -1. [Pre-flight](#pre-flight-is-the-host-clear-to-start); if [host-clear probes](#host-clear-probes) fail, [pre-flight recovery](#pre-flight-recovery) first. -2. One `:test-cover` Shell command. Prefer `block_until_ms` large enough for a **healthy** run (~15m macOS, ~45–60m iOS/Android). `block_until_ms: 0` is OK **if** you then poll the **tee file** (or `notify_on_output` / AwaitShell `pattern`) per [startup fail-fast poll](#startup-fail-fast-poll). Do **not** poll `pgrep`, Detox, process names, or `:8090` for **completion**. If the Shell tool returns no exit status under default sandbox permissions, see [agent command policy § Shell sandbox / permissions](agent-command-policy.md#shell-sandbox-permissions) before retrying or concluding failure. -3. From repo root, tee the canonical command to a **unique** path (`/tmp/rnfb-e2e--.log`). **Never** overwrite a known-good 1×3 log. The short `/tmp/rnfb-e2e-.log` name is a human convenience only — agents must not reuse it across diagnostic items. - -```bash -yarn tests:android:test-cover 2>&1 | tee /tmp/rnfb-e2e-android-.log -yarn tests:ios:test-cover 2>&1 | tee /tmp/rnfb-e2e-ios-.log -yarn tests:macos:test-cover 2>&1 | tee /tmp/rnfb-e2e-macos-.log -``` - -Do not substitute other entrypoints — see [agent rule](#agent-rule-read-first). - -4. Completion — **prefer shell exit code** when the Shell tool returns one: `0` finished; non-zero failed/aborted. If the Shell tool is **aborted, interrupted, or returns no exit status**, do **not** conclude failure or incomplete from that alone — check the tee log footer for [done markers](#stalled-run-detection) before deciding; see [interrupted run](#interrupted-run-abort-killed-terminal-eaddrinuse-on-8090). -5. Parse log tail with **anchored** patterns; do not infer from processes. Do **not** use bare `rg 'passing|failing'` — it matches mid-suite test titles too (e.g. `accepts passing in…`), not just the Jest summary line: - -```bash -rg '^\s*\d+ (passing|failing)' /tmp/rnfb-e2e-.log | tail -2 -rg '^\s+\d+\)' /tmp/rnfb-e2e-.log # failure blocks, if any -rg 'jet-coverage.*merged .* before NYC' /tmp/rnfb-e2e-.log | tail -1 -rg 'Tests Complete' /tmp/rnfb-e2e-.log | tail -1 # optional, see below -``` - -**Done footers** (either is sufficient; both together is strongest): Jest summary `N passing` / `N failing`, **and** — on the coverage path — `[jet-coverage] merged … before NYC shutdown`. `✨ Tests Complete ✨` is **optional** — it is not always emitted on local macOS runs; never require it alone as the done signal. Other markers: `[rnfb-e2e] orchestrate-state=`, `[jet-control] launch-ready received`. - -6. Return only platform, exit code (or `unknown (tool aborted); log footer green|red` when the Shell tool gave no exit status — [interrupted run](#interrupted-run-abort-killed-terminal-eaddrinuse-on-8090)), pass/fail line, failing tests, log path, optional coverage-gap line. No full log upstream. -7. **Waiting on output:** during the first ~60s, `notify_on_output` / AwaitShell `pattern` **must** be the [startup-fail notify pattern](#startup-fail-fast-poll) (`E2E_STARTUP_FAILFAST_NOTIFY_PATTERN` in [`scripts/e2e/lib/e2e-startup-failfast.sh`](../../scripts/e2e/lib/e2e-startup-failfast.sh) — hard infra only, not `currentStatus` / status-query timeout). After a healthy launch, never pattern bare `passing` or bare `APP_STATUS` — use an anchored pattern such as `^\s*\d+ (passing|failing)` or `jet-coverage.*merged .* before NYC`. Prefer the Shell tool's own exit code when it returns normally after launch is healthy. - - - - -### Startup fail-fast poll - -Startup failures are **immediate**. After a startup-fail marker, do **not** wait for `launchApp` (timeouts in [`tests/e2e/detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js)) or the 5-minute [stalled run](#stalled-run-detection) window. - -This is **tee-log monitoring**, not process polling. It complements [running one iteration](#running-one-iteration) and [stalled run detection](#stalled-run-detection); it does not change Detox flags ([infrastructure change bar](#e2e-infrastructure-change-bar)). - -After starting `:test-cover` teed to a **unique** path (`/tmp/rnfb-e2e--.log`): - -1. Check the tee **immediately**, then every **~5s for ~60s** (or `notify_on_output` / AwaitShell `pattern` with the markers below). -2. On **any** marker: **STOP** the run, scoped [pre-flight recovery](#pre-flight-recovery) / `yarn tests:e2e:release`, and return YAML. Do not AwaitShell the full `launchApp` timeout. -3. After a **healthy** launch (`Jet client connected` / `launch-ready received`), use existing stalled-run / done-footer rules. - -**Startup-fail markers** (abort immediately; do not wait the full `launchApp` timeout): - -| Match | Do not match | -| -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ReactContext is null` (dead Fabric launch that does not recover) | Detox `ws-client:APP_STATUS The app seems to be idle` (healthy idle after `launch-ready`) | -| `TELNET_ERROR` / `Cannot connect` | Load-induced `ws-client:APP_STATUS` + `currentStatus` / status-query timeout (`response within …ms timeout`) — latency, not hard infra; do not serialize Android or kill a 9-cell wave for it | -| serial leftover: `waiting for Metro on port 12007` **and** `emulator-5554` | slotted android slot-0 `waiting for Metro on port 12007` with `emulator-5556` (healthy) | -| `emulator-16` in the adb list | — | -| `Jest did not exit` | — | -| `Could not connect to development server` / `No script URL provided` | — | -| `Detox.framework could not be found` | — | -| `Package uses different ABI(s) than its instrumentation` | — | -| `Received a message from the client, but server wasn't running` | — | -| `[rnfb-e2e] launchApp timed out after` | In-process `launchApp` retry still running (max 2; logs `launchApp failure reason=` first) | - -**notify_on_output / AwaitShell `pattern`:** `ReactContext is null\|TELNET_ERROR\|Cannot connect\|emulator-16\|Jest did not exit` — same string as `E2E_STARTUP_FAILFAST_NOTIFY_PATTERN`. **Must not** use bare `APP_STATUS`, bare `currentStatus`, bare `…ms timeout`, or bare `waiting for Metro on port 12007` (slot-0 Metro is `:12007`). Serial leftover `:12007` is `waiting for Metro on port 12007` **together with** `emulator-5554`. - -First infra fail on a wave (`pod:install` / `:build` / preflight / startup-fail marker): abort remaining cells (do not wait), then scoped release in each cell's slot env (the [manual machine wipe](#manual-machine-wipe) only at explicit user direction). `yarn tests::pod:install` or `:build` failure is infra (stop the wave) — not a product mocha fail to wait out. - -### Pre-flight: is the host clear to start? - -**Canonical owner** for host-clear probes, recovery after abort, and service checks. Other OKF docs link here by reference — do not duplicate commands or probes elsewhere. - -Run **all four** steps before every `:test-cover`. After an [interrupted run](#interrupted-run-abort-killed-terminal-eaddrinuse-on-8090), run [pre-flight recovery](#pre-flight-recovery) and re-run the probes. - - - -#### 0. Prepare complete (when `packages/*/lib/**` changed) - -If product code under `packages/*/lib/**` was edited in this session, **`yarn lerna:prepare`** (or scoped `yarn lerna run prepare --scope …`) must have **fully finished with exit code 0** before pre-flight steps 1–3 or any `:test-cover` / `:build`. - -- **Wait** for the prepare shell to return — do not batch prepare in parallel with Metro restart, pre-flight probes, or e2e in the same agent turn. -- **Then** restart Metro when it was already running: [packager reset-cache](#packager-reset-cache-eaddrinuse) (matching iOS/Android vs macOS packager — not interchangeable). -- **Then** continue with host-clear probes and service checks below. - -Skipping this gate causes missing or half-written `dist/module/**` while Metro `/status` still returns 200 — a common source of bundle-load and module-not-found failures that look like product bugs. - -Owner for install/prepare serialization: [agent command policy § prepare must finish first](agent-command-policy.md#prepare-must-finish-first). - -**Stale install after a merge or pull (blocking).** A merge or pull that changes React Native or native dependency versions (or the Apple app lifecycle) leaves `node_modules`, `tests/ios/Pods`, and the native builds on the old version. Symptom: `:test-cover` fails before any Mocha test runs (iOS app killed shortly after launch, `NoSceneLifecycleAdoption` / `AppWillTerminateWithError` / `waitForActive`; Android `No instrumentation runner found` after a cold boot). Treat this as a stale install first, not a host, Simulator, or Metro fault. Re-run the [install / patch / fmt gate](agent-command-policy.md#install-patch-fmt-gate-blocking) (root `yarn`), then `yarn tests:ios:pod:install` (if it fails on stale Pods or hermes-engine podspec drift, delete the gitignored `tests/ios/Pods` and re-run it), then `yarn tests:ios:build` / `yarn tests:android:build`, then one `:test-cover` per platform. - -#### 1. Host clear - -No in-flight test run on the target platform: - -| Platform | Clear when | -| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Android** | [Android app reset](#android-app-reset-blocking) + `yarn tests:e2e:check --platform=android` pass | -| **iOS** | `yarn tests:e2e:check --platform=ios` passes — the identity's own simulator (`iPhone 17` serial, or the slot base) is not booted and no stray listener is on `:8090`. Other booted simulators are reported as INFO and do not fail the check. Detox boots `iPhone 17` from `tests/.detoxrc.js`; do not pre-boot or leave it running. The `test-expo` / `test-rn-bare` `ios:launch-smoke` scripts boot their simulator (default `iPhone 18 Pro`) and do not shut it down; it is never recorded, so release leaves it alone, and it does not block this check (it is not the identity's device). Shutting it down is a human-operator step. Plain [host-clear probes](#host-clear-probes) without `--platform=ios` intentionally do **not** fail on an unrelated booted simulator — see [global device scoping](#global-device-scoping). | -| **macOS** | [Host-clear probes](#host-clear-probes) pass (no macOS test app process — default `io.invertase.testing`, or `RNFB_MACOS_PRODUCT_NAME` when set) | - -Also wait for any visible unfinished `yarn tests:*:test-cover`. - -A Jet port that accepts loopback connections but has no listener `lsof` can attribute to this user (likely another user's server, such as a root service in a cloud guest image) is BUSY with `owner=unrecorded` in `yarn tests:e2e:check`; release cannot stop it, so free the port from its owner or use a free slot. `tests/e2e/firebase.test.js` likewise fails its pre-spawn Android Jet host-clear and its retry drain after about 2 s of such accepts, instead of waiting 30 s for the port to close. Neither treats a missing or unresponsive `lsof` as a foreign listener. - - - -**Android app reset (blocking)** — run **before every** Android `:test-cover`, not only after a failed run: - -```bash -ANDROID_SERIAL="${ANDROID_SERIAL:-emulator-5554}" -adb -s "$ANDROID_SERIAL" shell am force-stop com.invertase.testing -adb -s "$ANDROID_SERIAL" shell am force-stop com.invertase.testing.test -# Or via generic release (also clears Jet/Metro per env): -# yarn tests:e2e:release --only android-apps,jet -``` - -The main app (`com.invertase.testing`) can sit on **“waiting for jet to start tests…”** while the [host-clear probe](#host-clear-probes) still passes (it only checks `com.invertase.testing.test`). A stale main app then connects as a **second Jet client** after Detox launches a fresh run → `Received a message from the client, but server wasn't running` and no Mocha summary. Force-stop **both** packages, then re-run the probe. - -On **darwin** hosts, also clear the macOS test app before Android `:test-cover` when they share a Jet port (serial default `:8090`, or the same `JET_REMOTE_PORT` / platform Jet in slotted runs). Alternating macOS and Android without killing the macOS app leaves a stale macOS Jet client → duplicate clients and `server wasn't running`. - -```bash -MACOS_APP="${RNFB_MACOS_PRODUCT_NAME:-io.invertase.testing}" -! pgrep -x "$MACOS_APP" >/dev/null 2>&1 -# or: yarn tests:e2e:release --only macos-app,jet -# Release stops only the macOS app pid this checkout's run recorded (never killall by name). -``` - -(`firebase.test.js` runs this automatically via `ensureAndroidJetHostClear` before spawning Android Jet; use the probe manually when prepping from the runbook.) - - - -**Host-clear probes** — `yarn tests:e2e:check` / `yarn tests:e2e:release` (scripts under `scripts/e2e/`). They resolve [configurable e2e environment](#configurable-e2e-environment) first, else **serial defaults only**. **Exit 0 = clear.** Mellifera does **not** feed these commands a JSON file — it exports the same `RNFB_*` env, then calls these yarn targets ([e2e parallel design § layers](e2e-parallel-design.md#rnfb-mellifera-tart-layers)). - -`yarn tests:e2e:check` **default** reports Jet + apps + simulators — not Metro/emulator ports (those are [services ready](#2-services-ready)). Pass `--services` to treat Metro/emulator as BUSY. `--platform=android|ios|macos` scopes devices ([global device scoping](#global-device-scoping)). Android host-clear also reports **stray `emulator-*` serials** (console ports outside serial **5554** and slotted **5556+2n**, e.g. Detox FreePortFinder **10000–20000** guests `emulator-16xxx`). A stray this checkout's run recorded, or that a recorded process spawned, is BUSY, and default `yarn tests:e2e:release --devices` frees it. A stray whose qemu runs from this checkout on **this identity's AVD** (`owner=this-checkout-unrecorded`, any port including FreePortFinder) is also BUSY — same as an allocated-serial cold-boot respawn — and default `--devices` stops it. Any other stray is INFO with its owner, qemu cwd and AVD: strays are host-global, so another owner's stray would otherwise fail every identity's check, and no slot move clears it. A stray on another identity's AVD that traces to this checkout stays INFO — stop it from the shell that started it, or manually with `yarn tests:e2e:release --include-unrecorded --devices --only android-emulator` in that identity's env. Only the manual `--all-slots` wipe stops another owner's stray. - -**Default (no args, no slot env):** serial ports/devices only. Do **not** wipe leftover `TestingAVD-N` / slot sims / slotted `12xxx` ports. Preferred slot scope is `eval "$(yarn tests:e2e:export-slot-env …)"` then check/release; direct `--slot=N` uses the same **0..effective max** guard and fails before probes or release. iOS device scope targets the exact neutral base name — [iOS slot simulators](#ios-slot-simulators). - - - -**Run record (release scope).** An e2e run may only perturb what it started and works with. Each start records what it owns under `.e2e-run//` (override the base with `RNFB_E2E_RUN_RECORD_DIR`; git-ignored): Metro (`yarn tests:packager:*`), the Firebase emulator suite (`yarn tests:emulator:start`), the Jet listeners and macOS app (`:test-cover`), and the Android emulator / iOS simulator **instance** the run booted or worked with. Pids are recorded at spawn (Metro, the emulator suite, and Jet; on macOS, Jet records itself from `tests-macos/.jetrc.js` `before()`, before it opens its ports), so an interrupted start is still freed. Pid entries carry the process start time (`/proc` on Linux, `ps lstart` in `LC_ALL=C TZ=UTC` elsewhere) and are named per process instance, so a reused pid never counts. A listener counts as owned when it, or an ancestor, is a recorded pid. Device entries carry an instance token — the qemu pid + start time (Android, serial taken from qemu `-port`) or the `launchd_sim` pid + start time (iOS) — recorded at test start, after every harness reboot (the Android cold boot and iOS simulator reboot in both the `launchApp` retry and the Jet-attempt retry, even when the reboot throws), and when Detox setup booted the device but the test never started. The harness cold boot stops only this run's emulator — its recorded instance, or the qemu on its own console port that traces to this checkout, with `emu kill` sent only when one was selected and `emu avd name` matches — never by AVD name, so another owner's `-read-only` emulator on the same AVD (even on this console port) keeps running; it re-records only this checkout's qemu on the serial it spawned. An unrecorded emulator on the identity's AVD that traces to this checkout (`owner=this-checkout-unrecorded`, e.g. Detox/harness cold-boot respawn after the recorded qemu died) is BUSY, and default `yarn tests:e2e:release --devices` stops it — otherwise release/check could report CLEAR while `TestingAVD-N` / the slot serial stayed up. Another owner's emulator on the identity's own serial is BUSY instead (this run's Detox would attach to it), with its owner, cwd and the first free slot. Release leaves that foreign instance running and therefore exits non-zero; move the run to the named slot. Release acts on a recorded device only while that exact instance is alive; a device another owner has since rebooted is left alone, and the entry is pruned once its instance is gone. - -**Kill policy:** default `yarn tests:e2e:release` frees **recorded resources** — SIGTERM then SIGKILL of recorded listener PIDs on in-scope ports, `kill` of the recorded macOS app pid (never `killall` by name), `simctl shutdown ` of the recorded simulator instance, and with `--devices` `adb -s emu kill` (only once `emu avd name` matches) plus a signal to the recorded qemu pid, a qemu a recorded process spawned, or this checkout's unrecorded qemu on the identity's AVD (`owner=this-checkout-unrecorded`, cwd in this repo — cold-boot respawns). It never stops the shared adb server. Anything else on the identity's ports is another owner's: release prints `owner=… left running`, the holder's command and cwd, and exits non-zero if the port stays busy. No process-group / starter-shell assumptions. CI launch-smoke scripts (`test-expo` / `test-rn-bare` `ios:launch-smoke`) follow the same rule: they fail fast if their Metro port is held and stop only the Metro tree they spawned; `simulator-logging.sh` restarts only its own UDID's log streams unless on a single-tenant runner (`CI=true` or `RNFB_SIM_UI_RESET=1`). - -**Fail fast, never take over:** `yarn tests:e2e:check` annotates each busy port, app, and device with an owner. `owner=this-checkout` is recorded (release frees it). `owner=this-checkout-unrecorded` runs from this checkout but no run recorded it; for Metro/Jet/macOS/apps/non-identity devices check prints the exact manual command, e.g. `yarn tests:e2e:release --include-unrecorded --only metro`. For this identity's AVD qemu (any port), the BUSY line names default `yarn tests:e2e:release --devices` instead — that path does not need `--include-unrecorded`. `owner=unrecorded` is another owner: check names the first free slot (ports, `TestingAVD-N` qemu and slot simulator all idle) and the override `eval "$(yarn tests:e2e:export-slot-env N)"`. Move the run there, or free the holder from its owner. Scripts never pick a slot for you and never kill another owner. Harness fail-fast messages (Metro, Jet, macOS app) show the same owner, cwd, and hint. - -**One-time upgrade note.** Processes started before the run record existed (a Metro, emulator suite, or booted device from an older checkout of this branch) are unrecorded, so the first check after upgrading can report them `owner=this-checkout-unrecorded` (an emulator by its qemu cwd, which is under `tests/` when Detox booted it). An unrecorded qemu on **this identity's AVD** (allocated serial or FreePortFinder stray) is BUSY and default `yarn tests:e2e:release --devices` stops it; an unrecorded stray on another identity's AVD stays INFO. A simulator's `launchd_sim` is a child of launchd running from `/`, so an unrecorded simulator cannot be traced to a checkout and shows `owner=unrecorded`; shut it down yourself if it is yours (`xcrun simctl shutdown `). For ports/apps still needing the manual flag, run the printed `yarn tests:e2e:release --include-unrecorded --only ` once in that identity's env; later runs record what they start. - - - -**Manual machine wipe (explicit user direction only).** General scripts, `yarn test:full`, Mellifera, and CI never pass these flags: - -| Flag | Scope | -| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--include-unrecorded` | Also kill unrecorded holders on **this identity's** ports and the macOS app by name, and force-stop the test apps on the configured serial when that emulator traces to this checkout. With `--devices`, default release already stops this checkout's unrecorded emulator on the identity's AVD; this flag still covers that path plus other unrecorded device holders and the identity's simulator when it traces to this checkout. Another owner's device and its apps are reported and left running. | -| `--all-slots` (implies the above) | Whole machine through **effective max** (default/cap **7**; [slot index](#e2e-slot-index)): every slot's ports, `TestingAVD-N`, slot sims, macOS `.sN`, plus stray `emulator-*` serials. It kills other owners' live runs, so only use it when the user says the machine is theirs. | - -```bash -yarn tests:e2e:check -yarn tests:e2e:check --services -yarn tests:e2e:check --platform=ios -yarn tests:e2e:release -# yarn tests:e2e:release --only jet,android-apps -# yarn tests:e2e:release --devices -# Manual, explicit user direction only (kills every owner): -# yarn tests:e2e:release --all-slots --devices -``` - -Manual one-liners (defaults only — use when debugging without the scripts): - -```bash -JET_PORT="${JET_REMOTE_PORT:-${RNFB_ANDROID_JET_PORT:-${RNFB_IOS_JET_PORT:-${RNFB_MACOS_JET_PORT:-8090}}}}" -test -z "$(lsof -nP -iTCP:${JET_PORT} -sTCP:LISTEN -t 2>/dev/null || true)" -ANDROID_SERIAL="${ANDROID_SERIAL:-emulator-5554}" -! adb -s "$ANDROID_SERIAL" shell pidof com.invertase.testing.test >/dev/null 2>&1 -! pgrep -x "${RNFB_MACOS_PRODUCT_NAME:-io.invertase.testing}" >/dev/null 2>&1 -``` - - - -**Pre-flight recovery (serial)** — when probes fail **after** [Android app reset](#android-app-reset-blocking), abort, kill, or `EADDRINUSE` on the Jet port. Canonical recovery uses the env-aware scripts below. `EADDRINUSE` on **`:8081`** (or a slotted Metro port) during packager restart is a different path — [packager reset-cache](#packager-reset-cache-eaddrinuse) (this block does **not** free Metro). - -```bash -yarn tests:e2e:release -# If AVD/sim must go down too: -yarn tests:e2e:release --devices -yarn tests:e2e:check # must exit 0 -``` - -If release reports `owner=unrecorded`, another owner holds the identity: move to the free slot that check names. Do not reach for the [manual machine wipe](#manual-machine-wipe) unless the user directs it. - -**Functions build lock.** `yarn tests:emulator:start` takes `.github/workflows/scripts/functions/.build.lock.d` while the functions package builds. A killed start used to leave that directory behind, and the next start waited 300s. A lock whose holder pid is gone is removed automatically. `yarn tests:e2e:release` does not clear it. If a start still fails with `timed out waiting for functions build lock` and no emulator start is running: - -```bash -rm -rf .github/workflows/scripts/functions/.build.lock.d -``` - -Do **not** use `boot-simulator.sh` or `simctl shutdown all` as routine prep ([what not to do](#what-not-to-do)). - - - -**Packager start** — `yarn tests:packager:jet` / `jet-reset-cache` (and macOS variants). Honor `RCT_METRO_PORT`. Kill this checkout's **recorded** listener on that port (SIGTERM then SIGKILL — [run record](#run-record)), then start clean and record the new Metro. If a listener this checkout did not record still holds the port, fail fast naming its pid and the slot override — another worktree's live Metro is never killed. On a host with other RNFB worktrees, load the [slot env](#slot-lifecycle) before the first packager/emulator start. Metro's `TMPDIR` (its cache) is per listen port: `${RNFB_METRO_CACHE_ROOT:-$HOME/.metro}/rnfb-${RCT_METRO_PORT}`. The Metro log defaults to the caller's `${TMPDIR:-/tmp}/rnfb-metro-${RCT_METRO_PORT}.log` (`RNFB_METRO_LOG` overrides), read before `TMPDIR` is repointed at the cache. Wait until `http://127.0.0.1:${RCT_METRO_PORT}/status` contains `packager-status:running` (long documented timeout), then succeed or **fail** — no hidden restart inside `:test-cover`. Before start, **conditionally** `watchman watch-del` for **this Metro project root** (skip when a sibling Metro already owns that root — see below), then always `watch-project` the allowlist trees Metro would reload — not the whole monorepo plus native `*/build`. Never `watch-del` the repo root. Hard Watchman reset when alone, or with `RNFB_METRO_FORCE_WATCHMAN_RESET=1` when no sibling must survive. - -**Slotted dual `tests/` packagers:** `yarn test:full --slot N` (and manual android∥ios) starts **two** `yarn tests:packager:jet` processes against the same `tests/` root on distinct `RCT_METRO_PORT` values, plus macOS on `tests-macos/` — **three** Metros total. After killing **this** port only, `scripts/e2e/start-packager.sh` **skips** `watchman watch-del` when a sibling Metro already owns `$METRO_ROOT`: a live process with Metro/react-native cmdline and cwd equal to that root (LISTEN not required — covers cold dual-start before either port binds). Emulator listeners (qemu/netsimd) with cwd under `tests/` do **not** count. Always runs the `watch-project` allowlist; never `watch-del` the repo root. Force a hard reset only with `RNFB_METRO_FORCE_WATCHMAN_RESET=1` when no sibling must survive. Same-platform parallel still needs separate worktrees ([parallel topology](#parallel-e2e-topology)). - - - -**Packager restart (`jet-reset-cache`)** — same kill-then-start as above (port from env, default `:8081`). Matching packager only — iOS/Android (`tests/`) vs macOS (`tests-macos/`); not interchangeable. - -```bash -yarn tests:packager:jet-reset-cache -# yarn tests:macos:packager:jet-reset-cache -``` - -#### 2. Services ready - -Metro and emulators must be **running and responsive** — do not assume from a prior session or background start. This is the **opposite** of [host-clear](#host-clear-probes) (clear = nothing listening; ready = packager/emulators up). - -```bash -METRO_PORT="${RCT_METRO_PORT:-${RNFB_METRO_PORT:-8081}}" -FIRESTORE_PORT="${RNFB_ANDROID_EMULATOR_FIRESTORE_PORT:-${RNFB_IOS_EMULATOR_FIRESTORE_PORT:-${RNFB_MACOS_EMULATOR_FIRESTORE_PORT:-8080}}}" -FUNCTIONS_PORT="${RNFB_ANDROID_EMULATOR_FUNCTIONS_PORT:-${RNFB_IOS_EMULATOR_FUNCTIONS_PORT:-${RNFB_MACOS_EMULATOR_FUNCTIONS_PORT:-5001}}}" -curl -sf "http://127.0.0.1:${METRO_PORT}/status" -curl -sf "http://127.0.0.1:${FIRESTORE_PORT}" >/dev/null -test -n "$(lsof -nP -iTCP:${FUNCTIONS_PORT} -sTCP:LISTEN -t 2>/dev/null || true)" # Functions emulator — listener only -``` - -**Metro alive or dead (blocking, last check before `:test-cover`).** Run the Metro `curl` again after `:build` and read the body. Do not discard it. **Alive:** body contains `packager-status:running`. **Dead:** `curl` fails, or the body does not contain that string. A port listener with any other HTTP success is dead. If dead, start `yarn tests:packager:jet` (iOS/Android) or `yarn tests:macos:packager:jet` (macOS) again and require alive. Do not start `:test-cover` while Metro is dead. Metro can pass this check before `:build` and be dead after it. Slotted android∥ios may share one `tests/` root on distinct ports (sibling-safe `watch-del`); re-start only the dead port. - -If Metro or Firestore checks fail: start `yarn tests:packager:jet` (iOS/Android) or `yarn tests:macos:packager:jet` (macOS) and `yarn tests:emulator:start` (background) from **this checkout's repo root**; re-check until both pass. After **`yarn lerna:prepare` has finished** (step [0](#prepare-completion-gate-blocking)) or test-runner patch edits, restart the packager via [packager start](#packager-reset-cache-eaddrinuse) — never restart Metro while prepare is still running. - -A listener on the Metro/Firestore ports (or Functions) alone is **not** sufficient for Metro/Firestore — their HTTP checks must succeed. **Functions:** verify the listener is up; `curl -sf` of the Functions root path exits non-zero (**404**) — expected, not a service failure. - -`yarn tests:emulator:start` honors the active platform’s `RNFB_*_EMULATOR_*` ports (serial `firebase.json` defaults when unset), including Firebase Tools aux binds (websocket / eventarc / tasks). Ready-check uses **those** ports, never a hardcoded `:8080` / `:5001`. Interactive `--no-daemon` may stay foreground; CI / background callers wait until the suite is ready then return — same implementation, two invocation modes. - - - -**Checkout ownership (blocking on multi-worktree hosts)** — HTTP/port checks can pass while Metro or Firebase emulators belong to a **different** RNFB worktree (shared `:8081` / `:8080` / `:5001` / `:9099`). That is **not** services-ready for this checkout. - -After the curls above succeed, verify listener **cwd** paths are under **this** repo root (`$REPO_ROOT`): - -```bash -# REPO_ROOT = absolute path to this worktree (pwd at monorepo root) -listen_cwd() { # usage: listen_cwd - local pid - pid="$(lsof -nP -iTCP:"$1" -sTCP:LISTEN -t 2>/dev/null | head -1)" - test -n "$pid" || return 1 - lsof -a -p "$pid" -d cwd 2>/dev/null | awk '/cwd/ {print $NF; exit}' -} -metro_cwd="$(listen_cwd 8081)" -fs_cwd="$(listen_cwd 8080)" -case "$metro_cwd" in "$REPO_ROOT"|"$REPO_ROOT"/*) ;; *) echo "Metro cwd not this checkout: $metro_cwd"; false ;; esac -case "$fs_cwd" in "$REPO_ROOT"|"$REPO_ROOT"/*) ;; *) echo "Firestore emulator cwd not this checkout: $fs_cwd"; false ;; esac -``` - -Expected shapes when started via this checkout's `yarn tests:*`: Metro cwd ends with `/tests` (iOS/Android packager) or `/tests-macos` (macOS packager); Firestore/Auth/Functions cwd ends with `/.github/workflows/scripts`. A full parallel slot that runs android/ios **and** macos has **three** Metro listeners (android + ios share `tests/` on distinct ports; macos on `tests-macos/`) — verify **each**. Two `tests/` Metros are OK because packager start **skips** `watch-del` when a sibling owns that root ([packager start](#packager-reset-cache-eaddrinuse)). If ownership fails: stop the foreign listeners (or finish that worktree's run), then start `yarn tests:packager:jet` and/or `yarn tests:macos:packager:jet` plus `yarn tests:emulator:start` from **this** `$REPO_ROOT` and re-check curls **and** cwd. Do not proceed to `:test-cover` on a foreign-owned stack. - -#### 3. Harness matches validation tier - -Confirm local harness overrides (or committed files for **full** tier only) match the item's **`validation_tier`** ([iteration vocabulary](iteration-vocabulary.md#work-queue-fields)), **not** the branch's committed harness alone. - -| Tier | Harness before `:test-cover` | -| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Unit-focused** (`implementation`) | **Area narrowing required** — [`tests/harness.overrides.js`](#local-harness-overrides-harnessoverridesjs) with `modules` + `RNFBDebug: true`; `.only` OK locally. | -| **Area-focused** (`independent-review`, `baseline-capture`) | **Area narrowing required** — same overrides file; load **full** spec file(s) for the package area; **no** `.only`; `RNFBDebug: true`. | -| **Full** (`pre-merge-validation`) | **No** `harness.overrides.js` (delete or `{}`); full app in committed `tests/app.js`; `RNFBDebug: false`. | - -Committed full harness on the branch does **not** override **unit-focused** or **area-focused** tier for local runs. Package workflows define **which module/spec** (e.g. [pipelines § area harness](../packages/firestore/pipeline-implementation-workflow.md#pipeline-area-harness)). **How:** [local harness overrides](#local-harness-overrides-harnessoverridesjs). Never commit `harness.overrides.js`. - -See [Harness narrowing gate (blocking)](#harness-narrowing-gate-blocking) — a run that skips step 3 does **not** close `implementation_gate` or `review_gate`. - -### Stalled run detection - -See also [startup fail-fast poll](#startup-fail-fast-poll) (check immediately for launch-fail markers; do not wait this 5-minute window first). - -Completion = shell exit code + log markers — not open-ended log tailing. - -| Platform | Early markers (≈2–3 min) | Done | -| --------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------ | -| **macOS** | `Jet client connected` | Jest `N passing` / `N failing`, preferably **and** `[jet-coverage] merged … before NYC shutdown` | -| **iOS/Android** | Detox launch done, `Jet client connected` | Same | - -`✨ Tests Complete ✨` is **optional** if present — it is not always emitted on local macOS runs; treat it as a bonus signal, never a required one. - -**If stalled** — no new markers for **5 minutes**, or past tier budget (~15m macOS, ~45–60m iOS/Android) without a Jest summary (`N passing`/`N failing`) or `[jet-coverage] merged … before NYC shutdown`: treat as [interrupted run](#interrupted-run-abort-killed-terminal-eaddrinuse-on-8090). Do not gate the stall decision on emoji `Tests Complete` alone. Run [pre-flight recovery](#pre-flight-recovery), confirm [host-clear probes](#host-clear-probes) and [services ready](#2-services-ready), retry. Do not keep watching flat tee output. Launch-time failures are [startup fail-fast poll](#startup-fail-fast-poll), not this window. - -Android `:test-cover` that **FAIL**s then Jest `did not exit` is a hang, not a stall to wait out — kill hung yarn/jest/detox PIDs, then [Android Detox launch ANR](#android-detox-launch-anr-abi-mismatch) if logcat showed ANR / ABI mismatch, otherwise [interrupted run](#interrupted-run-abort-killed-terminal-eaddrinuse-on-8090). - -- macOS bundle/Metro hangs → [ci-workflows/other.md § bundle load hang](../ci-workflows/other.md#ci-failure-bundle-load-hang--could-not-connect-to-development-server) -- iOS Metro at launch → [ci-workflows/ios.md § Metro unresponsive](../ci-workflows/ios.md) - -Do not poll `pgrep`, process names, or `:8090` for _completion_ ([above](#how-a-platform-run-is-structured-androidios)). Stall detection uses **missing progress markers**, not exit polling. - -### Harness narrowing gate (blocking) - -**Both `unit-focused` and `area-focused` tiers require area narrowing before the first `:test-cover`.** The only difference between those tiers is whether `.only` is allowed and whether the full package-area spec loads — not whether the harness stays at full app load. - -**Primary mechanism:** create a local **`tests/harness.overrides.js`** (gitignored) from [`tests/harness.overrides.example.js`](../../tests/harness.overrides.example.js). Committed `tests/app.js` and `tests/globals.js` stay at full harness — do **not** edit them for module narrowing or `RNFBDebug`. See [local harness overrides](#local-harness-overrides-harnessoverridesjs). - -| Mistake | Symptom | Gate impact | -| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | -| Run `:test-cover` with no overrides (full harness) during `implementation` or `independent-review` | macOS/iOS/Android pass counts in the **hundreds or thousands** (all modules via `require.context`) | Run is **invalid** — does not close `implementation_gate` or `review_gate` | -| Edit only one platform block in `tests/app.js` (legacy pattern) while the other still pushes full list | macOS ~700 firestore tests pass; iOS/Android logs show `database`, `crashlytics`, etc. | Run is **invalid** on iOS/Android — use [overrides file](#local-harness-overrides-harnessoverridesjs) instead | -| Correct area harness via overrides | Pass counts match loaded module/spec scope ([sanity table](#sanity-check-by-platform)) | Expected | - -**Apply locally before every `:test-cover` at unit-focused or area-focused tier** — even when git shows the full push harness. **Remove** `tests/harness.overrides.js` (or export `{}`) after the run when the branch keeps full harness (typical until **full** / pre-merge). Never commit `harness.overrides.js`. - -**Validation report must state:** harness narrowed (yes/no), override file used (yes/no), which module/spec loads, whether pass counts match area scope, and **which platforms ran** with exit codes. A green full-app run is not a substitute. - - - -### Platform coverage gate (blocking — no shortcuts) - -**Both `unit-focused` (implementation) and `area-focused` (baseline-capture, independent-review) require e2e on every platform where the changed module loads in the committed harness** — not a subset for convenience. - -Determine required platforms from committed [`tests/app.js`](../../tests/app.js) platform blocks (use **committed** lists when deciding macOS vs native requirement, not a narrowed local harness): - -| Platform class | When required | -| ---------------------------- | ------------------------------------------------------------------------------------------------ | -| **macOS** (`Platform.other`) | Module appears in the committed `if (Platform.other)` list (or overrides `modules` includes it) | -| **iOS** and **Android** | Module appears in the committed `if (!Platform.other)` list (or overrides `modules` includes it) | - -**What in the frozen diff triggers this gate** - -| Frozen-diff touch | Required platforms | -| ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | -| Native bridge / podspec / TurboModule spec / **committed** `packages/*/ios/generated/**` or `…/android/**/generated/**` | Every platform where the module loads (table above); rebuild per [Rules §3](#rules) before `:test-cover` | -| `packages/*/lib/**` (JS/TS runtime of a module that loads on native or macOS) | Same platform matrix as above for that module | -| **`packages/*/e2e/**`** (Detox/Jet specs for a package module) | **Same platform matrix** — area-narrowed `:test-cover` on **every** platform where that module loads, **even when the frozen diff has no native hunk for that OS** | - -E2e-only diffs still exercise the same host/native clients as product code. Skipping Android because “only iOS sources changed” (or the reverse) is an **invalid shortcut** when `packages//e2e/**` is in the frozen tree and the module is on that platform’s harness list. Authoring evidence note: [change authoring § validation evidence](change-authoring-workflow.md#validation-evidence-blocking). - -**Area-focused (`baseline-capture`, `independent-review`) — closes `review_gate` / baseline only when:** - -1. Full loaded package spec(s) with [area narrowing](#harness-narrowing-gate-blocking) (no `.only`). -2. **Serial** `:test-cover` on **each required platform** above — pre-flight before **every** run. -3. Native platforms: `yarn tests::build` before first `:test-cover` when native changed ([Rules §3](#rules)). -4. Validation handoff includes a **platform matrix**: platform, exit code, pass/fail/pending counts, log path. - -**Invalid shortcuts (do not close gates):** - -- “macOS + iOS minimum”; skipping **Android** when the module loads on Android. -- “Skip Android if time tight” or “Android fallback only if iOS failures look env-related” without a fresh Android run. -- Skipping a platform because the frozen diff has **no native sources for that OS** while `packages/*/e2e/**` (or `lib/**`) for a module that loads there **is** in the frozen tree. -- Substituting a prior implementer log for `independent-review` on the frozen tree. -- Treating **`yarn codegen:verify`** (or scripts/OKF-only Jest) as enough when `packages/*/ios/generated/**`, `packages/*/android/**/generated/**`, native shells, podspecs, or specs changed — those still need iOS + Android `:test-cover` ([Rules §3](#rules)). -- Closing pre-flight on port/HTTP checks alone when Metro/emulators are owned by another worktree ([checkout ownership](#services-checkout-ownership-blocking)). - -**Module-specific skip:** only when the module is **absent** from that platform’s harness list (e.g. `messaging` is not on macOS). Record in the work-queue **Notes** — not an oral exception. - -**Unit-focused (`implementation`) — native or package e2e touched:** macOS first when the path is TS/web-only; when the module loads on iOS **and** Android, run **both** before closing `implementation_gate` (same narrowing; `.only` OK locally; never commit). Package `e2e/**` edits follow the same matrix as native for that module. - -See also: [coverage design § platform parity](coverage-design.md#coverage-expectations-policy), [validation checklist § handoff](validation-checklist.md#handoff-checklist). - -**Checklist (copy before first run):** - -1. `tests/harness.overrides.js` exists with correct `modules` (almost always include `'app'`) and `RNFBDebug: true`. -2. Overrides `modules` lists only the package under change (e.g. `['app', 'firestore']`). -3. Spec load uses direct `require` of the area spec — not `require.context` for all packages — when sub-suite narrowing applies; otherwise full package `require.context` is OK when the module list is narrowed. -4. No `.only` when tier is **area-focused**; `.only` optional when tier is **unit-focused**. -5. Grep log: pass count consistent with area scope ([sanity table](#sanity-check-by-platform)), not a full-app load (hundreds or thousands of tests across unrelated modules). - -### Unit-focused-tier iteration loop - -For `implementation` work type — validation tier **unit-focused** ([change authoring workflow](change-authoring-workflow.md#implementation-inner-loop)): - -1. [Pre-flight](#pre-flight-is-the-host-clear-to-start) — [prepare completion gate](#prepare-completion-gate-blocking) when `lib/**` changed, [host-clear probes](#host-clear-probes), services ready, **harness overrides in place** (step 3), **`RNFBDebug: true`** via overrides; if probes fail, [pre-flight recovery](#pre-flight-recovery) first. -2. Edit e2e/spec; add `.only` if needed; never commit overrides or `.only`. -3. macOS first when TS-only: `yarn tests:macos:test-cover 2>&1 | tee /tmp/rnfb-e2e-macos.log` — wait for exit code ([stalled run](#stalled-run-detection) if markers stop). -4. If macOS green and native touched: `yarn tests::build && yarn tests::test-cover 2>&1 | tee /tmp/rnfb-e2e-.log`; one platform at a time. -5. Grep log tail → fix → repeat from step 1. -6. When `implementation_gate` closes, next work type is `documentation?` then `independent-review` at **area-focused** tier — [change authoring § primary loop](change-authoring-workflow.md#primary-loop); [frozen tree](change-authoring-workflow.md#frozen-tree); no `.only`; area narrowing per package workflow. - - - -### One `:test-cover` at a time - -**Serial default** for gate closure and unslotted hosts — see [host rule](change-authoring-workflow.md#host-rule). Slotted exception: [parallel e2e topology](#parallel-e2e-topology) + [configurable e2e environment](#configurable-e2e-environment). - -| Rule | Requirement | -| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **One unslotted e2e at a time** | Wait for prior shell exit code + short log summary (unless each run has distinct slotted ports/devices per [parallel e2e topology](#parallel-e2e-topology)) | -| **No overlapping tiers** | Never run unit-focused-tier and area-focused-tier `:test-cover` concurrently on one host | -| **Clean pre-flight every run** | [Pre-flight](#pre-flight-is-the-host-clear-to-start) — [host-clear probes](#host-clear-probes), services, harness tier | -| **Phase J e2e** | Same serial `:test-cover` rule. Authoring loop: [change authoring primary loop](change-authoring-workflow.md#primary-loop) (`documentation?` before frozen `independent-review`). Harness: [pipeline area harness](../packages/firestore/pipeline-implementation-workflow.md#pipeline-area-harness) | - -Tier scope table: [E2e validation tiers](#e2e-validation-tiers-unit-focused-area-focused-full). - -Each run owns its blocking `:test-cover` and returns summaries only. - -### Interrupted run (abort, killed terminal, EADDRINUSE on :8090) - -**Serial recovery.** Check the log before recovering. After a STOP/abort or a Shell tool interruption that leaves the exit status unknown, read the `/tmp/rnfb-e2e-.log` footer **first** — before `pkill`, [pre-flight recovery](#pre-flight-recovery), or any other kill/recovery step: - -```bash -rg '^\s*\d+ (passing|failing)' /tmp/rnfb-e2e-.log | tail -2 -rg 'jet-coverage.*merged .* before NYC' /tmp/rnfb-e2e-.log | tail -1 -``` - -- **Done footers present** (Jest `N passing`/`N failing`, preferably with `[jet-coverage] merged … before NYC shutdown`) → treat the run as **complete**. Record pass/fail from the log; report exit as `unknown (tool aborted); log footer green|red` — do not conclude failure or incomplete just because the Shell tool gave no exit status. -- **Log shows incomplete or stalled** (no done footers, matches [stalled run detection](#stalled-run-detection)) → only then run [pre-flight recovery](#pre-flight-recovery), confirm [host-clear probes](#host-clear-probes) pass, then rerun from repo root: `yarn tests::build && yarn tests::test-cover` (foreground; tee if logging). Keep one `:test-cover` active at a time on a host. - - - -#### macOS: done footer green but `tee`/shell never returns - -**Failure mode (fixed):** the Jest summary and `[jet-coverage] merged … before NYC shutdown` footer print, but the foreground `| tee /tmp/rnfb-e2e-macos*.log` shell never exits — Agent Shell looks idle/hung forever. Root cause was spawning `io.invertase.testing` with `stdio: ['ignore', 'inherit', 'inherit']`: the app inherited the write end of the tee pipe, so the pipe never saw EOF even after the suite finished. Fixed by detaching macOS app stdio (`stdio: ['ignore', 'ignore', 'ignore']`) and hardening `killMacOsTestApp()` (soft kill → wait → SIGKILL → verify, on the pids this run spawned and recorded only) in [`tests-macos/.jetrc.js`](../../tests-macos/.jetrc.js). - -If this recurs: `yarn tests:e2e:release --only macos-app` in the run's slot env stops the recorded app pid so the tee pipe can close (`pgrep -x "$RNFB_MACOS_PRODUCT_NAME"` shows whether it is still alive); the anchored log footer ([done footers](#stalled-run-detection)) is still the authoritative completion signal, not the shell exit code alone. The recommended tee command (`yarn tests:macos:test-cover 2>&1 | tee /tmp/rnfb-e2e-macos.log` — [running one iteration](#running-one-iteration)) is unchanged by this fix. - -`:test-cover` FAIL followed by Jest `did not exit` will **not** self-exit — kill the hung yarn/jest/detox PIDs, then recover. If Android logcat showed ANR / `Package uses different ABI(s) than its instrumentation`, use [Android Detox launch ANR](#android-detox-launch-anr-abi-mismatch) (not gray-screen snapshot wipe alone). Packager `EADDRINUSE` on `:8081` is [packager reset-cache](#packager-reset-cache-eaddrinuse), not this `:8090` block. - -### What not to do - -- Do not invoke the test runner (Jet), Detox, Metro, or emulators except through repo-root `yarn tests:*` commands in this doc — see [agent rule](#agent-rule-read-first). -- Do not run `:test-cover`, `:build`, Metro restart, or pre-flight while **`yarn` / `yarn lerna:prepare` is still in progress** — wait for exit 0 first ([prepare completion gate](#prepare-completion-gate-blocking)). -- Do not run native `:build` until [install / patch / fmt gate](agent-command-policy.md#install-patch-fmt-gate-blocking) is satisfied (fmt **≥ 12.1.0**). -- Do not background `:test-cover` and poll `pgrep`, `detox`, or process names for **completion**. Do poll the **tee log** for [startup-fail markers](#startup-fail-fast-poll) (immediately, then ~5s for ~60s). Do not wait the full `launchApp` timeout after a marker. -- Do not use `:test-cover-reuse`, `:test-cover-and-process`, or `:test-reuse` when measuring coverage or closing review gates. -- Do not use `:8090` listening as “e2e still running” without the platform active signal above. -- Do not start unslotted iOS/Android/macOS `:test-cover` concurrently on one host (same Metro/Jet/emulator defaults). Slotted cross-platform concurrency only per [parallel e2e topology](#parallel-e2e-topology). -- Do not edit source while a tee'd run is still in progress. -- Do not passively tail tee output when progress markers stop — follow [stalled run detection](#stalled-run-detection). -- Do not run **full** harness (`require.context`, all modules) for **unit-focused**/**area-focused** tier — match [harness to tier](#3-harness-matches-validation-tier). -- Do not run `.github/workflows/scripts/boot-simulator.sh`, `simctl shutdown all`, or `kill -9` on `:8090` or Metro `:8081` as prep. `boot-simulator.sh` is CI-only or internal to iOS test-runner retry. -- Do not wait out Android `:test-cover` FAIL + Jest `did not exit` — kill hung PIDs ([Android Detox launch ANR](#android-detox-launch-anr-abi-mismatch)). Do not treat that ANR/ABI log as an AsyncStorage product failure. - -## Typical loop - -iOS is one order. On a shared host, slot env is loaded before the packager or emulator. `yarn tests:ios:pod:install` is a separate prior step. `yarn tests:ios:build` compiles only and does not install pods. `yarn tests:ios:test-cover` does not build. The agent emulator command is `yarn tests:emulator:start` (`yarn tests:emulator:start-ci` is CI-only). The agent test command is `yarn tests:ios:test-cover` (`yarn tests:ios:test` is a different script). After the packager starts, its status body contains `packager-status:running`, then [services ready](#2-services-ready) repeats that check after the build. - -```bash -# iOS -yarn tests:ios:pod:install -yarn tests:ios:build -yarn tests:e2e:check --platform=ios # host-clear -yarn tests:emulator:start # long-running -yarn tests:packager:jet # long-running; status body contains packager-status:running -# services-ready, then: -yarn tests:ios:test-cover - -# Android / macOS. Apple :build compiles only — pod:install is a separate prior step (skip for Android). -yarn tests:emulator:start -yarn tests:packager:jet -# yarn tests:macos:packager:jet # when running macOS Jet instead -yarn tests:android:build && yarn tests:android:test-cover -yarn tests:macos:pod:install -yarn tests:macos:build && yarn tests:macos:test-cover -``` - -## Fast iteration: test narrowing - -Full e2e loads every package. Narrow locally; **never commit** narrowing. - -| Kind | Mechanism | Scope | -| -------------------------- | ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | -| **Area narrowing** | [`tests/harness.overrides.js`](#local-harness-overrides-harnessoverridesjs) | Which modules load (filter `platformSupportedModules` on all platforms) | -| **Sub-suite narrowing** | Temporary edit to `tests/app.js` (`require` one spec instead of `require.context`) | Which spec files load within a module — **unit-focused diagnosis only** | -| **Single-test narrowing** | `it.only(...)` | One case in a loaded file | -| **Single-suite narrowing** | `describe.only(...)` | One block in a loaded file | - -**Area narrowing** = overrides file for modules + `RNFBDebug`; not test-runner `--grep` or packager `--target`. - - - -### Local harness overrides (`harness.overrides.js`) - -**Canonical owner** for module narrowing and fail-fast debug. Package workflows name **which module/spec**; this section defines **how** to focus the harness without editing committed files. - -#### Setup - -```bash -cp tests/harness.overrides.example.js tests/harness.overrides.js -``` - -Edit `tests/harness.overrides.js` (gitignored — never commit). Shape: - -| Field | Purpose | -| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | -| `modules?: string[]` | After each platform block builds its list, filter to only these module names (works on macOS **and** iOS/Android — no dual-block edits) | -| `RNFBDebug?: boolean` | `true` = verbose RNFB logging + disabled test retries ([§ fail-fast](#fail-fast-rnfbdebug-and-sub-suite-narrowing)) | -| `e2eHelperSecret?: string` | Shared secret for live `fetchAppCheckTokenV2` ([§ macOS App Check helper secret](#macos-app-check-helper-secret)) | - -**Example — app package only, debug on:** - -```javascript -module.exports = { - RNFBDebug: true, - modules: ['app'], -}; -``` - -Omit a field or export `{}` to keep committed defaults for that field. - - - -#### macOS App Check helper secret - -macOS ("other") App Check **custom-provider** e2e calls live `fetchAppCheckTokenV2`, which requires `data.secret` matching Secret Manager `E2E_HELPER_SECRET`. Tests read `harnessOverrides.e2eHelperSecret` via `FirebaseHelpers.hasAppCheckHelperSecret()` / `fetchAppCheckToken()` in `tests/globals.js` and `this.skip()` when it is absent (same as fork CI without the GitHub secret). - -- **Local install:** fetch + merge commands — [agent command policy § App Check e2e helper secret](agent-command-policy.md#app-check-e2e-helper-secret) (merge preserves `modules` / `RNFBDebug`; never commit `harness.overrides.js`). -- **Secret Manager set / deploy / CI GitHub secret:** [firebase-testing-project § e2e cloud helper callables](firebase-testing-project.md#e2e-cloud-helper-callables). -- **iOS / Android** App Check e2e use **debug tokens** and do **not** need `e2eHelperSecret`. - -#### How it works - -Committed [`tests/app.js`](../../tests/app.js) still builds full `platformSupportedModules` per platform block. If `harness.overrides.js` exists, [`tests/globals.js`](../../tests/globals.js) reads `RNFBDebug` and `tests/app.js` filters the module list **after** the platform block runs — so one overrides file applies on every platform. - -#### Spec loading (optional second narrowing) - -Module specs load in `loadTests()` via `platformSupportedModules.includes('')` — usually `require.context('../packages//e2e', …)`. - -| Goal | Change | -| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Full package area | Overrides `modules` only — leave `require.context` as-is | -| Single spec file | **Temporarily** replace `require.context` for that module with `require('../packages//e2e/.e2e.js')` in `tests/app.js` — **never commit** ([sub-suite](#fail-fast-rnfbdebug-and-sub-suite-narrowing); unit-focused diagnosis only unless package workflow says otherwise) | - -#### Revert before `full` tier or commit - -1. Delete `tests/harness.overrides.js` or set `module.exports = {}`. -2. Revert any temporary `require.context` → single `require` edits in `tests/app.js`. -3. Remove all `.only` and native instrumentation. - -Do **not** revert durable product wiring in committed `tests/globals.js` (e.g. `NativeRNFBTurbo*` proxy routing — [NewArch-AD-13](../new-architecture/architecture-decisions.md#newarch-ad-13)). - -#### Sanity check by platform - -| Platform | Narrowed firestore-only (full `packages/firestore/e2e`) | Pipeline-only (`Pipeline.e2e.js`) | -| ------------- | -------------------------------------------------------- | --------------------------------- | -| macOS | ~**700** passing | ~**100** passing | -| iOS / Android | Same order of magnitude as macOS for the same spec scope | ~**100** passing | - -Pass counts in the **thousands** or unrelated suites (`database`, `crashlytics`, …) in the log → confirm overrides file exists with correct `modules` and re-run. - -**Area example:** `modules: ['app', 'firestore']` + full firestore specs via existing `require.context`. - -Package-specific spec names: [Firestore pipeline harness](../packages/firestore/pipeline-implementation-workflow.md#pipeline-area-harness). Area narrowing otherwise: [§ local harness overrides](#local-harness-overrides-harnessoverridesjs). - - - -### Fail-fast (`RNFBDebug`) and sub-suite narrowing - -**`RNFBDebug`:** for **`unit-focused`** and **`area-focused`** tiers, set **`RNFBDebug: true`** in `tests/harness.overrides.js` **before the first `:test-cover`** — not optional. It prints per-case start/finish and **disables Mocha retry/backoff**, so failures surface immediately instead of burning time on retries. Committed `tests/globals.js` default stays `false`. Remove overrides (or set `RNFBDebug: false`) before **`full`** tier or commit ([§ before merge](#before-merge-pr-handoff)). - -| Kind | Mechanism | When | -| ------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Sub-suite narrowing** | `describe.only` / `require` one e2e file (e.g. `Aggregate/count.e2e.js` only) | **Unit-focused diagnosis only** — after [pre-flight](#pre-flight-is-the-host-clear-to-start) is clean and the **same failure repeats** on back-to-back runs without assertion progress. Never for **`area-focused`** gate closure (no `.only`). Never commit. | -| **Single-test narrowing** | `it.only(...)` | Same as sub-suite — unit-focused diagnosis only | - -Package workflows may name default area specs (e.g. [Firestore pipeline harness](../packages/firestore/pipeline-implementation-workflow.md#pipeline-area-harness)); sub-suite narrowing is **tighter** than area narrowing for iteration speed. - -**E2e diagnosis escalation** (cross-package): [change authoring § implementation inner loop](change-authoring-workflow.md#e2e-diagnosis-escalation). - -Package workflows may further restrict narrowing per [validation tier](#e2e-validation-tiers-unit-focused-area-focused-full). - -## E2e validation tiers (unit-focused / area-focused / full) - -All tiers use [canonical commands](#rules), [host rule](change-authoring-workflow.md#host-rule), and clean [pre-flight](#pre-flight-is-the-host-clear-to-start). Tier names describe **scope** — see [iteration vocabulary](iteration-vocabulary.md#validation-tier-identifiers). Public OKF owns the terms, gates, and commands. - -| Validation tier | E2e scope | Narrowing allowed | Typical work type | -| ---------------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------- | -| **Unit-focused** | Fast loop while product code is changing | `harness.overrides.js` + optional `.only` / sub-suite `require` in `tests/app.js` — **never commit** | `implementation` | -| **Area-focused** | Full loaded spec(s) for the package/area under change | **`harness.overrides.js`** required; **no** `.only` | `baseline-capture`, `independent-review` | -| **Full** | Unfocused — all modules, all platforms | Delete overrides file — committed full harness only | `pre-merge-validation` | - -**Universal rules:** - -- **Serial default** for gate closure — one unslotted `:test-cover` at a time. Slotted cross-platform concurrency only per [parallel e2e topology](#parallel-e2e-topology) (still never two of the **same** platform from one worktree). -- Every run starts from **verified [pre-flight](#pre-flight-is-the-host-clear-to-start)**; if probes fail, [pre-flight recovery](#pre-flight-recovery) before another run. -- Use **only** canonical commands from this doc. -- Never overlap unit-focused-tier and area-focused-tier `:test-cover` on one host. - -See also: [unit-focused-tier loop](#unit-focused-tier-iteration-loop), [one :test-cover at a time](#one-test-cover-at-a-time), [pre-merge](#before-merge-pr-handoff). - -## Environment - -- **Devices** — Serial iOS/Android: Detox boots `iPhone 17` / `TestingAVD`. Slotted Android: `TestingAVD-N`. Slotted iOS: `.detoxrc` names `RN E2E iOS slot-N`; patched Detox boots that exact base or fails when it is registry-taken — [iOS slot simulators](#ios-slot-simulators). iOS `:test-cover` should preflight with `yarn tests:e2e:check --platform=ios`, which fails when the identity's own simulator is already booted — see [global device scoping](#global-device-scoping). macOS auto-starts app. -- **adb empty** — `adb devices` should list no emulator this run did not start. `adb kill-server` restarts the shared server for every owner: explicit user direction only ([manual machine wipe](#manual-machine-wipe)). -- **Stale processes (serial default)** — one Metro (`:8081`) per packager project (`tests/` for iOS/Android, `tests-macos/` for macOS), one emulator set (`:8080`, `:9099`, `:9000`, `:4400`, `:5001`, …). Stray listener on `:8090` after a run → [pre-flight recovery](#pre-flight-recovery), then restart background services with [Rules §1–2](#rules) (`yarn tests:packager:jet` or `yarn tests:macos:packager:jet`, `yarn tests:emulator:start`). Reset-cache `EADDRINUSE` on `:8081` → [packager reset-cache](#packager-reset-cache-eaddrinuse). Slotted runs: [configurable e2e environment](#configurable-e2e-environment). -- **Android Gradle home** — leave `GRADLE_USER_HOME` unset so Gradle uses the host default (`~/.gradle`). Slotted `export-slot-env` does **not** isolate a per-slot Gradle home; independent git worktrees share `~/.gradle` by design (Gradle’s user home is built for concurrent CI). If a host does not default there, optionally set `GRADLE_USER_HOME=$HOME/.gradle` as host setup — not slot isolation. Historical “cross-worktree Gradle race” (`bundleLibRuntimeToDirDebug` resolving another tree’s absolute `node_modules` paths) was **rsync path poisoning** (stale `autolinking.json` / config-cache worktree roots), not a Gradle cache concurrency bug. - - - -### Configurable e2e environment - -Serial e2e uses committed defaults (Metro `:8081`, Jet `:8090`, emulators `:8080` / `:9099` / …). Slotted parallel runs export **per-platform prefixed** ports (e.g. `RNFB_ANDROID_JET_PORT`, `RNFB_IOS_METRO_PORT`) **before** Metro/native build and `:test-cover`. Unset vars keep legacy serial behaviour. - - - - -**Parallel e2e topology (worktrees):** same-platform parallel needs **one git worktree per concurrent instance** of that platform. Populate each instance with `git worktree add` (or clone) + `yarn` in **that** tree — never `rsync` sources between local slot worktrees. A single worktree may run **at most** `1× android ∥ 1× ios ∥ 1× macos` (distinct Metro/Jet/emulator blocks + distinct AVD/sim + distinct macOS `PRODUCT_NAME`). Example: `3× android + 3× ios + 3× macos` ⇒ three worktrees. Do **not** launch two of the same platform from one worktree — native products, Detox configs, coverage, and (macOS) one `macos/build` tree are not multi-instance-safe. Why: [e2e parallel design](e2e-parallel-design.md). iOS derived data is `tests/ios/build`; macOS is `tests-macos/macos/build`. Do **not** change Swift explicit-module (or other) xcodebuild settings to paper over concurrent builds — [infrastructure change bar](#e2e-infrastructure-change-bar). - -**The Law — same runbook as serial:** load slot env in this shell, then use the [Rules §1–4](#rules) yarn scripts. On a shared host, load that env before the first packager or emulator start. iOS is one order: `yarn tests:ios:pod:install`, then `yarn tests:ios:build` (compiles only; does not install pods), then host-clear, then `yarn tests:emulator:start` and `yarn tests:packager:jet`, then [services ready](#2-services-ready) (Metro status contains `packager-status:running` after the build), then `yarn tests:ios:test-cover`. The agent emulator command is `yarn tests:emulator:start` (`yarn tests:emulator:start-ci` is CI-only). The agent test command is `yarn tests:ios:test-cover`. `yarn tests:ios:test` is a different script. `:test-cover` does not build; the native app has to exist first. - -```bash -# iOS -eval "$(yarn tests:e2e:clear-slot-env)" # serial only: drop leftover export-slot-env -eval "$(yarn tests:e2e:export-slot-env ios N)" # omit for serial defaults; N is the slot index -yarn tests:ios:pod:install # separate prior step; :build does not install pods; serialize across worktrees -yarn tests:ios:build # compiles only; does not run tests -yarn tests:e2e:check --platform=ios # host-clear -yarn tests:emulator:start # long-running; not the CI-only -ci script -yarn tests:packager:jet # long-running; status body contains packager-status:running -# services-ready (that status check after the build), then: -yarn tests:ios:test-cover # does not build -yarn tests:e2e:release [--devices] # optional -``` - -Android and macOS keep slot env, then packager, emulator, `:build`, and `:test-cover`. macOS `pod:install` stays a separate prior step before `yarn tests:macos:build`. That block is not the iOS order. - -```bash -# Android or macOS -eval "$(yarn tests:e2e:clear-slot-env)" # serial only: drop leftover export-slot-env -eval "$(yarn tests:e2e:export-slot-env N)" # android or macos; omit for serial defaults -yarn tests:e2e:check # optional; default = serial-only; slotted = env from the line above -yarn tests:packager:jet # macos: yarn tests:macos:packager:jet -yarn tests:emulator:start -yarn tests:macos:pod:install # macOS, when needed — serialize across worktrees (shared CocoaPods CDN) -yarn tests::build # compiles only; does not invoke pod install -yarn tests::test-cover -yarn tests:e2e:release [--devices] # optional -``` - -No second lifecycle (no host flock, no Metro-after-build, no slotted packager/test-cover yarn aliases, no `clean-slot-build-artifacts`). Collision control is **slot identity + check/release**. Mellifera leases slots; Tart may host a slot VM — [layers](e2e-parallel-design.md#rnfb-mellifera-tart-layers). - - - -**Slot index (`N`):** decimal integer **0..effective max**, where effective max is **min(configured `E2E_SLOTTED_MAX`, hard 7)**. The same guard applies to `yarn tests:e2e:export-slot-env` (and apply) and to canonical `yarn tests:e2e:check --slot=N` / `release --slot=N`. Invalid or out-of-range fails **before any export, probe, or release action** (`eval "$(…)"` cannot apply a partial env). Lowering `E2E_SLOTTED_MAX` is honored; raising it cannot exceed Detox slot **7**. Preferred lifecycle selector remains `eval "$(yarn tests:e2e:export-slot-env …)"` then check/release. - -**`--all-slots` sweeps** (ports, Android AVDs, exact iOS neutral bases, macOS `.sN`, check/release) use that same effective max. The release sweep is the [manual machine wipe](#manual-machine-wipe). - -**Setup count:** `yarn tests:e2e:setup-android-avds [count]` / `yarn tests:e2e:setup-ios-sims [count]` accept a strict decimal integer **1..8** (default **1**). `count=8` provisions indices **0..7**. Invalid values and **9+** fail **before any inventory or device command**. Setup count is the hard Detox inventory bound, independent of a lowered sweep ceiling. - - - -### Full suite orchestrator (`yarn test:full`) - -`scripts/run-full-tests.sh` is the **prescribed full gate** for pre-merge validation in a single worktree. It runs install → Apple pods (ios ∥ macos) → parallel verify (builds, tsc, attw, lint, jest, android/ios unit) → `:test-cover` e2e with coverage post-process. attw ∥ ios unit: [Types-AD-5](architecture-decisions.md#types-ad-5--pack-ignores-nested-ios-unit-build-trees--accepted). - - - -**Overlapping verify / Jest:** when several worktrees run `yarn test:full` (or the verify phase) concurrently while Apple `:build` writes under `tests/ios/build` / `tests-macos/macos/build`, a Jest walk that recurses those trees can hit ENOENT (live SPM extracts) or SIGSEGV under multi-worker verify. Committed-harness scans skip `build` / `Pods` / `DerivedData` (and similar) directories — [`packages/app/__tests__/harnessCommittedDefaults.test.ts`](../../packages/app/__tests__/harnessCommittedDefaults.test.ts). If verify still flakes under heavy overlap, retry that worktree’s verify (or the full command) once; do not treat a single ENOENT/SIGSEGV under sibling `:build` as product failure. - -**Deterministic by default:** every run performs scoped `yarn tests:e2e:release --devices` + check before e2e, and the same release after (pass or fail). That release clears the Metro, Jet, Firebase emulator suite, test apps, and AVD/sims this checkout's runs [recorded](#run-record) — `--devices` adds device teardown on top of the port release, not instead of it ([release script default](../../scripts/e2e/release-e2e-resources.sh)). A port held by another owner fails the pre-flight check instead of being killed. `yarn test:full` never wipes the machine; the old `--clear-whole-host` flag now exits 2 and points to the [manual machine wipe](#manual-machine-wipe). Fast reuse / tight edit loops use the decomposed `yarn tests:*` commands in this doc — not `yarn test:full`. - -```bash -yarn test:full # serial unslotted e2e (ios → android → macos; Metro switch) -yarn test:full --slot 3 # slotted parallel e2e (1× android ∥ 1× ios ∥ 1× macos) -yarn test:full --verbose # stream output (default: compact status + LOGDIR logs) -``` - -| Flag | Default | Purpose | -| ----------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--slot N` | off (serial) | Parallel slotted e2e in this worktree. `N` must be a [slot index](#e2e-slot-index) `export-slot-env` would accept. Each platform subprocess gets its own `eval "$(yarn tests:e2e:export-slot-env N)"` — **never** one android export for all three. | -| `--verbose` | off | Stream step output. Default prints one status line per phase; full logs under `${TMPDIR:-/tmp}/rnfb-full-*` (preserved on failure). | - - - -**Scratch paths:** RNFB's e2e and fixture scripts write logs and scratch files outside the checkout only under `${TMPDIR:-/tmp}`: the `yarn test:full` LOGDIR, the release recheck output (one file per run, removed on exit), the Metro log, the Firebase emulator log (`RNFB_EMULATOR_LOG`), and the test-expo / test-rn-bare logs and DerivedData. A caller that points `TMPDIR` at a per-run directory removes all of them by deleting it. The Metro cache is separate ([packager start](#packager-start)): point `RNFB_METRO_CACHE_ROOT` into the same directory to include it. Explicit path overrides (`RNFB_*_LOG`, `RNFB_TEST_RN_BARE_*`, `RNFB_TEST_EXPO_*`) still win; CI workflows pin the paths they upload as artifacts. - -Slotted mode: no e2e retries (fail-fast). Serial mode: up to 3 `:test-cover` attempts per platform. Slotted e2e uses distinct Metro listeners (`tests/` for android+ios, `tests-macos/` for macos) and **three Firebase emulator suites** (one `yarn tests:emulator:start` per platform subshell after `export-slot-env N`) — no serial Metro switch. - -**Readiness (orchestrator):** follow [§2 Services ready](#2-services-ready) — Metro `curl /status` with `packager-status:running`; emulator ready = `yarn tests:emulator:start` exit 0 (Functions port via `e2e_port_listening` inside that script). No fixed `sleep` for readiness; poll or delegate to canonical `yarn tests:*`. - -**First use of a slot:** `yarn tests:e2e:setup-android-avds [count]` / `yarn tests:e2e:setup-ios-sims [count]` — [setup count](#e2e-slot-index). Both scripts are **create/reuse-only** — an existing device is reported and reused; neither deletes, renames, or erases anything. Serial unslotted devices stay `TestingAVD` / `iPhone 17`. iOS simulators are created on **`RNFB_IOS_SIM_RUNTIME`** (default `iOS 27.0`); CI/Jet reboot paths use **UDID** + selected-Xcode **Device Hub** — see [iOS CI simulator reliability](../ci-workflows/ios.md#simulator-reliability). Naming and host migration: [iOS slot simulators](#ios-slot-simulators). - -**Base `TestingAVD` prerequisite (Android):** `yarn tests:e2e:setup-android-avds` does **not** create the serial `TestingAVD`; [`scripts/e2e/create-android-avds.sh`](../../scripts/e2e/create-android-avds.sh) only clones an existing base (`RNFB_ANDROID_BASE_AVD`, default `TestingAVD`) into `TestingAVD-N` and fails with `base AVD 'TestingAVD' not found` otherwise. A human creates it once in Android Studio Device Manager; CI uses API **36**, `google_apis`, `x86_64` ([`tests_e2e_android.yml`](../../.github/workflows/tests_e2e_android.yml) matrix). If the script reports it missing, agents stop and ask the user — `avdmanager` is not on the [agent allowlist](agent-command-policy.md). Match the CI API level: the readiness probe in [`tests/e2e/firebase.test.js`](../../tests/e2e/firebase.test.js) runs `adb shell cmd package wait-for-handler`, which API 33 does not support (`Unknown command: wait-for-handler`), so an older image stalls retrying `android-ready package handler wait` until `RNFB_REBOOT_ANDROID_EMULATOR_TIMEOUT_MS` (default 5 min) and the app never launches. - -Keep exported env in the **same shell**. `export-slot-env` loads full `RNFB_{ANDROID,IOS,MACOS}_*` carry-in, `ANDROID_SERIAL=emulator-$((5556+2*N))`, `RNFB_ANDROID_CONSOLE_PORT` (Detox must not FreePortFinder **10000–20000**), `RNFB_MACOS_PRODUCT_NAME=io.invertase.testing.sN`. Does not set `GRADLE_USER_HOME`. - -**Serial leftover env + Jest transform cache:** `tests/.babelrc` / `tests-macos/.babelrc` `babel-plugin-transform-inline-environment-variables` inlines `RNFB_*` at transform time. Jest’s transform cache does **not** include those env values, so a prior slotted shell can make serial `:test-cover` wait on android slot-0 Metro **`:12007`**. Mitigations: `eval "$(yarn tests:e2e:clear-slot-env)"` before a serial Law run; `e2e_sanitize_serial_env` inside packager / emulator / `:build` / `:test-cover` when `RNFB_E2E_SLOT` is unset (then **pins** `RNFB_ANDROID_CONSOLE_PORT=5554` / `ANDROID_SERIAL=emulator-5554` so Detox does not FreePortFinder **10000–20000**); `cache: false` in `tests/e2e/jest.config.js` so Detox Jest cannot replay a slotted transform. Host Metro wait is not the only leftover: a **slot-baked APK** (`react_native_dev_server_port=12007`) on serial `:test-cover` still launches `TestingAVD`/`emulator-5554` then fails Detox `isReady` / APP_STATUS — `e2e_assert_android_apk_metro_port` fail-fasts that mismatch. - -**Check/release with slot env loaded:** all three platform port blocks for that slot (ports+apps; `--devices` for AVD/sims). Mid-wave free of one platform: `--platform=`. `--platform=` never selects a slot. No slot env → serial defaults only (not leftover slots). Release frees only [recorded](#run-record) resources in that scope. Direct `--slot=N` is the same [slot index](#e2e-slot-index) guard; preferred lifecycle is still export then check/release. `--slot=N` re-applies slot N's env (ports, `TestingAVD-N` / `emulator-<5556+2N>`, `RN E2E iOS slot-N`, `io.invertase.testing.sN`), so a bare `--slot=N` never falls back to the serial emulator or simulator; a caller `RNFB_E2E_PLATFORM` or `--platform=` still narrows it. It exits 2 before any probe or release when a different slot's env is loaded. `--all-slots` skips the re-apply. - -**Infra failures:** hub/port taken, suite busy, Detox `TELNET_ERROR` / leftover `emulator-16xxx`, wrong-owner Metro, **`yarn tests:ios:pod:install` / `yarn tests:macos:pod:install` / `:build` failure** → **abort the wave**. On the first infra fail: stop remaining platform×slot cells (do **not** wait for them to finish), then scoped `yarn tests:e2e:release` in each cell's slot env. That frees only what each cell recorded, so it is safe while other owners are live. The [manual machine wipe](#manual-machine-wipe) is never part of wave handling. `:test-cover` does not restart Metro. - -**Overlapping Apple `pod:install`:** CocoaPods trunk CDN (`source 'https://cdn.cocoapods.org/'` in `tests/ios/Podfile`, shared `~/.cocoapods`) is a **host-global** cache. Concurrent `yarn tests:ios:pod:install` (which deletes `ios/Podfile.lock` then resolves) can miss trunk specs (`Unable to find a specification for SocketRocket (~> 0.7.1)`) while sibling worktrees succeed. macOS SocketRocket is a **local** `react-native-macos` podspec, so that miss is iOS CDN/spec — not a missing git repo and not Swift explicit modules. **Serialize** all Apple `yarn tests::pod:install` across worktrees **before** overlapping `:build` / `:test-cover`. `:build` still must not invoke pod install. - -**Wave operator checklist (before N×3 cells):** scoped recovery per slot, then serialized Apple pods. **Pre-wave:** in each slot's env, `yarn tests:e2e:release --devices` + `yarn tests:e2e:check` must be CLEAR. A slot that stays BUSY with `owner=unrecorded` belongs to another owner — use a free slot, or ask the user before any [manual machine wipe](#manual-machine-wipe). Then serialize `yarn tests:ios:pod:install` and `yarn tests:macos:pod:install` across all worktrees (one platform×slot at a time — **not** a host flock). Run ios then macos for **each configured slot** (`0..N-1`, one worktree per slot) before overlapping `:build` / `:test-cover`. Do **not** launch concurrent Apple `pod:install` across worktrees. Pre-wave release stops only the emulator/simulator instances each slot's runs recorded (leftovers from other owners stay BUSY); it does **not** dismiss an already-visible Android Emulator crash-report modal. That dialog is the **emulator binary’s** Google crash reporter (not Android Studio IDE settings, not macOS ReportCrash). Detox spawns `emulator` from CLI — use `emulator -crash-report-mode never` (see `emulator -help`; requires Android Emulator **≥ 37**, confirmed on 37.1.11.0 — older emulators lack the flag and `SPAWN_FAIL` at launch, so update the emulator rather than working around it) or set macOS `com.android.Emulator` `set.crashReportPreference` to `2` (Never; `0`=Ask, `1`=Always per AOSP `qt-settings.h`). The UI control **When to send crash reports** lives only under the **standalone** emulator window: Extended controls → Settings → General ([Android docs](https://developer.android.com/studio/run/emulator-extended-controls)); it is unavailable when the emulator runs embedded in Android Studio or headless from Detox. - -**Overlapping 3×3 is 9 cells at once.** After serialized Apple `pod:install` (CDN only), launch android + ios + macos `:test-cover` on all three worktrees together — qemu included while Apple Jets are live. Do **not** serialize Android. Do **not** wait for Apple `:test-cover` to finish before qemu. Do **not** treat Detox `currentStatus` / status-query timeout latency as host-capacity proof or as a reason to run fewer than 9 cells. Latency is tolerated: raise Detox ready/status timeouts and launch retries ([`tests/e2e/detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js), [Detox yarn patch](../ci-workflows/detox-patches.md)) so CI-like slowness waits instead of flakes. Hard infra still aborts ([startup fail-fast poll](#startup-fail-fast-poll)). Metro `/status` can be `packager-status:running` before `:build` and dead at `:test-cover` — start `yarn tests:packager:*` kill-then-start again immediately before `:test-cover` (same `RCT_METRO_PORT` / `${RNFB_METRO_CACHE_ROOT:-$HOME/.metro}/rnfb-${port}` / `/status` re-gate). Jet launch-retry/drain leftover listen PIDs this run owns (SIGTERM then SIGKILL; a foreign holder fails fast); macOS bundle wait fail-fast if `/status` is not `packager-status:running` within 120s. Same-platform 3× still needs **three worktrees**. Do **not** use host flock, Metro-after-build, per-slot `GRADLE_USER_HOME`, or `setsid`. - -**Slotted device identities (including slot 0):** `TestingAVD-N`, exact `RN E2E iOS slot-N` ([iOS slot simulators](#ios-slot-simulators)), Detox `*.slotN`, `io.invertase.testing.sN`. Console `5556+2N` (never `5554` for slotted 0). Detox `LaunchCommand` already prepends `-port`; do not add `-port` to `bootArgs`. Apple `:build` compiles only — `pod:install` is a prior step when pods may be stale. - -**Parallel / multi-platform carry-in:** every Metro/Jest/Detox process for a slot gets the **full** `RNFB_{ANDROID,IOS,MACOS}_*` set (`tests/.babelrc` / `tests-macos/.babelrc` inline static `process.env.RNFB_*`). Do not use `RNFB_E2E_PLATFORM` to choose ports. In-app: `getE2eEmulatorPort(…)` — never hardcode serial emulator ports. - -**Firebase emulator suites:** one suite per platform×slot; `yarn tests:emulator:start` pins auth/database/firestore/functions/storage/hub/logging **and** Firestore websocket / Eventarc / Tasks (`FS+8/+9/+12`). Abort if those ports are busy. Ready = Functions port listening. Serialize `scripts/functions` yarn/build across concurrent starts. - -**macOS:** `yarn tests:macos:build` derives `RNFB_MACOS_PRODUCT_NAME_SUFFIX` for pbxproj — never pass global `PRODUCT_NAME=` on the xcodebuild CLI. See [macOS process identity](#macos-process-identity-concurrency). - -| Variable | Purpose | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `RCT_METRO_PORT`, `RNFB_METRO_PORT` | Metro bundler **listen** port for this process. Slotted: matches the **active** platform×slot (`export-slot-env`), e.g. ios slot 0 = **12107**, android slot 0 = **12007** — never reuse android’s port for iOS | -| `RNFB_{ANDROID,IOS,MACOS}_METRO_PORT` | Per-platform Metro port (in-app / host selection via self-detection). Formula + slot-0 worked example: [e2e parallel design § Metro](e2e-parallel-design.md#metro-per-worktree-and-per-slot) | -| `JET_REMOTE_PORT`, `JET_METRO_PORT` | Process-local Jet / Metro hints (global fallback) | -| `RNFB_{ANDROID,IOS,MACOS}_JET_PORT` | Per-platform Jet WebSocket port | -| `RNFB_{ANDROID,IOS,MACOS}_JET_CONTROL_PORT` | Per-platform Jet HTTP control (preferred); `RNFB_JET_CONTROL_PORT` remains a process-local fallback | -| `RNFB_JET_CONTROL_PORT` | Process-local Jet HTTP control plane fallback (default `JET_REMOTE_PORT + 1`) | -| `RNFB_{ANDROID,IOS,MACOS}_EMULATOR_{FIRESTORE,AUTH,DATABASE,FUNCTIONS,STORAGE,HUB,LOGGING}_PORT` | Per-platform Firebase emulator suite (in-app + host). `yarn tests:emulator:start` also derives Firestore `websocketPort` / Eventarc / Tasks from the firestore port | -| `RNFB_DETOX_ANDROID_CONFIG`, `RNFB_DETOX_IOS_CONFIG` | Detox configuration name (e.g. `android.emu.debug.slot0`, `ios.sim.debug.slot1`). Honoured on **slotted** runs only: serial `yarn tests:*` (no `RNFB_E2E_SLOT` / `RNFB_E2E_HOST_SLOT`) unsets these and the device overrides via `e2e_sanitize_serial_env`, so e.g. `RNFB_DETOX_ANDROID_CONFIG=android.att.debug` is silently ignored and serial always targets `TestingAVD` / `iPhone 17` | -| `RNFB_DETOX_STATUS_QUERY_TIMEOUT_MS`, `RNFB_DETOX_LOGIN_TIMEOUT_MS`, `RNFB_DETOX_DEBUG_SYNCHRONIZATION_MS`, `RNFB_LAUNCH_APP_TIMEOUT_MS`, `RNFB_LAUNCH_APP_RELEASE_TIMEOUT_MS`, `RNFB_LAUNCH_APP_MAX_ATTEMPTS` | Load-latency knobs. **Defaults live in** [`tests/e2e/detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js). Detox Login / CurrentStatus floors also require the yarn patch ([detox-patches](../ci-workflows/detox-patches.md)). Do not copy timeout numbers elsewhere | -| `RNFB_ANDROID_ADB_INSTALL_TIMEOUT_MS` | Android Detox `pm install` spawn timeout (policy default **300000ms**). **Defaults live in** [`tests/e2e/detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js). Detox `ADB.js` patch hardcodes the same value at yarn apply time — env override does not reach Detox without patch regen ([detox-patches](../ci-workflows/detox-patches.md)) | -| `RNFB_JET_AWAIT_EXIT_STALL_MS` | After `launch-ready`, abort if Jet has not exited within this window (policy default **1200000ms**). Stall sets `retryableAtJetLevel` so Jet **attempt 2** (+ iOS sim reboot) runs once. Log state `stall-kill-jet`. **Defaults live in** [`tests/e2e/detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js) | -| `RNFB_E2E_SLOT` | Slot index for orchestration / AVD / sim naming. Set by `export-slot-env` — [slot index](#e2e-slot-index) | -| `GRADLE_USER_HOME` | Optional host setup only. Leave unset for the Gradle default (`~/.gradle`); slotted `export-slot-env` does not set or isolate it. If the host does not default to `$HOME/.gradle`, you may set `GRADLE_USER_HOME=$HOME/.gradle` — not a per-slot override | -| `RNFB_E2E_PLATFORM` | Optional orchestration label only — **not** used for port selection (prefer unset in slotted multi-platform launches) | -| `RNFB_ANDROID_AVD`, `RNFB_IOS_SIMULATOR`, `RNFB_ANDROID_EMULATOR_BOOT_ARGS` | Device selection overrides. Slotted helpers set `TestingAVD-{n}` / exact `RN E2E iOS slot-{n}` (including `n=0`; patched Detox reuses that iOS base or fails when registry-taken, see [iOS slot simulators](#ios-slot-simulators)); serial defaults stay `TestingAVD` / `iPhone 17`. `RNFB_ANDROID_EMULATOR_BOOT_ARGS` is snapshot flags only — never include `-port` | -| `RNFB_ANDROID_CONSOLE_PORT`, `ANDROID_SERIAL` | Android qemu console port and adb serial. **Serial** `e2e_sanitize_serial_env` pins `5554` / `emulator-5554` (`TestingAVD`). **Slotted** helpers pin `5556+2×slot` / `emulator-${port}` (adb-safe **[5554, 5584]**, skipping 5554 so unslotted `emulator-5554` can coexist). Detox patch uses this instead of FreePortFinder 10000–20000 | -| `RNFB_MACOS_PRODUCT_NAME` | macOS `PRODUCT_NAME` / process name (default `io.invertase.testing`). Required distinct per concurrent macOS slot. Slotted helpers set `io.invertase.testing.s`; override via `RNFB_MACOS_PRODUCT_NAME_OVERRIDE` | -| `RNFB_MACOS_BUNDLE_IDENTIFIER` | macOS `CFBundleIdentifier` (default derived from product name). Metro `app=` follows this. Slotted override: `RNFB_MACOS_BUNDLE_IDENTIFIER_OVERRIDE` | -| `ORG_GRADLE_PROJECT_reactNativeDevServerPort` | Android Gradle Metro port baked into the APK's `react_native_dev_server_port` resource at build time. **Set automatically** by `yarn tests:android:build` (`RNFB_ANDROID_METRO_PORT` → `RCT_METRO_PORT` → `RNFB_METRO_PORT` → `JET_METRO_PORT` → `8081`) — only export it yourself when building Android outside that script (e.g. `detox build` invoked directly). Detox's `reversePorts` (`tests/.detoxrc.js`) already forwards the same slotted Metro port; this var makes the APK actually _ask_ for that port. `yarn tests:android:test-cover` asserts that baked integer matches the active Metro port after `e2e_sanitize_serial_env` (serial **8081**, slotted `RNFB_ANDROID_METRO_PORT`). A slot-baked **12007** APK plus serial host wait/reverse **8081** is APP_STATUS `currentStatus` / `isReady` hang — host Metro prefetch of `:8081` still succeeds. Re-`:build` in the same env; do not skip `:build` after a slotted APK in this worktree. | -| `SIMCTL_CHILD_RCT_METRO_PORT` | iOS simulator child Metro port | -| `RNFB_E2E_DEBUG` | Verbose `[rnfb-e2e]` port resolution logging in app helpers | -| `RNFB_MELLIFERA` | Mellifera-only. Must **not** change RNFB `yarn tests:e2e:check` / `release` behavior. Mellifera maps a reservation to `RNFB_*` env, then calls those yarn targets | - -See [host-clear probes](#host-clear-probes) (`yarn tests:e2e:check` / `yarn tests:e2e:release`). - - - -**Global device scoping** — with no `--platform`, no `RNFB_E2E_PLATFORM`, and no per-platform port env set, check/release use **serial defaults only**. They probe android app state on the default serial and the macOS default process name, but do **not** escalate a booted serial `iPhone 17` to BUSY (INFO only). Even with `--platform=ios`, only the identity's exact simulator is BUSY; any other booted simulator is another owner's and stays INFO. Pass `--platform=ios` when iOS is about to run ([host clear](#1-host-clear)). `--platform=` does **not** load a slot — see [slot lifecycle](#slot-lifecycle). `--all-slots` is the only unscoped leftover-slot wipe, and it is [manual only](#manual-machine-wipe). - -Setup: `yarn tests:e2e:setup-android-avds [count]` / `yarn tests:e2e:setup-ios-sims [count]` (create/reuse-only; [setup count](#e2e-slot-index), [iOS slot simulators](#ios-slot-simulators)). - - - -#### iOS slot simulators (exact neutral base or fail) - -Slotted iOS devices use a **repo-neutral base name**: **`RN E2E iOS slot-N`**, with `N` a [slot index](#e2e-slot-index). [`tests/.detoxrc.js`](../../tests/.detoxrc.js) `ios.sim.debug.slotN` sets `device.name` to that **base**. The name is deliberately not RNFB-specific so one Mac can host other React Native e2e stacks — Detox or Appium — on the same slot devices; on such a host RNFB's reserved index is **slot 3** (the `yarn test:full --slot 3` example above). Serial unslotted iOS stays **`iPhone 17`** and Android stays `TestingAVD` / `TestingAVD-N`. - -| Surface | Name / owner | -| ------- | ------------ | -| `.detoxrc` `device.name` for `ios.sim.debug.slotN` | `RN E2E iOS slot-N` — the **base** | -| `yarn tests:e2e:setup-ios-sims` | create/reuse of the **base** only | -| Device that runs slotted iOS | exact **`RN E2E iOS slot-N`** base | -| `RNFB_IOS_SIMULATOR` from `export-slot-env` | the exact base used by Detox, check, and release | -| Serial `ios.sim.debug` | stock Detox allocates **`iPhone 17`**, on `RNFB_IOS_SIM_RUNTIME` when set; CI pins the booted UDID instead ([ios.md § simulator reliability](../ci-workflows/ios.md#simulator-reliability)) | - -**Stock Detox is not sufficient for this contract.** Detox 20.51.0 reuses a free matching base, but when every match is registry-taken it calls `AppleSimUtils.create()` and creates a suffixed simulator. [`tests/patches/detox+20.51.0.patch`](../../tests/patches/detox+20.51.0.patch) (`patch-package` via `tests` `prepare`) preserves free exact-base reuse for `RN E2E iOS slot-0`…`slot-7`, but fails before creation when the base is taken. The error directs the operator to confirm Mellifera/manual ownership, release the owner, and inspect the Detox device registry only when no owner is active. Serial `iPhone 17` and unrelated simulator configurations keep stock allocation behavior. Apply the patch with root `yarn` — [install / patch / fmt gate](agent-command-policy.md#install-patch-fmt-gate-blocking). This is **not** the Yarn Berry Detox patch under `.yarn/patches/` ([detox-patches.md](../ci-workflows/detox-patches.md)). - -**Setup is create/reuse-only.** `yarn tests:e2e:setup-ios-sims [count]` creates a missing base and reports an existing one as `exists`. It never deletes, renames, erases, shuts down, or re-creates a device. - -**An occupied base is a hard ownership conflict.** Detox must not escape a Mellifera/manual slot lease by creating another simulator. Release the owning run, or resolve a stale registry entry only after confirming no owner is active. - -**Check/release are exact-name scoped.** After [export](#e2e-slot-index) (or a range-validated `--slot=N`), `yarn tests:e2e:check` reports BUSY when the selected slot's exact base is booted; `yarn tests:e2e:release --devices` issues `simctl shutdown ` for the simulator that slot's run [recorded](#run-record) (shutdown only — release never deletes a simulator). Matching is whole-name, so `slot-1` never picks up `slot-10` or any suffixed name. The manual `--include-unrecorded` shuts down the exact base only when it traces to this checkout, which in practice means recorded: an unrecorded simulator's `launchd_sim` runs from `/`, so it is left running — shut it down with `xcrun simctl shutdown `. Only `--all-slots` shuts down by name, every exact base through **effective max** plus serial `iPhone 17` ([manual machine wipe](#manual-machine-wipe)). - - - -##### Migrating a host off legacy `RNFB E2E iOS slot-N` (human operator only) - -Hosts provisioned before the neutral base still hold `RNFB E2E iOS slot-N` devices (and their `-Detox` clones). Nothing in the runbook selects them, so they are inert; the only reason to remove them is reclaiming disk on a host that is about to run a slotted iOS wave. - -This is a **human-operator** procedure. Agents must not run it — `xcrun simctl delete` is not in the [agent command registry](agent-command-policy.md#canonical-registry), and unregistered direct `simctl` device commands are [forbidden](agent-command-policy.md#forbidden-always). An agent that needs the migration asks the operator to run it. - -For the **one** slot `N` being migrated (shown for `N=3`): - -```bash -xcrun simctl delete 'RNFB E2E iOS slot-3' # exact legacy base -xcrun simctl delete 'RNFB E2E iOS slot-3-Detox' # exact legacy Detox clone -yarn tests:e2e:setup-ios-sims 4 # recreate neutral bases 0..3 (create/reuse-only) -``` - -| Safety rule | Why | -| ----------- | --- | -| Delete **only** the two exact legacy names for the selected `N` | A broader match can destroy a device another worktree, repo, or operator is mid-run on | -| Never prefix/glob delete (`RNFB E2E iOS*`), `simctl delete all`, `simctl delete unavailable`, or `simctl shutdown all` | Not scoped to this migration; also [what not to do](#what-not-to-do) | -| Never delete a neutral `RN E2E iOS slot-N` base | It is the live slot device, shared with any other e2e stack on this host | -| Never delete, rename, or erase serial **`iPhone 17`** | Serial unslotted e2e and CI depend on it | -| Recreate only via `yarn tests:e2e:setup-ios-sims` | A hand-rolled `simctl create` can pick a different device type or runtime than the setup script resolves | - - - -#### macOS process identity (concurrency) - -| Surface | Default | Concurrent macOS | -| ---------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | -| **Process / `PRODUCT_NAME`** | `io.invertase.testing` | Set `RNFB_MACOS_PRODUCT_NAME` (e.g. `io.invertase.testing.s1`) — required for isolation | -| App path | `…/${PRODUCT_NAME}.app/Contents/MacOS/${PRODUCT_NAME}` | Follows product name | -| `CFBundleIdentifier` | `org.reactjs.native.io-invertase-testing` | `RNFB_MACOS_BUNDLE_IDENTIFIER` or derived `org.reactjs.native.${PRODUCT_NAME with dots→hyphens}` | -| Metro `app=` query | matches bundle ID | [`tests-macos/.jetrc.js`](../../tests-macos/.jetrc.js) reads the same env | -| Firebase / GoogleService | **None on macOS target** | No cloud re-registration for JS/Other e2e | - -`yarn tests:macos:build` exports `RNFB_MACOS_PRODUCT_NAME_SUFFIX` into the xcodebuild environment (pbxproj expansion only). Check uses `RNFB_MACOS_PRODUCT_NAME` for `pgrep`; release and the Jet harness stop only the app pid the run spawned and [recorded](#run-record) under that name (`killall` by name is only in the manual `--include-unrecorded` path). Same-platform parallel still needs **one worktree per macOS instance** ([parallel topology](#parallel-e2e-topology)). Mild residual: shared `io.invertase.firebase` preferences suite across apps. - - - -### Android emulator gray screen / Quick Boot (blocking) - -Detox's default emulator launch **restores the AVD Quick Boot snapshot** unless told otherwise. On `TestingAVD` that can leave the device **`offline` on a gray screen** — `adb devices` shows `emulator-XXXX offline` and Detox hangs on `wait-for-device`. - -**Root cause:** warm boot paths — Quick Boot snapshot restore on Detox launch, and (pre-fix) `adb reboot` on Jet retry — skip a full cold boot. - -**Fix (committed):** [`tests/.detoxrc.js`](../../tests/.detoxrc.js) sets `bootArgs: '-no-snapshot-load -no-snapshot-save'` on the `TestingAVD` device. Jet retry in [`tests/e2e/firebase.test.js`](../../tests/e2e/firebase.test.js) cold-restarts the same emulator (kill + relaunch with the same args) instead of `adb reboot`. - -**Detect:** - -```bash -adb devices -l # emulator-XXXX offline -pgrep -fl "$(node -e "console.log(require('./tests/e2e/androidAdbRange').qemuAvdPgrepPattern('TestingAVD'))")" -rg 'SPAWN_CMD.*@TestingAVD' /tmp/rnfb-e2e-android.log # no -no-snapshot-load → stale runbook / config -``` - -**Recovery before `:test-cover`:** - -```bash -# Frees the emulator this checkout's run recorded (or one a recorded process spawned): -# adb -s emu kill once emu avd name matches, plus a signal to that exact qemu -# pid. Never a kill by AVD name; never restarts the shared adb server. -yarn tests:e2e:release --platform=android --devices -yarn tests:e2e:check --platform=android # must exit 0 -# If gray screen persists after cold-boot config, wipe Quick Boot snapshots: -# rm -rf ~/.android/avd/TestingAVD.avd/snapshots -``` - -`adb kill-server` disconnects every owner's emulators; run it only at explicit user direction ([manual machine wipe](#manual-machine-wipe)). - -Then rerun [pre-flight](#pre-flight-is-the-host-clear-to-start) and `yarn tests:android:test-cover`. Cold boot adds ~30–60s to the first Android launch vs Quick Boot — expected. - -**Local settle/load stays skipped** (not CI). Serial local runs log `android-ready: skipping settle/load (not CI)` then `launchApp complete`. Forcing local settle/load without that bar can fail in ~3s with Fabric `ReactContext is null!` while Metro prefetch succeeds. - -**Android `detoxEnableSynchronization` must be `0`.** Detox native `LaunchArgs.shouldDisableSynchronization()` is `enableSynchronization.equals("0")`. Passing `'NO'` still registers Fabric idling resources (`FabricDetoxIdlingResourceFactoryStrategy` → `getCurrentReactContextSafe`). Negative: `am instrument … -e detoxEnableSynchronization NO` then `ReactContext is null!` at that factory. Positive: launch args `'0'` so idling is not installed before RN has a context. `ReactContext is null` is also retryable at launch/Jet level. After FAIL, Detox Jest `forceExit: true` plus killing the yarn/jet process tree so `:test-cover` cannot hang on open handles. - -If Detox launches then ANRs (~6s) with logcat ABI mismatch, that is **not** this path — [Android Detox launch ANR](#android-detox-launch-anr-abi-mismatch). - - - -### Android Detox launch ANR / ABI mismatch - -Sibling of [gray screen / Quick Boot](#android-emulator-gray-screen--quick-boot-blocking) — different failure. Offline-emulator / Quick Boot snapshot recovery does **not** cover this path. Do **not** treat this as an AsyncStorage product failure (`NativeModule: AsyncStorage is null` is a Metro singleton issue — [pins § AsyncStorage](test-app-dependency-pins.md#asyncstorage-dual-pin--metro-singleton)). - -**Detect:** `yarn tests:android:test-cover` Detox `am instrument` starts `com.invertase.testing`; ActivityManager **ANR ~6s**; instrumentation crashes. Logcat: `Package uses different ABI(s) than its instrumentation` (app `arm64-v8a`, test apk `null`). After FAIL, Jest prints `did not exit` and `:test-cover` **hangs until killed**. Metro Android bundle may still be HTTP 200. - -**Recovery:** - -1. Stop this run's hung `:test-cover` — the run will **not** self-exit. Stop the Shell that started it (or `kill` its exact pid). Do not `pkill -f` by command line: that matches other worktrees' runs. - -2. Then the same scoped teardown as gray-screen (emulator kill only — **not** snapshot wipe): - -```bash -yarn tests:e2e:release --platform=android --devices -yarn tests:e2e:check --platform=android # must exit 0 -``` - -3. Re-run [pre-flight](#pre-flight-is-the-host-clear-to-start) and `yarn tests:android:test-cover`. - -### iOS Detox framework cache - -Detox injects a prebuilt **`Detox.framework`** and XCUITest runner from a versioned cache under **`~/Library/Detox/ios/`** (hashed by Xcode version). iOS `:test-cover` / `:build` **fail before any test runs** if that cache is missing or stale (common after Xcode upgrade, first checkout, or a failed Detox postinstall). - -**Detect (from a failed iOS run log):** - -```bash -rg 'Detox\.framework could not be found' /tmp/rnfb-e2e-ios.log -``` - -Typical error (Detox prints the fix inline): - -```text -DetoxRuntimeError: .../Library/Detox/ios/framework//Detox.framework could not be found, -this means either you changed a version of Xcode or Detox postinstall script was unsuccessful. -To attempt a fix try running 'detox clean-framework-cache && detox build-framework-cache' -``` - -**Detect (proactive, before `:test-cover`):** - -```bash -test -d ~/Library/Detox/ios/framework/*/Detox.framework && echo "Detox framework cache: OK" || echo "Detox framework cache: MISSING" -``` - -**Fix (canonical — repo root):** - -```bash -yarn tests:ios:detox-framework-cache:rebuild -``` - -This runs Detox's `rebuild-framework-cache` (clean + build of both the injected Detox library and the XCUITest runner) from the `tests/` workspace. Expect ~10–30s on a warm machine; first build after Xcode change may take longer. - -**Verify cache present after rebuild:** - -```bash -ls ~/Library/Detox/ios/framework/*/Detox.framework -ls ~/Library/Detox/ios/xcuitest-runner/*/ -``` - -Then resume the iOS order in [Typical loop](#typical-loop). - -CI restores the same tree from `~/Library/Detox/ios` keyed by Xcode version ([iOS workflow § Detox Framework Cache Restore](../ci-workflows/ios.md)). Local developers must rebuild when the cache is missing — it is not committed to git. - - - -### TurboModule migration — stale JS/native toolchain (blocking) - -During TurboModule work, three different **`undefined`** / load failures are easy to confuse: - -| Symptom | Likely cause | Fix (escalate in order) | -| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `this.native.isFoo` is **`undefined`** in JS | Spec/native **constants** chain incomplete (`getConstants`, `getTypedExportedConstants`, iOS typed constants) | [NewArch-AD-15](../new-architecture/architecture-decisions.md#newarch-ad-15--constant-memoization-scope-static-only--accepted); spec must declare `getConstants` when JS reads native constants | -| Android `Proxy target must be an Object` | JNI not linked / **stale autolinking cache** | Delete `tests/android/build/generated/autolinking/autolinking.json` + `*.sha`, `:build` | -| Metro redbox **`Requiring unknown module "undefined"`** at app load | **Stale Metro and/or partial native refresh** after codegen / `lib/**` / podspec changes | Steps below; then [full refresh](#turbomodule-full-toolchain-refresh) if needed | - -**Detect:** app redbox before `Jet client connected`; `curl` of `index.bundle` may still return 200 — that does **not** rule out staleness. - -**Routine fix** (try first after codegen, podspec, or `packages/*/lib/**` edits): - -1. [Prepare completion gate](#prepare-completion-gate-blocking) — `yarn lerna:prepare` exit 0. -2. Regenerate codegen if specs changed — [agent command policy § TurboModule codegen](agent-command-policy.md#turbomodule-codegen) (wipe configured `outputPath`, then package `android:codegen` / `ios:codegen`). -3. **`yarn tests::build`** — iOS and macOS **compile only**. Full e2e / test process **requires** `yarn tests:ios:pod:install` / `yarn tests:macos:pod:install` as a **separate prior step** before the matching `:build` (after codegen / podspec / native Apple changes). A bare `:build` without pod install is allowed when pods are already installed and you only need a compile. Android `:build` does not use CocoaPods. -4. Matching packager reset-cache (Metro was running during the edits) — [packager reset-cache](#packager-reset-cache-eaddrinuse). -5. [Pre-flight](#pre-flight-is-the-host-clear-to-start) → **`yarn tests::test-cover`**. - - - -**Full toolchain refresh** — when the routine fix still shows `Requiring unknown module "undefined"` or you wiped `node_modules` mid-migration: - -1. [Pre-flight recovery](#pre-flight-recovery) — stop Metro, Jet, Detox; scoped sim/AVD release via `yarn tests:e2e:release --devices` when needed. -2. Remove **all** `node_modules` (repo root, `tests/`, and under `packages/*` if present). -3. **`yarn`** at repo root (wait for exit 0 — includes `lerna:prepare`, root Gemfile gems via `yarn ruby:install`, and patches). -4. Confirm [install / patch / fmt gate](agent-command-policy.md#install-patch-fmt-gate-blocking) (fmt **≥ 12.1.0**) before any native `:build`. -5. Regenerate **all** touched packages' codegen from `tests/` ([agent command policy § TurboModule codegen](agent-command-policy.md#turbomodule-codegen)). -6. **iOS/macOS:** `yarn tests::pod:install` then `yarn tests::build` as two commands (`:build` compiles only). Required after codegen / podspec / native Apple changes. A bare `:build` is allowed when pods are already installed. Android skips `pod:install`. -7. Matching packager reset-cache ([packager reset-cache](#packager-reset-cache-eaddrinuse)) → pre-flight → `:test-cover`. - -Do **not** treat this redbox as a missing TurboModule registration until the refresh sequence has been run once on a clean tree. - -## Diagnosing hangs - -**Local stalls** — see [stalled run detection](#stalled-run-detection) first (Metro `/status`, `Jet client connected` markers). - -**Native / device logs** (remove instrumentation before merge): - -- **macOS** — `log show --predicate 'process == "io.invertase.testing"' --last 10m --style compact`; filter `com.facebook.react.log:javascript` for bundle errors. **Blank window / Jet never connects:** often `Native module NativeRNFBTurboApp is not registered` — [NewArch-AD-2](../new-architecture/architecture-decisions.md#newarch-ad-2--naming-nativernfbturbo--accepted) (web/macOS registry must include turbo keys). Other bundle errors → [other.md](../ci-workflows/other.md) -- **iOS** — `xcrun simctl spawn booted log stream --level debug --style compact --predicate 'process == "testing"'`; silent hangs: `sample ` on `testing`. Metro redbox **`Requiring unknown module "undefined"`** → [TurboModule stale toolchain](#turbomodule-stale-toolchain-blocking). -- **Android** — `adb logcat` (filter your tags) - -**Crashlytics on-disk report inspection (iOS / Android):** - -- **iOS** — pending reports live under the app container's `Library/Caches/com.crashlytics.data//v5/reports/active//` (`custom_exception_{a,b}.clsrecord`, `user_incremental_kv.clsrecord`). String fields such as the exception `reason` are **hex-encoded**, so a plain-text grep for the error message gives false negatives — hex-decode, or also match the hex form (e.g. `printf '%s' "$MSG" | xxd -p | tr -d '\n'`). The SDK processes and removes `active/` reports on the next app launch, so inspect before relaunching. -- **Android** — pending events are **plain JSON** at `files/.crashlytics.v3//open-sessions//event<10 digits>`, with custom keys in that session's `keys` file. The next launch — including a background restart by datatransport `JobInfoSchedulerService` — can finalize sessions into `reports/`, so inspect before any relaunch and diff the whole `.crashlytics.v3/` tree rather than one path. -- **Android `run-as` access** — `adb shell run-as com.invertase.testing` needs a debuggable APK. Making the `tests/android` release build debuggable (to keep the embedded JS bundle without Metro) flips `BuildConfig.DEBUG`, which enables React Native developer support and makes the app expect Metro; also override `getUseDeveloperSupport()` → `false` in `tests/android` `MainApplication`. Both changes are local-only and never committed. Physical-device runs: [agent command policy § physical-device runs](agent-command-policy.md#physical-device-runs). - -**Benign noise:** iOS Detox `EXEC_FAIL "xcrun simctl terminate … io.invertase.testing" … found nothing to terminate` — app wasn't running; ignore. - -**Cloud API pressure** — Installations / Remote Config failures with FIS 503 or “Too many server requests” are live-project quota on **any** platform, not emulator issues. See [Firebase testing project — CI triage](firebase-testing-project.md#ci-triage-cloud-api-quota-pressure). - -## Before merge (PR handoff) - -Pre-merge applies once to the branch commit stream before merge/push intended for merge, not after every commit. - -1. Remove all narrowing ([full tier](#e2e-validation-tiers-unit-focused-area-focused-full)): delete `tests/harness.overrides.js` (or `{}`), revert any temporary `require.context` → single `require` edits in `tests/app.js`, remove all `.only`, remove native instrumentation. Committed `tests/globals.js` / `tests/app.js` stay at full harness defaults — do not revert durable product wiring (e.g. `NativeRNFBTurbo*` proxy). -2. [Pre-flight](#pre-flight-is-the-host-clear-to-start) — [host-clear probes](#host-clear-probes) pass before each platform run. -3. Rebuild when needed (`tests::build`; `yarn lerna:prepare` for `lib/**`). After TurboModule codegen or native bridge edits, see [TurboModule stale toolchain](#turbomodule-stale-toolchain-blocking). -4. Full unfocused suite with coverage on **iOS, Android, macOS** — one platform at a time, all green. -5. Record [validation evidence package](validation-checklist.md#validation-evidence-package) and [coverage evidence package](coverage-design.md#coverage-evidence-package) when lib/native touched — required before merge or push ([change authoring § validation evidence](change-authoring-workflow.md#validation-evidence-blocking)). +**Never invoke the test runner (Jet), Detox, Metro, or emulators directly.** Use **only** the repo-root `yarn tests:*` commands defined in this runbook (this file and the `e2e/` files below; for example `yarn tests:packager:jet`, `yarn tests:emulator:start`, `yarn tests::test-cover`). Do not run `jet`, `npx jet`, `yarn jet`, `detox test`, `cd tests && …`, or ad-hoc Metro/emulator start commands. When another doc mentions e2e, Jet, Detox, or pre-flight, follow the link to this runbook — do not infer commands from log output or implementation details. + +Install, prepare, validation, the workspace Expo example / documented-path iOS **link** closer (`yarn test-expo:ios:link`), and the RN CLI prebuilt RNCore iOS **build** fixture (`yarn test-rn-bare:ios:build`) are **not** in this doc — they live in [agent command policy](agent-command-policy.md). Those commands are **not** Detox e2e. E2e stays exclusively `yarn tests:*`. **Before any native `:build`:** [install / patch / fmt gate](commands/native-build-gate.md#install-patch-fmt-gate-blocking) (root `yarn` exit 0 + fmt **≥ 12.1.0**). + +## Files + +Content moved from this file into the files below. Headings and anchors keep their names in the new file; each old anchor sits on the line under its new home, so old `#links` still land here and point on. + +- [E2e: prerequisites and Apple host toolchain](e2e/prerequisites.md): Once-per-checkout e2e prerequisites, Apple host toolchain expectations, and physical device signing. + +- [E2e: rules](e2e/rules.md): Canonical e2e command rules (packager, emulators, rebuild, coverage), test-app native modules, infrastructure change bar, and what not to do. + +- [E2e: running one iteration](e2e/run-loop.md): Serialized e2e loops, how a platform run is structured, test-runner host orchestration log triage, and running one iteration. + +- [E2e: startup fail-fast poll](e2e/startup-fail-fast.md): Startup fail-fast markers, poll cadence, and hard-infra vs latency classification. + +- [E2e: pre-flight](e2e/preflight.md): Pre-flight steps before every :test-cover: prepare complete, services ready, checkout ownership, and harness tier. Host-clear detail is a separate file. + +- [E2e: pre-flight step 1, host clear](e2e/preflight-host-clear.md): Host-clear table, Android app reset, host-clear probes, run record, and manual machine wipe. + +- [E2e: recovery and diagnosis](e2e/recovery.md): Pre-flight recovery, packager start and reset-cache, stalled run detection, interrupted runs, and diagnosing hangs. + +- [E2e: gates and validation tiers](e2e/gates.md): Harness narrowing gate, platform coverage gate, unit-focused loop, one :test-cover at a time, e2e validation tiers, and before-merge. + +- [E2e: typical loop and test narrowing](e2e/narrowing.md): Typical loop, local harness overrides, spec loading, sanity counts, and RNFBDebug fail-fast / sub-suite narrowing. + +- [E2e: environment and slot topology](e2e/environment.md): Devices and stale-process environment notes, configurable e2e environment, parallel topology, slot lifecycle, and slot index. + +- [E2e: full suite orchestrator](e2e/full-suite.md): yarn test:full flags, deterministic release, overlapping verify / Jest, and scratch paths. + +- [E2e: slotted parallel operation](e2e/slotted-parallel.md): Slotted mode readiness, first use of a slot, carry-in, check/release, waves, overlapping pods, and global device scoping. + +- [E2e: slot environment variables](e2e/slot-env-variables.md): Reference table of every RNFB e2e port, device, and timeout environment variable. +- [E2e: iOS slot simulators and macOS process identity](e2e/slot-devices.md): Exact neutral iOS slot simulator contract, legacy migration (human operator only), and macOS process identity. + +- [E2e: platform troubleshooting](e2e/platform-troubleshooting.md): Android emulator gray screen, Detox launch ANR / ABI mismatch, iOS Detox framework cache, and TurboModule stale toolchain. + ## Notes diff --git a/okf-bundle/testing/test-app-dependency-pins.md b/okf-bundle/testing/test-app-dependency-pins.md index 7e25822307..b655028c4f 100644 --- a/okf-bundle/testing/test-app-dependency-pins.md +++ b/okf-bundle/testing/test-app-dependency-pins.md @@ -12,7 +12,7 @@ Canonical owner for **intentional** version locks on the e2e apps (`tests/` mobi Codegen determinism: [NewArch-AD-20](../new-architecture/architecture-decisions.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted). -**Apple CI / local e2e alignment:** dedicated iOS jobs require **Xcode 27** (stable) and default simulator runtime **`iOS 27.0`** ([iOS CI workflows § Apple CI toolchain](../ci-workflows/ios.md#apple-ci-toolchain-xcode-27)); local hosts should match [running e2e § Apple host toolchain](running-e2e.md#apple-host-toolchain-local). These pins are **test-fixture only** — do not raise RNFB consumer deployment or Xcode floors in product metadata when documenting them. +**Apple CI / local e2e alignment:** dedicated iOS jobs require **Xcode 27** (stable) and default simulator runtime **`iOS 27.0`** ([iOS CI workflows § Apple CI toolchain](../ci-workflows/ios.md#apple-ci-toolchain-xcode-27)); local hosts should match [running e2e § Apple host toolchain](e2e/prerequisites.md#apple-host-toolchain-local). These pins are **test-fixture only** — do not raise RNFB consumer deployment or Xcode floors in product metadata when documenting them. @@ -58,7 +58,7 @@ Root `package.json` must **not** use blanket `resolutions` for `react-native`, ` **CLI rationale:** mobile CLI **`20.2.0`** matches the React Native **0.88.0-rc.3** community template (`@react-native-community/template@0.88.0-rc.3-ada64d0`; the bare `0.88.0-rc.3` tag is not that template). macOS keeps the **0.78** CLI band with `react-native-macos@0.78.6`. Never add a global resolution that would pull `tests-macos` onto the mobile line. -**fmt / Apple Clang:** RN **0.88.0-rc.3** ships fmt **12.1.0** upstream (no mobile `patch-package` fmt bump). macOS **0.78.3** still applies [`tests-macos/patches/react-native+0.78.3.patch`](../../tests-macos/patches/react-native+0.78.3.patch). Always verify via [install / patch / fmt gate](agent-command-policy.md#install-patch-fmt-gate-blocking). +**fmt / Apple Clang:** RN **0.88.0-rc.3** ships fmt **12.1.0** upstream (no mobile `patch-package` fmt bump). macOS **0.78.3** still applies [`tests-macos/patches/react-native+0.78.3.patch`](../../tests-macos/patches/react-native+0.78.3.patch). Always verify via [install / patch / fmt gate](commands/native-build-gate.md#install-patch-fmt-gate-blocking). **macOS deployment target (Xcode 27):** Xcode 27 rejects `MACOSX_DEPLOYMENT_TARGET` below **12.0**. `react-native-macos` **0.78.6** podspecs still declare macOS **11.0**, and `react_native_post_install` only clamps to that floor, so a Podfile `platform` bump alone is insufficient. [`tests-macos/macos/Podfile`](../../tests-macos/macos/Podfile) therefore sets `platform :macos, '12.0'` and, in `post_install` after `react_native_post_install`, raises every pod target (including `*_privacy` resource bundles and aggregate targets) whose `MACOSX_DEPLOYMENT_TARGET` is unset or below 12.0 to **12.0**. The app project already targets **12.0**. Test fixture only — RNFB consumer React Native, Xcode, and deployment floors are unchanged. Remove the override only when `react-native-macos` moves to a line whose podspecs declare ≥ **12.0**. @@ -102,10 +102,10 @@ Mobile `tests/` is on async-storage **3.x** (TurboModule `RNAsyncStorage`). macO ## Related -- [Running e2e § Apple host toolchain](running-e2e.md#apple-host-toolchain-local) — local Xcode 27 + iOS 27.0 + Device Hub +- [Running e2e § Apple host toolchain](e2e/prerequisites.md#apple-host-toolchain-local) — local Xcode 27 + iOS 27.0 + Device Hub - [iOS CI workflows § Apple CI toolchain](../ci-workflows/ios.md#apple-ci-toolchain-xcode-27) — GHA `xcode-27` gate - [NewArch-AD-20](../new-architecture/architecture-decisions.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted) — codegen reproducibility / no floating toolchain -- [NewArch-AD-21](../new-architecture/architecture-decisions.md#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--accepted) — ResultT inject **retired** on mobile 0.86 (upstream emits `ResultT`) +- [NewArch-AD-21](../new-architecture/architecture-decisions.md#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete) — ResultT inject **retired** on mobile 0.86 (upstream emits `ResultT`) - [Other CI — macOS e2e](../ci-workflows/other.md) — macOS pipeline (`tests-macos/`) - [Agent command policy](agent-command-policy.md) — install / patch / fmt gate - [`tests/package.json`](../../tests/package.json) / [`tests-macos/package.json`](../../tests-macos/package.json) / [`test-expo/package.json`](../../test-expo/package.json) / [`test-rn-bare/package.json`](../../test-rn-bare/package.json) — declared pins diff --git a/okf-bundle/testing/validation-checklist.md b/okf-bundle/testing/validation-checklist.md index 0aedf175e1..78b1de7c57 100644 --- a/okf-bundle/testing/validation-checklist.md +++ b/okf-bundle/testing/validation-checklist.md @@ -3,264 +3,34 @@ type: Reference title: Validation checklist description: Canonical command sequence for validating RNFB TS/JS changes, e2e, and handoff. tags: [testing, validation, jest, compare-types, lint, coverage] -timestamp: 2026-09-10T00:00:00Z +timestamp: 2026-12-02T00:00:00Z --- # Validation checklist Validation commands for development/handoff. Other docs/skills link here; do not restate. -Coverage acceptance: [expectations](coverage-design.md#coverage-expectations-policy) + [completion signal](coverage-design.md#coverage-as-completion-signal) on every touched file. - -## When to run what - - - -Work types and tiers: [change authoring workflow](change-authoring-workflow.md#work-types). Term ids: [iteration vocabulary](iteration-vocabulary.md). - -| Work type | Scope | Shortcuts | -| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `gap-analysis` | `compare:types`, config read, SDK declarations | n/a | -| `baseline-capture` | Full loaded spec(s) + e2e on [**every required platform**](running-e2e.md#platform-coverage-gate-blocking) | **area-focused** tier; [area narrowing required](running-e2e.md#harness-narrowing-gate-blocking); no `.only`, no `:test-cover-reuse`; **no platform shortcuts** | -| `implementation` | Unit-focused Jest + e2e on **every required platform** when native bridge, **committed `**/generated/**`**, podspec/spec/codegen wiring, or macOS TS/runtime path changed — **Jest-only / `yarn codegen:verify` do not close `implementation_gate`**; `lib/**` edits need `yarn lerna:prepare` + Metro restart, not platform `:build` for JS alone ([running e2e § Rules #3](running-e2e.md#rules)) | **unit-focused** tier; [harness overrides + RNFBDebug](running-e2e.md#local-harness-overrides-harnessoverridesjs) before `:test-cover`; optional `.only` / sub-suite for diagnosis; [platform coverage gate](running-e2e.md#platform-coverage-gate-blocking) — no platform shortcuts | -| `documentation` | Promote user docs + durable OKF + `AGENTS.md` + `CONTRIBUTING.md` on the same change set **before** `independent-review` | none — does **not** run the [OKF bundle scan](#okf-bundle-review); loop: [change authoring § work types](change-authoring-workflow.md#work-types) | -| `independent-review` | Full checklist; e2e on **every required platform** (macOS / iOS / Android per harness); **this pass is the OKF scan** when `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` are in the frozen tree | **area-focused** tier; [platform coverage gate](running-e2e.md#platform-coverage-gate-blocking) — **no shortcuts**; [frozen tree](change-authoring-workflow.md#frozen-tree) (report-only except revert `.only`); never commit overrides, sub-suite `.only`, or temporary `tests/app.js` edits ([fail-fast §](running-e2e.md#fail-fast-rnfbdebug-and-sub-suite-narrowing)) | -| `commit` | Stage after gates closed | [change authoring § commit](change-authoring-workflow.md#commit) — staging only; OKF contract findings → `documentation?` then re-scan | -| `pre-merge-validation` | Full unfocused suite | **full** tier — [running-e2e § merge](running-e2e.md#before-merge-pr-handoff); entire PR branch, once | - -## Prepare and compile - -Repo root. **Agents:** [agent command policy](agent-command-policy.md) — only these invocations; never `yarn workspace … prepare` or package-scoped `yarn run build` for diagnostics. - -```bash -yarn # install + postinstallDev (lerna:prepare + ruby:install) -yarn lerna:prepare # after packages/*/lib/** edits — transpiles lib → dist/module via each package prepare target -yarn tsc:compile -yarn tsc:compile:consumer -yarn tsc:compile:test-expo # when test-expo/** TS in the diff — [agent command policy](agent-command-policy.md); never `cd test-expo && tsc` -yarn attw:check # scoped attw + Expo plugin smoke; allowlisted pack stage — [Types-AD](architecture-decisions.md) -``` - -`yarn lerna:prepare` runs each package **`prepare`** script (`build` then `compile`/bob). That is the canonical **`lib/**`→`dist/module/**`** path. Do **not** use `cd packages/ && yarn compile` as a substitute — `compile` is a step **inside** `prepare`, not a standalone agent entrypoint. - -**Blocking:** `yarn` and `yarn lerna:prepare` must **exit 0 before any other command** (Jest, tsc, e2e, Metro, builds) — never parallelize. [Agent command policy § prepare must finish first](agent-command-policy.md#prepare-must-finish-first); e2e pre-flight: [running e2e § prepare completion gate](running-e2e.md#prepare-completion-gate-blocking). **Before native `:build`:** [install / patch / fmt gate](agent-command-policy.md#install-patch-fmt-gate-blocking) (fmt **≥ 12.1.0**). - -## API reference and type parity - -```bash -yarn reference:api # after consumer tsc -yarn compare:types # remove stale config entries when fixed -``` - -Configs: `.github/scripts/compare-types/configs/`. Package workflows define ordering (e.g. [pipelines](../packages/firestore/pipeline-implementation-workflow.md#compare-types-gap-analysis)). - -When **`typedoc.json` or `packages/*/typedoc.json`** changes anything that can alter reference URL structure, also run the [legacy redirect audit](../documentation-site-maintenance.md#redirect-audit-required-when-typedoc-config-changes) (verify every `docs.json` → `redirects` target; add mappings for newly orphaned legacy `/reference/...` paths). - -For any package registered in `compare:types`, type parity is a **review-gate requirement**, not a best-effort signal. Before closing `independent-review`, the touched package must have: - -- no undocumented differences, -- no stale config entries, -- and any intentional RN-only exports documented in that package config to the [compare-types justification bar](../../.github/scripts/compare-types/README.md#justification-bar). - -If `yarn compare:types` fails because of unrelated packages, keep the touched package's result in the handoff and add/fix a work-queue item for the unrelated drift. Do not close a review gate for a registered package when its own compare-types output is failing. - -## Jest - -```bash -yarn tests:jest # full suite at handoff -``` - -Focused example: - -```bash -yarn tests:jest --watchman=false packages/firestore/__tests__/pipelines.test.ts -``` - -Optional: `yarn tests:jest-coverage`. - - -**Focused coverage:** `--collectCoverageFrom` is an array option, so test paths placed after it are swallowed as globs and Jest runs every suite; put the test paths first and pass one brace glob (`yarn tests:jest --watchman=false packages/analytics/plugin packages/auth/plugin --coverage --coverageReporters=text '--collectCoverageFrom=packages/{analytics,auth}/plugin/src/**/*.ts'`). - - -**Unhandled rejections:** on Node 24 an unhandled promise rejection crashes the Jest process (`triggerUncaughtException`), aborting the file so other tests report nothing; a `process.on('unhandledRejection')` listener in a test cannot reliably observe it (Jest sandboxes `process`). Assert the handler is attached instead: spy the method returning the promise, wrap the returned promise's `then` to capture the derived promise, and assert that resolves (pattern: `packages/app-check/__tests__/initializeAppCheck.test.ts`). When proving such tests fail on old code, run them one at a time (`-t`) so each failure is reported. - - - -**Host-dependent test (darwin).** `packages/app/__tests__/iosSimulatorHelpers.test.js` › "resolves slot-1 UDID on pinned runtime when present" runs live `simctl` on macOS and fails unless an **`RN E2E iOS slot-1`** simulator exists on `RNFB_IOS_SIM_RUNTIME` (default `iOS 27.0`); on Linux it only static-checks the helper. On a Mac without that device the full suite exits 1 whatever the diff is. To provision it: `yarn tests:e2e:setup-ios-sims 2` (creates slot-0 and slot-1; create/reuse-only — [setup count](running-e2e.md#e2e-slot-index), [iOS slot simulators](running-e2e.md#ios-slot-simulators)). When a reviewer cannot provision it, rerun that file alone (`yarn tests:jest --watchman=false packages/app/__tests__/iosSimulatorHelpers.test.js`) to show only that test fails, and record the `jest` row with the real exit and evidence such as `N-1/N suites; 1 host-dependent failure (no slot-1 sim), unrelated to diff`. This exemption does not apply when the diff touches `scripts/e2e/lib/ios-simulator-helpers.sh`, `scripts/e2e/create-ios-simulators.sh`, or that test file. - -## Android JVM unit tests - -When `packages/*/android/**` Java bridge/state-machine logic changed (or added under `src/test/java`): - -```bash -yarn tests:android:unit # JUnit-first — [AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1) -``` - -Produces Jacoco `*.exec` that **counts** toward native touched-line coverage when merged. After Android e2e: - -```bash -yarn tests:android:post-e2e-coverage # pull .ec → jacocoTestReport (unit + e2e merge) -# optional explicit merge: -yarn tests:android:test:jacoco-report -``` - -Merged Codecov path: `jacocoTestReport.xml` — [coverage design](coverage-design.md). JVM unit does **not** replace [platform coverage gate](running-e2e.md#platform-coverage-gate-blocking) e2e. - - - -## iOS XCTest unit tests - -When `packages/*/ios/**` Objective-C/C++ bridge logic changed (or an in-package `*UnitTests.xcodeproj` was added): - -```bash -yarn tests:ios:unit # macOS/host-first — [IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1) -``` - -Produces `coverage/ios-unit/lcov.info` and **merges into** `coverage/ios-native/lcov.info`. After iOS e2e, `yarn tests:ios:test:process-coverage` merges unit LCOV again so e2e export does not drop XCTest hits — [coverage design](coverage-design.md) (non-zero exit from the trailing NYC JS report can leave `coverage/ios-native/lcov.info` already written and usable). In-package XCTest does **not** replace [platform coverage gate](running-e2e.md#platform-coverage-gate-blocking) e2e. - - - -## iOS Ruby unit tests (SPM / CocoaPods helpers) - -**Blocking for `implementation_gate` / `review_gate` / handoff** when the diff touches any of: - -- `packages/app/**/*.rb` (production helpers such as `firebase_spm.rb`, `firebase_json.rb`) -- `packages/app/__tests__/*_test.rb` - -```bash -yarn ruby:install # root Gemfile; included in root yarn via postinstallDev; skips exit 0 when bundle not on PATH, ruby < 3.3.1, or bundle cannot run -yarn tests:ios:ruby # yarn lint:ruby (RuboCop) then all *_test.rb + SimpleCov → coverage/ios-ruby/lcov.info -yarn lint:ruby # RuboCop only (same Gemfile; not part of root yarn lint) -``` - -Do not `bundle install --gemfile=packages/app/__tests__/Gemfile`. That vendors under `packages/app/__tests__/vendor/` and `yarn lint:js` then fails on vendor. [JS lint / Bundler vendor](agent-command-policy.md#js-lint-bundler-vendor). - -Host Ruby must be **>= 3.3.1** (not 3.3.0); do not downgrade lockfile `simplecov` — [agent command policy § iOS Ruby](agent-command-policy.md#ios-ruby-spm-helpers). - -Opt-in shape/embed suites skip cleanly when cocoapods/xcodeproj are absent; exit **0** when only skips occur alongside a green unit suite. Coverage artifact and Codecov flag **`ios-ruby`**: [coverage design § iOS Ruby](coverage-design.md#ios-ruby-simplecov). Touched production Ruby lines need test support in the [coverage evidence package](coverage-design.md#coverage-evidence-package) before `review_gate` closes — same spirit as JS/native touched-line bar. Canonical command only ([agent command policy](agent-command-policy.md)); do **not** use ad-hoc `ruby packages/app/__tests__/…_test.rb` as the gate. - - - -## Lint and formatting - -**Blocking before `implementation` handoff and on the frozen tree for `independent-review`.** Run from repo root after prepare/compile when TS/JS changed. **Owner of which script to run** — [change authoring](change-authoring-workflow.md) hops here; do not duplicate this table there. - -**CI Lint job** (`.github/workflows/linting.yml`) is `yarn lint` = `lint:js` + `lint:deps` + `lint:android` + `lint:ios:check`. `lint:android` is **Java** (`google-java-format`); it does **not** format Kotlin. Kotlin format is repo-root `./gradlew ktlintFormat` ([agent command policy](agent-command-policy.md)), not part of `yarn lint`. - -### Lint-by-tree / by-diff - -Run **only** the scripts whose trees are in the diff (exit 0). Do not run the rest. - -| Tree in diff | Script | Notes | -| ------------ | ------ | ----- | -| `packages/**` or `test-expo/**` JS/TS | `yarn lint:js` | ESLint `packages/*` and `test-expo/` (one script; do not invent a `test-expo` lint entrypoint). Implementation may `yarn lint:js --fix` then re-run until clean. Prefer that over `yarn format:js`. A flood under `packages/app/__tests__/vendor/` is local Bundler vendor, not product lint. Do not treat it as the lint gate. [Agent command policy § JS lint / Bundler vendor](agent-command-policy.md#js-lint-bundler-vendor). | -| `packages/*/lib/**` | `yarn lint:deps` | Blocking. [dependency-cycle linting](../monorepo-tooling/prepare-and-cache.md#dependency-cycle-linting). | -| Java under `packages/*/android` | `yarn lint:android` | **Implementation only.** `google-java-format --set-exit-if-changed --replace` on **`.java`** — **mutates**. Does **not** format `.kt`. Only Java entrypoint ([agent command policy](agent-command-policy.md)); never invent `yarn google-java-format` / `npx google-java-format`. Can flake; rerun once/twice if failure is not clearly in diff. Commit formatter output. | -| Kotlin under `packages/*/android` or `tests/android/**/*.kt` | repo-root `./gradlew ktlintFormat` | **Implementation only.** **Mutates.** Include `tests/android/**/*.kt` when those files are in the diff. Invocation and filter: [agent command policy § Android Kotlin format](agent-command-policy.md#android-kotlin-format). Frozen review: do not run. | -| iOS native (`packages/*/ios` `.h` / `.cpp` / `.m` / `.mm`, not generated) | `yarn lint:ios:check` | clang-format **check** (`-n -Werror`). Implementation may `yarn lint:ios:fix` then re-check. Repo pins `clang-format@1.7.0` (exact, not `^`): `1.8.0` ships darwin **x86_64** only (needs Rosetta); `1.7.0`’s misnamed `darwin_x64` path is native **arm64**. Intel Mac is not a supported local `lint:ios` host (App Store / Xcode / macOS floor). | -| `docs/**`, or docs tooling (`scripts/docs-snippets-tsc.mjs`, `scripts/docs-member-check.mjs`, `scripts/lib/mdx-fences.mjs`, `eslint.docs-snippets.config.mjs`) | `yarn lint:markdown` (`yarn lint:markdown:fix` for Prettier formatting) then `yarn lint:spellcheck` then `yarn docs:tsc:check` then `yarn docs:member:check` then `yarn lint:docs-links` | Docs tree globs and the docs tooling files above (CI docs job). OKF-only diffs skip these. Gotchas below. Link-check: [§ docs.page link check](#docs-page-link-check). | - - - -**Docs lint gotchas** (docs tree or docs tooling only): - -- **`yarn lint:markdown`:** three steps, all blocking. (1) ESLint on `docs/**/*.mdx` with the base config. (2) ESLint with `eslint.docs-snippets.config.mjs` (`flatCodeBlocks` over `js`, `javascript`, `jsx`, `ts`, `typescript` and `tsx` fences): parse errors, `no-undef` (`js` / `jsx` fences), unused variables (`@typescript-eslint` rule for `ts` / `tsx` fences) and `react/jsx-no-undef` (`ts` / `tsx` fences). Top-level named function and arrow helper bindings are exempt from the unused-variable check (the config appends a `void (...)` reference); fences marked `// codeblock-ignore` are skipped. (3) Prettier `--check` on `docs/**/*.mdx` and the docs tooling `.mjs` files (exact table column padding). `yarn lint:markdown:fix` runs Prettier `--write` over the same set ([agent command policy](agent-command-policy.md)). Wide tables: prefix `{/* prettier-ignore */}`, compact single-space cells, see `docs/migrating-to-v26.mdx`. -- **Spellcheck frontmatter:** `spellchecker-cli` exits **0** when frontmatter fails to parse (`Failed to parse YAML frontmatter, ignoring it`) and skips checking that page's frontmatter. `yarn lint:spellcheck` runs it through `scripts/spellcheck.mjs`, which streams the output through unchanged and turns that case into exit **1** with a fix hint. Unquoted colons in values (e.g. `description: v27: Imagen API removal`) are the common trigger — quote the value. Keep that wrapper in place if the script is ever rewritten; a bare `spellchecker` invocation restores the silent pass. -- **`yarn docs:tsc:check`:** blocking. Compiles the `js`, `javascript`, `jsx`, `ts`, `typescript` and `tsx` fences in `docs/**/*.mdx` against the consumer type surface (`tsconfig.consumer.json`); other fence languages are counted and listed as not compiled. Exit **1** on a failed fence, on a fence-grammar error (unclosed fence, `~~~` fence, or a fence inside a blockquote), or when no compilable fence is found. The fence grammar (indented fences are de-indented, CRLF is normalised) is shared with `docs:member:check` in `scripts/lib/mdx-fences.mjs`. Imports are hoisted with the TypeScript compiler API and the rest of the fence is wrapped in an async function, so top-level `await` and `export default` compile. Unhandled forms (`export const`, `export { ... }`, `export =`, `import x = require()`) need the ignore marker. Opt out of an intentionally partial fence with `// codeblock-ignore` as the first non-blank line inside the fence. Limits: strict mode is off, so null misuse and implicit `any` are not reported, and all fences share one type environment, so a fence can pass because another fence pulls in a global type. Failures print `:`. The console shows the first 10 failing fences followed by `and M more ... not shown`; set `DOCS_TSC_ALL=1` on the same command to print every failing fence, then filter that output by path to confirm one docs area. Generated files in gitignored `.docs-snippets-tsc/` are named `docs__.block.`. Do not re-check with `yarn tsc --project tsconfig.docs-snippets.generated.json ` (TS5042: project cannot mix with source files) or a full-project `yarn tsc -p` (the `tsc` CLI drops cross-file semantic diagnostics). For TS2307 on an `@react-native-firebase/*` package whose `dist/typescript` is missing, the output names the prepare command from the [agent command policy](agent-command-policy.md#prepare-must-finish-first). -- **`yarn docs:member:check`:** blocking. For each `.github/scripts/compare-types/configs/.ts`: (1) every `extraInRN` name must be mentioned (prose or code) under that package's docs tree (`perf-config` → `docs/perf`, `firestore-pipelines` → `docs/firestore`), except names in the `DEPRECATED_EXEMPT` list in `scripts/docs-member-check.mjs` (config basename → name → reason; each entry needs a non-empty reason, and an exempt name that docs still mention does not fail); (2) every runtime function the taught pages import by name from the package must be referenced by the matching `test-expo/app` screen. The screen must value-import the name from the same specifier the docs use, and the local binding must appear as an identifier outside import statements (comments and strings do not count). This proves a reference, not a call. Taught pages are `docs//usage/**` by default; `app` reads `docs/app/**`; `firestore-pipelines` reads `docs/firestore/pipelines/**` and only the `@react-native-firebase/firestore/pipelines` specifier. A package that needs a screen and teaches zero names fails. Limits: namespace and default imports teach nothing; `// codeblock-ignore` fences still count as taught; a local that shadows an imported name is not detected. A screen control for an untaught function does not fail. Guards: every `packages/*` directory with a `package.json` needs a compare-types config or an `EXEMPT_PACKAGES` entry with a reason (`vertexai`), and a stale exemption fails; `NO_SCREEN` packages (none today) fail if a screen file exists; the check verifies every `DEPRECATED_EXEMPT` name is in that config's `extraInRN` and that each top-level exported declaration of it under `packages//lib/**` carries an `@deprecated` JSDoc tag, so an exemption cannot hide a live API (only top-level declarations are seen: re-export specifiers, `export { A as X }` aliases, namespace members, `export import` and destructured exports are not, so such a name fails closed with "not found"), and a stale entry (config gone, name not in `extraInRN`, name not found in source, or no longer deprecated) fails. Migration guides are not packages. `DOCS_MEMBER_VERBOSE=1` lists the taught names and each verified deprecated exemption with its `@deprecated` file:line. - -A JS-only (or docs-only) diff does **not** require full `yarn lint`. Full `yarn lint` is the CI equivalent when the diff spans those package trees **and** mutating `lint:android` is allowed (`implementation`). Full `yarn lint` still does **not** run Kotlin `ktlintFormat`. - -### Frozen `independent-review` (check-only) - -Frozen review is [report/check-only except revert `.only`](change-authoring-workflow.md#frozen-tree). **Do not** run `yarn lint:android`, repo-root `./gradlew ktlintFormat`, or full `yarn lint` — those formatters **mutate** the tree. Run the **check-only** by-diff scripts: `lint:js` (JS/TS), `lint:deps` (lib), `lint:ios:check` (ios), `yarn lint:markdown`/`yarn lint:spellcheck`/`yarn lint:docs-links`/`docs:tsc:check`/`docs:member:check` (docs tree or [docs tooling](#docs-lint-gotchas) only). There is no allowlisted check-only Kotlin ktlint task. - - - -### `yarn lint:docs-links` — fix failures; bot-gate warnings only - -When `docs/**` is in the diff, **`yarn lint:docs-links` exit code 0** is blocking ([change authoring § validation evidence](change-authoring-workflow.md#validation-evidence-blocking)). Record it during `documentation` and re-confirm on frozen `independent-review` — [change authoring § work types](change-authoring-workflow.md#work-types); missing that evidence when `docs/**` was touched is **serious**. Which failures are errors vs warnings, and the `rnfirebase.io` override: [documentation site maintenance § Docs.page link check](../documentation-site-maintenance.md#docs-page-link-check-ci). - -**Agents must fix every `error` line** (internal links, assets, MDX render, metadata, true external 404s). Do not hand off or close gates while errors remain. - -**The only acceptable non-fix** is a **`warn`** on an **external** link where the checker reports a **bot/WAF gate** (common on npmjs.com, stackoverflow.com, some Google support URLs). Those URLs are often valid in a browser. **Do not** replace, remove, or “fix” those links to clear warnings, and do not relax check severity (flags or `docs.json` overrides) to hide real failures. - -If an external link is a true **404** / **not found** at **error** severity, fix it like any other error. If unsure, verify in a browser; 403 from npm/SO in warn output alone is not grounds to change the link. An **error** that clears on re-run — a **5xx** or timeout on any host, or a bot-gate status (e.g. **429**) on `rnfirebase.io` — is a host/rate problem, not a broken link: re-run until exit 0; do not change the link or the override. One that fails on every re-run is a real breakage — fix it. - -## Expo example and documented-path iOS link (not e2e) - -`test-expo/` is a user-facing Expo example **and** the documented-path iOS link closer. Closer: **`yarn test-expo:ios:link`** only (build-only; does not launch) — [agent command policy](agent-command-policy.md). Typecheck: **`yarn tsc:compile:test-expo`**. JS lint: **`yarn lint:js`** (already includes `test-expo/`; do not invent a second lint entrypoint). Not Detox; do not add `yarn tests:ios:*` or ad-hoc `expo prebuild` / `xcodebuild` / `cd test-expo && …` as those gates. App package: [packages/app](../packages/app/index.md). - -## RN CLI prebuilt RNCore iOS compile (not e2e) - -Workspace fixture `test-rn-bare/`: **`yarn test-rn-bare:ios:build`** then **`yarn test-rn-bare:ios:launch-smoke`** (iOS 27 UIScene gate; CI runs both, and again for the dynamic Firebase probe with facade-reference, framework-load, and configure assertions — [probe launch smoke](agent-command-policy.md#dynamic-firebase-probe-launch-smoke)) — [agent command policy](agent-command-policy.md). Not Detox; not the Expo link/launch closers; do not add `yarn tests:ios:*` or ad-hoc `pod` / `xcodebuild` / `simctl` as those closers. App package: [packages/app](../packages/app/index.md). - -## E2e with coverage - -[Pre-flight](running-e2e.md#pre-flight-is-the-host-clear-to-start) (host-clear probes + services + **[checkout ownership](running-e2e.md#services-checkout-ownership-blocking)** + harness tier) before every run — [agent command policy](agent-command-policy.md) and [e2e agent rule](running-e2e.md#agent-rule-read-first): use **only** `yarn tests:*` commands from [running e2e](running-e2e.md). Match harness to work type — **unit-focused**/**area-focused** never use full app load ([running e2e § harness](running-e2e.md#3-harness-matches-validation-tier)). - -Commands: [Running e2e tests](running-e2e.md). Post-process: [Coverage design](coverage-design.md) (iOS `tests:ios:test:process-coverage`, Android `tests:android:unit` + `tests:android:post-e2e-coverage` → merged `jacocoTestReport`). - -Some suites hit **cloud APIs**, e.g. Firestore Pipelines → `pipelines-e2e` Enterprise DB ([pipelines.md](../packages/firestore/pipelines.md#backend-cloud-enterprise-not-the-local-emulator)). - -## OKF bundle review - -When the frozen tree includes `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md`, **`independent-review` is this scan**. Confirm every [OKF update contract](../documentation-policy.md#okf-update-contract) row: Canonical location, DRY, [Efficiency](../documentation-policy.md#efficiency), link hygiene, Durability. **Report only** — do not edit the frozen tree. The `documentation` work type promotes durable text; it does not run this scan. Close `commit` only after this scan when those files changed. Do not add OKF after a frozen review without another `independent-review`. - -Goal: each iteration improves OKF and removes conflicting guidance. Check meanings live in the contract; do not treat this list as a thinner substitute. - - - -## Validation evidence package - -**Blocking.** Before closing **`implementation_gate`**, **`review_gate`**, **`commit_gate`**, or publishing (`git push` / PR update), record evidence per [change authoring § validation evidence](change-authoring-workflow.md#validation-evidence-blocking). Minimum template: - -```markdown -| Step | Command | Exit | Evidence | -| ------------------------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------------------------------------------------------------- | -| prepare | yarn lerna:prepare | 0 | — | -| jest | yarn tests:jest | 0 | N/N tests | -| ios Ruby unit | yarn tests:ios:ruby | 0 | when `packages/app/**/*.rb` or `packages/app/__tests__/*_test.rb` touched — coverage/ios-ruby/lcov.info ([§ iOS Ruby](#ios-ruby-unit-tests)) | -| android JVM unit | yarn tests:android:unit | 0 | when `packages/*/android/**` Java changed — [AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1) | -| ios XCTest unit | yarn tests:ios:unit | 0 | when `packages/*/ios/**` ObjC/C++ or `*UnitTests.xcodeproj` changed — [IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1) | -| e2e macOS | yarn tests:macos:test-cover | 0 | X passing — /tmp/...log | -| e2e iOS | yarn tests:ios:test-cover | 0 | Y passing — /tmp/...log | -| e2e Android | yarn tests:android:test-cover | 0 | Z passing — /tmp/...log | -| android merged Jacoco | yarn tests:android:post-e2e-coverage | 0 | jacocoTestReport.xml (unit + e2e) — [coverage design](coverage-design.md) | -| compare:types | yarn compare:types | 0 | 0/0/0 | -| lint (by-tree) | [§ lint and formatting](#lint-and-formatting) | 0 | matching scripts; frozen review: check-only (no `lint:android` / `ktlintFormat` / full `yarn lint`) | -| lint:deps (lib diff) | yarn lint:deps | 0 | when `packages/*/lib/**` in diff — [dependency-cycle linting](../monorepo-tooling/prepare-and-cache.md#dependency-cycle-linting) | -| lint:markdown (CI docs) | yarn lint:markdown | 0 | when `docs/**` or docs tooling in diff (ESLint, snippet ESLint, Prettier; [§ gotchas](#docs-lint-gotchas)) | -| lint:spellcheck (CI docs) | yarn lint:spellcheck | 0 | when `docs/**` in diff | -| docs:tsc:check (CI docs) | yarn docs:tsc:check | 0 | when `docs/**` or docs tooling in diff; failed fence, fence-grammar error, or no compilable fence exits 1 | -| docs:member:check (CI docs) | yarn docs:member:check | 0 | when `docs/**`, docs tooling, compare-types configs, test-expo screens, or a new `packages/*` directory in diff | -| lint:docs-links (CI docs) | yarn lint:docs-links | 0 | when `docs/**` in diff — errors fail; bot-gate warnings do not | -| coverage | post-process + region table | — | [coverage evidence package](coverage-design.md#coverage-evidence-package); closes `coverage_evidence_gate` when lib/native bridge or `packages/app/**/*.rb` touched | -``` - -Exit codes must be the **real** ones: the agent shell is zsh, where `${PIPESTATUS[0]}` silently expands to empty — [agent command policy § agent shell is zsh](agent-command-policy.md#agent-shell-is-zsh). - -**History rewrite invalidates** prior rows — re-run and replace the table after amend/rebase. - -## Handoff checklist - -- [ ] `yarn lerna:prepare` (after any `packages/*/lib/**` edits) -- [ ] `yarn tsc:compile`, `yarn tsc:compile:consumer` -- [ ] `yarn tsc:compile:test-expo` when `test-expo/**` TS is in the diff ([agent command policy](agent-command-policy.md)) -- [ ] `yarn attw:check` when `package.json` `exports`, `plugin/build`, or published types changed ([Types-AD](architecture-decisions.md)) -- [ ] `yarn reference:api` -- [ ] Redirect audit when TypeDoc config changed ([documentation site maintenance § redirect audit](../documentation-site-maintenance.md#redirect-audit-required-when-typedoc-config-changes)) -- [ ] `yarn tests:jest` -- [ ] `yarn tests:ios:ruby` when `packages/app/**/*.rb` or `packages/app/__tests__/*_test.rb` touched ([§ iOS Ruby](#ios-ruby-unit-tests); [coverage design](coverage-design.md#ios-ruby-simplecov)) -- [ ] `yarn tests:android:unit` when `packages/*/android/**` Java / `src/test/java` changed ([AndroidTest-AD-1](android-architecture-decisions.md#androidtest-ad-1)) -- [ ] `yarn tests:ios:unit` when `packages/*/ios/**` ObjC/C++ or `packages/*/ios/*UnitTests` changed ([IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1)) -- [ ] TurboModule wrapper contract ([NewArch-AD-17.1](../new-architecture/architecture-decisions.md#newarch-ad-171--jest-turbomodule-contract-test--accepted)) when `packages/app/lib/internal/registry/nativeModule.ts`, `nativeModuleAndroidIos.ts`, or TurboModule wrapper behavior changed: `yarn tests:jest -- packages/app/__tests__/nativeModuleContract.test.ts` -- [ ] `yarn compare:types` (stale config entries removed) -- [ ] Lint by-tree / by-diff per [§ lint and formatting](#lint-and-formatting) (frozen `independent-review`: check-only — no `yarn lint:android` / `./gradlew ktlintFormat` / full `yarn lint`) -- [ ] E2e green on **every required platform** for the changed module ([platform coverage gate](running-e2e.md#platform-coverage-gate-blocking); [harness narrowing gate](running-e2e.md#harness-narrowing-gate-blocking); no `.only`; committed `RNFBDebug` remains `false`) -- [ ] Android post-e2e merged Jacoco when Android native touched: `yarn tests:android:post-e2e-coverage` → `jacocoTestReport.xml` ([coverage design](coverage-design.md)) -- [ ] [Validation evidence package](validation-checklist.md#validation-evidence-package) recorded (exit codes, e2e counts, log paths) -- [ ] [Coverage evidence package](coverage-design.md#coverage-evidence-package) when lib/native bridge **or** `packages/app/**/*.rb` touched — `coverage_evidence_gate` closed with verdict line; gaps investigated to fix, delete, or acceptable-exception bar -- [ ] Durable OKF / `AGENTS.md` / `CONTRIBUTING.md` promoted in `documentation` **before** frozen review; [OKF bundle scan](#okf-bundle-review) completed in `independent-review` when those files changed (contract findings → `documentation?` then re-scan, not `commit`-pass edits) - -Package workflows may add items (e.g. pipeline before/after snapshots — [pipeline workflow](../packages/firestore/pipeline-implementation-workflow.md)). +Coverage acceptance: [expectations](code-coverage/policy.md#coverage-expectations-policy) + [completion signal](code-coverage/policy.md#coverage-as-completion-signal) on every touched file. + +## Files + +Content moved from this file into the files below. Headings and anchors keep their names in the new file; each old anchor sits on the line under its new home, so old `#links` still land here and point on. + +- [Validation: when to run what](validation/work-types.md): Validation scope and allowed shortcuts per work type. + +- [Validation: prepare, compile, API reference, type parity](validation/compile-and-types.md): Prepare and tsc commands, reference:api, compare:types review-gate bar, and the TypeDoc redirect audit trigger. + +- [Validation: Jest](validation/jest.md): Jest commands, focused coverage flags, unhandled rejection pattern, and the host-dependent darwin test exemption. + +- [Validation: native unit tests](validation/native-unit.md): Android JVM unit, iOS XCTest unit, and iOS Ruby unit test rows with their triggers. + +- [Validation: lint and formatting](validation/lint.md): Lint-by-tree script table (blocking), what full yarn lint covers, and frozen-review check-only rules. + +- [Validation: docs lint](validation/docs-lint.md): Docs lint gotchas (lint:markdown, spellcheck, docs:tsc:check, docs:member:check) and the lint:docs-links bar. + +- [Validation: Expo, RN CLI fixtures and e2e](validation/fixtures-and-e2e.md): Expo example link, RN CLI prebuilt RNCore compile, and e2e-with-coverage validation rows. + +- [Validation: OKF bundle review](validation/okf-review.md): When independent-review is the OKF bundle scan and what it checks. + +- [Validation: evidence package and handoff checklist](validation/evidence-and-handoff.md): Validation evidence template (blocking) and the handoff checklist. + diff --git a/okf-bundle/testing/validation/compile-and-types.md b/okf-bundle/testing/validation/compile-and-types.md new file mode 100644 index 0000000000..8d827a7cf6 --- /dev/null +++ b/okf-bundle/testing/validation/compile-and-types.md @@ -0,0 +1,47 @@ +--- +type: Reference +title: 'Validation: prepare, compile, API reference, type parity' +description: 'Prepare and tsc commands, reference:api, compare:types review-gate bar, and the TypeDoc redirect audit trigger.' +tags: [testing, validation, tsc, compare-types] +timestamp: 2026-12-02T00:00:00Z +--- + +# Validation: prepare, compile, API reference, type parity + +Part of [Validation checklist](../validation-checklist.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Prepare and compile + +Repo root. **Agents:** [agent command policy](../agent-command-policy.md) — only these invocations; never `yarn workspace … prepare` or package-scoped `yarn run build` for diagnostics. + +```bash +yarn # install + postinstallDev (lerna:prepare + ruby:install) +yarn lerna:prepare # after packages/*/lib/** edits — transpiles lib → dist/module via each package prepare target +yarn tsc:compile +yarn tsc:compile:consumer +yarn tsc:compile:test-expo # when test-expo/** TS in the diff — [agent command policy](../agent-command-policy.md); never `cd test-expo && tsc` +yarn attw:check # scoped attw + Expo plugin smoke; allowlisted pack stage — [Types-AD](../architecture-decisions.md) +``` + +`yarn lerna:prepare` runs each package **`prepare`** script (`build` then `compile`/bob). That is the canonical **`lib/**`→`dist/module/**`** path. Do **not** use `cd packages/ && yarn compile` as a substitute — `compile` is a step **inside** `prepare`, not a standalone agent entrypoint. + +**Blocking:** `yarn` and `yarn lerna:prepare` must **exit 0 before any other command** (Jest, tsc, e2e, Metro, builds) — never parallelize. [Agent command policy § prepare must finish first](../commands/core.md#prepare-must-finish-first); e2e pre-flight: [running e2e § prepare completion gate](../e2e/preflight.md#prepare-completion-gate-blocking). **Before native `:build`:** [install / patch / fmt gate](../commands/native-build-gate.md#install-patch-fmt-gate-blocking) (fmt **≥ 12.1.0**). + +## API reference and type parity + +```bash +yarn reference:api # after consumer tsc +yarn compare:types # remove stale config entries when fixed +``` + +Configs: `.github/scripts/compare-types/configs/`. Package workflows define ordering (e.g. [pipelines](../../packages/firestore/pipeline-implementation-workflow.md#compare-types-gap-analysis)). + +When **`typedoc.json` or `packages/*/typedoc.json`** changes anything that can alter reference URL structure, also run the [legacy redirect audit](../../documentation-site-maintenance.md#redirect-audit-required-when-typedoc-config-changes) (verify every `docs.json` → `redirects` target; add mappings for newly orphaned legacy `/reference/...` paths). + +For any package registered in `compare:types`, type parity is a **review-gate requirement**, not a best-effort signal. Before closing `independent-review`, the touched package must have: + +- no undocumented differences, +- no stale config entries, +- and any intentional RN-only exports documented in that package config to the [compare-types justification bar](../../../.github/scripts/compare-types/README.md#justification-bar). + +If `yarn compare:types` fails because of unrelated packages, keep the touched package's result in the handoff and add/fix a work-queue item for the unrelated drift. Do not close a review gate for a registered package when its own compare-types output is failing. diff --git a/okf-bundle/testing/validation/docs-lint.md b/okf-bundle/testing/validation/docs-lint.md new file mode 100644 index 0000000000..1de61f849d --- /dev/null +++ b/okf-bundle/testing/validation/docs-lint.md @@ -0,0 +1,32 @@ +--- +type: Reference +title: 'Validation: docs lint' +description: 'Docs lint gotchas (lint:markdown, spellcheck, docs:tsc:check, docs:member:check) and the lint:docs-links bar.' +tags: [testing, validation, docs, lint] +timestamp: 2026-12-02T00:00:00Z +--- + +# Validation: docs lint + +Part of [Validation checklist](../validation-checklist.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + + + +**Docs lint gotchas** (docs tree or docs tooling only): + +- **`yarn lint:markdown`:** three steps, all blocking. (1) ESLint on `docs/**/*.mdx` with the base config. (2) ESLint with `eslint.docs-snippets.config.mjs` (`flatCodeBlocks` over `js`, `javascript`, `jsx`, `ts`, `typescript` and `tsx` fences): parse errors, `no-undef` (`js` / `jsx` fences), unused variables (`@typescript-eslint` rule for `ts` / `tsx` fences) and `react/jsx-no-undef` (`ts` / `tsx` fences). Top-level named function and arrow helper bindings are exempt from the unused-variable check (the config appends a `void (...)` reference); fences marked `// codeblock-ignore` are skipped. (3) Prettier `--check` on `docs/**/*.mdx` and the docs tooling `.mjs` files (exact table column padding). `yarn lint:markdown:fix` runs Prettier `--write` over the same set ([agent command policy](../agent-command-policy.md)). Wide tables: prefix `{/* prettier-ignore */}`, compact single-space cells, see `docs/migrating-to-v26.mdx`. +- **Spellcheck frontmatter:** `spellchecker-cli` exits **0** when frontmatter fails to parse (`Failed to parse YAML frontmatter, ignoring it`) and skips checking that page's frontmatter. `yarn lint:spellcheck` runs it through `scripts/spellcheck.mjs`, which streams the output through unchanged and turns that case into exit **1** with a fix hint. Unquoted colons in values (e.g. `description: v27: Imagen API removal`) are the common trigger — quote the value. Keep that wrapper in place if the script is ever rewritten; a bare `spellchecker` invocation restores the silent pass. +- **`yarn docs:tsc:check`:** blocking. Compiles the `js`, `javascript`, `jsx`, `ts`, `typescript` and `tsx` fences in `docs/**/*.mdx` against the consumer type surface (`tsconfig.consumer.json`); other fence languages are counted and listed as not compiled. Exit **1** on a failed fence, on a fence-grammar error (unclosed fence, `~~~` fence, or a fence inside a blockquote), or when no compilable fence is found. The fence grammar (indented fences are de-indented, CRLF is normalised) is shared with `docs:member:check` in `scripts/lib/mdx-fences.mjs`. Imports are hoisted with the TypeScript compiler API and the rest of the fence is wrapped in an async function, so top-level `await` and `export default` compile. Unhandled forms (`export const`, `export { ... }`, `export =`, `import x = require()`) need the ignore marker. Opt out of an intentionally partial fence with `// codeblock-ignore` as the first non-blank line inside the fence. Limits: strict mode is off, so null misuse and implicit `any` are not reported, and all fences share one type environment, so a fence can pass because another fence pulls in a global type. Failures print `:`. The console shows the first 10 failing fences followed by `and M more ... not shown`; set `DOCS_TSC_ALL=1` on the same command to print every failing fence, then filter that output by path to confirm one docs area. Generated files in gitignored `.docs-snippets-tsc/` are named `docs__.block.`. Do not re-check with `yarn tsc --project tsconfig.docs-snippets.generated.json ` (TS5042: project cannot mix with source files) or a full-project `yarn tsc -p` (the `tsc` CLI drops cross-file semantic diagnostics). For TS2307 on an `@react-native-firebase/*` package whose `dist/typescript` is missing, the output names the prepare command from the [agent command policy](../commands/core.md#prepare-must-finish-first). +- **`yarn docs:member:check`:** blocking. For each `.github/scripts/compare-types/configs/.ts`: (1) every `extraInRN` name must be mentioned (prose or code) under that package's docs tree (`perf-config` → `docs/perf`, `firestore-pipelines` → `docs/firestore`), except names in the `DEPRECATED_EXEMPT` list in `scripts/docs-member-check.mjs` (config basename → name → reason; each entry needs a non-empty reason, and an exempt name that docs still mention does not fail); (2) every runtime function the taught pages import by name from the package must be referenced by the matching `test-expo/app` screen. The screen must value-import the name from the same specifier the docs use, and the local binding must appear as an identifier outside import statements (comments and strings do not count). This proves a reference, not a call. Taught pages are `docs//usage/**` by default; `app` reads `docs/app/**`; `firestore-pipelines` reads `docs/firestore/pipelines/**` and only the `@react-native-firebase/firestore/pipelines` specifier. A package that needs a screen and teaches zero names fails. Limits: namespace and default imports teach nothing; `// codeblock-ignore` fences still count as taught; a local that shadows an imported name is not detected. A screen control for an untaught function does not fail. Guards: every `packages/*` directory with a `package.json` needs a compare-types config or an `EXEMPT_PACKAGES` entry with a reason (`vertexai`), and a stale exemption fails; `NO_SCREEN` packages (none today) fail if a screen file exists; the check verifies every `DEPRECATED_EXEMPT` name is in that config's `extraInRN` and that each top-level exported declaration of it under `packages//lib/**` carries an `@deprecated` JSDoc tag, so an exemption cannot hide a live API (only top-level declarations are seen: re-export specifiers, `export { A as X }` aliases, namespace members, `export import` and destructured exports are not, so such a name fails closed with "not found"), and a stale entry (config gone, name not in `extraInRN`, name not found in source, or no longer deprecated) fails. Migration guides are not packages. `DOCS_MEMBER_VERBOSE=1` lists the taught names and each verified deprecated exemption with its `@deprecated` file:line. + + + +### `yarn lint:docs-links` — fix failures; bot-gate warnings only + +When `docs/**` is in the diff, **`yarn lint:docs-links` exit code 0** is blocking ([change authoring § validation evidence](../authoring/gates.md#validation-evidence-blocking)). Record it during `documentation` and re-confirm on frozen `independent-review` — [change authoring § work types](../authoring/loop.md#work-types); missing that evidence when `docs/**` was touched is **serious**. Which failures are errors vs warnings, and the `rnfirebase.io` override: [documentation site maintenance § Docs.page link check](../../documentation-site-maintenance.md#docs-page-link-check-ci). + +**Agents must fix every `error` line** (internal links, assets, MDX render, metadata, true external 404s). Do not hand off or close gates while errors remain. + +**The only acceptable non-fix** is a **`warn`** on an **external** link where the checker reports a **bot/WAF gate** (common on npmjs.com, stackoverflow.com, some Google support URLs). Those URLs are often valid in a browser. **Do not** replace, remove, or “fix” those links to clear warnings, and do not relax check severity (flags or `docs.json` overrides) to hide real failures. + +If an external link is a true **404** / **not found** at **error** severity, fix it like any other error. If unsure, verify in a browser; 403 from npm/SO in warn output alone is not grounds to change the link. An **error** that clears on re-run — a **5xx** or timeout on any host, or a bot-gate status (e.g. **429**) on `rnfirebase.io` — is a host/rate problem, not a broken link: re-run until exit 0; do not change the link or the override. One that fails on every re-run is a real breakage — fix it. diff --git a/okf-bundle/testing/validation/evidence-and-handoff.md b/okf-bundle/testing/validation/evidence-and-handoff.md new file mode 100644 index 0000000000..6b2309b378 --- /dev/null +++ b/okf-bundle/testing/validation/evidence-and-handoff.md @@ -0,0 +1,67 @@ +--- +type: Reference +title: 'Validation: evidence package and handoff checklist' +description: 'Validation evidence template (blocking) and the handoff checklist.' +tags: [testing, validation, evidence, handoff] +timestamp: 2026-12-02T00:00:00Z +--- + +# Validation: evidence package and handoff checklist + +Part of [Validation checklist](../validation-checklist.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + + + +## Validation evidence package + +**Blocking.** Before closing **`implementation_gate`**, **`review_gate`**, **`commit_gate`**, or publishing (`git push` / PR update), record evidence per [change authoring § validation evidence](../authoring/gates.md#validation-evidence-blocking). Minimum template: + +```markdown +| Step | Command | Exit | Evidence | +| ------------------------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------------------------------------------------------------- | +| prepare | yarn lerna:prepare | 0 | — | +| jest | yarn tests:jest | 0 | N/N tests | +| ios Ruby unit | yarn tests:ios:ruby | 0 | when `packages/app/**/*.rb` or `packages/app/__tests__/*_test.rb` touched — coverage/ios-ruby/lcov.info ([§ iOS Ruby](native-unit.md#ios-ruby-unit-tests)) | +| android JVM unit | yarn tests:android:unit | 0 | when `packages/*/android/**` Java changed — [AndroidTest-AD-1](../android-architecture-decisions.md#androidtest-ad-1) | +| ios XCTest unit | yarn tests:ios:unit | 0 | when `packages/*/ios/**` ObjC/C++ or `*UnitTests.xcodeproj` changed — [IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1) | +| e2e macOS | yarn tests:macos:test-cover | 0 | X passing — /tmp/...log | +| e2e iOS | yarn tests:ios:test-cover | 0 | Y passing — /tmp/...log | +| e2e Android | yarn tests:android:test-cover | 0 | Z passing — /tmp/...log | +| android merged Jacoco | yarn tests:android:post-e2e-coverage | 0 | jacocoTestReport.xml (unit + e2e) — [coverage design](../coverage-design.md) | +| compare:types | yarn compare:types | 0 | 0/0/0 | +| lint (by-tree) | [§ lint and formatting](lint.md#lint-and-formatting) | 0 | matching scripts; frozen review: check-only (no `lint:android` / `ktlintFormat` / full `yarn lint`) | +| lint:deps (lib diff) | yarn lint:deps | 0 | when `packages/*/lib/**` in diff — [dependency-cycle linting](../../monorepo-tooling/prepare-and-cache.md#dependency-cycle-linting) | +| lint:markdown (CI docs) | yarn lint:markdown | 0 | when `docs/**` or docs tooling in diff (ESLint, snippet ESLint, Prettier; [§ gotchas](docs-lint.md#docs-lint-gotchas)) | +| lint:spellcheck (CI docs) | yarn lint:spellcheck | 0 | when `docs/**` in diff | +| docs:tsc:check (CI docs) | yarn docs:tsc:check | 0 | when `docs/**` or docs tooling in diff; failed fence, fence-grammar error, or no compilable fence exits 1 | +| docs:member:check (CI docs) | yarn docs:member:check | 0 | when `docs/**`, docs tooling, compare-types configs, test-expo screens, or a new `packages/*` directory in diff | +| lint:docs-links (CI docs) | yarn lint:docs-links | 0 | when `docs/**` in diff — errors fail; bot-gate warnings do not | +| coverage | post-process + region table | — | [coverage evidence package](../code-coverage/policy.md#coverage-evidence-package); closes `coverage_evidence_gate` when lib/native bridge or `packages/app/**/*.rb` touched | +``` + +Exit codes must be the **real** ones: the agent shell is zsh, where `${PIPESTATUS[0]}` silently expands to empty — [agent command policy § agent shell is zsh](../commands/core.md#agent-shell-is-zsh). + +**History rewrite invalidates** prior rows — re-run and replace the table after amend/rebase. + +## Handoff checklist + +- [ ] `yarn lerna:prepare` (after any `packages/*/lib/**` edits) +- [ ] `yarn tsc:compile`, `yarn tsc:compile:consumer` +- [ ] `yarn tsc:compile:test-expo` when `test-expo/**` TS is in the diff ([agent command policy](../agent-command-policy.md)) +- [ ] `yarn attw:check` when `package.json` `exports`, `plugin/build`, or published types changed ([Types-AD](../architecture-decisions.md)) +- [ ] `yarn reference:api` +- [ ] Redirect audit when TypeDoc config changed ([documentation site maintenance § redirect audit](../../documentation-site-maintenance.md#redirect-audit-required-when-typedoc-config-changes)) +- [ ] `yarn tests:jest` +- [ ] `yarn tests:ios:ruby` when `packages/app/**/*.rb` or `packages/app/__tests__/*_test.rb` touched ([§ iOS Ruby](native-unit.md#ios-ruby-unit-tests); [coverage design](../code-coverage/local.md#ios-ruby-simplecov)) +- [ ] `yarn tests:android:unit` when `packages/*/android/**` Java / `src/test/java` changed ([AndroidTest-AD-1](../android-architecture-decisions.md#androidtest-ad-1)) +- [ ] `yarn tests:ios:unit` when `packages/*/ios/**` ObjC/C++ or `packages/*/ios/*UnitTests` changed ([IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1)) +- [ ] TurboModule wrapper contract ([NewArch-AD-17.1](../../new-architecture/architecture-decisions.md#newarch-ad-171--jest-turbomodule-contract-test--accepted)) when `packages/app/lib/internal/registry/nativeModule.ts`, `nativeModuleAndroidIos.ts`, or TurboModule wrapper behavior changed: `yarn tests:jest -- packages/app/__tests__/nativeModuleContract.test.ts` +- [ ] `yarn compare:types` (stale config entries removed) +- [ ] Lint by-tree / by-diff per [§ lint and formatting](lint.md#lint-and-formatting) (frozen `independent-review`: check-only — no `yarn lint:android` / `./gradlew ktlintFormat` / full `yarn lint`) +- [ ] E2e green on **every required platform** for the changed module ([platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking); [harness narrowing gate](../e2e/gates.md#harness-narrowing-gate-blocking); no `.only`; committed `RNFBDebug` remains `false`) +- [ ] Android post-e2e merged Jacoco when Android native touched: `yarn tests:android:post-e2e-coverage` → `jacocoTestReport.xml` ([coverage design](../coverage-design.md)) +- [ ] [Validation evidence package](#validation-evidence-package) recorded (exit codes, e2e counts, log paths) +- [ ] [Coverage evidence package](../code-coverage/policy.md#coverage-evidence-package) when lib/native bridge **or** `packages/app/**/*.rb` touched — `coverage_evidence_gate` closed with verdict line; gaps investigated to fix, delete, or acceptable-exception bar +- [ ] Durable OKF / `AGENTS.md` / `CONTRIBUTING.md` promoted in `documentation` **before** frozen review; [OKF bundle scan](okf-review.md#okf-bundle-review) completed in `independent-review` when those files changed (contract findings → `documentation?` then re-scan, not `commit`-pass edits) + +Package workflows may add items (e.g. pipeline before/after snapshots — [pipeline workflow](../../packages/firestore/pipeline-implementation-workflow.md)). diff --git a/okf-bundle/testing/validation/fixtures-and-e2e.md b/okf-bundle/testing/validation/fixtures-and-e2e.md new file mode 100644 index 0000000000..43f8ca2c98 --- /dev/null +++ b/okf-bundle/testing/validation/fixtures-and-e2e.md @@ -0,0 +1,27 @@ +--- +type: Reference +title: 'Validation: Expo, RN CLI fixtures and e2e' +description: 'Expo example link, RN CLI prebuilt RNCore compile, and e2e-with-coverage validation rows.' +tags: [testing, validation, expo, e2e] +timestamp: 2026-12-02T00:00:00Z +--- + +# Validation: Expo, RN CLI fixtures and e2e + +Part of [Validation checklist](../validation-checklist.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Expo example and documented-path iOS link (not e2e) + +`test-expo/` is a user-facing Expo example **and** the documented-path iOS link closer. Closer: **`yarn test-expo:ios:link`** only (build-only; does not launch) — [agent command policy](../agent-command-policy.md). Typecheck: **`yarn tsc:compile:test-expo`**. JS lint: **`yarn lint:js`** (already includes `test-expo/`; do not invent a second lint entrypoint). Not Detox; do not add `yarn tests:ios:*` or ad-hoc `expo prebuild` / `xcodebuild` / `cd test-expo && …` as those gates. App package: [packages/app](../../packages/app/index.md). + +## RN CLI prebuilt RNCore iOS compile (not e2e) + +Workspace fixture `test-rn-bare/`: **`yarn test-rn-bare:ios:build`** then **`yarn test-rn-bare:ios:launch-smoke`** (iOS 27 UIScene gate; CI runs both, and again for the dynamic Firebase probe with facade-reference, framework-load, and configure assertions — [probe launch smoke](../commands/fixtures.md#dynamic-firebase-probe-launch-smoke)) — [agent command policy](../agent-command-policy.md). Not Detox; not the Expo link/launch closers; do not add `yarn tests:ios:*` or ad-hoc `pod` / `xcodebuild` / `simctl` as those closers. App package: [packages/app](../../packages/app/index.md). + +## E2e with coverage + +[Pre-flight](../e2e/preflight.md#pre-flight-is-the-host-clear-to-start) (host-clear probes + services + **[checkout ownership](../e2e/preflight.md#services-checkout-ownership-blocking)** + harness tier) before every run — [agent command policy](../agent-command-policy.md) and [e2e agent rule](../running-e2e.md#agent-rule-read-first): use **only** `yarn tests:*` commands from [running e2e](../running-e2e.md). Match harness to work type — **unit-focused**/**area-focused** never use full app load ([running e2e § harness](../e2e/preflight.md#3-harness-matches-validation-tier)). + +Commands: [Running e2e tests](../running-e2e.md). Post-process: [Coverage design](../coverage-design.md) (iOS `tests:ios:test:process-coverage`, Android `tests:android:unit` + `tests:android:post-e2e-coverage` → merged `jacocoTestReport`). + +Some suites hit **cloud APIs**, e.g. Firestore Pipelines → `pipelines-e2e` Enterprise DB ([pipelines.md](../../packages/firestore/pipelines.md#backend-cloud-enterprise-not-the-local-emulator)). diff --git a/okf-bundle/testing/validation/jest.md b/okf-bundle/testing/validation/jest.md new file mode 100644 index 0000000000..9e8594c1a9 --- /dev/null +++ b/okf-bundle/testing/validation/jest.md @@ -0,0 +1,35 @@ +--- +type: Reference +title: 'Validation: Jest' +description: 'Jest commands, focused coverage flags, unhandled rejection pattern, and the host-dependent darwin test exemption.' +tags: [testing, validation, jest] +timestamp: 2026-12-02T00:00:00Z +--- + +# Validation: Jest + +Part of [Validation checklist](../validation-checklist.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Jest + +```bash +yarn tests:jest # full suite at handoff +``` + +Focused example: + +```bash +yarn tests:jest --watchman=false packages/firestore/__tests__/pipelines.test.ts +``` + +Optional: `yarn tests:jest-coverage`. + + +**Focused coverage:** `--collectCoverageFrom` is an array option, so test paths placed after it are swallowed as globs and Jest runs every suite; put the test paths first and pass one brace glob (`yarn tests:jest --watchman=false packages/analytics/plugin packages/auth/plugin --coverage --coverageReporters=text '--collectCoverageFrom=packages/{analytics,auth}/plugin/src/**/*.ts'`). + + +**Unhandled rejections:** on Node 24 an unhandled promise rejection crashes the Jest process (`triggerUncaughtException`), aborting the file so other tests report nothing; a `process.on('unhandledRejection')` listener in a test cannot reliably observe it (Jest sandboxes `process`). Assert the handler is attached instead: spy the method returning the promise, wrap the returned promise's `then` to capture the derived promise, and assert that resolves (pattern: `packages/app-check/__tests__/initializeAppCheck.test.ts`). When proving such tests fail on old code, run them one at a time (`-t`) so each failure is reported. + + + +**Host-dependent test (darwin).** `packages/app/__tests__/iosSimulatorHelpers.test.js` › "resolves slot-1 UDID on pinned runtime when present" runs live `simctl` on macOS and fails unless an **`RN E2E iOS slot-1`** simulator exists on `RNFB_IOS_SIM_RUNTIME` (default `iOS 27.0`); on Linux it only static-checks the helper. On a Mac without that device the full suite exits 1 whatever the diff is. To provision it: `yarn tests:e2e:setup-ios-sims 2` (creates slot-0 and slot-1; create/reuse-only — [setup count](../e2e/environment.md#e2e-slot-index), [iOS slot simulators](../e2e/slot-devices.md#ios-slot-simulators)). When a reviewer cannot provision it, rerun that file alone (`yarn tests:jest --watchman=false packages/app/__tests__/iosSimulatorHelpers.test.js`) to show only that test fails, and record the `jest` row with the real exit and evidence such as `N-1/N suites; 1 host-dependent failure (no slot-1 sim), unrelated to diff`. This exemption does not apply when the diff touches `scripts/e2e/lib/ios-simulator-helpers.sh`, `scripts/e2e/create-ios-simulators.sh`, or that test file. diff --git a/okf-bundle/testing/validation/lint.md b/okf-bundle/testing/validation/lint.md new file mode 100644 index 0000000000..f9cda62fcc --- /dev/null +++ b/okf-bundle/testing/validation/lint.md @@ -0,0 +1,38 @@ +--- +type: Reference +title: 'Validation: lint and formatting' +description: 'Lint-by-tree script table (blocking), what full yarn lint covers, and frozen-review check-only rules.' +tags: [testing, validation, lint] +timestamp: 2026-12-02T00:00:00Z +--- + +# Validation: lint and formatting + +Part of [Validation checklist](../validation-checklist.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + + + +## Lint and formatting + +**Blocking before `implementation` handoff and on the frozen tree for `independent-review`.** Run from repo root after prepare/compile when TS/JS changed. **Owner of which script to run** — [change authoring](../change-authoring-workflow.md) hops here; do not duplicate this table there. + +**CI Lint job** (`.github/workflows/linting.yml`) is `yarn lint` = `lint:js` + `lint:deps` + `lint:android` + `lint:ios:check`. `lint:android` is **Java** (`google-java-format`); it does **not** format Kotlin. Kotlin format is repo-root `./gradlew ktlintFormat` ([agent command policy](../agent-command-policy.md)), not part of `yarn lint`. + +### Lint-by-tree / by-diff + +Run **only** the scripts whose trees are in the diff (exit 0). Do not run the rest. + +| Tree in diff | Script | Notes | +| --- | --- | --- | +| `packages/**` or `test-expo/**` JS/TS | `yarn lint:js` | ESLint `packages/*` and `test-expo/` (one script; do not invent a `test-expo` lint entrypoint). Implementation may `yarn lint:js --fix` then re-run until clean. Prefer that over `yarn format:js`. A flood under `packages/app/__tests__/vendor/` is local Bundler vendor, not product lint. Do not treat it as the lint gate. [Agent command policy § JS lint / Bundler vendor](../commands/core.md#js-lint-bundler-vendor). | +| `packages/*/lib/**` | `yarn lint:deps` | Blocking. [dependency-cycle linting](../../monorepo-tooling/prepare-and-cache.md#dependency-cycle-linting). | +| Java under `packages/*/android` | `yarn lint:android` | **Implementation only.** `google-java-format --set-exit-if-changed --replace` on **`.java`** — **mutates**. Does **not** format `.kt`. Only Java entrypoint ([agent command policy](../agent-command-policy.md)); never invent `yarn google-java-format` / `npx google-java-format`. Can flake; rerun once/twice if failure is not clearly in diff. Commit formatter output. | +| Kotlin under `packages/*/android` or `tests/android/**/*.kt` | repo-root `./gradlew ktlintFormat` | **Implementation only.** **Mutates.** Include `tests/android/**/*.kt` when those files are in the diff. Invocation and filter: [agent command policy § Android Kotlin format](../commands/native.md#android-kotlin-format). Frozen review: do not run. | +| iOS native (`packages/*/ios` `.h` / `.cpp` / `.m` / `.mm`, not generated) | `yarn lint:ios:check` | clang-format **check** (`-n -Werror`). Implementation may `yarn lint:ios:fix` then re-check. Repo pins `clang-format@1.7.0` (exact, not `^`): `1.8.0` ships darwin **x86_64** only (needs Rosetta); `1.7.0`’s misnamed `darwin_x64` path is native **arm64**. Intel Mac is not a supported local `lint:ios` host (App Store / Xcode / macOS floor). | +| `docs/**`, or docs tooling (`scripts/docs-snippets-tsc.mjs`, `scripts/docs-member-check.mjs`, `scripts/lib/mdx-fences.mjs`, `eslint.docs-snippets.config.mjs`) | `yarn lint:markdown` (`yarn lint:markdown:fix` for Prettier formatting) then `yarn lint:spellcheck` then `yarn docs:tsc:check` then `yarn docs:member:check` then `yarn lint:docs-links` | Docs tree globs and the docs tooling files above (CI docs job). OKF-only diffs skip these. Gotchas below. Link-check: [§ docs.page link check](docs-lint.md#docs-page-link-check). | + +A JS-only (or docs-only) diff does **not** require full `yarn lint`. Full `yarn lint` is the CI equivalent when the diff spans those package trees **and** mutating `lint:android` is allowed (`implementation`). Full `yarn lint` still does **not** run Kotlin `ktlintFormat`. + +### Frozen `independent-review` (check-only) + +Frozen review is [report/check-only except revert `.only`](../authoring/review-and-commit.md#frozen-tree). **Do not** run `yarn lint:android`, repo-root `./gradlew ktlintFormat`, or full `yarn lint` — those formatters **mutate** the tree. Run the **check-only** by-diff scripts: `lint:js` (JS/TS), `lint:deps` (lib), `lint:ios:check` (ios), `yarn lint:markdown`/`yarn lint:spellcheck`/`yarn lint:docs-links`/`docs:tsc:check`/`docs:member:check` (docs tree or [docs tooling](docs-lint.md#docs-lint-gotchas) only). There is no allowlisted check-only Kotlin ktlint task. diff --git a/okf-bundle/testing/validation/native-unit.md b/okf-bundle/testing/validation/native-unit.md new file mode 100644 index 0000000000..aa5db97f56 --- /dev/null +++ b/okf-bundle/testing/validation/native-unit.md @@ -0,0 +1,62 @@ +--- +type: Reference +title: 'Validation: native unit tests' +description: 'Android JVM unit, iOS XCTest unit, and iOS Ruby unit test rows with their triggers.' +tags: [testing, validation, android, ios, ruby] +timestamp: 2026-12-02T00:00:00Z +--- + +# Validation: native unit tests + +Part of [Validation checklist](../validation-checklist.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## Android JVM unit tests + +When `packages/*/android/**` Java bridge/state-machine logic changed (or added under `src/test/java`): + +```bash +yarn tests:android:unit # JUnit-first — [AndroidTest-AD-1](../android-architecture-decisions.md#androidtest-ad-1) +``` + +Produces Jacoco `*.exec` that **counts** toward native touched-line coverage when merged. After Android e2e: + +```bash +yarn tests:android:post-e2e-coverage # pull .ec → jacocoTestReport (unit + e2e merge) +# optional explicit merge: +yarn tests:android:test:jacoco-report +``` + +Merged Codecov path: `jacocoTestReport.xml` — [coverage design](../coverage-design.md). JVM unit does **not** replace [platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking) e2e. + + + +## iOS XCTest unit tests + +When `packages/*/ios/**` Objective-C/C++ bridge logic changed (or an in-package `*UnitTests.xcodeproj` was added): + +```bash +yarn tests:ios:unit # macOS/host-first — [IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1) +``` + +Produces `coverage/ios-unit/lcov.info` and **merges into** `coverage/ios-native/lcov.info`. After iOS e2e, `yarn tests:ios:test:process-coverage` merges unit LCOV again so e2e export does not drop XCTest hits — [coverage design](../coverage-design.md) (non-zero exit from the trailing NYC JS report can leave `coverage/ios-native/lcov.info` already written and usable). In-package XCTest does **not** replace [platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking) e2e. + + + +## iOS Ruby unit tests (SPM / CocoaPods helpers) + +**Blocking for `implementation_gate` / `review_gate` / handoff** when the diff touches any of: + +- `packages/app/**/*.rb` (production helpers such as `firebase_spm.rb`, `firebase_json.rb`) +- `packages/app/__tests__/*_test.rb` + +```bash +yarn ruby:install # root Gemfile; included in root yarn via postinstallDev; skips exit 0 when bundle not on PATH, ruby < 3.3.1, or bundle cannot run +yarn tests:ios:ruby # yarn lint:ruby (RuboCop) then all *_test.rb + SimpleCov → coverage/ios-ruby/lcov.info +yarn lint:ruby # RuboCop only (same Gemfile; not part of root yarn lint) +``` + +Do not `bundle install --gemfile=packages/app/__tests__/Gemfile`. That vendors under `packages/app/__tests__/vendor/` and `yarn lint:js` then fails on vendor. [JS lint / Bundler vendor](../commands/core.md#js-lint-bundler-vendor). + +Host Ruby must be **>= 3.3.1** (not 3.3.0); do not downgrade lockfile `simplecov` — [agent command policy § iOS Ruby](../commands/native.md#ios-ruby-spm-helpers). + +Opt-in shape/embed suites skip cleanly when cocoapods/xcodeproj are absent; exit **0** when only skips occur alongside a green unit suite. Coverage artifact and Codecov flag **`ios-ruby`**: [coverage design § iOS Ruby](../code-coverage/local.md#ios-ruby-simplecov). Touched production Ruby lines need test support in the [coverage evidence package](../code-coverage/policy.md#coverage-evidence-package) before `review_gate` closes — same spirit as JS/native touched-line bar. Canonical command only ([agent command policy](../agent-command-policy.md)); do **not** use ad-hoc `ruby packages/app/__tests__/…_test.rb` as the gate. diff --git a/okf-bundle/testing/validation/okf-review.md b/okf-bundle/testing/validation/okf-review.md new file mode 100644 index 0000000000..a681d590fd --- /dev/null +++ b/okf-bundle/testing/validation/okf-review.md @@ -0,0 +1,17 @@ +--- +type: Reference +title: 'Validation: OKF bundle review' +description: 'When independent-review is the OKF bundle scan and what it checks.' +tags: [testing, validation, okf] +timestamp: 2026-12-02T00:00:00Z +--- + +# Validation: OKF bundle review + +Part of [Validation checklist](../validation-checklist.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## OKF bundle review + +When the frozen tree includes `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md`, **`independent-review` is this scan**. Confirm every [OKF update contract](../../documentation-policy.md#okf-update-contract) row: Canonical location, DRY, [Efficiency](../../documentation-policy.md#efficiency), link hygiene, Durability. **Report only** — do not edit the frozen tree. The `documentation` work type promotes durable text; it does not run this scan. Close `commit` only after this scan when those files changed. Do not add OKF after a frozen review without another `independent-review`. + +Goal: each iteration improves OKF and removes conflicting guidance. Check meanings live in the contract; do not treat this list as a thinner substitute. diff --git a/okf-bundle/testing/validation/work-types.md b/okf-bundle/testing/validation/work-types.md new file mode 100644 index 0000000000..00eaae0e3b --- /dev/null +++ b/okf-bundle/testing/validation/work-types.md @@ -0,0 +1,27 @@ +--- +type: Reference +title: 'Validation: when to run what' +description: 'Validation scope and allowed shortcuts per work type.' +tags: [testing, validation, work-types] +timestamp: 2026-12-02T00:00:00Z +--- + +# Validation: when to run what + +Part of [Validation checklist](../validation-checklist.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## When to run what + + + +Work types and tiers: [change authoring workflow](../authoring/loop.md#work-types). Term ids: [iteration vocabulary](../iteration-vocabulary.md). + +| Work type | Scope | Shortcuts | +| --- | --- | --- | +| `gap-analysis` | `compare:types`, config read, SDK declarations | n/a | +| `baseline-capture` | Full loaded spec(s) + e2e on [**every required platform**](../e2e/gates.md#platform-coverage-gate-blocking) | **area-focused** tier; [area narrowing required](../e2e/gates.md#harness-narrowing-gate-blocking); no `.only`, no `:test-cover-reuse`; **no platform shortcuts** | +| `implementation` | Unit-focused Jest + e2e on **every required platform** when native bridge, **committed `**/generated/**`**, podspec/spec/codegen wiring, or macOS TS/runtime path changed — **Jest-only / `yarn codegen:verify` do not close `implementation_gate`**; `lib/**` edits need `yarn lerna:prepare` + Metro restart, not platform `:build` for JS alone ([running e2e § Rules #3](../e2e/rules.md#rules)) | **unit-focused** tier; [harness overrides + RNFBDebug](../e2e/narrowing.md#local-harness-overrides-harnessoverridesjs) before `:test-cover`; optional `.only` / sub-suite for diagnosis; [platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking) — no platform shortcuts | +| `documentation` | Promote user docs + durable OKF + `AGENTS.md` + `CONTRIBUTING.md` on the same change set **before** `independent-review` | none — does **not** run the [OKF bundle scan](okf-review.md#okf-bundle-review); loop: [change authoring § work types](../authoring/loop.md#work-types) | +| `independent-review` | Full checklist; e2e on **every required platform** (macOS / iOS / Android per harness); **this pass is the OKF scan** when `okf-bundle/` reference docs, `AGENTS.md`, or `CONTRIBUTING.md` are in the frozen tree | **area-focused** tier; [platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking) — **no shortcuts**; [frozen tree](../authoring/review-and-commit.md#frozen-tree) (report-only except revert `.only`); never commit overrides, sub-suite `.only`, or temporary `tests/app.js` edits ([fail-fast §](../e2e/narrowing.md#fail-fast-rnfbdebug-and-sub-suite-narrowing)) | +| `commit` | Stage after gates closed | [change authoring § commit](../authoring/review-and-commit.md#commit) — staging only; OKF contract findings → `documentation?` then re-scan | +| `pre-merge-validation` | Full unfocused suite | **full** tier — [running-e2e § merge](../e2e/gates.md#before-merge-pr-handoff); entire PR branch, once | From b424141588d0d0dc16a3f8760cc0e123921bdef0 Mon Sep 17 00:00:00 2001 From: russellwheatley Date: Fri, 4 Dec 2026 08:57:52 +0000 Subject: [PATCH 2/5] chore(agents): remove unused ts-js-validation skill Nothing loads it, and its command list had drifted from okf-bundle: it ran full yarn lint (rewrites Java, banned during frozen review) and yarn format:js, and skipped the docs checks. The AGENTS.md routes own validation per diff. --- .agents/skills/ts-js-validation/SKILL.md | 134 ----------------------- 1 file changed, 134 deletions(-) delete mode 100644 .agents/skills/ts-js-validation/SKILL.md diff --git a/.agents/skills/ts-js-validation/SKILL.md b/.agents/skills/ts-js-validation/SKILL.md deleted file mode 100644 index 2ae92d2abf..0000000000 --- a/.agents/skills/ts-js-validation/SKILL.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -name: ts-js-validation -description: Validate React Native Firebase changes by running the CI-equivalent prepare, TypeScript, lint, Jest, formatting, and compare-types scripts. Use before handoff, commit, or push when package sources, native bridge code, or docs changed. -metadata: - owner_team: react-native-firebase - maintainer: russell.wheatley - status: draft - tags: typescript,javascript,testing,validation,formatting,react-native-firebase - last_reviewed: "2026-07-06" - version: "0.2.0" ---- - -# React Native Firebase TS/JS Validation - -## Scope - -Use this skill to validate changes in the React Native Firebase monorepo before handoff, commit, or push. - -It runs the same static-analysis and compile/test commands CI uses for the Lint, TypeScript, Jest, docs, and compare-types jobs — not a narrowed JS-only subset. - -## Triggers - -Use this skill when the user asks for: - -- testing TS or JS changes -- validating TypeScript or JavaScript edits before commit or handoff -- running the standard validation pass for RNFB -- checking whether package changes compile and pass Jest -- formatting and linting before push -- CI-equivalent validation before publication - -## Out-of-scope boundaries - -Do not use this skill for: - -- release validation that requires the full platform, emulator, Detox, or packaging matrix (see [validation checklist § e2e](../../../okf-bundle/testing/validation-checklist.md)) -- migrating a package from JavaScript to TypeScript; use the TypeScript refactor or migration skills instead - -## Defaults - -- Default tool or method: run the canonical command sequence below from the repository root -- Fallback when default fails: stop, inspect the failure, fix issues in the current change set when authorized, then rerun the failed command and any later commands -- Why this default exists: the sequence mirrors CI Lint + TypeScript + Jest + docs + compare-types gates - -## Command sequence - -Run these root `package.json` scripts in order. **Canonical checklist:** [validation-checklist.md](../../../okf-bundle/testing/validation-checklist.md). **Agent allowlist (no improvisation):** [agent-command-policy.md](../../../okf-bundle/testing/agent-command-policy.md). OKF bundle wins if this skill disagrees. - -1. `yarn lerna:prepare` -2. `yarn tsc:compile` -3. `yarn tsc:compile:consumer` -4. `yarn reference:api` -5. `yarn lint` — **CI Lint job** (`lint:js` + `lint:android` + `lint:ios:check`). When `lint:android` reformats Java, commit the formatter output and rerun until exit 0. -6. When `docs/**` changed: `yarn lint:markdown` then `yarn lint:spellcheck` — **CI docs job** -7. `yarn lint:js --fix` then `yarn lint:js` when step 5 reported ESLint issues only (optional shortcut before re-running full `yarn lint`) -8. `yarn tests:jest` -9. `yarn format:js` — inspect diff; rerun `yarn lint` if formatting touched files -10. `yarn compare:types` - -## Gotchas - -- **Forbidden:** `yarn workspace … prepare`, `cd packages/ && yarn prepare/build`, `yarn jet`, `npx jet` — see [agent command policy](../../../okf-bundle/testing/agent-command-policy.md). On failure, fix product code and re-run the **same** canonical command. -- **`yarn lint` is not optional** when native Java or iOS sources are in the diff — `lint:js` alone does not match CI. -- **`yarn lint:spellcheck` is not optional** when `docs/**` is in the diff — `lint:markdown` alone does not match CI. -- `yarn format:js` writes changes across `packages/**/*.{js,ts,tsx}`. Check the diff after formatting and do not revert user changes. -- Run commands from the repository root so workspace resolution, root `tsconfig.json`, and Jest configuration are consistent. -- `yarn lerna:prepare` may rebuild or refresh package artifacts needed before TypeScript or tests run. -- `yarn compare:types` installs dependencies under `.github/scripts/compare-types` before running the type parity comparison. Keep it last. -- If validation is slow, keep the command running rather than replacing it with a narrower command unless the user explicitly narrows validation. - -## Workflow - -1. Confirm the task scope and note changed packages, native paths, or docs. -2. Check whether the worktree has unrelated dirty files if the current task includes code edits or commit preparation. -3. Run the command sequence from the repository root. -4. If `yarn lint:android` or `yarn format:js` changes files, include those changes and rerun `yarn lint` before continuing. -5. If a command fails: - - stop before running later commands - - identify whether the failure belongs to the current changes, pre-existing repo state, or missing local setup - - fix current-change failures when authorized, then rerun the failed command and continue the remaining sequence -6. Return a concise result with the commands run, pass/fail status, and any remaining blockers. - -## Validation loop - -1. Run the command sequence. -2. If validation fails because of current changes and fixing is in scope, fix the issue and rerun the failed command plus all later commands. -3. If validation fails for unrelated or environment-specific reasons, stop and report the blocker with the command that failed and the shortest useful error summary. -4. Only report success when every applicable command in the sequence completes successfully. - -## Output format - -Use this template: - -```markdown -# TS/JS Validation - -## Summary -- passed | failed | blocked -- one-sentence validation verdict - -## Commands -- `yarn lerna:prepare`: passed | failed | not run -- `yarn tsc:compile`: passed | failed | not run -- `yarn tsc:compile:consumer`: passed | failed | not run -- `yarn reference:api`: passed | failed | not run -- `yarn lint`: passed | failed | not run -- `yarn lint:markdown`: passed | failed | not run | n/a -- `yarn lint:spellcheck`: passed | failed | not run | n/a -- `yarn tests:jest`: passed | failed | not run -- `yarn format:js`: passed | failed | changed files -- `yarn compare:types`: passed | failed | not run - -## Findings -- failing suite, compiler error, or setup blocker if any - -## Next actions -1. next required action, only if validation did not fully pass -``` - -## Constraints - -- Keep responses factual and grounded in command output. -- Do not skip `yarn lint` or docs lint rows when the diff requires them. -- Do not claim validation passed unless `compare:types` ran after any formatting changes. -- Do not revert unrelated local changes. -- Avoid broad refactors while fixing validation failures. - -## Additional resources - -Load files only when needed: - -- **`okf-bundle/testing/validation-checklist.md`** — full validation command list including e2e, coverage, and CI job mapping -- Read `package.json` if command names or script definitions need to be confirmed. -- Read affected package `type-test.ts` or nearby `__tests__/` files only when a failure needs package-specific diagnosis. From cdf06be79c66014c98e608f3b2c45722cee4322c Mon Sep 17 00:00:00 2001 From: russellwheatley Date: Fri, 4 Dec 2026 09:01:50 +0000 Subject: [PATCH 3/5] docs(okf): split iOS CI and NewArch ADR docs, hoist forbidden commands ci-workflows/ios.md and new-architecture/architecture-decisions.md were the two largest stable docs left (about 12k tokens each) after the testing split. Both are split verbatim into ios/ and decisions/ with the same catalog convention: the old path keeps every old anchor, and links inside the bundle point at the new homes. The ADR catalog gains a one-line decision index so finding NewArch-AD- costs one small read. The forbidden-command table moves from testing/commands/forbidden.md into agent-command-policy.md, directly under the agent rule, so the file every agent is sent to first shows what never to run without another hop. --- CONTRIBUTING.md | 4 +- okf-bundle/CONTEXT.md | 5 +- okf-bundle/ci-workflows/detox-patches.md | 4 +- okf-bundle/ci-workflows/index.md | 4 +- okf-bundle/ci-workflows/ios.md | 665 +----------------- .../ci-workflows/ios/orchestration-jet.md | 211 ++++++ .../ci-workflows/ios/orchestration-launch.md | 172 +++++ .../ci-workflows/ios/release-and-tooling.md | 148 ++++ .../ci-workflows/ios/simulator-reliability.md | 165 +++++ okf-bundle/ci-workflows/other.md | 2 +- okf-bundle/index.md | 2 +- okf-bundle/ios-spm-native-imports.md | 2 +- .../architecture-decisions.md | 442 ++---------- .../decisions/codegen-and-toolchain.md | 142 ++++ .../decisions/events-tests-process.md | 142 ++++ .../new-architecture/decisions/js-runtime.md | 144 ++++ okf-bundle/new-architecture/index.md | 2 +- okf-bundle/routes/expo-plugin.md | 2 +- okf-bundle/routes/index.md | 2 +- okf-bundle/testing/agent-command-policy.md | 31 +- .../invariants-and-troubleshooting.md | 2 +- okf-bundle/testing/code-coverage/pipelines.md | 2 +- okf-bundle/testing/commands/fixtures.md | 2 +- okf-bundle/testing/commands/forbidden.md | 33 - okf-bundle/testing/commands/native.md | 6 +- okf-bundle/testing/e2e/narrowing.md | 2 +- .../testing/e2e/platform-troubleshooting.md | 2 +- okf-bundle/testing/e2e/prerequisites.md | 4 +- okf-bundle/testing/e2e/recovery.md | 2 +- okf-bundle/testing/e2e/rules.md | 4 +- okf-bundle/testing/e2e/run-loop.md | 4 +- okf-bundle/testing/e2e/slot-devices.md | 2 +- .../testing/firebase-testing-project.md | 2 +- okf-bundle/testing/index.md | 2 +- .../testing/local-ios-e2e-reproduction.md | 2 +- .../testing/test-app-dependency-pins.md | 8 +- .../validation/evidence-and-handoff.md | 2 +- 37 files changed, 1248 insertions(+), 1124 deletions(-) create mode 100644 okf-bundle/ci-workflows/ios/orchestration-jet.md create mode 100644 okf-bundle/ci-workflows/ios/orchestration-launch.md create mode 100644 okf-bundle/ci-workflows/ios/release-and-tooling.md create mode 100644 okf-bundle/ci-workflows/ios/simulator-reliability.md create mode 100644 okf-bundle/new-architecture/decisions/codegen-and-toolchain.md create mode 100644 okf-bundle/new-architecture/decisions/events-tests-process.md create mode 100644 okf-bundle/new-architecture/decisions/js-runtime.md delete mode 100644 okf-bundle/testing/commands/forbidden.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f3b5da3981..483783f829 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -89,11 +89,11 @@ The New Architecture commits generated native code (CMake files, podspecs, JSI/s 1. **Bump the mobile app RN (and macOS only when that stack moves).** Update `tests/package.json` (`react-native`, CLI / `@react-native/*`) for mobile + codegen. Update `tests-macos/package.json` (`react-native`, `react-native-macos`) only when the macOS pair advances. Do **not** reintroduce blanket root `resolutions` for `react-native` / `@react-native/codegen` / CLI — each app pins its own line; codegen resolves from **`tests/`**. Never float the toolchain (`latest`, `*`, `^x.y`). Individual packages must not declare their own `react-native` devDependency. See [test app dependency pins](okf-bundle/testing/test-app-dependency-pins.md). 2. `yarn install` and verify pins: from `tests/` and `tests-macos/` report their expected `react-native` versions; `rg 'react-native@npm:' yarn.lock` should show the intended line(s) (plus `react-native-macos` for the macOS app). -3. **Regenerate all native artifacts** when the **mobile** RN/codegen line changes: `yarn codegen:all` (wipe-then-regen on each configured `--outputPath` via [`scripts/codegen-package.mjs`](scripts/codegen-package.mjs) — [NewArch-AD-22](okf-bundle/new-architecture/architecture-decisions.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)), then review the diff — macro/podspec/JSI churn is expected on an RN bump. +3. **Regenerate all native artifacts** when the **mobile** RN/codegen line changes: `yarn codegen:all` (wipe-then-regen on each configured `--outputPath` via [`scripts/codegen-package.mjs`](scripts/codegen-package.mjs) — [NewArch-AD-22](okf-bundle/new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)), then review the diff — macro/podspec/JSI churn is expected on an RN bump. 4. **Rebuild native on both platforms** (iOS + Android) and run the e2e suite; generated changes only take effect after a native rebuild. Rebuild/run macOS Jet from `tests-macos/` when that app's native shell or Metro entry changed. 5. `yarn codegen:verify` must pass (it re-runs wipe+regen via `codegen-package.mjs` and fails on any drift). If it flags drift on an unchanged RN, the mobile toolchain is mis-pinned — fix the `tests/` pins, do not commit the drift. -See [NewArch-AD-20](okf-bundle/new-architecture/architecture-decisions.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted) for the rationale. +See [NewArch-AD-20](okf-bundle/new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted) for the rationale. --- diff --git a/okf-bundle/CONTEXT.md b/okf-bundle/CONTEXT.md index c303c395db..4694663f5b 100644 --- a/okf-bundle/CONTEXT.md +++ b/okf-bundle/CONTEXT.md @@ -3,7 +3,7 @@ type: Reference title: okf-bundle structure description: 'How the knowledge bundle is laid out, where a new fact goes, how to move text without breaking #anchors, and where the layout deliberately departs from ICM defaults.' tags: [okf, structure, routes, documentation] -timestamp: 2026-12-02T00:00:00Z +timestamp: 2026-12-04T00:00:00Z --- # okf-bundle structure @@ -19,6 +19,7 @@ The bundle is the factory shelf for changing this repo: stable reference that ag | `testing/` | Testing owners. `testing/index.md` lists every file | | `testing/commands/`, `authoring/`, `validation/`, `e2e/`, `code-coverage/` | Task-sized sections of `agent-command-policy.md`, `change-authoring-workflow.md`, `validation-checklist.md`, `running-e2e.md`, `coverage-design.md` | | `ci-workflows/`, `monorepo-tooling/`, `new-architecture/`, `packages//` | Area owners, each with an `index.md` | +| `ci-workflows/ios/`, `new-architecture/decisions/` | Task-sized sections of `ci-workflows/ios.md` and `new-architecture/architecture-decisions.md` (the ADR catalog keeps a one-line decision index) | | `**/*work-queue.md` | Grandfathered ephemeral queues; never create new ones ([work-queue documents](documentation-policy.md#work-queue-documents)) | ## Writing here @@ -39,7 +40,7 @@ Kept on purpose, OKF conventions win where they conflict: - **Catalogs are `index.md`, not `CONTEXT.md`.** OKF names folder catalogs `index.md`. Folders here are shelves of reference, not pipeline stages, so they have no Inputs / Process / Outputs contracts; the change authoring loop is the pipeline and lives in `testing/authoring/`. - **`index.md` uses bundle-root links (`/testing/...`).** That is the existing OKF catalog style. A link checker must resolve a leading `/` against `okf-bundle/`, not the filesystem root. -- **Old paths stay as catalogs.** `agent-command-policy.md`, `change-authoring-workflow.md`, `validation-checklist.md`, `running-e2e.md` and `coverage-design.md` keep their intro, any agent rule, a file list, and an `` for every old anchor, instead of an `index.md` inside each new subfolder. External referrers keep working and each subfolder still has one catalog (its sibling file). +- **Old paths stay as catalogs.** `agent-command-policy.md`, `change-authoring-workflow.md`, `validation-checklist.md`, `running-e2e.md`, `coverage-design.md`, `ci-workflows/ios.md` and `new-architecture/architecture-decisions.md` keep their intro, any agent rule, a file list, and an `` for every old anchor, instead of an `index.md` inside each new subfolder. External referrers keep working and each subfolder still has one catalog (its sibling file). - **`AGENTS.md` keeps a few repo-wide rules** (command allowlist, change authoring evidence, public vs ephemeral, PR scope) as one-line links. It is the only file every agent is sure to load. - **`testing/commands/constraints.md` restates other command rows** as one plain-text block for pasting into prompts. It predates this layout; each line's owner is a registry or trap section in `testing/commands/`. - **`testing/code-coverage/`**, not `coverage/`: the repo `.gitignore` ignores every folder named `coverage`. diff --git a/okf-bundle/ci-workflows/detox-patches.md b/okf-bundle/ci-workflows/detox-patches.md index 76a538a9b4..04bc63e879 100644 --- a/okf-bundle/ci-workflows/detox-patches.md +++ b/okf-bundle/ci-workflows/detox-patches.md @@ -30,7 +30,7 @@ Patches are in-repo. Prefer direct patch-file edits or headless workflow; `yarn | Ignore missing adb reverse on teardown | `ADB.js` | Android | Jet WS 1006 triggers mid-run `reverse --remove` → adb exit 1 | | **2× device-registry lock stale** | `ExclusiveLockfile.js` | iOS, macOS, Android | `proper-lockfile` `ECOMPROMISED` before tests start | -Related patches: `jet`, `mocha-remote-client`, `mocha-remote-server` — WS reconnect grace, coverage handshake, client keepalive, parse buffering, reconnect assignment order, `transformFailure` Metro symbolication soft-fail; **host control HTTP on `JET_REMOTE_PORT + 1` (default 8091)** for launch defer + orchestrate phase (`RNFB_JET_DEFER_RUN`); HTTP POST `/coverage` on 8090 removed; **`fatal_disconnect` / exitOnError must `process.exit(1)` after `cleanup()`** so Detox Jest cannot sit for `testTimeout` (1h) after native crash + Jet dead disconnect. See [Jet host orchestration](../testing/e2e/run-loop.md#jet-host-orchestration-ports-and-launch-gate), [coverage design](../testing/coverage-design.md), [iOS issues 6–8](ios.md#6-jet-websocket-disconnect-1006--1001) (incl. [6c](ios.md#6c-release-transformfailure-masks-real-errors-metro-symbolication)). +Related patches: `jet`, `mocha-remote-client`, `mocha-remote-server` — WS reconnect grace, coverage handshake, client keepalive, parse buffering, reconnect assignment order, `transformFailure` Metro symbolication soft-fail; **host control HTTP on `JET_REMOTE_PORT + 1` (default 8091)** for launch defer + orchestrate phase (`RNFB_JET_DEFER_RUN`); HTTP POST `/coverage` on 8090 removed; **`fatal_disconnect` / exitOnError must `process.exit(1)` after `cleanup()`** so Detox Jest cannot sit for `testTimeout` (1h) after native crash + Jet dead disconnect. See [Jet host orchestration](../testing/e2e/run-loop.md#jet-host-orchestration-ports-and-launch-gate), [coverage design](../testing/coverage-design.md), [iOS issues 6–8](ios/orchestration-jet.md#6-jet-websocket-disconnect-1006--1001) (incl. [6c](ios/orchestration-jet.md#6c-release-transformfailure-masks-real-errors-metro-symbolication)). ## Updating the jet patch (headless) @@ -48,7 +48,7 @@ yarn patch-commit -s "$PATCH_DIR" 3. `yarn install` from repo root — confirm updated `yarn.lock` patch hash and applied files in `tests/node_modules/jet/`. -**Touch list:** `lib/commonjs/cli.js` (server: WS `coverage-data`, reconnect grace, **`startControlHttpServer` on port `JET_REMOTE_PORT + 1`**, defer `server.run()` until `POST /launch-ready` when `RNFB_JET_DEFER_RUN=1`; **no** control HTTP on the 8090 WebSocket stack), `lib/commonjs/index.js` + `src/index.tsx` (client: `client.uploadCoverage()`; `transformFailure` symbolication soft-fail — [iOS §6c](ios.md#6c-release-transformfailure-masks-real-errors-metro-symbolication)). Metro resolves Jet via `"react-native": "src/index"` — patching `lib/` alone does not fix macOS bundles. +**Touch list:** `lib/commonjs/cli.js` (server: WS `coverage-data`, reconnect grace, **`startControlHttpServer` on port `JET_REMOTE_PORT + 1`**, defer `server.run()` until `POST /launch-ready` when `RNFB_JET_DEFER_RUN=1`; **no** control HTTP on the 8090 WebSocket stack), `lib/commonjs/index.js` + `src/index.tsx` (client: `client.uploadCoverage()`; `transformFailure` symbolication soft-fail — [iOS §6c](ios/orchestration-jet.md#6c-release-transformfailure-masks-real-errors-metro-symbolication)). Metro resolves Jet via `"react-native": "src/index"` — patching `lib/` alone does not fix macOS bundles. ## Device registry lock (`ECOMPROMISED`) diff --git a/okf-bundle/ci-workflows/index.md b/okf-bundle/ci-workflows/index.md index 2140052e78..bc5df0ff67 100644 --- a/okf-bundle/ci-workflows/index.md +++ b/okf-bundle/ci-workflows/index.md @@ -4,7 +4,7 @@ GitHub Actions job shape, platform reliability, and artifact triage. ## Platforms -* [iOS](ios.md) — **`xcode-27`** + **Xcode 27** + **iOS 27.0** runtime, **Device Hub** boot, XCTest unit (`yarn tests:ios:unit`), logging, troubleshooting, [CI baseload policy](ios.md#ci-baseload-policy-instrumentation); [Tart lab suspended](../testing/local-ios-e2e-reproduction.md#status-suspended) +* [iOS](ios.md) (catalog; sections under `ios/`) — **`xcode-27`** + **Xcode 27** + **iOS 27.0** runtime, **Device Hub** boot, XCTest unit (`yarn tests:ios:unit`), logging, troubleshooting, [CI baseload policy](ios/simulator-reliability.md#ci-baseload-policy-instrumentation); [Tart lab suspended](../testing/local-ios-e2e-reproduction.md#status-suspended) * [Android](android.md) — JVM unit step, idling, adb teardown, merged Jacoco / native coverage * [Other](other.md) — macOS e2e, Windows/shared @@ -18,7 +18,7 @@ GitHub Actions job shape, platform reliability, and artifact triage. * [Test-runner orchestration (log triage)](../testing/e2e/run-loop.md#test-runner-host-orchestration-log-triage-only) — ports 8090/8091, defer-run launch gate markers * [Detox patches](detox-patches.md) — inventory, `ECOMPROMISED`, patch workflow * [Cloud API quota triage](../testing/firebase-testing-project.md#ci-triage-cloud-api-quota-pressure) — live FIS/RC pressure (all platforms) -* [iOS diagnostics](ios.md#operational-notes) — `resource-monitor.sh`, `flake-summary.sh`, [CI baseload / load settle](ios.md#ci-baseload-policy-instrumentation) +* [iOS diagnostics](ios/release-and-tooling.md#operational-notes) — `resource-monitor.sh`, `flake-summary.sh`, [CI baseload / load settle](ios/simulator-reliability.md#ci-baseload-policy-instrumentation) ## Related diff --git a/okf-bundle/ci-workflows/ios.md b/okf-bundle/ci-workflows/ios.md index 926a6e150c..3faa01ce4e 100644 --- a/okf-bundle/ci-workflows/ios.md +++ b/okf-bundle/ci-workflows/ios.md @@ -3,7 +3,7 @@ type: Reference title: iOS CI workflows description: iOS CI simulator reliability, instrumentation, Detox orchestration, failure triage, and pinned tooling guidance. tags: [ci, ios, detox, simulator, e2e, troubleshooting] -timestamp: 2026-08-26T00:00:00Z +timestamp: 2026-12-04T00:00:00Z --- # iOS CI workflows @@ -32,660 +32,21 @@ Archive-only and macOS-only jobs set `RNFB_CI_REQUIRE_IOS_SIM_RUNTIME=0` (Xcode **Local contributors** mirror the same Xcode / runtime / Device Hub expectations — [running e2e § Apple host toolchain](../testing/e2e/prerequisites.md#apple-host-toolchain-local). Mobile fixture versions (**RN 0.88.0-rc.3**, **Expo 58**) are in [test app dependency pins](../testing/test-app-dependency-pins.md#current-pins). -**iOS 26.5 sim runtime** (or an older Tart seed) is **not** a substitute for this ratchet: it may help explain **runtime-only** deltas (see [§ issue 5](#5-metro-unresponsive-at-launch--waitforactive-hang-active-app) `localhost` vs `127.0.0.1`), but it cannot satisfy the **Xcode 27** / **iOS 27** / UIScene launch-smoke gates. Details: [local Tart lab § iOS 26.5 not proof](../testing/local-ios-e2e-reproduction.md#ios-26-5-not-proof). +**iOS 26.5 sim runtime** (or an older Tart seed) is **not** a substitute for this ratchet: it may help explain **runtime-only** deltas (see [§ issue 5](ios/orchestration-launch.md#5-metro-unresponsive-at-launch--waitforactive-hang-active-app) `localhost` vs `127.0.0.1`), but it cannot satisfy the **Xcode 27** / **iOS 27** / UIScene launch-smoke gates. Details: [local Tart lab § iOS 26.5 not proof](../testing/local-ios-e2e-reproduction.md#ios-26-5-not-proof). **Tart VM lab** — optional stress repro under `scripts/tart/` is [temporarily suspended](../testing/local-ios-e2e-reproduction.md#status-suspended); CI truth remains this workflow and `configure-apple-ci.sh`. -## Simulator reliability + -### Problem +## Files -On GHA macOS runners, `simctl list` can show `Booted` before the simulator is test-ready: +Content moved from this file into the files below. Headings and anchors keep their names in the new file; each old anchor sits on the line under its new home, so old `#links` still land here and point on. -1. First-boot `com.apple.datamigrator` can run for minutes; app install/launch is unreliable until done. -2. Device names are ambiguous across runtimes; `boot-simulator.sh` resolves or creates a **UDID** on the pinned iOS 27 runtime (`RNFB_IOS_SIM_RUNTIME`, default `iOS 27.0`) before boot/install. In CI it also writes that UDID to `$GITHUB_ENV` as `RNFB_IOS_SIMULATOR_UDID`. The serial `simulator` device in `tests/.detoxrc.js` passes it to Detox as `id`, or, without a UDID (outside CI), `RNFB_IOS_SIM_RUNTIME` as `os`, so Detox allocates the simulator this step booted; `e2e_sanitize_serial_env` keeps both variables. `tests/e2e/firebase.test.js` fails before the first launch if Detox's device is not that UDID. Matched by name alone, Detox can pick a same-named simulator on another runtime the image ships and cold-boot it during the Detox step, next to the pre-booted one. -3. `Booted` ≠ ready; install/launch during migration can hang/fail. - -### What we do - -**Pre-boot step** (`.github/workflows/scripts/boot-simulator.sh`), run via `nick-fields/retry` before Detox: - -> **Not for local operators.** `boot-simulator.sh` is **CI-only** (this workflow) or invoked **internally** by `tests/e2e/firebase.test.js` on iOS test-runner retry. Local e2e: [running-e2e.md](../testing/running-e2e.md) only — [host-clear probes](../testing/e2e/preflight-host-clear.md#host-clear-probes), [agent rule](../testing/running-e2e.md#agent-rule-read-first). Do not run `boot-simulator.sh` as operator prep. - -| Phase | What happens | -|--------|----------------| -| `resolve_device` | Read simulator name from `tests/.detoxrc.js` (e.g. `iPhone 17` or `RN E2E iOS slot-N`) | -| `resolve_udid` | `rnfb_ensure_ios_simulator_udid` on `RNFB_IOS_SIM_RUNTIME` (default iOS 27.0); export `RNFB_IOS_SIMULATOR_UDID` (and append it to `$GITHUB_ENV` in CI) | -| `kill_resolved` | Kill Device Hub (or legacy Simulator.app), terminate app, `simctl shutdown` the resolved UDID | -| `boot_command` | `xcrun simctl boot ` | -| `foreground_simulator` | `open /Applications/DeviceHub.app --args -CurrentDeviceUDID ` (never `open -a Simulator` / `open -a Device Hub`) | -| `wait_for_full_boot` | Poll every 20s (up to 11 min) until `simctl bootstatus` reports ready | -| `wait_shutdown` | If device is still `Booted` when install is about to run, poll up to 120s for `Shutdown` (avoids LaunchServices races after Jet retries) | -| `install_app` | `simctl install` the built `testing.app` **only after** bootstatus succeeds | - -During `wait_for_full_boot`, `[boot-status]` logs: - -- Whether `simctl list` shows the device as `Booted` -- **Data migration** snippets from `xcrun simctl bootstatus -d` (probed with a short timeout so the step keeps printing progress instead of looking hung) -- Elapsed time per poll - -Wait for **`simctl bootstatus`**, not just `Booted`. - -**Timeouts** (tuned for first-boot migration on latest iOS): - -| Setting | Value | Notes | -|---------|-------|--------| -| Pre-Boot retry step | 12 min × 3 attempts | was 5 min | -| Job `timeout-minutes` | 87 | +7 min vs previous 80 | -| Detox test step | 62 min | +7 min vs previous 55 | - -Simulator device caching deferred; bad migration cache needs invalidation policy. - -### Simulator logging and video (troubleshooting) - -Artifacts upload on every run (`if: always()`). - -| Artifact | Source | Use when | -|----------|--------|----------| -| `sim-app--_log` | One filtered `log stream` → `sim-app.log` (`testing` + SpringBoard/invertase) | `[rnfb-lifecycle]`, Detox WS, Metro probes, FrontBoard launch failures | -| `detox-step--_log` | Detox/Jet step stdout/stderr (`tee detox-step.log`) | `[jet-ws]`, `[rnfb-e2e]`, `[jet-coverage]`, Jest output — primary orchestration log | -| `flake-summary--` | `.github/workflows/scripts/flake-summary.sh` → `flake-summary.txt` | Pre-digested `rg` hits across detox/sim-app/metro/resource-monitor logs | -| `resource-monitor--_log` | `.github/workflows/scripts/resource-monitor.sh` → `resource-monitor.log` | Periodic `uptime` + `ps` snapshots (10s default) to correlate WS drops with CPU/memory pressure | -| `metro--_log` | Wrapper `metro.log` plus packager detail `/tmp/rnfb-metro-*.log` (`scripts/e2e/start-packager.sh`; the workflow pins `RNFB_METRO_LOG` to `/tmp`; debug only) | Metro hung, slow bundle, or unresponsive `/status` during app launch — wrapper alone is often 1–2 lines; inspect the detail log | -| `simulator--_video` | `simctl recordVideo` → `simulator.mp4` | Visual confirmation (**`workflow_dispatch` / `workflow_call` `record_screens: true` only**) | -| `screenrecording--` | `screencapture` of the Mac desktop | Includes Device Hub window (**`record_screens: true` only**) | -| `screenrecording-setup--.mov` | Guidepup setup recording | Very early environment setup (**`record_screens: true` only**) | -| `emulator-scripts-logs--` | `.github/workflows/scripts/*.log` | Script output if redirected | - -Video artifacts upload only when **`record_screens: true`** (see [CI baseload policy](#ci-baseload-policy-instrumentation) below). - -### CI baseload policy (instrumentation) - -**Why** — macOS GHA runners showed `loadavg` in the hundreds during iOS e2e. Unfiltered simulator debug log streams (~1M+ lines/run before Detox), host syslog with `--backtrace`, dual video capture (host + sim), and three separate log streams kept baseline CPU/disk load high. A pre-Detox gate at load **10** never cleared within the wait budget. - -**What changed** — shrink always-on instrumentation; gate load immediately before Jet/Detox orchestration at a realistic threshold (**20**). - -**Workflow order** (`.github/workflows/tests_e2e_ios.yml`, before Detox): - -| Step | Script / action | Notes | -|------|-----------------|-------| -| Pre-Boot Simulator | `RNFB_START_SIM_LOGS=0 ./boot-simulator.sh` | Boot + install only; no log streams | -| Start Simulator App Log | `RNFB_SIM_BOOT_MODE=logs ./boot-simulator.sh` | One filtered stream + `resource-monitor.sh`; sim video only if `RNFB_RECORD_SCREENS=1`. Streams from `RNFB_IOS_SIMULATOR_UDID` (from `$GITHUB_ENV`), not `booted` | -| Wait for host load to settle | `wait-for-load-settle.sh` | Poll until `load1 < 20` or 1200s timeout; `continue-on-error: true` | -| Detox Test Debug / Release | `yarn tests:ios:test-cover` / `:release` | Jet orchestration begins here | - -**Removed (high I/O / never triaged from artifacts)** - -| Was | Why removed | -|-----|-------------| -| Host `log stream --backtrace` → `syslog.log` | Whole-machine syslog; heavy under Spotlight/indexing | -| Unfiltered `simctl log stream` → `simulator.log` | Millions of debug lines; triage uses filtered app/SpringBoard lines only | -| Separate `testing.log` + `springboard-invertase.log` | Merged into one stream (below) | - -**Single sim log** — `simulator-logging.sh` writes **`sim-app.log`** via one predicate: - -```text -process == "testing" OR (process == "SpringBoard" AND eventMessage CONTAINS "invertase") -``` - -Covers `[rnfb-lifecycle]`, Detox/Metro app lines, and FrontBoard/LaunchServices invertase failures. - -**Optional video — `record_screens` input** — on `workflow_dispatch` and `workflow_call` only; default **`false`**. PR/push runs leave it off. - -| When `record_screens: true` | When false (default) | -|-----------------------------|-------------------------| -| Guidepup setup recording | Skipped | -| Host `screencapture` → `screenrecording.*` | Skipped | -| `simctl recordVideo` → `simulator.mp4` | Skipped | - -Set explicitly for UI regressions: `gh workflow run tests_e2e_ios.yml -f record_screens=true`. - -**Load settle env** (`wait-for-load-settle.sh`): - -| Variable | Default | Role | -|----------|---------|------| -| `RNFB_LOAD_SETTLE_MAX_LOAD` | **20** | Proceed when 1-min loadavg drops below this | -| `RNFB_LOAD_SETTLE_MAX_WAIT_SEC` | 1200 | Stop waiting and proceed anyway | -| `RNFB_LOAD_SETTLE_POLL_SEC` | 5 | Poll interval | - -Log markers: `[load-settle] ts=… elapsed=… load1=… threshold=20` in the workflow step; copied into `flake-summary.txt` when present. - -**Triage** — Debug legs often plateau higher than release (Metro still running). Saturated runners may never reach 20; treat `[load-settle] WARN: timed out` as informational — Detox still runs. Correlate flakes with `resource-monitor-*_log` and `[jet-ws] disconnect_context loadavg=…` rather than expecting idle hosts. - -**When to use which log** - -- **Boot / migration / “simulator won’t start”** — read the **Pre-Boot Simulator** step log in GitHub Actions first. Look for `[boot-status]` lines and `bootstatus -d` migration output. -- **Detox / app / test failures** — start with **`detox-step-*_log`** or **`flake-summary-*`** (fast triage). For native app instrumentation, download **`sim-app-*_log`**. Jet WS drops (1006/1001) appear in the Detox step (`[jet-ws]`, `[rnfb-e2e]`). For debug Metro issues, also download `metro-*_log`. -- **FrontBoard / relaunch after terminate** — `sim-app-*_log` plus `[rnfb-e2e] install-state` / `launchApp failure` lines in `detox-step-*_log`. -- **Runner load during flake** — `resource-monitor-*_log` (correlate timestamps with `[jet-ws] disconnect_context` loadavg/mem lines). -- **UI regressions** — re-run with `record_screens: true` → `simulator-*_video` or `screenrecording-*`. - -**Downloading artifacts** - -Workflow page **Artifacts**, or: - -```bash -gh run download -n sim-app-debug-0_log -``` - -**Analyzing `sim-app.log`** - -Useful patterns: - -```bash -rg 'testing\[' sim-app.log | rg -i 'waitForActive|waitForActiveDone|com\.wix\.Detox|ready action too early' -rg '\[rnfb-lifecycle\]' sim-app.log -rg '\[rnfb-lifecycle\].*RCTJavaScriptDidFailToLoad|packager-probe|packager-status-fetch' sim-app.log -rg 'No script URL provided|com\.facebook\.react\.log' sim-app.log -rg -i 'invertase|FrontBoard|unknown' sim-app.log -``` - -Long `datamigrator` activity with no `io.invertase.testing` means migration/pre-boot install not done. - -### Detox configuration - -Device type comes from `tests/.detoxrc.js`; boot script and Detox use it. No hard-coded UDID: in CI, Detox takes the UDID the boot step resolved ([simulator reliability](#problem)). - -**Missing Detox framework cache** — if iOS `:test-cover` fails before tests with `Detox.framework could not be found`, rebuild the local cache: [running e2e § iOS Detox framework cache](../testing/e2e/platform-troubleshooting.md#ios-detox-framework-cache) (`yarn tests:ios:detox-framework-cache:rebuild`). CI restores `~/Library/Detox/ios` from Actions cache keyed by Xcode version. - -### Codecov (debug matrix only) - -Debug leg: `yarn tests:ios:unit` (in-package XCTest; [IosTest-AD-1](../testing/ios-architecture-decisions.md#iostest-ad-1)) then Detox → `yarn tests:ios:test:process-coverage` + Codecov flags `e2e-ts-ios`, `ios-native`; `codecov/project/ios-native` blocks on missing native upload. **debug+spm** also runs `yarn tests:ios:ruby` and uploads Codecov flag `ios-ruby` (no `flag_management` hard gate — [coverage design § iOS Ruby](../testing/code-coverage/local.md#ios-ruby-simplecov)). Release skips coverage. Unit LCOV merges into `coverage/ios-native/lcov.info` — [coverage design](../testing/coverage-design.md). - -### E2E test app orchestration (Detox + Jet) - -After pre-boot, failures often move inside app process `testing`: boot/install are fine, `launchApp` stalls while app stays alive. - -#### 1. Early `ready` race - -**Detox step symptom** - -``` -ws-server connection :50400<->:50415 -ws-server The app has dispatched "ready" action too early. -``` - -**Cause** — iOS `DetoxManager` sends `ready` before server `login`; Detox 20.x drops it, so `launchApp()` waits forever. - -**Mitigation** — Detox patch buffers early `ready` and replays after `login`; see [detox-patches.md](detox-patches.md). - -#### 2. Device registry lock (`ECOMPROMISED`) - -**Symptom** — failure before test output, often first minute: - -``` -Error: Unable to update lock within the stale threshold - code: 'ECOMPROMISED' -``` - -**Cause** — Detox locks `~/Library/Detox/device.registry.json`; 10s heartbeat can miss under CI load ([Detox #4210](https://github.com/wix/Detox/issues/4210)). - -**Mitigation** — same Detox patch doubles stale to 20s in `ExclusiveLockfile.js`. We do **not** use `detox reset-lock-file` in CI (wipes the ledger). See [detox-patches.md](detox-patches.md#device-registry-lock-ecompromised). - -**Sentinel** — `proper-lockfile` + `ECOMPROMISED` in the Detox step log; build and Pre-Boot steps green. - -#### 3. Main-thread delay before WebSocket handshake - -**Symptom** — 30–60s gap between app launched and first `Connection 1: ready` / `handshake successful`; main-thread Firebase/RN/LLVM startup can defer WS callbacks. - -**Mitigations** - -| Change | Location | -|--------|----------| -| Wait for Jet (port 8090) before `launchApp` | `tests/e2e/firebase.test.js` | -| Defer `server.run()` until host `POST /launch-ready` on control port **8091** (`RNFB_JET_DEFER_RUN=1`) | Jet patch + `firebase.test.js` — [Jet host orchestration](../testing/e2e/run-loop.md#jet-host-orchestration-ports-and-launch-gate) | -| `POST /orchestrate-state` + `[rnfb-e2e] orchestrate-state=` for launch/retry triage | `firebase.test.js` + Jet patch | -| Wait for Metro (`/status`) before `launchApp` | `tests/e2e/firebase.test.js` (debug Detox configs only; release skips Metro wait) | -| Bounded `launchApp` timeout / retries | [`tests/e2e/detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js) (consumed by `firebase.test.js`); release uses `RNFB_LAUNCH_APP_RELEASE_TIMEOUT_MS` from the same module; Detox Login / CurrentStatus: [detox-patches](detox-patches.md) | -| `detoxEnableSynchronization: '0'` at launch (native `equals("0")`; `'NO'` still installs Fabric idling) | `tests/e2e/firebase.test.js` — [running e2e § gray screen](../testing/e2e/platform-troubleshooting.md#android-emulator-gray-screen--quick-boot-blocking) | -| `detoxURLBlacklistRegex: '.*'` | `tests/e2e/firebase.test.js` (existing) | - -#### 4. `waitForActive` / scene never foreground-active - -**Symptom** — `isReady` + `waitForActive`, no `waitForActiveDone`; app alive, scene remains unattached/inactive. - -**Instrumentation** — `AppDelegate.mm` logs `[rnfb-lifecycle]` at launch, lifecycle notifications, and +30s/+60s probes. - -**Distinguish from issue 5** — If `[rnfb-lifecycle]` probes show `UIApplication.state=active` / `foregroundActive` but Detox still hangs on `waitForActive`, the cause is likely Metro/JS bundle load failure (issue 5), not scene activation. - -#### 5. Metro unresponsive at launch → `waitForActive` hang (active app) - -**Symptom** — same as issue 4, but `[rnfb-lifecycle]` shows app active; usually debug-only (live Metro). - -**Cause chain**: - -1. Debug app requests `http://localhost:8081/status` from inside the simulator; TCP connects but Metro returns no bytes within ~10s (`NSURLErrorDomain Code=-1001`). -2. RN logs `No script URL provided. Make sure the packager is running...` and shows RedBox; DetoxSync adds an RN-load idling resource that never clears. -3. Detox WS login/`isReady` succeed (early-ready patch works), then `waitForActive` is received but **`waitForActiveDone` never arrives** even though UIKit is active. - -Metro can look healthy on the **host** during pre-fetch minutes earlier while being unresponsive when the app actually launches. - -**Instrumentation** — `AppDelegate.mm` observes `RCTJavaScriptDidFailToLoadNotification` and logs: - -- `event=RCTJavaScriptDidFailToLoad` with NSError domain/code/description -- `event=packager-probe` — `[RCTBundleURLProvider isPackagerRunning:]`, `packagerServerHostPort`, resolved `bundleURL` -- `event=packager-status-fetch` — direct `http://localhost:8081/status` fetch from inside the app with explicit timeout and HTTP status/body or error - -**Mitigations in this repo** - -| Change | Location | -|--------|----------| -| Wait for Metro `/status` before `launchApp` | `tests/e2e/firebase.test.js` (debug Detox configs only) | -| In-process `launchApp` retry on launch failure (logs `launchApp failure reason=`) | `tests/e2e/firebase.test.js` (`RNFB_LAUNCH_APP_MAX_ATTEMPTS` — default in [`detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js)) | -| Keep install on inner retry (`delete: false` on attempt 2+) | `tests/e2e/firebase.test.js` | -| Slow `terminateApp` (≥ `RNFB_SLOW_TERMINATE_MS`, default 10s) → reboot via `boot-simulator.sh` | `tests/e2e/firebase.test.js` | -| Full Jet e2e retry when inner launch retries exhausted, await-exit stall, or WS/coverage teardown retryable | `tests/e2e/firebase.test.js` (`retryableAtJetLevel`, `isRetryableE2eFailure`; stall → `stall-kill-jet`) | -| `simctl get_app_container` / `listapps` before and after each launch attempt | `tests/e2e/firebase.test.js` (`[rnfb-e2e] install-state`) | -| Bounded `launchApp` timeout | Debug: `RNFB_LAUNCH_APP_TIMEOUT_MS`; release: `RNFB_LAUNCH_APP_RELEASE_TIMEOUT_MS`. Defaults for both live in [`detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js). On CI's boot-prepared simulator, the run's first launch skips `delete: true`, because Detox init (`behavior.init.reinstallApp`) has just reinstalled the app; later launches keep the existing delete rules | -| Metro log artifacts (`metro.log` + `/tmp/rnfb-metro-*.log`) | `.github/workflows/tests_e2e_ios.yml` | -| JS load failure + packager probe logging | `tests/ios/testing/AppDelegate.mm` | -| Bundle URL pinned to `127.0.0.1` (bypasses RN `localhost` fallback) | `tests/ios/testing/AppDelegate.mm` | - -**Known intermittent pattern (community)** — RN iOS debug builds commonly hit `No script URL provided` when Metro is down, slow, or reachable from the host but not from the simulator process. Reported causes include: Metro event loop blocked under load (TCP connect succeeds, HTTP hangs — matches our `-1001` on `/status`), macOS network proxy intercepting `localhost:8081`, port 8081 contention, and `RCTBundleURLProvider` returning a nil bundle URL despite `isPackagerRunning=YES` ([react-native#49173](https://github.com/facebook/react-native/issues/49173)). On **iOS 26+ simulators**, hostname resolution for `localhost` vs `127.0.0.1` can be unreliable; hardcoding `127.0.0.1` in bundle URL resolution has been reported to fix intermittent Metro disconnects ([react-native#56447](https://github.com/facebook/react-native/issues/56447)). Our test app now pins the debug bundle URL to `127.0.0.1:8081` and the e2e harness retries `launchApp` on retryable launch failures (Metro/bundle timeout, FrontBoard errors) before failing the Jet attempt. Release uses an embedded bundle, shorter launch timeout, and no Metro wait. These are typically **environment/timing** flakes rather than app logic bugs. - -#### Diagnosing from `sim-app.log` - -Download the artifact (`gh run download -n sim-app-debug-0_log`), unzip if needed, then search `sim-app.log`. - -**Quick triage** — map Detox step timestamps to simulator log (`testing[]`): - -```bash -# Detox orchestration inside the app process -rg 'testing\[' sim-app.log | rg -i 'waitForActive|waitForActiveDone|com\.wix\.Detox|ready action too early' - -# App lifecycle confirmation (AppDelegate instrumentation) -rg '\[rnfb-lifecycle\]' sim-app.log - -# Metro / JS bundle load failure (issue 5) -rg '\[rnfb-lifecycle\].*RCTJavaScriptDidFailToLoad|packager-probe|packager-status-fetch' sim-app.log -rg 'No script URL provided|com\.facebook\.react\.log' sim-app.log -rg 'testing\[' sim-app.log | rg '8081/status|index\.bundle' - -# SpringBoard launch intent vs app scene state -rg 'com\.invertase\.testing' sim-app.log | rg -i 'foreground-interactive|visibility.*Foreground|running-active' -rg 'testing\[' sim-app.log | rg -i 'Deactivation reason|activationState|UISceneActivationState' - -# WebSocket timing (main-thread block before handshake) -rg 'testing\[' sim-app.log | rg 'Connection 1: ready|handshake successful' - -# Heavy startup on main thread (often precedes WS delay) -rg 'testing\[' sim-app.log | rg -i 'FIRApp|RNFB|RCTBridge|configure' -``` - -**Sentinel patterns** - -| Pattern | Meaning | -|---------|---------| -| `ready action too early` in Detox step only | Early-ready race (patch should fix; check patch applied in `yarn install`) | -| `ECOMPROMISED` / `Unable to update lock within the stale threshold` | Device registry lock heartbeat missed — see [detox-patches.md](detox-patches.md) | -| `codecov/project/ios-native` fail | Native lcov not uploaded — check process-coverage step and Codecov Uploads tab for `ios-native` flag | -| `waitForActive` without `waitForActiveDone` | Scene/active hang (issue 4) **or** Metro/JS load failure (issue 5) — check `[rnfb-lifecycle]` probes | -| `probe+30s` / `probe+60s` with `UIApplication.state=inactive` or scene `unattached` | App never became foreground-active (issue 4); compare with SpringBoard `foreground-interactive` lines | -| `probe+30s` / `probe+60s` with `active` / `foregroundActive` but no `waitForActiveDone` | Metro/JS bundle failure despite active UIKit (issue 5); check `RCTJavaScriptDidFailToLoad` and `packager-status-fetch` | -| `packager-status-fetch ... error domain=NSURLErrorDomain code=-1001` | Metro TCP reachable but HTTP timed out from simulator | -| `No script URL provided` in `com.facebook.react.log` | RN never got bundle URL; only `/status` attempts, no `index.bundle` | -| `FBSOpenApplicationServiceErrorDomain` / `unknown to FrontBoard` | LaunchServices race after terminate — see [issue 7](#7-frontboard--launchservices-race-after-terminaterelaunch) | -| `Failed to send 'coverage-ready' message` | Coverage handshake flake — see [issue 8](#8-coverage-teardown-handshake-failure-tests-pass-nyc-00) | -| `[rnfb-e2e] retry-eligibility ... retryable=false` | Check `checks=` JSON for which sub-condition blocked Jet attempt 2 | -| `handshake successful` 30–60s after `simctl launch` | Main-thread startup delay; not a boot failure | -| Only `com.apple.datamigrator` activity, no `testing[` | Pre-boot / migration issue — use Actions `[boot-status]` log, not Detox orchestration | - -**Example healthy sequence** (abbreviated): `didFinishLaunching+after` → `UIApplicationDidBecomeActiveNotification` / scene `foregroundActive` → Detox `loginSuccess` → `isReady` → `waitForActiveDone`. A gap between SpringBoard foreground request and `[rnfb-lifecycle]` `active` is the smoking gun for issue 4. For issue 5, lifecycle probes show `active` but you will see `RCTJavaScriptDidFailToLoad` and/or `No script URL provided` before Detox stalls on `waitForActive`. - -For Metro-side post-mortem, also download `metro-*_log` and check whether Metro logged bundle requests or stalled around the launch timestamp. The wrapper `metro.log` is often only 1–2 lines; prefer the packager detail log: - -```bash -rg -i 'BUNDLE|index\.bundle|8081|error|ECONN|transform' metro.log /tmp/rnfb-metro-*.log -``` - -**Mitigations in this repo (summary)** - -| Change | Location | -|--------|----------| -| Buffer early `ready`, replay after app `login` | `.yarn/patches/detox-npm-20.51.0-*.patch` → `AnonymousConnectionHandler.js` | -| Raise Login / CurrentStatus timeouts | [detox-patches inventory](detox-patches.md) → `actions.js` | -| 2× device-registry lock stale (20s) | `.yarn/patches/detox-npm-20.51.0-*.patch` → `ExclusiveLockfile.js` | -| Jet + Metro wait, bounded `launchApp` with retry, Detox launch args, install-state + retry-eligibility logging | `tests/e2e/firebase.test.js` + [`detoxLatencyPolicy.js`](../../tests/e2e/detoxLatencyPolicy.js) | -| Cloud quota Jet retry + cooldown + metrics/summary hooks | `tests/e2e/firebase.test.js`, `packages/app/e2e/cloud-metrics.js` — see [cloud API quota triage](../testing/firebase-testing-project.md#ci-triage-cloud-api-quota-pressure) | -| Lifecycle + JS load / packager probe logging; bundle URL `127.0.0.1` | `tests/ios/testing/AppDelegate.mm` | -| Pre-boot + `bootstatus` + shutdown wait before install | `boot-simulator.sh` | -| Baseload shrink: one `sim-app.log` stream, load settle before Detox, optional video | `simulator-logging.sh`, `wait-for-load-settle.sh`, `tests_e2e_ios.yml` — [CI baseload policy](#ci-baseload-policy-instrumentation) | -| Filtered logs, resource monitor, flake summary, Detox `tee` | `.github/workflows/tests_e2e_ios.yml`, `resource-monitor.sh`, `flake-summary.sh` | -| Metro log artifacts (`metro.log` + `/tmp/rnfb-metro-*.log`) | `.github/workflows/tests_e2e_ios.yml` | - -#### 6. Jet WebSocket disconnect (1006 / 1001) - -**Symptom** (Detox step, debug and release): - -``` -[🟨] Jet client disconnected - for no particular reason (code = 1006). -[jet-ws] transient_disconnect code=1006 grace_ms=30000 waiting_for_reconnect -``` - -The app process (`testing[]`) often stays alive in `sim-app.log` — the break is the **simulator → host** mocha-remote WebSocket on port **8090**, not a native crash. - -**Cause** — Transient abnormal WebSocket closure (1006 = no close frame; 1001 = going away). Common in long debug+coverage runs (live Metro + Istanbul `__coverage__` growth + port 8090 forwarding). mocha-remote-client auto-reconnects in ~1s; Jet and mocha-remote-server now preserve the runner during a grace window instead of exiting immediately. - -**Mitigations in this repo** - -| Change | Location | -|--------|----------| -| 30s reconnect grace for 1006/1001 before fatal exit | `.yarn/patches/jet-npm-0.9.0-dev.13-*.patch` → `cli.js` | -| `reconnectGraceMs: 30000` | `tests/.jetrc.js` | -| mocha-remote-server preserves runner + sends `pull-coverage` on reconnect | `.yarn/patches/mocha-remote-server-npm-1.13.2-*.patch` | -| Assign `this.client` **before** `emit('connection')`; `Server.send()` warns instead of throwing | mocha-remote-server patch → `Server.js` | -| Client WS keepalive (`ping` when supported) + `readyState` logging on send failure | `.yarn/patches/mocha-remote-client-npm-1.13.2-*.patch` | -| `disconnect_context` logs `loadavg`, `process.memoryUsage()`, orchestrate phase, current test/suite, coverage-upload flag | Jet patch → `cli.js` | -| One Jet e2e retry when grace expires (`RETRYABLE_DISCONNECT`) or session/coverage retryable | `tests/e2e/firebase.test.js` | -| Structured WS / orchestration logging | `[jet-ws]`, `[rnfb-e2e]`, `[mocha-remote-ws]` prefixes | - -**Diagnosing from CI logs** (start with `detox-step-*_log` or `flake-summary-*`): - -```bash -# Jet WS lifecycle -rg '\[jet-ws\]|\[rnfb-e2e\]|\[mocha-remote-ws\]|Jet client disconnected|RETRYABLE_DISCONNECT' detox-step.log - -# Disconnect resource context (+ orchestrate phase when defer-run enabled) -rg '\[jet-ws\] disconnect_context|\[rnfb-e2e\] orchestrate-state' detox-step.log - -# Grace window recovered (no e2e retry needed) -rg '\[jet-ws\] reconnect_recovered|\[mocha-remote-ws\] reconnect_recovered' detox-step.log - -# Fatal transient disconnect → e2e retry eligible -rg '\[jet-ws\] (transient_disconnect|fatal_disconnect|RETRYABLE_DISCONNECT)' detox-step.log - -# Retry decision tree -rg '\[rnfb-e2e\] retry-eligibility' detox-step.log - -# Runner load at disconnect time -rg 'disconnect_context|resource-monitor' detox-step.log resource-monitor.log -``` - -**Sentinel patterns** - -| Pattern | Meaning | -|---------|---------| -| `transient_disconnect code=1006` then `reconnect_recovered` | Flaky WS; grace window saved the run | -| `fatal_disconnect code=1006 grace_expired_ms=30000` + `RETRYABLE_DISCONNECT` | Grace failed; e2e should retry once | -| `[rnfb-e2e] Retrying after transient Jet WS` | Second Jet attempt starting (simulator reboot) | -| `disconnect_context` with high loadavg / RSS | Correlate with `resource-monitor-*_log` snapshot at same UTC timestamp | -| Release passes, debug fails with 1006 | Points at Metro/debug+coverage load, not test logic | -| `reconnect_recovered` alone then ordinary product assertion (single `Jet tests on `) | **Not** Jet-retryable — bare reconnect must not mask deterministic product bugs. Tradeoff: avoids false retries; D1 (Release `transformFailure` mask) + D4 (secondary app-name collision) cover related flakes separately | -| `reconnect_recovered` **and** desync signal (`Jet tests on ` ≥2 / suite re-entry, or `Unknown% ( 0/0 )`, or `[🟥] Stopped the server`) | Mid-suite reconnect left polluted JS / Firebase registry or lost coverage; Jet attempt 2 should trigger (`jetReconnectDesync` in `retry-eligibility`) | -| `reconnect_recovered` then `Error: No client connected` or `send skipped action=pull-coverage` | Reconnect send race (issue 6b); Jet attempt 2 should trigger | -| `awaiting-jet-exit` + ~20m silence + coverage `0/0` + `stall-kill-jet` (then Jet attempt 2 / iOS reboot) | Jet never produced mocha after `launch-ready` — stall is **retryable** once (`retryableAtJetLevel`); inspect `[rnfb-e2e] stall-diagnostics` / `lsof` on `:8090`/`:8091`/`:8081`, `[jet-control] server.run starting` vs defer-only, and Metro detail in `/tmp/rnfb-metro-*.log` inside `metro-*_log` | - -#### 6b. Reconnect send race under extreme host load - -**Symptom** (often **release** matrix leg, mid-run during heavy emulator tests e.g. Functions `HttpsError`): - -``` -[jet-ws] transient_disconnect code=1006 grace_ms=30000 waiting_for_reconnect -[jet-ws] reconnect_recovered code=1006 elapsed_ms=~30000 -Error: No client connected -``` - -Or, after the server patch, the Jet process stays up but logs: - -``` -[mocha-remote-ws] send skipped action=pull-coverage readyState=... -``` - -**Cause** — macOS GitHub runners can become **heavily I/O saturated** at any time (Spotlight indexing is a common contributor). We **cannot** disable Spotlight — `xcodebuild` / Xcode expect an up-to-date index. Under load averages in the hundreds, a transient WS 1006 is more likely; the 30s grace window often **does** recover the transport, but upstream `mocha-remote-server` used to `emit('connection')` **before** assigning `this.client`. Jet's `connection` listener immediately called `server.send({ action: 'pull-coverage' })`, which threw `No client connected` and **killed the Jet Node process** (uncaught exception). That failure was **not** classified as retryable WS disconnect — `retry-eligibility` showed all `false`. - -A duplicate proactive `pull-coverage` in the Jet patch made the race worse (two senders on reconnect). - -**Mitigations in this repo** - -| Change | Location | -|--------|----------| -| `this.client = ws` before `emit('connection')`; protocol check first | mocha-remote-server patch → `handleConnection` | -| Single `pull-coverage` after reconnect (server only, when runner active) | mocha-remote-server patch → `handleConnection` | -| Remove Jet `connection` handler `pull-coverage` (keep `reconnect_recovered` log) | Jet patch → `cli.js` | -| `Server.send()` logs `[mocha-remote-ws] send skipped` instead of throwing | mocha-remote-server patch → `Server.js` | -| `JET_NO_CLIENT_CONNECTED_RE` → retryable Jet session failure | `tests/e2e/firebase.test.js` | - -**Diagnosing** - -```bash -rg 'reconnect_recovered|No client connected|send skipped action=pull-coverage' detox-step.log -rg '\[rnfb-e2e\] retry-eligibility' detox-step.log -rg 'disconnect_context|resource-monitor' detox-step.log resource-monitor.log -``` - -Correlate `disconnect_context loadavg=…` with `resource-monitor-*_log` — high loadavg during disconnect is expected on saturated runners and is **not** something we can eliminate; orchestration must tolerate it. - -**Reference symptom** — grace can recover after a disconnect, then Jet may still crash on `No client connected`. - -#### 6c. Release `transformFailure` masks real errors (Metro symbolication) - -**Symptom** (Release builds, or Debug when Metro is not serving the app bundle — any failing assertion): - -``` -Failed to transform failure: Bundle was not loaded from Metro. -``` - -**Cause** — Jet `JetProvider.transformFailure` calls RN `symbolicateStackTrace`, which talks to Metro. Release embeds JS (no Metro); when symbolication throws, mocha-remote replaces the **original** test failure with `Failed to transform failure: …`, hiding the real assertion. - -**Mitigation in this repo** - -| Change | Location | -|--------|----------| -| Catch symbolication failure; `console.warn` one line; return original `err` | `.yarn/patches/jet-npm-0.9.0-dev.13-*.patch` → `src/index.tsx`, `lib/*/index.js` | - -**Sentinel patterns** - -| Pattern | Meaning | -|---------|---------| -| `[jet] symbolicateStackTrace unavailable; returning original error` | Soft-fail path hit; original test error preserved | -| `Failed to transform failure: Bundle was not loaded from Metro.` | Pre-fix masking — patch missing or not applied after install | - -#### 7. FrontBoard / LaunchServices race after terminate+relaunch - -**Symptom** — Second `launchApp` attempt fails after a slow or failed first launch: - -``` -FBSOpenApplicationServiceErrorDomain -Application "io.invertase.testing" is unknown to FrontBoard -``` - -Often preceded by `[rnfb-e2e] terminateApp ... elapsed=60000ms` (or similar) in `detox-step-*_log`. - -**Cause** — Detox `terminateApp` / `simctl` teardown left LaunchServices in a bad state, or `delete: true` on retry removed the install while SpringBoard still tracked the old bundle. - -**Mitigations in this repo** - -| Change | Location | -|--------|----------| -| `RETRYABLE_LAUNCH_RE` includes `unknown to FrontBoard` / `FBSOpenApplicationServiceErrorDomain` | `tests/e2e/firebase.test.js` | -| Inner retry keeps install (`delete: false` on attempt 2+) | `tests/e2e/firebase.test.js` | -| Slow terminate (≥ `RNFB_SLOW_TERMINATE_MS`) → full `boot-simulator.sh` reboot before relaunch | `tests/e2e/firebase.test.js` | -| Exhausted inner launch retries escalate to **Jet attempt 2** (`retryableAtJetLevel`) | `tests/e2e/firebase.test.js` | -| `simctl get_app_container` + `listapps` logging (`[rnfb-e2e] install-state`) | `tests/e2e/firebase.test.js` | -| Filtered sim app log artifact | `sim-app.log` | -| `wait_shutdown` before `simctl install` on reboot | `boot-simulator.sh` | - -**Diagnosing** - -```bash -rg 'install-state|launchApp failure|FrontBoard|FBSOpenApplication|terminateApp' detox-step.log -rg -i 'invertase|FrontBoard|unknown' sim-app.log -``` - -#### 8. Coverage teardown handshake failure (tests pass, NYC 0/0) - -**Symptom** — Full Jet suite passes, then `"after all"` / coverage teardown fails: - -``` -Failed to send 'coverage-ready' message: WebSocket is closed -[jet-coverage] merged 0 file(s) -Coverage summary: Unknown% ( 0/0 ) -``` - -May follow `[jet-ws] reconnect_recovered` mid-run — transport reconnected but the coverage upload socket was already dead. - -**Cause** — mocha-remote **transport** reconnect ≠ **coverage handshake** recovery (`coverage-ready` → server `pull-coverage` → `coverage-data` → `coverage-ack`). - -**Mitigations in this repo** - -| Change | Location | -|--------|----------| -| Server sends `pull-coverage` proactively after reconnect | mocha-remote-server patch only (Jet `connection` handler must not duplicate) | -| Client `uploadCoverage()` retries up to 3× with backoff; logs `readyState` at send | mocha-remote-client patch | -| `[jet-coverage] server recv coverage-ready` / client send logging | mocha-remote-server + client patches | -| `JET_COVERAGE_TEARDOWN_RE` → retryable Jet session failure | `tests/e2e/firebase.test.js` | -| Jet attempt 2 on reconnect + lost coverage (`JET_COVERAGE_LOST_RE`) | `tests/e2e/firebase.test.js` | - -**Diagnosing** - -```bash -rg '\[jet-coverage\]|coverage-ready|coverage-ack|pull-coverage|merged 0 file' detox-step.log -rg '\[rnfb-e2e\] retry-eligibility' detox-step.log -``` - -| Pattern | Meaning | -|---------|---------| -| `reconnect_recovered` then `coverage-ready.*WebSocket is closed` | Handshake flake; should be Jet-retryable | -| `[jet-coverage] client send coverage-ready attempt=2` | Client retry in progress | -| `merged 0 file(s)` after disconnect | NYC got no JS coverage — check handshake lines above | - -See also [coverage design — e2e TypeScript coverage](../testing/code-coverage/pipelines.md#e2e-typescript-coverage-jet--nyc). - -**Cloud API quota (Installations / Remote Config)** — platform-agnostic; see [firebase testing project — CI triage](../testing/firebase-testing-project.md#ci-triage-cloud-api-quota-pressure). - -### `ios-release-archive` job — real-device archive validation - -The simulator Release build does not exercise Xcode's real-device Archive -action or its install-style post-processing. This job therefore runs an -unsigned `generic/platform=iOS` Release archive (SPM-only; CocoaPods Firebase -is not supported with Firebase Apple SDK 13+). It requires no signing identity -or simulator. - -After archiving, `.github/workflows/scripts/verify-ios-release-archive.sh` -checks each embedded binary's `@rpath` framework dependencies against the -frameworks present in the archived app. A failure names the missing framework -and referencing binary with an `[ios-release-archive] MISSING:` line. - -This gate covers archive compilation and missing-framework embedding. It does -not launch the app and is not equivalent to a signed device or TestFlight test; -runtime-only failures still require a real launch. The SPM embedding decision -and its original failure mode are documented in -[`ios-spm-native-imports.md`](../ios-spm-native-imports.md#runtime-framework-embedding). -A `"...xcframework-ios.signature"` (or `-ios-simulator.signature`) couldn't -be copied to `"Signatures"` failure from this job is a known Xcode Archive -bug, not a regression — see -[archive signature-copy collision](../ios-spm-native-imports.md#archive-signature-copy-collision). - -### Operational notes - -- **macOS runner load / Spotlight** — GHA macOS hosts may run Spotlight indexing (or other disk-heavy work) at any time and saturate disk I/O. Disabling Spotlight is **not** an option for Xcode CI. Design for tolerance: longer grace windows, non-throwing `Server.send()`, Jet e2e retry on orchestration crashes, trimmed CI instrumentation ([CI baseload policy](#ci-baseload-policy-instrumentation)), `resource-monitor` + `disconnect_context` for triage. Do not treat high `loadavg` alone as a misconfiguration. -- **Release vs debug** — matrix runs both; each has separate artifacts (`debug` / `release` in the artifact name). -- **Retry** — Pre-Boot retries up to 3 times with 60s between attempts (clean shutdown + boot each time). Jet e2e retries once on retryable WS / launch / coverage teardown / **cloud quota** failures (simulator reboot via `boot-simulator.sh` on iOS; cloud quota adds cooldown — [cloud API quota triage](../testing/firebase-testing-project.md#ci-triage-cloud-api-quota-pressure)). -- **Do not boot the simulator only inside Detox** — historical races where the testee never sent “ready” to the Detox proxy; pre-boot remains mandatory. -- **CI helper scripts** (repo root relative): - -| Script | Env vars | Role | -|--------|----------|------| -| `.github/workflows/scripts/simulator-logging.sh` | `RNFB_RECORD_SCREENS` (0/1), `RNFB_SIM_LOG_DIR`, `RNFB_SIM_LOG_STDOUT` | One filtered `sim-app.log` stream; optional sim video — sourced by `boot-simulator.sh` | -| `.github/workflows/scripts/wait-for-load-settle.sh` | `RNFB_LOAD_SETTLE_MAX_LOAD` (default **20**), `RNFB_LOAD_SETTLE_MAX_WAIT_SEC`, `RNFB_LOAD_SETTLE_POLL_SEC` | Poll host load immediately before Detox | -| `.github/workflows/scripts/resource-monitor.sh` | `RNFB_RESOURCE_MONITOR_INTERVAL_SEC` (default 10), `RNFB_RESOURCE_MONITOR_LOG` | Background `uptime` + `ps` snapshots during Detox | -| `.github/workflows/scripts/flake-summary.sh` | `RNFB_DETOX_LOG`, `RNFB_FLAKE_SUMMARY_OUT` | Post-run `rg` digest → `flake-summary.txt` | -| `.github/workflows/scripts/configure-apple-ci.sh` | `XCODE_VERSION` / `RNFB_CI_XCODE_SELECTOR`, `RNFB_IOS_SIM_RUNTIME`, `RNFB_CI_REQUIRE_IOS_SIM_RUNTIME` | Post-`setup-xcode` gate: stable Xcode major 27 + optional iOS 27 runtime pin | - -Detox steps use `tee detox-step.log` and `exit ${PIPESTATUS[0]}` so the artifact preserves full output while the step still fails correctly. - -### Local stress iteration (optional) - -> **CI/manual mirror only.** The steps below reproduce CI deflake semantics on a developer machine. Local e2e runs must use [running-e2e.md](../testing/running-e2e.md) only — do not substitute `boot-simulator.sh`, `resource-monitor.sh`, or `flake-summary.sh` for the canonical `:build && :test-cover` loop. - -To deflake without pushing every change, mirror CI on a macOS machine or VM (SSH is fine): emulators → build → `boot-simulator.sh` (pre-boot, CI-only) → `wait-for-load-settle.sh` → `resource-monitor.sh` → `:test-cover` per [running e2e](../testing/running-e2e.md) → `flake-summary.sh`. Wrap in a loop over `iterations` and collect `local-e2e-artifacts/iter-N-*` directories. - -### Pinned Homebrew utilities - -CI installs macOS build helpers from **vendored formulae** in `.github/homebrew-rnfb/Formula/` instead of live taps (`wix/brew`, `homebrew-core`). Each formula file is frozen in git with pinned `url`, source `sha256`, and bottle hashes — similar in spirit to SHA-pinned GitHub Actions. - -| Formula | Version | Upstream source | Used in | -|---------|---------|-----------------|---------| -| `applesimutils.rb` | 0.9.12 | [wix/homebrew-brew](https://github.com/wix/homebrew-brew), pinned in vendored formula | iOS e2e (`tests_e2e_ios.yml`) | -| `xcbeautify.rb` | 3.2.1 | [homebrew-core](https://github.com/Homebrew/homebrew-core), pinned in vendored formula | iOS e2e + macOS e2e (`tests_e2e_other.yml`) | - -**Workflow install** — both workflows call `.github/workflows/scripts/install-homebrew-rnfb.sh` (from repo root). Homebrew 6+ refuses bare `brew install --formula path/to.rb`; the script copies formulae into a local `invertase/rnfb` tap, trusts it once per job, then installs: - -```bash -# iOS e2e (tests_e2e_ios.yml) -bash .github/workflows/scripts/install-homebrew-rnfb.sh applesimutils xcbeautify - -# macOS e2e (tests_e2e_other.yml) -bash .github/workflows/scripts/install-homebrew-rnfb.sh xcbeautify -``` - -**Why** — Third-party taps can change formula definitions on every `brew update`. Vendoring avoids supply-chain drift and Brew 6 untrusted-tap warnings for live third-party taps. We still `brew trust invertase/rnfb` for the ephemeral local tap copy each job creates. The install script **uninstalls any existing `homebrew-core` (or other tap) install** of the same formula name first — GHA macOS images often preinstall `xcbeautify`, and Brew refuses same-name formulae from two taps. - -#### When to update a pinned formula - -- CI **Install brew utilities** fails after a macOS runner / Xcode image bump (common for `xcbeautify` Swift/`on_sequoia` conditionals). -- You need a newer **applesimutils** or **xcbeautify** feature or bugfix. -- A security advisory affects the pinned upstream release (bump `url` / version and checksums). - -#### How to update a pinned formula - -1. **Fetch the upstream formula** you want to vendor (usually `master`, or a specific commit if you need a known-good revision): - - ```bash - # applesimutils (wix tap) - curl -fsSL "https://raw.githubusercontent.com/wix/homebrew-brew/master/Formula/applesimutils.rb" \ - -o /tmp/applesimutils.rb - - # xcbeautify (homebrew-core) - curl -fsSL "https://raw.githubusercontent.com/Homebrew/homebrew-core/master/Formula/x/xcbeautify.rb" \ - -o /tmp/xcbeautify.rb - ``` - -2. **Record the upstream commit** (for the table above and the file header): - - ```bash - # applesimutils - gh api repos/wix/homebrew-brew/commits \ - -f path=Formula/applesimutils.rb -f per_page=1 \ - --jq '.[0].sha[:12]' - - # xcbeautify - gh api repos/Homebrew/homebrew-core/commits \ - -f path=Formula/x/xcbeautify.rb -f per_page=1 \ - --jq '.[0].sha[:12]' - ``` - -3. **Merge into `.github/homebrew-rnfb/Formula/.rb`** — keep the RNFB header at the top (replace version + commit), then paste the upstream `class` body. Remove `head "..."` lines if present (frozen vendored formulae should not track moving branches). Example header: - - ```ruby - # frozen_string_literal: true - # RNFB CI vendored formula — do not install from third-party taps in workflows. - # Upstream: wix/homebrew-brew @ <12-char-sha> — AppleSimulatorUtils - # Update: see okf-bundle/ci-workflows/ios.md#pinned-homebrew-utilities - ``` - -4. **Verify locally on macOS** (from repo root): - - ```bash - bash .github/workflows/scripts/install-homebrew-rnfb.sh - --version # xcbeautify - applesimutils --help # applesimutils (no --version) - ``` - - If upgrading a formula already in your Cellar, uninstall first: `brew uninstall `. - -5. **Update this doc** — bump the version and upstream-commit columns in the table above. - -6. **Open a PR** — CI will exercise the same install script as production workflows. Watch the **Install brew utilities** step timing (`applesimutils` often builds from source on `xcode-27`). - -#### Local dev (optional) - -Match CI with the install script, or install a single formula file via the script: - -```bash -bash .github/workflows/scripts/install-homebrew-rnfb.sh applesimutils xcbeautify -``` - -See also `CONTRIBUTING.md` and `tests/README.md`. - -**`applesimutils` on modern runners** — upstream bottles target older macOS releases; GHA `xcode-27` typically **builds from source** (needs Xcode). Expect a longer “Install brew utilities” step than `xcbeautify`, which usually installs from a matching bottle. +- [iOS CI: simulator reliability and instrumentation](ios/simulator-reliability.md): Why iOS simulators flake on CI, what the workflow does about it, simulator logging and video, CI baseload policy, Detox configuration, and Codecov on the debug matrix. + +- [iOS CI: e2e app orchestration, launch failures](ios/orchestration-launch.md): Detox + Jet orchestration in the test app and launch-phase failures 1 to 5 (early ready race, device registry lock, main-thread delay, waitForActive, Metro unresponsive), plus diagnosing from sim-app.log. + +- [iOS CI: Jet WebSocket, relaunch and coverage teardown failures](ios/orchestration-jet.md): Failures 6 to 8: Jet WebSocket disconnects, reconnect send race, release transformFailure masking, FrontBoard relaunch race, and coverage teardown handshake failure. + +- [iOS CI: release archive, operations and pinned tools](ios/release-and-tooling.md): ios-release-archive job, operational notes, local stress iteration, and the pinned Homebrew utilities (applesimutils, xcbeautify) with how to update them. + diff --git a/okf-bundle/ci-workflows/ios/orchestration-jet.md b/okf-bundle/ci-workflows/ios/orchestration-jet.md new file mode 100644 index 0000000000..087d34888f --- /dev/null +++ b/okf-bundle/ci-workflows/ios/orchestration-jet.md @@ -0,0 +1,211 @@ +--- +type: Reference +title: 'iOS CI: Jet WebSocket, relaunch and coverage teardown failures' +description: 'Failures 6 to 8: Jet WebSocket disconnects, reconnect send race, release transformFailure masking, FrontBoard relaunch race, and coverage teardown handshake failure.' +tags: [ci, ios, jet, coverage, troubleshooting] +timestamp: 2026-12-04T00:00:00Z +--- + +# iOS CI: Jet WebSocket, relaunch and coverage teardown failures + +Part of [iOS CI workflows](../ios.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +#### 6. Jet WebSocket disconnect (1006 / 1001) + +**Symptom** (Detox step, debug and release): + +``` +[🟨] Jet client disconnected - for no particular reason (code = 1006). +[jet-ws] transient_disconnect code=1006 grace_ms=30000 waiting_for_reconnect +``` + +The app process (`testing[]`) often stays alive in `sim-app.log` — the break is the **simulator → host** mocha-remote WebSocket on port **8090**, not a native crash. + +**Cause** — Transient abnormal WebSocket closure (1006 = no close frame; 1001 = going away). Common in long debug+coverage runs (live Metro + Istanbul `__coverage__` growth + port 8090 forwarding). mocha-remote-client auto-reconnects in ~1s; Jet and mocha-remote-server now preserve the runner during a grace window instead of exiting immediately. + +**Mitigations in this repo** + +| Change | Location | +|--------|----------| +| 30s reconnect grace for 1006/1001 before fatal exit | `.yarn/patches/jet-npm-0.9.0-dev.13-*.patch` → `cli.js` | +| `reconnectGraceMs: 30000` | `tests/.jetrc.js` | +| mocha-remote-server preserves runner + sends `pull-coverage` on reconnect | `.yarn/patches/mocha-remote-server-npm-1.13.2-*.patch` | +| Assign `this.client` **before** `emit('connection')`; `Server.send()` warns instead of throwing | mocha-remote-server patch → `Server.js` | +| Client WS keepalive (`ping` when supported) + `readyState` logging on send failure | `.yarn/patches/mocha-remote-client-npm-1.13.2-*.patch` | +| `disconnect_context` logs `loadavg`, `process.memoryUsage()`, orchestrate phase, current test/suite, coverage-upload flag | Jet patch → `cli.js` | +| One Jet e2e retry when grace expires (`RETRYABLE_DISCONNECT`) or session/coverage retryable | `tests/e2e/firebase.test.js` | +| Structured WS / orchestration logging | `[jet-ws]`, `[rnfb-e2e]`, `[mocha-remote-ws]` prefixes | + +**Diagnosing from CI logs** (start with `detox-step-*_log` or `flake-summary-*`): + +```bash +# Jet WS lifecycle +rg '\[jet-ws\]|\[rnfb-e2e\]|\[mocha-remote-ws\]|Jet client disconnected|RETRYABLE_DISCONNECT' detox-step.log + +# Disconnect resource context (+ orchestrate phase when defer-run enabled) +rg '\[jet-ws\] disconnect_context|\[rnfb-e2e\] orchestrate-state' detox-step.log + +# Grace window recovered (no e2e retry needed) +rg '\[jet-ws\] reconnect_recovered|\[mocha-remote-ws\] reconnect_recovered' detox-step.log + +# Fatal transient disconnect → e2e retry eligible +rg '\[jet-ws\] (transient_disconnect|fatal_disconnect|RETRYABLE_DISCONNECT)' detox-step.log + +# Retry decision tree +rg '\[rnfb-e2e\] retry-eligibility' detox-step.log + +# Runner load at disconnect time +rg 'disconnect_context|resource-monitor' detox-step.log resource-monitor.log +``` + +**Sentinel patterns** + +| Pattern | Meaning | +|---------|---------| +| `transient_disconnect code=1006` then `reconnect_recovered` | Flaky WS; grace window saved the run | +| `fatal_disconnect code=1006 grace_expired_ms=30000` + `RETRYABLE_DISCONNECT` | Grace failed; e2e should retry once | +| `[rnfb-e2e] Retrying after transient Jet WS` | Second Jet attempt starting (simulator reboot) | +| `disconnect_context` with high loadavg / RSS | Correlate with `resource-monitor-*_log` snapshot at same UTC timestamp | +| Release passes, debug fails with 1006 | Points at Metro/debug+coverage load, not test logic | +| `reconnect_recovered` alone then ordinary product assertion (single `Jet tests on `) | **Not** Jet-retryable — bare reconnect must not mask deterministic product bugs. Tradeoff: avoids false retries; D1 (Release `transformFailure` mask) + D4 (secondary app-name collision) cover related flakes separately | +| `reconnect_recovered` **and** desync signal (`Jet tests on ` ≥2 / suite re-entry, or `Unknown% ( 0/0 )`, or `[🟥] Stopped the server`) | Mid-suite reconnect left polluted JS / Firebase registry or lost coverage; Jet attempt 2 should trigger (`jetReconnectDesync` in `retry-eligibility`) | +| `reconnect_recovered` then `Error: No client connected` or `send skipped action=pull-coverage` | Reconnect send race (issue 6b); Jet attempt 2 should trigger | +| `awaiting-jet-exit` + ~20m silence + coverage `0/0` + `stall-kill-jet` (then Jet attempt 2 / iOS reboot) | Jet never produced mocha after `launch-ready` — stall is **retryable** once (`retryableAtJetLevel`); inspect `[rnfb-e2e] stall-diagnostics` / `lsof` on `:8090`/`:8091`/`:8081`, `[jet-control] server.run starting` vs defer-only, and Metro detail in `/tmp/rnfb-metro-*.log` inside `metro-*_log` | + +#### 6b. Reconnect send race under extreme host load + +**Symptom** (often **release** matrix leg, mid-run during heavy emulator tests e.g. Functions `HttpsError`): + +``` +[jet-ws] transient_disconnect code=1006 grace_ms=30000 waiting_for_reconnect +[jet-ws] reconnect_recovered code=1006 elapsed_ms=~30000 +Error: No client connected +``` + +Or, after the server patch, the Jet process stays up but logs: + +``` +[mocha-remote-ws] send skipped action=pull-coverage readyState=... +``` + +**Cause** — macOS GitHub runners can become **heavily I/O saturated** at any time (Spotlight indexing is a common contributor). We **cannot** disable Spotlight — `xcodebuild` / Xcode expect an up-to-date index. Under load averages in the hundreds, a transient WS 1006 is more likely; the 30s grace window often **does** recover the transport, but upstream `mocha-remote-server` used to `emit('connection')` **before** assigning `this.client`. Jet's `connection` listener immediately called `server.send({ action: 'pull-coverage' })`, which threw `No client connected` and **killed the Jet Node process** (uncaught exception). That failure was **not** classified as retryable WS disconnect — `retry-eligibility` showed all `false`. + +A duplicate proactive `pull-coverage` in the Jet patch made the race worse (two senders on reconnect). + +**Mitigations in this repo** + +| Change | Location | +|--------|----------| +| `this.client = ws` before `emit('connection')`; protocol check first | mocha-remote-server patch → `handleConnection` | +| Single `pull-coverage` after reconnect (server only, when runner active) | mocha-remote-server patch → `handleConnection` | +| Remove Jet `connection` handler `pull-coverage` (keep `reconnect_recovered` log) | Jet patch → `cli.js` | +| `Server.send()` logs `[mocha-remote-ws] send skipped` instead of throwing | mocha-remote-server patch → `Server.js` | +| `JET_NO_CLIENT_CONNECTED_RE` → retryable Jet session failure | `tests/e2e/firebase.test.js` | + +**Diagnosing** + +```bash +rg 'reconnect_recovered|No client connected|send skipped action=pull-coverage' detox-step.log +rg '\[rnfb-e2e\] retry-eligibility' detox-step.log +rg 'disconnect_context|resource-monitor' detox-step.log resource-monitor.log +``` + +Correlate `disconnect_context loadavg=…` with `resource-monitor-*_log` — high loadavg during disconnect is expected on saturated runners and is **not** something we can eliminate; orchestration must tolerate it. + +**Reference symptom** — grace can recover after a disconnect, then Jet may still crash on `No client connected`. + +#### 6c. Release `transformFailure` masks real errors (Metro symbolication) + +**Symptom** (Release builds, or Debug when Metro is not serving the app bundle — any failing assertion): + +``` +Failed to transform failure: Bundle was not loaded from Metro. +``` + +**Cause** — Jet `JetProvider.transformFailure` calls RN `symbolicateStackTrace`, which talks to Metro. Release embeds JS (no Metro); when symbolication throws, mocha-remote replaces the **original** test failure with `Failed to transform failure: …`, hiding the real assertion. + +**Mitigation in this repo** + +| Change | Location | +|--------|----------| +| Catch symbolication failure; `console.warn` one line; return original `err` | `.yarn/patches/jet-npm-0.9.0-dev.13-*.patch` → `src/index.tsx`, `lib/*/index.js` | + +**Sentinel patterns** + +| Pattern | Meaning | +|---------|---------| +| `[jet] symbolicateStackTrace unavailable; returning original error` | Soft-fail path hit; original test error preserved | +| `Failed to transform failure: Bundle was not loaded from Metro.` | Pre-fix masking — patch missing or not applied after install | + +#### 7. FrontBoard / LaunchServices race after terminate+relaunch + +**Symptom** — Second `launchApp` attempt fails after a slow or failed first launch: + +``` +FBSOpenApplicationServiceErrorDomain +Application "io.invertase.testing" is unknown to FrontBoard +``` + +Often preceded by `[rnfb-e2e] terminateApp ... elapsed=60000ms` (or similar) in `detox-step-*_log`. + +**Cause** — Detox `terminateApp` / `simctl` teardown left LaunchServices in a bad state, or `delete: true` on retry removed the install while SpringBoard still tracked the old bundle. + +**Mitigations in this repo** + +| Change | Location | +|--------|----------| +| `RETRYABLE_LAUNCH_RE` includes `unknown to FrontBoard` / `FBSOpenApplicationServiceErrorDomain` | `tests/e2e/firebase.test.js` | +| Inner retry keeps install (`delete: false` on attempt 2+) | `tests/e2e/firebase.test.js` | +| Slow terminate (≥ `RNFB_SLOW_TERMINATE_MS`) → full `boot-simulator.sh` reboot before relaunch | `tests/e2e/firebase.test.js` | +| Exhausted inner launch retries escalate to **Jet attempt 2** (`retryableAtJetLevel`) | `tests/e2e/firebase.test.js` | +| `simctl get_app_container` + `listapps` logging (`[rnfb-e2e] install-state`) | `tests/e2e/firebase.test.js` | +| Filtered sim app log artifact | `sim-app.log` | +| `wait_shutdown` before `simctl install` on reboot | `boot-simulator.sh` | + +**Diagnosing** + +```bash +rg 'install-state|launchApp failure|FrontBoard|FBSOpenApplication|terminateApp' detox-step.log +rg -i 'invertase|FrontBoard|unknown' sim-app.log +``` + +#### 8. Coverage teardown handshake failure (tests pass, NYC 0/0) + +**Symptom** — Full Jet suite passes, then `"after all"` / coverage teardown fails: + +``` +Failed to send 'coverage-ready' message: WebSocket is closed +[jet-coverage] merged 0 file(s) +Coverage summary: Unknown% ( 0/0 ) +``` + +May follow `[jet-ws] reconnect_recovered` mid-run — transport reconnected but the coverage upload socket was already dead. + +**Cause** — mocha-remote **transport** reconnect ≠ **coverage handshake** recovery (`coverage-ready` → server `pull-coverage` → `coverage-data` → `coverage-ack`). + +**Mitigations in this repo** + +| Change | Location | +|--------|----------| +| Server sends `pull-coverage` proactively after reconnect | mocha-remote-server patch only (Jet `connection` handler must not duplicate) | +| Client `uploadCoverage()` retries up to 3× with backoff; logs `readyState` at send | mocha-remote-client patch | +| `[jet-coverage] server recv coverage-ready` / client send logging | mocha-remote-server + client patches | +| `JET_COVERAGE_TEARDOWN_RE` → retryable Jet session failure | `tests/e2e/firebase.test.js` | +| Jet attempt 2 on reconnect + lost coverage (`JET_COVERAGE_LOST_RE`) | `tests/e2e/firebase.test.js` | + +**Diagnosing** + +```bash +rg '\[jet-coverage\]|coverage-ready|coverage-ack|pull-coverage|merged 0 file' detox-step.log +rg '\[rnfb-e2e\] retry-eligibility' detox-step.log +``` + +| Pattern | Meaning | +|---------|---------| +| `reconnect_recovered` then `coverage-ready.*WebSocket is closed` | Handshake flake; should be Jet-retryable | +| `[jet-coverage] client send coverage-ready attempt=2` | Client retry in progress | +| `merged 0 file(s)` after disconnect | NYC got no JS coverage — check handshake lines above | + +See also [coverage design — e2e TypeScript coverage](../../testing/code-coverage/pipelines.md#e2e-typescript-coverage-jet--nyc). + +**Cloud API quota (Installations / Remote Config)** — platform-agnostic; see [firebase testing project — CI triage](../../testing/firebase-testing-project.md#ci-triage-cloud-api-quota-pressure). diff --git a/okf-bundle/ci-workflows/ios/orchestration-launch.md b/okf-bundle/ci-workflows/ios/orchestration-launch.md new file mode 100644 index 0000000000..8ade56107d --- /dev/null +++ b/okf-bundle/ci-workflows/ios/orchestration-launch.md @@ -0,0 +1,172 @@ +--- +type: Reference +title: 'iOS CI: e2e app orchestration, launch failures' +description: 'Detox + Jet orchestration in the test app and launch-phase failures 1 to 5 (early ready race, device registry lock, main-thread delay, waitForActive, Metro unresponsive), plus diagnosing from sim-app.log.' +tags: [ci, ios, detox, jet, troubleshooting] +timestamp: 2026-12-04T00:00:00Z +--- + +# iOS CI: e2e app orchestration, launch failures + +Part of [iOS CI workflows](../ios.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +### E2E test app orchestration (Detox + Jet) + +After pre-boot, failures often move inside app process `testing`: boot/install are fine, `launchApp` stalls while app stays alive. + +#### 1. Early `ready` race + +**Detox step symptom** + +``` +ws-server connection :50400<->:50415 +ws-server The app has dispatched "ready" action too early. +``` + +**Cause** — iOS `DetoxManager` sends `ready` before server `login`; Detox 20.x drops it, so `launchApp()` waits forever. + +**Mitigation** — Detox patch buffers early `ready` and replays after `login`; see [detox-patches.md](../detox-patches.md). + +#### 2. Device registry lock (`ECOMPROMISED`) + +**Symptom** — failure before test output, often first minute: + +``` +Error: Unable to update lock within the stale threshold + code: 'ECOMPROMISED' +``` + +**Cause** — Detox locks `~/Library/Detox/device.registry.json`; 10s heartbeat can miss under CI load ([Detox #4210](https://github.com/wix/Detox/issues/4210)). + +**Mitigation** — same Detox patch doubles stale to 20s in `ExclusiveLockfile.js`. We do **not** use `detox reset-lock-file` in CI (wipes the ledger). See [detox-patches.md](../detox-patches.md#device-registry-lock-ecompromised). + +**Sentinel** — `proper-lockfile` + `ECOMPROMISED` in the Detox step log; build and Pre-Boot steps green. + +#### 3. Main-thread delay before WebSocket handshake + +**Symptom** — 30–60s gap between app launched and first `Connection 1: ready` / `handshake successful`; main-thread Firebase/RN/LLVM startup can defer WS callbacks. + +**Mitigations** + +| Change | Location | +|--------|----------| +| Wait for Jet (port 8090) before `launchApp` | `tests/e2e/firebase.test.js` | +| Defer `server.run()` until host `POST /launch-ready` on control port **8091** (`RNFB_JET_DEFER_RUN=1`) | Jet patch + `firebase.test.js` — [Jet host orchestration](../../testing/e2e/run-loop.md#jet-host-orchestration-ports-and-launch-gate) | +| `POST /orchestrate-state` + `[rnfb-e2e] orchestrate-state=` for launch/retry triage | `firebase.test.js` + Jet patch | +| Wait for Metro (`/status`) before `launchApp` | `tests/e2e/firebase.test.js` (debug Detox configs only; release skips Metro wait) | +| Bounded `launchApp` timeout / retries | [`tests/e2e/detoxLatencyPolicy.js`](../../../tests/e2e/detoxLatencyPolicy.js) (consumed by `firebase.test.js`); release uses `RNFB_LAUNCH_APP_RELEASE_TIMEOUT_MS` from the same module; Detox Login / CurrentStatus: [detox-patches](../detox-patches.md) | +| `detoxEnableSynchronization: '0'` at launch (native `equals("0")`; `'NO'` still installs Fabric idling) | `tests/e2e/firebase.test.js` — [running e2e § gray screen](../../testing/e2e/platform-troubleshooting.md#android-emulator-gray-screen--quick-boot-blocking) | +| `detoxURLBlacklistRegex: '.*'` | `tests/e2e/firebase.test.js` (existing) | + +#### 4. `waitForActive` / scene never foreground-active + +**Symptom** — `isReady` + `waitForActive`, no `waitForActiveDone`; app alive, scene remains unattached/inactive. + +**Instrumentation** — `AppDelegate.mm` logs `[rnfb-lifecycle]` at launch, lifecycle notifications, and +30s/+60s probes. + +**Distinguish from issue 5** — If `[rnfb-lifecycle]` probes show `UIApplication.state=active` / `foregroundActive` but Detox still hangs on `waitForActive`, the cause is likely Metro/JS bundle load failure (issue 5), not scene activation. + +#### 5. Metro unresponsive at launch → `waitForActive` hang (active app) + +**Symptom** — same as issue 4, but `[rnfb-lifecycle]` shows app active; usually debug-only (live Metro). + +**Cause chain**: + +1. Debug app requests `http://localhost:8081/status` from inside the simulator; TCP connects but Metro returns no bytes within ~10s (`NSURLErrorDomain Code=-1001`). +2. RN logs `No script URL provided. Make sure the packager is running...` and shows RedBox; DetoxSync adds an RN-load idling resource that never clears. +3. Detox WS login/`isReady` succeed (early-ready patch works), then `waitForActive` is received but **`waitForActiveDone` never arrives** even though UIKit is active. + +Metro can look healthy on the **host** during pre-fetch minutes earlier while being unresponsive when the app actually launches. + +**Instrumentation** — `AppDelegate.mm` observes `RCTJavaScriptDidFailToLoadNotification` and logs: + +- `event=RCTJavaScriptDidFailToLoad` with NSError domain/code/description +- `event=packager-probe` — `[RCTBundleURLProvider isPackagerRunning:]`, `packagerServerHostPort`, resolved `bundleURL` +- `event=packager-status-fetch` — direct `http://localhost:8081/status` fetch from inside the app with explicit timeout and HTTP status/body or error + +**Mitigations in this repo** + +| Change | Location | +|--------|----------| +| Wait for Metro `/status` before `launchApp` | `tests/e2e/firebase.test.js` (debug Detox configs only) | +| In-process `launchApp` retry on launch failure (logs `launchApp failure reason=`) | `tests/e2e/firebase.test.js` (`RNFB_LAUNCH_APP_MAX_ATTEMPTS` — default in [`detoxLatencyPolicy.js`](../../../tests/e2e/detoxLatencyPolicy.js)) | +| Keep install on inner retry (`delete: false` on attempt 2+) | `tests/e2e/firebase.test.js` | +| Slow `terminateApp` (≥ `RNFB_SLOW_TERMINATE_MS`, default 10s) → reboot via `boot-simulator.sh` | `tests/e2e/firebase.test.js` | +| Full Jet e2e retry when inner launch retries exhausted, await-exit stall, or WS/coverage teardown retryable | `tests/e2e/firebase.test.js` (`retryableAtJetLevel`, `isRetryableE2eFailure`; stall → `stall-kill-jet`) | +| `simctl get_app_container` / `listapps` before and after each launch attempt | `tests/e2e/firebase.test.js` (`[rnfb-e2e] install-state`) | +| Bounded `launchApp` timeout | Debug: `RNFB_LAUNCH_APP_TIMEOUT_MS`; release: `RNFB_LAUNCH_APP_RELEASE_TIMEOUT_MS`. Defaults for both live in [`detoxLatencyPolicy.js`](../../../tests/e2e/detoxLatencyPolicy.js). On CI's boot-prepared simulator, the run's first launch skips `delete: true`, because Detox init (`behavior.init.reinstallApp`) has just reinstalled the app; later launches keep the existing delete rules | +| Metro log artifacts (`metro.log` + `/tmp/rnfb-metro-*.log`) | `.github/workflows/tests_e2e_ios.yml` | +| JS load failure + packager probe logging | `tests/ios/testing/AppDelegate.mm` | +| Bundle URL pinned to `127.0.0.1` (bypasses RN `localhost` fallback) | `tests/ios/testing/AppDelegate.mm` | + +**Known intermittent pattern (community)** — RN iOS debug builds commonly hit `No script URL provided` when Metro is down, slow, or reachable from the host but not from the simulator process. Reported causes include: Metro event loop blocked under load (TCP connect succeeds, HTTP hangs — matches our `-1001` on `/status`), macOS network proxy intercepting `localhost:8081`, port 8081 contention, and `RCTBundleURLProvider` returning a nil bundle URL despite `isPackagerRunning=YES` ([react-native#49173](https://github.com/facebook/react-native/issues/49173)). On **iOS 26+ simulators**, hostname resolution for `localhost` vs `127.0.0.1` can be unreliable; hardcoding `127.0.0.1` in bundle URL resolution has been reported to fix intermittent Metro disconnects ([react-native#56447](https://github.com/facebook/react-native/issues/56447)). Our test app now pins the debug bundle URL to `127.0.0.1:8081` and the e2e harness retries `launchApp` on retryable launch failures (Metro/bundle timeout, FrontBoard errors) before failing the Jet attempt. Release uses an embedded bundle, shorter launch timeout, and no Metro wait. These are typically **environment/timing** flakes rather than app logic bugs. + +#### Diagnosing from `sim-app.log` + +Download the artifact (`gh run download -n sim-app-debug-0_log`), unzip if needed, then search `sim-app.log`. + +**Quick triage** — map Detox step timestamps to simulator log (`testing[]`): + +```bash +# Detox orchestration inside the app process +rg 'testing\[' sim-app.log | rg -i 'waitForActive|waitForActiveDone|com\.wix\.Detox|ready action too early' + +# App lifecycle confirmation (AppDelegate instrumentation) +rg '\[rnfb-lifecycle\]' sim-app.log + +# Metro / JS bundle load failure (issue 5) +rg '\[rnfb-lifecycle\].*RCTJavaScriptDidFailToLoad|packager-probe|packager-status-fetch' sim-app.log +rg 'No script URL provided|com\.facebook\.react\.log' sim-app.log +rg 'testing\[' sim-app.log | rg '8081/status|index\.bundle' + +# SpringBoard launch intent vs app scene state +rg 'com\.invertase\.testing' sim-app.log | rg -i 'foreground-interactive|visibility.*Foreground|running-active' +rg 'testing\[' sim-app.log | rg -i 'Deactivation reason|activationState|UISceneActivationState' + +# WebSocket timing (main-thread block before handshake) +rg 'testing\[' sim-app.log | rg 'Connection 1: ready|handshake successful' + +# Heavy startup on main thread (often precedes WS delay) +rg 'testing\[' sim-app.log | rg -i 'FIRApp|RNFB|RCTBridge|configure' +``` + +**Sentinel patterns** + +| Pattern | Meaning | +|---------|---------| +| `ready action too early` in Detox step only | Early-ready race (patch should fix; check patch applied in `yarn install`) | +| `ECOMPROMISED` / `Unable to update lock within the stale threshold` | Device registry lock heartbeat missed — see [detox-patches.md](../detox-patches.md) | +| `codecov/project/ios-native` fail | Native lcov not uploaded — check process-coverage step and Codecov Uploads tab for `ios-native` flag | +| `waitForActive` without `waitForActiveDone` | Scene/active hang (issue 4) **or** Metro/JS load failure (issue 5) — check `[rnfb-lifecycle]` probes | +| `probe+30s` / `probe+60s` with `UIApplication.state=inactive` or scene `unattached` | App never became foreground-active (issue 4); compare with SpringBoard `foreground-interactive` lines | +| `probe+30s` / `probe+60s` with `active` / `foregroundActive` but no `waitForActiveDone` | Metro/JS bundle failure despite active UIKit (issue 5); check `RCTJavaScriptDidFailToLoad` and `packager-status-fetch` | +| `packager-status-fetch ... error domain=NSURLErrorDomain code=-1001` | Metro TCP reachable but HTTP timed out from simulator | +| `No script URL provided` in `com.facebook.react.log` | RN never got bundle URL; only `/status` attempts, no `index.bundle` | +| `FBSOpenApplicationServiceErrorDomain` / `unknown to FrontBoard` | LaunchServices race after terminate — see [issue 7](orchestration-jet.md#7-frontboard--launchservices-race-after-terminaterelaunch) | +| `Failed to send 'coverage-ready' message` | Coverage handshake flake — see [issue 8](orchestration-jet.md#8-coverage-teardown-handshake-failure-tests-pass-nyc-00) | +| `[rnfb-e2e] retry-eligibility ... retryable=false` | Check `checks=` JSON for which sub-condition blocked Jet attempt 2 | +| `handshake successful` 30–60s after `simctl launch` | Main-thread startup delay; not a boot failure | +| Only `com.apple.datamigrator` activity, no `testing[` | Pre-boot / migration issue — use Actions `[boot-status]` log, not Detox orchestration | + +**Example healthy sequence** (abbreviated): `didFinishLaunching+after` → `UIApplicationDidBecomeActiveNotification` / scene `foregroundActive` → Detox `loginSuccess` → `isReady` → `waitForActiveDone`. A gap between SpringBoard foreground request and `[rnfb-lifecycle]` `active` is the smoking gun for issue 4. For issue 5, lifecycle probes show `active` but you will see `RCTJavaScriptDidFailToLoad` and/or `No script URL provided` before Detox stalls on `waitForActive`. + +For Metro-side post-mortem, also download `metro-*_log` and check whether Metro logged bundle requests or stalled around the launch timestamp. The wrapper `metro.log` is often only 1–2 lines; prefer the packager detail log: + +```bash +rg -i 'BUNDLE|index\.bundle|8081|error|ECONN|transform' metro.log /tmp/rnfb-metro-*.log +``` + +**Mitigations in this repo (summary)** + +| Change | Location | +|--------|----------| +| Buffer early `ready`, replay after app `login` | `.yarn/patches/detox-npm-20.51.0-*.patch` → `AnonymousConnectionHandler.js` | +| Raise Login / CurrentStatus timeouts | [detox-patches inventory](../detox-patches.md) → `actions.js` | +| 2× device-registry lock stale (20s) | `.yarn/patches/detox-npm-20.51.0-*.patch` → `ExclusiveLockfile.js` | +| Jet + Metro wait, bounded `launchApp` with retry, Detox launch args, install-state + retry-eligibility logging | `tests/e2e/firebase.test.js` + [`detoxLatencyPolicy.js`](../../../tests/e2e/detoxLatencyPolicy.js) | +| Cloud quota Jet retry + cooldown + metrics/summary hooks | `tests/e2e/firebase.test.js`, `packages/app/e2e/cloud-metrics.js` — see [cloud API quota triage](../../testing/firebase-testing-project.md#ci-triage-cloud-api-quota-pressure) | +| Lifecycle + JS load / packager probe logging; bundle URL `127.0.0.1` | `tests/ios/testing/AppDelegate.mm` | +| Pre-boot + `bootstatus` + shutdown wait before install | `boot-simulator.sh` | +| Baseload shrink: one `sim-app.log` stream, load settle before Detox, optional video | `simulator-logging.sh`, `wait-for-load-settle.sh`, `tests_e2e_ios.yml` — [CI baseload policy](simulator-reliability.md#ci-baseload-policy-instrumentation) | +| Filtered logs, resource monitor, flake summary, Detox `tee` | `.github/workflows/tests_e2e_ios.yml`, `resource-monitor.sh`, `flake-summary.sh` | +| Metro log artifacts (`metro.log` + `/tmp/rnfb-metro-*.log`) | `.github/workflows/tests_e2e_ios.yml` | diff --git a/okf-bundle/ci-workflows/ios/release-and-tooling.md b/okf-bundle/ci-workflows/ios/release-and-tooling.md new file mode 100644 index 0000000000..dca7b163df --- /dev/null +++ b/okf-bundle/ci-workflows/ios/release-and-tooling.md @@ -0,0 +1,148 @@ +--- +type: Reference +title: 'iOS CI: release archive, operations and pinned tools' +description: 'ios-release-archive job, operational notes, local stress iteration, and the pinned Homebrew utilities (applesimutils, xcbeautify) with how to update them.' +tags: [ci, ios, release, homebrew] +timestamp: 2026-12-04T00:00:00Z +--- + +# iOS CI: release archive, operations and pinned tools + +Part of [iOS CI workflows](../ios.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +### `ios-release-archive` job — real-device archive validation + +The simulator Release build does not exercise Xcode's real-device Archive +action or its install-style post-processing. This job therefore runs an +unsigned `generic/platform=iOS` Release archive (SPM-only; CocoaPods Firebase +is not supported with Firebase Apple SDK 13+). It requires no signing identity +or simulator. + +After archiving, `.github/workflows/scripts/verify-ios-release-archive.sh` +checks each embedded binary's `@rpath` framework dependencies against the +frameworks present in the archived app. A failure names the missing framework +and referencing binary with an `[ios-release-archive] MISSING:` line. + +This gate covers archive compilation and missing-framework embedding. It does +not launch the app and is not equivalent to a signed device or TestFlight test; +runtime-only failures still require a real launch. The SPM embedding decision +and its original failure mode are documented in +[`ios-spm-native-imports.md`](../../ios-spm-native-imports.md#runtime-framework-embedding). +A `"...xcframework-ios.signature"` (or `-ios-simulator.signature`) couldn't +be copied to `"Signatures"` failure from this job is a known Xcode Archive +bug, not a regression — see +[archive signature-copy collision](../../ios-spm-native-imports.md#archive-signature-copy-collision). + +### Operational notes + +- **macOS runner load / Spotlight** — GHA macOS hosts may run Spotlight indexing (or other disk-heavy work) at any time and saturate disk I/O. Disabling Spotlight is **not** an option for Xcode CI. Design for tolerance: longer grace windows, non-throwing `Server.send()`, Jet e2e retry on orchestration crashes, trimmed CI instrumentation ([CI baseload policy](simulator-reliability.md#ci-baseload-policy-instrumentation)), `resource-monitor` + `disconnect_context` for triage. Do not treat high `loadavg` alone as a misconfiguration. +- **Release vs debug** — matrix runs both; each has separate artifacts (`debug` / `release` in the artifact name). +- **Retry** — Pre-Boot retries up to 3 times with 60s between attempts (clean shutdown + boot each time). Jet e2e retries once on retryable WS / launch / coverage teardown / **cloud quota** failures (simulator reboot via `boot-simulator.sh` on iOS; cloud quota adds cooldown — [cloud API quota triage](../../testing/firebase-testing-project.md#ci-triage-cloud-api-quota-pressure)). +- **Do not boot the simulator only inside Detox** — historical races where the testee never sent “ready” to the Detox proxy; pre-boot remains mandatory. +- **CI helper scripts** (repo root relative): + +| Script | Env vars | Role | +|--------|----------|------| +| `.github/workflows/scripts/simulator-logging.sh` | `RNFB_RECORD_SCREENS` (0/1), `RNFB_SIM_LOG_DIR`, `RNFB_SIM_LOG_STDOUT` | One filtered `sim-app.log` stream; optional sim video — sourced by `boot-simulator.sh` | +| `.github/workflows/scripts/wait-for-load-settle.sh` | `RNFB_LOAD_SETTLE_MAX_LOAD` (default **20**), `RNFB_LOAD_SETTLE_MAX_WAIT_SEC`, `RNFB_LOAD_SETTLE_POLL_SEC` | Poll host load immediately before Detox | +| `.github/workflows/scripts/resource-monitor.sh` | `RNFB_RESOURCE_MONITOR_INTERVAL_SEC` (default 10), `RNFB_RESOURCE_MONITOR_LOG` | Background `uptime` + `ps` snapshots during Detox | +| `.github/workflows/scripts/flake-summary.sh` | `RNFB_DETOX_LOG`, `RNFB_FLAKE_SUMMARY_OUT` | Post-run `rg` digest → `flake-summary.txt` | +| `.github/workflows/scripts/configure-apple-ci.sh` | `XCODE_VERSION` / `RNFB_CI_XCODE_SELECTOR`, `RNFB_IOS_SIM_RUNTIME`, `RNFB_CI_REQUIRE_IOS_SIM_RUNTIME` | Post-`setup-xcode` gate: stable Xcode major 27 + optional iOS 27 runtime pin | + +Detox steps use `tee detox-step.log` and `exit ${PIPESTATUS[0]}` so the artifact preserves full output while the step still fails correctly. + +### Local stress iteration (optional) + +> **CI/manual mirror only.** The steps below reproduce CI deflake semantics on a developer machine. Local e2e runs must use [running-e2e.md](../../testing/running-e2e.md) only — do not substitute `boot-simulator.sh`, `resource-monitor.sh`, or `flake-summary.sh` for the canonical `:build && :test-cover` loop. + +To deflake without pushing every change, mirror CI on a macOS machine or VM (SSH is fine): emulators → build → `boot-simulator.sh` (pre-boot, CI-only) → `wait-for-load-settle.sh` → `resource-monitor.sh` → `:test-cover` per [running e2e](../../testing/running-e2e.md) → `flake-summary.sh`. Wrap in a loop over `iterations` and collect `local-e2e-artifacts/iter-N-*` directories. + +### Pinned Homebrew utilities + +CI installs macOS build helpers from **vendored formulae** in `.github/homebrew-rnfb/Formula/` instead of live taps (`wix/brew`, `homebrew-core`). Each formula file is frozen in git with pinned `url`, source `sha256`, and bottle hashes — similar in spirit to SHA-pinned GitHub Actions. + +| Formula | Version | Upstream source | Used in | +|---------|---------|-----------------|---------| +| `applesimutils.rb` | 0.9.12 | [wix/homebrew-brew](https://github.com/wix/homebrew-brew), pinned in vendored formula | iOS e2e (`tests_e2e_ios.yml`) | +| `xcbeautify.rb` | 3.2.1 | [homebrew-core](https://github.com/Homebrew/homebrew-core), pinned in vendored formula | iOS e2e + macOS e2e (`tests_e2e_other.yml`) | + +**Workflow install** — both workflows call `.github/workflows/scripts/install-homebrew-rnfb.sh` (from repo root). Homebrew 6+ refuses bare `brew install --formula path/to.rb`; the script copies formulae into a local `invertase/rnfb` tap, trusts it once per job, then installs: + +```bash +# iOS e2e (tests_e2e_ios.yml) +bash .github/workflows/scripts/install-homebrew-rnfb.sh applesimutils xcbeautify + +# macOS e2e (tests_e2e_other.yml) +bash .github/workflows/scripts/install-homebrew-rnfb.sh xcbeautify +``` + +**Why** — Third-party taps can change formula definitions on every `brew update`. Vendoring avoids supply-chain drift and Brew 6 untrusted-tap warnings for live third-party taps. We still `brew trust invertase/rnfb` for the ephemeral local tap copy each job creates. The install script **uninstalls any existing `homebrew-core` (or other tap) install** of the same formula name first — GHA macOS images often preinstall `xcbeautify`, and Brew refuses same-name formulae from two taps. + +#### When to update a pinned formula + +- CI **Install brew utilities** fails after a macOS runner / Xcode image bump (common for `xcbeautify` Swift/`on_sequoia` conditionals). +- You need a newer **applesimutils** or **xcbeautify** feature or bugfix. +- A security advisory affects the pinned upstream release (bump `url` / version and checksums). + +#### How to update a pinned formula + +1. **Fetch the upstream formula** you want to vendor (usually `master`, or a specific commit if you need a known-good revision): + + ```bash + # applesimutils (wix tap) + curl -fsSL "https://raw.githubusercontent.com/wix/homebrew-brew/master/Formula/applesimutils.rb" \ + -o /tmp/applesimutils.rb + + # xcbeautify (homebrew-core) + curl -fsSL "https://raw.githubusercontent.com/Homebrew/homebrew-core/master/Formula/x/xcbeautify.rb" \ + -o /tmp/xcbeautify.rb + ``` + +2. **Record the upstream commit** (for the table above and the file header): + + ```bash + # applesimutils + gh api repos/wix/homebrew-brew/commits \ + -f path=Formula/applesimutils.rb -f per_page=1 \ + --jq '.[0].sha[:12]' + + # xcbeautify + gh api repos/Homebrew/homebrew-core/commits \ + -f path=Formula/x/xcbeautify.rb -f per_page=1 \ + --jq '.[0].sha[:12]' + ``` + +3. **Merge into `.github/homebrew-rnfb/Formula/.rb`** — keep the RNFB header at the top (replace version + commit), then paste the upstream `class` body. Remove `head "..."` lines if present (frozen vendored formulae should not track moving branches). Example header: + + ```ruby + # frozen_string_literal: true + # RNFB CI vendored formula — do not install from third-party taps in workflows. + # Upstream: wix/homebrew-brew @ <12-char-sha> — AppleSimulatorUtils + # Update: see okf-bundle/ci-workflows/ios.md#pinned-homebrew-utilities + ``` + +4. **Verify locally on macOS** (from repo root): + + ```bash + bash .github/workflows/scripts/install-homebrew-rnfb.sh + --version # xcbeautify + applesimutils --help # applesimutils (no --version) + ``` + + If upgrading a formula already in your Cellar, uninstall first: `brew uninstall `. + +5. **Update this doc** — bump the version and upstream-commit columns in the table above. + +6. **Open a PR** — CI will exercise the same install script as production workflows. Watch the **Install brew utilities** step timing (`applesimutils` often builds from source on `xcode-27`). + +#### Local dev (optional) + +Match CI with the install script, or install a single formula file via the script: + +```bash +bash .github/workflows/scripts/install-homebrew-rnfb.sh applesimutils xcbeautify +``` + +See also `CONTRIBUTING.md` and `tests/README.md`. + +**`applesimutils` on modern runners** — upstream bottles target older macOS releases; GHA `xcode-27` typically **builds from source** (needs Xcode). Expect a longer “Install brew utilities” step than `xcbeautify`, which usually installs from a matching bottle. diff --git a/okf-bundle/ci-workflows/ios/simulator-reliability.md b/okf-bundle/ci-workflows/ios/simulator-reliability.md new file mode 100644 index 0000000000..973f95c815 --- /dev/null +++ b/okf-bundle/ci-workflows/ios/simulator-reliability.md @@ -0,0 +1,165 @@ +--- +type: Reference +title: 'iOS CI: simulator reliability and instrumentation' +description: 'Why iOS simulators flake on CI, what the workflow does about it, simulator logging and video, CI baseload policy, Detox configuration, and Codecov on the debug matrix.' +tags: [ci, ios, simulator, detox, troubleshooting] +timestamp: 2026-12-04T00:00:00Z +--- + +# iOS CI: simulator reliability and instrumentation + +Part of [iOS CI workflows](../ios.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +### Problem + +On GHA macOS runners, `simctl list` can show `Booted` before the simulator is test-ready: + +1. First-boot `com.apple.datamigrator` can run for minutes; app install/launch is unreliable until done. +2. Device names are ambiguous across runtimes; `boot-simulator.sh` resolves or creates a **UDID** on the pinned iOS 27 runtime (`RNFB_IOS_SIM_RUNTIME`, default `iOS 27.0`) before boot/install. In CI it also writes that UDID to `$GITHUB_ENV` as `RNFB_IOS_SIMULATOR_UDID`. The serial `simulator` device in `tests/.detoxrc.js` passes it to Detox as `id`, or, without a UDID (outside CI), `RNFB_IOS_SIM_RUNTIME` as `os`, so Detox allocates the simulator this step booted; `e2e_sanitize_serial_env` keeps both variables. `tests/e2e/firebase.test.js` fails before the first launch if Detox's device is not that UDID. Matched by name alone, Detox can pick a same-named simulator on another runtime the image ships and cold-boot it during the Detox step, next to the pre-booted one. +3. `Booted` ≠ ready; install/launch during migration can hang/fail. + +### What we do + +**Pre-boot step** (`.github/workflows/scripts/boot-simulator.sh`), run via `nick-fields/retry` before Detox: + +> **Not for local operators.** `boot-simulator.sh` is **CI-only** (this workflow) or invoked **internally** by `tests/e2e/firebase.test.js` on iOS test-runner retry. Local e2e: [running-e2e.md](../../testing/running-e2e.md) only — [host-clear probes](../../testing/e2e/preflight-host-clear.md#host-clear-probes), [agent rule](../../testing/running-e2e.md#agent-rule-read-first). Do not run `boot-simulator.sh` as operator prep. + +| Phase | What happens | +|--------|----------------| +| `resolve_device` | Read simulator name from `tests/.detoxrc.js` (e.g. `iPhone 17` or `RN E2E iOS slot-N`) | +| `resolve_udid` | `rnfb_ensure_ios_simulator_udid` on `RNFB_IOS_SIM_RUNTIME` (default iOS 27.0); export `RNFB_IOS_SIMULATOR_UDID` (and append it to `$GITHUB_ENV` in CI) | +| `kill_resolved` | Kill Device Hub (or legacy Simulator.app), terminate app, `simctl shutdown` the resolved UDID | +| `boot_command` | `xcrun simctl boot ` | +| `foreground_simulator` | `open /Applications/DeviceHub.app --args -CurrentDeviceUDID ` (never `open -a Simulator` / `open -a Device Hub`) | +| `wait_for_full_boot` | Poll every 20s (up to 11 min) until `simctl bootstatus` reports ready | +| `wait_shutdown` | If device is still `Booted` when install is about to run, poll up to 120s for `Shutdown` (avoids LaunchServices races after Jet retries) | +| `install_app` | `simctl install` the built `testing.app` **only after** bootstatus succeeds | + +During `wait_for_full_boot`, `[boot-status]` logs: + +- Whether `simctl list` shows the device as `Booted` +- **Data migration** snippets from `xcrun simctl bootstatus -d` (probed with a short timeout so the step keeps printing progress instead of looking hung) +- Elapsed time per poll + +Wait for **`simctl bootstatus`**, not just `Booted`. + +**Timeouts** (tuned for first-boot migration on latest iOS): + +| Setting | Value | Notes | +|---------|-------|--------| +| Pre-Boot retry step | 12 min × 3 attempts | was 5 min | +| Job `timeout-minutes` | 87 | +7 min vs previous 80 | +| Detox test step | 62 min | +7 min vs previous 55 | + +Simulator device caching deferred; bad migration cache needs invalidation policy. + +### Simulator logging and video (troubleshooting) + +Artifacts upload on every run (`if: always()`). + +| Artifact | Source | Use when | +|----------|--------|----------| +| `sim-app--_log` | One filtered `log stream` → `sim-app.log` (`testing` + SpringBoard/invertase) | `[rnfb-lifecycle]`, Detox WS, Metro probes, FrontBoard launch failures | +| `detox-step--_log` | Detox/Jet step stdout/stderr (`tee detox-step.log`) | `[jet-ws]`, `[rnfb-e2e]`, `[jet-coverage]`, Jest output — primary orchestration log | +| `flake-summary--` | `.github/workflows/scripts/flake-summary.sh` → `flake-summary.txt` | Pre-digested `rg` hits across detox/sim-app/metro/resource-monitor logs | +| `resource-monitor--_log` | `.github/workflows/scripts/resource-monitor.sh` → `resource-monitor.log` | Periodic `uptime` + `ps` snapshots (10s default) to correlate WS drops with CPU/memory pressure | +| `metro--_log` | Wrapper `metro.log` plus packager detail `/tmp/rnfb-metro-*.log` (`scripts/e2e/start-packager.sh`; the workflow pins `RNFB_METRO_LOG` to `/tmp`; debug only) | Metro hung, slow bundle, or unresponsive `/status` during app launch — wrapper alone is often 1–2 lines; inspect the detail log | +| `simulator--_video` | `simctl recordVideo` → `simulator.mp4` | Visual confirmation (**`workflow_dispatch` / `workflow_call` `record_screens: true` only**) | +| `screenrecording--` | `screencapture` of the Mac desktop | Includes Device Hub window (**`record_screens: true` only**) | +| `screenrecording-setup--.mov` | Guidepup setup recording | Very early environment setup (**`record_screens: true` only**) | +| `emulator-scripts-logs--` | `.github/workflows/scripts/*.log` | Script output if redirected | + +Video artifacts upload only when **`record_screens: true`** (see [CI baseload policy](#ci-baseload-policy-instrumentation) below). + +### CI baseload policy (instrumentation) + +**Why** — macOS GHA runners showed `loadavg` in the hundreds during iOS e2e. Unfiltered simulator debug log streams (~1M+ lines/run before Detox), host syslog with `--backtrace`, dual video capture (host + sim), and three separate log streams kept baseline CPU/disk load high. A pre-Detox gate at load **10** never cleared within the wait budget. + +**What changed** — shrink always-on instrumentation; gate load immediately before Jet/Detox orchestration at a realistic threshold (**20**). + +**Workflow order** (`.github/workflows/tests_e2e_ios.yml`, before Detox): + +| Step | Script / action | Notes | +|------|-----------------|-------| +| Pre-Boot Simulator | `RNFB_START_SIM_LOGS=0 ./boot-simulator.sh` | Boot + install only; no log streams | +| Start Simulator App Log | `RNFB_SIM_BOOT_MODE=logs ./boot-simulator.sh` | One filtered stream + `resource-monitor.sh`; sim video only if `RNFB_RECORD_SCREENS=1`. Streams from `RNFB_IOS_SIMULATOR_UDID` (from `$GITHUB_ENV`), not `booted` | +| Wait for host load to settle | `wait-for-load-settle.sh` | Poll until `load1 < 20` or 1200s timeout; `continue-on-error: true` | +| Detox Test Debug / Release | `yarn tests:ios:test-cover` / `:release` | Jet orchestration begins here | + +**Removed (high I/O / never triaged from artifacts)** + +| Was | Why removed | +|-----|-------------| +| Host `log stream --backtrace` → `syslog.log` | Whole-machine syslog; heavy under Spotlight/indexing | +| Unfiltered `simctl log stream` → `simulator.log` | Millions of debug lines; triage uses filtered app/SpringBoard lines only | +| Separate `testing.log` + `springboard-invertase.log` | Merged into one stream (below) | + +**Single sim log** — `simulator-logging.sh` writes **`sim-app.log`** via one predicate: + +```text +process == "testing" OR (process == "SpringBoard" AND eventMessage CONTAINS "invertase") +``` + +Covers `[rnfb-lifecycle]`, Detox/Metro app lines, and FrontBoard/LaunchServices invertase failures. + +**Optional video — `record_screens` input** — on `workflow_dispatch` and `workflow_call` only; default **`false`**. PR/push runs leave it off. + +| When `record_screens: true` | When false (default) | +|-----------------------------|-------------------------| +| Guidepup setup recording | Skipped | +| Host `screencapture` → `screenrecording.*` | Skipped | +| `simctl recordVideo` → `simulator.mp4` | Skipped | + +Set explicitly for UI regressions: `gh workflow run tests_e2e_ios.yml -f record_screens=true`. + +**Load settle env** (`wait-for-load-settle.sh`): + +| Variable | Default | Role | +|----------|---------|------| +| `RNFB_LOAD_SETTLE_MAX_LOAD` | **20** | Proceed when 1-min loadavg drops below this | +| `RNFB_LOAD_SETTLE_MAX_WAIT_SEC` | 1200 | Stop waiting and proceed anyway | +| `RNFB_LOAD_SETTLE_POLL_SEC` | 5 | Poll interval | + +Log markers: `[load-settle] ts=… elapsed=… load1=… threshold=20` in the workflow step; copied into `flake-summary.txt` when present. + +**Triage** — Debug legs often plateau higher than release (Metro still running). Saturated runners may never reach 20; treat `[load-settle] WARN: timed out` as informational — Detox still runs. Correlate flakes with `resource-monitor-*_log` and `[jet-ws] disconnect_context loadavg=…` rather than expecting idle hosts. + +**When to use which log** + +- **Boot / migration / “simulator won’t start”** — read the **Pre-Boot Simulator** step log in GitHub Actions first. Look for `[boot-status]` lines and `bootstatus -d` migration output. +- **Detox / app / test failures** — start with **`detox-step-*_log`** or **`flake-summary-*`** (fast triage). For native app instrumentation, download **`sim-app-*_log`**. Jet WS drops (1006/1001) appear in the Detox step (`[jet-ws]`, `[rnfb-e2e]`). For debug Metro issues, also download `metro-*_log`. +- **FrontBoard / relaunch after terminate** — `sim-app-*_log` plus `[rnfb-e2e] install-state` / `launchApp failure` lines in `detox-step-*_log`. +- **Runner load during flake** — `resource-monitor-*_log` (correlate timestamps with `[jet-ws] disconnect_context` loadavg/mem lines). +- **UI regressions** — re-run with `record_screens: true` → `simulator-*_video` or `screenrecording-*`. + +**Downloading artifacts** + +Workflow page **Artifacts**, or: + +```bash +gh run download -n sim-app-debug-0_log +``` + +**Analyzing `sim-app.log`** + +Useful patterns: + +```bash +rg 'testing\[' sim-app.log | rg -i 'waitForActive|waitForActiveDone|com\.wix\.Detox|ready action too early' +rg '\[rnfb-lifecycle\]' sim-app.log +rg '\[rnfb-lifecycle\].*RCTJavaScriptDidFailToLoad|packager-probe|packager-status-fetch' sim-app.log +rg 'No script URL provided|com\.facebook\.react\.log' sim-app.log +rg -i 'invertase|FrontBoard|unknown' sim-app.log +``` + +Long `datamigrator` activity with no `io.invertase.testing` means migration/pre-boot install not done. + +### Detox configuration + +Device type comes from `tests/.detoxrc.js`; boot script and Detox use it. No hard-coded UDID: in CI, Detox takes the UDID the boot step resolved ([simulator reliability](#problem)). + +**Missing Detox framework cache** — if iOS `:test-cover` fails before tests with `Detox.framework could not be found`, rebuild the local cache: [running e2e § iOS Detox framework cache](../../testing/e2e/platform-troubleshooting.md#ios-detox-framework-cache) (`yarn tests:ios:detox-framework-cache:rebuild`). CI restores `~/Library/Detox/ios` from Actions cache keyed by Xcode version. + +### Codecov (debug matrix only) + +Debug leg: `yarn tests:ios:unit` (in-package XCTest; [IosTest-AD-1](../../testing/ios-architecture-decisions.md#iostest-ad-1)) then Detox → `yarn tests:ios:test:process-coverage` + Codecov flags `e2e-ts-ios`, `ios-native`; `codecov/project/ios-native` blocks on missing native upload. **debug+spm** also runs `yarn tests:ios:ruby` and uploads Codecov flag `ios-ruby` (no `flag_management` hard gate — [coverage design § iOS Ruby](../../testing/code-coverage/local.md#ios-ruby-simplecov)). Release skips coverage. Unit LCOV merges into `coverage/ios-native/lcov.info` — [coverage design](../../testing/coverage-design.md). diff --git a/okf-bundle/ci-workflows/other.md b/okf-bundle/ci-workflows/other.md index a2ff62b54a..8db682734d 100644 --- a/okf-bundle/ci-workflows/other.md +++ b/okf-bundle/ci-workflows/other.md @@ -64,7 +64,7 @@ URL: http://localhost:8081/index.bundle?platform=macos&...&inlineSourceMap=false 1. **Startup race** — app opened before Metro finished bundle; native HTTP got truncated response (`-1017`), JS never loaded. 2. **Prefetch URL mismatch** — warmed URL differed from app request, causing cache miss and second bundle build. -3. **`localhost` vs `127.0.0.1`** — same class as [iOS AppDelegate](ios.md#operational-notes); macOS may use `::1` while Metro streams. +3. **`localhost` vs `127.0.0.1`** — same class as [iOS AppDelegate](ios/release-and-tooling.md#operational-notes); macOS may use `::1` while Metro streams. **Mitigations in this repo** diff --git a/okf-bundle/index.md b/okf-bundle/index.md index 5488978ef8..ae399e1a21 100644 --- a/okf-bundle/index.md +++ b/okf-bundle/index.md @@ -34,7 +34,7 @@ okf_version: '0.1' # Cross-cutting work -- [TurboModule / New Architecture](/new-architecture/index.md) — [ADR](/new-architecture/architecture-decisions.md); Codegen TurboModules (library `includesGeneratedCode` vs test-app build-time — [NewArch-AD-5](/new-architecture/architecture-decisions.md#newarch-ad-5--commit-generated-code--accepted)); coordinated New Architecture break +- [TurboModule / New Architecture](/new-architecture/index.md) — [ADR](/new-architecture/architecture-decisions.md); Codegen TurboModules (library `includesGeneratedCode` vs test-app build-time — [NewArch-AD-5](/new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-5--commit-generated-code--accepted)); coordinated New Architecture break - [iOS SPM native integration decisions](/ios-spm-native-imports.md) — dual imports, Swift-product helpers, runtime framework embedding, Expo precompiled module linkage repair - [iOS RNCore podspec invariants](/ios-rncore-podspec.md) — Clang non-modular-includes flag and `pod_target_xcconfig` order under `use_frameworks!` - [Monorepo tooling](/monorepo-tooling/index.md) — Nx local cache, deterministic prepare graph, declaration maps, dependency-cycle linting, dev watch; decisions (ADR) + rollout queue; [maintainer publish](/monorepo-tooling/maintainer-publish.md) diff --git a/okf-bundle/ios-spm-native-imports.md b/okf-bundle/ios-spm-native-imports.md index 35ec3bab68..de8370f3f8 100644 --- a/okf-bundle/ios-spm-native-imports.md +++ b/okf-bundle/ios-spm-native-imports.md @@ -746,4 +746,4 @@ and evidence requirements are owned by the [validation checklist](testing/validation-checklist.md) and [change authoring workflow](testing/change-authoring-workflow.md). The archive job's purpose and limitations are owned by -[iOS CI workflows](ci-workflows/ios.md#ios-release-archive-job--real-device-archive-validation). +[iOS CI workflows](ci-workflows/ios/release-and-tooling.md#ios-release-archive-job--real-device-archive-validation). diff --git a/okf-bundle/new-architecture/architecture-decisions.md b/okf-bundle/new-architecture/architecture-decisions.md index 60c5b8c66e..8b29d28b1c 100644 --- a/okf-bundle/new-architecture/architecture-decisions.md +++ b/okf-bundle/new-architecture/architecture-decisions.md @@ -3,7 +3,7 @@ type: Reference title: New Architecture decisions (ADR) description: Canonical owner of durable architectural decisions for the React Native Firebase TurboModule migration — the "what we decided and why". Other new-architecture docs reference this; they do not restate decisions. tags: [new-architecture, turbomodule, architecture, decisions, adr] -timestamp: 2026-06-29T00:00:00Z +timestamp: 2026-12-04T00:00:00Z --- # New Architecture decisions (ADR) @@ -24,402 +24,50 @@ All decisions in this document use the **`NewArch-AD-`** prefix (e.g. `NewArc | **Proposed** | Recommended, awaiting maintainer sign-off; safe to plan around. | | **Open** | Under analysis; do not lock in code until resolved. | ---- - -## NewArch-AD-1 — New Architecture only — **Accepted** - -One coordinated semver major across the monorepo. No dual old/new bridge per package (`functions` precedent: v24). The legacy bridge interop layer remains available to consumers via RN itself, but RNFB ships TurboModule-only. - -**Why:** A per-package dual-bridge would multiply native surface and testing. A single coordinated break is cheaper to build and reason about. - ---- - -## NewArch-AD-2 — Naming: `NativeRNFBTurbo*` — **Accepted** - -Codegen spec/module names use the `NativeRNFBTurbo*` prefix (`NativeRNFBTurboAuth`, `NativeRNFBTurboFirestore`, …). Spec files must be prefixed `Native` per RN Codegen. - -**Why:** Disambiguates from legacy `RNFB*` module names during transition; satisfies Codegen's `Native*` spec-file requirement. - -**Web / macOS registration:** [`nativeModuleWeb.ts`](../../packages/app/lib/internal/nativeModuleWeb.ts) registers JS-SDK shims by module name in the **registry object initializer** (not deferred to bottom-of-file calls) so `NativeRNFBTurbo*` keys exist before `RNFBNativeEventEmitter` instantiates during circular imports. When `APP_NATIVE_MODULE` changes, register **both** the legacy `RNFBAppModule` key and the turbo name. Missing that registration surfaces as a macOS blank window / `Native module NativeRNFBTurboApp is not registered`. - ---- - -## NewArch-AD-3 — Strong Codegen typing — **Accepted** - -Strong Codegen types wherever the API allows. Source of truth: `packages/*/lib/types/internal.ts`, native method inventories, firebase-js-sdk shapes. Use `Object` / open maps only where payloads are genuinely dynamic. - -**Codegen-safe naming:** Spec methods and generated symbols must avoid language keywords or reserved identifiers across TypeScript, C++, Java, and ObjC++ targets. Known blockers: `delete` as a method name breaks generated native code; TypeScript primitive `object` is rejected by RN Codegen for NativeModule specs (`TSObjectKeyword`) — use a shaped type, Codegen `Object` for truly dynamic maps, or a named interface. Also avoid generated-target reserved words (`class`, `default`, `new`, `switch`, `case`, `try`, `catch`, `return`, `void`, `static`, `public`, `private`, `protected`, `namespace`, `operator`, `template`, `this`, `self`). If a legacy method already uses a reserved word, rename the spec method and keep the public JS API stable via the wrapper. - ---- - -## NewArch-AD-4 — Events deferred to Phase C — **Accepted** - -Keep the legacy event path (`RNFBNativeEventEmitter` → app-module proxy → `RNFBRCTEventEmitter` / `ReactNativeFirebaseEventEmitter` → `SharedEventEmitter` fan-out) under TurboModules. Codegen EventEmitter cutover is a **future** change, not part of the method-call shell. - -**Escalation:** if area-focused e2e or device testing shows a package's events cannot work over the legacy proxy under TurboModules, cut that package's event path over in its own change rather than waiting. **Highest risk:** `messaging` (background/iOS AppDelegate, headless JS task). - -### messaging — EventEmitter stays on the legacy proxy - -**Decision:** `messaging` ships the **method-call TurboModule shell** only. Event emit/subscribe stays on the legacy proxy until a future Codegen EventEmitter cutover. - -| Assertion | Primary source | -|-----------|----------------| -| Native emit sites do not use the messaging module bridge | iOS categories/delegates (`RNFBMessaging+AppDelegate.m`, `+UNUserNotificationCenter.m`, `+FIRMessagingDelegate.m`) call `RNFBRCTEventEmitter`; Android receiver/service/module call `ReactNativeFirebaseEventEmitter` | -| JS subscribes via the app-module proxy, not the messaging shell | `packages/messaging/lib/index.ts` — `nativeEvents` array → `RNFBNativeEventEmitter` → `NativeRNFBTurboApp` ([NewArch-AD-18 E1](#newarch-ad-18--raw-vs-wrapped-resolver-policy--accepted)) | -| Android background (quit/killed) is outside the event-proxy path | `ReactNativeFirebaseMessagingHeadlessService` (`HeadlessJsTaskService`); `AppRegistry.registerHeadlessTask('ReactNativeFirebaseMessagingHeadlessTask', …)` in `packages/messaging/lib/index.ts` | -| iOS background data messages couple shell method + event proxy | `RNFBMessaging+AppDelegate.m` — `signalBackgroundMessageHandlerSet` on shell, then `RNFBRCTEventEmitter` for `messaging_message_received_background` | -| iOS emitter implementation is legacy bridge API (Phase C debt) | `packages/app/ios/RNFBApp/RNFBRCTEventEmitter.m` — `bridge enqueueJSCall:@"RCTDeviceEventEmitter"` | - -The deferral discriminator is **not** satisfied by structure alone: nothing in the messaging native tree requires EventEmitter cutover when the shell becomes a TurboModule. - -**Testing:** Messaging is the highest-risk legacy-proxy package. Area-focused e2e must cover **event delivery**, not only turbo method calls — foreground message receipt, token refresh, notification-opened, and (on iOS) background handler timing against `signalBackgroundMessageHandlerSet`. Device validation is required where the harness cannot automate FCM delivery or AppDelegate background races. Escalate event cutover **only** if that testing proves the proxy fails. iOS `RCTRootView` / `addCustomPropsToUserProps` headless wiring is a separate shell implementation concern, not an event-path escalation trigger. - ---- - - - -## NewArch-AD-5 — Commit generated code — **Accepted** - -**Library packages only:** `includesGeneratedCode: true`; commit Codegen output under `packages/*/android/.../generated` and `packages/*/ios/generated`, mirroring `packages/functions`. CLI `--source library`. - -**Test app is not that contract.** `tests/package.json` must **not** set `includesGeneratedCode: true` — that makes CLI `--outputPath` the *final* dir and writes `tests/ios/ReactCodegen` / `tests/ios/Package.swift` while CocoaPods wants `tests/ios/build/generated/ios/ReactCodegen`. Test-app Codegen output is **build-time, not committed**. [`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) `testing` entry: `--source app`; CLI `--outputPath` is the RN app *base* (`ios` / `.`) because app codegen appends `build/generated/ios` and `android/app/build/generated/source/codegen`. Wipe those derived dirs **and** scrub/gitignore dumps at `tests/ios/Package.swift`, `tests/ios/ReactCodegen/`, `tests/ios/ReactAppDependencyProvider/`. Do not flatten test-app iOS output (keep nested `ReactCodegen`). Skip `scrubAppOnlyIosArtifacts`. That entry does **not** change library codegen. - -**Guard (NewArch-AD-17.3):** CI runs `yarn codegen:verify` — wipe-then-regen ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)) then `git diff --exit-code` on the **library generated trees named above**. Test-app generated trees are not in that check. - ---- - -## NewArch-AD-6 — Unified native module resolver — **Accepted** - -`packages/app/lib/internal/nativeModuleAndroidIos.ts` resolves `TurboModuleRegistry.get(name) ?? NativeModules[name]`. - -**Why / semantics (researched, scope-limited):** In **bridgeless** mode with the **unified native-module proxy** (RN ≥ 0.74 New Architecture default; the repo's test app is RN 0.78 + `newArchEnabled`), both `TurboModuleRegistry.get(name)` and `NativeModules[name]` route through one unified, **cached** `nativeModuleProxy` (`BridgelessNativeModuleProxy` backing `global.nativeModuleProxy`, which *is* `NativeModules`) — so they return the **same instance** for a migrated module; the `??` cannot hand back two divergent wrappers. **Scope caveat (verified by design review):** this identity is confirmed for **bridgeless + unified proxy**; the bridged-New-Architecture path (`__turboModuleProxy` set without bridgeless) is a *different* lookup from bridged `NativeModules` lazy config and is **not verified** to share identity — RNFB targets bridgeless NA, so this is an untested edge, not a supported config. The `NativeModules` fallback is **load-bearing during Phases 1–5**: an unmigrated package's legacy module is null in `TurboModuleRegistry.get` and resolves via the interop-backed `NativeModules` (`legacyBinding_`). - -**Phase R action:** remove the `NativeModules` fallback once all packages are migrated, so a missing module throws instead of returning soft-undefined. - ---- - -## NewArch-AD-7 — `codegenConfig.name` = aggregate library name; one `codegenConfig` per package — **Accepted** - -Each package has **one** `codegenConfig` whose `name` is an **aggregate library name** of the form `RNFBTurboModules` (e.g. `RNFBAppTurboModules`, `RNFBFunctionsTurboModules`, `RNFBFirestoreTurboModules`), **not** a module name. Multiple TurboModules in a package are listed under iOS `modulesProvider` (spec name → ObjC class) and live in the `specs/` dir; Android registers each shell in the package class. **One rule for every package**, single- and multi-spec alike — no degenerate exceptions. - -**Why:** Multi-module packages (database ×5, firestore ×4) cannot name the library after one module, so the aggregate-library shape is mandatory for them; applying it everywhere gives a single rule reviewers can apply without thinking about spec count. The aggregate-library shape is the one RN documents and the one that generalizes. - -**`functions` correction (one-time):** `functions` shipped with `codegenConfig.name: "NativeRNFBTurboFunctions"` (the *module* name). Rename to `RNFBFunctionsTurboModules` for consistency. **Downside: effectively none.** `codegenConfig.name` is the *generated-library* identifier (drives generated file/JNI/CMake target names) — it is **internal**, not a public/consumer symbol, and is **distinct from the module name** `NativeRNFBTurboFunctions` (the `RCT_EXPORT_MODULE` / `TurboModuleRegistry.get('NativeRNFBTurboFunctions')` key), which **stays unchanged**. The rename is mechanical: change `name`, re-run `yarn codegen` ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted) wipe-then-regen removes the old library tree under the configured `outputPath`), and update `react-native.config.js` `cmakeListsPath` / shell imports **only if** those paths embed the old library name, then commit. Only risk is a build-wiring reference to the old library name outside the wiped tree; a clean codegen + build catches it. Track as a small standalone follow-up (low risk, no consumer impact). - -**Gate:** every spec name appears as a `modulesProvider` key (iOS) and is registered in the package class (Android); `codegenConfig.name` matches `RNFBTurboModules`. - -Reference: [`packages/app/package.json`](../../packages/app/package.json) `codegenConfig`. - ---- - -## NewArch-AD-8 — TurboModule JS enumeration: `for...in` + `Object.create` — **Accepted** - -When wrapping or extending a native module, enumerate methods with **`for...in`** (not `Object.keys`) and extend with **`Object.create(host, descriptors)`** (never copy the host into a plain `{}` / spread / `Object.assign({}, host)`). - -**Why:** TurboModules expose methods lazily on the **prototype**, which are non-own; `Object.keys`/spread see nothing and produce `XYZ is not a function`. Codegen methods **are** enumerable via `for...in` (confirmed), so `for...in` + `Object.create` both finds them and preserves the prototype. Reference: [RN enable-libraries § "XYZ is not a function"](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/enable-libraries.md#javascript-xyz--is-not-a-function-it-is-undefined), [facebook/react-native#43221](https://github.com/facebook/react-native/issues/43221). - -Code: [`registry/nativeModule.ts`](../../packages/app/lib/internal/registry/nativeModule.ts), [`nativeModuleAndroidIos.ts`](../../packages/app/lib/internal/nativeModuleAndroidIos.ts). - ---- - -## NewArch-AD-9 — `requiresMainQueueSetup` returns `NO` — **Accepted** - -iOS TurboModule shells return `NO` from `+ requiresMainQueueSetup`. Any genuinely main-thread/UIKit work in `getConstants`/init is dispatched explicitly to the main queue, not by forcing whole-module main-queue setup. - -**Why:** Under TurboModules, `requiresMainQueueSetup = YES` makes the lazy module load run setup **synchronously on the main thread** — the JS thread blocks on main (deadlock risk under fling) **and synchronous methods are blocked** (which would block [NewArch-AD-16 Phase S](#newarch-ad-16--phase-s-asyncsync-conversion--open)). Reference: [RN #49957](https://github.com/facebook/react-native/pull/49957), [RN commit d7ac21c](https://github.com/facebook/react-native/commit/d7ac21cec5492e180fbf3817af7be64ab121cb75) (under TurboModules `getConstants` runs on the JS thread, not the main queue). - -**Per-package audit (part of gap-analysis):** inventory each shell's `getConstants`/init and any `methodQueue` override for genuine main-thread/UIKit dependencies; default to `NO`; dispatch only the specific main-thread work that needs it. - -**Phase 0 status — implemented (2026-06-29 re-implementation pass).** Both shells return `NO`; legacy `methodQueue = dispatch_get_main_queue()` overrides removed per [NewArch-AD-19](#newarch-ad-19--turbomodule-methodqueue-policy--accepted). Validate on-device during area-focused e2e if any method regresses. - ---- - -## NewArch-AD-10 — Cross-package native state is centralized in `app`, with testable APIs — **Accepted** - -`packages/app` is the home of cross-package native APIs and shared state (it always has been). This is acceptable; the goal is to **formalize** it: prefer explicit, testable accessors over bare `public static` fields, and ensure any inter-module state really is routed through `app` rather than duplicated per package. - -**Known shared state to keep centralized:** `authDomains` / iOS `customAuthDomains` (read by `auth` + `RCTConvertFirebase`); `ReactNativeFirebaseJSON` / `Meta` / `Preferences` / `UniversalFirebasePreferences` (read by database, firestore, messaging, crashlytics, app-check); the event emitters (NewArch-AD-4 / Phase C). When a package migrates, it must keep reaching these `app`-owned singletons; do not fork a second copy. - -**Direction:** treat the current `public static` maps as tolerated legacy carryover; a new cross-package channel should be an explicit app-owned API/singleton with tests, not a new public static. - -**Encapsulation (optional, later):** refactor un-encapsulated shared-state items (bare `public static` maps such as `authDomains`) behind explicit, testable `app`-owned accessor methods, and audit that all inter-module state is genuinely centralized in `app`. Optional — it does not block shipping TurboModules. - ---- - -## NewArch-AD-11 — Multi-module method names are merged; uniqueness enforced by test — **Accepted** - -Multiple specs/modules in one package are **merged flat** into a single resolved native object (so JS keeps calling `native.documentGet(...)` etc.). Method names must therefore be **globally unique across a package's specs**. Follow the existing `` naming already in use (`documentGet`, `collectionGet`, `transactionBegin`, `aggregateQuery`, …) — which is why there are zero collisions today. - -**Enforcement:** a build/test-time uniqueness assertion (part of NewArch-AD-17's contract test) asserts the union of method names across a package's specs has no duplicates. Optional `__DEV__` runtime guard in the merge loop warns on overwrite. We do **not** namespace sub-modules on the wire (would churn every call site). - ---- - -## NewArch-AD-12 — One commit per package — **Accepted** - -Convert a whole package (all its legacy modules → all its specs) in one [change authoring](../testing/authoring/loop.md#primary-loop) loop (`documentation?` before frozen `independent-review`); land it as one `feat()!: migrate to TurboModules` (breaking: New Architecture required). Multiple specs ≠ multiple commits — they share `codegenConfig`, generated artifacts, podspec/gradle guards, and JS wiring that only build and pass e2e together. - ---- - -## NewArch-AD-13 — Test harness: committed defaults + gitignored local overrides — **Accepted** - -`tests/globals.js` and `tests/app.js` keep the **committed defaults** (`RNFBDebug = false`, full `platformSupportedModules`, durable product wiring such as the `NativeRNFBTurbo*` resolver routing). Local per-run choices (`RNFBDebug = true`, a focused module list) live in a small **gitignored overrides file** that the harness reads if present. - -**Why:** Durable product wiring (e.g. routing `NativeRNFBTurbo*` through the resolver) currently shares files with ephemeral narrowing, so a `git checkout` revert of narrowing also drops product wiring — this already happened once. It also bites human developers who narrow locally and then lose or accidentally commit it. Separating committed defaults from a gitignored overrides file makes the durable wiring un-revertable and the local narrowing impossible to commit. - -**Mechanism:** - -- Committed **`tests/harness.overrides.example.js`** — the shape demonstrator. Heavily commented for a human or agent: what each field means, valid values, and exactly what to paste to narrow modules / enable `RNFBDebug`. Exports an empty/no-op override so copying it changes nothing until edited. -- Gitignored **`tests/harness.overrides.js`** — the real local file; developers/agents copy the example to this name and edit it. -- `tests/globals.js` / `tests/app.js` read `harness.overrides.js` if present, else fall back to committed defaults. Because `tests/app.js` uses `require.context` (Metro static analysis), the override must express module narrowing as a **filter list the harness applies to the static set**, not a dynamic `require`. - -**Ordering caution (do this in order):** add `tests/harness.overrides.js` to `.gitignore` **first** and verify it is ignored (`git check-ignore`), **then** create the local file — so the real overrides file can never be accidentally tracked. The committed example file (`harness.overrides.example.js`) must **not** be ignored. - -### NewArch-AD-13a — Optional overrides need a resolver stub (Metro dependency-map integrity) — **Accepted** - -The optional `require('./harness.overrides.js')` in `tests/app.js` / `tests/globals.js` sits in a `try/catch`, so Metro treats it as an **optional dependency**. When the gitignored file is **absent** (the default), Metro 0.81.x (RN 0.78) **omits the unresolved optional dependency from the requiring module's serialized dependency-id array** instead of inserting a placeholder. That shifts every later dependency index down by one and drops the module's **final** dependency — surfacing at runtime, during the very first `App()` render, as `Requiring unknown module "undefined"`. It is deterministic and independent of caches, `node_modules`, `lazy` bundling, and RN version; it was masked whenever a developer happened to have a local `harness.overrides.js` present, and it breaks any clean checkout / CI that runs e2e without one. - -**Decision:** `tests/metro.config.js` `resolveRequest` resolves `./harness.overrides.js` to a **committed empty stub** (`tests/harness.overrides.stub.js` → `module.exports = {}`) whenever the local file does not exist; a present local override resolves normally. The dependency then always resolves, so the dependency map stays intact. - -**Why not just commit a real `harness.overrides.js`:** keeping the override gitignored (AD-13) preserves "local narrowing can never be committed"; the resolver stub restores Metro integrity without giving that up. Keep the `try/catch` as defense-in-depth. The stub must never carry overrides. - ---- - -## NewArch-AD-14 — Native-module wrapper: memoizing lazy `Proxy` — **Accepted** - -The wrapper gives every native method: (1) **arg prepending** (`appName`, region/databaseId — the native bridge argument injection that lets product code call `firestore().collection(...)` without passing `appName`), (2) **error mapping** (native rejections → `NativeFirebaseError`), (3) **iOS null-encoding** for TurboModule object args. These responsibilities are mandatory product behavior. - -**Decision:** wrap via a **memoizing lazy `Proxy`** — each method is wrapped+bound **on first call** and cached, instead of eagerly materializing every method at first touch. - -**Why over eager:** eager builds all closures up front (auth ≈ 59, firestore ≈ 31 per cache key) and **defeats TurboModule prototype lazy loading**; the lazy Proxy preserves laziness (only pay for methods actually called), removes the eager `getConstants` rebuild on hot paths ([NewArch-AD-15](#newarch-ad-15--constant-memoization-scope-static-only--accepted)), and lets the `app`-path and `FirebaseModule`-path wrapping converge on one shape. The Proxy must enumerate via `for...in` and preserve the host prototype ([NewArch-AD-8](#newarch-ad-8--turbomodule-js-enumeration-forin--objectcreate--accepted)) — it must **not** flatten onto a frozen `{}` (that is the eager pattern being replaced). - -**Coupling note:** the current `initialiseNativeModule` flatten-onto-`{}` + `Object.freeze` only works because eager wrapping pre-materializes own-enumerable methods. Moving to the Proxy means returning the Proxy (or a Proxy-backed object), **not** an `Object.assign`-ed frozen plain object. Update both the multi-module merge and the single-module path together. - -### NewArch-AD-14a — Multi-host merge: routing composite Proxy (required for multi-module) - -A single `Proxy` has **one** target/`[[Prototype]]`, so it cannot represent N independent TurboModule hosts (firestore ×4, database ×5) whose lazy methods live on **separate** prototype chains. The single-host Proxy is insufficient for multi-module packages, which **Phase 1 hits immediately** (`FirestoreStatics`, `DatabaseSyncTree`). Design the merge as a **routing composite Proxy**, not a flattened object: - -1. **At init (metadata only, cheap):** `for...in` each raw host to build a `methodName → { host, key }` routing map. No wrapping/binding yet — just discover which host owns each name. (Method names are unique across a package's specs by [NewArch-AD-11](#newarch-ad-11--multi-module-method-names-are-merged-uniqueness-enforced-by-test--accepted), so the map has no collisions.) -2. **`get(name)` trap:** on first access, look up `{ host, key }`, wrap+bind from the **correct** host (arg-prepend + error-map + iOS null-encode), memoize the wrapped fn, return it. Preserves per-host prototype/laziness. -3. **`has` / `ownKeys` / `getOwnPropertyDescriptor`:** answer from the routing map (so `in`, `for...in`, and `Object.keys` over the merged surface behave). -4. **Drop the dead `multiModuleRoot[moduleName] = !!nativeModule` boolean flags** — they are written but never read in product code; if optional-module presence is ever needed, keep it in a side table, not on the callable surface. -5. **No `Object.freeze`** on the composite — immutability is provided by the Proxy traps (no `set`), not by freezing. - -The single-module path is the degenerate N=1 case of the same composite (one host in the routing map). Implement both through the one mechanism. **NewArch-AD-17.1's contract test must include a 2-host merge fixture** even before firestore ships, since Phase 0 (`app`/`utils` are resolved as *separate* single-host surfaces) does **not** exercise this path. - ---- - -## NewArch-AD-15 — Constant memoization scope: static only — **Accepted** - -Memoize constants that are **static after init** (e.g. app `NATIVE_FIREBASE_APPS`, `FIREBASE_RAW_JSON`; iOS/file-path constants). Do **not** memoize constants that can change at runtime; expose those as **methods**, not cached constants. - -**Why / coherency:** Memoization is JS-layer caching. For static native state a cached snapshot can't drift; for **dynamic** native state it can, with no native→JS invalidation signal. - -**Constant taxonomy (classify each before caching):** - -| Class | Examples | Caching rule | -|-------|----------|--------------| -| **bootstrap-only** | `NATIVE_FIREBASE_APPS` | Snapshot at bootstrap. JS never re-reads it today, so memoizing preserves current semantics — but document it as a bootstrap snapshot; runtime `initializeApp`/`deleteApp` will **not** be reflected (already true). | -| **build-time static** | `FIREBASE_RAW_JSON`, path constants (`DOCUMENT_DIRECTORY`, …) | Safe to memoize indefinitely. | -| **session-static** | `isRunningInTestLab` | Safe to memoize. | -| **dynamic** | `androidPlayServices` | **Never cache as a constant.** Expose as a method (`androidGetPlayServicesStatus()`); remove from the spec's `getConstants` typing when converted. | - -**Hot-path bug to fix in the same pass:** `withTurboConstants` calls `getConstants()` on **every** `getReactNativeModule()` resolve — the exact rebuild NewArch-AD-14/NewArch-AD-15 target. And `messaging.isSupported()` currently reads the Play Services value via the **legacy** module name `RNFBUtilsModule` and the static constant — under turbo-only resolution that name returns nothing, so `isSupported()` breaks. Fix it to resolve `NativeRNFBTurboUtils` **and** read via the dynamic method, not the constant. - ---- - -## NewArch-AD-16 — Phase S (async→sync conversion) — **Open** - -Some RNFB methods are `Promise` only because the legacy bridge forced async, while firebase-js-sdk is synchronous. TurboModules support sync JSI methods, so those can return to sync parity. **Discriminator:** keep `Promise` when the native work has real latency (network / disk / keychain / token); convert only pure bridge-forced async. - -**Open question driving the gap-analysis:** the "keep async if it does network/IO/disk" rule assumes firebase-js-sdk's sync methods do **not** do blocking IO for the same functionality. That must be verified per method (does the web SDK do the work in-memory, or defer it?), because if web is genuinely sync-and-non-blocking, RNFB may be able to be sync too. Do not lock the conversion list until that inventory exists. Blocked by NewArch-AD-9 (`requiresMainQueueSetup = NO`) — sync methods require it. - ---- - -## NewArch-AD-17 — Spec contract + parity tests — **Accepted** - -Jest-level tests, reused across packages: - -1. **Resolution/enumeration contract** — **Accepted.** A fixture that models a TurboModule (methods **non-own on the prototype**, constants own; `Object.keys(raw) === []`) and asserts every spec method is callable through the **real wrapper** (`getNativeModule`/`getAppModule`). Catches the NewArch-AD-8 enumeration class — and now the NewArch-AD-14 Proxy behavior — in sub-second Jest instead of 30-minute e2e. Build alongside the Phase 0 re-implementation. **Must include a 2-host merge fixture** (two mock TurboModule hosts, disjoint method sets) that exercises the [NewArch-AD-14a routing composite Proxy](#newarch-ad-14a--multi-host-merge-routing-composite-proxy-required-for-multi-module) — because Phase 0 (`app`/`utils` resolved as separate single-host surfaces) does not, yet Phase 1 (firestore/database) depends on it. - - - -### NewArch-AD-17.1 — Jest TurboModule contract test — **Accepted** - -**Canonical file:** [`packages/app/__tests__/nativeModuleContract.test.ts`](../../packages/app/__tests__/nativeModuleContract.test.ts) - -**Describe block (grep anchor):** `TurboModule wrapper contract (NewArch-AD-17.1)` - -**Scoped Jest command:** - -```bash -yarn tests:jest -- packages/app/__tests__/nativeModuleContract.test.ts -``` - -**Full suite** (`yarn tests:jest`) must also stay green — the contract test is part of the global Jest run, not a separate harness. - -**Fixtures required in that file:** - -| Case | Asserts | -|------|---------| -| TurboModule host shape | Methods non-own on prototype; `Object.keys(raw) === []` | -| Single-host wrapper | Every spec method callable via `getNativeModule()` | -| 2-host merge (NewArch-AD-14a) | Routing composite Proxy dispatches to the correct host per method name | - -**When required:** any change to [`nativeModule.ts`](../../packages/app/lib/internal/registry/nativeModule.ts), `withTurboConstants`, or TurboModule wrapper behavior — re-run the scoped command above before closing `implementation_gate` or `review_gate`. -2. **Spec↔native parity** — **Accepted.** Assert each package's spec method-name set equals the union of Android `@ReactMethod` (generated Java spec) and iOS TurboModule protocol methods (generated ObjC spec header), and (NewArch-AD-11) the union across a package's specs has no duplicate names. - - - -### NewArch-AD-17.2 — Spec↔native parity test — **Accepted** - -**Canonical file:** [`packages/app/__tests__/turboModuleSpecNativeParity.test.ts`](../../packages/app/__tests__/turboModuleSpecNativeParity.test.ts) - -**Describe block (grep anchor):** `Spec↔native parity (NewArch-AD-17.2)` - -**Scoped Jest command:** - -```bash -yarn tests:jest -- packages/app/__tests__/turboModuleSpecNativeParity.test.ts -``` - -**Helper:** [`specNativeParityHelper.ts`](../../packages/app/__tests__/specNativeParityHelper.ts) — parses TS spec interfaces, Android generated `*Spec.java` `@ReactMethod` names, and iOS generated `@protocol NativeRNFBTurbo*Spec` method names. - -3. **Codegen-up-to-date CI** — **Accepted.** Root `yarn codegen:verify` runs [`scripts/codegen-verify.mjs`](../../scripts/codegen-verify.mjs) (wipe-then-regen via [`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) `--all`, including the test-app `testing` entry) then `git diff --exit-code` on the **library generated trees** ([NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted)). Test-app output is not committed and is not part of that diff. Wired in the CI lint job ([`.github/workflows/linting.yml`](../../.github/workflows/linting.yml)). - - - -### NewArch-AD-17.3 — Codegen verify CI — **Accepted** - -**Command:** `yarn codegen:verify` - -**When required:** any change to `packages/*/specs/**` or Codegen/RN version bumps that could regenerate native artifacts — run before closing `implementation_gate` or `review_gate`. - -**Git check:** library generated trees only — [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted) (globs owned there; do not restate). - -**Wipe-then-regen:** [`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) (invoked by package `android:codegen` / `ios:codegen` and by [`scripts/codegen-verify.mjs`](../../scripts/codegen-verify.mjs)) must **delete each package's configured `--outputPath`** before CLI codegen writes ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)). ResultT inject is retired on the current mobile pin ([NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete) superseded). - -**Why:** The current Jest mocks are plain enumerable objects and structurally cannot reproduce the enumeration bug that already cost an iteration; these tests close that blind spot and make iterations faster and higher quality. - -**Determinism requirement:** `codegen:verify` is only meaningful if `yarn codegen` is reproducible. It resolves the RN/Codegen toolchain at run time, so the toolchain **must** be pinned to the app's RN line ([NewArch-AD-20](#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted)); otherwise a host/CI with a drifted `@react-native/codegen` or `react-native` emits spurious drift (0.82/0.80 macros, podspec path changes) or masks real drift. - ---- - -## NewArch-AD-18 — Raw vs wrapped resolver policy — **Accepted** - -Two resolution surfaces exist and must be used deliberately: - -- **Wrapped** (`getNativeModule(module)` / `getAppModule()` → the [NewArch-AD-14](#newarch-ad-14--native-module-wrapper-memoizing-lazy-proxy--accepted) Proxy): the **default** for all product calls. Gives arg-prepend, error mapping, iOS null-encoding. -- **Raw** (`getReactNativeModule(name)`): the **bare** native object from the unified resolver — no wrapping. - -**Default rule:** new product code uses the **wrapped** surface. Raw access is allowed **only** when listed in the canonical exception table below (or after a gap-analysis finds a new legitimate case, documents it here, and adds an in-code rationale comment). Raw callers must use the **turbo** module name ([NewArch-AD-2](#newarch-ad-2--naming-nativernfbturbo--accepted)). Raw callers do **not** get error mapping — they must handle native errors themselves. - -**Gap-analysis gate (every package):** as part of spec authoring, `grep` the repo for `getReactNativeModule(` in product code. For each hit: (1) is it already in the table below? (2) if not, is it a bug (legacy module name, should be wrapped)? (3) if genuinely new, add a row here with policy rationale **before** landing the PR. - -### Canonical exception table - -| # | Call site | Module name | Category | Why raw (policy) | Action | -|---|-----------|---------------|----------|------------------|--------| -| E1 | [`RNFBNativeEventEmitter.ts`](../../packages/app/lib/internal/RNFBNativeEventEmitter.ts) (constructor, `addListener`, `removeAllListeners`, `removeSubscription`) | `NativeRNFBTurboApp` | **Permanent** | React Native's `NativeEventEmitter` must receive the **same raw host object** that implements `addListener` / `removeListeners` on the native side. Wrapping would break event subscription identity and the RN event-bridge contract. A typed Codegen event path is a future cutover, not a reason to wrap this site. | Keep raw; turbo name. | -| E2 | [`nativeModule.ts`](../../packages/app/lib/internal/registry/nativeModule.ts) `initialiseNativeModule` / `getAppModule` bootstrap | any | **Infrastructure** | The wrapper factory itself must read the bare host to build the [NewArch-AD-14](#newarch-ad-14--native-module-wrapper-memoizing-lazy-proxy--accepted) Proxy/composite. Not a product bypass. | N/A | -| E3 | [`nativeModuleAndroidIos.ts`](../../packages/app/lib/internal/nativeModuleAndroidIos.ts) unified resolver | any | **Infrastructure** | Defines `getReactNativeModule`; applies `withTurboConstants` before returning. Not a product bypass. | N/A | -| E4 | [`tests/globals.js`](../../tests/globals.js) `NativeModules` proxy getter | `RNF*` / `NativeRNFBTurbo*` | **Infrastructure** | E2e harness routes RNFB module names through the real unified resolver so specs that read `NativeModules.NativeRNFBTurboApp` (e.g. [`events.e2e.js`](../../packages/app/e2e/events.e2e.js)) get a live module, not a stub. Durable product wiring — not harness narrowing. | Keep; part of Phase 0. | -| E5 | [`UtilsStatics.ts`](../../packages/app/lib/utils/UtilsStatics.ts) `FilePath` getter | `NativeRNFBTurboUtils` | **Phase 0 fix** | Reads path **constants** synchronously from the utils host without a `FirebaseModule` instance (static getter on `Utils.Statics`). Raw was acceptable pre-turbo; under [NewArch-AD-15](#newarch-ad-15--constant-memoization-scope-static-only--accepted) migrate to a dedicated wrapped utils accessor (or memoized static read via resolver) so constants are not rebuilt per access. Turbo name is already correct. | Fix in Phase 0 re-implementation. | -| E6 | [`messaging/lib/index.ts`](../../packages/messaging/lib/index.ts) `isSupported()` | ~~`RNFBUtilsModule`~~ → `NativeRNFBTurboUtils` | **Phase 0 fix (bug)** | Cross-package read of Play Services availability. Was using **legacy module name** (returns `undefined` under turbo-only) and a **dynamic constant** (`androidPlayServices`) that can go stale. Must use turbo name + **dynamic method** `androidGetPlayServicesStatus()` per [NewArch-AD-15](#newarch-ad-15--constant-memoization-scope-static-only--accepted). | **Must-fix** in Phase 0. | -| E7 | [`app/lib/modular.ts`](../../packages/app/lib/modular.ts) `metaGetAll`, `jsonGetAll`, `preferences*` | `NativeRNFBTurboApp` | **Not an exception — migrate** | No policy reason for raw; these are app-module method calls with no arg-prepend skip. Should use **`getAppModule()`** (wrapped) for error mapping consistency. Listed here so gap-analysis catches them. | Migrate to `getAppModule()` in Phase 0. | -| E8 | [`FirestoreStatics.ts`](../../packages/firestore/lib/FirestoreStatics.ts) `setLogLevel` | `NativeRNFBTurboFirestore` | **Phase 1 fix** | Cross-package static helper bypasses `FirebaseModule`/`getNativeModule`. Uses turbo main host via [`getStaticFirestoreMainModule()`](../../packages/firestore/lib/internal/staticNativeModule.ts) (NewArch-AD-18 E8). Raw access retained — no wrapped surface for static helpers. | Done — firestore Phase 1. | -| E9 | [`DatabaseSyncTree.ts`](../../packages/database/lib/DatabaseSyncTree.ts) `native` getter | `RNFBDatabaseQueryModule` | **Deferred — Phase 4** | Internal sync listener tree calls query module directly for low-latency sync ops, bypassing the merged multi-module surface. Acceptable until database migrates; then turbo name + evaluate whether wrapped merge surface suffices. | Fix when `database` migrates. | -| E10 | [`phone-number-verification/lib/index.ts`](../../packages/phone-number-verification/lib/index.ts) `getNativeModule()` | `RNFBPnvModule` / `NativeRNFBTurboPnv` | **Permanent (direct resolver)** | Package bypasses `createModuleNamespace` by design. Direct resolver is intentional; use the turbo name. | Keep direct; turbo name. | - -**Adding a new exception:** gap-analysis must justify why wrapping breaks (not merely "it's convenient"). Update this table and add a one-line `// NewArch-AD-18 E: ` comment at the call site. - ---- - -## NewArch-AD-19 — TurboModule `methodQueue` policy — **Accepted** - -Default: **do not override `methodQueue`.** Remove legacy `- (dispatch_queue_t)methodQueue { return dispatch_get_main_queue(); }` overrides (present on `RNFBAppModule` and `RNFBUtilsModule`) unless a specific method genuinely needs the main thread — in which case dispatch *that method's* main-thread work explicitly (the `RCTUnsafeExecuteOnMainQueueSync` pattern already used in `initializeApp`), rather than forcing the whole module onto main. - -**Why:** A module-wide `methodQueue = main_queue` couples every async method to the main thread (jank/contention) and is inconsistent with [NewArch-AD-9](#newarch-ad-9--requiresmainqueuesetup-returns-no--accepted) (`requiresMainQueueSetup = NO`). **Caveat (unverified):** how TurboModule JSI honors `methodQueue` for sync vs async methods is not documented; treat removal as a native change to validate on-device during Phase 0 re-implementation, not a blind delete. Keep explicit main dispatch only where UI (e.g. Play Services resolution dialogs) requires it. - ---- - -## NewArch-AD-20 — Pin the RN/Codegen toolchain; RN bumps are coordinated breaking changes — **Accepted** - -Committed generated native artifacts ([NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted)) are **RN-version-specific templates**: CMake `target_compile_options` vs `target_compile_reactnative_options`, podspec `RCT_SCRIPT_RN_DIR` paths / `add_rncore_dependency`, and JSI/spec signatures all change across RN releases. `yarn codegen` stamps whatever `@react-native/codegen` + `react-native` the toolchain resolves **at run time**. If that diverges from the test app's RN, codegen emits artifacts that mismatch the app → the native build breaks and [`codegen:verify`](#newarch-ad-173--codegen-verify-ci--accepted) becomes environment-nondeterministic. - -**This happened:** root `"@react-native-community/cli": "latest"` hoisted `@react-native/codegen@0.82` (and pulled `react-native@0.82`), while `packages/functions` carried a stray `"react-native": "^0.80.1"` devDep — together producing spurious 0.82/0.80 drift (CMake macro flip, functions podspec path/`add_rncore_dependency` changes) that would break the RN 0.78 build if committed. - -**Decision:** - -- Pin the RN/Codegen toolchain to the **mobile test app** (`tests/`) RN line via that workspace's dependencies — `react-native`, `@react-native/codegen`, and `@react-native-community/cli` fixed to the same line (no floating `latest` / `*` / stray package `react-native` devDeps). Do **not** use blanket root `resolutions` for those packages: the macOS e2e app (`tests-macos/`) may pin a different RN + `react-native-macos` pair. `yarn codegen` / `codegen:verify` must resolve the toolchain from **`tests/`**. Current pin values and the dual-app model live in [test app dependency pins](../testing/test-app-dependency-pins.md) — do not restate version numbers here. -- **No floating specifiers** (`latest`, `*`, `^0.80`, …) for the RN toolchain in any workspace `package.json`. Individual packages must **not** declare their own `react-native` devDependency — rely on the hoisted version from the mobile test app (as `app-check` / `storage` do). -- Treat a React Native upgrade of the **mobile** app as **one coordinated breaking change**: bump `tests/` RN **and** regenerate all `generated/**`, rebuild native on iOS + Android, and re-run `codegen:verify` — in a single change. Bumping `tests-macos/` follows `react-native-macos` compatibility and does not by itself require codegen regen. See the **Updating React Native** checklist in [CONTRIBUTING.md](../../CONTRIBUTING.md) and [test app dependency pins § When pins may move](../testing/test-app-dependency-pins.md#when-pins-may-move). - -**Why:** makes generated output reproducible everywhere (local + CI), prevents silent native-build breaks, and makes the RN coupling explicit and auditable. - ---- - -## NewArch-AD-21 — Interim iOS `ResultT` alias without full codegen regen — **Superseded (exit complete)** - -**Context (historical):** Consumer apps on RN **0.84+** require `using ResultT = Constants;` inside each codegen `Constants::Builder` ([RN #54919](https://github.com/facebook/react-native/pull/54919)). While the mobile test app was pinned to **0.78**, committed iOS headers omitted the alias, so an interim inject script patched headers after each 0.78 codegen pass. - -**Exit (CPRN-236 / NewArch-AD-20 mobile bump):** The mobile app is on **RN 0.86.2**. Upstream `@react-native/codegen@0.86.2` emits `using ResultT = …` natively. The inject script (`scripts/patch-ios-codegen-resultt.mjs`) and its `codegen:verify` hook are **removed**. Regenerate with `yarn codegen:all` ([`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) from `tests/`). - -**Do not reintroduce** the inject on the current mobile pin. macOS remains on 0.78 for the shell only and does not own codegen artifacts. - ---- - -## NewArch-AD-22 — Codegen is wipe-then-regen on the configured outputPath — **Accepted** - -**Decision:** Before every Codegen write to a package's configured `--outputPath`, **delete that directory entirely**, then run CLI codegen. Applies to: - -- [`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) (mobile toolchain from `tests/`; used by each package's `android:codegen` / `ios:codegen` and by [`scripts/codegen-verify.mjs`](../../scripts/codegen-verify.mjs)) - -ResultT inject ([NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete)) is **retired** on the current mobile pin (0.86 emits `ResultT` natively). Do not reintroduce `patch-ios-codegen-resultt.mjs` after wipe+regen. - -**Why:** React Native Codegen does not reliably remove obsolete generated files when specs, `codegenConfig.name`, or templates change. Incremental overwrite leaves orphan classes / wrong library trees under the same `outputPath`, which break Android (`duplicate class`) or leave stale committed artifacts that [NewArch-AD-17.3](#newarch-ad-173--codegen-verify-ci--accepted) would not catch without a wipe. Wipe-then-regen makes the committed tree match a clean emit ([NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted)). - -**Scope / limits:** - -- Wipe targets **only** the configured `--outputPath` (e.g. `android/.../generated`, `ios/generated`). Hand-written sources outside that path (e.g. `RCTConvert+FIROptions`) are untouched. -- **Test app (`--source app`):** CLI `--outputPath` is the RN app *base* (`tests/ios` / `tests/`), not the artifact dir. RN appends `build/generated/ios` and `android/app/build/generated/source/codegen` — those derived dirs are `OUTPUT_PATHS.testing` and **are** the wipe targets. Also wipe/gitignore dumps at the iOS project base (`Package.swift`, `ReactCodegen/`, `ReactAppDependencyProvider/`) — [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted). Do not wipe the whole `tests/ios/` tree. -- Wipe removes orphans **on the same path**. A **sibling** wrong tree from a prior bad `outputPath` (e.g. `src/main/java/.../generated` vs `src/reactnative/java/.../generated`) still needs a one-time manual delete. Keep **one** canonical tree; align shell imports, `build.gradle` `sourceSets`, and `cmakeListsPath`. -- After a `codegenConfig.name` rename ([NewArch-AD-7](#newarch-ad-7--codegenconfigname--aggregate-library-name-one-codegenconfig-per-package--accepted)), wipe clears the old library under `outputPath`; update `cmakeListsPath` / imports only when those paths embed the old name. - -**Related:** [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted), [NewArch-AD-7](#newarch-ad-7--codegenconfigname--aggregate-library-name-one-codegenconfig-per-package--accepted), [NewArch-AD-17.3](#newarch-ad-173--codegen-verify-ci--accepted), [NewArch-AD-20](#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted), [NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete). - ---- - -## NewArch-AD-23 — Stock upstream TurboModules; no alternate native framework — **Accepted** - -**Decision:** New Architecture support stays on canonical upstream React Native TurboModules (Codegen specs, generated artifacts, Kotlin/Java spec implementations, and the thin Objective-C++ `getTurboModule:` adapter). Swift and Kotlin are implementation languages behind that contract. They are not a reason to change the module framework. - -**Alternatives considered and rejected:** - -- Expo Modules API. Swift/Kotlin-first, but adds the `expo` dependency. That dependency is outside the external list RNFB already ships. -- Nitro. Direct Swift↔C++ without an Objective-C++ adapter, but it is a third-party module ABI, also outside that list. - -**Why:** `react-native` is already an unavoidable dependency. A second module framework is not. The language migration (Swift business logic, Kotlin spec implementations, Swift/Kotlin tests) does not change this. - -**Not this decision:** - -- NewArch-AD-1 rejects a dual old/new bridge. It does not choose among TurboModules, Expo Modules, and Nitro. -- NewArch-AD-12 governs the original TurboModule cutover commit (`feat()!: migrate to TurboModules`). Later language-port slices are separate commits and do not re-open NewArch-AD-12. - ---- - -## NewArch-AD-24 — JNI deprecation CMake patch until min RN ≥ 0.89 — **Accepted** - -**Context:** React Native **0.89+** deprecates the `JavaTurboModule::invokeJavaMethod` overload that takes a cached `jmethodID` ([facebook/react-native#59619](https://github.com/facebook/react-native/pull/59619)). RNFB still commits library JNI under each package's `generated/jni/` for TurboModules ([NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted)). Stock codegen continues to emit the legacy call shape so builds keep working on React Native versions **before** 0.89. On 0.89+, `target_compile_reactnative_options` turns deprecation warnings into errors (`-Werror`), breaking all library codegen CMake targets. - -**Decision:** After each successful **library** Android wipe-then-regen ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)), [`scripts/codegen-package.mjs`](../../scripts/codegen-package.mjs) post-processes `jni/CMakeLists.txt` to append `target_compile_options( PRIVATE -Wno-error=deprecated-declarations)` with a stable `# RNFB:` marker comment. Scope: **16** library packages (not `testing` app codegen). Idempotent on re-run. - -**Why not regenerate call sites now:** The replacement `invokeJavaMethod` overload exists only from RN **0.89**; rewriting committed `.cpp` output would break the documented compatibility window for older React Native lines still supported alongside the mobile test app pin. - -**Exit criterion:** When RNFB's minimum supported React Native is **≥ 0.89**, run `yarn codegen:all` with a 0.89+ toolchain so upstream templates emit the new overload, commit regenerated JNI, and **remove** this CMake post-process (delete `patchAndroidJniDeprecationCMake` and the marker block from committed `CMakeLists.txt` files). - -**Related:** [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted), [NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted), [agent-command-policy § TurboModule codegen](../testing/commands/native.md#turbomodule-codegen). - ---- +## Decision index + +| ID | Decision | Status | +| --- | --- | --- | +| [NewArch-AD-1](decisions/codegen-and-toolchain.md#newarch-ad-1--new-architecture-only--accepted) | New Architecture only | Accepted | +| [NewArch-AD-2](decisions/codegen-and-toolchain.md#newarch-ad-2--naming-nativernfbturbo--accepted) | Naming: `NativeRNFBTurbo*` | Accepted | +| [NewArch-AD-3](decisions/codegen-and-toolchain.md#newarch-ad-3--strong-codegen-typing--accepted) | Strong Codegen typing | Accepted | +| [NewArch-AD-4](decisions/events-tests-process.md#newarch-ad-4--events-deferred-to-phase-c--accepted) | Events deferred to Phase C | Accepted | +| [NewArch-AD-5](decisions/codegen-and-toolchain.md#newarch-ad-5--commit-generated-code--accepted) | Commit generated code | Accepted | +| [NewArch-AD-6](decisions/js-runtime.md#newarch-ad-6--unified-native-module-resolver--accepted) | Unified native module resolver | Accepted | +| [NewArch-AD-7](decisions/codegen-and-toolchain.md#newarch-ad-7--codegenconfigname--aggregate-library-name-one-codegenconfig-per-package--accepted) | `codegenConfig.name` = aggregate library name; one `codegenConfig` per package | Accepted | +| [NewArch-AD-8](decisions/js-runtime.md#newarch-ad-8--turbomodule-js-enumeration-forin--objectcreate--accepted) | TurboModule JS enumeration: `for...in` + `Object.create` | Accepted | +| [NewArch-AD-9](decisions/js-runtime.md#newarch-ad-9--requiresmainqueuesetup-returns-no--accepted) | `requiresMainQueueSetup` returns `NO` | Accepted | +| [NewArch-AD-10](decisions/js-runtime.md#newarch-ad-10--cross-package-native-state-is-centralized-in-app-with-testable-apis--accepted) | Cross-package native state is centralized in `app`, with testable APIs | Accepted | +| [NewArch-AD-11](decisions/js-runtime.md#newarch-ad-11--multi-module-method-names-are-merged-uniqueness-enforced-by-test--accepted) | Multi-module method names are merged; uniqueness enforced by test | Accepted | +| [NewArch-AD-12](decisions/events-tests-process.md#newarch-ad-12--one-commit-per-package--accepted) | One commit per package | Accepted | +| [NewArch-AD-13](decisions/events-tests-process.md#newarch-ad-13--test-harness-committed-defaults--gitignored-local-overrides--accepted) | Test harness: committed defaults + gitignored local overrides | Accepted | +| [NewArch-AD-13a](decisions/events-tests-process.md#newarch-ad-13a--optional-overrides-need-a-resolver-stub-metro-dependency-map-integrity--accepted) | Optional overrides need a resolver stub (Metro dependency-map integrity) | Accepted | +| [NewArch-AD-14](decisions/js-runtime.md#newarch-ad-14--native-module-wrapper-memoizing-lazy-proxy--accepted) | Native-module wrapper: memoizing lazy `Proxy` | Accepted | +| [NewArch-AD-14a](decisions/js-runtime.md#newarch-ad-14a--multi-host-merge-routing-composite-proxy-required-for-multi-module) | Multi-host merge: routing composite Proxy (required for multi-module) | | +| [NewArch-AD-15](decisions/js-runtime.md#newarch-ad-15--constant-memoization-scope-static-only--accepted) | Constant memoization scope: static only | Accepted | +| [NewArch-AD-16](decisions/events-tests-process.md#newarch-ad-16--phase-s-asyncsync-conversion--open) | Phase S (async→sync conversion) | Open | +| [NewArch-AD-17](decisions/events-tests-process.md#newarch-ad-17--spec-contract--parity-tests--accepted) | Spec contract + parity tests | Accepted | +| [NewArch-AD-17.1](decisions/events-tests-process.md#newarch-ad-171--jest-turbomodule-contract-test--accepted) | Jest TurboModule contract test | Accepted | +| [NewArch-AD-17.2](decisions/events-tests-process.md#newarch-ad-172--specnative-parity-test--accepted) | Spec↔native parity test | Accepted | +| [NewArch-AD-17.3](decisions/events-tests-process.md#newarch-ad-173--codegen-verify-ci--accepted) | Codegen verify CI | Accepted | +| [NewArch-AD-18](decisions/js-runtime.md#newarch-ad-18--raw-vs-wrapped-resolver-policy--accepted) | Raw vs wrapped resolver policy | Accepted | +| [NewArch-AD-19](decisions/js-runtime.md#newarch-ad-19--turbomodule-methodqueue-policy--accepted) | TurboModule `methodQueue` policy | Accepted | +| [NewArch-AD-20](decisions/codegen-and-toolchain.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted) | Pin the RN/Codegen toolchain; RN bumps are coordinated breaking changes | Accepted | +| [NewArch-AD-21](decisions/codegen-and-toolchain.md#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete) | Interim iOS `ResultT` alias without full codegen regen | Superseded (exit complete) | +| [NewArch-AD-22](decisions/codegen-and-toolchain.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted) | Codegen is wipe-then-regen on the configured outputPath | Accepted | +| [NewArch-AD-23](decisions/codegen-and-toolchain.md#newarch-ad-23--stock-upstream-turbomodules-no-alternate-native-framework--accepted) | Stock upstream TurboModules; no alternate native framework | Accepted | +| [NewArch-AD-24](decisions/codegen-and-toolchain.md#newarch-ad-24--jni-deprecation-cmake-patch-until-min-rn--089--accepted) | JNI deprecation CMake patch until min RN ≥ 0.89 | Accepted | + +## Files + +Content moved from this file into the files below. Headings and anchors keep their names in the new file; each old anchor sits on the line under its new home, so old `#links` still land here and point on. + +- [NewArch ADRs: Codegen, naming and toolchain](decisions/codegen-and-toolchain.md): NewArch-AD-1, 2, 3, 5, 7, 20 to 24: New Architecture only, naming, typing, committed generated code, codegenConfig, RN/Codegen pins, wipe-then-regen, stock TurboModules, JNI CMake patch. + +- [NewArch ADRs: native module resolver and JS wrapper](decisions/js-runtime.md): NewArch-AD-6, 8 to 11, 14, 15, 18, 19: unified resolver, enumeration, main queue setup, centralized native state, merged method names, memoizing Proxy, constant scope, raw vs wrapped resolver, methodQueue. + +- [NewArch ADRs: events, test harness and process](decisions/events-tests-process.md): NewArch-AD-4, 12, 13, 16, 17: events deferred to Phase C, one commit per package, harness defaults and local overrides, Phase S, spec contract and parity tests. + ## Related docs diff --git a/okf-bundle/new-architecture/decisions/codegen-and-toolchain.md b/okf-bundle/new-architecture/decisions/codegen-and-toolchain.md new file mode 100644 index 0000000000..6710d5779d --- /dev/null +++ b/okf-bundle/new-architecture/decisions/codegen-and-toolchain.md @@ -0,0 +1,142 @@ +--- +type: Reference +title: 'NewArch ADRs: Codegen, naming and toolchain' +description: 'NewArch-AD-1, 2, 3, 5, 7, 20 to 24: New Architecture only, naming, typing, committed generated code, codegenConfig, RN/Codegen pins, wipe-then-regen, stock TurboModules, JNI CMake patch.' +tags: [new-architecture, turbomodule, codegen, adr] +timestamp: 2026-12-04T00:00:00Z +--- + +# NewArch ADRs: Codegen, naming and toolchain + +Part of [New Architecture decisions (ADR)](../architecture-decisions.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## NewArch-AD-1 — New Architecture only — **Accepted** + +One coordinated semver major across the monorepo. No dual old/new bridge per package (`functions` precedent: v24). The legacy bridge interop layer remains available to consumers via RN itself, but RNFB ships TurboModule-only. + +**Why:** A per-package dual-bridge would multiply native surface and testing. A single coordinated break is cheaper to build and reason about. + +--- + +## NewArch-AD-2 — Naming: `NativeRNFBTurbo*` — **Accepted** + +Codegen spec/module names use the `NativeRNFBTurbo*` prefix (`NativeRNFBTurboAuth`, `NativeRNFBTurboFirestore`, …). Spec files must be prefixed `Native` per RN Codegen. + +**Why:** Disambiguates from legacy `RNFB*` module names during transition; satisfies Codegen's `Native*` spec-file requirement. + +**Web / macOS registration:** [`nativeModuleWeb.ts`](../../../packages/app/lib/internal/nativeModuleWeb.ts) registers JS-SDK shims by module name in the **registry object initializer** (not deferred to bottom-of-file calls) so `NativeRNFBTurbo*` keys exist before `RNFBNativeEventEmitter` instantiates during circular imports. When `APP_NATIVE_MODULE` changes, register **both** the legacy `RNFBAppModule` key and the turbo name. Missing that registration surfaces as a macOS blank window / `Native module NativeRNFBTurboApp is not registered`. + +--- + +## NewArch-AD-3 — Strong Codegen typing — **Accepted** + +Strong Codegen types wherever the API allows. Source of truth: `packages/*/lib/types/internal.ts`, native method inventories, firebase-js-sdk shapes. Use `Object` / open maps only where payloads are genuinely dynamic. + +**Codegen-safe naming:** Spec methods and generated symbols must avoid language keywords or reserved identifiers across TypeScript, C++, Java, and ObjC++ targets. Known blockers: `delete` as a method name breaks generated native code; TypeScript primitive `object` is rejected by RN Codegen for NativeModule specs (`TSObjectKeyword`) — use a shaped type, Codegen `Object` for truly dynamic maps, or a named interface. Also avoid generated-target reserved words (`class`, `default`, `new`, `switch`, `case`, `try`, `catch`, `return`, `void`, `static`, `public`, `private`, `protected`, `namespace`, `operator`, `template`, `this`, `self`). If a legacy method already uses a reserved word, rename the spec method and keep the public JS API stable via the wrapper. + +--- + + + +## NewArch-AD-5 — Commit generated code — **Accepted** + +**Library packages only:** `includesGeneratedCode: true`; commit Codegen output under `packages/*/android/.../generated` and `packages/*/ios/generated`, mirroring `packages/functions`. CLI `--source library`. + +**Test app is not that contract.** `tests/package.json` must **not** set `includesGeneratedCode: true` — that makes CLI `--outputPath` the *final* dir and writes `tests/ios/ReactCodegen` / `tests/ios/Package.swift` while CocoaPods wants `tests/ios/build/generated/ios/ReactCodegen`. Test-app Codegen output is **build-time, not committed**. [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) `testing` entry: `--source app`; CLI `--outputPath` is the RN app *base* (`ios` / `.`) because app codegen appends `build/generated/ios` and `android/app/build/generated/source/codegen`. Wipe those derived dirs **and** scrub/gitignore dumps at `tests/ios/Package.swift`, `tests/ios/ReactCodegen/`, `tests/ios/ReactAppDependencyProvider/`. Do not flatten test-app iOS output (keep nested `ReactCodegen`). Skip `scrubAppOnlyIosArtifacts`. That entry does **not** change library codegen. + +**Guard (NewArch-AD-17.3):** CI runs `yarn codegen:verify` — wipe-then-regen ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)) then `git diff --exit-code` on the **library generated trees named above**. Test-app generated trees are not in that check. + +--- + +## NewArch-AD-7 — `codegenConfig.name` = aggregate library name; one `codegenConfig` per package — **Accepted** + +Each package has **one** `codegenConfig` whose `name` is an **aggregate library name** of the form `RNFBTurboModules` (e.g. `RNFBAppTurboModules`, `RNFBFunctionsTurboModules`, `RNFBFirestoreTurboModules`), **not** a module name. Multiple TurboModules in a package are listed under iOS `modulesProvider` (spec name → ObjC class) and live in the `specs/` dir; Android registers each shell in the package class. **One rule for every package**, single- and multi-spec alike — no degenerate exceptions. + +**Why:** Multi-module packages (database ×5, firestore ×4) cannot name the library after one module, so the aggregate-library shape is mandatory for them; applying it everywhere gives a single rule reviewers can apply without thinking about spec count. The aggregate-library shape is the one RN documents and the one that generalizes. + +**`functions` correction (one-time):** `functions` shipped with `codegenConfig.name: "NativeRNFBTurboFunctions"` (the *module* name). Rename to `RNFBFunctionsTurboModules` for consistency. **Downside: effectively none.** `codegenConfig.name` is the *generated-library* identifier (drives generated file/JNI/CMake target names) — it is **internal**, not a public/consumer symbol, and is **distinct from the module name** `NativeRNFBTurboFunctions` (the `RCT_EXPORT_MODULE` / `TurboModuleRegistry.get('NativeRNFBTurboFunctions')` key), which **stays unchanged**. The rename is mechanical: change `name`, re-run `yarn codegen` ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted) wipe-then-regen removes the old library tree under the configured `outputPath`), and update `react-native.config.js` `cmakeListsPath` / shell imports **only if** those paths embed the old library name, then commit. Only risk is a build-wiring reference to the old library name outside the wiped tree; a clean codegen + build catches it. Track as a small standalone follow-up (low risk, no consumer impact). + +**Gate:** every spec name appears as a `modulesProvider` key (iOS) and is registered in the package class (Android); `codegenConfig.name` matches `RNFBTurboModules`. + +Reference: [`packages/app/package.json`](../../../packages/app/package.json) `codegenConfig`. + +--- + +## NewArch-AD-20 — Pin the RN/Codegen toolchain; RN bumps are coordinated breaking changes — **Accepted** + +Committed generated native artifacts ([NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted)) are **RN-version-specific templates**: CMake `target_compile_options` vs `target_compile_reactnative_options`, podspec `RCT_SCRIPT_RN_DIR` paths / `add_rncore_dependency`, and JSI/spec signatures all change across RN releases. `yarn codegen` stamps whatever `@react-native/codegen` + `react-native` the toolchain resolves **at run time**. If that diverges from the test app's RN, codegen emits artifacts that mismatch the app → the native build breaks and [`codegen:verify`](events-tests-process.md#newarch-ad-173--codegen-verify-ci--accepted) becomes environment-nondeterministic. + +**This happened:** root `"@react-native-community/cli": "latest"` hoisted `@react-native/codegen@0.82` (and pulled `react-native@0.82`), while `packages/functions` carried a stray `"react-native": "^0.80.1"` devDep — together producing spurious 0.82/0.80 drift (CMake macro flip, functions podspec path/`add_rncore_dependency` changes) that would break the RN 0.78 build if committed. + +**Decision:** + +- Pin the RN/Codegen toolchain to the **mobile test app** (`tests/`) RN line via that workspace's dependencies — `react-native`, `@react-native/codegen`, and `@react-native-community/cli` fixed to the same line (no floating `latest` / `*` / stray package `react-native` devDeps). Do **not** use blanket root `resolutions` for those packages: the macOS e2e app (`tests-macos/`) may pin a different RN + `react-native-macos` pair. `yarn codegen` / `codegen:verify` must resolve the toolchain from **`tests/`**. Current pin values and the dual-app model live in [test app dependency pins](../../testing/test-app-dependency-pins.md) — do not restate version numbers here. +- **No floating specifiers** (`latest`, `*`, `^0.80`, …) for the RN toolchain in any workspace `package.json`. Individual packages must **not** declare their own `react-native` devDependency — rely on the hoisted version from the mobile test app (as `app-check` / `storage` do). +- Treat a React Native upgrade of the **mobile** app as **one coordinated breaking change**: bump `tests/` RN **and** regenerate all `generated/**`, rebuild native on iOS + Android, and re-run `codegen:verify` — in a single change. Bumping `tests-macos/` follows `react-native-macos` compatibility and does not by itself require codegen regen. See the **Updating React Native** checklist in [CONTRIBUTING.md](../../../CONTRIBUTING.md) and [test app dependency pins § When pins may move](../../testing/test-app-dependency-pins.md#when-pins-may-move). + +**Why:** makes generated output reproducible everywhere (local + CI), prevents silent native-build breaks, and makes the RN coupling explicit and auditable. + +--- + +## NewArch-AD-21 — Interim iOS `ResultT` alias without full codegen regen — **Superseded (exit complete)** + +**Context (historical):** Consumer apps on RN **0.84+** require `using ResultT = Constants;` inside each codegen `Constants::Builder` ([RN #54919](https://github.com/facebook/react-native/pull/54919)). While the mobile test app was pinned to **0.78**, committed iOS headers omitted the alias, so an interim inject script patched headers after each 0.78 codegen pass. + +**Exit (NewArch-AD-20 mobile bump):** The mobile app is on **RN 0.86.2**. Upstream `@react-native/codegen@0.86.2` emits `using ResultT = …` natively. The inject script (`scripts/patch-ios-codegen-resultt.mjs`) and its `codegen:verify` hook are **removed**. Regenerate with `yarn codegen:all` ([`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) from `tests/`). + +**Do not reintroduce** the inject on the current mobile pin. macOS remains on 0.78 for the shell only and does not own codegen artifacts. + +--- + +## NewArch-AD-22 — Codegen is wipe-then-regen on the configured outputPath — **Accepted** + +**Decision:** Before every Codegen write to a package's configured `--outputPath`, **delete that directory entirely**, then run CLI codegen. Applies to: + +- [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) (mobile toolchain from `tests/`; used by each package's `android:codegen` / `ios:codegen` and by [`scripts/codegen-verify.mjs`](../../../scripts/codegen-verify.mjs)) + +ResultT inject ([NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete)) is **retired** on the current mobile pin (0.86 emits `ResultT` natively). Do not reintroduce `patch-ios-codegen-resultt.mjs` after wipe+regen. + +**Why:** React Native Codegen does not reliably remove obsolete generated files when specs, `codegenConfig.name`, or templates change. Incremental overwrite leaves orphan classes / wrong library trees under the same `outputPath`, which break Android (`duplicate class`) or leave stale committed artifacts that [NewArch-AD-17.3](events-tests-process.md#newarch-ad-173--codegen-verify-ci--accepted) would not catch without a wipe. Wipe-then-regen makes the committed tree match a clean emit ([NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted)). + +**Scope / limits:** + +- Wipe targets **only** the configured `--outputPath` (e.g. `android/.../generated`, `ios/generated`). Hand-written sources outside that path (e.g. `RCTConvert+FIROptions`) are untouched. +- **Test app (`--source app`):** CLI `--outputPath` is the RN app *base* (`tests/ios` / `tests/`), not the artifact dir. RN appends `build/generated/ios` and `android/app/build/generated/source/codegen` — those derived dirs are `OUTPUT_PATHS.testing` and **are** the wipe targets. Also wipe/gitignore dumps at the iOS project base (`Package.swift`, `ReactCodegen/`, `ReactAppDependencyProvider/`) — [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted). Do not wipe the whole `tests/ios/` tree. +- Wipe removes orphans **on the same path**. A **sibling** wrong tree from a prior bad `outputPath` (e.g. `src/main/java/.../generated` vs `src/reactnative/java/.../generated`) still needs a one-time manual delete. Keep **one** canonical tree; align shell imports, `build.gradle` `sourceSets`, and `cmakeListsPath`. +- After a `codegenConfig.name` rename ([NewArch-AD-7](#newarch-ad-7--codegenconfigname--aggregate-library-name-one-codegenconfig-per-package--accepted)), wipe clears the old library under `outputPath`; update `cmakeListsPath` / imports only when those paths embed the old name. + +**Related:** [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted), [NewArch-AD-7](#newarch-ad-7--codegenconfigname--aggregate-library-name-one-codegenconfig-per-package--accepted), [NewArch-AD-17.3](events-tests-process.md#newarch-ad-173--codegen-verify-ci--accepted), [NewArch-AD-20](#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted), [NewArch-AD-21](#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete). + +--- + +## NewArch-AD-23 — Stock upstream TurboModules; no alternate native framework — **Accepted** + +**Decision:** New Architecture support stays on canonical upstream React Native TurboModules (Codegen specs, generated artifacts, Kotlin/Java spec implementations, and the thin Objective-C++ `getTurboModule:` adapter). Swift and Kotlin are implementation languages behind that contract. They are not a reason to change the module framework. + +**Alternatives considered and rejected:** + +- Expo Modules API. Swift/Kotlin-first, but adds the `expo` dependency. That dependency is outside the external list RNFB already ships. +- Nitro. Direct Swift↔C++ without an Objective-C++ adapter, but it is a third-party module ABI, also outside that list. + +**Why:** `react-native` is already an unavoidable dependency. A second module framework is not. The language migration (Swift business logic, Kotlin spec implementations, Swift/Kotlin tests) does not change this. + +**Not this decision:** + +- NewArch-AD-1 rejects a dual old/new bridge. It does not choose among TurboModules, Expo Modules, and Nitro. +- NewArch-AD-12 governs the original TurboModule cutover commit (`feat()!: migrate to TurboModules`). Later language-port slices are separate commits and do not re-open NewArch-AD-12. + +--- + +## NewArch-AD-24 — JNI deprecation CMake patch until min RN ≥ 0.89 — **Accepted** + +**Context:** React Native **0.89+** deprecates the `JavaTurboModule::invokeJavaMethod` overload that takes a cached `jmethodID` ([facebook/react-native#59619](https://github.com/facebook/react-native/pull/59619)). RNFB still commits library JNI under each package's `generated/jni/` for TurboModules ([NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted)). Stock codegen continues to emit the legacy call shape so builds keep working on React Native versions **before** 0.89. On 0.89+, `target_compile_reactnative_options` turns deprecation warnings into errors (`-Werror`), breaking all library codegen CMake targets. + +**Decision:** After each successful **library** Android wipe-then-regen ([NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)), [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) post-processes `jni/CMakeLists.txt` to append `target_compile_options( PRIVATE -Wno-error=deprecated-declarations)` with a stable `# RNFB:` marker comment. Scope: **16** library packages (not `testing` app codegen). Idempotent on re-run. + +**Why not regenerate call sites now:** The replacement `invokeJavaMethod` overload exists only from RN **0.89**; rewriting committed `.cpp` output would break the documented compatibility window for older React Native lines still supported alongside the mobile test app pin. + +**Exit criterion:** When RNFB's minimum supported React Native is **≥ 0.89**, run `yarn codegen:all` with a 0.89+ toolchain so upstream templates emit the new overload, commit regenerated JNI, and **remove** this CMake post-process (delete `patchAndroidJniDeprecationCMake` and the marker block from committed `CMakeLists.txt` files). + +**Related:** [NewArch-AD-5](#newarch-ad-5--commit-generated-code--accepted), [NewArch-AD-22](#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted), [agent-command-policy § TurboModule codegen](../../testing/commands/native.md#turbomodule-codegen). + +--- diff --git a/okf-bundle/new-architecture/decisions/events-tests-process.md b/okf-bundle/new-architecture/decisions/events-tests-process.md new file mode 100644 index 0000000000..951b58e973 --- /dev/null +++ b/okf-bundle/new-architecture/decisions/events-tests-process.md @@ -0,0 +1,142 @@ +--- +type: Reference +title: 'NewArch ADRs: events, test harness and process' +description: 'NewArch-AD-4, 12, 13, 16, 17: events deferred to Phase C, one commit per package, harness defaults and local overrides, Phase S, spec contract and parity tests.' +tags: [new-architecture, turbomodule, testing, adr] +timestamp: 2026-12-04T00:00:00Z +--- + +# NewArch ADRs: events, test harness and process + +Part of [New Architecture decisions (ADR)](../architecture-decisions.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## NewArch-AD-4 — Events deferred to Phase C — **Accepted** + +Keep the legacy event path (`RNFBNativeEventEmitter` → app-module proxy → `RNFBRCTEventEmitter` / `ReactNativeFirebaseEventEmitter` → `SharedEventEmitter` fan-out) under TurboModules. Codegen EventEmitter cutover is a **future** change, not part of the method-call shell. + +**Escalation:** if area-focused e2e or device testing shows a package's events cannot work over the legacy proxy under TurboModules, cut that package's event path over in its own change rather than waiting. **Highest risk:** `messaging` (background/iOS AppDelegate, headless JS task). + +### messaging — EventEmitter stays on the legacy proxy + +**Decision:** `messaging` ships the **method-call TurboModule shell** only. Event emit/subscribe stays on the legacy proxy until a future Codegen EventEmitter cutover. + +| Assertion | Primary source | +|-----------|----------------| +| Native emit sites do not use the messaging module bridge | iOS categories/delegates (`RNFBMessaging+AppDelegate.m`, `+UNUserNotificationCenter.m`, `+FIRMessagingDelegate.m`) call `RNFBRCTEventEmitter`; Android receiver/service/module call `ReactNativeFirebaseEventEmitter` | +| JS subscribes via the app-module proxy, not the messaging shell | `packages/messaging/lib/index.ts` — `nativeEvents` array → `RNFBNativeEventEmitter` → `NativeRNFBTurboApp` ([NewArch-AD-18 E1](js-runtime.md#newarch-ad-18--raw-vs-wrapped-resolver-policy--accepted)) | +| Android background (quit/killed) is outside the event-proxy path | `ReactNativeFirebaseMessagingHeadlessService` (`HeadlessJsTaskService`); `AppRegistry.registerHeadlessTask('ReactNativeFirebaseMessagingHeadlessTask', …)` in `packages/messaging/lib/index.ts` | +| iOS background data messages couple shell method + event proxy | `RNFBMessaging+AppDelegate.m` — `signalBackgroundMessageHandlerSet` on shell, then `RNFBRCTEventEmitter` for `messaging_message_received_background` | +| iOS emitter implementation is legacy bridge API (Phase C debt) | `packages/app/ios/RNFBApp/RNFBRCTEventEmitter.m` — `bridge enqueueJSCall:@"RCTDeviceEventEmitter"` | + +The deferral discriminator is **not** satisfied by structure alone: nothing in the messaging native tree requires EventEmitter cutover when the shell becomes a TurboModule. + +**Testing:** Messaging is the highest-risk legacy-proxy package. Area-focused e2e must cover **event delivery**, not only turbo method calls — foreground message receipt, token refresh, notification-opened, and (on iOS) background handler timing against `signalBackgroundMessageHandlerSet`. Device validation is required where the harness cannot automate FCM delivery or AppDelegate background races. Escalate event cutover **only** if that testing proves the proxy fails. iOS `RCTRootView` / `addCustomPropsToUserProps` headless wiring is a separate shell implementation concern, not an event-path escalation trigger. + +--- + +## NewArch-AD-12 — One commit per package — **Accepted** + +Convert a whole package (all its legacy modules → all its specs) in one [change authoring](../../testing/authoring/loop.md#primary-loop) loop (`documentation?` before frozen `independent-review`); land it as one `feat()!: migrate to TurboModules` (breaking: New Architecture required). Multiple specs ≠ multiple commits — they share `codegenConfig`, generated artifacts, podspec/gradle guards, and JS wiring that only build and pass e2e together. + +--- + +## NewArch-AD-13 — Test harness: committed defaults + gitignored local overrides — **Accepted** + +`tests/globals.js` and `tests/app.js` keep the **committed defaults** (`RNFBDebug = false`, full `platformSupportedModules`, durable product wiring such as the `NativeRNFBTurbo*` resolver routing). Local per-run choices (`RNFBDebug = true`, a focused module list) live in a small **gitignored overrides file** that the harness reads if present. + +**Why:** Durable product wiring (e.g. routing `NativeRNFBTurbo*` through the resolver) currently shares files with ephemeral narrowing, so a `git checkout` revert of narrowing also drops product wiring — this already happened once. It also bites human developers who narrow locally and then lose or accidentally commit it. Separating committed defaults from a gitignored overrides file makes the durable wiring un-revertable and the local narrowing impossible to commit. + +**Mechanism:** + +- Committed **`tests/harness.overrides.example.js`** — the shape demonstrator. Heavily commented for a human or agent: what each field means, valid values, and exactly what to paste to narrow modules / enable `RNFBDebug`. Exports an empty/no-op override so copying it changes nothing until edited. +- Gitignored **`tests/harness.overrides.js`** — the real local file; developers/agents copy the example to this name and edit it. +- `tests/globals.js` / `tests/app.js` read `harness.overrides.js` if present, else fall back to committed defaults. Because `tests/app.js` uses `require.context` (Metro static analysis), the override must express module narrowing as a **filter list the harness applies to the static set**, not a dynamic `require`. + +**Ordering caution (do this in order):** add `tests/harness.overrides.js` to `.gitignore` **first** and verify it is ignored (`git check-ignore`), **then** create the local file — so the real overrides file can never be accidentally tracked. The committed example file (`harness.overrides.example.js`) must **not** be ignored. + +### NewArch-AD-13a — Optional overrides need a resolver stub (Metro dependency-map integrity) — **Accepted** + +The optional `require('./harness.overrides.js')` in `tests/app.js` / `tests/globals.js` sits in a `try/catch`, so Metro treats it as an **optional dependency**. When the gitignored file is **absent** (the default), Metro 0.81.x (RN 0.78) **omits the unresolved optional dependency from the requiring module's serialized dependency-id array** instead of inserting a placeholder. That shifts every later dependency index down by one and drops the module's **final** dependency — surfacing at runtime, during the very first `App()` render, as `Requiring unknown module "undefined"`. It is deterministic and independent of caches, `node_modules`, `lazy` bundling, and RN version; it was masked whenever a developer happened to have a local `harness.overrides.js` present, and it breaks any clean checkout / CI that runs e2e without one. + +**Decision:** `tests/metro.config.js` `resolveRequest` resolves `./harness.overrides.js` to a **committed empty stub** (`tests/harness.overrides.stub.js` → `module.exports = {}`) whenever the local file does not exist; a present local override resolves normally. The dependency then always resolves, so the dependency map stays intact. + +**Why not just commit a real `harness.overrides.js`:** keeping the override gitignored (AD-13) preserves "local narrowing can never be committed"; the resolver stub restores Metro integrity without giving that up. Keep the `try/catch` as defense-in-depth. The stub must never carry overrides. + +--- + +## NewArch-AD-16 — Phase S (async→sync conversion) — **Open** + +Some RNFB methods are `Promise` only because the legacy bridge forced async, while firebase-js-sdk is synchronous. TurboModules support sync JSI methods, so those can return to sync parity. **Discriminator:** keep `Promise` when the native work has real latency (network / disk / keychain / token); convert only pure bridge-forced async. + +**Open question driving the gap-analysis:** the "keep async if it does network/IO/disk" rule assumes firebase-js-sdk's sync methods do **not** do blocking IO for the same functionality. That must be verified per method (does the web SDK do the work in-memory, or defer it?), because if web is genuinely sync-and-non-blocking, RNFB may be able to be sync too. Do not lock the conversion list until that inventory exists. Blocked by NewArch-AD-9 (`requiresMainQueueSetup = NO`) — sync methods require it. + +--- + +## NewArch-AD-17 — Spec contract + parity tests — **Accepted** + +Jest-level tests, reused across packages: + +1. **Resolution/enumeration contract** — **Accepted.** A fixture that models a TurboModule (methods **non-own on the prototype**, constants own; `Object.keys(raw) === []`) and asserts every spec method is callable through the **real wrapper** (`getNativeModule`/`getAppModule`). Catches the NewArch-AD-8 enumeration class — and now the NewArch-AD-14 Proxy behavior — in sub-second Jest instead of 30-minute e2e. Build alongside the Phase 0 re-implementation. **Must include a 2-host merge fixture** (two mock TurboModule hosts, disjoint method sets) that exercises the [NewArch-AD-14a routing composite Proxy](js-runtime.md#newarch-ad-14a--multi-host-merge-routing-composite-proxy-required-for-multi-module) — because Phase 0 (`app`/`utils` resolved as separate single-host surfaces) does not, yet Phase 1 (firestore/database) depends on it. + + + +### NewArch-AD-17.1 — Jest TurboModule contract test — **Accepted** + +**Canonical file:** [`packages/app/__tests__/nativeModuleContract.test.ts`](../../../packages/app/__tests__/nativeModuleContract.test.ts) + +**Describe block (grep anchor):** `TurboModule wrapper contract (NewArch-AD-17.1)` + +**Scoped Jest command:** + +```bash +yarn tests:jest -- packages/app/__tests__/nativeModuleContract.test.ts +``` + +**Full suite** (`yarn tests:jest`) must also stay green — the contract test is part of the global Jest run, not a separate harness. + +**Fixtures required in that file:** + +| Case | Asserts | +|------|---------| +| TurboModule host shape | Methods non-own on prototype; `Object.keys(raw) === []` | +| Single-host wrapper | Every spec method callable via `getNativeModule()` | +| 2-host merge (NewArch-AD-14a) | Routing composite Proxy dispatches to the correct host per method name | + +**When required:** any change to [`nativeModule.ts`](../../../packages/app/lib/internal/registry/nativeModule.ts), `withTurboConstants`, or TurboModule wrapper behavior — re-run the scoped command above before closing `implementation_gate` or `review_gate`. +2. **Spec↔native parity** — **Accepted.** Assert each package's spec method-name set equals the union of Android `@ReactMethod` (generated Java spec) and iOS TurboModule protocol methods (generated ObjC spec header), and (NewArch-AD-11) the union across a package's specs has no duplicate names. + + + +### NewArch-AD-17.2 — Spec↔native parity test — **Accepted** + +**Canonical file:** [`packages/app/__tests__/turboModuleSpecNativeParity.test.ts`](../../../packages/app/__tests__/turboModuleSpecNativeParity.test.ts) + +**Describe block (grep anchor):** `Spec↔native parity (NewArch-AD-17.2)` + +**Scoped Jest command:** + +```bash +yarn tests:jest -- packages/app/__tests__/turboModuleSpecNativeParity.test.ts +``` + +**Helper:** [`specNativeParityHelper.ts`](../../../packages/app/__tests__/specNativeParityHelper.ts) — parses TS spec interfaces, Android generated `*Spec.java` `@ReactMethod` names, and iOS generated `@protocol NativeRNFBTurbo*Spec` method names. + +3. **Codegen-up-to-date CI** — **Accepted.** Root `yarn codegen:verify` runs [`scripts/codegen-verify.mjs`](../../../scripts/codegen-verify.mjs) (wipe-then-regen via [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) `--all`, including the test-app `testing` entry) then `git diff --exit-code` on the **library generated trees** ([NewArch-AD-5](codegen-and-toolchain.md#newarch-ad-5--commit-generated-code--accepted)). Test-app output is not committed and is not part of that diff. Wired in the CI lint job ([`.github/workflows/linting.yml`](../../../.github/workflows/linting.yml)). + + + +### NewArch-AD-17.3 — Codegen verify CI — **Accepted** + +**Command:** `yarn codegen:verify` + +**When required:** any change to `packages/*/specs/**` or Codegen/RN version bumps that could regenerate native artifacts — run before closing `implementation_gate` or `review_gate`. + +**Git check:** library generated trees only — [NewArch-AD-5](codegen-and-toolchain.md#newarch-ad-5--commit-generated-code--accepted) (globs owned there; do not restate). + +**Wipe-then-regen:** [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs) (invoked by package `android:codegen` / `ios:codegen` and by [`scripts/codegen-verify.mjs`](../../../scripts/codegen-verify.mjs)) must **delete each package's configured `--outputPath`** before CLI codegen writes ([NewArch-AD-22](codegen-and-toolchain.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)). ResultT inject is retired on the current mobile pin ([NewArch-AD-21](codegen-and-toolchain.md#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete) superseded). + +**Why:** The current Jest mocks are plain enumerable objects and structurally cannot reproduce the enumeration bug that already cost an iteration; these tests close that blind spot and make iterations faster and higher quality. + +**Determinism requirement:** `codegen:verify` is only meaningful if `yarn codegen` is reproducible. It resolves the RN/Codegen toolchain at run time, so the toolchain **must** be pinned to the app's RN line ([NewArch-AD-20](codegen-and-toolchain.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted)); otherwise a host/CI with a drifted `@react-native/codegen` or `react-native` emits spurious drift (0.82/0.80 macros, podspec path changes) or masks real drift. + +--- diff --git a/okf-bundle/new-architecture/decisions/js-runtime.md b/okf-bundle/new-architecture/decisions/js-runtime.md new file mode 100644 index 0000000000..adf224c541 --- /dev/null +++ b/okf-bundle/new-architecture/decisions/js-runtime.md @@ -0,0 +1,144 @@ +--- +type: Reference +title: 'NewArch ADRs: native module resolver and JS wrapper' +description: 'NewArch-AD-6, 8 to 11, 14, 15, 18, 19: unified resolver, enumeration, main queue setup, centralized native state, merged method names, memoizing Proxy, constant scope, raw vs wrapped resolver, methodQueue.' +tags: [new-architecture, turbomodule, resolver, adr] +timestamp: 2026-12-04T00:00:00Z +--- + +# NewArch ADRs: native module resolver and JS wrapper + +Part of [New Architecture decisions (ADR)](../architecture-decisions.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. + +## NewArch-AD-6 — Unified native module resolver — **Accepted** + +`packages/app/lib/internal/nativeModuleAndroidIos.ts` resolves `TurboModuleRegistry.get(name) ?? NativeModules[name]`. + +**Why / semantics (researched, scope-limited):** In **bridgeless** mode with the **unified native-module proxy** (RN ≥ 0.74 New Architecture default; the repo's test app is RN 0.78 + `newArchEnabled`), both `TurboModuleRegistry.get(name)` and `NativeModules[name]` route through one unified, **cached** `nativeModuleProxy` (`BridgelessNativeModuleProxy` backing `global.nativeModuleProxy`, which *is* `NativeModules`) — so they return the **same instance** for a migrated module; the `??` cannot hand back two divergent wrappers. **Scope caveat (verified by design review):** this identity is confirmed for **bridgeless + unified proxy**; the bridged-New-Architecture path (`__turboModuleProxy` set without bridgeless) is a *different* lookup from bridged `NativeModules` lazy config and is **not verified** to share identity — RNFB targets bridgeless NA, so this is an untested edge, not a supported config. The `NativeModules` fallback is **load-bearing during Phases 1–5**: an unmigrated package's legacy module is null in `TurboModuleRegistry.get` and resolves via the interop-backed `NativeModules` (`legacyBinding_`). + +**Phase R action:** remove the `NativeModules` fallback once all packages are migrated, so a missing module throws instead of returning soft-undefined. + +--- + +## NewArch-AD-8 — TurboModule JS enumeration: `for...in` + `Object.create` — **Accepted** + +When wrapping or extending a native module, enumerate methods with **`for...in`** (not `Object.keys`) and extend with **`Object.create(host, descriptors)`** (never copy the host into a plain `{}` / spread / `Object.assign({}, host)`). + +**Why:** TurboModules expose methods lazily on the **prototype**, which are non-own; `Object.keys`/spread see nothing and produce `XYZ is not a function`. Codegen methods **are** enumerable via `for...in` (confirmed), so `for...in` + `Object.create` both finds them and preserves the prototype. Reference: [RN enable-libraries § "XYZ is not a function"](https://github.com/reactwg/react-native-new-architecture/blob/main/docs/enable-libraries.md#javascript-xyz--is-not-a-function-it-is-undefined), [facebook/react-native#43221](https://github.com/facebook/react-native/issues/43221). + +Code: [`registry/nativeModule.ts`](../../../packages/app/lib/internal/registry/nativeModule.ts), [`nativeModuleAndroidIos.ts`](../../../packages/app/lib/internal/nativeModuleAndroidIos.ts). + +--- + +## NewArch-AD-9 — `requiresMainQueueSetup` returns `NO` — **Accepted** + +iOS TurboModule shells return `NO` from `+ requiresMainQueueSetup`. Any genuinely main-thread/UIKit work in `getConstants`/init is dispatched explicitly to the main queue, not by forcing whole-module main-queue setup. + +**Why:** Under TurboModules, `requiresMainQueueSetup = YES` makes the lazy module load run setup **synchronously on the main thread** — the JS thread blocks on main (deadlock risk under fling) **and synchronous methods are blocked** (which would block [NewArch-AD-16 Phase S](events-tests-process.md#newarch-ad-16--phase-s-asyncsync-conversion--open)). Reference: [RN #49957](https://github.com/facebook/react-native/pull/49957), [RN commit d7ac21c](https://github.com/facebook/react-native/commit/d7ac21cec5492e180fbf3817af7be64ab121cb75) (under TurboModules `getConstants` runs on the JS thread, not the main queue). + +**Per-package audit (part of gap-analysis):** inventory each shell's `getConstants`/init and any `methodQueue` override for genuine main-thread/UIKit dependencies; default to `NO`; dispatch only the specific main-thread work that needs it. + +**Phase 0 status — implemented (2026-06-29 re-implementation pass).** Both shells return `NO`; legacy `methodQueue = dispatch_get_main_queue()` overrides removed per [NewArch-AD-19](#newarch-ad-19--turbomodule-methodqueue-policy--accepted). Validate on-device during area-focused e2e if any method regresses. + +--- + +## NewArch-AD-10 — Cross-package native state is centralized in `app`, with testable APIs — **Accepted** + +`packages/app` is the home of cross-package native APIs and shared state (it always has been). This is acceptable; the goal is to **formalize** it: prefer explicit, testable accessors over bare `public static` fields, and ensure any inter-module state really is routed through `app` rather than duplicated per package. + +**Known shared state to keep centralized:** `authDomains` / iOS `customAuthDomains` (read by `auth` + `RCTConvertFirebase`); `ReactNativeFirebaseJSON` / `Meta` / `Preferences` / `UniversalFirebasePreferences` (read by database, firestore, messaging, crashlytics, app-check); the event emitters (NewArch-AD-4 / Phase C). When a package migrates, it must keep reaching these `app`-owned singletons; do not fork a second copy. + +**Direction:** treat the current `public static` maps as tolerated legacy carryover; a new cross-package channel should be an explicit app-owned API/singleton with tests, not a new public static. + +**Encapsulation (optional, later):** refactor un-encapsulated shared-state items (bare `public static` maps such as `authDomains`) behind explicit, testable `app`-owned accessor methods, and audit that all inter-module state is genuinely centralized in `app`. Optional — it does not block shipping TurboModules. + +--- + +## NewArch-AD-11 — Multi-module method names are merged; uniqueness enforced by test — **Accepted** + +Multiple specs/modules in one package are **merged flat** into a single resolved native object (so JS keeps calling `native.documentGet(...)` etc.). Method names must therefore be **globally unique across a package's specs**. Follow the existing `` naming already in use (`documentGet`, `collectionGet`, `transactionBegin`, `aggregateQuery`, …) — which is why there are zero collisions today. + +**Enforcement:** a build/test-time uniqueness assertion (part of NewArch-AD-17's contract test) asserts the union of method names across a package's specs has no duplicates. Optional `__DEV__` runtime guard in the merge loop warns on overwrite. We do **not** namespace sub-modules on the wire (would churn every call site). + +--- + +## NewArch-AD-14 — Native-module wrapper: memoizing lazy `Proxy` — **Accepted** + +The wrapper gives every native method: (1) **arg prepending** (`appName`, region/databaseId — the native bridge argument injection that lets product code call `firestore().collection(...)` without passing `appName`), (2) **error mapping** (native rejections → `NativeFirebaseError`), (3) **iOS null-encoding** for TurboModule object args. These responsibilities are mandatory product behavior. + +**Decision:** wrap via a **memoizing lazy `Proxy`** — each method is wrapped+bound **on first call** and cached, instead of eagerly materializing every method at first touch. + +**Why over eager:** eager builds all closures up front (auth ≈ 59, firestore ≈ 31 per cache key) and **defeats TurboModule prototype lazy loading**; the lazy Proxy preserves laziness (only pay for methods actually called), removes the eager `getConstants` rebuild on hot paths ([NewArch-AD-15](#newarch-ad-15--constant-memoization-scope-static-only--accepted)), and lets the `app`-path and `FirebaseModule`-path wrapping converge on one shape. The Proxy must enumerate via `for...in` and preserve the host prototype ([NewArch-AD-8](#newarch-ad-8--turbomodule-js-enumeration-forin--objectcreate--accepted)) — it must **not** flatten onto a frozen `{}` (that is the eager pattern being replaced). + +**Coupling note:** the current `initialiseNativeModule` flatten-onto-`{}` + `Object.freeze` only works because eager wrapping pre-materializes own-enumerable methods. Moving to the Proxy means returning the Proxy (or a Proxy-backed object), **not** an `Object.assign`-ed frozen plain object. Update both the multi-module merge and the single-module path together. + +### NewArch-AD-14a — Multi-host merge: routing composite Proxy (required for multi-module) + +A single `Proxy` has **one** target/`[[Prototype]]`, so it cannot represent N independent TurboModule hosts (firestore ×4, database ×5) whose lazy methods live on **separate** prototype chains. The single-host Proxy is insufficient for multi-module packages, which **Phase 1 hits immediately** (`FirestoreStatics`, `DatabaseSyncTree`). Design the merge as a **routing composite Proxy**, not a flattened object: + +1. **At init (metadata only, cheap):** `for...in` each raw host to build a `methodName → { host, key }` routing map. No wrapping/binding yet — just discover which host owns each name. (Method names are unique across a package's specs by [NewArch-AD-11](#newarch-ad-11--multi-module-method-names-are-merged-uniqueness-enforced-by-test--accepted), so the map has no collisions.) +2. **`get(name)` trap:** on first access, look up `{ host, key }`, wrap+bind from the **correct** host (arg-prepend + error-map + iOS null-encode), memoize the wrapped fn, return it. Preserves per-host prototype/laziness. +3. **`has` / `ownKeys` / `getOwnPropertyDescriptor`:** answer from the routing map (so `in`, `for...in`, and `Object.keys` over the merged surface behave). +4. **Drop the dead `multiModuleRoot[moduleName] = !!nativeModule` boolean flags** — they are written but never read in product code; if optional-module presence is ever needed, keep it in a side table, not on the callable surface. +5. **No `Object.freeze`** on the composite — immutability is provided by the Proxy traps (no `set`), not by freezing. + +The single-module path is the degenerate N=1 case of the same composite (one host in the routing map). Implement both through the one mechanism. **NewArch-AD-17.1's contract test must include a 2-host merge fixture** even before firestore ships, since Phase 0 (`app`/`utils` are resolved as *separate* single-host surfaces) does **not** exercise this path. + +--- + +## NewArch-AD-15 — Constant memoization scope: static only — **Accepted** + +Memoize constants that are **static after init** (e.g. app `NATIVE_FIREBASE_APPS`, `FIREBASE_RAW_JSON`; iOS/file-path constants). Do **not** memoize constants that can change at runtime; expose those as **methods**, not cached constants. + +**Why / coherency:** Memoization is JS-layer caching. For static native state a cached snapshot can't drift; for **dynamic** native state it can, with no native→JS invalidation signal. + +**Constant taxonomy (classify each before caching):** + +| Class | Examples | Caching rule | +|-------|----------|--------------| +| **bootstrap-only** | `NATIVE_FIREBASE_APPS` | Snapshot at bootstrap. JS never re-reads it today, so memoizing preserves current semantics — but document it as a bootstrap snapshot; runtime `initializeApp`/`deleteApp` will **not** be reflected (already true). | +| **build-time static** | `FIREBASE_RAW_JSON`, path constants (`DOCUMENT_DIRECTORY`, …) | Safe to memoize indefinitely. | +| **session-static** | `isRunningInTestLab` | Safe to memoize. | +| **dynamic** | `androidPlayServices` | **Never cache as a constant.** Expose as a method (`androidGetPlayServicesStatus()`); remove from the spec's `getConstants` typing when converted. | + +**Hot-path bug to fix in the same pass:** `withTurboConstants` calls `getConstants()` on **every** `getReactNativeModule()` resolve — the exact rebuild NewArch-AD-14/NewArch-AD-15 target. And `messaging.isSupported()` currently reads the Play Services value via the **legacy** module name `RNFBUtilsModule` and the static constant — under turbo-only resolution that name returns nothing, so `isSupported()` breaks. Fix it to resolve `NativeRNFBTurboUtils` **and** read via the dynamic method, not the constant. + +--- + +## NewArch-AD-18 — Raw vs wrapped resolver policy — **Accepted** + +Two resolution surfaces exist and must be used deliberately: + +- **Wrapped** (`getNativeModule(module)` / `getAppModule()` → the [NewArch-AD-14](#newarch-ad-14--native-module-wrapper-memoizing-lazy-proxy--accepted) Proxy): the **default** for all product calls. Gives arg-prepend, error mapping, iOS null-encoding. +- **Raw** (`getReactNativeModule(name)`): the **bare** native object from the unified resolver — no wrapping. + +**Default rule:** new product code uses the **wrapped** surface. Raw access is allowed **only** when listed in the canonical exception table below (or after a gap-analysis finds a new legitimate case, documents it here, and adds an in-code rationale comment). Raw callers must use the **turbo** module name ([NewArch-AD-2](codegen-and-toolchain.md#newarch-ad-2--naming-nativernfbturbo--accepted)). Raw callers do **not** get error mapping — they must handle native errors themselves. + +**Gap-analysis gate (every package):** as part of spec authoring, `grep` the repo for `getReactNativeModule(` in product code. For each hit: (1) is it already in the table below? (2) if not, is it a bug (legacy module name, should be wrapped)? (3) if genuinely new, add a row here with policy rationale **before** landing the PR. + +### Canonical exception table + +| # | Call site | Module name | Category | Why raw (policy) | Action | +|---|-----------|---------------|----------|------------------|--------| +| E1 | [`RNFBNativeEventEmitter.ts`](../../../packages/app/lib/internal/RNFBNativeEventEmitter.ts) (constructor, `addListener`, `removeAllListeners`, `removeSubscription`) | `NativeRNFBTurboApp` | **Permanent** | React Native's `NativeEventEmitter` must receive the **same raw host object** that implements `addListener` / `removeListeners` on the native side. Wrapping would break event subscription identity and the RN event-bridge contract. A typed Codegen event path is a future cutover, not a reason to wrap this site. | Keep raw; turbo name. | +| E2 | [`nativeModule.ts`](../../../packages/app/lib/internal/registry/nativeModule.ts) `initialiseNativeModule` / `getAppModule` bootstrap | any | **Infrastructure** | The wrapper factory itself must read the bare host to build the [NewArch-AD-14](#newarch-ad-14--native-module-wrapper-memoizing-lazy-proxy--accepted) Proxy/composite. Not a product bypass. | N/A | +| E3 | [`nativeModuleAndroidIos.ts`](../../../packages/app/lib/internal/nativeModuleAndroidIos.ts) unified resolver | any | **Infrastructure** | Defines `getReactNativeModule`; applies `withTurboConstants` before returning. Not a product bypass. | N/A | +| E4 | [`tests/globals.js`](../../../tests/globals.js) `NativeModules` proxy getter | `RNF*` / `NativeRNFBTurbo*` | **Infrastructure** | E2e harness routes RNFB module names through the real unified resolver so specs that read `NativeModules.NativeRNFBTurboApp` (e.g. [`events.e2e.js`](../../../packages/app/e2e/events.e2e.js)) get a live module, not a stub. Durable product wiring — not harness narrowing. | Keep; part of Phase 0. | +| E5 | [`UtilsStatics.ts`](../../../packages/app/lib/utils/UtilsStatics.ts) `FilePath` getter | `NativeRNFBTurboUtils` | **Phase 0 fix** | Reads path **constants** synchronously from the utils host without a `FirebaseModule` instance (static getter on `Utils.Statics`). Raw was acceptable pre-turbo; under [NewArch-AD-15](#newarch-ad-15--constant-memoization-scope-static-only--accepted) migrate to a dedicated wrapped utils accessor (or memoized static read via resolver) so constants are not rebuilt per access. Turbo name is already correct. | Fix in Phase 0 re-implementation. | +| E6 | [`messaging/lib/index.ts`](../../../packages/messaging/lib/index.ts) `isSupported()` | ~~`RNFBUtilsModule`~~ → `NativeRNFBTurboUtils` | **Phase 0 fix (bug)** | Cross-package read of Play Services availability. Was using **legacy module name** (returns `undefined` under turbo-only) and a **dynamic constant** (`androidPlayServices`) that can go stale. Must use turbo name + **dynamic method** `androidGetPlayServicesStatus()` per [NewArch-AD-15](#newarch-ad-15--constant-memoization-scope-static-only--accepted). | **Must-fix** in Phase 0. | +| E7 | [`app/lib/modular.ts`](../../../packages/app/lib/modular.ts) `metaGetAll`, `jsonGetAll`, `preferences*` | `NativeRNFBTurboApp` | **Not an exception — migrate** | No policy reason for raw; these are app-module method calls with no arg-prepend skip. Should use **`getAppModule()`** (wrapped) for error mapping consistency. Listed here so gap-analysis catches them. | Migrate to `getAppModule()` in Phase 0. | +| E8 | [`FirestoreStatics.ts`](../../../packages/firestore/lib/FirestoreStatics.ts) `setLogLevel` | `NativeRNFBTurboFirestore` | **Phase 1 fix** | Cross-package static helper bypasses `FirebaseModule`/`getNativeModule`. Uses turbo main host via [`getStaticFirestoreMainModule()`](../../../packages/firestore/lib/internal/staticNativeModule.ts) (NewArch-AD-18 E8). Raw access retained — no wrapped surface for static helpers. | Done — firestore Phase 1. | +| E9 | [`DatabaseSyncTree.ts`](../../../packages/database/lib/DatabaseSyncTree.ts) `native` getter | `RNFBDatabaseQueryModule` | **Deferred — Phase 4** | Internal sync listener tree calls query module directly for low-latency sync ops, bypassing the merged multi-module surface. Acceptable until database migrates; then turbo name + evaluate whether wrapped merge surface suffices. | Fix when `database` migrates. | +| E10 | [`phone-number-verification/lib/index.ts`](../../../packages/phone-number-verification/lib/index.ts) `getNativeModule()` | `RNFBPnvModule` / `NativeRNFBTurboPnv` | **Permanent (direct resolver)** | Package bypasses `createModuleNamespace` by design. Direct resolver is intentional; use the turbo name. | Keep direct; turbo name. | + +**Adding a new exception:** gap-analysis must justify why wrapping breaks (not merely "it's convenient"). Update this table and add a one-line `// NewArch-AD-18 E: ` comment at the call site. + +--- + +## NewArch-AD-19 — TurboModule `methodQueue` policy — **Accepted** + +Default: **do not override `methodQueue`.** Remove legacy `- (dispatch_queue_t)methodQueue { return dispatch_get_main_queue(); }` overrides (present on `RNFBAppModule` and `RNFBUtilsModule`) unless a specific method genuinely needs the main thread — in which case dispatch *that method's* main-thread work explicitly (the `RCTUnsafeExecuteOnMainQueueSync` pattern already used in `initializeApp`), rather than forcing the whole module onto main. + +**Why:** A module-wide `methodQueue = main_queue` couples every async method to the main thread (jank/contention) and is inconsistent with [NewArch-AD-9](#newarch-ad-9--requiresmainqueuesetup-returns-no--accepted) (`requiresMainQueueSetup = NO`). **Caveat (unverified):** how TurboModule JSI honors `methodQueue` for sync vs async methods is not documented; treat removal as a native change to validate on-device during Phase 0 re-implementation, not a blind delete. Keep explicit main dispatch only where UI (e.g. Play Services resolution dialogs) requires it. + +--- diff --git a/okf-bundle/new-architecture/index.md b/okf-bundle/new-architecture/index.md index 9ce6af74d6..f95b237ff0 100644 --- a/okf-bundle/new-architecture/index.md +++ b/okf-bundle/new-architecture/index.md @@ -6,7 +6,7 @@ Durable architectural decisions for React Native Firebase TurboModules. Product ## Documents -* [Architecture decisions (ADR)](architecture-decisions.md) — **canonical owner** of durable decisions ([NewArch-AD-5](architecture-decisions.md#newarch-ad-5--commit-generated-code--accepted): library vs test-app codegen) +* [Architecture decisions (ADR)](architecture-decisions.md) (decision index; entries under `decisions/`) — **canonical owner** of durable decisions ([NewArch-AD-5](decisions/codegen-and-toolchain.md#newarch-ad-5--commit-generated-code--accepted): library vs test-app codegen) ## Reference implementation diff --git a/okf-bundle/routes/expo-plugin.md b/okf-bundle/routes/expo-plugin.md index 1e725c5b76..2a6aeed813 100644 --- a/okf-bundle/routes/expo-plugin.md +++ b/okf-bundle/routes/expo-plugin.md @@ -36,7 +36,7 @@ About 8,000 tokens with this file and `AGENTS.md` (steps 1 to 3). | Exports, `plugin/build`, published types | `yarn attw:check` | [handoff checklist](../testing/validation/evidence-and-handoff.md#handoff-checklist) | | `test-expo` screens or compare-types configs | `yarn docs:member:check` | [evidence template](../testing/validation/evidence-and-handoff.md#validation-evidence-package) | -Never ad-hoc `expo prebuild`, `xcodebuild`, `pod`, `simctl` or `cd test-expo && ...` ([forbidden](../testing/commands/forbidden.md)). +Never ad-hoc `expo prebuild`, `xcodebuild`, `pod`, `simctl` or `cd test-expo && ...` ([forbidden](../testing/agent-command-policy.md#forbidden-always)). ## Not triggered by this diff diff --git a/okf-bundle/routes/index.md b/okf-bundle/routes/index.md index 524e59600d..ca5a392338 100644 --- a/okf-bundle/routes/index.md +++ b/okf-bundle/routes/index.md @@ -43,7 +43,7 @@ Each area index lists its own workflow; combine it with the route for the files ## Every route assumes -- Shell commands come only from the [agent rule](../testing/agent-command-policy.md#agent-rule-read-first) registry; anything else is [forbidden](../testing/commands/forbidden.md). +- Shell commands come only from the [agent rule](../testing/agent-command-policy.md#agent-rule-read-first) registry; anything else is [forbidden](../testing/agent-command-policy.md#forbidden-always). - Work types and tiers: [change authoring § work types](../testing/authoring/loop.md#work-types). Term ids: [iteration vocabulary](../testing/iteration-vocabulary.md). - Exit codes come from zsh: use `${pipestatus[1]}` or bare `$?` ([trap](../testing/commands/core.md#agent-shell-is-zsh)). - `implementation`, `documentation` and `independent-review` are separate passes ([frozen tree](../testing/authoring/review-and-commit.md#frozen-tree)). A route's "Review and handoff" step is for the reviewer pass, not the authoring pass. diff --git a/okf-bundle/testing/agent-command-policy.md b/okf-bundle/testing/agent-command-policy.md index dc3c2172bb..bc7c2afa24 100644 --- a/okf-bundle/testing/agent-command-policy.md +++ b/okf-bundle/testing/agent-command-policy.md @@ -21,7 +21,32 @@ Single source for **which shell commands agents may run** in this repo. E2e `yar 3. **Before any native `:build`:** root `yarn` exit 0 **and** patched fmt **≥ 12.1.0** — [install / patch / fmt gate](commands/native-build-gate.md#install-patch-fmt-gate-blocking). Do **not** invent Podfile/fmt workarounds. 4. When a canonical command fails: read the **full** output, fix **product code** (or re-run root `yarn` for a patch miss), re-run the **same** command. Do **not** switch invocation style. 5. Do **not** infer alternate commands from error strings (`command not found: genversion`, `Couldn't find a script named "jet"`, etc.) — see [known traps](commands/core.md#known-traps). -6. The [command constraints](commands/constraints.md#command-constraints) apply to every shell session in this repo. +6. Never run anything in [forbidden (always)](#forbidden-always), directly below. +7. The [command constraints](commands/constraints.md#command-constraints) apply to every shell session in this repo. + + + +## Forbidden (always) + +| Command | Why | +| --- | --- | +| `yarn workspace @react-native-firebase/* prepare` (and variants) | Not canonical; breaks root devDependency binary resolution | +| `cd packages/ && yarn prepare` / `yarn run build` | Same trap; not the postinstall / lerna code path | +| `yarn google-java-format`, bare `google-java-format`, `npx google-java-format`, `google-java-format -i` | Invented format entrypoints — **only** `yarn lint:android` for **Java** | +| `ktlint`, `npx ktlint`, invented `yarn` ktlint scripts, `cd tests/android && ./gradlew ktlintFormat` | Invented Kotlin format — **only** repo-root `./gradlew ktlintFormat` | +| `npm install` (any cwd) / `yarn` / `yarn install` only in `tests/` for monorepo deps | Root `yarn` applies patches and workspace links; tests-only install is insufficient | +| Ad-hoc `./gradlew …` outside allowlisted yarn scripts (`tests:android:unit`, `tests:android:build`, `tests:android:post-e2e-coverage`, `tests:android:test:jacoco-report`, etc.) and outside repo-root `./gradlew ktlintFormat` | Wrong task / cwd / report path; invents CI that does not match Codecov | +| Ad-hoc `xcodebuild test` / CocoaPods `test_spec` / `tests/ios/testingTests` as the iOS unit gate | Misses LCOV merge — **only** `yarn tests:ios:unit` ([IosTest-AD-1](ios-architecture-decisions.md#iostest-ad-1)) | +| Ad-hoc `ruby packages/app/__tests__/…_test.rb` (or bare runner) as the validation gate | Misses SimpleCov / suite discovery — **only** `yarn tests:ios:ruby` | +| Ad-hoc `expo prebuild`, `xcodebuild`, `cd test-expo && tsc`, or `cd test-expo && …` as a test-expo link, typecheck, or launch gate | **Only** `yarn test-expo:ios:link` / `yarn tsc:compile:test-expo` from repo root — not Detox / `yarn tests:*` / `yarn test-rn-bare:ios:build` | +| Ad-hoc `pod`, `xcodebuild`, or `cd test-rn-bare && …` as the RN CLI prebuilt RNCore iOS build gate | **Only** `yarn test-rn-bare:ios:build` from repo root — not Detox / `yarn tests:*` / `yarn test-expo:ios:link`. Ad-hoc `pod` / `xcodebuild` stay never-use | +| `react-native init`, `npx @react-native-community/cli init`, `npx react-native init` | Not on the allowlist — seed checked-in RN CLI trees via [template gotcha](commands/fixtures.md#react-native-community-template-checked-in-rn-cli-ios) | +| `yarn jet`, `npx jet`, `cd tests && yarn jet …` | [E2e agent rule](running-e2e.md#agent-rule-read-first) | +| `detox test`, bare `detox`, `cd tests && detox …` | E2e agent rule | +| bare `bundle install` at repo root | Use **`yarn ruby:install`** or root **`yarn`** (`postinstallDev` includes ruby:install) | +| Ad-hoc Metro / emulator start | Use `yarn tests:packager:jet` (iOS/Android) or `yarn tests:macos:packager:jet` (macOS), `yarn tests:emulator:start` ([running e2e](e2e/rules.md#rules)) | +| Direct `xcrun simctl delete` / `erase` / `rename` / `create` (and `simctl delete all` / `unavailable`, `simctl shutdown all`) as e2e device management | Destroys devices other worktrees, repos, or operators may be mid-run on. Provision with `yarn tests:e2e:setup-ios-sims` (create/reuse-only), free with `yarn tests:e2e:release --devices` (shutdown only). Legacy-simulator removal is human-operator — [migration](e2e/slot-devices.md#ios-slot-simulator-migration) | +| Spawn / PATH probes to “test” Jet or genversion | Log triage only; fix product code and re-run canonical command | ## Canonical registry @@ -35,7 +60,7 @@ The allowlist is one registry split by domain. A command is allowed only when it | `test-expo/` link, launch smoke, duplicate ObjC class check; `test-rn-bare/` build and launch smoke | [fixtures](commands/fixtures.md#canonical-registry) | | E2e and coverage, pre-flight, slot devices, slotted parallel, coverage post-process, Detox cache, CocoaPods provisioning, App Check helper secret | [e2e](commands/e2e.md#canonical-registry) | -Never run: [forbidden (always)](commands/forbidden.md). Before any native `:build`: [install / patch / fmt gate](commands/native-build-gate.md#install-patch-fmt-gate-blocking). +Never run: [forbidden (always)](#forbidden-always). Before any native `:build`: [install / patch / fmt gate](commands/native-build-gate.md#install-patch-fmt-gate-blocking). ## Files @@ -49,8 +74,6 @@ Content moved from this file into the files below. Headings and anchors keep the - [Agent commands: install / patch / fmt gate](commands/native-build-gate.md): Blocking install, patch, fmt and CocoaPods checks before any native :build, and the fmt / Apple Clang 21 trap. -- [Agent commands: forbidden (always)](commands/forbidden.md): Commands agents must never run, with the reason and the canonical replacement. - - [Agent commands: native lint, unit tests, codegen](commands/native.md): Allowlisted Android Java/Kotlin format, iOS Ruby lint and tests, Android JVM and iOS XCTest unit tests, TurboModule codegen, and their traps. - [Agent commands: constraints block](commands/constraints.md): Condensed plain-text constraints block for pasting into agent prompts; each line is owned by a section of the command files. diff --git a/okf-bundle/testing/code-coverage/invariants-and-troubleshooting.md b/okf-bundle/testing/code-coverage/invariants-and-troubleshooting.md index 7a662146dd..27384f036c 100644 --- a/okf-bundle/testing/code-coverage/invariants-and-troubleshooting.md +++ b/okf-bundle/testing/code-coverage/invariants-and-troubleshooting.md @@ -45,7 +45,7 @@ Part of [Coverage design](../coverage-design.md), split so a task loads only the | Jet after: coverage not enabled | Release / non-instrumented build | Use `:test-cover` debug builds | | `swiftCompatibility56` undefined | Profile link flags on all Pods | App target only for `OTHER_LDFLAGS` | | No `[jet-coverage] WS received` | Patches missing | `yarn install`; `.yarn/patches/` | -| WS closed on `reconnect_recovered` | Handshake on dead socket | Client retry + server pull; `JET_COVERAGE_TEARDOWN_RE` — [iOS issue 8](../../ci-workflows/ios.md#8-coverage-teardown-handshake-failure-tests-pass-nyc-00) | +| WS closed on `reconnect_recovered` | Handshake on dead socket | Client retry + server pull; `JET_COVERAGE_TEARDOWN_RE` — [iOS issue 8](../../ci-workflows/ios/orchestration-jet.md#8-coverage-teardown-handshake-failure-tests-pass-nyc-00) | | Empty NYC / lcov | Environment or patch issue during `:test-cover` | Re-run per [running e2e](../running-e2e.md) — do not invoke the test runner directly | | `tests:ios:test:process-coverage` exits 1; NYC `concurrency` got `0` | Trailing NYC JS report failed after native LCOV write | Read `coverage/ios-native/lcov.info` — still the artifact; exit ≠ missing native coverage ([§ E2e iOS native](native.md#e2e-ios-native-llvm)) | | Codecov missing iOS native | Wrong path/name | `coverage/ios-native/lcov.info` | diff --git a/okf-bundle/testing/code-coverage/pipelines.md b/okf-bundle/testing/code-coverage/pipelines.md index 49f52d3cca..d0640b9b4e 100644 --- a/okf-bundle/testing/code-coverage/pipelines.md +++ b/okf-bundle/testing/code-coverage/pipelines.md @@ -107,7 +107,7 @@ Jet self-wraps under NYC with `--coverage`. entrypoints run `rn-coverage js report` into `coverage/js//lcov.info`, using `tests/nyc.config.js` for source-map remap. This supplements rather than replaces the RNFB Jet/NYC transport and its `coverage/lcov.info` artifact. -- **Transfer:** patched test-runner/mocha-remote WS only (`coverage-ready` → `pull-coverage` → `coverage-data` → `coverage-ack`); HTTP POST `/coverage` deleted (`attachHttpServer` removed). Host launch/orchestrate control uses a **separate** HTTP server on **8091** (not the 8090 WS stack) — see [test-runner orchestration (log triage)](../e2e/run-loop.md#test-runner-host-orchestration-log-triage-only). Patches: `.yarn/patches/` (`jet`, `mocha-remote-client`, `mocha-remote-server`). See [iOS issues 6–6b](../../ci-workflows/ios.md#6-jet-websocket-disconnect-1006--1001), [issue 8](../../ci-workflows/ios.md#8-coverage-teardown-handshake-failure-tests-pass-nyc-00), [jet patch workflow](../../ci-workflows/detox-patches.md#updating-the-jet-patch-headless). +- **Transfer:** patched test-runner/mocha-remote WS only (`coverage-ready` → `pull-coverage` → `coverage-data` → `coverage-ack`); HTTP POST `/coverage` deleted (`attachHttpServer` removed). Host launch/orchestrate control uses a **separate** HTTP server on **8091** (not the 8090 WS stack) — see [test-runner orchestration (log triage)](../e2e/run-loop.md#test-runner-host-orchestration-log-triage-only). Patches: `.yarn/patches/` (`jet`, `mocha-remote-client`, `mocha-remote-server`). See [iOS issues 6–6b](../../ci-workflows/ios/orchestration-jet.md#6-jet-websocket-disconnect-1006--1001), [issue 8](../../ci-workflows/ios/orchestration-jet.md#8-coverage-teardown-handshake-failure-tests-pass-nyc-00), [jet patch workflow](../../ci-workflows/detox-patches.md#updating-the-jet-patch-headless). **NYC settings:** diff --git a/okf-bundle/testing/commands/fixtures.md b/okf-bundle/testing/commands/fixtures.md index 19d063f5f8..697e907207 100644 --- a/okf-bundle/testing/commands/fixtures.md +++ b/okf-bundle/testing/commands/fixtures.md @@ -64,7 +64,7 @@ A probe `pod install` rewrites the tracked `test-rn-bare/ios/testrnbare.xcodepro - **`@react-native-community/template` is not installed by root `yarn`.** It is not a `react-native` dependency, so a green install does **not** put the community template under `node_modules`. - Seeding or refreshing a **checked-in** RN CLI `ios/` tree (fixture app under the monorepo) after yarn **cannot** assume that package exists. The checked-in vanilla CLI compile fixture is `test-rn-bare/` (closer `yarn test-rn-bare:ios:build`). Do not re-seed it. - **Workaround:** one-shot pin `@react-native-community/template@` on the fixture package, copy `ios/` + JS entry files from the template into the fixture, then **remove** the pin. Do not leave the template as a durable dependency. -- **Never** `react-native init` / `npx @react-native-community/cli init` / `npx react-native init` — not on the agent allowlist (see [Forbidden](forbidden.md#forbidden-always)). +- **Never** `react-native init` / `npx @react-native-community/cli init` / `npx react-native init` — not on the agent allowlist (see [Forbidden](../agent-command-policy.md#forbidden-always)). ### expo-router autolink exclude (`@expo/ui`) diff --git a/okf-bundle/testing/commands/forbidden.md b/okf-bundle/testing/commands/forbidden.md deleted file mode 100644 index 082f6009ee..0000000000 --- a/okf-bundle/testing/commands/forbidden.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -type: Reference -title: 'Agent commands: forbidden (always)' -description: 'Commands agents must never run, with the reason and the canonical replacement.' -tags: [testing, agents, commands] -timestamp: 2026-12-02T00:00:00Z ---- - -# Agent commands: forbidden (always) - -Part of [Agent command policy](../agent-command-policy.md), split so a task loads only the section it needs. Section headings and `#anchors` are unchanged from that file; "this doc" or "this file" in the text means that whole document. - -## Forbidden (always) - -| Command | Why | -| --- | --- | -| `yarn workspace @react-native-firebase/* prepare` (and variants) | Not canonical; breaks root devDependency binary resolution | -| `cd packages/ && yarn prepare` / `yarn run build` | Same trap; not the postinstall / lerna code path | -| `yarn google-java-format`, bare `google-java-format`, `npx google-java-format`, `google-java-format -i` | Invented format entrypoints — **only** `yarn lint:android` for **Java** | -| `ktlint`, `npx ktlint`, invented `yarn` ktlint scripts, `cd tests/android && ./gradlew ktlintFormat` | Invented Kotlin format — **only** repo-root `./gradlew ktlintFormat` | -| `npm install` (any cwd) / `yarn` / `yarn install` only in `tests/` for monorepo deps | Root `yarn` applies patches and workspace links; tests-only install is insufficient | -| Ad-hoc `./gradlew …` outside allowlisted yarn scripts (`tests:android:unit`, `tests:android:build`, `tests:android:post-e2e-coverage`, `tests:android:test:jacoco-report`, etc.) and outside repo-root `./gradlew ktlintFormat` | Wrong task / cwd / report path; invents CI that does not match Codecov | -| Ad-hoc `xcodebuild test` / CocoaPods `test_spec` / `tests/ios/testingTests` as the iOS unit gate | Misses LCOV merge — **only** `yarn tests:ios:unit` ([IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1)) | -| Ad-hoc `ruby packages/app/__tests__/…_test.rb` (or bare runner) as the validation gate | Misses SimpleCov / suite discovery — **only** `yarn tests:ios:ruby` | -| Ad-hoc `expo prebuild`, `xcodebuild`, `cd test-expo && tsc`, or `cd test-expo && …` as a test-expo link, typecheck, or launch gate | **Only** `yarn test-expo:ios:link` / `yarn tsc:compile:test-expo` from repo root — not Detox / `yarn tests:*` / `yarn test-rn-bare:ios:build` | -| Ad-hoc `pod`, `xcodebuild`, or `cd test-rn-bare && …` as the RN CLI prebuilt RNCore iOS build gate | **Only** `yarn test-rn-bare:ios:build` from repo root — not Detox / `yarn tests:*` / `yarn test-expo:ios:link`. Ad-hoc `pod` / `xcodebuild` stay never-use | -| `react-native init`, `npx @react-native-community/cli init`, `npx react-native init` | Not on the allowlist — seed checked-in RN CLI trees via [template gotcha](fixtures.md#react-native-community-template-checked-in-rn-cli-ios) | -| `yarn jet`, `npx jet`, `cd tests && yarn jet …` | [E2e agent rule](../running-e2e.md#agent-rule-read-first) | -| `detox test`, bare `detox`, `cd tests && detox …` | E2e agent rule | -| bare `bundle install` at repo root | Use **`yarn ruby:install`** or root **`yarn`** (`postinstallDev` includes ruby:install) | -| Ad-hoc Metro / emulator start | Use `yarn tests:packager:jet` (iOS/Android) or `yarn tests:macos:packager:jet` (macOS), `yarn tests:emulator:start` ([running e2e](../e2e/rules.md#rules)) | -| Direct `xcrun simctl delete` / `erase` / `rename` / `create` (and `simctl delete all` / `unavailable`, `simctl shutdown all`) as e2e device management | Destroys devices other worktrees, repos, or operators may be mid-run on. Provision with `yarn tests:e2e:setup-ios-sims` (create/reuse-only), free with `yarn tests:e2e:release --devices` (shutdown only). Legacy-simulator removal is human-operator — [migration](../e2e/slot-devices.md#ios-slot-simulator-migration) | -| Spawn / PATH probes to “test” Jet or genversion | Log triage only; fix product code and re-run canonical command | diff --git a/okf-bundle/testing/commands/native.md b/okf-bundle/testing/commands/native.md index cb991a8d63..8c22fb903b 100644 --- a/okf-bundle/testing/commands/native.md +++ b/okf-bundle/testing/commands/native.md @@ -69,7 +69,7 @@ Rows of the canonical registry that this file owns. Other rows: [registry index] - **`cd packages/ && yarn ios:codegen`** (or `yarn android:codegen`) often fails with **`unknown command 'codegen'`** after a clean `yarn` — `@react-native-community/cli` resolves from the **test app** workspace. -- Package scripts **wipe then regen** the configured `--outputPath` ([NewArch-AD-22](../../new-architecture/architecture-decisions.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)). Prefer those yarn scripts when CLI resolution works. -- **Canonical (mobile toolchain from `tests/`):** use each package's `yarn android:codegen` / `yarn ios:codegen` script, which delegates to [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs). The shared runner wipes the configured output path and invokes the pinned mobile CLI from `tests/`; do not run the CLI manually. RN 0.86 emits `ResultT` natively, so the former inject script is retired ([NewArch-AD-21](../../new-architecture/architecture-decisions.md#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete)). -- **CI / library packages:** `yarn codegen:verify`. Library vs test-app codegen (committed trees, `includesGeneratedCode`, git-diff guard, test-app dump gitignore): [NewArch-AD-5](../../new-architecture/architecture-decisions.md#newarch-ad-5--commit-generated-code--accepted). Test-app iOS CLI `--outputPath` is `ios` (project base); wipe is `ios/build/generated/ios` plus `tests/ios/Package.swift` and sibling app dumps. +- Package scripts **wipe then regen** the configured `--outputPath` ([NewArch-AD-22](../../new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)). Prefer those yarn scripts when CLI resolution works. +- **Canonical (mobile toolchain from `tests/`):** use each package's `yarn android:codegen` / `yarn ios:codegen` script, which delegates to [`scripts/codegen-package.mjs`](../../../scripts/codegen-package.mjs). The shared runner wipes the configured output path and invokes the pinned mobile CLI from `tests/`; do not run the CLI manually. RN 0.86 emits `ResultT` natively, so the former inject script is retired ([NewArch-AD-21](../../new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete)). +- **CI / library packages:** `yarn codegen:verify`. Library vs test-app codegen (committed trees, `includesGeneratedCode`, git-diff guard, test-app dump gitignore): [NewArch-AD-5](../../new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-5--commit-generated-code--accepted). Test-app iOS CLI `--outputPath` is `ios` (project base); wipe is `ios/build/generated/ios` plus `tests/ios/Package.swift` and sibling app dumps. - After **library** regen: commit the generated trees named in NewArch-AD-5, then `:build` + Metro reset-cache before `:test-cover`. diff --git a/okf-bundle/testing/e2e/narrowing.md b/okf-bundle/testing/e2e/narrowing.md index f669896705..9da843f7e5 100644 --- a/okf-bundle/testing/e2e/narrowing.md +++ b/okf-bundle/testing/e2e/narrowing.md @@ -106,7 +106,7 @@ Module specs load in `loadTests()` via `platformSupportedModules.includes(' diff --git a/okf-bundle/testing/e2e/recovery.md b/okf-bundle/testing/e2e/recovery.md index 328c34cfcd..d33c2e536e 100644 --- a/okf-bundle/testing/e2e/recovery.md +++ b/okf-bundle/testing/e2e/recovery.md @@ -96,7 +96,7 @@ If this recurs: `yarn tests:e2e:release --only macos-app` in the run's slot env **Native / device logs** (remove instrumentation before merge): -- **macOS** — `log show --predicate 'process == "io.invertase.testing"' --last 10m --style compact`; filter `com.facebook.react.log:javascript` for bundle errors. **Blank window / Jet never connects:** often `Native module NativeRNFBTurboApp is not registered` — [NewArch-AD-2](../../new-architecture/architecture-decisions.md#newarch-ad-2--naming-nativernfbturbo--accepted) (web/macOS registry must include turbo keys). Other bundle errors → [other.md](../../ci-workflows/other.md) +- **macOS** — `log show --predicate 'process == "io.invertase.testing"' --last 10m --style compact`; filter `com.facebook.react.log:javascript` for bundle errors. **Blank window / Jet never connects:** often `Native module NativeRNFBTurboApp is not registered` — [NewArch-AD-2](../../new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-2--naming-nativernfbturbo--accepted) (web/macOS registry must include turbo keys). Other bundle errors → [other.md](../../ci-workflows/other.md) - **iOS** — `xcrun simctl spawn booted log stream --level debug --style compact --predicate 'process == "testing"'`; silent hangs: `sample ` on `testing`. Metro redbox **`Requiring unknown module "undefined"`** → [TurboModule stale toolchain](platform-troubleshooting.md#turbomodule-stale-toolchain-blocking). - **Android** — `adb logcat` (filter your tags) diff --git a/okf-bundle/testing/e2e/rules.md b/okf-bundle/testing/e2e/rules.md index fb6d4f1cc2..1a1386a2d5 100644 --- a/okf-bundle/testing/e2e/rules.md +++ b/okf-bundle/testing/e2e/rules.md @@ -40,7 +40,7 @@ yarn tests:emulator:start - **Apple `:build` compiles only.** `yarn tests:ios:build` / `yarn tests:macos:build` do not run CocoaPods. Full e2e / test process **requires** `yarn tests:ios:pod:install` or `yarn tests:macos:pod:install` as a **separate prior step** before the matching `:build` (after codegen / podspec / native Apple changes, and in [slot lifecycle](environment.md#slot-lifecycle) / `run-full-tests.sh` / CI). A bare `:build` without pod install is allowed when pods are already installed and you only need a compile. - **Committed codegen / generated native artifacts count as native** — any change under `packages/*/ios/generated/**` or `packages/*/android/**/generated/**` (including wipe-then-regen orphan deletions), or TurboModule **codegen / spec / podspec / native shell**, is a native change: rebuild + [platform coverage](gates.md#platform-coverage-gate-blocking) e2e on iOS and Android. **`yarn codegen:verify` is not a substitute** for `:test-cover` ([change authoring § forbidden shortcuts](../authoring/gates.md#forbidden-shortcuts)). - `packages/*/lib/**` changed → **`yarn lerna:prepare` must run to completion (exit 0) before anything else** — Metro serves `dist/module/**`, not `lib/**`. See [prepare completion gate](preflight.md#prepare-completion-gate-blocking) and [agent command policy § prepare must finish first](../commands/core.md#prepare-must-finish-first). After prepare finishes, restart the **matching** packager when Metro was already running ([packager reset-cache](recovery.md#packager-reset-cache-eaddrinuse)). - - TurboModule **codegen / spec / podspec / native shell** changed → same as native changed, plus regen codegen ([agent command policy § TurboModule codegen](../commands/native.md#turbomodule-codegen); wipe-then-regen [NewArch-AD-22](../../new-architecture/architecture-decisions.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)) when specs changed; if app loads with Metro redbox `Requiring unknown module "undefined"`, see [TurboModule stale toolchain](platform-troubleshooting.md#turbomodule-stale-toolchain-blocking). + - TurboModule **codegen / spec / podspec / native shell** changed → same as native changed, plus regen codegen ([agent command policy § TurboModule codegen](../commands/native.md#turbomodule-codegen); wipe-then-regen [NewArch-AD-22](../../new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-22--codegen-is-wipe-then-regen-on-the-configured-outputpath--accepted)) when specs changed; if app loads with Metro redbox `Requiring unknown module "undefined"`, see [TurboModule stale toolchain](platform-troubleshooting.md#turbomodule-stale-toolchain-blocking). - **JS bundle (debug):** all platforms (iOS, Android, macOS) load JS from Metro; only **release** builds pre-bundle/embed JS. `lib/**` edits alone do not require `:build` — use the [prepare completion gate](preflight.md#prepare-completion-gate-blocking) and Metro restart above. - **TS coverage:** run `:build` before `:test-cover` on iOS/Android so Istanbul + patched test-runner coverage instrumentation is in the debug native app (bundle still from Metro). After test-runner patch changes, restart the packager with `yarn tests:packager:jet-reset-cache` ([packager reset-cache](recovery.md#packager-reset-cache-eaddrinuse)). @@ -86,7 +86,7 @@ Coverage flush is **package-owned**. Test-app modules are **integration probes o - **iOS:** `tests/ios/testing/RNFBTestingMessagingModule.m` — `NativeModules.RNFBTestingMessaging.messagingPreservesExistingDelegate()` - Standalone so the coverage TurboModule stays product-neutral ([coverage design § react-native-coverage](../code-coverage/test-app-modules.md#react-native-coverage)). -**Probe hits in native coverage:** Messaging e2e `getRNFBTesting().completesNonFCMRemoteNotification()`, `getRNFBTesting().serializeMessagingUserInfo(...)`, and `NativeModules.RNFBTestingMessaging.messagingPreservesExistingDelegate()` exercise product sources (for example `RNFBMessaging+AppDelegate.m` non-FCM `completionHandler`, `RNFBMessagingSerializer.m`). Android e2e `getRNFBTesting().messagingStoreSupportsDisabledStorage()` exercises `ReactNativeFirebaseMessagingStoreImpl` disabled-storage paths. After iOS `:test-cover` and `yarn tests:ios:test:process-coverage`, iOS probe lines appear as hits in `coverage/ios-native/lcov.info` (Android probe hits land in Jacoco). Record them in the [coverage evidence package](../code-coverage/policy.md#coverage-evidence-package); passing probes are not a substitute for that artifact. Test-app vs library codegen (not committed; wipe derived `tests/ios/build/generated/ios`; gitignore `tests/ios/Package.swift` and sibling app dumps): [NewArch-AD-5](../../new-architecture/architecture-decisions.md#newarch-ad-5--commit-generated-code--accepted). +**Probe hits in native coverage:** Messaging e2e `getRNFBTesting().completesNonFCMRemoteNotification()`, `getRNFBTesting().serializeMessagingUserInfo(...)`, and `NativeModules.RNFBTestingMessaging.messagingPreservesExistingDelegate()` exercise product sources (for example `RNFBMessaging+AppDelegate.m` non-FCM `completionHandler`, `RNFBMessagingSerializer.m`). Android e2e `getRNFBTesting().messagingStoreSupportsDisabledStorage()` exercises `ReactNativeFirebaseMessagingStoreImpl` disabled-storage paths. After iOS `:test-cover` and `yarn tests:ios:test:process-coverage`, iOS probe lines appear as hits in `coverage/ios-native/lcov.info` (Android probe hits land in Jacoco). Record them in the [coverage evidence package](../code-coverage/policy.md#coverage-evidence-package); passing probes are not a substitute for that artifact. Test-app vs library codegen (not committed; wipe derived `tests/ios/build/generated/ios`; gitignore `tests/ios/Package.swift` and sibling app dumps): [NewArch-AD-5](../../new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-5--commit-generated-code--accepted). diff --git a/okf-bundle/testing/e2e/run-loop.md b/okf-bundle/testing/e2e/run-loop.md index e838ea591e..1edadcb49d 100644 --- a/okf-bundle/testing/e2e/run-loop.md +++ b/okf-bundle/testing/e2e/run-loop.md @@ -34,7 +34,7 @@ macOS: `yarn tests:macos:test-cover` only — same `:8090` transport, no Detox. #### Test-runner host orchestration (log triage only) -**No commands to run from this section** — for interpreting `:test-cover` logs and CI artifacts only. Patch workflow: [detox-patches.md](../../ci-workflows/detox-patches.md#updating-the-jet-patch-headless). CI triage: [iOS orchestration](../../ci-workflows/ios.md#e2e-test-app-orchestration-detox--jet). +**No commands to run from this section** — for interpreting `:test-cover` logs and CI artifacts only. Patch workflow: [detox-patches.md](../../ci-workflows/detox-patches.md#updating-the-jet-patch-headless). CI triage: [iOS orchestration](../../ci-workflows/ios/orchestration-launch.md#e2e-test-app-orchestration-detox--jet). | Port | Protocol | Role | | --- | --- | --- | @@ -60,7 +60,7 @@ macOS: `yarn tests:macos:test-cover` only — same `:8090` transport, no Detox. GitHub Actions **Testing E2E iOS** adds CI-only steps local `:test-cover` does not run: pre-boot (`boot-simulator.sh`), one filtered **`sim-app.log`** stream, **`wait-for-load-settle.sh`** (threshold **20**) immediately before Detox, and optional video when `record_screens: true`. Host syslog and unfiltered simulator logs are **disabled** to reduce runner baseload. -**Canonical owner:** [iOS CI baseload policy](../../ci-workflows/ios.md#ci-baseload-policy-instrumentation). Artifact names and triage: [simulator logging and video](../../ci-workflows/ios.md#simulator-logging-and-video-troubleshooting). +**Canonical owner:** [iOS CI baseload policy](../../ci-workflows/ios/simulator-reliability.md#ci-baseload-policy-instrumentation). Artifact names and triage: [simulator logging and video](../../ci-workflows/ios/simulator-reliability.md#simulator-logging-and-video-troubleshooting). ### Running one iteration diff --git a/okf-bundle/testing/e2e/slot-devices.md b/okf-bundle/testing/e2e/slot-devices.md index 7ef3cf85e5..fb8729e0be 100644 --- a/okf-bundle/testing/e2e/slot-devices.md +++ b/okf-bundle/testing/e2e/slot-devices.md @@ -38,7 +38,7 @@ Slotted iOS devices use a **repo-neutral base name**: **`RN E2E iOS slot-N`**, w Hosts provisioned before the neutral base still hold `RNFB E2E iOS slot-N` devices (and their `-Detox` clones). Nothing in the runbook selects them, so they are inert; the only reason to remove them is reclaiming disk on a host that is about to run a slotted iOS wave. -This is a **human-operator** procedure. Agents must not run it — `xcrun simctl delete` is not in the [agent command registry](../agent-command-policy.md#canonical-registry), and unregistered direct `simctl` device commands are [forbidden](../commands/forbidden.md#forbidden-always). An agent that needs the migration asks the operator to run it. +This is a **human-operator** procedure. Agents must not run it — `xcrun simctl delete` is not in the [agent command registry](../agent-command-policy.md#canonical-registry), and unregistered direct `simctl` device commands are [forbidden](../agent-command-policy.md#forbidden-always). An agent that needs the migration asks the operator to run it. For the **one** slot `N` being migrated (shown for `N=3`): diff --git a/okf-bundle/testing/firebase-testing-project.md b/okf-bundle/testing/firebase-testing-project.md index 82278b2b23..be4d85a45f 100644 --- a/okf-bundle/testing/firebase-testing-project.md +++ b/okf-bundle/testing/firebase-testing-project.md @@ -160,7 +160,7 @@ RC cases cascade when FIS token fetch fails. Functions emulator tests may still | Record quota-class Jet failure to Cloud Logging via live `e2eCloudMetricsV2` | `packages/app/e2e/cloud-metrics.js`, `tests/globals.js` | | On FIS/quota Jet failure, log `cloud-pressure-analysis` pointer (Cloud Logging filter + summary callable URL) — no per-run summary dump | `tests/e2e/firebase.test.js` | -Attempt 2 uses the same platform-specific drain/reboot as other Jet retries (iOS simulator reboot, Android emulator reboot, etc.) — see [iOS operational notes](../ci-workflows/ios.md#operational-notes). +Attempt 2 uses the same platform-specific drain/reboot as other Jet retries (iOS simulator reboot, Android emulator reboot, etc.) — see [iOS operational notes](../ci-workflows/ios/release-and-tooling.md#operational-notes). **Diagnosing** (any platform Detox step log): diff --git a/okf-bundle/testing/index.md b/okf-bundle/testing/index.md index d9244b45c4..739c7a265c 100644 --- a/okf-bundle/testing/index.md +++ b/okf-bundle/testing/index.md @@ -16,7 +16,7 @@ Owner of every testing topic in the bundle. Pick a file by task; to pick by chan * [native build gate](commands/native-build-gate.md) — [install / patch / fmt gate](commands/native-build-gate.md#install-patch-fmt-gate-blocking) before native `:build` * [fixtures](commands/fixtures.md) — Expo example + documented-path iOS **link**, launch smoke, per-module duplicate ObjC class check (`yarn test-expo-fixture:ios:dupes`), RN CLI prebuilt RNCore iOS **build** (not Detox) * [e2e](commands/e2e.md) — `yarn tests:*`, pre-flight, slots, coverage post-process, [App Check e2e helper secret](commands/e2e.md#app-check-e2e-helper-secret) -* [forbidden (always)](commands/forbidden.md) · [constraints block](commands/constraints.md#command-constraints) (condensed, for prompts) +* [forbidden (always)](agent-command-policy.md#forbidden-always) · [constraints block](commands/constraints.md#command-constraints) (condensed, for prompts) ## Change authoring: [change-authoring-workflow.md](change-authoring-workflow.md) diff --git a/okf-bundle/testing/local-ios-e2e-reproduction.md b/okf-bundle/testing/local-ios-e2e-reproduction.md index 0234142ce4..ec8d4aca64 100644 --- a/okf-bundle/testing/local-ios-e2e-reproduction.md +++ b/okf-bundle/testing/local-ios-e2e-reproduction.md @@ -37,7 +37,7 @@ Until then, treat existing golden/warmed VMs built from **Xcode 26.5** / **`maco ## iOS 26.5 is not a proof path for this ratchet -An **iOS 26.5** simulator runtime (or Tart images seeded with **Xcode 26.5**) may still be useful for **runtime-differential** debugging — for example Metro `localhost` vs `127.0.0.1` behaviour noted in [iOS CI workflows § issue 5](../ci-workflows/ios.md#5-metro-unresponsive-at-launch--waitforactive-hang-active-app). +An **iOS 26.5** simulator runtime (or Tart images seeded with **Xcode 26.5**) may still be useful for **runtime-differential** debugging — for example Metro `localhost` vs `127.0.0.1` behaviour noted in [iOS CI workflows § issue 5](../ci-workflows/ios/orchestration-launch.md#5-metro-unresponsive-at-launch--waitforactive-hang-active-app). It does **not** satisfy: diff --git a/okf-bundle/testing/test-app-dependency-pins.md b/okf-bundle/testing/test-app-dependency-pins.md index b655028c4f..0e79ed863d 100644 --- a/okf-bundle/testing/test-app-dependency-pins.md +++ b/okf-bundle/testing/test-app-dependency-pins.md @@ -10,7 +10,7 @@ timestamp: 2026-09-10T00:00:00Z Canonical owner for **intentional** version locks on the e2e apps (`tests/` mobile, `tests-macos/` macOS), the Expo example / documented-path iOS link closer (`test-expo/`), the RN CLI compile fixture (`test-rn-bare/`), and how the RN/codegen toolchain is selected. Do not “helpfully” bump these via Dependabot merges or drive-by upgrades without coordinating the affected app (and codegen when mobile moves). -Codegen determinism: [NewArch-AD-20](../new-architecture/architecture-decisions.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted). +Codegen determinism: [NewArch-AD-20](../new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted). **Apple CI / local e2e alignment:** dedicated iOS jobs require **Xcode 27** (stable) and default simulator runtime **`iOS 27.0`** ([iOS CI workflows § Apple CI toolchain](../ci-workflows/ios.md#apple-ci-toolchain-xcode-27)); local hosts should match [running e2e § Apple host toolchain](e2e/prerequisites.md#apple-host-toolchain-local). These pins are **test-fixture only** — do not raise RNFB consumer deployment or Xcode floors in product metadata when documenting them. @@ -89,7 +89,7 @@ Mobile `tests/` is on async-storage **3.x** (TurboModule `RNAsyncStorage`). macO 1. Bump `tests/` `react-native` and matching `@react-native/*` / CLI band 2. Bump `test-rn-bare/package.json` to the same RN / CLI / `@react-native/*` in the **same change** 3. Bump `test-expo/package.json` `react-native` / `react` in the **same change** (Expo SDK is separate) -4. Regenerate codegen / rebuild native per [NewArch-AD-20](../new-architecture/architecture-decisions.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted) (`yarn codegen:all` → `scripts/codegen-package.mjs`). Codegen still resolves from **`tests/`** only. +4. Regenerate codegen / rebuild native per [NewArch-AD-20](../new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted) (`yarn codegen:all` → `scripts/codegen-package.mjs`). Codegen still resolves from **`tests/`** only. 5. Keep `tests-macos/` on the `react-native-macos`-compatible pair until that stack can move **macOS (`tests-macos/`)**: @@ -104,8 +104,8 @@ Mobile `tests/` is on async-storage **3.x** (TurboModule `RNAsyncStorage`). macO - [Running e2e § Apple host toolchain](e2e/prerequisites.md#apple-host-toolchain-local) — local Xcode 27 + iOS 27.0 + Device Hub - [iOS CI workflows § Apple CI toolchain](../ci-workflows/ios.md#apple-ci-toolchain-xcode-27) — GHA `xcode-27` gate -- [NewArch-AD-20](../new-architecture/architecture-decisions.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted) — codegen reproducibility / no floating toolchain -- [NewArch-AD-21](../new-architecture/architecture-decisions.md#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete) — ResultT inject **retired** on mobile 0.86 (upstream emits `ResultT`) +- [NewArch-AD-20](../new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-20--pin-the-rncodegen-toolchain-rn-bumps-are-coordinated-breaking-changes--accepted) — codegen reproducibility / no floating toolchain +- [NewArch-AD-21](../new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-21--interim-ios-resultt-alias-without-full-codegen-regen--superseded-exit-complete) — ResultT inject **retired** on mobile 0.86 (upstream emits `ResultT`) - [Other CI — macOS e2e](../ci-workflows/other.md) — macOS pipeline (`tests-macos/`) - [Agent command policy](agent-command-policy.md) — install / patch / fmt gate - [`tests/package.json`](../../tests/package.json) / [`tests-macos/package.json`](../../tests-macos/package.json) / [`test-expo/package.json`](../../test-expo/package.json) / [`test-rn-bare/package.json`](../../test-rn-bare/package.json) — declared pins diff --git a/okf-bundle/testing/validation/evidence-and-handoff.md b/okf-bundle/testing/validation/evidence-and-handoff.md index 6b2309b378..b81dfb433f 100644 --- a/okf-bundle/testing/validation/evidence-and-handoff.md +++ b/okf-bundle/testing/validation/evidence-and-handoff.md @@ -55,7 +55,7 @@ Exit codes must be the **real** ones: the agent shell is zsh, where `${PIPESTATU - [ ] `yarn tests:ios:ruby` when `packages/app/**/*.rb` or `packages/app/__tests__/*_test.rb` touched ([§ iOS Ruby](native-unit.md#ios-ruby-unit-tests); [coverage design](../code-coverage/local.md#ios-ruby-simplecov)) - [ ] `yarn tests:android:unit` when `packages/*/android/**` Java / `src/test/java` changed ([AndroidTest-AD-1](../android-architecture-decisions.md#androidtest-ad-1)) - [ ] `yarn tests:ios:unit` when `packages/*/ios/**` ObjC/C++ or `packages/*/ios/*UnitTests` changed ([IosTest-AD-1](../ios-architecture-decisions.md#iostest-ad-1)) -- [ ] TurboModule wrapper contract ([NewArch-AD-17.1](../../new-architecture/architecture-decisions.md#newarch-ad-171--jest-turbomodule-contract-test--accepted)) when `packages/app/lib/internal/registry/nativeModule.ts`, `nativeModuleAndroidIos.ts`, or TurboModule wrapper behavior changed: `yarn tests:jest -- packages/app/__tests__/nativeModuleContract.test.ts` +- [ ] TurboModule wrapper contract ([NewArch-AD-17.1](../../new-architecture/decisions/events-tests-process.md#newarch-ad-171--jest-turbomodule-contract-test--accepted)) when `packages/app/lib/internal/registry/nativeModule.ts`, `nativeModuleAndroidIos.ts`, or TurboModule wrapper behavior changed: `yarn tests:jest -- packages/app/__tests__/nativeModuleContract.test.ts` - [ ] `yarn compare:types` (stale config entries removed) - [ ] Lint by-tree / by-diff per [§ lint and formatting](lint.md#lint-and-formatting) (frozen `independent-review`: check-only — no `yarn lint:android` / `./gradlew ktlintFormat` / full `yarn lint`) - [ ] E2e green on **every required platform** for the changed module ([platform coverage gate](../e2e/gates.md#platform-coverage-gate-blocking); [harness narrowing gate](../e2e/gates.md#harness-narrowing-gate-blocking); no `.only`; committed `RNFBDebug` remains `false`) From be258ea639b0c80b73326b0d5bc21d9c6bb62a0f Mon Sep 17 00:00:00 2001 From: russellwheatley Date: Fri, 4 Dec 2026 09:04:00 +0000 Subject: [PATCH 4/5] docs(okf): remove work-queue trackers from okf-bundle Four phase trackers (monorepo tooling rollout, App Check iOS provider init, Firestore pipeline coverage, compare-types parity) still lived in the bundle as grandfathered queues, about 128 KB of mutable status next to stable reference, plus an ephemeral prepare benchmark log. Three queues were marked complete; compare-types had not moved since August. Reference docs linked into them for live status. The files are removed (git history keeps them). Reference docs no longer link into them or cite their phase ids, and the one durable fact that only lived in a queue (known gaps in the lint:deps allowlist) moves to prepare-and-cache.md. The policy drops the grandfathered exception: queues live in Linear project documents and no tracker goes back into the repo. --- okf-bundle/CONTEXT.md | 1 - okf-bundle/documentation-policy.md | 10 +- okf-bundle/index.md | 4 +- .../architecture-decisions.md | 9 +- okf-bundle/monorepo-tooling/index.md | 1 - .../monorepo-tooling/prepare-and-cache.md | 14 +- .../prepare-benchmark-baseline.md | 58 --- okf-bundle/monorepo-tooling/work-queue.md | 391 ----------------- .../app-check/architecture-decisions.md | 6 +- okf-bundle/packages/app-check/index.md | 1 - .../app-check/ios-provider-init-work-queue.md | 230 ---------- okf-bundle/packages/firestore/index.md | 1 - .../firestore/pipeline-coverage-work-queue.md | 415 ------------------ .../pipeline-implementation-workflow.md | 4 +- .../firestore/pipeline-platform-parity.md | 6 +- .../firestore/pipeline-sdk-support-audit.md | 13 +- okf-bundle/packages/firestore/pipelines.md | 9 +- .../testing/change-authoring-workflow.md | 2 +- okf-bundle/testing/code-coverage/policy.md | 1 - .../testing/compare-types-work-queue.md | 403 ----------------- okf-bundle/testing/e2e/gates.md | 2 +- okf-bundle/testing/iteration-vocabulary.md | 4 +- 22 files changed, 38 insertions(+), 1547 deletions(-) delete mode 100644 okf-bundle/monorepo-tooling/prepare-benchmark-baseline.md delete mode 100644 okf-bundle/monorepo-tooling/work-queue.md delete mode 100644 okf-bundle/packages/app-check/ios-provider-init-work-queue.md delete mode 100644 okf-bundle/packages/firestore/pipeline-coverage-work-queue.md delete mode 100644 okf-bundle/testing/compare-types-work-queue.md diff --git a/okf-bundle/CONTEXT.md b/okf-bundle/CONTEXT.md index 4694663f5b..b2cc0b61bd 100644 --- a/okf-bundle/CONTEXT.md +++ b/okf-bundle/CONTEXT.md @@ -20,7 +20,6 @@ The bundle is the factory shelf for changing this repo: stable reference that ag | `testing/commands/`, `authoring/`, `validation/`, `e2e/`, `code-coverage/` | Task-sized sections of `agent-command-policy.md`, `change-authoring-workflow.md`, `validation-checklist.md`, `running-e2e.md`, `coverage-design.md` | | `ci-workflows/`, `monorepo-tooling/`, `new-architecture/`, `packages//` | Area owners, each with an `index.md` | | `ci-workflows/ios/`, `new-architecture/decisions/` | Task-sized sections of `ci-workflows/ios.md` and `new-architecture/architecture-decisions.md` (the ADR catalog keeps a one-line decision index) | -| `**/*work-queue.md` | Grandfathered ephemeral queues; never create new ones ([work-queue documents](documentation-policy.md#work-queue-documents)) | ## Writing here diff --git a/okf-bundle/documentation-policy.md b/okf-bundle/documentation-policy.md index 9c62e7aa7e..1a4e3b4c26 100644 --- a/okf-bundle/documentation-policy.md +++ b/okf-bundle/documentation-policy.md @@ -17,10 +17,10 @@ Single source of truth for OKF knowledge and commit wording. Other OKF docs/work | Kind | Where it lives | What it contains | |------|----------------|------------------| | **Public (durable)** | GitHub-**public** reference docs and indexes under `okf-bundle/` (not work-queue files) | Stable API names, registry IDs, SDK versions, classifications, verification **methods**, architecture, canonical commands | -| **Ephemeral** | Linear **project** work-queue documents (grandfathered `okf-bundle/**/*work-queue.md` until migrated) | Session phase/probe IDs, **planned commit subjects** (`commit_subject`), gate state, `next_work_type`, snapshot labels, dated banners, run counts | +| **Ephemeral** | Linear **project** work-queue documents | Session phase/probe IDs, **planned commit subjects** (`commit_subject`), gate state, `next_work_type`, snapshot labels, dated banners, run counts | | **Private** | Linear issues and internal docs | Issue IDs, discussion, non-public commercial terms. Not GitHub-public; not the same as ephemeral | -GitHub-public **reference** docs, `AGENTS.md`, commits, and PR titles must **not** contain ephemeral fields (for example work-queue gates) or private items (for example Linear issue identifiers). Queue **state** lives on Linear project documents, not in new git files. Grandfathered repo `*work-queue.md` files may still hold ephemeral fields until pickup. +GitHub-public **reference** docs, `AGENTS.md`, commits, and PR titles must **not** contain ephemeral fields (for example work-queue gates) or private items (for example Linear issue identifiers). Queue **state** lives on Linear project documents, not in new git files. **Rules** @@ -52,7 +52,7 @@ Scan the **entire** `okf-bundle/` tree against: | **DRY** | No duplicated procedures, policy paragraphs, or ephemeral snapshots outside work queues | | **Efficiency** | Shortest text that stays **complete and true** ([§ Efficiency](#efficiency)). Completeness wins over brevity | | **Link hygiene** | Cross-links resolve; indexes list canonical entry points | -| **Durability** | No ephemeral or private fields in GitHub-public **reference** docs, commits, or PR titles. Queue state lives on Linear (or a grandfathered repo file until pickup). Linear issue identifiers stay off GitHub | +| **Durability** | No ephemeral or private fields in GitHub-public **reference** docs, commits, or PR titles. Queue state lives on Linear. Linear issue identifiers stay off GitHub | **Report-only** during `independent-review` ([frozen tree](testing/authoring/review-and-commit.md#frozen-tree)). **Fix before `git commit`**. Do not add OKF after a frozen review without another `independent-review`. Work-queue edits still follow this split. @@ -81,9 +81,9 @@ Work queues are **intentionally ephemeral**: phases, **commit subjects**, gates, **Home:** a Linear **project** document on the issue's Linear project. Not a git file, and not the issue description. One copy. Document shape: How the Work Queue Orchestrator Works. Issue pointer rules: Cross Platform Issue Authoring & Agent Workflow Guide, Step 10. -**Do not create** new `okf-bundle/**/*work-queue.md` files. +**Do not create** `*work-queue.md` files, or any other tracker or phase log, anywhere in the repo. -**Existing repo queues:** stay the source of truth until that item is next picked up. On pickup, copy the file into a Linear project document, point the Linear issue at it (`Queue: linear-work-queue`), and delete the file in the same change. Do not dual-write. +**Old repo queues:** none remain in the tree; earlier `okf-bundle/**/*work-queue.md` files are in git history only. To resume one, copy it from history into a Linear project document and point the Linear issue at it (`Queue: linear-work-queue`). Do not restore it to the repo. Work queues record **gates**, **`next_work_type`**, **`validation_tier`**, and **`commit_subject`** using field names and allowed values from [iteration vocabulary](testing/iteration-vocabulary.md). Gate semantics, workflow rules, and `commit_subject` recording: [change authoring workflow](testing/change-authoring-workflow.md) (including [§ commit](testing/authoring/review-and-commit.md#commit)). Public OKF owns those terms, gates, and commands. They do **not** name agent roles, dispatch instructions, or session choreography. diff --git a/okf-bundle/index.md b/okf-bundle/index.md index ae399e1a21..2f725036c0 100644 --- a/okf-bundle/index.md +++ b/okf-bundle/index.md @@ -37,13 +37,13 @@ okf_version: '0.1' - [TurboModule / New Architecture](/new-architecture/index.md) — [ADR](/new-architecture/architecture-decisions.md); Codegen TurboModules (library `includesGeneratedCode` vs test-app build-time — [NewArch-AD-5](/new-architecture/decisions/codegen-and-toolchain.md#newarch-ad-5--commit-generated-code--accepted)); coordinated New Architecture break - [iOS SPM native integration decisions](/ios-spm-native-imports.md) — dual imports, Swift-product helpers, runtime framework embedding, Expo precompiled module linkage repair - [iOS RNCore podspec invariants](/ios-rncore-podspec.md) — Clang non-modular-includes flag and `pod_target_xcconfig` order under `use_frameworks!` -- [Monorepo tooling](/monorepo-tooling/index.md) — Nx local cache, deterministic prepare graph, declaration maps, dependency-cycle linting, dev watch; decisions (ADR) + rollout queue; [maintainer publish](/monorepo-tooling/maintainer-publish.md) +- [Monorepo tooling](/monorepo-tooling/index.md) — Nx local cache, deterministic prepare graph, declaration maps, dependency-cycle linting, dev watch; decisions (ADR); [maintainer publish](/monorepo-tooling/maintainer-publish.md) # Packages - [AI](/packages/ai/index.md) — Agent Platform / Vertex backend naming, compare-types, generative models - [App](/packages/app/index.md) — core app / Expo plugin / iOS SPM helpers; Expo example + documented-path iOS link (`test-expo/`); RN CLI prebuilt RNCore iOS compile (`test-rn-bare/`) -- [App Check](/packages/app-check/index.md) — iOS provider-factory init (pending + fail-closed), ADRs + work queue for #9116 +- [App Check](/packages/app-check/index.md) — iOS provider-factory init (pending + fail-closed), ADRs for #9116 - [Auth](/packages/auth/index.md) — modular API type parity, platform matrix, `compare:types` - [Firestore](/packages/firestore/index.md) — Pipelines architecture, parity, e2e coverage - [Functions](/packages/functions/index.md) — callables; `FunctionsError` not usable as `instanceof` under consumer types diff --git a/okf-bundle/monorepo-tooling/architecture-decisions.md b/okf-bundle/monorepo-tooling/architecture-decisions.md index d6700d138e..51c47191d9 100644 --- a/okf-bundle/monorepo-tooling/architecture-decisions.md +++ b/okf-bundle/monorepo-tooling/architecture-decisions.md @@ -8,7 +8,7 @@ timestamp: 2026-07-26T00:00:00Z # Monorepo tooling decisions (ADR) -**Canonical owner of durable build-tooling decisions.** Each entry is a decision plus rationale and the rejected alternatives. Design detail lives in [prepare, cache, and watch design](prepare-and-cache.md); ephemeral rollout state lives in the [rollout work queue](work-queue.md). Those docs **link here** for the "why" — they do not restate decisions. +**Canonical owner of durable build-tooling decisions.** Each entry is a decision plus rationale and the rejected alternatives. Design detail lives in [prepare, cache, and watch design](prepare-and-cache.md). That doc **links here** for the "why" and does not restate decisions. **Policy:** [OKF documentation and commit policy](../documentation-policy.md). @@ -45,7 +45,7 @@ Adopt Nx **local computation cache** by adding an `nx.json`. Keep `lerna run` as **Why:** Lerna already routes `lerna run` through Nx; an `nx.json` unlocks caching and graph ordering with no new task runner. Local cache turns a no-op `yarn lerna:prepare` and unchanged-package installs into near-instant cache replays, and rebuilds only changed packages + dependents. -**Prerequisite — update Lerna to current:** bump `lerna` to the latest release before this work; that pulls a current bundled `nx`, which (a) supports the `nx.json` keys used here (`neverConnectToCloud`, per-target `cache`/`inputs`/`outputs`, `namedInputs`) and (b) includes the `nx watch --all --initialRun` fix needed later. Tracked as [work-queue MT0.0](work-queue.md#mt00--update-lerna-to-current-prerequisite). +**Prerequisite — update Lerna to current:** bump `lerna` to the latest release before this work; that pulls a current bundled `nx`, which (a) supports the `nx.json` keys used here (`neverConnectToCloud`, per-target `cache`/`inputs`/`outputs`, `namedInputs`) and (b) includes the `nx watch --all --initialRun` fix needed later. **No-cloud everywhere:** `neverConnectToCloud: true` blocks _connecting/setup_ only — per Nx docs it does **not** disable cloud usage at command time. The runtime guard is `NX_NO_CLOUD=true` (or `--no-cloud`), so it is applied in **both** places: on the local `lerna:prepare` entrypoint (via `cross-env`, see [MonoTool-AD-4](#monotool-ad-4--one-inlined-prepare-command-no-wrapper-script--accepted)) and in every CI job that runs Nx ([MonoTool-AD-8](#monotool-ad-8--nxcache-shared-on-ci-not-on-publish--accepted)). @@ -94,7 +94,7 @@ The only prepare entrypoint stays **`yarn lerna:prepare`**. Its inline body gain **Why:** `lerna run prepare` is already a single inlined line and already routes through Nx; with [MonoTool-AD-1](#monotool-ad-1--nx-local-cache-via-the-lerna-runner-no-turborepo-no-nx-cloud--accepted) + [MonoTool-AD-3](#monotool-ad-3--build-order-via-devdependencies-not-manual-phase-scripts--accepted) it becomes cached and correctly ordered with zero new surface and zero churn to the many OKF/agent docs that reference `yarn lerna:prepare`. The `NX_NO_CLOUD=true` prefix is the runtime no-cloud guard ([MonoTool-AD-1](#monotool-ad-1--nx-local-cache-via-the-lerna-runner-no-turborepo-no-nx-cloud--accepted)). Agents keep a single canonical command; scoped prepare is removed from docs. -**Ordering fallback:** the clean-tree ordering relies on `lerna run prepare` honoring the graph. Lerna's own topological `--sort` on the [MonoTool-AD-3](#monotool-ad-3--build-order-via-devdependencies-not-manual-phase-scripts--accepted) devDep edges should order `app` first regardless of Nx; the `nx.json` `dependsOn: ["^prepare"]` additionally drives the cache graph. If `lerna run` is ever found **not** to expand `^prepare`, the drop-in remedy is to make the inline body `cross-env NX_NO_CLOUD=true nx run-many -t prepare` (same entrypoint name). MT1 acceptance explicitly tests repeatable clean-tree ordering to catch this. +**Ordering fallback:** the clean-tree ordering relies on `lerna run prepare` honoring the graph. Lerna's own topological `--sort` on the [MonoTool-AD-3](#monotool-ad-3--build-order-via-devdependencies-not-manual-phase-scripts--accepted) devDep edges should order `app` first regardless of Nx; the `nx.json` `dependsOn: ["^prepare"]` additionally drives the cache graph. If `lerna run` is ever found **not** to expand `^prepare`, the drop-in remedy is to make the inline body `cross-env NX_NO_CLOUD=true nx run-many -t prepare` (same entrypoint name). Check repeatable clean-tree ordering whenever the prepare graph changes to catch this. **Rejected:** A `scripts/rnfb-prepare.sh` wrapper — adds surface/churn for no gain over the existing inlined line. @@ -159,7 +159,7 @@ CI PR/main jobs may restore/save `.nx/cache` via `actions/cache` (keyed on `yarn ## MonoTool-AD-9 — Dev watch rebuilds prepare; e2e TDD rerun is event-driven off Metro — **Deferred** -**Deferred to a gap-analysis pre-phase** ([work-queue MT-WATCH](work-queue.md#mt-watch--dev-watch--e2e-rerun-gap-analysis-pre-phase--deferred)). No incremental dev-watch/hot-reload loop exists today; rather than lock a mechanism now, the direction below is recorded and the details are driven by a dedicated analysis phase that is **not on the critical path** for the cache/graph/declaration-map/lint work. +**Deferred to a gap-analysis pre-phase.** No incremental dev-watch/hot-reload loop exists today; rather than lock a mechanism now, the direction below is recorded and the details are driven by a dedicated analysis phase that is **not on the critical path** for the cache/graph/declaration-map/lint work. **Direction:** provide a root **`dev:watch`** that uses `nx watch` to rebuild `dist/**` on `lib/**` change. For the e2e TDD loop, drive test rerun from a **Metro bundle-ready event** (HMR `update-done` / `onBundleBuilt`), not a fixed `sleep`. Because RNFB owns the Jet test runner and its HTTP control plane (port 8091), add a control action to re-run the loaded suite on that signal. @@ -238,7 +238,6 @@ Detail: [prepare-and-cache § patch-package prepare](prepare-and-cache.md#patch- | ---------------------------------------------- | -------------------------------------------------------------------- | | Design detail (cache, graph, watch, benchmark) | [prepare-and-cache.md](prepare-and-cache.md) | | Maintainer publish procedure | [maintainer-publish.md](maintainer-publish.md) | -| Ephemeral rollout state | [work-queue.md](work-queue.md) | | Agent shell commands | [agent command policy](../testing/agent-command-policy.md) | | Change loop / gates | [change authoring workflow](../testing/change-authoring-workflow.md) | | Doc/commit policy | [documentation policy](../documentation-policy.md) | diff --git a/okf-bundle/monorepo-tooling/index.md b/okf-bundle/monorepo-tooling/index.md index bb4b7463f9..f91334393a 100644 --- a/okf-bundle/monorepo-tooling/index.md +++ b/okf-bundle/monorepo-tooling/index.md @@ -9,7 +9,6 @@ Build-tooling decisions and design for the React Native Firebase monorepo: task - [Architecture decisions (ADR)](architecture-decisions.md) — **canonical owner** of durable tooling decisions (the "what + why"); other docs reference it - [Prepare, cache, and watch design](prepare-and-cache.md) — durable design: Nx local cache, deterministic prepare graph, declaration maps, dependency-cruiser, dev watch + TDD hook chain, benchmark methodology - [Maintainer publish](maintainer-publish.md) — **canonical owner** of the Publish workflow procedure: main-only API docs deploy, branch dist-tags, same-publish recovery -- [Rollout work queue](work-queue.md) — ephemeral phase tracker, per-item steps, gates, and acceptance criteria ## Scope diff --git a/okf-bundle/monorepo-tooling/prepare-and-cache.md b/okf-bundle/monorepo-tooling/prepare-and-cache.md index c5f964f940..8b58746ec5 100644 --- a/okf-bundle/monorepo-tooling/prepare-and-cache.md +++ b/okf-bundle/monorepo-tooling/prepare-and-cache.md @@ -8,7 +8,7 @@ timestamp: 2026-07-26T00:00:00Z # Prepare, cache, and watch design -Durable design for RNFB monorepo build tooling. Decisions (the "what + why") are owned by [architecture-decisions.md](architecture-decisions.md); this doc holds the design detail those decisions imply. Rollout order and acceptance criteria are ephemeral — see the [rollout work queue](work-queue.md). +Durable design for RNFB monorepo build tooling. Decisions (the "what + why") are owned by [architecture-decisions.md](architecture-decisions.md); this doc holds the design detail those decisions imply. Rollout order and acceptance criteria are ephemeral and are not kept here. **Policy:** [OKF documentation and commit policy](../documentation-policy.md). **Canonical prepare command and agent rules:** [agent command policy](../testing/agent-command-policy.md) — this doc does not redefine the entrypoint. @@ -191,7 +191,7 @@ Enable in the shared base and the two standalone configs only ([MonoTool-AD-5](a "declarationMap": true ``` -bob's `typescript` (tsc) target emits `.d.ts` + `.d.ts.map` beside `dist/typescript/**`; IDE go-to-definition lands on `lib/**` source. Because each package's `files` already publishes `lib` (source) alongside `dist`, the emitted map resolves for **external** consumers too — verify by opening a published `.d.ts.map` and confirming its `sources` point at the shipped `lib/*.ts` with no absolute paths leaking (see [work-queue MT2 acceptance](work-queue.md#mt2--declaration-maps)). +bob's `typescript` (tsc) target emits `.d.ts` + `.d.ts.map` beside `dist/typescript/**`; IDE go-to-definition lands on `lib/**` source. Because each package's `files` already publishes `lib` (source) alongside `dist`, the emitted map resolves for **external** consumers too — verify by opening a published `.d.ts.map` and confirming its `sources` point at the shipped `lib/*.ts` with no absolute paths leaking. ## Dependency-cycle linting @@ -200,17 +200,18 @@ bob's `typescript` (tsc) target emits `.d.ts` + `.d.ts.map` beside `dist/typescr - `no-circular` — no import cycles - `not-to-own-dist` — **scoped** rule: `lib/**` must not import its **own** package's built output via a _relative_ `../dist/**` / `./dist/**` path. It must **not** forbid the intentional hub API `@react-native-firebase/app/dist/module/...`, which ~15 satellites import by design (mapped to type stubs via each package's tsconfig `paths`). A blanket `no lib → **/dist/**` rule would fail on the **current** tree — see [MonoTool-AD-6](architecture-decisions.md#monotool-ad-6--dependency-cycle-linting-via-dependency-cruiser-as-lintdeps--accepted). - graph allowlist — satellites import only `@react-native-firebase/app` (its published subpaths); `ai` → `auth`/`app-check`; `vertexai` → `ai` +- known gaps — type-only imports bypass the graph allowlist (value imports are enforced; matches the existing `ai` / `vertexai` patterns), and a relative cross-package `../..//dist/` import bypasses allowlist path matching (the tree uses alias imports only; `not-to-own-dist` still catches same-package relative `dist`) **Config scoping** (`.dependency-cruiser.cjs`) — required for correct, fast, false-positive-free runs: - `doNotFollow` / `exclude` for `node_modules`, `packages/*/dist/**`, `packages/*/__tests__/**`, `packages/*/e2e/**` so the built output and tests are not analysed as source. -- `options.tsConfig` + `enhancedResolveOptions` so the `@react-native-firebase/*` path aliases resolve; otherwise cross-package edges are silently unresolved and the MT4 allowlist has nothing to enforce. Verify one real cross-package edge is actually detected (not skipped as unresolvable). +- `options.tsConfig` + `enhancedResolveOptions` so the `@react-native-firebase/*` path aliases resolve; otherwise cross-package edges are silently unresolved and the graph allowlist has nothing to enforce. Verify one real cross-package edge is actually detected (not skipped as unresolvable). **Agent/CI wiring** (commands and gates): [validation checklist § lint](../testing/validation/lint.md#lint-and-formatting), [change authoring § validation evidence](../testing/authoring/gates.md#validation-evidence-blocking). Optional non-CI `lint:deps-report` (HTML) for debugging. ## Developer watch and the e2e TDD hook chain — **deferred (gap-analysis pre-phase)** -> **Deferred.** No incremental dev-watch / hot-reload loop exists today. The whole watch + event-driven-rerun design is deferred to a **gap-analysis pre-phase** ([work-queue MT-WATCH](work-queue.md#mt-watch--dev-watch--e2e-rerun-gap-analysis-pre-phase--deferred)) that produces detailed, verified analysis before any implementation. The prepare/cache/graph/declaration-map/lint work below and above does **not** depend on it. The command sketches here are **inputs to that analysis, not accepted commands** — they carry known defects called out inline. +> **Deferred.** No incremental dev-watch / hot-reload loop exists today. The whole watch + event-driven-rerun design is deferred to a **gap-analysis pre-phase** that produces detailed, verified analysis before any implementation. The prepare/cache/graph/declaration-map/lint work below and above does **not** depend on it. The command sketches here are **inputs to that analysis, not accepted commands** — they carry known defects called out inline. **Bundling premise:** per [running e2e § Rules #3](../testing/e2e/rules.md#rules) (canonical owner). The inner loop is therefore `lib` edit → `dist` rebuild → Metro re-bundle → test rerun ([MonoTool-AD-9](architecture-decisions.md#monotool-ad-9--dev-watch-rebuilds-prepare-e2e-tdd-rerun-is-event-driven-off-metro--deferred)). @@ -224,7 +225,7 @@ nx watch --all -- nx run-many -t prepare -p $NX_PROJECT_NAME - Watches `packages/*/lib/**`; incremental bob rebuild into `dist/`. - **Command caveats to resolve in the pre-phase:** - - `--all --initialRun` was a **no-op bug** fixed only Aug-2025 (nx PR #32282); pin/verify the bundled nx version (updating Lerna to current pulls a current nx — see [work-queue prerequisite](work-queue.md#mt00--update-lerna-to-current-prerequisite)). Do the first pass explicitly with `nx run-many -t prepare` instead of trusting `--initialRun`. + - `--all --initialRun` was a **no-op bug** fixed only Aug-2025 (nx PR #32282); pin/verify the bundled nx version (updating Lerna to current pulls a current nx). Do the first pass explicitly with `nx run-many -t prepare` instead of trusting `--initialRun`. - `$NX_PROJECT_NAME` is **comma-joined** when several projects change in one watch batch, so `nx run :prepare` is invalid — use `nx run-many -t prepare -p $NX_PROJECT_NAME`. - Unit TDD: `yarn tests:jest --watch -- packages//__tests__/.test.ts` (same-package imports resolve to `../lib`; cross-package needs upstream `dist`). @@ -253,12 +254,11 @@ A macOS shell script (`scripts/benchmark-prepare.sh`) records median-of-3 timing | C | No-op rebuild | after B; no edits | `yarn lerna:prepare` | | D | Single-package edit | after B; touch one `packages/firestore/lib/*` file | `yarn lerna:prepare` | -Record pre-Nx baselines (B/C/D before `nx.json`) and post-Nx numbers; C and D are where the local cache shows. A macOS-only script is representative for CI too: **most RNFB CI runs on macOS runners**, so a local macOS median is a valid proof of the CI gain (no separate Linux capture needed). Results live in the ephemeral [rollout work queue](work-queue.md) / a benchmarks note, not in this durable doc. +Record pre-Nx baselines (B/C/D before `nx.json`) and post-Nx numbers; C and D are where the local cache shows. A macOS-only script is representative for CI too: **most RNFB CI runs on macOS runners**, so a local macOS median is a valid proof of the CI gain (no separate Linux capture needed). Results live in an ephemeral work-queue document or a benchmarks note, not in this durable doc. ## Related docs | Topic | Document | | --------------------------------- | ---------------------------------------------------------------------------------------------------- | | Decisions + rejected alternatives | [architecture-decisions.md](architecture-decisions.md) | -| Rollout phases, gates, acceptance | [work-queue.md](work-queue.md) | | Canonical prepare/e2e commands | [agent command policy](../testing/agent-command-policy.md), [running e2e](../testing/running-e2e.md) | diff --git a/okf-bundle/monorepo-tooling/prepare-benchmark-baseline.md b/okf-bundle/monorepo-tooling/prepare-benchmark-baseline.md deleted file mode 100644 index 328dcc5f83..0000000000 --- a/okf-bundle/monorepo-tooling/prepare-benchmark-baseline.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -type: Ephemeral -title: Prepare benchmark baseline -description: Ephemeral pre- and post-Nx benchmark output for MT0.3 / MT1. -tags: [monorepo, tooling, benchmark, prepare, ephemeral] -timestamp: 2026-07-10T21:30:00Z ---- - -# Prepare benchmark baseline - -Ephemeral MT0.3 / MT1 note. These numbers are baseline evidence for the monorepo tooling rollout and are intentionally not part of the durable prepare/cache design. - -Command for both runs: - -```bash -bash ./scripts/benchmark-prepare.sh -``` - -## Pre-Nx baseline (MT0.3) - -Environment notes: - -- Host: macOS (`darwin 25.5.0`). -- Tree state: `nx.json` absent before the benchmark run. -- Benchmark logs: `.tmp/prepare-benchmarks/20260710-122118/`. -- Script scenario D applies and then removes a temporary comment in `packages/firestore/lib/index.ts` so content-hash-based runners observe a real single-package edit. -- First sandboxed attempt exited before timing because the sandbox could not remove a few ignored `node_modules` entries; the recorded run below was rerun unsandboxed and exited 0. - -| Scenario | Name | Median (s) | Runs (s) | -| -------- | ------------------- | ---------- | ------------------------- | -| A | Cold install | 125.583 | 125.583, 138.092, 122.102 | -| B | Full rebuild | 23.686 | 24.171, 23.686, 23.461 | -| C | No-op rebuild | 23.694 | 23.555, 23.811, 23.694 | -| D | Single-package edit | 23.758 | 23.849, 23.758, 23.515 | - -Exit code: 0. - -## Post-Nx with cache (MT1) - -Environment notes: - -- Host: macOS (`darwin 25.5.0`). -- Tree state: `nx.json` present; `yarn lerna:prepare` uses `NX_NO_CLOUD=true`; Nx local cache enabled (`.nx/cache`). -- Benchmark logs: `.tmp/prepare-benchmarks/20260710-152608/`. -- Scenario D uses the same reversible firestore comment marker as the pre-Nx run. -- Scenario B resets `packages/*/dist` and `packages/*/plugin/build` but retains `node_modules` and `.nx/cache` from prior scenarios (matches warm-tree full-rebuild after cold install). -- Scenario D first iteration (5.270s) is a cache miss for the edited package; iterations 2–3 are warm cache hits (~1.44s). - -| Scenario | Name | Median (s) | Runs (s) | Pre-Nx median (s) | Speedup | -| -------- | ------------------- | ---------- | ---------------------- | ----------------- | ----------------------------------------- | -| A | Cold install | 95.079 | 93.605, 95.079, 95.855 | 125.583 | ~1.3× | -| B | Full rebuild | 1.880 | 1.980, 1.880, 1.865 | 23.686 | ~12.6× | -| C | No-op rebuild | 1.410 | 1.494, 1.409, 1.410 | 23.694 | ~16.8× | -| D | Single-package edit | 1.457 | 5.270, 1.457, 1.437 | 23.758 | ~16.3× (median; first run 5.270s on miss) | - -Exit code: 0. - -**Takeaway:** Nx local cache materially improves repeat `yarn lerna:prepare` (B/C/D ~24s → ~1.4–1.9s). Cold install (A) still dominated by `yarn` link/postinstall; post-Nx cold install is modestly faster (~95s vs ~126s), likely from cache replay during postinstallDev prepare. diff --git a/okf-bundle/monorepo-tooling/work-queue.md b/okf-bundle/monorepo-tooling/work-queue.md deleted file mode 100644 index abf61c49de..0000000000 --- a/okf-bundle/monorepo-tooling/work-queue.md +++ /dev/null @@ -1,391 +0,0 @@ ---- -type: Reference -title: Monorepo tooling rollout work queue -description: Ephemeral phase tracker for rolling out Nx local cache, deterministic prepare graph, declaration maps, dependency-cycle linting, and dev watch in the React Native Firebase monorepo. -tags: [monorepo, tooling, nx, work-queue, rollout] -timestamp: 2026-07-10T00:00:00Z ---- - -# Monorepo tooling — rollout work queue - -> **COMPLETE (2026-07-11):** **MT0.0–MT4** + docs committed. **MTV** closed — validation + review **GREEN**; branch ready for PR. **Next pickup: MT-WATCH** (deferred) or PR. -> **Goal/order:** update Lerna → guardrails first (cycle lint, docs, benchmark) → deterministic cached prepare (graph + `nx.json` incl. complete outputs + scoped inputs + no-cloud + `ai` split) → declaration maps → dependency-rule hardening → full validation. Dev watch / e2e-rerun is **deferred** to a later gap-analysis pre-phase (not on the critical path). - -Ephemeral tracker; see [OKF policy](../documentation-policy.md). Work types / tiers / gate field ids: [iteration vocabulary](../testing/iteration-vocabulary.md). **Loop, gates, host rule, harness:** [change authoring workflow](../testing/change-authoring-workflow.md) — not restated. **Agent commands:** [agent command policy](../testing/agent-command-policy.md) only — no `yarn workspace … prepare`, no Jet probes. - -Durable decisions: **[architecture-decisions.md](architecture-decisions.md)**. Design detail: **[prepare-and-cache.md](prepare-and-cache.md)**. - ---- - -## Locked decisions (index) - -| ADR | Decision | -| -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | -| [MonoTool-AD-1](architecture-decisions.md#monotool-ad-1--nx-local-cache-via-the-lerna-runner-no-turborepo-no-nx-cloud--accepted) | Nx local cache via Lerna runner; no Turborepo; no Nx Cloud | -| [MonoTool-AD-2](architecture-decisions.md#monotool-ad-2--keep-lerna-for-versioning-and-publish--accepted) | Keep Lerna for versioning + publish | -| [MonoTool-AD-3](architecture-decisions.md#monotool-ad-3--build-order-via-devdependencies-not-manual-phase-scripts--accepted) | Build order via `devDependencies` | -| [MonoTool-AD-4](architecture-decisions.md#monotool-ad-4--one-inlined-prepare-command-no-wrapper-script--accepted) | One inlined prepare command; no wrapper script | -| [MonoTool-AD-5](architecture-decisions.md#monotool-ad-5--keep-react-native-builder-bob-emit-declaration-maps--accepted) | Keep bob; emit declaration maps | -| [MonoTool-AD-6](architecture-decisions.md#monotool-ad-6--dependency-cycle-linting-via-dependency-cruiser-as-lintdeps--accepted) | dependency-cruiser as `lint:deps` | -| [MonoTool-AD-7](architecture-decisions.md#monotool-ad-7--ai-test-fixtures-are-a-jest-prerequisite-not-a-build-step--accepted) | AI fixtures = Jest prerequisite, not build step | -| [MonoTool-AD-8](architecture-decisions.md#monotool-ad-8--nxcache-shared-on-ci-not-on-publish--accepted) | `.nx/cache` on CI (with `NX_NO_CLOUD`), not on publish | -| [MonoTool-AD-9](architecture-decisions.md#monotool-ad-9--dev-watch-rebuilds-prepare-e2e-tdd-rerun-is-event-driven-off-metro--deferred) | Dev watch + e2e rerun off Metro — **Deferred** (gap-analysis pre-phase) | -| [MonoTool-AD-10](architecture-decisions.md#monotool-ad-10--generated-version-files-are-declared-cache-outputs-not-committed--accepted) | Generated version files are declared cache `outputs`, not committed | -| [MonoTool-AD-11](architecture-decisions.md#monotool-ad-11--scope-prepare-cache-inputs-with-a-jssource-namedinput--accepted) | Scope `prepare` cache inputs via a `jsSource` namedInput | -| [MonoTool-AD-12](architecture-decisions.md#monotool-ad-12--never-nx-cache-prepare-when-the-script-is-patch-package--accepted) | Never Nx-cache `prepare` when the script is `patch-package` | - ---- - -## Phase ordering - -| Phase | Scope | Depends on | Why | -| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | --------------------------------------------------------------------------------- | -| **MT0.0** | Update `lerna` to current (pulls current bundled `nx`) | — | Prereq: nx.json keys + `nx watch` fixes; cheap | -| **MT0.1** | dependency-cruiser `lint:deps` (`no-circular`) + scoped config + CI + change-authoring gate | MT0.0 | Guardrail; cheap; catches cycles before graph edits | -| **MT0.2** | Durable OKF docs (this bundle) | — | **Landed** (planning + adversarial-review revision) | -| **MT0.3** | `scripts/benchmark-prepare.sh` + pre-Nx baseline numbers | MT0.0 | Baseline before cache claims | -| **MT1** | devDependency graph (17 pkgs) + `nx.json` (scoped `inputs` + complete `outputs` + no-cloud) + inline prepare (name unchanged) + `ai` prepare split + gated AI fetch + CI `.nx/cache` (`NX_NO_CLOUD`) | MT0.3 | Deterministic, cached prepare | -| **MT2** | `declarationMap` in base + `ai` + `vertexai` tsconfig | MT1 | IDE go-to-definition; cheap follow-on | -| **MT4** | dependency-cruiser rule hardening (`not-to-own-dist` scoped + hub/chain allowlist) | MT1 | Enforce graph after devDeps land | -| **MT-WATCH** | **Deferred** — gap-analysis pre-phase: dev watch + event-driven e2e rerun | MT1 | Not built today; needs detailed analysis before implementation; off critical path | -| **MTV** | Branch-wide validation | MT1, MT2, MT4 | Merge gate (MT-WATCH not required) | - ---- - -## Resume checklist - -Gate prerequisites before any `:test-cover` ([host rule](../testing/change-authoring-workflow.md#host-rule)): - -1. [Pre-flight](../testing/running-e2e.md#pre-flight-is-the-host-clear-to-start): [host-clear probes](../testing/running-e2e.md#host-clear-probes), [services ready](../testing/running-e2e.md#2-services-ready), [harness matches validation tier](../testing/running-e2e.md#3-harness-matches-validation-tier); [one :test-cover at a time](../testing/running-e2e.md#one-test-cover-at-a-time); [frozen tree](../testing/change-authoring-workflow.md#frozen-tree) for `independent-review`. -2. Most items here are config/build/docs (no `:test-cover`); e2e applies only where the row's `validation_tier` names it (**MTV**, and the deferred **MT-WATCH** if/when it reaches implementation). - ---- - -## Per-item detail - -Each item uses the [change authoring primary loop](../testing/change-authoring-workflow.md#primary-loop) (`documentation?` before frozen `independent-review`). Gate fields: [iteration vocabulary](../testing/iteration-vocabulary.md). No item touches `packages/*/lib/**` runtime or `android/ios` native, so **`coverage_evidence_gate: n/a`** throughout (verify per item against the [coverage grep](../testing/coverage-design.md)). - -### MT0.0 — Update Lerna to current (prerequisite) - -- **next_work_type:** `commit` · **validation_tier:** `area-focused` · gates: impl `closed`, review `closed`, commit `closed` · **commit_subject:** `build(deps): refresh nx for lerna runner` -- **Do:** - - Bump `lerna` to the latest release in root `devDependencies`; refresh `yarn.lock`. This pulls a current bundled `nx` ([MonoTool-AD-1 prerequisite](architecture-decisions.md#monotool-ad-1--nx-local-cache-via-the-lerna-runner-no-turborepo-no-nx-cloud--accepted)). - - Confirm the bundled `nx` version supports the `nx.json` keys used in MT1 (`neverConnectToCloud`, `namedInputs`, per-target `cache`/`inputs`/`outputs`) and includes the `nx watch --all --initialRun` fix (nx PR #32282) needed by the deferred MT-WATCH. -- **Acceptance:** - - `yarn` installs cleanly; `yarn lerna:prepare` still exits 0 (behavior unchanged pre-`nx.json`). - - `yarn lint`, `yarn tsc:compile`, `yarn tests:jest` remain green. - - Record the resulting `lerna` + bundled `nx` versions in a note (feeds MT1/MT-WATCH version checks). -- **Implementation evidence (unit-focused, 2026-07-10):** - - Change: `lerna` was already current at `9.0.7`; refreshed transitive `nx` / `@nx/devkit` from `22.1.3` → `22.7.6` via **lockfile refresh** (no root `resolutions` pins; Lerna's `>=21.5.3 <23.0.0` range resolves to latest 22.x). - - Files changed: `yarn.lock` (Nx-family bump only; no `package.json` pin). - - Version evidence: `lerna` `9.0.7` → `9.0.7`; bundled `nx` `22.1.3` → `22.7.6`; `nx-schema.json` includes `neverConnectToCloud`, `namedInputs`, and per-target `cache`/`inputs`/`outputs`. - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn` | 0 | Clean install; peer warnings only | - | `yarn lerna:prepare` | 0 | 20 projects prepared successfully | - | `yarn lint` | 0 | JS + Android + iOS lint/checks green | - | `yarn tsc:compile` | 0 | Root TS compile clean | - | `yarn tests:jest` | 0 | 82 suites / 1172 tests passed; log `/tmp/mt0-jest.log` | -- **Independent-review findings (area-focused, 2026-07-10):** - - **Serious (initial):** first pass used `resolutions` for `nx` only; `@nx/devkit` skewed at `22.1.3`. Remediation replaced pins with lockfile refresh (no root resolutions); Nx-family aligns at `22.7.6`. - - **Minor:** commit subject updated to `build(deps): refresh nx for lerna runner`. - - Review validation reran green before finding: `yarn` 0 (`/tmp/mt0-review-yarn.log`), `yarn lerna:prepare` 0, `yarn lint` 0 (`/tmp/mt0-review-lint.log`), `yarn tsc:compile` 0 (`/tmp/mt0-review-tsc.log`), `yarn tsc:compile:consumer` 0 (`/tmp/mt0-review-tsc-consumer.log`), `yarn tests:jest` 0 (`/tmp/mt0-review-jest.log`, 82 suites / 1172 tests). Coverage evidence: n/a (no `packages/*/lib/**` or native bridge sources). -- **Remediation evidence (unit-focused, 2026-07-10):** - - Change: removed `nx` / `@nx/devkit` `resolutions`; `yarn install` lockfile refresh aligns all Nx-family packages at `22.7.6` (no `22.1.3` entries remain). - - Version evidence: `lerna` `9.0.7` unchanged; `nx` `22.7.6`; `@nx/devkit` `22.7.6`; `@nx/nx-darwin-arm64` `22.7.6`; `nx-schema.json` keys present; `nx watch --all --initialRun` supported at `22.7.6` (>= 22.6.0 threshold). - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn` | 0 | Clean install; peer warnings only; log `/tmp/mt0-remediation-yarn.log` | - | `yarn lerna:prepare` | 0 | 20 projects prepared successfully; log `/tmp/mt0-remediation-lerna-prepare.log` | - | `yarn lint` | 0 | JS + Android + iOS lint/checks green; log `/tmp/mt0-remediation-lint.log` | - | `yarn tsc:compile` | 0 | Root TS compile clean; log `/tmp/mt0-remediation-tsc.log` | - | `yarn tests:jest` | 0 | 82 suites / 1172 tests passed; log `/tmp/mt0-remediation-jest.log` | - | `yarn tsc:compile:consumer` | 0 | Consumer TS compile clean; log `/tmp/mt0-remediation-tsc-consumer.log` | -- **Independent-review evidence after remediation (area-focused, 2026-07-10):** - - Findings: none. Serious `@nx/devkit` skew fixed; no `22.1.3` Nx-family entries remain in `yarn.lock`; `nx`, `@nx/devkit`, and all `@nx/nx-*` platform packages resolve to `22.7.6`. - - Diff scope verified: `package.json` unchanged by Nx pinning; `lerna` remains `^9.0.7` / CLI `9.0.7`; lockfile churn is Nx-family transitive updates, not unrelated scope. - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn` | 0 | Clean install + postinstall prepare; log `/tmp/mt0-fresh-review-yarn.log` | - | `yarn lerna:prepare` | 0 | 20 projects prepared | - | `yarn lint` | 0 | JS + Android + iOS checks green; log `/tmp/mt0-fresh-review-lint.log` | - | `yarn tsc:compile` | 0 | Root TS compile; log `/tmp/mt0-fresh-review-tsc.log` | - | `yarn tests:jest` | 0 | 82 suites / 1172 tests; log `/tmp/mt0-fresh-review-jest.log` | - | `yarn tsc:compile:consumer` | 0 | Consumer TS compile; log `/tmp/mt0-fresh-review-tsc-consumer.log` | - - Coverage evidence: n/a (no `packages/*/lib/**` or native bridge sources). - -### MT0.1 — dependency-cruiser `lint:deps` - -- **next_work_type:** `commit` · **validation_tier:** `area-focused` · gates: impl `closed`, review `closed`, commit `closed` · **commit_subject:** `build(deps): add dependency-cruiser lint:deps for lib import graph` -- **Do:** - - Add `dependency-cruiser` devDependency (root). - - Add `.dependency-cruiser.cjs` with rule `no-circular` on `packages/*/lib/**` (allowlist + `not-to-own-dist` hardening deferred to MT4). **Scope the config now** ([design](prepare-and-cache.md#dependency-cycle-linting)): `doNotFollow`/`exclude` for `node_modules`, `packages/*/dist/**`, `packages/*/__tests__/**`, `packages/*/e2e/**`; set `options.tsConfig` + `enhancedResolveOptions` so the `@react-native-firebase/*` path aliases resolve. - - `package.json`: `"lint:deps": "depcruise --config .dependency-cruiser.cjs packages"`; add `yarn lint:deps` into the JS lint path. - - CI: add a `lint:deps` step in [`.github/workflows/linting.yml`](../../../.github/workflows/linting.yml) lint job. - - `okf-bundle/testing/validation-checklist.md` § lint + `change-authoring-workflow.md` lint gate: note `lint:deps` blocking when `packages/*/lib/**` in diff (durable OKF edit → DRY pass). -- **Acceptance:** - - `yarn lint:deps` exits 0 on current tree (graph is a DAG today). - - Resolution sanity: at least one real cross-package edge (e.g. a satellite → `@react-native-firebase/app/...`) is **resolved**, not reported as unresolvable (proves the tsconfig-alias wiring works). - - `yarn lint` (full) still exits 0. - - Introducing a deliberate temporary cycle makes `yarn lint:deps` exit non-zero (then revert). - - CI lint job runs the step. -- **Implementation evidence (unit-focused, 2026-07-10):** - - Change: added `dependency-cruiser@17.4.3`; new `.dependency-cruiser.cjs` with scoped inter-package `no-circular` on `packages/*/lib/**`, excludes for `node_modules`/`dist`/`__tests__`/`e2e`, TS path-alias resolution via generated `tsconfig.depcruise.json`; root `lint:deps` wired into `yarn lint`; CI step in `.github/workflows/linting.yml`; OKF validation gates updated in `validation-checklist.md` + `change-authoring-workflow.md`. - - Files changed: `package.json`, `yarn.lock`, `.dependency-cruiser.cjs`, `.github/workflows/linting.yml`, `okf-bundle/testing/validation-checklist.md`, `okf-bundle/testing/change-authoring-workflow.md`. - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn lint:deps` | 0 | 32 modules / 74 deps; log `/tmp/mt01-lint-deps.log` | - | `yarn lint` | 0 | JS + deps + Android + iOS; log `/tmp/mt01-lint.log` | - | temporary cycle → `yarn lint:deps` | 3 | app ↔ crashlytics cycle detected; log `/tmp/mt01-lint-deps-cycle.log` | - | post-revert `yarn lint:deps` | 0 | temp import reverted; clean tree restored | - - Resolution sanity: `packages/analytics/` → `packages/app/` edge resolved (`@react-native-firebase/app/dist/module/common`, types `aliased-tsconfig-paths`); 0 unresolved from analytics; log `/tmp/mt01-resolution-sanity.log`. - - Follow-ups flagged by implementer: generated `tsconfig.depcruise.json` each run (consider `.gitignore`); graph currently analyzes compiled `lib/**/*.js` (excludes `.ts`); CI runs `lint:deps` twice via dedicated step + `yarn lint`. -- **Independent-review findings (area-focused, 2026-07-10):** - - **Serious:** config excludes authored `lib/**/*.ts` and effectively analyzes ephemeral/committed `.js` sidecars, not the real TS import graph; on a clean CI tree without local compile sidecars, MT0.1 acceptance is not proven. Remediation required: remove `.ts` exclude, cruise authored TS under `packages/*/lib/**`, and re-validate on a clean tree. - - **Minor:** gitignore generated `tsconfig.depcruise.json`; tighten cruise scope/excludes (`plugin/__tests__`, non-`lib/**` noise); deduplicate CI `lint:deps` invocation (dedicated step or `yarn lint`, not both). - - Review validation: `yarn lint:deps` 0 (`/tmp/mt01-review-lint-deps.log`); `yarn lint`/`yarn lint:js` failed on this host due to ephemeral untracked `packages/*/lib/**/*.js` sidecars (~19.5k eslint errors), outside MT0.1 frozen scope but relevant to clean-tree proof. Coverage evidence: n/a. -- **Remediation evidence (unit-focused, 2026-07-10):** - - Change: TS-first depcruise config (`includeOnly` on `packages/*/lib/**/*.ts(x)`, `moduleResolution: 'node'`, `noEmit: true`); scoped excludes; gitignored `tsconfig.depcruise.json`; `lint:deps` scoped to `packages/*/lib`; CI deduped to single `yarn lint` step. - - Files changed: `.dependency-cruiser.cjs`, `.gitignore`, `package.json`, `.github/workflows/linting.yml`, `okf-bundle/testing/validation-checklist.md`. - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn lint:deps` (clean TS tree) | 0 | 19 modules / 23 deps; log `/tmp/mt01-remediation-lint-deps-clean.log` | - | resolution sanity (analytics → app) | 0 | `@react-native-firebase/app` → `packages/app/` via `aliased-tsconfig-paths`; log `/tmp/mt01-remediation-resolution-sanity.log` | - | temp cycle → `yarn lint:deps` | 3 | app ↔ crashlytics; log `/tmp/mt01-remediation-lint-deps-cycle.log`; reverted | - | post-revert `yarn lint:deps` | 0 | log `/tmp/mt01-remediation-lint-deps-post-revert.log` | - | `yarn lint:js` | 0 | ESLint green | - | `yarn lint` | 1 | `lint:deps` passes; `lint:android` failed (`google-java-format` exit 1) — implementer claims pre-existing Android formatter flake unrelated to MT0.1 | - - Clean-tree proof: validation used authored TS only (ephemeral untracked `lib/**/*.js` sidecars temporarily moved aside; tracked memidb `.js` retained). -- **Independent-review evidence after remediation (area-focused, 2026-07-10):** - - Findings: no serious findings. One minor local-only caveat: with ephemeral untracked `lib/**/*.js` sidecars present, standalone `yarn lint:deps` can vacuously pass (0 deps cruised); mitigated because `yarn lint` runs `lint:js` first and CI uses clean checkout. - - Validation evidence (clean TS tree): - | Command | Exit | Notes | - |---------|------|-------| - | `yarn lint:deps` | 0 | 19 modules / 23 deps cruised; log `/tmp/mt01-fresh-review-lint-deps-clean.log` | - | resolution sanity (analytics → app) | 0 | `@react-native-firebase/app` → `packages/app/` | - | `yarn lint:js` | 0 | log `/tmp/mt01-fresh-review-lint-js` | - | `yarn lint` | 0 | js + deps + android + ios; log `/tmp/mt01-fresh-review-lint-clean.log` | - | `yarn lint:android` (isolated) | 0 | prior android flake not reproduced | - - Coverage evidence: n/a. - -### MT0.2 — Durable OKF docs — **landed** - -- **work type:** `documentation` · **validation_tier:** none · gates: n/a · **commit_subject:** `docs: add monorepo tooling OKF bundle` -- **Do:** `okf-bundle/monorepo-tooling/{index.md,architecture-decisions.md,prepare-and-cache.md,work-queue.md}`; add a "Monorepo tooling" entry to [`okf-bundle/index.md`](../index.md). -- **Acceptance:** OKF DRY/consistency pass green (canonical location, link hygiene, durable vs ephemeral split); decisions live only in `architecture-decisions.md`; ephemeral phases live only here. Documentation/DRY pass completed after `docs: correct assertion about JS bundles in dev`. - -### MT0.3 — Benchmark baseline - -- **next_work_type:** `commit` · **validation_tier:** none · gates: impl `closed`, review `closed`, commit `closed` · **commit_subject:** `build(scripts): add prepare benchmark script` -- **Do:** `scripts/benchmark-prepare.sh` (macOS; scenarios A–D from [prepare-and-cache § benchmark](prepare-and-cache.md#benchmark-methodology)); capture **pre-Nx** B/C/D medians into a benchmarks note. -- **Acceptance:** - - Script runs A–D, prints median-of-3 per scenario, exits 0. - - Pre-Nx baseline numbers recorded (used to prove MT1 gains). -- **Implementation evidence (none tier, 2026-07-10):** - - Change: added `scripts/benchmark-prepare.sh` (macOS guard, scenarios A–D, median-of-3, reversible firestore edit with `EXIT` trap); ephemeral baseline note `prepare-benchmark-baseline.md`. - - Files changed: `scripts/benchmark-prepare.sh`, `okf-bundle/monorepo-tooling/prepare-benchmark-baseline.md`. - - Pre-Nx medians (s): A 125.583; B 23.686; C 23.694; D 23.758. Logs: `.tmp/prepare-benchmarks/20260710-122118/`. - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `bash ./scripts/benchmark-prepare.sh` | 0 | Full A–D run (~624s unsandboxed); sandboxed first attempt failed on partial `node_modules` removal | - | `bash -n scripts/benchmark-prepare.sh` | 0 | Syntax check | - - Coverage evidence: n/a (no `packages/*/lib/**` runtime or native bridge edits committed). -- **Independent-review evidence (none tier, 2026-07-10):** - - Findings: none. Script aligns with `prepare-and-cache.md` benchmark methodology; baseline numbers live in ephemeral note only. - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `bash -n scripts/benchmark-prepare.sh` | 0 | Review smoke syntax check | - - Coverage evidence: n/a. - -### MT1 — Deterministic cached prepare - -- **next_work_type:** `commit` · **validation_tier:** `area-focused` · gates: impl `closed`, review `closed`, commit `closed` · **commit_subject:** `build(deps): enforce package build order and enable nx prepare cache` -- **Do:** - - Add `"@react-native-firebase/app": ""` to `devDependencies` of the **17 packages** = every package except `app` and `vertexai` (16 plain satellites + `ai`); `vertexai` orders transitively via its `ai` dependency ([MonoTool-AD-3](architecture-decisions.md#monotool-ad-3--build-order-via-devdependencies-not-manual-phase-scripts--accepted); counts owned by [prepare-and-cache § graph](prepare-and-cache.md#package-dependency-graph)). - - Add `nx.json` — [design](prepare-and-cache.md#nx-local-cache): `neverConnectToCloud: true`; `namedInputs.jsSource`; `prepare` target `dependsOn: ["^prepare"]`, `inputs: ["jsSource"]` ([MonoTool-AD-11](architecture-decisions.md#monotool-ad-11--scope-prepare-cache-inputs-with-a-jssource-namedinput--accepted)), `cache: true`, `outputs` = `dist/**` + `plugin/build/**` + **`lib/version.ts`** ([MonoTool-AD-10](architecture-decisions.md#monotool-ad-10--generated-version-files-are-declared-cache-outputs-not-committed--accepted)). - - Add an `app`-scoped `nx.targets.prepare.outputs` override in `packages/app/package.json` re-listing `dist/**`, `plugin/build/**`, `lib/version.ts`, **`ios/RNFBApp/RNFBVersion.m`**, **`android/src/reactnative/java/io/invertase/firebase/app/ReactNativeFirebaseVersion.java`** ([MonoTool-AD-10](architecture-decisions.md#monotool-ad-10--generated-version-files-are-declared-cache-outputs-not-committed--accepted)). - - Update the `yarn lerna:prepare` **body** (name unchanged) to `cross-env NX_NO_CLOUD=true lerna run prepare` ([MonoTool-AD-4](architecture-decisions.md#monotool-ad-4--one-inlined-prepare-command-no-wrapper-script--accepted)). - - `packages/ai`: drop `yarn tests:ai:mocks` from `prepare`; add an **AI-test-gated** Jest prerequisite (single flat jest config — a `globalSetup` that no-ops unless the run includes `packages/ai/__tests__/**`, or a `projects` split) running the fetch + convert scripts; make the fetch offline-idempotent (local-clone short-circuit before `git ls-remote`) ([MonoTool-AD-7](architecture-decisions.md#monotool-ad-7--ai-test-fixtures-are-a-jest-prerequisite-not-a-build-step--accepted)). - - CI: restore/save `.nx/cache` via `actions/cache` in PR/main jobs; set `NX_NO_CLOUD=true` on every Nx-running job; **do not** touch `publish.yml` ([MonoTool-AD-8](architecture-decisions.md#monotool-ad-8--nxcache-shared-on-ci-not-on-publish--accepted)). - - Remove scoped-prepare guidance from `validation-checklist.md` (durable OKF edit → DRY pass). -- **Acceptance:** - - **Determinism:** from a clean dist (`rm -rf packages/*/dist packages/*/plugin/build`), `yarn lerna:prepare` exits 0 **repeatably** (run ≥3×); `packages/app/dist/**` exists before any satellite `compile` (no ordering race). If ordering is not honored, switch the inline body to `nx run-many -t prepare` ([MonoTool-AD-4 fallback](architecture-decisions.md#monotool-ad-4--one-inlined-prepare-command-no-wrapper-script--accepted)). - - **Cache-replay completeness (regression guard for [MonoTool-AD-10](architecture-decisions.md#monotool-ad-10--generated-version-files-are-declared-cache-outputs-not-committed--accepted)):** after a warm prepare, delete the generated files (`git clean -fdx -- 'packages/*/lib/version.ts' packages/app/ios/RNFBApp/RNFBVersion.m 'packages/app/android/**/ReactNativeFirebaseVersion.java'`) **and** `packages/*/dist`, then re-run `yarn lerna:prepare` (cache hit) → all generated files are restored, and `yarn tests:jest` + `yarn tsc:compile` still exit 0. (Simulates the fresh-CI-checkout + restored-`.nx/cache` path.) - - `yarn tsc:compile` and `yarn tsc:compile:consumer` exit 0. - - `yarn tests:jest` exits 0, including `packages/ai` (fixtures fetched via the gated prerequisite, not `prepare`); a **non-AI** `yarn tests:jest` run performs **no** network fetch. - - **Input scoping ([MonoTool-AD-11](architecture-decisions.md#monotool-ad-11--scope-prepare-cache-inputs-with-a-jssource-namedinput--accepted)):** editing a package's `__tests__`/`e2e`/`android`/`ios` file does **not** invalidate its `prepare` cache; editing its `lib/**` does. - - A no-op `yarn lerna:prepare` (MT0.3 scenario C) is materially faster than the pre-Nx baseline (cache hit); single-package edit (D) rebuilds only that package + dependents. - - **Publish-flow check ([MonoTool-AD-2](architecture-decisions.md#monotool-ad-2--keep-lerna-for-versioning-and-publish--accepted)):** a `lerna version` **dry run** rewrites the new internal `@react-native-firebase/app` devDep ranges to the bumped version and shows no other release-flow change (no side effects). - - `git grep vertexai-sdk-test-data` shows fixtures still gitignored; `yarn` (fresh) does **not** clone test data. - - Optional (review discretion): one platform e2e smoke to confirm `dist/module/**` output is unchanged by the ordering change. -- **Implementation evidence (unit-focused, 2026-07-10):** - - Change: 17-package `@react-native-firebase/app` devDep graph; root `nx.json` (scoped inputs/outputs, no-cloud); app nx output override; `cross-env NX_NO_CLOUD=true lerna run prepare`; AI mocks out of `prepare` into gated Jest `globalSetup`; fetch script local-clone fast path; CI `.nx/cache` restore/save + `NX_NO_CLOUD` on jest/lint/e2e jobs; validation-checklist scoped-prepare line removed. - - Files changed: `nx.json`, `package.json`, `packages/{app,ai,16 satellites}/package.json`, `jest.config.js`, `scripts/jest-ai-mocks-global-setup.js`, `scripts/fetch_ai_mock_responses.ts`, `.github/workflows/{tests_jest,linting,tests_e2e_*}.yml`, `okf-bundle/testing/validation-checklist.md`, `yarn.lock`. - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn` | 0 | Fresh install + postinstallDev prepare (20 projects); `/tmp/mt1-yarn-fresh.log` | - | `yarn lerna:prepare` ×3 | 0 | Warm cache ~1.38–1.40s each; `/tmp/mt1-lerna-prepare-repeat.log` | - | Determinism (clean dist ×3) | 0 | `packages/app/dist/module/index.js` present; `/tmp/mt1-determinism.log` | - | Cache-replay (AD-10) | 0 | 20/20 cache hits; version + native files restored; `/tmp/mt1-cache-replay-*.log` | - | `yarn tsc:compile` | 0 | `/tmp/mt1-tsc.log` | - | `yarn tsc:compile:consumer` | 0 | `/tmp/mt1-tsc-consumer.log` | - | `yarn tests:jest` | 0 | 82 suites / 1172 tests; `/tmp/mt1-jest.log` | - | Non-AI jest | 0 | 59 suites / 847 tests, no network; `/tmp/mt1-jest-non-ai.log` | - | `yarn lint:js` + `yarn lint:deps` | 0 | `/tmp/mt1-lint-{js,deps}.log` | - | Benchmark (post-Nx A–D) | 0 | See `prepare-benchmark-baseline.md` § Post-Nx; logs `.tmp/prepare-benchmarks/20260710-152608/`; C **1.410s** vs pre-Nx **23.694s** (~16.8×); B **1.880s** vs **23.686s** (~12.6×); D median **1.457s** vs **23.758s** | - | `lerna changed` + devDep spot-check | n/a | No `--dry-run` in Lerna 9; devDeps at `25.1.0` on analytics/ai/firestore; `/tmp/mt1-lerna-changed.log` | - | `git grep vertexai-sdk-test-data` | 0 | Fixtures gitignored; `/tmp/mt1-git-grep-fixtures.log` | - - Coverage evidence: n/a (no `packages/*/lib/**` or native bridge product edits). - - Deviations noted: full `yarn lint` (android/ios) not run; lib-edit cache bust not directly exercised; Nx intermittent flaky-task warning on cache-replay (all exit 0). -- **Independent-review findings (area-focused, 2026-07-10):** - - **Serious:** `nx.json` + `scripts/jest-ai-mocks-global-setup.js` untracked — must stage before commit. - - **Serious:** `shouldFetchAiMocks()` ignores CLI `--testPathIgnorePatterns=packages/ai` (Jest passes pre-CLI config to globalSetup); non-AI runs can still fetch on fresh hosts. **Fix:** inspect `process.argv` for ignore patterns containing `packages/ai`. - - **Minor:** non-AI validation command misleading until #2 fixed. - - **Nit:** do not commit `.dependency-cruiser.min.cjs`; android format warning pre-existing. - - Review validation: all re-runs green; cache-replay AD-10 verified 20/20 hits. Logs `/tmp/mt1-review-*.log`. - - **Gate:** review_gate stays **open** — remediation required. -- **Remediation evidence (unit-focused, 2026-07-10):** - - Change: `getArgvTestPathIgnorePatterns()` merges CLI `--testPathIgnorePatterns` (= and space forms) with `globalConfig.testPathIgnorePatterns`; AI ignored via argv skips fetch. - - Files changed: `scripts/jest-ai-mocks-global-setup.js`. - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn tests:jest --testPathIgnorePatterns=packages/ai` | 0 | No fetch output; `/tmp/mt1-remediation-ignore-equals.log` | - | `yarn tests:jest --testPathIgnorePatterns packages/ai` | 0 | No fetch output; `/tmp/mt1-remediation-ignore-space.log` | - | `yarn tests:jest -- packages/firestore` | 0 | No fetch; `/tmp/mt1-remediation-firestore.log` | - | `yarn tests:jest -- packages/ai` | 0 | Fetch invoked; `/tmp/mt1-remediation-ai-fetch.log` | - | `node --check scripts/jest-ai-mocks-global-setup.js` | 0 | Syntax | -- **Independent-review evidence after remediation (area-focused, 2026-07-10):** - - Findings: none. Prior serious (untracked deliverables — content OK; staged at commit; globalSetup argv gating) resolved. - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn lerna:prepare` | 0 | 20/20 cache hits; `/tmp/mt1-delta-review-20260710-125221.log` | - | Non-AI jest (ignore patterns) | 0 | Zero fetch with clone moved aside | - | `yarn tests:jest -- packages/ai` | 0 | Fetch invoked when AI included | - | `yarn tests:jest` (full) | 0 | 82 suites / 1172 tests | - | `yarn tsc:compile` + consumer | 0 | | - - Coverage evidence: n/a. - -### MT2 — Declaration maps - -- **next_work_type:** `commit` · **validation_tier:** `area-focused` · gates: impl `closed`, review `closed`, commit `closed` · **commit_subject:** `build(ts): emit declaration maps for package builds` -- **Do:** add `declaration: true` + `declarationMap: true` to `tsconfig.packages.base.json`, `packages/ai/tsconfig.json`, `packages/vertexai/tsconfig.json` ([MonoTool-AD-5](architecture-decisions.md#monotool-ad-5--keep-react-native-builder-bob-emit-declaration-maps--accepted)). -- **Acceptance:** - - After `yarn lerna:prepare`, `packages/*/dist/typescript/**/*.d.ts.map` exist. - - `yarn tsc:compile` exits 0; `yarn lint` exits 0. - - Spot-check: IDE go-to-definition on a cross-package symbol lands on `lib/**` source (record the check in notes). - - **Map resolves to shipped source:** open one emitted `.d.ts.map` and confirm its `sources` point at the published `lib/*.ts` (relative, no absolute path leak) — since `files` publishes `lib`, external consumers get go-to-definition too. - - `.d.ts.map` do not leak into unintended published paths (bob `files`/`exclude` still correct). -- **Implementation evidence (unit-focused, 2026-07-10):** - - Change: added `declaration: true` + `declarationMap: true` to `tsconfig.packages.base.json`, `packages/ai/tsconfig.json`, `packages/vertexai/tsconfig.json` ([MonoTool-AD-5](architecture-decisions.md#monotool-ad-5--keep-react-native-builder-bob-emit-declaration-maps--accepted)). - - Files changed: `tsconfig.packages.base.json`, `packages/ai/tsconfig.json`, `packages/vertexai/tsconfig.json`. - - Map spot-check: `FirebaseApp` (`analytics/lib/index.ts` → `@react-native-firebase/app` → `packages/app/dist/typescript/lib/index.d.ts`) go-to-def target `packages/app/lib/index.ts`; `index.d.ts.map` has `sourceRoot: ""`, `sources: ["../../../lib/index.ts"]`, 0 absolute-path leaks; 310 `.d.ts.map` emitted, all under `dist/typescript` (0 in `dist/module`). - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn lerna:prepare` | 0 | 20 projects rebuilt (base tsconfig change busted cache); `/tmp/mt2-prepare.log` | - | `.d.ts.map` count/leak scan | 0 | 310 maps; 0 absolute leaks; 0 outside `dist/typescript`; `/tmp/mt2-dtsmap-count.log`, `/tmp/mt2-leak-scan.log` | - | `yarn tsc:compile` | 0 | `/tmp/mt2-tsc.log` | - | `yarn tsc:compile:consumer` | 0 | `/tmp/mt2-tsc-consumer.log` | - | `yarn lint` (full) | 0 | js + deps + android + ios; `/tmp/mt2-lint-2.log` (android formatter flaked once, clean on re-run) | - | `yarn lint:deps` | 0 | 19 modules / 23 deps; `/tmp/mt2-lint-deps.log` | - | `yarn tests:jest` | 0 | 82 suites / 1172 tests; `/tmp/mt2-jest.log` | - - Coverage evidence: n/a (tsconfig/build-config only; no `packages/*/lib/**` or native bridge edits). -- **Independent-review evidence (area-focused, 2026-07-10):** - - Findings: none. Product diff is three tsconfig files only. - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn lerna:prepare` | 0 | 20/20 cache hits; `/tmp/mt2-review-prepare.log` | - | `.d.ts.map` count/leak scan | 0 | 310 maps; 0 absolute leaks; 0 in `dist/module`; `/tmp/mt2-review-dtsmap-scan.log` | - | `npm pack --dry-run` (analytics) | 0 | 11 maps in tarball under `dist/typescript`; `/tmp/mt2-review-publish-check.log` | - | `yarn tsc:compile` + consumer | 0 | `/tmp/mt2-review-tsc.log`, `/tmp/mt2-review-tsc-consumer.log` | - | `yarn lint` (full) | 0 | js + deps + android + ios; `/tmp/mt2-review-lint-full.log` | - | `yarn tests:jest` | 0 | 82 suites / 1172 tests; `/tmp/mt2-review-jest.log` | - - Coverage evidence: n/a. - -### MT4 — dependency-cruiser rule hardening — **gated on MT1** - -- **next_work_type:** `commit` · **validation_tier:** `area-focused` · gates: impl `closed`, review `closed`, commit `closed` · **commit_subject:** `build(deps): enforce package import boundaries` -- **Do:** extend `.dependency-cruiser.cjs` ([MonoTool-AD-6](architecture-decisions.md#monotool-ad-6--dependency-cycle-linting-via-dependency-cruiser-as-lintdeps--accepted)): **`not-to-own-dist`** (forbid only _relative_ `../dist/**`/`./dist/**` imports — **not** the mapped hub API `@react-native-firebase/app/dist/module/...`, which is legitimate); graph allowlist (satellites → `app` only; `ai` → `auth`/`app-check`; `vertexai` → `ai`). -- **Acceptance:** - - `yarn lint:deps` exits 0 on current tree with the stricter rules (the existing `@react-native-firebase/app/dist/module/...` imports in ~15 satellites must **not** be flagged). - - A deliberate off-graph import (e.g. `firestore` importing `auth`) fails `lint:deps` (then revert). - - A deliberate _relative_ own-`../dist` import fails `lint:deps` (then revert). - - `yarn lint` full still exits 0. -- **Implementation evidence (unit-focused, 2026-07-10):** - - Change: extended `.dependency-cruiser.cjs` with `not-to-own-dist` (module scope, same-package capture), `hub-no-internal`, `satellites-only-hub`, `ai-graph`, `vertexai-graph`; dynamic tsconfig paths for all non-hub packages; `includeOnly` widened to retain own-dist edges; collapse removed so module-scope violations survive. - - Files changed: `.dependency-cruiser.cjs`. - - Probe evidence: - | Probe | Exit | Notes | - |-------|------|-------| - | Clean `yarn lint:deps` | 0 | 313 modules / 963 deps; `/tmp/mt4-lint-deps-clean.log` | - | Off-graph (firestore → auth) | 1 | `satellites-only-hub`; reverted; `/tmp/mt4-probe-off-graph.log` | - | Own-dist (analytics `../dist/module`) | 1 | `not-to-own-dist`; reverted; `/tmp/mt4-probe-own-dist.log` | - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn lint:js` | 0 | `/tmp/mt4-lint-js.log` | - | `yarn lint` (full) | 0 | `/tmp/mt4-lint-full.log` | - | `yarn tsc:compile` | 0 | `/tmp/mt4-tsc-compile.log` | - | `yarn tests:jest` | 0 | 82 suites / 1172 tests; `/tmp/mt4-tests-jest.log` | - - Coverage evidence: n/a (config-only). -- **Independent-review evidence (area-focused, 2026-07-10):** - - Findings: **minor** (non-blocking, out of MT4 acceptance scope): (1) type-only imports bypass graph allowlist — value imports enforced; matches existing ai/vertexai patterns; (2) relative cross-package `../../pkg/dist/` bypasses allowlist path matching — current tree uses alias imports only; own-dist rule catches same-package relative dist. - - Validation evidence: - | Command | Exit | Notes | - |---------|------|-------| - | `yarn lint:deps` (clean) | 0 | 313 modules / 963 deps; `/tmp/mt4-review-lint-deps-clean.log` | - | Off-graph probe (firestore → auth) | 1 | reverted; `/tmp/mt4-review-probe-off-graph.log` | - | Own-dist probe | 1 | reverted; `/tmp/mt4-review-probe-own-dist.log` | - | `yarn lint` (full) | 0 | `/tmp/mt4-review-lint-full.log` | - | `yarn tsc:compile` | 0 | `/tmp/mt4-review-tsc-compile.log` | - | `yarn tests:jest` | 0 | 82 suites / 1172 tests; `/tmp/mt4-review-tests-jest.log` | - - Coverage evidence: n/a. - -### MT-WATCH — Dev watch + e2e rerun (gap-analysis pre-phase) — **Deferred** - -- **next_work_type:** `gap-analysis` · **validation_tier:** `area-focused` (only if it reaches implementation) · gates: impl `open`, review `open`, commit `open` · **commit_subject:** n/a until analysis converges -- **Status:** Deferred — no incremental dev-watch/hot-reload loop exists today; **off the critical path** for MT1/MT2/MT4/MTV ([MonoTool-AD-9](architecture-decisions.md#monotool-ad-9--dev-watch-rebuilds-prepare-e2e-tdd-rerun-is-event-driven-off-metro--deferred)). This pre-phase does the detailed analysis that must precede any implementation. -- **Do (analysis):** - - Resolve the Tier A command caveats ([design](prepare-and-cache.md#tier-a--prepare-watch--unit-tdd-sketch-to-be-validated)): verify bundled `nx` includes the `--all --initialRun` fix (else first pass via `nx run-many -t prepare`); use `nx run-many -t prepare -p $NX_PROJECT_NAME` for multi-project watch batches. - - Note: the OKF debug/release correction already landed separately as `docs: correct assertion about JS bundles in dev`; [running e2e § Rules #3](../testing/running-e2e.md#rules) is now the canonical owner of that fact. MT-WATCH only needs to analyze the dev-watch and event-driven rerun mechanics. - - Analyze the event-driven e2e rerun (Metro `update-done`/`onBundleBuilt` → Jet `POST /rerun` on `8091`; [design Tier C](prepare-and-cache.md#tier-c--event-driven-e2e-rerun-spike); [Jet patch workflow](../ci-workflows/detox-patches.md#updating-the-jet-patch-headless)); confirm `update-done` observability and whether an app-side Jet reload hook is simpler; assess coverage-teardown-handshake bypass in fast-rerun mode. -- **Acceptance (analysis):** - - Written findings: viability, chosen command shapes, and a go/no-go for a follow-on implementation phase (with its own gates). If no-go, close as `documentation` (record findings) — do not force implementation. - - `dev:watch`, if later implemented, is **human-only** — `agent-command-policy.md` keeps `yarn lerna:prepare` canonical. - -### MTV — Branch-wide validation — **closed** - -- **next_work_type:** n/a · **validation_tier:** `full` · gates: impl `closed`, review `closed`, commit `closed` · **commit_subject:** n/a (no product edit) -- **Status (2026-07-11):** **GREEN** — validation ([e821793c](e821793c-c586-4a43-ac25-0d7ae53c350a)) + independent review ([4361b403](4361b403-8cb6-4706-96e4-174bf77b59d2)); no critical/serious findings. -- **Validation evidence:** - - Static: prepare ×3 (21 cache hits), AD-10 replay, tsc ×2, Jest 82/1172, lint/compare:types/reference:api exit 0 — `/tmp/mtv2-full-*.log` - - E2e: macOS **710/0/34**, iOS **848/0/85**, Android **878/0/54** — `/tmp/mtv2-full-e2e-*.log` - - Review: lint:deps, tsc, compare:types, prepare spot-check (20/20 hits) — `/tmp/mtv2-review-*.log` -- **Review follow-ups (non-blocking, post-merge OK):** `app/scripts/**` in nx cache inputs; `lint:deps` in agent-command-policy registry; AD-4 scoped-prepare wording; CI cache key nit. - ---- - -## Current gates - -| Item | impl | review | commit | next_work_type | -| -------- | ------ | ------ | ------ | --------------------------------------------- | -| MT0.0 | closed | closed | closed | `commit` | -| MT0.1 | closed | closed | closed | `commit` | -| MT0.2 | closed | n/a | closed | `documentation` (landed) | -| MT0.3 | closed | closed | closed | `commit` | -| MT1 | closed | closed | closed | `commit` | -| MT2 | closed | closed | closed | `commit` | -| MT4 | closed | closed | closed | `commit` | -| MT-WATCH | open | open | open | `gap-analysis` (deferred) | -| MTV | closed | closed | closed | n/a (merge gate passed) | diff --git a/okf-bundle/packages/app-check/architecture-decisions.md b/okf-bundle/packages/app-check/architecture-decisions.md index d7519ce10c..475b3e86b0 100644 --- a/okf-bundle/packages/app-check/architecture-decisions.md +++ b/okf-bundle/packages/app-check/architecture-decisions.md @@ -8,7 +8,7 @@ timestamp: 2026-08-04T00:00:00Z # App Check decisions (ADR) -**Canonical owner of durable architectural decisions** for `@react-native-firebase/app-check`. Procedure and ephemeral gate state live in the [iOS provider init work queue](ios-provider-init-work-queue.md). That queue **links here** for the "why" — it does not restate decisions. +**Canonical owner of durable architectural decisions** for `@react-native-firebase/app-check`. Ephemeral procedure and gate state live in Linear project work-queue documents ([work-queue documents](../../documentation-policy.md#work-queue-documents)); they **link here** for the "why" and do not restate decisions. **Policy:** [OKF documentation and commit policy](../../documentation-policy.md). @@ -91,7 +91,7 @@ Prefer a small iOS unit/host test or injectable seam proving pre-configure `crea Treat the behavior change as a **bug fix** with an explicit release note and troubleshooting docs (early token fetch before `initializeAppCheck` now errors; release builds must not exchange debug tokens). Do **not** hold for a coordinated semver major solely for this. -**Why:** The old behavior was unsupported footgun behavior, not a documented API. Callers still need a clear “configure before use” story ([docs work in the queue](ios-provider-init-work-queue.md)). +**Why:** The old behavior was unsupported footgun behavior, not a documented API. Callers still need a clear “configure before use” story. --- @@ -99,7 +99,7 @@ Treat the behavior change as a **bug fix** with an explicit release note and tro While pending, token completions must use an **actionable** error that mentions configuring / `initializeAppCheck`. -**Locked shape (AC0 gap-analysis):** +**Locked shape (from gap-analysis):** | Layer | Value | | ----- | ----- | diff --git a/okf-bundle/packages/app-check/index.md b/okf-bundle/packages/app-check/index.md index d46a7b235c..bd3791705b 100644 --- a/okf-bundle/packages/app-check/index.md +++ b/okf-bundle/packages/app-check/index.md @@ -5,7 +5,6 @@ Knowledge for App Check native/JS initialization, especially iOS provider-factor ## Documents * [Architecture decisions (ADR)](architecture-decisions.md) — `AppCheck-AD-*` (pending provider, fail-closed tokens, plugin order, deferred firebase.json pre-JS provider) -* [iOS provider init work queue](ios-provider-init-work-queue.md) — ephemeral gates for [#9116](https://github.com/invertase/react-native-firebase/issues/9116) (pending + fail-closed fix) ## Related repository files diff --git a/okf-bundle/packages/app-check/ios-provider-init-work-queue.md b/okf-bundle/packages/app-check/ios-provider-init-work-queue.md deleted file mode 100644 index d4e0750ab4..0000000000 --- a/okf-bundle/packages/app-check/ios-provider-init-work-queue.md +++ /dev/null @@ -1,230 +0,0 @@ ---- -type: Reference -title: App Check iOS provider init work queue -description: Ephemeral tracker for fixing iOS App Check installing the debug provider before JS configure (GitHub #9116). -tags: [app-check, ios, provider, work-queue] -timestamp: 2026-08-04T00:00:00Z ---- - -# App Check iOS provider init — work queue - -> **DONE:** All gates closed 2026-08-07. Commit subject: `fix(app-check, ios): do not install debug provider before configure`. No further pickup for this item. -> **Goal:** Stop release (and DEBUG) builds from installing `FIRAppCheckDebugProvider` during eager `FirebaseApp.configure()`; pending facade + fail-closed tokens until `configureProvider`; JS configure-before-auto-refresh; plugin comment/docs honesty; soft-break troubleshooting docs. -> **Upstream:** [#9116](https://github.com/invertase/react-native-firebase/issues/9116). Contributor [#9117](https://github.com/invertase/react-native-firebase/pull/9117) left open as temporary patch; close manually when the durable PR is up (do not merge #9117 as the long-term design). - -Ephemeral tracker; see [OKF policy](../../documentation-policy.md). Work types / tiers / gate field ids: [iteration vocabulary](../../testing/iteration-vocabulary.md). **Loop, gates, host rule, harness:** [change authoring workflow](../../testing/change-authoring-workflow.md) — not restated. **Agent commands:** [agent command policy](../../testing/agent-command-policy.md) only. - -Durable decisions: **[architecture-decisions.md](architecture-decisions.md)**. Package index: **[index.md](index.md)**. - ---- - -## Locked decisions (index) - -| ADR | Decision | -| --- | -------- | -| [AppCheck-AD-1](architecture-decisions.md#appcheck-ad-1--pending-provider-before-configure-fail-closed-token-apis--accepted) | Pending provider + fail-closed tokens | -| [AppCheck-AD-2](architecture-decisions.md#appcheck-ad-2--same-pending-path-for-debug-and-release--accepted) | Same path for DEBUG and release | -| [AppCheck-AD-3](architecture-decisions.md#appcheck-ad-3--expo--appdelegate-keep-factory-before-firebaseappconfigure--accepted) | Keep factory before `configure()`; fix comments/docs only | -| [AppCheck-AD-4](architecture-decisions.md#appcheck-ad-4--initializeappcheck-configure-provider-before-enabling-auto-refresh--accepted) | JS: configure provider before auto-refresh | -| [AppCheck-AD-5](architecture-decisions.md#appcheck-ad-5--pre-js-native-provider-via-firebasejson--deferred) | firebase.json pre-JS provider — **Deferred** | -| [AppCheck-AD-6](architecture-decisions.md#appcheck-ad-6--native-regression-coverage-preferred-no-new-ios-xctest-platform-in-this-fix--accepted) | Prefer native seam/test; fallback Jest/plugin/e2e | -| [AppCheck-AD-7](architecture-decisions.md#appcheck-ad-7--soft-break-release-framing--accepted) | Soft-break bug fix + troubleshooting docs | -| [AppCheck-AD-8](architecture-decisions.md#appcheck-ad-8--fail-closed-error-identity--accepted) | `appCheck/provider-not-ready` — **Accepted** (AC0) | - ---- - -## Phase ordering - -| Phase | Focus | Why | -| ----- | ----- | --- | -| **AC0** | `gap-analysis` | Promote/confirm ADRs; lock AppCheck-AD-8; estimate diff size → keep one AC1 or split AC1a/b/c | -| **AC1** | `implementation` | Pending factory + fail-closed + tests; JS reorder; plugin comment (single item if reasonably sized) | -| **AC2** | `independent-review` | Frozen tree; area-focused; **iOS + Android + macOS** app-check e2e | -| **AC3** | `documentation` | Site troubleshooting (`exchangeDebugToken` 403); usage “configure before use”; OKF durable moves; release-note wording | -| **AC4** | `commit` | [change authoring § commit](../../testing/change-authoring-workflow.md#commit) (or per-split subjects if AC0 re-slices) | - -**Re-slice rule (AC0):** Prefer one AC1 implementation if the diff stays reasonably sized. If AC0 estimates a large blast radius, split before coding into e.g. **AC1a** native pending/fail-closed + tests, **AC1b** JS reorder, **AC1c** plugin comment — each with its own gates/commit subjects as needed. - ---- - -## Resume checklist - -Before any `:test-cover` ([host rule](../../testing/change-authoring-workflow.md#host-rule)): - -1. [Pre-flight](../../testing/running-e2e.md#pre-flight-is-the-host-clear-to-start): host-clear probes, services ready, harness matches validation tier; [harness narrowing gate](../../testing/running-e2e.md#harness-narrowing-gate-blocking); serial `:test-cover`; [frozen tree](../../testing/change-authoring-workflow.md#frozen-tree) for `independent-review`. -2. **unit-focused (AC1):** iOS-speed loop (native `:build` when iOS native touched) + Jest + plugin tests; Android/macOS e2e optional unless needed for diagnosis. -3. **area-focused (AC2):** full loaded app-check spec on **iOS, Android, and macOS**. - ---- - -## Current snapshot - -**Label:** `app-check-ios-provider-init-queue-authored-2026-08-04` - -**Next pickup:** none — item complete. - -**Current gates:** AC0–AC4 all closed 2026-08-07. AC1/AC2 `review_gate` closed on a user-accepted exception for the delta re-review tier (see AC2 section below). `commit_gate` closes on the commit matching the subject above. - ---- - -## Item arbiter - -| Item | Scope | `commit_subject` | `implementation_gate` | `review_gate` | `commit_gate` | `next_work_type` | `validation_tier` | `platform` | Notes | -| ---- | ----- | ---------------- | ----------------------- | ------------- | ------------- | ---------------- | ------------------- | ---------- | ----- | -| **AC0** | ADR lock + size / re-slice | — | closed | closed | closed | — (done) | `none` | — | Closed 2026-08-04. Single AC1 (~150–250 LOC). AppCheck-AD-8 Accepted as `appCheck/provider-not-ready`. Do not merge #9117. | -| **AC1** | Native pending + fail-closed + tests; JS reorder; plugin comment | `fix(app-check, ios): do not install debug provider before configure` | closed | closed | closed | — (done) | `area-focused` | `ios`+`android`+`macos` | Exclude Podfile.lock. Nit remediation evidence below. | -| **AC2** | Independent review of AC1 | `fix(app-check, ios): do not install debug provider before configure` | closed | closed | closed | — (done) | `area-focused` | `ios`+`android`+`macos` | Full re-review green with nits 2026-08-05. Delta closed 2026-08-07 on user-accepted exception (see below). | -| **AC3** | User docs + durable OKF | `fix(app-check, ios): do not install debug provider before configure` | closed | closed | closed | — (done) | `none` | — | Docs done 2026-08-07. `lib/types/internal.ts` activate() docstring fixed; `docs/app-check/usage/index.mdx` Expo/configure-before-use note + new Troubleshooting section (`appCheck/provider-not-ready`, `exchangeDebugToken` soft-break). AD-8 durable docs re-verified accurate against code, no changes needed. | -| **AC4** | Commit | `fix(app-check, ios): do not install debug provider before configure` | closed | closed | closed | — (done) | `none` | — | Stage product + docs + this queue together. Exclude `tests/*/Podfile.lock`. | - ---- - -## AC0 — gap-analysis checklist - -Read-only. Closed 2026-08-04 (explore gap-analysis). - -- [x] Confirm factory-before-configure still required by current Firebase iOS App Check docs/SDK behavior -- [x] Trace `createProviderWithApp:` → eager `FIRAppCheckInterop` → JS `configureProvider` on current `main` -- [x] Choose fail-closed `NSError` / JS code — **Accepted:** `provider-not-ready` → `appCheck/provider-not-ready` ([AppCheck-AD-8](architecture-decisions.md#appcheck-ad-8--fail-closed-error-identity--accepted)) -- [x] Assess native test seam vs XCTest cost — nil `delegateProvider` seam; no new XCTest; Jest + plugin + AC2 e2e ([AppCheck-AD-6](architecture-decisions.md#appcheck-ad-6--native-regression-coverage-preferred-no-new-ios-xctest-platform-in-this-fix--accepted)) -- [x] Estimate AC1 diff size → **single AC1** (~150–250 LOC); no AC1a/b/c -- [x] Note plugin snapshot tests — source-comment-only → **no** snapshot updates unless emitted AppDelegate text changes -- [x] Note stale docs lines for AC3 — `packages/app-check/lib/types/internal.ts` “including the module”; `docs/app-check/usage/index.mdx` Expo/configure-before-use / missing `exchangeDebugToken` troubleshooting; plugin comment inverted - -**AC0 notes (evidence summary):** - -- Footgun: `RNFBAppCheckProviderFactory.m` `createProviderWithApp:` calls `configure:… providerName:@"debug"`. -- JS AD-4 gap: `lib/index.ts` enables auto-refresh before `configureProvider`. -- Module today maps all provider errors to `token-error`; AC1 must map pending → `provider-not-ready`. -- Android already throws if `create` before configure; iOS uses pending facade instead (AD-1). - ---- - -## AC1 — implementation acceptance (draft) - -- [x] Pre-configure `createProviderWithApp:` does not call `configure:… providerName:@"debug"` -- [x] Pending token APIs fail closed (no network) -- [x] `configureProvider` attaches real delegate; subsequent tokens use configured provider -- [x] JS `initializeAppCheck` configures provider before auto-refresh -- [x] Expo plugin comment corrected; emitted order unchanged -- [x] Tests per AppCheck-AD-6; validation + coverage evidence recorded (unit-focused) - -**AC1 unit-focused validation evidence:** - -| Check | Exit | Result | Log | -| --- | --- | --- | --- | -| `yarn` + `yarn lerna:prepare` | 0 | green | (shell) | -| Jest app-check + plugin | 0 | **25 passed**, 5 snapshots unchanged | `/tmp/rnfb-jest-app-check.log` | -| `yarn lint` (js+deps+android+ios) | 0 | green | `/tmp/rnfb-lint.log` | -| `yarn tests:ios:pod:install` | 0 | pods installed | `/tmp/rnfb-ios-pod-install.log` | -| `yarn tests:ios:build` | 0 | Build Succeeded | `/tmp/rnfb-ios-build.log` | -| `yarn tests:ios:test-cover` | 0 | **42 passing**, 0 failing | `/tmp/rnfb-e2e-ios.log` | -| `yarn tests:ios:test:process-coverage` | 0 | `coverage/ios-native/lcov.info` | `/tmp/rnfb-ios-native-coverage.log` | - -Harness: narrowed to `app`+`appCheck` during run; overrides removed after. Coverage: factory/configure/JS AD-4 hit; pending fail-closed **0% e2e** — gap disposition AppCheck-AD-6 nil-delegate seam (ADR-accepted). Residual: optional e2e negative case for AC2 judgment. Note: `tests/ios/Podfile.lock` dirty from pod install (review whether to include). - ---- - -## AC2 — independent-review (failed 2026-08-05) - -**Verdict:** failed (critical). Area-focused e2e green: iOS 42 / Android 42 / macOS 35+2 pending. Jest 24. Harness narrowed `app`+`appCheck`, reverted after. **Exclude** `tests/ios/Podfile.lock` and `tests/macos/Podfile.lock` from commit. - -| Severity | Finding | Fix | -| --- | --- | --- | -| **critical** | AD-8 JS identity lost: `FIRAppCheck` wraps `RNFBErrorDomain` pending errors; module reads top-level `userInfo[@"code"]` only → JS gets `appCheck/token-error` not `appCheck/provider-not-ready`. Files: `RNFBAppCheckProvider.m` emit; `RNFBAppCheckModule.mm` mapper. | In module `getToken` / `getLimitedUseToken`, if factory provider for app has `delegateProvider == nil`, reject `provider-not-ready` **before** calling FIRAppCheck. Optionally also walk `NSUnderlyingErrorKey`. | -| **nit** | Podfile.lock churn (AppCheckCore patch + macOS pod install) | Exclude from AC1 commit | - -**AC2 validation evidence:** - -| Check | Exit | Result | Log | -| --- | --- | --- | --- | -| Jest app-check + plugin | 0 | 24 passed | `/tmp/rnfb-jest-app-check.log` | -| `yarn tests:ios:test-cover` | 0 | **42 passing** | `/tmp/rnfb-e2e-ios.log` | -| `yarn tests:android:test-cover` | 0 | **42 passing** | `/tmp/rnfb-e2e-android.log` | -| `yarn tests:macos:test-cover` | 0 | **35 passing**, 2 pending | `/tmp/rnfb-e2e-macos.log` | - -Coverage: factory pending/configure/JS AD-4 hit; module `provider-not-ready` mapper **0%** (broken by SDK wrap). AD-6 e2e gap on pending path not a separate finding; finding #1 is product/AD-8. - ---- - -## AC2 — independent-review re-run (green with nits 2026-08-05) - -**Verdict:** green with nits. Prior AD-8 critical **resolved** (iOS e2e both pending cases assert `provider-not-ready`, not `token-error`). Acceptance 1–7 hold. Do not merge #9117. - -| Severity | Finding | Disposition | -| --- | --- | --- | -| **nit** | AD-8 message string duplicated | **Fixed** — `kRNFBAppCheckProviderNotReadyMessage` in Provider.h/.m; Module uses shared constant. Unit-focused iOS 44 green. | -| **nit** | `tests/ios/Podfile.lock` + `tests/macos/Podfile.lock` dirty | **Exclude** from commit (not product) | - -**Nit remediation validation (unit-focused iOS):** - -| Check | Exit | Result | Log | -| --- | --- | --- | --- | -| `yarn tests:ios:build` | 0 | Build Succeeded | (shell) | -| `yarn tests:ios:test-cover` | 0 | **44 passing** (both AD-8 cases) | `/tmp/rnfb-e2e-ios.log` | - -**AC2 validation evidence:** - -| Check | Exit | Result | Log | -| --- | --- | --- | --- | -| Jest app-check + plugin | 0 | **25 passed** | `/tmp/rnfb-jest-app-check.log` | -| `yarn lint` / `yarn compare:types` | 0 | green | `/tmp/rnfb-lint.log`, `/tmp/rnfb-compare-types.log` | -| `yarn tests:ios:test-cover` | 0 | **44 passing** | `/tmp/rnfb-e2e-ios.log` | -| `yarn tests:android:test-cover` | 0 | **42 passing**, 2 pending | `/tmp/rnfb-e2e-android.log` | -| `yarn tests:macos:test-cover` | 0 | **35 passing**, 4 pending | `/tmp/rnfb-e2e-macos.log` | - -Harness: `app`+`appCheck`, reverted. Coverage: pre-check FNDA:7; provider pending bodies FNDA:0 (shadowed by module pre-check, acceptable). - -**Delta re-review disposition (user-accepted exception, 2026-08-07):** The 2026-08-05 area-focused reviewer run above already covers the full AC1 diff pre-fix. The subsequent nit fix (shared `kRNFBAppCheckProviderNotReadyMessage` constant) touches only `RNFBAppCheckProvider.h/.m` and `RNFBAppCheckModule.mm` — a string-literal extraction, no logic change, no Android/macOS files touched. A fresh area-focused reviewer for this delta would re-run Android/macOS e2e that this diff cannot affect. User confirmed accepting the iOS-only unit-focused evidence (`yarn tests:ios:build` + `yarn tests:ios:test-cover`, 44 passing, both AD-8 pending cases) as sufficient to close `review_gate` for AC1/AC2, in lieu of relaunching the delta area-focused reviewer. `review_gate` closed 2026-08-07. - ---- - -## AC1 remediation — AD-8 mapping (unit-focused green 2026-08-05) - -**Fix:** `RNFBAppCheckRejectIfProviderNotReady` in module before FIRAppCheck; `providerForApp:` on factory; `RejectCodeForError` walks `NSUnderlyingErrorKey`. E2e on `secondaryFromNative` asserts `provider-not-ready` (not `token-error`). - -| Check | Exit | Result | Log | -| --- | --- | --- | --- | -| Jest `appcheck.test.ts` | 0 | **15/15** | `/tmp/rnfb-jest-appcheck.log` | -| `yarn tests:ios:build` | 0 | Build Succeeded | `/tmp/rnfb-ios-build.log` | -| `yarn tests:ios:test-cover` | 0 | **44 passing**, 0 failing | `/tmp/rnfb-e2e-ios.log` | -| `yarn tests:ios:test:process-coverage` | 0 | `coverage/ios-native/lcov.info` | (processed 2026-08-05) | - -Harness: `app`+`appCheck`, reverted after. Coverage: pre-check helper FNDA:7; AD-8 e2e both green. Exclude Podfile.lock. - ---- - -## AC3 — documentation (closed 2026-08-07) - -**Scope:** `packages/app-check/lib/types/internal.ts` (stale `activate()` docstring), `docs/app-check/usage/index.mdx` (Expo/configure-before-use note, new Troubleshooting section), durable OKF re-verification (no changes needed — `AppCheck-AD-8` locked shape confirmed to match code exactly), OKF bundle consistency scan. - -**Validation evidence:** - -| Check | Exit | Result | -| --- | --- | --- | -| `yarn lerna:prepare` | 0 | 20 projects, app-check rebuilt clean | -| `yarn tsc:compile` | 0 | no errors | -| `yarn lint:js` | 0 | no errors | -| `yarn lint:markdown` | 0 | Prettier-clean | -| `yarn lint:spellcheck` | 0 | no failures | -| `yarn format:js` | 0 | no reformat needed on target files (unrelated `packages/app/type-test.ts` drift reformatted then reverted, out of scope) | -| `yarn compare:types` | 0 | app-check: 4 missing / 9 extra / 2 different — documented (pre-existing) | - -**OKF bundle consistency pass:** full `okf-bundle/` sweep, focused on `packages/app-check/**` and inbound links. No DRY violations or dangling anchors found in files touched by this item. - -**Draft release-note wording** (repo has no CHANGELOG/changeset file; for PR body use): - -- Fixed: on iOS, App Check could install and use the debug provider before `initializeAppCheck` ran, including in release builds, sometimes producing unexpected `exchangeDebugToken` 403/429 traffic. The native provider now stays pending until `initializeAppCheck` (or the deprecated `activate`) is called. -- Behavior change: requesting a token before `initializeAppCheck` now rejects immediately with `appCheck/provider-not-ready` instead of silently exchanging a debug token or falling through to another provider. - ---- - -## Related product files (starting points) - -- `packages/app-check/ios/RNFBAppCheck/RNFBAppCheckProviderFactory.m` -- `packages/app-check/ios/RNFBAppCheck/RNFBAppCheckProvider.m` -- `packages/app-check/ios/RNFBAppCheck/RNFBAppCheckModule.mm` -- `packages/app-check/lib/index.ts` (`initializeAppCheck`) -- `packages/app-check/plugin/src/ios/appDelegate.ts` -- `packages/app-check/plugin/__tests__/` -- `docs/app-check/usage/index.mdx` diff --git a/okf-bundle/packages/firestore/index.md b/okf-bundle/packages/firestore/index.md index 502a617d09..89bb89383f 100644 --- a/okf-bundle/packages/firestore/index.md +++ b/okf-bundle/packages/firestore/index.md @@ -7,7 +7,6 @@ Firestore Pipelines (`pipelines` entry) and native bridge behavior. ## Documents * [**Other platform — Firestore Lite**](other-platform-firestore-lite.md) — macOS/Other uses `firebase/firestore/lite` only; unsupported API list; web bridge files -* [Coverage work queue](pipeline-coverage-work-queue.md) — ephemeral gates and `next_work_type` * [Pipelines implementation workflow](pipeline-implementation-workflow.md) — compare-types, serialization, coverage snapshots; extends [change authoring](../../testing/change-authoring-workflow.md) * [Serialization testing](serialization-testing.md) — required Jest/e2e checks per expression export * [Platform parity](pipeline-platform-parity.md) — drift registry, remediation, iOS unsupported map diff --git a/okf-bundle/packages/firestore/pipeline-coverage-work-queue.md b/okf-bundle/packages/firestore/pipeline-coverage-work-queue.md deleted file mode 100644 index 44bf6a7b49..0000000000 --- a/okf-bundle/packages/firestore/pipeline-coverage-work-queue.md +++ /dev/null @@ -1,415 +0,0 @@ ---- -type: Reference -title: Pipeline coverage and parity work queue -description: Phase tracker for Firestore Pipelines coverage expansion, platform parity audit/remediation, and SDK support reconciliation. -tags: [firestore, pipelines, coverage, parity, e2e, work-queue] -timestamp: 2026-06-25T12:00:00Z ---- - -# Pipeline coverage and parity — work queue - -> **COMPLETE:** **Merge gate** closed — static pre-merge green; **R** closed. Ready for PR [9086](https://github.com/invertase/react-native-firebase/pull/9086) force-push + CI **after** [validation evidence](../../testing/change-authoring-workflow.md#validation-evidence-blocking) still valid on published commits. -> **Goal/order:** platform parity first; then TS/native coverage toward intractable limits. Links: [parity](pipeline-platform-parity.md), [SDK audit](pipeline-sdk-support-audit.md), [coverage](../../testing/coverage-design.md), [e2e](../../testing/running-e2e.md), [architecture](pipelines.md). - ---- - -Ephemeral tracker; see [OKF policy](../../documentation-policy.md). - ---- - -## Phase ordering (2026-06-25) - -**Parity before coverage.** Otherwise tests add `Platform.`* workarounds, misclassify bridge drift as intractable, and deepen Swift/Java drift. - -**Sequence from H onward:** **H** → **I** drift inventory → **Ib** SDK support reconciliation → **J** (**J0** probes → **J0b** iOS lowering consolidation → **J1–J6** bridge) → **K–Q** coverage → **R** snapshot. - - -| Phase | Focus | -| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Ib** | Reconcile SDK CHANGELOG + bridge audit vs RNFB lowering; [repeatable method](pipeline-sdk-support-audit.md) | -| **J0** | iOS runtime probes — one function per commit; authoritative guard list | -| **J0b** | **iOS NodeBuilder lowering consolidation** — dedupe boolean/receiver-chain paths added during J0 (see [J0b](#j0b--ios-nodebuilder-lowering-consolidation-complete)); **before J1–J6** | -| **J1–J6** | Bridge remediation (P-001, P-005, P-010–P-012, P-034) after **J0 + J0b** | - - ---- - -## Resume checklist - -Gate prerequisites before any `:test-cover` ([host rule](../../testing/change-authoring-workflow.md#host-rule)): - -1. [Pre-flight](../../testing/running-e2e.md#pre-flight-is-the-host-clear-to-start): [host-clear probes](../../testing/running-e2e.md#host-clear-probes), [services ready](../../testing/running-e2e.md#2-services-ready), [harness matches validation tier](../../testing/running-e2e.md#3-harness-matches-validation-tier) ([narrowing gate](../../testing/running-e2e.md#harness-narrowing-gate-blocking) — required for **unit-focused** and **area-focused**; not [push harness](#harness)); [one :test-cover at a time](../../testing/running-e2e.md#one-test-cover-at-a-time); [frozen tree](../../testing/change-authoring-workflow.md#frozen-tree) for `independent-review`. -2. Guard probes: [SDK runtime verification](pipeline-sdk-support-audit.md#6-runtime-verification-authoritative) + [Phase J protocol](#phase-j-iteration-protocol-strict) below. -3. Coverage deltas: full clean cycle; never trust stale `.ec`/profraw ([coverage stale data](../../testing/coverage-design.md#stale-coverage-data)). - ---- - -## Phase table - - -| Phase | Focus | Status | Outcome | -| ------ | ------------------------------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | -| **A** | Baseline e2e + Jet TS coverage | ✅ | 3-platform verify; harness + jet patch | -| **B** | Android dead-code removal | ✅ | `buildParsed`* cluster; NodeBuilder 55%→66% | -| **C** | Gap map + tooling | ✅ | `map-pipeline-coverage-gaps.sh` | -| **D** | Native lowering e2e | ✅ | subcollection 100%; schedule dispatch 100% | -| **E** | Executor / Parser / BridgeFactory e2e | ✅ | Android Executor 49%→58%; iOS BridgeFactory 83% | -| **F** | Android L900–1299 lowering | ✅ | **Dead removal** — loop 106→77 missed; NodeBuilder 70.2% | -| **G** | iOS operand modes + map passthrough | ✅ | **+8 operand probes** via raw-where e2e; map execute intractable | -| **H** | TS `pipeline_validate` execute guards | ✅ | e2e tamper tests + Android parser ref-constant fix; `pipeline_validate` ~93% macOS TS lcov | -| **I** | **Platform parity audit** | ✅ | 31 e2e branches; registry P-001–P-031 | -| **Ib** | **SDK support reconciliation** | ✅ | Guard list vs iOS 12.15 / Android 34.15 CHANGELOG; [audit method](pipeline-sdk-support-audit.md) | -| **J** | **Parity remediation** | **✅ complete** | **J0** probes → **J0b** consolidation → **J0 remainder** → **J1–J6** | -| **K** | TS `pipeline_runtime` + `expressions` | **✅** | Jest alias/normalization batch; expressions e2e receiver probe | -| **L** | Android parsed-aggregate tail | **✅** | expression-arg `arrayAgg`/`arrayAggDistinct` e2e; parsed tail 258/408 | -| **M** | Android exit frames + receiver chains | **✅** | 3 e2e; NodeBuilder 75.03%; exit −29 missed | -| **N** | iOS stage coercion | **✅** | iOS/web stage coercion + operand tail; macOS 139 / iOS 144 / Android 144 area-focused | -| **O** | Android Executor remainder | **✅** | 58%→60.94%; 7 e2e; ~130 missed dead-code → Phase Q | -| **P** | Jest-only TS paths | **✅** | 100% lines pipeline_validate; L49 → Q | -| **Q** | Intractability audit | **✅** | −238 Executor dead lines; intractable caps documented | -| **R** | Pre-merge harness restore | **✅** | 698/0 macOS; 866/0 Android; iOS 838/0 after `38cc8815a` fix | - - -**Compare-types exports:** unblocked — **R** complete. - ---- - -## Current snapshot - -**Label:** `after-phase-r-final`; **harness:** full app (committed defaults) - -**Next item:** force-push branch → PR 9086 CI → paste [PR post draft](#pr-post-draft-coverage-table--copy-for-merge-comment) — only after [validation evidence](../../testing/change-authoring-workflow.md#validation-evidence-blocking) still valid on published commits. - -**Current gates:** **Merge gate** **closed** (2026-07-03). compare:types 19/19 documented; Jest 1146/1146; tsc + lint green. **K–R** complete. - -**E2e (Phase R full tier):** macOS **698**/0, iOS **838**/0, Android **866**/0 passing. - -| Target | Phase A baseline | Phase R final | Delta | -| ------ | ---------------- | ------------- | ----- | -| TS `pipeline_runtime.ts` | **86%** | **91.07%** (204/224) | **+5.07 pp** | -| TS `expressions.ts` | **89%** | **93.98%** (250/266) | **+4.98 pp** | -| TS `pipeline_validate.ts` | **~93%** | **88.64%** (78/88) | −4.36 pp (e2e lcov vs macOS/Jest mix) | -| Android NodeBuilder | **67.5%** (1167/1729) | **75.18%** (1324/1761) | **+7.68 pp** | -| Android Executor | **~49%** / **58%** (post-E) | **76.59%** (386/504) | **+18.6–27.6 pp** | -| iOS NodeBuilder | **68.89%** | **69.10%** (1516/2194) | **+0.21 pp** | -| Android EnterObject loop (L900 band) | **106 missed** | **65 missed** (71.98%) | **−41 missed** | -| iOS operand modes (L919–1006) | **27 missed** (69.32%) | **17 missed** (72.58%) | **−10 missed** | - -**Notable commits:** parity J0–J6; coverage K–Q (−238 Executor dead lines); R-iOS `38cc8815a`; android coverage upload `94299783a`. - ---- - -| **Q** Intractability audit | `refactor(firestore, android): remove dead pipeline Executor lowering code` | **closed** | **closed** | **closed** | — | — | — | −238 lines; 151 Android pass; intractable caps in queue | - -| **J2** P-005 `integerLiteral` | `fix(firestore, android): align pipeline integerLiteral constant lowering with iOS` | **closed** | **closed** | **closed** | — | — | — | P-005 → Resolved; CFBoolean deferral accepted | -| **J3** P-010 stage option expressions | `fix(firestore, android): align pipeline stage option expression fields with iOS` | **closed** | **closed** | **closed** | — | — | — | P-010 → Resolved | -| **J4** P-011 constant envelope | `fix(firestore, android): align pipeline constant envelope routing with iOS` | **closed** | **closed** | **closed** | — | — | — | P-011 → Resolved | -| **J5** P-012 timestampTruncate arity | `fix(firestore, android): align pipeline timestampTruncate arity validation with iOS` | **closed** | **closed** | **closed** | — | — | — | P-012 → Resolved; iOS explicit arity guard deferred | -| **J6** P-034 operand-mode audit | `docs(firestore): close P-034 operand-mode e2e audit after J1 parity` | **closed** | **closed** | **closed** | — | — | — | No code trims; P-021/P-022 confirmed | -| **K** TS runtime/expressions | `test(firestore): expand pipeline TS runtime and expression coverage` | **closed** | **closed** | **closed** | — | — | — | Jest batch + receiver `currentTimestamp` e2e probe | - -**Arbiter gate (2026-06-25):** - - -| Probe | `commit_subject` | `implementation_gate` | `review_gate` | `next_work_type` | `validation_tier` | `platform` | Notes | -| ----------------------------- | ---------------- | --------------------- | ------------- | ---------------- | ----------------- | ---------- | ----------------------------------------------------------------------- | -| **J0-1** `stringRepeat` | — | closed | **closed** | — | — | — | stringRepeat unified iOS path | -| **J0-2** `switchOn` | — | closed | **closed** | — | — | — | switchOn unified iOS path | -| **J0-3** `trunc` | — | closed | **closed** | — | — | — | trunc unified iOS path | -| **J0-4** `conditional` | — | closed | **closed** | — | — | — | iOS wire `conditional`; unified e2e | -| **J0-5** `round` | — | closed | **closed** | — | — | — | round unified iOS path (TS-only) | -| **J0-6** `substring` | — | closed | **closed** | — | — | — | **rnfb-bridge-gap** — reclassified; guard retained | -| **J0-7** `timestampAdd` | — | closed | **closed** | — | — | — | **rnfb-bridge-gap** — probe + SDK source; guard retained | -| **J0-8** `timestampSubtract` | — | closed | **closed** | — | — | — | **rnfb-bridge-gap** — SDK `timestamp_subtract`; fix iOS wire + receiver | -| **J0-9** `arrayGet` | — | closed | **closed** | — | — | — | **rnfb-bridge-gap** — SDK `array_get` receiver wire; guard retained | -| **J0b** | — | closed | **closed** | — | — | — | switchOn boolean receiver consolidation | -| **J0-6′** `substring` | — | closed | **closed** | — | — | — | iOS receiver chain; guard removed; unified e2e | -| **J0-7′** `timestampAdd` | — | closed | **closed** | — | — | — | `timestampAdd(amount:unit:)` | -| **J0-8′** `timestampSubtract` | — | closed | **closed** | — | — | — | wire `timestamp_subtract` | -| **J0-9′** `arrayGet` | — | closed | **closed** | — | — | — | `.arrayGet(_:)` | -| **J1** P-001 operand coercion | `fix(firestore, android): align pipeline operand coercion with iOS` | **closed** | **closed** | **closed** | — | — | — | P-001 → Resolved; deferred `COMPARISON_OPERAND` call-site wiring | - - - -| Target | macOS | iOS | Android (gap map) | Phase | -| --------------------------- | ----------------- | ---------------------- | -------------------------------------- | ----- | -| Parity drift (bridge) | — | — | **0 open** (P-034 closed) | **J** | -| Parity drift (SDK/macOS-js) | 11 vacuous | 10 reduced + 3 vacuous | documented | — | -| TS `pipeline_runtime.ts` | 86% | **90.62% (203/224)** | K batch (Jest; e2e lcov unchanged) | **K** | -| TS `expressions.ts` | 89% | **93.61% (249/266)** | K batch (+1 e2e line) | **K** | -| Android NodeBuilder | 67.5% (1167/1729) | **75.03% (1322/1762)** | M: exit −29 missed; loop −12 | L, M | -| Android loop L900–1299 | 106 missed | **64 missed** | M: −12 from baseline 76 | M | -| Android Executor | 58% | **~97% live (387/~397)** post-Q dead removal | Q: −238 lines dead; jacoco regen at commit | O, Q | -| iOS NodeBuilder | 68.89% | **~70%+ (Phase N)** | G: +15 hit; N: stage coercion | N | -| iOS operand modes L919–1006 | 27 missed | **reduced (Phase N)** | N operand tail e2e | N, Q | - - -```bash -bash scripts/map-pipeline-coverage-gaps.sh # current -bash scripts/map-pipeline-coverage-gaps.sh after-phase-g -bash scripts/map-pipeline-coverage-gaps.sh after-phase-f-dead-removal -``` - ---- - -## Branch commits (A–G) - -| Commit subject | Summary | -| -------------- | ------- | -| Android e2e infra: Detox FabricTimers, `.ec` delete, OKF stale-coverage docs | Phase A infra | -| Android NodeBuilder: remove dormant lowering duplicates (Phase F) | Dead-code removal | -| E2e: expression frame lowering regression cases (Phase F) | Lowering e2e | -| E2e: iOS operand modes via raw where filters (Phase G) | Operand-mode probes | - -Earlier: A–E baseline, dead code, gap map, lowering/executor e2e. - ---- - -## Completed phase summaries - -### Phase F (Android loop L900–1299) - -- Added five e2e tests under `enter object expression frame lowering coverage`; green 128/133/133; **zero Jacoco delta** because Parser normalizes before NodeBuilder. -- Removed **183 lines** duplicate/zero-caller lowering: wrappers, raw-operator boolean arms duplicated in Parser, scalar/String/Expression entry arms unreachable from `serializeExpressionNode`. -- **Result:** loop **106 → 77 missed**; NodeBuilder **67.5% → 70.2%** (fewer lines, higher %). -- **Remainder → Phase M:** vector expression handler (expression-vector rhs), exit/receiver tails. - -**Lesson:** e2e that passes but moves no probes → audit callers before adding more tests. - -### Phase G (iOS operand modes + map passthrough) - -- One e2e: `coerces bare rhs operands through raw where filters`; raw `.where({ condition: { operator, fieldPath, value }})` with bare string/array/bool rhs (modular wraps rhs constants and misses operand-mode arms). -- **Result:** iOS NodeBuilder **+0.95 pp**; operand modes **69.32% → 78.41%** (−8 missed). -- **Map passthrough execute success (L1208–1219):** **intractable** — Firestore rejects `map(field(…))` execute; lowering already covered by existing error-path e2e. -- **Operand tail (19 missed):** L928, L948–949, L961–966, L973–974, L990–1006 — triage in **Phase I**; Android side is **P-001** (bridge gap, not coverage-only). -- **Parity note:** e2e uses `Platform.android` split for ordering RHS — **must close in Phase J**, not extend in Phase K+. - -### Infra side quest (Phase A) - -- Detox `FabricTimersIdlingResource` no-op under New Arch (launch crash fix). -- Android post-e2e deletes processed `.ec` (parity with iOS profraw delete). -- OKF: stale coverage → full clean cycle, do not re-report without fresh e2e. - ---- - -## Phase H — complete - -**Commit subject:** `test(firestore): expand pipeline execute validation e2e coverage` (representative). - -- Six e2e tests tamper `_source`/`_stages` before `execute()` to hit JS validation guards. -- **Result:** `pipeline_validate.ts` ~93% macOS TS lcov (+17 lines). -- **Remaining 6 lines → Phase P/Q:** runtime-unreachable guards; Jest `pipelines-validate.test.ts` covers direct-call paths. -- **Android parser fix:** document-reference `{ path: "col/doc" }` constants. - ---- - -## Phase I — platform parity audit (complete 2026-06-25) - -**Deliverable:** [pipeline-platform-parity.md](pipeline-platform-parity.md) — full registry. - -**Audit inputs:** - -- E2e drift inventory — 31 `Platform.*` sites; 141/146 delta = 5 app `utils*` tests (not Pipeline) -- Native bridge diff — NodeBuilder coercion is primary drift -- JS guards audit — single `isIOS` pre-execute guard; execute-options JS gate on all platforms - -**Triage totals:** - - -| Class | Count | Action | -| ------------- | --------------------------------- | -------------------------------------- | -| **bridge** | 5 | Phase **J** (J1–J5) | -| **SDK** | 3 stage/aggregate gaps | Document (P-013–P-015) | -| **macOS-js** | 11 vacuous/reduced Pipeline tests | Document (P-004, P-018–P-028) | -| **test-only** | 1 | Unify after J1 (P-034) | -| **RNFB-JS** | 2 | Document or narrow in J (P-016, P-017) | -| **closed** | P-002, P-006 | — | - - ---- - -## Phase Ib — SDK support reconciliation (complete 2026-06-25) - -**Goal:** Document repeatable SDK/bridge audit method; drive Phase J queue from runtime e2e + native lowering. - -**Pins audited:** iOS Firestore **12.15.0**, Android BOM **34.15.0**. - -**Deliverables:** - -- [pipeline-sdk-support-audit.md](pipeline-sdk-support-audit.md) — repeatable method + support matrix -- Former iOS JS function guard removed (2026-06-25); parity is native bridge + unified e2e -- **Runtime e2e probes (Phase J0/J0 remainder) are authoritative** — CHANGELOG + bridge audit alone is insufficient - -**Audit input:** native bridge + CHANGELOG cross-check. - ---- - -## Phase J — parity remediation (complete) - -### Phase J iteration protocol (strict) - -Each J0 probe / J1–J6 bridge step uses the [change authoring primary loop](../../testing/change-authoring-workflow.md#primary-loop) and [work types](../../testing/change-authoring-workflow.md#work-types) (`documentation?` before frozen `independent-review`). No overlapping `:test-cover`. - -**Phase J harness / e2e (not a second loop):** `implementation` is Jest + **unit-focused** (`.only` / tight narrowing OK locally; **no commit**). Frozen `independent-review` is **area-focused**: [harness overrides](../../testing/running-e2e.md#local-harness-overrides-harnessoverridesjs); no `tests/**` except revert `.only` ([frozen tree](../../testing/change-authoring-workflow.md#frozen-tree)); serial [host rule](../../testing/change-authoring-workflow.md#host-rule). `commit` only after `review_gate` closed ([change authoring § commit](../../testing/change-authoring-workflow.md#commit)). - -Canonical commands: [one :test-cover at a time](../../testing/running-e2e.md#one-test-cover-at-a-time), [one iteration](../../testing/running-e2e.md#running-one-iteration), [guard probes](pipeline-sdk-support-audit.md#6-runtime-verification-authoritative) ([J0](#j0--ios-runtime-guard-probes-do-first)). - -### J0 — iOS runtime guard probes (do first) - -Per [SDK audit §6](pipeline-sdk-support-audit.md): one function/commit; remove guard; restore full iOS e2e assertions; verify canonical iOS e2e only. - - -| Probe | Function | Rationale | `implementation_gate` | `review_gate` | `next_work_type` | -| ----- | ------------------- | ------------------------------------------------------- | --------------------- | ------------- | ---------------- | -| J0-1 | `stringRepeat` | iOS CHANGELOG 12.12.0 | closed | **closed** | — | -| J0-2 | `switchOn` | iOS CHANGELOG 12.12.0 | closed | **closed** | — | -| J0-3 | `trunc` | iOS CHANGELOG 12.11.0 | closed | **closed** | — | -| J0-4 | `conditional` | `ConditionalExpression` 12.11.0; iOS wire `conditional` | closed | **closed** | — | -| J0-5 | `round` | No CHANGELOG; Android + bridge ok | closed | **closed** | — | -| J0-6 | `substring` | SDK API present; generic iOS wire fails | closed | **closed** | — | -| J0-7 | `timestampAdd` | SDK `timestamp_add` receiver wire | closed | **closed** | — | -| J0-8 | `timestampSubtract` | SDK `timestamp_subtract`; RNFB emits `timestamp_sub` | closed | **closed** | — | -| J0-9 | `arrayGet` | SDK `array_get` receiver wire | closed | **closed** | — | - - -**Output:** unified cross-platform e2e, confirmed parity classifications. - -### J0b — iOS NodeBuilder lowering consolidation (complete) - -**Commit subject:** `refactor(firestore, ios): consolidate pipeline switchOn boolean receiver lowering` - -**Why:** `switchOn` landed a parallel coercion layer alongside existing stack-based lowering. Correctness verified; **maintainability / drift risk** if more one-off paths land before consolidation. - -**Goal:** Consolidate J0-added boolean/receiver-chain lowering into **shared** NodeBuilder paths (align with Android `scheduleBooleanReceiverChain` / `EnterObjectBooleanFrame` where feasible). Remove fragile KVC probing where `ExprBridge` extraction exists. **No behavior change** — area-focused-tier Pipeline e2e must stay green (especially `switchOn`, `stringRepeat`, and any probe-specific cases). - -**Scope:** `packages/firestore/ios/RNFBFirestore/RNFBFirestorePipelineNodeBuilder.swift` only (unless consolidation requires Parser touch — stop and note). - -**Protocol:** [Change authoring primary loop](../../testing/change-authoring-workflow.md#primary-loop) (`documentation?` before frozen `independent-review`). Phase J harness/e2e: [Phase J iteration protocol](#phase-j-iteration-protocol-strict) — **unit-focused** `implementation` (switchOn + affected probe tests), then **area-focused** frozen review. - -**Gate for J1–J6:** **J0 complete + J0b committed** + parity registry updated. - -### J0 remainder — iOS receiver-chain parity (complete) - -**Status:** **complete** — J0-6′…J0-9′ receiver-chain batch: iOS lowering, empty guard list, unified e2e. - -**Scope delivered:** `RNFBFirestorePipelineNodeBuilder.swift` receiver infrastructure + unified e2e at substring / arrayGet (×2) / timestampAdd|Subtract sites. JS iOS function guard removed. - - -| Function | SDK wire (pinned iOS) | Fix | -| ------------------- | ------------------------------------------- | --------------------------------------------------- | -| `substring` | `substring` `[self, position, length?]` | `.substring(position:length:)` receiver chain | -| `timestampAdd` | `timestamp_add` `[self, unit, amount]` | `.timestampAdd(amount:unit:)` (amount first in SDK) | -| `timestampSubtract` | `timestamp_subtract` `[self, unit, amount]` | Wire `timestamp_subtract` + receiver chain | -| `arrayGet` | `array_get` `[self, offset]` | `.arrayGet(_:)` receiver chain | - - -### J1–J6 — bridge remediation (after J0 + J0b) - - -| Step | Registry | Work | -| ------ | -------- | ----------------------------------------------------------- | -| **J1** | P-001 | Android operand coercion parity | -| **J2** | P-005 | Android `integerLiteral` constant lowering | -| **J3** | P-010 | Expression-valued `distanceField` / `indexField` on Android | -| **J4** | P-011 | Parser constant envelope routing | -| **J5** | P-012 | `timestampTruncate` arity validation on Android | -| **J6** | P-034 | Unify operand-mode e2e after bridge parity | - - -**Gate for Phase K+:** J0 complete + **J0b** committed + J1–J6 bridge commits + parity **Resolved** updated. - -## Phase R — pre-merge snapshot - -**Status:** **closed** — full-tier 3-platform; iOS fix `38cc8815a` (`fix(firestore, ios): align pipeline stage option coercion with Android`). - -| Platform | Exit | Pass / Fail / Pending | Log | -| -------- | ---- | --------------------- | --- | -| macOS | 0 | 698 / 0 / 38 | `/tmp/rnfb-e2e-macos-r-full.log` | -| iOS | 0 | **838** / 0 / 87 | `/tmp/rnfb-e2e-ios-r-full-rerun.log` | -| Android | 0 | 866 / 0 / 58 | `/tmp/rnfb-e2e-android-r-full.log` | - -**R-iOS fix:** `coerceStageOptionFieldName` for unnest/findNearest; limit/offset defer to bridge factory. Area-focused 151/0; full-tier iOS re-run 838/0. - -**Gap map:** `bash scripts/map-pipeline-coverage-gaps.sh after-phase-r-final`; snapshot `scripts/snapshot-pipeline-coverage.sh after-phase-r-final`. TS + iOS + Android coverage artifacts present (`coverage/lcov.info`, `coverage/ios-native/lcov.info`, Jacoco). - ---- - -## Coverage phases (K–Q) — after parity - - -| Phase | Target | -| ----- | ------------------------------------------------------------------------ | -| **K** | `pipeline_runtime.ts` + `expressions.ts` normalization gaps | -| **L** | Android parsed-aggregate expression args (~143 missed) | -| **M** | Android exit frames, receiver chains, vector expression handler (F tail) | -| **N** | iOS stage coercion (~293 missed), operand tail | -| **O** | Android Executor error branches | -| **P** | Jest-only TS validation paths | -| **Q** | Intractability audit (map execute, debug gates, codegen caps) | - - -**R:** revert harness narrowing; **full** unfocused 3-platform run ([full tier](../../testing/running-e2e.md#e2e-validation-tiers-unit-focused-area-focused-full)); final gate before compare-types. - ---- - -## Harness - -- **Push state (committed):** full test app — all `platformSupportedModules` + `require.context` in `tests/app.js`. For merge/CI only; **not** the harness for local `:test-cover` during J–Q. -- **Local `:test-cover`:** must match arbiter `**validation_tier`** — [running e2e § harness + narrowing gate](../../testing/running-e2e.md#harness-narrowing-gate-blocking). `**implementation` → unit-focused** and `**independent-review` → area-focused:** both require [area narrowing](pipeline-implementation-workflow.md#pipeline-area-harness) locally **before** first run even when git has full harness. Revert before **R** (full tier). -- `tests/globals.js` — `RNFBDebug = true` optional **locally** for fail-fast; committed default must stay `false` ([running e2e § RNFBDebug](../../testing/running-e2e.md#fast-iteration-test-narrowing)) - ---- - -## Workflow (each phase) - -**Phases I–J (parity):** - -1. Audit or implement bridge fix with **shared** e2e assertions. -2. Update OKF parity registry (open/close rows). -3. **Phase J:** [change authoring primary loop](../../testing/change-authoring-workflow.md#primary-loop) (`documentation?` before frozen `independent-review`); Phase J harness/e2e in [Phase J iteration protocol](#phase-j-iteration-protocol-strict); never overlap `:test-cover` ([host rule](../../testing/change-authoring-workflow.md#host-rule)). -4. 3-platform e2e on canonical commands ([running-e2e rules 6–7](../../testing/running-e2e.md)). - -**Phases K–Q (coverage):** - -1. `bash scripts/map-pipeline-coverage-gaps.sh before-` -2. Prove **live vs dead** before implementing -3. *No new `Platform.` branches** — if a probe only passes on one platform, stop and file drift for Phase J follow-up -4. OKF background + `:build` if native + `:test-cover` + native post-process -5. `bash scripts/map-pipeline-coverage-gaps.sh after-` -6. One focused commit per logical change (message describes **what**, not phase letter) - -**Pitfalls:** iOS `constant(0/1)` → bool (use `constant(2+)`); raw AND where is Android-native (`Platform.other` skip on macOS; document); Detox boots AVD, no manual `emulator -avd`. - ---- - -## Phase Q — intractability audit (in progress) - -**Audit method:** caller grep + `buildNativePipeline` stack trace for union routing; Parser owns `readableMapToJava` for execute entry. - -**Removed (Android Executor, zero callers):** - -| Cluster | Lines | Rationale | -| ------- | ----- | --------- | -| `getJavaValue` / `readableMapToJava` / `readableArrayToJava` / `populateReadableContainers` + frame classes | ~200 | Duplicate Parser helpers; no call sites in Executor | -| `applyPrimitiveRawOptions` | ~42 | Superseded by `applyPrimitiveRawStageOptions` (live at `applyRawStage`) | -| `applyUnionStage` + `applyStage` union branch | ~9 | Unions handled in `buildNativePipeline` via `PendingUnionPipelineStage`; `ParsedUnionStage` never reaches `applyStage` | - -**Intractable (document only — no removal):** - -| Cap | Location | Rationale | -| --- | -------- | --------- | -| `validateSource` default param | `pipeline_validate.ts` L49 | Sole call site passes explicit `` `${fieldName}.source` ``; default unreachable; harmless | -| Map passthrough execute success | NodeBuilder L1208–1219 (G) | Firestore rejects `map(field(…))` execute | -| Map execute / task-guard tails | Executor `resolvePipelineTask` empty-exception arm | e2e-only; no stable probe | -| iOS operand-mode tail | NodeBuilder L928–1006 | Bridge parity closed; residual misses are SDK-shaped | - ---- - -## Historical notes (A–E) - -- **A:** Jet WS coverage transfer; 3-platform TS lcov baseline. -- **B:** Removed Android `buildParsed`* (~690 lines, 0%). -- **C:** `map-pipeline-coverage-gaps.sh`. -- **D:** Subcollection 100%; schedule dispatch 100%; lowering e2e expansion. -- **E:** Executor 49%→58%; database/rawOptions/sample/findNearest/unnest/rawStage e2e. - diff --git a/okf-bundle/packages/firestore/pipeline-implementation-workflow.md b/okf-bundle/packages/firestore/pipeline-implementation-workflow.md index d2e3d691cc..87435e9b27 100644 --- a/okf-bundle/packages/firestore/pipeline-implementation-workflow.md +++ b/okf-bundle/packages/firestore/pipeline-implementation-workflow.md @@ -18,7 +18,7 @@ Pipeline-specific requirements for one `.github/scripts/compare-types/configs/fi |-------|----------| | **Change authoring loop** | [change-authoring-workflow.md](../../testing/change-authoring-workflow.md) | | Bridge design, subqueries, coercion | [pipelines.md](pipelines.md) | -| Live gate snapshots | [pipeline-coverage-work-queue.md](pipeline-coverage-work-queue.md) | +| Live gate snapshots | Linear project work-queue document ([work-queue documents](../../documentation-policy.md#work-queue-documents)) | | Work types, tiers, gates | [change-authoring-workflow.md](../../testing/change-authoring-workflow.md); term ids: [iteration-vocabulary.md](../../testing/iteration-vocabulary.md) | | E2e commands | [running-e2e.md](../../testing/running-e2e.md) | | Coverage policy | [coverage-design.md](../../testing/coverage-design.md) | @@ -136,4 +136,4 @@ Before `git commit`: [validation evidence package](../../testing/validation/evid - **Two native expression builders per platform** — edit the live path; use coverage to disambiguate ([pipelines.md § Cross-platform e2e](pipelines.md#two-expression-builders-per-platform--edit-the-live-one)). - iOS profraw pull can flake — retry once before treating as environment failure. -Parity remediation serial rules and live probe status: [pipeline coverage work queue](pipeline-coverage-work-queue.md) (ephemeral). +Live probe status is ephemeral and lives in the work item's Linear work-queue document. diff --git a/okf-bundle/packages/firestore/pipeline-platform-parity.md b/okf-bundle/packages/firestore/pipeline-platform-parity.md index 222fc69487..5a35549bd0 100644 --- a/okf-bundle/packages/firestore/pipeline-platform-parity.md +++ b/okf-bundle/packages/firestore/pipeline-platform-parity.md @@ -18,7 +18,7 @@ Completion signals: | Outcome | Action | |---------|--------| | Same behavior on iOS, Android, macOS (JS SDK) | Required default — shared e2e assertions, no `Platform.*` branches unless macOS has no native bridge | -| RNFB bridge gap (one platform lowers/coerces differently) | **Fix the bridge** — parity remediation ([work queue](pipeline-coverage-work-queue.md)) | +| RNFB bridge gap (one platform lowers/coerces differently) | **Fix the bridge** — parity remediation | | Native SDK does not support the feature | Document here with SDK version/evidence; optional reduced e2e on that platform only | | macOS-only path (firebase-js-sdk, no RN bridge) | Document; use `Platform.other` skip when the test requires native-only wire shapes | @@ -26,7 +26,7 @@ No permanent `Platform.android` / `Platform.ios` e2e workaround without registry # Drift registry -**Status:** bridge gaps **P-005–P-012** remediated; operand-mode audit **P-034** closed. Live coordination: [work queue](pipeline-coverage-work-queue.md). +**Status:** bridge gaps **P-005–P-012** remediated; operand-mode audit **P-034** closed. **Classification key:** `bridge` | `SDK` | `macOS-js` | `test-only` | `RNFB-JS` @@ -110,7 +110,7 @@ For each **bridge** row: 3. Run 3-platform e2e ([running-e2e.md](/testing/running-e2e.md)). 4. Record closure in **Resolved** below. -**Gate:** expand coverage only after bridge gaps + iOS guard verification close; see [work queue](pipeline-coverage-work-queue.md). +**Gate:** expand coverage for a function only after its bridge gap is fixed and its iOS runtime guard is verified ([SDK audit § 6](pipeline-sdk-support-audit.md#6-runtime-verification-authoritative)). # Resolved diff --git a/okf-bundle/packages/firestore/pipeline-sdk-support-audit.md b/okf-bundle/packages/firestore/pipeline-sdk-support-audit.md index 9adb333ddb..20b491f53c 100644 --- a/okf-bundle/packages/firestore/pipeline-sdk-support-audit.md +++ b/okf-bundle/packages/firestore/pipeline-sdk-support-audit.md @@ -10,7 +10,7 @@ timestamp: 2026-06-25T00:00:00Z RNFB pipeline parity depends on native bridge lowering matching pinned Firebase SDKs. This method compares RNFB exports, CHANGELOG evidence, bridge code, and runtime e2e execute probes. -Related: [Platform parity](pipeline-platform-parity.md), [work queue](pipeline-coverage-work-queue.md) (live status). +Related: [Platform parity](pipeline-platform-parity.md). **Policy:** [OKF documentation and commit policy](../../documentation-policy.md). @@ -123,13 +123,13 @@ Per function: CHANGELOG + bridge audit is insufficient. Authority = RNFB execute on pinned SDK. -Probe order/gates/live status: [work queue](pipeline-coverage-work-queue.md#j0--ios-runtime-guard-probes-do-first). Commands: [running-e2e.md](../../testing/running-e2e.md). +Commands: [running-e2e.md](../../testing/running-e2e.md). **Per-function probe (iOS):** 1. Branch from current main; **one function or batch at a time** when bridge work is scoped. 2. Implement or fix native lowering; unify matching `Pipeline.e2e.js` assertions cross-platform. -3. Close gates via the [change authoring primary loop](../../testing/authoring/loop.md#primary-loop) (`documentation?` before frozen `independent-review`). Phase J e2e/harness: [work queue Phase J](pipeline-coverage-work-queue.md#phase-j-iteration-protocol-strict). +3. Close gates via the [change authoring primary loop](../../testing/authoring/loop.md#primary-loop) (`documentation?` before frozen `independent-review`). 4. Record outcome: - **`independent-review` pass** → `sdk-supported-bridge-ok`; close parity row; `commit` after `review_gate` closed **with** [validation/coverage evidence](../../testing/validation/evidence-and-handoff.md#validation-evidence-package) recorded. - **`invalid-argument` / pipeline execute error** → capture exact message; classify `sdk-unsupported-confirmed` or `rnfb-bridge-gap` (compare native request in debug logs). @@ -145,7 +145,6 @@ After probes update: | `RNFBFirestorePipelineNodeBuilder.swift` / Android NodeBuilder | New or fixed lowering | | `Pipeline.e2e.js` | Unified cross-platform assertions | | [pipeline-platform-parity.md](pipeline-platform-parity.md) | Bridge / SDK gap rows | -| [pipeline-coverage-work-queue.md](pipeline-coverage-work-queue.md) | Live remediation tracker | Re-run on `@react-native-firebase/app` `sdkVersions` bump. @@ -155,7 +154,7 @@ Re-run on `@react-native-firebase/app` `sdkVersions` bump. **Pins:** iOS Firestore **12.15.0**, Android BOM **34.15.0**. -**Method:** steps 1–5 above; audit detail in [work queue](pipeline-coverage-work-queue.md). +**Method:** steps 1–5 above. ## iOS CHANGELOG evidence (≤ 12.15.0) @@ -173,8 +172,6 @@ Re-run on `@react-native-firebase/app` `sdkVersions` bump. ## Support matrix (runtime verification) -Live probes/gates: [work queue](pipeline-coverage-work-queue.md#j0--ios-runtime-guard-probes-do-first). - | Function | iOS bridge | Android bridge | CHANGELOG @ 12.15 | Classification | Verification status | |----------|------------|----------------|-------------------|----------------|---------------------| | `stringRepeat` | Generic `string_repeat` | raw | **Added 12.12** | **sdk-supported-bridge-ok** | Unified cross-platform e2e | @@ -196,8 +193,6 @@ Live probes/gates: [work queue](pipeline-coverage-work-queue.md#j0--ios-runtime- ## Recommended remediation order -Live order/gates: [work queue](pipeline-coverage-work-queue.md). - | Step | Work | |------|------| | **1** | iOS runtime bridge probes + unified e2e ([§6](#6-runtime-verification-authoritative)) | diff --git a/okf-bundle/packages/firestore/pipelines.md b/okf-bundle/packages/firestore/pipelines.md index 0364305452..8302c332bd 100644 --- a/okf-bundle/packages/firestore/pipelines.md +++ b/okf-bundle/packages/firestore/pipelines.md @@ -165,7 +165,7 @@ Each platform has a **live** execute-time lowering path and a dormant sibling. From `tests::test-cover` + post-processing; refresh with `bash scripts/map-pipeline-coverage-gaps.sh