dsh-volcano-git-plugin 0.0.0-stage → 1.7.2

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/git-core.mjs ADDED
@@ -0,0 +1,2755 @@
1
+ // git-core.mjs — dsh-git-manager 核心
2
+ //
3
+ // 零依赖 git CLI 封装:所有 git 调用通过 runGit 走 argv 数组(无 shell),
4
+ // 全部解析器为纯函数(便于 TDD 单测)。本文件可被 index.js 与 scripts/self-test.mjs 共用。
5
+ //
6
+ // 设计要点:
7
+ // - runGit(cwd, args, opts) → 统一出口,超时/过大/缺 git 抛 GitError(kind, ...)
8
+ // - 解析器只接受字符串、只返回结构化对象;不依赖 git core 内部
9
+ // - 路径防护(safeJoin):discard 未跟踪 / resolveConflict custom 共用
10
+ // - 查询/变更函数全部 async(cwd, ...),抛 GitError,由 index.js 包 envelope
11
+
12
+ import { execFile } from "node:child_process";
13
+ import { rm, writeFile, readFile } from "node:fs/promises";
14
+ import { existsSync, statSync, readdirSync } from "node:fs";
15
+ import { resolve, join, sep, basename } from "node:path";
16
+ import { tmpdir } from "node:os";
17
+ import { randomBytes } from "node:crypto";
18
+
19
+ // ============================================================================
20
+ // runGit 封装
21
+ // ============================================================================
22
+
23
+ export class GitError extends Error {
24
+ constructor(kind, message, extra) {
25
+ super(message);
26
+ this.name = "GitError";
27
+ this.kind = kind; // "missing" | "timeout" | "too-large" | "exit"
28
+ Object.assign(this, extra || {});
29
+ }
30
+ }
31
+
32
+ const BASE_ARGS = [
33
+ "-c", "core.quotepath=false",
34
+ "-c", "color.ui=false",
35
+ "-c", "i18n.logoutputencoding=UTF-8",
36
+ ];
37
+
38
+ const LOCAL_TIMEOUT = 30000;
39
+ const NET_TIMEOUT = 180000;
40
+
41
+ export function runGit(cwd, args, opts = {}) {
42
+ const timeoutMs = opts.timeoutMs ?? LOCAL_TIMEOUT;
43
+ const maxBuffer = opts.maxBuffer ?? 32 * 1024 * 1024;
44
+ return new Promise((resolve, reject) => {
45
+ execFile(
46
+ "git",
47
+ BASE_ARGS.concat(args),
48
+ {
49
+ cwd,
50
+ windowsHide: true,
51
+ encoding: "utf8",
52
+ timeout: timeoutMs,
53
+ maxBuffer,
54
+ env: Object.assign({}, process.env, {
55
+ GIT_TERMINAL_PROMPT: "0",
56
+ GIT_EDITOR: "true",
57
+ // 编辑器脚本由 buildEditorCommand 用 process.execPath 启动:Electron 宿主下
58
+ // execPath 是 Electron 主程序,此变量强制其以纯 node 模式跑脚本;纯 node
59
+ // 宿主下无副作用(P3-A 集成加固,2026-09-29)。
60
+ ELECTRON_RUN_AS_NODE: "1",
61
+ }, opts.env || {}), // per-call 覆盖(P3-A rebase 的 GIT_SEQUENCE_EDITOR / GIT_EDITOR 队列)
62
+ },
63
+ (err, stdout, stderr) => {
64
+ if (!err) return resolve({ code: 0, stdout, stderr });
65
+ if (err.code === "ENOENT") {
66
+ return reject(new GitError("missing", "找不到 git 可执行文件,请先安装 Git。", { cause: err }));
67
+ }
68
+ if (err.killed || err.signal === "SIGTERM") {
69
+ return reject(new GitError("timeout", "git 操作超时(>" + Math.round(timeoutMs / 1000) + "s)", { stderr }));
70
+ }
71
+ if (err.code === "ENOBUFS" || /maxBuffer/i.test(String(err.message || ""))) {
72
+ return reject(new GitError("too-large", "git 输出过大,请缩小范围(如单文件 diff)。", { stderr }));
73
+ }
74
+ const exitCode = typeof err.code === "number" ? err.code : null;
75
+ const msg = String(stderr || err.message || "git 命令失败").trim();
76
+ reject(new GitError("exit", msg, { exitCode, stderr, stdout }));
77
+ },
78
+ );
79
+ });
80
+ }
81
+
82
+ // 与 runGit 等价的便捷封装:跑网络类命令(fetch/pull/push)使用更长超时。
83
+ export function runGitNet(cwd, args, opts = {}) {
84
+ return runGit(cwd, args, Object.assign({ timeoutMs: NET_TIMEOUT }, opts));
85
+ }
86
+
87
+ // ============================================================================
88
+ // 路径防护(discard 未跟踪 + resolveConflict custom 共用)
89
+ // ============================================================================
90
+
91
+ export function safeJoin(toplevel, rel) {
92
+ if (!toplevel || typeof rel !== "string" || rel.length === 0) {
93
+ throw new GitError("exit", "非法路径:路径为空");
94
+ }
95
+ // 绝对路径直接拒绝(只能传相对路径)
96
+ if (resolve(rel) === rel || /^[a-zA-Z]:[\\/]/.test(rel) || rel.startsWith("/")) {
97
+ throw new GitError("exit", "非法路径(必须是相对路径):" + rel);
98
+ }
99
+ // 关键:toplevel 先 resolve 归一化。git rev-parse 在 Windows 上输出正斜杠
100
+ // (如 "D:/repo"),而 resolve() 归一为反斜杠;不归一化就会让下面的
101
+ // startsWith(root + sep) 永远 false,所有合法路径都被误判越界。
102
+ const root = resolve(toplevel);
103
+ const abs = resolve(root, rel);
104
+ const rootWithSep = root.endsWith(sep) ? root : root + sep;
105
+ if (abs !== root && !abs.startsWith(rootWithSep)) {
106
+ throw new GitError("exit", "非法路径(越出仓库根目录):" + rel);
107
+ }
108
+ return abs;
109
+ }
110
+
111
+ // 子仓库 containment 校验(子仓库支持 §4.5 / 方案 §4.5):
112
+ // 与 safeJoin 同一道闸、同一套归一化教训——先 resolve(root) 再前缀判定。
113
+ // 区别:入参 p 是「候选仓库的绝对路径」(client 传回来的 activeRepo.path),
114
+ // 不是仓库内相对路径;相对路径同样按 root 解析,返回归一化后的绝对路径。
115
+ // Windows 路径大小写不敏感(方案 §5.3):比较前统一小写,否则 D:\Repo 与
116
+ // d:\repo 互判越界;POSIX 上大小写敏感,保持原样。
117
+ export function validateRepoPath(rootToplevel, p) {
118
+ if (typeof rootToplevel !== "string" || rootToplevel.length === 0) {
119
+ throw new GitError("exit", "非法路径:仓库根为空");
120
+ }
121
+ if (typeof p !== "string" || p.length === 0) {
122
+ throw new GitError("exit", "非法路径:路径为空");
123
+ }
124
+ const norm = (s) => (process.platform === "win32" ? s.toLowerCase() : s);
125
+ const root = resolve(rootToplevel);
126
+ const abs = resolve(root, p);
127
+ const rootKey = norm(root);
128
+ const absKey = norm(abs);
129
+ const rootWithSepKey = rootKey.endsWith(sep) ? rootKey : rootKey + sep;
130
+ if (absKey !== rootKey && !absKey.startsWith(rootWithSepKey)) {
131
+ throw new GitError("exit", "非法路径(越出仓库根目录):" + p);
132
+ }
133
+ return abs;
134
+ }
135
+
136
+ // 路径等价判定(大小写不敏感仅在 Windows 生效):去重 / 「toplevel 就是这个目录」
137
+ // 的自检共用(方案 §5.3)。
138
+ function samePath(a, b) {
139
+ const x = resolve(a);
140
+ const y = resolve(b);
141
+ return process.platform === "win32" ? x.toLowerCase() === y.toLowerCase() : x === y;
142
+ }
143
+
144
+ // 相对路径 → posix 归一(子仓库发现的三路来源——submodule status / ls-files -z /
145
+ // 调用方——分隔符不统一,统一成正斜杠再当 id 用)
146
+ function toPosixRel(p) {
147
+ return String(p == null ? "" : p).split(/[\\/]+/).filter(Boolean).join("/");
148
+ }
149
+
150
+ // ============================================================================
151
+ // 入参白名单校验(防选项注入:execFile 不拼 shell,但位置参数若以 "-" 开头
152
+ // 会被 git 当作选项;rev/tag 名/文件名一律先过白名单再进 argv)
153
+ // ============================================================================
154
+
155
+ // rev / ref:sha、HEAD、HEAD~n、@{...}、分支/tag 名等;禁 "-" 开头、空白与元字符
156
+ const REV_RE = /^[A-Za-z0-9._\/^~@{}:+=-]+$/;
157
+ export function checkRev(rev, label) {
158
+ if (typeof rev !== "string" || rev.length === 0) {
159
+ throw new GitError("exit", (label || "操作") + " 需要 ref");
160
+ }
161
+ if (rev.startsWith("-") || !REV_RE.test(rev)) {
162
+ throw new GitError("exit", (label || "操作") + " 非法 ref:" + rev);
163
+ }
164
+ return rev;
165
+ }
166
+
167
+ // reset target 白名单(契约 §2.4):sha 十六进制 / HEAD / HEAD~n / @{...},
168
+ // 拒绝其他一切形态(含 "-" 开头)防选项注入。
169
+ export function checkResetTarget(target) {
170
+ const t = target == null || target === "" ? "HEAD" : target;
171
+ if (typeof t !== "string") throw new GitError("exit", "reset target 非法");
172
+ const ok = /^[0-9a-fA-F]{4,40}$/.test(t)
173
+ || t === "HEAD"
174
+ || /^HEAD~[0-9]{1,3}$/.test(t)
175
+ || /^@\{[A-Za-z0-9._^~:+-]{1,64}\}$/.test(t);
176
+ if (!ok) throw new GitError("exit", "reset target 非法:" + t);
177
+ return t;
178
+ }
179
+
180
+ // tag / 分支名校验(对齐 git check-ref-format 的关键禁止项)
181
+ export function checkRefName(name, label) {
182
+ if (typeof name !== "string" || name.length === 0) {
183
+ throw new GitError("exit", (label || "操作") + " 需要 name");
184
+ }
185
+ const bad = name.startsWith("-") || name.startsWith("/") || name.endsWith("/")
186
+ || name.endsWith(".") || name.endsWith(".lock") || name.includes("..")
187
+ || name.includes("//") || name.includes("@{") || /[\s~^:?*\[\\]/.test(name);
188
+ if (bad) throw new GitError("exit", (label || "操作") + " 非法名称:" + name);
189
+ return name;
190
+ }
191
+
192
+ // stash 序号:缺省 0,必须是非负整数
193
+ export function checkStashIndex(index) {
194
+ if (index == null || index === "") return 0;
195
+ const n = Number(index);
196
+ if (!Number.isInteger(n) || n < 0 || n > 9999) {
197
+ throw new GitError("exit", "非法 stash 序号:" + index);
198
+ }
199
+ return n;
200
+ }
201
+
202
+ // remote 名:git remote add/rename/remove 的 name
203
+ export function checkRemoteName(name, label) {
204
+ if (typeof name !== "string" || name.length === 0) {
205
+ throw new GitError("exit", (label || "remote") + " 需要 name");
206
+ }
207
+ if (name.startsWith("-") || /[\s~^:?*\[\\/@{}]/.test(name) || name.includes("..")) {
208
+ throw new GitError("exit", (label || "remote") + " 非法名称:" + name);
209
+ }
210
+ return name;
211
+ }
212
+
213
+ // ============================================================================
214
+ // 查询:probeRepo
215
+ // ============================================================================
216
+
217
+ export async function probeRepo(path) {
218
+ // 不是目录就返回 { isRepo:false },让客户端提供「初始化仓库」入口
219
+ if (!path) return { isRepo: false };
220
+ try {
221
+ if (!existsSync(path) || !statSync(path).isDirectory()) {
222
+ return { isRepo: false };
223
+ }
224
+ } catch (_) {
225
+ return { isRepo: false };
226
+ }
227
+ let revRaw;
228
+ try {
229
+ revRaw = await runGit(path, ["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir", "--is-bare-repository"]);
230
+ } catch (e) {
231
+ if (e instanceof GitError && e.kind === "exit") {
232
+ // 不是仓库(exit 128 + "not a git repository")
233
+ return { isRepo: false };
234
+ }
235
+ throw e;
236
+ }
237
+ const lines = revRaw.stdout.split("\n").map((s) => s.trim());
238
+ const toplevel = lines[0];
239
+ const gitDir = lines[1];
240
+ const commonDir = lines[2];
241
+ const bare = lines[3] === "true";
242
+
243
+ // 当前 ref
244
+ let branch = null;
245
+ let detached = false;
246
+ let headShort = null;
247
+ let unborn = false;
248
+ try {
249
+ const sym = await runGit(path, ["symbolic-ref", "--short", "-q", "HEAD"]);
250
+ branch = sym.stdout.trim() || null;
251
+ // symbolic-ref 成功 ≠ HEAD 存在:unborn 分支(init 后无 commit)同样返回
252
+ // refs/heads/<name>。必须再用 rev-parse 验证 HEAD 可解析。
253
+ try {
254
+ const ver = await runGit(path, ["rev-parse", "--short=12", "HEAD"]);
255
+ headShort = ver.stdout.trim();
256
+ } catch (_) {
257
+ unborn = true;
258
+ }
259
+ } catch (e) {
260
+ if (e instanceof GitError && e.kind === "exit") {
261
+ detached = true;
262
+ try {
263
+ const ver = await runGit(path, ["rev-parse", "--short=12", "HEAD"]);
264
+ headShort = ver.stdout.trim();
265
+ } catch (_) {
266
+ unborn = true;
267
+ }
268
+ } else {
269
+ throw e;
270
+ }
271
+ }
272
+
273
+ // worktree 判定
274
+ let isLinkedWorktree = false;
275
+ let mainWorktreePath = undefined;
276
+ if (gitDir && commonDir && gitDir !== commonDir) {
277
+ isLinkedWorktree = true;
278
+ try {
279
+ const m = await runGit(path, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
280
+ // mainWorktreePath 是主 worktree 的工作目录(不是 .git),从 commonDir 反推
281
+ // 例:commonDir = "D:/repo/.git" → mainWorktreePath = "D:/repo"
282
+ const absCommon = resolve(path, m.stdout.trim());
283
+ const parent = absCommon.replace(/[\\/]\.git$/, "");
284
+ if (parent !== absCommon) mainWorktreePath = parent;
285
+ } catch (_) { /* noop */ }
286
+ }
287
+
288
+ // merge / rebase 状态(gitDir 可能是相对路径,先归一化到 cwd)
289
+ const gitDirAbs = resolve(path, gitDir);
290
+ const merging = existsSync(join(gitDirAbs, "MERGE_HEAD"));
291
+ const rebasing = existsSync(join(gitDirAbs, "rebase-merge")) || existsSync(join(gitDirAbs, "rebase-apply"));
292
+
293
+ const out = {
294
+ isRepo: true,
295
+ toplevel,
296
+ gitDir,
297
+ commonDir,
298
+ bare,
299
+ branch,
300
+ detached,
301
+ headShort: unborn ? null : headShort,
302
+ unborn,
303
+ merging,
304
+ rebasing,
305
+ isLinkedWorktree,
306
+ };
307
+ // 网关 assertJsonValue 会拒绝显式 undefined 的 own key——defined 才带上
308
+ if (mainWorktreePath !== undefined) out.mainWorktreePath = mainWorktreePath;
309
+ return out;
310
+ }
311
+
312
+ // ============================================================================
313
+ // 解析器(纯函数,TDD 单测目标)
314
+ // ============================================================================
315
+
316
+ // 将 porcelain v2 + -z 输出解析为 status 对象
317
+ // 文档:https://git-scm.com/docs/git-status
318
+ // - header 行以 '#' 开头
319
+ // - 类型 1(ordinary):"1 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <path>"
320
+ // - 类型 2(rename/copy):"2 <XY> <sub> <mH> <mI> <mW> <hH> <hI> R<score> <newPath>" + 下一 token = origPath
321
+ // - 类型 u(unmerged/conflict):"u <XY> <sub> <m1> <m2> <m3> <mW> <h1> <h2> <h3> <path>"
322
+ // - 未跟踪:"? <path>",已忽略:"! <path>"
323
+ export function parseStatusV2(text) {
324
+ const result = {
325
+ branch: null,
326
+ detached: false,
327
+ headSha: null,
328
+ upstream: null,
329
+ ahead: 0,
330
+ behind: 0,
331
+ unborn: false,
332
+ staged: [],
333
+ unstaged: [],
334
+ untracked: [],
335
+ conflicted: [],
336
+ };
337
+ if (!text) return result;
338
+ const tokens = text.split("\0");
339
+ for (const tok of tokens) {
340
+ if (tok.length === 0) continue;
341
+ if (tok.startsWith("# branch.oid ")) {
342
+ const v = tok.slice("# branch.oid ".length).trim();
343
+ if (v === "(initial)") {
344
+ result.unborn = true;
345
+ result.headSha = null;
346
+ } else if (v) {
347
+ result.headSha = v;
348
+ }
349
+ } else if (tok.startsWith("# branch.head ")) {
350
+ const v = tok.slice("# branch.head ".length).trim();
351
+ if (v && v !== "(detached)") result.branch = v;
352
+ else if (v === "(detached)") result.detached = true;
353
+ } else if (tok.startsWith("# branch.upstream ")) {
354
+ result.upstream = tok.slice("# branch.upstream ".length).trim() || null;
355
+ } else if (tok.startsWith("# branch.ab ")) {
356
+ const m = tok.slice("# branch.ab ".length).trim().match(/^\+(\d+)\s+-(\d+)/);
357
+ if (m) { result.ahead = Number(m[1]); result.behind = Number(m[2]); }
358
+ } else if (tok.startsWith("1 ") || tok.startsWith("2 ") || tok.startsWith("u ") || tok.startsWith("? ")) {
359
+ // 第一遍只关心 header
360
+ }
361
+ }
362
+ // 第二遍处理条目(含 rename 的双 token)
363
+ const entries = [];
364
+ for (let i = 0; i < tokens.length; i++) {
365
+ const tok = tokens[i];
366
+ if (tok.length === 0) continue;
367
+ if (tok.startsWith("# ") || tok.startsWith("? ") || tok.startsWith("! ")) continue;
368
+ const parts = tok.split(" ");
369
+ const type = parts[0];
370
+ if (type === "1" || type === "u") {
371
+ entries.push({ tok, origPath: null });
372
+ } else if (type === "2") {
373
+ // rename/copy: <newPath> 后面紧跟一个 origPath token
374
+ const next = tokens[i + 1] || "";
375
+ entries.push({ tok, origPath: next.length > 0 ? next : null });
376
+ i++;
377
+ }
378
+ }
379
+ for (const e of entries) {
380
+ const parts = e.tok.split(" ");
381
+ const type = parts[0];
382
+ if (type === "1") {
383
+ const x = parts[1][0];
384
+ const y = parts[1][1];
385
+ const path = parts.slice(8).join(" ");
386
+ if (x !== "." && x !== "?") {
387
+ const entry = { path, x, y, kind: mapXYChar(x) };
388
+ attachSubFields(entry, parts[2], parts[3], parts[4], parts[6], parts[7]);
389
+ result.staged.push(entry);
390
+ }
391
+ if (y !== "." && y !== "?") {
392
+ const entry = { path, x, y, kind: mapXYChar(y) };
393
+ attachSubFields(entry, parts[2], parts[3], parts[4], parts[6], parts[7]);
394
+ result.unstaged.push(entry);
395
+ }
396
+ } else if (type === "2") {
397
+ const x = parts[1][0];
398
+ const y = parts[1][1];
399
+ const path = parts.slice(9).join(" ");
400
+ if (x !== "." && x !== "?") {
401
+ const entry = { path, x, y, kind: "renamed", oldPath: e.origPath || "" };
402
+ attachSubFields(entry, parts[2], parts[3], parts[4], parts[6], parts[7]);
403
+ result.staged.push(entry);
404
+ }
405
+ if (y !== "." && y !== "?") {
406
+ const entry = { path, x, y, kind: "renamed", oldPath: e.origPath || "" };
407
+ attachSubFields(entry, parts[2], parts[3], parts[4], parts[6], parts[7]);
408
+ result.unstaged.push(entry);
409
+ }
410
+ } else if (type === "u") {
411
+ const xy = parts[1];
412
+ const path = parts.slice(10).join(" ");
413
+ result.conflicted.push({ path, xy });
414
+ }
415
+ }
416
+ // 第三遍:未跟踪 / 已忽略
417
+ for (const tok of tokens) {
418
+ if (tok.startsWith("? ")) result.untracked.push(tok.slice(2));
419
+ }
420
+ return result;
421
+ }
422
+
423
+ // 子仓库语义挂载(子仓库支持 §2.3):type 1/2 行第 3 列 <sub>、第 4/5 列 mode 与第 7/8 列 hH/hI。
424
+ // - subState:<sub> 形如 "N..."(非子模块)/ "SC.."(S=子模块, C=指针变更,
425
+ // 第三位=已跟踪内容脏, 第四位=未跟踪内容脏)。原样字符串挂载,非 N 才挂 key。
426
+ // - gitlink:仅 mode 160000(gitlink 条目)且 hH(HEAD 侧)/ hI(index 侧)都是
427
+ // 40 位 sha 且不相等 → staged 的 gitlink 指针变更(实测
428
+ // `1 M. S... 160000 160000 160000 <hH> <hI> libs/inner`)。
429
+ // mode 收窄是必须的:普通已暂存文件的 hH/hI 是 blob sha,同样 40 位且不等
430
+ // (实测 `1 M. N... 100644 100644 100644 <blob> <blob> m.txt` 会误挂)。
431
+ // 注意 worktree 侧的指针漂移(子模块 checkout 到别的提交、index 未变)hH===hI,
432
+ // 不挂 gitlink——那种由 submodule.status 的 '+' 前缀表达。
433
+ // JSON-safe:可选字段有值才挂 key(AGENTS.md 网关教训)。
434
+ function attachSubFields(entry, sub, mH, mI, hH, hI) {
435
+ if (typeof sub === "string" && sub.length > 0 && sub[0] !== "N") {
436
+ entry.subState = sub;
437
+ }
438
+ const isGitlinkMode = mH === "160000" || mI === "160000";
439
+ if (isGitlinkMode && typeof hH === "string" && typeof hI === "string" && hH !== hI
440
+ && /^[0-9a-f]{40}$/.test(hH) && /^[0-9a-f]{40}$/.test(hI)) {
441
+ entry.gitlink = { fromSha: hH, toSha: hI };
442
+ }
443
+ }
444
+
445
+ function mapXYChar(c) {
446
+ // 把 porcelain v2 的单字符 X/Y 映射为 kind:
447
+ // M = modified(内容修改), A = added(新增到 index), D = deleted(删于 index/工作区),
448
+ // R = renamed, C = copied, T = typechange(文件类型/权限变化), U = unmerged/conflict
449
+ switch (c) {
450
+ case "M": return "modified";
451
+ case "A": return "added";
452
+ case "D": return "deleted";
453
+ case "R": return "renamed";
454
+ case "C": return "copied";
455
+ case "T": return "typechange";
456
+ case "U": return "conflicted";
457
+ default: return "modified";
458
+ }
459
+ }
460
+
461
+ // ============================================================================
462
+ // 查询:getStatus(含 merging/rebasing 标记,依赖 gitDir 路径)
463
+ // ============================================================================
464
+
465
+ export async function getStatus(cwd) {
466
+ const raw = await runGit(cwd, ["status", "--porcelain=v2", "--branch", "--untracked-files=normal", "-z"]);
467
+ const parsed = parseStatusV2(raw.stdout);
468
+ // 用 probeRepo 拿到 gitDir 判断 merging/rebasing。
469
+ // gitDir 可能是相对路径(cwd=toplevel 时返回 ".git")——必须 resolve(cwd, gitDir)
470
+ // 归一化到仓库,否则 join(".git", ...) 相对到 DSH 进程 cwd,merging 永远 false。
471
+ let merging = false, rebasing = false;
472
+ try {
473
+ const probe = await probeRepo(cwd);
474
+ if (probe.isRepo && probe.gitDir) {
475
+ const gitDirAbs = resolve(cwd, probe.gitDir);
476
+ merging = existsSync(join(gitDirAbs, "MERGE_HEAD"));
477
+ rebasing = existsSync(join(gitDirAbs, "rebase-merge")) || existsSync(join(gitDirAbs, "rebase-apply"));
478
+ }
479
+ } catch (_) { /* noop */ }
480
+ return Object.assign({}, parsed, { merging, rebasing });
481
+ }
482
+
483
+ // 状态摘要(纯函数):从 parseStatusV2/getStatus 的输出算脏计数。
484
+ // repoTree 的每节点摘要与 self-test 共用同一口径——只取计数,不带文件明细。
485
+ export function statusSummary(parsedStatus) {
486
+ const s = parsedStatus || {};
487
+ const n = (a) => (Array.isArray(a) ? a.length : 0);
488
+ return {
489
+ staged: n(s.staged),
490
+ unstaged: n(s.unstaged),
491
+ untracked: n(s.untracked),
492
+ conflicted: n(s.conflicted),
493
+ };
494
+ }
495
+
496
+ // ============================================================================
497
+ // 子仓库发现:listSubRepos(子仓库支持 §2.1 / 方案 §4.1)
498
+ // 输入 rootToplevel,输出 { repos: RepoNode[] }(含 root 自身,root 排第一,
499
+ // 其余按 relPath 字典序)。两路发现源合并去重:
500
+ // 1. submodule 注册链:git submodule status --recursive + .gitmodules 的 name/url
501
+ // 2. 嵌套独立仓库:root 的未跟踪目录(git 折叠的 dir/)逐个 probe
502
+ // 节点语义(JSON-safe:可选字段有值才挂 key,计数恒为数字,字符串无值用 ""):
503
+ // 任何一步失败只挂 error + dirty 全 0,不炸整体。
504
+ // ============================================================================
505
+
506
+ // repoTree 每节点要跑 2-3 个 git 进程;不限并发在 Windows 上是进程风暴,
507
+ // 顺序跑则十来个子仓库要 1-2s(方案 §5.4)。取 4 并发。
508
+ const SUBREPO_CONCURRENCY = 4;
509
+
510
+ // 有限并发 map(零依赖自实现,不引依赖)
511
+ async function mapLimit(items, limit, fn) {
512
+ const list = Array.isArray(items) ? items : [];
513
+ const out = new Array(list.length);
514
+ if (list.length === 0) return out;
515
+ let next = 0;
516
+ const workers = [];
517
+ const n = Math.max(1, Math.min(limit, list.length));
518
+ for (let i = 0; i < n; i++) {
519
+ workers.push((async () => {
520
+ for (;;) {
521
+ const idx = next++;
522
+ if (idx >= list.length) return;
523
+ out[idx] = await fn(list[idx], idx);
524
+ }
525
+ })());
526
+ }
527
+ await Promise.all(workers);
528
+ return out;
529
+ }
530
+
531
+ function gitErrText(e) {
532
+ if (e && typeof e.message === "string" && e.message.length > 0) return e.message;
533
+ return String(e);
534
+ }
535
+
536
+ function emptyDirty() {
537
+ return { staged: 0, unstaged: 0, untracked: 0, conflicted: 0 };
538
+ }
539
+
540
+ // 节点骨架(probe 失败时也保证字段齐全:branch ""/headShort ""/dirty 全 0)
541
+ function blankNode(abs, meta) {
542
+ return {
543
+ id: meta.relPath,
544
+ path: abs,
545
+ relPath: meta.relPath,
546
+ name: meta.name,
547
+ kind: meta.kind,
548
+ depth: meta.relPath === "" ? 0 : meta.relPath.split("/").length,
549
+ initialized: meta.initialized !== false,
550
+ branch: "",
551
+ detached: false,
552
+ unborn: false,
553
+ headShort: "",
554
+ dirty: emptyDirty(),
555
+ };
556
+ }
557
+
558
+ // 已知 probe 的仓库 → 节点(status 查询失败只挂 error,不影响其它字段)
559
+ async function nodeFromProbe(abs, meta, probe) {
560
+ const node = blankNode(abs, meta);
561
+ node.branch = probe.branch || "";
562
+ node.detached = !!probe.detached;
563
+ node.unborn = !!probe.unborn;
564
+ node.headShort = probe.headShort || "";
565
+ try {
566
+ node.dirty = statusSummary(await getStatus(abs));
567
+ } catch (e) {
568
+ node.error = gitErrText(e);
569
+ }
570
+ return node;
571
+ }
572
+
573
+ // 未初始化 submodule:没有 .git,语义位全空(unborn 只对有 .git 的仓库有意义)
574
+ function uninitializedSubmoduleNode(abs, relPath, name) {
575
+ return blankNode(abs, { relPath, name, kind: "submodule", initialized: false });
576
+ }
577
+
578
+ // `git submodule status --recursive` 解析(纯函数):
579
+ // `<前缀><40位sha> <path> (<describe>)`,前缀 ' '正常 / '-'未初始化 /
580
+ // '+'指针不符 / 'U'冲突。行尾 describe 容忍(路径本身含括号是极端情况,忽略)。
581
+ function parseSubmoduleStatus(text) {
582
+ const out = [];
583
+ if (!text) return out;
584
+ for (const line of String(text).split("\n")) {
585
+ if (!line) continue;
586
+ const m = /^([ +\-U])([0-9a-f]{40}) (.*)$/.exec(line);
587
+ if (!m) continue;
588
+ let p = m[3];
589
+ const described = /^(.*) \([^()]*\)$/.exec(p);
590
+ if (described) p = described[1];
591
+ const relPath = toPosixRel(p);
592
+ if (!relPath) continue;
593
+ out.push({ prefix: m[1], sha: m[2], relPath });
594
+ }
595
+ return out;
596
+ }
597
+
598
+ async function readSubmoduleEntries(rootAbs) {
599
+ try {
600
+ const r = await runGit(rootAbs, ["submodule", "status", "--recursive"]);
601
+ return parseSubmoduleStatus(r.stdout);
602
+ } catch (_) {
603
+ return []; // 无 .gitmodules / git 报错 → 无注册子仓库
604
+ }
605
+ }
606
+
607
+ // .gitmodules 的 name/url 映射:按 config key 的 <name> 段聚合,
608
+ // 返回 relPath(posix) → { name, url }。文件不存在或无匹配 → 空映射。
609
+ async function readGitmodulesMap(rootAbs) {
610
+ const byName = new Map();
611
+ try {
612
+ const r = await runGit(rootAbs, ["config", "-f", ".gitmodules", "--get-regexp", "^submodule\\..*\\.(path|url)$"]);
613
+ for (const line of r.stdout.split("\n")) {
614
+ if (!line) continue;
615
+ const sp = line.indexOf(" ");
616
+ if (sp < 0) continue;
617
+ const key = line.slice(0, sp);
618
+ const value = line.slice(sp + 1).trim();
619
+ const m = /^submodule\.(.+)\.(path|url)$/.exec(key);
620
+ if (!m) continue;
621
+ const name = m[1];
622
+ const entry = byName.get(name) || { name, path: "", url: "" };
623
+ if (m[2] === "path") entry.path = toPosixRel(value);
624
+ else entry.url = value;
625
+ byName.set(name, entry);
626
+ }
627
+ } catch (_) {
628
+ return new Map();
629
+ }
630
+ const byPath = new Map();
631
+ for (const entry of byName.values()) {
632
+ if (entry.path) byPath.set(entry.path, entry);
633
+ }
634
+ return byPath;
635
+ }
636
+
637
+ // root 的未跟踪目录(git 折叠成 `dir/`):嵌套独立仓库以此形态出现。
638
+ // .gitignore 忽略的不出现,属预期(方案 §5.1 的"未跟踪"口径)。
639
+ // 用 -z:非 -z 时含特殊字符的路径会被 C 风格引号包裹,解析要再反转义。
640
+ async function readUntrackedDirs(rootAbs) {
641
+ try {
642
+ const r = await runGit(rootAbs, ["ls-files", "--others", "--directory", "--exclude-standard", "-z"]);
643
+ const out = [];
644
+ for (const raw of r.stdout.split("\0")) {
645
+ if (!raw.endsWith("/")) continue; // 只取折叠的目录条目(文件条目另作他用)
646
+ const relPath = toPosixRel(raw);
647
+ if (relPath) out.push(relPath);
648
+ }
649
+ return out;
650
+ } catch (_) {
651
+ return [];
652
+ }
653
+ }
654
+
655
+ // nested 节点的 originUrl(子仓库支持 P2):在该嵌套仓库读 remote.origin.url,
656
+ // 非空才挂 key(JSON-safe)——供客户端「注册为 submodule」转换用(submoduleAdd
657
+ // 复用同一个 url)。submodule / root 节点不挂:submodule 的 url 已在 .gitmodules
658
+ // (node.submodule.url),root 的 remote 由设置 Tab 管。
659
+ async function attachNestedOrigin(node, abs) {
660
+ try {
661
+ const r = await runGit(abs, ["config", "--get", "remote.origin.url"]);
662
+ const url = r.stdout.trim();
663
+ if (url) node.originUrl = url;
664
+ } catch (_) {
665
+ /* 无 origin remote(exit 1)→ 不挂 key */
666
+ }
667
+ }
668
+
669
+ export async function listSubRepos(rootToplevel) {
670
+ if (typeof rootToplevel !== "string" || rootToplevel.length === 0) {
671
+ throw new GitError("exit", "repoTree 需要仓库根路径");
672
+ }
673
+ const rootAbs = resolve(rootToplevel);
674
+ const rootProbe = await probeRepo(rootAbs);
675
+ if (!rootProbe || !rootProbe.isRepo) {
676
+ throw new GitError("exit", "不是 git 仓库:" + rootAbs);
677
+ }
678
+ const rootNode = await nodeFromProbe(
679
+ rootAbs,
680
+ { relPath: "", name: basename(rootAbs) || rootAbs, kind: "root" },
681
+ rootProbe,
682
+ );
683
+
684
+ const [subEntries, modMap] = await Promise.all([
685
+ readSubmoduleEntries(rootAbs),
686
+ readGitmodulesMap(rootAbs),
687
+ ]);
688
+
689
+ // ---- 路 1:submodule 注册链 ----
690
+ const subNodes = await mapLimit(subEntries, SUBREPO_CONCURRENCY, async (entry) => {
691
+ const relPath = entry.relPath;
692
+ // 病态 .gitmodules(手改成 ../escape 之类):safeJoin 抛错 → 该条目不进树,
693
+ // 但不能炸掉整个 repoTree
694
+ let abs;
695
+ try {
696
+ abs = safeJoin(rootAbs, relPath);
697
+ } catch (_) {
698
+ return null;
699
+ }
700
+ const mod = modMap.get(relPath);
701
+ const name = (mod && mod.name) || relPath.split("/").pop() || relPath;
702
+ // 前缀 '-' = 未初始化:目录可能为空/不存在,不进 probe
703
+ if (entry.prefix === "-") return uninitializedSubmoduleNode(abs, relPath, name);
704
+
705
+ // recordedSha:父仓库 index 记录的 gitlink 指针(取不到给 "")
706
+ let recordedSha = "";
707
+ try {
708
+ recordedSha = (await runGit(rootAbs, ["rev-parse", "--short=12", ":" + relPath])).stdout.trim();
709
+ } catch (_) {
710
+ recordedSha = "";
711
+ }
712
+ const meta = { relPath, name, kind: "submodule", initialized: true };
713
+ let node;
714
+ try {
715
+ const probe = await probeRepo(abs);
716
+ if (!probe || !probe.isRepo) return uninitializedSubmoduleNode(abs, relPath, name);
717
+ // 必须是独立子仓库:toplevel 就是这个目录本身(否则它落在别的仓库里)
718
+ if (!samePath(probe.toplevel, abs)) return null;
719
+ node = await nodeFromProbe(abs, meta, probe);
720
+ } catch (e) {
721
+ // probe 抛错(超时/git 缺失…):节点仍返回,挂 error
722
+ node = blankNode(abs, meta);
723
+ node.error = gitErrText(e);
724
+ }
725
+ node.submodule = {
726
+ state: entry.prefix === "U" ? "conflict" : entry.prefix === "+" ? "pointer-mismatch" : "ok",
727
+ sha: entry.sha.slice(0, 12),
728
+ recordedSha,
729
+ url: (mod && mod.url) || "",
730
+ };
731
+ return node;
732
+ });
733
+
734
+ // ---- 路 2:嵌套独立仓库(submodule 路覆盖到的跳过:kind 不重复计)----
735
+ const covered = new Set();
736
+ for (const n of subNodes) {
737
+ if (!n) continue;
738
+ covered.add(process.platform === "win32" ? n.path.toLowerCase() : n.path);
739
+ }
740
+ const untrackedDirs = await readUntrackedDirs(rootAbs);
741
+ const nestedNodes = await mapLimit(untrackedDirs, SUBREPO_CONCURRENCY, async (relPath) => {
742
+ let abs;
743
+ try {
744
+ abs = safeJoin(rootAbs, relPath);
745
+ } catch (_) {
746
+ return null;
747
+ }
748
+ if (covered.has(process.platform === "win32" ? abs.toLowerCase() : abs)) return null;
749
+ try {
750
+ const probe = await probeRepo(abs);
751
+ // 候选只是「一个未跟踪目录」:不是独立仓库(普通未跟踪目录)或 toplevel
752
+ // 不是它自己(更深层仓库折叠在同一个未跟踪目录里)→ 都不算节点
753
+ if (!probe || !probe.isRepo || !samePath(probe.toplevel, abs)) return null;
754
+ const node = await nodeFromProbe(abs, { relPath, name: basename(abs) || relPath, kind: "nested" }, probe);
755
+ await attachNestedOrigin(node, abs);
756
+ return node;
757
+ } catch (_) {
758
+ return null; // 探测不出来的候选不是「已知仓库」,不进树
759
+ }
760
+ });
761
+
762
+ const repos = [rootNode].concat(subNodes, nestedNodes).filter(Boolean);
763
+ repos.sort((a, b) => {
764
+ if (a.relPath === "") return b.relPath === "" ? 0 : -1; // root 恒第一
765
+ if (b.relPath === "") return 1;
766
+ return a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0;
767
+ });
768
+ return { repos };
769
+ }
770
+
771
+ // revExists:批量校验 sha 是否存在于该仓库对象库(子仓库支持 P1 §3.6)。
772
+ // 用途:历史 Tab 里某个提交改了 gitlink(指针 a→b)时,客户端据此决定
773
+ // 「在子仓库中查看 a..b」按钮是否可用——浅克隆 / GC 掉旧指针时 a 或 b 可能不在
774
+ // 子仓库的本地对象库里,此时必须禁用跳转而不是让 diffRange 报未知修订。
775
+ // 返回形状恒 JSON-safe:{ checks: [{ rev, ok }] },顺序与入参一致。
776
+ //
777
+ // 入参白名单比 checkRev 严得多:只收纯十六进制 sha(7-40 位)。checkRev 放行的
778
+ // 「HEAD~3 / @{yesterday} / 任意分支名」在这里一律拒绝——因为拼 ^{commit}
779
+ // 后缀后仍会进 argv,表达式形态(如 "a..b"、"--upload-pack")是注入面,
780
+ // 而这里的需求本来就只要「一个 sha 在不在」。后缀由本函数内部拼接,调用方无法注入。
781
+ const REV_EXISTS_SHA_RE = /^[0-9a-fA-F]{7,40}$/;
782
+ export async function revExists(cwd, revs) {
783
+ const list = Array.isArray(revs) ? revs : [];
784
+ const checks = [];
785
+ for (const raw of list) {
786
+ if (typeof raw !== "string" || !REV_EXISTS_SHA_RE.test(raw)) {
787
+ throw new GitError("exit", "revExists 非法 sha:" + String(raw));
788
+ }
789
+ let ok = false;
790
+ try {
791
+ // --verify + --quiet:不存在(含非 commit 对象)时 exit 1 且无输出
792
+ await runGit(cwd, ["rev-parse", "--verify", "--quiet", raw + "^{commit}"]);
793
+ ok = true;
794
+ } catch (e) {
795
+ // 只有「确实不存在」这一种 exit 1 被吞成 ok:false;非仓库(128)、
796
+ // 超时、git 缺失等一律上抛,让 Host 入口照常映射错误码
797
+ if (e instanceof GitError && e.kind === "exit" && e.exitCode === 1) ok = false;
798
+ else throw e;
799
+ }
800
+ checks.push({ rev: raw, ok });
801
+ }
802
+ return { checks };
803
+ }
804
+
805
+ // ============================================================================
806
+ // 解析器:parseBranchRefs
807
+ // 输入:git for-each-ref --format=<fmt> refs/heads refs/remotes 输出(每行 \n 分割,
808
+ // 字段 \t 分割;subject 可能有 tab 但放最后)
809
+ // 格式字段:%(refname)%09%(refname:short)%09%(objectname:short)%09%(committerdate:unix)%09%(upstream:short)%09%(upstream:track)%09%(HEAD)%09%(subject)
810
+ // ============================================================================
811
+
812
+ export function parseBranchRefs(text) {
813
+ const result = { locals: [], remotes: [] };
814
+ if (!text) return result;
815
+ for (const line of text.split("\n")) {
816
+ if (line.length === 0) continue;
817
+ const parts = line.split("\t");
818
+ if (parts.length < 8) continue;
819
+ const [refname, name, shortSha, at, upstream, track, headFlag, ...rest] = parts;
820
+ const subject = rest.join("\t");
821
+ const branch = {
822
+ name,
823
+ refname,
824
+ shortSha,
825
+ at: Number(at) || 0,
826
+ upstream: upstream || null,
827
+ ahead: null,
828
+ behind: null,
829
+ upstreamGone: false,
830
+ subject,
831
+ current: headFlag === "*",
832
+ };
833
+ if (track) {
834
+ const mAhead = /ahead (\d+)/.exec(track);
835
+ const mBehind = /behind (\d+)/.exec(track);
836
+ if (mAhead) branch.ahead = Number(mAhead[1]);
837
+ if (mBehind) branch.behind = Number(mBehind[1]);
838
+ if (/gone/.test(track)) branch.upstreamGone = true;
839
+ }
840
+ if (refname.startsWith("refs/remotes/")) {
841
+ result.remotes.push(branch);
842
+ } else {
843
+ result.locals.push(branch);
844
+ }
845
+ }
846
+ return result;
847
+ }
848
+
849
+ // ============================================================================
850
+ // 解析器:parseRemotes
851
+ // 输入:git remote -v 输出
852
+ // 行:name\turl (fetch|push)
853
+ // ============================================================================
854
+
855
+ export function parseRemotes(text) {
856
+ const map = new Map();
857
+ if (!text) return [];
858
+ for (const line of text.split("\n")) {
859
+ if (line.length === 0) continue;
860
+ const m = line.match(/^(\S+)\s+(\S+)\s+\((fetch|push)\)\s*$/);
861
+ if (!m) continue;
862
+ const [, name, url, kind] = m;
863
+ if (!map.has(name)) map.set(name, { name, fetchUrl: null, pushUrl: null });
864
+ const entry = map.get(name);
865
+ if (kind === "fetch") entry.fetchUrl = url;
866
+ else entry.pushUrl = url;
867
+ }
868
+ return Array.from(map.values());
869
+ }
870
+
871
+ // ============================================================================
872
+ // 解析器:parseLogText
873
+ // 输入:git log -z --format=%H%x1f%h%x1f%P%x1f%an%x1f%ae%x1f%at%x1f%D%x1f%s%x1f%b
874
+ // record 分隔:\0;field 分隔:\x1f
875
+ // parents 是空格分隔的 oid 列表;body 是 subject 之后的多行正文(v2 §6,
876
+ // amend 预填用),无正文时为 ""(字段恒定挂载,wire 安全)
877
+ // ============================================================================
878
+
879
+ export function parseLogText(text) {
880
+ const commits = [];
881
+ if (!text) return commits;
882
+ for (const rec of text.split("\0")) {
883
+ if (rec.length === 0) continue;
884
+ const parts = rec.split("\x1f");
885
+ if (parts.length < 8) continue;
886
+ const [sha, short, parentsRaw, author, email, at, refs, subject] = parts;
887
+ const parents = parentsRaw.trim() ? parentsRaw.trim().split(" ") : [];
888
+ // %b 带尾随换行;去掉尾随空白,保留内部多行结构
889
+ const body = (parts[8] || "").replace(/\s+$/, "");
890
+ commits.push({
891
+ sha,
892
+ short,
893
+ parents,
894
+ author,
895
+ email,
896
+ at: Number(at) || 0,
897
+ refs: refs || "",
898
+ subject,
899
+ body,
900
+ });
901
+ }
902
+ return commits;
903
+ }
904
+
905
+ // ============================================================================
906
+ // 查询:getBranches / getRemotes / getLog
907
+ // ============================================================================
908
+
909
+ const BRANCH_FMT =
910
+ "%(refname)%09%(refname:short)%09%(objectname:short)%09%(committerdate:unix)" +
911
+ "%09%(upstream:short)%09%(upstream:track)%09%(HEAD)%09%(subject)";
912
+
913
+ export async function getBranches(cwd) {
914
+ const raw = await runGit(cwd, [
915
+ "for-each-ref", "--format=" + BRANCH_FMT,
916
+ "refs/heads", "refs/remotes",
917
+ ]);
918
+ const parsed = parseBranchRefs(raw.stdout);
919
+ // 当前分支:尝试从 status header 拿
920
+ let current = null;
921
+ try {
922
+ const st = await runGit(cwd, ["status", "--porcelain=v2", "--branch", "-z"]);
923
+ for (const tok of st.stdout.split("\0")) {
924
+ if (tok.startsWith("# branch.head ")) {
925
+ const v = tok.slice("# branch.head ".length).trim();
926
+ if (v && v !== "(detached)") current = v;
927
+ }
928
+ }
929
+ } catch (_) { /* noop */ }
930
+ if (current) {
931
+ for (const b of parsed.locals) b.current = (b.name === current);
932
+ }
933
+ return Object.assign({ current }, parsed);
934
+ }
935
+
936
+ export async function getRemotes(cwd) {
937
+ const raw = await runGit(cwd, ["remote", "-v"]);
938
+ return parseRemotes(raw.stdout);
939
+ }
940
+
941
+ export async function getLog(cwd, opts = {}) {
942
+ // maxCount/limit 兼容两种叫法(契约 §2.2 "原有 skip/limit 保留")
943
+ const maxCount = opts.maxCount ?? opts.limit ?? 200;
944
+ const skip = opts.skip ?? 0;
945
+ const all = opts.all === true;
946
+ const ref = opts.ref || null;
947
+ const args = ["log", "--date-order", "-z", "--format=%H%x1f%h%x1f%P%x1f%an%x1f%ae%x1f%at%x1f%D%x1f%s%x1f%b",
948
+ "--max-count=" + maxCount, "--skip=" + skip];
949
+ if (all) args.push("--all");
950
+ if (ref) args.push(checkRev(ref, "log"));
951
+ // 过滤器(v2 §2.2):author / grep / since / until 都是选项值(单 argv,无注入面)
952
+ if (typeof opts.author === "string" && opts.author.length > 0) args.push("--author=" + opts.author);
953
+ if (typeof opts.grep === "string" && opts.grep.length > 0) args.push("--grep=" + opts.grep);
954
+ if (typeof opts.since === "string" && opts.since.length > 0) args.push("--since=" + opts.since);
955
+ if (typeof opts.until === "string" && opts.until.length > 0) args.push("--until=" + opts.until);
956
+ // 路径过滤:safeJoin 防护(拒绝对对路径 / .. 越界),pathspec 放 "--" 之后
957
+ let fileArg = null;
958
+ if (typeof opts.file === "string" && opts.file.length > 0) {
959
+ safeJoin(cwd, opts.file);
960
+ fileArg = opts.file;
961
+ }
962
+ let raw;
963
+ try {
964
+ raw = await runGit(cwd, fileArg ? args.concat(["--", fileArg]) : args);
965
+ } catch (e) {
966
+ if (e instanceof GitError && e.kind === "exit") {
967
+ // 只对 unborn HEAD / unknown revision 这两类"预期无历史"的情况返回空;
968
+ // 其他错误(如 ref 拼错、被禁用、网络)必须透传,否则 UI 看不出问题。
969
+ const msg = (e.stderr || e.message || "").toLowerCase();
970
+ const expectedEmpty = /does not have any commits/.test(msg)
971
+ || /unknown revision/.test(msg)
972
+ || /ambiguous argument ['"]?unknown/.test(msg)
973
+ || /not a git repository/.test(msg);
974
+ if (expectedEmpty) return { commits: [], hasMore: false };
975
+ throw e;
976
+ }
977
+ throw e;
978
+ }
979
+ const commits = parseLogText(raw.stdout);
980
+ return { commits, hasMore: commits.length === maxCount };
981
+ }
982
+
983
+ // ============================================================================
984
+ // 解析器:parseWorktreePorcelain
985
+ // 输入:git worktree list --porcelain(与 -c core.quotepath=false 配合,CJK 路径不过滤)
986
+ // 记录按空行分隔,每行 key 空格 value
987
+ // key ∈ worktree | HEAD | branch | detached | bare | locked | prunable
988
+ // ============================================================================
989
+
990
+ export function parseWorktreePorcelain(text) {
991
+ const result = [];
992
+ if (!text) return result;
993
+ // 兼容 -z:有些平台可能输出 NUL 分隔(rare);优先按空行切
994
+ const normalized = text.replace(/\0/g, "\n");
995
+ const records = normalized.split(/\n\s*\n/);
996
+ for (const rec of records) {
997
+ if (rec.trim().length === 0) continue;
998
+ // prunable 不能是 null(typert union(boolean,string) 不含 null),默认 false
999
+ const item = { path: null, headSha: null, branch: null, detached: false, bare: false, locked: false, prunable: false };
1000
+ for (const line of rec.split("\n")) {
1001
+ const idx = line.indexOf(" ");
1002
+ let key, value;
1003
+ if (idx < 0) {
1004
+ key = line.trim();
1005
+ value = "";
1006
+ } else {
1007
+ key = line.slice(0, idx);
1008
+ value = line.slice(idx + 1);
1009
+ }
1010
+ if (key === "worktree") item.path = value;
1011
+ else if (key === "HEAD") item.headSha = value;
1012
+ else if (key === "branch") {
1013
+ const m = /^refs\/heads\/(.+)$/.exec(value);
1014
+ item.branch = m ? m[1] : value;
1015
+ } else if (key === "detached") item.detached = true;
1016
+ else if (key === "bare") item.bare = true;
1017
+ else if (key === "locked") item.locked = value || true;
1018
+ else if (key === "prunable") item.prunable = value || true;
1019
+ }
1020
+ if (item.path) result.push(item);
1021
+ }
1022
+ return result;
1023
+ }
1024
+
1025
+ // ============================================================================
1026
+ // 查询:getWorktrees(基础字段 + 行内状态富化)
1027
+ // 返回 { worktrees: [...] },每条含 path/branch/detached 等基础字段、current
1028
+ // 标注,以及行内状态(脏计数 / ahead-behind / headShort),供客户端渲染。
1029
+ // 富化语义(JSON-safe:有值才挂 key,绝不挂 undefined/null):
1030
+ // - dirty = statusSummary(getStatus(path)):staged/unstaged/untracked/conflicted 四个数字
1031
+ // - ahead / behind:仅当该 worktree 有 upstream 时才挂(新分支无 upstream 就不挂)
1032
+ // - headShort:headSha 前 12 位(与 probeRepo 的 --short=12 同口径),非空才挂
1033
+ // - error:状态查询失败(目录被删、git 报错等)时只挂 error,单节点失败不炸整体
1034
+ // bare worktree 没有工作区,直接跳过富化。
1035
+ // 每个 worktree 都要跑一次 status(内部再 probeRepo),不限并发在 Windows 上
1036
+ // 是进程风暴,故限 4 并发(WORKTREE_CONCURRENCY)。
1037
+ // ============================================================================
1038
+
1039
+ // 每个 worktree 富化要跑 status(+ probeRepo);4 并发与子仓库发现同口径。
1040
+ const WORKTREE_CONCURRENCY = 4;
1041
+
1042
+ export async function getWorktrees(cwd) {
1043
+ const raw = await runGit(cwd, ["worktree", "list", "--porcelain"]);
1044
+ const list = parseWorktreePorcelain(raw.stdout);
1045
+ // 标注 current(cwd 或 toplevel 与 item.path 匹配)
1046
+ const probe = await probeRepo(cwd);
1047
+ const toplevel = probe.isRepo ? probe.toplevel : null;
1048
+ for (const item of list) {
1049
+ item.current = (toplevel && item.path && (item.path === toplevel || item.path.toLowerCase() === toplevel.toLowerCase()));
1050
+ }
1051
+ // 行内状态富化(非 bare):dirty / ahead / behind / headShort;失败只挂 error
1052
+ await mapLimit(list, WORKTREE_CONCURRENCY, async (item) => {
1053
+ if (item.bare || !item.path) return;
1054
+ try {
1055
+ const st = await getStatus(item.path);
1056
+ item.dirty = statusSummary(st);
1057
+ // 有 upstream 才有 ahead/behind;无 upstream 时不挂这两个 key
1058
+ if (typeof st.upstream === "string" && st.upstream.length > 0) {
1059
+ item.ahead = st.ahead;
1060
+ item.behind = st.behind;
1061
+ }
1062
+ const head = item.headSha || st.headSha || "";
1063
+ if (head) item.headShort = head.slice(0, 12);
1064
+ } catch (e) {
1065
+ item.error = gitErrText(e);
1066
+ }
1067
+ });
1068
+ return { worktrees: list };
1069
+ }
1070
+
1071
+ // ============================================================================
1072
+ // 查询:getDiff(4 种 scope + 未跟踪合成 + 截断)
1073
+ // ============================================================================
1074
+
1075
+ const DIFF_TEXT_CAP = 1500 * 1000; // 1.5MB 字符,超出置 truncated
1076
+
1077
+ export async function getDiff(cwd, opts = {}) {
1078
+ const scope = opts.scope || "worktree";
1079
+ const context = opts.context ?? 3;
1080
+ const ctxArg = ["-U" + context];
1081
+ let text = "";
1082
+ let truncated = false;
1083
+ try {
1084
+ if (scope === "worktree") {
1085
+ const args = ["diff"].concat(ctxArg).concat(opts.file ? ["--", opts.file] : []);
1086
+ const r = await runGit(cwd, args);
1087
+ text = r.stdout;
1088
+ } else if (scope === "staged") {
1089
+ const args = ["diff", "--cached"].concat(ctxArg).concat(opts.file ? ["--", opts.file] : []);
1090
+ const r = await runGit(cwd, args);
1091
+ text = r.stdout;
1092
+ } else if (scope === "commit") {
1093
+ if (!opts.sha) throw new GitError("exit", "diff(scope=commit) 需要 sha");
1094
+ const args = ["show", "--format=fuller", "--no-color", "-U" + context, opts.sha].concat(opts.file ? ["--", opts.file] : []);
1095
+ const r = await runGit(cwd, args);
1096
+ text = r.stdout;
1097
+ } else if (scope === "compare") {
1098
+ if (!opts.base || !opts.target) throw new GitError("exit", "diff(scope=compare) 需要 base + target");
1099
+ const args = ["diff", "-U" + context, opts.base + "..." + opts.target].concat(opts.file ? ["--", opts.file] : []);
1100
+ const r = await runGit(cwd, args);
1101
+ text = r.stdout;
1102
+ } else if (scope === "untracked") {
1103
+ if (!opts.file) throw new GitError("exit", "diff(scope=untracked) 需要 file");
1104
+ // git diff --no-index 在有差异时退出 1,正常
1105
+ try {
1106
+ const r = await runGit(cwd, ["diff", "--no-index", "-U" + context, "--", "/dev/null", opts.file]);
1107
+ text = r.stdout;
1108
+ } catch (e) {
1109
+ if (e instanceof GitError && e.kind === "exit" && e.exitCode === 1 && e.stdout) {
1110
+ text = e.stdout; // 退出 1 + 有 stdout = 有差异
1111
+ } else {
1112
+ throw e;
1113
+ }
1114
+ }
1115
+ } else {
1116
+ throw new GitError("exit", "未知 scope:" + scope);
1117
+ }
1118
+ } catch (e) {
1119
+ if (e instanceof GitError && e.kind === "exit" && e.exitCode === 1 && e.stdout) {
1120
+ // 普通 diff exit 1 表示有差异,正常返回 stdout
1121
+ text = e.stdout;
1122
+ } else {
1123
+ throw e;
1124
+ }
1125
+ }
1126
+ if (text.length > DIFF_TEXT_CAP) {
1127
+ text = text.slice(0, DIFF_TEXT_CAP);
1128
+ truncated = true;
1129
+ }
1130
+ return { text, truncated };
1131
+ }
1132
+
1133
+ // ============================================================================
1134
+ // 变更:hunk 级补丁(IDEA 式逐块操作:撤销此块 / 取消暂存此块)
1135
+ // ============================================================================
1136
+
1137
+ // 从完整 unified diff 文本中提取"某文件的第 hunkIndex 个块",拼成可独立
1138
+ // `git apply` 的最小补丁(文件头 + 单个 hunk)。纯函数,便于 fixture 测试。
1139
+ export function extractHunkPatch(diffText, file, hunkIndex) {
1140
+ if (typeof diffText !== "string" || diffText.length === 0) {
1141
+ throw new GitError("exit", "没有可用的 diff 文本");
1142
+ }
1143
+ if (typeof file !== "string" || file.length === 0) {
1144
+ throw new GitError("exit", "hunk 操作需要 file");
1145
+ }
1146
+ const idx = Number(hunkIndex);
1147
+ if (!Number.isInteger(idx) || idx < 0) {
1148
+ throw new GitError("exit", "非法 hunkIndex:" + hunkIndex);
1149
+ }
1150
+ // 按 "diff --git " 切文件段;段内:@@ 之前是文件头,之后每 @@ 开一个 hunk,
1151
+ // "" 等尾随行归入当前 hunk。
1152
+ const sections = [];
1153
+ let cur = null;
1154
+ for (const line of diffText.split("\n")) {
1155
+ if (line.startsWith("diff --git ")) {
1156
+ cur = { headerLines: [line], hunks: [], curHunk: null };
1157
+ sections.push(cur);
1158
+ } else if (!cur) {
1159
+ continue; // diff 之前的行(如 git show 的提交头)
1160
+ } else if (line.startsWith("@@")) {
1161
+ cur.curHunk = [line];
1162
+ cur.hunks.push(cur.curHunk);
1163
+ } else if (cur.curHunk) {
1164
+ cur.curHunk.push(line);
1165
+ } else {
1166
+ cur.headerLines.push(line);
1167
+ }
1168
+ }
1169
+ const unquote = (p) => (p && p.startsWith('"') && p.endsWith('"') ? p.slice(1, -1) : p);
1170
+ const wantNew = "b/" + file;
1171
+ const wantOld = "a/" + file;
1172
+ let target = null;
1173
+ for (const s of sections) {
1174
+ let newPath = null;
1175
+ let oldPath = null;
1176
+ for (const h of s.headerLines) {
1177
+ if (h.startsWith("+++ ")) newPath = unquote(h.slice(4));
1178
+ else if (h.startsWith("--- ")) oldPath = unquote(h.slice(4));
1179
+ }
1180
+ if (newPath === wantNew || oldPath === wantOld) { target = s; break; }
1181
+ // 兜底:diff --git a/<old> b/<new> 首行整体匹配
1182
+ if (s.headerLines[0] === "diff --git " + wantOld + " " + wantNew) { target = s; break; }
1183
+ }
1184
+ if (!target) throw new GitError("exit", "diff 中找不到文件:" + file);
1185
+ if (idx >= target.hunks.length) {
1186
+ throw new GitError("exit", "hunkIndex 越界:" + idx + "(该文件共 " + target.hunks.length + " 块)");
1187
+ }
1188
+ const patch = target.headerLines.concat(target.hunks[idx]).join("\n");
1189
+ return patch.endsWith("\n") ? patch : patch + "\n";
1190
+ }
1191
+
1192
+ // 对单个 hunk 执行反向应用:
1193
+ // scope=worktree → git apply --reverse 把工作区该块恢复成 index 版本(IDEA「撤销」)
1194
+ // scope=staged → git apply --reverse --cached 把该块移出暂存区(改动保留在工作区)
1195
+ // 返回最新 status(与其他 mutation 一致)。
1196
+ export async function applyHunk(cwd, opts = {}) {
1197
+ const scope = opts.scope;
1198
+ if (scope !== "worktree" && scope !== "staged") {
1199
+ throw new GitError("exit", "hunkApply 只支持 scope=worktree(撤销此块)/ staged(取消暂存此块)");
1200
+ }
1201
+ const file = opts.file;
1202
+ if (typeof file !== "string" || file.length === 0) {
1203
+ throw new GitError("exit", "hunkApply 需要 file");
1204
+ }
1205
+ const probe = await probeRepo(cwd);
1206
+ if (!probe.isRepo) throw new GitError("not-a-repo", "hunkApply:仓库不可用");
1207
+ // 路径防护:与 discard 同一道闸(拒绝绝对路径 / .. 越界)
1208
+ safeJoin(probe.toplevel, file);
1209
+ // patch 内路径是仓库根相对路径,getDiff/git apply 都必须在 toplevel 跑
1210
+ // (cwd 是子目录时 git diff -- <根相对路径> 会匹配不到)。
1211
+ const top = probe.toplevel;
1212
+ const diff = await getDiff(top, { scope, file });
1213
+ const patch = extractHunkPatch(diff.text, file, opts.hunkIndex);
1214
+ const tmpFile = join(tmpdir(), "dsh-gm-hunk-" + process.pid + "-" + randomBytes(6).toString("hex") + ".patch");
1215
+ try {
1216
+ await writeFile(tmpFile, patch, "utf8");
1217
+ const args = ["apply", "--reverse", "--whitespace=nowarn"];
1218
+ if (scope === "staged") args.push("--cached");
1219
+ args.push(tmpFile);
1220
+ await runGit(top, args);
1221
+ } finally {
1222
+ await rm(tmpFile, { force: true });
1223
+ }
1224
+ return getStatus(top);
1225
+ }
1226
+
1227
+ // ============================================================================
1228
+ // 变更:lineApply + extractLinePatch(P3-A §8.3 行级暂存/撤销)
1229
+ // ============================================================================
1230
+
1231
+ // 从完整 unified diff 中提取「某文件第 hunkIndex 个块内 rows[rowStart..rowEnd]」的
1232
+ // 最小补丁(纯函数)。行下标 0 基、含端点、只计 @@ 头之后的 ctx/add/del 行
1233
+ // ("" 等标记行随其紧邻上一行自动带出、不单独寻址)。
1234
+ // 正确重写 @@ 头两侧行计数与起始行号:count>0 时 start=首行号;count=0 时
1235
+ // start=插入点前一行(git -U0 实测约定,如 `@@ -3,0 +4,2 @@`);原 hunk 该侧
1236
+ // 本就为 0 时 start 保持不变。覆盖整个 hunk 时输出与 extractHunkPatch 逐字节一致。
1237
+ export function extractLinePatch(diffText, file, hunkIndex, rowStart, rowEnd) {
1238
+ if (typeof diffText !== "string" || diffText.length === 0) {
1239
+ throw new GitError("exit", "没有可用的 diff 文本");
1240
+ }
1241
+ if (typeof file !== "string" || file.length === 0) {
1242
+ throw new GitError("exit", "lineApply 需要 file");
1243
+ }
1244
+ const hIdx = Number(hunkIndex);
1245
+ if (!Number.isInteger(hIdx) || hIdx < 0) {
1246
+ throw new GitError("exit", "非法 hunkIndex:" + hunkIndex);
1247
+ }
1248
+ const r0 = Number(rowStart);
1249
+ const r1 = Number(rowEnd);
1250
+ if (!Number.isInteger(r0) || !Number.isInteger(r1)) {
1251
+ throw new GitError("exit", "非法行区间:" + rowStart + ".." + rowEnd);
1252
+ }
1253
+ if (r0 > r1) {
1254
+ throw new GitError("exit", "非法行区间(rowStart>rowEnd):" + r0 + ".." + r1);
1255
+ }
1256
+ // 切文件段 / hunk(与 extractHunkPatch 同一套解析规则)
1257
+ const sections = [];
1258
+ let cur = null;
1259
+ for (const line of diffText.split("\n")) {
1260
+ if (line.startsWith("diff --git ")) {
1261
+ cur = { headerLines: [line], hunks: [], curHunk: null };
1262
+ sections.push(cur);
1263
+ } else if (!cur) {
1264
+ continue;
1265
+ } else if (line.startsWith("@@")) {
1266
+ cur.curHunk = [line];
1267
+ cur.hunks.push(cur.curHunk);
1268
+ } else if (cur.curHunk) {
1269
+ cur.curHunk.push(line);
1270
+ } else {
1271
+ cur.headerLines.push(line);
1272
+ }
1273
+ }
1274
+ const unquote = (p) => (p && p.startsWith('"') && p.endsWith('"') ? p.slice(1, -1) : p);
1275
+ const wantNew = "b/" + file;
1276
+ const wantOld = "a/" + file;
1277
+ let target = null;
1278
+ for (const s of sections) {
1279
+ let newPath = null;
1280
+ let oldPath = null;
1281
+ for (const h of s.headerLines) {
1282
+ if (h.startsWith("+++ ")) newPath = unquote(h.slice(4));
1283
+ else if (h.startsWith("--- ")) oldPath = unquote(h.slice(4));
1284
+ }
1285
+ if (newPath === wantNew || oldPath === wantOld) { target = s; break; }
1286
+ if (s.headerLines[0] === "diff --git " + wantOld + " " + wantNew) { target = s; break; }
1287
+ }
1288
+ if (!target) throw new GitError("exit", "diff 中找不到文件:" + file);
1289
+ if (hIdx >= target.hunks.length) {
1290
+ throw new GitError("exit", "hunkIndex 越界:" + hIdx + "(该文件共 " + target.hunks.length + " 块)");
1291
+ }
1292
+ const hunk = target.hunks[hIdx];
1293
+ const header = hunk[0];
1294
+ const rows = hunk.slice(1);
1295
+ // 可寻址行 = ctx/add/del;标记行(\ ...)不计下标
1296
+ const addrIdx = [];
1297
+ for (let i = 0; i < rows.length; i++) {
1298
+ const t = rows[i][0];
1299
+ if (t === " " || t === "+" || t === "-") addrIdx.push(i);
1300
+ }
1301
+ if (r0 < 0 || r1 >= addrIdx.length) {
1302
+ throw new GitError("exit", "行区间越界:" + r0 + ".." + r1 + "(该 hunk 共 " + addrIdx.length + " 行)");
1303
+ }
1304
+ // 选中行 + 紧随其后的标记行( 等)
1305
+ const picked = [];
1306
+ for (let k = r0; k <= r1; k++) {
1307
+ const i = addrIdx[k];
1308
+ picked.push(rows[i]);
1309
+ if (rows[i + 1] !== undefined && rows[i + 1].startsWith("\\")) picked.push(rows[i + 1]);
1310
+ }
1311
+ // @@ 头重写
1312
+ const m = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/.exec(header);
1313
+ if (!m) throw new GitError("exit", "无法解析 hunk 头:" + header);
1314
+ const oldStart = Number(m[1]);
1315
+ const oldCount = m[2] === undefined ? 1 : Number(m[2]);
1316
+ const newStart = Number(m[3]);
1317
+ const newCount = m[4] === undefined ? 1 : Number(m[4]);
1318
+ const suffix = m[5] || "";
1319
+ let oldBefore = 0, newBefore = 0;
1320
+ for (let k = 0; k < r0; k++) {
1321
+ const t = rows[addrIdx[k]][0];
1322
+ if (t === " " || t === "-") oldBefore++;
1323
+ if (t === " " || t === "+") newBefore++;
1324
+ }
1325
+ let selOld = 0, selNew = 0;
1326
+ for (const line of picked) {
1327
+ const t = line[0];
1328
+ if (t === " " || t === "-") selOld++;
1329
+ if (t === " " || t === "+") selNew++;
1330
+ }
1331
+ const startFor = (origStart, origCount, before, count) => {
1332
+ if (count > 0) return origStart + before;
1333
+ if (origCount === 0) return origStart; // 该侧原本就是 0:start 已是"前一行"语义
1334
+ return Math.max(origStart + before - 1, 0);
1335
+ };
1336
+ const isFull = r0 === 0 && r1 === addrIdx.length - 1;
1337
+ const newHeader = isFull
1338
+ ? header // 整 hunk:与 extractHunkPatch 逐字节一致(计数/起点本就相等)
1339
+ : "@@ -" + startFor(oldStart, oldCount, oldBefore, selOld) + (selOld === 1 ? "" : "," + selOld)
1340
+ + " +" + startFor(newStart, newCount, newBefore, selNew) + (selNew === 1 ? "" : "," + selNew)
1341
+ + " @@" + suffix;
1342
+ const patch = target.headerLines.concat([newHeader]).concat(picked).join("\n");
1343
+ return patch.endsWith("\n") ? patch : patch + "\n";
1344
+ }
1345
+
1346
+ // 执行映射(§8.3):stage→apply --cached;unstage→apply --reverse --cached;
1347
+ // discard→apply --reverse。选区可能无上下文 → --unidiff-zero。
1348
+ // 与 hunkApply 同一道闸:safeJoin + cwd 必须在 probe.toplevel。
1349
+ export async function applyLine(cwd, opts = {}) {
1350
+ const file = opts.file;
1351
+ const scope = opts.scope;
1352
+ const mode = opts.mode;
1353
+ if (typeof file !== "string" || file.length === 0) {
1354
+ throw new GitError("exit", "lineApply 需要 file");
1355
+ }
1356
+ const key = scope + "/" + mode;
1357
+ if (key !== "unstaged/stage" && key !== "staged/unstage" && key !== "unstaged/discard") {
1358
+ throw new GitError("exit", "lineApply 非法 scope/mode 组合:" + key);
1359
+ }
1360
+ const probe = await probeRepo(cwd);
1361
+ if (!probe.isRepo) throw new GitError("not-a-repo", "lineApply:仓库不可用");
1362
+ safeJoin(probe.toplevel, file);
1363
+ const top = probe.toplevel;
1364
+ const diff = await getDiff(top, { scope: scope === "staged" ? "staged" : "worktree", file });
1365
+ const patch = extractLinePatch(diff.text, file, opts.hunkIndex, opts.rowStart, opts.rowEnd);
1366
+ const tmpFile = join(tmpdir(), "dsh-gm-line-" + process.pid + "-" + randomBytes(6).toString("hex") + ".patch");
1367
+ try {
1368
+ await writeFile(tmpFile, patch, "utf8");
1369
+ const args = ["apply", "--unidiff-zero", "--whitespace=nowarn"];
1370
+ if (mode === "stage") args.push("--cached");
1371
+ else if (mode === "unstage") args.push("--reverse", "--cached");
1372
+ else args.push("--reverse");
1373
+ args.push(tmpFile);
1374
+ await runGit(top, args);
1375
+ } finally {
1376
+ await rm(tmpFile, { force: true });
1377
+ }
1378
+ return getStatus(top);
1379
+ }
1380
+
1381
+ // ============================================================================
1382
+ // 变更:stageHunk(暂存此块,v2 §2.1)
1383
+ // getDiff(unstaged) → extractHunkPatch(不 reverse)→ git apply --cached
1384
+ // 把工作区该 hunk 的内容正向应用到 index(hunk 级暂存,不动其他块)
1385
+ // ============================================================================
1386
+
1387
+ export async function stageHunkFile(cwd, opts = {}) {
1388
+ const file = opts.file;
1389
+ if (typeof file !== "string" || file.length === 0) {
1390
+ throw new GitError("exit", "stageHunk 需要 file");
1391
+ }
1392
+ const probe = await probeRepo(cwd);
1393
+ if (!probe.isRepo) throw new GitError("not-a-repo", "stageHunk:仓库不可用");
1394
+ // 路径防护:与 hunkApply/discard 同一道闸(拒绝绝对路径 / .. 越界)
1395
+ safeJoin(probe.toplevel, file);
1396
+ // patch 内路径是仓库根相对路径,getDiff/git apply 都必须在 toplevel 跑
1397
+ const top = probe.toplevel;
1398
+ const diff = await getDiff(top, { scope: "worktree", file });
1399
+ const patch = extractHunkPatch(diff.text, file, opts.hunkIndex);
1400
+ const tmpFile = join(tmpdir(), "dsh-gm-stage-" + process.pid + "-" + randomBytes(6).toString("hex") + ".patch");
1401
+ try {
1402
+ await writeFile(tmpFile, patch, "utf8");
1403
+ await runGit(top, ["apply", "--cached", "--whitespace=nowarn", tmpFile]);
1404
+ } finally {
1405
+ await rm(tmpFile, { force: true });
1406
+ }
1407
+ return getStatus(top);
1408
+ }
1409
+
1410
+ // ============================================================================
1411
+ // 变更:stage / unstage / discard / commit
1412
+ // ============================================================================
1413
+
1414
+ // stage:all=true 时整仓暂存,可带 exclude(相对路径数组,仓库根相对)。
1415
+ // exclude 只在 all=true 时生效——files 模式按调用方给的路径逐条 add,忽略它。
1416
+ // 用途(子仓库支持 §5.1):「暂存全部」要把嵌套独立仓库目录排除掉,否则
1417
+ // `git add dir/` 会把它折成一个意外 gitlink(不在 .gitmodules 里的嵌入仓库)。
1418
+ export async function stageFiles(cwd, files, all, exclude) {
1419
+ if (all) {
1420
+ const ex = Array.isArray(exclude)
1421
+ ? exclude.filter((e) => typeof e === "string" && e.length > 0)
1422
+ : [];
1423
+ if (ex.length > 0) {
1424
+ await runGit(cwd, ["add", "-A", "--", "."].concat(ex.map((e) => ":(exclude)" + e)));
1425
+ } else {
1426
+ await runGit(cwd, ["add", "-A"]);
1427
+ }
1428
+ } else {
1429
+ if (!Array.isArray(files) || files.length === 0) throw new GitError("exit", "stage 需要 files 或 all=true");
1430
+ await runGit(cwd, ["add", "--"].concat(files));
1431
+ }
1432
+ return getStatus(cwd);
1433
+ }
1434
+
1435
+ export async function unstageFiles(cwd, files) {
1436
+ if (!Array.isArray(files) || files.length === 0) throw new GitError("exit", "unstage 需要 files");
1437
+ await runGit(cwd, ["restore", "--staged", "--"].concat(files));
1438
+ return getStatus(cwd);
1439
+ }
1440
+
1441
+ export async function discardFiles(cwd, files, includeUntracked) {
1442
+ if (!Array.isArray(files) || files.length === 0) throw new GitError("exit", "discard 需要 files");
1443
+ const probe = await probeRepo(cwd);
1444
+ if (!probe.isRepo) throw new GitError("not-a-repo", "discard:仓库不可用");
1445
+ // git rev-parse --git-dir 在 cwd=toplevel 时返回相对 ".git";existsSync 必须
1446
+ // 基于仓库 cwd 解析绝对路径,否则拿 DSH 进程 cwd 去判断 MERGE_HEAD 就废了。
1447
+ const gitDirAbs = resolve(cwd, probe.gitDir);
1448
+
1449
+ // 防护前置:先校验所有请求路径都在仓库根内(拒绝绝对路径与 .. 越界),
1450
+ // 再做任何破坏性动作。
1451
+ for (const f of files) safeJoin(probe.toplevel, f);
1452
+
1453
+ // 拆分:未跟踪 vs 已跟踪。git restore 对未跟踪路径直接报 "did not match",
1454
+ // 把整批操作炸掉 → 必须先分类。未跟踪清单来自 status(probeRepo 不含 status)。
1455
+ const st = await getStatus(cwd);
1456
+ const untrackedSet = new Set(st.untracked || []);
1457
+ const tracked = [];
1458
+ const toDelete = [];
1459
+ for (const f of files) {
1460
+ if (untrackedSet.has(f)) toDelete.push(f);
1461
+ else tracked.push(f);
1462
+ }
1463
+ if (tracked.length > 0) {
1464
+ await runGit(cwd, ["restore", "--worktree", "--"].concat(tracked));
1465
+ }
1466
+ const skipped = [];
1467
+ if (includeUntracked && toDelete.length > 0) {
1468
+ for (const f of toDelete) {
1469
+ const abs = safeJoin(probe.toplevel, f);
1470
+ // 嵌套仓库保护(子仓库支持 §5.1):路径自身或其子树里只要有 .git(文件=
1471
+ // 子模块的 gitdir 指针,目录=嵌套独立仓库),一律跳过不删——rm -rf 会把
1472
+ // 用户整个子仓库连历史一起抹掉,而 UI 上点的是「丢弃未跟踪文件」。
1473
+ if (containsGitDir(abs)) {
1474
+ skipped.push(f);
1475
+ continue;
1476
+ }
1477
+ try {
1478
+ // recursive:未跟踪清单来自 --untracked-files=normal,未跟踪目录是折叠
1479
+ // 形态("dir/"),不带 recursive 时 rm 对目录报 EISDIR 且被下面的吞错
1480
+ // 吃掉——用户点了「丢弃未跟踪文件」目录却还在(子仓库支持 P1)。
1481
+ // 防护顺序不变:containsGitDir 判定始终在删除之前。
1482
+ await rm(abs, { force: true, recursive: true });
1483
+ } catch (_) { /* missing 是正常的 */ }
1484
+ }
1485
+ }
1486
+ const status = await getStatus(cwd);
1487
+ // 同时带 merging/rebasing 给客户端(避免 banner 漏掉:见 self-test §4.7.4)
1488
+ status.merging = existsSync(join(gitDirAbs, "MERGE_HEAD"));
1489
+ status.rebasing = existsSync(join(gitDirAbs, "rebase-merge")) || existsSync(join(gitDirAbs, "rebase-apply"));
1490
+ // 仅非空时挂 key(JSON-safe:显式 undefined 的 own key 会被网关拒绝)。
1491
+ // Host 入口会把它提到 envelope 的 { status, skipped } 上。
1492
+ if (skipped.length > 0) status.skipped = skipped;
1493
+ return status;
1494
+ }
1495
+
1496
+ // 待删除路径里是否存在 .git(自身或子树):嵌套仓库保护(方案 §5.1)。
1497
+ // 有界扫描——未跟踪目录可能是个巨大的 clone,不设上限会让「丢弃未跟踪文件」卡住。
1498
+ // 预算取值(子仓库支持 P1:4/400 → 6/2000):删除改为递归之后,漏检的代价从
1499
+ // 「目录没删掉」变成「连子仓库历史一起删光」→ 向检出保守方向放宽;预算仍有界,
1500
+ // 且 readdirSync 极快(2000 项是毫秒级),不会成为 UI 卡顿源。
1501
+ const NESTED_SCAN_MAX_DEPTH = 6;
1502
+ const NESTED_SCAN_MAX_ENTRIES = 2000;
1503
+ function containsGitDir(abs) {
1504
+ let budget = NESTED_SCAN_MAX_ENTRIES;
1505
+ const walk = (dir, depth) => {
1506
+ if (budget <= 0 || depth > NESTED_SCAN_MAX_DEPTH) return false;
1507
+ if (existsSync(join(dir, ".git"))) return true;
1508
+ if (depth === NESTED_SCAN_MAX_DEPTH) return false;
1509
+ let entries;
1510
+ try {
1511
+ entries = readdirSync(dir, { withFileTypes: true });
1512
+ } catch (_) {
1513
+ return false; // 不是目录 / 读不了 → 交给调用方的 rm 处理
1514
+ }
1515
+ for (const ent of entries) {
1516
+ if (!ent.isDirectory()) continue;
1517
+ if (budget-- <= 0) return false;
1518
+ if (walk(join(dir, ent.name), depth + 1)) return true;
1519
+ }
1520
+ return false;
1521
+ };
1522
+ return walk(abs, 0);
1523
+ }
1524
+
1525
+ export async function commitStaged(cwd, message, amend) {
1526
+ if (typeof message !== "string" || message.length === 0) throw new GitError("exit", "commit 需要 message");
1527
+ const args = ["commit", "-m", message];
1528
+ if (amend) args.push("--amend");
1529
+ await runGit(cwd, args);
1530
+ const sha = (await runGit(cwd, ["rev-parse", "--short=12", "HEAD"])).stdout.trim();
1531
+ const status = await getStatus(cwd);
1532
+ return Object.assign({ commit: sha }, { status });
1533
+ }
1534
+
1535
+ // ============================================================================
1536
+ // 变更:分支 + merge + 解决
1537
+ // ============================================================================
1538
+
1539
+ export async function createBranch(cwd, name, startPoint, checkout) {
1540
+ if (typeof name !== "string" || name.length === 0) throw new GitError("exit", "branchCreate 需要 name");
1541
+ if (checkout) {
1542
+ await runGit(cwd, ["switch", "-c", name].concat(startPoint ? [startPoint] : []));
1543
+ } else {
1544
+ await runGit(cwd, ["branch", name].concat(startPoint ? [startPoint] : []));
1545
+ }
1546
+ return getStatus(cwd);
1547
+ }
1548
+
1549
+ export async function switchBranch(cwd, name) {
1550
+ if (typeof name !== "string" || name.length === 0) throw new GitError("exit", "checkout 需要 name");
1551
+ await runGit(cwd, ["switch", name]);
1552
+ return getStatus(cwd);
1553
+ }
1554
+
1555
+ export async function deleteBranch(cwd, name, force) {
1556
+ if (typeof name !== "string" || name.length === 0) throw new GitError("exit", "branchDelete 需要 name");
1557
+ await runGit(cwd, ["branch", force ? "-D" : "-d", name]);
1558
+ return getStatus(cwd);
1559
+ }
1560
+
1561
+ export async function renameBranch(cwd, oldName, newName) {
1562
+ await runGit(cwd, ["branch", "-m", oldName, newName]);
1563
+ return getStatus(cwd);
1564
+ }
1565
+
1566
+ export async function mergeBranch(cwd, branch, noFf) {
1567
+ if (typeof branch !== "string") throw new GitError("exit", "merge 需要 branch");
1568
+ const args = ["merge", "--no-edit"];
1569
+ if (noFf) args.push("--no-ff");
1570
+ args.push(branch);
1571
+ let merged = true;
1572
+ try {
1573
+ await runGit(cwd, args);
1574
+ } catch (e) {
1575
+ if (e instanceof GitError && e.kind === "exit" && /conflict/i.test(e.stderr || "")) {
1576
+ merged = false;
1577
+ } else if (e instanceof GitError && e.kind === "exit") {
1578
+ // 自动判断:exit 但无 conflict 关键词 → 用 status 看 conflicted
1579
+ const st = await getStatus(cwd);
1580
+ if (st.conflicted.length > 0) merged = false;
1581
+ else throw e;
1582
+ } else {
1583
+ throw e;
1584
+ }
1585
+ }
1586
+ const status = await getStatus(cwd);
1587
+ return { merged, status };
1588
+ }
1589
+
1590
+ export async function abortMerge(cwd) {
1591
+ // 按进行中的操作类型选择 abort 命令(P3-A §8.2 优先级):
1592
+ // rebase > MERGE_HEAD > CHERRY_PICK_HEAD > REVERT_HEAD > unmerged 兜底 > 抛错。
1593
+ // 各操作状态互斥,`git merge --abort` 对 cherry-pick/rebase 状态无效(反之亦然)。
1594
+ const probe = await probeRepo(cwd);
1595
+ if (!probe.isRepo) throw new GitError("not-a-repo", "abortMerge:仓库不可用");
1596
+ const gitDirAbs = resolve(cwd, probe.gitDir);
1597
+ const inRebase = existsSync(join(gitDirAbs, "rebase-merge")) || existsSync(join(gitDirAbs, "rebase-apply"));
1598
+ const inMerge = existsSync(join(gitDirAbs, "MERGE_HEAD"));
1599
+ const inCherryPick = existsSync(join(gitDirAbs, "CHERRY_PICK_HEAD"));
1600
+ const inRevert = existsSync(join(gitDirAbs, "REVERT_HEAD"));
1601
+ if (inRebase) {
1602
+ await runGit(cwd, ["rebase", "--abort"]);
1603
+ await cleanupRebaseQueue(gitDirAbs); // rebase 中止:squash 消息队列作废
1604
+ } else if (inMerge) {
1605
+ await runGit(cwd, ["merge", "--abort"]);
1606
+ } else if (inCherryPick) {
1607
+ await runGit(cwd, ["cherry-pick", "--abort"]);
1608
+ } else if (inRevert) {
1609
+ await runGit(cwd, ["revert", "--abort"]);
1610
+ } else {
1611
+ // 兜底(Lead 裁决 2026-09-29,stash pop/apply 冲突路径):stash 冲突不写任何
1612
+ // 操作 HEAD 状态文件,只留 unmerged index 条目。对这些冲突文件
1613
+ // `git restore --source=HEAD --staged --worktree`(文件清单来自 status 的
1614
+ // unmerged 条目并过 safeJoin),其他文件已套用的改动保留、stash 条目保留。
1615
+ // 既无状态文件又无 unmerged → 照旧抛错,防止误点把 staged 内容干出"空操作"。
1616
+ const st = await getStatus(cwd);
1617
+ const unmerged = (st.conflicted || []).map((e) => e.path);
1618
+ if (unmerged.length > 0) {
1619
+ for (const f of unmerged) safeJoin(probe.toplevel, f);
1620
+ await runGit(probe.toplevel, ["restore", "--source=HEAD", "--staged", "--worktree", "--"].concat(unmerged));
1621
+ } else {
1622
+ throw new GitError("exit", "当前没有可中止的合并/cherry-pick/revert 操作");
1623
+ }
1624
+ }
1625
+ return getStatus(cwd);
1626
+ }
1627
+
1628
+ export async function continueMerge(cwd) {
1629
+ // 守门:MERGE_HEAD / CHERRY_PICK_HEAD / REVERT_HEAD / rebase 目录都不存在时,
1630
+ // `git commit --no-edit` 会提交当前 staged 内容,用户误点会得到一个
1631
+ // "意外空 commit"——必须先校验。
1632
+ // cherry-pick/revert 冲突解决后同样由 `git commit --no-edit` 完成
1633
+ //(MERGE_MSG 已备好原提交信息,commit 成功自动清状态文件)。
1634
+ // P3-A §8.2 状态分派:rebase-merge/rebase-apply → `git rebase --continue`。
1635
+ const probe = await probeRepo(cwd);
1636
+ if (!probe.isRepo) throw new GitError("not-a-repo", "continueMerge:仓库不可用");
1637
+ const gitDirAbs = resolve(cwd, probe.gitDir);
1638
+ const inRebase = existsSync(join(gitDirAbs, "rebase-merge")) || existsSync(join(gitDirAbs, "rebase-apply"));
1639
+ const inCommit = existsSync(join(gitDirAbs, "MERGE_HEAD"))
1640
+ || existsSync(join(gitDirAbs, "CHERRY_PICK_HEAD"))
1641
+ || existsSync(join(gitDirAbs, "REVERT_HEAD"));
1642
+ if (!inRebase && !inCommit) {
1643
+ throw new GitError("exit", "当前不在合并/变基/cherry-pick 中,无可继续的操作");
1644
+ }
1645
+ if (inRebase) {
1646
+ // 重新挂载 squash 消息队列(rebaseRun 落在 gitDir、跨进程存活),
1647
+ // 保证冲突之后的 squash 步骤仍按队列顺序替换提交信息
1648
+ const armed = await rebaseMessageQueueEnv(gitDirAbs);
1649
+ try {
1650
+ await runGit(cwd, ["rebase", "--continue"], { env: armed.env });
1651
+ } finally {
1652
+ if (armed.scriptPath) await rm(armed.scriptPath, { force: true });
1653
+ }
1654
+ if (!isRebasing(gitDirAbs)) await cleanupRebaseQueue(gitDirAbs);
1655
+ } else {
1656
+ await runGit(cwd, ["commit", "--no-edit"]);
1657
+ }
1658
+ return getStatus(cwd);
1659
+ }
1660
+
1661
+ // cherry-pick 单个提交到当前分支。
1662
+ // 冲突时不抛错(与 mergeBranch 同款契约):返回 { picked:false, status },
1663
+ // 仓库进入 CHERRY_PICK_HEAD 状态 → 冲突页解决后「继续」即完成 pick,
1664
+ // 「中止」走 abortMerge 的 cherry-pick --abort 分支。
1665
+ // 其他失败(空 pick、工作区脏导致无法应用等)原样抛 GitError。
1666
+ export async function cherryPickCommit(cwd, sha) {
1667
+ // sha 白名单校验:虽然 execFile argv 不拼 shell,仍收紧到纯十六进制
1668
+ if (typeof sha !== "string" || !/^[0-9a-fA-F]{4,64}$/.test(sha)) {
1669
+ throw new GitError("exit", "cherryPick 需要合法 commit sha(4-64 位十六进制)");
1670
+ }
1671
+ let picked = true;
1672
+ try {
1673
+ await runGit(cwd, ["cherry-pick", sha]);
1674
+ } catch (e) {
1675
+ if (e instanceof GitError && e.kind === "exit") {
1676
+ const st = await getStatus(cwd);
1677
+ if (st.conflicted.length > 0 || /conflict/i.test(e.stderr || "")) {
1678
+ picked = false;
1679
+ } else {
1680
+ throw e;
1681
+ }
1682
+ } else {
1683
+ throw e;
1684
+ }
1685
+ }
1686
+ const status = await getStatus(cwd);
1687
+ return { picked, status };
1688
+ }
1689
+
1690
+ // ============================================================================
1691
+ // 冲突内容 + 解决
1692
+ // ============================================================================
1693
+
1694
+ export async function getConflictContent(cwd, file) {
1695
+ if (typeof file !== "string") throw new GitError("exit", "conflictContent 需要 file");
1696
+ const probe = await probeRepo(cwd);
1697
+ if (!probe.isRepo) throw new GitError("not-a-repo", "conflictContent:仓库不可用");
1698
+ const out = { ours: undefined, theirs: undefined, base: undefined, worktree: undefined };
1699
+ const read = async (label, stage) => {
1700
+ try {
1701
+ const r = await runGit(cwd, ["show", ":" + stage + ":" + file]);
1702
+ out[label] = r.stdout;
1703
+ } catch (e) {
1704
+ if (e instanceof GitError && e.kind === "exit") {
1705
+ out[label] = undefined; // 阶段不存在(常见:删文件时 stage 不存在)
1706
+ } else throw e;
1707
+ }
1708
+ };
1709
+ await read("base", 1);
1710
+ await read("ours", 2);
1711
+ await read("theirs", 3);
1712
+ try {
1713
+ const abs = safeJoin(probe.toplevel, file);
1714
+ out.worktree = await readFile(abs, "utf8");
1715
+ } catch (_) { out.worktree = undefined; }
1716
+ return out;
1717
+ }
1718
+
1719
+ // 该路径当前的未合并条目(`git ls-files -u -- <file>`):
1720
+ // 每行「<mode> <sha> <stage>\t<path>」,解析成 { mode, sha, stage }[]。
1721
+ // 必须在仓库 toplevel 跑:ls-files 的 pathspec 以仓库根下的相对路径解释,
1722
+ // cwd 在子目录时传同一个相对路径匹配不到。非仓库 / 无未合并条目 → 空数组
1723
+ // (调用方据此回落普通文本冲突逻辑,绝不因此中断既有路径)。
1724
+ async function readUnmergedEntries(toplevel, file) {
1725
+ if (!toplevel) return [];
1726
+ let stdout = "";
1727
+ try {
1728
+ stdout = (await runGit(toplevel, ["ls-files", "-u", "--", file])).stdout;
1729
+ } catch (_) {
1730
+ return []; // 非仓库 / 该路径无未合并条目
1731
+ }
1732
+ const out = [];
1733
+ for (const line of String(stdout || "").split("\n")) {
1734
+ const m = /^(\d{6})\s+([0-9a-f]{40})\s+([123])\t/.exec(line);
1735
+ if (m) out.push({ mode: m[1], sha: m[2], stage: Number(m[3]) });
1736
+ }
1737
+ return out;
1738
+ }
1739
+
1740
+ // 把某个 gitlink 冲突解析到指定指针(子仓库支持 P1)。
1741
+ //
1742
+ // 为什么不用 `git checkout --ours/--theirs -- <gitlink>`(实测 git 2.53):
1743
+ // 对 mode 160000 的未合并条目,这两个选项对 index 是**静默空操作**——三个 stage
1744
+ // 原样留着,退出码 0、无输出;随后的 `git add` 记的是子仓库**工作区当前 HEAD**
1745
+ // (合并冲突时 git 已把子模块切到某一侧),于是「选我们的」实际落成对方的指针。
1746
+ // 这里改用两条底层命令把「选哪一侧」表达准确:
1747
+ // 1. index:`git update-index --cacheinfo 160000,<sha>,<file>` 直接把选中的
1748
+ // stage2/stage3 指针写成 stage0——这就是子仓库被 checkout 到该 sha 后
1749
+ // `git add` 会写下的东西,冲突随之解除;选中侧是「删除」(该 stage 不存在)
1750
+ // 时用 `--force-remove` 把 gitlink 条目从 index 摘掉。
1751
+ // 2. 子仓库工作区:best-effort 同步到同一指针,否则 status 会留下
1752
+ // "modified: libs/base (new commits)" 漂移。**只在子仓库干净时**切,
1753
+ // 有本地改动/对象缺失一律保持原样(漂移可见可恢复,绝不丢弃子仓库里的工作)。
1754
+ async function resolveGitlinkConflict(toplevel, file, subAbs, stage, unmerged) {
1755
+ const picked = unmerged.find((e) => e.stage === stage && e.mode === "160000");
1756
+ if (!picked) {
1757
+ // 选中的一侧删掉了这个子模块 → 解析即「index 里不再有这个 gitlink」
1758
+ await runGit(toplevel, ["update-index", "--force-remove", "--", file]);
1759
+ return;
1760
+ }
1761
+ await runGit(toplevel, ["update-index", "--add", "--cacheinfo", "160000," + picked.sha + "," + file]);
1762
+ try {
1763
+ const head = (await runGit(subAbs, ["rev-parse", "HEAD"])).stdout.trim();
1764
+ if (head === picked.sha) return;
1765
+ if ((await runGit(subAbs, ["status", "--porcelain"])).stdout.trim().length > 0) return;
1766
+ await runGit(subAbs, ["checkout", "--detach", picked.sha]);
1767
+ } catch (_) { /* 子仓库不可用/对象不在本地:index 已解析,漂移由用户自行处理 */ }
1768
+ }
1769
+
1770
+ export async function resolveConflictFile(cwd, file, strategy, content) {
1771
+ if (typeof file !== "string") throw new GitError("exit", "resolveConflict 需要 file");
1772
+ // probe 只跑一次:gitlink 分派与 custom 的路径防护共用(AGENTS.md:不重复 probe)
1773
+ const probe = await probeRepo(cwd);
1774
+
1775
+ // gitlink(子模块指针,index mode 160000)冲突分派(子仓库支持 P1 / 方案 §2.3):
1776
+ // 冲突对象是「指针」不是文件内容,没有可编辑文本 → custom 直接拒绝;
1777
+ // ours = stage2、theirs = stage3。其余 strategy 沿用原报错。
1778
+ const unmerged = probe && probe.isRepo ? await readUnmergedEntries(probe.toplevel, file) : [];
1779
+ if (unmerged.some((e) => e.mode === "160000")) {
1780
+ if (strategy === "custom") {
1781
+ throw new GitError("exit", "子模块指针冲突不支持手动编辑内容");
1782
+ }
1783
+ if (strategy !== "ours" && strategy !== "theirs") {
1784
+ throw new GitError("exit", "未知 strategy:" + strategy);
1785
+ }
1786
+ const abs = safeJoin(probe.toplevel, file); // 路径防护(绝对路径 / .. 越界拒绝),与 custom 同款
1787
+ await resolveGitlinkConflict(probe.toplevel, file, abs, strategy === "ours" ? 2 : 3, unmerged);
1788
+ return getStatus(cwd);
1789
+ }
1790
+
1791
+ if (strategy === "ours") {
1792
+ await runGit(cwd, ["checkout", "--ours", "--", file]);
1793
+ await runGit(cwd, ["add", "--", file]);
1794
+ } else if (strategy === "theirs") {
1795
+ await runGit(cwd, ["checkout", "--theirs", "--", file]);
1796
+ await runGit(cwd, ["add", "--", file]);
1797
+ } else if (strategy === "custom") {
1798
+ if (!probe.isRepo) throw new GitError("not-a-repo", "resolveConflict:仓库不可用");
1799
+ const abs = safeJoin(probe.toplevel, file);
1800
+ await writeFile(abs, content || "", "utf8");
1801
+ await runGit(cwd, ["add", "--", file]);
1802
+ } else {
1803
+ throw new GitError("exit", "未知 strategy:" + strategy);
1804
+ }
1805
+ return getStatus(cwd);
1806
+ }
1807
+
1808
+ // ============================================================================
1809
+ // 解析器:parseStashList(v2 §2.2)
1810
+ // 输入:git stash list -z --format=%gd%x1f%gs%x1f%ct(记录以 \0 分隔)
1811
+ // 输出 stashEntry:{ index, ref, subject, at }
1812
+ // ============================================================================
1813
+
1814
+ const STASH_FMT = "%gd%x1f%gs%x1f%ct";
1815
+
1816
+ export function parseStashList(text) {
1817
+ const out = [];
1818
+ if (!text) return out;
1819
+ for (const rec of text.split("\0")) {
1820
+ if (rec.trim().length === 0) continue;
1821
+ const parts = rec.split("\x1f");
1822
+ if (parts.length < 3) continue;
1823
+ const [ref, subject, atRaw] = parts;
1824
+ const m = /stash@\{(\d+)\}/.exec(ref);
1825
+ out.push({
1826
+ index: m ? Number(m[1]) : out.length,
1827
+ ref,
1828
+ subject,
1829
+ at: Number(atRaw) || 0,
1830
+ });
1831
+ }
1832
+ return out;
1833
+ }
1834
+
1835
+ export async function getStashes(cwd) {
1836
+ const r = await runGit(cwd, ["stash", "list", "-z", "--format=" + STASH_FMT]);
1837
+ return { stashes: parseStashList(r.stdout) };
1838
+ }
1839
+
1840
+ export async function stashPush(cwd, message, includeUntracked) {
1841
+ const args = ["stash", "push"];
1842
+ if (includeUntracked) args.push("-u");
1843
+ if (typeof message === "string" && message.length > 0) args.push("-m", message);
1844
+ await runGit(cwd, args);
1845
+ return getStashes(cwd);
1846
+ }
1847
+
1848
+ // pop / apply 共用:冲突不抛错(与 mergeBranch/revertCommit 同款契约),
1849
+ // status.conflicted 非空即把最新 status 交回客户端走冲突页;
1850
+ // 其他失败(坏序号等)原样抛 GitError,不吞错误。
1851
+ async function stashApplyish(cwd, cmd, index) {
1852
+ const sel = "stash@{" + checkStashIndex(index) + "}";
1853
+ let err = null;
1854
+ try {
1855
+ await runGit(cwd, ["stash", cmd, sel]);
1856
+ } catch (e) {
1857
+ if (e instanceof GitError && e.kind === "exit") err = e;
1858
+ else throw e;
1859
+ }
1860
+ const status = await getStatus(cwd);
1861
+ if (err && status.conflicted.length === 0) throw err;
1862
+ return status;
1863
+ }
1864
+
1865
+ export async function stashPop(cwd, index) {
1866
+ return stashApplyish(cwd, "pop", index);
1867
+ }
1868
+
1869
+ export async function stashApply(cwd, index) {
1870
+ return stashApplyish(cwd, "apply", index);
1871
+ }
1872
+
1873
+ export async function stashDrop(cwd, index) {
1874
+ await runGit(cwd, ["stash", "drop", "stash@{" + checkStashIndex(index) + "}"]);
1875
+ return getStashes(cwd);
1876
+ }
1877
+
1878
+ export async function stashClear(cwd) {
1879
+ await runGit(cwd, ["stash", "clear"]);
1880
+ return getStashes(cwd);
1881
+ }
1882
+
1883
+ // ============================================================================
1884
+ // 解析器:parseTagList(v2 §2.2)
1885
+ // 输入:git for-each-ref --format=<TAG_FMT> refs/tags
1886
+ // TAG_FMT 每条 7 字段、%00 分隔、条目以换行收尾(contents 可多行,
1887
+ // 不能按换行切记录)→ 按 \0 切成 7 字段一组;组首 chunk 带上一条的换行前缀。
1888
+ // 输出 tagInfo:{ name, sha, short, subject, at, annotated, message? }
1889
+ // ============================================================================
1890
+
1891
+ const TAG_FMT =
1892
+ "%(refname:short)%00%(objectname)%00%(objecttype)%00%(*objectname)" +
1893
+ "%00%(creatordate:unix)%00%(subject)%00%(contents)%00";
1894
+
1895
+ export function parseTagList(text) {
1896
+ const out = [];
1897
+ if (!text) return out;
1898
+ const chunks = text.split("\0");
1899
+ for (let i = 0; i + 6 < chunks.length; i += 7) {
1900
+ const name = chunks[i].replace(/^[\r\n]+/, "");
1901
+ const objectname = chunks[i + 1];
1902
+ const objecttype = chunks[i + 2];
1903
+ const deref = chunks[i + 3];
1904
+ const at = Number(chunks[i + 4]) || 0;
1905
+ const subject = chunks[i + 5].replace(/^[\r\n]+/, "");
1906
+ const contents = chunks[i + 6].replace(/^[\r\n]+/, "");
1907
+ if (!name) continue;
1908
+ const annotated = objecttype === "tag";
1909
+ // annotated tag 的 ref 指向 tag 对象,%(*objectname) 才是提交 sha
1910
+ const sha = (annotated && deref ? deref : objectname) || objectname || "";
1911
+ const item = {
1912
+ name,
1913
+ sha,
1914
+ short: sha.slice(0, 7),
1915
+ subject: subject.trim(),
1916
+ at,
1917
+ annotated,
1918
+ };
1919
+ // message 只在 annotated 且有内容时挂(网关 JSON-safe:不挂 undefined key)
1920
+ const message = contents.replace(/\r\n/g, "\n").replace(/\s+$/, "");
1921
+ if (annotated && message) item.message = message;
1922
+ out.push(item);
1923
+ }
1924
+ return out;
1925
+ }
1926
+
1927
+ export async function getTags(cwd) {
1928
+ const r = await runGit(cwd, ["for-each-ref", "--format=" + TAG_FMT, "refs/tags"]);
1929
+ return { tags: parseTagList(r.stdout) };
1930
+ }
1931
+
1932
+ export async function createTag(cwd, name, sha, message, force) {
1933
+ checkRefName(name, "tagCreate");
1934
+ const annotated = typeof message === "string" && message.trim().length > 0;
1935
+ const args = ["tag"];
1936
+ if (annotated) args.push("-a", "-m", message);
1937
+ if (force) args.push("-f");
1938
+ args.push(name);
1939
+ if (sha) args.push(checkRev(sha, "tagCreate"));
1940
+ await runGit(cwd, args);
1941
+ return getTags(cwd);
1942
+ }
1943
+
1944
+ export async function deleteTag(cwd, name) {
1945
+ checkRefName(name, "tagDelete");
1946
+ await runGit(cwd, ["tag", "-d", name]);
1947
+ return getTags(cwd);
1948
+ }
1949
+
1950
+ // ============================================================================
1951
+ // 变更:reset(v2 §2.2)/ revert
1952
+ // ============================================================================
1953
+
1954
+ // reset 当前分支。mode 只允许 soft|mixed|hard(枚举校验,防 "-" 注入);
1955
+ // target 走 checkResetTarget 白名单(sha / HEAD / HEAD~n / @{...})。
1956
+ // hard 本身不做 UI 确认——确认是 client 的职责(契约 §2.4)。
1957
+ export async function resetRepo(cwd, mode, target) {
1958
+ const m = mode === "soft" || mode === "mixed" || mode === "hard" ? mode : null;
1959
+ if (!m) throw new GitError("exit", "reset mode 只允许 soft|mixed|hard,收到:" + mode);
1960
+ const t = checkResetTarget(target);
1961
+ await runGit(cwd, ["reset", "--" + m, t]);
1962
+ return getStatus(cwd);
1963
+ }
1964
+
1965
+ // revert 单个提交。冲突不抛错(与 cherryPickCommit 同款契约):
1966
+ // 返回 { reverted:false, status },仓库进 REVERT_HEAD 态 → 冲突页解决后
1967
+ // mergeContinue 完成、abortMerge 的 revert --abort 分支中止。
1968
+ // 其他失败原样抛 GitError。
1969
+ export async function revertCommit(cwd, sha) {
1970
+ if (typeof sha !== "string" || !/^[0-9a-fA-F]{4,64}$/.test(sha)) {
1971
+ throw new GitError("exit", "revert 需要合法 commit sha(4-64 位十六进制)");
1972
+ }
1973
+ let reverted = true;
1974
+ let err = null;
1975
+ try {
1976
+ await runGit(cwd, ["revert", "--no-edit", sha]);
1977
+ } catch (e) {
1978
+ if (e instanceof GitError && e.kind === "exit") { reverted = false; err = e; }
1979
+ else throw e;
1980
+ }
1981
+ const status = await getStatus(cwd);
1982
+ if (!reverted) {
1983
+ // 只有"冲突 / revert 进行中(REVERT_HEAD 在场)"按不抛错处理;其余透传
1984
+ const probe = await probeRepo(cwd);
1985
+ const inRevert = probe.isRepo
1986
+ && existsSync(join(resolve(cwd, probe.gitDir), "REVERT_HEAD"));
1987
+ if (!inRevert && status.conflicted.length === 0) throw err;
1988
+ }
1989
+ return { reverted, status };
1990
+ }
1991
+
1992
+ // ============================================================================
1993
+ // 解析器:parseBlame(v2 §2.2)
1994
+ // 输入:git blame --porcelain 输出
1995
+ // 组头:"<sha> <origLine> <finalLine> [<numLines>]" + 元数据块(author/author-time/...)
1996
+ // 组内后续行:同 sha 短头 + 直接 "\t<原文>"。元数据只在组头出现一次,
1997
+ // 之后同 sha 的行沿用最近一次的 author/at。
1998
+ // 输出 blameLine:{ sha, short, author, at, line, text }
1999
+ // ============================================================================
2000
+
2001
+ export function parseBlame(text) {
2002
+ const out = [];
2003
+ if (!text) return out;
2004
+ let author = "";
2005
+ let at = 0;
2006
+ let head = null;
2007
+ for (const raw of text.split("\n")) {
2008
+ if (raw.startsWith("\t")) {
2009
+ if (head) {
2010
+ out.push({
2011
+ sha: head.sha,
2012
+ short: head.sha.slice(0, 7),
2013
+ author,
2014
+ at,
2015
+ line: head.finalLine,
2016
+ text: raw.slice(1),
2017
+ });
2018
+ head = null;
2019
+ }
2020
+ continue;
2021
+ }
2022
+ const m = /^([0-9a-f]{40}) (\d+) (\d+)(?: (\d+))?$/.exec(raw);
2023
+ if (m) {
2024
+ head = { sha: m[1], finalLine: Number(m[3]) };
2025
+ continue;
2026
+ }
2027
+ if (raw.startsWith("author ")) author = raw.slice(7);
2028
+ else if (raw.startsWith("author-time ")) at = Number(raw.slice(12)) || 0;
2029
+ }
2030
+ return out;
2031
+ }
2032
+
2033
+ const BLAME_LINE_CAP = 5000; // UI 一次渲染上限(契约 §3.7)
2034
+
2035
+ export async function getBlame(cwd, opts = {}) {
2036
+ const file = opts.file;
2037
+ if (typeof file !== "string" || file.length === 0) {
2038
+ throw new GitError("exit", "blame 需要 file");
2039
+ }
2040
+ const probe = await probeRepo(cwd);
2041
+ if (!probe.isRepo) throw new GitError("not-a-repo", "blame:仓库不可用");
2042
+ safeJoin(probe.toplevel, file);
2043
+ const top = probe.toplevel;
2044
+ const args = ["blame", "--porcelain"];
2045
+ if (opts.start != null || opts.end != null) {
2046
+ const start = opts.start == null ? 1 : Number(opts.start);
2047
+ const end = opts.end == null ? start : Number(opts.end);
2048
+ if (!Number.isInteger(start) || start < 1 || !Number.isInteger(end) || end < start) {
2049
+ throw new GitError("exit", "blame 行区间非法:" + opts.start + ".." + opts.end);
2050
+ }
2051
+ args.push("-L", start + "," + end);
2052
+ }
2053
+ if (opts.ref) args.push(checkRev(opts.ref, "blame"));
2054
+ args.push("--", file);
2055
+ const r = await runGit(top, args);
2056
+ const all = parseBlame(r.stdout);
2057
+ const truncated = all.length > BLAME_LINE_CAP;
2058
+ return { lines: truncated ? all.slice(0, BLAME_LINE_CAP) : all, truncated };
2059
+ }
2060
+
2061
+ // ============================================================================
2062
+ // 变更/查询:diffRange(v2 §2.2 范围对比)
2063
+ // 请求 { from, to?, file?, kind? },kind ∈ patch|stat(缺省 patch)
2064
+ // to 缺省时与工作区比较(git diff <from>);file 走 safeJoin,在 toplevel 跑
2065
+ // ============================================================================
2066
+
2067
+ export async function getDiffRange(cwd, opts = {}) {
2068
+ const from = checkRev(opts.from, "diffRange");
2069
+ const to = opts.to ? checkRev(opts.to, "diffRange") : null;
2070
+ const kind = opts.kind === "stat" ? "stat" : "patch";
2071
+ const file = typeof opts.file === "string" && opts.file.length > 0 ? opts.file : null;
2072
+ const probe = await probeRepo(cwd);
2073
+ if (!probe.isRepo) throw new GitError("not-a-repo", "diffRange:仓库不可用");
2074
+ const top = probe.toplevel;
2075
+ if (file) safeJoin(top, file);
2076
+ const args = ["diff"];
2077
+ if (kind === "stat") args.push("--stat");
2078
+ else args.push("-U3");
2079
+ args.push(from);
2080
+ if (to) args.push(to);
2081
+ if (file) args.push("--", file);
2082
+ let text = "";
2083
+ try {
2084
+ const r = await runGit(top, args);
2085
+ text = r.stdout;
2086
+ } catch (e) {
2087
+ if (e instanceof GitError && e.kind === "exit" && e.exitCode === 1 && e.stdout) {
2088
+ text = e.stdout; // exit 1 + 有 stdout = 有差异
2089
+ } else {
2090
+ throw e;
2091
+ }
2092
+ }
2093
+ if (text.length > DIFF_TEXT_CAP) {
2094
+ text = text.slice(0, DIFF_TEXT_CAP);
2095
+ return { text, truncated: true };
2096
+ }
2097
+ return { text, truncated: false };
2098
+ }
2099
+
2100
+ // ============================================================================
2101
+ // 解析器:parseReflog(v2 §2.2)
2102
+ // 输入:git reflog -z --format=%H%x1f%h%x1f%gD%x1f%gs%x1f%ct(记录 \0 分隔)
2103
+ // 输出 reflogEntry:{ sha, short, selector, message, at }
2104
+ // ============================================================================
2105
+
2106
+ const REFLOG_FMT = "%H%x1f%h%x1f%gD%x1f%gs%x1f%ct";
2107
+
2108
+ export function parseReflog(text) {
2109
+ const out = [];
2110
+ if (!text) return out;
2111
+ for (const rec of text.split("\0")) {
2112
+ if (rec.length === 0) continue;
2113
+ const parts = rec.split("\x1f");
2114
+ if (parts.length < 5) continue;
2115
+ const [sha, short, selector, message, at] = parts;
2116
+ out.push({ sha, short, selector, message, at: Number(at) || 0 });
2117
+ }
2118
+ return out;
2119
+ }
2120
+
2121
+ export async function getReflog(cwd, opts = {}) {
2122
+ let limit = Number(opts.limit);
2123
+ if (!Number.isInteger(limit) || limit <= 0) limit = 50;
2124
+ if (limit > 5000) limit = 5000;
2125
+ let raw;
2126
+ try {
2127
+ raw = await runGit(cwd, ["reflog", "-z", "--format=" + REFLOG_FMT, "-n", String(limit)]);
2128
+ } catch (e) {
2129
+ if (e instanceof GitError && e.kind === "exit") {
2130
+ const msg = (e.stderr || e.message || "").toLowerCase();
2131
+ if (/does not have any commits|unknown revision|no reflog/.test(msg)) {
2132
+ return { entries: [] };
2133
+ }
2134
+ throw e;
2135
+ }
2136
+ throw e;
2137
+ }
2138
+ return { entries: parseReflog(raw.stdout) };
2139
+ }
2140
+
2141
+ // ============================================================================
2142
+ // P3-A(§8.1/§8.2):交互式 rebase 全家 + 状态分派
2143
+ //
2144
+ // GIT_SEQUENCE_EDITOR / GIT_EDITOR 机制:git 用 `sh -c '<editor> "$@"' <editor> <file>`
2145
+ // 启动编辑器,editor 值天然是 sh 命令串。我们只构造「带引号的解释器 + 脚本 + 模式」
2146
+ // 三段固定形态(shQuote 只做双引号转义,无任何 shell 逻辑拼接),脚本本体是写到
2147
+ // tmpdir 的 node 脚本,业务数据全走环境变量与文件:
2148
+ // seq 模式:把 DSH_GM_TODO_SRC 指向的 todo 文件复制到 git-rebase-todo(替换默认 todo)
2149
+ // msg 模式:从 DSH_GM_MSG_QUEUE 队列取下一条 message 覆盖提交信息文件,
2150
+ // 非空才覆盖(空/越界保留 git 默认合并文本)——squash+message 替换语义
2151
+ // 队列文件放 gitDir(跨进程存活):冲突解决后 mergeContinue 重新挂载同一队列,
2152
+ // 多条 squash 消息按 todo 顺序依次消费(Lead 裁决 Q2)。
2153
+ // ============================================================================
2154
+
2155
+ const REBASE_EDITOR_SCRIPT = [
2156
+ 'import { readFileSync, writeFileSync, copyFileSync } from "node:fs";',
2157
+ "const mode = process.argv[2];",
2158
+ "const target = process.argv[process.argv.length - 1];",
2159
+ 'if (mode === "seq") {',
2160
+ " copyFileSync(process.env.DSH_GM_TODO_SRC, target);",
2161
+ '} else if (mode === "msg") {',
2162
+ " try {",
2163
+ ' const q = JSON.parse(readFileSync(process.env.DSH_GM_MSG_QUEUE, "utf8"));',
2164
+ " const i = q.cursor | 0;",
2165
+ " q.cursor = i + 1;",
2166
+ ' writeFileSync(process.env.DSH_GM_MSG_QUEUE, JSON.stringify(q), "utf8");',
2167
+ " const m = q.messages[i];",
2168
+ ' if (typeof m === "string" && m.length > 0) writeFileSync(target, m.replace(/\\r\\n/g, "\\n"), "utf8");',
2169
+ " } catch (e) { /* 队列缺失/损坏:保留 git 默认消息 */ }",
2170
+ "}",
2171
+ "process.exit(0);",
2172
+ ].join("\n");
2173
+
2174
+ const REBASE_QUEUE_FILE = "dsh-gm-msg-queue.json";
2175
+
2176
+ // sh 双引号转义:\ 与 " $ ` 前加反斜杠(sh 双引号内 \\ → \,路径往返无损)
2177
+ function shQuote(s) {
2178
+ return '"' + String(s).replace(/(["$`\\])/g, "\\$1") + '"';
2179
+ }
2180
+
2181
+ // 构造 editor 值:解释器 + 脚本 + 模式(mode 为固定字面量 seq|msg)
2182
+ export function buildEditorCommand(scriptPath, mode) {
2183
+ return shQuote(process.execPath) + " " + shQuote(scriptPath) + " " + mode;
2184
+ }
2185
+
2186
+ function isRebasing(gitDirAbs) {
2187
+ return existsSync(join(gitDirAbs, "rebase-merge")) || existsSync(join(gitDirAbs, "rebase-apply"));
2188
+ }
2189
+
2190
+ async function cleanupRebaseQueue(gitDirAbs) {
2191
+ try { await rm(join(gitDirAbs, REBASE_QUEUE_FILE), { force: true }); } catch (_) { /* noop */ }
2192
+ }
2193
+
2194
+ // 队列落盘到 gitDir(跨进程存活);messages 与 squash 步骤一一对应
2195
+ async function armMessageQueue(gitDirAbs, messages) {
2196
+ const queuePath = join(gitDirAbs, REBASE_QUEUE_FILE);
2197
+ await writeFile(queuePath, JSON.stringify({ messages, cursor: 0 }), "utf8");
2198
+ return queuePath;
2199
+ }
2200
+
2201
+ // mergeContinue 续跑时重新挂载队列:队列文件在则写一个新脚本并返回 env
2202
+ async function rebaseMessageQueueEnv(gitDirAbs) {
2203
+ const queuePath = join(gitDirAbs, REBASE_QUEUE_FILE);
2204
+ if (!existsSync(queuePath)) return { env: {}, scriptPath: null };
2205
+ const scriptPath = join(tmpdir(), "dsh-gm-editor-" + process.pid + "-" + randomBytes(6).toString("hex") + ".mjs");
2206
+ await writeFile(scriptPath, REBASE_EDITOR_SCRIPT, "utf8");
2207
+ return {
2208
+ env: { GIT_EDITOR: buildEditorCommand(scriptPath, "msg"), DSH_GM_MSG_QUEUE: queuePath },
2209
+ scriptPath,
2210
+ };
2211
+ }
2212
+
2213
+ // todo 条目校验(防 todo 注入:action 枚举 + 纯 hex sha + subject 去控制字符)
2214
+ export const REBASE_ACTIONS = ["pick", "squash", "fixup", "drop", "edit"];
2215
+
2216
+ export function normalizeRebaseEntry(entry, label) {
2217
+ const at = label || "rebase";
2218
+ if (!entry || typeof entry !== "object") throw new GitError("exit", at + " 的 todo 条目非法");
2219
+ const action = typeof entry.action === "string" ? entry.action : "";
2220
+ if (!REBASE_ACTIONS.includes(action)) {
2221
+ throw new GitError("exit", at + " 非法 action:" + action);
2222
+ }
2223
+ const sha = typeof entry.sha === "string" ? entry.sha : "";
2224
+ if (!/^[0-9a-fA-F]{4,64}$/.test(sha)) {
2225
+ throw new GitError("exit", at + " 非法 sha:" + sha);
2226
+ }
2227
+ // subject 只是 todo 的注释部分:去换行/控制字符并截断,防止注入额外 todo 行
2228
+ const subject = String(entry.subject == null ? "" : entry.subject)
2229
+ .replace(/[\x00-\x1f\x7f]+/g, " ")
2230
+ .slice(0, 120);
2231
+ const out = { sha, subject, action };
2232
+ // message 仅 squash 生效(替换合并后的提交信息);fixup 忽略(Lead 裁决 Q2)
2233
+ const message = typeof entry.message === "string" ? entry.message.replace(/\r\n/g, "\n") : "";
2234
+ if (action === "squash" && message.length > 0) out.message = message;
2235
+ return out;
2236
+ }
2237
+
2238
+ // 纯函数:entries → todo 文本(每行 "action sha subject",subject 为注释)
2239
+ export function buildRebaseTodo(entries) {
2240
+ if (!Array.isArray(entries) || entries.length === 0) {
2241
+ throw new GitError("exit", "rebaseRun 需要 entries(base..HEAD 的 todo 列表)");
2242
+ }
2243
+ const lines = [];
2244
+ for (const e of entries) {
2245
+ const n = normalizeRebaseEntry(e, "rebaseRun");
2246
+ lines.push(n.action + " " + n.sha + (n.subject ? " " + n.subject : ""));
2247
+ }
2248
+ return lines.join("\n") + "\n";
2249
+ }
2250
+
2251
+ // 解析器:parseRebasePlan(git log --reverse -z --format=%H%x1f%h%x1f%s 输出)
2252
+ // 输出 rebaseTodo:{ sha, short, subject, action:"pick" }(应用顺序最旧在前)
2253
+ export function parseRebasePlan(text) {
2254
+ const out = [];
2255
+ if (!text) return out;
2256
+ for (const rec of text.split("\0")) {
2257
+ if (rec.length === 0) continue;
2258
+ const parts = rec.split("\x1f");
2259
+ if (parts.length < 3) continue;
2260
+ const [sha, short, subject] = parts;
2261
+ out.push({ sha, short, subject, action: "pick" });
2262
+ }
2263
+ return out;
2264
+ }
2265
+
2266
+ // 查询:rebasePlan —— base..HEAD(不含 base)的 todo 候选,最旧在前
2267
+ export async function rebasePlan(cwd, base) {
2268
+ const b = checkRev(base, "rebasePlan");
2269
+ let raw;
2270
+ try {
2271
+ raw = await runGit(cwd, ["log", "--reverse", "-z", "--format=%H%x1f%h%x1f%s", b + "..HEAD"]);
2272
+ } catch (e) {
2273
+ if (e instanceof GitError && e.kind === "exit" && /does not have any commits/.test(e.stderr || "")) {
2274
+ return { entries: [] };
2275
+ }
2276
+ throw e;
2277
+ }
2278
+ return { entries: parseRebasePlan(raw.stdout) };
2279
+ }
2280
+
2281
+ // 变更:rebaseRun —— 写 todo + GIT_SEQUENCE_EDITOR 替换 + git rebase -i --autosquash
2282
+ // 冲突/ edit 停驻都不抛错:返回 { done:false, status },仓库进 rebase 态
2283
+ export async function rebaseRun(cwd, base, entries) {
2284
+ const b = checkRev(base, "rebaseRun");
2285
+ // 先整体校验,任何一条非法都不落任何文件/不启动 rebase
2286
+ const norm = (Array.isArray(entries) && entries.length > 0)
2287
+ ? entries.map((e) => normalizeRebaseEntry(e, "rebaseRun"))
2288
+ : (() => { throw new GitError("exit", "rebaseRun 需要 entries(base..HEAD 的 todo 列表)"); })();
2289
+ const probe = await probeRepo(cwd);
2290
+ if (!probe.isRepo) throw new GitError("not-a-repo", "rebaseRun:仓库不可用");
2291
+ const gitDirAbs = resolve(cwd, probe.gitDir);
2292
+
2293
+ const stamp = process.pid + "-" + randomBytes(6).toString("hex");
2294
+ const todoSrc = join(tmpdir(), "dsh-gm-todo-" + stamp + ".txt");
2295
+ const scriptPath = join(tmpdir(), "dsh-gm-editor-" + stamp + ".mjs");
2296
+ const env = {
2297
+ GIT_SEQUENCE_EDITOR: buildEditorCommand(scriptPath, "seq"),
2298
+ DSH_GM_TODO_SRC: todoSrc,
2299
+ };
2300
+ try {
2301
+ await writeFile(todoSrc, buildRebaseTodo(norm), "utf8");
2302
+ await writeFile(scriptPath, REBASE_EDITOR_SCRIPT, "utf8");
2303
+ const squashes = norm.filter((e) => e.action === "squash");
2304
+ if (squashes.length > 0) {
2305
+ // 队列 = squash 步骤的消息(含空串=保留默认),落 gitDir 供冲突后续挂载
2306
+ env.GIT_EDITOR = buildEditorCommand(scriptPath, "msg");
2307
+ env.DSH_GM_MSG_QUEUE = await armMessageQueue(gitDirAbs, squashes.map((e) => e.message || ""));
2308
+ }
2309
+ let err = null;
2310
+ try {
2311
+ await runGit(cwd, ["rebase", "-i", "--autosquash", b], { env });
2312
+ } catch (e) {
2313
+ if (e instanceof GitError && e.kind === "exit") err = e;
2314
+ else throw e;
2315
+ }
2316
+ const status = await getStatus(cwd);
2317
+ // done 判定按状态文件:edit 动作 exit 0 但停在 rebase 中(实测)
2318
+ const done = !isRebasing(gitDirAbs);
2319
+ if (done) {
2320
+ await cleanupRebaseQueue(gitDirAbs);
2321
+ if (err) throw err; // 失败且未进 rebase 态 = 非冲突错误(坏 base/脏工作区等)
2322
+ }
2323
+ return { done, status };
2324
+ } finally {
2325
+ await rm(todoSrc, { force: true });
2326
+ await rm(scriptPath, { force: true });
2327
+ }
2328
+ }
2329
+
2330
+ // 变更:fixupCommit —— 用暂存改动修正任意历史提交(改写历史,UI 二次确认)
2331
+ // git commit --fixup/--squash=<sha> → git rebase -i --autosquash <sha>^
2332
+ // (root 提交退化 --root;GIT_SEQUENCE_EDITOR=true 保留 git 生成的 autosquash todo)
2333
+ export async function fixupCommit(cwd, sha, mode, message) {
2334
+ const s = checkRev(sha, "fixupCommit");
2335
+ const m = mode == null || mode === "" ? "fixup" : mode;
2336
+ if (m !== "fixup" && m !== "squash") {
2337
+ throw new GitError("exit", "fixupCommit mode 只允许 fixup|squash,收到:" + mode);
2338
+ }
2339
+ const msg = typeof message === "string" ? message.replace(/\r\n/g, "\n") : "";
2340
+ // fixup+message 忽略(fixup 保留原提交信息,要改信息用 squash)——Lead 裁决 Q2
2341
+ await runGit(cwd, ["commit", m === "squash" ? "--squash=" + s : "--fixup=" + s]);
2342
+
2343
+ const probe = await probeRepo(cwd);
2344
+ if (!probe.isRepo) throw new GitError("not-a-repo", "fixupCommit:仓库不可用");
2345
+ const gitDirAbs = resolve(cwd, probe.gitDir);
2346
+
2347
+ // base = <sha>^;root 提交没有 ^ → --root
2348
+ let base = null;
2349
+ try {
2350
+ await runGit(cwd, ["rev-parse", "--verify", "--quiet", s + "^"]);
2351
+ base = s + "^";
2352
+ } catch (_) { base = null; }
2353
+
2354
+ // squash+message = 替换合并后的提交信息(消息队列);fixup 不建队列
2355
+ const queue = m === "squash" && msg.length > 0 ? [msg] : [];
2356
+ const stamp = process.pid + "-" + randomBytes(6).toString("hex");
2357
+ const scriptPath = queue.length > 0
2358
+ ? join(tmpdir(), "dsh-gm-editor-" + stamp + ".mjs")
2359
+ : null;
2360
+ const env = { GIT_SEQUENCE_EDITOR: "true" }; // 保留 git 生成的 autosquash todo
2361
+ try {
2362
+ if (scriptPath) {
2363
+ await writeFile(scriptPath, REBASE_EDITOR_SCRIPT, "utf8");
2364
+ env.GIT_EDITOR = buildEditorCommand(scriptPath, "msg");
2365
+ env.DSH_GM_MSG_QUEUE = await armMessageQueue(gitDirAbs, queue);
2366
+ }
2367
+ let err = null;
2368
+ try {
2369
+ await runGit(cwd, base
2370
+ ? ["rebase", "-i", "--autosquash", base]
2371
+ : ["rebase", "-i", "--autosquash", "--root"], { env });
2372
+ } catch (e) {
2373
+ if (e instanceof GitError && e.kind === "exit") err = e;
2374
+ else throw e;
2375
+ }
2376
+ const status = await getStatus(cwd);
2377
+ const done = !isRebasing(gitDirAbs);
2378
+ if (done) {
2379
+ await cleanupRebaseQueue(gitDirAbs);
2380
+ if (err) throw err;
2381
+ }
2382
+ return { done, status };
2383
+ } finally {
2384
+ if (scriptPath) await rm(scriptPath, { force: true });
2385
+ }
2386
+ }
2387
+
2388
+ // 变更:rebaseBranch —— 当前分支 rebase 到 branch 之上(git rebase <branch>)
2389
+ // 冲突不抛错:{ done:false, status } + rebase 态,走 mergeContinue/abortMerge 分派
2390
+ export async function rebaseBranch(cwd, branch) {
2391
+ const b = checkRev(branch, "rebaseBranch");
2392
+ const probe = await probeRepo(cwd);
2393
+ if (!probe.isRepo) throw new GitError("not-a-repo", "rebaseBranch:仓库不可用");
2394
+ const gitDirAbs = resolve(cwd, probe.gitDir);
2395
+ let err = null;
2396
+ try {
2397
+ await runGit(cwd, ["rebase", b]);
2398
+ } catch (e) {
2399
+ if (e instanceof GitError && e.kind === "exit") err = e;
2400
+ else throw e;
2401
+ }
2402
+ const status = await getStatus(cwd);
2403
+ const done = !isRebasing(gitDirAbs);
2404
+ if (done && err) throw err;
2405
+ return { done, status };
2406
+ }
2407
+
2408
+ // ============================================================================
2409
+ // 网络:fetch / pull / push
2410
+ // ============================================================================
2411
+
2412
+ const NET_OUTPUT_TAIL = 4000;
2413
+ function tail(s, n) {
2414
+ if (!s) return "";
2415
+ return s.length > n ? s.slice(s.length - n) : s;
2416
+ }
2417
+
2418
+ export async function fetchRemote(cwd, remote) {
2419
+ const args = ["fetch", "--prune"];
2420
+ if (remote) args.push(remote);
2421
+ let output = "";
2422
+ let err = null;
2423
+ try {
2424
+ const r = await runGitNet(cwd, args);
2425
+ output = tail((r.stdout + r.stderr).trim(), NET_OUTPUT_TAIL);
2426
+ } catch (e) {
2427
+ if (e instanceof GitError) {
2428
+ err = e;
2429
+ output = tail((e.stdout || "" + (e.stderr || "")).trim(), NET_OUTPUT_TAIL);
2430
+ } else throw e;
2431
+ }
2432
+ const status = await getStatus(cwd);
2433
+ if (err) {
2434
+ // 把 status 一并附在错误上,让 Host 仍能把 status 推给客户端(不丢上下文)
2435
+ err._status = status;
2436
+ err._output = output;
2437
+ throw err;
2438
+ }
2439
+ return { output, status };
2440
+ }
2441
+
2442
+ export async function pullBranch(cwd, opts = {}) {
2443
+ const args = ["pull"];
2444
+ if (opts.rebase) args.push("--rebase");
2445
+ if (opts.remote) args.push(opts.remote);
2446
+ if (opts.branch) args.push(opts.branch);
2447
+ let output = "";
2448
+ let err = null;
2449
+ try {
2450
+ const r = await runGitNet(cwd, args);
2451
+ output = tail((r.stdout + r.stderr).trim(), NET_OUTPUT_TAIL);
2452
+ } catch (e) {
2453
+ if (e instanceof GitError) {
2454
+ err = e;
2455
+ output = tail(((e.stdout || "") + (e.stderr || "")).trim(), NET_OUTPUT_TAIL);
2456
+ } else throw e;
2457
+ }
2458
+ const status = await getStatus(cwd);
2459
+ if (err) { err._status = status; err._output = output; throw err; }
2460
+ return { output, status };
2461
+ }
2462
+
2463
+ export async function pushBranch(cwd, opts = {}) {
2464
+ const args = ["push"];
2465
+ if (opts.setUpstream) args.push("-u");
2466
+ if (opts.forceWithLease) args.push("--force-with-lease");
2467
+ if (opts.remote) args.push(opts.remote);
2468
+ // v2 §2.2:refSpec 扩展(push tag 用,如 refs/tags/v1.0)。
2469
+ // 白名单校验(禁 "-" 开头/空白/元字符),传 git push 的 refspec 位置参数。
2470
+ if (typeof opts.refSpec === "string" && opts.refSpec.length > 0) {
2471
+ checkRev(opts.refSpec, "push");
2472
+ args.push(opts.refSpec);
2473
+ } else if (opts.branch) {
2474
+ args.push(opts.branch);
2475
+ }
2476
+ let output = "";
2477
+ let err = null;
2478
+ try {
2479
+ const r = await runGitNet(cwd, args);
2480
+ output = tail((r.stdout + r.stderr).trim(), NET_OUTPUT_TAIL);
2481
+ } catch (e) {
2482
+ if (e instanceof GitError) {
2483
+ err = e;
2484
+ output = tail(((e.stdout || "") + (e.stderr || "")).trim(), NET_OUTPUT_TAIL);
2485
+ } else throw e;
2486
+ }
2487
+ const status = await getStatus(cwd);
2488
+ if (err) { err._status = status; err._output = output; throw err; }
2489
+ return { output, status };
2490
+ }
2491
+
2492
+ // ============================================================================
2493
+ // Worktree 管理
2494
+ // ============================================================================
2495
+
2496
+ export async function addWorktree(cwd, worktreePath, newBranch, startPoint) {
2497
+ if (!worktreePath) throw new GitError("exit", "worktreeAdd 需要 worktreePath");
2498
+ // git worktree add 语法:worktree add [-b <new>] [--detach] <path> [<commit-ish>]
2499
+ // 关键:<path> 必须是第一个位置参数;detach 是 flag(无值),commit-ish 在 path 之后。
2500
+ const args = ["worktree", "add"];
2501
+ if (newBranch) args.push("-b", newBranch);
2502
+ if (newBranch && startPoint) {
2503
+ // git > 2.30 接受 -b newBranch startPoint 与 -b newBranch startPoint path 两种顺序;统一 path-first
2504
+ args.push(worktreePath, startPoint);
2505
+ } else {
2506
+ args.push(worktreePath);
2507
+ if (startPoint) {
2508
+ // 隐式 detached:把 startPoint 当 commit-ish 加在 path 后面
2509
+ args.push(startPoint);
2510
+ }
2511
+ }
2512
+ await runGit(cwd, args);
2513
+ return getWorktrees(cwd);
2514
+ }
2515
+
2516
+ export async function removeWorktree(cwd, worktreePath, force) {
2517
+ if (!worktreePath) throw new GitError("exit", "worktreeRemove 需要 worktreePath");
2518
+ const args = ["worktree", "remove"];
2519
+ if (force) args.push("--force");
2520
+ args.push(worktreePath);
2521
+ await runGit(cwd, args);
2522
+ return getWorktrees(cwd);
2523
+ }
2524
+
2525
+ export async function pruneWorktrees(cwd) {
2526
+ await runGit(cwd, ["worktree", "prune"]);
2527
+ return getWorktrees(cwd);
2528
+ }
2529
+
2530
+ export async function initRepo(cwd) {
2531
+ await runGit(cwd, ["init", "-b", "main"]);
2532
+ return probeRepo(cwd);
2533
+ }
2534
+
2535
+ // ============================================================================
2536
+ // P2(v2 §2.3):remote 增删改 / config 读写
2537
+ // ============================================================================
2538
+
2539
+ export async function addRemote(cwd, name, url, pushUrl) {
2540
+ checkRemoteName(name, "remoteAdd");
2541
+ if (typeof url !== "string" || url.length === 0 || url.startsWith("-")) {
2542
+ throw new GitError("exit", "remoteAdd 需要合法 url");
2543
+ }
2544
+ if (pushUrl != null && pushUrl !== "" && (typeof pushUrl !== "string" || pushUrl.startsWith("-"))) {
2545
+ throw new GitError("exit", "remoteAdd pushUrl 非法");
2546
+ }
2547
+ await runGit(cwd, ["remote", "add", name, url]);
2548
+ if (typeof pushUrl === "string" && pushUrl.length > 0) {
2549
+ await runGit(cwd, ["remote", "set-url", "--push", name, pushUrl]);
2550
+ }
2551
+ return { remotes: await getRemotes(cwd) };
2552
+ }
2553
+
2554
+ export async function removeRemote(cwd, name) {
2555
+ checkRemoteName(name, "remoteRemove");
2556
+ await runGit(cwd, ["remote", "remove", name]);
2557
+ return { remotes: await getRemotes(cwd) };
2558
+ }
2559
+
2560
+ export async function renameRemote(cwd, oldName, newName) {
2561
+ checkRemoteName(oldName, "remoteRename");
2562
+ checkRemoteName(newName, "remoteRename");
2563
+ await runGit(cwd, ["remote", "rename", oldName, newName]);
2564
+ return { remotes: await getRemotes(cwd) };
2565
+ }
2566
+
2567
+ // 解析器:parseConfigList
2568
+ // 输入:git config -z --list(每条 "key\nvalue",记录以 \0 分隔;
2569
+ // value 可含换行 → 按第一个 \n 切 key/value)
2570
+ // 输出 configEntry:{ key, value }
2571
+ export function parseConfigList(text) {
2572
+ const out = [];
2573
+ if (!text) return out;
2574
+ for (const rec of text.split("\0")) {
2575
+ if (rec.length === 0) continue;
2576
+ const idx = rec.indexOf("\n");
2577
+ if (idx < 0) continue;
2578
+ out.push({ key: rec.slice(0, idx), value: rec.slice(idx + 1) });
2579
+ }
2580
+ return out;
2581
+ }
2582
+
2583
+ // config key 校验:section.subsection.key 形态,禁 "-" 开头与空白
2584
+ function checkConfigKey(key, label) {
2585
+ if (typeof key !== "string" || key.length === 0) {
2586
+ throw new GitError("exit", (label || "config") + " 需要 key");
2587
+ }
2588
+ if (key.startsWith("-") || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key)) {
2589
+ throw new GitError("exit", (label || "config") + " 非法 key:" + key);
2590
+ }
2591
+ return key;
2592
+ }
2593
+
2594
+ function configScopeArgs(global) {
2595
+ return [global ? "--global" : "--local"];
2596
+ }
2597
+
2598
+ export async function getConfig(cwd, global) {
2599
+ const args = ["config", "-z", "--list"].concat(configScopeArgs(!!global));
2600
+ const r = await runGit(cwd, args);
2601
+ return { entries: parseConfigList(r.stdout) };
2602
+ }
2603
+
2604
+ export async function setConfig(cwd, key, value, global) {
2605
+ checkConfigKey(key, "configSet");
2606
+ if (typeof value !== "string") throw new GitError("exit", "configSet 需要 value");
2607
+ await runGit(cwd, ["config"].concat(configScopeArgs(!!global)).concat([key, value]));
2608
+ return getConfig(cwd, global);
2609
+ }
2610
+
2611
+ export async function unsetConfig(cwd, key, global) {
2612
+ checkConfigKey(key, "configUnset");
2613
+ await runGit(cwd, ["config"].concat(configScopeArgs(!!global)).concat(["--unset-all", key]));
2614
+ return getConfig(cwd, global);
2615
+ }
2616
+
2617
+ // ============================================================================
2618
+ // 子仓库支持 P2(2026-10-13):submodule 管理五方法
2619
+ // init / update / sync / deinit / add。契约:位置参数是**仓库内路径**(相对
2620
+ // toplevel),不是 .gitmodules 里的注册名——git CLI 的这五个子命令收的就是路径
2621
+ // (方案 §2.2 表格里的 `name?` 已据此修正为 `subPath`;只有 add 的 --name 才是
2622
+ // 注册名)。所有 subPath 过 safeJoin 防护后才进 argv(与 mode/discard 同款)。
2623
+ // update / add 可能触发 clone(走网络)→ 用 runGitNet(180s),其余 runGit。
2624
+ // ============================================================================
2625
+
2626
+ // submodule 注册名白名单(仅 submoduleAdd 的 --name 用):submodule name 会被当作
2627
+ // config key `submodule.<name>.path` / `.url` 的一段,git 的 config 解析比
2628
+ // check-ref-format 宽,故此处按 checkRefName 同款收紧:非空;禁空白与 ~^:?*[\;
2629
+ // 禁 - 与 . 开头(前者会被 git 当选项,后者是保留的相对路径标记);禁 ..;
2630
+ // 禁 / 结尾。不含通用的 ".."→ 已单列。
2631
+ export function checkSubmoduleName(name, label) {
2632
+ if (typeof name !== "string" || name.length === 0) {
2633
+ throw new GitError("exit", (label || "submodule") + " 需要 name");
2634
+ }
2635
+ const bad = name.startsWith("-") || name.startsWith(".")
2636
+ || name.endsWith("/") || name.includes("..")
2637
+ || /[\s~^:?*\[\\]/.test(name);
2638
+ if (bad) throw new GitError("exit", (label || "submodule") + " 非法名称:" + name);
2639
+ return name;
2640
+ }
2641
+
2642
+ // url 白名单:非空、无空白(换行/空格会让 argv 与日志语义都不可控)、禁 - 开头
2643
+ // (防选项注入)。其余合法性交给 git 自己报错(协议不支持等)。
2644
+ function checkSubmoduleUrl(url) {
2645
+ if (typeof url !== "string" || url.length === 0 || /\s/.test(url) || url.startsWith("-")) {
2646
+ throw new GitError("exit", "submoduleAdd 需要合法 url");
2647
+ }
2648
+ return url;
2649
+ }
2650
+
2651
+ // 本地路径 url 判定:git 2.38+ 默认 protocol.file.allow=user,主要防的是「不可信
2652
+ // .gitmodules 连锁触发 file 传输」(克隆攻击面),而这里的 url 是用户在 UI 里
2653
+ // 显式输入/选择的,属用户自己点的那一下 → 自动前置 -c protocol.file.allow=always
2654
+ // 是合理的(UNC 路径 \\server\share 同属本地,一并覆盖)。
2655
+ function isLocalSubmoduleUrl(url) {
2656
+ return existsSync(url)
2657
+ || url.startsWith("./") || url.startsWith("../")
2658
+ || url.startsWith("/") || url.startsWith("\\\\")
2659
+ || /^[a-zA-Z]:[\\/]/.test(url);
2660
+ }
2661
+
2662
+ // 五个 submodule 方法共用的入口归一:cwd 可能是仓库内子目录 → 先 probeRepo 取
2663
+ // toplevel,全部命令在 toplevel 跑(git submodule 对 cwd 敏感);subPath 相对
2664
+ // toplevel 过 safeJoin(拒绝绝对路径与 .. 越界),返回 posix 形态进 argv。
2665
+ // subPath 缺省合法(= 全量),required=true 时(deinit/add)缺省即抛错。
2666
+ async function resolveSubmoduleTarget(cwd, subPath, opts = {}) {
2667
+ const probe = await probeRepo(cwd);
2668
+ if (!probe || !probe.isRepo) {
2669
+ throw new GitError("exit", (opts.label || "submodule") + ":路径不是 git 仓库:" + cwd);
2670
+ }
2671
+ const toplevel = resolve(probe.toplevel);
2672
+ if (subPath == null || subPath === "") {
2673
+ if (opts.required) {
2674
+ throw new GitError("exit", (opts.label || "submodule") + " 需要 subPath");
2675
+ }
2676
+ return { toplevel, subPath: null };
2677
+ }
2678
+ safeJoin(toplevel, subPath);
2679
+ return { toplevel, subPath: toPosixRel(subPath) };
2680
+ }
2681
+
2682
+ export async function submoduleInit(cwd, subPath) {
2683
+ const t = await resolveSubmoduleTarget(cwd, subPath, { label: "submoduleInit" });
2684
+ const args = ["submodule", "init"];
2685
+ if (t.subPath) args.push("--", t.subPath);
2686
+ await runGit(t.toplevel, args);
2687
+ return { status: await getStatus(t.toplevel) };
2688
+ }
2689
+
2690
+ export async function submoduleUpdate(cwd, opts) {
2691
+ const o = opts || {};
2692
+ const t = await resolveSubmoduleTarget(cwd, o.subPath, { label: "submoduleUpdate" });
2693
+ const args = ["submodule", "update"];
2694
+ if (o.init) args.push("--init");
2695
+ if (o.recursive) args.push("--recursive");
2696
+ if (t.subPath) args.push("--", t.subPath);
2697
+ // 首次 update 会 clone(走网络)→ 长超时
2698
+ await runGitNet(t.toplevel, args);
2699
+ return { status: await getStatus(t.toplevel) };
2700
+ }
2701
+
2702
+ export async function submoduleSync(cwd, subPath) {
2703
+ const t = await resolveSubmoduleTarget(cwd, subPath, { label: "submoduleSync" });
2704
+ const args = ["submodule", "sync"];
2705
+ if (t.subPath) args.push("--", t.subPath);
2706
+ await runGit(t.toplevel, args);
2707
+ return { status: await getStatus(t.toplevel) };
2708
+ }
2709
+
2710
+ // deinit 是危险操作(清空子模块工作区目录 + 注销本地配置,.gitmodules 保留),
2711
+ // 契约要求 subPath 必填:不带 -- 的 deinit 会清空**全部**子模块。
2712
+ export async function submoduleDeinit(cwd, subPath, force) {
2713
+ const t = await resolveSubmoduleTarget(cwd, subPath, { label: "submoduleDeinit", required: true });
2714
+ const args = ["submodule", "deinit"];
2715
+ if (force) args.push("-f");
2716
+ args.push("--", t.subPath);
2717
+ await runGit(t.toplevel, args);
2718
+ return { status: await getStatus(t.toplevel) };
2719
+ }
2720
+
2721
+ export async function submoduleAdd(cwd, opts) {
2722
+ const o = opts || {};
2723
+ const url = checkSubmoduleUrl(o.url);
2724
+ const probe = await probeRepo(cwd);
2725
+ if (!probe || !probe.isRepo) {
2726
+ throw new GitError("exit", "submoduleAdd:路径不是 git 仓库:" + cwd);
2727
+ }
2728
+ const toplevel = resolve(probe.toplevel);
2729
+ if (o.subPath == null || o.subPath === "") {
2730
+ throw new GitError("exit", "submoduleAdd 需要 subPath");
2731
+ }
2732
+ // 路径防护先过(越界/绝对路径在跑命令前就拒掉)
2733
+ const abs = safeJoin(toplevel, o.subPath);
2734
+ const subPath = toPosixRel(o.subPath);
2735
+ const args = [];
2736
+ if (isLocalSubmoduleUrl(url)) args.push("-c", "protocol.file.allow=always");
2737
+ args.push("submodule", "add");
2738
+ // name 可选(缺省 git 按 remote 仓库名派生);给了就过注册名白名单
2739
+ if (o.name != null && o.name !== "") args.push("--name", checkSubmoduleName(o.name, "submoduleAdd"));
2740
+ args.push("--", url, subPath);
2741
+ // clone 可能走网络 → 长超时;失败(目录已存在且非空 / url 不可达等)按 GitError 上抛
2742
+ try {
2743
+ await runGitNet(toplevel, args);
2744
+ } catch (e) {
2745
+ // git 2.38+ 对「.git/modules/<name> 有同名残留」的路径拒绝 add
2746
+ //(fatal: A git directory for '...' is found locally)——卸载后重加、
2747
+ // 嵌套仓库就地注册都会撞上。按 git 自己的提示用 --force 复用本地对象库
2748
+ // 重试一次(此处本就是用户显式操作,且 url 已过白名单)。
2749
+ if (!(e instanceof GitError) || !/found locally/.test(e.stderr || "")) throw e;
2750
+ const forceArgs = args.slice();
2751
+ forceArgs.splice(forceArgs.indexOf("submodule") + 1, 0, "--force");
2752
+ await runGitNet(toplevel, forceArgs);
2753
+ }
2754
+ return { status: await getStatus(toplevel), probe: await probeRepo(abs) };
2755
+ }