dsh-git-push 2.18.2 → 2.20.17

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 (90) hide show
  1. package/.gitignore +4 -0
  2. package/README.md +12 -5
  3. package/cli-audit.mjs +141 -0
  4. package/cli-tool.mjs +86 -0
  5. package/cli.mjs +116 -324
  6. package/lib/ARCHITECTURE.md +3 -0
  7. package/lib/app/audit-api.js +1 -1
  8. package/lib/app/command-registry.js +16 -3
  9. package/lib/app/constants.js +9 -0
  10. package/lib/app/handlers/clone.js +12 -3
  11. package/lib/app/handlers/http-constants.js +11 -2
  12. package/lib/app/handlers/npm.js +4 -2
  13. package/lib/app/handlers/repos.js +10 -1
  14. package/lib/app/handlers/settings.js +9 -1
  15. package/lib/app/http-handlers.js +24 -3
  16. package/lib/app/inject-text.js +1 -0
  17. package/lib/app/schema-audit.js +42 -0
  18. package/lib/app/schema.js +19 -19
  19. package/lib/app/scope-check.js +69 -0
  20. package/lib/app/settings-bridge.js +51 -0
  21. package/lib/app/tool-call.js +56 -7
  22. package/lib/ast/credential.js +130 -14
  23. package/lib/ast/dataflow.js +127 -10
  24. package/lib/ast/index.js +2 -0
  25. package/lib/ast/naming.js +9 -1
  26. package/lib/ast/scope-collisions.js +228 -0
  27. package/lib/ast/treesitter.js +142 -1
  28. package/lib/audit/history.js +1 -1
  29. package/lib/audit/orchestrate.js +93 -6
  30. package/lib/audit/scope-policy.js +110 -0
  31. package/lib/audit-rules/audit-rules-dsh.yml +16 -1
  32. package/lib/audit-rules/audit-rules-nodejs.yml +21 -6
  33. package/lib/audit-rules/audit-rules-paths.yml +7 -1
  34. package/lib/audit-ui-sdk/contract.js +117 -0
  35. package/lib/audit-ui-sdk/index.js +17 -0
  36. package/lib/checks/common.js +4 -4
  37. package/lib/checks/dispatch.js +5 -0
  38. package/lib/checks/index.js +2 -0
  39. package/lib/checks/regex.js +8 -3
  40. package/lib/checks/scope-collision.js +68 -0
  41. package/lib/cli/commands-audit.mjs +13 -18
  42. package/lib/cli/commands-tool.mjs +93 -0
  43. package/lib/cli/commands-vcs.mjs +2 -1
  44. package/lib/cli/shared.mjs +448 -0
  45. package/lib/client-parts/{account.js → git/account.js} +1 -1
  46. package/lib/client-parts/{actions.js → git/actions.js} +26 -11
  47. package/lib/client-parts/{apply.js → git/apply.js} +1 -1
  48. package/lib/client-parts/{browser.js → git/browser.js} +1 -1
  49. package/lib/client-parts/{const.js → git/const.js} +6 -1
  50. package/lib/client-parts/{controller.js → git/controller.js} +23 -11
  51. package/lib/client-parts/{icons.js → git/icons.js} +1 -1
  52. package/lib/client-parts/{loader.js → git/loader.js} +1 -1
  53. package/lib/client-parts/{npm.js → git/npm.js} +1 -1
  54. package/lib/client-parts/{page.js → git/page.js} +11 -21
  55. package/lib/client-parts/{repo.js → git/repo.js} +1 -1
  56. package/lib/client-parts/{settings.js → git/settings.js} +1 -1
  57. package/lib/client-parts/{utils.js → git/utils.js} +1 -1
  58. package/lib/client.js +75 -354
  59. package/lib/commit-push/pre-commit-engine.js +388 -0
  60. package/lib/commit-push.js +44 -17
  61. package/lib/exempt/index.js +5 -2
  62. package/lib/git/ignore.js +6 -4
  63. package/lib/git/init-compat.js +83 -4
  64. package/lib/git/push.js +25 -2
  65. package/lib/git/sensitive.js +30 -1
  66. package/lib/git/transport.js +31 -10
  67. package/lib/http/index.js +82 -10
  68. package/lib/lint-adapter/detect.js +161 -0
  69. package/lib/lint-adapter/index.js +50 -0
  70. package/lib/lint-adapter/runner.js +133 -0
  71. package/lib/npm/npmrc.js +22 -5
  72. package/lib/rule/compilers/structure.js +24 -0
  73. package/lib/score/index.js +36 -4
  74. package/lib/self/index.js +1 -1
  75. package/package.json +25 -2
  76. package/scripts/audit-gate.mjs +235 -0
  77. package/scripts/build-client.mjs +15 -8
  78. package/scripts/bump-version.mjs +20 -5
  79. package/scripts/check-js-scope.mjs +87 -0
  80. package/scripts/check.mjs +51 -4
  81. package/scripts/scan-file-io.mjs +5 -1
  82. package/scripts/scan-version.mjs +10 -7
  83. package/skills/dev/dsh-git-push.md +70 -2
  84. package/skills/guide/guide-audit.md +11 -11
  85. package/skills/guide/guide-cli-scripts.md +3 -3
  86. package/skills/guide/guide-commit-push.md +2 -2
  87. package/skills/guide/guide-inject-ui.md +0 -16
  88. package/assets/start.sh +0 -396
  89. package/scripts/scan-hardcoded-paths.mjs +0 -125
  90. /package/lib/client-parts/{audit.js → audit/audit.js} +0 -0
