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.
@@ -0,0 +1,443 @@
1
+ /**
2
+ * flow.yaml 的解析与校验。
3
+ *
4
+ * 为什么手写:红线 2 不许加依赖。这个文件只认本插件 schema 用得到的写法——
5
+ * 缩进 map、块级 seq、行内 [a, b] 和 { a: 1 }、# 注释、引号标量。超出子集的
6
+ * 写法一律报语法错并给行号,不猜、不兜底。猜错的 YAML 比报错危险得多:
7
+ * 它会让一个写错的阶段配置看起来像生效了。
8
+ *
9
+ * 校验分两档:
10
+ * errors 阻止保存,project_run 直接拒跑
11
+ * warnings 只打日志,照常跑
12
+ *
13
+ * 行号是必须的。不给行号的配置错误,用户拿着只能从头数。
14
+ */
15
+
16
+ /** 认得的顶层键。其余进 warnings,不拦。 */
17
+ const TOP_KEYS = ['process', 'limits', 'phases']
18
+
19
+ /** 认得的 phase 键。 */
20
+ const PHASE_KEYS = ['id', 'reads', 'writes', 'gate', 'model', 'instructions', 'on_success', 'on_gate_fail']
21
+
22
+ /** 认得的 gate 键。 */
23
+ const GATE_KEYS = ['kind', 'min_score', 'blindspots', 'on_fail', 'max_rework', 'assertions_exit_zero']
24
+
25
+ const KNOWN_GATE_KINDS = ['intent', 'artifact_present', 'assertions_exit_zero', 'verdict']
26
+
27
+ /** 内置四阶的 id。不在这四个里的环节要靠 instructions 才知道该做什么。 */
28
+ const BUILTIN_PHASE_IDS = ['requirement', 'plan', 'build', 'qa']
29
+
30
+ /**
31
+ * 去掉行尾注释。
32
+ *
33
+ * 引号里的 # 不是注释——`cmd: "echo #1"` 这种写法真的会出现。所以逐字符扫,
34
+ * 碰到引号就进去,出来之前不认 #。
35
+ */
36
+ function stripComment(line) {
37
+ let quote = ''
38
+ for (let i = 0; i < line.length; i += 1) {
39
+ const ch = line[i]
40
+ if (quote !== '') {
41
+ if (ch === '\\' && quote === '"') { i += 1; continue }
42
+ if (ch === quote) quote = ''
43
+ continue
44
+ }
45
+ if (ch === '"' || ch === "'") { quote = ch; continue }
46
+ if (ch === '#') return line.slice(0, i)
47
+ }
48
+ return line
49
+ }
50
+
51
+ /** 标量还原:引号走 JSON 转义,纯数字转 number,true/false 转 boolean。 */
52
+ function scalar(text) {
53
+ const t = text.trim()
54
+ if (t.length >= 2 && t.startsWith('"') && t.endsWith('"')) {
55
+ try { return String(JSON.parse(t)) } catch { return t.slice(1, -1) }
56
+ }
57
+ if (t.length >= 2 && t.startsWith("'") && t.endsWith("'")) return t.slice(1, -1)
58
+ if (t === 'true') return true
59
+ if (t === 'false') return false
60
+ if (t === 'null' || t === '~') return null
61
+ if (/^-?\d+$/u.test(t)) return Number.parseInt(t, 10)
62
+ if (/^-?\d+\.\d+$/u.test(t)) return Number.parseFloat(t)
63
+ return t
64
+ }
65
+
66
+ /** 行内 [a, b] / { a: 1 }。返回 null 表示「这不是行内写法」。 */
67
+ function inlineValue(text) {
68
+ const t = text.trim()
69
+ if (t.startsWith('[') && t.endsWith(']')) {
70
+ const inner = t.slice(1, -1).trim()
71
+ if (inner === '') return []
72
+ return splitTopLevel(inner, ',').map(part => scalar(part))
73
+ }
74
+ if (t.startsWith('{') && t.endsWith('}')) {
75
+ const inner = t.slice(1, -1).trim()
76
+ const out = {}
77
+ if (inner === '') return out
78
+ for (const part of splitTopLevel(inner, ',')) {
79
+ const at = part.indexOf(':')
80
+ if (at === -1) return null
81
+ out[part.slice(0, at).trim()] = scalar(part.slice(at + 1))
82
+ }
83
+ return out
84
+ }
85
+ return null
86
+ }
87
+
88
+ /** 按分隔符切,但不切引号和括号里面的。 */
89
+ function splitTopLevel(text, sep) {
90
+ const parts = []
91
+ let depth = 0
92
+ let quote = ''
93
+ let start = 0
94
+ for (let i = 0; i < text.length; i += 1) {
95
+ const ch = text[i]
96
+ if (quote !== '') {
97
+ if (ch === '\\' && quote === '"') { i += 1; continue }
98
+ if (ch === quote) quote = ''
99
+ continue
100
+ }
101
+ if (ch === '"' || ch === "'") { quote = ch; continue }
102
+ if (ch === '[' || ch === '{') { depth += 1; continue }
103
+ if (ch === ']' || ch === '}') { depth -= 1; continue }
104
+ if (ch === sep && depth === 0) {
105
+ parts.push(text.slice(start, i))
106
+ start = i + 1
107
+ }
108
+ }
109
+ parts.push(text.slice(start))
110
+ return parts
111
+ }
112
+
113
+ /**
114
+ * 解析 flow.yaml。
115
+ *
116
+ * 返回 { value, errors }。errors 每条 { line, message },value 可能残缺——
117
+ * 语法错了就别拿它跑,但要把能读出来的部分带回去,方便报错时说清哪一段坏了。
118
+ */
119
+ export function parseFlowYaml(text) {
120
+ const errors = []
121
+ const root = {}
122
+ if (typeof text !== 'string' || text.trim() === '') {
123
+ return { value: root, errors: [{ line: 0, message: '文件是空的' }] }
124
+ }
125
+
126
+ // 预处理:留下有内容的行,记住原行号。
127
+ const rows = []
128
+ const rawLines = text.split(/\r?\n/u)
129
+ for (let i = 0; i < rawLines.length; i += 1) {
130
+ const stripped = stripComment(rawLines[i])
131
+ if (stripped.trim() === '') continue
132
+ const indent = stripped.length - stripped.trimStart().length
133
+ rows.push({ indent, text: stripped.trim(), line: i + 1 })
134
+ }
135
+ if (rows.length === 0) return { value: root, errors: [{ line: 0, message: '文件里只有注释' }] }
136
+
137
+ let cursor = 0
138
+
139
+ /** 解析一个缩进块,返回 [值, 是否 seq]。 */
140
+ function parseBlock(indent) {
141
+ if (cursor >= rows.length) return [{}, false]
142
+ const isSeq = rows[cursor].text.startsWith('- ') || rows[cursor].text === '-'
143
+ if (isSeq) {
144
+ const arr = []
145
+ while (cursor < rows.length && rows[cursor].indent === indent && (rows[cursor].text.startsWith('- ') || rows[cursor].text === '-')) {
146
+ const row = rows[cursor]
147
+ const restRaw = row.text === '-' ? '' : row.text.slice(2)
148
+ const rest = restRaw.trim()
149
+ if (rest === '') {
150
+ // 只有一根横杠,内容全在下面的子块里。
151
+ cursor += 1
152
+ if (cursor < rows.length && rows[cursor].indent > indent) {
153
+ const [child] = parseBlock(rows[cursor].indent)
154
+ arr.push(child)
155
+ } else {
156
+ arr.push({})
157
+ }
158
+ continue
159
+ }
160
+ // `- id: xxx`:这一个 seq 项本身就是个 map,横杠后面那截是它的第一行。
161
+ // 后续的兄弟字段缩进必须正好对齐这第一行内容的起始列,多一格少一格都不算。
162
+ // 早先按 `indent + 2` 硬算,遇到 `- id:` 这种多个空格的写法就对不上,
163
+ // 而更常见的是忘了吃掉后续兄弟字段,游标卡住,后面整份配置全读飞。
164
+ const pad = restRaw.length - restRaw.trimStart().length
165
+ const itemIndent = indent + 2 + pad
166
+ const item = {}
167
+ cursor += 1
168
+ consumeMapEntry(item, rest, row.line, itemIndent)
169
+ while (cursor < rows.length && rows[cursor].indent === itemIndent) {
170
+ const sub = rows[cursor]
171
+ cursor += 1
172
+ consumeMapEntry(item, sub.text, sub.line, itemIndent)
173
+ }
174
+ arr.push(item)
175
+ }
176
+ return [arr, true]
177
+ }
178
+ const obj = {}
179
+ while (cursor < rows.length && rows[cursor].indent === indent) {
180
+ const row = rows[cursor]
181
+ cursor += 1
182
+ consumeMapEntry(obj, row.text, row.line, indent)
183
+ }
184
+ return [obj, false]
185
+ }
186
+
187
+ /** 吃一条 `key: value`,value 空的话继续往下吃子块。 */
188
+ function consumeMapEntry(target, text, line, indent) {
189
+ const at = findColon(text)
190
+ if (at === -1) {
191
+ errors.push({ line, message: `这一行看不懂,应该是 \`键: 值\` 的形式:${text}` })
192
+ return
193
+ }
194
+ const key = text.slice(0, at).trim()
195
+ const rest = text.slice(at + 1).trim()
196
+ if (key === '') {
197
+ errors.push({ line, message: '冒号前面没有键名' })
198
+ return
199
+ }
200
+ if (rest === '') {
201
+ // 往下找子块。缩进必须更深,否则就是空值。
202
+ if (cursor < rows.length && rows[cursor].indent > indent) {
203
+ const [child] = parseBlock(rows[cursor].indent)
204
+ target[key] = child
205
+ } else {
206
+ target[key] = {}
207
+ }
208
+ return
209
+ }
210
+ const inline = inlineValue(rest)
211
+ target[key] = inline === null ? scalar(rest) : inline
212
+ }
213
+
214
+ function findColon(text) {
215
+ let quote = ''
216
+ let depth = 0
217
+ for (let i = 0; i < text.length; i += 1) {
218
+ const ch = text[i]
219
+ if (quote !== '') {
220
+ if (ch === '\\' && quote === '"') { i += 1; continue }
221
+ if (ch === quote) quote = ''
222
+ continue
223
+ }
224
+ if (ch === '"' || ch === "'") { quote = ch; continue }
225
+ if (ch === '[' || ch === '{') { depth += 1; continue }
226
+ if (ch === ']' || ch === '}') { depth -= 1; continue }
227
+ if (ch === ':' && depth === 0) return i
228
+ }
229
+ return -1
230
+ }
231
+
232
+ const [first] = parseBlock(rows[0].indent)
233
+ Object.assign(root, first)
234
+ if (cursor < rows.length) {
235
+ errors.push({ line: rows[cursor].line, message: '这一行的缩进对不上,没法归到任何一层' })
236
+ }
237
+ return { value: root, errors }
238
+ }
239
+
240
+ /**
241
+ * 校验解析出来的结构。
242
+ *
243
+ * 返回 { ok, errors, warnings, phases }。ok=false 时 project_run 拒跑。
244
+ * phases 是按 flow.yaml 顺序排好的数组,后续执行只认这个。
245
+ */
246
+ export function validateFlow(doc) {
247
+ const errors = []
248
+ const warnings = []
249
+ const phases = []
250
+
251
+ const err = (line, message) => errors.push({ line, message })
252
+ const warn = (line, message) => warnings.push({ line, message })
253
+
254
+ if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) {
255
+ err(0, '顶层必须是一个 map')
256
+ return { ok: false, errors, warnings, phases }
257
+ }
258
+
259
+ for (const key of Object.keys(doc)) {
260
+ if (!TOP_KEYS.includes(key)) warn(0, `顶层有不认识的键 \`${key}\`,会被忽略`)
261
+ }
262
+
263
+ const process = doc.process
264
+ if (process === undefined || process === null) {
265
+ err(0, '缺 `process`')
266
+ } else if (typeof process !== 'object') {
267
+ err(0, '`process` 必须是 map')
268
+ } else {
269
+ if (typeof process.name !== 'string' || process.name.trim() === '') {
270
+ err(0, '缺 `process.name`:没有名字的工作流没法在日志和状态里认出来')
271
+ }
272
+ if (process.version === undefined) warn(0, '`process.version` 没写,按 1 处理')
273
+ else if (!Number.isInteger(process.version)) warn(0, '`process.version` 应该是整数')
274
+ }
275
+
276
+ const limits = doc.limits
277
+ if (limits !== undefined && limits !== null) {
278
+ if (typeof limits !== 'object' || Array.isArray(limits)) {
279
+ err(0, '`limits` 必须是 map')
280
+ } else {
281
+ if (limits.max_rework !== undefined && !Number.isInteger(limits.max_rework)) {
282
+ warn(0, '`limits.max_rework` 应该是整数,这一项会被忽略')
283
+ }
284
+ if (limits.max_total_tokens !== undefined && !Number.isInteger(limits.max_total_tokens)) {
285
+ warn(0, '`limits.max_total_tokens` 应该是整数,这一项会被忽略')
286
+ }
287
+ }
288
+ }
289
+
290
+ const rawPhases = doc.phases
291
+ if (!Array.isArray(rawPhases) || rawPhases.length === 0) {
292
+ err(0, '`phases` 是空的:至少要有需求、规划、实施、质检四个环节')
293
+ return { ok: false, errors, warnings, phases }
294
+ }
295
+
296
+ const seen = new Set()
297
+ rawPhases.forEach((raw, index) => {
298
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
299
+ err(0, `第 ${index + 1} 个环节不是 map`)
300
+ return
301
+ }
302
+ const id = typeof raw.id === 'string' ? raw.id.trim() : ''
303
+ if (id === '') {
304
+ err(0, `第 ${index + 1} 个环节没有 \`id\`:环节之间靠 id 互相指,缺了就连不起来`)
305
+ return
306
+ }
307
+ if (seen.has(id)) {
308
+ err(0, `环节 id \`${id}\` 重复了`)
309
+ return
310
+ }
311
+ seen.add(id)
312
+
313
+ for (const key of Object.keys(raw)) {
314
+ if (!PHASE_KEYS.includes(key)) warn(0, `环节 \`${id}\` 有不认识的键 \`${key}\`,会被忽略`)
315
+ }
316
+
317
+ // 内置四阶各有专用实现,不写 instructions 也知道干什么。
318
+ // 别的环节没有专用实现,只能靠 instructions——不写就别指望它跑出东西来。
319
+ const instructions = typeof raw.instructions === 'string' ? raw.instructions.trim() : ''
320
+ if (!BUILTIN_PHASE_IDS.includes(id) && instructions === '') {
321
+ warn(0, `环节 \`${id}\` 不是内置四阶之一,又没写 \`instructions\`:跑起来会因为不知道该做什么而被跳过`)
322
+ }
323
+
324
+ const reads = normalizeStringList(raw.reads)
325
+ const writes = normalizeStringList(raw.writes)
326
+ if (reads === null) err(0, `环节 \`${id}\` 的 \`reads\` 必须是列表`)
327
+ if (writes === null) err(0, `环节 \`${id}\` 的 \`writes\` 必须是列表`)
328
+
329
+ const gate = raw.gate
330
+ if (gate === undefined || gate === null) {
331
+ warn(0, `环节 \`${id}\` 没写 \`gate\`,这一阶不设门禁`)
332
+ } else if (typeof gate !== 'object' || Array.isArray(gate)) {
333
+ err(0, `环节 \`${id}\` 的 \`gate\` 必须是 map`)
334
+ } else {
335
+ for (const key of Object.keys(gate)) {
336
+ if (!GATE_KEYS.includes(key)) warn(0, `环节 \`${id}\` 的 gate 有不认识的键 \`${key}\``)
337
+ }
338
+ if (gate.kind !== undefined && !KNOWN_GATE_KINDS.includes(gate.kind)) {
339
+ err(0, `环节 \`${id}\` 的 \`gate.kind\` 写的是 \`${gate.kind}\`,只认 ${KNOWN_GATE_KINDS.join(' / ')}`)
340
+ }
341
+ if (gate.min_score !== undefined && !Number.isInteger(gate.min_score)) {
342
+ warn(0, `环节 \`${id}\` 的 \`gate.min_score\` 应该是整数`)
343
+ }
344
+ if (gate.max_rework !== undefined && !Number.isInteger(gate.max_rework)) {
345
+ warn(0, `环节 \`${id}\` 的 \`gate.max_rework\` 应该是整数`)
346
+ }
347
+ if (Array.isArray(gate.blindspots) === false && gate.blindspots !== undefined) {
348
+ warn(0, `环节 \`${id}\` 的 \`gate.blindspots\` 应该是列表`)
349
+ }
350
+ }
351
+
352
+ phases.push({
353
+ id,
354
+ index,
355
+ reads: reads ?? [],
356
+ writes: writes ?? [],
357
+ gate: gate === undefined || gate === null ? null : gate,
358
+ model: raw.model === undefined ? null : raw.model,
359
+ instructions: typeof raw.instructions === 'string' ? raw.instructions : '',
360
+ onSuccess: typeof raw.on_success === 'string' ? raw.on_success.trim() : '',
361
+ onGateFail: typeof raw.on_gate_fail === 'string' ? raw.on_gate_fail.trim() : '',
362
+ })
363
+ })
364
+
365
+ // 跳转目标只能指向前面出现过的环节。
366
+ //
367
+ // 指到后面会成环:A 失败跳 B、B 失败跳 A,跑起来就是无限循环,
368
+ // 而 max_rework 管的是「同一个环节返工几次」,管不了跨环节来回跳。
369
+ const indexById = new Map(phases.map(p => [p.id, p.index]))
370
+ const checkTarget = (phase, target, field) => {
371
+ if (target === '') return
372
+ const at = indexById.get(target)
373
+ if (at === undefined) {
374
+ err(0, `环节 \`${phase.id}\` 的 \`${field}\` 指向 \`${target}\`,但没有这个环节`)
375
+ return
376
+ }
377
+ if (at >= phase.index) {
378
+ err(0, `环节 \`${phase.id}\` 的 \`${field}\` 指向 \`${target}\`(第 ${at + 1} 个),只能指向它前面出现过的环节,否则会来回跳成死循环`)
379
+ }
380
+ }
381
+ for (const phase of phases) {
382
+ checkTarget(phase, phase.onSuccess, 'on_success')
383
+ checkTarget(phase, phase.onGateFail, 'on_gate_fail')
384
+ const gateFail = phase.gate !== null && typeof phase.gate === 'object' ? phase.gate.on_fail : undefined
385
+ if (typeof gateFail === 'string' && gateFail.trim() !== '') {
386
+ checkTarget(phase, gateFail.trim(), 'gate.on_fail')
387
+ }
388
+ }
389
+
390
+ return { ok: errors.length === 0, errors, warnings, phases }
391
+ }
392
+
393
+ /** 列表字段:缺省算空,字符串当单元素,别的算写错。 */
394
+ function normalizeStringList(value) {
395
+ if (value === undefined || value === null) return []
396
+ if (typeof value === 'string') return value.trim() === '' ? [] : [value.trim()]
397
+ if (!Array.isArray(value)) return null
398
+ const out = []
399
+ for (const item of value) {
400
+ if (typeof item !== 'string') return null
401
+ const t = item.trim()
402
+ if (t !== '') out.push(t)
403
+ }
404
+ return out
405
+ }
406
+
407
+ /** 一步到位:文本进,结论出。项目里调用最多的就是这个。 */
408
+ export function loadFlow(text) {
409
+ const { value, errors: syntaxErrors } = parseFlowYaml(text)
410
+ if (syntaxErrors.length > 0) {
411
+ return { ok: false, errors: syntaxErrors, warnings: [], phases: [], doc: value }
412
+ }
413
+ const result = validateFlow(value)
414
+ return { ...result, doc: value }
415
+ }
416
+
417
+ /**
418
+ * 把校验结果整理成给人看的一段话。
419
+ *
420
+ * 行号一定要出现在第一行:用户拿到报错第一件事是去文件里跳行,
421
+ * 埋在第三行之后的正文里他看不见。
422
+ */
423
+ export function describeFlowProblems(result) {
424
+ const lines = []
425
+ for (const e of result.errors) {
426
+ lines.push(e.line > 0 ? `第 ${e.line} 行:${e.message}` : e.message)
427
+ }
428
+ for (const w of result.warnings) {
429
+ lines.push(w.line > 0 ? `第 ${w.line} 行(提醒):${w.message}` : `提醒:${w.message}`)
430
+ }
431
+ return lines.join('\n')
432
+ }
433
+
434
+ /** 内置四阶。没有 flow.yaml 时就是它,行为和 0.8.x 完全一致。 */
435
+ export const BUILTIN_FLOW = {
436
+ process: { name: 'four-stage', version: 1 },
437
+ phases: [
438
+ { id: 'requirement', reads: [], writes: ['Requirement.md'], gate: { kind: 'intent', min_score: 95 } },
439
+ { id: 'plan', reads: ['Requirement.md'], writes: ['Plan.md'], gate: { kind: 'artifact_present' } },
440
+ { id: 'build', reads: ['Plan.md'], writes: ['Execution_Log.md'], gate: { kind: 'assertions_exit_zero' } },
441
+ { id: 'qa', reads: ['Requirement.md', 'Plan.md', 'Execution_Log.md'], writes: ['QA_Report.md'], gate: { kind: 'verdict', on_fail: 'build' } },
442
+ ],
443
+ }