dsh-extra-plan 0.0.0-stage → 1.7.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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -2
  3. package/assets/presets/extra-plan/agent.cordis.yml +580 -0
  4. package/assets/presets/extra-plan/preset-definition-extra-plan-executor.generated.yml +115 -0
  5. package/assets/presets/extra-plan/preset-definition-extra-plan-planner.generated.yml +113 -0
  6. package/assets/presets/extra-plan/preset-definition-extra-plan-prober.generated.yml +107 -0
  7. package/assets/presets/extra-plan/preset-definition-extra-plan-reviewer.generated.yml +115 -0
  8. package/assets/presets/extra-plan/preset-definition.generated.yml +335 -0
  9. package/assets/presets/extra-plan/preset.yml +2 -0
  10. package/cordis.patch.yml +7 -0
  11. package/index.js +1671 -0
  12. package/lib/agent-runtime.js +172 -0
  13. package/lib/agent-session.js +65 -0
  14. package/lib/assembly-presentation.js +267 -0
  15. package/lib/client-carrier.js +7 -0
  16. package/lib/client.js +314 -0
  17. package/lib/extra-plan-gate-tool.js +387 -0
  18. package/lib/gate-decisions.js +744 -0
  19. package/lib/gate-words.js +108 -0
  20. package/lib/live-config.js +293 -0
  21. package/lib/log-retention.js +132 -0
  22. package/lib/model-routing.js +648 -0
  23. package/lib/path-policy.js +464 -0
  24. package/lib/plan-draft-tool.js +294 -0
  25. package/lib/planner-budget.js +136 -0
  26. package/lib/preset-defaults.generated.js +17 -0
  27. package/lib/preset-settings.js +3 -0
  28. package/lib/preset-sync.js +809 -0
  29. package/lib/preset-yaml.js +438 -0
  30. package/lib/role-contract.js +11 -0
  31. package/lib/run-code-scanner.js +360 -0
  32. package/lib/run-code-static.js +621 -0
  33. package/lib/runtime-diagnostics.js +89 -0
  34. package/lib/runtime-lifecycle.js +162 -0
  35. package/lib/runtime-static.js +23 -0
  36. package/lib/save-contract.js +263 -0
  37. package/lib/save-persistence.js +223 -0
  38. package/lib/save-plan-markdown-parser.js +369 -0
  39. package/lib/save-plan-validation-diagnostics.js +49 -0
  40. package/lib/save-plan-validation.js +812 -0
  41. package/lib/save-probe-validation.js +173 -0
  42. package/lib/save-source-verification.js +195 -0
  43. package/lib/save-tool-factories.js +270 -0
  44. package/lib/sdk-text-cache.js +161 -0
  45. package/lib/settings-contract.js +191 -0
  46. package/lib/settings.js +369 -0
  47. package/lib/shell-mutation.js +484 -0
  48. package/lib/usage-ledger-background.js +214 -0
  49. package/lib/usage-ledger-worker.js +116 -0
  50. package/lib/usage-ledger.js +1393 -0
  51. package/locale/en.json +6 -0
  52. package/locale/settings/en.json +6 -0
  53. package/locale/settings/zh.json +6 -0
  54. package/locale/zh.json +6 -0
  55. package/package.json +56 -4
  56. package/scripts/generate-runtime-defaults.mjs +796 -0
