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. diff --git a/AGENTS.md b/AGENTS.md index 9fc7af28a4..fed34ad413 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). Paths that look like another type: [look-alike trees](okf-bundle/routes/index.md#look-alike-trees). + +| 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/**`, `packages/*/specs/*.ts` (TurboModule specs), codegen wiring, `packages/app/**/*.rb` | [native](okf-bundle/routes/native.md) | +| `packages/*/e2e/**`, `tests/**`, `tests-macos/**` (e2e test app), 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/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 new file mode 100644 index 0000000000..b2cc0b61bd --- /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-04T00: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` | +| `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) | + +## 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`, `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/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..04bc63e879 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/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 ac262f8ab6..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 @@ -15,12 +15,12 @@ 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) +* [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 * [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..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 @@ -30,662 +30,23 @@ 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). +**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/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. - -| 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/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. - -### 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). - -### 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/running-e2e.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) | -| `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/coverage-design.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 7ee7cf7fad..8db682734d 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). @@ -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/documentation-policy.md b/okf-bundle/documentation-policy.md index acec9ae6cb..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** @@ -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: @@ -52,9 +52,9 @@ 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/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 @@ -81,10 +81,10 @@ 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/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..2f725036c0 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,31 +18,32 @@ 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 -- [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) +- [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/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/monorepo-tooling/architecture-decisions.md b/okf-bundle/monorepo-tooling/architecture-decisions.md index 5f5b1351d1..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,11 +159,11 @@ 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. -**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**. @@ -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 4392bc8035..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 @@ -19,7 +18,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..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. @@ -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. @@ -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,19 +200,20 @@ 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-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. +> **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/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) @@ -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`). @@ -238,7 +239,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. @@ -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/new-architecture/architecture-decisions.md b/okf-bundle/new-architecture/architecture-decisions.md index f97befe962..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](architecture-decisions.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-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/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. - ---- - -## 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--accepted) 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--accepted)) 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--accepted). - ---- - -## 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/agent-command-policy.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 @@ -427,5 +75,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/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 779bc77886..f95b237ff0 100644 --- a/okf-bundle/new-architecture/index.md +++ b/okf-bundle/new-architecture/index.md @@ -6,16 +6,16 @@ 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 -* [`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-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/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..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 @@ -16,7 +15,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-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 9fca13e672..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) | @@ -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 @@ -136,4 +136,4 @@ Before `git commit`: [validation evidence package](../../testing/validation-chec - **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 e0f37bd48d..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,15 +123,15 @@ 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/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`). 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. @@ -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 7ad7b1e23f..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