@hamsterbase/evidra 0.2.0 → 0.3.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.
Files changed (42) hide show
  1. package/dist/sdk/conformance-rules.js +1454 -0
  2. package/dist/sdk/conformance.js +5 -0
  3. package/dist/sdk/index.d.ts +10 -0
  4. package/dist/sdk/main.js +65 -37
  5. package/dist/sdk/rules.d.ts +149 -0
  6. package/dist/sdk/types-B6cBsknY.d.ts +12 -0
  7. package/dist/service/cli.js +697 -332
  8. package/dist/web/assets/{cssMode-C0YhK9yk.js → cssMode-N9cXKwMi.js} +1 -1
  9. package/dist/web/assets/{editor.api-CMNmRHg7.js → editor.api-DQVi2UMW.js} +1 -1
  10. package/dist/web/assets/{freemarker2-BPF-_qAr.js → freemarker2-Bvgs91Zz.js} +1 -1
  11. package/dist/web/assets/{handlebars-ZZYTfRBR.js → handlebars-BjYNaKwZ.js} +1 -1
  12. package/dist/web/assets/{html-Dgtv0wV7.js → html-DYaGhp1Y.js} +1 -1
  13. package/dist/web/assets/{htmlMode-CE3TDKC3.js → htmlMode-Cytjzdia.js} +1 -1
  14. package/dist/web/assets/index-C1ua-VrZ.css +2 -0
  15. package/dist/web/assets/index-CnwObt1E.js +35 -0
  16. package/dist/web/assets/{javascript-v3U6PHk8.js → javascript-BG3RI78V.js} +1 -1
  17. package/dist/web/assets/{jsonMode-CRbfEt8i.js → jsonMode-tKunAGWo.js} +1 -1
  18. package/dist/web/assets/{liquid-D_mEV4oV.js → liquid-CyQio9RN.js} +1 -1
  19. package/dist/web/assets/{lspLanguageFeatures-DX6MhoAE.js → lspLanguageFeatures-CkQ_7-NP.js} +1 -1
  20. package/dist/web/assets/{mdx-BhVFxchM.js → mdx-C7agFNoG.js} +1 -1
  21. package/dist/web/assets/{monaco-C2bEmNwl.js → monaco-CdRk6sx6.js} +4 -4
  22. package/dist/web/assets/{python-BWAEzptE.js → python-Xk-DSDx5.js} +1 -1
  23. package/dist/web/assets/{razor-fGgHB_D8.js → razor-SQg0PKrI.js} +1 -1
  24. package/dist/web/assets/{tsMode-Dhqndf6Y.js → tsMode-njI9r4C-.js} +1 -1
  25. package/dist/web/assets/{typescript-BdctO1F-.js → typescript-BHUW13-O.js} +1 -1
  26. package/dist/web/assets/{workers-CL1LWpiD.js → workers-ZUzAKd5C.js} +1 -1
  27. package/dist/web/assets/{xml-h8WCDUbN.js → xml-B6qKvuxn.js} +1 -1
  28. package/dist/web/assets/{yaml-Dh4FUWeU.js → yaml-BhUHqKCu.js} +1 -1
  29. package/dist/web/index.html +2 -2
  30. package/package.json +15 -6
  31. package/packages/conformance/rules/commit-message/RULE.md +29 -0
  32. package/packages/conformance/rules/duplicate-localization/RULE.md +37 -0
  33. package/packages/conformance/rules/e2e-scenarios-structure/RULE.md +39 -0
  34. package/packages/conformance/rules/index.md +18 -0
  35. package/packages/conformance/rules/same-dir-import-only/RULE.md +35 -0
  36. package/packages/conformance/rules/single-component-file/RULE.md +33 -0
  37. package/packages/conformance/rules/source-locale-defaults/RULE.md +48 -0
  38. package/packages/conformance/rules/sync-locales/RULE.md +45 -0
  39. package/packages/conformance/rules/ui-scenarios-structure/RULE.md +43 -0
  40. package/skills/evidra/SKILL.md +8 -3
  41. package/dist/web/assets/index-D_0ZWPum.js +0 -37
  42. package/dist/web/assets/index-U9oKSlEO.css +0 -2
@@ -1,6 +1,6 @@
1
1
  // packages/service/src/cli.ts
2
2
  import { cac } from "cac";
3
- import path30 from "node:path";
3
+ import path33 from "node:path";
4
4
 
5
5
  // modules/core/implementations/Functions/resolveConfig.ts
6
6
  import path3 from "node:path";
@@ -29,10 +29,22 @@ var NamespaceSchema = z3.object({
29
29
  id: z3.string().regex(/^[A-Za-z0-9-]+$/),
30
30
  name: z3.string().trim().min(1)
31
31
  });
32
+ var ChangeConfigSchema = z3.object({
33
+ scope: z3.union([
34
+ z3.array(z3.string().trim().min(1)),
35
+ z3.string().transform(
36
+ (value) => value.split(",").map((scope) => scope.trim()).filter(Boolean)
37
+ )
38
+ ]).default([]).transform((scopes) => [...new Set(scopes)]),
39
+ notedir: z3.string().trim().min(1).default("changelog-notes"),
40
+ /** 更新日志读取的本地分支。 */
41
+ branch: z3.string().trim().min(1).default("main")
42
+ });
32
43
  var ConfigSchema = z3.object({
33
44
  reportDir: z3.string().min(1).optional(),
34
45
  storage: z3.enum(["s3", "local"]).default("local"),
35
- namespaces: z3.array(NamespaceSchema)
46
+ namespaces: z3.array(NamespaceSchema),
47
+ change: ChangeConfigSchema.optional()
36
48
  });
37
49
 
38
50
  // modules/core/implementations/config.ts
@@ -55,7 +67,8 @@ function parseConfig(config) {
55
67
  return {
56
68
  reportDir: dir,
57
69
  storage: value.storage,
58
- namespaces: value.namespaces.map(({ id, name }) => ({ id, name }))
70
+ namespaces: value.namespaces.map(({ id, name }) => ({ id, name })),
71
+ ...value.change ? { change: value.change } : {}
59
72
  };
60
73
  }
61
74
 
@@ -295,7 +308,7 @@ import { readFile as readFile4, readdir } from "node:fs/promises";
295
308
  import path8 from "node:path";
296
309
 
297
310
  // modules/core/contracts/taskRecord.ts
298
- var TASK_SCEHAM_VERSION = 3;
311
+ var TASK_SCHEMA_VERSION = 3;
299
312
 
300
313
  // modules/core/implementations/Utils/readJson.ts
301
314
  import { readFile as readFile3 } from "node:fs/promises";
