dsh-git-push 3.0.0 → 3.1.0

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 (65) hide show
  1. package/README.md +76 -48
  2. package/cli.mjs +4 -3
  3. package/lib/app/apply.js +11 -9
  4. package/lib/app/command-registry.js +4 -2
  5. package/lib/app/handlers/http-constants.js +8 -0
  6. package/lib/app/handlers/preprocess.js +3 -6
  7. package/lib/app/handlers/repo-actions.js +0 -1
  8. package/lib/app/handlers/repos.js +137 -10
  9. package/lib/app/handlers/settings.js +34 -15
  10. package/lib/app/index.js +1 -1
  11. package/lib/app/inject-text.js +3 -18
  12. package/lib/app/schema.js +20 -10
  13. package/lib/app/settings-bridge.js +60 -8
  14. package/lib/app/tool-call.js +26 -22
  15. package/lib/cli/commands-vcs.mjs +35 -1
  16. package/lib/cli/shared.mjs +1 -1
  17. package/lib/client/index.js +11 -16
  18. package/lib/client-parts/git/account.js +21 -12
  19. package/lib/client-parts/git/actions.js +23 -77
  20. package/lib/client-parts/git/apply.js +8 -2
  21. package/lib/client-parts/git/browser.js +1 -1
  22. package/lib/client-parts/git/const.js +33 -1
  23. package/lib/client-parts/git/controller.js +175 -176
  24. package/lib/client-parts/git/icons.js +1 -1
  25. package/lib/client-parts/git/loader.js +1 -1
  26. package/lib/client-parts/git/npm.js +56 -37
  27. package/lib/client-parts/git/page.js +53 -1
  28. package/lib/client-parts/git/repo.js +8 -1
  29. package/lib/client-parts/git/settings.js +13 -1
  30. package/lib/client-parts/git/state.js +237 -0
  31. package/lib/client-parts/git/utils.js +1 -1
  32. package/lib/client.js +631 -312
  33. package/lib/commit-push/pre-commit-engine.js +584 -32
  34. package/lib/commit-push.js +63 -47
  35. package/lib/context/index.js +7 -5
  36. package/lib/core/config.js +1 -27
  37. package/lib/core/exec.js +2 -11
  38. package/lib/git/identity-rewrite.js +1 -1
  39. package/lib/git/index.js +1 -1
  40. package/lib/git/push.js +2 -17
  41. package/lib/git/repo-index.js +8 -3
  42. package/lib/npm/install.js +1 -1
  43. package/lib/npm/registry.js +2 -2
  44. package/lib/plugin/auto-push.js +3 -6
  45. package/lib/preprocess/providers.js +5 -1
  46. package/lib/self/index.js +1 -1
  47. package/package.json +4 -7
  48. package/skills/dev/dsh-git-push.md +9 -9
  49. package/skills/guide/guide-commit-push.md +11 -13
  50. package/skills/workflow/README.md +0 -1
  51. package/skills/workflow/task-completion-report.md +2 -2
  52. package/.auditignore +0 -30
  53. package/.gitignore +0 -43
  54. package/lib/BUGFIX-NOTES-2026-09-14.md +0 -278
  55. package/lib/app/schema-preprocess.js +0 -42
  56. package/lib/user-requirements.json +0 -15
  57. package/scripts/build-client.mjs +0 -133
  58. package/scripts/bump-version.mjs +0 -178
  59. package/scripts/check.mjs +0 -205
  60. package/scripts/doc-func.mjs +0 -212
  61. package/scripts/doc-tree.mjs +0 -458
  62. package/scripts/doc-version.mjs +0 -149
  63. package/scripts/local-registry.mjs +0 -38
  64. package/scripts/scan-version.mjs +0 -125
  65. package/scripts/version-source.mjs +0 -173
package/README.md CHANGED
@@ -1,32 +1,39 @@
1
1
  # dsh-git-push
2
2
 
3
- DSH 的 git 提交推送与代码审计插件:提交前自动过审计门禁,提交、推送、发包一条命令完成。
3
+ DSH 的 **git 提交推送插件**:提交、推送、克隆、账号校验、仓库扫描与 npm 发布,一个工具搞定。
4
+
5
+ 提交前可选跑「预处理门禁」:本插件只负责"跑一个命令、按退出码决定放行还是拦截",
6
+ 检查内容由可插拔的 provider 决定(审计由独立包 `audit-sluice` 提供)。
4
7
 
5
8
  ## 功能
6
9
 
7
10
  | 功能 | 做什么 | 入口 |
8
11
  |---|---|---|
9
- | 提交推送 | 审计通过后提交并推送,支持 dry-run / force / 指定 remote | `git_commit_push` / `commit` |
12
+ | 提交推送 | 提交并推送;支持 dry-run / force / 指定 remote / 精确路径 | `git_commit_push` / `commit` |
10
13
  | 仓库扫描 | 列出仓库的未提交、未推送、分叉与近期活动 | `git_scan` / `scan` |
11
- | 代码审计 | 静态检查 + 质量评分,diff 或全量两种范围 | `code_audit` / `audit` / `/git-audit` |
12
- | 历史提交审计 | 逐提交回放审计并落盘报告 | `code_audit --history` / `audit --history` |
13
14
  | 克隆仓库 | 按 owner/repo 克隆到指定目录 | `git_clone` / `clone` |
14
15
  | 克隆预演 | 只看将拉取什么,不落盘 | `git_clone_preview` / `clone-preview` |
15
16
  | 建远端仓 | 给本地仓库建远端并设置 origin | `git_remote_create` / `remote-create` |
16
17
  | 可见性 | 切换仓库 public / private | `git_set_visibility` / `set-visibility` |
17
18
  | 改名 | 给远程仓库改名(dryRun 默认开,列出旧名出现位置) | `git_remote_rename` / `rename` |
18
- | 凭据与账号 | 校验 GitHub token 与 SSH 公钥、生成密钥对 | `git_account_check` / `git_gen_ssh_key` |
19
+ | 凭据与账号 | 校验 GitHub token 与 SSH 公钥、生成密钥对、导出凭据环境变量 | `git_account_check` / `git_gen_ssh_key` / `git_cred_env` |
19
20
  | 身份改写 | 把历史提交身份统一成登录账号 | `git_identity_rewrite` / `identity-rewrite` |
