lemma-agent 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +121 -2
  2. package/bin/lemma.mjs +42 -0
  3. package/dist/acceptance.js +63 -0
  4. package/dist/admin.js +1482 -0
  5. package/dist/agents.js +245 -0
  6. package/dist/api-member.js +537 -0
  7. package/dist/app.js +161 -0
  8. package/dist/board.js +185 -0
  9. package/dist/business-tools.js +153 -0
  10. package/dist/change-ops.js +91 -0
  11. package/dist/changes.js +46 -0
  12. package/dist/cli-runner.js +106 -0
  13. package/dist/code-tools.js +396 -0
  14. package/dist/coding-benchmark-fixtures.js +1049 -0
  15. package/dist/coding-benchmark-suite.js +1252 -0
  16. package/dist/collaboration-benchmark.js +349 -0
  17. package/dist/config.js +392 -0
  18. package/dist/context-benchmark.js +91 -0
  19. package/dist/conventions.js +282 -0
  20. package/dist/conversation.js +39 -0
  21. package/dist/credentials.js +44 -0
  22. package/dist/deliverables.js +43 -0
  23. package/dist/digest.js +129 -0
  24. package/dist/dispatch.js +801 -0
  25. package/dist/execution-settings.js +24 -0
  26. package/dist/git-workbench.js +800 -0
  27. package/dist/git.js +149 -0
  28. package/dist/integration-git.js +108 -0
  29. package/dist/integrations.js +557 -0
  30. package/dist/jobs.js +100 -0
  31. package/dist/lead.js +263 -0
  32. package/dist/learning.js +36 -0
  33. package/dist/main.js +1402 -0
  34. package/dist/mcp-settings.js +45 -0
  35. package/dist/mcp-tools.js +102 -0
  36. package/dist/member-settings.js +245 -0
  37. package/dist/model-selection.js +48 -0
  38. package/dist/models.js +145 -0
  39. package/dist/native-selectors.js +45 -0
  40. package/dist/native-terminal-components.js +100 -0
  41. package/dist/ood-benchmark.js +660 -0
  42. package/dist/operations.js +21 -0
  43. package/dist/printer.js +113 -0
  44. package/dist/repair.js +102 -0
  45. package/dist/resources.js +31 -0
  46. package/dist/result-summary.js +8 -0
  47. package/dist/results.js +41 -0
  48. package/dist/scope.js +114 -0
  49. package/dist/sessions.js +95 -0
  50. package/dist/settings.js +30 -0
  51. package/dist/task-commands.js +37 -0
  52. package/dist/task-lifecycle.js +49 -0
  53. package/dist/task-readiness.js +22 -0
  54. package/dist/task-recovery.js +116 -0
  55. package/dist/task-review.js +70 -0
  56. package/dist/task-workflow.js +424 -0
  57. package/dist/terminal-layout.js +27 -0
  58. package/dist/terminal-state.js +145 -0
  59. package/dist/terminal.js +800 -0
  60. package/dist/tool-settings.js +111 -0
  61. package/dist/tools.js +1043 -0
  62. package/dist/ux-telemetry.js +127 -0
  63. package/dist/view.js +114 -0
  64. package/package.json +79 -6
  65. package/web/index.html +136 -0
  66. package/web/js/conversations.js +312 -0
  67. package/web/js/dag.js +495 -0
  68. package/web/js/drawer.js +139 -0
  69. package/web/js/editors.js +424 -0
  70. package/web/js/gitlens.js +844 -0
  71. package/web/js/main.js +152 -0
  72. package/web/js/sankey.js +476 -0
  73. package/web/js/store.js +291 -0
  74. package/web/js/ticket.js +151 -0
  75. package/web/js/timeline.js +183 -0
  76. package/web/js/topology.js +454 -0
  77. package/web/js/util.js +232 -0
  78. package/web/js/views.js +1496 -0
  79. package/web/style.css +5299 -0
