dsh-workflow-execute 0.0.0-stage → 1.0.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,258 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * dsh-workflow-execute — 工作流 YAML 校验器(纯函数,无 IO)。
5
+ *
6
+ * 工作流 YAML 本体是 schema 权威;这里只做结构级检查,分两档:
7
+ * - errors 阻止保存:YAML 语法错 / 缺 process.name / phases 为空 / 环节缺 id /
8
+ * id 重复 / on_success·on_gate_fail·on_rating_fail 指向不存在的环节。
9
+ * - warnings 只提示:缺 guid·display_name·version、未知键、阶段无环节、
10
+ * max_rework/min_score 类型不对。
11
+ *
12
+ * 行号:用 YAML.LineCounter 把节点 offset 换成 1-based 行号,供编辑器定位。
13
+ */
14
+
15
+ const YAML = require('yaml')
16
+
17
+ const TOP_KEYS = new Set(['process', 'limits', 'abnormal_handler', 'phases'])
18
+ const PROCESS_KEYS = new Set(['name', 'guid', 'display_name', 'description', 'category', 'complexity', 'version'])
19
+ const COMPLEXITIES = ['low', 'medium', 'high']
20
+ const LIMIT_KEYS = new Set(['max_step_executions', 'max_total_tokens', 'judge_timeout_ms'])
21
+ const PHASE_KEYS = new Set(['id', 'name', 'spec', 'spec_ref', 'acceptance_criteria', 'links'])
22
+ const LINK_KEYS = new Set([
23
+ 'id', 'name', 'step_template', 'prompt', 'executor', 'expert', 'expert_name', 'skills',
24
+ 'review_type', 'expected_artifacts', 'gates', 'on_success', 'on_gate_fail', 'on_rating_fail',
25
+ 'max_rework', 'acceptance_criteria', 'review_prompt',
26
+ ])
27
+ const FLOW_KEYWORDS = new Set(['next', 'end', 'break'])
28
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
29
+
30
+ const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
31
+ const isNonEmptyString = (v) => typeof v === 'string' && v.trim() !== ''
32
+
33
+ /**
34
+ * 解析文本为 Document + 普通对象;语法错误带行号返回,不抛。
35
+ * @returns {{ doc: import('yaml').Document, data: any, lineCounter: YAML.LineCounter, syntaxErrors: Array<{code,message,line,col}> }}
36
+ */
37
+ function parseProcessYaml(text) {
38
+ const lineCounter = new YAML.LineCounter()
39
+ const doc = YAML.parseDocument(String(text ?? ''), { lineCounter, prettyErrors: true, uniqueKeys: true })
40
+ const syntaxErrors = doc.errors.map((e) => {
41
+ const pos = e.linePos && e.linePos[0] ? e.linePos[0] : (Array.isArray(e.pos) ? lineCounter.linePos(e.pos[0]) : { line: 1, col: 1 })
42
+ return { code: 'yaml_syntax', message: String(e.message || e).split('\n')[0], line: pos.line, col: pos.col, path: '' }
43
+ })
44
+ let data
45
+ try { data = doc.errors.length === 0 ? doc.toJS({ maxAliasCount: 1000 }) : undefined } catch (e) {
46
+ syntaxErrors.push({ code: 'yaml_syntax', message: String(e && e.message || e), line: 1, col: 1, path: '' })
47
+ }
48
+ return { doc, data, lineCounter, syntaxErrors }
49
+ }
50
+
51
+ /** 节点路径 → 1-based 行号(找不到返回 undefined)。 */
52
+ function lineOf(doc, lineCounter, path) {
53
+ try {
54
+ const node = doc.getIn(path, true)
55
+ const range = node && node.range
56
+ if (!range) return undefined
57
+ return lineCounter.linePos(range[0]).line
58
+ } catch { return undefined }
59
+ }
60
+
61
+ /** 解析流转值:next/end/break 关键字、`goto:<id>`、或直接 `<id>`。返回引用的环节 id 或 null。 */
62
+ function flowTarget(value) {
63
+ if (typeof value !== 'string') return null
64
+ const v = value.trim()
65
+ if (v === '' || FLOW_KEYWORDS.has(v)) return null
66
+ return v.startsWith('goto:') ? v.slice(5).trim() : v
67
+ }
68
+
69
+ /**
70
+ * 从已解析对象提取列表元信息。
71
+ * @param data 解析后的普通对象(可能 undefined)
72
+ */
73
+ function extractMeta(data) {
74
+ const p = isMap(data) && isMap(data.process) ? data.process : {}
75
+ const phases = isMap(data) && Array.isArray(data.phases) ? data.phases : []
76
+ let linkCount = 0
77
+ for (const ph of phases) if (isMap(ph) && Array.isArray(ph.links)) linkCount += ph.links.length
78
+ return {
79
+ name: isNonEmptyString(p.name) ? p.name.trim() : '',
80
+ guid: typeof p.guid === 'string' ? p.guid : '',
81
+ display_name: isNonEmptyString(p.display_name) ? p.display_name.trim() : '',
82
+ description: typeof p.description === 'string' ? p.description.trim() : '',
83
+ category: isNonEmptyString(p.category) ? p.category.trim() : '',
84
+ complexity: isNonEmptyString(p.complexity) ? p.complexity.trim() : '',
85
+ version: p.version === undefined || p.version === null ? '' : String(p.version),
86
+ phaseCount: phases.length,
87
+ linkCount,
88
+ }
89
+ }
90
+
91
+ /**
92
+ * 校验一份工作流。
93
+ * @param {string|{doc,data,lineCounter,syntaxErrors}} input 文本或 parseProcessYaml 结果
94
+ * @returns {{ errors: Diag[], warnings: Diag[], meta: object }} Diag = {code, message, path, line?}
95
+ */
96
+ function validateProcess(input, options = {}) {
97
+ const parsed = typeof input === 'string' ? parseProcessYaml(input) : input
98
+ const { doc, data, lineCounter } = parsed
99
+ const errors = [...parsed.syntaxErrors]
100
+ const warnings = []
101
+ const at = (path) => lineOf(doc, lineCounter, path)
102
+ const err = (code, message, path) => errors.push({ code, message, path: path.join('.'), line: at(path) })
103
+ const warn = (code, message, path) => warnings.push({ code, message, path: path.join('.'), line: at(path) })
104
+
105
+ if (errors.length > 0 || data === undefined) {
106
+ return { errors, warnings, meta: extractMeta(undefined) }
107
+ }
108
+ if (!isMap(data)) {
109
+ err('not_a_map', '顶层必须是映射(process / phases …)', [])
110
+ return { errors, warnings, meta: extractMeta(undefined) }
111
+ }
112
+ for (const key of Object.keys(data)) {
113
+ if (!TOP_KEYS.has(key)) warn('unknown_key', `未知顶层键 "${key}"`, [key])
114
+ }
115
+
116
+ // ── process ──
117
+ if (!isMap(data.process)) {
118
+ err('missing_process', '缺少 process 块', ['process'])
119
+ } else {
120
+ const p = data.process
121
+ for (const key of Object.keys(p)) {
122
+ if (!PROCESS_KEYS.has(key)) warn('unknown_key', `process 下未知键 "${key}"`, ['process', key])
123
+ }
124
+ if (p.complexity !== undefined && p.complexity !== null && p.complexity !== ''
125
+ && !COMPLEXITIES.includes(String(p.complexity))) {
126
+ warn('unknown_complexity', `process.complexity 只能是 low / medium / high(低 / 中 / 高)`, ['process', 'complexity'])
127
+ }
128
+ if (!isNonEmptyString(p.name)) err('missing_name', 'process.name 必填且不能为空', ['process', 'name'])
129
+ else if (/[\\/]/.test(p.name)) err('bad_name', 'process.name 不能包含路径分隔符', ['process', 'name'])
130
+ if (!isNonEmptyString(p.guid)) warn('missing_guid', '建议填写 process.guid(UUID,用于标识工作流身份)', ['process', 'guid'])
131
+ else if (!UUID_RE.test(p.guid)) warn('bad_guid', 'process.guid 不是 UUID 格式', ['process', 'guid'])
132
+ if (!isNonEmptyString(p.display_name)) warn('missing_display_name', '建议填写 process.display_name(界面显示名)', ['process', 'display_name'])
133
+ if (p.version === undefined || p.version === null || String(p.version).trim() === '') warn('missing_version', '建议填写 process.version', ['process', 'version'])
134
+ }
135
+
136
+ // ── limits / abnormal_handler ──
137
+ if (data.limits !== undefined && data.limits !== null) {
138
+ if (!isMap(data.limits)) warn('bad_limits', 'limits 应为映射', ['limits'])
139
+ else {
140
+ for (const key of Object.keys(data.limits)) {
141
+ if (!LIMIT_KEYS.has(key)) warn('unknown_key', `limits 下未知键 "${key}"`, ['limits', key])
142
+ else if (data.limits[key] !== null && !(Number.isInteger(data.limits[key]) && data.limits[key] >= 0)) {
143
+ warn('bad_limit', `limits.${key} 应为非负整数或 null`, ['limits', key])
144
+ }
145
+ }
146
+ }
147
+ }
148
+ if (data.abnormal_handler !== undefined && data.abnormal_handler !== null && !isMap(data.abnormal_handler)) {
149
+ warn('bad_abnormal_handler', 'abnormal_handler 应为映射或 null', ['abnormal_handler'])
150
+ }
151
+
152
+ // ── phases / links ──
153
+ if (!Array.isArray(data.phases) || data.phases.length === 0) {
154
+ err('missing_phases', 'phases 必须是非空列表', ['phases'])
155
+ return { errors, warnings, meta: extractMeta(data) }
156
+ }
157
+ const phaseIds = new Map()
158
+ const linkIds = new Map()
159
+ const flowRefs = []
160
+ data.phases.forEach((ph, pi) => {
161
+ const pPath = ['phases', pi]
162
+ if (!isMap(ph)) { err('bad_phase', `第 ${pi + 1} 个阶段不是映射`, pPath); return }
163
+ for (const key of Object.keys(ph)) {
164
+ if (!PHASE_KEYS.has(key)) warn('unknown_key', `阶段 "${ph.id || pi + 1}" 下未知键 "${key}"`, [...pPath, key])
165
+ }
166
+ if (!isNonEmptyString(ph.id)) err('missing_phase_id', `第 ${pi + 1} 个阶段缺少 id`, [...pPath, 'id'])
167
+ else if (phaseIds.has(ph.id)) err('duplicate_phase_id', `阶段 id 重复 "${ph.id}"`, [...pPath, 'id'])
168
+ else phaseIds.set(ph.id, pi)
169
+ if (!Array.isArray(ph.links) || ph.links.length === 0) {
170
+ warn('empty_phase', `阶段 "${ph.id || pi + 1}" 没有环节`, [...pPath, 'links'])
171
+ return
172
+ }
173
+ ph.links.forEach((ln, li) => {
174
+ const lPath = [...pPath, 'links', li]
175
+ if (!isMap(ln)) { err('bad_link', `阶段 "${ph.id}" 第 ${li + 1} 个环节不是映射`, lPath); return }
176
+ for (const key of Object.keys(ln)) {
177
+ if (!LINK_KEYS.has(key)) warn('unknown_key', `环节 "${ln.id || li + 1}" 下未知键 "${key}"`, [...lPath, key])
178
+ }
179
+ if (!isNonEmptyString(ln.id)) err('missing_link_id', `阶段 "${ph.id}" 第 ${li + 1} 个环节缺少 id`, [...lPath, 'id'])
180
+ else if (linkIds.has(ln.id)) err('duplicate_link_id', `环节 id 重复 "${ln.id}"`, [...lPath, 'id'])
181
+ else linkIds.set(ln.id, lPath)
182
+ if (!isNonEmptyString(ln.prompt)) warn('empty_prompt', `环节 "${ln.id || li + 1}" 没有 prompt`, [...lPath, 'prompt'])
183
+ if (ln.max_rework !== undefined && ln.max_rework !== null && !(Number.isInteger(ln.max_rework) && ln.max_rework >= 0)) {
184
+ warn('bad_max_rework', `环节 "${ln.id}" 的 max_rework 应为非负整数`, [...lPath, 'max_rework'])
185
+ }
186
+ if (ln.skills !== undefined && ln.skills !== null && !Array.isArray(ln.skills)) {
187
+ warn('bad_skills', `环节 "${ln.id}" 的 skills 应为列表`, [...lPath, 'skills'])
188
+ }
189
+ if (Array.isArray(ln.gates)) {
190
+ ln.gates.forEach((g, gi) => {
191
+ if (!isMap(g)) { warn('bad_gate', `环节 "${ln.id}" 第 ${gi + 1} 个门禁不是映射`, [...lPath, 'gates', gi]); return }
192
+ if (g.min_score !== undefined && g.min_score !== null && typeof g.min_score !== 'number') {
193
+ warn('bad_min_score', `环节 "${ln.id}" 门禁 "${g.name || gi + 1}" 的 min_score 应为数字`, [...lPath, 'gates', gi, 'min_score'])
194
+ }
195
+ })
196
+ } else if (ln.gates !== undefined && ln.gates !== null) {
197
+ warn('bad_gates', `环节 "${ln.id}" 的 gates 应为列表`, [...lPath, 'gates'])
198
+ }
199
+ for (const field of ['on_success', 'on_gate_fail', 'on_rating_fail']) {
200
+ const target = flowTarget(ln[field])
201
+ if (target !== null) flowRefs.push({ field, target, path: [...lPath, field], linkId: ln.id })
202
+ }
203
+ })
204
+ })
205
+ for (const ref of flowRefs) {
206
+ if (!linkIds.has(ref.target) && !phaseIds.has(ref.target)) {
207
+ err('dangling_flow', `环节 "${ref.linkId}" 的 ${ref.field} 指向不存在的环节 "${ref.target}"`, ref.path)
208
+ }
209
+ }
210
+ return { errors, warnings, meta: extractMeta(data) }
211
+ }
212
+
213
+ /** 新建空白工作流骨架(带注释说明每个字段)。 */
214
+ function skeletonYaml({ name, displayName, guid }) {
215
+ const safeName = String(name || 'new-process')
216
+ return `# 工作流(Process)定义。每个阶段(phase)包含若干环节(link),
217
+ # 环节按 on_success / on_gate_fail 流转;门禁(gates)不过会按 max_rework 返工。
218
+ process:
219
+ name: ${YAML.stringify(safeName).trim()}
220
+ guid: ${guid}
221
+ display_name: ${YAML.stringify(displayName || safeName).trim()}
222
+ description: |
223
+ 一句话说明这个工作流适合什么场景。
224
+ category: software # 分类,用于筛选
225
+ complexity: medium # 复杂度:low / medium / high(低 / 中 / 高)
226
+ version: 1.0.0
227
+ limits:
228
+ max_step_executions: null # 环节执行总次数上限(null = 不限)
229
+ max_total_tokens: null # token 总量上限(null = 不限)
230
+ abnormal_handler: null # 如 { trigger_on: [capped_step, capped_token, failed] }
231
+ phases:
232
+ - id: phase-1
233
+ name: 阶段 1
234
+ spec: |
235
+ 这个阶段要达成什么。
236
+ acceptance_criteria: |
237
+ 阶段验收标准。
238
+ links:
239
+ - id: link-1
240
+ name: 环节 1
241
+ prompt: |
242
+ 交给 agent 的指令。
243
+ executor: null # 执行器,如 atomcode
244
+ expert: null # 专家名(对应专家库)
245
+ skills: [] # 技能名列表(对应技能库)
246
+ review_type: ai # ai | human | none
247
+ expected_artifacts: []
248
+ gates: [] # 如 { name: 方案存在, type: ai_criteria_review, min_score: 60 }
249
+ on_success: end # next | end | <环节 id> | goto:<环节 id>
250
+ on_gate_fail: break # break | <环节 id> | goto:<环节 id>
251
+ on_rating_fail: break
252
+ max_rework: 2
253
+ acceptance_criteria: ''
254
+ review_prompt: ''
255
+ `
256
+ }
257
+
258
+ module.exports = { parseProcessYaml, validateProcess, extractMeta, skeletonYaml, flowTarget, lineOf, COMPLEXITIES }
package/src/zip.js ADDED
@@ -0,0 +1,85 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * 零依赖 ZIP 构建(与 dsh-file-share share-core 同款):目录条目 STORE,
5
+ * 文件条目 deflateRaw,同步构建,UTF-8 文件名。
6
+ */
7
+
8
+ const zlib = require('node:zlib')
9
+
10
+ const CRC_TABLE = (() => {
11
+ const t = new Int32Array(256)
12
+ for (let n = 0; n < 256; n++) {
13
+ let c = n
14
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)
15
+ t[n] = c
16
+ }
17
+ return t
18
+ })()
19
+
20
+ function crc32(buf) {
21
+ let c = -1
22
+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xFF] ^ (c >>> 8)
23
+ return (c ^ -1) >>> 0
24
+ }
25
+
26
+ function dosDateTime(ms) {
27
+ const d = new Date(ms)
28
+ const time = (d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1)
29
+ const date = ((Math.max(0, d.getFullYear() - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate())
30
+ return { time: time & 0xFFFF, date: date & 0xFFFF }
31
+ }
32
+
33
+ /** entries: [{ name, data?, isDir?, mtime? }] → Buffer */
34
+ function buildZip(entries) {
35
+ const locals = []
36
+ const centrals = []
37
+ let offset = 0
38
+ for (const ent of entries) {
39
+ const nameBuf = Buffer.from(ent.name, 'utf8')
40
+ const data = ent.isDir || !ent.data ? Buffer.alloc(0) : ent.data
41
+ const method = ent.isDir ? 0 : 8
42
+ const compressed = ent.isDir ? data : zlib.deflateRawSync(data)
43
+ const { time, date } = dosDateTime(ent.mtime || Date.now())
44
+ const local = Buffer.alloc(30)
45
+ local.writeUInt32LE(0x04034b50, 0)
46
+ local.writeUInt16LE(20, 4)
47
+ local.writeUInt16LE(0x0800, 6)
48
+ local.writeUInt16LE(method, 8)
49
+ local.writeUInt16LE(time, 10)
50
+ local.writeUInt16LE(date, 12)
51
+ local.writeUInt32LE(crc32(data), 14)
52
+ local.writeUInt32LE(compressed.length, 18)
53
+ local.writeUInt32LE(data.length, 22)
54
+ local.writeUInt16LE(nameBuf.length, 26)
55
+ locals.push(local, nameBuf, compressed)
56
+
57
+ const central = Buffer.alloc(46)
58
+ central.writeUInt32LE(0x02014b50, 0)
59
+ central.writeUInt16LE(20, 4)
60
+ central.writeUInt16LE(20, 6)
61
+ central.writeUInt16LE(0x0800, 8)
62
+ central.writeUInt16LE(method, 10)
63
+ central.writeUInt16LE(time, 12)
64
+ central.writeUInt16LE(date, 14)
65
+ central.writeUInt32LE(crc32(data), 16)
66
+ central.writeUInt32LE(compressed.length, 20)
67
+ central.writeUInt32LE(data.length, 24)
68
+ central.writeUInt16LE(nameBuf.length, 28)
69
+ central.writeUInt32LE(ent.isDir ? 0x10 : 0, 38)
70
+ central.writeUInt32LE(offset, 42)
71
+ centrals.push(central, nameBuf)
72
+
73
+ offset += 30 + nameBuf.length + compressed.length
74
+ }
75
+ const centralBuf = Buffer.concat(centrals)
76
+ const eocd = Buffer.alloc(22)
77
+ eocd.writeUInt32LE(0x06054b50, 0)
78
+ eocd.writeUInt16LE(entries.length, 8)
79
+ eocd.writeUInt16LE(entries.length, 10)
80
+ eocd.writeUInt32LE(centralBuf.length, 12)
81
+ eocd.writeUInt32LE(offset, 16)
82
+ return Buffer.concat([...locals, centralBuf, eocd])
83
+ }
84
+
85
+ module.exports = { buildZip, crc32 }