dsh-project-flow 0.0.0-stage → 0.8.1

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/evidence.mjs ADDED
@@ -0,0 +1,504 @@
1
+ /**
2
+ * Completion_Evidence.json 生成器。
3
+ *
4
+ * 目标是让验收结果机器可读,而不是一段模型写的自然语言总结。
5
+ * 五个字段各自有明确的数据来源,拿不到就如实写 null,不编。
6
+ *
7
+ * 1 requirement_met 外部测试脚本的 exit code
8
+ * 2 cost_incurred watchdog 累计的 token 估算 + 人民币换算
9
+ * 3 retry_count state.json 的口径:每阶 attempt、返工、回滚
10
+ * 4 files_modified 快照仓库的 git diff --numstat
11
+ * 5 remaining_risks QA_Report.md 的「可接受的风险」节 + 门控里的假设妥协
12
+ *
13
+ * 纯 Node,不依赖 ctx。
14
+ */
15
+
16
+ import { execFile } from 'node:child_process'
17
+ import { writeFile, readFile, readdir, stat } from 'node:fs/promises'
18
+ import { homedir } from 'node:os'
19
+ import { join } from 'node:path'
20
+
21
+ export const EVIDENCE_FILE = 'Completion_Evidence.json'
22
+ export const EVIDENCE_SCHEMA_VERSION = 1
23
+
24
+ /** 默认汇率。真要参赛就按当天牌价配,别用默认值。 */
25
+ const DEFAULT_CNY_RATE = 7.2
26
+
27
+ /** 测试脚本默认超时。跑集成测试可能慢,给足 10 分钟。 */
28
+ const DEFAULT_TEST_TIMEOUT_MS = 600000
29
+
30
+ /**
31
+ * 试一下某条命令在不在。Windows 上 `python` 经常指向应用商店的占位程序,
32
+ * 它退出码是 9009,直接拿来跑测试只会得到一条看不懂的失败。
33
+ */
34
+ function commandWorks(command, cwd) {
35
+ return new Promise(resolve => {
36
+ const isWindows = process.platform === 'win32'
37
+ execFile(
38
+ isWindows ? 'cmd.exe' : '/bin/sh',
39
+ isWindows ? ['/c', `${command} -V`] : ['-c', `${command} -V`],
40
+ { cwd, timeout: 8000, windowsHide: true },
41
+ error => resolve(error === null),
42
+ )
43
+ })
44
+ }
45
+
46
+ /** 直接跑一个可执行文件,不经过 shell。绝对路径用它,免得 cmd 把引号吃掉。 */
47
+ function fileWorks(file, args, cwd) {
48
+ return new Promise(resolve => {
49
+ execFile(file, args, { cwd, timeout: 8000, windowsHide: true }, error => resolve(error === null))
50
+ })
51
+ }
52
+
53
+ /** 挑一个真能用的 Python 解释器;一个都没有就返回空字符串。 */
54
+ async function pickPython(cwd) {
55
+ for (const candidate of ['python', 'py -3', 'python3']) {
56
+ if (await commandWorks(candidate, cwd)) return candidate
57
+ }
58
+ // 系统 PATH 上一个都没有时,退到 DSH 自己带的那份解释器。
59
+ // 装过 DSH 就有,比让证据包永远显示「测试没跑」有用。
60
+ const home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
61
+ let runtimes = []
62
+ try {
63
+ runtimes = await readdir(join(home, 'dsh-runtimes'))
64
+ } catch {
65
+ return ''
66
+ }
67
+ for (const name of runtimes) {
68
+ const exe = join(home, 'dsh-runtimes', name, 'dependencies', 'python', 'python.exe')
69
+ try {
70
+ await stat(exe)
71
+ } catch {
72
+ continue
73
+ }
74
+ if (!await fileWorks(exe, ['-V'], cwd)) continue
75
+ // 路径带空格才加引号:cmd /c 会把裸引号吃掉,无空格时加了反而坏事。
76
+ return exe.includes(' ') ? `"${exe}"` : exe
77
+ }
78
+ return ''
79
+ }
80
+
81
+ /**
82
+ * 猜**单个**目录该用哪条命令跑测试。只探这一层,不往下钻。
83
+ *
84
+ * 返回 { command, why },猜不出来时 command 为空字符串。
85
+ */
86
+ async function detectIn(cwd) {
87
+ const has = async name => {
88
+ try {
89
+ await stat(join(cwd, name))
90
+ return true
91
+ } catch {
92
+ return false
93
+ }
94
+ }
95
+
96
+ // Node:只有真的写了 scripts.test 才跑,脚手架默认那句
97
+ // "echo \"Error: no test specified\"" 不算测试。
98
+ if (await has('package.json')) {
99
+ try {
100
+ const pkg = JSON.parse(await readFile(join(cwd, 'package.json'), 'utf8'))
101
+ const script = pkg?.scripts?.test
102
+ if (typeof script === 'string' && script.trim() !== '' && !/no test specified/i.test(script)) {
103
+ return { command: 'npm test', why: 'package.json 里有 scripts.test' }
104
+ }
105
+ } catch {
106
+ // package.json 读不动就当作没有,接着往下猜
107
+ }
108
+ }
109
+
110
+ for (const [file, command] of [
111
+ ['go.mod', 'go test ./...'],
112
+ ['Cargo.toml', 'cargo test'],
113
+ ['pom.xml', 'mvn -q test'],
114
+ ]) {
115
+ if (await has(file)) return { command, why: `目录里有 ${file}` }
116
+ }
117
+
118
+ const hasPytestConfig = await has('pytest.ini') || await has('conftest.py')
119
+ || await has('tox.ini') || await has('setup.cfg')
120
+
121
+ let entries = []
122
+ try {
123
+ entries = await readdir(cwd)
124
+ } catch {
125
+ entries = []
126
+ }
127
+ const pyTest = entries.find(name => /^test_.+\.py$/.test(name)) ?? entries.find(name => /_test\.py$/.test(name))
128
+
129
+ if (hasPytestConfig || pyTest !== undefined) {
130
+ const pattern = pyTest === undefined
131
+ ? 'test_*.py'
132
+ : /^test_.+\.py$/.test(pyTest) ? 'test_*.py' : '*_test.py'
133
+ const runner = hasPytestConfig ? '-m pytest -q' : `-m unittest discover -v -p ${pattern}`
134
+ const why = hasPytestConfig ? '有 pytest 配置' : `目录里有 ${pyTest}`
135
+ const py = await pickPython(cwd)
136
+ // 一个能用的解释器都挑不出来时也给一条命令:让它照常去跑、照常留下
137
+ // exit code,证据包里就能看出是环境缺 python,而不是活没干完。
138
+ return {
139
+ command: `${py === '' ? 'python' : py} ${runner}`,
140
+ why: py === '' ? `${why},但 PATH 上找不到可用的 python` : why,
141
+ }
142
+ }
143
+
144
+ if (await has('Makefile')) {
145
+ try {
146
+ const body = await readFile(join(cwd, 'Makefile'), 'utf8')
147
+ if (/^test\s*:/m.test(body)) return { command: 'make test', why: 'Makefile 里有 test 目标' }
148
+ } catch {
149
+ // 读不动就算了
150
+ }
151
+ }
152
+
153
+ return { command: '', why: '没找到能自动跑的测试,也没配 testCommand' }
154
+ }
155
+
156
+ /** 扫一层子目录时跳过的目录,进去纯属浪费时间。 */
157
+ const SKIP_DIRS = new Set([
158
+ 'node_modules', '.git', '.project-flow', '.venv', 'venv',
159
+ '__pycache__', 'dist', 'build', 'out', 'target', '.next',
160
+ ])
161
+
162
+ /**
163
+ * 猜这个工作区该用哪条命令跑测试,以及该在哪个目录里跑。
164
+ *
165
+ * 只在 testCommand 留空或写 `auto` 时用。宁可猜错也不装作「没测试」:
166
+ * 猜错至少留下 exit code 可查,不配 testCommand 只会让证据包永远显示
167
+ * 「要求未满足」,而人一看那行就以为活没干完,其实只是没人告诉它跑什么。
168
+ *
169
+ * 先看工作区根目录,找不到就往下扫一层子目录——产物经常落在子目录里
170
+ * (本机实测踩过:脚本和测试都在 csv2md/ 下,根目录干干净净,探测直接说没找到)。
171
+ * 所以返回值多带一个 cwd,告诉调用方该在哪儿跑。
172
+ */
173
+ export async function detectTestCommand(cwd) {
174
+ if (typeof cwd !== 'string' || cwd.trim() === '') {
175
+ return { command: '', why: '没有工作目录,猜不了', cwd: '' }
176
+ }
177
+
178
+ const direct = await detectIn(cwd)
179
+ if (direct.command !== '') return { ...direct, cwd }
180
+
181
+ let entries = []
182
+ try {
183
+ entries = await readdir(cwd, { withFileTypes: true })
184
+ } catch {
185
+ return { ...direct, cwd }
186
+ }
187
+ for (const entry of entries) {
188
+ if (!entry.isDirectory() || SKIP_DIRS.has(entry.name) || entry.name.startsWith('.')) continue
189
+ const sub = join(cwd, entry.name)
190
+ const hit = await detectIn(sub)
191
+ if (hit.command !== '') {
192
+ return { ...hit, why: `${hit.why}(在 ${entry.name}/ 下)`, cwd: sub }
193
+ }
194
+ }
195
+
196
+ return { ...direct, cwd }
197
+ }
198
+
199
+ /**
200
+ * 跑外部测试脚本,只认 exit code。
201
+ *
202
+ * 用 shell 执行,因为用户写的是 `pnpm test` 这种带参数的命令行,
203
+ * 不是单个可执行文件。
204
+ */
205
+ export function runTestCommand(command, cwd, timeoutMs = DEFAULT_TEST_TIMEOUT_MS) {
206
+ return new Promise(resolve => {
207
+ const startedAt = Date.now()
208
+ if (typeof command !== 'string' || command.trim() === '') {
209
+ resolve({
210
+ command: '',
211
+ ran: false,
212
+ ok: false,
213
+ exitCode: null,
214
+ durationMs: 0,
215
+ stdoutTail: '',
216
+ stderrTail: '',
217
+ reason: '没有配置 testCommand',
218
+ })
219
+ return
220
+ }
221
+
222
+ const isWindows = process.platform === 'win32'
223
+ const shell = isWindows ? 'cmd.exe' : '/bin/sh'
224
+ const flag = isWindows ? '/c' : '-c'
225
+
226
+ execFile(shell, [flag, command], {
227
+ cwd,
228
+ timeout: timeoutMs,
229
+ maxBuffer: 4 * 1024 * 1024,
230
+ windowsHide: true,
231
+ }, (error, stdout, stderr) => {
232
+ const durationMs = Date.now() - startedAt
233
+ // 非零退出、超时、命令不存在都会走到 error 分支。
234
+ // exit code 0 是唯一算通过的情况,其余一律 false,不做推测。
235
+ const exitCode = error === null
236
+ ? 0
237
+ : typeof error.code === 'number'
238
+ ? error.code
239
+ : null
240
+ resolve({
241
+ command,
242
+ ran: true,
243
+ ok: exitCode === 0,
244
+ exitCode,
245
+ durationMs,
246
+ stdoutTail: String(stdout ?? '').slice(-4000),
247
+ stderrTail: String(stderr ?? '').slice(-4000),
248
+ reason: error === null
249
+ ? 'exit code 0'
250
+ : error.killed === true
251
+ ? `超过 ${Math.round(timeoutMs / 1000)} 秒被终止`
252
+ : exitCode === 9009 || exitCode === 127
253
+ // 命令本身就没找到。Windows 上这条最常见的原因是 python
254
+ // 指向了应用商店的占位程序,它退出码就是 9009。
255
+ ? `exit code ${exitCode}:命令没找到,把解释器全路径写进 testCommand 再跑`
256
+ : `exit code ${exitCode ?? '未知'}`,
257
+ })
258
+ })
259
+ })
260
+ }
261
+
262
+ /**
263
+ * 从快照仓库算每个文件的行数变化。
264
+ *
265
+ * 用 `diff --numstat` 而不是 `--name-status`:前者给「加了几行、删了几行」,
266
+ * 后者只给文件列表。从第一轮实施前的快照到最后一次实施后的快照,
267
+ * 这样多轮返工的结果会累加在一起,而不是只看最后一轮。
268
+ *
269
+ * 快照不可用(没有 git、或从没打过快照)时返回 undefined,调用方写 null。
270
+ */
271
+ export async function collectFileChanges(gitRun, attempts, fallbackFiles) {
272
+ const list = Array.isArray(attempts) ? attempts : []
273
+ const first = list.find(item => typeof item?.before === 'string' && item.before !== '')
274
+ const last = [...list].reverse().find(item => typeof item?.after === 'string' && item.after !== '')
275
+
276
+ if (first === undefined || last === undefined) {
277
+ // 没有快照:只能给文件清单,行数如实写 null
278
+ const paths = Array.isArray(fallbackFiles) ? fallbackFiles : []
279
+ if (paths.length === 0) return []
280
+ return paths.map(path => ({
281
+ path,
282
+ change: 'modified',
283
+ added_lines: null,
284
+ deleted_lines: null,
285
+ measured: false,
286
+ }))
287
+ }
288
+
289
+ // numstat 给行数但不说文件是新增还是修改(纯追加也会是 +N/-0),
290
+ // name-status 说类型但不给行数。两个都跑,按路径合起来。
291
+ const [numstat, nameStatus] = await Promise.all([
292
+ gitRun(['diff', '--numstat', '--no-renames', first.before, last.after, '--']),
293
+ gitRun(['diff', '--name-status', '--no-renames', first.before, last.after, '--']),
294
+ ])
295
+ if (numstat.ok !== true) return undefined
296
+
297
+ const kindOf = new Map()
298
+ if (nameStatus.ok === true) {
299
+ for (const line of nameStatus.stdout.split(/\r?\n/u)) {
300
+ if (line.trim() === '') continue
301
+ const [code, ...rest] = line.split('\t')
302
+ const path = rest.join('\t').trim()
303
+ if (path !== '') kindOf.set(path, code?.[0])
304
+ }
305
+ }
306
+
307
+ const rows = numstat.stdout
308
+ .split(/\r?\n/u)
309
+ .filter(line => line.trim() !== '')
310
+ .map(line => {
311
+ const [added, deleted, ...rest] = line.split('\t')
312
+ const path = rest.join('\t').trim()
313
+ if (path === '') return undefined
314
+ // 二进制文件 numstat 给的是 `-`,不是数字
315
+ const isBinary = added === '-' || deleted === '-'
316
+ const code = kindOf.get(path)
317
+ return {
318
+ path,
319
+ change: code === 'A'
320
+ ? 'added'
321
+ : code === 'D'
322
+ ? 'deleted'
323
+ : code === 'M' || code === 'T'
324
+ ? 'modified'
325
+ // 没拿到 name-status 时才退回去看行数
326
+ : Number(added) > 0 && Number(deleted) === 0
327
+ ? 'added'
328
+ : Number(added) === 0 && Number(deleted) > 0
329
+ ? 'deleted'
330
+ : 'modified',
331
+ added_lines: isBinary ? null : Number(added),
332
+ deleted_lines: isBinary ? null : Number(deleted),
333
+ measured: !isBinary,
334
+ }
335
+ })
336
+ .filter(entry => entry !== undefined)
337
+
338
+ return rows
339
+ }
340
+
341
+ /** 从 QA_Report.md 里抠「可接受的风险」那一节。 */
342
+ export function extractRisks(qaText) {
343
+ if (typeof qaText !== 'string' || qaText.trim() === '') return []
344
+ const lines = qaText.split(/\r?\n/u)
345
+ const risks = []
346
+ let inSection = false
347
+ for (const line of lines) {
348
+ const heading = /^\s*#{1,6}\s*(.+)$/u.exec(line)
349
+ if (heading !== null) {
350
+ // 换到别的节就停止;标题里带「风险」才算命中
351
+ inSection = /风险|risk/iu.test(heading[1])
352
+ continue
353
+ }
354
+ if (!inSection) continue
355
+ const item = /^\s*[-*·]\s*(.+)$/u.exec(line)
356
+ if (item !== null && item[1].trim() !== '') risks.push(item[1].trim())
357
+ }
358
+ return risks
359
+ }
360
+
361
+ /** 把 token 数和单价换成钱。token 数一并带出去,证据包要用。 */
362
+ export function costOf({ inputTokens, outputTokens, pricing, cnyRate }) {
363
+ const price = pricing ?? { input: 0, output: 0 }
364
+ const rate = Number.isFinite(cnyRate) && cnyRate > 0 ? cnyRate : DEFAULT_CNY_RATE
365
+ const input = Number.isFinite(inputTokens) ? inputTokens : 0
366
+ const output = Number.isFinite(outputTokens) ? outputTokens : 0
367
+ const usd = (input / 1e6) * price.input + (output / 1e6) * price.output
368
+ return {
369
+ inputTokens: input,
370
+ outputTokens: output,
371
+ estimated_usd: Number(usd.toFixed(6)),
372
+ estimated_cny: Number((usd * rate).toFixed(4)),
373
+ cny_rate: rate,
374
+ }
375
+ }
376
+
377
+ /**
378
+ * 组装整份证据包。
379
+ *
380
+ * 每个字段都标了 source,让评审一眼能看出这个数是测出来的还是估出来的。
381
+ * 这一栏是给比赛看的,不是给日志看的——估的就是估的,不装精确。
382
+ */
383
+ export async function buildEvidence(input) {
384
+ const {
385
+ project, artifacts, startedAt,
386
+ intent, requirements,
387
+ test, cost, counters, files, qa, assumptions,
388
+ } = input
389
+
390
+ const risks = [...new Set([
391
+ ...(Array.isArray(qa?.acceptableRisks) ? qa.acceptableRisks : []),
392
+ ...(Array.isArray(assumptions) ? assumptions : []),
393
+ ])].filter(item => typeof item === 'string' && item.trim() !== '')
394
+
395
+ return {
396
+ schema_version: EVIDENCE_SCHEMA_VERSION,
397
+ generated_at: new Date().toISOString(),
398
+ project,
399
+ artifacts,
400
+
401
+ // 1
402
+ requirement_met: test?.ok === true,
403
+ requirement_source: {
404
+ kind: 'external_test',
405
+ command: test?.command ?? '',
406
+ ran: test?.ran === true,
407
+ exit_code: test?.exitCode ?? null,
408
+ duration_ms: test?.durationMs ?? null,
409
+ note: test?.reason ?? '',
410
+ },
411
+
412
+ // 2
413
+ cost_incurred: {
414
+ input_tokens: cost?.inputTokens ?? 0,
415
+ output_tokens: cost?.outputTokens ?? 0,
416
+ total_tokens: (cost?.inputTokens ?? 0) + (cost?.outputTokens ?? 0),
417
+ estimated_usd: cost?.estimated_usd ?? 0,
418
+ estimated_cny: cost?.estimated_cny ?? 0,
419
+ cny_rate: cost?.cny_rate ?? DEFAULT_CNY_RATE,
420
+ // 子会话不返回 token 用量,所以这是按字符估的。写清楚,别让人当成账单。
421
+ method: 'estimated_from_characters',
422
+ precision_note: '子会话只返回文本、不返回 token 用量,这里按约 2.5 字符一 token 估算,与真实账单有偏差',
423
+ },
424
+
425
+ // 3
426
+ retry_count: {
427
+ // total 只数「多花的次数」:阶内重试 + 返工 + 回滚。
428
+ // 一次跑通的干净流程这里必须是 0,不能把每阶的第一次调用也算成重试。
429
+ total: (counters?.stageRetries ?? 0) + (counters?.reworks ?? 0) + (counters?.rollbacks ?? 0),
430
+ stage_retries: counters?.stageRetries ?? 0,
431
+ by_stage: counters?.byStage ?? { plan: 0, build: 0, check: 0 },
432
+ reworks: counters?.reworks ?? 0,
433
+ rollbacks: counters?.rollbacks ?? 0,
434
+ max_rework_reached: counters?.maxReworkReached === true,
435
+ // 每阶调了几次子会话(含第一次)。和重试次数不是一个数,别混。
436
+ stage_calls: counters?.stageCalls ?? 0,
437
+ },
438
+
439
+ // 4
440
+ files_modified: Array.isArray(files) ? files : [],
441
+ files_summary: {
442
+ count: Array.isArray(files) ? files.length : 0,
443
+ added_lines: sumOf(files, 'added_lines'),
444
+ deleted_lines: sumOf(files, 'deleted_lines'),
445
+ measured: Array.isArray(files) && files.length > 0 && files.every(entry => entry.measured === true),
446
+ },
447
+
448
+ // 5
449
+ remaining_risks: risks,
450
+ risk_sources: {
451
+ from_qa_report: Array.isArray(qa?.acceptableRisks) ? qa.acceptableRisks.length : 0,
452
+ from_assumptions: Array.isArray(assumptions) ? assumptions.length : 0,
453
+ },
454
+
455
+ // 给评审看的上下文,不算五个必填字段
456
+ context: {
457
+ intent: typeof intent === 'string' ? intent.slice(0, 2000) : '',
458
+ requirement_count: Array.isArray(requirements) ? requirements.length : 0,
459
+ quality_verdict: qa?.verdict ?? '',
460
+ quality_reasons: Array.isArray(qa?.reasons) ? qa.reasons : [],
461
+ started_at: startedAt ?? null,
462
+ },
463
+ }
464
+ }
465
+
466
+ function sumOf(list, key) {
467
+ if (!Array.isArray(list)) return 0
468
+ let total = 0
469
+ for (const entry of list) {
470
+ const value = entry?.[key]
471
+ if (typeof value === 'number' && Number.isFinite(value)) total += value
472
+ }
473
+ return total
474
+ }
475
+
476
+ /** 落盘。文件名固定,覆盖写——每次读取都是最新一次验收的结果。 */
477
+ export async function writeEvidence(artifacts, evidence) {
478
+ const path = join(artifacts, EVIDENCE_FILE)
479
+ await writeFile(path, `${JSON.stringify(evidence, null, 2)}\n`, 'utf8')
480
+ return path
481
+ }
482
+
483
+ /** 读回来。补丁里给 project_status 之类的只读工具用。 */
484
+ export async function readEvidence(artifacts) {
485
+ try {
486
+ return JSON.parse(await readFile(join(artifacts, EVIDENCE_FILE), 'utf8'))
487
+ } catch {
488
+ return undefined
489
+ }
490
+ }
491
+
492
+ /** 一行摘要,塞进 project_run 的返回里。 */
493
+ export function evidenceSummary(evidence, path) {
494
+ const cost = evidence.cost_incurred
495
+ const retry = evidence.retry_count
496
+ return [
497
+ `完成证据包:${path}`,
498
+ `· 测试 ${evidence.requirement_met ? '通过' : '未通过'}(exit ${evidence.requirement_source.exit_code ?? '未跑'})`,
499
+ `· 消耗约 ${cost.total_tokens} token ≈ ¥${cost.estimated_cny}(估算)`,
500
+ `· 重试 ${retry.total} 次(阶内 ${retry.stage_retries ?? 0},返工 ${retry.reworks},回滚 ${retry.rollbacks})`,
501
+ `· 改动 ${evidence.files_summary.count} 个文件 +${evidence.files_summary.added_lines}/-${evidence.files_summary.deleted_lines} 行`,
502
+ `· 残留风险 ${evidence.remaining_risks.length} 条`,
503
+ ].join('\n')
504
+ }