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.
Files changed (44) 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/orchestrator/board.js +332 -0
  11. package/dist/orchestrator/cli.js +628 -0
  12. package/dist/orchestrator/index.js +4 -0
  13. package/dist/orchestrator/integrate.js +344 -0
  14. package/dist/orchestrator/lane-channel.js +146 -0
  15. package/dist/orchestrator/lane-executor.js +439 -0
  16. package/dist/orchestrator/lane-repl.js +154 -0
  17. package/dist/orchestrator/lane-site.js +255 -0
  18. package/dist/orchestrator/lanes.js +72 -0
  19. package/dist/orchestrator/lease.js +132 -0
  20. package/dist/orchestrator/live-log.js +193 -0
  21. package/dist/orchestrator/repl.js +435 -0
  22. package/dist/orchestrator/review.js +135 -0
  23. package/dist/orchestrator/scheduler.js +673 -0
  24. package/dist/orchestrator/scope.js +88 -0
  25. package/dist/orchestrator/state.js +533 -0
  26. package/dist/orchestrator/store.js +221 -0
  27. package/dist/orchestrator/supervisor-prompt.js +54 -0
  28. package/dist/orchestrator/supervisor.js +798 -0
  29. package/dist/orchestrator/tail.js +508 -0
  30. package/dist/orchestrator/task-prompt.js +93 -0
  31. package/dist/orchestrator/terminal.js +269 -0
  32. package/dist/orchestrator/tools.js +392 -0
  33. package/dist/orchestrator/types.js +1 -0
  34. package/dist/orchestrator/watch-panel.js +154 -0
  35. package/dist/orchestrator/worker.js +475 -0
  36. package/dist/orchestrator/workspaces.js +191 -0
  37. package/dist/repl/commands/memory.js +1 -1
  38. package/dist/repl/runtime.js +16 -2
  39. package/dist/session/store.js +1 -1
  40. package/dist/tools/builtins/ask-human.js +27 -6
  41. package/dist/ui/handoff-block.js +91 -0
  42. package/dist/ui/layout-internal/statusbar.js +2 -1
  43. package/dist/ui/prompt-internal/editor.js +49 -0
  44. package/package.json +2 -2
@@ -7,9 +7,13 @@ import { spawnSync } from 'node:child_process';
7
7
  import { mkdirSync, rmdirSync, existsSync, symlinkSync } from 'node:fs';
8
8
  import { join, resolve } from 'node:path';
9
9
  import { randomBytes } from 'node:crypto';
