mocode-ai 1.9.6 → 1.9.9
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/pipeline.js +8 -3
- 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/compact.js +8 -1
- package/dist/session/store.js +1 -1
- package/dist/tools/builtins/ask-human.js +27 -6
- package/dist/tools/constants.js +10 -0
- 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,673 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { WorkspaceLeaseManager } from './lease.js';
|
|
4
|
+
import { needsReview, reviewRun } from './review.js';
|
|
5
|
+
import { scopeOverlaps, validateChangedFiles } from './scope.js';
|
|
6
|
+
const ACTIVE = new Set(['dispatching', 'running']);
|
|
7
|
+
const TERMINAL = new Set(['completed', 'failed', 'cancelled']);
|
|
8
|
+
const TERMINAL_RUNS = new Set(['completed', 'failed', 'cancelled']);
|
|
9
|
+
function readyCandidates(run) {
|
|
10
|
+
return Object.values(run.tasks).filter((task) => {
|
|
11
|
+
if (task.status === 'failed' || task.status === 'interrupted')
|
|
12
|
+
return task.attempts < task.maxAttempts;
|
|
13
|
+
return task.status === 'pending' && task.dependsOn.every((id) => run.tasks[id]?.status === 'completed');
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
function sleep(ms) {
|
|
17
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* 任务最终写在哪:`inplace` 档写共享的原目录(所有 lane 同名冲突),
|
|
21
|
+
* 隔离档位(worktree / copy)各有独立现场,按 lane 区分。
|
|
22
|
+
*/
|
|
23
|
+
function executionRoot(task, run) {
|
|
24
|
+
const lane = run.lanes[task.lane];
|
|
25
|
+
if (!lane)
|
|
26
|
+
return run.workspaceRoot.toLowerCase();
|
|
27
|
+
if ((lane.mode ?? 'worktree') === 'inplace')
|
|
28
|
+
return lane.workspaceRoot.toLowerCase();
|
|
29
|
+
return `lane:${lane.id}`;
|
|
30
|
+
}
|
|
31
|
+
function handoff(task, result) {
|
|
32
|
+
return {
|
|
33
|
+
taskId: task.id,
|
|
34
|
+
attempt: task.attempts,
|
|
35
|
+
outcome: result.outcome,
|
|
36
|
+
summary: result.summary,
|
|
37
|
+
changedFiles: result.changedFiles,
|
|
38
|
+
validation: result.validation ?? task.contract.requiredChecks.map((command) => ({ command, status: 'not_reported' })),
|
|
39
|
+
artifacts: [result.patchPath, result.sessionArchivePath].filter((item) => item !== undefined),
|
|
40
|
+
risks: [...(result.risks ?? []), ...(result.error ? [result.error] : [])],
|
|
41
|
+
...(result.tokens !== undefined ? { tokens: result.tokens } : {}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Control-plane gate: a Worker cannot self-declare completion that violates its task contract. */
|
|
45
|
+
function completionViolation(task, result) {
|
|
46
|
+
if (!result.summary.trim())
|
|
47
|
+
return 'Worker returned an empty handoff summary.';
|
|
48
|
+
const failed = result.validation?.find((item) => item.status === 'failed');
|
|
49
|
+
if (failed)
|
|
50
|
+
return `Worker reported a failed validation: ${failed.command}`;
|
|
51
|
+
const missing = task.contract.requiredChecks.filter((command) => !result.validation?.some((item) => item.command === command && item.status === 'passed'));
|
|
52
|
+
if (missing.length > 0)
|
|
53
|
+
return `Required checks were not reported as passed: ${missing.join(', ')}`;
|
|
54
|
+
if (task.contract.changePolicy === 'read_only' && result.changedFiles.length > 0) {
|
|
55
|
+
return `Read-only task modified files: ${result.changedFiles.join(', ')}`;
|
|
56
|
+
}
|
|
57
|
+
const scopeErrors = validateChangedFiles(task.contract, result.changedFiles);
|
|
58
|
+
return scopeErrors.length > 0 ? scopeErrors.join(' ') : undefined;
|
|
59
|
+
}
|
|
60
|
+
export class OrchestrationScheduler {
|
|
61
|
+
store;
|
|
62
|
+
worker;
|
|
63
|
+
hooks;
|
|
64
|
+
pollMs;
|
|
65
|
+
cancelGraceMs;
|
|
66
|
+
waitForMore;
|
|
67
|
+
review;
|
|
68
|
+
leases = new WorkspaceLeaseManager();
|
|
69
|
+
/** 在跑的 Worker:taskId → 完成 promise。并发调度的全部状态都在这里。 */
|
|
70
|
+
inFlight = new Map();
|
|
71
|
+
/** taskId → 上一次记录的等待原因;同一个原因只落一次事件,避免每 250ms 刷屏。 */
|
|
72
|
+
deferred = new Map();
|
|
73
|
+
/** 已落盘的 conflict.serialized 组合(task\0blockedBy\0overlap),同组合只记一次。 */
|
|
74
|
+
serialized = new Set();
|
|
75
|
+
/** 预算超限的人话说明;进 awaiting_user 时作为 reason 落账。 */
|
|
76
|
+
budgetNote;
|
|
77
|
+
cancellationSent = false;
|
|
78
|
+
constructor(store, worker, hooks = {}, options = {}) {
|
|
79
|
+
this.store = store;
|
|
80
|
+
this.worker = worker;
|
|
81
|
+
this.hooks = hooks;
|
|
82
|
+
this.pollMs = options.pollMs ?? 250;
|
|
83
|
+
this.cancelGraceMs = options.cancelGraceMs ?? 15_000;
|
|
84
|
+
this.waitForMore = options.waitForMore === true;
|
|
85
|
+
this.review = options.review ?? ((run) => reviewRun(run));
|
|
86
|
+
}
|
|
87
|
+
async run() {
|
|
88
|
+
this.recoverInFlightTasks();
|
|
89
|
+
while (!TERMINAL_RUNS.has(this.store.current.status)) {
|
|
90
|
+
this.observeCancellation();
|
|
91
|
+
if (this.store.current.cancellationRequested) {
|
|
92
|
+
await this.cancelRun();
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
// idle / awaiting_user 都是「没活可干但有救」的状态:可以继续等新任务,也可以直接返回给调用方。
|
|
96
|
+
// awaiting_user 必须由人显式 dispatch 唤醒,不在原地自己转圈。
|
|
97
|
+
if (this.store.current.status === 'awaiting_user')
|
|
98
|
+
break;
|
|
99
|
+
if (this.store.current.status === 'idle' && !this.hasRunnableWork()) {
|
|
100
|
+
if (!this.waitForMore)
|
|
101
|
+
break;
|
|
102
|
+
await sleep(this.pollMs);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
// 预算闸:超限时不再派发新任务,已在跑的让它跑完,然后进 awaiting_user 等人决定。
|
|
106
|
+
if (!this.enforceBudget()) {
|
|
107
|
+
if (this.inFlight.size > 0) {
|
|
108
|
+
await Promise.race([...this.inFlight.values(), sleep(this.pollMs)]);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
this.append({ type: 'run.awaiting_user', data: { reason: this.budgetNote ?? 'Run budget exhausted.' } });
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
this.promoteReadyTasks();
|
|
115
|
+
this.dispatchReady();
|
|
116
|
+
if (this.inFlight.size > 0) {
|
|
117
|
+
// 任一 Worker 结束或一个轮询窗口过去就回来补槽位。
|
|
118
|
+
await Promise.race([...this.inFlight.values(), sleep(this.pollMs)]);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
const run = this.store.current;
|
|
122
|
+
if (Object.values(run.tasks).every((task) => task.status === 'completed')) {
|
|
123
|
+
await this.finishCompleted();
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
const irrecoverable = Object.values(run.tasks).some((task) => task.status === 'failed' || (task.status === 'interrupted' && task.attempts >= task.maxAttempts));
|
|
127
|
+
const blocked = Object.values(run.tasks).some((task) => task.status === 'pending' && task.dependsOn.some((id) => run.tasks[id]?.status !== 'completed'));
|
|
128
|
+
if (irrecoverable || blocked) {
|
|
129
|
+
// 重试耗尽不等于「必须终止」:现场与会话都还在,交给人决定是补任务还是收工。
|
|
130
|
+
this.append({
|
|
131
|
+
type: 'run.awaiting_user',
|
|
132
|
+
data: {
|
|
133
|
+
reason: irrecoverable
|
|
134
|
+
? 'A task exhausted its attempts; add a follow-up task or close the run.'
|
|
135
|
+
: 'A task cannot run because its dependency did not complete.',
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
await sleep(this.pollMs);
|
|
141
|
+
}
|
|
142
|
+
return this.store.current;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* 预算判定:返回 false 表示「不该再派新活」。
|
|
146
|
+
* 只记录一次超限事件(run.budget_exhausted 不允许重复落到同一状态上),
|
|
147
|
+
* 真正的状态转移留给 run() 在 in-flight 清空后做。
|
|
148
|
+
*/
|
|
149
|
+
enforceBudget() {
|
|
150
|
+
const run = this.store.current;
|
|
151
|
+
const budget = run.policy?.budget;
|
|
152
|
+
if (!budget)
|
|
153
|
+
return true;
|
|
154
|
+
if (budget.maxTokensPerRun !== undefined) {
|
|
155
|
+
const used = run.usage?.tokens ?? 0;
|
|
156
|
+
if (used >= budget.maxTokensPerRun)
|
|
157
|
+
return this.markBudgetExhausted('tokens', used, budget.maxTokensPerRun);
|
|
158
|
+
}
|
|
159
|
+
if (budget.maxWallClockMs !== undefined) {
|
|
160
|
+
const used = Date.now() - Date.parse(run.budgetWindowStart ?? run.createdAt);
|
|
161
|
+
if (used >= budget.maxWallClockMs)
|
|
162
|
+
return this.markBudgetExhausted('wall_clock', used, budget.maxWallClockMs);
|
|
163
|
+
}
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
markBudgetExhausted(limit, used, cap) {
|
|
167
|
+
if (!this.budgetNote) {
|
|
168
|
+
this.append({ type: 'run.budget_exhausted', data: { limit, used } });
|
|
169
|
+
this.budgetNote = `Run budget exhausted (${limit}: ${used} / ${cap}). Add a task to continue or close the run.`;
|
|
170
|
+
}
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* 把 ready 任务填进空槽位。
|
|
175
|
+
*
|
|
176
|
+
* 三道门:全局槽位、lane 独占(同一现场/会话不能同时跑两个任务)、工作区租约。
|
|
177
|
+
* 另:同一执行根(只有 `inplace` 会共享根)上的写任务先按契约 scope 判一下交集,
|
|
178
|
+
* 好把「为什么在等」说得更具体(`scope_overlap` vs `workspace_lease`);
|
|
179
|
+
* 真正的互斥保证来自租约本身:inplace 对同一目录恒为独占。
|
|
180
|
+
*/
|
|
181
|
+
dispatchReady() {
|
|
182
|
+
const run = this.store.current;
|
|
183
|
+
const limit = run.policy?.maxConcurrentWorkers ?? 6;
|
|
184
|
+
const perWorkspace = run.policy?.maxConcurrentPerWorkspace ?? 6;
|
|
185
|
+
for (const task of Object.values(run.tasks)) {
|
|
186
|
+
if (this.inFlight.size >= limit)
|
|
187
|
+
break;
|
|
188
|
+
if (task.status !== 'ready' || this.inFlight.has(task.id))
|
|
189
|
+
continue;
|
|
190
|
+
const busyLane = [...this.inFlight.keys()].find((id) => run.tasks[id]?.lane === task.lane);
|
|
191
|
+
if (busyLane) {
|
|
192
|
+
this.deferTask(task.id, 'lane_busy', busyLane);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const conflict = this.conflictWith(task.id, run);
|
|
196
|
+
if (conflict) {
|
|
197
|
+
this.deferTask(task.id, 'scope_overlap', conflict);
|
|
198
|
+
this.serializeConflict(task.id, conflict, 'scope');
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
const lane = run.lanes[task.lane];
|
|
202
|
+
const mode = lane?.mode ?? 'worktree';
|
|
203
|
+
const lease = this.leases.tryAcquire(lane?.workspaceRoot ?? run.workspaceRoot, mode === 'inplace' ? 'inplace' : 'isolated', perWorkspace);
|
|
204
|
+
if (!lease) {
|
|
205
|
+
this.deferTask(task.id, 'workspace_lease', lane?.workspaceRoot);
|
|
206
|
+
this.serializeConflict(task.id, lane?.workspaceRoot ?? run.workspaceRoot, 'workspace');
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
this.deferred.delete(task.id);
|
|
210
|
+
const pending = this.execute(task)
|
|
211
|
+
.catch((error) => {
|
|
212
|
+
// execute 自己吞掉 Worker 异常;能到这里只剩账本写入之类的硬故障。
|
|
213
|
+
this.hooks.onEvent?.({ type: 'task.progress', data: { taskId: task.id, message: `scheduler error: ${String(error)}` } }, this.store.current);
|
|
214
|
+
})
|
|
215
|
+
.finally(() => {
|
|
216
|
+
this.inFlight.delete(task.id);
|
|
217
|
+
try {
|
|
218
|
+
lease.release();
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
// 释放失败最多留下一个过期锁文件;下次 tryAcquire 会按 PID 判活接管。
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
this.inFlight.set(task.id, pending);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/** 两个**写**任务是否可能撞在同一个执行根上;返回先占者的 taskId。 */
|
|
228
|
+
conflictWith(taskId, run) {
|
|
229
|
+
const task = run.tasks[taskId];
|
|
230
|
+
if (task.contract.changePolicy !== 'isolated_write')
|
|
231
|
+
return undefined;
|
|
232
|
+
const root = executionRoot(task, run);
|
|
233
|
+
for (const otherId of this.inFlight.keys()) {
|
|
234
|
+
const other = run.tasks[otherId];
|
|
235
|
+
if (!other || other.contract.changePolicy !== 'isolated_write')
|
|
236
|
+
continue;
|
|
237
|
+
if (executionRoot(other, run) !== root)
|
|
238
|
+
continue;
|
|
239
|
+
if (scopeOverlaps(task.contract, other.contract))
|
|
240
|
+
return otherId;
|
|
241
|
+
}
|
|
242
|
+
return undefined;
|
|
243
|
+
}
|
|
244
|
+
deferTask(taskId, reason, blockedBy) {
|
|
245
|
+
const key = `${reason}:${blockedBy ?? ''}`;
|
|
246
|
+
if (this.deferred.get(taskId) === key)
|
|
247
|
+
return;
|
|
248
|
+
this.deferred.set(taskId, key);
|
|
249
|
+
this.append({ type: 'task.deferred', data: { taskId, reason, blockedBy } });
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* 写冲突的显式审计事件:`task.deferred` 说的是「这个任务为什么没发出去」,
|
|
253
|
+
* 这条说的是「哪些写操作被串行化了、被谁挡住」——事后能直接回答「谁先占了这批文件」。
|
|
254
|
+
* 同一对 (task, blockedBy) 只记一次,避免每个轮询窗口刷屏。
|
|
255
|
+
*/
|
|
256
|
+
serializeConflict(taskId, blockedBy, overlap) {
|
|
257
|
+
const dedupe = `${taskId}\u0000${blockedBy}\u0000${overlap}`;
|
|
258
|
+
if (this.serialized.has(dedupe))
|
|
259
|
+
return;
|
|
260
|
+
this.serialized.add(dedupe);
|
|
261
|
+
this.append({ type: 'conflict.serialized', data: { taskId, blockedBy, overlap } });
|
|
262
|
+
}
|
|
263
|
+
/** 把一次收工判定写进账本(CLI `review` 用)。只是建议,不改变 Run 状态。 */
|
|
264
|
+
recordReview(review) {
|
|
265
|
+
if (TERMINAL_RUNS.has(this.store.current.status)) {
|
|
266
|
+
throw new Error(`Run ${this.store.current.id} is ${this.store.current.status}; reviews can no longer be recorded.`);
|
|
267
|
+
}
|
|
268
|
+
this.append({ type: 'run.reviewed', data: { review } });
|
|
269
|
+
}
|
|
270
|
+
/** 还有可执行或被重试的任务(即使 Run 处于 idle,也能被唤醒回到 running)。 */
|
|
271
|
+
hasRunnableWork() {
|
|
272
|
+
const run = this.store.current;
|
|
273
|
+
if (Object.values(run.tasks).some((task) => ACTIVE.has(task.status)))
|
|
274
|
+
return true;
|
|
275
|
+
return readyCandidates(run).length > 0;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* 所有任务完成时的收尾:autoClose 直接结束 Run;否则进入 idle,等下一轮 dispatch。
|
|
279
|
+
* lane 与 session 都保留 —— 这是「跑完不关门、随时接着派」的核心。
|
|
280
|
+
*/
|
|
281
|
+
async finishCompleted() {
|
|
282
|
+
if (this.store.current.autoClose !== false) {
|
|
283
|
+
await this.closeLanes('run completed');
|
|
284
|
+
this.append({ type: 'run.completed', data: {} });
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
await this.reviewIfNeeded();
|
|
288
|
+
this.append({ type: 'run.idle', data: { reason: 'queue_drained' } });
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* idle 前的收工判定:只是建议,不改变 Run 状态。
|
|
292
|
+
* 判定失败或关闭都不阻塞进 idle —— 调度不能被一个模型调用卡住。
|
|
293
|
+
*/
|
|
294
|
+
async reviewIfNeeded() {
|
|
295
|
+
const run = this.store.current;
|
|
296
|
+
if (run.policy?.reviewOnIdle === false)
|
|
297
|
+
return;
|
|
298
|
+
if (!needsReview(run))
|
|
299
|
+
return;
|
|
300
|
+
let review;
|
|
301
|
+
try {
|
|
302
|
+
review = await this.review(run);
|
|
303
|
+
}
|
|
304
|
+
catch (error) {
|
|
305
|
+
review = {
|
|
306
|
+
verdict: 'unknown',
|
|
307
|
+
rationale: '',
|
|
308
|
+
remaining: [],
|
|
309
|
+
createdAt: new Date().toISOString(),
|
|
310
|
+
error: error instanceof Error ? error.message : String(error),
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
this.append({ type: 'run.reviewed', data: { review } });
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* 显式关闭一条 lane(CLI `close`):导出累计 diff、归档会话,并按 keepWorktree 决定是否删现场。
|
|
317
|
+
* 若此时所有任务已完成、所有 lane 已关闭,Run 随之收尾。
|
|
318
|
+
*/
|
|
319
|
+
async closeLaneById(laneId, reason) {
|
|
320
|
+
const lane = this.store.current.lanes[laneId];
|
|
321
|
+
if (!lane)
|
|
322
|
+
throw new Error(`Unknown lane: ${laneId}`);
|
|
323
|
+
if (!lane.closed)
|
|
324
|
+
await this.closeLane(lane, reason);
|
|
325
|
+
await this.finalizeIfDone();
|
|
326
|
+
return this.store.current;
|
|
327
|
+
}
|
|
328
|
+
/** idle / awaiting_user 状态下把新增任务唤醒:append task.added + run.resumed 后交给 run()。 */
|
|
329
|
+
appendTask(task, options = {}) {
|
|
330
|
+
const run = this.store.current;
|
|
331
|
+
if (run.status !== 'idle' && run.status !== 'awaiting_user') {
|
|
332
|
+
throw new Error(`Run ${run.id} is ${run.status}; tasks can only be added while idle or awaiting the user.`);
|
|
333
|
+
}
|
|
334
|
+
const lane = run.lanes[task.lane?.trim() || task.id];
|
|
335
|
+
if (lane?.closed) {
|
|
336
|
+
if (!options.reopenLane) {
|
|
337
|
+
throw new Error(`Lane ${lane.id} is closed; pass --reuse to reopen it (only the conversation history survives).`);
|
|
338
|
+
}
|
|
339
|
+
this.append({ type: 'lane.reopened', data: { laneId: lane.id } });
|
|
340
|
+
}
|
|
341
|
+
this.append({ type: 'task.added', data: { task } });
|
|
342
|
+
this.append({ type: 'run.resumed', data: { reason: 'task_added' } });
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* 把「人按下了继续」写进账本:idle / awaiting_user 都回到 running。
|
|
346
|
+
* 幂等:running 或终态直接忽略,CLI 可以无条件调。
|
|
347
|
+
*/
|
|
348
|
+
resume(reason = 'Operator resumed the run.') {
|
|
349
|
+
const run = this.store.current;
|
|
350
|
+
if (run.status === 'running' || TERMINAL_RUNS.has(run.status))
|
|
351
|
+
return;
|
|
352
|
+
this.append({ type: 'run.resumed', data: { reason } });
|
|
353
|
+
}
|
|
354
|
+
async finalizeIfDone() {
|
|
355
|
+
const run = this.store.current;
|
|
356
|
+
if (TERMINAL_RUNS.has(run.status))
|
|
357
|
+
return;
|
|
358
|
+
const allTasksDone = Object.values(run.tasks).every((task) => task.status === 'completed');
|
|
359
|
+
const allLanesClosed = Object.values(run.lanes).every((lane) => lane.closed || !lane.worktreePath);
|
|
360
|
+
if (!allTasksDone || !allLanesClosed)
|
|
361
|
+
return;
|
|
362
|
+
if (run.status === 'running')
|
|
363
|
+
return;
|
|
364
|
+
this.append({ type: 'run.completed', data: { reason: 'All lanes closed by the operator.' } });
|
|
365
|
+
}
|
|
366
|
+
recoverInFlightTasks() {
|
|
367
|
+
for (const task of Object.values(this.store.current.tasks)) {
|
|
368
|
+
if (!ACTIVE.has(task.status))
|
|
369
|
+
continue;
|
|
370
|
+
this.append({
|
|
371
|
+
type: 'task.interrupted',
|
|
372
|
+
data: {
|
|
373
|
+
taskId: task.id,
|
|
374
|
+
error: 'Controller restarted while the worker was in flight.',
|
|
375
|
+
sessionId: task.sessionId,
|
|
376
|
+
},
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
promoteReadyTasks() {
|
|
381
|
+
for (const task of readyCandidates(this.store.current)) {
|
|
382
|
+
this.append({
|
|
383
|
+
type: 'task.ready',
|
|
384
|
+
data: {
|
|
385
|
+
taskId: task.id,
|
|
386
|
+
reason: task.status === 'interrupted' ? 'recovery' : task.status === 'failed' ? 'retry' : 'dependencies_satisfied',
|
|
387
|
+
},
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
async execute(taskSnapshot) {
|
|
392
|
+
const attempt = taskSnapshot.attempts + 1;
|
|
393
|
+
const workerId = `worker-${randomUUID().slice(0, 8)}`;
|
|
394
|
+
this.append({ type: 'task.dispatching', data: { taskId: taskSnapshot.id, attempt, workerId } });
|
|
395
|
+
let result;
|
|
396
|
+
const pending = this.worker.run({
|
|
397
|
+
run: this.store.current,
|
|
398
|
+
task: this.store.current.tasks[taskSnapshot.id],
|
|
399
|
+
attempt,
|
|
400
|
+
workerId,
|
|
401
|
+
lane: this.laneRequest(taskSnapshot.lane),
|
|
402
|
+
}, (progress) => this.recordProgress(taskSnapshot.id, progress));
|
|
403
|
+
try {
|
|
404
|
+
result = await this.waitForWorkerOrCancellation(pending);
|
|
405
|
+
}
|
|
406
|
+
catch (error) {
|
|
407
|
+
result = {
|
|
408
|
+
outcome: 'interrupted',
|
|
409
|
+
summary: '',
|
|
410
|
+
changedFiles: [],
|
|
411
|
+
error: error instanceof Error ? error.message : String(error),
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
this.appendLaneCheckpoint(result);
|
|
415
|
+
const current = this.store.current.tasks[taskSnapshot.id];
|
|
416
|
+
if (result.outcome === 'completed') {
|
|
417
|
+
const violation = completionViolation(current, result);
|
|
418
|
+
if (violation)
|
|
419
|
+
result = { ...result, outcome: 'failed', error: violation };
|
|
420
|
+
}
|
|
421
|
+
if (result.outcome === 'cancelled') {
|
|
422
|
+
this.append({ type: 'task.cancelled', data: { taskId: taskSnapshot.id, reason: result.error ?? 'Cancelled.' } });
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
const taskHandoff = handoff({ ...current, attempts: attempt }, result);
|
|
426
|
+
const handoffPath = this.store.artifactPath(taskSnapshot.id, `attempt-${attempt}-handoff.json`);
|
|
427
|
+
taskHandoff.artifacts.unshift(handoffPath);
|
|
428
|
+
fs.writeFileSync(handoffPath, `${JSON.stringify(taskHandoff, null, 2)}\n`, 'utf8');
|
|
429
|
+
if (result.outcome === 'completed') {
|
|
430
|
+
this.append({
|
|
431
|
+
type: 'task.completed',
|
|
432
|
+
data: {
|
|
433
|
+
taskId: taskSnapshot.id,
|
|
434
|
+
handoff: taskHandoff,
|
|
435
|
+
sessionId: result.sessionId,
|
|
436
|
+
workspacePath: result.workspacePath,
|
|
437
|
+
patchPath: result.patchPath,
|
|
438
|
+
sessionArchivePath: result.sessionArchivePath,
|
|
439
|
+
},
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
else {
|
|
443
|
+
const type = result.outcome === 'interrupted' ? 'task.interrupted' : 'task.failed';
|
|
444
|
+
this.append({
|
|
445
|
+
type,
|
|
446
|
+
data: {
|
|
447
|
+
taskId: taskSnapshot.id,
|
|
448
|
+
error: result.error ?? (result.summary || 'Worker failed.'),
|
|
449
|
+
handoff: taskHandoff,
|
|
450
|
+
sessionId: result.sessionId,
|
|
451
|
+
workspacePath: result.workspacePath,
|
|
452
|
+
patchPath: result.patchPath,
|
|
453
|
+
sessionArchivePath: result.sessionArchivePath,
|
|
454
|
+
},
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
/** lane 现场快照:有 worktree/session 时 Worker 会复用,否则新建。 */
|
|
459
|
+
laneRequest(laneId) {
|
|
460
|
+
const lane = this.store.current.lanes[laneId];
|
|
461
|
+
if (!lane)
|
|
462
|
+
return undefined;
|
|
463
|
+
return {
|
|
464
|
+
id: lane.id,
|
|
465
|
+
workspaceRoot: lane.workspaceRoot,
|
|
466
|
+
mode: lane.mode ?? 'worktree',
|
|
467
|
+
worktreePath: lane.worktreePath,
|
|
468
|
+
baseTree: lane.baseTree,
|
|
469
|
+
baselineTree: lane.baselineTree,
|
|
470
|
+
baselineIndex: lane.baselineIndex,
|
|
471
|
+
sessionId: lane.sessionId,
|
|
472
|
+
keepWorktree: lane.keepWorktree,
|
|
473
|
+
allowInplace: lane.allowInplace,
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
recordProgress(taskId, progress) {
|
|
477
|
+
const task = this.store.current.tasks[taskId];
|
|
478
|
+
if (!task)
|
|
479
|
+
return;
|
|
480
|
+
const lane = this.store.current.lanes[task.lane];
|
|
481
|
+
if (progress.approval?.state === 'requested') {
|
|
482
|
+
// 先把「它在问什么」落账,再记 progress:控制面读状态时能看到完整的审批对象。
|
|
483
|
+
this.append({
|
|
484
|
+
type: 'task.approval_requested',
|
|
485
|
+
data: {
|
|
486
|
+
taskId,
|
|
487
|
+
approval: {
|
|
488
|
+
id: progress.approval.id,
|
|
489
|
+
taskId,
|
|
490
|
+
kind: progress.approval.kind,
|
|
491
|
+
title: progress.approval.title,
|
|
492
|
+
detail: progress.approval.detail,
|
|
493
|
+
options: progress.approval.options,
|
|
494
|
+
requestedAt: new Date().toISOString(),
|
|
495
|
+
},
|
|
496
|
+
},
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
else if (progress.approval?.state === 'resolved') {
|
|
500
|
+
const pending = this.store.current.tasks[taskId]?.approvals?.[progress.approval.id];
|
|
501
|
+
// 超时兜底与正常回答都会走到这里;只有账本里确实还挂着这条时才落 resolved,
|
|
502
|
+
// 否则(例如新 attempt 已清空审批表)重复落账会被 reducer 拒绝。
|
|
503
|
+
if (pending && !pending.resolved) {
|
|
504
|
+
this.append({
|
|
505
|
+
type: 'task.approval_resolved',
|
|
506
|
+
data: { taskId, approvalId: progress.approval.id, resolution: progress.approval.resolution },
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
if (lane && progress.lane?.opened && progress.workspacePath && !lane.worktreePath) {
|
|
511
|
+
this.append({
|
|
512
|
+
type: 'lane.opened',
|
|
513
|
+
data: {
|
|
514
|
+
laneId: lane.id,
|
|
515
|
+
worktreePath: progress.workspacePath,
|
|
516
|
+
baseTree: progress.lane.baseTree,
|
|
517
|
+
baseIndex: progress.lane.baseIndex,
|
|
518
|
+
},
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
if (lane && progress.sessionId && lane.sessionId !== progress.sessionId) {
|
|
522
|
+
this.append({ type: 'lane.session', data: { laneId: lane.id, sessionId: progress.sessionId } });
|
|
523
|
+
}
|
|
524
|
+
if (task.status === 'dispatching' && progress.started) {
|
|
525
|
+
this.append({
|
|
526
|
+
type: 'task.started',
|
|
527
|
+
data: {
|
|
528
|
+
taskId: task.id,
|
|
529
|
+
sessionId: progress.sessionId,
|
|
530
|
+
workspacePath: progress.workspacePath ?? task.workspacePath,
|
|
531
|
+
},
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
if (['dispatching', 'running'].includes(this.store.current.tasks[taskId].status)) {
|
|
535
|
+
this.append({
|
|
536
|
+
type: 'task.progress',
|
|
537
|
+
data: { taskId, message: progress.message, sessionId: progress.sessionId },
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
/** 账本里还挂着等待回答的人工介入(跨任务平铺)。 */
|
|
542
|
+
pendingApprovals() {
|
|
543
|
+
const result = [];
|
|
544
|
+
for (const task of Object.values(this.store.current.tasks)) {
|
|
545
|
+
for (const approval of Object.values(task.approvals ?? {})) {
|
|
546
|
+
if (!approval.resolved)
|
|
547
|
+
result.push({ taskId: task.id, approval });
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return result;
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* 把操作者的回答转给正在等它的 Worker。
|
|
554
|
+
*
|
|
555
|
+
* 返回 false 的三种情形都意味着「这条请求已经不可能得到回答」:账本里没有、
|
|
556
|
+
* 已经 resolved、或者执行器手里已经没有这个 id(超时/进程已退)。调用方必须如实报告,
|
|
557
|
+
* 不能假装成功——用户会以为按钮生效了。
|
|
558
|
+
*/
|
|
559
|
+
respondApproval(approvalId, resolution) {
|
|
560
|
+
const owner = this.pendingApprovals().find((item) => item.approval.id === approvalId);
|
|
561
|
+
if (!owner)
|
|
562
|
+
return false;
|
|
563
|
+
if (!this.worker.respondApproval)
|
|
564
|
+
return false;
|
|
565
|
+
return this.worker.respondApproval(approvalId, resolution);
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Run 结束前收尾所有打开过的 lane:导出整条 lane 的累计 patch、归档最终会话、按需删除 worktree。
|
|
569
|
+
* 已关闭或从未打开过的 lane 跳过;收尾失败不阻塞 Run 终态,只降级为一条风险事件。
|
|
570
|
+
*/
|
|
571
|
+
async closeLanes(reason) {
|
|
572
|
+
// P1 之前创建的 Run 没有 lanes 字段,恢复时按「无 lane」处理。
|
|
573
|
+
for (const lane of Object.values(this.store.current.lanes ?? {})) {
|
|
574
|
+
if (!lane.worktreePath || lane.closed)
|
|
575
|
+
continue;
|
|
576
|
+
await this.closeLane(lane, reason);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
async closeLane(lane, reason) {
|
|
580
|
+
let closed = { kept: lane.keepWorktree };
|
|
581
|
+
if (this.worker.closeLane) {
|
|
582
|
+
try {
|
|
583
|
+
closed = await this.worker.closeLane({ run: this.store.current, lane, reason });
|
|
584
|
+
}
|
|
585
|
+
catch (failure) {
|
|
586
|
+
closed = {
|
|
587
|
+
kept: true,
|
|
588
|
+
error: `Lane cleanup failed: ${failure instanceof Error ? failure.message : String(failure)}`,
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
// 收尾错误只能落在 lane.closed 里:此刻任务都已终态,task.progress 会被状态机拒绝。
|
|
593
|
+
this.append({
|
|
594
|
+
type: 'lane.closed',
|
|
595
|
+
data: {
|
|
596
|
+
laneId: lane.id,
|
|
597
|
+
reason,
|
|
598
|
+
patchPath: closed.patchPath,
|
|
599
|
+
sessionArchivePath: closed.sessionArchivePath,
|
|
600
|
+
kept: closed.kept,
|
|
601
|
+
error: closed.error,
|
|
602
|
+
},
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
appendLaneCheckpoint(result) {
|
|
606
|
+
const laneId = result.laneId;
|
|
607
|
+
if (!laneId)
|
|
608
|
+
return;
|
|
609
|
+
if (!result.baselineTree && !result.baselineIndex)
|
|
610
|
+
return;
|
|
611
|
+
const lane = this.store.current.lanes[laneId];
|
|
612
|
+
if (!lane?.worktreePath || lane.closed)
|
|
613
|
+
return;
|
|
614
|
+
if (lane.baselineTree === result.baselineTree && lane.baselineIndex === result.baselineIndex)
|
|
615
|
+
return;
|
|
616
|
+
this.append({
|
|
617
|
+
type: 'lane.checkpoint',
|
|
618
|
+
data: { laneId, baselineTree: result.baselineTree, baselineIndex: result.baselineIndex },
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
async waitForWorkerOrCancellation(pending) {
|
|
622
|
+
// A rejected worker promise is observed by the race below; this guard only prevents an
|
|
623
|
+
// unhandled rejection when the scheduler gives up earlier (cancel grace timeout).
|
|
624
|
+
void pending.catch(() => undefined);
|
|
625
|
+
let cancelledAt;
|
|
626
|
+
while (true) {
|
|
627
|
+
const winner = await Promise.race([
|
|
628
|
+
pending.then((value) => ({ kind: 'result', value })),
|
|
629
|
+
new Promise((resolve) => setTimeout(() => resolve({ kind: 'tick' }), this.pollMs)),
|
|
630
|
+
]);
|
|
631
|
+
if (winner.kind === 'result')
|
|
632
|
+
return winner.value;
|
|
633
|
+
this.observeCancellation();
|
|
634
|
+
if (!this.store.current.cancellationRequested)
|
|
635
|
+
continue;
|
|
636
|
+
if (!this.cancellationSent) {
|
|
637
|
+
this.cancellationSent = true;
|
|
638
|
+
cancelledAt = Date.now();
|
|
639
|
+
await this.worker.cancel('Orchestration cancellation requested.');
|
|
640
|
+
}
|
|
641
|
+
else if (cancelledAt !== undefined && Date.now() - cancelledAt >= this.cancelGraceMs) {
|
|
642
|
+
return {
|
|
643
|
+
outcome: 'cancelled',
|
|
644
|
+
summary: '',
|
|
645
|
+
changedFiles: [],
|
|
646
|
+
error: 'Worker did not stop within the cancellation grace period.',
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
observeCancellation() {
|
|
652
|
+
if (this.store.cancellationMarkerExists() && !this.store.current.cancellationRequested) {
|
|
653
|
+
this.append({ type: 'run.cancel_requested', data: { reason: 'Cancellation marker observed.' } });
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
async cancelRun() {
|
|
657
|
+
if (!this.cancellationSent) {
|
|
658
|
+
this.cancellationSent = true;
|
|
659
|
+
await this.worker.cancel('Orchestration cancelled.');
|
|
660
|
+
}
|
|
661
|
+
for (const task of Object.values(this.store.current.tasks)) {
|
|
662
|
+
if (!TERMINAL.has(task.status)) {
|
|
663
|
+
this.append({ type: 'task.cancelled', data: { taskId: task.id, reason: 'Orchestration cancelled.' } });
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
await this.closeLanes('run cancelled');
|
|
667
|
+
this.append({ type: 'run.cancelled', data: { reason: 'Cancellation requested.' } });
|
|
668
|
+
}
|
|
669
|
+
append(event) {
|
|
670
|
+
this.store.append(event);
|
|
671
|
+
this.hooks.onEvent?.(event, this.store.current);
|
|
672
|
+
}
|
|
673
|
+
}
|