@@ -0,0 +1,800 @@
1
+ // GitLens 风格多仓库图谱、提交与推送工作台,以及 Agent 自主管理 + 关键风险人工确认网关。
2
+ import { randomUUID } from "node:crypto";
3
+ import { execFile } from "node:child_process";
4
+ import { existsSync, readFileSync, statSync } from "node:fs";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { defineDoc, defineTool } from "@earendil-works/pi-durable";
7
+ import { arr, bool, obj, oneOf, opt, str } from "@earendil-works/pi-schema";
8
+ import { autonomyChecksForRoot } from "./config.js";
9
+ import { git } from "./git.js";
10
+ export const GitWorkbench = defineDoc({
11
+ kind: "lemma.git.workbench",
12
+ version: 1,
13
+ scope: "session",
14
+ initial: () => ({ requireHumanPush: false, gates: {} }),
15
+ checkpointWhen: () => false,
16
+ });
17
+ function makeGitError(message, extra = {}) {
18
+ const err = new Error(message);
19
+ Object.assign(err, extra);
20
+ return err;
21
+ }
22
+ function samePath(a, b) {
23
+ const left = resolve(a), right = resolve(b);
24
+ return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
25
+ }
26
+ function findGitRootSync(dir) {
27
+ let cur = resolve(dir);
28
+ while (true) {
29
+ if (existsSync(join(cur, ".git")))
30
+ return { root: cur, isGit: true };
31
+ const parent = dirname(cur);
32
+ if (parent === cur)
33
+ return { root: resolve(dir), isGit: false };
34
+ cur = parent;
35
+ }
36
+ }
37
+ export function isSensitiveGitPath(filePath) {
38
+ const norm = filePath.replace(/\\/g, "/");
39
+ const base = norm.split("/").pop() ?? norm;
40
+ return (/^\.env($|\.)/i.test(base) ||
41
+ /\.sqlite([-.]|$)/i.test(base) ||
42
+ /credentials\.json$/i.test(base) ||
43
+ /\.(pem|key|p12|pfx)$/i.test(base) ||
44
+ /(^|\/)(secrets?|private)\//i.test(norm));
45
+ }
46
+ function sanitizeRemoteUrl(url) {
47
+ return url.replace(/\/\/[^/@\s]+@/g, "//***@");
48
+ }
49
+ function validRefName(ref) {
50
+ return Boolean(ref) && !ref.startsWith("-") && !/[\s~^:?*[\\]|\.\./.test(ref);
51
+ }
52
+ function gitWithTimeout(cwd, args, timeoutMs = 25_000) {
53
+ return new Promise((res) => {
54
+ execFile("git", ["-C", cwd, ...args], {
55
+ maxBuffer: 64 * 1024 * 1024,
56
+ timeout: timeoutMs,
57
+ windowsHide: true,
58
+ encoding: "utf8",
59
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" },
60
+ }, (error, stdout, stderr) => {
61
+ const code = error ? (typeof error.code === "number" ? (error.code) : 1) : 0;
62
+ const extraErr = error && error.killed ? "Git 命令执行超时(可能是网络或凭据确认等待超时)。\n" : "";
63
+ res({ code, stdout: String(stdout ?? ""), stderr: extraErr + String(stderr ?? "") });
64
+ });
65
+ });
66
+ }
67
+ /** 列出当前会话涉及的 Git 仓库(主工作目录 + 外部改动所属仓库) */
68
+ export function discoverManagedRepoRoots(config, changes) {
69
+ const main = findGitRootSync(config.workdir);
70
+ const out = [{ root: main.root, isMain: true, isGit: main.isGit }];
71
+ for (const ch of changes.list()) {
72
+ if (!ch.root || !existsSync(ch.root))
73
+ continue;
74
+ const resolved = findGitRootSync(ch.root);
75
+ if (!out.some((item) => samePath(item.root, resolved.root))) {
76
+ out.push({ root: resolved.root, isMain: false, isGit: resolved.isGit });
77
+ }
78
+ }
79
+ return out;
80
+ }
81
+ /** 校验并解析前端或工具请求的仓库路径,禁止越界访问会话外任意目录 */
82
+ export function resolveManagedRepo(config, changes, requested) {
83
+ const repos = discoverManagedRepoRoots(config, changes);
84
+ if (!requested?.trim())
85
+ return repos[0];
86
+ const target = findGitRootSync(requested.trim()).root;
87
+ const hit = repos.find((item) => samePath(item.root, target) || samePath(item.root, requested.trim()));
88
+ if (!hit)
89
+ throw makeGitError("只能管理当前会话主仓库或已发生改动的关联仓库。", { statusCode: 403, code: "REPO_NOT_ALLOWED" });
90
+ return hit;
91
+ }
92
+ export function parseWorkingStatus(porcelainZ) {
93
+ const entries = [];
94
+ const parts = porcelainZ.split("\0");
95
+ for (let i = 0; i < parts.length; i++) {
96
+ const rec = parts[i];
97
+ if (!rec || rec.length < 4)
98
+ continue;
99
+ const x = rec[0];
100
+ const y = rec[1];
101
+ const path = rec.slice(3);
102
+ let origPath;
103
+ if (x === "R" || x === "C")
104
+ origPath = parts[++i];
105
+ const untracked = x === "?" && y === "?";
106
+ const conflict = x === "U" || y === "U" || (x === "A" && y === "A") || (x === "D" && y === "D");
107
+ const staged = !untracked && x !== " ";
108
+ const unstaged = !untracked && y !== " ";
109
+ const statusLabel = conflict ? "冲突" : untracked ? "未跟踪" : x === "A" ? "新增" : x === "D" || y === "D" ? "删除" : x === "R" || y === "R" ? "重命名" : "修改";
110
+ entries.push({ path, origPath, indexStatus: x, workStatus: y, statusLabel, staged, unstaged, untracked, conflict, sensitive: isSensitiveGitPath(path) });
111
+ }
112
+ return entries;
113
+ }
114
+ export async function readRepoSummary(entry, changes) {
115
+ const allChanges = changes.list().filter((c) => samePath(c.root, entry.root));
116
+ const changeCounts = {
117
+ pending: allChanges.filter((c) => c.status === "pending").length,
118
+ conflict: allChanges.filter((c) => c.status === "conflict").length,
119
+ running: allChanges.filter((c) => c.status === "running").length,
120
+ applied: allChanges.filter((c) => c.status === "applied").length,
121
+ };
122
+ const name = entry.root.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || entry.root;
123
+ if (!entry.isGit) {
124
+ return {
125
+ root: entry.root, name, isMain: entry.isMain, isGit: false,
126
+ branch: null, head: null, upstream: null, remote: null, ahead: 0, behind: 0, dirtyCount: 0, conflictCount: 0, remotes: [], changeCounts,
127
+ };
128
+ }
129
+ const [headRes, branchRes, upRes, remoteRes, statusRes] = await Promise.all([
130
+ git(entry.root, ["rev-parse", "--verify", "-q", "HEAD"]),
131
+ git(entry.root, ["symbolic-ref", "--short", "-q", "HEAD"]),
132
+ git(entry.root, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]),
133
+ git(entry.root, ["remote", "-v"]),
134
+ git(entry.root, ["status", "--porcelain=v1", "-z"]),
135
+ ]);
136
+ const head = headRes.code === 0 ? headRes.stdout.trim() : null;
137
+ const branch = branchRes.code === 0 ? branchRes.stdout.trim() : head ? `HEAD@${head.slice(0, 7)}` : null;
138
+ const upstream = upRes.code === 0 ? upRes.stdout.trim() : null;
139
+ const remotesMap = new Map();
140
+ for (const line of remoteRes.stdout.split(/\r?\n/)) {
141
+ const m = line.match(/^(\S+)\s+(\S+)\s+\((fetch|push)\)$/);
142
+ if (m && (!remotesMap.has(m[1]) || m[3] === "push"))
143
+ remotesMap.set(m[1], sanitizeRemoteUrl(m[2]));
144
+ }
145
+ const remotes = [...remotesMap.entries()].map(([rName, url]) => ({ name: rName, url }));
146
+ let ahead = 0;
147
+ let behind = 0;
148
+ let remote = upstream ? upstream.split("/")[0] ?? null : remotes[0]?.name ?? null;
149
+ if (upstream && head) {
150
+ const lr = await git(entry.root, ["rev-list", "--left-right", "--count", `HEAD...${upstream}`]);
151
+ if (lr.code === 0) {
152
+ const [a, b] = lr.stdout.trim().split(/\s+/).map(Number);
153
+ if (Number.isFinite(a))
154
+ ahead = a;
155
+ if (Number.isFinite(b))
156
+ behind = b;
157
+ }
158
+ }
159
+ else if (head && remote && branch) {
160
+ // 本地分支未设置 tracking 时,如远端已存在同名分支(如 origin/main)则计算差值,否则视为本地新建待发布提交数
161
+ const remoteRef = `${remote}/${branch}`;
162
+ const verifyRemote = await git(entry.root, ["rev-parse", "--verify", "-q", `refs/remotes/${remoteRef}`]);
163
+ if (verifyRemote.code === 0) {
164
+ const lr = await git(entry.root, ["rev-list", "--left-right", "--count", `HEAD...refs/remotes/${remoteRef}`]);
165
+ if (lr.code === 0) {
166
+ const [a, b] = lr.stdout.trim().split(/\s+/).map(Number);
167
+ if (Number.isFinite(a))
168
+ ahead = a;
169
+ if (Number.isFinite(b))
170
+ behind = b;
171
+ }
172
+ }
173
+ else {
174
+ const cnt = await git(entry.root, ["rev-list", "--count", "HEAD"]);
175
+ if (cnt.code === 0 && Number.isFinite(Number(cnt.stdout.trim())))
176
+ ahead = Number(cnt.stdout.trim());
177
+ }
178
+ }
179
+ const working = statusRes.code === 0 ? parseWorkingStatus(statusRes.stdout) : [];
180
+ return {
181
+ root: entry.root,
182
+ name,
183
+ isMain: entry.isMain,
184
+ isGit: true,
185
+ branch,
186
+ head,
187
+ upstream,
188
+ remote,
189
+ ahead,
190
+ behind,
191
+ dirtyCount: working.length,
192
+ conflictCount: working.filter((w) => w.conflict).length,
193
+ remotes,
194
+ changeCounts,
195
+ };
196
+ }
197
+ export async function listManagedRepos(config, changes) {
198
+ const entries = discoverManagedRepoRoots(config, changes);
199
+ return Promise.all(entries.map((e) => readRepoSummary(e, changes)));
200
+ }
201
+ /** 获取 GitLens Commit Graph 所需完整拓扑数据(工作区变更、提交图谱、分支与 Lemma worktree 关联) */
202
+ export async function inspectRepoGraph(config, changes, requestedRepo, limit = 60) {
203
+ const entry = resolveManagedRepo(config, changes, requestedRepo);
204
+ const repo = await readRepoSummary(entry, changes);
205
+ const repoChanges = changes.list().filter((c) => samePath(c.root, entry.root));
206
+ if (!entry.isGit) {
207
+ return { repo, working: [], branches: [], commits: [], repoChanges };
208
+ }
209
+ const statusRes = await git(entry.root, ["status", "--porcelain=v1", "-z"]);
210
+ const working = statusRes.code === 0 ? parseWorkingStatus(statusRes.stdout) : [];
211
+ const refFmt = "%(refname:short)%x1f%(upstream:short)%x1f%(HEAD)%x1f%(objectname:short)%x1f%(subject)";
212
+ const brRes = await git(entry.root, ["for-each-ref", `--format=${refFmt}`, "refs/heads"]);
213
+ const branches = brRes.code === 0
214
+ ? brRes.stdout
215
+ .split(/\r?\n/)
216
+ .filter(Boolean)
217
+ .map((line) => {
218
+ const [name = "", upstream = "", headMark = "", sha = "", subject = ""] = line.split("\x1f");
219
+ return { name, ...(upstream ? { upstream } : {}), head: headMark === "*", sha, subject };
220
+ })
221
+ : [];
222
+ const upstreamTipRes = repo.upstream ? await git(entry.root, ["rev-parse", "--verify", "-q", repo.upstream]) : null;
223
+ const upstreamTip = upstreamTipRes?.code === 0 ? upstreamTipRes.stdout.trim() : null;
224
+ const unpushedSet = new Set();
225
+ if (repo.upstream && repo.head) {
226
+ const upList = await git(entry.root, ["rev-list", `${repo.upstream}..HEAD`]);
227
+ if (upList.code === 0)
228
+ for (const s of upList.stdout.split(/\r?\n/).filter(Boolean))
229
+ unpushedSet.add(s.trim());
230
+ }
231
+ else if (repo.head && repo.remote && repo.branch) {
232
+ const fallbackRef = `refs/remotes/${repo.remote}/${repo.branch}`;
233
+ const v = await git(entry.root, ["rev-parse", "--verify", "-q", fallbackRef]);
234
+ if (v.code === 0) {
235
+ const upList = await git(entry.root, ["rev-list", `${fallbackRef}..HEAD`]);
236
+ if (upList.code === 0)
237
+ for (const s of upList.stdout.split(/\r?\n/).filter(Boolean))
238
+ unpushedSet.add(s.trim());
239
+ }
240
+ else {
241
+ const upList = await git(entry.root, ["rev-list", "-n", String(Math.max(10, Math.min(120, limit))), "HEAD"]);
242
+ if (upList.code === 0)
243
+ for (const s of upList.stdout.split(/\r?\n/).filter(Boolean))
244
+ unpushedSet.add(s.trim());
245
+ }
246
+ }
247
+ const changesByHead = new Map();
248
+ for (const ch of repoChanges) {
249
+ if (!ch.head || ch.status === "dropped")
250
+ continue;
251
+ const list = changesByHead.get(ch.head) ?? [];
252
+ list.push({
253
+ id: ch.id,
254
+ agent: ch.agent,
255
+ model: ch.model,
256
+ status: ch.status,
257
+ branch: ch.branch,
258
+ base: ch.base,
259
+ head: ch.head,
260
+ task: ch.task,
261
+ filesCount: ch.files.length,
262
+ add: ch.add,
263
+ del: ch.del,
264
+ basedOn: ch.basedOn,
265
+ integrationStatus: ch.integration?.status,
266
+ });
267
+ changesByHead.set(ch.head, list);
268
+ }
269
+ const commits = [];
270
+ if (repo.head) {
271
+ const safeLimit = Math.max(10, Math.min(120, Math.floor(limit)));
272
+ const logRes = await git(entry.root, [
273
+ "log",
274
+ "--all",
275
+ "--topo-order",
276
+ `-n`,
277
+ String(safeLimit),
278
+ "--shortstat",
279
+ `--format=__COMMIT__%n%H%x1f%P%x1f%D%x1f%an%x1f%ae%x1f%at%x1f%s`,
280
+ ]);
281
+ if (logRes.code === 0) {
282
+ const blocks = logRes.stdout.split("__COMMIT__\n").slice(1);
283
+ for (const block of blocks) {
284
+ const lines = block.split(/\r?\n/);
285
+ const header = lines[0];
286
+ if (!header)
287
+ continue;
288
+ const [sha = "", parentsRaw = "", refsRaw = "", author = "", email = "", atSec = "0", subject = ""] = header.split("\x1f");
289
+ let filesCount = 0, add = 0, del = 0;
290
+ const statLine = lines.find((l) => /file[s]? changed/.test(l));
291
+ if (statLine) {
292
+ const mf = statLine.match(/(\d+)\s+file/);
293
+ const ma = statLine.match(/(\d+)\s+insertion/);
294
+ const md = statLine.match(/(\d+)\s+deletion/);
295
+ if (mf)
296
+ filesCount = Number(mf[1]);
297
+ if (ma)
298
+ add = Number(ma[1]);
299
+ if (md)
300
+ del = Number(md[1]);
301
+ }
302
+ const refs = refsRaw
303
+ .split(",")
304
+ .map((r) => r.trim())
305
+ .filter(Boolean);
306
+ commits.push({
307
+ sha,
308
+ shortSha: sha.slice(0, 7),
309
+ parents: parentsRaw.trim() ? parentsRaw.trim().split(/\s+/) : [],
310
+ refs,
311
+ author,
312
+ email,
313
+ at: Number(atSec) * 1000,
314
+ subject,
315
+ filesCount,
316
+ add,
317
+ del,
318
+ isHead: sha === repo.head,
319
+ isUpstream: !!upstreamTip && sha === upstreamTip,
320
+ unpushed: unpushedSet.has(sha),
321
+ changes: changesByHead.get(sha) ?? [],
322
+ });
323
+ }
324
+ }
325
+ }
326
+ return { repo, working, branches, commits, repoChanges };
327
+ }
328
+ /** 获取单次提交或当前未提交工作区的文件树与 Diff */
329
+ export async function inspectRepoCommit(config, changes, requestedRepo, shaOrWorktree, fileFilter) {
330
+ const entry = resolveManagedRepo(config, changes, requestedRepo);
331
+ if (!entry.isGit)
332
+ throw makeGitError("该目录还不是 Git 仓库。", { statusCode: 400 });
333
+ const maxBytes = 350_000;
334
+ const filterArgs = fileFilter?.trim() ? ["--", fileFilter.trim()] : [];
335
+ if (shaOrWorktree === "WORKTREE") {
336
+ const statusRes = await git(entry.root, ["status", "--porcelain=v1", "-z"]);
337
+ const working = statusRes.code === 0 ? parseWorkingStatus(statusRes.stdout) : [];
338
+ const hasHead = (await git(entry.root, ["rev-parse", "--verify", "-q", "HEAD"])).code === 0;
339
+ const statsMap = new Map();
340
+ if (hasHead) {
341
+ const ns = await git(entry.root, ["diff", "--numstat", "-z", "--no-renames", "HEAD"]);
342
+ if (ns.code === 0) {
343
+ for (const rec of ns.stdout.split("\0").filter(Boolean)) {
344
+ const m = rec.match(/^(-|\d+)\t(-|\d+)\t([\s\S]+)$/);
345
+ if (m)
346
+ statsMap.set(m[3], { add: m[1] === "-" ? 0 : Number(m[1]), del: m[2] === "-" ? 0 : Number(m[2]), binary: m[1] === "-" || undefined });
347
+ }
348
+ }
349
+ }
350
+ const files = working.map((w) => {
351
+ const st = statsMap.get(w.path);
352
+ let add = st?.add ?? 0;
353
+ let del = st?.del ?? 0;
354
+ if (w.untracked && !st) {
355
+ try {
356
+ const full = join(entry.root, w.path);
357
+ const sz = statSync(full).size;
358
+ if (sz <= 128 * 1024) {
359
+ const raw = readFileSync(full);
360
+ if (!raw.includes(0))
361
+ add = raw.toString("utf8").split(/\r?\n/).length;
362
+ }
363
+ }
364
+ catch { }
365
+ }
366
+ return { path: w.path, add, del, binary: st?.binary, statusLabel: w.statusLabel, sensitive: w.sensitive };
367
+ });
368
+ let diffText = "";
369
+ if (hasHead) {
370
+ const d = await git(entry.root, ["diff", "--no-color", "--no-renames", "HEAD", ...filterArgs]);
371
+ if (d.code === 0)
372
+ diffText = d.stdout;
373
+ }
374
+ const targetUntracked = working.filter((w) => w.untracked && (!fileFilter?.trim() || w.path === fileFilter.trim()));
375
+ for (const u of targetUntracked.slice(0, 12)) {
376
+ try {
377
+ const full = join(entry.root, u.path);
378
+ const sz = statSync(full).size;
379
+ if (sz > 64 * 1024) {
380
+ diffText += `\ndiff --git a/${u.path} b/${u.path}\n@@ -0,0 +1,1 @@\n+[未跟踪文件过大(${sz} bytes),请直接在工作区查看]\n`;
381
+ continue;
382
+ }
383
+ const buf = readFileSync(full);
384
+ if (buf.includes(0)) {
385
+ diffText += `\ndiff --git a/${u.path} b/${u.path}\n@@ -0,0 +1,1 @@\n+[二进制未跟踪文件(${sz} bytes)]\n`;
386
+ continue;
387
+ }
388
+ const lines = buf.toString("utf8").split(/\r?\n/).slice(0, 200);
389
+ diffText += `\ndiff --git a/${u.path} b/${u.path}\nnew file mode 100644\n@@ -0,0 +1,${lines.length} @@\n${lines.map((l) => `+${l}`).join("\n")}\n`;
390
+ }
391
+ catch { }
392
+ }
393
+ const truncated = diffText.length > maxBytes;
394
+ return {
395
+ sha: "WORKTREE",
396
+ isWorktree: true,
397
+ subject: "当前工作区未提交改动",
398
+ files,
399
+ diff: truncated ? diffText.slice(0, maxBytes) : diffText,
400
+ truncated,
401
+ };
402
+ }
403
+ if (!/^[a-fA-F0-9]{4,40}$/.test(shaOrWorktree))
404
+ throw makeGitError("提交哈希格式无效。", { statusCode: 400 });
405
+ const verify = await git(entry.root, ["rev-parse", "--verify", "-q", `${shaOrWorktree}^{commit}`]);
406
+ if (verify.code !== 0)
407
+ throw makeGitError(`找不到提交 ${shaOrWorktree}。`, { statusCode: 404 });
408
+ const fullSha = verify.stdout.trim();
409
+ const metaRes = await git(entry.root, ["show", "-s", "--format=%H%x1f%P%x1f%D%x1f%an%x1f%at%x1f%s%x1f%b", fullSha]);
410
+ const [sha = fullSha, parentsRaw = "", refsRaw = "", author = "", atSec = "0", subject = "", body = ""] = metaRes.stdout.split("\x1f");
411
+ const ns = await git(entry.root, ["diff-tree", "--no-commit-id", "--numstat", "-r", "--root", "-z", "--no-renames", fullSha]);
412
+ const files = [];
413
+ if (ns.code === 0) {
414
+ for (const rec of ns.stdout.split("\0").filter(Boolean)) {
415
+ const m = rec.match(/^(-|\d+)\t(-|\d+)\t([\s\S]+)$/);
416
+ if (m)
417
+ files.push({ path: m[3], add: m[1] === "-" ? 0 : Number(m[1]), del: m[2] === "-" ? 0 : Number(m[2]), binary: m[1] === "-" || undefined, sensitive: isSensitiveGitPath(m[3]) });
418
+ }
419
+ }
420
+ const patchRes = await git(entry.root, ["show", "--no-color", "--no-renames", "--format=", "--patch", "--root", fullSha, ...filterArgs]);
421
+ const rawDiff = patchRes.code === 0 ? patchRes.stdout : "";
422
+ const truncated = rawDiff.length > maxBytes;
423
+ return {
424
+ sha,
425
+ isWorktree: false,
426
+ author,
427
+ at: Number(atSec) * 1000,
428
+ parents: parentsRaw.trim() ? parentsRaw.trim().split(/\s+/) : [],
429
+ refs: refsRaw.split(",").map((r) => r.trim()).filter(Boolean),
430
+ subject,
431
+ body: body.trim(),
432
+ files,
433
+ diff: truncated ? rawDiff.slice(0, maxBytes) : rawDiff,
434
+ truncated,
435
+ };
436
+ }
437
+ export async function recordPushGate(harness, context, gateInput) {
438
+ const gate = { ...gateInput, id: `gate-${randomUUID().slice(0, 8)}`, status: "pending", createdAt: Date.now() };
439
+ if (harness && context) {
440
+ await harness.commit(async (tx) => {
441
+ const doc = await tx.doc(GitWorkbench);
442
+ // 若同一仓库同一动作已存在未处理网关,更新它以免重复刷屏
443
+ const existing = Object.values(doc.gates).find((g) => g.status === "pending" && samePath(g.repo, gate.repo) && g.action === gate.action && g.branch === gate.branch);
444
+ if (existing) {
445
+ gate.id = existing.id;
446
+ doc.gates[existing.id] = gate;
447
+ }
448
+ else {
449
+ doc.gates[gate.id] = gate;
450
+ }
451
+ }, context);
452
+ }
453
+ return gate;
454
+ }
455
+ export async function setGitPushPolicy(harness, context, requireHumanPush) {
456
+ let out;
457
+ await harness.commit(async (tx) => {
458
+ const doc = await tx.doc(GitWorkbench);
459
+ doc.requireHumanPush = requireHumanPush;
460
+ out = JSON.parse(JSON.stringify(doc));
461
+ }, context);
462
+ return out;
463
+ }
464
+ export async function fetchManagedRepo(config, changes, requestedRepo, remote) {
465
+ const entry = resolveManagedRepo(config, changes, requestedRepo);
466
+ if (!entry.isGit)
467
+ throw makeGitError("该目录不是 Git 仓库。", { statusCode: 400 });
468
+ const targetRemote = remote?.trim() || (await readRepoSummary(entry, changes)).remote || "origin";
469
+ if (!validRefName(targetRemote))
470
+ throw makeGitError("Remote 名称无效。", { statusCode: 400 });
471
+ const res = await gitWithTimeout(entry.root, ["fetch", "--prune", targetRemote]);
472
+ if (res.code !== 0)
473
+ throw makeGitError(`git fetch 失败:${(res.stderr || res.stdout).trim() || "请检查网络或代理/凭据设置"}`, { statusCode: 409 });
474
+ return { repo: await readRepoSummary(entry, changes), output: (res.stdout + res.stderr).trim() || `已从 ${targetRemote} 更新远端状态` };
475
+ }
476
+ export async function pullManagedRepo(deps, opts) {
477
+ const entry = resolveManagedRepo(deps.config, deps.changes, opts.repo);
478
+ if (!entry.isGit)
479
+ throw makeGitError("该目录不是 Git 仓库。", { statusCode: 400 });
480
+ const summary = await readRepoSummary(entry, deps.changes);
481
+ if (summary.dirtyCount > 0)
482
+ throw makeGitError("工作区有未提交改动,请先提交后再拉取(pull --ff-only)。", { statusCode: 409 });
483
+ const remote = opts.remote?.trim() || summary.remote || "origin";
484
+ const branch = opts.branch?.trim() || summary.branch || "";
485
+ if (!validRefName(remote) || (branch && !validRefName(branch)))
486
+ throw makeGitError("分支或 Remote 名称无效。", { statusCode: 400 });
487
+ const args = branch ? ["pull", "--ff-only", remote, branch] : ["pull", "--ff-only"];
488
+ const res = await gitWithTimeout(entry.root, args);
489
+ if (res.code !== 0) {
490
+ const msg = (res.stderr || res.stdout).trim();
491
+ if (opts.actor === "agent") {
492
+ const gate = await recordPushGate(deps.harness, deps.context, {
493
+ repo: entry.root,
494
+ action: "pull",
495
+ branch: branch || "HEAD",
496
+ remote,
497
+ reason: `无法快进拉取(ff-only),本地与 ${remote} 可能已分叉,需人工决策合并或变基。`,
498
+ details: [msg.slice(-400)],
499
+ });
500
+ throw makeGitError(gate.reason, { statusCode: 409, code: "HUMAN_GATE", gate });
501
+ }
502
+ throw makeGitError(`快进拉取失败:${msg}`, { statusCode: 409 });
503
+ }
504
+ return { repo: await readRepoSummary(entry, deps.changes), output: (res.stdout + res.stderr).trim() || "快进拉取成功" };
505
+ }
506
+ export async function commitManagedRepo(deps, opts) {
507
+ const entry = resolveManagedRepo(deps.config, deps.changes, opts.repo);
508
+ if (!entry.isGit)
509
+ throw makeGitError("该目录不是 Git 仓库。", { statusCode: 400 });
510
+ const message = opts.message.trim();
511
+ if (!message)
512
+ throw makeGitError("提交说明(Commit message)不能为空。", { statusCode: 400 });
513
+ const statusRes = await git(entry.root, ["status", "--porcelain=v1", "-z"]);
514
+ const working = statusRes.code === 0 ? parseWorkingStatus(statusRes.stdout) : [];
515
+ if (!working.length)
516
+ throw makeGitError("工作区干净,没有待提交的改动。", { statusCode: 409 });
517
+ const summary = await readRepoSummary(entry, deps.changes);
518
+ const targets = opts.files?.length ? working.filter((w) => opts.files.includes(w.path)) : working;
519
+ if (!targets.length)
520
+ throw makeGitError("未匹配到指定的待提交文件。", { statusCode: 400 });
521
+ const conflicts = targets.filter((w) => w.conflict).map((w) => w.path);
522
+ const diffCheck = await git(entry.root, ["diff", "--check"]);
523
+ const hasMarkers = diffCheck.code !== 0 && /conflict marker/i.test(diffCheck.stdout + diffCheck.stderr);
524
+ if (conflicts.length || hasMarkers) {
525
+ const reason = conflicts.length ? `存在未解决合并冲突:${conflicts.join("、")}` : "检测到残留冲突标记(<<<<<<< / >>>>>>>),不能提交。";
526
+ if (opts.actor === "agent") {
527
+ const gate = await recordPushGate(deps.harness, deps.context, {
528
+ repo: entry.root,
529
+ action: "commit",
530
+ branch: summary.branch ?? "HEAD",
531
+ message,
532
+ files: targets.map((t) => t.path),
533
+ reason,
534
+ });
535
+ throw makeGitError(reason, { statusCode: 409, code: "HUMAN_GATE", gate });
536
+ }
537
+ throw makeGitError(reason, { statusCode: 409 });
538
+ }
539
+ if (opts.actor === "agent") {
540
+ const sensitive = targets.filter((w) => w.sensitive).map((w) => w.path);
541
+ if (sensitive.length) {
542
+ const reason = `包含敏感或本地数据文件(${sensitive.join("、")}),已转为关键人工确认,禁止 Agent 自动提交。`;
543
+ const gate = await recordPushGate(deps.harness, deps.context, {
544
+ repo: entry.root,
545
+ action: "commit",
546
+ branch: summary.branch ?? "HEAD",
547
+ message,
548
+ files: targets.map((t) => t.path),
549
+ reason,
550
+ details: sensitive,
551
+ });
552
+ throw makeGitError(reason, { statusCode: 409, code: "HUMAN_GATE", gate });
553
+ }
554
+ const checks = autonomyChecksForRoot(entry.root, deps.config);
555
+ const failedApplied = deps.changes.list().find((ch) => samePath(ch.root, entry.root) && ch.status === "applied" && deps.config.autonomy.enabled && checks.length > 0 && ch.verification && !ch.verification.passed);
556
+ if (failedApplied) {
557
+ const reason = `改动 #${failedApplied.id} 的验收检查未通过,Agent 不能自动提交,需人工复核。`;
558
+ const gate = await recordPushGate(deps.harness, deps.context, {
559
+ repo: entry.root,
560
+ action: "commit",
561
+ branch: summary.branch ?? "HEAD",
562
+ message,
563
+ files: targets.map((t) => t.path),
564
+ reason,
565
+ });
566
+ throw makeGitError(reason, { statusCode: 409, code: "HUMAN_GATE", gate });
567
+ }
568
+ }
569
+ if (opts.files?.length) {
570
+ await git(entry.root, ["reset", "-q"]);
571
+ const addRes = await git(entry.root, ["add", "-A", "--", ...targets.map((t) => t.path)]);
572
+ if (addRes.code !== 0)
573
+ throw makeGitError(`暂存文件失败:${addRes.stderr.trim()}`, { statusCode: 409 });
574
+ }
575
+ else {
576
+ const addRes = await git(entry.root, ["add", "-A"]);
577
+ if (addRes.code !== 0)
578
+ throw makeGitError(`暂存全部文件失败:${addRes.stderr.trim()}`, { statusCode: 409 });
579
+ }
580
+ const stagedCheck = await git(entry.root, ["diff", "--cached", "--quiet"]);
581
+ if (stagedCheck.code === 0)
582
+ throw makeGitError("暂存区没有实际变动内容,未生成空提交。", { statusCode: 409 });
583
+ const hasName = (await git(entry.root, ["config", "user.name"])).code === 0;
584
+ const hasEmail = (await git(entry.root, ["config", "user.email"])).code === 0;
585
+ const authorArgs = hasName && hasEmail ? [] : ["-c", "user.name=pi-agent", "-c", "user.email=pi-agent@localhost"];
586
+ const commitRes = await git(entry.root, [...authorArgs, "commit", "-q", "-m", message]);
587
+ if (commitRes.code !== 0)
588
+ throw makeGitError(`提交失败:${(commitRes.stderr || commitRes.stdout).trim()}`, { statusCode: 409 });
589
+ const newHead = (await git(entry.root, ["rev-parse", "HEAD"])).stdout.trim();
590
+ return { repo: await readRepoSummary(entry, deps.changes), sha: newHead, message, committedFiles: targets.length };
591
+ }
592
+ export async function pushManagedRepo(deps, opts) {
593
+ const entry = resolveManagedRepo(deps.config, deps.changes, opts.repo);
594
+ if (!entry.isGit)
595
+ throw makeGitError("该目录不是 Git 仓库。", { statusCode: 400 });
596
+ const summary = await readRepoSummary(entry, deps.changes);
597
+ const remote = opts.remote?.trim() || summary.remote || "";
598
+ if (!remote)
599
+ throw makeGitError("当前仓库尚未配置远程仓库(remote),无法推送。", { statusCode: 409 });
600
+ const branch = opts.branch?.trim() || summary.branch || "";
601
+ if (!branch || branch.startsWith("HEAD@") || !validRefName(remote) || !validRefName(branch)) {
602
+ throw makeGitError("请先签出有效分支后再推送(当前处于游离 HEAD 或分支名无效)。", { statusCode: 409 });
603
+ }
604
+ const isCurrentBranch = summary.branch === branch;
605
+ if (opts.forceWithLease && opts.actor === "agent") {
606
+ const gate = await recordPushGate(deps.harness, deps.context, {
607
+ repo: entry.root,
608
+ action: "force_push",
609
+ branch,
610
+ remote,
611
+ reason: "强制推送(--force-with-lease)属于高危历史改写操作,禁止 Agent 自动执行,必须由人工确认。",
612
+ });
613
+ throw makeGitError(gate.reason, { statusCode: 409, code: "HUMAN_GATE", gate });
614
+ }
615
+ if (opts.actor === "agent") {
616
+ const wb = deps.harness && deps.context ? await deps.harness.snapshot(GitWorkbench, deps.context) : undefined;
617
+ if (wb?.requireHumanPush) {
618
+ const gate = await recordPushGate(deps.harness, deps.context, {
619
+ repo: entry.root,
620
+ action: "push",
621
+ branch,
622
+ remote,
623
+ reason: "已启用「推送前人工确认」,请核对 GitLens 提交图与改动后批准推送。",
624
+ details: [`目标:${remote}/${branch}`, `待推送提交:${summary.ahead}`],
625
+ });
626
+ throw makeGitError(gate.reason, { statusCode: 409, code: "HUMAN_GATE", gate });
627
+ }
628
+ if (isCurrentBranch && summary.conflictCount > 0) {
629
+ const gate = await recordPushGate(deps.harness, deps.context, {
630
+ repo: entry.root,
631
+ action: "push",
632
+ branch,
633
+ remote,
634
+ reason: "工作区仍存在未解决冲突,禁止 Agent 推送。",
635
+ });
636
+ throw makeGitError(gate.reason, { statusCode: 409, code: "HUMAN_GATE", gate });
637
+ }
638
+ if (isCurrentBranch && summary.dirtyCount > 0) {
639
+ const gate = await recordPushGate(deps.harness, deps.context, {
640
+ repo: entry.root,
641
+ action: "push",
642
+ branch,
643
+ remote,
644
+ reason: `工作区还有 ${summary.dirtyCount} 个未提交文件,Agent 不在未确认状态自动推送,请先提交或人工确认。`,
645
+ });
646
+ throw makeGitError(gate.reason, { statusCode: 409, code: "HUMAN_GATE", gate });
647
+ }
648
+ const checks = autonomyChecksForRoot(entry.root, deps.config);
649
+ const failed = deps.changes.list().find((ch) => samePath(ch.root, entry.root) && ["applied", "pending"].includes(ch.status) && (isCurrentBranch || ch.branch === branch) && deps.config.autonomy.enabled && checks.length > 0 && ch.verification && !ch.verification.passed);
650
+ if (failed) {
651
+ const gate = await recordPushGate(deps.harness, deps.context, {
652
+ repo: entry.root,
653
+ action: "push",
654
+ branch,
655
+ remote,
656
+ reason: `改动 #${failed.id} 未通过配置验收检查,禁止 Agent 自动推送,需人工决定。`,
657
+ });
658
+ throw makeGitError(gate.reason, { statusCode: 409, code: "HUMAN_GATE", gate });
659
+ }
660
+ }
661
+ // 推送当前分支且未勾选强推时,先探测是否落后/分叉
662
+ if (isCurrentBranch && !opts.forceWithLease) {
663
+ await gitWithTimeout(entry.root, ["fetch", "--quiet", remote], 15_000).catch(() => null);
664
+ const latest = await readRepoSummary(entry, deps.changes);
665
+ if (latest.behind > 0) {
666
+ const reason = `远端 ${remote}/${branch} 领先本地 ${latest.behind} 个提交(本地领先 ${latest.ahead} 个),存在分叉不能直接快进推送。`;
667
+ if (opts.actor === "agent") {
668
+ const gate = await recordPushGate(deps.harness, deps.context, {
669
+ repo: entry.root,
670
+ action: "force_push",
671
+ branch,
672
+ remote,
673
+ reason: `${reason} 已转人工处理(先拉取或安全强推)。`,
674
+ details: [`ahead: ${latest.ahead}`, `behind: ${latest.behind}`],
675
+ });
676
+ throw makeGitError(gate.reason, { statusCode: 409, code: "HUMAN_GATE", gate, ahead: latest.ahead, behind: latest.behind });
677
+ }
678
+ throw makeGitError(reason, { statusCode: 409, code: "DIVERGED", ahead: latest.ahead, behind: latest.behind });
679
+ }
680
+ }
681
+ const args = ["push"];
682
+ if (opts.forceWithLease)
683
+ args.push("--force-with-lease");
684
+ if (opts.setUpstream || !summary.upstream)
685
+ args.push("-u");
686
+ args.push(remote, branch);
687
+ const pushRes = await gitWithTimeout(entry.root, args, 30_000);
688
+ if (pushRes.code !== 0) {
689
+ const msg = (pushRes.stderr || pushRes.stdout).trim();
690
+ const diverged = /non-fast-forward|fetch first|rejected/i.test(msg);
691
+ if (diverged && opts.actor === "agent") {
692
+ const gate = await recordPushGate(deps.harness, deps.context, {
693
+ repo: entry.root,
694
+ action: "force_push",
695
+ branch,
696
+ remote,
697
+ reason: `推送被远端拒绝(non-fast-forward),需人工确认拉取合并或强推。`,
698
+ details: [msg.slice(-400)],
699
+ });
700
+ throw makeGitError(gate.reason, { statusCode: 409, code: "HUMAN_GATE", gate });
701
+ }
702
+ throw makeGitError(`git push 失败:${msg || "请检查网络/代理或远端权限"}`, { statusCode: 409, ...(diverged ? { code: "DIVERGED" } : {}) });
703
+ }
704
+ return { repo: await readRepoSummary(entry, deps.changes), remote, branch, output: (pushRes.stdout + pushRes.stderr).trim() || `已成功推送到 ${remote}/${branch}` };
705
+ }
706
+ export async function resolvePushGate(deps, gateId, decision, note) {
707
+ const wb = await deps.harness.snapshot(GitWorkbench, deps.context);
708
+ const gate = wb?.gates[gateId];
709
+ if (!gate)
710
+ throw makeGitError(`找不到待确认记录 ${gateId}。`, { statusCode: 404 });
711
+ if (gate.status !== "pending")
712
+ throw makeGitError(`该记录已经处理(${gate.status})。`, { statusCode: 409 });
713
+ let result;
714
+ if (decision === "approve") {
715
+ if (gate.action === "commit") {
716
+ result = await commitManagedRepo(deps, { repo: gate.repo, message: gate.message || "commit reviewed changes", files: gate.files, actor: "human" });
717
+ }
718
+ else if (gate.action === "push") {
719
+ result = await pushManagedRepo(deps, { repo: gate.repo, branch: gate.branch, remote: gate.remote, actor: "human" });
720
+ }
721
+ else if (gate.action === "force_push") {
722
+ result = await pushManagedRepo(deps, { repo: gate.repo, branch: gate.branch, remote: gate.remote, forceWithLease: true, actor: "human" });
723
+ }
724
+ else if (gate.action === "pull") {
725
+ result = await pullManagedRepo(deps, { repo: gate.repo, branch: gate.branch, remote: gate.remote, actor: "human" });
726
+ }
727
+ }
728
+ let saved;
729
+ await deps.harness.commit(async (tx) => {
730
+ const doc = await tx.doc(GitWorkbench);
731
+ const cur = doc.gates[gateId];
732
+ cur.status = decision === "approve" ? "approved" : "rejected";
733
+ cur.resolvedAt = Date.now();
734
+ if (note?.trim())
735
+ cur.resolutionNote = note.trim();
736
+ saved = JSON.parse(JSON.stringify(cur));
737
+ }, deps.context);
738
+ return { gate: saved, result };
739
+ }
740
+ /** 供总调度自主管理日常 Git(status / fetch / clean commit / clean ff push),关键风险自动转人工网关 */
741
+ export function createRepoGitTool(deps) {
742
+ return defineTool({
743
+ name: "repo_git",
744
+ description: "管理主仓库及本次会话关联外部仓库的 Git 状态与日常提交流转。支持 status(查看分支/ahead-behind/未提交/worktree)、fetch、commit(仅在无冲突、无敏感文件和检查未失败时提交)、push(仅允许干净无分叉的快进推送)及 pull(仅 ff-only)。凡涉及历史分叉、强制推送、冲突、敏感文件或“推送前需人工确认”设置,系统会自动拦截并生成待人工确认单提交到后台网页 GitLens 工作台,绝不强行越权。",
745
+ parameters: obj({
746
+ action: oneOf(["status", "fetch", "commit", "push", "pull"]),
747
+ repo: opt(str({ description: "可选:目标仓库根目录(不传默认为主工作目录;跨仓库协作时可传对应外部仓库路径)" })),
748
+ message: opt(str({ description: "commit 时必填:清晰语义化的提交说明" })),
749
+ files: opt(arr(str(), { description: "可选:commit 时仅提交指定的相对路径列表" })),
750
+ remote: opt(str({ description: "可选:remote 名称,默认使用当前跟踪远端或 origin" })),
751
+ branch: opt(str({ description: "可选:push/pull 的目标分支,默认当前签出分支" })),
752
+ }),
753
+ replay: "safe",
754
+ execute: async (args, api, context) => {
755
+ const harness = deps.getHarness();
756
+ try {
757
+ if (args.action === "status") {
758
+ const repos = await listManagedRepos(deps.config, deps.changes);
759
+ const target = args.repo ? await inspectRepoGraph(deps.config, deps.changes, args.repo, 20) : null;
760
+ const wb = harness ? await harness.snapshot(GitWorkbench, context) : undefined;
761
+ const pendingGates = Object.values(wb?.gates ?? {}).filter((g) => g.status === "pending");
762
+ return {
763
+ output: [{ type: "text", text: JSON.stringify({ repos, detail: target ? { repo: target.repo, working: target.working, branches: target.branches, recentCommits: target.commits.slice(0, 12) } : undefined, requireHumanPush: wb?.requireHumanPush ?? false, pendingGates }) }],
764
+ };
765
+ }
766
+ if (args.action === "fetch") {
767
+ const res = await fetchManagedRepo(deps.config, deps.changes, args.repo, args.remote);
768
+ deps.onChanged?.(`Agent fetch (${res.repo.name}):${res.output}`);
769
+ return { output: [{ type: "text", text: JSON.stringify(res) }] };
770
+ }
771
+ if (args.action === "pull") {
772
+ const res = await pullManagedRepo({ config: deps.config, changes: deps.changes, harness, context }, { repo: args.repo, remote: args.remote, branch: args.branch, actor: "agent" });
773
+ deps.onChanged?.(`Agent pull --ff-only (${res.repo.name}):${res.output}`);
774
+ return { output: [{ type: "text", text: JSON.stringify(res) }] };
775
+ }
776
+ if (args.action === "commit") {
777
+ if (!args.message?.trim())
778
+ return { output: [{ type: "text", text: "action=commit 需要提供 message 提交说明。" }], isError: true };
779
+ const res = await commitManagedRepo({ config: deps.config, changes: deps.changes, harness, context }, { repo: args.repo, message: args.message, files: args.files, actor: "agent" });
780
+ deps.onChanged?.(`Agent 提交 (${res.repo.name}@${res.sha.slice(0, 7)}):${res.message}`);
781
+ return { output: [{ type: "text", text: JSON.stringify(res) }] };
782
+ }
783
+ const res = await pushManagedRepo({ config: deps.config, changes: deps.changes, harness, context }, { repo: args.repo, remote: args.remote, branch: args.branch, actor: "agent" });
784
+ deps.onChanged?.(`Agent 推送 (${res.repo.name} -> ${res.remote}/${res.branch}):${res.output}`);
785
+ return { output: [{ type: "text", text: JSON.stringify(res) }] };
786
+ }
787
+ catch (error) {
788
+ const ge = error;
789
+ if (ge.code === "HUMAN_GATE" && ge.gate) {
790
+ deps.onChanged?.(`需人工确认 Git 操作(${ge.gate.action} · ${ge.gate.branch}):${ge.gate.reason}`);
791
+ return {
792
+ output: [{ type: "text", text: `【已触发关键人工确认单 #${ge.gate.id}】${ge.gate.reason}\n请提示用户在后台网页「改动 → GitLens 工作台」核对后一键批准或驳回,勿尝试强行绕过。` }],
793
+ isError: true,
794
+ };
795
+ }
796
+ return { output: [{ type: "text", text: ge.message || String(error) }], isError: true };
797
+ }
798
+ },
799
+ });
800
+ }