20
- | 发布 | 发布 npm 包(dryRun 默认只体检;凭据由插件托管,无需 npm login)。**网络边界**:dryRun 会 GET 真实上游查版本占用(只读),但绝不写入公共 registry;`localPreview=true` 全程不碰公网 | `npm_publish` / `npm-publish` |
21
+ | 发布 | 发布 npm 包(dryRun 默认只体检;凭据由插件托管,无需 npm login) | `npm_publish` / `npm-publish` |
21
22
  | 撤包 | 从 registry 撤版本(默认 dryRun 预检,不可逆) | `npm_unpublish` / `unpublish` |
22
- | 豁免标记 | 给文件加/删豁免注释并校验是否真生效 | `exempt` |
23
- | I/O 风险扫描 | 扫描读写操作的风险分级 | `io_scan` / `file-io` |
24
- | 链接检查 | 检查文档里的 URL 是否有效 | `link_check` / `link-check` |
25
- | 拼接产物作用域 | 查分片拼成单文件后同一作用域内的重名(后者静默顶掉前者) | `scope_check` / `scope-check` |
26
- | 巨型文件拆分 | 按顶层块拆分单文件并校验导出一致 | `module_splitter` / `module-splitter` |
27
23
  | git 透传 | 执行任意 git 命令,凭据自动注入 | `git_sluice` / `git` |
28
- | HTTP 接口直调 | 调用本插件的全部 HTTP 接口 | `git_api` / `api` |
29
- | 审计结果查询 | 按规则/文件/严重级/规则包聚合审计结果 | `GET /api/git-push/audit` |
24
+ | HTTP 接口直调 | 调用本插件的 HTTP 接口 | `git_api` / `api` |
25
+ | 预处理动作 | 转发到声明该动作的 provider(审计/静态检查等) | `git-sluice preprocess <action>` |
26
+ | 静态检查类工具 | `code_audit`(含 `history=true` 逐提交回放)/ `io_scan` / `link_check` / `scope_check` / `exempt`——**实现由 `audit-sluice` 提供,需安装** | 同名工具 |
27
+
28
+ ## 提交前检查(可选,独立包实现)
29
+
30
+ 检查逻辑不在本插件里——由独立包 **`audit-sluice`** 提供(`npm install audit-sluice`)。
31
+ 装上后本插件自动发现它;**不装也能正常用**,只是不做提交前检查,返回值里会标注"预处理未执行"。
32
+
33
+ ```bash
34
+ audit-sluice audit --repo <路径> --scope diff --json # 也能脱离本插件独立跑:stdout 单行 JSON,exit 0|1|2
35
+ audit-sluice config # 它的配置(扫描范围/文件上限/禁用规则包/权重)
36
+ ```
30
37
 
31
38
  ## 环境要求
32
39
 
@@ -38,82 +45,103 @@ DSH 的 git 提交推送与代码审计插件:提交前自动过审计门禁
38
45
 
39
46
  ### 侧边栏面板
40
47
 
41
- - **账号信息**:GitHub 与 npm 账号状态、凭据与 SSH 公钥
42
- - **审计面板**:规则包启停、排序、命中数
43
- - **设置**:审计开关、扫描范围、评分权重、自动推送开关
48
+ - **账号信息**:GitHub 与 npm 账号状态、凭据与 SSH 公钥、本地/云端仓库列表
49
+ - **设置**:凭据与密钥、推送通道、推送门禁、自动推送、**提交前预处理开关**(其余审计项归 `audit-sluice` 自己的配置)
44
50
 
45
51
  ### 聊天框指令
46
52
 
47
53
  ```
48
- /git-audit # 审计当前仓库(默认 diff 范围)
49
- /git-audit --full # 全量审计
50
- /link-check # 检查文档里的链接
54
+ /git-scan # 扫描工作区里的 git 仓库
55
+ /git-account # 校验 GitHub 账号与凭据
56
+ /git-clone-preview <owner/repo> # 克隆预演
51
57
  ```
52
58
 
53
59
  ### AI 工具
54
60
 
55
61
  ```js
56
62
  git_scan({ root }) // root 可空:空=自动识别家目录
57
- code_audit({ repo, scope, includeFindings }) // repo 必填;scope 可空(空=full);includeFindings 可空(空=精简输出)
58
- git_commit_push({ message, repo, push, dryRun }) // message 必填;repo 可空(空=当前目录);push 可空(空=推送);dryRun 可空(空=真提交)
59
- git_clone({ target, dest, branch, history }) // target 必填(owner/repo 或完整 URL);dest 可空(空=工作区根);history 可空(空=整树快照)
60
- git_clone_preview({ target, branch }) // target 必填;branch 可空(空=默认分支)
61
- git_api({ path, method, query, body }) // path 可空(空=列出全部接口);method 可空(空=GET)
63
+ git_commit_push({ repo, message, push, dryRun }) // repo/message 必填;其余可空
64
+ git_clone({ target, dest, branch, history }) // target 必填(owner/repo 或完整 URL)
65
+ git_clone_preview({ target, branch }) // target 必填;branch 可空
66
+ git_api({ path, method, query, body }) // path 可空(空=列出全部接口)
62
67
  git_sluice({ args }) // args 必填:与 git 一致的参数串
63
68
  git_account_check({ token, sshPub }) // 两者都可空:不传则自动解析本机凭据
64
- git_gen_ssh_key({ email, force }) // email 必填;force 可空(空=已存在时不覆盖)
65
- git_identity_rewrite({ paths, dryRun, write, push }) // 全可空:dryRun 默认只报告,write 才改写
66
- git_remote_create({ repo, visibility, dryRun }) // repo 必填;visibility 可空(空=private)
69
+ git_cred_env({}) // 输出凭据环境变量前缀(不含明文)
70
+ git_gen_ssh_key({ email, force }) // email 必填
71
+ git_identity_rewrite({ paths, dryRun, write, push }) // 全可空:dryRun 默认只报告
72
+ git_remote_create({ repo, visibility, dryRun }) // repo 必填
67
73
  git_set_visibility({ repo, visibility }) // 两者必填
68
74
  npm_publish({ dir, dryRun, confirm, tag, otp }) // dryRun 默认 true(只体检,不写 registry)
69
- npm_publish({ dir, localPreview: true }) // 本地 registry 彩排:publish→install→加载全走本机,全程不碰公网
70
- exempt({ action, rule, path, scope, line, reason }) // action 与 rule 必填;path 可数组;scope=header(文件头)或 line
71
- io_scan({ repo, writeOnly }) // 两者都可空:writeOnly 空=读写都看
72
- link_check({ path }) // path 可空:空=整个工作区
73
- scope_check({ files, repo, prefix, allowlist, topLevelMustBeEmpty }) // 全可空:files 空=读项目 dshScopeCheck.files;prefix 空=按项目契约
74
- module_splitter({ command, file, plan, dryRun }) // command 必填(analyze/split/verify);dryRun 可空
75
+ npm_unpublish({ name, version, dryRun, confirm }) // dryRun 默认 true
76
+ // 以下需安装 audit-sluice(未装时返回可诊断错误,不影响其他工具)
77
+ code_audit({ repo, scope, includeFindings })
78
+ io_scan({ repo, writeOnly })
79
+ link_check({ path })
80
+ scope_check({ files, repo, prefix, allowlist, topLevelMustBeEmpty })
81
+ exempt({ action, rule, path, scope, line, reason })
75
82
  ```
