dsh-git-push 0.0.0-stage → 2.8.6

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 (279) hide show
  1. package/.auditignore +30 -0
  2. package/.gitignore +39 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1486 -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 +266 -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 +192 -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 +672 -0
  32. package/lib/app/tools.js +34 -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 +215 -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 +137 -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 +148 -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 +476 -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 +171 -0
  190. package/lib/npm/registry.js +168 -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 +196 -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/cpu-sample.mjs +188 -0
  231. package/scripts/doc-drift.mjs +200 -0
  232. package/scripts/doc-func.mjs +212 -0
  233. package/scripts/doc-tree.mjs +456 -0
  234. package/scripts/doc-version.mjs +220 -0
  235. package/scripts/frontend-preview-check.mjs +124 -0
  236. package/scripts/hot-path-probe-cjs.cjs +71 -0
  237. package/scripts/hot-path-probe-fs-shim.mjs +28 -0
  238. package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
  239. package/scripts/hot-path-probe.mjs +153 -0
  240. package/scripts/module-splitter.py +800 -0
  241. package/scripts/platform-scan.mjs +168 -0
  242. package/scripts/preview-gen.mjs +489 -0
  243. package/scripts/preview-local-runner.mjs +55 -0
  244. package/scripts/preview-server-direct.mjs +116 -0
  245. package/scripts/preview-server.mjs +305 -0
  246. package/scripts/preview-slot-data.mjs +123 -0
  247. package/scripts/probe-recheck.mjs +47 -0
  248. package/scripts/readme-gen.mjs +268 -0
  249. package/scripts/rename-locator.mjs +97 -0
  250. package/scripts/rule-switch.mjs +97 -0
  251. package/scripts/rules-solo-audit.mjs +173 -0
  252. package/scripts/scan-file-io.mjs +713 -0
  253. package/scripts/scan-hardcoded-paths.mjs +125 -0
  254. package/scripts/scan-repos.mjs +167 -0
  255. package/scripts/scan-version.mjs +122 -0
  256. package/scripts/scrub-user-wording.mjs +420 -0
  257. package/scripts/symbol-index.mjs +85 -0
  258. package/scripts/sync-plugin-install.mjs +223 -0
  259. package/scripts/sync-plugin.mjs +279 -0
  260. package/scripts/verify-prestep.mjs +100 -0
  261. package/skills/dev/audit-rule-authoring.md +58 -0
  262. package/skills/dev/dsh-git-push.md +323 -0
  263. package/skills/dev/git-push-live-fix.md +45 -0
  264. package/skills/dsh-repo-index.md +35 -0
  265. package/skills/guide/guide-audit.md +167 -0
  266. package/skills/guide/guide-cli-scripts.md +104 -0
  267. package/skills/guide/guide-clone-repos.md +173 -0
  268. package/skills/guide/guide-commit-push.md +156 -0
  269. package/skills/guide/guide-inject-ui.md +166 -0
  270. package/skills/guide/guide-slash-completion.md +118 -0
  271. package/skills/workflow/README.md +21 -0
  272. package/skills/workflow/git-commit-discipline.md +68 -0
  273. package/skills/workflow/git-project-startup.md +85 -0
  274. package/skills/workflow/git-rebuild-process.md +57 -0
  275. package/skills/workflow/github-operations.md +91 -0
  276. package/skills/workflow/readme-sync-git-md.md +28 -0
  277. package/skills/workflow/task-completion-report.md +73 -0
  278. package/skills/workflow/tool-json-add-ask.md +35 -0
  279. package/skills/workflow/versioning-rule.md +211 -0
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Git 执行层 · 远端仓库管理
3
+ *
4
+ * 职责:远端仓库创建(不存在则建,默认 private)与可见性切换。
5
+ */
6
+
7
+ import { existsSync } from 'node:fs';
8
+ import { basename, join } from 'node:path';
9
+ import { githubFetch } from './api.js';
10
+ import { resolveToken } from './credentials.js';
11
+ import { runGit } from './exec.js';
12
+
13
+ /* ───────── 远端仓库常量 ───────── */
14
+ const USER_CHECK_TIMEOUT_MS = 15_000; // 建仓前 /user 校验超时
15
+ /** 写进 origin 的 git 远端形态前缀(与插件自身仓库一致;git 与两处解析器都认)。 */
16
+ const GH_WEB = 'https://github.com';
17
+
18
+ /** origin 是否是「不可用于 git 的 API 形态 URL」(REST 端点,不是 git remote)。 */
19
+ function isApiFormOrigin(url) {
20
+ return /^https?:\/\/api\.github\.com\/repos\//i.test(String(url || '').trim());
21
+ }
22
+
23
+ /**
24
+ * 让本地仓库的 origin 指向**可用的 git URL**。
25
+ *
26
+ * 为什么单独抽出来(2026-10-09 缺陷修复,任务.md B5):
27
+ * 原实现把 origin 写成 `${GH_API}/repos/<owner>/<name>`(即 `https://api.github.com/repos/…`)——
28
+ * 那是 **REST API 端点**,不是 git remote:`git push/fetch origin` 必然失败,
29
+ * 且随后 `git_commit_push` 的推送核验会报
30
+ * 「推送未落地:远端查不到分支 master(两条通道一致:API HTTP 404,ls-remote 无该分支)」。
31
+ * 实测(新建插件 dsh-file-path-tracker):把 origin 改成 SSH 形态后一次推送成功。
32
+ * 现统一写成 `https://github.com/<owner>/<name>`(git 可用,`parseOwnerRepoFromRemote` 与
33
+ * `parseGithubOwnerRepo` 都能解析),并**自愈**:origin 已存在但仍是 API 形态时改回 git 形态
34
+ * —— 这样用旧版建过仓的仓库不用手工修。
35
+ * @returns {{action:'add'|'repair'|'keep', url:string, from?:string}}
36
+ */
37
+ function ensureUsableOrigin(repoPath, ownerName, name) {
38
+ const gitUrl = `${GH_WEB}/${ownerName}/${name}`;
39
+ const cur = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath });
40
+ if (!cur.ok) {
41
+ runGit(['remote', 'add', 'origin', gitUrl], { cwd: repoPath });
42
+ return { action: 'add', url: gitUrl };
43
+ }
44
+ const existing = String(cur.stdout || cur.stderr || '').trim();
45
+ if (isApiFormOrigin(existing)) {
46
+ runGit(['remote', 'set-url', 'origin', gitUrl], { cwd: repoPath });
47
+ return { action: 'repair', from: existing, url: gitUrl };
48
+ }
49
+ return { action: 'keep', url: existing };
50
+ }
51
+
52
+ /** 建仓(POST /user/repos)并设置 origin。dryRun 只探测不创建。 */
53
+ export async function ensureRemoteRepo({ repoPath = '', owner = '', visibility = 'private', dryRun = false, token = '' } = {}) {
54
+ const name = basename(repoPath || '');
55
+ if (!name) return { ok: false, error: '缺仓库路径' };
56
+ // 仓库名必须是 ASCII——前置拦截并**明确报错**,不做静默变形。
57
+ // 事故(用户实测):项目文件夹名含中文(「逆向-malang」)时,名字在 URL 构造/参数传递中
58
+ // 被拆掉,残余片段被当成选项式 token(`--malang`),建出来的远端名与预期完全不符,
59
+ // 而且因为「创建成功」返回 ok,用户直到查远端才发现。GitHub 仓库名本身也只允许
60
+ // ASCII(字母/数字/`.`/`_`/`-`),所以这里直接拒绝并给出改名示例,让用户改名后重试。
61
+ if (!/^[A-Za-z0-9._-]+$/.test(name)) {
62
+ return {
63
+ ok: false,
64
+ code: 'NON_ASCII_REPO_NAME',
65
+ error: `仓库名「${name}」含非 ASCII 字符——GitHub 仓库名只支持 ASCII(字母/数字/./_/-)。`
66
+ + '请把项目文件夹改成 ASCII 名后重试(例:逆向-malang → malang-reverse)。'
67
+ + '插件不自动改名,避免建出与预期不符的远端仓库。',
68
+ };
69
+ }
70
+ const vis = (visibility || 'private').toLowerCase() === 'public' ? 'public' : 'private';
71
+ const tok = token || resolveToken({ repoPath }).token;
72
+ if (!tok && !dryRun) return { ok: false, error: '无 token(插件 config.json 的 githubToken 键,或环境变量 DSH_GIT_PUSH_TOKEN)' };
73
+ // owner 缺省取 token 对应用户(GET /user)——保证 owner≠库名时同名检测与 origin 均正确
74
+ let ownerName = owner || '';
75
+ if (!ownerName) {
76
+ const me = await githubFetch('/user', { token: tok, timeout: USER_CHECK_TIMEOUT_MS });
77
+ if (me.status === 200 && me.json?.login) ownerName = me.json.login;
78
+ else if (dryRun) ownerName = name; // dry-run 无 token:占位 owner 继续模拟,不阻断
79
+ else return { ok: false, error: '无法确定 owner(传 owner 参数或提供有效 token)' };
80
+ }
81
+ const exists = await githubFetch(`/repos/${ownerName}/${name}`, { token: tok });
82
+ if (exists.status === 200) {
83
+ // 仓库已存在也要**确保 origin 可用**(原来这里直接 return,不碰 origin ⇒ 本地缺 origin 或
84
+ // 是旧版写下的 API 形态时会一直坏着)。
85
+ let originAction = 'skip';
86
+ if (repoPath && existsSync(join(repoPath, '.git'))) {
87
+ originAction = ensureUsableOrigin(repoPath, ownerName, name).action;
88
+ }
89
+ return { ok: true, exists: true, owner: ownerName, name, visibility: vis, reason: '已存在同名仓库', origin: `${GH_WEB}/${ownerName}/${name}`, originAction };
90
+ }
91
+ if (dryRun) return { ok: true, dryRun: true, wouldCreate: true, owner: ownerName, name, visibility: vis };
92
+ const created = await githubFetch('/user/repos', { token: tok, method: 'POST', body: { name, private: vis === 'private' } });
93
+ if (created.status !== 201) return { ok: false, error: created.json?.message || created.error || `创建失败: HTTP ${created.status}` };
94
+ let originInfo = { action: 'skip', url: `${GH_WEB}/${ownerName}/${name}` };
95
+ if (repoPath && existsSync(join(repoPath, '.git'))) {
96
+ originInfo = ensureUsableOrigin(repoPath, ownerName, name);
97
+ }
98
+ return { ok: true, created: true, owner: ownerName, name, visibility: vis, origin: originInfo.url, originAction: originInfo.action };
99
+ }
100
+
101
+ /** 从本地仓库 origin remote 解析 owner/repo(支持 api.github.com/repos/、github.com、ssh:// 三格式)。 */
102
+ export function parseOwnerRepoFromRemote(remoteUrl) {
103
+ const url = String(remoteUrl || '').trim();
104
+ let match = url.match(/api\.github\.com\/repos\/([^/\s]+)\/([^/\s]+?)(?:\.git)?$/);
105
+ if (match) return { owner: match[1], repo: match[2] };
106
+ match = url.match(/([^/\s:]+)\/([^/\s]+?)(?:\.git)?$/);
107
+ if (match && match[1] !== 'repos') return { owner: match[1], repo: match[2] };
108
+ return { owner: '', repo: '' };
109
+ }
110
+
111
+ /** 可见性切换(PATCH /repos/{owner}/{repo} {"private": bool})。repoPath 提供时从本地仓库 origin 解析 owner/repo。 */
112
+ export async function setVisibility({ owner = '', repo = '', visibility = '', token = '', repoPath = '' } = {}) {
113
+ const target = (visibility || '').toLowerCase();
114
+ if (!['public', 'private'].includes(target)) return { ok: false, error: 'visibility 必须为 public 或 private' };
115
+ // bugfix:git_set_visibility 工具传 repoPath(本地仓库路径)——从 origin remote 解析 owner/repo
116
+ if ((!owner || !repo) && repoPath) {
117
+ const cur = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath });
118
+ const parsed = parseOwnerRepoFromRemote(cur.stdout || cur.stderr || '');
119
+ owner = owner || parsed.owner;
120
+ repo = repo || parsed.repo;
121
+ }
122
+ if (!owner || !repo) return { ok: false, error: '缺 owner/repo' };
123
+ const tok = token || resolveToken({}).token;
124
+ if (!tok) return { ok: false, error: '无 token' };
125
+ const visRes = await githubFetch(`/repos/${owner}/${repo}`, { token: tok, method: 'PATCH', body: { private: target === 'private' } });
126
+ if (visRes.status !== 200) return { ok: false, error: visRes.json?.message || visRes.error || `HTTP ${visRes.status}` };
127
+ return { ok: true, owner, repo, visibility: visRes.json?.private ? 'private' : 'public', to: target };
128
+ }
@@ -0,0 +1,512 @@
1
+ /**
2
+ * dsh-git-push — dsh-repo-index 自动维护(由 v1 lib/repo-index.js 移植进 v2)。
3
+ *
4
+ * 功能:扫描 workspace 全部 git 仓库(含嵌套 .git)+ 本地目录,自动生成 dsh-repo-index.json
5
+ * (唯一权威源码索引),并在推送成功后重建同步(账号卡片本地扫描同时读取它做
6
+ * 「索引登记」标注——联动:即使本地仓库未设 remote/上游,也能显示它的 GitHub 归属)。
7
+ *
8
+ * 数据来源:
9
+ * - git remote URL → 仓库地址 + 恢复命令(公开 ssh clone / 私有 token clone)
10
+ * - GitHub API(token) → 可见性(public/private),查不到回退手工标注/未知
11
+ * - 各项目 package.json dsh.skills + skills/*.md frontmatter → skills 字段
12
+ * - workspace 顶层无 remote 的目录 → localOnly 字段
13
+ *
14
+ * 写入目标:插件配置目录 $DSH_HOME/git-push/dsh-repo-index.json(credentialsDir,
15
+ * 修正:原工作区 dsh-git-push-User/<owner>/ 同级仓已废除,索引收敛插件
16
+ * 自持、不入 git;与 dsh-repo-index skill 权威位置一致)。失败全部静默降级,
17
+ * 不阻塞扫描/推送。
18
+ */
19
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from 'node:fs';
20
+ import { readFile, readdir, stat, access } from 'node:fs/promises';
21
+ import { join, basename, dirname } from 'node:path';
22
+
23
+ import { scanRepos, parseGithubOwnerRepo, githubFetch } from './index.js';
24
+ import { credentialsDir } from './credentials.js';
25
+ import { writeTextAtomic, readJson, writeJsonAtomic, updateJsonAtomic } from './atomic-json.js';
26
+
27
+ const INDEX_FILE = 'dsh-repo-index.json';
28
+ const VIS_CHECK_TIMEOUT_MS = 10_000; // GitHub 可见性查询超时
29
+ const AUTO_GEN_NOTE = 'auto-generated by dsh-git-push: DO NOT EDIT MANUALLY'; // 索引文件防手工编辑标记
30
+
31
+ /* ───────────────────────── 读取(账号卡片本地扫描联动) ───────────────────────── */
32
+
33
+ /**
34
+ * 找插件配置目录下的索引文件:$DSH_HOME/git-push/dsh-repo-index.json
35
+ * (修正:原 <workspaceRoot>/dsh-git-push-User/<owner>/ 已废除,
36
+ * 凭据/索引收敛插件自持;workspaceRoot 保留作兼容入参,不再参与路径解析)。
37
+ */
38
+ export function locateRepoIndex(workspaceRoot) {
39
+ const p = join(credentialsDir({ workspaceRoot: workspaceRoot || '' }), INDEX_FILE);
40
+ return existsSync(p) ? p : null;
41
+ }
42
+
43
+ /** 读索引:{ name → {owner, repo, repoUrl, visibility} };无索引/损坏 → null。 */
44
+ export function readRepoIndexMap(workspaceRoot) {
45
+ const p = locateRepoIndex(workspaceRoot);
46
+ if (!p) return null;
47
+ try {
48
+ const parsed = JSON.parse(readFileSync(p, 'utf8'));
49
+ const map = {};
50
+ for (const r of Array.isArray(parsed.repos) ? parsed.repos : []) {
51
+ if (!r || !r.name) continue;
52
+ const match = (r.repoUrl || '').match(/\/repos\/([^/]+)\/([^/]+)\/?$/);
53
+ map[r.name] = {
54
+ owner: match ? match[1] : '',
55
+ repo: match ? match[2] : r.name,
56
+ path: r.path || '', // 透传本地完整路径(索引重建时缓存,供列表精确定位)
57
+ repoUrl: r.repoUrl || '',
58
+ visibility: r.visibility || '未知',
59
+ // 透传云端合并字段(mergeCloudReposIntoIndex 写入)——本地列表
60
+ // 刷新远端状态用:默认分支 / 云端最后推送时间 / 是否纯云端(本地无副本)/ 描述
61
+ defaultBranch: r.defaultBranch || '',
62
+ pushedAt: r.pushedAt || '',
63
+ cloudOnly: !!r.cloudOnly,
64
+ description: r.description || '',
65
+ // 透传远端状态补查字段(updateRepoRemoteStateInIndex 写入)——列表
66
+ // liveSkipped 补查后的 SSH 真源结果:云端 HEAD / 领先落后 / 同步态
67
+ remoteHead: r.remoteHead || '',
68
+ ahead: (r.ahead === null || r.ahead === undefined) ? null : Number(r.ahead),
69
+ behind: (r.behind === null || r.behind === undefined) ? null : Number(r.behind),
70
+ remoteHeadAt: r.remoteHeadAt || '',
71
+ synced: !!r.synced,
72
+ remoteStateAt: r.remoteStateAt || '',
73
+ };
74
+ }
75
+ return map;
76
+ } catch { return null; }
77
+ }
78
+
79
+ /** 为单个本地仓库附上索引信息:目录名匹配索引条目;未命中/无索引 → null。 */
80
+ export function indexEntryForRepo(localPath, indexMap) {
81
+ if (!indexMap || !localPath) return null;
82
+ const name = localPath.split('/').pop() || '';
83
+ return indexMap[name] ? { ...indexMap[name] } : null;
84
+ }
85
+
86
+ /* ───────────────────────── 生成(v1 移植:推送成功后全量重建) ───────────────────────── */
87
+
88
+ /** 解析 md frontmatter 的 name(--- 块内第一处 name: xxx) */
89
+ export function parseMdFrontmatterName(content) {
90
+ const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
91
+ if (!match) return '';
92
+ const n = match[1].match(/^\s*name:\s*(.+)$/m);
93
+ return n ? n[1].trim() : '';
94
+ }
95
+
96
+ /** 收集某项目的 skill 名列表:优先 package.json dsh.skills,其次扫描 skills/*.md frontmatter */
97
+ export async function collectProjectSkills(projectPath) {
98
+ const skills = [];
99
+ const seen = new Set();
100
+ const pkgPath = join(projectPath, 'package.json');
101
+ if (await exists(pkgPath)) {
102
+ try {
103
+ const pkg = JSON.parse(await readFile(pkgPath, 'utf8'));
104
+ const declared = Array.isArray(pkg.dsh?.skills) ? pkg.dsh.skills : [];
105
+ for (const rel of declared) {
106
+ const name = basename(rel).replace(/\.md$/, '');
107
+ if (name && !seen.has(name)) { seen.add(name); skills.push(name); }
108
+ }
109
+ } catch { /* 坏 JSON 忽略,走目录扫描 */ }
110
+ }
111
+ const skillsDir = join(projectPath, 'skills');
112
+ if (await exists(skillsDir)) {
113
+ try {
114
+ // 逐文件读 skill 文档:改异步以免在循环内阻塞(skill 数随项目增长)
115
+ for (const f of await readdir(skillsDir)) {
116
+ if (!f.endsWith('.md')) continue;
117
+ const name = basename(f).replace(/\.md$/, '');
118
+ if (seen.has(name)) continue; // package.json 声明优先
119
+ const content = await readFile(join(skillsDir, f), 'utf8');
120
+ const fmName = parseMdFrontmatterName(content);
121
+ if (fmName && fmName !== name && !seen.has(fmName)) { seen.add(fmName); skills.push(fmName); }
122
+ else if (!seen.has(name)) { seen.add(name); skills.push(name); }
123
+ }
124
+ } catch { /* 读不到跳过 */ }
125
+ }
126
+ return skills;
127
+ }
128
+
129
+ /** 异步探测路径是否存在(node:fs/promises 不提供 exists)。 */
130
+ async function exists(p) {
131
+ try { await access(p); return true; } catch { return false; }
132
+ }
133
+
134
+ /** 从既有索引解析可见性标注:{ repoName: '公开' | '私有' }(API 查不到时回退)。 */
135
+ export function parseManualVisibility(existingContent) {
136
+ const map = {};
137
+ if (!existingContent) return map;
138
+ try {
139
+ const existing = JSON.parse(existingContent);
140
+ if (existing && Array.isArray(existing.repos)) {
141
+ for (const r of existing.repos) {
142
+ if (r && r.name && (r.visibility === '公开' || r.visibility === '私有')) map[r.name] = r.visibility;
143
+ }
144
+ }
145
+ } catch { /* 非 JSON 忽略 */ }
146
+ return map;
147
+ }
148
+
149
+ /** 查 GitHub 仓库可见性;token 缺失/请求失败返回 null(回退手工/未知)。 */
150
+ async function queryGitHubVisibility(repoName, token, owner = 'EIGHTfs') {
151
+ if (!token) return null;
152
+ try {
153
+ const resp = await githubFetch(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}`, { token, timeout: VIS_CHECK_TIMEOUT_MS });
154
+ if (resp.status !== 200 || !resp.json) return null;
155
+ const repoData = resp.json;
156
+ if (repoData.private === true || repoData.visibility === 'private') return '私有';
157
+ return '公开';
158
+ } catch {
159
+ return null;
160
+ }
161
+ }
162
+
163
+ /** 从 remote URL 生成仓库地址 + 恢复命令(地址统一 api.github.com/repos/o/r,恢复走 git_clone)。 */
164
+ function remoteToRepoInfo(remote, visibility) {
165
+ if (!remote) return { repoUrl: '(无 remote)', cloneCmd: '—' };
166
+ const pr = parseGithubOwnerRepo(remote);
167
+ if (pr) {
168
+ const repoUrl = `https://api.github.com/repos/${pr.owner}/${pr.repo}`;
169
+ const cloneCmd = `git_clone target=${pr.owner}/${pr.repo}` + (visibility === '私有' ? '(私有,需 token)' : '');
170
+ return { repoUrl, cloneCmd };
171
+ }
172
+ return { repoUrl: remote, cloneCmd: `git_clone target=${remote}` };
173
+ }
174
+
175
+ /** 可见性查询:GitHub API 优先(并发 4,避免串行等 28 个仓库),失败回退手工标注/未知。 */
176
+ async function buildRepoIndexVisibility({ repos, token, manualVisibility, owner }) {
177
+ const visibilityMap = { ...manualVisibility };
178
+ const queue = [...repos];
179
+ const workers = Array.from({ length: 4 }, async () => {
180
+ while (queue.length) {
181
+ const r = queue.shift();
182
+ if (!r || !r.remote) continue;
183
+ // 只解析一次(同一入参重复调用是纯浪费;性能规则 performance/repeat-identical-call 命中)
184
+ const pr = parseGithubOwnerRepo(r.remote);
185
+ if (!pr && !String(r.remote).includes('github.com')) continue; // 非 GitHub 仓库不查
186
+ const api = await queryGitHubVisibility(r.name, token, pr?.owner || owner);
187
+ if (api) visibilityMap[r.name] = api;
188
+ }
189
+ });
190
+ await Promise.all(workers);
191
+ return visibilityMap;
192
+ }
193
+
194
+ /** localOnly 收集:workspace 顶层目录(排除隐藏/已有 remote 的仓库/数据目录)。 */
195
+ async function buildRepoIndexLocalOnly({ workspaceRoot, repos, localOnlyExtra }) {
196
+ const localOnly = new Set(localOnlyExtra);
197
+ try {
198
+ for (const entry of await readdir(workspaceRoot)) {
199
+ if (entry.startsWith('.') || entry === 'node_modules' || entry === 'data' || entry === 'backup') continue;
200
+ const p = join(workspaceRoot, entry);
201
+ // 单个条目的 stat 失败(权限/竞态删除)跳过,不影响整体扫描
202
+ try { if (!(await stat(p)).isDirectory()) continue; } catch { continue; }
203
+ if (repos.some((r) => r.name === entry)) continue; // 已有 GitHub remote 的仓库不进 localOnly
204
+ if (/^dsh-/.test(entry) || /DeepSeekHarness/i.test(entry)) localOnly.add(entry);
205
+ }
206
+ } catch { /* 读不到跳过 */ }
207
+ return localOnly;
208
+ }
209
+
210
+ /**
211
+ * 生成 dsh-repo-index.json 内容(JSON 结构)。
212
+ * opts: { workspaceRoot, depth, extraRepos, extraReposFile, token, manualVisibility,
213
+ * localOnlyExtra, owner }
214
+ */
215
+ export async function buildRepoIndex({ workspaceRoot, depth = 20, extraRepos = [], extraReposFile = '', token = '', manualVisibility = {}, localOnlyExtra = [], owner = 'EIGHTfs', offline = false, maxRepos = 200 } = {}) {
216
+ const repos = scanRepos(workspaceRoot || '.', { depth, extraRepos, extraReposFile, maxRepos });
217
+ // offline=true 时**纯离线**重建(账号卡片「扫描」按钮语义)——跳过 GitHub API
218
+ // 可见性联网查询(visibilityMap 只用既有标注 manualVisibility),全程不联网;
219
+ // 联网可见性刷新只在 push 在线路径(offline 缺省 false)做。
220
+ const visibilityMap = offline ? { ...manualVisibility } : await buildRepoIndexVisibility({ repos, token, manualVisibility, owner });
221
+
222
+ // 索引只存「本地所属且与登录账号一致」的仓库——有 remote 的仓库按 remote owner
223
+ // 判定(== owner 才入列);无 remote 的本地仓库无 GitHub 归属,不进 repoList(归入 localOnly)。
224
+ // 此前 repoList 收纳全部 scanRepos 结果,索引会混入其他账号/无归属仓库。
225
+ const ownedRepos = repos.filter((r) => {
226
+ if (!r.remote) return false;
227
+ const pr = parseGithubOwnerRepo(r.remote);
228
+ return pr ? pr.owner === owner : false;
229
+ });
230
+ // collectProjectSkills 已改 async(逐文件读 skill 文档不再阻塞),
231
+ // 故用 Promise.all 并发收集;后续 .sort 保持原有按名排序。
232
+ const repoList = (await Promise.all(ownedRepos.map(async (r) => {
233
+ const skills = await collectProjectSkills(r.path);
234
+ const { repoUrl, cloneCmd } = remoteToRepoInfo(r.remote, visibilityMap[r.name]);
235
+ const vis = visibilityMap[r.name] || '未知';
236
+ // 存本地完整路径 path(供账号卡片列表精确定位真实目录——工作区在
237
+ // <DSH 家根>/工作区/<repo>,不能靠 join(扫描根, name) 反推,会拼错层级)。
238
+ return { name: r.name, path: r.path, repoUrl, visibility: vis, cloneCmd, skills };
239
+ }))).sort((a, b) => a.name.localeCompare(b.name));
240
+
241
+ const localOnly = await buildRepoIndexLocalOnly({ workspaceRoot, repos, localOnlyExtra });
242
+
243
+ const index = {
244
+ name: 'dsh-repo-index',
245
+ description: '本机所有 DSH 插件/项目的 GitHub 源码索引(唯一权威):每个项目的仓库地址、可见性(公开/私有)、恢复命令、对应 skill。任何 AI 需要恢复/克隆某个 dsh-* 插件源码、确认某项目仓库地址与可见性、本地插件目录丢失需要重建时读取本文件;其他 skill 写源码位置一律引用本索引,不各自复制仓库地址。',
246
+ version: 1,
247
+ generatedAt: new Date().toISOString(),
248
+ owner,
249
+ note: AUTO_GEN_NOTE,
250
+ repos: repoList,
251
+ localOnly: [...localOnly].sort(),
252
+ recovery: [
253
+ '# 1) 查本索引确认仓库地址与可见性',
254
+ '# 2) 公开/私有统一走 git_clone(api.github.com Git Data API,需 token)',
255
+ 'git_clone { target: "OWNER/<项目名>", dest: "<目标目录>" }',
256
+ '# 3) 恢复后按插件安装三要素装回主环境(测试实例先行 + 接管式重启)',
257
+ ].join('\n'),
258
+ };
259
+ return JSON.stringify(index, null, 2) + '\n';
260
+ }
261
+
262
+ /**
263
+ * 写入索引:既有文件原位更新;不存在写 $DSH_HOME/git-push/dsh-repo-index.json
264
+ * (修正:原 dsh-git-push-User/<owner>/ 同级仓已废除,索引收敛插件配置目录)。
265
+ */
266
+ export function syncRepoIndex({ content, workspaceRoot = '', owner = 'EIGHTfs', syncTarget = '' } = {}) {
267
+ const target = syncTarget || locateRepoIndex(workspaceRoot) || join(credentialsDir({ workspaceRoot: workspaceRoot || '' }), INDEX_FILE);
268
+ // 不变量「索引只存本地仓库」:写入前**剔除云端-only 残留条目**(cloudOnly=true 或
269
+ // path 为空的旧数据)——此前 merge 曾把本地无副本的云仓库登记进索引,这些条目既违反新语义,
270
+ // 又让前端列表出现空 path 行(React 同 key 警告)。写侧统一过滤,读到的旧索引入口即自愈。
271
+ let out = content;
272
+ try {
273
+ const parsed = JSON.parse(content);
274
+ if (parsed && Array.isArray(parsed.repos)) {
275
+ const kept = parsed.repos.filter((r) => r && !r.cloudOnly && String(r.path || '').trim());
276
+ if (kept.length !== parsed.repos.length) {
277
+ parsed.repos = kept;
278
+ out = JSON.stringify(parsed, null, 2) + '\n';
279
+ }
280
+ }
281
+ } catch { /* 非 JSON 内容(或调用方传纯文本)→ 原样写 */ }
282
+ // 统一:复用 atomic-json 的原子写(.tmp + rename + chmod),原手写 tmpPath 逻辑移除
283
+ const wr = writeTextAtomic(target, out);
284
+ return wr.ok ? { ok: true, written: [target] } : { ok: false, written: [] };
285
+ }
286
+
287
+ /**
288
+ * 把「全量重建结果」与「现有索引」**合并**(不全量覆盖)。
289
+ *
290
+ * 背景(用户实测):maintainRepoIndex 全量重建后用新内容**整文件覆盖**索引,
291
+ * 而每次重建只含当次扫描范围(owner 过滤 / depth / maxRepos 受限)——于是
292
+ * dsh-repo-index.json 常被覆盖成「只剩最新一次扫描的子集」,丢历史条目。
293
+ * 合并语义:新结果按 name 覆盖命中条目(保留现有条目的独有字段,如
294
+ * remoteHead/ahead 等远端状态),现有未命中条目保留,新条目追加——
295
+ * 任何一次更新都不丢既有数据。
296
+ * @param {object|null} existing 现有索引对象(null=无/损坏)
297
+ * @param {string} freshContent buildRepoIndex 输出的 JSON 字符串
298
+ * @returns {{index: object, updated: number}}
299
+ */
300
+ function mergeFreshIntoExisting(existing, freshContent) {
301
+ let fresh = null;
302
+ try { fresh = JSON.parse(freshContent); } catch { fresh = null; }
303
+ if (!fresh || !Array.isArray(fresh.repos)) {
304
+ // 新结果不可用(损坏/空)→ 保留现有索引原样
305
+ return { index: existing || { name: 'dsh-repo-index', version: 1, generatedAt: new Date().toISOString(), repos: [], localOnly: [] }, updated: 0 };
306
+ }
307
+ const index = existing && Array.isArray(existing.repos) ? existing : {
308
+ name: fresh.name || 'dsh-repo-index',
309
+ version: 1,
310
+ generatedAt: new Date().toISOString(),
311
+ owner: fresh.owner || 'EIGHTfs',
312
+ note: AUTO_GEN_NOTE,
313
+ repos: [],
314
+ localOnly: [],
315
+ };
316
+ const freshMap = new Map(fresh.repos.map((r) => [String(r.name || ''), r]));
317
+ let updated = 0;
318
+ const seen = new Set();
319
+ const merged = (index.repos || []).map((prev) => {
320
+ const fr = freshMap.get(String(prev.name || ''));
321
+ if (!fr) return prev; // 本次扫描没扫到的旧条目:保留
322
+ seen.add(String(prev.name || ''));
323
+ updated += 1;
324
+ // fresh 覆盖核心字段(path/repoUrl/cloneCmd/skills…),prev 独有字段(远端状态等)保留;
325
+ // visibility 只在 fresh 有真值时才覆盖(fresh 在离线重建时可能回退为既有标注/空)
326
+ const next = { ...prev, ...fr };
327
+ if (!String(fr.visibility || '').trim()) next.visibility = prev.visibility;
328
+ return next;
329
+ });
330
+ for (const fr of fresh.repos) {
331
+ if (!seen.has(String(fr.name || ''))) { merged.push(fr); updated += 1; }
332
+ }
333
+ // 逐个 add 而不是 new Set([...a, ...b]):避免为去重把两个数组各复制一遍
334
+ // (ast-grep 结构查询一次性列出了全仓同型写法;此处是插件代码里的最后一处)
335
+ const localOnlySet = new Set(index.localOnly || []);
336
+ for (const x of fresh.localOnly || []) localOnlySet.add(x);
337
+ return {
338
+ index: {
339
+ ...index,
340
+ repos: merged.sort((a, b) => String(a.name).localeCompare(String(b.name))),
341
+ localOnly: [...localOnlySet].sort(),
342
+ generatedAt: new Date().toISOString(),
343
+ owner: fresh.owner || index.owner,
344
+ },
345
+ updated,
346
+ };
347
+ }
348
+
349
+ /**
350
+ * **统一更新入口(收口)**:所有 dsh-repo-index.json 更新都走本函数。
351
+ *
352
+ * 三种模式:
353
+ * · mode='rebuild'(默认):全量重建(buildRepoIndex)→ 与现有索引**合并**写回
354
+ * (不全量覆盖,任何更新不丢既有条目)——替代原 maintainRepoIndex 的整文件覆盖;
355
+ * · mode='merge-cloud':云端扫描结果合并(转发 mergeCloudReposIntoIndex);
356
+ * · mode='single':单条目远端状态补查(转发 updateRepoRemoteStateInIndex)。
357
+ *
358
+ * 返回 `indexUpdated` 标志:调用方(HTTP 端点 / 工具 / CLI)透传给 UI,
359
+ * UI 本地仓库列表据此重新读取 dsh-repo-index(/repos-local),保持列表最新。
360
+ * @param {object} opts { workspaceRoot, token, owner, depth, extraRepos, extraReposFile,
361
+ * syncTarget, offline, maxRepos, mode, cloudRepos, repoName, remoteState }
362
+ * @returns {Promise<{ok:boolean, indexUpdated:boolean, target?:string, updated?:number, error?:string}>}
363
+ */
364
+ export async function updateRepoIndex({ workspaceRoot = '', token = '', owner = 'EIGHTfs', depth = 20, extraRepos = [], extraReposFile = '', syncTarget = '', offline = false, maxRepos = 200, mode = 'rebuild', cloudRepos = [], repoName = '', remoteState = {} } = {}) {
365
+ try {
366
+ if (mode === 'merge-cloud') {
367
+ const r = mergeCloudReposIntoIndex({ workspaceRoot, owner, cloudRepos, syncTarget });
368
+ return { ...r, indexUpdated: r.ok === true };
369
+ }
370
+ if (mode === 'single') {
371
+ const r = updateRepoRemoteStateInIndex({ workspaceRoot, repoName, remoteState, syncTarget });
372
+ return { ...r, indexUpdated: r.ok === true };
373
+ }
374
+ // rebuild(默认):全量重建 → 与现有索引合并(不全量覆盖)
375
+ const target = syncTarget || locateRepoIndex(workspaceRoot) || join(credentialsDir({ workspaceRoot: workspaceRoot || '' }), INDEX_FILE);
376
+ let existing = null;
377
+ try { if (existsSync(target)) existing = JSON.parse(readFileSync(target, 'utf8')); } catch { existing = null; }
378
+ const manualVisibility = parseManualVisibility(existing ? JSON.stringify(existing) : '');
379
+ // offline=true(账号卡片「扫描」)时纯离线重建——owner 过滤来自本地 remote
380
+ // 解析(不联网),可见性回退既有标注,不给 buildRepoIndex 传 token 即不触发可见性网络。
381
+ const fresh = await buildRepoIndex({
382
+ workspaceRoot, depth, extraRepos, extraReposFile,
383
+ token: offline ? '' : token, manualVisibility, owner, offline, maxRepos,
384
+ });
385
+ const { index, updated } = mergeFreshIntoExisting(existing, fresh);
386
+ const sync = syncRepoIndex({ content: JSON.stringify(index, null, 2) + '\n', workspaceRoot, owner, syncTarget });
387
+ return { ok: sync.ok, target: sync.written[0] || '', indexUpdated: sync.ok === true, updated };
388
+ } catch (e) {
389
+ return { ok: false, error: String(e?.message || e) };
390
+ }
391
+ }
392
+
393
+ /**
394
+ * 推送成功后全量重建索引(v1 语义;起内部走 updateRepoIndex 合并,不再整文件覆盖)。
395
+ * token 缺失时可见性回退既有标注/未知;任何失败静默返回 {ok:false, error},不阻塞推送结果。
396
+ * @deprecated 新代码请直接调 updateRepoIndex(统一入口);本函数保留签名兼容旧调用。
397
+ */
398
+ export async function maintainRepoIndex({ workspaceRoot = '', token = '', owner = 'EIGHTfs', depth = 20, extraRepos = [], extraReposFile = '', syncTarget = '', offline = false, maxRepos = 200 } = {}) {
399
+ const r = await updateRepoIndex({ workspaceRoot, token, owner, depth, extraRepos, extraReposFile, syncTarget, offline, maxRepos, mode: 'rebuild' });
400
+ return r;
401
+ }
402
+
403
+ /**
404
+ * 云端扫描结果合并进索引(新增:账号卡片「云端」扫描也写索引)。
405
+ *
406
+ * 语义:把 listCloudRepos 返回的云端仓库(owner 名下全部仓库)登记/更新进
407
+ * dsh-repo-index.json——云端仓库即使本地没有副本也登记(cloudOnly 标记),
408
+ * 本地已有副本的条目保留本地字段(path/skills/cloneCmd)并刷新云端状态
409
+ * (defaultBranch/pushedAt/description/visibility 按云端真源)。
410
+ * 任何失败静默返回 {ok:false, error},不阻塞云端扫描响应。
411
+ *
412
+ * @param {object} opts
413
+ * { workspaceRoot, owner, cloudRepos: [{fullName,name,private,defaultBranch,pushedAt,description,cloneUrl}], syncTarget }
414
+ * @returns {{ok:boolean, updated:number, target?:string, error?}}
415
+ */
416
+ export function mergeCloudReposIntoIndex({ workspaceRoot = '', owner = 'EIGHTfs', cloudRepos = [], syncTarget = '' } = {}) {
417
+ try {
418
+ const target = syncTarget || locateRepoIndex(workspaceRoot) || join(credentialsDir({ workspaceRoot: workspaceRoot || '' }), INDEX_FILE);
419
+ let existing = null;
420
+ try {
421
+ if (existsSync(target)) existing = JSON.parse(readFileSync(target, 'utf8'));
422
+ } catch { existing = null; }
423
+ // 保底结构:老索引/坏 JSON → 空容器,合并后写回
424
+ const index = existing && typeof existing === 'object' && Array.isArray(existing.repos) ? existing : {
425
+ name: 'dsh-repo-index',
426
+ version: 1,
427
+ generatedAt: new Date().toISOString(),
428
+ owner,
429
+ note: AUTO_GEN_NOTE,
430
+ repos: [],
431
+ localOnly: [],
432
+ };
433
+ const byName = new Map((index.repos || []).map((r) => [r.name, r]));
434
+ let updated = 0;
435
+ for (const cloudRepo of Array.isArray(cloudRepos) ? cloudRepos : []) {
436
+ const name = String(cloudRepo.name || '').trim();
437
+ if (!name) continue;
438
+ const prev = byName.get(name);
439
+ // 语义收缩:**dsh-repo-index 只存本地仓库**——云端扫描只**更新**索引里已有
440
+ // 条目的云端字段(defaultBranch/pushedAt/visibility 等),**不新增云端-only 条目**
441
+ // (本地没有副本的云仓库不进索引;前端「云端有、本地无」由 repos-cloud 的 localExists 判断)。
442
+ if (!prev) continue;
443
+ const repoUrl = `https://api.github.com/repos/${String(cloudRepo.fullName || `${owner}/${name}`)}`;
444
+ // 云端真源可见性(listCloudRepos 的 private 布尔)优先,覆盖本地标注
445
+ const visibility = cloudRepo.private === true ? '私有' : '公开';
446
+ const next = {
447
+ ...prev, // 保留本地条目全部既有字段(path/skills/cloneCmd…)
448
+ name,
449
+ repoUrl,
450
+ visibility,
451
+ // 云端状态字段(本地列表/远端状态刷新用)
452
+ defaultBranch: String(cloudRepo.defaultBranch || ''),
453
+ pushedAt: String(cloudRepo.pushedAt || ''),
454
+ description: String(cloudRepo.description || ''),
455
+ owner,
456
+ repo: name,
457
+ };
458
+ if (prev.visibility !== next.visibility || prev.pushedAt !== next.pushedAt) updated++;
459
+ byName.set(name, next);
460
+ }
461
+ index.repos = [...byName.values()].sort((a, b) => String(a.name).localeCompare(String(b.name)));
462
+ index.generatedAt = new Date().toISOString();
463
+ index.owner = owner;
464
+ const written = syncRepoIndex({ content: JSON.stringify(index, null, 2) + '\n', workspaceRoot, owner, syncTarget });
465
+ return { ok: true, updated, ...written };
466
+ } catch (e) {
467
+ return { ok: false, error: String(e?.message || e) };
468
+ }
469
+ }
470
+
471
+ /**
472
+ * 把「远端状态补查结果」写回索引条目(本地扫描完自动补查 liveSkipped 仓库)。
473
+ *
474
+ * 本地列表(repos-local)对超预算/熔断的仓库标 liveSkipped(远端状态未知);本函数把
475
+ * liveRemoteHead 补查到的 remoteHead/ahead/behind/remoteHeadAt/synced 写回索引,
476
+ * 下次列表读取直接有值(不再每次补查)。
477
+ * 扩展:remoteState 支持 visibility —— 推送成功后回写可见性,
478
+ * 此前只有「全量重建索引(maintainRepoIndex)」才会刷新 visibility,而推送路径
479
+ * 调的就是全量重建,它**不写** remoteHead/remoteHeadAt/remoteStateAt,
480
+ * 于是推送后索引里这些远端状态字段长期停留在上一轮扫描的旧值。
481
+ * @param {object} opts { workspaceRoot, repoName, remoteState }
482
+ * remoteState = { remoteHead, ahead, behind, remoteHeadAt, synced, visibility? }
483
+ * visibility 传空/未传 = 不改动既有值(避免把已知可见性抹成「未知」)
484
+ * @returns {{ok:boolean, target?:string, error?}}
485
+ */
486
+ export function updateRepoRemoteStateInIndex({ workspaceRoot = '', repoName = '', remoteState = {}, syncTarget = '' } = {}) {
487
+ try {
488
+ const target = syncTarget || locateRepoIndex(workspaceRoot) || join(credentialsDir({ workspaceRoot: workspaceRoot || '' }), INDEX_FILE);
489
+ let index = null;
490
+ try {
491
+ if (existsSync(target)) index = JSON.parse(readFileSync(target, 'utf8'));
492
+ } catch { index = null; }
493
+ if (!index || !Array.isArray(index.repos) || !repoName) return { ok: false, error: '索引缺失/仓库名缺失' };
494
+ const hit = index.repos.find((r) => r.name === repoName);
495
+ if (!hit) return { ok: false, error: `索引无 ${repoName} 条目(先云端/本地扫描登记)` };
496
+ const { remoteHead = '', ahead = null, behind = null, remoteHeadAt = '', synced = false, visibility = '' } = remoteState;
497
+ hit.remoteHead = remoteHead;
498
+ hit.ahead = ahead;
499
+ hit.behind = behind;
500
+ hit.remoteHeadAt = remoteHeadAt;
501
+ hit.synced = synced;
502
+ // 可见性只在拿到真值时覆盖:'' 表示「本次没查到」而非「未知」,
503
+ // 直接写会把云端扫描/手工标注得到的好值抹掉。
504
+ if (visibility) hit.visibility = visibility;
505
+ hit.remoteStateAt = new Date().toISOString();
506
+ index.generatedAt = new Date().toISOString();
507
+ const written = syncRepoIndex({ content: JSON.stringify(index, null, 2) + '\n', workspaceRoot, owner: index.owner || 'EIGHTfs', syncTarget });
508
+ return { ok: true, ...written };
509
+ } catch (e) {
510
+ return { ok: false, error: String(e?.message || e) };
511
+ }
512
+ }