mocode-ai 1.9.5 → 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.
Files changed (45) hide show
  1. package/dist/agent/index.js +27 -0
  2. package/dist/agent/model-turn.js +6 -6
  3. package/dist/agent/request-governor.js +1 -1
  4. package/dist/context/vision-window.js +24 -9
  5. package/dist/host/protocol.js +4 -1
  6. package/dist/host/stdio.js +45 -1
  7. package/dist/index.js +7 -0
  8. package/dist/jobs/dir-snapshot.js +332 -0
  9. package/dist/jobs/worktree.js +78 -20
  10. package/dist/llm/index.js +3 -0
  11. package/dist/orchestrator/board.js +332 -0
  12. package/dist/orchestrator/cli.js +628 -0
  13. package/dist/orchestrator/index.js +4 -0
  14. package/dist/orchestrator/integrate.js +344 -0
  15. package/dist/orchestrator/lane-channel.js +146 -0
  16. package/dist/orchestrator/lane-executor.js +439 -0
  17. package/dist/orchestrator/lane-repl.js +154 -0
  18. package/dist/orchestrator/lane-site.js +255 -0
  19. package/dist/orchestrator/lanes.js +72 -0
  20. package/dist/orchestrator/lease.js +132 -0
  21. package/dist/orchestrator/live-log.js +193 -0
  22. package/dist/orchestrator/repl.js +435 -0
  23. package/dist/orchestrator/review.js +135 -0
  24. package/dist/orchestrator/scheduler.js +673 -0
  25. package/dist/orchestrator/scope.js +88 -0
  26. package/dist/orchestrator/state.js +533 -0
  27. package/dist/orchestrator/store.js +221 -0
  28. package/dist/orchestrator/supervisor-prompt.js +54 -0
  29. package/dist/orchestrator/supervisor.js +798 -0
  30. package/dist/orchestrator/tail.js +508 -0
  31. package/dist/orchestrator/task-prompt.js +93 -0
  32. package/dist/orchestrator/terminal.js +269 -0
  33. package/dist/orchestrator/tools.js +392 -0
  34. package/dist/orchestrator/types.js +1 -0
  35. package/dist/orchestrator/watch-panel.js +154 -0
  36. package/dist/orchestrator/worker.js +475 -0
  37. package/dist/orchestrator/workspaces.js +191 -0
  38. package/dist/repl/commands/memory.js +1 -1
  39. package/dist/repl/runtime.js +16 -2
  40. package/dist/session/store.js +1 -1
  41. package/dist/tools/builtins/ask-human.js +27 -6
  42. package/dist/ui/handoff-block.js +91 -0
  43. package/dist/ui/layout-internal/statusbar.js +2 -1
  44. package/dist/ui/prompt-internal/editor.js +49 -0
  45. package/package.json +2 -2
