dsh-github-flow 0.3.0 → 0.4.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 (94) hide show
  1. package/README.en.md +220 -143
  2. package/README.md +202 -124
  3. package/docs/UPGRADE-NOTES.md +14 -8
  4. package/docs/architecture.md +111 -129
  5. package/lib/api/routes-actions.js +117 -0
  6. package/lib/api/routes-overview.js +94 -2
  7. package/lib/cache.d.ts +4 -0
  8. package/lib/cache.js +14 -0
  9. package/lib/client.d.ts +13 -1
  10. package/lib/client.js +2906 -2475
  11. package/lib/executor/git-parser.d.ts +25 -0
  12. package/lib/executor/git-parser.js +143 -0
  13. package/lib/executor/platform-guide.d.ts +14 -0
  14. package/lib/executor/platform-guide.js +40 -0
  15. package/lib/executor/process-utils.d.ts +51 -0
  16. package/lib/executor/process-utils.js +162 -0
  17. package/lib/executor/version-utils.d.ts +12 -0
  18. package/lib/executor/version-utils.js +27 -0
  19. package/lib/executor.d.ts +45 -48
  20. package/lib/executor.js +184 -353
  21. package/lib/git-watcher.d.ts +36 -0
  22. package/lib/git-watcher.js +91 -0
  23. package/lib/main.js +10 -0
  24. package/lib/renderers/cache.d.ts +8 -0
  25. package/lib/renderers/cache.js +66 -0
  26. package/lib/renderers/common.d.ts +24 -0
  27. package/lib/renderers/common.js +88 -0
  28. package/lib/renderers/gist.d.ts +15 -0
  29. package/lib/renderers/gist.js +99 -0
  30. package/lib/renderers/issue.d.ts +4 -0
  31. package/lib/renderers/issue.js +70 -0
  32. package/lib/renderers/label.d.ts +4 -0
  33. package/lib/renderers/label.js +48 -0
  34. package/lib/renderers/markdown.d.ts +15 -32
  35. package/lib/renderers/markdown.js +15 -624
  36. package/lib/renderers/pr.d.ts +4 -0
  37. package/lib/renderers/pr.js +107 -0
  38. package/lib/renderers/release.d.ts +4 -0
  39. package/lib/renderers/release.js +74 -0
  40. package/lib/renderers/repo.d.ts +4 -0
  41. package/lib/renderers/repo.js +149 -0
  42. package/lib/renderers/ruleset.d.ts +4 -0
  43. package/lib/renderers/ruleset.js +74 -0
  44. package/lib/renderers/run.d.ts +4 -0
  45. package/lib/renderers/run.js +79 -0
  46. package/lib/renderers/skill.d.ts +4 -0
  47. package/lib/renderers/skill.js +61 -0
  48. package/lib/renderers/status.d.ts +23 -0
  49. package/lib/renderers/status.js +124 -0
  50. package/lib/tools/cache.d.ts +64 -0
  51. package/lib/tools/cache.js +186 -0
  52. package/lib/tools/gist.d.ts +155 -0
  53. package/lib/tools/gist.js +190 -0
  54. package/lib/tools/help.js +107 -6
  55. package/lib/tools/image-utils.d.ts +8 -0
  56. package/lib/tools/image-utils.js +34 -0
  57. package/lib/tools/issue.d.ts +8 -1
  58. package/lib/tools/issue.js +26 -4
  59. package/lib/tools/label.d.ts +80 -0
  60. package/lib/tools/label.js +237 -0
  61. package/lib/tools/pr.d.ts +8 -0
  62. package/lib/tools/pr.js +48 -3
  63. package/lib/tools/ruleset.d.ts +80 -0
  64. package/lib/tools/ruleset.js +177 -0
  65. package/lib/tools/status.d.ts +39 -0
  66. package/lib/tools/status.js +53 -0
  67. package/lib/types.d.ts +39 -0
  68. package/lib/ui/auth-guide-card.d.ts +4 -0
  69. package/lib/ui/auth-guide-card.js +161 -0
  70. package/lib/ui/branch-selector.d.ts +10 -0
  71. package/lib/ui/branch-selector.js +163 -0
  72. package/lib/ui/commit-modal.d.ts +8 -0
  73. package/lib/ui/commit-modal.js +89 -0
  74. package/lib/ui/icons.d.ts +7 -0
  75. package/lib/ui/icons.js +53 -0
  76. package/lib/ui/network-banner.d.ts +10 -0
  77. package/lib/ui/network-banner.js +54 -0
  78. package/lib/ui/storage.d.ts +26 -0
  79. package/lib/ui/storage.js +134 -0
  80. package/lib/ui/styles.d.ts +6 -0
  81. package/lib/ui/styles.js +1285 -0
  82. package/lib/ui/sync-settings-modal.d.ts +11 -0
  83. package/lib/ui/sync-settings-modal.js +350 -0
  84. package/lib/ui/sync-status-badge.d.ts +8 -0
  85. package/lib/ui/sync-status-badge.js +64 -0
  86. package/lib/ui/upgrade-card.d.ts +7 -0
  87. package/lib/ui/upgrade-card.js +197 -0
  88. package/lib/ui/utils.d.ts +10 -0
  89. package/lib/ui/utils.js +66 -0
  90. package/lib/ui/workspace-panel.d.ts +4 -0
  91. package/lib/ui/workspace-panel.js +464 -0
  92. package/lib/version.d.ts +1 -1
  93. package/lib/version.js +1 -1
  94. package/package.json +1 -1
