dsh-git-push 0.0.0-stage → 2.8.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.
Files changed (278) hide show
  1. package/.auditignore +30 -0
  2. package/.gitignore +39 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1482 -2
  5. package/cli.mjs +360 -0
  6. package/cordis.patch.yml +14 -0
  7. package/lib/ARCHITECTURE.md +34 -0
  8. package/lib/BUGFIX-NOTES-2026-09-14.md +278 -0
  9. package/lib/app/apply.js +275 -0
  10. package/lib/app/audit-api.js +158 -0
  11. package/lib/app/command-registry.js +262 -0
  12. package/lib/app/constants.js +16 -0
  13. package/lib/app/handlers/account.js +166 -0
  14. package/lib/app/handlers/clone.js +168 -0
  15. package/lib/app/handlers/http-constants.js +9 -0
  16. package/lib/app/handlers/identity-rewrite.js +94 -0
  17. package/lib/app/handlers/meta.js +175 -0
  18. package/lib/app/handlers/npm.js +169 -0
  19. package/lib/app/handlers/repo-actions.js +143 -0
  20. package/lib/app/handlers/repos.js +231 -0
  21. package/lib/app/handlers/settings.js +62 -0
  22. package/lib/app/host-doc-checks.js +25 -0
  23. package/lib/app/http-handlers.js +131 -0
  24. package/lib/app/index.js +30 -0
  25. package/lib/app/inject-text.js +191 -0
  26. package/lib/app/scan-root.js +23 -0
  27. package/lib/app/schema.js +150 -0
  28. package/lib/app/settings-bridge.js +167 -0
  29. package/lib/app/slash-commands.js +395 -0
  30. package/lib/app/slot-stats.js +35 -0
  31. package/lib/app/tool-call.js +662 -0
  32. package/lib/app/tools.js +40 -0
  33. package/lib/ast/brace.js +105 -0
  34. package/lib/ast/callgraph.js +135 -0
  35. package/lib/ast/code-lines.js +114 -0
  36. package/lib/ast/consts.js +12 -0
  37. package/lib/ast/control-flow.js +461 -0
  38. package/lib/ast/credential.js +199 -0
  39. package/lib/ast/dataflow.js +274 -0
  40. package/lib/ast/dup-code.js +165 -0
  41. package/lib/ast/index.js +36 -0
  42. package/lib/ast/io-risk-const.js +95 -0
  43. package/lib/ast/io-risk-fn.js +208 -0
  44. package/lib/ast/io-risk-loop.js +308 -0
  45. package/lib/ast/io-risk.js +314 -0
  46. package/lib/ast/lang.js +156 -0
  47. package/lib/ast/line-count.js +52 -0
  48. package/lib/ast/magic-number.js +272 -0
  49. package/lib/ast/naming.js +284 -0
  50. package/lib/ast/perf.js +472 -0
  51. package/lib/ast/scope.js +241 -0
  52. package/lib/ast/shell.js +131 -0
  53. package/lib/ast/size.js +378 -0
  54. package/lib/ast/symbol-index.js +399 -0
  55. package/lib/ast/tokenizer.js +341 -0
  56. package/lib/audit/analysis-coverage.js +98 -0
  57. package/lib/audit/audit-file.js +182 -0
  58. package/lib/audit/checks.js +17 -0
  59. package/lib/audit/client-entry.js +93 -0
  60. package/lib/audit/collector.js +477 -0
  61. package/lib/audit/ext-runner.js +80 -0
  62. package/lib/audit/file-context.js +138 -0
  63. package/lib/audit/finding.js +50 -0
  64. package/lib/audit/gitignore-match.js +113 -0
  65. package/lib/audit/glob.js +63 -0
  66. package/lib/audit/history-report.js +100 -0
  67. package/lib/audit/history.js +126 -0
  68. package/lib/audit/ignore-blind.js +101 -0
  69. package/lib/audit/index.js +33 -0
  70. package/lib/audit/orchestrate.js +476 -0
  71. package/lib/audit/public.js +24 -0
  72. package/lib/audit/repo-level.js +30 -0
  73. package/lib/audit/report-yaml.js +86 -0
  74. package/lib/audit/slot.js +65 -0
  75. package/lib/audit-defaults.js +18 -0
  76. package/lib/audit-rules/audit-rules-comment.yml +247 -0
  77. package/lib/audit-rules/audit-rules-cpp.yml +22 -0
  78. package/lib/audit-rules/audit-rules-docs.yml +32 -0
  79. package/lib/audit-rules/audit-rules-dsh.yml +162 -0
  80. package/lib/audit-rules/audit-rules-filehealth.yml +42 -0
  81. package/lib/audit-rules/audit-rules-folder.yml +99 -0
  82. package/lib/audit-rules/audit-rules-frontend.yml +335 -0
  83. package/lib/audit-rules/audit-rules-go.yml +22 -0
  84. package/lib/audit-rules/audit-rules-i18n.yml +45 -0
  85. package/lib/audit-rules/audit-rules-java.yml +105 -0
  86. package/lib/audit-rules/audit-rules-nodejs.yml +647 -0
  87. package/lib/audit-rules/audit-rules-npm.yml +187 -0
  88. package/lib/audit-rules/audit-rules-paths.yml +92 -0
  89. package/lib/audit-rules/audit-rules-performance.yml +207 -0
  90. package/lib/audit-rules/audit-rules-php.yml +22 -0
  91. package/lib/audit-rules/audit-rules-private.yml +24 -0
  92. package/lib/audit-rules/audit-rules-python.yml +106 -0
  93. package/lib/audit-rules/audit-rules-robustness.yml +27 -0
  94. package/lib/audit-rules/audit-rules-rust.yml +22 -0
  95. package/lib/audit-rules/audit-rules-structure.yml +159 -0
  96. package/lib/audit-rules/audit-rules-swift.yml +22 -0
  97. package/lib/audit-rules/audit-rules-template.yml +108 -0
  98. package/lib/checks/button-bind.js +276 -0
  99. package/lib/checks/common.js +170 -0
  100. package/lib/checks/credential-file.js +43 -0
  101. package/lib/checks/dataflow.js +40 -0
  102. package/lib/checks/dispatch.js +112 -0
  103. package/lib/checks/dup-code.js +69 -0
  104. package/lib/checks/dup-const.js +232 -0
  105. package/lib/checks/file-health.js +150 -0
  106. package/lib/checks/filter.js +131 -0
  107. package/lib/checks/folder.js +173 -0
  108. package/lib/checks/hardcoded-path.js +98 -0
  109. package/lib/checks/index.js +46 -0
  110. package/lib/checks/io.js +66 -0
  111. package/lib/checks/magic-number.js +42 -0
  112. package/lib/checks/npm-json.js +273 -0
  113. package/lib/checks/private.js +63 -0
  114. package/lib/checks/regex.js +256 -0
  115. package/lib/checks/semantic.js +134 -0
  116. package/lib/checks/structural.js +274 -0
  117. package/lib/cli/commands-account.mjs +107 -0
  118. package/lib/cli/commands-audit.mjs +144 -0
  119. package/lib/cli/commands-doc.mjs +127 -0
  120. package/lib/cli/commands-vcs.mjs +175 -0
  121. package/lib/client/index.js +162 -0
  122. package/lib/client-parts/00-loader.js +33 -0
  123. package/lib/client-parts/01-const.js +207 -0
  124. package/lib/client-parts/02-utils.js +62 -0
  125. package/lib/client-parts/03-icons.js +12 -0
  126. package/lib/client-parts/10-account.js +83 -0
  127. package/lib/client-parts/11-browser.js +95 -0
  128. package/lib/client-parts/20-repo.js +374 -0
  129. package/lib/client-parts/21-audit.js +301 -0
  130. package/lib/client-parts/22-settings.js +146 -0
  131. package/lib/client-parts/23-npm.js +383 -0
  132. package/lib/client-parts/30-page.js +56 -0
  133. package/lib/client-parts/40-controller.js +1092 -0
  134. package/lib/client-parts/41-actions.js +279 -0
  135. package/lib/client-parts/99-apply.js +72 -0
  136. package/lib/client.js +3195 -0
  137. package/lib/commit-push.js +144 -0
  138. package/lib/context/index.js +363 -0
  139. package/lib/core/atomic-json.js +98 -0
  140. package/lib/core/config.js +40 -0
  141. package/lib/core/credentials.js +274 -0
  142. package/lib/core/endpoints.js +109 -0
  143. package/lib/core/exec.js +162 -0
  144. package/lib/exempt/index.js +292 -0
  145. package/lib/fs/edit-after-read.js +103 -0
  146. package/lib/fsx.js +87 -0
  147. package/lib/git/account-status.js +140 -0
  148. package/lib/git/account.js +233 -0
  149. package/lib/git/api.js +136 -0
  150. package/lib/git/atomic-json.js +6 -0
  151. package/lib/git/browse.js +38 -0
  152. package/lib/git/clone-download.js +397 -0
  153. package/lib/git/clone-history-mode.js +143 -0
  154. package/lib/git/clone-history.js +175 -0
  155. package/lib/git/clone-jobs.js +250 -0
  156. package/lib/git/clone-replay-io.js +172 -0
  157. package/lib/git/clone-replay.js +275 -0
  158. package/lib/git/clone.js +445 -0
  159. package/lib/git/cloud.js +46 -0
  160. package/lib/git/commit-message.js +141 -0
  161. package/lib/git/config.js +6 -0
  162. package/lib/git/cred-env.js +88 -0
  163. package/lib/git/credentials.js +6 -0
  164. package/lib/git/endpoints.js +6 -0
  165. package/lib/git/exec.js +6 -0
  166. package/lib/git/identity-rewrite.js +297 -0
  167. package/lib/git/identity.js +150 -0
  168. package/lib/git/ignore.js +69 -0
  169. package/lib/git/index.js +41 -0
  170. package/lib/git/module-splitter.js +47 -0
  171. package/lib/git/post-push.js +101 -0
  172. package/lib/git/push-diagnose.js +142 -0
  173. package/lib/git/push.js +470 -0
  174. package/lib/git/remote-resolve.js +146 -0
  175. package/lib/git/remote.js +128 -0
  176. package/lib/git/repo-index.js +512 -0
  177. package/lib/git/repos.js +235 -0
  178. package/lib/git/scan-runner.js +159 -0
  179. package/lib/git/sensitive.js +134 -0
  180. package/lib/git/transport.js +430 -0
  181. package/lib/git/visibility.js +35 -0
  182. package/lib/git/wrapped-git.js +68 -0
  183. package/lib/http/index.js +170 -0
  184. package/lib/index.js +24 -0
  185. package/lib/link-check/index.js +187 -0
  186. package/lib/npm/account.js +64 -0
  187. package/lib/npm/install.js +211 -0
  188. package/lib/npm/npmrc.js +56 -0
  189. package/lib/npm/publish.js +167 -0
  190. package/lib/npm/registry.js +147 -0
  191. package/lib/plugin/auto-detect.js +92 -0
  192. package/lib/plugin/auto-push.js +154 -0
  193. package/lib/plugin/index.js +250 -0
  194. package/lib/readme-templates/readme.yml +38 -0
  195. package/lib/rule/compilers/credential.js +62 -0
  196. package/lib/rule/compilers/dataflow.js +38 -0
  197. package/lib/rule/compilers/file-health.js +75 -0
  198. package/lib/rule/compilers/frontend.js +86 -0
  199. package/lib/rule/compilers/func.js +35 -0
  200. package/lib/rule/compilers/helpers.js +71 -0
  201. package/lib/rule/compilers/index.js +29 -0
  202. package/lib/rule/compilers/link-semantic.js +45 -0
  203. package/lib/rule/compilers/list-kinds.js +12 -0
  204. package/lib/rule/compilers/numeric-kinds.js +66 -0
  205. package/lib/rule/compilers/regex.js +78 -0
  206. package/lib/rule/compilers/structure.js +80 -0
  207. package/lib/rule/compilers.js +17 -0
  208. package/lib/rule/homoglyph.js +45 -0
  209. package/lib/rule/loader.js +270 -0
  210. package/lib/rule/registry.js +115 -0
  211. package/lib/rule/scope.js +67 -0
  212. package/lib/score/docs-score.js +166 -0
  213. package/lib/score/index.js +140 -0
  214. package/lib/self/index.js +193 -0
  215. package/lib/skip-dirs.js +64 -0
  216. package/lib/tool-probes.json +50 -0
  217. package/lib/user-requirements.json +14 -0
  218. package/lib/vendor/js-yaml/LICENSE +21 -0
  219. package/lib/vendor/js-yaml/js-yaml.mjs +3073 -0
  220. package/package.json +95 -4
  221. package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
  222. package/scripts/audit-ext/_example-readme-present.mjs +34 -0
  223. package/scripts/audit-ext/variable-min-length.mjs +102 -0
  224. package/scripts/audit-runner.mjs +35 -0
  225. package/scripts/audit-runtime-check.mjs +129 -0
  226. package/scripts/browser-page-probe.mjs +271 -0
  227. package/scripts/build-client.mjs +119 -0
  228. package/scripts/check.mjs +88 -0
  229. package/scripts/clean-date-comments.py +102 -0
  230. package/scripts/doc-drift.mjs +200 -0
  231. package/scripts/doc-func.mjs +212 -0
  232. package/scripts/doc-tree.mjs +456 -0
  233. package/scripts/doc-version.mjs +220 -0
  234. package/scripts/frontend-preview-check.mjs +124 -0
  235. package/scripts/hot-path-probe-cjs.cjs +71 -0
  236. package/scripts/hot-path-probe-fs-shim.mjs +28 -0
  237. package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
  238. package/scripts/hot-path-probe.mjs +153 -0
  239. package/scripts/module-splitter.py +800 -0
  240. package/scripts/platform-scan.mjs +168 -0
  241. package/scripts/preview-gen.mjs +489 -0
  242. package/scripts/preview-local-runner.mjs +55 -0
  243. package/scripts/preview-server-direct.mjs +116 -0
  244. package/scripts/preview-server.mjs +305 -0
  245. package/scripts/preview-slot-data.mjs +123 -0
  246. package/scripts/probe-recheck.mjs +47 -0
  247. package/scripts/readme-gen.mjs +268 -0
  248. package/scripts/rename-locator.mjs +97 -0
  249. package/scripts/rule-switch.mjs +97 -0
  250. package/scripts/rules-solo-audit.mjs +173 -0
  251. package/scripts/scan-file-io.mjs +713 -0
  252. package/scripts/scan-hardcoded-paths.mjs +125 -0
  253. package/scripts/scan-repos.mjs +167 -0
  254. package/scripts/scan-version.mjs +122 -0
  255. package/scripts/scrub-user-wording.mjs +420 -0
  256. package/scripts/symbol-index.mjs +85 -0
  257. package/scripts/sync-plugin-install.mjs +223 -0
  258. package/scripts/sync-plugin.mjs +279 -0
  259. package/scripts/verify-prestep.mjs +100 -0
  260. package/skills/dev/audit-rule-authoring.md +58 -0
  261. package/skills/dev/dsh-git-push.md +323 -0
  262. package/skills/dev/git-push-live-fix.md +45 -0
  263. package/skills/dsh-repo-index.md +35 -0
  264. package/skills/guide/guide-audit.md +167 -0
  265. package/skills/guide/guide-cli-scripts.md +104 -0
  266. package/skills/guide/guide-clone-repos.md +173 -0
  267. package/skills/guide/guide-commit-push.md +156 -0
  268. package/skills/guide/guide-inject-ui.md +166 -0
  269. package/skills/guide/guide-slash-completion.md +118 -0
  270. package/skills/workflow/README.md +21 -0
  271. package/skills/workflow/git-commit-discipline.md +68 -0
  272. package/skills/workflow/git-project-startup.md +85 -0
  273. package/skills/workflow/git-rebuild-process.md +57 -0
  274. package/skills/workflow/github-operations.md +91 -0
  275. package/skills/workflow/readme-sync-git-md.md +28 -0
  276. package/skills/workflow/task-completion-report.md +73 -0
  277. package/skills/workflow/tool-json-add-ask.md +35 -0
  278. package/skills/workflow/versioning-rule.md +211 -0
