dsh-config-manager 0.2.2 → 0.2.4

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.
@@ -7,8 +7,9 @@
7
7
  * - 加密快照(EncryptedSections 密文载荷,无法平铺为明文 JSON 分区)走「密文单文件」布局:
8
8
  * 整个快照 JSON 提交到 <workDir>/snapshots-encrypted/<id>.json(远端已存密文;
9
9
  * 本地工作副本即远端镜像,不产生额外明文审计副本)。
10
- * - 命令执行走 node:child_process execFile(promise 封装,数组参数无 shell 注入),
11
- * 始终使用系统 PATH 中的 git(固定命令 'git'),可注入 exec 便于测试。
10
+ * - 命令执行走 node:child_process spawn(数组参数无 shell 注入、无 maxBuffer 截断错误),
11
+ * 超时**整棵进程树**一起 kill(issue #122:只 SIGTERM git.exe 会留下 git-remote-https /
12
+ * index-pack 孤儿继续下载);始终使用系统 PATH 中的 git(固定命令 'git'),可注入 exec 便于测试。
12
13
  * - 认证:token 仅从注入的 credentials provider 读取(每次网络操作时 getToken()),
13
14
  * 经 git credential helper(store --file=<临时文件>)传给 git —— token 不进入 argv、
14
15
  * 不进入 repoUrl、不写入任何同步内容/commit message/日志;临时凭据文件用后即删。
@@ -17,11 +18,11 @@
17
18
  * - 契约:同 id 重复 upload = 覆盖(幂等友好:内容无变化时不产生 commit);download 不存在抛错;
18
19
  * delete 不存在视为成功。
19
20
  */
20
- import { execFile } from 'node:child_process';
21
+ import { spawn } from 'node:child_process';
22
+ import type { ChildProcess } from 'node:child_process';
21
23
  import fs from 'node:fs/promises';
22
24
  import os from 'node:os';
23
25
  import path from 'node:path';
24
- import { promisify } from 'node:util';
25
26
 
26
27
  import { createSnapshotFs, joinFs } from '../fs.ts';
27
28
  import type { SnapshotFs } from '../fs.ts';
@@ -48,8 +49,6 @@ import type { MsgFunc } from '../../core/messages.ts';
48
49
  import { withWorkdirLock, WorkdirLockError } from '../../utils/workdir-lock.ts';
49
50
  import { fastForwardFetchArgs, fastForwardMergeArgs, isMissingRemoteRefError, parseCurrentBranch } from '../../utils/git-fast-forward.ts';
50
51
 
51
- const execFileAsync = promisify(execFile);
52
-
53
52
  /** git 命令执行结果(code ≠ 0 = git 命令失败/退出非零) */
