dsh-project-flow 0.9.3 → 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 (70) hide show
  1. package/CHANGELOG.md +197 -12
  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/FEATURES.md +9 -6
  10. package/docs/anchors/file-whitelist.md +1 -1
  11. package/http/routes.mjs +252 -0
  12. package/index.js +173 -8612
  13. package/issues/issue.mjs +322 -0
  14. package/package.json +16 -1
  15. package/persistence/lock.mjs +67 -0
  16. package/persistence/log.mjs +43 -0
  17. package/persistence/recovery.mjs +118 -0
  18. package/persistence/state.mjs +202 -0
  19. package/pricing/estimate.mjs +72 -0
  20. package/prompts/rules.mjs +192 -0
  21. package/rollback/ledger.mjs +237 -0
  22. package/runner/pipeline.mjs +1190 -0
  23. package/runner/stage.mjs +370 -0
  24. package/runner/tools/context.mjs +64 -0
  25. package/runner/tools/decorate-cost.mjs +49 -0
  26. package/runner/tools/doctor.mjs +59 -0
  27. package/runner/tools/estimate.mjs +63 -0
  28. package/runner/tools/execute-run.mjs +255 -0
  29. package/runner/tools/models.mjs +55 -0
  30. package/runner/tools/resume.mjs +136 -0
  31. package/runner/tools/rollback.mjs +291 -0
  32. package/runner/tools/run.mjs +262 -0
  33. package/runner/tools/set.mjs +65 -0
  34. package/runner/tools/snapshots.mjs +83 -0
  35. package/runner/tools/status.mjs +70 -0
  36. package/runner/tools.mjs +94 -0
  37. package/shared/constants.mjs +273 -0
  38. package/shared/tool.mjs +32 -0
  39. package/shared/util.mjs +231 -0
  40. package/snapshot/repo.mjs +452 -0
  41. package/state/registry.mjs +40 -0
  42. package/tests/aesthetic.test.mjs +20 -12
  43. package/tests/apply-wiring.test.mjs +172 -0
  44. package/tests/assertions-e2e.mjs +2 -1
  45. package/tests/atomic-write.test.mjs +129 -0
  46. package/tests/client-bundle.test.mjs +3 -3
  47. package/tests/command-whitelist.test.mjs +135 -0
  48. package/tests/contract.test.mjs +2 -2
  49. package/tests/desktop.test.mjs +2 -2
  50. package/tests/domains.test.mjs +10 -7
  51. package/tests/e2e.mjs +2 -1
  52. package/tests/extra-phase.test.mjs +2 -2
  53. package/tests/feedback.test.mjs +2 -1
  54. package/tests/flow-gate.test.mjs +16 -56
  55. package/tests/issues-e2e.mjs +2 -1
  56. package/tests/panel-independence.test.mjs +2 -2
  57. package/tests/panel-report.test.mjs +2 -2
  58. package/tests/paths.mjs +70 -1
  59. package/tests/preview-path.test.mjs +2 -1
  60. package/tests/qa-assertions.test.mjs +10 -3
  61. package/tests/run-all.mjs +5 -0
  62. package/tests/snapshot-core.test.mjs +234 -0
  63. package/tests/stage-model.test.mjs +2 -2
  64. package/tests/stop-resume.test.mjs +7 -2
  65. package/tests/watch-root.test.mjs +2 -1
  66. package/ui/prompt.mjs +101 -0
  67. package/workspace/models.mjs +111 -0
  68. package/workspace/panel.mjs +359 -0
  69. package/workspace/paths.mjs +393 -0
  70. package/workspace/resume.mjs +107 -0
