csspilot 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -10373,10 +10373,84 @@ var {
10373
10373
  Help
10374
10374
  } = import_index.default;
10375
10375
 
10376
- // src/commands/doctor.ts
10377
- import { existsSync as existsSync2 } from "node:fs";
10378
- import { createRequire } from "node:module";
10379
- import { join as join5 } from "node:path";
10376
+ // src/commands/init/ci-initializer.ts
10377
+ import { access, mkdir, writeFile } from "node:fs/promises";
10378
+ import { join } from "node:path";
10379
+ async function exists(path) {
10380
+ try {
10381
+ await access(path);
10382
+ return true;
10383
+ } catch {
10384
+ return false;
10385
+ }
10386
+ }
10387
+ async function detectCi(root) {
10388
+ const workflow = join(root, ".github", "workflows", "testpilot.yml");
10389
+ return {
10390
+ githubWorkflows: await exists(join(root, ".github", "workflows")),
10391
+ gitlabCi: await exists(join(root, ".gitlab-ci.yml")),
10392
+ hasTestpilotWorkflow: await exists(workflow)
10393
+ };
10394
+ }
10395
+ var CI_TEMPLATE = `# csspilot ci init \u751F\u6210;Git Push -> TestPilot Server \u7684\u6B63\u5F0F\u540C\u6B65\u8FB9\u754C
10396
+ name: TestPilot
10397
+
10398
+ on:
10399
+ push:
10400
+ branches: [main]
10401
+
10402
+ jobs:
10403
+ testpilot:
10404
+ runs-on: ubuntu-latest
10405
+ env:
10406
+ TESTPILOT_SERVER_URL: \${{ secrets.TESTPILOT_SERVER_URL }}
10407
+ steps:
10408
+ - uses: actions/checkout@v4
10409
+
10410
+ - uses: actions/setup-node@v4
10411
+ with:
10412
+ node-version: 22
10413
+
10414
+ - name: Validate cases
10415
+ run: npx -y csspilot@latest validate
10416
+
10417
+ # sync-metadata \u662F Git Push -> Server \u7684\u6B63\u5F0F\u540C\u6B65\u8FB9\u754C;\u672A\u914D\u7F6E Server \u65F6\u8DF3\u8FC7
10418
+ - name: Sync case metadata
10419
+ if: \${{ env.TESTPILOT_SERVER_URL != '' }}
10420
+ run: npx -y csspilot@latest sync-metadata
10421
+
10422
+ # \u9700\u8981\u5728 CI \u91CC\u8DD1\u7528\u4F8B\u65F6\u518D\u542F\u7528(Server \u89E6\u53D1\u6216\u672C\u5730\u89E6\u53D1\u5747\u53EF)
10423
+ # - name: Run cases
10424
+ # run: npx -y csspilot@latest run
10425
+ `;
10426
+ async function initCi(root) {
10427
+ const file2 = join(root, ".github", "workflows", "testpilot.yml");
10428
+ if (await exists(file2)) {
10429
+ return { created: false, file: file2 };
10430
+ }
10431
+ await mkdir(join(root, ".github", "workflows"), { recursive: true });
10432
+ await writeFile(file2, CI_TEMPLATE, "utf8");
10433
+ return { created: true, file: file2 };
10434
+ }
10435
+
10436
+ // src/commands/ci.ts
10437
+ function makeCiCommand() {
10438
+ const ci = new Command("ci").description("CI \u96C6\u6210(\u751F\u6210\u6A21\u677F,\u4E0D\u4FEE\u6539\u5DF2\u6709 CI)");
10439
+ ci.command("init").description("\u751F\u6210 .github/workflows/testpilot.yml(validate + sync-metadata;\u5DF2\u6709\u5219\u8DF3\u8FC7)").action(async () => {
10440
+ const result = await initCi(process.cwd());
10441
+ if (result.created) {
10442
+ console.log(`\u2713 CI \u5DE5\u4F5C\u6D41\u5DF2\u751F\u6210 ${result.file}`);
10443
+ console.log(" Git Push \u540E\u81EA\u52A8\u6267\u884C csspilot validate \u4E0E sync-metadata(\u9700\u914D\u7F6E TESTPILOT_SERVER_URL Secret)");
10444
+ } else {
10445
+ console.log(`\u2713 CI \u5DE5\u4F5C\u6D41\u5DF2\u5B58\u5728 ${result.file}(\u8DF3\u8FC7)`);
10446
+ }
10447
+ });
10448
+ return ci;
10449
+ }
10450
+
10451
+ // src/commands/init/doctor.ts
10452
+ import { existsSync as existsSync6 } from "node:fs";
10453
+ import { join as join21 } from "node:path";
10380
10454
 
10381
10455
  // ../../packages/core/src/errors/index.ts
