@aarwitz/tapp 0.17.27 → 0.18.0

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.
@@ -20,6 +20,7 @@ import {
20
20
  import { baselinePathForTarget, existingBaselinePathForTarget, renderGithubWorkflow, selectApplicationTarget, writeCiInstallation, writeTargetBaseline } from "./ci-setup.js";
21
21
  import { executeReleaseContract, runProductProcess } from "./product-execution.js";
22
22
  import { projectArtifactDirectory } from "./project-paths.js";
23
+ import { BUSINESS_WORKFLOW_PATH } from "./business-workflows.js";
23
24
 
24
25
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
25
26
  const packageVersion = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8")).version;
@@ -209,7 +210,7 @@ function listRepositoryFlows(root) {
209
210
  steps = (block.match(/^\s{2}-\s/gm) || []).length;
210
211
  }
211
212
  } catch { /* Artifact remains inspectable; deterministic replay reports invalid syntax. */ }
212
- return { id:`flow_${crypto.createHash("sha256").update(relativePath).digest("hex").slice(0, 16)}`, name, path:relativePath, platform, steps, status:"committed" };
213
+ return { id:`flow_${crypto.createHash("sha256").update(relativePath).digest("hex").slice(0, 16)}`, name, path:relativePath, platform, steps, sha256:crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"), status:"committed" };
213
214
  })
214
215
  .sort((left, right) => left.path.localeCompare(right.path));
215
216
  }