@@ -0,0 +1,322 @@
1
+ /**
2
+ * 问题闭环:编号、复验、按 diff 判断有没有真碰到那处。
3
+ */
4
+ import { ISSUE_LIMIT, SEVERITIES } from '../shared/constants.mjs'
5
+ import { normalizeIssueText, quoteScalar, splitFrontMatter, unquoteScalar } from '../shared/util.mjs'
6
+
7
+ export function issueKeyOf(issue) {
8
+ const loc = normalizeIssueText(issue?.location).toLowerCase().replace(/^\.\//u, '')
9
+ const claim = normalizeIssueText(issue?.claim).toLowerCase()
10
+ .replace(/[,。;:、,.;:!?!?"'“”‘’()()]/gu, '')
11
+ return `${loc}\u0000${claim}`
12
+ }
13
+
14
+ export function normalizeIncomingIssues(raw) {
15
+ const list = Array.isArray(raw) ? raw : []
16
+ const out = []
17
+ for (const item of list) {
18
+ if (item === null || typeof item !== 'object' || Array.isArray(item)) continue
19
+ const severity = normalizeIssueText(item.severity).toUpperCase()
20
+ const issue = {
21
+ severity: SEVERITIES.includes(severity) ? severity : 'P1',
22
+ location: normalizeIssueText(item.location),
23
+ claim: normalizeIssueText(item.claim),
24
+ evidence: normalizeIssueText(item.evidence),
25
+ detect: normalizeIssueText(item.detect),
26
+ pass: normalizeIssueText(item.pass),
27
+ resolved: item.resolved === true,
28
+ }
29
+ if (issue.claim === '' && issue.location === '') continue
30
+ out.push(issue)
31
+ }
32
+ return out
33
+ }
34
+
35
+ export function parseAssertionBlock(text) {
36
+ const { front } = splitFrontMatter(text)
37
+ if (front === '') return []
38
+ const rows = []
39
+ let inBlock = false
40
+ let current
41
+ for (const rawLine of front.split(/\r?\n/u)) {
42
+ const line = rawLine.replace(/\s+$/u, '')
43
+ if (/^assertions\s*:\s*(\[\])?\s*$/u.test(line)) {
44
+ inBlock = true
45
+ continue
46
+ }
47
+ // 顶格的非空行意味着这一段结束了。
48
+ if (inBlock && /^[A-Za-z_]\w*\s*:/u.test(line)) {
49
+ inBlock = false
50
+ current = undefined
51
+ }
52
+ if (!inBlock) continue
53
+ const start = /^\s*-\s*req\s*:\s*(.+)$/u.exec(line)
54
+ if (start !== null) {
55
+ const req = Number.parseInt(unquoteScalar(start[1]), 10)
56
+ current = { req: Number.isInteger(req) ? req : rows.length + 1 }
57
+ rows.push(current)
58
+ continue
59
+ }
60
+ if (current === undefined) continue
61
+ const field = /^\s+(cmd|exit|durationMs|status)\s*:\s*(.*)$/u.exec(line)
62
+ if (field === null) continue
63
+ const [, key, rawValue] = field
64
+ const value = unquoteScalar(rawValue)
65
+ if (key === 'cmd') current.cmd = value
66
+ else if (key === 'status') current.status = value
67
+ else {
68
+ const num = Number.parseInt(value, 10)
69
+ current[key] = Number.isInteger(num) ? num : null
70
+ }
71
+ }
72
+ return rows
73
+ }
74
+
75
+ export function parseIssueBlock(text) {
76
+ const { front } = splitFrontMatter(text)
77
+ if (front === '') return []
78
+ const issues = []
79
+ let inIssues = false
80
+ let current
81
+ for (const rawLine of front.split(/\r?\n/u)) {
82
+ const line = rawLine.replace(/\s+$/u, '')
83
+ if (/^issues\s*:\s*(\[\])?\s*$/u.test(line)) {
84
+ inIssues = true
85
+ continue
86
+ }
87
+ if (inIssues && /^[A-Za-z_]\w*\s*:/u.test(line)) {
88
+ inIssues = false
89
+ current = undefined
90
+ }
91
+ if (!inIssues) continue
92
+ const start = /^\s*-\s*id\s*:\s*(.*)$/u.exec(line)
93
+ if (start !== null) {
94
+ current = { id: unquoteScalar(start[1]) }
95
+ issues.push(current)
96
+ continue
97
+ }
98
+ if (current === undefined) continue
99
+ const field = /^\s+(severity|location|claim|evidence|detect|pass|status|note)\s*:\s*(.*)$/u.exec(line)
100
+ if (field === null) {
101
+ const rounds = /^\s+rounds\s*:\s*(\d+)\s*$/u.exec(line)
102
+ if (rounds !== null && current !== undefined) current.roundsOpen = Number(rounds[1])
103
+ continue
104
+ }
105
+ current[field[1]] = unquoteScalar(field[2])
106
+ }
107
+ return issues.filter(item => typeof item.id === 'string' && item.id !== '')
108
+ }
109
+
110
+ export function issueLines(issue) {
111
+ const lines = [
112
+ ` - id: ${quoteScalar(issue.id)}`,
113
+ ` severity: ${quoteScalar(issue.severity)}`,
114
+ ` location: ${quoteScalar(issue.location)}`,
115
+ ` claim: ${quoteScalar(issue.claim)}`,
116
+ ` evidence: ${quoteScalar(issue.evidence)}`,
117
+ ` detect: ${quoteScalar(issue.detect)}`,
118
+ ` pass: ${quoteScalar(issue.pass)}`,
119
+ ` status: ${quoteScalar(issue.status)}`,
120
+ ]
121
+ if (typeof issue.note === 'string' && issue.note !== '') lines.push(` note: ${quoteScalar(issue.note)}`)
122
+ // 连续几轮没闭环。用来触发「别再无脑返工了」的那道闸,
123
+ // 和 maxRework 不是一回事:maxRework 数的是整轮,这个数的是同一条问题。
124
+ if (Number.isInteger(issue.roundsOpen) && issue.roundsOpen > 0) lines.push(` rounds: ${issue.roundsOpen}`)
125
+ return lines
126
+ }
127
+
128
+ export function mergeIssueRounds(previous, incoming, diffText) {
129
+ const prev = Array.isArray(previous) ? previous : []
130
+ const next = Array.isArray(incoming) ? incoming : []
131
+ let maxIndex = 0
132
+ for (const item of prev) {
133
+ const match = /^Q-(\d+)$/u.exec(String(item?.id ?? ''))
134
+ if (match !== null) maxIndex = Math.max(maxIndex, Number(match[1]))
135
+ }
136
+ const byKey = new Map()
137
+ for (const item of prev) byKey.set(issueKeyOf(item), item)
138
+ const touched = new Set()
139
+ const issues = []
140
+ const reopened = []
141
+ const invalid = []
142
+
143
+ for (const item of next) {
144
+ const key = issueKeyOf(item)
145
+ const old = byKey.get(key)
146
+ const missing = normalizeIssueText(item.detect) === '' || normalizeIssueText(item.pass) === ''
147
+ if (old !== undefined && touched.has(old.id) !== true) {
148
+ touched.add(old.id)
149
+ const sameFile = diffTouches(diffText, item.location)
150
+ if (old.status === 'closed') {
151
+ if (item.resolved === true) continue
152
+ if (sameFile !== true) continue
153
+ const revived = { ...old, ...item, id: old.id, status: 'reopened', note: '上一轮判 closed,这一轮 diff 又动了同一处' }
154
+ issues.push(revived)
155
+ reopened.push(revived)
156
+ continue
157
+ }
158
+ const status = item.resolved === true ? 'closed' : missing ? 'invalid' : 'open'
159
+ const roundsOpen = status === 'closed' ? 0 : (Number.isInteger(old.roundsOpen) ? old.roundsOpen : 0) + 1
160
+ const merged = {
161
+ ...old,
162
+ ...item,
163
+ id: old.id,
164
+ status,
165
+ roundsOpen,
166
+ ...(missing ? { note: '缺少 detect 或 pass,验不了' } : {}),
167
+ }
168
+ issues.push(merged)
169
+ if (status === 'invalid') invalid.push(merged)
170
+ continue
171
+ }
172
+ // 新问题:发新号。同一轮里重复描述的,认第一个。
173
+ if ([...issues, ...prev].some(candidate => issueKeyOf(candidate) === key)) continue
174
+ maxIndex += 1
175
+ const id = `Q-${String(maxIndex).padStart(3, '0')}`
176
+ const status = missing ? 'invalid' : item.resolved === true ? 'closed' : 'open'
177
+ const created = { ...item, id, status, ...(missing ? { note: '缺少 detect 或 pass,验不了' } : {}) }
178
+ issues.push(created)
179
+ if (status === 'invalid') invalid.push(created)
180
+ }
181
+
182
+ // 模型没提到的上轮问题:原样留下。不提到不等于修好,这条是闭环能不能信的关键。
183
+ for (const item of prev) {
184
+ if (touched.has(item.id)) continue
185
+ if (item.status === 'closed') continue
186
+ issues.push({
187
+ ...item,
188
+ roundsOpen: (Number.isInteger(item.roundsOpen) ? item.roundsOpen : 0) + 1,
189
+ })
190
+ }
191
+
192
+ // 条数超限:先保 P0/P1,其余标 deferred,不参与返工判据。
193
+ const processed = []
194
+ const deferred = []
195
+ for (const item of issues) {
196
+ const counts = item.status === 'open' || item.status === 'reopened' || item.status === 'invalid'
197
+ if (counts && item.severity === 'P2' && issues.length > ISSUE_LIMIT) {
198
+ deferred.push({ ...item, status: 'deferred' })
199
+ continue
200
+ }
201
+ processed.push(item)
202
+ }
203
+ const finalList = processed.concat(deferred)
204
+ const open = finalList.filter(item => item.status === 'open' || item.status === 'reopened')
205
+ // 同一条问题连着三轮没闭环:再多返工也是原地打转,这道闸比 maxRework 更早响。
206
+ const stuck = open.filter(item => (Number.isInteger(item.roundsOpen) ? item.roundsOpen : 0) >= 3)
207
+ return {
208
+ issues: finalList,
209
+ open,
210
+ openCount: open.length,
211
+ openP0P1: open.filter(item => item.severity === 'P0' || item.severity === 'P1').length,
212
+ reopened,
213
+ invalid,
214
+ deferred,
215
+ stuck,
216
+ }
217
+ }
218
+
219
+ export function diffTouches(diffText, location) {
220
+ const text = typeof diffText === 'string' ? diffText : ''
221
+ const loc = normalizeIssueText(location)
222
+ if (text === '' || loc === '') return false
223
+ const filePart = loc.split(':')[0].trim().replace(/^\.\//u, '').replace(/^[ab]\//u, '')
224
+ if (filePart === '') return false
225
+ const lineMatch = /:(\d+)/u.exec(loc)
226
+ const line = lineMatch === null ? undefined : Number(lineMatch[1])
227
+ let currentFile = ''
228
+ let range
229
+ for (const rawLine of text.split(/\r?\n/u)) {
230
+ const header = /^\+\+\+ b\/(.+)$/u.exec(rawLine)
231
+ if (header !== null) {
232
+ currentFile = header[1].trim()
233
+ range = undefined
234
+ continue
235
+ }
236
+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/u.exec(rawLine)
237
+ if (hunk !== null) {
238
+ range = { start: Number(hunk[1]), count: hunk[2] === undefined ? 1 : Number(hunk[2]) }
239
+ continue
240
+ }
241
+ if (currentFile === '' || range === undefined) continue
242
+ if (currentFile !== filePart && currentFile.endsWith(`/${filePart}`) !== true) continue
243
+ if (line === undefined) return true
244
+ const end = range.start + Math.max(range.count, 1) - 1
245
+ if (line >= range.start && line <= end) return true
246
+ }
247
+ return false
248
+ }
249
+
250
+ export function parseIssueTables(text) {
251
+ const source = typeof text === 'string' ? text : ''
252
+ const lines = source.split(/\r?\n/u)
253
+ const issues = []
254
+ for (let index = 0; index < lines.length; index += 1) {
255
+ const header = lines[index].trim()
256
+ if (header.startsWith('|') !== true || /^\|[\s:-]+\|/u.test(header)) continue
257
+ const cells = header.split('|').map(cell => cell.trim()).filter((cell, at, all) => at > 0 && at < all.length - 1)
258
+ const severityAt = cells.findIndex(cell => /^(严重级|严重程度|severity|优先级|级别)$/iu.test(cell))
259
+ if (severityAt === -1) {
260
+ // 整张跳过:没有声明严重级的表,说什么都不算缺陷清单。
261
+ while (index < lines.length && lines[index].trim().startsWith('|')) index += 1
262
+ continue
263
+ }
264
+ const pick = names => cells.findIndex(cell => names.some(name => new RegExp(name, 'iu').test(cell)))
265
+ const locationAt = pick(['位置', 'location', '文件'])
266
+ const claimAt = pick(['问题', 'claim', '描述', '缺陷'])
267
+ const evidenceAt = pick(['证据', 'evidence'])
268
+ const detectAt = pick(['检测', 'detect', '复现', '怎么验'])
269
+ const passAt = pick(['通过', 'pass', '验收', '标准'])
270
+ let row = index + 1
271
+ if (row < lines.length && /^\|[\s:|-]+\|$/u.test(lines[row].trim())) row += 1
272
+ for (; row < lines.length; row += 1) {
273
+ const line = lines[row].trim()
274
+ if (line.startsWith('|') !== true) break
275
+ const cellsOfRow = line.split('|').map(cell => cell.trim()).filter((cell, at, all) => at > 0 && at < all.length - 1)
276
+ const severity = (cellsOfRow[severityAt] ?? '').toUpperCase()
277
+ if (SEVERITIES.includes(severity) !== true) continue
278
+ issues.push({
279
+ severity,
280
+ location: locationAt === -1 ? '' : cellsOfRow[locationAt] ?? '',
281
+ claim: claimAt === -1 ? '' : cellsOfRow[claimAt] ?? '',
282
+ evidence: evidenceAt === -1 ? '' : cellsOfRow[evidenceAt] ?? '',
283
+ detect: detectAt === -1 ? '' : cellsOfRow[detectAt] ?? '',
284
+ pass: passAt === -1 ? '' : cellsOfRow[passAt] ?? '',
285
+ })
286
+ }
287
+ index = row - 1
288
+ }
289
+ return issues
290
+ }
291
+
292
+ export function renderFixLog(fixes, round) {
293
+ const list = Array.isArray(fixes) ? fixes : []
294
+ if (list.length === 0) return ''
295
+ const lines = [`## 本轮修复(R${round})`, '']
296
+ for (const item of list) {
297
+ const id = normalizeIssueText(item?.id) || 'Q-???'
298
+ const change = normalizeIssueText(item?.change) || '(没写改了什么)'
299
+ const command = normalizeIssueText(item?.command)
300
+ const result = normalizeIssueText(item?.result)
301
+ lines.push(`- ${id} → ${change}${command === '' ? '' : ` → \`${command}\``} → ${result === '' ? '(没写结果)' : result}`)
302
+ }
303
+ return lines.join('\n')
304
+ }
305
+
306
+ export function renderKnownIssues(issues) {
307
+ const list = Array.isArray(issues) ? issues : []
308
+ const open = list.filter(item => item.status === 'open' || item.status === 'reopened')
309
+ if (open.length === 0) return ''
310
+ const lines = [
311
+ '## 上一轮还没闭环的问题(逐条回答,别重新编号)',
312
+ '',
313
+ ]
314
+ for (const item of open) {
315
+ lines.push(`- ${item.id}|${item.severity}|${item.location || '(没写位置)'}|${item.claim}`)
316
+ if (item.pass !== '') lines.push(` 通过标准:${item.pass}`)
317
+ if (item.detect !== '') lines.push(` 检测方式:${item.detect}`)
318
+ }
319
+ lines.push('', '修好了就在这一轮的 issues 里带上同一个 id 并写 "resolved": true;没修就照原样再列一遍。')
320
+ return lines.join('\n')
321
+ }
322
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-project-flow",
3
- "version": "0.9.3",
3
+ "version": "0.10.1",
4
4
  "private": false,
5
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.",
6
6
  "type": "module",
@@ -49,6 +49,21 @@
49
49
  "tests/*.mjs",
50
50
  "index.js",
51
51
  "client.js",
52
+ "shared/",
53
+ "state/",
54
+ "config/",
55
+ "persistence/",
56
+ "snapshot/",
57
+ "rollback/",
58
+ "checks/",
59
+ "issues/",
60
+ "runner/",
61
+ "prompts/",
62
+ "workspace/",
63
+ "pricing/",
64
+ "http/",
65
+ "commands/",
66
+ "ui/",
52
67
  "gate.mjs",
53
68
  "flow.schema.mjs",
54
69
  "watchdog.mjs",
@@ -0,0 +1,67 @@
1
+ /**
2
+ * 项目锁:活着的持有者挡住,死掉的持有者把锁挪到一边当证据。
3
+ */
4
+ import { join } from 'node:path'
5
+ import { readFile, mkdir, rename, writeFile, rm } from 'node:fs/promises'
6
+ import { isAlive, nowIso, stateDir, writeFileAtomic } from '../shared/util.mjs'
7
+
8
+ export function lockFile(cwd, project) {
9
+ return join(stateDir(cwd, project), 'run.lock')
10
+ }
11
+
12
+ export async function readLock(cwd, project) {
13
+ try {
14
+ const parsed = JSON.parse(await readFile(lockFile(cwd, project), 'utf8'))
15
+ return parsed !== null && typeof parsed === 'object' ? parsed : undefined
16
+ } catch {
17
+ return undefined
18
+ }
19
+ }
20
+
21
+ export async function acquireLock(cwd, project, settings) {
22
+ await mkdir(stateDir(cwd, project), { recursive: true })
23
+ const file = lockFile(cwd, project)
24
+ const existing = await readLock(cwd, project)
25
+ if (existing !== undefined) {
26
+ const beat = Date.parse(existing.heartbeatAt ?? existing.startedAt ?? '')
27
+ const age = Number.isFinite(beat) ? Date.now() - beat : Number.POSITIVE_INFINITY
28
+ const other = existing.pid !== process.pid && isAlive(existing.pid)
29
+ if (other && age < settings.staleLockMs) return { ok: false, holder: existing }
30
+ try {
31
+ await rename(file, `${file}.stale-${Date.now()}`)
32
+ } catch {
33
+ // if it cannot be moved, the write below still claims it
34
+ }
35
+ }
36
+ await writeFileAtomic(file, `${JSON.stringify({
37
+ pid: process.pid,
38
+ project,
39
+ startedAt: nowIso(),
40
+ heartbeatAt: nowIso(),
41
+ }, null, 2)}\n`)
42
+ return { ok: true, file }
43
+ }
44
+
45
+ export async function touchLock(cwd, project) {
46
+ const holder = await readLock(cwd, project)
47
+ if (holder === undefined || holder.pid !== process.pid) return
48
+ try {
49
+ await writeFile(lockFile(cwd, project), `${JSON.stringify({
50
+ ...holder,
51
+ heartbeatAt: nowIso(),
52
+ }, null, 2)}\n`, 'utf8')
53
+ } catch {
54
+ // heartbeat is advisory
55
+ }
56
+ }
57
+
58
+ export async function releaseLock(cwd, project) {
59
+ const holder = await readLock(cwd, project)
60
+ if (holder !== undefined && holder.pid !== process.pid) return
61
+ try {
62
+ await rm(lockFile(cwd, project), { force: true })
63
+ } catch {
64
+ // nothing to release
65
+ }
66
+ }
67
+
@@ -0,0 +1,43 @@
1
+ /**
2
+ * 运行日志与下一步提示。日志自己写失败不能拖垮一次运行。
3
+ */
4
+ import { mkdir, readFile, rename, appendFile } from 'node:fs/promises'
5
+ import { join } from 'node:path'
6
+ import { ARTIFACT, LOG_ROTATE_BYTES } from '../shared/constants.mjs'
7
+ import { nowIso, stateDir, writeFileAtomic } from '../shared/util.mjs'
8
+
9
+ export async function logLine(cwd, project, message) {
10
+ if (typeof project !== 'string' || project === '') return
11
+ try {
12
+ const dir = stateDir(cwd, project)
13
+ await mkdir(dir, { recursive: true })
14
+ const file = join(dir, 'run.log')
15
+ let size = 0
16
+ try {
17
+ size = (await readFile(file, 'utf8')).length
18
+ } catch {
19
+ size = 0
20
+ }
21
+ if (size > LOG_ROTATE_BYTES) {
22
+ try {
23
+ await rename(file, `${file}.1`)
24
+ } catch {
25
+ // rotation is best effort
26
+ }
27
+ }
28
+ const line = `${nowIso()} ${String(message).replace(/\r?\n/gu, ' ')}\n`
29
+ await appendFile(join(dir, 'run.log'), line, 'utf8')
30
+ } catch {
31
+ // logging is diagnostics only
32
+ }
33
+ }
34
+
35
+ export async function writeNextStep(cwd, project, text) {
36
+ try {
37
+ await writeFileAtomic(join(stateDir(cwd, project), ARTIFACT.nextStep), `# 下一步\n\n${text.trim()}\n`)
38
+ } catch {
39
+ // 写不进去只少了份副本,note 里还有
40
+ }
41
+ return text
42
+ }
43
+
@@ -0,0 +1,118 @@
1
+ /**
2
+ * 自愈:从残留产物反推 state.json,把死锁和悬空阶段收拾干净。
3
+ */
4
+ import { readdir, rename } from 'node:fs/promises'
5
+ import { join } from 'node:path'
6
+ import { lockFile, readLock } from './lock.mjs'
7
+ import { readArtifact, readState, writeState } from './state.mjs'
8
+ import { ARTIFACT } from '../shared/constants.mjs'
9
+ import { extractSection, isAlive, nowIso, stateDir, withoutHeading } from '../shared/util.mjs'
10
+ import { pfState } from '../state/registry.mjs'
11
+
12
+ export async function repairState(cwd, project) {
13
+ const dir = stateDir(cwd, project)
14
+ let files
15
+ try {
16
+ files = await readdir(dir)
17
+ } catch {
18
+ return undefined
19
+ }
20
+ const logExists = files.includes(ARTIFACT.log)
21
+ const qaExists = files.includes(ARTIFACT.qa)
22
+ if (!files.includes(ARTIFACT.requirement) && !logExists) return undefined
23
+ let stage = 1
24
+ if (files.includes(ARTIFACT.plan)) stage = 2
25
+ if (logExists) stage = 3
26
+ if (qaExists) stage = 4
27
+
28
+ // 意图和要求是 resume 唯一没法重新推导的东西,从 Requirement.md 里捞回来。
29
+ const intentArtifact = await readArtifact(cwd, project, ARTIFACT.requirement)
30
+ const intent = withoutHeading(extractSection(intentArtifact, '## 用户要求', true))
31
+ const requirementBlock = extractSection(intentArtifact, '## 用户要求')
32
+ const requirements = requirementBlock
33
+ .split(/\r?\n/u)
34
+ .map(line => line.replace(/^\s*\d+[.)]\s*/u, '').trim())
35
+ .filter(line => line !== '')
36
+
37
+ if (files.includes('state.json')) {
38
+ try {
39
+ await rename(join(dir, 'state.json'), join(dir, `state.json.corrupt-${Date.now()}`))
40
+ } catch {
41
+ // keep going even when the broken file cannot be moved
42
+ }
43
+ }
44
+ // 返工次数从 Execution_Log.md 的轮次标记数出来
45
+ const logText = await readArtifact(cwd, project, ARTIFACT.log) ?? ''
46
+ const rounds = (logText.match(/## 实施 R\d+/gu) ?? []).length
47
+ return writeState(cwd, project, {
48
+ stage,
49
+ status: 'rebuilt-from-artifacts',
50
+ rework: Math.max(0, rounds - 1),
51
+ ...(intent === '' ? {} : { intent }),
52
+ ...(requirements.length === 0 ? {} : { requirements }),
53
+ rebuiltAt: nowIso(),
54
+ })
55
+ }
56
+
57
+ export async function sweep(cwd, settings, projectFilter, mutate = true) {
58
+ const actions = []
59
+ let names = []
60
+ try {
61
+ const entries = await readdir(join(cwd, '.project-flow'), { withFileTypes: true })
62
+ names = entries.filter(entry => entry.isDirectory()).map(entry => entry.name)
63
+ } catch {
64
+ return actions
65
+ }
66
+ for (const project of names.sort()) {
67
+ if (projectFilter !== undefined && project !== projectFilter) continue
68
+ const holder = await readLock(cwd, project)
69
+ if (holder !== undefined) {
70
+ const beat = Date.parse(holder.heartbeatAt ?? holder.startedAt ?? '')
71
+ const age = Number.isFinite(beat) ? Date.now() - beat : Number.POSITIVE_INFINITY
72
+ const alive = holder.pid !== process.pid && isAlive(holder.pid)
73
+ if (!alive && age >= settings.staleLockMs) {
74
+ actions.push(`${project}:遗留锁(pid ${holder.pid},心跳 ${holder.heartbeatAt ?? '无'})`)
75
+ if (mutate) {
76
+ try {
77
+ await rename(lockFile(cwd, project), `${lockFile(cwd, project)}.stale-${Date.now()}`)
78
+ actions[actions.length - 1] += ',已移开'
79
+ } catch {
80
+ actions[actions.length - 1] += ',移开失败'
81
+ }
82
+ }
83
+ }
84
+ }
85
+ const state = await readState(cwd, project)
86
+ if (state === undefined) {
87
+ // A brand-new project has no state.json yet: `project_run` creates the
88
+ // lock first and writes state only once the pipeline starts, so reporting
89
+ // "corrupt" here would fire on every first run and send the user chasing
90
+ // a problem that does not exist. Only a project with prior artifacts can
91
+ // be genuinely broken.
92
+ const artifacts = await readdir(stateDir(cwd, project)).catch(() => [])
93
+ const hasPriorRun = artifacts.includes(ARTIFACT.requirement) || artifacts.includes(ARTIFACT.plan)
94
+ if (!hasPriorRun) continue
95
+ actions.push(`${project}:state.json 缺失或损坏`)
96
+ if (mutate) {
97
+ const repaired = await repairState(cwd, project)
98
+ actions[actions.length - 1] += repaired === undefined
99
+ ? ',产物不足,无法重建'
100
+ : `,已按产物重建为第 ${repaired.stage} 段`
101
+ }
102
+ continue
103
+ }
104
+ const open = typeof state.status === 'string' && /^(planning|building|checking)$|^(rework-\d+|checking R\d+)$/u.test(state.status)
105
+ if (open && state.interruptedAt === undefined && !pfState.running.has(project)) {
106
+ actions.push(`${project}:第 ${state.stage ?? '?'} 段的「${state.status}」没有收尾`)
107
+ if (mutate) {
108
+ await writeState(cwd, project, {
109
+ interruptedAt: nowIso(),
110
+ status: `${state.status}(中断)`,
111
+ })
112
+ actions[actions.length - 1] += ',已标记中断,可用 project_resume 续跑'
113
+ }
114
+ }
115
+ }
116
+ return actions
117
+ }
118
+