@aiti-ai/aiti-git-ops 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/git-engine.ts ADDED
@@ -0,0 +1,967 @@
1
+ /**
2
+ * aiti-git-ops · git 写引擎核心(方案 docs/aiti-git-ops-shared-plan.md §1)
3
+ *
4
+ * 设计要点:
5
+ * - 白名单子命令 + 每入口手写参数拼装,不经手用户原始 args(杜绝 --exec/--upload-pack 注入面);
6
+ * - ref 形参数一律先过基础校验(拒前置 "-"/控制字符/空白)+ rev-parse --verify --end-of-options
7
+ * 解析(旧 git 无该标志时自动回退)/ check-ref-format 原生校验(分支/tag 名,unicode 合法名放行);
8
+ * - checkout 家族永不传 -f;reset 仅 --mixed;clean 不在白名单(untracked 走隔离区);
9
+ * - 路径输出一律 -z(NUL 分隔、永不引号化——中文/空格/引号/换行文件名原样透传;
10
+ * porcelain v1 默认 core.quotePath=true 会把非 ASCII 路径打成八进制转义,v1 行解析不可救);
11
+ * - 同仓写操作 + 预检读全部经 queueRepo 串行(§1.7);
12
+ * - 全部 execFileAsync(数组参数、无 shell——Windows 兼容天然合规,见 docs/windows-compat-lessons.md §0);
13
+ * - 审计 jsonl(state 层 5MB 滚动)+ 事件 onChanged 回调(index.ts 接 event-bus topic)。
14
+ */
15
+ import { createHash } from "node:crypto";
16
+ import { mkdir, rename, rm, cp, appendFile, stat } from "node:fs/promises";
17
+ import { dirname, join, isAbsolute, relative, resolve as pathResolve } from "node:path";
18
+ import { execFileAsync, queueRepo } from "@aiti-ai/ext-shared/exec-async";
19
+
20
+ // ── 结构化错误 ───────────────────────────────────────────────────────────────
21
+
22
+ export interface GitOpsFail extends Error {
23
+ status: number;
24
+ conflict?: boolean;
25
+ files?: string[];
26
+ detail?: string;
27
+ }
28
+
29
+ export function fail(status: number, message: string, extra: Partial<GitOpsFail> = {}): never {
30
+ const e = new Error(message) as GitOpsFail;
31
+ e.status = status;
32
+ Object.assign(e, extra);
33
+ throw e;
34
+ }
35
+
36
+ const gitErr = (e: unknown, fallback: string): never => {
37
+ const err = e as { stderr?: string; message?: string };
38
+ const detail = err?.stderr ? ":" + String(err.stderr).split("\n").filter(Boolean).slice(0, 3).join(";")
39
+ : err?.message ? ":" + err.message : "";
40
+ fail(500, fallback + detail);
41
+ };
42
+
43
+ /** git 旧版本不认识新子命令/开关时的错误特征(restore 2.23 / stash push 2.13 / --end-of-options 2.24) */
44
+ const looksLikeUnknownOption = (e: unknown): boolean => {
45
+ const s = String((e as { stderr?: string })?.stderr || "") + String((e as Error)?.message || "");
46
+ return /unknown (option|switch)|unrecognized|unknown argument|^usage: /im.test(s);
47
+ };
48
+
49
+ // ── 引擎配置(index.ts startup 注入;state/cache 目录分层) ──────────────────
50
+
51
+ let stateDir = "";
52
+ let cacheDir = "";
53
+ let onChanged: ((repo: string, kind: string, summary: string) => void) | null = null;
54
+ let auditSource = "unknown";
55
+
56
+ export function initGitEngine(opts: {
57
+ stateDir: string;
58
+ cacheDir: string;
59
+ onChanged?: (repo: string, kind: string, summary: string) => void;
60
+ source?: string;
61
+ }) {
62
+ stateDir = opts.stateDir;
63
+ cacheDir = opts.cacheDir;
64
+ onChanged = opts.onChanged ?? null;
65
+ auditSource = opts.source ?? "unknown";
66
+ }
67
+
68
+ // 数据分层:审计(state,不可再生)→ <stateDir>/aiti-git-ops/git-ops.jsonl;
69
+ // 隔离区(cache,可整体 rm -rf 自愈)→ <cacheDir>/aiti-git-ops/discarded/<ts>/<rel>
70
+ const auditFile = () => join(stateDir, "aiti-git-ops", "git-ops.jsonl");
71
+ const quarantineRoot = () => join(cacheDir, "aiti-git-ops", "discarded");
72
+ const AUDIT_MAX_BYTES = 5 * 1024 * 1024;
73
+
74
+ async function audit(entry: Record<string, unknown>) {
75
+ if (!stateDir) return;
76
+ try {
77
+ await mkdir(dirname(auditFile()), { recursive: true });
78
+ const f = auditFile();
79
+ try {
80
+ const s = await stat(f);
81
+ if (s.size > AUDIT_MAX_BYTES) await rename(f, f + ".1"); // 滚动(保留一代)
82
+ } catch { /* 不存在 */ }
83
+ await appendFile(f, JSON.stringify({ ts: new Date().toISOString(), source: auditSource, ...entry }) + "\n");
84
+ } catch { /* 审计失败不阻断操作 */ }
85
+ }
86
+
87
+ const changed = (repo: string, kind: string, summary: string) => {
88
+ try { abCache.delete(repo); } catch { /* 缓存失效失败不阻断 */ } // commit/sync 后 ahead-behind 立即新鲜
89
+ try { onChanged?.(repo, kind, summary); } catch { /* 事件失败不阻断 */
90
+ }
91
+ };
92
+
93
+ // ahead-behind 60s 内存 TTL(freshness 数据无需重启存续;§1.4 的 cache/ 磁盘缓存留 M2 按需)。
94
+ // ⚠ 声明须先于 changed() 引用之外的可读位置——运行时经 changed() 失效。
95
+ const abCache = new Map<string, { v: [number, number] | null; at: number }>();
96
+ const AB_TTL_MS = 60_000;
97
+
98
+ export const repoTopic = (repo: string) => "aiti-git-ops:changed:" + createHash("sha1").update(repo).digest("hex").slice(0, 12);
99
+
100
+ // ── 基础工具 ────────────────────────────────────────────────────────────────
101
+
102
+ /** 仓库根解析:cwd 必须是绝对路径且落在 git 仓内;返回 toplevel */
103
+ export async function repoRoot(cwd: string): Promise<string> {
104
+ if (!cwd || typeof cwd !== "string" || !isAbsolute(cwd)) fail(400, "cwd 必须是绝对路径");
105
+ try {
106
+ const out = await execFileAsync("git", ["rev-parse", "--show-toplevel"], { cwd, timeoutMs: 15_000 });
107
+ const root = out.trim();
108
+ if (!root) fail(400, "不是 git 仓库: " + cwd);
109
+ return root;
110
+ } catch (e) {
111
+ const first = String((e as { stderr?: string })?.stderr || "").split("\n").filter(Boolean)[0];
112
+ fail(400, "不是 git 仓库: " + cwd + (first ? `(${first})` : ""));
113
+ }
114
+ }
115
+
116
+ const run = (repo: string, args: string[], timeoutMs = 120_000) =>
117
+ execFileAsync("git", args, { cwd: repo, timeoutMs });
118
+
119
+ /** 路径穿越防护(拷自 aiti-git-review 生产验证实现) */
120
+ export function safeRel(base: string, target: string): string {
121
+ const abs = pathResolve(base, target);
122
+ const rel = relative(pathResolve(base), abs);
123
+ // 不得用 pathResolve(rel)===abs 兜底——cwd 恰为 repo 根时会误判穿越
124
+ if (rel.startsWith("..") || rel.startsWith("/") || isAbsolute(rel)) throw new Error("path outside repo: " + target);
125
+ return rel === "" ? "." : rel;
126
+ }
127
+
128
+ /** ref 形参基础校验:拒前置 "-"(选项注入)、控制字符、空白、超长。
129
+ * unicode 分支名(如「分支-01」)是 git 合法 ref,放行——选项注入面已由
130
+ * 「无 shell + 数组参数 + 值位拼装 + rev-parse --end-of-options」挡死,字符集不再人为收窄。 */
131
+ const CTL_RE = /[\u0000-\u001f\u007f]/;
132
+ export function assertSafeRef(ref: string, what = "ref"): string {
133
+ if (typeof ref !== "string" || !ref || ref.length > 200 || ref.startsWith("-") || CTL_RE.test(ref) || /\s/.test(ref)) {
134
+ fail(400, `非法 ${what}: ${JSON.stringify(ref)}`);
135
+ }
136
+ return ref;
137
+ }
138
+
139
+ /** 分支/tag 名校验:基础校验 + git 原生 check-ref-format(全量规则:..、.lock、@{ 等由 git 拒) */
140
+ export async function assertBranchName(repo: string, name: string, kind: "branch" | "tag" = "branch") {
141
+ assertSafeRef(name, kind === "tag" ? "tag 名" : "分支名");
142
+ const args = kind === "tag" ? ["check-ref-format", `refs/tags/${name}`] : ["check-ref-format", "--branch", name];
143
+ try {
144
+ await run(repo, args, 15_000);
145
+ } catch {
146
+ fail(400, `非法${kind === "tag" ? " tag" : "分支"}名: ${JSON.stringify(name)}`);
147
+ }
148
+ return name;
149
+ }
150
+
151
+ /** 任意 ref → commit sha(存在性 + 注入双验证;旧 git 无 --end-of-options 自动回退) */
152
+ export async function resolveCommit(repo: string, ref: string): Promise<string> {
153
+ assertSafeRef(ref);
154
+ const tryParse = (flag: boolean) =>
155
+ run(repo, flag ? ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`] : ["rev-parse", "--verify", `${ref}^{commit}`], 15_000);
156
+ try {
157
+ return (await tryParse(true)).trim();
158
+ } catch (e) {
159
+ if (looksLikeUnknownOption(e)) {
160
+ try { return (await tryParse(false)).trim(); } catch { /* 落到 404 */ }
161
+ }
162
+ fail(404, "ref 不存在或不是 commit: " + ref);
163
+ }
164
+ }
165
+
166
+ async function headSha(repo: string): Promise<string> {
167
+ try {
168
+ return (await run(repo, ["rev-parse", "HEAD"], 15_000)).trim();
169
+ } catch (e) {
170
+ gitErr(e, "无 HEAD(空仓库?)");
171
+ }
172
+ }
173
+
174
+ // ── status / diff 路径解析(一律 -z:NUL 分隔、不引号化,全文件名形态安全) ───
175
+
176
+ export interface StatusEntry { xy: string; path: string }
177
+
178
+ /**
179
+ * `git status --porcelain -z` 解析。记录形态:
180
+ * `XY <path>\0`;rename/copy 为 `XY <to>\0<from>\0`(注意 -z 下 to 在前)。
181
+ * path 为 TO(rename 覆盖面以新路径为准);未跟踪目录保持 `dir/` 尾斜杠形态。
182
+ */
183
+ export function parseStatusZ(out: string): StatusEntry[] {
184
+ const entries: StatusEntry[] = [];
185
+ const toks = out.split("\0");
186
+ for (let i = 0; i < toks.length; i++) {
187
+ const t = toks[i];
188
+ if (!t) continue;
189
+ const xy = t.slice(0, 2);
190
+ const p = t.slice(3);
191
+ if (xy[0] === "R" || xy[0] === "C") i++; // 跳过 FROM 路径(下一 token)
192
+ entries.push({ xy, path: p });
193
+ }
194
+ return entries;
195
+ }
196
+
197
+ async function statusEntries(repo: string): Promise<StatusEntry[]> {
198
+ return parseStatusZ(await run(repo, ["status", "--porcelain", "-z"], 15_000));
199
+ }
200
+
201
+ // ── checkout 预检管道(§1.3) ────────────────────────────────────────────────
202
+
203
+ /**
204
+ * dirty ∩ affected 预检。返回冲突文件列表;空数组 = 放行。
205
+ * 豁免:目标 commit 与当前 HEAD 相同(必然无文件变化)。
206
+ */
207
+ export async function precheckConflict(repo: string, targetSha: string): Promise<string[]> {
208
+ const head = await headSha(repo);
209
+ if (head === targetSha) return [];
210
+ const dirty = (await statusEntries(repo)).map((e) => e.path);
211
+ const affected = (await run(repo, ["diff", "--name-only", "--no-renames", "-z", "HEAD", targetSha], 30_000))
212
+ .split("\0").filter(Boolean);
213
+ const aff = new Set(affected);
214
+ return dirty.filter((p) => aff.has(p) || aff.has(p.replace(/\/$/, "")));
215
+ }
216
+
217
+ // ── API 实现(每个入口手写参数拼装) ─────────────────────────────────────────
218
+
219
+ export interface Refs {
220
+ repo: string;
221
+ current: string | null;
222
+ detached: boolean;
223
+ /** HEAD 全 sha(detached 时为该 commit;空仓库 null)——plan baseHEAD/回滚用 */
224
+ head: string | null;
225
+ branches: string[];
226
+ remotes: string[];
227
+ tags: string[];
228
+ aheadBehind: [number, number] | null;
229
+ dirtyCount: number;
230
+ dirtyFiles: { xy: string; path: string }[];
231
+ }
232
+
233
+ // ahead-behind 60s 内存 TTL(freshness 数据无需重启存续;§1.4 的 cache/ 磁盘缓存留 M2 按需)
234
+
235
+ export async function gitRefs(cwd: string): Promise<Refs> {
236
+ const repo = await repoRoot(cwd);
237
+ const eachRef = async (pattern: string, cap: number) =>
238
+ (await run(repo, ["for-each-ref", "--format=%(refname:short)", `--count=${cap}`, pattern], 30_000))
239
+ .split("\n").map((s) => s.trim()).filter(Boolean);
240
+ let current: string | null = null;
241
+ let detached = false;
242
+ try {
243
+ current = (await run(repo, ["symbolic-ref", "--short", "HEAD"], 15_000)).trim();
244
+ } catch {
245
+ detached = true;
246
+ current = (await headSha(repo)).slice(0, 12);
247
+ }
248
+ let ab = abCache.get(repo);
249
+ if (!ab || Date.now() - ab.at > AB_TTL_MS) {
250
+ let v: [number, number] | null = null;
251
+ try {
252
+ const parts = (await run(repo, ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"], 30_000)).trim().split(/\s+/);
253
+ if (parts.length === 2) v = [Number(parts[0]), Number(parts[1])];
254
+ } catch { /* 无 upstream */ }
255
+ ab = { v, at: Date.now() };
256
+ abCache.set(repo, ab);
257
+ }
258
+ const dirty = await statusEntries(repo);
259
+ let head: string | null = null;
260
+ try {
261
+ head = (await run(repo, ["rev-parse", "HEAD"], 15_000)).trim() || null;
262
+ } catch { /* 空仓库无 HEAD */ }
263
+ return {
264
+ repo, current, detached, head,
265
+ branches: await eachRef("refs/heads", 500),
266
+ remotes: await eachRef("refs/remotes", 200),
267
+ tags: await eachRef("refs/tags", 200),
268
+ aheadBehind: ab.v,
269
+ dirtyCount: dirty.length,
270
+ // 部分暂存勾选清单(cap 200 防超大脏区;xy 供 UI 标 staged/??)
271
+ dirtyFiles: dirty.slice(0, 200).map((e) => ({ xy: e.xy, path: e.path })),
272
+ };
273
+ }
274
+
275
+ /**
276
+ * stash 条目文件清单(部分提取勾选用):tracked = diff name-only(该 stash 的已跟踪改动);
277
+ * untracked = ls-tree 第三父(仅 -u 入 stash 的条目有)。条目保留不 drop 的提取语义见 stashApply。
278
+ */
279
+ export async function stashFiles(cwd: string, index: number): Promise<{ tracked: string[]; untracked: string[] }> {
280
+ const repo = await repoRoot(cwd);
281
+ const ref = stashRef(index);
282
+ let tracked: string[] = [];
283
+ try {
284
+ tracked = (await run(repo, ["diff", "--name-only", "--no-renames", "-z", `${ref}^`, ref], 30_000)).split("\0").filter(Boolean);
285
+ } catch (e) {
286
+ gitErr(e, "stash 文件清单失败");
287
+ }
288
+ let untracked: string[] = [];
289
+ try {
290
+ untracked = (await run(repo, ["ls-tree", "-r", "-z", "--name-only", `${ref}^3`], 30_000)).split("\0").filter(Boolean);
291
+ } catch { /* 该 stash 无未跟踪部分 */ }
292
+ return { tracked, untracked };
293
+ }
294
+
295
+ /**
296
+ * 图谱分页。注意:`git log --graph` 与 `--skip` 不兼容(静默返回空,实测 git 2.48),
297
+ * 改为 --max-count=(skip+count+1) 后本地切片;是否还有下一页用 rev-list --count 判断。
298
+ */
299
+ export async function gitLog(cwd: string, cursor: number, count = 50): Promise<{ lines: string[]; nextCursor: number | null }> {
300
+ const repo = await repoRoot(cwd);
301
+ const skip = Number.isInteger(cursor) && cursor > 0 ? cursor : 0;
302
+ const out = await run(repo, ["log", "--graph", "--oneline", "--date-order", `--max-count=${skip + count + 1}`], 60_000);
303
+ const all = out.split("\n");
304
+ if (all[all.length - 1] === "") all.pop();
305
+ const lines = all.slice(skip, skip + count);
306
+ let nextCursor: number | null = null;
307
+ if (lines.length === count) {
308
+ try {
309
+ const total = Number((await run(repo, ["rev-list", "--count", "HEAD"], 30_000)).trim());
310
+ if (skip + count < total) nextCursor = skip + count;
311
+ } catch { /* 空仓库 */ }
312
+ }
313
+ return { lines, nextCursor };
314
+ }
315
+
316
+ /** checkout 家族统一入口(永不 -f;mode=stash-then-switch 时先 stash 后切) */
317
+ export async function gitCheckout(cwd: string, ref: string, mode?: string): Promise<{ ok: true; branch: string }> {
318
+ const repo = await repoRoot(cwd);
319
+ assertSafeRef(ref, "ref");
320
+ return queueRepo(repo, async () => {
321
+ const sha = await resolveCommit(repo, ref);
322
+ // mode=stash-then-switch 是 409 三选一里用户确认后的重入——不再拦,直接 stash 后切
323
+ if (mode !== "stash-then-switch") {
324
+ const conflict = await precheckConflict(repo, sha);
325
+ if (conflict.length > 0) fail(409, "脏文件与目标分支改动重叠", { conflict: true, files: conflict });
326
+ } else {
327
+ try {
328
+ await run(repo, ["stash", "push", "--include-untracked", "-m", "aiti-git-ops: switch to " + ref]);
329
+ } catch (e) {
330
+ gitErr(e, "stash 失败(切换中止,工作区未动)");
331
+ }
332
+ }
333
+ try {
334
+ await run(repo, ["checkout", ref]);
335
+ } catch (e) {
336
+ gitErr(e, "checkout 失败");
337
+ }
338
+ await audit({ repo, cmd: "checkout", ref, mode: mode ?? "direct" });
339
+ changed(repo, "branch", "checkout " + ref);
340
+ return { ok: true as const, branch: ref };
341
+ });
342
+ }
343
+
344
+ export async function gitBranchCreate(cwd: string, name: string, from?: string, checkout = true): Promise<{ ok: true; branch: string }> {
345
+ const repo = await repoRoot(cwd);
346
+ await assertBranchName(repo, name);
347
+ return queueRepo(repo, async () => {
348
+ const fromSha = await resolveCommit(repo, from || "HEAD");
349
+ // 预检豁免(v2):from === 当前 HEAD 时建并检出永不改文件
350
+ if (checkout && fromSha !== (await headSha(repo))) {
351
+ const conflict = await precheckConflict(repo, fromSha);
352
+ if (conflict.length > 0) fail(409, "脏文件与起点 commit 改动重叠", { conflict: true, files: conflict });
353
+ }
354
+ try {
355
+ if (checkout) await run(repo, ["checkout", "-b", name, fromSha]);
356
+ else await run(repo, ["branch", name, fromSha]);
357
+ } catch (e) {
358
+ gitErr(e, "建分支失败");
359
+ }
360
+ await audit({ repo, cmd: "branch-create", name, from: fromSha, checkout });
361
+ changed(repo, "branch", "create " + name);
362
+ return { ok: true as const, branch: name };
363
+ });
364
+ }
365
+
366
+ export async function gitBranchDelete(cwd: string, name: string): Promise<{ ok: true }> {
367
+ const repo = await repoRoot(cwd);
368
+ await assertBranchName(repo, name);
369
+ return queueRepo(repo, async () => {
370
+ try {
371
+ await run(repo, ["branch", "-d", name]);
372
+ } catch (e) {
373
+ gitErr(e, "删除失败(-d 安全删:未合并的分支会被 git 拒绝)");
374
+ }
375
+ await audit({ repo, cmd: "branch-delete", name });
376
+ changed(repo, "branch", "delete " + name);
377
+ return { ok: true as const };
378
+ });
379
+ }
380
+
381
+ export async function gitTags(cwd: string): Promise<{ tags: { name: string; type: string; date: string }[] }> {
382
+ const repo = await repoRoot(cwd);
383
+ const out = await run(repo, ["for-each-ref", "--count=200", "--format=%(refname:short)%09%(objecttype)%09%(creatordate:iso8601)", "refs/tags"], 30_000);
384
+ const tags = out.split("\n").filter(Boolean).map((l) => {
385
+ const [name, type, date] = l.split("\t");
386
+ return { name, type, date };
387
+ });
388
+ return { tags };
389
+ }
390
+
391
+ export async function gitTagCreate(cwd: string, name: string, ref?: string, opts?: { annotate?: boolean; message?: string }): Promise<{ ok: true }> {
392
+ const repo = await repoRoot(cwd);
393
+ await assertBranchName(repo, name, "tag");
394
+ return queueRepo(repo, async () => {
395
+ const args = ["tag"];
396
+ if (opts?.annotate || opts?.message) args.push("-a", "-m", opts?.message || name);
397
+ args.push(name);
398
+ if (ref) args.push(await resolveCommit(repo, ref));
399
+ try {
400
+ await run(repo, args);
401
+ } catch (e) {
402
+ gitErr(e, "建 tag 失败");
403
+ }
404
+ await audit({ repo, cmd: "tag-create", name, ref: ref || "HEAD" });
405
+ changed(repo, "branch", "tag " + name);
406
+ return { ok: true as const };
407
+ });
408
+ }
409
+
410
+ // ── commit 详情 / cherry-pick(图谱 commit 卡,方案 docs/aiti-git-ops-commit-card-plan.md)──
411
+
412
+ export interface CommitFile { path: string; oldPath?: string; status: string; additions: number; deletions: number }
413
+
414
+ export interface CommitInfo {
415
+ sha: string;
416
+ author: string;
417
+ email: string;
418
+ date: string;
419
+ subject: string;
420
+ body: string;
421
+ parents: string[];
422
+ /** merge commit(files = 与第一父的 diff) */
423
+ merge: boolean;
424
+ files: CommitFile[];
425
+ additions: number;
426
+ deletions: number;
427
+ }
428
+
429
+ /** 空树 sha(root commit 的 diff base;对象不必存在于 odb,git 特判。sha256 仓库不同——极端边界,报错透出) */
430
+ const EMPTY_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
431
+
432
+ async function commitParents(repo: string, sha: string): Promise<string[]> {
433
+ try {
434
+ return (await run(repo, ["rev-list", "--parents", "-n", "1", sha], 15_000)).trim().split(/\s+/).slice(1).filter(Boolean);
435
+ } catch (e) {
436
+ gitErr(e, "读取 parent 失败");
437
+ }
438
+ }
439
+
440
+ /**
441
+ * commit 文件清单:name-status(状态 + old/new)× numstat(增删行数)两路合并。
442
+ * `-z` rename 记录 token 序(2026-09-19 git 2.48 fixture 实测钉死,勿凭文档记忆改):
443
+ * name-status = `R100\0<old>\0<new>\0`;numstat = `<add>\t<del>\t\0<old>\0<new>\0`(path 位空)。
444
+ */
445
+ async function commitFileList(repo: string, base: string, sha: string): Promise<CommitFile[]> {
446
+ const statusOut = await run(repo, ["diff", "--name-status", "-z", "-M", base, sha], 30_000).catch((e) => gitErr(e, "读取 commit 状态失败"));
447
+ const numOut = await run(repo, ["diff", "--numstat", "-z", "-M", base, sha], 30_000).catch((e) => gitErr(e, "读取 commit 文件清单失败"));
448
+ const ns: { status: string; path: string; oldPath?: string }[] = [];
449
+ {
450
+ const toks = statusOut.split("\0");
451
+ for (let i = 0; i < toks.length; i++) {
452
+ const t = toks[i];
453
+ if (!t) continue;
454
+ const letter = t[0] || "?";
455
+ const first = toks[++i] ?? "";
456
+ if (letter === "R" || letter === "C") {
457
+ const second = toks[++i] ?? "";
458
+ ns.push({ status: letter, path: second || first, oldPath: second ? first : undefined });
459
+ } else {
460
+ ns.push({ status: letter, path: first });
461
+ }
462
+ }
463
+ }
464
+ const counts = new Map<string, { a: number; d: number }>();
465
+ {
466
+ const toks = numOut.split("\0");
467
+ for (let i = 0; i < toks.length; i++) {
468
+ const t = toks[i];
469
+ if (!t) continue;
470
+ const i1 = t.indexOf("\t");
471
+ const i2 = i1 >= 0 ? t.indexOf("\t", i1 + 1) : -1;
472
+ if (i1 < 0 || i2 < 0) continue; // 防御:畸形记录跳过
473
+ const rec = { a: Number(t.slice(0, i1)) || 0, d: Number(t.slice(i1 + 1, i2)) || 0 };
474
+ const pathPart = t.slice(i2 + 1);
475
+ if (pathPart === "") {
476
+ const oldP = toks[++i] ?? "";
477
+ const newP = toks[++i] ?? "";
478
+ counts.set(oldP, rec);
479
+ counts.set(newP, rec);
480
+ } else {
481
+ counts.set(pathPart, rec);
482
+ }
483
+ }
484
+ }
485
+ return ns.map((e) => {
486
+ const c = counts.get(e.path) ?? counts.get(e.oldPath ?? "") ?? { a: 0, d: 0 };
487
+ return { path: e.path, oldPath: e.oldPath, status: e.status, additions: c.a, deletions: c.d };
488
+ });
489
+ }
490
+
491
+ /** commit 元信息 + 变更文件清单(merge 取第一父 diff——与 GitHub 一致;root commit 对空树) */
492
+ export async function gitCommitShow(cwd: string, ref: string): Promise<CommitInfo> {
493
+ const repo = await repoRoot(cwd);
494
+ const sha = await resolveCommit(repo, ref);
495
+ // 字段分隔用 %x1f(单元分隔符):subject/body 可含 \t 与任意可打印字符
496
+ const meta = await run(repo, ["show", "-s", "--format=%x1f%H%x1f%an%x1f%ae%x1f%aI%x1f%s%x1f%b%x1f%P", sha], 15_000).catch((e) => gitErr(e, "读取 commit 失败"));
497
+ const f = meta.split("\x1f");
498
+ const parents = (f[7] ?? "").split(/\s+/).filter(Boolean);
499
+ const base = parents[0] || EMPTY_TREE_SHA;
500
+ const files = await commitFileList(repo, base, sha);
501
+ return {
502
+ sha,
503
+ author: f[2] ?? "",
504
+ email: f[3] ?? "",
505
+ date: f[4] ?? "",
506
+ subject: f[5] ?? "",
507
+ body: (f[6] ?? "").replace(/\n$/, ""),
508
+ parents,
509
+ merge: parents.length > 1,
510
+ files,
511
+ additions: files.reduce((s, x) => s + x.additions, 0),
512
+ deletions: files.reduce((s, x) => s + x.deletions, 0),
513
+ };
514
+ }
515
+
516
+ /** 单文件 patch 面板内嵌查看上限(截断在行边界;完整审阅引导跳 aiti-git-review) */
517
+ const COMMIT_DIFF_MAX_BYTES = 400 * 1024;
518
+
519
+ export async function gitCommitDiff(cwd: string, ref: string, paths: unknown): Promise<{ patch: string; truncated: boolean }> {
520
+ const repo = await repoRoot(cwd);
521
+ const sha = await resolveCommit(repo, ref);
522
+ if (!Array.isArray(paths) || paths.length === 0 || paths.length > 4) fail(400, "paths 必须是 1-4 个文件路径(rename 传 [新路径, 旧路径])");
523
+ const rels = paths.map((p) => {
524
+ if (typeof p !== "string" || !p) fail(400, "path 必须是非空字符串");
525
+ try {
526
+ return safeRel(repo, p);
527
+ } catch {
528
+ fail(400, "路径越界: " + p);
529
+ }
530
+ });
531
+ const parents = await commitParents(repo, sha);
532
+ const base = parents[0] || EMPTY_TREE_SHA;
533
+ let out = "";
534
+ try {
535
+ out = await run(repo, ["diff", base, sha, "--", ...rels], 60_000);
536
+ } catch (e) {
537
+ gitErr(e, "读取 diff 失败");
538
+ }
539
+ const buf = Buffer.from(out, "utf8");
540
+ if (buf.length <= COMMIT_DIFF_MAX_BYTES) return { patch: out, truncated: false };
541
+ const cut = buf.subarray(0, COMMIT_DIFF_MAX_BYTES).toString("utf8");
542
+ const nl = cut.lastIndexOf("\n");
543
+ return { patch: (nl > 0 ? cut.slice(0, nl) : cut) + "\n…(已截断)", truncated: true };
544
+ }
545
+
546
+ /**
547
+ * cherry-pick 到当前分支。冲突(CHERRY_PICK_HEAD 在位)→ 409 + 未合并文件清单——
548
+ * 仓库留在 cherry-pick 中间态,UI 必须给出 abort 出口(opts.abort → --abort)。
549
+ */
550
+ export async function gitCherryPick(cwd: string, ref: string, opts?: { abort?: boolean }): Promise<{ ok: true; sha?: string }> {
551
+ const repo = await repoRoot(cwd);
552
+ return queueRepo(repo, async () => {
553
+ if (opts?.abort) {
554
+ try {
555
+ await run(repo, ["cherry-pick", "--abort"]);
556
+ } catch (e) {
557
+ gitErr(e, "终止 cherry-pick 失败(没有进行中的 cherry-pick?)");
558
+ }
559
+ await audit({ repo, cmd: "cherry-pick-abort" });
560
+ changed(repo, "commit", "cherry-pick abort");
561
+ return { ok: true as const };
562
+ }
563
+ const sha = await resolveCommit(repo, ref);
564
+ try {
565
+ await run(repo, ["cherry-pick", sha]);
566
+ } catch (e) {
567
+ const inPick = await run(repo, ["rev-parse", "--verify", "-q", "CHERRY_PICK_HEAD"], 15_000).then(() => true, () => false);
568
+ if (inPick) {
569
+ const files = (await run(repo, ["diff", "--name-only", "--diff-filter=U", "-z"], 30_000)).split("\0").filter(Boolean);
570
+ fail(409, "cherry-pick 冲突(可用「终止 cherry-pick」回到原状)", { conflict: true, files });
571
+ }
572
+ gitErr(e, "cherry-pick 失败(工作区有未提交改动?)");
573
+ }
574
+ await audit({ repo, cmd: "cherry-pick", sha });
575
+ changed(repo, "commit", "cherry-pick " + sha.slice(0, 8));
576
+ return { ok: true as const, sha };
577
+ });
578
+ }
579
+
580
+ // ── 暂存 / 丢弃 / 提交 ──────────────────────────────────────────────────────
581
+
582
+ const relPaths = (repo: string, paths: unknown): string[] => {
583
+ if (!Array.isArray(paths) || paths.length === 0) fail(400, "paths 必须是非空数组");
584
+ return paths.map((p) => {
585
+ if (typeof p !== "string") fail(400, "path 必须是字符串");
586
+ try {
587
+ return safeRel(repo, p);
588
+ } catch {
589
+ fail(400, "路径越界: " + p);
590
+ }
591
+ });
592
+ };
593
+
594
+ /** 嵌套去重:勾选了 ["dir", "dir/f.txt"] 时丢弃 dir/f.txt(dir 搬走后子路径已不存在) */
595
+ function dedupNested(paths: string[]): string[] {
596
+ const sorted = [...paths].sort();
597
+ const out: string[] = [];
598
+ for (const p of sorted) {
599
+ if (out.length === 0 || !p.startsWith(out[out.length - 1] + "/")) out.push(p);
600
+ }
601
+ return out;
602
+ }
603
+
604
+ /** 旧 git(<2.23)无 restore 时的回退:reset(index)/ checkout(worktree)等价形态 */
605
+ async function restoreOrLegacy(repo: string, trackedArgs: string[][], legacyArgs: string[][]): Promise<void> {
606
+ try {
607
+ for (const a of trackedArgs) await run(repo, a);
608
+ } catch (e) {
609
+ if (!looksLikeUnknownOption(e)) gitErr(e, "git restore 失败");
610
+ for (const a of legacyArgs) await run(repo, a);
611
+ }
612
+ }
613
+
614
+ export async function gitStage(cwd: string, paths: string[]): Promise<{ ok: true }> {
615
+ const repo = await repoRoot(cwd);
616
+ const rels = relPaths(repo, paths);
617
+ return queueRepo(repo, async () => {
618
+ try {
619
+ await run(repo, ["add", "--", ...rels]);
620
+ } catch (e) {
621
+ gitErr(e, "暂存失败");
622
+ }
623
+ await audit({ repo, cmd: "stage", paths: rels });
624
+ changed(repo, "stage", `stage ${rels.length} 文件`);
625
+ return { ok: true as const };
626
+ });
627
+ }
628
+
629
+ export async function gitUnstage(cwd: string, paths: string[]): Promise<{ ok: true }> {
630
+ const repo = await repoRoot(cwd);
631
+ const rels = relPaths(repo, paths);
632
+ return queueRepo(repo, async () => {
633
+ await restoreOrLegacy(repo, [["restore", "--staged", "--", ...rels]], [["reset", "-q", "--", ...rels]]);
634
+ await audit({ repo, cmd: "unstage", paths: rels });
635
+ changed(repo, "stage", `unstage ${rels.length} 文件`);
636
+ return { ok: true as const };
637
+ });
638
+ }
639
+
640
+ /**
641
+ * 丢弃工作区改动(IDE 语义:暂存区+工作区一起丢)。
642
+ * 全版本原语组合(不依赖 restore——Apple Git 2.24 的 restore --worktree --staged
643
+ * 无 --source 时 worktree 从 index 取内容,新增文件删不掉,实测 mac):
644
+ * reset -q(全部 unstage)→ ls-tree HEAD 分流:在 HEAD 的 checkout 恢复内容;
645
+ * 不在 HEAD(staged 新增)的 fs.rm 删文件。untracked 整树搬隔离区(EXDEV 回退 cp+rm)。
646
+ */
647
+ export async function gitDiscard(cwd: string, paths: string[]): Promise<{ ok: true; quarantined: string[] }> {
648
+ const repo = await repoRoot(cwd);
649
+ const rels = dedupNested(relPaths(repo, paths));
650
+ return queueRepo(repo, async () => {
651
+ const entries = await statusEntries(repo);
652
+ const untrackedSet = new Set(entries.filter((e) => e.xy === "??").map((e) => e.path));
653
+ const tracked: string[] = [];
654
+ const untracked: string[] = [];
655
+ for (const rel of rels) {
656
+ if (untrackedSet.has(rel) || untrackedSet.has(rel + "/")) untracked.push(rel);
657
+ else tracked.push(rel);
658
+ }
659
+ const quarantined: string[] = [];
660
+ if (tracked.length > 0) {
661
+ await run(repo, ["reset", "-q", "--", ...tracked]);
662
+ let headFiles = new Set<string>();
663
+ try {
664
+ const ls = await run(repo, ["ls-tree", "-r", "-z", "--name-only", "HEAD"], 30_000);
665
+ headFiles = new Set(ls.split("\0").filter(Boolean));
666
+ } catch { /* 空仓库无 HEAD:tracked 全是新增 */ }
667
+ const inHead = tracked.filter((p) => headFiles.has(p));
668
+ const added = tracked.filter((p) => !headFiles.has(p));
669
+ if (inHead.length > 0) {
670
+ try {
671
+ await run(repo, ["checkout", "--", ...inHead]);
672
+ } catch (e) {
673
+ gitErr(e, "丢弃已跟踪文件改动失败");
674
+ }
675
+ }
676
+ for (const p of added) {
677
+ await rm(join(repo, p), { force: true, recursive: false });
678
+ }
679
+ }
680
+ if (untracked.length > 0) {
681
+ if (!cacheDir) fail(500, "cacheDir 未配置,无法隔离未跟踪文件");
682
+ const ts = Date.now();
683
+ for (const rel of untracked) {
684
+ const src = join(repo, rel);
685
+ const dest = join(quarantineRoot(), String(ts), rel);
686
+ await mkdir(dirname(dest), { recursive: true });
687
+ try {
688
+ await rename(src, dest);
689
+ } catch (e) {
690
+ if ((e as { code?: string })?.code === "EXDEV") {
691
+ await cp(src, dest, { recursive: true, errorOnExist: true, force: false });
692
+ await rm(src, { recursive: true, force: true });
693
+ } else {
694
+ gitErr(e, "隔离区搬移失败: " + rel);
695
+ }
696
+ }
697
+ quarantined.push(dest);
698
+ }
699
+ }
700
+ await audit({ repo, cmd: "discard", paths: rels, quarantined });
701
+ changed(repo, "stage", `discard ${rels.length} 文件`);
702
+ return { ok: true as const, quarantined };
703
+ });
704
+ }
705
+
706
+ export async function gitCommit(cwd: string, message?: string, amend = false): Promise<{ ok: true; sha: string; summary: string }> {
707
+ const repo = await repoRoot(cwd);
708
+ if (!amend && (!message || typeof message !== "string")) fail(400, "缺少提交消息");
709
+ return queueRepo(repo, async () => {
710
+ const args = ["commit"];
711
+ if (amend) {
712
+ args.push("--amend");
713
+ if (message) args.push("-m", message);
714
+ else args.push("--no-edit");
715
+ } else args.push("-m", message as string);
716
+ try {
717
+ await run(repo, args);
718
+ } catch (e) {
719
+ gitErr(e, "提交失败(无暂存内容?)");
720
+ }
721
+ const sha = (await run(repo, ["rev-parse", "HEAD"], 15_000)).trim();
722
+ const summary = (await run(repo, ["log", "-1", "--pretty=%s"], 15_000)).trim();
723
+ await audit({ repo, cmd: "commit", sha, message: summary });
724
+ changed(repo, "commit", "commit: " + summary);
725
+ return { ok: true as const, sha, summary };
726
+ });
727
+ }
728
+
729
+ // ── plan 逐组执行(断点续跑) ────────────────────────────────────────────────
730
+
731
+ export interface PlanGroup { files: string[]; message: string }
732
+
733
+ export async function gitPlanExecute(cwd: string, groups: PlanGroup[]): Promise<{ ok: boolean; completed: number; failedGroup: number | null; shas: string[]; error?: string }> {
734
+ const repo = await repoRoot(cwd);
735
+ if (!Array.isArray(groups) || groups.length === 0) fail(400, "groups 必须是非空数组");
736
+ return queueRepo(repo, async () => {
737
+ const shas: string[] = [];
738
+ for (let i = 0; i < groups.length; i++) {
739
+ const g = groups[i];
740
+ if (!g || !Array.isArray(g.files) || g.files.length === 0 || !g.message) {
741
+ return { ok: false, completed: i, failedGroup: i, shas, error: `第 ${i + 1} 组格式非法(files 非空 + message 必填)` };
742
+ }
743
+ const rels = relPaths(repo, g.files);
744
+ try {
745
+ await run(repo, ["add", "--", ...rels]);
746
+ await run(repo, ["commit", "-m", g.message]);
747
+ shas.push((await run(repo, ["rev-parse", "HEAD"], 15_000)).trim());
748
+ } catch (e) {
749
+ const err = e as { stderr?: string; message?: string };
750
+ await audit({ repo, cmd: "plan-execute", failedGroup: i, error: err.stderr || err.message });
751
+ return { ok: false, completed: i, failedGroup: i, shas, error: String(err.stderr || err.message || "").split("\n")[0] };
752
+ }
753
+ }
754
+ await audit({ repo, cmd: "plan-execute", groups: groups.length, shas });
755
+ changed(repo, "commit", `plan execute ${groups.length} 组`);
756
+ return { ok: true, completed: groups.length, failedGroup: null, shas };
757
+ });
758
+ }
759
+
760
+ /** 回滚本计划 = reset --mixed <baseHEAD>(仅显式按钮调用;禁 --hard) */
761
+ export async function gitPlanRollback(cwd: string, baseHEAD: string): Promise<{ ok: true }> {
762
+ const repo = await repoRoot(cwd);
763
+ return queueRepo(repo, async () => {
764
+ const sha = await resolveCommit(repo, baseHEAD);
765
+ try {
766
+ await run(repo, ["reset", "--mixed", sha]);
767
+ } catch (e) {
768
+ gitErr(e, "回滚失败");
769
+ }
770
+ await audit({ repo, cmd: "plan-rollback", baseHEAD: sha });
771
+ changed(repo, "commit", "plan rollback");
772
+ return { ok: true as const };
773
+ });
774
+ }
775
+
776
+ // ── stash 家族 ──────────────────────────────────────────────────────────────
777
+
778
+ const stashRef = (index: number) => {
779
+ if (!Number.isInteger(index) || index < 0) fail(400, "index 必须是非负整数");
780
+ return `stash@{${index}}`;
781
+ };
782
+
783
+ export async function stashList(cwd: string): Promise<{ items: { ref: string; sha: string; date: string; message: string }[] }> {
784
+ const repo = await repoRoot(cwd);
785
+ let out = "";
786
+ try {
787
+ // -z:记录 NUL 结尾(消息可含任意字符不串行);%s 为 subject(无换行),\t 分隔前 3 字段
788
+ out = await run(repo, ["stash", "list", "-z", "--date=iso", "--pretty=format:%gd%x09%H%x09%cd%x09%s"], 30_000);
789
+ } catch (e) {
790
+ gitErr(e, "stash list 失败");
791
+ }
792
+ const items = out.split("\0").filter(Boolean).map((rec) => {
793
+ const parts = rec.split("\t");
794
+ return { ref: parts[0], sha: parts[1], date: parts[2], message: parts.slice(3).join("\t") };
795
+ });
796
+ return { items };
797
+ }
798
+
799
+ export async function stashPush(cwd: string, opts: { message?: string; includeUntracked?: boolean; paths?: string[] }): Promise<{ ok: true; hadChanges: boolean }> {
800
+ const repo = await repoRoot(cwd);
801
+ return queueRepo(repo, async () => {
802
+ const args = ["stash", "push"];
803
+ if (opts.includeUntracked) args.push("--include-untracked");
804
+ if (opts.message) args.push("-m", opts.message);
805
+ let rels: string[] | null = null;
806
+ if (opts.paths) {
807
+ rels = relPaths(repo, opts.paths);
808
+ args.push("--", ...rels);
809
+ }
810
+ // 失败必须透传(pathspec 不匹配/锁冲突等)——静默 ok 会让 UI 误报「已暂存」
811
+ let out = "";
812
+ try {
813
+ out = await run(repo, args);
814
+ } catch (e) {
815
+ gitErr(e, "stash push 失败");
816
+ }
817
+ const hadChanges = !/No local changes to save/i.test(out);
818
+ await audit({ repo, cmd: "stash-push", paths: rels ?? "(all)", hadChanges });
819
+ if (hadChanges) changed(repo, "stash", "stash push");
820
+ return { ok: true as const, hadChanges };
821
+ });
822
+ }
823
+
824
+ export async function stashApply(cwd: string, index: number, opts: { pop?: boolean; paths?: string[] }): Promise<{ ok: true }> {
825
+ const repo = await repoRoot(cwd);
826
+ const ref = stashRef(index);
827
+ return queueRepo(repo, async () => {
828
+ if (opts.paths) {
829
+ // 部分提取:tracked restore --source(旧 git 回退 checkout <ref> --);
830
+ // untracked checkout <stash>^3(第三父);条目保留不 drop
831
+ const rels = dedupNested(relPaths(repo, opts.paths));
832
+ const wanted = new Set(rels);
833
+ const untracked = new Set<string>();
834
+ try {
835
+ const ls = await run(repo, ["ls-tree", "-r", "-z", "--name-only", `${ref}^3`], 30_000);
836
+ for (const l of ls.split("\0").filter(Boolean)) if (wanted.has(l)) untracked.add(l);
837
+ } catch { /* 该 stash 无未跟踪部分 */ }
838
+ const tracked = rels.filter((p) => !untracked.has(p));
839
+ await restoreOrLegacy(
840
+ repo,
841
+ tracked.length > 0 ? [["restore", "--source", ref, "--", ...tracked]] : [],
842
+ tracked.length > 0 ? [["checkout", ref, "--", ...tracked]] : [],
843
+ );
844
+ for (const p of untracked) {
845
+ try {
846
+ await run(repo, ["checkout", `${ref}^3`, "--", p]);
847
+ } catch (e) {
848
+ gitErr(e, "部分提取失败: " + p);
849
+ }
850
+ }
851
+ await audit({ repo, cmd: "stash-apply", index, paths: rels, partial: true });
852
+ changed(repo, "stash", "stash apply (partial)");
853
+ return { ok: true as const };
854
+ }
855
+ try {
856
+ await run(repo, opts.pop ? ["stash", "pop", ref] : ["stash", "apply", ref]);
857
+ } catch (e) {
858
+ // pop 冲突时 git 自动保留条目——错误透传给 UI 引导「从 stash 建分支」
859
+ gitErr(e, (opts.pop ? "pop" : "apply") + " 失败(冲突时条目保留)");
860
+ }
861
+ await audit({ repo, cmd: "stash-apply", index, pop: !!opts.pop });
862
+ changed(repo, "stash", opts.pop ? "stash pop" : "stash apply");
863
+ return { ok: true as const };
864
+ });
865
+ }
866
+
867
+ export async function stashDrop(cwd: string, index: number): Promise<{ ok: true; sha: string }> {
868
+ const repo = await repoRoot(cwd);
869
+ const ref = stashRef(index);
870
+ return queueRepo(repo, async () => {
871
+ // locale 无关的 sha 来源:drop 前解析(drop 后该 ref 已清,rev-parse 必失败;
872
+ // 输出括号在本地化 git 下是全角「()」,半角正则不可依赖——只作补充)。
873
+ let sha = "";
874
+ try { sha = (await run(repo, ["rev-parse", ref], 10_000)).trim(); } catch { /* 无此条目 */ }
875
+ let out = "";
876
+ try {
877
+ out = await run(repo, ["stash", "drop", ref]);
878
+ } catch (e) {
879
+ gitErr(e, "drop 失败");
880
+ }
881
+ if (!sha) sha = (out.match(/\(([0-9a-f]{7,40})\)/))?.[1] ?? "";
882
+ await audit({ repo, cmd: "stash-drop", index, sha });
883
+ changed(repo, "stash", "stash drop");
884
+ return { ok: true as const, sha };
885
+ });
886
+ }
887
+
888
+ export async function stashBranch(cwd: string, index: number, name: string): Promise<{ ok: true }> {
889
+ const repo = await repoRoot(cwd);
890
+ const ref = stashRef(index);
891
+ await assertBranchName(repo, name);
892
+ return queueRepo(repo, async () => {
893
+ try {
894
+ await run(repo, ["stash", "branch", name, ref]);
895
+ } catch (e) {
896
+ gitErr(e, "stash branch 失败");
897
+ }
898
+ await audit({ repo, cmd: "stash-branch", index, name });
899
+ changed(repo, "stash", "stash branch " + name);
900
+ return { ok: true as const };
901
+ });
902
+ }
903
+
904
+ // ── 远端同步 ────────────────────────────────────────────────────────────────
905
+
906
+ async function currentBranch(repo: string): Promise<string> {
907
+ try {
908
+ return (await run(repo, ["symbolic-ref", "--short", "HEAD"], 15_000)).trim();
909
+ } catch {
910
+ fail(400, "detached HEAD,无法同步");
911
+ }
912
+ }
913
+
914
+ export async function gitPush(cwd: string, opts: { remote?: string; branch?: string; setUpstream?: boolean }): Promise<{ ok: true; output: string }> {
915
+ const repo = await repoRoot(cwd);
916
+ return queueRepo(repo, async () => {
917
+ const remote = assertSafeRef(opts.remote || "origin", "remote");
918
+ const branch = assertSafeRef(opts.branch || (await currentBranch(repo)), "branch");
919
+ const hasUpstream = await run(repo, ["rev-parse", "--abbrev-ref", "@{upstream}"], 15_000).then(() => true, () => false);
920
+ const args = ["push", "--atomic"];
921
+ if (opts.setUpstream || !hasUpstream) args.push("-u", remote, branch);
922
+ else args.push(remote, branch);
923
+ let out = "";
924
+ try {
925
+ out = await run(repo, args, 300_000);
926
+ } catch (e) {
927
+ gitErr(e, "push 失败");
928
+ }
929
+ await audit({ repo, cmd: "push", remote, branch });
930
+ changed(repo, "sync", `push ${remote}/${branch}`);
931
+ return { ok: true as const, output: out.trim().split("\n").slice(-5).join("\n") };
932
+ });
933
+ }
934
+
935
+ export async function gitPull(cwd: string, opts: { mode?: "ff-only" | "rebase" | "merge" }): Promise<{ ok: true; output: string }> {
936
+ const repo = await repoRoot(cwd);
937
+ const mode = opts.mode || "ff-only";
938
+ return queueRepo(repo, async () => {
939
+ const args = ["pull"];
940
+ if (mode === "rebase") args.push("--rebase");
941
+ else if (mode === "merge") args.push("--no-ff");
942
+ else args.push("--ff-only");
943
+ let out = "";
944
+ try {
945
+ out = await run(repo, args, 300_000);
946
+ } catch (e) {
947
+ gitErr(e, `pull 失败(${mode})`);
948
+ }
949
+ await audit({ repo, cmd: "pull", mode });
950
+ changed(repo, "sync", "pull " + mode);
951
+ return { ok: true as const, output: out.trim().split("\n").slice(-5).join("\n") };
952
+ });
953
+ }
954
+
955
+ export async function gitFetch(cwd: string, remote?: string): Promise<{ ok: true }> {
956
+ const repo = await repoRoot(cwd);
957
+ const r = assertSafeRef(remote || "origin", "remote");
958
+ return queueRepo(repo, async () => {
959
+ try {
960
+ await run(repo, ["fetch", r], 300_000);
961
+ } catch (e) {
962
+ gitErr(e, "fetch 失败");
963
+ }
964
+ await audit({ repo, cmd: "fetch", remote: r });
965
+ return { ok: true as const };
966
+ });
967
+ }