dsh-project-flow 0.9.2 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +0 -0
  2. package/README.md +25 -0
  3. package/checks/assertion.mjs +104 -0
  4. package/checks/command.mjs +416 -0
  5. package/checks/requirement.mjs +91 -0
  6. package/commands/slash.mjs +754 -0
  7. package/commands/steer.mjs +43 -0
  8. package/config/settings.mjs +217 -0
  9. package/docs/DETAIL.md +2 -0
  10. package/docs/FEATURES.md +9 -6
  11. package/docs/anchors/file-whitelist.md +1 -1
  12. package/http/routes.mjs +252 -0
  13. package/index.js +173 -8538
  14. package/issues/issue.mjs +322 -0
  15. package/package.json +16 -1
  16. package/persistence/lock.mjs +67 -0
  17. package/persistence/log.mjs +43 -0
  18. package/persistence/recovery.mjs +118 -0
  19. package/persistence/state.mjs +202 -0
  20. package/pricing/estimate.mjs +72 -0
  21. package/prompts/rules.mjs +192 -0
  22. package/rollback/ledger.mjs +237 -0
  23. package/runner/pipeline.mjs +1190 -0
  24. package/runner/stage.mjs +370 -0
  25. package/runner/tools/context.mjs +64 -0
  26. package/runner/tools/decorate-cost.mjs +49 -0
  27. package/runner/tools/doctor.mjs +59 -0
  28. package/runner/tools/estimate.mjs +63 -0
  29. package/runner/tools/execute-run.mjs +255 -0
  30. package/runner/tools/models.mjs +55 -0
  31. package/runner/tools/resume.mjs +136 -0
  32. package/runner/tools/rollback.mjs +291 -0
  33. package/runner/tools/run.mjs +262 -0
  34. package/runner/tools/set.mjs +65 -0
  35. package/runner/tools/snapshots.mjs +83 -0
  36. package/runner/tools/status.mjs +70 -0
  37. package/runner/tools.mjs +94 -0
  38. package/shared/constants.mjs +273 -0
  39. package/shared/tool.mjs +32 -0
  40. package/shared/util.mjs +231 -0
  41. package/snapshot/repo.mjs +452 -0
  42. package/state/registry.mjs +40 -0
  43. package/tests/aesthetic.test.mjs +20 -12
  44. package/tests/apply-wiring.test.mjs +172 -0
  45. package/tests/assertions-e2e.mjs +2 -1
  46. package/tests/atomic-write.test.mjs +129 -0
  47. package/tests/client-bundle.test.mjs +3 -3
  48. package/tests/command-whitelist.test.mjs +135 -0
  49. package/tests/contract.test.mjs +2 -2
  50. package/tests/desktop.test.mjs +2 -2
  51. package/tests/domains.test.mjs +10 -7
  52. package/tests/e2e.mjs +2 -1
  53. package/tests/extra-phase.test.mjs +2 -2
  54. package/tests/feedback.test.mjs +2 -1
  55. package/tests/flow-gate.test.mjs +16 -56
  56. package/tests/issues-e2e.mjs +2 -1
  57. package/tests/panel-independence.test.mjs +2 -2
  58. package/tests/panel-report.test.mjs +2 -2
  59. package/tests/paths.mjs +70 -1
  60. package/tests/preview-path.test.mjs +2 -1
  61. package/tests/qa-assertions.test.mjs +10 -3
  62. package/tests/run-all.mjs +6 -0
  63. package/tests/snapshot-core.test.mjs +234 -0
  64. package/tests/stage-model.test.mjs +2 -2
  65. package/tests/steer-command.test.mjs +151 -0
  66. package/tests/stop-resume.test.mjs +7 -2
  67. package/tests/watch-root.test.mjs +2 -1
  68. package/ui/prompt.mjs +101 -0
  69. package/workspace/models.mjs +111 -0
  70. package/workspace/panel.mjs +359 -0
  71. package/workspace/paths.mjs +393 -0
  72. package/workspace/resume.mjs +107 -0