54
53
  export interface GitExecResult {
55
54
  stdout: string;
@@ -57,7 +56,7 @@ export interface GitExecResult {
57
56
  code: number;
58
57
  }
59
58
 
60
- /** 可注入的 git 执行器(测试 mock 用);默认实现 = child_process.execFile promise 封装 */
59
+ /** 可注入的 git 执行器(测试 mock 用);默认实现 = child_process.spawn promise 封装(超时杀进程树) */
61
60
  export type GitExecFn = (
62
61
  cmd: string,
63
62
  args: string[],
@@ -146,7 +145,7 @@ export interface GitTransportOptions {
146
145
  timeoutMs?: number;
147
146
  /** 幂等读操作(list/download 的 clone/pull)的网络重试参数;缺省 attempts=3、250ms 起指数退避 */
148
147
  retry?: SyncRetryOptions;
149
- /** 注入 exec(测试 mock 用);缺省 = execFile 封装 */
148
+ /** 注入 exec(测试 mock 用);缺省 = spawn 封装(超时杀进程树) */
150
149
  exec?: GitExecFn;
151
150
  /** 提交作者(写入远端历史),默认 DSH Config Sync <sync@dsh.local> */
152
151
  author?: GitAuthor;
@@ -184,10 +183,29 @@ const BLOBS_REL = 'blobs';
184
183
  * 远端分支的顶层出现别的名字 = 这不是本插件的同步仓库,合并它等于把别人的仓库内容搬进工作副本。
185
184
  */
186
185
  const ADOPT_ROOT_ALLOW = new Set<string>([SNAPSHOTS_REL, SNAPSHOTS_ENCRYPTED_REL, BLOBS_REL]);
186
+ /**
187
+ * 同步仓库只在这三个顶层目录里写内容 ⇒ partial clone 的 sparse-checkout 面与它同源(issue #122)。
188
+ * 远端仓库比同步内容大几个数量级时(报告者现场:1.8 GB 仓库 / 6 MB 内容),全量 clone 与全量 fetch
189
+ * 都要拉完整对象图,而工作副本真正需要的只有这三个目录。
190
+ */
191
+ const SYNC_ROOT_DIRS: readonly string[] = [...ADOPT_ROOT_ALLOW];
192
+ /**
193
+ * 走网络的 git 子命令:一律附加低速上限(issue #122)。
194
+ *
195
+ * 为什么必须显式设:git 的默认 http 低速门限极宽松,链路被限速/黑洞时一条 fetch 能安静地耗到
196
+ * timeoutMs(120 s),再乘上重试次数 = 用户看到的就是「永久停在正在检查远端变更」。
197
+ * 30 s 内平均速率低于 1 KB/s 即明确失败,交给既有分类器判 timeout(瞬时、可重试)。
198
+ */
199
+ const NETWORK_SUBCOMMANDS = new Set<string>(['clone', 'fetch', 'push', 'ls-remote', 'pull']);
200
+ const LOW_SPEED_ARGS: readonly string[] = ['-c', 'http.lowSpeedLimit=1000', '-c', 'http.lowSpeedTime=30'];
187
201
  const DEFAULT_AUTHOR: GitAuthor = { name: 'DSH Config Sync', email: 'sync@dsh.local' };
188
202
  const DEFAULT_CREDENTIAL_USERNAME = 'oauth2';
189
203
  /** 快照 id 安全字符集:字母数字开头,仅 . _ -;防路径穿越与 commit message 注入 */
190
204
  const SAFE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
205
+ /** git 对象 id(sha1 40 位 / sha256 64 位)—— ls-remote 输出与 rev-parse 结果共用同一判定 */
206
+ const SHA_RE = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
207
+ /** 老 git 不认新选项(partial clone 需 ≥2.19、cone sparse-checkout 需 ≥2.25):据此回落全量 clone */
208
+ const UNSUPPORTED_GIT_OPTION_RE = /unknown option|unrecognized argument|unknown switch|is not a git command|unsupported/i;
191
209
 
192
210
  /**
193
211
  * SSH 主机密钥校验失败(issue #79):git 只回一句 `Host key verification failed`,
@@ -201,35 +219,118 @@ const SSH_HOST_KEY_RE = /host key verification failed|remote host identification
201
219
  */
202
220
  const DIVERGED_HISTORY_RE = /refusing to merge unrelated histories|unrelated histories|not possible to fast-forward/i;
203
221
 
204
- const defaultExec: GitExecFn = async (cmd, args, opts) => {
205
- try {
206
- const { stdout, stderr } = await execFileAsync(cmd, args, {
207
- cwd: opts.cwd,
208
- timeout: opts.timeoutMs,
209
- maxBuffer: 16 * 1024 * 1024,
210
- windowsHide: true,
211
- encoding: 'utf8',
212
- // issue #120:credential helper 走 shell 且本机没有可用 shell 时,改用 env 注入认证头重试 ——
213
- // 追加在继承的 process.env 上(env 缺省 = 完全继承,不改变既有行为)
214
- env: opts.env === undefined ? undefined : { ...process.env, ...opts.env },
215
- });
216
- return { stdout: String(stdout), stderr: String(stderr), code: 0 };
217
- } catch (err) {
218
- const e = err as { code?: number | string; killed?: boolean; signal?: string; stdout?: string; stderr?: string };
219
- const detail = String(e.stderr ?? '') !== '' ? String(e.stderr) : (err instanceof Error ? err.message : String(err));
220
- // 超时(execFile 到点 kill)在 git 的 stderr 里常常是空的:补一句可判定的文字,
221
- // 让 transport.ts 的统一分类器把它识别成 timeout(瞬时、可重试),而不是 unknown。
222
- const timedOut = e.killed === true || e.signal === 'SIGTERM' || e.code === 'ETIMEDOUT';
223
- const stderr = timedOut && !/timed out|timeout/i.test(detail)
224
- ? `git command timed out after ${String(opts.timeoutMs ?? 0)}ms: ${detail}`
225
- : detail;
226
- return {
227
- stdout: String(e.stdout ?? ''),
228
- stderr,
229
- code: typeof e.code === 'number' ? e.code : 1,
222
+ /** 超时 kill 之后等 stdio 关闭的宽限:逃出进程组的孙进程可能一直握着管道(issue #122) */
223
+ const EXEC_KILL_GRACE_MS = 5_000;
224
+ /** 单条命令累计输出上限(与旧 execFile maxBuffer 同口径,超限即 kill) */
225
+ const EXEC_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
226
+
227
+ /**
228
+ * 默认 git 执行器:spawn + **进程树** kill(issue #122)。
229
+ *
230
+ * 为什么不再用 execFile:它的 timeout 只对 git.exe 自己发 SIGTERM,而真正在下包的是 git.exe 的子进程
231
+ * (git-remote-https / git index-pack)。父进程被杀、孙进程继续写 tmp_pack_*,管道不关闭 ⇒ execFile 的
232
+ * promise 连超时错误都可能不返回 ⇒ 上层「正在检查远端变更...」永久挂起,下一轮重试再起一份,最终 N 份
233
+ * 并发下载同一个 pack。
234
+ * 这里改为:POSIX 上 detached 起独立进程组,超时对**整组**发 SIGKILL;Windows 上 `taskkill /T /F`;
235
+ * 无论 kill 是否成功,宽限期到点都带着已收集输出收尾 —— 绝不把「管道没关」变成上层无限等待。
236
+ *
237
+ * 导出仅供测试直接验证「超时 + 进程树 kill + 有界收尾」(issue #122 的验收面)。
238
+ */
239
+ export const defaultGitExec: GitExecFn = async (cmd, args, opts) =>
240
+ await new Promise<GitExecResult>((resolve) => {
241
+ const isWin = process.platform === 'win32';
242
+ // issue #120:credential helper 走 shell 且本机没有可用 shell 时,改用 env 注入认证头重试 ——
243
+ // 追加在继承的 process.env 上(env 缺省 = 完全继承,不改变既有行为)
244
+ const env = opts.env === undefined ? undefined : { ...process.env, ...opts.env };
245
+ let stdout = '';
246
+ let stderr = '';
247
+ let bytes = 0;
248
+ let settled = false;
249
+ let timedOut = false;
250
+ let overflow = false;
251
+ let timer: NodeJS.Timeout | null = null;
252
+ let graceTimer: NodeJS.Timeout | null = null;
253
+ let child: ChildProcess | null = null;
254
+
255
+ const settle = (code: number): void => {
256
+ if (settled) return;
257
+ settled = true;
258
+ if (timer !== null) clearTimeout(timer);
259
+ if (graceTimer !== null) clearTimeout(graceTimer);
260
+ let text = stderr;
261
+ if (code !== 0) {
262
+ if (overflow && !/exceed/i.test(text)) text = `${text}\noutput exceeded ${String(EXEC_MAX_OUTPUT_BYTES)} bytes`;
263
+ if (text.trim() === '') text = `git ${args[0] ?? ''} exited with code ${String(code)}`;
264
+ // 超时在 git 的 stderr 里常常是空的:补一句可判定的文字,让 transport.ts 的统一分类器
265
+ // 把它识别成 timeout(瞬时、可重试),而不是 unknown。
266
+ if (timedOut && !/timed out|timeout/i.test(text)) {
267
+ text = `git command timed out after ${String(opts.timeoutMs ?? 0)}ms: ${text}`;
268
+ }
269
+ }
270
+ resolve({ stdout, stderr: text, code });
230
271
  };
231
- }
232
- };
272
+
273
+ const killTree = (): void => {
274
+ const pid = child?.pid;
275
+ if (pid === undefined) return;
276
+ if (isWin) {
277
+ // 只 SIGTERM git.exe 会留下 git-remote-https / index-pack 孤儿(issue #122)⇒ 整棵树强杀
278
+ try {
279
+ spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
280
+ .on('error', () => { /* 尽力而为:kill 失败也要靠宽限期收尾 */ });
281
+ } catch { /* 同上 */ }
282
+ return;
283
+ }
284
+ try {
285
+ process.kill(-pid, 'SIGKILL'); // 负 pid = 整个进程组(detached 起的子进程是组长)
286
+ } catch {
287
+ try { child?.kill('SIGKILL'); } catch { /* 已退出 */ }
288
+ }
289
+ };
290
+
291
+ try {
292
+ child = spawn(cmd, args, {
293
+ ...(opts.cwd === undefined ? {} : { cwd: opts.cwd }),
294
+ ...(env === undefined ? {} : { env }),
295
+ windowsHide: true,
296
+ // POSIX:独立进程组,超时才可能连孙进程一起杀;Windows 用 taskkill /T
297
+ detached: !isWin,
298
+ stdio: ['ignore', 'pipe', 'pipe'],
299
+ });
300
+ } catch (err) {
301
+ resolve({ stdout: '', stderr: err instanceof Error ? err.message : String(err), code: 1 });
302
+ return;
303
+ }
304
+
305
+ const collect = (sink: 'out' | 'err') => (chunk: Buffer): void => {
306
+ bytes += chunk.length;
307
+ if (bytes > EXEC_MAX_OUTPUT_BYTES) {
308
+ if (!overflow) {
309
+ overflow = true;
310
+ killTree();
311
+ }
312
+ return;
313
+ }
314
+ if (sink === 'out') stdout += chunk.toString('utf8');
315
+ else stderr += chunk.toString('utf8');
316
+ };
317
+ child.stdout?.on('data', collect('out'));
318
+ child.stderr?.on('data', collect('err'));
319
+ child.on('error', (err) => {
320
+ stderr = stderr === '' ? err.message : stderr;
321
+ settle(1);
322
+ });
323
+ child.on('close', (code) => { settle(typeof code === 'number' ? code : 1); });
324
+
325
+ if (opts.timeoutMs !== undefined) {
326
+ timer = setTimeout(() => {
327
+ timedOut = true;
328
+ killTree();
329
+ // 进程树 kill 之后管道仍可能被握着(逃出进程组的孙进程)⇒ 宽限期到点强制收尾
330
+ graceTimer = setTimeout(() => { settle(1); }, EXEC_KILL_GRACE_MS);
331
+ }, Math.max(1, opts.timeoutMs));
332
+ }
333
+ });
233
334
 
234
335
  /** 实现 SyncTransport 的 git 通道。所有操作前 ensureRepo() 保证工作副本就绪,网络命令带凭据。 */
235
336
  export class GitTransport implements SyncTransport {
@@ -244,6 +345,8 @@ export class GitTransport implements SyncTransport {
244
345
  exec: GitExecFn;
245
346
  };
246
347
  private repoReady = false;
348
+ /** 该工作副本是否 partial clone(remote.origin.promisor);null = 尚未判定(issue #122) */
349
+ private partialClone: boolean | null = null;
247
350
  /**
248
351
  * 工作副本锁的可重入深度:list/upload/download/delete 都会经 ensureRepo → reconcileOrigin,
249
352
  * rebuildWorkDir → adoptRemoteHistory 也各自嵌套;外层入口持锁,内层直接跑。
@@ -278,7 +381,7 @@ export class GitTransport implements SyncTransport {
278
381
  gitBin: 'git',
279
382
  timeoutMs: options.timeoutMs ?? DEFAULT_SYNC_TIMEOUT_MS,
280
383
  retry: options.retry ?? {},
281
- exec: options.exec ?? defaultExec,
384
+ exec: options.exec ?? defaultGitExec,
282
385
  author: options.author ?? DEFAULT_AUTHOR,
283
386
  credentialUsername: options.credentialUsername ?? DEFAULT_CREDENTIAL_USERNAME,
284
387
  };
@@ -584,7 +687,7 @@ export class GitTransport implements SyncTransport {
584
687
  // 每次尝试前重查 .git:上一次尝试其实建出了仓库就视为成功,避免「目录非空」误判。
585
688
  await withSyncRetry(async () => {
586
689
  if (await fsx.exists(gitDir)) return;
587
- await this.runGit(['clone', this.o.repoUrl, '.'], { cwd: this.o.workDir, withCredential: true });
690
+ await this.cloneIntoWorkDir();
588
691
  }, this.o.retry);
589
692
  // 仓库级提交身份(写入远端历史,可经 author 选项覆盖;不改全局配置)
590
693
  await this.runGit(['config', 'user.name', this.o.author.name]);
@@ -592,6 +695,88 @@ export class GitTransport implements SyncTransport {
592
695
  this.repoReady = true;
593
696
  }
594
697
 
698
+ /**
699
+ * 首次 clone(issue #122):partial clone + sparse-checkout,只落地同步内容。
700
+ *
701
+ * 为什么:同步仓库可能比同步内容大几个数量级(报告者现场 1.8 GB 仓库 / 6 MB 内容)。此前 `git clone`
702
+ * 全量落地,之后每次 fetch 还要拉完整对象图 ⇒ 一次「检查远端变更」就下几百 MB。
703
+ * `--filter=blob:none` 只取 commit+tree,`--no-checkout` 先不落地任何文件,
704
+ * `sparse-checkout set --cone <三个目录>` 之后 checkout 只 materialize 这三个目录的 blob。
705
+ *
706
+ * 老 git 不认这些选项(unknown option)时回落全量 clone —— 行为与修复前完全一致,绝不因优化失败。
707
+ */
708
+ private async cloneIntoWorkDir(): Promise<void> {
709
+ const cwd = this.o.workDir;
710
+ this.partialClone = null; // reclone 后重新判定(配置可能变)
711
+ const filteredArgs = ['clone', '--filter=blob:none', '--no-checkout', this.o.repoUrl, '.'];
712
+ const filtered = await this.runGit(filteredArgs, { cwd, withCredential: true, allowNonZero: true });
713
+ if (filtered.code !== 0) {
714
+ if (!UNSUPPORTED_GIT_OPTION_RE.test(filtered.stderr + ' ' + filtered.stdout)) {
715
+ // 真实失败(网络 / 鉴权 / 超时):沿用既有分类与文案(含 issue #120 的凭据通道判定)
716
+ this.raiseGitFailure(filteredArgs, filtered, await this.readTokenOnce(), false);
717
+ }
718
+ // 老 git:回落全量 clone(全量 clone 自带 checkout)
719
+ await clearDirContents(cwd);
720
+ await this.runGit(['clone', this.o.repoUrl, '.'], { cwd, withCredential: true });
721
+ return;
722
+ }
723
+ const branch = await this.currentBranch();
724
+ const head = await this.runGit(['rev-parse', '--verify', '--quiet', 'HEAD'], { allowNonZero: true });
725
+ if (head.code !== 0) return; // 空仓库:没有可 checkout 的树,后续 push 会建分支
726
+ const target = branch === '' ? 'HEAD' : branch;
727
+ const sparse = await this.runGit(['sparse-checkout', 'set', '--cone', ...SYNC_ROOT_DIRS], { allowNonZero: true });
728
+ if (sparse.code !== 0) {
729
+ // 老 git 没有 cone 模式:宁可全量落地(修复前行为),也不留下一个空工作树
730
+ await this.runGit(['checkout', target], { allowNonZero: true });
731
+ return;
732
+ }
733
+ // checkout 失败必须可见(空工作树会让上层以为「远端没有快照」)
734
+ await this.runGit(['checkout', target]);
735
+ }
736
+
737
+ /**
738
+ * 该工作副本是不是 partial clone(`remote.origin.promisor=true`)。
739
+ *
740
+ * 只有 partial clone 才能给 fetch 加 `--filter=blob:none`:对普通全量副本加过滤会让后续 checkout
741
+ * 拿到缺失的 blob。存量副本(1.8 GB 那种)因此只受益于 ls-remote 短路与 `--no-tags`,不会被改坏。
742
+ */
743
+ private async isPartialClone(): Promise<boolean> {
744
+ if (this.partialClone !== null) return this.partialClone;
745
+ const res = await this.runGit(['config', '--get', 'remote.origin.promisor'], { allowNonZero: true });
746
+ this.partialClone = res.code === 0 && res.stdout.trim() === 'true';
747
+ return this.partialClone;
748
+ }
749
+
750
+ /** 拉取姿态:partial clone 保持 blob 过滤;同步仓库不需要 tag(issue #122) */
751
+ private async fetchOptionFlags(): Promise<string[]> {
752
+ const flags: string[] = [];
753
+ if (await this.isPartialClone()) flags.push('--filter=blob:none');
754
+ flags.push('--no-tags');
755
+ return flags;
756
+ }
757
+
758
+ /** 远端分支当前的 sha(ls-remote 只取一行 refs);读不到 → null(短路是优化,失败一律回落正常 fetch) */
759
+ private async lsRemoteBranchSha(branch: string): Promise<string | null> {
760
+ const res = await this.runGit(
761
+ ['ls-remote', '--heads', 'origin', `refs/heads/${branch}`],
762
+ { withCredential: true, allowNonZero: true },
763
+ );
764
+ if (res.code !== 0) return null;
765
+ for (const line of res.stdout.split('\n')) {
766
+ const [sha, ref] = line.trim().split('\t');
767
+ if (ref === `refs/heads/${branch}` && sha !== undefined && SHA_RE.test(sha)) return sha;
768
+ }
769
+ return null;
770
+ }
771
+
772
+ /** 解析引用指向的 sha;读不到 / 不是 sha → null */
773
+ private async revParseSha(ref: string): Promise<string | null> {
774
+ const res = await this.runGit(['rev-parse', '--verify', '--quiet', ref], { allowNonZero: true });
775
+ if (res.code !== 0) return null;
776
+ const sha = res.stdout.trim();
777
+ return SHA_RE.test(sha) ? sha : null;
778
+ }
779
+
595
780
  /**
596
781
  * 让工作副本的 origin 与配置的 repoUrl 保持一致(issue #79)。
597
782
  *
@@ -607,6 +792,7 @@ export class GitTransport implements SyncTransport {
607
792
  await this.runGit(['remote', 'add', 'origin', this.o.repoUrl]);
608
793
  } else if (origin !== '' && origin !== this.o.repoUrl) {
609
794
  await this.runGit(['remote', 'set-url', 'origin', this.o.repoUrl]);
795
+ this.partialClone = null; // 换了远端 ⇒ promisor 判定失效(issue #122)
610
796
  }
611
797
  const push = await this.runGit(['remote', 'get-url', '--push', 'origin'], { allowNonZero: true });
612
798
  const pushUrl = push.code === 0 ? push.stdout.trim() : '';
@@ -811,7 +997,7 @@ export class GitTransport implements SyncTransport {
811
997
  }
812
998
  // fetch 是网络操作(幂等读)→ 允许有限指数退避重试
813
999
  await withSyncRetry(async () => {
814
- await this.runGit(['fetch', 'origin'], { withCredential: true });
1000
+ await this.runGit(['fetch', ...(await this.fetchOptionFlags()), 'origin'], { withCredential: true });
815
1001
  }, this.o.retry);
816
1002
  const remoteRef = `refs/remotes/origin/${branch}`;
817
1003
  const refRes = await this.runGit(['rev-parse', '--verify', '--quiet', remoteRef], { allowNonZero: true });
@@ -879,6 +1065,12 @@ export class GitTransport implements SyncTransport {
879
1065
  const attempt = async (): Promise<void> => {
880
1066
  const branch = await this.currentBranch();
881
1067
  if (branch === '') return; // detached HEAD:没有 upstream 概念(与原「no tracking information」同姿态跳过)
1068
+ // issue #122:稳态(远端没变)时**连 fetch 都不发**。一次 ls-remote 只回一行 refs(~1 KB),
1069
+ // 而 fetch 即使没有新内容也要协商 refs、且远端仓库远大于同步内容时要遍历完整对象图
1070
+ // (报告者现场:1.8 GB 仓库 / 6 MB 内容 ⇒ 一次「检查远端变更」卡死)。
1071
+ // 跳过条件必须两个同时成立:远端 sha == 本地远端跟踪引用(没有新对象可拉)**且** HEAD == 该 sha
1072
+ // (本地已合并)。只比 refs 就跳过 merge 会漏掉「上次 fetch 成功、merge 没跑完」的副本 ——
1073
+ // 那种副本没有新对象可拉,但必须继续本地 merge。
882
1074
  // **不再用 `git pull --ff-only`**:它是「fetch 写 FETCH_HEAD + 读 FETCH_HEAD 合并」的两步动作,
883
1075
  // 并发驱动同一个工作副本时 FETCH_HEAD 会留下多行 for-merge 记录,随后每个 pull 都以
884
1076
  // `fatal: Cannot fast-forward to multiple branches.` 失败(本机 5 并发实测全败),
@@ -886,12 +1078,18 @@ export class GitTransport implements SyncTransport {
886
1078
  // 显式 refspec fetch + 显式远端跟踪分支 merge 完全不读 FETCH_HEAD(同样 5 并发实测全成功),
887
1079
  // 语义与 ff-only pull 一致:能快进就快进,不能快进就报「历史分叉」。
888
1080
  // 参数与判定在 utils/git-fast-forward.ts(market 侧共用同一份实现)。
889
- const fetched = await this.runGit(fastForwardFetchArgs(branch), { withCredential: true, allowNonZero: true });
890
- if (fetched.code !== 0) {
891
- const combined = fetched.stderr + ' ' + fetched.stdout;
892
- // 远端还没有这个分支(全新空仓库 / 分支被改名)→ 与「无 upstream」一样静默跳过
893
- if (isMissingRemoteRefError(combined)) return;
894
- await this.throwPullFailure(combined, fetched.stderr);
1081
+ const remoteSha = await this.lsRemoteBranchSha(branch);
1082
+ const localSha = await this.revParseSha(`refs/remotes/origin/${branch}`);
1083
+ if (remoteSha !== null && remoteSha === localSha) {
1084
+ if (await this.revParseSha('HEAD') === remoteSha) return; // 已是最新:零 fetch、零 merge
1085
+ } else {
1086
+ const fetched = await this.runGit(fastForwardFetchArgs(branch, await this.fetchOptionFlags()), { withCredential: true, allowNonZero: true });
1087
+ if (fetched.code !== 0) {
1088
+ const combined = fetched.stderr + ' ' + fetched.stdout;
1089
+ // 远端还没有这个分支(全新空仓库 / 分支被改名)→ 与「无 upstream」一样静默跳过
1090
+ if (isMissingRemoteRefError(combined)) return;
1091
+ await this.throwPullFailure(combined, fetched.stderr);
1092
+ }
895
1093
  }
896
1094
  const merged = await this.runGit(fastForwardMergeArgs(branch), { allowNonZero: true });
897
1095
  if (merged.code === 0) return;
@@ -938,6 +1136,8 @@ export class GitTransport implements SyncTransport {
938
1136
  opts: { cwd?: string; withCredential?: boolean; allowNonZero?: boolean; requirePushToken?: boolean } = {},
939
1137
  ): Promise<GitExecResult> {
940
1138
  const cwd = opts.cwd === undefined ? this.o.workDir : opts.cwd;
1139
+ // 网络子命令一律带低速上限:真卡住在 30 s 内明确失败,而不是耗满 timeoutMs(issue #122)
1140
+ const networkArgs = NETWORK_SUBCOMMANDS.has(args[0] ?? '') ? [...LOW_SPEED_ARGS] : [];
941
1141
  let extra: string[] = [];
942
1142
  let token: string | null = null;
943
1143
  let cleanup: (() => Promise<void>) | null = null;
@@ -956,7 +1156,7 @@ export class GitTransport implements SyncTransport {
956
1156
  // 而目录里原本就有别的内容时宁可放弃重试,也绝不删用户文件。
957
1157
  const cloneTargetWasEmpty = args[0] === 'clone' ? await isEmptyDir(cwd) : false;
958
1158
  try {
959
- let result = await this.o.exec(this.o.gitBin, [...extra, ...args], { cwd, timeoutMs: this.o.timeoutMs });
1159
+ let result = await this.o.exec(this.o.gitBin, [...extra, ...networkArgs, ...args], { cwd, timeoutMs: this.o.timeoutMs });
960
1160
  // issue #120:credential helper 必须经 shell 执行(值里不含空格也一样,git 统一拼成
961
1161
  // `sh -c 'git <helper> ...'`),而 Android 上 git 二进制的 GIT_SHELL_PATH 指向 App 沙箱里
962
1162
  // 不存在的 Termux sh;`core.askpass` 又要 exec 权限(Android 10+ 对 targetSdk ≥ 29 禁执行应用
@@ -966,33 +1166,11 @@ export class GitTransport implements SyncTransport {
966
1166
  const headerEnv = credentialHeaderEnv(this.o.repoUrl, this.o.credentialUsername, token);
967
1167
  if (Object.keys(headerEnv).length > 0 && (args[0] !== 'clone' || cloneTargetWasEmpty)) {
968
1168
  if (args[0] === 'clone') await clearDirContents(cwd);
969
- result = await this.o.exec(this.o.gitBin, args, { cwd, timeoutMs: this.o.timeoutMs, env: headerEnv });
1169
+ result = await this.o.exec(this.o.gitBin, [...networkArgs, ...args], { cwd, timeoutMs: this.o.timeoutMs, env: headerEnv });
970
1170
  }
971
1171
  }
972
1172
  if (result.code !== 0 && !opts.allowNonZero) {
973
- const combined = result.stderr + ' ' + result.stdout;
974
- // 统一分类(超时 / 网络 / 鉴权 / 5xx…):上层可据 kind / retryable 分流,不必解析 message
975
- const classified = classifyNetworkErrorText(combined);
976
- // issue #79:SSH 主机密钥校验失败 → 换成「怎么信任该主机」的可操作说明(绝不自动信任)
977
- if (SSH_HOST_KEY_RE.test(combined)) {
978
- throw new GitTransportError(this.hostKeyMessage(), { kind: 'auth', retryable: false });
979
- }
980
- // 推送 + 鉴权失败:git 原文只说「认证失败」——换成能照做的说明(令牌失效 / 无写权限 / 远端禁用了密码推送)
981
- // issue #115:clone 的鉴权失败原文(remote: Write access to repository not granted / 403)读不出「缺哪种权限」,
982
- // 换成点名 Contents: Read and write 的说明 —— 否则用户只会以为令牌坏了(细粒度 PAT 常只勾了 Administration)
983
- // issue #120:helper 根本没能执行时,「请确认令牌有效」是错误指引(令牌可能是好的)——
984
- // 这类失败必须点名平台原因,排在 push/clone 的鉴权文案之前。
985
- const credentialBlocked = isCredentialExecFailure(combined);
986
- const message = credentialBlocked
987
- ? this.msg('sync.git.credentialHelperBlocked', { err: this.mask(result.stderr, token) })
988
- : opts.requirePushToken === true && classified.kind === 'auth'
989
- ? this.msg('sync.git.pushAuthFailed', { err: this.mask(result.stderr, token) })
990
- : args[0] === 'clone' && classified.kind === 'auth'
991
- ? this.msg('sync.git.cloneAuthFailed', { err: this.mask(result.stderr, token) })
992
- : this.msg('sync.git.cmdFailed', { args: args.join(' '), code: String(result.code), err: this.mask(result.stderr, token) });
993
- // 归类同样不能交给原文:`cannot exec ...: No such file or directory` 里的 ENOENT 会被判成
994
- // notfound(「仓库不存在」),而真实原因是凭据通道不可用 → 钉成 auth(非瞬时、别重试)。
995
- throw new GitTransportError(message, credentialBlocked ? { kind: 'auth', retryable: false } : classified);
1173
+ this.raiseGitFailure(args, result, token, opts.requirePushToken === true);
996
1174
  }
997
1175
  return result;
998
1176
  } catch (err) {
@@ -1008,6 +1186,36 @@ export class GitTransport implements SyncTransport {
1008
1186
  }
1009
1187
  }
1010
1188
 
1189
+ /**
1190
+ * 把「git 退出非零」归一成可操作错误(runGit 与 clone 回落共用同一套文案与分类)。
1191
+ * token 只用于脱敏,绝不进 message。
1192
+ */
1193
+ private raiseGitFailure(args: string[], result: GitExecResult, token: string | null, requirePushToken: boolean): never {
1194
+ const combined = result.stderr + ' ' + result.stdout;
1195
+ // 统一分类(超时 / 网络 / 鉴权 / 5xx…):上层可据 kind / retryable 分流,不必解析 message
1196
+ const classified = classifyNetworkErrorText(combined);
1197
+ // issue #79:SSH 主机密钥校验失败 → 换成「怎么信任该主机」的可操作说明(绝不自动信任)
1198
+ if (SSH_HOST_KEY_RE.test(combined)) {
1199
+ throw new GitTransportError(this.hostKeyMessage(), { kind: 'auth', retryable: false });
1200
+ }
1201
+ // 推送 + 鉴权失败:git 原文只说「认证失败」——换成能照做的说明(令牌失效 / 无写权限 / 远端禁用了密码推送)
1202
+ // issue #115:clone 的鉴权失败原文(remote: Write access to repository not granted / 403)读不出「缺哪种权限」,
1203
+ // 换成点名 Contents: Read and write 的说明 —— 否则用户只会以为令牌坏了(细粒度 PAT 常只勾了 Administration)
1204
+ // issue #120:helper 根本没能执行时,「请确认令牌有效」是错误指引(令牌可能是好的)——
1205
+ // 这类失败必须点名平台原因,排在 push/clone 的鉴权文案之前。
1206
+ const credentialBlocked = isCredentialExecFailure(combined);
1207
+ const message = credentialBlocked
1208
+ ? this.msg('sync.git.credentialHelperBlocked', { err: this.mask(result.stderr, token) })
1209
+ : requirePushToken && classified.kind === 'auth'
1210
+ ? this.msg('sync.git.pushAuthFailed', { err: this.mask(result.stderr, token) })
1211
+ : args[0] === 'clone' && classified.kind === 'auth'
1212
+ ? this.msg('sync.git.cloneAuthFailed', { err: this.mask(result.stderr, token) })
1213
+ : this.msg('sync.git.cmdFailed', { args: args.join(' '), code: String(result.code), err: this.mask(result.stderr, token) });
1214
+ // 归类同样不能交给原文:`cannot exec ...: No such file or directory` 里的 ENOENT 会被判成
1215
+ // notfound(「仓库不存在」),而真实原因是凭据通道不可用 → 钉成 auth(非瞬时、别重试)。
1216
+ throw new GitTransportError(message, credentialBlocked ? { kind: 'auth', retryable: false } : classified);
1217
+ }
1218
+
1011
1219
  /**
1012
1220
  * 为网络命令构造 credential helper 参数:
1013
1221
  * 仅 http(s) 远端需要 token;本地路径 / ssh 走 git 原生认证(密钥),不调用 provider。
@@ -9,9 +9,14 @@
9
9
  * 语义与 ff-only pull 一致:能快进就快进,不能快进就报「历史分叉」。
10
10
  */
11
11
 
12
- /** `git fetch` 参数:只更新 origin/<branch> 这个远端跟踪引用,不写 FETCH_HEAD */
13
- export function fastForwardFetchArgs(branch: string): string[] {
14
- return ['fetch', 'origin', `+refs/heads/${branch}:refs/remotes/origin/${branch}`];
12
+ /**
13
+ * `git fetch` 参数:只更新 origin/<branch> 这个远端跟踪引用,不写 FETCH_HEAD。
14
+ *
15
+ * `flags` 是给调用方补的拉取姿态(如 `--filter=blob:none`/`--no-tags`),必须排在 `origin` 之前:
16
+ * git 只认「子命令后、URL 前」的选项,放到 refspec 之后会被当成 refspec 解析。
17
+ */
18
+ export function fastForwardFetchArgs(branch: string, flags: readonly string[] = []): string[] {
19
+ return ['fetch', ...flags, 'origin', `+refs/heads/${branch}:refs/remotes/origin/${branch}`];
15
20
  }
16
21
 
17
22
  /** `git merge` 参数:快进到显式远端跟踪分支(不依赖 upstream 配置,也不读 FETCH_HEAD) */