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,255 @@
|
|
|
1
|
+
// Lane 的「执行现场」:git worktree / 非 git 副本 / 原地目录的打开、基线、差分与收尾。
|
|
2
|
+
//
|
|
3
|
+
// 为什么单独成模块:同一套现场语义现在有两个执行器要用——
|
|
4
|
+
// - `HostWorkerExecutor`(headless:spawn bin/mocode-agent-host.js,跑 runAgentCore);
|
|
5
|
+
// - `LaneReplExecutor`(可视:开一个真 mocode REPL 窗口,经 lane.commands/events 驱动)。
|
|
6
|
+
// 两个执行器如果各自实现一遍 patch/diff 口径,迟早会在「什么算改动」上分叉,所以现场逻辑
|
|
7
|
+
// 只此一份,执行器只负责「用谁去干活」。
|
|
8
|
+
//
|
|
9
|
+
// 这里的任何一步无法归档都必须保留现场:lane 可能是成果的唯一副本。
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { createWorktree, removeWorktree, snapshotWorktreeChanges, worktreeIsUsable, } from '../jobs/worktree.js';
|
|
14
|
+
import { createDirCopy, diffRoots, diffSnapshots, isMocodeRuntimeState, readSnapshot, snapshotDirectory, writeSnapshot, } from '../jobs/dir-snapshot.js';
|
|
15
|
+
import { validateChangedFiles } from './scope.js';
|
|
16
|
+
/**
|
|
17
|
+
* 非 git 档位的差分与复制排除项:`.mocode` 下的运行时目录(会话、编排账本、历史现场)既不该被当成
|
|
18
|
+
* 用户改动,也不该在复制时被算进体积预算。项目级 `.mocode/config` 仍然保留,副本里配置不变。
|
|
19
|
+
*/
|
|
20
|
+
export const NON_GIT_EXCLUDES = ['.mocode/sessions', '.mocode/orchestrations', '.mocode/worktrees', '.mocode/lanes'];
|
|
21
|
+
/**
|
|
22
|
+
* 改动审计的排除规则。除运行时目录外还要剔除 mocode 自己写出的状态(记忆、统计、便签):
|
|
23
|
+
* 那些不是 Worker 对用户代码的改动,否则 `read_only` 任务会被自己的运行时文件误判成「改了文件」。
|
|
24
|
+
*/
|
|
25
|
+
export const AUDIT_OPTIONS = { excludes: NON_GIT_EXCLUDES, ignore: isMocodeRuntimeState };
|
|
26
|
+
/** 默认的副本落点根:与编排账本同在 `~/.mocode` 下,但不在任何工作区内部。 */
|
|
27
|
+
export function defaultCopyRoot(env = process.env) {
|
|
28
|
+
const configured = env.MOCODE_LANE_COPY_ROOT?.trim();
|
|
29
|
+
return configured ? path.resolve(configured) : path.join(os.homedir(), '.mocode', 'lanes');
|
|
30
|
+
}
|
|
31
|
+
export function isWithin(parent, child) {
|
|
32
|
+
const rel = path.relative(path.resolve(parent), path.resolve(child));
|
|
33
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* 选一个**不在源目录内部**的副本落点。
|
|
37
|
+
*
|
|
38
|
+
* 副本绝不能落在被复制的目录里:`fs.cpSync` 会拒绝「复制到自身子目录」,
|
|
39
|
+
* 而且落进去的副本又会被下一次复制再复制一遍。默认落在 `~/.mocode/lanes`,
|
|
40
|
+
* 但工作区本身可能就是家目录,所以再退一步到系统临时目录;都落在源内才报错。
|
|
41
|
+
*/
|
|
42
|
+
export function resolveCopyTarget(source, preferredRoot, runId, laneId) {
|
|
43
|
+
for (const root of [preferredRoot, path.join(os.tmpdir(), 'mocode-lanes')]) {
|
|
44
|
+
const target = path.join(root, runId, laneId, 'copy');
|
|
45
|
+
if (!isWithin(source, target))
|
|
46
|
+
return target;
|
|
47
|
+
}
|
|
48
|
+
throw new Error(`Cannot place the isolated copy for lane ${laneId}: every candidate root is inside ${source}. ` +
|
|
49
|
+
'Set MOCODE_LANE_COPY_ROOT to a directory outside it, or run in place with --allow-inplace.');
|
|
50
|
+
}
|
|
51
|
+
export function orchestrationDir(run) {
|
|
52
|
+
return path.join(run.workspaceRoot, '.mocode', 'orchestrations', run.id);
|
|
53
|
+
}
|
|
54
|
+
/** 现场管理:打开 / 算基线 / 差分 / 写 attempt patch / 收尾归档。 */
|
|
55
|
+
export class LaneSite {
|
|
56
|
+
createIsolatedWorktree;
|
|
57
|
+
collectChanges;
|
|
58
|
+
removeIsolatedWorktree;
|
|
59
|
+
copyLimitBytes;
|
|
60
|
+
copyRoot;
|
|
61
|
+
constructor(options = {}) {
|
|
62
|
+
this.createIsolatedWorktree = options.createWorktree ?? createWorktree;
|
|
63
|
+
this.collectChanges = options.collectChanges ?? snapshotWorktreeChanges;
|
|
64
|
+
this.removeIsolatedWorktree = options.removeWorktree ?? removeWorktree;
|
|
65
|
+
this.copyLimitBytes = options.copyLimitBytes;
|
|
66
|
+
this.copyRoot = options.copyRoot ? path.resolve(options.copyRoot) : defaultCopyRoot();
|
|
67
|
+
}
|
|
68
|
+
artifact(run, laneId, ...parts) {
|
|
69
|
+
const file = path.join(orchestrationDir(run), 'artifacts', 'lanes', laneId, ...parts);
|
|
70
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
71
|
+
return file;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* 打开执行现场。git 仓库走 worktree(P1 行为),非 git 目录走副本;
|
|
75
|
+
* `inplace` 必须由用户显式授权,否则拒绝执行——原地写不是系统能替用户做的决定。
|
|
76
|
+
*/
|
|
77
|
+
openExecution(lane, request) {
|
|
78
|
+
const repoRoot = lane?.workspaceRoot ?? request.run.workspaceRoot;
|
|
79
|
+
const mode = lane?.mode ?? 'worktree';
|
|
80
|
+
if (mode === 'worktree') {
|
|
81
|
+
if (lane?.worktreePath && worktreeIsUsable(lane.worktreePath)) {
|
|
82
|
+
return { path: lane.worktreePath, repoRoot, mode, created: false };
|
|
83
|
+
}
|
|
84
|
+
const worktree = this.createIsolatedWorktree(repoRoot);
|
|
85
|
+
return { path: worktree.path, repoRoot, mode, created: true };
|
|
86
|
+
}
|
|
87
|
+
if (mode === 'inplace') {
|
|
88
|
+
if (!lane?.allowInplace) {
|
|
89
|
+
throw new Error(`Lane ${lane?.id ?? '(unknown)'} targets a non-git workspace ${repoRoot}. ` +
|
|
90
|
+
'Refusing to write in place without --allow-inplace; drop the flag to use a copy instead.');
|
|
91
|
+
}
|
|
92
|
+
return { path: repoRoot, repoRoot, mode, created: !lane.worktreePath };
|
|
93
|
+
}
|
|
94
|
+
// copy:复用已有副本,否则整目录复制一份。
|
|
95
|
+
if (lane?.worktreePath && fs.existsSync(lane.worktreePath)) {
|
|
96
|
+
return { path: lane.worktreePath, repoRoot, mode, created: false };
|
|
97
|
+
}
|
|
98
|
+
const target = resolveCopyTarget(repoRoot, this.copyRoot, request.run.id, lane?.id ?? request.task.id);
|
|
99
|
+
const created = createDirCopy(repoRoot, target, {
|
|
100
|
+
excludes: NON_GIT_EXCLUDES,
|
|
101
|
+
maxBytes: this.copyLimitBytes,
|
|
102
|
+
});
|
|
103
|
+
return { path: created, repoRoot, mode, created: true };
|
|
104
|
+
}
|
|
105
|
+
/** 新建现场时计算基线:git 用 tree 对象,非 git 用目录索引快照文件。 */
|
|
106
|
+
baseFor(site, request, lane) {
|
|
107
|
+
if (site.mode === 'worktree') {
|
|
108
|
+
const base = this.collectChanges({ path: site.path, repoRoot: site.repoRoot });
|
|
109
|
+
return { baseTree: base.tree };
|
|
110
|
+
}
|
|
111
|
+
const snapshot = snapshotDirectory(site.path, AUDIT_OPTIONS);
|
|
112
|
+
const file = writeSnapshot(this.artifact(request.run, lane?.id ?? request.task.id, 'base-index.json'), snapshot);
|
|
113
|
+
return { baseIndex: file };
|
|
114
|
+
}
|
|
115
|
+
collect(site, context) {
|
|
116
|
+
if (site.mode === 'worktree') {
|
|
117
|
+
// 审计口径与 copy 档位保持一致:mocode 自己的运行时文件不算 Worker 的改动。
|
|
118
|
+
// 少了这一层,git lane 里的 `read_only` 任务会被自己的 `.mocode/sessions/**` 判死。
|
|
119
|
+
const changes = this.collectChanges({ path: site.path, repoRoot: site.repoRoot }, context.baselineTree, AUDIT_OPTIONS);
|
|
120
|
+
return { changedFiles: changes.changedFiles, patch: changes.patch, tree: changes.tree };
|
|
121
|
+
}
|
|
122
|
+
const baselineFile = context.baselineIndex ?? this.artifact(context.run, context.laneId, 'base-index.json');
|
|
123
|
+
let baseline;
|
|
124
|
+
try {
|
|
125
|
+
baseline = readSnapshot(baselineFile);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
baseline = snapshotDirectory(site.path, AUDIT_OPTIONS);
|
|
129
|
+
}
|
|
130
|
+
const current = snapshotDirectory(site.path, AUDIT_OPTIONS);
|
|
131
|
+
const diff = diffSnapshots(baseline, current);
|
|
132
|
+
const index = writeSnapshot(this.artifact(context.run, context.laneId, `attempt-${context.attempt}-index.json`), current);
|
|
133
|
+
// 副本档位的基线内容仍在原目录里,能给出真实 unified diff;
|
|
134
|
+
// 原地写没有可用的旧内容,只报 changedFiles(lane.diff 由清单文件代替)。
|
|
135
|
+
const patch = site.mode === 'copy' && diff.changed.length > 0
|
|
136
|
+
? diffRoots(site.repoRoot, site.path, diff.changed, AUDIT_OPTIONS) || null
|
|
137
|
+
: null;
|
|
138
|
+
return { changedFiles: diff.changed, patch, index };
|
|
139
|
+
}
|
|
140
|
+
/** 把一次 attempt 的差分落成产物;没有 patch 时返回 undefined(非 git 档位只能给清单)。 */
|
|
141
|
+
writeAttemptPatch(run, taskId, attempt, changes, mode) {
|
|
142
|
+
if (!changes.patch)
|
|
143
|
+
return undefined;
|
|
144
|
+
const file = path.join(orchestrationDir(run), 'artifacts', taskId, `attempt-${attempt}.${mode === 'worktree' ? 'patch' : 'diff'}`);
|
|
145
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
146
|
+
fs.writeFileSync(file, changes.patch, 'utf8');
|
|
147
|
+
return file;
|
|
148
|
+
}
|
|
149
|
+
/** 控制面门槛:Worker 不能自宣完成却违反任务契约。 */
|
|
150
|
+
violations(contract, changedFiles) {
|
|
151
|
+
return [
|
|
152
|
+
...(contract.changePolicy === 'read_only' && changedFiles.length > 0
|
|
153
|
+
? [`Read-only worker modified files: ${changedFiles.join(', ')}`]
|
|
154
|
+
: []),
|
|
155
|
+
...validateChangedFiles(contract, changedFiles),
|
|
156
|
+
];
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* 收尾 lane:导出整条 lane 相对打开时的累计 diff、归档最终会话,再按需销毁执行现场。
|
|
160
|
+
* 任何一步无法归档都保留现场——lane 可能是唯一的成果副本。
|
|
161
|
+
*/
|
|
162
|
+
async closeLane(request) {
|
|
163
|
+
const { lane } = request;
|
|
164
|
+
const mode = lane.mode ?? 'worktree';
|
|
165
|
+
if (!lane.worktreePath)
|
|
166
|
+
return { kept: mode === 'inplace' };
|
|
167
|
+
if (mode === 'inplace') {
|
|
168
|
+
// 原地写没有可删除的现场;留下的只有 changedFiles 清单与归档会话。
|
|
169
|
+
const patchPath = this.writeInplaceManifest(request);
|
|
170
|
+
const sessionArchivePath = this.archiveSession(request, lane.worktreePath);
|
|
171
|
+
return { patchPath, sessionArchivePath, kept: true };
|
|
172
|
+
}
|
|
173
|
+
const site = { path: lane.worktreePath, repoRoot: lane.workspaceRoot, mode, created: false };
|
|
174
|
+
let patchPath;
|
|
175
|
+
let keep = lane.keepWorktree;
|
|
176
|
+
let error;
|
|
177
|
+
let sessionArchivePath;
|
|
178
|
+
const exists = mode === 'worktree' ? worktreeIsUsable(site.path) : fs.existsSync(site.path);
|
|
179
|
+
if (exists) {
|
|
180
|
+
try {
|
|
181
|
+
const changes = this.collect(site, {
|
|
182
|
+
run: request.run,
|
|
183
|
+
laneId: lane.id,
|
|
184
|
+
attempt: 'close',
|
|
185
|
+
// 收尾导出的是整条 lane 相对打开时的累计改动。
|
|
186
|
+
baselineTree: lane.baseTree,
|
|
187
|
+
baselineIndex: this.laneBaseIndex(request.run, lane.id),
|
|
188
|
+
});
|
|
189
|
+
if (changes.patch) {
|
|
190
|
+
patchPath = this.artifact(request.run, lane.id, mode === 'worktree' ? 'lane.patch' : 'lane.diff');
|
|
191
|
+
fs.writeFileSync(patchPath, changes.patch, 'utf8');
|
|
192
|
+
}
|
|
193
|
+
else if (changes.changedFiles.length > 0) {
|
|
194
|
+
patchPath = this.artifact(request.run, lane.id, 'lane.files.json');
|
|
195
|
+
fs.writeFileSync(patchPath, `${JSON.stringify({ mode, root: lane.workspaceRoot, changedFiles: changes.changedFiles }, null, 2)}\n`, 'utf8');
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch (failure) {
|
|
199
|
+
keep = true;
|
|
200
|
+
error = `Lane artifact collection failed: ${failure instanceof Error ? failure.message : String(failure)}`;
|
|
201
|
+
}
|
|
202
|
+
try {
|
|
203
|
+
sessionArchivePath = this.archiveSession(request, site.path);
|
|
204
|
+
}
|
|
205
|
+
catch (failure) {
|
|
206
|
+
keep = true;
|
|
207
|
+
error = `${error ? `${error} ` : ''}Lane session archive failed: ${failure instanceof Error ? failure.message : String(failure)}`;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (!keep) {
|
|
211
|
+
try {
|
|
212
|
+
if (mode === 'worktree')
|
|
213
|
+
this.removeIsolatedWorktree({ path: site.path, repoRoot: site.repoRoot });
|
|
214
|
+
else
|
|
215
|
+
fs.rmSync(site.path, { recursive: true, force: true });
|
|
216
|
+
}
|
|
217
|
+
catch (failure) {
|
|
218
|
+
error = `${error ? `${error} ` : ''}Execution site cleanup failed: ${failure instanceof Error ? failure.message : String(failure)}`;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return { patchPath, sessionArchivePath, kept: keep, error };
|
|
222
|
+
}
|
|
223
|
+
archiveSession(request, execPath) {
|
|
224
|
+
const { lane } = request;
|
|
225
|
+
if (!lane.sessionId)
|
|
226
|
+
return undefined;
|
|
227
|
+
const source = path.join(execPath, '.mocode', 'sessions', lane.sessionId);
|
|
228
|
+
if (!fs.existsSync(source))
|
|
229
|
+
return undefined;
|
|
230
|
+
const target = path.join(request.run.workspaceRoot, '.mocode', 'orchestrations', request.run.id, 'artifacts', 'lanes', lane.id, 'session');
|
|
231
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
232
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
233
|
+
fs.cpSync(source, target, { recursive: true });
|
|
234
|
+
return target;
|
|
235
|
+
}
|
|
236
|
+
/** 打开 lane 时落下的目录索引基线(非 git 档位);不存在时由 collect 退化处理。 */
|
|
237
|
+
laneBaseIndex(run, laneId) {
|
|
238
|
+
return this.artifact(run, laneId, 'base-index.json');
|
|
239
|
+
}
|
|
240
|
+
/** 原地写的 lane 收尾只留清单:没有基线内容就无法生成 diff,宁可说清楚也不伪造 patch。 */
|
|
241
|
+
writeInplaceManifest(request) {
|
|
242
|
+
const { lane } = request;
|
|
243
|
+
try {
|
|
244
|
+
const baseline = readSnapshot(this.laneBaseIndex(request.run, lane.id));
|
|
245
|
+
const current = snapshotDirectory(lane.workspaceRoot, AUDIT_OPTIONS);
|
|
246
|
+
const diff = diffSnapshots(baseline, current);
|
|
247
|
+
const file = this.artifact(request.run, lane.id, 'lane.files.json');
|
|
248
|
+
fs.writeFileSync(file, `${JSON.stringify({ mode: 'inplace', root: lane.workspaceRoot, changedFiles: diff.changed }, null, 2)}\n`, 'utf8');
|
|
249
|
+
return file;
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
return undefined;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// lane 档位与 Run 定义的落定(CLI `supervise start/dispatch` 与 Supervisor 对话工具共用)。
|
|
2
|
+
//
|
|
3
|
+
// 这里只做「纯判定 + 目录校验」,不碰账本也不启动调度:`resolveLaneMode` 决定一条 lane 写在哪,
|
|
4
|
+
// `prepareDefinition` 在建 Run 之前把所有 lane 的绝对路径与档位钉死。两者原本住在 cli.ts,
|
|
5
|
+
// 抽出来的原因只有一个—— Supervisor 的工具集也要用同一套规则,不能各写一份。
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { gitTopLevel } from '../jobs/worktree.js';
|
|
9
|
+
/** 该目录能否用 git worktree 隔离:必须是仓库根,而不是仓库里的子目录。 */
|
|
10
|
+
export function gitRootStatus(dir) {
|
|
11
|
+
const top = gitTopLevel(dir);
|
|
12
|
+
if (!top)
|
|
13
|
+
return 'none';
|
|
14
|
+
return path.resolve(top) === path.resolve(dir) ? 'root' : 'subdirectory';
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* 按工作区能力决定执行档位:git 仓库根 → worktree;其它 → copy(非 git 的默认选择)。
|
|
18
|
+
* `inplace` 只有在用户显式 `--allow-inplace` 时才允许,否则直接报错而不是静默降级。
|
|
19
|
+
*/
|
|
20
|
+
export function resolveLaneMode(dir, declared, allowInplace) {
|
|
21
|
+
if (!fs.existsSync(dir))
|
|
22
|
+
throw new Error(`workspace does not exist: ${dir}`);
|
|
23
|
+
const git = gitRootStatus(dir);
|
|
24
|
+
if (declared === 'inplace') {
|
|
25
|
+
if (!allowInplace) {
|
|
26
|
+
throw new Error(`${dir} would be modified in place. Pass --allow-inplace to accept that, or drop the mode to use a copy.`);
|
|
27
|
+
}
|
|
28
|
+
return 'inplace';
|
|
29
|
+
}
|
|
30
|
+
if (declared === 'copy')
|
|
31
|
+
return 'copy';
|
|
32
|
+
if (declared === 'worktree') {
|
|
33
|
+
if (git !== 'root') {
|
|
34
|
+
throw new Error(`${dir} cannot use the worktree mode (${git === 'none' ? 'not a git repository' : 'not the git repository root'}).`);
|
|
35
|
+
}
|
|
36
|
+
return 'worktree';
|
|
37
|
+
}
|
|
38
|
+
// 未声明:git 仓库根用 worktree,非 git 目录用副本。
|
|
39
|
+
// git 子目录既不能建 worktree(会放大到整仓),也不该静默只复制一个子目录,
|
|
40
|
+
// 所以要求用户显式给出仓库根或显式指定 copy。
|
|
41
|
+
if (git === 'subdirectory') {
|
|
42
|
+
throw new Error(`${dir} is inside the git repository ${gitTopLevel(dir)}; pass that repository root so the worker sees the whole tree.`);
|
|
43
|
+
}
|
|
44
|
+
return git === 'root' ? 'worktree' : 'copy';
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* 建 Run 前把所有 lane 的档位落定,并逐个校验工作区。
|
|
48
|
+
* 没有声明 lanes 时按每个任务的 lane 隐式补一条(与 state.normalizeLanes 的规则一致)。
|
|
49
|
+
*/
|
|
50
|
+
export function prepareDefinition(definition, root, allowInplace) {
|
|
51
|
+
const declared = definition.lanes ?? [];
|
|
52
|
+
const lanes = [];
|
|
53
|
+
if (declared.length > 0) {
|
|
54
|
+
const seen = new Set();
|
|
55
|
+
for (const lane of declared) {
|
|
56
|
+
const dir = path.resolve(root, lane.workspaceRoot ?? '.');
|
|
57
|
+
const key = `${lane.id}\u0000${dir}`;
|
|
58
|
+
if (seen.has(key))
|
|
59
|
+
continue;
|
|
60
|
+
seen.add(key);
|
|
61
|
+
lanes.push({ ...lane, workspaceRoot: dir, mode: resolveLaneMode(dir, lane.mode, allowInplace) });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
const dir = path.resolve(root);
|
|
66
|
+
const mode = resolveLaneMode(dir, undefined, allowInplace);
|
|
67
|
+
for (const id of new Set(definition.tasks.map((task) => task.lane?.trim() || task.id))) {
|
|
68
|
+
lanes.push({ id, workspaceRoot: dir, mode });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return { ...definition, lanes };
|
|
72
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// 工作区写租约:并发 Worker 之间「谁能同时写同一个目录」的仲裁。
|
|
2
|
+
//
|
|
3
|
+
// 进程内的 ResourceLockManager 保护不了另一个 Host 进程,所以 inplace 档位额外用
|
|
4
|
+
// `<workspace>/.mocode/lane.lock` 做跨进程互斥(与 store 的 controller.lock 同一套思路:
|
|
5
|
+
// 写 PID + token,进程已死才允许接管)。
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { randomBytes } from 'node:crypto';
|
|
9
|
+
function processIsAlive(pid) {
|
|
10
|
+
try {
|
|
11
|
+
process.kill(pid, 0);
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
return error.code === 'EPERM';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function lockPath(workspaceRoot) {
|
|
19
|
+
return path.join(workspaceRoot, '.mocode', 'lane.lock');
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* 跨进程拿原地写锁。返回 undefined 表示别的进程正在原地写。
|
|
23
|
+
* 锁文件坏掉或持锁进程已死时清掉重试一次;两次失败就如实返回冲突。
|
|
24
|
+
*/
|
|
25
|
+
function acquireInplaceFileLock(workspaceRoot) {
|
|
26
|
+
const target = lockPath(workspaceRoot);
|
|
27
|
+
const token = randomBytes(12).toString('hex');
|
|
28
|
+
const write = () => {
|
|
29
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
30
|
+
const fd = fs.openSync(target, 'wx');
|
|
31
|
+
try {
|
|
32
|
+
fs.writeFileSync(fd, `${JSON.stringify({ pid: process.pid, token, acquiredAt: new Date().toISOString() })}\n`);
|
|
33
|
+
fs.fsyncSync(fd);
|
|
34
|
+
}
|
|
35
|
+
finally {
|
|
36
|
+
fs.closeSync(fd);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
try {
|
|
40
|
+
write();
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error.code !== 'EEXIST')
|
|
44
|
+
throw error;
|
|
45
|
+
let owner = {};
|
|
46
|
+
try {
|
|
47
|
+
owner = JSON.parse(fs.readFileSync(target, 'utf8'));
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
if (typeof owner.pid !== 'number' || processIsAlive(owner.pid))
|
|
53
|
+
return undefined;
|
|
54
|
+
try {
|
|
55
|
+
fs.unlinkSync(target);
|
|
56
|
+
write();
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return () => {
|
|
63
|
+
try {
|
|
64
|
+
const owner = JSON.parse(fs.readFileSync(target, 'utf8'));
|
|
65
|
+
if (owner.token === token)
|
|
66
|
+
fs.unlinkSync(target);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// 无法证明锁属于自己时绝不删除。
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* 一次 Run 内的工作区租约表。
|
|
75
|
+
*
|
|
76
|
+
* - `isolated`(worktree / copy):同工作区允许多个,受 `maxConcurrentPerWorkspace` 约束;
|
|
77
|
+
* - `inplace`:同工作区**独占**,进程内单持有者 + 跨进程文件锁。
|
|
78
|
+
*/
|
|
79
|
+
export class WorkspaceLeaseManager {
|
|
80
|
+
held = new Map();
|
|
81
|
+
/** 尝试取租约;返回 undefined 表示当前不可取(调用方据此延后该任务)。 */
|
|
82
|
+
tryAcquire(workspaceRoot, kind, perWorkspaceLimit) {
|
|
83
|
+
const key = path.resolve(workspaceRoot).toLowerCase();
|
|
84
|
+
const current = this.held.get(key) ?? { isolated: 0, inplace: false };
|
|
85
|
+
if (current.inplace)
|
|
86
|
+
return undefined;
|
|
87
|
+
if (kind === 'inplace') {
|
|
88
|
+
if (current.isolated > 0)
|
|
89
|
+
return undefined;
|
|
90
|
+
const releaseFile = acquireInplaceFileLock(workspaceRoot);
|
|
91
|
+
if (!releaseFile)
|
|
92
|
+
return undefined;
|
|
93
|
+
this.held.set(key, { isolated: 0, inplace: true });
|
|
94
|
+
let released = false;
|
|
95
|
+
return {
|
|
96
|
+
workspaceRoot,
|
|
97
|
+
kind,
|
|
98
|
+
release: () => {
|
|
99
|
+
if (released)
|
|
100
|
+
return;
|
|
101
|
+
released = true;
|
|
102
|
+
releaseFile();
|
|
103
|
+
this.held.delete(key);
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
if (current.isolated >= perWorkspaceLimit)
|
|
108
|
+
return undefined;
|
|
109
|
+
this.held.set(key, { ...current, isolated: current.isolated + 1 });
|
|
110
|
+
let released = false;
|
|
111
|
+
return {
|
|
112
|
+
workspaceRoot,
|
|
113
|
+
kind,
|
|
114
|
+
release: () => {
|
|
115
|
+
if (released)
|
|
116
|
+
return;
|
|
117
|
+
released = true;
|
|
118
|
+
const entry = this.held.get(key);
|
|
119
|
+
if (!entry)
|
|
120
|
+
return;
|
|
121
|
+
if (entry.isolated <= 1)
|
|
122
|
+
this.held.delete(key);
|
|
123
|
+
else
|
|
124
|
+
this.held.set(key, { ...entry, isolated: entry.isolated - 1 });
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/** 当前持有的租约数量(测试与 status 用)。 */
|
|
129
|
+
get size() {
|
|
130
|
+
return this.held.size;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// Lane 级别的「现场直播」通道:worker 的执行画面写进 live.log,人的回话写进 live.inbox。
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要它:worker 的 stdout 是 supervisor 独占的 NDJSON 控制通道(审批回传、取消、心跳都在上面),
|
|
4
|
+
// 所以「让 mocode 在另一个终端里跑给人看」不能靠把 stdout 交出去——那要重写整套控制通道。
|
|
5
|
+
// 改成旁路:控制通道一个字不动,执行画面另写一份 append-only 文件,独立终端只读这个文件。
|
|
6
|
+
//
|
|
7
|
+
// 三个文件,都在 `<workspace>/.mocode/orchestrations/<run>/artifacts/lanes/<lane>/`:
|
|
8
|
+
// live.log worker → 人(NDJSON 事件流,tail 面板按字节偏移增量读)
|
|
9
|
+
// live.inbox 人 → worker(NDJSON 指令流,supervisor 轮询消费后转成 tell / 审批)
|
|
10
|
+
// live.receipts supervisor → 人(每条 inbox 指令的处理结果,tail 显示「已送达」)
|
|
11
|
+
//
|
|
12
|
+
// 为什么是文件而不是 IPC:独立终端是个独立进程,生命周期与 supervisor 无关;文件是唯一
|
|
13
|
+
// 不需要握手、不需要端口、崩了也不影响对方的通道。代价是轮询延迟(tail 100ms、supervisor 600ms),
|
|
14
|
+
// 而这个场景里人能感知的阈值远大于此。
|
|
15
|
+
//
|
|
16
|
+
// 写入缓冲:文本 delta 每 token 一条,逐条 fsync 会把 worker 拖成 I/O 瓶颈。
|
|
17
|
+
// 120ms 或 64 条触发一次 append,收尾强制 flush——人看到的是「一行一行出」,不是逐字符。
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
/**
|
|
21
|
+
* 一次尝试的三个文件路径。只算路径,不建目录(`LaneLiveLog` 建)。
|
|
22
|
+
*
|
|
23
|
+
* 按 **task 粒度** 而不是 lane 粒度:同一个 lane 可以被后续任务续用(lane/会话有状态),
|
|
24
|
+
* 而每次 attempt 都会重置 live.log——lane 粒度会让并发/连续两个 attempt 互相抹掉画面。
|
|
25
|
+
* task 粒度还正好对应「派出去一个任务 = 一个窗口」的直觉。
|
|
26
|
+
*/
|
|
27
|
+
export function laneLivePaths(workspaceRoot, runId, laneId, taskId) {
|
|
28
|
+
const dir = path.join(path.resolve(workspaceRoot), '.mocode', 'orchestrations', runId, 'artifacts', 'lanes', laneId);
|
|
29
|
+
const stem = path.join(dir, `live-${taskId}`);
|
|
30
|
+
return {
|
|
31
|
+
log: `${stem}.log`,
|
|
32
|
+
inbox: `${stem}.inbox`,
|
|
33
|
+
receipts: `${stem}.receipts`,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const FLUSH_INTERVAL_MS = 120;
|
|
37
|
+
const FLUSH_MAX_PENDING = 64;
|
|
38
|
+
/**
|
|
39
|
+
* 一条 lane 的事件流写入器。缓冲 → 定时/定量 flush → 收尾 `flush()`。
|
|
40
|
+
*
|
|
41
|
+
* 刻意不做错误处理上报:写日志失败不能中断 worker 的正常执行(那是用户的活),
|
|
42
|
+
* 内部吞掉并置 `broken`,后续写入变成 no-op。
|
|
43
|
+
*/
|
|
44
|
+
export class LaneLiveLog {
|
|
45
|
+
paths;
|
|
46
|
+
pending = [];
|
|
47
|
+
timer = null;
|
|
48
|
+
broken = false;
|
|
49
|
+
constructor(paths) {
|
|
50
|
+
this.paths = paths;
|
|
51
|
+
try {
|
|
52
|
+
fs.mkdirSync(path.dirname(paths.log), { recursive: true });
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
this.broken = true;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** 一条事件入缓冲。立即 flush 的条件:攒够 64 条(大段输出)或定时器到点。 */
|
|
59
|
+
push(event) {
|
|
60
|
+
if (this.broken)
|
|
61
|
+
return;
|
|
62
|
+
this.pending.push(`${JSON.stringify(event)}\n`);
|
|
63
|
+
if (this.pending.length >= FLUSH_MAX_PENDING) {
|
|
64
|
+
this.flush();
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (this.timer)
|
|
68
|
+
return;
|
|
69
|
+
this.timer = setTimeout(() => {
|
|
70
|
+
this.timer = null;
|
|
71
|
+
this.flush();
|
|
72
|
+
}, FLUSH_INTERVAL_MS);
|
|
73
|
+
this.timer.unref?.();
|
|
74
|
+
}
|
|
75
|
+
/** 把缓冲落到磁盘。收尾必须调一次,否则最后几句话看不到。 */
|
|
76
|
+
flush() {
|
|
77
|
+
if (this.timer) {
|
|
78
|
+
clearTimeout(this.timer);
|
|
79
|
+
this.timer = null;
|
|
80
|
+
}
|
|
81
|
+
if (this.broken || this.pending.length === 0)
|
|
82
|
+
return;
|
|
83
|
+
const payload = this.pending.join('');
|
|
84
|
+
this.pending = [];
|
|
85
|
+
try {
|
|
86
|
+
fs.appendFileSync(this.paths.log, payload, 'utf8');
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
this.broken = true;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** 清空日志并开始新的一段(每次 attempt 一个文件,避免上一轮的内容混进来)。 */
|
|
93
|
+
reset() {
|
|
94
|
+
this.pending = [];
|
|
95
|
+
try {
|
|
96
|
+
fs.mkdirSync(path.dirname(this.paths.log), { recursive: true });
|
|
97
|
+
fs.writeFileSync(this.paths.log, '', 'utf8');
|
|
98
|
+
this.broken = false;
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
this.broken = true;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** 解析一段 NDJSON 文本;坏行(写到一半就被读到)跳过,不当错误。 */
|
|
106
|
+
export function parseLiveLines(text) {
|
|
107
|
+
const out = [];
|
|
108
|
+
for (const line of text.split('\n')) {
|
|
109
|
+
const trimmed = line.trim();
|
|
110
|
+
if (!trimmed)
|
|
111
|
+
continue;
|
|
112
|
+
try {
|
|
113
|
+
out.push(JSON.parse(trimmed));
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
// 末尾半行(writer 正在追加):下一轮再读
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* 从 `offset` 开始增量读 live.log。
|
|
123
|
+
*
|
|
124
|
+
* 只推进到最后一个完整行:worker 正在追加的那半行留给下一轮,否则会把一条 JSON
|
|
125
|
+
* 劈成两条坏事件(表现为「工具行偶尔乱码」)。
|
|
126
|
+
*/
|
|
127
|
+
export function readLiveLog(file, offset = 0) {
|
|
128
|
+
let fd;
|
|
129
|
+
try {
|
|
130
|
+
fd = fs.openSync(file, 'r');
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return { events: [], offset };
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
const size = fs.fstatSync(fd).size;
|
|
137
|
+
if (size <= offset)
|
|
138
|
+
return { events: [], offset };
|
|
139
|
+
const length = size - offset;
|
|
140
|
+
const buffer = Buffer.allocUnsafe(length);
|
|
141
|
+
fs.readSync(fd, buffer, 0, length, offset);
|
|
142
|
+
const text = buffer.toString('utf8');
|
|
143
|
+
const lastNewline = text.lastIndexOf('\n');
|
|
144
|
+
if (lastNewline < 0)
|
|
145
|
+
return { events: [], offset };
|
|
146
|
+
const complete = text.slice(0, lastNewline + 1);
|
|
147
|
+
return {
|
|
148
|
+
events: parseLiveLines(complete),
|
|
149
|
+
offset: offset + Buffer.byteLength(complete, 'utf8'),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return { events: [], offset };
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
fs.closeSync(fd);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/** 往 lane 信箱写一条指令(tail 面板用)。 */
|
|
160
|
+
export function appendLiveCommand(paths, command) {
|
|
161
|
+
fs.mkdirSync(path.dirname(paths.inbox), { recursive: true });
|
|
162
|
+
fs.appendFileSync(paths.inbox, `${JSON.stringify(command)}\n`, 'utf8');
|
|
163
|
+
}
|
|
164
|
+
/** supervisor 侧:把处理结果写回给终端。 */
|
|
165
|
+
export function appendLiveReceipt(paths, receipt) {
|
|
166
|
+
try {
|
|
167
|
+
fs.mkdirSync(path.dirname(paths.receipts), { recursive: true });
|
|
168
|
+
fs.appendFileSync(paths.receipts, `${JSON.stringify(receipt)}\n`, 'utf8');
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
// 回执写不进去不影响命令本身已经生效
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* 逐行读一个文件,跳过已经消费过的行(按行数而非字节)。
|
|
176
|
+
*
|
|
177
|
+
* 信箱用行数做游标:指令行很短、频率极低(人打字),按行比按字节便宜且不怕尾部半行。
|
|
178
|
+
*/
|
|
179
|
+
export function readLinesFrom(file, consumed) {
|
|
180
|
+
let content;
|
|
181
|
+
try {
|
|
182
|
+
content = fs.readFileSync(file, 'utf8');
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return { lines: [], consumed };
|
|
186
|
+
}
|
|
187
|
+
const all = content.split('\n');
|
|
188
|
+
// split 的最后一个元素永远是「没有结尾换行的那段」:文件以 \n 结尾时它是空串,
|
|
189
|
+
// 否则是正在写入的半行。两种都不该被消费,所以统一丢掉。
|
|
190
|
+
const complete = all.slice(0, -1);
|
|
191
|
+
const pending = complete.slice(consumed);
|
|
192
|
+
return { lines: pending, consumed: consumed + pending.length };
|
|
193
|
+
}
|