@midscene/test 1.17.8-beta-20261106101231.0 → 1.17.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/es/154.mjs +2 -0
  2. package/dist/es/164.mjs +1469 -0
  3. package/dist/es/164.mjs.map +1 -0
  4. package/dist/es/183.mjs +295 -0
  5. package/dist/es/183.mjs.map +1 -0
  6. package/dist/es/1~112.mjs +372 -0
  7. package/dist/es/1~112.mjs.map +1 -0
  8. package/dist/es/209.mjs +1 -0
  9. package/dist/es/299.mjs +1886 -0
  10. package/dist/es/299.mjs.map +1 -0
  11. package/dist/es/398.mjs +5 -0
  12. package/dist/es/398.mjs.map +1 -0
  13. package/dist/es/431.mjs +375 -0
  14. package/dist/es/431.mjs.map +1 -0
  15. package/dist/es/470.mjs +1 -0
  16. package/dist/es/487.mjs +1 -0
  17. package/dist/es/629.mjs +1 -0
  18. package/dist/es/793.mjs +1 -0
  19. package/dist/es/822.mjs +1 -0
  20. package/dist/es/946.mjs +1 -0
  21. package/dist/es/cli/index.mjs +3 -2196
  22. package/dist/es/cli/index.mjs.map +1 -1
  23. package/dist/es/cli/model-command.mjs +1 -296
  24. package/dist/es/index.mjs +10 -409
  25. package/dist/es/index.mjs.map +1 -1
  26. package/dist/es/midscene/index.mjs +9 -9
  27. package/dist/es/midscene/index.mjs.map +1 -1
  28. package/dist/es/runtime/index.mjs +4 -5
  29. package/dist/es/runtime/index.mjs.map +1 -1
  30. package/dist/es/test-cli.mjs +1 -3786
  31. package/dist/lib/0~703.js.map +1 -1
  32. package/dist/lib/cli/index.js +45 -58
  33. package/dist/lib/cli/index.js.map +1 -1
  34. package/dist/lib/cli/model-command.js +1 -1
  35. package/dist/lib/cli/model-command.js.map +1 -1
  36. package/dist/lib/index.js +8 -37
  37. package/dist/lib/index.js.map +1 -1
  38. package/dist/lib/midscene/index.js +1 -1
  39. package/dist/lib/midscene/index.js.map +1 -1
  40. package/dist/lib/runtime/index.js +1 -1
  41. package/dist/lib/runtime/index.js.map +1 -1
  42. package/dist/lib/test-cli.js +884 -877
  43. package/dist/lib/test-cli.js.map +1 -1
  44. package/dist/types/cli/index.d.ts +4 -0
  45. package/package.json +20 -21
  46. package/dist/es/1~4.mjs +0 -383
  47. package/dist/es/1~4.mjs.map +0 -1
  48. package/dist/es/1~731.mjs +0 -306
  49. package/dist/es/1~731.mjs.map +0 -1
  50. package/dist/es/cli/model-command.mjs.map +0 -1
  51. package/dist/es/test-cli.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"299.mjs","sources":["../../src/cli/model-usage.ts","../../src/cli/result-store.ts","../../src/cli/test-project.ts","../../src/cli/project-preparation.ts","../../src/cli/prepare-test-run.ts","../../src/cli/console-scope.ts","../../src/cli/document-invocation.ts","../../src/cli/file-scheduler.ts","../../src/cli/operation-journal.ts","../../src/cli/run-prepared-project.ts"],"sourcesContent":["import { stripVTControlCharacters } from 'node:util';\nimport type { TestRunReportMetrics } from '@midscene/core';\nimport { sumTestRunReportMetrics } from '@midscene/core/internal/test-runner';\nimport { globalConfigManager } from '@midscene/shared/env';\nimport type { StepRunResult } from '../engine/types';\n\n/** Names only; do not initialize an Agent or require model credentials for custom Nodes. */\nexport function configuredModelNames(): { name: string; intents: string[] }[] {\n const env = globalConfigManager.getAllEnvConfig();\n const defaultName = env.MIDSCENE_MODEL_NAME;\n const models = new Map<string, string[]>();\n for (const [intent, name] of [\n ['default', defaultName],\n ['planning', env.MIDSCENE_PLANNING_MODEL_NAME || defaultName],\n ['insight', env.MIDSCENE_INSIGHT_MODEL_NAME || defaultName],\n ] as const) {\n if (!name) continue;\n const intents = models.get(name) ?? [];\n intents.push(intent);\n models.set(name, intents);\n }\n return [...models].map(([name, intents]) => ({ name, intents }));\n}\n\n/** Execution snapshots replace earlier snapshots; never add the same execution twice. */\nexport class CliModelUsage {\n private executions = new Map<string, TestRunReportMetrics>();\n private missing = new Set<string>();\n\n add(step: StepRunResult): void {\n for (const trace of step.report?.traces ?? []) {\n if (trace.metrics) {\n this.executions.set(trace.executionId, trace.metrics);\n this.missing.delete(trace.executionId);\n } else if (!this.executions.has(trace.executionId)) {\n this.missing.add(trace.executionId);\n }\n }\n }\n\n snapshot(): TestRunReportMetrics | undefined {\n if (!this.executions.size && !this.missing.size) return undefined;\n return sumTestRunReportMetrics(\n [...this.executions.values()],\n this.missing.size ? ['Some execution usage has not been recorded.'] : [],\n );\n }\n}\n\nexport function formatTokenCount(value: number): string {\n if (value < 1000) return String(Math.round(value));\n if (value < 1_000_000) return `${(value / 1000).toFixed(1)}k`;\n return `${(value / 1_000_000).toFixed(1)}m`;\n}\n\nexport function formatModelUsage(metrics?: TestRunReportMetrics): string[] {\n if (!metrics) return ['—'];\n if (!metrics.models?.length) {\n const name =\n metrics.modelCallCount || metrics.collection?.status === 'unknown'\n ? 'unknown'\n : '—';\n return [`${name} · ${formatTokenUsage(metrics)}`];\n }\n return metrics.models.map((model) => {\n const name =\n stripVTControlCharacters(model.modelName).replace(/\\s+/g, ' ').trim() ||\n 'unknown';\n // Per-model snapshots have no collection state. Retain the run's state\n // conservatively so missing usage never becomes an apparently complete row.\n const usage = formatTokenUsage({\n ...metrics,\n modelCallCount: model.callCount,\n promptTokens: model.promptTokens,\n cachedInputTokens: model.cachedInputTokens,\n completionTokens: model.completionTokens,\n totalTokens: model.totalTokens,\n });\n return `${name} · ${usage}`;\n });\n}\n\nexport function formatTokenUsage(\n metrics?: TestRunReportMetrics,\n includeCached = true,\n): string {\n if (!metrics) return '—';\n const state = (field: 'totalTokens' | 'promptTokens' | 'completionTokens') =>\n metrics.collection?.fields?.[field] ??\n metrics.collection?.status ??\n 'complete';\n if (state('totalTokens') === 'unknown') return '— (usage unavailable)';\n if (\n !metrics.modelCallCount &&\n !metrics.totalTokens &&\n state('totalTokens') === 'complete'\n )\n return '0 (no model calls)';\n const count = (field: 'totalTokens' | 'promptTokens' | 'completionTokens') =>\n state(field) === 'unknown'\n ? '—'\n : `${state(field) === 'partial' ? '≥' : ''}${formatTokenCount(metrics[field])}`;\n return [\n `${count('totalTokens')} total${state('totalTokens') === 'partial' ? ' (partial)' : ''}`,\n `${count('promptTokens')} input${includeCached && metrics.cachedInputTokens ? ` (${formatTokenCount(metrics.cachedInputTokens)} cached)` : ''}`,\n `${count('completionTokens')} output`,\n ].join(' · ');\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport {\n WorkflowPublicationError,\n sanitizeReportError,\n} from '@midscene/core/internal/test-runner';\nimport type { CaseRunResult, WorkflowDocumentRunResult } from '../engine/types';\nimport type { PreparedExecutionProject } from './execution-plan';\nimport type { TestProjectCollectionError, TestProjectRunResult } from './types';\n\nconst writeJson = async (path: string, value: unknown) => {\n try {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, JSON.stringify(value, null, 2));\n } catch (error) {\n throw new WorkflowPublicationError('write-result', path, error);\n }\n};\n\nexport const writeTestRunPlan = (\n runDir: string,\n projects: readonly PreparedExecutionProject[],\n) =>\n writeJson(join(runDir, 'plan.json'), {\n schemaVersion: 1,\n createdAt: new Date().toISOString(),\n projects: projects.map((item) => ({\n projectId: item.project.projectId,\n name: item.project.name,\n documents: item.plans ?? [],\n })),\n });\n\nconst toPosix = (value: string): string => value.split(sep).join('/');\n\nexport const caseAttemptResultPath = (\n projectId: string,\n documentId: string,\n result: CaseRunResult,\n): string =>\n toPosix(\n join(\n projectId,\n 'documents',\n documentId,\n 'cases',\n result.caseId,\n `${result.runId}.json`,\n ),\n );\n\nexport const workflowDocumentResultPath = (\n result: WorkflowDocumentRunResult,\n): string =>\n toPosix(\n join(\n result.projectId,\n 'documents',\n result.documentId,\n result.attemptIndex === undefined\n ? 'document.json'\n : `${result.documentRunId}.json`,\n ),\n );\n\nexport const collectionErrorPath = (\n projectId: string,\n sourcePath: string,\n): string => {\n const id = createHash('sha256')\n .update(JSON.stringify([projectId, sourcePath]))\n .digest('hex');\n return toPosix(join(projectId, 'collection-errors', `${id}.json`));\n};\n\nexport const writeWorkflowDocumentResult = (\n runDir: string,\n result: WorkflowDocumentRunResult,\n) => {\n const { documentRunId: _documentRunId, ...persistedResult } = result;\n return writeJson(\n join(runDir, workflowDocumentResultPath(result)),\n persistedResult,\n );\n};\n\nexport const writeCaseAttemptResult = (\n runDir: string,\n projectId: string,\n documentId: string,\n result: CaseRunResult,\n) => {\n const { runId: attemptId, ...persistedResult } = result;\n return writeJson(\n join(runDir, caseAttemptResultPath(projectId, documentId, result)),\n {\n ...persistedResult,\n attemptId,\n },\n );\n};\n\nexport const writeCollectionError = (\n runDir: string,\n collectionError: TestProjectCollectionError,\n) => {\n return writeJson(\n join(\n runDir,\n collectionErrorPath(\n collectionError.projectId,\n collectionError.sourcePath,\n ),\n ),\n { kind: 'collection-error', ...collectionError },\n );\n};\n\nconst relativeToSummary = (summaryPath: string, target: string): string => {\n const value = relative(dirname(summaryPath), target);\n return toPosix(value || '.');\n};\n\nconst errorJson = sanitizeReportError;\n\nexport interface TestProjectResultFileOptions {\n projectRoot: string;\n configPath?: string;\n result: TestProjectRunResult;\n}\n\nexport const writeTestProjectRunResult = (\n options: TestProjectResultFileOptions,\n) => {\n const { result } = options;\n const fact = (path: string) => toPosix(path);\n\n return writeJson(result.summaryPath, {\n schemaVersion: result.schemaVersion,\n runId: result.runId,\n startedAt: result.startedAt,\n endedAt: result.endedAt,\n durationMs: result.durationMs,\n status: result.status,\n exitCode: result.exitCode,\n ...(result.errors?.length ? { errors: result.errors.map(errorJson) } : {}),\n projectRoot: options.projectRoot,\n ...(options.configPath ? { configPath: options.configPath } : {}),\n factsRoot: '.',\n plan: 'plan.json',\n ...(result.operationLog\n ? {\n operationLog: {\n ...result.operationLog,\n path: relativeToSummary(\n result.summaryPath,\n result.operationLog.path,\n ),\n },\n }\n : {}),\n reportDir: relativeToSummary(result.summaryPath, result.reportDir),\n ...(result.reportPath\n ? { report: relativeToSummary(result.summaryPath, result.reportPath) }\n : {}),\n ...(result.markdownPath\n ? { markdown: relativeToSummary(result.summaryPath, result.markdownPath) }\n : {}),\n summary: result.summary,\n ...(result.metrics ? { metrics: result.metrics } : {}),\n projects: result.projects.map((project) => ({\n projectId: project.projectId,\n name: project.name,\n status: project.status,\n retry: project.retry,\n fileSelection: project.fileSelection,\n tagSelection: project.tagSelection,\n sourceCount: project.sourceCount,\n selectedCaseCount: project.selectedCaseCount,\n filteredCaseCount: project.filteredCaseCount,\n ...(project.lifecycle\n ? {\n lifecycle: {\n status: project.lifecycle.status,\n startedAt: project.lifecycle.startedAt,\n endedAt: project.lifecycle.endedAt,\n durationMs: project.lifecycle.durationMs,\n ...(project.lifecycle.cleanup\n ? { cleanup: project.lifecycle.cleanup }\n : {}),\n ...(project.lifecycle.pendingOperations\n ? { pendingOperations: project.lifecycle.pendingOperations }\n : {}),\n ...(project.lifecycle.setupError\n ? { setupError: errorJson(project.lifecycle.setupError) }\n : {}),\n ...(project.lifecycle.teardownErrors\n ? {\n teardownErrors:\n project.lifecycle.teardownErrors.map(errorJson),\n }\n : {}),\n },\n }\n : {}),\n cases: project.cases.map((outcome) => ({\n ...(outcome.documentRunId\n ? { documentRunId: outcome.documentRunId }\n : {}),\n documentId: outcome.documentId,\n caseId: outcome.caseId,\n sourcePath: outcome.sourcePath,\n caseIndex: outcome.caseIndex,\n name: outcome.name,\n status: outcome.status,\n ...(outcome.notRunReason ? { notRunReason: outcome.notRunReason } : {}),\n ...(outcome.attempts\n ? {\n attempts: outcome.attempts.map((attempt) => ({\n attemptId: attempt.runId,\n attemptIndex: attempt.attemptIndex,\n status: attempt.status,\n ...(attempt.cleanup ? { cleanup: attempt.cleanup } : {}),\n ...(attempt.pendingOperations\n ? { pendingOperations: attempt.pendingOperations }\n : {}),\n ...(attempt.executionStatus\n ? { executionStatus: attempt.executionStatus }\n : {}),\n ...(attempt.retryDecision\n ? { retryDecision: attempt.retryDecision }\n : {}),\n resultFile: fact(\n caseAttemptResultPath(\n project.projectId,\n outcome.documentId,\n attempt,\n ),\n ),\n ...(attempt.reportPaths?.length\n ? {\n reports: attempt.reportPaths.map((path) =>\n relativeToSummary(result.summaryPath, path),\n ),\n }\n : {}),\n })),\n }\n : {}),\n })),\n documents: project.documents.map((document) => ({\n documentId: document.documentId,\n ...(document.attemptIndex === undefined\n ? {}\n : {\n attemptIndex: document.attemptIndex,\n documentRunId: document.documentRunId,\n }),\n sourcePath: document.sourcePath,\n status: document.status,\n ...(document.cleanup ? { cleanup: document.cleanup } : {}),\n ...(document.pendingOperations\n ? { pendingOperations: document.pendingOperations }\n : {}),\n ...(document.executionStatus\n ? { executionStatus: document.executionStatus }\n : {}),\n ...(document.retryDecision\n ? { retryDecision: document.retryDecision }\n : {}),\n resultFile: fact(workflowDocumentResultPath(document)),\n ...(document.reportPaths?.length\n ? {\n reports: document.reportPaths.map((path) =>\n relativeToSummary(result.summaryPath, path),\n ),\n }\n : {}),\n })),\n collectionErrors: project.collectionErrors.map((error) => ({\n sourcePath: error.sourcePath,\n errorFile: fact(collectionErrorPath(error.projectId, error.sourcePath)),\n })),\n })),\n });\n};\n","import { dirname, isAbsolute, resolve, sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { require as tsxRequire } from 'tsx/cjs/api';\nimport { NodeRegistry } from '../engine/registry';\nimport type { NodeDefinition } from '../node/types';\n\nimport type {\n FileSetupDefinition,\n JsonValue,\n ProjectSetupDefinition,\n ResolvedExecutionProject,\n TestFileSelection,\n TestTagSelection,\n} from '@midscene/core/internal/test-runner';\nexport type {\n FileSetupContext,\n FileSetupDefinition,\n JsonPrimitive,\n JsonValue,\n ProjectSetupContext,\n ProjectSetupDefinition,\n ProjectTeardown,\n ProjectTeardownContext,\n ResolvedExecutionProject,\n TestFileSelection,\n TestTagSelection,\n} from '@midscene/core/internal/test-runner';\nimport type { ExecutionProjectDefinition as CoreExecutionProjectDefinition } from '@midscene/core/internal/test-runner';\n\nexport type ExecutionProjectDefinition<\n TContext = unknown,\n TProjectContext = TContext,\n> = Omit<\n CoreExecutionProjectDefinition<TProjectContext>,\n 'nodes' | 'fileSetup'\n> & {\n fileSetup?: FileSetupDefinition<TContext, TProjectContext>;\n nodes?: readonly NodeDefinition<any, any, TContext>[];\n};\n\nexport interface TestOptions {\n /** Global active files, including preparation and cleanup. Default 1; null is unlimited. */\n maxConcurrentFiles?: number | null;\n /** Projects from setup through completed cleanup. Default 1; null is unlimited. */\n maxConcurrentProjects?: number | null;\n /** Milliseconds for each Project setup/fileSetup, including device waits. */\n setupTimeout?: number;\n /** Milliseconds per cleanup scope; shared deadline during abnormal shutdown. */\n teardownTimeout?: number;\n bail?: number;\n testTimeout?: number;\n}\n\nexport interface ResolvedTestOptions {\n maxConcurrentFiles: number | null;\n maxConcurrentProjects: number | null;\n setupTimeout: number;\n teardownTimeout: number;\n bail: number;\n testTimeout: number;\n}\n\nexport interface TestOutputDefinition {\n /** Explicit report location, relative to the Test project. Defaults to report/ under the artifact root. */\n reportDir?: string;\n /** Defaults to a self-contained HTML; external assets require HTTP preview. */\n reportFormat?: 'single-html' | 'html-and-external-assets';\n}\n\nexport interface ResolvedTestOutputDefinition {\n reportDir?: string;\n reportFormat: 'single-html' | 'html-and-external-assets';\n}\n\nconst projectIdFromIndex = (index: number): string => `project-${index}`;\n\nexport interface TestProjectDefinition<\n TContext = undefined,\n TProjectContext = TContext,\n> {\n setup?: ProjectSetupDefinition<TProjectContext>;\n fileSetup?: FileSetupDefinition<TContext, TProjectContext>;\n projects?: readonly ExecutionProjectDefinition<TContext, TProjectContext>[];\n test?: TestOptions;\n output?: TestOutputDefinition;\n nodes?: readonly NodeDefinition<any, any, TContext>[];\n}\n\nexport interface LoadedExecutionProject<\n TContext = unknown,\n TProjectContext = TContext,\n> extends ResolvedExecutionProject<TProjectContext> {\n readonly fileSetup?: FileSetupDefinition<TContext, TProjectContext>;\n /** Effective Nodes: globals plus project-local overrides. */\n readonly nodes: NodeRegistry;\n}\n\nexport interface LoadedTestProject<\n TContext = undefined,\n TProjectContext = TContext,\n> {\n projects: readonly LoadedExecutionProject<TContext, TProjectContext>[];\n hasExplicitProjects: boolean;\n test: ResolvedTestOptions;\n output: ResolvedTestOutputDefinition;\n nodes: NodeRegistry;\n resolveNode(name: string): NodeDefinition<any, any, TContext> | undefined;\n}\n\nexport const defineTestProject = <\n TContext = undefined,\n TProjectContext = TContext,\n>(\n definition: TestProjectDefinition<TContext, TProjectContext>,\n): TestProjectDefinition<TContext, TProjectContext> => definition;\n\nexport const defineProjectSetup = <TProjectContext>(\n definition: ProjectSetupDefinition<TProjectContext>,\n): ProjectSetupDefinition<TProjectContext> => definition;\n\nexport const defineFileSetup = <TContext, TProjectContext = unknown>(\n definition: FileSetupDefinition<TContext, TProjectContext>,\n): FileSetupDefinition<TContext, TProjectContext> => definition;\n\nconst getDefaultExport = (loaded: unknown, absolutePath: string): unknown => {\n if (typeof loaded === 'object' && loaded !== null && 'default' in loaded) {\n const defaultExport = (loaded as { default: unknown }).default;\n if (\n typeof defaultExport === 'object' &&\n defaultExport !== null &&\n '__esModule' in defaultExport\n ) {\n if ('default' in defaultExport) {\n return (defaultExport as { default: unknown }).default;\n }\n throw new TypeError(\n `Midscene config \"${absolutePath}\" must have a default export.`,\n );\n }\n return defaultExport;\n }\n throw new TypeError(\n `Midscene config \"${absolutePath}\" must have a default export.`,\n );\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst rejectUnknownKeys = (\n value: Record<string, unknown>,\n allowedKeys: readonly string[],\n label: string,\n): void => {\n const allowed = new Set(allowedKeys);\n const unknown = Object.keys(value).find((key) => !allowed.has(key));\n if (unknown) {\n throw new TypeError(\n `Midscene config ${label}.${unknown} is not supported.`,\n );\n }\n};\n\nconst isAbsolutePattern = (pattern: string): boolean =>\n isAbsolute(pattern) ||\n /^[A-Za-z]:[\\\\/]/.test(pattern) ||\n pattern.startsWith('\\\\\\\\');\n\nconst validatePatterns = (\n value: unknown,\n field: 'include' | 'exclude',\n label = 'files',\n allowEmptyInclude = false,\n): readonly string[] => {\n if (!Array.isArray(value)) {\n throw new TypeError(`Midscene config ${label}.${field} must be an array.`);\n }\n if (field === 'include' && value.length === 0 && !allowEmptyInclude) {\n throw new TypeError(\n `Midscene config ${label}.include must be a non-empty array.`,\n );\n }\n\n return value.map((pattern, index) => {\n if (typeof pattern !== 'string' || pattern.trim().length === 0) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be a non-empty string.`,\n );\n }\n if (isAbsolutePattern(pattern)) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be relative to the project root.`,\n );\n }\n if (pattern.split(/[\\\\/]/).includes('..')) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must not contain a \"..\" path segment.`,\n );\n }\n if (pattern.includes('\\\\')) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must use POSIX path separators (/).`,\n );\n }\n if (pattern.startsWith('!')) {\n if (field === 'include') {\n throw new TypeError(\n `Midscene config ${label}.include[${index}] must not be a negated pattern. Use files.exclude instead.`,\n );\n }\n throw new TypeError(\n `Midscene config ${label}.exclude[${index}] must not be a negated pattern.`,\n );\n }\n return pattern;\n });\n};\n\nexport const validateTestFileSelection = (\n value: unknown,\n label = 'files',\n): TestFileSelection | undefined => {\n if (value === undefined) return undefined;\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(value, ['include', 'exclude'], label);\n const include = validatePatterns(value.include, 'include', label);\n const exclude =\n value.exclude === undefined\n ? undefined\n : validatePatterns(value.exclude, 'exclude', label);\n return Object.freeze({\n include: Object.freeze(include),\n ...(exclude ? { exclude: Object.freeze(exclude) } : {}),\n });\n};\n\nconst validateTagList = (\n value: unknown,\n field: 'include' | 'exclude',\n label: string,\n): readonly string[] => {\n if (value === undefined) return [];\n if (!Array.isArray(value)) {\n throw new TypeError(`Midscene config ${label}.${field} must be an array.`);\n }\n return value.map((tag, index) => {\n if (typeof tag !== 'string' || tag.trim().length === 0) {\n throw new TypeError(\n `Midscene config ${label}.${field}[${index}] must be a non-empty string.`,\n );\n }\n return tag;\n });\n};\n\nconst validateTagSelection = (\n value: unknown,\n label: string,\n): Readonly<Required<TestTagSelection>> => {\n if (value === undefined) return Object.freeze({ include: [], exclude: [] });\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n return Object.freeze({\n include: Object.freeze(validateTagList(value.include, 'include', label)),\n exclude: Object.freeze(validateTagList(value.exclude, 'exclude', label)),\n });\n};\n\nfunction assertJsonValue(\n value: unknown,\n path: string,\n seen: Set<unknown>,\n): asserts value is JsonValue {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'boolean'\n ) {\n return;\n }\n if (typeof value === 'number') {\n if (Number.isFinite(value)) return;\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (typeof value !== 'object' || value === undefined) {\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) !== Object.prototype &&\n Object.getPrototypeOf(value) !== null\n ) {\n throw new TypeError(`Midscene config ${path} must be JSON-compatible.`);\n }\n if (seen.has(value)) {\n throw new TypeError(`Midscene config ${path} must not contain cycles.`);\n }\n seen.add(value);\n if (Array.isArray(value)) {\n value.forEach((item, index) =>\n assertJsonValue(item, `${path}[${index}]`, seen),\n );\n } else {\n for (const [key, child] of Object.entries(value)) {\n assertJsonValue(child, `${path}.${key}`, seen);\n }\n }\n seen.delete(value);\n}\n\nconst deepFreezeJson = <T extends JsonValue>(value: T): T => {\n if (typeof value === 'object' && value !== null) {\n for (const child of Object.values(value)) deepFreezeJson(child);\n Object.freeze(value);\n }\n return value;\n};\n\nconst validateVariables = (\n value: unknown,\n label: string,\n): Readonly<Record<string, JsonValue>> => {\n if (value === undefined) return Object.freeze({});\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n assertJsonValue(value, label, new Set());\n return deepFreezeJson(value as Record<string, JsonValue>);\n};\n\nconst validateSetup = <TSetup>(\n value: unknown,\n label: string,\n): TSetup | undefined => {\n if (value === undefined) return undefined;\n if (!isRecord(value)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(value, ['name', 'setup'], label);\n if (typeof value.name !== 'string' || value.name.trim().length === 0) {\n throw new TypeError(`Midscene config ${label}.name must be non-empty.`);\n }\n if (typeof value.setup !== 'function') {\n throw new TypeError(`Midscene config ${label}.setup must be a function.`);\n }\n return value as unknown as TSetup;\n};\n\nconst validatePositiveInteger = (\n value: unknown,\n fallback: number,\n label: string,\n): number => {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || (value as number) <= 0) {\n throw new TypeError(`Midscene config ${label} must be a positive integer.`);\n }\n return value as number;\n};\n\nconst validateNonNegativeInteger = (\n value: unknown,\n fallback: number,\n label: string,\n): number => {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || (value as number) < 0) {\n throw new TypeError(\n `Midscene config ${label} must be a non-negative integer.`,\n );\n }\n return value as number;\n};\n\nconst validateConcurrency = (value: unknown, label: string): number | null => {\n if (value === null) return null;\n return validatePositiveInteger(value, 1, label);\n};\n\nconst validateFileConcurrency = (\n maxConcurrentFiles: number,\n fileSetup: unknown,\n label: string,\n): void => {\n if (maxConcurrentFiles > 1 && !fileSetup) {\n throw new TypeError(\n `Midscene config ${label}.fileSetup is required when the effective maxConcurrentFiles is greater than 1.`,\n );\n }\n};\n\nconst validateExecutionProjects = <TContext, TProjectContext>(\n value: unknown,\n defaultSetup: unknown,\n defaultFileSetup: unknown,\n globalNodes: NodeRegistry,\n test: ResolvedTestOptions,\n): {\n projects: readonly LoadedExecutionProject<TContext, TProjectContext>[];\n hasExplicitProjects: boolean;\n} => {\n if (value === undefined) {\n const setup = validateSetup<ProjectSetupDefinition<TProjectContext>>(\n defaultSetup,\n 'setup',\n );\n const fileSetup = validateSetup<\n FileSetupDefinition<TContext, TProjectContext>\n >(defaultFileSetup, 'fileSetup');\n const maxConcurrentFiles =\n test.maxConcurrentFiles ?? Number.POSITIVE_INFINITY;\n validateFileConcurrency(maxConcurrentFiles, fileSetup, 'default');\n return {\n hasExplicitProjects: false,\n projects: Object.freeze([\n Object.freeze({\n projectId: projectIdFromIndex(0),\n name: 'default',\n ...(setup ? { setup } : {}),\n ...(fileSetup ? { fileSetup } : {}),\n maxConcurrentFiles,\n tags: Object.freeze({ include: [], exclude: [] }),\n retry: 0,\n variables: Object.freeze({}),\n nodes: new NodeRegistry(globalNodes.definitions()),\n }),\n ]),\n };\n }\n if (defaultSetup !== undefined) {\n throw new TypeError(\n 'Midscene config setup cannot be used together with projects. Move setup to projects[].setup.',\n );\n }\n if (defaultFileSetup !== undefined) {\n throw new TypeError(\n 'Midscene config fileSetup cannot be used together with projects. Move fileSetup to projects[].fileSetup.',\n );\n }\n if (!Array.isArray(value) || value.length === 0) {\n throw new TypeError(\n 'Midscene config projects must be a non-empty array when declared.',\n );\n }\n const names = new Set<string>();\n const projects = value.map((candidate, index) => {\n const label = `projects[${index}]`;\n if (!isRecord(candidate)) {\n throw new TypeError(`Midscene config ${label} must be an object.`);\n }\n rejectUnknownKeys(\n candidate,\n [\n 'name',\n 'setup',\n 'fileSetup',\n 'maxConcurrentFiles',\n 'nodes',\n 'files',\n 'tags',\n 'retry',\n 'variables',\n ],\n label,\n );\n if (\n typeof candidate.name !== 'string' ||\n candidate.name.trim().length === 0\n ) {\n throw new TypeError(`Midscene config ${label}.name must be non-empty.`);\n }\n if (names.has(candidate.name)) {\n throw new TypeError(\n `Midscene config project name \"${candidate.name}\" must be unique.`,\n );\n }\n names.add(candidate.name);\n const files = validateTestFileSelection(candidate.files, `${label}.files`);\n if (candidate.nodes !== undefined && !Array.isArray(candidate.nodes)) {\n throw new TypeError(`Midscene config ${label}.nodes must be an array.`);\n }\n const localNodes = new NodeRegistry(\n candidate.nodes as NodeDefinition[] | undefined,\n );\n const nodes = new NodeRegistry([\n ...globalNodes.definitions().filter((node) => !localNodes.has(node.name)),\n ...localNodes.definitions(),\n ]);\n const fileSetup = validateSetup<\n FileSetupDefinition<TContext, TProjectContext>\n >(candidate.fileSetup, `${label}.fileSetup`);\n const globalFileLimit = test.maxConcurrentFiles ?? Number.POSITIVE_INFINITY;\n const maxConcurrentFiles = Math.min(\n globalFileLimit,\n validatePositiveInteger(\n candidate.maxConcurrentFiles,\n globalFileLimit,\n `${label}.maxConcurrentFiles`,\n ),\n );\n validateFileConcurrency(maxConcurrentFiles, fileSetup, label);\n return Object.freeze({\n projectId: projectIdFromIndex(index),\n name: candidate.name,\n nodes,\n ...(fileSetup ? { fileSetup } : {}),\n maxConcurrentFiles,\n ...(files ? { files } : {}),\n tags: validateTagSelection(candidate.tags, `${label}.tags`),\n retry: validateNonNegativeInteger(candidate.retry, 0, `${label}.retry`),\n variables: validateVariables(candidate.variables, `${label}.variables`),\n ...(candidate.setup === undefined\n ? {}\n : {\n setup: validateSetup<ProjectSetupDefinition<TProjectContext>>(\n candidate.setup,\n `${label}.setup`,\n )!,\n }),\n });\n });\n return { projects: Object.freeze(projects), hasExplicitProjects: true };\n};\n\nconst validateTestOptions = (\n value: unknown,\n hasExplicitProjects: boolean,\n): ResolvedTestOptions => {\n if (value !== undefined && !isRecord(value)) {\n throw new TypeError('Midscene config test must be an object.');\n }\n const candidate = (value ?? {}) as Record<string, unknown>;\n if (candidate.maxConcurrency !== undefined) {\n const limit =\n typeof candidate.maxConcurrency === 'number' &&\n Number.isInteger(candidate.maxConcurrency) &&\n candidate.maxConcurrency > 0\n ? candidate.maxConcurrency\n : 1;\n throw new TypeError(\n [\n 'Midscene config test.maxConcurrency is no longer supported.',\n 'It controlled project concurrency, not file concurrency. Remove it and use:',\n ` test: { maxConcurrentProjects: ${limit}, maxConcurrentFiles: ${hasExplicitProjects ? limit : 1} }`,\n hasExplicitProjects\n ? ' Set projects[].maxConcurrentFiles to 1 to keep files sequential within each project.'\n : ' The implicit default project keeps running files sequentially.',\n hasExplicitProjects\n ? 'For parallel files, configure fileSetup and raise both test.maxConcurrentFiles and projects[].maxConcurrentFiles.'\n : 'For parallel files, configure fileSetup and raise test.maxConcurrentFiles.',\n 'Migration guide: https://midscenejs.com/midscene-test/configuration.html#existing-configurations',\n ].join('\\n'),\n );\n }\n return Object.freeze({\n maxConcurrentFiles: validateConcurrency(\n candidate.maxConcurrentFiles,\n 'test.maxConcurrentFiles',\n ),\n maxConcurrentProjects: validateConcurrency(\n candidate.maxConcurrentProjects,\n 'test.maxConcurrentProjects',\n ),\n setupTimeout: validatePositiveInteger(\n candidate.setupTimeout,\n 120_000,\n 'test.setupTimeout',\n ),\n teardownTimeout: validatePositiveInteger(\n candidate.teardownTimeout,\n 30_000,\n 'test.teardownTimeout',\n ),\n bail: validateNonNegativeInteger(\n (candidate as Record<string, unknown>).bail,\n 0,\n 'test.bail',\n ),\n testTimeout: validatePositiveInteger(\n (candidate as Record<string, unknown>).testTimeout,\n 120_000,\n 'test.testTimeout',\n ),\n });\n};\n\nconst validateOutputPath = (value: unknown, label: string): string => {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new TypeError(`Midscene config ${label} must be non-empty.`);\n }\n return value;\n};\n\nconst validateOutput = (value: unknown): ResolvedTestOutputDefinition => {\n if (value !== undefined && !isRecord(value)) {\n throw new TypeError('Midscene config output must be an object.');\n }\n const candidate = (value ?? {}) as Record<string, unknown>;\n rejectUnknownKeys(candidate, ['reportDir', 'reportFormat'], 'output');\n if (\n candidate.reportFormat !== undefined &&\n candidate.reportFormat !== 'single-html' &&\n candidate.reportFormat !== 'html-and-external-assets'\n ) {\n throw new TypeError(\n 'Midscene config output.reportFormat must be single-html or html-and-external-assets.',\n );\n }\n return Object.freeze({\n reportFormat: candidate.reportFormat ?? 'single-html',\n ...(candidate.reportDir === undefined\n ? {}\n : {\n reportDir: validateOutputPath(\n candidate.reportDir,\n 'output.reportDir',\n ),\n }),\n });\n};\n\nconst validateTestProjectDefinition = <TContext, TProjectContext = TContext>(\n definition: unknown,\n): LoadedTestProject<TContext, TProjectContext> => {\n if (!isRecord(definition)) {\n throw new TypeError('Midscene config must default export an object.');\n }\n if (definition.nodes !== undefined && !Array.isArray(definition.nodes)) {\n throw new TypeError('Midscene config nodes must be an array.');\n }\n if ('setupWorkflow' in definition) {\n throw new TypeError(\n 'Midscene config setupWorkflow is no longer supported. Use setup or projects[].setup instead.',\n );\n }\n if ('setupDocument' in definition) {\n throw new TypeError(\n 'Midscene config setupDocument is not supported. Use setup or projects[].setup for resources, and beforeAll/afterAll for document lifecycle steps.',\n );\n }\n if ('root' in definition) {\n throw new TypeError(\n 'Midscene config root is not supported. Run midscene-test from the project directory or select its config with --config instead.',\n );\n }\n if ('files' in definition) {\n throw new TypeError(\n 'Midscene config files is not supported at the root. Move it to projects[].files.',\n );\n }\n if ('testRunner' in definition) {\n throw new TypeError(\n 'Midscene config testRunner is not supported. Rename it to test.',\n );\n }\n rejectUnknownKeys(\n definition,\n ['setup', 'fileSetup', 'projects', 'test', 'output', 'nodes'],\n 'root',\n );\n const nodes = new NodeRegistry(\n definition.nodes as NodeDefinition[] | undefined,\n );\n const test = validateTestOptions(\n definition.test,\n definition.projects !== undefined,\n );\n const resolvedProjects = validateExecutionProjects<TContext, TProjectContext>(\n definition.projects,\n definition.setup,\n definition.fileSetup,\n nodes,\n test,\n );\n return {\n ...resolvedProjects,\n test,\n output: validateOutput(definition.output),\n nodes,\n resolveNode: (name) =>\n nodes.get(name) as NodeDefinition<any, any, TContext> | undefined,\n };\n};\n\nconst assertSupportedConfig = (absolutePath: string): '.ts' | '.mjs' => {\n if (!absolutePath.endsWith('.ts') && !absolutePath.endsWith('.mjs')) {\n const extension = absolutePath.match(/(\\.[^./\\\\]+)$/)?.[1] ?? '(none)';\n throw new TypeError(\n `Unsupported Midscene config extension: ${extension}. Supported extensions: .ts, .mjs.`,\n );\n }\n return absolutePath.endsWith('.mjs') ? '.mjs' : '.ts';\n};\n\nconst canRetryWithCjsLoader = (error: unknown): error is Error => {\n if (!(error instanceof Error)) return false;\n const errorCode = (error as Error & { code?: string }).code;\n return (\n (error instanceof SyntaxError &&\n /^Unexpected (?:identifier|reserved word|token)/.test(error.message)) ||\n errorCode === 'ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX' ||\n (errorCode === 'ERR_UNKNOWN_FILE_EXTENSION' &&\n /^Unknown file extension\\b/.test(error.message))\n );\n};\n\nexport async function loadTestProject<\n TContext = undefined,\n TProjectContext = TContext,\n>(configPath?: string): Promise<LoadedTestProject<TContext, TProjectContext>> {\n if (!configPath) {\n return validateTestProjectDefinition<TContext, TProjectContext>({\n nodes: [],\n });\n }\n\n const absolutePath = resolve(configPath);\n const extension = assertSupportedConfig(absolutePath);\n let loaded: unknown;\n try {\n if (extension === '.mjs') {\n loaded = await import(pathToFileURL(absolutePath).href);\n } else {\n // Select tsx's ESM entry even when this loader is built as CommonJS.\n // Its CommonJS entry can resolve the async loader relative to the wrong directory.\n const { tsImport } = await import('tsx/esm/api');\n loaded = await tsImport(pathToFileURL(absolutePath).href, {\n parentURL: pathToFileURL(`${dirname(absolutePath)}${sep}`).href,\n tsconfig: false,\n });\n }\n } catch (error) {\n try {\n if (extension === '.mjs' || !canRetryWithCjsLoader(error)) throw error;\n loaded = tsxRequire(absolutePath, pathToFileURL(absolutePath));\n } catch (fallbackError) {\n const message =\n fallbackError instanceof Error ? `: ${fallbackError.message}` : '';\n throw new Error(\n `Failed to load Midscene config \"${absolutePath}\"${message}`,\n { cause: fallbackError },\n );\n }\n }\n\n return validateTestProjectDefinition<TContext, TProjectContext>(\n getDefaultExport(loaded, absolutePath),\n );\n}\n","import { readdirSync, realpathSync } from 'node:fs';\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport type { CollectedWorkflowDocument } from '@midscene/core/internal/test-runner';\nimport { buildTestRunReportPlan } from '@midscene/core/internal/test-runner';\nimport { globSync } from 'tinyglobby';\nimport { WorkflowError, WorkflowParseError } from '../errors';\nimport { collectWorkflowDocument } from '../parser/collect';\nimport type {\n PreparedDocumentInvocation,\n PreparedExecutionProject,\n ProjectPreparationOptions,\n} from './execution-plan';\nimport { writeCollectionError } from './result-store';\nimport type { LoadedExecutionProject, TestFileSelection } from './test-project';\nimport { validateTestFileSelection } from './test-project';\nimport type { TestProjectCollectionError } from './types';\n\nexport const CONFIG_NAMES = [\n 'midscene.config.ts',\n 'midscene.config.mjs',\n] as const;\nconst CONFIG_PREFIX = 'midscene.config.';\nconst ALWAYS_IGNORED_PATTERNS = [\n '.git/**',\n '.midscene/**',\n 'midscene_run/**',\n 'node_modules/**',\n '**/.git/**',\n '**/.midscene/**',\n '**/midscene_run/**',\n '**/node_modules/**',\n];\n\nexport const DEFAULT_TEST_FILE_SELECTION: TestFileSelection = {\n include: ['**/*.{yaml,yml}'],\n};\n\nconst toPosix = (value: string): string => value.split(sep).join('/');\n\nconst discoverResolvedTestFiles = (\n projectRoot: string,\n selection: TestFileSelection,\n excludedDirectories: readonly string[] = [],\n): string[] => {\n const root = resolve(projectRoot);\n const outputPatterns = excludedDirectories.flatMap((directory) => {\n const withinRoot = relative(root, directory);\n if (\n !withinRoot ||\n isAbsolute(withinRoot) ||\n withinRoot === '..' ||\n withinRoot.startsWith(`..${sep}`)\n )\n return [];\n // Escape glob metacharacters: output paths are literal directories.\n const literal = toPosix(withinRoot).replace(/([*?{}[\\]()!])/g, '\\\\$1');\n return [`${literal}/**`];\n });\n const match = (patterns: readonly string[]) =>\n globSync(patterns, {\n absolute: true,\n caseSensitiveMatch: false,\n cwd: root,\n dot: true,\n expandDirectories: false,\n followSymbolicLinks: false,\n ignore: [\n ...ALWAYS_IGNORED_PATTERNS,\n ...outputPatterns,\n ...(selection.exclude ?? []),\n ],\n onlyFiles: true,\n }).filter((file) => /\\.ya?ml$/i.test(file));\n const files = match(selection.include);\n\n return [...new Set(files.map((file) => resolve(file)))].sort((a, b) => {\n const relativeA = toPosix(relative(root, a));\n const relativeB = toPosix(relative(root, b));\n return relativeA < relativeB ? -1 : relativeA > relativeB ? 1 : 0;\n });\n};\n\nexport const discoverTestFiles = (\n projectRoot: string,\n selection: TestFileSelection = DEFAULT_TEST_FILE_SELECTION,\n): string[] => {\n const normalized = validateTestFileSelection(selection);\n if (!normalized) throw new TypeError('Test file selection is required.');\n return discoverResolvedTestFiles(projectRoot, normalized);\n};\n\nexport const discoverTestConfig = (projectRoot: string): string | undefined => {\n const root = resolve(projectRoot);\n const candidates = readdirSync(root)\n .filter((name) => name.startsWith(CONFIG_PREFIX))\n .sort();\n const supported = candidates.filter((name) =>\n CONFIG_NAMES.includes(name as (typeof CONFIG_NAMES)[number]),\n );\n const unsupported = candidates.filter(\n (name) => !CONFIG_NAMES.includes(name as (typeof CONFIG_NAMES)[number]),\n );\n if (unsupported.length > 0) {\n throw new Error(\n [\n `Unsupported or conflicting Midscene configs found in ${root}:`,\n ...candidates.map((name) => `- ${name}`),\n `Only ${CONFIG_NAMES.join(' and ')} are supported.`,\n ].join('\\n'),\n );\n }\n if (supported.length > 1) {\n throw new Error(\n [\n `Multiple Midscene configs found in ${root}:`,\n ...supported.map((name) => `- ${name}`),\n 'Pass --config <path> to select one explicitly.',\n ].join('\\n'),\n );\n }\n return supported[0] ? join(root, supported[0]) : undefined;\n};\n\nconst asCollectionError = (\n projectId: string,\n projectName: string,\n sourcePath: string,\n error: unknown,\n): TestProjectCollectionError => ({\n projectId,\n projectName,\n sourcePath,\n error:\n error instanceof WorkflowError\n ? error\n : new WorkflowParseError(\n `Failed to collect workflow document \"${sourcePath}\": ${\n error instanceof Error ? error.message : String(error)\n }`,\n { projectName, sourcePath },\n error,\n ),\n});\n\nexport const matchesTags = (\n tags: readonly string[],\n selection: LoadedExecutionProject['tags'],\n): boolean => {\n if (selection.exclude.some((tag) => tags.includes(tag))) return false;\n return (\n selection.include.length === 0 ||\n selection.include.some((tag) => tags.includes(tag))\n );\n};\n\nconst filterDocumentCases = (\n document: CollectedWorkflowDocument,\n project: LoadedExecutionProject,\n): { document?: CollectedWorkflowDocument; filtered: number } => {\n const cases = document.cases.filter((item) =>\n matchesTags(item.definition.tags ?? [], project.tags),\n );\n const filtered = document.cases.length - cases.length;\n return cases.length === 0\n ? { filtered }\n : { document: { ...document, cases }, filtered };\n};\n\nexport const selectProjects = <TProjectContext>(\n projects: readonly LoadedExecutionProject<TProjectContext>[],\n names: readonly string[] | undefined,\n): readonly LoadedExecutionProject<TProjectContext>[] => {\n if (!names || names.length === 0) return projects;\n const requested = new Set(names);\n if (requested.size !== names.length) {\n throw new Error('Each --project name may only be specified once.');\n }\n const known = new Set(projects.map((project) => project.name));\n const unknown = names.find((name) => !known.has(name));\n if (unknown) throw new Error(`Unknown Midscene project: ${unknown}`);\n return projects.filter((project) => requested.has(project.name));\n};\n\n/** Prepare and validate every document before any Project resource is acquired. */\nexport async function prepareProject(\n project: LoadedExecutionProject,\n projectRoot: string,\n runDir: string,\n defaultTimeoutMs: number,\n options: ProjectPreparationOptions = {},\n): Promise<PreparedExecutionProject> {\n const platform = options.platform?.trim();\n const fileSelection = project.files ?? DEFAULT_TEST_FILE_SELECTION;\n const prerequisiteFile = options.prerequisiteFile\n ? resolve(options.prerequisiteFile)\n : undefined;\n const discoveredFiles =\n options.files ??\n discoverResolvedTestFiles(\n options.discoveryRoot ?? projectRoot,\n fileSelection,\n options.excludedDirectories,\n );\n const selectedPath = options.testPath\n ? realpathSync(options.testPath)\n : undefined;\n const mainFiles = selectedPath\n ? discoveredFiles.filter((file) => {\n const within = relative(selectedPath, realpathSync(file));\n return (\n within === '' ||\n (!isAbsolute(within) &&\n within !== '..' &&\n !within.startsWith(`..${sep}`))\n );\n })\n : discoveredFiles;\n const files = [\n ...(prerequisiteFile ? [prerequisiteFile] : []),\n ...mainFiles.filter((file) => file !== prerequisiteFile),\n ];\n const occurrences = new Map<string, number>();\n const sources = files.map((absolutePath) => {\n const invocationIndex = occurrences.get(absolutePath) ?? 0;\n occurrences.set(absolutePath, invocationIndex + 1);\n return {\n projectId: project.projectId,\n projectName: project.name,\n sourcePath: toPosix(relative(projectRoot, absolutePath)),\n absolutePath,\n invocationIndex,\n };\n });\n const collectionErrors: TestProjectCollectionError[] = [];\n const invocations: PreparedDocumentInvocation[] = [];\n const plans: import('@midscene/core').TestRunReportDocumentPlan[] = [];\n let filteredCaseCount = 0;\n\n if (sources.length === 0 && !options.testPath) {\n const error = asCollectionError(\n project.projectId,\n project.name,\n '<project>',\n new WorkflowParseError(\n `No workflow YAML files found for project \"${project.name}\" in ${projectRoot}.`,\n { projectName: project.name, projectRoot },\n ),\n );\n collectionErrors.push(error);\n await writeCollectionError(runDir, error);\n }\n\n for (const source of sources) {\n try {\n const collected = await options.collectDocument?.(source, project);\n if (collected) {\n filteredCaseCount += collected.filteredCaseCount;\n if (collected.invocation) {\n const plan = buildTestRunReportPlan(collected.invocation.document, {\n defaultTimeoutMs: collected.invocation.defaultTimeoutMs,\n retry: collected.invocation.retry,\n });\n invocations.push({ ...collected.invocation, plan });\n plans.push(plan);\n }\n continue;\n }\n const document = collectWorkflowDocument(source, {\n resolveNode: project.nodes.get.bind(project.nodes),\n variables: project.variables,\n env: process.env,\n });\n const filtered =\n source.absolutePath === prerequisiteFile\n ? { document, filtered: 0 }\n : filterDocumentCases(document, project);\n const plan = buildTestRunReportPlan(document, {\n selectedCaseIds:\n filtered.document?.cases.map((item) => item.caseId) ?? [],\n defaultTimeoutMs,\n retry: { scope: 'case', count: project.retry },\n });\n plans.push(plan);\n filteredCaseCount += filtered.filtered;\n if (filtered.document)\n invocations.push({\n plan,\n document: filtered.document,\n retry: { scope: 'case', count: project.retry },\n defaultTimeoutMs,\n reportEnabled: true,\n bindings: {\n resolveNode: project.nodes.require.bind(project.nodes),\n ...(project.fileSetup\n ? {\n documentSetup: {\n name: project.fileSetup.name,\n setup({ projectContext, document, signal, onTeardown }) {\n return project.fileSetup!.setup({\n project,\n projectContext,\n file: document,\n env: Object.freeze({ ...process.env }),\n signal,\n onTeardown,\n });\n },\n },\n }\n : {}),\n },\n });\n } catch (error) {\n const collectionError = asCollectionError(\n project.projectId,\n project.name,\n source.sourcePath,\n error,\n );\n collectionErrors.push(collectionError);\n await writeCollectionError(runDir, collectionError);\n }\n }\n\n const documents = invocations.map((invocation) => invocation.document);\n const prerequisiteSource = sources.find(\n (source) => source.absolutePath === prerequisiteFile,\n );\n const prerequisiteDocument = documents.find(\n (document) => document.sourcePath === prerequisiteSource?.sourcePath,\n );\n return {\n project,\n ...(platform ? { platform } : {}),\n documentConcurrency: options.documentConcurrency ?? 1,\n ...(prerequisiteDocument\n ? { prerequisiteDocumentId: prerequisiteDocument.documentId }\n : {}),\n fileSelection,\n sources,\n documents,\n invocations,\n plans,\n collectionErrors,\n selectedCaseCount: documents.reduce(\n (total, document) => total + document.cases.length,\n 0,\n ),\n filteredCaseCount,\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport { existsSync, mkdirSync, statSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport {\n resolveMidsceneRunDir,\n runWithMidsceneRunDir,\n} from '@midscene/shared/common';\nimport { NativeWorkflowFormatError } from '../parser/collect';\nimport type {\n PreparedExecutionProject,\n PreparedTestRunPlan,\n TestProjectRunOptions,\n TestRunInput,\n} from './execution-plan';\nimport {\n discoverTestConfig,\n prepareProject,\n selectProjects,\n} from './project-preparation';\nimport { loadTestProject } from './test-project';\n\nconst padDatePart = (value: number): string => String(value).padStart(2, '0');\n\nexport const createTestRunId = (\n date = new Date(),\n uuid = randomUUID(),\n): string => {\n const timestamp = [\n date.getFullYear(),\n padDatePart(date.getMonth() + 1),\n padDatePart(date.getDate()),\n padDatePart(date.getHours()),\n padDatePart(date.getMinutes()),\n padDatePart(date.getSeconds()),\n ].join('');\n return `${timestamp}-${uuid.slice(0, 8)}`;\n};\n\nconst assertDirectory = (path: string, label: string): void => {\n if (!existsSync(path) || !statSync(path).isDirectory()) {\n throw new Error(`${label} does not exist or is not a directory: ${path}`);\n }\n};\n\nexport const resolveRunInput = (\n options: Pick<\n TestProjectRunOptions,\n 'cwd' | 'projectRoot' | 'configPath' | 'testPath'\n >,\n): TestRunInput => {\n const cwd = resolve(options.cwd ?? process.cwd());\n assertDirectory(cwd, 'Test working directory');\n const searchRoot = resolve(cwd, options.projectRoot ?? '.');\n assertDirectory(searchRoot, 'Test project directory');\n const configPath = options.configPath\n ? resolve(cwd, options.configPath)\n : discoverTestConfig(searchRoot);\n if (options.configPath && /\\.ya?ml$/i.test(configPath!)) {\n throw new Error(\n `midscene-test --config only accepts a native TypeScript or JavaScript project config: ${configPath}. Run legacy batch YAML with \\`midscene --config ${options.configPath}\\`.`,\n );\n }\n if (configPath && (!existsSync(configPath) || !statSync(configPath).isFile()))\n throw new Error(\n `Midscene config does not exist or is not a file: ${configPath}`,\n );\n const testPath = options.testPath\n ? resolve(cwd, options.testPath)\n : undefined;\n if (testPath) {\n if (!existsSync(testPath))\n throw new Error(`Test path does not exist: ${testPath}`);\n const stat = statSync(testPath);\n if (!stat.isDirectory() && !(stat.isFile() && /\\.ya?ml$/i.test(testPath)))\n throw new Error(\n `Test input must be a YAML file or directory: ${testPath}`,\n );\n }\n return {\n cwd,\n projectRoot: configPath ? dirname(configPath) : searchRoot,\n ...(configPath ? { configPath } : {}),\n ...(testPath ? { testPath } : {}),\n };\n};\n\n/** Composition boundary only: execution receives no raw input syntax or host options. */\nexport async function prepareTestRun(\n options: TestProjectRunOptions,\n): Promise<PreparedTestRunPlan> {\n const startedAt = new Date();\n const runId = createTestRunId(startedAt);\n const input = resolveRunInput(options);\n const { configPath } = input;\n const standalonePath = configPath ? undefined : input.testPath;\n const discovery =\n standalonePath && statSync(standalonePath).isFile()\n ? { files: [standalonePath] }\n : { discoveryRoot: standalonePath };\n const definition = await loadTestProject<unknown>(configPath);\n const artifactDir = resolveMidsceneRunDir(input.projectRoot);\n return runWithMidsceneRunDir(artifactDir, async () => {\n const resultDir = options.resultDir\n ? resolve(input.cwd, options.resultDir)\n : join(artifactDir, 'test-results');\n const runDir = join(resultDir, runId);\n const summaryPath = join(runDir, 'summary.json');\n const reportDir = definition.output.reportDir\n ? resolve(input.projectRoot, definition.output.reportDir)\n : join(artifactDir, 'report');\n mkdirSync(resultDir, { recursive: true });\n mkdirSync(runDir);\n const projects: PreparedExecutionProject[] = [];\n for (const project of selectProjects(\n definition.projects,\n options.projectNames,\n ))\n projects.push(\n await prepareProject(\n project,\n input.projectRoot,\n runDir,\n definition.test.testTimeout,\n {\n testPath: input.testPath,\n ...discovery,\n excludedDirectories: [\n artifactDir,\n resultDir,\n reportDir,\n ...['cache', 'log', 'output', 'tmp', 'dump'].map((name) =>\n join(artifactDir, name),\n ),\n ],\n },\n ),\n );\n if (\n input.testPath &&\n projects.every(\n (project) =>\n project.selectedCaseCount === 0 &&\n project.collectionErrors.length === 0,\n )\n )\n throw new Error(\n `No test cases match \"${input.testPath}\" in ${input.projectRoot}. Check --project, files.include/files.exclude, tags, and ignored output directories.`,\n );\n const hasFormatMismatch = projects.some((project) =>\n project.collectionErrors.some(\n ({ error }) => error instanceof NativeWorkflowFormatError,\n ),\n );\n return {\n startedAt,\n runId,\n projectRoot: input.projectRoot,\n artifactDir,\n ...(configPath ? { configPath } : {}),\n resultDir,\n runDir,\n summaryPath,\n reportDir,\n definition,\n projects,\n // A wrong-format file invalidates the complete command invocation. Other\n // native collection failures retain the existing per-Project isolation.\n preflightScope: hasFormatMismatch ? 'run' : 'project',\n reportEnabled: true,\n publications: [],\n onProgress: options.onProgress ?? (() => {}),\n onEvent: options.onEvent,\n };\n });\n}\n","import type { NodeDefinition } from '@midscene/core/internal/test-runner';\nimport { runWithConsoleLogScope } from '@midscene/shared/logger';\n\n/** Bind logs to the Node that emitted them, rather than the latest live row. */\nexport function scopeNodeConsole<TInput, TData, TContext>(\n node: NodeDefinition<TInput, TData, TContext>,\n): NodeDefinition<TInput, TData, TContext> {\n return {\n ...node,\n execute(ctx) {\n const position = ctx.scope === 'case' ? ctx.case : ctx.document;\n const scope = {\n projectName: position.projectName,\n sourcePath: position.sourcePath,\n ...(ctx.scope === 'case'\n ? {\n caseId: ctx.case.caseId,\n caseName: ctx.case.name,\n runId: ctx.case.runId,\n }\n : { runId: ctx.document.documentRunId }),\n phase: position.phase,\n stepIndex: position.stepIndex,\n node: node.name,\n };\n return runWithConsoleLogScope(scope, () =>\n node.execute({\n ...ctx,\n onTeardown(teardown) {\n ctx.onTeardown(() =>\n runWithConsoleLogScope(\n { ...scope, phase: 'teardown', stepIndex: undefined },\n teardown,\n ),\n );\n },\n }),\n );\n },\n };\n}\n","import {\n WorkflowExecutionFailure,\n decideRetry,\n isResourceRecoveryError,\n runDocumentAttempts,\n runWorkflowDocument,\n} from '@midscene/core/internal/test-runner';\nimport type {\n CaseRunOutcome,\n StepExecutionInfo,\n StepRunResult,\n WorkflowDocumentExecutionResult,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport { runWithConsoleLogScope } from '@midscene/shared/logger';\nimport { isFatalDeviceError } from '../errors';\nimport { scopeNodeConsole } from './console-scope';\nimport type { PreparedDocumentInvocation } from './execution-plan';\nimport type { TestReporterEvent } from './reporter-events';\nimport {\n writeCaseAttemptResult,\n writeWorkflowDocumentResult,\n} from './result-store';\nimport type { LoadedExecutionProject } from './test-project';\nimport type { TestProjectCaseRunResult } from './types';\n\ninterface DocumentInvocationSinks {\n cases: TestProjectCaseRunResult[];\n documents: WorkflowDocumentRunResult[];\n}\n\ninterface ExecuteDocumentInvocationOptions {\n isolatedContext?: boolean;\n setupTimeoutMs?: number;\n teardownTimeoutMs?: () => number;\n onUnresolvedResources?(): void;\n /** Classify failures by resource ownership, independently of notifications. */\n isProjectResourceFailure?(error: unknown): boolean;\n invocation: PreparedDocumentInvocation;\n project: LoadedExecutionProject<unknown>;\n projectContext: unknown;\n runDir: string;\n signal: AbortSignal;\n rootSignal: AbortSignal;\n shouldBail(): boolean;\n isProjectFatal(): boolean;\n markProjectFatal(): void;\n addFailedCases(count: number): void;\n onProgress(message: string): void;\n onEvent?(event: TestReporterEvent): void;\n onDocumentResult?(result: WorkflowDocumentRunResult): Promise<void>;\n sinks: DocumentInvocationSinks;\n}\n\nconst stepPosition = (info: StepExecutionInfo) =>\n info.scope === 'case' ? info.case : info.document;\n\nconst formatStep = (info: StepExecutionInfo): string => {\n const position = stepPosition(info);\n const phase = position.phase === 'steps' ? 'step' : position.phase;\n return `${phase} ${position.stepIndex + 1}/${info.stepCount}: ${info.node}`;\n};\n\nconst formatStepResult = (\n info: StepExecutionInfo,\n result: StepRunResult,\n): string => {\n const indent = info.scope === 'case' ? ' ' : ' ';\n if (result.status === 'not-run')\n return `${indent}– ${formatStep(info)} (not run: ${result.notRunReason})`;\n const symbol = result.status === 'success' ? '✓' : '✗';\n const error = result.error ? ` — ${result.error.message}` : '';\n const continuation = result.continuedAfterError ? '; continuing' : '';\n return `${indent}${symbol} ${formatStep(info)} (${result.durationMs} ms)${error}${continuation}`;\n};\n\nconst caseHasFatalError = (outcome: CaseRunOutcome): boolean =>\n (outcome.attempts ?? []).some(\n (attempt) =>\n [...attempt.beforeEach, ...attempt.steps, ...attempt.afterEach].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) ||\n (attempt.teardownErrors ?? []).some(isFatalDeviceError) ||\n !!attempt.executionErrors?.some(isResourceRecoveryError),\n );\n\nconst documentHasFatalError = (result: WorkflowDocumentRunResult): boolean =>\n [...result.beforeAll, ...result.afterAll].some(\n (step) => step.error && isFatalDeviceError(step.error),\n ) ||\n (result.teardownErrors ?? []).some(isFatalDeviceError) ||\n !!result.executionErrors?.some(isResourceRecoveryError);\n\n// Only an explicit ownership signal can establish a Project-wide failure.\nexport const isSharedResourceFailure = (error: unknown): boolean => {\n const seen = new Set<object>();\n const pending: unknown[] = [error];\n while (pending.length && seen.size < 50) {\n const item = pending.pop();\n if (typeof item !== 'object' || item === null || seen.has(item)) continue;\n seen.add(item);\n const failure = item as {\n code?: string;\n cause?: unknown;\n errors?: unknown[];\n };\n if (failure.code === 'PROJECT_RESOURCE_ERROR') return true;\n if (failure.cause) pending.push(failure.cause);\n if (Array.isArray(failure.errors))\n pending.push(...failure.errors.slice(0, 50));\n }\n return false;\n};\n\n/** Execute prepared document policies through the shared retry boundary. */\nexport async function executeDocumentInvocation(\n options: ExecuteDocumentInvocationOptions,\n): Promise<void> {\n const { invocation, project, sinks } = options;\n const isProjectResourceFailure =\n options.isProjectResourceFailure ?? (() => false);\n const { document } = invocation;\n const documentRetry = invocation.retry.scope === 'document';\n const attempts: WorkflowDocumentExecutionResult[] = [];\n const fileSetup = invocation.bindings.documentSetup;\n const documentSetup = fileSetup\n ? {\n ...fileSetup,\n setup(ctx: Parameters<typeof fileSetup.setup>[0]) {\n const scope = {\n projectName: project.name,\n sourcePath: document.sourcePath,\n runId: ctx.document.documentRunId,\n phase: 'fileSetup',\n };\n return runWithConsoleLogScope(scope, async () => {\n try {\n return await fileSetup.setup({\n ...ctx,\n onTeardown(teardown) {\n ctx.onTeardown(() =>\n runWithConsoleLogScope(\n { ...scope, phase: 'teardown' },\n teardown,\n ),\n );\n },\n });\n } catch (error) {\n if (isProjectResourceFailure(error)) options.markProjectFatal();\n throw error;\n }\n });\n },\n }\n : undefined;\n\n options.onEvent?.({\n type: 'document-start',\n documentId: document.documentId,\n projectName: project.name,\n sourcePath: document.sourcePath,\n cases: document.cases.length,\n });\n\n await runDocumentAttempts(\n {\n retry: documentRetry ? invocation.retry.count : 0,\n signal: options.signal,\n shouldStop: () => options.shouldBail() || options.isProjectFatal(),\n },\n async (documentAttemptIndex) => {\n if (documentRetry)\n options.onProgress(\n ` file attempt ${documentAttemptIndex + 1}/${invocation.retry.count + 1}: ${document.sourcePath}`,\n );\n const execution = await runWithConsoleLogScope(\n { projectName: project.name, sourcePath: document.sourcePath },\n () =>\n runWorkflowDocument(document, {\n plan: invocation.plan,\n documentAttemptIndex: documentRetry\n ? documentAttemptIndex\n : undefined,\n ...invocation.bindings,\n resolveNode: (name) =>\n scopeNodeConsole(invocation.bindings.resolveNode(name)),\n documentSetup,\n setupTimeoutMs: options.setupTimeoutMs,\n teardownTimeoutMs: options.teardownTimeoutMs,\n project,\n projectContext: options.projectContext,\n retry: documentRetry ? 0 : invocation.retry.count,\n signal: options.signal,\n defaultTimeoutMs: invocation.defaultTimeoutMs,\n shouldStop: () =>\n options.rootSignal.aborted ||\n options.shouldBail() ||\n options.isProjectFatal(),\n stopReason: () =>\n options.rootSignal.aborted\n ? 'interrupted'\n : options.isProjectFatal()\n ? 'fatal-error'\n : 'bail',\n isFatalError: (run) =>\n [...run.beforeEach, ...run.steps, ...run.afterEach].some(\n (step) =>\n step.error &&\n (isFatalDeviceError(step.error) ||\n isProjectResourceFailure(step.error)),\n ) ||\n (run.teardownErrors ?? []).some(\n (error) =>\n isFatalDeviceError(error) || isProjectResourceFailure(error),\n ),\n onCaseStart: (collectedCase) => {\n options.onProgress(\n ` [case ${collectedCase.caseIndex + 1}/${document.cases.length}] ${collectedCase.definition.name}`,\n );\n },\n onStepStart: (info) => {\n options.onEvent?.({\n type: 'step-start',\n projectName: project.name,\n info,\n });\n const indent = info.scope === 'case' ? ' ' : ' ';\n options.onProgress(`${indent}→ ${formatStep(info)}`);\n },\n onStepResult: async (info, result) => {\n if (isProjectResourceFailure(result.error))\n options.markProjectFatal();\n await invocation.bindings.onStepResult?.(info, result);\n options.onProgress(formatStepResult(info, result));\n options.onEvent?.({\n type: 'step-end',\n projectName: project.name,\n info,\n result,\n });\n },\n onCaseResult: async (attempt) => {\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n options.onProgress(\n ` ${attempt.status === 'success' ? '✓' : '✗'} case attempt ${attempt.attemptIndex + 1}/${documentRetry ? 1 : invocation.retry.count + 1}: ${attempt.name} (${attempt.durationMs} ms)`,\n );\n if (!documentRetry)\n options.onEvent?.({\n type: 'case-attempt-end',\n attempt,\n maxAttempts: invocation.retry.count + 1,\n });\n },\n onCaseOutcome: (outcome) => {\n if (documentRetry)\n options.onEvent?.({\n type: 'case-progress',\n outcome,\n documentAttemptIndex,\n });\n else options.onEvent?.({ type: 'case-end', outcome });\n if (\n outcome.attempts?.some(\n (attempt) =>\n [\n ...attempt.beforeEach,\n ...attempt.steps,\n ...attempt.afterEach,\n ].some((step) => isProjectResourceFailure(step.error)) ||\n attempt.teardownErrors?.some(isProjectResourceFailure),\n )\n )\n options.markProjectFatal();\n if (!options.isolatedContext && caseHasFatalError(outcome))\n options.markProjectFatal();\n if (!documentRetry && outcome.status === 'failed')\n options.addFailedCases(1);\n },\n onDocumentResult: options.onDocumentResult,\n }),\n ).catch(async (error: unknown) => {\n if (error instanceof WorkflowExecutionFailure) {\n const partial = error.result as WorkflowDocumentExecutionResult;\n const resourceOnly =\n error.errors.length > 0 &&\n error.errors.every(\n (failure) =>\n isResourceRecoveryError(failure) ||\n partial.document.hostErrors?.some(\n (host) =>\n host.phase === 'cleanup' &&\n (host.error === failure ||\n (host.error instanceof Error &&\n host.error.cause === failure)),\n ),\n );\n // Legacy recovery failures stop context reuse. Isolated file failures\n // are checked for unresolved resources below; publication still throws.\n if (resourceOnly) {\n if (\n !options.isolatedContext &&\n error.errors.some(isResourceRecoveryError)\n )\n options.markProjectFatal();\n return partial;\n }\n if (documentRetry)\n partial.document.retryDecision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: 'failed',\n infrastructureError: true,\n });\n attempts.push(partial);\n sinks.documents.push(partial.document);\n sinks.cases.push(\n ...partial.cases.map((outcome) => ({\n ...outcome,\n documentId: document.documentId,\n documentRunId: partial.document.documentRunId,\n })),\n );\n try {\n for (const outcome of partial.cases)\n for (const attempt of outcome.attempts ?? [])\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n await writeWorkflowDocumentResult(options.runDir, partial.document);\n } catch (publicationError) {\n throw new WorkflowExecutionFailure(partial, [\n ...error.errors,\n publicationError,\n ]);\n }\n }\n throw error;\n });\n\n if (!options.isolatedContext && documentHasFatalError(execution.document))\n options.markProjectFatal();\n if (\n [\n ...execution.document.beforeAll,\n ...execution.document.afterAll,\n ...(execution.document.hostErrors ?? []).map(({ error }) => ({\n error,\n })),\n ...(execution.document.teardownErrors ?? []).map((error) => ({\n error,\n })),\n ].some(({ error }) => isProjectResourceFailure(error))\n )\n options.markProjectFatal();\n const owners = [\n execution.document,\n ...execution.cases.flatMap((outcome) => outcome.attempts ?? []),\n ];\n const cleanupPending = owners.some(\n (owner) => owner.cleanup?.status === 'pending',\n );\n const operationPending = owners.some(\n (owner) => !!owner.pendingOperations?.length,\n );\n const cleanupFailed = owners.some(\n (owner) =>\n owner.cleanup?.status === 'failed' ||\n !!owner.teardownErrors?.length ||\n ('hostErrors' in owner &&\n owner.hostErrors?.some(({ phase }) => phase === 'cleanup')),\n );\n // Legacy files reuse their Project context. Isolated files may continue\n // after settled local cleanup failure; unresolved ownership stops dispatch.\n if (cleanupPending || operationPending) {\n options.markProjectFatal();\n options.onUnresolvedResources?.();\n } else if (cleanupFailed && !options.isolatedContext)\n options.markProjectFatal();\n const failed =\n execution.document.status === 'failed' ||\n execution.cases.some((item) => item.status !== 'success');\n const decision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: failed ? 'failed' : 'success',\n cleanupPending,\n cleanupFailed,\n operationPending,\n fatalError: options.isProjectFatal(),\n interrupted: options.signal.aborted || options.rootSignal.aborted,\n shouldStop: options.shouldBail(),\n });\n if (documentRetry) execution.document.retryDecision = decision;\n if (documentRetry && decision.decision === 'retry')\n options.onEvent?.({\n type: 'document-retry',\n document: execution.document,\n maxAttempts: invocation.retry.count + 1,\n });\n attempts.push(execution);\n sinks.cases.push(\n ...execution.cases.map((outcome) => ({\n ...outcome,\n documentId: document.documentId,\n documentRunId: execution.document.documentRunId,\n })),\n );\n sinks.documents.push(execution.document);\n // Per-attempt callbacks publish incremental facts; seal the final retry\n // decision after callback-driven interruption/bail has been observed.\n try {\n for (const outcome of execution.cases)\n for (const attempt of outcome.attempts ?? [])\n await writeCaseAttemptResult(\n options.runDir,\n project.projectId,\n document.documentId,\n attempt,\n );\n await writeWorkflowDocumentResult(options.runDir, execution.document);\n } catch (error) {\n execution.document.status = 'failed';\n execution.document.hostErrors = [\n ...(execution.document.hostErrors ?? []),\n { phase: 'publication', error },\n ];\n if (documentRetry)\n execution.document.retryDecision = decideRetry({\n scope: 'document',\n retryCount: invocation.retry.count,\n attemptIndex: documentAttemptIndex,\n status: 'failed',\n infrastructureError: true,\n });\n throw new WorkflowExecutionFailure(execution, [error]);\n }\n return decision.decision === 'retry' ? 'failed' : undefined;\n },\n );\n\n const final = attempts.at(-1);\n if (!final) return;\n if (documentRetry)\n for (const outcome of final.cases)\n options.onEvent?.({\n type: 'case-end',\n outcome,\n documentRetries: attempts.length - 1,\n });\n const failedCases = final.cases.filter(\n (item) => item.status === 'failed',\n ).length;\n options.onEvent?.({\n type: 'document-end',\n document: final.document,\n cases: final.cases,\n durationMs: attempts.reduce(\n (total, attempt) => total + attempt.document.durationMs,\n 0,\n ),\n });\n if (documentRetry && failedCases) options.addFailedCases(failedCases);\n else if (final.document.status === 'failed' && failedCases === 0)\n options.addFailedCases(Math.max(1, failedCases));\n}\n","import type {\n ProjectRuntime,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport {\n WorkflowError,\n getPendingScopeOperations,\n getResourceCleanupCompletion,\n trackResourceOperation,\n waitForScopeOperations,\n} from '@midscene/core/internal/test-runner';\nimport { runWithConsoleLogScope } from '@midscene/shared/logger';\nimport { createProjectRuntime } from '../engine/project-runtime';\nimport {\n executeDocumentInvocation,\n isSharedResourceFailure,\n} from './document-invocation';\nimport type { PreparedExecutionProject } from './execution-plan';\nimport type { TestReporterEvent } from './reporter-events';\nimport type {\n TestExecutionProjectRunResult,\n TestProjectCaseRunResult,\n} from './types';\n\ninterface FileProjectState {\n prepared: PreparedExecutionProject;\n cases: TestProjectCaseRunResult[];\n documents: WorkflowDocumentRunResult[];\n runtime?: ProjectRuntime;\n lifecycle?: TestExecutionProjectRunResult['lifecycle'];\n cursor: number;\n active: number;\n initializing: boolean;\n finished: boolean;\n fatal: boolean;\n setupFailed: boolean;\n}\n\ninterface FileSchedulerOptions {\n projects: readonly PreparedExecutionProject[];\n maxConcurrentFiles: number;\n maxConcurrentProjects: number;\n setupTimeoutMs: number;\n teardownTimeoutMs(): number;\n signal: AbortSignal;\n runDir: string;\n preflightFailed: boolean;\n shouldBail(): boolean;\n addFailedCases(count: number): void;\n announceProject(project: PreparedExecutionProject, index: number): void;\n onProgress(project: PreparedExecutionProject, message: string): void;\n onInfrastructureError(error: unknown): void;\n onEvent?(event: TestReporterEvent): void;\n onProjectEnd?(state: FileProjectState): void;\n}\n\n/** Round-robin files within global file and live Project limits. */\nexport async function runPreparedFiles(\n options: FileSchedulerOptions,\n): Promise<FileProjectState[]> {\n const states: FileProjectState[] = options.projects.map((prepared) => ({\n prepared,\n cases: [],\n documents: [],\n cursor: 0,\n active: 0,\n initializing: false,\n finished: false,\n fatal: false,\n setupFailed: false,\n }));\n let nextProject = 0;\n let resourcesUnresolved = false;\n let occupied = 0;\n let occupiedProjects = 0;\n const cleanupQueue: Array<() => void> = [];\n const release = () => {\n occupied--;\n while (occupied < options.maxConcurrentFiles && cleanupQueue.length) {\n occupied++;\n cleanupQueue.shift()!();\n }\n wake?.();\n };\n let wake: (() => void) | undefined;\n const running = new Set<Promise<void>>();\n const stopped = (state: FileProjectState) =>\n options.signal.aborted || options.shouldBail() || state.fatal;\n const invalid = (state: FileProjectState) =>\n options.preflightFailed || state.prepared.collectionErrors.length > 0;\n const unresolved = () => {\n if (resourcesUnresolved) return;\n resourcesUnresolved = true;\n options.onInfrastructureError(\n new WorkflowError(\n 'Resources are still running or cleanup is pending. No new test files will start.',\n { code: 'UNRESOLVED_FILE_RESOURCES' },\n ),\n );\n };\n const finalizeProject = (state: FileProjectState) => {\n const { prepared } = state;\n const completed = new Set(state.cases.map((item) => item.caseId));\n const reason = invalid(state)\n ? 'project-preflight-failed'\n : state.setupFailed\n ? 'project-setup-failed'\n : options.signal.aborted\n ? 'interrupted'\n : state.fatal\n ? 'fatal-error'\n : 'bail';\n for (const document of prepared.documents)\n for (const item of document.cases) {\n if (completed.has(item.caseId)) continue;\n state.cases.push({\n documentId: document.documentId,\n caseId: item.caseId,\n projectName: prepared.project.name,\n name: item.definition.name,\n sourcePath: item.sourcePath,\n caseIndex: item.caseIndex,\n status: 'not-run',\n notRunReason: reason,\n });\n }\n const order = new Map(\n prepared.documents.map((document, i) => [document.documentId, i]),\n );\n const position = (id: string) => order.get(id) ?? Number.MAX_SAFE_INTEGER;\n state.cases.sort(\n (a, b) =>\n position(a.documentId) - position(b.documentId) ||\n a.caseIndex - b.caseIndex,\n );\n state.documents.sort(\n (a, b) => position(a.documentId) - position(b.documentId),\n );\n };\n const finishProject = async (state: FileProjectState) => {\n if (!state.runtime || state.finished) return;\n state.finished = true;\n try {\n options.onEvent?.({\n type: 'project-phase',\n projectName: state.prepared.project.name,\n phase: 'teardown',\n });\n } catch (error) {\n // A presentation failure must not prevent releasing owned resources.\n options.onInfrastructureError(error);\n }\n const failed =\n state.fatal ||\n options.signal.aborted ||\n state.cases.some((item) => item.status !== 'success') ||\n state.documents.some((item) => item.status !== 'success');\n state.lifecycle = await runWithConsoleLogScope(\n { projectName: state.prepared.project.name, phase: 'teardown' },\n () => state.runtime!.finish(failed ? 'failed' : 'success'),\n );\n const releaseProject = () => {\n occupiedProjects--;\n wake?.();\n };\n if (\n state.lifecycle.cleanup?.status === 'pending' ||\n state.lifecycle.pendingOperations?.length\n ) {\n unresolved();\n // A result snapshot can precede actual resource release.\n void Promise.all([\n waitForScopeOperations(state.runtime.signal),\n getResourceCleanupCompletion(state.runtime.signal),\n ]).then(releaseProject, (error) => {\n options.onInfrastructureError(error);\n releaseProject();\n });\n } else {\n releaseProject();\n finalizeProject(state);\n options.onProjectEnd?.(state);\n }\n };\n\n const admit = () => {\n for (let offset = 0; offset < states.length; offset++) {\n const index = (nextProject + offset) % states.length;\n const state = states[index];\n if (invalid(state) || state.finished || state.initializing) continue;\n if (!state.runtime && occupiedProjects >= options.maxConcurrentProjects)\n continue;\n const cleanupOnly =\n !!state.runtime &&\n state.active === 0 &&\n (stopped(state) || state.cursor === state.prepared.invocations.length);\n if (\n !cleanupOnly &&\n (stopped(state) ||\n state.cursor >= state.prepared.invocations.length ||\n state.active >=\n (state.prepared.project.maxConcurrentFiles ??\n options.maxConcurrentFiles))\n )\n continue;\n nextProject = (index + 1) % states.length;\n occupied++;\n state.active++;\n if (!state.runtime && !cleanupOnly) {\n // Claim both budgets before setup so idle Projects are not pre-created.\n occupiedProjects++;\n state.initializing = true;\n }\n const invocationIndex = cleanupOnly ? -1 : state.cursor++;\n return { state, index, invocationIndex };\n }\n };\n\n const run = async ({\n state,\n index,\n invocationIndex,\n }: NonNullable<ReturnType<typeof admit>>) => {\n const { prepared } = state;\n const { project } = prepared;\n let fileResourcesPending = false;\n try {\n if (invocationIndex < 0) {\n await finishProject(state);\n return;\n }\n if (!state.runtime) {\n state.runtime = createProjectRuntime({\n project,\n setup: project.setup,\n signal: options.signal,\n setupTimeoutMs: options.setupTimeoutMs,\n teardownTimeoutMs: options.teardownTimeoutMs,\n });\n setMaxListeners(\n Math.max(\n 10,\n Math.min(\n prepared.invocations.length,\n project.maxConcurrentFiles ?? options.maxConcurrentFiles,\n ) + 1,\n ),\n state.runtime.signal,\n );\n options.announceProject(prepared, index);\n options.onEvent?.({\n type: 'project-phase',\n projectName: project.name,\n phase: 'setup',\n });\n await runWithConsoleLogScope(\n { projectName: project.name, phase: 'setup' },\n () => state.runtime!.start(),\n );\n options.onEvent?.({\n type: 'project-phase',\n projectName: project.name,\n phase: 'running',\n });\n state.initializing = false;\n if (!state.runtime.canRun) {\n state.fatal = true;\n state.setupFailed = true;\n }\n wake?.();\n }\n if (stopped(state)) return;\n const invocation = prepared.invocations[invocationIndex];\n options.onProgress(\n prepared,\n ` [document ${invocationIndex + 1}/${prepared.invocations.length}] ${invocation.document.sourcePath}`,\n );\n await executeDocumentInvocation({\n invocation,\n project,\n projectContext: state.runtime.context,\n runDir: options.runDir,\n signal: state.runtime.signal,\n rootSignal: options.signal,\n shouldBail: options.shouldBail,\n isProjectFatal: () => state.fatal,\n markProjectFatal: () => {\n if (state.fatal) return;\n state.fatal = true;\n state.runtime?.abort(\n new WorkflowError(\n `Project \"${project.name}\" shared execution environment is unavailable.`,\n { code: 'PROJECT_RESOURCE_ERROR' },\n ),\n );\n },\n addFailedCases: options.addFailedCases,\n onProgress: (message) =>\n options.onProgress(\n prepared,\n options.maxConcurrentFiles > 1\n ? ` [${invocation.document.sourcePath}]${message}`\n : message,\n ),\n sinks: state,\n onEvent: options.onEvent,\n isolatedContext: project.fileSetup !== undefined,\n isProjectResourceFailure: isSharedResourceFailure,\n setupTimeoutMs: options.setupTimeoutMs,\n teardownTimeoutMs: options.teardownTimeoutMs,\n onUnresolvedResources: () => {\n fileResourcesPending = true;\n unresolved();\n },\n });\n } catch (error) {\n state.fatal = true;\n fileResourcesPending =\n !!state.runtime &&\n getPendingScopeOperations(state.runtime.signal).length > 0;\n options.onInfrastructureError(error);\n } finally {\n state.initializing = false;\n try {\n // The last file retains its global/local admission through shared cleanup.\n if (\n state.active === 1 &&\n (stopped(state) || state.cursor === prepared.invocations.length)\n )\n await finishProject(state);\n } catch (error) {\n options.onInfrastructureError(error);\n }\n state.active--;\n if (\n state.runtime &&\n (fileResourcesPending || state.lifecycle?.cleanup?.status === 'pending')\n ) {\n // A returned pending snapshot does not release the actual admission.\n // At shutdown this may conservatively wait for siblings in the Project.\n void waitForScopeOperations(state.runtime.signal).then(\n release,\n (error) => {\n options.onInfrastructureError(error);\n release();\n },\n );\n } else release();\n wake?.();\n }\n };\n\n while (true) {\n const changed = new Promise<void>((resolve) => {\n wake = resolve;\n });\n while (occupied < options.maxConcurrentFiles) {\n const job = admit();\n if (!job) break;\n const task = run(job);\n running.add(task);\n const settled = () => {\n running.delete(task);\n wake?.();\n };\n void task.then(settled, (error) => {\n options.onInfrastructureError(error);\n settled();\n });\n }\n if (!running.size) break;\n await changed;\n }\n wake = undefined;\n\n // Pending acquisitions/disposers retain their admissions after the result\n // deadline. Idle initialized Projects queue actual cleanup behind those\n // admissions; their snapshots still return within the shared shutdown limit.\n await Promise.all(\n states.map(async (state) => {\n if (!state.runtime || state.finished) return;\n const admission = new Promise<void>((resolve) => {\n cleanupQueue.push(resolve);\n });\n trackResourceOperation({}, admission, state.runtime.signal);\n while (occupied < options.maxConcurrentFiles && cleanupQueue.length) {\n occupied++;\n cleanupQueue.shift()!();\n }\n try {\n await finishProject(state);\n } catch (error) {\n options.onInfrastructureError(error);\n } finally {\n void Promise.all([\n admission,\n getResourceCleanupCompletion(state.runtime.signal),\n ]).then(release, (error) => {\n options.onInfrastructureError(error);\n release();\n });\n }\n }),\n );\n\n for (const state of states) {\n const { prepared } = state;\n if (!state.runtime)\n options.announceProject(prepared, states.indexOf(state));\n finalizeProject(state);\n }\n return states;\n}\nimport { setMaxListeners } from 'node:events';\n","import { appendFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { TestRunReportOperationEvent } from '@midscene/core';\n\n/** Registered operations keep this sink after the report has been sealed.\n * Each small, bounded event is written before returning to the operation. No\n * open file descriptor or mutable report object is retained by the journal.\n */\nexport function createOperationJournal(runDir: string) {\n const path = join(runDir, 'operations.jsonl');\n writeFileSync(path, '', { flag: 'wx' });\n return {\n path,\n append(event: Readonly<TestRunReportOperationEvent>) {\n appendFileSync(path, `${JSON.stringify(event)}\\n`);\n },\n };\n}\n","import { setMaxListeners } from 'node:events';\nimport { dirname, join } from 'node:path';\nimport type { TestRunReportSourceIndex } from '@midscene/core';\nimport {\n WorkflowExecutionFailure,\n WorkflowPublicationError,\n asExecutionError,\n observeResourceOperations,\n sumTestRunReportMetrics,\n} from '@midscene/core/internal/test-runner';\nimport type {\n CollectedCase,\n WorkflowDocumentRunResult,\n} from '@midscene/core/internal/test-runner';\nimport {\n ReportSession,\n TestRunReportAssembler,\n calculateTestRunHealth,\n} from '@midscene/core/report';\nimport { runWithMidsceneRunDir } from '@midscene/shared/common';\nimport { getDebug } from '@midscene/shared/logger';\nimport { writeTestResultMarkdown } from '../report/result-markdown';\nimport {\n buildTestRunReportDump,\n collectTestRunReportSources,\n} from '../report/test-run-report';\nimport type {\n PreparedExecutionProject,\n PreparedTestRunPlan,\n} from './execution-plan';\nimport { runPreparedFiles } from './file-scheduler';\nimport { configuredModelNames } from './model-usage';\nimport { createOperationJournal } from './operation-journal';\nimport { writeTestProjectRunResult, writeTestRunPlan } from './result-store';\nimport type {\n TestExecutionProjectRunResult,\n TestProjectCaseRunResult,\n TestProjectRunResult,\n TestProjectRunSummary,\n} from './types';\n\nconst asNotRun = (\n documentId: string,\n collectedCase: CollectedCase,\n projectName: string,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n): TestProjectCaseRunResult => ({\n documentId,\n caseId: collectedCase.caseId,\n projectName,\n name: collectedCase.definition.name,\n sourcePath: collectedCase.sourcePath,\n caseIndex: collectedCase.caseIndex,\n status: 'not-run',\n notRunReason: reason,\n});\n\nconst summarize = (\n projects: readonly TestExecutionProjectRunResult[],\n): TestProjectRunSummary => {\n const healthCases = projects.flatMap((project) => {\n const documentAttemptByRunId = new Map(\n project.documents.map((document) => [\n document.documentRunId,\n document.attemptIndex ?? 0,\n ]),\n );\n return latestById(project.cases, (item) => item.caseId).map((item) => {\n return {\n status: item.status,\n ...(item.run ? { run: item.run } : {}),\n ...(item.attempts ? { attempts: item.attempts } : {}),\n retryCount: item.documentRunId\n ? (documentAttemptByRunId.get(item.documentRunId) ?? 0)\n : 0,\n };\n });\n });\n const documents = projects.flatMap((project) =>\n latestById(project.documents, (item) => item.documentId),\n );\n const health = calculateTestRunHealth(healthCases);\n return {\n total: health.total,\n passed: health.passed,\n failed: health.failed,\n notRun: health.notRun,\n passedAfterRetry: health.passedAfterRetry,\n finalPassRate: health.finalPassRate,\n firstPassRate: health.firstPassRate,\n filtered: projects.reduce(\n (total, project) => total + project.filteredCaseCount,\n 0,\n ),\n collectionErrors: projects.reduce(\n (total, project) => total + project.collectionErrors.length,\n 0,\n ),\n documentFailures: documents.filter(\n (document) => document.status === 'failed',\n ).length,\n projectFailures: projects.filter((project) => project.status === 'failed')\n .length,\n };\n};\n\nconst latestById = <T>(items: readonly T[], id: (item: T) => string): T[] => [\n ...new Map(items.map((item) => [id(item), item])).values(),\n];\n\nconst notRunSuite = (\n prepared: PreparedExecutionProject,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n): TestProjectCaseRunResult[] =>\n prepared.documents.flatMap((document) =>\n document.cases.map((item) =>\n asNotRun(document.documentId, item, prepared.project.name, reason),\n ),\n );\n\n/** The executor sees prepared policies and bindings, never source-language rules. */\nexport async function runPreparedTestProject(\n plan: PreparedTestRunPlan,\n): Promise<TestProjectRunResult> {\n const reports = new ReportSession(join(plan.runDir, 'records'));\n return runWithMidsceneRunDir(plan.artifactDir, () =>\n reports.run(() => runWithReportSession(plan, reports)),\n );\n}\n\nasync function runWithReportSession(\n plan: PreparedTestRunPlan,\n reports: ReportSession,\n): Promise<TestProjectRunResult> {\n const {\n startedAt,\n runId,\n projectRoot,\n configPath,\n resultDir,\n runDir,\n summaryPath,\n reportDir,\n definition,\n projects: preparedProjects,\n } = plan;\n const progress = plan.onProgress;\n const totalDocuments = preparedProjects.reduce(\n (total, prepared) => total + prepared.documents.length,\n 0,\n );\n const totalCases = preparedProjects.reduce(\n (total, prepared) => total + prepared.selectedCaseCount,\n 0,\n );\n const totalErrors = preparedProjects.reduce(\n (total, prepared) => total + prepared.collectionErrors.length,\n 0,\n );\n plan.onEvent?.({\n type: 'run-start',\n configuredModels: configuredModelNames(),\n projects: preparedProjects.length,\n documents: totalDocuments + totalErrors,\n cases: totalCases,\n projectRoot,\n configPath,\n startedAt: startedAt.toISOString(),\n maxConcurrentProjects: definition.test.maxConcurrentProjects,\n maxConcurrentFiles: definition.test.maxConcurrentFiles,\n files: preparedProjects.flatMap((prepared) => [\n ...prepared.documents.map((document) => ({\n documentId: document.documentId,\n projectName: prepared.project.name,\n sourcePath: document.sourcePath,\n cases: document.cases.length,\n })),\n ...prepared.collectionErrors.map((error) => ({\n documentId: error.sourcePath,\n projectName: prepared.project.name,\n sourcePath: error.sourcePath,\n cases: 0,\n })),\n ]),\n });\n progress(\n `midscene-test: preflighted ${preparedProjects.length} projects, ${totalDocuments} documents, ${totalCases} cases, ${totalErrors} collection errors`,\n );\n\n const effectiveConcurrency = Math.min(\n definition.test.maxConcurrentFiles ?? Number.POSITIVE_INFINITY,\n Math.max(1, totalDocuments),\n );\n await writeTestRunPlan(runDir, preparedProjects);\n const journal = createOperationJournal(runDir);\n const rootController = new AbortController();\n setMaxListeners(\n Math.max(10, effectiveConcurrency + 1),\n rootController.signal,\n );\n const handleSignal = (signal: NodeJS.Signals) => {\n rootController.abort(new Error(`Workflow interrupted by ${signal}.`));\n };\n const sigint = () => handleSignal('SIGINT');\n const sigterm = () => handleSignal('SIGTERM');\n process.on('SIGINT', sigint);\n process.on('SIGTERM', sigterm);\n\n let failedCaseCount = 0;\n const bailReached = () =>\n definition.test.bail > 0 && failedCaseCount >= definition.test.bail;\n let shutdownDeadline: number | undefined;\n const beginShutdown = () => {\n shutdownDeadline ??= Date.now() + definition.test.teardownTimeout;\n };\n rootController.signal.addEventListener('abort', beginShutdown, {\n once: true,\n });\n const addFailedCases = (count: number) => {\n failedCaseCount += count;\n if (bailReached()) beginShutdown();\n };\n const teardownTimeoutMs = () =>\n Math.max(\n 0,\n Math.min(\n definition.test.teardownTimeout,\n shutdownDeadline === undefined\n ? Number.POSITIVE_INFINITY\n : shutdownDeadline - Date.now(),\n ),\n );\n let hasInfrastructureError = false;\n const infrastructureErrors: unknown[] = [];\n const recordInfrastructureError = (error: unknown) => {\n const errors =\n error instanceof WorkflowExecutionFailure ? error.errors : [error];\n for (const item of errors)\n if (!infrastructureErrors.includes(item)) infrastructureErrors.push(item);\n hasInfrastructureError = true;\n rootController.abort(error);\n };\n const runInfrastructureCallback = <T>(callback: () => T): T => {\n try {\n return callback();\n } catch (error) {\n recordInfrastructureError(error);\n throw error;\n }\n };\n const stopObservingOperations = observeResourceOperations(\n rootController.signal,\n (event) => {\n try {\n journal.append(event);\n } catch (error) {\n recordInfrastructureError(\n new WorkflowPublicationError('write-result', journal.path, error),\n );\n getDebug('test-runner:operations', { console: true })(\n `Could not persist operation event: ${String(error)}`,\n );\n }\n },\n );\n type PreparedProject = (typeof preparedProjects)[number];\n const announceProject = (prepared: PreparedProject, projectIndex: number) => {\n const { project } = prepared;\n runInfrastructureCallback(() =>\n progress(\n `[project ${projectIndex + 1}/${preparedProjects.length}] ${project.name}`,\n ),\n );\n };\n const buildProjectResult = (\n prepared: PreparedProject,\n cases: readonly TestProjectCaseRunResult[],\n documents: readonly WorkflowDocumentRunResult[],\n lifecycle?: TestExecutionProjectRunResult['lifecycle'],\n ): TestExecutionProjectRunResult => {\n const { project } = prepared;\n const projectFailed =\n prepared.collectionErrors.length > 0 ||\n latestById(cases, (item) => item.caseId).some(\n (item) => item.status !== 'success',\n ) ||\n latestById(documents, (item) => item.documentId).some(\n (item) => item.status === 'failed',\n ) ||\n lifecycle?.status === 'failed';\n return {\n projectId: project.projectId,\n name: project.name,\n ...(prepared.platform ? { platform: prepared.platform } : {}),\n status: projectFailed ? 'failed' : 'success',\n retry: project.retry,\n fileSelection: prepared.fileSelection,\n tagSelection: project.tags,\n sourceCount: prepared.sources.length,\n selectedCaseCount: prepared.selectedCaseCount,\n filteredCaseCount: prepared.filteredCaseCount,\n ...(lifecycle ? { lifecycle } : {}),\n cases,\n plans: prepared.plans,\n documents,\n collectionErrors: prepared.collectionErrors,\n };\n };\n const buildSkippedProjectResult = (\n prepared: PreparedProject,\n projectIndex: number,\n reason: NonNullable<TestProjectCaseRunResult['notRunReason']>,\n ): TestExecutionProjectRunResult => {\n announceProject(prepared, projectIndex);\n return buildProjectResult(prepared, notRunSuite(prepared, reason), []);\n };\n const projectResults: Array<TestExecutionProjectRunResult | undefined> =\n new Array(preparedProjects.length);\n\n try {\n const states = await runPreparedFiles({\n projects: preparedProjects,\n maxConcurrentFiles: effectiveConcurrency,\n maxConcurrentProjects:\n definition.test.maxConcurrentProjects ?? Number.POSITIVE_INFINITY,\n setupTimeoutMs: definition.test.setupTimeout,\n teardownTimeoutMs,\n signal: rootController.signal,\n runDir,\n preflightFailed: plan.preflightScope === 'run' && totalErrors > 0,\n shouldBail: bailReached,\n addFailedCases,\n announceProject,\n onProgress: (prepared, message) =>\n runInfrastructureCallback(() =>\n progress(\n preparedProjects.length > 1 || effectiveConcurrency > 1\n ? `[${prepared.project.name}]${message}`\n : message,\n ),\n ),\n onEvent: (event) =>\n runInfrastructureCallback(() => plan.onEvent?.(event)),\n onProjectEnd: (state) =>\n runInfrastructureCallback(() =>\n plan.onEvent?.({\n type: 'project-end',\n project: buildProjectResult(\n state.prepared,\n state.cases,\n state.documents,\n state.lifecycle,\n ),\n }),\n ),\n onInfrastructureError: recordInfrastructureError,\n });\n states.forEach((state, index) => {\n projectResults[index] = buildProjectResult(\n state.prepared,\n state.cases,\n state.documents,\n state.lifecycle,\n );\n });\n } catch (error) {\n recordInfrastructureError(error);\n } finally {\n stopObservingOperations();\n process.off('SIGINT', sigint);\n process.off('SIGTERM', sigterm);\n }\n\n const completedProjectResults = preparedProjects.map(\n (prepared, projectIndex) => {\n const result = projectResults[projectIndex];\n if (result) return result;\n const reason = prepared.collectionErrors.length\n ? 'project-preflight-failed'\n : rootController.signal.aborted\n ? 'interrupted'\n : bailReached()\n ? 'bail'\n : undefined;\n if (!reason) {\n throw new Error(\n `Project scheduler did not produce a result for \"${prepared.project.name}\".`,\n );\n }\n return buildSkippedProjectResult(prepared, projectIndex, reason);\n },\n );\n\n const summary = summarize(completedProjectResults);\n const failed =\n hasInfrastructureError ||\n rootController.signal.aborted ||\n summary.failed > 0 ||\n summary.notRun > 0 ||\n summary.collectionErrors > 0 ||\n summary.documentFailures > 0 ||\n summary.projectFailures > 0;\n const endedAt = new Date();\n const result: TestProjectRunResult = {\n schemaVersion: 3,\n operationLog: { path: journal.path, snapshotAt: endedAt.toISOString() },\n runId,\n startedAt: startedAt.toISOString(),\n endedAt: endedAt.toISOString(),\n durationMs: Math.max(0, endedAt.getTime() - startedAt.getTime()),\n status: failed ? 'failed' : 'success',\n exitCode: failed ? 1 : 0,\n resultDir,\n summaryPath,\n reportDir,\n summary,\n projects: completedProjectResults,\n cases: completedProjectResults.flatMap((project) => project.cases),\n documents: completedProjectResults.flatMap((project) => project.documents),\n collectionErrors: completedProjectResults.flatMap(\n (project) => project.collectionErrors,\n ),\n ...(hasInfrastructureError\n ? { errors: infrastructureErrors.map(asExecutionError) }\n : {}),\n };\n let completedResult = result;\n let reportIndex: TestRunReportSourceIndex | undefined;\n const publish = async (\n operation: 'write-result' | 'write-report',\n path: string,\n callback: () => unknown | Promise<unknown>,\n ): Promise<boolean> => {\n try {\n await callback();\n return true;\n } catch (error) {\n recordInfrastructureError(\n error instanceof WorkflowPublicationError ||\n error instanceof WorkflowExecutionFailure\n ? error\n : new WorkflowPublicationError(operation, path, error),\n );\n completedResult = {\n ...completedResult,\n status: 'failed',\n exitCode: 1,\n errors: infrastructureErrors.map(asExecutionError),\n };\n return false;\n }\n };\n const writeSummary = () =>\n publish('write-result', summaryPath, () =>\n writeTestProjectRunResult({\n projectRoot,\n ...(configPath ? { configPath } : {}),\n result: completedResult,\n }),\n );\n let extraSources: Awaited<ReturnType<ReportSession['finish']>> = [];\n await publish('write-report', reports.directory, async () => {\n extraSources = await reports.finish();\n });\n const writeReport = () =>\n publish('write-report', reportDir, async () => {\n if (!plan.reportEnabled) return;\n const reportPath = await new TestRunReportAssembler().assembleAsync({\n outputDir: reportDir,\n outputFormat: plan.definition.output.reportFormat,\n reportFileName: `midscene-e2e-${runId}`,\n overwrite: false,\n sources: [\n ...collectTestRunReportSources(completedResult),\n ...extraSources.map((source) => ({ ...source, scopeId: runId })),\n ],\n buildRunnerDump: (index) => {\n reportIndex = index;\n const dump = buildTestRunReportDump(completedResult, index);\n completedResult = { ...completedResult, metrics: dump.metrics };\n const warn = getDebug('test-runner:report-assembler', {\n console: true,\n });\n for (const diagnostic of dump.diagnostics ?? [])\n warn(diagnostic.message);\n return dump;\n },\n });\n completedResult = { ...completedResult, reportPath };\n });\n // Publish each artifact once. The summary includes the report path or its\n // failure. If the summary itself fails, the thrown result remains authoritative;\n // do not rebuild an already-published execution report to backfill that error.\n await writeReport();\n for (const publication of plan.publications)\n await publish(publication.operation, publication.path, async () => {\n await publication.publish(completedResult);\n });\n await publish(\n 'write-result',\n join(dirname(summaryPath), 'result.md'),\n async () => {\n if (!completedResult.metrics) {\n const dump = buildTestRunReportDump(\n completedResult,\n reportIndex ?? {\n sources: [],\n metrics: sumTestRunReportMetrics([]),\n },\n );\n completedResult = { ...completedResult, metrics: dump.metrics };\n }\n const markdownPath = await writeTestResultMarkdown(\n completedResult,\n reportIndex,\n );\n completedResult = { ...completedResult, markdownPath };\n },\n );\n if (completedResult.reportPath && !hasInfrastructureError)\n await publish('write-result', reports.directory, () => reports.prune());\n await writeSummary();\n if (hasInfrastructureError)\n throw new WorkflowExecutionFailure(completedResult, infrastructureErrors);\n return completedResult;\n}\n"],"names":["configuredModelNames","env","globalConfigManager","defaultName","models","Map","intent","name","intents","CliModelUsage","step","trace","sumTestRunReportMetrics","Set","formatTokenCount","value","String","Math","formatModelUsage","metrics","formatTokenUsage","model","stripVTControlCharacters","usage","includeCached","state","field","count","writeJson","path","mkdir","dirname","writeFile","JSON","error","WorkflowPublicationError","writeTestRunPlan","runDir","projects","join","Date","item","toPosix","sep","caseAttemptResultPath","projectId","documentId","result","workflowDocumentResultPath","undefined","collectionErrorPath","sourcePath","id","createHash","writeWorkflowDocumentResult","_documentRunId","persistedResult","writeCaseAttemptResult","attemptId","writeCollectionError","collectionError","relativeToSummary","summaryPath","target","relative","errorJson","sanitizeReportError","writeTestProjectRunResult","options","fact","project","outcome","attempt","document","projectIdFromIndex","index","defineTestProject","definition","defineProjectSetup","defineFileSetup","getDefaultExport","loaded","absolutePath","defaultExport","TypeError","isRecord","Array","rejectUnknownKeys","allowedKeys","label","allowed","unknown","Object","key","isAbsolutePattern","pattern","isAbsolute","validatePatterns","allowEmptyInclude","validateTestFileSelection","include","exclude","validateTagList","tag","validateTagSelection","assertJsonValue","seen","Number","child","deepFreezeJson","validateVariables","validateSetup","validatePositiveInteger","fallback","validateNonNegativeInteger","validateConcurrency","validateFileConcurrency","maxConcurrentFiles","fileSetup","validateExecutionProjects","defaultSetup","defaultFileSetup","globalNodes","test","setup","NodeRegistry","names","candidate","files","localNodes","nodes","node","globalFileLimit","validateTestOptions","hasExplicitProjects","limit","validateOutputPath","validateOutput","validateTestProjectDefinition","resolvedProjects","assertSupportedConfig","extension","canRetryWithCjsLoader","Error","errorCode","SyntaxError","loadTestProject","configPath","resolve","pathToFileURL","tsImport","tsxRequire","fallbackError","message","CONFIG_NAMES","CONFIG_PREFIX","ALWAYS_IGNORED_PATTERNS","DEFAULT_TEST_FILE_SELECTION","discoverResolvedTestFiles","projectRoot","selection","excludedDirectories","root","outputPatterns","directory","withinRoot","literal","match","patterns","globSync","file","a","b","relativeA","relativeB","discoverTestFiles","normalized","discoverTestConfig","candidates","readdirSync","supported","unsupported","asCollectionError","projectName","WorkflowError","WorkflowParseError","matchesTags","tags","filterDocumentCases","cases","filtered","selectProjects","requested","known","prepareProject","defaultTimeoutMs","platform","fileSelection","prerequisiteFile","discoveredFiles","selectedPath","realpathSync","mainFiles","within","occurrences","sources","invocationIndex","collectionErrors","invocations","plans","filteredCaseCount","source","collected","plan","buildTestRunReportPlan","collectWorkflowDocument","process","projectContext","signal","onTeardown","documents","invocation","prerequisiteSource","prerequisiteDocument","total","padDatePart","createTestRunId","date","uuid","randomUUID","timestamp","assertDirectory","existsSync","statSync","resolveRunInput","cwd","searchRoot","testPath","stat","prepareTestRun","startedAt","runId","input","standalonePath","discovery","artifactDir","resolveMidsceneRunDir","runWithMidsceneRunDir","resultDir","reportDir","mkdirSync","hasFormatMismatch","NativeWorkflowFormatError","scopeNodeConsole","ctx","position","scope","runWithConsoleLogScope","teardown","stepPosition","info","formatStep","phase","formatStepResult","indent","symbol","continuation","caseHasFatalError","isFatalDeviceError","isResourceRecoveryError","documentHasFatalError","isSharedResourceFailure","pending","failure","executeDocumentInvocation","sinks","isProjectResourceFailure","documentRetry","attempts","documentSetup","runDocumentAttempts","documentAttemptIndex","execution","runWorkflowDocument","run","collectedCase","WorkflowExecutionFailure","partial","resourceOnly","host","decideRetry","publicationError","owners","cleanupPending","owner","operationPending","cleanupFailed","failed","decision","final","failedCases","runPreparedFiles","states","prepared","nextProject","resourcesUnresolved","occupied","occupiedProjects","cleanupQueue","release","wake","running","stopped","invalid","unresolved","finalizeProject","completed","reason","order","i","finishProject","releaseProject","Promise","waitForScopeOperations","getResourceCleanupCompletion","admit","offset","cleanupOnly","fileResourcesPending","createProjectRuntime","setMaxListeners","getPendingScopeOperations","changed","job","task","settled","admission","trackResourceOperation","createOperationJournal","writeFileSync","event","appendFileSync","asNotRun","summarize","healthCases","documentAttemptByRunId","latestById","health","calculateTestRunHealth","items","notRunSuite","runPreparedTestProject","reports","ReportSession","runWithReportSession","preparedProjects","progress","totalDocuments","totalCases","totalErrors","effectiveConcurrency","journal","rootController","AbortController","handleSignal","sigint","sigterm","failedCaseCount","bailReached","shutdownDeadline","beginShutdown","addFailedCases","teardownTimeoutMs","hasInfrastructureError","infrastructureErrors","recordInfrastructureError","errors","runInfrastructureCallback","callback","stopObservingOperations","observeResourceOperations","getDebug","announceProject","projectIndex","buildProjectResult","lifecycle","projectFailed","buildSkippedProjectResult","projectResults","completedProjectResults","summary","endedAt","asExecutionError","completedResult","reportIndex","publish","operation","writeSummary","extraSources","writeReport","reportPath","TestRunReportAssembler","collectTestRunReportSources","dump","buildTestRunReportDump","warn","diagnostic","publication","markdownPath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pB,wBACjC,MAAMsB,QAAQ,gBAAgB3C,QAAQ,SAAS,EAAE,IAAMA,QAAQ,KAAK;IACtE,MAAM6C;IACN,IAAIxB,wBACF,MAAM,IAAIvF,yBAAyB2G,iBAAiBnB;IACtD,OAAOmB;AACT"}