package/lib/executor.js CHANGED
@@ -1,296 +1,20 @@
1
- import { execFile, spawn } from 'node:child_process';
1
+ import { execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
3
  import fs from 'node:fs';
4
+ import os from 'node:os';
4
5
  import path from 'node:path';
5
6
  import { findMostRecentWorkspacePath, findWorkspacePathBySession, hasGitDir } from './workspace.js';
7
+ // 子模块纯函数解耦导入并对外部 Re-export 保证 100% 向后兼容
8
+ import { parseGhVersion, compareGhVersions } from './executor/version-utils.js';
9
+ import { spawnWithStdin, safeSlice, cutByUtf8Bytes, truncateOutput } from './executor/process-utils.js';
10
+ import { parseGitStatusOutput, parseGitLogLines, parseGitBranchLines } from './executor/git-parser.js';
11
+ import { getPlatformInstallGuide, getGhUpgradeHint } from './executor/platform-guide.js';
12
+ export { parseGhVersion, compareGhVersions, spawnWithStdin, safeSlice, cutByUtf8Bytes, truncateOutput, parseGitStatusOutput, parseGitLogLines, parseGitBranchLines, getPlatformInstallGuide, getGhUpgradeHint, };
6
13
  const execFileAsync = promisify(execFile);
7
- /**
8
- * spawn 形态的执行通道(stdin 可选注入)。
9
- *
10
- * 为什么存在:execFile 的 input 选项在本机(node 22.18.0 + Windows)实测从不写入
11
- * 子进程 stdin——既无数据也无 EOF,管道永久悬空(gh secret set 等需要 stdin 的
12
- * 命令会一直等到超时)。最小复现:execFile+input 对 `cmd /c more` 与 node 子进程
13
- * 均挂起;而 spawn + stdin.end(data) 全部正常。此函数即为后者的工程化封装,
14
- * 仅在调用方显式传入 stdin 时使用,其余路径保持 execFileAsync 零改动。
15
- *
16
- * 为什么超时要自己管:spawn 无 timeout 选项,用 kill + SIGTERM 兜底;
17
- * 输出按 maxBuffer 手工聚合(上限与 execFile 路径一致,15MB)。
18
- */
19
- function spawnWithStdin(ghPath, args, opts) {
20
- return new Promise((resolve, reject) => {
21
- const child = spawn(ghPath, args, {
22
- cwd: opts.cwd,
23
- env: opts.env,
24
- windowsHide: true,
25
- stdio: ['pipe', 'pipe', 'pipe'],
26
- });
27
- const outChunks = [];
28
- const errChunks = [];
29
- let totalBytes = 0;
30
- let killed = false;
31
- let settled = false;
32
- const timer = setTimeout(() => {
33
- killed = true;
34
- child.kill();
35
- }, opts.timeout);
36
- const settle = (err) => {
37
- if (settled)
38
- return;
39
- settled = true;
40
- clearTimeout(timer);
41
- if (err)
42
- reject(err);
43
- else
44
- resolve({ stdout: Buffer.concat(outChunks), stderr: Buffer.concat(errChunks), killed });
45
- };
46
- // 聚合上限:超出即杀(与 execFile maxBuffer 语义一致;gh 正常输出远小于此)
47
- const MAX_BYTES = 15 * 1024 * 1024;
48
- child.stdout?.on('data', (d) => {
49
- totalBytes += d.length;
50
- outChunks.push(d);
51
- if (totalBytes > MAX_BYTES) {
52
- killed = true;
53
- child.kill();
54
- }
55
- });
56
- child.stderr?.on('data', (d) => { errChunks.push(d); });
57
- child.on('error', (err) => {
58
- // spawn 失败(如 ENOENT)对齐 execFile 的错误形状:code 保留在 Error 上
59
- const e = Object.assign(new Error(err.message), { code: err.code });
60
- settle(e);
61
- });
62
- child.on('close', (code, signal) => {
63
- if (killed) {
64
- // 超时/超量被杀:对齐 execFile 的 Timeout 错误形状(err.killed + signal)
65
- const e = Object.assign(new Error(`Command timed out after ${opts.timeout}ms`), { killed: true, signal: signal || 'SIGTERM' });
66
- settle(e);
67
- return;
68
- }
69
- if (code !== 0) {
70
- const e = Object.assign(new Error(`Command failed with exit code ${code}`), { code, stderr: Buffer.concat(errChunks).toString('utf8').slice(0, 800) });
71
- settle(e);
72
- return;
73
- }
74
- settle();
75
- });
76
- // stdin 注入:end(data) 半关闭(写完即 EOF),子进程流式读取或一次性读取均可
77
- child.stdin?.end(opts.stdin, (err) => {
78
- if (err && !settled) {
79
- const e = Object.assign(new Error(`stdin write failed: ${err.message}`), { code: 'EPIPE' });
80
- settle(e);
81
- }
82
- });
83
- });
84
- }
85
14
  /** 认证状态缓存时长。用户手动 `gh auth login/logout` 后最多 30 秒内面板才会反映,属可接受代价 */
86
15
  const AUTH_CACHE_TTL_MS = 30_000;
87
16
  /** gh 版本缓存时长。与 authCache 同哲学:gh 升级是分钟级低频事件,30 秒陈旧窗口无实际影响 */
88
17
  const GH_VERSION_CACHE_TTL_MS = 30_000;
89
- /**
90
- * 从 `gh --version` 输出中解析语义化版本号。
91
- * 抽成导出纯函数的原因与 truncateOutput 相同:解析逻辑是「看似简单实则易错」的边界区,
92
- * 必须能用单元测试钉死(不匹配输入返回 null 而非抛错,调用方据此走 fail-open)。
93
- */
94
- export function parseGhVersion(output) {
95
- const m = /gh version (\d+\.\d+\.\d+)/.exec(output || '');
96
- return m ? m[1] : null;
97
- }
98
- /**
99
- * 数值分段比较两个 gh 版本:a>b 返回 1、a<b 返回 -1、相等返回 0。
100
- * 为什么不能用字符串比较:`'2.96.0' < '2.100.0'` 在字典序下为 false('1'<'9'),
101
- * 这会把 2.100 误判为低于 2.96,导致可用命令被错误降级。逐段 Number 比较是唯一正确姿势。
102
- */
103
- export function compareGhVersions(a, b) {
104
- const pa = a.split('.').map(Number);
105
- const pb = b.split('.').map(Number);
106
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
107
- const da = pa[i] ?? 0;
108
- const db = pb[i] ?? 0;
109
- if (da > db)
110
- return 1;
111
- if (da < db)
112
- return -1;
113
- }
114
- return 0;
115
- }
116
- /**
117
- * 解析 `git status -sb --porcelain` 输出为结构化状态。
118
- * 抽导出纯函数(parseGhVersion 同理):三形态解析是易错边界区,单测钉死。
119
- *
120
- * 输出形态(实测):
121
- * `## master...origin/master [ahead 2, behind 1]` 有 ahead/behind
122
- * `## master...origin/master` 与远程同步
123
- * `## master` / `## HEAD (no branch)` 无 upstream(ahead/behind 未知=-1)
124
- * 后续每行 `<XY> <path>` 为 porcelain 变更项(XY 两字符状态码,?? = untracked)。
125
- */
126
- export function parseGitStatusOutput(output) {
127
- const lines = (output || '').split('\n').filter((l) => l.length > 0);
128
- if (lines.length === 0 || !lines[0].startsWith('## '))
129
- return null;
130
- const branchLine = lines[0].slice(3); // 去掉 '## ' 前缀
131
- const hasUpstream = branchLine.includes('...');
132
- const branchPart = hasUpstream ? branchLine.split('...')[0] : branchLine.split(' ')[0];
133
- let ahead = -1;
134
- let behind = -1;
135
- if (hasUpstream) {
136
- // ahead/behind 段在 upstream 之后(可能与 #id 同现:origin/master #12)。
137
- // git 输出形态实测:`[ahead 2]` / `[behind 1]` / `[ahead 2, behind 1]`——
138
- // 单括号内逗号分隔,behind 不必然前邻 '['(正则不可锚定 '[',否则
139
- // `[ahead 2, behind 1]` 形态的 behind 永远漏解析——单测抓到的真实 Bug)
140
- const trackingPart = branchLine.split('...')[1] || '';
141
- ahead = 0;
142
- behind = 0;
143
- const aheadMatch = /ahead (\d+)/.exec(trackingPart);
144
- const behindMatch = /behind (\d+)/.exec(trackingPart);
145
- if (aheadMatch)
146
- ahead = Number(aheadMatch[1]);
147
- if (behindMatch)
148
- behind = Number(behindMatch[1]);
149
- // 仅 ahead 无 behind 时 behind=0(反之亦然)——git 输出只列非零侧
150
- }
151
- const dirtyFiles = [];
152
- for (let i = 1; i < lines.length && dirtyFiles.length < 20; i++) {
153
- const line = lines[i];
154
- if (line.length < 4)
155
- continue;
156
- const status = line.slice(0, 2).trim() || 'M';
157
- // 路径可能含空格(git 不加引号场景);rename 形态 `R old -> new` 取 new
158
- let p = line.slice(3);
159
- const renameArrow = p.indexOf(' -> ');
160
- if (renameArrow >= 0)
161
- p = p.slice(renameArrow + 4);
162
- dirtyFiles.push({ status, path: p });
163
- }
164
- return {
165
- branch: branchPart.replace(/\s*\(no branch\)$/, '') || 'HEAD',
166
- ahead,
167
- behind,
168
- dirtyCount: Math.max(0, lines.length - 1),
169
- hasUpstream,
170
- dirtyFiles,
171
- };
172
- }
173
- /**
174
- * 解析 `git log` 输出为提交条目数组。
175
- * 支持两种形态:
176
- * 1. 结构化带详情:%x1e 为 commit 间分隔符,%x1f 为字段间分隔符(含 fullSha/email/date/body/stat);
177
- * 2. 简易管道符:%h|%an|%ar|%s 行格式(兼容旧单测输入)。
178
- * 空输出返回 []。
179
- */
180
- export function parseGitLogLines(output) {
181
- const out = (output || '').trim();
182
- if (!out)
183
- return [];
184
- if (out.includes('\x1e') || out.includes('\x1f')) {
185
- const records = out.split('\x1e').filter((c) => c.trim().length > 0);
186
- return records.map((chunk) => {
187
- const parts = chunk.split('\x1f');
188
- return {
189
- sha: (parts[0] || '').trim(),
190
- fullSha: (parts[1] || '').trim() || undefined,
191
- author: (parts[2] || '').trim(),
192
- email: (parts[3] || '').trim() || undefined,
193
- date: (parts[4] || '').trim() || undefined,
194
- relative: (parts[5] || '').trim(),
195
- subject: (parts[6] || '').trim(),
196
- body: (parts[7] || '').trim() || undefined,
197
- stat: (parts[8] || '').trim() || undefined,
198
- };
199
- });
200
- }
201
- return out.split('\n').filter(Boolean).map((line) => {
202
- const parts = line.split('|');
203
- return {
204
- sha: parts[0] || '',
205
- author: parts[1] || '',
206
- relative: parts[2] || '',
207
- subject: parts.slice(3).join('|'),
208
- };
209
- });
210
- }
211
- /**
212
- * 按码点安全截取字符串,等价于 String.prototype.slice 但对孤立的代理对(surrogate pair)做占位替换。
213
- * 为什么必须这样截:本文件末尾会按 UTF-8 字节数截断,而 node:child_process 把 stdout 按字节缓冲区
214
- * 切分后再 toString('utf8'),一个汉字被从中间切开时会变成 U+FFFD 替换字符。直接用 slice 会把半截
215
- * 代理对留在结果里,导致下游 JSON.stringify 产出孤立转义序列、写入文件时编码报错。
216
- */
217
- function safeSlice(input, start, end) {
218
- const chars = Array.from(input);
219
- const from = Math.max(0, start);
220
- const to = end === undefined ? chars.length : Math.max(from, end);
221
- return chars.slice(from, to).map((c) => (c.length === 1 && c.charCodeAt(0) >= 0xd800 && c.charCodeAt(0) <= 0xdfff ? '\ufffd' : c)).join('');
222
- }
223
- /**
224
- * 以 UTF-8 字节数(而非字符串长度)为口径,从两端保留内容。
225
- * 为什么需要:maxOutputChars 数的是字符,中文一个字占 3 字节。只按字符限长时,
226
- * 中文环境下真实放行的字节量可达标称值的数倍,Token 预算保护会失真。
227
- * 采用二分查找定位截断点,避免对超大输出逐字符累加造成 O(n) 反复编码。
228
- */
229
- function cutByUtf8Bytes(input, headBytes, tailBytes) {
230
- const encoder = new TextEncoder();
231
- const totalBytes = encoder.encode(input).length;
232
- if (totalBytes <= headBytes + tailBytes) {
233
- return { head: input, tail: '', keptHeadBytes: totalBytes, keptTailBytes: 0, truncated: false };
234
- }
235
- const chars = Array.from(input);
236
- const atByte = (limit, fromEnd) => {
237
- let lo = 0;
238
- let hi = chars.length;
239
- let bytes = 0;
240
- while (lo < hi) {
241
- const mid = (lo + hi + 1) >> 1;
242
- const slice = fromEnd ? chars.slice(chars.length - mid) : chars.slice(0, mid);
243
- const size = encoder.encode(slice.join('')).length;
244
- if (size <= limit) {
245
- lo = mid;
246
- bytes = size;
247
- }
248
- else {
249
- hi = mid - 1;
250
- }
251
- }
252
- return { count: lo, bytes };
253
- };
254
- const headPart = atByte(headBytes, false);
255
- const tailPart = atByte(tailBytes, true);
256
- return {
257
- head: safeSlice(input, 0, headPart.count),
258
- tail: safeSlice(input, chars.length - tailPart.count),
259
- keptHeadBytes: headPart.bytes,
260
- keptTailBytes: tailPart.bytes,
261
- truncated: true,
262
- };
263
- }
264
- /**
265
- * 按「字符数 + UTF-8 字节数」双口径截断输出。
266
- * 抽成纯函数是刻意的:截断逻辑是崩溃高发区(切碎多字节字符、误伤 JSON、把二进制流截成垃圾),
267
- * 但通过真实 gh 命令很难稳定复现超限输出,抽出来才能用单元测试覆盖边界。
268
- */
269
- export function truncateOutput(input, maxChars, maxBytes) {
270
- // 双重口径限长:字符数守住 Token 预算,字节数守住真实传输量。
271
- // 中文场景下两者会分别触发,因此两条路径的提示文案必须区分,避免用户按错误的配置项去调参。
272
- if (input.length > maxChars) {
273
- // 保留前 1/3 字符和尾部 1/2 字符,保留开头上下文和错误尾部
274
- const headLen = Math.floor(maxChars * 0.35);
275
- const tailLen = Math.floor(maxChars * 0.55);
276
- const head = safeSlice(input, 0, headLen);
277
- const tail = safeSlice(input, input.length - tailLen);
278
- return {
279
- text: `${head}\n\n... [⚠️ 提示:内容过长已由 DSH GitHub 插件截断中间部分,当前截取前 ${Math.round(headLen / 1024)}KB 与后 ${Math.round(tailLen / 1024)}KB] ...\n\n${tail}`,
280
- truncated: true,
281
- };
282
- }
283
- const byteCut = cutByUtf8Bytes(input, Math.floor(maxBytes * 0.35), Math.floor(maxBytes * 0.55));
284
- if (byteCut.truncated) {
285
- // 这里必须用「实际保留的字节数」而非 maxChars 推导值:字节口径触发时 maxChars 往往远大于
286
- // 字节上限,早先版本照抄字符分支的算法,会报出与实际严重不符的「已保留 100KB」(实际仅数百字节)。
287
- return {
288
- text: `${byteCut.head}\n\n... [⚠️ 提示:内容超出 UTF-8 字节上限 (${maxBytes} bytes) 已截断中间部分,实际保留前 ${byteCut.keptHeadBytes} 字节与后 ${byteCut.keptTailBytes} 字节;如需放宽请调大配置项 maxOutputBytes] ...\n\n${byteCut.tail}`,
289
- truncated: true,
290
- };
291
- }
292
- return { text: input, truncated: false };
293
- }
294
18
  export class GhExecutor {
295
19
  ghPath;
296
20
  defaultTimeoutMs;
@@ -354,41 +78,28 @@ export class GhExecutor {
354
78
  this.proxyManager = manager;
355
79
  }
356
80
  /**
357
- * 智能解析最可靠的工作区物理路径:
358
- * 1. 优先使用显式指定的有效 cwd(若包含 .git 目录)
359
- * 2. 使用显式传入的 sessionId 或环境变量 DSH_SESSION_ID 精确反查工作区
360
- * 3. 递归探测:若传入了 explicitCwd(如聚合父目录),自动检查其直系子目录中是否包含 Git 仓库
361
- * 4. 匹配 ~/.dsh/storages/workspace.json 中最近活跃且存在 .git 的仓库工作区
362
- * 5. 回退到 process.cwd()
81
+ * 解析命令实际执行的工作区根目录
82
+ * 严格遵循数据事实源与工作区物理所有权,消除越权篡改:
83
+ * 1. 显式路径第一优先级:调用方只要显式指定了路径,该物理路径即为唯一事实源,原样返回自身;
84
+ * 绝不递归扫描子目录、绝不越权篡改;无 Git 目录则让下游探测真实反映无 Git 状态;
85
+ * 2. 仅在未显式指定 cwd 时,才尝试使用 sessionId 或环境变量 DSH_SESSION_ID 反查工作区;
86
+ * 3. 仅在完全未指定 cwd 且无会话时(全局命令行调用),才兜底回退到最近活跃的 Git 工作区或 process.cwd()。
363
87
  */
364
88
  resolveWorkspaceCwd(explicitCwd, explicitSessionId) {
365
- // 1. 显式路径优先,若有效且直接包含 .git 目录,则直接使用
366
- if (explicitCwd && hasGitDir(explicitCwd)) {
89
+ // 1. 显式路径第一优先级:只要显式指定了路径且在磁盘真实存在,原样返回该目录作为唯一事实源!
90
+ // 绝不进入子目录去“借用”子项目的 Git 仓库,杜绝在聚合目录或未绑定工作区中张冠李戴!
91
+ if (explicitCwd && fs.existsSync(explicitCwd)) {
367
92
  return explicitCwd;
368
93
  }
369
- // 2. 使用显式传入的 sessionId 或环境变量中的 DSH_SESSION_ID 反查
94
+ // 2. 仅在未显式指定 cwd 时,使用显式传入的 sessionId 或环境变量中的 DSH_SESSION_ID 反查
370
95
  const targetSessionId = explicitSessionId || process.env.DSH_SESSION_ID;
371
96
  if (targetSessionId) {
372
- const bySession = findWorkspacePathBySession(targetSessionId);
373
- if (bySession && hasGitDir(bySession))
374
- return bySession;
375
- }
376
- // 3. 递归探测:若传入了 explicitCwd(如非 Git 的父工作区目录),检查其一级子目录中是否存在 Git 仓库
377
- if (explicitCwd && fs.existsSync(explicitCwd)) {
378
- try {
379
- const entries = fs.readdirSync(explicitCwd, { withFileTypes: true });
380
- for (const entry of entries) {
381
- if (entry.isDirectory()) {
382
- const subDir = path.join(explicitCwd, entry.name);
383
- if (hasGitDir(subDir)) {
384
- return subDir;
385
- }
386
- }
387
- }
97
+ const sessionPath = findWorkspacePathBySession(targetSessionId);
98
+ if (sessionPath && fs.existsSync(sessionPath)) {
99
+ return sessionPath;
388
100
  }
389
- catch { }
390
101
  }
391
- // 4. 从工作区配置中匹配最近活跃且明确具备 .git 的仓库路径
102
+ // 3. 仅在完全没有显式指定目录与会话工作区(如无上下文的全局调用)时,才从工作区配置中匹配最近活跃且明确具备 .git 的仓库路径
392
103
  const recent = findMostRecentWorkspacePath();
393
104
  if (recent)
394
105
  return recent;
@@ -513,11 +224,19 @@ export class GhExecutor {
513
224
  return this.authCache.value;
514
225
  }
515
226
  const value = await this.probeAuth(cwd);
516
- // 只缓存确定的结果:出错时(未安装/未登录/网络异常)不缓存,
517
- // 否则用户 `gh auth login` 之后还要再等满一个 TTL 才能看到面板恢复。
518
- if (value.loggedIn) {
227
+ // 成功登录且无网络故障时落缓存
228
+ if (value.loggedIn && !value.networkError) {
519
229
  this.authCache = { at: now, value };
520
230
  }
231
+ else if (value.networkError && this.authCache && this.authCache.value.loggedIn) {
232
+ // 容灾保全:若本次刷新遭遇网络波动,但之前已有确凿的有效登录缓存,
233
+ // 保全已有登录身份,仅追加网络异常标识,绝不让界面闪烁误报为「未登录」
234
+ return {
235
+ ...this.authCache.value,
236
+ networkError: true,
237
+ networkErrorReason: value.networkErrorReason,
238
+ };
239
+ }
521
240
  return value;
522
241
  }
523
242
  /**
@@ -593,12 +312,7 @@ export class GhExecutor {
593
312
  }
594
313
  /** gh 升级命令按平台提示(复用三态状态机的平台判断口径) */
595
314
  getGhUpgradeHint() {
596
- const p = process.platform;
597
- if (p === 'win32')
598
- return '升级命令:`winget upgrade GitHub.cli`(或从 https://cli.github.com/ 下载最新 .msi)。';
599
- if (p === 'darwin')
600
- return '升级命令:`brew upgrade gh`(或从 https://cli.github.com/ 下载最新安装包)。';
601
- return '升级方式:更新系统包(Debian/Ubuntu: `sudo apt update && sudo apt install gh`;Fedora: `sudo dnf upgrade gh`),或见 https://cli.github.com/。';
315
+ return getGhUpgradeHint();
602
316
  }
603
317
  /**
604
318
  * 本地 Git 状态只读探测(白名单通道)。
@@ -734,51 +448,144 @@ export class GhExecutor {
734
448
  return null;
735
449
  }
736
450
  }
737
- /** 生成当前操作系统平台的推荐安装引导与命令 */
738
- getPlatformInstallGuide() {
739
- const p = process.platform;
740
- if (p === 'win32') {
741
- return {
742
- command: 'winget install --id GitHub.cli',
743
- altCommand: 'scoop install gh',
744
- downloadUrl: 'https://cli.github.com/',
745
- description: '推荐使用 Windows Package Manager (winget) 一键安装,或下载官方 .msi 安装包。',
746
- };
451
+ /**
452
+ * 纯本地读取工作区的所有 Git 分支(按提交时间倒序)。
453
+ * 包含当前 HEAD 分支标记、关联 upstream、最新提交简述与相对时间。
454
+ * 零网络往返,毫秒级本地管道输出。
455
+ */
456
+ async getGitBranches(cwd) {
457
+ const targetCwd = this.resolveWorkspaceCwd(cwd);
458
+ if (!hasGitDir(targetCwd)) {
459
+ return null;
460
+ }
461
+ const fmt = '%(refname:short)|%(HEAD)|%(upstream:short)|%(committerdate:relative)|%(objectname:short)|%(subject)';
462
+ try {
463
+ const { stdout } = await execFileAsync('git', ['branch', '-a', '--sort=-committerdate', `--format=${fmt}`], {
464
+ cwd: targetCwd,
465
+ timeout: 4_000,
466
+ windowsHide: true,
467
+ });
468
+ return parseGitBranchLines(String(stdout));
747
469
  }
748
- if (p === 'darwin') {
470
+ catch {
471
+ return null;
472
+ }
473
+ }
474
+ /**
475
+ * 安全切换当前工作区的 Git 分支。
476
+ * 三重安全防御纪律:
477
+ * 1. 目标工作区必须存在有效的 .git 目录;
478
+ * 2. 分支名称严格执行字符白名单校验,防命令行参数注入;
479
+ * 3. 检查工作区干净度(dirtyCount),若有未提交或未保存的变更直接阻断,杜绝代码被破坏性覆盖。
480
+ */
481
+ async switchGitBranch(cwd, branchName) {
482
+ const targetCwd = this.resolveWorkspaceCwd(cwd);
483
+ if (!hasGitDir(targetCwd)) {
484
+ return { ok: false, error: '当前工作区不是有效的 Git 仓库' };
485
+ }
486
+ const cleanBranch = (branchName || '').trim();
487
+ // 安全白名单校验:只允许字母、数字、点号、斜杠、减号和下划线,禁止以 - 开头(防 flag 注入),禁止包含连续点号 ..
488
+ if (!cleanBranch || cleanBranch.startsWith('-') || cleanBranch.includes('..') || cleanBranch.includes('\\') || !/^[a-zA-Z0-9_\/.-]+$/.test(cleanBranch)) {
489
+ return { ok: false, error: '非法分支名称,仅允许字母、数字、短横线、下划线与斜杠组合' };
490
+ }
491
+ // 防线二:工作区未提交变更阻断(Dirty File Guard)
492
+ const gitSt = await this.getLocalGitStatus(targetCwd);
493
+ if (gitSt && gitSt.dirtyCount > 0) {
749
494
  return {
750
- command: 'brew install gh',
751
- altCommand: 'port install gh',
752
- downloadUrl: 'https://cli.github.com/',
753
- description: '推荐使用 Homebrew 安装 GitHub CLI。',
495
+ ok: false,
496
+ error: `工作区有 ${gitSt.dirtyCount} 个未提交的文件变更。为防止代码被覆盖,请先提交或保存后再切换分支。`,
754
497
  };
755
498
  }
756
- return {
757
- command: 'sudo apt install gh',
758
- altCommand: 'sudo dnf install gh',
759
- downloadUrl: 'https://cli.github.com/',
760
- description: '推荐使用系统包管理器安装(Debian/Ubuntu 运行 apt,Fedora/CentOS 运行 dnf)。',
761
- };
499
+ try {
500
+ let args = ['checkout', cleanBranch];
501
+ let targetName = cleanBranch;
502
+ if (cleanBranch.startsWith('origin/')) {
503
+ targetName = cleanBranch.replace(/^origin\//, '');
504
+ // 若本地已有同名分支,直接切本地;若无则通过 --track 建立追踪分支
505
+ const branches = await this.getGitBranches(targetCwd);
506
+ const hasLocal = branches?.branches.some((b) => !b.isRemote && b.name === targetName);
507
+ args = hasLocal ? ['checkout', targetName] : ['checkout', '--track', cleanBranch];
508
+ }
509
+ await execFileAsync('git', args, {
510
+ cwd: targetCwd,
511
+ timeout: 5_000,
512
+ windowsHide: true,
513
+ });
514
+ return { ok: true, currentBranch: targetName };
515
+ }
516
+ catch (err) {
517
+ const stderr = err?.stderr?.toString().trim();
518
+ const msg = stderr || err?.message || '切换分支失败';
519
+ return { ok: false, error: msg };
520
+ }
521
+ }
522
+ /** 生成当前操作系统平台的推荐安装引导与命令 */
523
+ getPlatformInstallGuide() {
524
+ return getPlatformInstallGuide();
525
+ }
526
+ /**
527
+ * 纯本地检测宿主机 GitHub CLI 配置文件中是否存在已配置的账号凭据。
528
+ * 零子进程、零网络往返,毫秒级读取,专供断网与网络卡顿时的 Fail-Safe 容灾降级。
529
+ */
530
+ checkLocalGhCredential() {
531
+ try {
532
+ const candidates = [];
533
+ if (process.platform === 'win32') {
534
+ const appData = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
535
+ candidates.push(path.join(appData, 'GitHub CLI', 'hosts.yml'));
536
+ }
537
+ candidates.push(path.join(os.homedir(), '.config', 'gh', 'hosts.yml'));
538
+ for (const file of candidates) {
539
+ if (fs.existsSync(file)) {
540
+ const content = fs.readFileSync(file, 'utf8');
541
+ // 匹配 hosts.yml 中的 user: xxx 或 users:\n xxx:
542
+ const userMatch = content.match(/user:\s*([A-Za-z0-9_-]+)/i) || content.match(/users:\s*[\r\n]+\s+([A-Za-z0-9_-]+):/i);
543
+ const hasOauth = content.includes('oauth_token') || content.includes('users:');
544
+ if (userMatch || hasOauth) {
545
+ return {
546
+ user: userMatch ? userMatch[1] : undefined,
547
+ hasToken: true,
548
+ };
549
+ }
550
+ }
551
+ }
552
+ }
553
+ catch { }
554
+ return null;
762
555
  }
763
- /** 实际执行 `gh auth status` 并解析结果,不含缓存逻辑 */
556
+ /**
557
+ * 实际执行认证探测并解析结果,不含外部缓存逻辑。
558
+ * 解耦本地安装态、本地凭据态与网络可达态:
559
+ * 1. 安装态通过 getGhVersion 本地轻量确认,网络超时/断网绝不篡改 installed 结论;
560
+ * 2. 本地凭据通过 checkLocalGhCredential 读取,断网时仍可识别人类账号;
561
+ * 3. 精准分流网络超时/异常(networkError)与真正的未认证(explicitLoggedOut)。
562
+ */
764
563
  async probeAuth(cwd) {
564
+ // 1. 本地安装态先行探测(纯本地进程调用,零网络依赖)
565
+ const version = await this.getGhVersion().catch(() => null);
566
+ const isInstalledLocally = Boolean(version);
567
+ // 2. 本地已存登录凭据探测(纯本地文件读取,零网络依赖)
568
+ const localCred = this.checkLocalGhCredential();
569
+ // 3. 执行 gh auth status 校验远端有效性
765
570
  const res = await this.run(['auth', 'status'], { cwd, timeoutMs: 10_000, rawText: true });
766
571
  const raw = (res.rawOutput || '') + '\n' + (res.error || '');
767
- // 多重维度强健判定登录态 (容错 Windows Unicode 乱码、Keyring 告警与不同版本 CLI 输出差分)
572
+ // 4. 精准网络异常特征检测(超时、DNS解析失败、代理拒绝、连接重置)
573
+ const isTimeout = Boolean(res.error && (res.error.includes('执行超时') || res.error.includes('timed out')));
574
+ const isNetworkError = isTimeout || /dial\s+tcp|connectex|connection\s+refused|lookup\s+api\.github\.com|getaddrinfow|TLS\s+handshake|proxyconnect|network\s+is\s+unreachable|i\/o\s+timeout/i.test(raw);
575
+ // 5. 显式未登录特征(必须排除网络错误干扰,仅在无网络问题且 CLI 明确指示未登录时成立)
576
+ const isExplicitlyLoggedOut = !isNetworkError && (/not\s+logged\s+in/i.test(raw) ||
577
+ raw.includes('gh auth login') ||
578
+ raw.includes('authentication required') ||
579
+ raw.includes('No accounts found'));
580
+ // 6. 成功登录特征判定
768
581
  const hasLoggedInFlag = /logged\s+in\s+to/i.test(raw) || raw.includes('✓') || raw.includes('√');
769
582
  const hasActiveFlag = /active\s+account:\s*true/i.test(raw);
770
583
  const hasTokenFlag = raw.includes('Token:') || raw.includes('Token scopes:');
771
584
  const accountMatch = raw.match(/account\s+([A-Za-z0-9_-]+)/i);
772
585
  const hasAccount = Boolean(accountMatch && accountMatch[1] && accountMatch[1].toLowerCase() !== 'none');
773
- // 显式未登录特征排查
774
- const isExplicitlyLoggedOut = /not\s+logged\s+in/i.test(raw) ||
775
- raw.includes('gh auth login') ||
776
- raw.includes('authentication required') ||
777
- raw.includes('No accounts found');
778
- const loggedIn = !isExplicitlyLoggedOut && (hasLoggedInFlag || hasActiveFlag || (hasTokenFlag && hasAccount));
779
- // 只要已登录或有常规输出,则必然安装了 gh
780
- const isNotInstalled = Boolean(res.error && (res.error.includes('系统未检测到 GitHub CLI') || res.error.includes('ENOENT')));
781
- const installed = loggedIn || !isNotInstalled;
586
+ // 7. 安装状态结论:若本地版本已确认,或者命令返回了非 ENOENT 的输出,必然已安装
587
+ const isNotInstalled = !isInstalledLocally && Boolean(res.error && (res.error.includes('系统未检测到 GitHub CLI') || res.error.includes('ENOENT')));
588
+ const installed = isInstalledLocally || !isNotInstalled;
782
589
  if (!installed) {
783
590
  return {
784
591
  installed: false,
@@ -788,6 +595,25 @@ export class GhExecutor {
788
595
  raw: res.error,
789
596
  };
790
597
  }
598
+ // 8. 网络异常处理:绝不能把网络超时/断网归咎为“未登录”或“未安装”
599
+ if (isNetworkError) {
600
+ const errorReason = isTimeout
601
+ ? '连接 GitHub API 超时 (10 秒)。请检查网络连通性或代理配置。'
602
+ : '无法连接至 GitHub 服务器(网络波动或被系统代理阻断)。';
603
+ return {
604
+ installed: true,
605
+ // 若本地确认有配置好的账号,保持 loggedIn 为 true(Fail-Safe 容灾),并标记 networkError
606
+ loggedIn: Boolean(localCred?.hasToken || hasLoggedInFlag),
607
+ user: localCred?.user || (accountMatch ? accountMatch[1] : undefined),
608
+ host: 'github.com',
609
+ platform: process.platform,
610
+ networkError: true,
611
+ networkErrorReason: errorReason,
612
+ hasLocalToken: Boolean(localCred?.hasToken),
613
+ raw,
614
+ };
615
+ }
616
+ const loggedIn = !isExplicitlyLoggedOut && (hasLoggedInFlag || hasActiveFlag || (hasTokenFlag && hasAccount));
791
617
  if (!loggedIn) {
792
618
  return {
793
619
  installed: true,
@@ -797,7 +623,7 @@ export class GhExecutor {
797
623
  };
798
624
  }
799
625
  // 解析用户名
800
- let user;
626
+ let user = localCred?.user;
801
627
  if (accountMatch) {
802
628
  user = accountMatch[1];
803
629
  }
@@ -863,6 +689,11 @@ export class GhExecutor {
863
689
  */
864
690
  async getRepoMetadata(cwd, sessionId) {
865
691
  const targetCwd = this.resolveWorkspaceCwd(cwd, sessionId);
692
+ // 绝对前置门禁:当前目录若自身不存在 .git 目录,铁证如山判定为未关联本地 Git 仓库
693
+ // 直接返回 null,杜绝一切在非 Git 目录误报关联的可能!
694
+ if (!hasGitDir(targetCwd)) {
695
+ return null;
696
+ }
866
697
  // 1. 优先尝试由 gh 直接根据当前上下文识别
867
698
  const res = await this.run(['repo', 'view', '--json', 'nameWithOwner,name,owner,defaultBranchRef,description,isPrivate,url'], { cwd: targetCwd, timeoutMs: 10_000 });
868
699
  if (res.ok && res.data && res.data.nameWithOwner) {
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Git 元数据变更事件载荷
3
+ */
4
+ export interface GitChangeEvent {
5
+ /** 是否检测到本地 Git 元数据变动 */
6
+ changed?: boolean;
7
+ /** 触发时间戳(毫秒) */
8
+ at?: number;
9
+ /** 是否因达到长轮询上限而超时返回 */
10
+ timeout?: boolean;
11
+ }
12
+ /**
13
+ * Git 监听器配置项
14
+ */
15
+ export interface GitWatchOptions {
16
+ /** 防抖时间(毫秒),默认 800ms */
17
+ debounceMs?: number;
18
+ /** 长轮询超时时间(毫秒),默认 35,000ms */
19
+ timeoutMs?: number;
20
+ }
21
+ /**
22
+ * 定向针对 .git/HEAD 与 .git/index 创建非递归文件系统监听器。
23
+ * 零源码目录遍历,避免句柄耗尽与高 CPU 占用。
24
+ *
25
+ * 核心机制:
26
+ * 1. 靶向监听:仅监控 .git/HEAD 与 .git/index,若都不存在则兜底监控 .git 目录;
27
+ * 2. 800ms 防抖合并:避免连续 git 操作(如 git add 多个文件)产生事件风暴;
28
+ * 3. 单次触发保证(At-Most-Once):变更触发或超时熔断后,立即自动执行清理并释放全部句柄;
29
+ * 4. 显式释放:返回可随时主动调用的清理函数 stop()。
30
+ *
31
+ * @param cwd 目标 Git 仓库根目录
32
+ * @param onTrigger 变更发生或超时触发时的回调函数
33
+ * @param options 可选配置项(防抖与超时时间)
34
+ * @returns 停止监听并释放全部句柄的清理函数
35
+ */
36
+ export declare function watchGitMetadata(cwd: string, onTrigger: (event: GitChangeEvent) => void, options?: GitWatchOptions): () => void;