@@ -0,0 +1,344 @@
1
+ // Lane 成果的集成:把各条 lane 的 patch 安全地合回它们各自的工作区。
2
+ //
3
+ // 为什么不直接 `git apply` 完事:
4
+ // - 并行 lane 之间可能改同一个文件,单条 patch 逐个 --check 都能过,合在一起却互相踩;
5
+ // - 目标工作区可能还带着用户自己的未提交改动,patch 会覆盖掉;
6
+ // - 部分成功比全都不做更糟:用户看到「一半合进去了」根本没法判断现场。
7
+ //
8
+ // 因此这里分三步,任何一步失败都不留痕迹:
9
+ // 1. 预检(precheck):解析每条 patch 的改动文件、要求每个文件在目标里干净、逐条 `git apply --check`;
10
+ // 2. 试合(dry-run,默认):把这几条 patch 依次应用到目标**在内存里的副本**上不行——
11
+ // 改为「备份被触及文件 → 真应用 → 任何一条失败就整批还原」;
12
+ // 3. 落账(commit 由用户决定):只写工作树,不提交、不切分支、不碰 index。
13
+ //
14
+ // `git apply` 本身在非 git 目录也能工作(已实测),所以非 git 的 copy lane 用同一套流程。
15
+ import fs from 'node:fs';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+ import { spawnSync } from 'node:child_process';
19
+ import { gitTopLevel } from '../jobs/worktree.js';
20
+ function gitRaw(args, cwd) {
21
+ const result = spawnSync('git', args, { cwd, encoding: 'utf8', windowsHide: true });
22
+ return { ok: result.status === 0, stdout: result.stdout ?? '', stderr: result.stderr ?? '' };
23
+ }
24
+ /** 解析 patch 触及的文件:`--numstat -z` 对二进制也给出路径,比读 diff 头稳。 */
25
+ function patchFiles(patchPath) {
26
+ const result = gitRaw(['apply', '--numstat', '-z', patchPath], path.dirname(patchPath));
27
+ if (!result.ok)
28
+ throw new Error(result.stderr.trim() || 'git apply --numstat failed');
29
+ const files = [];
30
+ for (const record of result.stdout.split('\0')) {
31
+ if (!record.trim())
32
+ continue;
33
+ // 记录形如 "12\t3\tsrc/a.ts";二进制记作 "-\t-\tb.png"。
34
+ const tab = record.lastIndexOf('\t');
35
+ files.push(record.slice(tab + 1));
36
+ }
37
+ return [...new Set(files)].sort();
38
+ }
39
+ function containsBinaryHunk(patchPath) {
40
+ const text = fs.readFileSync(patchPath, 'utf8');
41
+ return text.includes('@@ binary @@') || text.includes('GIT binary patch');
42
+ }
43
+ /** 目标工作区里这些文件是否带着未提交改动(仅 git 仓库能判断)。 */
44
+ function dirtyAmong(root, gitRoot, files) {
45
+ if (!gitRoot)
46
+ return [];
47
+ const result = gitRaw(['status', '--porcelain', '-z', '--untracked-files=all'], root);
48
+ if (!result.ok)
49
+ return [];
50
+ const dirty = new Set();
51
+ for (const record of result.stdout.split('\0')) {
52
+ if (record.length < 4)
53
+ continue;
54
+ // 形如 " M src/a.ts" / "?? new.txt" / "R old -> new"(rename 在 -z 下分两条记录)。
55
+ const target = record.slice(3).trim();
56
+ if (!target)
57
+ continue;
58
+ dirty.add(target.split(path.sep).join('/'));
59
+ }
60
+ const prefix = path.relative(gitRoot, root).split(path.sep).join('/');
61
+ const scoped = (file) => (prefix && prefix !== '.' ? `${prefix}/${file}` : file);
62
+ return files.filter((file) => dirty.has(scoped(file)));
63
+ }
64
+ function lanePatchPath(lane) {
65
+ const candidate = lane.closed?.patchPath;
66
+ if (!candidate)
67
+ return undefined;
68
+ // lane.files.json 是「无法产出内容 diff」时的清单,不是可应用的 patch。
69
+ return candidate.toLowerCase().endsWith('.json') ? undefined : candidate;
70
+ }
71
+ /**
72
+ * 汇总一次 Run 的集成计划。只读:不写工作区、不改账本,可以随便调。
73
+ * lane 必须已 close —— 开着的 lane 现场还在变,合进去的一半成果没法追。
74
+ */
75
+ export function planIntegration(run, options = {}) {
76
+ const wanted = options.lanes && options.lanes.length > 0 ? new Set(options.lanes) : undefined;
77
+ const warnings = [];
78
+ const byRoot = new Map();
79
+ for (const lane of Object.values(run.lanes ?? {})) {
80
+ if (wanted && !wanted.has(lane.id))
81
+ continue;
82
+ const root = path.resolve(lane.workspaceRoot);
83
+ const mode = lane.mode ?? 'worktree';
84
+ const base = {
85
+ laneId: lane.id,
86
+ mode,
87
+ workspaceRoot: root,
88
+ status: 'ready',
89
+ files: [],
90
+ dirtyFiles: [],
91
+ };
92
+ if (mode === 'inplace') {
93
+ byRoot.set(root, [...(byRoot.get(root) ?? []), { ...base, status: 'inplace' }]);
94
+ continue;
95
+ }
96
+ const patchPath = lanePatchPath(lane);
97
+ if (!lane.closed) {
98
+ byRoot.set(root, [...(byRoot.get(root) ?? []), { ...base, status: 'not-closed' }]);
99
+ continue;
100
+ }
101
+ if (!patchPath) {
102
+ byRoot.set(root, [...(byRoot.get(root) ?? []), { ...base, status: 'no-changes' }]);
103
+ continue;
104
+ }
105
+ if (!fs.existsSync(patchPath)) {
106
+ byRoot.set(root, [
107
+ ...(byRoot.get(root) ?? []),
108
+ { ...base, status: 'missing-patch', patchPath, error: `patch not found: ${patchPath}` },
109
+ ]);
110
+ continue;
111
+ }
112
+ let files = [];
113
+ try {
114
+ if (containsBinaryHunk(patchPath)) {
115
+ byRoot.set(root, [
116
+ ...(byRoot.get(root) ?? []),
117
+ {
118
+ ...base,
119
+ status: 'unsupported',
120
+ patchPath,
121
+ error: 'patch contains binary hunks; apply it manually with `git apply`',
122
+ },
123
+ ]);
124
+ continue;
125
+ }
126
+ files = patchFiles(patchPath);
127
+ }
128
+ catch (error) {
129
+ byRoot.set(root, [
130
+ ...(byRoot.get(root) ?? []),
131
+ { ...base, status: 'unsupported', patchPath, error: error instanceof Error ? error.message : String(error) },
132
+ ]);
133
+ continue;
134
+ }
135
+ if (files.length === 0) {
136
+ byRoot.set(root, [...(byRoot.get(root) ?? []), { ...base, status: 'no-changes', patchPath }]);
137
+ continue;
138
+ }
139
+ byRoot.set(root, [...(byRoot.get(root) ?? []), { ...base, patchPath, files }]);
140
+ }
141
+ const targets = [];
142
+ for (const [workspaceRoot, lanes] of byRoot) {
143
+ const gitRoot = gitTopLevel(workspaceRoot);
144
+ const blocked = [];
145
+ if (!fs.existsSync(workspaceRoot))
146
+ blocked.push(`workspace missing: ${workspaceRoot}`);
147
+ for (const lane of lanes) {
148
+ if (lane.status !== 'ready' || !lane.patchPath)
149
+ continue;
150
+ const dirtyFiles = dirtyAmong(workspaceRoot, gitRoot, lane.files);
151
+ lane.dirtyFiles = dirtyFiles;
152
+ if (dirtyFiles.length > 0) {
153
+ lane.status = 'conflict';
154
+ lane.error = `target has uncommitted changes in: ${dirtyFiles.join(', ')}`;
155
+ }
156
+ else {
157
+ // 预检:逐条独立 --check。跨 lane 的相互冲突由「备份 + 整体回滚」兜住,
158
+ // 因为 --check 校验的是当前工作树,看不出一条还没来得及应用的 patch 的效果。
159
+ const check = gitRaw(['apply', '--check', lane.patchPath], workspaceRoot);
160
+ if (!check.ok) {
161
+ lane.status = 'conflict';
162
+ lane.error = check.stderr.trim() || 'git apply --check failed';
163
+ }
164
+ }
165
+ if (lane.status === 'conflict' && lane.error)
166
+ blocked.push(`lane ${lane.laneId}: ${lane.error}`);
167
+ }
168
+ // 同一文件被多条 lane 改:合起来必冲突,不如提前说清楚(不是错误,可能仍有意义的部分)。
169
+ const seen = new Map();
170
+ for (const lane of lanes) {
171
+ for (const file of lane.files) {
172
+ const other = seen.get(file);
173
+ if (other) {
174
+ warnings.push(`lanes ${other} and ${lane.laneId} both touch ${file}; they will be applied in order and may conflict`);
175
+ }
176
+ else {
177
+ seen.set(file, lane.laneId);
178
+ }
179
+ }
180
+ }
181
+ targets.push({
182
+ workspaceRoot,
183
+ gitRoot,
184
+ lanes,
185
+ ready: blocked.length === 0 && lanes.some((l) => l.status === 'ready'),
186
+ blocked,
187
+ });
188
+ }
189
+ return { runId: run.id, targets, warnings };
190
+ }
191
+ /** 备份被触及文件 → 依次应用 → 任何一步失败整批还原。返回写进去的文件列表。 */
192
+ function applyGroup(root, lanes, backupRoot) {
193
+ const files = [...new Set(lanes.flatMap((lane) => lane.files))].sort();
194
+ const backups = new Map();
195
+ for (const file of files) {
196
+ const source = path.join(root, file);
197
+ if (!fs.existsSync(source)) {
198
+ backups.set(file, null);
199
+ continue;
200
+ }
201
+ const target = path.join(backupRoot, file);
202
+ fs.mkdirSync(path.dirname(target), { recursive: true });
203
+ fs.copyFileSync(source, target);
204
+ backups.set(file, target);
205
+ }
206
+ const restore = () => {
207
+ for (const [file, backup] of backups) {
208
+ const target = path.join(root, file);
209
+ try {
210
+ if (backup === null)
211
+ fs.rmSync(target, { force: true });
212
+ else {
213
+ fs.mkdirSync(path.dirname(target), { recursive: true });
214
+ fs.copyFileSync(backup, target);
215
+ }
216
+ }
217
+ catch {
218
+ // 还原失败只能留现场:错误消息里已经点明被触及的文件列表。
219
+ }
220
+ }
221
+ };
222
+ for (const lane of lanes) {
223
+ if (!lane.patchPath)
224
+ continue;
225
+ const applied = gitRaw(['apply', '--whitespace=nowarn', lane.patchPath], root);
226
+ if (!applied.ok) {
227
+ restore();
228
+ return { files, error: `lane ${lane.laneId}: ${applied.stderr.trim() || 'git apply failed'}` };
229
+ }
230
+ }
231
+ return { files };
232
+ }
233
+ /**
234
+ * 执行集成:默认只做计划(dry-run),`apply: true` 才写工作区。
235
+ * 写工作树但**不提交**:是否 commit / 开分支 / revert 仍由用户决定。
236
+ */
237
+ export function integrateRun(run, options = {}) {
238
+ const plan = planIntegration(run, options);
239
+ const results = [];
240
+ for (const target of plan.targets) {
241
+ const lanes = target.lanes.filter((lane) => lane.status === 'ready');
242
+ if (lanes.length === 0) {
243
+ results.push({ workspaceRoot: target.workspaceRoot, status: 'skipped', files: [] });
244
+ continue;
245
+ }
246
+ if (target.blocked.length > 0) {
247
+ // 一组里有一条冲突就整组不做:半组合并比不合更难收拾。
248
+ results.push({
249
+ workspaceRoot: target.workspaceRoot,
250
+ status: 'skipped',
251
+ files: [],
252
+ error: target.blocked.join('; '),
253
+ });
254
+ continue;
255
+ }
256
+ if (options.apply !== true) {
257
+ results.push({
258
+ workspaceRoot: target.workspaceRoot,
259
+ status: 'dry-run',
260
+ files: [...new Set(lanes.flatMap((lane) => lane.files))].sort(),
261
+ });
262
+ continue;
263
+ }
264
+ const backupRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'mocode-integrate-'));
265
+ try {
266
+ const outcome = applyGroup(target.workspaceRoot, lanes, backupRoot);
267
+ results.push({
268
+ workspaceRoot: target.workspaceRoot,
269
+ status: outcome.error ? 'failed' : 'applied',
270
+ files: outcome.error ? [] : outcome.files,
271
+ error: outcome.error,
272
+ });
273
+ }
274
+ finally {
275
+ fs.rmSync(backupRoot, { recursive: true, force: true });
276
+ }
277
+ }
278
+ return { plan, applied: options.apply === true, results };
279
+ }
280
+ /**
281
+ * 集成记录不写事件账本:`integrate` 几乎总在 Run 终态后执行,而终态账本是冻结的
282
+ * (reducer 会拒绝任何追加)。落在 `artifacts/integration.jsonl`,一合一行,便于事后追溯。
283
+ */
284
+ export function appendIntegrationLog(file, result) {
285
+ const record = {
286
+ at: new Date().toISOString(),
287
+ runId: result.plan.runId,
288
+ applied: result.applied,
289
+ targets: result.plan.targets.map((target) => ({
290
+ workspaceRoot: target.workspaceRoot,
291
+ lanes: target.lanes.map((lane) => ({
292
+ laneId: lane.laneId,
293
+ mode: lane.mode,
294
+ status: lane.status,
295
+ files: lane.files,
296
+ error: lane.error,
297
+ })),
298
+ })),
299
+ results: result.results,
300
+ };
301
+ fs.mkdirSync(path.dirname(file), { recursive: true });
302
+ fs.appendFileSync(file, `${JSON.stringify(record)}\n`, 'utf8');
303
+ }
304
+ const STATUS_LABEL = {
305
+ ready: '✓ ready',
306
+ 'no-changes': '· no changes',
307
+ 'not-closed': '! lane still open (close it first)',
308
+ inplace: '· written in place',
309
+ 'missing-patch': '! patch missing',
310
+ unsupported: '! not auto-appliable',
311
+ conflict: '! conflict',
312
+ };
313
+ /** 供 CLI 输出:先按工作区分组,再给一行总账(合了几个文件、有没有被挡)。 */
314
+ export function formatIntegration(result) {
315
+ const lines = [];
316
+ for (const target of result.plan.targets) {
317
+ lines.push(`workspace ${target.workspaceRoot}${target.gitRoot ? '' : ' (not a git repository)'}`);
318
+ for (const lane of target.lanes) {
319
+ lines.push(` ${STATUS_LABEL[lane.status]} lane ${lane.laneId} (${lane.mode})` +
320
+ `${lane.files.length > 0 ? ` ${lane.files.length} file(s)` : ''}` +
321
+ `${lane.error ? `\n ${lane.error}` : ''}` +
322
+ `${lane.dirtyFiles.length > 0 ? `\n dirty: ${lane.dirtyFiles.join(', ')}` : ''}`);
323
+ }
324
+ if (target.blocked.length > 0)
325
+ lines.push(` blocked: ${target.blocked.length} lane(s) need attention`);
326
+ const outcome = result.results.find((item) => item.workspaceRoot === target.workspaceRoot);
327
+ if (outcome) {
328
+ lines.push(` result: ${outcome.status}` +
329
+ `${outcome.files.length > 0 ? ` (${outcome.files.length} file(s))` : ''}` +
330
+ `${outcome.error ? `\n ${outcome.error}` : ''}`);
331
+ }
332
+ }
333
+ for (const warning of result.plan.warnings)
334
+ lines.push(`warning: ${warning}`);
335
+ if (!result.applied) {
336
+ const pending = result.results.filter((item) => item.status === 'dry-run').length;
337
+ lines.push(pending > 0
338
+ ? `dry run — nothing was written. Re-run with --apply to merge ${result.results
339
+ .filter((item) => item.status === 'dry-run')
340
+ .reduce((total, item) => total + item.files.length, 0)} file(s).`
341
+ : 'dry run — nothing to merge.');
342
+ }
343
+ return `${lines.join('\n')}\n`;
344
+ }
@@ -0,0 +1,146 @@
1
+ // Lane 与 supervisor 之间的文件通道。
2
+ //
3
+ // 为什么需要文件而不是 stdio:派出去的 worker 现在就是**一个真的 mocode REPL**(同款 TUI、同款输入框),
4
+ // 它必须独占 stdin/stdout 才能跟人交互。于是控制面与它之间只能走旁路文件:
5
+ //
6
+ // lane.commands supervisor → lane (派活 / 插话:一行一条 NDJSON 指令)
7
+ // lane.events lane → supervisor (ready / turn.started / turn.finished / exit)
8
+ //
9
+ // 与上一版 live.log 的区别:这里**不再**镜像 worker 的执行画面。画面就在那个终端里,人能直接看、
10
+ // 直接打字;控制面只关心「这一轮跑完了没有、结论是什么」。少一条正文级事件流,少一套只读面板。
11
+ //
12
+ // 为什么按 lane 而不是按 task 分文件:一个 lane 就是一个长驻的 REPL 进程(会话有状态),
13
+ // 后续任务续接同一进程,通道自然也是这条 lane 的。task 的身份通过指令/事件里的 `id` 携带。
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ /**
17
+ * 只算路径,不建目录。
18
+ *
19
+ * 放在 `<workspace>/.mocode/orchestrations/<run>/artifacts/lanes/<lane>/` 下,与 lane.patch /
20
+ * session 归档同处一地:一次 Run 的全部产物在一个目录里,事后排查不用四处找。
21
+ */
22
+ export function laneChannelPaths(workspaceRoot, runId, laneId) {
23
+ const dir = path.join(path.resolve(workspaceRoot), '.mocode', 'orchestrations', runId, 'artifacts', 'lanes', laneId);
24
+ return {
25
+ events: path.join(dir, 'lane.events'),
26
+ commands: path.join(dir, 'lane.commands'),
27
+ stop: path.join(dir, 'lane.stop'),
28
+ };
29
+ }
30
+ /** 解析一段 NDJSON;写到一半的坏行跳过(下一轮再读),不当错误。 */
31
+ export function parseJsonLines(text) {
32
+ const out = [];
33
+ for (const line of text.split('\n')) {
34
+ const trimmed = line.trim();
35
+ if (!trimmed)
36
+ continue;
37
+ try {
38
+ out.push(JSON.parse(trimmed));
39
+ }
40
+ catch {
41
+ // 尾部半行:writer 正在追加,留给下一轮
42
+ }
43
+ }
44
+ return out;
45
+ }
46
+ /**
47
+ * 逐行读一个文件,只返回 `consumed` 之后**完整**的行。
48
+ *
49
+ * 用行数而不是字节做游标:这两条通道的行都很短(指令/事件),频率也低(一次任务几行),
50
+ * 按行便宜且天然不怕尾部半行。`split('\n')` 的最后一个元素永远是没有结尾换行的那段,
51
+ * 文件以 \n 结尾时是空串、否则是正在写的半行——两种都不该被消费。
52
+ *
53
+ * `total` 是文件当前**完整行数**。调用方要拿它和游标比:通道文件会被新窗口截断
54
+ * (见 `resetLaneChannel`),那时 `total < consumed`,游标必须归零,否则会一直读到空、
55
+ * 永远看不到新内容(真实事故:ready 事件明明写了,控制面等了 30s 判窗口没起来)。
56
+ */
57
+ export function readLinesFrom(file, consumed) {
58
+ let content;
59
+ try {
60
+ content = fs.readFileSync(file, 'utf8');
61
+ }
62
+ catch {
63
+ return { lines: [], consumed, total: 0 };
64
+ }
65
+ const complete = content.split('\n').slice(0, -1);
66
+ const pending = complete.slice(consumed);
67
+ return { lines: pending, consumed: consumed + pending.length, total: complete.length };
68
+ }
69
+ /** 增量读通道文件里的结构化条目。 */
70
+ export function readChannel(file, consumed) {
71
+ const read = readLinesFrom(file, consumed);
72
+ return { items: parseJsonLines(read.lines.join('\n')), consumed: read.consumed, total: read.total };
73
+ }
74
+ function appendLine(file, value) {
75
+ fs.mkdirSync(path.dirname(file), { recursive: true });
76
+ fs.appendFileSync(file, `${JSON.stringify(value)}\n`, 'utf8');
77
+ }
78
+ /** supervisor 侧:投一条指令。 */
79
+ export function appendLaneCommand(paths, command) {
80
+ appendLine(paths.commands, command);
81
+ }
82
+ /** lane 侧:报一条事件。写失败不影响正在跑的这一轮(日志是旁路)。 */
83
+ export function appendLaneEvent(paths, event) {
84
+ try {
85
+ appendLine(paths.events, event);
86
+ }
87
+ catch {
88
+ // 通道不可写(权限/磁盘)不该让对话崩掉;下一轮事件仍会尝试。
89
+ }
90
+ }
91
+ /**
92
+ * 通道重置:新的 lane 进程接手时清掉上一轮的残留。
93
+ *
94
+ * **两条通道都要清**,理由不同:
95
+ * - `events` 是上一代窗口的日志,留着会让控制面把旧 ready / 旧 exit 当成这一代的;
96
+ * - `commands` 更要清——它是只追加的,而新窗口的读游标从 0 开始,于是**已经执行过的
97
+ * 旧指令会被当成待办重放一遍**。真实事故:一个新窗口起来后重跑了一条 20 小时前的
98
+ * 任务,人在窗口里看到的任务和刚派的那条完全不是一个。
99
+ *
100
+ * 清 `commands` 之所以安全:控制面只在**确认 ready 之后**才投指令
101
+ * (`lane-executor.ts` 的 `appendLaneCommand` 在 `ensureWindow` 之后)。窗口启动这一刻
102
+ * 文件里剩下的必然是上一代窗口的遗留,不存在「投了但还没被执行」的指令——那种情况
103
+ * 控制面正等着 `turn.finished`,窗口死了那一次 attempt 直接判 failed、下一次换新 id 重派。
104
+ */
105
+ export function resetLaneChannel(paths) {
106
+ for (const file of [paths.events, paths.commands]) {
107
+ try {
108
+ fs.mkdirSync(path.dirname(file), { recursive: true });
109
+ fs.writeFileSync(file, '', 'utf8');
110
+ }
111
+ catch {
112
+ // 写不进去不影响主流程:最坏结果是重放,不是崩掉。
113
+ }
114
+ }
115
+ // 上一次窗口留下的关闭请求必须清掉,否则新窗口一起来就会立刻自尽。
116
+ clearLaneStop(paths);
117
+ }
118
+ /** supervisor 侧:请求 lane 优雅关窗(走 REPL 自己的退出路径,能正确复原终端)。 */
119
+ export function requestLaneStop(paths, reason = 'stop requested') {
120
+ try {
121
+ fs.mkdirSync(path.dirname(paths.stop), { recursive: true });
122
+ fs.writeFileSync(paths.stop, JSON.stringify({ t: Date.now(), reason }), 'utf8');
123
+ }
124
+ catch {
125
+ // 写不进去就让调用方退到硬杀
126
+ }
127
+ }
128
+ /** lane 侧:有没有人请求关窗。 */
129
+ export function laneStopRequested(paths) {
130
+ try {
131
+ fs.accessSync(paths.stop);
132
+ return true;
133
+ }
134
+ catch {
135
+ return false;
136
+ }
137
+ }
138
+ /** 清掉关闭请求(开新窗口前 / 窗口已退出后)。 */
139
+ export function clearLaneStop(paths) {
140
+ try {
141
+ fs.rmSync(paths.stop, { force: true });
142
+ }
143
+ catch {
144
+ // 忽略
145
+ }
146
+ }