Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion doc_web_interne/docs/repository-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,10 @@ data; never uninstall or clear it to force an installation.

Read `tools/e2e/README.md`. `npm run test:testerarmy` runs Dreamer web;
`test:testerarmy:lucid`, `test:testerarmy:meditation`, and `test:testerarmy:site`
select the other web products. For a native installed Release build use
select the other web products. A native `run` without `E2E_DEVICE` reserves a
disposable Simlock device, installs the identified Release and releases the lease
after the runner finishes; see the [Simlock procedure](../../tools/e2e/README.md#automatic-simlock-reservation).
For an explicitly selected native installed Release build use
`E2E_DEVICE=<emulator-serial> npm run test:testerarmy:mobile -- <product> android`
or an explicitly named iOS Simulator with `<product> ios`. Product is dreamer,
lucid or meditation. Run setup/browser installation once through package scripts.
Expand Down
2 changes: 1 addition & 1 deletion e2e/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ the runner continues independent steps so their evidence is still available.
| Marketing site | `test:testerarmy:site -- run` | Generated multilingual pages and interactions; run `docs:build` first. |
| Real local backend | `test:e2e:backend` | Owned disposable Supabase Auth/Postgres/PostgREST: durability, account isolation, offline recovery, server quotas, theme compatibility and Apple-token privacy. |
| Optional hosted test branch | `test:e2e:branch` | Saved free/premium sessions; production and unlisted targets fail before network access. |
| Native Release | `test:testerarmy:mobile -- <dreamer\|lucid\|meditation> <android\|ios> run` | One identified Release build on one owned emulator/Simulator, with explicit device and Release receipt. |
| Native Release | `test:testerarmy:mobile -- <dreamer\|lucid\|meditation> <android\|ios> run` | One identified Release and one owned emulator/Simulator: automatically leased with Simlock when `E2E_DEVICE` is unset, or explicitly selected. |

Use `--grep` or `--tag` to select a focused journey, for example:

Expand Down
56 changes: 54 additions & 2 deletions tools/e2e/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ E2E_PERSONAS=1 E2E_PERSONA_MODEL=gpt-6.1-sol \

Once the pilot passes, replace `persona-morning` with `personas` to run all four
on each platform. Do not set `E2E_WORKERS` for native: each invocation owns one
explicit device and its lock. The first recorded action is `app.open()`, followed
leased or explicitly named device and its lock. The first recorded action is `app.open()`, followed
by a fresh synthetic app state. Native assertions use accessibility locators,
keyboard dismissal, scroll-to-visible and the native AI consent dialog. Samira
checks the completed reply and edits an unsent draft after reopening; Lucas checks
Expand Down Expand Up @@ -477,6 +477,56 @@ It never generates a native project or selects a phone. The descriptor accepts
Android requires Java 17, an installed SDK and an OTA-disabled embedded bundle.
iOS requires an existing project/Pods, an embedded JS bundle and a Simulator build.

### Automatic Simlock reservation

For a native `run` without `E2E_DEVICE`, the runner reserves one disposable
simulator or emulator from the configured Simlock pool, installs the Release
identified by `E2E_RELEASE_RECEIPT`, runs the selected journeys and releases its
own lease after the SDK and device checks finish. It waits for capacity by default;
it never downloads a runtime or selects a physical phone. A missing or malformed
receipt is refused before reserving; a lost lease or unconfirmed release fails
the run. `simlock-lease.json` and `simlock-release.json` in the run directory
record the reservation and its acknowledged release; the existing `end.json`
remains the final verdict.

```sh
E2E_RELEASE_RECEIPT=PATH_TO_IOS_RELEASE_JSON \
mise exec -- npm run test:testerarmy:mobile -- dreamer ios run --grep 'onboarding'
E2E_RELEASE_RECEIPT=PATH_TO_ANDROID_RELEASE_JSON \
mise exec -- npm run test:testerarmy:mobile -- dreamer android run --grep 'onboarding'
```

The configured machine uses `~/Projects/infra-ops/simlock-pilot/simlock`; on
another machine use `E2E_SIMLOCK_BIN` or a `simlock` executable on `PATH`.
Optional `E2E_SIMLOCK_MODEL` and `E2E_SIMLOCK_OS` select an installed catalog
entry; `E2E_SIMLOCK_TIMEOUT_SECONDS` bounds the wait (default 180), and
`E2E_SIMLOCK_NO_WAIT=1` refuses when capacity is unavailable. The pool resets
devices on release, so never place personal data or unique evidence there.
Android requires Simlock to return its isolated ADB server port; the runner
refuses a grant without it instead of using an unscoped server.
The foreground lease holder renews while the runner lives and is bound to its PID.
It runs in its own process group, so Ctrl-C reaches only the runner, which stops at
its next checkpoint, cleans up and then releases. Simlock 0.4.0 keeps a request
queued for capacity after its client dies and grants it anyway, so an interrupt
while queued waits until the request is granted (then released at once) or times
out. Never kill a queued holder: its later grant would block the pool until the
30-minute lease TTL expires.
On a local Simlock worker the shims' `--lease` scoping is advisory: once the lease
is lost or released they refuse every further device command, and after a loss
no SDK child starts. Each shim call also checks that this runner's lease holder is
still alive, so a loss during a synchronous install or collection is refused at once.
Codex and Claude use their existing Simlock session identity; a plain terminal
gets an invocation-specific identity shared by the lease and release commands.
Before reserving on the Mac mini, follow
`~/Projects/infra-ops/storage-guard/AGENT_RULES.md`: scan, register the campaign
with an honest device/build budget, and finish it afterward. The runner does not
register that storage campaign automatically.

An explicit `E2E_DEVICE` keeps the existing owned-device flow and does not acquire
a Simlock lease. `list`, `build`, `inspect` and `mcp` do not auto-reserve devices.
The Simlock lease and the existing runner lock serve different purposes; neither
replaces the Release receipt, installed identity checks or native evidence.

Example from an isolated checkout with an existing Android project:

```sh
Expand Down Expand Up @@ -511,7 +561,9 @@ without locale rules, and values are never printed. See the official
New source inputs require a new build. Unchanged app/native input digests permit
reuse after a test-only commit; build-source and test-source revisions stay distinct.

`--install-release` is opt-in and simulator/emulator-only. The existing runner
With an explicit `E2E_DEVICE`, `--install-release` is opt-in and
simulator/emulator-only; a fresh Simlock lease installs the identified Release
automatically. The existing runner
holds the device lock, validates the receipt/source/binary, installs that binary,
pulls and hashes the installed APK (or hashes the installed Simulator `.app`),
then launches collection and SDK tests. The owner decision of2026-10-06 makes
Expand Down
3 changes: 3 additions & 0 deletions tools/e2e/native-release.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { validateReleaseReceipt, runWithInstallDiagnostics, normalizeAvdName, validateBuildCommand, nativeInputs, archiveReleaseBinary, releaseMetadata } from './native-release.mjs';
import { virtualLinks } from './test-support/virtual-links.mjs';
// The Simlock reservation guards join this file instead of a new package.json
// script: root scripts feed the Expo runtime fingerprint.
import './simlock-native.test.mjs';
const sha = 'a'.repeat(64);
test('iteration APK commands never qualify as Release on either path syntax', () => {
for (const wrapper of ['/repo/android/gradlew', 'C:\\repo\\android\\gradlew.bat']) {
Expand Down
83 changes: 79 additions & 4 deletions tools/e2e/run.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { readNativeBackendState } from './native-backend-state.ts';
import { acquireNativeBackendRunLock, releaseNativeBackendRunLock } from './native-backend-lock.mjs';
import { PERSONA_ACT_MODEL } from './persona-models.mjs';
import { selectionOwesNothing } from './zones.mjs';
import { acquireSimlock, needsSimlock } from './simlock-native.mjs';

const cwd = fileURLToPath(new URL('.', import.meta.url));
const root = fileURLToPath(new URL('../../', import.meta.url));
Expand Down Expand Up @@ -166,6 +167,26 @@ let inspectionStarted = false;
let inspectionClosed = false;
let mcpStarted = false;
let resourceCleanup = 'not-started';
let simlock;
let simlockRelease;
let simlockLost = false;
let simlockPreserveState = false;
let interruptActiveChild;
// From the reservation until the SDK child starts, a signal stops the run at the next
// checkpoint, so the device lock, agent-device state and lease are still cleaned up.
const simlockInterrupt = () => { requestedSignal = 130; };
const simlockTerminate = () => { requestedSignal = 143; };
function simlockCheckpoint() {
if (simlockLost) throw new Error('SIMLOCK_LEASE_LOST_BEFORE_SDK');
if (simlock && requestedSignal) throw new Error('SIMLOCK_INTERRUPTED');
}
// Shape only; identity, digests and profile rules need the device and checkout.
function releaseShape(receipt) {
if (typeof receipt?.binary?.path !== 'string' || !receipt.binary.path
|| !receipt.profile || typeof receipt.profile !== 'object' || Array.isArray(receipt.profile))
throw new Error('RELEASE_PROVENANCE');
return receipt;
}
const secondary = [];
const installationErrorDetails = [];
const startedAt = Date.now();
Expand All @@ -176,6 +197,8 @@ const campaignId = env.E2E_CAMPAIGN_ID ?? env.CIRCLE_WORKFLOW_JOB_ID ?? null;
const context = () => ({ locale: platform !== 'web' && env.E2E_PERSONAS === '1' ? 'fr-FR' : env.E2E_WEB_LOCALE ?? (product === 'lucid' ? 'fr-FR' : 'en-US'), featureSheets: env.EXPO_PUBLIC_ONBOARDING_FEATURE_SHEETS_ENABLED === 'true',
...(env.E2E_PERSONAS === '1' ? { personas: true, personaModel: env.E2E_PERSONA_MODEL?.trim() || env.E2E_PERSONA_ACT_MODEL?.trim() || PERSONA_ACT_MODEL } : {}) });
async function execute(executable, argv, logName, childEnv = env, workdir = cwd) {
// After an interrupt on a leased device, no further SDK child starts.
if (simlock && (requestedSignal || simlockLost)) return requestedSignal ?? 3;
const logFd = logName ? openSync(join(output, logName), 'wx') : undefined;
const child = spawn(executable, argv, { cwd: workdir, env: childEnv, stdio: logFd === undefined ? 'inherit' : ['ignore', logFd, logFd], detached: process.platform !== 'win32' });
const stopProgress = startSdkProgress(child, {
Expand All @@ -191,17 +214,20 @@ async function execute(executable, argv, logName, childEnv = env, workdir = cwd)
};
const interrupt = () => { requestedSignal = 130; relay('SIGINT'); };
const terminate = () => { requestedSignal = 143; relay('SIGTERM'); };
const interruptForLeaseLoss = () => relay('SIGTERM');
interruptActiveChild = interruptForLeaseLoss;
process.on('SIGINT', interrupt);
process.on('SIGTERM', terminate);
try {
return await new Promise((resolve, reject) => {
child.once('error', reject);
child.once('close', (code, signal) => resolve(requestedSignal ?? code ?? (signal === 'SIGTERM' ? 143 : signal ? 130 : 1)));
child.once('close', (code, signal) => resolve(requestedSignal ?? (simlockLost ? 3 : code ?? (signal === 'SIGTERM' ? 143 : signal ? 130 : 1))));
});
} finally {
stopProgress();
process.off('SIGINT', interrupt);
process.off('SIGTERM', terminate);
if (interruptActiveChild === interruptForLeaseLoss) interruptActiveChild = undefined;
if (logFd !== undefined) closeSync(logFd);
}
}
Expand Down Expand Up @@ -382,6 +408,21 @@ async function runSdk() {
}
try {
sourceBefore = sourceSnapshot(root, product);
if (needsSimlock({ platform, command, env })) {
if (!releaseFile || !existsSync(resolve(releaseFile)))
throw new Error('An existing E2E_RELEASE_RECEIPT is required before reserving a Simlock device.');
releaseShape(JSON.parse(readFileSync(resolve(releaseFile), 'utf8')));
process.on('SIGINT', simlockInterrupt);
process.on('SIGTERM', simlockTerminate);
simlock = await acquireSimlock({
platform, env, shimDirectory: join(cwd, 'simlock-bin'),
onSignal: signal => { requestedSignal = signal === 'SIGINT' ? 130 : 143; },
onLoss: () => { simlockLost = true; secondary.push('SIMLOCK_LEASE_LOST'); interruptActiveChild?.(); },
});
writeOnce(join(output, 'simlock-lease.json'), simlock.evidence);
// The pooled QA device is reset after every lease; install the identified Release.
installRelease = true;
}
const device = env.E2E_DEVICE;
let binary = null;
if (platform !== 'web' && command !== 'build') {
Expand All @@ -404,7 +445,7 @@ try {
fd = openSync(lock, 'wx');
writeFileSync(fd, JSON.stringify({ pid: process.pid, product, platform, device }));
if (!releaseFile) throw new Error('E2E_RELEASE_RECEIPT is required; create it through the explicit native build command.');
release = JSON.parse(readFileSync(resolve(releaseFile), 'utf8'));
release = releaseShape(JSON.parse(readFileSync(resolve(releaseFile), 'utf8')));
if (nativeJourneys) {
const backend = readNativeBackendState();
if (release.profile.name !== 'local-backend' || release.profile.backend?.origin !== backend.proxy.origin
Expand Down Expand Up @@ -455,7 +496,11 @@ try {
trackedDiffSha256: diffSha256,
command: ['node', 'tools/e2e/run.mjs', product, platform, command, ...args, ...(releaseFile ? ['--release-receipt', resolve(releaseFile)] : []), ...(installRelease ? ['--install-release'] : [])],
rerunEnvironment: platform === 'web' ? { E2E_WEB_LOCALE: context().locale, EXPO_PUBLIC_ONBOARDING_FEATURE_SHEETS_ENABLED: String(context().featureSheets), E2E_WEB_PORT: new URL(expectedOrigin).port, E2E_WORKERS: env.E2E_WORKERS, E2E_KEEP_METRO_CACHE: env.E2E_KEEP_METRO_CACHE === '1' ? '1' : null,
...(env.E2E_PERSONAS === '1' ? { E2E_PERSONAS: '1', E2E_PERSONA_MODEL: context().personaModel } : {}) } : { E2E_DEVICE: env.E2E_DEVICE ?? null, E2E_AVD_NAME: env.E2E_AVD_NAME ?? 'Pixel_9_API_37',
...(env.E2E_PERSONAS === '1' ? { E2E_PERSONAS: '1', E2E_PERSONA_MODEL: context().personaModel } : {}) } : { ...(simlock
? { E2E_SIMLOCK_BIN: env.E2E_SIMLOCK_BIN, E2E_SIMLOCK_MODEL: env.E2E_SIMLOCK_MODEL ?? null,
E2E_SIMLOCK_OS: env.E2E_SIMLOCK_OS ?? null, E2E_SIMLOCK_TIMEOUT_SECONDS: env.E2E_SIMLOCK_TIMEOUT_SECONDS ?? null,
E2E_SIMLOCK_NO_WAIT: env.E2E_SIMLOCK_NO_WAIT ?? null }
: { E2E_DEVICE: env.E2E_DEVICE ?? null, E2E_AVD_NAME: env.E2E_AVD_NAME ?? 'Pixel_9_API_37' }),
...(env.E2E_PERSONAS === '1' ? { E2E_PERSONAS: '1', E2E_PERSONA_MODEL: context().personaModel } : {}),
...(nativeJourneys ? { E2E_NATIVE_JOURNEYS: '1', E2E_NATIVE_BACKEND_MANIFEST: env.E2E_NATIVE_BACKEND_MANIFEST,
E2E_NATIVE_QA_AUDIO: env.E2E_NATIVE_QA_AUDIO, E2E_NATIVE_RECOVERY_PORT: env.E2E_NATIVE_RECOVERY_PORT ?? '31284' } : {}) },
Expand Down Expand Up @@ -512,6 +557,7 @@ try {
if (command === 'mcp') { mcpStarted = true; primary = await execute(process.execPath, [...webNodeArgs, cli, command, '--target', `${product}-${platform}`, '--max-sessions', '1'], undefined, cliEnvironment()); }
else if (platform === 'web') await runSdk();
else {
simlockCheckpoint();
installHandoffStarted = true;
installationDiagnostics = await runWithInstallDiagnostics({
install: installRelease ? async () => {
Expand All @@ -522,7 +568,7 @@ try {
writeOnce(join(output, 'installed-start.json'), verifyInstalledRelease({ receipt: release, device: identity, output, read }));
installedReady = true;
},
launch: runSdk, onDiagnostic: (code, error) => {
launch: async () => { simlockCheckpoint(); return runSdk(); }, onDiagnostic: (code, error) => {
secondary.push(code); installationErrorDetails.push({ code, message: error instanceof Error ? error.message.slice(0, 4096) : 'Non-Error diagnostic' });
},
});
Expand Down Expand Up @@ -553,6 +599,22 @@ try {
} else if (mcpStarted) {
resourceCleanup = 'unproven'; secondary.push('NATIVE_MCP_CLEANUP_UNPROVEN');
}
if (simlock && sdkLaunched) {
try {
// This state directory is unique to this invocation, so --clean cannot
// stop another agent's shared daemon or remove another session.
const deviceCli = join(cwd, 'node_modules/agent-device/bin/agent-device.mjs');
const stopped = spawnSync(process.execPath, [deviceCli, 'daemon', 'stop', '--clean', '--state-dir', env.AGENT_DEVICE_STATE_DIR],
{ cwd, env, encoding: 'utf8', timeout: 30_000 });
writeOnce(join(output, 'simlock-agent-cleanup.json'), { status: stopped.status,
stdout: stopped.stdout?.slice(-4096) ?? '', stderr: stopped.stderr?.slice(-4096) ?? '', error: stopped.error?.message ?? null });
if (stopped.error || stopped.status !== 0) throw new Error('SIMLOCK_AGENT_CLEANUP');
} catch (error) {
simlockPreserveState = true; resourceCleanup = 'unproven';
secondary.push('SIMLOCK_AGENT_CLEANUP_UNPROVEN');
console.error(`${error.message}; retained state: ${env.AGENT_DEVICE_STATE_DIR}`);
}
}
if (backendLock) attempt('BACKEND_LOCK_RELEASE', () => releaseNativeBackendRunLock(backendLock));
if (fd !== undefined) {
attempt('LOCK_CLOSE', () => closeSync(fd));
Expand All @@ -564,6 +626,17 @@ try {
unlinkSync(lock);
});
}
if (simlock) {
try {
simlockRelease = await simlock.release({ preserveState: simlockPreserveState });
writeOnce(join(output, 'simlock-release.json'), simlockRelease);
} catch (error) {
secondary.push('SIMLOCK_RELEASE_UNPROVEN');
console.error(error.message);
}
}
process.off('SIGINT', simlockInterrupt);
process.off('SIGTERM', simlockTerminate);
if (hostStalls.length) {
// A failed run during a host stall stays failed; the code says why, so it is rerun on a
// quiet host instead of being read as an app regression. A passed run is left as it is.
Expand All @@ -577,6 +650,8 @@ try {
applicationQualified: command === 'run' && !emptySelection && preserveStatus(requestedSignal ?? primary, secondary) === 0,
ownerDecision: '2026-10-06-install-hash-diagnostic-and-release-own-wrapper-lock',
secondaryErrors: secondary, resourceCleanup, lockReleased: lock ? !existsSync(lock) : true,
...(simlock ? { simlock: { ...simlock.evidence, released: Boolean(simlockRelease),
...(simlockPreserveState ? { retainedStateDirectory: env.AGENT_DEVICE_STATE_DIR } : {}) } } : {}),
...(backendLock ? { backendLockReleased: !existsSync(backendLock.path) } : {}), hostStalls,
}));
process.exitCode = preserveStatus(requestedSignal ?? primary, secondary);
Expand Down
2 changes: 2 additions & 0 deletions tools/e2e/simlock-bin/adb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/sh
exec node "$(dirname "$0")/../simlock-driver.mjs" adb "$@"
2 changes: 2 additions & 0 deletions tools/e2e/simlock-bin/xcrun
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/sh
exec node "$(dirname "$0")/../simlock-driver.mjs" xcrun "$@"
Loading