dsh-project-flow 0.11.0 → 0.13.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/host/codex.mjs ADDED
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Codex 宿主适配器:把 `codex exec` 包成一个假的 DSH ctx。
3
+ *
4
+ * 为什么是「假 ctx」而不是重写一条流水
5
+ * ──────────────────────────────────
6
+ * `runner/pipeline.mjs` 对 ctx 的依赖只有一处:把 ctx 原样递给 runStage。
7
+ * 真正用 ctx 的只有 runStage 里的 `subagentsOf(ctx).startActivation(...)`。
8
+ * 所以只要这个假 ctx 实现了 startActivation 的返回契约,**整条四阶流水
9
+ * 一行都不用改**——快照、补丁台账、判据、问题闭环、返工、证据包全都白拿。
10
+ *
11
+ * 分叉出第二套流水是这里最该避免的事:两边各有各的 bug,修一边漏一边,
12
+ * 三个月后没人说得清哪个才是真的。
13
+ *
14
+ * 返回契约(runStage 的 settle 要的)
15
+ * ──────────────────────────────────
16
+ * { kind: 'external', result: Promise<{ stopReason, output, diagnostic }>, dispose() }
17
+ *
18
+ * `output` 必须是内容块数组 `[{ type: 'text', text }]`——shared/util 的 textOf
19
+ * 只认这个形状,给字符串会得到空串,而且不报错。这是个安静的错误,容易踩。
20
+ *
21
+ * 事件流
22
+ * ──────
23
+ * `codex exec --json` 每行一个 JSON:
24
+ *
25
+ * {"type":"thread.started","thread_id":"…"}
26
+ * {"type":"turn.started"}
27
+ * {"type":"item.started","item":{"id":"item_2","type":"command_execution",…,"status":"in_progress"}}
28
+ * {"type":"item.completed","item":{"id":"item_2","type":"command_execution",…,"exit_code":0}}
29
+ * {"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"…"}}
30
+ * {"type":"turn.completed","usage":{…}}
31
+ *
32
+ * 这一条比 DSH 那边强:`item.started` 和 `item.completed` 成对出现、带 id,
33
+ * 工具边界是明确的观测,不是猜。DSH 外部后端拿不到任何活跃信号(连 agent
34
+ * 对象都没有),只能靠文件 mtime 兜底。
35
+ *
36
+ * @module host/codex
37
+ */
38
+
39
+ import { spawn } from 'node:child_process'
40
+ import { existsSync, readdirSync } from 'node:fs'
41
+ import { join } from 'node:path'
42
+ import { createInterface } from 'node:readline'
43
+
44
+ /** 缺省沙箱:能写工作区,但碰不到外面。 */
45
+ const DEFAULT_SANDBOX = 'workspace-write'
46
+
47
+ /**
48
+ * 把内容块数组压成一段文本。
49
+ *
50
+ * runStage 传进来的 prompt 是 `[{type:'text',text},{type:'image',…}]` 这种形状。
51
+ * 图片块先跳过——codex 支持 `-i`,但需要真实文件路径,而 DSH 的图片块里
52
+ * 是 base64。要接的话得先落盘,那是下一步的事,不在这里假装支持。
53
+ */
54
+ function promptTextOf(content) {
55
+ if (typeof content === 'string') return content
56
+ if (!Array.isArray(content)) return ''
57
+ return content
58
+ .filter(block => block !== null && typeof block === 'object' && block.type === 'text')
59
+ .map(block => (typeof block.text === 'string' ? block.text : ''))
60
+ .join('\n\n')
61
+ }
62
+
63
+ /** 把一条命令压成一行,给熔断日志用。 */
64
+ function briefCommand(command) {
65
+ const text = typeof command === 'string' ? command.replace(/\s+/gu, ' ').trim() : ''
66
+ return text.length > 80 ? `${text.slice(0, 80)}…` : text
67
+ }
68
+
69
+ /**
70
+ * 造一个假 ctx。pipeline 只认 `subagents.startActivation` 这一个方法。
71
+ *
72
+ * @param bin codex 可执行文件绝对路径
73
+ * @param cwd 默认工作目录(spec.cwd 优先)
74
+ * @param model 留空表示用 codex 自己 config.toml 里的模型
75
+ * @param sandbox read-only / workspace-write / danger-full-access
76
+ * @param watchdog 守护器。事件直接喂给它——它天然对应「当前在跑的那一阶」,
77
+ * 不需要再做一次路由。
78
+ * @param onRun 可选:每次起子进程时回调,用来打印进度
79
+ */
80
+ export function createCodexCtx(options = {}) {
81
+ const {
82
+ bin,
83
+ // 放在 bin 前面的一串参数。正常用不到;测试时把 bin 指成 node、
84
+ // 这里放一个假 codex 脚本,就能把整条解析链跑一遍而不碰真模型。
85
+ binArgs = [],
86
+ cwd = process.cwd(),
87
+ model = '',
88
+ sandbox = DEFAULT_SANDBOX,
89
+ extraArgs = [],
90
+ watchdog,
91
+ onRun,
92
+ } = options
93
+
94
+ if (typeof bin !== 'string' || bin === '') {
95
+ throw new Error('createCodexCtx 需要一个 codex 可执行文件路径')
96
+ }
97
+
98
+ // 累计真实 usage。插件的预算器是按字符估的(它拿不到 token 数),
99
+ // 而 codex 每个 turn 结束都会报真账。两个数放一起给人看,别让人以为
100
+ // 估算值就是账单。
101
+ const totalUsage = { input: 0, output: 0, cached: 0, turns: 0 }
102
+
103
+ return {
104
+ /** 宿主名字,给日志和证据包用。 */
105
+ host: { name: 'codex', model, sandbox },
106
+
107
+ /** 截至目前的真实 token 用量(来自 codex 的 turn.completed)。 */
108
+ usage() {
109
+ return { ...totalUsage }
110
+ },
111
+
112
+ subagents: {
113
+ /**
114
+ * 起一次 codex exec,返回 runStage 要的 activation。
115
+ *
116
+ * spec 里 runStage 会塞:provider / label / prompt / parent / signal /
117
+ * delivery / cwd / agentOptions。这里只用 prompt、cwd、signal 三样,
118
+ * 其余是 DSH 的东西,对 codex 没意义。
119
+ */
120
+ async startActivation(spec = {}) {
121
+ const workdir = typeof spec.cwd === 'string' && spec.cwd !== '' ? spec.cwd : cwd
122
+ const prompt = promptTextOf(spec.prompt)
123
+ if (prompt === '') {
124
+ return failedActivation('这一阶的 prompt 是空的:没有内容投给 codex,不能起空会话')
125
+ }
126
+
127
+ const label = typeof spec.label === 'string' ? spec.label : 'codex'
128
+ const args = [...binArgs, 'exec', '--json', '--skip-git-repo-check', '-C', workdir]
129
+ if (typeof model === 'string' && model !== '') args.push('-m', model)
130
+ if (typeof sandbox === 'string' && sandbox !== '') args.push('-s', sandbox)
131
+ args.push(...extraArgs)
132
+ // 用 `-` 让 codex 从 stdin 读 prompt:中文、换行、引号全不用转义。
133
+ args.push('-')
134
+
135
+ onRun?.({ label, workdir, promptChars: prompt.length })
136
+
137
+ const controller = new AbortController()
138
+ const forwardAbort = () => {
139
+ try { controller.abort() } catch { /* 已经 abort 过 */ }
140
+ }
141
+ if (spec.signal?.aborted === true) forwardAbort()
142
+ else spec.signal?.addEventListener('abort', forwardAbort, { once: true })
143
+
144
+ let child
145
+ try {
146
+ child = spawn(bin, args, {
147
+ cwd: workdir,
148
+ stdio: ['pipe', 'pipe', 'pipe'],
149
+ signal: controller.signal,
150
+ windowsHide: true,
151
+ })
152
+ } catch (error) {
153
+ return failedActivation(`codex 起不来:${error?.message ?? error}`)
154
+ }
155
+
156
+ // prompt 走 stdin。写失败(进程已经死了)不该抛到外面——下面的 close
157
+ // 事件会带着退出码回来,那才是结论。
158
+ try {
159
+ child.stdin.on('error', () => {})
160
+ child.stdin.end(prompt, 'utf8')
161
+ } catch { /* 见上 */ }
162
+
163
+ const openTools = new Set()
164
+ let lastMessage = ''
165
+ let stderrTail = ''
166
+ let usage = undefined
167
+ let sawTurnCompleted = false
168
+ let killedBySignal = false
169
+
170
+ child.stderr?.on('data', chunk => {
171
+ stderrTail = (stderrTail + chunk.toString('utf8')).slice(-4000)
172
+ })
173
+
174
+ const rl = createInterface({ input: child.stdout })
175
+ rl.on('line', line => {
176
+ const text = line.trim()
177
+ if (text === '') return
178
+ let event
179
+ try {
180
+ event = JSON.parse(text)
181
+ } catch {
182
+ // 不是 JSON 的行(进度条、彩色的杂音)直接忽略,但要顶一下心跳:
183
+ // 能吐字节就说明它还活着。
184
+ watchdog?.touch()
185
+ return
186
+ }
187
+ const type = typeof event?.type === 'string' ? event.type : ''
188
+ const item = event?.item
189
+
190
+ // 每一个事件都是活着的证据。codex 的流是有节奏的,比 DSH 外部后端
191
+ // 那种「一句话不说九分钟」强太多。
192
+ watchdog?.touch()
193
+
194
+ if (type === 'item.started' && item?.type === 'command_execution') {
195
+ openTools.add(item.id)
196
+ watchdog?.toolStart(briefCommand(item.command) || 'command_execution')
197
+ return
198
+ }
199
+ if (type === 'item.completed' && item?.type === 'command_execution') {
200
+ if (openTools.delete(item.id)) watchdog?.toolEnd()
201
+ return
202
+ }
203
+ if (type === 'item.completed' && item?.type === 'agent_message') {
204
+ if (typeof item.text === 'string' && item.text !== '') lastMessage = item.text
205
+ return
206
+ }
207
+ if (type === 'turn.completed') {
208
+ sawTurnCompleted = true
209
+ if (event.usage !== undefined) {
210
+ usage = event.usage
211
+ totalUsage.turns += 1
212
+ totalUsage.input += Number(event.usage.input_tokens ?? 0) || 0
213
+ totalUsage.output += Number(event.usage.output_tokens ?? 0) || 0
214
+ totalUsage.cached += Number(event.usage.cached_input_tokens ?? 0) || 0
215
+ }
216
+ return
217
+ }
218
+ if (type === 'error' && typeof event.message === 'string') {
219
+ // 重连提示不是失败:codex 会自己退到 HTTPS 再试。只留最后一条做诊断。
220
+ stderrTail = `${stderrTail}\n${event.message}`.slice(-4000)
221
+ }
222
+ })
223
+
224
+ const result = new Promise(resolve => {
225
+ const finish = (stopReason, diagnostic) => {
226
+ // 收尾时把没配对的工具全作废:被 kill 的命令不会再有 completed。
227
+ for (const _ of openTools) watchdog?.toolEnd()
228
+ openTools.clear()
229
+ try { rl.close() } catch { /* 已经关了 */ }
230
+ resolve({
231
+ stopReason,
232
+ diagnostic,
233
+ usage,
234
+ // textOf 只认块数组,给字符串会静默变空串
235
+ output: lastMessage === '' ? [] : [{ type: 'text', text: lastMessage }],
236
+ })
237
+ }
238
+
239
+ child.on('error', error => {
240
+ killedBySignal = true
241
+ // spawn 带 signal 时,abort 会走 error 而不是 close(消息是
242
+ // "The operation was aborted")。不在这儿认一次的话,用户按了
243
+ // 停止却看到「codex 进程出错」,会以为插件坏了。
244
+ if (spec.signal?.aborted === true) {
245
+ finish('error', `${label}:已取消`)
246
+ return
247
+ }
248
+ finish('error', `${label}:codex 进程出错(${error?.message ?? error})`)
249
+ })
250
+
251
+ child.on('close', (code, signal) => {
252
+ const aborted = spec.signal?.aborted === true
253
+ if (aborted || killedBySignal) {
254
+ finish('error', `${label}:已取消`)
255
+ return
256
+ }
257
+ if (code === 0 && sawTurnCompleted) {
258
+ finish('completed', undefined)
259
+ return
260
+ }
261
+ const tail = stderrTail.trim().split(/\r?\n/u).slice(-6).join(' / ')
262
+ finish(
263
+ 'error',
264
+ `${label}:codex 退出码 ${code ?? signal ?? '?'}`
265
+ + (sawTurnCompleted ? '' : ',没跑到 turn.completed')
266
+ + (tail === '' ? '' : `|${tail.slice(0, 400)}`),
267
+ )
268
+ })
269
+ })
270
+
271
+ return {
272
+ // external:不要给 handle.agent。runStage 看到 external 就不去挂事件监听,
273
+ // 那边的监听本来就是给 DSH 本地子会话准备的,这里没有。
274
+ kind: 'external',
275
+ result,
276
+ dispose: async () => {
277
+ spec.signal?.removeEventListener?.('abort', forwardAbort)
278
+ const alive = () => child.exitCode === null && child.signalCode === null
279
+ if (!alive()) return
280
+ try { child.kill() } catch { /* 已经退了 */ }
281
+ // Windows 上 SIGTERM 不一定立刻生效,尤其对方是个不肯退的 node 进程。
282
+ // 等一小会儿还没死就硬杀——留在后台的 codex 会继续烧钱,那不是小事。
283
+ await new Promise(resolve => setTimeout(resolve, 150))
284
+ if (!alive()) return
285
+ try { child.kill('SIGKILL') } catch { /* 系统不支持就直接算了 */ }
286
+ },
287
+ }
288
+ },
289
+ },
290
+ }
291
+ }
292
+
293
+ /** 一起手就失败(比如 prompt 空)时用的占位 activation。 */
294
+ function failedActivation(message) {
295
+ return {
296
+ kind: 'external',
297
+ result: Promise.resolve({ stopReason: 'error', diagnostic: message, output: [] }),
298
+ dispose: async () => {},
299
+ }
300
+ }
301
+
302
+ /**
303
+ * 找本机的 codex 可执行文件。
304
+ *
305
+ * 顺序是有讲究的:
306
+ *
307
+ * 1. `CODEX_CLI_PATH` —— 用户或桌面应用明确指的那个,不猜
308
+ * 2. `AppData\Local\OpenAI\Codex\bin\<build>\codex.exe` —— 真正的 CLI 二进制。
309
+ * `<build>` 是版本号目录(比如 45e749ac65b97f3a),升级就会换一个,
310
+ * 所以得扫目录、取最新那个,不能写死。
311
+ *
312
+ * 不去碰 `Program Files\WindowsApps\...`:那是桌面应用自带的副本,路径带版本号
313
+ * 还有 ACL 限制,拿来当 CLI 用是会踩坑的。
314
+ *
315
+ * @returns 找到的绝对路径;找不到返回空串,由调用方决定怎么报
316
+ */
317
+ export function findCodexBinary(env = process.env) {
318
+ const home = env.USERPROFILE ?? env.HOME ?? ''
319
+
320
+ if (typeof env.CODEX_CLI_PATH === 'string' && env.CODEX_CLI_PATH !== '') {
321
+ try {
322
+ if (existsSync(env.CODEX_CLI_PATH)) return env.CODEX_CLI_PATH
323
+ } catch { /* 路径里有权限问题就当没配 */ }
324
+ }
325
+
326
+ if (home === '') return ''
327
+ const base = join(home, 'AppData', 'Local', 'OpenAI', 'Codex', 'bin')
328
+ try {
329
+ if (!existsSync(base)) return ''
330
+ const found = readdirSync(base)
331
+ .map(name => join(base, name, 'codex.exe'))
332
+ .filter(candidate => existsSync(candidate))
333
+ if (found.length > 0) return found[found.length - 1]
334
+ } catch {
335
+ // 目录读不动就当没装
336
+ }
337
+ return ''
338
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-project-flow",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "private": false,
5
- "description": "Four-stage project workflow: requirement, plan, build, QA, with an intent gate, a rework loop, self-healing recovery, a watchdog that stops runaway runs, snapshot rollback with a retention cap, a single status light, and a machine-readable Completion_Evidence.json.",
5
+ "description": "Delivery control for AI coding agents: every requirement gets a runnable check whose exit code decides the verdict, every write goes into a patch ledger so rollback can restore exactly that file, every round leaves a snapshot diff and a machine-readable completion evidence pack, and spend is capped before each call. Two paces: quick (one subagent) for small edits, safe (four gated stages) for long jobs.",
6
6
  "type": "module",
7
7
  "main": "index.js",
8
8
  "author": {
@@ -83,7 +83,10 @@
83
83
  "assets/*.png",
84
84
  "README.md",
85
85
  "CHANGELOG.md",
86
- "LICENSE"
86
+ "LICENSE",
87
+ "bin/",
88
+ "host/",
89
+ "tests/fixtures/"
87
90
  ],
88
91
  "dsh": {
89
92
  "bundle": {
@@ -105,6 +108,9 @@
105
108
  "optional": true
106
109
  }
107
110
  },
111
+ "bin": {
112
+ "flow": "./bin/flow.mjs"
113
+ },
108
114
  "scripts": {
109
115
  "bench": "node bench/run.mjs",
110
116
  "test": "node tests/run-all.mjs"
@@ -12,7 +12,7 @@ import { shouldUseDesktop, desktopBuildNote, desktopQaNote } from '../desktop.mj
12
12
  import { criteriaInPlay, describeAssertions, gateAssertions, renderQaFrontMatter } from '../checks/assertion.mjs'
13
13
  import { allowedCommandsOf, runRequirementChecks } from '../checks/command.mjs'
14
14
  import { buildCheckEntries, parseRequirementChecks, renderRequirementChecks, requirementFingerprint, stripInlineCheck } from '../checks/requirement.mjs'
15
- import { snapshotExcludesOf } from '../config/settings.mjs'
15
+ import { normalizeDeliveryMode, snapshotExcludesOf } from '../config/settings.mjs'
16
16
  import { mergeIssueRounds, normalizeIncomingIssues, parseIssueBlock, parseIssueTables, renderFixLog, renderKnownIssues } from '../issues/issue.mjs'
17
17
  import { logLine, writeNextStep } from '../persistence/log.mjs'
18
18
  import { appendArtifact, contractBlock, readArtifact, readContract, readRequirementFingerprint, readState, resolveFlow, saveArtifact, saveRequirementFingerprint, writeState } from '../persistence/state.mjs'
@@ -30,8 +30,30 @@ import { hitsForbidden, stageModelOf } from '../workspace/paths.mjs'
30
30
  export function createPipeline(ctx) {
31
31
 
32
32
  const runPipeline = async options => {
33
- const { cwd, project, intent, requirements, checks, constraints, confirmation, maxRework, parent, signal, seed, settings, healed, mode, watchdog } = options
33
+ // 这些字段本来由 DSH 那边的调用方给。CLI 入口(bin/flow.mjs)不经过那一层,
34
+ // 少传一个就炸在 `healed.length` 上——外部入口不该被这种默认值问题挡住,
35
+ // 所以能给默认值的都给上。
36
+ const {
37
+ cwd, project, intent, requirements = [], checks = [], constraints,
38
+ confirmation, maxRework, parent, signal, seed, settings,
39
+ healed = [], mode, watchdog,
40
+ } = options
34
41
  const artifacts = stateDir(cwd, project)
42
+
43
+ /**
44
+ * 交付模式。
45
+ *
46
+ * safe(默认)—— 规划、实施、质检各开一个子会话,四阶完整走。
47
+ * quick —— 跳过规划和质检这两次子会话:任务书直接用 Requirement.md
48
+ * 原文,质检只在「每条要求都有 check 且全过」时才免掉模型。
49
+ *
50
+ * quick 省的是两次子会话的钱和时间,不是省掉判断:命令的退出码照样逐条跑,
51
+ * 有任何一条没过、或者有要求压根没写 check,立刻退回派子会话,跟 safe 一样。
52
+ *
53
+ * 为什么要有这个:一件「把日志级别从 info 改成 debug」的小事,也走完整四阶的话,
54
+ * 用户会觉得还不如直接跟 agent 说。流程重不重,取决于它配不配得上这件事。
55
+ */
56
+ const quickMode = normalizeDeliveryMode(settings.deliveryMode) === 'quick'
35
57
  const routeNotes = []
36
58
  const noteRoute = note => {
37
59
  if (typeof note === 'string' && note !== '' && !routeNotes.includes(note)) routeNotes.push(note)
@@ -395,16 +417,38 @@ export function createPipeline(ctx) {
395
417
  // 契约现场读一次,不引用外层变量——规划段和写契约那段不在同一个函数作用域里,
396
418
  // 之前 activeFlow 就是这么踩的:看着在同一个函数,实际不是。
397
419
  const plannerContract = contractBlock(await readContract(cwd, project))
398
- const planned = await runStage(ctx, stageOptions({
399
- provider: planRoute.provider,
400
- llmProvider: planRoute.llmProvider,
401
- model: planRoute.model,
402
- label: `${project} 规划`,
403
- stageKey: 'plan',
404
- prompt: `${plannerContract}${plannerContract === '' ? '' : '\n\n'}${PLANNER_PROMPT(requirementText, constraints, (await listFiles(cwd)).join('\n'))}`
405
- + (aesthetic.enabled === true ? `${planNote(aesthetic.carriers)}\n${ceilingPlanNote(aesthetic.carriers)}\n${describePatterns(patterns)}` : '')
406
- + domainPlanNote(domain),
407
- }))
420
+ // ── 快速模式:不派规划子会话 ──────────────────────────────
421
+ //
422
+ // 只把「派子会话」这一步换掉,后面的解析、落盘、任务书检查、实施、质检
423
+ // 一个字都不用改。这样两条模式共用同一条流水,不会分叉出第二套行为——
424
+ // 分叉过的代码最后一定有一边没人维护。
425
+ //
426
+ // 拿 Requirement.md 原文当任务书是够的:第 1 阶已经把「要什么、判据是
427
+ // 什么」问清楚了,规划的价值主要在长任务上拆步骤,小修小改不值一次子会话。
428
+ const planned = quickMode
429
+ ? {
430
+ ok: true,
431
+ stopReason: 'completed',
432
+ routeNote: '',
433
+ text: JSON.stringify({
434
+ plan: '快速模式:跳过规划。任务书直接取 Requirement.md 原文。',
435
+ buildTicket: requirementText ?? '',
436
+ }),
437
+ }
438
+ : await runStage(ctx, stageOptions({
439
+ provider: planRoute.provider,
440
+ llmProvider: planRoute.llmProvider,
441
+ model: planRoute.model,
442
+ label: `${project} 规划`,
443
+ stageKey: 'plan',
444
+ prompt: `${plannerContract}${plannerContract === '' ? '' : '\n\n'}${PLANNER_PROMPT(requirementText, constraints, (await listFiles(cwd)).join('\n'))}`
445
+ + (aesthetic.enabled === true ? `${planNote(aesthetic.carriers)}\n${ceilingPlanNote(aesthetic.carriers)}\n${describePatterns(patterns)}` : '')
446
+ + domainPlanNote(domain),
447
+ }))
448
+ if (quickMode) {
449
+ await writeState(cwd, project, { stage: 2, status: 'plan-skipped' })
450
+ await logLine(cwd, project, '快速模式:跳过规划,按 Requirement.md 直接实施')
451
+ }
408
452
  noteRoute(planned.routeNote)
409
453
  await watchdog?.afterStage(planned)
410
454
  await recordCost()
@@ -935,22 +979,44 @@ export function createPipeline(ctx) {
935
979
  llmProvider: settings.checkProvider,
936
980
  model: settings.checkModel,
937
981
  })
938
- const checked = await runStage(ctx, stageOptions({
939
- provider: checkRoute.provider,
940
- llmProvider: checkRoute.llmProvider,
941
- model: checkRoute.model,
942
- label: `${project} 质检${rework === 0 ? '' : ` R${rework}`}`,
943
- stageKey: 'check',
944
- // 质检只读三个文件加一份 diff,不碰内存里的 intent / planText / buildSummary。
945
- // 它要判断的是「落盘的东西够不够」,不是「有人在对话里说了什么」。
946
- // diff 从快照仓库算,是这一轮真实改了什么——自述可以说假话,diff 不会。
947
- // 视觉类任务还要把预览图一并塞进去:看不见就别评。
948
- prompt: qaText,
949
- promptParts: qaText === '' ? undefined : [
950
- { type: 'text', text: qaText },
951
- ...preview.parts,
952
- ],
953
- }))
982
+ // ── 快速模式:判据说清了就不派质检子会话 ──────────────────────
983
+ //
984
+ // 只在「每条要求都有 check,而且这次全过」时才跳过。这不是放水:
985
+ // 退出码已经逐条回答了「做到没有」,模型再来一遍只是复述。
986
+ // 反过来说,只要有一条没过、或者有要求没写 check,就老老实实派子会话,
987
+ // 和完整模式一模一样。
988
+ const quickQa = quickMode && criteriaInPlay(assertions) && gate.verdict === 'PASS'
989
+ if (quickQa) {
990
+ await logLine(cwd, project, '快速模式:check 全过,跳过质检子会话')
991
+ }
992
+ const checked = quickQa
993
+ ? {
994
+ ok: true,
995
+ stopReason: 'completed',
996
+ routeNote: '',
997
+ // 形状要和模型返回的一致,后面 parseJsonBlock 才认得出来
998
+ text: JSON.stringify({
999
+ verdict: 'PASS',
1000
+ issues: [],
1001
+ note: '快速模式:Requirement.md 里的 check 全过,没有派质检子会话复核',
1002
+ }),
1003
+ }
1004
+ : await runStage(ctx, stageOptions({
1005
+ provider: checkRoute.provider,
1006
+ llmProvider: checkRoute.llmProvider,
1007
+ model: checkRoute.model,
1008
+ label: `${project} 质检${rework === 0 ? '' : ` R${rework}`}`,
1009
+ stageKey: 'check',
1010
+ // 质检只读三个文件加一份 diff,不碰内存里的 intent / planText / buildSummary。
1011
+ // 它要判断的是「落盘的东西够不够」,不是「有人在对话里说了什么」。
1012
+ // diff 从快照仓库算,是这一轮真实改了什么——自述可以说假话,diff 不会。
1013
+ // 视觉类任务还要把预览图一并塞进去:看不见就别评。
1014
+ prompt: qaText,
1015
+ promptParts: qaText === '' ? undefined : [
1016
+ { type: 'text', text: qaText },
1017
+ ...preview.parts,
1018
+ ],
1019
+ }))
954
1020
  noteRoute(checked.routeNote)
955
1021
  await watchdog?.afterStage(checked)
956
1022
  await recordCost()
@@ -53,6 +53,20 @@ export const Config = z.object({
53
53
  * 'auto' 这一档甚至不在合法值里,写了会被悄悄归一成 strict。
54
54
  */
55
55
  flowGate: z.string().default('off'),
56
+ /**
57
+ * 交付模式。
58
+ *
59
+ * safe —— 规划、实施、质检各开一个子会话,四阶完整走。默认。
60
+ * quick —— 跳过规划和质检这两次子会话:任务书直接取 Requirement.md 原文,
61
+ * 质检在「每条要求都有 check 且全过」时免掉模型复核。
62
+ *
63
+ * quick 不省判断,只省两次子会话:命令的退出码照样逐条跑,任何一条没过、
64
+ * 或者有要求没写 check,就退回派子会话,跟 safe 一样。
65
+ *
66
+ * 这是给「改一行配置」「修个错别字」这类活准备的。同一套流程硬套在它们
67
+ * 身上,用户会觉得还不如直接跟 agent 说话——流程重不重,得配得上这件事。
68
+ */
69
+ deliveryMode: z.string().default('safe'),
56
70
  /**
57
71
  * 第一次在普通目录开工时,自动把「工作流」目录建出来。
58
72
  * 只有 flowGate 为 strict 时才起作用:off / auto 下根本不会走到这一步。