@@ -327,7 +340,7 @@ async function writeJsonAtomic(file, value) {
327
340
  // modules/core/implementations/Utils/readTaskRecord.ts
328
341
  async function readTaskRecord(file) {
329
342
  const manifest = JSON.parse(await readFile4(file, "utf8"));
330
- if ((manifest.formatVersion ?? 0) < TASK_SCEHAM_VERSION)
343
+ if ((manifest.formatVersion ?? 0) < TASK_SCHEMA_VERSION)
331
344
  throw new Error("\u62A5\u544A\u683C\u5F0F\u4E0D\u652F\u6301\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C\u6D4B\u8BD5");
332
345
  const directory = path8.join(path8.dirname(file), "cases");
333
346
  const files = (await readdir(directory)).filter((name) => name.endsWith(".json")).sort();
@@ -461,8 +474,6 @@ var CompareTaskInputSchema = z8.object({ repoRoot: z8.string(), taskId: z8.strin
461
474
  // modules/core/implementations/internal/compare.ts
462
475
  import { access } from "node:fs/promises";
463
476
  import path13 from "node:path";
464
- import pixelmatch from "pixelmatch";
465
- import { PNG } from "pngjs";
466
477
 
467
478
  // modules/core/contracts/internal/compare.ts
468
479
  import { z as z9 } from "zod";
@@ -480,6 +491,25 @@ async function download(_cwd, storage, key) {
480
491
  return Buffer.from(await storage.download(key));
481
492
  }
482
493
 
494
+ // modules/core/implementations/Utils/imageDiff.ts
495
+ import pixelmatch from "pixelmatch";
496
+ import { PNG } from "pngjs";
497
+ function diffPng(png, match, oldBytes, newBytes) {
498
+ const oldImage = png.sync.read(Buffer.from(oldBytes));
499
+ const newImage = png.sync.read(Buffer.from(newBytes));
500
+ if (oldImage.width !== newImage.width || oldImage.height !== newImage.height) {
501
+ return { dimensionMismatch: true };
502
+ }
503
+ const diff = new png({ width: oldImage.width, height: oldImage.height });
504
+ const diffPixels = match(oldImage.data, newImage.data, diff.data, diff.width, diff.height, {
505
+ threshold: 0.1
506
+ });
507
+ return { diffPixels, png: png.sync.write(diff) };
508
+ }
509
+ function localImageDiff(oldBytes, newBytes) {
510
+ return diffPng(PNG, pixelmatch, oldBytes, newBytes);
511
+ }
512
+
483
513
  // modules/core/implementations/Utils/imageDiffPool.ts
484
514
  import { createRequire } from "node:module";
485
515
  import { Worker } from "node:worker_threads";
@@ -492,24 +522,11 @@ const { PNG } = require(workerData.pngjsPath);
492
522
  const pixelmatchModule = require(workerData.pixelmatchPath);
493
523
  const pixelmatch = pixelmatchModule.default || pixelmatchModule;
494
524
 
525
+ const diffPng = ${diffPng.toString()};
526
+
495
527
  parentPort.on('message', ({ id, oldBytes, newBytes }) => {
496
528
  try {
497
- const oldImage = PNG.sync.read(Buffer.from(oldBytes));
498
- const newImage = PNG.sync.read(Buffer.from(newBytes));
499
- if (oldImage.width !== newImage.width || oldImage.height !== newImage.height) {
500
- parentPort.postMessage({ id, dimensionMismatch: true });
501
- return;
502
- }
503
- const diff = new PNG({ width: oldImage.width, height: oldImage.height });
504
- const diffPixels = pixelmatch(
505
- oldImage.data,
506
- newImage.data,
507
- diff.data,
508
- diff.width,
509
- diff.height,
510
- { threshold: 0.1 },
511
- );
512
- parentPort.postMessage({ id, diffPixels, png: PNG.sync.write(diff) });
529
+ parentPort.postMessage({ id, ...diffPng(PNG, pixelmatch, oldBytes, newBytes) });
513
530
  } catch (error) {
514
531
  parentPort.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
515
532
  }
@@ -938,18 +955,6 @@ async function imageDiff(oldBytes, newBytes, pool) {
938
955
  }
939
956
  return localImageDiff(oldBytes, newBytes);
940
957
  }
941
- function localImageDiff(oldBytes, newBytes) {
942
- const oldImage = PNG.sync.read(Buffer.from(oldBytes));
943
- const newImage = PNG.sync.read(Buffer.from(newBytes));
944
- if (oldImage.width !== newImage.width || oldImage.height !== newImage.height) {
945
- return { dimensionMismatch: true };
946
- }
947
- const diff = new PNG({ width: oldImage.width, height: oldImage.height });
948
- const diffPixels = pixelmatch(oldImage.data, newImage.data, diff.data, diff.width, diff.height, {
949
- threshold: 0.1
950
- });
951
- return { diffPixels, png: PNG.sync.write(diff) };
952
- }
953
958
 
954
959
  // modules/core/implementations/repository.ts
955
960
  import path15 from "node:path";
@@ -1114,9 +1119,6 @@ async function compareTask(input) {
1114
1119
  return compare({ taskId }, reportDir, reportDir, storageFor(reportDir, root));
1115
1120
  }
1116
1121
 
1117
- // modules/core/implementations/Functions/approve.ts
1118
- import path18 from "node:path";
1119
-
1120
1122
  // modules/core/contracts/functions/approve.ts
1121
1123
  import { z as z11 } from "zod";
1122
1124
  var ApproveInputSchema = z11.object({
@@ -1169,7 +1171,7 @@ async function readBaseline(root, namespace) {
1169
1171
  }
1170
1172
 
1171
1173
  // modules/core/implementations/internal/updateBaseline.ts
1172
- import { mkdir as mkdir3, readdir as readdir2, rm as rm3 } from "node:fs/promises";
1174
+ import { readdir as readdir2, rm as rm3 } from "node:fs/promises";
1173
1175
  import path17 from "node:path";
1174
1176
 
1175
1177
  // modules/core/contracts/internal/updateBaseline.ts
@@ -1201,7 +1203,7 @@ function canonical2(value) {
1201
1203
  }
1202
1204
 
1203
1205
  // modules/core/implementations/internal/updateBaseline.ts
1204
- async function updateBaselineUnlocked(input, cwd, baselineRoot, storage, concurrency = 1) {
1206
+ async function updateBaseline(input, cwd, baselineRoot, storage, concurrency = 1) {
1205
1207
  const value = UpdateBaselineInputSchema.parse(input);
1206
1208
  const directory = taskDirectory(cwd, value.taskPath);
1207
1209
  const record = await readTaskRecord(path17.join(directory, "task.json"));
@@ -1303,10 +1305,14 @@ async function updateBaselineUnlocked(input, cwd, baselineRoot, storage, concurr
1303
1305
  };
1304
1306
  const { approvedAt: _approvedAt, ...content } = entry;
1305
1307
  const filename = `baseline-${hash(canonical2(content))}.json`;
1308
+ const superseded = await readdir2(paths.directory).catch((error) => {
1309
+ if (error.code === "ENOENT") return [];
1310
+ throw error;
1311
+ });
1306
1312
  await writeJsonAtomic(path17.join(paths.directory, filename), entry);
1307
- for (const file of await readdir2(paths.directory)) {
1313
+ for (const file of superseded) {
1308
1314
  if (file !== filename && /^baseline(?:-[a-f0-9]{64})?\.json$/.test(file)) {
1309
- await rm3(path17.join(paths.directory, file));
1315
+ await rm3(path17.join(paths.directory, file), { force: true });
1310
1316
  }
1311
1317
  }
1312
1318
  const caseFile = [...casePath, filename].join("/");
@@ -1331,41 +1337,8 @@ async function updateBaselineUnlocked(input, cwd, baselineRoot, storage, concurr
1331
1337
  comparison: nextComparison
1332
1338
  };
1333
1339
  }
1334
- var writes = /* @__PURE__ */ new Map();
1335
- async function updateBaseline(input, cwd, baselineRoot, storage, concurrency = 1) {
1336
- const key = path17.resolve(baselineRoot);
1337
- const next = (writes.get(key) ?? Promise.resolve()).then(async () => {
1338
- const lock = path17.join(baselineRoot, "cache", "baseline-write.lock");
1339
- await mkdir3(path17.dirname(lock), { recursive: true });
1340
- const deadline = Date.now() + 3e4;
1341
- for (; ; ) {
1342
- try {
1343
- await mkdir3(lock);
1344
- break;
1345
- } catch (error) {
1346
- if (error.code !== "EEXIST") throw error;
1347
- if (Date.now() >= deadline) throw new Error("\u57FA\u7EBF\u5199\u5165\u9501\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5\u662F\u5426\u6709\u4E2D\u65AD\u7684\u5199\u5165");
1348
- await new Promise((resolve) => setTimeout(resolve, 20));
1349
- }
1350
- }
1351
- try {
1352
- return await updateBaselineUnlocked(input, cwd, baselineRoot, storage, concurrency);
1353
- } finally {
1354
- await rm3(lock, { recursive: true, force: true });
1355
- }
1356
- });
1357
- const settled = next.catch(() => {
1358
- });
1359
- writes.set(key, settled);
1360
- try {
1361
- return await next;
1362
- } finally {
1363
- if (writes.get(key) === settled) writes.delete(key);
1364
- }
1365
- }
1366
1340
 
1367
1341
  // modules/core/implementations/Functions/approve.ts
1368
- var approvals = /* @__PURE__ */ new Map();
1369
1342
  async function approve(input) {
1370
1343
  const {
1371
1344
  repoRoot: root,
@@ -1374,33 +1347,24 @@ async function approve(input) {
1374
1347
  baselineVersion: expectedVersion
1375
1348
  } = ApproveInputSchema.parse(input);
1376
1349
  const task = await readTask(root, taskId);
1377
- const key = path18.join(root, task.namespace);
1378
- const next = (approvals.get(key) ?? Promise.resolve()).then(async () => {
1379
- if (!task.finishedAt) throw new Error("\u4EFB\u52A1\u5C1A\u672A\u7ED3\u675F");
1380
- if (!ids.length || new Set(ids).size !== ids.length) throw new Error("\u5BA1\u6279\u7528\u4F8B\u5217\u8868\u4E3A\u7A7A\u6216\u91CD\u590D");
1381
- const reportDir = await reportRoot(root);
1382
- if (await readBaselineVersion(reportDir, task.namespace) !== expectedVersion)
1383
- return { conflict: true, comparison: await compareTask({ repoRoot: root, taskId }) };
1384
- const comparison = await compareTask({ repoRoot: root, taskId });
1385
- const cases = ids.map((id) => {
1386
- const diff = comparison.cases.find((item) => item.id === id);
1387
- if (!diff) throw new Error("\u7528\u4F8B\u4E0D\u53EF\u5BA1\u6279");
1388
- return { id, baselineHash: diff.baselineHash ?? null };
1389
- });
1390
- const result = await updateBaseline(
1391
- { taskPath: await taskPathOf(root, taskId), cases, baselineVersion: expectedVersion },
1392
- reportDir,
1393
- reportDir,
1394
- storageFor(reportDir, root)
1395
- );
1396
- return { conflict: result.conflict, comparison: result.comparison };
1350
+ if (!task.finishedAt) throw new Error("\u4EFB\u52A1\u5C1A\u672A\u7ED3\u675F");
1351
+ if (!ids.length || new Set(ids).size !== ids.length) throw new Error("\u5BA1\u6279\u7528\u4F8B\u5217\u8868\u4E3A\u7A7A\u6216\u91CD\u590D");
1352
+ const reportDir = await reportRoot(root);
1353
+ if (await readBaselineVersion(reportDir, task.namespace) !== expectedVersion)
1354
+ return { conflict: true, comparison: await compareTask({ repoRoot: root, taskId }) };
1355
+ const comparison = await compareTask({ repoRoot: root, taskId });
1356
+ const cases = ids.map((id) => {
1357
+ const diff = comparison.cases.find((item) => item.id === id);
1358
+ if (!diff) throw new Error("\u7528\u4F8B\u4E0D\u53EF\u5BA1\u6279");
1359
+ return { id, baselineHash: diff.baselineHash ?? null };
1397
1360
  });
1398
- approvals.set(
1399
- key,
1400
- next.catch(() => {
1401
- })
1361
+ const result = await updateBaseline(
1362
+ { taskPath: await taskPathOf(root, taskId), cases, baselineVersion: expectedVersion },
1363
+ reportDir,
1364
+ reportDir,
1365
+ storageFor(reportDir, root)
1402
1366
  );
1403
- return next;
1367
+ return { conflict: result.conflict, comparison: result.comparison };
1404
1368
  }
1405
1369
 
1406
1370
  // modules/core/contracts/functions/reviewCodeChanges.ts
@@ -1413,17 +1377,14 @@ var ReviewCodeChangesInputSchema = z13.object({
1413
1377
  reviewed: z13.boolean()
1414
1378
  });
1415
1379
 
1416
- // modules/core/implementations/Functions/reviewCodeChanges.ts
1417
- import { realpath as realpath3 } from "node:fs/promises";
1418
-
1419
1380
  // modules/core/implementations/gitChanges.ts
1420
1381
  import { createHash as createHash3 } from "node:crypto";
1421
1382
  import { createReadStream } from "node:fs";
1422
1383
  import { lstat, readlink, realpath } from "node:fs/promises";
1423
- import path19 from "node:path";
1384
+ import path18 from "node:path";
1424
1385
 
1425
1386
  // modules/core/implementations/git.ts
1426
- import { execFile } from "node:child_process";
1387
+ import { execFile, spawn } from "node:child_process";
1427
1388
  function runGit(repoRoot, args, timeoutMs = 2e4) {
1428
1389
  return new Promise((resolve) => {
1429
1390
  execFile(
@@ -1448,6 +1409,26 @@ async function gitOptional(repoRoot, args) {
1448
1409
  async function resolveRef(repoRoot, ref) {
1449
1410
  return gitOptional(repoRoot, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
1450
1411
  }
1412
+ function gitCatFileBatch(repoRoot, oids) {
1413
+ return new Promise((resolve, reject) => {
1414
+ const child = spawn("git", ["-C", repoRoot, "cat-file", "--batch"], {
1415
+ stdio: ["pipe", "pipe", "pipe"],
1416
+ timeout: 6e4,
1417
+ windowsHide: true
1418
+ });
1419
+ const chunks = [];
1420
+ let stderr = "";
1421
+ child.stdout.on("data", (chunk) => chunks.push(chunk));
1422
+ child.stderr.on("data", (chunk) => stderr += chunk);
1423
+ child.on("error", reject);
1424
+ child.on(
1425
+ "close",
1426
+ (code) => code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(stderr.trim() || `git cat-file \u9000\u51FA\u7801 ${code}`))
1427
+ );
1428
+ child.stdin.on("error", reject);
1429
+ child.stdin.end(oids.join("\n") + "\n");
1430
+ });
1431
+ }
1451
1432
 
1452
1433
  // modules/core/implementations/gitChanges.ts
1453
1434
  var MAX_BYTES = 256 * 1024;
@@ -1493,20 +1474,20 @@ function fileDigest(file) {
1493
1474
  });
1494
1475
  }
1495
1476
  async function worktreeSide(repo, file) {
1496
- const absolute = path19.resolve(repo, file);
1497
- const parent = await realpath(path19.dirname(absolute));
1498
- const relative = path19.relative(repo, parent);
1499
- if (relative === ".." || relative.startsWith(`..${path19.sep}`) || path19.isAbsolute(relative))
1477
+ const absolute = path18.resolve(repo, file);
1478
+ const parent = await realpath(path18.dirname(absolute));
1479
+ const relative = path18.relative(repo, parent);
1480
+ if (relative === ".." || relative.startsWith(`..${path18.sep}`) || path18.isAbsolute(relative))
1500
1481
  throw new Error("\u6587\u4EF6\u4E0D\u5728\u4ED3\u5E93\u5185");
1501
- const stat3 = await lstat(absolute);
1502
- if (stat3.isSymbolicLink()) return { mode: "120000", hash: hash(await readlink(absolute)) };
1503
- if (stat3.isDirectory()) {
1482
+ const stat4 = await lstat(absolute);
1483
+ if (stat4.isSymbolicLink()) return { mode: "120000", hash: hash(await readlink(absolute)) };
1484
+ if (stat4.isDirectory()) {
1504
1485
  const commit = (await git(absolute, ["rev-parse", "HEAD"])).trim();
1505
1486
  return { mode: "160000", hash: hash(`Subproject commit ${commit}
1506
1487
  `) };
1507
1488
  }
1508
1489
  return {
1509
- mode: stat3.mode & 73 ? "100755" : "100644",
1490
+ mode: stat4.mode & 73 ? "100755" : "100644",
1510
1491
  hash: await fileDigest(absolute)
1511
1492
  };
1512
1493
  }
@@ -1522,103 +1503,72 @@ function reviewKey(change, after) {
1522
1503
  })
1523
1504
  );
1524
1505
  }
1525
- function publicChange(change, after) {
1506
+ async function collectCodeChanges(root, ref) {
1507
+ const { sha, files } = await collectChanges(root, ref);
1508
+ const repo = await realpath(root);
1526
1509
  return {
1527
- path: change.path,
1528
- ...change.oldPath ? { oldPath: change.oldPath } : {},
1529
- status: change.status,
1530
- reviewKey: reviewKey(change, after)
1510
+ sha,
1511
+ files: await mapLimit(files, 16, async (change) => ({
1512
+ path: change.path,
1513
+ ...change.oldPath ? { oldPath: change.oldPath } : {},
1514
+ status: change.status,
1515
+ reviewKey: reviewKey(
1516
+ change,
1517
+ change.status === "deleted" ? null : await worktreeSide(repo, change.path)
1518
+ )
1519
+ }))
1531
1520
  };
1532
1521
  }
1533
1522
  async function reviewFile(root) {
1534
- return path19.join(await reportRoot(root), "cache", "reviews", "code.json");
1523
+ return path18.join(await reportRoot(root), "cache", "reviews", "code.json");
1535
1524
  }
1536
1525
  async function readReviews(root) {
1537
1526
  return await readJson(await reviewFile(root)) ?? {};
1538
1527
  }
1539
1528
 
1540
- // modules/core/implementations/Functions/getGitChanges.ts
1541
- import { realpath as realpath2 } from "node:fs/promises";
1542
-
1543
- // modules/core/contracts/functions/getGitChanges.ts
1544
- import { z as z14 } from "zod";
1545
- var GetGitChangesInputSchema = z14.object({ repoRoot: z14.string(), ref: z14.string() });
1546
-
1547
- // modules/core/implementations/Functions/getGitChanges.ts
1548
- async function getGitChanges(input) {
1549
- const { repoRoot: root, ref } = GetGitChangesInputSchema.parse(input);
1550
- const { sha, files } = await collectChanges(root, ref);
1551
- const repo = await realpath2(root);
1552
- const reviews = await readReviews(root);
1553
- const changes = [];
1554
- for (const change of files) {
1555
- const after = change.status === "deleted" ? null : await worktreeSide(repo, change.path);
1556
- changes.push(publicChange(change, after));
1557
- }
1558
- const keys = new Set(changes.map((change) => change.reviewKey));
1559
- return {
1560
- sha,
1561
- files: changes,
1562
- reviewed: Object.keys(reviews).filter((key) => keys.has(key)).sort()
1563
- };
1564
- }
1565
-
1566
1529
  // modules/core/implementations/Functions/reviewCodeChanges.ts
1567
1530
  async function reviewCodeChanges(input) {
1568
1531
  const { repoRoot, ref, version: version2, items, reviewed } = ReviewCodeChangesInputSchema.parse(input);
1569
- const changes = await getGitChanges({ repoRoot, ref });
1570
- if (changes.sha !== version2)
1532
+ const changes = await collectCodeChanges(repoRoot, ref);
1533
+ const keys = new Set(changes.files.map((file) => file.reviewKey));
1534
+ if (changes.sha !== version2 || items.some((key) => !keys.has(key)))
1571
1535
  throw Object.assign(new Error("\u4EE3\u7801\u6539\u52A8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u65B0\u5BA1\u6838"), { statusCode: 409 });
1572
- const files = items.map((key) => {
1573
- const file = changes.files.find((item) => item.reviewKey === key);
1574
- if (!file)
1575
- throw Object.assign(new Error("\u4EE3\u7801\u6539\u52A8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u65B0\u5BA1\u6838"), { statusCode: 409 });
1576
- return { path: file.path, key };
1577
- });
1578
- if (new Set(files.map((file) => file.key)).size !== files.length)
1579
- throw new Error("\u5BA1\u6838\u6587\u4EF6\u4E0D\u80FD\u91CD\u590D");
1580
- const { files: currentChanges } = await collectChanges(repoRoot, ref);
1581
- const byPath = new Map(currentChanges.map((change) => [change.path, change]));
1582
- const repo = await realpath3(repoRoot);
1536
+ if (new Set(items).size !== items.length) throw new Error("\u5BA1\u6838\u6587\u4EF6\u4E0D\u80FD\u91CD\u590D");
1583
1537
  const reviews = await readReviews(repoRoot);
1584
- for (const file of files) {
1585
- const change = byPath.get(file.path);
1586
- if (!change)
1587
- throw Object.assign(new Error("\u4EE3\u7801\u6539\u52A8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u65B0\u5BA1\u6838"), { statusCode: 409 });
1588
- const after = change.status === "deleted" ? null : await worktreeSide(repo, change.path);
1589
- if (reviewKey(change, after) !== file.key)
1590
- throw Object.assign(new Error("\u4EE3\u7801\u6539\u52A8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u65B0\u5BA1\u6838"), { statusCode: 409 });
1591
- if (reviewed) reviews[file.key] = (/* @__PURE__ */ new Date()).toISOString();
1592
- else delete reviews[file.key];
1538
+ for (const key of items) {
1539
+ if (reviewed) reviews[key] = (/* @__PURE__ */ new Date()).toISOString();
1540
+ else delete reviews[key];
1593
1541
  }
1594
1542
  await writeJsonAtomic(await reviewFile(repoRoot), reviews);
1595
- return { reviewed: (await getGitChanges({ repoRoot, ref })).reviewed };
1543
+ return {
1544
+ reviewed: Object.keys(reviews).filter((key) => keys.has(key)).sort()
1545
+ };
1596
1546
  }
1597
1547
 
1598
1548
  // modules/core/implementations/Functions/reviewBaselineChanges.ts
1599
- import path22 from "node:path";
1549
+ import path21 from "node:path";
1600
1550
 
1601
1551
  // modules/core/contracts/functions/reviewBaselineChanges.ts
1602
- import { z as z15 } from "zod";
1603
- var ReviewBaselineChangesInputSchema = z15.object({
1604
- repoRoot: z15.string(),
1605
- ref: z15.string(),
1606
- version: z15.string(),
1607
- items: z15.array(z15.string()).min(1),
1608
- reviewed: z15.boolean()
1552
+ import { z as z14 } from "zod";
1553
+ var ReviewBaselineChangesInputSchema = z14.object({
1554
+ repoRoot: z14.string(),
1555
+ ref: z14.string(),
1556
+ version: z14.string(),
1557
+ items: z14.array(z14.string()).min(1),
1558
+ reviewed: z14.boolean()
1609
1559
  });
1610
1560
 
1611
1561
  // modules/core/contracts/functions/getBaselineChanges.ts
1612
- import { z as z16 } from "zod";
1613
- var GetBaselineChangesInputSchema = z16.object({ repoRoot: z16.string(), ref: z16.string() });
1562
+ import { z as z15 } from "zod";
1563
+ var GetBaselineChangesInputSchema = z15.object({ repoRoot: z15.string(), ref: z15.string() });
1614
1564
 
1615
1565
  // modules/core/implementations/reportResources.ts
1616
- import path20 from "node:path";
1566
+ import path19 from "node:path";
1617
1567
  function reportStaticUrl(reportDir, file) {
1618
- const relative = path20.relative(reportDir, file);
1619
- if (relative.startsWith("..") || path20.isAbsolute(relative))
1568
+ const relative = path19.relative(reportDir, file);
1569
+ if (relative.startsWith("..") || path19.isAbsolute(relative))
1620
1570
  throw new Error("\u56FE\u7247\u8DEF\u5F84\u8D85\u51FA\u62A5\u544A\u76EE\u5F55");
1621
- return `/report-static/${relative.split(path20.sep).map(encodeURIComponent).join("/")}`;
1571
+ return `/report-static/${relative.split(path19.sep).map(encodeURIComponent).join("/")}`;
1622
1572
  }
1623
1573
  async function prepareBaselineImages(root, snapshots) {
1624
1574
  const reportDir = await reportRoot(root);
@@ -1638,8 +1588,7 @@ async function prepareBaselineImages(root, snapshots) {
1638
1588
 
1639
1589
  // modules/core/implementations/Functions/getBaselineChanges.ts
1640
1590
  import { readFile as readFile9 } from "node:fs/promises";
1641
- import { execFile as execFile2 } from "node:child_process";
1642
- import path21 from "node:path";
1591
+ import path20 from "node:path";
1643
1592
  import { PNG as PNG2 } from "pngjs";
1644
1593
  async function fromGit(root, sha, file) {
1645
1594
  const result = await runGit(root, ["show", `${sha}:${file}`]);
@@ -1648,33 +1597,26 @@ async function fromGit(root, sha, file) {
1648
1597
  if (!exists.ok) return null;
1649
1598
  throw new Error(result.stderr);
1650
1599
  }
1651
- async function gitBaselineFiles(root, sha, directory) {
1600
+ async function gitBaselineFiles(root, sha, directory, only) {
1652
1601
  const result = await runGit(root, ["ls-tree", "-r", "-z", sha, "--", directory]);
1653
1602
  if (!result.ok) throw new Error(result.stderr);
1654
1603
  const files = result.stdout.split("\0").filter(Boolean).flatMap((line) => {
1655
1604
  const separator = line.indexOf(" ");
1656
1605
  const file = line.slice(separator + 1);
1657
1606
  const [, type, oid] = line.slice(0, separator).split(" ");
1658
- return type === "blob" && /\/baseline(?:-[a-f0-9]{64})?\.json$/.test(file) ? [{ file, oid }] : [];
1607
+ if (type !== "blob" || !/\/baseline(?:-[a-f0-9]{64})?\.json$/.test(file)) return [];
1608
+ const parts = file.slice(directory.length + 1).split("/");
1609
+ const namespace = parts[0];
1610
+ const casePath = parts.slice(1, -1).join("/");
1611
+ return !only || only.has(`${namespace}/${casePath}`) ? [{ file, oid, namespace, casePath }] : [];
1659
1612
  }).sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0);
1660
1613
  if (!files.length) return [];
1661
- const output = await new Promise((resolve, reject) => {
1662
- const child = execFile2(
1663
- "git",
1664
- ["-C", root, "cat-file", "--batch"],
1665
- {
1666
- encoding: "buffer",
1667
- maxBuffer: 32 * 1024 * 1024,
1668
- timeout: 2e4,
1669
- windowsHide: true
1670
- },
1671
- (error, stdout) => error ? reject(error) : resolve(stdout)
1672
- );
1673
- child.stdin.on("error", reject);
1674
- child.stdin.end(files.map(({ oid }) => oid).join("\n") + "\n");
1675
- });
1614
+ const output = await gitCatFileBatch(
1615
+ root,
1616
+ files.map(({ oid }) => oid)
1617
+ );
1676
1618
  let offset = 0;
1677
- return files.map(({ file, oid }) => {
1619
+ return files.map(({ file, oid, namespace, casePath }) => {
1678
1620
  const end = output.indexOf(10, offset);
1679
1621
  const [actualOid, type, length] = output.subarray(offset, end).toString().split(" ");
1680
1622
  const size = Number(length);
@@ -1684,8 +1626,7 @@ async function gitBaselineFiles(root, sha, directory) {
1684
1626
  output.subarray(end + 1, end + 1 + size).toString("utf8")
1685
1627
  );
1686
1628
  offset = end + 1 + size + 1;
1687
- const parts = file.slice(directory.length + 1).split("/");
1688
- return { namespace: parts[0], path: parts.slice(1, -1).join("/"), file, baseline };
1629
+ return { namespace, path: casePath, file, baseline };
1689
1630
  });
1690
1631
  }
1691
1632
  async function currentBaseline(root, namespace) {
@@ -1723,12 +1664,12 @@ async function getBaselineChanges(input) {
1723
1664
  const { repoRoot: root, ref } = GetBaselineChangesInputSchema.parse(input);
1724
1665
  const { sha, files: gitChanges } = await collectChanges(root, ref);
1725
1666
  if (!sha) throw new Error("\u627E\u4E0D\u5230\u6BD4\u8F83\u5206\u652F");
1726
- const entries = [];
1667
+ const entries2 = [];
1727
1668
  const config = await loadConfig({ repoRoot: root });
1728
1669
  const historicalConfig = await fromGit(root, sha, "evidra.config.json");
1729
1670
  const oldConfig = historicalConfig ? parseConfig(JSON.parse(historicalConfig)) : config;
1730
- const currentDirectory = path21.posix.join(config.reportDir.split(path21.sep).join("/"), "baselines");
1731
- const oldDirectory = path21.posix.join(oldConfig.reportDir.split(path21.sep).join("/"), "baselines");
1671
+ const currentDirectory = path20.posix.join(config.reportDir.split(path20.sep).join("/"), "baselines");
1672
+ const oldDirectory = path20.posix.join(oldConfig.reportDir.split(path20.sep).join("/"), "baselines");
1732
1673
  const configChanged = gitChanges.some((item) => item.path === "evidra.config.json");
1733
1674
  const affected = new Set(
1734
1675
  gitChanges.flatMap((item) => [item.path, item.oldPath].filter((file) => !!file)).flatMap((file) => {
@@ -1743,7 +1684,7 @@ async function getBaselineChanges(input) {
1743
1684
  return [];
1744
1685
  })
1745
1686
  );
1746
- const historical = configChanged || affected.size ? await gitBaselineFiles(root, sha, oldDirectory) : [];
1687
+ const historical = configChanged || affected.size ? await gitBaselineFiles(root, sha, oldDirectory, configChanged ? void 0 : affected) : [];
1747
1688
  const namespaces = configChanged || affected.size ? [...config.namespaces] : [];
1748
1689
  const byNamespace = /* @__PURE__ */ new Map();
1749
1690
  for (const item of historical) {
@@ -1786,10 +1727,10 @@ async function getBaselineChanges(input) {
1786
1727
  }
1787
1728
  const changed = snapshots.some((snapshot) => snapshot.change !== "same") || a?.baseline.name !== b?.baseline.name || canonical(a?.baseline.treePath) !== canonical(b?.baseline.treePath);
1788
1729
  if (!changed) continue;
1789
- entries.push({
1730
+ entries2.push({
1790
1731
  namespace: namespace.id,
1791
1732
  namespaceName: namespace.name,
1792
- file: b?.file ? path21.posix.join(currentDirectory, namespace.id, b.file) : a?.file ?? path21.posix.join(currentDirectory, namespace.id, b?.path ?? a.path, "baseline.json"),
1733
+ file: b?.file ? path20.posix.join(currentDirectory, namespace.id, b.file) : a?.file ?? path20.posix.join(currentDirectory, namespace.id, b?.path ?? a.path, "baseline.json"),
1793
1734
  item: {
1794
1735
  id: b?.baseline.id ?? a.baseline.id,
1795
1736
  change: !a ? "added" : !b ? "deleted" : "modified",
@@ -1800,21 +1741,21 @@ async function getBaselineChanges(input) {
1800
1741
  });
1801
1742
  }
1802
1743
  }
1803
- const digest = version([sha, entries]);
1744
+ const digest = version([sha, entries2]);
1804
1745
  const reportDir = await reportRoot(root);
1805
1746
  await prepareBaselineImages(
1806
1747
  root,
1807
- entries.flatMap(
1748
+ entries2.flatMap(
1808
1749
  (entry) => entry.item.snapshots.flatMap(
1809
1750
  (snapshot) => [snapshot.baseline, snapshot.current].filter((item) => !!item)
1810
1751
  )
1811
1752
  )
1812
1753
  );
1813
- for (const entry of entries) {
1754
+ for (const entry of entries2) {
1814
1755
  for (const snapshot of entry.item.snapshots) {
1815
1756
  if (snapshot.baseline?.type === "image" && snapshot.current?.type === "image" && snapshot.baseline.key !== snapshot.current.key) {
1816
1757
  const file = await prepareImageDiff(root, snapshot.baseline, snapshot.current);
1817
- snapshot.diffFile = path21.relative(reportDir, file).split(path21.sep).join("/");
1758
+ snapshot.diffFile = path20.relative(reportDir, file).split(path20.sep).join("/");
1818
1759
  snapshot.diffUrl = reportStaticUrl(reportDir, file);
1819
1760
  }
1820
1761
  }
@@ -1823,26 +1764,26 @@ async function getBaselineChanges(input) {
1823
1764
  ref,
1824
1765
  sha,
1825
1766
  version: digest,
1826
- entries,
1767
+ entries: entries2,
1827
1768
  reviewed: await readJson(
1828
- path21.join(await reportRoot(root), "cache", "reviews", `${digest}.json`)
1769
+ path20.join(await reportRoot(root), "cache", "reviews", `${digest}.json`)
1829
1770
  ) ?? []
1830
1771
  };
1831
1772
  }
1832
1773
  async function prepareImageDiff(root, before, after) {
1833
1774
  if (!before.key || !after.key) throw new Error("\u57FA\u7EBF\u56FE\u7247\u7F3A\u5C11\u5BF9\u8C61\u5B58\u50A8 key");
1834
1775
  const reportDir = await reportRoot(root);
1835
- const directory = path21.join(
1776
+ const directory = path20.join(
1836
1777
  reportDir,
1837
1778
  "cache",
1838
1779
  "comparisons",
1839
1780
  version(["git", before.key, after.key])
1840
1781
  );
1841
- const index = path21.join(directory, "diff-v2.json");
1782
+ const index = path20.join(directory, "diff-v2.json");
1842
1783
  const cached = await readJson(index);
1843
1784
  try {
1844
1785
  if (cached) {
1845
- const file2 = path21.join(directory, cached);
1786
+ const file2 = path20.join(directory, cached);
1846
1787
  await readFile9(file2);
1847
1788
  return file2;
1848
1789
  }
@@ -1859,7 +1800,7 @@ async function prepareImageDiff(root, before, after) {
1859
1800
  const result = localImageDiff(PNG2.sync.write(left), PNG2.sync.write(right));
1860
1801
  if (!result.png) throw new Error("\u65E0\u6CD5\u751F\u6210\u56FE\u7247\u5DEE\u5F02");
1861
1802
  const filename = `diff-${hash(result.png)}.png`;
1862
- const file = path21.join(directory, filename);
1803
+ const file = path20.join(directory, filename);
1863
1804
  await writeBytesAtomic(file, result.png);
1864
1805
  await writeJsonAtomic(index, filename);
1865
1806
  return file;
@@ -1880,23 +1821,23 @@ async function reviewBaselineChanges(input) {
1880
1821
  for (const id of items) reviewed ? selected.add(id) : selected.delete(id);
1881
1822
  const ids = [...selected];
1882
1823
  await writeJsonAtomic(
1883
- path22.join(await reportRoot(repoRoot), "cache", "reviews", `${version2}.json`),
1824
+ path21.join(await reportRoot(repoRoot), "cache", "reviews", `${version2}.json`),
1884
1825
  ids
1885
1826
  );
1886
1827
  return { reviewed: ids };
1887
1828
  }
1888
1829
 
1889
1830
  // modules/core/implementations/Functions/deleteBaselineFile.ts
1890
- import path23 from "node:path";
1831
+ import path22 from "node:path";
1891
1832
  import { rm as rm4 } from "node:fs/promises";
1892
1833
 
1893
1834
  // modules/core/contracts/functions/deleteBaselineFile.ts
1894
- import { z as z17 } from "zod";
1895
- var DeleteBaselineFileInputSchema = z17.object({
1896
- repoRoot: z17.string(),
1897
- namespace: z17.string(),
1898
- file: z17.string(),
1899
- version: z17.string()
1835
+ import { z as z16 } from "zod";
1836
+ var DeleteBaselineFileInputSchema = z16.object({
1837
+ repoRoot: z16.string(),
1838
+ namespace: z16.string(),
1839
+ file: z16.string(),
1840
+ version: z16.string()
1900
1841
  });
1901
1842
 
1902
1843
  // modules/core/implementations/Functions/deleteBaselineFile.ts
@@ -1908,19 +1849,19 @@ async function deleteBaselineFile(input) {
1908
1849
  throw Object.assign(new Error("\u57FA\u7EBF\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0"), { statusCode: 409 });
1909
1850
  if (!current.candidates.some((item) => item.file === file))
1910
1851
  throw Object.assign(new Error("\u57FA\u7EBF\u6587\u4EF6\u4E0D\u5B58\u5728"), { statusCode: 404 });
1911
- await rm4(path23.join(absoluteReportPath, "baselines", namespace, file));
1852
+ await rm4(path22.join(absoluteReportPath, "baselines", namespace, file));
1912
1853
  return { ok: true };
1913
1854
  }
1914
1855
 
1915
1856
  // modules/core/implementations/Functions/compareTasks.ts
1916
- import path24 from "node:path";
1857
+ import path23 from "node:path";
1917
1858
 
1918
1859
  // modules/core/contracts/functions/compareTasks.ts
1919
- import { z as z18 } from "zod";
1920
- var CompareTasksInputSchema = z18.object({
1921
- repoRoot: z18.string(),
1922
- baseTaskId: z18.string().regex(/^[a-zA-Z0-9_-]{3,}$/),
1923
- taskId: z18.string().regex(/^[a-zA-Z0-9_-]{3,}$/)
1860
+ import { z as z17 } from "zod";
1861
+ var CompareTasksInputSchema = z17.object({
1862
+ repoRoot: z17.string(),
1863
+ baseTaskId: z17.string().regex(/^[a-zA-Z0-9_-]{3,}$/),
1864
+ taskId: z17.string().regex(/^[a-zA-Z0-9_-]{3,}$/)
1924
1865
  });
1925
1866
 
1926
1867
  // modules/core/implementations/Functions/compareTasks.ts
@@ -1958,7 +1899,7 @@ async function compareTasks(input) {
1958
1899
  download: (key) => readTaskImage(reportDir, key),
1959
1900
  localPath: async (key) => {
1960
1901
  await readTaskImage(reportDir, key);
1961
- return path24.resolve(reportDir, "objects", key);
1902
+ return path23.resolve(reportDir, "objects", key);
1962
1903
  },
1963
1904
  upload: async () => {
1964
1905
  throw new Error("\u4EFB\u52A1\u6BD4\u8F83\u4E0D\u5199\u5165\u57FA\u7EBF\u5B58\u50A8");
@@ -1987,9 +1928,28 @@ async function compareTasks(input) {
1987
1928
  };
1988
1929
  }
1989
1930
 
1931
+ // modules/core/contracts/functions/getGitChanges.ts
1932
+ import { z as z18 } from "zod";
1933
+ var GetGitChangesInputSchema = z18.object({ repoRoot: z18.string(), ref: z18.string() });
1934
+
1935
+ // modules/core/implementations/Functions/getGitChanges.ts
1936
+ async function getGitChanges(input) {
1937
+ const { repoRoot: root, ref } = GetGitChangesInputSchema.parse(input);
1938
+ const [{ sha, files }, reviews] = await Promise.all([
1939
+ collectCodeChanges(root, ref),
1940
+ readReviews(root)
1941
+ ]);
1942
+ const keys = new Set(files.map((change) => change.reviewKey));
1943
+ return {
1944
+ sha,
1945
+ files,
1946
+ reviewed: Object.keys(reviews).filter((key) => keys.has(key)).sort()
1947
+ };
1948
+ }
1949
+
1990
1950
  // modules/core/implementations/Functions/getGitDiff.ts
1991
- import path25 from "node:path";
1992
- import { lstat as lstat2, readFile as readFile10, readlink as readlink2, realpath as realpath4 } from "node:fs/promises";
1951
+ import path24 from "node:path";
1952
+ import { lstat as lstat2, readFile as readFile10, readlink as readlink2, realpath as realpath2 } from "node:fs/promises";
1993
1953
 
1994
1954
  // modules/core/contracts/functions/getGitDiff.ts
1995
1955
  import { z as z19 } from "zod";
@@ -2007,7 +1967,7 @@ async function getGitDiff(input) {
2007
1967
  const entry = files.find((entry2) => entry2.path === file);
2008
1968
  if (!entry) throw new Error("\u627E\u4E0D\u5230\u4EE3\u7801\u6539\u52A8\u6587\u4EF6");
2009
1969
  if (expectedKey) {
2010
- const after = entry.status === "deleted" ? null : await worktreeSide(await realpath4(root), entry.path);
1970
+ const after = entry.status === "deleted" ? null : await worktreeSide(await realpath2(root), entry.path);
2011
1971
  if (reviewKey(entry, after) !== expectedKey)
2012
1972
  throw Object.assign(new Error("\u4EE3\u7801\u6539\u52A8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0"), { statusCode: 409 });
2013
1973
  }
@@ -2022,18 +1982,18 @@ async function getGitDiff(input) {
2022
1982
  else original = await git(root, ["show", object]);
2023
1983
  }
2024
1984
  if (entry.status !== "deleted") {
2025
- const absolute = path25.resolve(root, file);
2026
- const parent = await realpath4(path25.dirname(absolute));
2027
- const repo = await realpath4(root);
2028
- const relative = path25.relative(repo, parent);
2029
- if (relative === ".." || relative.startsWith(`..${path25.sep}`) || path25.isAbsolute(relative))
1985
+ const absolute = path24.resolve(root, file);
1986
+ const parent = await realpath2(path24.dirname(absolute));
1987
+ const repo = await realpath2(root);
1988
+ const relative = path24.relative(repo, parent);
1989
+ if (relative === ".." || relative.startsWith(`..${path24.sep}`) || path24.isAbsolute(relative))
2030
1990
  throw new Error("\u6587\u4EF6\u4E0D\u5728\u4ED3\u5E93\u5185");
2031
- const stat3 = await lstat2(absolute);
2032
- if (stat3.isSymbolicLink()) modified = await readlink2(absolute);
2033
- else if (stat3.isDirectory())
1991
+ const stat4 = await lstat2(absolute);
1992
+ if (stat4.isSymbolicLink()) modified = await readlink2(absolute);
1993
+ else if (stat4.isDirectory())
2034
1994
  modified = `Subproject commit ${(await git(absolute, ["rev-parse", "HEAD"])).trim()}
2035
1995
  `;
2036
- else if (stat3.size > MAX_BYTES) tooLarge = true;
1996
+ else if (stat4.size > MAX_BYTES) tooLarge = true;
2037
1997
  else modified = await readFile10(absolute, "utf8");
2038
1998
  }
2039
1999
  const isBinary = original.includes("\0") || modified.includes("\0");
@@ -2048,10 +2008,150 @@ async function getGitDiff(input) {
2048
2008
  };
2049
2009
  }
2050
2010
 
2051
- // modules/core/contracts/functions/listTaskSummaries.ts
2011
+ // modules/core/implementations/Functions/pruneTasks.ts
2012
+ import { readdir as readdir4, readFile as readFile11, rm as rm5, rmdir, stat } from "node:fs/promises";
2013
+ import path26 from "node:path";
2014
+
2015
+ // modules/core/contracts/functions/pruneTasks.ts
2052
2016
  import { z as z20 } from "zod";
2053
- var ListTaskSummariesInputSchema = z20.object({
2054
- repoRoot: z20.string()
2017
+ var PruneTasksInputSchema = z20.object({
2018
+ repoRoot: z20.string(),
2019
+ /** 只统计可清理的任务数量,不删除。 */
2020
+ dryRun: z20.boolean().optional()
2021
+ });
2022
+
2023
+ // modules/core/contracts/internal/listTasks.ts
2024
+ import { z as z21 } from "zod";
2025
+ var ListTasksInputSchema = z21.object({
2026
+ limit: z21.number().int().min(1).max(100).optional()
2027
+ });
2028
+ var TASK_LIST_LIMIT = 50;
2029
+
2030
+ // modules/core/implementations/internal/listTasks.ts
2031
+ import { readdir as readdir3 } from "node:fs/promises";
2032
+ import path25 from "node:path";
2033
+ async function listTasks(input, cwd, namespaces) {
2034
+ const { limit = 20 } = ListTasksInputSchema.parse(input);
2035
+ const root = path25.join(cwd, "tasks");
2036
+ const tasks = [];
2037
+ const removable = [];
2038
+ async function directories(directory, pattern) {
2039
+ try {
2040
+ return (await readdir3(directory, { withFileTypes: true })).filter((entry) => entry.isDirectory() && pattern.test(entry.name)).map((entry) => entry.name).sort((a, b) => a < b ? 1 : a > b ? -1 : 0);
2041
+ } catch (error) {
2042
+ if (error.code === "ENOENT") return [];
2043
+ throw error;
2044
+ }
2045
+ }
2046
+ for (const day of await directories(root, /^\d{4}-\d{2}-\d{2}$/)) {
2047
+ const dayRoot = path25.join(root, day);
2048
+ for (const run of await directories(dayRoot, /^\d{2}-\d{2}-\d{2}-[A-Za-z0-9-]+$/)) {
2049
+ if (tasks.length === limit) {
2050
+ removable.push(`${day}/${run}`);
2051
+ continue;
2052
+ }
2053
+ const file = path25.join(dayRoot, run, "task.json");
2054
+ const manifest = await readJson(file);
2055
+ if (!manifest || (manifest.formatVersion ?? 0) < TASK_SCHEMA_VERSION || !namespaces.has(manifest.task.namespace))
2056
+ continue;
2057
+ if (manifest.task.finishedAt && manifest.failedCount !== void 0) {
2058
+ tasks.push({ ...manifest.task, failedCount: manifest.failedCount });
2059
+ continue;
2060
+ }
2061
+ const record = await readTaskRecord(file);
2062
+ tasks.push({
2063
+ ...record.task,
2064
+ failedCount: record.cases.filter((item) => item.result.status === "failed").length
2065
+ });
2066
+ }
2067
+ }
2068
+ return { tasks, removable };
2069
+ }
2070
+
2071
+ // modules/core/implementations/Functions/pruneTasks.ts
2072
+ var OBJECT_GRACE_MS = 10 * 60 * 1e3;
2073
+ async function entries(directory) {
2074
+ try {
2075
+ return await readdir4(directory, { withFileTypes: true });
2076
+ } catch (error) {
2077
+ if (error.code === "ENOENT") return [];
2078
+ throw error;
2079
+ }
2080
+ }
2081
+ async function removeIfEmpty(directory) {
2082
+ await rmdir(directory).catch((error) => {
2083
+ if (!["ENOTEMPTY", "EEXIST", "ENOENT"].includes(error.code ?? "")) throw error;
2084
+ });
2085
+ }
2086
+ async function removeUnreferencedObjects(reportDir) {
2087
+ const referenced = /* @__PURE__ */ new Set();
2088
+ const tasks = path26.join(reportDir, "tasks");
2089
+ for (const day of await entries(tasks)) {
2090
+ if (!day.isDirectory() || day.name === "_index") continue;
2091
+ for (const run of await entries(path26.join(tasks, day.name))) {
2092
+ const cases = path26.join(tasks, day.name, run.name, "cases");
2093
+ for (const file of await entries(cases)) {
2094
+ if (!file.name.endsWith(".json")) continue;
2095
+ const item = JSON.parse(await readFile11(path26.join(cases, file.name), "utf8"));
2096
+ for (const image of [...item.snapshots ?? [], ...item.observations ?? []])
2097
+ if (image.type === "image") referenced.add(image.key);
2098
+ }
2099
+ }
2100
+ }
2101
+ const objects = path26.join(reportDir, "objects");
2102
+ const deadline = Date.now() - OBJECT_GRACE_MS;
2103
+ const directories = [];
2104
+ for (const entry of await readdir4(objects, { withFileTypes: true, recursive: true }).catch(
2105
+ (error) => {
2106
+ if (error.code === "ENOENT") return [];
2107
+ throw error;
2108
+ }
2109
+ )) {
2110
+ const file = path26.join(entry.parentPath, entry.name);
2111
+ if (entry.isDirectory()) {
2112
+ directories.push(file);
2113
+ continue;
2114
+ }
2115
+ if (referenced.has(path26.relative(objects, file).split(path26.sep).join("/"))) continue;
2116
+ if ((await stat(file)).mtimeMs < deadline) await rm5(file);
2117
+ }
2118
+ for (const directory of directories.sort((a, b) => b.length - a.length))
2119
+ await removeIfEmpty(directory);
2120
+ }
2121
+ async function pruneTasks(input) {
2122
+ const { repoRoot, dryRun } = PruneTasksInputSchema.parse(input);
2123
+ const config = await loadConfig({ repoRoot });
2124
+ const reportDir = await reportRoot(repoRoot);
2125
+ const { removable } = await listTasks(
2126
+ { limit: TASK_LIST_LIMIT },
2127
+ reportDir,
2128
+ new Set(config.namespaces.map((item) => item.id))
2129
+ );
2130
+ if (dryRun || !removable.length) return { count: removable.length };
2131
+ const cache = pathSchema.cache(reportDir).directory;
2132
+ const comparisons = path26.join(cache, "comparisons");
2133
+ const taskComparisons = path26.join(cache, "task-comparisons");
2134
+ const options = { recursive: true, force: true };
2135
+ for (const taskPath of removable) {
2136
+ const taskId = taskPath.split("/")[1].slice("HH-mm-ss-".length);
2137
+ await rm5(taskDirectory(reportDir, taskPath), options);
2138
+ await rm5(pathSchema.taskIndex(reportDir, taskId), { force: true });
2139
+ for (const namespace of await entries(comparisons))
2140
+ await rm5(path26.join(comparisons, namespace.name, taskId), options);
2141
+ await rm5(path26.join(taskComparisons, taskId), options);
2142
+ for (const base of await entries(taskComparisons))
2143
+ await rm5(path26.join(taskComparisons, base.name, taskId), options);
2144
+ }
2145
+ for (const day of new Set(removable.map((taskPath) => taskPath.split("/")[0])))
2146
+ await removeIfEmpty(path26.join(reportDir, "tasks", day));
2147
+ await removeUnreferencedObjects(reportDir);
2148
+ return { count: removable.length };
2149
+ }
2150
+
2151
+ // modules/core/contracts/functions/listTaskSummaries.ts
2152
+ import { z as z22 } from "zod";
2153
+ var ListTaskSummariesInputSchema = z22.object({
2154
+ repoRoot: z22.string()
2055
2155
  });
2056
2156
 
2057
2157
  // modules/core/implementations/reportStatus.ts
@@ -2097,54 +2197,13 @@ function taskDisplay(task) {
2097
2197
  };
2098
2198
  }
2099
2199
 
2100
- // modules/core/implementations/internal/listTasks.ts
2101
- import { readdir as readdir3 } from "node:fs/promises";
2102
- import path26 from "node:path";
2103
-
2104
- // modules/core/contracts/internal/listTasks.ts
2105
- import { z as z21 } from "zod";
2106
- var ListTasksInputSchema = z21.object({
2107
- limit: z21.number().int().min(1).max(100).optional()
2108
- });
2109
-
2110
- // modules/core/implementations/internal/listTasks.ts
2111
- async function listTasks(input, cwd, namespaces) {
2112
- const { limit = 20 } = ListTasksInputSchema.parse(input);
2113
- const root = path26.join(cwd, "tasks");
2114
- const tasks = [];
2115
- async function directories(directory, pattern) {
2116
- try {
2117
- return (await readdir3(directory, { withFileTypes: true })).filter((entry) => entry.isDirectory() && pattern.test(entry.name)).map((entry) => entry.name).sort((a, b) => a < b ? 1 : a > b ? -1 : 0);
2118
- } catch (error) {
2119
- if (error.code === "ENOENT") return [];
2120
- throw error;
2121
- }
2122
- }
2123
- for (const day of await directories(root, /^\d{4}-\d{2}-\d{2}$/)) {
2124
- const dayRoot = path26.join(root, day);
2125
- for (const run of await directories(dayRoot, /^\d{2}-\d{2}-\d{2}-[A-Za-z0-9-]+$/)) {
2126
- const file = path26.join(dayRoot, run, "task.json");
2127
- const manifest = await readJson(file);
2128
- if (!manifest || (manifest.formatVersion ?? 0) < TASK_SCEHAM_VERSION || !namespaces.has(manifest.task.namespace))
2129
- continue;
2130
- const record = await readTaskRecord(file);
2131
- tasks.push({
2132
- ...record.task,
2133
- failedCount: record.cases.filter((item) => item.result.status === "failed").length
2134
- });
2135
- if (tasks.length === limit) return { tasks };
2136
- }
2137
- }
2138
- return { tasks };
2139
- }
2140
-
2141
2200
  // modules/core/implementations/Functions/listTaskSummaries.ts
2142
2201
  async function listTaskSummaries(input) {
2143
2202
  const { repoRoot: root } = ListTaskSummariesInputSchema.parse(input);
2144
2203
  const config = await loadConfig({ repoRoot: root });
2145
2204
  const namespaces = new Set(config.namespaces.map((item) => item.id));
2146
2205
  const reportDir = await reportRoot(root);
2147
- const page = await listTasks({ limit: 40 }, reportDir, namespaces);
2206
+ const page = await listTasks({ limit: TASK_LIST_LIMIT }, reportDir, namespaces);
2148
2207
  const tasks = page.tasks;
2149
2208
  const versions = new Map(
2150
2209
  await Promise.all(
@@ -2181,8 +2240,8 @@ async function listTaskSummaries(input) {
2181
2240
  }
2182
2241
 
2183
2242
  // modules/core/contracts/functions/readProjectInfo.ts
2184
- import { z as z22 } from "zod";
2185
- var ReadProjectInfoInputSchema = z22.object({ repoRoot: z22.string() });
2243
+ import { z as z23 } from "zod";
2244
+ var ReadProjectInfoInputSchema = z23.object({ repoRoot: z23.string() });
2186
2245
 
2187
2246
  // modules/core/implementations/Functions/readProjectInfo.ts
2188
2247
  var FALLBACK_REFS = ["main", "master", "origin/main", "origin/master"];
@@ -2228,15 +2287,15 @@ async function readProjectInfo(input) {
2228
2287
  }
2229
2288
 
2230
2289
  // modules/core/contracts/functions/listBaselines.ts
2231
- import { z as z23 } from "zod";
2232
- var ListBaselinesInputSchema = z23.object({ repoRoot: z23.string() });
2290
+ import { z as z24 } from "zod";
2291
+ var ListBaselinesInputSchema = z24.object({ repoRoot: z24.string() });
2233
2292
 
2234
2293
  // modules/core/implementations/reportTree.ts
2235
2294
  var reportEntryKey = (namespace, id) => JSON.stringify([namespace, id]);
2236
- function buildReportTree(namespaces, entries, running) {
2295
+ function buildReportTree(namespaces, entries2, running) {
2237
2296
  return namespaces.flatMap((ns) => {
2238
2297
  const children = [];
2239
- for (const entry of entries.filter((e) => e.namespace === ns.id)) {
2298
+ for (const entry of entries2.filter((e) => e.namespace === ns.id)) {
2240
2299
  const item = entry.item.current ?? entry.item.baseline;
2241
2300
  const parts = item.treePath.length ? item.treePath : [{ key: item.id, display: item.name }];
2242
2301
  let nodes = children;
@@ -2283,7 +2342,7 @@ async function listBaselines(input) {
2283
2342
  ...(group.candidates ?? []).flatMap((item) => item.baseline.snapshots)
2284
2343
  ])
2285
2344
  );
2286
- const entries = namespaces.flatMap(
2345
+ const entries2 = namespaces.flatMap(
2287
2346
  (group) => (group.candidates ?? group.cases.map((baseline) => ({ baseline, file: "", ignored: false }))).map(({ baseline, file, ignored }) => ({
2288
2347
  key: reportEntryKey(group.id, file || baseline.id),
2289
2348
  ignored,
@@ -2303,15 +2362,15 @@ async function listBaselines(input) {
2303
2362
  }
2304
2363
  }))
2305
2364
  );
2306
- return { namespaces, entries, tree: buildReportTree(namespaces, entries, false) };
2365
+ return { namespaces, entries: entries2, tree: buildReportTree(namespaces, entries2, false) };
2307
2366
  }
2308
2367
 
2309
2368
  // modules/core/implementations/Functions/readTaskReport.ts
2310
2369
  import path27 from "node:path";
2311
2370
 
2312
2371
  // modules/core/contracts/functions/readTaskReport.ts
2313
- import { z as z24 } from "zod";
2314
- var ReadTaskReportInputSchema = z24.object({ repoRoot: z24.string(), taskId: z24.string() });
2372
+ import { z as z25 } from "zod";
2373
+ var ReadTaskReportInputSchema = z25.object({ repoRoot: z25.string(), taskId: z25.string() });
2315
2374
 
2316
2375
  // modules/core/implementations/Functions/readTaskReport.ts
2317
2376
  async function readTaskReport(input) {
@@ -2339,7 +2398,7 @@ async function readTaskReport(input) {
2339
2398
  id: task.namespace,
2340
2399
  name: task.namespace
2341
2400
  };
2342
- const entries = comparison.cases.map((item) => ({
2401
+ const entries2 = comparison.cases.map((item) => ({
2343
2402
  key: reportEntryKey(task.namespace, item.id),
2344
2403
  namespace: task.namespace,
2345
2404
  item,
@@ -2354,7 +2413,208 @@ async function readTaskReport(input) {
2354
2413
  caseCount: task.cases.length,
2355
2414
  failedCount: task.cases.filter((item) => item.result.status === "failed").length
2356
2415
  });
2357
- return { task, comparison, entries, tree: buildReportTree([namespace], entries, true), display };
2416
+ return { task, comparison, entries: entries2, tree: buildReportTree([namespace], entries2, true), display };
2417
+ }
2418
+
2419
+ // modules/core/implementations/Functions/listChangelogCommits.ts
2420
+ import path29 from "node:path";
2421
+
2422
+ // modules/core/contracts/functions/changelog.ts
2423
+ import { z as z26 } from "zod";
2424
+ var ChangelogNoteSchema = z26.object({
2425
+ changelog: z26.string().optional(),
2426
+ reviewed: z26.boolean().optional(),
2427
+ entries: z26.record(z26.string(), z26.string()).optional(),
2428
+ excludeTags: z26.array(z26.string()).optional()
2429
+ }).passthrough();
2430
+ var ListChangelogCommitsInputSchema = z26.object({
2431
+ repoRoot: z26.string()
2432
+ });
2433
+ var GetChangelogFilesInputSchema = z26.object({
2434
+ repoRoot: z26.string(),
2435
+ commitId: z26.string().regex(/^[a-f0-9]{40}$/)
2436
+ });
2437
+ var GetChangelogDiffInputSchema = GetChangelogFilesInputSchema.extend({
2438
+ file: z26.string().min(1)
2439
+ });
2440
+ var ChangelogPatchSchema = z26.object({
2441
+ scope: z26.string().optional(),
2442
+ changelog: z26.string().optional(),
2443
+ reviewed: z26.boolean().optional(),
2444
+ excludeTags: z26.array(z26.string()).optional()
2445
+ });
2446
+ var UpdateChangelogNoteInputSchema = GetChangelogFilesInputSchema.extend({
2447
+ patch: ChangelogPatchSchema
2448
+ });
2449
+
2450
+ // modules/core/implementations/changelog.ts
2451
+ import path28 from "node:path";
2452
+ async function changelogConfig(repoRoot) {
2453
+ const config = await loadConfig({ repoRoot });
2454
+ if (!config.change) throw Object.assign(new Error("\u6B64\u9879\u76EE\u672A\u914D\u7F6E\u66F4\u65B0\u65E5\u5FD7"), { statusCode: 404 });
2455
+ return { ...config.change, notedir: path28.resolve(repoRoot, config.change.notedir) };
2456
+ }
2457
+ function notePath(notedir, commitId) {
2458
+ return path28.join(notedir, commitId.slice(0, 2), `${commitId.slice(2)}.json`);
2459
+ }
2460
+ async function readChangelogNote(notedir, commitId) {
2461
+ return ChangelogNoteSchema.parse(await readJson(notePath(notedir, commitId)) ?? {});
2462
+ }
2463
+ async function commitMetadata(repoRoot, commitId) {
2464
+ const raw = await git(repoRoot, ["show", "-s", "--format=%H%x00%cs%x00%s", commitId, "--"]);
2465
+ const [sha, date, message] = raw.trimEnd().split("\0");
2466
+ const tags = (await git(repoRoot, ["tag", "--points-at", commitId])).split("\n").filter(Boolean);
2467
+ return { commitId: sha, date, message, tags };
2468
+ }
2469
+ function toChangelogCommit(metadata, note, scope) {
2470
+ return {
2471
+ ...metadata,
2472
+ reviewed: note.reviewed ?? false,
2473
+ changelog: note.changelog ?? "",
2474
+ entries: Object.fromEntries(
2475
+ scope.map((key) => [
2476
+ key,
2477
+ note.entries && Object.hasOwn(note.entries, key) ? note.entries[key] : ""
2478
+ ])
2479
+ ),
2480
+ excludeTags: note.excludeTags ?? []
2481
+ };
2482
+ }
2483
+ async function commitFiles(repoRoot, commitId) {
2484
+ const parent = await gitOptional(repoRoot, ["rev-parse", "--verify", `${commitId}^1`]);
2485
+ const raw = await git(
2486
+ repoRoot,
2487
+ parent ? ["diff", "--name-status", "-z", "--find-renames", parent, commitId, "--"] : [
2488
+ "diff-tree",
2489
+ "--root",
2490
+ "--no-commit-id",
2491
+ "-r",
2492
+ "--name-status",
2493
+ "-z",
2494
+ "--find-renames",
2495
+ commitId,
2496
+ "--"
2497
+ ]
2498
+ );
2499
+ const fields = raw.split("\0");
2500
+ const files = [];
2501
+ for (let i = 0; fields[i]; ) {
2502
+ const code = fields[i++];
2503
+ const first = fields[i++];
2504
+ const renamed = code.startsWith("R") || code.startsWith("C");
2505
+ const file = renamed ? fields[i++] : first;
2506
+ if (!file) throw new Error("\u65E0\u6CD5\u89E3\u6790\u63D0\u4EA4\u6587\u4EF6");
2507
+ files.push({
2508
+ path: file,
2509
+ ...renamed ? { oldPath: first } : {},
2510
+ status: code.startsWith("R") ? "renamed" : code.startsWith("C") || code === "A" ? "added" : code === "D" ? "deleted" : "modified"
2511
+ });
2512
+ }
2513
+ return { parent, files: files.sort((a, b) => a.path.localeCompare(b.path)) };
2514
+ }
2515
+
2516
+ // modules/core/implementations/Functions/listChangelogCommits.ts
2517
+ async function listChangelogCommits(input) {
2518
+ const { repoRoot } = ListChangelogCommitsInputSchema.parse(input);
2519
+ const { change: config } = await loadConfig({ repoRoot });
2520
+ if (!config) return "";
2521
+ const sha = await resolveRef(repoRoot, `refs/heads/${config.branch}`);
2522
+ if (!sha) return "";
2523
+ const [raw, tagOutput] = await Promise.all([
2524
+ git(repoRoot, ["log", "--format=%H%x00%cs%x00%s", sha, "--"]),
2525
+ git(repoRoot, [
2526
+ "for-each-ref",
2527
+ "--format=%(objectname) %(refname:short) %(*objectname)",
2528
+ "refs/tags"
2529
+ ])
2530
+ ]);
2531
+ const tags = /* @__PURE__ */ new Map();
2532
+ for (const line of tagOutput.split("\n").filter(Boolean)) {
2533
+ const [object, tag, dereferenced] = line.trim().split(" ");
2534
+ const key = dereferenced || object;
2535
+ tags.set(key, [...tags.get(key) ?? [], tag]);
2536
+ }
2537
+ const commits = await mapLimit(raw.trimEnd().split("\n").filter(Boolean), 16, async (line) => {
2538
+ const [commitId, date, message] = line.split("\0");
2539
+ return toChangelogCommit(
2540
+ { commitId, date, message, tags: tags.get(commitId) ?? [] },
2541
+ await readChangelogNote(path29.resolve(repoRoot, config.notedir), commitId),
2542
+ config.scope
2543
+ );
2544
+ });
2545
+ return { scope: config.scope, commits };
2546
+ }
2547
+
2548
+ // modules/core/implementations/Functions/getChangelogFiles.ts
2549
+ async function getChangelogFiles(input) {
2550
+ const { repoRoot, commitId } = GetChangelogFilesInputSchema.parse(input);
2551
+ await changelogConfig(repoRoot);
2552
+ const { files } = await commitFiles(repoRoot, commitId);
2553
+ return { commitId, files };
2554
+ }
2555
+
2556
+ // modules/core/implementations/Functions/getChangelogDiff.ts
2557
+ async function getChangelogDiff(input) {
2558
+ const { repoRoot, commitId, file } = GetChangelogDiffInputSchema.parse(input);
2559
+ await changelogConfig(repoRoot);
2560
+ const { parent, files } = await commitFiles(repoRoot, commitId);
2561
+ const entry = files.find((item) => item.path === file);
2562
+ if (!entry) throw Object.assign(new Error("\u6B64\u6587\u4EF6\u4E0D\u5728\u63D0\u4EA4\u5DEE\u5F02\u4E2D"), { statusCode: 404 });
2563
+ let tooLarge = false;
2564
+ const readSide = async (ref, name, absent) => {
2565
+ if (!ref || absent) return "";
2566
+ const object = `${ref}:${name}`;
2567
+ const type = (await git(repoRoot, ["cat-file", "-t", object])).trim();
2568
+ if (type === "commit")
2569
+ return `Subproject commit ${(await git(repoRoot, ["rev-parse", object])).trim()}
2570
+ `;
2571
+ if (Number(await git(repoRoot, ["cat-file", "-s", object])) > MAX_BYTES) {
2572
+ tooLarge = true;
2573
+ return "";
2574
+ }
2575
+ return git(repoRoot, ["show", object]);
2576
+ };
2577
+ const [original, modified] = await Promise.all([
2578
+ readSide(parent, entry.oldPath ?? file, entry.status === "added"),
2579
+ readSide(commitId, file, entry.status === "deleted")
2580
+ ]);
2581
+ const isBinary = original.includes("\0") || modified.includes("\0");
2582
+ return {
2583
+ ...entry,
2584
+ original: isBinary || tooLarge ? "" : original,
2585
+ modified: isBinary || tooLarge ? "" : modified,
2586
+ isBinary,
2587
+ tooLarge
2588
+ };
2589
+ }
2590
+
2591
+ // modules/core/implementations/Functions/updateChangelogNote.ts
2592
+ async function updateChangelogNote(input) {
2593
+ const { repoRoot, commitId, patch } = UpdateChangelogNoteInputSchema.parse(input);
2594
+ const config = await changelogConfig(repoRoot);
2595
+ const metadata = await commitMetadata(repoRoot, commitId);
2596
+ if (patch.changelog !== void 0 && (config.scope.length ? !patch.scope || !config.scope.includes(patch.scope) : !!patch.scope))
2597
+ throw Object.assign(new Error("\u66F4\u65B0\u65E5\u5FD7 scope \u4E0E\u9879\u76EE\u914D\u7F6E\u4E0D\u5339\u914D"), { statusCode: 400 });
2598
+ if (patch.excludeTags?.some((tag) => !metadata.tags.includes(tag)))
2599
+ throw Object.assign(new Error("\u6807\u7B7E\u4E0D\u5C5E\u4E8E\u6B64\u63D0\u4EA4"), { statusCode: 400 });
2600
+ const file = notePath(config.notedir, commitId);
2601
+ const note = await readChangelogNote(config.notedir, commitId);
2602
+ note.reviewed ??= false;
2603
+ if (patch.reviewed !== void 0) note.reviewed = patch.reviewed;
2604
+ if (patch.excludeTags !== void 0) note.excludeTags = [...new Set(patch.excludeTags)];
2605
+ if (config.scope.length) {
2606
+ note.entries = {
2607
+ ...Object.fromEntries(config.scope.map((scope) => [scope, ""])),
2608
+ ...note.entries
2609
+ };
2610
+ if (patch.changelog !== void 0)
2611
+ note.entries = { ...note.entries, [patch.scope]: patch.changelog };
2612
+ } else {
2613
+ note.changelog ??= "";
2614
+ if (patch.changelog !== void 0) note.changelog = patch.changelog;
2615
+ }
2616
+ await writeJsonAtomic(file, note);
2617
+ return toChangelogCommit(metadata, note, config.scope);
2358
2618
  }
2359
2619
 
2360
2620
  // packages/service/src/index.ts
@@ -2365,16 +2625,16 @@ import { serve } from "@hono/node-server";
2365
2625
  import { serveStatic } from "@hono/node-server/serve-static";
2366
2626
  import { Hono } from "hono";
2367
2627
  import { existsSync } from "node:fs";
2368
- import { stat } from "node:fs/promises";
2369
- import path28 from "node:path";
2370
- import { z as z25 } from "zod";
2628
+ import { stat as stat2 } from "node:fs/promises";
2629
+ import path30 from "node:path";
2630
+ import { z as z27 } from "zod";
2371
2631
  function defaultWebDist() {
2372
- const fromSource = path28.resolve(import.meta.dirname, "../../../dist/web");
2373
- const fromBundle = path28.resolve(import.meta.dirname, "../../dist/web");
2374
- return [fromSource, fromBundle].find((directory) => existsSync(path28.join(directory, "index.html"))) ?? fromSource;
2632
+ const fromSource = path30.resolve(import.meta.dirname, "../../../dist/web");
2633
+ const fromBundle = path30.resolve(import.meta.dirname, "../../dist/web");
2634
+ return [fromSource, fromBundle].find((directory) => existsSync(path30.join(directory, "index.html"))) ?? fromSource;
2375
2635
  }
2376
2636
  async function startServer(options) {
2377
- const root = path28.resolve(options.repoRoot);
2637
+ const root = path30.resolve(options.repoRoot);
2378
2638
  await loadConfig({ repoRoot: root });
2379
2639
  const webDist = options.webDist ?? defaultWebDist();
2380
2640
  const app = createApp(root, webDist);
@@ -2405,7 +2665,7 @@ async function startServer(options) {
2405
2665
  function createApp(root, webDist) {
2406
2666
  const app = new Hono();
2407
2667
  app.onError((error, context) => {
2408
- const status = error instanceof z25.ZodError ? 400 : error.statusCode ?? 500;
2668
+ const status = error instanceof z27.ZodError ? 400 : error.statusCode ?? 500;
2409
2669
  return context.json({ error: String(error.message ?? error) }, status);
2410
2670
  });
2411
2671
  app.use("/api/*", async (context, next) => {
@@ -2416,6 +2676,39 @@ function createApp(root, webDist) {
2416
2676
  "/api/project",
2417
2677
  async (context) => context.json(await readProjectInfo({ repoRoot: root }))
2418
2678
  );
2679
+ app.get(
2680
+ "/api/changelog",
2681
+ async (context) => context.json(await listChangelogCommits({ repoRoot: root }))
2682
+ );
2683
+ app.get(
2684
+ "/api/changelog/:commitId/files",
2685
+ async (context) => context.json(
2686
+ await getChangelogFiles({
2687
+ repoRoot: root,
2688
+ commitId: context.req.param("commitId")
2689
+ })
2690
+ )
2691
+ );
2692
+ app.get(
2693
+ "/api/changelog/:commitId/diff",
2694
+ async (context) => context.json(
2695
+ await getChangelogDiff({
2696
+ repoRoot: root,
2697
+ commitId: context.req.param("commitId"),
2698
+ file: context.req.query("path") ?? ""
2699
+ })
2700
+ )
2701
+ );
2702
+ app.patch(
2703
+ "/api/changelog/:commitId",
2704
+ async (context) => context.json(
2705
+ await updateChangelogNote({
2706
+ repoRoot: root,
2707
+ commitId: context.req.param("commitId"),
2708
+ patch: await context.req.json()
2709
+ })
2710
+ )
2711
+ );
2419
2712
  app.get(
2420
2713
  "/api/code-changes",
2421
2714
  async (context) => context.json(await getGitChanges({ repoRoot: root, ref: context.req.query("ref") ?? "HEAD" }))
@@ -2458,6 +2751,14 @@ function createApp(root, webDist) {
2458
2751
  "/api/baselines",
2459
2752
  async (context) => context.json(await listBaselines({ repoRoot: root }))
2460
2753
  );
2754
+ app.get(
2755
+ "/api/tasks/removable",
2756
+ async (context) => context.json(await pruneTasks({ repoRoot: root, dryRun: true }))
2757
+ );
2758
+ app.delete(
2759
+ "/api/tasks/removable",
2760
+ async (context) => context.json(await pruneTasks({ repoRoot: root }))
2761
+ );
2461
2762
  app.get("/api/tasks/:taskId", async (context) => {
2462
2763
  return context.json(
2463
2764
  await readTaskReport({ repoRoot: root, taskId: context.req.param("taskId") })
@@ -2483,12 +2784,12 @@ function createApp(root, webDist) {
2483
2784
  await next();
2484
2785
  const filePath = context.get("staticFile");
2485
2786
  if (!filePath) return;
2486
- const stats = await stat(filePath);
2787
+ const stats = await stat2(filePath);
2487
2788
  context.header(
2488
2789
  "ETag",
2489
2790
  `W/"${stats.size.toString(16)}-${stats.mtimeMs.toString(16)}-${stats.ctimeMs.toString(16)}"`
2490
2791
  );
2491
- const relativePath = path28.relative(webDist, filePath).split(path28.sep).join("/");
2792
+ const relativePath = path30.relative(webDist, filePath).split(path30.sep).join("/");
2492
2793
  const immutable = context.req.path.startsWith("/report-static/") && /(?:^|[-/])[a-f0-9]{64}\.png$/.test(context.req.path) || !context.req.path.startsWith("/report-static/") && /^assets\/.+-[\w-]{8,}\.[\w.]+$/.test(relativePath);
2493
2794
  context.header("Cache-Control", immutable ? "public, max-age=31536000, immutable" : "no-cache");
2494
2795
  if (context.res.status !== 200 || !["GET", "HEAD"].includes(context.req.method)) return;
@@ -2528,7 +2829,7 @@ function createApp(root, webDist) {
2528
2829
  await next();
2529
2830
  });
2530
2831
  app.get("*", serveStatic({ root: webDist, ...staticOptions }));
2531
- app.get("*", (context, next) => path28.extname(context.req.path) ? context.notFound() : next());
2832
+ app.get("*", (context, next) => path30.extname(context.req.path) ? context.notFound() : next());
2532
2833
  app.get("*", serveStatic({ root: webDist, path: "index.html", ...staticOptions }));
2533
2834
  app.get("*", (context) => context.text("\u62A5\u544A UI \u5C1A\u672A\u6784\u5EFA\uFF1A\u8BF7\u5148\u8FD0\u884C pnpm build", 404));
2534
2835
  return app;
@@ -2557,47 +2858,108 @@ async function startWorkbench(options) {
2557
2858
  }
2558
2859
 
2559
2860
  // packages/service/src/init.ts
2560
- import { mkdir as mkdir4, readFile as readFile11, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
2561
- import path29 from "node:path";
2861
+ import { mkdir as mkdir3, readFile as readFile12, stat as stat3, writeFile as writeFile3 } from "node:fs/promises";
2862
+ import path31 from "node:path";
2562
2863
  async function initProject(directory) {
2563
- const root = path29.resolve(directory);
2564
- await mkdir4(root, { recursive: true });
2864
+ const root = path31.resolve(directory);
2865
+ await mkdir3(root, { recursive: true });
2565
2866
  const messages = [];
2566
2867
  async function create(file, content) {
2567
2868
  try {
2568
2869
  await writeFile3(file, content, { flag: "wx" });
2569
- messages.push(`\u5DF2\u521B\u5EFA ${path29.relative(root, file)}`);
2870
+ messages.push(`\u5DF2\u521B\u5EFA ${path31.relative(root, file)}`);
2570
2871
  } catch (error) {
2571
2872
  if (error.code !== "EEXIST") throw error;
2572
- messages.push(`\u5DF2\u4FDD\u7559 ${path29.relative(root, file)}`);
2873
+ messages.push(`\u5DF2\u4FDD\u7559 ${path31.relative(root, file)}`);
2573
2874
  }
2574
2875
  }
2575
- const skill = await readFile11(
2576
- path29.resolve(import.meta.dirname, "../../../skills/evidra/SKILL.md"),
2876
+ const skill = await readFile12(
2877
+ path31.resolve(import.meta.dirname, "../../../skills/evidra/SKILL.md"),
2577
2878
  "utf8"
2578
2879
  );
2579
2880
  let injected = false;
2580
2881
  for (const agent of [".claude", ".codex"]) {
2581
2882
  let exists = false;
2582
2883
  try {
2583
- exists = (await stat2(path29.join(root, agent))).isDirectory();
2884
+ exists = (await stat3(path31.join(root, agent))).isDirectory();
2584
2885
  } catch (error) {
2585
2886
  if (error.code !== "ENOENT") throw error;
2586
2887
  }
2587
2888
  if (!exists) continue;
2588
2889
  injected = true;
2589
- const target = path29.join(root, agent, "skills/evidra");
2590
- await mkdir4(target, { recursive: true });
2591
- await create(path29.join(target, "SKILL.md"), skill);
2890
+ const target = path31.join(root, agent, "skills/evidra");
2891
+ await mkdir3(target, { recursive: true });
2892
+ await create(path31.join(target, "SKILL.md"), skill);
2592
2893
  }
2593
2894
  if (!injected) messages.push("\u672A\u53D1\u73B0 .claude \u6216 .codex \u6587\u4EF6\u5939\uFF0C\u672A\u6CE8\u5165\u4EFB\u4F55 skill\u3002");
2594
2895
  return messages;
2595
2896
  }
2596
2897
 
2898
+ // packages/conformance/runner/cli.ts
2899
+ import { access as access2 } from "node:fs/promises";
2900
+ import path32 from "node:path";
2901
+ import { pathToFileURL } from "node:url";
2902
+ import { tsImport } from "tsx/esm/api";
2903
+
2904
+ // packages/conformance/runner/run.ts
2905
+ async function runner(common, tasks) {
2906
+ const results = [];
2907
+ for (const [index, task] of tasks.entries()) {
2908
+ try {
2909
+ const result = await task(Object.freeze({ ...common }));
2910
+ if (!result || typeof result.name !== "string" || typeof result.success !== "boolean" || typeof result.messages !== "string" || typeof result.howToFix !== "string") {
2911
+ throw new Error("\u4EFB\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684 RuleResult");
2912
+ }
2913
+ results.push(result);
2914
+ } catch (error) {
2915
+ results.push({
2916
+ name: `rule[${index + 1}]`,
2917
+ success: false,
2918
+ messages: error instanceof Error ? error.message : String(error),
2919
+ howToFix: "\u4FEE\u590D\u8BE5\u4EFB\u52A1\u7684\u914D\u7F6E\u6216\u6267\u884C\u9519\u8BEF\u540E\u91CD\u65B0\u8FD0\u884C\u3002"
2920
+ });
2921
+ }
2922
+ }
2923
+ return results;
2924
+ }
2925
+
2926
+ // packages/conformance/runner/report.ts
2927
+ function printResults(results) {
2928
+ for (const result of results) {
2929
+ console.log(`== ${result.name} ==`);
2930
+ console.log(result.messages);
2931
+ if (!result.success && result.howToFix) console.log(`\u4FEE\u590D\u5EFA\u8BAE\uFF1A${result.howToFix}`);
2932
+ console.log("");
2933
+ }
2934
+ return results.every((result) => result.success);
2935
+ }
2936
+
2937
+ // packages/conformance/runner/cli.ts
2938
+ async function runConformance(directory) {
2939
+ const file = path32.resolve(directory, "evidra.conformance.ts");
2940
+ await access2(file).catch(() => {
2941
+ throw new Error(`\u65E0\u6CD5\u8BFB\u53D6\u914D\u7F6E\u6587\u4EF6\uFF1A${file}`);
2942
+ });
2943
+ let config;
2944
+ try {
2945
+ const loaded = (await tsImport(pathToFileURL(file).href, import.meta.url)).default;
2946
+ config = loaded?.__esModule ? loaded.default : loaded;
2947
+ } catch (error) {
2948
+ throw new Error(
2949
+ `\u52A0\u8F7D\u914D\u7F6E\u5931\u8D25 ${file}\uFF1A${error instanceof Error ? error.message : String(error)}`
2950
+ );
2951
+ }
2952
+ if (!config || !Array.isArray(config.rules) || config.rules.some((task) => typeof task !== "function") || config.projectRoot !== void 0 && typeof config.projectRoot !== "string") {
2953
+ throw new Error(`${file} \u5FC5\u987B\u9ED8\u8BA4\u5BFC\u51FA { projectRoot?: string, rules: RuleTask[] }`);
2954
+ }
2955
+ const projectRoot = path32.resolve(path32.dirname(file), config.projectRoot ?? ".");
2956
+ return printResults(await runner({ projectRoot }, config.rules));
2957
+ }
2958
+
2597
2959
  // packages/service/src/cli.ts
2598
2960
  var cli = cac("evidra");
2599
2961
  cli.command("init [path]", "\u590D\u5236 skill \u5230\u9879\u76EE\uFF0C\u9ED8\u8BA4\u5F53\u524D\u76EE\u5F55").action(async (target) => {
2600
- const root = path30.resolve(target ?? process.cwd());
2962
+ const root = path33.resolve(target ?? process.cwd());
2601
2963
  console.log(`\u521D\u59CB\u5316 Evidra\uFF1A${root}`);
2602
2964
  for (const message of await initProject(root)) console.log(message);
2603
2965
  });
@@ -2606,14 +2968,14 @@ cli.command("start", "\u542F\u52A8\u5DE5\u4F5C\u53F0\uFF0C\u670D\u52A1\u5728\u52
2606
2968
  if (!Number.isInteger(port) || port < 1 || port > 65535)
2607
2969
  throw new Error("\u7AEF\u53E3\u5FC5\u987B\u662F 1\u201365535 \u7684\u6574\u6570");
2608
2970
  await startWorkbench({
2609
- repoRoot: path30.resolve(options.repo ?? process.env.TEST_REPORT_REPO ?? process.cwd()),
2971
+ repoRoot: path33.resolve(options.repo ?? process.env.TEST_REPORT_REPO ?? process.cwd()),
2610
2972
  port
2611
2973
  });
2612
2974
  });
2613
2975
  cli.command("compare", "\u8C03\u7528 core \u6BD4\u8F83\u4EFB\u52A1\u548C\u57FA\u7EBF\uFF0C\u8F93\u51FA summary").option("--repo <path>", "\u4ED3\u5E93\u8DEF\u5F84\uFF0C\u9ED8\u8BA4\u5F53\u524D\u76EE\u5F55").option("--task-id <id>", "\u4EFB\u52A1 ID").option("--full", "\u8F93\u51FA\u5B8C\u6574\u6BD4\u8F83\u7ED3\u679C").action(async (options) => {
2614
2976
  if (!options.taskId) throw new Error("\u8BF7\u63D0\u4F9B --task-id");
2615
2977
  const result = await compareTask({
2616
- repoRoot: path30.resolve(options.repo ?? process.cwd()),
2978
+ repoRoot: path33.resolve(options.repo ?? process.cwd()),
2617
2979
  taskId: options.taskId
2618
2980
  });
2619
2981
  console.log(JSON.stringify(options.full ? result : result.summary, null, 2));
@@ -2623,13 +2985,16 @@ cli.command("compare-tasks", "\u6BD4\u8F83\u4E24\u4E2A\u4EFB\u52A1\u7684\u7528\u
2623
2985
  if (!options.baseTaskId) throw new Error("\u8BF7\u63D0\u4F9B --base-task-id");
2624
2986
  if (!options.taskId) throw new Error("\u8BF7\u63D0\u4F9B --task-id");
2625
2987
  const result = await compareTasks({
2626
- repoRoot: path30.resolve(options.repo ?? process.cwd()),
2988
+ repoRoot: path33.resolve(options.repo ?? process.cwd()),
2627
2989
  baseTaskId: options.baseTaskId,
2628
2990
  taskId: options.taskId
2629
2991
  });
2630
2992
  console.log(JSON.stringify(options.full ? result : result.summary, null, 2));
2631
2993
  }
2632
2994
  );
2995
+ cli.command("conformance", "\u6267\u884C\u5F53\u524D\u76EE\u5F55 evidra.conformance.ts \u4E2D\u7684\u89C4\u7EA6").action(async () => {
2996
+ process.exitCode = await runConformance(process.cwd()) ? 0 : 1;
2997
+ });
2633
2998
  cli.help();
2634
2999
  try {
2635
3000
  cli.parse(process.argv, { run: false });