mocode-ai 1.9.6 → 1.9.8
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/dist/agent/index.js +27 -0
- package/dist/agent/model-turn.js +6 -6
- package/dist/agent/request-governor.js +1 -1
- package/dist/context/vision-window.js +24 -9
- package/dist/host/protocol.js +4 -1
- package/dist/host/stdio.js +45 -1
- package/dist/index.js +7 -0
- package/dist/jobs/dir-snapshot.js +332 -0
- package/dist/jobs/worktree.js +78 -20
- package/dist/orchestrator/board.js +332 -0
- package/dist/orchestrator/cli.js +628 -0
- package/dist/orchestrator/index.js +4 -0
- package/dist/orchestrator/integrate.js +344 -0
- package/dist/orchestrator/lane-channel.js +146 -0
- package/dist/orchestrator/lane-executor.js +439 -0
- package/dist/orchestrator/lane-repl.js +154 -0
- package/dist/orchestrator/lane-site.js +255 -0
- package/dist/orchestrator/lanes.js +72 -0
- package/dist/orchestrator/lease.js +132 -0
- package/dist/orchestrator/live-log.js +193 -0
- package/dist/orchestrator/repl.js +435 -0
- package/dist/orchestrator/review.js +135 -0
- package/dist/orchestrator/scheduler.js +673 -0
- package/dist/orchestrator/scope.js +88 -0
- package/dist/orchestrator/state.js +533 -0
- package/dist/orchestrator/store.js +221 -0
- package/dist/orchestrator/supervisor-prompt.js +54 -0
- package/dist/orchestrator/supervisor.js +798 -0
- package/dist/orchestrator/tail.js +508 -0
- package/dist/orchestrator/task-prompt.js +93 -0
- package/dist/orchestrator/terminal.js +269 -0
- package/dist/orchestrator/tools.js +392 -0
- package/dist/orchestrator/types.js +1 -0
- package/dist/orchestrator/watch-panel.js +154 -0
- package/dist/orchestrator/worker.js +475 -0
- package/dist/orchestrator/workspaces.js +191 -0
- package/dist/repl/commands/memory.js +1 -1
- package/dist/repl/runtime.js +16 -2
- package/dist/session/store.js +1 -1
- package/dist/tools/builtins/ask-human.js +27 -6
- package/dist/ui/handoff-block.js +91 -0
- package/dist/ui/layout-internal/statusbar.js +2 -1
- package/dist/ui/prompt-internal/editor.js +49 -0
- package/package.json +2 -2
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
function normalizePattern(pattern) {
|
|
3
|
+
const normalized = pattern.trim().replaceAll('\\', '/').replace(/^\.\//, '');
|
|
4
|
+
return normalized.endsWith('/') ? `${normalized}**` : normalized;
|
|
5
|
+
}
|
|
6
|
+
function globRegex(pattern) {
|
|
7
|
+
const source = normalizePattern(pattern);
|
|
8
|
+
let regex = '^';
|
|
9
|
+
for (let index = 0; index < source.length; index++) {
|
|
10
|
+
const char = source[index];
|
|
11
|
+
if (char === '*') {
|
|
12
|
+
if (source[index + 1] === '*') {
|
|
13
|
+
index += 1;
|
|
14
|
+
if (source[index + 1] === '/') {
|
|
15
|
+
index += 1;
|
|
16
|
+
regex += '(?:.*/)?';
|
|
17
|
+
}
|
|
18
|
+
else
|
|
19
|
+
regex += '.*';
|
|
20
|
+
}
|
|
21
|
+
else
|
|
22
|
+
regex += '[^/]*';
|
|
23
|
+
}
|
|
24
|
+
else if (char === '?')
|
|
25
|
+
regex += '[^/]';
|
|
26
|
+
else
|
|
27
|
+
regex += char.replace(/[|\\{}()[\]^$+?.-]/g, '\\$&');
|
|
28
|
+
}
|
|
29
|
+
return new RegExp(`${regex}$`);
|
|
30
|
+
}
|
|
31
|
+
function normalizeChangedPath(file) {
|
|
32
|
+
const normalized = path.posix.normalize(file.replaceAll('\\', '/').replace(/^\.\//, ''));
|
|
33
|
+
if (!normalized ||
|
|
34
|
+
normalized === '.' ||
|
|
35
|
+
normalized === '..' ||
|
|
36
|
+
normalized.startsWith('../') ||
|
|
37
|
+
normalized.startsWith('/') ||
|
|
38
|
+
/^[A-Za-z]:\//.test(normalized)) {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
return normalized;
|
|
42
|
+
}
|
|
43
|
+
/** 通配符之前的静态前缀;`src/a/**` → `src/a`,`**\/*` → ``。 */
|
|
44
|
+
function staticPrefix(pattern) {
|
|
45
|
+
const normalized = normalizePattern(pattern);
|
|
46
|
+
const wildcard = normalized.search(/[*?]/);
|
|
47
|
+
const head = wildcard < 0 ? normalized : normalized.slice(0, wildcard);
|
|
48
|
+
return head.replace(/\/+$/, '');
|
|
49
|
+
}
|
|
50
|
+
function prefixOverlaps(a, b) {
|
|
51
|
+
if (a === b || a === '' || b === '')
|
|
52
|
+
return true;
|
|
53
|
+
return a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* 两个写任务的改动范围是否可能相交。用于并发调度:相交就串行,避免同一批文件被两路同时改。
|
|
57
|
+
*
|
|
58
|
+
* 这是**保守近似**:只看 allow 模式的静态前缀,宁可误判相交(多串行一个任务),
|
|
59
|
+
* 也不要在并发写里丢改动。
|
|
60
|
+
*/
|
|
61
|
+
export function scopeOverlaps(a, b) {
|
|
62
|
+
for (const left of a.scope.allow) {
|
|
63
|
+
for (const right of b.scope.allow) {
|
|
64
|
+
if (prefixOverlaps(staticPrefix(left), staticPrefix(right)))
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
export function validateChangedFiles(contract, changedFiles) {
|
|
71
|
+
const allow = contract.scope.allow.map(globRegex);
|
|
72
|
+
const deny = contract.scope.deny.map(globRegex);
|
|
73
|
+
const errors = [];
|
|
74
|
+
for (const raw of changedFiles) {
|
|
75
|
+
const file = normalizeChangedPath(raw);
|
|
76
|
+
if (!file) {
|
|
77
|
+
errors.push(`Invalid changed-file path: ${raw}`);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (deny.some((pattern) => pattern.test(file))) {
|
|
81
|
+
errors.push(`Changed file is denied by task scope: ${file}`);
|
|
82
|
+
}
|
|
83
|
+
else if (!allow.some((pattern) => pattern.test(file))) {
|
|
84
|
+
errors.push(`Changed file is outside the allowed task scope: ${file}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return errors;
|
|
88
|
+
}
|
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { ORCHESTRATION_SCHEMA_VERSION, } from './types.js';
|
|
3
|
+
/** 并发与收工判定的默认策略;`policy` 缺省或局部给出时用它补齐。 */
|
|
4
|
+
export const DEFAULT_RUN_POLICY = {
|
|
5
|
+
maxConcurrentWorkers: 6,
|
|
6
|
+
maxConcurrentPerWorkspace: 6,
|
|
7
|
+
reviewOnIdle: true,
|
|
8
|
+
};
|
|
9
|
+
function normalizePolicy(input) {
|
|
10
|
+
const policy = { ...DEFAULT_RUN_POLICY };
|
|
11
|
+
if (!input)
|
|
12
|
+
return policy;
|
|
13
|
+
for (const key of ['maxConcurrentWorkers', 'maxConcurrentPerWorkspace']) {
|
|
14
|
+
const value = input[key];
|
|
15
|
+
if (value === undefined)
|
|
16
|
+
continue;
|
|
17
|
+
if (!Number.isInteger(value) || value < 1)
|
|
18
|
+
throw new Error(`policy.${key} must be a positive integer.`);
|
|
19
|
+
policy[key] = value;
|
|
20
|
+
}
|
|
21
|
+
if (input.reviewOnIdle !== undefined)
|
|
22
|
+
policy.reviewOnIdle = input.reviewOnIdle === true;
|
|
23
|
+
if (input.budget) {
|
|
24
|
+
const budget = {};
|
|
25
|
+
for (const key of ['maxTokensPerRun', 'maxWallClockMs']) {
|
|
26
|
+
const value = input.budget[key];
|
|
27
|
+
if (value === undefined)
|
|
28
|
+
continue;
|
|
29
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
|
|
30
|
+
throw new Error(`policy.budget.${key} must be a positive number.`);
|
|
31
|
+
}
|
|
32
|
+
budget[key] = Math.floor(value);
|
|
33
|
+
}
|
|
34
|
+
// 空 budget 与「不限」等价,不写进账本,避免看起来像已配置。
|
|
35
|
+
if (Object.keys(budget).length > 0)
|
|
36
|
+
policy.budget = budget;
|
|
37
|
+
}
|
|
38
|
+
return policy;
|
|
39
|
+
}
|
|
40
|
+
const TERMINAL_TASKS = new Set(['completed', 'failed', 'cancelled']);
|
|
41
|
+
const ACTIVE_TASKS = new Set(['dispatching', 'running']);
|
|
42
|
+
const TERMINAL_RUNS = new Set(['completed', 'failed', 'cancelled']);
|
|
43
|
+
const LANE_MODES = new Set(['worktree', 'copy', 'inplace']);
|
|
44
|
+
const TASK_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
|
|
45
|
+
function assertText(value, label) {
|
|
46
|
+
if (typeof value !== 'string' || !value.trim())
|
|
47
|
+
throw new Error(`${label} must be a non-empty string.`);
|
|
48
|
+
}
|
|
49
|
+
function stringArray(value, fallback, label) {
|
|
50
|
+
if (value === undefined)
|
|
51
|
+
return [...fallback];
|
|
52
|
+
if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || !item.trim())) {
|
|
53
|
+
throw new Error(`${label} must be an array of non-empty strings.`);
|
|
54
|
+
}
|
|
55
|
+
return [...new Set(value.map((item) => item.trim()))];
|
|
56
|
+
}
|
|
57
|
+
function normalizeTask(input) {
|
|
58
|
+
if (!input || typeof input !== 'object')
|
|
59
|
+
throw new Error('Each task must be an object.');
|
|
60
|
+
assertText(input.id, 'task.id');
|
|
61
|
+
if (!TASK_ID_RE.test(input.id)) {
|
|
62
|
+
throw new Error(`task.id must match ${TASK_ID_RE.source}: ${input.id}`);
|
|
63
|
+
}
|
|
64
|
+
assertText(input.title, `task ${input.id} title`);
|
|
65
|
+
if (input.lane !== undefined && (typeof input.lane !== 'string' || !TASK_ID_RE.test(input.lane.trim()))) {
|
|
66
|
+
throw new Error(`task ${input.id} lane must match ${TASK_ID_RE.source}`);
|
|
67
|
+
}
|
|
68
|
+
assertText(input.objective, `task ${input.id} objective`);
|
|
69
|
+
if (input.changePolicy !== undefined && !['read_only', 'isolated_write'].includes(input.changePolicy)) {
|
|
70
|
+
throw new Error(`Task ${input.id} has an unsupported changePolicy.`);
|
|
71
|
+
}
|
|
72
|
+
if (input.maxAttempts !== undefined && (!Number.isInteger(input.maxAttempts) || input.maxAttempts < 1)) {
|
|
73
|
+
throw new Error(`Task ${input.id} maxAttempts must be a positive integer.`);
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
id: input.id,
|
|
77
|
+
lane: input.lane?.trim() || input.id,
|
|
78
|
+
title: input.title.trim(),
|
|
79
|
+
contract: {
|
|
80
|
+
objective: input.objective.trim(),
|
|
81
|
+
scope: {
|
|
82
|
+
allow: stringArray(input.scope?.allow, ['**/*'], `task ${input.id} scope.allow`),
|
|
83
|
+
deny: stringArray(input.scope?.deny, ['.git/**'], `task ${input.id} scope.deny`),
|
|
84
|
+
},
|
|
85
|
+
acceptanceCriteria: stringArray(input.acceptanceCriteria, [], `task ${input.id} acceptanceCriteria`),
|
|
86
|
+
requiredChecks: stringArray(input.requiredChecks, [], `task ${input.id} requiredChecks`),
|
|
87
|
+
changePolicy: input.changePolicy ?? 'isolated_write',
|
|
88
|
+
},
|
|
89
|
+
dependsOn: stringArray(input.dependsOn, [], `task ${input.id} dependsOn`),
|
|
90
|
+
status: 'pending',
|
|
91
|
+
attempts: 0,
|
|
92
|
+
maxAttempts: input.maxAttempts ?? 1,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
export function createInitialRun(id, workspaceRoot, definition, now = new Date().toISOString()) {
|
|
96
|
+
assertText(id, 'run id');
|
|
97
|
+
assertText(definition.objective, 'objective');
|
|
98
|
+
if (!Array.isArray(definition.tasks) || definition.tasks.length === 0) {
|
|
99
|
+
throw new Error('An orchestration requires at least one task.');
|
|
100
|
+
}
|
|
101
|
+
const tasks = {};
|
|
102
|
+
for (const input of definition.tasks) {
|
|
103
|
+
const task = normalizeTask(input);
|
|
104
|
+
if (tasks[task.id])
|
|
105
|
+
throw new Error(`Duplicate task id: ${task.id}`);
|
|
106
|
+
tasks[task.id] = task;
|
|
107
|
+
}
|
|
108
|
+
for (const task of Object.values(tasks)) {
|
|
109
|
+
for (const dependency of task.dependsOn) {
|
|
110
|
+
if (!tasks[dependency])
|
|
111
|
+
throw new Error(`Task ${task.id} depends on unknown task ${dependency}.`);
|
|
112
|
+
if (dependency === task.id)
|
|
113
|
+
throw new Error(`Task ${task.id} cannot depend on itself.`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
assertAcyclic(tasks);
|
|
117
|
+
const explicitLaneIds = new Set(definition.tasks.flatMap((input) => (input.lane?.trim() ? [input.lane.trim()] : [])));
|
|
118
|
+
const lanes = normalizeLanes(workspaceRoot, definition.lanes, tasks, explicitLaneIds);
|
|
119
|
+
return {
|
|
120
|
+
schemaVersion: ORCHESTRATION_SCHEMA_VERSION,
|
|
121
|
+
id,
|
|
122
|
+
objective: definition.objective.trim(),
|
|
123
|
+
workspaceRoot,
|
|
124
|
+
status: 'running',
|
|
125
|
+
sequence: 0,
|
|
126
|
+
tasks,
|
|
127
|
+
lanes,
|
|
128
|
+
/** 跑空后是否直接收尾;false 时进入 idle 等待继续派活(长驻 lane)。 */
|
|
129
|
+
autoClose: definition.autoClose === true,
|
|
130
|
+
policy: normalizePolicy(definition.policy),
|
|
131
|
+
cancellationRequested: false,
|
|
132
|
+
createdAt: now,
|
|
133
|
+
updatedAt: now,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
function assertAcyclic(tasks) {
|
|
137
|
+
const visiting = new Set();
|
|
138
|
+
const visited = new Set();
|
|
139
|
+
const visit = (id) => {
|
|
140
|
+
if (visiting.has(id))
|
|
141
|
+
throw new Error(`Task graph contains a cycle at ${id}.`);
|
|
142
|
+
if (visited.has(id))
|
|
143
|
+
return;
|
|
144
|
+
visiting.add(id);
|
|
145
|
+
for (const dependency of tasks[id].dependsOn)
|
|
146
|
+
visit(dependency);
|
|
147
|
+
visiting.delete(id);
|
|
148
|
+
visited.add(id);
|
|
149
|
+
};
|
|
150
|
+
for (const id of Object.keys(tasks))
|
|
151
|
+
visit(id);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Lane 是执行现场(worktree + 会话)的归属单位。声明式 lanes 可以指向别的仓库;
|
|
155
|
+
* 未声明的 lane 按「Run 自己的 workspaceRoot」隐式建一条,因此旧的 dag.json 不受影响。
|
|
156
|
+
*/
|
|
157
|
+
function normalizeLanes(workspaceRoot, inputs, tasks, explicitLaneIds) {
|
|
158
|
+
const lanes = {};
|
|
159
|
+
const declare = (input) => {
|
|
160
|
+
if (!input || typeof input !== 'object')
|
|
161
|
+
throw new Error('Each lane must be an object.');
|
|
162
|
+
assertText(input.id, 'lane.id');
|
|
163
|
+
if (!TASK_ID_RE.test(input.id))
|
|
164
|
+
throw new Error(`lane.id must match ${TASK_ID_RE.source}: ${input.id}`);
|
|
165
|
+
if (lanes[input.id])
|
|
166
|
+
throw new Error(`Duplicate lane id: ${input.id}`);
|
|
167
|
+
if (input.mode !== undefined && !LANE_MODES.has(input.mode)) {
|
|
168
|
+
throw new Error(`lane ${input.id} has an unsupported mode: ${String(input.mode)}`);
|
|
169
|
+
}
|
|
170
|
+
lanes[input.id] = {
|
|
171
|
+
id: input.id,
|
|
172
|
+
workspaceRoot: path.resolve(workspaceRoot, input.workspaceRoot ?? '.'),
|
|
173
|
+
// 缺省 worktree:CLI 会在建 Run 前按工作区是否 git 仓库把 mode 补全。
|
|
174
|
+
mode: input.mode ?? 'worktree',
|
|
175
|
+
allowInplace: input.allowInplace === true,
|
|
176
|
+
keepWorktree: input.keepWorktree === true,
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
for (const input of inputs ?? [])
|
|
180
|
+
declare(input);
|
|
181
|
+
const declared = (inputs ?? []).length > 0;
|
|
182
|
+
for (const task of Object.values(tasks)) {
|
|
183
|
+
if (lanes[task.lane])
|
|
184
|
+
continue;
|
|
185
|
+
// 声明了 lanes 又显式写了指向不存在的 lane,多半是拼写错误:宁可报错,也不要静默
|
|
186
|
+
// 新开一条 worktree + 新会话。未写 lane(缺省=task.id)仍按需隐式创建。
|
|
187
|
+
if (declared && explicitLaneIds.has(task.lane)) {
|
|
188
|
+
throw new Error(`Task ${task.id} references unknown lane ${task.lane}.`);
|
|
189
|
+
}
|
|
190
|
+
lanes[task.lane] = {
|
|
191
|
+
id: task.lane,
|
|
192
|
+
workspaceRoot: path.resolve(workspaceRoot),
|
|
193
|
+
mode: 'worktree',
|
|
194
|
+
allowInplace: false,
|
|
195
|
+
keepWorktree: false,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
return lanes;
|
|
199
|
+
}
|
|
200
|
+
export function makeEvent(run, event) {
|
|
201
|
+
return {
|
|
202
|
+
...event,
|
|
203
|
+
schemaVersion: ORCHESTRATION_SCHEMA_VERSION,
|
|
204
|
+
sequence: run.sequence + 1,
|
|
205
|
+
timestamp: new Date().toISOString(),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
function taskOf(run, id) {
|
|
209
|
+
const task = run.tasks[id];
|
|
210
|
+
if (!task)
|
|
211
|
+
throw new Error(`Unknown orchestration task: ${id}`);
|
|
212
|
+
return task;
|
|
213
|
+
}
|
|
214
|
+
export function reduceEvent(current, event) {
|
|
215
|
+
if (event.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION)
|
|
216
|
+
throw new Error('Unsupported orchestration event schema.');
|
|
217
|
+
if (event.type === 'run.created') {
|
|
218
|
+
if (current)
|
|
219
|
+
throw new Error('run.created can only be the first event.');
|
|
220
|
+
if (event.sequence !== 1 || event.data.run.sequence !== 0 || event.data.run.status !== 'running') {
|
|
221
|
+
throw new Error('run.created must initialize a running run at sequence 1.');
|
|
222
|
+
}
|
|
223
|
+
return { ...event.data.run, sequence: event.sequence, updatedAt: event.timestamp };
|
|
224
|
+
}
|
|
225
|
+
if (!current)
|
|
226
|
+
throw new Error(`Event ${event.type} appeared before run.created.`);
|
|
227
|
+
// 终态冻结账本;`idle` 仍可追加(长驻 lane:跑空后继续 dispatch)。
|
|
228
|
+
if (TERMINAL_RUNS.has(current.status))
|
|
229
|
+
throw new Error(`Run ${current.id} is already ${current.status}.`);
|
|
230
|
+
if (event.sequence !== current.sequence + 1) {
|
|
231
|
+
throw new Error(`Expected orchestration event ${current.sequence + 1}, received ${event.sequence}.`);
|
|
232
|
+
}
|
|
233
|
+
const run = structuredClone(current);
|
|
234
|
+
run.sequence = event.sequence;
|
|
235
|
+
run.updatedAt = event.timestamp;
|
|
236
|
+
// lane 是后加的概念:P1 早期创建的 Run 没有 lanes 字段,恢复时补成空表以免读路径抛错。
|
|
237
|
+
run.lanes ??= {};
|
|
238
|
+
run.autoClose ??= false;
|
|
239
|
+
run.policy ??= { ...DEFAULT_RUN_POLICY };
|
|
240
|
+
for (const lane of Object.values(run.lanes)) {
|
|
241
|
+
// 旧 Run 的 lane 没有 mode:P1 只有 worktree 一档。
|
|
242
|
+
lane.mode ??= 'worktree';
|
|
243
|
+
lane.allowInplace ??= false;
|
|
244
|
+
}
|
|
245
|
+
if (event.type === 'task.added') {
|
|
246
|
+
// 只在静默态接受追加:running 时任务图应当已经规划完毕,允许追加会让调度依据漂移。
|
|
247
|
+
// `awaiting_user` 与 `idle` 一样是「没人在跑」的静默态,追加后由 run.resumed 唤醒。
|
|
248
|
+
if (run.status !== 'idle' && run.status !== 'awaiting_user') {
|
|
249
|
+
throw new Error(`Run ${run.id} can only accept new tasks while idle.`);
|
|
250
|
+
}
|
|
251
|
+
const task = normalizeTask(event.data.task);
|
|
252
|
+
if (run.tasks[task.id])
|
|
253
|
+
throw new Error(`Duplicate task id: ${task.id}`);
|
|
254
|
+
for (const dependency of task.dependsOn) {
|
|
255
|
+
if (!run.tasks[dependency])
|
|
256
|
+
throw new Error(`Task ${task.id} depends on unknown task ${dependency}.`);
|
|
257
|
+
}
|
|
258
|
+
if (!run.lanes[task.lane]) {
|
|
259
|
+
// 追加任务可以落到已有 lane 上,也可以隐式新建一条(用 Run 的 workspaceRoot)。
|
|
260
|
+
run.lanes[task.lane] = {
|
|
261
|
+
id: task.lane,
|
|
262
|
+
workspaceRoot: run.workspaceRoot,
|
|
263
|
+
mode: 'worktree',
|
|
264
|
+
allowInplace: false,
|
|
265
|
+
keepWorktree: false,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
run.tasks[task.id] = task;
|
|
269
|
+
}
|
|
270
|
+
else if (event.type === 'run.idle') {
|
|
271
|
+
if (run.status !== 'running')
|
|
272
|
+
throw new Error(`Run ${run.id} cannot idle from ${run.status}.`);
|
|
273
|
+
if (Object.values(run.tasks).some((task) => ACTIVE_TASKS.has(task.status))) {
|
|
274
|
+
throw new Error(`Run ${run.id} cannot idle while a task is active.`);
|
|
275
|
+
}
|
|
276
|
+
run.status = 'idle';
|
|
277
|
+
}
|
|
278
|
+
else if (event.type === 'run.awaiting_user') {
|
|
279
|
+
if (run.status !== 'running')
|
|
280
|
+
throw new Error(`Run ${run.id} cannot await a user from ${run.status}.`);
|
|
281
|
+
if (Object.values(run.tasks).some((task) => ACTIVE_TASKS.has(task.status))) {
|
|
282
|
+
throw new Error(`Run ${run.id} cannot await a user while a task is active.`);
|
|
283
|
+
}
|
|
284
|
+
run.status = 'awaiting_user';
|
|
285
|
+
run.awaitingReason = event.data.reason;
|
|
286
|
+
// 冻结壁钟消耗:预算判定不再随人等待的时长增长。
|
|
287
|
+
run.usage = {
|
|
288
|
+
tokens: run.usage?.tokens ?? 0,
|
|
289
|
+
wallClockMs: Date.parse(event.timestamp) - Date.parse(run.budgetWindowStart ?? run.createdAt),
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
else if (event.type === 'run.budget_exhausted') {
|
|
293
|
+
if (run.status !== 'running')
|
|
294
|
+
throw new Error(`Run ${run.id} cannot exhaust its budget from ${run.status}.`);
|
|
295
|
+
run.usage = {
|
|
296
|
+
tokens: event.data.limit === 'tokens' ? event.data.used : (run.usage?.tokens ?? 0),
|
|
297
|
+
wallClockMs: event.data.limit === 'wall_clock' ? event.data.used : (run.usage?.wallClockMs ?? 0),
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
else if (event.type === 'run.resumed') {
|
|
301
|
+
if (run.status !== 'idle' && run.status !== 'awaiting_user') {
|
|
302
|
+
throw new Error(`Run ${run.id} cannot resume from ${run.status}.`);
|
|
303
|
+
}
|
|
304
|
+
run.status = 'running';
|
|
305
|
+
run.awaitingReason = undefined;
|
|
306
|
+
// 预算按「一段连续自主工作」算:人一旦介入就重新开一个窗口,
|
|
307
|
+
// 否则超限的 Run 一 resume 就立刻又超限,等于永远蹬不动。
|
|
308
|
+
run.budgetWindowStart = event.timestamp;
|
|
309
|
+
run.usage = { tokens: 0, wallClockMs: 0 };
|
|
310
|
+
}
|
|
311
|
+
else if (event.type === 'run.reviewed') {
|
|
312
|
+
// 收工判定只是建议:它不改变 Run 状态,也不允许在终态账本上追加(上面已拦)。
|
|
313
|
+
run.lastReview = event.data.review;
|
|
314
|
+
}
|
|
315
|
+
else if (event.type === 'conflict.serialized') {
|
|
316
|
+
// 纯观测事件:审计“哪些写任务因为改同一批文件而被串行”。不改任务状态,不广播。
|
|
317
|
+
if (!run.tasks[event.data.taskId])
|
|
318
|
+
throw new Error(`Unknown orchestration task: ${event.data.taskId}`);
|
|
319
|
+
}
|
|
320
|
+
else if (event.type === 'run.cancel_requested') {
|
|
321
|
+
if (run.cancellationRequested)
|
|
322
|
+
throw new Error(`Run ${run.id} already has a cancellation request.`);
|
|
323
|
+
run.cancellationRequested = true;
|
|
324
|
+
}
|
|
325
|
+
else if (event.type === 'run.completed') {
|
|
326
|
+
if (!Object.values(run.tasks).every((task) => task.status === 'completed')) {
|
|
327
|
+
throw new Error(`Run ${run.id} cannot complete while tasks remain unfinished.`);
|
|
328
|
+
}
|
|
329
|
+
run.status = 'completed';
|
|
330
|
+
}
|
|
331
|
+
else if (event.type === 'run.failed') {
|
|
332
|
+
if (Object.values(run.tasks).some((task) => ACTIVE_TASKS.has(task.status))) {
|
|
333
|
+
throw new Error(`Run ${run.id} cannot fail while a task is active.`);
|
|
334
|
+
}
|
|
335
|
+
run.status = 'failed';
|
|
336
|
+
}
|
|
337
|
+
else if (event.type === 'run.cancelled') {
|
|
338
|
+
if (!run.cancellationRequested)
|
|
339
|
+
throw new Error(`Run ${run.id} cannot cancel without a cancellation request.`);
|
|
340
|
+
if (Object.values(run.tasks).some((task) => !TERMINAL_TASKS.has(task.status))) {
|
|
341
|
+
throw new Error(`Run ${run.id} cannot cancel while tasks remain non-terminal.`);
|
|
342
|
+
}
|
|
343
|
+
run.status = 'cancelled';
|
|
344
|
+
}
|
|
345
|
+
else if ('laneId' in event.data) {
|
|
346
|
+
const lane = run.lanes[event.data.laneId];
|
|
347
|
+
if (!lane)
|
|
348
|
+
throw new Error(`Unknown orchestration lane: ${event.data.laneId}`);
|
|
349
|
+
if (event.type === 'lane.opened') {
|
|
350
|
+
if (lane.closed)
|
|
351
|
+
throw new Error(`Lane ${lane.id} is already closed.`);
|
|
352
|
+
// 允许重开:崩溃恢复后执行现场可能已被销毁,Worker 会新建一个并重新上报基线。
|
|
353
|
+
lane.worktreePath = event.data.worktreePath;
|
|
354
|
+
lane.baseTree = event.data.baseTree;
|
|
355
|
+
lane.baselineTree = event.data.baseTree;
|
|
356
|
+
lane.baseIndex = event.data.baseIndex;
|
|
357
|
+
lane.baselineIndex = event.data.baseIndex;
|
|
358
|
+
}
|
|
359
|
+
else if (event.type === 'lane.reopened') {
|
|
360
|
+
// 显式 --reuse:现场已删除,只把会话历史接回来,基线等 Worker 重新上报。
|
|
361
|
+
if (!lane.closed)
|
|
362
|
+
throw new Error(`Lane ${lane.id} is not closed.`);
|
|
363
|
+
lane.closed = undefined;
|
|
364
|
+
lane.worktreePath = undefined;
|
|
365
|
+
lane.baseTree = undefined;
|
|
366
|
+
lane.baselineTree = undefined;
|
|
367
|
+
lane.baseIndex = undefined;
|
|
368
|
+
lane.baselineIndex = undefined;
|
|
369
|
+
}
|
|
370
|
+
else if (event.type === 'lane.session') {
|
|
371
|
+
if (lane.closed)
|
|
372
|
+
throw new Error(`Lane ${lane.id} is already closed.`);
|
|
373
|
+
lane.sessionId = event.data.sessionId;
|
|
374
|
+
}
|
|
375
|
+
else if (event.type === 'lane.checkpoint') {
|
|
376
|
+
if (!lane.worktreePath)
|
|
377
|
+
throw new Error(`Lane ${lane.id} has no open worktree.`);
|
|
378
|
+
if (lane.closed)
|
|
379
|
+
throw new Error(`Lane ${lane.id} is already closed.`);
|
|
380
|
+
lane.baselineTree = event.data.baselineTree;
|
|
381
|
+
lane.baselineIndex = event.data.baselineIndex;
|
|
382
|
+
}
|
|
383
|
+
else if (event.type === 'lane.closed') {
|
|
384
|
+
if (lane.closed)
|
|
385
|
+
throw new Error(`Lane ${lane.id} is already closed.`);
|
|
386
|
+
lane.closed = {
|
|
387
|
+
reason: event.data.reason,
|
|
388
|
+
patchPath: event.data.patchPath,
|
|
389
|
+
sessionArchivePath: event.data.sessionArchivePath,
|
|
390
|
+
kept: event.data.kept,
|
|
391
|
+
error: event.data.error,
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
else if ('taskId' in event.data) {
|
|
396
|
+
const task = taskOf(run, event.data.taskId);
|
|
397
|
+
if (event.type === 'task.approval_requested') {
|
|
398
|
+
// 人工介入只可能发生在任务真的在跑的时候:dispatching 太早(Host 还没起来),
|
|
399
|
+
// 已是终态则说明这是迟到的上报,忽略会让「谁在等」永久悬空,所以直接拒绝。
|
|
400
|
+
if (!['dispatching', 'running'].includes(task.status)) {
|
|
401
|
+
throw new Error(`Task ${task.id} cannot request approval from ${task.status}.`);
|
|
402
|
+
}
|
|
403
|
+
task.approvals ??= {};
|
|
404
|
+
if (task.approvals[event.data.approval.id]) {
|
|
405
|
+
throw new Error(`Task ${task.id} already has a pending approval ${event.data.approval.id}.`);
|
|
406
|
+
}
|
|
407
|
+
task.approvals[event.data.approval.id] = { ...event.data.approval, taskId: task.id };
|
|
408
|
+
}
|
|
409
|
+
else if (event.type === 'task.approval_resolved') {
|
|
410
|
+
const approval = task.approvals?.[event.data.approvalId];
|
|
411
|
+
if (!approval)
|
|
412
|
+
throw new Error(`Task ${task.id} has no approval ${event.data.approvalId}.`);
|
|
413
|
+
if (approval.resolved)
|
|
414
|
+
throw new Error(`Approval ${event.data.approvalId} is already resolved.`);
|
|
415
|
+
approval.resolved = event.data.resolution;
|
|
416
|
+
}
|
|
417
|
+
else if (event.type === 'task.ready') {
|
|
418
|
+
if (!['pending', 'failed', 'interrupted'].includes(task.status)) {
|
|
419
|
+
throw new Error(`Task ${task.id} cannot become ready from ${task.status}.`);
|
|
420
|
+
}
|
|
421
|
+
if (!task.dependsOn.every((id) => run.tasks[id]?.status === 'completed')) {
|
|
422
|
+
throw new Error(`Task ${task.id} cannot become ready before its dependencies complete.`);
|
|
423
|
+
}
|
|
424
|
+
if (task.status !== 'pending' && task.attempts >= task.maxAttempts) {
|
|
425
|
+
throw new Error(`Task ${task.id} has exhausted its attempts.`);
|
|
426
|
+
}
|
|
427
|
+
task.status = 'ready';
|
|
428
|
+
task.error = undefined;
|
|
429
|
+
task.finishedAt = undefined;
|
|
430
|
+
}
|
|
431
|
+
else if (event.type === 'task.deferred') {
|
|
432
|
+
// 被槽位/租约/冲突挡住:任务保持 ready,只把「为什么在等」记进 lastEvent,供 status 展示。
|
|
433
|
+
if (task.status !== 'ready')
|
|
434
|
+
throw new Error(`Task ${task.id} cannot defer from ${task.status}.`);
|
|
435
|
+
task.lastEvent = event.data.blockedBy
|
|
436
|
+
? `deferred (${event.data.reason}) by ${event.data.blockedBy}`
|
|
437
|
+
: `deferred (${event.data.reason})`;
|
|
438
|
+
}
|
|
439
|
+
else if (event.type === 'task.dispatching') {
|
|
440
|
+
if (task.status !== 'ready')
|
|
441
|
+
throw new Error(`Task ${task.id} cannot dispatch from ${task.status}.`);
|
|
442
|
+
if (event.data.attempt !== task.attempts + 1 || event.data.attempt > task.maxAttempts) {
|
|
443
|
+
throw new Error(`Task ${task.id} received invalid attempt ${event.data.attempt}.`);
|
|
444
|
+
}
|
|
445
|
+
task.status = 'dispatching';
|
|
446
|
+
task.attempts = event.data.attempt;
|
|
447
|
+
task.workerId = event.data.workerId;
|
|
448
|
+
task.sessionId = undefined;
|
|
449
|
+
task.workspacePath = event.data.workspacePath;
|
|
450
|
+
task.patchPath = undefined;
|
|
451
|
+
task.sessionArchivePath = undefined;
|
|
452
|
+
task.output = undefined;
|
|
453
|
+
task.error = undefined;
|
|
454
|
+
// 新 attempt 的 Worker 是全新进程:上一轮的挂起审批不可能再被回答,清掉以免控制面显示幽灵请求。
|
|
455
|
+
task.approvals = undefined;
|
|
456
|
+
task.lastEvent = undefined;
|
|
457
|
+
task.startedAt = undefined;
|
|
458
|
+
task.finishedAt = undefined;
|
|
459
|
+
}
|
|
460
|
+
else if (event.type === 'task.started') {
|
|
461
|
+
if (task.status !== 'dispatching')
|
|
462
|
+
throw new Error(`Task ${task.id} cannot start from ${task.status}.`);
|
|
463
|
+
task.status = 'running';
|
|
464
|
+
task.sessionId = event.data.sessionId ?? task.sessionId;
|
|
465
|
+
task.workspacePath = event.data.workspacePath ?? task.workspacePath;
|
|
466
|
+
task.startedAt = event.timestamp;
|
|
467
|
+
}
|
|
468
|
+
else if (event.type === 'task.progress') {
|
|
469
|
+
if (!['dispatching', 'running'].includes(task.status))
|
|
470
|
+
throw new Error(`Task ${task.id} cannot report progress from ${task.status}.`);
|
|
471
|
+
task.lastEvent = event.data.message;
|
|
472
|
+
task.sessionId = event.data.sessionId ?? task.sessionId;
|
|
473
|
+
}
|
|
474
|
+
else if (event.type === 'task.completed') {
|
|
475
|
+
if (!['dispatching', 'running'].includes(task.status))
|
|
476
|
+
throw new Error(`Task ${task.id} cannot complete from ${task.status}.`);
|
|
477
|
+
if (event.data.handoff.taskId !== task.id ||
|
|
478
|
+
event.data.handoff.attempt !== task.attempts ||
|
|
479
|
+
event.data.handoff.outcome !== 'completed') {
|
|
480
|
+
throw new Error(`Task ${task.id} received a mismatched completion handoff.`);
|
|
481
|
+
}
|
|
482
|
+
task.status = 'completed';
|
|
483
|
+
task.output = event.data.handoff;
|
|
484
|
+
task.sessionId = event.data.sessionId ?? task.sessionId;
|
|
485
|
+
task.workspacePath = event.data.workspacePath ?? task.workspacePath;
|
|
486
|
+
task.patchPath = event.data.patchPath;
|
|
487
|
+
task.sessionArchivePath = event.data.sessionArchivePath;
|
|
488
|
+
task.error = undefined;
|
|
489
|
+
task.finishedAt = event.timestamp;
|
|
490
|
+
// 预算按“已完成任务上报的 usage”累加;缺报按 0,不猜测。
|
|
491
|
+
if (event.data.handoff.tokens) {
|
|
492
|
+
run.usage = {
|
|
493
|
+
tokens: (run.usage?.tokens ?? 0) + event.data.handoff.tokens,
|
|
494
|
+
wallClockMs: 0,
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
else if (event.type === 'task.failed' || event.type === 'task.interrupted') {
|
|
499
|
+
if (!['dispatching', 'running'].includes(task.status))
|
|
500
|
+
throw new Error(`Task ${task.id} cannot stop from ${task.status}.`);
|
|
501
|
+
const expectedOutcome = event.type === 'task.failed' ? 'failed' : 'interrupted';
|
|
502
|
+
if (event.data.handoff &&
|
|
503
|
+
(event.data.handoff.taskId !== task.id ||
|
|
504
|
+
event.data.handoff.attempt !== task.attempts ||
|
|
505
|
+
event.data.handoff.outcome !== expectedOutcome)) {
|
|
506
|
+
throw new Error(`Task ${task.id} received a mismatched ${expectedOutcome} handoff.`);
|
|
507
|
+
}
|
|
508
|
+
task.status = expectedOutcome;
|
|
509
|
+
task.error = event.data.error;
|
|
510
|
+
task.output = event.data.handoff;
|
|
511
|
+
task.sessionId = event.data.sessionId ?? task.sessionId;
|
|
512
|
+
task.workspacePath = event.data.workspacePath ?? task.workspacePath;
|
|
513
|
+
task.patchPath = event.data.patchPath;
|
|
514
|
+
task.sessionArchivePath = event.data.sessionArchivePath;
|
|
515
|
+
task.finishedAt = event.timestamp;
|
|
516
|
+
}
|
|
517
|
+
else if (event.type === 'task.cancelled') {
|
|
518
|
+
if (TERMINAL_TASKS.has(task.status))
|
|
519
|
+
throw new Error(`Task ${task.id} is already terminal.`);
|
|
520
|
+
task.status = 'cancelled';
|
|
521
|
+
task.error = event.data.reason;
|
|
522
|
+
task.finishedAt = event.timestamp;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return run;
|
|
526
|
+
}
|
|
527
|
+
export function isRunTerminal(run) {
|
|
528
|
+
return run.status !== 'running' && run.status !== 'idle' && run.status !== 'awaiting_user';
|
|
529
|
+
}
|
|
530
|
+
/** Run 是否还能接活(running / idle / awaiting_user);`awaiting_user` 用 dispatch 唤醒。 */
|
|
531
|
+
export function isRunLive(run) {
|
|
532
|
+
return !isRunTerminal(run);
|
|
533
|
+
}
|