dsh-git-push 2.10.1 → 2.10.5

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 (45) hide show
  1. package/README.md +8 -0
  2. package/assets/tree-sitter/LICENSE +0 -0
  3. package/assets/tree-sitter/README.md +0 -0
  4. package/assets/tree-sitter/tree-sitter-javascript.wasm +0 -0
  5. package/assets/tree-sitter/tree-sitter-python.wasm +0 -0
  6. package/assets/tree-sitter/tree-sitter-typescript.wasm +0 -0
  7. package/assets/tree-sitter/tree-sitter.js +0 -0
  8. package/assets/tree-sitter/tree-sitter.wasm +0 -0
  9. package/lib/ARCHITECTURE.md +27 -0
  10. package/lib/app/apply.js +0 -0
  11. package/lib/app/audit-api.js +2 -0
  12. package/lib/app/handlers/settings.js +0 -0
  13. package/lib/app/handlers/workspace-paths.js +0 -0
  14. package/lib/app/repo-ownership.js +65 -0
  15. package/lib/app/schema.js +0 -0
  16. package/lib/app/settings-bridge.js +0 -0
  17. package/lib/app/tool-call.js +4 -0
  18. package/lib/ast/code-lines.js +0 -0
  19. package/lib/ast/fs-hotspots.js +0 -0
  20. package/lib/ast/index.js +0 -0
  21. package/lib/ast/tokenizer.js +0 -0
  22. package/lib/ast/treesitter.js +0 -0
  23. package/lib/audit/audit-file.js +15 -1
  24. package/lib/audit/orchestrate.js +1 -0
  25. package/lib/audit/ownership.js +46 -0
  26. package/lib/checks/fs-scanner.js +0 -0
  27. package/lib/checks/regex.js +0 -0
  28. package/lib/cli/commands-audit.mjs +3 -0
  29. package/lib/core/workspace-paths.js +0 -0
  30. package/lib/exempt/tool.js +0 -0
  31. package/lib/git/clone-history-mode.js +22 -9
  32. package/lib/git/clone-replay-io.js +10 -4
  33. package/lib/git/clone.js +8 -2
  34. package/lib/git/commit-message.js +0 -0
  35. package/lib/git/index-format.js +0 -0
  36. package/lib/git/init-compat.js +118 -0
  37. package/lib/git/push-diagnose.js +0 -0
  38. package/lib/self/index.js +1 -1
  39. package/package.json +1 -1
  40. package/scripts/bump-version.mjs +163 -0
  41. package/scripts/check.mjs +68 -0
  42. package/scripts/cpu-sample.mjs +0 -0
  43. package/scripts/picker-repro.mjs +0 -0
  44. package/scripts/scan-fs-hotspots.mjs +0 -0
  45. package/skills/guide/guide-audit.md +29 -0
package/README.md CHANGED
@@ -265,6 +265,7 @@ dsh-git-push/
265
265
  │ │ ├── http-handlers.js — HTTP 路由分发(薄 router:前置校验 + switch 各端点调 handlers/ 模块)
266
266
  │ │ ├── index.js — 插件入口再导出(宿主 main 指向)
267
267
  │ │ ├── inject-text.js — 注入文本(工具用法提示 FUNCTION_USAGE_HINT)
268
+ │ │ ├── repo-ownership.js — (待注释)
268
269
  │ │ ├── scan-root.js — 默认扫描根解析(配置优先→DSH 家根自动识别)
269
270
  │ │ ├── schema.js — 配置 schema(宿主导出缺失时兜底)
270
271
  │ │ ├── settings-bridge.js — 设置读写桥(host scope 共享;绕开 client isLoopback=memory 落盘陷阱)
@@ -315,6 +316,7 @@ dsh-git-push/
315
316
  │ │ ├── ignore-blind.js — 审计静默失明检测(本地 git 排除配置把整仓判成忽略时告警)
316
317
  │ │ ├── index.js — 审计层统一出口(auditFull/auditChanged)
317
318
  │ │ ├── orchestrate.js — 审计编排(收集→检查→汇总)
319
+ │ │ ├── ownership.js — (待注释)
318
320
  │ │ ├── public.js — (待注释)
319
321
  │ │ ├── repo-level.js — 仓库级语义规则
320
322
  │ │ ├── report-yaml.js — (待注释)
@@ -422,6 +424,7 @@ dsh-git-push/
422
424
  │ │ ├── ignore.js — .gitignore 兜底(DEFAULT_IGNORE_PATTERNS 补齐)
423
425
  │ │ ├── index-format.js — (待注释)
424
426
  │ │ ├── index.js — Git 执行层统一出口
427
+ │ │ ├── init-compat.js — (待注释)
425
428
  │ │ ├── module-splitter.js — (待注释)
426
429
  │ │ ├── post-push.js — 推送后增强(remote-tracking ref/aux remote/tag)
427
430
  │ │ ├── push-diagnose.js — (待注释)
@@ -470,6 +473,7 @@ dsh-git-push/
470
473
  │ ├── audit-runtime-check.mjs — 三层审计 L3 运行时检测脚本
471
474
  │ ├── browser-page-probe.mjs — (待注释)
472
475
  │ ├── build-client.mjs — 客户端分片拼接(PART_ORDER + --check 门禁 + 形态铁律自检)
476
+ │ ├── bump-version.mjs — (待注释)
473
477
  │ ├── check.mjs — 语法检查脚本(npm run check)
474
478
  │ ├── clean-date-comments.py — (待注释)
475
479
  │ ├── cpu-sample.mjs — (待注释)
@@ -592,7 +596,9 @@ dsh-git-push/
592
596
  │ ├── test-gitignore-nongit-dir.mjs — (待注释)
593
597
  │ ├── test-history-audit.mjs — (待注释)
594
598
  │ ├── test-http.mjs — HTTP 总入口测试(Origin/CSRF/413/路由)
599
+ │ ├── test-ignore-e2e.mjs — (待注释)
595
600
  │ ├── test-index-jsonl.mjs — (待注释)
601
+ │ ├── test-init-compat.mjs — (待注释)
596
602
  │ ├── test-inject-switch.mjs — 注入开发者要求清单子开关回归
597
603
  │ ├── test-inject-system-prompt.mjs — 注入系统提示词回归
598
604
  │ ├── test-io-risk.mjs — IO 风险分级测试(四级判定/字段完整性/汇总/排序/finding 转换)
@@ -619,6 +625,7 @@ dsh-git-push/
619
625
  │ ├── test-picker-layout.mjs — (待注释)
620
626
  │ ├── test-platform-scan.mjs — (待注释)
621
627
  │ ├── test-plugin.mjs — 插件接线测试(入口导出/工具清单/双副本同步)
628
+ │ ├── test-privacy-ownership.mjs — (待注释)
622
629
  │ ├── test-private-gate.mjs — (待注释)
623
630
  │ ├── test-project-type-filter.mjs — 项目类型规则适配测试(非 dsh 项目不加载 dsh 槽位/0.x 版本规则、timeout 限 js 系、folder 尊重 gitignore——Pawchive 误报消除驱动)
624
631
  │ ├── test-push-diagnose.mjs — (待注释)
@@ -659,6 +666,7 @@ dsh-git-push/
659
666
  │ ├── test-workspace-paths.mjs — (待注释)
660
667
  │ ├── fixtures/ — (待注释)
661
668
  │ │ ├── TimeZoneComboBox-CRnoCikG.js — Pawchive 混淆产物样本(hash 文件名——跳过判定 fixture)
669
+ │ │ └── …(5 个更深文件)
662
670
  │ ├── helpers/ — (待注释)
663
671
  │ │ ├── test-cache.mjs — (待注释)
664
672
  │ │ ├── tmp-dir.mjs — (待注释)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -32,3 +32,30 @@
32
32
  `lib/rule/compilers.js` 只做纯再导出。
33
33
  - 仓库级/文件系统上下文类检查(如读 .gitignore、git 命令)不在逐文件检查器里臆测,
34
34
  交给 `lib/audit/` 编排层或 `lib/checks/` 中带上下文参数的入口。
