dsh-git-push 2.20.11 → 2.20.18

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 (58) hide show
  1. package/README.md +10 -6
  2. package/cli-audit.mjs +141 -0
  3. package/cli-tool.mjs +86 -0
  4. package/cli.mjs +114 -335
  5. package/lib/app/command-registry.js +3 -2
  6. package/lib/app/constants.js +9 -0
  7. package/lib/app/handlers/clone.js +12 -3
  8. package/lib/app/handlers/http-constants.js +11 -2
  9. package/lib/app/handlers/npm.js +4 -2
  10. package/lib/app/handlers/repos.js +10 -1
  11. package/lib/app/handlers/settings.js +9 -1
  12. package/lib/app/http-handlers.js +24 -3
  13. package/lib/app/schema-audit.js +42 -0
  14. package/lib/app/schema.js +19 -19
  15. package/lib/app/settings-bridge.js +51 -0
  16. package/lib/app/tool-call.js +7 -5
  17. package/lib/audit-rules/audit-rules-paths.yml +7 -1
  18. package/lib/audit-ui-sdk/contract.js +117 -0
  19. package/lib/audit-ui-sdk/index.js +17 -0
  20. package/lib/checks/regex.js +6 -1
  21. package/lib/cli/commands-audit.mjs +12 -17
  22. package/lib/cli/commands-tool.mjs +93 -0
  23. package/lib/cli/commands-vcs.mjs +2 -1
  24. package/lib/cli/shared.mjs +448 -0
  25. package/lib/client-parts/{account.js → git/account.js} +1 -1
  26. package/lib/client-parts/{actions.js → git/actions.js} +26 -11
  27. package/lib/client-parts/{apply.js → git/apply.js} +1 -1
  28. package/lib/client-parts/{browser.js → git/browser.js} +1 -1
  29. package/lib/client-parts/{const.js → git/const.js} +6 -1
  30. package/lib/client-parts/{controller.js → git/controller.js} +23 -11
  31. package/lib/client-parts/{icons.js → git/icons.js} +1 -1
  32. package/lib/client-parts/{loader.js → git/loader.js} +1 -1
  33. package/lib/client-parts/{npm.js → git/npm.js} +1 -1
  34. package/lib/client-parts/{page.js → git/page.js} +11 -21
  35. package/lib/client-parts/{repo.js → git/repo.js} +1 -1
  36. package/lib/client-parts/{settings.js → git/settings.js} +1 -1
  37. package/lib/client-parts/{utils.js → git/utils.js} +1 -1
  38. package/lib/client.js +75 -354
  39. package/lib/commit-push/pre-commit-engine.js +388 -0
  40. package/lib/commit-push.js +42 -20
  41. package/lib/git/transport.js +31 -10
  42. package/lib/http/index.js +82 -10
  43. package/lib/npm/npmrc.js +22 -5
  44. package/lib/self/index.js +1 -1
  45. package/package.json +6 -2
  46. package/scripts/audit-gate.mjs +235 -0
  47. package/scripts/build-client.mjs +15 -8
  48. package/scripts/check.mjs +12 -3
  49. package/scripts/scan-file-io.mjs +5 -1
  50. package/scripts/scan-version.mjs +10 -7
  51. package/skills/dev/dsh-git-push.md +62 -0
  52. package/skills/guide/guide-audit.md +11 -11
  53. package/skills/guide/guide-cli-scripts.md +3 -3
  54. package/skills/guide/guide-commit-push.md +2 -2
  55. package/skills/guide/guide-inject-ui.md +0 -16
  56. package/assets/start.sh +0 -396
  57. package/scripts/scan-hardcoded-paths.mjs +0 -125
  58. /package/lib/client-parts/{audit.js → audit/audit.js} +0 -0
package/cli.mjs CHANGED
@@ -1,373 +1,152 @@
1
1
  #!/usr/bin/env node
2
2
  // dsh-skip-i18n: CLI 输出硬编码中文为产品行为(无 i18n 需求)
3
3
  /**
4
- * dsh-git-push 独立 CLI(git-sluice)
4
+ * dsh-git-push 独立 CLI · **git 侧**(bin: git-sluice)
5
5
  * 不依赖 DSH 运行时,可独立运行。命名/参数与 lib 函数完全一致(外部 API 与函数名一致)。
6
+ *
7
+ * 三个入口的分工(切割线单处定义在 lib/cli/shared.mjs 的 CLI_ENTRIES):
8
+ * git-sluice 提交/推送/克隆/账号/仓库扫描/发布(本文件)
9
+ * audit-sluice 审计/规则/评分/静态检查(cli-audit.mjs)
10
+ * tool-sluice 拆分/模板/自检(cli-tool.mjs)
11
+ * 跨侧命令**明确报错并给出可照抄的替代命令**,不静默转发——静默转发会让「三个 CLI」名不副实。
12
+ *
13
+ * 本文件只保留:命令表 + HELP 文本 + 薄壳。解析/打印/分发/跨侧提示都在 lib/cli/shared.mjs。
6
14
  */
7
- import './lib/app/host-doc-checks.js'; // 审计包边界:文档漂移检查器由宿主(独立 CLI)注入
8
- import { VERSION, readmeTemplate, yamlTemplate, helpSync } from './lib/self/index.js';
9
- import { loadRuleFiles, discoverRuleSlots } from './lib/rule/loader.js';
10
- import { compileAllRules } from './lib/rule/registry.js';
15
+ import { VERSION } from './lib/self/index.js';
11
16
  import { runWrappedGit } from './lib/git/wrapped-git.js';
12
- import { registryByCli, parseRegistryArgs } from './lib/app/command-registry.js';
13
- import { callTool } from './lib/app/tool-call.js';
14
- import { readFileSync, realpathSync } from 'node:fs';
15
17
 
16
- // 结构化:命令实现按域抽到 lib/cli/commands-*.mjs(audit/account/vcs/doc),
17
- // 本文件保留入口编排(HELP/parseArgv/命令分发表/运行入口)。
18
- // 具名 import 而非 `export ... from`:COMMANDS 表直接引用 cmdXxx 变量名,
18
+ // 具名 import 而非 `export ... from`:COMMANDS 表直接引用 cmdXxx 变量名,
19
19
  // re-export 不建立本模块作用域绑定,会 ReferenceError。
