@aarwitz/tapp 0.35.7 → 0.35.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,9 +32,10 @@ const scriptsDir = path.join(repoRoot, "scripts");
32
32
  import { writeCaptureProvenance, readCaptureProvenance, captureBelongsToProject, provenanceLabel } from "./capture-provenance.js";
33
33
  import { chooseSignInSubmit, findSignInSubmit } from "./sign-in.js";
34
34
  // TAPP_HOME (set by the `tapp` CLI when installed) redirects writable output to a user directory.
35
- // The old alias remains a read-only fallback; unset repository development stays local.
35
+ // Unset (a source checkout), evidence still goes to ~/.tapp/captures (TM-651): never into the
36
+ // repository, where the evidence clearing-out never looks.
36
37
  const tappHome = (process.env.TAPP_HOME || "").trim();
37
- const capturesDir = tappHome ? path.join(tappHome, "captures") : path.join(repoRoot, "captures");
38
+ const capturesDir = path.join(tappHome || path.join(os.homedir(), ".tapp"), "captures");
38
39
  const MAX_OUTPUT_CHARS = 60_000;
39
40
  const requiredAuthToken = (process.env.TAPP_MCP_TOKEN || "").trim();
40
41
 
@@ -935,9 +936,9 @@ async function startWebSession(url, { testEmail = "", testPassword = "", device
935
936
  try {
936
937
  const parsed = new URL(String(url || ""));
937
938
  if (!/^https?:$/.test(parsed.protocol)) return { error:"Web session URL must be http(s)" };
938
- const { loadPlaywright, webContextOptions, webBrowserLaunchOptions } = await import("./web-explorer.js");
939
+ const { loadPlaywright, webContextOptions, webBrowserLaunchOptions, launchWebBrowser } = await import("./web-explorer.js");
939
940
  const { chromium, devices } = await loadPlaywright();
940
- browser = await chromium.launch(webBrowserLaunchOptions());
941
+ browser = await launchWebBrowser(chromium, webBrowserLaunchOptions());
941
942
  const context = await browser.newContext({ ...webContextOptions({ device, viewport, devices }), ...(recordVideoDir ? {recordVideo:{dir:recordVideoDir}} : {}) });
942
943
  const page = await context.newPage();
943
944
  await page.goto(parsed.href, { waitUntil:"domcontentloaded", timeout:30_000 });
@@ -163,7 +163,7 @@ export class JourneyStore {
163
163
  }
164
164
 
165
165
  forget(slug) {
166
- try { fs.rmSync(this.flowPath(slug), { force: true }); fs.rmSync(this.statusPath(slug), { force: true }); return true; } catch { return false; }
166
+ try { fs.rmSync(this.flowPath(slug), { force: true }); fs.rmSync(this.statusPath(slug), { force: true }); fs.rmSync(this.reportedPath(slug), { force: true }); return true; } catch { return false; }
167
167
  }
168
168
 
169
169
  statusPath(slug) {
@@ -183,10 +183,38 @@ export class JourneyStore {
183
183
  }
184
184
 
185
185
  /** Every journey here, with its last result. Names only; never the file contents. */
186
+ // A journey that runs somewhere else — the owner's own machine, against staging or
187
+ // localhost — and reports how it went (ADR-0011 §4). Only the name and the result arrive:
188
+ // never the journey, a credential or a screenshot. The cloud cannot run it, so there is no
189
+ // flow file, and it is never due for a daily check.
190
+ reportedPath(slug) {
191
+ return path.join(this.root, ".reported", `${slugify(slug)}.json`);
192
+ }
193
+
194
+ report({ name, platform = "web", url = "", steps = 0, machine = "", passed, executed = 0, total = 0, failed = 0, at = null }) {
195
+ const slug = slugify(name);
196
+ const file = this.reportedPath(slug);
197
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
198
+ const status = { passed: !!passed, at: at || new Date().toISOString(), captureId: null, executed, total, failed };
199
+ const record = { name, slug, platform, url, steps, machine, status, reportedAt: new Date().toISOString() };
200
+ fs.writeFileSync(file, JSON.stringify(record), { mode: 0o600 });
201
+ return record;
202
+ }
203
+
204
+ reported(slug) {
205
+ try { return JSON.parse(fs.readFileSync(this.reportedPath(slug), "utf8")); } catch { return null; }
206
+ }
207
+
186
208
  list() {
187
209
  let entries = [];
188
210
  try { entries = fs.readdirSync(this.root, { withFileTypes: true }); } catch { return []; }
189
211
  const out = [];
212
+ let reported = [];
213
+ try { reported = fs.readdirSync(path.join(this.root, ".reported")).filter((name) => name.endsWith(".json")); } catch { /* none */ }
214
+ for (const name of reported.sort()) {
215
+ const record = this.reported(name.replace(/\.json$/, ""));
216
+ if (record) out.push({ name: record.name, slug: record.slug, platform: record.platform || "web", url: record.url || "", actor: "", steps: record.steps || 0, status: record.status, source: "reported", machine: record.machine || "" });
217
+ }
190
218
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
191
219
  if (!entry.isFile() || !/\.ya?ml$/i.test(entry.name)) continue;
192
220
  const slug = entry.name.replace(/\.ya?ml$/i, "");
@@ -128,6 +128,8 @@ export async function runMacosFlow({ flow, appPath, logPath, screenshotDir, driv
128
128
  } else if (action === "assert_ai") {
129
129
  status = "skip";
130
130
  detail = "AI assertions are advisory and are not part of deterministic macOS replay";
131
+ } else if (action === "open_url") {
132
+ throw new Error("open_url is not supported on macOS — a desktop app has no system-level link handoff to replay");
131
133
  } else {
132
134
  throw new Error(`unknown action ‘${action}’`);
133
135
  }
@@ -8,6 +8,10 @@
8
8
  // Configuration is two values, from flags or the environment:
9
9
  // TAPP_STUDIO https://app.runtapp.com
10
10
  // TAPP_TOKEN tapp_…
11
+ import fs from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+
11
15
  const POLL_MS = 1500;
12
16
  const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
13
17
 
@@ -74,10 +78,52 @@ export async function runStudioJourney(config, name, { onProgress = () => {}, ti
74
78
  }
75
79
  }
76
80
 
81
+ /**
82
+ * The account this machine reports to (ADR-0011 §4): the link the Studio wrote under TAPP_HOME,
83
+ * or TAPP_STUDIO + TAPP_TOKEN in the environment, which win so one shell can report elsewhere.
84
+ * Null when neither is set — reporting is then simply not on.
85
+ */
86
+ export function studioLinkFor(env = process.env) {
87
+ if (env.TAPP_STUDIO && env.TAPP_TOKEN) {
88
+ try { const config = studioConfig({}, env); return config ? { ...config, email: "" } : null; } catch { return null; }
89
+ }
90
+ const home = (env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp");
91
+ try {
92
+ const link = JSON.parse(fs.readFileSync(path.join(home, "studio-link.json"), "utf8"));
93
+ return link && typeof link.origin === "string" && typeof link.token === "string" ? { origin: link.origin, token: link.token, email: link.email || "" } : null;
94
+ } catch { return null; }
95
+ }
96
+
97
+ /** The runner's own verdict, from the log every platform's runner writes: the last result line. */
98
+ export function flowResultFromLog(text) {
99
+ let found = null;
100
+ for (const line of String(text || "").split("\n")) {
101
+ const m = line.match(/^OCQA_FLOW_RESULT:(\{.*\})\s*$/);
102
+ if (m) { try { found = JSON.parse(m[1]); } catch { /* a partial line */ } }
103
+ }
104
+ return found;
105
+ }
106
+
107
+ /** Who this token belongs to. Used once, when a machine is linked, so the link can say whose it is. */
108
+ export async function verifyStudioToken(config) {
109
+ const session = await call(config, "/api/session");
110
+ if (session.access !== "account" || !session.email) throw new Error("That token did not sign in to an account on the Studio");
111
+ return { email: session.email };
112
+ }
113
+
114
+ /**
115
+ * Tell the Studio how a journey run somewhere else went (ADR-0011 §4). The name and the result
116
+ * travel; the journey itself, credentials and screenshots stay where the run happened.
117
+ */
118
+ export async function reportStudioJourney(config, { name, platform = "web", url = "", steps = 0, machine = "", passed, executed = 0, total = 0, failed = 0, at = null }) {
119
+ return call(config, "/api/journeys/report", { method: "POST", body: { name, platform, url, steps, machine, passed: !!passed, executed, total, failed, at } });
120
+ }
121
+
77
122
  /** One line per journey, for a terminal or an agent's transcript. */
78
123
  export function formatJourneyStatus(journey) {
79
124
  const status = journey.status;
80
125
  const state = !status ? "never run" : status.passed ? "passing" : "FAILING";
81
126
  const when = status?.at ? ` · ${new Date(status.at).toISOString().replace("T", " ").slice(0, 16)}` : "";
82
- return `${state === "FAILING" ? "✗" : state === "passing" ? "✓" : "·"} ${journey.name} — ${journey.steps || 0} steps · ${state}${when}`;
127
+ const where = journey.source === "reported" && journey.machine ? ` · runs on ${journey.machine}` : "";
128
+ return `${state === "FAILING" ? "✗" : state === "passing" ? "✓" : "·"} ${journey.name} — ${journey.steps || 0} steps · ${state}${when}${where}`;
83
129
  }
@@ -13,7 +13,7 @@ import fs from "fs";
13
13
  import path from "path";
14
14
  import { createRequire } from "module";
15
15
  import {
16
- NAV_TIMEOUT_MS, loadPlaywright, webBrowserLaunchOptions, webContextOptions, installWebListenerTracking,
16
+ NAV_TIMEOUT_MS, loadPlaywright, webBrowserLaunchOptions, launchWebBrowser, webContextOptions, installWebListenerTracking,
17
17
  waitForWebStability, captureElementEvidence, shouldReportWebRequestFailure, auditStructuralControls,
18
18
  auditFindingsFromControls, slug, detectBlockingOverlay, chooseOverlayDismissal,
19
19
  } from "./web-explorer.js";
@@ -406,7 +406,7 @@ export async function auditWebSite({
406
406
  const maxPages = Math.max(1, Math.min(200, Number(pages) || 1));
407
407
 
408
408
  const { chromium, devices } = await loadPlaywright();
409
- const browser = await chromium.launch(webBrowserLaunchOptions(process.env, {}));
409
+ const browser = await launchWebBrowser(chromium, webBrowserLaunchOptions(process.env, {}));
410
410
  const capture = capturesDir ? openCapture(capturesDir, captureId || auditCaptureId()) : null;
411
411
  const provenance = capture ? writeCaptureProvenance(capture.dir, { kind: "audit", platform: "web", target: start.href }) : null;
412
412
  try {
@@ -536,6 +536,42 @@ export function webTransitionOrigin(pendingNavigation, currentScreen) {
536
536
  return pendingNavigation?.fromScreen || currentScreen || null;
537
537
  }
538
538
 
539
+ // Playwright reports a browser that dies at startup as "Target page, context or browser has been
540
+ // closed" and keeps the real reason in its debug log (DEBUG=pw:browser). Capture the browser's own
541
+ // stderr through a logger so the reason reaches the ordinary error, without launch arguments
542
+ // ("<launching>"), env, or unrelated protocol chatter.
543
+ export function browserStartupReason(lines) {
544
+ const reasons = [];
545
+ for (const raw of lines) {
546
+ for (const part of String(raw).split("\n")) {
547
+ const line = part.replace(/^\[\d+:\d+:\d+\/\d+\.\d+:/, "[").trim();
548
+ if (!line || /^<(launching|launched|gracefully|kill)/i.test(line) || /^<\w+ pid=/.test(line)) continue;
549
+ if (/\b(error|fail(ed)?|denied|fatal|cannot|can't|unable|sandbox|missing|not found|no such)\b/i.test(line) && !reasons.includes(line)) reasons.push(line.slice(0, 300));
550
+ }
551
+ }
552
+ return reasons.slice(0, 5);
553
+ }
554
+
555
+ export async function launchWebBrowser(chromium, options) {
556
+ const lines = [];
557
+ const logger = {
558
+ isEnabled: (name) => name === "browser",
559
+ log: (name, _severity, message) => { if (name === "browser") lines.push(String(message)); },
560
+ };
561
+ try {
562
+ return await chromium.launch({ ...options, logger });
563
+ } catch (error) {
564
+ const reasons = browserStartupReason(lines);
565
+ if (reasons.length) {
566
+ const first = String(error?.message || error).split("\n")[0];
567
+ const wrapped = new Error(`${first}\nBrowser startup reason: ${reasons.join(" | ")}`);
568
+ wrapped.cause = error;
569
+ throw wrapped;
570
+ }
571
+ throw error;
572
+ }
573
+ }
574
+
539
575
  export function webBrowserLaunchOptions(environment = process.env, { watch = false } = {}) {
540
576
  const browserProxy = String(environment.TAPP_BROWSER_PROXY_SERVER || "").trim();
541
577
  if (environment.TAPP_ENFORCE_PUBLIC_EGRESS === "1" && !/^http:\/\/127\.0\.0\.1:\d+$/.test(browserProxy)) {
@@ -696,7 +732,7 @@ export async function inspectWebPage({ url, timeoutMs = NAV_TIMEOUT_MS, screensh
696
732
  if (!/^https?:$/.test(target.protocol)) throw new Error("Web inspection needs a valid http(s) URL");
697
733
 
698
734
  const { chromium, devices } = await loadPlaywright();
699
- const browser = await chromium.launch(webBrowserLaunchOptions());
735
+ const browser = await launchWebBrowser(chromium, webBrowserLaunchOptions());
700
736
  try {
701
737
  const context = await browser.newContext(webContextOptions({ device, viewport, devices }));
702
738
  const page = await context.newPage();
@@ -872,7 +908,7 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
872
908
  };
873
909
 
874
910
  const { chromium, devices } = await loadPlaywright();
875
- const browser = await chromium.launch(webBrowserLaunchOptions(process.env, { watch }));
911
+ const browser = await launchWebBrowser(chromium, webBrowserLaunchOptions(process.env, { watch }));
876
912
  const captureProfile = webContextOptions({ device, viewport, devices });
877
913
  // Evidence is only comparable when the capture conditions are on record: a desktop run and a
878
914
  // phone run legitimately disagree about which nav links exist, and a baseline diff across
@@ -349,6 +349,10 @@ export async function executeWebFlowStep({ page, step, vars = {}, defaultTimeout
349
349
  }
350
350
  } else if (action === "back") {
351
351
  await page.goBack({ waitUntil: "domcontentloaded" });
352
+ } else if (action === "open_url") {
353
+ // A journey starting from an email link ("tap the sign-in link in your receipt") is just a
354
+ // navigation on web — the one-time part of the link substitutes like any other target.
355
+ await page.goto(target, { waitUntil: "domcontentloaded" });
352
356
  } else if (action === "wait_for") {
353
357
  if (!await waitForScreen(page, target, timeout)) throw new Error(`‘${target}’ never appeared within ${timeout}ms${await visibleLabelsHint(page)}`);
354
358
  } else if (action === "wait") {
@@ -424,8 +428,8 @@ export async function runWebFlow({ flow, url, logPath, screenshotDir, recordVide
424
428
  const loggedFlow = { ...flow, steps: [...setup, ...flow.steps, ...teardown] };
425
429
  const log = new FlowLog({ logPath, flow: loggedFlow });
426
430
  const pw = playwright || await loadPlaywright();
427
- const { webBrowserLaunchOptions } = await import("./web-explorer.js");
428
- const browser = await pw.chromium.launch(webBrowserLaunchOptions());
431
+ const { webBrowserLaunchOptions, launchWebBrowser } = await import("./web-explorer.js");
432
+ const browser = await launchWebBrowser(pw.chromium, webBrowserLaunchOptions());
429
433
  const contextOptions = webContextOptions({ device, viewport, devices: pw.devices });
430
434
  // Without an explicit size Playwright fits the recording into 800px, so a replay filmed at a
431
435
  // desktop viewport came out small and soft however large the window was. Film at the size the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aarwitz/tapp",
3
- "version": "0.35.7",
3
+ "version": "0.35.8",
4
4
  "mcpName": "io.github.aarwitz/tapp",
5
5
  "description": "Let coding agents verify UI changes on real iOS, Android, and web surfaces, then enforce reviewed proof in deterministic CI.",
6
6
  "license": "MIT",
@@ -98,7 +98,7 @@
98
98
  "mobile"
99
99
  ],
100
100
  "scripts": {
101
- "test": "node --test tests/report.test.js tests/regression.test.js tests/engine.test.js tests/project-config.test.js tests/application-model.test.js tests/ui-map.test.js tests/focused-navigation.test.js tests/task-runtime.test.js tests/release-contract.test.js tests/pr-selection.test.js tests/flow-runtime.test.js tests/flow-variables.test.js tests/flow-recording.test.js tests/sim-recorder.test.js tests/feedback.test.js tests/web-explorer.test.js tests/web-session.test.js tests/web-link-audit.test.js tests/web-overlay.test.js tests/web-audit.test.js tests/page-observations.test.js tests/capture-provenance.test.js tests/capture-frames.test.js tests/actor-store.test.js tests/account-store.test.js tests/alerts.test.js tests/access-jwt.test.js tests/oauth.test.js tests/studio-client.test.js tests/journeys.test.js tests/ios-crash-attribution.test.js tests/ios-simulator-selection.test.js tests/ios-recording-stop.test.js tests/web-flow.test.js tests/sign-in.test.js tests/signin-honesty.test.js tests/scenario-runtime.test.js tests/android-driver.test.js tests/android-explorer.test.js tests/evidence-retention.test.js tests/android-flow.test.js tests/macos-driver.test.js tests/android-primitives-protocol.test.js tests/managed-web.test.js tests/product-operations.test.js tests/job-lanes.test.js tests/browser-product.test.js tests/browser-chat-narration.test.js tests/browser-run-reading.test.js tests/browser-onboarding.test.js tests/managed-operation.test.js tests/ci-setup.test.js tests/ci-install.test.js tests/cli.test.js tests/mcp-workspace.test.js tests/action.test.js tests/package-surface.test.js tests/agent-surface.test.js tests/platforms.test.js tests/presentation-contract.test.js tests/landing-brand.test.js tests/ci-gate.test.js tests/ci-report.test.js tests/desktop-protocol.test.js tests/ios-flow-protocol.test.js tests/feedback-triage-0919.test.js vscode-extension/test/bridge.test.js",
101
+ "test": "node --test tests/report.test.js tests/regression.test.js tests/engine.test.js tests/project-config.test.js tests/application-model.test.js tests/ui-map.test.js tests/focused-navigation.test.js tests/task-runtime.test.js tests/release-contract.test.js tests/pr-selection.test.js tests/flow-runtime.test.js tests/flow-variables.test.js tests/flow-recording.test.js tests/sim-recorder.test.js tests/feedback.test.js tests/web-explorer.test.js tests/web-session.test.js tests/web-link-audit.test.js tests/web-overlay.test.js tests/web-audit.test.js tests/page-observations.test.js tests/capture-provenance.test.js tests/capture-frames.test.js tests/actor-store.test.js tests/account-store.test.js tests/alerts.test.js tests/access-jwt.test.js tests/oauth.test.js tests/studio-client.test.js tests/journeys.test.js tests/ios-crash-attribution.test.js tests/ios-simulator-selection.test.js tests/ios-recording-stop.test.js tests/web-flow.test.js tests/sign-in.test.js tests/signin-honesty.test.js tests/scenario-runtime.test.js tests/android-driver.test.js tests/android-explorer.test.js tests/evidence-retention.test.js tests/android-flow.test.js tests/macos-driver.test.js tests/macos-flow.test.js tests/android-primitives-protocol.test.js tests/managed-web.test.js tests/product-operations.test.js tests/job-lanes.test.js tests/browser-product.test.js tests/browser-chat-narration.test.js tests/browser-run-reading.test.js tests/browser-onboarding.test.js tests/managed-operation.test.js tests/ci-setup.test.js tests/ci-install.test.js tests/cli.test.js tests/mcp-workspace.test.js tests/action.test.js tests/package-surface.test.js tests/agent-surface.test.js tests/platforms.test.js tests/presentation-contract.test.js tests/landing-brand.test.js tests/ci-gate.test.js tests/ci-report.test.js tests/desktop-protocol.test.js tests/ios-flow-protocol.test.js tests/feedback-triage-0919.test.js vscode-extension/test/bridge.test.js",
102
102
  "test:browser-journey": "node --test tests/browser-journey.test.js",
103
103
  "test:browser-native": "TAPP_RUN_NATIVE_BROWSER=1 node --test tests/browser-native-journey.test.js"
104
104
  }
@@ -374,7 +374,7 @@ xcrun simctl install "$UDID" "$APP_PATH" || { echo "❌ simctl install failed
374
374
  # ── Autonomous exploration (quick-capture builds the harness itself if needed).
375
375
  # --actions 0 = flows-only: the reviewed suites are the whole deterministic surface. No
376
376
  # explorer touches the app — the point, for targets wired to production backends (#11).
377
- CAPTURE_ROOT="${TAPP_HOME:-$ROOT}/captures"
377
+ CAPTURE_ROOT="${TAPP_HOME:-$HOME/.tapp}/captures" # never the repository (TM-651)
378
378
  mkdir -p "$CAPTURE_ROOT"
379
379
  CAPTURE_DIR="$(mktemp -d "$CAPTURE_ROOT/ci.XXXXXX")"
380
380
  MARKERS=""
@@ -18,16 +18,16 @@ PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
18
18
  # TAPP_CAPTURE_DIR selects one exact run directory (used by CI so a failed run can never
19
19
  # accidentally reuse stale markers). TAPP_HOME redirects all writable output otherwise —
20
20
  # set by the `tapp` CLI when running as an installed npm package, where the package dir
21
- # must stay read-only. Unset (repo dev flow), everything lands in the repo as before.
22
- TAPP_RUNTIME_HOME="${TAPP_HOME:-}"
21
+ # must stay read-only. Unset (a run from a source checkout), evidence still goes to
22
+ # ~/.tapp/captures like everywhere else in Tapp (TM-651): never into the repository,
23
+ # where the evidence clearing-out (evidence-retention.js) never looks.
24
+ TAPP_RUNTIME_HOME="${TAPP_HOME:-$HOME/.tapp}"
23
25
  if [[ -n "${TAPP_CAPTURE_DIR:-}" ]]; then
24
26
  CAPTURE_DIR="$TAPP_CAPTURE_DIR"
25
- elif [[ -n "$TAPP_RUNTIME_HOME" ]]; then
26
- CAPTURE_DIR="$TAPP_RUNTIME_HOME/captures/ios-$(date +%Y%m%d-%H%M%S)"
27
27
  else
28
- CAPTURE_DIR="$PROJECT_ROOT/captures/ios-$(date +%Y%m%d-%H%M%S)"
28
+ CAPTURE_DIR="$TAPP_RUNTIME_HOME/captures/ios-$(date +%Y%m%d-%H%M%S)"
29
29
  fi
30
- if [[ -n "$TAPP_RUNTIME_HOME" ]]; then
30
+ if [[ -n "${TAPP_HOME:-}" ]]; then
31
31
  HARNESS_DERIVED="$TAPP_RUNTIME_HOME/harness-derived"
32
32
  else
33
33
  HARNESS_DERIVED="/tmp/tapp-harness-derived"
@@ -104,24 +104,44 @@ ensure_harness_built() {
104
104
  fi
105
105
  echo "Preparing harness for $sim_name (source, simulator, or Xcode cache changed)..." >&2
106
106
  local src_fp=$(harness_fingerprint)
107
- mkdir -p "$HARNESS_DERIVED/Build/Products"
108
- rm -f "$marker"
109
- # Xcode leaves old SDK descriptors beside the new one. Only the descriptor emitted by
110
- # this successful build may become current; never select an arbitrary directory entry.
111
- find "$HARNESS_DERIVED/Build/Products" -maxdepth 1 -name '*.xctestrun' -type f -delete
112
- xcodebuild build-for-testing \
113
- -project "$HARNESS_PROJECT" \
114
- -scheme OCQAHarnessUITests \
115
- -destination "platform=iOS Simulator,id=$UDID" \
116
- -derivedDataPath "$HARNESS_DERIVED" \
117
- 2>&1 | tail -5 >&2
118
- local products=()
119
- while IFS= read -r product; do products+=("$product"); done < <(find "$HARNESS_DERIVED/Build/Products" -maxdepth 1 -name '*.xctestrun' -type f)
120
- if [[ ${#products[@]} -ne 1 ]]; then
121
- echo "ERROR: Harness build produced ${#products[@]} test descriptors; no cache was selected." >&2
122
- return 1
123
- fi
124
- printf '%s\n%s\n%s\n' "$udid" "$src_fp" "$(basename "${products[0]}")" > "$marker"
107
+ # TM-973: a build-for-testing into ~/.tapp/harness-derived has failed with
108
+ # errors that only show up under disk/memory pressure ("disk I/O error" on
109
+ # XCBuildData/build.db) — an identical build into a FRESH derived-data
110
+ # folder succeeds. One retry from a clean folder recovers from that, and
111
+ # the full log (not just xcodebuild's own tail) names what actually failed
112
+ # when both attempts fail, instead of a bare "(5 failures)".
113
+ local log_dir; log_dir="$(dirname "$HARNESS_DERIVED")"
114
+ mkdir -p "$log_dir"
115
+ local build_log build_rc attempt products
116
+ for attempt in 1 2; do
117
+ mkdir -p "$HARNESS_DERIVED/Build/Products"
118
+ rm -f "$marker"
119
+ # Xcode leaves old SDK descriptors beside the new one. Only the descriptor emitted by
120
+ # this successful build may become current; never select an arbitrary directory entry.
121
+ find "$HARNESS_DERIVED/Build/Products" -maxdepth 1 -name '*.xctestrun' -type f -delete
122
+ build_log="$log_dir/harness-build-attempt-$attempt.log"
123
+ build_rc=0
124
+ xcodebuild build-for-testing \
125
+ -project "$HARNESS_PROJECT" \
126
+ -scheme OCQAHarnessUITests \
127
+ -destination "platform=iOS Simulator,id=$UDID" \
128
+ -derivedDataPath "$HARNESS_DERIVED" \
129
+ > "$build_log" 2>&1 || build_rc=$?
130
+ tail -5 "$build_log" >&2
131
+ products=()
132
+ while IFS= read -r product; do products+=("$product"); done < <(find "$HARNESS_DERIVED/Build/Products" -maxdepth 1 -name '*.xctestrun' -type f 2>/dev/null)
133
+ if [[ $build_rc -eq 0 && ${#products[@]} -eq 1 ]]; then
134
+ printf '%s\n%s\n%s\n' "$udid" "$src_fp" "$(basename "${products[0]}")" > "$marker"
135
+ return 0
136
+ fi
137
+ if [[ $attempt -eq 1 ]]; then
138
+ echo "Harness build failed (exit $build_rc, ${#products[@]} test descriptor(s)); deleting $HARNESS_DERIVED and retrying once into a clean folder..." >&2
139
+ rm -rf "$HARNESS_DERIVED"
140
+ fi
141
+ done
142
+ echo "ERROR: Harness build failed twice (exit $build_rc, ${#products[@]} test descriptor(s) produced). Full log: $build_log" >&2
143
+ grep -i "error:" "$build_log" >&2 || tail -20 "$build_log" >&2
144
+ return 1
125
145
  }
126
146
 
127
147
  run_harness_test() {