35
+
36
+ ## 审计引擎与提交推送:不拆成两个包,但把边界钉死
37
+
38
+ **决策(2026-10-24)**:保持单包 `dsh-git-push`,不拆出独立审计 npm 包。
39
+
40
+ 拆包换不到收益:
41
+
42
+ - 外部使用者的需求是「提交前拦截」这个整体(`git_commit_push` 的门禁 + `code_audit`),不是「只装审计引擎」;
43
+ - 「脱离 DSH 跑审计」已由 `cli.mjs`(`git-sluice`,不依赖宿主)覆盖;
44
+ - 而拆包的代价是**持续**的:两包版本同步、固定发布顺序、依赖范围约束——同类 monorepo 双包仓库上刚观察到这些成本落地成 bug(版本各升各的、`files` 声明漂移)。
45
+
46
+ 但不拆包 ≠ 放弃边界。实测依赖方向是干净的:
47
+
48
+ | 方向 | 数量 | 说明 |
49
+ |---|---|---|
50
+ | 审计层 → git/npm/commit-push | **0** | 审计层完全不知道提交推送存在 |
51
+ | git/npm/commit-push → 审计层 | **7** | 唯一耦合面:`commit-push.js` 3 处(audit/exempt/score)+ `git/{ignore,repos,sensitive}.js` 4 处 |
52
+
53
+ 由 `scripts/check.mjs` 的**层边界门禁**钉住(两处都已自证会变红):
54
+
55
+ 1. 审计层任一文件 import git 层 ⇒ 直接失败;
56
+ 2. 反向接缝数超过预算 7 ⇒ 失败(要上调必须写明理由)。
57
+
58
+ **维护约定**:审计层需要 git 能力时(读 `.gitignore`、跑 `git status`),走**自己文件内的轻量
59
+ `execFileSync('git', …)`**(如 `lib/audit/collector.js`),不得顺手 `import` `lib/git/` 的
60
+ `runGit`/`transport.js`——那 7 处接缝是「提交门禁要调审计」的必需耦合,多一处都是在把它糊掉。
61
+ 真出现外部只要审计引擎的用户,按这张表拆:动那 7 行 import + 建包,其余是机械操作。
package/lib/app/apply.js CHANGED
File without changes
@@ -13,6 +13,7 @@
13
13
  import { buildRuleSlotMap } from '../audit/slot.js';
14
14
  import { isBlockerFinding } from '../audit/index.js';
15
15
  import { MAX_MSG_PREVIEW } from './constants.js';
16
+ import { probeRepoOwnership } from './repo-ownership.js';
16
17
 
17
18
  /** 支持的聚合维度(非法值回落 rule)。 */
18
19
  export const GROUP_BY_KEYS = ['rule', 'file', 'severity', 'slot'];
