dsh-project-flow 0.8.3 → 0.9.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/CHANGELOG.md +104 -0
- package/README.md +125 -364
- package/bench/corpus/qa-fail-3-issues.md +33 -0
- package/bench/corpus/qa-fail-assertion.md +20 -0
- package/bench/corpus/qa-fail-missing-detect.md +21 -0
- package/bench/corpus/qa-pass.md +9 -0
- package/bench/corpus/qa-reverify-partial.md +30 -0
- package/bench/corpus/qa-unverified-only.md +15 -0
- package/bench/corpus/requirement-no-check.md +8 -0
- package/bench/corpus/requirement-with-check.md +16 -0
- package/bench/corpus/reverify-table-not-defects.md +18 -0
- package/bench/run.mjs +142 -0
- package/client.js +195 -9
- package/cordis.patch.yml +4 -3
- package/docs/CHECKS.md +100 -0
- package/docs/ISSUES.md +75 -0
- package/docs/LEDGER.md +46 -0
- package/docs/adr/0001-four-stage-isolation.md +25 -0
- package/docs/adr/0002-file-handoff-not-context.md +27 -0
- package/docs/adr/0003-diff-over-self-report.md +27 -0
- package/docs/adr/0004-issue-level-rework.md +30 -0
- package/docs/adr/0005-assertion-over-prose.md +30 -0
- package/docs/anchors/assertion-exec.md +39 -0
- package/docs/anchors/cost-accounting.md +44 -0
- package/docs/anchors/diff-reconciliation.md +35 -0
- package/docs/anchors/file-whitelist.md +29 -0
- package/docs/anchors/intent-gate.md +41 -0
- package/docs/anchors/issue-loop.md +40 -0
- package/docs/anchors/patch-ledger.md +38 -0
- package/docs/anchors/watchdog.md +30 -0
- package/flow.schema.mjs +443 -0
- package/index.js +2233 -86
- package/package.json +8 -1
package/index.js
CHANGED
|
@@ -20,12 +20,14 @@
|
|
|
20
20
|
* 授权流程见 docs/COMMERCIAL.md。
|
|
21
21
|
*/
|
|
22
22
|
import { mkdir, readFile, writeFile, readdir, appendFile, rename, rm, stat } from 'node:fs/promises'
|
|
23
|
-
import { readFileSync, existsSync } from 'node:fs'
|
|
23
|
+
import { readFileSync, existsSync, appendFileSync } from 'node:fs'
|
|
24
24
|
import { join, isAbsolute, dirname, resolve, relative, basename, sep } from 'node:path'
|
|
25
25
|
import { fileURLToPath } from 'node:url'
|
|
26
26
|
import { homedir, tmpdir } from 'node:os'
|
|
27
27
|
import { execFile } from 'node:child_process'
|
|
28
|
+
import { createHash } from 'node:crypto'
|
|
28
29
|
import z from '@deepseek-ai/schemastery'
|
|
30
|
+
import { loadFlow, describeFlowProblems, BUILTIN_FLOW } from './flow.schema.mjs'
|
|
29
31
|
import {
|
|
30
32
|
Watchdog,
|
|
31
33
|
WatchdogFault,
|
|
@@ -239,6 +241,16 @@ export const Config = z.object({
|
|
|
239
241
|
testCommand: z.string().default('auto'),
|
|
240
242
|
testTimeoutMs: z.natural().default(600000),
|
|
241
243
|
cnyRate: z.number().min(0.0001).default(7),
|
|
244
|
+
// ── 断言执行器 ──────────────────────────────────────────────
|
|
245
|
+
/**
|
|
246
|
+
* 额外放行的命令,逗号或空格分隔。默认那 9 类写死在代码里,这一项只能往上加:
|
|
247
|
+
* 白名单一旦可以被配置删空,「判据」就又回到模型嘴里了。
|
|
248
|
+
*/
|
|
249
|
+
checkAllowedCommands: z.string().default(''),
|
|
250
|
+
/** 单条 check 的超时。不是一轮总和:一轮里每条各自计时。 */
|
|
251
|
+
checkTimeoutMs: z.natural().default(120000),
|
|
252
|
+
/** stdout / stderr 留多少字符的尾巴。超长只留尾部——报错基本写在最后几行。 */
|
|
253
|
+
checkStdoutTailChars: z.natural().default(8000),
|
|
242
254
|
})
|
|
243
255
|
|
|
244
256
|
const STAGE_LABEL = {
|
|
@@ -274,6 +286,233 @@ const ARTIFACT = {
|
|
|
274
286
|
log: 'Execution_Log.md',
|
|
275
287
|
qa: 'QA_Report.md',
|
|
276
288
|
nextStep: 'Next_Step.md',
|
|
289
|
+
// 判据指纹:Requirement.md 里 check 字段的 sha256。第 2 阶入口算一次,
|
|
290
|
+
// 第 4 阶复算一次,对不上就停机——中途改判据等于自己给自己放水。
|
|
291
|
+
requirementHash: 'requirement.sha',
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ── 补丁台账 ──────────────────────────────────────────────────
|
|
295
|
+
//
|
|
296
|
+
// 回滚以前靠 git 快照整棵还原。问题是 precise 模式只还原 attempts 里记的文件,
|
|
297
|
+
// 而 attempts 的文件清单来自实施段的自述——自述可以说假话。
|
|
298
|
+
//
|
|
299
|
+
// 台账记的是「插件自己看到的每次写入」:beforeSha / afterSha 都是插件算的,
|
|
300
|
+
// 不靠自述。回滚按台账走,只动 agent 真的写过的路径,不卷走用户手改的东西。
|
|
301
|
+
|
|
302
|
+
/** 台账目录:.project-flow/<project>/ledger/ */
|
|
303
|
+
function ledgerDir(cwd, project) {
|
|
304
|
+
return join(stateDir(cwd, project), 'ledger')
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** 台账文件:patch-ledger.jsonl,逐行 JSON 追加写,不覆盖。 */
|
|
308
|
+
function ledgerPath(cwd, project) {
|
|
309
|
+
return join(ledgerDir(cwd, project), 'patch-ledger.jsonl')
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* 把路径里的反斜杠统一成正斜杠。
|
|
314
|
+
*
|
|
315
|
+
* Windows 上同一个文件可能以 `src\a.ts` 和 `src/a.ts` 两种面貌出现,
|
|
316
|
+
* 不归一的话台账里会有两个 key,回滚只还原其中一个。
|
|
317
|
+
*/
|
|
318
|
+
export function normalizedPatchPath(path) {
|
|
319
|
+
const text = typeof path === 'string' ? path : String(path ?? '')
|
|
320
|
+
return text.replace(/\\/gu, '/').replace(/^\.\//u, '').trim()
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** 文件的 sha256,不存在返回 null。 */
|
|
324
|
+
async function fileSha256(path) {
|
|
325
|
+
try {
|
|
326
|
+
const data = await readFile(path)
|
|
327
|
+
return createHash('sha256').update(data).digest('hex')
|
|
328
|
+
} catch {
|
|
329
|
+
return null
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** 同步版:用于追加写时的 beforeSha(此时文件还没被改)。 */
|
|
334
|
+
function fileSha256Sync(path) {
|
|
335
|
+
try {
|
|
336
|
+
const data = readFileSync(path)
|
|
337
|
+
return createHash('sha256').update(data).digest('hex')
|
|
338
|
+
} catch {
|
|
339
|
+
return null
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* 往台账追加一行。
|
|
345
|
+
*
|
|
346
|
+
* 用 appendFileSync 同步写:实施段写文件和台账追加必须原子,
|
|
347
|
+
* 中间不能被中断——否则文件改了但台账没记,那条改动就丢了。
|
|
348
|
+
*/
|
|
349
|
+
export function appendLedgerEntry(cwd, project, entry) {
|
|
350
|
+
const path = ledgerPath(cwd, project)
|
|
351
|
+
try {
|
|
352
|
+
mkdirSync(ledgerDir(cwd, project), { recursive: true })
|
|
353
|
+
const line = JSON.stringify(entry) + '\n'
|
|
354
|
+
appendFileSync(path, line, 'utf8')
|
|
355
|
+
} catch {
|
|
356
|
+
// 台账写失败不该中断实施段——但要在日志里留痕。
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** mkdirSync 的引入(appendLedgerEntry 用)。 */
|
|
361
|
+
import { mkdirSync } from 'node:fs'
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* 读台账,返回条目数组。坏 JSON 行不静默跳过:报错并列出行号。
|
|
365
|
+
*/
|
|
366
|
+
export function readLedger(cwd, project) {
|
|
367
|
+
const path = ledgerPath(cwd, project)
|
|
368
|
+
let text
|
|
369
|
+
try {
|
|
370
|
+
text = readFileSync(path, 'utf8')
|
|
371
|
+
} catch {
|
|
372
|
+
return []
|
|
373
|
+
}
|
|
374
|
+
const lines = text.split(/\r?\n/u).filter(line => line.trim() !== '')
|
|
375
|
+
const entries = []
|
|
376
|
+
const bad = []
|
|
377
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
378
|
+
try {
|
|
379
|
+
const obj = JSON.parse(lines[i])
|
|
380
|
+
if (obj !== null && typeof obj === 'object' && !Array.isArray(obj)) {
|
|
381
|
+
entries.push(obj)
|
|
382
|
+
} else {
|
|
383
|
+
bad.push({ line: i + 1, text: lines[i].slice(0, 100) })
|
|
384
|
+
}
|
|
385
|
+
} catch {
|
|
386
|
+
bad.push({ line: i + 1, text: lines[i].slice(0, 100) })
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
if (bad.length > 0) {
|
|
390
|
+
const msg = `台账有 ${bad.length} 行坏 JSON:` + bad.map(b => `第 ${b.line} 行(${b.text})`).join('、')
|
|
391
|
+
throw new Error(msg)
|
|
392
|
+
}
|
|
393
|
+
return entries
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* 记录实施段的一次文件写入。
|
|
398
|
+
*
|
|
399
|
+
* 在实施段真正写文件之前调 recordBefore,拿到 beforeSha;
|
|
400
|
+
* 写完之后调 recordAfter,拿到 afterSha 并追加台账。
|
|
401
|
+
* 两步分开是因为「写之前」和「写之后」的文件状态都要记。
|
|
402
|
+
*/
|
|
403
|
+
export async function recordFileWrite(cwd, project, filePath, batchId, stage, index) {
|
|
404
|
+
const abs = isAbsolute(filePath) ? filePath : join(cwd, filePath)
|
|
405
|
+
const rel = normalizedPatchPath(isAbsolute(filePath) ? relative(cwd, filePath) : filePath)
|
|
406
|
+
const beforeSha = await fileSha256(abs)
|
|
407
|
+
return {
|
|
408
|
+
index,
|
|
409
|
+
batchId,
|
|
410
|
+
stage,
|
|
411
|
+
path: rel,
|
|
412
|
+
beforeSha,
|
|
413
|
+
afterSha: null,
|
|
414
|
+
status: 'pending',
|
|
415
|
+
ts: nowIso(),
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** 写完文件后补上 afterSha 并追加到台账。 */
|
|
420
|
+
export function commitLedgerEntry(cwd, project, entry, afterSha) {
|
|
421
|
+
const committed = { ...entry, afterSha, status: 'applied', ts: nowIso() }
|
|
422
|
+
appendLedgerEntry(cwd, project, committed)
|
|
423
|
+
return committed
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* 按最后一批 applied 条目还原。
|
|
428
|
+
*
|
|
429
|
+
* 只动台账里的 path,不在台账里的文件原样保留。
|
|
430
|
+
* 还原后追加一条 reverted 记录,指回原条目 index。
|
|
431
|
+
*/
|
|
432
|
+
export async function rollbackByLedger(cwd, project) {
|
|
433
|
+
const entries = readLedger(cwd, project)
|
|
434
|
+
if (entries.length === 0) {
|
|
435
|
+
return { ok: false, reason: '台账为空,没有可回滚的条目' }
|
|
436
|
+
}
|
|
437
|
+
// 找最后一批 applied:从末尾往前,连续的 applied 条目是同一批。
|
|
438
|
+
const applied = entries.filter(e => e.status === 'applied')
|
|
439
|
+
if (applied.length === 0) {
|
|
440
|
+
return { ok: false, reason: '台账里没有 applied 条目' }
|
|
441
|
+
}
|
|
442
|
+
// 按 batchId 分组,取最后那个 batch
|
|
443
|
+
const batchIds = [...new Set(applied.map(e => e.batchId))]
|
|
444
|
+
const lastBatch = batchIds[batchIds.length - 1]
|
|
445
|
+
const batchEntries = applied.filter(e => e.batchId === lastBatch)
|
|
446
|
+
|
|
447
|
+
const restored = []
|
|
448
|
+
const failed = []
|
|
449
|
+
for (const entry of batchEntries) {
|
|
450
|
+
const abs = join(cwd, entry.path)
|
|
451
|
+
try {
|
|
452
|
+
if (entry.beforeSha === null) {
|
|
453
|
+
// 文件原来不存在,回滚就是删掉它
|
|
454
|
+
await rm(abs, { force: true })
|
|
455
|
+
restored.push(`${entry.path}(删除)`)
|
|
456
|
+
} else {
|
|
457
|
+
// 从快照仓库 checkout 这个文件到 beforeSha 对应的版本
|
|
458
|
+
// 但 beforeSha 是哈希不是 git object——只能靠快照的 commit 来 checkout。
|
|
459
|
+
// 台账回滚的语义是「还原到这一批写入之前」,不是「还原到某个 git commit」。
|
|
460
|
+
// 所以这里走的是:如果文件当前哈希 !== beforeSha,就报「内容已被手改,不能自动还原」。
|
|
461
|
+
const currentSha = await fileSha256(abs)
|
|
462
|
+
if (currentSha === entry.beforeSha) {
|
|
463
|
+
// 已经和写入前一样了,不用动
|
|
464
|
+
restored.push(`${entry.path}(已一致)`)
|
|
465
|
+
} else if (currentSha === null) {
|
|
466
|
+
// 文件被删了,需要重建——但没有内容来源。报告这个情况。
|
|
467
|
+
failed.push(`${entry.path}(文件已被删除,无法重建)`)
|
|
468
|
+
} else {
|
|
469
|
+
// 文件被手改了,不能盲目覆盖
|
|
470
|
+
failed.push(`${entry.path}(已被手改,当前 ${currentSha?.slice(0, 8)} ≠ 写入前 ${entry.beforeSha?.slice(0, 8)})`)
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
} catch (error) {
|
|
474
|
+
failed.push(`${entry.path}(${messageOf(error)})`)
|
|
475
|
+
}
|
|
476
|
+
// 记 reverted 条目
|
|
477
|
+
appendLedgerEntry(cwd, project, {
|
|
478
|
+
index: entry.index,
|
|
479
|
+
batchId: entry.batchId,
|
|
480
|
+
stage: entry.stage,
|
|
481
|
+
path: entry.path,
|
|
482
|
+
beforeSha: entry.afterSha,
|
|
483
|
+
afterSha: entry.beforeSha,
|
|
484
|
+
status: 'reverted',
|
|
485
|
+
rollbackOf: entry.index,
|
|
486
|
+
ts: nowIso(),
|
|
487
|
+
})
|
|
488
|
+
}
|
|
489
|
+
return {
|
|
490
|
+
ok: failed.length === 0,
|
|
491
|
+
restored,
|
|
492
|
+
failed,
|
|
493
|
+
batchId: lastBatch,
|
|
494
|
+
count: batchEntries.length,
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* 检查 diff 里改的文件是否都在台账里。
|
|
500
|
+
* 不在台账里的算「越界改动」——不是实施段写的,是别的来源改的。
|
|
501
|
+
*/
|
|
502
|
+
export function checkLedgerCoverage(cwd, project, diffPaths) {
|
|
503
|
+
const entries = readLedger(cwd, project)
|
|
504
|
+
const ledgerPaths = new Set(entries
|
|
505
|
+
.filter(e => e.status === 'applied')
|
|
506
|
+
.map(e => normalizedPatchPath(e.path)))
|
|
507
|
+
const diff = Array.isArray(diffPaths) ? diffPaths : []
|
|
508
|
+
const outOfBounds = diff
|
|
509
|
+
.map(p => normalizedPatchPath(p))
|
|
510
|
+
.filter(p => !ledgerPaths.has(p))
|
|
511
|
+
return {
|
|
512
|
+
total: diff.length,
|
|
513
|
+
inLedger: diff.length - outOfBounds.length,
|
|
514
|
+
outOfBounds,
|
|
515
|
+
}
|
|
277
516
|
}
|
|
278
517
|
|
|
279
518
|
/**
|
|
@@ -374,11 +613,21 @@ async function attemptDiff(cwd, project, attempts, limitChars = DIFF_LIMIT_CHARS
|
|
|
374
613
|
* 按 STAGE_IO 拼出某一阶该看到的全部上下文。
|
|
375
614
|
* extraKeys 只给返工用(实施阶额外读上一轮的 QA_Report)。
|
|
376
615
|
* 读不到的文件直接跳过,不报错——缺产物由调用方按各自的规则处理。
|
|
616
|
+
*
|
|
617
|
+
* 传了 flow 就按 flow.yaml 里声明的 reads 读;不传走内置四阶。两条路
|
|
618
|
+
* 拿到的都是 ARTIFACT 的 key,下游 readArtifact 不用改。
|
|
377
619
|
*/
|
|
378
|
-
async function stageContext(cwd, project, stage, extraKeys = []) {
|
|
379
|
-
const
|
|
380
|
-
|
|
620
|
+
async function stageContext(cwd, project, stage, extraKeys = [], flow = undefined, contractText = undefined) {
|
|
621
|
+
const keys = flow === undefined
|
|
622
|
+
? [...(STAGE_IO[stage]?.reads ?? []), ...extraKeys]
|
|
623
|
+
: [...phaseReadKeys(flow.phases?.[stage - 1]), ...extraKeys]
|
|
381
624
|
const parts = []
|
|
625
|
+
// 契约排在最前面:它是这一阶的前提,不是附录。
|
|
626
|
+
// 放最前还有一个实际好处——上下文被截断时,截掉的是后面的产物,不是约定。
|
|
627
|
+
//
|
|
628
|
+
// 收参数而不是自己读:这个函数是纯拼装,读盘交给调用方。自己读的话它就跟
|
|
629
|
+
// 契约那套(哈希、上限)绑死了,单测也抠不出来单独跑。
|
|
630
|
+
if (typeof contractText === 'string' && contractText !== '') parts.push(contractText)
|
|
382
631
|
for (const key of keys) {
|
|
383
632
|
let text = await readArtifact(cwd, project, ARTIFACT[key])
|
|
384
633
|
if (text === undefined) continue
|
|
@@ -440,24 +689,28 @@ class StopRequested extends Error {
|
|
|
440
689
|
}
|
|
441
690
|
|
|
442
691
|
/** Resolve the parent conversation's working directory without a hard dependency. */
|
|
443
|
-
function cwdOf(ctx, agent) {
|
|
692
|
+
export function cwdOf(ctx, agent) {
|
|
444
693
|
const candidates = []
|
|
445
694
|
if (agent !== undefined) {
|
|
695
|
+
// 会话自己记的 cwd 排第一:那才是用户在左边工作区里选的那个文件夹。
|
|
696
|
+
//
|
|
697
|
+
// workingDirectory 服务排在后面当兜底——它有时候给的是「进程启动目录」,
|
|
698
|
+
// 不是会话目录。照它算,用户在左边切到 D:\我的项目,插件拿到的还是
|
|
699
|
+
// C:\...\default-workspace,于是工作流建在默认工作区、状态栏也显示那儿。
|
|
700
|
+
// 用户报的「只有默认工作区」就是这个。
|
|
701
|
+
const recorded = agent.session?.header?.cwd
|
|
702
|
+
if (typeof recorded === 'string' && isAbsolute(recorded)) candidates.push(recorded)
|
|
446
703
|
const workingDirectory = ctx.get('workingDirectory')
|
|
447
704
|
if (workingDirectory !== undefined) {
|
|
448
705
|
try {
|
|
449
706
|
candidates.push(workingDirectory.get(agent.session))
|
|
450
707
|
} catch {
|
|
451
|
-
//
|
|
708
|
+
// 拿不到就靠上面那个来源
|
|
452
709
|
}
|
|
453
710
|
}
|
|
454
|
-
const recorded = agent.session?.header?.cwd
|
|
455
|
-
if (typeof recorded === 'string' && isAbsolute(recorded)) candidates.push(recorded)
|
|
456
711
|
}
|
|
457
712
|
const valid = candidates.filter(item => typeof item === 'string' && item !== '')
|
|
458
|
-
//
|
|
459
|
-
// workingDirectory 有时给的是进程启动目录而不是会话目录,照它算就会得出
|
|
460
|
-
// 「工作流目录也算不在工作流里」——用户看到的状态栏永远是「未启用」。
|
|
713
|
+
// 两个来源打架时,优先选那个真在「工作流」里的——那是明确的意图信号。
|
|
461
714
|
const inFlow = valid.find(item => item.split(/[\\/]+/u).includes(FLOW_DIR_NAME))
|
|
462
715
|
return inFlow ?? valid[0] ?? process.cwd()
|
|
463
716
|
}
|
|
@@ -604,10 +857,222 @@ function assertIntentConverged(confirmation) {
|
|
|
604
857
|
}
|
|
605
858
|
}
|
|
606
859
|
|
|
860
|
+
/** 面板顶栏要显示版本号。读一次就够,装好之后不会变。 */
|
|
861
|
+
const PKG_VERSION = (() => {
|
|
862
|
+
try {
|
|
863
|
+
const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
|
|
864
|
+
return typeof pkg.version === 'string' ? pkg.version : ''
|
|
865
|
+
} catch {
|
|
866
|
+
return ''
|
|
867
|
+
}
|
|
868
|
+
})()
|
|
869
|
+
|
|
607
870
|
function stateDir(cwd, project) {
|
|
608
871
|
return join(cwd, '.project-flow', project)
|
|
609
872
|
}
|
|
610
873
|
|
|
874
|
+
// ── 完成契约 ────────────────────────────────────────────────────
|
|
875
|
+
//
|
|
876
|
+
// 长任务跨压缩之后,模型容易忘掉第 1 阶确认过的要求和禁改范围,后半段
|
|
877
|
+
// 开始自由发挥。这里把「要做什么、不许碰什么、什么算做完」存成一份文件,
|
|
878
|
+
// 每一阶都重新塞进 prompt——压缩带走的是对话,带不走磁盘。
|
|
879
|
+
//
|
|
880
|
+
// 长度上限 1200 字符是硬的:这段要进每一阶的 prompt,太长就把真正的内容挤掉了。
|
|
881
|
+
|
|
882
|
+
const CONTRACT_FILE = 'contract.json'
|
|
883
|
+
const CONTRACT_MAX_CHARS = 1200
|
|
884
|
+
|
|
885
|
+
const filled = value => typeof value === 'string' && value.trim() !== ''
|
|
886
|
+
|
|
887
|
+
/**
|
|
888
|
+
* 契约指纹。
|
|
889
|
+
*
|
|
890
|
+
* 只覆盖三份内容,不含创建时间之类的噪音——同内容必须同指纹,
|
|
891
|
+
* 否则「契约被换了」会天天误报。
|
|
892
|
+
*/
|
|
893
|
+
export function contractSha(contract) {
|
|
894
|
+
const basis = JSON.stringify({
|
|
895
|
+
requirements: Array.isArray(contract?.requirements) ? contract.requirements : [],
|
|
896
|
+
forbidden: Array.isArray(contract?.forbidden) ? contract.forbidden : [],
|
|
897
|
+
doneWhen: Array.isArray(contract?.doneWhen) ? contract.doneWhen : [],
|
|
898
|
+
})
|
|
899
|
+
return createHash('sha256').update(basis, 'utf8').digest('hex')
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
export async function readContract(cwd, project) {
|
|
903
|
+
try {
|
|
904
|
+
const parsed = JSON.parse(await readFile(join(stateDir(cwd, project), CONTRACT_FILE), 'utf8'))
|
|
905
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
|
|
906
|
+
return parsed
|
|
907
|
+
} catch {
|
|
908
|
+
return undefined
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
export async function writeContract(cwd, project, input) {
|
|
913
|
+
const dir = stateDir(cwd, project)
|
|
914
|
+
await mkdir(dir, { recursive: true })
|
|
915
|
+
const next = {
|
|
916
|
+
requirements: Array.isArray(input?.requirements) ? input.requirements.filter(filled).map(item => item.trim()) : [],
|
|
917
|
+
forbidden: Array.isArray(input?.forbidden) ? input.forbidden.filter(filled).map(item => item.trim()) : [],
|
|
918
|
+
doneWhen: Array.isArray(input?.doneWhen) ? input.doneWhen.filter(filled).map(item => item.trim()) : [],
|
|
919
|
+
}
|
|
920
|
+
next.sha = contractSha(next)
|
|
921
|
+
await writeFileAtomic(join(dir, CONTRACT_FILE), `${JSON.stringify(next, null, 2)}\n`)
|
|
922
|
+
return next
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* 把契约压成一段 prompt。
|
|
927
|
+
*
|
|
928
|
+
* 超长时的砍法有顺序:先砍「算做完」,再砍要求(从最后一条往前砍),
|
|
929
|
+
* 禁改项最后砍。理由是禁改项一旦被砍掉,越界就没人拦得住——那是这份契约
|
|
930
|
+
* 唯一能造成实际损失的地方,宁可少讲两条要求。
|
|
931
|
+
*/
|
|
932
|
+
export function contractBlock(contract) {
|
|
933
|
+
if (contract === undefined || contract === null) return ''
|
|
934
|
+
const reqs = Array.isArray(contract.requirements) ? contract.requirements : []
|
|
935
|
+
const forbidden = Array.isArray(contract.forbidden) ? contract.forbidden : []
|
|
936
|
+
const done = Array.isArray(contract.doneWhen) ? contract.doneWhen : []
|
|
937
|
+
if (reqs.length === 0 && forbidden.length === 0 && done.length === 0) return ''
|
|
938
|
+
|
|
939
|
+
const build = (r, f, d) => [
|
|
940
|
+
'## 这次任务的约定(每阶都重贴,压缩后也还在)',
|
|
941
|
+
...(r.length === 0 ? [] : ['要求:', ...r.map((line, index) => `${index + 1}. ${line}`)]),
|
|
942
|
+
...(d.length === 0 ? [] : ['算做完:', ...d.map(line => `- ${line}`)]),
|
|
943
|
+
...(f.length === 0 ? [] : ['不许碰(碰了要回滚):', ...f.map(line => `- ${line}`)]),
|
|
944
|
+
].join('\n')
|
|
945
|
+
|
|
946
|
+
let text = build(reqs, forbidden, done)
|
|
947
|
+
if (text.length <= CONTRACT_MAX_CHARS) return text
|
|
948
|
+
|
|
949
|
+
text = build(reqs, forbidden, [])
|
|
950
|
+
if (text.length <= CONTRACT_MAX_CHARS) return text
|
|
951
|
+
|
|
952
|
+
let keep = reqs.length
|
|
953
|
+
while (keep > 0 && build(reqs.slice(0, keep), forbidden, []).length > CONTRACT_MAX_CHARS) keep -= 1
|
|
954
|
+
text = build(reqs.slice(0, keep), forbidden, [])
|
|
955
|
+
if (text.length <= CONTRACT_MAX_CHARS) return text
|
|
956
|
+
|
|
957
|
+
// 要求砍光还超,就只剩禁改项。这条再长也不砍——它是底线。
|
|
958
|
+
text = ['## 这次任务的约定', '不许碰(碰了要回滚):', ...forbidden.map(line => `- ${line}`)].join('\n')
|
|
959
|
+
return text.length <= CONTRACT_MAX_CHARS ? text : text.slice(0, CONTRACT_MAX_CHARS)
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/**
|
|
963
|
+
* 判断一个路径有没有踩到禁改项。
|
|
964
|
+
*
|
|
965
|
+
* 比的是「规范化之后的前缀或相等」——用户写 `src/legacy`,那 `src/legacy/a.ts`
|
|
966
|
+
* 也算踩。反过来写 `src/legacy/a.ts` 不该把整个目录判进来。
|
|
967
|
+
* 反斜杠统一成正斜杠,不然同一个路径在 Windows 上会有两种写法。
|
|
968
|
+
*/
|
|
969
|
+
export function hitsForbidden(filePath, forbidden) {
|
|
970
|
+
if (typeof filePath !== 'string' || filePath === '') return ''
|
|
971
|
+
const norm = value => value.replace(/\\+/gu, '/').replace(/\/+$/u, '').toLowerCase()
|
|
972
|
+
const target = norm(filePath)
|
|
973
|
+
for (const entry of Array.isArray(forbidden) ? forbidden : []) {
|
|
974
|
+
const rule = norm(String(entry))
|
|
975
|
+
if (rule === '') continue
|
|
976
|
+
if (target === rule || target.startsWith(`${rule}/`)) return String(entry)
|
|
977
|
+
}
|
|
978
|
+
return ''
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// ── 声明式流程 ──────────────────────────────────────────────────
|
|
982
|
+
//
|
|
983
|
+
// 四阶以前是写死的:想加一个「安全评审」阶,或者换某一阶读哪些文件,
|
|
984
|
+
// 得改 index.js。现在项目目录里放一份 flow.yaml 就能改,代码只负责校验和执行。
|
|
985
|
+
//
|
|
986
|
+
// 向后兼容是硬要求:没有 flow.yaml 时走 BUILTIN_FLOW,行为和 0.8.x 逐条一致。
|
|
987
|
+
// 所以 STAGE_IO 留着不动——它是内置四阶的「不装 flow.yaml 时的那份」,
|
|
988
|
+
// 也是解析不出 flow.yaml 时的退路。
|
|
989
|
+
|
|
990
|
+
/** 项目自己的 flow.yaml。和 Requirement.md 放一起,一个项目一份。 */
|
|
991
|
+
function flowPath(cwd, project) {
|
|
992
|
+
return join(stateDir(cwd, project), 'flow.yaml')
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/** 产物文件名 → ARTIFACT 的 key。flow.yaml 里写文件名,内部认 key。 */
|
|
996
|
+
const ARTIFACT_KEY_BY_FILE = new Map(
|
|
997
|
+
Object.entries(ARTIFACT).map(([key, fileName]) => [fileName, key]),
|
|
998
|
+
)
|
|
999
|
+
|
|
1000
|
+
/**
|
|
1001
|
+
* 读某个项目生效的流程。
|
|
1002
|
+
*
|
|
1003
|
+
* 三种结果:
|
|
1004
|
+
* - 没有 flow.yaml:返回内置四阶,`configured=false`
|
|
1005
|
+
* - 有且合法:返回它,`configured=true`
|
|
1006
|
+
* - 有但不合法:返回内置四阶并带上 errors——调用方决定是拒跑还是照跑。
|
|
1007
|
+
* 只在 project_run 入口拒,别的路径(状态栏、诊断)不该因为配置写错就整个不可用。
|
|
1008
|
+
*/
|
|
1009
|
+
async function resolveFlow(cwd, project) {
|
|
1010
|
+
const file = flowPath(cwd, project)
|
|
1011
|
+
let text
|
|
1012
|
+
try {
|
|
1013
|
+
text = await readFile(file, 'utf8')
|
|
1014
|
+
} catch {
|
|
1015
|
+
return { flow: BUILTIN_FLOW, configured: false, errors: [], warnings: [] }
|
|
1016
|
+
}
|
|
1017
|
+
const result = loadFlow(text)
|
|
1018
|
+
if (!result.ok) {
|
|
1019
|
+
return { flow: BUILTIN_FLOW, configured: true, errors: result.errors, warnings: result.warnings }
|
|
1020
|
+
}
|
|
1021
|
+
return {
|
|
1022
|
+
flow: { process: result.doc.process, phases: result.phases },
|
|
1023
|
+
configured: true,
|
|
1024
|
+
errors: [],
|
|
1025
|
+
warnings: result.warnings,
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/**
|
|
1030
|
+
* 把 flow.yaml 里写的文件名换算成 ARTIFACT 的 key。
|
|
1031
|
+
*
|
|
1032
|
+
* 认不出来的是 glob(比如 `src/**`)——那不是产物,不参与「这一阶该读到什么」,
|
|
1033
|
+
* 直接跳过。跳过不是错误:flow.yaml 允许声明它读取代码目录,只是这一层喂不了。
|
|
1034
|
+
*/
|
|
1035
|
+
function phaseReadKeys(phase) {
|
|
1036
|
+
if (phase === undefined || phase === null || !Array.isArray(phase.reads)) return []
|
|
1037
|
+
const keys = []
|
|
1038
|
+
for (const entry of phase.reads) {
|
|
1039
|
+
if (typeof entry !== 'string') continue
|
|
1040
|
+
const key = ARTIFACT_KEY_BY_FILE.get(entry) ?? ARTIFACT_KEY_BY_FILE.get(basename(entry))
|
|
1041
|
+
if (key !== undefined) keys.push(key)
|
|
1042
|
+
}
|
|
1043
|
+
return keys
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/**
|
|
1047
|
+
* 某一阶到底用哪个模型。
|
|
1048
|
+
*
|
|
1049
|
+
* 优先级:flow.yaml 里 phase 的 `model` > project-flow.json 里的 > 继承主对话。
|
|
1050
|
+
* 三者都空就是「跟主对话走」——空串在这个插件里一直是这个意思,不是「没设」。
|
|
1051
|
+
*
|
|
1052
|
+
* 只在调用点算,不缓存到模块变量:两个项目可以同时跑(maxConcurrentProjects=2),
|
|
1053
|
+
* 一个项目级的状态放在模块上就会串。
|
|
1054
|
+
*/
|
|
1055
|
+
export function stageModelOf(settings, flow, stageNo, fallback) {
|
|
1056
|
+
const phase = flow?.phases?.[stageNo - 1]
|
|
1057
|
+
const configured = phase !== undefined && phase !== null && typeof phase.model === 'object' && phase.model !== null
|
|
1058
|
+
? phase.model
|
|
1059
|
+
: null
|
|
1060
|
+
const fromPhase = key => {
|
|
1061
|
+
if (configured === null) return ''
|
|
1062
|
+
const value = configured[key]
|
|
1063
|
+
return typeof value === 'string' ? value.trim() : ''
|
|
1064
|
+
}
|
|
1065
|
+
const phaseProvider = fromPhase('provider')
|
|
1066
|
+
const phaseModel = fromPhase('model')
|
|
1067
|
+
return {
|
|
1068
|
+
provider: settings.provider,
|
|
1069
|
+
llmProvider: phaseProvider !== '' ? phaseProvider : fallback.llmProvider,
|
|
1070
|
+
model: phaseModel !== '' ? phaseModel : fallback.model,
|
|
1071
|
+
// 这个模型是 flow.yaml 指定的,还是配置里来的——回退日志要说清是谁的锅。
|
|
1072
|
+
source: phaseModel !== '' ? 'flow.yaml' : fallback.llmProvider === '' && fallback.model === '' ? 'inherit' : 'config',
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
|
|
611
1076
|
/**
|
|
612
1077
|
* Reject a project name that would escape `.project-flow`.
|
|
613
1078
|
*
|
|
@@ -708,21 +1173,64 @@ const FLOW_DIR_NAME = '工作流'
|
|
|
708
1173
|
*/
|
|
709
1174
|
const FLOW_GATE_MODES = ['strict', 'off']
|
|
710
1175
|
|
|
711
|
-
function flowModeOf(settings) {
|
|
1176
|
+
export function flowModeOf(settings) {
|
|
712
1177
|
const raw = typeof settings?.flowGate === 'string' ? settings.flowGate.trim().toLowerCase() : ''
|
|
713
1178
|
return FLOW_GATE_MODES.includes(raw) ? raw : 'strict'
|
|
714
1179
|
}
|
|
715
1180
|
|
|
1181
|
+
/**
|
|
1182
|
+
* 这个路径是不是落在系统盘上。
|
|
1183
|
+
*
|
|
1184
|
+
* Windows 上系统盘就是 `%SystemDrive%`(通常 C:)。别的平台没这个概念,
|
|
1185
|
+
* 一律返回 false——这条规则是给 Windows 用户省系统盘用的。
|
|
1186
|
+
*/
|
|
1187
|
+
export function onSystemDrive(target) {
|
|
1188
|
+
if (process.platform !== 'win32') return false
|
|
1189
|
+
const system = (process.env.SystemDrive ?? 'C:').replace(/[\\/]+$/u, '').toLowerCase()
|
|
1190
|
+
const normalized = String(target ?? '').replace(/\\+/gu, '/').toLowerCase()
|
|
1191
|
+
return normalized === system.toLowerCase() || normalized.startsWith(`${system.toLowerCase()}/`)
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
/**
|
|
1195
|
+
* 找一个能放数据的盘。
|
|
1196
|
+
*
|
|
1197
|
+
* 从 D 往后试:C 装系统和缓存,项目数据不该放那儿。都没有就返回 undefined,
|
|
1198
|
+
* 调用方据此留在原地——单盘机器上没得选,报错也没用。
|
|
1199
|
+
*/
|
|
1200
|
+
export function pickDataDrive() {
|
|
1201
|
+
if (process.platform !== 'win32') return undefined
|
|
1202
|
+
for (const letter of ['D', 'E', 'F', 'G']) {
|
|
1203
|
+
try {
|
|
1204
|
+
if (existsSync(`${letter}:\\`)) return `${letter}:`
|
|
1205
|
+
} catch {
|
|
1206
|
+
// 这个盘符不可访问,试下一个
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
return undefined
|
|
1210
|
+
}
|
|
1211
|
+
|
|
716
1212
|
/**
|
|
717
1213
|
* 工作模式的地盘在哪(只有 strict 模式用它算「应该在的目录」)。
|
|
718
1214
|
*
|
|
719
|
-
* `flowRoot`
|
|
720
|
-
*
|
|
1215
|
+
* `flowRoot` 配了绝对路径就只认那个路径及其子目录;没配就看 cwd 落在哪个盘——
|
|
1216
|
+
* 系统盘上不建,见下面的说明。
|
|
721
1217
|
*/
|
|
722
|
-
function flowRootOf(cwd, settings) {
|
|
1218
|
+
export function flowRootOf(cwd, settings) {
|
|
723
1219
|
const configured = typeof settings.flowRoot === 'string' ? settings.flowRoot.trim() : ''
|
|
724
1220
|
if (configured !== '' && isAbsolute(configured)) return resolve(configured)
|
|
725
|
-
|
|
1221
|
+
const base = resolve(cwd)
|
|
1222
|
+
// 不往系统盘上建工作流。
|
|
1223
|
+
//
|
|
1224
|
+
// 用户的默认工作区就在 C 盘(DSH 装在 C,默认工作区跟着走),于是
|
|
1225
|
+
// 「谁的工作区就在谁下面建」等于把项目数据全塞进系统盘。他明确说了
|
|
1226
|
+
// 「默认不要在此盘」——那就是别在 C 盘上建。
|
|
1227
|
+
//
|
|
1228
|
+
// 有别的盘就挪过去(<盘>:\工作流),单盘机器上留在原地。
|
|
1229
|
+
if (onSystemDrive(base)) {
|
|
1230
|
+
const data = pickDataDrive()
|
|
1231
|
+
if (data !== undefined) return join(`${data}${sep}`, FLOW_DIR_NAME)
|
|
1232
|
+
}
|
|
1233
|
+
return join(base, configured === '' ? FLOW_DIR_NAME : configured)
|
|
726
1234
|
}
|
|
727
1235
|
|
|
728
1236
|
/**
|
|
@@ -747,7 +1255,7 @@ function flowRootConfigured(settings) {
|
|
|
747
1255
|
* 所以:配置根下面如果真有一个「工作流」且里面已经有 .project-flow,
|
|
748
1256
|
* 就指到那一层;否则才用配置根本身。
|
|
749
1257
|
*/
|
|
750
|
-
function flowRootTargetOf(cwd, settings) {
|
|
1258
|
+
export function flowRootTargetOf(cwd, settings) {
|
|
751
1259
|
const root = flowRootOf(cwd, settings)
|
|
752
1260
|
try {
|
|
753
1261
|
const nested = join(root, FLOW_DIR_NAME)
|
|
@@ -765,7 +1273,7 @@ function flowRootTargetOf(cwd, settings) {
|
|
|
765
1273
|
* 1. flowRoot 配了绝对路径 —— 这是明确表态「只在这个子树里用」,那就守它
|
|
766
1274
|
* 2. flowGate=strict —— 用户主动要那道边界
|
|
767
1275
|
*/
|
|
768
|
-
function insideFlow(cwd, settings) {
|
|
1276
|
+
export function insideFlow(cwd, settings) {
|
|
769
1277
|
const configured = typeof settings.flowRoot === 'string' ? settings.flowRoot.trim() : ''
|
|
770
1278
|
const here = resolve(cwd)
|
|
771
1279
|
// 配了绝对路径:就是那个目录的子树,别处一律不算。这条不看 flowGate,
|
|
@@ -810,20 +1318,29 @@ function flowGateMessage(cwd, settings) {
|
|
|
810
1318
|
* @returns {{ root: string, created: boolean, moved: boolean }}
|
|
811
1319
|
* root 这次该用的工作目录;created 表示这次新建了目录;moved 表示 base 从 cwd 换成了 root
|
|
812
1320
|
*/
|
|
813
|
-
async function ensureFlowRoot(cwd, settings) {
|
|
1321
|
+
export async function ensureFlowRoot(cwd, settings) {
|
|
814
1322
|
if (insideFlow(cwd, settings)) {
|
|
815
1323
|
return { root: cwd, created: false, moved: false }
|
|
816
1324
|
}
|
|
817
|
-
|
|
818
|
-
|
|
1325
|
+
// 用 flowRootTargetOf 而不是 flowRootOf:配了绝对路径时,真正的项目数据
|
|
1326
|
+
// 常常在它下面那层「工作流」里(用户配 D:\某个目录,项目在 D:\某个目录\工作流)。
|
|
1327
|
+
// 用外层的话,工作目录会指到没有 .project-flow 的地方,项目一个都看不见。
|
|
1328
|
+
const root = flowRootTargetOf(cwd, settings)
|
|
1329
|
+
// mkdir recursive 对已存在的目录不报错,所以「建成功了」和「这次新建了」
|
|
1330
|
+
// 是两件事,得分开判。以前把两者混成一个 created,于是每次调用都报
|
|
1331
|
+
// 「新建了」——状态栏和日志里都会说一句假话。
|
|
1332
|
+
const existed = existsSync(root)
|
|
819
1333
|
try {
|
|
820
1334
|
await mkdir(root, { recursive: true })
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
//
|
|
824
|
-
|
|
1335
|
+
} catch (error) {
|
|
1336
|
+
// 建不出来就说清是哪条路走不通。
|
|
1337
|
+
//
|
|
1338
|
+
// 以前这里静默退回,用户看到的只有一句「不在工作流目录里」——他完全
|
|
1339
|
+
// 不知道该干什么:是权限问题?盘只读?还是路径本身不合法?
|
|
1340
|
+
// 一句「建不出来」比一句「不行」有用得多。
|
|
1341
|
+
return { root: cwd, created: false, moved: false, error: messageOf(error), attempted: root }
|
|
825
1342
|
}
|
|
826
|
-
return { root, created:
|
|
1343
|
+
return { root, created: !existed, moved: true }
|
|
827
1344
|
}
|
|
828
1345
|
|
|
829
1346
|
/** 上次在这个工作流目录里确认过的盲区与假设,放在工作流根下的一个文件里。 */
|
|
@@ -1128,23 +1645,28 @@ async function runStage(ctx, options) {
|
|
|
1128
1645
|
try {
|
|
1129
1646
|
let activation
|
|
1130
1647
|
let used = routes[0]
|
|
1131
|
-
|
|
1648
|
+
// 每级失败都留一条,不只是第一个:三级都试过之后,用户要知道是哪一级
|
|
1649
|
+
// 顶住了。只记 firstError 的话,「配置那个起不来」会把「继承主对话也起不来」
|
|
1650
|
+
// 吞掉,日志上看着像一次成功回退。
|
|
1651
|
+
const failures = []
|
|
1132
1652
|
for (const route of routes) {
|
|
1133
1653
|
try {
|
|
1134
1654
|
activation = await start(route)
|
|
1135
1655
|
used = route
|
|
1136
1656
|
break
|
|
1137
1657
|
} catch (error) {
|
|
1138
|
-
|
|
1658
|
+
failures.push({ route, error })
|
|
1139
1659
|
}
|
|
1140
1660
|
}
|
|
1141
|
-
if (activation === undefined) throw
|
|
1661
|
+
if (activation === undefined) throw failures[0]?.error ?? new Error('所有路由都起不来')
|
|
1142
1662
|
const describe = route => route.model === ''
|
|
1143
1663
|
? '主对话模型'
|
|
1144
1664
|
: `${route.llmProvider === '' ? route.provider : route.llmProvider}/${route.model}`
|
|
1145
1665
|
if (used !== routes[0]) {
|
|
1146
|
-
routeNote = `${label}
|
|
1147
|
-
|
|
1666
|
+
routeNote = `${label}|` + failures
|
|
1667
|
+
.map(item => `tried=${describe(item.route)} reason=${messageOf(item.error).slice(0, 120)}`)
|
|
1668
|
+
.join(';')
|
|
1669
|
+
+ `|fellBackTo=${describe(used)}`
|
|
1148
1670
|
}
|
|
1149
1671
|
|
|
1150
1672
|
let outcome = await settle(activation)
|
|
@@ -1615,22 +2137,908 @@ export function estimateCost(settings, { requirements = 0, models } = {}) {
|
|
|
1615
2137
|
}
|
|
1616
2138
|
}
|
|
1617
2139
|
|
|
1618
|
-
/** 所有轮次实施报过或快照比对出来的文件并集,快照不可用时拿它兜底。 */
|
|
1619
|
-
function buildSummaryFiles(attempts) {
|
|
1620
|
-
const set = new Set()
|
|
1621
|
-
for (const item of Array.isArray(attempts) ? attempts : []) {
|
|
1622
|
-
for (const path of Array.isArray(item?.files) ? item.files : []) {
|
|
1623
|
-
if (typeof path === 'string' && path !== '') set.add(path)
|
|
2140
|
+
/** 所有轮次实施报过或快照比对出来的文件并集,快照不可用时拿它兜底。 */
|
|
2141
|
+
function buildSummaryFiles(attempts) {
|
|
2142
|
+
const set = new Set()
|
|
2143
|
+
for (const item of Array.isArray(attempts) ? attempts : []) {
|
|
2144
|
+
for (const path of Array.isArray(item?.files) ? item.files : []) {
|
|
2145
|
+
if (typeof path === 'string' && path !== '') set.add(path)
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
return [...set]
|
|
2149
|
+
}
|
|
2150
|
+
async function readArtifact(cwd, project, fileName) {
|
|
2151
|
+
try {
|
|
2152
|
+
return await readFile(join(stateDir(cwd, project), fileName), 'utf8')
|
|
2153
|
+
} catch {
|
|
2154
|
+
return undefined
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
|
|
2158
|
+
// ── 断言执行器 ──────────────────────────────────────────────────
|
|
2159
|
+
//
|
|
2160
|
+
// 质检以前只说「我核过了」。这一节让它自己跑命令:Requirement.md 的 YAML
|
|
2161
|
+
// 前置块里,每条要求可以带一条 check,退出码就是判据。
|
|
2162
|
+
//
|
|
2163
|
+
// 分工定死:模型解释结果,命令产出结果。命令说不过,模型说过了也不算数;
|
|
2164
|
+
// 要求没写 check,那一条就只能记 unverified,不能算 PASS——这是这一节存在的
|
|
2165
|
+
// 全部理由,破了这条就等于回到原来那套。
|
|
2166
|
+
|
|
2167
|
+
/** 默认白名单。配置只能往上加:能删的话「判据」就又能被配置关掉了。 */
|
|
2168
|
+
const DEFAULT_ALLOWED_COMMANDS = ['node', 'npm', 'pnpm', 'python', 'pytest', 'git', 'cargo', 'go', 'dotnet']
|
|
2169
|
+
|
|
2170
|
+
/** 单条 check 的默认超时,以及断言输出留多长的尾巴。 */
|
|
2171
|
+
const DEFAULT_CHECK_TIMEOUT_MS = 120000
|
|
2172
|
+
const DEFAULT_CHECK_TAIL_CHARS = 8000
|
|
2173
|
+
|
|
2174
|
+
/**
|
|
2175
|
+
* 「命令不存在」超过这个条数就整组退成 unverified。
|
|
2176
|
+
* 连着五条都 ENOENT,说明这台机器没装那套工具链,不是这次实现写错了;
|
|
2177
|
+
* 硬判 FAIL 会把环境问题记成代码问题,返工几轮也修不好。
|
|
2178
|
+
*/
|
|
2179
|
+
const CHECK_MISSING_BINARY_LIMIT = 5
|
|
2180
|
+
|
|
2181
|
+
/**
|
|
2182
|
+
* 拆文件头那段 YAML 前置块。
|
|
2183
|
+
*
|
|
2184
|
+
* 手写行解析,不引 YAML 库:这一块只放 checks,格式由我们自己定,
|
|
2185
|
+
* 引一个库换来的「通用」在这里没有用。
|
|
2186
|
+
*/
|
|
2187
|
+
function splitFrontMatter(text) {
|
|
2188
|
+
if (typeof text !== 'string') return { front: '', body: '' }
|
|
2189
|
+
const trimmed = text.replace(/^\uFEFF/u, '')
|
|
2190
|
+
if (!trimmed.startsWith('---')) return { front: '', body: trimmed }
|
|
2191
|
+
const firstBreak = trimmed.indexOf('\n')
|
|
2192
|
+
if (firstBreak === -1) return { front: '', body: trimmed }
|
|
2193
|
+
const end = trimmed.indexOf('\n---', firstBreak)
|
|
2194
|
+
if (end === -1) return { front: '', body: trimmed }
|
|
2195
|
+
return {
|
|
2196
|
+
front: trimmed.slice(firstBreak + 1, end),
|
|
2197
|
+
body: trimmed.slice(end + 4).replace(/^\n+/u, ''),
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
|
|
2201
|
+
/** YAML 标量还原:双引号走 JSON 转义,单引号按 YAML 规矩去掉一层。 */
|
|
2202
|
+
function unquoteScalar(value) {
|
|
2203
|
+
const text = typeof value === 'string' ? value.trim() : ''
|
|
2204
|
+
if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) {
|
|
2205
|
+
try {
|
|
2206
|
+
return String(JSON.parse(text))
|
|
2207
|
+
} catch {
|
|
2208
|
+
return text.slice(1, -1)
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
if (text.length >= 2 && text.startsWith("'") && text.endsWith("'")) return text.slice(1, -1)
|
|
2212
|
+
return text
|
|
2213
|
+
}
|
|
2214
|
+
|
|
2215
|
+
/** 写回去时的标量引法。空串写成 '',其余一律 JSON 双引号——YAML 认这一套。 */
|
|
2216
|
+
function quoteScalar(value) {
|
|
2217
|
+
const text = typeof value === 'string' ? value : String(value ?? '')
|
|
2218
|
+
return text === '' ? "''" : JSON.stringify(text)
|
|
2219
|
+
}
|
|
2220
|
+
|
|
2221
|
+
/**
|
|
2222
|
+
* 把 Requirement.md 的前置块读成 [{ req, cmd, expectExit }]。
|
|
2223
|
+
*
|
|
2224
|
+
* 只认 checks: 下面那几行,别的一概不碰:前置块以后还要放别的东西,
|
|
2225
|
+
* 见什么认什么都收进来,迟早会把散文当成命令跑。
|
|
2226
|
+
*/
|
|
2227
|
+
export function parseRequirementChecks(text) {
|
|
2228
|
+
const { front } = splitFrontMatter(text)
|
|
2229
|
+
if (front === '') return []
|
|
2230
|
+
const entries = []
|
|
2231
|
+
let inChecks = false
|
|
2232
|
+
let current
|
|
2233
|
+
for (const rawLine of front.split(/\r?\n/u)) {
|
|
2234
|
+
const line = rawLine.replace(/\s+$/u, '')
|
|
2235
|
+
if (/^checks\s*:\s*$/u.test(line)) {
|
|
2236
|
+
inChecks = true
|
|
2237
|
+
continue
|
|
2238
|
+
}
|
|
2239
|
+
// 顶格的非空行意味着 checks 这一段结束了。
|
|
2240
|
+
if (inChecks && /^\S/u.test(line)) {
|
|
2241
|
+
inChecks = false
|
|
2242
|
+
current = undefined
|
|
2243
|
+
}
|
|
2244
|
+
if (!inChecks) continue
|
|
2245
|
+
const reqMatch = /^\s*-\s*req\s*:\s*(\d+)\s*$/u.exec(line)
|
|
2246
|
+
if (reqMatch !== null) {
|
|
2247
|
+
current = { req: Number(reqMatch[1]), cmd: '', expectExit: 0 }
|
|
2248
|
+
entries.push(current)
|
|
2249
|
+
continue
|
|
2250
|
+
}
|
|
2251
|
+
if (current === undefined) continue
|
|
2252
|
+
const cmdMatch = /^\s+cmd\s*:\s*(.*)$/u.exec(line)
|
|
2253
|
+
if (cmdMatch !== null) {
|
|
2254
|
+
current.cmd = unquoteScalar(cmdMatch[1])
|
|
2255
|
+
continue
|
|
2256
|
+
}
|
|
2257
|
+
const exitMatch = /^\s+exit\s*:\s*(-?\d+)\s*$/u.exec(line)
|
|
2258
|
+
if (exitMatch !== null) current.expectExit = Number(exitMatch[1])
|
|
2259
|
+
}
|
|
2260
|
+
return entries
|
|
2261
|
+
}
|
|
2262
|
+
|
|
2263
|
+
/** 反过来:把断言表写成一段前置块。cmd 为空表示这条要求没定义判据。 */
|
|
2264
|
+
export function renderRequirementChecks(entries) {
|
|
2265
|
+
if (!Array.isArray(entries) || entries.length === 0) return ''
|
|
2266
|
+
const lines = ['---', 'checks:']
|
|
2267
|
+
for (const entry of entries) {
|
|
2268
|
+
lines.push(` - req: ${entry.req}`)
|
|
2269
|
+
lines.push(` cmd: ${quoteScalar(entry.cmd ?? '')}`)
|
|
2270
|
+
lines.push(` exit: ${Number.isInteger(entry.expectExit) ? entry.expectExit : 0}`)
|
|
2271
|
+
}
|
|
2272
|
+
lines.push('---')
|
|
2273
|
+
return lines.join('\n')
|
|
2274
|
+
}
|
|
2275
|
+
|
|
2276
|
+
/**
|
|
2277
|
+
* 判据指纹:req / 命令 / 期望退出码三样的 sha256。
|
|
2278
|
+
*
|
|
2279
|
+
* 只覆盖判据本身,不覆盖要求正文——文案改写不是作弊,改判据才是。
|
|
2280
|
+
* 顺序也算在内:把两条命令对调,跑起来结果就变了。
|
|
2281
|
+
*
|
|
2282
|
+
* 使用固定字段顺序的 JSON(req、cmd、expectedExit,按原顺序排列)作为输入,
|
|
2283
|
+
* sha256 输出小写十六进制。
|
|
2284
|
+
*/
|
|
2285
|
+
export function requirementFingerprint(entries) {
|
|
2286
|
+
const list = Array.isArray(entries) ? entries : []
|
|
2287
|
+
const canonical = JSON.stringify(
|
|
2288
|
+
list.map(entry => ({
|
|
2289
|
+
req: Number.isInteger(entry.req) ? entry.req : 0,
|
|
2290
|
+
cmd: typeof entry.cmd === 'string' ? entry.cmd : '',
|
|
2291
|
+
expectedExit: Number.isInteger(entry.expectExit) ? entry.expectExit : 0,
|
|
2292
|
+
})),
|
|
2293
|
+
)
|
|
2294
|
+
return createHash('sha256').update(canonical, 'utf8').digest('hex')
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
/** 命令名归一:取 basename、小写、去掉 Windows 的扩展名。 */
|
|
2298
|
+
function commandNameOf(token) {
|
|
2299
|
+
const base = basename(String(token ?? '').trim()).toLowerCase()
|
|
2300
|
+
return base.replace(/\.(exe|cmd|bat|ps1)$/u, '')
|
|
2301
|
+
}
|
|
2302
|
+
|
|
2303
|
+
/** 生效的白名单 = 写死的 9 类 + 配置里加的,去掉空串和重复。 */
|
|
2304
|
+
export function allowedCommandsOf(settings) {
|
|
2305
|
+
const extra = typeof settings?.checkAllowedCommands === 'string' ? settings.checkAllowedCommands : ''
|
|
2306
|
+
const names = [...DEFAULT_ALLOWED_COMMANDS, ...extra.split(/[,\s]+/u)]
|
|
2307
|
+
.map(commandNameOf)
|
|
2308
|
+
.filter(name => name !== '')
|
|
2309
|
+
return [...new Set(names)]
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
/**
|
|
2313
|
+
* 按 shell 的习惯切命令,但不交给 shell 执行。
|
|
2314
|
+
*
|
|
2315
|
+
* 切是为了拿首 token 去比白名单、把剩下的当参数传给 execFile。
|
|
2316
|
+
* execFile 不走 shell,所以 `;` `|` `&&` 都不会被解释——它们只会变成
|
|
2317
|
+
* 传给程序的普通字符串参数。这是「白名单」能立得住的物理前提。
|
|
2318
|
+
*/
|
|
2319
|
+
export function tokenizeCommand(cmd) {
|
|
2320
|
+
const text = typeof cmd === 'string' ? cmd : ''
|
|
2321
|
+
const tokens = []
|
|
2322
|
+
let current = ''
|
|
2323
|
+
let quote = ''
|
|
2324
|
+
let started = false
|
|
2325
|
+
for (const ch of text) {
|
|
2326
|
+
if (quote !== '') {
|
|
2327
|
+
if (ch === quote) {
|
|
2328
|
+
quote = ''
|
|
2329
|
+
continue
|
|
2330
|
+
}
|
|
2331
|
+
current += ch
|
|
2332
|
+
continue
|
|
2333
|
+
}
|
|
2334
|
+
if (ch === '"' || ch === "'") {
|
|
2335
|
+
quote = ch
|
|
2336
|
+
started = true
|
|
2337
|
+
continue
|
|
2338
|
+
}
|
|
2339
|
+
if (/\s/u.test(ch)) {
|
|
2340
|
+
if (started) {
|
|
2341
|
+
tokens.push(current)
|
|
2342
|
+
current = ''
|
|
2343
|
+
started = false
|
|
2344
|
+
}
|
|
2345
|
+
continue
|
|
2346
|
+
}
|
|
2347
|
+
current += ch
|
|
2348
|
+
started = true
|
|
2349
|
+
}
|
|
2350
|
+
if (started) tokens.push(current)
|
|
2351
|
+
return tokens
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
/**
|
|
2355
|
+
* 一条命令能不能跑。拒绝理由要写清楚是哪一条规则拦的,否则人只看到一句
|
|
2356
|
+
* 「没跑」,会以为插件坏了。
|
|
2357
|
+
*/
|
|
2358
|
+
export function checkDenial(cmd, allowed) {
|
|
2359
|
+
const list = Array.isArray(allowed) ? allowed : DEFAULT_ALLOWED_COMMANDS
|
|
2360
|
+
if (typeof cmd !== 'string' || cmd.trim() === '') return { denied: true, reason: 'check 是空的' }
|
|
2361
|
+
const tokens = tokenizeCommand(cmd)
|
|
2362
|
+
const name = commandNameOf(tokens[0] ?? '')
|
|
2363
|
+
if (name === '') return { denied: true, reason: '认不出命令名' }
|
|
2364
|
+
if (!list.includes(name)) {
|
|
2365
|
+
return { denied: true, reason: `命令 ${name} 不在白名单里(只放行 ${list.join(' / ')})` }
|
|
2366
|
+
}
|
|
2367
|
+
return { denied: false, name, file: tokens[0], args: tokens.slice(1) }
|
|
2368
|
+
}
|
|
2369
|
+
|
|
2370
|
+
/** 输出只留尾巴。stdout 大的时候前面几千行是噪音,报错在最后几行。 */
|
|
2371
|
+
function tailOf(text, limit) {
|
|
2372
|
+
const value = typeof text === 'string' ? text : ''
|
|
2373
|
+
const max = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : DEFAULT_CHECK_TAIL_CHARS
|
|
2374
|
+
return value.length <= max ? value : value.slice(value.length - max)
|
|
2375
|
+
}
|
|
2376
|
+
|
|
2377
|
+
/**
|
|
2378
|
+
* 真正起进程。默认实现走 execFile:不走 shell,超时用 SIGKILL 收掉,
|
|
2379
|
+
* 拿不到可执行文件时按 127 记(和 shell 的规矩一致)。
|
|
2380
|
+
*/
|
|
2381
|
+
function defaultSpawnCheck({ file, args, cwd, timeoutMs, env }) {
|
|
2382
|
+
return new Promise(resolve => {
|
|
2383
|
+
execFile(file, args, {
|
|
2384
|
+
cwd,
|
|
2385
|
+
timeout: timeoutMs,
|
|
2386
|
+
killSignal: 'SIGKILL',
|
|
2387
|
+
windowsHide: true,
|
|
2388
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
2389
|
+
...(env === undefined ? {} : { env }),
|
|
2390
|
+
}, (error, stdout, stderr) => {
|
|
2391
|
+
const output = `${stdout ?? ''}${stderr ?? ''}`
|
|
2392
|
+
if (error === null || error === undefined) {
|
|
2393
|
+
resolve({ exit: 0, output })
|
|
2394
|
+
return
|
|
2395
|
+
}
|
|
2396
|
+
if (error.code === 'ENOENT') {
|
|
2397
|
+
resolve({ exit: 127, output: `${output}${error.message}`, missing: true })
|
|
2398
|
+
return
|
|
2399
|
+
}
|
|
2400
|
+
const timedOut = error.killed === true || (error.signal !== undefined && error.signal !== null)
|
|
2401
|
+
// 超时一律记 124(和 shell timeout 命令一致),不用内核信号码。
|
|
2402
|
+
if (timedOut) {
|
|
2403
|
+
resolve({ exit: 124, output, timedOut: true })
|
|
2404
|
+
return
|
|
2405
|
+
}
|
|
2406
|
+
if (typeof error.code === 'number') {
|
|
2407
|
+
resolve({ exit: error.code, output })
|
|
2408
|
+
return
|
|
2409
|
+
}
|
|
2410
|
+
resolve({ exit: 1, output: `${output}${error.message}` })
|
|
2411
|
+
})
|
|
2412
|
+
})
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
/**
|
|
2416
|
+
* 串行跑全部 check,返回 assertions[]。
|
|
2417
|
+
*
|
|
2418
|
+
* 串行是有意的:同一项目不会同时跑两轮,但这些命令可能抢同一个端口、
|
|
2419
|
+
* 同一份构建产物,并发跑等于自己给自己制造不确定性。
|
|
2420
|
+
*/
|
|
2421
|
+
export async function runRequirementChecks(options) {
|
|
2422
|
+
const {
|
|
2423
|
+
entries = [],
|
|
2424
|
+
cwd,
|
|
2425
|
+
allowed = DEFAULT_ALLOWED_COMMANDS,
|
|
2426
|
+
timeoutMs = DEFAULT_CHECK_TIMEOUT_MS,
|
|
2427
|
+
tailChars = DEFAULT_CHECK_TAIL_CHARS,
|
|
2428
|
+
env,
|
|
2429
|
+
spawnCheck = defaultSpawnCheck,
|
|
2430
|
+
} = options ?? {}
|
|
2431
|
+
const assertions = []
|
|
2432
|
+
for (const entry of Array.isArray(entries) ? entries : []) {
|
|
2433
|
+
const req = Number.isInteger(entry?.req) ? entry.req : assertions.length + 1
|
|
2434
|
+
const cmd = typeof entry?.cmd === 'string' ? entry.cmd.trim() : ''
|
|
2435
|
+
if (cmd === '') {
|
|
2436
|
+
assertions.push({ req, cmd: null, exit: null, durationMs: 0, stdoutTail: '', status: 'unverified' })
|
|
2437
|
+
continue
|
|
2438
|
+
}
|
|
2439
|
+
const denial = checkDenial(cmd, allowed)
|
|
2440
|
+
if (denial.denied === true) {
|
|
2441
|
+
assertions.push({
|
|
2442
|
+
req,
|
|
2443
|
+
cmd,
|
|
2444
|
+
exit: 126,
|
|
2445
|
+
durationMs: 0,
|
|
2446
|
+
stdoutTail: `白名单拒绝:${denial.reason}`,
|
|
2447
|
+
status: 'denied',
|
|
2448
|
+
denied: true,
|
|
2449
|
+
})
|
|
2450
|
+
continue
|
|
2451
|
+
}
|
|
2452
|
+
const startedAt = Date.now()
|
|
2453
|
+
let run
|
|
2454
|
+
try {
|
|
2455
|
+
run = await spawnCheck({ file: denial.file, args: denial.args, cwd, timeoutMs, env })
|
|
2456
|
+
} catch (error) {
|
|
2457
|
+
run = { exit: 1, output: messageOf(error) }
|
|
2458
|
+
}
|
|
2459
|
+
const durationMs = Date.now() - startedAt
|
|
2460
|
+
const expectExit = Number.isInteger(entry?.expectExit) ? entry.expectExit : 0
|
|
2461
|
+
const status = run.timedOut === true
|
|
2462
|
+
? 'fail'
|
|
2463
|
+
: run.missing === true
|
|
2464
|
+
? 'missing'
|
|
2465
|
+
: run.exit === expectExit ? 'pass' : 'fail'
|
|
2466
|
+
assertions.push({
|
|
2467
|
+
req,
|
|
2468
|
+
cmd,
|
|
2469
|
+
exit: run.exit ?? null,
|
|
2470
|
+
durationMs,
|
|
2471
|
+
stdoutTail: tailOf(run.output ?? '', tailChars),
|
|
2472
|
+
status,
|
|
2473
|
+
...(run.timedOut === true ? { timeout: true } : {}),
|
|
2474
|
+
...(expectExit === 0 ? {} : { expectExit }),
|
|
2475
|
+
})
|
|
2476
|
+
}
|
|
2477
|
+
const missing = assertions.filter(item => item.status === 'missing')
|
|
2478
|
+
const degrade = missing.length > CHECK_MISSING_BINARY_LIMIT
|
|
2479
|
+
for (const item of assertions) {
|
|
2480
|
+
if (item.status !== 'missing') continue
|
|
2481
|
+
// 环境里没有这条命令:少数几条按 FAIL 记(应该是这次实现要用的工具),
|
|
2482
|
+
// 成片缺失按 unverified 记(更像是这台机器没装)。
|
|
2483
|
+
item.status = degrade ? 'unverified' : 'fail'
|
|
2484
|
+
}
|
|
2485
|
+
return assertions
|
|
2486
|
+
}
|
|
2487
|
+
|
|
2488
|
+
/**
|
|
2489
|
+
* 判据到底有没有启用:至少有一条要求真写了 check。
|
|
2490
|
+
*
|
|
2491
|
+
* 一条都没有的时候走老路——不能因为「第 1 阶没给判据」就把每个项目都判死,
|
|
2492
|
+
* 那等于把流程关了。混着写(有的有 check、有的没有)才算启用,那种情况下
|
|
2493
|
+
* 没 check 的那几条是 unverified,不能跟着一起 PASS。
|
|
2494
|
+
*/
|
|
2495
|
+
export function criteriaInPlay(assertions) {
|
|
2496
|
+
const list = Array.isArray(assertions) ? assertions : []
|
|
2497
|
+
return list.some(item => item.status !== 'unverified')
|
|
2498
|
+
}
|
|
2499
|
+
|
|
2500
|
+
/**
|
|
2501
|
+
* 把 assertions 折成一个判据结论。
|
|
2502
|
+
*
|
|
2503
|
+
* FAIL —— 有命令跑了但没过,或者被白名单拒了。这一轮不许 PASS。
|
|
2504
|
+
* UNVERIFIED —— 有要求压根没有 check。也不许 PASS:判不了不等于判过了。
|
|
2505
|
+
* PASS —— 每条要求都有 check 且都过了。
|
|
2506
|
+
*/
|
|
2507
|
+
export function gateAssertions(assertions, requirementCount) {
|
|
2508
|
+
const list = Array.isArray(assertions) ? assertions : []
|
|
2509
|
+
const failed = list.filter(item => item.status === 'fail' || item.status === 'denied')
|
|
2510
|
+
const unverified = list.filter(item => item.status === 'unverified')
|
|
2511
|
+
const passed = list.filter(item => item.status === 'pass')
|
|
2512
|
+
const covered = new Set(list.map(item => item.req))
|
|
2513
|
+
const total = Number.isInteger(requirementCount) && requirementCount > 0 ? requirementCount : covered.size
|
|
2514
|
+
const uncovered = []
|
|
2515
|
+
for (let index = 1; index <= total; index += 1) if (!covered.has(index)) uncovered.push(index)
|
|
2516
|
+
const verdict = failed.length > 0 ? 'FAIL' : (unverified.length > 0 || uncovered.length > 0) ? 'UNVERIFIED' : 'PASS'
|
|
2517
|
+
return {
|
|
2518
|
+
verdict,
|
|
2519
|
+
failed,
|
|
2520
|
+
unverified,
|
|
2521
|
+
passed,
|
|
2522
|
+
uncovered,
|
|
2523
|
+
total,
|
|
2524
|
+
checked: list.length,
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
|
|
2528
|
+
/** 给质检看的断言摘要:跑过什么、退出码多少、尾巴里写了什么。 */
|
|
2529
|
+
export function describeAssertions(gate) {
|
|
2530
|
+
if (gate === undefined || gate === null) return ''
|
|
2531
|
+
const lines = [
|
|
2532
|
+
'## 插件自己跑过的断言(这部分不是模型判断,是命令的退出码)',
|
|
2533
|
+
'',
|
|
2534
|
+
`结论:${gate.verdict}|共 ${gate.total} 条要求,有判据 ${gate.checked} 条,过 ${gate.passed.length} 条,`
|
|
2535
|
+
+ `未过 ${gate.failed.length} 条,判不了 ${gate.unverified.length + gate.uncovered.length} 条`,
|
|
2536
|
+
]
|
|
2537
|
+
if (gate.checked === 0) {
|
|
2538
|
+
lines.push('', '这次一条 check 都没有:所有要求都是 unverified,按规矩不能算 PASS。')
|
|
2539
|
+
return lines.join('\n')
|
|
2540
|
+
}
|
|
2541
|
+
for (const item of gate.failed) {
|
|
2542
|
+
lines.push('', `- 第 ${item.req} 条:${item.cmd}`, ` 退出码 ${item.exit ?? '?'},用时 ${item.durationMs}ms`)
|
|
2543
|
+
if (item.timeout === true) lines.push(' 超时被收掉(timeout: true)')
|
|
2544
|
+
const tail = String(item.stdoutTail ?? '').trim()
|
|
2545
|
+
if (tail !== '') lines.push(' 输出的尾巴:', ' ```', ...tail.split(/\r?\n/u).slice(-15).map(line => ` ${line}`), ' ```')
|
|
2546
|
+
}
|
|
2547
|
+
for (const item of gate.unverified) {
|
|
2548
|
+
lines.push('', `- 第 ${item.req} 条:没有 check,判不了(unverified)`)
|
|
2549
|
+
}
|
|
2550
|
+
return lines.join('\n')
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2553
|
+
/**
|
|
2554
|
+
* 把 assertions 写成 QA_Report.md 的前置块。
|
|
2555
|
+
*
|
|
2556
|
+
* 正文还是给人看的散文,机器要的这几个字段进前置块:
|
|
2557
|
+
* 报告以后要被第 3 阶、被证据包、被状态栏读,各读各的,别互相猜格式。
|
|
2558
|
+
*/
|
|
2559
|
+
export function renderAssertionsBlock(assertions, meta = {}) {
|
|
2560
|
+
const lines = ['---']
|
|
2561
|
+
if (typeof meta.verdict === 'string' && meta.verdict !== '') lines.push(`verdict: ${quoteScalar(meta.verdict)}`)
|
|
2562
|
+
if (Number.isInteger(meta.round)) lines.push(`round: ${meta.round}`)
|
|
2563
|
+
lines.push(...assertionFrontLines(assertions))
|
|
2564
|
+
lines.push('---')
|
|
2565
|
+
return lines.join('\n')
|
|
2566
|
+
}
|
|
2567
|
+
|
|
2568
|
+
/**
|
|
2569
|
+
* 报告的前置块:verdict / round / issues / assertions 四段。
|
|
2570
|
+
*
|
|
2571
|
+
* issues 放前面是有意的:返工看的是它,质检报告的第一屏就该是待办。
|
|
2572
|
+
* assertions 是命令跑出来的事实,排在后面当证据。
|
|
2573
|
+
*/
|
|
2574
|
+
export function renderQaFrontMatter(meta = {}) {
|
|
2575
|
+
const lines = ['---']
|
|
2576
|
+
if (typeof meta.verdict === 'string' && meta.verdict !== '') lines.push(`verdict: ${quoteScalar(meta.verdict)}`)
|
|
2577
|
+
if (Number.isInteger(meta.round)) lines.push(`round: ${meta.round}`)
|
|
2578
|
+
const issues = Array.isArray(meta.issues) ? meta.issues : []
|
|
2579
|
+
if (issues.length === 0) {
|
|
2580
|
+
lines.push('issues: []')
|
|
2581
|
+
} else {
|
|
2582
|
+
lines.push('issues:')
|
|
2583
|
+
for (const issue of issues) lines.push(...issueLines(issue))
|
|
2584
|
+
}
|
|
2585
|
+
lines.push(...assertionFrontLines(meta.assertions))
|
|
2586
|
+
lines.push('---')
|
|
2587
|
+
return lines.join('\n')
|
|
2588
|
+
}
|
|
2589
|
+
|
|
2590
|
+
/** 断言那一段的 YAML 行,两处写报告共用一个实现。 */
|
|
2591
|
+
function assertionFrontLines(assertions) {
|
|
2592
|
+
const list = Array.isArray(assertions) ? assertions : []
|
|
2593
|
+
if (list.length === 0) return ['assertions: []']
|
|
2594
|
+
const lines = ['assertions:']
|
|
2595
|
+
for (const item of list) {
|
|
2596
|
+
lines.push(` - req: ${Number.isInteger(item.req) ? item.req : 0}`)
|
|
2597
|
+
lines.push(` cmd: ${!item.cmd && item.cmd !== 0 ? "''" : quoteScalar(String(item.cmd))}`)
|
|
2598
|
+
lines.push(` exit: ${typeof item.exit === 'number' ? item.exit : 'null'}`)
|
|
2599
|
+
lines.push(` durationMs: ${Number.isInteger(item.durationMs) ? item.durationMs : 0}`)
|
|
2600
|
+
lines.push(` status: ${item.status ?? 'unknown'}`)
|
|
2601
|
+
if (item.timeout === true) lines.push(' timeout: true')
|
|
2602
|
+
if (item.denied === true) lines.push(' denied: true')
|
|
2603
|
+
const tail = String(item.stdoutTail ?? '')
|
|
2604
|
+
if (tail === '') {
|
|
2605
|
+
lines.push(" stdoutTail: ''")
|
|
2606
|
+
} else {
|
|
2607
|
+
lines.push(' stdoutTail: |')
|
|
2608
|
+
for (const line of tail.split(/\r?\n/u)) lines.push(` ${line}`)
|
|
2609
|
+
}
|
|
2610
|
+
}
|
|
2611
|
+
return lines
|
|
2612
|
+
}
|
|
2613
|
+
|
|
2614
|
+
/**
|
|
2615
|
+
* 从 requirements 生成断言表:一条要求一行,cmd 为空就是「没定义判据」。
|
|
2616
|
+
*
|
|
2617
|
+
* check 可以从两个地方来:
|
|
2618
|
+
* 1. project_run 的 checks 参数(更结构化,req 用 1 起的序号)
|
|
2619
|
+
* 2. 要求文本里自带的一行 `check: ...`(人或后来的模型直接改 Requirement.md)
|
|
2620
|
+
*/
|
|
2621
|
+
export function buildCheckEntries(requirements, checks) {
|
|
2622
|
+
const list = Array.isArray(requirements) ? requirements : []
|
|
2623
|
+
const extra = Array.isArray(checks) ? checks : []
|
|
2624
|
+
return list.map((line, index) => {
|
|
2625
|
+
const text = typeof line === 'string' ? line : String(line ?? '')
|
|
2626
|
+
const inline = /(?:\r?\n|\s*\|\|\s*)\s*check\s*:\s*([\s\S]+)$/u.exec(text)
|
|
2627
|
+
const fromList = extra.find(item => item !== null && typeof item === 'object' && Number(item.req) === index + 1)
|
|
2628
|
+
const listed = fromList !== undefined && typeof fromList.check === 'string' && fromList.check.trim() !== ''
|
|
2629
|
+
? fromList.check.trim()
|
|
2630
|
+
: ''
|
|
2631
|
+
const cmd = listed !== '' ? listed : inline === null ? '' : inline[1].trim()
|
|
2632
|
+
// checks 列表中 exit 等价于 checkExit:两个字段都接收,checkExit 优先,缺省均为 0
|
|
2633
|
+
const rawExit = fromList !== undefined
|
|
2634
|
+
? (Number.isInteger(Number(fromList.checkExit)) ? fromList.checkExit : (Number.isInteger(Number(fromList.exit)) ? fromList.exit : undefined))
|
|
2635
|
+
: undefined
|
|
2636
|
+
const expectExit = Number.isInteger(Number(rawExit)) ? Number(rawExit) : 0
|
|
2637
|
+
return { req: index + 1, cmd, expectExit }
|
|
2638
|
+
})
|
|
2639
|
+
}
|
|
2640
|
+
|
|
2641
|
+
/** 要求正文里那行 `check:` 去掉,正文只留人看的话。 */
|
|
2642
|
+
export function stripInlineCheck(line) {
|
|
2643
|
+
const text = typeof line === 'string' ? line : String(line ?? '')
|
|
2644
|
+
return text.replace(/(?:\r?\n|\s*\|\|\s*)\s*check\s*:\s*[\s\S]+$/u, '').trim()
|
|
2645
|
+
}
|
|
2646
|
+
|
|
2647
|
+
/**
|
|
2648
|
+
* 把当前判据的指纹落盘。
|
|
2649
|
+
*
|
|
2650
|
+
* 只在第 2 阶入口调一次——写在这儿而不是第 4 阶开头,是因为这里才是
|
|
2651
|
+
* 「判据定稿」的那一刻:规划还没跑,实施还没动,任何人都还没机会改它。
|
|
2652
|
+
*/
|
|
2653
|
+
async function saveRequirementFingerprint(cwd, project) {
|
|
2654
|
+
const text = await readArtifact(cwd, project, ARTIFACT.requirement) ?? ''
|
|
2655
|
+
const digest = requirementFingerprint(parseRequirementChecks(text))
|
|
2656
|
+
await saveArtifact(cwd, project, ARTIFACT.requirementHash, digest)
|
|
2657
|
+
return digest
|
|
2658
|
+
}
|
|
2659
|
+
|
|
2660
|
+
/** 读回第 2 阶记下的指纹。没有就是空串:老项目、或者第 2 阶没跑过。 */
|
|
2661
|
+
async function readRequirementFingerprint(cwd, project) {
|
|
2662
|
+
const text = await readArtifact(cwd, project, ARTIFACT.requirementHash)
|
|
2663
|
+
return typeof text === 'string' ? text.trim() : ''
|
|
2664
|
+
}
|
|
2665
|
+
|
|
2666
|
+
// ── 问题级闭环 ──────────────────────────────────────────────────
|
|
2667
|
+
//
|
|
2668
|
+
// 返工的旧判据是「质检判了 FAIL 就再来一轮」。它有两个毛病:一是一条模糊的
|
|
2669
|
+
// FAIL 也能烧掉一整轮,二是第二轮没人记得第一轮那几条到底修了没有——报告
|
|
2670
|
+
// 每轮重写,问题没有身份。
|
|
2671
|
+
//
|
|
2672
|
+
// 这一节给问题发编号:Q-001 一旦发出去,跨轮就是它。返工只看「还有几条没闭环」,
|
|
2673
|
+
// 不看模型那句话是 PASS 还是 FAIL。
|
|
2674
|
+
|
|
2675
|
+
const SEVERITIES = ['P0', 'P1', 'P2']
|
|
2676
|
+
|
|
2677
|
+
/** 一轮最多认真处理这么多条。超出来的先搁着,别让一次报告把返工预算用光。 */
|
|
2678
|
+
const ISSUE_LIMIT = 50
|
|
2679
|
+
|
|
2680
|
+
/** 一处空白差异不该让同一条问题换个身份。 */
|
|
2681
|
+
function normalizeIssueText(value) {
|
|
2682
|
+
return String(value ?? '').replace(/\s+/gu, ' ').trim()
|
|
2683
|
+
}
|
|
2684
|
+
|
|
2685
|
+
/**
|
|
2686
|
+
* 认「同一条问题」用的键:位置 + 说法。
|
|
2687
|
+
*
|
|
2688
|
+
* 不含严重级——模型这轮写 P1、下轮写 P0 是常事,那不该变成两个问题;
|
|
2689
|
+
* 也不含证据和检测方式——那些是随轮次变的描述,不是身份。
|
|
2690
|
+
*/
|
|
2691
|
+
export function issueKeyOf(issue) {
|
|
2692
|
+
const loc = normalizeIssueText(issue?.location).toLowerCase().replace(/^\.\//u, '')
|
|
2693
|
+
const claim = normalizeIssueText(issue?.claim).toLowerCase()
|
|
2694
|
+
.replace(/[,。;:、,.;:!?!?"'“”‘’()()]/gu, '')
|
|
2695
|
+
return `${loc}\u0000${claim}`
|
|
2696
|
+
}
|
|
2697
|
+
|
|
2698
|
+
/** 前端模型交上来的东西可能是任何形状,先规整成固定的八个字段里的六个。 */
|
|
2699
|
+
export function normalizeIncomingIssues(raw) {
|
|
2700
|
+
const list = Array.isArray(raw) ? raw : []
|
|
2701
|
+
const out = []
|
|
2702
|
+
for (const item of list) {
|
|
2703
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) continue
|
|
2704
|
+
const severity = normalizeIssueText(item.severity).toUpperCase()
|
|
2705
|
+
const issue = {
|
|
2706
|
+
severity: SEVERITIES.includes(severity) ? severity : 'P1',
|
|
2707
|
+
location: normalizeIssueText(item.location),
|
|
2708
|
+
claim: normalizeIssueText(item.claim),
|
|
2709
|
+
evidence: normalizeIssueText(item.evidence),
|
|
2710
|
+
detect: normalizeIssueText(item.detect),
|
|
2711
|
+
pass: normalizeIssueText(item.pass),
|
|
2712
|
+
resolved: item.resolved === true,
|
|
2713
|
+
}
|
|
2714
|
+
if (issue.claim === '' && issue.location === '') continue
|
|
2715
|
+
out.push(issue)
|
|
2716
|
+
}
|
|
2717
|
+
return out
|
|
2718
|
+
}
|
|
2719
|
+
|
|
2720
|
+
/**
|
|
2721
|
+
* 从 QA_Report.md 的前置块里把 assertions 读回来。
|
|
2722
|
+
*
|
|
2723
|
+
* 和 parseIssueBlock 一个路子:只认 assertions: 那一段,别的不碰。
|
|
2724
|
+
* 面板要显示「哪条命令挂了、退出码多少」,光一个 fail 计数说不出事。
|
|
2725
|
+
*
|
|
2726
|
+
* stdoutTail 是 `|` 块,可能是好几行,这里不读内容——面板只显示有没有输出、
|
|
2727
|
+
* 失败时给个入口让人去看原文件。把整段 stdout 塞进面板反而没法看。
|
|
2728
|
+
*/
|
|
2729
|
+
export function parseAssertionBlock(text) {
|
|
2730
|
+
const { front } = splitFrontMatter(text)
|
|
2731
|
+
if (front === '') return []
|
|
2732
|
+
const rows = []
|
|
2733
|
+
let inBlock = false
|
|
2734
|
+
let current
|
|
2735
|
+
for (const rawLine of front.split(/\r?\n/u)) {
|
|
2736
|
+
const line = rawLine.replace(/\s+$/u, '')
|
|
2737
|
+
if (/^assertions\s*:\s*(\[\])?\s*$/u.test(line)) {
|
|
2738
|
+
inBlock = true
|
|
2739
|
+
continue
|
|
2740
|
+
}
|
|
2741
|
+
// 顶格的非空行意味着这一段结束了。
|
|
2742
|
+
if (inBlock && /^[A-Za-z_]\w*\s*:/u.test(line)) {
|
|
2743
|
+
inBlock = false
|
|
2744
|
+
current = undefined
|
|
2745
|
+
}
|
|
2746
|
+
if (!inBlock) continue
|
|
2747
|
+
const start = /^\s*-\s*req\s*:\s*(.+)$/u.exec(line)
|
|
2748
|
+
if (start !== null) {
|
|
2749
|
+
const req = Number.parseInt(unquoteScalar(start[1]), 10)
|
|
2750
|
+
current = { req: Number.isInteger(req) ? req : rows.length + 1 }
|
|
2751
|
+
rows.push(current)
|
|
2752
|
+
continue
|
|
2753
|
+
}
|
|
2754
|
+
if (current === undefined) continue
|
|
2755
|
+
const field = /^\s+(cmd|exit|durationMs|status)\s*:\s*(.*)$/u.exec(line)
|
|
2756
|
+
if (field === null) continue
|
|
2757
|
+
const [, key, rawValue] = field
|
|
2758
|
+
const value = unquoteScalar(rawValue)
|
|
2759
|
+
if (key === 'cmd') current.cmd = value
|
|
2760
|
+
else if (key === 'status') current.status = value
|
|
2761
|
+
else {
|
|
2762
|
+
const num = Number.parseInt(value, 10)
|
|
2763
|
+
current[key] = Number.isInteger(num) ? num : null
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
return rows
|
|
2767
|
+
}
|
|
2768
|
+
|
|
2769
|
+
/**
|
|
2770
|
+
* 从 QA_Report.md 的前置块里把 issues 读回来。
|
|
2771
|
+
*
|
|
2772
|
+
* 读回来是为了「上一轮那条」还认得出来:跨轮的 id、closed 不许复活、
|
|
2773
|
+
* 同区段重开,全都建立在这份读得回来的基础上。
|
|
2774
|
+
*/
|
|
2775
|
+
export function parseIssueBlock(text) {
|
|
2776
|
+
const { front } = splitFrontMatter(text)
|
|
2777
|
+
if (front === '') return []
|
|
2778
|
+
const issues = []
|
|
2779
|
+
let inIssues = false
|
|
2780
|
+
let current
|
|
2781
|
+
for (const rawLine of front.split(/\r?\n/u)) {
|
|
2782
|
+
const line = rawLine.replace(/\s+$/u, '')
|
|
2783
|
+
if (/^issues\s*:\s*(\[\])?\s*$/u.test(line)) {
|
|
2784
|
+
inIssues = true
|
|
2785
|
+
continue
|
|
2786
|
+
}
|
|
2787
|
+
if (inIssues && /^[A-Za-z_]\w*\s*:/u.test(line)) {
|
|
2788
|
+
inIssues = false
|
|
2789
|
+
current = undefined
|
|
2790
|
+
}
|
|
2791
|
+
if (!inIssues) continue
|
|
2792
|
+
const start = /^\s*-\s*id\s*:\s*(.*)$/u.exec(line)
|
|
2793
|
+
if (start !== null) {
|
|
2794
|
+
current = { id: unquoteScalar(start[1]) }
|
|
2795
|
+
issues.push(current)
|
|
2796
|
+
continue
|
|
2797
|
+
}
|
|
2798
|
+
if (current === undefined) continue
|
|
2799
|
+
const field = /^\s+(severity|location|claim|evidence|detect|pass|status|note)\s*:\s*(.*)$/u.exec(line)
|
|
2800
|
+
if (field === null) {
|
|
2801
|
+
const rounds = /^\s+rounds\s*:\s*(\d+)\s*$/u.exec(line)
|
|
2802
|
+
if (rounds !== null && current !== undefined) current.roundsOpen = Number(rounds[1])
|
|
2803
|
+
continue
|
|
2804
|
+
}
|
|
2805
|
+
current[field[1]] = unquoteScalar(field[2])
|
|
2806
|
+
}
|
|
2807
|
+
return issues.filter(item => typeof item.id === 'string' && item.id !== '')
|
|
2808
|
+
}
|
|
2809
|
+
|
|
2810
|
+
/** 一条 issue 写成 YAML 行。文字里的换行交给 JSON 转义,读回来还是原文。 */
|
|
2811
|
+
function issueLines(issue) {
|
|
2812
|
+
const lines = [
|
|
2813
|
+
` - id: ${quoteScalar(issue.id)}`,
|
|
2814
|
+
` severity: ${quoteScalar(issue.severity)}`,
|
|
2815
|
+
` location: ${quoteScalar(issue.location)}`,
|
|
2816
|
+
` claim: ${quoteScalar(issue.claim)}`,
|
|
2817
|
+
` evidence: ${quoteScalar(issue.evidence)}`,
|
|
2818
|
+
` detect: ${quoteScalar(issue.detect)}`,
|
|
2819
|
+
` pass: ${quoteScalar(issue.pass)}`,
|
|
2820
|
+
` status: ${quoteScalar(issue.status)}`,
|
|
2821
|
+
]
|
|
2822
|
+
if (typeof issue.note === 'string' && issue.note !== '') lines.push(` note: ${quoteScalar(issue.note)}`)
|
|
2823
|
+
// 连续几轮没闭环。用来触发「别再无脑返工了」的那道闸,
|
|
2824
|
+
// 和 maxRework 不是一回事:maxRework 数的是整轮,这个数的是同一条问题。
|
|
2825
|
+
if (Number.isInteger(issue.roundsOpen) && issue.roundsOpen > 0) lines.push(` rounds: ${issue.roundsOpen}`)
|
|
2826
|
+
return lines
|
|
2827
|
+
}
|
|
2828
|
+
|
|
2829
|
+
/**
|
|
2830
|
+
* 把这一轮的模型意见并进上一轮的台账。
|
|
2831
|
+
*
|
|
2832
|
+
* 规则(每一条都对应一个具体的翻车现场):
|
|
2833
|
+
* - 认得出是同一条 → 沿用原 id,不新发号
|
|
2834
|
+
* - 上一轮 closed 的,模型这轮又提,只有在 diff 真碰了同一文件同一区段时
|
|
2835
|
+
* 才算 reopened;否则忽略——不然「修好的」会被一句模糊重述反复翻案
|
|
2836
|
+
* - 上一轮 open 的,这轮模型没提到 → 保持 open。没提到不等于修好了
|
|
2837
|
+
* - detect / pass 缺一个 → invalid:这条问题没法验,整轮按 FAIL 处理
|
|
2838
|
+
* - 模型明写 resolved: true → closed
|
|
2839
|
+
*/
|
|
2840
|
+
export function mergeIssueRounds(previous, incoming, diffText) {
|
|
2841
|
+
const prev = Array.isArray(previous) ? previous : []
|
|
2842
|
+
const next = Array.isArray(incoming) ? incoming : []
|
|
2843
|
+
let maxIndex = 0
|
|
2844
|
+
for (const item of prev) {
|
|
2845
|
+
const match = /^Q-(\d+)$/u.exec(String(item?.id ?? ''))
|
|
2846
|
+
if (match !== null) maxIndex = Math.max(maxIndex, Number(match[1]))
|
|
2847
|
+
}
|
|
2848
|
+
const byKey = new Map()
|
|
2849
|
+
for (const item of prev) byKey.set(issueKeyOf(item), item)
|
|
2850
|
+
const touched = new Set()
|
|
2851
|
+
const issues = []
|
|
2852
|
+
const reopened = []
|
|
2853
|
+
const invalid = []
|
|
2854
|
+
|
|
2855
|
+
for (const item of next) {
|
|
2856
|
+
const key = issueKeyOf(item)
|
|
2857
|
+
const old = byKey.get(key)
|
|
2858
|
+
const missing = normalizeIssueText(item.detect) === '' || normalizeIssueText(item.pass) === ''
|
|
2859
|
+
if (old !== undefined && touched.has(old.id) !== true) {
|
|
2860
|
+
touched.add(old.id)
|
|
2861
|
+
const sameFile = diffTouches(diffText, item.location)
|
|
2862
|
+
if (old.status === 'closed') {
|
|
2863
|
+
if (item.resolved === true) continue
|
|
2864
|
+
if (sameFile !== true) continue
|
|
2865
|
+
const revived = { ...old, ...item, id: old.id, status: 'reopened', note: '上一轮判 closed,这一轮 diff 又动了同一处' }
|
|
2866
|
+
issues.push(revived)
|
|
2867
|
+
reopened.push(revived)
|
|
2868
|
+
continue
|
|
2869
|
+
}
|
|
2870
|
+
const status = item.resolved === true ? 'closed' : missing ? 'invalid' : 'open'
|
|
2871
|
+
const roundsOpen = status === 'closed' ? 0 : (Number.isInteger(old.roundsOpen) ? old.roundsOpen : 0) + 1
|
|
2872
|
+
const merged = {
|
|
2873
|
+
...old,
|
|
2874
|
+
...item,
|
|
2875
|
+
id: old.id,
|
|
2876
|
+
status,
|
|
2877
|
+
roundsOpen,
|
|
2878
|
+
...(missing ? { note: '缺少 detect 或 pass,验不了' } : {}),
|
|
2879
|
+
}
|
|
2880
|
+
issues.push(merged)
|
|
2881
|
+
if (status === 'invalid') invalid.push(merged)
|
|
2882
|
+
continue
|
|
2883
|
+
}
|
|
2884
|
+
// 新问题:发新号。同一轮里重复描述的,认第一个。
|
|
2885
|
+
if ([...issues, ...prev].some(candidate => issueKeyOf(candidate) === key)) continue
|
|
2886
|
+
maxIndex += 1
|
|
2887
|
+
const id = `Q-${String(maxIndex).padStart(3, '0')}`
|
|
2888
|
+
const status = missing ? 'invalid' : item.resolved === true ? 'closed' : 'open'
|
|
2889
|
+
const created = { ...item, id, status, ...(missing ? { note: '缺少 detect 或 pass,验不了' } : {}) }
|
|
2890
|
+
issues.push(created)
|
|
2891
|
+
if (status === 'invalid') invalid.push(created)
|
|
2892
|
+
}
|
|
2893
|
+
|
|
2894
|
+
// 模型没提到的上轮问题:原样留下。不提到不等于修好,这条是闭环能不能信的关键。
|
|
2895
|
+
for (const item of prev) {
|
|
2896
|
+
if (touched.has(item.id)) continue
|
|
2897
|
+
if (item.status === 'closed') continue
|
|
2898
|
+
issues.push({
|
|
2899
|
+
...item,
|
|
2900
|
+
roundsOpen: (Number.isInteger(item.roundsOpen) ? item.roundsOpen : 0) + 1,
|
|
2901
|
+
})
|
|
2902
|
+
}
|
|
2903
|
+
|
|
2904
|
+
// 条数超限:先保 P0/P1,其余标 deferred,不参与返工判据。
|
|
2905
|
+
const processed = []
|
|
2906
|
+
const deferred = []
|
|
2907
|
+
for (const item of issues) {
|
|
2908
|
+
const counts = item.status === 'open' || item.status === 'reopened' || item.status === 'invalid'
|
|
2909
|
+
if (counts && item.severity === 'P2' && issues.length > ISSUE_LIMIT) {
|
|
2910
|
+
deferred.push({ ...item, status: 'deferred' })
|
|
2911
|
+
continue
|
|
2912
|
+
}
|
|
2913
|
+
processed.push(item)
|
|
2914
|
+
}
|
|
2915
|
+
const finalList = processed.concat(deferred)
|
|
2916
|
+
const open = finalList.filter(item => item.status === 'open' || item.status === 'reopened')
|
|
2917
|
+
// 同一条问题连着三轮没闭环:再多返工也是原地打转,这道闸比 maxRework 更早响。
|
|
2918
|
+
const stuck = open.filter(item => (Number.isInteger(item.roundsOpen) ? item.roundsOpen : 0) >= 3)
|
|
2919
|
+
return {
|
|
2920
|
+
issues: finalList,
|
|
2921
|
+
open,
|
|
2922
|
+
openCount: open.length,
|
|
2923
|
+
openP0P1: open.filter(item => item.severity === 'P0' || item.severity === 'P1').length,
|
|
2924
|
+
reopened,
|
|
2925
|
+
invalid,
|
|
2926
|
+
deferred,
|
|
2927
|
+
stuck,
|
|
2928
|
+
}
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
/** 这一轮的 diff 有没有碰这条问题指的那处。文件对上、行号落在 hunk 里才算。 */
|
|
2932
|
+
export function diffTouches(diffText, location) {
|
|
2933
|
+
const text = typeof diffText === 'string' ? diffText : ''
|
|
2934
|
+
const loc = normalizeIssueText(location)
|
|
2935
|
+
if (text === '' || loc === '') return false
|
|
2936
|
+
const filePart = loc.split(':')[0].trim().replace(/^\.\//u, '').replace(/^[ab]\//u, '')
|
|
2937
|
+
if (filePart === '') return false
|
|
2938
|
+
const lineMatch = /:(\d+)/u.exec(loc)
|
|
2939
|
+
const line = lineMatch === null ? undefined : Number(lineMatch[1])
|
|
2940
|
+
let currentFile = ''
|
|
2941
|
+
let range
|
|
2942
|
+
for (const rawLine of text.split(/\r?\n/u)) {
|
|
2943
|
+
const header = /^\+\+\+ b\/(.+)$/u.exec(rawLine)
|
|
2944
|
+
if (header !== null) {
|
|
2945
|
+
currentFile = header[1].trim()
|
|
2946
|
+
range = undefined
|
|
2947
|
+
continue
|
|
2948
|
+
}
|
|
2949
|
+
const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/u.exec(rawLine)
|
|
2950
|
+
if (hunk !== null) {
|
|
2951
|
+
range = { start: Number(hunk[1]), count: hunk[2] === undefined ? 1 : Number(hunk[2]) }
|
|
2952
|
+
continue
|
|
1624
2953
|
}
|
|
2954
|
+
if (currentFile === '' || range === undefined) continue
|
|
2955
|
+
if (currentFile !== filePart && currentFile.endsWith(`/${filePart}`) !== true) continue
|
|
2956
|
+
if (line === undefined) return true
|
|
2957
|
+
const end = range.start + Math.max(range.count, 1) - 1
|
|
2958
|
+
if (line >= range.start && line <= end) return true
|
|
1625
2959
|
}
|
|
1626
|
-
return
|
|
2960
|
+
return false
|
|
1627
2961
|
}
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
2962
|
+
|
|
2963
|
+
/**
|
|
2964
|
+
* 模型没按 JSON 回、改交了一张表时的兜底。
|
|
2965
|
+
*
|
|
2966
|
+
* 只有表头里明写严重级那一列才认;没有那一列的表格整张跳过。
|
|
2967
|
+
* 早期版本的规则是「第 2 格长得像 P0-P3 就当缺陷」——那不是解析,那是猜。
|
|
2968
|
+
*/
|
|
2969
|
+
export function parseIssueTables(text) {
|
|
2970
|
+
const source = typeof text === 'string' ? text : ''
|
|
2971
|
+
const lines = source.split(/\r?\n/u)
|
|
2972
|
+
const issues = []
|
|
2973
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
2974
|
+
const header = lines[index].trim()
|
|
2975
|
+
if (header.startsWith('|') !== true || /^\|[\s:-]+\|/u.test(header)) continue
|
|
2976
|
+
const cells = header.split('|').map(cell => cell.trim()).filter((cell, at, all) => at > 0 && at < all.length - 1)
|
|
2977
|
+
const severityAt = cells.findIndex(cell => /^(严重级|严重程度|severity|优先级|级别)$/iu.test(cell))
|
|
2978
|
+
if (severityAt === -1) {
|
|
2979
|
+
// 整张跳过:没有声明严重级的表,说什么都不算缺陷清单。
|
|
2980
|
+
while (index < lines.length && lines[index].trim().startsWith('|')) index += 1
|
|
2981
|
+
continue
|
|
2982
|
+
}
|
|
2983
|
+
const pick = names => cells.findIndex(cell => names.some(name => new RegExp(name, 'iu').test(cell)))
|
|
2984
|
+
const locationAt = pick(['位置', 'location', '文件'])
|
|
2985
|
+
const claimAt = pick(['问题', 'claim', '描述', '缺陷'])
|
|
2986
|
+
const evidenceAt = pick(['证据', 'evidence'])
|
|
2987
|
+
const detectAt = pick(['检测', 'detect', '复现', '怎么验'])
|
|
2988
|
+
const passAt = pick(['通过', 'pass', '验收', '标准'])
|
|
2989
|
+
let row = index + 1
|
|
2990
|
+
if (row < lines.length && /^\|[\s:|-]+\|$/u.test(lines[row].trim())) row += 1
|
|
2991
|
+
for (; row < lines.length; row += 1) {
|
|
2992
|
+
const line = lines[row].trim()
|
|
2993
|
+
if (line.startsWith('|') !== true) break
|
|
2994
|
+
const cellsOfRow = line.split('|').map(cell => cell.trim()).filter((cell, at, all) => at > 0 && at < all.length - 1)
|
|
2995
|
+
const severity = (cellsOfRow[severityAt] ?? '').toUpperCase()
|
|
2996
|
+
if (SEVERITIES.includes(severity) !== true) continue
|
|
2997
|
+
issues.push({
|
|
2998
|
+
severity,
|
|
2999
|
+
location: locationAt === -1 ? '' : cellsOfRow[locationAt] ?? '',
|
|
3000
|
+
claim: claimAt === -1 ? '' : cellsOfRow[claimAt] ?? '',
|
|
3001
|
+
evidence: evidenceAt === -1 ? '' : cellsOfRow[evidenceAt] ?? '',
|
|
3002
|
+
detect: detectAt === -1 ? '' : cellsOfRow[detectAt] ?? '',
|
|
3003
|
+
pass: passAt === -1 ? '' : cellsOfRow[passAt] ?? '',
|
|
3004
|
+
})
|
|
3005
|
+
}
|
|
3006
|
+
index = row - 1
|
|
3007
|
+
}
|
|
3008
|
+
return issues
|
|
3009
|
+
}
|
|
3010
|
+
|
|
3011
|
+
/** 实施段交上来的修复清单,写成 Execution_Log.md 里那一节。 */
|
|
3012
|
+
export function renderFixLog(fixes, round) {
|
|
3013
|
+
const list = Array.isArray(fixes) ? fixes : []
|
|
3014
|
+
if (list.length === 0) return ''
|
|
3015
|
+
const lines = [`## 本轮修复(R${round})`, '']
|
|
3016
|
+
for (const item of list) {
|
|
3017
|
+
const id = normalizeIssueText(item?.id) || 'Q-???'
|
|
3018
|
+
const change = normalizeIssueText(item?.change) || '(没写改了什么)'
|
|
3019
|
+
const command = normalizeIssueText(item?.command)
|
|
3020
|
+
const result = normalizeIssueText(item?.result)
|
|
3021
|
+
lines.push(`- ${id} → ${change}${command === '' ? '' : ` → \`${command}\``} → ${result === '' ? '(没写结果)' : result}`)
|
|
3022
|
+
}
|
|
3023
|
+
return lines.join('\n')
|
|
3024
|
+
}
|
|
3025
|
+
|
|
3026
|
+
/** 给质检看的上一轮台账:让它逐条回答修没修,而不是重新写一份新的。 */
|
|
3027
|
+
export function renderKnownIssues(issues) {
|
|
3028
|
+
const list = Array.isArray(issues) ? issues : []
|
|
3029
|
+
const open = list.filter(item => item.status === 'open' || item.status === 'reopened')
|
|
3030
|
+
if (open.length === 0) return ''
|
|
3031
|
+
const lines = [
|
|
3032
|
+
'## 上一轮还没闭环的问题(逐条回答,别重新编号)',
|
|
3033
|
+
'',
|
|
3034
|
+
]
|
|
3035
|
+
for (const item of open) {
|
|
3036
|
+
lines.push(`- ${item.id}|${item.severity}|${item.location || '(没写位置)'}|${item.claim}`)
|
|
3037
|
+
if (item.pass !== '') lines.push(` 通过标准:${item.pass}`)
|
|
3038
|
+
if (item.detect !== '') lines.push(` 检测方式:${item.detect}`)
|
|
1633
3039
|
}
|
|
3040
|
+
lines.push('', '修好了就在这一轮的 issues 里带上同一个 id 并写 "resolved": true;没修就照原样再列一遍。')
|
|
3041
|
+
return lines.join('\n')
|
|
1634
3042
|
}
|
|
1635
3043
|
|
|
1636
3044
|
/** Every project under `.project-flow` as a status line, sorted by name. */
|
|
@@ -2070,10 +3478,16 @@ ${rework ? `这次是返工。上一轮质检判了 FAIL,意见在 ${ARTIFACT.
|
|
|
2070
3478
|
{
|
|
2071
3479
|
"summary": "你实际做了什么,逐条对应任务书",
|
|
2072
3480
|
"files": ["改动的文件路径"],
|
|
3481
|
+
"fixes": [
|
|
3482
|
+
{ "id": "Q-002", "change": "改了什么", "command": "你为这一条跑过的验证命令", "result": "通过 / 还是没过" }
|
|
3483
|
+
],
|
|
2073
3484
|
"deviations": ["与任务书不一致的地方;没有就空数组"],
|
|
2074
3485
|
"unresolved": ["没做完或做不到的;没有就空数组"]
|
|
2075
3486
|
}
|
|
2076
3487
|
\`\`\`
|
|
3488
|
+
|
|
3489
|
+
\`fixes\` 只在返工时写:一条对应 ${ARTIFACT.qa} 里的一个编号,每行只说「改了什么、跑了哪条命令、结果如何」,
|
|
3490
|
+
不要写散文,也不要漏——漏掉的那条下一轮还是 open。
|
|
2077
3491
|
`
|
|
2078
3492
|
|
|
2079
3493
|
/** 载体 id → 中文名,给采集环节的 prompt 用。认不出来的 id 原样带出。 */
|
|
@@ -2150,12 +3564,35 @@ diff 里改了、任务书里没要求的,算做多了。diff 拿不到的时
|
|
|
2150
3564
|
输出必须是一个 JSON 代码块,verdict 只允许 PASS 或 FAIL 两个值:
|
|
2151
3565
|
\`\`\`json
|
|
2152
3566
|
{
|
|
2153
|
-
"verdict": "
|
|
3567
|
+
"verdict": "FAIL",
|
|
3568
|
+
"issues": [
|
|
3569
|
+
{
|
|
3570
|
+
"severity": "P1",
|
|
3571
|
+
"location": "src/a.ts:12",
|
|
3572
|
+
"claim": "空数组会走到 reduce 里抛 TypeError",
|
|
3573
|
+
"evidence": "diff 第 12 行直接 reduce,没有 length 判断",
|
|
3574
|
+
"detect": "node -e \\"const f=require('./src/a'); f([])\\"",
|
|
3575
|
+
"pass": "f([]) 返回 [] 而不是抛错",
|
|
3576
|
+
"resolved": false
|
|
3577
|
+
}
|
|
3578
|
+
],
|
|
2154
3579
|
"reasons": ["判 PASS 时写你核过哪几条;判 FAIL 时写具体哪里不达标,最多 5 条,每条要能被下一轮照着改"],
|
|
2155
3580
|
"acceptable_risks": ["判 PASS 时列你知道但没有解决、且判断可以接受的风险;没有就空数组"]
|
|
2156
3581
|
}
|
|
2157
3582
|
\`\`\`
|
|
2158
3583
|
|
|
3584
|
+
## 问题清单的三条硬规矩
|
|
3585
|
+
|
|
3586
|
+
1. **每条都要有 \`detect\` 和 \`pass\`。** \`detect\` 是一条能跑的命令、或者一步能照着做的检查;
|
|
3587
|
+
\`pass\` 是「做到什么算过」。缺一个,这条问题就不成立,整轮按「问题缺少可执行定义」判 FAIL
|
|
3588
|
+
——没有验法的意见,下一轮改不改都说不清。
|
|
3589
|
+
2. **\`severity\` 只认 \`P0\` \`P1\` \`P2\`。** P0 = 交不了,P1 = 明显不对,P2 = 可以留到以后。
|
|
3590
|
+
3. **上一轮的问题要给答复。** 见了 id 就在同一份 issues 里带上那个 id:修好了写 \`"resolved": true\`,
|
|
3591
|
+
没修就照原样再列一遍(可以不重复描述)。不要换个说法另开一条——那会变成两个问题。
|
|
3592
|
+
|
|
3593
|
+
要交表格也行,但表头必须有「严重级」这一列(位置 / 问题 / 证据 / 检测 / 通过标准 也按这个顺序列)。
|
|
3594
|
+
没有严重级那一列的表会被整张跳过,等于没写。
|
|
3595
|
+
|
|
2159
3596
|
\`acceptable_risks\` 是给验收报告用的:这些风险会被原样写进完成证据包,
|
|
2160
3597
|
所以每条都要写成人能看懂的一句话——「没做并发测试,单机场景够用」这种,
|
|
2161
3598
|
不要写「可能存在风险」这种谁都能说的话。
|
|
@@ -2165,7 +3602,7 @@ diff 里改了、任务书里没要求的,算做多了。diff 拿不到的时
|
|
|
2165
3602
|
|
|
2166
3603
|
不要写建议、不要写评价、不要写「基本通过」。只有 PASS 和 FAIL 两个词。`
|
|
2167
3604
|
|
|
2168
|
-
const QA_PROMPT = (requirement, plan, log, diff) => {
|
|
3605
|
+
const QA_PROMPT = (requirement, plan, log, diff, known = '') => {
|
|
2169
3606
|
|
|
2170
3607
|
const diffSection = diff?.ok === true
|
|
2171
3608
|
? (diff.text.trim() === ''
|
|
@@ -2191,7 +3628,7 @@ ${log}
|
|
|
2191
3628
|
## 改动(从快照仓库两端算出来的 git diff)
|
|
2192
3629
|
|
|
2193
3630
|
${diffSection}
|
|
2194
|
-
`
|
|
3631
|
+
${known === '' ? '' : `\n${known}\n`}`
|
|
2195
3632
|
}
|
|
2196
3633
|
|
|
2197
3634
|
/**
|
|
@@ -2616,6 +4053,57 @@ async function watchRootOf(cwd, settings) {
|
|
|
2616
4053
|
* 客户端自己也能从 .project-flow 里读,但这个函数让模型和命令也能问
|
|
2617
4054
|
* 「现在什么状态」,两边口径一致。
|
|
2618
4055
|
*/
|
|
4056
|
+
/**
|
|
4057
|
+
* 面板要的那一小份报告摘要。
|
|
4058
|
+
*
|
|
4059
|
+
* 不返回全文:面板一屏放不下,QA_Report.md 本身是给人读的散文。
|
|
4060
|
+
* 只留三样——还开着的问题、断言的分类计数、挂掉的那几条命令。
|
|
4061
|
+
*
|
|
4062
|
+
* 读不到就返回空结构,不报错:没跑过质检的项目本来就没有这份报告。
|
|
4063
|
+
*/
|
|
4064
|
+
async function panelReportOf(watch, name) {
|
|
4065
|
+
let text
|
|
4066
|
+
try {
|
|
4067
|
+
text = await readArtifact(watch, name, ARTIFACT.qa)
|
|
4068
|
+
} catch {
|
|
4069
|
+
text = undefined
|
|
4070
|
+
}
|
|
4071
|
+
const empty = { issues: [], assertions: { total: 0, pass: 0, fail: 0, unverified: 0 }, failed: [] }
|
|
4072
|
+
if (typeof text !== 'string' || text.trim() === '') return empty
|
|
4073
|
+
|
|
4074
|
+
const all = parseIssueBlock(text)
|
|
4075
|
+
const assertions = parseAssertionBlock(text)
|
|
4076
|
+
const count = status => assertions.filter(item => item.status === status).length
|
|
4077
|
+
return {
|
|
4078
|
+
issues: all
|
|
4079
|
+
.filter(item => item.status === 'open' || item.status === 'reopened')
|
|
4080
|
+
.map(item => ({
|
|
4081
|
+
id: typeof item.id === 'string' ? item.id : '',
|
|
4082
|
+
severity: typeof item.severity === 'string' ? item.severity : '',
|
|
4083
|
+
location: typeof item.location === 'string' ? item.location.slice(0, 120) : '',
|
|
4084
|
+
claim: typeof item.claim === 'string' ? item.claim.slice(0, 160) : '',
|
|
4085
|
+
detect: typeof item.detect === 'string' ? item.detect.slice(0, 160) : '',
|
|
4086
|
+
status: item.status,
|
|
4087
|
+
})),
|
|
4088
|
+
assertions: {
|
|
4089
|
+
total: assertions.length,
|
|
4090
|
+
pass: count('pass'),
|
|
4091
|
+
fail: count('fail'),
|
|
4092
|
+
unverified: count('unverified'),
|
|
4093
|
+
},
|
|
4094
|
+
// 挂掉的命令单独拎出来。面板上要显示「哪一条、退出码多少」——
|
|
4095
|
+
// 只说「失败 1 条」等于让人再去翻文件。
|
|
4096
|
+
failed: assertions
|
|
4097
|
+
.filter(item => item.status === 'fail' || item.status === 'timeout' || item.status === 'denied')
|
|
4098
|
+
.map(item => ({
|
|
4099
|
+
req: item.req,
|
|
4100
|
+
cmd: typeof item.cmd === 'string' ? item.cmd.slice(0, 160) : '',
|
|
4101
|
+
exit: Number.isInteger(item.exit) ? item.exit : null,
|
|
4102
|
+
status: item.status,
|
|
4103
|
+
})),
|
|
4104
|
+
}
|
|
4105
|
+
}
|
|
4106
|
+
|
|
2619
4107
|
export async function panelSnapshot(cwd, settings, onlyProject, sessionId) {
|
|
2620
4108
|
const watch = await watchRootOf(cwd, settings)
|
|
2621
4109
|
const inside = insideFlow(cwd, settings)
|
|
@@ -2647,6 +4135,9 @@ export async function panelSnapshot(cwd, settings, onlyProject, sessionId) {
|
|
|
2647
4135
|
status: typeof state.status === 'string' ? state.status : '',
|
|
2648
4136
|
rework: typeof state.rework === 'number' ? state.rework : 0,
|
|
2649
4137
|
maxRework: typeof state.maxRework === 'number' ? state.maxRework : settings.maxRework,
|
|
4138
|
+
// 未闭环问题数(P0+P1 的 open+reopened 数):阶段灯旁那个 open: N。
|
|
4139
|
+
// 它和 rework 是两件事——一个是「还剩几件事」,一个是「花了几轮」。
|
|
4140
|
+
open: typeof state.openCritical === 'number' ? state.openCritical : (typeof state.openIssues === 'number' ? state.openIssues : 0),
|
|
2650
4141
|
running: runningEntry !== undefined,
|
|
2651
4142
|
/**
|
|
2652
4143
|
* 这个项目是不是「你这个会话」开的。
|
|
@@ -2658,6 +4149,21 @@ export async function panelSnapshot(cwd, settings, onlyProject, sessionId) {
|
|
|
2658
4149
|
mine: runningEntry !== undefined
|
|
2659
4150
|
&& sessionId !== undefined
|
|
2660
4151
|
&& runningEntry.sessionId === sessionId,
|
|
4152
|
+
/**
|
|
4153
|
+
* 这个项目是不是「你这个对话」碰过的——跑完之后也算。
|
|
4154
|
+
*
|
|
4155
|
+
* mine 只覆盖「正在跑」,跑完就假了;状态栏靠这一条才能一个对话一个,
|
|
4156
|
+
* 而不是所有对话都退回显示同一个项目。
|
|
4157
|
+
*
|
|
4158
|
+
* 三种值,缺一不可:
|
|
4159
|
+
* true 归我
|
|
4160
|
+
* false 不归我(这个项目有归属记录,但里面没有我这个会话)
|
|
4161
|
+
* null 未知归属——升级之前跑的老项目没有 ownerSessions,
|
|
4162
|
+
* 不能judge成「不是我的」,否则升级当天所有老项目一起消失
|
|
4163
|
+
*/
|
|
4164
|
+
owned: sessionId !== undefined && Array.isArray(state.ownerSessions)
|
|
4165
|
+
? state.ownerSessions.includes(sessionId)
|
|
4166
|
+
: null,
|
|
2661
4167
|
// 已花掉的钱:每阶结束都会落盘,状态栏直接读,不用再算
|
|
2662
4168
|
cost: state.cost === undefined ? undefined : {
|
|
2663
4169
|
cny: state.cost.spentCny,
|
|
@@ -2665,10 +4171,20 @@ export async function panelSnapshot(cwd, settings, onlyProject, sessionId) {
|
|
|
2665
4171
|
},
|
|
2666
4172
|
interruptedAt: state.interruptedAt ?? null,
|
|
2667
4173
|
updatedAt: state.updatedAt ?? null,
|
|
4174
|
+
// 开工时间。面板要显示「这一轮跑了多久」——只有 updatedAt 算不出时长,
|
|
4175
|
+
// 而 state 里本来就有这一项,不用另存。
|
|
4176
|
+
startedAt: state.startedAt ?? null,
|
|
2668
4177
|
verdict: typeof state.verdict === 'string' ? state.verdict : '',
|
|
4178
|
+
// 面板要能看到「还差哪几条」「哪条命令没过」。光有一个 open 数字
|
|
4179
|
+
// 说不出事,用户还得去翻 QA_Report.md——那正是这个面板想省掉的一步。
|
|
4180
|
+
//
|
|
4181
|
+
// 读不到就返回空数组,不报错:没跑过质检的项目本来就没有这份报告。
|
|
4182
|
+
report: await panelReportOf(watch, name),
|
|
2669
4183
|
})
|
|
2670
4184
|
}
|
|
2671
4185
|
const snapshot = {
|
|
4186
|
+
// 面板顶栏那一行要显示插件版本。宿主自己读 package.json,不靠客户端猜。
|
|
4187
|
+
version: PKG_VERSION,
|
|
2672
4188
|
// 算出来的时间。客户端靠它判断这份是不是自己刚触发的那一次——
|
|
2673
4189
|
// 缓存是全进程共用的,不校验时间就会读到别的栏(工作流/默认工作区)的数据。
|
|
2674
4190
|
at: nowIso(),
|
|
@@ -2788,6 +4304,10 @@ export function apply(ctx, config) {
|
|
|
2788
4304
|
testCommand: config.testCommand ?? 'auto',
|
|
2789
4305
|
testTimeoutMs: config.testTimeoutMs ?? 600000,
|
|
2790
4306
|
cnyRate: config.cnyRate ?? 7,
|
|
4307
|
+
// 断言执行器:白名单、单条超时、输出留尾的长度。
|
|
4308
|
+
checkAllowedCommands: config.checkAllowedCommands ?? '',
|
|
4309
|
+
checkTimeoutMs: config.checkTimeoutMs ?? 120000,
|
|
4310
|
+
checkStdoutTailChars: config.checkStdoutTailChars ?? 8000,
|
|
2791
4311
|
}
|
|
2792
4312
|
|
|
2793
4313
|
const overridePaths = () => {
|
|
@@ -2932,12 +4452,36 @@ function splitRoute(value) {
|
|
|
2932
4452
|
type: 'array',
|
|
2933
4453
|
required: true,
|
|
2934
4454
|
items: { type: 'string' },
|
|
2935
|
-
description: '
|
|
4455
|
+
description: '用户的要求,一条一行,要能逐条核对。质检环节会照着这些逐项验。要带断言就在这一条里加一行 `check: <命令>`,或者改用 checks 参数。',
|
|
4456
|
+
},
|
|
4457
|
+
checks: {
|
|
4458
|
+
type: 'array',
|
|
4459
|
+
items: {
|
|
4460
|
+
type: 'object',
|
|
4461
|
+
additionalProperties: false,
|
|
4462
|
+
required: ['req', 'check'],
|
|
4463
|
+
properties: {
|
|
4464
|
+
req: { type: 'integer', description: 'requirements 里第几条,1 起。' },
|
|
4465
|
+
check: { type: 'string', description: '一条命令,退出码等于 checkExit(默认 0)才算过。' },
|
|
4466
|
+
checkExit: { type: 'integer', description: '期望退出码,默认 0。' },
|
|
4467
|
+
},
|
|
4468
|
+
},
|
|
4469
|
+
description: '每条要求的可执行判据:写进 Requirement.md 的前置块,第 4 阶由插件自己跑,不看模型怎么说。',
|
|
2936
4470
|
},
|
|
2937
4471
|
constraints: {
|
|
2938
4472
|
type: 'string',
|
|
2939
4473
|
description: '边界:不能碰的文件、不要用的技术、预算或风格限制。',
|
|
2940
4474
|
},
|
|
4475
|
+
forbidden: {
|
|
4476
|
+
type: 'array',
|
|
4477
|
+
items: { type: 'string' },
|
|
4478
|
+
description: '不许碰的路径(目录或文件,相对绝对都行)。实施段跑完会拿它比对台账,碰到就判 FAIL 并要求回滚。',
|
|
4479
|
+
},
|
|
4480
|
+
doneWhen: {
|
|
4481
|
+
type: 'array',
|
|
4482
|
+
items: { type: 'string' },
|
|
4483
|
+
description: '算做完的判据,一句话一条。和 requirements 一起写进 contract.json,每一阶都会重贴。',
|
|
4484
|
+
},
|
|
2941
4485
|
intentConfidence: {
|
|
2942
4486
|
type: 'integer',
|
|
2943
4487
|
required: true,
|
|
@@ -3047,12 +4591,17 @@ function splitRoute(value) {
|
|
|
3047
4591
|
// 但**配了绝对 flowRoot 就不许挪**:那代表用户明确表态「只在那儿用」。
|
|
3048
4592
|
// 擅自把活挪过去,会在用户工程目录旁边另起一个 .project-flow,
|
|
3049
4593
|
// 项目就散了——用户的原话是「默认工作区里不可以跑工作流」。
|
|
4594
|
+
let createError
|
|
4595
|
+
let createAttempt
|
|
3050
4596
|
if (!flowRootConfigured(settings)
|
|
3051
4597
|
&& settings.autoCreateFlowDir === true
|
|
3052
4598
|
&& flowModeOf(settings) === 'strict'
|
|
3053
4599
|
&& !insideFlow(cwd, settings)) {
|
|
3054
4600
|
const ensured = await ensureFlowRoot(cwd, settings)
|
|
3055
4601
|
if (ensured.created === true) cwd = ensured.root
|
|
4602
|
+
// 建不出来要留话:后面那句拒绝只说「不在工作流目录里」,看不出是权限问题。
|
|
4603
|
+
createError = ensured.error
|
|
4604
|
+
createAttempt = ensured.attempted
|
|
3056
4605
|
}
|
|
3057
4606
|
// 在这儿开过工就记下来:下次在别的目录打开会话,状态栏照样知道该看哪儿。
|
|
3058
4607
|
// 不记的话,人一换目录,那边就只剩一句「未启用」——正是用户报的那个问题。
|
|
@@ -3068,7 +4617,7 @@ function splitRoute(value) {
|
|
|
3068
4617
|
verdict: `不在「${FLOW_DIR_NAME}」目录里`,
|
|
3069
4618
|
issues: [],
|
|
3070
4619
|
artifacts: stateDir(cwd, args.project),
|
|
3071
|
-
note: flowGateMessage(cwd, settings),
|
|
4620
|
+
note: flowGateMessage(cwd, settings) + (createError === undefined ? '' : `\n\n工作流目录本来该自动建出来的,但建失败了:${createAttempt}\n${createError}\n换个能写的盘,或者把 flowRoot 配成你确定有权限的绝对路径。`),
|
|
3072
4621
|
}
|
|
3073
4622
|
}
|
|
3074
4623
|
// 门控过了就记下来:下次在同一个目录开工,五格能直接沿用,不用再问用户一遍。
|
|
@@ -3102,7 +4651,10 @@ function splitRoute(value) {
|
|
|
3102
4651
|
project: args.project,
|
|
3103
4652
|
intent: args.intent,
|
|
3104
4653
|
requirements: args.requirements,
|
|
4654
|
+
checks: args.checks,
|
|
3105
4655
|
constraints: args.constraints ?? '',
|
|
4656
|
+
forbidden: args.forbidden,
|
|
4657
|
+
doneWhen: args.doneWhen,
|
|
3106
4658
|
confirmation,
|
|
3107
4659
|
maxRework: args.maxRework ?? settings.maxRework,
|
|
3108
4660
|
parent,
|
|
@@ -3290,6 +4842,46 @@ function splitRoute(value) {
|
|
|
3290
4842
|
// here, so one check covers them all.
|
|
3291
4843
|
assertProjectName(project)
|
|
3292
4844
|
const settings = settingsOf()
|
|
4845
|
+
// 契约落盘:要求 + 不许碰 + 算做完。
|
|
4846
|
+
//
|
|
4847
|
+
// 每一阶的 prompt 都会把这份重贴一遍,所以上下文压缩带走的东西它带不走。
|
|
4848
|
+
// 只写一次、每轮复用,不在这里覆盖用户的既定约定——resume 时 options 里
|
|
4849
|
+
// 没有 requirements,那就读回原来那份继续用。
|
|
4850
|
+
const contractBefore = await readContract(cwd, project)
|
|
4851
|
+
let contract = contractBefore
|
|
4852
|
+
if (Array.isArray(options.requirements) && options.requirements.length > 0) {
|
|
4853
|
+
contract = await writeContract(cwd, project, {
|
|
4854
|
+
requirements: options.requirements,
|
|
4855
|
+
forbidden: options.forbidden,
|
|
4856
|
+
doneWhen: options.doneWhen,
|
|
4857
|
+
})
|
|
4858
|
+
// 契约换了要说一声:判据被换过而没人提,比判据写错更糟。
|
|
4859
|
+
if (contractBefore !== undefined && contractBefore.sha !== contract.sha) {
|
|
4860
|
+
await logLine(
|
|
4861
|
+
cwd,
|
|
4862
|
+
project,
|
|
4863
|
+
`契约变了(${String(contractBefore.sha ?? '').slice(0, 8)} → ${contract.sha.slice(0, 8)}),这一轮按新的算`,
|
|
4864
|
+
)
|
|
4865
|
+
}
|
|
4866
|
+
}
|
|
4867
|
+
// flow.yaml 写错了就别开跑:跑到一半才发现配置不对,钱已经花出去了。
|
|
4868
|
+
// 没有 flow.yaml 时 configured=false,这一段整段跳过,行为和 0.8.x 逐条一致。
|
|
4869
|
+
const flowResolution = await resolveFlow(cwd, project)
|
|
4870
|
+
if (flowResolution.configured) {
|
|
4871
|
+
if (flowResolution.errors.length > 0) {
|
|
4872
|
+
throw new Error(`项目 ${project} 的 flow.yaml 有问题,先改好再跑:\n${describeFlowProblems(flowResolution)}`)
|
|
4873
|
+
}
|
|
4874
|
+
// 执行器的顺序语义是「按位置认」:第 1 个=需求、第 2 个=规划、第 3 个=
|
|
4875
|
+
// 实施、最后 1 个=质检,中间那些是插在实施和质检之间的额外阶段。
|
|
4876
|
+
// 少于四个就没法凑出这四件事,直接拒。
|
|
4877
|
+
if (flowResolution.flow.phases.length < 4) {
|
|
4878
|
+
throw new Error(
|
|
4879
|
+
`项目 ${project} 的 flow.yaml 只有 ${flowResolution.flow.phases.length} 个环节,至少要四个:`
|
|
4880
|
+
+ '需求、规划、实施、质检。顺序按位置认,中间多出来的会插在实施和质检之间跑。',
|
|
4881
|
+
)
|
|
4882
|
+
}
|
|
4883
|
+
}
|
|
4884
|
+
const activeFlow = flowResolution.flow
|
|
3293
4885
|
// 顺手把模型配置落一份给状态栏:它只读文件,不调命令
|
|
3294
4886
|
void writePanelFile(cwd, settings)
|
|
3295
4887
|
// 状态栏的停止按钮要有东西可停。这一轮自己的开关,和外面传进来的信号合成一份,
|
|
@@ -3302,6 +4894,26 @@ function splitRoute(value) {
|
|
|
3302
4894
|
controller: stop,
|
|
3303
4895
|
sessionId: options.parent?.id ?? options.parent?.session?.id,
|
|
3304
4896
|
})
|
|
4897
|
+
|
|
4898
|
+
// 记下「这个项目被哪些会话碰过」,落盘。
|
|
4899
|
+
//
|
|
4900
|
+
// 上面那个 panelStops 只在本轮运行期间有效——跑完就清掉,于是 mine 变假,
|
|
4901
|
+
// 状态栏退回「全表第一个项目」,所有对话看到的都是同一个。用户说的
|
|
4902
|
+
// 「所有工作区对话共用一条状态栏」就是这条退路造成的。
|
|
4903
|
+
// 落盘之后,跑完、重启、隔天回来都还认得出来。
|
|
4904
|
+
//
|
|
4905
|
+
// 存数组不是单个值:A 对话开的项目,B 对话可以接着 resume,两边都该看得见。
|
|
4906
|
+
// 只留最近 8 个,防止长年累月越攒越长。
|
|
4907
|
+
const panelSessionId = options.parent?.id ?? options.parent?.session?.id
|
|
4908
|
+
if (typeof panelSessionId === 'string' && panelSessionId !== '') {
|
|
4909
|
+
const before = await readState(cwd, project)
|
|
4910
|
+
const owners = Array.isArray(before?.ownerSessions)
|
|
4911
|
+
? before.ownerSessions.filter(item => typeof item === 'string' && item !== '')
|
|
4912
|
+
: []
|
|
4913
|
+
if (!owners.includes(panelSessionId)) {
|
|
4914
|
+
await writeState(cwd, project, { ownerSessions: [...owners, panelSessionId].slice(-8) })
|
|
4915
|
+
}
|
|
4916
|
+
}
|
|
3305
4917
|
const signal = mergeSignals(options.signal, stop.signal)
|
|
3306
4918
|
const claim = await acquireLock(cwd, project, settings)
|
|
3307
4919
|
if (claim.ok !== true) {
|
|
@@ -3453,7 +5065,7 @@ function splitRoute(value) {
|
|
|
3453
5065
|
* count, and says which stage to start from.
|
|
3454
5066
|
*/
|
|
3455
5067
|
const runPipeline = async options => {
|
|
3456
|
-
const { cwd, project, intent, requirements, constraints, confirmation, maxRework, parent, signal, seed, settings, healed, mode, watchdog } = options
|
|
5068
|
+
const { cwd, project, intent, requirements, checks, constraints, confirmation, maxRework, parent, signal, seed, settings, healed, mode, watchdog } = options
|
|
3457
5069
|
const artifacts = stateDir(cwd, project)
|
|
3458
5070
|
const routeNotes = []
|
|
3459
5071
|
const noteRoute = note => {
|
|
@@ -3725,11 +5337,20 @@ function splitRoute(value) {
|
|
|
3725
5337
|
// 意图确认那段弄丢,第 4 阶质检就没得核了。所以只有真开跑(有 confirmation)
|
|
3726
5338
|
// 或者文件根本不在的时候才写。
|
|
3727
5339
|
if (confirmation !== undefined || existingRequirement === undefined || existingRequirement.trim() === '') {
|
|
3728
|
-
|
|
5340
|
+
// 判据(check)和陈旧的散文一样,是这一阶写的,不是第 2 阶现编的:
|
|
5341
|
+
// 它进 Requirement.md 的前置块,从这里开始就是「用户的判据」,
|
|
5342
|
+
// 后面谁改它,第 4 阶的指纹都会认出来。
|
|
5343
|
+
const checkEntries = buildCheckEntries(requirements, checks)
|
|
5344
|
+
const front = renderRequirementChecks(checkEntries)
|
|
5345
|
+
const body = ticketBlock(
|
|
3729
5346
|
'需求',
|
|
3730
|
-
`${intent}\n\n## 用户要求\n\n${requirements.map((line, index) => `${index + 1}. ${line}`).join('\n')}${convergence}`,
|
|
3731
|
-
)
|
|
5347
|
+
`${intent}\n\n## 用户要求\n\n${requirements.map((line, index) => `${index + 1}. ${stripInlineCheck(line)}`).join('\n')}${convergence}`,
|
|
5348
|
+
)
|
|
5349
|
+
await saveArtifact(cwd, project, ARTIFACT.requirement, front === '' ? body : `${front}\n\n${body}`)
|
|
3732
5350
|
}
|
|
5351
|
+
// 指纹每次进第 2 阶都落一份(包括续跑):旧项目没有这个文件的时候,
|
|
5352
|
+
// 第 4 阶不能因为「没有基线」就跳过比对——那样等于谁都能事后补一条 check。
|
|
5353
|
+
await saveRequirementFingerprint(cwd, project)
|
|
3733
5354
|
await writeState(cwd, project, { stage: 2, status: 'planning' })
|
|
3734
5355
|
// ── 审美采集:去网上找骨架,攒进库 ──────────────────
|
|
3735
5356
|
//
|
|
@@ -3785,13 +5406,21 @@ function splitRoute(value) {
|
|
|
3785
5406
|
// 规划不再从内存拿 intent 变量,而是读刚落的 Requirement.md——
|
|
3786
5407
|
// 这样它和用户之间就只剩这一个文件。
|
|
3787
5408
|
const requirementText = await readArtifact(cwd, project, ARTIFACT.requirement)
|
|
3788
|
-
|
|
3789
|
-
|
|
5409
|
+
// flow.yaml 里 plan 环节写了 model 就用它,没写就用配置里的。
|
|
5410
|
+
const planRoute = stageModelOf(settings, (await resolveFlow(cwd, project)).flow, 2, {
|
|
3790
5411
|
llmProvider: settings.planProvider,
|
|
3791
5412
|
model: settings.planModel,
|
|
5413
|
+
})
|
|
5414
|
+
// 契约现场读一次,不引用外层变量——规划段和写契约那段不在同一个函数作用域里,
|
|
5415
|
+
// 之前 activeFlow 就是这么踩的:看着在同一个函数,实际不是。
|
|
5416
|
+
const plannerContract = contractBlock(await readContract(cwd, project))
|
|
5417
|
+
const planned = await runStage(ctx, stageOptions({
|
|
5418
|
+
provider: planRoute.provider,
|
|
5419
|
+
llmProvider: planRoute.llmProvider,
|
|
5420
|
+
model: planRoute.model,
|
|
3792
5421
|
label: `${project} 规划`,
|
|
3793
5422
|
stageKey: 'plan',
|
|
3794
|
-
prompt: PLANNER_PROMPT(requirementText, constraints, (await listFiles(cwd)).join('\n'))
|
|
5423
|
+
prompt: `${plannerContract}${plannerContract === '' ? '' : '\n\n'}${PLANNER_PROMPT(requirementText, constraints, (await listFiles(cwd)).join('\n'))}`
|
|
3795
5424
|
+ (aesthetic.enabled === true ? `${planNote(aesthetic.carriers)}\n${ceilingPlanNote(aesthetic.carriers)}\n${describePatterns(patterns)}` : '')
|
|
3796
5425
|
+ domainPlanNote(domain),
|
|
3797
5426
|
}))
|
|
@@ -3864,10 +5493,16 @@ function splitRoute(value) {
|
|
|
3864
5493
|
})
|
|
3865
5494
|
// The pre-build snapshot is what "roll this attempt back" means later.
|
|
3866
5495
|
const before = await snap(`实施前 R${rework + 1}`)
|
|
3867
|
-
|
|
3868
|
-
|
|
5496
|
+
// 返工循环里每轮都算一次:flow.yaml 里的 model 是这一轮的真相,
|
|
5497
|
+
// 不在循环外缓存——中途改了配置,下一轮就该按新的来。
|
|
5498
|
+
const buildRoute = stageModelOf(settings, (await resolveFlow(cwd, project)).flow, 3, {
|
|
3869
5499
|
llmProvider: settings.buildProvider,
|
|
3870
5500
|
model: settings.buildModel,
|
|
5501
|
+
})
|
|
5502
|
+
const built = await runStage(ctx, stageOptions({
|
|
5503
|
+
provider: buildRoute.provider,
|
|
5504
|
+
llmProvider: buildRoute.llmProvider,
|
|
5505
|
+
model: buildRoute.model,
|
|
3871
5506
|
// 轮次用 rework+1:rework 是「已经返工过几次」,返工 1 次说明这是第 2 轮。
|
|
3872
5507
|
// 之前写成 R${rework},结果快照说「实施前 R2」、日志标签说「实施 R1」,
|
|
3873
5508
|
// 对着日志数轮次会数错。
|
|
@@ -3875,7 +5510,7 @@ function splitRoute(value) {
|
|
|
3875
5510
|
stageKey: 'build',
|
|
3876
5511
|
// 实施只读 Plan.md;返工时额外读上一轮的 QA_Report.md。
|
|
3877
5512
|
// 读什么由 STAGE_IO 决定,不在这里手工拼内存变量。
|
|
3878
|
-
prompt: `${BUILDER_RULES(rework)}${aesthetic.enabled === true ? `\n${buildRules(aesthetic.carriers)}\n${describePatterns(patterns)}` : ''}${domainBuildRules(domain)}${useDesktop ? desktopBuildNote() : ''}\n\n${await stageContext(cwd, project, 3, rework > 0 ? ['qa'] : [])}`,
|
|
5513
|
+
prompt: `${BUILDER_RULES(rework)}${aesthetic.enabled === true ? `\n${buildRules(aesthetic.carriers)}\n${describePatterns(patterns)}` : ''}${domainBuildRules(domain)}${useDesktop ? desktopBuildNote() : ''}\n\n${await stageContext(cwd, project, 3, rework > 0 ? ['qa'] : [], (await resolveFlow(cwd, project)).flow, contractBlock(await readContract(cwd, project)))}`,
|
|
3879
5514
|
}))
|
|
3880
5515
|
noteRoute(built.routeNote)
|
|
3881
5516
|
await watchdog?.afterStage(built)
|
|
@@ -3910,6 +5545,11 @@ function splitRoute(value) {
|
|
|
3910
5545
|
const build = parseJsonBlock(built.text, 'summary')
|
|
3911
5546
|
buildSummary = typeof build?.summary === 'string' ? build.summary : built.text.slice(0, 800)
|
|
3912
5547
|
await appendArtifact(cwd, project, ARTIFACT.log, ticketBlock(`实施 R${rework + 1}`, buildSummary))
|
|
5548
|
+
// 返工的修复台账:一条一行,只写「编号 → 改了什么 → 跑了哪条命令 → 结果」。
|
|
5549
|
+
// 这一节存在的意义是把「这轮到底修了哪几条」固定成事实,
|
|
5550
|
+
// 免得下一轮质检只能靠 diff 猜。
|
|
5551
|
+
const fixLog = renderFixLog(build?.fixes, rework + 1)
|
|
5552
|
+
if (fixLog !== '') await appendArtifact(cwd, project, ARTIFACT.log, fixLog)
|
|
3913
5553
|
// Record what this attempt touched, so a precise rollback knows which
|
|
3914
5554
|
// files to put back without needing the builder to be honest later.
|
|
3915
5555
|
const claimed = normalizePaths(build?.files)
|
|
@@ -3917,6 +5557,24 @@ function splitRoute(value) {
|
|
|
3917
5557
|
if (touched.length === 0 && before !== '') {
|
|
3918
5558
|
touched = (await snapshotDiff(cwd, project, before)).map(entry => entry.path)
|
|
3919
5559
|
}
|
|
5560
|
+
// ── 补丁台账:记录这一轮实施段真的写了哪些文件 ──
|
|
5561
|
+
// attempts 的文件清单来自实施段自述,可以说假话;台账记的是
|
|
5562
|
+
// 插件通过快照 diff 看到的实际改动,beforeSha/afterSha 都是插件算的。
|
|
5563
|
+
const batchId = `${project}-R${rework + 1}`
|
|
5564
|
+
if (touched.length > 0) {
|
|
5565
|
+
const ledgerEntries = []
|
|
5566
|
+
for (let i = 0; i < touched.length; i += 1) {
|
|
5567
|
+
const entry = await recordFileWrite(cwd, project, touched[i], batchId, 3, i + 1)
|
|
5568
|
+
ledgerEntries.push(entry)
|
|
5569
|
+
}
|
|
5570
|
+
// 写完之后再算 afterSha:此时文件已经是实施段改过的版本
|
|
5571
|
+
for (const entry of ledgerEntries) {
|
|
5572
|
+
const abs = join(cwd, entry.path)
|
|
5573
|
+
const afterSha = await fileSha256(abs)
|
|
5574
|
+
commitLedgerEntry(cwd, project, entry, afterSha)
|
|
5575
|
+
}
|
|
5576
|
+
await logLine(cwd, project, `补丁台账:${ledgerEntries.length} 条写入(batchId=${batchId})`)
|
|
5577
|
+
}
|
|
3920
5578
|
const after = await snap(`实施后 R${rework + 1}`)
|
|
3921
5579
|
attempts.push({
|
|
3922
5580
|
round: rework + 1,
|
|
@@ -3928,22 +5586,267 @@ function splitRoute(value) {
|
|
|
3928
5586
|
at: nowIso(),
|
|
3929
5587
|
})
|
|
3930
5588
|
await writeState(cwd, project, { attempts })
|
|
5589
|
+
|
|
5590
|
+
// ── 越界检查 ──────────────────────────────────────────
|
|
5591
|
+
//
|
|
5592
|
+
// 契约里的「不许碰」在这里兑现。只能写在写完文件之后:插件没有
|
|
5593
|
+
// 「工具调用前」那个钩子,拦不住第一次写,但能保证它跑不掉——
|
|
5594
|
+
// 判 FAIL、把契约原文贴回去、让人用台账把这批改动撤掉。
|
|
5595
|
+
//
|
|
5596
|
+
// touched 来自快照 diff,不是实施段自述,所以它说不说谎都一样。
|
|
5597
|
+
const guard = await readContract(cwd, project)
|
|
5598
|
+
const violated = touched
|
|
5599
|
+
.map(file => ({ file, rule: hitsForbidden(file, guard?.forbidden) }))
|
|
5600
|
+
.filter(item => item.rule !== '')
|
|
5601
|
+
if (violated.length > 0) {
|
|
5602
|
+
const detail = violated.map(item => `${item.file}(踩到「${item.rule}」)`).join(';')
|
|
5603
|
+
await writeState(cwd, project, {
|
|
5604
|
+
stage: 3,
|
|
5605
|
+
status: 'forbidden-touched',
|
|
5606
|
+
rework,
|
|
5607
|
+
lastError: detail,
|
|
5608
|
+
})
|
|
5609
|
+
await logLine(cwd, project, `越界:${detail}`)
|
|
5610
|
+
return craft({
|
|
5611
|
+
outcome: 'blocked',
|
|
5612
|
+
stage: 3,
|
|
5613
|
+
rework,
|
|
5614
|
+
plan: planText,
|
|
5615
|
+
buildSummary,
|
|
5616
|
+
verdict: `改了不许碰的地方:${detail}`,
|
|
5617
|
+
issues: [
|
|
5618
|
+
`越界改动:${detail}`,
|
|
5619
|
+
...(Array.isArray(guard?.forbidden) ? guard.forbidden.map(line => `不许碰:${line}`) : []),
|
|
5620
|
+
],
|
|
5621
|
+
note: await writeNextStep(cwd, project, explainStop({
|
|
5622
|
+
stage: 3,
|
|
5623
|
+
verdict: '越界',
|
|
5624
|
+
reason: `实施段改了契约里写着不许碰的路径:${detail}。`,
|
|
5625
|
+
resumable: true,
|
|
5626
|
+
next: '先 project_rollback mode="ledger" 把这批撤掉,再让实施段重做。契约原文在 .project-flow/<项目>/contract.json。',
|
|
5627
|
+
})),
|
|
5628
|
+
})
|
|
5629
|
+
}
|
|
3931
5630
|
needBuild = false
|
|
3932
5631
|
}
|
|
3933
5632
|
|
|
5633
|
+
// ── 中间阶段 ──────────────────────────────────────────────
|
|
5634
|
+
//
|
|
5635
|
+
// flow.yaml 允许在实施和质检之间插阶段(任务书举的例子是安全评审)。
|
|
5636
|
+
// 位置语义:前三个是需求/规划/实施,最后一个是质检,中间那些才是额外阶段。
|
|
5637
|
+
// 所以是 slice(3, -1) 而不是 slice(2, -1)——内置四阶下它切出空数组,
|
|
5638
|
+
// 一个都不跑,「没有 flow.yaml 时行为完全不变」就是在这一句兑现的。
|
|
5639
|
+
//
|
|
5640
|
+
// 中间阶段用通用子会话:读它声明的文件,按 instructions 干活。四阶各有
|
|
5641
|
+
// 专用 prompt,但未知阶段没法预先写专用 prompt,所以只能通用。没写
|
|
5642
|
+
// instructions 的直接跳过并记日志,不猜它想干什么——猜错了是白花钱。
|
|
5643
|
+
const middleFlow = (await resolveFlow(cwd, project)).flow
|
|
5644
|
+
const middlePhases = middleFlow.phases.slice(3, -1)
|
|
5645
|
+
for (const phase of middlePhases) {
|
|
5646
|
+
cancelled()
|
|
5647
|
+
const instruction = typeof phase.instructions === 'string' ? phase.instructions.trim() : ''
|
|
5648
|
+
if (instruction === '') {
|
|
5649
|
+
await logLine(cwd, project, `中间阶段 ${phase.id} 没写 instructions,跳过`)
|
|
5650
|
+
continue
|
|
5651
|
+
}
|
|
5652
|
+
await writeState(cwd, project, { stage: 3, status: `extra:${phase.id}`, rework })
|
|
5653
|
+
const inputs = []
|
|
5654
|
+
for (const file of phase.reads) {
|
|
5655
|
+
// 只喂产物文件。src/** 这类 glob 指的是代码目录,喂不进上下文,跳过。
|
|
5656
|
+
const text = await readArtifact(cwd, project, basename(file))
|
|
5657
|
+
if (text !== undefined) inputs.push(`## ${file}\n\n${text.trim()}`)
|
|
5658
|
+
}
|
|
5659
|
+
const extra = await runStage(ctx, stageOptions({
|
|
5660
|
+
provider: settings.provider,
|
|
5661
|
+
llmProvider: settings.planProvider,
|
|
5662
|
+
model: settings.planModel,
|
|
5663
|
+
label: `${project} ${phase.id}${rework === 0 ? '' : ` R${rework + 1}`}`,
|
|
5664
|
+
stageKey: phase.id,
|
|
5665
|
+
prompt: `${instruction}${inputs.length === 0 ? '' : `\n\n${inputs.join('\n\n')}`}`,
|
|
5666
|
+
}))
|
|
5667
|
+
noteRoute(extra.routeNote)
|
|
5668
|
+
await watchdog?.afterStage(extra)
|
|
5669
|
+
await recordCost()
|
|
5670
|
+
cancelled()
|
|
5671
|
+
if (!extra.ok) {
|
|
5672
|
+
const why = diagnoseEmptyError(extra.stopReason, extra.diagnostic)
|
|
5673
|
+
await writeState(cwd, project, {
|
|
5674
|
+
stage: 3,
|
|
5675
|
+
status: `中间阶段 ${phase.id} 失败`,
|
|
5676
|
+
rework,
|
|
5677
|
+
lastError: why,
|
|
5678
|
+
})
|
|
5679
|
+
await logLine(cwd, project, `中间阶段 ${phase.id} 失败:${extra.stopReason}|${why}`)
|
|
5680
|
+
return craft({
|
|
5681
|
+
outcome: 'blocked',
|
|
5682
|
+
stage: 3,
|
|
5683
|
+
rework,
|
|
5684
|
+
plan: planText,
|
|
5685
|
+
buildSummary,
|
|
5686
|
+
verdict: `中间阶段 ${phase.id} 没跑完`,
|
|
5687
|
+
issues: [why],
|
|
5688
|
+
note: await writeNextStep(cwd, project, explainStop({
|
|
5689
|
+
stage: 3,
|
|
5690
|
+
verdict: `${phase.id} 没跑完`,
|
|
5691
|
+
reason: `中间阶段 ${phase.id} 试了 ${settings.maxStageRetries + 1} 次都没正常结束:${why}。`,
|
|
5692
|
+
resumable: true,
|
|
5693
|
+
next: '「继续」会从这个中间阶段接着跑,前面几阶不重做。',
|
|
5694
|
+
})),
|
|
5695
|
+
})
|
|
5696
|
+
}
|
|
5697
|
+
// 门禁只认「产物在不在」。intent 要问用户、verdict 属于质检那一段的
|
|
5698
|
+
// 职责、assertions 要跑命令——这些在这里重复一遍就是两套判定。
|
|
5699
|
+
const gateOfMiddle = phase.gate !== null && typeof phase.gate === 'object' ? phase.gate : {}
|
|
5700
|
+
if (gateOfMiddle.kind === 'artifact_present') {
|
|
5701
|
+
const produced = []
|
|
5702
|
+
for (const file of phase.writes) {
|
|
5703
|
+
const text = await readArtifact(cwd, project, basename(file))
|
|
5704
|
+
if (text !== undefined && text.trim() !== '') produced.push(file)
|
|
5705
|
+
}
|
|
5706
|
+
if (produced.length === 0) {
|
|
5707
|
+
const why = `中间阶段 ${phase.id} 跑完了,但没产出它声明的任何文件(${phase.writes.join('、') || 'writes 是空的'})`
|
|
5708
|
+
await writeState(cwd, project, { stage: 3, status: `extra-missing:${phase.id}`, rework, lastError: why })
|
|
5709
|
+
await logLine(cwd, project, why)
|
|
5710
|
+
return craft({
|
|
5711
|
+
outcome: 'blocked',
|
|
5712
|
+
stage: 3,
|
|
5713
|
+
rework,
|
|
5714
|
+
plan: planText,
|
|
5715
|
+
buildSummary,
|
|
5716
|
+
verdict: why,
|
|
5717
|
+
issues: [why],
|
|
5718
|
+
note: await writeNextStep(cwd, project, explainStop({
|
|
5719
|
+
stage: 3,
|
|
5720
|
+
verdict: `中间阶段 ${phase.id} 没产出`,
|
|
5721
|
+
reason: why,
|
|
5722
|
+
resumable: true,
|
|
5723
|
+
next: '「继续」会重跑这个中间阶段,前面几阶不重做。',
|
|
5724
|
+
})),
|
|
5725
|
+
})
|
|
5726
|
+
}
|
|
5727
|
+
}
|
|
5728
|
+
await appendArtifact(
|
|
5729
|
+
cwd,
|
|
5730
|
+
project,
|
|
5731
|
+
ARTIFACT.log,
|
|
5732
|
+
ticketBlock(`${phase.id} R${rework + 1}`, typeof extra.text === 'string' ? extra.text.slice(0, 800) : ''),
|
|
5733
|
+
)
|
|
5734
|
+
}
|
|
5735
|
+
|
|
3934
5736
|
await writeState(cwd, project, {
|
|
3935
5737
|
stage: 4,
|
|
3936
5738
|
status: rework === 0 ? 'checking' : `checking R${rework}`,
|
|
3937
5739
|
rework,
|
|
3938
5740
|
})
|
|
3939
5741
|
|
|
5742
|
+
// ── 判据先跑,模型后判 ──────────────────────────────────
|
|
5743
|
+
//
|
|
5744
|
+
// 顺序很重要:命令先跑完,结果原样塞进质检的输入里。模型看到的不是
|
|
5745
|
+
// 「请你自己判断」,而是「这些命令的退出码在这里,照着解释」。它说 PASS
|
|
5746
|
+
// 也翻不了命令的案。
|
|
5747
|
+
const requirementForQa = await readArtifact(cwd, project, ARTIFACT.requirement) ?? ''
|
|
5748
|
+
const storedFingerprint = await readRequirementFingerprint(cwd, project)
|
|
5749
|
+
const checkEntries = parseRequirementChecks(requirementForQa)
|
|
5750
|
+
const liveFingerprint = requirementFingerprint(checkEntries)
|
|
5751
|
+
const fingerprintMissing = storedFingerprint === ''
|
|
5752
|
+
const fingerprintInvalid = !fingerprintMissing && !/^[0-9a-fA-F]{64}$/u.test(storedFingerprint)
|
|
5753
|
+
const fingerprintMismatch = !fingerprintMissing && !fingerprintInvalid && liveFingerprint !== storedFingerprint
|
|
5754
|
+
if (fingerprintMissing || fingerprintInvalid || fingerprintMismatch) {
|
|
5755
|
+
// 判据被改:第 2 阶定过的 check 现在和磁盘上的不一样,或者根本就没
|
|
5756
|
+
// 记过指纹(requirement.sha 缺失/非法)。考题被换过的那种情况下,
|
|
5757
|
+
// 跑出来的任何结论都不作数。
|
|
5758
|
+
const detail = fingerprintMissing
|
|
5759
|
+
? 'requirement.sha 缺失(第 2 阶没跑或产物被删)'
|
|
5760
|
+
: fingerprintInvalid
|
|
5761
|
+
? `requirement.sha 内容非法:不是 64 位十六进制(${storedFingerprint.slice(0, 20)}…)`
|
|
5762
|
+
: `指纹 ${storedFingerprint.slice(0, 12)} → ${liveFingerprint.slice(0, 12)}`
|
|
5763
|
+
await writeState(cwd, project, {
|
|
5764
|
+
stage: 4,
|
|
5765
|
+
status: 'criteria-tampered',
|
|
5766
|
+
rework,
|
|
5767
|
+
lastError: `判据被改:${detail}`,
|
|
5768
|
+
})
|
|
5769
|
+
await logLine(cwd, project, `判据被改:${detail},停机`)
|
|
5770
|
+
return craft({
|
|
5771
|
+
outcome: 'blocked',
|
|
5772
|
+
stage: 4,
|
|
5773
|
+
rework,
|
|
5774
|
+
plan: planText,
|
|
5775
|
+
buildSummary,
|
|
5776
|
+
verdict: '判据被改',
|
|
5777
|
+
issues: [
|
|
5778
|
+
fingerprintMissing
|
|
5779
|
+
? 'requirement.sha 缺失:第 2 阶没跑或产物被删,判据指纹没有基线,这一轮不跑命令。'
|
|
5780
|
+
: fingerprintInvalid
|
|
5781
|
+
? `requirement.sha 内容非法(${storedFingerprint.slice(0, 24)}…),不是合法指纹,这一轮不跑命令。`
|
|
5782
|
+
: `Requirement.md 里 check 的指纹变了:第 2 阶记的是 ${storedFingerprint.slice(0, 16)}…,现在是 ${liveFingerprint.slice(0, 16)}…`,
|
|
5783
|
+
'这一轮不跑任何 check、也不出结论:考题的状态不对,跑出来的结果说明不了任何事。',
|
|
5784
|
+
],
|
|
5785
|
+
note: await writeNextStep(cwd, project, explainStop({
|
|
5786
|
+
stage: 4,
|
|
5787
|
+
verdict: '判据被改',
|
|
5788
|
+
reason: fingerprintMissing
|
|
5789
|
+
? 'requirement.sha 不存在:第 2 阶没跑,或者这个项目的 check 从来没被定稿过。'
|
|
5790
|
+
: fingerprintInvalid
|
|
5791
|
+
? `requirement.sha 坏了:${storedFingerprint.slice(0, 24)}… 不是 64 位十六进制。`
|
|
5792
|
+
: `${ARTIFACT.requirement} 的 check 字段和第 2 阶定稿时算的 sha256 对不上:中途有人改了判据。`,
|
|
5793
|
+
resumable: true,
|
|
5794
|
+
next: fingerprintMissing || fingerprintInvalid
|
|
5795
|
+
? '用 project_run 重开这个项目(会重新记指纹),不要手动补一个 sha 文件。'
|
|
5796
|
+
: `把 check 改回第 2 阶那一版,或者用 project_run 重开这个项目(会重新定稿并记新指纹)。`,
|
|
5797
|
+
})),
|
|
5798
|
+
})
|
|
5799
|
+
}
|
|
5800
|
+
const assertions = await runRequirementChecks({
|
|
5801
|
+
entries: checkEntries,
|
|
5802
|
+
cwd,
|
|
5803
|
+
allowed: allowedCommandsOf(settings),
|
|
5804
|
+
timeoutMs: settings.checkTimeoutMs,
|
|
5805
|
+
tailChars: settings.checkStdoutTailChars,
|
|
5806
|
+
})
|
|
5807
|
+
const gate = gateAssertions(assertions)
|
|
5808
|
+
if (Array.isArray(assertions) && assertions.length > 0) {
|
|
5809
|
+
await logLine(cwd, project, criteriaInPlay(assertions)
|
|
5810
|
+
? `断言:${gate.verdict}|过 ${gate.passed.length} / 未过 ${gate.failed.length} / 判不了 ${gate.unverified.length + gate.uncovered.length}`
|
|
5811
|
+
: `断言:这次一条 check 都没有(${assertions.length} 条要求全 unverified),结论只来自模型`)
|
|
5812
|
+
}
|
|
5813
|
+
|
|
3940
5814
|
// 先把质检要看的东西准备好:三个文件 + diff,视觉类任务再加预览图。
|
|
3941
|
-
|
|
3942
|
-
|
|
5815
|
+
//
|
|
5816
|
+
// diff 单独拿一次:它既要喂给质检,也要用来判断「上一轮判 closed 的问题
|
|
5817
|
+
// 是不是又被这轮改回去了」。同一个东西读两遍会漂。
|
|
5818
|
+
const diffForQa = await attemptDiff(cwd, project, attempts)
|
|
5819
|
+
// ── 越界检测:diff 里改的文件是否都在台账里 ──
|
|
5820
|
+
// 不在台账里的算「越界改动」——不是实施段写的,是别的来源改的。
|
|
5821
|
+
// 这种情况写进日志,但不阻断流程:用户手改的文件不该挡住质检。
|
|
5822
|
+
let outOfBoundsNote = ''
|
|
5823
|
+
try {
|
|
5824
|
+
const diffPaths = diffForQa?.ok === true
|
|
5825
|
+
? diffForQa.text.split(/\r?\n/u)
|
|
5826
|
+
.filter(line => /^diff --git a\//u.test(line))
|
|
5827
|
+
.map(line => /^diff --git a\/(.+?) b\//u.exec(line)?.[1] ?? '')
|
|
5828
|
+
.filter(p => p !== '')
|
|
5829
|
+
: []
|
|
5830
|
+
if (diffPaths.length > 0) {
|
|
5831
|
+
const coverage = checkLedgerCoverage(cwd, project, diffPaths)
|
|
5832
|
+
if (coverage.outOfBounds.length > 0) {
|
|
5833
|
+
outOfBoundsNote = `越界改动 ${coverage.outOfBounds.length} 个文件(不在台账里):${coverage.outOfBounds.slice(0, 5).join('、')}`
|
|
5834
|
+
await logLine(cwd, project, outOfBoundsNote)
|
|
5835
|
+
}
|
|
5836
|
+
}
|
|
5837
|
+
} catch {
|
|
5838
|
+
// 台账读不了就跳过越界检测,不阻断质检
|
|
5839
|
+
}
|
|
5840
|
+
// 上一轮的账本在这一轮报告覆盖之前读回来,否则跨轮就断了。
|
|
5841
|
+
const previousReport = await readArtifact(cwd, project, ARTIFACT.qa) ?? ''
|
|
5842
|
+
const previousIssues = parseIssueBlock(previousReport)
|
|
5843
|
+
const qaText = `${contractBlock(await readContract(cwd, project))}${QA_PROMPT(
|
|
5844
|
+
requirementForQa,
|
|
3943
5845
|
await readArtifact(cwd, project, ARTIFACT.plan) ?? '',
|
|
3944
5846
|
await readArtifact(cwd, project, ARTIFACT.log) ?? '',
|
|
3945
|
-
|
|
3946
|
-
|
|
5847
|
+
diffForQa,
|
|
5848
|
+
renderKnownIssues(previousIssues),
|
|
5849
|
+
)}${describeAssertions(gate)}${aesthetic.enabled === true ? checkRules(aesthetic.carriers) : ''}${domainQaChecks(domain)}${useDesktop ? desktopQaNote() : ''}`
|
|
3947
5850
|
|
|
3948
5851
|
// 有预览图就喂进去。喂不了(模型不支持看图)也有退路:prompt 里已经写了
|
|
3949
5852
|
// 「没有预览图就写审美未核」,不会静默放行。
|
|
@@ -3957,10 +5860,14 @@ function splitRoute(value) {
|
|
|
3957
5860
|
await logLine(cwd, project, `质检输入:${preview.note}`)
|
|
3958
5861
|
}
|
|
3959
5862
|
|
|
3960
|
-
const
|
|
3961
|
-
provider: settings.provider,
|
|
5863
|
+
const checkRoute = stageModelOf(settings, (await resolveFlow(cwd, project)).flow, 4, {
|
|
3962
5864
|
llmProvider: settings.checkProvider,
|
|
3963
5865
|
model: settings.checkModel,
|
|
5866
|
+
})
|
|
5867
|
+
const checked = await runStage(ctx, stageOptions({
|
|
5868
|
+
provider: checkRoute.provider,
|
|
5869
|
+
llmProvider: checkRoute.llmProvider,
|
|
5870
|
+
model: checkRoute.model,
|
|
3964
5871
|
label: `${project} 质检${rework === 0 ? '' : ` R${rework}`}`,
|
|
3965
5872
|
stageKey: 'check',
|
|
3966
5873
|
// 质检只读三个文件加一份 diff,不碰内存里的 intent / planText / buildSummary。
|
|
@@ -4022,8 +5929,39 @@ function splitRoute(value) {
|
|
|
4022
5929
|
? `质检既没 JSON 也没判词,正文 ${text.length} 字:${text.slice(0, 200).replace(/\s+/gu, ' ')}`
|
|
4023
5930
|
: `质检没按 JSON 回,从正文里认出结论 ${rawVerdict}(正文 ${text.length} 字)`)
|
|
4024
5931
|
}
|
|
4025
|
-
|
|
5932
|
+
// 命令的结论压过模型的结论。只在「这一项目真写了判据」时生效:
|
|
5933
|
+
// 一条 check 都没有的项目(老的、纯文档的)照老路走,否则升级之后
|
|
5934
|
+
// 每个项目都会被判死,那不是加判据,那是把流程关了。
|
|
5935
|
+
const gateActive = criteriaInPlay(assertions)
|
|
5936
|
+
let passed = rawVerdict === 'PASS'
|
|
4026
5937
|
verdict = rawVerdict === '' ? '质检没给出 PASS/FAIL' : rawVerdict
|
|
5938
|
+
if (gateActive && gate.verdict === 'FAIL') {
|
|
5939
|
+
passed = false
|
|
5940
|
+
verdict = `FAIL(断言未过 ${gate.failed.length} 条)`
|
|
5941
|
+
} else if (gateActive && gate.verdict === 'UNVERIFIED' && passed) {
|
|
5942
|
+
// 判不了不等于判过了。
|
|
5943
|
+
passed = false
|
|
5944
|
+
verdict = 'FAIL(有要求没有 check,判不了)'
|
|
5945
|
+
}
|
|
5946
|
+
|
|
5947
|
+
// ── 问题台账:这一轮到底还剩几条没闭环 ──────────────────
|
|
5948
|
+
//
|
|
5949
|
+
// 模型给 JSON 就走 JSON;没给 JSON 才退回解析表格(表头必须声明严重级)。
|
|
5950
|
+
// 两条路都不通,这一轮就没有可执行的意见,按「没法照着改」停机。
|
|
5951
|
+
const incomingIssues = normalizeIncomingIssues(
|
|
5952
|
+
Array.isArray(check?.issues) && check.issues.length > 0 ? check.issues : parseIssueTables(typeof checked.text === 'string' ? checked.text : ''),
|
|
5953
|
+
)
|
|
5954
|
+
const ledger = mergeIssueRounds(previousIssues, incomingIssues, typeof diffForQa?.text === 'string' ? diffForQa.text : '')
|
|
5955
|
+
if (ledger.invalid.length > 0) {
|
|
5956
|
+
// detect / pass 缺一条,这条问题就没法验;整轮按 FAIL,别指望返工能补。
|
|
5957
|
+
passed = false
|
|
5958
|
+
verdict = 'FAIL(问题缺少可执行定义)'
|
|
5959
|
+
} else if (ledger.openCount > 0) {
|
|
5960
|
+
// 还有没闭环的问题,就不许算过——哪怕模型说 PASS。
|
|
5961
|
+
// 判词直接写「几条没闭环」:返工看的是这个数,不是 PASS/FAIL 两个词。
|
|
5962
|
+
passed = false
|
|
5963
|
+
verdict = `FAIL(${ledger.openCount} 条没闭环)`
|
|
5964
|
+
}
|
|
4027
5965
|
|
|
4028
5966
|
// 骨架的反馈:这一轮用过的那几条,质检过了加分,没过减分。
|
|
4029
5967
|
// 没有这个闭环,库只会越来越多,不会越来越准。
|
|
@@ -4050,25 +5988,123 @@ function splitRoute(value) {
|
|
|
4050
5988
|
const issues = parsedIssues.length > 0 || rawText === ''
|
|
4051
5989
|
? parsedIssues
|
|
4052
5990
|
: [`质检没按 JSON 回,以下是它的原文(前 1200 字):\n${rawText.slice(0, 1200)}`]
|
|
5991
|
+
// 断言没过的条目必须进 issues:第 3 阶返工只按这份清单改,
|
|
5992
|
+
// 命令的退出码不写进去,它就只改模型顺嘴提的那几条。
|
|
5993
|
+
if (gateActive && gate.verdict !== 'PASS') {
|
|
5994
|
+
for (const item of gate.failed) {
|
|
5995
|
+
const why = item.denied === true
|
|
5996
|
+
? '被白名单拒了'
|
|
5997
|
+
: item.timeout === true
|
|
5998
|
+
? '超时被收掉'
|
|
5999
|
+
: `退出码 ${item.exit ?? '?'}(期望 ${item.expectExit ?? 0})`
|
|
6000
|
+
const tail = String(item.stdoutTail ?? '').trim().split(/\r?\n/u).slice(-6).join(' / ')
|
|
6001
|
+
issues.push(`第 ${item.req} 条判据没过:${item.cmd} ${why}${tail === '' ? '' : `|输出尾巴:${tail}`}`)
|
|
6002
|
+
}
|
|
6003
|
+
for (const item of gate.unverified) {
|
|
6004
|
+
issues.push(`第 ${item.req} 条没有 check,判不了:这一条不能算过,得先在 Requirement.md 里给它写一条可执行的判据`)
|
|
6005
|
+
}
|
|
6006
|
+
}
|
|
4053
6007
|
// 质检自己说「知道但接受」的风险,进证据包的 remaining_risks
|
|
4054
6008
|
const acceptableRisks = Array.isArray(check?.acceptable_risks)
|
|
4055
6009
|
? check.acceptable_risks.filter(item => typeof item === 'string' && item.trim() !== '').slice(0, 8)
|
|
4056
6010
|
: []
|
|
4057
|
-
|
|
6011
|
+
|
|
6012
|
+
// ── 问题台账:这一轮到底还剩几条没闭环 ──────────────────
|
|
6013
|
+
if (ledger.open.length > 0) {
|
|
6014
|
+
for (const item of ledger.open) {
|
|
6015
|
+
issues.push(`${item.id}|${item.severity}|${item.location || '(没写位置)'}|${item.claim}`)
|
|
6016
|
+
}
|
|
6017
|
+
}
|
|
6018
|
+
await writeState(cwd, project, {
|
|
6019
|
+
openIssues: ledger.openCount,
|
|
6020
|
+
openCritical: ledger.openP0P1,
|
|
6021
|
+
})
|
|
6022
|
+
// 报告分两半:前置块给机器读(verdict + assertions),正文给人读。
|
|
6023
|
+
// 以前只有正文,第 3 阶返工时得靠模型再解释一遍「哪条没过」——那一遍解释
|
|
6024
|
+
// 就是二手信息,现在退出码直接躺着,谁读都一样。
|
|
6025
|
+
const assertionLine = (item) => {
|
|
6026
|
+
const tail = String(item.stdoutTail ?? '').trim().split(/\r?\n/u).slice(-3).join(' / ')
|
|
6027
|
+
return `- 第 ${item.req} 条:${item.status}|${item.cmd === null || item.cmd === undefined ? '(没有 check)' : item.cmd}`
|
|
6028
|
+
+ `|exit ${typeof item.exit === 'number' ? item.exit : '-'}|${item.durationMs}ms`
|
|
6029
|
+
+ `${item.timeout === true ? '|timeout' : ''}${item.denied === true ? '|白名单拒绝' : ''}`
|
|
6030
|
+
+ `${tail === '' ? '' : `|${tail}`}`
|
|
6031
|
+
}
|
|
6032
|
+
const issueLedgerLine = (item) => {
|
|
6033
|
+
const head = `- ${item.id}|${item.severity}|${item.status}|${item.location || '(没写位置)'}|${item.claim}`
|
|
6034
|
+
const more = []
|
|
6035
|
+
if (item.detect !== '') more.push(` 检测:\`${item.detect}\``)
|
|
6036
|
+
if (item.pass !== '') more.push(` 通过标准:${item.pass}`)
|
|
6037
|
+
if (typeof item.note === 'string' && item.note !== '') more.push(` 备注:${item.note}`)
|
|
6038
|
+
return [head, ...more].join('\n')
|
|
6039
|
+
}
|
|
6040
|
+
const reportFront = renderQaFrontMatter({ verdict, round: rework, issues: ledger.issues, assertions })
|
|
6041
|
+
await saveArtifact(cwd, project, ARTIFACT.qa, `${reportFront}\n\n${ticketBlock(
|
|
4058
6042
|
`质检结论:${verdict}`,
|
|
4059
6043
|
[
|
|
4060
6044
|
verdict,
|
|
4061
6045
|
issues.length === 0 ? '' : `## 核过 / 不达标\n\n${issues.map(line => `- ${line}`).join('\n')}`,
|
|
6046
|
+
`## 问题台账\n\n${ledger.issues.length === 0
|
|
6047
|
+
? '(这一轮没有提出具体问题)'
|
|
6048
|
+
: ledger.issues.map(issueLedgerLine).join('\n')}`,
|
|
6049
|
+
`## 断言\n\n${assertions.length === 0
|
|
6050
|
+
? '(这次没有一条 check,结论只来自模型)'
|
|
6051
|
+
: assertions.map(assertionLine).join('\n')}`,
|
|
4062
6052
|
// 单列一节,格式固定,证据包按标题抠条目
|
|
4063
6053
|
`## 可接受的风险\n\n${acceptableRisks.length === 0
|
|
4064
6054
|
? '(无)'
|
|
4065
6055
|
: acceptableRisks.map(line => `- ${line}`).join('\n')}`,
|
|
4066
6056
|
].filter(part => part !== '').join('\n\n'),
|
|
4067
|
-
))
|
|
6057
|
+
)}`)
|
|
6058
|
+
|
|
6059
|
+
// 判据没定义导致的 FAIL,返工修不了:命令是第 1 阶定的,第 3 阶改不了考题。
|
|
6060
|
+
// 这种情况直接停,说清要补什么,别让它白跑一轮返工。
|
|
6061
|
+
if (gateActive && gate.verdict === 'UNVERIFIED' && gate.failed.length === 0) {
|
|
6062
|
+
await writeState(cwd, project, { stage: 4, status: 'qa-unverified', rework, verdict })
|
|
6063
|
+
await logLine(cwd, project, `质检:${gate.unverified.length + gate.uncovered.length} 条要求没有 check,判不了 PASS,停机等补判据`)
|
|
6064
|
+
return craft({
|
|
6065
|
+
outcome: 'blocked',
|
|
6066
|
+
stage: 4,
|
|
6067
|
+
rework,
|
|
6068
|
+
plan: planText,
|
|
6069
|
+
buildSummary,
|
|
6070
|
+
verdict,
|
|
6071
|
+
issues,
|
|
6072
|
+
note: await writeNextStep(cwd, project, explainStop({
|
|
6073
|
+
stage: 4,
|
|
6074
|
+
verdict: '有要求没有 check,判不了',
|
|
6075
|
+
reason: `第 ${gate.unverified.length + gate.uncovered.length} 条要求没写 check,没有可执行的判据,按规矩不能算 PASS。返工也补不上——判据是第 1 阶定的,第 3 阶改不了。`,
|
|
6076
|
+
resumable: true,
|
|
6077
|
+
next: `在 ${ARTIFACT.requirement} 的 checks 前置块里给这几条补上 check(或者下次 project_run 时用 checks 参数),再「继续」。`,
|
|
6078
|
+
})),
|
|
6079
|
+
})
|
|
6080
|
+
}
|
|
6081
|
+
|
|
6082
|
+
// 问题缺少可执行定义:detect / pass 缺一条,这条意见就没法验。
|
|
6083
|
+
// 这不是实现的问题,返工照着一句模糊的话改只会越改越散,所以停机。
|
|
6084
|
+
if (ledger.invalid.length > 0) {
|
|
6085
|
+
await writeState(cwd, project, { stage: 4, status: 'qa-issues-undefined', rework, verdict })
|
|
6086
|
+
await logLine(cwd, project, `质检报告有 ${ledger.invalid.length} 条问题没写全 detect/pass,整轮 FAIL`)
|
|
6087
|
+
return craft({
|
|
6088
|
+
outcome: 'blocked',
|
|
6089
|
+
stage: 4,
|
|
6090
|
+
rework,
|
|
6091
|
+
plan: planText,
|
|
6092
|
+
buildSummary,
|
|
6093
|
+
verdict,
|
|
6094
|
+
issues,
|
|
6095
|
+
note: await writeNextStep(cwd, project, explainStop({
|
|
6096
|
+
stage: 4,
|
|
6097
|
+
verdict: '问题缺少可执行定义',
|
|
6098
|
+
reason: `${ledger.invalid.map(item => item.id).join('、')} 没有写全 detect / pass。没有验法的问题,下一轮改没改都说不清,返工也是瞎改。`,
|
|
6099
|
+
resumable: true,
|
|
6100
|
+
next: '「继续」会让质检重出一轮意见。要是每次都这样,说明任务书里那条要求本身没法验,先把要求写具体。',
|
|
6101
|
+
})),
|
|
6102
|
+
})
|
|
6103
|
+
}
|
|
4068
6104
|
|
|
4069
6105
|
if (passed) {
|
|
4070
|
-
await writeState(cwd, project, { stage: 4, status: 'passed', rework, verdict })
|
|
4071
|
-
await logLine(cwd, project, `质检通过(返工 ${rework}
|
|
6106
|
+
await writeState(cwd, project, { stage: 4, status: 'passed', rework, verdict, openIssues: 0, openCritical: 0 })
|
|
6107
|
+
await logLine(cwd, project, `质检通过(返工 ${rework} 次,问题全部闭环)`)
|
|
4072
6108
|
|
|
4073
6109
|
// 验收的最后一步:跑外部测试拿 exit code,再把整轮的事实写成 JSON。
|
|
4074
6110
|
// 质检说 PASS 只代表「按需求做的」,测试才是「能不能跑」——两件事分开记。
|
|
@@ -4100,11 +6136,38 @@ function splitRoute(value) {
|
|
|
4100
6136
|
})
|
|
4101
6137
|
}
|
|
4102
6138
|
|
|
4103
|
-
//
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
await writeState(cwd, project, { stage: 4, status: '
|
|
4107
|
-
await logLine(cwd, project,
|
|
6139
|
+
// 同一条问题连着三轮没闭环:停,别再空转。report 已经写明卡在哪几条。
|
|
6140
|
+
if (ledger.stuck.length > 0) {
|
|
6141
|
+
verdict = `${ledger.stuck.length} 条问题连续 3 轮没闭环`
|
|
6142
|
+
await writeState(cwd, project, { stage: 4, status: 'stuck-open-issues', rework, verdict })
|
|
6143
|
+
await logLine(cwd, project, `连续 3 轮没闭环:${ledger.stuck.map(item => item.id).join('、')},停机`)
|
|
6144
|
+
return craft({
|
|
6145
|
+
outcome: 'stopped',
|
|
6146
|
+
stage: 4,
|
|
6147
|
+
rework,
|
|
6148
|
+
plan: planText,
|
|
6149
|
+
buildSummary,
|
|
6150
|
+
verdict,
|
|
6151
|
+
issues,
|
|
6152
|
+
note: await writeNextStep(cwd, project, explainStop({
|
|
6153
|
+
stage: 4,
|
|
6154
|
+
verdict: `${ledger.stuck.length} 条问题连续 3 轮没闭环`,
|
|
6155
|
+
reason: `卡在这几条:${ledger.stuck.map(item => `${item.id} ${item.claim}`).join(';')}。同样的意见返第三遍还是没过,说明不是没看见,是做不到或者判据本身有问题。`,
|
|
6156
|
+
resumable: true,
|
|
6157
|
+
next: '要么你自己动手改这几处,要么把这条要求放宽(改 Requirement.md)再「继续」。原样再来一轮只会再停一次。',
|
|
6158
|
+
})),
|
|
6159
|
+
})
|
|
6160
|
+
}
|
|
6161
|
+
|
|
6162
|
+
// 返工判据从「判了 FAIL 就返工」改成「还有没闭环的问题才返工」。
|
|
6163
|
+
// 一条待办都没有的 FAIL 去返工,等于让实施段自己猜哪里不对。
|
|
6164
|
+
//
|
|
6165
|
+
// 例外:判据(check)自己没过。那不是「没问题」,是有一条明确的可执行判据
|
|
6166
|
+
// 在报错——报告里的断言那节就是待办,照它改得动。
|
|
6167
|
+
const assertionActionable = gateActive && gate.verdict === 'FAIL'
|
|
6168
|
+
if (ledger.openCount === 0 && assertionActionable !== true) {
|
|
6169
|
+
await writeState(cwd, project, { stage: 4, status: 'qa-failed-no-issues', rework, openIssues: 0 })
|
|
6170
|
+
await logLine(cwd, project, `质检判 FAIL 但没有未闭环问题(${ledger.issues.length} 条台账)`)
|
|
4108
6171
|
return craft({
|
|
4109
6172
|
outcome: 'blocked',
|
|
4110
6173
|
stage: 4,
|
|
@@ -4112,20 +6175,21 @@ function splitRoute(value) {
|
|
|
4112
6175
|
plan: planText,
|
|
4113
6176
|
buildSummary,
|
|
4114
6177
|
verdict,
|
|
4115
|
-
issues
|
|
6178
|
+
issues,
|
|
4116
6179
|
note: await writeNextStep(cwd, project, explainStop({
|
|
4117
6180
|
stage: 4,
|
|
4118
|
-
verdict: '质检判 FAIL
|
|
4119
|
-
reason:
|
|
6181
|
+
verdict: '质检判 FAIL 但没有可返工的问题',
|
|
6182
|
+
reason: `${ARTIFACT.qa} 里没有一条 open 的问题,返工没有目标。`
|
|
6183
|
+
+ `(这轮台账 ${ledger.issues.length} 条:${ledger.issues.map(item => `${item.id}=${item.status}`).join('、') || '空的'})`,
|
|
4120
6184
|
resumable: true,
|
|
4121
|
-
next: '
|
|
6185
|
+
next: '「继续」会让它重跑质检,通常能给出一份带 detect / pass 的问题清单;老这样说明任务书里的要求太抽象,得先把要求写具体。',
|
|
4122
6186
|
})),
|
|
4123
6187
|
})
|
|
4124
6188
|
}
|
|
4125
6189
|
rework += 1
|
|
4126
6190
|
if (rework > maxRework) {
|
|
4127
6191
|
await writeState(cwd, project, { stage: 4, status: 'stopped-after-rework-limit', rework: rework - 1 })
|
|
4128
|
-
await logLine(cwd, project, `返工上限 ${maxRework}
|
|
6192
|
+
await logLine(cwd, project, `返工上限 ${maxRework} 次用完,停机;未闭环 ${ledger.openCount} 条`)
|
|
4129
6193
|
return craft({
|
|
4130
6194
|
outcome: 'stopped',
|
|
4131
6195
|
stage: 4,
|
|
@@ -4136,16 +6200,15 @@ function splitRoute(value) {
|
|
|
4136
6200
|
issues,
|
|
4137
6201
|
note: await writeNextStep(cwd, project, explainStop({
|
|
4138
6202
|
stage: 4,
|
|
4139
|
-
verdict: `返工 ${rework - 1}
|
|
4140
|
-
reason:
|
|
4141
|
-
? `返工上限 ${maxRework} 次用完了,最后一次是「${verdict}」但没留下具体修改点。`
|
|
4142
|
-
: `返工上限 ${maxRework} 次用完了,最后一次仍卡在:${issues.slice(0, 3).join(';')}`,
|
|
6203
|
+
verdict: `返工 ${rework - 1} 次仍有 ${ledger.openCount} 条没闭环`,
|
|
6204
|
+
reason: `返工上限 ${maxRework} 次用完了,还卡在这几条:${ledger.open.slice(0, 3).map(item => `${item.id} ${item.claim}`).join(';')}`,
|
|
4143
6205
|
resumable: true,
|
|
4144
6206
|
next: '三条路:你自己动手改;把要求放宽(改 Requirement.md)再「继续」;或者放弃这个项目。继续循环下去只会空烧钱,所以故意停在这里。',
|
|
4145
6207
|
})),
|
|
4146
6208
|
})
|
|
4147
6209
|
}
|
|
4148
6210
|
// 修正任务书不再生成:第三阶返工时读的是 QA_Report.md 本身。
|
|
6211
|
+
await logLine(cwd, project, `R${rework} 返工:未闭环 ${ledger.openCount} 条(${ledger.open.map(item => item.id).join('、')})`)
|
|
4149
6212
|
needBuild = true
|
|
4150
6213
|
}
|
|
4151
6214
|
}
|
|
@@ -4222,7 +6285,7 @@ function splitRoute(value) {
|
|
|
4222
6285
|
|
|
4223
6286
|
const rollbackTool = defineTool({
|
|
4224
6287
|
name: 'project_rollback',
|
|
4225
|
-
description: '把工作区回滚到某个快照。mode=full 整棵恢复到目标快照(连新增文件一起清掉);mode=precise
|
|
6288
|
+
description: '把工作区回滚到某个快照。mode=full 整棵恢复到目标快照(连新增文件一起清掉);mode=precise 只还原指定那次实施动过的文件,不碰你手改的其他东西;mode=ledger 按补丁台账还原最后一批写入,只动 agent 真的写过的路径。默认先干跑给 diff,dryRun=false 才真回滚;真回滚前会自动再打一张 pre-rollback 快照,回错了还能再回来。',
|
|
4226
6289
|
parameters: {
|
|
4227
6290
|
project: {
|
|
4228
6291
|
type: 'string',
|
|
@@ -4235,7 +6298,7 @@ function splitRoute(value) {
|
|
|
4235
6298
|
},
|
|
4236
6299
|
mode: {
|
|
4237
6300
|
type: 'string',
|
|
4238
|
-
description: 'full=整棵恢复(默认);precise
|
|
6301
|
+
description: 'full=整棵恢复(默认);precise=只还原那一次实施动过的文件;ledger=按补丁台账还原最后一批写入。',
|
|
4239
6302
|
},
|
|
4240
6303
|
dryRun: {
|
|
4241
6304
|
type: 'boolean',
|
|
@@ -4273,11 +6336,64 @@ function splitRoute(value) {
|
|
|
4273
6336
|
const cwd = args.cwd !== undefined && isAbsolute(args.cwd) ? args.cwd : cwdOf(ctx, exec.agent)
|
|
4274
6337
|
const project = assertProjectName(args.project)
|
|
4275
6338
|
const dryRun = args.dryRun !== false
|
|
4276
|
-
|
|
6339
|
+
// ledger 模式不走 git 快照,走台账。
|
|
6340
|
+
const isLedger = args.mode === 'ledger'
|
|
6341
|
+
const mode = isLedger ? 'ledger' : (args.mode === 'precise' ? 'precise' : 'full')
|
|
4277
6342
|
const fail = (line, details = '') => ({
|
|
4278
6343
|
ok: false, dryRun, target: '', line, changes: [], details,
|
|
4279
6344
|
})
|
|
4280
6345
|
|
|
6346
|
+
// ── ledger 模式:按补丁台账回滚 ──
|
|
6347
|
+
if (isLedger) {
|
|
6348
|
+
// 先写 pre-rollback 快照(如果 git 可用),回错了还能再回去
|
|
6349
|
+
if (await gitAvailable() === true) {
|
|
6350
|
+
const settings0 = settingsOf()
|
|
6351
|
+
const guard = await takeSnapshot(cwd, project, `pre-rollback-ledger ${nowIso().slice(0, 19)}`, {
|
|
6352
|
+
excludes: snapshotExcludesOf(settings0),
|
|
6353
|
+
})
|
|
6354
|
+
if (guard.ok === true) {
|
|
6355
|
+
await logLine(cwd, project, `台账回滚前快照 → ${guard.commit.slice(0, 8)}`)
|
|
6356
|
+
}
|
|
6357
|
+
}
|
|
6358
|
+
// 台账不存在时报错,不静默回滚全部
|
|
6359
|
+
const ledgerFile = ledgerPath(cwd, project)
|
|
6360
|
+
if (!existsSync(ledgerFile)) {
|
|
6361
|
+
return fail(
|
|
6362
|
+
`项目 ${project}:没有补丁台账(${ledgerFile} 不存在),mode=ledger 没法回滚。`,
|
|
6363
|
+
'台账在实施段每次写文件时自动追加。如果这个项目是在台账功能加上之前跑的,就没有台账。',
|
|
6364
|
+
)
|
|
6365
|
+
}
|
|
6366
|
+
// 坏 JSON 行报错,不静默跳过
|
|
6367
|
+
let ledgerResult
|
|
6368
|
+
try {
|
|
6369
|
+
ledgerResult = await rollbackByLedger(cwd, project)
|
|
6370
|
+
} catch (error) {
|
|
6371
|
+
return fail(`台账回滚失败:${messageOf(error)}`, '台账里有坏 JSON 行,一个文件都不会动。')
|
|
6372
|
+
}
|
|
6373
|
+
if (ledgerResult.ok !== true && ledgerResult.reason !== undefined) {
|
|
6374
|
+
return fail(`台账回滚失败:${ledgerResult.reason}`)
|
|
6375
|
+
}
|
|
6376
|
+
const restored = ledgerResult.restored ?? []
|
|
6377
|
+
const failed = ledgerResult.failed ?? []
|
|
6378
|
+
await logLine(cwd, project, `台账回滚:还原 ${restored.length} 个文件${failed.length > 0 ? `,${failed.length} 个失败` : ''}(batchId=${ledgerResult.batchId})`)
|
|
6379
|
+
await writeState(cwd, project, {
|
|
6380
|
+
rollbacks: [
|
|
6381
|
+
...(Array.isArray(state?.rollbacks) ? state.rollbacks : []),
|
|
6382
|
+
{ to: 'ledger', mode, at: nowIso(), batchId: ledgerResult.batchId, remaining: failed.length },
|
|
6383
|
+
],
|
|
6384
|
+
})
|
|
6385
|
+
return {
|
|
6386
|
+
ok: failed.length === 0,
|
|
6387
|
+
dryRun: false,
|
|
6388
|
+
target: `ledger:${ledgerResult.batchId}`,
|
|
6389
|
+
line: `台账回滚(batchId=${ledgerResult.batchId}):还原 ${restored.length} 个文件${failed.length > 0 ? `,${failed.length} 个失败` : ''}。`,
|
|
6390
|
+
changes: [...restored, ...failed],
|
|
6391
|
+
details: failed.length === 0
|
|
6392
|
+
? '只动了台账里记录的文件,其他文件原样保留。'
|
|
6393
|
+
: `失败:\n${failed.map(f => ` ${f}`).join('\n')}`,
|
|
6394
|
+
}
|
|
6395
|
+
}
|
|
6396
|
+
|
|
4281
6397
|
if (await gitAvailable() !== true) {
|
|
4282
6398
|
return fail(`项目 ${project}:这台机器上没有可用的 git,回滚做不了。`)
|
|
4283
6399
|
}
|
|
@@ -4727,6 +6843,9 @@ async function decorateCost(result, settings, requirements, cwd) {
|
|
|
4727
6843
|
return { ok: false, line: `不认识的阶段「${args.stage}」。用 规划 / 实施 / 质检。` }
|
|
4728
6844
|
}
|
|
4729
6845
|
const value = (args.model ?? '').trim()
|
|
6846
|
+
// 写错名字当场拒,别等跑起来才在回退日志里看见。
|
|
6847
|
+
const unknown = await unknownModelMessage(value)
|
|
6848
|
+
if (unknown !== undefined) return { ok: false, line: unknown }
|
|
4730
6849
|
if (value === '' || value === '清空' || value === 'reset') {
|
|
4731
6850
|
await writeOverride({ [key]: '' })
|
|
4732
6851
|
return { ok: true, line: `已把「${args.stage}」恢复成继承当前模型,立即生效。` }
|
|
@@ -4834,6 +6953,34 @@ async function decorateCost(result, settings, requirements, cwd) {
|
|
|
4834
6953
|
return { providers: groups.filter(group => group.models.length > 0 || group.failed === true) }
|
|
4835
6954
|
}
|
|
4836
6955
|
|
|
6956
|
+
/**
|
|
6957
|
+
* 模型名写错要在保存时拦住,不能等跑起来才在回退日志里看见。
|
|
6958
|
+
*
|
|
6959
|
+
* 只有真探到列表时才校验。一个都探不出来(llm 服务没起、profile 里没配模型)
|
|
6960
|
+
* 就放行——那种情况下拦人等于把人锁死在配置界面外面,而错名字本来也有
|
|
6961
|
+
* 三级回退兜着。
|
|
6962
|
+
*
|
|
6963
|
+
* 三种写法都认:`kimi`、`workbuddy/kimi`、`workbuddy kimi`。用户记不清
|
|
6964
|
+
* 该带不带 provider 前缀,不该因为写法差异被判「模型不存在」。
|
|
6965
|
+
*/
|
|
6966
|
+
const unknownModelMessage = async model => {
|
|
6967
|
+
if (typeof model !== 'string' || model.trim() === '') return undefined
|
|
6968
|
+
const wanted = model.trim()
|
|
6969
|
+
const catalog = await listModelCatalog()
|
|
6970
|
+
const known = []
|
|
6971
|
+
for (const group of catalog.providers ?? []) {
|
|
6972
|
+
for (const item of group.models ?? []) {
|
|
6973
|
+
if (typeof item.id !== 'string' || item.id === '') continue
|
|
6974
|
+
known.push(item.id, `${group.id}/${item.id}`, `${group.id} ${item.id}`)
|
|
6975
|
+
}
|
|
6976
|
+
}
|
|
6977
|
+
if (known.length === 0) return undefined
|
|
6978
|
+
const lower = wanted.toLowerCase()
|
|
6979
|
+
if (known.some(id => id.toLowerCase() === lower)) return undefined
|
|
6980
|
+
const unique = [...new Set(known)]
|
|
6981
|
+
return `模型「${wanted}」不在本机可用列表里,没有写入。可用的有:\n${unique.map(id => ` ${id}`).join('\n')}`
|
|
6982
|
+
}
|
|
6983
|
+
|
|
4837
6984
|
/**
|
|
4838
6985
|
* 刷新「本机有哪些模型」这份缓存。
|
|
4839
6986
|
*
|