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,41 @@
1
+ /**
2
+ * Git 操作层 · 统一出口
3
+ *
4
+ * 分层位置:本目录是「执行层」——真正调 git / GitHub API / 读写凭据的地方。
5
+ * 审计与评分在 lib/audit/ · lib/score/,规则在 lib/audit-rules/,本目录不管审计。
6
+ *
7
+ * 模块划分(按「对外做什么」而非按类型):
8
+ * exec.js 进程执行(runGit/gitRaw,含超时与错误规整)
9
+ * config.js 插件根目录定位与开发者要求清单读取
10
+ * credentials.js 凭据解析与落盘(token / SSH 公钥 / 密钥生成)
11
+ * api.js GitHub REST 调用(含 owner/repo 解析、可见性探测)
12
+ * sensitive.js 提交前敏感信息扫描
13
+ * ignore.js .gitignore 兜底与产物忽略
14
+ * transport.js 推送通道(SSH / API)/ 远端 head 查询 / blob 上传
15
+ * push.js 提交推送编排(commitAndPush 及推送后增强)
16
+ * clone.js 经 API 克隆
17
+ * remote.js 远端仓库的创建与可见性切换
18
+ * repos.js 仓库扫描与展示(脱敏)
19
+ * account.js GitHub 账号校验与结果格式化
20
+ *
21
+ * 本文件只做再导出:调用方继续 `from './git/index.js'` 导入,路径稳定。
22
+ */
23
+
24
+ export { runGit, runGitAsync, gitRaw } from './exec.js';
25
+ export { PLUGIN_ROOT, loadRequirements } from './config.js';
26
+ export { credentialsDir, resolveSshKey, resolveToken, maskToken, readSshPub, persistGithubToken, persistSshPub, persistNpmToken, readNpmToken, generateSshKey } from './credentials.js';
27
+ export { GH_API, githubFetch, parseGithubOwnerRepo, isBadCredentials, detectRepoVisibility } from './api.js';
28
+ export { resolveRepoVisibility } from './visibility.js';
29
+ export { scanSensitiveFiles } from './sensitive.js';
30
+ export { DEFAULT_IGNORE_PATTERNS, ensureGitignore } from './ignore.js';
31
+ export { fetchRemoteHeads, dispatchPush, pushViaSsh, pushViaApi, sshReason, isNonFastForward, liveRemoteHead, liveRemoteHeadAsync } from './transport.js';
32
+ export { readmeCheckHint, commitAndPush, pushCurrentBranch } from './push.js';
33
+ export { cloneViaApi, previewClone, resolveMaxCloneFileMB, isPartialCloneDir } from './clone.js';
34
+ export { ensureRemoteRepo, setVisibility } from './remote.js';
35
+ export { scanRepos, scanReposAsync, collectRepoPaths, describeRepo, describeRepoAsync, maskRemoteUrl } from './repos.js';
36
+ export { browseDir } from './browse.js';
37
+ export { listCloudRepos } from './cloud.js';
38
+ export { checkGithubAccount, formatGithubAccountBlock, fetchApiQuota } from './account.js';
39
+ export { writeAccountStatusFromResult, accountStatusFile, readAccountStatus, refreshAccountStatus, buildAccountStatus, updateAccountStatusQuota } from './account-status.js';
40
+ export { locateRepoIndex, readRepoIndexMap, indexEntryForRepo, buildRepoIndex, maintainRepoIndex, updateRepoIndex, mergeCloudReposIntoIndex, updateRepoRemoteStateInIndex } from './repo-index.js';
41
+ export { scanRunner, runScan, waitScanDelta, readScanLive, resetScanLive, scanLiveFile, stopScanWatch } from './scan-runner.js';
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Git 执行层 · module-splitter 子进程调用(CLI 与工具共用)
3
+ *
4
+ * 为什么单独成文件:cli.mjs cmdModuleSplitter 与 lib/app/tool-call.js
5
+ * module_splitter case 各写了一份 python3 spawn 逻辑(参数拼装/ENOENT/错误截断/
6
+ * 脚本路径解析)——同一实现两份,改一处漏一处。抽到本模块后两处只做「传参 + 格式化输出」。
7
+ *
8
+ * 行为约定:参数数组 spawn(防注入);脚本相对插件根解析;python3 缺失返回明确的
9
+ * ENOENT 文案(module-splitter 依赖 python3 标准库)。
10
+ */
11
+
12
+ import { spawnSync } from 'node:child_process';
13
+ import { fileURLToPath } from 'node:url';
14
+
15
+ /** module-splitter 子命令白名单。 */
16
+ export const SPLITTER_SUBCOMMANDS = ['analyze', 'split', 'verify'];
17
+ /** 子进程最大等待时长(ms)。 */
18
+ export const SPLITTER_TIMEOUT_MS = 120_000;
19
+ /** 报错截断长度。 */
20
+ export const SPLITTER_ERR_MAX_LEN = 800;
21
+
22
+ /**
23
+ * 调 scripts/module-splitter.py(python3 零依赖)。
24
+ * @param {{sub:string, target:string, dryRun?:boolean}} p sub=analyze|split|verify;target=文件/plan 路径
25
+ * @returns {{ok:boolean, error?:string, status?:number, output?:string, sub?:string, target?:string}}
26
+ * ok:true 时 output=stdout;失败 ok:false 且 error 可读。
27
+ */
28
+ export function runModuleSplitter({ sub = '', target = '', dryRun = false } = {}) {
29
+ if (!SPLITTER_SUBCOMMANDS.includes(sub)) {
30
+ return { ok: false, error: `module-splitter 子命令应为 ${SPLITTER_SUBCOMMANDS.join('|')}(得「${sub || '(空)'}」)` };
31
+ }
32
+ if (!target) {
33
+ return { ok: false, error: 'module-splitter 需要目标参数:analyze <file.js> / split <plan.json> / verify <plan.json>' };
34
+ }
35
+ const script = fileURLToPath(new URL('../../scripts/module-splitter.py', import.meta.url));
36
+ const argv = [script, sub, target];
37
+ if (dryRun) argv.push('--dry-run');
38
+ const r = spawnSync('python3', argv, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, timeout: SPLITTER_TIMEOUT_MS });
39
+ if (r.error) {
40
+ const msg = r.error.code === 'ENOENT' ? 'python3 不可用(module-splitter 依赖 python3 标准库)' : `执行失败: ${r.error.message}`;
41
+ return { ok: false, error: msg };
42
+ }
43
+ if (r.status !== 0) {
44
+ return { ok: false, status: r.status, error: String(r.stderr || r.stdout || '执行失败').trim().slice(0, SPLITTER_ERR_MAX_LEN) };
45
+ }
46
+ return { ok: true, sub, target, dryRun, output: String(r.stdout || '') };
47
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * dsh-git-push — 推送成功后增强(D15 拆出的小模块)
3
+ *
4
+ * Git Data API(api.github.com)推送成功后,本地 git 无法自动感知远端状态,
5
+ * 本模块补齐三件事:
6
+ * 1) updateRemoteTrackingRef — 用本地 HEAD sha 内容等价代理写入 refs/remotes/origin/<branch>
7
+ * (API 在远端新建的 commit sha 本地无对象,update-ref 报 nonexistent object;
8
+ * 推送内容与本地 HEAD tree 完全等价,故用本地 HEAD sha 代理,git log origin/<branch> 可看远端内容)
9
+ * 2) ensureAuxSshRemote — 确保辅助 SSH remote(github-ssh → ssh://git@ssh.github.com:443/owner/repo.git)
10
+ * 存在,支持标准 git fetch/pull
11
+ * 3) autoTagDSHProject — dsh- 前缀项目推送成功后自动打 v<version> tag(便于官方发现)
12
+ *
13
+ * 全部失败不阻断推送成功(结果记入 result.push.remoteRef / .auxRemote / result.autoTag)。
14
+ */
15
+ import { existsSync, readFileSync } from 'node:fs';
16
+ import { basename, join } from 'node:path';
17
+
18
+ import { runGit, githubFetch, parseGithubOwnerRepo } from './index.js';
19
+
20
+ /** 读仓库 package.json version(无 package.json / 解析失败 → '')。 */
21
+ export function readPkgVersion(repoPath) {
22
+ try {
23
+ const pkgPath = join(repoPath, 'package.json');
24
+ if (!existsSync(pkgPath)) return '';
25
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
26
+ return String(pkg.version || '').trim();
27
+ } catch { return ''; }
28
+ }
29
+
30
+ /**
31
+ * 维护 remote-tracking ref:update-ref refs/remotes/origin/<branch> = <refTarget>。
32
+ * @returns {string} 人类可读结果(成功= ref 摘要;失败= 错误说明),不抛异常
33
+ */
34
+ export function updateRemoteTrackingRef(repoPath, branchRef, refTarget) {
35
+ try {
36
+ const upd = runGit(['update-ref', `refs/remotes/origin/${branchRef}`, refTarget], { cwd: repoPath });
37
+ return upd.ok
38
+ ? `refs/remotes/origin/${branchRef} = ${String(refTarget).slice(0, 7)}`
39
+ : `update-ref 失败: ${(upd.stderr || '').trim().slice(0, 120)}`;
40
+ } catch (e) {
41
+ return `update-ref 异常: ${e?.message || e}`;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * 确保辅助 SSH remote(github-ssh)存在。同名但指向不同 URL 时不覆盖(用户可能自设过),仅记录。
47
+ * 结果写入 result.push.auxRemote(v1 语义)。
48
+ */
49
+ export function ensureAuxSshRemote(repoPath, owner, repo, result = {}) {
50
+ const AUX = 'github-ssh';
51
+ if (!owner || !repo) return;
52
+ const pushSlot = result.push ?? (result.push = {});
53
+ const url = `ssh://git@ssh.github.com:443/${owner}/${repo}.git`;
54
+ const existing = runGit(['remote', 'get-url', AUX], { cwd: repoPath });
55
+ if (existing.ok && existing.stdout.trim()) {
56
+ pushSlot.auxRemote = existing.stdout.trim() !== url
57
+ ? `${AUX} 已存在(${existing.stdout.trim()})`
58
+ : `${AUX} 已就绪`;
59
+ return;
60
+ }
61
+ const addResult = runGit(['remote', 'add', AUX, url], { cwd: repoPath });
62
+ pushSlot.auxRemote = addResult.ok
63
+ ? `${AUX} → ${url}`
64
+ : `${AUX} 添加失败: ${(addResult.stderr || '').trim().slice(0, 120)}`;
65
+ }
66
+
67
+ /**
68
+ * dsh- 前缀项目自动打 tag(起全部走 api.github.com):
69
+ * 打 v<version> tag 到 commitSha。repo 名非 dsh- 前缀 / 无版本 / 无 sha / 无 token / 无 origin → 跳过。
70
+ * @returns {Promise<{ok, skipped?, tag?, reason?, error?}>}
71
+ */
72
+ export async function autoTagDSHProject({ repoPath = '', version = '', commitSha = '', owner = '', repo = '', token = '' } = {}) {
73
+ try {
74
+ const repoName = repo || basename(repoPath);
75
+ if (!/^dsh-/i.test(repoName)) return { ok: false, skipped: 'not-dsh-prefix', reason: repoName };
76
+ const tag = 'v' + (version || readPkgVersion(repoPath) || '').replace(/^v/i, '');
77
+ if (!tag || tag === 'v') return { ok: false, skipped: 'no-version' };
78
+ if (!commitSha) return { ok: false, skipped: 'no-commit-sha' };
79
+ if (!token) return { ok: false, skipped: 'no-token' };
80
+ const originUrl = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }).stdout;
81
+ const parsed = parseGithubOwnerRepo(originUrl);
82
+ const ownerName = owner || parsed?.owner || '';
83
+ const repoName2 = repo || parsed?.repo || '';
84
+ if (!ownerName || !repoName2) return { ok: false, skipped: 'no-origin' };
85
+ // API 超时(毫秒):tag 存在性探测 + 创建共用
86
+ const tagTimeoutMs = 30_000;
87
+ const exists = await githubFetch(`/repos/${ownerName}/${repoName2}/git/ref/tags/${tag}`, { token, timeout: tagTimeoutMs });
88
+ if (exists.status === 200) return { ok: false, skipped: 'tag-exists', tag };
89
+ const tagRes = await githubFetch(`/repos/${ownerName}/${repoName2}/git/refs`, {
90
+ token, method: 'POST', body: { ref: `refs/tags/${tag}`, sha: commitSha }, timeout: tagTimeoutMs,
91
+ });
92
+ if (tagRes.status === 201) return { ok: true, tag };
93
+ if (tagRes.status === 422) {
94
+ if (/already exists/i.test(tagRes.json?.message || '')) return { ok: false, skipped: 'tag-exists', tag };
95
+ return { ok: false, skipped: '422', tag, error: tagRes.json?.message || tagRes.status };
96
+ }
97
+ return { ok: false, skipped: String(tagRes.status), tag, error: tagRes.error || ('GitHub API ' + tagRes.status) };
98
+ } catch (e) {
99
+ return { ok: false, skipped: 'error', error: String(e?.message || e) };
100
+ }
101
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Git 执行层 · 推送失败的**结构化诊断**(把「事实」与「推断」分开)。
3
+ *
4
+ * 为什么需要这个模块(实测缺陷):
5
+ * 推送失败时插件此前只返回一句自由文本 `reason`(例如
6
+ * `id_rsa: ERROR: Repository not found. fatal: Could not read from remote repository. Please make
7
+ * sure you have the correct access rights and the repository exists.`),
8
+ * 读它的人(AI 或人都一样)只能**脑补** ✗ —— 实测就被脑补成「上游仓库不存在」,
9
+ * 而这句话在 Git/GitHub 语义下**根本不足以支撑该结论**:
10
+ *
11
+ * ⚠️ 关键事实:GitHub 对「仓库不存在」与「当前凭据没有访问权限」**故意返回同一句**
12
+ * `Repository not found.`(私有库不泄露存在性)⇒ 只能得出
13
+ * 「**不存在 或 无权限,二者不可区分**」,**不能**断言「不存在」。
14
+ *
15
+ * 本模块把失败拆成三个层次,杜绝过度推断:
16
+ * · code —— 机器可判的分类码(枚举,调用方可 switch)
17
+ * · fact —— **原文证据**(远端/ git 到底说了什么,不做解释)
18
+ * · inference —— 人话解释 + `confidence`(当分类本身有歧义时,明确写「不可区分」并降置信度)
19
+ * · nextSteps —— 可执行的下一步(配 token / 校验公钥 / 核对仓库名或权限 …)
20
+ *
21
+ * 设计约束:
22
+ * · 纯函数、零 IO(可单测、可在任意通道复用);
23
+ * · 规则按**真实样本**写(见 test/test-push-diagnose.mjs 的样本表),不凭想象加规则;
24
+ * · 分类器**只做归类**,不产生「不存在」这类否定性断言(由调用方按 code 措辞)。
25
+ */
26
+
27
+ /** 失败分类码 → 人话解释(inference 的基底)。 */
28
+ export const PUSH_FAILURE_CODES = {
29
+ 'no-remote': '本地没有可用的 GitHub remote(或 remote 指向的仓库与目标不一致)',
30
+ 'auth-missing': '本机没有可用于该远端的凭据(没配 token / https 无凭据 / SSH 未启用密钥)',
31
+ 'auth-denied': '凭据存在但被远端拒绝(SSH 公钥未登记到该账号,或 token 无效/过期/无该仓库权限)',
32
+ 'repo-not-found-or-no-access': '远端拒绝了这次推送:仓库**不存在**,**或** 当前凭据**没有访问权限**'
33
+ + '(GitHub 对两种情况返回同一句,二者不可区分 ⇒ 不能据此断定「仓库不存在」)',
34
+ dns: '域名解析失败(DNS 或网关问题)',
35
+ network: '网络不可达或超时(连接被拒 / 超时 / 路由不通)',
36
+ 'host-key': 'SSH 主机密钥校验失败(known_hosts 缺少该主机,或远端指纹变了)',
37
+ diverged: '本地与远端已分叉(non-fast-forward):远端有本地没有的提交',
38
+ protected: '目标分支受保护或被远端策略拒绝',
39
+ 'rate-limited': '被远端限流(429 / rate limit)',
40
+ 'server-error': '远端服务端错误(5xx / RPC failed)',
41
+ unknown: '未能归类(现有信息不足,需要完整 stderr 才能判断)',
42
+ };
43
+
44
+ /** 分类 → 下一步建议(可执行、少废话)。 */
45
+ const NEXT_STEPS = {
46
+ 'no-remote': ['用 git_remote_create 建/复用远端仓库并把 origin 指过去', '或手动 git remote add origin <ssh://git@ssh.github.com:443/<owner>/<repo>.git>'],
47
+ 'auth-missing': ['在插件「设置 → 凭据与密钥」配 GitHub token(或改用 SSH 形态 remote)', '调用 git_account_check 确认凭据可用'],
48
+ 'auth-denied': ['用 git_account_check 看当前账号与公钥指纹,确认这把公钥已登记到该账号', '确认 token 未过期且对该仓库有权限(私有库需授权)'],
49
+ 'repo-not-found-or-no-access': [
50
+ '核对 owner/repo 拼写(本机可用 git remote -v 看实际地址)',
51
+ '确认当前账号对该仓库有访问权限(私有库需要被授权)',
52
+ '用 git_account_check 看登录账号是否是仓库所有者',
53
+ '⚠️ 不要据这句话断定「仓库不存在」——它与「无权限」不可区分',
54
+ ],
55
+ dns: ['检查 DNS/网关:curl -I --connect-timeout 4 https://api.github.com'],
56
+ network: ['测连通性:curl -I https://api.github.com 与 ssh -p 443 -T git@ssh.github.com'],
57
+ 'host-key': ['先手动验证主机:ssh -p 443 -T git@ssh.github.com(插件推送用临时 known_hosts)'],
58
+ diverged: ['先 git fetch 并整合远端提交再推;确认要覆盖远端历史时再显式 force(谨慎)'],
59
+ protected: ['确认分支保护规则(是否禁止直接推 main)', '或改推到特性分支再走 PR'],
60
+ 'rate-limited': ['稍后重试(限流窗口通常几分钟)'],
61
+ 'server-error': ['稍后重试;持续失败查 GitHub Status'],
62
+ unknown: ['保留完整 stderr 人工判断;先确认到远端的连通性(api.github.com / ssh.github.com:443)'],
63
+ };
64
+
65
+ /** 分类码 → 置信度。带歧义的分类**必须**降级为 low(防过度推断)。 */
66
+ const CONFIDENCE = {
67
+ 'repo-not-found-or-no-access': 'low',
68
+ unknown: 'low',
69
+ };
70
+
71
+ /** 规则表:命中即归类(顺序敏感:越具体的越靠前)。 */
72
+ const RULES = [
73
+ // ① 无凭据(git/curl 拿不到用户名密码)——这是「事实」,不是「仓库不存在」
74
+ ['auth-missing', /could not read Username|could not read Password|terminal prompts disabled|fatal: Authentication failed for 'https/i],
75
+ // ② SSH 主机密钥
76
+ ['host-key', /host key verification failed|remote host identification has changed|no matching host key/i],
77
+ // ③ 凭据存在但被拒(公钥未登记 / token 无效)
78
+ ['auth-denied', /permission denied \(publickey\)|publickey|invalid username or (password|token)|bad credentials|401 unauthorized/i],
79
+ // ④ 仓库不存在**或**无权限(GitHub 同一句)——绝不断言「不存在」
80
+ ['repo-not-found-or-no-access', /repository not found|repository .{0,40}not found|does not exist|not accessible|could not read from remote repository|remote: not found|403 forbidden/i],
81
+ // ⑤ DNS / 网络
82
+ ['dns', /could not resolve host|temporary failure in name resolution|getaddrinfo|name or service not known/i],
83
+ ['network', /connection timed out|connection refused|network is unreachable|operation timed out|failed to connect|connection reset|no route to host/i],
84
+ // ⑥ 分叉 / 保护分支 / 限流 / 服务端
85
+ ['diverged', /non-fast-forward|fetch first|updates were rejected|远程仓库包含您本地尚不存在的提交/i],
86
+ ['protected', /protected branch|gh006|refusing to allow|push declined due to repository rule/i],
87
+ ['rate-limited', /\b429\b|rate limit|secondary rate/i],
88
+ ['server-error', /internal server error|rpc failed|remote end hung up|\b50[0-9]\b|\b5\d\d\b/i],
89
+ ];
90
+
91
+ /** 由 HTTP 状态码辅助归类(API 通道用;文本规则已含 401/403 时以文本优先)。 */
92
+ function byHttpStatus(status) {
93
+ const s = Number(status);
94
+ if (!Number.isFinite(s) || s < 400) return null;
95
+ if (s === 401) return 'auth-denied';
96
+ if (s === 403) return 'protected';
97
+ if (s === 404) return 'repo-not-found-or-no-access';
98
+ if (s === 429) return 'rate-limited';
99
+ if (s >= 500) return 'server-error';
100
+ return null;
101
+ }
102
+
103
+ /**
104
+ * 归类推送失败。
105
+ * @param {string} text 失败原文(git stderr / API message / 组合 reason)
106
+ * @param {{httpStatus?:number, method?:string, noRemote?:boolean}} [opts]
107
+ * @returns {{code:string, fact:string, inference:string, confidence:'high'|'low', nextSteps:string[]}}
108
+ */
109
+ export function classifyPushFailure(text = '', opts = {}) {
110
+ const raw = String(text || '').replace(/\s+/g, ' ').trim();
111
+ let code = null;
112
+ // 显式标记优先(调用方已知「没有可用 remote」,无需从文本猜)
113
+ if (opts.noRemote === true) code = 'no-remote';
114
+ if (!code) {
115
+ for (const [c, re] of RULES) {
116
+ if (re.test(raw)) { code = c; break; }
117
+ }
118
+ }
119
+ if (!code && opts.httpStatus !== undefined && opts.httpStatus !== null) code = byHttpStatus(opts.httpStatus);
120
+ if (!code) code = 'unknown';
121
+ const confidence = CONFIDENCE[code] || 'high';
122
+ return {
123
+ code,
124
+ fact: raw.slice(0, 400),
125
+ inference: PUSH_FAILURE_CODES[code] || PUSH_FAILURE_CODES.unknown,
126
+ confidence,
127
+ nextSteps: NEXT_STEPS[code] || NEXT_STEPS.unknown,
128
+ };
129
+ }
130
+
131
+ /**
132
+ * 把诊断渲染成一行可读文本(工具回执 / 日志用)。
133
+ * 措辞纪律:`fact` 在前(原文证据),`inference` 只作解释;带歧义的分类必须带「不可区分」提示。
134
+ * @param {object} dg classifyPushFailure 的返回
135
+ * @returns {string}
136
+ */
137
+ export function describePushDiagnosis(dg = {}) {
138
+ const code = dg.code || 'unknown';
139
+ const conf = dg.confidence === 'low' ? '(推断,置信度低)' : '(依据充分)';
140
+ const steps = Array.isArray(dg.nextSteps) && dg.nextSteps.length ? `|下一步:${dg.nextSteps[0]}` : '';
141
+ return `分类 ${code}${conf}:${dg.inference || ''}${steps}`;
142
+ }