10382
10456
  var TestPilotError = class extends Error {
@@ -10389,7 +10463,7 @@ var TestPilotError = class extends Error {
10389
10463
  };
10390
10464
 
10391
10465
  // ../../packages/core/src/constants/index.ts
10392
- import { join } from "node:path";
10466
+ import { join as join2 } from "node:path";
10393
10467
  var TESTPILOT_DIR = ".testpilot";
10394
10468
  var RUNS_DIR = `${TESTPILOT_DIR}/artifacts/runs`;
10395
10469
  var RESULT_FILE = "result.json";
@@ -10398,14 +10472,14 @@ var DEFAULT_STEP_TIMEOUT_MS = 15e3;
10398
10472
  var WECHAT_DEVTOOLS_CLI_PATHS = [
10399
10473
  "C:/Program Files (x86)/Tencent/\u5FAE\u4FE1web\u5F00\u53D1\u8005\u5DE5\u5177/cli.bat",
10400
10474
  "C:/Program Files/Tencent/\u5FAE\u4FE1web\u5F00\u53D1\u8005\u5DE5\u5177/cli.bat",
10401
- join(process.env.LOCALAPPDATA ?? ".", "\u5FAE\u4FE1web\u5F00\u53D1\u8005\u5DE5\u5177", "cli.bat"),
10475
+ join2(process.env.LOCALAPPDATA ?? ".", "\u5FAE\u4FE1web\u5F00\u53D1\u8005\u5DE5\u5177", "cli.bat"),
10402
10476
  "/Applications/wechatwebdevtools.app/Contents/MacOS/cli"
10403
10477
  ];
10404
10478
 
10405
10479
  // ../../packages/core/src/config-loader.ts
10406
10480
  var import_yaml = __toESM(require_dist(), 1);
10407
10481
  import { readFile } from "node:fs/promises";
10408
- import { join as join2 } from "node:path";
10482
+ import { join as join3 } from "node:path";
10409
10483
 
10410
10484
  // ../../node_modules/.pnpm/zod@4.6.1/node_modules/zod/v4/classic/external.js
10411
10485
  var external_exports = {};
@@ -15439,7 +15513,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
15439
15513
  var NONE = 0;
15440
15514
  var ASSUMED = 1;
15441
15515
  var PROVEN = 2;
15442
- function isRecursive(inst, stack, resolve3) {
15516
+ function isRecursive(inst, stack, resolve5) {
15443
15517
  const cached2 = recursive.get(inst);
15444
15518
  if (cached2 !== void 0)
15445
15519
  return cached2 ? PROVEN : NONE;
@@ -15449,7 +15523,7 @@ function isRecursive(inst, stack, resolve3) {
15449
15523
  let result = NONE;
15450
15524
  const check2 = (child) => {
15451
15525
  if (result !== PROVEN && child?._zod) {
15452
- const answer = isRecursive(child, stack, resolve3);
15526
+ const answer = isRecursive(child, stack, resolve5);
15453
15527
  if (answer > result)
15454
15528
  result = answer;
15455
15529
  }
@@ -15460,7 +15534,7 @@ function isRecursive(inst, stack, resolve3) {
15460
15534
  const desc = Object.getOwnPropertyDescriptor(sh, key);
15461
15535
  if (spread && !desc.enumerable)
15462
15536
  continue;
15463
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
15537
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve5) : NONE;
15464
15538
  if (child > answer)
15465
15539
  answer = child;
15466
15540
  }
@@ -15527,7 +15601,7 @@ function isRecursive(inst, stack, resolve3) {
15527
15601
  break;
15528
15602
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
15529
15603
  case "lazy": {
15530
- const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
15604
+ const inner = def._cachedInner ?? (resolve5 ? inst._zod.innerType : void 0);
15531
15605
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
15532
15606
  break;
15533
15607
  }
@@ -30080,8 +30154,24 @@ function date4(params) {
30080
30154
  }
30081
30155
 
30082
30156
  // ../../packages/core/src/config-loader.ts
30157
+ var environmentEntrySchema = external_exports.strictObject({ baseUrl: external_exports.string().min(1).optional() }).optional();
30083
30158
  var configSchema = external_exports.strictObject({
30159
+ /** 配置文件版本(csspilot init 生成为 1) */
30160
+ version: external_exports.number().optional(),
30161
+ /** 旧式用例目录字段;与 test.caseDirectory 等价,二选一 */
30084
30162
  casesDir: external_exports.string().min(1).optional(),
30163
+ project: external_exports.strictObject({ name: external_exports.string().min(1).optional() }).optional(),
30164
+ test: external_exports.strictObject({
30165
+ directory: external_exports.string().min(1).optional(),
30166
+ caseDirectory: external_exports.string().min(1).optional()
30167
+ }).optional(),
30168
+ /** 环境配置:default 指定默认环境名,其余键为环境名 -> { baseUrl } */
30169
+ environment: external_exports.record(external_exports.string(), external_exports.union([external_exports.string().min(1), environmentEntrySchema])).optional(),
30170
+ /** 项目声明的执行端(playwright / wechatide);仅作声明,实际可用性以 doctor 检测为准 */
30171
+ adapters: external_exports.array(external_exports.string().min(1)).optional(),
30172
+ workspace: external_exports.strictObject({ default: external_exports.string().min(1).optional() }).optional(),
30173
+ /** TestPilot Control Plane 地址(sync-metadata / init 关联项目时使用) */
30174
+ server: external_exports.strictObject({ baseUrl: external_exports.string().min(1).optional() }).optional(),
30085
30175
  web: external_exports.strictObject({ baseUrl: external_exports.string().min(1).optional() }).optional(),
30086
30176
  miniapp: external_exports.strictObject({
30087
30177
  projectPath: external_exports.string().min(1).optional(),
@@ -30089,7 +30179,7 @@ var configSchema = external_exports.strictObject({
30089
30179
  }).optional()
30090
30180
  });
30091
30181
  async function loadTestpilotConfig(cwd = process.cwd()) {
30092
- const file2 = join2(cwd, "testpilot.yaml");
30182
+ const file2 = join3(cwd, "testpilot.yaml");
30093
30183
  let raw;
30094
30184
  try {
30095
30185
  raw = (0, import_yaml.parse)(await readFile(file2, "utf8"));
@@ -30105,7 +30195,15 @@ async function loadTestpilotConfig(cwd = process.cwd()) {
30105
30195
  throw new Error(`testpilot.yaml \u914D\u7F6E\u4E0D\u5408\u6CD5:${detail}`);
30106
30196
  }
30107
30197
  return {
30108
- casesDir: result.data.casesDir ?? DEFAULT_CASES_DIR,
30198
+ version: result.data.version,
30199
+ // 用例目录:旧字段 casesDir 优先,其次 test.caseDirectory,最后默认值
30200
+ casesDir: result.data.casesDir ?? result.data.test?.caseDirectory ?? DEFAULT_CASES_DIR,
30201
+ testDirectory: result.data.test?.directory,
30202
+ projectName: result.data.project?.name,
30203
+ environment: result.data.environment,
30204
+ adapters: result.data.adapters,
30205
+ workspace: result.data.workspace,
30206
+ server: result.data.server,
30109
30207
  web: result.data.web,
30110
30208
  miniapp: result.data.miniapp
30111
30209
  };
@@ -30114,7 +30212,7 @@ async function loadTestpilotConfig(cwd = process.cwd()) {
30114
30212
  // ../../packages/core/src/wechat-devtools.ts
30115
30213
  import { execFile } from "node:child_process";
30116
30214
  import { existsSync, readdirSync } from "node:fs";
30117
- import { join as join3 } from "node:path";
30215
+ import { join as join4 } from "node:path";
30118
30216
  var CLI_NAMES = ["cli.bat", "cli"];
30119
30217
  var REGISTRY_UNINSTALL_KEYS = [
30120
30218
  "HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
@@ -30130,7 +30228,7 @@ async function findWechatDevToolsCli() {
30130
30228
  if (process.platform !== "win32") return void 0;
30131
30229
  for (const dir of candidateInstallDirs()) {
30132
30230
  for (const name of CLI_NAMES) {
30133
- const cli = join3(dir, name);
30231
+ const cli = join4(dir, name);
30134
30232
  if (existsSync(cli)) return cli;
30135
30233
  }
30136
30234
  }
@@ -30143,19 +30241,19 @@ function candidateInstallDirs() {
30143
30241
  const drive = `${String.fromCharCode(code)}:\\`;
30144
30242
  if (!existsSync(drive)) continue;
30145
30243
  tencentParents.push(
30146
- join3(drive, "Program Files (x86)", "Tencent"),
30147
- join3(drive, "Program Files", "Tencent")
30244
+ join4(drive, "Program Files (x86)", "Tencent"),
30245
+ join4(drive, "Program Files", "Tencent")
30148
30246
  );
30149
30247
  }
30150
30248
  if (process.env.LOCALAPPDATA) {
30151
- tencentParents.push(join3(process.env.LOCALAPPDATA, "Programs"));
30249
+ tencentParents.push(join4(process.env.LOCALAPPDATA, "Programs"));
30152
30250
  }
30153
30251
  for (const parent of tencentParents) {
30154
30252
  if (!existsSync(parent)) continue;
30155
30253
  try {
30156
30254
  for (const entry of readdirSync(parent)) {
30157
30255
  if (/微信web开发者工具|wechatwebdevtools/i.test(entry)) {
30158
- dirs.push(join3(parent, entry));
30256
+ dirs.push(join4(parent, entry));
30159
30257
  }
30160
30258
  }
30161
30259
  } catch {
@@ -30178,7 +30276,7 @@ async function findFromRegistry() {
30178
30276
  const installDir = dirBefore(raw, /微信开发者工具\.exe|卸载微信开发者工具\.exe/i);
30179
30277
  if (!installDir) continue;
30180
30278
  for (const name of CLI_NAMES) {
30181
- const cli = join3(installDir, name);
30279
+ const cli = join4(installDir, name);
30182
30280
  if (existsSync(cli)) return cli;
30183
30281
  }
30184
30282
  }
@@ -30201,185 +30299,12 @@ function execToString(command, args) {
30201
30299
  });
30202
30300
  }
30203
30301
 
30204
- // src/lib/cases.ts
30205
- import { readdir, stat } from "node:fs/promises";
30206
- import { extname, join as join4 } from "node:path";
30207
- var DEFAULT_CASES_DIR2 = "tests/e2e/cases";
30208
- async function collectCaseFiles(paths) {
30209
- const files = [];
30210
- for (const input2 of paths) {
30211
- const info = await stat(input2).catch(() => void 0);
30212
- if (!info) continue;
30213
- if (info.isDirectory()) {
30214
- files.push(...await collectFromDir(input2));
30215
- } else if (isCaseFile(input2)) {
30216
- files.push(input2);
30217
- }
30218
- }
30219
- return [...new Set(files)].sort();
30220
- }
30221
- async function collectFromDir(dir) {
30222
- const entries = await readdir(dir, { withFileTypes: true });
30223
- const found = [];
30224
- for (const entry of entries) {
30225
- const full = join4(dir, entry.name);
30226
- if (entry.isDirectory()) {
30227
- found.push(...await collectFromDir(full));
30228
- } else if (isCaseFile(entry.name)) {
30229
- found.push(full);
30230
- }
30231
- }
30232
- return found;
30233
- }
30234
- function isCaseFile(file2) {
30235
- const ext = extname(file2).toLowerCase();
30236
- return ext === ".yaml" || ext === ".yml";
30237
- }
30238
-
30239
- // src/commands/doctor.ts
30240
- function makeDoctorCommand() {
30241
- return new Command("doctor").description("\u68C0\u67E5\u672C\u5730\u73AF\u5883(Node / Playwright / WeChat DevTools / \u9879\u76EE\u914D\u7F6E)").action(async () => {
30242
- let problems = 0;
30243
- const ok = (label) => console.log(`\u2713 ${label}`);
30244
- const fail = (label, hint) => {
30245
- problems++;
30246
- console.log(`\u2717 ${label}${hint ? `(${hint})` : ""}`);
30247
- };
30248
- console.log("TestPilot Doctor");
30249
- console.log("");
30250
- const nodeMajor = Number(process.versions.node.split(".")[0]);
30251
- if (nodeMajor >= 22) ok(`Node.js ${process.versions.node}`);
30252
- else fail(`Node.js ${process.versions.node}`, "\u9700\u8981 Node.js >= 22");
30253
- ok("TestPilot CLI (0.1.0)");
30254
- if (existsSync2("testpilot.yaml")) ok("testpilot.yaml");
30255
- else fail("testpilot.yaml", "\u8FD0\u884C npx csspilot init \u751F\u6210");
30256
- const caseFiles = await collectCaseFiles([DEFAULT_CASES_DIR2]).catch(() => []);
30257
- if (caseFiles.length > 0) ok(`${DEFAULT_CASES_DIR2} (${caseFiles.length} \u4E2A\u7528\u4F8B)`);
30258
- else fail(DEFAULT_CASES_DIR2, "\u672A\u627E\u5230\u7528\u4F8B");
30259
- if (existsSync2(".ai/skills/testpilot/manifest.yaml")) ok("TestPilot Skill (.ai/skills/testpilot)");
30260
- else fail("TestPilot Skill", "\u8FD0\u884C npx csspilot init \u5B89\u88C5");
30261
- console.log("");
30262
- console.log("Web");
30263
- const playwright = resolvePlaywright();
30264
- if (!playwright) {
30265
- fail("Playwright", "pnpm add -D playwright \u6216 @playwright/test");
30266
- fail("Chromium");
30267
- } else {
30268
- ok(`Playwright (${playwright.version})`);
30269
- if (chromiumInstalled(playwright.module)) ok("Chromium");
30270
- else fail("Chromium", "pnpm exec playwright install chromium");
30271
- }
30272
- console.log("");
30273
- console.log("Mini Program");
30274
- const devtools = await findWechatDevToolsCli();
30275
- if (devtools) ok(`WeChat Developer Tools (${devtools})`);
30276
- else fail("WeChat Developer Tools", "\u672A\u627E\u5230,\u53EF\u8BBE\u7F6E WECHAT_DEVTOOLS_CLI \u6307\u5411 cli \u53EF\u6267\u884C\u6587\u4EF6");
30277
- console.log("");
30278
- console.log(problems === 0 ? "Environment looks good." : `\u53D1\u73B0 ${problems} \u4E2A\u95EE\u9898,\u89C1\u4E0A\u8868\u3002`);
30279
- });
30280
- }
30281
- function resolvePlaywright() {
30282
- const require2 = createRequire(join5(process.cwd(), "package.json"));
30283
- for (const name of ["playwright", "@playwright/test"]) {
30284
- try {
30285
- const module = require2(name);
30286
- const version2 = require2(`${name}/package.json`).version;
30287
- return { module, version: version2 };
30288
- } catch {
30289
- continue;
30290
- }
30291
- }
30292
- return void 0;
30293
- }
30294
- function chromiumInstalled(module) {
30295
- try {
30296
- const path = module.chromium.executablePath();
30297
- return path !== "" && existsSync2(path);
30298
- } catch {
30299
- return false;
30300
- }
30301
- }
30302
-
30303
- // src/commands/init.ts
30304
- import { existsSync as existsSync3 } from "node:fs";
30305
- import { access, cp, mkdir, writeFile } from "node:fs/promises";
30306
- import { dirname, join as join6 } from "node:path";
30307
- import { fileURLToPath } from "node:url";
30308
- var TESTPILOT_YAML_TEMPLATE = `# TestPilot \u9879\u76EE\u914D\u7F6E
30309
- # validate / list / run \u9ED8\u8BA4\u5728\u8FD9\u4E2A\u76EE\u5F55\u67E5\u627E *.yaml \u7528\u4F8B
30310
- casesDir: tests/e2e/cases
30311
-
30312
- # Web \u7AEF:navigate \u76F8\u5BF9 url \u7684\u57FA\u51C6\u5730\u5740
30313
- # web:
30314
- # baseUrl: http://127.0.0.1:8080
30315
-
30316
- # \u5C0F\u7A0B\u5E8F\u7AEF:\u586B\u5165\u5C0F\u7A0B\u5E8F\u9879\u76EE\u76EE\u5F55\u540E\u5373\u53EF\u6267\u884C target: miniapp \u7684\u6B65\u9AA4
30317
- # miniapp:
30318
- # projectPath: path/to/miniprogram
30319
- # cliPath: C:/Program Files (x86)/Tencent/\u5FAE\u4FE1web\u5F00\u53D1\u8005\u5DE5\u5177/cli.bat
30320
- `;
30321
- async function exists(path) {
30322
- try {
30323
- await access(path);
30324
- return true;
30325
- } catch {
30326
- return false;
30327
- }
30328
- }
30329
- function resolveSkillSourceDir() {
30330
- const fromEnv = process.env.TESTPILOT_SKILL_DIR;
30331
- if (fromEnv) return fromEnv;
30332
- const bundled = fileURLToPath(new URL("./skills/testpilot", import.meta.url));
30333
- if (existsSync3(bundled)) return bundled;
30334
- const inRepo = fileURLToPath(new URL("../../../../skills/testpilot", import.meta.url));
30335
- return existsSync3(inRepo) ? inRepo : void 0;
30336
- }
30337
- function makeInitCommand() {
30338
- return new Command("init").description("\u628A TestPilot \u63A5\u5165\u5F53\u524D\u4E1A\u52A1\u9879\u76EE").action(async () => {
30339
- const cwd = process.cwd();
30340
- const skillDest = join6(cwd, ".ai", "skills", "testpilot");
30341
- if (await exists(join6(skillDest, "manifest.yaml"))) {
30342
- console.log("\u2713 Skill \u5B89\u88C5 .ai/skills/testpilot/(\u5DF2\u5B58\u5728,\u8DF3\u8FC7)");
30343
- } else {
30344
- const skillSrc = resolveSkillSourceDir();
30345
- if (!skillSrc) {
30346
- console.error("\u2717 \u65E0\u6CD5\u5B9A\u4F4D TestPilot Skill \u6E90\u76EE\u5F55");
30347
- console.error(" \u53EF\u901A\u8FC7\u73AF\u5883\u53D8\u91CF TESTPILOT_SKILL_DIR \u6307\u5B9A skills/testpilot \u8DEF\u5F84\u540E\u91CD\u8BD5");
30348
- process.exitCode = 1;
30349
- return;
30350
- }
30351
- await mkdir(dirname(skillDest), { recursive: true });
30352
- await cp(skillSrc, skillDest, { recursive: true });
30353
- console.log("\u2713 Skill \u5B89\u88C5 .ai/skills/testpilot/");
30354
- }
30355
- await mkdir(join6(cwd, ".testpilot", "artifacts"), { recursive: true });
30356
- const keep = join6(cwd, ".testpilot", "artifacts", ".gitkeep");
30357
- if (!await exists(keep)) {
30358
- await writeFile(keep, "", "utf8");
30359
- }
30360
- console.log("\u2713 Runtime \u76EE\u5F55 .testpilot/");
30361
- for (const dir of ["tests/e2e/cases", "tests/e2e/fixtures", "tests/e2e/data"]) {
30362
- await mkdir(join6(cwd, dir), { recursive: true });
30363
- }
30364
- console.log("\u2713 \u6D4B\u8BD5\u76EE\u5F55 tests/e2e/{cases,fixtures,data}");
30365
- const configPath = join6(cwd, "testpilot.yaml");
30366
- if (await exists(configPath)) {
30367
- console.log("\u2713 \u9879\u76EE\u914D\u7F6E testpilot.yaml(\u5DF2\u5B58\u5728,\u8DF3\u8FC7)");
30368
- } else {
30369
- await writeFile(configPath, TESTPILOT_YAML_TEMPLATE, "utf8");
30370
- console.log("\u2713 \u9879\u76EE\u914D\u7F6E testpilot.yaml");
30371
- }
30372
- console.log("");
30373
- console.log("\u4E0B\u4E00\u6B65:");
30374
- console.log(" 1. \u8BA9 AI \u9605\u8BFB .ai/skills/testpilot/SKILL.md");
30375
- console.log(" 2. \u5728 tests/e2e/cases/ \u521B\u5EFA Case(\u9075\u5FAA SKILL.md \u4E0E rules/)");
30376
- console.log(" 3. npx csspilot validate");
30377
- console.log(" 4. npx csspilot run");
30378
- });
30379
- }
30302
+ // ../../packages/sdk/src/client.ts
30303
+ import { isAbsolute as isAbsolute3, join as join17 } from "node:path";
30380
30304
 
30381
- // src/commands/list.ts
30382
- import { readFile as readFile2 } from "node:fs/promises";
30305
+ // ../../packages/sdk/src/cases.ts
30306
+ import { mkdir as mkdir3, readFile as readFile3, readdir, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
30307
+ import { dirname, extname, isAbsolute, join as join6, resolve as resolve2 } from "node:path";
30383
30308
 
30384
30309
  // ../../packages/dsl/src/schema/index.ts
30385
30310
  var STEP_TARGETS = ["web", "miniapp"];
@@ -30412,6 +30337,12 @@ var caseSchema = external_exports.strictObject({
30412
30337
  id: external_exports.string().regex(/^[a-z0-9][a-z0-9-]*$/, "id \u9700\u4E3A kebab-case(\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26)"),
30413
30338
  name: external_exports.string().min(1, "name \u4E0D\u80FD\u4E3A\u7A7A"),
30414
30339
  description: external_exports.string().optional(),
30340
+ /** 引用 Test Workspace(多系统环境组合);Case 只表达测试意图,环境由 Workspace 提供 */
30341
+ workspace: external_exports.string().min(1).optional(),
30342
+ /** 引用项目环境(testpilot.yaml environment 段);Case 不写死地址 */
30343
+ environment: external_exports.string().min(1).optional(),
30344
+ /** 引用测试账号标识;凭据由 Environment + Server/CI Secret 管理,禁止写进 Case */
30345
+ accountRef: external_exports.string().min(1).optional(),
30415
30346
  tags: external_exports.array(external_exports.string().min(1)).optional(),
30416
30347
  steps: external_exports.array(stepSchema).min(1, "Case \u81F3\u5C11\u5305\u542B\u4E00\u4E2A step")
30417
30348
  });
@@ -30577,61 +30508,142 @@ function checkVariableRefs(step, at, declared, issues) {
30577
30508
  }
30578
30509
  }
30579
30510
 
30580
- // src/commands/list.ts
30581
- function makeListCommand() {
30582
- return new Command("list").description("\u5217\u51FA\u6D4B\u8BD5\u7528\u4F8B").option("--tag <tag>", "\u6309\u6807\u7B7E\u8FC7\u6EE4").action(async (options) => {
30583
- const tag = options.tag;
30584
- const config2 = await loadTestpilotConfig().catch((err) => {
30585
- console.error(err.message);
30586
- process.exitCode = 1;
30587
- return void 0;
30588
- });
30589
- if (!config2) return;
30590
- const files = await collectCaseFiles([config2.casesDir]);
30591
- if (files.length === 0) {
30592
- console.error(`\u672A\u627E\u5230\u7528\u4F8B\u76EE\u5F55 ${config2.casesDir}`);
30593
- console.error("\u63D0\u793A:\u5148\u8FD0\u884C npx csspilot init \u63A5\u5165 TestPilot");
30594
- process.exitCode = 1;
30595
- return;
30596
- }
30597
- const cases = [];
30598
- const broken = [];
30599
- for (const file2 of files) {
30600
- const source = await readFile2(file2, "utf8");
30601
- const parsed = parseCase(source);
30602
- if (parsed.ok) {
30603
- cases.push({ id: parsed.data.id, file: file2, tags: parsed.data.tags ?? [] });
30604
- } else {
30605
- broken.push({ file: file2, message: parsed.issues[0]?.message ?? "\u89E3\u6790\u5931\u8D25" });
30606
- }
30511
+ // ../../packages/sdk/src/project.ts
30512
+ import { mkdir as mkdir2, readFile as readFile2, stat, writeFile as writeFile2 } from "node:fs/promises";
30513
+ import { join as join5, resolve } from "node:path";
30514
+ function resolveRoot(root) {
30515
+ return resolve(root ?? process.cwd());
30516
+ }
30517
+ async function loadProjectConfig(root) {
30518
+ return loadTestpilotConfig(resolveRoot(root));
30519
+ }
30520
+ async function inspectProject(root) {
30521
+ const dir = resolveRoot(root);
30522
+ const config2 = await loadTestpilotConfig(dir);
30523
+ const casesDir = join5(dir, config2.casesDir);
30524
+ const artifactsDir = join5(dir, TESTPILOT_DIR, "artifacts");
30525
+ const [hasConfig, casesDirExists, skillInstalled] = await Promise.all([
30526
+ exists2(join5(dir, "testpilot.yaml")),
30527
+ exists2(casesDir),
30528
+ exists2(join5(dir, ".agents", "skills", "testpilot"))
30529
+ ]);
30530
+ return {
30531
+ root: dir,
30532
+ hasConfig,
30533
+ config: config2,
30534
+ casesDir,
30535
+ casesDirExists,
30536
+ artifactsDir,
30537
+ runsDir: join5(artifactsDir, "runs"),
30538
+ skillInstalled,
30539
+ targets: config2.miniapp ? ["web", "miniapp"] : ["web"]
30540
+ };
30541
+ }
30542
+ async function exists2(path) {
30543
+ return await stat(path).catch(() => void 0) !== void 0;
30544
+ }
30545
+ var PROJECT_LINK_FILE = join5(TESTPILOT_DIR, "project.json");
30546
+ async function readProjectLink(root) {
30547
+ const file2 = join5(resolveRoot(root), PROJECT_LINK_FILE);
30548
+ try {
30549
+ const raw = JSON.parse(await readFile2(file2, "utf8"));
30550
+ if (!raw.projectId) return void 0;
30551
+ return raw;
30552
+ } catch {
30553
+ return void 0;
30554
+ }
30555
+ }
30556
+ async function writeProjectLink(link, root) {
30557
+ const file2 = join5(resolveRoot(root), PROJECT_LINK_FILE);
30558
+ await mkdir2(join5(file2, ".."), { recursive: true });
30559
+ await writeFile2(file2, `${JSON.stringify(link, null, 2)}
30560
+ `, "utf8");
30561
+ return file2;
30562
+ }
30563
+
30564
+ // ../../packages/sdk/src/cases.ts
30565
+ async function collectCaseFiles(paths) {
30566
+ const files = [];
30567
+ for (const input2 of paths) {
30568
+ const info = await stat2(input2).catch(() => void 0);
30569
+ if (!info) continue;
30570
+ if (info.isDirectory()) {
30571
+ files.push(...await collectFromDir(input2));
30572
+ } else if (isCaseFile(input2)) {
30573
+ files.push(input2);
30607
30574
  }
30608
- const visible = tag ? cases.filter((item) => item.tags.includes(tag)) : cases;
30609
- console.log("TestPilot Cases");
30610
- console.log("");
30611
- for (const item of visible) {
30612
- const tagLabel = item.tags.length > 0 ? ` [${item.tags.join(", ")}]` : "";
30613
- console.log(`\u2713 ${item.id}${tagLabel}`);
30614
- console.log(` ${item.file}`);
30615
- console.log("");
30575
+ }
30576
+ return [...new Set(files)].sort();
30577
+ }
30578
+ async function collectFromDir(dir) {
30579
+ const entries = await readdir(dir, { withFileTypes: true });
30580
+ const found = [];
30581
+ for (const entry of entries) {
30582
+ const full = join6(dir, entry.name);
30583
+ if (entry.isDirectory()) {
30584
+ found.push(...await collectFromDir(full));
30585
+ } else if (isCaseFile(entry.name)) {
30586
+ found.push(full);
30616
30587
  }
30617
- for (const item of broken) {
30618
- console.log(`\u2717 ${item.file}`);
30619
- console.log(` ${item.message}`);
30620
- console.log("");
30588
+ }
30589
+ return found;
30590
+ }
30591
+ function isCaseFile(file2) {
30592
+ const ext = extname(file2).toLowerCase();
30593
+ return ext === ".yaml" || ext === ".yml";
30594
+ }
30595
+ function resolveAgainstRoot(root, file2) {
30596
+ return isAbsolute(file2) ? file2 : resolve2(resolveRoot(root), file2);
30597
+ }
30598
+ async function collectCases(paths, options = {}) {
30599
+ const files = await collectCaseFiles(
30600
+ paths.map((input2) => resolveAgainstRoot(options.root, input2))
30601
+ );
30602
+ const infos = [];
30603
+ for (const file2 of files) {
30604
+ const validation = await validateCaseFile(file2);
30605
+ infos.push({
30606
+ file: file2,
30607
+ valid: validation.ok,
30608
+ case: validation.data,
30609
+ issues: validation.issues
30610
+ });
30611
+ }
30612
+ return infos;
30613
+ }
30614
+ async function readCaseFile(file2, options = {}) {
30615
+ const target = resolveAgainstRoot(options.root, file2);
30616
+ const source = await readFile3(target, "utf8");
30617
+ return { file: target, source, validation: validateCaseSource(source) };
30618
+ }
30619
+ async function validateCaseFile(file2) {
30620
+ const source = await readFile3(file2, "utf8");
30621
+ return validateCaseSource(source);
30622
+ }
30623
+ async function writeCaseFile(file2, source, options = {}) {
30624
+ const target = resolveAgainstRoot(options.root, file2);
30625
+ const validation = validateCaseSource(source);
30626
+ if (!validation.ok) {
30627
+ return { file: target, written: false, validation };
30628
+ }
30629
+ if (!options.overwrite) {
30630
+ const existing = await stat2(target).catch(() => void 0);
30631
+ if (existing) {
30632
+ throw new Error(`\u7528\u4F8B\u6587\u4EF6\u5DF2\u5B58\u5728:${target}(\u8986\u76D6\u9700\u663E\u5F0F overwrite: true)`);
30621
30633
  }
30622
- const brokenNote = broken.length > 0 ? `,${broken.length} \u4E2A\u6587\u4EF6\u89E3\u6790\u5931\u8D25` : "";
30623
- console.log(`\u5171 ${visible.length} \u4E2A\u7528\u4F8B${tag ? `(tag: ${tag})` : ""}${brokenNote}`);
30624
- });
30634
+ }
30635
+ await mkdir3(dirname(target), { recursive: true });
30636
+ await writeFile3(target, source, "utf8");
30637
+ return { file: target, written: true, validation };
30625
30638
  }
30626
30639
 
30627
- // src/commands/report.ts
30628
- import { exec } from "node:child_process";
30629
- import { readFile as readFile3, readdir as readdir2 } from "node:fs/promises";
30630
- import { join as join8 } from "node:path";
30640
+ // ../../packages/sdk/src/reports.ts
30641
+ import { readFile as readFile6 } from "node:fs/promises";
30642
+ import { join as join16 } from "node:path";
30631
30643
 
30632
30644
  // ../../packages/reporter/src/report.ts
30633
- import { writeFile as writeFile2 } from "node:fs/promises";
30634
- import { join as join7, resolve } from "node:path";
30645
+ import { writeFile as writeFile4 } from "node:fs/promises";
30646
+ import { join as join7, resolve as resolve3 } from "node:path";
30635
30647
 
30636
30648
  // ../../packages/reporter/src/summary.ts
30637
30649
  function toSummaryView(summary) {
@@ -30651,12 +30663,12 @@ function toSummaryView(summary) {
30651
30663
 
30652
30664
  // ../../packages/reporter/src/report.ts
30653
30665
  async function writeReports(runDir, summary) {
30654
- const dir = resolve(runDir);
30666
+ const dir = resolve3(runDir);
30655
30667
  const jsonPath = join7(dir, "report.json");
30656
30668
  const htmlPath = join7(dir, "report.html");
30657
30669
  const payload = { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), summary };
30658
- await writeFile2(jsonPath, JSON.stringify(payload, null, 2), "utf8");
30659
- await writeFile2(htmlPath, renderHtml(summary), "utf8");
30670
+ await writeFile4(jsonPath, JSON.stringify(payload, null, 2), "utf8");
30671
+ await writeFile4(htmlPath, renderHtml(summary), "utf8");
30660
30672
  return { json: jsonPath, html: htmlPath };
30661
30673
  }
30662
30674
  function renderHtml(summary) {
@@ -30725,91 +30737,549 @@ function escapeHtml(input2) {
30725
30737
  return input2.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
30726
30738
  }
30727
30739
 
30728
- // src/commands/report.ts
30729
- function makeReportCommand() {
30730
- return new Command("report").description("\u751F\u6210\u6D4B\u8BD5\u62A5\u544A(JSON + HTML)").option("--run <id>", "\u8FD0\u884C\u8BB0\u5F55 ID,\u9ED8\u8BA4\u6700\u8FD1\u4E00\u6B21").option("--open", "\u751F\u6210\u540E\u5728\u6D4F\u89C8\u5668\u6253\u5F00", false).action(async (options) => {
30731
- const runId = options.run ?? await latestRunId();
30732
- if (!runId) {
30733
- console.error(`\u672A\u627E\u5230\u8FD0\u884C\u8BB0\u5F55(${RUNS_DIR} \u4E3A\u7A7A,\u5148\u8FD0\u884C npx csspilot run)`);
30734
- process.exitCode = 1;
30735
- return;
30736
- }
30737
- const runDir = join8(RUNS_DIR, runId);
30738
- let summary;
30739
- try {
30740
- summary = JSON.parse(await readFile3(join8(runDir, RESULT_FILE), "utf8"));
30741
- } catch {
30742
- console.error(`\u8BFB\u53D6\u8FD0\u884C\u7ED3\u679C\u5931\u8D25:${join8(runDir, RESULT_FILE)}`);
30743
- process.exitCode = 1;
30744
- return;
30745
- }
30746
- const written = await writeReports(runDir, summary);
30747
- console.log(`\u2713 report.json ${written.json}`);
30748
- console.log(`\u2713 report.html ${written.html}`);
30749
- if (options.open) await openInBrowser(written.html);
30750
- });
30751
- }
30752
- async function latestRunId() {
30753
- const entries = await readdir2(RUNS_DIR).catch(() => []);
30754
- return entries.sort().at(-1);
30755
- }
30756
- function openInBrowser(file2) {
30757
- const command = process.platform === "win32" ? `start "" "${file2}"` : process.platform === "darwin" ? `open "${file2}"` : `xdg-open "${file2}"`;
30758
- return new Promise((resolvePromise) => {
30759
- exec(command, () => resolvePromise());
30760
- });
30761
- }
30740
+ // ../../packages/sdk/src/runs.ts
30741
+ import { readFile as readFile5, readdir as readdir3 } from "node:fs/promises";
30742
+ import { isAbsolute as isAbsolute2, join as join15 } from "node:path";
30762
30743
 
30763
- // src/commands/run.ts
30764
- import { readFile as readFile5 } from "node:fs/promises";
30765
- import { join as join16 } from "node:path";
30744
+ // ../../packages/execution-engine/src/artifacts/index.ts
30745
+ import { mkdir as mkdir8 } from "node:fs/promises";
30746
+ import { join as join11 } from "node:path";
30766
30747
 
30767
- // ../../packages/adapter-playwright/src/browser.ts
30768
- import { chromium } from "playwright";
30769
- function resolveHeadless(options) {
30770
- if (options.headless !== void 0) return options.headless;
30771
- return process.env.TESTPILOT_HEADLESS !== "false";
30772
- }
30773
- function stepTimeout(options) {
30774
- const fromEnv = Number(process.env.TESTPILOT_STEP_TIMEOUT);
30775
- if (options.timeout !== void 0) return options.timeout;
30776
- return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : DEFAULT_STEP_TIMEOUT_MS;
30777
- }
30778
- async function launchBrowser(options = {}) {
30779
- const browser = await chromium.launch({ headless: resolveHeadless(options) });
30780
- return { browser };
30781
- }
30782
- async function openCaseContext(bundle, options, evidenceTmpDir) {
30783
- const context = await bundle.browser.newContext({
30784
- ...evidenceTmpDir ? { recordVideo: { dir: evidenceTmpDir } } : {}
30785
- });
30786
- context.setDefaultTimeout(stepTimeout(options));
30787
- if (evidenceTmpDir) {
30788
- await context.tracing.start({ screenshots: true, snapshots: true });
30748
+ // ../../packages/evidence/src/log.ts
30749
+ import { appendFile, mkdir as mkdir4 } from "node:fs/promises";
30750
+ import { dirname as dirname2 } from "node:path";
30751
+ var RunLogger = class {
30752
+ constructor(filePath) {
30753
+ this.filePath = filePath;
30789
30754
  }
30790
- const page = await context.newPage();
30791
- return { context, page };
30792
- }
30793
-
30794
- // ../../packages/adapter-playwright/src/page.ts
30795
- import { existsSync as existsSync4 } from "node:fs";
30796
- import { mkdtemp, readFile as readFile4, rm } from "node:fs/promises";
30797
- import { tmpdir } from "node:os";
30798
- import { join as join9 } from "node:path";
30799
- var PlaywrightAdapter = class {
30800
- constructor(bundle, options = {}) {
30801
- this.bundle = bundle;
30802
- this.options = options;
30755
+ info(message) {
30756
+ return this.write("INFO", message);
30803
30757
  }
30804
- target = "web";
30805
- current;
30758
+ warn(message) {
30759
+ return this.write("WARN", message);
30760
+ }
30761
+ error(message) {
30762
+ return this.write("ERROR", message);
30763
+ }
30764
+ async write(level, message) {
30765
+ await mkdir4(dirname2(this.filePath), { recursive: true });
30766
+ const line = `${(/* @__PURE__ */ new Date()).toISOString()} ${level} ${message}
30767
+ `;
30768
+ await appendFile(this.filePath, line, "utf8");
30769
+ }
30770
+ };
30771
+
30772
+ // ../../packages/evidence/src/screenshot.ts
30773
+ import { mkdir as mkdir5, writeFile as writeFile5 } from "node:fs/promises";
30774
+ import { dirname as dirname3, join as join8 } from "node:path";
30775
+ async function saveScreenshot(dir, fileName, data) {
30776
+ const file2 = join8(dir, fileName);
30777
+ await mkdir5(dirname3(file2), { recursive: true });
30778
+ await writeFile5(file2, data);
30779
+ return file2;
30780
+ }
30781
+
30782
+ // ../../packages/evidence/src/trace.ts
30783
+ import { mkdir as mkdir6, writeFile as writeFile6 } from "node:fs/promises";
30784
+ import { dirname as dirname4, join as join9 } from "node:path";
30785
+ async function saveTrace(dir, fileName, data) {
30786
+ const file2 = join9(dir, fileName);
30787
+ await mkdir6(dirname4(file2), { recursive: true });
30788
+ await writeFile6(file2, data);
30789
+ return file2;
30790
+ }
30791
+
30792
+ // ../../packages/evidence/src/video.ts
30793
+ import { mkdir as mkdir7, writeFile as writeFile7 } from "node:fs/promises";
30794
+ import { dirname as dirname5, join as join10 } from "node:path";
30795
+ async function saveVideo(dir, fileName, data) {
30796
+ const file2 = join10(dir, fileName);
30797
+ await mkdir7(dirname5(file2), { recursive: true });
30798
+ await writeFile7(file2, data);
30799
+ return file2;
30800
+ }
30801
+
30802
+ // ../../packages/execution-engine/src/artifacts/index.ts
30803
+ var ArtifactManager = class {
30804
+ constructor(runDir) {
30805
+ this.runDir = runDir;
30806
+ this.screenshotsDir = join11(runDir, "screenshots");
30807
+ this.videosDir = join11(runDir, "videos");
30808
+ this.tracesDir = join11(runDir, "traces");
30809
+ this.logsDir = join11(runDir, "logs");
30810
+ this.logger = new RunLogger(join11(this.logsDir, "run.log"));
30811
+ }
30812
+ screenshotsDir;
30813
+ videosDir;
30814
+ tracesDir;
30815
+ logsDir;
30816
+ logger;
30817
+ async prepare() {
30818
+ await mkdir8(this.screenshotsDir, { recursive: true });
30819
+ await mkdir8(this.logsDir, { recursive: true });
30820
+ }
30821
+ /** 保存步骤截图,返回相对 run 目录的路径(screenshots/xxx.png,统一正斜杠供报告链接使用) */
30822
+ async saveStepScreenshot(fileName, data) {
30823
+ await saveScreenshot(this.screenshotsDir, fileName, data);
30824
+ return `screenshots/${fileName}`;
30825
+ }
30826
+ /** 保存用例录屏,返回相对 run 目录的路径(videos/xxx.webm) */
30827
+ async saveVideo(fileName, data) {
30828
+ await saveVideo(this.videosDir, fileName, data);
30829
+ return `videos/${fileName}`;
30830
+ }
30831
+ /** 保存用例 trace 包,返回相对 run 目录的路径(traces/xxx.zip) */
30832
+ async saveTrace(fileName, data) {
30833
+ await saveTrace(this.tracesDir, fileName, data);
30834
+ return `traces/${fileName}`;
30835
+ }
30836
+ };
30837
+
30838
+ // ../../packages/execution-engine/src/context/index.ts
30839
+ var ExecutionContext = class {
30840
+ variables = /* @__PURE__ */ new Map();
30841
+ set(name, value) {
30842
+ this.variables.set(name, value);
30843
+ }
30844
+ get(name) {
30845
+ return this.variables.get(name);
30846
+ }
30847
+ /** 将字符串中的 ${name} 替换为已提取的变量值;未定义的引用保持原样(校验阶段已拦截) */
30848
+ resolve(template) {
30849
+ return template.replace(
30850
+ /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,
30851
+ (match, name) => this.variables.get(name) ?? match
30852
+ );
30853
+ }
30854
+ };
30855
+
30856
+ // ../../packages/execution-engine/src/lifecycle/index.ts
30857
+ import { mkdir as mkdir9, readdir as readdir2 } from "node:fs/promises";
30858
+ import { join as join12 } from "node:path";
30859
+ function dateStamp(date5 = /* @__PURE__ */ new Date()) {
30860
+ const year = date5.getFullYear();
30861
+ const month = String(date5.getMonth() + 1).padStart(2, "0");
30862
+ const day = String(date5.getDate()).padStart(2, "0");
30863
+ return `${year}${month}${day}`;
30864
+ }
30865
+ async function allocateRunId(runsRoot2) {
30866
+ const stamp = dateStamp();
30867
+ const existing = await readdir2(runsRoot2).catch(() => []);
30868
+ let max = 0;
30869
+ for (const name of existing) {
30870
+ const match = /^(\d{8})-(\d{3})$/.exec(name);
30871
+ if (match && match[1] === stamp) {
30872
+ max = Math.max(max, Number(match[2]));
30873
+ }
30874
+ }
30875
+ return `${stamp}-${String(max + 1).padStart(3, "0")}`;
30876
+ }
30877
+ async function ensureRunDir(runsRoot2, runId) {
30878
+ const runDir = join12(runsRoot2, runId);
30879
+ await mkdir9(runDir, { recursive: true });
30880
+ return runDir;
30881
+ }
30882
+
30883
+ // ../../packages/execution-engine/src/events/index.ts
30884
+ import { appendFile as appendFile2, mkdir as mkdir10 } from "node:fs/promises";
30885
+ import { dirname as dirname6 } from "node:path";
30886
+ var EventBus = class {
30887
+ subscribers = [];
30888
+ subscribe(subscriber) {
30889
+ this.subscribers.push(subscriber);
30890
+ }
30891
+ async emit(event) {
30892
+ for (const subscriber of this.subscribers) {
30893
+ await subscriber(event);
30894
+ }
30895
+ }
30896
+ };
30897
+ function ndjsonSubscriber(filePath) {
30898
+ return async (event) => {
30899
+ await mkdir10(dirname6(filePath), { recursive: true });
30900
+ await appendFile2(filePath, `${JSON.stringify(event)}
30901
+ `, "utf8");
30902
+ };
30903
+ }
30904
+
30905
+ // ../../packages/adapter-core/src/session.ts
30906
+ var AdapterSession = class {
30907
+ constructor(target, factory) {
30908
+ this.target = target;
30909
+ this.factory = factory;
30910
+ }
30911
+ adapter;
30912
+ get opened() {
30913
+ return this.adapter !== void 0;
30914
+ }
30915
+ /** 惰性创建;已创建则复用 */
30916
+ async get() {
30917
+ if (!this.adapter) {
30918
+ this.adapter = await this.factory.create();
30919
+ await this.adapter.launch();
30920
+ }
30921
+ return this.adapter;
30922
+ }
30923
+ async close() {
30924
+ if (this.adapter) {
30925
+ await this.adapter.close().catch(() => void 0);
30926
+ this.adapter = void 0;
30927
+ }
30928
+ }
30929
+ };
30930
+
30931
+ // ../../packages/execution-engine/src/engine/adapter-resolver.ts
30932
+ var AdapterResolver = class {
30933
+ factories = /* @__PURE__ */ new Map();
30934
+ sessions = /* @__PURE__ */ new Map();
30935
+ register(factory) {
30936
+ this.factories.set(factory.target, factory);
30937
+ }
30938
+ /** 取得(或创建)target 的会话 */
30939
+ async session(target) {
30940
+ let session = this.sessions.get(target);
30941
+ if (!session) {
30942
+ const factory = this.factories.get(target);
30943
+ if (!factory) {
30944
+ throw new TestPilotError("ADAPTER_NOT_FOUND", `\u672A\u6CE8\u518C target "${target}" \u7684 adapter,\u8BE5\u7AEF\u6B65\u9AA4\u65E0\u6CD5\u6267\u884C`);
30945
+ }
30946
+ session = new AdapterSession(target, factory);
30947
+ this.sessions.set(target, session);
30948
+ }
30949
+ return session;
30950
+ }
30951
+ async closeAll() {
30952
+ for (const session of this.sessions.values()) {
30953
+ await session.close();
30954
+ }
30955
+ this.sessions.clear();
30956
+ }
30957
+ };
30958
+
30959
+ // ../../packages/execution-engine/src/engine/step-executor.ts
30960
+ async function executeStep(step, index, adapter, context, artifacts, options) {
30961
+ const startedAt = Date.now();
30962
+ const result = {
30963
+ index,
30964
+ target: step.target,
30965
+ action: step.action,
30966
+ status: "passed",
30967
+ durationMs: 0
30968
+ };
30969
+ try {
30970
+ const locator = step.locator ? {
30971
+ text: step.locator.text !== void 0 ? context.resolve(step.locator.text) : void 0,
30972
+ css: step.locator.css !== void 0 ? context.resolve(step.locator.css) : void 0
30973
+ } : void 0;
30974
+ switch (step.action) {
30975
+ case "launch":
30976
+ await adapter.launch();
30977
+ break;
30978
+ case "navigate":
30979
+ await adapter.navigate(context.resolve(step.url ?? ""));
30980
+ break;
30981
+ case "click":
30982
+ await adapter.click(locator);
30983
+ break;
30984
+ case "input":
30985
+ await adapter.input(locator, context.resolve(step.value ?? ""));
30986
+ break;
30987
+ case "select":
30988
+ await adapter.select(locator, context.resolve(step.value ?? ""));
30989
+ break;
30990
+ case "wait":
30991
+ await adapter.wait(locator, step.timeout);
30992
+ break;
30993
+ case "assert":
30994
+ await adapter.assert(locator, context.resolve(step.expected ?? ""));
30995
+ break;
30996
+ case "extract": {
30997
+ const value = await adapter.extract(locator);
30998
+ if (step.variable) {
30999
+ context.set(step.variable, value);
31000
+ result.extracted = { [step.variable]: value };
31001
+ }
31002
+ break;
31003
+ }
31004
+ case "screenshot": {
31005
+ const data = await adapter.screenshot();
31006
+ result.screenshot = await artifacts.saveStepScreenshot(`${options.screenshotName}.png`, data);
31007
+ break;
31008
+ }
31009
+ default: {
31010
+ const exhaustive = step.action;
31011
+ throw new Error(`\u4E0D\u652F\u6301\u7684 action:${String(exhaustive)}`);
31012
+ }
31013
+ }
31014
+ } catch (err) {
31015
+ result.status = "failed";
31016
+ result.error = err instanceof Error ? err.message : String(err);
31017
+ try {
31018
+ const data = await adapter.screenshot();
31019
+ result.screenshot = await artifacts.saveStepScreenshot(`${options.screenshotName}-failed.png`, data);
31020
+ } catch {
31021
+ }
31022
+ }
31023
+ result.durationMs = Date.now() - startedAt;
31024
+ return result;
31025
+ }
31026
+
31027
+ // ../../packages/execution-engine/src/engine/execution-engine.ts
31028
+ var ExecutionEngine = class {
31029
+ async runCase(data, options) {
31030
+ const { runId, file: file2, artifacts, bus, resolver } = options;
31031
+ const startedAt = /* @__PURE__ */ new Date();
31032
+ const context = new ExecutionContext();
31033
+ const steps = [];
31034
+ const evidenceAdapters = /* @__PURE__ */ new Map();
31035
+ let caseError;
31036
+ await bus.emit({ type: "case-started", runId, caseId: data.id, file: file2, ts: startedAt.toISOString() });
31037
+ await artifacts.logger.info(`case ${data.id} started (${file2})`);
31038
+ for (const [index, step] of data.steps.entries()) {
31039
+ await bus.emit({
31040
+ type: "step-started",
31041
+ runId,
31042
+ caseId: data.id,
31043
+ index,
31044
+ target: step.target,
31045
+ action: step.action,
31046
+ ts: (/* @__PURE__ */ new Date()).toISOString()
31047
+ });
31048
+ let result;
31049
+ try {
31050
+ const adapter = await (await resolver.session(step.target)).get();
31051
+ if (adapter.startEvidence && !evidenceAdapters.has(step.target)) {
31052
+ try {
31053
+ await adapter.startEvidence(data.id);
31054
+ evidenceAdapters.set(step.target, adapter);
31055
+ } catch (err) {
31056
+ await artifacts.logger.info(
31057
+ `evidence start failed for ${step.target}: ${err instanceof Error ? err.message : String(err)}`
31058
+ );
31059
+ }
31060
+ }
31061
+ result = await executeStep(step, index, adapter, context, artifacts, {
31062
+ screenshotName: `${data.id}-step-${String(index).padStart(2, "0")}`
31063
+ });
31064
+ } catch (err) {
31065
+ result = {
31066
+ index,
31067
+ target: step.target,
31068
+ action: step.action,
31069
+ status: "failed",
31070
+ durationMs: 0,
31071
+ error: err instanceof Error ? err.message : String(err)
31072
+ };
31073
+ }
31074
+ steps.push(result);
31075
+ await artifacts.logger.info(`step ${index} ${step.action} -> ${result.status}${result.error ? ` - ${result.error}` : ""}`);
31076
+ await bus.emit({
31077
+ type: "step-finished",
31078
+ runId,
31079
+ caseId: data.id,
31080
+ index,
31081
+ target: step.target,
31082
+ action: step.action,
31083
+ status: result.status,
31084
+ durationMs: result.durationMs,
31085
+ error: result.error,
31086
+ ts: (/* @__PURE__ */ new Date()).toISOString()
31087
+ });
31088
+ if (result.status === "failed") {
31089
+ caseError = result.error;
31090
+ for (const [skipIndex, skippedStep] of data.steps.entries()) {
31091
+ if (skipIndex <= index) continue;
31092
+ steps.push({
31093
+ index: skipIndex,
31094
+ target: skippedStep.target,
31095
+ action: skippedStep.action,
31096
+ status: "skipped",
31097
+ durationMs: 0
31098
+ });
31099
+ }
31100
+ break;
31101
+ }
31102
+ }
31103
+ const finishedAt = /* @__PURE__ */ new Date();
31104
+ const status = caseError ? "failed" : "passed";
31105
+ const caseResult = {
31106
+ caseId: data.id,
31107
+ caseName: data.name,
31108
+ file: file2,
31109
+ status,
31110
+ steps,
31111
+ startedAt: startedAt.toISOString(),
31112
+ finishedAt: finishedAt.toISOString(),
31113
+ durationMs: finishedAt.getTime() - startedAt.getTime()
31114
+ };
31115
+ if (caseError) caseResult.error = caseError;
31116
+ for (const [target, adapter] of evidenceAdapters) {
31117
+ if (!adapter.stopEvidence) continue;
31118
+ try {
31119
+ const evidence = await adapter.stopEvidence(data.id);
31120
+ if (evidence.video) {
31121
+ caseResult.video = await artifacts.saveVideo(`${data.id}-${target}.webm`, evidence.video);
31122
+ }
31123
+ if (evidence.trace) {
31124
+ caseResult.trace = await artifacts.saveTrace(`${data.id}-${target}.zip`, evidence.trace);
31125
+ }
31126
+ } catch (err) {
31127
+ await artifacts.logger.info(
31128
+ `evidence stop failed for ${target}: ${err instanceof Error ? err.message : String(err)}`
31129
+ );
31130
+ }
31131
+ }
31132
+ await bus.emit({
31133
+ type: "case-finished",
31134
+ runId,
31135
+ caseId: data.id,
31136
+ status,
31137
+ durationMs: finishedAt.getTime() - startedAt.getTime(),
31138
+ ts: finishedAt.toISOString()
31139
+ });
31140
+ await artifacts.logger.info(`case ${data.id} ${status}`);
31141
+ return caseResult;
31142
+ }
31143
+ };
31144
+
31145
+ // ../../packages/execution-engine/src/engine/result-collector.ts
31146
+ function buildRunSummary(runId, startedAt, cases, options = {}) {
31147
+ const finishedAt = /* @__PURE__ */ new Date();
31148
+ const totals = {
31149
+ cases: cases.length,
31150
+ passed: cases.filter((item) => item.status === "passed").length,
31151
+ failed: cases.filter((item) => item.status === "failed").length,
31152
+ steps: 0,
31153
+ stepsPassed: 0,
31154
+ stepsFailed: 0,
31155
+ stepsSkipped: 0
31156
+ };
31157
+ for (const item of cases) {
31158
+ for (const step of item.steps) {
31159
+ totals.steps++;
31160
+ if (step.status === "passed") totals.stepsPassed++;
31161
+ else if (step.status === "failed") totals.stepsFailed++;
31162
+ else totals.stepsSkipped++;
31163
+ }
31164
+ }
31165
+ return {
31166
+ runId,
31167
+ startedAt: startedAt.toISOString(),
31168
+ finishedAt: finishedAt.toISOString(),
31169
+ durationMs: finishedAt.getTime() - startedAt.getTime(),
31170
+ status: totals.failed > 0 ? "failed" : "passed",
31171
+ ...options.cancelled ? { cancelled: true } : {},
31172
+ cases,
31173
+ totals
31174
+ };
31175
+ }
31176
+
31177
+ // ../../packages/execution-engine/src/engine/test-runner.ts
31178
+ import { writeFile as writeFile8 } from "node:fs/promises";
31179
+ import { join as join13, resolve as resolve4 } from "node:path";
31180
+ var TestRunner = class {
31181
+ resolver;
31182
+ runsRoot;
31183
+ customRunId;
31184
+ extraSubscriber;
31185
+ signal;
31186
+ constructor(options) {
31187
+ this.resolver = options.resolver;
31188
+ this.runsRoot = resolve4(options.runsRoot ?? join13(process.cwd(), ".testpilot", "artifacts", "runs"));
31189
+ this.customRunId = options.runId;
31190
+ this.extraSubscriber = options.onEvent;
31191
+ this.signal = options.signal;
31192
+ }
31193
+ async run(cases) {
31194
+ const startedAt = /* @__PURE__ */ new Date();
31195
+ const runId = this.customRunId ?? await allocateRunId(this.runsRoot);
31196
+ const runDir = await ensureRunDir(this.runsRoot, runId);
31197
+ const artifacts = new ArtifactManager(runDir);
31198
+ await artifacts.prepare();
31199
+ const bus = new EventBus();
31200
+ bus.subscribe(ndjsonSubscriber(join13(runDir, "events.ndjson")));
31201
+ if (this.extraSubscriber) bus.subscribe(this.extraSubscriber);
31202
+ await bus.emit({ type: "run-started", runId, totalCases: cases.length, ts: startedAt.toISOString() });
31203
+ await artifacts.logger.info(`run ${runId} started with ${cases.length} case(s)`);
31204
+ const engine = new ExecutionEngine();
31205
+ const results = [];
31206
+ for (const item of cases) {
31207
+ if (this.signal?.aborted) {
31208
+ await artifacts.logger.info(`run ${runId} cancelled before case ${item.data.id}`);
31209
+ break;
31210
+ }
31211
+ results.push(
31212
+ await engine.runCase(item.data, {
31213
+ runId,
31214
+ file: item.file,
31215
+ artifacts,
31216
+ bus,
31217
+ resolver: this.resolver
31218
+ })
31219
+ );
31220
+ }
31221
+ const cancelled = this.signal?.aborted === true;
31222
+ await this.resolver.closeAll();
31223
+ const summary = buildRunSummary(runId, startedAt, results, { cancelled });
31224
+ await bus.emit({
31225
+ type: "run-finished",
31226
+ runId,
31227
+ status: summary.status,
31228
+ totals: { cases: summary.totals.cases, passed: summary.totals.passed, failed: summary.totals.failed },
31229
+ ts: (/* @__PURE__ */ new Date()).toISOString()
31230
+ });
31231
+ await artifacts.logger.info(`run ${runId} finished: ${summary.status}`);
31232
+ await writeFile8(join13(runDir, RESULT_FILE), JSON.stringify(summary, null, 2), "utf8");
31233
+ return summary;
31234
+ }
31235
+ };
31236
+
31237
+ // ../../packages/adapter-playwright/src/browser.ts
31238
+ import { chromium } from "playwright";
31239
+ function resolveHeadless(options) {
31240
+ if (options.headless !== void 0) return options.headless;
31241
+ return process.env.TESTPILOT_HEADLESS !== "false";
31242
+ }
31243
+ function stepTimeout(options) {
31244
+ const fromEnv = Number(process.env.TESTPILOT_STEP_TIMEOUT);
31245
+ if (options.timeout !== void 0) return options.timeout;
31246
+ return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : DEFAULT_STEP_TIMEOUT_MS;
31247
+ }
31248
+ async function launchBrowser(options = {}) {
31249
+ const browser = await chromium.launch({ headless: resolveHeadless(options) });
31250
+ return { browser };
31251
+ }
31252
+ async function openCaseContext(bundle, options, evidenceTmpDir) {
31253
+ const context = await bundle.browser.newContext({
31254
+ ...evidenceTmpDir ? { recordVideo: { dir: evidenceTmpDir } } : {}
31255
+ });
31256
+ context.setDefaultTimeout(stepTimeout(options));
31257
+ if (evidenceTmpDir) {
31258
+ await context.tracing.start({ screenshots: true, snapshots: true });
31259
+ }
31260
+ const page = await context.newPage();
31261
+ return { context, page };
31262
+ }
31263
+
31264
+ // ../../packages/adapter-playwright/src/page.ts
31265
+ import { existsSync as existsSync2 } from "node:fs";
31266
+ import { mkdtemp, readFile as readFile4, rm } from "node:fs/promises";
31267
+ import { tmpdir } from "node:os";
31268
+ import { join as join14 } from "node:path";
31269
+ var PlaywrightAdapter = class {
31270
+ constructor(bundle, options = {}) {
31271
+ this.bundle = bundle;
31272
+ this.options = options;
31273
+ }
31274
+ target = "web";
31275
+ current;
30806
31276
  /** 浏览器在 create() 时已启动;context/page 按用例惰性创建,launch 保持幂等 */
30807
31277
  async launch() {
30808
31278
  }
30809
31279
  /** 开始用例级取证:为本用例创建独立 context(录屏 + trace) */
30810
31280
  async startEvidence(_caseId) {
30811
31281
  await this.closeContextQuietly();
30812
- const evidenceTmpDir = await mkdtemp(join9(tmpdir(), "testpilot-pw-"));
31282
+ const evidenceTmpDir = await mkdtemp(join14(tmpdir(), "testpilot-pw-"));
30813
31283
  this.current = {
30814
31284
  ...await openCaseContext(this.bundle, this.options, evidenceTmpDir),
30815
31285
  evidenceTmpDir
@@ -30820,12 +31290,12 @@ var PlaywrightAdapter = class {
30820
31290
  if (!this.current) return {};
30821
31291
  const { context, page, evidenceTmpDir } = this.current;
30822
31292
  this.current = void 0;
30823
- const traceZipPath = join9(evidenceTmpDir ?? tmpdir(), "trace.zip");
31293
+ const traceZipPath = join14(evidenceTmpDir ?? tmpdir(), "trace.zip");
30824
31294
  await context.tracing.stop({ path: traceZipPath }).catch(() => void 0);
30825
31295
  const recordedVideoPath = await page.video()?.path().catch(() => void 0);
30826
31296
  await context.close().catch(() => void 0);
30827
- const video = recordedVideoPath && existsSync4(recordedVideoPath) ? await readFile4(recordedVideoPath) : void 0;
30828
- const trace = evidenceTmpDir && existsSync4(traceZipPath) ? await readFile4(traceZipPath) : void 0;
31297
+ const video = recordedVideoPath && existsSync2(recordedVideoPath) ? await readFile4(recordedVideoPath) : void 0;
31298
+ const trace = evidenceTmpDir && existsSync2(traceZipPath) ? await readFile4(traceZipPath) : void 0;
30829
31299
  if (evidenceTmpDir) await rm(evidenceTmpDir, { recursive: true, force: true }).catch(() => void 0);
30830
31300
  return { video, trace };
30831
31301
  }
@@ -30929,7 +31399,7 @@ var automatorLauncher = {
30929
31399
  }
30930
31400
  };
30931
31401
  function delay(ms) {
30932
- return new Promise((resolve3) => setTimeout(resolve3, ms));
31402
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
30933
31403
  }
30934
31404
  async function connectWithRetry(wsEndpoint, timeoutMs) {
30935
31405
  const startedAt = Date.now();
@@ -31110,11 +31580,11 @@ var MiniAppAdapter = class {
31110
31580
  };
31111
31581
 
31112
31582
  // ../../packages/adapter-wechatide/src/project.ts
31113
- import { existsSync as existsSync5 } from "node:fs";
31583
+ import { existsSync as existsSync3 } from "node:fs";
31114
31584
  async function resolveMiniappConfig(input2) {
31115
31585
  const projectPath = input2.projectPath ?? process.env.TESTPILOT_MINIPROGRAM_PROJECT_PATH;
31116
31586
  if (!projectPath) return void 0;
31117
- if (!existsSync5(projectPath)) {
31587
+ if (!existsSync3(projectPath)) {
31118
31588
  throw new Error(`\u5C0F\u7A0B\u5E8F\u9879\u76EE\u8DEF\u5F84\u4E0D\u5B58\u5728:${projectPath}`);
31119
31589
  }
31120
31590
  const cliPath = input2.cliPath ?? process.env.WECHAT_DEVTOOLS_CLI ?? await findWechatDevToolsCli();
@@ -31138,564 +31608,860 @@ function wechatideAdapterFactory(input2 = {}) {
31138
31608
  }
31139
31609
  return new MiniAppAdapter(config2);
31140
31610
  }
31141
- };
31142
- }
31143
-
31144
- // ../../packages/execution-engine/src/artifacts/index.ts
31145
- import { mkdir as mkdir6 } from "node:fs/promises";
31146
- import { join as join13 } from "node:path";
31147
-
31148
- // ../../packages/evidence/src/log.ts
31149
- import { appendFile, mkdir as mkdir2 } from "node:fs/promises";
31150
- import { dirname as dirname2 } from "node:path";
31151
- var RunLogger = class {
31152
- constructor(filePath) {
31153
- this.filePath = filePath;
31154
- }
31155
- info(message) {
31156
- return this.write("INFO", message);
31157
- }
31158
- warn(message) {
31159
- return this.write("WARN", message);
31160
- }
31161
- error(message) {
31162
- return this.write("ERROR", message);
31163
- }
31164
- async write(level, message) {
31165
- await mkdir2(dirname2(this.filePath), { recursive: true });
31166
- const line = `${(/* @__PURE__ */ new Date()).toISOString()} ${level} ${message}
31167
- `;
31168
- await appendFile(this.filePath, line, "utf8");
31169
- }
31170
- };
31171
-
31172
- // ../../packages/evidence/src/screenshot.ts
31173
- import { mkdir as mkdir3, writeFile as writeFile3 } from "node:fs/promises";
31174
- import { dirname as dirname3, join as join10 } from "node:path";
31175
- async function saveScreenshot(dir, fileName, data) {
31176
- const file2 = join10(dir, fileName);
31177
- await mkdir3(dirname3(file2), { recursive: true });
31178
- await writeFile3(file2, data);
31179
- return file2;
31180
- }
31181
-
31182
- // ../../packages/evidence/src/trace.ts
31183
- import { mkdir as mkdir4, writeFile as writeFile4 } from "node:fs/promises";
31184
- import { dirname as dirname4, join as join11 } from "node:path";
31185
- async function saveTrace(dir, fileName, data) {
31186
- const file2 = join11(dir, fileName);
31187
- await mkdir4(dirname4(file2), { recursive: true });
31188
- await writeFile4(file2, data);
31189
- return file2;
31190
- }
31191
-
31192
- // ../../packages/evidence/src/video.ts
31193
- import { mkdir as mkdir5, writeFile as writeFile5 } from "node:fs/promises";
31194
- import { dirname as dirname5, join as join12 } from "node:path";
31195
- async function saveVideo(dir, fileName, data) {
31196
- const file2 = join12(dir, fileName);
31197
- await mkdir5(dirname5(file2), { recursive: true });
31198
- await writeFile5(file2, data);
31199
- return file2;
31200
- }
31201
-
31202
- // ../../packages/execution-engine/src/artifacts/index.ts
31203
- var ArtifactManager = class {
31204
- constructor(runDir) {
31205
- this.runDir = runDir;
31206
- this.screenshotsDir = join13(runDir, "screenshots");
31207
- this.videosDir = join13(runDir, "videos");
31208
- this.tracesDir = join13(runDir, "traces");
31209
- this.logsDir = join13(runDir, "logs");
31210
- this.logger = new RunLogger(join13(this.logsDir, "run.log"));
31211
- }
31212
- screenshotsDir;
31213
- videosDir;
31214
- tracesDir;
31215
- logsDir;
31216
- logger;
31217
- async prepare() {
31218
- await mkdir6(this.screenshotsDir, { recursive: true });
31219
- await mkdir6(this.logsDir, { recursive: true });
31220
- }
31221
- /** 保存步骤截图,返回相对 run 目录的路径(screenshots/xxx.png,统一正斜杠供报告链接使用) */
31222
- async saveStepScreenshot(fileName, data) {
31223
- await saveScreenshot(this.screenshotsDir, fileName, data);
31224
- return `screenshots/${fileName}`;
31225
- }
31226
- /** 保存用例录屏,返回相对 run 目录的路径(videos/xxx.webm) */
31227
- async saveVideo(fileName, data) {
31228
- await saveVideo(this.videosDir, fileName, data);
31229
- return `videos/${fileName}`;
31230
- }
31231
- /** 保存用例 trace 包,返回相对 run 目录的路径(traces/xxx.zip) */
31232
- async saveTrace(fileName, data) {
31233
- await saveTrace(this.tracesDir, fileName, data);
31234
- return `traces/${fileName}`;
31235
- }
31236
- };
31237
-
31238
- // ../../packages/execution-engine/src/context/index.ts
31239
- var ExecutionContext = class {
31240
- variables = /* @__PURE__ */ new Map();
31241
- set(name, value) {
31242
- this.variables.set(name, value);
31243
- }
31244
- get(name) {
31245
- return this.variables.get(name);
31246
- }
31247
- /** 将字符串中的 ${name} 替换为已提取的变量值;未定义的引用保持原样(校验阶段已拦截) */
31248
- resolve(template) {
31249
- return template.replace(
31250
- /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,
31251
- (match, name) => this.variables.get(name) ?? match
31252
- );
31253
- }
31254
- };
31255
-
31256
- // ../../packages/execution-engine/src/lifecycle/index.ts
31257
- import { mkdir as mkdir7, readdir as readdir3 } from "node:fs/promises";
31258
- import { join as join14 } from "node:path";
31259
- function dateStamp(date5 = /* @__PURE__ */ new Date()) {
31260
- const year = date5.getFullYear();
31261
- const month = String(date5.getMonth() + 1).padStart(2, "0");
31262
- const day = String(date5.getDate()).padStart(2, "0");
31263
- return `${year}${month}${day}`;
31264
- }
31265
- async function allocateRunId(runsRoot) {
31266
- const stamp = dateStamp();
31267
- const existing = await readdir3(runsRoot).catch(() => []);
31268
- let max = 0;
31269
- for (const name of existing) {
31270
- const match = /^(\d{8})-(\d{3})$/.exec(name);
31271
- if (match && match[1] === stamp) {
31272
- max = Math.max(max, Number(match[2]));
31273
- }
31274
- }
31275
- return `${stamp}-${String(max + 1).padStart(3, "0")}`;
31276
- }
31277
- async function ensureRunDir(runsRoot, runId) {
31278
- const runDir = join14(runsRoot, runId);
31279
- await mkdir7(runDir, { recursive: true });
31280
- return runDir;
31611
+ };
31281
31612
  }
31282
31613
 
31283
- // ../../packages/execution-engine/src/events/index.ts
31284
- import { appendFile as appendFile2, mkdir as mkdir8 } from "node:fs/promises";
31285
- import { dirname as dirname6 } from "node:path";
31286
- var EventBus = class {
31287
- subscribers = [];
31288
- subscribe(subscriber) {
31289
- this.subscribers.push(subscriber);
31290
- }
31291
- async emit(event) {
31292
- for (const subscriber of this.subscribers) {
31293
- await subscriber(event);
31294
- }
31614
+ // ../../packages/sdk/src/runs.ts
31615
+ var RunError = class extends Error {
31616
+ code;
31617
+ constructor(code, message) {
31618
+ super(message);
31619
+ this.name = "RunError";
31620
+ this.code = code;
31295
31621
  }
31296
31622
  };
31297
- function ndjsonSubscriber(filePath) {
31298
- return async (event) => {
31299
- await mkdir8(dirname6(filePath), { recursive: true });
31300
- await appendFile2(filePath, `${JSON.stringify(event)}
31301
- `, "utf8");
31302
- };
31623
+ function createDefaultAdapters(config2) {
31624
+ return [
31625
+ playwrightAdapterFactory({ baseUrl: config2.web?.baseUrl }),
31626
+ wechatideAdapterFactory({
31627
+ projectPath: config2.miniapp?.projectPath,
31628
+ cliPath: config2.miniapp?.cliPath
31629
+ })
31630
+ ];
31631
+ }
31632
+ async function runCases(options = {}) {
31633
+ const root = resolveRoot(options.root);
31634
+ const config2 = await loadProjectConfig(root);
31635
+ const inputs = options.paths && options.paths.length > 0 ? options.paths.map((input2) => isAbsolute2(input2) ? input2 : join15(root, input2)) : [join15(root, config2.casesDir)];
31636
+ const cases = await collectCases(inputs, { root });
31637
+ if (cases.length === 0) {
31638
+ throw new RunError("ENO_CASES", `\u672A\u627E\u5230\u7528\u4F8B\u6587\u4EF6(\u67E5\u627E:${inputs.join(", ")})`);
31639
+ }
31640
+ const invalid = cases.filter((item) => !item.valid);
31641
+ const runnable = cases.filter(
31642
+ (item) => item.valid && item.case && (!options.tag || (item.case.tags ?? []).includes(options.tag))
31643
+ );
31644
+ const tagFiltered = cases.length - invalid.length - runnable.length;
31645
+ if (runnable.length === 0) {
31646
+ throw new RunError(
31647
+ "EINVALID_CASES",
31648
+ invalid.length > 0 ? "\u6240\u6709\u7528\u4F8B\u6821\u9A8C\u5931\u8D25,\u65E0\u53EF\u6267\u884C\u7528\u4F8B" : "\u6CA1\u6709\u5339\u914D\u7684\u7528\u4F8B"
31649
+ );
31650
+ }
31651
+ const factories = options.adapters ?? createDefaultAdapters(config2);
31652
+ const resolver = new AdapterResolver();
31653
+ for (const factory of factories) resolver.register(factory);
31654
+ const runner = new TestRunner({
31655
+ resolver,
31656
+ runsRoot: join15(root, RUNS_DIR),
31657
+ runId: options.runId,
31658
+ onEvent: options.onEvent,
31659
+ signal: options.signal
31660
+ });
31661
+ const summary = await runner.run(
31662
+ runnable.map((item) => ({ data: item.case, file: item.file }))
31663
+ );
31664
+ return { summary, invalid, tagFiltered };
31665
+ }
31666
+ function runsRoot(root) {
31667
+ return join15(resolveRoot(root), RUNS_DIR);
31668
+ }
31669
+ async function listRuns(options = {}) {
31670
+ const base = runsRoot(options.root);
31671
+ const entries = await readdir3(base).catch(() => []);
31672
+ const metas = [];
31673
+ for (const entry of entries.filter((name) => /^\d{8}-\d{3}$/.test(name)).sort().reverse()) {
31674
+ metas.push({ ...await readRunMeta(base, entry), runId: entry, dir: join15(base, entry) });
31675
+ }
31676
+ return metas;
31677
+ }
31678
+ async function latestRunId(options = {}) {
31679
+ const runs = await listRuns(options);
31680
+ return runs[0]?.runId;
31681
+ }
31682
+ async function getRun(runId, options = {}) {
31683
+ const base = runsRoot(options.root);
31684
+ const file2 = join15(base, runId, RESULT_FILE);
31685
+ try {
31686
+ return JSON.parse(await readFile5(file2, "utf8"));
31687
+ } catch {
31688
+ throw new RunError("ENO_CASES", `\u8BFB\u53D6\u8FD0\u884C\u7ED3\u679C\u5931\u8D25:${file2}(\u8FD0\u884C\u672A\u5B8C\u6210\u6216 runId \u4E0D\u5B58\u5728)`);
31689
+ }
31690
+ }
31691
+ async function getRunEvents(runId, options = {}) {
31692
+ const file2 = join15(runsRoot(options.root), runId, "events.ndjson");
31693
+ const source = await readFile5(file2, "utf8").catch(() => "");
31694
+ return source.split("\n").filter((line) => line.trim().length > 0).map((line) => JSON.parse(line));
31695
+ }
31696
+ async function readRunMeta(base, runId) {
31697
+ try {
31698
+ const summary = JSON.parse(
31699
+ await readFile5(join15(base, runId, RESULT_FILE), "utf8")
31700
+ );
31701
+ return {
31702
+ status: summary.status,
31703
+ cancelled: summary.cancelled,
31704
+ startedAt: summary.startedAt,
31705
+ finishedAt: summary.finishedAt,
31706
+ durationMs: summary.durationMs,
31707
+ totals: summary.totals
31708
+ };
31709
+ } catch {
31710
+ return { status: "unknown" };
31711
+ }
31303
31712
  }
31304
31713
 
31305
- // ../../packages/execution-engine/src/scheduler/index.ts
31306
- async function runSequential(items, handler) {
31307
- const results = [];
31308
- for (const [index, item] of items.entries()) {
31309
- results.push(await handler(item, index));
31714
+ // ../../packages/sdk/src/reports.ts
31715
+ async function generateReport(runId, options = {}) {
31716
+ const id = runId ?? await latestRunId(options);
31717
+ if (!id) {
31718
+ throw new Error("\u672A\u627E\u5230\u8FD0\u884C\u8BB0\u5F55(\u5148\u8FD0\u884C\u4E00\u6B21\u7528\u4F8B)");
31719
+ }
31720
+ const runDir = join16(resolveRoot(options.root), RUNS_DIR, id);
31721
+ let summary;
31722
+ try {
31723
+ summary = JSON.parse(await readFile6(join16(runDir, "result.json"), "utf8"));
31724
+ } catch {
31725
+ throw new Error(`\u8BFB\u53D6\u8FD0\u884C\u7ED3\u679C\u5931\u8D25:${join16(runDir, "result.json")}(\u8FD0\u884C\u672A\u5B8C\u6210\u6216 runId \u4E0D\u5B58\u5728)`);
31310
31726
  }
31311
- return results;
31727
+ const written = await writeReports(runDir, summary);
31728
+ return { runId: id, json: written.json, html: written.html };
31729
+ }
31730
+ async function readReport(runId, options = {}) {
31731
+ const file2 = join16(resolveRoot(options.root), RUNS_DIR, runId, "report.json");
31732
+ const source = await readFile6(file2, "utf8").catch(() => void 0);
31733
+ return source ? JSON.parse(source) : void 0;
31312
31734
  }
31313
31735
 
31314
- // ../../packages/adapter-core/src/session.ts
31315
- var AdapterSession = class {
31316
- constructor(target, factory) {
31317
- this.target = target;
31318
- this.factory = factory;
31736
+ // ../../packages/sdk/src/client.ts
31737
+ function resolveInput(root, input2) {
31738
+ return isAbsolute3(input2) ? input2 : join17(root, input2);
31739
+ }
31740
+ var TestPilotClient = class {
31741
+ /** 业务项目根目录(绝对路径) */
31742
+ root;
31743
+ constructor(options = {}) {
31744
+ this.root = resolveRoot(options.root);
31745
+ }
31746
+ // ---- project ----
31747
+ /** 读取项目配置(testpilot.yaml 不存在时返回默认配置) */
31748
+ getConfig() {
31749
+ return loadProjectConfig(this.root);
31750
+ }
31751
+ /** 项目自检:目录结构 / 配置 / Skill 安装状态 / 可用执行端 */
31752
+ inspect() {
31753
+ return inspectProject(this.root);
31754
+ }
31755
+ /** 读取本地项目与 Server Project 的关联(.testpilot/project.json) */
31756
+ getProjectLink() {
31757
+ return readProjectLink(this.root);
31758
+ }
31759
+ /** 写入本地项目与 Server Project 的关联 */
31760
+ linkProject(link) {
31761
+ return writeProjectLink(link, this.root);
31762
+ }
31763
+ // ---- cases ----
31764
+ /** 收集并校验用例;paths 相对本项目根目录,默认按配置的 casesDir */
31765
+ async listCases(paths, tag) {
31766
+ const config2 = await this.getConfig();
31767
+ const inputs = paths && paths.length > 0 ? paths : [config2.casesDir];
31768
+ const infos = await collectCases(inputs.map((input2) => resolveInput(this.root, input2)), {
31769
+ root: this.root
31770
+ });
31771
+ return tag ? infos.filter((item) => item.case?.tags?.includes(tag)) : infos;
31319
31772
  }
31320
- adapter;
31321
- get opened() {
31322
- return this.adapter !== void 0;
31773
+ /** 读取单个用例:source 原文 + 校验结果 */
31774
+ readCase(file2) {
31775
+ return readCaseFile(file2, { root: this.root });
31323
31776
  }
31324
- /** 惰性创建;已创建则复用 */
31325
- async get() {
31326
- if (!this.adapter) {
31327
- this.adapter = await this.factory.create();
31328
- await this.adapter.launch();
31329
- }
31330
- return this.adapter;
31777
+ /** 写入用例(供 Agent 的 create_case 工具使用):先校验后落盘 */
31778
+ writeCase(file2, source, options = {}) {
31779
+ return writeCaseFile(file2, source, { root: this.root, ...options });
31331
31780
  }
31332
- async close() {
31333
- if (this.adapter) {
31334
- await this.adapter.close().catch(() => void 0);
31335
- this.adapter = void 0;
31336
- }
31781
+ // ---- runs ----
31782
+ /** 执行一次运行 */
31783
+ runCases(options = {}) {
31784
+ return runCases({ ...options, root: this.root });
31337
31785
  }
31338
- };
31339
-
31340
- // ../../packages/execution-engine/src/engine/adapter-resolver.ts
31341
- var AdapterResolver = class {
31342
- factories = /* @__PURE__ */ new Map();
31343
- sessions = /* @__PURE__ */ new Map();
31344
- register(factory) {
31345
- this.factories.set(factory.target, factory);
31786
+ /** 历史运行列表(最近的在前) */
31787
+ listRuns() {
31788
+ return listRuns({ root: this.root });
31346
31789
  }
31347
- /** 取得(或创建)target 的会话 */
31348
- async session(target) {
31349
- let session = this.sessions.get(target);
31350
- if (!session) {
31351
- const factory = this.factories.get(target);
31352
- if (!factory) {
31353
- throw new TestPilotError("ADAPTER_NOT_FOUND", `\u672A\u6CE8\u518C target "${target}" \u7684 adapter,\u8BE5\u7AEF\u6B65\u9AA4\u65E0\u6CD5\u6267\u884C`);
31354
- }
31355
- session = new AdapterSession(target, factory);
31356
- this.sessions.set(target, session);
31357
- }
31358
- return session;
31790
+ /** 读取一次运行的汇总结果(result.json) */
31791
+ getRun(runId) {
31792
+ return getRun(runId, { root: this.root });
31359
31793
  }
31360
- async closeAll() {
31361
- for (const session of this.sessions.values()) {
31362
- await session.close();
31363
- }
31364
- this.sessions.clear();
31794
+ /** 读取一次运行的完整事件流(events.ndjson) */
31795
+ getRunEvents(runId) {
31796
+ return getRunEvents(runId, { root: this.root });
31797
+ }
31798
+ // ---- reports ----
31799
+ /** 生成报告(默认最近一次运行) */
31800
+ generateReport(runId) {
31801
+ return generateReport(runId, { root: this.root });
31802
+ }
31803
+ /** 读取已生成的报告 */
31804
+ readReport(runId) {
31805
+ return readReport(runId, { root: this.root });
31365
31806
  }
31366
31807
  };
31367
31808
 
31368
- // ../../packages/execution-engine/src/engine/step-executor.ts
31369
- async function executeStep(step, index, adapter, context, artifacts, options) {
31370
- const startedAt = Date.now();
31371
- const result = {
31372
- index,
31373
- target: step.target,
31374
- action: step.action,
31375
- status: "passed",
31376
- durationMs: 0
31377
- };
31378
- try {
31379
- const locator = step.locator ? {
31380
- text: step.locator.text !== void 0 ? context.resolve(step.locator.text) : void 0,
31381
- css: step.locator.css !== void 0 ? context.resolve(step.locator.css) : void 0
31382
- } : void 0;
31383
- switch (step.action) {
31384
- case "launch":
31385
- await adapter.launch();
31386
- break;
31387
- case "navigate":
31388
- await adapter.navigate(context.resolve(step.url ?? ""));
31389
- break;
31390
- case "click":
31391
- await adapter.click(locator);
31392
- break;
31393
- case "input":
31394
- await adapter.input(locator, context.resolve(step.value ?? ""));
31395
- break;
31396
- case "select":
31397
- await adapter.select(locator, context.resolve(step.value ?? ""));
31398
- break;
31399
- case "wait":
31400
- await adapter.wait(locator, step.timeout);
31401
- break;
31402
- case "assert":
31403
- await adapter.assert(locator, context.resolve(step.expected ?? ""));
31404
- break;
31405
- case "extract": {
31406
- const value = await adapter.extract(locator);
31407
- if (step.variable) {
31408
- context.set(step.variable, value);
31409
- result.extracted = { [step.variable]: value };
31410
- }
31411
- break;
31412
- }
31413
- case "screenshot": {
31414
- const data = await adapter.screenshot();
31415
- result.screenshot = await artifacts.saveStepScreenshot(`${options.screenshotName}.png`, data);
31416
- break;
31417
- }
31418
- default: {
31419
- const exhaustive = step.action;
31420
- throw new Error(`\u4E0D\u652F\u6301\u7684 action:${String(exhaustive)}`);
31421
- }
31809
+ // src/commands/init/adapter-detector.ts
31810
+ import { existsSync as existsSync4, readFileSync } from "node:fs";
31811
+ import { join as join18 } from "node:path";
31812
+ async function detectAdapters(root, projectType) {
31813
+ const required2 = projectType === "hybrid" ? ["playwright", "wechatide"] : projectType === "wechat-miniapp" ? ["wechatide"] : projectType === "web" ? ["playwright"] : [];
31814
+ const pkg = readPackageJsonDeps(root);
31815
+ const hasPlaywrightDep = pkg !== void 0 && ("playwright" in pkg || "@playwright/test" in pkg);
31816
+ const playwrightInstalled = hasPlaywrightDep || existsSync4(join18(root, "node_modules", "playwright"));
31817
+ const devtoolsCli = await findWechatDevToolsCli().catch(() => void 0);
31818
+ return [
31819
+ {
31820
+ id: "playwright",
31821
+ available: playwrightInstalled,
31822
+ detail: playwrightInstalled ? pkg?.["playwright"] ?? pkg?.["@playwright/test"] ?? "\u5DF2\u5B89\u88C5" : "\u672A\u68C0\u6D4B\u5230(pnpm add -D playwright)",
31823
+ required: required2.includes("playwright")
31824
+ },
31825
+ {
31826
+ id: "wechatide",
31827
+ available: devtoolsCli !== void 0,
31828
+ detail: devtoolsCli ?? "\u672A\u627E\u5230\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177(\u53EF\u8BBE\u7F6E WECHAT_DEVTOOLS_CLI \u6307\u5411 cli \u53EF\u6267\u884C\u6587\u4EF6)",
31829
+ required: required2.includes("wechatide")
31422
31830
  }
31423
- } catch (err) {
31424
- result.status = "failed";
31425
- result.error = err instanceof Error ? err.message : String(err);
31831
+ ];
31832
+ }
31833
+ function readPackageJsonDeps(root) {
31834
+ const file2 = join18(root, "package.json");
31835
+ if (!existsSync4(file2)) return void 0;
31836
+ try {
31837
+ const pkg = JSON.parse(readFileSync(file2, "utf8"));
31838
+ return { ...pkg.dependencies, ...pkg.devDependencies };
31839
+ } catch {
31840
+ return void 0;
31841
+ }
31842
+ }
31843
+
31844
+ // src/commands/init/environment-initializer.ts
31845
+ import { readFile as readFile7 } from "node:fs/promises";
31846
+ import { join as join19 } from "node:path";
31847
+ var ENV_REF_PATTERN = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
31848
+ async function collectEnvVarRefs(root) {
31849
+ let text;
31850
+ try {
31851
+ text = await readFile7(join19(root, "testpilot.yaml"), "utf8");
31852
+ } catch {
31853
+ return [];
31854
+ }
31855
+ const names = /* @__PURE__ */ new Set();
31856
+ for (const match of text.matchAll(ENV_REF_PATTERN)) {
31857
+ names.add(match[1]);
31858
+ }
31859
+ return [...names].sort();
31860
+ }
31861
+
31862
+ // src/commands/init/project-detector.ts
31863
+ import { existsSync as existsSync5, readFileSync as readFileSync2 } from "node:fs";
31864
+ import { basename, join as join20 } from "node:path";
31865
+
31866
+ // src/lib/git.ts
31867
+ import { execFile as execFile2 } from "node:child_process";
31868
+ import { promisify } from "node:util";
31869
+ var execFileAsync = promisify(execFile2);
31870
+ async function readGitInfo(root) {
31871
+ const run = async (args) => {
31426
31872
  try {
31427
- const data = await adapter.screenshot();
31428
- result.screenshot = await artifacts.saveStepScreenshot(`${options.screenshotName}-failed.png`, data);
31873
+ const { stdout } = await execFileAsync("git", args, { cwd: root });
31874
+ return stdout.trim() || void 0;
31429
31875
  } catch {
31876
+ return void 0;
31430
31877
  }
31878
+ };
31879
+ const [branch, commit, repositoryUrl] = await Promise.all([
31880
+ run(["rev-parse", "--abbrev-ref", "HEAD"]),
31881
+ run(["rev-parse", "HEAD"]),
31882
+ run(["remote", "get-url", "origin"])
31883
+ ]);
31884
+ return { branch, commit, repositoryUrl };
31885
+ }
31886
+
31887
+ // src/commands/init/project-detector.ts
31888
+ var WEB_DEP_MARKERS = [
31889
+ "playwright",
31890
+ "@playwright/test",
31891
+ "vite",
31892
+ "next",
31893
+ "react",
31894
+ "vue",
31895
+ "@angular/core",
31896
+ "nuxt",
31897
+ "svelte"
31898
+ ];
31899
+ var E2E_DIR_CANDIDATES = ["tests/e2e", "test/e2e", "e2e", "cypress"];
31900
+ function readPackageJson(root) {
31901
+ const file2 = join20(root, "package.json");
31902
+ if (!existsSync5(file2)) return void 0;
31903
+ try {
31904
+ return JSON.parse(readFileSync2(file2, "utf8"));
31905
+ } catch {
31906
+ return void 0;
31431
31907
  }
31432
- result.durationMs = Date.now() - startedAt;
31433
- return result;
31908
+ }
31909
+ function detectProjectType(root) {
31910
+ const pkg = readPackageJson(root);
31911
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
31912
+ const isWechat = existsSync5(join20(root, "project.config.json")) || existsSync5(join20(root, "app.json")) || existsSync5(join20(root, "miniprogram", "app.json"));
31913
+ const isWeb = existsSync5(join20(root, "index.html")) || WEB_DEP_MARKERS.some((marker) => deps?.[marker] !== void 0) || [".ts", ".tsx", ".js", ".jsx"].some((ext) => existsSync5(join20(root, "src", `index${ext}`)));
31914
+ if (isWechat && isWeb) return "hybrid";
31915
+ if (isWechat) return "wechat-miniapp";
31916
+ if (isWeb) return "web";
31917
+ return "unknown";
31918
+ }
31919
+ async function detectProject(root) {
31920
+ const pkg = readPackageJson(root);
31921
+ const type = detectProjectType(root);
31922
+ const language = existsSync5(join20(root, "tsconfig.json")) ? "TypeScript" : pkg || existsSync5(join20(root, "src")) ? "JavaScript" : "Unknown";
31923
+ const packageManager = existsSync5(join20(root, "pnpm-lock.yaml")) ? "pnpm" : existsSync5(join20(root, "yarn.lock")) ? "yarn" : existsSync5(join20(root, "package-lock.json")) ? "npm" : "npx";
31924
+ const existingE2eDirs = E2E_DIR_CANDIDATES.filter((dir) => existsSync5(join20(root, dir)));
31925
+ return {
31926
+ root,
31927
+ name: pkg?.name ?? basename(root),
31928
+ type,
31929
+ language,
31930
+ packageManager,
31931
+ git: await readGitInfo(root),
31932
+ hasTestsE2e: existingE2eDirs.includes("tests/e2e"),
31933
+ existingE2eDirs,
31934
+ hasTestpilotConfig: existsSync5(join20(root, "testpilot.yaml")),
31935
+ hasProjectLink: existsSync5(join20(root, ".testpilot", "project.json"))
31936
+ };
31937
+ }
31938
+ function defaultAdapterFor(type) {
31939
+ if (type === "wechat-miniapp") return "wechatide";
31940
+ return "playwright";
31941
+ }
31942
+ function adaptersFor(type) {
31943
+ if (type === "hybrid") return ["playwright", "wechatide"];
31944
+ if (type === "wechat-miniapp") return ["wechatide"];
31945
+ if (type === "web") return ["playwright"];
31946
+ return ["playwright"];
31434
31947
  }
31435
31948
 
31436
- // ../../packages/execution-engine/src/engine/execution-engine.ts
31437
- var ExecutionEngine = class {
31438
- async runCase(data, options) {
31439
- const { runId, file: file2, artifacts, bus, resolver } = options;
31440
- const startedAt = /* @__PURE__ */ new Date();
31441
- const context = new ExecutionContext();
31442
- const steps = [];
31443
- const evidenceAdapters = /* @__PURE__ */ new Map();
31444
- let caseError;
31445
- await bus.emit({ type: "case-started", runId, caseId: data.id, file: file2, ts: startedAt.toISOString() });
31446
- await artifacts.logger.info(`case ${data.id} started (${file2})`);
31447
- for (const [index, step] of data.steps.entries()) {
31448
- await bus.emit({
31449
- type: "step-started",
31450
- runId,
31451
- caseId: data.id,
31452
- index,
31453
- target: step.target,
31454
- action: step.action,
31455
- ts: (/* @__PURE__ */ new Date()).toISOString()
31456
- });
31457
- let result;
31458
- try {
31459
- const adapter = await (await resolver.session(step.target)).get();
31460
- if (adapter.startEvidence && !evidenceAdapters.has(step.target)) {
31461
- try {
31462
- await adapter.startEvidence(data.id);
31463
- evidenceAdapters.set(step.target, adapter);
31464
- } catch (err) {
31465
- await artifacts.logger.info(
31466
- `evidence start failed for ${step.target}: ${err instanceof Error ? err.message : String(err)}`
31467
- );
31468
- }
31469
- }
31470
- result = await executeStep(step, index, adapter, context, artifacts, {
31471
- screenshotName: `${data.id}-step-${String(index).padStart(2, "0")}`
31472
- });
31473
- } catch (err) {
31474
- result = {
31475
- index,
31476
- target: step.target,
31477
- action: step.action,
31478
- status: "failed",
31479
- durationMs: 0,
31480
- error: err instanceof Error ? err.message : String(err)
31481
- };
31482
- }
31483
- steps.push(result);
31484
- await artifacts.logger.info(`step ${index} ${step.action} -> ${result.status}${result.error ? ` - ${result.error}` : ""}`);
31485
- await bus.emit({
31486
- type: "step-finished",
31487
- runId,
31488
- caseId: data.id,
31489
- index,
31490
- target: step.target,
31491
- action: step.action,
31492
- status: result.status,
31493
- durationMs: result.durationMs,
31494
- error: result.error,
31495
- ts: (/* @__PURE__ */ new Date()).toISOString()
31949
+ // src/commands/init/doctor.ts
31950
+ async function runDoctor(root) {
31951
+ const sections = [];
31952
+ const push = (name, items) => {
31953
+ if (items.length > 0) sections.push({ name, items });
31954
+ };
31955
+ const ok = (label) => ({ status: "ok", label });
31956
+ const warn = (label, hint) => ({ status: "warn", label, hint });
31957
+ const error62 = (label, hint) => ({ status: "error", label, hint });
31958
+ const nodeMajor = Number(process.versions.node.split(".")[0]);
31959
+ push("Runtime", [
31960
+ nodeMajor >= 22 ? ok(`Node.js ${process.versions.node}`) : error62(`Node.js ${process.versions.node}`, "\u9700\u8981 Node.js >= 22")
31961
+ ]);
31962
+ const info = await detectProject(root);
31963
+ const projectItems = [
31964
+ ok(`Project ${info.name}(${info.type})`),
31965
+ info.git.commit ? ok(`Git repository(${info.git.branch ?? "detached"} \xB7 ${info.git.commit.slice(0, 7)})`) : warn("Git repository \u672A\u68C0\u6D4B\u5230", "Case Metadata \u65E0\u6CD5\u540C\u6B65\u5230 Server"),
31966
+ existsSync6(join21(root, ".testpilot", "project.json")) ? ok(".testpilot/project.json") : error62(".testpilot/project.json", "\u8FD0\u884C npx csspilot init \u751F\u6210"),
31967
+ existsSync6(join21(root, "testpilot.yaml")) ? ok("testpilot.yaml") : error62("testpilot.yaml", "\u8FD0\u884C npx csspilot init \u751F\u6210")
31968
+ ];
31969
+ push("Project", projectItems);
31970
+ const config2 = await loadTestpilotConfig(root).catch(() => void 0);
31971
+ const casesDir = config2?.casesDir ?? "tests/e2e/cases";
31972
+ const cases = await collectCases([casesDir], { root }).catch(() => []);
31973
+ const invalidCount = cases.filter((item) => !item.valid).length;
31974
+ const testDir = join21(root, "tests", "e2e");
31975
+ push("Test", [
31976
+ existsSync6(testDir) ? ok("tests/e2e") : error62("tests/e2e", "\u8FD0\u884C npx csspilot init \u521B\u5EFA"),
31977
+ existsSync6(join21(root, casesDir)) ? ok(`cases directory(${casesDir})`) : error62(`cases directory(${casesDir})`, "\u8FD0\u884C npx csspilot init \u521B\u5EFA"),
31978
+ cases.length === 0 ? warn("Case validation \u8DF3\u8FC7(\u672A\u627E\u5230\u7528\u4F8B)", "\u5728 tests/e2e/cases \u521B\u5EFA Case") : invalidCount === 0 ? ok(`Case validation(${cases.length} \u4E2A\u7528\u4F8B\u5168\u90E8\u6709\u6548)`) : error62(`Case validation(${invalidCount}/${cases.length} \u4E2A\u7528\u4F8B\u6821\u9A8C\u5931\u8D25)`, "\u8FD0\u884C npx csspilot validate \u67E5\u770B\u8BE6\u60C5")
31979
+ ]);
31980
+ const skillDir = join21(root, ".agents", "skills", "testpilot");
31981
+ push("Agent", [
31982
+ existsSync6(join21(skillDir, "manifest.yaml")) ? ok("TestPilot Skill(.agents/skills/testpilot)") : error62("TestPilot Skill", "\u8FD0\u884C npx csspilot init \u5B89\u88C5"),
31983
+ existsSync6(join21(skillDir, "references", "project.md")) ? ok("Project testing guide(references/)") : warn("Project testing guide \u7F3A\u5931", "references/ \u7531 init \u751F\u6210;\u53EF\u91CD\u65B0\u8FD0\u884C npx csspilot init")
31984
+ ]);
31985
+ const adapters = await detectAdapters(root, info.type);
31986
+ push(
31987
+ "Adapters",
31988
+ adapters.map(
31989
+ (item) => item.available ? ok(`${item.id}(${item.detail})`) : item.required ? warn(`${item.id} \u4E0D\u53EF\u7528`, item.detail) : warn(`${item.id} \u672A\u5B89\u88C5(\u53EF\u9009)`, item.detail)
31990
+ )
31991
+ );
31992
+ const refs = await collectEnvVarRefs(root);
31993
+ if (refs.length > 0) {
31994
+ push(
31995
+ "Environment",
31996
+ refs.map(
31997
+ (name) => process.env[name] !== void 0 ? ok(name) : error62(`${name} missing`, "\u5728\u8FD0\u884C\u73AF\u5883(.env / CI Secret)\u4E2D\u8BBE\u7F6E")
31998
+ )
31999
+ );
32000
+ }
32001
+ const serverUrl = process.env.TESTPILOT_SERVER_URL ?? config2?.server?.baseUrl;
32002
+ if (serverUrl) {
32003
+ const link = await readProjectLink(root);
32004
+ const serverItems = [];
32005
+ try {
32006
+ const res = await fetch(`${serverUrl.replace(/\/$/, "")}/api/health`, {
32007
+ signal: AbortSignal.timeout(3e3)
31496
32008
  });
31497
- if (result.status === "failed") {
31498
- caseError = result.error;
31499
- for (const [skipIndex, skippedStep] of data.steps.entries()) {
31500
- if (skipIndex <= index) continue;
31501
- steps.push({
31502
- index: skipIndex,
31503
- target: skippedStep.target,
31504
- action: skippedStep.action,
31505
- status: "skipped",
31506
- durationMs: 0
31507
- });
31508
- }
31509
- break;
31510
- }
32009
+ serverItems.push(res.ok ? ok(`Connected(${serverUrl})`) : error62(`Server ${res.status}`, serverUrl));
32010
+ } catch (err) {
32011
+ serverItems.push(
32012
+ error62(`Server \u4E0D\u53EF\u8FBE(${serverUrl})`, err instanceof Error ? err.message : String(err))
32013
+ );
31511
32014
  }
31512
- const finishedAt = /* @__PURE__ */ new Date();
31513
- const status = caseError ? "failed" : "passed";
31514
- const caseResult = {
31515
- caseId: data.id,
31516
- caseName: data.name,
31517
- file: file2,
31518
- status,
31519
- steps,
31520
- startedAt: startedAt.toISOString(),
31521
- finishedAt: finishedAt.toISOString(),
31522
- durationMs: finishedAt.getTime() - startedAt.getTime()
31523
- };
31524
- if (caseError) caseResult.error = caseError;
31525
- for (const [target, adapter] of evidenceAdapters) {
31526
- if (!adapter.stopEvidence) continue;
31527
- try {
31528
- const evidence = await adapter.stopEvidence(data.id);
31529
- if (evidence.video) {
31530
- caseResult.video = await artifacts.saveVideo(`${data.id}-${target}.webm`, evidence.video);
31531
- }
31532
- if (evidence.trace) {
31533
- caseResult.trace = await artifacts.saveTrace(`${data.id}-${target}.zip`, evidence.trace);
31534
- }
31535
- } catch (err) {
31536
- await artifacts.logger.info(
31537
- `evidence stop failed for ${target}: ${err instanceof Error ? err.message : String(err)}`
31538
- );
31539
- }
32015
+ if (link?.projectId) serverItems.push(ok(`Project association(${link.projectId})`));
32016
+ else serverItems.push(warn("Project association \u7F3A\u5931", "\u8FD0\u884C npx csspilot init \u91CD\u65B0\u5173\u8054"));
32017
+ push("Server", serverItems);
32018
+ }
32019
+ const all = sections.flatMap((section) => section.items);
32020
+ return {
32021
+ sections,
32022
+ errors: all.filter((item) => item.status === "error").length,
32023
+ warnings: all.filter((item) => item.status === "warn").length
32024
+ };
32025
+ }
32026
+ var MARK = { ok: "\u2714", warn: "\u26A0", error: "\u2717" };
32027
+ function printDoctor(report) {
32028
+ console.log("TestPilot Doctor");
32029
+ console.log("");
32030
+ for (const section of report.sections) {
32031
+ console.log(section.name);
32032
+ console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
32033
+ for (const item of section.items) {
32034
+ const hint = item.hint ? `(${item.hint})` : "";
32035
+ console.log(`${MARK[item.status]} ${item.label}${hint}`);
31540
32036
  }
31541
- await bus.emit({
31542
- type: "case-finished",
31543
- runId,
31544
- caseId: data.id,
31545
- status,
31546
- durationMs: finishedAt.getTime() - startedAt.getTime(),
31547
- ts: finishedAt.toISOString()
32037
+ console.log("");
32038
+ }
32039
+ console.log("Result");
32040
+ console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
32041
+ console.log(`${report.errors} error${report.errors === 1 ? "" : "s"}`);
32042
+ console.log(`${report.warnings} warning${report.warnings === 1 ? "" : "s"}`);
32043
+ }
32044
+
32045
+ // src/commands/doctor.ts
32046
+ function makeDoctorCommand() {
32047
+ return new Command("doctor").description("TestPilot \u5065\u5EB7\u68C0\u67E5(Runtime / \u9879\u76EE / \u7528\u4F8B / Skill / Adapter / \u73AF\u5883\u53D8\u91CF / Server)").action(async () => {
32048
+ const report = await runDoctor(process.cwd());
32049
+ printDoctor(report);
32050
+ if (report.errors > 0) process.exitCode = 1;
32051
+ });
32052
+ }
32053
+
32054
+ // src/commands/init/index.ts
32055
+ import { join as join25 } from "node:path";
32056
+
32057
+ // src/commands/init/config-initializer.ts
32058
+ import { access as access2, mkdir as mkdir11, writeFile as writeFile9 } from "node:fs/promises";
32059
+ import { basename as basename2, join as join22 } from "node:path";
32060
+ async function exists3(path) {
32061
+ try {
32062
+ await access2(path);
32063
+ return true;
32064
+ } catch {
32065
+ return false;
32066
+ }
32067
+ }
32068
+ var TEST_DIR = "tests/e2e";
32069
+ var CASE_DIR = "tests/e2e/cases";
32070
+ function renderTestpilotYaml(info) {
32071
+ const adapters = adaptersFor(info.type).map((item) => ` - ${item}`).join("\n");
32072
+ return `# TestPilot \u9879\u76EE\u914D\u7F6E(Source of Truth)
32073
+ version: 1
32074
+
32075
+ project:
32076
+ name: ${info.name}
32077
+
32078
+ test:
32079
+ directory: ${TEST_DIR}
32080
+ caseDirectory: ${CASE_DIR}
32081
+
32082
+ # \u73AF\u5883\u914D\u7F6E:Case \u7528 environment: <\u540D\u79F0> \u5F15\u7528;baseUrl \u7531\u73AF\u5883\u53D8\u91CF\u6CE8\u5165,\u7981\u6B62\u5199\u660E\u6587
32083
+ environment:
32084
+ default: test
32085
+ test:
32086
+ baseUrl: \${TEST_BASE_URL}
32087
+ staging:
32088
+ baseUrl: \${STAGING_BASE_URL}
32089
+
32090
+ # \u9879\u76EE\u58F0\u660E\u7684\u6267\u884C\u7AEF(\u5B9E\u9645\u53EF\u7528\u6027\u4EE5 csspilot doctor \u68C0\u6D4B\u4E3A\u51C6)
32091
+ adapters:
32092
+ ${adapters}
32093
+
32094
+ # \u9ED8\u8BA4 Workspace(\u591A\u7CFB\u7EDF\u73AF\u5883\u7EC4\u5408);Case \u4E5F\u53EF\u7528 workspace \u5B57\u6BB5\u6309\u9700\u58F0\u660E
32095
+ # workspace:
32096
+ # default: my-workspace
32097
+
32098
+ # TestPilot Server(Control Plane)\u5730\u5740;init \u5173\u8054\u9879\u76EE\u4E0E sync-metadata \u4F7F\u7528
32099
+ # \u4E5F\u53EF\u7528\u73AF\u5883\u53D8\u91CF TESTPILOT_SERVER_URL \u8986\u76D6
32100
+ # server:
32101
+ # baseUrl: http://127.0.0.1:3000
32102
+
32103
+ # Web \u7AEF:navigate \u76F8\u5BF9 url \u7684\u57FA\u51C6\u5730\u5740
32104
+ # web:
32105
+ # baseUrl: http://127.0.0.1:8080
32106
+
32107
+ # \u5C0F\u7A0B\u5E8F\u7AEF:\u586B\u5165\u5C0F\u7A0B\u5E8F\u9879\u76EE\u76EE\u5F55\u540E\u5373\u53EF\u6267\u884C target: miniapp \u7684\u6B65\u9AA4
32108
+ # miniapp:
32109
+ # projectPath: path/to/miniprogram
32110
+ # cliPath: C:/Program Files (x86)/Tencent/\u5FAE\u4FE1web\u5F00\u53D1\u8005\u5DE5\u5177/cli.bat
32111
+ `;
32112
+ }
32113
+ async function initTestPilotConfig(root, info, adapters) {
32114
+ const yamlPath = join22(root, "testpilot.yaml");
32115
+ let yaml = "reused";
32116
+ if (!await exists3(yamlPath)) {
32117
+ await writeFile9(yamlPath, renderTestpilotYaml(info), "utf8");
32118
+ yaml = "created";
32119
+ }
32120
+ const runtimeDir = join22(root, ".testpilot", "artifacts");
32121
+ await mkdir11(runtimeDir, { recursive: true });
32122
+ const keep = join22(runtimeDir, ".gitkeep");
32123
+ if (!await exists3(keep)) {
32124
+ await writeFile9(keep, "", "utf8");
32125
+ }
32126
+ const existing = await readProjectLink(root);
32127
+ const defaultAdapter = defaultAdapterFor(info.type);
32128
+ const serverUrl = process.env.TESTPILOT_SERVER_URL ?? void 0;
32129
+ const link = existing ? { ...existing, version: existing.version ?? 1 } : {
32130
+ ...await createProjectOnServer(root, info, adapters, serverUrl),
32131
+ version: 1,
32132
+ testDir: TEST_DIR,
32133
+ caseDir: CASE_DIR,
32134
+ defaultAdapter
32135
+ };
32136
+ if (link.testDir === void 0 || link.caseDir === void 0 || link.defaultAdapter === void 0) {
32137
+ link.testDir ??= TEST_DIR;
32138
+ link.caseDir ??= CASE_DIR;
32139
+ link.defaultAdapter ??= defaultAdapter;
32140
+ }
32141
+ if (link.serverUrl === void 0 && serverUrl) link.serverUrl = serverUrl;
32142
+ const projectLinkFile = await writeProjectLink(link, root);
32143
+ return { yaml, runtimeDir: join22(root, ".testpilot"), projectLink: link, projectLinkFile };
32144
+ }
32145
+ async function createProjectOnServer(root, info, _adapters, serverUrl) {
32146
+ const git = info.git;
32147
+ const base = { repositoryUrl: git.repositoryUrl, branch: git.branch };
32148
+ if (!serverUrl) return { ...base, projectId: `proj_${randomId()}` };
32149
+ try {
32150
+ const res = await fetch(`${serverUrl.replace(/\/$/, "")}/api/projects`, {
32151
+ method: "POST",
32152
+ headers: { "content-type": "application/json" },
32153
+ body: JSON.stringify({
32154
+ name: info.name || basename2(root),
32155
+ rootPath: root,
32156
+ repositoryUrl: git.repositoryUrl,
32157
+ defaultBranch: git.branch
32158
+ })
31548
32159
  });
31549
- await artifacts.logger.info(`case ${data.id} ${status}`);
31550
- return caseResult;
32160
+ if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
32161
+ const project = await res.json();
32162
+ return { ...base, serverUrl, projectId: `proj_${project.id}` };
32163
+ } catch (err) {
32164
+ console.error(`\u2717 \u9879\u76EE\u5173\u8054 Server(${serverUrl})\u4E0D\u53EF\u8FBE:${err instanceof Error ? err.message : err}`);
32165
+ return { ...base, serverUrl, projectId: `proj_${randomId()}` };
31551
32166
  }
31552
- };
32167
+ }
32168
+ function randomId() {
32169
+ return Math.random().toString(16).slice(2, 10);
32170
+ }
31553
32171
 
31554
- // ../../packages/execution-engine/src/engine/result-collector.ts
31555
- function buildRunSummary(runId, startedAt, cases) {
31556
- const finishedAt = /* @__PURE__ */ new Date();
31557
- const totals = {
31558
- cases: cases.length,
31559
- passed: cases.filter((item) => item.status === "passed").length,
31560
- failed: cases.filter((item) => item.status === "failed").length,
31561
- steps: 0,
31562
- stepsPassed: 0,
31563
- stepsFailed: 0,
31564
- stepsSkipped: 0
32172
+ // src/commands/init/skill-installer.ts
32173
+ import { existsSync as existsSync7 } from "node:fs";
32174
+ import { access as access3, cp, mkdir as mkdir12, writeFile as writeFile10 } from "node:fs/promises";
32175
+ import { dirname as dirname7, join as join23 } from "node:path";
32176
+ import { fileURLToPath } from "node:url";
32177
+ async function exists4(path) {
32178
+ try {
32179
+ await access3(path);
32180
+ return true;
32181
+ } catch {
32182
+ return false;
32183
+ }
32184
+ }
32185
+ function resolveSkillSourceDir() {
32186
+ const fromEnv = process.env.TESTPILOT_SKILL_DIR;
32187
+ if (fromEnv) return fromEnv;
32188
+ const bundled = fileURLToPath(new URL("../../skills/testpilot", import.meta.url));
32189
+ if (existsSync7(bundled)) return bundled;
32190
+ const inRepo = fileURLToPath(new URL("../../../../../skills/testpilot", import.meta.url));
32191
+ return existsSync7(inRepo) ? inRepo : void 0;
32192
+ }
32193
+ async function installSkill(root, info, adapters) {
32194
+ const dest = join23(root, ".agents", "skills", "testpilot");
32195
+ let core = "reused";
32196
+ if (!await exists4(join23(dest, "manifest.yaml"))) {
32197
+ const src = resolveSkillSourceDir();
32198
+ if (!src) {
32199
+ throw new Error(
32200
+ "\u65E0\u6CD5\u5B9A\u4F4D TestPilot Skill \u6E90\u76EE\u5F55;\u53EF\u901A\u8FC7\u73AF\u5883\u53D8\u91CF TESTPILOT_SKILL_DIR \u6307\u5B9A skills/testpilot \u8DEF\u5F84"
32201
+ );
32202
+ }
32203
+ await mkdir12(dirname7(dest), { recursive: true });
32204
+ await cp(src, dest, { recursive: true });
32205
+ core = "created";
32206
+ }
32207
+ const refsDir = join23(dest, "references");
32208
+ const files = [
32209
+ ["project.md", () => renderProjectMd(info, adapters)],
32210
+ ["test-conventions.md", renderTestConventionsMd],
32211
+ ["adapters.md", () => renderAdaptersMd(adapters)]
32212
+ ];
32213
+ let references = "reused";
32214
+ for (const [name, render] of files) {
32215
+ const file2 = join23(refsDir, name);
32216
+ if (await exists4(file2)) continue;
32217
+ await mkdir12(refsDir, { recursive: true });
32218
+ await writeFile10(file2, render(), "utf8");
32219
+ references = "created";
32220
+ }
32221
+ return { core, references, dest };
32222
+ }
32223
+ function renderProjectMd(info, adapters) {
32224
+ const available = adapters.filter((item) => item.available).map((item) => item.id);
32225
+ return `# Project
32226
+
32227
+ \u81EA\u52A8\u751F\u6210\u4E8E \`csspilot init\`,\u63CF\u8FF0\u672C\u9879\u76EE\u7684 TestPilot \u63A5\u5165\u4FE1\u606F;Agent \u4F18\u5148\u4ECE\u8FD9\u91CC\u4E86\u89E3\u9879\u76EE\u3002
32228
+
32229
+ - Project name: ${info.name}
32230
+ - Project type: ${info.type}
32231
+ - Language: ${info.language}
32232
+ - Package manager: ${info.packageManager}
32233
+ - Test directory: tests/e2e
32234
+ - Case directory: tests/e2e/cases
32235
+ - Available adapters: ${available.length > 0 ? available.join(", ") : "(none detected)"}
32236
+ - Default environment: test(testpilot.yaml environment.default)
32237
+ - Default workspace: \u672A\u8BBE\u7F6E(Case \u53EF\u6309\u9700\u58F0\u660E workspace \u5B57\u6BB5)
32238
+ `;
32239
+ }
32240
+ function renderTestConventionsMd() {
32241
+ return `# Test Conventions
32242
+
32243
+ \u672C\u9879\u76EE E2E \u6D4B\u8BD5\u7EA6\u5B9A,Agent \u751F\u6210/\u4FEE\u6539 Case \u65F6\u5FC5\u987B\u9075\u5B88:
32244
+
32245
+ 1. E2E Case \u4F4D\u4E8E tests/e2e/cases
32246
+ 2. Case \u4F7F\u7528 TestPilot DSL
32247
+ 3. \u4E0D\u5141\u8BB8\u76F4\u63A5\u8C03\u7528 Playwright
32248
+ 4. \u4E0D\u5141\u8BB8\u76F4\u63A5\u8C03\u7528 WeChatIDE
32249
+ 5. \u4E0D\u5141\u8BB8\u5728 Case \u4E2D\u5199\u660E\u6587\u5BC6\u7801(\u7528 accountRef \u5F15\u7528)
32250
+ 6. \u4F18\u5148\u590D\u7528\u5DF2\u6709 Case
32251
+ 7. \u65B0\u589E Case \u5FC5\u987B\u901A\u8FC7 csspilot validate
32252
+ 8. Case ID \u5FC5\u987B\u552F\u4E00
32253
+ `;
32254
+ }
32255
+ function renderAdaptersMd(adapters) {
32256
+ const lines = adapters.map(
32257
+ (item) => `- ${item.id}: ${item.available ? "\u53EF\u7528" : "\u4E0D\u53EF\u7528"}${item.required ? "(\u9879\u76EE\u9700\u8981)" : "(\u53EF\u9009)"} \u2014 ${item.detail}`
32258
+ );
32259
+ return `# Adapters
32260
+
32261
+ \u6267\u884C\u7AEF\u68C0\u6D4B\u7ED3\u679C(\u4EE5 \`csspilot doctor\` \u6700\u65B0\u8F93\u51FA\u4E3A\u51C6):
32262
+
32263
+ ${lines.join("\n")}
32264
+
32265
+ Agent \u6C38\u8FDC\u4E0D\u76F4\u63A5\u64CD\u4F5C Adapter;Case \u7ECF Execution Engine \u8C03\u5EA6\u5230\u5BF9\u5E94 Adapter \u6267\u884C\u3002
32266
+ `;
32267
+ }
32268
+
32269
+ // src/commands/init/test-structure.ts
32270
+ import { existsSync as existsSync8, readdirSync as readdirSync2 } from "node:fs";
32271
+ import { mkdir as mkdir13, writeFile as writeFile11 } from "node:fs/promises";
32272
+ import { join as join24 } from "node:path";
32273
+ async function initTestStructure(root, _info) {
32274
+ const dirs = {
32275
+ cases: join24(root, "tests", "e2e", "cases"),
32276
+ fixtures: join24(root, "tests", "e2e", "fixtures"),
32277
+ data: join24(root, "tests", "e2e", "data")
31565
32278
  };
31566
- for (const item of cases) {
31567
- for (const step of item.steps) {
31568
- totals.steps++;
31569
- if (step.status === "passed") totals.stepsPassed++;
31570
- else if (step.status === "failed") totals.stepsFailed++;
31571
- else totals.stepsSkipped++;
32279
+ const existed = {
32280
+ cases: existsSync8(dirs.cases),
32281
+ fixtures: existsSync8(dirs.fixtures),
32282
+ data: existsSync8(dirs.data)
32283
+ };
32284
+ for (const dir of Object.values(dirs)) {
32285
+ await mkdir13(dir, { recursive: true });
32286
+ }
32287
+ for (const [name, dir] of Object.entries(dirs)) {
32288
+ if (!existed[name] && readdirSync2(dir).length === 0) {
32289
+ await writeFile11(join24(dir, ".gitkeep"), "", "utf8").catch(() => void 0);
31572
32290
  }
31573
32291
  }
31574
32292
  return {
31575
- runId,
31576
- startedAt: startedAt.toISOString(),
31577
- finishedAt: finishedAt.toISOString(),
31578
- durationMs: finishedAt.getTime() - startedAt.getTime(),
31579
- status: totals.failed > 0 ? "failed" : "passed",
31580
- cases,
31581
- totals
32293
+ cases: existed.cases ? "reused" : "created",
32294
+ fixtures: existed.fixtures ? "reused" : "created",
32295
+ data: existed.data ? "reused" : "created"
31582
32296
  };
31583
32297
  }
31584
32298
 
31585
- // ../../packages/execution-engine/src/engine/test-runner.ts
31586
- import { writeFile as writeFile6 } from "node:fs/promises";
31587
- import { join as join15, resolve as resolve2 } from "node:path";
31588
- var TestRunner = class {
31589
- resolver;
31590
- runsRoot;
31591
- extraSubscriber;
31592
- constructor(options) {
31593
- this.resolver = options.resolver;
31594
- this.runsRoot = resolve2(options.runsRoot ?? join15(process.cwd(), ".testpilot", "artifacts", "runs"));
31595
- this.extraSubscriber = options.onEvent;
31596
- }
31597
- async run(cases) {
31598
- const startedAt = /* @__PURE__ */ new Date();
31599
- const runId = await allocateRunId(this.runsRoot);
31600
- const runDir = await ensureRunDir(this.runsRoot, runId);
31601
- const artifacts = new ArtifactManager(runDir);
31602
- await artifacts.prepare();
31603
- const bus = new EventBus();
31604
- bus.subscribe(ndjsonSubscriber(join15(runDir, "events.ndjson")));
31605
- if (this.extraSubscriber) bus.subscribe(this.extraSubscriber);
31606
- await bus.emit({ type: "run-started", runId, totalCases: cases.length, ts: startedAt.toISOString() });
31607
- await artifacts.logger.info(`run ${runId} started with ${cases.length} case(s)`);
31608
- const engine = new ExecutionEngine();
31609
- const results = await runSequential(
31610
- cases,
31611
- (item) => engine.runCase(item.data, {
31612
- runId,
31613
- file: item.file,
31614
- artifacts,
31615
- bus,
31616
- resolver: this.resolver
31617
- })
31618
- );
31619
- await this.resolver.closeAll();
31620
- const summary = buildRunSummary(runId, startedAt, results);
31621
- await bus.emit({
31622
- type: "run-finished",
31623
- runId,
31624
- status: summary.status,
31625
- totals: { cases: summary.totals.cases, passed: summary.totals.passed, failed: summary.totals.failed },
31626
- ts: (/* @__PURE__ */ new Date()).toISOString()
31627
- });
31628
- await artifacts.logger.info(`run ${runId} finished: ${summary.status}`);
31629
- await writeFile6(join15(runDir, RESULT_FILE), JSON.stringify(summary, null, 2), "utf8");
31630
- return summary;
32299
+ // src/commands/init/index.ts
32300
+ async function runInit(root, options = {}) {
32301
+ if (options.serverUrl !== void 0) {
32302
+ if (options.serverUrl === null) delete process.env.TESTPILOT_SERVER_URL;
32303
+ else process.env.TESTPILOT_SERVER_URL = options.serverUrl;
32304
+ }
32305
+ const project = await detectProject(root);
32306
+ console.log(`\u2714 Project: ${project.name}`);
32307
+ console.log(`\u2714 Type: ${project.type}`);
32308
+ console.log(`\u2714 Language: ${project.language}`);
32309
+ console.log(`\u2714 Package Manager: ${project.packageManager}`);
32310
+ console.log(project.git.commit ? `\u2714 Git repository ${project.git.branch ?? "(detached)"}` : "\u2717 Git repository \u672A\u68C0\u6D4B\u5230");
32311
+ const adapters = await detectAdapters(root, project.type);
32312
+ console.log("");
32313
+ console.log("Testing adapters:");
32314
+ for (const adapter of adapters) {
32315
+ const mark = adapter.available ? "\u2713" : "\u2717";
32316
+ console.log(`${mark} ${adapter.id}${adapter.available ? "" : " not detected"} \u2014 ${adapter.detail}`);
32317
+ }
32318
+ console.log("");
32319
+ const config2 = await initTestPilotConfig(root, project, adapters);
32320
+ console.log(
32321
+ config2.yaml === "created" ? "\u2713 \u9879\u76EE\u914D\u7F6E testpilot.yaml" : "\u2713 \u9879\u76EE\u914D\u7F6E testpilot.yaml(\u5DF2\u5B58\u5728,\u4FDD\u7559)"
32322
+ );
32323
+ console.log(`\u2713 Runtime \u76EE\u5F55 ${join25(".testpilot", "artifacts")}`);
32324
+ const serverMode = config2.projectLink.serverUrl ? `Server:${config2.projectLink.serverUrl}` : "\u672C\u5730\u6A21\u5F0F";
32325
+ console.log(`\u2713 \u9879\u76EE\u5173\u8054 ${config2.projectLink.projectId}(${serverMode})`);
32326
+ const testStructure = await initTestStructure(root, project);
32327
+ const reuseNote = project.existingE2eDirs.filter((dir) => dir !== "tests/e2e");
32328
+ console.log(
32329
+ testStructure.cases === "reused" ? "\u2713 \u6D4B\u8BD5\u76EE\u5F55 tests/e2e(\u5DF2\u5B58\u5728,\u590D\u7528)" : "\u2713 \u6D4B\u8BD5\u76EE\u5F55 tests/e2e/{cases,fixtures,data}"
32330
+ );
32331
+ if (reuseNote.length > 0) {
32332
+ console.log(` \u26A0 \u68C0\u6D4B\u5230\u5176\u4ED6 E2E \u76EE\u5F55:${reuseNote.join(", ")}(\u4FDD\u7559\u4E0D\u52A8,\u672A\u5F3A\u5236\u8FC1\u79FB)`);
32333
+ }
32334
+ const skill = await installSkill(root, project, adapters);
32335
+ console.log(
32336
+ skill.core === "created" ? `\u2713 Skill \u5B89\u88C5 ${join25(".agents", "skills", "testpilot")}` : "\u2713 Skill \u5B89\u88C5 .agents/skills/testpilot/(\u5DF2\u5B58\u5728,\u8DF3\u8FC7)"
32337
+ );
32338
+ console.log(
32339
+ skill.references === "created" ? "\u2713 Agent \u4E0A\u4E0B\u6587 references/{project,test-conventions,adapters}.md" : "\u2713 Agent \u4E0A\u4E0B\u6587 references/(\u5DF2\u5B58\u5728,\u4FDD\u7559)"
32340
+ );
32341
+ console.log("\u2713 \u73AF\u5883\u914D\u7F6E environment \u6BB5(test/staging),baseUrl \u7531 TEST_BASE_URL \u7B49\u53D8\u91CF\u6CE8\u5165");
32342
+ const ci = await detectCi(root);
32343
+ if (ci.hasTestpilotWorkflow) {
32344
+ console.log("\u2713 CI .github/workflows/testpilot.yml(\u5DF2\u5B58\u5728)");
32345
+ } else if (ci.githubWorkflows || ci.gitlabCi) {
32346
+ console.log("\u26A0 CI \u68C0\u6D4B\u5230\u5DF2\u6709 CI \u914D\u7F6E,\u672A\u6539\u52A8;\u53EF\u8FD0\u884C npx csspilot ci init \u751F\u6210 TestPilot \u5DE5\u4F5C\u6D41");
32347
+ } else {
32348
+ console.log("\u2139 CI \u672A\u68C0\u6D4B\u5230 CI;\u53EF\u8FD0\u884C npx csspilot ci init \u751F\u6210\u6A21\u677F");
31631
32349
  }
31632
- };
32350
+ console.log("");
32351
+ const doctor = await runDoctor(root);
32352
+ printDoctor(doctor);
32353
+ console.log("\u4E0B\u4E00\u6B65:");
32354
+ console.log(" 1. \u8BA9 AI \u9605\u8BFB .agents/skills/testpilot/SKILL.md(\u9879\u76EE\u4E0A\u4E0B\u6587\u89C1 references/)");
32355
+ console.log(" 2. \u5728 tests/e2e/cases/ \u521B\u5EFA Case(\u9075\u5FAA references/test-conventions.md)");
32356
+ console.log(" 3. npx csspilot validate && npx csspilot run");
32357
+ return { project, adapters, config: config2, testStructure, skill, doctor };
32358
+ }
32359
+ function makeInitCommand() {
32360
+ return new Command("init").description("\u628A TestPilot \u63A5\u5165\u5F53\u524D\u4E1A\u52A1\u9879\u76EE(\u5E42\u7B49,\u53EF\u91CD\u590D\u6267\u884C)").option("--server <url>", "TestPilot Server \u5730\u5740(\u9ED8\u8BA4\u8BFB TESTPILOT_SERVER_URL / testpilot.yaml)").action(async (options) => {
32361
+ try {
32362
+ await runInit(process.cwd(), options.server ? { serverUrl: options.server } : {});
32363
+ } catch (err) {
32364
+ console.error(`\u2717 init \u5931\u8D25:${err instanceof Error ? err.message : String(err)}`);
32365
+ process.exitCode = 1;
32366
+ }
32367
+ });
32368
+ }
31633
32369
 
31634
- // src/commands/run.ts
31635
- function makeRunCommand() {
31636
- return new Command("run").description("\u6267\u884C\u6D4B\u8BD5\u7528\u4F8B(\u9ED8\u8BA4\u8FD0\u884C testpilot.yaml \u914D\u7F6E\u7684 Case)").argument("[paths...]", "\u7528\u4F8B\u6587\u4EF6\u6216\u76EE\u5F55,\u9ED8\u8BA4\u6309\u9879\u76EE\u914D\u7F6E").option("--tag <tag>", "\u6309\u6807\u7B7E\u8FC7\u6EE4\u7528\u4F8B").action(async (paths, options) => {
31637
- const config2 = await loadTestpilotConfig().catch((err) => {
32370
+ // src/commands/list.ts
32371
+ function makeListCommand() {
32372
+ return new Command("list").description("\u5217\u51FA\u6D4B\u8BD5\u7528\u4F8B").option("--tag <tag>", "\u6309\u6807\u7B7E\u8FC7\u6EE4").action(async (options) => {
32373
+ const client = new TestPilotClient();
32374
+ const infos = await client.listCases(void 0, options.tag).catch((err) => {
31638
32375
  console.error(err.message);
31639
32376
  process.exitCode = 1;
31640
32377
  return void 0;
31641
32378
  });
31642
- if (!config2) return;
31643
- const inputs = paths && paths.length > 0 ? paths : [config2.casesDir];
31644
- const files = await collectCaseFiles(inputs);
31645
- if (files.length === 0) {
31646
- console.error(`\u672A\u627E\u5230\u7528\u4F8B\u6587\u4EF6(\u67E5\u627E:${inputs.join(", ")})`);
32379
+ if (!infos) return;
32380
+ if (infos.length === 0) {
32381
+ const config2 = await client.getConfig();
32382
+ console.error(`\u672A\u627E\u5230\u7528\u4F8B\u76EE\u5F55 ${config2.casesDir}`);
32383
+ console.error("\u63D0\u793A:\u5148\u8FD0\u884C npx csspilot init \u63A5\u5165 TestPilot");
31647
32384
  process.exitCode = 1;
31648
32385
  return;
31649
32386
  }
31650
- const cases = [];
31651
- let invalid = 0;
31652
- let tagFiltered = 0;
31653
- for (const file2 of files) {
31654
- const source = await readFile5(file2, "utf8");
31655
- const result = validateCaseSource(source);
31656
- if (!result.ok || !result.data) {
31657
- invalid++;
31658
- console.log(`\u2717 ${file2}(\u6821\u9A8C\u672A\u901A\u8FC7,\u5DF2\u8DF3\u8FC7;\u8FD0\u884C npx csspilot validate \u67E5\u770B\u8BE6\u60C5)`);
31659
- continue;
31660
- }
31661
- if (options.tag && !(result.data.tags ?? []).includes(options.tag)) {
31662
- tagFiltered++;
31663
- continue;
32387
+ console.log("TestPilot Cases");
32388
+ console.log("");
32389
+ for (const item of infos) {
32390
+ if (item.valid) {
32391
+ const tags = item.case?.tags ?? [];
32392
+ const tagLabel = tags.length > 0 ? ` [${tags.join(", ")}]` : "";
32393
+ console.log(`\u2713 ${item.case?.id}${tagLabel}`);
32394
+ console.log(` ${item.file}`);
32395
+ } else {
32396
+ console.log(`\u2717 ${item.file}`);
32397
+ console.log(` ${item.issues[0]?.message ?? "\u89E3\u6790\u5931\u8D25"}`);
31664
32398
  }
31665
- cases.push({ data: result.data, file: file2 });
32399
+ console.log("");
32400
+ }
32401
+ const broken = infos.filter((item) => !item.valid).length;
32402
+ const brokenNote = broken > 0 ? `,${broken} \u4E2A\u6587\u4EF6\u89E3\u6790\u5931\u8D25` : "";
32403
+ const visible = infos.length - broken;
32404
+ console.log(`\u5171 ${visible} \u4E2A\u7528\u4F8B${options.tag ? `(tag: ${options.tag})` : ""}${brokenNote}`);
32405
+ });
32406
+ }
32407
+
32408
+ // src/commands/report.ts
32409
+ import { exec } from "node:child_process";
32410
+ function makeReportCommand() {
32411
+ return new Command("report").description("\u751F\u6210\u6D4B\u8BD5\u62A5\u544A(JSON + HTML)").option("--run <id>", "\u8FD0\u884C\u8BB0\u5F55 ID,\u9ED8\u8BA4\u6700\u8FD1\u4E00\u6B21").option("--open", "\u751F\u6210\u540E\u5728\u6D4F\u89C8\u5668\u6253\u5F00", false).action(async (options) => {
32412
+ const client = new TestPilotClient();
32413
+ try {
32414
+ const report = await client.generateReport(options.run);
32415
+ console.log(`\u2713 report.json ${report.json}`);
32416
+ console.log(`\u2713 report.html ${report.html}`);
32417
+ if (options.open) await openInBrowser(report.html);
32418
+ } catch (err) {
32419
+ console.error(err instanceof Error ? err.message : err);
32420
+ process.exitCode = 1;
31666
32421
  }
31667
- if (cases.length === 0) {
31668
- console.error("\u6CA1\u6709\u53EF\u6267\u884C\u7684\u7528\u4F8B");
32422
+ });
32423
+ }
32424
+ function openInBrowser(file2) {
32425
+ const command = process.platform === "win32" ? `start "" "${file2}"` : process.platform === "darwin" ? `open "${file2}"` : `xdg-open "${file2}"`;
32426
+ return new Promise((resolvePromise) => {
32427
+ exec(command, () => resolvePromise());
32428
+ });
32429
+ }
32430
+
32431
+ // src/commands/run.ts
32432
+ import { join as join26 } from "node:path";
32433
+ function makeRunCommand() {
32434
+ return new Command("run").description("\u6267\u884C\u6D4B\u8BD5\u7528\u4F8B(\u9ED8\u8BA4\u8FD0\u884C testpilot.yaml \u914D\u7F6E\u7684 Case)").argument("[paths...]", "\u7528\u4F8B\u6587\u4EF6\u6216\u76EE\u5F55,\u9ED8\u8BA4\u6309\u9879\u76EE\u914D\u7F6E").option("--tag <tag>", "\u6309\u6807\u7B7E\u8FC7\u6EE4\u7528\u4F8B").action(async (paths, options) => {
32435
+ const client = new TestPilotClient();
32436
+ try {
32437
+ const { summary, invalid, tagFiltered } = await client.runCases({
32438
+ paths,
32439
+ tag: options.tag,
32440
+ onEvent: consoleEventHandler
32441
+ });
32442
+ const notes = [
32443
+ invalid.length > 0 ? `${invalid.length} \u4E2A\u6821\u9A8C\u5931\u8D25\u8DF3\u8FC7` : "",
32444
+ tagFiltered > 0 ? `${tagFiltered} \u4E2A\u88AB --tag \u8FC7\u6EE4` : ""
32445
+ ].filter(Boolean).join(",");
32446
+ console.log("");
32447
+ console.log(
32448
+ `Run ${summary.runId}${summary.cancelled ? "(\u5DF2\u53D6\u6D88)" : ""}: ${summary.status.toUpperCase()} \u2014 \u7528\u4F8B \u2713${summary.totals.passed} \u2717${summary.totals.failed},\u6B65\u9AA4 \u2713${summary.totals.stepsPassed} \u2717${summary.totals.stepsFailed} \u21B7${summary.totals.stepsSkipped}${notes ? `(${notes})` : ""}`
32449
+ );
32450
+ console.log(`\u4EA7\u7269\u76EE\u5F55:${join26(".testpilot", "artifacts", "runs", summary.runId)}`);
32451
+ console.log("\u67E5\u770B\u62A5\u544A:npx csspilot report");
32452
+ if (summary.status === "failed") process.exitCode = 1;
32453
+ } catch (err) {
32454
+ console.error(err instanceof Error ? err.message : err);
31669
32455
  process.exitCode = 1;
31670
- return;
31671
32456
  }
31672
- const resolver = new AdapterResolver();
31673
- resolver.register(playwrightAdapterFactory({ baseUrl: config2.web?.baseUrl }));
31674
- resolver.register(
31675
- wechatideAdapterFactory({
31676
- projectPath: config2.miniapp?.projectPath,
31677
- cliPath: config2.miniapp?.cliPath
31678
- })
31679
- );
31680
- const runner = new TestRunner({ resolver, onEvent: consoleEventHandler });
31681
- const notes = [
31682
- invalid > 0 ? `${invalid} \u4E2A\u6821\u9A8C\u5931\u8D25\u8DF3\u8FC7` : "",
31683
- tagFiltered > 0 ? `${tagFiltered} \u4E2A\u88AB --tag \u8FC7\u6EE4` : ""
31684
- ].filter(Boolean).join(",");
31685
- console.log(`\u8FD0\u884C ${cases.length} \u4E2A\u7528\u4F8B${notes ? `(${notes})` : ""}
31686
- `);
31687
- const summary = await runner.run(cases);
31688
- console.log("");
31689
- console.log(
31690
- `Run ${summary.runId}: ${summary.status.toUpperCase()} \u2014 \u7528\u4F8B \u2713${summary.totals.passed} \u2717${summary.totals.failed},\u6B65\u9AA4 \u2713${summary.totals.stepsPassed} \u2717${summary.totals.stepsFailed} \u21B7${summary.totals.stepsSkipped}`
31691
- );
31692
- console.log(`\u4EA7\u7269\u76EE\u5F55:${join16(".testpilot", "artifacts", "runs", summary.runId)}`);
31693
- console.log("\u67E5\u770B\u62A5\u544A:npx csspilot report");
31694
- if (summary.status === "failed") process.exitCode = 1;
31695
32457
  });
31696
32458
  }
31697
32459
  function consoleEventHandler(event) {
31698
32460
  switch (event.type) {
32461
+ case "run-started":
32462
+ console.log(`\u8FD0\u884C ${event.totalCases} \u4E2A\u7528\u4F8B
32463
+ `);
32464
+ break;
31699
32465
  case "case-started":
31700
32466
  console.log(`\u25B6 ${event.caseId} (${event.file})`);
31701
32467
  break;
@@ -31711,49 +32477,117 @@ function consoleEventHandler(event) {
31711
32477
  }
31712
32478
  }
31713
32479
 
32480
+ // src/commands/sync-metadata.ts
32481
+ import { relative } from "node:path";
32482
+ function makeSyncMetadataCommand() {
32483
+ return new Command("sync-metadata").description("\u540C\u6B65 Case Metadata \u5FEB\u7167\u5230 TestPilot Server(CI / git push \u540E\u4F7F\u7528)").option("--server <url>", "TestPilot Server \u5730\u5740(\u9ED8\u8BA4\u53D6 project.json \u6216 testpilot.yaml)").action(async (options) => {
32484
+ const client = new TestPilotClient();
32485
+ const link = await client.getProjectLink();
32486
+ if (!link) {
32487
+ console.error("\u672A\u627E\u5230 .testpilot/project.json(\u5148\u8FD0\u884C npx csspilot init \u5173\u8054\u9879\u76EE)");
32488
+ process.exitCode = 1;
32489
+ return;
32490
+ }
32491
+ const config2 = await client.getConfig().catch(() => void 0);
32492
+ const serverUrl = options.server ?? process.env.TESTPILOT_SERVER_URL ?? link.serverUrl ?? config2?.server?.baseUrl;
32493
+ if (!serverUrl) {
32494
+ console.error("\u672A\u914D\u7F6E TestPilot Server \u5730\u5740(testpilot.yaml server.baseUrl \u6216 TESTPILOT_SERVER_URL)");
32495
+ process.exitCode = 1;
32496
+ return;
32497
+ }
32498
+ const git = await readGitInfo(process.cwd());
32499
+ if (!git.commit || !git.branch) {
32500
+ console.error("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93(\u6216\u6CA1\u6709\u4EFB\u4F55\u63D0\u4EA4);sync-metadata \u4EE5 Git Commit \u4E3A\u540C\u6B65\u5355\u5143");
32501
+ process.exitCode = 1;
32502
+ return;
32503
+ }
32504
+ const infos = await client.listCases();
32505
+ const cases = infos.filter((item) => item.valid && item.case).map((item) => ({
32506
+ id: item.case.id,
32507
+ title: item.case.name,
32508
+ file: relative(process.cwd(), item.file).split("\\").join("/"),
32509
+ tags: item.case.tags ?? []
32510
+ }));
32511
+ const skipped = infos.length - cases.length;
32512
+ const numericId = /(\d+)$/.exec(link.projectId ?? "")?.[1];
32513
+ if (!numericId) {
32514
+ console.error(
32515
+ `\u9879\u76EE\u5173\u8054 ${link.projectId} \u4E0D\u662F Server \u6CE8\u518C\u7684\u9879\u76EE(\u672C\u5730\u6A21\u5F0F);\u8BF7\u91CD\u65B0\u8FD0\u884C npx csspilot init \u5E76\u914D\u7F6E server.baseUrl`
32516
+ );
32517
+ process.exitCode = 1;
32518
+ return;
32519
+ }
32520
+ try {
32521
+ const res = await fetch(
32522
+ `${serverUrl.replace(/\/$/, "")}/api/projects/${numericId}/cases/sync`,
32523
+ {
32524
+ method: "POST",
32525
+ headers: { "content-type": "application/json" },
32526
+ body: JSON.stringify({
32527
+ repository: git.repositoryUrl,
32528
+ branch: git.branch,
32529
+ commit: git.commit,
32530
+ cases
32531
+ })
32532
+ }
32533
+ );
32534
+ if (!res.ok) {
32535
+ throw new Error(`${res.status} ${(await res.text()).slice(0, 200)}`);
32536
+ }
32537
+ const result = await res.json();
32538
+ console.log(`\u2713 \u5DF2\u540C\u6B65 ${serverUrl}`);
32539
+ console.log(` \u5206\u652F/\u63D0\u4EA4:${result.branch} \xB7 ${result.commit.slice(0, 7)}`);
32540
+ console.log(
32541
+ ` \u65B0\u589E ${result.added} \xB7 \u66F4\u65B0 ${result.updated} \xB7 \u5220\u9664 ${result.deleted},\u5F53\u524D active \u5171 ${result.activeTotal} \u4E2A`
32542
+ );
32543
+ if (skipped > 0) console.log(` (\u8DF3\u8FC7 ${skipped} \u4E2A\u6821\u9A8C\u5931\u8D25\u7684\u7528\u4F8B\u6587\u4EF6)`);
32544
+ } catch (err) {
32545
+ console.error(`\u2717 \u540C\u6B65\u5931\u8D25:${err instanceof Error ? err.message : err}`);
32546
+ process.exitCode = 1;
32547
+ }
32548
+ });
32549
+ }
32550
+
31714
32551
  // src/commands/validate.ts
31715
- import { readFile as readFile6 } from "node:fs/promises";
31716
32552
  function makeValidateCommand() {
31717
32553
  return new Command("validate").description("\u6821\u9A8C\u7528\u4F8B DSL").argument("[paths...]", "\u7528\u4F8B\u6587\u4EF6\u6216\u76EE\u5F55,\u9ED8\u8BA4\u6309\u9879\u76EE\u914D\u7F6E").action(async (paths) => {
31718
- const config2 = await loadTestpilotConfig().catch((err) => {
32554
+ const client = new TestPilotClient();
32555
+ const infos = await client.listCases(paths).catch((err) => {
31719
32556
  console.error(err.message);
31720
32557
  process.exitCode = 1;
31721
32558
  return void 0;
31722
32559
  });
31723
- if (!config2) return;
31724
- const inputs = paths && paths.length > 0 ? paths : [config2.casesDir];
31725
- const files = await collectCaseFiles(inputs);
31726
- if (files.length === 0) {
31727
- console.error(`\u672A\u627E\u5230\u7528\u4F8B\u6587\u4EF6(\u67E5\u627E:${inputs.join(", ")})`);
32560
+ if (!infos) return;
32561
+ if (infos.length === 0) {
32562
+ console.error(`\u672A\u627E\u5230\u7528\u4F8B\u6587\u4EF6(\u67E5\u627E:${(paths ?? []).join(", ") || "\u9879\u76EE\u914D\u7F6E\u7684 casesDir"})`);
31728
32563
  console.error("\u63D0\u793A:\u5148\u8FD0\u884C npx csspilot init \u63A5\u5165 TestPilot");
31729
32564
  process.exitCode = 1;
31730
32565
  return;
31731
32566
  }
31732
32567
  let failed = 0;
31733
- for (const file2 of files) {
31734
- const source = await readFile6(file2, "utf8");
31735
- const result = validateCaseSource(source);
31736
- if (result.ok) {
31737
- console.log(`\u2713 ${result.data?.id ?? "(unknown)"} ${file2}`);
32568
+ for (const item of infos) {
32569
+ if (item.valid) {
32570
+ console.log(`\u2713 ${item.case?.id ?? "(unknown)"} ${item.file}`);
31738
32571
  } else {
31739
32572
  failed++;
31740
- console.log(`\u2717 ${file2}`);
31741
- for (const issue2 of result.issues) {
32573
+ console.log(`\u2717 ${item.file}`);
32574
+ for (const issue2 of item.issues) {
31742
32575
  const prefix = issue2.code === "yaml" ? "" : `${issue2.path}: `;
31743
32576
  console.log(` - ${prefix}${issue2.message}`);
31744
32577
  }
31745
32578
  }
31746
32579
  }
31747
32580
  console.log("");
31748
- console.log(`${files.length - failed}/${files.length} \u4E2A\u7528\u4F8B\u901A\u8FC7\u6821\u9A8C`);
32581
+ console.log(`${infos.length - failed}/${infos.length} \u4E2A\u7528\u4F8B\u901A\u8FC7\u6821\u9A8C`);
31749
32582
  if (failed > 0) process.exitCode = 1;
31750
32583
  });
31751
32584
  }
31752
32585
 
31753
32586
  // src/cli.ts
32587
+ var CLI_VERSION = "0.2.0";
31754
32588
  async function createCli() {
31755
32589
  const program2 = new Command();
31756
- program2.name("csspilot").description("TestPilot \u2014 AI Native \u8DE8\u7AEF\u4E1A\u52A1\u6D4B\u8BD5\u57FA\u7840\u8BBE\u65BD").version("0.1.0").addCommand(makeInitCommand()).addCommand(makeValidateCommand()).addCommand(makeListCommand()).addCommand(makeRunCommand()).addCommand(makeReportCommand()).addCommand(makeDoctorCommand());
32590
+ program2.name("csspilot").description("TestPilot \u2014 AI Native \u8DE8\u7AEF\u4E1A\u52A1\u6D4B\u8BD5\u57FA\u7840\u8BBE\u65BD CLI").version(CLI_VERSION).addCommand(makeInitCommand()).addCommand(makeValidateCommand()).addCommand(makeListCommand()).addCommand(makeRunCommand()).addCommand(makeReportCommand()).addCommand(makeSyncMetadataCommand()).addCommand(makeDoctorCommand()).addCommand(makeCiCommand());
31757
32591
  return program2;
31758
32592
  }
31759
32593
  export {