10
- function git(args, cwd) {
10
+ function gitRaw(args, cwd) {
11
11
  const r = spawnSync('git', args, { cwd, encoding: 'utf8', windowsHide: true });
12
- return { ok: r.status === 0, output: `${r.stdout ?? ''}${r.stderr ?? ''}`.trim() };
12
+ return { ok: r.status === 0, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };
13
+ }
14
+ function git(args, cwd) {
15
+ const result = gitRaw(args, cwd);
16
+ return { ok: result.ok, output: `${result.stdout}${result.stderr}`.trim() };
13
17
  }
14
18
  /** 当前 git 仓库根;不是 git 仓库时返回 null。 */
15
19
  export function gitTopLevel(cwd = process.cwd()) {
@@ -20,10 +24,10 @@ export function gitTopLevel(cwd = process.cwd()) {
20
24
  * 创建 detached worktree(基于 HEAD)。
21
25
  * 失败(非 git 仓库 / 有未跟踪冲突)抛错,由调用方决定是否回退普通模式。
22
26
  */
23
- export function createWorktree() {
24
- const repoRoot = gitTopLevel();
27
+ export function createWorktree(cwd = process.cwd()) {
28
+ const repoRoot = gitTopLevel(cwd);
25
29
  if (!repoRoot)
26
- throw new Error('not a git repository (worktree isolation requires git)');
30
+ throw new Error(`not a git repository: ${cwd} (worktree isolation requires git)`);
27
31
  const id = `${Date.now()}-${randomBytes(2).toString('hex')}`;
28
32
  const wtPath = join(repoRoot, '.mocode', 'worktrees', `wt-${id}`);
29
33
  mkdirSync(join(repoRoot, '.mocode', 'worktrees'), { recursive: true });
@@ -44,25 +48,79 @@ export function createWorktree() {
44
48
  }
45
49
  return { path: wtPath, repoRoot };
46
50
  }
51
+ /** 主仓库是否有未提交改动:worktree 基于 HEAD,看不到它们,调用方可据此提示 Worker 视角。 */
52
+ export function gitRepositoryDirty(dir) {
53
+ const status = git(['status', '--porcelain', '--untracked-files=normal'], dir);
54
+ return status.ok && status.output.length > 0;
55
+ }
56
+ const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
57
+ function headTree(wt) {
58
+ const head = git(['rev-parse', 'HEAD^{tree}'], wt.path);
59
+ // 空仓库没有 HEAD:以空 tree 为基线,未跟踪文件即全部改动。
60
+ return head.ok && head.output ? head.output : EMPTY_TREE;
61
+ }
47
62
  /**
48
- * 把 worktree 相对 HEAD 的全部改动导出为 unified diff(含未跟踪文件,binary 标记为
49
- * Binary files differ)。无改动返回 null(调用方不写空 patch 文件)。
50
- *
51
- * 用 spawnSync 而非异步 spawn:本函数只在 headless/runner 的收尾路径调用(事件循环
52
- * 已无流式渲染在跑),且 removeWorktree 本身就是同步链,拆异步收益为零。
63
+ * 把 worktree 当前内容写成 tree 对象(只写 index,不提交),再相对 baselineTree 计算改动。
64
+ * 共享 worktree 的 lane 靠它把「本次 attempt 的产出」与之前 attempt 的成果区分开;
65
+ * baselineTree 省略时以 HEAD 为基线。
66
+ */
67
+ export function snapshotWorktreeChanges(wt, baselineTree, options = {}) {
68
+ // add -A 让修改、删除、未跟踪文件都进入 index,write-tree 才能给出完整内容。
69
+ const added = git(['add', '-A', '--', '.'], wt.path);
70
+ if (!added.ok)
71
+ throw new Error(`git add -A failed: ${added.output}`);
72
+ const written = git(['write-tree'], wt.path);
73
+ if (!written.ok || !written.output)
74
+ throw new Error(`git write-tree failed: ${written.output}`);
75
+ const tree = written.output;
76
+ const baseline = baselineTree ?? headTree(wt);
77
+ if (baseline === tree)
78
+ return { changedFiles: [], patch: null, tree };
79
+ const names = gitRaw(['diff', '--name-only', '-z', baseline, tree, '--'], wt.path);
80
+ if (!names.ok)
81
+ throw new Error(`git diff --name-only failed: ${names.stderr.trim()}`);
82
+ const all = [...new Set(names.stdout.split('\0').filter(Boolean))].sort();
83
+ // mocode 自己写出的会话/记忆/统计/便签不是 Worker 对用户代码的改动。不过滤的话,
84
+ // `read_only` 任务会被自己的运行时文件判成「改了文件」而整条失败——真实事故:git lane 里
85
+ // 三个只读调研任务连续失败,报的改动全是 `.mocode/sessions/**`。注意 worktree 基于 HEAD,
86
+ // 若仓库的 `.gitignore` 只在未提交的改动里加了 `.mocode/`,这些文件在 worktree 里既不被
87
+ // 跟踪也不被忽略,`add -A` 必然把它们收进来,所以这一层必须在代码里过滤。
88
+ const ignore = options.ignore;
89
+ const changedFiles = ignore ? all.filter((rel) => !ignore(rel)) : all;
90
+ if (changedFiles.length === 0)
91
+ return { changedFiles: [], patch: null, tree };
92
+ // 剔除过文件时 patch 也要限在这组路径上,否则 `.mocode` 的 diff 会跟着 lane.patch 导出。
93
+ const diff = ignore && changedFiles.length !== all.length
94
+ ? gitRaw(['diff', '--binary', baseline, tree, '--', ...changedFiles.map((rel) => `:(literal)${rel}`)], wt.path)
95
+ : gitRaw(['diff', '--binary', baseline, tree, '--'], wt.path);
96
+ if (!diff.ok)
97
+ throw new Error(`git diff failed: ${diff.stderr.trim()}`);
98
+ if (!diff.stdout)
99
+ throw new Error('git reported changes but produced an empty patch.');
100
+ return { changedFiles, patch: diff.stdout.endsWith('\n') ? diff.stdout : `${diff.stdout}\n`, tree };
101
+ }
102
+ /**
103
+ * 严格收集 worktree 相对 HEAD 的文件列表与 unified diff。无改动不是错误;Git 命令失败会
104
+ * 抛错,供需要保证成果不丢失的编排器决定保留 worktree。
105
+ */
106
+ export function collectWorktreeChanges(wt, options = {}) {
107
+ return snapshotWorktreeChanges(wt, undefined, options);
108
+ }
109
+ /** worktree 目录是否仍然可用(被手工删掉或 prune 后不能复用)。 */
110
+ export function worktreeIsUsable(wtPath) {
111
+ return existsSync(join(wtPath, '.git'));
112
+ }
113
+ /**
114
+ * 兼容旧调用方:无改动或 Git 导出失败均返回 null。需要区分两者的新代码应使用
115
+ * collectWorktreeChanges,避免在成果未保存时销毁 worktree。
53
116
  */
54
117
  export function exportWorktreePatch(wt) {
55
- const status = git(['status', '--porcelain'], wt.path);
56
- if (!status.ok || !status.output)
57
- return null; // 无改动 / git 不可用
58
- // 未跟踪文件:先 git add -N(intent-to-add) 让 diff 能覆盖新文件,否则 --worktree
59
- // 默认跳过 untracked,新建的文件会随 worktree 一起消失。--intent-to-add 不改
60
- // index 的实际内容、不产生对象,worktree remove --force 可正常清理。
61
- git(['add', '-N', '.'], wt.path);
62
- const diff = git(['diff', 'HEAD', '--binary'], wt.path);
63
- if (!diff.ok || !diff.output)
118
+ try {
119
+ return collectWorktreeChanges(wt).patch;
120
+ }
121
+ catch {
64
122
  return null;
65
- return `${diff.output}\n`;
123
+ }
66
124
  }
67
125
  /** 先删 node_modules 链接(防误伤目标),再移除 worktree + prune。 */
68
126
  export function removeWorktree(wt) {
@@ -0,0 +1,332 @@
1
+ // 监管工作台的数据层:把「这机器上有哪些工作区 × 每个工作区里有哪些 Run/lane」
2
+ // 收成一份扁平的、可渲染的快照。
3
+ //
4
+ // 读盘策略:只在面板需要时才读,且**优先读 snapshot.json**(原子写、已归约好的完整状态),
5
+ // 不重放 events.jsonl。重放是 append-only 账本的真相源,但一次面板刷新要跑几十个 Run 时
6
+ // 重放会把每次刷新变成 O(全部事件),而面板每秒都要刷。`OrchestrationStore.load` 留给定点
7
+ // 排查(snapshot 缺失或损坏时作为回退)。
8
+ //
9
+ // 渲染拆成纯函数(`renderBoard`),面板循环只负责键位与定时器,因此配色/截断/空态都能单测。
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { ui } from '../ui/theme.js';
13
+ import { ansiDisplayWidth, truncateAnsi } from '../ui/render.js';
14
+ import { orchestrationRoot } from './store.js';
15
+ const TERMINAL = new Set(['completed', 'failed', 'cancelled']);
16
+ function laneFromRun(run, lane) {
17
+ const tasks = Object.values(run.tasks ?? {}).filter((task) => (task.lane ?? task.id) === lane.id);
18
+ const done = tasks.filter((task) => task.status === 'completed').length;
19
+ // 「当前」优先取仍在跑的;否则取最新结束的那条,让面板始终有可读的上下文。
20
+ const active = tasks.find((task) => task.status === 'running' || task.status === 'dispatching');
21
+ const latest = [...tasks].sort((a, b) => finishKey(b).localeCompare(finishKey(a)))[0];
22
+ const shown = active ?? latest;
23
+ // 待决审批与风险都扫整条 lane 的任务,而不是只看当前那条:
24
+ // 「刚跑完的那条留了个风险,下一条已经在跑」是最需要被看见的情形。
25
+ const pendingApprovals = tasks.flatMap((task) => Object.values(task.approvals ?? {})
26
+ .filter((approval) => !approval.resolved)
27
+ .map((approval) => ({ id: approval.id, kind: approval.kind, title: approval.title })));
28
+ const risks = tasks.flatMap((task) => task.output?.risks ?? []);
29
+ return {
30
+ runId: run.id,
31
+ laneId: lane.id,
32
+ mode: lane.mode ?? 'worktree',
33
+ executionRoot: lane.worktreePath,
34
+ state: lane.closed ? 'closed' : 'open',
35
+ taskId: shown?.id,
36
+ taskStatus: shown?.status,
37
+ lastEvent: shown?.lastEvent,
38
+ sessionId: lane.sessionId ?? shown?.sessionId,
39
+ awaitingReason: run.status === 'awaiting_user' ? run.awaitingReason : undefined,
40
+ done,
41
+ total: tasks.length,
42
+ closedReason: lane.closed?.reason,
43
+ error: lane.closed?.error,
44
+ pendingApprovals,
45
+ risks,
46
+ };
47
+ }
48
+ function finishKey(task) {
49
+ return task.finishedAt ?? task.startedAt ?? '';
50
+ }
51
+ /** 快路径:snapshot.json 与 events 账本同源(每次 append 后原子重写),损坏时才回退重放。 */
52
+ function readRunSnapshot(directory) {
53
+ const file = path.join(directory, 'snapshot.json');
54
+ try {
55
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
56
+ // 只做形状最低校验:真正的合法性由 events 决定,这里只防「野 JSON」把面板画崩。
57
+ if (!parsed || typeof parsed.id !== 'string' || !parsed.tasks || typeof parsed.status !== 'string') {
58
+ return undefined;
59
+ }
60
+ return parsed;
61
+ }
62
+ catch {
63
+ return undefined;
64
+ }
65
+ }
66
+ function loadRuns(root, options) {
67
+ const dir = orchestrationRoot(root);
68
+ let names;
69
+ try {
70
+ names = fs
71
+ .readdirSync(dir, { withFileTypes: true })
72
+ .filter((entry) => entry.isDirectory())
73
+ .map((entry) => entry.name);
74
+ }
75
+ catch {
76
+ return { runs: [], broken: 0 };
77
+ }
78
+ const runs = [];
79
+ let broken = 0;
80
+ for (const name of names) {
81
+ const run = readRunSnapshot(path.join(dir, name));
82
+ if (!run) {
83
+ // 没有 snapshot 只有 events 的 P1 现场:面板不当它坏盘,只是这次不显示。
84
+ if (fs.existsSync(path.join(dir, name, 'events.jsonl')))
85
+ broken++;
86
+ continue;
87
+ }
88
+ if (!options.includeTerminal && TERMINAL.has(run.status))
89
+ continue;
90
+ runs.push({
91
+ id: run.id,
92
+ status: run.status,
93
+ objective: run.objective,
94
+ createdAt: run.createdAt,
95
+ updatedAt: run.updatedAt,
96
+ awaitingReason: run.awaitingReason,
97
+ lanes: Object.values(run.lanes ?? {}).map((lane) => laneFromRun(run, lane)),
98
+ });
99
+ }
100
+ runs.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
101
+ const limit = options.maxRunsPerWorkspace ?? 3;
102
+ return { runs: runs.slice(0, limit), broken };
103
+ }
104
+ /** 汇总整机快照。只读,纯 IO,不碰账本、不抢控制器锁。 */
105
+ export function collectBoard(options) {
106
+ const workspaces = [];
107
+ let busy = 0;
108
+ let live = 0;
109
+ let broken = 0;
110
+ for (const info of options.workspaces) {
111
+ if (!info.exists && options.includeMissing !== true)
112
+ continue;
113
+ const loaded = info.exists ? loadRuns(info.root, options) : { runs: [], broken: 0 };
114
+ broken += loaded.broken;
115
+ for (const run of loaded.runs) {
116
+ // 终态 Run 的 lane 即使没显式 close 也不再"活着"——Run 已经结束了,没人会往里派活。
117
+ const runAlive = !TERMINAL.has(run.status);
118
+ live += runAlive ? run.lanes.filter((lane) => lane.state === 'open').length : 0;
119
+ busy += run.lanes.filter((lane) => lane.taskStatus === 'running' || lane.taskStatus === 'dispatching').length;
120
+ }
121
+ workspaces.push({
122
+ root: info.root,
123
+ name: info.name,
124
+ exists: info.exists,
125
+ git: info.git,
126
+ branch: info.branch,
127
+ dirty: info.dirty,
128
+ sessionCount: info.sessions.length,
129
+ latestSession: info.sessions[0]?.id,
130
+ runs: loaded.runs,
131
+ });
132
+ }
133
+ // 有活的排前面:工作台第一眼要看到正在动的东西,而不是按路径字母序。
134
+ const activity = (workspace) => workspace.runs.reduce((sum, run) => sum + run.lanes.filter((lane) => lane.taskStatus === 'running').length, 0);
135
+ workspaces.sort((a, b) => activity(b) - activity(a) || Number(b.exists) - Number(a.exists) || a.root.localeCompare(b.root));
136
+ return { collectedAt: new Date().toISOString(), workspaces, busy, live, broken };
137
+ }
138
+ /** 把树拍平成可上下移动的行;工作区标题行也可选中(用于看该工作区的汇总)。 */
139
+ export function boardRows(board) {
140
+ const rows = [];
141
+ for (const workspace of board.workspaces) {
142
+ rows.push({ kind: 'workspace', workspaceRoot: workspace.root });
143
+ for (const run of workspace.runs) {
144
+ for (const lane of run.lanes) {
145
+ rows.push({ kind: 'lane', workspaceRoot: workspace.root, runId: run.id, laneId: lane.laneId });
146
+ }
147
+ }
148
+ }
149
+ return rows;
150
+ }
151
+ const LANE_GLYPH = {
152
+ running: '▶',
153
+ dispatching: '▶',
154
+ completed: '✓',
155
+ failed: '!',
156
+ interrupted: '!',
157
+ cancelled: '×',
158
+ pending: '○',
159
+ ready: '○',
160
+ };
161
+ function statusColor(status) {
162
+ if (status === 'running' || status === 'dispatching')
163
+ return ui.green;
164
+ if (status === 'failed' || status === 'interrupted')
165
+ return ui.red;
166
+ if (status === 'completed')
167
+ return ui.dim;
168
+ if (status === 'awaiting_user')
169
+ return ui.yellow;
170
+ return '';
171
+ }
172
+ function fit(text, width) {
173
+ return truncateAnsi(text, Math.max(1, width));
174
+ }
175
+ /** 左侧列表 + 右侧详情;窄终端退化成只有列表(详情靠 Enter 钻取)。 */
176
+ export function renderBoard(board, options) {
177
+ const cols = Math.max(20, options.cols);
178
+ const rows = Math.max(4, options.rows);
179
+ const flat = boardRows(board);
180
+ // -1 = 不标记选中(一次性快照用);否则钳到合法范围。
181
+ const selected = flat.length === 0 || options.selected < 0 ? -1 : Math.min(options.selected, flat.length - 1);
182
+ const lines = [];
183
+ const header = `${ui.bold}${ui.accent}mocode supervise${ui.reset} ` +
184
+ `${board.busy > 0 ? `${ui.green}${board.busy} running${ui.reset}` : `${ui.dim}idle${ui.reset}`}` +
185
+ `${ui.dim} · ${board.live} open lane(s) · ${board.workspaces.length} workspace(s)` +
186
+ `${board.broken > 0 ? ` · ${board.broken} unreadable run(s)` : ''}` +
187
+ ` · ${board.collectedAt.slice(11, 19)}${ui.reset}`;
188
+ lines.push(fit(header, cols));
189
+ const bodyRows = rows - 2; // 头部 + 底部键位
190
+ // 没有选中项(一次性快照)时右栏没有内容,硬画一条竖线只是噪声,退化成单列。
191
+ const wide = cols >= 76 && bodyRows >= 6 && selected >= 0;
192
+ const leftWidth = wide ? Math.min(62, Math.floor(cols * 0.58)) : cols;
193
+ const rightWidth = wide ? cols - leftWidth - 3 : 0;
194
+ const left = [];
195
+ let rowIndex = 0;
196
+ for (const workspace of board.workspaces) {
197
+ const running = workspace.runs.reduce((sum, run) => sum + run.lanes.filter((lane) => lane.taskStatus === 'running').length, 0);
198
+ const flags = [
199
+ workspace.exists ? '' : `${ui.red}missing${ui.reset}`,
200
+ workspace.git
201
+ ? `${ui.dim}git:${workspace.branch ?? '?'}${workspace.dirty ? '*' : ''}${ui.reset}`
202
+ : `${ui.dim}no-git${ui.reset}`,
203
+ ].filter(Boolean);
204
+ const marker = rowIndex === selected ? `${ui.accent}${ui.bold}▸${ui.reset}` : ' ';
205
+ const badge = running > 0 ? ` ${ui.green}● ${running} busy${ui.reset}` : '';
206
+ left.push({
207
+ text: `${marker} ${truncateAnsi(workspace.name, 28)} ${flags.join(' ')}${badge}`,
208
+ row: rowIndex,
209
+ });
210
+ rowIndex++;
211
+ for (const run of workspace.runs) {
212
+ for (const lane of run.lanes) {
213
+ const isSel = rowIndex === selected;
214
+ const glyph = LANE_GLYPH[lane.taskStatus ?? ''] ?? (lane.state === 'closed' ? '·' : '○');
215
+ const color = statusColor(lane.taskStatus) || (lane.state === 'closed' ? ui.dim : '');
216
+ const progress = lane.total > 0 ? `${lane.done}/${lane.total}` : '';
217
+ const activity = lane.lastEvent ? ` ${ui.dim}${lane.lastEvent}${ui.reset}` : '';
218
+ // 「有人等你」必须比 awaitingReason 更优先显示:它在跑,但停下来等回答了。
219
+ const ask = lane.pendingApprovals.length > 0
220
+ ? ` ${ui.yellow}? ${lane.pendingApprovals.length} approval(s)${ui.reset}`
221
+ : '';
222
+ const wait = lane.awaitingReason ? ` ${ui.yellow}waiting: ${lane.awaitingReason}${ui.reset}` : '';
223
+ const pointer = isSel ? `${ui.accent}${ui.bold}▸${ui.reset}` : ' ';
224
+ left.push({
225
+ text: `${pointer} ${color}${glyph} ${lane.laneId}${ui.reset}` +
226
+ ` ${ui.dim}${lane.mode}${ui.reset}` +
227
+ `${progress ? ` ${ui.dim}${progress}${ui.reset}` : ''}` +
228
+ `${lane.state === 'closed' ? ` ${ui.dim}closed${ui.reset}` : ''}` +
229
+ `${ask || wait || activity}`,
230
+ row: rowIndex,
231
+ });
232
+ rowIndex++;
233
+ }
234
+ }
235
+ if (workspace.runs.length === 0) {
236
+ left.push({ text: ` ${ui.dim}(no runs)${ui.reset}` });
237
+ }
238
+ }
239
+ if (flat.length === 0) {
240
+ left.push({
241
+ text: `${ui.dim} 还没有任何编排 Run。用 mocode supervise dispatch <workspace> --lane <id> <objective> 派第一个活。${ui.reset}`,
242
+ });
243
+ }
244
+ // 窗口:让选中行落在可视区中部,避免长列表一路顶到底。
245
+ const windowRows = bodyRows;
246
+ let start = 0;
247
+ if (selected >= 0 && left.length > windowRows) {
248
+ const pos = left.findIndex((line) => line.row === selected);
249
+ if (pos >= 0)
250
+ start = Math.max(0, Math.min(pos - Math.floor(windowRows / 2), left.length - windowRows));
251
+ }
252
+ const visible = left.slice(start, start + windowRows);
253
+ if (!wide) {
254
+ for (const line of visible)
255
+ lines.push(fit(line.text, leftWidth));
256
+ lines.push(footerLine(cols, flat.length));
257
+ const picked = visible.findIndex((line) => line.row === selected);
258
+ return { lines, selectedLine: picked >= 0 ? picked + 1 : 1, rows: flat };
259
+ }
260
+ // 右栏是「选中项详情」的一块固定内容,不跟着行的滚动位移走:
261
+ // 行对齐会把它切碎——列表只有 3 行时,第 4 条详情(下一步该干什么)就永远不显示。
262
+ const detail = detailLines(board, flat, selected, rightWidth);
263
+ for (let index = 0; index < windowRows; index++) {
264
+ const cell = visible[index];
265
+ const leftText = cell ? fit(cell.text, leftWidth) : '';
266
+ const pad = ' '.repeat(Math.max(0, leftWidth - ansiDisplayWidth(leftText)));
267
+ lines.push(`${leftText}${pad}${ui.dim}│${ui.reset} ${detail[index] ?? ''}`.trimEnd());
268
+ }
269
+ lines.push(footerLine(cols, flat.length));
270
+ const picked = visible.findIndex((cell) => cell.row === selected);
271
+ return { lines, selectedLine: picked >= 0 ? picked + 1 : 1, rows: flat };
272
+ }
273
+ function footerLine(cols, count) {
274
+ const footer = `${ui.dim}↑↓ 选择 · r 刷新 · q 退出${count > 0 ? ` · ${count} 行` : ''}${ui.reset}`;
275
+ return fit(footer, cols);
276
+ }
277
+ /** 非 TTY / `--json` 的一次性快照;人读版复用面板同一套行渲染。 */
278
+ export function formatBoardSnapshot(board, options = {}) {
279
+ if (options.json)
280
+ return `${JSON.stringify(board, null, 2)}\n`;
281
+ const rendered = renderBoard(board, { cols: options.cols ?? 100, rows: 200, selected: -1 });
282
+ // 一次性输出不该拖一堆尾部空白行。
283
+ const lines = [...rendered.lines];
284
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '')
285
+ lines.pop();
286
+ return `${lines.join('\n')}\n`;
287
+ }
288
+ /** 右侧详情:回答「在干什么 / 为什么等 / 改了哪些文件 / 下一步谁决定」。 */
289
+ function detailLines(board, flat, selected, width) {
290
+ const row = flat[selected];
291
+ if (!row)
292
+ return [];
293
+ const workspace = board.workspaces.find((item) => item.root === row.workspaceRoot);
294
+ if (!workspace)
295
+ return [];
296
+ const lines = [];
297
+ const add = (label, value) => {
298
+ if (!value)
299
+ return;
300
+ lines.push(fit(`${ui.dim}${label}${ui.reset} ${value}`, width));
301
+ };
302
+ if (row.kind === 'workspace') {
303
+ add('工作区', workspace.root);
304
+ add('类型', workspace.git ? `git ${workspace.branch ?? ''}${workspace.dirty ? ' (dirty)' : ''}` : '非 git');
305
+ add('会话', `${workspace.sessionCount} 个,最近 ${workspace.latestSession ?? '—'}`);
306
+ add('Run', `${workspace.runs.length} 个(面板只看未终态的)`);
307
+ return lines;
308
+ }
309
+ const run = workspace.runs.find((item) => item.id === row.runId);
310
+ const lane = run?.lanes.find((item) => item.laneId === row.laneId);
311
+ if (!run || !lane)
312
+ return lines;
313
+ add('Run', `${run.id} ${run.status}`);
314
+ add('目标', run.objective);
315
+ add('lane', `${lane.laneId} ${lane.mode} ${lane.state}`);
316
+ add('现场', lane.executionRoot);
317
+ add('会话', lane.sessionId);
318
+ add('任务', lane.taskId ? `${lane.taskId} ${lane.taskStatus ?? ''} ${lane.done}/${lane.total}` : undefined);
319
+ add('当前动作', lane.lastEvent);
320
+ for (const approval of lane.pendingApprovals) {
321
+ add('待回答', `${ui.yellow}? ${approval.kind} ${approval.id}${ui.reset} ${approval.title}`);
322
+ }
323
+ for (const risk of lane.risks.slice(0, 3)) {
324
+ add('风险', `${ui.yellow}${risk}${ui.reset}`);
325
+ }
326
+ if (lane.awaitingReason)
327
+ add('等待', `${ui.yellow}${lane.awaitingReason}${ui.reset}`);
328
+ if (lane.error)
329
+ add('错误', `${ui.red}${lane.error}${ui.reset}`);
330
+ add('下一步', 'dispatch 续派 / ask 问进度 / close 收工');
331
+ return lines;
332
+ }