@@ -0,0 +1,228 @@
1
+ /**
2
+ * 拼接产物的**作用域撞名检查**(通用:任何「多段 JS 拼进同一作用域」的产物都适用)。
3
+ *
4
+ * 要防的是什么:把多段 JS 拼进同一个作用域时,`var`/`function` 会被提升到函数顶部,
5
+ * 同名声明**后者覆盖前者且完全不报错**——某一段依赖的函数被另一段的同名函数顶掉,
6
+ * 运行时行为错乱却查不到任何异常。`const`/`let`/`class` 虽不提升,但同一块内重复声明
7
+ * 同样会让先声明的那份失效(区别只是某些情形会抛 SyntaxError)。
8
+ *
9
+ * 典型落点(本插件是一个代表,不是特例):
10
+ * · 浏览器端插件把多个分片拼成一个 `factory` 函数体(本插件 14 个分片);
11
+ * · 用 `<script>` 直接引入多段脚本(共享全局作用域);
12
+ * · 任何 `cat a.js b.js > bundle.js` 的土制打包。
13
+ *
14
+ * 判定方式(关键:**按真实作用域帧**而不是按缩进/深度):
15
+ * 遍历 token 维护一个花括号帧栈,每个 `{` 是一个**唯一帧**;声明绑定到
16
+ * 「最近的外层作用域帧」——
17
+ * · `var` / `function` → 绑定到最近的**函数作用域帧**(函数体或顶层);
18
+ * · `const` / `let` / `class` → 绑定到**当前帧**(块级作用域);
19
+ * · `for (…)` 头部里的声明 → 绑定到该 for 语句的**专属帧**(每次迭代新绑定,
20
+ * 兄弟循环同名合法;不这样处理会把 `for (const r of a)` + `for (const r of b)`
21
+ * 误判成同帧重名——实测本项目 16 处误报全是这种写法)。
22
+ * 于是「两个不同函数里的同名局部变量」天然分属不同帧 → 不算撞名(不会误报),
23
+ * 而「同一函数体里两段各声明一次同名」会被抓住(这正是静默覆盖的触发条件)。
24
+ *
25
+ * 三条可选检查项(都能关,便于不同项目按自己的契约启用):
26
+ * ① 顶层声明:`topLevelMustBeEmpty`(拼接产物常要求「文件顶层零声明」以免与别家撞名);
27
+ * ② 命名前缀:`prefix`(如 `dshgp_`;留空则跳过),`allowlist` 放行宿主/契约名;
28
+ * ③ 同帧重名:始终启用(这是本检查存在的理由)。
29
+ */
30
+ import { tokenize } from './tokenizer.js';
31
+
32
+ /** 会产生声明的关键字(其后第一个 ident 即声明名)。 */
33
+ const DECL_KEYWORDS = new Set(['function', 'const', 'let', 'var', 'class']);
34
+ /** 这些关键字后面跟的 `(`…`)` 是**控制语句条件**,其 `{` 是块而不是函数体。 */
35
+ const CONTROL_KEYWORDS = new Set(['if', 'for', 'while', 'switch', 'catch', 'with']);
36
+
37
+ /**
38
+ * 扫描文本,找出「同一作用域内被声明多次」的名字,以及对顶层/前缀契约的违反。
39
+ *
40
+ * @param {string} text 待检查的 JS 文本
41
+ * @param {{prefix?:string, allowlist?:string[], topLevelMustBeEmpty?:boolean,
42
+ * topLevelAllowlist?:string[]}} [opts]
43
+ * prefix:要求标识符带的前缀(如 `dshgp_`);留空表示不检查前缀。
44
+ * allowlist:前缀例外(宿主注入或契约固定的名字)。
45
+ * topLevelMustBeEmpty:是否禁止文件顶层出现声明(默认 true)。
46
+ * @returns {{ok:boolean, declarations:Array, duplicates:Array, topLevel:Array,
47
+ * missingPrefix:Array, violations:string[]}}
48
+ */
49
+ export function analyzeScopeCollisions(text = '', {
50
+ prefix = '', allowlist = [], topLevelMustBeEmpty = true, topLevelAllowlist = [],
51
+ } = {}) {
52
+ const tokens = tokenize(String(text));
53
+ const allowed = new Set(allowlist);
54
+ const topAllowed = new Set(topLevelAllowlist);
55
+
56
+ // 帧栈:{ id, isFunction }。id=0 表示文件顶层(虚拟帧,永远在栈底)。
57
+ const frames = [{ id: 0, isFunction: true }];
58
+ let nextFrameId = 1;
59
+ /** 上一个「有效」token 的形态标记,用于判断 `{` 是否为函数体。 */
60
+ let prevSignificant = '';
61
+ /**
62
+ * for 头部作用域:`for (const r of …)` 的绑定属于该 for 语句自己的作用域,
63
+ * 每次迭代都是新绑定 ⇒ 兄弟循环里同名合法。把这类声明绑到**专属虚拟帧**
64
+ * (负 id,与花括号帧号不冲突),否则两个兄弟 for 循环的 `const r`/`let i`
65
+ * 会被误判成同帧重名(本项目自审计实测 16 处误报,全是这种写法)。
66
+ * 覆盖 `for await (…)`:token 流是 for → await → (。
67
+ */
68
+ const parenStack = []; // { inFor, id } —— 当前打开的括号(只关心是否 for 头部)
69
+ let nextForFrameId = -1;
70
+ let forPending = false; // 刚读到 for(其后可能跟 await),下一个 ( 即 for 头部
71
+
72
+ const declarations = [];
73
+ const duplicates = [];
74
+ /** `${frameId}|${name}` → { count, firstLine }(firstLine 用于「哪两行撞了」的可定位文案)。 */
75
+ const seen = new Map();
76
+ /**
77
+ * 共享作用域帧=**最外层的函数体**(拼接后各段共同落入的那一个)。
78
+ * 前缀检查只针对它:函数内部的局部变量各属自己的帧、彼此不可能撞名,
79
+ * 要求它们也带前缀属过度约束(实测把 244 个局部变量误判成「缺前缀」)。
80
+ * 用「第一个函数帧」而非固定深度 ⇒ 包装形态变了也不用改判定。
81
+ */
82
+ let sharedFrameId = -1;
83
+
84
+ /** 找最近的外层函数作用域帧(var/function 绑定到它)。 */
85
+ const nearestFunctionFrame = () => {
86
+ for (let i = frames.length - 1; i >= 0; i -= 1) if (frames[i].isFunction) return frames[i].id;
87
+ return 0;
88
+ };
89
+
90
+ for (let i = 0; i < tokens.length; i += 1) {
91
+ const token = tokens[i];
92
+ const value = String(token.value);
93
+
94
+ // ── `for` 头部识别:for [await] ( → 该括号里的声明归 for 自己的作用域 ──
95
+ if (value === 'for') {
96
+ forPending = true;
97
+ prevSignificant = value;
98
+ continue;
99
+ }
100
+ if (value === 'await' && forPending) {
101
+ prevSignificant = value;
102
+ continue; // 保持 pending:`for await (…)`
103
+ }
104
+ if (value === '(') {
105
+ parenStack.push(forPending ? { inFor: true, id: nextForFrameId-- } : { inFor: false, id: 0 });
106
+ forPending = false;
107
+ prevSignificant = value;
108
+ continue;
109
+ }
110
+ if (value === ')') {
111
+ parenStack.pop();
112
+ forPending = false;
113
+ prevSignificant = value;
114
+ continue;
115
+ }
116
+ forPending = false;
117
+
118
+ if (value === '{') {
119
+ // 判断这个 `{` 是不是函数体:紧跟在 `=>` 后,或紧跟在函数参数表 `)` 后,
120
+ // 且该 `)` 不是 if/for/while/switch/catch 的控制条件。
121
+ let isFunction = false;
122
+ if (prevSignificant === '=>') isFunction = true;
123
+ else if (prevSignificant === ')') {
124
+ // 往回找与这个 `)` 配对的 `(`,看它前面是不是控制关键字
125
+ let depthParen = 0;
126
+ let openIdx = -1;
127
+ for (let k = i - 1; k >= 0; k -= 1) {
128
+ const v = String(tokens[k].value);
129
+ if (v === ')') depthParen += 1;
130
+ else if (v === '(') {
131
+ depthParen -= 1;
132
+ if (depthParen === 0) { openIdx = k; break; }
133
+ }
134
+ }
135
+ const beforeParen = openIdx > 0 ? String(tokens[openIdx - 1].value) : '';
136
+ isFunction = !CONTROL_KEYWORDS.has(beforeParen);
137
+ }
138
+ frames.push({ id: nextFrameId, isFunction });
139
+ if (isFunction && sharedFrameId < 0) sharedFrameId = nextFrameId;
140
+ nextFrameId += 1;
141
+ prevSignificant = '{';
142
+ continue;
143
+ }
144
+ if (value === '}') {
145
+ if (frames.length > 1) frames.pop();
146
+ prevSignificant = '}';
147
+ continue;
148
+ }
149
+
150
+ if (DECL_KEYWORDS.has(value)) {
151
+ // 跳过修饰符后取声明名
152
+ let j = i + 1;
153
+ while (j < tokens.length && ['*', 'async', 'export', 'default'].includes(String(tokens[j].value))) j += 1;
154
+ const nameToken = tokens[j];
155
+ if (nameToken && nameToken.type === 'ident') {
156
+ const name = String(nameToken.value);
157
+ const blockScoped = value === 'const' || value === 'let' || value === 'class';
158
+ const inForHeader = Boolean(parenStack.length && parenStack[parenStack.length - 1].inFor);
159
+ // for 头部里的声明(含 var)绑到该 for 的专属帧:兄弟循环同名合法,不算撞名
160
+ const frameId = inForHeader
161
+ ? parenStack[parenStack.length - 1].id
162
+ : (blockScoped ? frames[frames.length - 1].id : nearestFunctionFrame());
163
+ // frameDepth 只对花括号帧有意义;for 头部(虚拟帧)记为 -1,既不会误入「顶层声明」,
164
+ // 也不会参与共享作用域(sharedFrameId ≥1)的前缀判定。
165
+ const frameDepth = inForHeader ? -1 : frames.length - 1;
166
+ declarations.push({ name, keyword: value, line: token.line, frameId, frameDepth });
167
+ const key = `${frameId}|${name}`;
168
+ const prev = seen.get(key);
169
+ const count = (prev?.count || 0) + 1;
170
+ const keywords = prev ? [...prev.keywords, value] : [value];
171
+ seen.set(key, { count, firstLine: prev ? prev.firstLine : token.line, keywords });
172
+ // 只报一次:第 3 次及以后的同名声明不再重复入列(同一个名字一条命中,避免刷屏)
173
+ if (count === 2) {
174
+ duplicates.push({
175
+ name,
176
+ frameId,
177
+ scope: blockScoped ? 'block' : 'function',
178
+ line: token.line, // 后来者(静默覆盖的那份)
179
+ firstLine: prev.firstLine, // 先声明的那份
180
+ keywords, // 两次声明用的关键字(决定这条命中算不算真缺陷,见检查器)
181
+ });
182
+ }
183
+ }
184
+ prevSignificant = value;
185
+ continue;
186
+ }
187
+
188
+ prevSignificant = value;
189
+ }
190
+
191
+ const topLevel = declarations.filter((d) => d.frameDepth === 0);
192
+ // 前缀只约束**共享作用域帧**(最外层函数体):各函数内部的局部变量分属自己的帧、
193
+ // 彼此不可能撞名,要求它们也带前缀属过度约束(实测会把片段里的局部变量全判成缺前缀)。
194
+ const missingPrefix = !prefix ? [] : declarations.filter(
195
+ (d) => d.frameId === sharedFrameId && !d.name.startsWith(prefix) && !allowed.has(d.name),
196
+ );
197
+
198
+ // 三类命中都带上 message:violations 直接由它们汇总而成 —— **单一措辞源**。
199
+ // 审计检查器(lib/checks/scope-collision.js)出 finding 时直接用 item.message,
200
+ // 不再各自重写一遍文案(两处措辞必然漂移)。
201
+ const topLevelHits = !topLevelMustBeEmpty ? [] : topLevel
202
+ .filter((d) => !topAllowed.has(d.name))
203
+ .map((d) => ({
204
+ ...d,
205
+ message: `顶层声明 ${d.name}(第 ${d.line} 行):拼接产物应保持文件顶层零声明,避免与其它脚本/插件撞名`,
206
+ }));
207
+ const prefixHits = !prefix ? [] : missingPrefix.map((d) => ({
208
+ ...d,
209
+ message: `声明 ${d.name}(第 ${d.line} 行)缺少 ${prefix} 前缀:拼接分片共用同一作用域,裸名易被别段覆盖`,
210
+ }));
211
+ const duplicateHits = duplicates.map((d) => ({
212
+ ...d,
213
+ message: `「${d.scope === 'function' ? '同一函数作用域' : '同一代码块'}」内 ${d.name} 被声明 2 次以上`
214
+ + `(第 ${d.firstLine} 行与第 ${d.line} 行):var/function 会静默覆盖,后者顶掉前者且不报错`,
215
+ }));
216
+
217
+ const violations = [...topLevelHits, ...prefixHits, ...duplicateHits].map((d) => d.message);
218
+
219
+ return {
220
+ ok: violations.length === 0,
221
+ declarations,
222
+ duplicates: duplicateHits,
223
+ topLevel: topLevelHits,
224
+ missingPrefix: prefixHits,
225
+ violations,
226
+ sharedFrameId,
227
+ };
228
+ }
@@ -248,7 +248,7 @@ export async function confirmHits({ text, ext = '', grammar = '', hits = [] } =
248
248
  */
249
249
  export function makeSyncConfirmer(tree) {
250
250
  if (!tree || !tree.rootNode) return null;
251
- return (line, col) => {
251
+ const fn = (line, col) => {
252
252
  try {
253
253
  const l = Number(line);
254
254
  if (!Number.isFinite(l) || l < 1) return null;
@@ -261,6 +261,147 @@ export function makeSyncConfirmer(tree) {
261
261
  return null;
262
262
  }
263
263
  };
264
+ // 附带原始语法树:供「有树走树」的语义精筛(如凭据 credentialLinesFromTree)直接消费——
265
+ // 列级 opaque 确认与树级语义确认走同一棵预解析树,不重复解析(性能纪律)。
266
+ fn.tree = tree;
267
+ return fn;
268
+ }
269
+
270
+ /**
271
+ * 用语法树提取「凭据标识符被直接赋字符串/字节字面量」的行(方向 E1「有树走树」)。
272
+ *
273
+ * 为什么用树而不是 token:token 级看不出「赋值」的语法结构——
274
+ * `def _icon(token="text.secondary")` 的参数默认值、`token="前缀:"+uuid` 的复合右值、
275
+ * `x="a" if c else "b"` 的三元分支,在 token 流里都是 `ident = str`,只能一律当硬编码
276
+ * (外部 Python 仓库实测:这一类全是误报)。语法树上它们分别是
277
+ * default_parameter / assignment_pattern(不是赋值语句)、binary_operator(右值非字面量)、
278
+ * conditional_expression(右值非字面量),一眼排除。
279
+ *
280
+ * 判定语汇(凭据名识别、值是否有意义)由调用方 credential.js 以谓词传入:
281
+ * 本模块不 import credential.js,避免反向依赖成环,也保证「什么算凭据」只有一份定义。
282
+ *
283
+ * @param {object} tree parseText 的返回值(无根节点/异常一律返回 null,调用方回退)
284
+ * @param {(name:string, raw:string)=>boolean} credHit 「名字+值」组合判据(credential.js
285
+ * 的 isHardcodedCredentialValue——强弱分级与值置信度只有一份定义)
286
+ * @returns {null|Set<number>} 命中行号集合;null = 树不可用,调用方必须回退 token 级
287
+ */
288
+ export function credentialLinesFromTree(tree, credHit) {
289
+ if (!tree || !tree.rootNode || typeof credHit !== 'function') return null;
290
+ const out = new Set();
291
+ // 属性/成员访问左值(cfg.apikey、this.token、obj["secret"])在各语言的节点名。
292
+ const ATTRIBUTE_LHS = /^(attribute|member_expression|subscript|subscript_expression)$/;
293
+ // 字符串/字节字面量节点的类型名(各语言命名差异:string / string_literal /
294
+ // interpreted_string_literal(bytes/f-string) / raw_string_literal / character_literal)。
295
+ // 刻意不含 string_concat——`"a" + "b"` 的拼接值不是「直接字面量」,属复合右值。
296
+ const LIT = /^(string|string_literal|interpreted_string_literal|raw_string_literal|character_literal)$/;
297
+ // 字面量节点是否为「纯字面量」:f-string/插值串(children 含 interpolation /
298
+ // template_substitution / interpolation_expression)里值来自变量,不算硬编码内容。
299
+ const isPlainLiteral = (node) => {
300
+ if (!node || !LIT.test(node.type)) return false;
301
+ for (const c of node.children || []) {
302
+ if (/interpolation|substitution|expansion/i.test(String(c.type || ''))) return false;
303
+ }
304
+ return true;
305
+ };
306
+ // 遍历:收集「左值是凭据名、右值是单个字面量」的直接赋值行。
307
+ const walk = (node) => {
308
+ try {
309
+ // ① 真赋值语句(Python assignment / JS·TS assignment_expression):left=identifier,right=字面量
310
+ // 参数默认值(default_parameter/assignment_pattern)不在此类,天然排除。
311
+ if (node.type === 'assignment' || node.type === 'assignment_expression') {
312
+ const lhs = node.childForFieldName('left');
313
+ const rhs = node.childForFieldName('right');
314
+ // 左值名:裸标识符直接取;属性赋值(cfg.apikey = "…" / this.token = "…")取末段——
315
+ // 回退路径(token 级,`.` 允许跨越)对这类同样会报,树路径必须同等覆盖,否则改树反而漏报。
316
+ const name = lhs
317
+ ? (lhs.type === 'identifier' || lhs.type === 'variable_declarator'
318
+ ? String(lhs.text)
319
+ : String(lhs.text).split(/[.\[\]]/).pop().replace(/^['"]|['"]$/g, ''))
320
+ : '';
321
+ const lhsOk = lhs && (lhs.type === 'identifier' || ATTRIBUTE_LHS.test(lhs.type));
322
+ if (lhsOk && isPlainLiteral(rhs) && credHit(name, rhs.text)) {
323
+ out.add(node.startPosition.row + 1);
324
+ }
325
+ }
326
+ // ② 变量声明初始化(const token = "…"):variable_declarator name=identifier value=字面量
327
+ else if (node.type === 'variable_declarator' || node.type === 'init_declarator') {
328
+ const nm = node.childForFieldName('name');
329
+ const val = node.childForFieldName('value');
330
+ if (nm && nm.type === 'identifier' && isPlainLiteral(val) && credHit(String(nm.text), val.text)) {
331
+ out.add(node.startPosition.row + 1);
332
+ }
333
+ }
334
+ // ③ 对象字段({ token: "…" } / { apiKey: "…" }):pair,键名命中凭据词 + 值是字面量。
335
+ // f-string/插值字符串的值节点是 string 类型但含 interpolation 子节点——见 ③ 下的插值判定。
336
+ else if (node.type === 'pair' || node.type === 'property_assignment' || node.type === 'object_element') {
337
+ const keyNode = node.childForFieldName('key') || node.namedChildren[0];
338
+ const valNode = node.childForFieldName('value') || node.namedChildren[1];
339
+ const keyText = keyNode ? String(keyNode.text).replace(/^['"]|['"]$/g, '') : '';
340
+ if (keyNode && isPlainLiteral(valNode) && credHit(keyText, valNode.text)) {
341
+ out.add(node.startPosition.row + 1);
342
+ }
343
+ }
344
+ for (const child of node.namedChildren) walk(child);
345
+ } catch {
346
+ // 单节点异常不打断整树:已收集的命中照常返回(部分成功优于全失败)。
347
+ }
348
+ };
349
+ try {
350
+ walk(tree.rootNode);
351
+ return out;
352
+ } catch {
353
+ return null;
354
+ }
355
+ }
356
+
357
+ /**
358
+ * 用语法树收集「函数/方法定义名过短」的命中(方向 E 迁移第二条,short-func-name 树化)。
359
+ *
360
+ * 为什么必须用树(实测漏报):token 级只认「function 关键字后的 ident」,
361
+ * 于是 `class A { gh() {} }`、`const o = { ef() {} }` 这类**方法定义**完全查不到——
362
+ * 它们同样是「名字猜不出含义」的缺陷,却静默放行。
363
+ * 想在 token 级补齐只能靠「标识符 + ( 」近似,那会把 `ab(1)` 调用、`{ ef: ... }` 属性
364
+ * 全卷进来(误报换漏报,不划算)。语法树上它们是独立节点:
365
+ * function_declaration / generator_function_declaration / function_expression /
366
+ * method_definition / method_signature,且都带 name 字段;
367
+ * arrow_function、if_statement 无 name 字段 ⇒ 天然不误伤。
368
+ *
369
+ * @param {object} tree parseText 返回值
370
+ * @param {(name:string)=>boolean} isShort 名字判定(长度阈值 + 公认缩写白名单,由 naming.js 传入——判据只有一份)
371
+ * @returns {null|Array<{line:number, name:string}>} null = 树不可用,调用方回退 token 级
372
+ */
373
+ export function shortFunctionNamesFromTree(tree, isShort) {
374
+ if (!tree || !tree.rootNode || typeof isShort !== 'function') return null;
375
+ const DECL = new Set([
376
+ 'function_declaration', 'generator_function_declaration', 'function_expression',
377
+ 'method_definition', 'method_signature',
378
+ ]);
379
+ const out = [];
380
+ const walk = (node) => {
381
+ try {
382
+ if (DECL.has(node.type)) {
383
+ // 访问器(get ab() / set cd(v))跳过:它的 name 是**属性名**而非「做某事的函数名」,
384
+ // 且 get x / set x 配对是极常见惯例(框架存取器、计算属性)——按「函数名过短」报属语义错位。
385
+ // 刻意显式排除而非依赖初筛侥幸挡住:初筛放宽后这里不能变成误报源。
386
+ // 实测节点形态:method_definition 的 children[0].type 为 get/set(普通方法是 property_identifier)。
387
+ const lead = node.children && node.children[0];
388
+ const isAccessor = lead && /^(get|set)$/.test(String(lead.type));
389
+ const nm = node.childForFieldName('name');
390
+ // 仅裸标识符/属性名才算「定义名」;computed([x](){})等形态跳过,避免取到表达式文本
391
+ if (!isAccessor && nm && /^(identifier|property_identifier|private_property_identifier)$/.test(String(nm.type))) {
392
+ const name = String(nm.text);
393
+ if (isShort(name)) out.push({ line: nm.startPosition.row + 1, name });
394
+ }
395
+ }
396
+ for (const c of node.namedChildren) walk(c);
397
+ } catch { /* 单节点异常不打断整树 */ }
398
+ };
399
+ try {
400
+ walk(tree.rootNode);
401
+ return out;
402
+ } catch {
403
+ return null;
404
+ }
264
405
  }
265
406
 
266
407
  /** 清空全部缓存(测试与长驻进程内存回收用)。 */
@@ -72,7 +72,7 @@ export async function auditHistoryCommit(repoPath, commit, opts = {}, weights =
72
72
  writeFileSync(tarPath, arch.stdout);
73
73
  execFileSync('tar', ['-x', '-C', tmpDir, '-f', tarPath], { stdio: 'ignore' });
74
74
  const historyAudit = await auditFull(tmpDir, opts);
75
- const quality = scoreQuality(historyAudit.findings || [], weights, { files: historyAudit.files, docsScore: historyAudit.docsScore, dimFileCounts: historyAudit.dimFileCounts });
75
+ const quality = scoreQuality(historyAudit.findings || [], weights, { files: historyAudit.files, docsScore: historyAudit.docsScore, dimFileCounts: historyAudit.dimFileCounts, dimRuleCounts: historyAudit.dimRuleCounts });
76
76
  return {
77
77
  summary: historyAudit.summary || {},
78
78
  quality,
@@ -15,6 +15,7 @@ import { decorateTestExemptHint, makeFinding, summarize, normalizeExemptHints, C
15
15
  import { pickRepoLevelAnchorFile, repoLevelSemanticRuleIds } from './repo-level.js';
16
16
  import { checkDocsScore } from '../score/docs-score.js';
17
17
  import { runAuditExt } from './ext-runner.js';
18
+ import { runLintAdapters } from '../lint-adapter/index.js';
18
19
  import { buildRuleSlotMap, countRulesBySlot, slotStatsFromFindings } from './slot.js';
19
20
  import { findingsToYaml } from './report-yaml.js';
20
21
  /**
@@ -119,7 +120,21 @@ function appendIgnoreBlindSpot(findings, repoPath, scanned) {
119
120
  *
120
121
  * @returns {Promise<null|((line:number, col:number)=>boolean|null)>}
121
122
  */
123
+ /**
124
+ * 「有树走树」精筛 kind 清单(方向 E2):这些 astConfirmKind 的检查器在拿到语法树时
125
+ * 会走树语义路径(优于 token 近似),因此**只要规则集里有它们就预解析建树**——
126
+ * 不再局限于 astConfirmSpan(此前 .py 文件因槽位无 astConfirmSpan 规则而从不建树,
127
+ * 凭据精筛永远吃 token 级,是「有树不走树」的根因之一)。
128
+ * 新增成员必须同时在检查器里实现「无树回退」(D5),不得让审计因缺语法而失效。
129
+ */
130
+ const TREE_FIRST_KINDS = new Set(['credential-value', 'short-func-name']);
131
+
122
132
  async function buildTreeConfirmer(relPath, text, grouped) {
133
+ // 返回值语义(供 treeUsage 统计「有树不走树」是否复发):
134
+ // { confirm: fn, state: 'parsed' } ⇒ 语法可用且树真建立、并被消费
135
+ // { confirm: null, state: 'not-needed' } ⇒ 本文件规则集不需要树(省一次解析,正常)
136
+ // { confirm: null, state: 'no-grammar' } ⇒ 需要树但语言无语法(回退 token 级)
137
+ // { confirm: null, state: 'parse-failed' }⇒ 有语法却没建树(资产缺失/超预算/语法错误)——**最该警惕的一档**
123
138
  try {
124
139
  // ⚠️ 取**扩展名**(不是整条路径)——grammarForExt 收的是扩展名 ✓
125
140
  // 按 basename 的最后一个点取:避免 `docs/.vitepress/theme/index.ts` 这类**带点目录**踩坑 ✗
@@ -127,17 +142,18 @@ async function buildTreeConfirmer(relPath, text, grouped) {
127
142
  const base = String(relPath || '').split(/[\\/]/).pop();
128
143
  const ext = base.includes('.') ? base.slice(base.lastIndexOf('.') + 1) : '';
129
144
  const grammar = grammarForExt(ext);
130
- if (!grammar) return null;
145
+ if (!grammar) return { confirm: null, state: 'no-grammar' };
131
146
  let need = false;
132
147
  for (const rules of Object.values(grouped || {})) {
133
148
  if (!Array.isArray(rules)) continue;
134
- if (rules.some((r) => r?.astConfirmSpan === true)) { need = true; break; }
149
+ if (rules.some((r) => r?.astConfirmSpan === true || TREE_FIRST_KINDS.has(String(r?.astConfirmKind || '')))) { need = true; break; }
135
150
  }
136
- if (!need) return null;
151
+ if (!need) return { confirm: null, state: 'not-needed' };
137
152
  const tree = await parseText(text, grammar);
138
- return tree ? makeSyncConfirmer(tree) : null;
153
+ const confirm = tree ? makeSyncConfirmer(tree) : null;
154
+ return confirm ? { confirm, state: 'parsed' } : { confirm: null, state: 'parse-failed' };
139
155
  } catch {
140
- return null;
156
+ return { confirm: null, state: 'parse-failed' };
141
157
  }
142
158
  }
143
159
 
@@ -196,6 +212,31 @@ export function computeDimFileCounts(grouped, normFiles) {
196
212
  return counts;
197
213
  }
198
214
 
215
+ /**
216
+ * 每维度**绑定的生效规则数**(dim → 至少一条规则声明了该维度)。
217
+ *
218
+ * 用途:评分层据此把「零规则维度」权重记 0——本次生效规则集里一条规则都没绑定的维度,
219
+ * 对本仓库**没有检测能力**,不该按「无命中=满分」进总分(实测外部仓库五维齐满分抬到 85/A,
220
+ * 而人工核实出 6 个真问题)。
221
+ * 口径是**生效规则集**(grouped,已按仓库语言/槽位/豁免过滤),不是全量规则表:
222
+ * 纯 Python 仓库没有 C# 专属规则属正常,不该因此把可维护性记 0。
223
+ * 同维度多规则只计 1 次(要的是「有没有检测能力」,不是规则条数)。
224
+ * @returns {{[dim]: number}}
225
+ */
226
+ export function computeDimRuleCounts(grouped) {
227
+ const counts = {};
228
+ const seen = new Set();
229
+ for (const rules of Object.values(grouped || {})) {
230
+ if (!Array.isArray(rules)) continue;
231
+ for (const r of rules) {
232
+ if (!r || !r.id || seen.has(r.id)) continue;
233
+ seen.add(r.id);
234
+ for (const d of r.dimensions || []) counts[d] = (counts[d] || 0) + 1;
235
+ }
236
+ }
237
+ return counts;
238
+ }
239
+
199
240
  async function auditFiles(repoPath, files, opts = {}) {
200
241
  // 归一化:full 收集项用 path,changed 用 rel → 统一取 path
201
242
  const normFiles = files.map((f) => ({ path: f.path ?? f.rel, full: f.full, status: f.status }));
@@ -254,6 +295,8 @@ async function auditFiles(repoPath, files, opts = {}) {
254
295
  }
255
296
  // 动态权重分母(维度可作用文件数,见 computeDimFileCounts)——在所有规则过滤完成后统计
256
297
  const dimFileCounts = computeDimFileCounts(grouped, normFiles);
298
+ // 维度检测能力(生效规则集口径):评分层据此对零绑定维度记 0 权重
299
+ const dimRuleCounts = computeDimRuleCounts(grouped);
257
300
  const findings = [];
258
301
  if (opts.truncated) {
259
302
  findings.push(makeFinding({
@@ -271,13 +314,18 @@ async function auditFiles(repoPath, files, opts = {}) {
271
314
  const repoLevelRules = repoLevelSemanticRuleIds(grouped);
272
315
  const repoLevelAnchor = pickRepoLevelAnchorFile(normFiles);
273
316
  const fileTexts = []; // 跨文件重复检测用(全部代码文件文本)
317
+ // 语法树使用状态统计(方向 E3 防再哑门禁):随审计结果一起返回,
318
+ // 让「规则声明要吃树、却没吃到树」不再静默——parse-failed/no-grammar 数量在报告里可见。
319
+ const treeUsage = { parsed: 0, notNeeded: 0, noGrammar: 0, parseFailed: 0, byState: null };
320
+ const STATE_KEY = { parsed: 'parsed', 'not-needed': 'notNeeded', 'no-grammar': 'noGrammar', 'parse-failed': 'parseFailed' };
274
321
  for (const f of normFiles) {
275
322
  const text = readText(f.full);
276
323
  fileTexts.push({ path: f.path, text });
277
324
  const skipRepoLevel = repoLevelRules.size > 0 && f.path !== repoLevelAnchor;
278
325
  // tree-sitter 预解析(异步):有语法 + 本文件规则集确实要 astConfirmSpan 才解析;
279
326
  // 拿不到语法树 ⇒ treeConfirm 为 null ⇒ 检查器回退 token 级判定 ✓
280
- const treeConfirm = await buildTreeConfirmer(f.path, text, grouped);
327
+ const { confirm: treeConfirm, state: treeState } = await buildTreeConfirmer(f.path, text, grouped);
328
+ treeUsage[STATE_KEY[treeState] || 'parsed'] = (treeUsage[STATE_KEY[treeState] || 'parsed'] || 0) + 1;
281
329
  findings.push(...auditFile({ file: f.path, relPath: f.path, text, grouped }, {
282
330
  level: opts.auditLevel, repoHasJsYamlImport, repoPath,
283
331
  repoLevelRules: skipRepoLevel ? repoLevelRules : null,
@@ -345,6 +393,22 @@ async function auditFiles(repoPath, files, opts = {}) {
345
393
  try {
346
394
  findings.push(...(await runAuditExt(repoPath, { dir: opts.auditExtDir, log: opts.log })));
347
395
  } catch (e) { log?.warn?.(`审计扩展执行失败:${e?.message || e}`); }
396
+ // 外部 linter 委托层(方向 A):被审项目自带官方 linter(如 ruff——配置存在且 tools/·PATH 有可执行)时,
397
+ // 委托其 JSON 输出并入 findings。两条硬约束:①**只进评分与报告、绝不进拦截**(severity 恒封顶 warning,
398
+ // 见 lib/lint-adapter/runner.js,别人的规则集不裁决本仓能否提交);②探不到/跑不动/超时/坏输出**一律降级空**
399
+ // (D5,交回自研规则)。仅 full 范围委托:外部 linter 是全仓扫描器,diff 语义不符且拖慢提交门禁(与 analysisCoverage 同口径)。
400
+ // 必须放在 normalizeExemptHints 之前——外部 finding 同样要过豁免提示可信化。
401
+ // ⚠️ `opts.linters` 是**测试注入口**(可指定任意可执行路径),**不得接进 API/CLI**:
402
+ // lib/app/tool-call.js 的 buildAuditOpts 是字段白名单,外部 args 到不了这里;
403
+ // 一旦把它接进去,等于开「让审计引擎执行调用方指定二进制」的后门,改动时务必保持这条路封闭。
404
+ let linted = [];
405
+ if ((opts.scope || 'full') === 'full' && opts.lintAdapters !== false) {
406
+ try {
407
+ const la = await runLintAdapters(repoPath, { linters: opts.linters, log: opts.log });
408
+ findings.push(...la.findings);
409
+ linted = la.linted;
410
+ } catch (e) { log?.warn?.(`外部 linter 委托失败:${e?.message || e}`); }
411
+ }
348
412
  // 豁免提示可信化(2026-10-17)—— **必须放在所有 finding 追加完之后**:
349
413
  // 此前放在文件循环附近,后面还有 tree-doc/func-doc/split-docs/ignore/ext 五处追加 ⇒
350
414
  // 那些 finding 绕过校正,自证里仍能看到「提示 dsh-skip-quality 却没有标记能豁免」✗。
@@ -370,7 +434,30 @@ async function auditFiles(repoPath, files, opts = {}) {
370
434
  ok: true, scope: opts.scope || 'full', repo: repoPath, findings, summary: summarize(findings), slotStats, files: normFiles.length,
371
435
  docsScore,
372
436
  dimFileCounts,
437
+ dimRuleCounts,
438
+ // 外部 linter 委托状态(方向 A 防静默空转):本次委托了哪些 linter、各产出多少、降级原因。
439
+ // 项目自带 ruff 却长期 linted=[] ⇒ 报告里看得见(与 treeUsage 同一思路:用没用上外部权威源不靠猜)。
440
+ linted,
373
441
  analysisCoverage,
442
+ // 语法树消费状态(E3):needTree=规则声明要吃树的文件数,hasGrammar=其中有语法映射的,
443
+ // parsed=真建树数。parseFailed>0 或 coverage<1 ⇒ 语法资产/预算问题导致静默回退,报告里看得见。
444
+ treeUsage: (() => {
445
+ // needTree=规则声明要吃树的文件数;hasGrammar=其中语言有语法映射的;
446
+ // parseFailed=**有语法却没建出树**(资产缺失/超预算/语法错误)——防再哑核心指标。
447
+ // coverage=hasGrammar 里真建树比例;语法资产完好时应恒为 1。
448
+ const needTree = treeUsage.parsed + treeUsage.noGrammar + treeUsage.parseFailed;
449
+ const hasGrammar = treeUsage.parsed + treeUsage.parseFailed;
450
+ return {
451
+ needTree,
452
+ hasGrammar,
453
+ parsed: treeUsage.parsed,
454
+ tokenFallback: treeUsage.noGrammar + treeUsage.parseFailed,
455
+ noGrammar: treeUsage.noGrammar,
456
+ parseFailed: treeUsage.parseFailed,
457
+ notNeeded: treeUsage.notNeeded,
458
+ coverage: hasGrammar > 0 ? treeUsage.parsed / hasGrammar : null,
459
+ };
460
+ })(),
374
461
  // 层级聚合 YAML(summary → 拦截级别 → 目录 → 文件 → 规则明细)
375
462
  yaml: findingsToYaml(findings),
376
463
  };