dsh-flakefinder 0.4.23 → 0.5.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/lib/tools.js CHANGED
@@ -1,15 +1,19 @@
1
1
  /**
2
- * 五个面向模型的测试稳定性工具:
3
- * flaky_detect / flaky_history / flaky_quarantine / flaky_clear / flaky_report。
2
+ * 六个面向模型的测试稳定性工具:
3
+ * flaky_detect / flaky_history / flaky_quarantine / flaky_clear / flaky_report / flaky_health。
4
4
  *
5
5
  * @module dsh-flakefinder/tools
6
6
  */
7
- import { buildPlan, readFramework } from './args.js';
8
- import { aggregate, flakyTests } from './classify.js';
9
- import { assertTarget, optionalInteger, optionalString, requiredString, resolveRuns, } from './config.js';
10
- import { executePlan } from './runner.js';
11
- import { createStore, formatRef, parseRef } from './store.js';
7
+ import crypto from 'node:crypto';
12
8
  import { resolve } from 'node:path';
9
+ import { buildPlan, detectEnvironment, readFramework, } from './adapters.js';
10
+ import { aggregate, flakyTests, patternLabel, redactSecrets, } from './classify.js';
11
+ import { assertTarget, optionalBoolean, optionalInteger, optionalSeed, optionalString, readDetectMode, requiredString, resolveConcurrency, resolveRuns, } from './config.js';
12
+ import { executePlansBatch } from './runner.js';
13
+ import { annotateTestsWithQuarantine, createStore, formatRef, parseRef, summarizeStability, } from './store.js';
14
+ const MAX_SEED = 2147483647;
15
+ const MAX_UNTRUNCATED_TESTS = 60;
16
+ const MAX_STABLE_PASS_WHEN_TRUNCATED = 20;
13
17
  function compileParameters(spec) {
14
18
  const properties = {};
15
19
  const required = [];
@@ -23,6 +27,8 @@ function compileParameters(spec) {
23
27
  node.description = prop.description;
24
28
  if (typeof prop?.items === 'string')
25
29
  node.items = { type: prop.items };
30
+ if (Array.isArray(prop?.enum) && prop.enum.length > 0)
31
+ node.enum = [...prop.enum];
26
32
  properties[key] = node;
27
33
  }
28
34
  return { type: 'object', properties, ...(required.length > 0 ? { required } : {}) };
@@ -30,6 +36,25 @@ function compileParameters(spec) {
30
36
  function asRecord(value) {
31
37
  return typeof value === 'object' && value !== null ? value : {};
32
38
  }
39
+ function resolveInvocation(exec, cfg, baseRunner, baseStore) {
40
+ const context = exec;
41
+ const signal = context?.signal;
42
+ signal?.throwIfAborted();
43
+ const rawSessionCwd = context?.agent?.session?.header?.cwd;
44
+ const sessionCwd = typeof rawSessionCwd === 'string' && rawSessionCwd.trim() !== '' ? rawSessionCwd.trim() : undefined;
45
+ const cwd = sessionCwd ?? process.cwd();
46
+ const scopedStore = sessionCwd !== undefined
47
+ ? createStore(cfg.dataDir, cfg.quarantineFileRelative !== undefined ? resolve(sessionCwd, cfg.quarantineFileRelative) : cfg.quarantineFile, { workspace: sessionCwd })
48
+ : baseStore;
49
+ const scopedRunner = {
50
+ run: (argv, options) => baseRunner.run(argv, {
51
+ ...options,
52
+ cwd: options?.cwd ?? cwd,
53
+ signal: options?.signal ?? signal,
54
+ }),
55
+ };
56
+ return { cwd, signal, runner: scopedRunner, store: scopedStore };
57
+ }
33
58
  function parseRefList(args) {
34
59
  const raw = args.tests;
35
60
  if (!Array.isArray(raw) || raw.length === 0)
@@ -42,6 +67,34 @@ function parseRefList(args) {
42
67
  return parseRef(item);
43
68
  });
44
69
  }
70
+ function readScope(raw) {
71
+ if (raw === undefined || raw === null)
72
+ return 'workspace';
73
+ if (raw === 'workspace' || raw === 'all')
74
+ return raw;
75
+ throw new Error('scope 只支持 workspace / all,收到:' + String(raw));
76
+ }
77
+ function optionalFailureRate(args, key) {
78
+ const value = args[key];
79
+ if (value === undefined || value === null)
80
+ return undefined;
81
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 100) {
82
+ throw new Error('失败率(参数 ' + key + ')必须是 0-100 之间的数字。');
83
+ }
84
+ return Math.round(value * 10) / 10;
85
+ }
86
+ function pickDistinctSeeds(count) {
87
+ const used = new Set();
88
+ const seeds = [];
89
+ while (seeds.length < count) {
90
+ const candidate = crypto.randomInt(1, MAX_SEED);
91
+ if (!used.has(candidate)) {
92
+ used.add(candidate);
93
+ seeds.push(candidate);
94
+ }
95
+ }
96
+ return seeds;
97
+ }
45
98
  function verdictLabel(verdict) {
46
99
  switch (verdict) {
47
100
  case 'stable-pass': return '稳定通过';
@@ -52,32 +105,170 @@ function verdictLabel(verdict) {
52
105
  default: return verdict;
53
106
  }
54
107
  }
108
+ function formatTimeline(timeline) {
109
+ return timeline.map(symbol => {
110
+ switch (symbol) {
111
+ case 'P': return '✓';
112
+ case 'F': return '✗';
113
+ case 'T': return '⏱';
114
+ case 'S': return 'S';
115
+ case '-': return '-';
116
+ }
117
+ }).join('');
118
+ }
119
+ function formatStackSnippet(stack, maxLines = 5) {
120
+ const lines = stack.split(/\r?\n/).filter(line => line.trim() !== '');
121
+ if (lines.length <= maxLines)
122
+ return lines;
123
+ return [...lines.slice(0, maxLines), '…(共 ' + String(lines.length) + ' 行,完整精简堆栈见 payload)'];
124
+ }
125
+ function pythonSourceLabel(source) {
126
+ switch (source) {
127
+ case 'explicit': return '显式配置';
128
+ case 'virtual-env': return 'VIRTUAL_ENV';
129
+ case 'workspace-venv': return '工作区虚拟环境';
130
+ case 'default': return '默认命令';
131
+ }
132
+ }
133
+ function isSyntheticTest(test) {
134
+ return test.file === '(crash)' || test.file === '(timeout)';
135
+ }
136
+ function formatClusterMessage(cluster) {
137
+ const type = cluster.type?.trim();
138
+ if (type === undefined || type === '')
139
+ return cluster.message;
140
+ if (cluster.message.startsWith(type + ':') || cluster.message.startsWith(type + ' ')) {
141
+ return cluster.message;
142
+ }
143
+ return type + ': ' + cluster.message;
144
+ }
145
+ function renderTestDiagnostics(test, options) {
146
+ const lines = [];
147
+ const tag = options?.quarantineTag ? ' ' + options.quarantineTag : '';
148
+ const seen = test.passes + test.failures;
149
+ const tl = formatTimeline(test.timeline);
150
+ lines.push('- ' + formatRef(test) + tag
151
+ + '(失败率 ' + String(test.failureRate) + '%,' + String(test.failures) + '/' + String(seen)
152
+ + ',时间线:' + tl + ')');
153
+ if (test.passDurationAvgMs !== null && test.failDurationAvgMs !== null) {
154
+ lines.push(' 耗时:通过均 ' + String(test.passDurationAvgMs) + 'ms / 失败均 ' + String(test.failDurationAvgMs)
155
+ + 'ms(P95 ' + String(test.p95DurationMs) + 'ms,最大 ' + String(test.maxDurationMs) + 'ms)');
156
+ }
157
+ else if (test.failDurationAvgMs !== null && test.maxDurationMs > 0) {
158
+ lines.push(' 耗时:失败均 ' + String(test.failDurationAvgMs) + 'ms(最大 ' + String(test.maxDurationMs) + 'ms)');
159
+ }
160
+ if (test.patterns.length > 0) {
161
+ lines.push(' 模式:' + test.patterns.map(patternLabel).join(';'));
162
+ }
163
+ if (test.failedSeeds !== undefined && test.failedSeeds.length > 0) {
164
+ lines.push(' 失败种子:' + test.failedSeeds.join(', '));
165
+ }
166
+ for (const cluster of test.errorClusters.slice(0, 3)) {
167
+ const runList = cluster.runIndices.map(i => '#' + String(i)).join(',');
168
+ lines.push(' 错误 [' + String(cluster.count) + '次,轮次 ' + runList + ']:' + formatClusterMessage(cluster));
169
+ if (cluster.sampleStack) {
170
+ for (const stackLine of formatStackSnippet(cluster.sampleStack, 5)) {
171
+ lines.push(' ' + stackLine);
172
+ }
173
+ }
174
+ }
175
+ if (test.errorClusters.length > 3) {
176
+ lines.push(' …其余 ' + String(test.errorClusters.length - 3) + ' 类错误见 payload');
177
+ }
178
+ return lines;
179
+ }
55
180
  function resultSummary(result, runs = [], subject) {
56
181
  const lines = [];
57
- if (subject !== undefined)
58
- lines.push('目标:' + subject.target + '(framework=' + subject.framework + ')');
59
- lines.push('判定:' + verdictLabel(result.verdict), '重复运行:' + String(result.runs.length) + ' 次;总耗时:' + String(Math.round(result.durationMs / 100) / 10) + ' 秒', '稳定通过:' + String(result.stablePassCount) + ';稳定失败:' + String(result.stableFailCount) + ';flaky:' + String(result.flakyCount) + ';跳过:' + String(result.skippedCount));
60
- if (result.flakyCount > 0) {
61
- lines.push('flaky 用例:');
62
- for (const test of result.tests.filter(item => item.verdict === 'flaky')) {
63
- lines.push('- ' + formatRef(test) + '(失败率 ' + String(test.failureRate) + '%)');
182
+ if (subject !== undefined) {
183
+ const meta = ['framework=' + subject.framework];
184
+ if (subject.testName !== undefined)
185
+ meta.push('testName=' + subject.testName);
186
+ if (subject.mode !== 'full')
187
+ meta.push('mode=' + subject.mode);
188
+ if (subject.concurrency > 1)
189
+ meta.push('concurrency=' + String(subject.concurrency));
190
+ if (subject.shuffle)
191
+ meta.push('shuffle=true');
192
+ if (subject.explicitSeed !== undefined)
193
+ meta.push('seed=' + String(subject.explicitSeed));
194
+ lines.push('目标:' + subject.target + '(' + meta.join(',') + ')');
195
+ }
196
+ const actualRuns = result.runs.length;
197
+ const plannedRuns = subject?.plannedRuns ?? actualRuns;
198
+ const runNote = actualRuns < plannedRuns
199
+ ? '实际运行 ' + String(actualRuns) + '/' + String(plannedRuns) + ' 次(' + String(subject?.mode ?? 'early-stop') + ' 提前结束)'
200
+ : '重复运行:' + String(actualRuns) + ' 次';
201
+ lines.push('判定:' + verdictLabel(result.verdict), runNote + ';总耗时:' + String(Math.round(result.durationMs / 100) / 10) + ' 秒', '稳定通过:' + String(result.stablePassCount) + ';稳定失败:' + String(result.stableFailCount) + ';flaky:' + String(result.flakyCount) + ';跳过:' + String(result.skippedCount));
202
+ if (result.verdict === 'stable-pass' && result.confidence95MaxFlakeRate !== undefined) {
203
+ const tip = actualRuns < 10 ? ' 建议提高 runs(例如 10-20 次)以获得更高稳定性置信度。' : '';
204
+ lines.push('置信度提示:连续 ' + String(actualRuns) + ' 次全通过,95% 置信下残余偶发率 ≤ ' + String(result.confidence95MaxFlakeRate) + '%。' + tip);
205
+ }
206
+ const alreadyQuarantinedIds = new Set((subject?.annotation?.alreadyQuarantinedFlaky ?? []).map(item => item.id));
207
+ const flakyList = result.tests.filter(item => item.verdict === 'flaky');
208
+ if (flakyList.length > 0) {
209
+ lines.push('flaky 用例(' + String(flakyList.length) + '):');
210
+ for (const test of flakyList) {
211
+ const quarantineTag = isSyntheticTest(test)
212
+ ? '[运行异常]'
213
+ : (alreadyQuarantinedIds.has(test.id) ? '[已隔离]' : '[新增未隔离]');
214
+ lines.push(...renderTestDiagnostics(test, { quarantineTag }));
215
+ }
216
+ }
217
+ const stableFailList = result.tests.filter(item => item.verdict === 'stable-fail');
218
+ if (stableFailList.length > 0) {
219
+ const shown = stableFailList.slice(0, 5);
220
+ const heading = stableFailList.length > 5
221
+ ? '稳定失败用例(共 ' + String(stableFailList.length) + ' 个,展示前 5 个):'
222
+ : '稳定失败用例(' + String(stableFailList.length) + '):';
223
+ lines.push(heading);
224
+ for (const test of shown) {
225
+ lines.push(...renderTestDiagnostics(test));
226
+ }
227
+ }
228
+ const clearCandidates = subject?.annotation?.clearCandidates ?? [];
229
+ if (result.verdict === 'stable-pass' && clearCandidates.length > 0) {
230
+ lines.push('可解除隔离候选(本次全部稳定通过,共 ' + String(clearCandidates.length) + ' 条):');
231
+ for (const entry of clearCandidates) {
232
+ lines.push('- ' + formatRef(entry) + '(原隔离原因:' + entry.reason + ')');
64
233
  }
234
+ lines.push('建议使用 flaky_clear 移除上述已恢复稳定的隔离条目。');
65
235
  }
66
- // 部分运行崩溃时 aggregate 不抛错,但错误原文只在 run.error 里;不带到摘要里用户只能看到「flaky」而不知道进程挂了。
67
- const crashed = runs.filter(run => run.report === null || run.error !== undefined);
68
- if (crashed.length > 0) {
69
- const first = crashed.find(run => run.error !== undefined)?.error ?? '未产出报告(stderr:' + (crashed[0].stderr.trim().split(/\r?\n/).slice(-3).join(' | ') || '无输出') + ')';
70
- lines.push('有 ' + String(crashed.length) + ' 次运行异常:' + first);
236
+ if (subject?.quarantineWarning !== undefined) {
237
+ lines.push('隔离清单读取警告:' + subject.quarantineWarning + '(不影响本次检测结果)');
71
238
  }
72
- lines.push('下一步:' + nextStepOf(result.verdict));
239
+ const timedOutRuns = runs.filter(run => run.timedOut === true);
240
+ const truncatedRuns = runs.filter(run => run.truncated === true);
241
+ const crashedRuns = runs.filter(run => run.report === null || run.error !== undefined);
242
+ if (timedOutRuns.length > 0 || truncatedRuns.length > 0 || crashedRuns.length > 0) {
243
+ const tags = [];
244
+ if (timedOutRuns.length > 0)
245
+ tags.push('超时 ' + String(timedOutRuns.length) + ' 次');
246
+ if (truncatedRuns.length > 0)
247
+ tags.push('输出截断 ' + String(truncatedRuns.length) + ' 次');
248
+ const otherCrashed = crashedRuns.filter(run => run.timedOut !== true && run.truncated !== true);
249
+ if (otherCrashed.length > 0)
250
+ tags.push('运行异常 ' + String(otherCrashed.length) + ' 次');
251
+ const firstRaw = crashedRuns.find(run => run.error !== undefined)?.error
252
+ ?? (crashedRuns.length > 0
253
+ ? '未产出报告(stderr:' + (crashedRuns[0].stderr.trim().split(/\r?\n/).slice(-3).join(' | ') || '无输出') + ')'
254
+ : '测试输出超过 4MB 采集上限被截断');
255
+ lines.push('运行异常汇总(' + tags.join(',') + '):' + redactSecrets(firstRaw));
256
+ }
257
+ if ((subject?.omittedStablePassCount ?? 0) > 0) {
258
+ lines.push('结果精简:payload 已保留全部 flaky / 失败 / 跳过用例与前 ' + String(MAX_STABLE_PASS_WHEN_TRUNCATED) + ' 个稳定通过用例(省略 ' + String(subject.omittedStablePassCount) + ' 个稳定通过用例)。');
259
+ }
260
+ lines.push('下一步:' + nextStepOf(result.verdict, clearCandidates.length));
73
261
  return lines.join('\n');
74
262
  }
75
263
  /** 按判定给出下一步;文案复用 tools 里已有的工具名,避免另造词汇。 */
76
- function nextStepOf(verdict) {
264
+ function nextStepOf(verdict, clearCandidateCount = 0) {
77
265
  switch (verdict) {
78
- case 'flaky': return '先用 flaky_quarantine 把这些用例写进隔离清单(写清原因),再单跑定位竞态;修复后用 flaky_detect 复查并 flaky_clear。';
266
+ case 'flaky': return '先用 flaky_quarantine 把新增未隔离的用例写进隔离清单(写清原因),再结合模式/错误聚类单跑定位竞态;修复后用 flaky_detect(可配 mode=verify-fix)复查并 flaky_clear。';
79
267
  case 'stable-fail': return '先单独跑一次这个测试看失败原因;若每次运行都崩溃(提示未产出报告),检查框架 CLI、reporter 与 pytest 的 junitxml 依赖。';
80
- case 'stable-pass': return '多轮全部通过;若此前隔离过这些用例,可用 flaky_clear 移除。';
268
+ case 'stable-pass':
269
+ return clearCandidateCount > 0
270
+ ? '多轮全部通过,且命中 ' + String(clearCandidateCount) + ' 条已隔离用例,可直接用 flaky_clear 移除它们。'
271
+ : '多轮全部通过;若此前隔离过这些用例,可用 flaky_clear 移除。';
81
272
  case 'skipped': return '所有用例被跳过:检查测试文件里的 skip / 条件编译,或 target 是否只匹配到空壳文件。';
82
273
  case 'empty': return '没有解析到用例:确认 target 指向存在的测试文件或目录(可用 glob,如 test/**/*.test.mjs),必要时显式指定 framework。';
83
274
  default: return '可运行 flaky_history / flaky_report 查看历史趋势。';
@@ -91,8 +282,17 @@ const testSchema = {
91
282
  name: { type: 'string' },
92
283
  passes: { type: 'integer' },
93
284
  failures: { type: 'integer' },
285
+ skips: { type: 'integer' },
94
286
  failureRate: { type: 'number' },
95
287
  verdict: { type: 'string' },
288
+ timeline: { type: 'array', items: { type: 'string' } },
289
+ passDurationAvgMs: { oneOf: [{ type: 'number' }, { type: 'null' }] },
290
+ failDurationAvgMs: { oneOf: [{ type: 'number' }, { type: 'null' }] },
291
+ maxDurationMs: { type: 'number' },
292
+ p95DurationMs: { type: 'number' },
293
+ errorClusters: { type: 'array', items: { type: 'object', additionalProperties: true } },
294
+ patterns: { type: 'array', items: { type: 'string' } },
295
+ failedSeeds: { type: 'array', items: { type: 'integer' } },
96
296
  },
97
297
  additionalProperties: true,
98
298
  };
@@ -102,39 +302,48 @@ const detectSchema = {
102
302
  target: { type: 'string' },
103
303
  framework: { type: 'string' },
104
304
  runs: { type: 'integer' },
305
+ plannedRuns: { type: 'integer' },
306
+ mode: { type: 'string' },
307
+ concurrency: { type: 'integer' },
105
308
  verdict: { type: 'string' },
106
309
  stablePassCount: { type: 'integer' },
107
310
  stableFailCount: { type: 'integer' },
108
311
  flakyCount: { type: 'integer' },
109
312
  skippedCount: { type: 'integer' },
110
313
  durationMs: { type: 'integer' },
314
+ confidence95MaxFlakeRate: { type: 'number' },
111
315
  runResults: { type: 'array', items: { type: 'object', additionalProperties: true } },
112
316
  tests: { type: 'array', items: testSchema },
317
+ testsTruncated: { type: 'boolean' },
318
+ omittedStablePassCount: { type: 'integer' },
113
319
  flakyTests: { type: 'array', items: { type: 'object', additionalProperties: true } },
320
+ quarantineSync: { type: 'object', additionalProperties: true },
114
321
  },
115
322
  additionalProperties: true,
116
323
  };
117
- /** 构建五个工具定义。 */
324
+ /** 构建六个工具定义(每次执行只解析当前调用的工作区与取消信号,不重建工具定义)。 */
118
325
  export function buildFlakeTools(cfg, runner, store) {
119
- return buildWorkspaceTools(cfg, runner, store).map(tool => ({ ...tool, async execute(args, exec) {
120
- const context = exec;
121
- const signal = context?.signal;
122
- signal?.throwIfAborted();
123
- const cwd = context?.agent?.session?.header?.cwd || process.cwd();
124
- const scopedStore = context?.agent?.session?.header?.cwd && cfg.quarantineFileRelative ? createStore(cfg.dataDir, resolve(cwd, cfg.quarantineFileRelative)) : store;
125
- const scopedRunner = { run: (argv, options) => runner.run(argv, { ...options, cwd, signal }) };
126
- const selected = buildWorkspaceTools(cfg, scopedRunner, scopedStore, cwd, signal).find(row => row.name === tool.name);
127
- return selected.execute(args, exec);
128
- } }));
129
- }
130
- function buildWorkspaceTools(cfg, runner, store, cwd = process.cwd(), signal) {
131
326
  const detect = {
132
327
  name: 'flaky_detect',
133
- description: '重复运行测试多次并判定稳定性:stable-pass(全过)/ stable-fail(全挂)/ flaky(时好时坏)。支持 vitest / jest / pytest / node:test,自动探测本地框架。结果写入历史供 flaky_report 分析。',
328
+ description: '重复运行测试多次并判定稳定性:stable-pass(全过)/ stable-fail(全挂)/ flaky(时好时坏)。支持 vitest / jest / pytest / node:test、用例名过滤(testName)、早停模式(until-flaky / verify-fix)、受控并发(concurrency)、顺序打乱(shuffle/seed)、错误聚类、根因模式推断与隔离清单交叉对照。结果写入工作区历史供 flaky_report 分析。',
134
329
  parameters: compileParameters({
135
330
  target: { type: 'string', required: true, description: '测试文件、目录或 glob(相对当前工作区)。不能以 - 开头。' },
136
- framework: { type: 'string', description: 'auto(默认,自动探测 vitest→jest→pytest→node:test)/ vitest / jest / pytest / node。' },
137
- runs: { type: 'integer', description: '重复次数,默认取配置 defaultRuns。' },
331
+ framework: {
332
+ type: 'string',
333
+ enum: ['auto', 'vitest', 'jest', 'pytest', 'node'],
334
+ description: 'auto(默认,自动探测 vitest→jest→pytest→node:test)/ vitest / jest / pytest / node。',
335
+ },
336
+ runs: { type: 'integer', description: '重复次数(3-' + String(cfg.maxRuns) + '),默认取配置 defaultRuns。' },
337
+ testName: { type: 'string', description: '按用例名/模式精准过滤(Vitest/Jest -t、pytest -k、node:test --test-name-pattern)。不能以 - 开头。' },
338
+ mode: {
339
+ type: 'string',
340
+ enum: ['full', 'until-flaky', 'verify-fix'],
341
+ description: '执行模式:full(默认,跑满 runs 次)/ until-flaky(一旦确认不稳定即早停)/ verify-fix(修复复测,首次失败即早停)。',
342
+ },
343
+ concurrency: { type: 'integer', description: '受控并发 worker 数(1-4,默认取配置 defaultConcurrency)。' },
344
+ shuffle: { type: 'boolean', description: '是否打乱测试执行顺序(Vitest/Jest 生效,默认 false)。未传 seed 时每轮生成不同随机种子并记录。' },
345
+ seed: { type: 'integer', description: '可选随机种子(0-2147483647),配合 shuffle 复现特定顺序失败。' },
346
+ noCoverage: { type: 'boolean', description: '是否关闭覆盖率采集以加速复跑(Vitest/Jest 生效,默认取配置 noCoverage)。' },
138
347
  }),
139
348
  output: {
140
349
  schema: detectSchema,
@@ -144,19 +353,93 @@ function buildWorkspaceTools(cfg, runner, store, cwd = process.cwd(), signal) {
144
353
  return [{ type: 'text', text: summary === '' ? '检测完成。' : summary }];
145
354
  },
146
355
  },
147
- async execute(rawArgs) {
356
+ async execute(rawArgs, exec) {
357
+ const { cwd, signal, runner: scopedRunner, store: scopedStore } = resolveInvocation(exec, cfg, runner, store);
148
358
  const args = asRecord(rawArgs);
149
359
  const target = assertTarget(requiredString(args, 'target', '测试目标'));
150
360
  const requested = readFramework(args.framework);
151
361
  const runs = resolveRuns(args.runs, cfg);
152
- const plans = Array.from({ length: runs }, (_, index) => buildPlan(cwd, target, requested, index, cfg.pythonPath));
362
+ const testName = optionalString(args, 'testName');
363
+ const mode = readDetectMode(args.mode);
364
+ const concurrency = resolveConcurrency(args.concurrency, cfg);
365
+ const noCoverage = optionalBoolean(args, 'noCoverage', cfg.noCoverage);
366
+ const explicitSeed = optionalSeed(args, 'seed');
367
+ const shuffle = args.shuffle === undefined || args.shuffle === null
368
+ ? explicitSeed !== undefined
369
+ : optionalBoolean(args, 'shuffle', false);
370
+ const runSeeds = shuffle && explicitSeed === undefined ? pickDistinctSeeds(runs) : undefined;
371
+ const plans = Array.from({ length: runs }, (_, index) => buildPlan(cwd, target, requested, index, cfg.pythonPath, {
372
+ ...(testName !== undefined ? { testName } : {}),
373
+ noCoverage,
374
+ ...(shuffle ? { shuffle: true, seed: explicitSeed ?? runSeeds[index] } : {}),
375
+ concurrency,
376
+ pythonPathExplicit: cfg.pythonPathExplicit,
377
+ }));
153
378
  const framework = plans[0]?.framework ?? 'node';
154
- const executed = [];
155
- for (let index = 0; index < plans.length; index += 1) {
156
- signal?.throwIfAborted();
157
- executed.push(await executePlan(runner, plans[index], index + 1, cfg.timeoutMs, cwd, signal));
379
+ const executed = await executePlansBatch(scopedRunner, plans, {
380
+ timeoutMs: cfg.timeoutMs,
381
+ cwd,
382
+ signal,
383
+ concurrency,
384
+ mode,
385
+ });
386
+ const result = aggregate(executed.map(item => ({
387
+ index: item.index,
388
+ report: item.report,
389
+ durationMs: item.durationMs,
390
+ error: item.error,
391
+ timedOut: item.timedOut,
392
+ truncated: item.truncated,
393
+ seed: item.seed,
394
+ })));
395
+ let quarantineWarning;
396
+ let quarantineDoc = { version: 1, quarantined: [] };
397
+ if (typeof scopedStore.loadQuarantine === 'function') {
398
+ try {
399
+ quarantineDoc = await scopedStore.loadQuarantine();
400
+ }
401
+ catch (error) {
402
+ quarantineWarning = error instanceof Error ? error.message : String(error);
403
+ }
404
+ }
405
+ const rawAnnotation = annotateTestsWithQuarantine(result.tests, quarantineDoc);
406
+ const annotation = testName !== undefined
407
+ ? {
408
+ ...rawAnnotation,
409
+ clearCandidates: rawAnnotation.clearCandidates.filter(entry => entry.name !== null),
410
+ }
411
+ : rawAnnotation;
412
+ const failedSeedSet = new Set();
413
+ for (const test of result.tests) {
414
+ if (test.failedSeeds !== undefined) {
415
+ for (const seedValue of test.failedSeeds)
416
+ failedSeedSet.add(seedValue);
417
+ }
418
+ }
419
+ for (const run of result.runs) {
420
+ if (!run.success && run.seed !== undefined)
421
+ failedSeedSet.add(run.seed);
422
+ }
423
+ const failedSeeds = failedSeedSet.size > 0 ? [...failedSeedSet].sort((a, b) => a - b) : undefined;
424
+ const errorSummaryMap = new Map();
425
+ for (const test of result.tests) {
426
+ if (test.verdict !== 'flaky' && test.verdict !== 'stable-fail')
427
+ continue;
428
+ for (const cluster of test.errorClusters) {
429
+ const text = formatClusterMessage(cluster);
430
+ const shortText = text.length > 160 ? text.slice(0, 159) + '…' : text;
431
+ const existing = errorSummaryMap.get(cluster.fingerprint);
432
+ if (existing === undefined) {
433
+ errorSummaryMap.set(cluster.fingerprint, { message: shortText, count: cluster.count });
434
+ }
435
+ else {
436
+ existing.count += cluster.count;
437
+ }
438
+ }
158
439
  }
159
- const result = aggregate(executed.map(item => ({ index: item.index, report: item.report, durationMs: item.durationMs, error: item.error })));
440
+ const errorSummary = errorSummaryMap.size > 0
441
+ ? [...errorSummaryMap.values()].sort((a, b) => b.count - a.count).slice(0, 5)
442
+ : undefined;
160
443
  const flaky = flakyTests(result);
161
444
  const entry = {
162
445
  timestamp: new Date().toISOString(),
@@ -170,23 +453,82 @@ function buildWorkspaceTools(cfg, runner, store, cwd = process.cwd(), signal) {
170
453
  flakyCount: result.flakyCount,
171
454
  skippedCount: result.skippedCount,
172
455
  flakyTests: flaky,
456
+ ...(scopedStore.workspace !== undefined ? { workspace: scopedStore.workspace } : {}),
457
+ ...(testName !== undefined ? { testName } : {}),
458
+ ...(mode !== 'full' ? { mode } : {}),
459
+ ...(concurrency > 1 ? { concurrency } : {}),
460
+ ...(shuffle ? { shuffle: true } : {}),
461
+ ...(failedSeeds !== undefined ? { failedSeeds } : {}),
462
+ ...(errorSummary !== undefined ? { errorSummary } : {}),
173
463
  };
174
464
  signal?.throwIfAborted();
175
- await store.appendHistory(entry);
465
+ await scopedStore.appendHistory(entry);
466
+ let returnedTests = result.tests;
467
+ let testsTruncated = false;
468
+ let omittedStablePassCount = 0;
469
+ if (result.tests.length > MAX_UNTRUNCATED_TESTS) {
470
+ const nonPass = result.tests.filter(test => test.verdict !== 'stable-pass');
471
+ const stablePass = result.tests.filter(test => test.verdict === 'stable-pass');
472
+ if (stablePass.length > MAX_STABLE_PASS_WHEN_TRUNCATED) {
473
+ returnedTests = [...nonPass, ...stablePass.slice(0, MAX_STABLE_PASS_WHEN_TRUNCATED)];
474
+ testsTruncated = true;
475
+ omittedStablePassCount = stablePass.length - MAX_STABLE_PASS_WHEN_TRUNCATED;
476
+ }
477
+ }
478
+ const toSyncItem = (test) => ({
479
+ id: test.id,
480
+ file: test.file,
481
+ name: test.name,
482
+ ref: formatRef(test),
483
+ failureRate: test.failureRate,
484
+ });
485
+ const quarantineSync = {
486
+ newFlaky: annotation.newFlaky.filter(test => !isSyntheticTest(test)).map(toSyncItem),
487
+ alreadyQuarantinedFlaky: annotation.alreadyQuarantinedFlaky.map(toSyncItem),
488
+ clearCandidates: annotation.clearCandidates.map(item => ({
489
+ file: item.file,
490
+ name: item.name,
491
+ ref: formatRef(item),
492
+ reason: item.reason,
493
+ since: item.since,
494
+ })),
495
+ ...(quarantineWarning !== undefined ? { warning: quarantineWarning } : {}),
496
+ };
176
497
  return {
177
498
  target,
178
499
  framework,
179
500
  runs: result.runs.length,
501
+ plannedRuns: runs,
502
+ mode,
503
+ concurrency,
504
+ ...(testName !== undefined ? { testName } : {}),
505
+ ...(shuffle ? { shuffle: true } : {}),
506
+ ...(executed.length < runs ? { earlyStopped: true } : {}),
180
507
  verdict: result.verdict,
181
508
  stablePassCount: result.stablePassCount,
182
509
  stableFailCount: result.stableFailCount,
183
510
  flakyCount: result.flakyCount,
184
511
  skippedCount: result.skippedCount,
185
512
  durationMs: result.durationMs,
513
+ ...(result.confidence95MaxFlakeRate !== undefined ? { confidence95MaxFlakeRate: result.confidence95MaxFlakeRate } : {}),
186
514
  runResults: result.runs,
187
- tests: result.tests,
515
+ tests: returnedTests,
516
+ ...(testsTruncated ? { testsTruncated: true, omittedStablePassCount } : {}),
188
517
  flakyTests: flaky,
189
- summary: resultSummary(result, executed, { target, framework }),
518
+ quarantineSync,
519
+ summary: resultSummary(result, executed, {
520
+ target,
521
+ framework,
522
+ plannedRuns: runs,
523
+ testName,
524
+ mode,
525
+ concurrency,
526
+ shuffle,
527
+ explicitSeed: shuffle ? explicitSeed : undefined,
528
+ annotation,
529
+ quarantineWarning,
530
+ omittedStablePassCount,
531
+ }),
190
532
  };
191
533
  },
192
534
  timeoutMs: runsTimeout(cfg),
@@ -194,15 +536,24 @@ function buildWorkspaceTools(cfg, runner, store, cwd = process.cwd(), signal) {
194
536
  const history = {
195
537
  name: 'flaky_history',
196
538
  isConcurrencySafe: () => true,
197
- description: '查询 flaky_detect 的历史记录,可按测试目标过滤,用于判断某个测试是长期稳定失败还是偶发问题。',
539
+ description: '查询 flaky_detect 的历史记录,默认按当前工作区隔离,可按测试目标过滤或切到 scope=all 跨工作区查看。',
198
540
  parameters: compileParameters({
199
541
  target: { type: 'string', description: '按测试目标过滤(可选,子串匹配)。' },
200
542
  limit: { type: 'integer', description: '返回条数 1-100(默认 20)。' },
543
+ scope: {
544
+ type: 'string',
545
+ enum: ['workspace', 'all'],
546
+ description: '查询范围:workspace(默认,仅当前工作区)/ all(跨工作区汇总)。',
547
+ },
201
548
  }),
202
549
  output: {
203
550
  schema: {
204
551
  type: 'object',
205
- properties: { count: { type: 'integer' }, entries: { type: 'array', items: { type: 'object', additionalProperties: true } } },
552
+ properties: {
553
+ scope: { type: 'string' },
554
+ count: { type: 'integer' },
555
+ entries: { type: 'array', items: { type: 'object', additionalProperties: true } },
556
+ },
206
557
  additionalProperties: true,
207
558
  },
208
559
  render: (_args, value) => {
@@ -211,53 +562,112 @@ function buildWorkspaceTools(cfg, runner, store, cwd = process.cwd(), signal) {
211
562
  if (entries.length === 0) {
212
563
  return [{ type: 'text', text: '历史记录 0 条:还没有跑过 flaky_detect(或过滤条件没有命中)。下一步:先对目标运行 flaky_detect,再用本工具看趋势。' }];
213
564
  }
214
- const lines = ['历史记录 ' + String(entries.length) + ' 条(新的在前):'];
565
+ const scopeNote = rec.scope === 'all' ? ',跨工作区' : '';
566
+ const lines = ['历史记录 ' + String(entries.length) + ' 条(新的在前' + scopeNote + '):'];
215
567
  for (const item of entries) {
216
568
  const row = asRecord(item);
217
569
  const flaky = Number(row.flakyCount ?? 0);
218
- lines.push('- ' + row.timestamp + ' ' + row.target + '(' + row.framework + ',' + verdictLabel(String(row.verdict ?? '')) + ',' + String(row.runs ?? '?') + ' 次' + (flaky > 0 ? ',flaky ' + String(flaky) : '') + ')');
570
+ const extras = [
571
+ String(row.framework ?? ''),
572
+ verdictLabel(String(row.verdict ?? '')),
573
+ String(row.runs ?? '?') + ' 次',
574
+ ];
575
+ if (typeof row.testName === 'string' && row.testName !== '')
576
+ extras.push('testName=' + row.testName);
577
+ if (typeof row.mode === 'string' && row.mode !== '' && row.mode !== 'full')
578
+ extras.push('mode=' + row.mode);
579
+ if (flaky > 0)
580
+ extras.push('flaky ' + String(flaky));
581
+ lines.push('- ' + row.timestamp + ' ' + row.target + '(' + extras.join(',') + ')');
219
582
  }
220
583
  lines.push('下一步:需要判定标准/隔离清单汇总时用 flaky_report;修复后重新 flaky_detect 复查。');
221
584
  return [{ type: 'text', text: lines.join('\n') }];
222
585
  },
223
586
  },
224
- async execute(rawArgs) {
587
+ async execute(rawArgs, exec) {
588
+ const { store: scopedStore } = resolveInvocation(exec, cfg, runner, store);
225
589
  const args = asRecord(rawArgs);
226
590
  const target = optionalString(args, 'target');
227
591
  const limit = optionalInteger(args, 'limit', '返回条数', 1, 100, 20);
228
- const entries = await store.listHistory(target, limit);
229
- return { count: entries.length, entries };
592
+ const scope = readScope(args.scope);
593
+ const entries = await scopedStore.listHistory(target, limit, scope);
594
+ return { scope, count: entries.length, entries };
230
595
  },
231
596
  timeoutMs: 10000,
232
597
  };
233
598
  const quarantine = {
234
599
  name: 'flaky_quarantine',
235
- description: '把确认的 flaky 用例写入项目根 .flakefinder.json 隔离清单(不修改测试源码)。需要 flaky_detect 判定为 flaky 后再使用。',
600
+ description: '把确认的 flaky 用例写入项目根 .flakefinder.json 隔离清单(不修改测试源码),支持记录关联 issue 与最近失败率。需要 flaky_detect 判定为 flaky 后再使用。',
236
601
  parameters: compileParameters({
237
602
  tests: { type: 'array', items: 'string', required: true, description: '1-100 条测试引用:文件路径,或 "文件路径 > 用例名"。' },
238
603
  reason: { type: 'string', required: true, description: '隔离原因(会写进清单,例如:定时器竞态,见 issue #12)。' },
604
+ issue: { type: 'string', description: '关联的 issue / PR / 工单编号或链接(可选,例如 #123)。' },
605
+ lastFailureRate: { type: 'number', description: '最近一次检测到的失败率百分比 0-100(可选)。' },
239
606
  }),
240
607
  output: {
241
608
  schema: {
242
609
  type: 'object',
243
- properties: { file: { type: 'string' }, addedCount: { type: 'integer' }, added: { type: 'array', items: { type: 'object', additionalProperties: true } } },
610
+ properties: {
611
+ file: { type: 'string' },
612
+ addedCount: { type: 'integer' },
613
+ updatedCount: { type: 'integer' },
614
+ added: { type: 'array', items: { type: 'object', additionalProperties: true } },
615
+ updated: { type: 'array', items: { type: 'object', additionalProperties: true } },
616
+ },
244
617
  additionalProperties: true,
245
618
  },
246
619
  render: (_args, value) => {
247
620
  const rec = asRecord(value);
248
621
  const added = Number(rec.addedCount ?? 0);
249
- const head = added === 0
250
- ? '隔离清单 ' + rec.file + ' 未新增条目:这些用例已在清单里(同文件同用例名视为同一条)。'
251
- : '已写入隔离清单 ' + rec.file + ',新增 ' + String(added) + ' 条。';
252
- return [{ type: 'text', text: head + '\n下一步:修复后运行 flaky_detect 多轮全部通过,再用 flaky_clear 移除这些条目。' }];
622
+ const updated = Number(rec.updatedCount ?? 0);
623
+ const addedItems = Array.isArray(rec.added) ? rec.added : [];
624
+ const updatedItems = Array.isArray(rec.updated) ? rec.updated : [];
625
+ let head;
626
+ if (added > 0 && updated > 0) {
627
+ head = '已更新隔离清单 ' + String(rec.file ?? '') + ':新增 ' + String(added) + ' 条,更新 ' + String(updated) + ' 条。';
628
+ }
629
+ else if (added > 0) {
630
+ head = '已写入隔离清单 ' + String(rec.file ?? '') + ',新增 ' + String(added) + ' 条。';
631
+ }
632
+ else if (updated > 0) {
633
+ head = '已更新隔离清单 ' + String(rec.file ?? '') + ' 中已有的 ' + String(updated) + ' 条记录(保留原隔离时间,已更新原因/元数据)。';
634
+ }
635
+ else {
636
+ head = '隔离清单 ' + String(rec.file ?? '') + ' 无变更。';
637
+ }
638
+ const lines = [head];
639
+ for (const item of addedItems.slice(0, 10)) {
640
+ const row = asRecord(item);
641
+ lines.push('+ ' + formatRef({ file: String(row.file ?? ''), name: typeof row.name === 'string' ? row.name : null }) + ':' + String(row.reason ?? ''));
642
+ }
643
+ for (const item of updatedItems.slice(0, 10)) {
644
+ const row = asRecord(item);
645
+ lines.push('~ ' + formatRef({ file: String(row.file ?? ''), name: typeof row.name === 'string' ? row.name : null }) + ':' + String(row.reason ?? ''));
646
+ }
647
+ lines.push('下一步:修复后运行 flaky_detect 多轮全部通过,再用 flaky_clear 移除这些条目。');
648
+ return [{ type: 'text', text: lines.join('\n') }];
253
649
  },
254
650
  },
255
- async execute(rawArgs) {
651
+ async execute(rawArgs, exec) {
652
+ const { store: scopedStore } = resolveInvocation(exec, cfg, runner, store);
256
653
  const args = asRecord(rawArgs);
257
654
  const refs = parseRefList(args);
258
655
  const reason = requiredString(args, 'reason', '隔离原因');
259
- const outcome = await store.addQuarantine(refs, reason);
260
- return { file: outcome.file, addedCount: outcome.added.length, added: outcome.added };
656
+ const issue = optionalString(args, 'issue');
657
+ const lastFailureRate = optionalFailureRate(args, 'lastFailureRate');
658
+ const addOptions = {
659
+ ...(issue !== undefined ? { issue } : {}),
660
+ ...(lastFailureRate !== undefined ? { lastFailureRate } : {}),
661
+ };
662
+ const outcome = await scopedStore.addQuarantine(refs, reason, Object.keys(addOptions).length > 0 ? addOptions : undefined);
663
+ const updated = Array.isArray(outcome.updated) ? outcome.updated : [];
664
+ return {
665
+ file: outcome.file,
666
+ addedCount: outcome.added.length,
667
+ updatedCount: updated.length,
668
+ added: outcome.added,
669
+ updated,
670
+ };
261
671
  },
262
672
  timeoutMs: 10000,
263
673
  };
@@ -282,10 +692,11 @@ function buildWorkspaceTools(cfg, runner, store, cwd = process.cwd(), signal) {
282
692
  return [{ type: 'text', text: head + (removed === 0 ? '' : '\n下一步:建议再跑一次 flaky_detect,确认移除后仍稳定。') }];
283
693
  },
284
694
  },
285
- async execute(rawArgs) {
695
+ async execute(rawArgs, exec) {
696
+ const { store: scopedStore } = resolveInvocation(exec, cfg, runner, store);
286
697
  const args = asRecord(rawArgs);
287
698
  const refs = parseRefList(args);
288
- const outcome = await store.removeQuarantine(refs);
699
+ const outcome = await scopedStore.removeQuarantine(refs);
289
700
  return { file: outcome.file, removedCount: outcome.removed.length, removed: outcome.removed };
290
701
  },
291
702
  timeoutMs: 10000,
@@ -293,20 +704,28 @@ function buildWorkspaceTools(cfg, runner, store, cwd = process.cwd(), signal) {
293
704
  const report = {
294
705
  name: 'flaky_report',
295
706
  isConcurrencySafe: () => true,
296
- description: '汇总隔离清单与检测历史,输出项目测试稳定性报告(只读,不运行测试)。',
707
+ description: '汇总隔离清单、高频不稳定 Top 榜单、超期未复查提醒与检测历史,输出项目测试稳定性报告(只读,不运行测试)。',
297
708
  parameters: compileParameters({
298
709
  target: { type: 'string', description: '按测试目标过滤历史(可选)。' },
299
710
  historyLimit: { type: 'integer', description: '历史条数 1-100(默认 20)。' },
711
+ scope: {
712
+ type: 'string',
713
+ enum: ['workspace', 'all'],
714
+ description: '历史查询范围:workspace(默认,仅当前工作区)/ all(跨工作区汇总)。',
715
+ },
300
716
  }),
301
717
  output: {
302
718
  schema: {
303
719
  type: 'object',
304
720
  properties: {
721
+ scope: { type: 'string' },
305
722
  quarantineFile: { type: 'string' },
306
723
  quarantinedCount: { type: 'integer' },
307
724
  quarantined: { type: 'array', items: { type: 'object', additionalProperties: true } },
308
725
  historyCount: { type: 'integer' },
309
726
  history: { type: 'array', items: { type: 'object', additionalProperties: true } },
727
+ topFlakyTests: { type: 'array', items: { type: 'object', additionalProperties: true } },
728
+ staleQuarantined: { type: 'array', items: { type: 'object', additionalProperties: true } },
310
729
  },
311
730
  additionalProperties: true,
312
731
  },
@@ -314,6 +733,9 @@ function buildWorkspaceTools(cfg, runner, store, cwd = process.cwd(), signal) {
314
733
  const rec = asRecord(value);
315
734
  const quarantined = Array.isArray(rec.quarantined) ? rec.quarantined : [];
316
735
  const history = Array.isArray(rec.history) ? rec.history : [];
736
+ const topFlakyTests = Array.isArray(rec.topFlakyTests) ? rec.topFlakyTests : [];
737
+ const staleQuarantined = Array.isArray(rec.staleQuarantined) ? rec.staleQuarantined : [];
738
+ const staleDays = Number(rec.staleQuarantineDays ?? cfg.staleQuarantineDays);
317
739
  const lines = [
318
740
  '测试稳定性报告',
319
741
  '隔离清单:' + String(rec.quarantineFile ?? '') + '(' + String(rec.quarantinedCount ?? 0) + ' 条)',
@@ -322,34 +744,72 @@ function buildWorkspaceTools(cfg, runner, store, cwd = process.cwd(), signal) {
322
744
  lines.push('- 清单为空:还没有被隔离的用例。下一步:flaky_detect 判定为 flaky 后用 flaky_quarantine 写入。');
323
745
  for (const item of quarantined) {
324
746
  const row = asRecord(item);
325
- lines.push('- ' + formatRef({ file: String(row.file ?? ''), name: typeof row.name === 'string' ? row.name : null }) + ':' + String(row.reason ?? ''));
747
+ const meta = [];
748
+ if (typeof row.issue === 'string' && row.issue !== '')
749
+ meta.push('关联 ' + row.issue);
750
+ if (typeof row.lastFailureRate === 'number')
751
+ meta.push('最近失败率 ' + String(row.lastFailureRate) + '%');
752
+ const suffix = meta.length > 0 ? '(' + meta.join(',') + ')' : '';
753
+ lines.push('- ' + formatRef({ file: String(row.file ?? ''), name: typeof row.name === 'string' ? row.name : null }) + ':' + String(row.reason ?? '') + suffix);
754
+ }
755
+ if (staleQuarantined.length > 0) {
756
+ lines.push('', '超期未复查隔离项(>' + String(staleDays) + ' 天,共 ' + String(staleQuarantined.length) + ' 条):');
757
+ for (const item of staleQuarantined) {
758
+ const row = asRecord(item);
759
+ lines.push('- ' + formatRef({ file: String(row.file ?? ''), name: typeof row.name === 'string' ? row.name : null })
760
+ + ':已隔离 ' + String(row.ageDays ?? '?') + ' 天(原因:' + String(row.reason ?? '') + ')');
761
+ }
762
+ lines.push('建议对上述超期条目重新运行 flaky_detect 复查;若已稳定通过,用 flaky_clear 清理。');
763
+ }
764
+ if (topFlakyTests.length > 0) {
765
+ lines.push('', '历史高频不稳定 Top ' + String(topFlakyTests.length) + ':');
766
+ for (const item of topFlakyTests) {
767
+ const row = asRecord(item);
768
+ const tag = row.quarantined === true ? '[已隔离]' : '[未隔离]';
769
+ lines.push('- ' + formatRef({ file: String(row.file ?? ''), name: typeof row.name === 'string' ? row.name : null }) + ' ' + tag
770
+ + ':出现 ' + String(row.occurrences ?? 0) + ' 次,平均失败率 ' + String(row.avgFailureRate ?? 0)
771
+ + '%(最高 ' + String(row.maxFailureRate ?? 0) + '%)');
772
+ }
326
773
  }
327
- // 报告以前只渲染隔离清单,把 payload 里的检测历史整段丢掉;用户看不到「最近判定」。
328
774
  lines.push('', '检测历史:' + String(rec.historyCount ?? history.length) + ' 条');
329
775
  if (history.length === 0)
330
776
  lines.push('- 还没有检测记录:先对一个目标运行 flaky_detect。');
331
777
  for (const item of history.slice(0, 10)) {
332
778
  const row = asRecord(item);
333
779
  const flaky = Number(row.flakyCount ?? 0);
334
- lines.push('- ' + row.timestamp + ' ' + row.target + '(' + verdictLabel(String(row.verdict ?? '')) + ',' + String(row.runs ?? '?') + ' 次' + (flaky > 0 ? ',flaky ' + String(flaky) : '') + ')');
780
+ const extras = [verdictLabel(String(row.verdict ?? '')), String(row.runs ?? '?') + ' 次'];
781
+ if (typeof row.testName === 'string' && row.testName !== '')
782
+ extras.push('testName=' + row.testName);
783
+ if (typeof row.mode === 'string' && row.mode !== '' && row.mode !== 'full')
784
+ extras.push('mode=' + row.mode);
785
+ if (flaky > 0)
786
+ extras.push('flaky ' + String(flaky));
787
+ lines.push('- ' + row.timestamp + ' ' + row.target + '(' + extras.join(',') + ')');
335
788
  }
336
789
  if (history.length > 10)
337
790
  lines.push('…仅展示最近 10 条,其余用 flaky_history 查看');
338
791
  return [{ type: 'text', text: lines.join('\n') }];
339
792
  },
340
793
  },
341
- async execute(rawArgs) {
794
+ async execute(rawArgs, exec) {
795
+ const { store: scopedStore } = resolveInvocation(exec, cfg, runner, store);
342
796
  const args = asRecord(rawArgs);
343
797
  const target = optionalString(args, 'target');
344
798
  const historyLimit = optionalInteger(args, 'historyLimit', '历史条数', 1, 100, 20);
345
- const doc = await store.loadQuarantine();
346
- const historyEntries = await store.listHistory(target, historyLimit);
799
+ const scope = readScope(args.scope);
800
+ const doc = await scopedStore.loadQuarantine();
801
+ const historyEntries = await scopedStore.listHistory(target, historyLimit, scope);
802
+ const stability = summarizeStability(historyEntries, doc, { staleDays: cfg.staleQuarantineDays, topN: 5 });
347
803
  return {
348
- quarantineFile: store.quarantinePath,
804
+ scope,
805
+ quarantineFile: scopedStore.quarantinePath,
349
806
  quarantinedCount: doc.quarantined.length,
350
807
  quarantined: doc.quarantined,
351
808
  historyCount: historyEntries.length,
352
809
  history: historyEntries,
810
+ staleQuarantineDays: cfg.staleQuarantineDays,
811
+ topFlakyTests: stability.topFlakyTests,
812
+ staleQuarantined: stability.staleQuarantined,
353
813
  };
354
814
  },
355
815
  timeoutMs: 10000,
@@ -357,7 +817,7 @@ function buildWorkspaceTools(cfg, runner, store, cwd = process.cwd(), signal) {
357
817
  const flakyHealth = {
358
818
  name: 'flaky_health',
359
819
  isConcurrencySafe: () => true,
360
- description: 'dsh-flakefinder 自检:验证 Python 解释器与 pytest 是否可用(pytest 框架必需),并汇总默认配置。遇到问题时先运行本工具定位。',
820
+ description: 'dsh-flakefinder 自检:检查 Node 版本、工作区自动探测的测试框架(Vitest/Jest/pytest/node:test)、Python/pytest 可用性、隔离清单与历史文件可读性,并汇总默认配置。遇到问题时先运行本工具定位。',
361
821
  parameters: compileParameters({}),
362
822
  output: {
363
823
  schema: { type: 'object', additionalProperties: true },
@@ -365,53 +825,183 @@ function buildWorkspaceTools(cfg, runner, store, cwd = process.cwd(), signal) {
365
825
  const rec = asRecord(value);
366
826
  const checks = Array.isArray(rec.checks) ? rec.checks : [];
367
827
  const lines = ['dsh-flakefinder 自检' + (rec.ok === true ? ':正常。' : ':发现问题。')];
368
- const failed = [];
828
+ const requiredFailed = [];
829
+ const optionalFailed = [];
369
830
  for (const item of checks) {
370
831
  const c = asRecord(item);
371
- lines.push('- ' + c.name + ':' + (c.ok === true ? '✅' : '❌ ' + String(c.detail ?? '')));
372
- if (c.ok !== true)
373
- failed.push(String(c.name));
832
+ const detail = String(c.detail ?? '');
833
+ if (c.ok === true) {
834
+ lines.push('- ' + c.name + ':✅' + (detail !== '' ? ' ' + detail : ''));
835
+ }
836
+ else if (c.required === false) {
837
+ lines.push('- ' + c.name + ':ℹ️(可选)' + detail);
838
+ optionalFailed.push(String(c.name));
839
+ }
840
+ else {
841
+ lines.push('- ' + c.name + ':❌ ' + detail);
842
+ requiredFailed.push(String(c.name));
843
+ }
844
+ }
845
+ if (requiredFailed.includes('pytest') || requiredFailed.includes('python')) {
846
+ lines.push('下一步:当前工作区需要 Python/pytest,请先 pip install pytest,或把插件配置里的 pythonPath 指到正确的解释器,再运行 flaky_health 复查。');
847
+ }
848
+ else if (requiredFailed.length > 0) {
849
+ lines.push('下一步:按上面 ❌ 项的说明修好环境或备份修复损坏的文件,再运行 flaky_health 复查。');
850
+ }
851
+ else if (optionalFailed.includes('pytest') || optionalFailed.includes('python')) {
852
+ lines.push('说明:仅用 vitest / jest / node:test 时 Python/pytest 缺失不影响使用;若后续需要跑 Python 测试,再 pip install pytest 或配置 pythonPath。');
374
853
  }
375
- if (failed.includes('pytest'))
376
- lines.push('下一步:仅用 vitest / jest / node:test 时 pytest 缺失不影响;需要跑 Python 测试时先 pip install pytest,或把插件配置里的 pythonPath 指到正确的解释器。');
377
- else if (failed.length > 0)
378
- lines.push('下一步:按上面 ❌ 项的说明修好解释器/依赖,再运行 flaky_health 复查。');
379
854
  return [{ type: 'text', text: lines.join('\n') }];
380
855
  },
381
856
  },
382
- async execute() {
857
+ async execute(_rawArgs, exec) {
858
+ const { cwd, signal, runner: scopedRunner, store: scopedStore } = resolveInvocation(exec, cfg, runner, store);
859
+ const env = detectEnvironment(cwd, cfg);
860
+ const pythonRequired = env.pytest.configFound || cfg.pythonPathExplicit === true;
383
861
  const checks = [];
384
862
  let ok = true;
863
+ checks.push({
864
+ name: 'node',
865
+ ok: true,
866
+ required: true,
867
+ detail: env.nodeVersion + '(' + env.nodePath + ')',
868
+ });
869
+ const detectedParts = ['默认=' + env.defaultFramework];
870
+ if (env.vitest.available)
871
+ detectedParts.push('vitest=' + env.vitest.entryPath);
872
+ if (env.jest.available)
873
+ detectedParts.push('jest=' + env.jest.entryPath);
874
+ if (env.pytest.configFound)
875
+ detectedParts.push('pytest配置=' + env.pytest.configPath);
876
+ detectedParts.push('node:test=内置');
877
+ checks.push({
878
+ name: '工作区框架',
879
+ ok: true,
880
+ required: true,
881
+ detail: detectedParts.join(';'),
882
+ });
883
+ const pythonBin = env.pytest.pythonPath;
385
884
  try {
386
- const result = await runner.run([cfg.pythonPath, '--version'], { timeoutMs: 15000 });
885
+ const result = await scopedRunner.run([pythonBin, '--version'], { timeoutMs: 15000 });
886
+ signal?.throwIfAborted();
387
887
  const version = (result.stdout + result.stderr).split(/\r?\n/)[0]?.trim() ?? '';
388
- if (result.exitCode === 0)
389
- checks.push({ name: 'python', ok: true, detail: version + '(' + cfg.pythonPath + ')' });
888
+ if (result.exitCode === 0) {
889
+ checks.push({
890
+ name: 'python',
891
+ ok: true,
892
+ required: pythonRequired,
893
+ detail: version + '(' + pythonBin + ',' + pythonSourceLabel(env.pytest.pythonSource) + ')',
894
+ });
895
+ }
390
896
  else {
391
- ok = false;
392
- checks.push({ name: 'python', ok: false, detail: '退出码 ' + String(result.exitCode) });
897
+ if (pythonRequired)
898
+ ok = false;
899
+ checks.push({
900
+ name: 'python',
901
+ ok: false,
902
+ required: pythonRequired,
903
+ detail: '退出码 ' + String(result.exitCode) + '(' + pythonBin + ')',
904
+ });
393
905
  }
394
906
  }
395
907
  catch (error) {
396
- ok = false;
397
- checks.push({ name: 'python', ok: false, detail: error instanceof Error ? error.message : String(error) });
908
+ if (signal?.aborted)
909
+ throw signal.reason ?? error;
910
+ if (pythonRequired)
911
+ ok = false;
912
+ checks.push({
913
+ name: 'python',
914
+ ok: false,
915
+ required: pythonRequired,
916
+ detail: error instanceof Error ? error.message : String(error),
917
+ });
398
918
  }
919
+ signal?.throwIfAborted();
399
920
  try {
400
- const result = await runner.run([cfg.pythonPath, '-m', 'pytest', '--version'], { timeoutMs: 20000 });
921
+ const result = await scopedRunner.run([pythonBin, '-m', 'pytest', '--version'], { timeoutMs: 20000 });
922
+ signal?.throwIfAborted();
401
923
  const version = (result.stdout + result.stderr).split(/\r?\n/)[0]?.trim() ?? '';
402
- if (result.exitCode === 0)
403
- checks.push({ name: 'pytest', ok: true, detail: version });
924
+ if (result.exitCode === 0) {
925
+ checks.push({ name: 'pytest', ok: true, required: pythonRequired, detail: version });
926
+ }
404
927
  else {
405
- ok = false;
406
- checks.push({ name: 'pytest', ok: false, detail: '未安装或不可用(pip install pytest)' });
928
+ if (pythonRequired)
929
+ ok = false;
930
+ checks.push({ name: 'pytest', ok: false, required: pythonRequired, detail: '未安装或不可用(pip install pytest)' });
407
931
  }
408
932
  }
409
933
  catch (error) {
410
- ok = false;
411
- checks.push({ name: 'pytest', ok: false, detail: error instanceof Error ? error.message : String(error) });
934
+ if (signal?.aborted)
935
+ throw signal.reason ?? error;
936
+ if (pythonRequired)
937
+ ok = false;
938
+ checks.push({
939
+ name: 'pytest',
940
+ ok: false,
941
+ required: pythonRequired,
942
+ detail: error instanceof Error ? error.message : String(error),
943
+ });
412
944
  }
413
- checks.push({ name: '默认配置', ok: true, detail: 'defaultRuns=' + cfg.defaultRuns + ', timeoutMs=' + cfg.timeoutMs });
414
- return { ok, plugin: 'dsh-flakefinder', checks };
945
+ signal?.throwIfAborted();
946
+ if (typeof scopedStore.loadQuarantine === 'function') {
947
+ try {
948
+ const doc = await scopedStore.loadQuarantine();
949
+ checks.push({
950
+ name: '隔离清单',
951
+ ok: true,
952
+ required: true,
953
+ detail: scopedStore.quarantinePath + '(' + String(doc.quarantined.length) + ' 条)',
954
+ });
955
+ }
956
+ catch (error) {
957
+ ok = false;
958
+ checks.push({
959
+ name: '隔离清单',
960
+ ok: false,
961
+ required: true,
962
+ detail: error instanceof Error ? error.message : String(error),
963
+ });
964
+ }
965
+ }
966
+ if (typeof scopedStore.listHistory === 'function') {
967
+ try {
968
+ await scopedStore.listHistory(undefined, 1, 'workspace');
969
+ checks.push({
970
+ name: '历史记录',
971
+ ok: true,
972
+ required: true,
973
+ detail: (scopedStore.historyPath ?? cfg.dataDir) + '(可读)',
974
+ });
975
+ }
976
+ catch (error) {
977
+ ok = false;
978
+ checks.push({
979
+ name: '历史记录',
980
+ ok: false,
981
+ required: true,
982
+ detail: error instanceof Error ? error.message : String(error),
983
+ });
984
+ }
985
+ }
986
+ checks.push({
987
+ name: '默认配置',
988
+ ok: true,
989
+ required: false,
990
+ detail: 'defaultRuns=' + String(cfg.defaultRuns)
991
+ + ', maxRuns=' + String(cfg.maxRuns)
992
+ + ', defaultConcurrency=' + String(cfg.defaultConcurrency)
993
+ + ', noCoverage=' + String(cfg.noCoverage)
994
+ + ', timeoutMs=' + String(cfg.timeoutMs)
995
+ + ', staleQuarantineDays=' + String(cfg.staleQuarantineDays),
996
+ });
997
+ return {
998
+ ok,
999
+ plugin: 'dsh-flakefinder',
1000
+ workspace: cwd,
1001
+ pythonRequired,
1002
+ environment: env,
1003
+ checks,
1004
+ };
415
1005
  },
416
1006
  timeoutMs: 40000,
417
1007
  };