@@ -0,0 +1,812 @@
1
+ import { SAVE_PLAN_LIMITS, formatSavePlanSummary } from './save-contract.js'
2
+ import { parseTaskDocument } from './save-plan-markdown-parser.js'
3
+ import { makeDiagnostic } from './save-plan-validation-diagnostics.js'
4
+
5
+ const CONTRACT_ERROR_PREFIX = 'save_plan: 文件级任务合同校验不通过'
6
+ const MAX_DIAGNOSTICS = 20
7
+
8
+ const GROUP_RE = /^G[1-9]\d*$/
9
+ const REVIEW_GROUP_RE = /^R[1-9]\d*$/
10
+
11
+ const FILE_OPERATION_RE = /^(修改|新建|删除|生成)$/
12
+ const MODIFICATION_POINT_RE = /^M[1-9]\d*$/
13
+ const LOCATION_RE = /^L([1-9]\d*)(?:-([1-9]\d*))?$/
14
+ const EMPTY_FILE_MARKER = '空文件'
15
+
16
+ function isPlaceholderAnchor(value) {
17
+ return /^(?:整个文件|相关逻辑|执行时再找|待确认|待定|占位|TODO|TBD)$/i.test(String(value).trim())
18
+ }
19
+
20
+ function isAcceptancePlaceholder(value) {
21
+ const normalized = String(value).trim().replace(/[。;;,,::]+$/g, '').trim()
22
+ return /^(?:同方案|同上|同前|按方案|见方案|同前文|按上文|M[1-9]\d*)$/.test(normalized)
23
+ }
24
+
25
+ function parseLocation(value) {
26
+ if (typeof value !== 'string') return null
27
+ const match = value.trim().match(LOCATION_RE)
28
+ if (match === null) return null
29
+ const start = Number(match[1])
30
+ const end = match[2] === undefined ? start : Number(match[2])
31
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 1 || end < start) return null
32
+ return { start, end }
33
+ }
34
+
35
+ function pointIdentity(point) {
36
+ return point === null || point === undefined ? '' : String(point.id || '')
37
+ }
38
+
39
+ function validateIds(items, document, diagnostics, kind) {
40
+ const seen = new Map()
41
+ for (const item of items) {
42
+ if (seen.has(item.id)) diagnostics.push(makeDiagnostic(document, item.id, kind + 'ID', item.id, kind + ' ID 不得重复', undefined, item.line))
43
+ else seen.set(item.id, item)
44
+ }
45
+ const ids = Array.from(seen.keys()).sort((a, b) => a - b)
46
+ const continuous = ids.length > 0 && ids.every((id, index) => id === index + 1)
47
+ const ordered = items.every((item, index) => item.id === index + 1)
48
+ if (ids.length > 0 && !continuous) diagnostics.push(makeDiagnostic(document, ids[0], kind + 'ID', ids.join('、'), kind + ' ID 必须从 1 连续递增且不重复', undefined, seen.get(ids[0]).line))
49
+ if (ids.length > 0 && continuous && !ordered) diagnostics.push(makeDiagnostic(document, items[0].id, kind + 'ID', items.map((item) => item.id).join('、'), kind + '块必须按 ID 从 1 递增出现', undefined, items[0].line))
50
+ }
51
+
52
+ function isMarkdownWrapped(path) {
53
+ if (path.includes(String.fromCharCode(96))) return true
54
+ const pairs = [
55
+ ['<', '>'], ['[', ']'], ['(', ')'], ['{', '}'], ['「', '」'], ['『', '』'], ['【', '】'], ['《', '》'],
56
+ ['(', ')'], ['“', '”'], ['"', '"'], ["'", "'"]
57
+ ]
58
+ for (const [open, close] of pairs) if (path.startsWith(open) && path.endsWith(close)) return true
59
+ if (/^\*{1,2}.+\*{1,2}$/.test(path)) return true
60
+ if (/^_{1,2}.+_{1,2}$/.test(path)) return true
61
+ if (/^!?\[[^\]]+\]\([^)]*\)$/.test(path)) return true
62
+ return false
63
+ }
64
+
65
+ function pathIssue(value) {
66
+ if (typeof value !== 'string' || value.trim() === '') return '路径不能为空'
67
+ const path = value.trim()
68
+ if (/(?:#|:|\s+)(?:L)?[1-9]\d*(?:-[1-9]\d*)?$/.test(path)) return '拒绝把行号拼进路径,行号必须写在修改位置字段'
69
+ if (/^[A-Za-z]:/.test(path)) return '拒绝盘符路径,必须使用工作区相对路径'
70
+ if (/^[\\/]/.test(path)) return '拒绝绝对路径,必须使用工作区相对路径'
71
+ if (path.includes('\\')) return '拒绝反斜杠路径,只使用正斜杠'
72
+ if (path.endsWith('/')) return '拒绝尾斜杠,文件路径必须是文件路径'
73
+ const segments = path.split('/')
74
+ if (segments.some((segment) => segment === '')) return '拒绝空路径段'
75
+ if (segments.some((segment) => segment === '.' || segment === '..')) return '拒绝点段路径'
76
+ if (isMarkdownWrapped(path)) return '拒绝 Markdown 包裹,路径必须是裸相对路径'
77
+ return null
78
+ }
79
+
80
+ function workdirIssue(value) {
81
+ if (typeof value !== 'string' || value.trim() === '') return '工作目录不能为空'
82
+ const path = value.trim()
83
+ if (path === '.') return null
84
+ return pathIssue(path)
85
+ }
86
+
87
+ function platformIsCaseInsensitive(options) {
88
+ if (options !== undefined && options !== null && typeof options.platform === 'string') return options.platform === 'win32'
89
+ if (options !== undefined && options !== null && typeof options.caseInsensitive === 'boolean') return options.caseInsensitive
90
+ return process.platform === 'win32'
91
+ }
92
+
93
+ function pathKey(path, options) {
94
+ const normalized = String(path).replace(/\\/g, '/')
95
+ return platformIsCaseInsensitive(options) ? normalized.toLowerCase() : normalized
96
+ }
97
+
98
+ function parseDependencies(value) {
99
+ const raw = typeof value === 'string' ? value.trim() : ''
100
+ if (raw === '无') return { ids: [], issue: null }
101
+ if (raw === '') return { ids: [], issue: '依赖必须是“无”或以[任务N]组成的列表' }
102
+ const parts = raw.split(/[、,,;;]+/).map((part) => part.trim()).filter((part) => part !== '')
103
+ if (parts.length === 0 || parts.some((part) => !/^\[任务[1-9]\d*\]$/.test(part))) return { ids: [], issue: '依赖必须是“无”或以[任务N]组成的列表' }
104
+ const ids = parts.map((part) => Number(part.match(/^\[任务([1-9]\d*)\]$/)[1]))
105
+ if (new Set(ids).size !== ids.length) return { ids, issue: '依赖列表不得重复任务 ID' }
106
+ return { ids, issue: null }
107
+ }
108
+
109
+ function parseResources(value) {
110
+ const raw = typeof value === 'string' ? value.trim() : ''
111
+ if (raw === '无') return { ids: [], issue: null }
112
+ if (raw === '') return { ids: [], issue: '独占资源字段不能为空或写“无”' }
113
+ const parts = raw.split(/[,,]/).map((part) => part.trim())
114
+ if (parts.some((part) => part === '' || part === '无')) return { ids: [], issue: '独占资源必须是“无”或逗号分隔的非空稳定标识' }
115
+ if (new Set(parts).size !== parts.length) return { ids: parts, issue: '独占资源标识不得重复' }
116
+ return { ids: parts, issue: null }
117
+ }
118
+
119
+ function parseCheckRefs(value) {
120
+ const raw = typeof value === 'string' ? value.trim() : ''
121
+ if (raw === '') return { ids: [], issue: '正式验收必须引用一个或多个[检查N]' }
122
+ const parts = raw.split(/[、,,;;\s]+/).map((part) => part.trim()).filter((part) => part !== '')
123
+ if (parts.length === 0 || parts.some((part) => !/^\[检查[1-9]\d*\]$/.test(part))) return { ids: [], issue: '正式验收必须是一个或多个[检查N]引用列表' }
124
+ const ids = parts.map((part) => Number(part.match(/^\[检查([1-9]\d*)\]$/)[1]))
125
+ if (new Set(ids).size !== ids.length) return { ids, issue: '正式验收引用列表不得重复检查 ID' }
126
+ return { ids, issue: null }
127
+ }
128
+
129
+ function addPathDiagnostics(values, document, taskId, field, diagnostics, options, allowDirectory) {
130
+ for (const value of values) {
131
+ const issue = allowDirectory ? workdirIssue(value) : pathIssue(value)
132
+ if (issue !== null) diagnostics.push(makeDiagnostic(document, taskId, field, value, issue))
133
+ }
134
+ }
135
+
136
+ function validatePathSet(task, document, diagnostics, options) {
137
+ addPathDiagnostics(task.mainFiles, document, task.id, '主文件', diagnostics, options, false)
138
+ addPathDiagnostics(task.relatedFiles, document, task.id, '关联文件', diagnostics, options, false)
139
+ const rawSet = new Set()
140
+ const keySet = new Set()
141
+ for (const value of task.mainFiles.concat(task.relatedFiles)) {
142
+ if (typeof value !== 'string' || value === '') continue
143
+ const key = pathKey(value, options)
144
+ if (keySet.has(key)) diagnostics.push(makeDiagnostic(document, task.id, '文件集合', value, '同一任务的主文件和关联文件不得重复'))
145
+ keySet.add(key)
146
+ rawSet.add(value)
147
+ }
148
+ task.fileSet = rawSet
149
+ task.fileKeys = keySet
150
+ }
151
+
152
+ function validateResourceField(owner, document, taskId, diagnostics) {
153
+ if (owner.resources.length > 1) diagnostics.push(makeDiagnostic(document, taskId, '独占资源', owner.resources.join('、'), '独占资源为可选单值字段,不得重复'))
154
+ owner.resourceIds = []
155
+ if (owner.resources.length === 1) {
156
+ const parsed = parseResources(owner.resources[0])
157
+ owner.resourceIds = parsed.ids
158
+ if (parsed.issue !== null) diagnostics.push(makeDiagnostic(document, taskId, '独占资源', owner.resources[0], parsed.issue))
159
+ }
160
+ }
161
+
162
+ function validatePointIds(file, document, taskId, diagnostics, label) {
163
+ const seen = new Set()
164
+ for (const point of file.points) {
165
+ const id = pointIdentity(point)
166
+ if (!MODIFICATION_POINT_RE.test(id)) diagnostics.push(makeDiagnostic(document, taskId, label, id, '修改点 ID 必须是 M 后接非零正整数'))
167
+ if (seen.has(id)) diagnostics.push(makeDiagnostic(document, taskId, label, id, '同一文件内修改点 ID 不得重复'))
168
+ seen.add(id)
169
+ }
170
+ }
171
+
172
+ function validatePlanFileRecord(file, document, taskId, diagnostics, options) {
173
+ const pathIssueValue = pathIssue(file.path)
174
+ if (pathIssueValue !== null) diagnostics.push(makeDiagnostic(document, taskId, file.role === 'closure' ? '收尾文件' : file.role === 'main' ? '主文件' : '关联文件', file.path, pathIssueValue))
175
+ if (file.operations.length !== 1) diagnostics.push(makeDiagnostic(document, taskId, '文件操作', file.operations.join('、'), '每个主、关联或带文件收尾必须恰好有一条文件操作'))
176
+ const operation = file.operations.length === 1 ? file.operations[0] : ''
177
+ if (operation !== '' && !FILE_OPERATION_RE.test(operation)) diagnostics.push(makeDiagnostic(document, taskId, '文件操作', operation, '文件操作只能是修改、新建、删除或生成'))
178
+ if (file.points.length === 0) diagnostics.push(makeDiagnostic(document, taskId, '修改点', '', '每个文件必须至少绑定一个修改点'))
179
+ validatePointIds(file, document, taskId, diagnostics, '修改点')
180
+ if (operation === '修改') {
181
+ for (const point of file.points) {
182
+ if (point.locations.length !== 1) diagnostics.push(makeDiagnostic(document, taskId, '修改位置', point.locations.join('、'), '修改操作的每个修改点必须恰好有一条修改位置'))
183
+ if (point.anchors.length !== 1) diagnostics.push(makeDiagnostic(document, taskId, '定位锚点', point.anchors.join('、'), '修改操作的每个修改点必须恰好有一条定位锚点'))
184
+ if (point.actions.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic(document, taskId, '修改', '', '修改操作的每个修改点必须有非空具体动作'))
185
+ const location = point.locations.length === 1 ? point.locations[0] : ''
186
+ const anchor = point.anchors.length === 1 ? point.anchors[0] : ''
187
+ if (location === EMPTY_FILE_MARKER || anchor === EMPTY_FILE_MARKER) {
188
+ if (file.points.length !== 1 || location !== EMPTY_FILE_MARKER || anchor !== EMPTY_FILE_MARKER) diagnostics.push(makeDiagnostic(document, taskId, '空文件', location + ' / ' + anchor, '空文件例外必须是唯一修改点,且修改位置与定位锚点都写“空文件”'))
189
+ } else {
190
+ if (parseLocation(location) === null) diagnostics.push(makeDiagnostic(document, taskId, '修改位置', location, '修改位置必须是 L12 或 L12-34,端点须为安全正整数且不倒序'))
191
+ if (anchor === '' || anchor.includes('\n') || anchor.includes('\r') || isPlaceholderAnchor(anchor)) diagnostics.push(makeDiagnostic(document, taskId, '定位锚点', anchor, '定位锚点必须是去首尾空白后的非空单行原文片段,不得使用文件级或执行时查找占位'))
192
+ }
193
+ if (point.sources.length > 0 || point.commands.length > 0 || point.outputs.length > 0) diagnostics.push(makeDiagnostic(document, taskId, '生成字段', pointIdentity(point), '生成来源、生成命令和生成产物只能用于生成操作'))
194
+ }
195
+ } else if (operation === '新建' || operation === '删除' || operation === '生成') {
196
+ if (file.points.length !== 1) diagnostics.push(makeDiagnostic(document, taskId, '修改点', String(file.points.length), operation + '操作的每个文件必须恰好有一个修改点'))
197
+ const point = file.points.length === 1 ? file.points[0] : null
198
+ if (point !== null) {
199
+ if (point.actions.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic(document, taskId, '修改', pointIdentity(point), operation + '操作必须填写具体操作说明'))
200
+ if (point.locations.length > 0 || point.anchors.length > 0) diagnostics.push(makeDiagnostic(document, taskId, '修改位置', pointIdentity(point), operation + '操作不得伪填修改位置或原文锚点'))
201
+ if (operation === '删除') {
202
+ const action = point.actions.join(' ')
203
+ if (!/(整文件|整个文件|全文件)/.test(action) || !/(理由|原因|因为)/.test(action) || !/(引用|调用|清理)/.test(action)) diagnostics.push(makeDiagnostic(document, taskId, '修改', action, '删除操作说明必须包含整文件删除、理由与引用清理'))
204
+ }
205
+ if (operation === '生成') {
206
+ if (point.sources.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic(document, taskId, '生成来源', pointIdentity(point), '生成操作必须列出至少一个非空现有工作区来源'))
207
+ if (point.commands.filter((value) => value !== '').length !== 1) diagnostics.push(makeDiagnostic(document, taskId, '生成命令', point.commands.join('、'), '生成操作必须恰好列出一条非空生成命令'))
208
+ if (point.actions.filter((value) => value !== '').length === 0 && point.outputs.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic(document, taskId, '生成产物', pointIdentity(point), '生成操作必须描述产物'))
209
+ for (const source of point.sources) {
210
+ const issue = pathIssue(source)
211
+ if (issue !== null) diagnostics.push(makeDiagnostic(document, taskId, '生成来源', source, issue))
212
+ if (pathKey(source, options) === pathKey(file.path, options)) diagnostics.push(makeDiagnostic(document, taskId, '生成来源', source, '生成来源不得指向自身'))
213
+ }
214
+ } else if (point.sources.length > 0 || point.commands.length > 0 || point.outputs.length > 0) diagnostics.push(makeDiagnostic(document, taskId, '生成字段', pointIdentity(point), '生成来源、生成命令和生成产物只能用于生成操作'))
215
+ }
216
+ }
217
+ }
218
+
219
+ function validatePlanFileRecords(owner, document, taskId, diagnostics, options) {
220
+ if (owner.files.length === 0) diagnostics.push(makeDiagnostic(document, taskId, '文件记录', '', '新合同必须为每个主、关联或收尾文件声明文件操作与修改点'))
221
+ const expectedCount = (owner.mainFiles || []).length + (owner.relatedFiles || []).length + (owner.closureFiles || []).length
222
+ if (owner.files.length !== expectedCount) diagnostics.push(makeDiagnostic(document, taskId, '文件记录', owner.files.length, '文件记录必须与主、关联、收尾文件逐一对应'))
223
+ for (const file of owner.files) validatePlanFileRecord(file, document, taskId, diagnostics, options)
224
+ }
225
+
226
+ function validateAcceptanceFileRecord(file, document, taskId, diagnostics, options) {
227
+ const pathIssueValue = pathIssue(file.path)
228
+ if (pathIssueValue !== null) diagnostics.push(makeDiagnostic(document, taskId, file.role === 'closure' ? '收尾文件' : file.role === 'main' ? '主文件' : '关联文件', file.path, pathIssueValue))
229
+ if (file.operations.length !== 1) diagnostics.push(makeDiagnostic(document, taskId, '文件操作', file.operations.join('、'), '验收中的每个文件必须恰好有一条文件操作'))
230
+ const operation = file.operations.length === 1 ? file.operations[0] : ''
231
+ if (operation !== '' && !FILE_OPERATION_RE.test(operation)) diagnostics.push(makeDiagnostic(document, taskId, '文件操作', operation, '文件操作只能是修改、新建、删除或生成'))
232
+ if (file.points.length === 0) diagnostics.push(makeDiagnostic(document, taskId, '对应修改点', '', '每个验收文件必须绑定至少一个对应修改点'))
233
+ validatePointIds(file, document, taskId, diagnostics, '对应修改点')
234
+ for (const point of file.points) {
235
+ if (point.locations.length !== 1) diagnostics.push(makeDiagnostic(document, taskId, '验收定位', point.locations.join('、'), '每个对应修改点必须恰好有一条非空验收定位'))
236
+ const expectations = point.expectations.filter((value) => value !== '')
237
+ if (expectations.length === 0) diagnostics.push(makeDiagnostic(document, taskId, '期望', pointIdentity(point), '每个对应修改点必须有至少一条客观期望'))
238
+ if (expectations.some(isAcceptancePlaceholder)) diagnostics.push(makeDiagnostic(document, taskId, '期望', expectations.join('、'), '客观期望不得使用同方案、同上、同前或纯 M 编号占位'))
239
+ const location = point.locations.length === 1 ? point.locations[0] : ''
240
+ if (location === '' || location.includes('\n') || location.includes('\r') || isPlaceholderAnchor(location) || isAcceptancePlaceholder(location) || parseLocation(location) !== null) diagnostics.push(makeDiagnostic(document, taskId, '验收定位', location, '验收定位必须是修改后的符号、结构/行为条件或文件存在/不存在条件,不得使用同方案、同上、同前、纯 M 编号或旧行号占位'))
241
+ }
242
+ }
243
+ function validateAcceptanceFileRecords(owner, document, taskId, diagnostics, options) {
244
+ if (owner.files.length === 0) diagnostics.push(makeDiagnostic(document, taskId, '文件记录', '', '新合同必须为每个主、关联或收尾文件声明文件操作与验收对应修改点'))
245
+ const expectedCount = (owner.mainFiles || []).length + (owner.relatedFiles || []).length + (owner.closureFiles || []).length
246
+ if (owner.files.length !== expectedCount) diagnostics.push(makeDiagnostic(document, taskId, '文件记录', owner.files.length, '验收文件记录必须与主、关联、收尾文件逐一对应'))
247
+ for (const file of owner.files) validateAcceptanceFileRecord(file, document, taskId, diagnostics, options)
248
+ }
249
+
250
+ function validateTaskShape(task, document, isPlan, diagnostics, options) {
251
+ if (task.title === '') diagnostics.push(makeDiagnostic(document, task.id, '标题', '', '任务标题不能为空', undefined, task.line))
252
+ if (task.mainFiles.length !== 1) diagnostics.push(makeDiagnostic(document, task.id, '主文件', task.mainFiles.join('、'), '每个任务必须恰好有一个非空主文件', undefined, task.line))
253
+ validatePathSet(task, document, diagnostics, options)
254
+ if (isPlan) {
255
+ validatePlanFileRecords(task, document, task.id, diagnostics, options)
256
+ if (task.groups.length !== 1) diagnostics.push(makeDiagnostic(document, task.id, '执行组', task.groups.join('、'), '每个方案任务必须恰好有一个执行组', undefined, task.line))
257
+ for (const group of task.groups) if (!GROUP_RE.test(group)) diagnostics.push(makeDiagnostic(document, task.id, '执行组', group, '执行组必须匹配 G1、G2 等正整数组名', undefined, task.line))
258
+ if (task.dependencyFields.length !== 1) {
259
+ diagnostics.push(makeDiagnostic(document, task.id, '依赖', task.dependencyFields.join('、'), '每个方案任务必须恰好有一条依赖字段', undefined, task.line))
260
+ } else {
261
+ const parsed = parseDependencies(task.dependencyFields[0])
262
+ task.dependencies = parsed.ids
263
+ if (parsed.issue !== null) diagnostics.push(makeDiagnostic(document, task.id, '依赖', task.dependencyFields[0], parsed.issue, undefined, task.line))
264
+ }
265
+ if (task.dependencyReasons.length !== 1) diagnostics.push(makeDiagnostic(document, task.id, '依赖理由', task.dependencyReasons.join('、'), '每个方案任务必须恰好有一条依赖理由', undefined, task.line))
266
+ if (task.groupReasons.length !== 1) diagnostics.push(makeDiagnostic(document, task.id, '分组理由', task.groupReasons.join('、'), '每个方案任务必须恰好有一条分组理由', undefined, task.line))
267
+ if (task.modifications.length === 0) diagnostics.push(makeDiagnostic(document, task.id, '修改', '', '每个方案任务至少需要一条修改', undefined, task.line))
268
+ if (task.selfChecks.length === 0) diagnostics.push(makeDiagnostic(document, task.id, '自检', '', '每个方案任务至少需要一条自检', undefined, task.line))
269
+ if (task.dependencyReasons.length === 1) {
270
+ const reason = task.dependencyReasons[0].trim()
271
+ if (task.dependencies.length === 0 && reason !== '无') diagnostics.push(makeDiagnostic(document, task.id, '依赖理由', reason, '无依赖时依赖理由必须写“无”', undefined, task.line))
272
+ if (task.dependencies.length > 0 && (reason === '' || reason === '无')) diagnostics.push(makeDiagnostic(document, task.id, '依赖理由', reason, '有依赖时依赖理由必须是非“无”的实现先后说明', undefined, task.line))
273
+ }
274
+ if (task.groupReasons.length === 1 && task.relatedFiles.length > 0 && task.groupReasons[0].trim() === '无') diagnostics.push(makeDiagnostic(document, task.id, '分组理由', task.groupReasons[0], '存在关联文件时必须说明不能安全拆分的原因', undefined, task.line))
275
+ validateResourceField(task, document, task.id, diagnostics)
276
+ } else {
277
+ validateAcceptanceFileRecords(task, document, task.id, diagnostics, options)
278
+ if (task.expectations.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic(document, task.id, '期望', task.expectations.join('、'), '验收任务至少需要一条非空期望', undefined, task.line))
279
+ if (task.prohibitions.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic(document, task.id, '禁止', task.prohibitions.join('、'), '验收任务至少需要一条非空禁止', undefined, task.line))
280
+ if (task.formalAcceptance.length !== 1) diagnostics.push(makeDiagnostic(document, task.id, '正式验收', task.formalAcceptance.join('、'), '每个验收任务必须恰好有一条正式验收引用列表', undefined, task.line))
281
+ if (task.formalAcceptance.length === 1) {
282
+ const parsed = parseCheckRefs(task.formalAcceptance[0])
283
+ task.checkRefs = parsed.ids
284
+ if (parsed.issue !== null) diagnostics.push(makeDiagnostic(document, task.id, '正式验收', task.formalAcceptance[0], parsed.issue, undefined, task.line))
285
+ }
286
+ }
287
+ }
288
+
289
+ function graphCycles(nodes, edges) {
290
+ const colors = new Map()
291
+ const stack = []
292
+ const cycles = []
293
+ const cycleKeys = new Set()
294
+ const visit = (node) => {
295
+ colors.set(node, 1)
296
+ stack.push(node)
297
+ for (const next of edges.get(node) || []) {
298
+ if (colors.get(next) === 1) {
299
+ const start = stack.indexOf(next)
300
+ const cycle = stack.slice(start).concat(next)
301
+ const key = cycle.join('>')
302
+ if (!cycleKeys.has(key)) { cycleKeys.add(key); cycles.push(cycle) }
303
+ } else if (colors.get(next) !== 2) visit(next)
304
+ }
305
+ stack.pop()
306
+ colors.set(node, 2)
307
+ }
308
+ for (const node of nodes) if (colors.get(node) === undefined) visit(node)
309
+ return cycles
310
+ }
311
+
312
+ function groupSort(left, right) {
313
+ const a = Number(String(left).slice(1))
314
+ const b = Number(String(right).slice(1))
315
+ return a - b || String(left).localeCompare(String(right))
316
+ }
317
+
318
+ function firstTaskForGroup(tasks, group) {
319
+ const task = tasks.find((item) => item.groups[0] === group)
320
+ return task === undefined ? null : task.id
321
+ }
322
+
323
+ function validatePlanRelations(tasks, diagnostics, options) {
324
+ const byId = new Map()
325
+ for (const task of tasks) if (!byId.has(task.id)) byId.set(task.id, task)
326
+ const taskEdges = new Map(tasks.map((task) => [task.id, []]))
327
+ for (const task of tasks) {
328
+ for (const dependency of task.dependencies) {
329
+ if (!byId.has(dependency)) {
330
+ diagnostics.push(makeDiagnostic('plan', task.id, '依赖', '[任务' + dependency + ']', '依赖引用的任务 ID 不存在'))
331
+ continue
332
+ }
333
+ if (dependency === task.id) {
334
+ diagnostics.push(makeDiagnostic('plan', task.id, '依赖', '[任务' + dependency + ']', '任务不得依赖自身'))
335
+ continue
336
+ }
337
+ taskEdges.get(task.id).push(dependency)
338
+ }
339
+ }
340
+ for (const cycle of graphCycles(Array.from(taskEdges.keys()).sort((a, b) => a - b), taskEdges)) diagnostics.push(makeDiagnostic('plan', cycle[0], '依赖', cycle.map((id) => '[任务' + id + ']').join('→'), '任务依赖存在环'))
341
+
342
+ const groupEdges = new Map()
343
+ for (const task of tasks) {
344
+ const group = task.groups[0]
345
+ if (typeof group === 'string' && GROUP_RE.test(group) && !groupEdges.has(group)) groupEdges.set(group, [])
346
+ }
347
+ for (const task of tasks) {
348
+ const source = task.groups[0]
349
+ if (!groupEdges.has(source)) continue
350
+ for (const dependency of task.dependencies) {
351
+ const targetTask = byId.get(dependency)
352
+ if (targetTask === undefined) continue
353
+ const target = targetTask.groups[0]
354
+ if (!GROUP_RE.test(target) || source === target) continue
355
+ const edges = groupEdges.get(source)
356
+ if (!edges.includes(target)) edges.push(target)
357
+ if (!groupEdges.has(target)) groupEdges.set(target, [])
358
+ }
359
+ }
360
+ for (const cycle of graphCycles(Array.from(groupEdges.keys()).sort(groupSort), groupEdges)) diagnostics.push(makeDiagnostic('plan', firstTaskForGroup(tasks, cycle[0]), '执行组', cycle.join('→'), '执行组依赖存在环'))
361
+
362
+ const fileOwners = new Map()
363
+ for (const task of tasks) {
364
+ const group = task.groups[0]
365
+ for (const file of task.fileKeys) {
366
+ if (!fileOwners.has(file)) fileOwners.set(file, [])
367
+ const owners = fileOwners.get(file)
368
+ if (!owners.some((owner) => owner.id === task.id)) owners.push({ id: task.id, group })
369
+ }
370
+ }
371
+ for (const [file, owners] of fileOwners) if (owners.length > 1) diagnostics.push(makeDiagnostic('plan', owners[0].id, '文件集合', file, '不同数字任务不得重复使用主文件或关联文件,即使属于同一执行组也不允许'))
372
+
373
+ const groups = new Map()
374
+ for (const task of tasks) {
375
+ const group = task.groups[0]
376
+ if (!GROUP_RE.test(group)) continue
377
+ if (!groups.has(group)) groups.set(group, [])
378
+ groups.get(group).push(task)
379
+ }
380
+ for (const [group, members] of groups) {
381
+ if (members.length <= 1) continue
382
+ const reason = members[0].groupReasons[0] === undefined ? '' : members[0].groupReasons[0].trim()
383
+ if (reason === '' || reason === '无') diagnostics.push(makeDiagnostic('plan', members[0].id, '分组理由', reason, '同一执行组包含多个任务时必须使用相同且非“无”的分组理由'))
384
+ for (const member of members) if (member.groupReasons.length === 1 && member.groupReasons[0].trim() !== reason) diagnostics.push(makeDiagnostic('plan', member.id, '分组理由', member.groupReasons[0], '同一执行组多个任务的分组理由必须完全相同'))
385
+ }
386
+
387
+ const resourceOwners = new Map()
388
+ for (const task of tasks) {
389
+ for (const resource of task.resourceIds) {
390
+ const group = task.groups[0]
391
+ if (!resourceOwners.has(resource)) resourceOwners.set(resource, { group, taskId: task.id })
392
+ else if (resourceOwners.get(resource).group !== group) diagnostics.push(makeDiagnostic('plan', task.id, '独占资源', resource, '相同独占资源的数字任务必须归入同一执行组'))
393
+ }
394
+ }
395
+ }
396
+
397
+ function fileRecordKey(file, options) {
398
+ return String(file.role || '') + '|' + pathKey(file.path, options)
399
+ }
400
+
401
+ function pointIdSet(file) {
402
+ return new Set(file.points.map((point) => pointIdentity(point)))
403
+ }
404
+
405
+ function equalStringSets(left, right) {
406
+ if (left.size !== right.size) return false
407
+ for (const value of left) if (!right.has(value)) return false
408
+ return true
409
+ }
410
+
411
+ function validateFileRecordMapping(planOwner, checklistOwner, documentLabel, taskId, diagnostics, options) {
412
+ const planFiles = new Map()
413
+ const checklistFiles = new Map()
414
+ for (const file of planOwner.files || []) if (!planFiles.has(fileRecordKey(file, options))) planFiles.set(fileRecordKey(file, options), file)
415
+ for (const file of checklistOwner.files || []) if (!checklistFiles.has(fileRecordKey(file, options))) checklistFiles.set(fileRecordKey(file, options), file)
416
+ const keys = new Set(Array.from(planFiles.keys()).concat(Array.from(checklistFiles.keys())))
417
+ for (const key of keys) {
418
+ const planFile = planFiles.get(key)
419
+ const checklistFile = checklistFiles.get(key)
420
+ if (planFile === undefined) {
421
+ diagnostics.push(makeDiagnostic(documentLabel, taskId, '文件记录', key, '验收缺少方案中的文件记录'))
422
+ continue
423
+ }
424
+ if (checklistFile === undefined) {
425
+ diagnostics.push(makeDiagnostic(documentLabel, taskId, '文件记录', key, '方案文件缺少验收对应文件记录'))
426
+ continue
427
+ }
428
+ const planOperation = planFile.operations.length === 1 ? planFile.operations[0] : ''
429
+ const checklistOperation = checklistFile.operations.length === 1 ? checklistFile.operations[0] : ''
430
+ if (planOperation !== checklistOperation) diagnostics.push(makeDiagnostic(documentLabel, taskId, '文件操作', planFile.path + ':' + planOperation + ' <> ' + checklistOperation, '方案与验收的同文件操作必须一致'))
431
+ if (!equalStringSets(pointIdSet(planFile), pointIdSet(checklistFile))) diagnostics.push(makeDiagnostic(documentLabel, taskId, '修改点', planFile.path, '方案与验收的同文件修改点 ID 集合必须精确一致'))
432
+ }
433
+ }
434
+
435
+ function validateCrossDocument(plan, checklist, diagnostics, options) {
436
+ const planById = new Map()
437
+ const checklistById = new Map()
438
+ for (const task of plan.tasks) if (!planById.has(task.id)) planById.set(task.id, task)
439
+ for (const task of checklist.tasks) if (!checklistById.has(task.id)) checklistById.set(task.id, task)
440
+ const allIds = Array.from(new Set(Array.from(planById.keys()).concat(Array.from(checklistById.keys())))).sort((a, b) => a - b)
441
+ for (const id of allIds) {
442
+ const planTask = planById.get(id)
443
+ const checklistTask = checklistById.get(id)
444
+ if (planTask === undefined) { diagnostics.push(makeDiagnostic('plan/checklist', id, '任务ID', id, '方案缺少验收中存在的任务 ID')); continue }
445
+ if (checklistTask === undefined) { diagnostics.push(makeDiagnostic('plan/checklist', id, '任务ID', id, '验收缺少方案中存在的任务 ID')); continue }
446
+ if ((planTask.mainFiles[0] || '') !== (checklistTask.mainFiles[0] || '') && pathKey(planTask.mainFiles[0] || '', options) !== pathKey(checklistTask.mainFiles[0] || '', options)) diagnostics.push(makeDiagnostic('plan/checklist', id, '主文件', (planTask.mainFiles[0] || '') + ' <> ' + (checklistTask.mainFiles[0] || ''), '方案与验收的主文件必须一致'))
447
+ const planSet = new Set(planTask.mainFiles.concat(planTask.relatedFiles).map((value) => pathKey(value, options)))
448
+ const checklistSet = new Set(checklistTask.mainFiles.concat(checklistTask.relatedFiles).map((value) => pathKey(value, options)))
449
+ if (!equalStringSets(planSet, checklistSet)) diagnostics.push(makeDiagnostic('plan/checklist', id, '文件集合', Array.from(planTask.fileSet).join('、') + ' <> ' + Array.from(checklistTask.fileSet).join('、'), '方案与验收的主文件加关联文件集合必须一致'))
450
+ validateFileRecordMapping(planTask, checklistTask, 'plan/checklist', id, diagnostics, options)
451
+ }
452
+ if ((plan.closure === null) !== (checklist.closure === null)) diagnostics.push(makeDiagnostic('plan/checklist', null, '收尾', '', '方案与验收必须同时存在或同时省略收尾'))
453
+ if (plan.closure !== null && checklist.closure !== null) {
454
+ const planClosureFiles = new Set(plan.closure.closureFiles.map((value) => pathKey(value, options)))
455
+ const checklistClosureFiles = new Set(checklist.closure.closureFiles.map((value) => pathKey(value, options)))
456
+ if (!equalStringSets(planClosureFiles, checklistClosureFiles)) diagnostics.push(makeDiagnostic('plan/checklist', null, '收尾文件', plan.closure.closureFiles.join('、') + ' <> ' + checklist.closure.closureFiles.join('、'), '方案与验收的收尾文件集合必须一致'))
457
+ validateFileRecordMapping(plan.closure, checklist.closure, 'plan/checklist', null, diagnostics, options)
458
+ }
459
+ }
460
+
461
+ function validateClosure(closure, document, isPlan, tasks, diagnostics, options) {
462
+ if (closure === null) return
463
+ if (isPlan) {
464
+ addPathDiagnostics(closure.closureFiles, document, null, '收尾文件', diagnostics, options, false)
465
+ if (closure.closureFiles.length > 0) validatePlanFileRecords(closure, document, null, diagnostics, options)
466
+ const rawSet = new Set()
467
+ const keySet = new Set()
468
+ for (const value of closure.closureFiles) {
469
+ const key = pathKey(value, options)
470
+ if (keySet.has(key)) diagnostics.push(makeDiagnostic(document, null, '收尾文件', value, '收尾文件不得重复'))
471
+ keySet.add(key)
472
+ rawSet.add(value)
473
+ }
474
+ closure.fileSet = rawSet
475
+ closure.fileKeys = keySet
476
+ if (closure.closureDependencies.length !== 1) diagnostics.push(makeDiagnostic(document, null, '收尾依赖', closure.closureDependencies.join('、'), '收尾必须恰好有一条收尾依赖'))
477
+ else {
478
+ const parsed = parseDependencies(closure.closureDependencies[0])
479
+ closure.dependencies = parsed.ids
480
+ if (parsed.issue !== null) diagnostics.push(makeDiagnostic(document, null, '收尾依赖', closure.closureDependencies[0], '收尾依赖必须列出全部数字任务'))
481
+ }
482
+ if (closure.closureActions.length === 0) diagnostics.push(makeDiagnostic(document, null, '收尾动作', '', '收尾至少需要一条收尾动作'))
483
+ if (closure.selfChecks.length === 0) diagnostics.push(makeDiagnostic(document, null, '自检', '', '收尾至少需要一条自检'))
484
+ validateResourceField(closure, document, null, diagnostics)
485
+ const allIds = new Set(tasks.map((task) => task.id))
486
+ if (closure.dependencies.length !== allIds.size || closure.dependencies.some((id) => !allIds.has(id)) || new Set(closure.dependencies).size !== allIds.size) diagnostics.push(makeDiagnostic(document, null, '收尾依赖', closure.dependencies.map((id) => '[任务' + id + ']').join('、'), '收尾依赖必须恰好覆盖全部数字任务且不得重复'))
487
+ for (const file of closure.fileKeys) if (tasks.some((task) => task.fileKeys.has(file))) diagnostics.push(makeDiagnostic(document, null, '收尾文件', file, '收尾文件不得与数字任务修改文件重叠'))
488
+ } else {
489
+ addPathDiagnostics(closure.closureFiles, document, null, '收尾文件', diagnostics, options, false)
490
+ if (closure.closureFiles.length > 0) validateAcceptanceFileRecords(closure, document, null, diagnostics, options)
491
+ const rawSet = new Set()
492
+ const keySet = new Set()
493
+ for (const value of closure.closureFiles) {
494
+ const key = pathKey(value, options)
495
+ if (keySet.has(key)) diagnostics.push(makeDiagnostic(document, null, '收尾文件', value, '收尾文件不得重复'))
496
+ keySet.add(key)
497
+ rawSet.add(value)
498
+ }
499
+ closure.fileSet = rawSet
500
+ closure.fileKeys = keySet
501
+ if (closure.fileKeys.size > 0 && tasks.some((task) => Array.from(closure.fileKeys).some((file) => task.fileKeys.has(file)))) diagnostics.push(makeDiagnostic(document, null, '收尾文件', Array.from(closure.fileSet).join('、'), '收尾文件不得与数字任务修改文件重叠'))
502
+ if (closure.expectations.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic(document, null, '期望', '', '验收收尾至少需要一条期望'))
503
+ if (closure.prohibitions.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic(document, null, '禁止', '', '验收收尾至少需要一条禁止'))
504
+ if (closure.formalAcceptance.length !== 1) diagnostics.push(makeDiagnostic(document, null, '正式验收', closure.formalAcceptance.join('、'), '验收收尾必须恰好有一条正式验收引用列表'))
505
+ if (closure.formalAcceptance.length === 1) {
506
+ const parsed = parseCheckRefs(closure.formalAcceptance[0])
507
+ closure.checkRefs = parsed.ids
508
+ if (parsed.issue !== null) diagnostics.push(makeDiagnostic(document, null, '正式验收', closure.formalAcceptance[0], parsed.issue))
509
+ }
510
+ }
511
+ }
512
+
513
+ function validateGlobal(global, diagnostics) {
514
+ if (global === null) return
515
+ if (global.expectations.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic('checklist', null, '期望', '', '全局验收至少需要一条期望'))
516
+ if (global.prohibitions.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic('checklist', null, '禁止', '', '全局验收至少需要一条禁止'))
517
+ if (global.formalAcceptance.length !== 1) diagnostics.push(makeDiagnostic('checklist', null, '正式验收', global.formalAcceptance.join('、'), '全局验收必须恰好有一条正式验收引用列表'))
518
+ if (global.formalAcceptance.length === 1) {
519
+ const parsed = parseCheckRefs(global.formalAcceptance[0])
520
+ global.checkRefs = parsed.ids
521
+ if (parsed.issue !== null) diagnostics.push(makeDiagnostic('checklist', null, '正式验收', global.formalAcceptance[0], parsed.issue))
522
+ }
523
+ }
524
+
525
+ function validateChecks(parsed, diagnostics, options) {
526
+ if (parsed.checks.length === 0) diagnostics.push(makeDiagnostic('checklist', null, '检查块', '', '验收至少需要一个检查定义'))
527
+ validateIds(parsed.checks, 'checklist', diagnostics, '检查')
528
+ const signatureOwners = new Map()
529
+ const resourceOwners = new Map()
530
+ const checkById = new Map()
531
+ for (const check of parsed.checks) {
532
+ checkById.set(check.id, check)
533
+ if (check.title === '') diagnostics.push(makeDiagnostic('checklist', null, '标题', '', '检查标题不能为空'))
534
+ if (check.reviewGroups.length !== 1) diagnostics.push(makeDiagnostic('checklist', null, '验收组', check.reviewGroups.join('、'), '每个检查必须恰好有一个验收组'))
535
+ if (check.reviewGroups.length === 1 && !REVIEW_GROUP_RE.test(check.reviewGroups[0])) diagnostics.push(makeDiagnostic('checklist', null, '验收组', check.reviewGroups[0], '验收组必须匹配 R1、R2 等正整数组名'))
536
+ if (check.evidenceModes.length !== 1) diagnostics.push(makeDiagnostic('checklist', null, '取证方式', check.evidenceModes.join('、'), '每个检查必须恰好有一个取证方式'))
537
+ if (check.evidenceModes.length === 1 && check.evidenceModes[0] !== '只读复核' && check.evidenceModes[0] !== '执行取证') diagnostics.push(makeDiagnostic('checklist', null, '取证方式', check.evidenceModes[0], '取证方式只能是“只读复核”或“执行取证”'))
538
+ if (check.workdirs.length !== 1) diagnostics.push(makeDiagnostic('checklist', null, '工作目录', check.workdirs.join('、'), '每个检查必须恰好有一个工作目录'))
539
+ if (check.workdirs.length === 1) {
540
+ const issue = workdirIssue(check.workdirs[0])
541
+ if (issue !== null) diagnostics.push(makeDiagnostic('checklist', null, '工作目录', check.workdirs[0], issue))
542
+ }
543
+ if (check.checks.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic('checklist', null, '检查', '', '每个检查至少需要一条检查动作'))
544
+ if (check.evidence.filter((value) => value !== '').length === 0) diagnostics.push(makeDiagnostic('checklist', null, '验收证据', '', '每个检查至少需要一条验收证据'))
545
+ validateResourceField(check, 'checklist', null, diagnostics)
546
+ if (check.reviewGroups.length === 1 && check.evidenceModes.length === 1 && check.workdirs.length === 1) {
547
+ const signature = JSON.stringify([check.evidenceModes[0], pathKey(check.workdirs[0], options), check.checks])
548
+ if (signatureOwners.has(signature)) diagnostics.push(makeDiagnostic('checklist', null, '检查', check.title, '不同检查 ID 不得重复定义相同的取证方式、工作目录和检查行;请合并并复用同一检查 ID'))
549
+ else signatureOwners.set(signature, check.id)
550
+ }
551
+ if (check.reviewGroups.length === 1 && REVIEW_GROUP_RE.test(check.reviewGroups[0])) {
552
+ const group = check.reviewGroups[0]
553
+ for (const resource of check.resourceIds) {
554
+ if (!resourceOwners.has(resource)) resourceOwners.set(resource, group)
555
+ else if (resourceOwners.get(resource) !== group) diagnostics.push(makeDiagnostic('checklist', null, '独占资源', resource, '相同独占资源的检查必须归入同一验收组'))
556
+ }
557
+ }
558
+ }
559
+ const allCheckIds = new Set(parsed.checks.map((check) => check.id))
560
+ const attachRefs = (owner, taskId) => {
561
+ if (owner === null || owner === undefined || owner.formalAcceptance.length !== 1) return
562
+ const parsedRefs = parseCheckRefs(owner.formalAcceptance[0])
563
+ owner.checkRefs = parsedRefs.ids
564
+ if (parsedRefs.issue !== null) return
565
+ for (const id of owner.checkRefs) {
566
+ if (!allCheckIds.has(id)) diagnostics.push(makeDiagnostic('checklist', taskId, '正式验收', '[检查' + id + ']', '正式验收引用的检查 ID 不存在'))
567
+ const check = checkById.get(id)
568
+ if (check === undefined) continue
569
+ if (owner.kind === 'task') check.coverageTasks.push(owner.id)
570
+ else if (owner.kind === 'closure') check.coverageClosure = true
571
+ else if (owner.kind === 'global') check.coverageGlobal = true
572
+ }
573
+ }
574
+ for (const task of parsed.tasks) attachRefs(task, task.id)
575
+ attachRefs(parsed.closure, null)
576
+ attachRefs(parsed.global, null)
577
+ for (const check of parsed.checks) {
578
+ check.coverageTasks = Array.from(new Set(check.coverageTasks)).sort((a, b) => a - b)
579
+ if (!check.coverageTasks.length && !check.coverageClosure && !check.coverageGlobal) diagnostics.push(makeDiagnostic('checklist', null, '检查' + check.id, check.title, '检查定义不得成为孤儿,至少被任务、收尾或全局验收引用一次'))
580
+ }
581
+ return { checkById }
582
+ }
583
+
584
+ function sortIds(ids) {
585
+ return Array.from(new Set(ids)).sort((a, b) => a - b)
586
+ }
587
+
588
+ function buildInternalOrder(members, byId) {
589
+ const memberIds = members.map((task) => task.id).sort((a, b) => a - b)
590
+ const indegree = new Map(memberIds.map((id) => [id, 0]))
591
+ const next = new Map(memberIds.map((id) => [id, []]))
592
+ for (const id of memberIds) {
593
+ const task = byId.get(id)
594
+ for (const dependency of task.dependencies) {
595
+ if (!indegree.has(dependency)) continue
596
+ indegree.set(id, indegree.get(id) + 1)
597
+ next.get(dependency).push(id)
598
+ }
599
+ }
600
+ const queue = memberIds.filter((id) => indegree.get(id) === 0)
601
+ const order = []
602
+ while (queue.length > 0) {
603
+ queue.sort((a, b) => a - b)
604
+ const id = queue.shift()
605
+ order.push(id)
606
+ for (const child of next.get(id) || []) {
607
+ indegree.set(child, indegree.get(child) - 1)
608
+ if (indegree.get(child) === 0) queue.push(child)
609
+ }
610
+ }
611
+ return order.length === memberIds.length ? order : memberIds
612
+ }
613
+
614
+ function summarizeFileRecord(file) {
615
+ return {
616
+ path: file.path,
617
+ role: file.role,
618
+ operation: file.operations.length === 1 ? file.operations[0] : '',
619
+ points: file.points.map((point) => {
620
+ const locations = Array.isArray(point.locations) ? point.locations : []
621
+ const anchors = Array.isArray(point.anchors) ? point.anchors : []
622
+ return {
623
+ id: pointIdentity(point),
624
+ modificationLocation: locations.length > 0 ? locations[0] : '',
625
+ anchor: anchors.length > 0 ? anchors[0] : '',
626
+ actions: Array.isArray(point.actions) ? point.actions.slice() : [],
627
+ generationSources: Array.isArray(point.sources) ? point.sources.slice() : [],
628
+ generationCommands: Array.isArray(point.commands) ? point.commands.slice() : [],
629
+ generationOutputs: Array.isArray(point.outputs) ? point.outputs.slice() : [],
630
+ acceptanceLocation: locations.length > 0 ? locations[0] : '',
631
+ expectations: Array.isArray(point.expectations) ? point.expectations.slice() : []
632
+ }
633
+ })
634
+ }
635
+ }
636
+
637
+ function buildSummary(plan, checklist) {
638
+ const taskById = new Map(plan.tasks.map((task) => [task.id, task]))
639
+ const files = new Set()
640
+ for (const task of plan.tasks) for (const key of task.fileKeys) files.add(key)
641
+ const closureFiles = new Set(plan.closure === null ? [] : Array.from(plan.closure.fileKeys))
642
+ const taskFileCount = files.size
643
+ const fileCount = taskFileCount + closureFiles.size
644
+ const groupMap = new Map()
645
+ for (const task of plan.tasks) {
646
+ const group = task.groups[0]
647
+ if (!groupMap.has(group)) groupMap.set(group, [])
648
+ groupMap.get(group).push(task)
649
+ }
650
+ const groupIds = Array.from(groupMap.keys()).sort(groupSort)
651
+ const groups = groupIds.map((group) => {
652
+ const members = groupMap.get(group)
653
+ const external = []
654
+ const resources = []
655
+ for (const task of members) {
656
+ for (const dependency of task.dependencies) {
657
+ const dependencyTask = taskById.get(dependency)
658
+ if (dependencyTask !== undefined && dependencyTask.groups[0] !== group) external.push(dependencyTask.groups[0])
659
+ }
660
+ resources.push(...task.resourceIds)
661
+ }
662
+ const groupDependsOn = Array.from(new Set(external)).sort(groupSort)
663
+ return {
664
+ id: group,
665
+ group,
666
+ members: members.map((task) => task.id).sort((a, b) => a - b),
667
+ internalOrder: buildInternalOrder(members, taskById),
668
+ groupDependsOn,
669
+ externalDependencies: groupDependsOn.slice(),
670
+ initialState: groupDependsOn.length === 0 ? 'eligible' : 'waiting',
671
+ staticEligibility: groupDependsOn.length === 0 ? 'initially-eligible' : 'waits-for-prerequisite-delivery',
672
+ resources: Array.from(new Set(resources))
673
+ }
674
+ })
675
+ const checklistById = new Map(checklist.tasks.map((task) => [task.id, task]))
676
+ const tasks = plan.tasks.map((task) => {
677
+ const checklistTask = checklistById.get(task.id)
678
+ return {
679
+ id: task.id,
680
+ title: task.title,
681
+ mainFiles: task.mainFiles.slice(),
682
+ relatedFiles: task.relatedFiles.slice(),
683
+ files: task.mainFiles.concat(task.relatedFiles),
684
+ fileRecords: task.files.map(summarizeFileRecord),
685
+ acceptanceFileRecords: checklistTask === undefined ? [] : checklistTask.files.map(summarizeFileRecord),
686
+ executionGroup: task.groups[0],
687
+ group: task.groups[0],
688
+ dependencies: task.dependencies.slice(),
689
+ dependencyReason: task.dependencyReasons[0] || '',
690
+ groupReason: task.groupReasons[0] || '',
691
+ modifications: task.modifications.slice(),
692
+ selfChecks: task.selfChecks.slice(),
693
+ resources: task.resourceIds.slice()
694
+ }
695
+ })
696
+ const checks = checklist.checks.map((check) => ({
697
+ id: check.id,
698
+ title: check.title,
699
+ reviewGroup: check.reviewGroups[0],
700
+ evidenceMode: check.evidenceModes[0],
701
+ workdir: check.workdirs[0],
702
+ checks: check.checks.slice(),
703
+ evidence: check.evidence.slice(),
704
+ coverage: { tasks: sortIds(check.coverageTasks), closure: check.coverageClosure === true, global: check.coverageGlobal === true },
705
+ coverageKey: ['tasks:' + sortIds(check.coverageTasks).join(','), check.coverageClosure ? 'closure' : '', check.coverageGlobal ? 'global' : ''].filter((value) => value !== '').join('|'),
706
+ resources: check.resourceIds.slice()
707
+ }))
708
+ const reviewGroupMap = new Map()
709
+ for (const check of checklist.checks) {
710
+ const group = check.reviewGroups[0]
711
+ if (!reviewGroupMap.has(group)) reviewGroupMap.set(group, [])
712
+ reviewGroupMap.get(group).push(check)
713
+ }
714
+ const reviewGroups = Array.from(reviewGroupMap.keys()).sort(groupSort).map((group) => {
715
+ const members = reviewGroupMap.get(group)
716
+ return {
717
+ id: group,
718
+ reviewGroup: group,
719
+ checks: members.map((check) => check.id),
720
+ coverage: { tasks: sortIds(members.flatMap((check) => check.coverageTasks)), closure: members.some((check) => check.coverageClosure), global: members.some((check) => check.coverageGlobal) }
721
+ }
722
+ })
723
+ const closure = plan.closure === null ? null : {
724
+ files: plan.closure.closureFiles.slice(),
725
+ dependencies: plan.closure.dependencies.slice(),
726
+ actions: plan.closure.closureActions.slice(),
727
+ selfChecks: plan.closure.selfChecks.slice(),
728
+ resources: plan.closure.resourceIds.slice(),
729
+ checkRefs: checklist.closure === null ? [] : checklist.closure.checkRefs.slice(),
730
+ fileRecords: plan.closure.files.map(summarizeFileRecord),
731
+ acceptanceFileRecords: checklist.closure === null ? [] : checklist.closure.files.map(summarizeFileRecord),
732
+ coverageKey: 'closure'
733
+ }
734
+ const globalAcceptance = checklist.global === null ? null : {
735
+ expectations: checklist.global.expectations.slice(),
736
+ prohibitions: checklist.global.prohibitions.slice(),
737
+ checkRefs: checklist.global.checkRefs.slice(),
738
+ coverageKey: 'global'
739
+ }
740
+ return {
741
+ taskCount: plan.tasks.length,
742
+ taskFileCount,
743
+ fileCount,
744
+ closureFileCount: closureFiles.size,
745
+ totalFileCount: fileCount,
746
+ groupCount: groupIds.length,
747
+ reviewGroupCount: reviewGroups.length,
748
+ checkCount: checks.length,
749
+ hasClosure: plan.closure !== null,
750
+ hasGlobalAcceptance: checklist.global !== null,
751
+ tasks,
752
+ groups,
753
+ checks,
754
+ reviewGroups,
755
+ closure,
756
+ globalAcceptance,
757
+ global: globalAcceptance
758
+ }
759
+ }
760
+
761
+ function formatDiagnostic(diagnostic) {
762
+ const document = diagnostic.document || 'plan/checklist'
763
+ const task = diagnostic.taskId === null || diagnostic.taskId === undefined ? '任务全局' : '任务' + diagnostic.taskId
764
+ const value = String(diagnostic.value || '').replace(/[\r\n]+/g, ' ').slice(0, 240)
765
+ const position = Number.isInteger(diagnostic.line) && diagnostic.line > 0 ? ';位置:第 ' + diagnostic.line + ' 行' : ''
766
+ return '- ' + document + ' ' + task + ' 字段「' + diagnostic.field + '」值「' + value + '」:' + diagnostic.message + position + ';最小修复模板:' + diagnostic.template
767
+ }
768
+
769
+ function finalizeFailure(diagnostics) {
770
+ const shown = diagnostics.slice(0, MAX_DIAGNOSTICS)
771
+ const remaining = diagnostics.length - shown.length
772
+ let error = CONTRACT_ERROR_PREFIX + '(共 ' + diagnostics.length + ' 条诊断):\n' + shown.map(formatDiagnostic).join('\n')
773
+ if (remaining > 0) error += '\n- 其余剩余 ' + remaining + ' 条诊断已省略'
774
+ return { ok: false, diagnostics: shown, diagnosticCount: diagnostics.length, remaining, error }
775
+ }
776
+
777
+ export function validateSavePlanContract(plan, checklist, options) {
778
+ if (plan !== null && typeof plan === 'object' && typeof plan.plan === 'string' && (checklist === undefined || typeof checklist !== 'string')) {
779
+ if (options === undefined && checklist !== undefined && checklist !== null && typeof checklist === 'object') options = checklist
780
+ checklist = plan.checklist
781
+ plan = plan.plan
782
+ }
783
+ const diagnostics = []
784
+ const parsedPlan = parseTaskDocument(plan, 'plan')
785
+ const parsedChecklist = parseTaskDocument(checklist, 'checklist')
786
+ diagnostics.push(...parsedPlan.diagnostics, ...parsedChecklist.diagnostics)
787
+ if (parsedPlan.tasks.length === 0) diagnostics.push(makeDiagnostic('plan', null, '任务块', '', '方案至少需要一个任务块'))
788
+ if (parsedChecklist.tasks.length === 0) diagnostics.push(makeDiagnostic('checklist', null, '任务块', '', '验收至少需要一个任务块'))
789
+ validateIds(parsedPlan.tasks, 'plan', diagnostics, '任务')
790
+ validateIds(parsedChecklist.tasks, 'checklist', diagnostics, '任务')
791
+ if (parsedPlan.tasks.length > SAVE_PLAN_LIMITS.maxTasks) diagnostics.push(makeDiagnostic('plan', null, '任务数', parsedPlan.tasks.length, '任务数不得超过 ' + SAVE_PLAN_LIMITS.maxTasks + ' 个'))
792
+ if (parsedChecklist.tasks.length > SAVE_PLAN_LIMITS.maxTasks) diagnostics.push(makeDiagnostic('checklist', null, '任务数', parsedChecklist.tasks.length, '任务数不得超过 ' + SAVE_PLAN_LIMITS.maxTasks + ' 个'))
793
+ for (const task of parsedPlan.tasks) validateTaskShape(task, 'plan', true, diagnostics, options)
794
+ for (const task of parsedChecklist.tasks) validateTaskShape(task, 'checklist', false, diagnostics, options)
795
+ validatePlanRelations(parsedPlan.tasks, diagnostics, options)
796
+ validateClosure(parsedPlan.closure, 'plan', true, parsedPlan.tasks, diagnostics, options)
797
+ validateClosure(parsedChecklist.closure, 'checklist', false, parsedChecklist.tasks, diagnostics, options)
798
+ validateCrossDocument(parsedPlan, parsedChecklist, diagnostics, options)
799
+ validateGlobal(parsedChecklist.global, diagnostics)
800
+ validateChecks(parsedChecklist, diagnostics, options)
801
+ if (diagnostics.length > 0) return { ...finalizeFailure(diagnostics), limitExceeded: false }
802
+ const summary = buildSummary(parsedPlan, parsedChecklist)
803
+ const summaryText = formatSavePlanSummary(summary)
804
+ summary.summaryCharCount = summaryText.length
805
+ if (summaryText.length > SAVE_PLAN_LIMITS.maxSummaryChars) {
806
+ diagnostics.push(makeDiagnostic('plan/checklist', null, '派遣摘要', summaryText.length, '确定性派遣摘要超过 ' + SAVE_PLAN_LIMITS.maxSummaryChars + ' 字符上限;请减少任务、检查或正文重复'))
807
+ return { ...finalizeFailure(diagnostics), limitExceeded: true }
808
+ }
809
+ return { ok: true, summary, diagnostics: [], limitExceeded: false }
810
+ }
811
+
812
+ export { parseTaskDocument, CONTRACT_ERROR_PREFIX, pathIssue, parseDependencies, parseResources, parseCheckRefs }