@vostride/agent-qa-core 0.2.3 → 0.2.4

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/schema/config-schema.ts","../src/schema/workspace-schema.ts","../src/schema/services-schema.ts","../src/schema/primitives.ts","../src/schema/knowledge-schema.ts","../src/schema/retired-keys.ts","../src/schema/registry-schema.ts","../src/auth-state/schema.ts","../src/schema/use-schema.ts","../src/schema/analytics-schema.ts","../src/schema/test-schema.ts","../src/schema/action-schema.ts","../src/schema/resolve-knowledge-root.ts","../src/schema/suite-schema.ts","../src/hooks/schema.ts","../src/parser/yaml-parser.ts","../src/parser/errors.ts","../src/validation/yaml-fault.ts","../src/parser/file-resolver.ts","../src/parser/suite-parser.ts","../src/parser/cst-patch.ts","../src/agent/token-budget.ts","../src/agent/index.ts","../src/mobile/xml-parser.ts","../src/mobile/role-map.ts","../src/mobile/element-resolver.ts","../src/mobile/gestures.ts","../src/mobile/launch-resolver.ts","../src/mobile/appium-executable.ts","../src/mobile/webview-scrollers.ts","../src/auth-state/resolver.ts","../src/runtime-paths.ts","../src/auth-state/store.ts","../src/auth-state/runtime.ts","../src/auth-state/hook-env.ts","../src/auth/store.ts","../src/auth/plugin-registry.ts","../src/auth/resolver.ts","../src/plugin-loader-util.ts","../src/auth/plugin-loader.ts","../src/auth/pkce.ts","../src/auth/fetch-wrapper.ts","../src/providers/plugin-loader.ts","../src/logging/types.ts","../src/logging/log-manager.ts","../src/logging/cli-formatter.ts","../src/farm/credentials.ts","../src/farm/capability-mapper.ts","../src/farm/browserstack.ts","../src/farm/registry.ts","../src/suite/member.ts","../src/validation/validate.ts","../src/hooks/parser.ts","../src/utils/path-validation.ts","../src/workspace/workspace-paths.ts","../src/validation/formatter.ts","../src/validation/coord-bounds.ts","../src/hooks/index.ts","../src/ids/hook-id.ts","../src/ids/run-id.ts","../src/run-attributes.ts","../src/version.ts","../src/version-check/index.ts"],"sourcesContent":["export * from './types/index.js'\nexport * from './schema/index.js'\nexport * from './parser/index.js'\nexport { parseAllTestBindings } from './parser/yaml-parser.js'\nexport type { ParsedTestBinding, ParseAllTestBindingsResult } from './parser/yaml-parser.js'\nexport * from './agent/index.js'\nexport * from './mobile/index.js'\nexport * from './auth-state/index.js'\nexport * from './auth/index.js'\nexport * from './providers/index.js'\nexport * from './logging/index.js'\nexport * from './farm/index.js'\nexport * from './suite/index.js'\nexport * from './validation/index.js'\nexport * from './hooks/index.js'\nexport * from './ids/index.js'\n// 363 D-08: the run-artifact type family relocated to @vostride/agent-qa-schema (was ./artifacts).\nexport * from './workspace/index.js'\n// 2026-08-17 (Phase 398 plan 11, D-20): `./analytics/index.js` is GONE. Product telemetry is a host\n// concern composed at each host's own root out of `@vostride/agent-qa-analytics`, behind a port with\n// a closed event union — not an ambient capture/flush pair re-exported from every consumer of core.\nexport * from './run-attributes.js'\nexport * from './version.js'\nexport * from './version-check/index.js'\nexport * from './runtime-paths.js'\n// 363 D-08/Q10: the sharp screenshot pipeline (compress/align/dimensions) moved to\n// @vostride/agent-qa-runner-local (sharp left core); mobile adapters import it from there.\nexport { isPathInsideDir } from './utils/path-validation.js'\n","import { z } from 'zod'\nimport { WorkspaceSchema } from './workspace-schema.js'\nimport { ServicesSchema } from './services-schema.js'\nimport { KnowledgeConfigSchema } from './knowledge-schema.js'\nimport { retiredKeyScan } from './retired-keys.js'\nimport { RegistrySchema } from './registry-schema.js'\nimport { MobileAppStateSchema, UseSchema } from './use-schema.js'\nimport { AnalyticsSchema } from './analytics-schema.js'\n\nexport const AuthPluginDeclarationSchema = z.union([\n z.object({\n package: z.string().trim().min(1),\n }).strict(),\n z.object({\n path: z.string().trim().min(1),\n }).strict(),\n])\n\n// Provider plugins load in-process with full Node access; keep them first-party-only\n// until a container sandbox exists.\nexport const ProviderPluginDeclarationSchema = z.union([\n z.object({\n package: z.string().trim().min(1),\n }).strict(),\n z.object({\n path: z.string().trim().min(1),\n }).strict(),\n])\n\nexport const PluginsSchema = z.object({\n auth: z.array(AuthPluginDeclarationSchema).optional().default([]),\n providers: z.array(ProviderPluginDeclarationSchema).optional().default([]),\n}).strict()\n\nconst AgentQaConfigSchemaInner = z.object({\n workspace: WorkspaceSchema,\n services: ServicesSchema.prefault({}).optional(),\n // D-08: slim replacement for the retired v1 memory config surface; prefaulted so parsed\n // configs always materialize knowledge defaults (zod 4 .default() short-circuits without\n // parsing — .prefault() runs the inner defaults) — matches the providers `.default([])`\n // precedent in spirit.\n knowledge: KnowledgeConfigSchema.prefault({}),\n registry: RegistrySchema.optional(),\n use: UseSchema.optional(),\n plugins: PluginsSchema.optional(),\n analytics: AnalyticsSchema.optional(),\n // 432 D-18: the one production opt-in. Optional with no default: its consumer reads absence as\n // false, so only an explicit `true` in the validated config authorizes a production target.\n allowProduction: z.boolean().optional(),\n // 2026-10-01 (432-22, D-15/D-18/D-22): the `safety` section (`safety.trustMode`) is deleted with\n // trust mode. `allowProduction` above is the only production opt-in, and a file that still\n // declares `safety` gets the normal strict unrecognized-key error.\n // D-03 (Phase 372): eval substrate params. `judge` references a NAMED registry.llms entry;\n // strict so unknown eval subkeys are rejected.\n eval: z.object({\n judge: z.string().min(1).refine(name => name.trim().length > 0).optional(),\n judges: z.array(z.string().min(1).refine(name => name.trim().length > 0)).max(3).optional(),\n // Owner override of D-10 (2026-07-12): explicit default-off opt-in that lets a\n // KNOWN-same-family judge run; the eligibility law discloses the override on every\n // scored entry (familyOverride) and the report projection renders one honesty line.\n // Unknown families stay forbidden regardless.\n judgeAllowSameFamily: z.boolean().optional(),\n k: z.number().int().positive().optional(),\n seed: z.number().int().optional(),\n // 2026-09-07, 417 D-19: Gate-1 screen cap; recorded default lives in the CLI.\n // 2026-09-11, 422 D-14: `maxPerJob` bounds how many Gate-1 CALLS one post-run proposal job\n // may make; recorded default lives beside the handler (PROPOSE_DEFAULT_MAX_GATE1_PER_JOB).\n // A SECOND axis beside `maxScreens`, not a refinement of it — that one bounds how much a\n // single screening looks at, this one bounds how many screenings a run's tail buys — and an\n // operator can legitimately want a generous first and a tight second. Positive-integer only,\n // for the sharper version of the usual reason: a bound that silently fell back to the\n // recorded default because the operator typed `0` would buy replay work they refused. There\n // is deliberately NO CLI flag: the bound is charged durably per job and read back by a\n // resumed attempt, so a per-invocation flag would be a bound that could change between the\n // attempt that spent it and the attempt that has to honour what was spent.\n gate1: z.object({\n maxScreens: z.number().int().positive().optional(),\n maxPerJob: z.number().int().positive().optional(),\n }).strict().optional(),\n // 2026-09-07, 418 D-04/D-13/D-14: Gate-2 ablation cap, canary horizon (build ordinals)\n // and per-scope lower-trust cap; recorded defaults live in the CLI (GATE2_DEFAULT_*).\n gate2: z.object({\n maxAblations: z.number().int().positive().optional(),\n canaryHorizonBuilds: z.number().int().positive().optional(),\n maxLowerTrustPerScope: z.number().int().positive().optional(),\n }).strict().optional(),\n // 2026-09-11, 422 D-04: how many NOVEL seeds one adversarial refresh may derive from\n // before the rest are counted and deferred; recorded default lives in eval core\n // (ADVERSARIAL_DEFAULT_MAX_SEEDS_PER_REFRESH). Strict, and positive-integer only: a cap\n // that silently fell back to the default because the operator typed `0` is not a cap.\n // 2026-09-11, 422 D-04/D-10: `maxProbeCalls` bounds PROVIDER CALLS one refresh may make to\n // author probes; recorded default lives in eval-local\n // (ADVERSARIAL_DEFAULT_MAX_PROBE_CALLS). It is a SECOND budget beside the seed cap on\n // purpose — deterministic seeds cost CPU and authored probes cost money no later run can\n // recover — and it is held to the same positive-integer strictness for the sharper version\n // of the same reason: a cap that silently fell back to the default because the operator\n // typed `0` would buy calls they refused.\n adversarial: z.object({\n maxSeedsPerRefresh: z.number().int().positive().optional(),\n maxProbeCalls: z.number().int().positive().optional(),\n }).strict().optional(),\n seeding: z.object({\n silverPerTestCap: z.number().int().positive().optional(),\n }).strict().optional(),\n }).strict().optional(),\n}).strict()\n.superRefine((val, ctx) => {\n if (val.eval?.judge !== undefined && val.eval.judges !== undefined) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['eval'],\n message: 'Set either eval.judge or eval.judges, never both; remove one declaration.' })\n }\n const llms = val.registry?.llms ?? []\n const names = llms.map(c => c.name)\n const dupes = names.filter((n, i) => names.indexOf(n) !== i)\n for (const dupe of new Set(dupes)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['registry', 'llms'],\n message: `Duplicate LLM config name: \"${dupe}\"`,\n })\n }\n if ((val.use as any)?.platform) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['use', 'platform'],\n message: 'use.platform cannot be set at global config level. Set platform in test or suite YAML instead.',\n })\n }\n if (val.use?.llm && !names.includes(val.use.llm)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['use', 'llm'],\n message: `use.llm \"${val.use.llm}\" does not match any name in registry.llms`,\n })\n }\n if (!MobileAppStateSchema.safeParse(val.use?.mobile?.appState).success) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['use', 'mobile', 'appState'],\n message: 'use.mobile.appState is required and must be one of: preserve | reset',\n })\n }\n})\n\n// D-07: retired-key pipe pre-scan — the scan MUST run before the strict object because\n// zod (4.6.7 verified) skips refinements chained after a strict parse that rejects a value\n// (RESEARCH Pitfall 1). z.infer of the piped schema yields the stage-B output type,\n// so the exported AgentQaConfig type semantics are unchanged.\nexport const AgentQaConfigSchema = retiredKeyScan.pipe(AgentQaConfigSchemaInner)\n\nexport { WorkspaceSchema } from './workspace-schema.js'\nexport { AuthStateConfigSchema, ServicesSchema } from './services-schema.js'\nexport { KnowledgeConfigSchema } from './knowledge-schema.js'\nexport { RegistrySchema } from './registry-schema.js'\nexport {\n AuthStateUseSchema,\n MobileAppStateSchema,\n MobileUseSchema,\n MobileUseOverrideSchema,\n UseSchema,\n UseOverrideSchema,\n normalizeAuthStateUse,\n type NormalizedAuthStateUse,\n} from './use-schema.js'\nexport { AnalyticsSchema } from './analytics-schema.js'\nexport * from './primitives.js'\n","import { z } from 'zod'\n\nexport const WorkspaceSchema = z.object({\n testMatch: z.array(z.string().min(1)).min(1),\n suiteMatch: z.array(z.string().min(1)).min(1),\n testPathIgnore: z.array(z.string()).optional(),\n hooksFile: z.string().min(1, 'hooksFile is required.'),\n envFile: z.string().min(1, 'envFile is required.'),\n secretsFile: z.string().min(1, 'secretsFile is required.'),\n}).strict()\n","import { z } from 'zod'\nimport { DurationString, SizeString } from './primitives.js'\n\n/**\n * Whether a configured value is an ABSOLUTE `http:`/`https:` URL (408 D-08, WR-04 — T-408-16).\n *\n * FILE-LOCAL, DELIBERATELY, unlike `isLoopbackHost` below. That predicate is exported because TWO\n * mechanisms decide loopback membership and must not be two spellings; this one has exactly one\n * decision site — the parse boundary, immediately below. Exporting it would advertise a second\n * place to make the same check, and the whole point of a parse-time guard is that there is no\n * second place: nothing downstream should be re-deciding whether the base is safe.\n *\n * A RELATIVE VALUE IS REFUSED, not resolved. `new URL(value)` with no base throws for\n * `/relative/only` and for `not-a-url`, and the scheme test refuses `javascript:` and `mailto:`\n * — which parse fine and are exactly the shapes that must not reach an `href`.\n */\nfunction isAbsoluteHttpUrl(value: string): boolean {\n try {\n const url = new URL(value)\n return url.protocol === 'http:' || url.protocol === 'https:'\n } catch {\n return false\n }\n}\n\nexport const DashboardConfigSchema = z.object({\n port: z.number().optional(),\n dbPath: z.string().optional(),\n artifactsDir: z.string().optional(),\n // Phase 387, D-10: where an entity card's `url` points. BOTH optional, so the v52 default\n // is a card with no `url` at all rather than a link to a route nothing serves. The card\n // producer reads these through the masked config reader and renders\n // `ENTITY_URL_ROUTE` (@vostride/agent-qa-schema) against them.\n //\n // They live on the EXISTING `services.dashboard` block rather than on a new top-level\n // `dashboard` key: this project already has one dashboard configuration home, and a second\n // one would be two places an operator could reasonably write the same fact.\n //\n // 2026-09-01 (Phase 408 plan 10, WR-04 — T-408-16): REFINED TO AN ABSOLUTE http(s) URL, because\n // this value stops being a display string in M5. It composes the tokenless live link\n // (`live-link.ts`'s `liveRunLinkOf`, which only strips trailing slashes), and that link is\n // assigned to an `href` INSIDE the served App document — which runs with `allow-scripts` at an\n // opaque origin — as well as appended verbatim to every carrier tool result's model-readable\n // text. A `javascript:` base therefore composed a script-executing anchor. The trust boundary is\n // the operator, so this is not remote-triggerable; the finding is that a URL-shaped value reached\n // an `href` with no scheme check at any hop, and the guard costs one refinement.\n //\n // AT THE PARSE BOUNDARY, so there is exactly one place that decides. The defensive drop at the\n // anchor itself is the SECOND half of the same finding and lives in `app-wrapper.ts`.\n //\n // STILL `.optional()`: an absent base is a real and honest posture — a standalone `agent-qa mcp`\n // with no dashboard — and the carrier result names that absence rather than fabricating a URL.\n // An EMPTY STRING is now REFUSED, which is stricter than before: `\"\"` is not an absence an\n // operator wrote by leaving the key out, it is a value that composes a relative fragment reading\n // as a link and resolving against nothing.\n baseUrl: z.string().refine(\n isAbsoluteHttpUrl,\n { message: 'services.dashboard.baseUrl must be an absolute http(s) URL' },\n ).optional(),\n workspace: z.string().optional(),\n // 2026-10-01 (432-22, D-12/D-22): `runServiceTokens` is deleted. The run service is tokenless\n // since 432-21, and a file that still declares the key gets the normal strict unrecognized-key\n // error, with no migration and no special message. The local doors never needed a credential.\n // Phase 402 D-07: the interface this server binds. Consumed by 402-05's pre-listen bind guard,\n // which REFUSES any non-loopback value — unconditionally since the phase-402 verification round\n // (a declared run-service credential authenticates the three run-service paths and nothing else,\n // so it was never evidence that the rest of this server's surface was authed).\n //\n // DELIBERATELY NOT `LoopbackHostSchema` even so. That schema refuses at PARSE time, which would\n // make the runtime refusal unreachable and would report the problem as a config-shape error\n // rather than as the security refusal it is — and it would also refuse a loopback SPELLING this\n // field exists to allow (`localhost`, `::1`, `127.0.0.2` is refused on purpose).\n host: z.string().trim().min(1).optional(),\n}).strict()\n\n/**\n * THE ONE MEMBER SET FOR \"this host is loopback\" (402-05 D-07 — T-402-18).\n *\n * Exported because two mechanisms now decide loopback membership and they must not be two\n * spellings: `LoopbackHostSchema` below refuses a non-loopback MCP host at PARSE time, and\n * `startServer`'s pre-listen bind guard refuses a non-loopback DASHBOARD host at RUNTIME, with no\n * exemption. A second literal list would let the two drift, and the direction it would drift in is\n * a host one mechanism calls loopback and the other does not.\n */\nexport const LOOPBACK_HOSTS: readonly string[] = Object.freeze(['localhost', '127.0.0.1', '::1'])\n\n/** Whether a configured host names a loopback interface. The one predicate over the one set. */\nexport function isLoopbackHost(host: string): boolean {\n return LOOPBACK_HOSTS.includes(host.trim())\n}\n\nconst LoopbackHostSchema = z.string().trim().min(1).refine(\n isLoopbackHost,\n { message: 'MCP host must be localhost, 127.0.0.1, or ::1 in local-only mode' },\n)\n\n// 2026-10-01 (432-22, D-12/D-22): the per-caller credential declarations (`tokens`) and the stdio\n// config-write opt-in (`stdio.grantConfigWrite`, and with it the whole `stdio` object) are deleted.\n// MCP is tokenless since 432-21; a file that still declares either key gets the normal strict\n// unrecognized-key error, with no migration and no special message.\nexport const McpConfigSchema = z.object({\n enabled: z.boolean().optional(),\n transport: z.enum(['http', 'stdio']).optional(),\n host: LoopbackHostSchema.optional(),\n port: z.number().int().min(1).max(65535).optional(),\n path: z.string().trim().min(1).regex(/^\\//, 'MCP path must start with /').optional(),\n}).strict()\n\nexport const CacheConfigSchema = z.object({\n dir: z.string(),\n ttl: DurationString,\n}).strict()\n\nexport const AuthStateConfigSchema = z.object({\n dir: z.string().trim().min(1),\n}).strict()\n\nexport const LoggingConfigSchema = z.object({\n level: z.enum(['silent', 'error', 'warn', 'info', 'debug']),\n}).strict()\n\nexport const RecordingConfigSchema = z.object({\n enabled: z.boolean().default(true),\n keepFailuresOnly: z.boolean().optional(),\n}).strict()\n\nexport const AccessibilityConfigSchema = z.object({\n enabled: z.boolean(),\n standard: z.enum(['wcag2a', 'wcag2aa', 'wcag2aaa']).optional(),\n runAfter: z.enum(['every-step', 'navigation', 'test-end']).optional(),\n failOnViolation: z.boolean().optional(),\n disableRules: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n}).strict()\n\nexport const VisionServiceSchema = z.object({\n screenshotSize: SizeString.optional(),\n effectiveResolution: z.number().positive().int().optional(),\n}).strict()\n\nexport const ServicesSchema = z.object({\n dashboard: DashboardConfigSchema.optional(),\n mcp: McpConfigSchema.optional(),\n cache: CacheConfigSchema.optional(),\n authState: AuthStateConfigSchema.optional(),\n logging: LoggingConfigSchema.optional(),\n // Parse omitted containers too, while retaining optional authoring/input compatibility.\n recording: RecordingConfigSchema.prefault({}).optional(),\n accessibility: AccessibilityConfigSchema.optional(),\n vision: VisionServiceSchema.optional(),\n}).strict()\n","import { z } from 'zod'\nimport ms from 'ms'\nimport bytes from 'bytes'\n\nexport const DurationString = z.string()\n .refine((v) => ms(v as ms.StringValue) !== undefined, {\n message: 'Invalid duration format (e.g., \"30s\", \"5m\", \"1h\")',\n })\n .transform((v) => ms(v as ms.StringValue) as number)\n\nconst VALID_SIZE_RE = /^\\d+(?:\\.\\d+)?\\s*(?:b|kb|mb|gb|tb|k|m|g|t)$/i\n\nfunction normalizeSize(v: string): string {\n return v.replace(/^(\\d+(?:\\.\\d+)?)(k|m|g|t)$/i, '$1$2b')\n}\n\nexport const SizeString = z.string()\n .refine((v) => VALID_SIZE_RE.test(v.trim()) && bytes(normalizeSize(v)) !== null, {\n message: 'Invalid size format (e.g., \"256k\", \"1m\", \"5mb\")',\n })\n .transform((v) => bytes(normalizeSize(v)) as number)\n\nconst COMPATIBLE_PROVIDERS = new Set(['openai-compatible', 'anthropic-compatible'])\nconst SENSITIVE_HEADER_TERMS = ['authorization', 'cookie', 'x-api-key', 'api-key', 'token', 'secret']\nconst CONTROL_CHARACTER_RE = /[\\x00-\\x1F\\x7F]/\n\nfunction validateProviderHeaders(headers: Record<string, string>, ctx: z.RefinementCtx): void {\n const seen = new Set<string>()\n\n for (const [rawKey, rawValue] of Object.entries(headers)) {\n const key = rawKey.trim()\n const value = rawValue.trim()\n const normalizedKey = key.toLowerCase()\n\n if (key === '') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['providerHeaders'],\n message: 'Provider header keys cannot be empty.',\n })\n continue\n }\n\n if (seen.has(normalizedKey)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['providerHeaders'],\n message: `Duplicate provider header \"${key}\" is not allowed.`,\n })\n }\n seen.add(normalizedKey)\n\n if (CONTROL_CHARACTER_RE.test(key) || CONTROL_CHARACTER_RE.test(value)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['providerHeaders'],\n message: `Provider header \"${key}\" cannot contain control characters.`,\n })\n }\n\n const sensitiveTerm = SENSITIVE_HEADER_TERMS.find(term => normalizedKey.includes(term))\n if (sensitiveTerm) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['providerHeaders'],\n message: `Provider header \"${key}\" cannot contain auth-like term \"${sensitiveTerm}\".`,\n })\n }\n }\n}\n\nfunction validateModelConfig(\n config: { provider?: string; baseURL?: string; providerHeaders?: Record<string, string> },\n ctx: z.RefinementCtx,\n) {\n if (\n config.provider\n && COMPATIBLE_PROVIDERS.has(config.provider)\n && (!config.baseURL || config.baseURL.trim() === '')\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['baseURL'],\n message: `Base URL is required for ${config.provider} providers.`,\n })\n }\n\n if (config.providerHeaders !== undefined && config.provider !== 'anthropic-compatible') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['providerHeaders'],\n message: 'providerHeaders can only be used with anthropic-compatible providers.',\n })\n }\n\n if (config.providerHeaders) {\n validateProviderHeaders(config.providerHeaders, ctx)\n }\n}\n\nconst REMOVED_LLM_PROVIDER_VALUES = new Set([\n 'anthropic',\n 'openai',\n 'google',\n 'ollama',\n 'lmstudio',\n 'custom',\n])\n\nconst LLMProviderIdSchema = z.string()\n .regex(/^[a-z0-9][a-z0-9-]*$/, 'Provider must be lowercase alphanumeric + hyphens, starting with alphanumeric')\n .superRefine((provider, ctx) => {\n if (REMOVED_LLM_PROVIDER_VALUES.has(provider)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Provider \"${provider}\" has been removed. Use a compatible provider or an auth plugin provider ID.`,\n })\n }\n })\n\nconst ModelConfigBaseSchema = z.object({\n provider: LLMProviderIdSchema,\n model: z.string(),\n baseURL: z.string().optional(),\n providerHeaders: z.record(z.string(), z.string()).optional(),\n vision: z.boolean().default(true),\n}).strict()\n\nexport const ModelConfigSchema = ModelConfigBaseSchema.superRefine(validateModelConfig)\n\nexport const NameSlugSchema = z.string()\n .regex(/^[a-z0-9][a-z0-9.-]*$/, 'Name must be lowercase letters, digits, hyphens and dots, starting with a letter or digit')\n\nexport const NamedLLMConfigSchema = ModelConfigBaseSchema.extend({\n name: NameSlugSchema,\n contextWindow: SizeString.optional(),\n}).strict().superRefine(validateModelConfig)\n\nexport const TimeoutConfigSchema = z.object({\n step: DurationString,\n test: DurationString,\n navigation: DurationString,\n}).strict()\n\nexport const BrowserConfigSchema = z.object({\n name: z.enum(['chromium', 'firefox', 'webkit']),\n headless: z.boolean(),\n viewport: z.object({\n width: z.number(),\n height: z.number(),\n }).strict().optional(),\n}).strict()\n\nexport const TransportSchema = z.enum(['local', 'browserstack'])\n\n// 436 D-02: the per-step limits are positive integers with no unlimited value; resolvePlannerLimits\n// supplies the default. The old refilling planner key is refused by retired-keys.ts (436-08).\nexport const PlannerConfigSchema = z.object({\n maxActions: z.number().int().positive().optional(),\n maxPlanningTurns: z.number().int().positive().optional(),\n previousStepCount: z.number(),\n}).strict()\n\nexport const LogCaptureConfigSchema = z.object({\n console: z.boolean(),\n network: z.boolean(),\n}).strict()\n","import { z } from 'zod'\n\n// D-10: pure string predicate only — no node:path import. Path resolution happens at\n// composition roots through the host-aware resolver in ./resolve-knowledge-root.ts.\nconst isRepoRelative = (dir: string): boolean =>\n !/^[/\\\\]|^[A-Za-z]:[\\\\/]/.test(dir) && !/^\\.\\.(?:[/\\\\]|$)/.test(dir)\n\nexport const KnowledgeConfigSchema = z.object({\n dir: z.string().trim().min(1)\n .refine(isRepoRelative, {\n message: 'knowledge.dir must be repo-relative — the committed knowledge root must live inside the repo for PR review and the committed .gitignore split',\n })\n .default('agent-qa-knowledge'),\n // D-08: closed enum — deliberately no 'full' mode; full-res artifacts ride the\n // artifact store/git-LFS side channel per knowledge-store.md §5.\n commitArtifacts: z.enum(['none', 'thumbnails']).default('none'),\n // Absent = no cap: the engine's derived budget serves everything it ranks useful; when set\n // it is a hard ceiling min(cap, derived), clamped above min_brief — efficacy over token\n // saving (D-09, binds Phase 380 brief budgeting).\n contextBudgetTokens: z.number().int().positive().optional(),\n}).strict()\n","import { z } from 'zod'\n\n// D-07/D-11: refusals for config keys removed in v2. This scan is a zod pipe PRE-stage in front\n// of the strict root schema — a superRefine chained after .strict() never runs when strict rejects\n// a value (verified on zod 4.6.7), so these messages must fire first. The scan only ADDS issues; the\n// strict stage-B parse remains the acceptance authority. 2026-10-19 (445-07, D-23): every issue\n// carries params.retired so the CLI closes the error with the hard-cut steps.\nconst RETIRED_MEMORY_KEY_MESSAGES: Record<string, string> = {\n dir: 'services.memory.dir was removed in v2 — use knowledge.dir (default agent-qa-knowledge)',\n enabled: 'services.memory.enabled was removed in v2 — memory is always on; delete this key (no disable switch)',\n provider: 'services.memory.provider was removed in v2 — internalized — delete this key',\n minTrust: 'services.memory.minTrust was removed in v2 — internalized — delete this key',\n maxInjections: 'services.memory.maxInjections was removed in v2 — internalized — delete this key',\n curatorEnabled: 'services.memory.curatorEnabled was removed in v2 — internalized — delete this key',\n curatorLockTimeout: 'services.memory.curatorLockTimeout was removed in v2 — internalized — delete this key',\n trustConfirmDelta: 'services.memory.trustConfirmDelta was removed in v2 — internalized — delete this key',\n trustContradictDelta: 'services.memory.trustContradictDelta was removed in v2 — internalized — delete this key',\n ablationEnabled: 'services.memory.ablationEnabled was removed — no ablation exists',\n circuitBreakerEnabled: 'services.memory.circuitBreakerEnabled was removed — no circuit breaker exists',\n circuitBreakerWindowSize: 'services.memory.circuitBreakerWindowSize was removed — no circuit breaker exists',\n circuitBreakerBaselineSize: 'services.memory.circuitBreakerBaselineSize was removed — no circuit breaker exists',\n circuitBreakerThreshold: 'services.memory.circuitBreakerThreshold was removed — no circuit breaker exists',\n}\n\n// 2026-10-07 (436-08, D-05): the old refilling planner key is cut with no alias, migration or\n// fallback. The same message fires for the project config and for test and suite `use` overrides.\nexport const RETIRED_MAX_SUB_ACTIONS_MESSAGE =\n 'use.planner.maxSubActions was removed in v2 — it was a refilling iteration count; set use.planner.maxActions (default 30) and use.planner.maxPlanningTurns (default 30)'\n\nconst RETIRED_PLANNER_KEY = 'maxSubActions'\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction hasRetiredPlannerKey(use: unknown): boolean {\n return isPlainObject(use) && isPlainObject(use.planner) && Object.hasOwn(use.planner, RETIRED_PLANNER_KEY)\n}\n\nexport const retiredKeyScan = z.any().superRefine((value, ctx) => {\n if (!isPlainObject(value)) return\n\n if (isPlainObject(value.services) && value.services.memory !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['services', 'memory'],\n message: 'services.memory was removed in v2 — the memory config surface collapsed into the top-level knowledge block',\n })\n const memory = value.services.memory\n if (isPlainObject(memory)) {\n for (const key of Object.keys(memory)) {\n const message = RETIRED_MEMORY_KEY_MESSAGES[key]\n if (message) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['services', 'memory', key],\n message,\n })\n }\n }\n }\n }\n\n if (isPlainObject(value.workspace) && value.workspace.agentRules !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['workspace', 'agentRules'],\n message: 'workspace.agentRules was removed in v2 — rules dissolve into agent-qa-knowledge/policies/<scope>.md files',\n })\n }\n\n if (hasRetiredPlannerKey(value.use)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['use', 'planner', RETIRED_PLANNER_KEY],\n message: RETIRED_MAX_SUB_ACTIONS_MESSAGE,\n })\n }\n})\n\n// The pre-stage for a test or suite `use` override, for the same strict-parse reason as above.\nexport const retiredUseKeyScan = z.any().superRefine((value, ctx) => {\n if (hasRetiredPlannerKey(value)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['planner', RETIRED_PLANNER_KEY],\n message: RETIRED_MAX_SUB_ACTIONS_MESSAGE,\n })\n }\n})\n","import { z } from 'zod'\nimport { NamedLLMConfigSchema, TransportSchema } from './primitives.js'\nimport { TargetNameSchema } from '../auth-state/schema.js'\n\nfunction isAbsoluteAppPath(value: string): boolean {\n return value.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\n}\n\nexport const AppInstallSchema = z.object({\n path: z.string()\n .refine((v) => !isAbsoluteAppPath(v), { message: 'app.path must be relative' })\n .optional(),\n browserstack: z.string().optional(),\n}).strict()\n\nexport const TargetSchema = z.object({\n product: z.string()\n .refine(\n (v) => !/\\.\\./.test(v) && !/[/\\\\]/.test(v) && !/\\0/.test(v),\n { message: 'product must not contain \"..\", \"/\", \"\\\\\", or null bytes' }\n )\n .optional(),\n platform: z.enum(['web', 'android', 'ios']),\n bundleId: z.string().optional(),\n appPackage: z.string().optional(),\n appActivity: z.string().optional(),\n app: AppInstallSchema.optional(),\n url: z.string().optional(),\n // D-06 (phase 401): which environment a run against this target actually touches. Deliberately\n // `.optional()` with NO default — an undeclared target must stay visibly undeclared; since 432\n // (D-18) undeclared means non-production, decided where the production refusal reads it (the\n // run gate that decided \"shared\" is deleted). A default here would make silence and an honest\n // declaration indistinguishable at every later reader, and\n // `.strict()` above is what turns a typoed key into a refusal rather than a silent undeclared.\n // 432 D-18: `production` is the third declared class; only top-level `allowProduction: true`\n // opts a run into it.\n environment: z.enum(['local', 'shared', 'production']).optional(),\n}).strict().superRefine((val, ctx) => {\n if (val.platform === 'web' && !val.url) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Web targets must have a url' })\n }\n})\n\nexport const DeviceProfileSchema = z.object({\n platform: z.enum(['android', 'ios']),\n transport: TransportSchema,\n match: z.record(z.string(), z.unknown()).optional().default({}),\n}).strict().superRefine((val, ctx) => {\n if (val.transport === 'local') {\n const androidOnly = ['avd', 'serial', 'appPackage', 'appActivity', 'automationName', 'browserName', 'platformVersion']\n const iosOnly = ['udid', 'bundleId', 'automationName', 'platformVersion']\n const allowed = val.platform === 'android' ? androidOnly : iosOnly\n for (const key of Object.keys(val.match)) {\n if (!allowed.includes(key)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['match', key],\n message: `Match field \"${key}\" is not valid for ${val.platform} local transport. Allowed: ${allowed.join(', ')}`,\n })\n }\n }\n }\n})\n\nexport const ProviderConfigSchema = z.record(z.string(), z.unknown())\n\nexport const RegistrySchema = z.object({\n llms: z.array(NamedLLMConfigSchema).optional().default([]),\n targets: z.record(TargetNameSchema, TargetSchema).optional(),\n devices: z.record(z.string(), DeviceProfileSchema).optional(),\n providers: z.record(z.string(), ProviderConfigSchema).optional(),\n}).strict()\n","import { z } from 'zod'\n\nexport const AUTH_STATE_SCHEMA_VERSION = 2\nexport const AUTH_STATE_SLUG_PATTERN = /^[a-z][a-z0-9-]*[a-z0-9]$/\n\nexport const AuthStateNameSchema = z.string().regex(\n AUTH_STATE_SLUG_PATTERN,\n 'Auth state name must match ^[a-z][a-z0-9-]*[a-z0-9]$',\n)\n\nexport const TargetNameSchema = z.string().regex(\n AUTH_STATE_SLUG_PATTERN,\n 'Target name must match ^[a-z][a-z0-9-]*[a-z0-9]$',\n)\n\nexport const AuthStateMetadataSchema = z.object({\n version: z.literal(AUTH_STATE_SCHEMA_VERSION),\n kind: z.literal('web'),\n target: TargetNameSchema,\n name: AuthStateNameSchema,\n capturedAt: z.string().datetime(),\n}).strict()\n\nexport type AuthStateMetadata = z.infer<typeof AuthStateMetadataSchema>\n\n","import { z } from 'zod'\nimport {\n BrowserConfigSchema,\n DurationString,\n TimeoutConfigSchema,\n PlannerConfigSchema,\n LogCaptureConfigSchema,\n} from './primitives.js'\nimport { AuthStateNameSchema } from '../auth-state/schema.js'\n\nexport const MobileAppStateSchema = z.enum(['preserve', 'reset'])\n\nexport const MobileUseSchema = z.object({\n appState: MobileAppStateSchema,\n}).strict()\n\nexport const MobileUseOverrideSchema = z.object({\n appState: MobileAppStateSchema.optional(),\n}).strict()\n\nexport const AuthStateUseSchema = z.union([\n AuthStateNameSchema,\n z.object({\n name: AuthStateNameSchema,\n load: z.boolean().optional(),\n capture: z.boolean().optional(),\n }).strict(),\n])\n\nexport interface NormalizedAuthStateUse {\n name: string\n load: boolean\n capture: boolean\n}\n\nexport function normalizeAuthStateUse(\n use: { authState?: unknown } | undefined,\n): NormalizedAuthStateUse | undefined {\n const parsed = AuthStateUseSchema.safeParse(use?.authState)\n if (!parsed.success) return undefined\n\n if (typeof parsed.data === 'string') {\n return {\n name: parsed.data,\n load: true,\n capture: false,\n }\n }\n\n return {\n name: parsed.data.name,\n load: parsed.data.load ?? true,\n capture: parsed.data.capture ?? false,\n }\n}\n\nexport const UseSchema = z.object({\n browser: BrowserConfigSchema.optional(),\n mobile: MobileUseSchema.optional(),\n timeout: TimeoutConfigSchema.optional(),\n planner: PlannerConfigSchema.optional(),\n logCapture: LogCaptureConfigSchema.optional(),\n cache: z.boolean().optional(),\n llm: z.string().optional(),\n /**\n * Names the app-under-test build for the DCAY-01 buildTag-to-ordinal mapping.\n * Precedence: CLI --build-tag > AGENT_QA_BUILD_TAG > this config key.\n */\n buildTag: z.string().trim().min(1).optional(),\n /**\n * 402-03 (D-12): run the members of one run CONCURRENTLY. Absent or false is one member at a\n * time — today's behaviour, byte for byte.\n */\n parallel: z.boolean().optional(),\n /**\n * 402-03 (D-12): the ceiling on concurrent members when `parallel` is true. Absent resolves to\n * `DEFAULT_PARALLEL_WORKERS` (3). Effective concurrency is `min(memberCount, workers)`, decided\n * in exactly one place — `resolveEffectiveWorkers` in `@vostride/agent-qa-schema`.\n *\n * A POSITIVE INTEGER, refused otherwise: an unbounded or nonsensical count here is the only\n * reachable input to a concurrency denial-of-service (T-402-12), and it is a config typo rather\n * than a caller's field — `RunsStartInput` names neither of these two.\n *\n * NOT `.default(...)`: a defaulted key changes the PARSED config type and every hand-built\n * config fixture would then need it. The default is the resolver's, not the schema's.\n */\n workers: z.number().int().positive().optional(),\n}).strict()\n\nexport const UseOverrideSchema = z.object({\n browser: z.object({\n name: z.enum(['chromium', 'firefox', 'webkit']).optional(),\n headless: z.boolean().optional(),\n viewport: z.object({\n width: z.number().optional(),\n height: z.number().optional(),\n }).strict().optional(),\n }).strict().optional(),\n timeout: z.object({\n step: DurationString.optional(),\n test: DurationString.optional(),\n navigation: DurationString.optional(),\n }).strict().optional(),\n planner: z.object({\n maxActions: z.number().int().positive().optional(),\n maxPlanningTurns: z.number().int().positive().optional(),\n previousStepCount: z.number().optional(),\n }).strict().optional(),\n logCapture: z.object({\n console: z.boolean().optional(),\n network: z.boolean().optional(),\n }).strict().optional(),\n cache: z.boolean().optional(),\n authState: AuthStateUseSchema.optional(),\n mobile: MobileUseOverrideSchema.optional(),\n llm: z.string().optional(),\n parallel: z.boolean().optional(),\n /** 402-03 (D-12): the override half of `use.workers`. Same shape as `UseSchema`'s. */\n workers: z.number().int().positive().optional(),\n device: z.string().optional(),\n}).strict()\n","import { z } from 'zod'\n\nexport const AttributePredicateSchema = z.union([\n z.string(),\n z.object({\n regex: z.string().min(1),\n }).strict(),\n])\n\nexport const AnalyticsSchema = z.object({\n privacy: z.literal(true).optional(),\n passRateScope: z.object({\n attributes: z.record(z.string(), AttributePredicateSchema).optional(),\n }).strict().optional(),\n}).strict()\n\nexport type AnalyticsConfig = z.infer<typeof AnalyticsSchema>\n","import { z } from 'zod'\nimport ms from 'ms'\nimport { isCanonicalHookId, isCanonicalTestId } from '@vostride/agent-qa-ids'\nimport { retiredUseKeyScan } from './retired-keys.js'\nimport { UseOverrideSchema } from './use-schema.js'\n\nconst OptionalDuration = z.string()\n .refine((v) => ms(v as ms.StringValue) !== undefined, {\n message: 'Invalid duration format (e.g., \"30s\", \"5m\", \"1h\")',\n })\n .transform((v) => ms(v as ms.StringValue) as number)\n .optional()\n\nexport const CaptureConfigSchema = z.object({\n variable: z.string(),\n method: z.enum(['regex', 'selector', 'ai']),\n pattern: z.string().optional(),\n selector: z.string().optional(),\n description: z.string().optional(),\n}).strict()\n\nexport const TestStepSchema = z.union([\n z.string(),\n z.object({\n step: z.string(),\n timeout: OptionalDuration,\n retries: z.number().optional(),\n screenshot: z.boolean().optional(),\n capture: CaptureConfigSchema.optional(),\n }).strict(),\n])\n\nexport const TestMetaSchema = z.object({\n timeout: OptionalDuration,\n retries: z.number().optional(),\n record: z.boolean().optional(),\n}).strict()\n\nconst HookIdSchema = z.string().refine((value) => isCanonicalHookId(value), {\n message: 'Hook ID must be h_ followed by 10 id-agent words',\n})\n\nexport const TestDefinitionSchema = z.object({\n 'test-id': z.string().refine((value) => isCanonicalTestId(value), {\n message: 'Test ID must be t_ followed by 10 id-agent words',\n }),\n name: z.string(),\n target: z.string(),\n context: z.string().optional(),\n use: retiredUseKeyScan.pipe(UseOverrideSchema).optional(),\n meta: TestMetaSchema.optional(),\n setup: z.array(HookIdSchema).optional(),\n teardown: z.array(HookIdSchema).optional(),\n steps: z.array(TestStepSchema).min(1),\n}).strict()\n","import { z } from 'zod'\n\n// ActionSchema discriminated union removed — the single source of truth\n// for action definitions is now the tool registry (tools/registry.ts).\n// ActionPlanSchema uses a permissive action schema since runtime validation\n// is handled by the registry's Zod parse in toolCallToActionPlan.\n\nexport const ActionPlanSchema = z.object({\n reasoning: z.string().describe('Brief explanation of why this action was chosen'),\n action: z.object({ type: z.string() }).passthrough(),\n confidence: z.number().describe('Confidence level from 0 to 1'),\n stepComplete: z.boolean().default(false)\n .describe('Whether this action completes the step goal. Set true when the step objective is fully accomplished, false when more actions are needed.'),\n stepFailed: z.boolean().optional().default(false)\n .describe('Set true when the step goal cannot be achieved from the current screen state. When true, no action is executed and the step fails with the reasoning as the error message.'),\n})\n\nexport type ActionPlan = z.infer<typeof ActionPlanSchema>\n","import path from 'node:path'\n\n/**\n * Resolve the repo-relative directory validated by KnowledgeConfigSchema. `configDir` is the\n * directory containing agent-qa.config.yaml (the repository root by the committed-root\n * convention). Composition roots call this helper; Phase 374 has no live producer, so the first\n * runtime caller is Phase 378's Curator binding (D-01/D-14).\n */\nexport function resolveKnowledgeRoot(knowledge: { dir: string }, configDir: string): string {\n return path.resolve(configDir, knowledge.dir)\n}\n","import { z } from 'zod'\nimport { isCanonicalHookId, isCanonicalSuiteId, isCanonicalTestId } from '@vostride/agent-qa-ids'\nimport { retiredUseKeyScan } from './retired-keys.js'\nimport { UseOverrideSchema } from './use-schema.js'\n\nexport const SuiteTestEntrySchema = z.object({\n test: z.string(),\n id: z.string().refine((value) => isCanonicalTestId(value), {\n message: 'Test ID must be t_ followed by 10 id-agent words',\n }),\n}).strict()\n\nconst HookIdSchema = z.string().refine((value) => isCanonicalHookId(value), {\n message: 'Hook ID must be h_ followed by 10 id-agent words',\n})\n\nexport const SuiteDefinitionSchema = z.object({\n 'suite-id': z.string().refine((value) => isCanonicalSuiteId(value), {\n message: 'Suite ID must be s_ followed by 10 id-agent words',\n }).optional(),\n name: z.string(),\n target: z.string(),\n context: z.string().optional(),\n setup: z.array(HookIdSchema).optional(),\n teardown: z.array(HookIdSchema).optional(),\n tests: z.array(SuiteTestEntrySchema).min(1),\n use: retiredUseKeyScan.pipe(UseOverrideSchema).optional(),\n}).strict()\n","import { z } from 'zod'\nimport ms from 'ms'\nimport { isCanonicalHookId } from '@vostride/agent-qa-ids'\n\nconst HookDurationString = z.string()\n .refine((v) => ms(v as ms.StringValue) !== undefined, {\n message: 'Invalid duration format (e.g., \"30s\", \"2m\", \"1h\")',\n })\n .transform((v) => ms(v as ms.StringValue) as number)\n\nconst HOOK_ID_MESSAGE = 'Hook ID must be h_ followed by 10 id-agent words'\n\nexport const HookDefinitionSchema = z.object({\n id: z.string().refine((value) => isCanonicalHookId(value), {\n message: HOOK_ID_MESSAGE,\n }),\n name: z.string().min(1),\n runtime: z.enum(['node', 'bun', 'python', 'bash']),\n file: z.string().min(1),\n deps: z.array(z.string()).optional().default([]),\n packageFile: z.string().optional(),\n timeout: HookDurationString,\n network: z.boolean().optional().default(true),\n})\n\nexport const HooksFileSchema = z.object({\n hooks: z.array(HookDefinitionSchema),\n}).superRefine((val, ctx) => {\n const ids = new Set<string>()\n const names = new Set<string>()\n for (let i = 0; i < val.hooks.length; i++) {\n if (ids.has(val.hooks[i].id)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['hooks', i, 'id'],\n message: `Duplicate hook id: \"${val.hooks[i].id}\"`,\n })\n }\n if (names.has(val.hooks[i].name)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['hooks', i, 'name'],\n message: `Duplicate hook name: \"${val.hooks[i].name}\"`,\n })\n }\n ids.add(val.hooks[i].id)\n names.add(val.hooks[i].name)\n }\n})\n\nexport type HooksFileConfig = z.infer<typeof HooksFileSchema>\n","import { readFile } from 'node:fs/promises'\nimport { parseAllDocuments, LineCounter } from 'yaml'\nimport { TestDefinitionSchema } from '../schema/test-schema.js'\nimport type { TestDefinition } from '../types/test.js'\nimport { formatYamlError, formatZodErrors } from './errors.js'\nimport type { ParseError } from './errors.js'\nimport { findBareVariables } from '@vostride/agent-qa-runner'\n\nexport interface ParseResult {\n tests: TestDefinition[]\n errors: ParseError[]\n}\n\n/**\n * One parsed test paired with the exact source that produced it. ABRF-02 stable identity is\n * `filePath + test.name`; the legacy flattened parse result cannot retain that association and\n * caused multi-file direct runs to stamp every member with the first discovered file (CR-02).\n */\nexport interface ParsedTestBinding {\n test: TestDefinition\n filePath: string\n fileContent: string\n}\n\nexport interface ParseAllTestBindingsResult {\n bindings: ParsedTestBinding[]\n errors: ParseError[]\n}\n\nexport function parseTestFile(\n content: string,\n filePath: string,\n): ParseResult {\n const lineCounter = new LineCounter()\n const docs = parseAllDocuments(content, {\n lineCounter,\n prettyErrors: true,\n strict: true,\n keepSourceTokens: true,\n })\n\n const tests: TestDefinition[] = []\n const errors: ParseError[] = []\n\n for (const doc of docs) {\n // Skip empty documents (trailing --- or empty sections)\n if (doc.contents === null || doc.contents === undefined) continue\n\n // YAML-level syntax errors\n if (doc.errors.length > 0) {\n for (const err of doc.errors) {\n const pos = err.pos?.[0]\n const linePos =\n pos !== undefined ? lineCounter.linePos(pos) : undefined\n errors.push(formatYamlError(err, linePos, content, filePath))\n }\n continue\n }\n\n // Convert AST to plain JS object\n const value = doc.toJS()\n\n // Schema-level validation via Zod\n const parsed = TestDefinitionSchema.safeParse(value)\n if (!parsed.success) {\n errors.push(\n ...formatZodErrors(parsed.error, doc as unknown as Parameters<typeof formatZodErrors>[1], lineCounter, content, filePath),\n )\n } else {\n const bareErrors = checkBareVariables(parsed.data, filePath)\n if (bareErrors.length > 0) {\n errors.push(...bareErrors)\n } else {\n tests.push(parsed.data)\n }\n }\n }\n\n return { tests, errors }\n}\n\nfunction checkBareVariables(test: TestDefinition, filePath: string): ParseError[] {\n const errors: ParseError[] = []\n const textsToCheck: string[] = []\n\n if ((test as any).url) textsToCheck.push((test as any).url)\n for (const step of test.steps) {\n if (typeof step === 'string') {\n textsToCheck.push(step)\n } else {\n textsToCheck.push(step.step)\n }\n }\n\n for (const text of textsToCheck) {\n for (const varName of findBareVariables(text)) {\n errors.push({\n file: filePath,\n line: 1,\n column: 1,\n message: `Variable \"{{${varName}}}\" must use a namespace prefix: {{env:${varName}}}`,\n severity: 'error',\n source: text,\n })\n }\n }\n\n return errors\n}\n\nexport async function parseAllTestBindings(\n filePaths: string[],\n): Promise<ParseAllTestBindingsResult> {\n const bindings: ParsedTestBinding[] = []\n const allErrors: ParseError[] = []\n\n for (const filePath of filePaths) {\n const content = await readFile(filePath, 'utf-8')\n const result = parseTestFile(content, filePath)\n bindings.push(\n ...result.tests.map((test) => ({ test, filePath, fileContent: content })),\n )\n allErrors.push(...result.errors)\n }\n\n return { bindings, errors: allErrors }\n}\n\nexport async function parseAllTests(\n filePaths: string[],\n): Promise<ParseResult> {\n const { bindings, errors } = await parseAllTestBindings(filePaths)\n return { tests: bindings.map(({ test }) => test), errors }\n}\n","import pc from 'picocolors'\n\nimport { yamlParseFailureMessage } from '../validation/yaml-fault.js'\n\nexport interface ParseError {\n file: string\n line: number\n column: number\n message: string\n severity: 'error' | 'warning'\n source: string\n suggestion?: string\n}\n\ninterface FormatOptions {\n noColor?: boolean\n}\n\nfunction shouldUseColor(opts?: FormatOptions): boolean {\n if (opts?.noColor) return false\n if (process.env.NO_COLOR !== undefined) return false\n return true\n}\n\nexport function formatParseError(\n error: ParseError,\n opts?: FormatOptions,\n): string {\n const color = shouldUseColor(opts)\n const lineNum = String(error.line)\n const pad = ' '.repeat(lineNum.length)\n\n const red = color ? pc.red : (s: string) => s\n const bold = color ? pc.bold : (s: string) => s\n const blue = color ? pc.blue : (s: string) => s\n const boldRed = (s: string) => bold(red(s))\n const boldBlue = (s: string) => bold(blue(s))\n\n const severity =\n error.severity === 'error' ? boldRed('error') : bold(pc.yellow('warning'))\n\n let output = ''\n output += `${severity}: ${error.message}\\n`\n output += ` ${boldBlue('-->')} ${error.file}:${error.line}:${error.column}\\n`\n // THE SAME EMPTINESS GUARD `run.ts:605` ALREADY HAS (395-18). `formatYamlError` now returns an\n // empty `source`, and an excerpt block with no excerpt in it is a blank line and a caret pointing\n // at nothing. This is a rendering guard, not a second disclosure guard: the value is already empty\n // at the producer.\n if (error.source) {\n output += ` ${boldBlue(`${pad} |`)}\\n`\n output += ` ${boldBlue(`${lineNum} |`)} ${error.source}\\n`\n output += ` ${boldBlue(`${pad} |`)} ${' '.repeat(Math.max(0, error.column - 1))}${boldRed('^')}\\n`\n }\n\n if (error.suggestion) {\n output += ` ${boldBlue(`${pad} =`)} ${bold('help')}: ${error.suggestion}\\n`\n }\n\n return output\n}\n\nfunction getSourceLine(content: string, line: number): string {\n const lines = content.split('\\n')\n if (line < 1 || line > lines.length) return ''\n return lines[line - 1] ?? ''\n}\n\n/**\n * WHERE, NEVER WHAT — the FOURTH MEMBER, and the one that speaks on TWO channels (395-18 · F-01).\n *\n * `validateFiles` branches on `isSuiteFile` (`validation/validate.ts:341-345`). 395-16 hardened the\n * `if` arm (`validateSuiteFile`) and left the `else` arm: every plain test yaml, reaching here\n * through `validateTestFile` -> `parseTestFile` (`prettyErrors: true`). This function used to return\n * the caught error's own `message` — `yaml` pretty-prints a parse fault with a VERBATIM EXCERPT of\n * the source around the point it gave up, measured on the shipped binary carrying a planted\n * credential out of `agent-qa validate`. A `.suite.yaml` extension is not a property of what a file\n * contains, and it was the only thing separating a hardened member from a leaking one.\n *\n * AND `source` IS THE SECOND CHANNEL. It is `content` split by line and indexed by the fault's own\n * position — the person's own line, verbatim. `formatParseError` renders it, `run.ts:599-613` prints\n * it, and `run.ts:2676` persists the rendering into the dashboard DB. A store is a surface with a\n * delay, so hardening `message` alone would have left the `run` road republishing the same bytes.\n * Both fields are composed here, at the ONE producer `parseTestFile` feeds, so no downstream\n * consumer can reopen either channel.\n *\n * `prettyErrors` STAYS ON at the parser: it is what populates `linePos`, and the two numbers this\n * arm reads are the whole of what the product publishes. The pretty message is DISCARDED here, not\n * suppressed there.\n *\n * `formatZodErrors` is untouched and still carries `source`: a schema issue is a fact about the\n * SHAPE the person wrote, reported at a position this product chose, and the excerpt is the help.\n * The yaml arm is different because the excerpt's extent is the LIBRARY's choice, made around bytes\n * nobody validated.\n */\nexport function formatYamlError(\n err: { message: string; pos?: [number, number] },\n linePos: { line: number; col: number } | undefined,\n content: string,\n filePath: string,\n): ParseError {\n const line = linePos?.line ?? 1\n const col = linePos?.col ?? 1\n\n return {\n file: filePath,\n line,\n column: col,\n message: yamlParseFailureMessage(err),\n severity: 'error',\n source: '',\n suggestion: undefined,\n }\n}\n\nfunction zodPathToSuggestion(\n code: string,\n path: (string | number)[],\n message: string,\n): string | undefined {\n const field = path[path.length - 1]\n if (code === 'invalid_type') {\n if (typeof field === 'string') {\n return `check that '${field}' has the correct type`\n }\n return `check the value type at this position`\n }\n if (code === 'too_small') {\n if (typeof field === 'string' && field === 'steps') {\n return 'tests must have at least one step'\n }\n return message\n }\n if (code === 'invalid_union') {\n return 'steps must be strings like \"Click the login button\" or objects like { step: \"...\", timeout: \"30s\" }'\n }\n if (code === 'unrecognized_keys') {\n return message\n }\n if (typeof field === 'string') {\n return `did you forget to add '${field}'?`\n }\n return undefined\n}\n\ninterface YamlNode {\n range?: [number, number, number]\n items?: YamlNode[]\n key?: YamlNode\n value?: YamlNode | null\n srcToken?: unknown\n}\n\ninterface YamlDoc {\n contents: YamlNode | null\n}\n\ninterface LineCounterLike {\n linePos(offset: number): { line: number; col: number }\n}\n\ninterface ZodIssue {\n path: PropertyKey[]\n message: string\n code: string\n}\n\nfunction resolveNodeAtPath(\n doc: YamlDoc,\n path: (string | number)[],\n): YamlNode | null {\n let current: YamlNode | null = doc.contents\n if (!current) return null\n\n for (const segment of path) {\n if (!current) return null\n\n if (typeof segment === 'number') {\n // Array index — current should be a sequence node with items\n const items: YamlNode[] | undefined = current.items\n if (items && items[segment]) {\n current = items[segment]\n } else {\n return current\n }\n } else {\n // Object key — current should be a mapping node with items\n const items: YamlNode[] | undefined = current.items\n if (!items) return current\n\n let found = false\n for (const pair of items as YamlNode[]) {\n const keyNode: YamlNode | undefined = pair.key\n if (keyNode && 'value' in keyNode && keyNode.value === segment) {\n current = pair.value ?? null\n found = true\n break\n }\n // Sometimes keyNode is the scalar itself\n if (keyNode && 'source' in keyNode && (keyNode as { source?: string }).source === segment) {\n current = pair.value ?? null\n found = true\n break\n }\n }\n if (!found) return current\n }\n }\n\n return current\n}\n\nexport function formatZodErrors(\n zodError: { issues: ZodIssue[] },\n doc: YamlDoc,\n lineCounter: LineCounterLike,\n content: string,\n filePath: string,\n): ParseError[] {\n const errors: ParseError[] = []\n\n for (const issue of zodError.issues) {\n let line = 1\n let col = 1\n\n // Try to resolve the node at the Zod error path\n const issuePath = issue.path.filter((segment): segment is string | number => (\n typeof segment === 'string' || typeof segment === 'number'\n ))\n const node = resolveNodeAtPath(doc, issuePath)\n if (node?.range) {\n const pos = lineCounter.linePos(node.range[0])\n line = pos.line\n col = pos.col\n } else if (doc.contents?.range) {\n const pos = lineCounter.linePos(doc.contents.range[0])\n line = pos.line\n col = pos.col\n }\n\n const suggestion = zodPathToSuggestion(issue.code, issuePath, issue.message)\n\n errors.push({\n file: filePath,\n line,\n column: col,\n message: issuePath.length > 0\n ? `${issuePath.join('.')}: ${issue.message}`\n : issue.message,\n severity: 'error',\n source: getSourceLine(content, line),\n suggestion,\n })\n }\n\n return errors\n}\n","/**\n * A yaml parse failure as a POSITION, and as nothing else (395-10 · GAP 1 / CR-01 · 395-14 · F-01).\n *\n * THE ERROR IS NOT A MESSAGE SOURCE HERE. `yaml`'s `YAMLParseError` carries `linePos` — where the\n * parser gave up — beside a `message` that is pretty-printed with a verbatim excerpt of the\n * offending source line and a caret beneath the column. Every other property (`message`, `code`,\n * the object's own stringification) is derived from the person's file content and is therefore not\n * this product's to publish: the strings built from this one are persisted in blocked records,\n * printed by `proposals show`, thrown out of every config op, printed by `agent-qa validate`, and —\n * through `refusalMessage` — carried into a chat turn's answer and its session jsonl. So this\n * function reads two NUMBERS and composes a sentence of its own.\n *\n * THE FALLBACK IS VALUE-FREE TOO, and that is the point of having one. A throw with no `linePos` is\n * not a yaml parse error this product recognises, and the tempting repair — fall back to the error's\n * message when the position is missing — would reopen the whole channel for exactly the inputs\n * nobody anticipated.\n *\n * IT LIVES IN CORE AND HAS THREE CALLERS (395-14). It was a private copy in the cli composition\n * root; the loader guard and core's own `validateConfig` arm need the SAME sentence, and two\n * spellings of one sentence are two things that can drift apart. One primitive, three callers:\n * `cli/src/config.ts`, `core/src/validation/validate.ts`, and the cli validate port.\n *\n * THE ARGUMENT IS GUARDED BEFORE IT IS READ (395-14 · WR-08 / F-09). A `throw null` or a\n * `throw 'boom'` is a legal throw; the 395-10 copy reached for `.linePos` unguarded and answered a\n * TypeError for `null` — a crash inside the code whose whole job is to turn a fault into a sentence.\n */\nexport function yamlParseFailureMessage(error: unknown): string {\n if (typeof error !== 'object' || error === null) {\n return 'not readable as YAML (position unavailable)'\n }\n const linePos = (error as { linePos?: readonly { line?: unknown; col?: unknown }[] }).linePos\n const first = Array.isArray(linePos) ? linePos[0] : undefined\n if (typeof first?.line === 'number' && typeof first.col === 'number') {\n return `not readable as YAML at line ${first.line}, column ${first.col}`\n }\n return 'not readable as YAML (position unavailable)'\n}\n","import { readFile, access } from 'node:fs/promises'\nimport { dirname, resolve, extname } from 'node:path'\n\nexport interface FileAttachment {\n name: string\n path: string\n content: Buffer\n mimeType: string\n}\n\nconst MIME_TYPES: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.svg': 'image/svg+xml',\n '.pdf': 'application/pdf',\n '.doc': 'application/msword',\n '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n '.txt': 'text/plain',\n '.csv': 'text/csv',\n '.json': 'application/json',\n '.xml': 'application/xml',\n '.zip': 'application/zip',\n}\n\nfunction detectMimeType(filename: string): string {\n const ext = extname(filename).toLowerCase()\n return MIME_TYPES[ext] ?? 'application/octet-stream'\n}\n\nconst FILE_REF_PATTERN = /\\$\\{file:([^}]+)\\}/g\n\nexport async function resolveFileReferences(\n stepText: string,\n testFilePath: string,\n): Promise<{ resolvedText: string; attachments: FileAttachment[] }> {\n const matches = [...stepText.matchAll(FILE_REF_PATTERN)]\n\n if (matches.length === 0) {\n return { resolvedText: stepText, attachments: [] }\n }\n\n const testDir = dirname(testFilePath)\n const attachments: FileAttachment[] = []\n let resolvedText = stepText\n\n for (const match of matches) {\n const filename = match[1]\n const absolutePath = resolve(testDir, filename)\n\n try {\n await access(absolutePath)\n } catch {\n throw new Error(\n `File attachment not found: \"${filename}\" (resolved to \"${absolutePath}\", referenced in test \"${testFilePath}\")`,\n )\n }\n\n const content = await readFile(absolutePath) as Buffer\n\n attachments.push({\n name: filename,\n path: absolutePath,\n content,\n mimeType: detectMimeType(filename),\n })\n\n resolvedText = resolvedText.replace(match[0], absolutePath)\n }\n\n return { resolvedText, attachments }\n}\n","import { readFile } from 'node:fs/promises'\nimport { parse as parseYaml } from 'yaml'\nimport { SuiteDefinitionSchema } from '../schema/suite-schema.js'\nimport { yamlParseFailureMessage } from '../validation/yaml-fault.js'\nimport type { SuiteDefinition } from '../suite/types.js'\n\nexport async function parseSuiteFile(filePath: string): Promise<SuiteDefinition> {\n const content = await readFile(filePath, 'utf-8')\n\n let raw: unknown\n try {\n raw = parseYaml(content)\n } catch (err) {\n // WHERE, NEVER WHAT — the `run --suite` road (395-18, found by Task 2's enumeration).\n // This call had NO catch at all, so `yaml`'s pretty-printed throw travelled straight out of\n // `run.ts:1079`'s suite preflight and was reported as `Framework error: <the person's own\n // lines>`. Measured on the shipped binary carrying a planted credential before this arm\n // existed. `validateSuiteFile` — the SAME file class on the `validate` road — was hardened in\n // 395-16; this is its sibling one command over, which is the failure mode this codebase keeps\n // repeating.\n //\n // IT STILL THROWS. Turning it into a typed refusal is F-03's subject; only the message's\n // CONTENT changes here. The path is prefixed because the caller reports the message alone.\n // No `cause` is attached: a raw `YAMLParseError` hung on a thrown value is republished by\n // `util.inspect` and every printer built on it (395-16 · D-395-16-A).\n throw new Error(`${filePath}: ${yamlParseFailureMessage(err)}`)\n }\n\n return SuiteDefinitionSchema.parse(raw)\n}\n","// RFC-6902 patch application at the CST level (394, D-20 · WTST-07).\n//\n// The problem this file exists for: every JSON-Patch library on npm is correct and unusable here,\n// because all of them mutate plain JS values. Routing an edit through `doc.toJS()` and back throws\n// away the concrete syntax tree — the only thing carrying the bytes of the lines nobody asked to\n// change — so comments vanish, quoting is normalised and mapping keys come back in whatever order\n// the object literal had. WTST-07's promise is that an edit never reformats an untouched line, and\n// that promise is only keepable by mutating the CST in place and concatenating it back.\n//\n// A SIBLING, NOT A CHANGE TO `yaml-parser.ts`. `parseTestFile` calls `parseAllDocuments` and\n// discards the token array, so it structurally cannot serve the edit path. It is left alone and\n// re-used here for exactly one job: re-parsing the RENDERED bytes, which is how a mutation that\n// produced an unrunnable document becomes a refusal instead of a written file.\n//\n// THE FENCE AND THE PREFIX FENCE ARE DIFFERENT CONTROLS. `EDITABLE_POINTER_ROOTS` bounds WHICH\n// PART OF A DOCUMENT any patch may address at all (T-394-10); plan 06's passing-prefix fence\n// bounds WHICH STEP a repair may touch. Neither substitutes for the other, and a document whose\n// `target` is reachable is a document whose test can be silently pointed at a different app.\n\nimport {\n Composer,\n CST,\n Document,\n Parser,\n isMap,\n isScalar,\n isSeq,\n} from 'yaml'\nimport type { Node, Scalar, YAMLSeq } from 'yaml'\n\nimport {\n EDITABLE_POINTER_ROOTS,\n isEditablePointer,\n parseJsonPointer,\n} from '@vostride/agent-qa-schema'\nimport type { PatchOp, TestEditPatchSet } from '@vostride/agent-qa-schema'\n\nimport { parseTestFile } from './yaml-parser.js'\n\n/**\n * A test document parsed so that BOTH halves survive: the composed model a pointer resolves\n * against, and the token array the render concatenates.\n *\n * The two are not redundant. Pointer resolution needs the model (`getIn`-shaped navigation over\n * maps and sequences); byte preservation needs the tokens. Handing a caller only one of them would\n * force it to re-parse to get the other, and a second parse is a second opinion about the source.\n */\nexport interface ParsedTestDocument {\n readonly source: string\n readonly filePath: string\n readonly tokens: CST.Token[]\n readonly doc: Document\n}\n\n// ---- Refusals -------------------------------------------------------------------------------\n//\n// Separate classes, never one error carrying a `kind`. A caller legitimately distinguishes \"you\n// addressed a region you may not edit\" (a boundary violation worth reporting) from \"your pointer\n// does not resolve\" (a stale or hallucinated path, worth retrying against a fresh read) from\n// \"your edit produced a document this project cannot run\" (worth repairing) from \"that op cannot\n// be applied to that kind of node\" (worth re-planning the edit). One class with a discriminator\n// would make every one of those `catch` blocks read a string.\n\n/** A pointer addressed a document root outside `EDITABLE_POINTER_ROOTS` (T-394-10). */\nexport class PatchPointerOutsideEditableRegionError extends Error {\n constructor(readonly pointer: string) {\n super(\n `cst-patch: the pointer ${pointer} addresses a region no patch may edit; `\n + `only ${EDITABLE_POINTER_ROOTS.join(', ')} are editable, because a patch that can reach `\n + 'the identity fields can silently change which app the test drives',\n )\n this.name = 'PatchPointerOutsideEditableRegionError'\n }\n}\n\n/** A pointer named a node the document does not have. */\nexport class PatchPointerUnresolvableError extends Error {\n constructor(readonly pointer: string, readonly detail: string) {\n super(\n `cst-patch: the pointer ${pointer} does not resolve against this document (${detail}); `\n + 'a patch is applied to the document it was written against, never to a guess',\n )\n this.name = 'PatchPointerUnresolvableError'\n }\n}\n\n/**\n * The op cannot be applied to the node its pointer reached.\n *\n * `add` and `remove` operate on block-sequence items only. Adding or removing a top-level KEY\n * changes the document's shape rather than its content, and D-02 already routes a shape change\n * through whole-document emission with a full schema validation — so admitting it here would\n * publish a second, weaker path to the same outcome.\n */\nexport class PatchOpUnsupportedTargetError extends Error {\n constructor(readonly pointer: string, readonly detail: string) {\n super(`cst-patch: the pointer ${pointer} cannot carry this op: ${detail}`)\n this.name = 'PatchOpUnsupportedTargetError'\n }\n}\n\n/**\n * A document this project cannot run — checked on the SOURCE before anything is applied and on the\n * RENDERED bytes before anything may be written.\n *\n * Both directions matter. Validating only the render would let a pre-existing invalidity be\n * blamed on the patch; validating only the source would let a CST mutation that produced\n * structurally broken YAML reach a file. Same predicate, same evidence, two call sites.\n */\nexport class PatchedDocumentInvalidError extends Error {\n constructor(readonly phase: 'source' | 'rendered', readonly detail: string) {\n super(\n `cst-patch: the ${phase} document is not a valid test: ${detail}; `\n + 'a patched document is schema-validated before any caller may write it (WTST-07)',\n )\n this.name = 'PatchedDocumentInvalidError'\n }\n}\n\n// ---- Parse ----------------------------------------------------------------------------------\n\n/**\n * Parse a test file retaining the CST token array beside the composed document.\n *\n * The composer is given `keepSourceTokens` so every node carries a `srcToken` back-reference; that\n * back-reference is the entire bridge between a pointer (which addresses the model) and a mutation\n * (which must land on the syntax).\n */\nexport function parseTestFileWithTokens(source: string, filePath: string): ParsedTestDocument {\n const tokens = [...new Parser().parse(source)]\n const docs = [...new Composer({ keepSourceTokens: true }).compose(tokens)]\n\n if (docs.length !== 1) {\n throw new PatchedDocumentInvalidError(\n 'source',\n `expected exactly one YAML document, found ${docs.length}`,\n )\n }\n const doc = docs[0]!\n if (doc.errors.length > 0) {\n throw new PatchedDocumentInvalidError(\n 'source',\n doc.errors.map((error) => error.message).join('; '),\n )\n }\n\n assertRunnable('source', source, filePath)\n\n return { source, filePath, tokens, doc }\n}\n\nfunction assertRunnable(phase: 'source' | 'rendered', content: string, filePath: string): void {\n const { tests, errors } = parseTestFile(content, filePath)\n if (errors.length > 0) {\n throw new PatchedDocumentInvalidError(phase, errors.map((error) => error.message).join('; '))\n }\n if (tests.length !== 1) {\n throw new PatchedDocumentInvalidError(\n phase,\n `expected exactly one test definition, found ${tests.length}`,\n )\n }\n}\n\n// ---- Apply ----------------------------------------------------------------------------------\n\n/**\n * Apply a patch set in document order, mutating `parsed.doc` and its tokens in place.\n *\n * TWO PROPERTIES THE ORDER BUYS. First, the fence runs over the WHOLE set before any mutation, so\n * a set mixing a legitimate op with an out-of-region one leaves nothing behind — a per-op check\n * would have already rewritten the legitimate target by the time it refused. Second, each pointer\n * resolves against the document as PRIOR ops left it, which is what RFC-6902 means by a sequence\n * of operations: an `add` earlier in an array shifts every later index, and resolving every\n * pointer against the original document would edit a plausible, schema-valid, wrong step.\n */\nexport function applyPatchSetToTestDoc(\n parsed: ParsedTestDocument,\n patchSet: TestEditPatchSet,\n): void {\n for (const op of patchSet.patches) {\n if (!isEditablePointer(op.path)) throw new PatchPointerOutsideEditableRegionError(op.path)\n }\n for (const op of patchSet.patches) {\n applyOne(parsed.doc, op)\n }\n}\n\nfunction applyOne(doc: Document, op: PatchOp): void {\n const segments = parseJsonPointer(op.path)\n\n switch (op.op) {\n case 'replace': {\n const node = resolveNode(doc, segments)\n if (node === undefined) {\n throw new PatchPointerUnresolvableError(op.path, 'no node at that path')\n }\n if (!isScalar(node) || node.srcToken === undefined) {\n throw new PatchOpUnsupportedTargetError(\n op.path,\n 'replace writes one scalar token, and that path is a collection',\n )\n }\n CST.setScalarValue(node.srcToken, op.value)\n return\n }\n\n case 'add': {\n const { seqToken, index } = resolveSeqSlot(doc, op.path, segments, 'add')\n if (index > seqToken.items.length) {\n throw new PatchPointerUnresolvableError(\n op.path,\n `index ${index} is past the end of a ${seqToken.items.length}-item sequence`,\n )\n }\n if (index > 0) terminateItem(seqToken.items[index - 1])\n seqToken.items.splice(index, 0, newSeqItem(seqToken, op.value))\n normalizeItemStarts(seqToken)\n resyncSeqNode(doc, segments.slice(0, -1))\n return\n }\n\n case 'remove': {\n const { seqToken, index } = resolveSeqSlot(doc, op.path, segments, 'remove')\n if (index >= seqToken.items.length) {\n throw new PatchPointerUnresolvableError(\n op.path,\n `index ${index} is past the end of a ${seqToken.items.length}-item sequence`,\n )\n }\n seqToken.items.splice(index, 1)\n normalizeItemStarts(seqToken)\n resyncSeqNode(doc, segments.slice(0, -1))\n return\n }\n }\n}\n\ninterface SeqSlot {\n seqToken: CST.BlockSequence\n index: number\n}\n\n/** Resolve `<parent>/<index|->` to the parent's block-sequence token and a slot in it. */\nfunction resolveSeqSlot(\n doc: Document,\n pointer: string,\n segments: string[],\n op: 'add' | 'remove',\n): SeqSlot {\n if (segments.length < 2) {\n throw new PatchOpUnsupportedTargetError(\n pointer,\n `${op} operates on a sequence item, and that path names a top-level key; `\n + 'adding or removing a key is a document rewrite (D-02), not a patch',\n )\n }\n\n const parent = resolveNode(doc, segments.slice(0, -1))\n if (parent === undefined) {\n throw new PatchPointerUnresolvableError(pointer, 'the parent collection does not resolve')\n }\n if (!isSeq(parent)) {\n throw new PatchOpUnsupportedTargetError(\n pointer,\n `${op} operates on a sequence item, and the parent at that path is not a sequence`,\n )\n }\n\n const seqToken = (parent as YAMLSeq).srcToken\n if (seqToken === undefined || seqToken.type !== 'block-seq') {\n throw new PatchOpUnsupportedTargetError(\n pointer,\n `${op} rebuilds block-sequence indentation, and that sequence is written in flow style`,\n )\n }\n\n const last = segments[segments.length - 1]!\n if (op === 'add' && last === '-') return { seqToken, index: seqToken.items.length }\n\n const index = asIndex(last)\n if (index === undefined) {\n throw new PatchPointerUnresolvableError(pointer, `${last} is not a sequence index`)\n }\n return { seqToken, index }\n}\n\nfunction asIndex(segment: string): number | undefined {\n return /^(?:0|[1-9]\\d*)$/.test(segment) ? Number(segment) : undefined\n}\n\n/** Walk the composed model one reference token at a time. */\nfunction resolveNode(doc: Document, segments: string[]): Node | undefined {\n let node: unknown = doc.contents\n for (const segment of segments) {\n if (isSeq(node)) {\n const index = asIndex(segment)\n if (index === undefined || index >= node.items.length) return undefined\n node = node.items[index]\n } else if (isMap(node)) {\n const pair = node.items.find(\n (candidate) => isScalar(candidate.key) && String((candidate.key as Scalar).value) === segment,\n )\n if (pair === undefined) return undefined\n node = pair.value\n } else {\n return undefined\n }\n }\n return (node ?? undefined) as Node | undefined\n}\n\n/**\n * Re-compose the sequence NODE after its token items changed.\n *\n * The composed model and the CST are two views of one document, and a structural edit moves them\n * out of step: splicing `srcToken.items` changes what the file says while `seq.items` still\n * describes what it said. Every later pointer in the same set resolves against the MODEL, so\n * leaving it stale is exactly how the second op of a two-op set lands on the wrong index.\n */\nfunction resyncSeqNode(doc: Document, parentSegments: string[]): void {\n const parent = resolveNode(doc, parentSegments)\n if (!isSeq(parent)) return\n\n const seqToken = (parent as YAMLSeq).srcToken\n if (seqToken === undefined || seqToken.type !== 'block-seq') return\n\n const rebuilt = [\n ...new Composer({ keepSourceTokens: true }).compose([\n { type: 'document', offset: 0, start: [], value: seqToken },\n ]),\n ]\n const contents = rebuilt[0]?.contents\n if (!isSeq(contents)) return\n\n const seq = parent as YAMLSeq\n seq.items = contents.items\n}\n\n/**\n * Build a block-sequence item at the sequence's own indent.\n *\n * `createScalarToken` supplies a trailing newline of its own; without it an appended item glues\n * itself onto the previous line, which is the concrete failure the 394 research probe hit.\n */\nfunction newSeqItem(seqToken: CST.BlockSequence, value: string): CST.BlockSequence['items'][number] {\n return {\n start: [\n { type: 'seq-item-ind', offset: -1, indent: seqToken.indent, source: '-' },\n { type: 'space', offset: -1, indent: seqToken.indent + 1, source: ' ' },\n ],\n value: CST.createScalarToken(value, { indent: seqToken.indent + 2 }),\n }\n}\n\n/**\n * Give an item a trailing newline if it has none, so the next item starts on its own line.\n *\n * The absence of a terminator is expressed as an ABSENT `end` key, not an empty array: a file whose\n * last line has no newline yields a scalar token with no `end` property at all. Probing for the\n * key and returning early therefore skips exactly the case this function exists for — which is how\n * an append onto an unterminated last item produces two steps concatenated on one line. A\n * block-scalar carries its own terminator inside `source` and is left alone.\n */\nfunction terminateItem(item: CST.BlockSequence['items'][number] | undefined): void {\n const value = item?.value\n if (value === undefined || !CST.isScalar(value) || value.type === 'block-scalar') return\n const end = (value.end ??= [])\n if (end.some((token) => token.type === 'newline')) return\n end.push({ type: 'newline', offset: -1, indent: 0, source: '\\n' })\n}\n\n/**\n * Restore the one positional invariant of a block sequence after items moved.\n *\n * Item 0 alone does NOT carry its own leading whitespace — the indentation before the first `-`\n * belongs to the parent mapping item's separator tokens, while items 1..n each carry a `space`\n * token of their own. So an insert at index 0, or a removal of index 0, silently produces a\n * document where one line's indentation is wrong. Only items whose position-0-ness actually\n * changed are touched; every other item's `start` array is left exactly as parsed, which is what\n * keeps `remove` from re-indenting lines nobody addressed.\n */\nfunction normalizeItemStarts(seqToken: CST.BlockSequence): void {\n const pad = ' '.repeat(seqToken.indent)\n seqToken.items.forEach((item, index) => {\n const start = item.start\n const leadsWithSpace = start[0]?.type === 'space'\n if (index === 0 && leadsWithSpace) start.shift()\n if (index > 0 && !leadsWithSpace) {\n start.unshift({ type: 'space', offset: -1, indent: 0, source: pad })\n }\n })\n}\n\n// ---- Render ---------------------------------------------------------------------------------\n\n/**\n * Concatenate the whole token array back to bytes, then refuse anything unrunnable.\n *\n * THE RENDER IS OVER `parsed.tokens`, NEVER OVER THE DOCUMENT TOKEN ALONE. `CST.stringify`'s own\n * doc comment states it \"applies no validation whatsoever, and simply concatenates the sources in\n * their logical order\" — that concatenation IS the byte-preservation guarantee. A file's leading\n * comment is a separate token in the parser's output stream, positioned BEFORE the document token,\n * so `CST.stringify(documentToken)` drops it. That is the one genuinely non-obvious line here, it\n * was measured rather than reasoned about, and the frozen corpus's untouched-round-trip row is\n * the cell that catches a regression to it.\n */\nexport function renderPatchedTestDoc(parsed: ParsedTestDocument, filePath?: string): string {\n const rendered = parsed.tokens.map((token) => CST.stringify(token)).join('')\n assertRunnable('rendered', rendered, filePath ?? parsed.filePath)\n return rendered\n}\n","const CHARS_PER_TOKEN = 4\n\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / CHARS_PER_TOKEN)\n}\n","export type {\n StepContext,\n PlannerConfig,\n Planner,\n Verifier,\n VerificationResult,\n PlanResult,\n VerifyResult,\n ActionPlan,\n ExtractionMethod,\n ExtractorInput,\n CaptureResult,\n VariableExtractor,\n} from './types.js'\n\nexport { estimateTokens } from './token-budget.js'\n\n// Phase 363-11: core's per-test run path (runTest/runTestWithRetry + the inline-DSL parsers +\n// failure-summary) was dissolved onto runner soil (runMemberTest / run/inline-steps). Consumers\n// import those from @vostride/agent-qa-runner directly.\n\n// Variables subsystem moved to @vostride/agent-qa-runner (Phase 363 D-07); consumers\n// import it from runner directly. The env-file codec stays runner-owned (Plan 04) and is\n// re-exported here for the existing CLI/dashboard env-file consumers (the Plan-04 precedent).\nexport { parseEnvFile, serializeEnvFile } from '@vostride/agent-qa-runner'\n","import { XMLParser } from 'fast-xml-parser'\nimport type { InterimNode, RefBinding } from '@vostride/agent-qa-runner'\nimport { isToggleElement, type ElementLabels, type ElementState } from '@vostride/agent-qa-schema'\nimport type { ParsedMobileSource, RefEntry } from './types.js'\nimport { IOS_EDITABLE_TYPES, iosAccessibleOtherRole, normalizeRole } from './role-map.js'\n\nconst INTERACTIVE_ROLES = new Set([\n 'button', 'link', 'textbox', 'checkbox', 'radio', 'combobox',\n 'searchbox', 'slider', 'switch', 'tab', 'menuitem',\n // Additional interactive roles (matching expanded web set and mobile types)\n 'spinbutton', 'option', 'menuitemradio', 'menuitemcheckbox',\n 'gridcell', 'scrollbar', 'separator',\n 'grid', 'menu', 'menubar', 'tree', 'treegrid', 'treeitem',\n 'listbox', 'pickerwheel',\n])\n\nconst CONTENT_ROLES = new Set([\n 'text', 'heading', 'cell', 'listitem', 'image', 'navigation', 'alert',\n 'progressbar',\n])\n\n// Only interactive/content roles become interim nodes; structural containers\n// (group/window/application/scroll-area/...) are filtered — their children reparent to\n// the nearest surviving ancestor. This preserves the v1 element set exactly (the same\n// nodes that used to receive refs), now minted by the shared builder.\nfunction shouldEmit(role: string): boolean {\n return INTERACTIVE_ROLES.has(role) || CONTENT_ROLES.has(role)\n}\n\n// fast-xml-parser leaves attribute values as strings (parseAttributeValue is off), so a\n// real boolean signal is the literal \"true\" — coerce defensively per T-352-07.\nfunction boolAttr(value: unknown): boolean {\n return value === true || value === 'true'\n}\n\nfunction parseAndroidBounds(boundsStr: string): { x: number; y: number; width: number; height: number } | undefined {\n const match = boundsStr.match(/^\\[(\\d+),(\\d+)\\]\\[(\\d+),(\\d+)\\]$/)\n if (!match) return undefined\n const x1 = parseInt(match[1], 10)\n const y1 = parseInt(match[2], 10)\n const x2 = parseInt(match[3], 10)\n const y2 = parseInt(match[4], 10)\n return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 }\n}\n\nfunction parseIosBounds(attrs: Record<string, any>): { x: number; y: number; width: number; height: number } | undefined {\n const x = parseFloat(attrs['@_x'])\n const y = parseFloat(attrs['@_y'])\n const width = parseFloat(attrs['@_width'])\n const height = parseFloat(attrs['@_height'])\n if (isNaN(x) || isNaN(y) || isNaN(width) || isNaN(height)) return undefined\n return { x, y, width, height }\n}\n\nfunction extractLabel(attrs: Record<string, any>, platform: 'android' | 'ios'): string | undefined {\n if (platform === 'android') {\n const contentDesc = attrs['@_content-desc']\n if (contentDesc) return contentDesc\n const text = attrs['@_text']\n if (text) return text\n return undefined\n }\n // iOS\n const label = attrs['@_label']\n if (label) return label\n const name = attrs['@_name']\n if (name) return name\n const value = attrs['@_value']\n if (value) return value\n return undefined\n}\n\nfunction extractValue(attrs: Record<string, any>, platform: 'android' | 'ios'): string | undefined {\n const value = platform === 'android' ? attrs['@_text'] : attrs['@_value']\n if (value === undefined || value === null || value === '') return undefined\n return String(value)\n}\n\n/**\n * D-08 attribute lift. Only signals the platform actually emitted populate `state` —\n * an absent attribute leaves the key typed-absent (the builder applies documented\n * defaults). No signal is ever fabricated.\n *\n * Attribute names verified against core/src/mobile/__tests__/xml-parser.test.ts\n * page-source fixtures (Assumption A1): Android UiAutomator2 uses hyphenated\n * `resource-id`/`content-desc` and literal `checkable`/`checked`/`selected`/`focused`/\n * `scrollable`/`enabled`/`displayed`; iOS XCUITest uses `value`/`selected`/`enabled`/\n * `visible`. `scrollable` is retained in the raw attribute bag (consumed by\n * deriveMobileScroll), not lifted onto state.\n *\n * iOS `editable`: XCUITest exposes no editability attribute (WDA writes `focused` only on\n * tvOS, and `traits` lists public UIKit traits only), so the XCUI text-entry type is the\n * platform's editability signal. It is a candidate: the adapter confirms it by keyboard\n * focus at execution, which is how a static UITextView is told apart.\n *\n * iOS `checked` (437 D-03): XCUITest reports a switch, toggle or checkbox's state only as its\n * `value`, so for a classifier toggle of role `switch` or `checkbox` the value '1' lifts to\n * checked true and '0' to checked false. Any other value, or none, leaves `checked` absent.\n * `selected` keeps no toggle meaning on either platform.\n */\nfunction liftState(\n tagName: string,\n role: string,\n attrs: Record<string, any>,\n platform: 'android' | 'ios',\n bounds: { x: number; y: number; width: number; height: number } | undefined,\n viewport: { width: number; height: number } | undefined,\n): Partial<ElementState> {\n const state: Partial<ElementState> = {}\n\n if (attrs['@_enabled'] !== undefined) {\n state.enabled = boolAttr(attrs['@_enabled'])\n }\n if (attrs['@_selected'] !== undefined) {\n state.selected = boolAttr(attrs['@_selected'])\n }\n\n if (platform === 'android') {\n // `checked` is only meaningful when the widget is `checkable` — otherwise typed-absent.\n if (boolAttr(attrs['@_checkable']) && attrs['@_checked'] !== undefined) {\n state.checked = boolAttr(attrs['@_checked'])\n }\n if (attrs['@_focused'] !== undefined) {\n state.focused = boolAttr(attrs['@_focused'])\n }\n // visible derivation (documented): explicit displayed=false, else bounds fully\n // outside the viewport ⇒ offscreen. Absent otherwise (builder defaults visible=true).\n if (attrs['@_displayed'] !== undefined && !boolAttr(attrs['@_displayed'])) {\n state.visible = false\n } else if (bounds && viewport && (bounds.y + bounds.height < 0 || bounds.y > viewport.height)) {\n state.visible = false\n }\n } else {\n if ((role === 'switch' || role === 'checkbox') && isToggleElement({ role })) {\n const value = attrs['@_value']\n if (value === '1') state.checked = true\n else if (value === '0') state.checked = false\n }\n if (attrs['@_visible'] !== undefined && !boolAttr(attrs['@_visible'])) {\n state.visible = false\n } else if (bounds && viewport && (bounds.y + bounds.height < 0 || bounds.y > viewport.height)) {\n state.visible = false\n }\n if (IOS_EDITABLE_TYPES.has(tagName) && state.enabled !== false) {\n state.editable = true\n }\n }\n\n return state\n}\n\n/** Android maps `resource-id -> labels.testId` and `content-desc -> labels.ariaLabel`\n * (empty strings stay absent). iOS carries no dedicated label attributes here. */\nfunction liftLabels(attrs: Record<string, any>, platform: 'android' | 'ios'): ElementLabels {\n const labels: ElementLabels = {}\n if (platform === 'android') {\n const resourceId = attrs['@_resource-id']\n if (resourceId) labels.testId = String(resourceId)\n const contentDesc = attrs['@_content-desc']\n if (contentDesc) labels.ariaLabel = String(contentDesc)\n }\n return labels\n}\n\ninterface WalkContext {\n platform: 'android' | 'ios'\n nodes: InterimNode[]\n viewport?: { width: number; height: number }\n screenReference?: { width: number; height: number }\n}\n\nconst IOS_FULL_SCREEN_AREA_RATIO = 0.9\nconst IOS_PROMOTED_NAME_MAX = 120\n\nfunction collectAttrs(node: any): Record<string, any> {\n const attrs: Record<string, any> = {}\n for (const key of Object.keys(node)) {\n if (key.startsWith('@_')) attrs[key] = node[key]\n }\n return attrs\n}\n\n// UIKit merges an accessible element's subviews into it and exposes no child text, so its\n// label is the only handle; React Native pressables without an accessibilityRole surface\n// this way as XCUIElementTypeOther.\nfunction isIosAccessibleLabelledOther(\n tagName: string,\n attrs: Record<string, any>,\n ctx: WalkContext,\n): boolean {\n if (ctx.platform !== 'ios' || tagName !== 'XCUIElementTypeOther') return false\n if (!boolAttr(attrs['@_accessible'])) return false\n const label = attrs['@_label']\n if (label === undefined || label === null || String(label).trim() === '') return false\n const bounds = parseIosBounds(attrs)\n if (!bounds) return false\n if (attrs['@_visible'] !== undefined && !boolAttr(attrs['@_visible'])) return false\n // WDA reports a frame it cannot compute as (-1,-1,0,0).\n if (!(bounds.width > 0 && bounds.height > 0)) return false\n const ref = ctx.screenReference\n if (ref && ref.width > 0 && ref.height > 0) {\n const onScreen =\n bounds.x < ref.width &&\n bounds.y < ref.height &&\n bounds.x + bounds.width > 0 &&\n bounds.y + bounds.height > 0\n if (!onScreen) return false\n const area = bounds.width * bounds.height\n if (area >= IOS_FULL_SCREEN_AREA_RATIO * ref.width * ref.height) return false\n }\n return true\n}\n\n// React Native joins a pressable's subtree text into its label, which can run to paragraphs.\nfunction capPromotedName(label: string): string {\n const chars = Array.from(label)\n if (chars.length <= IOS_PROMOTED_NAME_MAX) return label\n return chars.slice(0, IOS_PROMOTED_NAME_MAX - 1).join('') + '…'\n}\n\nfunction descendantCarriesLabel(node: any, label: string, ctx: WalkContext): boolean {\n for (const childKey of Object.keys(node)) {\n if (childKey.startsWith('@_') || childKey === '#text') continue\n const childVal = node[childKey]\n const children = Array.isArray(childVal) ? childVal : [childVal]\n for (const child of children) {\n if (!child || typeof child !== 'object') continue\n const attrs = collectAttrs(child)\n const childLabel = extractLabel(attrs, ctx.platform)\n if (\n childLabel !== undefined &&\n String(childLabel).trim() === label &&\n shouldEmit(normalizeRole(childKey, ctx.platform))\n ) {\n return true\n }\n if (descendantCarriesLabel(child, label, ctx)) return true\n }\n }\n return false\n}\n\nfunction walkNode(node: any, tagName: string, parentIndex: number | undefined, ctx: WalkContext): void {\n const attrs: Record<string, any> = {}\n // fast-xml-parser puts attributes with @_ prefix at the node level\n for (const key of Object.keys(node)) {\n if (key.startsWith('@_')) {\n attrs[key] = node[key]\n }\n }\n\n let role = normalizeRole(tagName, ctx.platform)\n let emit = shouldEmit(role)\n let promoted = false\n\n if (ctx.platform === 'ios') {\n if (\n ctx.screenReference === undefined &&\n (tagName === 'XCUIElementTypeApplication' || tagName === 'XCUIElementTypeWindow')\n ) {\n const reference = parseIosBounds(attrs)\n if (reference && reference.width > 0 && reference.height > 0) {\n ctx.screenReference = { width: reference.width, height: reference.height }\n }\n }\n if (\n !emit &&\n isIosAccessibleLabelledOther(tagName, attrs, ctx) &&\n !descendantCarriesLabel(node, String(attrs['@_label']).trim(), ctx)\n ) {\n const traits = attrs['@_traits']\n role = iosAccessibleOtherRole(typeof traits === 'string' ? traits : undefined)\n emit = true\n promoted = true\n }\n }\n\n // The index children reparent to: this node's own index if it is emitted, else the\n // nearest surviving ancestor passed down.\n let childParentIndex = parentIndex\n\n if (emit) {\n const rawLabel = extractLabel(attrs, ctx.platform)\n const label = promoted && rawLabel !== undefined ? capPromotedName(String(rawLabel)) : rawLabel\n const value = extractValue(attrs, ctx.platform)\n\n let bounds: { x: number; y: number; width: number; height: number } | undefined\n if (ctx.platform === 'android' && attrs['@_bounds']) {\n bounds = parseAndroidBounds(attrs['@_bounds'])\n } else if (ctx.platform === 'ios') {\n bounds = parseIosBounds(attrs)\n }\n\n const state = liftState(tagName, role, attrs, ctx.platform, bounds, ctx.viewport)\n const labels = liftLabels(attrs, ctx.platform)\n\n // Retain the raw platform attribute bag (prefix stripped, values stringified).\n const attributes: Record<string, string> = {}\n for (const key of Object.keys(attrs)) {\n attributes[key.slice(2)] = String(attrs[key])\n }\n\n const interim: InterimNode = {\n role,\n ...(label !== undefined ? { name: label } : {}),\n ...(value !== undefined ? { value } : {}),\n ...(parentIndex !== undefined ? { parentIndex } : {}),\n ...(bounds !== undefined ? { bounds } : {}),\n ...(Object.keys(state).length > 0 ? { state } : {}),\n ...(Object.keys(labels).length > 0 ? { labels } : {}),\n attributes,\n nativeType: tagName,\n }\n\n childParentIndex = ctx.nodes.length\n ctx.nodes.push(interim)\n }\n\n // Walk children\n for (const childKey of Object.keys(node)) {\n if (childKey.startsWith('@_') || childKey === '#text') continue\n const childVal = node[childKey]\n const children = Array.isArray(childVal) ? childVal : [childVal]\n for (const child of children) {\n if (child && typeof child === 'object') {\n walkNode(child, childKey, childParentIndex, ctx)\n }\n }\n }\n}\n\nexport function parseMobileSource(\n xml: string,\n platform: 'android' | 'ios',\n viewport?: { width: number; height: number },\n): ParsedMobileSource {\n // WDA writes a newline in an attribute as `&#10;`; numeric references are decoded on iOS\n // only, so a multi-line value is observed as typed (Android parsing is left as it was).\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n allowBooleanAttributes: true,\n preserveOrder: false,\n htmlEntities: platform === 'ios',\n })\n\n const parsed = parser.parse(xml)\n\n const ctx: WalkContext = {\n platform,\n nodes: [],\n viewport,\n ...(platform === 'ios' && viewport ? { screenReference: viewport } : {}),\n }\n\n // Find root element(s) to walk\n // Android: <hierarchy>...</hierarchy>\n // iOS: <AppiumAUT>...</AppiumAUT>\n const rootKeys = Object.keys(parsed).filter(k => !k.startsWith('?'))\n for (const rootKey of rootKeys) {\n const rootVal = parsed[rootKey]\n if (rootVal && typeof rootVal === 'object') {\n // Walk children of root container (hierarchy or AppiumAUT)\n for (const childKey of Object.keys(rootVal)) {\n if (childKey.startsWith('@_') || childKey === '#text') continue\n const childVal = rootVal[childKey]\n const children = Array.isArray(childVal) ? childVal : [childVal]\n for (const child of children) {\n if (child && typeof child === 'object') {\n walkNode(child, childKey, undefined, ctx)\n }\n }\n }\n }\n }\n\n return { nodes: ctx.nodes }\n}\n\n/**\n * Reconstruct the execute-time `lastRefs` record from the interim nodes plus the shared\n * builder's ref->node binding (D-01/D-03). The mobile adapters store this privately so\n * planner-ref -> live-node resolution survives the builder taking over ref minting. No\n * position lives anywhere: not here, not on the binding, not on ElementInfo (438 D-13).\n */\nexport function buildRefEntries(\n nodes: InterimNode[],\n binding: Record<string, RefBinding>,\n): Record<string, RefEntry> {\n const entries: Record<string, RefEntry> = {}\n for (const [ref, { index }] of Object.entries(binding)) {\n const node = nodes[index]\n if (!node) continue\n const rawInputType = node.attributes?.['input-type']\n entries[ref] = {\n role: node.role,\n ...(node.name !== undefined ? { name: node.name } : {}),\n ...(node.bounds !== undefined ? { bounds: node.bounds } : {}),\n ...(node.nativeType !== undefined ? { nativeType: node.nativeType } : {}),\n ...(node.value !== undefined ? { value: node.value } : {}),\n ...(node.state?.editable === true ? { editable: true } : {}),\n ...(rawInputType !== undefined && /^\\d+$/.test(rawInputType)\n ? { inputType: Number(rawInputType) }\n : {}),\n }\n }\n return entries\n}\n\n/**\n * Best-effort mobile scroll metadata (D-10). Unlike web — which reads the exact window\n * scroll offset and document content size — mobile page source exposes no true scroll\n * position, so this is a documented approximation, explicit and never silently precise:\n * contentWidth/contentHeight are the maximum element extent across all node bounds\n * (falling back to the viewport dimensions when no node carries bounds), and\n * offsetX/offsetY stay 0 (no reliable scroll-offset signal in the source).\n */\nexport function deriveMobileScroll(\n nodes: InterimNode[],\n viewport: { width: number; height: number },\n): { offsetX: number; offsetY: number; contentWidth: number; contentHeight: number } {\n let maxX = viewport.width\n let maxY = viewport.height\n let sawBounds = false\n for (const node of nodes) {\n if (!node.bounds) continue\n sawBounds = true\n maxX = Math.max(maxX, node.bounds.x + node.bounds.width)\n maxY = Math.max(maxY, node.bounds.y + node.bounds.height)\n }\n return {\n offsetX: 0,\n offsetY: 0,\n contentWidth: sawBounds ? maxX : viewport.width,\n contentHeight: sawBounds ? maxY : viewport.height,\n }\n}\n","export const ANDROID_ROLE_MAP: Record<string, string> = {\n 'android.widget.Button': 'button',\n 'android.widget.ImageButton': 'button',\n 'android.widget.EditText': 'textbox',\n 'android.widget.AutoCompleteTextView': 'textbox',\n 'android.widget.TextView': 'text',\n 'android.widget.CheckedTextView': 'text',\n 'android.widget.CheckBox': 'checkbox',\n 'android.widget.Switch': 'switch',\n 'android.widget.ImageView': 'image',\n 'android.widget.ListView': 'list',\n 'android.widget.ScrollView': 'scroll-area',\n 'android.widget.HorizontalScrollView': 'scroll-area',\n 'android.view.View': 'group',\n 'android.view.ViewGroup': 'group',\n 'android.widget.FrameLayout': 'group',\n 'android.widget.LinearLayout': 'group',\n 'android.widget.RelativeLayout': 'group',\n 'android.widget.SearchView': 'searchbox',\n 'android.widget.Spinner': 'combobox',\n 'android.widget.SeekBar': 'slider',\n 'android.widget.RadioButton': 'radio',\n 'android.widget.CompoundButton': 'button',\n 'android.widget.ToggleButton': 'button',\n 'android.widget.ProgressBar': 'progressbar',\n 'android.widget.Toolbar': 'toolbar',\n 'android.widget.TabWidget': 'tablist',\n 'android.webkit.WebView': 'webview',\n 'androidx.recyclerview.widget.RecyclerView': 'list',\n 'androidx.constraintlayout.widget.ConstraintLayout': 'group',\n 'androidx.appcompat.widget.Toolbar': 'toolbar',\n 'androidx.viewpager.widget.ViewPager': 'group',\n 'androidx.core.widget.NestedScrollView': 'scroll-area',\n 'android.widget.NumberPicker': 'spinbutton',\n 'android.widget.DatePicker': 'combobox',\n 'android.widget.TimePicker': 'combobox',\n 'android.widget.RatingBar': 'slider',\n 'android.widget.CalendarView': 'grid',\n 'android.widget.TabHost': 'tablist',\n 'com.google.android.material.chip.Chip': 'button',\n 'com.google.android.material.floatingactionbutton.FloatingActionButton': 'button',\n 'com.google.android.material.tabs.TabLayout': 'tablist',\n 'com.google.android.material.textfield.TextInputEditText': 'textbox',\n 'com.google.android.material.switchmaterial.SwitchMaterial': 'switch',\n 'com.google.android.material.checkbox.MaterialCheckBox': 'checkbox',\n}\n\nexport const IOS_ROLE_MAP: Record<string, string> = {\n 'XCUIElementTypeButton': 'button',\n 'XCUIElementTypeTextField': 'textbox',\n 'XCUIElementTypeSecureTextField': 'textbox',\n 'XCUIElementTypeStaticText': 'text',\n 'XCUIElementTypeTextView': 'text',\n 'XCUIElementTypeSwitch': 'switch',\n 'XCUIElementTypeSlider': 'slider',\n 'XCUIElementTypeImage': 'image',\n 'XCUIElementTypeCell': 'cell',\n 'XCUIElementTypeTable': 'list',\n 'XCUIElementTypeCollectionView': 'list',\n 'XCUIElementTypeScrollView': 'scroll-area',\n 'XCUIElementTypeOther': 'group',\n 'XCUIElementTypeGroup': 'group',\n 'XCUIElementTypeNavigationBar': 'navigation',\n 'XCUIElementTypeTabBar': 'tablist',\n 'XCUIElementTypeSearchField': 'searchbox',\n 'XCUIElementTypeCheckBox': 'checkbox',\n 'XCUIElementTypeLink': 'link',\n 'XCUIElementTypeAlert': 'alert',\n 'XCUIElementTypeWebView': 'webview',\n 'XCUIElementTypeApplication': 'application',\n 'XCUIElementTypeWindow': 'window',\n 'XCUIElementTypePicker': 'combobox',\n 'XCUIElementTypePickerWheel': 'pickerwheel',\n 'XCUIElementTypeSegmentedControl': 'tablist',\n 'XCUIElementTypeStepper': 'spinbutton',\n 'XCUIElementTypeDatePicker': 'combobox',\n 'XCUIElementTypeMenu': 'menu',\n 'XCUIElementTypeMenuItem': 'menuitem',\n 'XCUIElementTypeMenuButton': 'button',\n 'XCUIElementTypeToggle': 'switch',\n 'XCUIElementTypePopUpButton': 'combobox',\n 'XCUIElementTypeComboBox': 'combobox',\n 'XCUIElementTypeRadioButton': 'radio',\n 'XCUIElementTypeRadioGroup': 'group',\n 'XCUIElementTypeToolbar': 'toolbar',\n 'XCUIElementTypeProgressIndicator': 'progressbar',\n 'XCUIElementTypeActivityIndicator': 'progressbar',\n 'XCUIElementTypeColorWell': 'button',\n}\n\nexport const IOS_EDITABLE_TYPES: ReadonlySet<string> = new Set([\n 'XCUIElementTypeTextField',\n 'XCUIElementTypeSecureTextField',\n 'XCUIElementTypeSearchField',\n 'XCUIElementTypeTextView',\n])\n\nconst IOS_TRAIT_ROLE_PRECEDENCE: ReadonlyArray<[ReadonlyArray<string>, string]> = [\n [['SearchField'], 'searchbox'],\n [['Adjustable'], 'slider'],\n [['TabBar'], 'tablist'],\n [['Button', 'ToggleButton'], 'button'],\n [['Link'], 'link'],\n [['Header'], 'heading'],\n [['Image'], 'image'],\n [['StaticText', 'UpdatesFrequently', 'SummaryElement'], 'text'],\n]\n\n// WDA joins trait names in dictionary order, so the string is split rather than matched whole.\nexport function iosAccessibleOtherRole(traits: string | undefined): string {\n const names = new Set(\n (traits ?? '')\n .split(',')\n .map(t => t.trim())\n .filter(t => t.length > 0),\n )\n for (const [traitNames, role] of IOS_TRAIT_ROLE_PRECEDENCE) {\n if (traitNames.some(t => names.has(t))) return role\n }\n return 'button'\n}\n\nexport function normalizeRole(type: string, platform: 'android' | 'ios'): string {\n const map = platform === 'android' ? ANDROID_ROLE_MAP : IOS_ROLE_MAP\n const mapped = map[type]\n if (mapped) return mapped\n\n // Fallback: strip known prefixes and lowercase\n let fallback = type\n if (platform === 'ios') {\n fallback = fallback.replace(/^XCUIElementType/, '')\n } else {\n fallback = fallback\n .replace(/^android\\.widget\\./, '')\n .replace(/^android\\.view\\./, '')\n .replace(/^android\\.webkit\\./, '')\n .replace(/^androidx\\.[\\w.]+\\./, '')\n .replace(/^com\\.google\\.android\\.[\\w.]+\\./, '')\n .replace(/^com\\.android\\.[\\w.]+\\./, '')\n }\n return fallback.toLowerCase() || 'element'\n}\n","import type { Action } from '@vostride/agent-qa-runner'\nimport type { MobileRefMap } from './types.js'\n\nconst ACTIONS_WITHOUT_REF = new Set(['navigate', 'waitFor', 'delay', 'assert', 'scroll', 'swipe', 'pinch', 'multiTap'])\n\nexport class MobileElementResolver {\n constructor(private refs: MobileRefMap) {}\n\n resolve(ref: string): { role: string; name?: string; bounds: { x: number; y: number; width: number; height: number }; center: { x: number; y: number } } {\n const data = this.refs[ref]\n if (!data) {\n const available = Object.keys(this.refs).join(', ') || 'none'\n throw new Error(`Unknown ref \"${ref}\". Available refs: ${available}`)\n }\n\n if (!data.bounds) {\n throw new Error(`Ref \"${ref}\" (${data.role}${data.name ? ` \"${data.name}\"` : ''}) has no bounds for coordinate resolution`)\n }\n\n const center = {\n x: data.bounds.x + data.bounds.width / 2,\n y: data.bounds.y + data.bounds.height / 2,\n }\n\n return {\n role: data.role,\n name: data.name,\n bounds: data.bounds,\n center,\n }\n }\n\n resolveAction(action: Action): { bounds: { x: number; y: number; width: number; height: number }; center: { x: number; y: number } } | null {\n if (ACTIONS_WITHOUT_REF.has(action.type)) {\n // scroll/swipe may have optional ref\n if (('ref' in action) && typeof (action as { ref?: string }).ref === 'string') {\n const resolved = this.resolve((action as { ref: string }).ref)\n return { bounds: resolved.bounds, center: resolved.center }\n }\n return null\n }\n\n if ('ref' in action && typeof (action as { ref?: string }).ref === 'string') {\n const resolved = this.resolve((action as { ref: string }).ref)\n return { bounds: resolved.bounds, center: resolved.center }\n }\n\n return null\n }\n}\n","export const KEY_MAP: Record<string, string> = {\n Enter: '\\uE007',\n Tab: '\\uE004',\n Escape: '\\uE00C',\n Backspace: '\\uE003',\n Space: '\\uE00D',\n ArrowUp: '\\uE013',\n ArrowDown: '\\uE014',\n ArrowLeft: '\\uE012',\n ArrowRight: '\\uE011',\n}\n\nexport function computePinch(\n centerX: number, centerY: number,\n scale: number,\n startDistance = 100,\n): {\n finger1Start: { x: number; y: number }; finger1End: { x: number; y: number }\n finger2Start: { x: number; y: number }; finger2End: { x: number; y: number }\n} {\n const halfStart = startDistance / 2\n const halfEnd = (startDistance * scale) / 2\n\n return {\n finger1Start: { x: centerX - halfStart, y: centerY },\n finger1End: { x: centerX - halfEnd, y: centerY },\n finger2Start: { x: centerX + halfStart, y: centerY },\n finger2End: { x: centerX + halfEnd, y: centerY },\n }\n}\n\nexport function computeFingerPositions(\n centerX: number, centerY: number,\n fingers: number,\n spacing = 40,\n): { x: number; y: number }[] {\n if (fingers === 2) {\n return [\n { x: centerX - spacing / 2, y: centerY },\n { x: centerX + spacing / 2, y: centerY },\n ]\n }\n // 3 fingers: triangle arrangement\n return [\n { x: centerX, y: centerY - spacing / 2 },\n { x: centerX - spacing / 2, y: centerY + spacing / 2 },\n { x: centerX + spacing / 2, y: centerY + spacing / 2 },\n ]\n}\n\nexport function computeSwipe(\n centerX: number, centerY: number,\n direction: 'up' | 'down' | 'left' | 'right',\n distance: number,\n): { startX: number; startY: number; endX: number; endY: number } {\n switch (direction) {\n case 'up':\n return { startX: centerX, startY: centerY + distance / 2, endX: centerX, endY: centerY - distance / 2 }\n case 'down':\n return { startX: centerX, startY: centerY - distance / 2, endX: centerX, endY: centerY + distance / 2 }\n case 'left':\n return { startX: centerX + distance / 2, startY: centerY, endX: centerX - distance / 2, endY: centerY }\n case 'right':\n return { startX: centerX - distance / 2, startY: centerY, endX: centerX + distance / 2, endY: centerY }\n }\n}\n","import { existsSync } from 'node:fs'\nimport { dirname, resolve as resolvePath } from 'node:path'\n\nexport type MobilePlatform = 'android' | 'ios'\nexport type MobileTransport = 'local' | 'browserstack'\nexport type MobileAppState = 'preserve' | 'reset'\n\nexport type MobileSetupErrorCategory =\n | 'device-resolution'\n | 'appium-startup'\n | 'device-readiness'\n | 'adapter-load'\n | 'app-install'\n | 'app-launch'\n\nexport interface MobileSetupErrorOptions {\n category: MobileSetupErrorCategory\n message: string\n platform?: MobilePlatform\n targetName?: string\n deviceName?: string\n appId?: string\n cause?: unknown\n sourceTrace?: string[]\n}\n\nexport class MobileSetupError extends Error {\n readonly category: MobileSetupErrorCategory\n readonly platform?: MobilePlatform\n readonly targetName?: string\n readonly deviceName?: string\n readonly appId?: string\n readonly sourceTrace?: string[]\n override readonly cause?: unknown\n\n constructor(options: MobileSetupErrorOptions) {\n super(options.message)\n this.name = 'MobileSetupError'\n this.category = options.category\n this.platform = options.platform\n this.targetName = options.targetName\n this.deviceName = options.deviceName\n this.appId = options.appId\n this.sourceTrace = options.sourceTrace\n this.cause = options.cause\n }\n}\n\nexport interface ResolvedMobileDevice {\n name: string\n platform: MobilePlatform\n transport: MobileTransport\n match: Record<string, unknown>\n}\n\nexport interface ResolvedMobileAppInstall {\n path?: string\n browserstack?: string\n browserstackBaseDir?: string\n sourceTrace: Record<string, string>\n}\n\nexport interface ResolvedMobileApp {\n bundleId?: string\n appPackage?: string\n appActivity?: string\n deepLinkAppId?: string\n install?: ResolvedMobileAppInstall\n sourceTrace: Record<string, string>\n}\n\nexport interface ResolvedMobileRunConfig {\n platform: MobilePlatform\n targetName: string\n deviceName: string\n transport: MobileTransport\n device: ResolvedMobileDevice\n app: ResolvedMobileApp\n appState: MobileAppState\n appium: { url?: string; managed?: boolean }\n sourceTrace: string[]\n}\n\nexport interface ResolveMobileRunConfigInput {\n config: Record<string, any>\n targetName: string\n platform?: MobilePlatform\n explicitDeviceName?: string\n useDeviceName?: string\n appState?: MobileAppState\n localBindings?: {\n devices?: Record<string, Record<string, unknown>>\n apps?: Record<string, { path?: string; browserstack?: string }>\n filePath?: string\n } | null\n configFilePath?: string\n localConfigFilePath?: string\n appiumUrl?: string\n}\n\ninterface TargetEntry {\n platform?: string\n bundleId?: string\n appPackage?: string\n appActivity?: string\n app?: {\n path?: string\n browserstack?: string\n }\n device?: string\n}\n\ninterface DeviceProfile {\n platform?: string\n transport?: string\n match?: Record<string, unknown>\n}\n\nfunction isMobilePlatform(value: unknown): value is MobilePlatform {\n return value === 'android' || value === 'ios'\n}\n\nfunction isMobileTransport(value: unknown): value is MobileTransport {\n return value === 'local' || value === 'browserstack'\n}\n\nfunction asOptionalString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction isAbsoluteAppInstallValue(value: string): boolean {\n return value.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\n}\n\nfunction baseDirFor(filePath?: string): string {\n return filePath ? dirname(filePath) : process.cwd()\n}\n\nfunction setupError(\n message: string,\n input: ResolveMobileRunConfigInput,\n extras: Partial<Omit<MobileSetupErrorOptions, 'category' | 'message' | 'targetName'>> = {},\n): MobileSetupError {\n return new MobileSetupError({\n category: 'device-resolution',\n message,\n targetName: input.targetName,\n ...extras,\n })\n}\n\nfunction appInstallError(\n message: string,\n input: ResolveMobileRunConfigInput,\n extras: Partial<Omit<MobileSetupErrorOptions, 'category' | 'message' | 'targetName'>> = {},\n): MobileSetupError {\n return new MobileSetupError({\n category: 'app-install',\n message,\n targetName: input.targetName,\n ...extras,\n })\n}\n\nfunction chooseDeviceName(input: ResolveMobileRunConfigInput): { name?: string; source?: string } {\n const candidates = [\n ['explicitDeviceName', input.explicitDeviceName],\n ['use.device', input.useDeviceName],\n ] as const\n\n for (const [source, value] of candidates) {\n const name = asOptionalString(value)\n if (name) return { name, source }\n }\n\n return {}\n}\n\nfunction resolveAppField(\n field: 'bundleId' | 'appPackage' | 'appActivity',\n targetValue: unknown,\n deviceValue: unknown,\n targetName: string,\n deviceName: string,\n input: ResolveMobileRunConfigInput,\n): { value?: string; source?: string } {\n const targetString = asOptionalString(targetValue)\n const deviceString = asOptionalString(deviceValue)\n\n if (targetString && deviceString && targetString !== deviceString) {\n throw setupError(\n `Conflicting ${field} for mobile target \"${targetName}\" and device \"${deviceName}\": target has \"${targetString}\", device has \"${deviceString}\"`,\n input,\n {\n deviceName,\n appId: targetString,\n },\n )\n }\n\n if (targetString) {\n return {\n value: targetString,\n source: `registry.targets.${targetName}.${field}`,\n }\n }\n if (deviceString) {\n return {\n value: deviceString,\n source: `registry.devices.${deviceName}.match.${field}`,\n }\n }\n return {}\n}\n\nfunction resolveAppInstall(\n target: TargetEntry,\n input: ResolveMobileRunConfigInput,\n platform: MobilePlatform,\n deviceName: string,\n sourceTrace: string[],\n): ResolvedMobileAppInstall | undefined {\n const localApp = input.localBindings?.apps?.[input.targetName]\n const installSourceTrace: Record<string, string> = {}\n\n const localPath = asOptionalString(localApp?.path)\n const targetPath = asOptionalString(target.app?.path)\n const pathValue = localPath ?? targetPath\n const pathSource = localPath\n ? `agent-qa.local.yaml apps.${input.targetName}.path`\n : targetPath\n ? `agent-qa.config.yaml registry.targets.${input.targetName}.app.path`\n : undefined\n const pathBaseDir = localPath\n ? baseDirFor(input.localConfigFilePath ?? input.localBindings?.filePath)\n : targetPath\n ? baseDirFor(input.configFilePath)\n : undefined\n\n const localBrowserStack = asOptionalString(localApp?.browserstack)\n const targetBrowserStack = asOptionalString(target.app?.browserstack)\n const browserstackValue = localBrowserStack ?? targetBrowserStack\n const browserstackSource = localBrowserStack\n ? `agent-qa.local.yaml apps.${input.targetName}.browserstack`\n : targetBrowserStack\n ? `agent-qa.config.yaml registry.targets.${input.targetName}.app.browserstack`\n : undefined\n const browserstackBaseDir = localBrowserStack\n ? baseDirFor(input.localConfigFilePath ?? input.localBindings?.filePath)\n : targetBrowserStack\n ? baseDirFor(input.configFilePath)\n : undefined\n\n const install: ResolvedMobileAppInstall = { sourceTrace: installSourceTrace }\n\n if (pathValue) {\n if (isAbsoluteAppInstallValue(pathValue)) {\n throw appInstallError(`Configured app path must be relative: ${pathValue}`, input, {\n platform,\n deviceName,\n appId: pathValue,\n sourceTrace: [...sourceTrace, `app.path=${pathSource}`],\n })\n }\n const resolvedPath = resolvePath(pathBaseDir ?? process.cwd(), pathValue)\n if (!existsSync(resolvedPath)) {\n throw appInstallError(`Configured app path not found: ${resolvedPath}`, input, {\n platform,\n deviceName,\n appId: pathValue,\n sourceTrace: [...sourceTrace, `app.path=${pathSource}`],\n })\n }\n install.path = resolvedPath\n if (pathSource) {\n installSourceTrace['app.path'] = pathSource\n sourceTrace.push(`app.path=${pathSource}`)\n }\n }\n\n if (browserstackValue) {\n if (isAbsoluteAppInstallValue(browserstackValue)) {\n throw appInstallError(`Configured BrowserStack app value must be relative or a BrowserStack reference: ${browserstackValue}`, input, {\n platform,\n deviceName,\n appId: browserstackValue,\n sourceTrace: [...sourceTrace, `app.browserstack=${browserstackSource}`],\n })\n }\n install.browserstack = browserstackValue\n install.browserstackBaseDir = browserstackBaseDir\n if (browserstackSource) {\n installSourceTrace['app.browserstack'] = browserstackSource\n sourceTrace.push(`app.browserstack=${browserstackSource}`)\n }\n }\n\n return install.path || install.browserstack ? install : undefined\n}\n\nexport function resolveMobileRunConfig(input: ResolveMobileRunConfigInput): ResolvedMobileRunConfig {\n const targets = input.config.registry?.targets as Record<string, TargetEntry> | undefined\n const target = targets?.[input.targetName]\n if (!target) {\n const available = targets ? Object.keys(targets).join(', ') : 'none'\n throw setupError(\n `Target \"${input.targetName}\" not found in config. Available targets: ${available}`,\n input,\n )\n }\n\n const platformCandidate = input.platform ?? target.platform\n if (!isMobilePlatform(platformCandidate)) {\n throw setupError(\n `Target \"${input.targetName}\" is not a mobile target`,\n input,\n )\n }\n const platform = platformCandidate\n\n const appState = input.appState\n if (appState !== 'preserve' && appState !== 'reset') {\n throw setupError(\n 'use.mobile.appState is required for native mobile app targets and must be one of: preserve | reset',\n input,\n { platform },\n )\n }\n\n const chosenDevice = chooseDeviceName(input)\n if (!chosenDevice.name) {\n throw setupError(\n `No device specified for mobile target \"${input.targetName}\"`,\n input,\n { platform },\n )\n }\n const deviceName = chosenDevice.name\n\n const devices = input.config.registry?.devices as Record<string, DeviceProfile> | undefined\n const deviceProfile = devices?.[deviceName]\n if (!deviceProfile) {\n const available = devices ? Object.keys(devices).join(', ') : 'none'\n throw setupError(\n `Device \"${deviceName}\" not found in registry.devices. Available devices: ${available}`,\n input,\n { platform, deviceName },\n )\n }\n\n if (deviceProfile.platform !== platform) {\n throw setupError(\n `Device \"${deviceName}\" platform \"${deviceProfile.platform ?? 'unknown'}\" does not match target \"${input.targetName}\" platform \"${platform}\"`,\n input,\n { platform, deviceName },\n )\n }\n\n const transport = isMobileTransport(deviceProfile.transport) ? deviceProfile.transport : 'local'\n const localMatch = input.localBindings?.devices?.[deviceName] ?? null\n const mergedMatch = { ...(deviceProfile.match ?? {}), ...(localMatch ?? {}) }\n\n const appSourceTrace: Record<string, string> = {}\n const sourceTrace = [\n `target=registry.targets.${input.targetName}`,\n `platform=${platform}`,\n `device=${chosenDevice.source}:${deviceName}`,\n `appState=use.mobile.appState:${appState}`,\n ]\n\n let app: ResolvedMobileApp\n if (platform === 'android') {\n const appPackage = resolveAppField('appPackage', target.appPackage, mergedMatch.appPackage, input.targetName, deviceName, input)\n const appActivity = resolveAppField('appActivity', target.appActivity, mergedMatch.appActivity, input.targetName, deviceName, input)\n if (appPackage.source) appSourceTrace.appPackage = appPackage.source\n if (appActivity.source) appSourceTrace.appActivity = appActivity.source\n app = {\n appPackage: appPackage.value,\n appActivity: appActivity.value,\n deepLinkAppId: appPackage.value,\n sourceTrace: appSourceTrace,\n }\n if (appPackage.source) sourceTrace.push(`app.appPackage=${appPackage.source}`)\n if (appActivity.source) sourceTrace.push(`app.appActivity=${appActivity.source}`)\n } else {\n const bundleId = resolveAppField('bundleId', target.bundleId, mergedMatch.bundleId, input.targetName, deviceName, input)\n if (bundleId.source) appSourceTrace.bundleId = bundleId.source\n app = {\n bundleId: bundleId.value,\n deepLinkAppId: bundleId.value,\n sourceTrace: appSourceTrace,\n }\n if (bundleId.source) sourceTrace.push(`app.bundleId=${bundleId.source}`)\n }\n\n const install = resolveAppInstall(target, input, platform, deviceName, sourceTrace)\n if (install) {\n app.install = install\n }\n\n return {\n platform,\n targetName: input.targetName,\n deviceName,\n transport,\n device: {\n name: deviceName,\n platform,\n transport,\n match: mergedMatch,\n },\n app,\n appState,\n appium: {\n url: input.appiumUrl,\n managed: !input.appiumUrl,\n },\n sourceTrace,\n }\n}\n","import { existsSync } from 'node:fs'\nimport { dirname, join, parse, resolve } from 'node:path'\n\nexport type AppiumExecutableSource = 'local' | 'path'\n\nexport interface ResolvedAppiumExecutable {\n command: string\n source: AppiumExecutableSource\n}\n\nexport interface ResolveAppiumExecutableOptions {\n cwd?: string\n platform?: NodeJS.Platform\n exists?: (path: string) => boolean\n}\n\nexport function localAppiumBinaryNames(platform: NodeJS.Platform = process.platform): string[] {\n return platform === 'win32' ? ['appium.cmd', 'appium.exe', 'appium'] : ['appium']\n}\n\nexport function resolveAppiumExecutable(opts: ResolveAppiumExecutableOptions = {}): ResolvedAppiumExecutable {\n const exists = opts.exists ?? existsSync\n const names = localAppiumBinaryNames(opts.platform ?? process.platform)\n let current = resolve(opts.cwd ?? process.cwd())\n const root = parse(current).root\n\n while (true) {\n for (const name of names) {\n const candidate = join(current, 'node_modules', '.bin', name)\n if (exists(candidate)) {\n return { command: candidate, source: 'local' }\n }\n }\n\n if (current === root) break\n current = dirname(current)\n }\n\n return { command: 'appium', source: 'path' }\n}\n\nexport function formatAppiumInstallGuidance(): string {\n return 'Install Appium locally with `npm install -D appium` (or `pnpm add -D appium` / `yarn add -D appium`). If you prefer a machine-wide setup, use `npm install -g appium`.'\n}\n","import { scrollerSetSwipeSignal } from '@vostride/agent-qa-runner'\nimport type { Direction, DocumentScrollOffsets, SwipeSignal } from '@vostride/agent-qa-runner'\n\n// 2026-10-08 (436-23): the WebView swipe is judged over identified, on-screen scrollers, and a\n// frame in view makes the read null (review WR-20, IN-32 · D-25).\n\n/** One WebView scroller with a structural identity: `document`, or a flat-tree path plus tag, id and class. */\nexport interface IdentifiedScrollOffsets extends DocumentScrollOffsets {\n id: string\n}\n\n/**\n * A WebDriver `execute` function body. It answers `null` when a frame (`iframe`, `frame`, `embed`,\n * `object`, `fencedframe`) with positive area intersects the viewport, because a swipe over it\n * moves content the page cannot measure. Otherwise it answers the document scroller first (id\n * `document`), then every on-screen element scroller in the document and its open shadow roots,\n * in tree order. A body whose overflow propagates to the viewport is not a member. Nothing is\n * written to the page: ids derive from structure alone. Closed shadow roots are unreachable.\n */\nexport const WEBVIEW_SCROLLERS_SCRIPT: string =\n 'var d = document, w = window, s = d.scrollingElement || d.documentElement;'\n + 'var vw = w.innerWidth, vh = w.innerHeight;'\n + 'var frames = { IFRAME: 1, FRAME: 1, EMBED: 1, OBJECT: 1, FENCEDFRAME: 1 };'\n + 'var sc = function (v) { return v === \"auto\" || v === \"scroll\" || v === \"overlay\"; };'\n + 'var inView = function (el) {'\n + ' var r = el.getBoundingClientRect();'\n + ' return Math.min(r.right, vw) > Math.max(r.left, 0) && Math.min(r.bottom, vh) > Math.max(r.top, 0);'\n + '};'\n + 'var rs = getComputedStyle(d.documentElement);'\n + 'var bodyPropagates = rs.overflowX === \"visible\" && rs.overflowY === \"visible\";'\n + 'var out = [{ id: \"document\", x: w.scrollX, y: w.scrollY,'\n + ' maxX: s.scrollWidth - s.clientWidth, maxY: s.scrollHeight - s.clientHeight }];'\n + 'var stack = [{ el: d.documentElement, path: \"0\" }];'\n + 'while (stack.length > 0) {'\n + ' var item = stack.pop(), el = item.el, path = item.path;'\n + ' var kids = [], i;'\n + ' if (el.shadowRoot) { for (i = 0; i < el.shadowRoot.children.length; i++) kids.push({ el: el.shadowRoot.children[i], path: path + \"/s\" + i }); }'\n + ' for (i = 0; i < el.children.length; i++) kids.push({ el: el.children[i], path: path + \"/\" + i });'\n + ' for (i = kids.length - 1; i >= 0; i--) stack.push(kids[i]);'\n + ' if (frames[String(el.tagName).toUpperCase()] && inView(el)) return null;'\n + ' if (el === s || el === d.documentElement || (el === d.body && bodyPropagates)) continue;'\n + ' var mx = el.scrollWidth - el.clientWidth, my = el.scrollHeight - el.clientHeight;'\n + ' if (!(mx > 0 || my > 0)) continue;'\n + ' var st = getComputedStyle(el);'\n + ' var sx = mx > 0 && sc(st.overflowX), sy = my > 0 && sc(st.overflowY);'\n + ' if ((!sx && !sy) || !inView(el)) continue;'\n + ' out.push({ id: path + \"|\" + String(el.localName) + \"#\" + (el.getAttribute(\"id\") || \"\") + \".\" + (el.getAttribute(\"class\") || \"\"),'\n + ' x: el.scrollLeft, y: el.scrollTop, maxX: sx ? mx : 0, maxY: sy ? my : 0 });'\n + '}'\n + 'return out;'\n\nfunction memberOf(value: unknown): IdentifiedScrollOffsets | undefined {\n if (!value || typeof value !== 'object') return undefined\n const { id, x, y, maxX, maxY } = value as Record<string, unknown>\n if (typeof id !== 'string' || id.length === 0) return undefined\n const offsets = [x, y, maxX, maxY]\n if (!offsets.every((n) => typeof n === 'number' && Number.isFinite(n))) return undefined\n return { id, x, y, maxX, maxY } as IdentifiedScrollOffsets\n}\n\nfunction byId(members: readonly unknown[]): Map<string, IdentifiedScrollOffsets> | undefined {\n if (members.length === 0) return undefined\n const map = new Map<string, IdentifiedScrollOffsets>()\n for (const value of members) {\n const member = memberOf(value)\n if (!member || map.has(member.id)) return undefined\n map.set(member.id, member)\n }\n return map\n}\n\n/** A non-empty array of members with string ids, finite offsets and no duplicate id; else undefined. */\nexport function parseWebViewScrollers(raw: unknown): IdentifiedScrollOffsets[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const map = byId(raw)\n return map ? [...map.values()] : undefined\n}\n\n/**\n * Before and after are paired by id. The same membership is judged by the scroller-set rule; a\n * changed membership is `moved` only when a member present in both reads moved, else `unknown`.\n */\nexport function webViewSwipeSignal(\n direction: Direction,\n before: readonly IdentifiedScrollOffsets[] | undefined,\n after: readonly IdentifiedScrollOffsets[] | undefined,\n): SwipeSignal {\n if (!before || !after) return 'unknown'\n const b = byId(before)\n const a = byId(after)\n if (!b || !a) return 'unknown'\n const common = [...b.keys()].filter((id) => a.has(id))\n const signal = scrollerSetSwipeSignal(\n direction,\n common.map((id) => b.get(id)!),\n common.map((id) => a.get(id)!),\n )\n const same = common.length === b.size && common.length === a.size\n if (same) return signal\n return signal === 'moved' ? 'moved' : 'unknown'\n}\n","import path from 'node:path'\nimport { DEFAULT_AGENT_QA_AUTH_STATES_DIR } from '../runtime-paths.js'\nimport { AuthStateNameSchema, TargetNameSchema } from './schema.js'\n\nexport type AuthStateTargetPlatform = 'web' | 'android' | 'ios'\n\nexport interface ResolveAuthStatePathsInput {\n configDir: string\n authStateDir?: string\n targetName: string\n stateName: string\n target?: {\n platform: AuthStateTargetPlatform\n }\n platform?: AuthStateTargetPlatform\n}\n\nexport interface ResolvedAuthStatePaths {\n targetName: string\n stateName: string\n rootDir: string\n targetDir: string\n payloadPath: string\n metadataPath: string\n}\n\nexport interface ResolveAuthStateRootInput {\n configDir: string\n authStateDir?: string\n}\n\nconst MOBILE_AUTH_STATE_ERROR = [\n 'auth state is only supported for web targets.',\n 'For native mobile, use use.mobile.appState: preserve when keeping app data between sessions.',\n 'App-state preservation is broader than auth and does not export generic secure-storage/keychain tokens.',\n].join(' ')\n\nfunction assertInsideRoot(rootDir: string, filePath: string): void {\n const relativePath = path.relative(rootDir, filePath)\n if (!relativePath || relativePath.startsWith('..') || path.isAbsolute(relativePath)) {\n throw new Error(`Resolved auth-state path escapes auth-state directory: ${filePath}`)\n }\n}\n\nexport function resolveAuthStateRoot(input: ResolveAuthStateRootInput): string {\n const { configDir, authStateDir } = input\n const configuredDir = authStateDir ?? DEFAULT_AGENT_QA_AUTH_STATES_DIR\n if (configuredDir.trim().length === 0) {\n throw new Error('authState.dir must be a non-empty path')\n }\n return path.isAbsolute(configuredDir)\n ? path.resolve(configuredDir)\n : path.resolve(configDir, configuredDir)\n}\n\nexport function resolveAuthStatePaths(input: ResolveAuthStatePathsInput): ResolvedAuthStatePaths {\n const targetName = TargetNameSchema.parse(input.targetName)\n const stateName = AuthStateNameSchema.parse(input.stateName)\n const platform = input.target?.platform ?? input.platform\n\n if (platform !== 'web') {\n throw new Error(MOBILE_AUTH_STATE_ERROR)\n }\n\n const rootDir = resolveAuthStateRoot({\n configDir: input.configDir,\n authStateDir: input.authStateDir,\n })\n const targetDir = path.join(rootDir, targetName)\n const payloadPath = path.join(targetDir, `${stateName}.json`)\n const metadataPath = path.join(targetDir, `${stateName}.meta.json`)\n\n assertInsideRoot(rootDir, payloadPath)\n assertInsideRoot(rootDir, metadataPath)\n\n return {\n targetName,\n stateName,\n rootDir,\n targetDir,\n payloadPath,\n metadataPath,\n }\n}\n","import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nexport const DEFAULT_AGENT_QA_RUNTIME_DIR = '.agent-qa'\nexport const DEFAULT_AGENT_QA_ARTIFACTS_DIR = '.agent-qa/artifacts'\nexport const DEFAULT_AGENT_QA_CACHE_DIR = '.agent-qa/cache'\nexport const DEFAULT_AGENT_QA_AUTH_STATES_DIR = '.agent-qa/auth-states'\nexport const DEFAULT_AGENT_QA_SCREENSHOTS_DIR = '.agent-qa/artifacts/screenshots'\nexport const DEFAULT_AGENT_QA_VIDEOS_DIR = '.agent-qa/artifacts/videos'\nexport const DEFAULT_AGENT_QA_RUNS_DB_PATH = '.agent-qa/runs.db'\nexport const LEGACY_AGENT_QA_DASHBOARD_DB_PATH = '.agent-qa/dashboard.db'\n\n/**\n * The runs database a config names, without migrating anything: the configured path, else the\n * default, else a legacy dashboard.db nothing has renamed yet. The writer's resolver renames that\n * legacy file on top of this; the CLI reader binds only the configured or default path.\n */\nexport function locateRunsDbPath(configDir: string, configuredDbPath?: string): string {\n const configured = configuredDbPath?.trim()\n if (configured) return resolve(configDir, configured)\n const defaultPath = resolve(configDir, DEFAULT_AGENT_QA_RUNS_DB_PATH)\n const legacyPath = resolve(configDir, LEGACY_AGENT_QA_DASHBOARD_DB_PATH)\n return !existsSync(defaultPath) && existsSync(legacyPath) ? legacyPath : defaultPath\n}\n","import { randomUUID } from 'node:crypto'\nimport type { Dirent } from 'node:fs'\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { AuthStateMetadataSchema, TargetNameSchema, type AuthStateMetadata } from './schema.js'\nimport { resolveAuthStatePaths, resolveAuthStateRoot, type ResolvedAuthStatePaths } from './resolver.js'\n\nexport interface WriteAuthStateFilesInput {\n payload: unknown\n metadata: AuthStateMetadata\n}\n\nexport interface ListAuthStateMetadataInput {\n configDir: string\n authStateDir?: string\n targetName?: string\n}\n\nexport interface RemoveAuthStateFilesInput {\n configDir: string\n authStateDir?: string\n targetName: string\n stateName: string\n target?: Parameters<typeof resolveAuthStatePaths>[0]['target']\n platform?: Parameters<typeof resolveAuthStatePaths>[0]['platform']\n}\n\nexport interface RemoveAuthStateTargetInput {\n configDir: string\n authStateDir?: string\n targetName: string\n target?: Parameters<typeof resolveAuthStatePaths>[0]['target']\n platform?: Parameters<typeof resolveAuthStatePaths>[0]['platform']\n}\n\nfunction assertMetadataMatches(paths: ResolvedAuthStatePaths, metadata: AuthStateMetadata): void {\n if (metadata.target !== paths.targetName) {\n throw new Error(`Auth-state metadata target \"${metadata.target}\" does not match resolved target \"${paths.targetName}\"`)\n }\n if (metadata.name !== paths.stateName) {\n throw new Error(`Auth-state metadata name \"${metadata.name}\" does not match resolved state \"${paths.stateName}\"`)\n }\n}\n\nasync function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n const serialized = `${JSON.stringify(value, null, 2)}\\n`\n const directory = path.dirname(filePath)\n const tempPath = path.join(directory, `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`)\n\n await mkdir(directory, { recursive: true })\n try {\n await writeFile(tempPath, serialized, { mode: 0o600 })\n await rename(tempPath, filePath)\n } catch (error) {\n await rm(tempPath, { force: true }).catch(() => undefined)\n throw error\n }\n}\n\nexport async function readAuthStateMetadata(paths: ResolvedAuthStatePaths): Promise<AuthStateMetadata> {\n let raw: string\n try {\n raw = await readFile(paths.metadataPath, 'utf-8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Auth-state metadata not found: ${paths.metadataPath}`)\n }\n throw error\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw new Error(`Invalid auth-state metadata JSON: ${paths.metadataPath}`)\n }\n\n const result = AuthStateMetadataSchema.safeParse(parsed)\n if (!result.success) {\n throw new Error(`Invalid auth-state metadata: ${result.error.issues.map(issue => issue.message).join('; ')}`)\n }\n\n assertMetadataMatches(paths, result.data)\n return result.data\n}\n\nexport async function writeAuthStateFiles(\n paths: ResolvedAuthStatePaths,\n input: WriteAuthStateFilesInput,\n): Promise<void> {\n const metadata = AuthStateMetadataSchema.parse(input.metadata)\n assertMetadataMatches(paths, metadata)\n\n await writeJsonAtomic(paths.payloadPath, input.payload)\n await writeJsonAtomic(paths.metadataPath, metadata)\n}\n\nexport async function listAuthStateMetadata(\n input: ListAuthStateMetadataInput,\n): Promise<AuthStateMetadata[]> {\n const rootDir = resolveAuthStateRoot({\n configDir: input.configDir,\n authStateDir: input.authStateDir,\n })\n const targetFilter = input.targetName ? TargetNameSchema.parse(input.targetName) : undefined\n\n let targetEntries: Dirent<string>[]\n try {\n targetEntries = await readdir(rootDir, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return []\n }\n throw error\n }\n\n const metadata: AuthStateMetadata[] = []\n for (const targetEntry of targetEntries) {\n if (!targetEntry.isDirectory()) continue\n const targetNameResult = TargetNameSchema.safeParse(targetEntry.name)\n if (!targetNameResult.success) continue\n const targetName = targetNameResult.data\n if (targetFilter && targetName !== targetFilter) continue\n\n let stateEntries: Dirent<string>[]\n const targetDir = path.join(rootDir, targetName)\n try {\n stateEntries = await readdir(targetDir, { withFileTypes: true })\n } catch {\n continue\n }\n\n for (const stateEntry of stateEntries) {\n if (!stateEntry.isFile() || !stateEntry.name.endsWith('.meta.json')) continue\n const stateName = stateEntry.name.slice(0, -'.meta.json'.length)\n const paths = (() => {\n try {\n return resolveAuthStatePaths({\n configDir: input.configDir,\n authStateDir: input.authStateDir,\n targetName,\n stateName,\n platform: 'web',\n })\n } catch {\n return null\n }\n })()\n if (!paths) continue\n\n try {\n const entry = await readAuthStateMetadata(paths)\n metadata.push(entry)\n } catch {\n continue\n }\n }\n }\n\n return metadata.sort((a, b) => {\n const targetOrder = a.target.localeCompare(b.target)\n return targetOrder === 0 ? a.name.localeCompare(b.name) : targetOrder\n })\n}\n\nexport async function removeAuthStateFiles(input: RemoveAuthStateFilesInput): Promise<void> {\n const paths = resolveAuthStatePaths(input)\n await rm(paths.payloadPath, { force: true })\n await rm(paths.metadataPath, { force: true })\n}\n\nexport async function removeAuthStateTarget(input: RemoveAuthStateTargetInput): Promise<void> {\n const paths = resolveAuthStatePaths({\n ...input,\n stateName: 'placeholder',\n })\n await rm(paths.targetDir, { recursive: true, force: true })\n}\n","import { readFile } from 'node:fs/promises'\nimport { readAuthStateMetadata } from './store.js'\nimport {\n resolveAuthStatePaths,\n type AuthStateTargetPlatform,\n type ResolvedAuthStatePaths,\n} from './resolver.js'\n\nexport interface ResolveAuthStateForRunInput {\n configDir: string\n authStateDir?: string\n targetName: string\n stateName: string\n target?: {\n platform: AuthStateTargetPlatform\n }\n platform?: AuthStateTargetPlatform\n}\n\nexport interface ResolvedAuthStateForRun {\n version: number\n kind: 'web'\n targetName: string\n stateName: string\n capturedAt: string\n storageStatePath: string\n}\n\nfunction createAuthStateReadError(targetName: string, stateName: string): Error {\n return new Error(\n `Auth state \"${stateName}\" for target \"${targetName}\" was not found or could not be read. ` +\n `Run agent-qa auth-state capture --target ${targetName} --name ${stateName}.`,\n )\n}\n\nasync function assertPayloadReadable(paths: ResolvedAuthStatePaths): Promise<void> {\n const raw = await readFile(paths.payloadPath, 'utf-8')\n JSON.parse(raw)\n}\n\nexport async function resolveAuthStateForRun(\n input: ResolveAuthStateForRunInput,\n): Promise<ResolvedAuthStateForRun> {\n const paths = resolveAuthStatePaths(input)\n\n try {\n const metadata = await readAuthStateMetadata(paths)\n await assertPayloadReadable(paths)\n return {\n version: metadata.version,\n kind: metadata.kind,\n targetName: metadata.target,\n stateName: metadata.name,\n capturedAt: metadata.capturedAt,\n storageStatePath: paths.payloadPath,\n }\n } catch {\n throw createAuthStateReadError(paths.targetName, paths.stateName)\n }\n}\n","// Auth-state hook env plumbing moved to @vostride/agent-qa-runner (Phase 363 D-06) so the\n// hook orchestration (runner) and DockerHookExecutor (runner-local) share it without importing\n// core. Re-exported here so core's other auth-state consumers keep resolving through the core\n// barrel until they re-point.\n\nexport {\n AUTH_STATE_HOOK_JSON_ENV,\n AUTH_STATE_HOOK_STORAGE_STATE_PATH_ENV,\n AUTH_STATE_HOOK_WORKSPACE_DIR,\n AUTH_STATE_HOOK_STORAGE_STATE_FILENAME,\n AUTH_STATE_HOOK_CONTAINER_STORAGE_STATE_PATH,\n isReservedAuthStateHookEnvKey,\n stripReservedAuthStateHookEnv,\n buildAuthStateHookEnv,\n} from '@vostride/agent-qa-runner'\n","import { randomUUID } from 'node:crypto'\nimport {\n readFile,\n writeFile,\n mkdir,\n unlink,\n rename,\n rm,\n lstat,\n realpath,\n readlink,\n} from 'node:fs/promises'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { homedir } from 'node:os'\nimport type { AuthCredential, AuthStore } from './types.js'\n\nexport function getAuthPath(): string {\n const xdg = process.env.XDG_DATA_HOME\n if (xdg) return join(xdg, 'agent-qa', 'auth.json')\n return join(homedir(), '.agent-qa', 'auth.json')\n}\n\nfunction isMissingFile(error: unknown): boolean {\n return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'\n}\n\nasync function isSymlink(authPath: string): Promise<boolean> {\n return lstat(authPath).then(\n stats => stats.isSymbolicLink(),\n (error: unknown) => {\n if (isMissingFile(error)) return false\n throw error\n },\n )\n}\n\n// A symlinked auth.json keeps its link: the file it points at is the one replaced, the same rule\n// ConfigManager.writeTarget applies to the config file.\nasync function authWriteTarget(authPath: string): Promise<string> {\n if (!(await isSymlink(authPath))) return authPath\n try {\n return await realpath(authPath)\n } catch (error) {\n if (!isMissingFile(error)) throw error\n return resolve(dirname(authPath), await readlink(authPath))\n }\n}\n\nasync function writeStoreAtomic(authPath: string, store: AuthStore): Promise<void> {\n const target = await authWriteTarget(authPath)\n const directory = dirname(target)\n const tempPath = join(directory, `.${basename(target)}.${process.pid}.${randomUUID()}.tmp`)\n await mkdir(directory, { recursive: true })\n try {\n await writeFile(tempPath, JSON.stringify(store, null, 2), { mode: 0o600 })\n await rename(tempPath, target)\n } catch (error) {\n await rm(tempPath, { force: true }).catch(() => undefined)\n throw error\n }\n}\n\nexport async function readAuth(path?: string): Promise<AuthStore> {\n const authPath = path ?? getAuthPath()\n try {\n const data = await readFile(authPath, 'utf-8')\n return JSON.parse(data) as AuthStore\n } catch {\n return {}\n }\n}\n\nexport async function writeAuth(\n provider: string,\n credential: AuthCredential,\n path?: string,\n): Promise<void> {\n const authPath = path ?? getAuthPath()\n const store = await readAuth(authPath)\n store[provider] = credential\n await writeStoreAtomic(authPath, store)\n}\n\nexport async function removeAuth(provider: string, path?: string): Promise<void> {\n const authPath = path ?? getAuthPath()\n const store = await readAuth(authPath)\n delete store[provider]\n if (Object.keys(store).length === 0 && !(await isSymlink(authPath))) {\n try {\n await unlink(authPath)\n } catch {\n // file already gone\n }\n return\n }\n await writeStoreAtomic(authPath, store)\n}\n\nexport async function getCredential(\n provider: string,\n path?: string,\n): Promise<AuthCredential | null> {\n const store = await readAuth(path)\n return store[provider] ?? null\n}\n","import type { LLMModelAdapter, OAuthTokens } from './types.js'\n\nexport type DashboardAuthMode = 'browser-poll' | 'manual-code'\n\nexport interface DashboardAuthMetadata {\n mode: DashboardAuthMode\n buttonLabel?: string\n}\n\nexport interface StartAuthContext {\n configName: string\n callbackUrl?: string\n}\n\nexport interface StartAuthResult {\n authorizeUrl: string\n sessionState?: unknown\n waitForTokens?: Promise<OAuthTokens>\n cleanup?: () => void\n}\n\nexport interface ExchangeCodeContext {\n code: string\n sessionState: unknown\n}\n\nexport interface CreateAuthFetchContext {\n getTokens: () => Promise<OAuthTokens>\n onRefreshed: (tokens: OAuthTokens) => Promise<void>\n}\n\nexport interface LLMAuthProviderPlugin {\n providerId: string\n credentialProviderId: string\n label: string\n modelAdapter: LLMModelAdapter\n dashboardAuth: DashboardAuthMetadata\n startAuth?: (ctx: StartAuthContext) => Promise<StartAuthResult>\n exchangeCode?: (ctx: ExchangeCodeContext) => Promise<OAuthTokens>\n createAuthFetch: (ctx: CreateAuthFetchContext) => typeof globalThis.fetch\n}\n\nconst plugins = new Map<string, LLMAuthProviderPlugin>()\n\nfunction validatePlugin(plugin: LLMAuthProviderPlugin): void {\n if (!plugin.providerId.trim()) {\n throw new Error('LLM auth plugin providerId is required')\n }\n if (!plugin.credentialProviderId.trim()) {\n throw new Error(`LLM auth plugin \"${plugin.providerId}\" credentialProviderId is required`)\n }\n if (!plugin.label.trim()) {\n throw new Error(`LLM auth plugin \"${plugin.providerId}\" label is required`)\n }\n}\n\nexport function registerLLMAuthProviderPlugin(plugin: LLMAuthProviderPlugin): void {\n validatePlugin(plugin)\n if (plugins.has(plugin.providerId)) {\n throw new Error(`LLM auth provider plugin \"${plugin.providerId}\" is already registered`)\n }\n plugins.set(plugin.providerId, plugin)\n}\n\nexport function registerLLMAuthProviderPlugins(providerPlugins: LLMAuthProviderPlugin[]): void {\n for (const plugin of providerPlugins) {\n registerLLMAuthProviderPlugin(plugin)\n }\n}\n\nexport function getLLMAuthProviderPlugin(providerId: string): LLMAuthProviderPlugin | undefined {\n return plugins.get(providerId)\n}\n\nexport function listLLMAuthProviderPlugins(): LLMAuthProviderPlugin[] {\n return [...plugins.values()]\n}\n\nexport function clearLLMAuthProviderPlugins(): void {\n plugins.clear()\n}\n","import { getLLMAuthProviderPlugin, type LLMAuthProviderPlugin } from './plugin-registry.js'\nimport { getCredential, writeAuth } from './store.js'\nimport type { AuthCredential, LLMProviderMode, OAuthTokens, ResolvedLLMAuth } from './types.js'\n\ninterface LLMAuthConfig {\n provider: LLMProviderMode | string\n model: string\n baseURL?: string\n providerHeaders?: Record<string, string>\n}\n\nconst SUBSCRIPTION_AUTH_PACKAGE = '@vostride/agent-qa-subscription-auth'\n\nexport const PUBLIC_PROVIDER_API_HOSTS: readonly string[] = Object.freeze([\n 'api.openai.com',\n 'api.anthropic.com',\n])\n\nfunction onPublicProviderApi(baseURL: string | undefined): boolean {\n if (typeof baseURL !== 'string' || !URL.canParse(baseURL)) return false\n return PUBLIC_PROVIDER_API_HOSTS.includes(new URL(baseURL).hostname)\n}\n\nfunction missingMessage(configName: string, provider: string, plugin?: LLMAuthProviderPlugin): string {\n if (plugin) {\n return `Sign in to \"${plugin.label}\" for the \"${configName}\" config: agent-qa auth login --config ${configName}`\n }\n\n const setKey = `agent-qa auth set --config ${configName} --type api-key`\n switch (provider) {\n case 'gemini':\n return `Save a Gemini API key for the \"${configName}\" config: ${setKey}`\n case 'openai-compatible':\n return `Save an API key for the \"${configName}\" config: ${setKey}`\n case 'anthropic-compatible':\n return `Save an API key for the \"${configName}\" config: ${setKey} (or --type bearer-token)`\n case 'openai-subscription':\n case 'anthropic-subscription':\n return `Provider \"${provider}\" needs the subscription-auth plugin: npm install -D ${SUBSCRIPTION_AUTH_PACKAGE}, and declare it under plugins.auth in agent-qa.config.yaml`\n default:\n return `Provider \"${provider}\" requires an auth plugin.`\n }\n}\n\nfunction unauthenticated(configName: string, provider: 'openai-compatible' | 'anthropic-compatible'): ResolvedLLMAuth {\n return {\n kind: 'unauthenticated',\n credentialKey: configName,\n provider,\n optional: true,\n message: 'Testing without a saved credential.',\n }\n}\n\nfunction isCompatibleProvider(provider: string): provider is 'openai-compatible' | 'anthropic-compatible' {\n return provider === 'openai-compatible' || provider === 'anthropic-compatible'\n}\n\nfunction usesApiKey(\n provider: string,\n plugin?: LLMAuthProviderPlugin,\n): provider is 'openai-compatible' | 'anthropic-compatible' | 'gemini' {\n return !plugin && (provider === 'openai-compatible' || provider === 'anthropic-compatible' || provider === 'gemini')\n}\n\nfunction unusableCredential(\n configName: string,\n provider: string,\n plugin?: LLMAuthProviderPlugin,\n): ResolvedLLMAuth {\n return isCompatibleProvider(provider)\n ? unauthenticated(configName, provider)\n : missing(configName, provider, plugin)\n}\n\nfunction missing(configName: string, provider: string, plugin?: LLMAuthProviderPlugin): ResolvedLLMAuth {\n return {\n kind: 'missing',\n credentialKey: configName,\n provider,\n required: true,\n message: missingMessage(configName, provider, plugin),\n }\n}\n\nfunction getOAuthTokens(\n configName: string,\n expectedProvider: string,\n authPath?: string,\n): () => Promise<OAuthTokens> {\n return async () => {\n const credential = await getCredential(configName, authPath)\n if (credential?.type !== 'oauth' || credential.provider !== expectedProvider) {\n throw new Error(`Expected ${expectedProvider} OAuth credential for ${configName}`)\n }\n return credential.tokens\n }\n}\n\nfunction writeRefreshedOAuth(\n configName: string,\n expectedProvider: string,\n authPath?: string,\n): (tokens: OAuthTokens) => Promise<void> {\n return async (tokens) => {\n const current = await getCredential(configName, authPath)\n if (current?.type !== 'oauth' || current.provider !== expectedProvider) {\n throw new Error(`Expected ${expectedProvider} OAuth credential for ${configName}`)\n }\n await writeAuth(configName, { ...current, tokens }, authPath)\n }\n}\n\nfunction authFetch(\n configName: string,\n plugin: LLMAuthProviderPlugin,\n credential: Extract<AuthCredential, { type: 'oauth' }>,\n authPath?: string,\n): ResolvedLLMAuth {\n const expectedProvider = plugin.credentialProviderId\n const getTokens = getOAuthTokens(configName, expectedProvider, authPath)\n const onRefreshed = writeRefreshedOAuth(configName, expectedProvider, authPath)\n\n return {\n kind: 'auth-fetch',\n credentialKey: configName,\n provider: plugin.providerId,\n modelAdapter: plugin.modelAdapter,\n fetch: plugin.createAuthFetch({ getTokens, onRefreshed }),\n expires: credential.tokens.expires,\n }\n}\n\nexport async function resolveLLMAuth(\n configName: string,\n llmConfig: LLMAuthConfig,\n authPath?: string,\n): Promise<ResolvedLLMAuth> {\n const credential = await getCredential(configName, authPath)\n const plugin = getLLMAuthProviderPlugin(llmConfig.provider)\n\n if (!credential) {\n // 2026-10-20 (445-16, D-41): a keyless config on the public provider API cannot run.\n if (isCompatibleProvider(llmConfig.provider) && !onPublicProviderApi(llmConfig.baseURL)) {\n return unauthenticated(configName, llmConfig.provider)\n }\n return missing(configName, llmConfig.provider, plugin)\n }\n\n if (credential.type === 'api') {\n if (credential.provider !== llmConfig.provider) {\n return unusableCredential(configName, llmConfig.provider, plugin)\n }\n if (!usesApiKey(llmConfig.provider, plugin)) {\n return missing(configName, llmConfig.provider, plugin)\n }\n return {\n kind: 'api-key',\n credentialKey: configName,\n provider: llmConfig.provider,\n apiKey: credential.key,\n }\n }\n\n if (credential.type === 'bearer') {\n if (credential.provider !== llmConfig.provider || llmConfig.provider !== 'anthropic-compatible') {\n return unusableCredential(configName, llmConfig.provider, plugin)\n }\n return {\n kind: 'bearer-token',\n credentialKey: configName,\n provider: 'anthropic-compatible',\n token: credential.token,\n }\n }\n\n if (credential.type === 'oauth') {\n if (plugin) {\n if (credential.provider !== plugin.credentialProviderId) {\n return missing(configName, llmConfig.provider, plugin)\n }\n return authFetch(configName, plugin, credential, authPath)\n }\n return unusableCredential(configName, llmConfig.provider)\n }\n\n return missing(configName, llmConfig.provider, plugin)\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\nexport type PluginDeclarationLike = {\n package?: string\n path?: string\n}\n\n/**\n * One filesystem path, rendered as the string a PERSON reads (395-28 · CR-03).\n *\n * `declarationLabel` below makes this disposition for a path the loader COMPOSED from the person's\n * own config. This is the same disposition for a path the loader merely FOUND — a manifest location,\n * or a path inside text Node's loader wrote. Inside `baseDir` it renders relative, because that is\n * the route the person recognizes from their own project; anywhere else it renders as a fixed\n * placeholder, because a `../../../..` chain out of the project is neither shorter nor safer than\n * the absolute path it replaces.\n */\nfunction personFacingPath(candidate: string, baseDir: string): string {\n let raw = candidate\n if (raw.startsWith('file://')) {\n try {\n raw = fileURLToPath(raw)\n } catch {\n return '<path>'\n }\n }\n const fromBase = relative(baseDir, raw)\n if (fromBase === '' || fromBase.startsWith('..') || isAbsolute(fromBase)) return '<path>'\n return fromBase\n}\n\n/**\n * An absolute path INSIDE prose, anchored so a slash in a word is not one (395-28 · CR-03).\n *\n * WHY ANCHORED. The obvious shape — \"any run of non-space characters containing a separator\" —\n * strips `and/or` and the person's own declared `plugins/local-auth.js` right along with the paths,\n * and a failure message that has lost its own diagnosis is a different defect from the one being\n * closed, not a fix for it. So a separator counts as the START of a path only when a boundary comes\n * first: the start of the string, whitespace, a quote, or an opening bracket. The `file://` form is\n * matched too, because that is the form Node's ESM loader quotes.\n *\n * The boundary is CAPTURED rather than looked behind, so adjacent paths separated by one space each\n * keep their own boundary available to the next match.\n */\nconst ABSOLUTE_PATH_IN_TEXT = /(^|[\\s'\"`([<])((?:file:\\/\\/)?(?:[A-Za-z]:)?[\\\\/][^\\s'\"`)\\]>]*)/g\n\nfunction stripAbsolutePaths(text: string, baseDir: string): string {\n return text.replace(\n ABSOLUTE_PATH_IN_TEXT,\n (_match, boundary: string, candidate: string) =>\n `${boundary}${personFacingPath(candidate, baseDir)}`,\n )\n}\n\nexport function findPackageJson(packageName: string, baseDir: string): string | null {\n let current = resolve(baseDir)\n while (true) {\n const candidate = resolve(current, 'node_modules', ...packageName.split('/'), 'package.json')\n if (existsSync(candidate)) return candidate\n\n const parent = dirname(current)\n if (parent === current) return null\n current = parent\n }\n}\n\nexport function exportTargetFromPackageJson(pkg: Record<string, unknown>): string | null {\n const exportsField = pkg.exports\n if (typeof exportsField === 'string') return exportsField\n if (exportsField && typeof exportsField === 'object') {\n const rootExport = (exportsField as Record<string, unknown>)['.'] ?? exportsField\n if (typeof rootExport === 'string') return rootExport\n if (rootExport && typeof rootExport === 'object') {\n const conditions = rootExport as Record<string, unknown>\n if (typeof conditions.import === 'string') return conditions.import\n if (typeof conditions.default === 'string') return conditions.default\n if (typeof conditions.require === 'string') return conditions.require\n }\n }\n if (typeof pkg.module === 'string') return pkg.module\n if (typeof pkg.main === 'string') return pkg.main\n return null\n}\n\n/**\n * A third party's `package.json` this resolver could not read as JSON (395-24 · WR-11).\n *\n * POSITION, NEVER CONTENT — the F-01 discipline, on a JSON channel. The unguarded\n * `JSON.parse(readFileSync(...))` below threw Node's own `SyntaxError`, and that error's text quotes\n * a FRAGMENT OF THE FILE back (`Unexpected token ... in JSON at position N`, and on newer V8 an\n * excerpt of the offending line). The bytes belong to a package in `node_modules`, not to the\n * person's own committed file, which is why the verifier filed it a warning rather than an F-01\n * member — but it is the same mechanism, and this file is where the phase put the one producer.\n *\n * NO `cause`, for `PluginNotInstalledError`'s reason: an `Error` carrying a `cause` is serialized by\n * `util.inspect` on roads this project has already been burned by, and the cause here is exactly the\n * `SyntaxError` whose bytes must not travel.\n *\n * POSITION IS NOT THE SAME AS AN ABSOLUTE PATH (395-28 · CR-03, secondary). `findPackageJson`\n * returns an absolute path, and the sentence used to interpolate it straight — handing the person a\n * route through their own filesystem to say something a project-relative route says just as well.\n * The `declarationKey`/`declarationLabel` split applies one type over: the TYPED FIELD keeps the\n * absolute path, because callers use it to open the file, and the SENTENCE renders through\n * `personFacingPath`, because that is what a person reads.\n */\nexport class PluginPackageManifestError extends Error {\n readonly packageJsonPath: string\n\n constructor(packageJsonPath: string, baseDir: string) {\n super(\n `Plugin package manifest ${personFacingPath(packageJsonPath, baseDir)} could not be read `\n + `as JSON.`,\n )\n this.name = 'PluginPackageManifestError'\n this.packageJsonPath = packageJsonPath\n }\n}\n\nexport function resolvePackageImportFromBase(packageName: string, baseDir: string): string | null {\n const packageJsonPath = findPackageJson(packageName, baseDir)\n if (!packageJsonPath) return null\n\n let pkg: Record<string, unknown>\n try {\n pkg = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as Record<string, unknown>\n } catch {\n // THROW, RATHER THAN RETURN null. `null` here means \"no export target found, try the loader's\n // own resolution\" — a legitimate outcome for a package whose manifest parsed fine. Returning it\n // for an UNREADABLE manifest would send an installed-but-corrupt package down the\n // `require.resolve` fallback and out as \"not installed\", which is WR-05's misnaming reached\n // from a second direction.\n throw new PluginPackageManifestError(packageJsonPath, baseDir)\n }\n const target = exportTargetFromPackageJson(pkg)\n if (!target || !target.startsWith('.')) return null\n return pathToFileURL(resolve(dirname(packageJsonPath), target)).href\n}\n\nexport function packageDeclarationValue(declaration: PluginDeclarationLike): string {\n return typeof declaration.package === 'string' ? declaration.package.trim() : ''\n}\n\nexport function pathDeclarationValue(declaration: PluginDeclarationLike): string {\n return typeof declaration.path === 'string' ? declaration.path.trim() : ''\n}\n\n/**\n * The INTERNAL identity of a declaration — a dedup map key, and nothing a person reads.\n *\n * The absolute path and the `package:`/`path:` discriminator prefix are both correct HERE: two\n * declarations naming the same file by different relative routes must collide in\n * `loadedDeclarations`, and a package named `foo` must not collide with a file named `foo`. Use\n * `declarationLabel` for anything that reaches a message (395-24 · WR-07).\n */\nexport function declarationKey(declaration: PluginDeclarationLike, baseDir: string): string {\n const packageName = packageDeclarationValue(declaration)\n if (packageName) return `package:${packageName}`\n return `path:${resolve(baseDir, pathDeclarationValue(declaration))}`\n}\n\n/**\n * The PERSON-FACING name of a declaration (395-24 · WR-07).\n *\n * `declarationKey`'s value was being interpolated straight into the loaders' own error sentences —\n * `Auth plugin \"path:/Users/someone/work/app/plugins/thing.js\" must export …` — which hands a person\n * an absolute path out of their own filesystem and an internal discriminator prefix that means\n * nothing to them. `PluginNotInstalledError` already names declarations correctly (it composes from\n * the DECLARATION, which is the person's own one-line config entry); this brings its neighbours to\n * the same discipline while leaving the map key alone, because the map key's absoluteness is its job.\n *\n * A path OUTSIDE `baseDir` renders as declared rather than as a `../../..` chain — the point is a\n * string the person recognizes from their config, not a shorter one.\n */\nexport function declarationLabel(declaration: PluginDeclarationLike, baseDir: string): string {\n const packageName = packageDeclarationValue(declaration)\n if (packageName) return packageName\n\n const declared = pathDeclarationValue(declaration)\n if (!isAbsolute(declared)) return declared\n const fromBase = relative(baseDir, declared)\n return fromBase === '' || fromBase.startsWith('..') ? declared : fromBase\n}\n\nexport type PluginDeclarationKind = 'auth' | 'provider'\n\n/**\n * A plugin the project's own config DECLARES and the project does not have (395-21 · F-05).\n *\n * THE MEASUREMENT THAT PRODUCED THIS TYPE. `agent-qa init --platform web` — the default,\n * non-interactive road — writes `plugins.auth: [{ package: \"@vostride/agent-qa-subscription-auth\" }]`\n * and a `package.json` naming that package, then tells the person to fetch it. Until they do, every\n * verb that resolves the config with plugin loading enabled dies on a bare `require.resolve`:\n *\n * Framework error: Cannot find module '@vostride/agent-qa-subscription-auth'\n * Require stack:\n * - /path/to/agent-qa.config.yaml\n *\n * That is Node's loader talking about its own internals — a \"Require stack\" naming a YAML file as\n * if it were a module — to a person whose actual next step is one install command that init itself\n * had already printed. The failure is real and must stay a failure; what changes is that it names\n * the package and the remedy instead of an import stack.\n *\n * ONE PRODUCER, BOTH MEMBERS. `loadLLMAuthPlugins` and `loadProviderPlugins` carried the identical\n * bare resolve-and-import, and this project's recurring failure mode is a guard placed on the member\n * a verifier happened to find while its sibling stays open (388/390/392/395-18). Both go through\n * `importDeclaredPluginModule` below.\n */\n/**\n * The npm package-name charset, anchored (395-24 · WR-06).\n *\n * WHY A GATE AT ALL. The sentence below composes the declaration's `package` string into\n * `npm install <that string>` — a COMMAND LINE THE CLI TELLS A PERSON TO RUN — and the schema behind\n * that string is `z.string().trim().min(1)` with no charset restriction whatsoever. It is not RCE:\n * the config is the person's own file, and nothing here executes anything. It is a channel round 4\n * created in which a string from a data file becomes a runnable command, and a person who pastes a\n * suggested command rarely re-reads it. So the runnable form is offered only for a name that\n * actually IS an npm name, and every other declaration gets the same remedy stated as prose.\n *\n * RETUNE NOTE. This is npm's own published name grammar as of 2026-08: optional `@scope/` prefix,\n * then lowercase letters, digits, and `-._~`. It deliberately does NOT accept uppercase (npm has\n * rejected uppercase in new names since 2017) — a legacy uppercase package still gets a correct\n * message, just without the composed command. If a future registry widens the grammar, widen THIS\n * constant; do not add a second check beside the producer.\n */\nconst NPM_PACKAGE_NAME = /^(?:@[a-z0-9-._~]+\\/)?[a-z0-9-._~]+$/\n\nexport class PluginNotInstalledError extends Error {\n readonly pluginKind: PluginDeclarationKind\n readonly pluginPackage: string | null\n readonly pluginPath: string | null\n\n constructor(declaration: PluginDeclarationLike, kind: PluginDeclarationKind) {\n const label = kind === 'auth' ? 'Auth' : 'Provider'\n const packageName = packageDeclarationValue(declaration)\n const pluginPath = pathDeclarationValue(declaration)\n const remedy = NPM_PACKAGE_NAME.test(packageName)\n ? `Install it with your package manager (for example: npm install ${packageName}), or remove `\n + `the plugins.${kind} entry that declares it.`\n : `Install it with your package manager, or remove the plugins.${kind} entry that declares it.`\n // NO `cause`, EVER (395-16 · D-395-16-A). The wrapped error carries a require stack of absolute\n // paths, and an `Error` with a `cause` is serialized by `util.inspect` on the roads this project\n // has already been burned by. The remedy is composed from the DECLARATION, which is the\n // person's own one-line config entry, and from nothing the loader saw.\n super(\n packageName\n ? `${label} plugin package \"${packageName}\" is declared in agent-qa.config.yaml but is not `\n + `installed. ${remedy}`\n : `${label} plugin file \"${pluginPath}\" is declared in agent-qa.config.yaml but could not be `\n + `loaded. Check that the path is correct and the file exists, or remove the `\n + `plugins.${kind} entry that declares it.`,\n )\n this.name = 'PluginNotInstalledError'\n this.pluginKind = kind\n this.pluginPackage = packageName === '' ? null : packageName\n this.pluginPath = pluginPath === '' ? null : pluginPath\n }\n}\n\nfunction isModuleResolutionFailure(err: unknown): boolean {\n const code = (err as { code?: unknown } | null)?.code\n return code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND'\n}\n\n/**\n * A plugin package that IS installed and could not be loaded (395-24 · WR-05).\n *\n * THE MISNAMING THIS TYPE ENDS. `isModuleResolutionFailure` answers `MODULE_NOT_FOUND` /\n * `ERR_MODULE_NOT_FOUND`, and Node raises those codes for a resolution failure ANYWHERE in the\n * import graph — including inside the plugin's own body, when the plugin's own transitive dependency\n * is missing or its `exports` target points at a file that is not there. The doc comment above the\n * importer claimed only the plugin's own RUNTIME throws pass through untouched, and that was true of\n * runtime throws and false of resolution failures one level down. The consequence a person met was\n * `… is declared in agent-qa.config.yaml but is not installed. Install it with npm install <pkg>` —\n * for a package sitting in their `node_modules` right then. They install what they already have,\n * nothing changes, and the message has actively misdirected them.\n *\n * The distinguishing fact is not the error's code but the FILESYSTEM: `findPackageJson` either\n * located the package under a `node_modules` on the way up from `baseDir`, or it did not.\n *\n * The underlying failure travels as TEXT, not as `cause`, for `PluginNotInstalledError`'s reason.\n */\nexport class PluginLoadFailedError extends Error {\n readonly pluginKind: PluginDeclarationKind\n readonly pluginPackage: string\n\n constructor(packageName: string, kind: PluginDeclarationKind, underlying: string) {\n const label = kind === 'auth' ? 'Auth' : 'Provider'\n super(\n `${label} plugin package \"${packageName}\" is installed but failed to load: ${underlying}. `\n + `This is a fault in the plugin or in its own dependencies, not a missing install.`,\n )\n this.name = 'PluginLoadFailedError'\n this.pluginKind = kind\n this.pluginPackage = packageName\n }\n}\n\n/**\n * The underlying failure's FIRST LINE, with the person's filesystem taken out of it.\n *\n * THE FIRST-LINE REDUCTION IS TRUE OF CJS AND INSUFFICIENT. CJS `MODULE_NOT_FOUND` puts its\n * `Require stack:` — a list of absolute paths out of the person's own filesystem — inside `.message`\n * itself, not only on `.stack`, and dropping every line after the first removes that list. The first\n * line is also the diagnostically useful part: it names the specifier that could not be resolved,\n * which is what a person needs to know which dependency their plugin is missing. Both of those\n * remain true. What was false was the implied converse — that the first line is therefore CLEAN.\n *\n * THE DIALECT THIS FILE ACTUALLY USES SAYS OTHERWISE (395-28 · CR-03). `importDeclaredPluginModule`\n * calls `await import(...)`, so the ESM loader is the only loader it reaches, and ESM writes its\n * paths INTO the first line rather than under it. Measured on Node v24.10.0:\n *\n * Cannot find module 'file:///abs/path/node_modules/@f/p/missing-entry.js' imported from\n * /abs/path/packages/core/src/plugin-loader-util.ts\n *\n * — two absolute paths, on one line, out of the person's filesystem. So the reduction is kept and a\n * SECOND, dialect-independent step is added: strip the absolute paths from whatever survives. That\n * covers CJS's remaining `Require stack` entries if a first line ever carries one, and it covers the\n * ESM form this file takes every time. `resolutionFailureFor` already holds `baseDir`; nothing new\n * is plumbed to reach it.\n *\n * `instanceof Error` rather than a cast, for validate.ts's reason (WR-04): a thrown non-Error must\n * still produce a string.\n */\nfunction messageOf(err: unknown, baseDir: string): string {\n const text = err instanceof Error ? err.message : String(err)\n return stripAbsolutePaths(text.split('\\n', 1)[0] ?? '', baseDir)\n}\n\n/**\n * Translate a module-resolution failure into the error that names what is actually wrong.\n *\n * A PATH declaration keeps `PluginNotInstalledError` — its sentence is already about a file that\n * could not be loaded and says to check the path, which is the right thing to say either way.\n */\nfunction resolutionFailureFor(\n declaration: PluginDeclarationLike,\n baseDir: string,\n kind: PluginDeclarationKind,\n err: unknown,\n): Error {\n const packageName = packageDeclarationValue(declaration)\n if (packageName && findPackageJson(packageName, baseDir) !== null) {\n return new PluginLoadFailedError(packageName, kind, messageOf(err, baseDir))\n }\n return new PluginNotInstalledError(declaration, kind)\n}\n\n/**\n * Resolve and import one declared plugin, answering the person when the module is not there.\n *\n * ONLY module-resolution failures are translated, and only for a package the filesystem says is\n * ABSENT. A plugin that IS installed rethrows as `PluginLoadFailedError` (resolution fault inside\n * its own graph) or untouched (its own runtime throw) — disguising either as \"not installed\" would\n * send the person to install something they already have.\n */\nexport async function importDeclaredPluginModule<T>(\n declaration: PluginDeclarationLike,\n baseDir: string,\n kind: PluginDeclarationKind,\n): Promise<T> {\n let specifier: string\n try {\n specifier = resolveModuleSpecifier(declaration, baseDir)\n } catch (err) {\n if (isModuleResolutionFailure(err)) throw resolutionFailureFor(declaration, baseDir, kind, err)\n throw err\n }\n\n try {\n return await import(specifier) as T\n } catch (err) {\n if (isModuleResolutionFailure(err)) throw resolutionFailureFor(declaration, baseDir, kind, err)\n throw err\n }\n}\n\nexport function resolveModuleSpecifier(declaration: PluginDeclarationLike, baseDir: string): string {\n const packageName = packageDeclarationValue(declaration)\n if (packageName) {\n const packageImport = resolvePackageImportFromBase(packageName, baseDir)\n if (packageImport) return packageImport\n\n const parentUrl = pathToFileURL(resolve(baseDir, 'agent-qa.config.yaml')).href\n try {\n const resolveImport = import.meta.resolve as (specifier: string, parent?: string) => string\n return resolveImport(packageName, parentUrl)\n } catch {\n const require = createRequire(resolve(baseDir, 'agent-qa.config.yaml'))\n return pathToFileURL(require.resolve(packageName)).href\n }\n }\n\n const pluginPath = pathDeclarationValue(declaration)\n const absolutePath = isAbsolute(pluginPath)\n ? pluginPath\n : resolve(baseDir, pluginPath)\n return pathToFileURL(absolutePath).href\n}\n","import { registerLLMAuthProviderPlugins, type LLMAuthProviderPlugin } from './plugin-registry.js'\nimport {\n declarationKey,\n declarationLabel,\n importDeclaredPluginModule,\n packageDeclarationValue,\n pathDeclarationValue,\n} from '../plugin-loader-util.js'\n\nexport type AuthPluginDeclaration =\n | { package: string; path?: never }\n | { path: string; package?: never }\n\nexport interface AuthPluginBundle {\n providers: LLMAuthProviderPlugin[]\n}\n\nexport interface LoadLLMAuthPluginsOptions {\n baseDir?: string\n}\n\ntype AuthPluginFactory = () => AuthPluginBundle | Promise<AuthPluginBundle>\ntype AuthPluginModule = {\n createSubscriptionAuthPlugin?: AuthPluginFactory\n createAuthPlugin?: AuthPluginFactory\n default?: AuthPluginFactory | AuthPluginBundle | AuthPluginModule\n providers?: LLMAuthProviderPlugin[]\n}\n\nconst loadedDeclarations = new Set<string>()\n\nasync function resolvePluginBundle(module: AuthPluginModule, source: string): Promise<AuthPluginBundle> {\n if (typeof module.createSubscriptionAuthPlugin === 'function') {\n return await module.createSubscriptionAuthPlugin()\n }\n if (typeof module.createAuthPlugin === 'function') {\n return await module.createAuthPlugin()\n }\n if (typeof module.default === 'function') {\n return await module.default()\n }\n if (module.default && typeof module.default === 'object') {\n const defaultModule = module.default as AuthPluginModule\n if (typeof defaultModule.createSubscriptionAuthPlugin === 'function') {\n return await defaultModule.createSubscriptionAuthPlugin()\n }\n if (typeof defaultModule.createAuthPlugin === 'function') {\n return await defaultModule.createAuthPlugin()\n }\n }\n if (module.default && typeof module.default === 'object' && Array.isArray(module.default.providers)) {\n return { providers: module.default.providers }\n }\n if (Array.isArray(module.providers)) {\n return { providers: module.providers }\n }\n throw new Error(`Auth plugin \"${source}\" must export createSubscriptionAuthPlugin(), createAuthPlugin(), default, or providers.`)\n}\n\nfunction validateDeclaration(declaration: AuthPluginDeclaration): void {\n const packageName = packageDeclarationValue(declaration)\n const pluginPath = pathDeclarationValue(declaration)\n\n if (packageName && pluginPath) {\n throw new Error('Auth plugin declaration must specify either package or path, not both.')\n }\n if (!packageName && !pluginPath) {\n throw new Error('Auth plugin declaration must specify package or path.')\n }\n}\n\nexport async function loadLLMAuthPlugins(\n declarations: AuthPluginDeclaration[] | undefined,\n options: LoadLLMAuthPluginsOptions = {},\n): Promise<LLMAuthProviderPlugin[]> {\n if (!declarations?.length) return []\n const baseDir = options.baseDir ?? process.cwd()\n const loadedProviders: LLMAuthProviderPlugin[] = []\n\n for (const declaration of declarations) {\n validateDeclaration(declaration)\n const key = declarationKey(declaration, baseDir)\n if (loadedDeclarations.has(key)) continue\n\n // A DECLARED PLUGIN THE PROJECT DOES NOT HAVE IS ANSWERED, NOT STACK-DUMPED (395-21 · F-05).\n // The product's own `init --platform web` declares the subscription-auth package before the\n // person has installed it, so this is the first thing a fresh project meets on `agent-qa run`.\n // It is still a failure — the plugin genuinely is not there — and it now names the package and\n // the install step instead of Node's require stack.\n const module = await importDeclaredPluginModule<AuthPluginModule>(declaration, baseDir, 'auth')\n // THE MAP KEY IS NOT THE PERSON'S NAME FOR IT (395-24 · WR-07). `key` is `path:/abs/route/to.js`\n // — absolute so two relative routes to one file collide in `loadedDeclarations`, prefixed so a\n // package cannot collide with a file. Neither fact belongs in a sentence a person reads, and\n // `resolvePluginBundle`'s \"must export …\" message is one.\n const bundle = await resolvePluginBundle(module, declarationLabel(declaration, baseDir))\n\n registerLLMAuthProviderPlugins(bundle.providers)\n loadedDeclarations.add(key)\n loadedProviders.push(...bundle.providers)\n }\n\n return loadedProviders\n}\n\nexport function clearLoadedLLMAuthPluginModules(): void {\n loadedDeclarations.clear()\n}\n","import { randomBytes, createHash } from 'node:crypto'\n\nexport function generatePKCE(): { verifier: string; challenge: string } {\n const verifier = randomBytes(32).toString('base64url')\n const challenge = createHash('sha256').update(verifier).digest('base64url')\n return { verifier, challenge }\n}\n\nexport function generateState(): string {\n return randomBytes(16).toString('hex')\n}\n","import type { AuthProvider, OAuthTokens, TokenRefreshFn } from './types.js'\n\nexport interface CreateAuthFetchOptions {\n provider: AuthProvider\n getTokens: () => Promise<OAuthTokens>\n refreshTokens: TokenRefreshFn\n onTokensRefreshed: (tokens: OAuthTokens) => Promise<void>\n headerTransform?: (headers: Headers, tokens: OAuthTokens) => void\n urlTransform?: (url: string) => string\n}\n\nexport function createAuthFetch(options: CreateAuthFetchOptions): typeof globalThis.fetch {\n const { provider, getTokens, refreshTokens, onTokensRefreshed, headerTransform, urlTransform } =\n options\n\n return async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {\n let tokens = await getTokens()\n\n if (tokens.expires < Date.now()) {\n tokens = await refreshTokens(provider, tokens.refresh)\n await onTokensRefreshed(tokens)\n }\n\n // Build headers without creating a Request (avoids Node duplex stream issue)\n const headers = new Headers()\n if (input instanceof Request) {\n input.headers.forEach((value, key) => { headers.set(key, value) })\n }\n if (init?.headers) {\n if (init.headers instanceof Headers) {\n init.headers.forEach((value, key) => { headers.set(key, value) })\n } else if (Array.isArray(init.headers)) {\n for (const [key, value] of init.headers) {\n if (value !== undefined) headers.set(key, String(value))\n }\n } else {\n for (const [key, value] of Object.entries(init.headers)) {\n if (value !== undefined) headers.set(key, String(value))\n }\n }\n }\n\n // Strip existing auth headers\n headers.delete('authorization')\n headers.delete('x-api-key')\n\n // Inject Bearer token\n headers.set('Authorization', `Bearer ${tokens.access}`)\n\n if (headerTransform) {\n headerTransform(headers, tokens)\n }\n\n // Extract URL\n let url: string\n if (typeof input === 'string') url = input\n else if (input instanceof URL) url = input.toString()\n else url = input.url\n\n if (urlTransform) {\n url = urlTransform(url)\n }\n\n const response = await globalThis.fetch(url, {\n ...init,\n headers,\n })\n\n if (!response.ok) {\n const respBody = await response.text()\n return new Response(respBody, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n })\n }\n\n return response\n }\n}\n","import {\n declarationKey,\n declarationLabel,\n importDeclaredPluginModule,\n packageDeclarationValue,\n pathDeclarationValue,\n} from '../plugin-loader-util.js'\n\nexport type ProviderPluginDeclaration =\n | { package: string; path?: never }\n | { path: string; package?: never }\n\nexport interface ProviderPluginDescriptor {\n id: string\n label: string\n adapter: (transport: unknown, modelId: string) => unknown\n authModes: string[]\n needsBaseURL?: boolean\n subscription?: boolean\n credentialOptional?: boolean\n modelAdapter?: string\n baseURLPlaceholder?: string\n defaultModel?: string\n}\n\nexport interface LoadProviderPluginsOptions {\n baseDir?: string\n}\n\ntype ProviderPluginModule = {\n default?: unknown\n providers?: unknown\n [key: string]: unknown\n}\n\nconst loadedDeclarations = new Set<string>()\nlet warnedFirstParty = false\n\nfunction warnFirstPartyProviderPlugins(): void {\n if (warnedFirstParty) return\n console.warn(\n '[agent-qa] plugins.providers modules run in-process with full Node access and can read credentials or screenshots. Use first-party provider plugins only until the container sandbox exists.',\n )\n warnedFirstParty = true\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction isProviderDescriptorCandidate(value: unknown): boolean {\n return isRecord(value) && (\n 'id' in value ||\n 'label' in value ||\n 'adapter' in value ||\n 'authModes' in value\n )\n}\n\nfunction assertProviderDescriptor(value: unknown, source: string): asserts value is ProviderPluginDescriptor {\n if (!isRecord(value)) {\n throw new Error(`Provider plugin \"${source}\" exported a descriptor that is not an object.`)\n }\n if (typeof value.id !== 'string' || !value.id.trim()) {\n throw new Error(`Provider plugin \"${source}\" descriptor id is required.`)\n }\n if (typeof value.label !== 'string' || !value.label.trim()) {\n throw new Error(`Provider plugin \"${source}\" descriptor label is required.`)\n }\n if (typeof value.adapter !== 'function') {\n throw new Error(`Provider plugin \"${source}\" descriptor adapter is required.`)\n }\n if (!Array.isArray(value.authModes) || !value.authModes.every((mode) => typeof mode === 'string')) {\n throw new Error(`Provider plugin \"${source}\" descriptor authModes must be a string array.`)\n }\n}\n\nfunction extractProvidersArray(value: unknown, source: string): ProviderPluginDescriptor[] | null {\n if (!isRecord(value) || !Array.isArray(value.providers)) return null\n for (const descriptor of value.providers) {\n assertProviderDescriptor(descriptor, source)\n }\n return value.providers as ProviderPluginDescriptor[]\n}\n\nfunction extractDescriptors(module: ProviderPluginModule, source: string): ProviderPluginDescriptor[] {\n const defaultProviders = extractProvidersArray(module.default, source)\n if (defaultProviders) return defaultProviders\n\n if (isProviderDescriptorCandidate(module.default)) {\n assertProviderDescriptor(module.default, source)\n return [module.default]\n }\n\n const namedProviders = extractProvidersArray(module, source)\n if (namedProviders) return namedProviders\n\n const namedDescriptors: ProviderPluginDescriptor[] = []\n for (const [name, value] of Object.entries(module)) {\n if (name === 'default' || name === 'providers') continue\n if (!isProviderDescriptorCandidate(value)) continue\n assertProviderDescriptor(value, source)\n namedDescriptors.push(value)\n }\n if (namedDescriptors.length > 0) return namedDescriptors\n\n throw new Error(`Provider plugin \"${source}\" must export a provider descriptor or providers array.`)\n}\n\nfunction validateDeclaration(declaration: ProviderPluginDeclaration): void {\n const packageName = packageDeclarationValue(declaration)\n const pluginPath = pathDeclarationValue(declaration)\n\n if (packageName && pluginPath) {\n throw new Error('Provider plugin declaration must specify either package or path, not both.')\n }\n if (!packageName && !pluginPath) {\n throw new Error('Provider plugin declaration must specify package or path.')\n }\n}\n\nexport async function loadProviderPlugins(\n declarations: ProviderPluginDeclaration[] | undefined,\n options: LoadProviderPluginsOptions = {},\n): Promise<ProviderPluginDescriptor[]> {\n if (!declarations?.length) return []\n\n warnFirstPartyProviderPlugins()\n\n const baseDir = options.baseDir ?? process.cwd()\n const loadedProviders: ProviderPluginDescriptor[] = []\n\n for (const declaration of declarations) {\n validateDeclaration(declaration)\n const key = declarationKey(declaration, baseDir)\n if (loadedDeclarations.has(key)) continue\n\n // THE SIBLING OF THE AUTH ROAD, hardened in the same pass (395-21 · F-05). `plugins.providers`\n // is not what the default scaffold declares, but it is the identical bare resolve-and-import\n // one directory over, and a class fixed only on the member a verifier happened to drive is how\n // this project has re-opened the same defect three rounds running.\n const module = await importDeclaredPluginModule<ProviderPluginModule>(declaration, baseDir, 'provider')\n // THE SIBLING OF THE AUTH ROAD'S WR-07 FIX, applied in the same pass for this file's own stated\n // reason: `extractDescriptors` and `assertProviderDescriptor` both interpolate this string into\n // person-facing sentences, and the map key's absolute `path:` form has no business in one.\n const descriptors = extractDescriptors(module, declarationLabel(declaration, baseDir))\n\n loadedDeclarations.add(key)\n loadedProviders.push(...descriptors)\n }\n\n return loadedProviders\n}\n\nexport function clearLoadedProviderPluginModules(): void {\n loadedDeclarations.clear()\n warnedFirstParty = false\n}\n","import { z } from 'zod'\n\nexport type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug'\n\nexport const LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n}\n\nexport type LogSource = 'agent' | 'adapter' | 'cache' | 'planner' | 'hook' | 'runner'\n\nexport interface LogEntry {\n id: string\n stepId: string | null\n runId: string\n level: Exclude<LogLevel, 'silent'>\n source: LogSource\n message: string\n data: Record<string, unknown>\n timestamp: string\n}\n\nexport interface LogStorage {\n insertLogs(entries: LogEntry[]): void\n getLogs(opts: {\n runId?: string\n stepId?: string\n level?: string\n source?: string\n limit?: number\n offset?: number\n }): LogEntry[]\n}\n\nexport interface ScopedLogger {\n debug(msg: string, data?: Record<string, unknown>): void\n info(msg: string, data?: Record<string, unknown>): void\n warn(msg: string, data?: Record<string, unknown>): void\n error(msg: string, data?: Record<string, unknown>): void\n}\n\n// Per-source Zod data schemas\nexport const AgentLogDataSchema = z.object({\n extractDom: z.boolean().optional(),\n hasScreenshot: z.boolean().optional(),\n duration: z.number().optional(),\n elementCount: z.number().optional(),\n})\n\nexport const AdapterLogDataSchema = z.object({\n actionType: z.string().optional(),\n selector: z.string().optional(),\n coordinates: z.object({ x: z.number(), y: z.number() }).optional(),\n elementProperties: z.record(z.string(), z.unknown()).optional(),\n duration: z.number().optional(),\n})\n\nexport const CacheLogDataSchema = z.object({\n operation: z.enum(['get', 'set', 'invalidate', 'bypass', 'batch-purge']),\n stepHash: z.string().optional(),\n screenHash: z.string().optional(),\n hit: z.boolean().optional(),\n age: z.number().optional(),\n entriesDeleted: z.number().optional(),\n})\n\nexport const PlannerLogDataSchema = z.object({\n model: z.string().optional(),\n promptTokens: z.number().optional(),\n completionTokens: z.number().optional(),\n latencyMs: z.number().optional(),\n confidence: z.number().optional(),\n actionType: z.string().optional(),\n})\n\nexport const HookLogDataSchema = z.object({\n hookName: z.string().optional(),\n phase: z.enum(['setup', 'teardown']).optional(),\n duration: z.number().optional(),\n success: z.boolean().optional(),\n})\n\nexport const RunnerLogDataSchema = z.object({\n stepIndex: z.number().optional(),\n totalSteps: z.number().optional(),\n testName: z.string().optional(),\n variablesCaptured: z.number().optional(),\n})\n\nexport const LogSourceDataSchemas: Record<LogSource, z.ZodType> = {\n agent: AgentLogDataSchema,\n adapter: AdapterLogDataSchema,\n cache: CacheLogDataSchema,\n planner: PlannerLogDataSchema,\n hook: HookLogDataSchema,\n runner: RunnerLogDataSchema,\n}\n","import { randomUUID } from 'node:crypto'\nimport { LOG_LEVEL_PRIORITY } from './types.js'\nimport type { LogLevel, LogSource, LogEntry, LogStorage, ScopedLogger } from './types.js'\nimport { formatLogEntry } from './cli-formatter.js'\nimport { redactSecretValue, type SecretRedactor } from '@vostride/agent-qa-runner'\n\n/**\n * One member's run-id binding, held in async context rather than on the manager (WINDOWS #233).\n *\n * `pending` is that member's own not-yet-attributed entries — the lines it wrote before it minted\n * its run id. Only these are backfilled by its `setRunId`, so a sibling can never adopt them.\n */\nexport interface MemberLogScope {\n runId: string\n readonly pending: LogEntry[]\n}\n\n/**\n * The host's async-context primitive, named STRUCTURALLY so this package never imports\n * `node:async_hooks`.\n *\n * `packages/core`'s host baseline is a regenerable DEBT record with a per-area clearance map — a\n * list that is meant to shrink — so a new host import here would be new debt, not a permission.\n * The composition root already owns every other reach into the world, so it owns this one too and\n * injects it. `node:async_hooks`'s `AsyncLocalStorage<MemberLogScope>` satisfies this exactly, with\n * no adapter.\n */\nexport interface AsyncScopeStore<T> {\n getStore(): T | undefined\n run<R>(store: T, fn: () => R): R\n}\n\n/** Thrown when a caller asks for member isolation the composition root never wired up. */\nexport class MemberLogScopeUnavailableError extends Error {\n constructor() {\n super(\n 'LogManager.runInMemberScope requires a memberScope store. Construct the manager with ' +\n '`memberScope: new AsyncLocalStorage()` — without it, concurrent members would silently ' +\n 'share one run id (WINDOWS #233).',\n )\n this.name = 'MemberLogScopeUnavailableError'\n }\n}\n\nexport class LogManager {\n private buffer: LogEntry[] = []\n private currentStepId: string | null = null\n private runId: string\n private runIdSet = false\n private readonly displayLevel: LogLevel\n private readonly storage?: LogStorage\n private readonly ndjson: boolean\n private redactor?: SecretRedactor\n private readonly memberScope?: AsyncScopeStore<MemberLogScope>\n\n constructor(opts: {\n runId?: string\n displayLevel: LogLevel\n storage?: LogStorage\n ndjson?: boolean\n redactor?: SecretRedactor\n memberScope?: AsyncScopeStore<MemberLogScope>\n }) {\n this.runId = opts.runId ?? ''\n this.runIdSet = !!opts.runId\n this.displayLevel = opts.displayLevel\n this.storage = opts.storage\n this.ndjson = opts.ndjson ?? false\n this.redactor = opts.redactor\n this.memberScope = opts.memberScope\n }\n\n setRedactor(redactor: SecretRedactor | undefined): void {\n this.redactor = redactor\n }\n\n /**\n * Run `fn` with its own run-id binding, so concurrent members cannot overwrite each other.\n *\n * ONE `LogManager` SERVES EVERY MEMBER of a run — `commands/run.ts` builds it once, outside the\n * per-member closure — and since 402-02/402-03 the direct path runs members concurrently. Without\n * a scope, `setRunId` is a single mutable field plus a whole-buffer backfill, so the LAST member\n * to mint an id claims every line in the buffer, its siblings' included (measured, not inferred).\n *\n * Outside a scope nothing changes: `setRunId` keeps its original whole-buffer behaviour, which is\n * what the sequential path and the run-level `onRunCreated` stamp rely on.\n */\n runInMemberScope<T>(fn: () => T): T {\n if (!this.memberScope) throw new MemberLogScopeUnavailableError()\n return this.memberScope.run({ runId: this.runId, pending: [] }, fn)\n }\n\n log(\n level: Exclude<LogLevel, 'silent'>,\n source: LogSource,\n message: string,\n data?: Record<string, unknown>,\n ): void {\n const scope = this.memberScope?.getStore()\n const entry: LogEntry = {\n id: randomUUID(),\n stepId: this.currentStepId,\n runId: scope ? scope.runId : this.runId,\n level,\n source,\n message: redactSecretValue(message, this.redactor),\n data: redactSecretValue(data ?? {}, this.redactor),\n timestamp: new Date().toISOString(),\n }\n this.buffer.push(entry)\n if (scope && !entry.runId) scope.pending.push(entry)\n\n if (this.shouldDisplay(level)) {\n process.stderr.write(formatLogEntry(entry) + '\\n')\n }\n\n if (this.ndjson) {\n this.emitNdjson(entry)\n }\n }\n\n private shouldDisplay(entryLevel: Exclude<LogLevel, 'silent'>): boolean {\n if (this.displayLevel === 'silent') return false\n return LOG_LEVEL_PRIORITY[entryLevel] <= LOG_LEVEL_PRIORITY[this.displayLevel]\n }\n\n /**\n * The SECOND writer on the `AGENT_QA_EVENT:` stdout channel — the first is the CLI's\n * `reporters/wire-reporter.ts`, which prints run-event envelopes on the same prefix. Both are\n * armed by `AGENT_QA_LIVE_EVENTS=true` (this one indirectly: `commands/run.ts` passes\n * `ndjson: process.env.AGENT_QA_LIVE_EVENTS === 'true'`), both are off by default, and nothing in\n * the product sets that variable. Entries are already redacted above, and are printed verbatim.\n * A supported opt-in; the user-facing contract for both writers is the CLI README's\n * \"Live events on stdout (opt-in)\". Do not change this line shape without mirroring it there.\n */\n private emitNdjson(entry: LogEntry): void {\n process.stdout.write(\n `AGENT_QA_EVENT:${JSON.stringify({ type: 'log', ...entry })}\\n`,\n )\n }\n\n setCurrentStep(stepId: string): void {\n this.currentStepId = stepId\n }\n\n clearCurrentStep(): void {\n this.currentStepId = null\n }\n\n setRunId(runId: string): void {\n const scope = this.memberScope?.getStore()\n if (scope) {\n scope.runId = runId\n // This member's OWN pre-mint lines only. A sibling's unattributed lines live in ITS scope.\n for (const entry of scope.pending) entry.runId = runId\n scope.pending.length = 0\n // The flush gate is a manager-level fact: a scoped stamp is still a real run id, and without\n // this a fully-attributed concurrent run would be silently discarded at flush().\n this.runIdSet = true\n return\n }\n this.runId = runId\n this.runIdSet = true\n for (const entry of this.buffer) {\n entry.runId = runId\n }\n }\n\n flush(): void {\n if (this.storage && this.buffer.length > 0) {\n if (!this.runIdSet) {\n this.buffer = []\n return\n }\n this.storage.insertLogs(this.buffer)\n }\n this.buffer = []\n }\n\n getBuffer(): LogEntry[] {\n return [...this.buffer]\n }\n\n createScopedLogger(source: LogSource): ScopedLogger {\n return {\n debug: (msg: string, data?: Record<string, unknown>) =>\n this.log('debug', source, msg, data),\n info: (msg: string, data?: Record<string, unknown>) =>\n this.log('info', source, msg, data),\n warn: (msg: string, data?: Record<string, unknown>) =>\n this.log('warn', source, msg, data),\n error: (msg: string, data?: Record<string, unknown>) =>\n this.log('error', source, msg, data),\n }\n }\n}\n","import pc from 'picocolors'\nimport type { LogEntry } from './types.js'\n\nconst LEVEL_COLORS: Record<string, (s: string) => string> = {\n error: pc.red,\n warn: pc.yellow,\n info: (s: string) => s,\n debug: pc.dim,\n}\n\nexport function formatLogEntry(entry: LogEntry): string {\n const time = pc.dim(entry.timestamp.slice(11, 23))\n const level = (LEVEL_COLORS[entry.level] ?? ((s: string) => s))(entry.level.toUpperCase().padEnd(5))\n const source = pc.cyan(`[${entry.source}]`)\n const dataKeys = Object.keys(entry.data)\n const dataSuffix = dataKeys.length > 0\n ? ' ' + pc.dim(dataKeys.map(k => `${k}=${JSON.stringify(entry.data[k])}`).join(' '))\n : ''\n return `${time} ${level} ${source} ${entry.message}${dataSuffix}`\n}\n","import type { FarmProviderConfig } from './types.js'\n\nconst ENV_MAP: Record<string, { username: string; accessKey: string }> = {\n browserstack: {\n username: 'BROWSERSTACK_USERNAME',\n accessKey: 'BROWSERSTACK_ACCESS_KEY',\n },\n}\n\nconst DISPLAY_NAMES: Record<string, string> = {\n browserstack: 'BrowserStack',\n}\n\nexport function resolveFarmCredentials(\n provider: string,\n providerConfig?: FarmProviderConfig,\n): { username: string; accessKey: string } {\n const envKeys = ENV_MAP[provider]\n if (!envKeys) {\n throw new Error(`Unknown farm provider: ${provider}`)\n }\n\n const envUsername = process.env[envKeys.username]\n const envAccessKey = process.env[envKeys.accessKey]\n\n if (envUsername && envAccessKey) {\n return { username: envUsername, accessKey: envAccessKey }\n }\n\n if (providerConfig?.username && providerConfig?.accessKey) {\n return { username: providerConfig.username, accessKey: providerConfig.accessKey }\n }\n\n const displayName = DISPLAY_NAMES[provider] ?? provider\n throw new Error(\n `${displayName} credentials not found. Set ${envKeys.username} and ${envKeys.accessKey} env vars, or add provider credentials to agent-qa.local.yaml.`,\n )\n}\n","import { createRequire } from 'node:module'\nimport type { BrowserConfig } from '@vostride/agent-qa-runner'\n\nconst BROWSER_MAP: Record<string, string> = {\n chromium: 'playwright-chromium',\n firefox: 'playwright-firefox',\n webkit: 'playwright-webkit',\n}\n\nexport function detectPlaywrightVersion(): string {\n try {\n const require = createRequire(typeof __filename === 'string' ? __filename : import.meta.url)\n const pkg = require('playwright-core/package.json') as { version: string }\n return pkg.version\n } catch {\n return '1.59.1'\n }\n}\n\nexport function mapWebCapabilities(\n browser: BrowserConfig,\n credentials: { username: string; accessKey: string },\n opts?: { testName?: string; playwrightVersion?: string },\n): Record<string, unknown> {\n if (!browser.viewport) {\n throw new Error('Farm mode requires browser.viewport to be set (e.g. { width: 1280, height: 720 })')\n }\n const bstackBrowser = BROWSER_MAP[browser.name]\n if (!bstackBrowser) {\n throw new Error(`Unsupported browser for BrowserStack: \"${browser.name}\". Supported: ${Object.keys(BROWSER_MAP).join(', ')}`)\n }\n\n return {\n browser: bstackBrowser,\n os: 'os x',\n os_version: 'sonoma',\n resolution: '1920x1080',\n 'browserstack.username': credentials.username,\n 'browserstack.accessKey': credentials.accessKey,\n 'client.playwrightVersion': opts?.playwrightVersion ?? detectPlaywrightVersion(),\n project: 'agent-qa',\n build: 'agent-qa-' + Date.now(),\n name: opts?.testName,\n }\n}\n\nexport function mapMobileCapabilities(\n match: Record<string, unknown>,\n platform: 'android' | 'ios',\n credentials: { username: string; accessKey: string },\n opts?: { testName?: string; testTimeout?: number },\n): Record<string, unknown> {\n if (!opts?.testTimeout) {\n throw new Error('Farm mode requires timeout.test to be set in config')\n }\n\n return {\n 'bstack:options': {\n userName: credentials.username,\n accessKey: credentials.accessKey,\n deviceName: match.deviceName as string | undefined,\n osVersion: match.platformVersion as string | undefined,\n projectName: 'agent-qa',\n buildName: 'agent-qa-' + Date.now(),\n sessionName: opts.testName,\n idleTimeout: Math.ceil(opts.testTimeout / 1000),\n },\n }\n}\n","import type { FarmProvider, FarmWebConfig, FarmMobileConfig, FarmProviderConfig } from './types.js'\nimport { resolveFarmCredentials } from './credentials.js'\nimport { mapWebCapabilities, mapMobileCapabilities } from './capability-mapper.js'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { basename, resolve as resolvePath } from 'node:path'\nimport { MobileSetupError } from '../mobile/launch-resolver.js'\n\nfunction isAbsoluteAppValue(value: string): boolean {\n return value.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\n}\n\nfunction isExplicitRelativePath(value: string): boolean {\n return value.startsWith('./') || value.startsWith('../')\n}\n\nexport async function resolveBrowserStackApp(config: FarmMobileConfig): Promise<string | undefined> {\n if (!config.app) return undefined\n if (isAbsoluteAppValue(config.app)) {\n throw new MobileSetupError({\n category: 'app-install',\n message: `BrowserStack app value must be a BrowserStack reference or relative upload path: ${config.app}`,\n platform: config.platform,\n appId: config.app,\n sourceTrace: config.appSourceTrace,\n })\n }\n\n const appBaseDir = config.appBaseDir ?? process.cwd()\n const resolvedPath = resolvePath(appBaseDir, config.app)\n const mustExist = isExplicitRelativePath(config.app)\n if (!existsSync(resolvedPath)) {\n if (mustExist) {\n throw new MobileSetupError({\n category: 'app-install',\n message: `Configured BrowserStack app upload path not found: ${resolvedPath}`,\n platform: config.platform,\n appId: config.app,\n sourceTrace: config.appSourceTrace,\n })\n }\n return config.app\n }\n\n const auth = Buffer.from(`${config.credentials.username}:${config.credentials.accessKey}`).toString('base64')\n const form = new FormData()\n form.append('file', new Blob([readFileSync(resolvedPath)]), basename(resolvedPath))\n\n let res: Response\n try {\n res = await fetch('https://api-cloud.browserstack.com/app-automate/upload', {\n method: 'POST',\n headers: { Authorization: `Basic ${auth}` },\n body: form,\n })\n } catch (err) {\n throw new MobileSetupError({\n category: 'app-install',\n message: `Failed to upload BrowserStack app: ${err instanceof Error ? err.message : String(err)}`,\n platform: config.platform,\n appId: config.app,\n sourceTrace: config.appSourceTrace,\n cause: err,\n })\n }\n\n if (!res.ok) {\n throw new MobileSetupError({\n category: 'app-install',\n message: `Failed to upload BrowserStack app: HTTP ${res.status}`,\n platform: config.platform,\n appId: config.app,\n sourceTrace: config.appSourceTrace,\n })\n }\n\n const body = await res.json() as { app_url?: string }\n if (!body.app_url) {\n throw new MobileSetupError({\n category: 'app-install',\n message: 'Failed to upload BrowserStack app: response missing app_url',\n platform: config.platform,\n appId: config.app,\n sourceTrace: config.appSourceTrace,\n })\n }\n return body.app_url\n}\n\nexport const browserstackProvider: FarmProvider = {\n name: 'BrowserStack',\n slug: 'browserstack',\n\n async resolveWebEndpoint(config: FarmWebConfig) {\n const caps = mapWebCapabilities(config.browser, config.credentials, {\n testName: config.testName,\n playwrightVersion: config.playwrightVersion,\n })\n const wsEndpoint = `wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(JSON.stringify(caps))}`\n return { wsEndpoint, capabilities: caps }\n },\n\n async resolveMobileCapabilities(config: FarmMobileConfig) {\n const bstackCaps = mapMobileCapabilities(config.match, config.platform, config.credentials, {\n testName: config.testName,\n testTimeout: config.testTimeout,\n })\n\n const automationName = (config.match.automationName as string) ??\n (config.platform === 'android' ? 'UiAutomator2' : 'XCUITest')\n const platformName = config.platform === 'android' ? 'Android' : 'iOS'\n\n const capabilities: Record<string, unknown> = {\n platformName,\n 'appium:automationName': automationName,\n }\n\n for (const [key, value] of Object.entries(config.match)) {\n if (key !== 'automationName' && key !== 'noReset') {\n capabilities[`appium:${key}`] = value\n }\n }\n\n Object.assign(capabilities, bstackCaps)\n\n const browserName = typeof config.match.browserName === 'string' ? config.match.browserName.trim() : ''\n const appStateNoReset = config.appState === 'preserve'\n ? true\n : config.appState === 'reset'\n ? false\n : undefined\n if (!browserName && appStateNoReset !== undefined) {\n capabilities['appium:noReset'] = appStateNoReset\n }\n\n const resolvedAppValue = await resolveBrowserStackApp(config)\n if (resolvedAppValue) {\n capabilities['appium:app'] = resolvedAppValue\n }\n\n return {\n hostname: 'hub.browserstack.com',\n port: 443,\n path: '/wd/hub',\n capabilities,\n }\n },\n\n resolveCredentials(providerConfig?: FarmProviderConfig) {\n return resolveFarmCredentials('browserstack', providerConfig)\n },\n\n async validateDevice(deviceName: string, platform: 'android' | 'ios') {\n let credentials: { username: string; accessKey: string }\n try {\n credentials = resolveFarmCredentials('browserstack')\n } catch {\n return { valid: false, suggestions: ['Could not validate — credentials not configured'] }\n }\n\n const auth = Buffer.from(`${credentials.username}:${credentials.accessKey}`).toString('base64')\n try {\n const res = await fetch('https://api-cloud.browserstack.com/app-automate/devices.json', {\n headers: { Authorization: `Basic ${auth}` },\n })\n if (!res.ok) {\n return { valid: false, suggestions: ['Could not validate — API returned ' + res.status] }\n }\n\n const devices = (await res.json()) as Array<{ device: string; os: string }>\n const targetOs = platform === 'android' ? 'android' : 'ios'\n const match = devices.find(\n (d) => d.device.toLowerCase() === deviceName.toLowerCase() && d.os.toLowerCase() === targetOs,\n )\n\n if (match) return { valid: true }\n\n const similar = devices\n .filter((d) => d.os.toLowerCase() === targetOs)\n .filter((d) => d.device.toLowerCase().includes(deviceName.toLowerCase().split(' ')[0]))\n .map((d) => d.device)\n .slice(0, 5)\n\n return { valid: false, suggestions: similar.length > 0 ? similar : undefined }\n } catch {\n return { valid: false, suggestions: ['Could not validate — network error'] }\n }\n },\n\n getSessionUrl(sessionId: string, type: 'web' | 'mobile') {\n if (type === 'web') {\n return `https://automate.browserstack.com/sessions/${sessionId}`\n }\n return `https://app-automate.browserstack.com/sessions/${sessionId}`\n },\n}\n","import type { FarmProvider } from './types.js'\nimport { browserstackProvider } from './browserstack.js'\n\nconst providers = new Map<string, FarmProvider>()\n\nexport function registerProvider(provider: FarmProvider): void {\n providers.set(provider.slug, provider)\n}\n\nexport function getProvider(slug: string): FarmProvider | undefined {\n return providers.get(slug)\n}\n\nexport function listProviders(): FarmProvider[] {\n return Array.from(providers.values())\n}\n\nexport function registerAllProviders(): void {\n registerProvider(browserstackProvider)\n}\n","import type { TestDefinition } from '../types/test.js'\nimport type { SuiteDefinition } from './types.js'\n\nfunction isPlainObject(val: unknown): val is Record<string, unknown> {\n return typeof val === 'object' && val !== null && !Array.isArray(val)\n}\n\nfunction deepMerge(base: unknown, override: unknown): unknown {\n if (!isPlainObject(base) || !isPlainObject(override)) return override\n const result: Record<string, unknown> = { ...base }\n for (const key of Object.keys(override)) {\n if (key in result && isPlainObject(result[key]) && isPlainObject(override[key])) {\n result[key] = deepMerge(result[key], override[key])\n } else {\n result[key] = override[key]\n }\n }\n return result\n}\n\n/**\n * Merge the suite's target/use into a member test and strip its own `url` (the suite owns\n * startup navigation). The per-member execution body (formerly `executeSuiteMember`) moved onto\n * runner soil (`runMemberTest`) in Phase 363; the CLI composition root patches each member with\n * this helper before running it.\n */\nexport function patchTestForSuite(\n test: TestDefinition,\n suite: SuiteDefinition,\n _index: number,\n): TestDefinition {\n const patched = structuredClone(test)\n\n if (suite.target) {\n ;(patched as any).target = suite.target\n }\n\n if (suite.use && (patched as any).use) {\n ;(patched as any).use = deepMerge(suite.use, (patched as any).use)\n } else {\n ;(patched as any).use = (patched as any).use ?? suite.use\n }\n\n delete (patched as any).url\n\n return patched\n}\n","import { readFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { parse as parseYaml, LineCounter, parseDocument } from 'yaml'\nimport { glob } from 'glob'\nimport { AgentQaConfigSchema } from '../schema/config-schema.js'\nimport { SuiteDefinitionSchema } from '../schema/suite-schema.js'\nimport { parseTestFile } from '../parser/yaml-parser.js'\nimport { parseHooksFile } from '../hooks/parser.js'\nimport { isPathInsideDir } from '../utils/path-validation.js'\nimport { yamlParseFailureMessage } from './yaml-fault.js'\nimport {\n discoverWorkspaceFiles,\n isWorkspacePathMatch,\n resolveWorkspaceFileTarget,\n type ResolvedWorkspacePaths,\n type WorkspaceFileKind,\n} from '../workspace/workspace-paths.js'\n\nexport interface ValidationDiagnostic {\n file: string\n line: number\n column: number\n message: string\n severity: 'error' | 'warning'\n}\n\nexport interface ValidationResult {\n diagnostics: ValidationDiagnostic[]\n fileCount: number\n errorCount: number\n warningCount: number\n}\n\nexport const VALID_FILENAME_RE = /^[a-zA-Z0-9._-]+\\.(suite\\.)?(yaml|yml)$/\n\nexport async function validateConfig(configPath: string): Promise<ValidationDiagnostic[]> {\n const diagnostics: ValidationDiagnostic[] = []\n\n let content: string\n try {\n content = await readFile(configPath, 'utf-8')\n } catch (err) {\n diagnostics.push({\n file: configPath,\n line: 1,\n column: 1,\n message: `Cannot read config file: ${(err as Error).message}`,\n severity: 'error',\n })\n return diagnostics\n }\n\n let parsed: unknown\n try {\n parsed = parseYaml(content)\n } catch (err) {\n // WHERE, NEVER WHAT (395-14 · F-01). This line used to interpolate the thrown error's own text,\n // and the vendored `yaml` package pretty-prints a parse error with an excerpt of the source\n // around the point it gave up — the person's own file content, printed by `agent-qa validate`\n // and measured carrying a planted credential. The diagnostic's `file` field already names the\n // file, so the message is the position and nothing else. This is the SIBLING SITE of the cli\n // loader's guard: `agent-qa validate` catches its own `resolveConfig` failure and defers here,\n // so a fix that hardened only the loader would leave this road printing the excerpt.\n diagnostics.push({\n file: configPath,\n line: 1,\n column: 1,\n message: yamlParseFailureMessage(err),\n severity: 'error',\n })\n return diagnostics\n }\n\n const result = AgentQaConfigSchema.safeParse(parsed)\n if (!result.success) {\n for (const issue of result.error.issues) {\n diagnostics.push({\n file: configPath,\n line: 1,\n column: 1,\n message: `${issue.path.join('.')}: ${issue.message}`,\n severity: 'error',\n })\n }\n }\n\n return diagnostics\n}\n\nfunction buildDiagnostic(file: string, message: string, severity: 'error' | 'warning' = 'error'): ValidationDiagnostic {\n return {\n file,\n line: 1,\n column: 1,\n message,\n severity,\n }\n}\n\nexport function validateTestFile(filePath: string, content: string): ValidationDiagnostic[] {\n const result = parseTestFile(content, filePath)\n return result.errors.map((e) => ({\n file: e.file,\n line: e.line,\n column: e.column,\n message: e.message,\n severity: e.severity,\n }))\n}\n\nexport function validateSuiteFile(filePath: string, content: string, basedir: string): ValidationDiagnostic[] {\n const diagnostics: ValidationDiagnostic[] = []\n\n const lineCounter = new LineCounter()\n let parsed: unknown\n try {\n parsed = parseYaml(content, { lineCounter })\n } catch (err) {\n // WHERE, NEVER WHAT — the THIRD MEMBER (395-16 · WINDOWS 139). Measured, not inferred: this\n // arm answered `YAML syntax error: Map keys must be unique at line 7, column 1:` followed by\n // the person's own line, rendered by `agent-qa validate`. The diagnostic's `file` field already\n // names the file, so the message is the position and nothing else — the same composition as the\n // config arm at :69 and the hooks arm in `parseHooksFile`.\n diagnostics.push({\n file: filePath,\n line: 1,\n column: 1,\n message: yamlParseFailureMessage(err),\n severity: 'error',\n })\n return diagnostics\n }\n\n const result = SuiteDefinitionSchema.safeParse(parsed)\n if (!result.success) {\n for (const issue of result.error.issues) {\n diagnostics.push({\n file: filePath,\n line: 1,\n column: 1,\n message: `${issue.path.join('.')}: ${issue.message}`,\n severity: 'error',\n })\n }\n return diagnostics\n }\n\n // Check test references exist on disk\n const doc = parseDocument(content, { lineCounter })\n const testsNode = doc.contents && 'get' in doc.contents ? (doc.contents as { get: (key: string, keepScalar?: boolean) => unknown }).get('tests', true) : undefined\n\n const tests = result.data.tests\n for (let i = 0; i < tests.length; i++) {\n const entry = tests[i]\n const testPath = entry.test\n\n if (!isPathInsideDir(testPath, basedir)) {\n diagnostics.push({\n file: filePath, line: 1, column: 1,\n message: `Path traversal rejected: ${testPath}`,\n severity: 'error',\n })\n continue\n }\n\n const resolved = path.resolve(basedir, testPath)\n if (!existsSync(resolved)) {\n let line = 1\n let column = 1\n const seqNode = testsNode as { items?: { range?: [number, number] }[] } | undefined\n if (seqNode?.items?.[i]?.range) {\n const pos = lineCounter.linePos(seqNode.items[i].range![0])\n line = pos.line\n column = pos.col\n }\n diagnostics.push({\n file: filePath,\n line,\n column,\n message: `Test reference not found: ${testPath} (resolved: ${resolved})`,\n severity: 'error',\n })\n }\n }\n\n return diagnostics\n}\n\nexport function validateFilename(filePath: string): ValidationDiagnostic[] {\n const basename = path.basename(filePath)\n if (!VALID_FILENAME_RE.test(basename)) {\n return [{\n file: filePath,\n line: 1,\n column: 1,\n message: `Invalid filename \"${basename}\" — expected pattern: [a-zA-Z0-9._-]+.(suite.)?(yaml|yml)`,\n severity: 'warning',\n }]\n }\n return []\n}\n\nexport async function validateHooksFile(\n hooksFilePath: string,\n options: { required?: boolean } = {},\n): Promise<ValidationDiagnostic[]> {\n const diagnostics: ValidationDiagnostic[] = []\n\n if (!existsSync(hooksFilePath)) {\n if (options.required) {\n return [buildDiagnostic(hooksFilePath, `Configured hooks file not found: ${hooksFilePath}`)]\n }\n return []\n }\n\n const { hooks, errors } = await parseHooksFile(hooksFilePath)\n if (errors.length > 0) {\n for (const err of errors) {\n diagnostics.push({\n file: hooksFilePath,\n line: 1,\n column: 1,\n message: err,\n severity: 'error',\n })\n }\n return diagnostics\n }\n\n for (const hook of hooks) {\n if (!existsSync(hook.file)) {\n diagnostics.push({\n file: hooksFilePath,\n line: 1,\n column: 1,\n message: `Hook \"${hook.name}\": script file not found: ${hook.file}`,\n severity: 'error',\n })\n }\n\n for (const dep of hook.deps) {\n if (!existsSync(dep)) {\n diagnostics.push({\n file: hooksFilePath,\n line: 1,\n column: 1,\n message: `Hook \"${hook.name}\": dependency file not found: ${dep}`,\n severity: 'error',\n })\n }\n }\n\n if (hook.packageFile && !existsSync(hook.packageFile)) {\n diagnostics.push({\n file: hooksFilePath,\n line: 1,\n column: 1,\n message: `Hook \"${hook.name}\": package file not found: ${hook.packageFile}`,\n severity: 'error',\n })\n }\n }\n\n return diagnostics\n}\n\nexport function validateHookReferences(\n setupOrTeardown: string[],\n hookIds: Set<string>,\n filePath: string,\n context: string,\n): ValidationDiagnostic[] {\n const diagnostics: ValidationDiagnostic[] = []\n for (const hookId of setupOrTeardown) {\n if (!hookIds.has(hookId)) {\n diagnostics.push({\n file: filePath,\n line: 1,\n column: 1,\n message: `Hook ID \"${hookId}\" referenced in ${context} but not defined in the configured hooks file`,\n severity: 'warning',\n })\n }\n }\n return diagnostics\n}\n\nexport async function detectGlobOverlap(\n testMatch: string[],\n suiteMatch: string[],\n ignore: string[],\n cwd?: string,\n): Promise<string[]> {\n if (testMatch.length === 0 || suiteMatch.length === 0) return []\n const globOptions = {\n ignore,\n absolute: true,\n ...(cwd ? { cwd } : {}),\n }\n const [testFiles, suiteFiles] = await Promise.all([\n glob(testMatch, globOptions),\n glob(suiteMatch, globOptions),\n ])\n const testSet = new Set(testFiles)\n return suiteFiles.filter((f) => testSet.has(f))\n}\n\nfunction isSuiteFile(filePath: string): boolean {\n return /\\.suite\\.(yaml|yml)$/.test(filePath)\n}\n\nexport async function validateFiles(\n filePaths: string[],\n configPath?: string,\n options: { basedir?: string } = {},\n): Promise<ValidationResult> {\n const diagnostics: ValidationDiagnostic[] = []\n\n if (configPath) {\n diagnostics.push(...await validateConfig(configPath))\n }\n\n for (const filePath of filePaths) {\n diagnostics.push(...validateFilename(filePath))\n\n let content: string\n try {\n content = await readFile(filePath, 'utf-8')\n } catch (err) {\n diagnostics.push({\n file: filePath,\n line: 1,\n column: 1,\n message: `Cannot read file: ${(err as Error).message}`,\n severity: 'error',\n })\n continue\n }\n\n if (isSuiteFile(filePath)) {\n diagnostics.push(...validateSuiteFile(filePath, content, options.basedir ?? process.cwd()))\n } else {\n diagnostics.push(...validateTestFile(filePath, content))\n }\n }\n\n const errorCount = diagnostics.filter((d) => d.severity === 'error').length\n const warningCount = diagnostics.filter((d) => d.severity === 'warning').length\n const files = new Set(diagnostics.map((d) => d.file))\n\n return {\n diagnostics,\n fileCount: filePaths.length,\n errorCount,\n warningCount,\n }\n}\n\nasync function resolveExplicitWorkspaceFile(\n workspace: ResolvedWorkspacePaths,\n filePath: string,\n): Promise<{ record?: { absolutePath: string }; diagnostic?: ValidationDiagnostic }> {\n const preferredKinds: WorkspaceFileKind[] = isSuiteFile(filePath)\n ? ['suite', 'test']\n : ['test', 'suite']\n\n for (const kind of preferredKinds) {\n try {\n const record = await resolveWorkspaceFileTarget({\n workspace,\n kind,\n filePath,\n requireExisting: true,\n })\n return { record }\n } catch {\n // Try the other configured file kind before reporting the path as invalid.\n }\n }\n\n return {\n diagnostic: buildDiagnostic(\n filePath,\n `File is not matched by configured workspace testMatch or suiteMatch patterns: ${filePath}`,\n ),\n }\n}\n\nfunction appendDiagnostics(result: ValidationResult, diagnostics: ValidationDiagnostic[]): void {\n for (const diagnostic of diagnostics) {\n result.diagnostics.push(diagnostic)\n if (diagnostic.severity === 'error') result.errorCount++\n else result.warningCount++\n }\n}\n\nfunction validateRequiredWorkspaceFiles(workspace: ResolvedWorkspacePaths): ValidationDiagnostic[] {\n const diagnostics: ValidationDiagnostic[] = []\n // The workspace agent-rules file was retired in Phase 373 — rules return as\n // committed agent-qa-knowledge/policies/ files via Reader L0 in Phase 380.\n for (const [key, file] of [\n ['workspace.envFile', workspace.envFile],\n ['workspace.secretsFile', workspace.secretsFile],\n ] as const) {\n if (!existsSync(file.absolutePath)) {\n diagnostics.push(buildDiagnostic(file.absolutePath, `Configured workspace file not found: ${key} -> ${file.absolutePath}`))\n }\n }\n return diagnostics\n}\n\nexport async function validateProject(options: {\n configPath?: string\n files?: string[]\n testMatch?: string[]\n testPathIgnore?: string[]\n suiteMatch?: string[]\n hooksFile?: string\n workspace?: ResolvedWorkspacePaths\n} = {}): Promise<ValidationResult> {\n let filePaths: string[]\n const preDiagnostics: ValidationDiagnostic[] = []\n\n if (options.files && options.files.length > 0 && options.workspace) {\n const resolvedFiles: string[] = []\n for (const file of options.files) {\n const { record, diagnostic } = await resolveExplicitWorkspaceFile(options.workspace, file)\n if (record) resolvedFiles.push(record.absolutePath)\n if (diagnostic) preDiagnostics.push(diagnostic)\n }\n filePaths = resolvedFiles\n } else if (options.files && options.files.length > 0) {\n filePaths = options.files.map((f) => path.resolve(f))\n } else if (options.workspace) {\n const [testFiles, suiteFiles] = await Promise.all([\n discoverWorkspaceFiles({ workspace: options.workspace, kind: 'test' }),\n discoverWorkspaceFiles({ workspace: options.workspace, kind: 'suite' }),\n ])\n filePaths = [...testFiles, ...suiteFiles].map(file => file.absolutePath)\n } else {\n const testPatterns = options.testMatch ?? []\n const suitePatterns = options.suiteMatch ?? []\n const allPatterns = [...testPatterns, ...suitePatterns]\n const ignore = options.testPathIgnore ?? []\n filePaths = allPatterns.length > 0\n ? await glob(allPatterns, { ignore, absolute: true })\n : []\n }\n\n const configPath = options.configPath ?? options.workspace?.configPath\n\n const result = await validateFiles(filePaths, configPath, {\n basedir: options.workspace?.configDir,\n })\n appendDiagnostics(result, preDiagnostics)\n\n const testPatterns = options.workspace?.testMatch ?? options.testMatch ?? []\n const suitePatterns = options.workspace?.suiteMatch ?? options.suiteMatch ?? []\n if (testPatterns.length > 0 && suitePatterns.length > 0) {\n const ignore = options.workspace?.testPathIgnore ?? options.testPathIgnore ?? []\n const overlapping = await detectGlobOverlap(testPatterns, suitePatterns, ignore, options.workspace?.configDir)\n for (const filePath of overlapping) {\n result.diagnostics.push({\n file: filePath,\n line: 1,\n column: 1,\n message: 'File matched by both testMatch and suiteMatch — may cause duplicate validation',\n severity: 'warning',\n })\n result.warningCount++\n }\n }\n\n appendDiagnostics(result, options.workspace ? validateRequiredWorkspaceFiles(options.workspace) : [])\n\n const hooksFilePath = options.workspace?.hooksFile.absolutePath ?? options.hooksFile\n const hooksDiags = hooksFilePath\n ? await validateHooksFile(hooksFilePath, { required: Boolean(options.workspace) })\n : []\n for (const d of hooksDiags) {\n result.diagnostics.push(d)\n if (d.severity === 'error') result.errorCount++\n else result.warningCount++\n }\n\n // Check hook ID references in test/suite files\n if (hooksFilePath && hooksDiags.length === 0 && existsSync(hooksFilePath)) {\n const { hooks } = await parseHooksFile(hooksFilePath)\n const hookIds = new Set(hooks.map(h => h.id))\n\n for (const filePath of filePaths) {\n const workspaceRelativePath = options.workspace\n ? path.relative(options.workspace.configDir, filePath).split(path.sep).join('/')\n : filePath\n const isWorkspaceFile = options.workspace\n ? isWorkspacePathMatch({ workspace: options.workspace, kind: isSuiteFile(filePath) ? 'suite' : 'test', workspaceRelativePath })\n : true\n if (!isWorkspaceFile) continue\n\n try {\n const content = await readFile(filePath, 'utf-8')\n const parsed = parseYaml(content)\n if (parsed && typeof parsed === 'object') {\n const setup = (parsed as Record<string, unknown>).setup as string[] | undefined\n const teardown = (parsed as Record<string, unknown>).teardown as string[] | undefined\n if (setup?.length) {\n const refDiags = validateHookReferences(setup, hookIds, filePath, 'setup')\n for (const d of refDiags) { result.diagnostics.push(d); result.warningCount++ }\n }\n if (teardown?.length) {\n const refDiags = validateHookReferences(teardown, hookIds, filePath, 'teardown')\n for (const d of refDiags) { result.diagnostics.push(d); result.warningCount++ }\n }\n }\n } catch { /* skip files that can't be parsed */ }\n }\n }\n\n return result\n}\n","import { readFile } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport { parse as parseYaml } from 'yaml'\nimport { HooksFileSchema } from './schema.js'\nimport { yamlParseFailureMessage } from '../validation/yaml-fault.js'\nimport type { HookDefinition } from '@vostride/agent-qa-runner'\n\nexport async function parseHooksFile(filePath: string): Promise<{ hooks: HookDefinition[]; errors: string[] }> {\n let raw: string\n try {\n raw = await readFile(filePath, 'utf-8')\n } catch (err) {\n return { hooks: [], errors: [`Failed to read hooks file: ${(err as Error).message}`] }\n }\n\n let parsed: unknown\n try {\n parsed = parseYaml(raw)\n } catch (err) {\n // WHERE, NEVER WHAT — the SIBLING MEMBER of the set the config arm was hardened on\n // (395-16 · CR-02). `hooks.yaml` is a member of the same file set `enumerateConfigFileSet`\n // pins, and this line used to interpolate the caught error's own text: `yaml` pretty-prints a\n // parse error with a verbatim excerpt of the source around the point it gave up, measured\n // carrying a planted credential out of `agent-qa validate`'s rendered output. One member\n // hardened while its sibling leaks is this codebase's recurring failure mode, so this arm\n // composes through the SAME core primitive the config arm uses — two spellings of one sentence\n // are two things that can drift apart. The path prefix is deliberate: these strings travel to\n // consumers that do not separately name the file — `validateHooksFile` (which builds a\n // diagnostic whose `file` field is the hooks path but whose rendered message stands alone) and\n // `run.ts`'s hooks load.\n //\n // THE DASHBOARD REGISTRY ROAD IS NOT ONE OF THEM, and the earlier revision of this comment said\n // it was (395-18, correcting the D-395-14-C doc-truth class). Measured, not inferred:\n // `hook-registry-manager.ts:307` returns on `registry.errors` — the registry's OWN parse copy at\n // `:753` — above the `parseHooksFile` call at `:315`, so on a malformed `hooks.yaml` the\n // dashboard road never reaches this arm at all. Those copies are a separate channel on a\n // separate surface and carry their own disposition (WINDOWS 140). A comment that names a\n // consumer the code cannot reach is a claim a later round will act on.\n return { hooks: [], errors: [`${filePath}: ${yamlParseFailureMessage(err)}`] }\n }\n\n const result = HooksFileSchema.safeParse(parsed)\n if (!result.success) {\n const errors = result.error.issues.map((issue) =>\n `${issue.path.join('.')}: ${issue.message}`\n )\n return { hooks: [], errors }\n }\n\n const dir = dirname(filePath)\n const hooks: HookDefinition[] = result.data.hooks.map((h) => ({\n ...h,\n file: resolve(dir, h.file),\n deps: h.deps.map((d) => resolve(dir, d)),\n packageFile: h.packageFile ? resolve(dir, h.packageFile) : undefined,\n }))\n\n return { hooks, errors: [] }\n}\n","import path from 'node:path'\n\nexport function isPathInsideDir(childPath: string, parentDir: string): boolean {\n if (!childPath) return false\n const resolved = path.resolve(parentDir, childPath)\n const relative = path.relative(parentDir, resolved)\n return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative)\n}\n","import { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { glob } from 'glob'\nimport type { AgentQaConfig } from '../types/config.js'\n\nexport type WorkspaceFileKind = 'test' | 'suite'\n\nexport interface ResolvedWorkspaceFile {\n configuredPath: string\n absolutePath: string\n workspaceRelativePath: string\n}\n\nexport interface WorkspaceFileRecord {\n kind: WorkspaceFileKind\n absolutePath: string\n workspaceRelativePath: string\n}\n\nexport interface ResolvedWorkspacePaths {\n configPath: string\n configDir: string\n testMatch: string[]\n suiteMatch: string[]\n testPathIgnore: string[]\n hooksFile: ResolvedWorkspaceFile\n envFile: ResolvedWorkspaceFile\n secretsFile: ResolvedWorkspaceFile\n}\n\ninterface ResolveWorkspacePathsInput {\n config: AgentQaConfig\n configPath: string\n requireExistingFiles?: boolean\n}\n\nfunction toForwardSlash(value: string): string {\n return value.split(path.sep).join('/')\n}\n\nfunction trimLeadingCurrentDir(value: string): string {\n return toForwardSlash(value).replace(/^\\.\\//, '')\n}\n\nfunction assertNonEmptyArray(value: unknown, key: string): string[] {\n if (!Array.isArray(value) || value.length === 0 || value.some(item => typeof item !== 'string' || item.trim().length === 0)) {\n throw new Error(`Missing required workspace config key: ${key}`)\n }\n return value\n}\n\nfunction assertNonEmptyString(value: unknown, key: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new Error(`Missing required workspace config key: ${key}`)\n }\n return value\n}\n\nfunction resolveWorkspaceScalar(configDir: string, key: string, configuredPath: unknown): ResolvedWorkspaceFile {\n const value = assertNonEmptyString(configuredPath, key)\n const absolutePath = path.isAbsolute(value) ? path.resolve(value) : path.resolve(configDir, value)\n return {\n configuredPath: value,\n absolutePath,\n workspaceRelativePath: trimLeadingCurrentDir(path.relative(configDir, absolutePath)),\n }\n}\n\nfunction assertInsideWorkspace(configDir: string, absolutePath: string, filePath: string): string {\n const relativePath = path.relative(configDir, absolutePath)\n if (!relativePath || relativePath.startsWith('..') || path.isAbsolute(relativePath)) {\n throw new Error(`Workspace file path escapes config directory: ${filePath}`)\n }\n return trimLeadingCurrentDir(relativePath)\n}\n\n/**\n * The ONE spelling of the durable workspace-relative IDENTITY recipe (390-08 / CR-02, D-01).\n *\n * `configDir`-rooted, forward-slashed, `./`-trimmed, and escape-refusing — literally\n * {@link assertInsideWorkspace} with {@link resolveWorkspaceFileTarget}'s resolution step in front,\n * exported rather than re-derived so no second spelling of the rule can drift from this one.\n *\n * WHY IT EXISTS: the committed `quarantine.jsonl` keys entries on this string and compares it with\n * `===`. An absolute path is bytes only the machine that wrote them can produce, so a ledger\n * carrying absolute identities could never match on a fresh CI checkout — it would be committed for\n * an inheritance it structurally cannot deliver. These bytes are IDENTITY ONLY and are never used\n * for file access; readers keep the absolute path they already resolved.\n *\n * Accepting an already-relative input (resolved against `configDir`, as\n * {@link resolveWorkspaceFileTarget} does) makes the mint idempotent: handing an identity through a\n * second layer cannot silently re-anchor it on `process.cwd()`.\n *\n * @throws when the path resolves outside `configDir` — an escaping file cannot mint an identity.\n */\nexport function workspaceRelativeIdentityPath(configDir: string, filePath: string): string {\n const absolutePath = path.isAbsolute(filePath)\n ? path.resolve(filePath)\n : path.resolve(configDir, filePath)\n return assertInsideWorkspace(configDir, absolutePath, filePath)\n}\n\nfunction escapeRegexChar(char: string): string {\n return char.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction globToRegex(pattern: string): RegExp {\n const normalized = trimLeadingCurrentDir(pattern)\n let source = ''\n\n for (let i = 0; i < normalized.length; i++) {\n const char = normalized[i]\n const next = normalized[i + 1]\n\n if (char === '*') {\n if (next === '*') {\n const afterGlobstar = normalized[i + 2]\n if (afterGlobstar === '/') {\n source += '(?:.*/)?'\n i += 2\n } else {\n source += '.*'\n i += 1\n }\n } else {\n source += '[^/]*'\n }\n continue\n }\n\n if (char === '?') {\n source += '[^/]'\n continue\n }\n\n if (char === '{') {\n const end = normalized.indexOf('}', i + 1)\n if (end !== -1) {\n const alternatives = normalized\n .slice(i + 1, end)\n .split(',')\n .map(part => part.split('').map(escapeRegexChar).join(''))\n source += `(?:${alternatives.join('|')})`\n i = end\n continue\n }\n }\n\n source += escapeRegexChar(char)\n }\n\n return new RegExp(`^${source}$`)\n}\n\nfunction matchesAnyPattern(workspaceRelativePath: string, patterns: string[]): boolean {\n const normalized = trimLeadingCurrentDir(workspaceRelativePath)\n return patterns.some(pattern => globToRegex(pattern).test(normalized))\n}\n\nfunction getKindPatterns(workspace: ResolvedWorkspacePaths, kind: WorkspaceFileKind): string[] {\n return kind === 'test' ? workspace.testMatch : workspace.suiteMatch\n}\n\nfunction isIgnored(workspace: ResolvedWorkspacePaths, workspaceRelativePath: string): boolean {\n return workspace.testPathIgnore.length > 0 && matchesAnyPattern(workspaceRelativePath, workspace.testPathIgnore)\n}\n\nexport function resolveWorkspacePaths(input: ResolveWorkspacePathsInput): ResolvedWorkspacePaths {\n const configPath = path.resolve(input.configPath)\n const configDir = path.dirname(configPath)\n const workspace = input.config.workspace\n\n if (!workspace) {\n throw new Error('Missing required workspace config key: workspace')\n }\n\n const resolved: ResolvedWorkspacePaths = {\n configPath,\n configDir,\n testMatch: assertNonEmptyArray(workspace.testMatch, 'workspace.testMatch'),\n suiteMatch: assertNonEmptyArray(workspace.suiteMatch, 'workspace.suiteMatch'),\n testPathIgnore: workspace.testPathIgnore ?? [],\n hooksFile: resolveWorkspaceScalar(configDir, 'workspace.hooksFile', workspace.hooksFile),\n envFile: resolveWorkspaceScalar(configDir, 'workspace.envFile', workspace.envFile),\n secretsFile: resolveWorkspaceScalar(configDir, 'workspace.secretsFile', workspace.secretsFile),\n }\n\n if (input.requireExistingFiles) {\n // The workspace agent-rules file was retired in Phase 373 — rules return as\n // committed agent-qa-knowledge/policies/ files via Reader L0 in Phase 380.\n for (const [key, file] of [\n ['workspace.hooksFile', resolved.hooksFile],\n ['workspace.envFile', resolved.envFile],\n ['workspace.secretsFile', resolved.secretsFile],\n ] as const) {\n if (!existsSync(file.absolutePath)) {\n throw new Error(`Configured workspace file not found: ${key} -> ${file.absolutePath}`)\n }\n }\n }\n\n return resolved\n}\n\nexport async function discoverWorkspaceFiles(input: {\n workspace: ResolvedWorkspacePaths\n kind: WorkspaceFileKind\n}): Promise<WorkspaceFileRecord[]> {\n const patterns = getKindPatterns(input.workspace, input.kind)\n const matches = await glob(patterns, {\n cwd: input.workspace.configDir,\n ignore: input.workspace.testPathIgnore,\n absolute: true,\n nodir: true,\n })\n\n return matches\n .map(match => path.resolve(match))\n .map(absolutePath => ({\n kind: input.kind,\n absolutePath,\n workspaceRelativePath: trimLeadingCurrentDir(path.relative(input.workspace.configDir, absolutePath)),\n }))\n .sort((a, b) => a.workspaceRelativePath.localeCompare(b.workspaceRelativePath))\n}\n\nexport async function resolveWorkspaceFileTarget(input: {\n workspace: ResolvedWorkspacePaths\n kind: WorkspaceFileKind\n filePath: string\n requireExisting?: boolean\n}): Promise<WorkspaceFileRecord> {\n const absolutePath = path.isAbsolute(input.filePath)\n ? path.resolve(input.filePath)\n : path.resolve(input.workspace.configDir, input.filePath)\n const workspaceRelativePath = assertInsideWorkspace(input.workspace.configDir, absolutePath, input.filePath)\n\n if (!isWorkspacePathMatch({\n workspace: input.workspace,\n kind: input.kind,\n workspaceRelativePath,\n })) {\n throw new Error(`Workspace ${input.kind} file is not matched by configured workspace patterns: ${workspaceRelativePath}`)\n }\n\n if (input.requireExisting && !existsSync(absolutePath)) {\n throw new Error(`Workspace ${input.kind} file not found: ${workspaceRelativePath}`)\n }\n\n return {\n kind: input.kind,\n absolutePath,\n workspaceRelativePath,\n }\n}\n\nexport function isWorkspacePathMatch(input: {\n workspace: ResolvedWorkspacePaths\n kind: WorkspaceFileKind\n workspaceRelativePath: string\n}): boolean {\n return matchesAnyPattern(input.workspaceRelativePath, getKindPatterns(input.workspace, input.kind))\n && !isIgnored(input.workspace, input.workspaceRelativePath)\n}\n","import pc from 'picocolors'\nimport type { ValidationResult, ValidationDiagnostic } from './validate.js'\n\nfunction groupByFile(diagnostics: ValidationDiagnostic[]): Map<string, ValidationDiagnostic[]> {\n const groups = new Map<string, ValidationDiagnostic[]>()\n for (const d of diagnostics) {\n const existing = groups.get(d.file)\n if (existing) {\n existing.push(d)\n } else {\n groups.set(d.file, [d])\n }\n }\n return groups\n}\n\nfunction formatSeverity(severity: 'error' | 'warning', color: boolean): string {\n if (severity === 'error') {\n return color ? pc.red('error') : 'error'\n }\n return color ? pc.yellow('warning') : 'warning'\n}\n\nfunction formatOutput(result: ValidationResult, color: boolean): string {\n if (result.diagnostics.length === 0) {\n const check = color ? pc.green('\\u2714') : '\\u2714'\n return `\\n${check} All files valid (${result.fileCount} file(s) checked)\\n`\n }\n\n const groups = groupByFile(result.diagnostics)\n const lines: string[] = ['']\n\n for (const [file, diagnostics] of groups) {\n const header = color ? pc.underline(pc.bold(file)) : file\n lines.push(header)\n\n for (const d of diagnostics) {\n const loc = `${d.line}:${d.column}`\n const sev = formatSeverity(d.severity, color).padEnd(color ? 20 : 7)\n lines.push(` ${loc} ${sev} ${d.message}`)\n }\n\n lines.push('')\n }\n\n const filesWithIssues = groups.size\n if (result.errorCount > 0) {\n const cross = color ? pc.red('\\u2716') : '\\u2716'\n lines.push(`${cross} ${result.errorCount} error(s), ${result.warningCount} warning(s) in ${filesWithIssues} file(s)`)\n } else {\n const warn = color ? pc.yellow('\\u26A0') : '\\u26A0'\n lines.push(`${warn} ${result.warningCount} warning(s) in ${filesWithIssues} file(s)`)\n }\n lines.push('')\n\n return lines.join('\\n')\n}\n\nexport function formatDiagnostics(result: ValidationResult): string {\n return formatOutput(result, true)\n}\n\nexport function formatDiagnosticsPlain(result: ValidationResult): string {\n return formatOutput(result, false)\n}\n","export function warnIfOutOfBounds(\n coords: { x?: number; y?: number },\n viewport: { width: number; height: number },\n actionType: string,\n): void {\n const { x, y } = coords\n const { width, height } = viewport\n if (x !== undefined && (x < 0 || x > width)) {\n console.warn(`[${actionType}] x=${x} outside viewport bounds [0, ${width}]`)\n }\n if (y !== undefined && (y < 0 || y > height)) {\n console.warn(`[${actionType}] y=${y} outside viewport bounds [0, ${height}]`)\n }\n}\n","// Hook PARSING stays in core (feeds the resolved RunConfig, D-05). Hook EXECUTION\n// (orchestrator, sandbox-runner, types) moved to @vostride/agent-qa-runner /\n// -runner-local in Phase 363 D-06 — no core re-export of runHooks/DockerHookExecutor\n// (no shim). The hook TYPE vocabulary is re-exported from runner so core parser/schema\n// consumers keep resolving through the core barrel.\nexport type { HookRuntime, HookDefinition, HookResult } from '@vostride/agent-qa-runner'\nexport { RUNTIME_IMAGE_MAP } from '@vostride/agent-qa-runner'\nexport * from './schema.js'\nexport { parseHooksFile } from './parser.js'\n","import { generateHookId as generateSharedHookId } from '@vostride/agent-qa-ids'\n\n// 395-05: re-exported on `generateRunId`'s footing, one file over. The mint and the schema that\n// REFUSES anything it did not produce (`HookDefinitionSchema` → `isCanonicalHookId`) then live\n// behind one package boundary, so a caller that can validate a hook can also make one — and\n// `packages/cli`'s ownership contract, which 394-11 deliberately emptied of the ids package with a\n// recorded reason, does not have to be reopened to let a host mint an id it cannot hand-format.\nexport function generateHookId(): string {\n return generateSharedHookId()\n}\n","import { generateRunId as generateSharedRunId, isCanonicalRunId as isSharedCanonicalRunId } from '@vostride/agent-qa-ids'\n\nexport function generateRunId(): string {\n return generateSharedRunId()\n}\n\n/**\n * Is this an id the run mint above would have produced? (2026-08-23, 401-20 · CR-04)\n *\n * THE MINT'S OWN INVERSE, re-exported one line under it and from the same package, so the two can\n * never answer about different id shapes. The invocation core takes this as a REQUIRED option\n * beside `mintRunId` for the reason the mint is one: `agent-local` may not name the ids package,\n * and a shape check invented there would be a second spelling of a run's identity.\n */\nexport function isCanonicalRunId(value: string): boolean {\n return isSharedCanonicalRunId(value)\n}\n","export type RunAttributes = Record<string, string>\n\nexport const INTERNAL_ATTRIBUTE_PREFIX = 'agent-qa.'\nexport const ATTR_TRIGGER = 'agent-qa.trigger'\nexport const ATTR_RUNNER = 'agent-qa.runner'\nexport const ATTR_GATE_RUN = 'agent-qa.gate-run'\n\nexport type RunAttributeTrigger = 'cli' | 'dashboard' | 'api' | 'mcp'\nexport type RunAttributeRunner = 'local' | 'browserstack'\n\nexport const RUN_ATTRIBUTE_KEY_MAX_LENGTH = 256\nexport const RUN_ATTRIBUTE_VALUE_MAX_LENGTH = 4096\nconst RUN_ATTRIBUTE_TRIGGERS: RunAttributeTrigger[] = ['cli', 'dashboard', 'api', 'mcp']\nconst RUN_ATTRIBUTE_RUNNERS: RunAttributeRunner[] = ['local', 'browserstack']\n\nexport interface ParsedRunAttrFlags {\n attributes: RunAttributes\n duplicateKeys: string[]\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction assertValidUserAttributeKey(key: string, sourceLabel: string): void {\n if (key.length === 0) {\n throw new Error(`${sourceLabel}: Attribute key must be non-empty`)\n }\n if (key.startsWith(INTERNAL_ATTRIBUTE_PREFIX)) {\n throw new Error(`${sourceLabel}: Attribute key \"${key}\" uses the reserved prefix \"${INTERNAL_ATTRIBUTE_PREFIX}\"`)\n }\n if (key.length > RUN_ATTRIBUTE_KEY_MAX_LENGTH) {\n throw new Error(`${sourceLabel}: Attribute key \"${key}\" exceeds ${RUN_ATTRIBUTE_KEY_MAX_LENGTH} characters`)\n }\n}\n\nfunction assertValidAttributeKeyShape(key: string, sourceLabel: string): void {\n if (key.length === 0) {\n throw new Error(`${sourceLabel}: Attribute key must be non-empty`)\n }\n if (key.length > RUN_ATTRIBUTE_KEY_MAX_LENGTH) {\n throw new Error(`${sourceLabel}: Attribute key \"${key}\" exceeds ${RUN_ATTRIBUTE_KEY_MAX_LENGTH} characters`)\n }\n}\n\nfunction assertValidAttributeValue(key: string, value: unknown, sourceLabel: string): asserts value is string {\n if (typeof value !== 'string') {\n throw new Error(`${sourceLabel}: Attribute value for \"${key}\" must be a string`)\n }\n if (value.length > RUN_ATTRIBUTE_VALUE_MAX_LENGTH) {\n throw new Error(`${sourceLabel}: Attribute value for \"${key}\" exceeds ${RUN_ATTRIBUTE_VALUE_MAX_LENGTH} characters`)\n }\n}\n\nfunction assertValidInternalAttribute(key: string, value: string, sourceLabel: string): void {\n if (key === ATTR_TRIGGER) {\n if (!RUN_ATTRIBUTE_TRIGGERS.includes(value as RunAttributeTrigger)) {\n throw new Error(`${sourceLabel}: Attribute value for \"${key}\" must be one of: ${RUN_ATTRIBUTE_TRIGGERS.join(', ')}`)\n }\n return\n }\n if (key === ATTR_RUNNER) {\n if (!RUN_ATTRIBUTE_RUNNERS.includes(value as RunAttributeRunner)) {\n throw new Error(`${sourceLabel}: Attribute value for \"${key}\" must be one of: ${RUN_ATTRIBUTE_RUNNERS.join(', ')}`)\n }\n return\n }\n if (key === ATTR_GATE_RUN) {\n if (value !== 'true') {\n throw new Error(`${sourceLabel}: Attribute value for \"${key}\" must be \"true\"`)\n }\n return\n }\n throw new Error(`${sourceLabel}: Attribute key \"${key}\" uses the reserved prefix \"${INTERNAL_ATTRIBUTE_PREFIX}\"`)\n}\n\nexport function validateUserRunAttributes(input: unknown, sourceLabel = 'run attributes'): RunAttributes {\n if (input === undefined || input === null) return {}\n if (!isPlainRecord(input)) {\n throw new Error(`${sourceLabel}: attributes must be a plain object`)\n }\n\n const attributes = Object.create(null) as RunAttributes\n for (const [key, value] of Object.entries(input)) {\n assertValidUserAttributeKey(key, sourceLabel)\n if (typeof value !== 'string') {\n throw new Error(`${sourceLabel}: Attribute value for \"${key}\" must be a string`)\n }\n if (value.length > RUN_ATTRIBUTE_VALUE_MAX_LENGTH) {\n throw new Error(`${sourceLabel}: Attribute value for \"${key}\" exceeds ${RUN_ATTRIBUTE_VALUE_MAX_LENGTH} characters`)\n }\n attributes[key] = value\n }\n return attributes\n}\n\nexport function validateTrustedRunAttributes(input: unknown, sourceLabel = 'run attributes'): RunAttributes {\n if (input === undefined || input === null) return {}\n if (!isPlainRecord(input)) {\n throw new Error(`${sourceLabel}: attributes must be a plain object`)\n }\n\n const attributes = Object.create(null) as RunAttributes\n for (const [key, value] of Object.entries(input)) {\n assertValidAttributeKeyShape(key, sourceLabel)\n assertValidAttributeValue(key, value, sourceLabel)\n if (key.startsWith(INTERNAL_ATTRIBUTE_PREFIX)) {\n assertValidInternalAttribute(key, value, sourceLabel)\n }\n attributes[key] = value\n }\n return attributes\n}\n\nexport function parseRunAttrFlags(flags: string[] | undefined): ParsedRunAttrFlags {\n const rawAttributes = Object.create(null) as Record<string, string>\n const seen = new Set<string>()\n const duplicateKeys = new Set<string>()\n\n for (const flag of flags ?? []) {\n const separator = flag.indexOf('=')\n if (separator <= 0) {\n throw new Error(`--run-attr must use KEY=VALUE format: \"${flag}\"`)\n }\n const key = flag.slice(0, separator)\n const value = flag.slice(separator + 1)\n if (seen.has(key)) duplicateKeys.add(key)\n seen.add(key)\n rawAttributes[key] = value\n }\n\n return {\n attributes: validateUserRunAttributes(rawAttributes, '--run-attr'),\n duplicateKeys: [...duplicateKeys].sort((left, right) => left.localeCompare(right)),\n }\n}\n\nexport function buildInternalRunAttributes(input: {\n trigger: RunAttributeTrigger\n runner: RunAttributeRunner\n}): RunAttributes {\n return {\n [ATTR_TRIGGER]: input.trigger,\n [ATTR_RUNNER]: input.runner,\n }\n}\n\nexport function mergeRunAttributes(internal: RunAttributes, user: RunAttributes): RunAttributes {\n return {\n ...user,\n ...internal,\n }\n}\n\nexport function sortRunAttributesForDisplay(\n attributes: RunAttributes,\n activeKeys: string[] = [],\n): Array<[string, string]> {\n const entries = Object.entries(attributes)\n const rank = (key: string): [number, number, string] => {\n const activeIndex = activeKeys.indexOf(key)\n if (activeIndex >= 0) return [0, activeIndex, key]\n if (key === ATTR_TRIGGER) return [1, 0, key]\n if (key === ATTR_RUNNER) return [1, 1, key]\n if (key === ATTR_GATE_RUN) return [1, 2, key]\n if (key.startsWith(INTERNAL_ATTRIBUTE_PREFIX)) return [1, 3, key]\n return [2, 0, key]\n }\n\n return entries.sort(([left], [right]) => {\n const leftRank = rank(left)\n const rightRank = rank(right)\n return leftRank[0] - rightRank[0] ||\n leftRank[1] - rightRank[1] ||\n leftRank[2].localeCompare(rightRank[2])\n })\n}\n\nexport function formatRunAttributesBlock(attributes: RunAttributes): string {\n const entries = sortRunAttributesForDisplay(attributes)\n if (entries.length === 0) return ''\n return [\n 'Run attributes:',\n ...entries.map(([key, value]) => ` ${key}=${value}`),\n ].join('\\n')\n}\n","import { createRequire } from 'node:module'\n\nconst require = createRequire(typeof __filename === 'string' ? __filename : import.meta.url)\n\nfunction readPackageVersion(): string {\n try {\n const manifest = require('../package.json') as { version?: unknown }\n if (typeof manifest.version === 'string' && manifest.version.trim()) {\n return manifest.version.trim()\n }\n } catch {\n // Keep public version consumers non-throwing if package metadata is unavailable.\n }\n\n return '0.0.0'\n}\n\nexport const AGENT_QA_VERSION = readPackageVersion()\n\nexport function getAgentQaVersion(): string {\n return AGENT_QA_VERSION\n}\n","import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport { getAgentQaVersion } from '../version.js'\n\nconst require = createRequire(typeof __filename === 'string' ? __filename : import.meta.url)\n\nconst AGENT_QA_NPM_REGISTRY_URL = 'https://registry.npmjs.org/agent-qa'\n\nexport const VERSION_CHECK_CACHE_TTL_MS = 24 * 60 * 60 * 1000\nexport const VERSION_CHECK_TIMEOUT_MS = 5000\n\nexport interface AgentQaUpdateStatus {\n installedVersion: string\n latestVersion?: string\n updateAvailable: boolean\n checkedAt?: string\n}\n\ntype VersionCheckFetch = (\n input: string | URL | Request,\n init?: RequestInit,\n) => Promise<Response>\n\nexport interface VersionCheckOptions {\n cachePath?: string\n fetchImpl?: VersionCheckFetch\n now?: () => Date\n timeoutMs?: number\n cacheTtlMs?: number\n homeDir?: string\n}\n\ninterface VersionCheckCacheFile {\n latestVersion?: string\n checkedAt?: string\n lastAttemptedAt?: string\n}\n\ninterface SemverApi {\n valid(version: string): string | null\n gt(version: string, otherVersion: string): boolean\n}\n\nlet semverApi: SemverApi | undefined\n\nexport function getAgentQaVersionCheckCachePath(homeDir?: string): string {\n return join(homeDir ?? homedir(), '.agent-qa', 'version-check.json')\n}\n\nexport async function getAgentQaUpdateStatus(\n options: VersionCheckOptions = {},\n): Promise<AgentQaUpdateStatus> {\n const installedVersion = getInstalledVersion()\n\n try {\n return await getAgentQaUpdateStatusInternal(installedVersion, options)\n } catch {\n return createStatus(installedVersion)\n }\n}\n\nasync function getAgentQaUpdateStatusInternal(\n installedVersion: string,\n options: VersionCheckOptions,\n): Promise<AgentQaUpdateStatus> {\n const semver = getSemverApi()\n if (!semver) {\n return createStatus(installedVersion)\n }\n\n const now = getNow(options.now)\n const nowMs = now.getTime()\n const nowIso = now.toISOString()\n const cacheTtlMs = getPositiveNumber(options.cacheTtlMs, VERSION_CHECK_CACHE_TTL_MS)\n const timeoutMs = getPositiveNumber(options.timeoutMs, VERSION_CHECK_TIMEOUT_MS)\n const cachePath = options.cachePath ?? getAgentQaVersionCheckCachePath(options.homeDir)\n const cache = await readVersionCheckCache(cachePath)\n const cachedLatestVersion = getValidVersion(cache?.latestVersion, semver)\n const checkedAtMs = getTimestamp(cache?.checkedAt)\n\n if (cachedLatestVersion && checkedAtMs !== undefined && nowMs - checkedAtMs < cacheTtlMs) {\n return createStatus(installedVersion, semver, cachedLatestVersion, cache?.checkedAt)\n }\n\n const lastAttemptedAtMs = getTimestamp(cache?.lastAttemptedAt)\n if (lastAttemptedAtMs !== undefined && nowMs - lastAttemptedAtMs < cacheTtlMs) {\n if (cachedLatestVersion && checkedAtMs !== undefined) {\n return createStatus(installedVersion, semver, cachedLatestVersion, cache?.checkedAt)\n }\n\n return createStatus(installedVersion)\n }\n\n const nextCache = { ...cache, lastAttemptedAt: nowIso }\n const refreshedLatestVersion = await fetchLatestVersion(options.fetchImpl, timeoutMs, semver)\n if (refreshedLatestVersion) {\n const refreshedCache = {\n latestVersion: refreshedLatestVersion,\n checkedAt: nowIso,\n lastAttemptedAt: nowIso,\n }\n await writeVersionCheckCache(cachePath, refreshedCache)\n return createStatus(installedVersion, semver, refreshedLatestVersion, nowIso)\n }\n\n await writeVersionCheckCache(cachePath, nextCache)\n if (cachedLatestVersion && checkedAtMs !== undefined) {\n return createStatus(installedVersion, semver, cachedLatestVersion, cache?.checkedAt)\n }\n\n return createStatus(installedVersion)\n}\n\nfunction getInstalledVersion(): string {\n try {\n return getAgentQaVersion().trim() || '0.0.0'\n } catch {\n return '0.0.0'\n }\n}\n\nfunction getSemverApi(): SemverApi | undefined {\n if (semverApi) return semverApi\n\n try {\n semverApi = require('semver') as SemverApi\n return semverApi\n } catch {\n return undefined\n }\n}\n\nfunction getValidVersion(version: unknown, semver: SemverApi): string | undefined {\n if (typeof version !== 'string') return undefined\n\n try {\n return semver.valid(version) ?? undefined\n } catch {\n return undefined\n }\n}\n\nfunction getTimestamp(value: unknown): number | undefined {\n if (typeof value !== 'string') return undefined\n\n const timestamp = Date.parse(value)\n return Number.isFinite(timestamp) ? timestamp : undefined\n}\n\nfunction getPositiveNumber(value: number | undefined, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback\n}\n\nfunction getNow(now: (() => Date) | undefined): Date {\n try {\n const candidate = now?.()\n if (candidate instanceof Date && Number.isFinite(candidate.getTime())) {\n return candidate\n }\n } catch {\n // Fall through to the system clock.\n }\n\n return new Date()\n}\n\nfunction createStatus(\n installedVersion: string,\n semver?: SemverApi,\n latestVersion?: string,\n checkedAt?: string,\n): AgentQaUpdateStatus {\n if (!latestVersion) {\n return {\n installedVersion,\n updateAvailable: false,\n }\n }\n\n const installedSemver = semver ? getValidVersion(installedVersion, semver) : undefined\n const updateAvailable = Boolean(\n installedSemver &&\n semver &&\n safeSemverGreaterThan(semver, latestVersion, installedSemver),\n )\n\n return {\n installedVersion,\n latestVersion,\n updateAvailable,\n checkedAt,\n }\n}\n\nfunction safeSemverGreaterThan(semver: SemverApi, version: string, otherVersion: string): boolean {\n try {\n return semver.gt(version, otherVersion)\n } catch {\n return false\n }\n}\n\nasync function readVersionCheckCache(cachePath: string): Promise<VersionCheckCacheFile | undefined> {\n try {\n const raw = await readFile(cachePath, 'utf-8')\n const parsed = JSON.parse(raw) as unknown\n if (!isRecord(parsed)) return undefined\n\n return {\n latestVersion: typeof parsed.latestVersion === 'string' ? parsed.latestVersion : undefined,\n checkedAt: typeof parsed.checkedAt === 'string' ? parsed.checkedAt : undefined,\n lastAttemptedAt:\n typeof parsed.lastAttemptedAt === 'string' ? parsed.lastAttemptedAt : undefined,\n }\n } catch {\n return undefined\n }\n}\n\nasync function writeVersionCheckCache(\n cachePath: string,\n cache: VersionCheckCacheFile,\n): Promise<void> {\n try {\n await mkdir(dirname(cachePath), { recursive: true })\n await writeFile(cachePath, JSON.stringify(cache, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n try {\n await chmod(cachePath, 0o600)\n } catch {\n // Cache permissions are best effort.\n }\n } catch {\n // Version checks must never block CLI or dashboard work.\n }\n}\n\nasync function fetchLatestVersion(\n fetchImpl: VersionCheckFetch | undefined,\n timeoutMs: number,\n semver: SemverApi,\n): Promise<string | undefined> {\n try {\n const fetcher = fetchImpl ?? globalThis.fetch?.bind(globalThis)\n if (typeof fetcher !== 'function') return undefined\n\n const response = await fetcher(AGENT_QA_NPM_REGISTRY_URL, {\n headers: { accept: 'application/json' },\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!response.ok) return undefined\n\n const body = (await response.json()) as unknown\n if (!isRecord(body) || !isRecord(body['dist-tags'])) return undefined\n\n return getValidVersion(body['dist-tags'].latest, semver)\n } catch {\n return undefined\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AEzB,UAAM,OAAQ,MAAM,SAAS,KAAK;AAClC,QAAI,CAACA,UAAS,IAAI,KAAK,CAACA,UAAS,KAAK,WAAW,CAAC,EAAG,QAAO;AAE5D,WAAO,gBAAgB,KAAK,WAAW,EAAE,QAAQ,MAAM;AAAA,EACzD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAASA,UAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;","names":["import_zod","import_zod","import_zod","ms","bytes","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_ms","ms","import_zod","path","import_zod","import_agent_qa_ids","HookIdSchema","import_zod","import_ms","import_agent_qa_ids","ms","pc","path","import_promises","import_node_path","import_promises","import_yaml","parseYaml","import_yaml","import_agent_qa_runner","import_agent_qa_schema","import_node_path","resolvePath","import_node_fs","import_node_path","import_agent_qa_runner","import_node_path","import_node_fs","import_node_path","path","import_promises","import_node_path","path","import_promises","import_agent_qa_runner","import_node_crypto","import_promises","import_node_path","path","import_node_fs","import_node_path","require","module","import_node_crypto","loadedDeclarations","module","validateDeclaration","import_zod","import_node_crypto","import_picocolors","pc","import_agent_qa_runner","import_node_module","import_meta","require","import_node_fs","import_node_path","resolvePath","isPlainObject","import_promises","import_node_fs","import_node_path","import_yaml","import_glob","import_promises","import_node_path","import_yaml","parseYaml","import_node_path","path","relative","import_node_fs","import_node_path","path","parseYaml","path","basename","testPatterns","suitePatterns","import_picocolors","pc","import_agent_qa_runner","import_agent_qa_ids","generateSharedHookId","import_agent_qa_ids","generateSharedRunId","isSharedCanonicalRunId","import_node_module","import_meta","require","import_promises","import_node_module","import_node_os","import_node_path","import_meta","require","isRecord"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/schema/config-schema.ts","../src/schema/workspace-schema.ts","../src/schema/services-schema.ts","../src/schema/primitives.ts","../src/schema/knowledge-schema.ts","../src/schema/retired-keys.ts","../src/schema/registry-schema.ts","../src/auth-state/schema.ts","../src/schema/use-schema.ts","../src/schema/analytics-schema.ts","../src/schema/test-schema.ts","../src/schema/resolve-knowledge-root.ts","../src/schema/suite-schema.ts","../src/hooks/schema.ts","../src/parser/yaml-parser.ts","../src/parser/errors.ts","../src/validation/yaml-fault.ts","../src/parser/file-resolver.ts","../src/parser/suite-parser.ts","../src/parser/cst-patch.ts","../src/agent/token-budget.ts","../src/agent/index.ts","../src/mobile/xml-parser.ts","../src/mobile/role-map.ts","../src/mobile/element-resolver.ts","../src/mobile/gestures.ts","../src/mobile/launch-resolver.ts","../src/mobile/appium-executable.ts","../src/mobile/webview-scrollers.ts","../src/auth-state/resolver.ts","../src/runtime-paths.ts","../src/auth-state/store.ts","../src/auth-state/runtime.ts","../src/auth-state/hook-env.ts","../src/auth/store.ts","../src/auth/plugin-registry.ts","../src/auth/resolver.ts","../src/plugin-loader-util.ts","../src/auth/plugin-loader.ts","../src/auth/pkce.ts","../src/auth/fetch-wrapper.ts","../src/providers/plugin-loader.ts","../src/logging/types.ts","../src/logging/log-manager.ts","../src/logging/cli-formatter.ts","../src/logging/run-text-output.ts","../src/suite/member.ts","../src/validation/validate.ts","../src/hooks/parser.ts","../src/utils/path-validation.ts","../src/workspace/workspace-paths.ts","../src/validation/formatter.ts","../src/validation/coord-bounds.ts","../src/hooks/index.ts","../src/ids/hook-id.ts","../src/ids/run-id.ts","../src/run-attributes.ts","../src/version.ts","../src/version-check/index.ts"],"sourcesContent":["export * from './types/index.js'\nexport * from './schema/index.js'\nexport * from './parser/index.js'\nexport { parseAllTestBindings } from './parser/yaml-parser.js'\nexport type { ParsedTestBinding, ParseAllTestBindingsResult } from './parser/yaml-parser.js'\nexport * from './agent/index.js'\nexport * from './mobile/index.js'\nexport * from './auth-state/index.js'\nexport * from './auth/index.js'\nexport * from './providers/index.js'\nexport * from './logging/index.js'\nexport * from './suite/index.js'\nexport * from './validation/index.js'\nexport * from './hooks/index.js'\nexport * from './ids/index.js'\nexport * from './workspace/index.js'\nexport * from './run-attributes.js'\nexport * from './version.js'\nexport * from './version-check/index.js'\nexport * from './runtime-paths.js'\nexport { isPathInsideDir } from './utils/path-validation.js'\n","import { z } from 'zod'\nimport { WorkspaceSchema } from './workspace-schema.js'\nimport { ServicesSchema } from './services-schema.js'\nimport { KnowledgeConfigSchema } from './knowledge-schema.js'\nimport { retiredKeyScan } from './retired-keys.js'\nimport { RegistrySchema } from './registry-schema.js'\nimport { UseSchema } from './use-schema.js'\nimport { AnalyticsSchema } from './analytics-schema.js'\n\nexport const AuthPluginDeclarationSchema = z.union([\n z.object({\n package: z.string().trim().min(1),\n }).strict(),\n z.object({\n path: z.string().trim().min(1),\n }).strict(),\n])\n\n// Provider plugins load in-process with full Node access; keep them first-party-only\n// until a container sandbox exists.\nexport const ProviderPluginDeclarationSchema = z.union([\n z.object({\n package: z.string().trim().min(1),\n }).strict(),\n z.object({\n path: z.string().trim().min(1),\n }).strict(),\n])\n\nexport const PluginsSchema = z.object({\n auth: z.array(AuthPluginDeclarationSchema).optional().default([]),\n providers: z.array(ProviderPluginDeclarationSchema).optional().default([]),\n}).strict()\n\nconst AgentQaConfigSchemaInner = z.object({\n workspace: WorkspaceSchema,\n services: ServicesSchema.prefault({}).optional(),\n // `.prefault` runs the inner defaults; zod 4's `.default()` short-circuits without parsing.\n knowledge: KnowledgeConfigSchema.prefault({}),\n registry: RegistrySchema.optional(),\n use: UseSchema.optional(),\n plugins: PluginsSchema.optional(),\n analytics: AnalyticsSchema.optional(),\n // There is no `safety` section: a file that still declares one gets the normal strict\n // unrecognized-key error.\n}).strict()\n.superRefine((val, ctx) => {\n const llms = val.registry?.llms ?? []\n const names = llms.map(c => c.name)\n const dupes = names.filter((n, i) => names.indexOf(n) !== i)\n for (const dupe of new Set(dupes)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['registry', 'llms'],\n message: `Duplicate LLM config name: \"${dupe}\"`,\n })\n }\n if ((val.use as any)?.platform) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['use', 'platform'],\n message: 'use.platform cannot be set at global config level. Set platform in test or suite YAML instead.',\n })\n }\n if (val.use?.llm && !names.includes(val.use.llm)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['use', 'llm'],\n message: `use.llm \"${val.use.llm}\" does not match any name in registry.llms`,\n })\n }\n})\n\n// The scan runs before the strict object: zod skips refinements after a strict parse rejects.\nexport const AgentQaConfigSchema = retiredKeyScan.pipe(AgentQaConfigSchemaInner)\n\nexport { WorkspaceSchema } from './workspace-schema.js'\nexport { AuthStateConfigSchema, ServicesSchema } from './services-schema.js'\nexport { KnowledgeConfigSchema } from './knowledge-schema.js'\nexport { RegistrySchema } from './registry-schema.js'\nexport {\n AuthStateUseSchema,\n MobileAppStateSchema,\n MobileUseSchema,\n MobileUseOverrideSchema,\n UseSchema,\n UseOverrideSchema,\n normalizeAuthStateUse,\n type NormalizedAuthStateUse,\n} from './use-schema.js'\nexport { AnalyticsSchema } from './analytics-schema.js'\nexport * from './primitives.js'\n","import { z } from 'zod'\n\nexport const WorkspaceSchema = z.object({\n testMatch: z.array(z.string().min(1)).min(1),\n suiteMatch: z.array(z.string().min(1)).min(1),\n testPathIgnore: z.array(z.string()).optional(),\n hooksFile: z.string().min(1, 'hooksFile is required.'),\n envFile: z.string().min(1, 'envFile is required.'),\n secretsFile: z.string().min(1, 'secretsFile is required.'),\n}).strict()\n","import { z } from 'zod'\nimport { SizeString } from './primitives.js'\n\n/**\n * Whether a configured value is an ABSOLUTE `http:`/`https:` URL.\n *\n * FILE-LOCAL, DELIBERATELY, unlike `isLoopbackHost` below, which is exported for the dashboard's\n * bind guard in another package. This one has exactly one decision site — the parse boundary,\n * immediately below. Exporting it would advertise a second place to make the same check, and the\n * whole point of a parse-time guard is that there is no second place: nothing downstream should be\n * re-deciding whether the base is safe.\n *\n * A RELATIVE VALUE IS REFUSED, not resolved. `new URL(value)` with no base throws for\n * `/relative/only` and for `not-a-url`, and the scheme test refuses `javascript:` and `mailto:`\n * — which parse fine and are exactly the shapes that must not reach an `href`.\n */\nfunction isAbsoluteHttpUrl(value: string): boolean {\n try {\n const url = new URL(value)\n return url.protocol === 'http:' || url.protocol === 'https:'\n } catch {\n return false\n }\n}\n\nexport const DashboardConfigSchema = z.object({\n port: z.number().optional(),\n dbPath: z.string().optional(),\n artifactsDir: z.string().optional(),\n // Only an absolute http(s) URL: the base composes an `href` inside the served App document.\n baseUrl: z.string().refine(\n isAbsoluteHttpUrl,\n { message: 'services.dashboard.baseUrl must be an absolute http(s) URL' },\n ).optional(),\n workspace: z.string().optional(),\n // The run service and the other local doors are tokenless, so this block declares no token key.\n // The interface the dashboard binds. A plain string, because the pre-listen bind guard refuses\n // any non-loopback value at runtime, as the security refusal it is rather than a config-shape\n // error, and a loopback spelling other than the default (`localhost`, `::1`) stays configurable.\n host: z.string().trim().min(1).optional(),\n}).strict()\n\n/**\n * The one member set for \"this host is loopback\", used by the dashboard's pre-listen bind guard in\n * `startServer`, which refuses a non-loopback dashboard host at runtime with no exemption.\n */\nexport const LOOPBACK_HOSTS: readonly string[] = Object.freeze(['localhost', '127.0.0.1', '::1'])\n\n/** Whether a configured host names a loopback interface. The one predicate over the one set. */\nexport function isLoopbackHost(host: string): boolean {\n return LOOPBACK_HOSTS.includes(host.trim())\n}\n\n// Whether the dashboard co-hosts the MCP endpoint, and the port it listens on.\nexport const McpConfigSchema = z.object({\n enabled: z.boolean().optional(),\n port: z.number().int().min(1).max(65535).optional(),\n}).strict()\n\nexport const CacheConfigSchema = z.object({\n dir: z.string(),\n}).strict()\n\nexport const AuthStateConfigSchema = z.object({\n dir: z.string().trim().min(1),\n}).strict()\n\nexport const LoggingConfigSchema = z.object({\n level: z.enum(['silent', 'error', 'warn', 'info', 'debug']),\n}).strict()\n\nexport const RecordingConfigSchema = z.object({\n enabled: z.boolean().default(true),\n keepFailuresOnly: z.boolean().optional(),\n}).strict()\n\nexport const AccessibilityConfigSchema = z.object({\n enabled: z.boolean(),\n standard: z.enum(['wcag2a', 'wcag2aa', 'wcag2aaa']).optional(),\n runAfter: z.enum(['every-step', 'test-end']).optional(),\n failOnViolation: z.boolean().optional(),\n disableRules: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n}).strict()\n\nexport const VisionServiceSchema = z.object({\n screenshotSize: SizeString.optional(),\n effectiveResolution: z.number().positive().int().optional(),\n}).strict()\n\nexport const ServicesSchema = z.object({\n dashboard: DashboardConfigSchema.optional(),\n mcp: McpConfigSchema.optional(),\n cache: CacheConfigSchema.optional(),\n authState: AuthStateConfigSchema.optional(),\n logging: LoggingConfigSchema.optional(),\n // Parse omitted containers too, while retaining optional authoring/input compatibility.\n recording: RecordingConfigSchema.prefault({}).optional(),\n accessibility: AccessibilityConfigSchema.optional(),\n vision: VisionServiceSchema.optional(),\n}).strict()\n","import { z } from 'zod'\nimport ms from 'ms'\nimport bytes from 'bytes'\n\nexport const DurationString = z.string()\n .refine((v) => ms(v as ms.StringValue) !== undefined, {\n message: 'Invalid duration format (e.g., \"30s\", \"5m\", \"1h\")',\n })\n .transform((v) => ms(v as ms.StringValue) as number)\n\nconst VALID_SIZE_RE = /^\\d+(?:\\.\\d+)?\\s*(?:b|kb|mb|gb|tb|k|m|g|t)$/i\n\nfunction normalizeSize(v: string): string {\n return v.replace(/^(\\d+(?:\\.\\d+)?)(k|m|g|t)$/i, '$1$2b')\n}\n\nexport const SizeString = z.string()\n .refine((v) => VALID_SIZE_RE.test(v.trim()) && bytes(normalizeSize(v)) !== null, {\n message: 'Invalid size format (e.g., \"256k\", \"1m\", \"5mb\")',\n })\n .transform((v) => bytes(normalizeSize(v)) as number)\n\nconst COMPATIBLE_PROVIDERS = new Set(['openai-compatible', 'anthropic-compatible'])\nconst SENSITIVE_HEADER_TERMS = ['authorization', 'cookie', 'x-api-key', 'api-key', 'token', 'secret']\nconst CONTROL_CHARACTER_RE = /[\\x00-\\x1F\\x7F]/\n\nfunction validateProviderHeaders(headers: Record<string, string>, ctx: z.RefinementCtx): void {\n const seen = new Set<string>()\n\n for (const [rawKey, rawValue] of Object.entries(headers)) {\n const key = rawKey.trim()\n const value = rawValue.trim()\n const normalizedKey = key.toLowerCase()\n\n if (key === '') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['providerHeaders'],\n message: 'Provider header keys cannot be empty.',\n })\n continue\n }\n\n if (seen.has(normalizedKey)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['providerHeaders'],\n message: `Duplicate provider header \"${key}\" is not allowed.`,\n })\n }\n seen.add(normalizedKey)\n\n if (CONTROL_CHARACTER_RE.test(key) || CONTROL_CHARACTER_RE.test(value)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['providerHeaders'],\n message: `Provider header \"${key}\" cannot contain control characters.`,\n })\n }\n\n const sensitiveTerm = SENSITIVE_HEADER_TERMS.find(term => normalizedKey.includes(term))\n if (sensitiveTerm) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['providerHeaders'],\n message: `Provider header \"${key}\" cannot contain auth-like term \"${sensitiveTerm}\".`,\n })\n }\n }\n}\n\nfunction validateModelConfig(\n config: { provider?: string; baseURL?: string; providerHeaders?: Record<string, string> },\n ctx: z.RefinementCtx,\n) {\n if (\n config.provider\n && COMPATIBLE_PROVIDERS.has(config.provider)\n && (!config.baseURL || config.baseURL.trim() === '')\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['baseURL'],\n message: `Base URL is required for ${config.provider} providers.`,\n })\n }\n\n if (config.providerHeaders !== undefined && config.provider !== 'anthropic-compatible') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['providerHeaders'],\n message: 'providerHeaders can only be used with anthropic-compatible providers.',\n })\n }\n\n if (config.providerHeaders) {\n validateProviderHeaders(config.providerHeaders, ctx)\n }\n}\n\nconst REMOVED_LLM_PROVIDER_VALUES = new Set([\n 'anthropic',\n 'openai',\n 'google',\n 'ollama',\n 'lmstudio',\n 'custom',\n])\n\nconst LLMProviderIdSchema = z.string()\n .regex(/^[a-z0-9][a-z0-9-]*$/, 'Provider must be lowercase alphanumeric + hyphens, starting with alphanumeric')\n .superRefine((provider, ctx) => {\n if (REMOVED_LLM_PROVIDER_VALUES.has(provider)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Provider \"${provider}\" has been removed. Use a compatible provider or an auth plugin provider ID.`,\n })\n }\n })\n\nconst ModelConfigBaseSchema = z.object({\n provider: LLMProviderIdSchema,\n model: z.string(),\n baseURL: z.string().optional(),\n providerHeaders: z.record(z.string(), z.string()).optional(),\n vision: z.boolean().default(true),\n}).strict()\n\nexport const ModelConfigSchema = ModelConfigBaseSchema.superRefine(validateModelConfig)\n\nexport const NameSlugSchema = z.string()\n .regex(/^[a-z0-9][a-z0-9.-]*$/, 'Name must be lowercase letters, digits, hyphens and dots, starting with a letter or digit')\n\nexport const NamedLLMConfigSchema = ModelConfigBaseSchema.extend({\n name: NameSlugSchema,\n contextWindow: SizeString.optional(),\n}).strict().superRefine(validateModelConfig)\n\nexport const TimeoutConfigSchema = z.object({\n step: DurationString,\n test: DurationString,\n navigation: DurationString.describe(\n 'How long a web page load or URL wait can take. Default 2m. Android and iOS runs do not use it.',\n ),\n}).strict()\n\nexport const BrowserConfigSchema = z.object({\n name: z.enum(['chromium', 'firefox', 'webkit']),\n headless: z.boolean(),\n viewport: z.object({\n width: z.number(),\n height: z.number(),\n }).strict().optional(),\n}).strict()\n\n// Positive integers with no unlimited value; `resolvePlannerLimits` supplies the default.\nexport const PlannerConfigSchema = z.object({\n maxActions: z.number().int().positive().optional(),\n maxPlanningTurns: z.number().int().positive().optional(),\n previousStepCount: z.number(),\n}).strict()\n\nexport const LogCaptureConfigSchema = z.object({\n console: z.boolean(),\n network: z.boolean(),\n}).strict()\n","import { z } from 'zod'\n\n// A pure string predicate; composition roots resolve the path through `resolve-knowledge-root.ts`.\nconst isRepoRelative = (dir: string): boolean =>\n !/^[/\\\\]|^[A-Za-z]:[\\\\/]/.test(dir) && !/^\\.\\.(?:[/\\\\]|$)/.test(dir)\n\nexport const KnowledgeConfigSchema = z.object({\n dir: z.string().trim().min(1)\n .refine(isRepoRelative, {\n message: 'knowledge.dir must be repo-relative — the committed knowledge root must live inside the repo for PR review and the committed .gitignore split',\n })\n .default('agent-qa-knowledge'),\n}).strict()\n","import { z } from 'zod'\n\n// Refusals for removed config keys. This scan is a zod pipe PRE-stage in front of the strict root\n// schema — a superRefine chained after .strict() never runs when strict rejects a value (verified\n// on zod 4.6.7), so these messages must fire first. The scan only ADDS issues; the strict stage-B\n// parse remains the acceptance authority. Every issue carries params.retired. Keys removed in v2\n// also carry params.hardCut, so the CLI closes the error with the hard-cut steps; any other removed\n// key closes with the ordinary key fix.\nconst RETIRED_MEMORY_KEY_MESSAGES: Record<string, string> = {\n dir: 'services.memory.dir was removed in v2 — use knowledge.dir (default agent-qa-knowledge)',\n enabled: 'services.memory.enabled was removed in v2 — memory is always on; delete this key (no disable switch)',\n provider: 'services.memory.provider was removed in v2 — internalized — delete this key',\n minTrust: 'services.memory.minTrust was removed in v2 — internalized — delete this key',\n maxInjections: 'services.memory.maxInjections was removed in v2 — internalized — delete this key',\n curatorEnabled: 'services.memory.curatorEnabled was removed in v2 — internalized — delete this key',\n curatorLockTimeout: 'services.memory.curatorLockTimeout was removed in v2 — internalized — delete this key',\n trustConfirmDelta: 'services.memory.trustConfirmDelta was removed in v2 — internalized — delete this key',\n trustContradictDelta: 'services.memory.trustContradictDelta was removed in v2 — internalized — delete this key',\n ablationEnabled: 'services.memory.ablationEnabled was removed — no ablation exists',\n circuitBreakerEnabled: 'services.memory.circuitBreakerEnabled was removed — no circuit breaker exists',\n circuitBreakerWindowSize: 'services.memory.circuitBreakerWindowSize was removed — no circuit breaker exists',\n circuitBreakerBaselineSize: 'services.memory.circuitBreakerBaselineSize was removed — no circuit breaker exists',\n circuitBreakerThreshold: 'services.memory.circuitBreakerThreshold was removed — no circuit breaker exists',\n}\n\nconst RETIRED_EVAL_KEY_MESSAGES: Record<string, string> = {\n gate1: 'eval.gate1 was removed: memory is no longer screened by replay before promotion. Delete this block.',\n gate2: 'eval.gate2 was removed: completed runs no longer replay served memory. Delete this block.',\n adversarial: 'eval.adversarial was removed: runs no longer stage adversarial probes. Delete this block.',\n seeding: 'eval.seeding was removed: runs no longer seed an eval corpus. Delete this block.',\n judge: 'eval.judge was removed: pass --judge <name> to agent-qa eval replay. Delete this key.',\n judges: 'eval.judges was removed: repeat --judge <name> on agent-qa eval replay. Delete this key.',\n judgeAllowSameFamily:\n 'eval.judgeAllowSameFamily was removed: pass --judge-allow-same-family to agent-qa eval replay. Delete this key.',\n k: 'eval.k was removed: pass --k <n> to agent-qa eval replay. Delete this key.',\n seed: 'eval.seed was removed: pass --seed <n> to agent-qa eval replay. Delete this key.',\n}\n\nconst RETIRED_STEP_KEY_MESSAGES: Record<string, string> = {\n retries:\n 'steps[].retries was removed: a test retries as a whole; set meta.retries. Delete this line.',\n screenshot:\n 'steps[].screenshot was removed: screenshots are set per run; pass --screenshot-mode every-step to agent-qa run. Delete this line.',\n}\n\nconst RETIRED_EVAL_BLOCK_MESSAGE =\n 'eval was removed: agent-qa eval replay takes its settings as flags. Delete this block.'\n\nconst RETIRED_ALLOW_PRODUCTION_MESSAGE =\n 'allowProduction was removed: production targets run like any other target. Delete this line.'\n\nconst RETIRED_REGISTRY_PROVIDERS_MESSAGE =\n 'registry.providers was removed: BrowserStack is no longer supported; runs use local Playwright and Appium. Delete this block.'\n\nconst RETIRED_DEVICE_TRANSPORT_MESSAGE =\n 'registry.devices.<name>.transport was removed: devices run on local Appium. Delete this line.'\n\nconst RETIRED_APP_BROWSERSTACK_MESSAGE =\n 'registry.targets.<name>.app.browserstack was removed: BrowserStack is no longer supported; app.path is the app file. Delete this line.'\n\nconst RETIRED_CACHE_TTL_MESSAGE =\n 'services.cache.ttl was removed: cached plans do not expire by age. Delete this line.'\n\nconst RETIRED_MCP_KEY_MESSAGES: Record<string, string> = {\n host: 'services.mcp.host was removed: agent-qa mcp always listens on 127.0.0.1. Delete this line.',\n path: 'services.mcp.path was removed: the MCP server answers on any path. Delete this line.',\n transport:\n 'services.mcp.transport was removed: agent-qa mcp uses stdio, or HTTP with --http. Delete this line.',\n}\n\nconst RETIRED_RUN_AFTER_NAVIGATION_MESSAGE =\n 'services.accessibility.runAfter: navigation was removed: it never ran a check. Use test-end, or delete the line for every-step.'\n\nconst RETIRED_KNOWLEDGE_KEY_MESSAGES: Record<string, string> = {\n contextBudgetTokens:\n \"knowledge.contextBudgetTokens was removed: agent-qa sizes each run's knowledge itself. Delete this line.\",\n commitArtifacts:\n 'knowledge.commitArtifacts was removed: knowledge bundles never commit images. Delete this line.',\n}\n\nconst RETIRED_LOCAL_PROVIDERS_MESSAGE =\n 'providers was removed: BrowserStack is no longer supported. Delete this block.'\n\nconst RETIRED_LOCAL_APP_BROWSERSTACK_MESSAGE =\n 'apps.<name>.browserstack was removed: BrowserStack is no longer supported; apps.<name>.path is the app file. Delete this line.'\n\n// The old refilling planner key is cut with no alias, migration or fallback. The same message\n// fires for the project config and for test and suite `use` overrides.\nexport const RETIRED_MAX_SUB_ACTIONS_MESSAGE =\n 'use.planner.maxSubActions was removed in v2 — it was a refilling iteration count; set use.planner.maxActions (default 30) and use.planner.maxPlanningTurns (default 30)'\n\nconst RETIRED_PLANNER_KEY = 'maxSubActions'\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction hasRetiredPlannerKey(use: unknown): boolean {\n return isPlainObject(use) && isPlainObject(use.planner) && Object.hasOwn(use.planner, RETIRED_PLANNER_KEY)\n}\n\nexport const retiredKeyScan = z.any().superRefine((value, ctx) => {\n if (!isPlainObject(value)) return\n\n if (isPlainObject(value.services) && value.services.memory !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true, hardCut: true },\n path: ['services', 'memory'],\n message: 'services.memory was removed in v2 — the memory config surface collapsed into the top-level knowledge block',\n })\n const memory = value.services.memory\n if (isPlainObject(memory)) {\n for (const key of Object.keys(memory)) {\n const message = RETIRED_MEMORY_KEY_MESSAGES[key]\n if (message) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true, hardCut: true },\n path: ['services', 'memory', key],\n message,\n })\n }\n }\n }\n }\n\n if (isPlainObject(value.workspace) && value.workspace.agentRules !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true, hardCut: true },\n path: ['workspace', 'agentRules'],\n message: 'workspace.agentRules was removed in v2 — rules dissolve into agent-qa-knowledge/policies/<scope>.md files',\n })\n }\n\n if (Object.hasOwn(value, 'eval')) {\n let named = 0\n if (isPlainObject(value.eval)) {\n for (const key of Object.keys(value.eval)) {\n if (Object.hasOwn(RETIRED_EVAL_KEY_MESSAGES, key)) {\n named++\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['eval', key],\n message: RETIRED_EVAL_KEY_MESSAGES[key],\n })\n }\n }\n }\n if (named === 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['eval'],\n message: RETIRED_EVAL_BLOCK_MESSAGE,\n })\n }\n }\n\n if (Object.hasOwn(value, 'allowProduction')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['allowProduction'],\n message: RETIRED_ALLOW_PRODUCTION_MESSAGE,\n })\n }\n\n if (isPlainObject(value.registry) && Object.hasOwn(value.registry, 'providers')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['registry', 'providers'],\n message: RETIRED_REGISTRY_PROVIDERS_MESSAGE,\n })\n }\n\n if (isPlainObject(value.registry) && isPlainObject(value.registry.devices)) {\n for (const [name, device] of Object.entries(value.registry.devices)) {\n if (isPlainObject(device) && Object.hasOwn(device, 'transport')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['registry', 'devices', name, 'transport'],\n message: RETIRED_DEVICE_TRANSPORT_MESSAGE,\n })\n }\n }\n }\n\n if (isPlainObject(value.registry) && isPlainObject(value.registry.targets)) {\n for (const [name, target] of Object.entries(value.registry.targets)) {\n if (isPlainObject(target) && isPlainObject(target.app) && Object.hasOwn(target.app, 'browserstack')) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['registry', 'targets', name, 'app', 'browserstack'],\n message: RETIRED_APP_BROWSERSTACK_MESSAGE,\n })\n }\n }\n }\n\n if (\n isPlainObject(value.services) &&\n isPlainObject(value.services.cache) &&\n Object.hasOwn(value.services.cache, 'ttl')\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['services', 'cache', 'ttl'],\n message: RETIRED_CACHE_TTL_MESSAGE,\n })\n }\n\n if (isPlainObject(value.services) && isPlainObject(value.services.mcp)) {\n for (const key of Object.keys(value.services.mcp)) {\n if (Object.hasOwn(RETIRED_MCP_KEY_MESSAGES, key)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['services', 'mcp', key],\n message: RETIRED_MCP_KEY_MESSAGES[key],\n })\n }\n }\n }\n\n if (\n isPlainObject(value.services) &&\n isPlainObject(value.services.accessibility) &&\n value.services.accessibility.runAfter === 'navigation'\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['services', 'accessibility', 'runAfter'],\n message: RETIRED_RUN_AFTER_NAVIGATION_MESSAGE,\n })\n }\n\n if (isPlainObject(value.knowledge)) {\n for (const key of Object.keys(value.knowledge)) {\n if (Object.hasOwn(RETIRED_KNOWLEDGE_KEY_MESSAGES, key)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: ['knowledge', key],\n message: RETIRED_KNOWLEDGE_KEY_MESSAGES[key],\n })\n }\n }\n }\n\n if (hasRetiredPlannerKey(value.use)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true, hardCut: true },\n path: ['use', 'planner', RETIRED_PLANNER_KEY],\n message: RETIRED_MAX_SUB_ACTIONS_MESSAGE,\n })\n }\n})\n\n// Refusals for removed agent-qa.local.yaml keys. Both local-file readers call this on the raw YAML\n// value before they normalize it. The message names the file and each key's path, never a value.\nexport function refuseRetiredLocalBindings(raw: unknown, filePath: string): void {\n if (!isPlainObject(raw)) return\n\n const issues: Array<{ path: string; message: string }> = []\n if (Object.hasOwn(raw, 'providers')) {\n issues.push({ path: 'providers', message: RETIRED_LOCAL_PROVIDERS_MESSAGE })\n }\n if (isPlainObject(raw.apps)) {\n for (const [name, app] of Object.entries(raw.apps)) {\n if (isPlainObject(app) && Object.hasOwn(app, 'browserstack')) {\n issues.push({ path: `apps.${name}.browserstack`, message: RETIRED_LOCAL_APP_BROWSERSTACK_MESSAGE })\n }\n }\n }\n if (issues.length === 0) return\n\n throw new Error(\n [`${filePath}:`, ...issues.map(issue => ` ${issue.path}: ${issue.message}`)].join('\\n'),\n )\n}\n\n// The pre-stage for a test or suite `use` override, for the same strict-parse reason as above.\nexport const retiredUseKeyScan = z.any().superRefine((value, ctx) => {\n if (hasRetiredPlannerKey(value)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true, hardCut: true },\n path: ['planner', RETIRED_PLANNER_KEY],\n message: RETIRED_MAX_SUB_ACTIONS_MESSAGE,\n })\n }\n})\n\n// Pre-stage for a test step: the strict step union would otherwise report a generic error.\nexport const retiredStepKeyScan = z.any().superRefine((value, ctx) => {\n if (!isPlainObject(value)) return\n for (const [key, message] of Object.entries(RETIRED_STEP_KEY_MESSAGES)) {\n if (!Object.hasOwn(value, key)) continue\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n params: { retired: true },\n path: [key],\n message,\n })\n }\n})\n","import { z } from 'zod'\nimport { NamedLLMConfigSchema } from './primitives.js'\nimport { TargetNameSchema } from '../auth-state/schema.js'\n\nfunction isAbsoluteAppPath(value: string): boolean {\n return value.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\n}\n\nexport const AppInstallSchema = z.object({\n path: z.string()\n .refine((v) => !isAbsoluteAppPath(v), { message: 'app.path must be relative' })\n .optional(),\n}).strict()\n\nexport const TargetSchema = z.object({\n product: z.string()\n .refine(\n (v) => !/\\.\\./.test(v) && !/[/\\\\]/.test(v) && !/\\0/.test(v),\n { message: 'product must not contain \"..\", \"/\", \"\\\\\", or null bytes' }\n )\n .optional(),\n platform: z.enum(['web', 'android', 'ios']),\n bundleId: z.string().optional(),\n appPackage: z.string().optional(),\n appActivity: z.string().optional(),\n app: AppInstallSchema.optional(),\n url: z.string().optional(),\n // A label only: agent-qa runs every target the same way, whatever it declares.\n environment: z\n .enum(['local', 'shared', 'production'])\n .optional()\n .describe(\"A label for this target's environment. agent-qa runs every target the same way.\"),\n}).strict().superRefine((val, ctx) => {\n if (val.platform === 'web' && !val.url) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Web targets must have a url' })\n }\n})\n\nexport const DeviceProfileSchema = z.object({\n platform: z.enum(['android', 'ios']),\n match: z.record(z.string(), z.unknown()).optional().default({}),\n}).strict().superRefine((val, ctx) => {\n const androidOnly = ['avd', 'serial', 'appPackage', 'appActivity', 'automationName', 'browserName', 'platformVersion']\n const iosOnly = ['udid', 'bundleId', 'automationName', 'platformVersion']\n const allowed = val.platform === 'android' ? androidOnly : iosOnly\n for (const key of Object.keys(val.match)) {\n if (!allowed.includes(key)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['match', key],\n message: `Match field \"${key}\" is not valid for an ${val.platform} device. Allowed: ${allowed.join(', ')}`,\n })\n }\n }\n})\n\nexport const RegistrySchema = z.object({\n llms: z.array(NamedLLMConfigSchema).optional().default([]),\n targets: z.record(TargetNameSchema, TargetSchema).optional(),\n devices: z.record(z.string(), DeviceProfileSchema).optional(),\n}).strict()\n","import { z } from 'zod'\n\nexport const AUTH_STATE_SCHEMA_VERSION = 2\nexport const AUTH_STATE_SLUG_PATTERN = /^[a-z][a-z0-9-]*[a-z0-9]$/\n\nexport const AuthStateNameSchema = z.string().regex(\n AUTH_STATE_SLUG_PATTERN,\n 'Auth state name must match ^[a-z][a-z0-9-]*[a-z0-9]$',\n)\n\nexport const TargetNameSchema = z.string().regex(\n AUTH_STATE_SLUG_PATTERN,\n 'Target name must match ^[a-z][a-z0-9-]*[a-z0-9]$',\n)\n\nexport const AuthStateMetadataSchema = z.object({\n version: z.literal(AUTH_STATE_SCHEMA_VERSION),\n kind: z.literal('web'),\n target: TargetNameSchema,\n name: AuthStateNameSchema,\n capturedAt: z.string().datetime(),\n}).strict()\n\nexport type AuthStateMetadata = z.infer<typeof AuthStateMetadataSchema>\n\n","import { z } from 'zod'\nimport {\n BrowserConfigSchema,\n DurationString,\n TimeoutConfigSchema,\n PlannerConfigSchema,\n LogCaptureConfigSchema,\n} from './primitives.js'\nimport { AuthStateNameSchema } from '../auth-state/schema.js'\n\nexport const MobileAppStateSchema = z.enum(['preserve', 'reset'])\n\nexport const MobileUseSchema = z.object({\n appState: MobileAppStateSchema,\n}).strict()\n\nexport const MobileUseOverrideSchema = z.object({\n appState: MobileAppStateSchema.optional(),\n}).strict()\n\nexport const AuthStateUseSchema = z.union([\n AuthStateNameSchema,\n z.object({\n name: AuthStateNameSchema,\n load: z.boolean().optional(),\n capture: z.boolean().optional(),\n }).strict(),\n])\n\nexport interface NormalizedAuthStateUse {\n name: string\n load: boolean\n capture: boolean\n}\n\nexport function normalizeAuthStateUse(\n use: { authState?: unknown } | undefined,\n): NormalizedAuthStateUse | undefined {\n const parsed = AuthStateUseSchema.safeParse(use?.authState)\n if (!parsed.success) return undefined\n\n if (typeof parsed.data === 'string') {\n return {\n name: parsed.data,\n load: true,\n capture: false,\n }\n }\n\n return {\n name: parsed.data.name,\n load: parsed.data.load ?? true,\n capture: parsed.data.capture ?? false,\n }\n}\n\nexport const UseSchema = z.object({\n browser: BrowserConfigSchema.optional(),\n mobile: MobileUseSchema.optional(),\n timeout: TimeoutConfigSchema.optional(),\n planner: PlannerConfigSchema.optional(),\n logCapture: LogCaptureConfigSchema.optional(),\n cache: z.boolean().optional(),\n llm: z.string().optional(),\n // Precedence: CLI `--build-tag`, then `AGENT_QA_BUILD_TAG`, then this key.\n buildTag: z.string().trim().min(1).optional(),\n // Runs one run's members concurrently; absent or false runs one member at a time.\n parallel: z.boolean().optional(),\n // Not defaulted, so the parsed type is unchanged; `resolveEffectiveWorkers` owns the default.\n workers: z.number().int().positive().optional(),\n}).strict()\n\nexport const UseOverrideSchema = z.object({\n browser: z.object({\n name: z.enum(['chromium', 'firefox', 'webkit']).optional(),\n headless: z.boolean().optional(),\n viewport: z.object({\n width: z.number().optional(),\n height: z.number().optional(),\n }).strict().optional(),\n }).strict().optional(),\n timeout: z.object({\n step: DurationString.optional(),\n test: DurationString.optional(),\n navigation: DurationString.optional().describe(\n 'How long a web page load or URL wait can take. Default 2m. Android and iOS runs do not use it.',\n ),\n }).strict().optional(),\n planner: z.object({\n maxActions: z.number().int().positive().optional(),\n maxPlanningTurns: z.number().int().positive().optional(),\n previousStepCount: z.number().optional(),\n }).strict().optional(),\n logCapture: z.object({\n console: z.boolean().optional(),\n network: z.boolean().optional(),\n }).strict().optional(),\n cache: z.boolean().optional(),\n authState: AuthStateUseSchema.optional(),\n mobile: MobileUseOverrideSchema.optional(),\n llm: z.string().optional(),\n parallel: z.boolean().optional(),\n // The override half of `use.workers`, shaped like `UseSchema`'s.\n workers: z.number().int().positive().optional(),\n device: z.string().optional(),\n}).strict()\n","import { z } from 'zod'\n\nexport const AttributePredicateSchema = z.union([\n z.string(),\n z.object({\n regex: z.string().min(1),\n }).strict(),\n])\n\nexport const AnalyticsSchema = z.object({\n privacy: z.literal(true).optional(),\n passRateScope: z.object({\n attributes: z.record(z.string(), AttributePredicateSchema).optional(),\n }).strict().optional(),\n}).strict()\n\nexport type AnalyticsConfig = z.infer<typeof AnalyticsSchema>\n","import { z } from 'zod'\nimport ms from 'ms'\nimport { isCanonicalHookId, isCanonicalTestId } from '@vostride/agent-qa-ids'\nimport { retiredStepKeyScan, retiredUseKeyScan } from './retired-keys.js'\nimport { UseOverrideSchema } from './use-schema.js'\n\nconst OptionalDuration = z.string()\n .refine((v) => ms(v as ms.StringValue) !== undefined, {\n message: 'Invalid duration format (e.g., \"30s\", \"5m\", \"1h\")',\n })\n .transform((v) => ms(v as ms.StringValue) as number)\n .optional()\n\nexport const CaptureConfigSchema = z.object({\n variable: z.string(),\n method: z.enum(['regex', 'selector', 'ai']),\n pattern: z.string().optional(),\n selector: z.string().optional(),\n description: z.string().optional(),\n}).strict()\n\nexport const TestStepSchema = z.union([\n z.string(),\n z.object({\n step: z.string(),\n timeout: OptionalDuration,\n capture: CaptureConfigSchema.optional(),\n }).strict(),\n])\n\nexport const TestMetaSchema = z.object({\n timeout: OptionalDuration,\n retries: z.number().optional(),\n record: z.boolean().optional(),\n}).strict()\n\nconst HookIdSchema = z.string().refine((value) => isCanonicalHookId(value), {\n message: 'Hook ID must be h_ followed by 10 id-agent words',\n})\n\nexport const TestDefinitionSchema = z.object({\n 'test-id': z.string().refine((value) => isCanonicalTestId(value), {\n message: 'Test ID must be t_ followed by 10 id-agent words',\n }),\n name: z.string(),\n target: z.string(),\n context: z.string().optional(),\n use: retiredUseKeyScan.pipe(UseOverrideSchema).optional(),\n meta: TestMetaSchema.optional(),\n setup: z.array(HookIdSchema).optional(),\n teardown: z.array(HookIdSchema).optional(),\n steps: z.array(retiredStepKeyScan.pipe(TestStepSchema)).min(1),\n}).strict()\n","import path from 'node:path'\n\n// `configDir` is the directory holding `agent-qa.config.yaml`.\nexport function resolveKnowledgeRoot(knowledge: { dir: string }, configDir: string): string {\n return path.resolve(configDir, knowledge.dir)\n}\n","import { z } from 'zod'\nimport { isCanonicalHookId, isCanonicalSuiteId, isCanonicalTestId } from '@vostride/agent-qa-ids'\nimport { retiredUseKeyScan } from './retired-keys.js'\nimport { UseOverrideSchema } from './use-schema.js'\n\nexport const SuiteTestEntrySchema = z.object({\n test: z.string(),\n id: z.string().refine((value) => isCanonicalTestId(value), {\n message: 'Test ID must be t_ followed by 10 id-agent words',\n }),\n}).strict()\n\nconst HookIdSchema = z.string().refine((value) => isCanonicalHookId(value), {\n message: 'Hook ID must be h_ followed by 10 id-agent words',\n})\n\nexport const SuiteDefinitionSchema = z.object({\n 'suite-id': z.string().refine((value) => isCanonicalSuiteId(value), {\n message: 'Suite ID must be s_ followed by 10 id-agent words',\n }).optional(),\n name: z.string(),\n target: z.string(),\n context: z.string().optional(),\n setup: z.array(HookIdSchema).optional(),\n teardown: z.array(HookIdSchema).optional(),\n tests: z.array(SuiteTestEntrySchema).min(1),\n use: retiredUseKeyScan.pipe(UseOverrideSchema).optional(),\n}).strict()\n","import { z } from 'zod'\nimport ms from 'ms'\nimport { isCanonicalHookId } from '@vostride/agent-qa-ids'\n\nconst HookDurationString = z.string()\n .refine((v) => ms(v as ms.StringValue) !== undefined, {\n message: 'Invalid duration format (e.g., \"30s\", \"2m\", \"1h\")',\n })\n .transform((v) => ms(v as ms.StringValue) as number)\n\nconst HOOK_ID_MESSAGE = 'Hook ID must be h_ followed by 10 id-agent words'\n\nexport const HookDefinitionSchema = z.object({\n id: z.string().refine((value) => isCanonicalHookId(value), {\n message: HOOK_ID_MESSAGE,\n }),\n name: z.string().min(1),\n runtime: z.enum(['node', 'bun', 'python', 'bash']),\n file: z.string().min(1),\n deps: z.array(z.string()).optional().default([]),\n packageFile: z.string().optional(),\n timeout: HookDurationString,\n network: z.boolean().optional().default(true),\n})\n\nexport const HooksFileSchema = z.object({\n hooks: z.array(HookDefinitionSchema),\n}).superRefine((val, ctx) => {\n const ids = new Set<string>()\n const names = new Set<string>()\n for (let i = 0; i < val.hooks.length; i++) {\n if (ids.has(val.hooks[i].id)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['hooks', i, 'id'],\n message: `Duplicate hook id: \"${val.hooks[i].id}\"`,\n })\n }\n if (names.has(val.hooks[i].name)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['hooks', i, 'name'],\n message: `Duplicate hook name: \"${val.hooks[i].name}\"`,\n })\n }\n ids.add(val.hooks[i].id)\n names.add(val.hooks[i].name)\n }\n})\n\nexport type HooksFileConfig = z.infer<typeof HooksFileSchema>\n","import { readFile } from 'node:fs/promises'\nimport { parseAllDocuments, LineCounter } from 'yaml'\nimport { TestDefinitionSchema } from '../schema/test-schema.js'\nimport type { TestDefinition } from '../types/test.js'\nimport { formatYamlError, formatZodErrors } from './errors.js'\nimport type { ParseError } from './errors.js'\nimport { findBareVariables } from '@vostride/agent-qa-runner'\n\nexport interface ParseResult {\n tests: TestDefinition[]\n errors: ParseError[]\n}\n\n// Identity is `filePath + test.name`; a flattened parse stamps every member with one file.\nexport interface ParsedTestBinding {\n test: TestDefinition\n filePath: string\n fileContent: string\n}\n\nexport interface ParseAllTestBindingsResult {\n bindings: ParsedTestBinding[]\n errors: ParseError[]\n}\n\nexport function parseTestFile(\n content: string,\n filePath: string,\n): ParseResult {\n const lineCounter = new LineCounter()\n const docs = parseAllDocuments(content, {\n lineCounter,\n prettyErrors: true,\n strict: true,\n keepSourceTokens: true,\n })\n\n const tests: TestDefinition[] = []\n const errors: ParseError[] = []\n\n for (const doc of docs) {\n // Skip empty documents (trailing --- or empty sections)\n if (doc.contents === null || doc.contents === undefined) continue\n\n // YAML-level syntax errors\n if (doc.errors.length > 0) {\n for (const err of doc.errors) {\n const pos = err.pos?.[0]\n const linePos =\n pos !== undefined ? lineCounter.linePos(pos) : undefined\n errors.push(formatYamlError(err, linePos, content, filePath))\n }\n continue\n }\n\n // Convert AST to plain JS object\n const value = doc.toJS()\n\n // Schema-level validation via Zod\n const parsed = TestDefinitionSchema.safeParse(value)\n if (!parsed.success) {\n errors.push(\n ...formatZodErrors(parsed.error, doc as unknown as Parameters<typeof formatZodErrors>[1], lineCounter, content, filePath),\n )\n } else {\n const bareErrors = checkBareVariables(parsed.data, filePath)\n if (bareErrors.length > 0) {\n errors.push(...bareErrors)\n } else {\n tests.push(parsed.data)\n }\n }\n }\n\n return { tests, errors }\n}\n\nfunction checkBareVariables(test: TestDefinition, filePath: string): ParseError[] {\n const errors: ParseError[] = []\n const textsToCheck: string[] = []\n\n if ((test as any).url) textsToCheck.push((test as any).url)\n for (const step of test.steps) {\n if (typeof step === 'string') {\n textsToCheck.push(step)\n } else {\n textsToCheck.push(step.step)\n }\n }\n\n for (const text of textsToCheck) {\n for (const varName of findBareVariables(text)) {\n errors.push({\n file: filePath,\n line: 1,\n column: 1,\n message: `Variable \"{{${varName}}}\" must use a namespace prefix: {{env:${varName}}}`,\n severity: 'error',\n source: text,\n })\n }\n }\n\n return errors\n}\n\nexport async function parseAllTestBindings(\n filePaths: string[],\n): Promise<ParseAllTestBindingsResult> {\n const bindings: ParsedTestBinding[] = []\n const allErrors: ParseError[] = []\n\n for (const filePath of filePaths) {\n const content = await readFile(filePath, 'utf-8')\n const result = parseTestFile(content, filePath)\n bindings.push(\n ...result.tests.map((test) => ({ test, filePath, fileContent: content })),\n )\n allErrors.push(...result.errors)\n }\n\n return { bindings, errors: allErrors }\n}\n\nexport async function parseAllTests(\n filePaths: string[],\n): Promise<ParseResult> {\n const { bindings, errors } = await parseAllTestBindings(filePaths)\n return { tests: bindings.map(({ test }) => test), errors }\n}\n","import pc from 'picocolors'\n\nimport { yamlParseFailureMessage } from '../validation/yaml-fault.js'\n\nexport interface ParseError {\n file: string\n line: number\n column: number\n message: string\n severity: 'error' | 'warning'\n source: string\n suggestion?: string\n}\n\ninterface FormatOptions {\n noColor?: boolean\n}\n\nfunction shouldUseColor(opts?: FormatOptions): boolean {\n if (opts?.noColor) return false\n if (process.env.NO_COLOR !== undefined) return false\n return true\n}\n\nexport function formatParseError(\n error: ParseError,\n opts?: FormatOptions,\n): string {\n const color = shouldUseColor(opts)\n const lineNum = String(error.line)\n const pad = ' '.repeat(lineNum.length)\n\n const red = color ? pc.red : (s: string) => s\n const bold = color ? pc.bold : (s: string) => s\n const blue = color ? pc.blue : (s: string) => s\n const boldRed = (s: string) => bold(red(s))\n const boldBlue = (s: string) => bold(blue(s))\n\n const severity =\n error.severity === 'error' ? boldRed('error') : bold(pc.yellow('warning'))\n\n let output = ''\n output += `${severity}: ${error.message}\\n`\n output += ` ${boldBlue('-->')} ${error.file}:${error.line}:${error.column}\\n`\n // `formatYamlError` returns an empty `source`, so the excerpt block is skipped.\n if (error.source) {\n output += ` ${boldBlue(`${pad} |`)}\\n`\n output += ` ${boldBlue(`${lineNum} |`)} ${error.source}\\n`\n output += ` ${boldBlue(`${pad} |`)} ${' '.repeat(Math.max(0, error.column - 1))}${boldRed('^')}\\n`\n }\n\n if (error.suggestion) {\n output += ` ${boldBlue(`${pad} =`)} ${bold('help')}: ${error.suggestion}\\n`\n }\n\n return output\n}\n\nfunction getSourceLine(content: string, line: number): string {\n const lines = content.split('\\n')\n if (line < 1 || line > lines.length) return ''\n return lines[line - 1] ?? ''\n}\n\n// Reports the fault's line and column only: yaml's pretty message quotes unvalidated source bytes.\nexport function formatYamlError(\n err: { message: string; pos?: [number, number] },\n linePos: { line: number; col: number } | undefined,\n content: string,\n filePath: string,\n): ParseError {\n const line = linePos?.line ?? 1\n const col = linePos?.col ?? 1\n\n return {\n file: filePath,\n line,\n column: col,\n message: yamlParseFailureMessage(err),\n severity: 'error',\n source: '',\n suggestion: undefined,\n }\n}\n\nfunction zodPathToSuggestion(\n code: string,\n path: (string | number)[],\n message: string,\n): string | undefined {\n const field = path[path.length - 1]\n if (code === 'invalid_type') {\n if (typeof field === 'string') {\n return `check that '${field}' has the correct type`\n }\n return `check the value type at this position`\n }\n if (code === 'too_small') {\n if (typeof field === 'string' && field === 'steps') {\n return 'tests must have at least one step'\n }\n return message\n }\n if (code === 'invalid_union') {\n return 'steps must be strings like \"Click the login button\" or objects like { step: \"...\", timeout: \"30s\" }'\n }\n if (code === 'unrecognized_keys') {\n return message\n }\n if (typeof field === 'string') {\n return `did you forget to add '${field}'?`\n }\n return undefined\n}\n\ninterface YamlNode {\n range?: [number, number, number]\n items?: YamlNode[]\n key?: YamlNode\n value?: YamlNode | null\n srcToken?: unknown\n}\n\ninterface YamlDoc {\n contents: YamlNode | null\n}\n\ninterface LineCounterLike {\n linePos(offset: number): { line: number; col: number }\n}\n\ninterface ZodIssue {\n path: PropertyKey[]\n message: string\n code: string\n}\n\nfunction resolveNodeAtPath(\n doc: YamlDoc,\n path: (string | number)[],\n): YamlNode | null {\n let current: YamlNode | null = doc.contents\n if (!current) return null\n\n for (const segment of path) {\n if (!current) return null\n\n if (typeof segment === 'number') {\n // Array index — current should be a sequence node with items\n const items: YamlNode[] | undefined = current.items\n if (items && items[segment]) {\n current = items[segment]\n } else {\n return current\n }\n } else {\n // Object key — current should be a mapping node with items\n const items: YamlNode[] | undefined = current.items\n if (!items) return current\n\n let found = false\n for (const pair of items as YamlNode[]) {\n const keyNode: YamlNode | undefined = pair.key\n if (keyNode && 'value' in keyNode && keyNode.value === segment) {\n current = pair.value ?? null\n found = true\n break\n }\n // Sometimes keyNode is the scalar itself\n if (keyNode && 'source' in keyNode && (keyNode as { source?: string }).source === segment) {\n current = pair.value ?? null\n found = true\n break\n }\n }\n if (!found) return current\n }\n }\n\n return current\n}\n\nexport function formatZodErrors(\n zodError: { issues: ZodIssue[] },\n doc: YamlDoc,\n lineCounter: LineCounterLike,\n content: string,\n filePath: string,\n): ParseError[] {\n const errors: ParseError[] = []\n\n for (const issue of zodError.issues) {\n let line = 1\n let col = 1\n\n // Try to resolve the node at the Zod error path\n const issuePath = issue.path.filter((segment): segment is string | number => (\n typeof segment === 'string' || typeof segment === 'number'\n ))\n const node = resolveNodeAtPath(doc, issuePath)\n if (node?.range) {\n const pos = lineCounter.linePos(node.range[0])\n line = pos.line\n col = pos.col\n } else if (doc.contents?.range) {\n const pos = lineCounter.linePos(doc.contents.range[0])\n line = pos.line\n col = pos.col\n }\n\n const suggestion = zodPathToSuggestion(issue.code, issuePath, issue.message)\n\n errors.push({\n file: filePath,\n line,\n column: col,\n message: issuePath.length > 0\n ? `${issuePath.join('.')}: ${issue.message}`\n : issue.message,\n severity: 'error',\n source: getSourceLine(content, line),\n suggestion,\n })\n }\n\n return errors\n}\n","// Reads only the two `linePos` numbers; the error's message quotes the person's file.\nexport function yamlParseFailureMessage(error: unknown): string {\n if (typeof error !== 'object' || error === null) {\n return 'not readable as YAML (position unavailable)'\n }\n const linePos = (error as { linePos?: readonly { line?: unknown; col?: unknown }[] }).linePos\n const first = Array.isArray(linePos) ? linePos[0] : undefined\n if (typeof first?.line === 'number' && typeof first.col === 'number') {\n return `not readable as YAML at line ${first.line}, column ${first.col}`\n }\n return 'not readable as YAML (position unavailable)'\n}\n","import { readFile, access } from 'node:fs/promises'\nimport { dirname, resolve, extname } from 'node:path'\n\nexport interface FileAttachment {\n name: string\n path: string\n content: Buffer\n mimeType: string\n}\n\nconst MIME_TYPES: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.svg': 'image/svg+xml',\n '.pdf': 'application/pdf',\n '.doc': 'application/msword',\n '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n '.txt': 'text/plain',\n '.csv': 'text/csv',\n '.json': 'application/json',\n '.xml': 'application/xml',\n '.zip': 'application/zip',\n}\n\nfunction detectMimeType(filename: string): string {\n const ext = extname(filename).toLowerCase()\n return MIME_TYPES[ext] ?? 'application/octet-stream'\n}\n\nconst FILE_REF_PATTERN = /\\$\\{file:([^}]+)\\}/g\n\nexport async function resolveFileReferences(\n stepText: string,\n testFilePath: string,\n): Promise<{ resolvedText: string; attachments: FileAttachment[] }> {\n const matches = [...stepText.matchAll(FILE_REF_PATTERN)]\n\n if (matches.length === 0) {\n return { resolvedText: stepText, attachments: [] }\n }\n\n const testDir = dirname(testFilePath)\n const attachments: FileAttachment[] = []\n let resolvedText = stepText\n\n for (const match of matches) {\n const filename = match[1]\n const absolutePath = resolve(testDir, filename)\n\n try {\n await access(absolutePath)\n } catch {\n throw new Error(\n `File attachment not found: \"${filename}\" (resolved to \"${absolutePath}\", referenced in test \"${testFilePath}\")`,\n )\n }\n\n const content = await readFile(absolutePath) as Buffer\n\n attachments.push({\n name: filename,\n path: absolutePath,\n content,\n mimeType: detectMimeType(filename),\n })\n\n resolvedText = resolvedText.replace(match[0], absolutePath)\n }\n\n return { resolvedText, attachments }\n}\n","import { readFile } from 'node:fs/promises'\nimport { parse as parseYaml } from 'yaml'\nimport { SuiteDefinitionSchema } from '../schema/suite-schema.js'\nimport { yamlParseFailureMessage } from '../validation/yaml-fault.js'\nimport type { SuiteDefinition } from '../suite/types.js'\n\nexport async function parseSuiteFile(filePath: string): Promise<SuiteDefinition> {\n const content = await readFile(filePath, 'utf-8')\n\n let raw: unknown\n try {\n raw = parseYaml(content)\n } catch (err) {\n // Still throws, with no `cause`: `util.inspect` would print the raw `YAMLParseError`.\n throw new Error(`${filePath}: ${yamlParseFailureMessage(err)}`)\n }\n\n return SuiteDefinitionSchema.parse(raw)\n}\n","// RFC 6902 patches applied to the CST in place; `doc.toJS()` would reformat untouched lines.\n\nimport {\n Composer,\n CST,\n Document,\n Parser,\n isMap,\n isScalar,\n isSeq,\n} from 'yaml'\nimport type { Node, Scalar, YAMLSeq } from 'yaml'\n\nimport {\n EDITABLE_POINTER_ROOTS,\n isEditablePointer,\n parseJsonPointer,\n} from '@vostride/agent-qa-schema'\nimport type { PatchOp, TestEditPatchSet } from '@vostride/agent-qa-schema'\n\nimport { parseTestFile } from './yaml-parser.js'\n\n/**\n * A test document parsed so that BOTH halves survive: the composed model a pointer resolves\n * against, and the token array the render concatenates.\n *\n * The two are not redundant. Pointer resolution needs the model (`getIn`-shaped navigation over\n * maps and sequences); byte preservation needs the tokens. Handing a caller only one of them would\n * force it to re-parse to get the other, and a second parse is a second opinion about the source.\n */\nexport interface ParsedTestDocument {\n readonly source: string\n readonly filePath: string\n readonly tokens: CST.Token[]\n readonly doc: Document\n}\n\n// ---- Refusals -------------------------------------------------------------------------------\n//\n// Separate classes, never one error carrying a `kind`. A caller legitimately distinguishes \"you\n// addressed a region you may not edit\" (a boundary violation worth reporting) from \"your pointer\n// does not resolve\" (a stale or hallucinated path, worth retrying against a fresh read) from\n// \"your edit produced a document this project cannot run\" (worth repairing) from \"that op cannot\n// be applied to that kind of node\" (worth re-planning the edit). One class with a discriminator\n// would make every one of those `catch` blocks read a string.\n\n/** A pointer addressed a document root outside `EDITABLE_POINTER_ROOTS`. */\nexport class PatchPointerOutsideEditableRegionError extends Error {\n constructor(readonly pointer: string) {\n super(\n `cst-patch: the pointer ${pointer} addresses a region no patch may edit; `\n + `only ${EDITABLE_POINTER_ROOTS.join(', ')} are editable, because a patch that can reach `\n + 'the identity fields can silently change which app the test drives',\n )\n this.name = 'PatchPointerOutsideEditableRegionError'\n }\n}\n\n/** A pointer named a node the document does not have. */\nexport class PatchPointerUnresolvableError extends Error {\n constructor(readonly pointer: string, readonly detail: string) {\n super(\n `cst-patch: the pointer ${pointer} does not resolve against this document (${detail}); `\n + 'a patch is applied to the document it was written against, never to a guess',\n )\n this.name = 'PatchPointerUnresolvableError'\n }\n}\n\n// `add` and `remove` act on block-sequence items only; a key change is a shape change.\nexport class PatchOpUnsupportedTargetError extends Error {\n constructor(readonly pointer: string, readonly detail: string) {\n super(`cst-patch: the pointer ${pointer} cannot carry this op: ${detail}`)\n this.name = 'PatchOpUnsupportedTargetError'\n }\n}\n\n/**\n * A document this project cannot run — checked on the SOURCE before anything is applied and on the\n * RENDERED bytes before anything may be written.\n *\n * Both directions matter. Validating only the render would let a pre-existing invalidity be\n * blamed on the patch; validating only the source would let a CST mutation that produced\n * structurally broken YAML reach a file. Same predicate, same evidence, two call sites.\n */\nexport class PatchedDocumentInvalidError extends Error {\n constructor(readonly phase: 'source' | 'rendered', readonly detail: string) {\n super(\n `cst-patch: the ${phase} document is not a valid test: ${detail}; `\n + 'a patched document is schema-validated before any caller may write it',\n )\n this.name = 'PatchedDocumentInvalidError'\n }\n}\n\n// ---- Parse ----------------------------------------------------------------------------------\n\n/**\n * Parse a test file retaining the CST token array beside the composed document.\n *\n * The composer is given `keepSourceTokens` so every node carries a `srcToken` back-reference; that\n * back-reference is the entire bridge between a pointer (which addresses the model) and a mutation\n * (which must land on the syntax).\n */\nexport function parseTestFileWithTokens(source: string, filePath: string): ParsedTestDocument {\n const tokens = [...new Parser().parse(source)]\n const docs = [...new Composer({ keepSourceTokens: true }).compose(tokens)]\n\n if (docs.length !== 1) {\n throw new PatchedDocumentInvalidError(\n 'source',\n `expected exactly one YAML document, found ${docs.length}`,\n )\n }\n const doc = docs[0]!\n if (doc.errors.length > 0) {\n throw new PatchedDocumentInvalidError(\n 'source',\n doc.errors.map((error) => error.message).join('; '),\n )\n }\n\n assertRunnable('source', source, filePath)\n\n return { source, filePath, tokens, doc }\n}\n\nfunction assertRunnable(phase: 'source' | 'rendered', content: string, filePath: string): void {\n const { tests, errors } = parseTestFile(content, filePath)\n if (errors.length > 0) {\n throw new PatchedDocumentInvalidError(phase, errors.map((error) => error.message).join('; '))\n }\n if (tests.length !== 1) {\n throw new PatchedDocumentInvalidError(\n phase,\n `expected exactly one test definition, found ${tests.length}`,\n )\n }\n}\n\n// ---- Apply ----------------------------------------------------------------------------------\n\n/**\n * Apply a patch set in document order, mutating `parsed.doc` and its tokens in place.\n *\n * TWO PROPERTIES THE ORDER BUYS. First, the fence runs over the WHOLE set before any mutation, so\n * a set mixing a legitimate op with an out-of-region one leaves nothing behind — a per-op check\n * would have already rewritten the legitimate target by the time it refused. Second, each pointer\n * resolves against the document as PRIOR ops left it, which is what RFC-6902 means by a sequence\n * of operations: an `add` earlier in an array shifts every later index, and resolving every\n * pointer against the original document would edit a plausible, schema-valid, wrong step.\n */\nexport function applyPatchSetToTestDoc(\n parsed: ParsedTestDocument,\n patchSet: TestEditPatchSet,\n): void {\n for (const op of patchSet.patches) {\n if (!isEditablePointer(op.path)) throw new PatchPointerOutsideEditableRegionError(op.path)\n }\n for (const op of patchSet.patches) {\n applyOne(parsed.doc, op)\n }\n}\n\nfunction applyOne(doc: Document, op: PatchOp): void {\n const segments = parseJsonPointer(op.path)\n\n switch (op.op) {\n case 'replace': {\n const node = resolveNode(doc, segments)\n if (node === undefined) {\n throw new PatchPointerUnresolvableError(op.path, 'no node at that path')\n }\n if (!isScalar(node) || node.srcToken === undefined) {\n throw new PatchOpUnsupportedTargetError(\n op.path,\n 'replace writes one scalar token, and that path is a collection',\n )\n }\n CST.setScalarValue(node.srcToken, op.value)\n return\n }\n\n case 'add': {\n const { seqToken, index } = resolveSeqSlot(doc, op.path, segments, 'add')\n if (index > seqToken.items.length) {\n throw new PatchPointerUnresolvableError(\n op.path,\n `index ${index} is past the end of a ${seqToken.items.length}-item sequence`,\n )\n }\n if (index > 0) terminateItem(seqToken.items[index - 1])\n seqToken.items.splice(index, 0, newSeqItem(seqToken, op.value))\n normalizeItemStarts(seqToken)\n resyncSeqNode(doc, segments.slice(0, -1))\n return\n }\n\n case 'remove': {\n const { seqToken, index } = resolveSeqSlot(doc, op.path, segments, 'remove')\n if (index >= seqToken.items.length) {\n throw new PatchPointerUnresolvableError(\n op.path,\n `index ${index} is past the end of a ${seqToken.items.length}-item sequence`,\n )\n }\n seqToken.items.splice(index, 1)\n normalizeItemStarts(seqToken)\n resyncSeqNode(doc, segments.slice(0, -1))\n return\n }\n }\n}\n\ninterface SeqSlot {\n seqToken: CST.BlockSequence\n index: number\n}\n\n/** Resolve `<parent>/<index|->` to the parent's block-sequence token and a slot in it. */\nfunction resolveSeqSlot(\n doc: Document,\n pointer: string,\n segments: string[],\n op: 'add' | 'remove',\n): SeqSlot {\n if (segments.length < 2) {\n throw new PatchOpUnsupportedTargetError(\n pointer,\n `${op} operates on a sequence item, and that path names a top-level key; `\n + 'adding or removing a key is a document rewrite, not a patch',\n )\n }\n\n const parent = resolveNode(doc, segments.slice(0, -1))\n if (parent === undefined) {\n throw new PatchPointerUnresolvableError(pointer, 'the parent collection does not resolve')\n }\n if (!isSeq(parent)) {\n throw new PatchOpUnsupportedTargetError(\n pointer,\n `${op} operates on a sequence item, and the parent at that path is not a sequence`,\n )\n }\n\n const seqToken = (parent as YAMLSeq).srcToken\n if (seqToken === undefined || seqToken.type !== 'block-seq') {\n throw new PatchOpUnsupportedTargetError(\n pointer,\n `${op} rebuilds block-sequence indentation, and that sequence is written in flow style`,\n )\n }\n\n const last = segments[segments.length - 1]!\n if (op === 'add' && last === '-') return { seqToken, index: seqToken.items.length }\n\n const index = asIndex(last)\n if (index === undefined) {\n throw new PatchPointerUnresolvableError(pointer, `${last} is not a sequence index`)\n }\n return { seqToken, index }\n}\n\nfunction asIndex(segment: string): number | undefined {\n return /^(?:0|[1-9]\\d*)$/.test(segment) ? Number(segment) : undefined\n}\n\n/** Walk the composed model one reference token at a time. */\nfunction resolveNode(doc: Document, segments: string[]): Node | undefined {\n let node: unknown = doc.contents\n for (const segment of segments) {\n if (isSeq(node)) {\n const index = asIndex(segment)\n if (index === undefined || index >= node.items.length) return undefined\n node = node.items[index]\n } else if (isMap(node)) {\n const pair = node.items.find(\n (candidate) => isScalar(candidate.key) && String((candidate.key as Scalar).value) === segment,\n )\n if (pair === undefined) return undefined\n node = pair.value\n } else {\n return undefined\n }\n }\n return (node ?? undefined) as Node | undefined\n}\n\n/**\n * Re-compose the sequence NODE after its token items changed.\n *\n * The composed model and the CST are two views of one document, and a structural edit moves them\n * out of step: splicing `srcToken.items` changes what the file says while `seq.items` still\n * describes what it said. Every later pointer in the same set resolves against the MODEL, so\n * leaving it stale is exactly how the second op of a two-op set lands on the wrong index.\n */\nfunction resyncSeqNode(doc: Document, parentSegments: string[]): void {\n const parent = resolveNode(doc, parentSegments)\n if (!isSeq(parent)) return\n\n const seqToken = (parent as YAMLSeq).srcToken\n if (seqToken === undefined || seqToken.type !== 'block-seq') return\n\n const rebuilt = [\n ...new Composer({ keepSourceTokens: true }).compose([\n { type: 'document', offset: 0, start: [], value: seqToken },\n ]),\n ]\n const contents = rebuilt[0]?.contents\n if (!isSeq(contents)) return\n\n const seq = parent as YAMLSeq\n seq.items = contents.items\n}\n\n// `createScalarToken` adds its own newline; without it an appended item joins the previous line.\nfunction newSeqItem(seqToken: CST.BlockSequence, value: string): CST.BlockSequence['items'][number] {\n return {\n start: [\n { type: 'seq-item-ind', offset: -1, indent: seqToken.indent, source: '-' },\n { type: 'space', offset: -1, indent: seqToken.indent + 1, source: ' ' },\n ],\n value: CST.createScalarToken(value, { indent: seqToken.indent + 2 }),\n }\n}\n\n/**\n * Give an item a trailing newline if it has none, so the next item starts on its own line.\n *\n * The absence of a terminator is expressed as an ABSENT `end` key, not an empty array: a file whose\n * last line has no newline yields a scalar token with no `end` property at all. Probing for the\n * key and returning early therefore skips exactly the case this function exists for — which is how\n * an append onto an unterminated last item produces two steps concatenated on one line. A\n * block-scalar carries its own terminator inside `source` and is left alone.\n */\nfunction terminateItem(item: CST.BlockSequence['items'][number] | undefined): void {\n const value = item?.value\n if (value === undefined || !CST.isScalar(value) || value.type === 'block-scalar') return\n const end = (value.end ??= [])\n if (end.some((token) => token.type === 'newline')) return\n end.push({ type: 'newline', offset: -1, indent: 0, source: '\\n' })\n}\n\n/**\n * Restore the one positional invariant of a block sequence after items moved.\n *\n * Item 0 alone does NOT carry its own leading whitespace — the indentation before the first `-`\n * belongs to the parent mapping item's separator tokens, while items 1..n each carry a `space`\n * token of their own. So an insert at index 0, or a removal of index 0, silently produces a\n * document where one line's indentation is wrong. Only items whose position-0-ness actually\n * changed are touched; every other item's `start` array is left exactly as parsed, which is what\n * keeps `remove` from re-indenting lines nobody addressed.\n */\nfunction normalizeItemStarts(seqToken: CST.BlockSequence): void {\n const pad = ' '.repeat(seqToken.indent)\n seqToken.items.forEach((item, index) => {\n const start = item.start\n const leadsWithSpace = start[0]?.type === 'space'\n if (index === 0 && leadsWithSpace) start.shift()\n if (index > 0 && !leadsWithSpace) {\n start.unshift({ type: 'space', offset: -1, indent: 0, source: pad })\n }\n })\n}\n\n// ---- Render ---------------------------------------------------------------------------------\n\n/**\n * Concatenate the whole token array back to bytes, then refuse anything unrunnable.\n *\n * THE RENDER IS OVER `parsed.tokens`, NEVER OVER THE DOCUMENT TOKEN ALONE. `CST.stringify`'s own\n * doc comment states it \"applies no validation whatsoever, and simply concatenates the sources in\n * their logical order\" — that concatenation IS the byte-preservation guarantee. A file's leading\n * comment is a separate token in the parser's output stream, positioned BEFORE the document token,\n * so `CST.stringify(documentToken)` drops it. That is the one genuinely non-obvious line here, it\n * was measured rather than reasoned about, and the frozen corpus's untouched-round-trip row is\n * the cell that catches a regression to it.\n */\nexport function renderPatchedTestDoc(parsed: ParsedTestDocument, filePath?: string): string {\n const rendered = parsed.tokens.map((token) => CST.stringify(token)).join('')\n assertRunnable('rendered', rendered, filePath ?? parsed.filePath)\n return rendered\n}\n","const CHARS_PER_TOKEN = 4\n\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / CHARS_PER_TOKEN)\n}\n","export { estimateTokens } from './token-budget.js'\n\n// Runner owns the env-file codec; the CLI and dashboard read it through core.\nexport { parseEnvFile, serializeEnvFile } from '@vostride/agent-qa-runner'\n","import { XMLParser } from 'fast-xml-parser'\nimport type { InterimNode, RefBinding } from '@vostride/agent-qa-runner'\nimport { isToggleElement, type ElementLabels, type ElementState } from '@vostride/agent-qa-schema'\nimport type { ParsedMobileSource, RefEntry } from './types.js'\nimport { IOS_EDITABLE_TYPES, iosAccessibleOtherRole, normalizeRole } from './role-map.js'\n\nconst INTERACTIVE_ROLES = new Set([\n 'button', 'link', 'textbox', 'checkbox', 'radio', 'combobox',\n 'searchbox', 'slider', 'switch', 'tab', 'menuitem',\n // Additional interactive roles (matching expanded web set and mobile types)\n 'spinbutton', 'option', 'menuitemradio', 'menuitemcheckbox',\n 'gridcell', 'scrollbar', 'separator',\n 'grid', 'menu', 'menubar', 'tree', 'treegrid', 'treeitem',\n 'listbox', 'pickerwheel',\n])\n\nconst CONTENT_ROLES = new Set([\n 'text', 'heading', 'cell', 'listitem', 'image', 'navigation', 'alert',\n 'progressbar',\n])\n\n// Only interactive and content roles become nodes; containers drop and their children reparent.\nfunction shouldEmit(role: string): boolean {\n return INTERACTIVE_ROLES.has(role) || CONTENT_ROLES.has(role)\n}\n\n// fast-xml-parser leaves attributes as strings, so a real boolean is the literal `\"true\"`.\nfunction boolAttr(value: unknown): boolean {\n return value === true || value === 'true'\n}\n\nfunction parseAndroidBounds(boundsStr: string): { x: number; y: number; width: number; height: number } | undefined {\n const match = boundsStr.match(/^\\[(\\d+),(\\d+)\\]\\[(\\d+),(\\d+)\\]$/)\n if (!match) return undefined\n const x1 = parseInt(match[1], 10)\n const y1 = parseInt(match[2], 10)\n const x2 = parseInt(match[3], 10)\n const y2 = parseInt(match[4], 10)\n return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 }\n}\n\nfunction parseIosBounds(attrs: Record<string, any>): { x: number; y: number; width: number; height: number } | undefined {\n const x = parseFloat(attrs['@_x'])\n const y = parseFloat(attrs['@_y'])\n const width = parseFloat(attrs['@_width'])\n const height = parseFloat(attrs['@_height'])\n if (isNaN(x) || isNaN(y) || isNaN(width) || isNaN(height)) return undefined\n return { x, y, width, height }\n}\n\nfunction extractLabel(attrs: Record<string, any>, platform: 'android' | 'ios'): string | undefined {\n if (platform === 'android') {\n const contentDesc = attrs['@_content-desc']\n if (contentDesc) return contentDesc\n const text = attrs['@_text']\n if (text) return text\n return undefined\n }\n // iOS\n const label = attrs['@_label']\n if (label) return label\n const name = attrs['@_name']\n if (name) return name\n const value = attrs['@_value']\n if (value) return value\n return undefined\n}\n\nfunction extractValue(attrs: Record<string, any>, platform: 'android' | 'ios'): string | undefined {\n const value = platform === 'android' ? attrs['@_text'] : attrs['@_value']\n if (value === undefined || value === null || value === '') return undefined\n return String(value)\n}\n\n// Only emitted signals populate `state`; iOS reports a toggle's state only as its `value`.\nfunction liftState(\n tagName: string,\n role: string,\n attrs: Record<string, any>,\n platform: 'android' | 'ios',\n bounds: { x: number; y: number; width: number; height: number } | undefined,\n viewport: { width: number; height: number } | undefined,\n): Partial<ElementState> {\n const state: Partial<ElementState> = {}\n\n if (attrs['@_enabled'] !== undefined) {\n state.enabled = boolAttr(attrs['@_enabled'])\n }\n if (attrs['@_selected'] !== undefined) {\n state.selected = boolAttr(attrs['@_selected'])\n }\n\n if (platform === 'android') {\n // `checked` is only meaningful when the widget is `checkable` — otherwise typed-absent.\n if (boolAttr(attrs['@_checkable']) && attrs['@_checked'] !== undefined) {\n state.checked = boolAttr(attrs['@_checked'])\n }\n if (attrs['@_focused'] !== undefined) {\n state.focused = boolAttr(attrs['@_focused'])\n }\n // visible derivation (documented): explicit displayed=false, else bounds fully\n // outside the viewport ⇒ offscreen. Absent otherwise (builder defaults visible=true).\n if (attrs['@_displayed'] !== undefined && !boolAttr(attrs['@_displayed'])) {\n state.visible = false\n } else if (bounds && viewport && (bounds.y + bounds.height < 0 || bounds.y > viewport.height)) {\n state.visible = false\n }\n } else {\n if ((role === 'switch' || role === 'checkbox') && isToggleElement({ role })) {\n const value = attrs['@_value']\n if (value === '1') state.checked = true\n else if (value === '0') state.checked = false\n }\n if (attrs['@_visible'] !== undefined && !boolAttr(attrs['@_visible'])) {\n state.visible = false\n } else if (bounds && viewport && (bounds.y + bounds.height < 0 || bounds.y > viewport.height)) {\n state.visible = false\n }\n if (IOS_EDITABLE_TYPES.has(tagName) && state.enabled !== false) {\n state.editable = true\n }\n }\n\n return state\n}\n\n/** Android maps `resource-id -> labels.testId` and `content-desc -> labels.ariaLabel`\n * (empty strings stay absent). iOS carries no dedicated label attributes here. */\nfunction liftLabels(attrs: Record<string, any>, platform: 'android' | 'ios'): ElementLabels {\n const labels: ElementLabels = {}\n if (platform === 'android') {\n const resourceId = attrs['@_resource-id']\n if (resourceId) labels.testId = String(resourceId)\n const contentDesc = attrs['@_content-desc']\n if (contentDesc) labels.ariaLabel = String(contentDesc)\n }\n return labels\n}\n\ninterface WalkContext {\n platform: 'android' | 'ios'\n nodes: InterimNode[]\n viewport?: { width: number; height: number }\n screenReference?: { width: number; height: number }\n}\n\nconst IOS_FULL_SCREEN_AREA_RATIO = 0.9\nconst IOS_PROMOTED_NAME_MAX = 120\n\nfunction collectAttrs(node: any): Record<string, any> {\n const attrs: Record<string, any> = {}\n for (const key of Object.keys(node)) {\n if (key.startsWith('@_')) attrs[key] = node[key]\n }\n return attrs\n}\n\n// UIKit merges an accessible element's subviews into it and exposes no child text, so its\n// label is the only handle; React Native pressables without an accessibilityRole surface\n// this way as XCUIElementTypeOther.\nfunction isIosAccessibleLabelledOther(\n tagName: string,\n attrs: Record<string, any>,\n ctx: WalkContext,\n): boolean {\n if (ctx.platform !== 'ios' || tagName !== 'XCUIElementTypeOther') return false\n if (!boolAttr(attrs['@_accessible'])) return false\n const label = attrs['@_label']\n if (label === undefined || label === null || String(label).trim() === '') return false\n const bounds = parseIosBounds(attrs)\n if (!bounds) return false\n if (attrs['@_visible'] !== undefined && !boolAttr(attrs['@_visible'])) return false\n // WDA reports a frame it cannot compute as (-1,-1,0,0).\n if (!(bounds.width > 0 && bounds.height > 0)) return false\n const ref = ctx.screenReference\n if (ref && ref.width > 0 && ref.height > 0) {\n const onScreen =\n bounds.x < ref.width &&\n bounds.y < ref.height &&\n bounds.x + bounds.width > 0 &&\n bounds.y + bounds.height > 0\n if (!onScreen) return false\n const area = bounds.width * bounds.height\n if (area >= IOS_FULL_SCREEN_AREA_RATIO * ref.width * ref.height) return false\n }\n return true\n}\n\n// React Native joins a pressable's subtree text into its label, which can run to paragraphs.\nfunction capPromotedName(label: string): string {\n const chars = Array.from(label)\n if (chars.length <= IOS_PROMOTED_NAME_MAX) return label\n return chars.slice(0, IOS_PROMOTED_NAME_MAX - 1).join('') + '…'\n}\n\nfunction descendantCarriesLabel(node: any, label: string, ctx: WalkContext): boolean {\n for (const childKey of Object.keys(node)) {\n if (childKey.startsWith('@_') || childKey === '#text') continue\n const childVal = node[childKey]\n const children = Array.isArray(childVal) ? childVal : [childVal]\n for (const child of children) {\n if (!child || typeof child !== 'object') continue\n const attrs = collectAttrs(child)\n const childLabel = extractLabel(attrs, ctx.platform)\n if (\n childLabel !== undefined &&\n String(childLabel).trim() === label &&\n shouldEmit(normalizeRole(childKey, ctx.platform))\n ) {\n return true\n }\n if (descendantCarriesLabel(child, label, ctx)) return true\n }\n }\n return false\n}\n\nfunction walkNode(node: any, tagName: string, parentIndex: number | undefined, ctx: WalkContext): void {\n const attrs: Record<string, any> = {}\n // fast-xml-parser puts attributes with @_ prefix at the node level\n for (const key of Object.keys(node)) {\n if (key.startsWith('@_')) {\n attrs[key] = node[key]\n }\n }\n\n let role = normalizeRole(tagName, ctx.platform)\n let emit = shouldEmit(role)\n let promoted = false\n\n if (ctx.platform === 'ios') {\n if (\n ctx.screenReference === undefined &&\n (tagName === 'XCUIElementTypeApplication' || tagName === 'XCUIElementTypeWindow')\n ) {\n const reference = parseIosBounds(attrs)\n if (reference && reference.width > 0 && reference.height > 0) {\n ctx.screenReference = { width: reference.width, height: reference.height }\n }\n }\n if (\n !emit &&\n isIosAccessibleLabelledOther(tagName, attrs, ctx) &&\n !descendantCarriesLabel(node, String(attrs['@_label']).trim(), ctx)\n ) {\n const traits = attrs['@_traits']\n role = iosAccessibleOtherRole(typeof traits === 'string' ? traits : undefined)\n emit = true\n promoted = true\n }\n }\n\n // The index children reparent to: this node's own index if it is emitted, else the\n // nearest surviving ancestor passed down.\n let childParentIndex = parentIndex\n\n if (emit) {\n const rawLabel = extractLabel(attrs, ctx.platform)\n const label = promoted && rawLabel !== undefined ? capPromotedName(String(rawLabel)) : rawLabel\n const value = extractValue(attrs, ctx.platform)\n\n let bounds: { x: number; y: number; width: number; height: number } | undefined\n if (ctx.platform === 'android' && attrs['@_bounds']) {\n bounds = parseAndroidBounds(attrs['@_bounds'])\n } else if (ctx.platform === 'ios') {\n bounds = parseIosBounds(attrs)\n }\n\n const state = liftState(tagName, role, attrs, ctx.platform, bounds, ctx.viewport)\n const labels = liftLabels(attrs, ctx.platform)\n\n // Retain the raw platform attribute bag (prefix stripped, values stringified).\n const attributes: Record<string, string> = {}\n for (const key of Object.keys(attrs)) {\n attributes[key.slice(2)] = String(attrs[key])\n }\n\n const interim: InterimNode = {\n role,\n ...(label !== undefined ? { name: label } : {}),\n ...(value !== undefined ? { value } : {}),\n ...(parentIndex !== undefined ? { parentIndex } : {}),\n ...(bounds !== undefined ? { bounds } : {}),\n ...(Object.keys(state).length > 0 ? { state } : {}),\n ...(Object.keys(labels).length > 0 ? { labels } : {}),\n attributes,\n nativeType: tagName,\n }\n\n childParentIndex = ctx.nodes.length\n ctx.nodes.push(interim)\n }\n\n // Walk children\n for (const childKey of Object.keys(node)) {\n if (childKey.startsWith('@_') || childKey === '#text') continue\n const childVal = node[childKey]\n const children = Array.isArray(childVal) ? childVal : [childVal]\n for (const child of children) {\n if (child && typeof child === 'object') {\n walkNode(child, childKey, childParentIndex, ctx)\n }\n }\n }\n}\n\nexport function parseMobileSource(\n xml: string,\n platform: 'android' | 'ios',\n viewport?: { width: number; height: number },\n): ParsedMobileSource {\n // WDA writes a newline in an attribute as `&#10;`; numeric references are decoded on iOS\n // only, so a multi-line value is observed as typed (Android parsing is left as it was).\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n allowBooleanAttributes: true,\n preserveOrder: false,\n htmlEntities: platform === 'ios',\n })\n\n const parsed = parser.parse(xml)\n\n const ctx: WalkContext = {\n platform,\n nodes: [],\n viewport,\n ...(platform === 'ios' && viewport ? { screenReference: viewport } : {}),\n }\n\n // Find root element(s) to walk\n // Android: <hierarchy>...</hierarchy>\n // iOS: <AppiumAUT>...</AppiumAUT>\n const rootKeys = Object.keys(parsed).filter(k => !k.startsWith('?'))\n for (const rootKey of rootKeys) {\n const rootVal = parsed[rootKey]\n if (rootVal && typeof rootVal === 'object') {\n // Walk children of root container (hierarchy or AppiumAUT)\n for (const childKey of Object.keys(rootVal)) {\n if (childKey.startsWith('@_') || childKey === '#text') continue\n const childVal = rootVal[childKey]\n const children = Array.isArray(childVal) ? childVal : [childVal]\n for (const child of children) {\n if (child && typeof child === 'object') {\n walkNode(child, childKey, undefined, ctx)\n }\n }\n }\n }\n }\n\n return { nodes: ctx.nodes }\n}\n\n// Planner-ref to live-node resolution for the adapters; no position lives on the binding.\nexport function buildRefEntries(\n nodes: InterimNode[],\n binding: Record<string, RefBinding>,\n): Record<string, RefEntry> {\n const entries: Record<string, RefEntry> = {}\n for (const [ref, { index }] of Object.entries(binding)) {\n const node = nodes[index]\n if (!node) continue\n const rawInputType = node.attributes?.['input-type']\n entries[ref] = {\n role: node.role,\n ...(node.name !== undefined ? { name: node.name } : {}),\n ...(node.bounds !== undefined ? { bounds: node.bounds } : {}),\n ...(node.nativeType !== undefined ? { nativeType: node.nativeType } : {}),\n ...(node.value !== undefined ? { value: node.value } : {}),\n ...(node.state?.editable === true ? { editable: true } : {}),\n ...(rawInputType !== undefined && /^\\d+$/.test(rawInputType)\n ? { inputType: Number(rawInputType) }\n : {}),\n }\n }\n return entries\n}\n\n// An approximation: page source has no scroll offset, so offsets are 0 and size is the node extent.\nexport function deriveMobileScroll(\n nodes: InterimNode[],\n viewport: { width: number; height: number },\n): { offsetX: number; offsetY: number; contentWidth: number; contentHeight: number } {\n let maxX = viewport.width\n let maxY = viewport.height\n let sawBounds = false\n for (const node of nodes) {\n if (!node.bounds) continue\n sawBounds = true\n maxX = Math.max(maxX, node.bounds.x + node.bounds.width)\n maxY = Math.max(maxY, node.bounds.y + node.bounds.height)\n }\n return {\n offsetX: 0,\n offsetY: 0,\n contentWidth: sawBounds ? maxX : viewport.width,\n contentHeight: sawBounds ? maxY : viewport.height,\n }\n}\n","export const ANDROID_ROLE_MAP: Record<string, string> = {\n 'android.widget.Button': 'button',\n 'android.widget.ImageButton': 'button',\n 'android.widget.EditText': 'textbox',\n 'android.widget.AutoCompleteTextView': 'textbox',\n 'android.widget.TextView': 'text',\n 'android.widget.CheckedTextView': 'text',\n 'android.widget.CheckBox': 'checkbox',\n 'android.widget.Switch': 'switch',\n 'android.widget.ImageView': 'image',\n 'android.widget.ListView': 'list',\n 'android.widget.ScrollView': 'scroll-area',\n 'android.widget.HorizontalScrollView': 'scroll-area',\n 'android.view.View': 'group',\n 'android.view.ViewGroup': 'group',\n 'android.widget.FrameLayout': 'group',\n 'android.widget.LinearLayout': 'group',\n 'android.widget.RelativeLayout': 'group',\n 'android.widget.SearchView': 'searchbox',\n 'android.widget.Spinner': 'combobox',\n 'android.widget.SeekBar': 'slider',\n 'android.widget.RadioButton': 'radio',\n 'android.widget.CompoundButton': 'button',\n 'android.widget.ToggleButton': 'button',\n 'android.widget.ProgressBar': 'progressbar',\n 'android.widget.Toolbar': 'toolbar',\n 'android.widget.TabWidget': 'tablist',\n 'android.webkit.WebView': 'webview',\n 'androidx.recyclerview.widget.RecyclerView': 'list',\n 'androidx.constraintlayout.widget.ConstraintLayout': 'group',\n 'androidx.appcompat.widget.Toolbar': 'toolbar',\n 'androidx.viewpager.widget.ViewPager': 'group',\n 'androidx.core.widget.NestedScrollView': 'scroll-area',\n 'android.widget.NumberPicker': 'spinbutton',\n 'android.widget.DatePicker': 'combobox',\n 'android.widget.TimePicker': 'combobox',\n 'android.widget.RatingBar': 'slider',\n 'android.widget.CalendarView': 'grid',\n 'android.widget.TabHost': 'tablist',\n 'com.google.android.material.chip.Chip': 'button',\n 'com.google.android.material.floatingactionbutton.FloatingActionButton': 'button',\n 'com.google.android.material.tabs.TabLayout': 'tablist',\n 'com.google.android.material.textfield.TextInputEditText': 'textbox',\n 'com.google.android.material.switchmaterial.SwitchMaterial': 'switch',\n 'com.google.android.material.checkbox.MaterialCheckBox': 'checkbox',\n}\n\nexport const IOS_ROLE_MAP: Record<string, string> = {\n 'XCUIElementTypeButton': 'button',\n 'XCUIElementTypeTextField': 'textbox',\n 'XCUIElementTypeSecureTextField': 'textbox',\n 'XCUIElementTypeStaticText': 'text',\n 'XCUIElementTypeTextView': 'text',\n 'XCUIElementTypeSwitch': 'switch',\n 'XCUIElementTypeSlider': 'slider',\n 'XCUIElementTypeImage': 'image',\n 'XCUIElementTypeCell': 'cell',\n 'XCUIElementTypeTable': 'list',\n 'XCUIElementTypeCollectionView': 'list',\n 'XCUIElementTypeScrollView': 'scroll-area',\n 'XCUIElementTypeOther': 'group',\n 'XCUIElementTypeGroup': 'group',\n 'XCUIElementTypeNavigationBar': 'navigation',\n 'XCUIElementTypeTabBar': 'tablist',\n 'XCUIElementTypeSearchField': 'searchbox',\n 'XCUIElementTypeCheckBox': 'checkbox',\n 'XCUIElementTypeLink': 'link',\n 'XCUIElementTypeAlert': 'alert',\n 'XCUIElementTypeWebView': 'webview',\n 'XCUIElementTypeApplication': 'application',\n 'XCUIElementTypeWindow': 'window',\n 'XCUIElementTypePicker': 'combobox',\n 'XCUIElementTypePickerWheel': 'pickerwheel',\n 'XCUIElementTypeSegmentedControl': 'tablist',\n 'XCUIElementTypeStepper': 'spinbutton',\n 'XCUIElementTypeDatePicker': 'combobox',\n 'XCUIElementTypeMenu': 'menu',\n 'XCUIElementTypeMenuItem': 'menuitem',\n 'XCUIElementTypeMenuButton': 'button',\n 'XCUIElementTypeToggle': 'switch',\n 'XCUIElementTypePopUpButton': 'combobox',\n 'XCUIElementTypeComboBox': 'combobox',\n 'XCUIElementTypeRadioButton': 'radio',\n 'XCUIElementTypeRadioGroup': 'group',\n 'XCUIElementTypeToolbar': 'toolbar',\n 'XCUIElementTypeProgressIndicator': 'progressbar',\n 'XCUIElementTypeActivityIndicator': 'progressbar',\n 'XCUIElementTypeColorWell': 'button',\n}\n\nexport const IOS_EDITABLE_TYPES: ReadonlySet<string> = new Set([\n 'XCUIElementTypeTextField',\n 'XCUIElementTypeSecureTextField',\n 'XCUIElementTypeSearchField',\n 'XCUIElementTypeTextView',\n])\n\nconst IOS_TRAIT_ROLE_PRECEDENCE: ReadonlyArray<[ReadonlyArray<string>, string]> = [\n [['SearchField'], 'searchbox'],\n [['Adjustable'], 'slider'],\n [['TabBar'], 'tablist'],\n [['Button', 'ToggleButton'], 'button'],\n [['Link'], 'link'],\n [['Header'], 'heading'],\n [['Image'], 'image'],\n [['StaticText', 'UpdatesFrequently', 'SummaryElement'], 'text'],\n]\n\n// WDA joins trait names in dictionary order, so the string is split rather than matched whole.\nexport function iosAccessibleOtherRole(traits: string | undefined): string {\n const names = new Set(\n (traits ?? '')\n .split(',')\n .map(t => t.trim())\n .filter(t => t.length > 0),\n )\n for (const [traitNames, role] of IOS_TRAIT_ROLE_PRECEDENCE) {\n if (traitNames.some(t => names.has(t))) return role\n }\n return 'button'\n}\n\nexport function normalizeRole(type: string, platform: 'android' | 'ios'): string {\n const map = platform === 'android' ? ANDROID_ROLE_MAP : IOS_ROLE_MAP\n const mapped = map[type]\n if (mapped) return mapped\n\n // Fallback: strip known prefixes and lowercase\n let fallback = type\n if (platform === 'ios') {\n fallback = fallback.replace(/^XCUIElementType/, '')\n } else {\n fallback = fallback\n .replace(/^android\\.widget\\./, '')\n .replace(/^android\\.view\\./, '')\n .replace(/^android\\.webkit\\./, '')\n .replace(/^androidx\\.[\\w.]+\\./, '')\n .replace(/^com\\.google\\.android\\.[\\w.]+\\./, '')\n .replace(/^com\\.android\\.[\\w.]+\\./, '')\n }\n return fallback.toLowerCase() || 'element'\n}\n","import type { Action } from '@vostride/agent-qa-runner'\nimport type { MobileRefMap } from './types.js'\n\nconst ACTIONS_WITHOUT_REF = new Set(['navigate', 'waitFor', 'delay', 'assert', 'scroll', 'swipe', 'pinch', 'multiTap'])\n\nexport class MobileElementResolver {\n constructor(private refs: MobileRefMap) {}\n\n resolve(ref: string): { role: string; name?: string; bounds: { x: number; y: number; width: number; height: number }; center: { x: number; y: number } } {\n const data = this.refs[ref]\n if (!data) {\n const available = Object.keys(this.refs).join(', ') || 'none'\n throw new Error(`Unknown ref \"${ref}\". Available refs: ${available}`)\n }\n\n if (!data.bounds) {\n throw new Error(`Ref \"${ref}\" (${data.role}${data.name ? ` \"${data.name}\"` : ''}) has no bounds for coordinate resolution`)\n }\n\n const center = {\n x: data.bounds.x + data.bounds.width / 2,\n y: data.bounds.y + data.bounds.height / 2,\n }\n\n return {\n role: data.role,\n name: data.name,\n bounds: data.bounds,\n center,\n }\n }\n\n resolveAction(action: Action): { bounds: { x: number; y: number; width: number; height: number }; center: { x: number; y: number } } | null {\n if (ACTIONS_WITHOUT_REF.has(action.type)) {\n // scroll/swipe may have optional ref\n if (('ref' in action) && typeof (action as { ref?: string }).ref === 'string') {\n const resolved = this.resolve((action as { ref: string }).ref)\n return { bounds: resolved.bounds, center: resolved.center }\n }\n return null\n }\n\n if ('ref' in action && typeof (action as { ref?: string }).ref === 'string') {\n const resolved = this.resolve((action as { ref: string }).ref)\n return { bounds: resolved.bounds, center: resolved.center }\n }\n\n return null\n }\n}\n","export const KEY_MAP: Record<string, string> = {\n Enter: '\\uE007',\n Tab: '\\uE004',\n Escape: '\\uE00C',\n Backspace: '\\uE003',\n Space: '\\uE00D',\n ArrowUp: '\\uE013',\n ArrowDown: '\\uE014',\n ArrowLeft: '\\uE012',\n ArrowRight: '\\uE011',\n}\n\nexport function computePinch(\n centerX: number, centerY: number,\n scale: number,\n startDistance = 100,\n): {\n finger1Start: { x: number; y: number }; finger1End: { x: number; y: number }\n finger2Start: { x: number; y: number }; finger2End: { x: number; y: number }\n} {\n const halfStart = startDistance / 2\n const halfEnd = (startDistance * scale) / 2\n\n return {\n finger1Start: { x: centerX - halfStart, y: centerY },\n finger1End: { x: centerX - halfEnd, y: centerY },\n finger2Start: { x: centerX + halfStart, y: centerY },\n finger2End: { x: centerX + halfEnd, y: centerY },\n }\n}\n\nexport function computeFingerPositions(\n centerX: number, centerY: number,\n fingers: number,\n spacing = 40,\n): { x: number; y: number }[] {\n if (fingers === 2) {\n return [\n { x: centerX - spacing / 2, y: centerY },\n { x: centerX + spacing / 2, y: centerY },\n ]\n }\n // 3 fingers: triangle arrangement\n return [\n { x: centerX, y: centerY - spacing / 2 },\n { x: centerX - spacing / 2, y: centerY + spacing / 2 },\n { x: centerX + spacing / 2, y: centerY + spacing / 2 },\n ]\n}\n\nexport function computeSwipe(\n centerX: number, centerY: number,\n direction: 'up' | 'down' | 'left' | 'right',\n distance: number,\n): { startX: number; startY: number; endX: number; endY: number } {\n switch (direction) {\n case 'up':\n return { startX: centerX, startY: centerY + distance / 2, endX: centerX, endY: centerY - distance / 2 }\n case 'down':\n return { startX: centerX, startY: centerY - distance / 2, endX: centerX, endY: centerY + distance / 2 }\n case 'left':\n return { startX: centerX + distance / 2, startY: centerY, endX: centerX - distance / 2, endY: centerY }\n case 'right':\n return { startX: centerX - distance / 2, startY: centerY, endX: centerX + distance / 2, endY: centerY }\n }\n}\n","import { existsSync } from 'node:fs'\nimport { dirname, resolve as resolvePath } from 'node:path'\n\nexport type MobilePlatform = 'android' | 'ios'\nexport type MobileAppState = 'preserve' | 'reset'\n\nexport type MobileSetupErrorCategory =\n | 'device-resolution'\n | 'appium-startup'\n | 'device-readiness'\n | 'adapter-load'\n | 'app-install'\n | 'app-launch'\n\nexport interface MobileSetupErrorOptions {\n category: MobileSetupErrorCategory\n message: string\n platform?: MobilePlatform\n targetName?: string\n deviceName?: string\n appId?: string\n cause?: unknown\n sourceTrace?: string[]\n}\n\nexport class MobileSetupError extends Error {\n readonly category: MobileSetupErrorCategory\n readonly platform?: MobilePlatform\n readonly targetName?: string\n readonly deviceName?: string\n readonly appId?: string\n readonly sourceTrace?: string[]\n override readonly cause?: unknown\n\n constructor(options: MobileSetupErrorOptions) {\n super(options.message)\n this.name = 'MobileSetupError'\n this.category = options.category\n this.platform = options.platform\n this.targetName = options.targetName\n this.deviceName = options.deviceName\n this.appId = options.appId\n this.sourceTrace = options.sourceTrace\n this.cause = options.cause\n }\n}\n\nexport interface ResolvedMobileDevice {\n name: string\n platform: MobilePlatform\n match: Record<string, unknown>\n}\n\nexport interface ResolvedMobileAppInstall {\n path?: string\n sourceTrace: Record<string, string>\n}\n\nexport interface ResolvedMobileApp {\n bundleId?: string\n appPackage?: string\n appActivity?: string\n deepLinkAppId?: string\n install?: ResolvedMobileAppInstall\n sourceTrace: Record<string, string>\n}\n\nexport interface ResolvedMobileRunConfig {\n platform: MobilePlatform\n targetName: string\n deviceName: string\n device: ResolvedMobileDevice\n app: ResolvedMobileApp\n appState: MobileAppState\n appium: { url?: string; managed?: boolean }\n sourceTrace: string[]\n}\n\nexport interface ResolveMobileRunConfigInput {\n config: Record<string, any>\n targetName: string\n platform?: MobilePlatform\n explicitDeviceName?: string\n useDeviceName?: string\n appState?: MobileAppState\n localBindings?: {\n devices?: Record<string, Record<string, unknown>>\n apps?: Record<string, { path?: string }>\n filePath?: string\n } | null\n configFilePath?: string\n localConfigFilePath?: string\n appiumUrl?: string\n}\n\ninterface TargetEntry {\n platform?: string\n bundleId?: string\n appPackage?: string\n appActivity?: string\n app?: {\n path?: string\n }\n device?: string\n}\n\ninterface DeviceProfile {\n platform?: string\n match?: Record<string, unknown>\n}\n\nfunction isMobilePlatform(value: unknown): value is MobilePlatform {\n return value === 'android' || value === 'ios'\n}\n\nfunction asOptionalString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction isAbsoluteAppInstallValue(value: string): boolean {\n return value.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(value) || value.startsWith('\\\\\\\\')\n}\n\nfunction baseDirFor(filePath?: string): string {\n return filePath ? dirname(filePath) : process.cwd()\n}\n\nfunction setupError(\n message: string,\n input: ResolveMobileRunConfigInput,\n extras: Partial<Omit<MobileSetupErrorOptions, 'category' | 'message' | 'targetName'>> = {},\n): MobileSetupError {\n return new MobileSetupError({\n category: 'device-resolution',\n message,\n targetName: input.targetName,\n ...extras,\n })\n}\n\nfunction appInstallError(\n message: string,\n input: ResolveMobileRunConfigInput,\n extras: Partial<Omit<MobileSetupErrorOptions, 'category' | 'message' | 'targetName'>> = {},\n): MobileSetupError {\n return new MobileSetupError({\n category: 'app-install',\n message,\n targetName: input.targetName,\n ...extras,\n })\n}\n\nfunction chooseDeviceName(input: ResolveMobileRunConfigInput): { name?: string; source?: string } {\n const candidates = [\n ['explicitDeviceName', input.explicitDeviceName],\n ['use.device', input.useDeviceName],\n ] as const\n\n for (const [source, value] of candidates) {\n const name = asOptionalString(value)\n if (name) return { name, source }\n }\n\n return {}\n}\n\nfunction resolveAppField(\n field: 'bundleId' | 'appPackage' | 'appActivity',\n targetValue: unknown,\n deviceValue: unknown,\n targetName: string,\n deviceName: string,\n input: ResolveMobileRunConfigInput,\n): { value?: string; source?: string } {\n const targetString = asOptionalString(targetValue)\n const deviceString = asOptionalString(deviceValue)\n\n if (targetString && deviceString && targetString !== deviceString) {\n throw setupError(\n `Conflicting ${field} for mobile target \"${targetName}\" and device \"${deviceName}\": target has \"${targetString}\", device has \"${deviceString}\"`,\n input,\n {\n deviceName,\n appId: targetString,\n },\n )\n }\n\n if (targetString) {\n return {\n value: targetString,\n source: `registry.targets.${targetName}.${field}`,\n }\n }\n if (deviceString) {\n return {\n value: deviceString,\n source: `registry.devices.${deviceName}.match.${field}`,\n }\n }\n return {}\n}\n\nfunction resolveAppInstall(\n target: TargetEntry,\n input: ResolveMobileRunConfigInput,\n platform: MobilePlatform,\n deviceName: string,\n sourceTrace: string[],\n): ResolvedMobileAppInstall | undefined {\n const localApp = input.localBindings?.apps?.[input.targetName]\n const installSourceTrace: Record<string, string> = {}\n\n const localPath = asOptionalString(localApp?.path)\n const targetPath = asOptionalString(target.app?.path)\n const pathValue = localPath ?? targetPath\n const pathSource = localPath\n ? `agent-qa.local.yaml apps.${input.targetName}.path`\n : targetPath\n ? `agent-qa.config.yaml registry.targets.${input.targetName}.app.path`\n : undefined\n const pathBaseDir = localPath\n ? baseDirFor(input.localConfigFilePath ?? input.localBindings?.filePath)\n : targetPath\n ? baseDirFor(input.configFilePath)\n : undefined\n\n const install: ResolvedMobileAppInstall = { sourceTrace: installSourceTrace }\n\n if (pathValue) {\n if (isAbsoluteAppInstallValue(pathValue)) {\n throw appInstallError(`Configured app path must be relative: ${pathValue}`, input, {\n platform,\n deviceName,\n appId: pathValue,\n sourceTrace: [...sourceTrace, `app.path=${pathSource}`],\n })\n }\n const resolvedPath = resolvePath(pathBaseDir ?? process.cwd(), pathValue)\n if (!existsSync(resolvedPath)) {\n throw appInstallError(`Configured app path not found: ${resolvedPath}`, input, {\n platform,\n deviceName,\n appId: pathValue,\n sourceTrace: [...sourceTrace, `app.path=${pathSource}`],\n })\n }\n install.path = resolvedPath\n if (pathSource) {\n installSourceTrace['app.path'] = pathSource\n sourceTrace.push(`app.path=${pathSource}`)\n }\n }\n\n return install.path ? install : undefined\n}\n\nexport function resolveMobileRunConfig(input: ResolveMobileRunConfigInput): ResolvedMobileRunConfig {\n const targets = input.config.registry?.targets as Record<string, TargetEntry> | undefined\n const target = targets?.[input.targetName]\n if (!target) {\n const available = targets ? Object.keys(targets).join(', ') : 'none'\n throw setupError(\n `Target \"${input.targetName}\" not found in config. Available targets: ${available}`,\n input,\n )\n }\n\n const platformCandidate = input.platform ?? target.platform\n if (!isMobilePlatform(platformCandidate)) {\n throw setupError(\n `Target \"${input.targetName}\" is not a mobile target`,\n input,\n )\n }\n const platform = platformCandidate\n\n const appState = input.appState\n if (appState !== 'preserve' && appState !== 'reset') {\n throw setupError(\n 'use.mobile.appState is required for native mobile app targets and must be one of: preserve | reset',\n input,\n { platform },\n )\n }\n\n const chosenDevice = chooseDeviceName(input)\n if (!chosenDevice.name) {\n throw setupError(\n `No device specified for mobile target \"${input.targetName}\"`,\n input,\n { platform },\n )\n }\n const deviceName = chosenDevice.name\n\n const devices = input.config.registry?.devices as Record<string, DeviceProfile> | undefined\n const deviceProfile = devices?.[deviceName]\n if (!deviceProfile) {\n const available = devices ? Object.keys(devices).join(', ') : 'none'\n throw setupError(\n `Device \"${deviceName}\" not found in registry.devices. Available devices: ${available}`,\n input,\n { platform, deviceName },\n )\n }\n\n if (deviceProfile.platform !== platform) {\n throw setupError(\n `Device \"${deviceName}\" platform \"${deviceProfile.platform ?? 'unknown'}\" does not match target \"${input.targetName}\" platform \"${platform}\"`,\n input,\n { platform, deviceName },\n )\n }\n\n const localMatch = input.localBindings?.devices?.[deviceName] ?? null\n const mergedMatch = { ...(deviceProfile.match ?? {}), ...(localMatch ?? {}) }\n\n const appSourceTrace: Record<string, string> = {}\n const sourceTrace = [\n `target=registry.targets.${input.targetName}`,\n `platform=${platform}`,\n `device=${chosenDevice.source}:${deviceName}`,\n `appState=use.mobile.appState:${appState}`,\n ]\n\n let app: ResolvedMobileApp\n if (platform === 'android') {\n const appPackage = resolveAppField('appPackage', target.appPackage, mergedMatch.appPackage, input.targetName, deviceName, input)\n const appActivity = resolveAppField('appActivity', target.appActivity, mergedMatch.appActivity, input.targetName, deviceName, input)\n if (appPackage.source) appSourceTrace.appPackage = appPackage.source\n if (appActivity.source) appSourceTrace.appActivity = appActivity.source\n app = {\n appPackage: appPackage.value,\n appActivity: appActivity.value,\n deepLinkAppId: appPackage.value,\n sourceTrace: appSourceTrace,\n }\n if (appPackage.source) sourceTrace.push(`app.appPackage=${appPackage.source}`)\n if (appActivity.source) sourceTrace.push(`app.appActivity=${appActivity.source}`)\n } else {\n const bundleId = resolveAppField('bundleId', target.bundleId, mergedMatch.bundleId, input.targetName, deviceName, input)\n if (bundleId.source) appSourceTrace.bundleId = bundleId.source\n app = {\n bundleId: bundleId.value,\n deepLinkAppId: bundleId.value,\n sourceTrace: appSourceTrace,\n }\n if (bundleId.source) sourceTrace.push(`app.bundleId=${bundleId.source}`)\n }\n\n const install = resolveAppInstall(target, input, platform, deviceName, sourceTrace)\n if (install) {\n app.install = install\n }\n\n return {\n platform,\n targetName: input.targetName,\n deviceName,\n device: {\n name: deviceName,\n platform,\n match: mergedMatch,\n },\n app,\n appState,\n appium: {\n url: input.appiumUrl,\n managed: !input.appiumUrl,\n },\n sourceTrace,\n }\n}\n","import { existsSync } from 'node:fs'\nimport { dirname, join, parse, resolve } from 'node:path'\n\nexport type AppiumExecutableSource = 'local' | 'path'\n\nexport interface ResolvedAppiumExecutable {\n command: string\n source: AppiumExecutableSource\n}\n\nexport interface ResolveAppiumExecutableOptions {\n cwd?: string\n platform?: NodeJS.Platform\n exists?: (path: string) => boolean\n}\n\nexport function localAppiumBinaryNames(platform: NodeJS.Platform = process.platform): string[] {\n return platform === 'win32' ? ['appium.cmd', 'appium.exe', 'appium'] : ['appium']\n}\n\nexport function resolveAppiumExecutable(opts: ResolveAppiumExecutableOptions = {}): ResolvedAppiumExecutable {\n const exists = opts.exists ?? existsSync\n const names = localAppiumBinaryNames(opts.platform ?? process.platform)\n let current = resolve(opts.cwd ?? process.cwd())\n const root = parse(current).root\n\n while (true) {\n for (const name of names) {\n const candidate = join(current, 'node_modules', '.bin', name)\n if (exists(candidate)) {\n return { command: candidate, source: 'local' }\n }\n }\n\n if (current === root) break\n current = dirname(current)\n }\n\n return { command: 'appium', source: 'path' }\n}\n\nexport function formatAppiumInstallGuidance(): string {\n return 'Install Appium locally with `npm install -D appium` (or `pnpm add -D appium` / `yarn add -D appium`). If you prefer a machine-wide setup, use `npm install -g appium`.'\n}\n","import { scrollerSetSwipeSignal } from '@vostride/agent-qa-runner'\nimport type { Direction, DocumentScrollOffsets, SwipeSignal } from '@vostride/agent-qa-runner'\n\n// Judged over identified on-screen scrollers; a frame in view makes the read null.\n\n/** One WebView scroller with a structural identity: `document`, or a flat-tree path plus tag, id and class. */\nexport interface IdentifiedScrollOffsets extends DocumentScrollOffsets {\n id: string\n}\n\n/**\n * A WebDriver `execute` function body. It answers `null` when a frame (`iframe`, `frame`, `embed`,\n * `object`, `fencedframe`) with positive area intersects the viewport, because a swipe over it\n * moves content the page cannot measure. Otherwise it answers the document scroller first (id\n * `document`), then every on-screen element scroller in the document and its open shadow roots,\n * in tree order. A body whose overflow propagates to the viewport is not a member. Nothing is\n * written to the page: ids derive from structure alone. Closed shadow roots are unreachable.\n */\nexport const WEBVIEW_SCROLLERS_SCRIPT: string =\n 'var d = document, w = window, s = d.scrollingElement || d.documentElement;'\n + 'var vw = w.innerWidth, vh = w.innerHeight;'\n + 'var frames = { IFRAME: 1, FRAME: 1, EMBED: 1, OBJECT: 1, FENCEDFRAME: 1 };'\n + 'var sc = function (v) { return v === \"auto\" || v === \"scroll\" || v === \"overlay\"; };'\n + 'var inView = function (el) {'\n + ' var r = el.getBoundingClientRect();'\n + ' return Math.min(r.right, vw) > Math.max(r.left, 0) && Math.min(r.bottom, vh) > Math.max(r.top, 0);'\n + '};'\n + 'var rs = getComputedStyle(d.documentElement);'\n + 'var bodyPropagates = rs.overflowX === \"visible\" && rs.overflowY === \"visible\";'\n + 'var out = [{ id: \"document\", x: w.scrollX, y: w.scrollY,'\n + ' maxX: s.scrollWidth - s.clientWidth, maxY: s.scrollHeight - s.clientHeight }];'\n + 'var stack = [{ el: d.documentElement, path: \"0\" }];'\n + 'while (stack.length > 0) {'\n + ' var item = stack.pop(), el = item.el, path = item.path;'\n + ' var kids = [], i;'\n + ' if (el.shadowRoot) { for (i = 0; i < el.shadowRoot.children.length; i++) kids.push({ el: el.shadowRoot.children[i], path: path + \"/s\" + i }); }'\n + ' for (i = 0; i < el.children.length; i++) kids.push({ el: el.children[i], path: path + \"/\" + i });'\n + ' for (i = kids.length - 1; i >= 0; i--) stack.push(kids[i]);'\n + ' if (frames[String(el.tagName).toUpperCase()] && inView(el)) return null;'\n + ' if (el === s || el === d.documentElement || (el === d.body && bodyPropagates)) continue;'\n + ' var mx = el.scrollWidth - el.clientWidth, my = el.scrollHeight - el.clientHeight;'\n + ' if (!(mx > 0 || my > 0)) continue;'\n + ' var st = getComputedStyle(el);'\n + ' var sx = mx > 0 && sc(st.overflowX), sy = my > 0 && sc(st.overflowY);'\n + ' if ((!sx && !sy) || !inView(el)) continue;'\n + ' out.push({ id: path + \"|\" + String(el.localName) + \"#\" + (el.getAttribute(\"id\") || \"\") + \".\" + (el.getAttribute(\"class\") || \"\"),'\n + ' x: el.scrollLeft, y: el.scrollTop, maxX: sx ? mx : 0, maxY: sy ? my : 0 });'\n + '}'\n + 'return out;'\n\nfunction memberOf(value: unknown): IdentifiedScrollOffsets | undefined {\n if (!value || typeof value !== 'object') return undefined\n const { id, x, y, maxX, maxY } = value as Record<string, unknown>\n if (typeof id !== 'string' || id.length === 0) return undefined\n const offsets = [x, y, maxX, maxY]\n if (!offsets.every((n) => typeof n === 'number' && Number.isFinite(n))) return undefined\n return { id, x, y, maxX, maxY } as IdentifiedScrollOffsets\n}\n\nfunction byId(members: readonly unknown[]): Map<string, IdentifiedScrollOffsets> | undefined {\n if (members.length === 0) return undefined\n const map = new Map<string, IdentifiedScrollOffsets>()\n for (const value of members) {\n const member = memberOf(value)\n if (!member || map.has(member.id)) return undefined\n map.set(member.id, member)\n }\n return map\n}\n\n/** A non-empty array of members with string ids, finite offsets and no duplicate id; else undefined. */\nexport function parseWebViewScrollers(raw: unknown): IdentifiedScrollOffsets[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const map = byId(raw)\n return map ? [...map.values()] : undefined\n}\n\n/**\n * Before and after are paired by id. The same membership is judged by the scroller-set rule; a\n * changed membership is `moved` only when a member present in both reads moved, else `unknown`.\n */\nexport function webViewSwipeSignal(\n direction: Direction,\n before: readonly IdentifiedScrollOffsets[] | undefined,\n after: readonly IdentifiedScrollOffsets[] | undefined,\n): SwipeSignal {\n if (!before || !after) return 'unknown'\n const b = byId(before)\n const a = byId(after)\n if (!b || !a) return 'unknown'\n const common = [...b.keys()].filter((id) => a.has(id))\n const signal = scrollerSetSwipeSignal(\n direction,\n common.map((id) => b.get(id)!),\n common.map((id) => a.get(id)!),\n )\n const same = common.length === b.size && common.length === a.size\n if (same) return signal\n return signal === 'moved' ? 'moved' : 'unknown'\n}\n","import path from 'node:path'\nimport { DEFAULT_AGENT_QA_AUTH_STATES_DIR } from '../runtime-paths.js'\nimport { AuthStateNameSchema, TargetNameSchema } from './schema.js'\n\nexport type AuthStateTargetPlatform = 'web' | 'android' | 'ios'\n\nexport interface ResolveAuthStatePathsInput {\n configDir: string\n authStateDir?: string\n targetName: string\n stateName: string\n target?: {\n platform: AuthStateTargetPlatform\n }\n platform?: AuthStateTargetPlatform\n}\n\nexport interface ResolvedAuthStatePaths {\n targetName: string\n stateName: string\n rootDir: string\n targetDir: string\n payloadPath: string\n metadataPath: string\n}\n\nexport interface ResolveAuthStateRootInput {\n configDir: string\n authStateDir?: string\n}\n\nconst MOBILE_AUTH_STATE_ERROR = [\n 'auth state is only supported for web targets.',\n 'For native mobile, use use.mobile.appState: preserve when keeping app data between sessions.',\n 'App-state preservation is broader than auth and does not export generic secure-storage/keychain tokens.',\n].join(' ')\n\nfunction assertInsideRoot(rootDir: string, filePath: string): void {\n const relativePath = path.relative(rootDir, filePath)\n if (!relativePath || relativePath.startsWith('..') || path.isAbsolute(relativePath)) {\n throw new Error(`Resolved auth-state path escapes auth-state directory: ${filePath}`)\n }\n}\n\nexport function resolveAuthStateRoot(input: ResolveAuthStateRootInput): string {\n const { configDir, authStateDir } = input\n const configuredDir = authStateDir ?? DEFAULT_AGENT_QA_AUTH_STATES_DIR\n if (configuredDir.trim().length === 0) {\n throw new Error('authState.dir must be a non-empty path')\n }\n return path.isAbsolute(configuredDir)\n ? path.resolve(configuredDir)\n : path.resolve(configDir, configuredDir)\n}\n\nexport function resolveAuthStatePaths(input: ResolveAuthStatePathsInput): ResolvedAuthStatePaths {\n const targetName = TargetNameSchema.parse(input.targetName)\n const stateName = AuthStateNameSchema.parse(input.stateName)\n const platform = input.target?.platform ?? input.platform\n\n if (platform !== 'web') {\n throw new Error(MOBILE_AUTH_STATE_ERROR)\n }\n\n const rootDir = resolveAuthStateRoot({\n configDir: input.configDir,\n authStateDir: input.authStateDir,\n })\n const targetDir = path.join(rootDir, targetName)\n const payloadPath = path.join(targetDir, `${stateName}.json`)\n const metadataPath = path.join(targetDir, `${stateName}.meta.json`)\n\n assertInsideRoot(rootDir, payloadPath)\n assertInsideRoot(rootDir, metadataPath)\n\n return {\n targetName,\n stateName,\n rootDir,\n targetDir,\n payloadPath,\n metadataPath,\n }\n}\n","import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nexport const DEFAULT_AGENT_QA_RUNTIME_DIR = '.agent-qa'\nexport const DEFAULT_AGENT_QA_ARTIFACTS_DIR = '.agent-qa/artifacts'\nexport const DEFAULT_AGENT_QA_CACHE_DIR = '.agent-qa/cache'\nexport const DEFAULT_AGENT_QA_AUTH_STATES_DIR = '.agent-qa/auth-states'\nexport const DEFAULT_AGENT_QA_SCREENSHOTS_DIR = '.agent-qa/artifacts/screenshots'\nexport const DEFAULT_AGENT_QA_VIDEOS_DIR = '.agent-qa/artifacts/videos'\nexport const DEFAULT_AGENT_QA_RUNS_DB_PATH = '.agent-qa/runs.db'\nexport const LEGACY_AGENT_QA_DASHBOARD_DB_PATH = '.agent-qa/dashboard.db'\n\n/**\n * The runs database a config names, without migrating anything: the configured path, else the\n * default, else a legacy dashboard.db nothing has renamed yet. The writer's resolver renames that\n * legacy file on top of this; the CLI reader binds only the configured or default path.\n */\nexport function locateRunsDbPath(configDir: string, configuredDbPath?: string): string {\n const configured = configuredDbPath?.trim()\n if (configured) return resolve(configDir, configured)\n const defaultPath = resolve(configDir, DEFAULT_AGENT_QA_RUNS_DB_PATH)\n const legacyPath = resolve(configDir, LEGACY_AGENT_QA_DASHBOARD_DB_PATH)\n return !existsSync(defaultPath) && existsSync(legacyPath) ? legacyPath : defaultPath\n}\n","import { randomUUID } from 'node:crypto'\nimport type { Dirent } from 'node:fs'\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { AuthStateMetadataSchema, TargetNameSchema, type AuthStateMetadata } from './schema.js'\nimport { resolveAuthStatePaths, resolveAuthStateRoot, type ResolvedAuthStatePaths } from './resolver.js'\n\nexport interface WriteAuthStateFilesInput {\n payload: unknown\n metadata: AuthStateMetadata\n}\n\nexport interface ListAuthStateMetadataInput {\n configDir: string\n authStateDir?: string\n targetName?: string\n}\n\nexport interface RemoveAuthStateFilesInput {\n configDir: string\n authStateDir?: string\n targetName: string\n stateName: string\n target?: Parameters<typeof resolveAuthStatePaths>[0]['target']\n platform?: Parameters<typeof resolveAuthStatePaths>[0]['platform']\n}\n\nexport interface RemoveAuthStateTargetInput {\n configDir: string\n authStateDir?: string\n targetName: string\n target?: Parameters<typeof resolveAuthStatePaths>[0]['target']\n platform?: Parameters<typeof resolveAuthStatePaths>[0]['platform']\n}\n\nfunction assertMetadataMatches(paths: ResolvedAuthStatePaths, metadata: AuthStateMetadata): void {\n if (metadata.target !== paths.targetName) {\n throw new Error(`Auth-state metadata target \"${metadata.target}\" does not match resolved target \"${paths.targetName}\"`)\n }\n if (metadata.name !== paths.stateName) {\n throw new Error(`Auth-state metadata name \"${metadata.name}\" does not match resolved state \"${paths.stateName}\"`)\n }\n}\n\nasync function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n const serialized = `${JSON.stringify(value, null, 2)}\\n`\n const directory = path.dirname(filePath)\n const tempPath = path.join(directory, `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`)\n\n await mkdir(directory, { recursive: true })\n try {\n await writeFile(tempPath, serialized, { mode: 0o600 })\n await rename(tempPath, filePath)\n } catch (error) {\n await rm(tempPath, { force: true }).catch(() => undefined)\n throw error\n }\n}\n\nexport async function readAuthStateMetadata(paths: ResolvedAuthStatePaths): Promise<AuthStateMetadata> {\n let raw: string\n try {\n raw = await readFile(paths.metadataPath, 'utf-8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Auth-state metadata not found: ${paths.metadataPath}`)\n }\n throw error\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw new Error(`Invalid auth-state metadata JSON: ${paths.metadataPath}`)\n }\n\n const result = AuthStateMetadataSchema.safeParse(parsed)\n if (!result.success) {\n throw new Error(`Invalid auth-state metadata: ${result.error.issues.map(issue => issue.message).join('; ')}`)\n }\n\n assertMetadataMatches(paths, result.data)\n return result.data\n}\n\nexport async function writeAuthStateFiles(\n paths: ResolvedAuthStatePaths,\n input: WriteAuthStateFilesInput,\n): Promise<void> {\n const metadata = AuthStateMetadataSchema.parse(input.metadata)\n assertMetadataMatches(paths, metadata)\n\n await writeJsonAtomic(paths.payloadPath, input.payload)\n await writeJsonAtomic(paths.metadataPath, metadata)\n}\n\nexport async function listAuthStateMetadata(\n input: ListAuthStateMetadataInput,\n): Promise<AuthStateMetadata[]> {\n const rootDir = resolveAuthStateRoot({\n configDir: input.configDir,\n authStateDir: input.authStateDir,\n })\n const targetFilter = input.targetName ? TargetNameSchema.parse(input.targetName) : undefined\n\n let targetEntries: Dirent<string>[]\n try {\n targetEntries = await readdir(rootDir, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return []\n }\n throw error\n }\n\n const metadata: AuthStateMetadata[] = []\n for (const targetEntry of targetEntries) {\n if (!targetEntry.isDirectory()) continue\n const targetNameResult = TargetNameSchema.safeParse(targetEntry.name)\n if (!targetNameResult.success) continue\n const targetName = targetNameResult.data\n if (targetFilter && targetName !== targetFilter) continue\n\n let stateEntries: Dirent<string>[]\n const targetDir = path.join(rootDir, targetName)\n try {\n stateEntries = await readdir(targetDir, { withFileTypes: true })\n } catch {\n continue\n }\n\n for (const stateEntry of stateEntries) {\n if (!stateEntry.isFile() || !stateEntry.name.endsWith('.meta.json')) continue\n const stateName = stateEntry.name.slice(0, -'.meta.json'.length)\n const paths = (() => {\n try {\n return resolveAuthStatePaths({\n configDir: input.configDir,\n authStateDir: input.authStateDir,\n targetName,\n stateName,\n platform: 'web',\n })\n } catch {\n return null\n }\n })()\n if (!paths) continue\n\n try {\n const entry = await readAuthStateMetadata(paths)\n metadata.push(entry)\n } catch {\n continue\n }\n }\n }\n\n return metadata.sort((a, b) => {\n const targetOrder = a.target.localeCompare(b.target)\n return targetOrder === 0 ? a.name.localeCompare(b.name) : targetOrder\n })\n}\n\nexport async function removeAuthStateFiles(input: RemoveAuthStateFilesInput): Promise<void> {\n const paths = resolveAuthStatePaths(input)\n await rm(paths.payloadPath, { force: true })\n await rm(paths.metadataPath, { force: true })\n}\n\nexport async function removeAuthStateTarget(input: RemoveAuthStateTargetInput): Promise<void> {\n const paths = resolveAuthStatePaths({\n ...input,\n stateName: 'placeholder',\n })\n await rm(paths.targetDir, { recursive: true, force: true })\n}\n","import { readFile } from 'node:fs/promises'\nimport { readAuthStateMetadata } from './store.js'\nimport {\n resolveAuthStatePaths,\n type AuthStateTargetPlatform,\n type ResolvedAuthStatePaths,\n} from './resolver.js'\n\nexport interface ResolveAuthStateForRunInput {\n configDir: string\n authStateDir?: string\n targetName: string\n stateName: string\n target?: {\n platform: AuthStateTargetPlatform\n }\n platform?: AuthStateTargetPlatform\n}\n\nexport interface ResolvedAuthStateForRun {\n version: number\n kind: 'web'\n targetName: string\n stateName: string\n capturedAt: string\n storageStatePath: string\n}\n\nfunction createAuthStateReadError(targetName: string, stateName: string): Error {\n return new Error(\n `Auth state \"${stateName}\" for target \"${targetName}\" was not found or could not be read. ` +\n `Run agent-qa auth-state capture --target ${targetName} --name ${stateName}.`,\n )\n}\n\nasync function assertPayloadReadable(paths: ResolvedAuthStatePaths): Promise<void> {\n const raw = await readFile(paths.payloadPath, 'utf-8')\n JSON.parse(raw)\n}\n\nexport async function resolveAuthStateForRun(\n input: ResolveAuthStateForRunInput,\n): Promise<ResolvedAuthStateForRun> {\n const paths = resolveAuthStatePaths(input)\n\n try {\n const metadata = await readAuthStateMetadata(paths)\n await assertPayloadReadable(paths)\n return {\n version: metadata.version,\n kind: metadata.kind,\n targetName: metadata.target,\n stateName: metadata.name,\n capturedAt: metadata.capturedAt,\n storageStatePath: paths.payloadPath,\n }\n } catch {\n throw createAuthStateReadError(paths.targetName, paths.stateName)\n }\n}\n","// Re-exported from runner so core's auth-state consumers resolve through the core barrel.\n\nexport {\n AUTH_STATE_HOOK_JSON_ENV,\n AUTH_STATE_HOOK_STORAGE_STATE_PATH_ENV,\n AUTH_STATE_HOOK_WORKSPACE_DIR,\n AUTH_STATE_HOOK_STORAGE_STATE_FILENAME,\n AUTH_STATE_HOOK_CONTAINER_STORAGE_STATE_PATH,\n isReservedAuthStateHookEnvKey,\n stripReservedAuthStateHookEnv,\n buildAuthStateHookEnv,\n} from '@vostride/agent-qa-runner'\n","import { randomUUID } from 'node:crypto'\nimport {\n readFile,\n writeFile,\n mkdir,\n unlink,\n rename,\n rm,\n lstat,\n realpath,\n readlink,\n} from 'node:fs/promises'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport { homedir } from 'node:os'\nimport type { AuthCredential, AuthStore } from './types.js'\n\nexport function getAuthPath(): string {\n const xdg = process.env.XDG_DATA_HOME\n if (xdg) return join(xdg, 'agent-qa', 'auth.json')\n return join(homedir(), '.agent-qa', 'auth.json')\n}\n\nfunction isMissingFile(error: unknown): boolean {\n return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'\n}\n\nasync function isSymlink(authPath: string): Promise<boolean> {\n return lstat(authPath).then(\n stats => stats.isSymbolicLink(),\n (error: unknown) => {\n if (isMissingFile(error)) return false\n throw error\n },\n )\n}\n\n// A symlinked auth.json keeps its link: the file it points at is the one replaced, the same rule\n// ConfigManager.writeTarget applies to the config file.\nasync function authWriteTarget(authPath: string): Promise<string> {\n if (!(await isSymlink(authPath))) return authPath\n try {\n return await realpath(authPath)\n } catch (error) {\n if (!isMissingFile(error)) throw error\n return resolve(dirname(authPath), await readlink(authPath))\n }\n}\n\nasync function writeStoreAtomic(authPath: string, store: AuthStore): Promise<void> {\n const target = await authWriteTarget(authPath)\n const directory = dirname(target)\n const tempPath = join(directory, `.${basename(target)}.${process.pid}.${randomUUID()}.tmp`)\n await mkdir(directory, { recursive: true })\n try {\n await writeFile(tempPath, JSON.stringify(store, null, 2), { mode: 0o600 })\n await rename(tempPath, target)\n } catch (error) {\n await rm(tempPath, { force: true }).catch(() => undefined)\n throw error\n }\n}\n\nexport async function readAuth(path?: string): Promise<AuthStore> {\n const authPath = path ?? getAuthPath()\n try {\n const data = await readFile(authPath, 'utf-8')\n return JSON.parse(data) as AuthStore\n } catch {\n return {}\n }\n}\n\nexport async function writeAuth(\n provider: string,\n credential: AuthCredential,\n path?: string,\n): Promise<void> {\n const authPath = path ?? getAuthPath()\n const store = await readAuth(authPath)\n store[provider] = credential\n await writeStoreAtomic(authPath, store)\n}\n\nexport async function removeAuth(provider: string, path?: string): Promise<void> {\n const authPath = path ?? getAuthPath()\n const store = await readAuth(authPath)\n delete store[provider]\n if (Object.keys(store).length === 0 && !(await isSymlink(authPath))) {\n try {\n await unlink(authPath)\n } catch {\n // file already gone\n }\n return\n }\n await writeStoreAtomic(authPath, store)\n}\n\nexport async function getCredential(\n provider: string,\n path?: string,\n): Promise<AuthCredential | null> {\n const store = await readAuth(path)\n return store[provider] ?? null\n}\n","import type { LLMModelAdapter, OAuthTokens } from './types.js'\n\nexport type DashboardAuthMode = 'browser-poll' | 'manual-code'\n\nexport interface DashboardAuthMetadata {\n mode: DashboardAuthMode\n buttonLabel?: string\n}\n\nexport interface StartAuthContext {\n configName: string\n callbackUrl?: string\n}\n\nexport interface StartAuthResult {\n authorizeUrl: string\n sessionState?: unknown\n waitForTokens?: Promise<OAuthTokens>\n cleanup?: () => void\n}\n\nexport interface ExchangeCodeContext {\n code: string\n sessionState: unknown\n}\n\nexport interface CreateAuthFetchContext {\n getTokens: () => Promise<OAuthTokens>\n onRefreshed: (tokens: OAuthTokens) => Promise<void>\n}\n\nexport interface LLMAuthProviderPlugin {\n providerId: string\n credentialProviderId: string\n label: string\n modelAdapter: LLMModelAdapter\n dashboardAuth: DashboardAuthMetadata\n startAuth?: (ctx: StartAuthContext) => Promise<StartAuthResult>\n exchangeCode?: (ctx: ExchangeCodeContext) => Promise<OAuthTokens>\n createAuthFetch: (ctx: CreateAuthFetchContext) => typeof globalThis.fetch\n}\n\nconst plugins = new Map<string, LLMAuthProviderPlugin>()\n\nfunction validatePlugin(plugin: LLMAuthProviderPlugin): void {\n if (!plugin.providerId.trim()) {\n throw new Error('LLM auth plugin providerId is required')\n }\n if (!plugin.credentialProviderId.trim()) {\n throw new Error(`LLM auth plugin \"${plugin.providerId}\" credentialProviderId is required`)\n }\n if (!plugin.label.trim()) {\n throw new Error(`LLM auth plugin \"${plugin.providerId}\" label is required`)\n }\n}\n\nexport function registerLLMAuthProviderPlugin(plugin: LLMAuthProviderPlugin): void {\n validatePlugin(plugin)\n if (plugins.has(plugin.providerId)) {\n throw new Error(`LLM auth provider plugin \"${plugin.providerId}\" is already registered`)\n }\n plugins.set(plugin.providerId, plugin)\n}\n\nexport function registerLLMAuthProviderPlugins(providerPlugins: LLMAuthProviderPlugin[]): void {\n for (const plugin of providerPlugins) {\n registerLLMAuthProviderPlugin(plugin)\n }\n}\n\nexport function getLLMAuthProviderPlugin(providerId: string): LLMAuthProviderPlugin | undefined {\n return plugins.get(providerId)\n}\n\nexport function listLLMAuthProviderPlugins(): LLMAuthProviderPlugin[] {\n return [...plugins.values()]\n}\n\nexport function clearLLMAuthProviderPlugins(): void {\n plugins.clear()\n}\n","import { getLLMAuthProviderPlugin, type LLMAuthProviderPlugin } from './plugin-registry.js'\nimport { getCredential, writeAuth } from './store.js'\nimport type { AuthCredential, LLMProviderMode, OAuthTokens, ResolvedLLMAuth } from './types.js'\n\ninterface LLMAuthConfig {\n provider: LLMProviderMode | string\n model: string\n baseURL?: string\n providerHeaders?: Record<string, string>\n}\n\nconst SUBSCRIPTION_AUTH_PACKAGE = '@vostride/agent-qa-subscription-auth'\n\nexport const PUBLIC_PROVIDER_API_HOSTS: readonly string[] = Object.freeze([\n 'api.openai.com',\n 'api.anthropic.com',\n])\n\nfunction onPublicProviderApi(baseURL: string | undefined): boolean {\n if (typeof baseURL !== 'string' || !URL.canParse(baseURL)) return false\n return PUBLIC_PROVIDER_API_HOSTS.includes(new URL(baseURL).hostname)\n}\n\nfunction missingMessage(configName: string, provider: string, plugin?: LLMAuthProviderPlugin): string {\n if (plugin) {\n return `Sign in to \"${plugin.label}\" for the \"${configName}\" config: agent-qa auth login --config ${configName}`\n }\n\n const setKey = `agent-qa auth set --config ${configName} --type api-key`\n switch (provider) {\n case 'gemini':\n return `Save a Gemini API key for the \"${configName}\" config: ${setKey}`\n case 'openai-compatible':\n return `Save an API key for the \"${configName}\" config: ${setKey}`\n case 'anthropic-compatible':\n return `Save an API key for the \"${configName}\" config: ${setKey} (or --type bearer-token)`\n case 'openai-subscription':\n case 'anthropic-subscription':\n return `Provider \"${provider}\" needs the subscription-auth plugin: npm install -D ${SUBSCRIPTION_AUTH_PACKAGE}, and declare it under plugins.auth in agent-qa.config.yaml`\n default:\n return `Provider \"${provider}\" requires an auth plugin.`\n }\n}\n\nfunction unauthenticated(configName: string, provider: 'openai-compatible' | 'anthropic-compatible'): ResolvedLLMAuth {\n return {\n kind: 'unauthenticated',\n credentialKey: configName,\n provider,\n optional: true,\n message: 'Testing without a saved credential.',\n }\n}\n\nfunction isCompatibleProvider(provider: string): provider is 'openai-compatible' | 'anthropic-compatible' {\n return provider === 'openai-compatible' || provider === 'anthropic-compatible'\n}\n\nfunction usesApiKey(\n provider: string,\n plugin?: LLMAuthProviderPlugin,\n): provider is 'openai-compatible' | 'anthropic-compatible' | 'gemini' {\n return !plugin && (provider === 'openai-compatible' || provider === 'anthropic-compatible' || provider === 'gemini')\n}\n\nfunction unusableCredential(\n configName: string,\n provider: string,\n plugin?: LLMAuthProviderPlugin,\n): ResolvedLLMAuth {\n return isCompatibleProvider(provider)\n ? unauthenticated(configName, provider)\n : missing(configName, provider, plugin)\n}\n\nfunction missing(configName: string, provider: string, plugin?: LLMAuthProviderPlugin): ResolvedLLMAuth {\n return {\n kind: 'missing',\n credentialKey: configName,\n provider,\n required: true,\n message: missingMessage(configName, provider, plugin),\n }\n}\n\nfunction getOAuthTokens(\n configName: string,\n expectedProvider: string,\n authPath?: string,\n): () => Promise<OAuthTokens> {\n return async () => {\n const credential = await getCredential(configName, authPath)\n if (credential?.type !== 'oauth' || credential.provider !== expectedProvider) {\n throw new Error(`Expected ${expectedProvider} OAuth credential for ${configName}`)\n }\n return credential.tokens\n }\n}\n\nfunction writeRefreshedOAuth(\n configName: string,\n expectedProvider: string,\n authPath?: string,\n): (tokens: OAuthTokens) => Promise<void> {\n return async (tokens) => {\n const current = await getCredential(configName, authPath)\n if (current?.type !== 'oauth' || current.provider !== expectedProvider) {\n throw new Error(`Expected ${expectedProvider} OAuth credential for ${configName}`)\n }\n await writeAuth(configName, { ...current, tokens }, authPath)\n }\n}\n\nfunction authFetch(\n configName: string,\n plugin: LLMAuthProviderPlugin,\n credential: Extract<AuthCredential, { type: 'oauth' }>,\n authPath?: string,\n): ResolvedLLMAuth {\n const expectedProvider = plugin.credentialProviderId\n const getTokens = getOAuthTokens(configName, expectedProvider, authPath)\n const onRefreshed = writeRefreshedOAuth(configName, expectedProvider, authPath)\n\n return {\n kind: 'auth-fetch',\n credentialKey: configName,\n provider: plugin.providerId,\n modelAdapter: plugin.modelAdapter,\n fetch: plugin.createAuthFetch({ getTokens, onRefreshed }),\n expires: credential.tokens.expires,\n }\n}\n\nexport async function resolveLLMAuth(\n configName: string,\n llmConfig: LLMAuthConfig,\n authPath?: string,\n): Promise<ResolvedLLMAuth> {\n const credential = await getCredential(configName, authPath)\n const plugin = getLLMAuthProviderPlugin(llmConfig.provider)\n\n if (!credential) {\n // A keyless config on the public provider API cannot run.\n if (isCompatibleProvider(llmConfig.provider) && !onPublicProviderApi(llmConfig.baseURL)) {\n return unauthenticated(configName, llmConfig.provider)\n }\n return missing(configName, llmConfig.provider, plugin)\n }\n\n if (credential.type === 'api') {\n if (credential.provider !== llmConfig.provider) {\n return unusableCredential(configName, llmConfig.provider, plugin)\n }\n if (!usesApiKey(llmConfig.provider, plugin)) {\n return missing(configName, llmConfig.provider, plugin)\n }\n return {\n kind: 'api-key',\n credentialKey: configName,\n provider: llmConfig.provider,\n apiKey: credential.key,\n }\n }\n\n if (credential.type === 'bearer') {\n if (credential.provider !== llmConfig.provider || llmConfig.provider !== 'anthropic-compatible') {\n return unusableCredential(configName, llmConfig.provider, plugin)\n }\n return {\n kind: 'bearer-token',\n credentialKey: configName,\n provider: 'anthropic-compatible',\n token: credential.token,\n }\n }\n\n if (credential.type === 'oauth') {\n if (plugin) {\n if (credential.provider !== plugin.credentialProviderId) {\n return missing(configName, llmConfig.provider, plugin)\n }\n return authFetch(configName, plugin, credential, authPath)\n }\n return unusableCredential(configName, llmConfig.provider)\n }\n\n return missing(configName, llmConfig.provider, plugin)\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\n\nexport type PluginDeclarationLike = {\n package?: string\n path?: string\n}\n\n// Inside `baseDir` renders relative; elsewhere a fixed placeholder, never a `../` chain.\nfunction personFacingPath(candidate: string, baseDir: string): string {\n let raw = candidate\n if (raw.startsWith('file://')) {\n try {\n raw = fileURLToPath(raw)\n } catch {\n return '<path>'\n }\n }\n const fromBase = relative(baseDir, raw)\n if (fromBase === '' || fromBase.startsWith('..') || isAbsolute(fromBase)) return '<path>'\n return fromBase\n}\n\n// A separator starts a path only after a boundary, so `and/or` and a relative path survive.\nconst ABSOLUTE_PATH_IN_TEXT = /(^|[\\s'\"`([<])((?:file:\\/\\/)?(?:[A-Za-z]:)?[\\\\/][^\\s'\"`)\\]>]*)/g\n\nfunction stripAbsolutePaths(text: string, baseDir: string): string {\n return text.replace(\n ABSOLUTE_PATH_IN_TEXT,\n (_match, boundary: string, candidate: string) =>\n `${boundary}${personFacingPath(candidate, baseDir)}`,\n )\n}\n\nexport function findPackageJson(packageName: string, baseDir: string): string | null {\n let current = resolve(baseDir)\n while (true) {\n const candidate = resolve(current, 'node_modules', ...packageName.split('/'), 'package.json')\n if (existsSync(candidate)) return candidate\n\n const parent = dirname(current)\n if (parent === current) return null\n current = parent\n }\n}\n\nexport function exportTargetFromPackageJson(pkg: Record<string, unknown>): string | null {\n const exportsField = pkg.exports\n if (typeof exportsField === 'string') return exportsField\n if (exportsField && typeof exportsField === 'object') {\n const rootExport = (exportsField as Record<string, unknown>)['.'] ?? exportsField\n if (typeof rootExport === 'string') return rootExport\n if (rootExport && typeof rootExport === 'object') {\n const conditions = rootExport as Record<string, unknown>\n if (typeof conditions.import === 'string') return conditions.import\n if (typeof conditions.default === 'string') return conditions.default\n if (typeof conditions.require === 'string') return conditions.require\n }\n }\n if (typeof pkg.module === 'string') return pkg.module\n if (typeof pkg.main === 'string') return pkg.main\n return null\n}\n\n// Position, never content: Node's JSON `SyntaxError` quotes the file, so it is not the `cause`.\nexport class PluginPackageManifestError extends Error {\n readonly packageJsonPath: string\n\n constructor(packageJsonPath: string, baseDir: string) {\n super(\n `Plugin package manifest ${personFacingPath(packageJsonPath, baseDir)} could not be read `\n + `as JSON.`,\n )\n this.name = 'PluginPackageManifestError'\n this.packageJsonPath = packageJsonPath\n }\n}\n\nexport function resolvePackageImportFromBase(packageName: string, baseDir: string): string | null {\n const packageJsonPath = findPackageJson(packageName, baseDir)\n if (!packageJsonPath) return null\n\n let pkg: Record<string, unknown>\n try {\n pkg = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as Record<string, unknown>\n } catch {\n // Throw rather than return `null`, or a corrupt manifest falls through as not installed.\n throw new PluginPackageManifestError(packageJsonPath, baseDir)\n }\n const target = exportTargetFromPackageJson(pkg)\n if (!target || !target.startsWith('.')) return null\n return pathToFileURL(resolve(dirname(packageJsonPath), target)).href\n}\n\nexport function packageDeclarationValue(declaration: PluginDeclarationLike): string {\n return typeof declaration.package === 'string' ? declaration.package.trim() : ''\n}\n\nexport function pathDeclarationValue(declaration: PluginDeclarationLike): string {\n return typeof declaration.path === 'string' ? declaration.path.trim() : ''\n}\n\n// A dedup key only; use `declarationLabel` for anything that reaches a message.\nexport function declarationKey(declaration: PluginDeclarationLike, baseDir: string): string {\n const packageName = packageDeclarationValue(declaration)\n if (packageName) return `package:${packageName}`\n return `path:${resolve(baseDir, pathDeclarationValue(declaration))}`\n}\n\n// What a person reads: the declaration as written, never the absolute key.\nexport function declarationLabel(declaration: PluginDeclarationLike, baseDir: string): string {\n const packageName = packageDeclarationValue(declaration)\n if (packageName) return packageName\n\n const declared = pathDeclarationValue(declaration)\n if (!isAbsolute(declared)) return declared\n const fromBase = relative(baseDir, declared)\n return fromBase === '' || fromBase.startsWith('..') ? declared : fromBase\n}\n\nexport type PluginDeclarationKind = 'auth' | 'provider'\n\n// The command is offered only for a real npm name, because a person runs what is suggested.\nconst NPM_PACKAGE_NAME = /^(?:@[a-z0-9-._~]+\\/)?[a-z0-9-._~]+$/\n\nexport class PluginNotInstalledError extends Error {\n readonly pluginKind: PluginDeclarationKind\n readonly pluginPackage: string | null\n readonly pluginPath: string | null\n\n constructor(declaration: PluginDeclarationLike, kind: PluginDeclarationKind) {\n const label = kind === 'auth' ? 'Auth' : 'Provider'\n const packageName = packageDeclarationValue(declaration)\n const pluginPath = pathDeclarationValue(declaration)\n const remedy = NPM_PACKAGE_NAME.test(packageName)\n ? `Install it with your package manager (for example: npm install ${packageName}), or remove `\n + `the plugins.${kind} entry that declares it.`\n : `Install it with your package manager, or remove the plugins.${kind} entry that declares it.`\n // No `cause`: the wrapped error's require stack holds absolute paths `util.inspect` prints.\n super(\n packageName\n ? `${label} plugin package \"${packageName}\" is declared in agent-qa.config.yaml but is not `\n + `installed. ${remedy}`\n : `${label} plugin file \"${pluginPath}\" is declared in agent-qa.config.yaml but could not be `\n + `loaded. Check that the path is correct and the file exists, or remove the `\n + `plugins.${kind} entry that declares it.`,\n )\n this.name = 'PluginNotInstalledError'\n this.pluginKind = kind\n this.pluginPackage = packageName === '' ? null : packageName\n this.pluginPath = pluginPath === '' ? null : pluginPath\n }\n}\n\nfunction isModuleResolutionFailure(err: unknown): boolean {\n const code = (err as { code?: unknown } | null)?.code\n return code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND'\n}\n\n// Installed but unloadable; resolution codes also fire for a missing transitive dependency.\nexport class PluginLoadFailedError extends Error {\n readonly pluginKind: PluginDeclarationKind\n readonly pluginPackage: string\n\n constructor(packageName: string, kind: PluginDeclarationKind, underlying: string) {\n const label = kind === 'auth' ? 'Auth' : 'Provider'\n super(\n `${label} plugin package \"${packageName}\" is installed but failed to load: ${underlying}. `\n + `This is a fault in the plugin or in its own dependencies, not a missing install.`,\n )\n this.name = 'PluginLoadFailedError'\n this.pluginKind = kind\n this.pluginPackage = packageName\n }\n}\n\n// First line only, then absolute paths stripped: ESM writes its paths into the first line.\nfunction messageOf(err: unknown, baseDir: string): string {\n const text = err instanceof Error ? err.message : String(err)\n return stripAbsolutePaths(text.split('\\n', 1)[0] ?? '', baseDir)\n}\n\n/**\n * Translate a module-resolution failure into the error that names what is actually wrong.\n *\n * A PATH declaration keeps `PluginNotInstalledError` — its sentence is already about a file that\n * could not be loaded and says to check the path, which is the right thing to say either way.\n */\nfunction resolutionFailureFor(\n declaration: PluginDeclarationLike,\n baseDir: string,\n kind: PluginDeclarationKind,\n err: unknown,\n): Error {\n const packageName = packageDeclarationValue(declaration)\n if (packageName && findPackageJson(packageName, baseDir) !== null) {\n return new PluginLoadFailedError(packageName, kind, messageOf(err, baseDir))\n }\n return new PluginNotInstalledError(declaration, kind)\n}\n\n/**\n * Resolve and import one declared plugin, answering the person when the module is not there.\n *\n * ONLY module-resolution failures are translated, and only for a package the filesystem says is\n * ABSENT. A plugin that IS installed rethrows as `PluginLoadFailedError` (resolution fault inside\n * its own graph) or untouched (its own runtime throw) — disguising either as \"not installed\" would\n * send the person to install something they already have.\n */\nexport async function importDeclaredPluginModule<T>(\n declaration: PluginDeclarationLike,\n baseDir: string,\n kind: PluginDeclarationKind,\n): Promise<T> {\n let specifier: string\n try {\n specifier = resolveModuleSpecifier(declaration, baseDir)\n } catch (err) {\n if (isModuleResolutionFailure(err)) throw resolutionFailureFor(declaration, baseDir, kind, err)\n throw err\n }\n\n try {\n return await import(specifier) as T\n } catch (err) {\n if (isModuleResolutionFailure(err)) throw resolutionFailureFor(declaration, baseDir, kind, err)\n throw err\n }\n}\n\nexport function resolveModuleSpecifier(declaration: PluginDeclarationLike, baseDir: string): string {\n const packageName = packageDeclarationValue(declaration)\n if (packageName) {\n const packageImport = resolvePackageImportFromBase(packageName, baseDir)\n if (packageImport) return packageImport\n\n const parentUrl = pathToFileURL(resolve(baseDir, 'agent-qa.config.yaml')).href\n try {\n const resolveImport = import.meta.resolve as (specifier: string, parent?: string) => string\n return resolveImport(packageName, parentUrl)\n } catch {\n const require = createRequire(resolve(baseDir, 'agent-qa.config.yaml'))\n return pathToFileURL(require.resolve(packageName)).href\n }\n }\n\n const pluginPath = pathDeclarationValue(declaration)\n const absolutePath = isAbsolute(pluginPath)\n ? pluginPath\n : resolve(baseDir, pluginPath)\n return pathToFileURL(absolutePath).href\n}\n","import { registerLLMAuthProviderPlugins, type LLMAuthProviderPlugin } from './plugin-registry.js'\nimport {\n declarationKey,\n declarationLabel,\n importDeclaredPluginModule,\n packageDeclarationValue,\n pathDeclarationValue,\n} from '../plugin-loader-util.js'\n\nexport type AuthPluginDeclaration =\n | { package: string; path?: never }\n | { path: string; package?: never }\n\nexport interface AuthPluginBundle {\n providers: LLMAuthProviderPlugin[]\n}\n\nexport interface LoadLLMAuthPluginsOptions {\n baseDir?: string\n}\n\ntype AuthPluginFactory = () => AuthPluginBundle | Promise<AuthPluginBundle>\ntype AuthPluginModule = {\n createSubscriptionAuthPlugin?: AuthPluginFactory\n createAuthPlugin?: AuthPluginFactory\n default?: AuthPluginFactory | AuthPluginBundle | AuthPluginModule\n providers?: LLMAuthProviderPlugin[]\n}\n\nconst loadedDeclarations = new Set<string>()\n\nasync function resolvePluginBundle(module: AuthPluginModule, source: string): Promise<AuthPluginBundle> {\n if (typeof module.createSubscriptionAuthPlugin === 'function') {\n return await module.createSubscriptionAuthPlugin()\n }\n if (typeof module.createAuthPlugin === 'function') {\n return await module.createAuthPlugin()\n }\n if (typeof module.default === 'function') {\n return await module.default()\n }\n if (module.default && typeof module.default === 'object') {\n const defaultModule = module.default as AuthPluginModule\n if (typeof defaultModule.createSubscriptionAuthPlugin === 'function') {\n return await defaultModule.createSubscriptionAuthPlugin()\n }\n if (typeof defaultModule.createAuthPlugin === 'function') {\n return await defaultModule.createAuthPlugin()\n }\n }\n if (module.default && typeof module.default === 'object' && Array.isArray(module.default.providers)) {\n return { providers: module.default.providers }\n }\n if (Array.isArray(module.providers)) {\n return { providers: module.providers }\n }\n throw new Error(`Auth plugin \"${source}\" must export createSubscriptionAuthPlugin(), createAuthPlugin(), default, or providers.`)\n}\n\nfunction validateDeclaration(declaration: AuthPluginDeclaration): void {\n const packageName = packageDeclarationValue(declaration)\n const pluginPath = pathDeclarationValue(declaration)\n\n if (packageName && pluginPath) {\n throw new Error('Auth plugin declaration must specify either package or path, not both.')\n }\n if (!packageName && !pluginPath) {\n throw new Error('Auth plugin declaration must specify package or path.')\n }\n}\n\nexport async function loadLLMAuthPlugins(\n declarations: AuthPluginDeclaration[] | undefined,\n options: LoadLLMAuthPluginsOptions = {},\n): Promise<LLMAuthProviderPlugin[]> {\n if (!declarations?.length) return []\n const baseDir = options.baseDir ?? process.cwd()\n const loadedProviders: LLMAuthProviderPlugin[] = []\n\n for (const declaration of declarations) {\n validateDeclaration(declaration)\n const key = declarationKey(declaration, baseDir)\n if (loadedDeclarations.has(key)) continue\n\n // A declared plugin the project lacks gets the package name and install step, not a stack.\n const module = await importDeclaredPluginModule<AuthPluginModule>(declaration, baseDir, 'auth')\n // The map key is absolute and prefixed for collisions; the message uses the person's own label.\n const bundle = await resolvePluginBundle(module, declarationLabel(declaration, baseDir))\n\n registerLLMAuthProviderPlugins(bundle.providers)\n loadedDeclarations.add(key)\n loadedProviders.push(...bundle.providers)\n }\n\n return loadedProviders\n}\n\nexport function clearLoadedLLMAuthPluginModules(): void {\n loadedDeclarations.clear()\n}\n","import { randomBytes, createHash } from 'node:crypto'\n\nexport function generatePKCE(): { verifier: string; challenge: string } {\n const verifier = randomBytes(32).toString('base64url')\n const challenge = createHash('sha256').update(verifier).digest('base64url')\n return { verifier, challenge }\n}\n\nexport function generateState(): string {\n return randomBytes(16).toString('hex')\n}\n","import type { AuthProvider, OAuthTokens, TokenRefreshFn } from './types.js'\n\nexport interface CreateAuthFetchOptions {\n provider: AuthProvider\n getTokens: () => Promise<OAuthTokens>\n refreshTokens: TokenRefreshFn\n onTokensRefreshed: (tokens: OAuthTokens) => Promise<void>\n headerTransform?: (headers: Headers, tokens: OAuthTokens) => void\n urlTransform?: (url: string) => string\n}\n\nexport function createAuthFetch(options: CreateAuthFetchOptions): typeof globalThis.fetch {\n const { provider, getTokens, refreshTokens, onTokensRefreshed, headerTransform, urlTransform } =\n options\n\n return async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {\n let tokens = await getTokens()\n\n if (tokens.expires < Date.now()) {\n tokens = await refreshTokens(provider, tokens.refresh)\n await onTokensRefreshed(tokens)\n }\n\n // Build headers without creating a Request (avoids Node duplex stream issue)\n const headers = new Headers()\n if (input instanceof Request) {\n input.headers.forEach((value, key) => { headers.set(key, value) })\n }\n if (init?.headers) {\n if (init.headers instanceof Headers) {\n init.headers.forEach((value, key) => { headers.set(key, value) })\n } else if (Array.isArray(init.headers)) {\n for (const [key, value] of init.headers) {\n if (value !== undefined) headers.set(key, String(value))\n }\n } else {\n for (const [key, value] of Object.entries(init.headers)) {\n if (value !== undefined) headers.set(key, String(value))\n }\n }\n }\n\n // Strip existing auth headers\n headers.delete('authorization')\n headers.delete('x-api-key')\n\n // Inject Bearer token\n headers.set('Authorization', `Bearer ${tokens.access}`)\n\n if (headerTransform) {\n headerTransform(headers, tokens)\n }\n\n // Extract URL\n let url: string\n if (typeof input === 'string') url = input\n else if (input instanceof URL) url = input.toString()\n else url = input.url\n\n if (urlTransform) {\n url = urlTransform(url)\n }\n\n const response = await globalThis.fetch(url, {\n ...init,\n headers,\n })\n\n if (!response.ok) {\n const respBody = await response.text()\n return new Response(respBody, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n })\n }\n\n return response\n }\n}\n","import {\n declarationKey,\n declarationLabel,\n importDeclaredPluginModule,\n packageDeclarationValue,\n pathDeclarationValue,\n} from '../plugin-loader-util.js'\n\nexport type ProviderPluginDeclaration =\n | { package: string; path?: never }\n | { path: string; package?: never }\n\nexport interface ProviderPluginDescriptor {\n id: string\n label: string\n adapter: (transport: unknown, modelId: string) => unknown\n authModes: string[]\n needsBaseURL?: boolean\n subscription?: boolean\n credentialOptional?: boolean\n modelAdapter?: string\n baseURLPlaceholder?: string\n defaultModel?: string\n}\n\nexport interface LoadProviderPluginsOptions {\n baseDir?: string\n}\n\ntype ProviderPluginModule = {\n default?: unknown\n providers?: unknown\n [key: string]: unknown\n}\n\nconst loadedDeclarations = new Set<string>()\nlet warnedFirstParty = false\n\nfunction warnFirstPartyProviderPlugins(): void {\n if (warnedFirstParty) return\n console.warn(\n '[agent-qa] plugins.providers modules run in-process with full Node access and can read credentials or screenshots. Use first-party provider plugins only until the container sandbox exists.',\n )\n warnedFirstParty = true\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction isProviderDescriptorCandidate(value: unknown): boolean {\n return isRecord(value) && (\n 'id' in value ||\n 'label' in value ||\n 'adapter' in value ||\n 'authModes' in value\n )\n}\n\nfunction assertProviderDescriptor(value: unknown, source: string): asserts value is ProviderPluginDescriptor {\n if (!isRecord(value)) {\n throw new Error(`Provider plugin \"${source}\" exported a descriptor that is not an object.`)\n }\n if (typeof value.id !== 'string' || !value.id.trim()) {\n throw new Error(`Provider plugin \"${source}\" descriptor id is required.`)\n }\n if (typeof value.label !== 'string' || !value.label.trim()) {\n throw new Error(`Provider plugin \"${source}\" descriptor label is required.`)\n }\n if (typeof value.adapter !== 'function') {\n throw new Error(`Provider plugin \"${source}\" descriptor adapter is required.`)\n }\n if (!Array.isArray(value.authModes) || !value.authModes.every((mode) => typeof mode === 'string')) {\n throw new Error(`Provider plugin \"${source}\" descriptor authModes must be a string array.`)\n }\n}\n\nfunction extractProvidersArray(value: unknown, source: string): ProviderPluginDescriptor[] | null {\n if (!isRecord(value) || !Array.isArray(value.providers)) return null\n for (const descriptor of value.providers) {\n assertProviderDescriptor(descriptor, source)\n }\n return value.providers as ProviderPluginDescriptor[]\n}\n\nfunction extractDescriptors(module: ProviderPluginModule, source: string): ProviderPluginDescriptor[] {\n const defaultProviders = extractProvidersArray(module.default, source)\n if (defaultProviders) return defaultProviders\n\n if (isProviderDescriptorCandidate(module.default)) {\n assertProviderDescriptor(module.default, source)\n return [module.default]\n }\n\n const namedProviders = extractProvidersArray(module, source)\n if (namedProviders) return namedProviders\n\n const namedDescriptors: ProviderPluginDescriptor[] = []\n for (const [name, value] of Object.entries(module)) {\n if (name === 'default' || name === 'providers') continue\n if (!isProviderDescriptorCandidate(value)) continue\n assertProviderDescriptor(value, source)\n namedDescriptors.push(value)\n }\n if (namedDescriptors.length > 0) return namedDescriptors\n\n throw new Error(`Provider plugin \"${source}\" must export a provider descriptor or providers array.`)\n}\n\nfunction validateDeclaration(declaration: ProviderPluginDeclaration): void {\n const packageName = packageDeclarationValue(declaration)\n const pluginPath = pathDeclarationValue(declaration)\n\n if (packageName && pluginPath) {\n throw new Error('Provider plugin declaration must specify either package or path, not both.')\n }\n if (!packageName && !pluginPath) {\n throw new Error('Provider plugin declaration must specify package or path.')\n }\n}\n\nexport async function loadProviderPlugins(\n declarations: ProviderPluginDeclaration[] | undefined,\n options: LoadProviderPluginsOptions = {},\n): Promise<ProviderPluginDescriptor[]> {\n if (!declarations?.length) return []\n\n warnFirstPartyProviderPlugins()\n\n const baseDir = options.baseDir ?? process.cwd()\n const loadedProviders: ProviderPluginDescriptor[] = []\n\n for (const declaration of declarations) {\n validateDeclaration(declaration)\n const key = declarationKey(declaration, baseDir)\n if (loadedDeclarations.has(key)) continue\n\n // The provider road shares the auth road's resolve-and-import, so it shares the guard.\n const module = await importDeclaredPluginModule<ProviderPluginModule>(declaration, baseDir, 'provider')\n // Descriptors interpolate this label into messages, which must not carry the absolute key.\n const descriptors = extractDescriptors(module, declarationLabel(declaration, baseDir))\n\n loadedDeclarations.add(key)\n loadedProviders.push(...descriptors)\n }\n\n return loadedProviders\n}\n\nexport function clearLoadedProviderPluginModules(): void {\n loadedDeclarations.clear()\n warnedFirstParty = false\n}\n","import { z } from 'zod'\n\nexport type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug'\n\nexport const LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n}\n\nexport type LogSource = 'agent' | 'adapter' | 'cache' | 'planner' | 'hook' | 'runner'\n\nexport interface LogEntry {\n id: string\n stepId: string | null\n runId: string\n level: Exclude<LogLevel, 'silent'>\n source: LogSource\n message: string\n data: Record<string, unknown>\n timestamp: string\n}\n\nexport interface LogStorage {\n insertLogs(entries: LogEntry[]): void\n getLogs(opts: {\n runId?: string\n stepId?: string\n level?: string\n source?: string\n limit?: number\n offset?: number\n }): LogEntry[]\n}\n\nexport interface ScopedLogger {\n debug(msg: string, data?: Record<string, unknown>): void\n info(msg: string, data?: Record<string, unknown>): void\n warn(msg: string, data?: Record<string, unknown>): void\n error(msg: string, data?: Record<string, unknown>): void\n}\n\n// Per-source Zod data schemas\nexport const AgentLogDataSchema = z.object({\n hasScreenshot: z.boolean().optional(),\n duration: z.number().optional(),\n elementCount: z.number().optional(),\n})\n\nexport const AdapterLogDataSchema = z.object({\n actionType: z.string().optional(),\n selector: z.string().optional(),\n coordinates: z.object({ x: z.number(), y: z.number() }).optional(),\n elementProperties: z.record(z.string(), z.unknown()).optional(),\n duration: z.number().optional(),\n})\n\nexport const CacheLogDataSchema = z.object({\n operation: z.enum(['get', 'set', 'invalidate', 'bypass', 'batch-purge']),\n stepHash: z.string().optional(),\n screenHash: z.string().optional(),\n hit: z.boolean().optional(),\n age: z.number().optional(),\n entriesDeleted: z.number().optional(),\n})\n\nexport const PlannerLogDataSchema = z.object({\n model: z.string().optional(),\n promptTokens: z.number().optional(),\n completionTokens: z.number().optional(),\n latencyMs: z.number().optional(),\n confidence: z.number().optional(),\n actionType: z.string().optional(),\n})\n\nexport const HookLogDataSchema = z.object({\n hookName: z.string().optional(),\n phase: z.enum(['setup', 'teardown']).optional(),\n duration: z.number().optional(),\n success: z.boolean().optional(),\n})\n\nexport const RunnerLogDataSchema = z.object({\n stepIndex: z.number().optional(),\n totalSteps: z.number().optional(),\n testName: z.string().optional(),\n variablesCaptured: z.number().optional(),\n})\n\nexport const LogSourceDataSchemas: Record<LogSource, z.ZodType> = {\n agent: AgentLogDataSchema,\n adapter: AdapterLogDataSchema,\n cache: CacheLogDataSchema,\n planner: PlannerLogDataSchema,\n hook: HookLogDataSchema,\n runner: RunnerLogDataSchema,\n}\n","import { randomUUID } from 'node:crypto'\nimport { LOG_LEVEL_PRIORITY } from './types.js'\nimport type { LogLevel, LogSource, LogEntry, LogStorage, ScopedLogger } from './types.js'\nimport { formatLogEntry } from './cli-formatter.js'\nimport { guardJsonText, printRunText, type RunTextEnv } from './run-text-output.js'\nimport { redactSecretValue, type SecretRedactor } from '@vostride/agent-qa-runner'\n\n// `pending` holds only this member's unattributed lines, so a sibling's `setRunId` skips them.\nexport interface MemberLogScope {\n runId: string\n readonly pending: LogEntry[]\n}\n\n/**\n * The host's async-context primitive, named STRUCTURALLY so this package never imports\n * `node:async_hooks`.\n *\n * `packages/core`'s host baseline is a regenerable DEBT record with a per-area clearance map — a\n * list that is meant to shrink — so a new host import here would be new debt, not a permission.\n * The composition root already owns every other reach into the world, so it owns this one too and\n * injects it. `node:async_hooks`'s `AsyncLocalStorage<MemberLogScope>` satisfies this exactly, with\n * no adapter.\n */\nexport interface AsyncScopeStore<T> {\n getStore(): T | undefined\n run<R>(store: T, fn: () => R): R\n}\n\n/** Thrown when a caller asks for member isolation the composition root never wired up. */\nexport class MemberLogScopeUnavailableError extends Error {\n constructor() {\n super(\n 'LogManager.runInMemberScope requires a memberScope store. Construct the manager with ' +\n '`memberScope: new AsyncLocalStorage()` — without it, concurrent members would silently ' +\n 'share one run id.',\n )\n this.name = 'MemberLogScopeUnavailableError'\n }\n}\n\nexport class LogManager {\n private buffer: LogEntry[] = []\n private currentStepId: string | null = null\n private runId: string\n private runIdSet = false\n private readonly displayLevel: LogLevel\n private readonly storage?: LogStorage\n private readonly ndjson: boolean\n private redactor?: SecretRedactor\n private readonly memberScope?: AsyncScopeStore<MemberLogScope>\n private readonly env?: RunTextEnv\n\n constructor(opts: {\n runId?: string\n displayLevel: LogLevel\n storage?: LogStorage\n ndjson?: boolean\n redactor?: SecretRedactor\n memberScope?: AsyncScopeStore<MemberLogScope>\n env?: RunTextEnv\n }) {\n this.runId = opts.runId ?? ''\n this.runIdSet = !!opts.runId\n this.displayLevel = opts.displayLevel\n this.storage = opts.storage\n this.ndjson = opts.ndjson ?? false\n this.redactor = opts.redactor\n this.memberScope = opts.memberScope\n this.env = opts.env\n }\n\n setRedactor(redactor: SecretRedactor | undefined): void {\n this.redactor = redactor\n }\n\n // One manager serves every concurrent member; outside a scope `setRunId` backfills the buffer.\n runInMemberScope<T>(fn: () => T): T {\n if (!this.memberScope) throw new MemberLogScopeUnavailableError()\n return this.memberScope.run({ runId: this.runId, pending: [] }, fn)\n }\n\n log(\n level: Exclude<LogLevel, 'silent'>,\n source: LogSource,\n message: string,\n data?: Record<string, unknown>,\n ): void {\n const scope = this.memberScope?.getStore()\n const entry: LogEntry = {\n id: randomUUID(),\n stepId: this.currentStepId,\n runId: scope ? scope.runId : this.runId,\n level,\n source,\n message: redactSecretValue(message, this.redactor),\n data: redactSecretValue(data ?? {}, this.redactor),\n timestamp: new Date().toISOString(),\n }\n this.buffer.push(entry)\n if (scope && !entry.runId) scope.pending.push(entry)\n\n if (this.shouldDisplay(level)) {\n printRunText(\n formatLogEntry(entry),\n (line) => {\n process.stderr.write(`${line}\\n`)\n },\n { env: this.env },\n )\n }\n\n if (this.ndjson) {\n this.emitNdjson(entry)\n }\n }\n\n private shouldDisplay(entryLevel: Exclude<LogLevel, 'silent'>): boolean {\n if (this.displayLevel === 'silent') return false\n return LOG_LEVEL_PRIORITY[entryLevel] <= LOG_LEVEL_PRIORITY[this.displayLevel]\n }\n\n /**\n * The SECOND writer on the `AGENT_QA_EVENT:` stdout channel — the first is the CLI's\n * `reporters/wire-reporter.ts`, which prints run-event envelopes on the same prefix. Both are\n * armed by `AGENT_QA_LIVE_EVENTS=true` (this one indirectly: `commands/run.ts` passes\n * `ndjson: process.env.AGENT_QA_LIVE_EVENTS === 'true'`), both are off by default, and nothing in\n * the product sets that variable. Entries are already redacted above, and are printed verbatim.\n * A supported opt-in; the user-facing contract for both writers is the CLI README's\n * \"Live events on stdout (opt-in)\". Do not change this line shape without mirroring it there.\n */\n private emitNdjson(entry: LogEntry): void {\n process.stdout.write(\n `AGENT_QA_EVENT:${guardJsonText(JSON.stringify({ type: 'log', ...entry }), this.env)}\\n`,\n )\n }\n\n setCurrentStep(stepId: string): void {\n this.currentStepId = stepId\n }\n\n clearCurrentStep(): void {\n this.currentStepId = null\n }\n\n setRunId(runId: string): void {\n const scope = this.memberScope?.getStore()\n if (scope) {\n scope.runId = runId\n // This member's OWN pre-mint lines only. A sibling's unattributed lines live in ITS scope.\n for (const entry of scope.pending) entry.runId = runId\n scope.pending.length = 0\n // The flush gate is a manager-level fact: a scoped stamp is still a real run id, and without\n // this a fully-attributed concurrent run would be silently discarded at flush().\n this.runIdSet = true\n return\n }\n this.runId = runId\n this.runIdSet = true\n for (const entry of this.buffer) {\n entry.runId = runId\n }\n }\n\n flush(): void {\n if (this.storage && this.buffer.length > 0) {\n if (!this.runIdSet) {\n this.buffer = []\n return\n }\n this.storage.insertLogs(this.buffer)\n }\n this.buffer = []\n }\n\n getBuffer(): LogEntry[] {\n return [...this.buffer]\n }\n\n createScopedLogger(source: LogSource): ScopedLogger {\n return {\n debug: (msg: string, data?: Record<string, unknown>) =>\n this.log('debug', source, msg, data),\n info: (msg: string, data?: Record<string, unknown>) =>\n this.log('info', source, msg, data),\n warn: (msg: string, data?: Record<string, unknown>) =>\n this.log('warn', source, msg, data),\n error: (msg: string, data?: Record<string, unknown>) =>\n this.log('error', source, msg, data),\n }\n }\n}\n","import pc from 'picocolors'\nimport type { LogEntry } from './types.js'\n\nconst LEVEL_COLORS: Record<string, (s: string) => string> = {\n error: pc.red,\n warn: pc.yellow,\n info: (s: string) => s,\n debug: pc.dim,\n}\n\nexport function formatLogEntry(entry: LogEntry): string {\n const time = pc.dim(entry.timestamp.slice(11, 23))\n const level = (LEVEL_COLORS[entry.level] ?? ((s: string) => s))(entry.level.toUpperCase().padEnd(5))\n const source = pc.cyan(`[${entry.source}]`)\n const dataKeys = Object.keys(entry.data)\n const dataSuffix = dataKeys.length > 0\n ? ' ' + pc.dim(dataKeys.map(k => `${k}=${JSON.stringify(entry.data[k])}`).join(' '))\n : ''\n return `${time} ${level} ${source} ${entry.message}${dataSuffix}`\n}\n","import { randomBytes } from 'node:crypto'\n\nexport type RunTextEnv = Readonly<Record<string, string | undefined>>\n\nexport interface PrintRunTextOptions {\n readonly env?: RunTextEnv\n readonly stdoutIsData?: boolean\n}\n\n// The root entry and the subpath entry each bundle a copy of this module, so the count lives on\n// globalThis where a reservation taken through either is seen by both.\nconst STDOUT_RESERVATIONS = Symbol.for('agent-qa.run-text-output.stdout-reservations')\n\ninterface StdoutReservations {\n count: number\n}\n\nfunction stdoutReservations(): StdoutReservations {\n const holder = globalThis as typeof globalThis & { [STDOUT_RESERVATIONS]?: StdoutReservations }\n holder[STDOUT_RESERVATIONS] ??= { count: 0 }\n return holder[STDOUT_RESERVATIONS]\n}\n\nexport function isGitHubActions(env: RunTextEnv = process.env): boolean {\n const value = env.GITHUB_ACTIONS\n return value !== undefined && value !== '' && value.toLowerCase() !== 'false' && value !== '0'\n}\n\nexport function guardRunText(text: string, env: RunTextEnv = process.env): string {\n if (!isGitHubActions(env)) return text\n // Longer than 6 characters, so the runner masks the token in the log.\n const token = randomBytes(16).toString('hex')\n const block = text.endsWith('\\n') ? text : `${text}\\n`\n return `::stop-commands::${token}\\n${block}::${token}::\\n`\n}\n\nexport function guardJsonText(serialized: string, env: RunTextEnv = process.env): string {\n return isGitHubActions(env) ? serialized.replaceAll('#', '\\\\u0023') : serialized\n}\n\n/** Marks this process's stdout as carrying a JSON document or protocol; returns the release. */\nexport function reserveStdoutForData(): () => void {\n const reservations = stdoutReservations()\n reservations.count += 1\n let released = false\n return () => {\n if (released) return\n released = true\n reservations.count -= 1\n }\n}\n\nexport function printRunText(\n text: string,\n print: (text: string) => void = (line) => console.log(line),\n options: PrintRunTextOptions = {},\n): void {\n const env = options.env ?? process.env\n if (!isGitHubActions(env)) {\n print(text)\n return\n }\n const block = guardRunText(text, env)\n // The runner reads stdout and stderr on separate threads, so every wrapped block shares one\n // stream: stdout, or stderr when stdout carries data. The caller's print never sees a block.\n if (options.stdoutIsData ?? stdoutReservations().count > 0) {\n process.stderr.write(block)\n return\n }\n process.stdout.write(block)\n}\n","import type { TestDefinition } from '../types/test.js'\nimport type { SuiteDefinition } from './types.js'\n\nfunction isPlainObject(val: unknown): val is Record<string, unknown> {\n return typeof val === 'object' && val !== null && !Array.isArray(val)\n}\n\nfunction deepMerge(base: unknown, override: unknown): unknown {\n if (!isPlainObject(base) || !isPlainObject(override)) return override\n const result: Record<string, unknown> = { ...base }\n for (const key of Object.keys(override)) {\n if (key in result && isPlainObject(result[key]) && isPlainObject(override[key])) {\n result[key] = deepMerge(result[key], override[key])\n } else {\n result[key] = override[key]\n }\n }\n return result\n}\n\n// Merges the suite's target and use into a member and drops its `url`: the suite owns startup.\nexport function patchTestForSuite(\n test: TestDefinition,\n suite: SuiteDefinition,\n _index: number,\n): TestDefinition {\n const patched = structuredClone(test)\n\n if (suite.target) {\n ;(patched as any).target = suite.target\n }\n\n if (suite.use && (patched as any).use) {\n ;(patched as any).use = deepMerge(suite.use, (patched as any).use)\n } else {\n ;(patched as any).use = (patched as any).use ?? suite.use\n }\n\n delete (patched as any).url\n\n return patched\n}\n","import { readFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { parse as parseYaml, LineCounter, parseDocument } from 'yaml'\nimport { glob } from 'glob'\nimport { AgentQaConfigSchema } from '../schema/config-schema.js'\nimport { SuiteDefinitionSchema } from '../schema/suite-schema.js'\nimport { parseTestFile } from '../parser/yaml-parser.js'\nimport { parseHooksFile } from '../hooks/parser.js'\nimport { isPathInsideDir } from '../utils/path-validation.js'\nimport { yamlParseFailureMessage } from './yaml-fault.js'\nimport {\n discoverWorkspaceFiles,\n isWorkspacePathMatch,\n resolveWorkspaceFileTarget,\n type ResolvedWorkspacePaths,\n type WorkspaceFileKind,\n} from '../workspace/workspace-paths.js'\n\nexport interface ValidationDiagnostic {\n file: string\n line: number\n column: number\n message: string\n severity: 'error' | 'warning'\n}\n\nexport interface ValidationResult {\n diagnostics: ValidationDiagnostic[]\n fileCount: number\n errorCount: number\n warningCount: number\n}\n\nexport const VALID_FILENAME_RE = /^[a-zA-Z0-9._-]+\\.(suite\\.)?(yaml|yml)$/\n\nexport async function validateConfig(configPath: string): Promise<ValidationDiagnostic[]> {\n const diagnostics: ValidationDiagnostic[] = []\n\n let content: string\n try {\n content = await readFile(configPath, 'utf-8')\n } catch (err) {\n diagnostics.push({\n file: configPath,\n line: 1,\n column: 1,\n message: `Cannot read config file: ${(err as Error).message}`,\n severity: 'error',\n })\n return diagnostics\n }\n\n let parsed: unknown\n try {\n parsed = parseYaml(content)\n } catch (err) {\n // The `file` field names the file, so the message is the position; an excerpt can leak.\n diagnostics.push({\n file: configPath,\n line: 1,\n column: 1,\n message: yamlParseFailureMessage(err),\n severity: 'error',\n })\n return diagnostics\n }\n\n const result = AgentQaConfigSchema.safeParse(parsed)\n if (!result.success) {\n for (const issue of result.error.issues) {\n diagnostics.push({\n file: configPath,\n line: 1,\n column: 1,\n message: `${issue.path.join('.')}: ${issue.message}`,\n severity: 'error',\n })\n }\n }\n\n return diagnostics\n}\n\nfunction buildDiagnostic(file: string, message: string, severity: 'error' | 'warning' = 'error'): ValidationDiagnostic {\n return {\n file,\n line: 1,\n column: 1,\n message,\n severity,\n }\n}\n\nexport function validateTestFile(filePath: string, content: string): ValidationDiagnostic[] {\n const result = parseTestFile(content, filePath)\n return result.errors.map((e) => ({\n file: e.file,\n line: e.line,\n column: e.column,\n message: e.message,\n severity: e.severity,\n }))\n}\n\nexport function validateSuiteFile(filePath: string, content: string, basedir: string): ValidationDiagnostic[] {\n const diagnostics: ValidationDiagnostic[] = []\n\n const lineCounter = new LineCounter()\n let parsed: unknown\n try {\n parsed = parseYaml(content, { lineCounter })\n } catch (err) {\n // The message is the position only, as in the config and hooks arms.\n diagnostics.push({\n file: filePath,\n line: 1,\n column: 1,\n message: yamlParseFailureMessage(err),\n severity: 'error',\n })\n return diagnostics\n }\n\n const result = SuiteDefinitionSchema.safeParse(parsed)\n if (!result.success) {\n for (const issue of result.error.issues) {\n diagnostics.push({\n file: filePath,\n line: 1,\n column: 1,\n message: `${issue.path.join('.')}: ${issue.message}`,\n severity: 'error',\n })\n }\n return diagnostics\n }\n\n // Check test references exist on disk\n const doc = parseDocument(content, { lineCounter })\n const testsNode = doc.contents && 'get' in doc.contents ? (doc.contents as { get: (key: string, keepScalar?: boolean) => unknown }).get('tests', true) : undefined\n\n const tests = result.data.tests\n for (let i = 0; i < tests.length; i++) {\n const entry = tests[i]\n const testPath = entry.test\n\n if (!isPathInsideDir(testPath, basedir)) {\n diagnostics.push({\n file: filePath, line: 1, column: 1,\n message: `Path traversal rejected: ${testPath}`,\n severity: 'error',\n })\n continue\n }\n\n const resolved = path.resolve(basedir, testPath)\n if (!existsSync(resolved)) {\n let line = 1\n let column = 1\n const seqNode = testsNode as { items?: { range?: [number, number] }[] } | undefined\n if (seqNode?.items?.[i]?.range) {\n const pos = lineCounter.linePos(seqNode.items[i].range![0])\n line = pos.line\n column = pos.col\n }\n diagnostics.push({\n file: filePath,\n line,\n column,\n message: `Test reference not found: ${testPath} (resolved: ${resolved})`,\n severity: 'error',\n })\n }\n }\n\n return diagnostics\n}\n\nexport function validateFilename(filePath: string): ValidationDiagnostic[] {\n const basename = path.basename(filePath)\n if (!VALID_FILENAME_RE.test(basename)) {\n return [{\n file: filePath,\n line: 1,\n column: 1,\n message: `Invalid filename \"${basename}\" — expected pattern: [a-zA-Z0-9._-]+.(suite.)?(yaml|yml)`,\n severity: 'warning',\n }]\n }\n return []\n}\n\nexport async function validateHooksFile(\n hooksFilePath: string,\n options: { required?: boolean } = {},\n): Promise<ValidationDiagnostic[]> {\n const diagnostics: ValidationDiagnostic[] = []\n\n if (!existsSync(hooksFilePath)) {\n if (options.required) {\n return [buildDiagnostic(hooksFilePath, `Configured hooks file not found: ${hooksFilePath}`)]\n }\n return []\n }\n\n const { hooks, errors } = await parseHooksFile(hooksFilePath)\n if (errors.length > 0) {\n for (const err of errors) {\n diagnostics.push({\n file: hooksFilePath,\n line: 1,\n column: 1,\n message: err,\n severity: 'error',\n })\n }\n return diagnostics\n }\n\n for (const hook of hooks) {\n if (!existsSync(hook.file)) {\n diagnostics.push({\n file: hooksFilePath,\n line: 1,\n column: 1,\n message: `Hook \"${hook.name}\": script file not found: ${hook.file}`,\n severity: 'error',\n })\n }\n\n for (const dep of hook.deps) {\n if (!existsSync(dep)) {\n diagnostics.push({\n file: hooksFilePath,\n line: 1,\n column: 1,\n message: `Hook \"${hook.name}\": dependency file not found: ${dep}`,\n severity: 'error',\n })\n }\n }\n\n if (hook.packageFile && !existsSync(hook.packageFile)) {\n diagnostics.push({\n file: hooksFilePath,\n line: 1,\n column: 1,\n message: `Hook \"${hook.name}\": package file not found: ${hook.packageFile}`,\n severity: 'error',\n })\n }\n }\n\n return diagnostics\n}\n\nexport function validateHookReferences(\n setupOrTeardown: string[],\n hookIds: Set<string>,\n filePath: string,\n context: string,\n): ValidationDiagnostic[] {\n const diagnostics: ValidationDiagnostic[] = []\n for (const hookId of setupOrTeardown) {\n if (!hookIds.has(hookId)) {\n diagnostics.push({\n file: filePath,\n line: 1,\n column: 1,\n message: `Hook ID \"${hookId}\" referenced in ${context} but not defined in the configured hooks file`,\n severity: 'warning',\n })\n }\n }\n return diagnostics\n}\n\nexport async function detectGlobOverlap(\n testMatch: string[],\n suiteMatch: string[],\n ignore: string[],\n cwd?: string,\n): Promise<string[]> {\n if (testMatch.length === 0 || suiteMatch.length === 0) return []\n const globOptions = {\n ignore,\n absolute: true,\n ...(cwd ? { cwd } : {}),\n }\n const [testFiles, suiteFiles] = await Promise.all([\n glob(testMatch, globOptions),\n glob(suiteMatch, globOptions),\n ])\n const testSet = new Set(testFiles)\n return suiteFiles.filter((f) => testSet.has(f))\n}\n\nfunction isSuiteFile(filePath: string): boolean {\n return /\\.suite\\.(yaml|yml)$/.test(filePath)\n}\n\nexport async function validateFiles(\n filePaths: string[],\n configPath?: string,\n options: { basedir?: string } = {},\n): Promise<ValidationResult> {\n const diagnostics: ValidationDiagnostic[] = []\n\n if (configPath) {\n diagnostics.push(...await validateConfig(configPath))\n }\n\n for (const filePath of filePaths) {\n diagnostics.push(...validateFilename(filePath))\n\n let content: string\n try {\n content = await readFile(filePath, 'utf-8')\n } catch (err) {\n diagnostics.push({\n file: filePath,\n line: 1,\n column: 1,\n message: `Cannot read file: ${(err as Error).message}`,\n severity: 'error',\n })\n continue\n }\n\n if (isSuiteFile(filePath)) {\n diagnostics.push(...validateSuiteFile(filePath, content, options.basedir ?? process.cwd()))\n } else {\n diagnostics.push(...validateTestFile(filePath, content))\n }\n }\n\n const errorCount = diagnostics.filter((d) => d.severity === 'error').length\n const warningCount = diagnostics.filter((d) => d.severity === 'warning').length\n const files = new Set(diagnostics.map((d) => d.file))\n\n return {\n diagnostics,\n fileCount: filePaths.length,\n errorCount,\n warningCount,\n }\n}\n\nasync function resolveExplicitWorkspaceFile(\n workspace: ResolvedWorkspacePaths,\n filePath: string,\n): Promise<{ record?: { absolutePath: string }; diagnostic?: ValidationDiagnostic }> {\n const preferredKinds: WorkspaceFileKind[] = isSuiteFile(filePath)\n ? ['suite', 'test']\n : ['test', 'suite']\n\n for (const kind of preferredKinds) {\n try {\n const record = await resolveWorkspaceFileTarget({\n workspace,\n kind,\n filePath,\n requireExisting: true,\n })\n return { record }\n } catch {\n // Try the other configured file kind before reporting the path as invalid.\n }\n }\n\n return {\n diagnostic: buildDiagnostic(\n filePath,\n `File is not matched by configured workspace testMatch or suiteMatch patterns: ${filePath}`,\n ),\n }\n}\n\nfunction appendDiagnostics(result: ValidationResult, diagnostics: ValidationDiagnostic[]): void {\n for (const diagnostic of diagnostics) {\n result.diagnostics.push(diagnostic)\n if (diagnostic.severity === 'error') result.errorCount++\n else result.warningCount++\n }\n}\n\nfunction validateRequiredWorkspaceFiles(workspace: ResolvedWorkspacePaths): ValidationDiagnostic[] {\n const diagnostics: ValidationDiagnostic[] = []\n for (const [key, file] of [\n ['workspace.envFile', workspace.envFile],\n ['workspace.secretsFile', workspace.secretsFile],\n ] as const) {\n if (!existsSync(file.absolutePath)) {\n diagnostics.push(buildDiagnostic(file.absolutePath, `Configured workspace file not found: ${key} -> ${file.absolutePath}`))\n }\n }\n return diagnostics\n}\n\nexport async function validateProject(options: {\n configPath?: string\n files?: string[]\n testMatch?: string[]\n testPathIgnore?: string[]\n suiteMatch?: string[]\n hooksFile?: string\n workspace?: ResolvedWorkspacePaths\n} = {}): Promise<ValidationResult> {\n let filePaths: string[]\n const preDiagnostics: ValidationDiagnostic[] = []\n\n if (options.files && options.files.length > 0 && options.workspace) {\n const resolvedFiles: string[] = []\n for (const file of options.files) {\n const { record, diagnostic } = await resolveExplicitWorkspaceFile(options.workspace, file)\n if (record) resolvedFiles.push(record.absolutePath)\n if (diagnostic) preDiagnostics.push(diagnostic)\n }\n filePaths = resolvedFiles\n } else if (options.files && options.files.length > 0) {\n filePaths = options.files.map((f) => path.resolve(f))\n } else if (options.workspace) {\n const [testFiles, suiteFiles] = await Promise.all([\n discoverWorkspaceFiles({ workspace: options.workspace, kind: 'test' }),\n discoverWorkspaceFiles({ workspace: options.workspace, kind: 'suite' }),\n ])\n filePaths = [...testFiles, ...suiteFiles].map(file => file.absolutePath)\n } else {\n const testPatterns = options.testMatch ?? []\n const suitePatterns = options.suiteMatch ?? []\n const allPatterns = [...testPatterns, ...suitePatterns]\n const ignore = options.testPathIgnore ?? []\n filePaths = allPatterns.length > 0\n ? await glob(allPatterns, { ignore, absolute: true })\n : []\n }\n\n const configPath = options.configPath ?? options.workspace?.configPath\n\n const result = await validateFiles(filePaths, configPath, {\n basedir: options.workspace?.configDir,\n })\n appendDiagnostics(result, preDiagnostics)\n\n const testPatterns = options.workspace?.testMatch ?? options.testMatch ?? []\n const suitePatterns = options.workspace?.suiteMatch ?? options.suiteMatch ?? []\n if (testPatterns.length > 0 && suitePatterns.length > 0) {\n const ignore = options.workspace?.testPathIgnore ?? options.testPathIgnore ?? []\n const overlapping = await detectGlobOverlap(testPatterns, suitePatterns, ignore, options.workspace?.configDir)\n for (const filePath of overlapping) {\n result.diagnostics.push({\n file: filePath,\n line: 1,\n column: 1,\n message: 'File matched by both testMatch and suiteMatch — may cause duplicate validation',\n severity: 'warning',\n })\n result.warningCount++\n }\n }\n\n appendDiagnostics(result, options.workspace ? validateRequiredWorkspaceFiles(options.workspace) : [])\n\n const hooksFilePath = options.workspace?.hooksFile.absolutePath ?? options.hooksFile\n const hooksDiags = hooksFilePath\n ? await validateHooksFile(hooksFilePath, { required: Boolean(options.workspace) })\n : []\n for (const d of hooksDiags) {\n result.diagnostics.push(d)\n if (d.severity === 'error') result.errorCount++\n else result.warningCount++\n }\n\n // Check hook ID references in test/suite files\n if (hooksFilePath && hooksDiags.length === 0 && existsSync(hooksFilePath)) {\n const { hooks } = await parseHooksFile(hooksFilePath)\n const hookIds = new Set(hooks.map(h => h.id))\n\n for (const filePath of filePaths) {\n const workspaceRelativePath = options.workspace\n ? path.relative(options.workspace.configDir, filePath).split(path.sep).join('/')\n : filePath\n const isWorkspaceFile = options.workspace\n ? isWorkspacePathMatch({ workspace: options.workspace, kind: isSuiteFile(filePath) ? 'suite' : 'test', workspaceRelativePath })\n : true\n if (!isWorkspaceFile) continue\n\n try {\n const content = await readFile(filePath, 'utf-8')\n const parsed = parseYaml(content)\n if (parsed && typeof parsed === 'object') {\n const setup = (parsed as Record<string, unknown>).setup as string[] | undefined\n const teardown = (parsed as Record<string, unknown>).teardown as string[] | undefined\n if (setup?.length) {\n const refDiags = validateHookReferences(setup, hookIds, filePath, 'setup')\n for (const d of refDiags) { result.diagnostics.push(d); result.warningCount++ }\n }\n if (teardown?.length) {\n const refDiags = validateHookReferences(teardown, hookIds, filePath, 'teardown')\n for (const d of refDiags) { result.diagnostics.push(d); result.warningCount++ }\n }\n }\n } catch { /* skip files that can't be parsed */ }\n }\n }\n\n return result\n}\n","import { readFile } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport { parse as parseYaml } from 'yaml'\nimport { HooksFileSchema } from './schema.js'\nimport { yamlParseFailureMessage } from '../validation/yaml-fault.js'\nimport type { HookDefinition } from '@vostride/agent-qa-runner'\n\nexport async function parseHooksFile(filePath: string): Promise<{ hooks: HookDefinition[]; errors: string[] }> {\n let raw: string\n try {\n raw = await readFile(filePath, 'utf-8')\n } catch (err) {\n return { hooks: [], errors: [`Failed to read hooks file: ${(err as Error).message}`] }\n }\n\n let parsed: unknown\n try {\n parsed = parseYaml(raw)\n } catch (err) {\n // The message says where the parse failed, never the excerpt, which can carry a credential.\n return { hooks: [], errors: [`${filePath}: ${yamlParseFailureMessage(err)}`] }\n }\n\n const result = HooksFileSchema.safeParse(parsed)\n if (!result.success) {\n const errors = result.error.issues.map((issue) =>\n `${issue.path.join('.')}: ${issue.message}`\n )\n return { hooks: [], errors }\n }\n\n const dir = dirname(filePath)\n const hooks: HookDefinition[] = result.data.hooks.map((h) => ({\n ...h,\n file: resolve(dir, h.file),\n deps: h.deps.map((d) => resolve(dir, d)),\n packageFile: h.packageFile ? resolve(dir, h.packageFile) : undefined,\n }))\n\n return { hooks, errors: [] }\n}\n","import path from 'node:path'\n\nexport function isPathInsideDir(childPath: string, parentDir: string): boolean {\n if (!childPath) return false\n const resolved = path.resolve(parentDir, childPath)\n const relative = path.relative(parentDir, resolved)\n return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative)\n}\n","import { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { glob } from 'glob'\nimport type { AgentQaConfig } from '../types/config.js'\n\nexport type WorkspaceFileKind = 'test' | 'suite'\n\nexport interface ResolvedWorkspaceFile {\n configuredPath: string\n absolutePath: string\n workspaceRelativePath: string\n}\n\nexport interface WorkspaceFileRecord {\n kind: WorkspaceFileKind\n absolutePath: string\n workspaceRelativePath: string\n}\n\nexport interface ResolvedWorkspacePaths {\n configPath: string\n configDir: string\n testMatch: string[]\n suiteMatch: string[]\n testPathIgnore: string[]\n hooksFile: ResolvedWorkspaceFile\n envFile: ResolvedWorkspaceFile\n secretsFile: ResolvedWorkspaceFile\n}\n\ninterface ResolveWorkspacePathsInput {\n config: AgentQaConfig\n configPath: string\n requireExistingFiles?: boolean\n}\n\nfunction toForwardSlash(value: string): string {\n return value.split(path.sep).join('/')\n}\n\nfunction trimLeadingCurrentDir(value: string): string {\n return toForwardSlash(value).replace(/^\\.\\//, '')\n}\n\nfunction assertNonEmptyArray(value: unknown, key: string): string[] {\n if (!Array.isArray(value) || value.length === 0 || value.some(item => typeof item !== 'string' || item.trim().length === 0)) {\n throw new Error(`Missing required workspace config key: ${key}`)\n }\n return value\n}\n\nfunction assertNonEmptyString(value: unknown, key: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new Error(`Missing required workspace config key: ${key}`)\n }\n return value\n}\n\nfunction resolveWorkspaceScalar(configDir: string, key: string, configuredPath: unknown): ResolvedWorkspaceFile {\n const value = assertNonEmptyString(configuredPath, key)\n const absolutePath = path.isAbsolute(value) ? path.resolve(value) : path.resolve(configDir, value)\n return {\n configuredPath: value,\n absolutePath,\n workspaceRelativePath: trimLeadingCurrentDir(path.relative(configDir, absolutePath)),\n }\n}\n\nfunction assertInsideWorkspace(configDir: string, absolutePath: string, filePath: string): string {\n const relativePath = path.relative(configDir, absolutePath)\n if (!relativePath || relativePath.startsWith('..') || path.isAbsolute(relativePath)) {\n throw new Error(`Workspace file path escapes config directory: ${filePath}`)\n }\n return trimLeadingCurrentDir(relativePath)\n}\n\n// Identity only, never file access: a ledger keyed on absolute paths matches on no other machine.\nexport function workspaceRelativeIdentityPath(configDir: string, filePath: string): string {\n const absolutePath = path.isAbsolute(filePath)\n ? path.resolve(filePath)\n : path.resolve(configDir, filePath)\n return assertInsideWorkspace(configDir, absolutePath, filePath)\n}\n\nfunction escapeRegexChar(char: string): string {\n return char.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction globToRegex(pattern: string): RegExp {\n const normalized = trimLeadingCurrentDir(pattern)\n let source = ''\n\n for (let i = 0; i < normalized.length; i++) {\n const char = normalized[i]\n const next = normalized[i + 1]\n\n if (char === '*') {\n if (next === '*') {\n const afterGlobstar = normalized[i + 2]\n if (afterGlobstar === '/') {\n source += '(?:.*/)?'\n i += 2\n } else {\n source += '.*'\n i += 1\n }\n } else {\n source += '[^/]*'\n }\n continue\n }\n\n if (char === '?') {\n source += '[^/]'\n continue\n }\n\n if (char === '{') {\n const end = normalized.indexOf('}', i + 1)\n if (end !== -1) {\n const alternatives = normalized\n .slice(i + 1, end)\n .split(',')\n .map(part => part.split('').map(escapeRegexChar).join(''))\n source += `(?:${alternatives.join('|')})`\n i = end\n continue\n }\n }\n\n source += escapeRegexChar(char)\n }\n\n return new RegExp(`^${source}$`)\n}\n\nfunction matchesAnyPattern(workspaceRelativePath: string, patterns: string[]): boolean {\n const normalized = trimLeadingCurrentDir(workspaceRelativePath)\n return patterns.some(pattern => globToRegex(pattern).test(normalized))\n}\n\nfunction getKindPatterns(workspace: ResolvedWorkspacePaths, kind: WorkspaceFileKind): string[] {\n return kind === 'test' ? workspace.testMatch : workspace.suiteMatch\n}\n\nfunction isIgnored(workspace: ResolvedWorkspacePaths, workspaceRelativePath: string): boolean {\n return workspace.testPathIgnore.length > 0 && matchesAnyPattern(workspaceRelativePath, workspace.testPathIgnore)\n}\n\nexport function resolveWorkspacePaths(input: ResolveWorkspacePathsInput): ResolvedWorkspacePaths {\n const configPath = path.resolve(input.configPath)\n const configDir = path.dirname(configPath)\n const workspace = input.config.workspace\n\n if (!workspace) {\n throw new Error('Missing required workspace config key: workspace')\n }\n\n const resolved: ResolvedWorkspacePaths = {\n configPath,\n configDir,\n testMatch: assertNonEmptyArray(workspace.testMatch, 'workspace.testMatch'),\n suiteMatch: assertNonEmptyArray(workspace.suiteMatch, 'workspace.suiteMatch'),\n testPathIgnore: workspace.testPathIgnore ?? [],\n hooksFile: resolveWorkspaceScalar(configDir, 'workspace.hooksFile', workspace.hooksFile),\n envFile: resolveWorkspaceScalar(configDir, 'workspace.envFile', workspace.envFile),\n secretsFile: resolveWorkspaceScalar(configDir, 'workspace.secretsFile', workspace.secretsFile),\n }\n\n if (input.requireExistingFiles) {\n for (const [key, file] of [\n ['workspace.hooksFile', resolved.hooksFile],\n ['workspace.envFile', resolved.envFile],\n ['workspace.secretsFile', resolved.secretsFile],\n ] as const) {\n if (!existsSync(file.absolutePath)) {\n throw new Error(`Configured workspace file not found: ${key} -> ${file.absolutePath}`)\n }\n }\n }\n\n return resolved\n}\n\nexport async function discoverWorkspaceFiles(input: {\n workspace: ResolvedWorkspacePaths\n kind: WorkspaceFileKind\n}): Promise<WorkspaceFileRecord[]> {\n const patterns = getKindPatterns(input.workspace, input.kind)\n const matches = await glob(patterns, {\n cwd: input.workspace.configDir,\n ignore: input.workspace.testPathIgnore,\n absolute: true,\n nodir: true,\n })\n\n return matches\n .map(match => path.resolve(match))\n .map(absolutePath => ({\n kind: input.kind,\n absolutePath,\n workspaceRelativePath: trimLeadingCurrentDir(path.relative(input.workspace.configDir, absolutePath)),\n }))\n .sort((a, b) => a.workspaceRelativePath.localeCompare(b.workspaceRelativePath))\n}\n\nexport async function resolveWorkspaceFileTarget(input: {\n workspace: ResolvedWorkspacePaths\n kind: WorkspaceFileKind\n filePath: string\n requireExisting?: boolean\n}): Promise<WorkspaceFileRecord> {\n const absolutePath = path.isAbsolute(input.filePath)\n ? path.resolve(input.filePath)\n : path.resolve(input.workspace.configDir, input.filePath)\n const workspaceRelativePath = assertInsideWorkspace(input.workspace.configDir, absolutePath, input.filePath)\n\n if (!isWorkspacePathMatch({\n workspace: input.workspace,\n kind: input.kind,\n workspaceRelativePath,\n })) {\n throw new Error(`Workspace ${input.kind} file is not matched by configured workspace patterns: ${workspaceRelativePath}`)\n }\n\n if (input.requireExisting && !existsSync(absolutePath)) {\n throw new Error(`Workspace ${input.kind} file not found: ${workspaceRelativePath}`)\n }\n\n return {\n kind: input.kind,\n absolutePath,\n workspaceRelativePath,\n }\n}\n\nexport function isWorkspacePathMatch(input: {\n workspace: ResolvedWorkspacePaths\n kind: WorkspaceFileKind\n workspaceRelativePath: string\n}): boolean {\n return matchesAnyPattern(input.workspaceRelativePath, getKindPatterns(input.workspace, input.kind))\n && !isIgnored(input.workspace, input.workspaceRelativePath)\n}\n","import pc from 'picocolors'\nimport type { ValidationResult, ValidationDiagnostic } from './validate.js'\n\nfunction groupByFile(diagnostics: ValidationDiagnostic[]): Map<string, ValidationDiagnostic[]> {\n const groups = new Map<string, ValidationDiagnostic[]>()\n for (const d of diagnostics) {\n const existing = groups.get(d.file)\n if (existing) {\n existing.push(d)\n } else {\n groups.set(d.file, [d])\n }\n }\n return groups\n}\n\nfunction formatSeverity(severity: 'error' | 'warning', color: boolean): string {\n if (severity === 'error') {\n return color ? pc.red('error') : 'error'\n }\n return color ? pc.yellow('warning') : 'warning'\n}\n\nfunction formatOutput(result: ValidationResult, color: boolean): string {\n if (result.diagnostics.length === 0) {\n const check = color ? pc.green('\\u2714') : '\\u2714'\n return `\\n${check} All files valid (${result.fileCount} file(s) checked)\\n`\n }\n\n const groups = groupByFile(result.diagnostics)\n const lines: string[] = ['']\n\n for (const [file, diagnostics] of groups) {\n const header = color ? pc.underline(pc.bold(file)) : file\n lines.push(header)\n\n for (const d of diagnostics) {\n const loc = `${d.line}:${d.column}`\n const sev = formatSeverity(d.severity, color).padEnd(color ? 20 : 7)\n lines.push(` ${loc} ${sev} ${d.message}`)\n }\n\n lines.push('')\n }\n\n const filesWithIssues = groups.size\n if (result.errorCount > 0) {\n const cross = color ? pc.red('\\u2716') : '\\u2716'\n lines.push(`${cross} ${result.errorCount} error(s), ${result.warningCount} warning(s) in ${filesWithIssues} file(s)`)\n } else {\n const warn = color ? pc.yellow('\\u26A0') : '\\u26A0'\n lines.push(`${warn} ${result.warningCount} warning(s) in ${filesWithIssues} file(s)`)\n }\n lines.push('')\n\n return lines.join('\\n')\n}\n\nexport function formatDiagnostics(result: ValidationResult): string {\n return formatOutput(result, true)\n}\n\nexport function formatDiagnosticsPlain(result: ValidationResult): string {\n return formatOutput(result, false)\n}\n","export function warnIfOutOfBounds(\n coords: { x?: number; y?: number },\n viewport: { width: number; height: number },\n actionType: string,\n): void {\n const { x, y } = coords\n const { width, height } = viewport\n if (x !== undefined && (x < 0 || x > width)) {\n console.warn(`[${actionType}] x=${x} outside viewport bounds [0, ${width}]`)\n }\n if (y !== undefined && (y < 0 || y > height)) {\n console.warn(`[${actionType}] y=${y} outside viewport bounds [0, ${height}]`)\n }\n}\n","// Hook parsing stays in core; hook execution lives in runner, which owns these types.\nexport type { HookRuntime, HookDefinition, HookResult } from '@vostride/agent-qa-runner'\nexport { RUNTIME_IMAGE_MAP, hookRunnerImage } from '@vostride/agent-qa-runner'\nexport * from './schema.js'\nexport { parseHooksFile } from './parser.js'\n","import { generateHookId as generateSharedHookId } from '@vostride/agent-qa-ids'\n\n// Re-exported so a caller that can validate a hook id can also mint one through core.\nexport function generateHookId(): string {\n return generateSharedHookId()\n}\n","import { generateRunId as generateSharedRunId, isCanonicalRunId as isSharedCanonicalRunId } from '@vostride/agent-qa-ids'\n\nexport function generateRunId(): string {\n return generateSharedRunId()\n}\n\n// The mint's inverse beside it, so the two never disagree on the id shape.\nexport function isCanonicalRunId(value: string): boolean {\n return isSharedCanonicalRunId(value)\n}\n","export type RunAttributes = Record<string, string>\n\nexport const INTERNAL_ATTRIBUTE_PREFIX = 'agent-qa.'\nexport const ATTR_TRIGGER = 'agent-qa.trigger'\nexport const ATTR_RUNNER = 'agent-qa.runner'\nexport const ATTR_GATE_RUN = 'agent-qa.gate-run'\n\nexport type RunAttributeTrigger = 'cli' | 'dashboard' | 'api' | 'mcp'\nexport type RunAttributeRunner = 'local'\n\nexport const RUN_ATTRIBUTE_KEY_MAX_LENGTH = 256\nexport const RUN_ATTRIBUTE_VALUE_MAX_LENGTH = 4096\n\nexport interface ParsedRunAttrFlags {\n attributes: RunAttributes\n duplicateKeys: string[]\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction assertValidUserAttributeKey(key: string, sourceLabel: string): void {\n if (key.length === 0) {\n throw new Error(`${sourceLabel}: Attribute key must be non-empty`)\n }\n if (key.startsWith(INTERNAL_ATTRIBUTE_PREFIX)) {\n throw new Error(`${sourceLabel}: Attribute key \"${key}\" uses the reserved prefix \"${INTERNAL_ATTRIBUTE_PREFIX}\"`)\n }\n if (key.length > RUN_ATTRIBUTE_KEY_MAX_LENGTH) {\n throw new Error(`${sourceLabel}: Attribute key \"${key}\" exceeds ${RUN_ATTRIBUTE_KEY_MAX_LENGTH} characters`)\n }\n}\n\nexport function validateUserRunAttributes(input: unknown, sourceLabel = 'run attributes'): RunAttributes {\n if (input === undefined || input === null) return {}\n if (!isPlainRecord(input)) {\n throw new Error(`${sourceLabel}: attributes must be a plain object`)\n }\n\n const attributes = Object.create(null) as RunAttributes\n for (const [key, value] of Object.entries(input)) {\n assertValidUserAttributeKey(key, sourceLabel)\n if (typeof value !== 'string') {\n throw new Error(`${sourceLabel}: Attribute value for \"${key}\" must be a string`)\n }\n if (value.length > RUN_ATTRIBUTE_VALUE_MAX_LENGTH) {\n throw new Error(`${sourceLabel}: Attribute value for \"${key}\" exceeds ${RUN_ATTRIBUTE_VALUE_MAX_LENGTH} characters`)\n }\n attributes[key] = value\n }\n return attributes\n}\n\nexport function parseRunAttrFlags(flags: string[] | undefined): ParsedRunAttrFlags {\n const rawAttributes = Object.create(null) as Record<string, string>\n const seen = new Set<string>()\n const duplicateKeys = new Set<string>()\n\n for (const flag of flags ?? []) {\n const separator = flag.indexOf('=')\n if (separator <= 0) {\n throw new Error(`--run-attr must use KEY=VALUE format: \"${flag}\"`)\n }\n const key = flag.slice(0, separator)\n const value = flag.slice(separator + 1)\n if (seen.has(key)) duplicateKeys.add(key)\n seen.add(key)\n rawAttributes[key] = value\n }\n\n return {\n attributes: validateUserRunAttributes(rawAttributes, '--run-attr'),\n duplicateKeys: [...duplicateKeys].sort((left, right) => left.localeCompare(right)),\n }\n}\n\nexport function buildInternalRunAttributes(input: {\n trigger: RunAttributeTrigger\n runner: RunAttributeRunner\n}): RunAttributes {\n return {\n [ATTR_TRIGGER]: input.trigger,\n [ATTR_RUNNER]: input.runner,\n }\n}\n\nexport function mergeRunAttributes(internal: RunAttributes, user: RunAttributes): RunAttributes {\n return {\n ...user,\n ...internal,\n }\n}\n\nexport function sortRunAttributesForDisplay(\n attributes: RunAttributes,\n activeKeys: string[] = [],\n): Array<[string, string]> {\n const entries = Object.entries(attributes)\n const rank = (key: string): [number, number, string] => {\n const activeIndex = activeKeys.indexOf(key)\n if (activeIndex >= 0) return [0, activeIndex, key]\n if (key === ATTR_TRIGGER) return [1, 0, key]\n if (key === ATTR_RUNNER) return [1, 1, key]\n if (key === ATTR_GATE_RUN) return [1, 2, key]\n if (key.startsWith(INTERNAL_ATTRIBUTE_PREFIX)) return [1, 3, key]\n return [2, 0, key]\n }\n\n return entries.sort(([left], [right]) => {\n const leftRank = rank(left)\n const rightRank = rank(right)\n return leftRank[0] - rightRank[0] ||\n leftRank[1] - rightRank[1] ||\n leftRank[2].localeCompare(rightRank[2])\n })\n}\n\nexport function formatRunAttributesBlock(attributes: RunAttributes): string {\n const entries = sortRunAttributesForDisplay(attributes)\n if (entries.length === 0) return ''\n return [\n 'Run attributes:',\n ...entries.map(([key, value]) => ` ${key}=${value}`),\n ].join('\\n')\n}\n","import { createRequire } from 'node:module'\n\nconst require = createRequire(typeof __filename === 'string' ? __filename : import.meta.url)\n\nfunction readPackageVersion(): string {\n try {\n const manifest = require('../package.json') as { version?: unknown }\n if (typeof manifest.version === 'string' && manifest.version.trim()) {\n return manifest.version.trim()\n }\n } catch {\n // Keep public version consumers non-throwing if package metadata is unavailable.\n }\n\n return '0.0.0'\n}\n\nexport const AGENT_QA_VERSION = readPackageVersion()\n\nexport function getAgentQaVersion(): string {\n return AGENT_QA_VERSION\n}\n","import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport { getAgentQaVersion } from '../version.js'\n\nconst require = createRequire(typeof __filename === 'string' ? __filename : import.meta.url)\n\nconst AGENT_QA_NPM_REGISTRY_URL = 'https://registry.npmjs.org/agent-qa'\n\nexport const VERSION_CHECK_CACHE_TTL_MS = 24 * 60 * 60 * 1000\nexport const VERSION_CHECK_TIMEOUT_MS = 5000\n\nexport interface AgentQaUpdateStatus {\n installedVersion: string\n latestVersion?: string\n updateAvailable: boolean\n checkedAt?: string\n}\n\ntype VersionCheckFetch = (\n input: string | URL | Request,\n init?: RequestInit,\n) => Promise<Response>\n\nexport interface VersionCheckOptions {\n cachePath?: string\n fetchImpl?: VersionCheckFetch\n now?: () => Date\n timeoutMs?: number\n cacheTtlMs?: number\n homeDir?: string\n}\n\ninterface VersionCheckCacheFile {\n latestVersion?: string\n checkedAt?: string\n lastAttemptedAt?: string\n}\n\ninterface SemverApi {\n valid(version: string): string | null\n gt(version: string, otherVersion: string): boolean\n}\n\nlet semverApi: SemverApi | undefined\n\nexport function getAgentQaVersionCheckCachePath(homeDir?: string): string {\n return join(homeDir ?? homedir(), '.agent-qa', 'version-check.json')\n}\n\nexport async function getAgentQaUpdateStatus(\n options: VersionCheckOptions = {},\n): Promise<AgentQaUpdateStatus> {\n const installedVersion = getInstalledVersion()\n\n try {\n return await getAgentQaUpdateStatusInternal(installedVersion, options)\n } catch {\n return createStatus(installedVersion)\n }\n}\n\nasync function getAgentQaUpdateStatusInternal(\n installedVersion: string,\n options: VersionCheckOptions,\n): Promise<AgentQaUpdateStatus> {\n const semver = getSemverApi()\n if (!semver) {\n return createStatus(installedVersion)\n }\n\n const now = getNow(options.now)\n const nowMs = now.getTime()\n const nowIso = now.toISOString()\n const cacheTtlMs = getPositiveNumber(options.cacheTtlMs, VERSION_CHECK_CACHE_TTL_MS)\n const timeoutMs = getPositiveNumber(options.timeoutMs, VERSION_CHECK_TIMEOUT_MS)\n const cachePath = options.cachePath ?? getAgentQaVersionCheckCachePath(options.homeDir)\n const cache = await readVersionCheckCache(cachePath)\n const cachedLatestVersion = getValidVersion(cache?.latestVersion, semver)\n const checkedAtMs = getTimestamp(cache?.checkedAt)\n\n if (cachedLatestVersion && checkedAtMs !== undefined && nowMs - checkedAtMs < cacheTtlMs) {\n return createStatus(installedVersion, semver, cachedLatestVersion, cache?.checkedAt)\n }\n\n const lastAttemptedAtMs = getTimestamp(cache?.lastAttemptedAt)\n if (lastAttemptedAtMs !== undefined && nowMs - lastAttemptedAtMs < cacheTtlMs) {\n if (cachedLatestVersion && checkedAtMs !== undefined) {\n return createStatus(installedVersion, semver, cachedLatestVersion, cache?.checkedAt)\n }\n\n return createStatus(installedVersion)\n }\n\n const nextCache = { ...cache, lastAttemptedAt: nowIso }\n const refreshedLatestVersion = await fetchLatestVersion(options.fetchImpl, timeoutMs, semver)\n if (refreshedLatestVersion) {\n const refreshedCache = {\n latestVersion: refreshedLatestVersion,\n checkedAt: nowIso,\n lastAttemptedAt: nowIso,\n }\n await writeVersionCheckCache(cachePath, refreshedCache)\n return createStatus(installedVersion, semver, refreshedLatestVersion, nowIso)\n }\n\n await writeVersionCheckCache(cachePath, nextCache)\n if (cachedLatestVersion && checkedAtMs !== undefined) {\n return createStatus(installedVersion, semver, cachedLatestVersion, cache?.checkedAt)\n }\n\n return createStatus(installedVersion)\n}\n\nfunction getInstalledVersion(): string {\n try {\n return getAgentQaVersion().trim() || '0.0.0'\n } catch {\n return '0.0.0'\n }\n}\n\nfunction getSemverApi(): SemverApi | undefined {\n if (semverApi) return semverApi\n\n try {\n semverApi = require('semver') as SemverApi\n return semverApi\n } catch {\n return undefined\n }\n}\n\nfunction getValidVersion(version: unknown, semver: SemverApi): string | undefined {\n if (typeof version !== 'string') return undefined\n\n try {\n return semver.valid(version) ?? undefined\n } catch {\n return undefined\n }\n}\n\nfunction getTimestamp(value: unknown): number | undefined {\n if (typeof value !== 'string') return undefined\n\n const timestamp = Date.parse(value)\n return Number.isFinite(timestamp) ? timestamp : undefined\n}\n\nfunction getPositiveNumber(value: number | undefined, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback\n}\n\nfunction getNow(now: (() => Date) | undefined): Date {\n try {\n const candidate = now?.()\n if (candidate instanceof Date && Number.isFinite(candidate.getTime())) {\n return candidate\n }\n } catch {\n // Fall through to the system clock.\n }\n\n return new Date()\n}\n\nfunction createStatus(\n installedVersion: string,\n semver?: SemverApi,\n latestVersion?: string,\n checkedAt?: string,\n): AgentQaUpdateStatus {\n if (!latestVersion) {\n return {\n installedVersion,\n updateAvailable: false,\n }\n }\n\n const installedSemver = semver ? getValidVersion(installedVersion, semver) : undefined\n const updateAvailable = Boolean(\n installedSemver &&\n semver &&\n safeSemverGreaterThan(semver, latestVersion, installedSemver),\n )\n\n return {\n installedVersion,\n latestVersion,\n updateAvailable,\n checkedAt,\n }\n}\n\nfunction safeSemverGreaterThan(semver: SemverApi, version: string, otherVersion: string): boolean {\n try {\n return semver.gt(version, otherVersion)\n } catch {\n return false\n }\n}\n\nasync function readVersionCheckCache(cachePath: string): Promise<VersionCheckCacheFile | undefined> {\n try {\n const raw = await readFile(cachePath, 'utf-8')\n const parsed = JSON.parse(raw) as unknown\n if (!isRecord(parsed)) return undefined\n\n return {\n latestVersion: typeof parsed.latestVersion === 'string' ? parsed.latestVersion : undefined,\n checkedAt: typeof parsed.checkedAt === 'string' ? parsed.checkedAt : undefined,\n lastAttemptedAt:\n typeof parsed.lastAttemptedAt === 'string' ? parsed.lastAttemptedAt : undefined,\n }\n } catch {\n return undefined\n }\n}\n\nasync function writeVersionCheckCache(\n cachePath: string,\n cache: VersionCheckCacheFile,\n): Promise<void> {\n try {\n await mkdir(dirname(cachePath), { recursive: true })\n await writeFile(cachePath, JSON.stringify(cache, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n try {\n await chmod(cachePath, 0o600)\n } catch {\n // Cache permissions are best effort.\n }\n } catch {\n // Version checks must never block CLI or dashboard work.\n }\n}\n\nasync function fetchLatestVersion(\n fetchImpl: VersionCheckFetch | undefined,\n timeoutMs: number,\n semver: SemverApi,\n): Promise<string | undefined> {\n try {\n const fetcher = fetchImpl ?? globalThis.fetch?.bind(globalThis)\n if (typeof fetcher !== 'function') return undefined\n\n const response = await fetcher(AGENT_QA_NPM_REGISTRY_URL, {\n headers: { accept: 'application/json' },\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!response.ok) return undefined\n\n const body = (await response.json()) as unknown\n if (!isRecord(body) || !isRecord(body['dist-tags'])) return undefined\n\n return getValidVersion(body['dist-tags'].latest, semver)\n } catch {\n return undefined\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAAA,EACT;AACF;AAEA,eAAe,uBACb,WACA,OACe;AACf,MAAI;AACF,cAAM,4BAAM,4BAAQ,SAAS,GAAG,EAAE,WAAW,KAAK,CAAC;AACnD,cAAM,4BAAU,WAAW,KAAK,UAAU,OAAO,MAAM,CAAC,GAAG;AAAA,MACzD,UAAU;AAAA,MACV,MAAM;AAAA,IACR,CAAC;AACD,QAAI;AACF,gBAAM,wBAAM,WAAW,GAAK;AAAA,IAC9B,QAAQ;AAAA,IAER;AAAA,EACF,QAAQ;AAAA,EAER;AACF;AAEA,eAAe,mBACb,WACA,WACA,QAC6B;AAC7B,MAAI;AACF,UAAM,UAAU,aAAa,WAAW,OAAO,KAAK,UAAU;AAC9D,QAAI,OAAO,YAAY,WAAY,QAAO;AAE1C,UAAM,WAAW,MAAM,QAAQ,2BAA2B;AAAA,MACxD,SAAS,EAAE,QAAQ,mBAAmB;AAAA,MACtC,QAAQ,YAAY,QAAQ,SAAS;AAAA,IACvC,CAAC;AACD,QAAI,CAAC,SAAS,GAAI,QAAO;AAEzB,UAAM,OAAQ,MAAM,SAAS,KAAK;AAClC,QAAI,CAACA,UAAS,IAAI,KAAK,CAACA,UAAS,KAAK,WAAW,CAAC,EAAG,QAAO;AAE5D,WAAO,gBAAgB,KAAK,WAAW,EAAE,QAAQ,MAAM;AAAA,EACzD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAASA,UAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;","names":["import_zod","import_zod","import_zod","ms","bytes","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_zod","import_ms","ms","path","import_zod","import_agent_qa_ids","HookIdSchema","import_zod","import_ms","import_agent_qa_ids","ms","pc","path","import_promises","import_node_path","import_promises","import_yaml","parseYaml","import_yaml","import_agent_qa_runner","import_agent_qa_schema","import_node_path","resolvePath","import_node_fs","import_node_path","import_agent_qa_runner","import_node_path","import_node_fs","import_node_path","path","import_promises","import_node_path","path","import_promises","import_agent_qa_runner","import_node_crypto","import_promises","import_node_path","path","import_node_fs","import_node_path","require","module","import_node_crypto","loadedDeclarations","module","validateDeclaration","import_zod","import_node_crypto","import_picocolors","pc","import_node_crypto","import_agent_qa_runner","isPlainObject","import_promises","import_node_fs","import_node_path","import_yaml","import_glob","import_promises","import_node_path","import_yaml","parseYaml","import_node_path","path","relative","import_node_fs","import_node_path","path","parseYaml","path","basename","testPatterns","suitePatterns","import_picocolors","pc","import_agent_qa_runner","import_agent_qa_ids","generateSharedHookId","import_agent_qa_ids","generateSharedRunId","isSharedCanonicalRunId","import_node_module","import_meta","require","import_promises","import_node_module","import_node_os","import_node_path","import_meta","require","isRecord"]}