@@ -102,6 +103,7 @@ export async function runAuditApi(repo, params = {}, cfg = {}) {
102
103
  const { scoreQuality } = await import('../score/index.js');
103
104
  const scope = params.scope === 'diff' ? 'diff' : 'full';
104
105
  const auditOpts = {
106
+ ownership: probeRepoOwnership(repo), // 隐私规则只对自有仓库生效(审计层只消费该字符串)
105
107
  scope,
106
108
  rulesetDir: params.rulesetDir || '',
107
109
  maxScanFiles: params.maxScanFiles ?? cfg.maxScanFiles ?? 0,
File without changes
File without changes
@@ -0,0 +1,65 @@
1
+ /**
2
+ * 装配层 · 仓库归属探测(供审计的隐私规则判断「是不是自己的仓库」)
3
+ *
4
+ * 为什么放在这里而不是 `lib/audit/`:
5
+ * 判定归属需要「本机 GitHub 账号」+「仓库 remote」,两者都在 `lib/git/**`;而边界门禁
6
+ * (test-audit-git-boundary.mjs)禁止 `lib/audit/**` 依赖 git 层——审计要能脱离宿主独立使用。
7
+ * 故探测放在装配层,结果以**字符串**注入审计(依赖倒置);纯判定逻辑在
8
+ * `lib/audit/ownership.js`(零依赖、可单测)。
9
+ *
10
+ * 取数口径(都只读本地,不跑网络):
11
+ * · 本机 login:账号状态快照(token/ssh 的 login 字段,由账号检查写入,见 account-status.js);
12
+ * · 仓库 owner:`git remote -v` 的 fetch URL 解析(parseGithubUrl)。
13
+ * 判不出(无快照 / 无 GitHub remote)一律返回 'unknown' ⇒ 上游按「照旧生效」处理。
14
+ *
15
+ * 已知局限:组织仓库的 owner 是组织名而非个人 login ⇒ 判为 'foreign'(隐私规则关闭)。
16
+ * 方向是保守误伤(少报),不是漏报自家隐私;如需覆盖组织仓库,可在此扩展自有组织名单。
17
+ */
18
+ import { listRemotes, parseGithubUrl } from '../git/remote-resolve.js';
19
+ import { readAccountStatus } from '../git/account-status.js';
20
+ import { classifyOwnership } from '../audit/ownership.js';
21
+
22
+ /** 同一仓库只探一次(remote 与账号快照都是磁盘读,逐文件审计时重复开销明显)。 */
23
+ const CACHE = new Map();
24
+
25
+ /** 本机 GitHub 登录名(小写;取不到返回空串)。 */
26
+ export function localLogin() {
27
+ try {
28
+ const st = readAccountStatus({});
29
+ const login = String(st?.token?.login || '') || String(st?.ssh?.login || '');
30
+ return login.trim().toLowerCase();
31
+ } catch {
32
+ return '';
33
+ }
34
+ }
35
+
36
+ /** 仓库 GitHub owner(小写;无 GitHub remote 返回空串)。 */
37
+ export function remoteOwner(repoPath) {
38
+ try {
39
+ const map = listRemotes(repoPath || '') || {};
40
+ for (const name of Object.keys(map)) {
41
+ const url = (map[name] && (map[name].fetch || map[name].push)) || '';
42
+ const parsed = parseGithubUrl(String(url || ''));
43
+ if (parsed && parsed.owner) return String(parsed.owner).trim().toLowerCase();
44
+ }
45
+ } catch { /* 非 git 目录 / 无 remote → 空串 */ }
46
+ return '';
47
+ }
48
+
49
+ /**
50
+ * 探测仓库归属(带进程内缓存)。
51
+ * @param {string} repoPath 仓库根目录
52
+ * @returns {'own'|'foreign'|'unknown'}
53
+ */
54
+ export function probeRepoOwnership(repoPath = '') {
55
+ const key = String(repoPath || '');
56
+ if (CACHE.has(key)) return CACHE.get(key);
57
+ const verdict = classifyOwnership(localLogin(), remoteOwner(key));
58
+ CACHE.set(key, verdict);
59
+ return verdict;
60
+ }
61
+
62
+ /** 清空缓存(测试用 / 账号切换后)。 */
63
+ export function resetRepoOwnershipCache() {
64
+ CACHE.clear();
65
+ }
package/lib/app/schema.js CHANGED
File without changes
File without changes
@@ -35,6 +35,7 @@ import { buildAuditApiGuide } from './inject-text.js';
35
35
  import { exemptStatsOf, GROUP_BY_KEYS } from './audit-api.js';
36
36
  import { setLastSlotHitStats } from './slot-stats.js';
37
37
  import { getDefaultScanRoot } from './scan-root.js';
38
+ import { probeRepoOwnership } from './repo-ownership.js';
38
39
 
39
40
  /**
40
41
  * 工具调用分发(薄适配:参数 → 总入口函数)。
@@ -448,6 +449,9 @@ function buildAuditOpts(args, cfg, scope) {
448
449
  includeIgnored: args.includeIgnored === true,
449
450
  // 分析覆盖率信息项(默认开;coverage:false 关闭——大仓库省一次读取+解析)
450
451
  coverage: args.coverage !== false,
452
+ // 仓库归属:隐私/凭据类规则只对自有仓库生效(他人仓库等同关闭),见 lib/audit/ownership.js。
453
+ // 探测在装配层(依赖 git 层),审计层只消费这个字符串(边界门禁:lib/audit 不得依赖 lib/git)。
454
+ ownership: probeRepoOwnership(args.repo),
451
455
  };
452
456
  }
453
457
 
File without changes
File without changes
package/lib/ast/index.js CHANGED
File without changes
File without changes
File without changes
@@ -2,6 +2,7 @@ import { runChecks } from './checks.js';
2
2
  import { exemptForFinding } from '../exempt/index.js';
3
3
  import { hasExternalCallTimeout, hasMkdirInSameFunction, hasForeignWriteTarget } from './file-context.js';
4
4
  import { CODE_EXTS } from './finding.js';
5
+ import { privacyRulesEnabled, isPrivacyRule } from './ownership.js';
5
6
 
6
7
  /**
7
8
  * 单文件审计:读文件 → 跑检查 → 豁免过滤(注册表驱动,7 标记全消费)。
@@ -132,7 +133,20 @@ export function auditFile({ file, relPath, text, grouped }, opts = {}) {
132
133
  const isTestFile = /(^|[/\\])(test|tests|__tests__|spec)[/\\]|\.(test|spec)\.(js|mjs|cjs|ts)$/i.test(String(relPath || file));
133
134
  const maintainabilityScoped = !isCode || isTestFile;
134
135
  const scopedGrouped = maintainabilityScoped ? { ...grouped, 'repeated-string': undefined, 'min-occurrences': undefined } : grouped;
135
- let findings = runChecks({ file, relPath, text, grouped: scopedGrouped }, { level: opts?.level, repoHasJsYamlImport: opts?.repoHasJsYamlImport, repoLevelRules: opts?.repoLevelRules, repoPath: opts?.repoPath, treeConfirm: opts?.treeConfirm });
136
+ // 隐私/凭据类规则只对**自有仓库**生效:克隆来的他人仓库里有什么邮箱/密钥与本次提交无关,
137
+ // 报出来是纯噪声(实测:某第三方 Unity 项目 3 条 blocker 全是 LICENSE 里的作者邮箱)。
138
+ // 判不出归属('unknown')时照旧生效——保守方向:宁可多报,不可漏掉自家隐私。
139
+ const privacyOn = privacyRulesEnabled(opts?.ownership);
140
+ const finalGrouped = privacyOn ? scopedGrouped : (() => {
141
+ const stripped = {};
142
+ for (const [kind, rules] of Object.entries(scopedGrouped || {})) {
143
+ if (!Array.isArray(rules)) { stripped[kind] = rules; continue; }
144
+ const keep = rules.filter((r) => !isPrivacyRule(r?.id));
145
+ if (keep.length) stripped[kind] = keep;
146
+ }
147
+ return stripped;
148
+ })();
149
+ let findings = runChecks({ file, relPath, text, grouped: finalGrouped }, { level: opts?.level, repoHasJsYamlImport: opts?.repoHasJsYamlImport, repoLevelRules: opts?.repoLevelRules, repoPath: opts?.repoPath, treeConfirm: opts?.treeConfirm });
136
150
  const isRuleDefFile = /(^|[/\\])audit-rules-[a-z0-9-]+\.ya?ml$/i.test(String(relPath || file));
137
151
  const fileLines = String(text || '').split('\n');
138
152
  // 语义级豁免:纯 regex 规则看不到的上下文在此兜底——
@@ -224,6 +224,7 @@ async function auditFiles(repoPath, files, opts = {}) {
224
224
  level: opts.auditLevel, repoHasJsYamlImport, repoPath,
225
225
  repoLevelRules: skipRepoLevel ? repoLevelRules : null,
226
226
  treeConfirm,
227
+ ownership: opts.ownership, // 仓库归属('own'|'foreign'|'unknown'):由装配层探测注入,审计层不读 git
227
228
  }));
228
229
  }
229
230
  // 跨文件重复代码检测(maintainability/no-duplicate-code,该抽公共函数)。
@@ -0,0 +1,46 @@
1
+ /**
2
+ * 审计层 · 隐私规则的生效范围(按仓库归属)
3
+ *
4
+ * 为什么需要(2026-10-28 用户确立的口径):
5
+ * 隐私/凭据类规则(secret-email、credfile-*、credref-* …)的**目的**是防止**自己的仓库**
6
+ * 把隐私推到远端。克隆来的第三方公开仓库里有什么邮箱/密钥,与你无关:报出来是纯粹噪声,
7
+ * 而且常常成片出现(实测:克隆一个 Unity 项目直接 3 条 blocker,全是第三方 LICENSE 里的
8
+ * 作者邮箱——版权文件含作者邮箱是法律要求,根本不是隐私泄漏)。
9
+ * 故:**隐私类规则只在「自己的仓库」生效;别人的 git 仓库等同关闭。**
10
+ *
11
+ * 为什么这里只放纯函数(架构约束):
12
+ * `lib/audit/**` 不得依赖 `lib/git/**`(边界门禁 test-audit-git-boundary.mjs:审计按独立包
13
+ * 设计,要能脱离宿主使用)。而「取本机账号 + 读 remote」必然依赖 git 层 ⇒ 探测放在**装配层**
14
+ * `lib/app/repo-ownership.js`,结果以**字符串**经 opts 注入进来(依赖倒置)。
15
+ * 本模块因此零 import、零副作用,可在任何环境下单测。
16
+ *
17
+ * 判据语义:'own'=自有(生效)|'foreign'=他人(关闭)|'unknown'=判不出(**照旧生效**——
18
+ * 保守方向:宁可多报,不可漏掉自家隐私)。
19
+ */
20
+
21
+ /**
22
+ * 纯函数:由「本机 login」与「仓库 owner」判归属。
23
+ * @param {string} login 本机 GitHub 登录名(空串 = 未知)
24
+ * @param {string} owner 仓库 remote 解析出的 owner(空串 = 未知)
25
+ * @returns {'own'|'foreign'|'unknown'}
26
+ */
27
+ export function classifyOwnership(login = '', owner = '') {
28
+ const me = String(login || '').trim().toLowerCase();
29
+ const them = String(owner || '').trim().toLowerCase();
30
+ if (!me || !them) return 'unknown';
31
+ return them === me ? 'own' : 'foreign';
32
+ }
33
+
34
+ /**
35
+ * 隐私/凭据类规则是否应在该仓库生效。
36
+ * @param {'own'|'foreign'|'unknown'} [ownership] 归属(缺省/undefined 按 unknown 处理 ⇒ 生效)
37
+ * @returns {boolean} true = 生效;false = 他人仓库,关闭
38
+ */
39
+ export function privacyRulesEnabled(ownership) {
40
+ return ownership !== 'foreign';
41
+ }
42
+
43
+ /** 规则 id 是否属隐私/凭据类(这类规则受归属限制)。 */
44
+ export function isPrivacyRule(ruleId) {
45
+ return /^(secret-|credfile-|credref-)/.test(String(ruleId || ''));
46
+ }
File without changes
File without changes
@@ -15,6 +15,7 @@ import { readSettings, applySettingsToCfg } from '../app/settings-bridge.js';
15
15
  import { defaultConfig } from '../client/index.js';
16
16
  import { access } from 'node:fs/promises';
17
17
  import { join } from 'node:path';
18
+ import { probeRepoOwnership } from '../app/repo-ownership.js';
18
19
 
19
20
  /** 审计 full 扫描 findings 打印条数上限(防刷屏)。 */
20
21
  const AUDIT_PRINT_LIMIT = 20;
@@ -78,6 +79,7 @@ async function runHistoryAuditCmd(root, flags) {
78
79
  const cfg = cliPluginConfig();
79
80
  const { runHistoryAudit } = await import('../audit/history.js');
80
81
  const opts = pluginEqualAuditOpts(cfg, flags, { scope: 'full' });
82
+ opts.ownership = probeRepoOwnership(root); // 与插件工具同参:隐私规则只对自有仓库生效
81
83
  const weights = pluginEqualWeights(cfg, flags);
82
84
  const r = await runHistoryAudit(root || '.', {
83
85
  since: flags.since, until: flags.until, outDir: flags.out,
@@ -96,6 +98,7 @@ async function runStandardAudit(root, flags) {
96
98
  const cfg = cliPluginConfig();
97
99
  const full = flags.full === true || !(await pathExists(join(root || '.', '.git')));
98
100
  const opts = pluginEqualAuditOpts(cfg, flags, { scope: full ? 'full' : 'diff' });
101
+ opts.ownership = probeRepoOwnership(root); // 与插件工具同参:隐私规则只对自有仓库生效
99
102
  const weights = pluginEqualWeights(cfg, flags);
100
103
  const auditResult = full ? await auditFull(root, opts) : await auditWithScope(root, opts);
101
104
  const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files });
File without changes
File without changes
@@ -16,6 +16,7 @@ import { fetchCommitChain } from './clone-history.js';
16
16
  import { replayHistory } from './clone-replay.js';
17
17
  import { createReplayIo } from './clone-replay-io.js';
18
18
  import { runGit } from './exec.js';
19
+ import { initRepoCompat } from './init-compat.js';
19
20
  import { resolveOwnerVisibility, accessPlan, sshGitUrl } from './visibility.js';
20
21
  import { resolveSshKeys } from './credentials.js';
21
22
 
@@ -134,15 +135,27 @@ export async function cloneWithGitFetch({
134
135
  };
135
136
 
136
137
  const n = Number(depth) > 0 ? Number(depth) : 0;
137
- const init = run(['init', '-q']);
138
- if (!init?.ok) return fail(`git init 失败:${init?.stderr || '未知'}`);
139
- // 不支持 mode 的卷(CIFS)上抑制权限噪音——与 API 路径同口径
140
- run(['config', 'core.fileMode', 'false']);
141
- if (!git(['remote', 'get-url', 'origin'], gitOpts)?.ok) {
142
- run(['remote', 'add', 'origin', remoteUrl]);
143
- } else {
144
- // 已存在 origin(续跑):按本次判断纠正,避免上次留下的 https 形态继续走镜像
145
- run(['remote', 'set-url', 'origin', remoteUrl]);
138
+ // 初始化 + origin 一步做完:本地盘走 git init + remote add;不支持 chmod 的卷
139
+ // (CIFS/SMB nounix)走手工 .git 结构降级 —— 那些卷上 git init / git config /
140
+ // git remote add 全都要写 .git/config,而写 config 时的 chmod(config.lock) 必然
141
+ // EPERM,git 直接 fatal。降级路径把 remote 段一并手写进 config(见 init-compat.js)
142
+ const initRes = initRepoCompat(repoPath, {
143
+ branch: branch || 'master',
144
+ remoteUrl,
145
+ chmodOk: deps.chmodOk,
146
+ gitInit: (args, o) => git(args, { ...gitOpts, ...o }),
147
+ });
148
+ steps.push({ cmd: `init (${initRes.via})`, ok: !!initRes.ok });
149
+ if (!initRes.ok) return fail(`git init 失败:${initRes.stderr || '未知'}`);
150
+ if (initRes.filemode) {
151
+ // 权限噪音抑制(只对本地盘有意义;降级路径已把 filemode=false 写进手工 config)
152
+ run(['config', 'core.fileMode', 'false']);
153
+ if (!git(['remote', 'get-url', 'origin'], gitOpts)?.ok) {
154
+ run(['remote', 'add', 'origin', remoteUrl]);
155
+ } else {
156
+ // 已存在 origin(续跑):按本次判断纠正,避免上次留下的 https 形态继续走镜像
157
+ run(['remote', 'set-url', 'origin', remoteUrl]);
158
+ }
146
159
  }
147
160
 
148
161
  // 显式 refspec:同时写入 refs/remotes/origin/<branch>,后续可据此建本地分支并设上游
@@ -22,9 +22,10 @@ import { existsSync, readFileSync, writeFileSync, renameSync, rmSync } from 'nod
22
22
 
23
23
  import { githubFetch } from './api.js';
24
24
  import { runGit } from './exec.js';
25
+ import { initRepoCompat } from './init-compat.js';
25
26
  import { downloadBlobs } from './clone-download.js';
26
27
  import {
27
- blobEntriesOf, initArgs, setRemoteArgs, configFileModeArgs, addAllArgs, writeTreeArgs,
28
+ blobEntriesOf, setRemoteArgs, configFileModeArgs, addAllArgs, writeTreeArgs,
28
29
  commitTreeArgs, updateRefArgs, setUpstreamArgs, localBranchRef, remoteTrackingRef, markerJson,
29
30
  } from './clone-replay.js';
30
31
 
@@ -145,13 +146,18 @@ export function createReplayIo({
145
146
 
146
147
  /** 重放前准备:init → 显式写 core.fileMode=false → 设 origin(已有 origin 则不覆盖)。 */
147
148
  async prepare() {
148
- const init = git(initArgs(), gitOpts);
149
- if (!init?.ok) return { ok: false, error: `git init 失败:${init?.stderr || '未知'}` };
149
+ // 不支持 chmod 的卷(CIFS/SMB nounix)上 git init / git config / git remote add
150
+ // 全都要写 .git/config,而写 config 时的 chmod(config.lock) 必然 EPERM ⇒ fatal。
151
+ // 改走手工 .git 结构降级:HEAD + config(filemode=false) + remote 段一次写好
152
+ const url = `https://github.com/${owner}/${repo}.git`;
153
+ const initRes = initRepoCompat(gitOpts.cwd, { remoteUrl: url, chmodOk: deps.chmodOk, gitInit: (args, o) => git(args, { ...gitOpts, ...o }) });
154
+ if (!initRes.ok) return { ok: false, error: `git init 失败:${initRes.stderr || '未知'}` };
155
+ // 降级路径:filemode 与 origin 都已写进 config,无需再执行 git config / remote add
156
+ if (!initRes.filemode) return { ok: true, fileModeSet: true, originSet: true, via: initRes.via };
150
157
  const cfg = git(configFileModeArgs(false), gitOpts);
151
158
  const hasOrigin = git(['remote', 'get-url', 'origin'], gitOpts);
152
159
  let originSet = true;
153
160
  if (!hasOrigin?.ok) {
154
- const url = `https://github.com/${owner}/${repo}.git`;
155
161
  const add = git(setRemoteArgs('origin', url), gitOpts);
156
162
  originSet = !!add?.ok;
157
163
  }
package/lib/git/clone.js CHANGED
@@ -18,6 +18,7 @@ import { resolveToken } from './credentials.js';
18
18
  import { downloadBlobs, partitionBySize, DEFAULT_MAX_FILE_MB, DEFAULT_CONCURRENCY, removeDirForce, PARTS_DIR } from './clone-download.js';
19
19
  import { cloneAbortSignal, cloneLog } from './clone-jobs.js';
20
20
  import { runGit } from './exec.js';
21
+ import { initRepoCompat } from './init-compat.js';
21
22
 
22
23
  /* ───────────────────────── clone / 建仓 / 可见性 ───────────────────────── */
23
24
 
@@ -322,12 +323,17 @@ export async function cloneViaApi({
322
323
  // 先删「进行中」标记:与 history 模式同理,它若留在目录里会被 git add -A 一并提交,
323
324
  // 使快照提交多出一个本不该存在的文件(此前实测残留在仓库里,需人工清理)。
324
325
  try { unlinkSync(join(targetDir, CLONE_MARKER)); } catch { /* 标记本就不在则忽略 */ }
326
+ // 初始化:本地盘走 git init;不支持 chmod 的卷(CIFS/SMB nounix)走手工 .git 结构,
327
+ // origin 一并手写进 config —— 那些卷上 `git remote add` 同样要写 .git/config 而失败
328
+ const apiRemoteUrl = `${GH_API}/repos/${owner}/${repo}`;
329
+ const initRes = initRepoCompat(targetDir, { branch: useBranch, remoteUrl: apiRemoteUrl });
330
+ if (!initRes.ok) return { ok: false, error: `git init 失败:${initRes.stderr || '未知'}`, dest: targetDir };
325
331
  for (const args of [
326
- ['init', '-q'], ['add', '-A'], ['-c', 'user.email=v2-clone@local', '-c', 'user.name=v2-clone', 'commit', '-q', '-m', `clone from ${owner}/${repo}@${useBranch}`],
332
+ ['add', '-A'], ['-c', 'user.email=v2-clone@local', '-c', 'user.name=v2-clone', 'commit', '-q', '-m', `clone from ${owner}/${repo}@${useBranch}`],
327
333
  ]) {
328
334
  runGit(args, { cwd: targetDir });
329
335
  }
330
- runGit(['remote', 'add', 'origin', `${GH_API}/repos/${owner}/${repo}`], { cwd: targetDir });
336
+ if (initRes.filemode) runGit(['remote', 'add', 'origin', apiRemoteUrl], { cwd: targetDir });
331
337
 
332
338
  // 成功:移除进行中标记,此后该目录不再被当作「可清理的残留」
333
339
  try { unlinkSync(join(targetDir, CLONE_MARKER)); } catch { /* 标记本就不在则忽略 */ }
File without changes
File without changes
@@ -0,0 +1,118 @@
1
+ /**
2
+ * git 仓库初始化兼容层(CIFS/SMB 等不支持 chmod 的文件系统)。
3
+ *
4
+ * 为什么需要(实测根因,2026-10-28):
5
+ * `git init` 末尾要把探测到的 `core.filemode` **写入** `.git/config`。写 config 走的是
6
+ * `config.lock` → chmod(继承原权限) → rename,而 CIFS 挂载带 `nounix` 时 chmod 一律
7
+ * `EPERM`,于是 git 直接 fatal:
8
+ * `error: chmod on .../.git/config.lock failed: Operation not permitted`
9
+ * `fatal: could not set 'core.filemode' to 'false'`
10
+ * 结果是在目标目录留下一个**未初始化的空 .git**,后续 add/commit 还会向上命中父仓库
11
+ * (把父仓库整棵树写进错误的历史,历史事故)。
12
+ * 同样的 chmod 也会让 `git config core.fileMode false` 失效——所以「先 git init 再关
13
+ * filemode」这条自救路线在 CIFS 上根本不成立。
14
+ *
15
+ * 实测结论(这三条是设计依据,改动前请重跑确认):
16
+ * ① `git init` / `git config` 写 config → 必然失败(chmod);
17
+ * ② **手工搭最小 .git 结构**后,`git add -A` / `git commit` / `git log` / `git reset`
18
+ * 全部正常——index.lock 与 refs 的写入不受影响,只有 config 的 chmod 是死穴;
19
+ * ③ `core.filemode = false` 写进 config 后,`git status` 才不再把所有文件报成 M
20
+ * (CIFS 上文件 mode 恒为 777,与 index 里记录的 100644 不符)。
21
+ *
22
+ * 因此降级路径 = 手写 `.git/{HEAD,config}` + 空 `objects/refs/info` 目录,绕开 git 的
23
+ * config 写入流程;config 里预先写死 `filemode = false`。
24
+ */
25
+ import { existsSync, mkdirSync, writeFileSync, chmodSync, rmSync } from 'node:fs';
26
+ import { join } from 'node:path';
27
+ import { runGit } from './exec.js';
28
+
29
+ /**
30
+ * 探测目录所在文件系统是否支持 chmod。
31
+ *
32
+ * 判据就是真去 chmod 一个临时文件——比看 mount 类型可靠(同类挂载的选项可能不同,
33
+ * 而且同一台机器上 NFS/CIFS/本地盘混合)。用完即删,不留残余。
34
+ * @param {string} dir 目标目录(不存在会先创建——clone 的目标目录本来就是新建的)
35
+ * @returns {boolean} true = 支持 chmod(可走标准 git init)
36
+ */
37
+ export function fsSupportsChmod(dir) {
38
+ const probe = join(dir, `.dshgp-chmod-probe-${process.pid}-${Date.now()}`);
39
+ try {
40
+ // 先确保目录存在:目标目录可能还没建,此时 writeFile 会 ENOENT,
41
+ // 若把 ENOENT 误判成「不支持 chmod」就会让所有全新目标目录都走降级分支(实测踩过)
42
+ mkdirSync(dir, { recursive: true });
43
+ writeFileSync(probe, '');
44
+ chmodSync(probe, 0o600);
45
+ return true;
46
+ } catch {
47
+ return false;
48
+ } finally {
49
+ try { rmSync(probe, { force: true }); } catch { /* 探测文件残留无所谓 */ }
50
+ }
51
+ }
52
+
53
+ /**
54
+ * 手工搭最小可用的 .git 结构(不经 git init)。
55
+ *
56
+ * 只写 git 真正必需的四样:HEAD(指分支)、config(含 filemode=false)、
57
+ * objects/(对象库)、refs/heads(提交后放分支引用);info/ 是配套惯例目录。
58
+ * 不写 index —— 交给首次 `git add` 自动生成(实测可行)。
59
+ * @param {string} dir 仓库工作树目录
60
+ * @param {{branch?: string, remoteName?: string, remoteUrl?: string}} [opts]
61
+ * branch 为目标分支名(HEAD 指向它);给了 remoteUrl 就把 remote 段一并写进 config
62
+ * —— 因为 `git remote add` 同样是写 config,在 CIFS 上一样会 chmod 失败
63
+ */
64
+ export function writeMinimalGitDir(dir, { branch = 'master', remoteName = 'origin', remoteUrl = '' } = {}) {
65
+ const g = join(dir, '.git');
66
+ for (const d of ['objects', 'refs/heads', 'refs/tags', 'info']) {
67
+ mkdirSync(join(g, d), { recursive: true });
68
+ }
69
+ // HEAD 指向分支名而不是具体 sha:首次 commit 后 git 会把 refs/heads/<branch> 建好
70
+ writeFileSync(join(g, 'HEAD'), `ref: refs/heads/${branch}\n`);
71
+ // filemode=false 是关键项:不加则 CIFS 上所有文件因 777 vs 100644 恒被报为已修改
72
+ const lines = [
73
+ '[core]',
74
+ '\trepositoryformatversion = 0',
75
+ '\tfilemode = false',
76
+ '\tbare = false',
77
+ '\tlogallrefupdates = true',
78
+ ];
79
+ if (remoteUrl) {
80
+ lines.push(`[remote "${remoteName}"]`, `\turl = ${remoteUrl}`, `\tfetch = +refs/heads/*:refs/remotes/${remoteName}/*`);
81
+ }
82
+ writeFileSync(join(g, 'config'), lines.join('\n') + '\n');
83
+ }
84
+
85
+ /**
86
+ * 初始化 git 仓库(自动适配不支持 chmod 的文件系统)。
87
+ *
88
+ * 能 chmod → 走标准 `git init -q`(行为与之前完全一致);
89
+ * 不能 chmod → 手写最小 .git 结构,等价于「已 init 完成」的仓库。
90
+ * @param {string} dir 目标目录(必须已存在)
91
+ * @param {{branch?: string, remoteUrl?: string, chmodOk?: boolean, gitInit?: (args: string[], opts: object) => object}} [opts]
92
+ * branch: 目标分支(降级路径写进 HEAD);remoteUrl: 降级路径一并写进 config 的 remote 段;
93
+ * chmodOk: 强制指定 chmod 能力(测试用,省略则真去探测目标卷);
94
+ * gitInit: 可注入的 git 执行器(测试用,缺省走 runGit)
95
+ * @returns {{ok: boolean, via: 'git-init'|'manual', filemode: boolean, stderr?: string}}
96
+ */
97
+ export function initRepoCompat(dir, { branch = 'master', remoteUrl = '', chmodOk, gitInit } = {}) {
98
+ const exec = typeof gitInit === 'function' ? gitInit : (args, opts) => runGit(args, opts);
99
+ const canChmod = typeof chmodOk === 'boolean' ? chmodOk : fsSupportsChmod(dir);
100
+ if (canChmod) {
101
+ const r = exec(['init', '-q'], { cwd: dir });
102
+ return { ok: !!r?.ok, via: 'git-init', filemode: true, stderr: r?.stderr };
103
+ }
104
+ try {
105
+ writeMinimalGitDir(dir, { branch, remoteUrl });
106
+ // 自检:结构搭好后 git 必须能识别出工作树,否则等于静默失败(历史事故的形态)
107
+ const rc = exec(['rev-parse', '--git-dir'], { cwd: dir });
108
+ if (!rc?.ok) return { ok: false, via: 'manual', filemode: false, stderr: rc?.stderr || '自检失败:git 未识别出新仓库' };
109
+ return { ok: true, via: 'manual', filemode: false };
110
+ } catch (e) {
111
+ return { ok: false, via: 'manual', filemode: false, stderr: String((e && e.message) || e) };
112
+ }
113
+ }
114
+
115
+ /** .git 目录是否已存在(续跑判断:已 init 过就不再重复写)。 */
116
+ export function hasGitDir(dir) {
117
+ return existsSync(join(dir, '.git'));
118
+ }
File without changes
package/lib/self/index.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
 
12
- export const VERSION = '2.10.1'; // 2.10.1:按插件架构修订审计规则(外部项目实测反馈,只修改判定逻辑、不以豁免代偿):①button-bind 按元素类型分流——button 要 click 类;input 接受 change/input/submit/pointerdown 等表单控件标准事件;<input type=file> 由原生 label.click() 触发、有程序化触发即视为接好;自定义分片目录(非标准 client-parts)降级 info,完整判定交产物。②函数范围识别补齐箭头函数/方法简写/asynс 体(此前只认 function 关键字 ⇒ maxFunctionLength 对纯箭头文件返回 0,导致 max-file-length 把聚合型文件误判成臃肿型且文案「最大函数 0 行(藏着超大函数)」自相矛盾);无函数时文案改为「顶层语句堆叠」。③button-bind 补进 dsh-skip-quality 的 blocked(此前该 kind 无任何标记可豁免,而规则 exemptHint 却指向它 ⇒ 提示写了不生效)。④guide-audit 增 §14 记录插件架构适配与性价比取舍。历史:2.10.0:仓库索引改 JSONL + 修 signal timed out。
12
+ export const VERSION = '2.10.5'; // 2.10.5:隐私/凭据类规则只对自有仓库生效(他人仓库等同关闭):克隆的第三方仓库里第三方 LICENSE/ReadMe 的作者邮箱不再成片报 blocker(实测某 Unity 项目 3 条 blocker 全由此而来);判不出归属时照旧生效(保守)。归属探测放装配层 lib/app/repo-ownership.js(依赖 git 层),审计层 lib/audit/ownership.js 只留纯函数并消费注入的归属字符串,守住『lib/audit 不依赖 lib/git』边界;CLI 与插件工具同参注入,保证两边结果一致。新增 scripts/bump-version.mjs:一键升版(默认 dry-run、--apply 才写盘),把散在三处的版本号收口,并自动重生成派生文档。另含 2.10.4 的 CIFS 克隆修复。。历史:2.10.4:修掉「克隆到 CIFS/SMB 挂载失败」——根因是 git init 要把 core.filemode 写进 .git/config,而写 config 走 config.lock→chmod→rename,挂载带 nounix 时 chmod 恒 EPERM ⇒ git 直接 fatal(留下未初始化的空 .git,整体克隆失败)。新增 lib/git/init-compat.js:真去 chmod 一个临时文件探测能力,不支持时手工搭最小 .git 结构(HEAD + config[filemode=false] + 空 objects/refs/info;remote 段一并手写,因 git remote add 同样要写 config),绕开 git 的 config 写入流程;实测降级后 add/commit/log/status/remote 全部正常。三处 init 调用点(clone.js / clone-history-mode.js / clone-replay-io.js)统一走该兼容层,deps 可注入 chmodOk 便于测试。新增 test/test-init-compat.mjs(6 例,含「降级结构必须是真仓库」与自证)。实测:katboi01/UmaViewer(157MB)经插件成功克隆到 CIFS 挂载,HEAD 与远端一致、脏文件 0。。2.10.3:忽略链路端到端回归。
13
13
  // 实测后果:该目录有 package.json ⇒ npm 去打包整棵 DSH 树、输出 2.1MB > spawnSync 默认 maxBuffer 1MB ⇒ ENOBUFS(npm_publish 的体检与真发全部失败);
14
14
  // 该目录没有 package.json 时报 ENOENT。现 publish 的两个调用点显式传 cwd=目标包目录,并给 runNpm 加 16MB maxBuffer。
15
15
  // 2.8.3:文案修正——「零改动 / 无新提交」明确为**正常成功路径**(注入用法、工具描述、README、skill 同批改),并修 job 输出自相矛盾(cleanSkipCommit 路径补 committed:false,不再显示「已提交,未推送」)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-git-push",
3
- "version": "2.10.1",
3
+ "version": "2.10.5",
4
4
  "description": "DSH git 自动提交推送插件——统一函数入口架构(规则/审计/git/自身/侧边栏/评分/豁免/上下文/HTTP/测试十大总入口)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-git-push — 一键版本升版(bump-version)
4
+ *
5
+ * 为什么要有这个脚本:版本号散在三处手工同步,每次发版都要手改
6
+ * ① `package.json` 的 version
7
+ * ② `lib/self/index.js` 的 `export const VERSION = '<v>'; // <v>:说明。历史:…`
8
+ * ③ `docs/releases.json` 新增一条 `<v>: "说明"`
9
+ * 少改一处就会被 doc-version / version-drift 门禁判为漂移,而这两处还各带长文本
10
+ * (VERSION 行还挂着历史链),手改既慢又容易写坏引号、破坏 JSON。
11
+ * 第 4 处(README 版本表 / CHANGELOG)已由 doc-version.mjs 从上面两处生成,无需手改。
12
+ *
13
+ * 用法:
14
+ * node scripts/bump-version.mjs --message "本次做了什么" # 预览(默认 dry-run)
15
+ * node scripts/bump-version.mjs --message "…" --apply # 真写盘
16
+ * node scripts/bump-version.mjs --to 2.11.0 --message "…" --apply # 指定版本(默认 patch +1)
17
+ * node scripts/bump-version.mjs --message-file /tmp/msg.txt --apply
18
+ *
19
+ * 约定:
20
+ * · **默认 dry-run**——只打印将要改动的三处(旧值 → 新值),不落盘;确认无误再加 --apply。
21
+ * (与 npm_publish / install-plugin 同口径:有副作用的动作先看预览再执行)
22
+ * · `--message` 必填:发版说明不能凭空生成,属于「人写内容」,脚本只负责把它同步到三处。
23
+ * · VERSION 行的历史链保留最近 2 个版本摘要,避免注释无限变长(沿用既有风格)。
24
+ * · 写完自动重生成版本文档(doc-version apply / doc-func apply / doc-tree sync+apply),
25
+ * 因为版本号一变,CHANGELOG 与函数索引必须跟着走,否则门禁立刻报漂移。
26
+ */
27
+ import { readFileSync, writeFileSync } from 'node:fs';
28
+ import { join, dirname } from 'node:path';
29
+ import { fileURLToPath } from 'node:url';
30
+ import { execFileSync } from 'node:child_process';
31
+
32
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
33
+ const PKG = join(ROOT, 'package.json');
34
+ const SELF = join(ROOT, 'lib', 'self', 'index.js');
35
+ const RELEASES = join(ROOT, 'docs', 'releases.json');
36
+
37
+ /** 解析命令行参数(只认 --flag value 与布尔 --apply)。 */
38
+ function parseArgs(argv) {
39
+ const out = { apply: false, to: '', message: '', messageFile: '' };
40
+ for (let i = 0; i < argv.length; i++) {
41
+ const a = argv[i];
42
+ if (a === '--apply') { out.apply = true; continue; }
43
+ if (a === '--message' || a === '-m') { out.message = argv[++i] || ''; continue; }
44
+ if (a === '--message-file') { out.messageFile = argv[++i] || ''; continue; }
45
+ if (a === '--to') { out.to = argv[++i] || ''; continue; }
46
+ }
47
+ return out;
48
+ }
49
+
50
+ const fail = (msg) => { console.error('✗ ' + msg); process.exit(1); };
51
+
52
+ /** 语义化版本比较:a < b 返回负。只支持 x.y.z。 */
53
+ function cmpVer(a, b) {
54
+ const pa = String(a).split('.').map(Number);
55
+ const pb = String(b).split('.').map(Number);
56
+ for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
57
+ return 0;
58
+ }
59
+
60
+ /** patch +1:默认每次提交升第三位(version-discipline 的既有口径)。 */
61
+ function bumpPatch(v) {
62
+ const [x, y, z] = String(v).split('.').map(Number);
63
+ return `${x}.${y}.${(z || 0) + 1}`;
64
+ }
65
+
66
+ function readJson(p) {
67
+ try { return JSON.parse(readFileSync(p, 'utf8')); } catch (e) { fail(`${p} 解析失败:${e.message}`); }
68
+ }
69
+
70
+ /**
71
+ * 拼新的 VERSION 行。
72
+ * 旧注释形如:`2.10.4:本次说明。历史:2.10.3:更早说明。` → 把「本次说明」降级进历史链,
73
+ * 只保留最近 2 条,避免每版都把整串历史再抄一遍(实测 2.9.x 之后该行已接近不可读)。
74
+ */
75
+ function buildVersionLine(oldLine, newVer, oldVer, message) {
76
+ const m = /export const VERSION = '([^']+)';\s*\/\/(.*)$/.exec(oldLine);
77
+ const oldComment = m ? m[2].trim() : '';
78
+ // 旧版本的「本次说明」= 历史链之前的那一段
79
+ const histIdx = oldComment.indexOf('历史:');
80
+ const oldMain = (histIdx >= 0 ? oldComment.slice(0, histIdx) : oldComment).replace(/^[\d.]+\s*[::]\s*/, '').trim();
81
+ const oldHist = histIdx >= 0 ? oldComment.slice(histIdx + '历史:'.length).trim() : '';
82
+ // 历史链:新压入的旧版摘要 + 原有最近 1 条
83
+ const prev = oldMain ? [`${oldVer}:${oldMain}`] : [];
84
+ const kept = oldHist ? oldHist.split(/。\s*(?=[\d.]+:)/).slice(0, 1).map((s) => s.replace(/。$/, '')) : [];
85
+ const chain = [...prev, ...kept].join('。');
86
+ const comment = `${newVer}:${message}。` + (chain ? `历史:${chain}。` : '');
87
+ return `export const VERSION = '${newVer}'; // ${comment}`;
88
+ }
89
+
90
+ const args = parseArgs(process.argv.slice(2));
91
+ const pkg = readJson(PKG);
92
+ const cur = String(pkg.version || '');
93
+ const target = args.to || bumpPatch(cur);
94
+ let message = args.message;
95
+ if (args.messageFile) {
96
+ try { message = readFileSync(args.messageFile, 'utf8').trim(); } catch (e) { fail(`--message-file 读取失败:${e.message}`); }
97
+ }
98
+ if (!/^\d+\.\d+\.\d+$/.test(target)) fail(`版本号必须为 x.y.z:${target}`);
99
+ if (cmpVer(target, cur) <= 0) fail(`目标版本 ${target} 必须大于当前 ${cur}`);
100
+ if (!message) fail('缺少 --message(发版说明需人写;或从 --message-file 读取)');
101
+
102
+ const releases = readJson(RELEASES);
103
+ if (releases[target]) fail(`docs/releases.json 已存在 ${target} 条目(不要重复升版)`);
104
+
105
+ const selfSrc = readFileSync(SELF, 'utf8');
106
+ const selfLines = selfSrc.split('\n');
107
+ const vi = selfLines.findIndex((l) => /^export const VERSION = '/.test(l));
108
+ if (vi < 0) fail('lib/self/index.js 未找到 VERSION 行');
109
+ const oldLine = selfLines[vi];
110
+ const newLine = buildVersionLine(oldLine, target, cur, message);
111
+
112
+ // ── 预览(默认 dry-run)
113
+ console.log(`升版:${cur} → ${target}${args.apply ? '(--apply 真写盘)' : '(dry-run,未写盘)'}`);
114
+ console.log('\n① package.json');
115
+ console.log(` - "version": "${cur}"`);
116
+ console.log(` + "version": "${target}"`);
117
+ console.log('\n② lib/self/index.js(VERSION 行)');
118
+ console.log(` - ${oldLine.slice(0, 90)}…`);
119
+ console.log(` + ${newLine.slice(0, 90)}…`);
120
+ console.log('\n③ docs/releases.json');
121
+ console.log(` + "${target}": "${message.slice(0, 70)}${message.length > 70 ? '…' : ''}"`);
122
+ console.log('\n④ 随后自动重生成:docs/CHANGELOG.md(doc-version)、docs/FUNCTIONS.md(doc-func)、tree-doc.json(doc-tree)');
123
+
124
+ if (!args.apply) {
125
+ console.log('\n确认无误后追加 --apply 才会写盘。');
126
+ process.exit(0);
127
+ }
128
+
129
+ // ── 写盘
130
+ // 注意:本仓库在 CIFS 挂载上,write/edit 工具会因 chmod 报 EPERM;脚本用 fs 直接写
131
+ // 普通文件(不触发 chmod),这正是把它脚本化的额外收益。
132
+ const newPkgText = readFileSync(PKG, 'utf8').replace(
133
+ /("version"\s*:\s*")[^"]+(")/,
134
+ `$1${target}$2`,
135
+ );
136
+ if (newPkgText === readFileSync(PKG, 'utf8')) fail('package.json 的 version 未替换成功(正则未命中)');
137
+ writeFileSync(PKG, newPkgText);
138
+
139
+ selfLines[vi] = newLine;
140
+ writeFileSync(SELF, selfLines.join('\n'));
141
+
142
+ const merged = { ...releases };
143
+ merged[target] = message;
144
+ // 按语义化版本排序,保持文件可读(原文件即按版本升序)
145
+ const sorted = {};
146
+ for (const k of Object.keys(merged).sort(cmpVer)) sorted[k] = merged[k];
147
+ writeFileSync(RELEASES, JSON.stringify(sorted, null, 2) + '\n');
148
+
149
+ console.log('\n✔ 三处已写入,重生成派生文档…');
150
+ for (const cmd of [
151
+ ['scripts/doc-version.mjs', ['apply']],
152
+ ['scripts/doc-func.mjs', ['apply']],
153
+ ['scripts/doc-tree.mjs', ['sync']],
154
+ ['scripts/doc-tree.mjs', ['apply']],
155
+ ]) {
156
+ try {
157
+ execFileSync(process.execPath, [join(ROOT, cmd[0]), ...cmd[1]], { cwd: ROOT, stdio: 'pipe', encoding: 'utf8' });
158
+ console.log(` ✔ ${cmd[0]} ${cmd[1].join(' ')}`);
159
+ } catch (e) {
160
+ console.error(` ✗ ${cmd[0]} 失败:${String(e?.stdout || e?.stderr || e).split('\n')[0]}`);
161
+ }
162
+ }
163
+ console.log(`\n完成:${cur} → ${target}。请跑 node scripts/doc-version.mjs check 与全量回归确认门禁绿。`);
package/scripts/check.mjs CHANGED
@@ -83,6 +83,74 @@ try {
83
83
  console.error(`✗ 分片构建校验失败:${e.message}`);
84
84
  }
85
85
 
86
+ // ── 层边界门禁(2026-10-24)────────────────────────────────────────────
87
+ // 背景:审计引擎与提交推送**决定不拆成两个 npm 包**(拆包的持续成本——双包版本同步、
88
+ // 固定发布顺序、依赖范围——换不到真实收益:外部使用者要的是「提交前拦截」这个整体,
89
+ // 而「脱离 DSH 跑审计」已由 cli.mjs 的独立 CLI 覆盖)。
90
+ // 但不拆包不等于放弃边界:审计层对 git 层是**实测零依赖**,这个事实一旦被顺手 import
91
+ // 侵蚀就再也回不来(历史包袱太重 = 不可逆)。所以把它钉成门禁。
92
+ // 不变量:
93
+ // ① 审计层任何文件都不得 import git/npm/commit-push 层(方向唯一:git → audit);
94
+ // ② 反向接缝数量有预算上限——允许存在(提交门禁必须调审计),但要能看见它在膨胀。
95
+ const AUDIT_DIRS = new Set(['ast', 'audit', 'audit-rules', 'checks', 'exempt', 'rule', 'score']);
96
+ const GIT_DIRS = new Set(['git', 'npm']);
97
+ const GIT_TOP = new Set(['commit-push.js']);
98
+ const AUDIT_TOP = new Set(['audit-defaults.js', 'skip-dirs.js']);
99
+ /** 反向接缝预算:实测 7 处(commit-push 3 + git/{ignore,repos,sensitive} 4);上调需写明理由。 */
100
+ const SEAM_BUDGET = 7;
101
+
102
+ const layerOf = (rel) => {
103
+ const top = rel.split('/')[0];
104
+ if (rel.includes('/') && AUDIT_DIRS.has(top)) return 'AUDIT';
105
+ if (rel.includes('/') && GIT_DIRS.has(top)) return 'GIT';
106
+ if (!rel.includes('/') && GIT_TOP.has(rel)) return 'GIT';
107
+ if (!rel.includes('/') && AUDIT_TOP.has(rel)) return 'AUDIT';
108
+ return 'OTHER';
109
+ };
110
+
111
+ let boundaryViolations = 0;
112
+ const seams = [];
113
+ for (const f of files) {
114
+ const rel = f.replace(ROOT + '/', '');
115
+ if (!rel.startsWith('lib/')) continue;
116
+ const inner = rel.slice('lib/'.length);
117
+ if (layerOf(inner) !== 'AUDIT') continue;
118
+ let src = '';
119
+ try { src = readFileSync(f, 'utf8'); } catch { continue; }
120
+ for (const m of src.matchAll(/from\s+['"](\.[^'"]+)['"]/g)) {
121
+ const target = join(dirname(f), m[1]).replace(ROOT + '/lib/', '');
122
+ if (layerOf(target) === 'GIT') {
123
+ boundaryViolations++;
124
+ console.error(`✗ 层边界违规:审计层 lib/${inner} import 了 git 层 ${m[1]}(审计引擎解耦)`);
125
+ }
126
+ }
127
+ }
128
+ // 反向接缝统计(允许,但要可见)
129
+ for (const f of files) {
130
+ const rel = f.replace(ROOT + '/', '');
131
+ if (!rel.startsWith('lib/')) continue;
132
+ const inner = rel.slice('lib/'.length);
133
+ if (layerOf(inner) !== 'GIT') continue;
134
+ let src = '';
135
+ try { src = readFileSync(f, 'utf8'); } catch { continue; }
136
+ for (const m of src.matchAll(/from\s+['"](\.[^'"]+)['"]/g)) {
137
+ const target = join(dirname(f), m[1]).replace(ROOT + '/lib/', '');
138
+ if (layerOf(target) === 'AUDIT') seams.push(`${inner} → ${target}`);
139
+ }
140
+ }
141
+ if (boundaryViolations) {
142
+ fail += boundaryViolations;
143
+ console.error(`✗ 层边界:${boundaryViolations} 处违规——审计层不得依赖 git/npm/commit-push`);
144
+ } else {
145
+ console.log(`✔ 层边界:审计层对 git 层 0 依赖(解耦成立)`);
146
+ }
147
+ if (seams.length > SEAM_BUDGET) {
148
+ fail++;
149
+ console.error(`✗ 反向接缝 ${seams.length} 处 > 预算 ${SEAM_BUDGET}:提交门禁调审计是必需的,但膨胀说明边界在糊掉——要么收敛,要么改预算并写明理由`);
150
+ } else {
151
+ console.log(`✔ 反向接缝(git → audit,唯一耦合面):${seams.length}/${SEAM_BUDGET} 处`);
152
+ }
153
+
86
154
  console.log(`\n${files.length - fail}/${files.length} 文件语法通过`);
87
155
  console.log(`${jsonFiles.length - jsonFail}/${jsonFiles.length} 个 JSON 可解析`);
88
156
  process.exitCode = (fail > 0 || jsonFail > 0) ? 1 : 0;
File without changes
File without changes
File without changes
@@ -239,3 +239,32 @@ console.log(x); // dsh-skip-residue: 本行为刻意保留的调试输出样本
239
239
  多种形态出现,小写搜会漏(实测:搜 `partFilter` 漏掉 `setPartFilter`,误判「零引用」而删掉底层实现)。
240
240
  注意这只针对「人工核查引用」;规则内部的**标识符匹配必须保持大小写敏感**(JS/Python 本身区分大小写,
241
241
  放宽只会引入新误报)。
242
+
243
+ ## 15. 忽略链路(.gitignore / .auditignore)的测试纪律
244
+
245
+ **这块历史上反复回归,而且每次都不是判定逻辑写错,而是接线层断掉。** 已知三次形态:
246
+
247
+ | 回归形态 | 症状 | 为什么内部函数测试挡不住 |
248
+ |---|---|---|
249
+ | 以**空 stdin** 调 `check-ignore`,从未传文件路径 | 忽略集恒空 ⇒ 全仓文件都进审计 | `buildIgnoreSet` 内部逻辑没改,改的是它的输入 |
250
+ | 大仓库降级:枚举全部文件被改成目录级判定 | 文件级规则(单个文件名)失效 | 降级是**性能分支**,内部单测仍走全量分支 |
251
+ | 调用方**漏传 `gitIgnoreRoot`** | 函数默认值 `null` = 不判定忽略 ⇒ 忽略完全不生效 | 函数行为没变,变的是调用参数 |
252
+
253
+ **纪律**:
254
+
255
+ - 忽略相关改动必须跑**端到端**(`auditFull` / `runAudit`),不能只测 `collectTextFiles`。
256
+ 既有 `test-collector-ignore.mjs` / `test-auditignore.mjs` 都只测内部函数,对上面三类天然失明;
257
+ 端到端守门员是 `test/test-ignore-e2e.mjs`(三条链路 + 对照组)。
258
+ - **必须有对照组**:断言「忽略的文件没出现」时,同时断言「该被审的文件出现了」。
259
+ 否则「全部文件都被排除」也会让测试假通过。
260
+ - 三条链路各自要有一条用例:full(走 `gitIgnoreRoot`)、diff(走 `collectChangedFiles` 独立路径)、
261
+ 非 git 目录(git check-ignore 不可用,靠 `parseGitignore` 纯 JS 兜底)。
262
+ - 样本要**入库**为固定 fixture(`test/fixtures/ignore-e2e/`),不要测试里现造:
263
+ 现造样本会随实现漂移,也让「什么叫被忽略」没有唯一答案。
264
+ 样本文件名用 `.js.fixture` / `.rules` 后缀——若直接叫 `gib.js` 且同目录放 `.gitignore`,
265
+ 这两份样本自己就会被忽略而**无法入库**(自我反噬)。
266
+ - 新增/修改忽略相关代码后,用「把 `gitIgnoreRoot` 强制改 `null`」自证测试会红——这是最容易复发的接线断点。
267
+
268
+ **排查时的第一个坑(我踩过)**:直接调 `collectTextFiles(dir, { repoPath: dir })` 会得到
269
+ 「忽略全失效」的假象——因为参数名是 `gitIgnoreRoot`,传错就等于显式关掉忽略判定。
270
+ 复现前先确认自己的探针参数与真实调用方一致(见 `lib/audit/orchestrate.js` 的调用处)。