@@ -0,0 +1,430 @@
1
+ /**
2
+ * Git 执行层 · 推送通道
3
+ *
4
+ * 职责:通道选择(dispatchPush)、远端 head 查询、SSH 推送、API 推送、推送结果核对。
5
+ *
6
+ * 两个通道的本质差别(选通道前必须知道):
7
+ * - SSH:`git push <ssh-url> HEAD:refs/heads/<branch>`,上传的是**本地提交对象本身**,
8
+ * 推上去的 sha 与本地 HEAD 完全一致。
9
+ * - API:走 Git Data API(blob → tree → commit → ref)**在远端重建提交**,
10
+ * 父提交/作者/时间戳都是新造的 → 远端 sha 必然与本地不同,本地与远端从此分叉。
11
+ * 因此默认通道是 SSH(pushMethod 默认 'ssh');只有没有可用私钥时才回落 API。
12
+ */
13
+
14
+ import { join } from 'node:path';
15
+ import { githubFetch, isBadCredentials, parseGithubOwnerRepo } from './api.js';
16
+ import { resolveSshKey, resolveSshKeys, resolveToken } from './credentials.js';
17
+ import { gitRaw, runGit, runGitAsync } from './exec.js';
18
+ // 「推送到 GitHub 时自动指定正确的 remote」:归属 + 本机可用形态(ssh:443)+ 名字优先级统一判定
19
+ import { resolveGithubRemote, parseGithubUrl } from './remote-resolve.js';
20
+ // 推送失败诊断(分类 + 置信度 + 下一步):把原文事实与推断分开返回
21
+ import { classifyPushFailure } from './push-diagnose.js';
22
+
23
+ /* ───────── 推送通道常量 ───────── */
24
+ const COMMITS_FETCH_TIMEOUT_MS = 20_000; // 远端 commits 查询超时
25
+ const SSH_REASON_MAX_LEN = 320; // ssh 失败原因截断
26
+ const FAILED_REASONS_MAX_LEN = 700; // 多通道失败原因拼接截断
27
+ const SSH_URL_TMPL = 'ssh://git@ssh.github.com:443'; // ssh 通道域名前缀(含端口)
28
+ const KNOWN_HOSTS_FILE_TMPL = 'dsh-git-push-known-hosts-${pid}'; // 临时 known_hosts 文件名模板
29
+ const REFS_HEADS_PREFIX = 'refs/heads/'; // 推送目标 ref 前缀
30
+
31
+ /** 组装 ssh URL:`SSH_URL_TMPL/<owner>/<repo>.git`。 */
32
+ function sshUrlOf(pr) {
33
+ return `${SSH_URL_TMPL}/${pr.owner}/${pr.repo}.git`;
34
+ }
35
+
36
+ /** 本进程的临时 known_hosts 文件绝对路径。 */
37
+ function knownHostsPath() {
38
+ return join('/tmp', KNOWN_HOSTS_FILE_TMPL.replace('${pid}', String(process.pid)));
39
+ }
40
+
41
+ /**
42
+ * 推送后回传远端最近 count 次提交(SHA/标题/时间),供工具结果展示。
43
+ * 复用 githubFetch(api.github.com);失败返回 { ok:false }(不阻断主流程)。
44
+ * @returns {{ok:boolean, owner?, repo?, branch?, heads?: {sha,title,date}[], error?}}
45
+ */
46
+ export async function fetchRemoteHeads({ owner = '', repo = '', branch = '', token = '', count = 3 } = {}) {
47
+ if (!owner || !repo) return { ok: false, error: '缺 owner/repo' };
48
+ const query = `sha=${encodeURIComponent(branch || '')}&per_page=${Number(count) || 3}`;
49
+ const commitsResp = await githubFetch(`/repos/${owner}/${repo}/commits?${query}`, { token, timeout: COMMITS_FETCH_TIMEOUT_MS });
50
+ if (commitsResp.status !== 200 || !Array.isArray(commitsResp.json)) {
51
+ return { ok: false, error: commitsResp.error || `commits ${commitsResp.status}`, heads: [] };
52
+ }
53
+ const heads = (commitsResp.json || []).map((c) => ({
54
+ sha: (c?.sha || '').slice(0, 7),
55
+ title: c?.commit?.message?.split('\n')[0] || '',
56
+ date: c?.commit?.author?.date || '',
57
+ })).filter((h) => h.sha);
58
+ return { ok: true, owner, repo, branch, heads };
59
+ }
60
+
61
+ /* ───────────────────────── 推送:通道调度 + 两条通道实现 ───────────────────────── */
62
+
63
+ /**
64
+ * 推送通道调度(单一决策点)。
65
+ *
66
+ * pushMethod 三档语义:
67
+ * - 'ssh'(默认):SSH 优先。有可用私钥就走 SSH(推本地 HEAD,远端 sha == 本地 sha,
68
+ * 本地与远端不分叉);无密钥或 SSH 推送失败 → 回落 API 并如实标注 fallback 原因。
69
+ * - 'api':API 优先(Git Data API 重建提交);失败时回落 SSH。
70
+ * - 'auto':探测优先——有私钥走 SSH,否则直接 API(不产生一次失败的尝试记录)。
71
+ *
72
+ * 为什么默认 ssh:API 通道会在远端重建 commit,推完远端 sha 与本地不同(本地 origin/master
73
+ * 引用与实际远端对不上),需要额外 fetch 才能对齐;SSH 直接用本地对象,sha 天然一致。
74
+ * @param {object} p { repoPath, branch?, token?, force?, pushMethod? }
75
+ * @returns {Promise<{ok, pushed, method?, reason?, fallbackReason?, key?, ...}>}
76
+ */
77
+ export async function dispatchPush({ repoPath = '', branch = '', token = '', force = false, pushMethod = 'ssh' } = {}) {
78
+ const mode = String(pushMethod || 'ssh').toLowerCase();
79
+ const hasKey = resolveSshKeys().length > 0;
80
+
81
+ const trySsh = () => pushViaSsh({ repoPath, branch, force });
82
+ const tryApi = () => pushViaApi({ repoPath, branch, token, force });
83
+
84
+ if (mode === 'api') {
85
+ const apiRes = await tryApi();
86
+ if (apiRes.ok) return apiRes;
87
+ const sshRes = trySsh();
88
+ if (sshRes.ok) return sshRes;
89
+ return { ok: false, pushed: false, method: 'api', reason: `API: ${apiRes.reason};SSH: ${sshRes.reason}` };
90
+ }
91
+
92
+ if (mode === 'auto' && !hasKey) return tryApi();
93
+
94
+ // 'ssh'(默认)与 'auto' 且存在密钥:SSH 优先
95
+ const sshRes = trySsh();
96
+ if (sshRes.ok) return sshRes;
97
+ // 远端分叉时不回落 API:API 会在远端重建提交、再分一条叉,且以「推送成功」掩盖成因。
98
+ // 此处如实报错,由调用方决定 force 强推还是先整合远端。
99
+ if (isNonFastForward(sshRes.reason)) {
100
+ const localHead = runGit(['rev-parse', 'HEAD'], { cwd: repoPath }).stdout;
101
+ const cur = branch || runGit(['branch', '--show-current'], { cwd: repoPath }).stdout || 'master';
102
+ const cached = runGit(['rev-parse', `refs/remotes/origin/${cur}`], { cwd: repoPath }).stdout;
103
+ const live = liveRemoteHead({ repoPath, branch: cur });
104
+ const remoteHead = live.sha || cached || '';
105
+ return {
106
+ ok: false, pushed: false, method: 'ssh', diverged: true,
107
+ localHead: localHead || '', remoteHead,
108
+ reason: `远端已分叉(non-fast-forward):本地 ${(localHead || '?').slice(0, 7)}`
109
+ + ` 与远端 ${(remoteHead || '?').slice(0, 7)}`
110
+ + (live.sha && cached && live.sha !== cached ? `(本地 origin/${cur} 缓存 ${(cached || '').slice(0, 7)} 已过期)` : '')
111
+ + '。已阻止回落 API。请先 fetch 整合,或确认后 force。'
112
+ + (sshRes.reason ? ` 原始:${sshRes.reason}` : ''),
113
+ };
114
+ }
115
+ const apiRes = await tryApi();
116
+ if (apiRes.ok) {
117
+ apiRes.fallbackReason = `SSH 未成功(${sshRes.reason})→ 回落 API(远端 sha 与本地不同)`;
118
+ return apiRes;
119
+ }
120
+ return { ok: false, pushed: false, method: 'ssh', reason: `SSH: ${sshRes.reason};API: ${apiRes.reason}` };
121
+ }
122
+
123
+ /**
124
+ * 从 ssh/git 的 stderr 提取「真正的原因」。
125
+ * 直接把 stderr 塞进结果,会把已知主机告警与 git 的「提示:」建议段一起带出来,
126
+ * 前 120 字符常被告警占满、真正的失败原因(如 non-fast-forward)反被截掉。
127
+ */
128
+ export function sshReason(stderr = '') {
129
+ const raw = String(stderr || '');
130
+ const lines = raw.split('\n')
131
+ .map((l) => l.trim())
132
+ .filter(Boolean)
133
+ .filter((l) => !/^Warning: Permanently added/.test(l))
134
+ .filter((l) => !/^(提示:|hint:|remote:)/.test(l));
135
+ const text = lines.join(' ').replace(/\s+/g, ' ').trim();
136
+ return (text || raw.trim() || 'ssh push 失败').slice(-SSH_REASON_MAX_LEN);
137
+ }
138
+
139
+ /**
140
+ * 判定是否为「远端分叉」(non-fast-forward)。
141
+ * 用途是拦住 API 回落:分叉时回落 API 会在远端**再重建一个提交**,本地与远端又多分一条叉,
142
+ * 每推一次多分一次,且成因被「推送成功」掩盖——正是默认走 SSH 要避免的情形。
143
+ */
144
+ export function isNonFastForward(text = '') {
145
+ return /non-fast-forward|fetch first|Updates were rejected|更新被拒绝|远程仓库包含您本地尚不存在的提交/i.test(String(text));
146
+ }
147
+
148
+ /**
149
+ * 优化:SSH 连接复用(ControlMaster)——列表逐仓探测时把 N 次 SSH 握手降到 1 次。
150
+ *
151
+ * 背景:liveRemoteHead 每次调用都新建 SSH 连接,而单次握手约 4~6s(实测 6.3s),
152
+ * 真正的 ls-remote 只占其中一小部分。实测同一 ControlPath 下第二次起降到 ~1.6s
153
+ * (省约 74%),跨仓库同样有效(首个 4.1s、后续 1.5~1.9s)。
154
+ * 列表里多仓串行时这是决定「是否超预算被熔断」的关键,故引入共享 ControlPath。
155
+ *
156
+ * 生命周期:用模块级单例 socket,惰性创建、进程退出时关闭;DSH_GIT_PUSH_NO_SSH_MUX=1
157
+ * 可关闭复用(排查连接问题时用)。任何失败都退化为「不复用」,不影响功能正确性。
158
+ */
159
+ let _sshMuxCtlPath = '';
160
+ function sshMuxCtlPath() {
161
+ if (process.env.DSH_GIT_PUSH_NO_SSH_MUX === '1') return '';
162
+ if (_sshMuxCtlPath) return _sshMuxCtlPath;
163
+ // ControlPath **不含 pid**——含 pid 时每个进程(含插件每次重载)各建一个
164
+ // socket,既无法跨调用复用、又会在 reload 后残留 /tmp 垃圾。实测稳定路径可跨进程复用
165
+ // (进程 A 3.8s 建立 → 进程 B/C 分别 1.45s/1.97s),且 DSH 里 repos-local 由同一长驻
166
+ // 进程处理,命中率很高。用 uid 隔离多用户,避免 /tmp 权限冲突。
167
+ const uid = (() => { try { return process.getuid ? process.getuid() : 'x'; } catch { return 'x'; } })();
168
+ _sshMuxCtlPath = join('/tmp', `dsh-git-push-mux-${uid}`);
169
+ // **不注册 exit 清理**。ControlPath 稳定后是「全机共享」的连接池,
170
+ // 在退出时 `ssh -O exit` 会把其他进程/会话正在复用的连接一并掐断(且 -O exit 对
171
+ // 共享 socket 是全局语义)。ControlPersist=60 已保证空闲连接 60s 后自行回收,
172
+ // 无需手工清理——这也避免了 /tmp 残留。
173
+ return _sshMuxCtlPath;
174
+ }
175
+
176
+ /** 组装 ls-remote 用的 GIT_SSH_COMMAND(含 ControlMaster 复用参数)。 */
177
+ function buildLsRemoteSshCmd(keyPath, known, { mux = true } = {}) {
178
+ const base = `ssh -i "${keyPath}" -p 443 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="${known}" -o BatchMode=yes -o ConnectTimeout=5`;
179
+ const ctl = mux ? sshMuxCtlPath() : '';
180
+ if (!ctl) return base;
181
+ // 复用:首个连接成为 master 并在 ControlPersist 内保活,后续直接走已有 socket
182
+ return `${base} -o ControlMaster=auto -o ControlPath="${ctl}" -o ControlPersist=60`;
183
+ }
184
+
185
+ /**
186
+ * 用插件 SSH 密钥 live ls-remote 远端分支 HEAD(不依赖过期的 origin/<branch> 缓存)。
187
+ * origin 是 https 时本地 fetch 常失败,账号卡片会把「远端已前走」显示成「领先 N」。
188
+ * @returns {{ok:boolean, sha:string, via?:string}}
189
+ */
190
+ export function liveRemoteHead({ repoPath = '', branch = '' } = {}) {
191
+ // 离线开关(单测/无外网)——直接失败,不触发 SSH/网络 ls-remote(防挂起)
192
+ if (process.env.DSH_GIT_PUSH_OFFLINE === '1') return { ok: false, sha: '', via: 'offline' };
193
+ // 自动指定正确的 remote(与推送同源判定:归属 + ssh:443 形态 + 名字优先级)
194
+ const rr = resolveGithubRemote({ repoPath });
195
+ const pr = (rr.ok && rr.url ? parseGithubUrl(rr.url) : null)
196
+ || parseGithubOwnerRepo(runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }).stdout);
197
+ const target = branch || runGit(['branch', '--show-current'], { cwd: repoPath }).stdout;
198
+ if (!pr || !target) return { ok: false, sha: '' };
199
+ const sshUrl = sshUrlOf(pr);
200
+ const known = knownHostsPath();
201
+ // 修复:ls-remote 必须**短超时**——此前用 runGit 默认 120s,本地列表逐仓 SSH
202
+ // 探测时一旦网络慢/不通,多仓叠加会把「读列表」卡死数分钟(打开面板像死机)。
203
+ // 现在 SSH ConnectTimeout=5 + git 侧 8s、最多试 2 个 key,保证列表秒级返回。
204
+ const LS_TIMEOUT = 8_000;
205
+ let tried = 0;
206
+ for (const { keyPath, kind } of resolveSshKeys()) {
207
+ if (tried >= 2) break; // 最多试 2 个 key,避免多 key 串行放大耗时
208
+ tried += 1;
209
+ const sshCmd = buildLsRemoteSshCmd(keyPath, known);
210
+ const r = runGit(['ls-remote', sshUrl, `${REFS_HEADS_PREFIX}${target}`], { cwd: repoPath, env: { GIT_SSH_COMMAND: sshCmd }, timeoutMs: LS_TIMEOUT });
211
+ if (r.ok) {
212
+ const sha = (r.stdout || '').trim().split(/\s+/)[0] || '';
213
+ if (sha) return { ok: true, sha, via: kind };
214
+ }
215
+ }
216
+ const lr = runGit(['ls-remote', rr.remote || 'origin', `${REFS_HEADS_PREFIX}${target}`], { cwd: repoPath, timeoutMs: LS_TIMEOUT });
217
+ if (lr.ok) {
218
+ const sha = (lr.stdout || '').trim().split(/\s+/)[0] || '';
219
+ if (sha) return { ok: true, sha, via: rr.remote || 'origin' };
220
+ }
221
+ return { ok: false, sha: '' };
222
+ }
223
+
224
+ /** SSH 回退:ssh.github.com:443(token 401 时)。force=true 时 --force(覆盖远端历史)。 */
225
+ export function pushViaSsh({ repoPath = '', branch = '', force = false }) {
226
+ const keys = resolveSshKeys();
227
+ if (!keys.length) return { ok: false, pushed: false, reason: '无 SSH 私钥(配置目录 id_rsa/id_ed25519/id_ecdsa)' };
228
+ // 自动指定正确的 remote(归属 + 本机可用形态 ssh:443 + 名字优先级;必要时 set-url)——不再写死 origin
229
+ const rr = resolveGithubRemote({ repoPath });
230
+ const picked = rr.ok && rr.url ? parseGithubUrl(rr.url) : null;
231
+ const originUrl = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }).stdout;
232
+ const pr = picked || parseGithubOwnerRepo(originUrl);
233
+ if (!pr) {
234
+ return {
235
+ ok: false, pushed: false,
236
+ reason: `无法判定 GitHub remote(origin:${String(originUrl || '').trim() || '不存在'};${(rr.reasons || []).join(';') || '无 GitHub remote'})`,
237
+ };
238
+ }
239
+ const target = branch || runGit(['branch', '--show-current'], { cwd: repoPath }).stdout;
240
+ if (!target) return { ok: false, pushed: false, reason: '无法确定目标分支' };
241
+ const sshUrl = sshUrlOf(pr);
242
+ const known = knownHostsPath();
243
+ // 逐个试探测到的密钥:配置目录里可能同时存在多把,其中未登记到 GitHub 的那把会
244
+ // 报 Permission denied (publickey),这里换下一把继续,避免「有可用密钥却推不动」。
245
+ const tried = [];
246
+ for (const { keyPath, kind } of keys) {
247
+ const sshCmd = `ssh -i "${keyPath}" -p 443 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="${known}" -o BatchMode=yes`;
248
+ const pushArgs = ['push', ...(force ? ['--force'] : []), sshUrl, `HEAD:refs/heads/${target}`];
249
+ const r = runGit(pushArgs, { cwd: repoPath, env: { GIT_SSH_COMMAND: sshCmd } });
250
+ if (r.ok) {
251
+ return { ok: true, pushed: true, method: 'ssh', force, key: kind, owner: pr.owner, repo: pr.repo, branch: target, remote: rr.remote, remoteAction: rr.action, remoteReasons: rr.reasons };
252
+ }
253
+ tried.push(`${kind}: ${sshReason(r.stderr)}`);
254
+ }
255
+ const reason = tried.join(' | ').slice(-FAILED_REASONS_MAX_LEN);
256
+ // 失败回执必须带结构化诊断:原文(fact)常有歧义,分类(code)+ 置信度 + 下一步才是可执行的部分 ✓
257
+ return { ok: false, pushed: false, method: 'ssh', reason, diagnosis: classifyPushFailure(reason, { method: 'ssh' }) };
258
+ }
259
+
260
+ /** token 401/坏凭据 → SSH 回退;回退也失败则返回统一失败对象。 */
261
+ async function sshFallback(repoPath, branch) {
262
+ const fb = await pushViaSsh({ repoPath, branch });
263
+ return fb.ok ? fb : { ok: false, pushed: false, method: 'ssh-fallback', reason: `token 失效(API 401)→ SSH 回退失败: ${fb.reason}` };
264
+ }
265
+
266
+ /** 判定 GitHub 返回是否「凭据不可用」(401 / Bad credentials),是则走 SSH 回退。 */
267
+ async function apiOrFallback(api, repoPath, branch, res) {
268
+ if (isBadCredentials(res.error || `HTTP ${res.status}`) || res.status === 401) {
269
+ return sshFallback(repoPath, branch);
270
+ }
271
+ return null; // 正常结果(含 404 等非凭据错误),由调用方继续处理
272
+ }
273
+
274
+ /**
275
+ * 推送(api.github.com Git Data API:blob → tree → commit → ref)。
276
+ * token 401 → pushViaSsh 回退。
277
+ * @returns {{ok, pushed, method?, commitSha?, reason?, branchAdjusted?}}
278
+ */
279
+ export async function pushViaApi({ repoPath = '', branch = '', token = '', force = false } = {}) {
280
+ const rr = resolveGithubRemote({ repoPath });
281
+ const origin = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }).stdout;
282
+ const pr = (rr.ok && rr.url ? parseGithubUrl(rr.url) : null) || parseGithubOwnerRepo(origin);
283
+ if (!pr) {
284
+ return {
285
+ ok: false, pushed: false,
286
+ reason: `无法判定 GitHub owner/repo(origin:${String(origin || '').trim() || '不存在'};${(rr.reasons || []).join(';') || '无 GitHub remote'})`,
287
+ };
288
+ }
289
+ const { owner, repo } = pr;
290
+ const tok = token || resolveToken({ repoPath }).token;
291
+ const api = (path, method = 'GET', body) => githubFetch(`/repos/${owner}/${repo}${path}`, { token: tok, method, body });
292
+
293
+ const headSha = runGit(['rev-parse', 'HEAD'], { cwd: repoPath }).stdout;
294
+ if (!headSha) return { ok: false, pushed: false, reason: '本地无提交' };
295
+ const lsOut = runGit(['ls-tree', '-r', 'HEAD'], { cwd: repoPath }).stdout;
296
+ const entries = lsOut.split('\n').filter(Boolean).map((l) => {
297
+ const match = l.match(/^(\d+)\s+(\w+)\s+([0-9a-f]+)\t(.*)$/);
298
+ return match && match[2] === 'blob' ? { mode: match[1], type: match[2], sha: match[3], path: match[4] } : null;
299
+ }).filter(Boolean);
300
+ if (!entries.length) return { ok: false, pushed: false, reason: '本地 tree 为空' };
301
+
302
+ // 分支解析:远端 default_branch 优先(防误建错名分支)
303
+ let targetBranch = branch || runGit(['branch', '--show-current'], { cwd: repoPath }).stdout || 'master';
304
+ let branchAdjusted = null;
305
+ const meta = await api('');
306
+ const fb1 = await apiOrFallback(api, repoPath, targetBranch, meta);
307
+ if (fb1) return fb1;
308
+ const refRes = await api(`/git/ref/heads/${targetBranch}`);
309
+ const fb2 = await apiOrFallback(api, repoPath, targetBranch, refRes);
310
+ if (fb2) return fb2;
311
+ // 分支免疫:仅当「请求分支在远端不存在」且「远端有不同名 default_branch」时才改用
312
+ // 默认分支——防误建错名新分支;请求分支已存在则保持请求值(v2 旧实现无条件切 default,会误切已有分支)
313
+ const hasRequestedRef = refRes.status === 200;
314
+ if (!hasRequestedRef && !branchAdjusted && meta.status === 200 && meta.json?.default_branch && meta.json.default_branch !== targetBranch) {
315
+ branchAdjusted = { from: targetBranch, to: meta.json.default_branch };
316
+ targetBranch = meta.json.default_branch;
317
+ }
318
+ const refRes2 = branchAdjusted ? await api(`/git/ref/heads/${targetBranch}`) : refRes;
319
+ const fb3 = branchAdjusted ? await apiOrFallback(api, repoPath, targetBranch, refRes2) : null;
320
+ if (fb3) return fb3;
321
+ const remoteHead = refRes2.status === 200 ? refRes2.json?.object?.sha : null;
322
+
323
+ // 内容级短路:远端 HEAD==本地 HEAD 或 tree sha 相同 → 无新内容可推,不建冗余 commit。
324
+ // force=覆盖历史:即使 tree 相同也要换 commit(去掉旧 parent)。
325
+ if (!force) {
326
+ if (remoteHead === headSha) {
327
+ return { ok: true, pushed: false, reason: '远端已是最新,无新提交可推送(正常,不是错误)', owner, repo, branch: targetBranch, branchAdjusted };
328
+ }
329
+ if (remoteHead) {
330
+ const localTree = runGit(['rev-parse', 'HEAD^{tree}'], { cwd: repoPath }).stdout;
331
+ const rc = await api(`/git/commits/${remoteHead}`);
332
+ const remoteTree = rc.json?.tree?.sha;
333
+ if (localTree && remoteTree && localTree === remoteTree) {
334
+ return { ok: true, pushed: false, reason: '远端已是最新,无新提交可推送(正常,不是错误)', owner, repo, branch: targetBranch, branchAdjusted };
335
+ }
336
+ }
337
+ }
338
+
339
+ // 远端已有 blob sha(复用,减少 API 调用)
340
+ const remoteBlobShas = new Set();
341
+ if (remoteHead) {
342
+ const t = await api(`/git/trees/${remoteHead}?recursive=1`);
343
+ if (t.status === 200 && Array.isArray(t.json?.tree)) {
344
+ for (const e of t.json.tree) if (e.type === 'blob') remoteBlobShas.add(e.sha);
345
+ }
346
+ }
347
+ const treeBuilt = await uploadBlobsAndBuildTree({ repoPath, entries, remoteBlobShas, api });
348
+ if (!treeBuilt.ok) return treeBuilt.fail;
349
+
350
+ // 建 commit(parent=远端 HEAD;force 不挂 parent)
351
+ const msg = runGit(['log', '-1', '--format=%s'], { cwd: repoPath }).stdout || 'chore: push via api';
352
+ const commit = await api('/git/commits', 'POST', { message: msg, tree: treeBuilt.treeSha, ...(!force && remoteHead ? { parents: [remoteHead] } : {}) });
353
+ if (commit.status !== 201) return { ok: false, pushed: false, reason: `建 commit 失败: ${commit.json?.message || commit.status}` };
354
+
355
+ // 更新 ref(有则 PATCH,无则 POST 创建)
356
+ if (remoteHead) {
357
+ const r = await api(`/git/refs/heads/${targetBranch}`, 'PATCH', { sha: commit.json.sha, force: !!force });
358
+ if (r.status !== 200) return { ok: false, pushed: false, reason: `更新 ref 失败: ${r.json?.message || r.status}` };
359
+ } else {
360
+ const r = await api('/git/refs', 'POST', { ref: `${REFS_HEADS_PREFIX}${targetBranch}`, sha: commit.json.sha });
361
+ if (r.status !== 201) {
362
+ if (r.status === 422) {
363
+ const r2 = await api(`/git/refs/heads/${targetBranch}`, 'PATCH', { sha: commit.json.sha, force: !!force });
364
+ if (r2.status !== 200) return { ok: false, pushed: false, reason: `更新 ref 失败: ${r2.json?.message || r2.status}` };
365
+ } else {
366
+ return { ok: false, pushed: false, reason: `创建 ref 失败: ${r.json?.message || r.status}` };
367
+ }
368
+ }
369
+ }
370
+ return { ok: true, pushed: true, method: 'api', commitSha: commit.json.sha, owner, repo, branch: targetBranch, branchAdjusted };
371
+ }
372
+
373
+ /**
374
+ * 逐 blob 上传(远端已有 sha 直接复用)+ 建 tree(拆分自 pushViaApi,控制单函数行数)。
375
+ * @returns {{ok:true, treeSha: string} | {ok:false, fail: object}}
376
+ */
377
+ async function uploadBlobsAndBuildTree({ repoPath, entries, remoteBlobShas, api }) {
378
+ const fail = (reason) => ({ ok: false, fail: { ok: false, pushed: false, reason } });
379
+ const treeEntries = [];
380
+ for (const e of entries) {
381
+ if (remoteBlobShas.has(e.sha)) { treeEntries.push({ path: e.path, mode: e.mode, type: 'blob', sha: e.sha }); continue; }
382
+ // 【修复 】读 blob 必须走 gitRaw(buffer 通道):runGit 的 utf8+trim
383
+ // 会丢末尾换行/损坏非 UTF-8 字节 → 上传 blob sha 与本地不一致(实测 17/109 文件损坏)。
384
+ // 判据只认 status:0 = 成功(空内容是合法空 blob);非 0 才是真失败(gitRaw 语义)。
385
+ const raw = gitRaw(['cat-file', 'blob', e.sha], { cwd: repoPath });
386
+ if (raw.status !== 0) return fail(`读 blob 失败: ${e.path}`);
387
+ const b = await api('/git/blobs', 'POST', { content: raw.stdout.toString('base64'), encoding: 'base64' });
388
+ if (b.status !== 201) return fail(`上传 blob 失败 ${e.path}: ${b.json?.message || b.status}`);
389
+ treeEntries.push({ path: e.path, mode: e.mode, type: 'blob', sha: b.json.sha });
390
+ }
391
+ const t = await api('/git/trees', 'POST', { tree: treeEntries });
392
+ if (t.status !== 201) return fail(`建 tree 失败: ${t.json?.message || t.status}`);
393
+ return { ok: true, treeSha: t.json.sha };
394
+ }
395
+
396
+ /**
397
+ * liveRemoteHead 的**异步版**:语义与返回值完全一致,改用 runGitAsync 以便真正并发。
398
+ *
399
+ * 新增:列表逐仓探测时,同步版 runGit 会阻塞事件循环,Promise worker 无法并行
400
+ * (实测 6 仓仍要 13s)。本函数让各仓的 git 子进程真正并行等待,配合 SSH 连接复用
401
+ * (ControlMaster)把 N 仓总耗时压到接近单仓。
402
+ * @returns {Promise<{ok:boolean, sha:string, via?:string}>}
403
+ */
404
+ export async function liveRemoteHeadAsync({ repoPath = '', branch = '' } = {}) {
405
+ if (process.env.DSH_GIT_PUSH_OFFLINE === '1') return { ok: false, sha: '', via: 'offline' };
406
+ const origin = (await runGitAsync(['remote', 'get-url', 'origin'], { cwd: repoPath })).stdout;
407
+ const pr = parseGithubOwnerRepo(origin);
408
+ const target = branch || (await runGitAsync(['branch', '--show-current'], { cwd: repoPath })).stdout;
409
+ if (!pr || !target) return { ok: false, sha: '' };
410
+ const sshUrl = sshUrlOf(pr);
411
+ const known = knownHostsPath();
412
+ const LS_TIMEOUT = 8_000;
413
+ let tried = 0;
414
+ for (const { keyPath, kind } of resolveSshKeys()) {
415
+ if (tried >= 2) break; // 最多试 2 个 key,避免多 key 串行放大耗时
416
+ tried += 1;
417
+ const sshCmd = buildLsRemoteSshCmd(keyPath, known);
418
+ const r = await runGitAsync(['ls-remote', sshUrl, `${REFS_HEADS_PREFIX}${target}`], { cwd: repoPath, env: { GIT_SSH_COMMAND: sshCmd }, timeoutMs: LS_TIMEOUT });
419
+ if (r.ok) {
420
+ const sha = (r.stdout || '').trim().split(/\s+/)[0] || '';
421
+ if (sha) return { ok: true, sha, via: kind };
422
+ }
423
+ }
424
+ const lr = await runGitAsync(['ls-remote', rr.remote || 'origin', `${REFS_HEADS_PREFIX}${target}`], { cwd: repoPath, timeoutMs: LS_TIMEOUT });
425
+ if (lr.ok) {
426
+ const sha = (lr.stdout || '').trim().split(/\s+/)[0] || '';
427
+ if (sha) return { ok: true, sha, via: 'origin' };
428
+ }
429
+ return { ok: false, sha: '' };
430
+ }
@@ -0,0 +1,35 @@
1
+ // dsh-git-push — 远端可见性解析(统一收口)
2
+ //
3
+ // 抽出原因:同一职责(可见性判定)此前在
4
+ // push.js 与 commit-push.js 各写一份,违反「同一职责单一入口」的设计,故抽成独立模块。
5
+ //
6
+ // 为什么独立成模块:可见性判定有**两个消费方**,此前各自实现(`resolveToken` +
7
+ // `detectRepoVisibility` 两处复制)会造成口径漂移(token 来源、探测失败兜底不一致):
8
+ // ① `lib/git/push.js` —— 私有库敏感文件豁免(private → 只扫描报告、不写 .gitignore)
9
+ // ② `lib/commit-push.js` —— 审计门禁豁免(private → 审计只报告不拦截)
10
+ // 统一走本入口后,两处拿到同一形状、同一兜底口径。
11
+ import { detectRepoVisibility } from './api.js';
12
+ import { resolveToken } from './credentials.js';
13
+
14
+ // 解析仓库远端可见性(统一收口)。
15
+ //
16
+ // 兜底口径:token 缺失 / 非 GitHub origin / API 失败 → 一律 `unknown`
17
+ // (调用方对 unknown 按保守处理:push 不豁免、审计门禁仍拦截)。
18
+ // 边界:resolveToken 自身抛错也吞成「无 token」(探测失败不该中断调用方流程)。
19
+ //
20
+ // @param {string} repoPath 仓库绝对路径
21
+ // @param {string} [token] 显式 token(缺省按仓库解析:仓库 token 文件 → 插件配置)
22
+ // @returns {Promise<{visibility: 'private'|'public'|'unknown', owner?: string, repo?: string, reason?: string}>}
23
+ // 可见性结果;`unknown` 时带 `reason` 说明原因
24
+ export async function resolveRepoVisibility(repoPath, token = '') {
25
+ let tok = token;
26
+ if (!tok) {
27
+ try { tok = resolveToken({ repoPath }).token; } catch { tok = ''; }
28
+ }
29
+ if (!tok) return { visibility: 'unknown', reason: '无可用 token' };
30
+ try {
31
+ return await detectRepoVisibility({ repoPath, token: tok });
32
+ } catch (e) {
33
+ return { visibility: 'unknown', reason: String((e && e.message) || e) };
34
+ }
35
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * 浅包装 git(最小版)——自动注入插件凭据,参数与 git 完全一致。
3
+ *
4
+ * 用法:git-sluice git <任意 git 参数>(例:git-sluice git pull / git clone owner/repo)
5
+ * 凭据自动注入(无需调用方传 token/私钥参数):
6
+ * · SSH 通道:GIT_SSH_COMMAND 指向插件私钥(与 git_cred_env 同口径:路径直通、私钥明文不经手)
7
+ * · HTTPS 通道:GIT_ASKPASS 指向 git-askpass.sh(从 config.json 读 token 回显)
8
+ */
9
+
10
+ import { execFileSync } from 'node:child_process';
11
+ import { buildCredEnv } from './cred-env.js';
12
+ import { resolveGitBin, GIT_MISSING_MSG, GIT_GLOBAL_ARGS } from './exec.js';
13
+ import { mirrorGitConfigEnv } from './endpoints.js';
14
+
15
+ /** 组装注入凭据后的 git 环境(在 process.env 基础上叠加插件凭据通道)。 */
16
+ export function buildWrappedGitEnv({ workspaceRoot = '' } = {}) {
17
+ const env = { ...process.env };
18
+ const cred = buildCredEnv({ workspaceRoot });
19
+ if (cred.ssh?.keyPath) {
20
+ // 与 cred-env 的 buildSshEnvPrefix 同口径(443 端口 + IdentitiesOnly + accept-new)
21
+ env.GIT_SSH_COMMAND = `ssh -i '${cred.ssh.keyPath}' -p 443 -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5`;
22
+ }
23
+ if (cred.https?.askpass) {
24
+ env.GIT_ASKPASS = cred.https.askpass;
25
+ env.GIT_TERMINAL_PROMPT = '0';
26
+ }
27
+ // 可选快通道:git 原生 url.<base>.insteadOf 改写 github https 访问。
28
+ // 口径与实现统一收口在 endpoints.js(默认关;api.github.com 不走镜像)。
29
+ mirrorGitConfigEnv(env);
30
+ return env;
31
+ }
32
+
33
+ /** 透传执行 git(参数原样传给 git,凭据自动注入;stdio 直连调用方)。 */
34
+ export function runWrappedGit(args = [], { workspaceRoot = '' } = {}) {
35
+ const env = buildWrappedGitEnv({ workspaceRoot });
36
+ // 显式解析 git 可执行文件:服务用户的 PATH 里往往没有 git(见 exec.js resolveGitBin 说明)
37
+ const bin = resolveGitBin();
38
+ if (!bin) { console.error(GIT_MISSING_MSG); return { ok: false, status: 127 }; }
39
+ try {
40
+ // 与 runGit 同口径带上 GIT_GLOBAL_ARGS(safe.directory=* 等),避免透传通道
41
+ // 在「仓库属主 ≠ 当前用户」时被 git 以 dubious ownership 拒绝
42
+ execFileSync(bin, GIT_GLOBAL_ARGS.concat(args), { stdio: 'inherit', env });
43
+ return { ok: true, status: 0 };
44
+ } catch (e) {
45
+ return { ok: false, status: typeof e.status === 'number' ? e.status : 1 };
46
+ }
47
+ }
48
+
49
+ /**
50
+ * 捕获输出的透传执行(工具调用用:返回 stdout/stderr 文本,AI 直接读结果)。
51
+ * 与 runWrappedGit 同凭据注入(SSH 私钥 / HTTPS askpass),不直连 stdio。
52
+ */
53
+ export function runWrappedGitCapture(args = [], { workspaceRoot = '' } = {}) {
54
+ const env = buildWrappedGitEnv({ workspaceRoot });
55
+ const bin = resolveGitBin();
56
+ if (!bin) return { ok: false, status: 127, stdout: '', stderr: GIT_MISSING_MSG };
57
+ try {
58
+ const r = execFileSync(bin, GIT_GLOBAL_ARGS.concat(args), { env, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 });
59
+ return { ok: true, status: 0, stdout: String(r), stderr: '' };
60
+ } catch (e) {
61
+ return {
62
+ ok: false,
63
+ status: typeof e.status === 'number' ? e.status : 1,
64
+ stdout: String(e.stdout || ''),
65
+ stderr: String(e.stderr || e.message || ''),
66
+ };
67
+ }
68
+ }