@@ -0,0 +1,359 @@
1
+ /**
2
+ * 状态栏数据:一行摘要、整张表、面板缓存、预览图。
3
+ */
4
+ import { readdir, stat, readFile, mkdir } from 'node:fs/promises'
5
+ import { join } from 'node:path'
6
+ import { PREVIEW_DIR } from '../aesthetic.mjs'
7
+ import { parseAssertionBlock, parseIssueBlock } from '../issues/issue.mjs'
8
+ import { readArtifact, readState } from '../persistence/state.mjs'
9
+ import { ARTIFACT, LIST_MAX_DEPTH, LIST_MAX_ENTRIES, LIST_SKIP_DIRS, MEDIA_TYPES, STAGE_LABEL } from '../shared/constants.mjs'
10
+ import { PKG_VERSION, dirExists, nowIso, stateDir, writeFileAtomic } from '../shared/util.mjs'
11
+ import { flowModeOf, flowRootConfigured, flowRootOf, flowRootTargetOf, focusOf, insideFlow, isScratchPath, watchRootOf } from './paths.mjs'
12
+ import { pfState } from '../state/registry.mjs'
13
+
14
+ export function statusLine(state) {
15
+ if (state === undefined) return '没有这个项目'
16
+ const stage = state.stage === undefined ? '?' : state.stage
17
+ if (stage === 0) return `${state.project}:还没开跑 —— ${state.status ?? '未开始'}`
18
+ const label = STAGE_LABEL[stage] ?? '?'
19
+ const rework = state.rework === undefined || state.rework === 0 ? '' : `,已返工 ${state.rework} 次`
20
+ const line = `${state.project}:第 ${stage} 段「${label}」 · ${state.status}${rework}`
21
+ const tail = []
22
+ if (typeof state.interruptedAt === 'string' && state.interruptedAt !== '') {
23
+ tail.push(`上次中断于 ${state.interruptedAt},跑 project_resume 续上`)
24
+ }
25
+ if (typeof state.lastError === 'string' && state.lastError !== '') {
26
+ tail.push(`最后错误:${state.lastError.slice(0, 200)}`)
27
+ }
28
+ return tail.length === 0 ? line : `${line}\n └ ${tail.join(';')}`
29
+ }
30
+
31
+ export async function listProjectLines(cwd) {
32
+ let names = []
33
+ try {
34
+ const entries = await readdir(join(cwd, '.project-flow'), { withFileTypes: true })
35
+ names = entries.filter(entry => entry.isDirectory()).map(entry => entry.name)
36
+ } catch {
37
+ return []
38
+ }
39
+ const lines = []
40
+ for (const project of names.sort()) {
41
+ const state = await readState(cwd, project)
42
+ lines.push(state === undefined ? `${project}:state.json 缺失,可用 project_doctor 修` : statusLine(state))
43
+ }
44
+ return lines
45
+ }
46
+
47
+ export async function listFiles(dir, limit = 60) {
48
+ const found = []
49
+ let entries = 0
50
+ let queue = [{ path: '', depth: 0 }]
51
+ try {
52
+ while (queue.length > 0 && found.length < limit * 6 && entries < LIST_MAX_ENTRIES) {
53
+ const next = []
54
+ for (const current of queue) {
55
+ if (entries >= LIST_MAX_ENTRIES) break
56
+ let dirents
57
+ try {
58
+ dirents = await readdir(current.path === '' ? dir : join(dir, current.path), { withFileTypes: true })
59
+ } catch {
60
+ continue
61
+ }
62
+ for (const dirent of dirents) {
63
+ entries += 1
64
+ if (entries > LIST_MAX_ENTRIES) break
65
+ const relative = current.path === '' ? dirent.name : `${current.path}/${dirent.name}`
66
+ if (dirent.isDirectory()) {
67
+ if (LIST_SKIP_DIRS.has(dirent.name)) continue
68
+ if (current.depth + 1 > LIST_MAX_DEPTH) continue
69
+ next.push({ path: relative, depth: current.depth + 1 })
70
+ continue
71
+ }
72
+ if (dirent.isFile()) found.push(relative)
73
+ }
74
+ }
75
+ queue = next
76
+ }
77
+ } catch {
78
+ return found.slice(0, limit)
79
+ }
80
+ return found.slice(0, limit)
81
+ }
82
+
83
+ export async function previewImageParts(cwd, project, limit = 8, budgetBytes = 6 * 1024 * 1024) {
84
+ // 提示词让子会话导出到「项目目录下的 preview/」,也就是 cwd/preview。
85
+ // 之前这里读的是 stateDir(cwd, project) —— 那是 .project-flow/<项目>/,
86
+ // 里面只有 snap.git 和几个 md,一张图都没有。于是 40 张预览图躺在
87
+ // cwd/preview 里没人看,质检每次都判「没有预览图」然后 FAIL、返工,
88
+ // 白烧几轮。读的地方必须和写的地方是同一个。
89
+ const primary = join(cwd, PREVIEW_DIR)
90
+ const first = await collectPreviewParts(primary, limit, budgetBytes)
91
+ if (first.parts.length > 0) return first
92
+ // 有任务会把图放进状态目录,两种都认,先认约定的那个
93
+ const fallback = await collectPreviewParts(join(stateDir(cwd, project), PREVIEW_DIR), limit, budgetBytes)
94
+ return fallback.parts.length > 0 ? fallback : first
95
+ }
96
+
97
+ export async function collectPreviewParts(dir, limit = 8, budgetBytes = 6 * 1024 * 1024) {
98
+ let names = []
99
+ try {
100
+ names = (await readdir(dir)).filter(name => MEDIA_TYPES[name.slice(name.lastIndexOf('.')).toLowerCase()] !== undefined)
101
+ } catch {
102
+ return { parts: [], note: '没有预览图' }
103
+ }
104
+ names.sort()
105
+ const parts = []
106
+ let bytes = 0
107
+ let skipped = 0
108
+ for (const name of names) {
109
+ if (parts.length >= limit) {
110
+ skipped += 1
111
+ continue
112
+ }
113
+ const path = join(dir, name)
114
+ try {
115
+ const info = await stat(path)
116
+ if (info.size > budgetBytes - bytes) {
117
+ skipped += 1
118
+ continue
119
+ }
120
+ const data = (await readFile(path)).toString('base64')
121
+ bytes += info.size
122
+ parts.push({
123
+ type: 'image',
124
+ mediaType: MEDIA_TYPES[name.slice(name.lastIndexOf('.')).toLowerCase()],
125
+ data,
126
+ name,
127
+ })
128
+ } catch {
129
+ skipped += 1
130
+ }
131
+ }
132
+ if (parts.length === 0) return { parts: [], note: `preview/ 里有 ${names.length} 个文件但一个都读不出来` }
133
+ const size = Math.round(bytes / 1024)
134
+ return {
135
+ parts,
136
+ note: `喂了 ${parts.length} 张预览图(共 ${size}KB)${skipped === 0 ? '' : `,另有 ${skipped} 张因限额跳过`}`,
137
+ }
138
+ }
139
+
140
+ export async function writePanelFile(cwd, settings) {
141
+ // 只在工作流目录里落这份:否则在普通目录改一下模型,状态栏就会在那边点亮,
142
+ // 而那个目录其实不接受工作模式。
143
+ if (!insideFlow(cwd, settings)) return undefined
144
+ const route = (llmProvider, model) => (model === '' ? '继承主对话' : `${llmProvider}/${model}`)
145
+ const payload = {
146
+ routes: {
147
+ intent: settings.intentModel === '' ? '主对话当前模型' : settings.intentModel,
148
+ plan: route(settings.planProvider === '' ? '默认路由' : settings.planProvider, settings.planModel),
149
+ build: route(settings.buildProvider === '' ? '默认路由' : settings.buildProvider, settings.buildModel),
150
+ check: route(settings.checkProvider === '' ? '默认路由' : settings.checkProvider, settings.checkModel),
151
+ },
152
+ maxRework: settings.maxRework,
153
+ concurrency: settings.maxConcurrentProjects,
154
+ updatedAt: nowIso(),
155
+ }
156
+ try {
157
+ await mkdir(join(cwd, '.project-flow'), { recursive: true })
158
+ await writeFileAtomic(join(cwd, '.project-flow', 'panel.json'), `${JSON.stringify(payload, null, 2)}\n`)
159
+ } catch {
160
+ // 写不进去只影响状态栏显示,不该拖累正在跑的东西
161
+ }
162
+ return payload
163
+ }
164
+
165
+ export async function panelReportOf(watch, name) {
166
+ let text
167
+ try {
168
+ text = await readArtifact(watch, name, ARTIFACT.qa)
169
+ } catch {
170
+ text = undefined
171
+ }
172
+ const empty = { issues: [], assertions: { total: 0, pass: 0, fail: 0, unverified: 0 }, failed: [] }
173
+ if (typeof text !== 'string' || text.trim() === '') return empty
174
+
175
+ const all = parseIssueBlock(text)
176
+ const assertions = parseAssertionBlock(text)
177
+ const count = status => assertions.filter(item => item.status === status).length
178
+ return {
179
+ issues: all
180
+ .filter(item => item.status === 'open' || item.status === 'reopened')
181
+ .map(item => ({
182
+ id: typeof item.id === 'string' ? item.id : '',
183
+ severity: typeof item.severity === 'string' ? item.severity : '',
184
+ location: typeof item.location === 'string' ? item.location.slice(0, 120) : '',
185
+ claim: typeof item.claim === 'string' ? item.claim.slice(0, 160) : '',
186
+ detect: typeof item.detect === 'string' ? item.detect.slice(0, 160) : '',
187
+ status: item.status,
188
+ })),
189
+ assertions: {
190
+ total: assertions.length,
191
+ pass: count('pass'),
192
+ fail: count('fail'),
193
+ unverified: count('unverified'),
194
+ },
195
+ // 挂掉的命令单独拎出来。面板上要显示「哪一条、退出码多少」——
196
+ // 只说「失败 1 条」等于让人再去翻文件。
197
+ failed: assertions
198
+ .filter(item => item.status === 'fail' || item.status === 'timeout' || item.status === 'denied')
199
+ .map(item => ({
200
+ req: item.req,
201
+ cmd: typeof item.cmd === 'string' ? item.cmd.slice(0, 160) : '',
202
+ exit: Number.isInteger(item.exit) ? item.exit : null,
203
+ status: item.status,
204
+ })),
205
+ }
206
+ }
207
+
208
+ export async function panelSnapshot(cwd, settings, onlyProject, sessionId) {
209
+ const watch = await watchRootOf(cwd, settings)
210
+ const inside = insideFlow(cwd, settings)
211
+ // cwd 落在工作流根下面的哪个子目录——那就是「当前这个任务」。
212
+ // 人在 …\工作流\csv2md 里开会话,想看的是 csv2md,不是整张表。
213
+ const focus = focusOf(cwd, watch)
214
+ const route = (llmProvider, model) => (model === '' ? '继承主对话' : `${llmProvider}/${model}`)
215
+ let names = []
216
+ if (onlyProject !== undefined) {
217
+ names = [onlyProject]
218
+ } else {
219
+ try {
220
+ const entries = await readdir(join(watch, '.project-flow'), { withFileTypes: true })
221
+ names = entries.filter(entry => entry.isDirectory()).map(entry => entry.name).sort()
222
+ } catch {
223
+ names = []
224
+ }
225
+ }
226
+ const projects = []
227
+ for (const name of names) {
228
+ const state = await readState(watch, name)
229
+ if (state === undefined) continue
230
+ const stage = typeof state.stage === 'number' ? state.stage : 0
231
+ const runningEntry = pfState.panelStops.get(name)
232
+ projects.push({
233
+ project: name,
234
+ stage,
235
+ stageLabel: STAGE_LABEL[stage] ?? '?',
236
+ status: typeof state.status === 'string' ? state.status : '',
237
+ rework: typeof state.rework === 'number' ? state.rework : 0,
238
+ maxRework: typeof state.maxRework === 'number' ? state.maxRework : settings.maxRework,
239
+ // 未闭环问题数(P0+P1 的 open+reopened 数):阶段灯旁那个 open: N。
240
+ // 它和 rework 是两件事——一个是「还剩几件事」,一个是「花了几轮」。
241
+ open: typeof state.openCritical === 'number' ? state.openCritical : (typeof state.openIssues === 'number' ? state.openIssues : 0),
242
+ running: runningEntry !== undefined,
243
+ /**
244
+ * 这个项目是不是「你这个会话」开的。
245
+ *
246
+ * 两个项目同时跑的时候,running 会有两条,客户端以前取第一个,
247
+ * 于是两个会话的状态栏显示同一个项目——看起来就像状态栏不独立。
248
+ * 有了 mine,每个会话先认自己开的那个。
249
+ */
250
+ mine: runningEntry !== undefined
251
+ && sessionId !== undefined
252
+ && runningEntry.sessionId === sessionId,
253
+ /**
254
+ * 这个项目是不是「你这个对话」碰过的——跑完之后也算。
255
+ *
256
+ * mine 只覆盖「正在跑」,跑完就假了;状态栏靠这一条才能一个对话一个,
257
+ * 而不是所有对话都退回显示同一个项目。
258
+ *
259
+ * 三种值,缺一不可:
260
+ * true 归我
261
+ * false 不归我(这个项目有归属记录,但里面没有我这个会话)
262
+ * null 未知归属——升级之前跑的老项目没有 ownerSessions,
263
+ * 不能judge成「不是我的」,否则升级当天所有老项目一起消失
264
+ */
265
+ owned: sessionId !== undefined && Array.isArray(state.ownerSessions)
266
+ ? state.ownerSessions.includes(sessionId)
267
+ : null,
268
+ // 已花掉的钱:每阶结束都会落盘,状态栏直接读,不用再算
269
+ cost: state.cost === undefined ? undefined : {
270
+ cny: state.cost.spentCny,
271
+ usd: state.cost.spentUsd,
272
+ },
273
+ interruptedAt: state.interruptedAt ?? null,
274
+ updatedAt: state.updatedAt ?? null,
275
+ // 开工时间。面板要显示「这一轮跑了多久」——只有 updatedAt 算不出时长,
276
+ // 而 state 里本来就有这一项,不用另存。
277
+ startedAt: state.startedAt ?? null,
278
+ verdict: typeof state.verdict === 'string' ? state.verdict : '',
279
+ // 面板要能看到「还差哪几条」「哪条命令没过」。光有一个 open 数字
280
+ // 说不出事,用户还得去翻 QA_Report.md——那正是这个面板想省掉的一步。
281
+ //
282
+ // 读不到就返回空数组,不报错:没跑过质检的项目本来就没有这份报告。
283
+ report: await panelReportOf(watch, name),
284
+ })
285
+ }
286
+ const snapshot = {
287
+ // 面板顶栏那一行要显示插件版本。宿主自己读 package.json,不靠客户端猜。
288
+ version: PKG_VERSION,
289
+ // 算出来的时间。客户端靠它判断这份是不是自己刚触发的那一次——
290
+ // 缓存是全进程共用的,不校验时间就会读到别的栏(工作流/默认工作区)的数据。
291
+ at: nowIso(),
292
+ // root 是「状态栏正在看的那个目录」,不一定等于当前工作目录:
293
+ // 人在别处开会话时,看的仍然是他那个工作流。
294
+ root: watch,
295
+ // 只有「当前目录不能开工、而且看的确实是另一个目录」才算在看别处。
296
+ // 在 …\工作流\csv2md 里开会话时 root 虽然是上一层的根,但那还是自己家,
297
+ // 不能提示「当前目录不在工作流里」;反过来,没线索时看的就是当前目录,
298
+ // 也不算「看别处」。
299
+ watching: inside !== true && watch !== cwd,
300
+ // 当前会话落在工作流里的哪个项目目录下;空表示没对着具体项目
301
+ focus,
302
+ // inside 只回答「能不能在当前目录开工」,和上面那个是两件事。
303
+ inside,
304
+ // 当前会话自己的目录。用户看到状态栏写「在看 C:\…」时要能分辨
305
+ // 那是「我现在在哪儿」,不是「我的工作流在哪」。
306
+ cwd,
307
+ /**
308
+ * 你的工作流到底在哪个目录。
309
+ *
310
+ * 配置里写死的 flowRoot 优先,并且会往下找一层真的装着 .project-flow 的
311
+ * 「工作流」子目录。状态栏拿它来告诉用户「该切到哪儿」,
312
+ * 不再把会话所在的 C 盘目录当成工作流位置——那正是用户报的那个疑问:
313
+ * 「为什么工作流的目录是在 C 盘」。
314
+ */
315
+ wherePath: flowRootTargetOf(cwd, settings),
316
+ flowRootConfigured: flowRootConfigured(settings),
317
+ gate: flowModeOf(settings),
318
+ // 不在工作流目录、但会自动建的时候,把该建的路径告诉界面。
319
+ // 三个条件缺一不可:不在工作流里、确实在看当前目录(正在看别处时
320
+ // 不该劝人在当前位置再建一个)、而且那个目录真的还不存在——
321
+ // 它已经在那儿了还写「会自动建」就是在骗人。
322
+ willCreate: inside !== true
323
+ && watch === cwd
324
+ && settings.autoCreateFlowDir === true
325
+ && flowModeOf(settings) === 'strict'
326
+ && !await dirExists(flowRootOf(cwd, settings))
327
+ ? flowRootOf(cwd, settings)
328
+ : undefined,
329
+ domain: settings.domain ?? 'auto',
330
+ routes: {
331
+ intent: settings.intentModel === '' ? '主对话当前模型' : settings.intentModel,
332
+ plan: route(settings.planProvider === '' ? '默认路由' : settings.planProvider, settings.planModel),
333
+ build: route(settings.buildProvider === '' ? '默认路由' : settings.buildProvider, settings.buildModel),
334
+ check: route(settings.checkProvider === '' ? '默认路由' : settings.checkProvider, settings.checkModel),
335
+ },
336
+ concurrency: { running: pfState.panelStops.size, limit: settings.maxConcurrentProjects },
337
+ projects,
338
+ }
339
+ pfState.lastPanelReport = {
340
+ at: nowIso(),
341
+ cwd,
342
+ root: watch,
343
+ focus,
344
+ inside,
345
+ watching: watch !== cwd,
346
+ gate: flowModeOf(settings),
347
+ willCreate: snapshot.willCreate ?? null,
348
+ projects: projects.map(item => `${item.project}:第${item.stage}阶 ${item.status}`),
349
+ }
350
+ // 临时目录里算出来的不算数:测试、e2e 全在那儿跑。
351
+ // 让它覆盖缓存的话,真实会话会读到一份「没有项目的就绪」——
352
+ // 这个坑刚踩过:跑完测试,每个会话的状态栏都变成「就绪」。
353
+ if (!isScratchPath(cwd)) {
354
+ pfState.lastPanelByRoot.set(watch, snapshot)
355
+ pfState.lastPanelFull = snapshot
356
+ }
357
+ return snapshot
358
+ }
359
+