@@ -242,6 +243,7 @@ export function readProductProject({ projectDir, outDir = ".tapp" } = {}) {
242
243
  ci,
243
244
  baselines,
244
245
  flows: listRepositoryFlows(root),
246
+ businessWorkflowDefinition: readJson(path.join(root,BUSINESS_WORKFLOW_PATH)),
245
247
  evidence: listProductRuns(root),
246
248
  state: {
247
249
  inspected: !!model,
@@ -0,0 +1,65 @@
1
+ import http from "node:http";
2
+ import https from "node:https";
3
+ import net from "node:net";
4
+ import dns from "node:dns/promises";
5
+
6
+ function publicIPv4(value) {
7
+ if (net.isIP(value) !== 4) return false;
8
+ const [a,b,c] = value.split('.').map(Number);
9
+ return !(a === 0 || a === 10 || a === 127 || a >= 224 ||
10
+ (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||
11
+ (a === 172 && b >= 16 && b <= 31) || (a === 192 && (b === 168 || b === 0 || (b === 88 && c === 99))) ||
12
+ (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) || (a === 203 && b === 0 && c === 113));
13
+ }
14
+ export async function resolvePublicHost(host) {
15
+ const normalized = host.toLowerCase().replace(/\.$/, "");
16
+ if (!normalized || normalized === "localhost" || /\.(localhost|local|internal|test|invalid)$/.test(normalized)) throw new Error("A publicly reachable app hostname is required");
17
+ const addresses = net.isIP(normalized) ? [{address:normalized}] : await dns.lookup(normalized,{all:true,family:4});
18
+ if (!addresses.length || addresses.some(item=>!publicIPv4(item.address))) throw new Error("Private and reserved network addresses are unavailable to hosted website runs");
19
+ return addresses[0].address;
20
+ }
21
+ export async function publicRequest(url, {method="POST",headers={},body,timeout=15000}={}) {
22
+ const target = new URL(url);
23
+ if(target.protocol !== "https:" || target.username || target.password || (target.port && target.port !== "443")) throw new Error("Backend actions require public HTTPS on port 443");
24
+ const address=await resolvePublicHost(target.hostname);
25
+ return new Promise((resolve,reject)=>{
26
+ const req=https.request(target,{method,headers,family:4,lookup:(_host,options,callback)=>options.all ? callback(null,[{address,family:4}]) : callback(null,address,4)},response=>{
27
+ let size=0; const chunks=[];
28
+ response.on("data",chunk=>{size+=chunk.length;if(size>262144) {response.destroy();req.destroy(new Error("Backend response exceeded 256 KiB"));}else chunks.push(chunk);});
29
+ response.on("error",reject);
30
+ response.on("end",()=>resolve({status:response.statusCode,body:Buffer.concat(chunks).toString("utf8")}));
31
+ });
32
+ req.on("error",reject);req.setTimeout(timeout,()=>req.destroy(new Error("Backend action timed out")));
33
+ if(body)req.write(body);req.end();
34
+ });
35
+ }
36
+
37
+ // Resolve and pin every TCP connection, including redirects and subresources.
38
+ // This proxy is for URL-only work; it deliberately cannot reach local dev servers.
39
+ export async function startPublicBrowserProxy() {
40
+ const sockets=new Set();
41
+ const track=socket=>{sockets.add(socket);socket.on("close",()=>sockets.delete(socket));socket.on("error",()=>{});return socket;};
42
+ const server=http.createServer(async (request,response)=>{
43
+ try{
44
+ const url=new URL(request.url);
45
+ if(url.protocol!=="http:" || (url.port && url.port!=="80") || url.username || url.password) throw new Error();
46
+ const address=await resolvePublicHost(url.hostname);
47
+ const headers={...request.headers,host:url.host};delete headers["proxy-authorization"];delete headers["proxy-connection"];
48
+ const outgoing=http.request({host:address,port:80,path:url.pathname+url.search,method:request.method,headers},remote=>{response.writeHead(remote.statusCode,remote.headers);remote.pipe(response);});
49
+ outgoing.on("socket",track);outgoing.setTimeout(30000,()=>outgoing.destroy());outgoing.on("error",()=>{if(!response.headersSent)response.writeHead(502);response.end();});
50
+ request.on("aborted",()=>outgoing.destroy());request.pipe(outgoing);
51
+ }catch{response.writeHead(403);response.end("Public network access required");}
52
+ });
53
+ server.on("connection",track);
54
+ server.on("connect",async (request,socket,head)=>{
55
+ try{
56
+ const target=new URL(`https://${request.url}`);
57
+ if(target.port && target.port!=="443")throw new Error();
58
+ const address=await resolvePublicHost(target.hostname);
59
+ const upstream=track(net.connect(443,address,()=>{socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");if(head.length)upstream.write(head);socket.pipe(upstream);upstream.pipe(socket);}));
60
+ upstream.setTimeout(120000,()=>upstream.destroy());socket.on("close",()=>upstream.destroy());upstream.on("close",()=>socket.destroy());
61
+ }catch{socket.end("HTTP/1.1 403 Forbidden\r\n\r\n");}
62
+ });
63
+ await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve);});
64
+ return {url:`http://127.0.0.1:${server.address().port}`,close:async()=>{for(const socket of sockets)socket.destroy();await new Promise(resolve=>server.close(resolve));}};
65
+ }
@@ -21,6 +21,7 @@ import { buildQaReport } from "./report.js";
21
21
  import { writeHtmlReport } from "./html-report.js";
22
22
  import { buildUiMapFromMarkers, writeUiMap } from "./ui-map.js";
23
23
  import { writeCaptureProvenance } from "./capture-provenance.js";
24
+ import { passiveUrlRisk } from "./business-observation.js";
24
25
 
25
26
  const require = createRequire(import.meta.url);
26
27
  const VERSION = (() => { try { return require("../../package.json").version; } catch { return "0.0.0"; } })();
@@ -110,10 +111,11 @@ async function auditPageHealth(page) {
110
111
  if (!src || src.startsWith("data:")) continue;
111
112
  if (img.complete && img.naturalWidth === 0) {
112
113
  // A 1×1 (or hidden) image that failed is a tracking pixel the visitor never sees, not a
113
- // broken picture on the page; a failed image lays out as a 16px placeholder box even when
114
- // it was meant to be invisible, so a cross-origin, query-string, alt-less one is a beacon.
114
+ // broken picture on the page.
115
115
  const box = img.getBoundingClientRect();
116
116
  if (box.width <= 2 || box.height <= 2) continue;
117
+ // A failed image lays out as a 16px placeholder box even when it was meant to be
118
+ // invisible; a cross-origin, query-string, alt-less image is a beacon, not a picture.
117
119
  let crossOrigin = false;
118
120
  try { crossOrigin = new URL(src, location.href).origin !== location.origin; } catch { /* keep */ }
119
121
  if (crossOrigin && /\?/.test(src) && !img.hasAttribute("alt")) continue;
@@ -208,7 +210,7 @@ async function checkLinks(context, links, { limit, pageUrl }) {
208
210
 
209
211
  // One page, inside an already-open context. Collects everything, then (if a capture is open) shoots
210
212
  // the page and each named element and appends the markers.
211
- async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, capture }) {
213
+ async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, capture, blockedRequests = new WeakSet(), observationOnly = false, allowLink = () => true }) {
212
214
  const page = await context.newPage();
213
215
  const bounded = Math.max(1000, Math.min(60_000, Number(timeoutMs) || NAV_TIMEOUT_MS));
214
216
  page.setDefaultTimeout(bounded);
@@ -231,6 +233,7 @@ async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, captur
231
233
  });
232
234
  page.on("requestfailed", (req) => {
233
235
  try {
236
+ if (blockedRequests.has(req)) return; // Our observation policy is not an application defect.
234
237
  const u = new URL(req.url());
235
238
  if (u.origin !== origin) return;
236
239
  const errorText = req.failure()?.errorText || "?";
@@ -246,7 +249,8 @@ async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, captur
246
249
 
247
250
  const controls = await auditStructuralControls(page);
248
251
  const health = await auditPageHealth(page);
249
- const links = await checkLinks(context, health.links, { limit: linkCheckLimit, pageUrl: page.url() });
252
+ const allowedLinks = health.links.filter(allowLink);
253
+ const links = await checkLinks(context, allowedLinks, { limit: linkCheckLimit, pageUrl: page.url() });
250
254
 
251
255
  const structural = auditFindingsFromControls(controls.dead).map((f, i) => ({ ...f, selector: controls.dead[i].selector }));
252
256
  const findings = [...structural, ...healthFindings(health.findings), ...loadFindings, ...links.findings];
@@ -273,12 +277,15 @@ async function auditOnePage(context, target, { timeoutMs, linkCheckLimit, captur
273
277
  return {
274
278
  url: page.url(),
275
279
  title: controls.title,
280
+ ...(observationOnly ? { visibleText: await page.locator("body").innerText({ timeout: bounded }).then(text => text.slice(0, 12000)).catch(() => ""),
281
+ visibleTextLimit: 12000 } : {}),
282
+ ...(page.video() ? { recording: path.basename(await page.video().path()) } : {}),
276
283
  controlsExamined: controls.controlCount,
277
284
  linksChecked: { total: links.total, checked: links.checked },
278
285
  // Why the wiring-dependent checks were skipped on this page, if they were.
279
286
  ...(controls.wiringUnverifiable ? { wiringUnverifiable: controls.wiringUnverifiable } : {}),
280
287
  findings,
281
- links: health.links,
288
+ links: allowedLinks,
282
289
  };
283
290
  } finally {
284
291
  await page.close().catch(() => {});
@@ -301,7 +308,7 @@ export function auditCaptureId(now = new Date()) {
301
308
  return `web-audit-${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}-${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`;
302
309
  }
303
310
 
304
- function finalizeCapture(capture, { startUrl, pages, findings, robotsBlocked, linksChecked, wiringUnverifiable = [] }) {
311
+ function finalizeCapture(capture, { startUrl, pages, findings, robotsBlocked, linksChecked, observationLimits = [], skippedLinks = [], wiringUnverifiable = [] }) {
305
312
  capture.emit("COMPLETE", { actions: 0, screens: pages.length, credentialsProvided: false, credentialsUsed: false, timedOut: false, stop: "audit-complete", readOnly: true, robotsBlocked });
306
313
  capture.close();
307
314
  const markers = path.join(capture.dir, "ocqa-markers.txt");
@@ -313,15 +320,18 @@ function finalizeCapture(capture, { startUrl, pages, findings, robotsBlocked, li
313
320
  Object.assign(report, {
314
321
  kind: "tapp-structural-audit",
315
322
  readOnly: true,
316
- inconclusive: false,
323
+ inconclusive: observationLimits.length > 0,
317
324
  runStatus: "completed",
318
325
  stopReason: "audit-complete",
319
- headline: findings.length === 0
326
+ headline: observationLimits.length > 0
327
+ ? `Passive audit of ${pages.length} page(s): ${findings.length} finding(s). Observation restrictions limited rendering; inspect those limits before attributing findings to the app.`
328
+ : findings.length === 0
320
329
  ? `Read-only audit of ${pages.length} page(s) — nothing broken was observed. Nothing was clicked; this says the page is served without structural defects, not that the product works.`
321
330
  : `${findings.length} defect(s) observed on ${pages.length} page(s) without clicking anything (${counts.critical} critical, ${counts.high} high, ${counts.medium} medium, ${counts.low} low).`,
322
331
  checkedFor: scope.checkedFor,
323
- notChecked: scope.notChecked,
324
- conditionsNotReached: [],
332
+ notChecked: [...scope.notChecked, ...observationLimits, ...(skippedLinks.length ? ["Potential action/signed links and robots exclusions were not fetched; see skippedLinks."] : [])],
333
+ skippedLinks,
334
+ conditionsNotReached: observationLimits,
325
335
  });
326
336
  fs.writeFileSync(path.join(capture.dir, "report.json"), JSON.stringify(report, null, 2));
327
337
  // The capture-local UI map is what ties a page screenshot to the findings on that page for
@@ -356,12 +366,13 @@ export function dedupeSiteIssues(findings = []) {
356
366
  export async function auditWebSite({
357
367
  url, pages = 1, timeoutMs = NAV_TIMEOUT_MS, device = "", viewport = "",
358
368
  linkCheckLimit = AUDIT_LINK_CHECK_LIMIT, delayMs = AUDIT_CRAWL_DELAY_MS,
359
- capturesDir = "", captureId = "", onPage = null,
369
+ capturesDir = "", captureId = "", onPage = null, observationOnly = false, recordVideo = false,
360
370
  }) {
361
371
  let start;
362
372
  try { start = new URL(url); }
363
373
  catch { throw new Error("Audit needs a valid http(s) URL"); }
364
374
  if (!/^https?:$/.test(start.protocol)) throw new Error("Audit needs a valid http(s) URL");
375
+ if (observationOnly && passiveUrlRisk(start.href)) throw new Error("Passive checks cannot open signed or potentially state-changing links");
365
376
  const maxPages = Math.max(1, Math.min(200, Number(pages) || 1));
366
377
 
367
378
  const { chromium, devices } = await loadPlaywright();
@@ -374,12 +385,39 @@ export async function auditWebSite({
374
385
  const probe = await browser.newContext(contextOptions);
375
386
  const defaultUa = contextOptions.userAgent || await (await probe.newPage()).evaluate(() => navigator.userAgent).catch(() => "");
376
387
  await probe.close();
377
- const context = await browser.newContext({ ...contextOptions, userAgent: `${defaultUa} tapp-audit/${VERSION} (+https://runtapp.com)`.trim() });
388
+ const context = await browser.newContext({ ...contextOptions,
389
+ ...(observationOnly ? { serviceWorkers: "block", acceptDownloads: false } : {}),
390
+ ...(recordVideo && capture ? { recordVideo: { dir: capture.dir } } : {}),
391
+ userAgent: `${defaultUa} tapp-audit/${VERSION} (+https://runtapp.com)`.trim() });
392
+ const blockedRequests = new WeakSet();
393
+ const observationLimits = new Set();
394
+ if (observationOnly) {
395
+ // Enforce the passive path even if page JavaScript tries to submit data.
396
+ // No login/storage state or application credentials enter this fresh context.
397
+ await context.route("**/*", async route => {
398
+ const request = route.request();
399
+ const method = request.method();
400
+ const risk = passiveUrlRisk(request.url());
401
+ if (!["GET", "HEAD"].includes(method) || risk) {
402
+ blockedRequests.add(request);
403
+ observationLimits.add(risk ? "A possible action or signed resource URL was blocked; dependent content was not verified."
404
+ : `${method} requests were blocked; content depending on those requests was not verified.`);
405
+ await route.abort("blockedbyclient");
406
+ return;
407
+ }
408
+ await route.continue();
409
+ });
410
+ if (typeof context.routeWebSocket !== "function") throw new Error("Passive hosted checks require a Playwright version with WebSocket routing");
411
+ await context.routeWebSocket("**/*", socket => {
412
+ observationLimits.add("WebSockets were blocked; live content depending on them was not verified.");
413
+ socket.close();
414
+ });
415
+ }
378
416
  await installWebListenerTracking(context);
379
417
  if (capture) capture.emit("CONTEXT", { ...(String(device || "").trim() ? { device: String(device).trim() } : {}), viewport: contextOptions.viewport, deviceScaleFactor: contextOptions.deviceScaleFactor ?? 1, mode: "audit", readOnly: true });
380
418
 
381
419
  let robots = [];
382
- if (maxPages > 1) {
420
+ if (maxPages > 1 || observationOnly) {
383
421
  try {
384
422
  const res = await context.request.get(new URL("/robots.txt", start).href, { timeout: 5_000, failOnStatusCode: false });
385
423
  if (res.ok()) robots = parseRobots(await res.text());
@@ -388,19 +426,33 @@ export async function auditWebSite({
388
426
 
389
427
  const results = [];
390
428
  const robotsBlocked = [];
429
+ const skippedLinks = new Map();
430
+ const allowLink = link => {
431
+ if (!observationOnly) return true;
432
+ const url = new URL(link.href);
433
+ const reason = passiveUrlRisk(link.href) || (url.origin === start.origin && !robotsAllows(robots, url.pathname) ? "robots-excluded" : null);
434
+ if (!reason) return true;
435
+ if (skippedLinks.size < 100) skippedLinks.set(link.href, { path: url.pathname, reason });
436
+ return false;
437
+ };
391
438
  const queued = new Set([start.href]);
392
439
  const queue = [start];
393
440
  let linksTotal = 0;
394
441
  let linksChecked = 0;
395
442
  while (queue.length && results.length < maxPages) {
396
443
  const target = queue.shift();
444
+ if (observationOnly && !robotsAllows(robots, target.pathname)) {
445
+ robotsBlocked.push(target.href);
446
+ observationLimits.add("robots.txt excluded a requested page; it was not inspected.");
447
+ continue;
448
+ }
397
449
  if (results.length > 0) {
398
450
  if (!robotsAllows(robots, target.pathname)) { robotsBlocked.push(target.href); continue; }
399
451
  if (delayMs > 0) await new Promise((r) => setTimeout(r, delayMs));
400
452
  }
401
453
  let result;
402
454
  try {
403
- result = await auditOnePage(context, target, { timeoutMs, linkCheckLimit, capture });
455
+ result = await auditOnePage(context, target, { timeoutMs, linkCheckLimit, capture, blockedRequests, observationOnly, allowLink });
404
456
  } catch (error) {
405
457
  if (results.length === 0) throw error;
406
458
  result = { url: target.href, title: "", controlsExamined: 0, linksChecked: { total: 0, checked: 0 }, links: [],
@@ -409,7 +461,8 @@ export async function auditWebSite({
409
461
  linksTotal += result.linksChecked.total;
410
462
  linksChecked += result.linksChecked.checked;
411
463
  const { links, ...pageResult } = result;
412
- results.push(pageResult);
464
+ results.push({ ...pageResult, ...(observationOnly ? { observedLinks: links.slice(0, 100),
465
+ observedLinksTruncated: links.length > 100 } : {}) });
413
466
  if (typeof onPage === "function") onPage(pageResult, results.length);
414
467
  // A link the HEAD check already found broken is reported; opening it would only repeat the finding.
415
468
  const broken = new Set(pageResult.findings.filter((f) => f.type === "broken_link").map((f) => f.target));
@@ -417,12 +470,15 @@ export async function auditWebSite({
417
470
  if (!link.sameOrigin || queued.has(link.href) || broken.has(link.href) || queued.size >= maxPages * 4) continue;
418
471
  let next;
419
472
  try { next = new URL(link.href); } catch { continue; }
473
+ if (observationOnly && next.origin !== start.origin) continue;
420
474
  if (/\.(pdf|zip|png|jpe?g|gif|svg|webp|mp4|mp3|css|js|xml|ico)$/i.test(next.pathname)) continue;
421
475
  queued.add(next.href);
422
476
  queue.push(next);
423
477
  }
424
478
  }
425
479
 
480
+ // Closing the context finalizes page recordings before evidence is uploaded.
481
+ await context.close();
426
482
  const findings = results.flatMap((r) => r.findings);
427
483
  const issues = dedupeSiteIssues(findings);
428
484
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
@@ -432,23 +488,27 @@ export async function auditWebSite({
432
488
  const summary = {
433
489
  kind: "tapp-structural-audit",
434
490
  readOnly: true,
491
+ ...(observationOnly ? { observationOnly: true, observationLimits: [...observationLimits],
492
+ inconclusive: observationLimits.size > 0,
493
+ observationPolicy: "Fresh unauthenticated browser; no interactions; GET/HEAD only; no WebSockets or service workers. Page loads may still generate server logs and analytics. Restricted rendering may affect findings." } : {}),
435
494
  url: start.href,
436
495
  pagesAudited: results.length,
437
496
  pagesWithUnverifiableWiring: wiringUnverifiable.length,
438
497
  pagesQueued: queue.length,
439
498
  robotsBlocked,
499
+ ...(observationOnly ? { skippedLinks: [...skippedLinks.values()], skippedLinksLimit: 100 } : {}),
440
500
  findingCounts: { ...bySeverity, total: findings.length },
441
501
  // One entry per distinct defect across the site, with the pages it appears on: a footer
442
502
  // link that answers 404 on six pages is one thing to fix, and one line in an email.
443
503
  issues,
444
504
  issueCount: issues.length,
445
505
  checkedFor: scope.checkedFor,
446
- notChecked: scope.notChecked,
506
+ notChecked: [...scope.notChecked, ...observationLimits, ...(skippedLinks.size ? ["Potential action/signed links and robots exclusions were not fetched; see skippedLinks."] : [])],
447
507
  pages: results,
448
508
  capture: null,
449
509
  };
450
510
  if (capture) {
451
- finalizeCapture(capture, { startUrl: start.href, pages: results, findings, robotsBlocked, linksChecked: { total: linksTotal, checked: linksChecked }, wiringUnverifiable });
511
+ finalizeCapture(capture, { startUrl: start.href, pages: results, findings, robotsBlocked, linksChecked: { total: linksTotal, checked: linksChecked }, observationLimits: [...observationLimits], skippedLinks: [...skippedLinks.values()], wiringUnverifiable });
452
512
  summary.capture = { id: capture.id, path: capture.dir, report: path.join(capture.dir, "report.html"), provenance };
453
513
  fs.writeFileSync(path.join(capture.dir, "audit.json"), JSON.stringify(summary, null, 2));
454
514
  }
@@ -666,7 +666,16 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
666
666
  const markersFd = fs.openSync(markersPath, "w");
667
667
  const emit = (kind, payload) => fs.writeSync(markersFd, `OCQA_${kind}:${JSON.stringify(payload)}\n`);
668
668
  const startedAtMs = Date.now();
669
- const emitAction = (payload) => emit("ACTION", { t: Date.now() - startedAtMs, ...payload });
669
+ const emitAction = (payload) => {
670
+ emit("ACTION", { t: Date.now() - startedAtMs, ...payload });
671
+ narrate(payload.narrative || `${payload.type} ${payload.target}`, { screen: payload.screen });
672
+ };
673
+ // Live narration for hosts that render a transcript (Studio chat). Counts stay on the
674
+ // regular progress tick; this carries what the action was and, on a new state, its screenshot.
675
+ const narrate = (narrative, extra = {}) => {
676
+ if (!onProgress) return;
677
+ try { onProgress({ action: actions, max: maxActions, states: screenCount, narrative, ...extra }); } catch {}
678
+ };
670
679
 
671
680
  const { chromium, devices } = await loadPlaywright();
672
681
  const browser = await chromium.launch(webBrowserLaunchOptions(process.env, { watch }));
@@ -869,6 +878,7 @@ export async function exploreWeb({ url, maxActions = 40, timeoutSec = 300, outDi
869
878
  screenshotFor.set(evidenceKey, { path: screenshotPath, busy: info.busy, route: key });
870
879
  screenCount = screenshotFor.size;
871
880
  await screenshotWithoutWebWatchUi(page, { path: screenshotPath }, watch).catch(() => {});
881
+ narrate(existingScreenshot ? `Settled on ${screen}` : `Reached ${screen}`, { screen, screenshot: screenshotPath });
872
882
  // Deterministic per-page detectors run once per distinct screen.
873
883
  if (webPageAppearsBlank(info)) issue("blank_screen", "high", "Page rendered no visible content", screen);
874
884
  else {
@@ -153,6 +153,12 @@ export async function runWebRequestStep({ step, startUrl, vars = {}, timeout = D
153
153
  init.body = JSON.stringify(substituteStructure(request.body, vars));
154
154
  if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) headers["content-type"] = "application/json";
155
155
  }
156
+ if (process.env.TAPP_ENFORCE_PUBLIC_EGRESS === "1") {
157
+ const { publicRequest } = await import("./public-network.js");
158
+ const response = await publicRequest(targetUrl, {method,headers,body:init.body,timeout:Number(request.timeoutMs) || timeout});
159
+ if (response.status !== Number(request.status ?? 200)) throw new Error(`${method} ${targetUrl.pathname} did not return the expected status`);
160
+ return { action:"request",target:`${method} ${targetUrl.pathname}`,status:"pass",detail:"" };
161
+ }
156
162
  const response = await fetch(targetUrl, init);
157
163
  const expected = Number(request.status ?? 200);
158
164
  if (response.status !== expected) throw new Error(`${method} ${targetUrl.pathname} returned ${response.status}; expected ${expected}`);
@@ -284,7 +290,7 @@ export function resolveGateFlowUrl(declared, gateUrl) {
284
290
  }
285
291
  }
286
292
 
287
- export async function runWebFlow({ flow, url, logPath, screenshotDir, playwright, device = "", viewport = "", urlIsFallback = false }) {
293
+ export async function runWebFlow({ flow, url, logPath, screenshotDir, recordVideoDir, variables = {}, strictOrigin = false, playwright, device = "", viewport = "", urlIsFallback = false }) {
288
294
  // urlIsFallback = the caller is a gate: the Flow's own page wins, rebased onto the gate's
289
295
  // deployment (see resolveGateFlowUrl). An explicit caller url (CLI positional) still overrides.
290
296
  const declaredUrl = flow.url || (/^https?:\/\//i.test(flow.app || "") ? flow.app : "");
@@ -296,12 +302,13 @@ export async function runWebFlow({ flow, url, logPath, screenshotDir, playwright
296
302
  const loggedFlow = { ...flow, steps: [...setup, ...flow.steps, ...teardown] };
297
303
  const log = new FlowLog({ logPath, flow: loggedFlow });
298
304
  const pw = playwright || await loadPlaywright();
299
- const browser = await pw.chromium.launch({ headless: true });
300
- const context = await browser.newContext(webContextOptions({ device, viewport, devices: pw.devices }));
305
+ const { webBrowserLaunchOptions } = await import("./web-explorer.js");
306
+ const browser = await pw.chromium.launch(webBrowserLaunchOptions());
307
+ const context = await browser.newContext({...webContextOptions({ device, viewport, devices: pw.devices }),...(recordVideoDir ? {recordVideo:{dir:recordVideoDir}} : {})});
301
308
  const page = await context.newPage();
302
309
  const timeout = Number(flow.timeoutMs ?? flow.timeout) || DEFAULT_TIMEOUT;
303
310
  page.setDefaultTimeout(timeout);
304
- const vars = flowVariables(flow);
311
+ const vars = flowVariables(flow, variables);
305
312
  let index = 0;
306
313
  let failed = false;
307
314
 
@@ -328,6 +335,10 @@ export async function runWebFlow({ flow, url, logPath, screenshotDir, playwright
328
335
  await page.goto(startUrl, { waitUntil: "domcontentloaded" });
329
336
  await settle(page);
330
337
  for (const step of flow.steps) {
338
+ if (strictOrigin && new URL(page.url()).origin !== new URL(startUrl).origin) {
339
+ emit({action:"origin",target:"connected app",status:"fail",detail:"The workflow left the connected app origin. Authorize a supported sign-in route before continuing."});
340
+ break;
341
+ }
331
342
  const outcome = await executeWebFlowStep({ page, step, vars, defaultTimeout: timeout });
332
343
  emit(outcome);
333
344
  if (outcome.status === "fail" && screenshotDir) {
@@ -343,6 +354,8 @@ export async function runWebFlow({ flow, url, logPath, screenshotDir, playwright
343
354
  }
344
355
  } finally {
345
356
  await requestPhase(teardown);
357
+ // Test doubles for playwright may not model a context; a real one always closes.
358
+ if (typeof context.close === "function") await context.close().catch(() => {});
346
359
  await browser.close().catch(() => {});
347
360
  }
348
361
  return log.finish({ url: startUrl });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aarwitz/tapp",
3
- "version": "0.17.27",
3
+ "version": "0.18.0",
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",
@@ -11,6 +11,11 @@
11
11
  "exports": {
12
12
  ".": "./mcp-server/src/index.js",
13
13
  "./product-operations": "./mcp-server/src/product-operations.js",
14
+ "./business-workflows": {
15
+ "types": "./mcp-server/src/business-workflows.d.ts",
16
+ "import": "./mcp-server/src/business-workflows.js"
17
+ },
18
+ "./business-workflow-runtime": "./mcp-server/src/business-workflow-runtime.js",
14
19
  "./contracts": {
15
20
  "types": "./mcp-server/src/release-contract.d.ts",
16
21
  "import": "./mcp-server/src/contract-authoring.js"
@@ -21,6 +26,7 @@
21
26
  "browser/",
22
27
  "docs/BROWSER-PRODUCT.md",
23
28
  "docs/PRODUCT-ENGINE.md",
29
+ "docs/BUSINESS-WORKFLOWS.md",
24
30
  "docs/application-model.md",
25
31
  "docs/scenarios.md",
26
32
  "mcp-server/src/",
@@ -24,6 +24,10 @@ try {
24
24
  url: process.argv[3],
25
25
  logPath,
26
26
  screenshotDir,
27
+ ...(process.env.TAPP_FLOW_RECORD_VIDEO === "1" ? {recordVideoDir:screenshotDir} : {}),
28
+ ...(process.env.TAPP_WORKFLOW_REPLAY === "1" ? {strictOrigin:true,variables:{
29
+ TEST_RUN_ID:process.env.TEST_RUN_ID || "",TEST_EMAIL:process.env.OCQA_TEST_EMAIL || "",TEST_PASSWORD:process.env.OCQA_TEST_PASSWORD || "",
30
+ }} : {}),
27
31
  device: process.env.TAPP_WEB_DEVICE || "",
28
32
  viewport: process.env.TAPP_WEB_VIEWPORT || "",
29
33
  });
@@ -12,13 +12,13 @@ screen or journey works from source inspection alone.
12
12
 
13
13
  | Intent | Operation |
14
14
  |---|---|
15
- | See or screenshot one screen | `open` / `tapp_open_app` |
16
- | Inspect controls on the current screen | `tree` / `tapp_ui_tree` |
17
- | Reach a named screen/control | `focus` / `tapp_focus` (source + observed UI Map fast path) |
18
- | Drive a specific journey | MCP session start → focus or act → end |
15
+ | See or screenshot one screen | `look` / `tapp_look` |
16
+ | Inspect controls on the current screen | `look --tree` / `tapp_look {tree:true}` |
17
+ | Reach a named screen/control | `explore --goal` / `tapp_explore {goal}` (source + observed UI Map fast path) |
18
+ | Drive a specific journey | `tapp_session` start → act → end |
19
19
  | Find bugs autonomously (owned app/environment; it clicks) | `explore` / `tapp_explore` |
20
- | Check production or a site you do not own (never clicks) | `audit` / `tapp_audit` |
21
- | Preserve a journey | record and save a Flow; replay it deterministically |
20
+ | Check production or a site you do not own (never clicks) | `explore --read-only` / `tapp_explore {readOnly:true}` |
21
+ | Preserve a journey | `tapp_session {action:"save_flow"}`; replay it with `run` / `tapp_run` |
22
22
  | Decide whether a merge passes policy | `ci`; exploration never decides this |
23
23
 
24
24
  Prefer connected `tapp_*` MCP tools when available: they keep interactive sessions alive and return
@@ -35,7 +35,7 @@ When the user asks for a general first test of a repository:
35
35
  3. If Tapp returns `target-selection-required`, present its actual choices and ask the user to pick.
36
36
  Never guess among multiple targets. Re-run with the selected platform/target exactly as Tapp
37
37
  instructs.
38
- 4. If a prerequisite is missing, call `tapp_health` when MCP is connected or run
38
+ 4. If a prerequisite is missing, call `tapp_doctor` when MCP is connected or run
39
39
  `npx -y @aarwitz/tapp@latest doctor`, apply only the stated remediation that is in scope, and
40
40
  retry once.
41
41
 
@@ -50,17 +50,17 @@ or owned HTTP(S) URL. Never explore a third-party web property: exploration clic
50
50
  When the user names a screen, control, or UI condition, do not discover the app one screenshot at a
51
51
  time. Start from the repository source, then use Tapp's observed navigation evidence:
52
52
 
53
- 1. In a source repository, run `npx -y @aarwitz/tapp@latest focus "<exact request>" [target]`; it
54
- selects the reviewed model target and prepares web, iOS, or Android from source. In an active MCP
55
- session call `tapp_focus`; for managed web, `tapp_session_start` can also take `projectDir` and
56
- `focus` without retyping the URL.
53
+ 1. In a source repository, run `npx -y @aarwitz/tapp@latest explore --goal "<exact request>" [target]`;
54
+ it selects the reviewed model target and prepares web, iOS, or Android from source. In an active MCP
55
+ session call `tapp_explore {goal}`; for managed web, `tapp_session {action:"start"}` can also take
56
+ `projectDir` and `focus` without retyping the URL.
57
57
  2. Tapp searches owned source, reconciles the likely surface with `.tapp/ui-map.json`, and executes
58
58
  the shortest runtime-observed route in one call. Read its final tree before visual assertions.
59
59
  3. If Tapp returns source evidence but no replayable route, inspect the cited file/line and relevant
60
60
  router/navigation source. Do not wander blindly or invent a path; ground the map or drive only a
61
61
  route supported by that source evidence.
62
62
 
63
- A fresh repository needs one grounding exploration before `focus` can replay a route. Source can
63
+ A fresh repository needs one grounding exploration before `--goal` can replay a route. Source can
64
64
  locate an unobserved surface, but it never authorizes unobserved taps.
65
65
 
66
66
  Source establishes intent and location; the real UI establishes behavior. A URL-only target has no
@@ -78,7 +78,7 @@ ship verdict. Report:
78
78
  - what Tapp explicitly did not check.
79
79
 
80
80
  Evidence is the capture the command just returned. `~/.tapp/captures/` is shared by every project on
81
- the machine; `tapp_list_captures` shows only this project's and labels each with its provenance. Never
81
+ the machine; `tapp_report` shows only this project's and labels each with its provenance. Never
82
82
  cite or reuse another project's capture, and never borrow one as a fixture — make a fresh one.
83
83
 
84
84
  If `inconclusive: true`, explain the blocker. A login wall or missing test data is not a pass. Ask for
@@ -109,4 +109,5 @@ workaround to finish a straightforward task; a result reported `ok`/`inconclusiv
109
109
  shouldn't have; or you're unsure whether something is a real app finding or a Tapp bug. One report
110
110
  per issue; when unsure, file — a closed non-issue costs nothing, an unreported bug stays a bug.
111
111
 
112
+ Older verbs and tool names (`audit`, `focus`, `open`, `tree`, `tapp_session_start`, …) still work for one minor version and print their new form.
112
113
  Read [references/commands.md](references/commands.md) only for exact CLI/MCP syntax, Flow replay, credentials, or platform prerequisites.