20
- import {
21
- cmdAudit, cmdScan, cliPluginConfig, pluginEqualAuditOpts, pluginEqualWeights,
22
- } from './lib/cli/commands-audit.mjs';
23
- export { cmdAudit, cmdScan, cliPluginConfig, pluginEqualAuditOpts, pluginEqualWeights };
24
20
  import {
25
21
  cmdAccountCheck, cmdCredEnv, cmdRemoteCreate, cmdSetVisibility, cmdGenSshKey,
26
22
  } from './lib/cli/commands-account.mjs';
27
- export { cmdAccountCheck, cmdCredEnv, cmdRemoteCreate, cmdSetVisibility, cmdGenSshKey };
23
+ import { cmdRepos, cmdIndex, cmdCommit, cmdClone } from './lib/cli/commands-vcs.mjs';
28
24
  import {
29
- cmdRepos, cmdIndex, cmdGit, cmdCommit, cmdLinkCheck, cmdClone,
30
- } from './lib/cli/commands-vcs.mjs';
31
- export { cmdRepos, cmdIndex, cmdGit, cmdCommit, cmdLinkCheck, cmdClone };
32
- import {
33
- cmdFileIo, cmdTreeDoc, cmdFunctions, cmdModuleSplitter,
34
- } from './lib/cli/commands-doc.mjs';
35
- export { cmdFileIo, cmdTreeDoc, cmdFunctions, cmdModuleSplitter };
25
+ CLI_GIT, CLI_ENTRIES, cliPluginConfig, parseArgv, parseVia, printToolResult, runAsEntry, runCli,
26
+ } from './lib/cli/shared.mjs';
36
27
 
37
- /** parseArgv 认识的选项白名单(cli-help-sync 机器比对基准,必须与 HELP 文本一致。
38
- * 注:-m 是单横线别名(helpSync 只比对 -- 双横线),不列入本表。
39
- * 注:**注册表驱动**的命令(scan/commit/clone/npm-publish/scope-check…)参数由
40
- * lib/app/command-registry.js 的 params 校验,与本表无关;但 HELP 里写了的 flag
41
- * 都必须在本表出现,否则 cli-help-sync 会报「HELP 写了但 parseArgv 不认」。 */
42
- export const KNOWN_FLAGS = ['--depth', '--full', '--ruleset', '--weights', '--include-ignored', '--push', '--no-push', '--dry-run', '--force', '--message', '--audit', '--ignore-patterns', '--requirements-confirmed', '--push-confirmed', '--json', '--max', '--owner', '--offline', '--paths', '--history', '--since', '--until', '--out', '--skip-empty',
43
- // npm 相关(与 command-registry 的 npm_publish 参数对齐:dir / dryRun / tag / otp / confirm)
44
- '--dir', '--tag', '--otp', '--confirm', '--global', '--ignore-scripts', '--async', '--no-dry-run',
45
- // file-io 三标签过滤
46
- '--summary', '--write', '--type', '--kind', '--risk', '--op', '--root', '--readme',
47
- // identity-rewrite:额外要统一的邮箱
48
- '--extra-emails',
49
- // scope-check(与 command-registry 的 scope_check 参数对齐)
50
- '--files', '--repo', '--prefix', '--allowlist', '--top-level-must-be-empty',
51
- // 补齐的 5 个命令(clone / account-check / remote-create / set-visibility / gen-ssh-key)
52
- '--dest', '--branch', '--preview', '--max-file-mb', '--concurrency', '--visibility', '--email', '--no-check-ssh', '--token'];
28
+ export const CLI_NAME = CLI_GIT;
53
29
 
54
- const HELP = `git-sluice v${VERSION} — dsh-git-push 引擎独立 CLI(脱离 DSH 运行)
30
+ /** parseArgv 认识的选项白名单(本侧 HELP 写着的那批;self-check 机器比对本表与 HELP 文本)。
31
+ * 注:-m 是单横线别名(helpSync 只比对 -- 双横线),不列入本表。
32
+ * 注:**注册表驱动**命令(scan/commit/clone/npm-publish…)的参数由 lib/app/command-registry.js
33
+ * 的 params 校验,与本表无关;但本侧 HELP 里写了的 flag 都必须在本表出现,
34
+ * 否则 self-check 会报「HELP 写了但 parseArgv 不认」。 */
35
+ export const KNOWN_FLAGS = [
36
+ '--audit', '--audit-exempt-paths', '--audit-exempt-reason', '--body', '--branch', '--ci-timeout-sec',
37
+ '--confirm', '--depth', '--dest', '--dry-run', '--extra-emails', '--extra-repos-file', '--force', '--history',
38
+ '--history-depth', '--ignore-patterns', '--json', '--local-preview', '--max', '--message', '--message-items',
39
+ '--method', '--no-dry-run', '--no-push', '--offline', '--otp', '--owner', '--paths', '--push',
40
+ '--push-confirmed', '--push-initial', '--query', '--remote', '--requirements-confirmed', '--root',
41
+ '--skip-smoke', '--ssh-pub', '--tag', '--token', '--update-remotes', '--visibility', '--wait-ci',
42
+ '--wait-visible', '--whole-package', '--write',
43
+ ];
44
+
45
+ const HELP = `git-sluice v${VERSION} — ${CLI_ENTRIES[CLI_GIT].intro}
55
46
 
56
47
  快速开始(第一次用——不用查源码):
57
48
  git-sluice account-check ① 先校验 GitHub 凭据(token/SSH 是否可用)
58
49
  git-sluice scan <目录> ② 看有哪些 git 仓库(分支/未提交/未推送)
59
- git-sluice audit <仓库> --full ③ 全量审计一个仓库(评分/问题/API 指引)
60
- git-sluice commit <仓库> --message "msg" ④ 提交推送(自动过审计门禁)
50
+ git-sluice commit <仓库> --message "msg" ③ 提交推送(自动过审计门禁)
61
51
  git-sluice help 全部命令与参数
62
52
 
63
- 用法:
53
+ 其它 CLI(本入口不含,敲错会给出替代命令):
54
+ audit-sluice 审计/规则/静态检查: audit ruleset file-io link-check scope-check functions tree-doc
55
+ tool-sluice 工具链: module-splitter yaml-template readme-template self-check
56
+
57
+ 用法(每行写的参数就是该命令真实接受的写法,照抄即可):
64
58
  git-sluice version 查看版本
