@tangle-network/agent-app 2.0.1 → 2.0.2

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.
@@ -813,8 +813,7 @@ function addCookieNeedles(file, hard) {
813
813
  import { execFileSync } from "child_process";
814
814
  import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
815
815
  import { basename, join as join4 } from "path";
816
- var W = 1440;
817
- var H = 900;
816
+ var DESKTOP_FRAME = { width: 1440, height: 900 };
818
817
  var BAR = 84;
819
818
  var MAX_HIGHLIGHTS_S = 178;
820
819
  var FONT_CANDIDATES = [
@@ -866,7 +865,7 @@ ${srtTime(c.start)} --> ${srtTime(c.end)}
866
865
  ${c.text}
867
866
  `).join("\n");
868
867
  }
869
- function assText(cues) {
868
+ function assText(cues, { width: W, height: H }) {
870
869
  const esc = (t) => t.replace(/\\/g, "\\\\").replace(/[{}]/g, "").replace(/\n/g, "\\N");
871
870
  const head = `[Script Info]
872
871
  ScriptType: v4.00+
@@ -916,14 +915,16 @@ function postProcessVideo(o) {
916
915
  mkdirSync2(o.videoDir, { recursive: true });
917
916
  const keep = join4(o.workDir, `${o.label}.webm`);
918
917
  if (o.webm !== keep) copyFileSync(o.webm, keep);
919
- writeFileSync(join4(o.workDir, `${o.label}.chapters.json`), JSON.stringify({ t0: o.t0, wallSeconds: o.wallSeconds, chapters: o.chapters }));
920
- return renderAll(keep, o.workDir, o.videoDir, o.label, o.t0, o.chapters, o.speedup2x, o.wallSeconds);
918
+ const size = o.size ?? DESKTOP_FRAME;
919
+ writeFileSync(join4(o.workDir, `${o.label}.chapters.json`), JSON.stringify({ t0: o.t0, wallSeconds: o.wallSeconds, chapters: o.chapters, size }));
920
+ return renderAll(keep, o.workDir, o.videoDir, o.label, o.t0, o.chapters, o.speedup2x, o.wallSeconds, size);
921
921
  }
922
922
  function rebuildVideo(rawLabelDir, videoDir, label, speedup2x) {
923
923
  const meta = JSON.parse(readFileSync3(join4(rawLabelDir, `${label}.chapters.json`), "utf8"));
924
- return renderAll(join4(rawLabelDir, `${label}.webm`), rawLabelDir, videoDir, label, meta.t0, meta.chapters, speedup2x, meta.wallSeconds);
924
+ return renderAll(join4(rawLabelDir, `${label}.webm`), rawLabelDir, videoDir, label, meta.t0, meta.chapters, speedup2x, meta.wallSeconds, meta.size ?? DESKTOP_FRAME);
925
925
  }
926
- function renderAll(webm, work, videoDir, label, t0, chapters, speedup2x, wallSeconds) {
926
+ function renderAll(webm, work, videoDir, label, t0, chapters, speedup2x, wallSeconds, size) {
927
+ const { width: W, height: H } = size;
927
928
  const clean = join4(work, `${label}.clean.mp4`);
928
929
  ff(["-i", webm, "-vf", `fps=25,scale=${W}:${H}:flags=lanczos,format=yuv420p`, "-c:v", "libx264", "-preset", "veryfast", "-crf", "22", "-threads", "2", "-an", clean]);
929
930
  const duration = probeSeconds(clean);
@@ -932,7 +933,7 @@ function renderAll(webm, work, videoDir, label, t0, chapters, speedup2x, wallSec
932
933
  const srt = join4(videoDir, `${label}.srt`);
933
934
  writeFileSync(srt, srtText(cues));
934
935
  const ass = join4(work, `${label}.full.ass`);
935
- writeFileSync(ass, assText(cues));
936
+ writeFileSync(ass, assText(cues, size));
936
937
  const full = join4(videoDir, `${label}-full.mp4`);
937
938
  const font = monoFont();
938
939
  const clock = `drawtext=${font ? `fontfile=${font}` : "font=monospace"}:text='%{pts\\:hms}':x=w-tw-28:y=h-${BAR / 2}-th/2:fontsize=26:fontcolor=white@0.8`;
@@ -956,7 +957,7 @@ function renderAll(webm, work, videoDir, label, t0, chapters, speedup2x, wallSec
956
957
  const joined = join4(work, `${label}.highlights.raw.mp4`);
957
958
  ff(["-f", "concat", "-safe", "0", "-i", listFile, "-c", "copy", joined]);
958
959
  const hass = join4(work, `${label}.highlights.ass`);
959
- writeFileSync(hass, assText(hcues));
960
+ writeFileSync(hass, assText(hcues, size));
960
961
  const highlights = join4(videoDir, `${label}-highlights.mp4`);
961
962
  ff(["-i", joined, "-vf", `pad=${W}:${H + BAR}:0:0:color=0x111111,ass=${hass}`, "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-threads", "2", "-pix_fmt", "yuv420p", "-movflags", "+faststart", highlights]);
962
963
  const out = [full, srt, highlights];
@@ -1229,4 +1230,4 @@ export {
1229
1230
  scoreboardMetaId,
1230
1231
  scoreboardRows
1231
1232
  };
1232
- //# sourceMappingURL=chunk-OZDMIYES.js.map
1233
+ //# sourceMappingURL=chunk-KTQM7JE6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/journeys/score.ts","../src/journeys/config.ts","../src/journeys/scrub.ts","../src/journeys/trace-zip.ts","../src/journeys/session.ts","../src/journeys/video.ts","../src/journeys/report.ts","../src/journeys/scoreboard.ts"],"sourcesContent":["/**\n * Whether a recorded chat turn worked, decided from what the person saw.\n *\n * The GTM journey harness scored 6 of 6 failed turns \"completed\":\n * it read failure only from `role=\"alert\"` and from the tail of the assistant's\n * markdown, and the red failure card a person saw carried neither. One caption\n * read \"Turn complete after 159.6 s\" over \"The agent stopped before finishing\".\n * This module is the replacement rule, pure so every case is a unit test:\n *\n * - failure evidence is read from the transcript region (failure-marked\n * elements, failure lines in plain text, and a Retry control that appeared),\n * not from the reply alone, and from after the turn's own prompt when the\n * page shows it (see page-reading.ts);\n * - only evidence that appeared during the turn counts, so an earlier failure in\n * the same thread cannot fail a later turn, even one the page re-renders after\n * Send, and a card that Retry replaced with a new failure still counts;\n * - a turn that ends with no new reply text is `empty`, never `completed`;\n * - a turn the person stopped is `stopped`, not a success and not a crash.\n */\n\n/** What one poll of the page returns. Collected in the page, judged here. */\nexport interface TranscriptSnapshot {\n /** Visible lines of the transcript region, trimmed, empty lines dropped. */\n readonly lines: readonly string[]\n /** Text of every failure-marked element (including hidden details). */\n readonly failureNodes: readonly string[]\n /** Retry controls inside the transcript region. */\n readonly retryButtons: number\n /**\n * The fields above hold only what follows the turn's own prompt. Everything\n * after the prompt is the turn's, so no earlier floor applies to it.\n */\n readonly anchored?: boolean\n}\n\nexport interface FailurePatterns {\n /** A line matching one of these is failure evidence. */\n readonly failure: readonly RegExp[]\n /** A line matching one of these means the person stopped the turn. */\n readonly stopped: readonly RegExp[]\n}\n\n/**\n * Failure text any agent app can show: typed failure codes, provider errors and\n * this package's own sandbox-stream copy. An app adds its own card copy through\n * `chat.failureText` in its journeys config.\n *\n * Matched as substrings of whole lines. A reply that QUOTES one of these fails\n * the turn too; that direction is deliberate, because missing a failure passes a\n * broken product while over-matching only costs a rerun.\n */\nexport const DEFAULT_FAILURE_TEXT: readonly RegExp[] = [\n /\\b[a-z]+(?:_[a-z]+)*\\.[a-z]+(?:_[a-z]+)*_(?:failed|unavailable|timeout)\\b/,\n /\\bAPIError \\d{3}\\b/,\n /stopped before a clean completion/i,\n /Failed to connect to Sandbox API/i,\n /\\bbilling\\.balance_required\\b|Add balance or upgrade your plan/i,\n /Internal Server Error/,\n /\\bECONNREFUSED\\b/,\n /Something went wrong/i,\n // agent-app's own sandbox failure copy (`formatSandboxProvisioningUserMessage`),\n // which every app on the shared runtime can render as a reply. Tests drive the\n // formatter's every branch through these, so the copy and the scorer cannot drift.\n /unable to (?:re)?connect to the sandbox/i,\n /sandbox service didn.t answer/i,\n /Sandbox recovery is required before chat can continue/i,\n /couldn.t (?:finish copying|copy) your Vault into the sandbox/i,\n /too large (?:for the sandbox to accept|to copy into the sandbox)/i,\n /attachment data is staged in the sandbox/i,\n]\n\n/** Runtime wording for a turn the person stopped. Apps add their own copy. */\nexport const DEFAULT_STOPPED_TEXT: readonly RegExp[] = [\n /interrupted by the user/i,\n /cancell?ed by (?:the )?user/i,\n /stopped by (?:the )?user/i,\n]\n\nfunction normalize(line: string): string {\n return line.replace(/\\s+/g, ' ').trim()\n}\n\n/** Every keyed item of a snapshot that can count as failure evidence. */\nfunction evidenceKeys(snapshot: TranscriptSnapshot, patterns: FailurePatterns, ignore: ReadonlySet<string>): Map<string, number> {\n const counts = new Map<string, number>()\n const add = (key: string) => counts.set(key, (counts.get(key) ?? 0) + 1)\n for (const raw of snapshot.lines) {\n const line = normalize(raw)\n if (!line || ignore.has(line)) continue\n if (patterns.stopped.some((p) => p.test(line))) add(`stopped:${line}`)\n else if (patterns.failure.some((p) => p.test(line))) add(`text:${line}`)\n }\n for (const raw of snapshot.failureNodes) {\n const text = normalize(raw)\n if (text && !ignore.has(text)) add(`node:${text.slice(0, 300)}`)\n }\n for (let i = 0; i < snapshot.retryButtons; i += 1) add('retry')\n return counts\n}\n\n/**\n * Failure evidence that appeared after the turn was sent.\n *\n * `begin` takes the snapshot from just before Send. Every later `observe`\n * lowers each item's floor to the fewest copies seen so far: when Retry removes\n * the old card and a new failure renders the same words, the count dips to zero\n * and climbs back to one, and that one is new. Anything that rose above its\n * floor at any point counts, even if the page later replaced it: on 2026-10-11\n * GTM showed \"The sandbox model stream stopped before a clean completion …\n * Hub credential source is revoked or expired\" five minutes into a turn, then\n * swapped it for a different card six minutes later.\n */\nexport class TurnEvidence {\n private floor = new Map<string, number>()\n private peak = new Map<string, number>()\n private anchored = false\n private readonly ignore: Set<string>\n\n constructor(private readonly patterns: FailurePatterns, prompt: string) {\n // The person's own prompt is on the page too; a prompt that mentions an\n // error must not fail its own turn.\n this.ignore = new Set(prompt.split('\\n').map(normalize).filter(Boolean))\n this.ignore.add(normalize(prompt))\n }\n\n begin(snapshot: TranscriptSnapshot): void {\n this.floor = evidenceKeys(snapshot, this.patterns, this.ignore)\n this.peak = new Map()\n this.anchored = snapshot.anchored === true\n }\n\n /** Read one snapshot. Returns the evidence that appeared for the first time, as display text. */\n observe(snapshot: TranscriptSnapshot): string[] {\n if (snapshot.anchored && !this.anchored) {\n // The first read that shows this turn's prompt: a floor taken from the whole transcript no longer applies.\n this.floor = new Map()\n this.anchored = true\n }\n const now = evidenceKeys(snapshot, this.patterns, this.ignore)\n for (const [key, floor] of this.floor) {\n const count = now.get(key) ?? 0\n if (count < floor) this.floor.set(key, count)\n }\n const fresh: string[] = []\n for (const [key, count] of now) {\n const extra = count - (this.floor.get(key) ?? 0)\n if (extra <= (this.peak.get(key) ?? 0)) continue\n if (!this.peak.has(key)) fresh.push(display(key))\n this.peak.set(key, extra)\n }\n return fresh\n }\n\n /** Everything that rose above its floor during the turn, in the order it appeared. */\n added(): { failures: string[]; stopped: string[]; retryAppeared: boolean } {\n const failures: string[] = []\n const stopped: string[] = []\n let retryAppeared = false\n for (const key of this.peak.keys()) {\n if (key === 'retry') retryAppeared = true\n else if (key.startsWith('stopped:')) stopped.push(key.slice('stopped:'.length))\n else failures.push(key.slice(key.indexOf(':') + 1))\n }\n return { failures, stopped, retryAppeared }\n }\n}\n\nfunction display(key: string): string {\n return key === 'retry' ? 'a Retry control appeared in the transcript' : key.slice(key.indexOf(':') + 1)\n}\n\n/**\n * Whether a turn is still going, from what the page shows. A status line is\n * progress while it changes; one left unchanged for {@link STATUS_STALE_MS}\n * with no Stop control is a notice left behind (GTM's \"Request was\n * interrupted by the user. Send a new message to continue.\" is a lasting\n * `role=\"status\"`), and treating it as progress held a stopped turn open until\n * its 15-minute timeout.\n */\nexport const STATUS_STALE_MS = 20_000\n\nexport function turnLooksActive(page: { stopVisible: boolean; statusLines: number; msSinceStatusChanged: number }): boolean {\n return page.stopVisible || (page.statusLines > 0 && page.msSinceStatusChanged < STATUS_STALE_MS)\n}\n\nexport type TurnOutcome = 'completed' | 'failed' | 'stopped' | 'empty' | 'timeout' | 'not-sent'\n\nexport interface TurnVerdict {\n outcome: TurnOutcome\n /** Plain words for a caption: the first failure line, or why the turn is not a pass. */\n error: string | null\n /** Every piece of failure evidence the turn added, for the report. */\n failures: string[]\n}\n\nexport interface TurnFacts {\n /** The send never reached the app. */\n readonly notSent?: string\n /** The app still listed the turn as running when the wait ran out. */\n readonly timedOut: boolean\n readonly evidence: ReturnType<TurnEvidence['added']>\n /** New reply characters this turn added. */\n readonly replyChars: number\n /** The journey pressed Stop during this turn. */\n readonly stopPressed: boolean\n}\n\n/** The one place a turn's outcome is decided. Order matters: evidence first. */\nexport function scoreTurn(facts: TurnFacts): TurnVerdict {\n if (facts.notSent) return { outcome: 'not-sent', error: facts.notSent, failures: [] }\n const { failures, stopped, retryAppeared } = facts.evidence\n const all = [...stopped, ...failures, ...(retryAppeared ? ['a Retry control appeared in the transcript'] : [])]\n // A Stop that took effect. One that did not (still running at the deadline)\n // falls through to `timeout`, because Stop failing is itself the defect.\n if (stopped.length || (facts.stopPressed && !facts.timedOut)) {\n return { outcome: 'stopped', error: stopped[0] ?? failures[0] ?? 'stopped by the journey', failures: all }\n }\n if (failures.length || retryAppeared) {\n return { outcome: 'failed', error: failures[0] ?? 'a Retry control appeared in the transcript', failures: all }\n }\n if (facts.timedOut) return { outcome: 'timeout', error: 'the turn was still running when the wait ended', failures: all }\n if (facts.replyChars === 0) return { outcome: 'empty', error: 'the turn ended without any reply text', failures: all }\n return { outcome: 'completed', error: null, failures: [] }\n}\n","/**\n * What an app tells the journeys kit about itself: where it is served, which\n * test identities may sign in, and the chat DOM a turn is measured on.\n *\n * It lives at the app root as `journeys.config.mjs`, beside\n * `launch-invariants.config.mjs`:\n *\n * import { defineJourneys } from '@tangle-network/agent-app/journeys'\n * export default defineJourneys({\n * app: 'gtm',\n * baseUrl: 'https://gtm.tangle.tools',\n * identities: {\n * member: { emailEnv: 'SMOKE_EMAIL', passwordEnv: 'SMOKE_PASSWORD', signIn: 'tangle' },\n * },\n * chat: { assistant: '.gtm-assistant-markdown', failureText: [/stopped before finishing/i] },\n * })\n *\n * Credentials are named, never stored: the config holds environment variable\n * names, and the values reach the process from the host's vault.\n */\nimport { existsSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { DEFAULT_FAILURE_TEXT, DEFAULT_STOPPED_TEXT } from './score.js'\n\nexport type SignInMethod = 'password' | 'tangle'\n\nexport interface JourneyIdentity {\n /** Environment variable that holds the account's email. */\n readonly emailEnv: string\n /** Environment variable that holds the account's password. */\n readonly passwordEnv: string\n /**\n * `password`: the app's own email sign-in (better-auth `sign-in/email`).\n * `tangle`: \"Log in with Tangle\": the app's SSO start, the Platform's email\n * sign-in, then the app's callback.\n */\n readonly signIn: SignInMethod\n}\n\n/** The ids a thread URL carries. */\nexport interface ThreadRoute {\n readonly threadId: string\n readonly workspaceId?: string\n}\n\n/**\n * The chat DOM a turn is read from. Defaults are agent-app's own components:\n * `ChatComposer` (the composer card, \"Message input\", \"Send\", \"Stop response\")\n * and the transcript's failure rows (`role=\"alert\"`, `data-notice-tone=\"error\"`).\n */\nexport interface ChatContract {\n /** Region whose text decides a turn's outcome. */\n readonly transcript: string\n /** Assistant reply blocks. `null` measures reply text as transcript growth beyond the prompt. */\n readonly assistant: string | null\n /** Progress lines inside the transcript (\"Sending…\", \"Searching the web\"). */\n readonly status: string\n /** Elements that mark a failed turn. */\n readonly failureNodes: string\n /** Failure lines this app shows in plain text, added to the package defaults. */\n readonly failureText: readonly RegExp[]\n /** Lines meaning the person stopped the turn, added to the package defaults. */\n readonly stoppedText: readonly RegExp[]\n /** The card holding the composer's input and action row. */\n readonly composer: string\n /** Accessible names inside the composer card. */\n readonly inputName: string\n readonly sendName: string\n readonly stopName: string\n /** Accessible name of a failed turn's retry control. */\n readonly retryName: RegExp\n /** A created thread's path. Named groups `threadId` (required) and `workspaceId`. */\n readonly threadPath: RegExp | null\n /** Path that lists a thread's running turns as JSON `{ running: string[] }`; the server's word on completion. */\n readonly runningTurns: ((route: ThreadRoute) => string) | null\n /** POST paths that mean the composer submitted, besides the page's own route. */\n readonly sendPaths: readonly RegExp[]\n}\n\nexport interface AuthPaths {\n readonly session: string\n readonly passwordSignIn: string\n readonly tangleStart: string\n}\n\nexport interface JourneysConfig {\n /** Short name, used for state and output folders. */\n readonly app: string\n /** Origin the journeys drive. `JOURNEYS_BASE_URL` overrides it, for a local stack. */\n readonly baseUrl: string\n readonly identities: Readonly<Record<string, JourneyIdentity>>\n readonly chat?: Partial<ChatContract>\n readonly auth?: Partial<AuthPaths>\n /** Chat turns one journey may send. Default 6. */\n readonly maxTurns?: number\n /** Sessions and raw recordings. Default `~/.local/state/agent-app-journeys/<app>`. */\n readonly stateDir?: string\n /** Files safe to copy off the host. Default `<stateDir>/out`. */\n readonly outDir?: string\n}\n\nexport interface ResolvedJourneysConfig {\n /** Marks a config whose defaults are filled; resolving it again returns it unchanged. */\n readonly resolved: true\n readonly app: string\n readonly baseUrl: string\n readonly identities: Readonly<Record<string, JourneyIdentity>>\n readonly chat: ChatContract\n readonly auth: AuthPaths\n readonly maxTurns: number\n readonly stateDir: string\n readonly outDir: string\n}\n\nexport const DEFAULT_CHAT_CONTRACT: ChatContract = {\n transcript: 'main',\n assistant: null,\n status: '[role=\"status\"]',\n failureNodes: '[role=\"alert\"], [data-notice-tone=\"error\"]',\n failureText: [],\n stoppedText: [],\n composer: '[data-testid=\"composer-card\"]',\n inputName: 'Message input',\n sendName: 'Send',\n stopName: 'Stop response',\n retryName: /^Retry$/,\n threadPath: null,\n runningTurns: null,\n sendPaths: [/^\\/api\\/(?:[^/]+\\/)*chat$/],\n}\n\nexport const DEFAULT_AUTH_PATHS: AuthPaths = {\n session: '/api/auth/get-session',\n passwordSignIn: '/api/auth/sign-in/email',\n tangleStart: '/auth/tangle/start',\n}\n\nexport const CONFIG_FILE_NAMES = ['journeys.config.mjs', 'journeys.config.js'] as const\n\n/** Identity for a typed config; also validates it. */\nexport function defineJourneys(config: JourneysConfig): JourneysConfig {\n resolveJourneysConfig(config)\n return config\n}\n\nconst ENV_NAME = /^[A-Z_][A-Z0-9_]*$/\n\n/** Fill defaults and refuse a config that cannot drive a journey. */\nexport function resolveJourneysConfig(config: JourneysConfig | ResolvedJourneysConfig, env: Record<string, string | undefined> = process.env): ResolvedJourneysConfig {\n if ('resolved' in config && config.resolved === true) return config\n const problems: string[] = []\n if (!/^[a-z0-9][a-z0-9-]{0,40}$/.test(config.app ?? '')) problems.push('app must be a short lowercase name such as \"gtm\"')\n const base = (env.JOURNEYS_BASE_URL ?? config.baseUrl ?? '').replace(/\\/$/, '')\n if (!/^https?:\\/\\/[^/]+$/.test(base)) problems.push(`baseUrl must be an origin such as https://app.example.com, got \"${base}\"`)\n const identities = config.identities ?? {}\n if (Object.keys(identities).length === 0) problems.push('identities must name at least one test identity')\n for (const [name, identity] of Object.entries(identities)) {\n if (name === 'anon') problems.push('\"anon\" is reserved for a signed-out context')\n if (!/^[a-z][a-z0-9-]*$/.test(name)) problems.push(`identity \"${name}\": use a lowercase name`)\n for (const key of ['emailEnv', 'passwordEnv'] as const) {\n if (!ENV_NAME.test(identity[key] ?? '')) problems.push(`identity \"${name}\": ${key} must be an environment variable NAME, not a value`)\n }\n if (identity.signIn !== 'password' && identity.signIn !== 'tangle') problems.push(`identity \"${name}\": signIn must be \"password\" or \"tangle\"`)\n }\n const chat: ChatContract = {\n ...DEFAULT_CHAT_CONTRACT,\n ...config.chat,\n failureText: [...DEFAULT_FAILURE_TEXT, ...(config.chat?.failureText ?? [])],\n stoppedText: [...DEFAULT_STOPPED_TEXT, ...(config.chat?.stoppedText ?? [])],\n }\n if (chat.threadPath && !/\\(\\?<threadId>/.test(chat.threadPath.source)) problems.push('chat.threadPath needs a named group (?<threadId>…)')\n const maxTurns = config.maxTurns ?? 6\n if (!Number.isInteger(maxTurns) || maxTurns < 0) problems.push('maxTurns must be a whole number')\n if (problems.length) throw new Error(`journeys config: ${problems.join('; ')}`)\n const stateDir = resolve(env.JOURNEYS_STATE_DIR ?? config.stateDir ?? join(homedir(), '.local/state/agent-app-journeys', config.app))\n return {\n resolved: true,\n app: config.app,\n baseUrl: base,\n identities,\n chat,\n auth: { ...DEFAULT_AUTH_PATHS, ...config.auth },\n maxTurns,\n stateDir,\n outDir: resolve(env.JOURNEYS_OUT ?? config.outDir ?? join(stateDir, 'out')),\n }\n}\n\n/** The ids in a thread URL, or null when the URL is not a thread on this origin. */\nexport function threadRouteIn(url: string, config: Pick<ResolvedJourneysConfig, 'baseUrl' | 'chat'>): ThreadRoute | null {\n if (!config.chat.threadPath) return null\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n return null\n }\n if (parsed.origin !== new URL(config.baseUrl).origin) return null\n const match = config.chat.threadPath.exec(parsed.pathname)\n const threadId = match?.groups?.threadId\n if (!threadId) return null\n const workspaceId = match?.groups?.workspaceId\n return workspaceId ? { threadId, workspaceId } : { threadId }\n}\n\n/** Environment variable names the config needs, for a vault loader. */\nexport function credentialNames(config: Pick<JourneysConfig, 'identities'>): string[] {\n return [...new Set(Object.values(config.identities).flatMap((identity) => [identity.emailEnv, identity.passwordEnv]))]\n}\n\n/** `JOURNEYS_CONFIG`, else the first config file in `dir`. */\nexport async function loadJourneysConfig(dir = process.cwd(), env: Record<string, string | undefined> = process.env): Promise<ResolvedJourneysConfig> {\n const file = env.JOURNEYS_CONFIG\n ? resolve(dir, env.JOURNEYS_CONFIG)\n : CONFIG_FILE_NAMES.map((name) => join(dir, name)).find((path) => existsSync(path))\n if (!file || !existsSync(file)) {\n throw new Error(`no ${CONFIG_FILE_NAMES[0]} in ${dir}; add one at the app root or set JOURNEYS_CONFIG`)\n }\n const loaded = (await import(pathToFileURL(file).href)) as { default?: JourneysConfig }\n if (!loaded.default) throw new Error(`${file} must export default defineJourneys({ … })`)\n return resolveJourneysConfig(loaded.default, env)\n}\n","/**\n * Making a journey's files safe to copy off the host.\n *\n * `scrubTrace` rewrites a Playwright trace.zip: it blanks cookie and\n * authorization headers and HAR cookie lists, blanks token-like query values,\n * drops the bodies of auth, token, session and collaboration calls, and then\n * replaces every needle (passwords, cookie values, the identities' emails)\n * anywhere in any entry. `assertNoSecrets` re-reads every output file, inside\n * the zips too, and refuses the whole folder if a password or cookie value\n * survived anywhere.\n */\nimport { readdirSync, readFileSync, statSync, openSync, closeSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { createZipWriter, inflateEntry, readCentralDirectory, readRaw } from './trace-zip.js'\n\nconst SENSITIVE_HEADERS = new Set([\n 'cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key',\n 'x-auth-token', 'x-stream-token', 'cf-access-token', 'x-csrf-token',\n])\nconst SENSITIVE_PATH = /\\/api\\/auth\\/|\\/auth\\/tangle\\/|token|session|\\/api\\/collaboration\\/|oauth|\\/consent|\\/api-access|api-key/i\nconst QUERY_NAMES = 'token|access_token|refresh_token|id_token|code|state|key|api_key|apikey|signature|sig|jwt|ticket|secret'\nconst QUERY = new RegExp(`([?&](?:${QUERY_NAMES})=)[^&\"'\\\\s\\\\\\\\]+`, 'gi')\nconst QUERY_NAME = new RegExp(`^(?:${QUERY_NAMES})$`, 'i')\nconst REDACTED = 'REDACTED'\n\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json }\ntype JsonObject = { [key: string]: Json }\n\nconst isObject = (v: Json | undefined): v is JsonObject => typeof v === 'object' && v !== null && !Array.isArray(v)\n\nfunction scrubHeaders(headers: Json | undefined): void {\n if (Array.isArray(headers)) {\n for (const h of headers) {\n if (isObject(h) && SENSITIVE_HEADERS.has(String(h.name ?? '').toLowerCase())) h.value = REDACTED\n }\n } else if (isObject(headers)) {\n for (const key of Object.keys(headers)) if (SENSITIVE_HEADERS.has(key.toLowerCase())) headers[key] = REDACTED\n }\n}\n\n/** Drop an inline or stored body; Playwright points at stored ones with `_file` or `_sha1`. */\nfunction forgetBody(holder: JsonObject, drop: Set<string>): void {\n for (const key of ['_file', '_sha1']) {\n const ref = holder[key]\n if (ref) {\n drop.add(String(ref).split('/').pop() ?? '')\n holder[key] = null\n }\n }\n if ('text' in holder) holder.text = REDACTED\n}\n\n/** Scrub any HAR-like request/response anywhere in one trace event. */\nfunction walk(node: Json | undefined, drop: Set<string>): void {\n if (Array.isArray(node)) {\n for (const v of node) walk(v, drop)\n return\n }\n if (!isObject(node)) return\n const req = node.request\n const res = node.response\n if (isObject(req) && 'url' in req) {\n const sensitive = SENSITIVE_PATH.test(String(req.url ?? '').split('?')[0] ?? '')\n scrubHeaders(req.headers)\n if ('cookies' in req) req.cookies = []\n const query = req.queryString\n if (Array.isArray(query)) {\n for (const q of query) if (isObject(q) && QUERY_NAME.test(String(q.name ?? ''))) q.value = REDACTED\n }\n if (sensitive && isObject(req.postData)) forgetBody(req.postData, drop)\n if (isObject(res)) {\n scrubHeaders(res.headers)\n if ('cookies' in res) res.cookies = []\n if (sensitive && isObject(res.content)) forgetBody(res.content, drop)\n }\n }\n for (const [key, value] of Object.entries(node)) {\n if (key.toLowerCase() === 'cookies' && Array.isArray(value)) node[key] = []\n else if (key === 'storageState') node[key] = null\n else if (SENSITIVE_HEADERS.has(key.toLowerCase()) && typeof value === 'string') node[key] = REDACTED\n else walk(value, drop)\n }\n}\n\n/** One `.trace` or `.network` JSONL entry, scrubbed. Bodies it dropped are added to `drop`. */\nexport function scrubJsonl(text: string, drop: Set<string>): string {\n const out: string[] = []\n for (const line of text.split('\\n')) {\n if (!line.trim()) continue\n let event: Json\n try {\n event = JSON.parse(line) as Json\n } catch {\n out.push(line.replace(QUERY, `$1${REDACTED}`))\n continue\n }\n walk(event, drop)\n out.push(JSON.stringify(event).replace(QUERY, `$1${REDACTED}`))\n }\n return out.join('\\n') + '\\n'\n}\n\n/** Every occurrence of every needle replaced. */\nexport function replaceNeedles(data: Buffer, needles: readonly string[]): Buffer {\n let out = data\n for (const needle of needles) {\n if (!needle) continue\n const n = Buffer.from(needle, 'utf8')\n if (out.indexOf(n) < 0) continue\n const parts: Buffer[] = []\n let from = 0\n for (let at = out.indexOf(n); at >= 0; at = out.indexOf(n, from)) {\n parts.push(out.subarray(from, at), Buffer.from(REDACTED))\n from = at + n.length\n }\n parts.push(out.subarray(from))\n out = Buffer.concat(parts)\n }\n return out\n}\n\nconst isEvents = (name: string) => name.endsWith('.trace') || name.endsWith('.network')\n\n/** Write a scrubbed copy of `src` to `dst`. Entries keep their order; dropped bodies are left out. */\nexport function scrubTrace(src: string, dst: string, needles: readonly string[]): { entries: number; dropped: number; rewritten: number } {\n const fd = openSync(src, 'r')\n try {\n const entries = readCentralDirectory(fd)\n const drop = new Set<string>()\n // Events first, so the bodies they point at are known before resources are copied.\n const events = new Map<string, Buffer>()\n for (const entry of entries) {\n if (!isEvents(entry.name)) continue\n events.set(entry.name, Buffer.from(scrubJsonl(inflateEntry(entry, readRaw(fd, entry)).toString('utf8'), drop), 'utf8'))\n }\n const writer = createZipWriter(dst)\n let dropped = 0\n let rewritten = 0\n for (const entry of entries) {\n const base = entry.name.split('/').pop() ?? ''\n if (entry.name.startsWith('resources/') && drop.has(base)) {\n dropped += 1\n continue\n }\n const raw = readRaw(fd, entry)\n const content = events.get(entry.name) ?? inflateEntry(entry, raw)\n const clean = replaceNeedles(content, needles)\n if (!events.has(entry.name) && clean === content) {\n writer.copy(entry, raw)\n } else {\n writer.add(entry.name, clean, entry)\n rewritten += 1\n }\n }\n writer.close()\n return { entries: entries.length, dropped, rewritten }\n } finally {\n closeSync(fd)\n }\n}\n\n/** Entries of a zip that still hold a hard needle, and how many mention a soft one. */\nfunction scanZip(path: string, hard: readonly string[], soft: readonly string[]): { hard: string[]; soft: number } {\n const fd = openSync(path, 'r')\n try {\n const hits: string[] = []\n let softHits = 0\n const hardBytes = hard.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n const softBytes = soft.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n for (const entry of readCentralDirectory(fd)) {\n const content = inflateEntry(entry, readRaw(fd, entry))\n if (hardBytes.some((n) => content.includes(n))) hits.push(entry.name)\n if (softBytes.some((n) => content.includes(n))) softHits += 1\n }\n return { hard: hits, soft: softHits }\n } finally {\n closeSync(fd)\n }\n}\n\n/**\n * Refuse to hand over a folder whose files hold a password or cookie value.\n * An identity's email only warns: it is a company test address, not a secret,\n * but it should be blurred before footage is shown outside the company.\n */\nexport function assertNoSecrets(dir: string, needles: { hard: readonly string[]; soft: readonly string[] }): { softHits: string[] } {\n const hits: string[] = []\n const softHits: string[] = []\n const hard = needles.hard.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n const soft = needles.soft.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n const visit = (d: string) => {\n for (const name of readdirSync(d)) {\n const path = join(d, name)\n if (statSync(path).isDirectory()) {\n visit(path)\n continue\n }\n if (path.endsWith('.zip')) {\n const found = scanZip(path, needles.hard, needles.soft)\n if (found.hard.length) hits.push(`${path} (${found.hard.slice(0, 5).join(', ')})`)\n if (found.soft) softHits.push(`${path} (${found.soft} entries)`)\n continue\n }\n const buf = readFileSync(path)\n if (hard.some((n) => buf.includes(n))) hits.push(path)\n if (soft.some((n) => buf.includes(n))) softHits.push(path)\n }\n }\n visit(dir)\n if (softHits.length) console.warn(`note: a test identity's email appears in ${softHits.join(', ')}; blur it before sharing outside the company`)\n if (hits.length) throw new Error(`REFUSING: secret material found in ${hits.join(', ')}; do not copy ${dir}`)\n return { softHits }\n}\n","/**\n * The slice of PKZIP a Playwright trace needs: read every entry of an archive\n * on disk one at a time, and write a new archive entry by entry.\n *\n * Why not `documents/zip`: that reader holds the archive in memory and refuses\n * zip64, and a recorded hour-long journey's trace is 6.6 GB with 49,117\n * entries, so offsets pass 4 GiB. This reader keeps\n * one entry in memory at a time and reads the zip64 records; the writer emits\n * zip64 fields only when a size, an offset or the entry count needs them.\n */\nimport { closeSync, fstatSync, openSync, readSync, writeSync } from 'node:fs'\nimport { deflateRawSync, inflateRawSync } from 'node:zlib'\nimport { crc32Update } from '../workspace-export/checksum.js'\n\nconst EOCD = 0x06054b50\nconst ZIP64_EOCD = 0x06064b50\nconst ZIP64_LOCATOR = 0x07064b50\nconst CENTRAL = 0x02014b50\nconst LOCAL = 0x04034b50\nconst U16 = 0xffff\nconst U32 = 0xffffffff\n\ninterface ZipEntryInfo {\n readonly name: string\n readonly method: number\n readonly crc32: number\n readonly compressedSize: number\n readonly uncompressedSize: number\n readonly localOffset: number\n readonly dosTime: number\n readonly dosDate: number\n}\n\nfunction readAt(fd: number, position: number, length: number): Buffer {\n const out = Buffer.alloc(length)\n let done = 0\n while (done < length) {\n const n = readSync(fd, out, done, length - done, position + done)\n if (n === 0) throw new Error(`zip: unexpected end of file at ${position + done}`)\n done += n\n }\n return out\n}\n\nconst u64 = (b: Buffer, at: number) => Number(b.readBigUInt64LE(at))\n\n/** Every entry in the central directory, sizes and offsets resolved through zip64 extras. */\nexport function readCentralDirectory(fd: number): ZipEntryInfo[] {\n const size = fstatSync(fd).size\n const tailLength = Math.min(size, 22 + U16 + 20)\n const tail = readAt(fd, size - tailLength, tailLength)\n let eocd = -1\n for (let i = tail.length - 22; i >= 0; i -= 1) {\n if (tail.readUInt32LE(i) === EOCD && i + 22 + tail.readUInt16LE(i + 20) === tail.length) {\n eocd = i\n break\n }\n }\n if (eocd < 0) throw new Error('zip: no end-of-central-directory record')\n let count = tail.readUInt16LE(eocd + 10)\n let cdSize = tail.readUInt32LE(eocd + 12)\n let cdOffset = tail.readUInt32LE(eocd + 16)\n if (eocd >= 20 && tail.readUInt32LE(eocd - 20) === ZIP64_LOCATOR) {\n const record = readAt(fd, u64(tail, eocd - 20 + 8), 56)\n if (record.readUInt32LE(0) !== ZIP64_EOCD) throw new Error('zip: zip64 locator points at no zip64 record')\n count = u64(record, 32)\n cdSize = u64(record, 40)\n cdOffset = u64(record, 48)\n }\n const cd = readAt(fd, cdOffset, cdSize)\n const entries: ZipEntryInfo[] = []\n let at = 0\n for (let i = 0; i < count; i += 1) {\n if (cd.readUInt32LE(at) !== CENTRAL) throw new Error(`zip: central directory is broken at entry ${i + 1} of ${count}`)\n const nameLength = cd.readUInt16LE(at + 28)\n const extraLength = cd.readUInt16LE(at + 30)\n const commentLength = cd.readUInt16LE(at + 32)\n let compressedSize = cd.readUInt32LE(at + 20)\n let uncompressedSize = cd.readUInt32LE(at + 24)\n let localOffset = cd.readUInt32LE(at + 42)\n const extra = cd.subarray(at + 46 + nameLength, at + 46 + nameLength + extraLength)\n for (let e = 0; e + 4 <= extra.length; ) {\n const id = extra.readUInt16LE(e)\n const len = extra.readUInt16LE(e + 2)\n if (id === 0x0001) {\n // Present in this order, and only for the fields set to 0xffffffff.\n let p = e + 4\n if (uncompressedSize === U32) { uncompressedSize = u64(extra, p); p += 8 }\n if (compressedSize === U32) { compressedSize = u64(extra, p); p += 8 }\n if (localOffset === U32) { localOffset = u64(extra, p); p += 8 }\n }\n e += 4 + len\n }\n entries.push({\n name: cd.toString('utf8', at + 46, at + 46 + nameLength),\n method: cd.readUInt16LE(at + 10),\n crc32: cd.readUInt32LE(at + 16),\n compressedSize,\n uncompressedSize,\n localOffset,\n dosTime: cd.readUInt16LE(at + 12),\n dosDate: cd.readUInt16LE(at + 14),\n })\n at += 46 + nameLength + extraLength + commentLength\n }\n return entries\n}\n\n/** One entry's stored bytes, still compressed. */\nexport function readRaw(fd: number, entry: ZipEntryInfo): Buffer {\n const local = readAt(fd, entry.localOffset, 30)\n if (local.readUInt32LE(0) !== LOCAL) throw new Error(`zip: '${entry.name}' has no local header`)\n const start = entry.localOffset + 30 + local.readUInt16LE(26) + local.readUInt16LE(28)\n return readAt(fd, start, entry.compressedSize)\n}\n\n/** One entry's content. */\nexport function inflateEntry(entry: ZipEntryInfo, raw: Buffer): Buffer {\n if (entry.method === 0) return raw\n if (entry.method === 8) return inflateRawSync(raw)\n throw new Error(`zip: '${entry.name}' uses unsupported compression method ${entry.method}`)\n}\n\ninterface ZipWriter {\n /** Add an entry from its content (deflated here). */\n add(name: string, content: Buffer, from?: Pick<ZipEntryInfo, 'dosTime' | 'dosDate'>): void\n /** Add an entry exactly as another archive stored it. */\n copy(entry: ZipEntryInfo, raw: Buffer): void\n close(): void\n}\n\ninterface Written {\n name: Buffer\n method: number\n crc32: number\n compressedSize: number\n uncompressedSize: number\n offset: number\n dosTime: number\n dosDate: number\n}\n\n/** Write a zip to `path`, entries in the order added. `forceZip64` exercises the large-archive records in tests. */\nexport function createZipWriter(path: string, opts: { forceZip64?: boolean } = {}): ZipWriter {\n const fd = openSync(path, 'w', 0o600)\n let position = 0\n const written: Written[] = []\n const put = (b: Buffer) => {\n let done = 0\n while (done < b.length) done += writeSync(fd, b, done, b.length - done)\n position += b.length\n }\n const big = (n: number) => opts.forceZip64 === true || n >= U32\n const writeEntry = (w: Omit<Written, 'offset'>, data: Buffer) => {\n const zip64 = big(w.compressedSize) || big(w.uncompressedSize)\n const header = Buffer.alloc(30 + w.name.length + (zip64 ? 20 : 0))\n header.writeUInt32LE(LOCAL, 0)\n header.writeUInt16LE(zip64 ? 45 : 20, 4)\n header.writeUInt16LE(0x0800, 6)\n header.writeUInt16LE(w.method, 8)\n header.writeUInt16LE(w.dosTime, 10)\n header.writeUInt16LE(w.dosDate, 12)\n header.writeUInt32LE(w.crc32, 14)\n header.writeUInt32LE(zip64 ? U32 : w.compressedSize, 18)\n header.writeUInt32LE(zip64 ? U32 : w.uncompressedSize, 22)\n header.writeUInt16LE(w.name.length, 26)\n header.writeUInt16LE(zip64 ? 20 : 0, 28)\n w.name.copy(header, 30)\n if (zip64) {\n const e = 30 + w.name.length\n header.writeUInt16LE(0x0001, e)\n header.writeUInt16LE(16, e + 2)\n header.writeBigUInt64LE(BigInt(w.uncompressedSize), e + 4)\n header.writeBigUInt64LE(BigInt(w.compressedSize), e + 12)\n }\n const offset = position\n put(header)\n put(data)\n written.push({ ...w, offset })\n }\n return {\n add(name, content, from) {\n const data = deflateRawSync(content)\n writeEntry({\n name: Buffer.from(name, 'utf8'),\n method: 8,\n crc32: crc32Update(0, content),\n compressedSize: data.length,\n uncompressedSize: content.length,\n dosTime: from?.dosTime ?? 0,\n dosDate: from?.dosDate ?? 0x21,\n }, data)\n },\n copy(entry, raw) {\n writeEntry({\n name: Buffer.from(entry.name, 'utf8'),\n method: entry.method,\n crc32: entry.crc32,\n compressedSize: entry.compressedSize,\n uncompressedSize: entry.uncompressedSize,\n dosTime: entry.dosTime,\n dosDate: entry.dosDate,\n }, raw)\n },\n close() {\n const cdOffset = position\n for (const w of written) {\n const fields: bigint[] = []\n if (big(w.uncompressedSize)) fields.push(BigInt(w.uncompressedSize))\n if (big(w.compressedSize)) fields.push(BigInt(w.compressedSize))\n if (big(w.offset)) fields.push(BigInt(w.offset))\n const extraLength = fields.length ? 4 + 8 * fields.length : 0\n const h = Buffer.alloc(46 + w.name.length + extraLength)\n h.writeUInt32LE(CENTRAL, 0)\n h.writeUInt16LE(45, 4)\n h.writeUInt16LE(fields.length ? 45 : 20, 6)\n h.writeUInt16LE(0x0800, 8)\n h.writeUInt16LE(w.method, 10)\n h.writeUInt16LE(w.dosTime, 12)\n h.writeUInt16LE(w.dosDate, 14)\n h.writeUInt32LE(w.crc32, 16)\n h.writeUInt32LE(big(w.compressedSize) ? U32 : w.compressedSize, 20)\n h.writeUInt32LE(big(w.uncompressedSize) ? U32 : w.uncompressedSize, 24)\n h.writeUInt16LE(w.name.length, 28)\n h.writeUInt16LE(extraLength, 30)\n h.writeUInt32LE(big(w.offset) ? U32 : w.offset, 42)\n w.name.copy(h, 46)\n if (fields.length) {\n const e = 46 + w.name.length\n h.writeUInt16LE(0x0001, e)\n h.writeUInt16LE(8 * fields.length, e + 2)\n fields.forEach((v, i) => h.writeBigUInt64LE(v, e + 4 + 8 * i))\n }\n put(h)\n }\n const cdSize = position - cdOffset\n const count = written.length\n const zip64 = opts.forceZip64 === true || count >= U16 || cdOffset >= U32 || cdSize >= U32\n if (zip64) {\n const recordOffset = position\n const r = Buffer.alloc(56)\n r.writeUInt32LE(ZIP64_EOCD, 0)\n r.writeBigUInt64LE(44n, 4)\n r.writeUInt16LE(45, 12)\n r.writeUInt16LE(45, 14)\n r.writeBigUInt64LE(BigInt(count), 24)\n r.writeBigUInt64LE(BigInt(count), 32)\n r.writeBigUInt64LE(BigInt(cdSize), 40)\n r.writeBigUInt64LE(BigInt(cdOffset), 48)\n put(r)\n const l = Buffer.alloc(20)\n l.writeUInt32LE(ZIP64_LOCATOR, 0)\n l.writeBigUInt64LE(BigInt(recordOffset), 8)\n l.writeUInt32LE(1, 16)\n put(l)\n }\n const end = Buffer.alloc(22)\n end.writeUInt32LE(EOCD, 0)\n end.writeUInt16LE(zip64 ? U16 : count, 8)\n end.writeUInt16LE(zip64 ? U16 : count, 10)\n end.writeUInt32LE(zip64 ? U32 : cdSize, 12)\n end.writeUInt32LE(zip64 ? U32 : cdOffset, 16)\n put(end)\n closeSync(fd)\n },\n }\n}\n","/**\n * Signed-in browser state for an app's test identities, with no login form in\n * any recorded frame.\n *\n * Sign-in happens over HTTP, never in a rendered page, so a recording starts\n * already signed in and no frame can show a password. The resulting storage\n * state (session cookies) is cached per origin and identity under the state\n * directory (mode 0600) and reused while the app's session endpoint still\n * answers with a verified user. Journeys running in parallel share it, so a\n * burst of journeys cannot trip an auth rate limit.\n *\n * Never press Sign out in a shared session: it revokes the session every\n * journey on the host is using. A journey that signs out opens its context with\n * `{ fresh: true }`, which signs in a session of its own.\n */\nimport { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { APIRequestContext } from 'playwright'\nimport type { JourneyIdentity, ResolvedJourneysConfig } from './config.js'\n\nexport interface SessionUser {\n id: string\n name: string | null\n emailVerified: boolean\n}\n\nclass SignInError extends Error {\n constructor(readonly status: number, message: string) {\n super(message)\n }\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n\nasync function playwrightRequest() {\n try {\n return (await import('playwright')).request\n } catch {\n throw new Error('journeys need the optional `playwright` peer: install playwright in the app that runs them')\n }\n}\n\nfunction sessionDir(config: ResolvedJourneysConfig): string {\n return join(config.stateDir, 'sessions', new URL(config.baseUrl).host)\n}\n\nfunction storageStatePath(config: ResolvedJourneysConfig, identity: string): string {\n return join(sessionDir(config), `${identity}.storage.json`)\n}\n\nfunction need(name: string): string {\n const value = process.env[name]?.trim()\n if (!value) throw new Error(`${name} is unset: load it from the host's vault into this process (the value is never printed)`)\n return value\n}\n\n/** The signed-in user behind a storage state, or null when it no longer signs in. */\nexport async function sessionUser(config: ResolvedJourneysConfig, state: string): Promise<SessionUser | null> {\n if (!existsSync(state)) return null\n const request = await playwrightRequest()\n const ctx = await request.newContext({ baseURL: config.baseUrl, storageState: state })\n try {\n const r = await ctx.get(config.auth.session, { maxRedirects: 0, timeout: 20_000 })\n if (!r.ok()) return null\n const body = (await r.json().catch(() => null)) as { user?: { id?: string; name?: string; emailVerified?: boolean } } | null\n const user = body?.user\n if (!user?.id) return null\n return { id: user.id, name: user.name ?? null, emailVerified: user.emailVerified === true }\n } finally {\n await ctx.dispose()\n }\n}\n\nasync function signInWithPassword(ctx: APIRequestContext, config: ResolvedJourneysConfig, email: string, password: string): Promise<void> {\n const r = await ctx.post(`${config.baseUrl}${config.auth.passwordSignIn}`, {\n headers: { 'content-type': 'application/json', origin: config.baseUrl },\n data: { email, password },\n maxRedirects: 0,\n })\n if (r.status() !== 200) throw new SignInError(r.status(), `email sign-in returned ${r.status()}`)\n}\n\n/** \"Log in with Tangle\": the app's start route, Platform sign-in, authorize, the app's callback. */\nasync function signInWithTangle(ctx: APIRequestContext, config: ResolvedJourneysConfig, email: string, password: string): Promise<void> {\n const base = config.baseUrl\n const start = await ctx.get(`${base}${config.auth.tangleStart}`, { maxRedirects: 0 })\n const first = start.headers()['location']\n if (!first) throw new SignInError(start.status(), `SSO start returned ${start.status()} without a redirect`)\n const authorize = new URL(first, base).toString()\n const platform = new URL(authorize).origin\n const signIn = await ctx.post(`${platform}/api/auth/sign-in/email`, {\n headers: { 'content-type': 'application/json', origin: platform },\n data: { email, password },\n maxRedirects: 0,\n })\n if (signIn.status() !== 200) throw new SignInError(signIn.status(), `Platform sign-in returned ${signIn.status()}`)\n const startPrefix = config.auth.tangleStart.replace(/\\/start$/, '/')\n let next = authorize\n for (let hop = 0; hop < 8; hop += 1) {\n const r = await ctx.get(next, { maxRedirects: 0 })\n const location = r.headers()['location']\n // Only a pathname is ever reported: the query carries OAuth codes.\n if (!location) throw new SignInError(r.status(), `SSO stopped at ${new URL(next).pathname} with ${r.status()}`)\n const url = new URL(location, next)\n if (url.origin === new URL(base).origin && !url.pathname.startsWith(startPrefix)) {\n if (url.pathname.startsWith('/login')) throw new SignInError(401, 'the app callback refused the sign-in')\n return\n }\n next = url.toString()\n }\n throw new SignInError(0, 'SSO did not return to the app within 8 redirects')\n}\n\n/** A cross-process lock: mkdir is atomic. A lock older than two minutes is stale. */\nasync function withLock<T>(dir: string, work: () => Promise<T>): Promise<T> {\n const deadline = Date.now() + 180_000\n for (;;) {\n try {\n mkdirSync(dir)\n break\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n const age = Date.now() - (statSync(dir, { throwIfNoEntry: false })?.mtimeMs ?? Date.now())\n if (age > 120_000) rmSync(dir, { recursive: true, force: true })\n if (Date.now() > deadline) throw new Error(`timed out waiting for ${dir}`)\n await sleep(500)\n }\n }\n try {\n return await work()\n } finally {\n rmSync(dir, { recursive: true, force: true })\n }\n}\n\nfunction identityOf(config: ResolvedJourneysConfig, name: string): JourneyIdentity {\n const identity = config.identities[name]\n if (!identity) throw new Error(`\"${name}\" is not an identity in the ${config.app} journeys config (${Object.keys(config.identities).join(', ')})`)\n return identity\n}\n\n/**\n * Path to a storage state signed in as `identity`. Reused while valid;\n * `fresh` signs in a session of its own (for a journey that signs out).\n */\nexport async function storageStateFor(\n config: ResolvedJourneysConfig,\n name: string,\n opts: { fresh?: boolean } = {},\n): Promise<{ path: string; user: SessionUser }> {\n const identity = identityOf(config, name)\n const dir = sessionDir(config)\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n const file = opts.fresh ? join(dir, `${name}.${process.pid}.${Date.now()}.storage.json`) : storageStatePath(config, name)\n const request = await playwrightRequest()\n return withLock(join(dir, `signin-${name}.lock`), async () => {\n if (!opts.fresh) {\n const cached = await sessionUser(config, file)\n if (cached) return { path: file, user: cached }\n }\n const email = need(identity.emailEnv)\n const password = need(identity.passwordEnv)\n for (let attempt = 1; ; attempt += 1) {\n const ctx = await request.newContext({ baseURL: config.baseUrl })\n try {\n if (identity.signIn === 'password') await signInWithPassword(ctx, config, email, password)\n else await signInWithTangle(ctx, config, email, password)\n const tmp = `${file}.tmp`\n await ctx.storageState({ path: tmp })\n chmodSync(tmp, 0o600)\n renameSync(tmp, file)\n break\n } catch (error) {\n const status = error instanceof SignInError ? error.status : 0\n if (status !== 429 || attempt >= 4) throw error\n await sleep(15_000 * attempt)\n } finally {\n await ctx.dispose()\n }\n }\n const user = await sessionUser(config, file)\n if (!user) throw new Error(`${name} signed in but ${config.auth.session} has no user`)\n // A read-only journey can still run; one that chats will be refused, so say so before it tries.\n if (!user.emailVerified) console.warn(`${name} signed in but is not email-verified; an app that requires verification will refuse its chat`)\n return { path: file, user }\n })\n}\n\n/**\n * Every value that must never leave the host. `hard`: passwords and each cookie\n * value (whole, URL-decoded, and its token half). `soft`: the identities'\n * emails, which are warned about but not refused.\n */\nexport function secretNeedles(config: ResolvedJourneysConfig): { hard: string[]; soft: string[] } {\n const hard = new Set<string>()\n const soft = new Set<string>()\n for (const identity of Object.values(config.identities)) {\n const password = process.env[identity.passwordEnv]?.trim()\n if (password) hard.add(password)\n const email = process.env[identity.emailEnv]?.trim()\n if (email) soft.add(email)\n }\n const root = join(config.stateDir, 'sessions')\n const stack = existsSync(root) ? [root] : []\n while (stack.length) {\n const dir = stack.pop()!\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const path = join(dir, entry.name)\n if (entry.isDirectory()) stack.push(path)\n else if (entry.name.endsWith('.storage.json')) addCookieNeedles(path, hard)\n }\n }\n return { hard: [...hard], soft: [...soft] }\n}\n\nfunction addCookieNeedles(file: string, hard: Set<string>): void {\n try {\n const state = JSON.parse(readFileSync(file, 'utf8')) as { cookies?: { value: string }[] }\n for (const { value } of state.cookies ?? []) {\n if (!value || value.length < 16) continue\n hard.add(value)\n let decoded = value\n try {\n decoded = decodeURIComponent(value)\n } catch {\n // A value that is not URI-encoded is already its own decoded form.\n }\n hard.add(decoded)\n const token = decoded.split('.')[0] ?? ''\n if (token.length >= 16) hard.add(token)\n }\n } catch {\n // A half-written state file holds nothing a finished run used.\n }\n}\n","/**\n * A recording turned into files a person can watch.\n *\n * <label>-full.mp4 H.264, the whole session at real speed, with an 84 px\n * caption bar under the UI: the chapter line and an elapsed clock\n * <label>.srt the same chapters as a sidecar caption file\n * <label>-highlights.mp4 at most 178 s: waits and idle stretches sped up, and the caption\n * says by how much (\"[01:09] First text after 23 s » 4.2x, 21 s real (whole wait 41 s)\")\n * <label>-x2.mp4 optional: the full video at 2x\n *\n * Captions sit in their own bar so they never cover the composer or a toast.\n * Needs `ffmpeg` and `ffprobe` on PATH; work runs at nice 10 on 2 threads.\n */\nimport { execFileSync } from 'node:child_process'\nimport { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { basename, join } from 'node:path'\n\nexport interface Chapter {\n /** Epoch ms. */\n at: number\n caption: string\n /** Context label, or null for every context. */\n label: string | null\n kind: 'step' | 'wait'\n /** Epoch ms a wait ended. */\n until?: number\n}\n\nexport interface Cue {\n start: number\n end: number\n text: string\n}\n\nexport interface HighlightSegment {\n /** Source range, seconds. */\n a: number\n b: number\n /** Speed-up factor. */\n k: number\n text: string\n}\n\n/** The frame a recording made before sizes were saved used. */\nconst DESKTOP_FRAME = { width: 1440, height: 900 }\ntype Frame = { width: number; height: number }\nconst BAR = 84\nexport const MAX_HIGHLIGHTS_S = 178\n\nconst FONT_CANDIDATES = [\n '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',\n '/usr/share/fonts/dejavu/DejaVuSansMono.ttf',\n '/System/Library/Fonts/Menlo.ttc',\n]\n\nfunction monoFont(): string | null {\n const configured = process.env.JOURNEYS_FONT_MONO\n if (configured && existsSync(configured)) return configured\n return FONT_CANDIDATES.find((path) => existsSync(path)) ?? null\n}\n\nfunction ff(args: string[]): void {\n execFileSync('nice', ['-n', '10', 'ffmpeg', '-hide_banner', '-loglevel', 'error', '-y', ...args], { stdio: ['ignore', 'inherit', 'inherit'] })\n}\n\nexport function probeSeconds(file: string): number {\n const out = execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', file], { encoding: 'utf8' }).trim()\n const n = Number(out)\n if (!Number.isFinite(n) || n <= 0) throw new Error(`ffprobe could not read the duration of ${file}: ${out}`)\n return n\n}\n\nconst pad2 = (n: number) => String(Math.floor(n)).padStart(2, '0')\nconst mmss = (s: number) => `${pad2(s / 60)}:${pad2(s % 60)}`\nconst srtTime = (s: number) => {\n const ms = Math.max(0, Math.round(s * 1000))\n return `${pad2(ms / 3_600_000)}:${pad2((ms / 60_000) % 60)}:${pad2((ms / 1000) % 60)},${String(ms % 1000).padStart(3, '0')}`\n}\nconst assTime = (s: number) => {\n const cs = Math.max(0, Math.round(s * 100))\n return `${Math.floor(cs / 360_000)}:${pad2((cs / 6000) % 60)}:${pad2((cs / 100) % 60)}.${String(cs % 100).padStart(2, '0')}`\n}\nconst humanSeconds = (s: number) => (s >= 90 ? `${Math.floor(s / 60)} min ${Math.round(s % 60)} s` : `${Math.round(s)} s`)\n\n/** Chapters on the video's own clock; each caption holds until the next. */\nexport function chapterCues(chapters: readonly Chapter[], t0: number, duration: number): Cue[] {\n const points = chapters\n .map((c) => ({ ...c, s: (c.at - t0) / 1000, e: c.until ? (c.until - t0) / 1000 : undefined }))\n .filter((c) => c.s < duration)\n .sort((a, b) => a.s - b.s)\n const cues: Cue[] = []\n for (let i = 0; i < points.length; i += 1) {\n const c = points[i]!\n const start = Math.max(0, c.s)\n const end = Math.min(duration, points[i + 1]?.s ?? duration)\n if (end - start < 0.05) continue\n const text = c.kind === 'wait' && c.e !== undefined ? `${c.caption} (real wait ${humanSeconds(c.e - c.s)})` : c.caption\n cues.push({ start, end, text })\n }\n return cues\n}\n\nfunction srtText(cues: readonly Cue[]): string {\n return cues.map((c, i) => `${i + 1}\\n${srtTime(c.start)} --> ${srtTime(c.end)}\\n${c.text}\\n`).join('\\n')\n}\n\nfunction assText(cues: readonly Cue[], { width: W, height: H }: Frame): string {\n const esc = (t: string) => t.replace(/\\\\/g, '\\\\\\\\').replace(/[{}]/g, '').replace(/\\n/g, '\\\\N')\n const head = `[Script Info]\\nScriptType: v4.00+\\nPlayResX: ${W}\\nPlayResY: ${H + BAR}\\nWrapStyle: 0\\n\\n[V4+ Styles]\\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\\nStyle: Bar,DejaVu Sans,26,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,0,0,1,28,200,14,1\\n\\n[Events]\\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\\n`\n return head + cues.map((c) => `Dialogue: 0,${assTime(c.start)},${assTime(c.end)},Bar,,0,0,0,,${esc(c.text)}`).join('\\n') + '\\n'\n}\n\n/**\n * The highlights cut: which source ranges, at what speed, under which caption.\n * A wait longer than 6 s plays in about 5 s; an idle stretch longer than 15 s\n * plays in about 10 s; then everything scales to fit {@link MAX_HIGHLIGHTS_S}.\n */\nexport function highlightPlan(chapters: readonly Chapter[], t0: number, duration: number): HighlightSegment[] {\n const pts = chapters\n .map((c) => ({ ...c, s: Math.max(0, (c.at - t0) / 1000), e: c.until ? (c.until - t0) / 1000 : undefined }))\n .sort((x, y) => x.s - y.s)\n const cuts = new Set<number>([0, duration])\n for (const p of pts) {\n if (p.s < duration) cuts.add(Math.round(p.s * 10) / 10)\n if (p.e !== undefined && p.e < duration) cuts.add(Math.round(p.e * 10) / 10)\n }\n const bounds = [...cuts].sort((x, y) => x - y)\n const segs: { a: number; b: number; k: number; text: string; wait: boolean; whole: number }[] = []\n for (let i = 0; i + 1 < bounds.length; i += 1) {\n const a = bounds[i]!\n const b = bounds[i + 1]!\n if (b - a < 0.15) continue\n const wait = [...pts].reverse().find((p) => p.kind === 'wait' && p.e !== undefined && p.s <= a + 0.05 && a < p.e - 0.05)\n // The latest step caption wins (e.g. \"First text after 31 s\" inside a wait); the wait adds its total.\n const step = [...pts].reverse().find((p) => p.kind === 'step' && p.s <= a + 0.05 && (!wait || p.s >= wait.s - 0.05))\n const len = b - a\n const k = wait ? (len > 6 ? len / 5 : 1) : len > 15 ? len / 10 : 1\n segs.push({ a, b, k, text: step?.caption ?? wait?.caption ?? '', wait: Boolean(wait), whole: wait?.e !== undefined ? wait.e - wait.s : 0 })\n }\n const shown = segs.reduce((n, s) => n + (s.b - s.a) / s.k, 0)\n const f = shown > MAX_HIGHLIGHTS_S ? shown / MAX_HIGHLIGHTS_S : 1\n return segs.map((s) => {\n const k = s.k * f\n const len = s.b - s.a\n const x = k >= 10 ? Math.round(k) : Math.round(k * 10) / 10\n const speed = k > 1.05 ? ` » ${x}x, ${humanSeconds(len)} real${s.wait ? ` (whole wait ${humanSeconds(s.whole)})` : ''}` : ''\n return { a: s.a, b: s.b, k, text: `[${mmss(s.a)}] ${s.text}${speed}` }\n })\n}\n\ninterface PostProcessInput {\n webm: string\n /** Raw working folder on the host; keeps the webm and chapters for a rebuild. */\n workDir: string\n videoDir: string\n label: string\n /** Epoch ms the recorded page was created. */\n t0: number\n wallSeconds: number\n chapters: readonly Chapter[]\n speedup2x: boolean\n /** The recorded frame; desktop when absent. */\n size?: Frame\n}\n\nexport function postProcessVideo(o: PostProcessInput): string[] {\n mkdirSync(o.videoDir, { recursive: true })\n const keep = join(o.workDir, `${o.label}.webm`)\n if (o.webm !== keep) copyFileSync(o.webm, keep)\n const size = o.size ?? DESKTOP_FRAME\n writeFileSync(join(o.workDir, `${o.label}.chapters.json`), JSON.stringify({ t0: o.t0, wallSeconds: o.wallSeconds, chapters: o.chapters, size }))\n return renderAll(keep, o.workDir, o.videoDir, o.label, o.t0, o.chapters, o.speedup2x, o.wallSeconds, size)\n}\n\n/** Re-render from a raw folder after editing `<label>.chapters.json` by hand. */\nexport function rebuildVideo(rawLabelDir: string, videoDir: string, label: string, speedup2x: boolean): string[] {\n const meta = JSON.parse(readFileSync(join(rawLabelDir, `${label}.chapters.json`), 'utf8')) as { t0: number; wallSeconds: number; chapters: Chapter[]; size?: Frame }\n return renderAll(join(rawLabelDir, `${label}.webm`), rawLabelDir, videoDir, label, meta.t0, meta.chapters, speedup2x, meta.wallSeconds, meta.size ?? DESKTOP_FRAME)\n}\n\nfunction renderAll(webm: string, work: string, videoDir: string, label: string, t0: number, chapters: readonly Chapter[], speedup2x: boolean, wallSeconds: number, size: Frame): string[] {\n const { width: W, height: H } = size\n const clean = join(work, `${label}.clean.mp4`)\n ff(['-i', webm, '-vf', `fps=25,scale=${W}:${H}:flags=lanczos,format=yuv420p`, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '22', '-threads', '2', '-an', clean])\n const duration = probeSeconds(clean)\n // Measured 2026-10-11 against a clock burned into the page: video time tracks\n // wall clock from page creation to within 0.2 s.\n if (duration < wallSeconds - 3) console.warn(`video is ${duration.toFixed(1)} s but ${wallSeconds.toFixed(1)} s passed before recording stopped; late captions may be early`)\n\n const cues = chapterCues(chapters, t0, duration)\n const srt = join(videoDir, `${label}.srt`)\n writeFileSync(srt, srtText(cues))\n const ass = join(work, `${label}.full.ass`)\n writeFileSync(ass, assText(cues, size))\n const full = join(videoDir, `${label}-full.mp4`)\n const font = monoFont()\n const clock = `drawtext=${font ? `fontfile=${font}` : 'font=monospace'}:text='%{pts\\\\:hms}':x=w-tw-28:y=h-${BAR / 2}-th/2:fontsize=26:fontcolor=white@0.8`\n ff(['-i', clean, '-vf', `pad=${W}:${H + BAR}:0:0:color=0x111111,ass=${ass},${clock}`, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', full])\n\n const plan = highlightPlan(chapters, t0, duration)\n const segDir = join(work, `${label}.segments`)\n mkdirSync(segDir, { recursive: true })\n const list: string[] = []\n const hcues: Cue[] = []\n let at = 0\n plan.forEach((s, i) => {\n const seg = join(segDir, `${String(i).padStart(3, '0')}.mp4`)\n ff(['-ss', s.a.toFixed(3), '-t', (s.b - s.a).toFixed(3), '-i', clean, '-vf', `setpts=PTS/${s.k.toFixed(4)},fps=25`, '-an', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', seg])\n const len = probeSeconds(seg)\n list.push(`file '${seg}'`)\n hcues.push({ start: at, end: at + len, text: s.text })\n at += len\n })\n const listFile = join(segDir, 'list.txt')\n writeFileSync(listFile, list.join('\\n') + '\\n')\n const joined = join(work, `${label}.highlights.raw.mp4`)\n ff(['-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', joined])\n const hass = join(work, `${label}.highlights.ass`)\n writeFileSync(hass, assText(hcues, size))\n const highlights = join(videoDir, `${label}-highlights.mp4`)\n ff(['-i', joined, '-vf', `pad=${W}:${H + BAR}:0:0:color=0x111111,ass=${hass}`, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', highlights])\n const out = [full, srt, highlights]\n if (speedup2x) {\n const x2 = join(videoDir, `${label}-x2.mp4`)\n ff(['-i', full, '-vf', 'setpts=PTS/2,fps=25', '-an', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', x2])\n out.push(x2)\n }\n console.log(`video ${label}: full ${duration.toFixed(1)} s, highlights ${at.toFixed(1)} s from ${plan.length} segments`)\n return out\n}\n\n/** Seconds at which to grab frames: one per caption (1.5 s in), at most `max`, evenly spread. */\nexport function frameTimes(srt: string | null, times: readonly number[], max = 10): number[] {\n let ts = [...times]\n if (!ts.length && srt) {\n ts = srt.split('\\n').filter((l) => l.includes('-->')).map((l) => {\n const [h = '0', m = '0', rest = '0'] = l.split(' --> ')[0]!.split(':')\n return Number(h) * 3600 + Number(m) * 60 + Number(rest.replace(',', '.')) + 1.5\n })\n }\n if (ts.length > max) {\n const step = ts.length / max\n ts = Array.from({ length: max }, (_, i) => ts[Math.floor(i * step)]!)\n }\n return ts\n}\n\n/** PNG frames of a video, named by label and timestamp, into `outDir`. */\nexport function extractFrames(video: string, srtFile: string | null, outDir: string, times: readonly number[], max = 10): string[] {\n const srt = srtFile && existsSync(srtFile) ? readFileSync(srtFile, 'utf8') : null\n return frameTimes(srt, times, max).map((t, i) => {\n const f = join(outDir, `frame-${basename(video).replace(/-full\\.mp4$/, '')}-${String(i + 1).padStart(2, '0')}-${mmss(t).replace(':', 'm')}s.png`)\n ff(['-ss', t.toFixed(2), '-i', video, '-frames:v', '1', f])\n return f\n })\n}\n","/**\n * The one file a reviewer opens: INDEX.md for a folder of recorded journeys.\n *\n * It lists the highlight cuts first, the critic's scorecard, the ranked fix\n * list (verified failures by rank, each with its evidence, fix, number to beat\n * and proving test), every recorded turn with its scored outcome, every video,\n * and what stayed unproven. The renderer is pure; `collectJourneyFiles` reads\n * the folder.\n */\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join, relative } from 'node:path'\nimport type { TurnRecord } from './journey.js'\n\n/** What the skeptical critic returns; the same shape the prove-journeys workflow asks for. */\nexport interface CriticResult {\n headline: string\n scorecard?: { journey: string; verifiedVerdict: string; keyTiming?: string; qualityGrade?: string; topIssue: string; video?: string }[]\n verifiedFailures?: {\n rank: number\n severity: string\n what: string\n journeys?: string[]\n evidence: string\n likelyCause?: string\n fix: string\n numberToBeat: string\n test: string\n }[]\n refutedOrUnproven?: string[]\n coverageGaps?: string[]\n}\n\nexport interface JourneyFiles {\n /** Folder relative to the index root, e.g. `j1-new-customer` or `j1-new-customer/r2`. */\n dir: string\n videos: { file: string; seconds: number | null }[]\n turns: Pick<TurnRecord, 'label' | 'outcome' | 'firstTextS' | 'completeS' | 'replyChars' | 'error' | 'sentAt'>[]\n}\n\nexport interface IndexInput {\n title: string\n critic?: CriticResult\n journeys: JourneyFiles[]\n}\n\nconst seconds = (s: number | null) => (s === null ? '?' : `${Math.round(s).toLocaleString('en-US')} s`)\nconst cell = (text: string | number | null | undefined) => String(text ?? '').replace(/\\|/g, '\\\\|').replace(/\\s*\\n\\s*/g, ' ')\nconst firstLine = (text: string) => text.split('\\n')[0]!.trim()\n\nfunction videoLabel(file: string): { base: string; kind: string } {\n const name = file.split('/').pop() ?? file\n const m = /^(.*)-(highlights|full|x2)\\.mp4$/.exec(name)\n return m ? { base: m[1]!, kind: m[2]! } : { base: name.replace(/\\.mp4$/, ''), kind: 'other' }\n}\n\n/** Every recorded turn's outcome, counted. The denominator is every turn in the folder's timings.json files. */\nexport function tallyTurns(journeys: readonly JourneyFiles[]): { total: number; byOutcome: Record<string, number> } {\n const byOutcome: Record<string, number> = {}\n let total = 0\n for (const j of journeys) {\n for (const t of j.turns) {\n total += 1\n byOutcome[t.outcome] = (byOutcome[t.outcome] ?? 0) + 1\n }\n }\n return { total, byOutcome }\n}\n\nexport function renderIndex(input: IndexInput): string {\n const out: string[] = [`# ${input.title}`, '']\n const { critic } = input\n const tally = tallyTurns(input.journeys)\n if (critic?.headline) out.push(`**Result.** ${critic.headline}`, '')\n if (tally.total) {\n const parts = Object.entries(tally.byOutcome).sort((a, b) => b[1] - a[1]).map(([k, n]) => `${n} ${k}`)\n out.push(`**Turns, as scored by the recorder:** ${parts.join(', ')}, of ${tally.total} recorded turns (source: each journey's timings.json).`, '')\n }\n\n const all = input.journeys.flatMap((j) => j.videos.map((v) => ({ ...v, dir: j.dir, path: j.dir ? `${j.dir}/${v.file}` : v.file })))\n const highlights = all.filter((v) => videoLabel(v.file).kind === 'highlights')\n const scoreVideos = (critic?.scorecard ?? []).map((s) => s.video ?? '').filter(Boolean)\n const rankOf = (path: string) => {\n const i = scoreVideos.findIndex((v) => v.endsWith(path))\n return i < 0 ? Number.MAX_SAFE_INTEGER : i\n }\n highlights.sort((a, b) => rankOf(a.path) - rankOf(b.path) || a.path.localeCompare(b.path))\n if (highlights.length) {\n out.push('## Start here: highlights, at most 3 minutes each', '')\n highlights.forEach((v, i) => {\n const card = critic?.scorecard?.find((s) => s.video?.endsWith(v.path))\n out.push(`${i + 1}. \\`${v.path}\\` (${seconds(v.seconds)})${card ? `. ${card.journey}: ${firstLine(card.topIssue)}` : ''}`)\n })\n out.push('')\n }\n\n if (critic?.scorecard?.length) {\n out.push('## Scorecard', '', '| Journey | Verdict | Key timing | Output | Top issue |', '|---|---|---|---|---|')\n for (const s of critic.scorecard) out.push(`| ${cell(s.journey)} | ${cell(s.verifiedVerdict)} | ${cell(s.keyTiming)} | ${cell(s.qualityGrade)} | ${cell(s.topIssue)} |`)\n out.push('')\n }\n\n const fixes = [...(critic?.verifiedFailures ?? [])].sort((a, b) => a.rank - b.rank)\n if (fixes.length) {\n out.push('## Ranked fixes (verified failures, customer impact first)', '')\n for (const f of fixes) {\n out.push(`${f.rank}. **${firstLine(f.what)}** (${f.severity}${f.journeys?.length ? `; ${f.journeys.join(', ')}` : ''})`)\n // Later lines keep their breaks, so a list inside `what` nests under its rank.\n for (const line of f.what.split('\\n').slice(1)) if (line.trim()) out.push(` ${line.trim()}`)\n out.push(` - Evidence: ${cell(f.evidence)}`)\n if (f.likelyCause) out.push(` - Likely cause: ${cell(f.likelyCause)}`)\n out.push(` - Fix: ${cell(f.fix)}`, ` - Number to beat: ${cell(f.numberToBeat)}`, ` - Proving test: ${cell(f.test)}`)\n }\n out.push('')\n }\n\n const turns = input.journeys.flatMap((j) => j.turns.map((t) => ({ ...t, dir: j.dir })))\n if (turns.length) {\n out.push('## Every recorded turn', '', '| Journey | Context | Sent | Outcome | First text | End | Reply chars | What went wrong |', '|---|---|---|---|---|---|---|---|')\n for (const t of turns) {\n out.push(`| ${cell(t.dir || '.')} | ${cell(t.label)} | ${cell(t.sentAt.slice(11, 19))}Z | ${cell(t.outcome)} | ${seconds(t.firstTextS)} | ${seconds(t.completeS)} | ${t.replyChars.toLocaleString('en-US')} | ${cell(t.error ?? '')} |`)\n }\n out.push('')\n }\n\n if (all.length) {\n out.push('## Every video', '')\n const dirs = [...new Set(all.map((v) => v.dir))]\n for (const dir of dirs) {\n out.push(`### \\`${dir || '.'}\\``, '')\n const byBase = new Map<string, typeof all>()\n for (const v of all.filter((x) => x.dir === dir)) {\n const { base } = videoLabel(v.file)\n byBase.set(base, [...(byBase.get(base) ?? []), v])\n }\n for (const [base, vids] of byBase) {\n const order = ['highlights', 'full', 'x2', 'other']\n vids.sort((a, b) => order.indexOf(videoLabel(a.file).kind) - order.indexOf(videoLabel(b.file).kind))\n out.push(`- ${base}: ${vids.map((v) => `\\`${v.file}\\` (${seconds(v.seconds)})`).join(', ')}`)\n }\n out.push('')\n }\n }\n\n const unproven = [...(critic?.refutedOrUnproven ?? []), ...(critic?.coverageGaps ?? [])]\n if (unproven.length) {\n out.push('## Refuted, unproven and not covered', '')\n for (const u of unproven) out.push(`- ${cell(u)}`)\n out.push('')\n }\n return out.join('\\n')\n}\n\n/**\n * Every journey folder under `root`: one that holds a `timings.json` or a\n * `video/` folder, at any depth. `probe` returns a video's duration in seconds.\n */\nexport function collectJourneyFiles(root: string, probe: (file: string) => number | null): JourneyFiles[] {\n const found: JourneyFiles[] = []\n const visit = (dir: string, depth: number) => {\n const timings = join(dir, 'timings.json')\n const videoDir = join(dir, 'video')\n const hasVideo = existsSync(videoDir) && statSync(videoDir).isDirectory()\n if (existsSync(timings) || hasVideo) {\n const videos = hasVideo\n ? readdirSync(videoDir).filter((f) => f.endsWith('.mp4')).sort().map((f) => ({ file: `video/${f}`, seconds: probe(join(videoDir, f)) }))\n : []\n let turns: JourneyFiles['turns'] = []\n if (existsSync(timings)) {\n try {\n turns = ((JSON.parse(readFileSync(timings, 'utf8')) as { turns?: JourneyFiles['turns'] }).turns ?? [])\n } catch {\n turns = []\n }\n }\n found.push({ dir: relative(root, dir), videos, turns })\n }\n if (depth >= 4) return\n for (const name of readdirSync(dir).sort()) {\n const path = join(dir, name)\n if (name === 'video' || name === 'turns' || name.startsWith('.')) continue\n if (statSync(path).isDirectory()) visit(path, depth + 1)\n }\n }\n visit(root, 0)\n return found\n}\n","/**\n * The readiness scoreboard writer: one run's journey summary as the writes\n * that put it on the shared board, so every app's rows land in one schema.\n *\n * The board is an artifact page whose shared store holds three collections:\n * `flows` (one row per flow), `prs` and `meta` (one document per app; Hardware's\n * is `board`, written before the board was shared). A row carries `app` and\n * `flowId`; a row without `app` belongs to Hardware. Hardware's rows predate the\n * shared board and live at their bare flow id and `meta/board`; its runner\n * passes `legacyIds` so those rows are updated in place, never duplicated.\n *\n * A document that already exists is merged (`update`) and pinned to the\n * version the caller read from the store (`versions`), so the text a person\n * wrote for a flow (what the customer does, its pass bar) survives every run,\n * and a field the run no longer has (an old blocker on a flow that now passes)\n * is deleted. A document with no known version is created with `set`; the\n * store refuses a `set` without a version on a document that already exists\n * (version_mismatch, nothing written; checked against the board's store), so a row a person wrote is never replaced.\n *\n * Pure: the same summary and options give the same writes, in the same order.\n */\n\nexport const SCOREBOARD_STATUSES = ['pass', 'fail', 'stall', 'blocked-host', 'blocked', 'skipped', 'unrecorded'] as const\nexport type ScoreboardStatus = (typeof SCOREBOARD_STATUSES)[number]\n\n/** Rows a store wrote before the board was shared, with no `app` field, belong to this app. */\nexport const LEGACY_SCOREBOARD_APP = 'hardware'\n\n/** One journey in a run's `summary.json`. */\nexport interface JourneySummaryEntry {\n /** Flow id, e.g. `c2` or `C2`; written upper-case. */\n id: string\n status: string\n /** Why it was blocked, skipped, stalled or failed. */\n reason?: string\n firstTextS?: number\n completeS?: number\n /** Links a reviewer can open. Only http(s) URLs are written; host paths are dropped. */\n videoUrl?: string\n traceUrl?: string\n evidenceUrl?: string\n}\n\n/** A run's summary, as an app's journey runner writes it. */\nexport interface JourneySummary {\n origin?: string\n /** Commit the run served. */\n sha?: string\n model?: string\n lane?: string\n /** ISO time of the run; required, so two runs are told apart. */\n updatedAt?: string\n journeys: JourneySummaryEntry[]\n}\n\nexport interface ScoreboardOptions {\n /** Short app name, e.g. `casework`. */\n app: string\n /** Current version of each document that exists, by `collection/docId`. */\n versions?: Readonly<Record<string, number>>\n /**\n * Write at the ids the board used before it was shared: the bare flow id and\n * `meta/board`. Only Hardware's runner sets this; every other app's rows are\n * `<app>-<flowId>` and `meta/<app>`.\n */\n legacyIds?: boolean\n}\n\n/** One entry of an artifact store batch, in the shape the batch write takes. */\nexport interface ScoreboardWrite {\n op: 'update' | 'set'\n collection: 'flows' | 'meta'\n doc_id: string\n data: Record<string, unknown>\n if_version?: number\n}\n\nexport interface ScoreboardResult {\n writes: ScoreboardWrite[]\n /** Entries the writer could not take as given, each with what it did instead. */\n warnings: string[]\n}\n\nconst DELETE = { __delete__: true } as const\nconst APP_NAME = /^[a-z][a-z0-9-]{0,40}$/\n\nconst isStatus = (value: string): value is ScoreboardStatus => (SCOREBOARD_STATUSES as readonly string[]).includes(value)\nconst url = (value: unknown): string | undefined => (typeof value === 'string' && /^https?:\\/\\//.test(value) ? value : undefined)\nconst seconds = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined)\n\n/** The document id a flow row lives at. */\nexport function scoreboardDocId(app: string, flowId: string, legacyIds = false): string {\n return legacyIds ? flowId : `${app}-${flowId}`\n}\n\n/** The `meta` document an app's run facts live at. */\nexport function scoreboardMetaId(app: string, legacyIds = false): string {\n return legacyIds ? 'board' : app\n}\n\n/** Keys in a fixed order, so the same input always serializes the same way. */\nfunction sorted(data: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.keys(data).sort().map((key) => [key, data[key]]))\n}\n\n/**\n * A document with a known version is merged, pinned to that version. One with\n * none is created with `set`, which takes no delete markers; if it does exist\n * after all, the store refuses the unpinned write and names it, so nothing a\n * person wrote there is overwritten.\n */\nfunction pinned(write: Omit<ScoreboardWrite, 'if_version'>, versions: ScoreboardOptions['versions']): ScoreboardWrite {\n const version = versions?.[`${write.collection}/${write.doc_id}`]\n if (version !== undefined) return { ...write, op: 'update', if_version: version }\n const data = Object.fromEntries(Object.entries(write.data).filter(([, value]) => value !== DELETE))\n return { ...write, op: 'set', data }\n}\n\nexport function scoreboardRows(summary: JourneySummary, options: ScoreboardOptions): ScoreboardResult {\n const app = options.app\n if (!APP_NAME.test(app)) throw new Error(`scoreboard: app must be a short lowercase name such as \"casework\", got \"${app}\"`)\n if (!summary || !Array.isArray(summary.journeys)) throw new Error('scoreboard: the summary has no journeys array')\n if (!summary.updatedAt || Number.isNaN(Date.parse(summary.updatedAt))) throw new Error('scoreboard: the summary needs updatedAt, an ISO time')\n\n const warnings: string[] = []\n const flows = new Map<string, ScoreboardWrite>()\n for (const entry of summary.journeys) {\n const flowId = String(entry.id ?? '').trim().toUpperCase()\n if (!flowId) { warnings.push('a journey without an id was skipped'); continue }\n let status: ScoreboardStatus\n if (isStatus(entry.status)) status = entry.status\n else { status = 'unrecorded'; warnings.push(`${flowId}: status \"${entry.status}\" is not one of ${SCOREBOARD_STATUSES.join(', ')}; written as unrecorded`) }\n if (flows.has(flowId)) warnings.push(`${flowId}: listed twice; the last entry wins`)\n for (const key of ['videoUrl', 'traceUrl', 'evidenceUrl'] as const) {\n if (entry[key] !== undefined && !url(entry[key])) warnings.push(`${flowId}: ${key} is not an http(s) link and was dropped`)\n }\n const reason = typeof entry.reason === 'string' && entry.reason.trim() ? entry.reason.trim() : undefined\n const data: Record<string, unknown> = {\n app,\n flowId,\n status,\n // A pass carries no blocker; any other status names why, or clears a stale one.\n blocker: status !== 'pass' && reason ? reason : DELETE,\n firstTextS: seconds(entry.firstTextS) ?? DELETE,\n completeS: seconds(entry.completeS) ?? DELETE,\n videoUrl: url(entry.videoUrl) ?? DELETE,\n traceUrl: url(entry.traceUrl) ?? DELETE,\n evidenceUrl: url(entry.evidenceUrl) ?? DELETE,\n sha: summary.sha ?? DELETE,\n recordedAt: summary.updatedAt,\n }\n flows.set(flowId, { op: 'update', collection: 'flows', doc_id: scoreboardDocId(app, flowId, options.legacyIds), data: sorted(data) })\n }\n\n const writes = [...flows.values()]\n .sort((a, b) => a.doc_id.localeCompare(b.doc_id, undefined, { numeric: true }))\n .map((write) => pinned(write, options.versions))\n const meta: Record<string, unknown> = {\n origin: summary.origin ?? DELETE,\n sha: summary.sha ?? DELETE,\n model: summary.model ?? DELETE,\n lane: summary.lane ?? DELETE,\n updatedAt: summary.updatedAt,\n }\n writes.push(pinned({ op: 'update', collection: 'meta', doc_id: scoreboardMetaId(app, options.legacyIds), data: sorted(meta) }, options.versions))\n return { writes, warnings }\n}\n"],"mappings":";;;;;AAmDO,IAAM,uBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,uBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,UAAU,MAAsB;AACvC,SAAO,KAAK,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACxC;AAGA,SAAS,aAAa,UAA8B,UAA2B,QAAkD;AAC/H,QAAM,SAAS,oBAAI,IAAoB;AACvC,QAAM,MAAM,CAAC,QAAgB,OAAO,IAAI,MAAM,OAAO,IAAI,GAAG,KAAK,KAAK,CAAC;AACvE,aAAW,OAAO,SAAS,OAAO;AAChC,UAAM,OAAO,UAAU,GAAG;AAC1B,QAAI,CAAC,QAAQ,OAAO,IAAI,IAAI,EAAG;AAC/B,QAAI,SAAS,QAAQ,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAG,KAAI,WAAW,IAAI,EAAE;AAAA,aAC5D,SAAS,QAAQ,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAG,KAAI,QAAQ,IAAI,EAAE;AAAA,EACzE;AACA,aAAW,OAAO,SAAS,cAAc;AACvC,UAAM,OAAO,UAAU,GAAG;AAC1B,QAAI,QAAQ,CAAC,OAAO,IAAI,IAAI,EAAG,KAAI,QAA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MAAM,UAAU,KAAK;AAAA,MACzC,WAAWA,SAAQ,MAAM,SAAS,KAAK;AAAA,MACvC,UAAU,IAAI,MAAM,QAAQ,KAAK;AAAA,MACjC,UAAU,IAAI,MAAM,QAAQ,KAAK;AAAA,MACjC,aAAa,IAAI,MAAM,WAAW,KAAK;AAAA,MACvC,KAAK,QAAQ,OAAO;AAAA,MACpB,YAAY,QAAQ;AAAA,IACtB;AACA,UAAM,IAAI,QAAQ,EAAE,IAAI,UAAU,YAAY,SAAS,QAAQ,gBAAgB,KAAK,QAAQ,QAAQ,SAAS,GAAG,MAAM,OAAO,IAAI,EAAE,CAAC;AAAA,EACtI;AAEA,QAAM,SAAS,CAAC,GAAG,MAAM,OAAO,CAAC,EAC9B,KAAK,CAAC,GAAG,MAAM,EAAE,OAAO,cAAc,EAAE,QAAQ,QAAW,EAAE,SAAS,KAAK,CAAC,CAAC,EAC7E,IAAI,CAAC,UAAU,OAAO,OAAO,QAAQ,QAAQ,CAAC;AACjD,QAAM,OAAgC;AAAA,IACpC,QAAQ,QAAQ,UAAU;AAAA,IAC1B,KAAK,QAAQ,OAAO;AAAA,IACpB,OAAO,QAAQ,SAAS;AAAA,IACxB,MAAM,QAAQ,QAAQ;AAAA,IACtB,WAAW,QAAQ;AAAA,EACrB;AACA,SAAO,KAAK,OAAO,EAAE,IAAI,UAAU,YAAY,QAAQ,QAAQ,iBAAiB,KAAK,QAAQ,SAAS,GAAG,MAAM,OAAO,IAAI,EAAE,GAAG,QAAQ,QAAQ,CAAC;AAChJ,SAAO,EAAE,QAAQ,SAAS;AAC5B;","names":["url","openSync","closeSync","join","openSync","closeSync","join","existsSync","readdirSync","readFileSync","statSync","join","resolve","url","existsSync","mkdirSync","readFileSync","join","existsSync","readdirSync","readFileSync","statSync","join","seconds"]}
@@ -12,7 +12,7 @@ import {
12
12
  scrubTrace,
13
13
  secretNeedles,
14
14
  storageStateFor
15
- } from "../chunk-OZDMIYES.js";
15
+ } from "../chunk-KTQM7JE6.js";
16
16
  import "../chunk-BTEVD7HG.js";
17
17
  import {
18
18
  invokedAsScript
@@ -32,7 +32,7 @@ import {
32
32
  tallyTurns,
33
33
  threadRouteIn,
34
34
  turnLooksActive
35
- } from "../chunk-OZDMIYES.js";
35
+ } from "../chunk-KTQM7JE6.js";
36
36
  import "../chunk-BTEVD7HG.js";
37
37
 
38
38
  // src/journeys/journey.ts
@@ -191,6 +191,13 @@ async function composerText(box) {
191
191
  // src/journeys/journey.ts
192
192
  var DESKTOP = { width: 1440, height: 900 };
193
193
  var PHONE = { width: 390, height: 844 };
194
+ var PHONE_CONTEXT = {
195
+ viewport: PHONE,
196
+ deviceScaleFactor: 2,
197
+ isMobile: true,
198
+ hasTouch: true,
199
+ userAgent: "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Mobile Safari/537.36"
200
+ };
194
201
  var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
195
202
  var secs = (ms) => Math.round(ms / 100) / 10;
196
203
  var CURSOR_SCRIPT = `(() => {
@@ -239,7 +246,7 @@ var Journey = class {
239
246
  screenshots = /* @__PURE__ */ new Set();
240
247
  startedAt = Date.now();
241
248
  /**
242
- * A recorded, traced 1440x900 context. A config identity starts signed in
249
+ * A recorded, traced context: 1440x900, or with `device: 'phone'` a 390x844 touch phone. A config identity starts signed in
243
250
  * from the cached session (no login form is ever recorded); `'anon'` starts
244
251
  * signed out, for public pages. Open at most two per journey.
245
252
  */
@@ -248,11 +255,13 @@ var Journey = class {
248
255
  if (!/^[a-z0-9][a-z0-9-]{0,30}$/.test(label)) throw new Error("context label: lowercase letters, digits and dashes");
249
256
  const storageState = identity === "anon" ? void 0 : (await storageStateFor(this.config, identity, opts)).path;
250
257
  const rawDir = join2(this.rawDir, label);
258
+ const device = opts.device ?? "desktop";
259
+ const size = device === "phone" ? { width: PHONE.width * 2, height: PHONE.height * 2 } : DESKTOP;
251
260
  const context = await this.browser.newContext({
252
261
  baseURL: this.config.baseUrl,
253
262
  storageState,
254
- viewport: DESKTOP,
255
- recordVideo: { dir: rawDir, size: DESKTOP },
263
+ ...device === "phone" ? PHONE_CONTEXT : { viewport: DESKTOP },
264
+ recordVideo: { dir: rawDir, size },
256
265
  locale: "en-US",
257
266
  timezoneId: "America/Denver"
258
267
  });
@@ -275,7 +284,7 @@ var Journey = class {
275
284
  }
276
285
  await context.tracing.start({ screenshots: true, snapshots: true, title: `${this.id} ${label}` });
277
286
  const page = await context.newPage();
278
- this.recorded.push({ label, identity, context, page, t0: Date.now(), rawDir });
287
+ this.recorded.push({ label, identity, device, size, context, page, t0: Date.now(), rawDir });
279
288
  return page;
280
289
  }
281
290
  recordedFor(page) {
@@ -395,22 +404,24 @@ var Journey = class {
395
404
  async shot(name, page, opts = {}) {
396
405
  const r = this.recordedFor(page);
397
406
  const slug = name.replace(/[^a-z0-9-]+/gi, "-").toLowerCase();
398
- const desktop = join2(this.outDir, `${slug}-desktop.png`);
407
+ const own = join2(this.outDir, `${slug}-${r.device}.png`);
399
408
  const cursor = (display) => r.page.evaluate((d) => {
400
409
  const c = document.getElementById("__journey_cursor");
401
410
  if (c) c.style.display = d;
402
411
  }, display).catch(() => {
403
412
  });
404
413
  await cursor("none");
405
- await r.page.screenshot({ path: desktop, fullPage: opts.fullPage ?? false });
406
- this.screenshots.add(desktop);
414
+ await r.page.screenshot({ path: own, fullPage: opts.fullPage ?? false });
415
+ this.screenshots.add(own);
407
416
  await cursor("");
417
+ if (r.device === "phone") return { phone: own };
418
+ const desktop = own;
408
419
  if (opts.phone === false) return { desktop };
409
420
  const phonePath = join2(this.outDir, `${slug}-phone.png`);
410
421
  let ctx = this.phones.get(r.identity);
411
422
  if (!ctx) {
412
423
  const storageState = r.identity === "anon" ? void 0 : (await storageStateFor(this.config, r.identity)).path;
413
- ctx = await this.browser.newContext({ baseURL: this.config.baseUrl, storageState, viewport: PHONE, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: "en-US", timezoneId: "America/Denver" });
424
+ ctx = await this.browser.newContext({ baseURL: this.config.baseUrl, storageState, ...PHONE_CONTEXT, locale: "en-US", timezoneId: "America/Denver" });
414
425
  this.phones.set(r.identity, ctx);
415
426
  }
416
427
  const phone = await ctx.newPage();
@@ -690,6 +701,7 @@ ${reply}${failures}
690
701
  videoDir: join2(this.outDir, "video"),
691
702
  label: r.label,
692
703
  t0: r.t0,
704
+ size: r.size,
693
705
  wallSeconds: (endedAt - r.t0) / 1e3,
694
706
  chapters: this.chapters.filter((c) => c.label === null || c.label === r.label),
695
707
  speedup2x: opts.speedup2x ?? false
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/journeys/journey.ts","../../src/journeys/artifacts.ts","../../src/journeys/page-reading.ts","../../src/journeys/send.ts"],"sourcesContent":["/**\n * One recorded journey through a running agent app: signed-in recorded\n * contexts, chapters, a person's pacing, desktop and phone screenshots,\n * measured chat turns, and a `finish()` that turns the recording into files\n * that are safe to copy off the host.\n *\n * const j = await startJourney('core-path') // reads journeys.config.mjs\n * const page = await j.open('founder', 'member') // recorded, already signed in\n * await j.step('Founder opens the workspace', () => page.goto('/app'), page)\n * await j.shot('home', page) // home-desktop.png + home-phone.png\n * const turn = await j.sendNew(page, 'Research …', { from: `/app/${ws}/chat/new` })\n * await j.finish() // mp4s, srt, highlights, scrubbed trace, timings\n *\n * Output, all safe to copy (finish() refuses otherwise):\n * <outDir>/<id>/video/<label>-full.mp4 <label>-highlights.mp4 <label>.srt <label>-trace.zip\n * <outDir>/<id>/<name>-desktop.png <name>-phone.png timings.json chapters.json turns/*.md\n * Raw webm and unscrubbed traces stay in <stateDir>/raw on the host.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { hostname } from 'node:os'\nimport { join } from 'node:path'\nimport type { Browser, BrowserContext, Locator, Page } from 'playwright'\nimport { pruneJourneyArtifacts } from './artifacts.js'\nimport { loadJourneysConfig, resolveJourneysConfig, threadRouteIn, type JourneysConfig, type ResolvedJourneysConfig, type ThreadRoute } from './config.js'\nimport { promptHead, readChatPage } from './page-reading.js'\nimport { scoreTurn, turnLooksActive, TurnEvidence, type TranscriptSnapshot, type TurnOutcome } from './score.js'\nimport { assertNoSecrets, scrubTrace } from './scrub.js'\nimport { clickUntilSubmitted, composerText, createSubmissionTracker, settleText } from './send.js'\nimport { secretNeedles, storageStateFor } from './session.js'\nimport { postProcessVideo, type Chapter } from './video.js'\n\nexport const DESKTOP = { width: 1440, height: 900 }\nexport const PHONE = { width: 390, height: 844 }\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\nconst secs = (ms: number) => Math.round(ms / 100) / 10\n\n/** A visible pointer so a viewer can follow clicks in a headless recording. Hidden for screenshots. */\nconst CURSOR_SCRIPT = `(() => {\n const install = () => {\n if (document.getElementById('__journey_cursor') || !document.body) return\n const dot = document.createElement('div')\n dot.id = '__journey_cursor'\n dot.setAttribute('aria-hidden', 'true')\n Object.assign(dot.style, { position: 'fixed', zIndex: '2147483647', width: '24px', height: '24px',\n margin: '-12px 0 0 -12px', borderRadius: '50%', background: 'rgba(255,72,48,.28)',\n border: '2px solid rgba(255,72,48,.95)', pointerEvents: 'none', left: (window.__jx ?? -100) + 'px',\n top: (window.__jy ?? -100) + 'px', transition: 'transform .12s ease-out' })\n document.body.appendChild(dot)\n }\n addEventListener('mousemove', (e) => { window.__jx = e.clientX; window.__jy = e.clientY\n const d = document.getElementById('__journey_cursor'); if (d) { d.style.left = e.clientX + 'px'; d.style.top = e.clientY + 'px' } }, true)\n addEventListener('mousedown', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(.55)' }, true)\n addEventListener('mouseup', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(1)' }, true)\n // After hydration, so the framework never meets a node it did not render.\n addEventListener('load', () => setTimeout(install, 1500))\n setInterval(install, 2000)\n})()`\n\ninterface Recorded {\n label: string\n identity: string\n context: BrowserContext\n page: Page\n t0: number\n rawDir: string\n}\n\nexport interface TurnRecord {\n label: string\n prompt: string\n threadId: string | null\n sentAt: string\n /** Seconds from the Send press. */\n firstProgressS: number | null\n firstProgressText: string | null\n firstTextS: number | null\n /** Seconds from Send to the first failure evidence on the page, if any appeared. */\n firstFailureS: number | null\n completeS: number | null\n outcome: TurnOutcome\n /** Plain words for what went wrong, or null for a completed turn. */\n error: string | null\n /** Every piece of failure evidence the turn added. */\n failures: string[]\n /** Where evidence was read: after the turn's own prompt, or the whole transcript when the page did not show the prompt. */\n evidenceScope: 'after-prompt' | 'whole-transcript' | null\n replyChars: number\n /** Distinct status lines the transcript showed, with when they appeared. */\n stages: { s: number; text: string }[]\n /** Seconds from Send at which the journey pressed Stop, if it did. */\n stopPressedS: number | null\n replyFile: string | null\n}\n\nexport interface StepRecord {\n caption: string\n label: string | null\n startS: number\n durationS: number\n ok: boolean\n error?: string\n}\n\nexport interface SendOptions {\n caption?: string\n timeoutMs?: number\n /** Keystroke delay for the prompt. */\n delay?: number\n /** Press Stop at first text, or this many seconds after Send. */\n stopAfter?: 'first-text' | number\n /** Type after what the composer already holds (mention pills, attachments)\n * instead of replacing it. The default select-all-and-delete erased the\n * `@agent` pills of GTM's first agent-mentions runs (2026-10-27). */\n keepDraft?: boolean\n}\n\n/** What the page shows right now, read in one evaluate. */\ninterface PageReading extends TranscriptSnapshot {\n status: string[]\n assistantChars: number\n transcriptChars: number\n stopVisible: boolean\n}\n\nexport class Journey {\n readonly outDir: string\n readonly rawDir: string\n readonly chapters: Chapter[] = []\n readonly steps: StepRecord[] = []\n readonly turns: TurnRecord[] = []\n private recorded: Recorded[] = []\n private phones = new Map<string, BrowserContext>()\n private screenshots = new Set<string>()\n private readonly startedAt = Date.now()\n\n constructor(readonly id: string, readonly config: ResolvedJourneysConfig, readonly browser: Browser, private readonly opts: { cursor: boolean }) {\n this.outDir = join(config.outDir, id)\n this.rawDir = join(config.stateDir, 'raw', `${id}-${new Date().toISOString().replace(/[:.]/g, '-')}`)\n mkdirSync(join(this.outDir, 'video'), { recursive: true })\n mkdirSync(join(this.outDir, 'turns'), { recursive: true })\n mkdirSync(this.rawDir, { recursive: true, mode: 0o700 })\n }\n\n /**\n * A recorded, traced 1440x900 context. A config identity starts signed in\n * from the cached session (no login form is ever recorded); `'anon'` starts\n * signed out, for public pages. Open at most two per journey.\n */\n async open(label: string, identity: string, opts: { fresh?: boolean } = {}): Promise<Page> {\n if (this.recorded.some((r) => r.label === label)) throw new Error(`a context labelled ${label} is already open`)\n if (!/^[a-z0-9][a-z0-9-]{0,30}$/.test(label)) throw new Error('context label: lowercase letters, digits and dashes')\n const storageState = identity === 'anon' ? undefined : (await storageStateFor(this.config, identity, opts)).path\n const rawDir = join(this.rawDir, label)\n const context = await this.browser.newContext({\n baseURL: this.config.baseUrl,\n storageState,\n viewport: DESKTOP,\n recordVideo: { dir: rawDir, size: DESKTOP },\n locale: 'en-US',\n timezoneId: 'America/Denver',\n })\n context.setDefaultTimeout(20_000)\n context.setDefaultNavigationTimeout(60_000)\n if (this.opts.cursor) await context.addInitScript(CURSOR_SCRIPT)\n if (process.env.JOURNEY_DEBUG_CLOCK === '1') {\n // Wall-clock seconds since recording start on every frame, for calibrating captions.\n await context.addInitScript((t0: number) => {\n setInterval(() => {\n let d = document.getElementById('__journey_clock')\n if (!d && document.body) {\n d = document.createElement('div')\n d.id = '__journey_clock'\n Object.assign(d.style, { position: 'fixed', left: '50%', top: '0', zIndex: '2147483647', font: 'bold 20px monospace', background: '#ff0', color: '#000', padding: '2px 6px', pointerEvents: 'none' })\n document.body.appendChild(d)\n }\n if (d) d.textContent = ((Date.now() - t0) / 1000).toFixed(1)\n }, 100)\n }, Date.now())\n }\n await context.tracing.start({ screenshots: true, snapshots: true, title: `${this.id} ${label}` })\n const page = await context.newPage()\n this.recorded.push({ label, identity, context, page, t0: Date.now(), rawDir })\n return page\n }\n\n private recordedFor(page?: Page): Recorded {\n const r = page ? this.recorded.find((x) => x.page === page) : this.recorded[0]\n if (!r) throw new Error('no recorded context for that page; call open() first')\n return r\n }\n\n /** A chapter at this instant: one plain line, shown in the caption bar and the .srt. */\n mark(caption: string, page?: Page): void {\n const label = page ? this.recordedFor(page).label : null\n this.chapters.push({ at: Date.now(), caption, label, kind: 'step' })\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}${caption}`)\n }\n\n /** A timed step with its own chapter. A failure is recorded, captioned, then rethrown. */\n async step<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n this.mark(caption, page)\n const start = Date.now()\n const entry: StepRecord = { caption, label: page ? this.recordedFor(page).label : null, startS: secs(start - this.startedAt), durationS: 0, ok: true }\n this.steps.push(entry)\n try {\n return await work()\n } catch (error) {\n entry.ok = false\n entry.error = String((error as Error)?.message ?? error).slice(0, 400)\n this.mark(`Step failed: ${caption}`, page)\n throw error\n } finally {\n entry.durationS = secs(Date.now() - start)\n }\n }\n\n /** A waiting span: real speed in the full video, sped up and labelled in the highlights. */\n async wait<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n const label = page ? this.recordedFor(page).label : null\n const chapter: Chapter = { at: Date.now(), caption, label, kind: 'wait', until: Date.now() }\n this.chapters.push(chapter)\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}(wait) ${caption}`)\n try {\n return await work()\n } finally {\n chapter.until = Date.now()\n }\n }\n\n pause(ms = 700): Promise<void> {\n return sleep(ms)\n }\n\n /** Move the visible pointer there, pause, click, pause. */\n async click(target: Locator, opts: { pauseAfter?: number } = {}): Promise<void> {\n await target.scrollIntoViewIfNeeded()\n const box = await target.boundingBox()\n if (box) await target.page().mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(250)\n await target.click()\n await sleep(opts.pauseAfter ?? 600)\n }\n\n /** Type at a readable pace into an input or textarea. */\n async type(target: Locator, text: string, opts: { delay?: number } = {}): Promise<void> {\n await this.click(target, { pauseAfter: 200 })\n const delay = opts.delay ?? 28\n await target.pressSequentially(text, { delay, timeout: 30_000 + text.length * (delay + 60) })\n await sleep(400)\n }\n\n /** The composer's message input. */\n composerInput(page: Page): Locator {\n return page.locator(this.config.chat.composer).getByRole('textbox', { name: this.config.chat.inputName })\n }\n\n private composerButton(page: Page, name: string): Locator {\n return page.locator(this.config.chat.composer).getByRole('button', { name, exact: true })\n }\n\n /**\n * Type into the chat composer at a readable pace. A line break is typed as\n * Shift+Enter, because Enter sends. Retries fast when hydration dropped\n * keystrokes. Never `fill()` a rich-text composer.\n */\n async typePrompt(page: Page, prompt: string, opts: { delay?: number; keepDraft?: boolean } = {}): Promise<void> {\n const box = this.composerInput(page)\n await box.waitFor({ state: 'visible', timeout: 30_000 })\n await sleep(1_200)\n const delay = opts.delay ?? (prompt.length > 400 ? 8 : 22)\n const want = prompt.replace(/\\s+/g, ' ').trim().slice(0, 80)\n for (let attempt = 0; attempt < 4; attempt += 1) {\n await this.click(box, { pauseAfter: 150 })\n if (opts.keepDraft) {\n await box.press('ControlOrMeta+End')\n } else {\n await box.press('ControlOrMeta+a')\n await box.press('Backspace')\n }\n const lines = prompt.split('\\n')\n for (let i = 0; i < lines.length; i += 1) {\n if (i > 0) await box.press('Shift+Enter')\n // Sized by length: a loaded host types slower than the context's 20 s default allows.\n const line = lines[i]!\n if (line) await box.pressSequentially(line, { delay: attempt === 0 ? delay : 0, timeout: 30_000 + line.length * (delay + 60) })\n }\n const text = (await composerText(box).catch(() => '')).replace(/\\s+/g, ' ').trim()\n if (text.includes(want)) return\n await sleep(1_000)\n }\n throw new Error('the composer never held the prompt')\n }\n\n /**\n * Which parts of the chat contract this page shows, without sending\n * anything. Run it on a second app before trusting turn timings there.\n */\n async checkChatContract(page: Page): Promise<Record<'transcript' | 'composer' | 'input' | 'send', boolean>> {\n const visible = (l: Locator) => l.first().isVisible().catch(() => false)\n return {\n transcript: await visible(page.locator(this.config.chat.transcript)),\n composer: await visible(page.locator(this.config.chat.composer)),\n input: await visible(this.composerInput(page)),\n send: await visible(this.composerButton(page, this.config.chat.sendName)),\n }\n }\n\n /**\n * Desktop screenshot of the recorded page, then the same URL in a phone\n * context (390x844, same identity). Look at both before judging the screen.\n */\n async shot(name: string, page?: Page, opts: { phone?: boolean; fullPage?: boolean; phoneUrl?: string } = {}): Promise<{ desktop: string; phone?: string }> {\n const r = this.recordedFor(page)\n const slug = name.replace(/[^a-z0-9-]+/gi, '-').toLowerCase()\n const desktop = join(this.outDir, `${slug}-desktop.png`)\n const cursor = (display: string) => r.page.evaluate((d) => { const c = document.getElementById('__journey_cursor'); if (c) c.style.display = d }, display).catch(() => {})\n await cursor('none')\n await r.page.screenshot({ path: desktop, fullPage: opts.fullPage ?? false })\n this.screenshots.add(desktop)\n await cursor('')\n if (opts.phone === false) return { desktop }\n const phonePath = join(this.outDir, `${slug}-phone.png`)\n let ctx = this.phones.get(r.identity)\n if (!ctx) {\n const storageState = r.identity === 'anon' ? undefined : (await storageStateFor(this.config, r.identity)).path\n ctx = await this.browser.newContext({ baseURL: this.config.baseUrl, storageState, viewport: PHONE, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: 'en-US', timezoneId: 'America/Denver' })\n this.phones.set(r.identity, ctx)\n }\n const phone = await ctx.newPage()\n try {\n await phone.goto(opts.phoneUrl ?? r.page.url(), { waitUntil: 'load' })\n await phone.waitForLoadState('networkidle', { timeout: 8_000 }).catch(() => {})\n await sleep(1_500)\n await phone.screenshot({ path: phonePath, fullPage: opts.fullPage ?? false })\n this.screenshots.add(phonePath)\n } finally {\n await phone.close()\n }\n return { desktop, phone: phonePath }\n }\n\n private budgetTurn(): void {\n if (this.turns.length >= this.config.maxTurns) {\n throw new Error(`this journey already sent ${this.turns.length} chat turns, its budget (maxTurns ${this.config.maxTurns})`)\n }\n }\n\n /**\n * Start a new thread: open `from` when given, type the prompt, press Send\n * like a person (again only while the page has not submitted; never deletes\n * a duplicate), wait for the thread, then measure the turn.\n */\n async sendNew(page: Page, prompt: string, opts: SendOptions & { from?: string } = {}): Promise<TurnRecord> {\n this.budgetTurn()\n if (opts.from && !page.url().startsWith(new URL(opts.from, this.config.baseUrl).href)) await page.goto(opts.from)\n await this.typePrompt(page, prompt, { delay: opts.delay, keepDraft: opts.keepDraft })\n const send = this.composerButton(page, this.config.chat.sendName)\n await send.waitFor({ state: 'visible' })\n const box = await send.boundingBox()\n if (box) await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(400)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const count = (request: { method(): string; url(): string }) => tracker.observe(request.method(), request.url())\n page.on('request', count)\n this.mark(opts.caption ?? `Sends: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n const onThread = () => threadRouteIn(page.url(), this.config) !== null\n try {\n await clickUntilSubmitted({\n landed: () => tracker.count > 0 || onThread(),\n ready: () => send.click({ trial: true, timeout: 5_000 }),\n click: () => send.click({ timeout: 5_000 }),\n wait: () => page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 1_000 }).then(() => undefined).catch(() => undefined),\n attempts: 15,\n })\n if (this.config.chat.threadPath) await page.waitForURL((url) => threadRouteIn(url.href, this.config) !== null, { timeout: 45_000 })\n } catch (error) {\n return this.notSent(page, prompt, sentAt, String((error as Error).message).slice(0, 300))\n } finally {\n page.off('request', count)\n }\n if (tracker.count > 1) console.warn(`the composer submitted ${tracker.count} times; a duplicate thread may exist (left in place)`)\n return this.measureTurn(page, prompt, sentAt, evidence, before, 0, opts)\n }\n\n /** A follow-up in the open thread: type, one Send press, measure. */\n async sendInThread(page: Page, prompt: string, opts: SendOptions = {}): Promise<TurnRecord> {\n this.budgetTurn()\n await this.typePrompt(page, prompt, { delay: opts.delay, keepDraft: opts.keepDraft })\n const send = this.composerButton(page, this.config.chat.sendName)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const posted = page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 30_000 })\n this.mark(opts.caption ?? `Follows up: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n await this.click(send, { pauseAfter: 0 })\n const sent = await posted.then(() => true).catch(() => false)\n if (!sent) return this.notSent(page, prompt, sentAt, 'no chat request within 30 s of pressing Send')\n return this.measureTurn(page, prompt, sentAt, evidence, before, Math.max(0, before.assistantChars), opts)\n }\n\n private patterns() {\n return { failure: this.config.chat.failureText, stopped: this.config.chat.stoppedText }\n }\n\n private blankTurn(page: Page, prompt: string, sentAt: number): TurnRecord {\n return {\n label: this.recordedFor(page).label, prompt, threadId: threadRouteIn(page.url(), this.config)?.threadId ?? null,\n sentAt: new Date(sentAt).toISOString(), firstProgressS: null, firstProgressText: null, firstTextS: null, firstFailureS: null, completeS: null,\n outcome: 'timeout', error: null, failures: [], evidenceScope: null, replyChars: 0, stages: [], stopPressedS: null, replyFile: null,\n }\n }\n\n private notSent(page: Page, prompt: string, sentAt: number, why: string): TurnRecord {\n const t = { ...this.blankTurn(page, prompt, sentAt), ...scoreTurn({ notSent: why, timedOut: false, evidence: { failures: [], stopped: [], retryAppeared: false }, replyChars: 0, stopPressed: false }) }\n this.turns.push(t)\n this.mark(`Turn not sent: ${oneLine(why, 90)}`, page)\n return t\n }\n\n /** One read of the transcript, composer and failure marks; with a prompt, the evidence that follows it. */\n private async read(page: Page, prompt: string | null = null): Promise<PageReading> {\n const c = this.config.chat\n const { assistant, ...reading } = await page.evaluate(readChatPage, {\n transcript: c.transcript, status: c.status, failureNodes: c.failureNodes, retrySource: c.retryName.source, retryFlags: c.retryName.flags,\n assistant: c.assistant, composer: c.composer, stopName: c.stopName, promptHead: prompt === null ? null : promptHead(prompt),\n })\n return { ...reading, assistantChars: assistant }\n }\n\n private async runningTurns(page: Page, route: ThreadRoute | null): Promise<string[] | null> {\n if (!route || !this.config.chat.runningTurns) return null\n const res = await page.request.get(this.config.chat.runningTurns(route))\n if (!res.ok()) throw new Error(`running turns answered ${res.status()}`)\n const body = (await res.json()) as { running?: unknown }\n if (!Array.isArray(body.running)) throw new Error('running turns returned no `running` array')\n return body.running.map(String)\n }\n\n /**\n * Time to first visible progress (a new status line or reply text), first\n * reply text, and the turn's end, polled every 300 ms. Failure evidence is\n * read after the turn's own prompt when the page shows it. The turn has ended\n * when, for two reads in a row, {@link turnLooksActive} is false and, where\n * the app lists running turns, the server lists none. Status lines already\n * on the page before Send are not progress. The outcome comes from\n * {@link scoreTurn}.\n */\n private async measureTurn(page: Page, prompt: string, sentAt: number, evidence: TurnEvidence, before: PageReading, baselineChars: number, opts: SendOptions): Promise<TurnRecord> {\n const t = this.blankTurn(page, prompt, sentAt)\n this.turns.push(t)\n const route = threadRouteIn(page.url(), this.config)\n t.threadId = route?.threadId ?? null\n const timeoutMs = opts.timeoutMs ?? 15 * 60_000\n const since = () => secs(Date.now() - sentAt)\n const standingStatus = new Set(before.status)\n // Without an assistant selector, reply text is transcript growth from the\n // first read after Send (the person's own message is on the page by then).\n let growthBase: number | null = null\n let growth = 0\n let sawActive = false\n let quiet = 0\n let lastServerCheck = 0\n let serverRunning: string[] | null = null\n let lastStage = ''\n let lastStatus = ''\n let statusChangedAt = Date.now()\n let finished = false\n await this.wait('Waiting for the agent', async () => {\n while (Date.now() - sentAt < timeoutMs) {\n const s = await this.read(page, prompt).catch(() => null)\n if (s) {\n t.evidenceScope = s.anchored ? 'after-prompt' : 'whole-transcript'\n const shown = evidence.observe(s)\n if (shown.length) {\n t.firstFailureS ??= since()\n this.mark(`Failure shown after ${since()} s: ${oneLine(shown[0]!, 90)}`, page)\n }\n const status = s.status.filter((line) => !standingStatus.has(line))\n growthBase ??= s.transcriptChars\n const chars = s.assistantChars >= 0 ? s.assistantChars - baselineChars : s.transcriptChars - growthBase - status.join(' ').length\n growth = Math.max(growth, chars)\n const stage = status.join(' | ').replace(/\\b\\d+(\\.\\d+)?\\s?s\\b/g, '').trim()\n if (stage && stage !== lastStage) {\n t.stages.push({ s: since(), text: status.join(' | ').slice(0, 160) })\n lastStage = stage\n }\n // Raw text, timers included: a ticking \"Preparing your workspace… 31s\" is changing.\n if (status.join(' | ') !== lastStatus) {\n lastStatus = status.join(' | ')\n statusChangedAt = Date.now()\n }\n if (t.firstProgressS === null && (status.length || chars > 0)) {\n t.firstProgressS = since()\n t.firstProgressText = status[0] ?? 'reply text'\n this.mark(`First visible progress after ${t.firstProgressS} s: ${oneLine(t.firstProgressText, 70)}`, page)\n }\n if (t.firstTextS === null && chars > 0) {\n t.firstTextS = since()\n this.mark(`First text after ${t.firstTextS} s`, page)\n }\n const stopDue = opts.stopAfter === 'first-text' ? t.firstTextS !== null : typeof opts.stopAfter === 'number' && since() >= opts.stopAfter\n if (t.stopPressedS === null && stopDue && s.stopVisible) {\n t.stopPressedS = since()\n this.mark(`Presses Stop after ${t.stopPressedS} s`, page)\n await this.click(this.composerButton(page, this.config.chat.stopName), { pauseAfter: 200 }).catch((e) => console.warn(`Stop press failed: ${e}`))\n }\n if (status.length > 0) sawActive = true\n const active = turnLooksActive({ stopVisible: s.stopVisible, statusLines: status.length, msSinceStatusChanged: Date.now() - statusChangedAt })\n quiet = active ? 0 : quiet + 1\n }\n if (route && this.config.chat.runningTurns && Date.now() - lastServerCheck > 2_000) {\n lastServerCheck = Date.now()\n // A failed read never implies the turn ended.\n serverRunning = await this.runningTurns(page, route).catch(() => serverRunning)\n if (serverRunning?.length) sawActive = true\n }\n const started = sawActive || t.firstTextS !== null || Date.now() - sentAt > 45_000\n const serverDone = !this.config.chat.runningTurns || !route || serverRunning?.length === 0\n if (started && quiet >= 2 && serverDone) {\n finished = true\n return\n }\n await sleep(300)\n }\n }, page)\n t.completeS = finished ? since() : null\n // Render lag only: the turn has ended, so wait for the transcript to stop changing before judging it.\n await settleText(() => this.read(page, prompt).then((r) => `${r.transcriptChars}:${r.failureNodes.length}:${r.retryButtons}`))\n const last = await this.read(page, prompt)\n t.evidenceScope = last.anchored ? 'after-prompt' : 'whole-transcript'\n evidence.observe(last)\n const finalText = this.config.chat.assistant ? await this.replyText(page) : ''\n t.replyChars = this.config.chat.assistant ? Math.max(0, finalText.length - baselineChars) : Math.max(0, growth)\n Object.assign(t, scoreTurn({ timedOut: !finished, evidence: evidence.added(), replyChars: t.replyChars, stopPressed: t.stopPressedS !== null }))\n const n = this.turns.length\n t.replyFile = join('turns', `${String(n).padStart(2, '0')}-${t.label}.md`)\n const reply = this.config.chat.assistant ? finalText.slice(baselineChars).trim() : '(this app configures no assistant selector; read the reply in the video or the trace)'\n const failures = t.failures.length ? `\\n\\n## Failure evidence\\n\\n${t.failures.map((f) => `- ${f}`).join('\\n')}` : ''\n writeFileSync(join(this.outDir, t.replyFile), `# Turn ${n} (${t.label})\\n\\n## Prompt\\n\\n${prompt}\\n\\n## Reply (${t.outcome})\\n\\n${reply}${failures}\\n`)\n this.mark(\n t.outcome === 'completed'\n ? `Turn complete after ${t.completeS} s (${t.replyChars} chars)`\n : `Turn ${t.outcome.toUpperCase()} after ${t.completeS ?? since()} s${t.error ? `: ${oneLine(t.error, 80)}` : ''}`,\n page,\n )\n return t\n }\n\n private async replyText(page: Page): Promise<string> {\n const sel = this.config.chat.assistant\n if (!sel) return ''\n return settleText(async () => (await page.locator(sel).allInnerTexts()).join('\\n').trim())\n }\n\n /**\n * Close everything, then per context: a captioned full .mp4, a highlights cut\n * (at most 178 s, long waits sped up and labelled), an .srt and a scrubbed\n * trace.zip; plus timings.json and chapters.json. Refuses (throws) when any\n * output file still holds a password or cookie value.\n */\n async finish(opts: { speedup2x?: boolean } = {}): Promise<{ outDir: string; files: string[] }> {\n for (const ctx of this.phones.values()) await ctx.close().catch(() => {})\n const files: string[] = []\n // Stop every recording first, so one context's video does not run on through another's processing.\n const stopped: { r: Recorded; rawTrace: string; webm: string | null; endedAt: number }[] = []\n for (const r of this.recorded) {\n const endedAt = Date.now()\n const rawTrace = join(r.rawDir, 'trace.raw.zip')\n await r.context.tracing.stop({ path: rawTrace }).catch((e) => console.warn(`tracing.stop failed for ${r.label}: ${e}`))\n const video = r.page.video()\n await r.context.close()\n stopped.push({ r, rawTrace, webm: video ? await video.path().catch(() => null) : null, endedAt })\n }\n const needles = secretNeedles(this.config)\n for (const { r, rawTrace, webm, endedAt } of stopped) {\n if (webm) {\n files.push(...postProcessVideo({\n webm, workDir: r.rawDir, videoDir: join(this.outDir, 'video'), label: r.label, t0: r.t0,\n wallSeconds: (endedAt - r.t0) / 1000, chapters: this.chapters.filter((c) => c.label === null || c.label === r.label),\n speedup2x: opts.speedup2x ?? false,\n }))\n }\n try {\n const clean = join(this.outDir, 'video', `${r.label}-trace.zip`)\n const result = scrubTrace(rawTrace, clean, [...needles.hard, ...needles.soft])\n console.log(`trace ${r.label}: ${result.entries} entries, ${result.dropped} sensitive bodies dropped, ${result.rewritten} rewritten`)\n files.push(clean)\n } catch (error) {\n console.warn(`trace ${r.label} not written: ${(error as Error).message}`)\n }\n }\n writeFileSync(join(this.outDir, 'chapters.json'), JSON.stringify(this.chapters.map((c) => ({ ...c, at: new Date(c.at).toISOString(), until: c.until ? new Date(c.until).toISOString() : undefined, offsetS: secs(c.at - this.startedAt) })), null, 2))\n writeFileSync(join(this.outDir, 'timings.json'), JSON.stringify({ journey: this.id, app: this.config.app, base: this.config.baseUrl, startedAt: new Date(this.startedAt).toISOString(), wallS: secs(Date.now() - this.startedAt), steps: this.steps, turns: this.turns }, null, 2))\n await this.browser.close()\n assertNoSecrets(this.outDir, needles)\n pruneJourneyArtifacts(this.outDir, new Set([\n ...files,\n ...this.screenshots,\n ...this.turns.flatMap((turn) => turn.replyFile ? [join(this.outDir, turn.replyFile)] : []),\n ]))\n console.log(`\\n${this.id}: ${this.steps.length} steps, ${this.turns.length} turns, wall ${secs(Date.now() - this.startedAt)} s`)\n for (const t of this.turns) {\n console.log(` turn[${t.label}] ${t.outcome}: progress ${t.firstProgressS ?? '-'} s, first text ${t.firstTextS ?? '-'} s, end ${t.completeS ?? '-'} s, ${t.replyChars} chars${t.error ? ` | ${oneLine(t.error, 100)}` : ''}`)\n }\n const host = process.env.JOURNEYS_HOST_ALIAS ?? hostname()\n console.log(`output: ${this.outDir}\\ncopy it (run where you will watch it):\\n rsync -a ${host}:${this.outDir}/ \"<dest>/${this.id}/\"`)\n return { outDir: this.outDir, files }\n }\n}\n\nexport function oneLine(text: string, max: number): string {\n const s = text.replace(/\\s+/g, ' ').trim()\n return s.length > max ? `${s.slice(0, max - 1)}…` : s\n}\n\n/** Open a journey. Without `config`, reads `journeys.config.mjs` from the working directory. */\nexport async function startJourney(id: string, opts: { config?: JourneysConfig | ResolvedJourneysConfig; cursor?: boolean; headless?: boolean } = {}): Promise<Journey> {\n if (!/^[a-z0-9][a-z0-9-]{1,60}$/.test(id)) throw new Error('journey id: lowercase letters, digits and dashes')\n const config = opts.config ? resolveJourneysConfig(opts.config) : await loadJourneysConfig()\n let chromium\n try {\n chromium = (await import('playwright')).chromium\n } catch {\n throw new Error('journeys need the optional `playwright` peer: install playwright in the app that runs them')\n }\n const browser = await chromium.launch({ headless: opts.headless ?? true })\n return new Journey(id, config, browser, { cursor: opts.cursor ?? true })\n}\n","import { readdirSync, rmSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nconst groups = [\n {\n directory: '',\n owns: (name: string) => name.endsWith('-desktop.png') || name.endsWith('-phone.png'),\n },\n {\n directory: 'video',\n owns: (name: string) => name.endsWith('.mp4') || name.endsWith('.srt') || name.endsWith('-trace.zip'),\n },\n {\n directory: 'turns',\n owns: (name: string) => name.endsWith('.md'),\n },\n] as const\n\nexport function pruneJourneyArtifacts(outDir: string, retained: ReadonlySet<string>): void {\n const keep = new Set([...retained].map((file) => resolve(file)))\n for (const group of groups) {\n const directory = join(resolve(outDir), group.directory)\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if ((!entry.isFile() && !entry.isSymbolicLink()) || !group.owns(entry.name)) continue\n const file = join(directory, entry.name)\n if (!keep.has(file)) rmSync(file)\n }\n }\n}\n","/**\n * The one read of a chat page a journey takes every 300 ms, run inside the page\n * by `page.evaluate`, so it must stay self-contained: DOM globals only, no\n * imports and no module-scope names.\n *\n * Failure evidence belongs to the turn whose prompt it follows. On 2026-10-11\n * GTM showed a live Stop as a grey notice, then, when the next message was\n * sent, re-rendered the stopped turn with its red \"You stopped this turn.\" card\n * and a Retry control, above the new message. Read from the whole transcript,\n * that card failed the follow-up, which had answered in 28.5 s. So when the\n * transcript shows the turn's own prompt, only failure marks, Retry controls\n * and lines after it count; when it does not, the whole transcript does.\n */\n\ninterface PageReadArgs {\n readonly transcript: string\n readonly status: string\n readonly failureNodes: string\n readonly retrySource: string\n readonly retryFlags: string\n readonly assistant: string | null\n readonly composer: string\n readonly stopName: string\n /** The turn's prompt as {@link promptHead} gives it; null reads the whole transcript. */\n readonly promptHead: string | null\n}\n\ninterface RawPageReading {\n /** Visible transcript lines (after the turn's prompt when `anchored`). */\n lines: string[]\n failureNodes: string[]\n retryButtons: number\n status: string[]\n /** Characters of assistant text on the page, or -1 with no assistant selector. */\n assistant: number\n transcriptChars: number\n stopVisible: boolean\n /** The turn's prompt was found, so the evidence fields hold only what follows it. */\n anchored: boolean\n}\n\n/** The text a transcript shows for a prompt: its first line, whitespace squashed, at most 48 characters. */\nexport function promptHead(prompt: string): string | null {\n const first = prompt.split('\\n').map((line) => line.replace(/\\s+/g, ' ').trim()).find(Boolean)\n return first ? first.slice(0, 48) : null\n}\n\nexport function readChatPage(c: PageReadArgs): RawPageReading {\n const squash = (s: string) => s.replace(/\\s+/g, ' ').trim()\n const clean = (e: Element) => squash(e.textContent ?? '')\n const region = document.querySelector<HTMLElement>(c.transcript)\n const composer = document.querySelector<HTMLElement>(c.composer)\n const assistantNodes = c.assistant ? Array.from(document.querySelectorAll<HTMLElement>(c.assistant)) : []\n const within = (sel: string) => (region ? Array.from(region.querySelectorAll(sel)) : [])\n\n // The last text node outside the composer and the assistant's own text that holds the prompt.\n let anchor: Node | null = null\n if (region && c.promptHead) {\n const walker = document.createTreeWalker(region, NodeFilter.SHOW_TEXT)\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n if (!squash(node.nodeValue ?? '').includes(c.promptHead)) continue\n if (composer?.contains(node) || assistantNodes.some((a) => a.contains(node))) continue\n anchor = node\n }\n }\n const after = (e: Element) => anchor === null || (anchor.compareDocumentPosition(e) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0\n\n const full = region?.innerText ?? ''\n let text = full\n const composerText = composer && region?.contains(composer) ? composer.innerText.trim() : ''\n if (composerText) {\n const at = text.lastIndexOf(composerText)\n if (at >= 0) text = text.slice(0, at) + text.slice(at + composerText.length)\n }\n let lines = text.split('\\n').map((l) => l.trim()).filter(Boolean)\n if (anchor && c.promptHead) {\n // The same rule for lines: the last one holding the prompt that is not the assistant's.\n const replyLines = new Set(assistantNodes.flatMap((a) => a.innerText.split('\\n').map(squash)))\n let last = -1\n for (let i = 0; i < lines.length; i += 1) {\n const line = squash(lines[i]!)\n if (line.includes(c.promptHead) && !replyLines.has(line)) last = i\n }\n lines = lines.slice(last + 1)\n }\n\n const status = within(c.status).map(clean).filter(Boolean)\n // textContent, not innerText: a failure's collapsed details (the code) count too.\n const failureNodes = within(c.failureNodes).filter(after).map(clean).filter(Boolean)\n const retry = new RegExp(c.retrySource, c.retryFlags)\n const retryButtons = within('button').filter((b) => after(b) && retry.test((b.getAttribute('aria-label') ?? b.textContent ?? '').trim())).length\n const assistant = c.assistant ? assistantNodes.map((e) => e.innerText).join('\\n').trim().length : -1\n const stopVisible = composer !== null && Array.from(composer.querySelectorAll('button')).some((b) =>\n (b.getAttribute('aria-label') ?? b.textContent ?? '').trim() === c.stopName && b.getClientRects().length > 0)\n return { lines, failureNodes, retryButtons, status, assistant, transcriptChars: full.trim().length, stopVisible, anchored: anchor !== null }\n}\n","/**\n * Pressing Send like a person, exactly as often as it takes and never once more.\n *\n * A new-chat composer can drop a press while its model selection is still\n * resolving, and its Send control is not disabled while that gate is shut, so\n * one press can be a silent no-op and a retry is necessary. A retry is also\n * dangerous: the press creates a thread, so a press after the page has already\n * submitted asks for a second one. Pure, so the rule is a unit test.\n */\n\n/** Paths a submission from `routePath` lands on: the route itself and its single-fetch `.data` form. */\nexport function routeSubmitPaths(routePath: string): string[] {\n const singleFetch = routePath.endsWith('/') ? `${routePath}_.data` : `${routePath}.data`\n return [routePath, singleFetch]\n}\n\nexport interface SubmissionTracker {\n /** Whether one request is a submission from the tracked page. */\n matches(method: string, url: string): boolean\n observe(method: string, url: string): void\n /** Submissions seen so far. Above zero means the turn is on its way. */\n readonly count: number\n}\n\n/**\n * Counts submissions from the page at `routeUrl`: a POST to that route (or its\n * `.data` form), or to one of `sendPaths`, on the same origin. A POST to the\n * same path on another origin is not this composer's.\n */\nexport function createSubmissionTracker(routeUrl: string, sendPaths: readonly RegExp[]): SubmissionTracker {\n if (!/^https?:\\/\\//i.test(routeUrl)) throw new Error(`createSubmissionTracker needs the page's full URL, got \"${routeUrl}\"`)\n const route = new URL(routeUrl)\n const exact = new Set(routeSubmitPaths(route.pathname))\n let count = 0\n const matches = (method: string, url: string): boolean => {\n if (method !== 'POST') return false\n let parsed: URL\n try {\n parsed = new URL(url, route.origin)\n } catch {\n return false\n }\n if (parsed.origin !== route.origin) return false\n return exact.has(parsed.pathname) || sendPaths.some((p) => p.test(parsed.pathname))\n }\n return {\n matches,\n observe(method, url) {\n if (matches(method, url)) count += 1\n },\n get count() {\n return count\n },\n }\n}\n\nexport interface SendDriveOps {\n /** True once a submission, or the navigation it causes, has been observed. */\n landed: () => boolean\n /** Wait until Send can take a press, without pressing it. */\n ready: () => Promise<void>\n click: () => Promise<void>\n /** Pause between presses, spent watching for the submission. */\n wait: () => Promise<void>\n attempts: number\n}\n\n/**\n * Press until the page submits. Each attempt waits for the control first and\n * takes its last look at `landed()` after that wait, so the press itself is the\n * only unguarded moment. A click failure is tolerated only once something has\n * landed: an accepted send tears the composer down mid-press.\n */\nexport async function clickUntilSubmitted(ops: SendDriveOps): Promise<void> {\n for (let attempt = 0; attempt < ops.attempts; attempt += 1) {\n if (ops.landed()) return\n try {\n await ops.ready()\n if (ops.landed()) return\n await ops.click()\n } catch (cause) {\n if (!ops.landed()) throw cause\n }\n if (ops.landed()) return\n await ops.wait()\n }\n if (ops.landed()) return\n throw new Error(`Send never submitted: the composer refused ${ops.attempts} presses`)\n}\n\n/**\n * Read until the value stops changing: six identical reads 500 ms apart. Every\n * caller has already seen the turn finish, so this covers render lag only.\n */\nexport async function settleText(\n read: () => Promise<string>,\n wait: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n timeoutMs = 20_000,\n): Promise<string> {\n const deadline = Date.now() + timeoutMs\n let previous: string | null = null\n let stable = 0\n for (;;) {\n const current = await read().catch(() => null)\n if (current === null) {\n stable = 0\n } else {\n stable = current === previous ? stable + 1 : 1\n previous = current\n if (stable >= 6) return current\n }\n if (Date.now() >= deadline) return previous ?? ''\n await wait(500)\n }\n}\n\n/**\n * The text a composer holds. A `<textarea>` or `<input>` (agent-app's own\n * ChatComposer) keeps typed text in `.value` and leaves `innerText` empty; a\n * contenteditable composer keeps it in `innerText`. Reading only `innerText`\n * failed every first chat turn on the default composer (Casework C1/C5).\n */\nexport async function composerText(box: { evaluate<R>(fn: (el: Element) => R): Promise<R> }): Promise<string> {\n return box.evaluate((el) => {\n const field = el as Element & { value?: unknown; innerText?: string }\n return typeof field.value === 'string' ? field.value : (field.innerText ?? el.textContent ?? '')\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,SAAS,WAAW,qBAAqB;AACzC,SAAS,gBAAgB;AACzB,SAAS,QAAAA,aAAY;;;ACpBrB,SAAS,aAAa,cAAc;AACpC,SAAS,MAAM,eAAe;AAE9B,IAAM,SAAS;AAAA,EACb;AAAA,IACE,WAAW;AAAA,IACX,MAAM,CAAC,SAAiB,KAAK,SAAS,cAAc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AAAA,EAC9G;AACA,QAAM,UAAU,MAAM,SAAS,OAAO,EAAE,UAAU,KAAK,YAAY,KAAK,CAAC;AACzE,SAAO,IAAI,QAAQ,IAAI,QAAQ,SAAS,EAAE,QAAQ,KAAK,UAAU,KAAK,CAAC;AACzE;","names":["join","composerText","resolve","resolve","join"]}
1
+ {"version":3,"sources":["../../src/journeys/journey.ts","../../src/journeys/artifacts.ts","../../src/journeys/page-reading.ts","../../src/journeys/send.ts"],"sourcesContent":["/**\n * One recorded journey through a running agent app: signed-in recorded\n * contexts, chapters, a person's pacing, desktop and phone screenshots,\n * measured chat turns, and a `finish()` that turns the recording into files\n * that are safe to copy off the host.\n *\n * const j = await startJourney('core-path') // reads journeys.config.mjs\n * const page = await j.open('founder', 'member') // recorded, already signed in\n * await j.step('Founder opens the workspace', () => page.goto('/app'), page)\n * await j.shot('home', page) // home-desktop.png + home-phone.png\n * const turn = await j.sendNew(page, 'Research …', { from: `/app/${ws}/chat/new` })\n * await j.finish() // mp4s, srt, highlights, scrubbed trace, timings\n *\n * Output, all safe to copy (finish() refuses otherwise):\n * <outDir>/<id>/video/<label>-full.mp4 <label>-highlights.mp4 <label>.srt <label>-trace.zip\n * <outDir>/<id>/<name>-desktop.png <name>-phone.png timings.json chapters.json turns/*.md\n * Raw webm and unscrubbed traces stay in <stateDir>/raw on the host.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { hostname } from 'node:os'\nimport { join } from 'node:path'\nimport type { Browser, BrowserContext, Locator, Page } from 'playwright'\nimport { pruneJourneyArtifacts } from './artifacts.js'\nimport { loadJourneysConfig, resolveJourneysConfig, threadRouteIn, type JourneysConfig, type ResolvedJourneysConfig, type ThreadRoute } from './config.js'\nimport { promptHead, readChatPage } from './page-reading.js'\nimport { scoreTurn, turnLooksActive, TurnEvidence, type TranscriptSnapshot, type TurnOutcome } from './score.js'\nimport { assertNoSecrets, scrubTrace } from './scrub.js'\nimport { clickUntilSubmitted, composerText, createSubmissionTracker, settleText } from './send.js'\nimport { secretNeedles, storageStateFor } from './session.js'\nimport { postProcessVideo, type Chapter } from './video.js'\n\nexport const DESKTOP = { width: 1440, height: 900 }\nexport const PHONE = { width: 390, height: 844 }\n/** One phone for recorded journeys and phone screenshots: a mobile Chrome on a 390x844 touch screen at 2x. */\nconst PHONE_CONTEXT = {\n viewport: PHONE, deviceScaleFactor: 2, isMobile: true, hasTouch: true,\n userAgent: 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Mobile Safari/537.36',\n}\nexport type JourneyDevice = 'desktop' | 'phone'\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\nconst secs = (ms: number) => Math.round(ms / 100) / 10\n\n/** A visible pointer so a viewer can follow clicks in a headless recording. Hidden for screenshots. */\nconst CURSOR_SCRIPT = `(() => {\n const install = () => {\n if (document.getElementById('__journey_cursor') || !document.body) return\n const dot = document.createElement('div')\n dot.id = '__journey_cursor'\n dot.setAttribute('aria-hidden', 'true')\n Object.assign(dot.style, { position: 'fixed', zIndex: '2147483647', width: '24px', height: '24px',\n margin: '-12px 0 0 -12px', borderRadius: '50%', background: 'rgba(255,72,48,.28)',\n border: '2px solid rgba(255,72,48,.95)', pointerEvents: 'none', left: (window.__jx ?? -100) + 'px',\n top: (window.__jy ?? -100) + 'px', transition: 'transform .12s ease-out' })\n document.body.appendChild(dot)\n }\n addEventListener('mousemove', (e) => { window.__jx = e.clientX; window.__jy = e.clientY\n const d = document.getElementById('__journey_cursor'); if (d) { d.style.left = e.clientX + 'px'; d.style.top = e.clientY + 'px' } }, true)\n addEventListener('mousedown', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(.55)' }, true)\n addEventListener('mouseup', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(1)' }, true)\n // After hydration, so the framework never meets a node it did not render.\n addEventListener('load', () => setTimeout(install, 1500))\n setInterval(install, 2000)\n})()`\n\ninterface Recorded {\n label: string\n identity: string\n device: JourneyDevice\n /** The recorded video's frame size. */\n size: { width: number; height: number }\n context: BrowserContext\n page: Page\n t0: number\n rawDir: string\n}\n\nexport interface TurnRecord {\n label: string\n prompt: string\n threadId: string | null\n sentAt: string\n /** Seconds from the Send press. */\n firstProgressS: number | null\n firstProgressText: string | null\n firstTextS: number | null\n /** Seconds from Send to the first failure evidence on the page, if any appeared. */\n firstFailureS: number | null\n completeS: number | null\n outcome: TurnOutcome\n /** Plain words for what went wrong, or null for a completed turn. */\n error: string | null\n /** Every piece of failure evidence the turn added. */\n failures: string[]\n /** Where evidence was read: after the turn's own prompt, or the whole transcript when the page did not show the prompt. */\n evidenceScope: 'after-prompt' | 'whole-transcript' | null\n replyChars: number\n /** Distinct status lines the transcript showed, with when they appeared. */\n stages: { s: number; text: string }[]\n /** Seconds from Send at which the journey pressed Stop, if it did. */\n stopPressedS: number | null\n replyFile: string | null\n}\n\nexport interface StepRecord {\n caption: string\n label: string | null\n startS: number\n durationS: number\n ok: boolean\n error?: string\n}\n\nexport interface SendOptions {\n caption?: string\n timeoutMs?: number\n /** Keystroke delay for the prompt. */\n delay?: number\n /** Press Stop at first text, or this many seconds after Send. */\n stopAfter?: 'first-text' | number\n /** Type after what the composer already holds (mention pills, attachments)\n * instead of replacing it. The default select-all-and-delete erased the\n * `@agent` pills of GTM's first agent-mentions runs (2026-10-27). */\n keepDraft?: boolean\n}\n\n/** What the page shows right now, read in one evaluate. */\ninterface PageReading extends TranscriptSnapshot {\n status: string[]\n assistantChars: number\n transcriptChars: number\n stopVisible: boolean\n}\n\nexport class Journey {\n readonly outDir: string\n readonly rawDir: string\n readonly chapters: Chapter[] = []\n readonly steps: StepRecord[] = []\n readonly turns: TurnRecord[] = []\n private recorded: Recorded[] = []\n private phones = new Map<string, BrowserContext>()\n private screenshots = new Set<string>()\n private readonly startedAt = Date.now()\n\n constructor(readonly id: string, readonly config: ResolvedJourneysConfig, readonly browser: Browser, private readonly opts: { cursor: boolean }) {\n this.outDir = join(config.outDir, id)\n this.rawDir = join(config.stateDir, 'raw', `${id}-${new Date().toISOString().replace(/[:.]/g, '-')}`)\n mkdirSync(join(this.outDir, 'video'), { recursive: true })\n mkdirSync(join(this.outDir, 'turns'), { recursive: true })\n mkdirSync(this.rawDir, { recursive: true, mode: 0o700 })\n }\n\n /**\n * A recorded, traced context: 1440x900, or with `device: 'phone'` a 390x844 touch phone. A config identity starts signed in\n * from the cached session (no login form is ever recorded); `'anon'` starts\n * signed out, for public pages. Open at most two per journey.\n */\n async open(label: string, identity: string, opts: { fresh?: boolean; device?: JourneyDevice } = {}): Promise<Page> {\n if (this.recorded.some((r) => r.label === label)) throw new Error(`a context labelled ${label} is already open`)\n if (!/^[a-z0-9][a-z0-9-]{0,30}$/.test(label)) throw new Error('context label: lowercase letters, digits and dashes')\n const storageState = identity === 'anon' ? undefined : (await storageStateFor(this.config, identity, opts)).path\n const rawDir = join(this.rawDir, label)\n const device = opts.device ?? 'desktop'\n // A phone records at its 2x pixels, so its text stays legible in the video.\n const size = device === 'phone' ? { width: PHONE.width * 2, height: PHONE.height * 2 } : DESKTOP\n const context = await this.browser.newContext({\n baseURL: this.config.baseUrl,\n storageState,\n ...(device === 'phone' ? PHONE_CONTEXT : { viewport: DESKTOP }),\n recordVideo: { dir: rawDir, size },\n locale: 'en-US',\n timezoneId: 'America/Denver',\n })\n context.setDefaultTimeout(20_000)\n context.setDefaultNavigationTimeout(60_000)\n if (this.opts.cursor) await context.addInitScript(CURSOR_SCRIPT)\n if (process.env.JOURNEY_DEBUG_CLOCK === '1') {\n // Wall-clock seconds since recording start on every frame, for calibrating captions.\n await context.addInitScript((t0: number) => {\n setInterval(() => {\n let d = document.getElementById('__journey_clock')\n if (!d && document.body) {\n d = document.createElement('div')\n d.id = '__journey_clock'\n Object.assign(d.style, { position: 'fixed', left: '50%', top: '0', zIndex: '2147483647', font: 'bold 20px monospace', background: '#ff0', color: '#000', padding: '2px 6px', pointerEvents: 'none' })\n document.body.appendChild(d)\n }\n if (d) d.textContent = ((Date.now() - t0) / 1000).toFixed(1)\n }, 100)\n }, Date.now())\n }\n await context.tracing.start({ screenshots: true, snapshots: true, title: `${this.id} ${label}` })\n const page = await context.newPage()\n this.recorded.push({ label, identity, device, size, context, page, t0: Date.now(), rawDir })\n return page\n }\n\n private recordedFor(page?: Page): Recorded {\n const r = page ? this.recorded.find((x) => x.page === page) : this.recorded[0]\n if (!r) throw new Error('no recorded context for that page; call open() first')\n return r\n }\n\n /** A chapter at this instant: one plain line, shown in the caption bar and the .srt. */\n mark(caption: string, page?: Page): void {\n const label = page ? this.recordedFor(page).label : null\n this.chapters.push({ at: Date.now(), caption, label, kind: 'step' })\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}${caption}`)\n }\n\n /** A timed step with its own chapter. A failure is recorded, captioned, then rethrown. */\n async step<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n this.mark(caption, page)\n const start = Date.now()\n const entry: StepRecord = { caption, label: page ? this.recordedFor(page).label : null, startS: secs(start - this.startedAt), durationS: 0, ok: true }\n this.steps.push(entry)\n try {\n return await work()\n } catch (error) {\n entry.ok = false\n entry.error = String((error as Error)?.message ?? error).slice(0, 400)\n this.mark(`Step failed: ${caption}`, page)\n throw error\n } finally {\n entry.durationS = secs(Date.now() - start)\n }\n }\n\n /** A waiting span: real speed in the full video, sped up and labelled in the highlights. */\n async wait<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n const label = page ? this.recordedFor(page).label : null\n const chapter: Chapter = { at: Date.now(), caption, label, kind: 'wait', until: Date.now() }\n this.chapters.push(chapter)\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}(wait) ${caption}`)\n try {\n return await work()\n } finally {\n chapter.until = Date.now()\n }\n }\n\n pause(ms = 700): Promise<void> {\n return sleep(ms)\n }\n\n /** Move the visible pointer there, pause, click, pause. */\n async click(target: Locator, opts: { pauseAfter?: number } = {}): Promise<void> {\n await target.scrollIntoViewIfNeeded()\n const box = await target.boundingBox()\n if (box) await target.page().mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(250)\n await target.click()\n await sleep(opts.pauseAfter ?? 600)\n }\n\n /** Type at a readable pace into an input or textarea. */\n async type(target: Locator, text: string, opts: { delay?: number } = {}): Promise<void> {\n await this.click(target, { pauseAfter: 200 })\n const delay = opts.delay ?? 28\n await target.pressSequentially(text, { delay, timeout: 30_000 + text.length * (delay + 60) })\n await sleep(400)\n }\n\n /** The composer's message input. */\n composerInput(page: Page): Locator {\n return page.locator(this.config.chat.composer).getByRole('textbox', { name: this.config.chat.inputName })\n }\n\n private composerButton(page: Page, name: string): Locator {\n return page.locator(this.config.chat.composer).getByRole('button', { name, exact: true })\n }\n\n /**\n * Type into the chat composer at a readable pace. A line break is typed as\n * Shift+Enter, because Enter sends. Retries fast when hydration dropped\n * keystrokes. Never `fill()` a rich-text composer.\n */\n async typePrompt(page: Page, prompt: string, opts: { delay?: number; keepDraft?: boolean } = {}): Promise<void> {\n const box = this.composerInput(page)\n await box.waitFor({ state: 'visible', timeout: 30_000 })\n await sleep(1_200)\n const delay = opts.delay ?? (prompt.length > 400 ? 8 : 22)\n const want = prompt.replace(/\\s+/g, ' ').trim().slice(0, 80)\n for (let attempt = 0; attempt < 4; attempt += 1) {\n await this.click(box, { pauseAfter: 150 })\n if (opts.keepDraft) {\n await box.press('ControlOrMeta+End')\n } else {\n await box.press('ControlOrMeta+a')\n await box.press('Backspace')\n }\n const lines = prompt.split('\\n')\n for (let i = 0; i < lines.length; i += 1) {\n if (i > 0) await box.press('Shift+Enter')\n // Sized by length: a loaded host types slower than the context's 20 s default allows.\n const line = lines[i]!\n if (line) await box.pressSequentially(line, { delay: attempt === 0 ? delay : 0, timeout: 30_000 + line.length * (delay + 60) })\n }\n const text = (await composerText(box).catch(() => '')).replace(/\\s+/g, ' ').trim()\n if (text.includes(want)) return\n await sleep(1_000)\n }\n throw new Error('the composer never held the prompt')\n }\n\n /**\n * Which parts of the chat contract this page shows, without sending\n * anything. Run it on a second app before trusting turn timings there.\n */\n async checkChatContract(page: Page): Promise<Record<'transcript' | 'composer' | 'input' | 'send', boolean>> {\n const visible = (l: Locator) => l.first().isVisible().catch(() => false)\n return {\n transcript: await visible(page.locator(this.config.chat.transcript)),\n composer: await visible(page.locator(this.config.chat.composer)),\n input: await visible(this.composerInput(page)),\n send: await visible(this.composerButton(page, this.config.chat.sendName)),\n }\n }\n\n /**\n * Desktop screenshot of the recorded page, then the same URL in a phone\n * context (390x844, same identity). Look at both before judging the screen.\n */\n async shot(name: string, page?: Page, opts: { phone?: boolean; fullPage?: boolean; phoneUrl?: string } = {}): Promise<{ desktop?: string; phone?: string }> {\n const r = this.recordedFor(page)\n const slug = name.replace(/[^a-z0-9-]+/gi, '-').toLowerCase()\n const own = join(this.outDir, `${slug}-${r.device}.png`)\n const cursor = (display: string) => r.page.evaluate((d) => { const c = document.getElementById('__journey_cursor'); if (c) c.style.display = d }, display).catch(() => {})\n await cursor('none')\n await r.page.screenshot({ path: own, fullPage: opts.fullPage ?? false })\n this.screenshots.add(own)\n await cursor('')\n // A recorded phone is its own phone screenshot.\n if (r.device === 'phone') return { phone: own }\n const desktop = own\n if (opts.phone === false) return { desktop }\n const phonePath = join(this.outDir, `${slug}-phone.png`)\n let ctx = this.phones.get(r.identity)\n if (!ctx) {\n const storageState = r.identity === 'anon' ? undefined : (await storageStateFor(this.config, r.identity)).path\n ctx = await this.browser.newContext({ baseURL: this.config.baseUrl, storageState, ...PHONE_CONTEXT, locale: 'en-US', timezoneId: 'America/Denver' })\n this.phones.set(r.identity, ctx)\n }\n const phone = await ctx.newPage()\n try {\n await phone.goto(opts.phoneUrl ?? r.page.url(), { waitUntil: 'load' })\n await phone.waitForLoadState('networkidle', { timeout: 8_000 }).catch(() => {})\n await sleep(1_500)\n await phone.screenshot({ path: phonePath, fullPage: opts.fullPage ?? false })\n this.screenshots.add(phonePath)\n } finally {\n await phone.close()\n }\n return { desktop, phone: phonePath }\n }\n\n private budgetTurn(): void {\n if (this.turns.length >= this.config.maxTurns) {\n throw new Error(`this journey already sent ${this.turns.length} chat turns, its budget (maxTurns ${this.config.maxTurns})`)\n }\n }\n\n /**\n * Start a new thread: open `from` when given, type the prompt, press Send\n * like a person (again only while the page has not submitted; never deletes\n * a duplicate), wait for the thread, then measure the turn.\n */\n async sendNew(page: Page, prompt: string, opts: SendOptions & { from?: string } = {}): Promise<TurnRecord> {\n this.budgetTurn()\n if (opts.from && !page.url().startsWith(new URL(opts.from, this.config.baseUrl).href)) await page.goto(opts.from)\n await this.typePrompt(page, prompt, { delay: opts.delay, keepDraft: opts.keepDraft })\n const send = this.composerButton(page, this.config.chat.sendName)\n await send.waitFor({ state: 'visible' })\n const box = await send.boundingBox()\n if (box) await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(400)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const count = (request: { method(): string; url(): string }) => tracker.observe(request.method(), request.url())\n page.on('request', count)\n this.mark(opts.caption ?? `Sends: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n const onThread = () => threadRouteIn(page.url(), this.config) !== null\n try {\n await clickUntilSubmitted({\n landed: () => tracker.count > 0 || onThread(),\n ready: () => send.click({ trial: true, timeout: 5_000 }),\n click: () => send.click({ timeout: 5_000 }),\n wait: () => page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 1_000 }).then(() => undefined).catch(() => undefined),\n attempts: 15,\n })\n if (this.config.chat.threadPath) await page.waitForURL((url) => threadRouteIn(url.href, this.config) !== null, { timeout: 45_000 })\n } catch (error) {\n return this.notSent(page, prompt, sentAt, String((error as Error).message).slice(0, 300))\n } finally {\n page.off('request', count)\n }\n if (tracker.count > 1) console.warn(`the composer submitted ${tracker.count} times; a duplicate thread may exist (left in place)`)\n return this.measureTurn(page, prompt, sentAt, evidence, before, 0, opts)\n }\n\n /** A follow-up in the open thread: type, one Send press, measure. */\n async sendInThread(page: Page, prompt: string, opts: SendOptions = {}): Promise<TurnRecord> {\n this.budgetTurn()\n await this.typePrompt(page, prompt, { delay: opts.delay, keepDraft: opts.keepDraft })\n const send = this.composerButton(page, this.config.chat.sendName)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const posted = page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 30_000 })\n this.mark(opts.caption ?? `Follows up: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n await this.click(send, { pauseAfter: 0 })\n const sent = await posted.then(() => true).catch(() => false)\n if (!sent) return this.notSent(page, prompt, sentAt, 'no chat request within 30 s of pressing Send')\n return this.measureTurn(page, prompt, sentAt, evidence, before, Math.max(0, before.assistantChars), opts)\n }\n\n private patterns() {\n return { failure: this.config.chat.failureText, stopped: this.config.chat.stoppedText }\n }\n\n private blankTurn(page: Page, prompt: string, sentAt: number): TurnRecord {\n return {\n label: this.recordedFor(page).label, prompt, threadId: threadRouteIn(page.url(), this.config)?.threadId ?? null,\n sentAt: new Date(sentAt).toISOString(), firstProgressS: null, firstProgressText: null, firstTextS: null, firstFailureS: null, completeS: null,\n outcome: 'timeout', error: null, failures: [], evidenceScope: null, replyChars: 0, stages: [], stopPressedS: null, replyFile: null,\n }\n }\n\n private notSent(page: Page, prompt: string, sentAt: number, why: string): TurnRecord {\n const t = { ...this.blankTurn(page, prompt, sentAt), ...scoreTurn({ notSent: why, timedOut: false, evidence: { failures: [], stopped: [], retryAppeared: false }, replyChars: 0, stopPressed: false }) }\n this.turns.push(t)\n this.mark(`Turn not sent: ${oneLine(why, 90)}`, page)\n return t\n }\n\n /** One read of the transcript, composer and failure marks; with a prompt, the evidence that follows it. */\n private async read(page: Page, prompt: string | null = null): Promise<PageReading> {\n const c = this.config.chat\n const { assistant, ...reading } = await page.evaluate(readChatPage, {\n transcript: c.transcript, status: c.status, failureNodes: c.failureNodes, retrySource: c.retryName.source, retryFlags: c.retryName.flags,\n assistant: c.assistant, composer: c.composer, stopName: c.stopName, promptHead: prompt === null ? null : promptHead(prompt),\n })\n return { ...reading, assistantChars: assistant }\n }\n\n private async runningTurns(page: Page, route: ThreadRoute | null): Promise<string[] | null> {\n if (!route || !this.config.chat.runningTurns) return null\n const res = await page.request.get(this.config.chat.runningTurns(route))\n if (!res.ok()) throw new Error(`running turns answered ${res.status()}`)\n const body = (await res.json()) as { running?: unknown }\n if (!Array.isArray(body.running)) throw new Error('running turns returned no `running` array')\n return body.running.map(String)\n }\n\n /**\n * Time to first visible progress (a new status line or reply text), first\n * reply text, and the turn's end, polled every 300 ms. Failure evidence is\n * read after the turn's own prompt when the page shows it. The turn has ended\n * when, for two reads in a row, {@link turnLooksActive} is false and, where\n * the app lists running turns, the server lists none. Status lines already\n * on the page before Send are not progress. The outcome comes from\n * {@link scoreTurn}.\n */\n private async measureTurn(page: Page, prompt: string, sentAt: number, evidence: TurnEvidence, before: PageReading, baselineChars: number, opts: SendOptions): Promise<TurnRecord> {\n const t = this.blankTurn(page, prompt, sentAt)\n this.turns.push(t)\n const route = threadRouteIn(page.url(), this.config)\n t.threadId = route?.threadId ?? null\n const timeoutMs = opts.timeoutMs ?? 15 * 60_000\n const since = () => secs(Date.now() - sentAt)\n const standingStatus = new Set(before.status)\n // Without an assistant selector, reply text is transcript growth from the\n // first read after Send (the person's own message is on the page by then).\n let growthBase: number | null = null\n let growth = 0\n let sawActive = false\n let quiet = 0\n let lastServerCheck = 0\n let serverRunning: string[] | null = null\n let lastStage = ''\n let lastStatus = ''\n let statusChangedAt = Date.now()\n let finished = false\n await this.wait('Waiting for the agent', async () => {\n while (Date.now() - sentAt < timeoutMs) {\n const s = await this.read(page, prompt).catch(() => null)\n if (s) {\n t.evidenceScope = s.anchored ? 'after-prompt' : 'whole-transcript'\n const shown = evidence.observe(s)\n if (shown.length) {\n t.firstFailureS ??= since()\n this.mark(`Failure shown after ${since()} s: ${oneLine(shown[0]!, 90)}`, page)\n }\n const status = s.status.filter((line) => !standingStatus.has(line))\n growthBase ??= s.transcriptChars\n const chars = s.assistantChars >= 0 ? s.assistantChars - baselineChars : s.transcriptChars - growthBase - status.join(' ').length\n growth = Math.max(growth, chars)\n const stage = status.join(' | ').replace(/\\b\\d+(\\.\\d+)?\\s?s\\b/g, '').trim()\n if (stage && stage !== lastStage) {\n t.stages.push({ s: since(), text: status.join(' | ').slice(0, 160) })\n lastStage = stage\n }\n // Raw text, timers included: a ticking \"Preparing your workspace… 31s\" is changing.\n if (status.join(' | ') !== lastStatus) {\n lastStatus = status.join(' | ')\n statusChangedAt = Date.now()\n }\n if (t.firstProgressS === null && (status.length || chars > 0)) {\n t.firstProgressS = since()\n t.firstProgressText = status[0] ?? 'reply text'\n this.mark(`First visible progress after ${t.firstProgressS} s: ${oneLine(t.firstProgressText, 70)}`, page)\n }\n if (t.firstTextS === null && chars > 0) {\n t.firstTextS = since()\n this.mark(`First text after ${t.firstTextS} s`, page)\n }\n const stopDue = opts.stopAfter === 'first-text' ? t.firstTextS !== null : typeof opts.stopAfter === 'number' && since() >= opts.stopAfter\n if (t.stopPressedS === null && stopDue && s.stopVisible) {\n t.stopPressedS = since()\n this.mark(`Presses Stop after ${t.stopPressedS} s`, page)\n await this.click(this.composerButton(page, this.config.chat.stopName), { pauseAfter: 200 }).catch((e) => console.warn(`Stop press failed: ${e}`))\n }\n if (status.length > 0) sawActive = true\n const active = turnLooksActive({ stopVisible: s.stopVisible, statusLines: status.length, msSinceStatusChanged: Date.now() - statusChangedAt })\n quiet = active ? 0 : quiet + 1\n }\n if (route && this.config.chat.runningTurns && Date.now() - lastServerCheck > 2_000) {\n lastServerCheck = Date.now()\n // A failed read never implies the turn ended.\n serverRunning = await this.runningTurns(page, route).catch(() => serverRunning)\n if (serverRunning?.length) sawActive = true\n }\n const started = sawActive || t.firstTextS !== null || Date.now() - sentAt > 45_000\n const serverDone = !this.config.chat.runningTurns || !route || serverRunning?.length === 0\n if (started && quiet >= 2 && serverDone) {\n finished = true\n return\n }\n await sleep(300)\n }\n }, page)\n t.completeS = finished ? since() : null\n // Render lag only: the turn has ended, so wait for the transcript to stop changing before judging it.\n await settleText(() => this.read(page, prompt).then((r) => `${r.transcriptChars}:${r.failureNodes.length}:${r.retryButtons}`))\n const last = await this.read(page, prompt)\n t.evidenceScope = last.anchored ? 'after-prompt' : 'whole-transcript'\n evidence.observe(last)\n const finalText = this.config.chat.assistant ? await this.replyText(page) : ''\n t.replyChars = this.config.chat.assistant ? Math.max(0, finalText.length - baselineChars) : Math.max(0, growth)\n Object.assign(t, scoreTurn({ timedOut: !finished, evidence: evidence.added(), replyChars: t.replyChars, stopPressed: t.stopPressedS !== null }))\n const n = this.turns.length\n t.replyFile = join('turns', `${String(n).padStart(2, '0')}-${t.label}.md`)\n const reply = this.config.chat.assistant ? finalText.slice(baselineChars).trim() : '(this app configures no assistant selector; read the reply in the video or the trace)'\n const failures = t.failures.length ? `\\n\\n## Failure evidence\\n\\n${t.failures.map((f) => `- ${f}`).join('\\n')}` : ''\n writeFileSync(join(this.outDir, t.replyFile), `# Turn ${n} (${t.label})\\n\\n## Prompt\\n\\n${prompt}\\n\\n## Reply (${t.outcome})\\n\\n${reply}${failures}\\n`)\n this.mark(\n t.outcome === 'completed'\n ? `Turn complete after ${t.completeS} s (${t.replyChars} chars)`\n : `Turn ${t.outcome.toUpperCase()} after ${t.completeS ?? since()} s${t.error ? `: ${oneLine(t.error, 80)}` : ''}`,\n page,\n )\n return t\n }\n\n private async replyText(page: Page): Promise<string> {\n const sel = this.config.chat.assistant\n if (!sel) return ''\n return settleText(async () => (await page.locator(sel).allInnerTexts()).join('\\n').trim())\n }\n\n /**\n * Close everything, then per context: a captioned full .mp4, a highlights cut\n * (at most 178 s, long waits sped up and labelled), an .srt and a scrubbed\n * trace.zip; plus timings.json and chapters.json. Refuses (throws) when any\n * output file still holds a password or cookie value.\n */\n async finish(opts: { speedup2x?: boolean } = {}): Promise<{ outDir: string; files: string[] }> {\n for (const ctx of this.phones.values()) await ctx.close().catch(() => {})\n const files: string[] = []\n // Stop every recording first, so one context's video does not run on through another's processing.\n const stopped: { r: Recorded; rawTrace: string; webm: string | null; endedAt: number }[] = []\n for (const r of this.recorded) {\n const endedAt = Date.now()\n const rawTrace = join(r.rawDir, 'trace.raw.zip')\n await r.context.tracing.stop({ path: rawTrace }).catch((e) => console.warn(`tracing.stop failed for ${r.label}: ${e}`))\n const video = r.page.video()\n await r.context.close()\n stopped.push({ r, rawTrace, webm: video ? await video.path().catch(() => null) : null, endedAt })\n }\n const needles = secretNeedles(this.config)\n for (const { r, rawTrace, webm, endedAt } of stopped) {\n if (webm) {\n files.push(...postProcessVideo({\n webm, workDir: r.rawDir, videoDir: join(this.outDir, 'video'), label: r.label, t0: r.t0, size: r.size,\n wallSeconds: (endedAt - r.t0) / 1000, chapters: this.chapters.filter((c) => c.label === null || c.label === r.label),\n speedup2x: opts.speedup2x ?? false,\n }))\n }\n try {\n const clean = join(this.outDir, 'video', `${r.label}-trace.zip`)\n const result = scrubTrace(rawTrace, clean, [...needles.hard, ...needles.soft])\n console.log(`trace ${r.label}: ${result.entries} entries, ${result.dropped} sensitive bodies dropped, ${result.rewritten} rewritten`)\n files.push(clean)\n } catch (error) {\n console.warn(`trace ${r.label} not written: ${(error as Error).message}`)\n }\n }\n writeFileSync(join(this.outDir, 'chapters.json'), JSON.stringify(this.chapters.map((c) => ({ ...c, at: new Date(c.at).toISOString(), until: c.until ? new Date(c.until).toISOString() : undefined, offsetS: secs(c.at - this.startedAt) })), null, 2))\n writeFileSync(join(this.outDir, 'timings.json'), JSON.stringify({ journey: this.id, app: this.config.app, base: this.config.baseUrl, startedAt: new Date(this.startedAt).toISOString(), wallS: secs(Date.now() - this.startedAt), steps: this.steps, turns: this.turns }, null, 2))\n await this.browser.close()\n assertNoSecrets(this.outDir, needles)\n pruneJourneyArtifacts(this.outDir, new Set([\n ...files,\n ...this.screenshots,\n ...this.turns.flatMap((turn) => turn.replyFile ? [join(this.outDir, turn.replyFile)] : []),\n ]))\n console.log(`\\n${this.id}: ${this.steps.length} steps, ${this.turns.length} turns, wall ${secs(Date.now() - this.startedAt)} s`)\n for (const t of this.turns) {\n console.log(` turn[${t.label}] ${t.outcome}: progress ${t.firstProgressS ?? '-'} s, first text ${t.firstTextS ?? '-'} s, end ${t.completeS ?? '-'} s, ${t.replyChars} chars${t.error ? ` | ${oneLine(t.error, 100)}` : ''}`)\n }\n const host = process.env.JOURNEYS_HOST_ALIAS ?? hostname()\n console.log(`output: ${this.outDir}\\ncopy it (run where you will watch it):\\n rsync -a ${host}:${this.outDir}/ \"<dest>/${this.id}/\"`)\n return { outDir: this.outDir, files }\n }\n}\n\nexport function oneLine(text: string, max: number): string {\n const s = text.replace(/\\s+/g, ' ').trim()\n return s.length > max ? `${s.slice(0, max - 1)}…` : s\n}\n\n/** Open a journey. Without `config`, reads `journeys.config.mjs` from the working directory. */\nexport async function startJourney(id: string, opts: { config?: JourneysConfig | ResolvedJourneysConfig; cursor?: boolean; headless?: boolean } = {}): Promise<Journey> {\n if (!/^[a-z0-9][a-z0-9-]{1,60}$/.test(id)) throw new Error('journey id: lowercase letters, digits and dashes')\n const config = opts.config ? resolveJourneysConfig(opts.config) : await loadJourneysConfig()\n let chromium\n try {\n chromium = (await import('playwright')).chromium\n } catch {\n throw new Error('journeys need the optional `playwright` peer: install playwright in the app that runs them')\n }\n const browser = await chromium.launch({ headless: opts.headless ?? true })\n return new Journey(id, config, browser, { cursor: opts.cursor ?? true })\n}\n","import { readdirSync, rmSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nconst groups = [\n {\n directory: '',\n owns: (name: string) => name.endsWith('-desktop.png') || name.endsWith('-phone.png'),\n },\n {\n directory: 'video',\n owns: (name: string) => name.endsWith('.mp4') || name.endsWith('.srt') || name.endsWith('-trace.zip'),\n },\n {\n directory: 'turns',\n owns: (name: string) => name.endsWith('.md'),\n },\n] as const\n\nexport function pruneJourneyArtifacts(outDir: string, retained: ReadonlySet<string>): void {\n const keep = new Set([...retained].map((file) => resolve(file)))\n for (const group of groups) {\n const directory = join(resolve(outDir), group.directory)\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if ((!entry.isFile() && !entry.isSymbolicLink()) || !group.owns(entry.name)) continue\n const file = join(directory, entry.name)\n if (!keep.has(file)) rmSync(file)\n }\n }\n}\n","/**\n * The one read of a chat page a journey takes every 300 ms, run inside the page\n * by `page.evaluate`, so it must stay self-contained: DOM globals only, no\n * imports and no module-scope names.\n *\n * Failure evidence belongs to the turn whose prompt it follows. On 2026-10-11\n * GTM showed a live Stop as a grey notice, then, when the next message was\n * sent, re-rendered the stopped turn with its red \"You stopped this turn.\" card\n * and a Retry control, above the new message. Read from the whole transcript,\n * that card failed the follow-up, which had answered in 28.5 s. So when the\n * transcript shows the turn's own prompt, only failure marks, Retry controls\n * and lines after it count; when it does not, the whole transcript does.\n */\n\ninterface PageReadArgs {\n readonly transcript: string\n readonly status: string\n readonly failureNodes: string\n readonly retrySource: string\n readonly retryFlags: string\n readonly assistant: string | null\n readonly composer: string\n readonly stopName: string\n /** The turn's prompt as {@link promptHead} gives it; null reads the whole transcript. */\n readonly promptHead: string | null\n}\n\ninterface RawPageReading {\n /** Visible transcript lines (after the turn's prompt when `anchored`). */\n lines: string[]\n failureNodes: string[]\n retryButtons: number\n status: string[]\n /** Characters of assistant text on the page, or -1 with no assistant selector. */\n assistant: number\n transcriptChars: number\n stopVisible: boolean\n /** The turn's prompt was found, so the evidence fields hold only what follows it. */\n anchored: boolean\n}\n\n/** The text a transcript shows for a prompt: its first line, whitespace squashed, at most 48 characters. */\nexport function promptHead(prompt: string): string | null {\n const first = prompt.split('\\n').map((line) => line.replace(/\\s+/g, ' ').trim()).find(Boolean)\n return first ? first.slice(0, 48) : null\n}\n\nexport function readChatPage(c: PageReadArgs): RawPageReading {\n const squash = (s: string) => s.replace(/\\s+/g, ' ').trim()\n const clean = (e: Element) => squash(e.textContent ?? '')\n const region = document.querySelector<HTMLElement>(c.transcript)\n const composer = document.querySelector<HTMLElement>(c.composer)\n const assistantNodes = c.assistant ? Array.from(document.querySelectorAll<HTMLElement>(c.assistant)) : []\n const within = (sel: string) => (region ? Array.from(region.querySelectorAll(sel)) : [])\n\n // The last text node outside the composer and the assistant's own text that holds the prompt.\n let anchor: Node | null = null\n if (region && c.promptHead) {\n const walker = document.createTreeWalker(region, NodeFilter.SHOW_TEXT)\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n if (!squash(node.nodeValue ?? '').includes(c.promptHead)) continue\n if (composer?.contains(node) || assistantNodes.some((a) => a.contains(node))) continue\n anchor = node\n }\n }\n const after = (e: Element) => anchor === null || (anchor.compareDocumentPosition(e) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0\n\n const full = region?.innerText ?? ''\n let text = full\n const composerText = composer && region?.contains(composer) ? composer.innerText.trim() : ''\n if (composerText) {\n const at = text.lastIndexOf(composerText)\n if (at >= 0) text = text.slice(0, at) + text.slice(at + composerText.length)\n }\n let lines = text.split('\\n').map((l) => l.trim()).filter(Boolean)\n if (anchor && c.promptHead) {\n // The same rule for lines: the last one holding the prompt that is not the assistant's.\n const replyLines = new Set(assistantNodes.flatMap((a) => a.innerText.split('\\n').map(squash)))\n let last = -1\n for (let i = 0; i < lines.length; i += 1) {\n const line = squash(lines[i]!)\n if (line.includes(c.promptHead) && !replyLines.has(line)) last = i\n }\n lines = lines.slice(last + 1)\n }\n\n const status = within(c.status).map(clean).filter(Boolean)\n // textContent, not innerText: a failure's collapsed details (the code) count too.\n const failureNodes = within(c.failureNodes).filter(after).map(clean).filter(Boolean)\n const retry = new RegExp(c.retrySource, c.retryFlags)\n const retryButtons = within('button').filter((b) => after(b) && retry.test((b.getAttribute('aria-label') ?? b.textContent ?? '').trim())).length\n const assistant = c.assistant ? assistantNodes.map((e) => e.innerText).join('\\n').trim().length : -1\n const stopVisible = composer !== null && Array.from(composer.querySelectorAll('button')).some((b) =>\n (b.getAttribute('aria-label') ?? b.textContent ?? '').trim() === c.stopName && b.getClientRects().length > 0)\n return { lines, failureNodes, retryButtons, status, assistant, transcriptChars: full.trim().length, stopVisible, anchored: anchor !== null }\n}\n","/**\n * Pressing Send like a person, exactly as often as it takes and never once more.\n *\n * A new-chat composer can drop a press while its model selection is still\n * resolving, and its Send control is not disabled while that gate is shut, so\n * one press can be a silent no-op and a retry is necessary. A retry is also\n * dangerous: the press creates a thread, so a press after the page has already\n * submitted asks for a second one. Pure, so the rule is a unit test.\n */\n\n/** Paths a submission from `routePath` lands on: the route itself and its single-fetch `.data` form. */\nexport function routeSubmitPaths(routePath: string): string[] {\n const singleFetch = routePath.endsWith('/') ? `${routePath}_.data` : `${routePath}.data`\n return [routePath, singleFetch]\n}\n\nexport interface SubmissionTracker {\n /** Whether one request is a submission from the tracked page. */\n matches(method: string, url: string): boolean\n observe(method: string, url: string): void\n /** Submissions seen so far. Above zero means the turn is on its way. */\n readonly count: number\n}\n\n/**\n * Counts submissions from the page at `routeUrl`: a POST to that route (or its\n * `.data` form), or to one of `sendPaths`, on the same origin. A POST to the\n * same path on another origin is not this composer's.\n */\nexport function createSubmissionTracker(routeUrl: string, sendPaths: readonly RegExp[]): SubmissionTracker {\n if (!/^https?:\\/\\//i.test(routeUrl)) throw new Error(`createSubmissionTracker needs the page's full URL, got \"${routeUrl}\"`)\n const route = new URL(routeUrl)\n const exact = new Set(routeSubmitPaths(route.pathname))\n let count = 0\n const matches = (method: string, url: string): boolean => {\n if (method !== 'POST') return false\n let parsed: URL\n try {\n parsed = new URL(url, route.origin)\n } catch {\n return false\n }\n if (parsed.origin !== route.origin) return false\n return exact.has(parsed.pathname) || sendPaths.some((p) => p.test(parsed.pathname))\n }\n return {\n matches,\n observe(method, url) {\n if (matches(method, url)) count += 1\n },\n get count() {\n return count\n },\n }\n}\n\nexport interface SendDriveOps {\n /** True once a submission, or the navigation it causes, has been observed. */\n landed: () => boolean\n /** Wait until Send can take a press, without pressing it. */\n ready: () => Promise<void>\n click: () => Promise<void>\n /** Pause between presses, spent watching for the submission. */\n wait: () => Promise<void>\n attempts: number\n}\n\n/**\n * Press until the page submits. Each attempt waits for the control first and\n * takes its last look at `landed()` after that wait, so the press itself is the\n * only unguarded moment. A click failure is tolerated only once something has\n * landed: an accepted send tears the composer down mid-press.\n */\nexport async function clickUntilSubmitted(ops: SendDriveOps): Promise<void> {\n for (let attempt = 0; attempt < ops.attempts; attempt += 1) {\n if (ops.landed()) return\n try {\n await ops.ready()\n if (ops.landed()) return\n await ops.click()\n } catch (cause) {\n if (!ops.landed()) throw cause\n }\n if (ops.landed()) return\n await ops.wait()\n }\n if (ops.landed()) return\n throw new Error(`Send never submitted: the composer refused ${ops.attempts} presses`)\n}\n\n/**\n * Read until the value stops changing: six identical reads 500 ms apart. Every\n * caller has already seen the turn finish, so this covers render lag only.\n */\nexport async function settleText(\n read: () => Promise<string>,\n wait: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n timeoutMs = 20_000,\n): Promise<string> {\n const deadline = Date.now() + timeoutMs\n let previous: string | null = null\n let stable = 0\n for (;;) {\n const current = await read().catch(() => null)\n if (current === null) {\n stable = 0\n } else {\n stable = current === previous ? stable + 1 : 1\n previous = current\n if (stable >= 6) return current\n }\n if (Date.now() >= deadline) return previous ?? ''\n await wait(500)\n }\n}\n\n/**\n * The text a composer holds. A `<textarea>` or `<input>` (agent-app's own\n * ChatComposer) keeps typed text in `.value` and leaves `innerText` empty; a\n * contenteditable composer keeps it in `innerText`. Reading only `innerText`\n * failed every first chat turn on the default composer (Casework C1/C5).\n */\nexport async function composerText(box: { evaluate<R>(fn: (el: Element) => R): Promise<R> }): Promise<string> {\n return box.evaluate((el) => {\n const field = el as Element & { value?: unknown; innerText?: string }\n return typ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IAC9N;AACA,UAAM,OAAO,QAAQ,IAAI,uBAAuB,SAAS;AACzD,YAAQ,IAAI,WAAW,KAAK,MAAM;AAAA;AAAA,aAAwD,IAAI,IAAI,KAAK,MAAM,aAAa,KAAK,EAAE,IAAI;AACrI,WAAO,EAAE,QAAQ,KAAK,QAAQ,MAAM;AAAA,EACtC;AACF;AAEO,SAAS,QAAQ,MAAc,KAAqB;AACzD,QAAM,IAAI,KAAK,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACzC,SAAO,EAAE,SAAS,MAAM,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC,WAAM;AACtD;AAGA,eAAsB,aAAa,IAAY,OAAmG,CAAC,GAAqB;AACtK,MAAI,CAAC,4BAA4B,KAAK,EAAE,EAAG,OAAM,IAAI,MAAM,kDAAkD;AAC7G,QAAM,SAAS,KAAK,SAAS,sBAAsB,KAAK,MAAM,IAAI,MAAM,mBAAmB;AAC3F,MAAI;AACJ,MAAI;AACF,gBAAY,MAAM,OAAO,YAAY,GAAG;AAAA,EAC1C,QAAQ;AACN,UAAM,IAAI,MAAM,4FAA4F;AAAA,EAC9G;AACA,QAAM,UAAU,MAAM,SAAS,OAAO,EAAE,UAAU,KAAK,YAAY,KAAK,CAAC;AACzE,SAAO,IAAI,QAAQ,IAAI,QAAQ,SAAS,EAAE,QAAQ,KAAK,UAAU,KAAK,CAAC;AACzE;","names":["join","composerText","resolve","resolve","join"]}
@@ -10,6 +10,7 @@ export declare const PHONE: {
10
10
  width: number;
11
11
  height: number;
12
12
  };
13
+ export type JourneyDevice = 'desktop' | 'phone';
13
14
  export interface TurnRecord {
14
15
  label: string;
15
16
  prompt: string;
@@ -77,12 +78,13 @@ export declare class Journey {
77
78
  cursor: boolean;
78
79
  });
79
80
  /**
80
- * A recorded, traced 1440x900 context. A config identity starts signed in
81
+ * A recorded, traced context: 1440x900, or with `device: 'phone'` a 390x844 touch phone. A config identity starts signed in
81
82
  * from the cached session (no login form is ever recorded); `'anon'` starts
82
83
  * signed out, for public pages. Open at most two per journey.
83
84
  */
84
85
  open(label: string, identity: string, opts?: {
85
86
  fresh?: boolean;
87
+ device?: JourneyDevice;
86
88
  }): Promise<Page>;
87
89
  private recordedFor;
88
90
  /** A chapter at this instant: one plain line, shown in the caption bar and the .srt. */
@@ -126,7 +128,7 @@ export declare class Journey {
126
128
  fullPage?: boolean;
127
129
  phoneUrl?: string;
128
130
  }): Promise<{
129
- desktop: string;
131
+ desktop?: string;
130
132
  phone?: string;
131
133
  }>;
132
134
  private budgetTurn;
@@ -21,6 +21,10 @@ export interface HighlightSegment {
21
21
  k: number;
22
22
  text: string;
23
23
  }
24
+ type Frame = {
25
+ width: number;
26
+ height: number;
27
+ };
24
28
  export declare const MAX_HIGHLIGHTS_S = 178;
25
29
  export declare function probeSeconds(file: string): number;
26
30
  /** Chapters on the video's own clock; each caption holds until the next. */
@@ -42,6 +46,8 @@ interface PostProcessInput {
42
46
  wallSeconds: number;
43
47
  chapters: readonly Chapter[];
44
48
  speedup2x: boolean;
49
+ /** The recorded frame; desktop when absent. */
50
+ size?: Frame;
45
51
  }
46
52
  export declare function postProcessVideo(o: PostProcessInput): string[];
47
53
  /** Re-render from a raw folder after editing `<label>.chapters.json` by hand. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "packageManager": "pnpm@11.28.8",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/journeys/score.ts","../src/journeys/config.ts","../src/journeys/scrub.ts","../src/journeys/trace-zip.ts","../src/journeys/session.ts","../src/journeys/video.ts","../src/journeys/report.ts","../src/journeys/scoreboard.ts"],"sourcesContent":["/**\n * Whether a recorded chat turn worked, decided from what the person saw.\n *\n * The GTM journey harness scored 6 of 6 failed turns \"completed\":\n * it read failure only from `role=\"alert\"` and from the tail of the assistant's\n * markdown, and the red failure card a person saw carried neither. One caption\n * read \"Turn complete after 159.6 s\" over \"The agent stopped before finishing\".\n * This module is the replacement rule, pure so every case is a unit test:\n *\n * - failure evidence is read from the transcript region (failure-marked\n * elements, failure lines in plain text, and a Retry control that appeared),\n * not from the reply alone, and from after the turn's own prompt when the\n * page shows it (see page-reading.ts);\n * - only evidence that appeared during the turn counts, so an earlier failure in\n * the same thread cannot fail a later turn, even one the page re-renders after\n * Send, and a card that Retry replaced with a new failure still counts;\n * - a turn that ends with no new reply text is `empty`, never `completed`;\n * - a turn the person stopped is `stopped`, not a success and not a crash.\n */\n\n/** What one poll of the page returns. Collected in the page, judged here. */\nexport interface TranscriptSnapshot {\n /** Visible lines of the transcript region, trimmed, empty lines dropped. */\n readonly lines: readonly string[]\n /** Text of every failure-marked element (including hidden details). */\n readonly failureNodes: readonly string[]\n /** Retry controls inside the transcript region. */\n readonly retryButtons: number\n /**\n * The fields above hold only what follows the turn's own prompt. Everything\n * after the prompt is the turn's, so no earlier floor applies to it.\n */\n readonly anchored?: boolean\n}\n\nexport interface FailurePatterns {\n /** A line matching one of these is failure evidence. */\n readonly failure: readonly RegExp[]\n /** A line matching one of these means the person stopped the turn. */\n readonly stopped: readonly RegExp[]\n}\n\n/**\n * Failure text any agent app can show: typed failure codes, provider errors and\n * this package's own sandbox-stream copy. An app adds its own card copy through\n * `chat.failureText` in its journeys config.\n *\n * Matched as substrings of whole lines. A reply that QUOTES one of these fails\n * the turn too; that direction is deliberate, because missing a failure passes a\n * broken product while over-matching only costs a rerun.\n */\nexport const DEFAULT_FAILURE_TEXT: readonly RegExp[] = [\n /\\b[a-z]+(?:_[a-z]+)*\\.[a-z]+(?:_[a-z]+)*_(?:failed|unavailable|timeout)\\b/,\n /\\bAPIError \\d{3}\\b/,\n /stopped before a clean completion/i,\n /Failed to connect to Sandbox API/i,\n /\\bbilling\\.balance_required\\b|Add balance or upgrade your plan/i,\n /Internal Server Error/,\n /\\bECONNREFUSED\\b/,\n /Something went wrong/i,\n // agent-app's own sandbox failure copy (`formatSandboxProvisioningUserMessage`),\n // which every app on the shared runtime can render as a reply. Tests drive the\n // formatter's every branch through these, so the copy and the scorer cannot drift.\n /unable to (?:re)?connect to the sandbox/i,\n /sandbox service didn.t answer/i,\n /Sandbox recovery is required before chat can continue/i,\n /couldn.t (?:finish copying|copy) your Vault into the sandbox/i,\n /too large (?:for the sandbox to accept|to copy into the sandbox)/i,\n /attachment data is staged in the sandbox/i,\n]\n\n/** Runtime wording for a turn the person stopped. Apps add their own copy. */\nexport const DEFAULT_STOPPED_TEXT: readonly RegExp[] = [\n /interrupted by the user/i,\n /cancell?ed by (?:the )?user/i,\n /stopped by (?:the )?user/i,\n]\n\nfunction normalize(line: string): string {\n return line.replace(/\\s+/g, ' ').trim()\n}\n\n/** Every keyed item of a snapshot that can count as failure evidence. */\nfunction evidenceKeys(snapshot: TranscriptSnapshot, patterns: FailurePatterns, ignore: ReadonlySet<string>): Map<string, number> {\n const counts = new Map<string, number>()\n const add = (key: string) => counts.set(key, (counts.get(key) ?? 0) + 1)\n for (const raw of snapshot.lines) {\n const line = normalize(raw)\n if (!line || ignore.has(line)) continue\n if (patterns.stopped.some((p) => p.test(line))) add(`stopped:${line}`)\n else if (patterns.failure.some((p) => p.test(line))) add(`text:${line}`)\n }\n for (const raw of snapshot.failureNodes) {\n const text = normalize(raw)\n if (text && !ignore.has(text)) add(`node:${text.slice(0, 300)}`)\n }\n for (let i = 0; i < snapshot.retryButtons; i += 1) add('retry')\n return counts\n}\n\n/**\n * Failure evidence that appeared after the turn was sent.\n *\n * `begin` takes the snapshot from just before Send. Every later `observe`\n * lowers each item's floor to the fewest copies seen so far: when Retry removes\n * the old card and a new failure renders the same words, the count dips to zero\n * and climbs back to one, and that one is new. Anything that rose above its\n * floor at any point counts, even if the page later replaced it: on 2026-10-11\n * GTM showed \"The sandbox model stream stopped before a clean completion …\n * Hub credential source is revoked or expired\" five minutes into a turn, then\n * swapped it for a different card six minutes later.\n */\nexport class TurnEvidence {\n private floor = new Map<string, number>()\n private peak = new Map<string, number>()\n private anchored = false\n private readonly ignore: Set<string>\n\n constructor(private readonly patterns: FailurePatterns, prompt: string) {\n // The person's own prompt is on the page too; a prompt that mentions an\n // error must not fail its own turn.\n this.ignore = new Set(prompt.split('\\n').map(normalize).filter(Boolean))\n this.ignore.add(normalize(prompt))\n }\n\n begin(snapshot: TranscriptSnapshot): void {\n this.floor = evidenceKeys(snapshot, this.patterns, this.ignore)\n this.peak = new Map()\n this.anchored = snapshot.anchored === true\n }\n\n /** Read one snapshot. Returns the evidence that appeared for the first time, as display text. */\n observe(snapshot: TranscriptSnapshot): string[] {\n if (snapshot.anchored && !this.anchored) {\n // The first read that shows this turn's prompt: a floor taken from the whole transcript no longer applies.\n this.floor = new Map()\n this.anchored = true\n }\n const now = evidenceKeys(snapshot, this.patterns, this.ignore)\n for (const [key, floor] of this.floor) {\n const count = now.get(key) ?? 0\n if (count < floor) this.floor.set(key, count)\n }\n const fresh: string[] = []\n for (const [key, count] of now) {\n const extra = count - (this.floor.get(key) ?? 0)\n if (extra <= (this.peak.get(key) ?? 0)) continue\n if (!this.peak.has(key)) fresh.push(display(key))\n this.peak.set(key, extra)\n }\n return fresh\n }\n\n /** Everything that rose above its floor during the turn, in the order it appeared. */\n added(): { failures: string[]; stopped: string[]; retryAppeared: boolean } {\n const failures: string[] = []\n const stopped: string[] = []\n let retryAppeared = false\n for (const key of this.peak.keys()) {\n if (key === 'retry') retryAppeared = true\n else if (key.startsWith('stopped:')) stopped.push(key.slice('stopped:'.length))\n else failures.push(key.slice(key.indexOf(':') + 1))\n }\n return { failures, stopped, retryAppeared }\n }\n}\n\nfunction display(key: string): string {\n return key === 'retry' ? 'a Retry control appeared in the transcript' : key.slice(key.indexOf(':') + 1)\n}\n\n/**\n * Whether a turn is still going, from what the page shows. A status line is\n * progress while it changes; one left unchanged for {@link STATUS_STALE_MS}\n * with no Stop control is a notice left behind (GTM's \"Request was\n * interrupted by the user. Send a new message to continue.\" is a lasting\n * `role=\"status\"`), and treating it as progress held a stopped turn open until\n * its 15-minute timeout.\n */\nexport const STATUS_STALE_MS = 20_000\n\nexport function turnLooksActive(page: { stopVisible: boolean; statusLines: number; msSinceStatusChanged: number }): boolean {\n return page.stopVisible || (page.statusLines > 0 && page.msSinceStatusChanged < STATUS_STALE_MS)\n}\n\nexport type TurnOutcome = 'completed' | 'failed' | 'stopped' | 'empty' | 'timeout' | 'not-sent'\n\nexport interface TurnVerdict {\n outcome: TurnOutcome\n /** Plain words for a caption: the first failure line, or why the turn is not a pass. */\n error: string | null\n /** Every piece of failure evidence the turn added, for the report. */\n failures: string[]\n}\n\nexport interface TurnFacts {\n /** The send never reached the app. */\n readonly notSent?: string\n /** The app still listed the turn as running when the wait ran out. */\n readonly timedOut: boolean\n readonly evidence: ReturnType<TurnEvidence['added']>\n /** New reply characters this turn added. */\n readonly replyChars: number\n /** The journey pressed Stop during this turn. */\n readonly stopPressed: boolean\n}\n\n/** The one place a turn's outcome is decided. Order matters: evidence first. */\nexport function scoreTurn(facts: TurnFacts): TurnVerdict {\n if (facts.notSent) return { outcome: 'not-sent', error: facts.notSent, failures: [] }\n const { failures, stopped, retryAppeared } = facts.evidence\n const all = [...stopped, ...failures, ...(retryAppeared ? ['a Retry control appeared in the transcript'] : [])]\n // A Stop that took effect. One that did not (still running at the deadline)\n // falls through to `timeout`, because Stop failing is itself the defect.\n if (stopped.length || (facts.stopPressed && !facts.timedOut)) {\n return { outcome: 'stopped', error: stopped[0] ?? failures[0] ?? 'stopped by the journey', failures: all }\n }\n if (failures.length || retryAppeared) {\n return { outcome: 'failed', error: failures[0] ?? 'a Retry control appeared in the transcript', failures: all }\n }\n if (facts.timedOut) return { outcome: 'timeout', error: 'the turn was still running when the wait ended', failures: all }\n if (facts.replyChars === 0) return { outcome: 'empty', error: 'the turn ended without any reply text', failures: all }\n return { outcome: 'completed', error: null, failures: [] }\n}\n","/**\n * What an app tells the journeys kit about itself: where it is served, which\n * test identities may sign in, and the chat DOM a turn is measured on.\n *\n * It lives at the app root as `journeys.config.mjs`, beside\n * `launch-invariants.config.mjs`:\n *\n * import { defineJourneys } from '@tangle-network/agent-app/journeys'\n * export default defineJourneys({\n * app: 'gtm',\n * baseUrl: 'https://gtm.tangle.tools',\n * identities: {\n * member: { emailEnv: 'SMOKE_EMAIL', passwordEnv: 'SMOKE_PASSWORD', signIn: 'tangle' },\n * },\n * chat: { assistant: '.gtm-assistant-markdown', failureText: [/stopped before finishing/i] },\n * })\n *\n * Credentials are named, never stored: the config holds environment variable\n * names, and the values reach the process from the host's vault.\n */\nimport { existsSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { DEFAULT_FAILURE_TEXT, DEFAULT_STOPPED_TEXT } from './score.js'\n\nexport type SignInMethod = 'password' | 'tangle'\n\nexport interface JourneyIdentity {\n /** Environment variable that holds the account's email. */\n readonly emailEnv: string\n /** Environment variable that holds the account's password. */\n readonly passwordEnv: string\n /**\n * `password`: the app's own email sign-in (better-auth `sign-in/email`).\n * `tangle`: \"Log in with Tangle\": the app's SSO start, the Platform's email\n * sign-in, then the app's callback.\n */\n readonly signIn: SignInMethod\n}\n\n/** The ids a thread URL carries. */\nexport interface ThreadRoute {\n readonly threadId: string\n readonly workspaceId?: string\n}\n\n/**\n * The chat DOM a turn is read from. Defaults are agent-app's own components:\n * `ChatComposer` (the composer card, \"Message input\", \"Send\", \"Stop response\")\n * and the transcript's failure rows (`role=\"alert\"`, `data-notice-tone=\"error\"`).\n */\nexport interface ChatContract {\n /** Region whose text decides a turn's outcome. */\n readonly transcript: string\n /** Assistant reply blocks. `null` measures reply text as transcript growth beyond the prompt. */\n readonly assistant: string | null\n /** Progress lines inside the transcript (\"Sending…\", \"Searching the web\"). */\n readonly status: string\n /** Elements that mark a failed turn. */\n readonly failureNodes: string\n /** Failure lines this app shows in plain text, added to the package defaults. */\n readonly failureText: readonly RegExp[]\n /** Lines meaning the person stopped the turn, added to the package defaults. */\n readonly stoppedText: readonly RegExp[]\n /** The card holding the composer's input and action row. */\n readonly composer: string\n /** Accessible names inside the composer card. */\n readonly inputName: string\n readonly sendName: string\n readonly stopName: string\n /** Accessible name of a failed turn's retry control. */\n readonly retryName: RegExp\n /** A created thread's path. Named groups `threadId` (required) and `workspaceId`. */\n readonly threadPath: RegExp | null\n /** Path that lists a thread's running turns as JSON `{ running: string[] }`; the server's word on completion. */\n readonly runningTurns: ((route: ThreadRoute) => string) | null\n /** POST paths that mean the composer submitted, besides the page's own route. */\n readonly sendPaths: readonly RegExp[]\n}\n\nexport interface AuthPaths {\n readonly session: string\n readonly passwordSignIn: string\n readonly tangleStart: string\n}\n\nexport interface JourneysConfig {\n /** Short name, used for state and output folders. */\n readonly app: string\n /** Origin the journeys drive. `JOURNEYS_BASE_URL` overrides it, for a local stack. */\n readonly baseUrl: string\n readonly identities: Readonly<Record<string, JourneyIdentity>>\n readonly chat?: Partial<ChatContract>\n readonly auth?: Partial<AuthPaths>\n /** Chat turns one journey may send. Default 6. */\n readonly maxTurns?: number\n /** Sessions and raw recordings. Default `~/.local/state/agent-app-journeys/<app>`. */\n readonly stateDir?: string\n /** Files safe to copy off the host. Default `<stateDir>/out`. */\n readonly outDir?: string\n}\n\nexport interface ResolvedJourneysConfig {\n /** Marks a config whose defaults are filled; resolving it again returns it unchanged. */\n readonly resolved: true\n readonly app: string\n readonly baseUrl: string\n readonly identities: Readonly<Record<string, JourneyIdentity>>\n readonly chat: ChatContract\n readonly auth: AuthPaths\n readonly maxTurns: number\n readonly stateDir: string\n readonly outDir: string\n}\n\nexport const DEFAULT_CHAT_CONTRACT: ChatContract = {\n transcript: 'main',\n assistant: null,\n status: '[role=\"status\"]',\n failureNodes: '[role=\"alert\"], [data-notice-tone=\"error\"]',\n failureText: [],\n stoppedText: [],\n composer: '[data-testid=\"composer-card\"]',\n inputName: 'Message input',\n sendName: 'Send',\n stopName: 'Stop response',\n retryName: /^Retry$/,\n threadPath: null,\n runningTurns: null,\n sendPaths: [/^\\/api\\/(?:[^/]+\\/)*chat$/],\n}\n\nexport const DEFAULT_AUTH_PATHS: AuthPaths = {\n session: '/api/auth/get-session',\n passwordSignIn: '/api/auth/sign-in/email',\n tangleStart: '/auth/tangle/start',\n}\n\nexport const CONFIG_FILE_NAMES = ['journeys.config.mjs', 'journeys.config.js'] as const\n\n/** Identity for a typed config; also validates it. */\nexport function defineJourneys(config: JourneysConfig): JourneysConfig {\n resolveJourneysConfig(config)\n return config\n}\n\nconst ENV_NAME = /^[A-Z_][A-Z0-9_]*$/\n\n/** Fill defaults and refuse a config that cannot drive a journey. */\nexport function resolveJourneysConfig(config: JourneysConfig | ResolvedJourneysConfig, env: Record<string, string | undefined> = process.env): ResolvedJourneysConfig {\n if ('resolved' in config && config.resolved === true) return config\n const problems: string[] = []\n if (!/^[a-z0-9][a-z0-9-]{0,40}$/.test(config.app ?? '')) problems.push('app must be a short lowercase name such as \"gtm\"')\n const base = (env.JOURNEYS_BASE_URL ?? config.baseUrl ?? '').replace(/\\/$/, '')\n if (!/^https?:\\/\\/[^/]+$/.test(base)) problems.push(`baseUrl must be an origin such as https://app.example.com, got \"${base}\"`)\n const identities = config.identities ?? {}\n if (Object.keys(identities).length === 0) problems.push('identities must name at least one test identity')\n for (const [name, identity] of Object.entries(identities)) {\n if (name === 'anon') problems.push('\"anon\" is reserved for a signed-out context')\n if (!/^[a-z][a-z0-9-]*$/.test(name)) problems.push(`identity \"${name}\": use a lowercase name`)\n for (const key of ['emailEnv', 'passwordEnv'] as const) {\n if (!ENV_NAME.test(identity[key] ?? '')) problems.push(`identity \"${name}\": ${key} must be an environment variable NAME, not a value`)\n }\n if (identity.signIn !== 'password' && identity.signIn !== 'tangle') problems.push(`identity \"${name}\": signIn must be \"password\" or \"tangle\"`)\n }\n const chat: ChatContract = {\n ...DEFAULT_CHAT_CONTRACT,\n ...config.chat,\n failureText: [...DEFAULT_FAILURE_TEXT, ...(config.chat?.failureText ?? [])],\n stoppedText: [...DEFAULT_STOPPED_TEXT, ...(config.chat?.stoppedText ?? [])],\n }\n if (chat.threadPath && !/\\(\\?<threadId>/.test(chat.threadPath.source)) problems.push('chat.threadPath needs a named group (?<threadId>…)')\n const maxTurns = config.maxTurns ?? 6\n if (!Number.isInteger(maxTurns) || maxTurns < 0) problems.push('maxTurns must be a whole number')\n if (problems.length) throw new Error(`journeys config: ${problems.join('; ')}`)\n const stateDir = resolve(env.JOURNEYS_STATE_DIR ?? config.stateDir ?? join(homedir(), '.local/state/agent-app-journeys', config.app))\n return {\n resolved: true,\n app: config.app,\n baseUrl: base,\n identities,\n chat,\n auth: { ...DEFAULT_AUTH_PATHS, ...config.auth },\n maxTurns,\n stateDir,\n outDir: resolve(env.JOURNEYS_OUT ?? config.outDir ?? join(stateDir, 'out')),\n }\n}\n\n/** The ids in a thread URL, or null when the URL is not a thread on this origin. */\nexport function threadRouteIn(url: string, config: Pick<ResolvedJourneysConfig, 'baseUrl' | 'chat'>): ThreadRoute | null {\n if (!config.chat.threadPath) return null\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n return null\n }\n if (parsed.origin !== new URL(config.baseUrl).origin) return null\n const match = config.chat.threadPath.exec(parsed.pathname)\n const threadId = match?.groups?.threadId\n if (!threadId) return null\n const workspaceId = match?.groups?.workspaceId\n return workspaceId ? { threadId, workspaceId } : { threadId }\n}\n\n/** Environment variable names the config needs, for a vault loader. */\nexport function credentialNames(config: Pick<JourneysConfig, 'identities'>): string[] {\n return [...new Set(Object.values(config.identities).flatMap((identity) => [identity.emailEnv, identity.passwordEnv]))]\n}\n\n/** `JOURNEYS_CONFIG`, else the first config file in `dir`. */\nexport async function loadJourneysConfig(dir = process.cwd(), env: Record<string, string | undefined> = process.env): Promise<ResolvedJourneysConfig> {\n const file = env.JOURNEYS_CONFIG\n ? resolve(dir, env.JOURNEYS_CONFIG)\n : CONFIG_FILE_NAMES.map((name) => join(dir, name)).find((path) => existsSync(path))\n if (!file || !existsSync(file)) {\n throw new Error(`no ${CONFIG_FILE_NAMES[0]} in ${dir}; add one at the app root or set JOURNEYS_CONFIG`)\n }\n const loaded = (await import(pathToFileURL(file).href)) as { default?: JourneysConfig }\n if (!loaded.default) throw new Error(`${file} must export default defineJourneys({ … })`)\n return resolveJourneysConfig(loaded.default, env)\n}\n","/**\n * Making a journey's files safe to copy off the host.\n *\n * `scrubTrace` rewrites a Playwright trace.zip: it blanks cookie and\n * authorization headers and HAR cookie lists, blanks token-like query values,\n * drops the bodies of auth, token, session and collaboration calls, and then\n * replaces every needle (passwords, cookie values, the identities' emails)\n * anywhere in any entry. `assertNoSecrets` re-reads every output file, inside\n * the zips too, and refuses the whole folder if a password or cookie value\n * survived anywhere.\n */\nimport { readdirSync, readFileSync, statSync, openSync, closeSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { createZipWriter, inflateEntry, readCentralDirectory, readRaw } from './trace-zip.js'\n\nconst SENSITIVE_HEADERS = new Set([\n 'cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key',\n 'x-auth-token', 'x-stream-token', 'cf-access-token', 'x-csrf-token',\n])\nconst SENSITIVE_PATH = /\\/api\\/auth\\/|\\/auth\\/tangle\\/|token|session|\\/api\\/collaboration\\/|oauth|\\/consent|\\/api-access|api-key/i\nconst QUERY_NAMES = 'token|access_token|refresh_token|id_token|code|state|key|api_key|apikey|signature|sig|jwt|ticket|secret'\nconst QUERY = new RegExp(`([?&](?:${QUERY_NAMES})=)[^&\"'\\\\s\\\\\\\\]+`, 'gi')\nconst QUERY_NAME = new RegExp(`^(?:${QUERY_NAMES})$`, 'i')\nconst REDACTED = 'REDACTED'\n\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json }\ntype JsonObject = { [key: string]: Json }\n\nconst isObject = (v: Json | undefined): v is JsonObject => typeof v === 'object' && v !== null && !Array.isArray(v)\n\nfunction scrubHeaders(headers: Json | undefined): void {\n if (Array.isArray(headers)) {\n for (const h of headers) {\n if (isObject(h) && SENSITIVE_HEADERS.has(String(h.name ?? '').toLowerCase())) h.value = REDACTED\n }\n } else if (isObject(headers)) {\n for (const key of Object.keys(headers)) if (SENSITIVE_HEADERS.has(key.toLowerCase())) headers[key] = REDACTED\n }\n}\n\n/** Drop an inline or stored body; Playwright points at stored ones with `_file` or `_sha1`. */\nfunction forgetBody(holder: JsonObject, drop: Set<string>): void {\n for (const key of ['_file', '_sha1']) {\n const ref = holder[key]\n if (ref) {\n drop.add(String(ref).split('/').pop() ?? '')\n holder[key] = null\n }\n }\n if ('text' in holder) holder.text = REDACTED\n}\n\n/** Scrub any HAR-like request/response anywhere in one trace event. */\nfunction walk(node: Json | undefined, drop: Set<string>): void {\n if (Array.isArray(node)) {\n for (const v of node) walk(v, drop)\n return\n }\n if (!isObject(node)) return\n const req = node.request\n const res = node.response\n if (isObject(req) && 'url' in req) {\n const sensitive = SENSITIVE_PATH.test(String(req.url ?? '').split('?')[0] ?? '')\n scrubHeaders(req.headers)\n if ('cookies' in req) req.cookies = []\n const query = req.queryString\n if (Array.isArray(query)) {\n for (const q of query) if (isObject(q) && QUERY_NAME.test(String(q.name ?? ''))) q.value = REDACTED\n }\n if (sensitive && isObject(req.postData)) forgetBody(req.postData, drop)\n if (isObject(res)) {\n scrubHeaders(res.headers)\n if ('cookies' in res) res.cookies = []\n if (sensitive && isObject(res.content)) forgetBody(res.content, drop)\n }\n }\n for (const [key, value] of Object.entries(node)) {\n if (key.toLowerCase() === 'cookies' && Array.isArray(value)) node[key] = []\n else if (key === 'storageState') node[key] = null\n else if (SENSITIVE_HEADERS.has(key.toLowerCase()) && typeof value === 'string') node[key] = REDACTED\n else walk(value, drop)\n }\n}\n\n/** One `.trace` or `.network` JSONL entry, scrubbed. Bodies it dropped are added to `drop`. */\nexport function scrubJsonl(text: string, drop: Set<string>): string {\n const out: string[] = []\n for (const line of text.split('\\n')) {\n if (!line.trim()) continue\n let event: Json\n try {\n event = JSON.parse(line) as Json\n } catch {\n out.push(line.replace(QUERY, `$1${REDACTED}`))\n continue\n }\n walk(event, drop)\n out.push(JSON.stringify(event).replace(QUERY, `$1${REDACTED}`))\n }\n return out.join('\\n') + '\\n'\n}\n\n/** Every occurrence of every needle replaced. */\nexport function replaceNeedles(data: Buffer, needles: readonly string[]): Buffer {\n let out = data\n for (const needle of needles) {\n if (!needle) continue\n const n = Buffer.from(needle, 'utf8')\n if (out.indexOf(n) < 0) continue\n const parts: Buffer[] = []\n let from = 0\n for (let at = out.indexOf(n); at >= 0; at = out.indexOf(n, from)) {\n parts.push(out.subarray(from, at), Buffer.from(REDACTED))\n from = at + n.length\n }\n parts.push(out.subarray(from))\n out = Buffer.concat(parts)\n }\n return out\n}\n\nconst isEvents = (name: string) => name.endsWith('.trace') || name.endsWith('.network')\n\n/** Write a scrubbed copy of `src` to `dst`. Entries keep their order; dropped bodies are left out. */\nexport function scrubTrace(src: string, dst: string, needles: readonly string[]): { entries: number; dropped: number; rewritten: number } {\n const fd = openSync(src, 'r')\n try {\n const entries = readCentralDirectory(fd)\n const drop = new Set<string>()\n // Events first, so the bodies they point at are known before resources are copied.\n const events = new Map<string, Buffer>()\n for (const entry of entries) {\n if (!isEvents(entry.name)) continue\n events.set(entry.name, Buffer.from(scrubJsonl(inflateEntry(entry, readRaw(fd, entry)).toString('utf8'), drop), 'utf8'))\n }\n const writer = createZipWriter(dst)\n let dropped = 0\n let rewritten = 0\n for (const entry of entries) {\n const base = entry.name.split('/').pop() ?? ''\n if (entry.name.startsWith('resources/') && drop.has(base)) {\n dropped += 1\n continue\n }\n const raw = readRaw(fd, entry)\n const content = events.get(entry.name) ?? inflateEntry(entry, raw)\n const clean = replaceNeedles(content, needles)\n if (!events.has(entry.name) && clean === content) {\n writer.copy(entry, raw)\n } else {\n writer.add(entry.name, clean, entry)\n rewritten += 1\n }\n }\n writer.close()\n return { entries: entries.length, dropped, rewritten }\n } finally {\n closeSync(fd)\n }\n}\n\n/** Entries of a zip that still hold a hard needle, and how many mention a soft one. */\nfunction scanZip(path: string, hard: readonly string[], soft: readonly string[]): { hard: string[]; soft: number } {\n const fd = openSync(path, 'r')\n try {\n const hits: string[] = []\n let softHits = 0\n const hardBytes = hard.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n const softBytes = soft.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n for (const entry of readCentralDirectory(fd)) {\n const content = inflateEntry(entry, readRaw(fd, entry))\n if (hardBytes.some((n) => content.includes(n))) hits.push(entry.name)\n if (softBytes.some((n) => content.includes(n))) softHits += 1\n }\n return { hard: hits, soft: softHits }\n } finally {\n closeSync(fd)\n }\n}\n\n/**\n * Refuse to hand over a folder whose files hold a password or cookie value.\n * An identity's email only warns: it is a company test address, not a secret,\n * but it should be blurred before footage is shown outside the company.\n */\nexport function assertNoSecrets(dir: string, needles: { hard: readonly string[]; soft: readonly string[] }): { softHits: string[] } {\n const hits: string[] = []\n const softHits: string[] = []\n const hard = needles.hard.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n const soft = needles.soft.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n const visit = (d: string) => {\n for (const name of readdirSync(d)) {\n const path = join(d, name)\n if (statSync(path).isDirectory()) {\n visit(path)\n continue\n }\n if (path.endsWith('.zip')) {\n const found = scanZip(path, needles.hard, needles.soft)\n if (found.hard.length) hits.push(`${path} (${found.hard.slice(0, 5).join(', ')})`)\n if (found.soft) softHits.push(`${path} (${found.soft} entries)`)\n continue\n }\n const buf = readFileSync(path)\n if (hard.some((n) => buf.includes(n))) hits.push(path)\n if (soft.some((n) => buf.includes(n))) softHits.push(path)\n }\n }\n visit(dir)\n if (softHits.length) console.warn(`note: a test identity's email appears in ${softHits.join(', ')}; blur it before sharing outside the company`)\n if (hits.length) throw new Error(`REFUSING: secret material found in ${hits.join(', ')}; do not copy ${dir}`)\n return { softHits }\n}\n","/**\n * The slice of PKZIP a Playwright trace needs: read every entry of an archive\n * on disk one at a time, and write a new archive entry by entry.\n *\n * Why not `documents/zip`: that reader holds the archive in memory and refuses\n * zip64, and a recorded hour-long journey's trace is 6.6 GB with 49,117\n * entries, so offsets pass 4 GiB. This reader keeps\n * one entry in memory at a time and reads the zip64 records; the writer emits\n * zip64 fields only when a size, an offset or the entry count needs them.\n */\nimport { closeSync, fstatSync, openSync, readSync, writeSync } from 'node:fs'\nimport { deflateRawSync, inflateRawSync } from 'node:zlib'\nimport { crc32Update } from '../workspace-export/checksum.js'\n\nconst EOCD = 0x06054b50\nconst ZIP64_EOCD = 0x06064b50\nconst ZIP64_LOCATOR = 0x07064b50\nconst CENTRAL = 0x02014b50\nconst LOCAL = 0x04034b50\nconst U16 = 0xffff\nconst U32 = 0xffffffff\n\ninterface ZipEntryInfo {\n readonly name: string\n readonly method: number\n readonly crc32: number\n readonly compressedSize: number\n readonly uncompressedSize: number\n readonly localOffset: number\n readonly dosTime: number\n readonly dosDate: number\n}\n\nfunction readAt(fd: number, position: number, length: number): Buffer {\n const out = Buffer.alloc(length)\n let done = 0\n while (done < length) {\n const n = readSync(fd, out, done, length - done, position + done)\n if (n === 0) throw new Error(`zip: unexpected end of file at ${position + done}`)\n done += n\n }\n return out\n}\n\nconst u64 = (b: Buffer, at: number) => Number(b.readBigUInt64LE(at))\n\n/** Every entry in the central directory, sizes and offsets resolved through zip64 extras. */\nexport function readCentralDirectory(fd: number): ZipEntryInfo[] {\n const size = fstatSync(fd).size\n const tailLength = Math.min(size, 22 + U16 + 20)\n const tail = readAt(fd, size - tailLength, tailLength)\n let eocd = -1\n for (let i = tail.length - 22; i >= 0; i -= 1) {\n if (tail.readUInt32LE(i) === EOCD && i + 22 + tail.readUInt16LE(i + 20) === tail.length) {\n eocd = i\n break\n }\n }\n if (eocd < 0) throw new Error('zip: no end-of-central-directory record')\n let count = tail.readUInt16LE(eocd + 10)\n let cdSize = tail.readUInt32LE(eocd + 12)\n let cdOffset = tail.readUInt32LE(eocd + 16)\n if (eocd >= 20 && tail.readUInt32LE(eocd - 20) === ZIP64_LOCATOR) {\n const record = readAt(fd, u64(tail, eocd - 20 + 8), 56)\n if (record.readUInt32LE(0) !== ZIP64_EOCD) throw new Error('zip: zip64 locator points at no zip64 record')\n count = u64(record, 32)\n cdSize = u64(record, 40)\n cdOffset = u64(record, 48)\n }\n const cd = readAt(fd, cdOffset, cdSize)\n const entries: ZipEntryInfo[] = []\n let at = 0\n for (let i = 0; i < count; i += 1) {\n if (cd.readUInt32LE(at) !== CENTRAL) throw new Error(`zip: central directory is broken at entry ${i + 1} of ${count}`)\n const nameLength = cd.readUInt16LE(at + 28)\n const extraLength = cd.readUInt16LE(at + 30)\n const commentLength = cd.readUInt16LE(at + 32)\n let compressedSize = cd.readUInt32LE(at + 20)\n let uncompressedSize = cd.readUInt32LE(at + 24)\n let localOffset = cd.readUInt32LE(at + 42)\n const extra = cd.subarray(at + 46 + nameLength, at + 46 + nameLength + extraLength)\n for (let e = 0; e + 4 <= extra.length; ) {\n const id = extra.readUInt16LE(e)\n const len = extra.readUInt16LE(e + 2)\n if (id === 0x0001) {\n // Present in this order, and only for the fields set to 0xffffffff.\n let p = e + 4\n if (uncompressedSize === U32) { uncompressedSize = u64(extra, p); p += 8 }\n if (compressedSize === U32) { compressedSize = u64(extra, p); p += 8 }\n if (localOffset === U32) { localOffset = u64(extra, p); p += 8 }\n }\n e += 4 + len\n }\n entries.push({\n name: cd.toString('utf8', at + 46, at + 46 + nameLength),\n method: cd.readUInt16LE(at + 10),\n crc32: cd.readUInt32LE(at + 16),\n compressedSize,\n uncompressedSize,\n localOffset,\n dosTime: cd.readUInt16LE(at + 12),\n dosDate: cd.readUInt16LE(at + 14),\n })\n at += 46 + nameLength + extraLength + commentLength\n }\n return entries\n}\n\n/** One entry's stored bytes, still compressed. */\nexport function readRaw(fd: number, entry: ZipEntryInfo): Buffer {\n const local = readAt(fd, entry.localOffset, 30)\n if (local.readUInt32LE(0) !== LOCAL) throw new Error(`zip: '${entry.name}' has no local header`)\n const start = entry.localOffset + 30 + local.readUInt16LE(26) + local.readUInt16LE(28)\n return readAt(fd, start, entry.compressedSize)\n}\n\n/** One entry's content. */\nexport function inflateEntry(entry: ZipEntryInfo, raw: Buffer): Buffer {\n if (entry.method === 0) return raw\n if (entry.method === 8) return inflateRawSync(raw)\n throw new Error(`zip: '${entry.name}' uses unsupported compression method ${entry.method}`)\n}\n\ninterface ZipWriter {\n /** Add an entry from its content (deflated here). */\n add(name: string, content: Buffer, from?: Pick<ZipEntryInfo, 'dosTime' | 'dosDate'>): void\n /** Add an entry exactly as another archive stored it. */\n copy(entry: ZipEntryInfo, raw: Buffer): void\n close(): void\n}\n\ninterface Written {\n name: Buffer\n method: number\n crc32: number\n compressedSize: number\n uncompressedSize: number\n offset: number\n dosTime: number\n dosDate: number\n}\n\n/** Write a zip to `path`, entries in the order added. `forceZip64` exercises the large-archive records in tests. */\nexport function createZipWriter(path: string, opts: { forceZip64?: boolean } = {}): ZipWriter {\n const fd = openSync(path, 'w', 0o600)\n let position = 0\n const written: Written[] = []\n const put = (b: Buffer) => {\n let done = 0\n while (done < b.length) done += writeSync(fd, b, done, b.length - done)\n position += b.length\n }\n const big = (n: number) => opts.forceZip64 === true || n >= U32\n const writeEntry = (w: Omit<Written, 'offset'>, data: Buffer) => {\n const zip64 = big(w.compressedSize) || big(w.uncompressedSize)\n const header = Buffer.alloc(30 + w.name.length + (zip64 ? 20 : 0))\n header.writeUInt32LE(LOCAL, 0)\n header.writeUInt16LE(zip64 ? 45 : 20, 4)\n header.writeUInt16LE(0x0800, 6)\n header.writeUInt16LE(w.method, 8)\n header.writeUInt16LE(w.dosTime, 10)\n header.writeUInt16LE(w.dosDate, 12)\n header.writeUInt32LE(w.crc32, 14)\n header.writeUInt32LE(zip64 ? U32 : w.compressedSize, 18)\n header.writeUInt32LE(zip64 ? U32 : w.uncompressedSize, 22)\n header.writeUInt16LE(w.name.length, 26)\n header.writeUInt16LE(zip64 ? 20 : 0, 28)\n w.name.copy(header, 30)\n if (zip64) {\n const e = 30 + w.name.length\n header.writeUInt16LE(0x0001, e)\n header.writeUInt16LE(16, e + 2)\n header.writeBigUInt64LE(BigInt(w.uncompressedSize), e + 4)\n header.writeBigUInt64LE(BigInt(w.compressedSize), e + 12)\n }\n const offset = position\n put(header)\n put(data)\n written.push({ ...w, offset })\n }\n return {\n add(name, content, from) {\n const data = deflateRawSync(content)\n writeEntry({\n name: Buffer.from(name, 'utf8'),\n method: 8,\n crc32: crc32Update(0, content),\n compressedSize: data.length,\n uncompressedSize: content.length,\n dosTime: from?.dosTime ?? 0,\n dosDate: from?.dosDate ?? 0x21,\n }, data)\n },\n copy(entry, raw) {\n writeEntry({\n name: Buffer.from(entry.name, 'utf8'),\n method: entry.method,\n crc32: entry.crc32,\n compressedSize: entry.compressedSize,\n uncompressedSize: entry.uncompressedSize,\n dosTime: entry.dosTime,\n dosDate: entry.dosDate,\n }, raw)\n },\n close() {\n const cdOffset = position\n for (const w of written) {\n const fields: bigint[] = []\n if (big(w.uncompressedSize)) fields.push(BigInt(w.uncompressedSize))\n if (big(w.compressedSize)) fields.push(BigInt(w.compressedSize))\n if (big(w.offset)) fields.push(BigInt(w.offset))\n const extraLength = fields.length ? 4 + 8 * fields.length : 0\n const h = Buffer.alloc(46 + w.name.length + extraLength)\n h.writeUInt32LE(CENTRAL, 0)\n h.writeUInt16LE(45, 4)\n h.writeUInt16LE(fields.length ? 45 : 20, 6)\n h.writeUInt16LE(0x0800, 8)\n h.writeUInt16LE(w.method, 10)\n h.writeUInt16LE(w.dosTime, 12)\n h.writeUInt16LE(w.dosDate, 14)\n h.writeUInt32LE(w.crc32, 16)\n h.writeUInt32LE(big(w.compressedSize) ? U32 : w.compressedSize, 20)\n h.writeUInt32LE(big(w.uncompressedSize) ? U32 : w.uncompressedSize, 24)\n h.writeUInt16LE(w.name.length, 28)\n h.writeUInt16LE(extraLength, 30)\n h.writeUInt32LE(big(w.offset) ? U32 : w.offset, 42)\n w.name.copy(h, 46)\n if (fields.length) {\n const e = 46 + w.name.length\n h.writeUInt16LE(0x0001, e)\n h.writeUInt16LE(8 * fields.length, e + 2)\n fields.forEach((v, i) => h.writeBigUInt64LE(v, e + 4 + 8 * i))\n }\n put(h)\n }\n const cdSize = position - cdOffset\n const count = written.length\n const zip64 = opts.forceZip64 === true || count >= U16 || cdOffset >= U32 || cdSize >= U32\n if (zip64) {\n const recordOffset = position\n const r = Buffer.alloc(56)\n r.writeUInt32LE(ZIP64_EOCD, 0)\n r.writeBigUInt64LE(44n, 4)\n r.writeUInt16LE(45, 12)\n r.writeUInt16LE(45, 14)\n r.writeBigUInt64LE(BigInt(count), 24)\n r.writeBigUInt64LE(BigInt(count), 32)\n r.writeBigUInt64LE(BigInt(cdSize), 40)\n r.writeBigUInt64LE(BigInt(cdOffset), 48)\n put(r)\n const l = Buffer.alloc(20)\n l.writeUInt32LE(ZIP64_LOCATOR, 0)\n l.writeBigUInt64LE(BigInt(recordOffset), 8)\n l.writeUInt32LE(1, 16)\n put(l)\n }\n const end = Buffer.alloc(22)\n end.writeUInt32LE(EOCD, 0)\n end.writeUInt16LE(zip64 ? U16 : count, 8)\n end.writeUInt16LE(zip64 ? U16 : count, 10)\n end.writeUInt32LE(zip64 ? U32 : cdSize, 12)\n end.writeUInt32LE(zip64 ? U32 : cdOffset, 16)\n put(end)\n closeSync(fd)\n },\n }\n}\n","/**\n * Signed-in browser state for an app's test identities, with no login form in\n * any recorded frame.\n *\n * Sign-in happens over HTTP, never in a rendered page, so a recording starts\n * already signed in and no frame can show a password. The resulting storage\n * state (session cookies) is cached per origin and identity under the state\n * directory (mode 0600) and reused while the app's session endpoint still\n * answers with a verified user. Journeys running in parallel share it, so a\n * burst of journeys cannot trip an auth rate limit.\n *\n * Never press Sign out in a shared session: it revokes the session every\n * journey on the host is using. A journey that signs out opens its context with\n * `{ fresh: true }`, which signs in a session of its own.\n */\nimport { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { APIRequestContext } from 'playwright'\nimport type { JourneyIdentity, ResolvedJourneysConfig } from './config.js'\n\nexport interface SessionUser {\n id: string\n name: string | null\n emailVerified: boolean\n}\n\nclass SignInError extends Error {\n constructor(readonly status: number, message: string) {\n super(message)\n }\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n\nasync function playwrightRequest() {\n try {\n return (await import('playwright')).request\n } catch {\n throw new Error('journeys need the optional `playwright` peer: install playwright in the app that runs them')\n }\n}\n\nfunction sessionDir(config: ResolvedJourneysConfig): string {\n return join(config.stateDir, 'sessions', new URL(config.baseUrl).host)\n}\n\nfunction storageStatePath(config: ResolvedJourneysConfig, identity: string): string {\n return join(sessionDir(config), `${identity}.storage.json`)\n}\n\nfunction need(name: string): string {\n const value = process.env[name]?.trim()\n if (!value) throw new Error(`${name} is unset: load it from the host's vault into this process (the value is never printed)`)\n return value\n}\n\n/** The signed-in user behind a storage state, or null when it no longer signs in. */\nexport async function sessionUser(config: ResolvedJourneysConfig, state: string): Promise<SessionUser | null> {\n if (!existsSync(state)) return null\n const request = await playwrightRequest()\n const ctx = await request.newContext({ baseURL: config.baseUrl, storageState: state })\n try {\n const r = await ctx.get(config.auth.session, { maxRedirects: 0, timeout: 20_000 })\n if (!r.ok()) return null\n const body = (await r.json().catch(() => null)) as { user?: { id?: string; name?: string; emailVerified?: boolean } } | null\n const user = body?.user\n if (!user?.id) return null\n return { id: user.id, name: user.name ?? null, emailVerified: user.emailVerified === true }\n } finally {\n await ctx.dispose()\n }\n}\n\nasync function signInWithPassword(ctx: APIRequestContext, config: ResolvedJourneysConfig, email: string, password: string): Promise<void> {\n const r = await ctx.post(`${config.baseUrl}${config.auth.passwordSignIn}`, {\n headers: { 'content-type': 'application/json', origin: config.baseUrl },\n data: { email, password },\n maxRedirects: 0,\n })\n if (r.status() !== 200) throw new SignInError(r.status(), `email sign-in returned ${r.status()}`)\n}\n\n/** \"Log in with Tangle\": the app's start route, Platform sign-in, authorize, the app's callback. */\nasync function signInWithTangle(ctx: APIRequestContext, config: ResolvedJourneysConfig, email: string, password: string): Promise<void> {\n const base = config.baseUrl\n const start = await ctx.get(`${base}${config.auth.tangleStart}`, { maxRedirects: 0 })\n const first = start.headers()['location']\n if (!first) throw new SignInError(start.status(), `SSO start returned ${start.status()} without a redirect`)\n const authorize = new URL(first, base).toString()\n const platform = new URL(authorize).origin\n const signIn = await ctx.post(`${platform}/api/auth/sign-in/email`, {\n headers: { 'content-type': 'application/json', origin: platform },\n data: { email, password },\n maxRedirects: 0,\n })\n if (signIn.status() !== 200) throw new SignInError(signIn.status(), `Platform sign-in returned ${signIn.status()}`)\n const startPrefix = config.auth.tangleStart.replace(/\\/start$/, '/')\n let next = authorize\n for (let hop = 0; hop < 8; hop += 1) {\n const r = await ctx.get(next, { maxRedirects: 0 })\n const location = r.headers()['location']\n // Only a pathname is ever reported: the query carries OAuth codes.\n if (!location) throw new SignInError(r.status(), `SSO stopped at ${new URL(next).pathname} with ${r.status()}`)\n const url = new URL(location, next)\n if (url.origin === new URL(base).origin && !url.pathname.startsWith(startPrefix)) {\n if (url.pathname.startsWith('/login')) throw new SignInError(401, 'the app callback refused the sign-in')\n return\n }\n next = url.toString()\n }\n throw new SignInError(0, 'SSO did not return to the app within 8 redirects')\n}\n\n/** A cross-process lock: mkdir is atomic. A lock older than two minutes is stale. */\nasync function withLock<T>(dir: string, work: () => Promise<T>): Promise<T> {\n const deadline = Date.now() + 180_000\n for (;;) {\n try {\n mkdirSync(dir)\n break\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n const age = Date.now() - (statSync(dir, { throwIfNoEntry: false })?.mtimeMs ?? Date.now())\n if (age > 120_000) rmSync(dir, { recursive: true, force: true })\n if (Date.now() > deadline) throw new Error(`timed out waiting for ${dir}`)\n await sleep(500)\n }\n }\n try {\n return await work()\n } finally {\n rmSync(dir, { recursive: true, force: true })\n }\n}\n\nfunction identityOf(config: ResolvedJourneysConfig, name: string): JourneyIdentity {\n const identity = config.identities[name]\n if (!identity) throw new Error(`\"${name}\" is not an identity in the ${config.app} journeys config (${Object.keys(config.identities).join(', ')})`)\n return identity\n}\n\n/**\n * Path to a storage state signed in as `identity`. Reused while valid;\n * `fresh` signs in a session of its own (for a journey that signs out).\n */\nexport async function storageStateFor(\n config: ResolvedJourneysConfig,\n name: string,\n opts: { fresh?: boolean } = {},\n): Promise<{ path: string; user: SessionUser }> {\n const identity = identityOf(config, name)\n const dir = sessionDir(config)\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n const file = opts.fresh ? join(dir, `${name}.${process.pid}.${Date.now()}.storage.json`) : storageStatePath(config, name)\n const request = await playwrightRequest()\n return withLock(join(dir, `signin-${name}.lock`), async () => {\n if (!opts.fresh) {\n const cached = await sessionUser(config, file)\n if (cached) return { path: file, user: cached }\n }\n const email = need(identity.emailEnv)\n const password = need(identity.passwordEnv)\n for (let attempt = 1; ; attempt += 1) {\n const ctx = await request.newContext({ baseURL: config.baseUrl })\n try {\n if (identity.signIn === 'password') await signInWithPassword(ctx, config, email, password)\n else await signInWithTangle(ctx, config, email, password)\n const tmp = `${file}.tmp`\n await ctx.storageState({ path: tmp })\n chmodSync(tmp, 0o600)\n renameSync(tmp, file)\n break\n } catch (error) {\n const status = error instanceof SignInError ? error.status : 0\n if (status !== 429 || attempt >= 4) throw error\n await sleep(15_000 * attempt)\n } finally {\n await ctx.dispose()\n }\n }\n const user = await sessionUser(config, file)\n if (!user) throw new Error(`${name} signed in but ${config.auth.session} has no user`)\n // A read-only journey can still run; one that chats will be refused, so say so before it tries.\n if (!user.emailVerified) console.warn(`${name} signed in but is not email-verified; an app that requires verification will refuse its chat`)\n return { path: file, user }\n })\n}\n\n/**\n * Every value that must never leave the host. `hard`: passwords and each cookie\n * value (whole, URL-decoded, and its token half). `soft`: the identities'\n * emails, which are warned about but not refused.\n */\nexport function secretNeedles(config: ResolvedJourneysConfig): { hard: string[]; soft: string[] } {\n const hard = new Set<string>()\n const soft = new Set<string>()\n for (const identity of Object.values(config.identities)) {\n const password = process.env[identity.passwordEnv]?.trim()\n if (password) hard.add(password)\n const email = process.env[identity.emailEnv]?.trim()\n if (email) soft.add(email)\n }\n const root = join(config.stateDir, 'sessions')\n const stack = existsSync(root) ? [root] : []\n while (stack.length) {\n const dir = stack.pop()!\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const path = join(dir, entry.name)\n if (entry.isDirectory()) stack.push(path)\n else if (entry.name.endsWith('.storage.json')) addCookieNeedles(path, hard)\n }\n }\n return { hard: [...hard], soft: [...soft] }\n}\n\nfunction addCookieNeedles(file: string, hard: Set<string>): void {\n try {\n const state = JSON.parse(readFileSync(file, 'utf8')) as { cookies?: { value: string }[] }\n for (const { value } of state.cookies ?? []) {\n if (!value || value.length < 16) continue\n hard.add(value)\n let decoded = value\n try {\n decoded = decodeURIComponent(value)\n } catch {\n // A value that is not URI-encoded is already its own decoded form.\n }\n hard.add(decoded)\n const token = decoded.split('.')[0] ?? ''\n if (token.length >= 16) hard.add(token)\n }\n } catch {\n // A half-written state file holds nothing a finished run used.\n }\n}\n","/**\n * A recording turned into files a person can watch.\n *\n * <label>-full.mp4 H.264, the whole session at real speed, with an 84 px\n * caption bar under the UI: the chapter line and an elapsed clock\n * <label>.srt the same chapters as a sidecar caption file\n * <label>-highlights.mp4 at most 178 s: waits and idle stretches sped up, and the caption\n * says by how much (\"[01:09] First text after 23 s » 4.2x, 21 s real (whole wait 41 s)\")\n * <label>-x2.mp4 optional: the full video at 2x\n *\n * Captions sit in their own bar so they never cover the composer or a toast.\n * Needs `ffmpeg` and `ffprobe` on PATH; work runs at nice 10 on 2 threads.\n */\nimport { execFileSync } from 'node:child_process'\nimport { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { basename, join } from 'node:path'\n\nexport interface Chapter {\n /** Epoch ms. */\n at: number\n caption: string\n /** Context label, or null for every context. */\n label: string | null\n kind: 'step' | 'wait'\n /** Epoch ms a wait ended. */\n until?: number\n}\n\nexport interface Cue {\n start: number\n end: number\n text: string\n}\n\nexport interface HighlightSegment {\n /** Source range, seconds. */\n a: number\n b: number\n /** Speed-up factor. */\n k: number\n text: string\n}\n\nconst W = 1440\nconst H = 900\nconst BAR = 84\nexport const MAX_HIGHLIGHTS_S = 178\n\nconst FONT_CANDIDATES = [\n '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',\n '/usr/share/fonts/dejavu/DejaVuSansMono.ttf',\n '/System/Library/Fonts/Menlo.ttc',\n]\n\nfunction monoFont(): string | null {\n const configured = process.env.JOURNEYS_FONT_MONO\n if (configured && existsSync(configured)) return configured\n return FONT_CANDIDATES.find((path) => existsSync(path)) ?? null\n}\n\nfunction ff(args: string[]): void {\n execFileSync('nice', ['-n', '10', 'ffmpeg', '-hide_banner', '-loglevel', 'error', '-y', ...args], { stdio: ['ignore', 'inherit', 'inherit'] })\n}\n\nexport function probeSeconds(file: string): number {\n const out = execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', file], { encoding: 'utf8' }).trim()\n const n = Number(out)\n if (!Number.isFinite(n) || n <= 0) throw new Error(`ffprobe could not read the duration of ${file}: ${out}`)\n return n\n}\n\nconst pad2 = (n: number) => String(Math.floor(n)).padStart(2, '0')\nconst mmss = (s: number) => `${pad2(s / 60)}:${pad2(s % 60)}`\nconst srtTime = (s: number) => {\n const ms = Math.max(0, Math.round(s * 1000))\n return `${pad2(ms / 3_600_000)}:${pad2((ms / 60_000) % 60)}:${pad2((ms / 1000) % 60)},${String(ms % 1000).padStart(3, '0')}`\n}\nconst assTime = (s: number) => {\n const cs = Math.max(0, Math.round(s * 100))\n return `${Math.floor(cs / 360_000)}:${pad2((cs / 6000) % 60)}:${pad2((cs / 100) % 60)}.${String(cs % 100).padStart(2, '0')}`\n}\nconst humanSeconds = (s: number) => (s >= 90 ? `${Math.floor(s / 60)} min ${Math.round(s % 60)} s` : `${Math.round(s)} s`)\n\n/** Chapters on the video's own clock; each caption holds until the next. */\nexport function chapterCues(chapters: readonly Chapter[], t0: number, duration: number): Cue[] {\n const points = chapters\n .map((c) => ({ ...c, s: (c.at - t0) / 1000, e: c.until ? (c.until - t0) / 1000 : undefined }))\n .filter((c) => c.s < duration)\n .sort((a, b) => a.s - b.s)\n const cues: Cue[] = []\n for (let i = 0; i < points.length; i += 1) {\n const c = points[i]!\n const start = Math.max(0, c.s)\n const end = Math.min(duration, points[i + 1]?.s ?? duration)\n if (end - start < 0.05) continue\n const text = c.kind === 'wait' && c.e !== undefined ? `${c.caption} (real wait ${humanSeconds(c.e - c.s)})` : c.caption\n cues.push({ start, end, text })\n }\n return cues\n}\n\nfunction srtText(cues: readonly Cue[]): string {\n return cues.map((c, i) => `${i + 1}\\n${srtTime(c.start)} --> ${srtTime(c.end)}\\n${c.text}\\n`).join('\\n')\n}\n\nfunction assText(cues: readonly Cue[]): string {\n const esc = (t: string) => t.replace(/\\\\/g, '\\\\\\\\').replace(/[{}]/g, '').replace(/\\n/g, '\\\\N')\n const head = `[Script Info]\\nScriptType: v4.00+\\nPlayResX: ${W}\\nPlayResY: ${H + BAR}\\nWrapStyle: 0\\n\\n[V4+ Styles]\\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\\nStyle: Bar,DejaVu Sans,26,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,0,0,1,28,200,14,1\\n\\n[Events]\\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\\n`\n return head + cues.map((c) => `Dialogue: 0,${assTime(c.start)},${assTime(c.end)},Bar,,0,0,0,,${esc(c.text)}`).join('\\n') + '\\n'\n}\n\n/**\n * The highlights cut: which source ranges, at what speed, under which caption.\n * A wait longer than 6 s plays in about 5 s; an idle stretch longer than 15 s\n * plays in about 10 s; then everything scales to fit {@link MAX_HIGHLIGHTS_S}.\n */\nexport function highlightPlan(chapters: readonly Chapter[], t0: number, duration: number): HighlightSegment[] {\n const pts = chapters\n .map((c) => ({ ...c, s: Math.max(0, (c.at - t0) / 1000), e: c.until ? (c.until - t0) / 1000 : undefined }))\n .sort((x, y) => x.s - y.s)\n const cuts = new Set<number>([0, duration])\n for (const p of pts) {\n if (p.s < duration) cuts.add(Math.round(p.s * 10) / 10)\n if (p.e !== undefined && p.e < duration) cuts.add(Math.round(p.e * 10) / 10)\n }\n const bounds = [...cuts].sort((x, y) => x - y)\n const segs: { a: number; b: number; k: number; text: string; wait: boolean; whole: number }[] = []\n for (let i = 0; i + 1 < bounds.length; i += 1) {\n const a = bounds[i]!\n const b = bounds[i + 1]!\n if (b - a < 0.15) continue\n const wait = [...pts].reverse().find((p) => p.kind === 'wait' && p.e !== undefined && p.s <= a + 0.05 && a < p.e - 0.05)\n // The latest step caption wins (e.g. \"First text after 31 s\" inside a wait); the wait adds its total.\n const step = [...pts].reverse().find((p) => p.kind === 'step' && p.s <= a + 0.05 && (!wait || p.s >= wait.s - 0.05))\n const len = b - a\n const k = wait ? (len > 6 ? len / 5 : 1) : len > 15 ? len / 10 : 1\n segs.push({ a, b, k, text: step?.caption ?? wait?.caption ?? '', wait: Boolean(wait), whole: wait?.e !== undefined ? wait.e - wait.s : 0 })\n }\n const shown = segs.reduce((n, s) => n + (s.b - s.a) / s.k, 0)\n const f = shown > MAX_HIGHLIGHTS_S ? shown / MAX_HIGHLIGHTS_S : 1\n return segs.map((s) => {\n const k = s.k * f\n const len = s.b - s.a\n const x = k >= 10 ? Math.round(k) : Math.round(k * 10) / 10\n const speed = k > 1.05 ? ` » ${x}x, ${humanSeconds(len)} real${s.wait ? ` (whole wait ${humanSeconds(s.whole)})` : ''}` : ''\n return { a: s.a, b: s.b, k, text: `[${mmss(s.a)}] ${s.text}${speed}` }\n })\n}\n\ninterface PostProcessInput {\n webm: string\n /** Raw working folder on the host; keeps the webm and chapters for a rebuild. */\n workDir: string\n videoDir: string\n label: string\n /** Epoch ms the recorded page was created. */\n t0: number\n wallSeconds: number\n chapters: readonly Chapter[]\n speedup2x: boolean\n}\n\nexport function postProcessVideo(o: PostProcessInput): string[] {\n mkdirSync(o.videoDir, { recursive: true })\n const keep = join(o.workDir, `${o.label}.webm`)\n if (o.webm !== keep) copyFileSync(o.webm, keep)\n writeFileSync(join(o.workDir, `${o.label}.chapters.json`), JSON.stringify({ t0: o.t0, wallSeconds: o.wallSeconds, chapters: o.chapters }))\n return renderAll(keep, o.workDir, o.videoDir, o.label, o.t0, o.chapters, o.speedup2x, o.wallSeconds)\n}\n\n/** Re-render from a raw folder after editing `<label>.chapters.json` by hand. */\nexport function rebuildVideo(rawLabelDir: string, videoDir: string, label: string, speedup2x: boolean): string[] {\n const meta = JSON.parse(readFileSync(join(rawLabelDir, `${label}.chapters.json`), 'utf8')) as { t0: number; wallSeconds: number; chapters: Chapter[] }\n return renderAll(join(rawLabelDir, `${label}.webm`), rawLabelDir, videoDir, label, meta.t0, meta.chapters, speedup2x, meta.wallSeconds)\n}\n\nfunction renderAll(webm: string, work: string, videoDir: string, label: string, t0: number, chapters: readonly Chapter[], speedup2x: boolean, wallSeconds: number): string[] {\n const clean = join(work, `${label}.clean.mp4`)\n ff(['-i', webm, '-vf', `fps=25,scale=${W}:${H}:flags=lanczos,format=yuv420p`, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '22', '-threads', '2', '-an', clean])\n const duration = probeSeconds(clean)\n // Measured 2026-10-11 against a clock burned into the page: video time tracks\n // wall clock from page creation to within 0.2 s.\n if (duration < wallSeconds - 3) console.warn(`video is ${duration.toFixed(1)} s but ${wallSeconds.toFixed(1)} s passed before recording stopped; late captions may be early`)\n\n const cues = chapterCues(chapters, t0, duration)\n const srt = join(videoDir, `${label}.srt`)\n writeFileSync(srt, srtText(cues))\n const ass = join(work, `${label}.full.ass`)\n writeFileSync(ass, assText(cues))\n const full = join(videoDir, `${label}-full.mp4`)\n const font = monoFont()\n const clock = `drawtext=${font ? `fontfile=${font}` : 'font=monospace'}:text='%{pts\\\\:hms}':x=w-tw-28:y=h-${BAR / 2}-th/2:fontsize=26:fontcolor=white@0.8`\n ff(['-i', clean, '-vf', `pad=${W}:${H + BAR}:0:0:color=0x111111,ass=${ass},${clock}`, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', full])\n\n const plan = highlightPlan(chapters, t0, duration)\n const segDir = join(work, `${label}.segments`)\n mkdirSync(segDir, { recursive: true })\n const list: string[] = []\n const hcues: Cue[] = []\n let at = 0\n plan.forEach((s, i) => {\n const seg = join(segDir, `${String(i).padStart(3, '0')}.mp4`)\n ff(['-ss', s.a.toFixed(3), '-t', (s.b - s.a).toFixed(3), '-i', clean, '-vf', `setpts=PTS/${s.k.toFixed(4)},fps=25`, '-an', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', seg])\n const len = probeSeconds(seg)\n list.push(`file '${seg}'`)\n hcues.push({ start: at, end: at + len, text: s.text })\n at += len\n })\n const listFile = join(segDir, 'list.txt')\n writeFileSync(listFile, list.join('\\n') + '\\n')\n const joined = join(work, `${label}.highlights.raw.mp4`)\n ff(['-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', joined])\n const hass = join(work, `${label}.highlights.ass`)\n writeFileSync(hass, assText(hcues))\n const highlights = join(videoDir, `${label}-highlights.mp4`)\n ff(['-i', joined, '-vf', `pad=${W}:${H + BAR}:0:0:color=0x111111,ass=${hass}`, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', highlights])\n const out = [full, srt, highlights]\n if (speedup2x) {\n const x2 = join(videoDir, `${label}-x2.mp4`)\n ff(['-i', full, '-vf', 'setpts=PTS/2,fps=25', '-an', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', x2])\n out.push(x2)\n }\n console.log(`video ${label}: full ${duration.toFixed(1)} s, highlights ${at.toFixed(1)} s from ${plan.length} segments`)\n return out\n}\n\n/** Seconds at which to grab frames: one per caption (1.5 s in), at most `max`, evenly spread. */\nexport function frameTimes(srt: string | null, times: readonly number[], max = 10): number[] {\n let ts = [...times]\n if (!ts.length && srt) {\n ts = srt.split('\\n').filter((l) => l.includes('-->')).map((l) => {\n const [h = '0', m = '0', rest = '0'] = l.split(' --> ')[0]!.split(':')\n return Number(h) * 3600 + Number(m) * 60 + Number(rest.replace(',', '.')) + 1.5\n })\n }\n if (ts.length > max) {\n const step = ts.length / max\n ts = Array.from({ length: max }, (_, i) => ts[Math.floor(i * step)]!)\n }\n return ts\n}\n\n/** PNG frames of a video, named by label and timestamp, into `outDir`. */\nexport function extractFrames(video: string, srtFile: string | null, outDir: string, times: readonly number[], max = 10): string[] {\n const srt = srtFile && existsSync(srtFile) ? readFileSync(srtFile, 'utf8') : null\n return frameTimes(srt, times, max).map((t, i) => {\n const f = join(outDir, `frame-${basename(video).replace(/-full\\.mp4$/, '')}-${String(i + 1).padStart(2, '0')}-${mmss(t).replace(':', 'm')}s.png`)\n ff(['-ss', t.toFixed(2), '-i', video, '-frames:v', '1', f])\n return f\n })\n}\n","/**\n * The one file a reviewer opens: INDEX.md for a folder of recorded journeys.\n *\n * It lists the highlight cuts first, the critic's scorecard, the ranked fix\n * list (verified failures by rank, each with its evidence, fix, number to beat\n * and proving test), every recorded turn with its scored outcome, every video,\n * and what stayed unproven. The renderer is pure; `collectJourneyFiles` reads\n * the folder.\n */\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join, relative } from 'node:path'\nimport type { TurnRecord } from './journey.js'\n\n/** What the skeptical critic returns; the same shape the prove-journeys workflow asks for. */\nexport interface CriticResult {\n headline: string\n scorecard?: { journey: string; verifiedVerdict: string; keyTiming?: string; qualityGrade?: string; topIssue: string; video?: string }[]\n verifiedFailures?: {\n rank: number\n severity: string\n what: string\n journeys?: string[]\n evidence: string\n likelyCause?: string\n fix: string\n numberToBeat: string\n test: string\n }[]\n refutedOrUnproven?: string[]\n coverageGaps?: string[]\n}\n\nexport interface JourneyFiles {\n /** Folder relative to the index root, e.g. `j1-new-customer` or `j1-new-customer/r2`. */\n dir: string\n videos: { file: string; seconds: number | null }[]\n turns: Pick<TurnRecord, 'label' | 'outcome' | 'firstTextS' | 'completeS' | 'replyChars' | 'error' | 'sentAt'>[]\n}\n\nexport interface IndexInput {\n title: string\n critic?: CriticResult\n journeys: JourneyFiles[]\n}\n\nconst seconds = (s: number | null) => (s === null ? '?' : `${Math.round(s).toLocaleString('en-US')} s`)\nconst cell = (text: string | number | null | undefined) => String(text ?? '').replace(/\\|/g, '\\\\|').replace(/\\s*\\n\\s*/g, ' ')\nconst firstLine = (text: string) => text.split('\\n')[0]!.trim()\n\nfunction videoLabel(file: string): { base: string; kind: string } {\n const name = file.split('/').pop() ?? file\n const m = /^(.*)-(highlights|full|x2)\\.mp4$/.exec(name)\n return m ? { base: m[1]!, kind: m[2]! } : { base: name.replace(/\\.mp4$/, ''), kind: 'other' }\n}\n\n/** Every recorded turn's outcome, counted. The denominator is every turn in the folder's timings.json files. */\nexport function tallyTurns(journeys: readonly JourneyFiles[]): { total: number; byOutcome: Record<string, number> } {\n const byOutcome: Record<string, number> = {}\n let total = 0\n for (const j of journeys) {\n for (const t of j.turns) {\n total += 1\n byOutcome[t.outcome] = (byOutcome[t.outcome] ?? 0) + 1\n }\n }\n return { total, byOutcome }\n}\n\nexport function renderIndex(input: IndexInput): string {\n const out: string[] = [`# ${input.title}`, '']\n const { critic } = input\n const tally = tallyTurns(input.journeys)\n if (critic?.headline) out.push(`**Result.** ${critic.headline}`, '')\n if (tally.total) {\n const parts = Object.entries(tally.byOutcome).sort((a, b) => b[1] - a[1]).map(([k, n]) => `${n} ${k}`)\n out.push(`**Turns, as scored by the recorder:** ${parts.join(', ')}, of ${tally.total} recorded turns (source: each journey's timings.json).`, '')\n }\n\n const all = input.journeys.flatMap((j) => j.videos.map((v) => ({ ...v, dir: j.dir, path: j.dir ? `${j.dir}/${v.file}` : v.file })))\n const highlights = all.filter((v) => videoLabel(v.file).kind === 'highlights')\n const scoreVideos = (critic?.scorecard ?? []).map((s) => s.video ?? '').filter(Boolean)\n const rankOf = (path: string) => {\n const i = scoreVideos.findIndex((v) => v.endsWith(path))\n return i < 0 ? Number.MAX_SAFE_INTEGER : i\n }\n highlights.sort((a, b) => rankOf(a.path) - rankOf(b.path) || a.path.localeCompare(b.path))\n if (highlights.length) {\n out.push('## Start here: highlights, at most 3 minutes each', '')\n highlights.forEach((v, i) => {\n const card = critic?.scorecard?.find((s) => s.video?.endsWith(v.path))\n out.push(`${i + 1}. \\`${v.path}\\` (${seconds(v.seconds)})${card ? `. ${card.journey}: ${firstLine(card.topIssue)}` : ''}`)\n })\n out.push('')\n }\n\n if (critic?.scorecard?.length) {\n out.push('## Scorecard', '', '| Journey | Verdict | Key timing | Output | Top issue |', '|---|---|---|---|---|')\n for (const s of critic.scorecard) out.push(`| ${cell(s.journey)} | ${cell(s.verifiedVerdict)} | ${cell(s.keyTiming)} | ${cell(s.qualityGrade)} | ${cell(s.topIssue)} |`)\n out.push('')\n }\n\n const fixes = [...(critic?.verifiedFailures ?? [])].sort((a, b) => a.rank - b.rank)\n if (fixes.length) {\n out.push('## Ranked fixes (verified failures, customer impact first)', '')\n for (const f of fixes) {\n out.push(`${f.rank}. **${firstLine(f.what)}** (${f.severity}${f.journeys?.length ? `; ${f.journeys.join(', ')}` : ''})`)\n // Later lines keep their breaks, so a list inside `what` nests under its rank.\n for (const line of f.what.split('\\n').slice(1)) if (line.trim()) out.push(` ${line.trim()}`)\n out.push(` - Evidence: ${cell(f.evidence)}`)\n if (f.likelyCause) out.push(` - Likely cause: ${cell(f.likelyCause)}`)\n out.push(` - Fix: ${cell(f.fix)}`, ` - Number to beat: ${cell(f.numberToBeat)}`, ` - Proving test: ${cell(f.test)}`)\n }\n out.push('')\n }\n\n const turns = input.journeys.flatMap((j) => j.turns.map((t) => ({ ...t, dir: j.dir })))\n if (turns.length) {\n out.push('## Every recorded turn', '', '| Journey | Context | Sent | Outcome | First text | End | Reply chars | What went wrong |', '|---|---|---|---|---|---|---|---|')\n for (const t of turns) {\n out.push(`| ${cell(t.dir || '.')} | ${cell(t.label)} | ${cell(t.sentAt.slice(11, 19))}Z | ${cell(t.outcome)} | ${seconds(t.firstTextS)} | ${seconds(t.completeS)} | ${t.replyChars.toLocaleString('en-US')} | ${cell(t.error ?? '')} |`)\n }\n out.push('')\n }\n\n if (all.length) {\n out.push('## Every video', '')\n const dirs = [...new Set(all.map((v) => v.dir))]\n for (const dir of dirs) {\n out.push(`### \\`${dir || '.'}\\``, '')\n const byBase = new Map<string, typeof all>()\n for (const v of all.filter((x) => x.dir === dir)) {\n const { base } = videoLabel(v.file)\n byBase.set(base, [...(byBase.get(base) ?? []), v])\n }\n for (const [base, vids] of byBase) {\n const order = ['highlights', 'full', 'x2', 'other']\n vids.sort((a, b) => order.indexOf(videoLabel(a.file).kind) - order.indexOf(videoLabel(b.file).kind))\n out.push(`- ${base}: ${vids.map((v) => `\\`${v.file}\\` (${seconds(v.seconds)})`).join(', ')}`)\n }\n out.push('')\n }\n }\n\n const unproven = [...(critic?.refutedOrUnproven ?? []), ...(critic?.coverageGaps ?? [])]\n if (unproven.length) {\n out.push('## Refuted, unproven and not covered', '')\n for (const u of unproven) out.push(`- ${cell(u)}`)\n out.push('')\n }\n return out.join('\\n')\n}\n\n/**\n * Every journey folder under `root`: one that holds a `timings.json` or a\n * `video/` folder, at any depth. `probe` returns a video's duration in seconds.\n */\nexport function collectJourneyFiles(root: string, probe: (file: string) => number | null): JourneyFiles[] {\n const found: JourneyFiles[] = []\n const visit = (dir: string, depth: number) => {\n const timings = join(dir, 'timings.json')\n const videoDir = join(dir, 'video')\n const hasVideo = existsSync(videoDir) && statSync(videoDir).isDirectory()\n if (existsSync(timings) || hasVideo) {\n const videos = hasVideo\n ? readdirSync(videoDir).filter((f) => f.endsWith('.mp4')).sort().map((f) => ({ file: `video/${f}`, seconds: probe(join(videoDir, f)) }))\n : []\n let turns: JourneyFiles['turns'] = []\n if (existsSync(timings)) {\n try {\n turns = ((JSON.parse(readFileSync(timings, 'utf8')) as { turns?: JourneyFiles['turns'] }).turns ?? [])\n } catch {\n turns = []\n }\n }\n found.push({ dir: relative(root, dir), videos, turns })\n }\n if (depth >= 4) return\n for (const name of readdirSync(dir).sort()) {\n const path = join(dir, name)\n if (name === 'video' || name === 'turns' || name.startsWith('.')) continue\n if (statSync(path).isDirectory()) visit(path, depth + 1)\n }\n }\n visit(root, 0)\n return found\n}\n","/**\n * The readiness scoreboard writer: one run's journey summary as the writes\n * that put it on the shared board, so every app's rows land in one schema.\n *\n * The board is an artifact page whose shared store holds three collections:\n * `flows` (one row per flow), `prs` and `meta` (one document per app; Hardware's\n * is `board`, written before the board was shared). A row carries `app` and\n * `flowId`; a row without `app` belongs to Hardware. Hardware's rows predate the\n * shared board and live at their bare flow id and `meta/board`; its runner\n * passes `legacyIds` so those rows are updated in place, never duplicated.\n *\n * A document that already exists is merged (`update`) and pinned to the\n * version the caller read from the store (`versions`), so the text a person\n * wrote for a flow (what the customer does, its pass bar) survives every run,\n * and a field the run no longer has (an old blocker on a flow that now passes)\n * is deleted. A document with no known version is created with `set`; the\n * store refuses a `set` without a version on a document that already exists\n * (version_mismatch, nothing written; checked against the board's store), so a row a person wrote is never replaced.\n *\n * Pure: the same summary and options give the same writes, in the same order.\n */\n\nexport const SCOREBOARD_STATUSES = ['pass', 'fail', 'stall', 'blocked-host', 'blocked', 'skipped', 'unrecorded'] as const\nexport type ScoreboardStatus = (typeof SCOREBOARD_STATUSES)[number]\n\n/** Rows a store wrote before the board was shared, with no `app` field, belong to this app. */\nexport const LEGACY_SCOREBOARD_APP = 'hardware'\n\n/** One journey in a run's `summary.json`. */\nexport interface JourneySummaryEntry {\n /** Flow id, e.g. `c2` or `C2`; written upper-case. */\n id: string\n status: string\n /** Why it was blocked, skipped, stalled or failed. */\n reason?: string\n firstTextS?: number\n completeS?: number\n /** Links a reviewer can open. Only http(s) URLs are written; host paths are dropped. */\n videoUrl?: string\n traceUrl?: string\n evidenceUrl?: string\n}\n\n/** A run's summary, as an app's journey runner writes it. */\nexport interface JourneySummary {\n origin?: string\n /** Commit the run served. */\n sha?: string\n model?: string\n lane?: string\n /** ISO time of the run; required, so two runs are told apart. */\n updatedAt?: string\n journeys: JourneySummaryEntry[]\n}\n\nexport interface ScoreboardOptions {\n /** Short app name, e.g. `casework`. */\n app: string\n /** Current version of each document that exists, by `collection/docId`. */\n versions?: Readonly<Record<string, number>>\n /**\n * Write at the ids the board used before it was shared: the bare flow id and\n * `meta/board`. Only Hardware's runner sets this; every other app's rows are\n * `<app>-<flowId>` and `meta/<app>`.\n */\n legacyIds?: boolean\n}\n\n/** One entry of an artifact store batch, in the shape the batch write takes. */\nexport interface ScoreboardWrite {\n op: 'update' | 'set'\n collection: 'flows' | 'meta'\n doc_id: string\n data: Record<string, unknown>\n if_version?: number\n}\n\nexport interface ScoreboardResult {\n writes: ScoreboardWrite[]\n /** Entries the writer could not take as given, each with what it did instead. */\n warnings: string[]\n}\n\nconst DELETE = { __delete__: true } as const\nconst APP_NAME = /^[a-z][a-z0-9-]{0,40}$/\n\nconst isStatus = (value: string): value is ScoreboardStatus => (SCOREBOARD_STATUSES as readonly string[]).includes(value)\nconst url = (value: unknown): string | undefined => (typeof value === 'string' && /^https?:\\/\\//.test(value) ? value : undefined)\nconst seconds = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined)\n\n/** The document id a flow row lives at. */\nexport function scoreboardDocId(app: string, flowId: string, legacyIds = false): string {\n return legacyIds ? flowId : `${app}-${flowId}`\n}\n\n/** The `meta` document an app's run facts live at. */\nexport function scoreboardMetaId(app: string, legacyIds = false): string {\n return legacyIds ? 'board' : app\n}\n\n/** Keys in a fixed order, so the same input always serializes the same way. */\nfunction sorted(data: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.keys(data).sort().map((key) => [key, data[key]]))\n}\n\n/**\n * A document with a known version is merged, pinned to that version. One with\n * none is created with `set`, which takes no delete markers; if it does exist\n * after all, the store refuses the unpinned write and names it, so nothing a\n * person wrote there is overwritten.\n */\nfunction pinned(write: Omit<ScoreboardWrite, 'if_version'>, versions: ScoreboardOptions['versions']): ScoreboardWrite {\n const version = versions?.[`${write.collection}/${write.doc_id}`]\n if (version !== undefined) return { ...write, op: 'update', if_version: version }\n const data = Object.fromEntries(Object.entries(write.data).filter(([, value]) => value !== DELETE))\n return { ...write, op: 'set', data }\n}\n\nexport function scoreboardRows(summary: JourneySummary, options: ScoreboardOptions): ScoreboardResult {\n const app = options.app\n if (!APP_NAME.test(app)) throw new Error(`scoreboard: app must be a short lowercase name such as \"casework\", got \"${app}\"`)\n if (!summary || !Array.isArray(summary.journeys)) throw new Error('scoreboard: the summary has no journeys array')\n if (!summary.updatedAt || Number.isNaN(Date.parse(summary.updatedAt))) throw new Error('scoreboard: the summary needs updatedAt, an ISO time')\n\n const warnings: string[] = []\n const flows = new Map<string, ScoreboardWrite>()\n for (const entry of summary.journeys) {\n const flowId = String(entry.id ?? '').trim().toUpperCase()\n if (!flowId) { warnings.push('a journey without an id was skipped'); continue }\n let status: ScoreboardStatus\n if (isStatus(entry.status)) status = entry.status\n else { status = 'unrecorded'; warnings.push(`${flowId}: status \"${entry.status}\" is not one of ${SCOREBOARD_STATUSES.join(', ')}; written as unrecorded`) }\n if (flows.has(flowId)) warnings.push(`${flowId}: listed twice; the last entry wins`)\n for (const key of ['videoUrl', 'traceUrl', 'evidenceUrl'] as const) {\n if (entry[key] !== undefined && !url(entry[key])) warnings.push(`${flowId}: ${key} is not an http(s) link and was dropped`)\n }\n const reason = typeof entry.reason === 'string' && entry.reason.trim() ? entry.reason.trim() : undefined\n const data: Record<string, unknown> = {\n app,\n flowId,\n status,\n // A pass carries no blocker; any other status names why, or clears a stale one.\n blocker: status !== 'pass' && reason ? reason : DELETE,\n firstTextS: seconds(entry.firstTextS) ?? DELETE,\n completeS: seconds(entry.completeS) ?? DELETE,\n videoUrl: url(entry.videoUrl) ?? DELETE,\n traceUrl: url(entry.traceUrl) ?? DELETE,\n evidenceUrl: url(entry.evidenceUrl) ?? DELETE,\n sha: summary.sha ?? DELETE,\n recordedAt: summary.updatedAt,\n }\n flows.set(flowId, { op: 'update', collection: 'flows', doc_id: scoreboardDocId(app, flowId, options.legacyIds), data: sorted(data) })\n }\n\n const writes = [...flows.values()]\n .sort((a, b) => a.doc_id.localeCompare(b.doc_id, undefined, { numeric: true }))\n .map((write) => pinned(write, options.versions))\n const meta: Record<string, unknown> = {\n origin: summary.origin ?? DELETE,\n sha: summary.sha ?? DELETE,\n model: summary.model ?? DELETE,\n lane: summary.lane ?? DELETE,\n updatedAt: summary.updatedAt,\n }\n writes.push(pinned({ op: 'update', collection: 'meta', doc_id: scoreboardMetaId(app, options.legacyIds), data: sorted(meta) }, options.versions))\n return { writes, warnings }\n}\n"],"mappings":";;;;;AAmDO,IAAM,uBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,uBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,UAAU,MAAsB;AACvC,SAAO,KAAK,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACxC;AAGA,SAAS,aAAa,UAA8B,UAA2B,QAAkD;AAC/H,QAAM,SAAS,oBAAI,IAAoB;AACvC,QAAM,MAAM,CAAC,QAAgB,OAAO,IAAI,MAAM,OAAO,IAAI,GAAG,KAAK,KAAK,CAAC;A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url","openSync","closeSync","join","openSync","closeSync","join","existsSync","readdirSync","readFileSync","statSync","join","resolve","url","existsSync","mkdirSync","readFileSync","join","existsSync","readdirSync","readFileSync","statSync","join","seconds"]}