@@ -0,0 +1,5 @@
1
+ import { defineNode as test_runner_defineNode } from "./793.mjs";
2
+ const defineNode = test_runner_defineNode;
3
+ export { defineNode };
4
+
5
+ //# sourceMappingURL=398.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"398.mjs","sources":["../../src/node/define-node.ts"],"sourcesContent":["import { defineNode as coreDefineNode } from '@midscene/core/internal/test-runner';\nimport type {\n DefineNodeOptions,\n DefineNodeWithSchemaOptions,\n NodeDefinition,\n NodeDefinitionWithSchema,\n NodeInputSchema,\n} from './types';\n\n// A type-only facade: validation and execution still belong to the shared kernel.\ninterface DefineNativeNode {\n <TSchema extends NodeInputSchema, TData = unknown, TContext = unknown>(\n options: DefineNodeWithSchemaOptions<TSchema, TData, TContext>,\n ): NodeDefinitionWithSchema<TSchema, TData, TContext>;\n <TInput = unknown, TData = unknown, TContext = unknown>(\n options: DefineNodeOptions<TInput, TData, TContext>,\n ): NodeDefinition<TInput, TData, TContext>;\n}\nexport const defineNode: DefineNativeNode = coreDefineNode;\n"],"names":["defineNode","coreDefineNode"],"mappings":";AAkBO,MAAMA,aAA+BC"}