65
- git-sluice ruleset [槽位...] 编译规则包并输出统计(默认全部槽位)
66
- git-sluice scan <root> [--depth N] 全量扫描目录(非 git 目录可查)
59
+ git-sluice scan <root> [--paths <路径,路径>] [--extra-repos-file <文件>]
60
+ 扫描本地 git 仓库(分支/remote/未提交/未推送;尊重 .gitignore:被忽略目录整棵跳过)
67
61
  git-sluice repos <root> [--depth N] [--max N] [--json]
68
- 扫描本地 git 仓库(尊重 .gitignore:被忽略目录整棵跳过)
62
+ 同上,可读文本通道(scan 是它的注册表通道,输出更精简)
69
63
  git-sluice index <root> [--owner <账号>] [--depth N] [--max N] [--offline] [--json]
70
- 重建仓库索引 dsh-repo-index.json(--offline=纯离线不查 GitHub API)
71
- git-sluice audit <root> [--full] [--ruleset <目录>] [--weights <JSON>] [--include-ignored] [--history [--since <提交>] [--until <提交>] [--out <目录>]]
72
- 审计目录(默认 diff 范围;--full=全量;--ruleset=自定规则目录;--weights=权重覆盖 JSON;--include-ignored=连 .gitignore 忽略的文件也扫;--history=历史提交审计——逐提交快照全量审计并落盘报告,--since/--until 起始~结束提交(皆缺省=全部历史、含两端),--out 报告保存目录(缺省=git 根 audit-history/))
73
- git-sluice commit <repo> --message <msg> [--push|--no-push] [--dry-run] [--force] [--audit] [--ignore-patterns <模式>] [--requirements-confirmed] [--push-confirmed] [--paths <路径1,路径2>] [--json]
74
- 审计门禁 → 提交(默认只 commit 不 push;--push 推远端;--force 强推覆盖远端历史;--requirements-confirmed 显式核对开发者要求;--push-confirmed 显式放行推送门禁;--paths 精确 add 指定文件替代 add -A)
75
- git-sluice clone-preview <owner/repo> [--branch <名>] [--json]
76
- git-sluice file-io [路径...] [--summary] [--write] [--type sync|async] [--kind read|write|delete|rename] [--risk high|medium|low] [--op <操作名>] [--json]
77
- 文件读写调用扫描(三标签:类型/操作/上下文)——同步 I/O 在异步路径会阻塞;写/删/改名涉及数据安全
78
- git-sluice link-check <路径> 检查 md/文本中的链接有效性(只 warning,flaky 域名打折)
79
- git-sluice scope-check [文件...] [--repo <目录>] [--prefix <前缀>] [--allowlist <名,名>] [--top-level-must-be-empty] [--files <文件,文件>] [--json]
80
- 拼接产物作用域撞名(多段 JS 拼进同一作用域):同一函数帧内 var/function/const/let/class 重名会让后者静默顶掉前者,运行期毫无线索;
81
- 判定按真实作用域帧(两个不同函数里的同名局部变量不算撞名);顶层声明与命名前缀按**被查项目自己**的 package.json(dshScopeCheck)判定,
82
- 没声明就只查同帧重名(不拿本项目的 dshgp_ 去要求别人);不给文件时取该项目 dshScopeCheck.files
83
- git-sluice npm-publish [目录] [--dry-run|--no-dry-run] [--tag <tag>] [--otp <码>] [--confirm] [--json]
84
- npm 发包(注册为后台 job):默认 dry-run,只体检 + npm publish --dry-run(**不写 registry**);
85
- 真发必须同时给 --no-dry-run 与 --confirm(不可撤销);体检项:private:true / 同名版本占用 / npm pack 清单
86
- git-sluice api npm-account [--json] npm 账号(离线快照)
87
- git-sluice api npm-check npm 账号在线校验(npm whoami,写快照)
88
- git-sluice api npm-owned 登录账号名下的公开包列表
89
- git-sluice api npm-packages --dir <目录> 该目录的依赖清单
90
- git-sluice api npm-install --dir <目录> --confirm [--global] [--async] [--ignore-scripts]
91
- 安装包(--global=全局;--async=异步 + 用 npm-install-progress 轮询进度;默认不执行安装脚本)
92
- git-sluice api npm-install-progress 安装进度/终态(consume:true 取走后复位)
93
- git-sluice api npm-publish --dry-run npm 发包(等价写法:走 api 通道,默认 dry-run)
94
- git-sluice identity-rewrite [仓库路径...] [--root <目录>] [--write] [--push] [--extra-emails <邮箱...>] [--json]
95
- 提交身份历史改写:把非规范身份(工具/AI 产生的 agent@dsh.local 等 + 账号 noreply 旧变体)
96
- 统一成登录账号规范身份;默认 dry-run 只报告,--write 才改(先建备份引用,自检通过才改写),
97
- --push 再用 force-with-lease 强推;只处理 origin 属于登录账号的仓库
98
- git-sluice module-splitter <analyze|split|verify> <file|plan> [--dry-run] [--json]
99
- git-sluice functions <analyze|apply> [目录] [--skip-empty] [--json]
100
- git-sluice tree-doc <sync|gen|check|apply> [--root <目录>] [--readme <路径>] [--write]
101
- README 目录结构维护:sync 索引同步(新增自动加键/删除自动删键);gen 生成树;check 检查漂移;apply 覆盖 README 标记块(封装 scripts/tree-doc.mjs)
102
- 函数索引与函数文档:analyze 生成 functions-index.json(复用 scripts/func-index.js,含签名/注释槽位);apply 读 JSON(人工补 comment 后)生成 docs/函数/*.md(文件删除归档 _archived,注释不丢)
103
- 巨型单文件按顶层块拆分(python3 零依赖;analyze 先出块/依赖图 → AI 写 plan.json → split 切分 → verify 校验导出面;--dry-run=split 只预演)
64
+ 重建仓库索引 dsh-repo-index.json(--offline=纯离线不查 GitHub API)
65
+ git-sluice commit <repo> --message <msg> [--push|--no-push] [--audit] [--dry-run] [--force] [--ignore-patterns <模式>] [--requirements-confirmed] [--push-confirmed] [--paths <路径1,路径2>] [--message-items <JSON>] [--audit-exempt-paths <文件,...>] [--audit-exempt-reason <理由>] [--remote <名>] [--wait-ci] [--ci-timeout-sec N]
66
+ 审计门禁 → 提交(默认只 commit 不 push;--push 推远端;--force 强推覆盖远端历史;
67
+ --requirements-confirmed 显式核对开发者要求;--push-confirmed 显式放行推送门禁;
68
+ --paths 精确 add 指定文件替代 add -A;--audit-exempt-paths 本次提交按文件临时豁免审计)
69
+ git-sluice clone <owner/repo> [dest] [--dest <目录>] [--branch <名>] [--history] [--history-depth N]
70
+ 从 GitHub 克隆仓库(Git Data API 通道,不直连 github.com;--history=重建真实提交历史)
71
+ git-sluice clone-preview <owner/repo> [--branch <名>]
72
+ clone 预演:只报告将拉取什么,不落盘
73
+ git-sluice remote-create <repo> [--visibility public|private] [--push-initial] [--dry-run]
74
+ 按项目文件夹在 GitHub 建远端仓库(已存在则复用),并指向 origin;--push-initial=建完首次推送
75
+ git-sluice rename <repo> <新名> [--dry-run] [--update-remotes]
76
+ 给 GitHub 远程仓库改名(--dry-run 只报告;--update-remotes 同步本地 remote)
77
+ git-sluice set-visibility <repo> --visibility public|private
78
+ 切换仓库公开/私有(改成公开有敏感信息暴露风险)
79
+ git-sluice identity-rewrite [仓库路径...] [--root <目录>] [--dry-run] [--write] [--push] [--extra-emails <邮箱...>] [--json]
80
+ 提交身份历史改写:把非规范身份(工具/AI 产生的 agent@dsh.local 等)统一成登录账号规范身份;
81
+ 默认 dry-run 只报告,--write 才改(先建备份引用,自检通过才改写),--push 再 force-with-lease 强推
82
+ git-sluice account-check [--token <t>] [--ssh-pub <公钥整行>]
83
+ 校验 GitHub 账号与凭据(token 在线校验 + SSH 公钥指纹)
84
+ git-sluice cred-env
85
+ 输出插件保管凭据的环境变量前缀(SSH: GIT_SSH_COMMAND 私钥路径 / HTTPS: GIT_ASKPASS 脚本)——AI 执行任意外部 git 命令时粘贴使用,全程无 token/私钥明文
86
+ git-sluice gen-ssh-key <x@y.z> [--force]
87
+ 生成 SSH 密钥对(公钥回传,私钥不出本机;--force=先备份再覆盖)
104
88
  git-sluice git <git 参数...> 浅包装 git:参数与 git 完全一致,凭据自动注入(SSH 私钥 / config.json token),无需传 token/私钥参数
105
- 例:git-sluice git pull | git clone owner/repo | git fetch origin(stdio 直连,退出码透传)
106
- git-sluice clone <owner/repo> [dest] [--branch <名>] [--dest <目录>] [--max-file-mb N] [--concurrency N] [--preview] [--json]
107
- 从 GitHub 克隆仓库(Git Data API 通道,不直连 github.com;--preview=只探测不写盘)
108
- git-sluice account-check [--token <t>] [--no-check-ssh] [--json]
109
- 校验 GitHub 账号与凭据(token 在线校验 + SSH 公钥指纹)
110
- git-sluice cred-env [--json]
111
- 输出插件保管凭据的环境变量前缀(SSH: GIT_SSH_COMMAND 私钥路径 / HTTPS: GIT_ASKPASS 脚本)——AI 执行任意外部 git 命令时粘贴使用,全程无 token/私钥明文
112
- git-sluice remote-create <repo> [--owner <账号>] [--visibility public|private] [--dry-run] [--json]
113
- 按项目文件夹在 GitHub 建远端仓库(已存在则复用),并指向 origin
114
- git-sluice set-visibility <repo> --visibility public|private [--json]
115
- 切换仓库公开/私有(public 有敏感信息暴露风险)
116
- git-sluice gen-ssh-key --email <x@y.z> [--force] [--json]
117
- 生成 SSH 密钥对(公钥回传,私钥不出本机;--force=先备份再覆盖)
118
- git-sluice yaml-template 输出规则 yml 模板(含 kind + dimensions 示范)
119
- git-sluice readme-template 输出 README 模板({{name}} {{version}} 占位符)
120
- git-sluice self-check 版本一致性 + HELP↔parseArgv 机器比对(自检)
89
+ 例:git-sluice git pull | git clone owner/repo | git fetch origin(stdio 直连,退出码透传)
90
+ git-sluice api <接口名> [--method GET|POST] [--query <JSON>] [--body <JSON>]
91
+ 直接调用本插件 HTTP API(与浏览器同源实现);不带接口名则列出全部可用接口
92
+ git-sluice npm-publish [目录] [--dry-run|--no-dry-run] [--tag <tag>] [--otp <码>] [--confirm] [--json] [--wait-visible] [--skip-smoke] [--local-preview]
93
+ npm 发包(注册为后台 job):默认 dry-run,只体检 + npm publish --dry-run(不写 registry);
94
+ 真发必须同时给 --no-dry-run 与 --confirm(不可撤销)
95
+ git-sluice unpublish <包名> [版本] [--whole-package] [--dry-run] [--confirm]
96
+ 从 npm registry 撤包(不可逆):默认 dry-run 只预检,真撤需关掉 --dry-run 并给 --confirm
121
97
  git-sluice help 显示本帮助
122
98
  `;
123
99
 
124
- // 导入 compilers 触发注册(副作用:注册 13 种编译函数到 RULE_COMPILERS)
125
- import './lib/rule/compilers.js';
126
-
127
- /**
128
- * 参数解析:白名单必须与 HELP 文本完全一致(cli-help-sync 自检)。
129
- *
130
- * 实现用**表驱动**而非 if-else 长链:每加一个 flag 只加一行表项,
131
- * 函数长度不随 flag 数增长(if-else 版加到第 21 个 flag 时func-lines 即 101 行、
132
- * 触发自己的 readability/max-function-length blocker)。
133
- *
134
- * 自检约束:helpSync 用正则 /--[\w-]+/g 扫本文件全文提取 flag 字面量,
135
- * 故下表必须**写成 `'--xxx'` 字面量**(拼字符串会让自检扫不到而误报)。
136
- */
137
-
138
- /** 布尔开关 flag → flags 字段名(出现即为 true)。 */
139
- const BOOL_FLAGS = {
140
- '--full': 'full',
141
- '--history': 'history',
142
- '--include-ignored': 'includeIgnored',
143
- '--dry-run': 'dryRun',
144
- '--force': 'force',
145
- '--req-confirm': 'reqConfirm',
146
- '--push-gate-confirmed': 'pushGateConfirmed',
147
- '--json': 'json',
148
- '--offline': 'offline',
149
- '--summary': 'summary',
150
- '--write': 'write',
151
- '--preview': 'preview',
152
- '--skip-empty': 'skipEmpty',
153
- '--no-check-ssh': null, // 特殊:置 false 而非 true(见下 applyBool)
154
- };
155
-
156
- /** 取值 flag → [flags 字段名, 缺值提示, 转换函数?]。 */
157
- const VALUE_FLAGS = {
158
- '--depth': ['depth', '--depth 缺值(用法: --depth N)', Number],
159
- '--max': ['max', '--max 缺值(用法: --max N)', Number],
160
- '--owner': ['owner', '--owner 缺值(用法: --owner <账号>)'],
161
- '--ruleset': ['ruleset', '--ruleset 缺值'],
162
- '--weights': ['weights', '--weights 缺值'],
163
- '-m': ['message', '-m 缺值(用法: -m <提交信息>)'],
164
- '--root': ['root', '--root 缺值(用法: --root <目录>)'],
165
- '--readme': ['readme', '--readme 缺值(用法: --readme <README路径>)'],
166
- '--type': ['type', '--type 缺值(用法: --type sync|async)'],
167
- '--kind': ['kind', '--kind 缺值(用法: --kind read|write|delete|rename)'],
168
- '--risk': ['risk', '--risk 缺值(用法: --risk high|medium|low)'],
169
- '--op': ['op', '--op 缺值(用法: --op writeFileSync)'],
170
- '--dest': ['dest', '--dest 缺值(用法: --dest <目录>)'],
171
- '--branch': ['branch', '--branch 缺值(用法: --branch <分支名>)'],
172
- '--max-file-mb': ['maxFileMB', '--max-file-mb 缺值(用法: --max-file-mb N)', Number],
173
- '--concurrency': ['concurrency', '--concurrency 缺值(用法: --concurrency N)', Number],
174
- '--visibility': ['visibility', '--visibility 缺值(用法: --visibility public|private)'],
175
- '--email': ['email', '--email 缺值(用法: --email x@y.z)'],
176
- '--token': ['token', '--token 缺值(用法: --token <ghp_...>)'],
177
- '--since': ['since', '--since 缺值(用法: --since <起始提交 sha/ref>)'],
178
- '--until': ['until', '--until 缺值(用法: --until <结束提交 sha/ref>)'],
179
- '--out': ['out', '--out 缺值(用法: --out <报告保存目录>)'],
180
- };
100
+ /** 命令表(本侧独有的 COMMANDS;注册表驱动的命令由 shared 的 resolveDispatch 处理)。
101
+ * 注:`git` 不用登记——注册表(git_sluice)已覆盖它,旧 cli.mjs 里那条 COMMANDS['git'] 是死代码。 */
102
+ export const COMMANDS = new Map([
103
+ ['repos', parseVia((flags, positional) => cmdRepos(positional[0] || '.', flags))],
104
+ ['index', parseVia((flags, positional) => cmdIndex(positional[0] || '.', flags))],
105
+ // `git` 必须走这里而不是注册表:注册表只认声明过的参数,会把 git 自己的 flag
106
+ // (如 `log --oneline`)当「未知参数」拒掉,与「参数与 git 完全一致」的承诺相反。
107
+ ['git', (rest) => cmdGit(rest)],
108
+ ]);
181
109
 