76
83
 
77
- ### 独立 CLI(git-sluice)
84
+ ### 提交前预处理链(可选)
85
+
86
+ `preCommit.stages` 按数组顺序跑多个阶段(如"先格式化、再审计");也可以**按次**用工具参数
87
+ `preprocessStages` 覆盖配置(优先级更高):
88
+
89
+ ```js
90
+ git_commit_push({
91
+ repo, message,
92
+ preprocessStages: [
93
+ { command: 'node', args: ['tools/fmt.mjs', '{filesFile}'], onFail: 'warn' },
94
+ { provider: 'audit', onFail: 'block' },
95
+ ],
96
+ })
97
+ ```
98
+
99
+ 每阶段可用 `{repo}` / `{filesFile}` / `{filesCount}` / `{stage}` 占位符,宿主同时注入
100
+ `PREPROCESS_REPO` / `PREPROCESS_CHANGED_FILES` 等环境变量。回执里 `preprocessStages` / `preprocessChanges` /
101
+ `stagesSource` 如实反映"哪个阶段改了什么、本次链来自参数还是配置"。契约见 [docs/SPEC.md](docs/SPEC.md) 第十七章。
102
+
103
+ ### 独立 CLI
78
104
 
79
105
  ```
80
106
  git-sluice account-check # 校验本机 GitHub 凭据
81
107
  git-sluice scan <目录> # 列出该目录下的 git 仓库
82
- git-sluice commit <仓库> --message "msg" # 提交并推送(自动过审计门禁)
108
+ git-sluice commit <仓库> --message "msg" # 提交(默认只 commit;--push 推远端)
109
+ git-sluice preprocess <action> ... # 转发到 provider(如 audit / io_scan / link_check)
83
110
  git-sluice help # git 侧全部命令
84
111
 
85
- audit-sluice audit <仓库> --full # 全量审计(加 --json 拿明细)
86
- audit-sluice scope-check [文件] # 查拼接产物同帧重名(无参数时读项目 dshScopeCheck.files)
87
- tool-sluice self-check # 三入口 HELP/参数/命令集一致性自检
112
+ tool-sluice self-check # 两入口 HELP/参数/命令集一致性自检
88
113
  ```
89
114
 
90
115
  ## API
91
116
 
92
- 38 个端点,统一前缀 `/api/git-push/`。常用:
117
+ 统一前缀 `/api/git-push/`(git 侧与共享),预处理侧统一前缀 `/api/preprocess/`。常用:
93
118
 
94
119
  | 端点 | 做什么 |
95
120
  |---|---|
96
121
  | `GET /api/git-push/status` | 插件状态与配置概览 |
97
122
  | `GET /api/git-push/scan` | 仓库扫描结果 |
98
- | `GET /api/git-push/audit` | 审计结果(支持 scope / groupBy / severity / top) |
99
- | `GET /api/git-push/repos` | 本地仓库列表 |
123
+ | `GET /api/git-push/repos-local` | 本地仓库列表(默认只读索引快照,毫秒级;`?live=1` 才同步探测远端) |
100
124
  | `GET /api/git-push/account-status` | 账号状态快照 |
101
- | `POST /api/git-push/credentials` | 写入凭据 |
125
+ | `POST /api/git-push/settings-set` | 写单个设置键 |
102
126
  | `GET /api/git-push/tools` | 工具清单 |
127
+ | `GET /api/preprocess/<action>` | 预处理端点(动作清单来自各 provider 的 manifest) |
103
128
 
104
129
  ```bash
105
- # 审计一个仓库(按规则聚合)
106
- curl "http://<本机IP>:<端口>/api/git-push/audit?repo=<仓库绝对路径>&scope=diff&groupBy=rule"
107
-
108
- # 列出全部可用接口
130
+ # 预处理动作清单
109
131
  curl "http://<本机IP>:<端口>/api/git-push/api"
132
+
133
+ # 审计结果(需安装 audit-sluice)
134
+ curl "http://<本机IP>:<端口>/api/preprocess/audit?repo=<仓库绝对路径>&scope=diff&groupBy=rule"
110
135
  ```
111
136
 
112
137
  ## 文档索引
113
138
 
114
- - [docs/SPEC.md](docs/SPEC.md) — 规格唯一入口(工具、接口、设置键、数据文件、规则体系)
115
- - [docs/功能-审计引擎.md](docs/功能-审计引擎.md) — 审计引擎(规则体系、判定、评分、委托层、豁免)
139
+ - [docs/SPEC.md](docs/SPEC.md) — 规格唯一入口(工具、接口、设置键、数据文件、与 audit-sluice 的耦合面)
116
140
  - [docs/功能-发布与工具链.md](docs/功能-发布与工具链.md) — 提交推送、克隆、npm 发布、仓库索引、文档生成
141
+ - [docs/PERF-BASELINE.md](docs/PERF-BASELINE.md) — git 侧性能基线
142
+ - [docs/PLAN-UI状态工厂.md](docs/PLAN-UI状态工厂.md) — UI 状态层改造计划与交付记录
117
143
  - [docs/FILE-TREE.md](docs/FILE-TREE.md) — 目录结构(自动生成)
118
144
  - [docs/CHANGELOG.md](docs/CHANGELOG.md) — 版本列表(自动生成)
119
145
  - [docs/FUNCTIONS.md](docs/FUNCTIONS.md) — 函数列表(自动生成)
146
+
147
+ 审计实现文档(规则体系、评分、豁免、性能基线)属独立包,见 `audit-sluice` 仓库的 `docs/`。
package/cli.mjs CHANGED
@@ -39,7 +39,8 @@ export const KNOWN_FLAGS = [
39
39
  '--confirm', '--depth', '--dest', '--dry-run', '--extra-emails', '--extra-repos-file', '--force', '--history',
40
40
  '--history-depth', '--ignore-patterns', '--json', '--local-preview', '--max', '--message', '--message-items',
41
41
  '--method', '--no-dry-run', '--no-push', '--offline', '--otp', '--owner', '--paths', '--push',
42
- '--push-confirmed', '--push-initial', '--query', '--remote', '--requirements-confirmed', '--root',
42
+ '--push-confirmed', '--push-initial', '--query', '--remote', '--root',
43
+ '--preprocess-stages',
43
44
  '--skip-smoke', '--ssh-pub', '--tag', '--token', '--update-remotes', '--visibility', '--wait-ci',
44
45
  '--wait-visible', '--whole-package', '--write',
45
46
  ];
