dsh-workplan 1.7.1 → 1.8.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.
- package/CHANGELOG.md +39 -0
- package/README.en.md +40 -1
- package/README.md +39 -1
- package/SECURITY.md +109 -0
- package/docs/SBOM.md +113 -0
- package/docs/cc/AVA-VULNERABILITY-ANALYSIS.md +97 -0
- package/docs/cc/CC-2026-ASSESSMENT.md +254 -0
- package/docs/cc/SECURITY-TARGET.md +239 -0
- package/docs/collaboration.md +440 -0
- package/docs/collapse-interaction-spec.md +272 -0
- package/docs/defect-report-count-inconsistency.md +370 -0
- package/docs/departments.md +194 -0
- package/docs/design-proposals/state-machine.reference.ts +836 -0
- package/docs/design-proposals/state-machine.test.reference.ts +655 -0
- package/docs/fix-report-derived-counts-1.4.3.md +199 -0
- package/docs/fix-report-phase-percent-1.5.2.md +284 -0
- package/docs/preview/progress-visual-1.5.0.html +683 -0
- package/docs/progress-visualization-clarify-20261028.md +211 -0
- package/docs/progress-visualization-design-20261028.md +607 -0
- package/docs/progress-visualization-locate-20261028.md +159 -0
- package/docs/progress-visualization-report-1.5.0.md +140 -0
- package/docs/release-notes-1.7.0.md +46 -0
- package/docs/release-notes-1.7.1.md +36 -0
- package/docs/release-record-1.5.1-20261028.md +258 -0
- package/docs/release-record-1.5.2-20261029.md +101 -0
- package/docs/release-record-1.7.0-20261030.md +58 -0
- package/docs/release-record-1.7.1-20261030.md +56 -0
- package/docs/repro-count-inconsistency.md +310 -0
- package/docs/review-collaboration-20261030.md +246 -0
- package/docs/root-cause-phase-percent.md +866 -0
- package/docs/state-progress-matrix.md +517 -0
- package/docs/status-grouping-ia.md +789 -0
- package/docs/stuck-review-1.3.0.md +646 -0
- package/docs/t4-contrast-measurement.json +496 -0
- package/docs/t4-contrast-measurement.md +177 -0
- package/docs/t8-fix-prioritization.md +105 -0
- package/docs/version-upgrade-rollback-1.5.0-20261028.md +654 -0
- package/docs/visual-refinement-spec.md +164 -0
- package/lib/host.js +3 -2
- package/lib/runtime.js +21 -0
- package/package.json +4 -2
- package/src/host.ts +3 -1
- package/src/runtime.ts +22 -0
|
@@ -0,0 +1,836 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* dsh-workplan — 子任务状态机、重置语义与不变量(单一真相源设计)
|
|
3
|
+
*
|
|
4
|
+
* 设计规则(详见 docs/state-machine-design.md):
|
|
5
|
+
*
|
|
6
|
+
* 1. `statuses[]` 是唯一事实:每个子任务的状态、进度、时间戳、childId、
|
|
7
|
+
* 摘要与错误只存在于这一处。
|
|
8
|
+
* 2. `stats` / `departments` 永远是派生值:只能由同一份 statuses 快照现算,
|
|
9
|
+
* 不允许缓存、不允许在别处累加(T2 缺陷 D1/D2/D4 的根因)。
|
|
10
|
+
* 3. `phase` 是生命周期状态,只由事件改变(PLAN_PHASE_EVENTS 表);不得由
|
|
11
|
+
* 序列化层“顺手”改写,也不得用 planPhase() 无条件覆盖。
|
|
12
|
+
* 4. 任何写入必须经过本模块的迁移函数;状态与伴随字段一起写,避免
|
|
13
|
+
* `pending + progress=100 + childId` 这类自相矛盾的组合。
|
|
14
|
+
* 5. 重置 = 回到初始态:必须同时清空 progress/childId/startedAt/finishedAt/
|
|
15
|
+
* summary/error 六个伴随字段。
|
|
16
|
+
* 6. 归一化(normalise)只用于读取历史/外部数据;断言(assert)用于写入后与
|
|
17
|
+
* 下发前。顺序固定为“先归一化、再断言”,否则旧数据会误报。
|
|
18
|
+
*
|
|
19
|
+
* 本文件是纯函数模块,不依赖 runtime / client,便于被任何一侧复用与测试。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** 子任务的四个合法状态。顺序即 UI 的展示顺序。 */
|
|
23
|
+
export const SUBTASK_STATUSES = ['pending', 'in_progress', 'done', 'blocked'] as const
|
|
24
|
+
export type SubtaskStatus = (typeof SUBTASK_STATUSES)[number]
|
|
25
|
+
|
|
26
|
+
/** 计划生命周期的九个合法阶段(与 docs/status-grouping-ia.md 的九值一致)。 */
|
|
27
|
+
export const PLAN_PHASES = [
|
|
28
|
+
'pending',
|
|
29
|
+
'planning',
|
|
30
|
+
'executing',
|
|
31
|
+
'integrating',
|
|
32
|
+
'paused',
|
|
33
|
+
'blocked',
|
|
34
|
+
'degraded',
|
|
35
|
+
'cancelled',
|
|
36
|
+
'done',
|
|
37
|
+
] as const
|
|
38
|
+
export type PlanPhase = (typeof PLAN_PHASES)[number]
|
|
39
|
+
|
|
40
|
+
/** 刚启动时的进度(沿用 1.4.x 行为:先给 5%,再在子 Agent 绑定后到 10%)。 */
|
|
41
|
+
export const START_PROGRESS = 5
|
|
42
|
+
/** 子 Agent 绑定成功后的进度。 */
|
|
43
|
+
export const ATTACH_PROGRESS = 10
|
|
44
|
+
/** blocked 却没有任何可读原因时的兜底文案(保证“受阻必有原因”不变量)。 */
|
|
45
|
+
export const BLOCKED_REASON_FALLBACK = '受阻(未记录原因)'
|
|
46
|
+
|
|
47
|
+
const STATUS_SET: ReadonlySet<string> = new Set<string>(SUBTASK_STATUSES)
|
|
48
|
+
const PHASE_SET: ReadonlySet<string> = new Set<string>(PLAN_PHASES)
|
|
49
|
+
|
|
50
|
+
export function isSubtaskStatus(value: unknown): value is SubtaskStatus {
|
|
51
|
+
return typeof value === 'string' && STATUS_SET.has(value)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function isPlanPhase(value: unknown): value is PlanPhase {
|
|
55
|
+
return typeof value === 'string' && PHASE_SET.has(value)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 一个子任务的规范形态。
|
|
60
|
+
*
|
|
61
|
+
* 允许携带额外字段(stageId/title/department/role/evidence…),迁移与归一化
|
|
62
|
+
* 会原样保留,避免状态层成为 schema 的第二真相源。
|
|
63
|
+
*/
|
|
64
|
+
export interface StatusEntry {
|
|
65
|
+
subtaskId: string
|
|
66
|
+
status: SubtaskStatus
|
|
67
|
+
progress: number
|
|
68
|
+
childId: string | null
|
|
69
|
+
startedAt: number | null
|
|
70
|
+
finishedAt: number | null
|
|
71
|
+
summary: string
|
|
72
|
+
error: string | null
|
|
73
|
+
[extra: string]: unknown
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface TransitionOptions {
|
|
77
|
+
/** 注入“当前时间”,测试与回放必须显式传入以保证确定性。 */
|
|
78
|
+
now?: number
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export class StateMachineError extends Error {
|
|
82
|
+
readonly code: string
|
|
83
|
+
|
|
84
|
+
constructor(message: string, code: string) {
|
|
85
|
+
super(message)
|
|
86
|
+
this.name = 'StateMachineError'
|
|
87
|
+
this.code = code
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export class InvalidEntryError extends StateMachineError {
|
|
92
|
+
constructor(message: string) {
|
|
93
|
+
super(message, 'INVALID_ENTRY')
|
|
94
|
+
this.name = 'InvalidEntryError'
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export class IllegalTransitionError extends StateMachineError {
|
|
99
|
+
readonly subtaskId: string
|
|
100
|
+
readonly from: SubtaskStatus
|
|
101
|
+
readonly action: TransitionType
|
|
102
|
+
|
|
103
|
+
constructor(subtaskId: string, from: SubtaskStatus, action: TransitionType, allowed: readonly SubtaskStatus[]) {
|
|
104
|
+
const allowedText = allowed.length > 0 ? allowed.join(' / ') : '无'
|
|
105
|
+
super(
|
|
106
|
+
`子任务 ${subtaskId} 当前为 ${from},不允许执行 ${action}(允许的来源状态:${allowedText})`,
|
|
107
|
+
'ILLEGAL_TRANSITION',
|
|
108
|
+
)
|
|
109
|
+
this.name = 'IllegalTransitionError'
|
|
110
|
+
this.subtaskId = subtaskId
|
|
111
|
+
this.from = from
|
|
112
|
+
this.action = action
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export class IllegalPhaseTransitionError extends StateMachineError {
|
|
117
|
+
readonly phase: PlanPhase
|
|
118
|
+
readonly event: PlanPhaseEvent
|
|
119
|
+
|
|
120
|
+
constructor(phase: PlanPhase, event: PlanPhaseEvent) {
|
|
121
|
+
super(`计划阶段 ${phase} 不接受事件 ${event}`, 'ILLEGAL_PHASE_TRANSITION')
|
|
122
|
+
this.name = 'IllegalPhaseTransitionError'
|
|
123
|
+
this.phase = phase
|
|
124
|
+
this.event = event
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface InvariantViolation {
|
|
129
|
+
/** 稳定的机器可读代码,例如 `pending.progress`、`stats.blocked`。 */
|
|
130
|
+
code: string
|
|
131
|
+
subtaskId: string | null
|
|
132
|
+
detail: string
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export class InvariantError extends StateMachineError {
|
|
136
|
+
readonly violations: InvariantViolation[]
|
|
137
|
+
|
|
138
|
+
constructor(violations: InvariantViolation[]) {
|
|
139
|
+
const head = violations
|
|
140
|
+
.slice(0, 8)
|
|
141
|
+
.map((item) => `${item.code}${item.subtaskId ? `(${item.subtaskId})` : ''}: ${item.detail}`)
|
|
142
|
+
.join(';')
|
|
143
|
+
super(`状态不变量被破坏(${violations.length} 处):${head}`, 'INVARIANT_VIOLATION')
|
|
144
|
+
this.name = 'InvariantError'
|
|
145
|
+
this.violations = violations
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
150
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function isTimestamp(value: unknown): value is number {
|
|
154
|
+
return typeof value === 'number' && Number.isFinite(value)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function clampProgress(value: unknown, max: number): number {
|
|
158
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return 0
|
|
159
|
+
return Math.min(max, Math.max(0, Math.round(value)))
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function textOrEmpty(value: unknown): string {
|
|
163
|
+
return typeof value === 'string' ? value : ''
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function nonEmptyText(value: unknown): string | null {
|
|
167
|
+
return typeof value === 'string' && value.trim() !== '' ? value : null
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function childIdOrNull(value: unknown): string | null {
|
|
171
|
+
return typeof value === 'string' && value.trim() !== '' ? value : null
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function timestampOrNull(value: unknown): number | null {
|
|
175
|
+
return isTimestamp(value) ? value : null
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 把任意输入归一化为规范形态。
|
|
180
|
+
*
|
|
181
|
+
* 该函数只做“修复”,不做“校验”:它会把历史脏数据收敛到合法组合,
|
|
182
|
+
* 供读取/回放路径使用;写入路径应使用 applyTransition,它保证输入合法。
|
|
183
|
+
*
|
|
184
|
+
* 修复规则(与设计文档 §3.1 一一对应):
|
|
185
|
+
* - pending:清空全部六个伴随字段;
|
|
186
|
+
* - in_progress:进度封顶 99,清 finishedAt/error,缺 startedAt 时补 now;
|
|
187
|
+
* - done:进度固定 100,清 error,缺 finishedAt 时补 now;
|
|
188
|
+
* - blocked:进度封顶 99,缺 finishedAt 时补 now,缺 error 时用 summary 兜底。
|
|
189
|
+
*/
|
|
190
|
+
export function normaliseEntry(entry: unknown, options?: TransitionOptions): StatusEntry {
|
|
191
|
+
if (!isRecord(entry)) throw new InvalidEntryError('状态项必须是对象')
|
|
192
|
+
const subtaskId = typeof entry.subtaskId === 'string' ? entry.subtaskId.trim() : ''
|
|
193
|
+
if (!subtaskId) throw new InvalidEntryError('subtaskId 必须是非空字符串')
|
|
194
|
+
if (!isSubtaskStatus(entry.status)) {
|
|
195
|
+
throw new InvalidEntryError(`子任务 ${subtaskId} 的 status 非法:${String(entry.status)}`)
|
|
196
|
+
}
|
|
197
|
+
const now = options?.now ?? Date.now()
|
|
198
|
+
if (!isTimestamp(now)) throw new StateMachineError('now 必须是有限数字', 'INVALID_TIMESTAMP')
|
|
199
|
+
const status = entry.status
|
|
200
|
+
const canonical: StatusEntry = {
|
|
201
|
+
...entry,
|
|
202
|
+
subtaskId,
|
|
203
|
+
status,
|
|
204
|
+
progress: clampProgress(entry.progress, 100),
|
|
205
|
+
childId: childIdOrNull(entry.childId),
|
|
206
|
+
startedAt: timestampOrNull(entry.startedAt),
|
|
207
|
+
finishedAt: timestampOrNull(entry.finishedAt),
|
|
208
|
+
summary: textOrEmpty(entry.summary),
|
|
209
|
+
error: nonEmptyText(entry.error),
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
switch (status) {
|
|
213
|
+
case 'pending':
|
|
214
|
+
canonical.progress = 0
|
|
215
|
+
canonical.childId = null
|
|
216
|
+
canonical.startedAt = null
|
|
217
|
+
canonical.finishedAt = null
|
|
218
|
+
canonical.summary = ''
|
|
219
|
+
canonical.error = null
|
|
220
|
+
break
|
|
221
|
+
case 'in_progress':
|
|
222
|
+
canonical.progress = Math.min(canonical.progress, 99)
|
|
223
|
+
canonical.finishedAt = null
|
|
224
|
+
canonical.error = null
|
|
225
|
+
canonical.startedAt = canonical.startedAt ?? now
|
|
226
|
+
break
|
|
227
|
+
case 'done':
|
|
228
|
+
canonical.progress = 100
|
|
229
|
+
canonical.error = null
|
|
230
|
+
canonical.finishedAt = canonical.finishedAt ?? now
|
|
231
|
+
break
|
|
232
|
+
case 'blocked':
|
|
233
|
+
canonical.progress = Math.min(canonical.progress, 99)
|
|
234
|
+
canonical.finishedAt = canonical.finishedAt ?? now
|
|
235
|
+
canonical.error = canonical.error ?? nonEmptyText(canonical.summary) ?? BLOCKED_REASON_FALLBACK
|
|
236
|
+
break
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return canonical
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function normaliseStatuses(statuses: readonly unknown[], options?: TransitionOptions): StatusEntry[] {
|
|
243
|
+
if (!Array.isArray(statuses)) {
|
|
244
|
+
throw new StateMachineError('statuses 必须是数组', 'INVALID_STATUSES')
|
|
245
|
+
}
|
|
246
|
+
return statuses.map((entry) => normaliseEntry(entry, options))
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** 迁移动作。每个动作只能从特定状态出发(见 ALLOWED_TRANSITIONS)。 */
|
|
250
|
+
export type TransitionType =
|
|
251
|
+
| 'start'
|
|
252
|
+
| 'bind-child'
|
|
253
|
+
| 'report-progress'
|
|
254
|
+
| 'complete'
|
|
255
|
+
| 'fail'
|
|
256
|
+
| 'reset'
|
|
257
|
+
| 'restart'
|
|
258
|
+
|
|
259
|
+
export const TRANSITION_TYPES = [
|
|
260
|
+
'start',
|
|
261
|
+
'bind-child',
|
|
262
|
+
'report-progress',
|
|
263
|
+
'complete',
|
|
264
|
+
'fail',
|
|
265
|
+
'reset',
|
|
266
|
+
'restart',
|
|
267
|
+
] as const satisfies readonly TransitionType[]
|
|
268
|
+
|
|
269
|
+
export type Transition =
|
|
270
|
+
| { type: 'start'; progress?: number; at?: number }
|
|
271
|
+
| { type: 'bind-child'; childId: string; progress?: number }
|
|
272
|
+
| { type: 'report-progress'; progress: number }
|
|
273
|
+
| { type: 'complete'; summary?: string; at?: number }
|
|
274
|
+
| { type: 'fail'; error: string; summary?: string; at?: number }
|
|
275
|
+
| { type: 'reset' }
|
|
276
|
+
| { type: 'restart'; progress?: number; at?: number }
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* 合法来源状态表(迁移矩阵的唯一实现点)。
|
|
280
|
+
*
|
|
281
|
+
* - `start` :只有 pending 可以启动;blocked/done 必须先 reset/restart。
|
|
282
|
+
* - `bind-child` :只有运行中的任务可以绑定子 Agent。
|
|
283
|
+
* - `report-progress` :只有运行中的任务可以报进度;100% 只能由 complete 写。
|
|
284
|
+
* - `complete` :运行中或重复完成(幂等补写摘要);不直接重开已完成任务。
|
|
285
|
+
* - `fail` :pending(主 Agent 直接判负)/运行中/重复受阻。
|
|
286
|
+
* - `reset` :四个状态都可回到初始态(幂等)。
|
|
287
|
+
* - `restart` :四个状态都可复位后立刻重跑。
|
|
288
|
+
*/
|
|
289
|
+
const ALLOWED_TRANSITIONS: Readonly<Record<TransitionType, readonly SubtaskStatus[]>> = {
|
|
290
|
+
start: ['pending'],
|
|
291
|
+
'bind-child': ['in_progress'],
|
|
292
|
+
'report-progress': ['in_progress'],
|
|
293
|
+
complete: ['in_progress', 'done'],
|
|
294
|
+
fail: ['pending', 'in_progress', 'blocked'],
|
|
295
|
+
reset: ['pending', 'in_progress', 'done', 'blocked'],
|
|
296
|
+
restart: ['pending', 'in_progress', 'done', 'blocked'],
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export function allowedSourceStatuses(type: TransitionType): readonly SubtaskStatus[] {
|
|
300
|
+
return ALLOWED_TRANSITIONS[type]
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function requireProgress(value: unknown, fallback: number): number {
|
|
304
|
+
if (value === undefined) return fallback
|
|
305
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > 99) {
|
|
306
|
+
throw new StateMachineError(
|
|
307
|
+
`progress 必须是 0-99 之间的整数(100 只属于 done),收到 ${String(value)}`,
|
|
308
|
+
'INVALID_PROGRESS',
|
|
309
|
+
)
|
|
310
|
+
}
|
|
311
|
+
return value
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function requireTimestamp(value: unknown, fallback: number): number {
|
|
315
|
+
if (value === undefined) return fallback
|
|
316
|
+
if (!isTimestamp(value)) {
|
|
317
|
+
throw new StateMachineError(`时间戳必须是有限数字,收到 ${String(value)}`, 'INVALID_TIMESTAMP')
|
|
318
|
+
}
|
|
319
|
+
return value
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function requireChildId(value: unknown): string {
|
|
323
|
+
const id = typeof value === 'string' ? value.trim() : ''
|
|
324
|
+
if (!id) throw new StateMachineError('childId 必须是非空字符串', 'INVALID_CHILD_ID')
|
|
325
|
+
return id
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function requireReason(value: unknown): string {
|
|
329
|
+
const reason = nonEmptyText(value)
|
|
330
|
+
if (!reason) throw new StateMachineError('fail 必须给出非空的 error 原因', 'MISSING_REASON')
|
|
331
|
+
return reason
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function startEntry(source: StatusEntry, progress: number, at: number): StatusEntry {
|
|
335
|
+
return {
|
|
336
|
+
...source,
|
|
337
|
+
status: 'in_progress',
|
|
338
|
+
progress,
|
|
339
|
+
childId: null,
|
|
340
|
+
startedAt: at,
|
|
341
|
+
finishedAt: null,
|
|
342
|
+
summary: '',
|
|
343
|
+
error: null,
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function resetEntry(source: StatusEntry): StatusEntry {
|
|
348
|
+
return {
|
|
349
|
+
...source,
|
|
350
|
+
status: 'pending',
|
|
351
|
+
progress: 0,
|
|
352
|
+
childId: null,
|
|
353
|
+
startedAt: null,
|
|
354
|
+
finishedAt: null,
|
|
355
|
+
summary: '',
|
|
356
|
+
error: null,
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function completeEntry(source: StatusEntry, summary: string | undefined, finishedAt: number): StatusEntry {
|
|
361
|
+
if (summary !== undefined && typeof summary !== 'string') {
|
|
362
|
+
throw new StateMachineError('complete 的 summary 必须是字符串', 'INVALID_TEXT')
|
|
363
|
+
}
|
|
364
|
+
return {
|
|
365
|
+
...source,
|
|
366
|
+
status: 'done',
|
|
367
|
+
progress: 100,
|
|
368
|
+
finishedAt,
|
|
369
|
+
error: null,
|
|
370
|
+
summary: summary === undefined ? source.summary : summary,
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function failEntry(source: StatusEntry, error: string, summary: string | undefined, finishedAt: number): StatusEntry {
|
|
375
|
+
if (summary !== undefined && typeof summary !== 'string') {
|
|
376
|
+
throw new StateMachineError('fail 的 summary 必须是字符串', 'INVALID_TEXT')
|
|
377
|
+
}
|
|
378
|
+
return {
|
|
379
|
+
...source,
|
|
380
|
+
status: 'blocked',
|
|
381
|
+
progress: Math.min(source.progress, 99),
|
|
382
|
+
finishedAt,
|
|
383
|
+
error: requireReason(error),
|
|
384
|
+
summary: summary === undefined ? source.summary : summary,
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* 执行一次状态迁移。输入必须是合法状态项(不合法会抛 InvalidEntryError),
|
|
390
|
+
* 迁移本身非法会抛 IllegalTransitionError——两者都必须被调用方当作契约错误,
|
|
391
|
+
* 而不是静默吞掉。
|
|
392
|
+
*/
|
|
393
|
+
export function applyTransition(entry: unknown, transition: Transition, options?: TransitionOptions): StatusEntry {
|
|
394
|
+
if (!isRecord(transition) || !isTransitionType(transition.type)) {
|
|
395
|
+
throw new StateMachineError(`未知的迁移动作:${String((transition as { type?: unknown })?.type)}`, 'INVALID_TRANSITION')
|
|
396
|
+
}
|
|
397
|
+
const now = options?.now ?? Date.now()
|
|
398
|
+
const source = normaliseEntry(entry, { now })
|
|
399
|
+
const allowed = ALLOWED_TRANSITIONS[transition.type]
|
|
400
|
+
if (!allowed.includes(source.status)) {
|
|
401
|
+
throw new IllegalTransitionError(source.subtaskId, source.status, transition.type, allowed)
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
let next: StatusEntry
|
|
405
|
+
switch (transition.type) {
|
|
406
|
+
case 'start':
|
|
407
|
+
next = startEntry(source, requireProgress(transition.progress, START_PROGRESS), requireTimestamp(transition.at, now))
|
|
408
|
+
break
|
|
409
|
+
case 'bind-child':
|
|
410
|
+
next = {
|
|
411
|
+
...source,
|
|
412
|
+
childId: requireChildId(transition.childId),
|
|
413
|
+
progress: Math.max(source.progress, requireProgress(transition.progress, ATTACH_PROGRESS)),
|
|
414
|
+
}
|
|
415
|
+
break
|
|
416
|
+
case 'report-progress':
|
|
417
|
+
next = { ...source, progress: requireProgress(transition.progress, source.progress) }
|
|
418
|
+
break
|
|
419
|
+
case 'complete':
|
|
420
|
+
next = completeEntry(source, transition.summary, requireTimestamp(transition.at, source.finishedAt ?? now))
|
|
421
|
+
break
|
|
422
|
+
case 'fail':
|
|
423
|
+
next = failEntry(source, transition.error, transition.summary, requireTimestamp(transition.at, source.finishedAt ?? now))
|
|
424
|
+
break
|
|
425
|
+
case 'reset':
|
|
426
|
+
next = resetEntry(source)
|
|
427
|
+
break
|
|
428
|
+
case 'restart': {
|
|
429
|
+
const at = requireTimestamp(transition.at, now)
|
|
430
|
+
next = startEntry(resetEntry(source), requireProgress(transition.progress, START_PROGRESS), at)
|
|
431
|
+
break
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
return normaliseEntry(next, { now })
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function isTransitionType(value: unknown): value is TransitionType {
|
|
439
|
+
return typeof value === 'string' && (TRANSITION_TYPES as readonly string[]).includes(value)
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* 计划级操作:一次性、原子地把一组任务带入某个语义状态。
|
|
444
|
+
*
|
|
445
|
+
* 与单个任务迁移的区别:这些操作表达“整轮结束/续跑/取消”的产品语义,
|
|
446
|
+
* 必须统一入口,禁止在 runtime 里手写 map 改状态(T2 缺陷 D3 的根因)。
|
|
447
|
+
*
|
|
448
|
+
* - `pause-round`:预算切片结束。只把 in_progress 归零为 pending;
|
|
449
|
+
* blocked/done/pending 原样保留(1.4.x 会把 blocked 也洗成 pending,
|
|
450
|
+
* 丢失“受阻”这一事实,属于语义回归)。
|
|
451
|
+
* - `resume`:续跑前复位。blocked/in_progress → pending;done/pending 保留。
|
|
452
|
+
* - `cancel`:取消。只把正在运行的任务归零,未开始/已完成原样保留;
|
|
453
|
+
* 取消是计划级结论,不把任务伪造成 blocked。
|
|
454
|
+
* - `normalise`:只归一化,不改语义(读取旧数据时使用)。
|
|
455
|
+
*/
|
|
456
|
+
export type PlanOperation = 'pause-round' | 'resume' | 'cancel' | 'normalise'
|
|
457
|
+
|
|
458
|
+
export const PLAN_OPERATIONS = ['pause-round', 'resume', 'cancel', 'normalise'] as const satisfies readonly PlanOperation[]
|
|
459
|
+
|
|
460
|
+
export function applyPlanOperation(
|
|
461
|
+
statuses: readonly unknown[],
|
|
462
|
+
operation: PlanOperation,
|
|
463
|
+
options?: TransitionOptions,
|
|
464
|
+
): StatusEntry[] {
|
|
465
|
+
if (!Array.isArray(statuses)) {
|
|
466
|
+
throw new StateMachineError('statuses 必须是数组', 'INVALID_STATUSES')
|
|
467
|
+
}
|
|
468
|
+
const now = options?.now ?? Date.now()
|
|
469
|
+
return statuses.map((entry) => {
|
|
470
|
+
const current = normaliseEntry(entry, { now })
|
|
471
|
+
switch (operation) {
|
|
472
|
+
case 'pause-round':
|
|
473
|
+
case 'cancel':
|
|
474
|
+
return current.status === 'in_progress' ? resetEntry(current) : current
|
|
475
|
+
case 'resume':
|
|
476
|
+
return current.status === 'blocked' || current.status === 'in_progress' ? resetEntry(current) : current
|
|
477
|
+
case 'normalise':
|
|
478
|
+
return current
|
|
479
|
+
default:
|
|
480
|
+
throw new StateMachineError(`未知的计划级操作:${String(operation)}`, 'INVALID_PLAN_OPERATION')
|
|
481
|
+
}
|
|
482
|
+
})
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/* ------------------------------------------------------------------ *
|
|
486
|
+
* 不变量:可被测试与 CI 直接断言,不依赖人工判断
|
|
487
|
+
* ------------------------------------------------------------------ */
|
|
488
|
+
|
|
489
|
+
function violation(code: string, subtaskId: string | null, detail: string): InvariantViolation {
|
|
490
|
+
return { code, subtaskId, detail }
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* 检查单个状态项的字段组合。
|
|
495
|
+
*
|
|
496
|
+
* 这里故意不归一化:不变量必须能发现“写入方写错了”,而不是替写入方掩盖。
|
|
497
|
+
*/
|
|
498
|
+
export function findEntryViolations(entry: unknown): InvariantViolation[] {
|
|
499
|
+
if (!isRecord(entry)) return [violation('entry.type', null, '状态项必须是对象')]
|
|
500
|
+
|
|
501
|
+
const violations: InvariantViolation[] = []
|
|
502
|
+
const subtaskId = typeof entry.subtaskId === 'string' && entry.subtaskId.trim() !== '' ? entry.subtaskId : null
|
|
503
|
+
const add = (code: string, detail: string): void => {
|
|
504
|
+
violations.push(violation(code, subtaskId, detail))
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
if (!subtaskId) add('subtask.id', `subtaskId 必须是非空字符串(收到 ${JSON.stringify(entry.subtaskId)})`)
|
|
508
|
+
if (!isSubtaskStatus(entry.status)) {
|
|
509
|
+
add('status.invalid', `status 必须是 ${SUBTASK_STATUSES.join(' / ')} 之一(收到 ${JSON.stringify(entry.status)})`)
|
|
510
|
+
return violations
|
|
511
|
+
}
|
|
512
|
+
const status = entry.status
|
|
513
|
+
|
|
514
|
+
const progress = entry.progress
|
|
515
|
+
if (typeof progress !== 'number' || !Number.isInteger(progress) || progress < 0 || progress > 100) {
|
|
516
|
+
add('progress.invalid', `progress 必须是 0-100 的整数(收到 ${JSON.stringify(progress)})`)
|
|
517
|
+
}
|
|
518
|
+
const progressIsInt = typeof progress === 'number' && Number.isInteger(progress)
|
|
519
|
+
|
|
520
|
+
const childId = entry.childId
|
|
521
|
+
if (!(childId === null || (typeof childId === 'string' && childId !== ''))) {
|
|
522
|
+
add('childId.invalid', `childId 必须是 null 或非空字符串(收到 ${JSON.stringify(childId)})`)
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const startedAt = entry.startedAt
|
|
526
|
+
if (!(startedAt === null || isTimestamp(startedAt))) {
|
|
527
|
+
add('startedAt.invalid', `startedAt 必须是 null 或有限数字(收到 ${JSON.stringify(startedAt)})`)
|
|
528
|
+
}
|
|
529
|
+
const finishedAt = entry.finishedAt
|
|
530
|
+
if (!(finishedAt === null || isTimestamp(finishedAt))) {
|
|
531
|
+
add('finishedAt.invalid', `finishedAt 必须是 null 或有限数字(收到 ${JSON.stringify(finishedAt)})`)
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const summary = entry.summary
|
|
535
|
+
if (typeof summary !== 'string') {
|
|
536
|
+
add('summary.invalid', `summary 必须是字符串(收到 ${JSON.stringify(summary)})`)
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const error = entry.error
|
|
540
|
+
if (!(error === null || typeof error === 'string')) {
|
|
541
|
+
add('error.invalid', `error 必须是 null 或字符串(收到 ${JSON.stringify(error)})`)
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
switch (status) {
|
|
545
|
+
case 'pending':
|
|
546
|
+
if (progressIsInt && progress !== 0) add('pending.progress', `pending 的 progress 必须为 0(收到 ${progress})`)
|
|
547
|
+
if (childId !== null) add('pending.childId', 'pending 不得携带 childId')
|
|
548
|
+
if (startedAt !== null) add('pending.startedAt', 'pending 不得携带 startedAt')
|
|
549
|
+
if (finishedAt !== null) add('pending.finishedAt', 'pending 不得携带 finishedAt')
|
|
550
|
+
if (summary !== '') add('pending.summary', 'pending 的 summary 必须为空')
|
|
551
|
+
if (error !== null) add('pending.error', 'pending 不得携带 error(本轮原因属于计划级,不属于任务)')
|
|
552
|
+
break
|
|
553
|
+
case 'in_progress':
|
|
554
|
+
if (progressIsInt && progress > 99) add('in_progress.progress', `in_progress 的 progress 不得超过 99(收到 ${progress})`)
|
|
555
|
+
if (finishedAt !== null) add('in_progress.finishedAt', 'in_progress 不得携带 finishedAt')
|
|
556
|
+
if (error !== null) add('in_progress.error', 'in_progress 不得携带 error')
|
|
557
|
+
if (!isTimestamp(startedAt)) add('in_progress.startedAt', 'in_progress 必须携带 startedAt')
|
|
558
|
+
break
|
|
559
|
+
case 'done':
|
|
560
|
+
if (progressIsInt && progress !== 100) add('done.progress', `done 的 progress 必须为 100(收到 ${progress})`)
|
|
561
|
+
if (!isTimestamp(finishedAt)) add('done.finishedAt', 'done 必须携带 finishedAt')
|
|
562
|
+
if (error !== null) add('done.error', 'done 不得携带 error')
|
|
563
|
+
break
|
|
564
|
+
case 'blocked':
|
|
565
|
+
if (progressIsInt && progress > 99) add('blocked.progress', `blocked 的 progress 不得超过 99(收到 ${progress})`)
|
|
566
|
+
if (!isTimestamp(finishedAt)) add('blocked.finishedAt', 'blocked 必须携带 finishedAt')
|
|
567
|
+
if (typeof error !== 'string' || error.trim() === '') add('blocked.error', 'blocked 必须携带非空 error 原因')
|
|
568
|
+
break
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
return violations
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** 检查整组状态项:逐项规则 + subtaskId 唯一。 */
|
|
575
|
+
export function findStatusViolations(statuses: unknown): InvariantViolation[] {
|
|
576
|
+
if (!Array.isArray(statuses)) return [violation('statuses.type', null, 'statuses 必须是数组')]
|
|
577
|
+
const violations: InvariantViolation[] = []
|
|
578
|
+
const seen = new Set<string>()
|
|
579
|
+
for (const entry of statuses) {
|
|
580
|
+
violations.push(...findEntryViolations(entry))
|
|
581
|
+
if (isRecord(entry) && typeof entry.subtaskId === 'string' && entry.subtaskId.trim() !== '') {
|
|
582
|
+
if (seen.has(entry.subtaskId)) {
|
|
583
|
+
violations.push(violation('subtask.duplicate', entry.subtaskId, `subtaskId 重复:${entry.subtaskId}`))
|
|
584
|
+
} else {
|
|
585
|
+
seen.add(entry.subtaskId)
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
return violations
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
interface Counts {
|
|
593
|
+
total: number
|
|
594
|
+
done: number
|
|
595
|
+
blocked: number
|
|
596
|
+
inProgress: number
|
|
597
|
+
pending: number
|
|
598
|
+
progress: number
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* 计数的独立实现(不调用 computeStats)。
|
|
603
|
+
*
|
|
604
|
+
* 它是不变量的“第二实现”,用来证明 runtime 下发的 stats 确实等于
|
|
605
|
+
* 同一份 statuses 的派生结果;两份实现算法必须一致,否则测试会失败。
|
|
606
|
+
*/
|
|
607
|
+
function countStatuses(statuses: readonly unknown[]): Counts {
|
|
608
|
+
let done = 0
|
|
609
|
+
let blocked = 0
|
|
610
|
+
let inProgress = 0
|
|
611
|
+
let pending = 0
|
|
612
|
+
let sum = 0
|
|
613
|
+
for (const entry of statuses) {
|
|
614
|
+
if (!isRecord(entry)) continue
|
|
615
|
+
if (entry.status === 'done') done += 1
|
|
616
|
+
else if (entry.status === 'blocked') blocked += 1
|
|
617
|
+
else if (entry.status === 'in_progress') inProgress += 1
|
|
618
|
+
else if (entry.status === 'pending') pending += 1
|
|
619
|
+
const value = typeof entry.progress === 'number' && Number.isFinite(entry.progress) ? entry.progress : 0
|
|
620
|
+
sum += value
|
|
621
|
+
}
|
|
622
|
+
const total = statuses.length
|
|
623
|
+
return {
|
|
624
|
+
total,
|
|
625
|
+
done,
|
|
626
|
+
blocked,
|
|
627
|
+
inProgress,
|
|
628
|
+
pending,
|
|
629
|
+
progress: total === 0 ? 0 : Math.round(sum / total),
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** 校验 stats 是否完全由同一份 statuses 派生(D1/D2/D4 的机器门禁)。 */
|
|
634
|
+
export function findStatsViolations(statuses: unknown, stats: unknown): InvariantViolation[] {
|
|
635
|
+
const list = Array.isArray(statuses) ? statuses : []
|
|
636
|
+
const expected = countStatuses(list)
|
|
637
|
+
if (!isRecord(stats)) return [violation('stats.type', null, 'stats 必须是对象')]
|
|
638
|
+
|
|
639
|
+
const violations: InvariantViolation[] = []
|
|
640
|
+
const fields = ['total', 'done', 'blocked', 'inProgress', 'pending', 'progress'] as const
|
|
641
|
+
for (const field of fields) {
|
|
642
|
+
const actual = stats[field]
|
|
643
|
+
if (actual !== expected[field]) {
|
|
644
|
+
violations.push(
|
|
645
|
+
violation(
|
|
646
|
+
`stats.${field}`,
|
|
647
|
+
null,
|
|
648
|
+
`stats.${field} = ${JSON.stringify(actual)},但 statuses 派生值为 ${expected[field]}`,
|
|
649
|
+
),
|
|
650
|
+
)
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
return violations
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
interface DepartmentAggregate {
|
|
657
|
+
total: number
|
|
658
|
+
done: number
|
|
659
|
+
blocked: number
|
|
660
|
+
inProgress: number
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* 校验 departments 是否与同一份 statuses 一致。
|
|
665
|
+
*
|
|
666
|
+
* 语义与 serialisePlan 一致:pending 不计入任何部门计数,但计入 total。
|
|
667
|
+
*/
|
|
668
|
+
export function findDepartmentViolations(statuses: unknown, departments: unknown): InvariantViolation[] {
|
|
669
|
+
if (!Array.isArray(statuses)) return [violation('statuses.type', null, 'statuses 必须是数组')]
|
|
670
|
+
if (!Array.isArray(departments)) return [violation('departments.type', null, 'departments 必须是数组')]
|
|
671
|
+
|
|
672
|
+
const expected = new Map<string, DepartmentAggregate>()
|
|
673
|
+
for (const entry of statuses) {
|
|
674
|
+
if (!isRecord(entry)) continue
|
|
675
|
+
const key = typeof entry.department === 'string' && entry.department !== '' ? entry.department : ''
|
|
676
|
+
const aggregate = expected.get(key) ?? { total: 0, done: 0, blocked: 0, inProgress: 0 }
|
|
677
|
+
aggregate.total += 1
|
|
678
|
+
if (entry.status === 'done') aggregate.done += 1
|
|
679
|
+
else if (entry.status === 'blocked') aggregate.blocked += 1
|
|
680
|
+
else if (entry.status === 'in_progress') aggregate.inProgress += 1
|
|
681
|
+
expected.set(key, aggregate)
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const violations: InvariantViolation[] = []
|
|
685
|
+
const seen = new Set<string>()
|
|
686
|
+
for (const item of departments) {
|
|
687
|
+
if (!isRecord(item)) {
|
|
688
|
+
violations.push(violation('departments.item', null, '部门条目必须是对象'))
|
|
689
|
+
continue
|
|
690
|
+
}
|
|
691
|
+
const id = typeof item.id === 'string' ? item.id : ''
|
|
692
|
+
seen.add(id)
|
|
693
|
+
const want = expected.get(id)
|
|
694
|
+
if (!want) {
|
|
695
|
+
violations.push(violation('departments.extra', null, `部门 ${JSON.stringify(item.id)} 在 statuses 中不存在`))
|
|
696
|
+
continue
|
|
697
|
+
}
|
|
698
|
+
for (const field of ['total', 'done', 'blocked', 'inProgress'] as const) {
|
|
699
|
+
if (item[field] !== want[field]) {
|
|
700
|
+
violations.push(
|
|
701
|
+
violation(
|
|
702
|
+
`departments.${field}`,
|
|
703
|
+
null,
|
|
704
|
+
`部门 ${id} 的 ${field} = ${JSON.stringify(item[field])},但 statuses 派生值为 ${want[field]}`,
|
|
705
|
+
),
|
|
706
|
+
)
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
for (const id of expected.keys()) {
|
|
711
|
+
if (!seen.has(id)) {
|
|
712
|
+
violations.push(violation('departments.missing', null, `statuses 中的部门 ${JSON.stringify(id)} 未出现在 departments 中`))
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
return violations
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* 校验计划阶段与任务集合是否相容:
|
|
720
|
+
* - done / integrating:不允许有未完成任务;
|
|
721
|
+
* - paused / blocked / cancelled:不允许仍有任务在运行(这些阶段是“已落定”的);
|
|
722
|
+
* - pending:不允许已有任何任务离开初始态。
|
|
723
|
+
*/
|
|
724
|
+
export function findPhaseViolations(phase: unknown, statuses: unknown): InvariantViolation[] {
|
|
725
|
+
if (!isPlanPhase(phase)) return [violation('phase.invalid', null, `未知的计划阶段:${JSON.stringify(phase)}`)]
|
|
726
|
+
const list = Array.isArray(statuses) ? statuses : []
|
|
727
|
+
const counts = countStatuses(list)
|
|
728
|
+
const violations: InvariantViolation[] = []
|
|
729
|
+
|
|
730
|
+
if (phase === 'done' || phase === 'integrating') {
|
|
731
|
+
if (counts.total === 0) violations.push(violation('phase.done.empty', null, `${phase} 阶段不应是空计划`))
|
|
732
|
+
if (counts.done !== counts.total) {
|
|
733
|
+
violations.push(
|
|
734
|
+
violation('phase.done', null, `${phase} 阶段仍有 ${counts.total - counts.done} 个任务未完成`),
|
|
735
|
+
)
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (phase === 'paused' || phase === 'blocked' || phase === 'cancelled') {
|
|
739
|
+
if (counts.inProgress !== 0) {
|
|
740
|
+
violations.push(violation('phase.terminal.inProgress', null, `${phase} 阶段仍有 ${counts.inProgress} 个任务在运行`))
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
if (phase === 'pending' && counts.done + counts.inProgress + counts.blocked !== 0) {
|
|
744
|
+
violations.push(violation('phase.pending', null, 'pending 阶段不允许存在已启动/已完成/受阻的任务'))
|
|
745
|
+
}
|
|
746
|
+
return violations
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
export interface InvariantInput {
|
|
750
|
+
statuses: unknown
|
|
751
|
+
stats?: unknown
|
|
752
|
+
departments?: unknown
|
|
753
|
+
phase?: unknown
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** 汇总所有启用的不变量检查;空数组表示全部通过。 */
|
|
757
|
+
export function collectViolations(input: InvariantInput): InvariantViolation[] {
|
|
758
|
+
const violations = findStatusViolations(input.statuses)
|
|
759
|
+
if (input.stats !== undefined) violations.push(...findStatsViolations(input.statuses, input.stats))
|
|
760
|
+
if (input.departments !== undefined) violations.push(...findDepartmentViolations(input.statuses, input.departments))
|
|
761
|
+
if (input.phase !== undefined) violations.push(...findPhaseViolations(input.phase, input.statuses))
|
|
762
|
+
return violations
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/** 断言所有启用的不变量;失败抛出 InvariantError,附带完整违规清单。 */
|
|
766
|
+
export function assertInvariants(input: InvariantInput): void {
|
|
767
|
+
const violations = collectViolations(input)
|
|
768
|
+
if (violations.length > 0) throw new InvariantError(violations)
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/* ------------------------------------------------------------------ *
|
|
772
|
+
* 计划阶段(phase)状态机
|
|
773
|
+
* ------------------------------------------------------------------ */
|
|
774
|
+
|
|
775
|
+
/** 计划阶段事件。命名与 runtime 的进入路径一一对应。 */
|
|
776
|
+
export type PlanPhaseEvent =
|
|
777
|
+
| 'defer' // plan 模式下延迟派发:pending → planning
|
|
778
|
+
| 'dispatch' // 开始一轮执行:pending/planning/paused/blocked → executing
|
|
779
|
+
| 'round-paused' // 预算切片结束:executing → paused
|
|
780
|
+
| 'round-blocked' // 本轮有任务受阻且已落定:executing → blocked
|
|
781
|
+
| 'round-completed' // 本轮全部完成但结果未写入:executing → integrating
|
|
782
|
+
| 'manual-completed-all' // 主 Agent 手动把最后一项做完:executing/blocked → integrating
|
|
783
|
+
| 'result-written' // 结果消息已写入:integrating → done
|
|
784
|
+
| 'cancel' // 任意可取消阶段 → cancelled
|
|
785
|
+
| 'degrade' // 计划不可生成:pending/planning → degraded
|
|
786
|
+
|
|
787
|
+
export const PLAN_PHASE_EVENTS = [
|
|
788
|
+
'defer',
|
|
789
|
+
'dispatch',
|
|
790
|
+
'round-paused',
|
|
791
|
+
'round-blocked',
|
|
792
|
+
'round-completed',
|
|
793
|
+
'manual-completed-all',
|
|
794
|
+
'result-written',
|
|
795
|
+
'cancel',
|
|
796
|
+
'degrade',
|
|
797
|
+
] as const satisfies readonly PlanPhaseEvent[]
|
|
798
|
+
|
|
799
|
+
const PHASE_TRANSITIONS: Readonly<Record<PlanPhase, Readonly<Partial<Record<PlanPhaseEvent, PlanPhase>>>>> = {
|
|
800
|
+
pending: { defer: 'planning', dispatch: 'executing', cancel: 'cancelled', degrade: 'degraded' },
|
|
801
|
+
planning: { dispatch: 'executing', cancel: 'cancelled', degrade: 'degraded' },
|
|
802
|
+
executing: {
|
|
803
|
+
'round-paused': 'paused',
|
|
804
|
+
'round-blocked': 'blocked',
|
|
805
|
+
'round-completed': 'integrating',
|
|
806
|
+
'manual-completed-all': 'integrating',
|
|
807
|
+
cancel: 'cancelled',
|
|
808
|
+
},
|
|
809
|
+
paused: { dispatch: 'executing', cancel: 'cancelled' },
|
|
810
|
+
blocked: { dispatch: 'executing', 'manual-completed-all': 'integrating', cancel: 'cancelled' },
|
|
811
|
+
integrating: { 'result-written': 'done', cancel: 'cancelled' },
|
|
812
|
+
degraded: {},
|
|
813
|
+
cancelled: {},
|
|
814
|
+
done: {},
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
const EVENT_SET: ReadonlySet<string> = new Set<string>(PLAN_PHASE_EVENTS)
|
|
818
|
+
|
|
819
|
+
export function isPlanPhaseEvent(value: unknown): value is PlanPhaseEvent {
|
|
820
|
+
return typeof value === 'string' && EVENT_SET.has(value)
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
export function allowedPhaseEvents(phase: PlanPhase): PlanPhaseEvent[] {
|
|
824
|
+
return Object.keys(PHASE_TRANSITIONS[phase]) as PlanPhaseEvent[]
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/**
|
|
828
|
+
* 执行一次阶段迁移;非法输入或非法迁移都抛错,禁止用 `?? fallback` 吞掉。
|
|
829
|
+
*/
|
|
830
|
+
export function applyPhaseEvent(phase: unknown, event: unknown): PlanPhase {
|
|
831
|
+
if (!isPlanPhase(phase)) throw new StateMachineError(`未知的计划阶段:${String(phase)}`, 'INVALID_PHASE')
|
|
832
|
+
if (!isPlanPhaseEvent(event)) throw new StateMachineError(`未知的阶段事件:${String(event)}`, 'INVALID_PHASE_EVENT')
|
|
833
|
+
const next = PHASE_TRANSITIONS[phase][event]
|
|
834
|
+
if (!next) throw new IllegalPhaseTransitionError(phase, event)
|
|
835
|
+
return next
|
|
836
|
+
}
|