182
- /** 默认值(函数内每次调用新建,避免跨调用串状态)。 */
183
- function defaultFlags() {
184
- return {
185
- depth: undefined, full: false, ruleset: undefined, weights: undefined, includeIgnored: false,
186
- push: undefined, dryRun: false, force: false, reqConfirm: false, pushGateConfirmed: false,
187
- message: undefined, json: false, max: undefined, owner: undefined, offline: false,
188
- summary: false, write: false, type: undefined, kind: undefined, risk: undefined, op: undefined,
189
- dest: undefined, branch: undefined, preview: false, maxFileMB: undefined, concurrency: undefined,
190
- visibility: undefined, email: undefined, checkSsh: true, token: undefined,
191
- };
110
+ /** 子命令:git —— 浅包装 git(参数原样透传,凭据自动注入)。
111
+ * 无参数时只让 git 打印自己的用法并返回 0(`git` 裸跑本身 exit 1,但「看用法」不是错误场景)。 */
112
+ export async function cmdGit(rest = []) {
113
+ const wrapped = await runWrappedGit(rest);
114
+ if (Array.isArray(rest) && rest.length === 0) return 0;
115
+ if (wrapped && wrapped.ok) return 0;
116
+ process.exitCode = typeof wrapped?.status === 'number' ? wrapped.status : 1;
117
+ return process.exitCode;
192
118
  }
193
119
 
194
- /** 布尔开关落值:--no-check-ssh 语义是「关掉」而非「开启」,单独处理。 */
195
- function applyBoolFlag(flags, a) {
196
- if (a === '--no-check-ssh') { flags.checkSsh = false; return; }
197
- // --push / --no-push 是同一字段的两态,不能混进 BOOL_FLAGS 的「出现即 true」
198
- if (a === '--push') { flags.push = true; return; }
199
- if (a === '--no-push') { flags.push = false; return; }
200
- flags[BOOL_FLAGS[a]] = true;
120
+ /** 未知命令的 git 透传(`git-sluice status` = `git status`;git-sluice 是 git 的超集)。 */
121
+ async function passthroughGit(argv) {
122
+ return await runWrappedGit(argv);
201
123
  }
202
124
 
203
- /** 取值 flag 落值。 */
204
- function applyValueFlag(flags, a, v) {
205
- const [field, , conv] = VALUE_FLAGS[a];
206
- flags[field] = conv ? conv(v) : v;
125
+ /**
126
+ * 入口 main。
127
+ * @param {string[]} argv
128
+ * @returns {Promise<number|undefined>} 退出码
129
+ */
130
+ export async function main(argv = process.argv.slice(2)) {
131
+ return await runCli({
132
+ cliName: CLI_GIT,
133
+ argv,
134
+ commands: COMMANDS,
135
+ helpText: HELP,
136
+ passthroughGit,
137
+ getConfig: cliPluginConfig,
138
+ });
207
139
  }
208
140
 
209
- export function parseArgv(argv) {
210
- const flags = defaultFlags();
211
- const positional = [];
212
- for (let i = 0; i < argv.length; i++) {
213
- const a = argv[i];
214
- if (a === '--push' || a === '--no-push' || a === '--no-check-ssh' || a in BOOL_FLAGS) {
215
- applyBoolFlag(flags, a);
216
- } else if (a in VALUE_FLAGS) {
217
- const v = argv[++i];
218
- if (v === undefined || v.startsWith('--')) return { error: VALUE_FLAGS[a][1] };
219
- applyValueFlag(flags, a, v);
220
- } else if (a.startsWith('--')) {
221
- return { error: `未知参数: ${a}` };
222
- } else {
223
- positional.push(a);
224
- }
225
- }
226
- return { flags, positional };
227
- }
141
+ runAsEntry(import.meta.url, main);
228
142
 
229
- /** 子命令:version */
143
+ // 兼容导出(外部/测试按老路径 import 这些名字;实现已按域迁到 lib/cli/commands-*.mjs)
144
+ export { parseArgv, printToolResult, cliPluginConfig };
145
+ export {
146
+ cmdAccountCheck, cmdCredEnv, cmdRemoteCreate, cmdSetVisibility, cmdGenSshKey,
147
+ cmdRepos, cmdIndex, cmdCommit, cmdClone,
148
+ };
149
+ /** 子命令:version(三入口同一实现,只有名字不同)。 */
230
150
  export function cmdVersion() {
231
151
  console.log(`git-sluice v${VERSION} — dsh-git-push(统一函数入口架构)`);
232
152
  }
233
-
234
- /** 子命令:ruleset — 编译规则包输出统计。 */
235
- export function cmdRuleset(slots) {
236
- const order = slots.length ? slots : null; // null=动态发现全部槽位
237
- const { ok, merged, errors, files, order: effective } = loadRuleFiles(order);
238
- const ctx = { errors: [] };
239
- const compiled = compileAllRules(merged.rules, ctx);
240
- if (!ok || ctx.errors.length) {
241
- console.error('规则编译失败:');
242
- for (const e of [...errors, ...ctx.errors]) console.error(' ✗ ' + e);
243
- process.exitCode = 1;
244
- return;
245
- }
246
- console.log(`规则包编译 OK(${effective.join('+')})`);
247
- console.log(` 文件: ${files.length} 个槽位, 规则条目 ${merged.rules.length}, 编译成功 ${compiled.length}`);
248
- const byKind = {};
249
- for (const r of compiled) byKind[r.kind || r.type || 'other'] = (byKind[r.kind || r.type || 'other'] || 0) + 1;
250
- for (const [k, v] of Object.entries(byKind)) console.log(` ${k}: ${v}`);
251
- }
252
-
253
- export function cmdYamlTemplate() {
254
- console.log(yamlTemplate());
255
- }
256
-
257
- /** 子命令:readme-template — 输出 README 模板。 */
258
- export function cmdReadmeTemplate() {
259
- console.log(readmeTemplate().template);
260
- }
261
-
262
- /** 子命令:self-check — 版本一致性 + HELP↔parseArgv 机器比对。 */
263
- export function cmdSelfCheck() {
264
- const helpRes = helpSync(HELP, KNOWN_FLAGS);
265
- let fail = 0;
266
- console.log('自身自检:');
267
- console.log(` version: v${VERSION}`);
268
- if (!helpRes.ok) {
269
- fail++;
270
- console.error(` ✗ cli-help-sync: HELP 与 parseArgv 不一致`);
271
- for (const f of helpRes.missingInHelp) console.error(` parseArgv 认但 HELP 没写: ${f}`);
272
- for (const f of helpRes.missingInParse) console.error(` HELP 写了但 parseArgv 不认: ${f}`);
273
- } else {
274
- console.log(` ✓ cli-help-sync: HELP 与 parseArgv 一致(${helpRes.helpFlags.join(' ')})`);
275
- }
276
- const pkgRes = readPkgJson();
277
- if (pkgRes && pkgRes.version && pkgRes.version !== VERSION) {
278
- fail++;
279
- console.error(` ✗ version: lib/self=${VERSION} vs package.json=${pkgRes.version}`);
280
- } else {
281
- console.log(` ✓ version: lib/self = package.json = ${VERSION}`);
282
- }
283
- process.exitCode = fail > 0 ? 1 : 0;
284
- }
285
-
286
- /** 读 package.json(失败返回 null)。 */
287
- function readPkgJson() {
288
- try {
289
- return JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
290
- } catch { return null; }
291
- }
292
-
293
- /** 命令分发表(重构:main 54 圈复杂度 → 表驱动分发)。
294
- * 每个条目 [命令名, handler(rest)];统一 parse 模式用 parseVia 包装。 */
295
-
296
-
297
- /** 注册表工具返回输出(默认文本化 summary/apiGuide/lines;--json 直出完整返回)。 */
298
- function printRegistryResult(r, json) {
299
- if (json) { console.log(JSON.stringify(r, null, 2)); return; }
300
- if (!r) return;
301
- if (r.error) { console.error(r.error); return; }
302
- if (r.apiGuide) { console.log(r.apiGuide); return; }
303
- const L = [];
304
- if (r.summary) L.push(`summary: ${JSON.stringify(r.summary)}`);
305
- if (r.quality) L.push(`quality: ${r.quality.score ?? '?'}/${r.quality.level ?? '?'}`);
306
- if (r.count != null) L.push(`count: ${r.count}`);
307
- // lines:工具自备的可读文本行(逐文件结论、命中明细等)——避免为此另造输出通道
308
- if (Array.isArray(r.lines) && r.lines.length) L.push(...r.lines);
309
- console.log(L.length ? L.join('\n') : JSON.stringify(r));
310
- }
311
-
312
- const parseVia = (run) => (rest) => {
313
- const { flags, positional, error } = parseArgv(rest);
314
- if (error) return console.error(error);
315
- return run(flags, positional);
316
- };
317
- const COMMANDS = new Map([
318
- ['ruleset', (rest) => cmdRuleset(rest)],
319
- ['audit', parseVia((f, p) => cmdAudit(p[0] || '.', f))], // audit 不走注册表——CLI 独立审计需完整 findings(不依赖宿主 API);工具 code_audit 输出 API 指引
320
- ['repos', parseVia((f, p) => cmdRepos(p[0] || '.', f))],
321
- ['index', parseVia((f, p) => cmdIndex(p[0] || '.', f))],
322
- ['functions', parseVia((f, p) => cmdFunctions(p[0] || '', p[1] || '', f))],
323
- ['tree-doc', parseVia((f, p) => cmdTreeDoc(p[0] || '', f))],
324
- ['git', (rest) => cmdGit(rest)], // 1.9.0:浅包装 git(自动凭据透传)
325
- ['yaml-template', () => cmdYamlTemplate()],
326
- ['readme-template', () => cmdReadmeTemplate()],
327
- ['self-check', () => cmdSelfCheck()],
328
- ]);
329
-
330
- export async function main(argv = process.argv.slice(2)) {
331
- const [cmd, ...rest] = argv;
332
- if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') {
333
- console.log(HELP);
334
- return;
335
- }
336
- if (cmd === 'version' || cmd === '-v' || cmd === '--version') return await cmdVersion();
337
- // 方案 B:注册表驱动命令优先(工具有对应 → 通用 parseArgs → callTool——
338
- // CLI 与插件工具同实现,自动对齐;CLI 独立于 DSH 运行:env 自备 + 本地配置)
339
- const reg = registryByCli(cmd);
340
- if (reg) {
341
- const { args, error } = parseRegistryArgs(rest, reg.params);
342
- if (error) { console.error(error); process.exitCode = 1; return 1; }
343
- try {
344
- const r = await callTool(reg.name, args, { workspaceRoot: process.cwd() }, cliPluginConfig(), console, null, null);
345
- printRegistryResult(r, args.json === true);
346
- // 退出码如实反映结果:ok:false = 命令失败(门禁/脚本据此判失败)。
347
- // ok:true 但 committed:false / pushed:false 这类「零改动正常路径」仍是 0。
348
- return r && r.ok === false ? 1 : 0;
349
- } catch (e) { console.error(String((e && e.message) || e)); process.exitCode = 1; return 1; }
350
- }
351
- const handler = COMMANDS.get(cmd);
352
- if (handler) return await handler(rest);
353
- // 1.9.0:未知命令透传为浅包装 git(自动凭据)——`git-sluice pull` = `git pull`
354
- // (git-sluice 是 git 的超集:已知子命令走插件,其余全部交给 git + 插件凭据)
355
- const wrapped = runWrappedGit([cmd, ...rest]);
356
- if (wrapped.ok) return 0;
357
- process.exitCode = typeof wrapped.status === 'number' ? wrapped.status : 1;
358
- return process.exitCode;
359
- }
360
-
361
- // 直接运行时入口(被 import 时不执行)
362
- // 修:符号链接场景(PATH 里 git-sluice → cli.mjs)下 process.argv[1] 是链接路径、
363
- // import.meta.url 是真实文件路径,两者字符串不相等 → 入口静默不执行(exit 0 无输出)。
364
- // 用 realpath 归一化:链接/相对/绝对路径都解析到同一真实路径再比。
365
- if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('cli.mjs')
366
- || import.meta.url === `file://${realpathSync(process.argv[1])}`) {
367
- // 顶层 await:main 已异步,未 await 时 rejection 会变成 unhandled rejection
368
- // (进程静默退出、退出码不对),故显式 await 并回传退出码。
369
- // 命令函数(cmdFileIo/cmdModuleSplitter 等)返回业务对象/数组,
370
- // 只有 number 才赋 exitCode——否则 `process.exitCode = 对象` 抛 ERR_INVALID_ARG_TYPE。
371
- const mainResult = await main();
372
- if (typeof mainResult === 'number' && Number.isInteger(mainResult)) process.exitCode = mainResult;
373
- }
@@ -63,7 +63,7 @@ export const TOOL_REGISTRY = [
63
63
  {
64
64
  // code_audit 不给 CLI 命令(cli 缺省)——CLI audit 用 lib/cli(完整 findings,独立于 DSH);
65
65
  // 工具 code_audit 输出 API 指引(宿主场景有聚合 API)。CLI 独立审计不能依赖宿主 API。
66
- name: 'code_audit', description: '审计仓库:L0 静态检查+10 维度评分(0-100)。默认精简输出(评分/问题数/豁免统计/API 指引);includeFindings=true 返回全量 findings;scope=full|diff;history=历史提交审计',
66
+ name: 'code_audit', description: '审计仓库:L0 静态检查+10 维度评分(0-100)。默认返回全量 findings+yaml(可直接读问题明细);includeFindings=false 或 summaryOnly=true 只要评分与摘要;scope=full|diff;history=历史提交审计',
67
67
  params: [
68
68
  { flag: 'repo', type: 'string', positional: 0, required: true, desc: '仓库绝对路径' },
69
69
  { flag: 'scope', type: 'string', enum: ['full', 'diff'], default: 'full', desc: '审计范围' },
@@ -75,7 +75,8 @@ export const TOOL_REGISTRY = [
75
75
  { flag: 'until', type: 'string', desc: 'history 结束提交' },
76
76
  { flag: 'outDir', type: 'string', desc: 'history 报告目录' },
77
77
  { flag: 'json', type: 'boolean', desc: 'JSON 输出(完整返回)' },
78
- { flag: 'includeFindings', type: 'boolean', desc: 'true 时返回全量审计结果(findings+yaml)' },
78
+ { flag: 'includeFindings', type: 'boolean', desc: '默认 true:返回全量审计结果(findings+yaml);传 false 精简为评分/摘要/API 指引' },
79
+ { flag: 'summaryOnly', type: 'boolean', desc: '只要评分与摘要(等价 includeFindings=false 的语义,更直观)' },
79
80
  ],
80
81
  },
81
82
  {
@@ -14,3 +14,12 @@ export const GIT_PUSH_SETTINGS_NS = 'git-push';
14
14
 
15
15
  /** blocked 消息预览截断长度(审计输出精简——完整 message 走 /audit 明细)。多入口共用,单处定义。 */
16
16
  export const MAX_MSG_PREVIEW = 80;
17
+
18
+ /**
19
+ * 提交前预处理引擎默认超时(毫秒,10 分钟)。
20
+ * 单处定义的原因:schema 默认值(lib/app/schema.js 的 preCommit.timeoutMs)与运行期兜底
21
+ * (lib/commit-push/pre-commit-engine.js)必须永远相等——两处各写一份数字,改一处漏另一处
22
+ * 就会出现「配置显示 10 分钟、实际跑 5 分钟」这种自相矛盾的静默不一致。
23
+ * 取值理由:大仓全量审计可达分钟级,但引擎卡死必须能被判定,不能无限等。
24
+ */
25
+ export const PRE_COMMIT_TIMEOUT_MS_DEFAULT = 600000;
@@ -159,10 +159,19 @@ export async function handleClonePreview(ctx) {
159
159
  return { status: r.ok ? 200 : 400, body: { ...r, dir, partial } };
160
160
  }
161
161
 
162
- /** GET|POST /api/git-push/clone-progress —— 轮询克隆进度。 */
162
+ /** GET|POST /api/git-push/clone-progress —— 轮询克隆进度。
163
+ *
164
+ * 为什么优先 GET:轮询端点用 POST 有两个副作用——① 它没有副作用(读进度本身不改状态),
165
+ * 用 POST 语义不对;② 写方法要过 CSRF Origin 校验,一旦被拒(如桌面端转发剥离 Origin)
166
+ * 就静默失败:进度条不刷新,用户误以为「克隆卡住」(外部报告实测踩到)。
167
+ * GET 是读方法,天然免 Origin 校验,轮询不会再因鉴权静默失效。
168
+ * consume 同时支持两种入口:body(POST 旧写法)与 query(GET ?consume=1),两者等价。
169
+ */
163
170
  export function handleCloneProgress(ctx) {
164
- const { body } = ctx;
171
+ const { body = {}, query = {} } = ctx;
172
+ const consume = body.consume === true || body.consume === 'true'
173
+ || query.consume === '1' || query.consume === 'true';
165
174
  const st = cloneJobStatus();
166
- if (st.state === 'done' && body.consume) clearCloneJobResult();
175
+ if (st.state === 'done' && consume) clearCloneJobResult();
167
176
  return { status: 200, body: { ok: true, ...st } };
168
177
  }
@@ -5,5 +5,14 @@
5
5
  export const LIST_LIVE_BUDGET_MS = 15_000;
6
6
  /** 远端探测并发度。与 SSH 默认 MaxSessions 兼容,且不超过 GitHub 连接容忍度。 */
7
7
  export const PROBE_CONCURRENCY = 4;
8
- /** 本地扫描等待超时(毫秒)。 */
9
- export const SCAN_WAIT_TIMEOUT_MS = 60_000;
8
+ /**
9
+ * 本地扫描长轮询的单次挂起上限(毫秒)。
10
+ *
11
+ * **必须小于前端 fetch 超时**(`dshgp_FETCH_TIMEOUT_MS` = 30s,取 80% 余量 ⇒ ≤24s)。
12
+ * 为什么:这是长轮询语义——服务端「挂起到有新进度或到点」才返回,到点返回
13
+ * `{timeout:true, running:true}`,前端据此再发起下一轮,推进由 `done` 事件驱动。
14
+ * 若服务端挂得比前端超时还久,前端会先 abort(`signal timed out`),
15
+ * 长轮询变成假失败——原先取 60s 正是这个错误(客户端 30s 必先炸)。
16
+ * `test/test-repos-live-budget.mjs` 有断言守着这条关系。
17
+ */
18
+ export const SCAN_WAIT_TIMEOUT_MS = 20_000;
@@ -131,7 +131,9 @@ export function handleNpmInstall(ctx) {
131
131
  dest: String(body?.dest || ''),
132
132
  global,
133
133
  ignoreScripts: body?.ignoreScripts !== false, // 默认 true(安全默认)
134
- registry: cfg?.npmRegistry || '',
134
+ // 未配置时必须传 undefined,不能传空串:`registry=''` 会被当成显式值一路写进 npmrc
135
+ // (`registry=` 空行),npm 解析空 URL 直接 ERR_INVALID_URL 崩掉。
136
+ registry: cfg?.npmRegistry || undefined,
135
137
  workspaceRoot: env?.workspaceRoot || '',
136
138
  };
137
139
  // async=true:走异步安装 + /npm-install-progress 轮询(UI 进度框用;对应 GitHub 克隆的进度模型)
@@ -158,7 +160,7 @@ export async function handleNpmPublish(ctx) {
158
160
  }
159
161
  const r = await publishPackage({
160
162
  dir: String(body?.dir || env?.workspaceRoot || ''),
161
- registry: cfg?.npmRegistry || '',
163
+ registry: cfg?.npmRegistry || undefined,
162
164
  workspaceRoot: env?.workspaceRoot || '',
163
165
  dryRun,
164
166
  tag: body?.tag || 'latest',
@@ -92,7 +92,16 @@ async function applyLiveRemote(list, deadline) {
92
92
  }
93
93
  const t0 = Date.now();
94
94
  let live = { ok: false, sha: '' };
95
- try { live = await liveRemoteHeadAsync({ repoPath: repoProbe.path, branch: repoProbe.branch || '' }); } catch { /* 忽略 */ }
95
+ // 把**剩余预算**传进单次探测:它内部会摊到每步 git 调用上。
96
+ // 只靠上面的 isProbeOverBudget 不够——那只在「调用前」检查,
97
+ // 单次探测里若有一步不带超时的 git 调用,整个请求仍会穿透整表预算
98
+ // (实测:DSH 启动后首开「本地」页 → 前端 30s fetch 超时 → signal timed out)。
99
+ const remainBudget = Number.isFinite(deadline) ? Math.max(0, deadline - Date.now()) : 0;
100
+ try {
101
+ live = await liveRemoteHeadAsync({
102
+ repoPath: repoProbe.path, branch: repoProbe.branch || '', budgetMs: remainBudget,
103
+ });
104
+ } catch { /* 忽略 */ }
96
105
  results.set(repoProbe.name, { live, elapsed: Date.now() - t0 });
97
106
  }
98
107
  });