@@ -68,9 +69,9 @@ const HELP = `git-sluice v${VERSION} — ${CLI_ENTRIES[CLI_GIT].intro}
68
69
  同上,可读文本通道(scan 是它的注册表通道,输出更精简)
69
70
  git-sluice index <root> [--owner <账号>] [--depth N] [--max N] [--offline] [--json]
70
71
  重建仓库索引 dsh-repo-index.json(--offline=纯离线不查 GitHub API)
71
- 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]
72
+ git-sluice commit <repo> --message <msg> [--push|--no-push] [--audit] [--dry-run] [--force] [--ignore-patterns <模式>] [--push-confirmed] [--paths <路径1,路径2>] [--message-items <JSON>] [--preprocess-stages <JSON|@文件>] [--audit-exempt-paths <文件,...>] [--audit-exempt-reason <理由>] [--remote <名>] [--wait-ci] [--ci-timeout-sec N]
72
73
  审计门禁 → 提交(默认只 commit 不 push;--push 推远端;--force 强推覆盖远端历史;
73
- --requirements-confirmed 显式核对开发者要求;--push-confirmed 显式放行推送门禁;
74
+ --push-confirmed 显式放行推送门禁;
74
75
  --paths 精确 add 指定文件替代 add -A;--audit-exempt-paths 本次提交按文件临时豁免审计)
75
76
  git-sluice clone <owner/repo> [dest] [--dest <目录>] [--branch <名>] [--history] [--history-depth N]
76
77
  从 GitHub 克隆仓库(Git Data API 通道,不直连 github.com;--history=重建真实提交历史)
package/lib/app/apply.js CHANGED
@@ -15,14 +15,13 @@ import { loadDefineTool, registerTools, registerContext, registerHttp, registerP
15
15
  // (settings 服务改为 SettingsForms:describe/update/replace/mutate/configure,命名空间由
16
16
  // Loader 条目派生)。本插件改为「特性检测自动切换」:旧宿主走 register 分支、0.2.0 走
17
17
  // describe 分支,故 GIT_PUSH_SETTINGS_NS(命名空间名)与 Config(旧分支注册用 schema)
18
- // 两个 import 仍需保留。按 comment-not-delete 保留原行注释,便于回退与对照。
19
- // 【原代码】import { GIT_PUSH_SETTINGS_NS, name } from './constants.js';
20
18
  import { GIT_PUSH_SETTINGS_NS } from './constants.js';
21
19
  import { PREPROCESS_API_PREFIX, adaptHttpHandler } from './http-handlers.js';
22
20
  import { readSettings, applySettingsToCfg, writeSettingsKey } from './settings-bridge.js';
23
- import { FUNCTION_USAGE_HINT, README_CHECK_HINT, buildRequirementsInjectionText } from './inject-text.js';
24
- // 【原代码】import { Config } from './schema.js';
21
+ import { FUNCTION_USAGE_HINT, README_CHECK_HINT, buildIdentityInjectionText } from './inject-text.js';
25
22
  import { Config } from './schema.js';
23
+ // 提交前预处理开关的生效值
24
+ import { resolvePreCommitEnabled } from '../commit-push/pre-commit-engine.js';
26
25
  import { callTool } from './tool-call.js';
27
26
  import { listTools } from './tools.js';
28
27
  import { registerSlashCommands } from './slash-commands.js';
@@ -34,7 +33,7 @@ import { join } from 'node:path';
34
33
  // (agent/pre-step,registerPreStepInjection,见下方 2.5 步);systemPrompt 只留三段。
35
34
  const ORDER_USAGE = 990; // 功能用法(工具清单 + 凭据托管说明)
36
35
  const ORDER_README_CHECK = 991; // 提交前必须核对 README 的提醒
37
- const ORDER_REQUIREMENTS = 992; // 开发者要求清单(提交前逐条核对)
36
+ const ORDER_IDENTITY = 992; // 身份告知(避免 AI 猜错项目归属)
38
37
 
39
38
  /**
40
39
  * 插件应用入口(DSH 调用)。
@@ -149,8 +148,8 @@ export async function apply(ctx, config = {}) {
149
148
  // 功能用法(插件每个工具怎么用 + 凭据托管说明)
150
149
  { name: 'dsh-git-push-usage', order: ORDER_USAGE, text: () => (cfg.injectSystemPrompt ? (cfg.injectUsageText || FUNCTION_USAGE_HINT) : '') }, // injectUsageText 配置覆盖默认注入文本
151
150
  { name: 'dsh-git-push-readme-check', order: ORDER_README_CHECK, text: () => (cfg.injectSystemPrompt ? README_CHECK_HINT : '') },
152
- // 开发者要求清单(子开关:注入总开关 且 提交前审计 且 injectRequirements 才注入)
153
- { name: 'dsh-git-push-requirements', order: ORDER_REQUIREMENTS, text: () => (cfg.injectSystemPrompt && cfg.auditEnabled && cfg.injectRequirements ? buildRequirementsInjectionText() : '') },
151
+ // 身份告知注入(只受「注入系统提示词」总开关控制)
152
+ { name: 'dsh-git-push-identity', order: ORDER_IDENTITY, text: () => (cfg.injectSystemPrompt ? buildIdentityInjectionText() : '') },
154
153
  ],
155
154
  log,
156
155
  });
@@ -244,7 +243,7 @@ export async function apply(ctx, config = {}) {
244
243
  if (!next || typeof next !== 'object') return;
245
244
  // watch **只处理凭据**。开关/扫描范围/权重真源是插件私有
246
245
  // config.json(启动 merge + HTTP settings-set)。yaml 缺键时 schema 默认
247
- // injectRequirements=false,若把 yaml 整包灌进 cfg 会把 HTTP 刚写入的
246
+ // injectSystemPrompt=false,若把 yaml 整包灌进 cfg 会把 HTTP 刚写入的
248
247
  // true 盖回去——开关点了不对的根因。
249
248
  if (typeof next.githubToken === 'string' && next.githubToken.trim()) {
250
249
  cfg.githubToken = next.githubToken.trim();
@@ -287,7 +286,10 @@ export async function apply(ctx, config = {}) {
287
286
  // 6) 客户端(设置卡片/侧边栏)不在 Host 注册:DSH 依据 package.json 的
288
287
  // dsh.client + exports["./client"] 自动发现 client.js。
289
288
 
290
- log?.info?.(`dsh-git-push v${VERSION} 已接线(工具 ${toolCount} 个 / 注入 ${sectionCount} 段 + ${preStepWired ? '上下文注入' : '上下文注入未接'} / HTTP ${httpWired ? '已注册' : '未注册'} / 斜杠 ${slashCount};审计默认${cfg.auditEnabled ? '开' : '关'} / 自动推送${autoPush.enabled ? '开(触发: ' + autoPush.trigger + ')' : '关'})`);
289
+ // 开关状态读生效值(resolvePreCommitEnabled 会把 config.json 里的真值算进来),
290
+ // 不直接读 cfg.preCommit.enabled:那只是 schema 默认值,会把「配置里其实开着」误报成关。
291
+ const preCommitState = resolvePreCommitEnabled(cfg);
292
+ log?.info?.(`dsh-git-push v${VERSION} 已接线(工具 ${toolCount} 个 / 注入 ${sectionCount} 段 + ${preStepWired ? '上下文注入' : '上下文注入未接'} / HTTP ${httpWired ? '已注册' : '未注册'} / 斜杠 ${slashCount};提交前预处理${preCommitState.enabled ? '开' : '关'}${preCommitState.source === 'legacy' ? '(沿用旧版开关键)' : ''} / 自动推送${autoPush.enabled ? '开(触发: ' + autoPush.trigger + ')' : '关'})`);
291
293
  // 【修复 】cordis 的 apply 返回值只能是 disposer 函数 / Promise / undefined;
292
294
  // 返回普通对象会抛 "Invalid effect" 导致插件树加载失败。插件内部注册均走 ctx.inject,
293
295
  // 生命周期由 cordis 管理,因此 apply 返回 undefined(标准写法)。
@@ -56,7 +56,7 @@ export const TOOL_REGISTRY = [
56
56
  ],
57
57
  },
58
58
  {
59
- name: 'git_commit_push', cli: 'commit', description: '一键提交并推送:一次调用 = 审计(blocker 拦截,可关)→ 有改动才 commit → 有可推内容才 push。零改动是**正常成功路径**:返回 ok:true + committed:false(job 状态 completed,不是失败);远端已最新则 ok:true + pushed:false;本地领先远端的已提交内容照样会推。message 必填(零改动时用不到);requirementsConfirmed=true(开发者要求全部核对达标)——**存在要求清单时任何调用都要带**(与有无改动、是否推送无关);push=false 只提交;dryRun 只模拟',
59
+ name: 'git_commit_push', cli: 'commit', description: '一键提交并推送:一次调用 = 审计(blocker 拦截,可关)→ 有改动才 commit → 有可推内容才 push。零改动是**正常成功路径**:返回 ok:true + committed:false(job 状态 completed,不是失败);远端已最新则 ok:true + pushed:false;本地领先远端的已提交内容照样会推。message 必填(零改动时用不到);push=false 只提交;dryRun 只模拟',
60
60
  // params 用函数形态:git 侧不写死审计层参数,审计可用时由预处理贡献(见文件头 AUDIT_COMMIT_PARAMS)
61
61
  params: (cfg, hasBuiltinEngine) => [
62
62
  { flag: 'repo', type: 'string', positional: 0, required: true, desc: '仓库绝对路径' },
@@ -69,9 +69,11 @@ export const TOOL_REGISTRY = [
69
69
  { flag: 'dryRun', type: 'boolean', desc: 'dry-run 只模拟不写入' },
70
70
  { flag: 'force', type: 'boolean', desc: 'force 强推(谨慎)' },
71
71
  { flag: 'ignorePatterns', type: 'string', desc: '自定义忽略 pattern(追加 .gitignore)' },
72
- { flag: 'requirementsConfirmed', type: 'boolean', desc: '已核对开发者要求' },
73
72
  { flag: 'pushConfirmed', type: 'boolean', desc: '推送门禁放行' },
74
73
  { flag: 'paths', type: 'string', desc: '精确 add 路径(逗号分隔)' },
74
+ // 本次调用的预处理链(覆盖配置文件里的 preCommit.stages)。
75
+ // 元素两种形态:{command,args?,onFail?,timeoutMs?} 跑任意脚本,或 {provider,onFail?,timeoutMs?} 走 provider 解析。
76
+ { flag: 'preprocessStages', type: 'array', desc: '本次调用的预处理阶段链(数组顺序即执行顺序,覆盖配置):元素为 {command,args?,onFail?,timeoutMs?} 或 {provider,onFail?,timeoutMs?};onFail=block|warn|skip(缺省 block);args 支持占位符 {repo}/{filesFile}/{filesCount}/{stage}' },
75
77
  { flag: 'remote', type: 'string', desc: '推送目标 remote(多 remote / fork 场景;缺省 origin)。推送与核验使用同一 remote' },
76
78
  { flag: 'waitCi', type: 'boolean', desc: '推送后等 CI 结果(默认不等):按推送的 sha 查 GitHub Actions,全绿=通过、任一失败=ciFailed、超时/无 CI 如实回报' },
77
79
  { flag: 'ciTimeoutSec', type: 'number', desc: '等 CI 的上限秒数(默认 900)' },
@@ -3,6 +3,14 @@
3
3
  */
4
4
  /** 本地列表 SSH live 探测整表共享预算(并发异步后为**上界**,超预算即跳过标 liveSkipped)。 */
5
5
  export const LIST_LIVE_BUDGET_MS = 15_000;
6
+ /**
7
+ * 远端状态的"新鲜期":超过它就在**后台**补查一次(请求本身只读索引,不联网)。
8
+ *
9
+ * 为什么要有这个数:列表接口把 27 次 SSH 内联在请求里时实测耗时 87s(前端 30s 必超时),
10
+ * 于是"打开本地页"= 报错。现在请求只返回索引快照,远端状态由后台补 —— 这个 TTL
11
+ * 决定"多久需要补一次",取 5 分钟:足够覆盖人工操作节奏,又不会让 ahead/behind 长期陈旧。
12
+ */
13
+ export const LIST_LIVE_TTL_MS = 5 * 60_000;
6
14
  /** 远端探测并发度。与 SSH 默认 MaxSessions 兼容,且不超过 GitHub 连接容忍度。 */
7
15
  export const PROBE_CONCURRENCY = 4;
8
16
  /**
@@ -34,16 +34,13 @@ export async function listRuleSlots(order, disabledSlots = [], hitStats = null)
34
34
 
35
35
  /** GET /api/preprocess/rule-slots */
36
36
  export async function handleRuleSlots(ctx) {
37
- const { cfg } = ctx;
38
37
  return withHostApi(async (api) => ({
39
38
  status: 200,
40
39
  body: {
41
40
  ok: true,
42
- slots: api.listRuleSlots(
43
- cfg.auditRuleOrder,
44
- Array.isArray(cfg.auditDisabledSlots) ? cfg.auditDisabledSlots : [],
45
- api.getLastSlotHitStats(),
46
- ),
41
+ // 顺序与禁用清单都不再由宿主决定:两个参数留空,由审计包按自己的配置/yml 决定。
42
+ // 宿主传空数组会被理解成「显式不禁用任何规则包」,反而覆盖掉用户在包里配的禁用项。
43
+ slots: api.listRuleSlots(undefined, undefined, api.getLastSlotHitStats()),
47
44
  },
48
45
  }));
49
46
  }
@@ -104,7 +104,6 @@ export async function handleRepoCommit(ctx) {
104
104
  message,
105
105
  push: false,
106
106
  audit: true,
107
- requirementsConfirmed: true,
108
107
  pushMethod: cfg.pushMethod || 'ssh',
109
108
  pushGate: false,
110
109
  pushConfirmed: true,
@@ -16,11 +16,15 @@ import {
16
16
  } from '../../git/repo-index.js';
17
17
  import { runScan, waitScanDelta } from '../../git/index.js';
18
18
  import { getDefaultScanRoot } from '../scan-root.js';
19
- import { LIST_LIVE_BUDGET_MS, PROBE_CONCURRENCY, SCAN_WAIT_TIMEOUT_MS } from './http-constants.js';
19
+ import { LIST_LIVE_BUDGET_MS, LIST_LIVE_TTL_MS, PROBE_CONCURRENCY, SCAN_WAIT_TIMEOUT_MS } from './http-constants.js';
20
20
 
21
21
  /** GET/POST /api/git-push/repos-local —— 本地仓库列表(读索引 + live 并发探测远端)。 */
22
22
  /** 构建本地仓库列表(读索引 → 本地路径探测 → 标记待 remote live 探测)。 */
23
- function buildLocalList(indexMap, root, deadline) {
23
+ function buildLocalList(indexMap, root, deadline, options) {
24
+ // probeLocal=false ⇒ **不 spawn 任何 git**,本地状态取索引里上次扫描/补查记下的快照。
25
+ // 为什么必须能关:这里每仓要跑 describeRepo + git log(4 次同步 spawn),
26
+ // 27 仓在 CIFS 上实测 ≈100s —— 放进 HTTP 请求就等于"打开列表必超时"。
27
+ const probeLocal = !(options && options.probeLocal === false);
24
28
  return Object.keys(indexMap).map((name) => {
25
29
  const entry = indexMap[name];
26
30
  const local = entry.path || join(root, name);
@@ -38,7 +42,16 @@ function buildLocalList(indexMap, root, deadline) {
38
42
  cloudOnly: !!entry.cloudOnly,
39
43
  branch: '', ahead: null, behind: null, changed: 0, lastCommit: '',
40
44
  };
41
- if (exists) {
45
+ // 索引里上次记下的本地状态(扫描/后台补查写入):请求路径直接用它,零 spawn
46
+ const cachedLocal = (entry.localState && typeof entry.localState === 'object') ? entry.localState : null;
47
+ if (cachedLocal) {
48
+ out.branch = cachedLocal.branch || '';
49
+ out.changed = Number(cachedLocal.changed) || 0;
50
+ out.lastCommit = cachedLocal.lastCommit || '';
51
+ out.localHead = cachedLocal.localHead || cachedLocal.lastCommit || '';
52
+ out.localHeadAt = cachedLocal.localHeadAt || '';
53
+ }
54
+ if (exists && probeLocal) {
42
55
  try {
43
56
  const repoState = describeRepo(local);
44
57
  out.branch = repoState.branch || '';
@@ -133,7 +146,74 @@ async function applyLiveRemote(list, deadline) {
133
146
  return list;
134
147
  }
135
148
 
136
- /** GET/POST /api/git-push/repos-local —— 本地仓库列表(读索引 + live 并发探测远端)。 */
149
+ /**
150
+ * 用索引里**上次补查到的远端状态**填充列表(纯本地计算,不联网)。
151
+ *
152
+ * 为什么要这么做:ahead/behind 只需要一个已知的远端 sha(本地 rev-list 就能算),
153
+ * 不需要再连一次远端。于是"列表请求"的代价 = 读索引 + 每仓一次本地 git,
154
+ * 与仓库数量线性但都是毫秒级;真正的网络探测交给后台。
155
+ *
156
+ * 没补过的仓库保持 liveSkipped=true(= 真未知,前端据此显示"同步中"而不是"0/0")。
157
+ * @param {Array<object>} list buildLocalList 的输出
158
+ * @returns {{liveAt: string, stale: boolean}} liveAt=最新一次远端状态时间
159
+ */
160
+ function mergeCachedRemote(list) {
161
+ let newestAt = 0;
162
+ let unknown = 0;
163
+ for (const row of list) {
164
+ const entry = row.indexed || {};
165
+ if (!row.path || !row.hasRemote) continue;
166
+ if (!entry.remoteHead) { row.liveSkipped = true; unknown += 1; continue; }
167
+ row.remoteHead = entry.remoteHead;
168
+ row.remoteHeadAt = entry.remoteHeadAt || '';
169
+ // ahead/behind 直接用索引里上次比较的结果 —— **不在请求路径 spawn git**
170
+ // (每个 spawn 在 CIFS 上 ≈1s,27 仓就能把 500ms 目标打成 100s)
171
+ if (entry.ahead === null || entry.ahead === undefined || entry.behind === null || entry.behind === undefined) {
172
+ row.ahead = null; row.behind = null; row.synced = false; row.liveSkipped = true;
173
+ } else {
174
+ row.ahead = Number(entry.ahead) || 0;
175
+ row.behind = Number(entry.behind) || 0;
176
+ row.synced = entry.synced === true;
177
+ }
178
+ const at = Date.parse(entry.remoteHeadAt || '');
179
+ if (Number.isFinite(at) && at > newestAt) newestAt = at;
180
+ }
181
+ const liveAt = newestAt ? new Date(newestAt).toISOString() : '';
182
+ const missingLocal = list.filter((r) => r.path && !r.lastCommit).length;
183
+ const tooOld = !newestAt || (Date.now() - newestAt) > LIST_LIVE_TTL_MS;
184
+ return { liveAt: liveAt, stale: tooOld || unknown > 0 || missingLocal > 0 };
185
+ }
186
+
187
+ /** 同一时刻只跑一个后台补查任务(多开页面/连续刷新不叠加探测)。 */
188
+ let liveRefreshRunning = false;
189
+
190
+ /**
191
+ * 后台补查远端状态(不阻塞请求):逐仓探测 → 写回索引 → 下次列表请求就带上了。
192
+ *
193
+ * 为什么放后台:27 仓 × SSH 实测 87s,放在请求里必然把前端 30s 超时打爆。
194
+ * 失败不影响列表:列表继续用上一次的状态,只是 stale 保持为真。
195
+ * @param {Array<object>} list 当前列表(只取有 path+hasRemote 的)
196
+ * @param {object} env 运行环境(workspaceRoot 等)
197
+ * @returns {boolean} 是否真的启动了(已有任务在跑 ⇒ false)
198
+ */
199
+ function scheduleLiveRefresh(list, env) {
200
+ if (liveRefreshRunning) return false;
201
+ const targets = list
202
+ .filter((r) => r.path && (r.hasRemote || !r.lastCommit))
203
+ .map((r) => ({ name: r.name, path: r.path, branch: r.branch || '' }));
204
+ if (!targets.length) return false;
205
+ liveRefreshRunning = true;
206
+ void (async () => {
207
+ try {
208
+ for (const target of targets) await refreshOneTarget(target, env);
209
+ } catch { /* 后台补查失败不影响列表:下一次请求仍会看到 stale 并重试 */ } finally {
210
+ liveRefreshRunning = false;
211
+ }
212
+ })();
213
+ return true;
214
+ }
215
+
216
+ /** GET/POST /api/git-push/repos-local —— 本地仓库列表(**只读索引快照**;远端状态后台补)。 */
137
217
  export async function handleReposLocal(ctx) {
138
218
  const { query, env, cfg } = ctx;
139
219
  const rebuild = query.rebuild === '1' || query.rebuild === 'true';
@@ -148,13 +228,44 @@ export async function handleReposLocal(ctx) {
148
228
  }
149
229
  const indexMap = readRepoIndexMap(env.workspaceRoot);
150
230
  let list = [];
231
+ let liveAt = '';
232
+ let stale = false;
151
233
  if (indexMap) {
152
- const deadline = Date.now() + LIST_LIVE_BUDGET_MS;
153
- list = buildLocalList(indexMap, path, deadline);
154
- await applyLiveRemote(list, deadline);
234
+ if (query.live === '1') {
235
+ // 显式"现在就同步探测"(排障/测试/手动刷新用):沿用原先的预算内并发探测。
236
+ // 默认路径**不走这里** —— 27 仓实测 87s,放在默认请求里必然把前端超时打爆。
237
+ const deadline = Date.now() + LIST_LIVE_BUDGET_MS;
238
+ list = buildLocalList(indexMap, path, deadline);
239
+ await applyLiveRemote(list, deadline);
240
+ stale = false;
241
+ } else {
242
+ // 默认:只读索引快照(不联网),远端状态用上次补查结果,本地即可算 ahead/behind
243
+ list = buildLocalList(indexMap, path, 0, { probeLocal: false });
244
+ const cached = mergeCachedRemote(list);
245
+ liveAt = cached.liveAt;
246
+ stale = cached.stale;
247
+ }
155
248
  if (owner) list = list.filter((r) => (r.indexed?.owner === owner) || !r.indexed?.owner);
249
+ // 远端状态过期/从未补过 ⇒ 交给后台补,请求立刻返回。
250
+ // ⚠️ 必须延到下一个宏任务再启动:补查函数里第一句是**同步** git spawn(runGit 取分支),
251
+ // 直接调会在返回响应前就阻塞住(实测总耗时 3.9s,其中 3.5s 是这句同步 git)。
252
+ if (stale) setTimeout(() => { scheduleLiveRefresh(list, env); }, 0);
156
253
  }
157
- return { status: 200, body: { ok: true, root: path, count: list.length, repos: list, owner: owner || null, indexedAvailable: !!indexMap, indexUpdated: rebuildIndexUpdated === true } };
254
+ return {
255
+ status: 200,
256
+ body: {
257
+ ok: true,
258
+ root: path,
259
+ count: list.length,
260
+ repos: list,
261
+ owner: owner || null,
262
+ indexedAvailable: !!indexMap,
263
+ indexUpdated: rebuildIndexUpdated === true,
264
+ // 远端状态的可见性交给前端:liveAt=上次同步时间,stale=正在后台补
265
+ liveAt: liveAt,
266
+ stale: stale,
267
+ },
268
+ };
158
269
  }
159
270
 
160
271
  export function handleReposLocalScan(ctx) {
@@ -209,8 +320,24 @@ async function refreshOneTarget(t, env) {
209
320
  state.compareOk = false;
210
321
  state.error = live.error || '远端不可达';
211
322
  }
212
- const up = updateRepoIndex({ workspaceRoot: env.workspaceRoot, repoName: name, remoteState: state, mode: 'single' });
213
- return { name, ok: true, remoteState: state, indexUpdated: up.ok, error: up.error };
323
+ // 顺手把**本地状态**一起记进索引:列表请求随后就能零 spawn 地渲染分支/未提交数/最近提交。
324
+ // 不记的话,请求路径只能每仓 describeRepo + git log(CIFS 上每仓 ≈4 次慢 spawn)。
325
+ const localState = (function () {
326
+ try {
327
+ const rs = describeRepo(repoPath);
328
+ const lc = runGit(['log', '-1', '--format=%cI'], { cwd: repoPath });
329
+ return {
330
+ branch: rs.branch || branch || '',
331
+ changed: Number(rs.changed) || 0,
332
+ lastCommit: rs.lastCommit || '',
333
+ localHead: rs.lastCommit || '',
334
+ localHeadAt: lc.ok ? (lc.stdout || '').trim() : '',
335
+ at: new Date().toISOString(),
336
+ };
337
+ } catch { return null; }
338
+ })();
339
+ const up = updateRepoIndex({ workspaceRoot: env.workspaceRoot, repoName: name, remoteState: state, localState: localState, mode: 'single' });
340
+ return { name, ok: true, remoteState: state, localState: localState, indexUpdated: up.ok, error: up.error };
214
341
  } catch (e) {
215
342
  return { name, ok: false, error: String(e?.message || e) };
216
343
  }
@@ -6,37 +6,51 @@
6
6
  * 设置读写走插件私有 config.json(不写公共 settings.yaml,见 settings-bridge.js 说明)。
7
7
  */
8
8
  import { redactConfig } from '../schema.js';
9
- import { readSettings, writeSettingsKey, applySettingsToCfg, appendSettingsLog } from '../settings-bridge.js';
9
+ import { readSettings, writeSettingsKey, writePreCommitEnabled, applySettingsToCfg, appendSettingsLog } from '../settings-bridge.js';
10
10
  import { persistSshPub, persistGithubToken, persistNpmToken } from '../../git/index.js';
11
11
 
12
12
  /** GET /api/git-push/settings-get —— 读插件 config.json 设置快照(token/ssh 掩码)。 */
13
13
  export function handleSettingsGet(ctx) {
14
14
  const { env } = ctx;
15
15
  const snap = readSettings({ workspaceRoot: env.workspaceRoot });
16
- // 同步 apply 后 cfg(settings-set 写盘后内存 cfg 即时更新;读侧也对齐
17
- // ——部分字段如 auditEnabled 在 status/settings-get 都读 cfg,需与内存一致)
18
16
  return { status: 200, body: { ok: true, settings: redactConfig(snap || {}) } };
19
17
  }
20
18
 
21
19
  /** 凭据类设置键:写成功后的回显值必须脱敏(明文只留在 config.json 0600 与凭据文件)。 */
22
20
  const SENSITIVE_SETTING_KEYS = new Set(['githubToken', 'sshPub', 'npmToken']);
23
21
 
22
+ /**
23
+ * 「提交前预处理」总开关的**前端键名**(settings-set 的扁平键)。
24
+ *
25
+ * 为什么需要扁平别名:配置文件里的真身是嵌套的 `preCommit.enabled`(与同块的
26
+ * command/args/timeoutMs 一起构成引擎配置),而 settings-set 的协议是「一个 key 一个 value」。
27
+ * 前端只认这个扁平键,写盘时翻译成嵌套键级合并(见 writePreCommitEnabled),
28
+ * 避免「改开关把同块的引擎路径一起覆盖掉」。
29
+ */
30
+ const PRECOMMIT_ENABLED_KEY = 'preCommitEnabled';
31
+
32
+ /**
33
+ * settings-set 允许写的键(白名单,防越权写入任意字段)。
34
+ *
35
+ * 为什么要显式列全:这条白名单是「前端能改什么」的唯一闸门,少列一个键 = 那个设置
36
+ * 静默存不下来;多列一个键 = 越权面。测试会把它与前端声明逐键比对,改这里必须同步。
37
+ */
38
+ export const ALLOWED_SETTING_KEYS = [
39
+ PRECOMMIT_ENABLED_KEY, 'injectSystemPrompt',
40
+ 'maxCloneFileMB', 'cloneConcurrency',
41
+ 'pushMethod',
42
+ 'githubToken', 'sshPub', 'pushGate',
43
+ 'npmToken', 'npmRegistry',
44
+ 'autoPushEnabled', 'autoPushTriggerText', 'autoPushScope', 'autoPushMessage',
45
+ ];
46
+
24
47
  /** POST /api/git-push/settings-set —— 写单个设置键(白名单防越权)。 */
25
48
  export async function handleSettingsSet(ctx) {
26
49
  const { body, env, cfg } = ctx;
27
50
  const log = ctx.cfg?.log || ctx.log || { warn: () => {} };
28
51
  const key = String(body.key || '');
29
52
  // 白名单:仅允许前端设置卡片声明的键(凭据走这里 + 下方同步 cfg)
30
- const allowedKeys = new Set([
31
- 'auditEnabled', 'injectRequirements', 'injectSystemPrompt', 'auditScanScope',
32
- 'maxScanFiles', 'weightOverrides',
33
- 'maxCloneFileMB', 'cloneConcurrency',
34
- 'pushMethod', 'auditRuleOrder', 'auditDisabledSlots',
35
- 'githubToken', 'sshPub', 'pushGate',
36
- 'npmToken', 'npmRegistry',
37
- 'autoPushEnabled', 'autoPushTriggerText', 'autoPushScope', 'autoPushMessage',
38
- ]);
39
- if (!allowedKeys.has(key)) return { status: 400, body: { ok: false, error: `不支持的设置键: ${key || '(空)'}` } };
53
+ if (!ALLOWED_SETTING_KEYS.includes(key)) return { status: 400, body: { ok: false, error: `不支持的设置键: ${key || '(空)'}` } };
40
54
  // 凭据落插件目录(github-token / *.pub / npmToken 一律 0600,绝不入库)
41
55
  if (key === 'githubToken') {
42
56
  const r = persistGithubToken(body.value, { workspaceRoot: env.workspaceRoot });
@@ -50,14 +64,19 @@ export async function handleSettingsSet(ctx) {
50
64
  const r = persistNpmToken(body.value, { workspaceRoot: env.workspaceRoot });
51
65
  if (!r.ok) return { status: 400, body: { ok: false, error: `npm token 持久化失败: ${r.error || '未知错误'}` } };
52
66
  }
53
- const r = await writeSettingsKey(key, body.value, { workspaceRoot: env.workspaceRoot });
67
+ // 嵌套块走专用写路径(键级合并);其余键仍走通用整键写入
68
+ const r = key === PRECOMMIT_ENABLED_KEY
69
+ ? await writePreCommitEnabled(body.value, { workspaceRoot: env.workspaceRoot })
70
+ : await writeSettingsKey(key, body.value, { workspaceRoot: env.workspaceRoot });
54
71
  appendSettingsLog({ key, value: body.value, via: 'http-settings-set', ok: r.ok, error: r.error }, { workspaceRoot: env.workspaceRoot });
55
72
  if (!r.ok) {
56
73
  return { status: r.code === 'BAD_KEY' ? 400 : 500, body: { ok: false, code: r.code || 'SETTINGS_WRITE', error: r.error } };
57
74
  }
58
75
  // 写盘成功后同步内存 cfg(即时生效;config.json 才是真源)
59
76
  try {
60
- applySettingsToCfg(cfg, { [key]: body.value });
77
+ applySettingsToCfg(cfg, key === PRECOMMIT_ENABLED_KEY
78
+ ? { preCommit: { enabled: body.value } }
79
+ : { [key]: body.value });
61
80
  } catch (e) {
62
81
  log?.warn?.(`settings-set cfg 同步跳过:${e?.message || e}`);
63
82
  }