dsh-git-push 2.18.2 → 2.20.11

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 (43) hide show
  1. package/.gitignore +4 -0
  2. package/README.md +3 -0
  3. package/cli.mjs +16 -3
  4. package/lib/ARCHITECTURE.md +3 -0
  5. package/lib/app/audit-api.js +1 -1
  6. package/lib/app/command-registry.js +13 -1
  7. package/lib/app/inject-text.js +1 -0
  8. package/lib/app/scope-check.js +69 -0
  9. package/lib/app/tool-call.js +49 -2
  10. package/lib/ast/credential.js +130 -14
  11. package/lib/ast/dataflow.js +127 -10
  12. package/lib/ast/index.js +2 -0
  13. package/lib/ast/naming.js +9 -1
  14. package/lib/ast/scope-collisions.js +228 -0
  15. package/lib/ast/treesitter.js +142 -1
  16. package/lib/audit/history.js +1 -1
  17. package/lib/audit/orchestrate.js +93 -6
  18. package/lib/audit/scope-policy.js +110 -0
  19. package/lib/audit-rules/audit-rules-dsh.yml +16 -1
  20. package/lib/audit-rules/audit-rules-nodejs.yml +21 -6
  21. package/lib/checks/common.js +4 -4
  22. package/lib/checks/dispatch.js +5 -0
  23. package/lib/checks/index.js +2 -0
  24. package/lib/checks/regex.js +2 -2
  25. package/lib/checks/scope-collision.js +68 -0
  26. package/lib/cli/commands-audit.mjs +1 -1
  27. package/lib/commit-push.js +6 -1
  28. package/lib/exempt/index.js +5 -2
  29. package/lib/git/ignore.js +6 -4
  30. package/lib/git/init-compat.js +83 -4
  31. package/lib/git/push.js +25 -2
  32. package/lib/git/sensitive.js +30 -1
  33. package/lib/lint-adapter/detect.js +161 -0
  34. package/lib/lint-adapter/index.js +50 -0
  35. package/lib/lint-adapter/runner.js +133 -0
  36. package/lib/rule/compilers/structure.js +24 -0
  37. package/lib/score/index.js +36 -4
  38. package/lib/self/index.js +1 -1
  39. package/package.json +20 -1
  40. package/scripts/bump-version.mjs +20 -5
  41. package/scripts/check-js-scope.mjs +87 -0
  42. package/scripts/check.mjs +39 -1
  43. package/skills/dev/dsh-git-push.md +8 -2
package/.gitignore CHANGED
@@ -37,3 +37,7 @@ lib/client.js
37
37
  # 缺失时 scripts/gen-preview.mjs 与 test-rule-slots-render 会自动生成一次,保证新克隆可用。
38
38
  assets/preview.html
39
39
 
40
+ # 外部 linter 委托层的工具副本(用户 2026-11-06 决定 git 忽略):
41
+ # tools/ruff 等二进制属本机/部署侧资产,不入库、不进 npm 发布包;部署副本由 sync_plugin 侧或手动放置。
42
+ /tools/
43
+ /tool/
package/README.md CHANGED
@@ -22,6 +22,7 @@ DSH 的 git 提交推送与代码审计插件:提交前自动过审计门禁
22
22
  | 豁免标记 | 给文件加/删豁免注释并校验是否真生效 | `exempt` |
23
23
  | I/O 风险扫描 | 扫描读写操作的风险分级 | `io_scan` / `file-io` |
24
24
  | 链接检查 | 检查文档里的 URL 是否有效 | `link_check` / `link-check` |
25
+ | 拼接产物作用域 | 查分片拼成单文件后同一作用域内的重名(后者静默顶掉前者) | `scope_check` / `scope-check` |
25
26
  | 巨型文件拆分 | 按顶层块拆分单文件并校验导出一致 | `module_splitter` / `module-splitter` |
26
27
  | git 透传 | 执行任意 git 命令,凭据自动注入 | `git_sluice` / `git` |
27
28
  | HTTP 接口直调 | 调用本插件的全部 HTTP 接口 | `git_api` / `api` |
@@ -68,6 +69,7 @@ npm_publish({ dir, dryRun, confirm, tag, otp }) // dryRun 默认 true(只
68
69
  exempt({ action, rule, path, scope, line, reason }) // action 与 rule 必填;path 可数组;scope=header(文件头)或 line
69
70
  io_scan({ repo, writeOnly }) // 两者都可空:writeOnly 空=读写都看
70
71
  link_check({ path }) // path 可空:空=整个工作区
72
+ scope_check({ files, repo, prefix, allowlist, topLevelMustBeEmpty }) // 全可空:files 空=读项目 dshScopeCheck.files;prefix 空=按项目契约
71
73
  module_splitter({ command, file, plan, dryRun }) // command 必填(analyze/split/verify);dryRun 可空
72
74
  ```
73
75
 
@@ -78,6 +80,7 @@ git-sluice account-check # 校验本机 GitHub 凭据
78
80
  git-sluice scan <目录> # 列出该目录下的 git 仓库
79
81
  git-sluice audit <仓库> --full # 全量审计(加 --json 拿明细)
80
82
  git-sluice commit <仓库> -m "msg" # 提交并推送(自动过审计门禁)
83
+ git-sluice scope-check [文件] # 查拼接产物同帧重名(无参数时读项目 dshScopeCheck.files)
81
84
  git-sluice help # 全部命令
82
85
  ```
83
86
 
package/cli.mjs CHANGED
@@ -35,7 +35,10 @@ import {
35
35
  export { cmdFileIo, cmdTreeDoc, cmdFunctions, cmdModuleSplitter };
36
36
 
37
37
  /** parseArgv 认识的选项白名单(cli-help-sync 机器比对基准,必须与 HELP 文本一致。
38
- * 注:-m 是单横线别名(helpSync 只比对 -- 双横线),不列入本表。 */
38
+ * 注:-m 是单横线别名(helpSync 只比对 -- 双横线),不列入本表。
39
+ * 注:**注册表驱动**的命令(scan/commit/clone/npm-publish/scope-check…)参数由
40
+ * lib/app/command-registry.js 的 params 校验,与本表无关;但 HELP 里写了的 flag
41
+ * 都必须在本表出现,否则 cli-help-sync 会报「HELP 写了但 parseArgv 不认」。 */
39
42
  export const KNOWN_FLAGS = ['--depth', '--full', '--ruleset', '--weights', '--include-ignored', '--push', '--no-push', '--dry-run', '--force', '--message', '--audit', '--ignore-patterns', '--requirements-confirmed', '--push-confirmed', '--json', '--max', '--owner', '--offline', '--paths', '--history', '--since', '--until', '--out', '--skip-empty',
40
43
  // npm 相关(与 command-registry 的 npm_publish 参数对齐:dir / dryRun / tag / otp / confirm)
41
44
  '--dir', '--tag', '--otp', '--confirm', '--global', '--ignore-scripts', '--async', '--no-dry-run',
@@ -43,6 +46,8 @@ export const KNOWN_FLAGS = ['--depth', '--full', '--ruleset', '--weights', '--in
43
46
  '--summary', '--write', '--type', '--kind', '--risk', '--op', '--root', '--readme',
44
47
  // identity-rewrite:额外要统一的邮箱
45
48
  '--extra-emails',
49
+ // scope-check(与 command-registry 的 scope_check 参数对齐)
50
+ '--files', '--repo', '--prefix', '--allowlist', '--top-level-must-be-empty',
46
51
  // 补齐的 5 个命令(clone / account-check / remote-create / set-visibility / gen-ssh-key)
47
52
  '--dest', '--branch', '--preview', '--max-file-mb', '--concurrency', '--visibility', '--email', '--no-check-ssh', '--token'];
48
53
 
@@ -71,6 +76,10 @@ const HELP = `git-sluice v${VERSION} — dsh-git-push 引擎独立 CLI(脱离
71
76
  git-sluice file-io [路径...] [--summary] [--write] [--type sync|async] [--kind read|write|delete|rename] [--risk high|medium|low] [--op <操作名>] [--json]
72
77
  文件读写调用扫描(三标签:类型/操作/上下文)——同步 I/O 在异步路径会阻塞;写/删/改名涉及数据安全
73
78
  git-sluice link-check <路径> 检查 md/文本中的链接有效性(只 warning,flaky 域名打折)
79
+ git-sluice scope-check [文件...] [--repo <目录>] [--prefix <前缀>] [--allowlist <名,名>] [--top-level-must-be-empty] [--files <文件,文件>] [--json]
80
+ 拼接产物作用域撞名(多段 JS 拼进同一作用域):同一函数帧内 var/function/const/let/class 重名会让后者静默顶掉前者,运行期毫无线索;
81
+ 判定按真实作用域帧(两个不同函数里的同名局部变量不算撞名);顶层声明与命名前缀按**被查项目自己**的 package.json(dshScopeCheck)判定,
82
+ 没声明就只查同帧重名(不拿本项目的 dshgp_ 去要求别人);不给文件时取该项目 dshScopeCheck.files
74
83
  git-sluice npm-publish [目录] [--dry-run|--no-dry-run] [--tag <tag>] [--otp <码>] [--confirm] [--json]
75
84
  npm 发包(注册为后台 job):默认 dry-run,只体检 + npm publish --dry-run(**不写 registry**);
76
85
  真发必须同时给 --no-dry-run 与 --confirm(不可撤销);体检项:private:true / 同名版本占用 / npm pack 清单
@@ -285,7 +294,7 @@ function readPkgJson() {
285
294
  * 每个条目 [命令名, handler(rest)];统一 parse 模式用 parseVia 包装。 */
286
295
 
287
296
 
288
- /** 注册表工具返回输出(默认文本化 summary/apiGuide;--json 直出完整返回)。 */
297
+ /** 注册表工具返回输出(默认文本化 summary/apiGuide/lines;--json 直出完整返回)。 */
289
298
  function printRegistryResult(r, json) {
290
299
  if (json) { console.log(JSON.stringify(r, null, 2)); return; }
291
300
  if (!r) return;
@@ -295,6 +304,8 @@ function printRegistryResult(r, json) {
295
304
  if (r.summary) L.push(`summary: ${JSON.stringify(r.summary)}`);
296
305
  if (r.quality) L.push(`quality: ${r.quality.score ?? '?'}/${r.quality.level ?? '?'}`);
297
306
  if (r.count != null) L.push(`count: ${r.count}`);
307
+ // lines:工具自备的可读文本行(逐文件结论、命中明细等)——避免为此另造输出通道
308
+ if (Array.isArray(r.lines) && r.lines.length) L.push(...r.lines);
298
309
  console.log(L.length ? L.join('\n') : JSON.stringify(r));
299
310
  }
300
311
 
@@ -332,7 +343,9 @@ export async function main(argv = process.argv.slice(2)) {
332
343
  try {
333
344
  const r = await callTool(reg.name, args, { workspaceRoot: process.cwd() }, cliPluginConfig(), console, null, null);
334
345
  printRegistryResult(r, args.json === true);
335
- return 0;
346
+ // 退出码如实反映结果:ok:false = 命令失败(门禁/脚本据此判失败)。
347
+ // ok:true 但 committed:false / pushed:false 这类「零改动正常路径」仍是 0。
348
+ return r && r.ok === false ? 1 : 0;
336
349
  } catch (e) { console.error(String((e && e.message) || e)); process.exitCode = 1; return 1; }
337
350
  }
338
351
  const handler = COMMANDS.get(cmd);
@@ -24,6 +24,9 @@
24
24
  注册各行精筛函数;新 kind 在此接线。
25
25
  4. **编排调度** `lib/audit/*`:`collector.js` 收文件 → `audit-file.js` 按 kind 调度到各检查器 →
26
26
  `orchestrate.js` 汇总、按规则包聚合命中数。`lib/audit/` 不驻留具体判定实现。
27
+ 例外(中立读取层):`client-entry.js` / `scope-policy.js` 只做「从仓库推导事实」
28
+ (客户端入口与分片目录、项目自己的作用域契约),供 `lib/checks/` 与 `lib/app/` 双向复用——
29
+ 放 `lib/app/` 会让 `checks → app` 反向依赖成环。
27
30
 
28
31
  ## 原则
29
32
 
@@ -127,7 +127,7 @@ export async function runAuditApi(repo, params = {}, cfg = {}) {
127
127
 
128
128
  const { summarize } = await import('../audit/index.js');
129
129
  const summary = summarize(auditResult.findings);
130
- const quality = scoreQuality(auditResult.findings, params.weights || {}, { files: auditResult.files, dimFileCounts: auditResult.dimFileCounts });
130
+ const quality = scoreQuality(auditResult.findings, params.weights || {}, { files: auditResult.files, dimFileCounts: auditResult.dimFileCounts, dimRuleCounts: auditResult.dimRuleCounts });
131
131
  // slot 归属映射(groupBy=slot 用):与 auditFiles 同源加载规则构建映射——
132
132
  // 审计返回不带 compiled,这里按相同 slots/disabledSlots 重新编译一次。
133
133
  let ruleSlotMap = new Map();
@@ -207,7 +207,7 @@ export const TOOL_REGISTRY = [
207
207
  ],
208
208
  },
209
209
  {
210
- name: 'git_api', cli: 'api', description: '直接调用本插件的 HTTP API(35 条接口,与浏览器/CLI 同源实现:内部走 handleHttp 同一条代码路径)。path=接口名(去掉 /api/git-push/ 前缀,如 status / rule-slots / audit / settings-get);method 默认 GET;query=查询参数 JSON(如 {"mode":"full"});body=POST 请求体 JSON;不传 path 则列出全部可用接口。写类接口(settings-set / repo-push 等)内部调用按本机同源放行。',
210
+ name: 'git_api', cli: 'api', description: '直接调用本插件的 HTTP API(36 条接口,与浏览器/CLI 同源实现:内部走 handleHttp 同一条代码路径)。path=接口名(去掉 /api/git-push/ 前缀,如 status / rule-slots / audit / settings-get);method 默认 GET;query=查询参数 JSON(如 {"mode":"full"});body=POST 请求体 JSON;不传 path 则列出全部可用接口。写类接口(settings-set / repo-push 等)内部调用按本机同源放行。',
211
211
  params: [
212
212
  { flag: 'path', type: 'string', positional: 0, desc: '接口名(缺省 = 列出全部接口)' },
213
213
  { flag: 'method', type: 'string', desc: 'HTTP 方法(默认 GET;写操作传 POST)' },
@@ -215,6 +215,18 @@ export const TOOL_REGISTRY = [
215
215
  { flag: 'body', type: 'string', desc: 'POST 请求体 JSON 字符串' },
216
216
  ],
217
217
  },
218
+ {
219
+ name: 'scope_check', cli: 'scope-check', description: '检查 JS 拼接产物的作用域撞名(多段 JS 拼进同一作用域时,同帧内 var/function 同名会让后者静默顶掉前者、运行时毫无报错线索)。判定按真实作用域帧——两个不同函数里的同名局部变量不算撞名。默认只查「同一函数帧内重名」(通用,任何项目可用);被查项目在 package.json 的 dshScopeCheck 声明了 files/prefix/allowlist/topLevelMustBeEmpty 时,按**项目自己的契约**追加查「顶层零声明 + 共享作用域命名前缀」,没声明就不查前缀(不拿本项目的 dshgp_ 要求别人)。files 缺省取项目 dshScopeCheck.files',
220
+ params: [
221
+ { flag: 'files', type: 'string', positional: 0, desc: '目标文件(逗号分隔;缺省读项目 package.json 的 dshScopeCheck.files)' },
222
+ { flag: 'repo', type: 'string', desc: '仓库根(缺省当前工作目录)' },
223
+ { flag: 'prefix', type: 'string', desc: '显式前缀(如 dshgp_):显式给了就对所有目标文件生效,不再按项目契约决定' },
224
+ { flag: 'allowlist', type: 'string', desc: '前缀例外名单(逗号分隔,覆盖项目声明)' },
225
+ // flag 与 package.json 的键同名:一处词汇,不做 CLI/配置两套命名
226
+ { flag: 'topLevelMustBeEmpty', type: 'boolean', desc: '显式要求文件顶层零声明(不给则按项目声明;CLI 写作 --top-level-must-be-empty)' },
227
+ { flag: 'json', type: 'boolean', desc: 'JSON 输出(CLI:git-sluice scope-check --json)' },
228
+ ],
229
+ },
218
230
  ];
219
231
 
220
232
  /**
@@ -36,6 +36,7 @@ export const FUNCTION_USAGE_HINT = [
36
36
  '· git_set_visibility —— 切换仓库 public/private。',
37
37
  '· git_clone —— 从 GitHub clone 到本地(走 GitHub API,不直连 github.com)。',
38
38
  '· link_check —— 检查文档内链接有效性(只报 warning,不拦截)。',
39
+ '· scope_check —— 检查 JS **拼接产物**的作用域撞名(多段 JS 拼进同一作用域时,同一函数帧内 var/function/const/let/class 重名会让后者静默顶掉前者、运行期毫无报错线索;判定按真实作用域帧,两个不同函数里的同名局部变量不算撞名)。参数:files(逗号分隔,缺省读项目 package.json 的 dshScopeCheck.files)/ repo / prefix / allowlist / topLevelMustBeEmpty。**通用**:没声明 dshScopeCheck 的项目只查同帧重名,不会拿本项目的 dshgp_ 前缀去要求别人;拼接产物做提交前自检、或给别的项目接门禁时用它(CLI 等价命令 git-sluice scope-check)。',
39
40
  '· npm_publish —— npm 发包(**后台 job**,返回 jobId 可用 job_output 查):默认 dryRun=true 只体检 + `npm publish --dry-run`(不写 registry ✗);真发必须同时传 confirm=true 与 dryRun=false(不可撤销,先 dryRun 看包内容)。参数:dir(目标包目录,缺省工作区)/ tag(默认 latest)/ otp(2FA)/ dryRun / confirm。',
40
41
  '· git_sluice —— 浅包装 git 透传工具(AI 直接调用任意 git 命令,凭据自动注入):args 传与 git 完全一致的参数串(空格分隔,路径含空格用引号);例:git_sluice({args:"status --short"}) / git_sluice({args:"log --oneline -5"}) / git_sluice({args:"branch -a"})。返回 status + stdout/stderr。git 的其余能力(log/diff/branch/tag/remote 等)用它;高频写操作仍走 git_commit_push/git_clone 等专用工具(自带审计/门禁)。',
41
42
  '【凭据由插件托管,不要到处找凭据】GitHub token 与 SSH 公钥存放在插件 config.json(git-push/config.json 的 githubToken、sshPub 键,0600);SSH 私钥仍为文件(git-push/id_rsa),由插件的推送/校验流程自动读取与选择通道(默认 SSH,token 401 回退 SSH)。',
@@ -0,0 +1,69 @@
1
+ /**
2
+ * 「拼接产物作用域检查」的**共享执行器**(工具 / 独立脚本 / 审计规则共用一份判定)。
3
+ *
4
+ * 为什么要有这一层:同一件事有三个入口(`scope_check` 工具、`scripts/check-js-scope.mjs`、
5
+ * 审计规则 kind=scope-collision),执行流程一旦各写一份就会漂移。这里只做
6
+ * 「找契约 → 逐文件分析 → 汇总」,真正的判定在 `lib/ast/scope-collisions.js`,
7
+ * 「按文件所属项目取契约」在 `lib/audit/scope-policy.js`(中立模块,审计侧也用它)。
8
+ *
9
+ * 契约适用口径(与审计侧**故意不同**,各有各的输入面):
10
+ * · 本执行器:目标文件是调用方**显式点名**的 ⇒ 视为产物;项目给了 `files` 清单
11
+ * 且不含该文件时仍不套契约(典型场景:分片源码不是产物,套前缀会把局部变量
12
+ * 全判成缺前缀)。
13
+ * · 审计侧(lib/checks/scope-collision.js):那是**全仓扫描**,必须严格按
14
+ * `files` 清单命中,否则每个 js 文件都会被套上前缀契约。
15
+ */
16
+ import { existsSync, readFileSync } from 'node:fs';
17
+ import { resolve } from 'node:path';
18
+
19
+ import { analyzeScopeCollisions } from '../ast/scope-collisions.js';
20
+ import { POLICY_SOURCE, readProjectScopePolicy } from '../audit/scope-policy.js';
21
+
22
+ export { POLICY_SOURCE };
23
+
24
+ /**
25
+ * 找出某个文件所属项目的契约配置(兼容旧名,实现在中立模块)。
26
+ * @param {string} file 目标文件绝对路径
27
+ */
28
+ export function policyForFile(file) {
29
+ return readProjectScopePolicy(file);
30
+ }
31
+
32
+ /**
33
+ * 逐文件跑检查。
34
+ * @param {{files:string[], prefix?:string, allowlist?:string[], topLevelMustBeEmpty?:boolean}} o
35
+ * prefix/allowlist/topLevelMustBeEmpty 显式给出时覆盖项目配置(顶层零声明需显式 true/false)。
36
+ * @returns {{ok:boolean, reports:Array<object>, policySources:string[]}}
37
+ */
38
+ export function runScopeCheck({ files = [], prefix = '', allowlist = [], topLevelMustBeEmpty } = {}) {
39
+ const reports = [];
40
+ const policySources = new Set();
41
+ for (const raw of files) {
42
+ const file = resolve(raw);
43
+ const own = readProjectScopePolicy(file);
44
+ // 项目没给 files 清单时,点名文件即产物;给了清单就只认清单内的文件
45
+ const contractApplies = own.declared && (own.files.length === 0 || own.isDeclaredArtifact);
46
+ const explicit = [];
47
+ if (prefix) explicit.push('prefix');
48
+ if (Array.isArray(allowlist) && allowlist.length) explicit.push('allowlist');
49
+ if (typeof topLevelMustBeEmpty === 'boolean') explicit.push('topLevel');
50
+ const policy = {
51
+ prefix: prefix || (contractApplies ? own.prefix : ''),
52
+ allowlist: Array.isArray(allowlist) && allowlist.length ? allowlist : (contractApplies ? own.allowlist : []),
53
+ topLevelMustBeEmpty: typeof topLevelMustBeEmpty === 'boolean'
54
+ ? topLevelMustBeEmpty
55
+ : (contractApplies && own.topLevelMustBeEmpty),
56
+ };
57
+ const source = explicit.length
58
+ ? `${POLICY_SOURCE.CLI}(${explicit.join('/')})`
59
+ : `${own.source}${own.configPath ? `:${own.configPath}` : ''}`;
60
+ policySources.add(source);
61
+ if (!existsSync(file)) {
62
+ reports.push({ file, ok: false, missing: true, violations: [`文件不存在:${file}`], declarations: [], duplicates: [] });
63
+ continue;
64
+ }
65
+ const result = analyzeScopeCollisions(readFileSync(file, 'utf8'), policy);
66
+ reports.push({ file, ...result, policy });
67
+ }
68
+ return { ok: reports.every((r) => r.ok), reports, policySources: [...policySources] };
69
+ }
@@ -10,7 +10,7 @@ import { existsSync, readFileSync, appendFileSync } from 'node:fs';
10
10
  import { MAX_MSG_PREVIEW } from './constants.js';
11
11
  import { access } from 'node:fs/promises';
12
12
  /** blocked 消息预览截断长度(工具返回精简——完整 message 走审计明细)。 */
13
- import { join } from 'node:path';
13
+ import { join, resolve, dirname } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
15
  import { spawnSync } from 'node:child_process';
16
16
  import './host-doc-checks.js'; // 审计包边界:文档漂移检查器由宿主注入(导入即接线,见 lib/app/host-doc-checks.js)
@@ -77,6 +77,8 @@ async function pushWithPostSteps(args, env, cfg) {
77
77
  ciTimeoutSec: Number(args.ciTimeoutSec) > 0 ? Number(args.ciTimeoutSec) : 900,
78
78
  // 精确 add 路径(逗号分隔,相对 repo);空 = git add -A 全量
79
79
  paths: String(args.paths || ''),
80
+ // 敏感文件扫描与审计同一开关:审计关闭 ⇒ 不扫(此前无条件全仓扫,属特权步骤)
81
+ scanSensitive: cfg.auditEnabled !== false,
80
82
  });
81
83
  // ── 鼓励使用结构化提交信息(messageItems):提醒 + 采用率留痕 ──────────────────
82
84
  // 为什么需要:默认路径(单串 message)更省事,结构化参数长期无人用 ⇒ 两件事互补:
@@ -523,7 +525,7 @@ async function runStandardAuditTool(args, env, cfg, log, weights) {
523
525
  : await auditWithScope(repo, auditOpts);
524
526
  const summary = summarize(auditResult.findings);
525
527
  // 0 文件(空目录/diff 0 变动)不评分——scoreQuality 返回 emptyResult 防满分
526
- const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files, dimFileCounts: auditResult.dimFileCounts });
528
+ const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files, dimFileCounts: auditResult.dimFileCounts, dimRuleCounts: auditResult.dimRuleCounts });
527
529
  // 审计后直接输出豁免类型统计 + 聚合类型 + 拦截列表(blocker 详情不用查 API)
528
530
  const exemptStats = exemptStatsOf(auditResult.findings);
529
531
  const blocked = auditResult.findings
@@ -748,6 +750,51 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
748
750
  }, env, cfg);
749
751
  return { ok: out?.status === 200 && out?.body?.ok !== false, status: out?.status, endpoint: ep, result: out?.body };
750
752
  }
753
+ case 'scope_check': {
754
+ // 拼接产物作用域撞名:判定在 lib/ast/scope-collisions.js、契约在 lib/audit/scope-policy.js、
755
+ // 执行流程在 lib/app/scope-check.js —— 与 scripts/check-js-scope.mjs、审计规则
756
+ // kind=scope-collision 三方共用同一份实现,此处只做参数映射与结果整形。
757
+ const { runScopeCheck } = await import('./scope-check.js');
758
+ const { readProjectScopePolicy } = await import('../audit/scope-policy.js');
759
+ const repoRoot = resolve(String(args.repo || env.workspaceRoot || process.cwd()));
760
+ const splitList = (value) => String(value || '').split(/[,;\s]+/).map((s) => s.trim()).filter(Boolean);
761
+ let targets = splitList(args.files).map((f) => resolve(repoRoot, f));
762
+ if (!targets.length) {
763
+ // 缺省取项目自己声明的产物清单(dshScopeCheck.files)——不猜文件名,
764
+ // 否则「哪些文件是拼接产物」这件事会散成两处判断(本文件 + package.json)。
765
+ const policy = readProjectScopePolicy(join(repoRoot, 'package.json'));
766
+ const base = policy.configPath ? dirname(policy.configPath) : repoRoot;
767
+ targets = policy.files.map((f) => resolve(base, f));
768
+ if (!targets.length) {
769
+ return { ok: false, error: `未指定 files,且 ${join(repoRoot, 'package.json')} 未声明 dshScopeCheck.files` };
770
+ }
771
+ }
772
+ const result = runScopeCheck({
773
+ files: targets,
774
+ prefix: String(args.prefix || ''),
775
+ allowlist: splitList(args.allowlist),
776
+ ...(typeof args.topLevelMustBeEmpty === 'boolean' ? { topLevelMustBeEmpty: args.topLevelMustBeEmpty } : {}),
777
+ });
778
+ const lines = result.policySources.map((src) => `策略来源:${src}`);
779
+ for (const report of result.reports) {
780
+ const rel = report.file.startsWith(`${repoRoot}/`) ? report.file.slice(repoRoot.length + 1) : report.file;
781
+ if (report.ok) {
782
+ lines.push(`✔ ${rel}:${(report.declarations || []).length} 个声明,无同帧重名`);
783
+ continue;
784
+ }
785
+ lines.push(`✗ ${rel}:`);
786
+ for (const violation of report.violations || []) lines.push(` - ${violation}`);
787
+ }
788
+ const violationCount = result.reports.reduce((sum, report) => sum + (report.violations || []).length, 0);
789
+ return {
790
+ ok: result.ok,
791
+ count: result.reports.length,
792
+ violations: violationCount,
793
+ policySources: result.policySources,
794
+ reports: result.reports,
795
+ lines,
796
+ };
797
+ }
751
798
  default:
752
799
  return { ok: false, error: `未知工具: ${toolName}` };
753
800
  }
@@ -6,9 +6,17 @@
6
6
  * 占位符判据(CRED_PLACEHOLDER / CRED_SCHEME_PREFIX / isMeaningfulCredentialValue)
7
7
  * 必须只有一份:两处检查共用,否则判据漂移会出现「同一串值 A 规则放行、
8
8
  * B 规则拦截」的自相矛盾。
9
+ *
10
+ * 精筛双路径(2026-11-06 方向 E1「有树走树」):
11
+ * checkCredentialRefAst(text, tree) 传入语法树时走 credentialLinesFromTree——按真语法
12
+ * 节点判「赋值左值是不是凭据名、右值是不是纯字面量」,参数默认值(default_parameter /
13
+ * assignment_pattern)、复合右值(binary_operator)、三元(conditional_expression)、
14
+ * f-string 插值天然落空;无树/解析失败回退 scanCredentialTokens(token 级近似)。
15
+ * 回退是常态路径之一(D5 口径)——双向样本回归见 test/test-tree-first-credential.mjs。
9
16
  */
10
17
 
11
18
  import { tokenize } from './tokenizer.js';
19
+ import { credentialLinesFromTree } from './treesitter.js';
12
20
 
13
21
  /**
14
22
  * 检查「凭据类标识符是否真的被赋了字面量值」(no-hardcoded-credentials kind 的 AST 精筛)。
@@ -66,16 +74,29 @@ const CRED_SCHEME_PREFIX = /^(gh[pousr]_|github_pat_|sk-[a-z]*-?|xox[baprs]-|glp
66
74
  */
67
75
  const CRED_INTERPOLATED = /\$\(|\$\{|^\$[A-Za-z0-9_]/;
68
76
 
69
- /** 去掉字符串字面量外层引号。 */
77
+ /** 去掉字符串字面量外层引号(含 Python bytes/raw/f 前缀:b"…" / rb'…')。 */
70
78
  function stripQuotes(raw) {
71
- return String(raw).replace(/^(\'|"|`)([\s\S]*)\1$/, '$2').trim();
79
+ return String(raw)
80
+ .replace(/^([a-zA-Z]{0,2})(\'|"|`)([\s\S]*)\2$/, '$3')
81
+ .trim();
72
82
  }
73
83
 
74
84
  /**
75
- * 判断一个字面量值是否算「真凭据」(非空、非掩码、非占位/演示)。
85
+ * 主题令牌/标签样式值形状:小写点分段(text.secondary / bg.hover / accent.subtle)
86
+ * 或「小写词+冒号」标签前缀(plugin-preset: / preview-remove:,后接拼接/插值)。
87
+ * 这类值是被 `token=`/`fill_token=` 之类**变量名撞词**带进来的样式枚举名,
88
+ * 不是凭据内容——外部仓库实测 10 条 blocker 全部误报源于此形态。
89
+ * 刻意取最小面:段内禁大写禁特殊字符、点分段≥2 或尾冒号;
90
+ * `hunter2`(全小写无点无冒号)这类真弱口令**不在豁免内**,照报。
91
+ */
92
+ const THEME_TOKEN_SHAPE = /^[a-z][a-z0-9_-]*(\.[a-z][a-z0-9_-]*)+:?$/;
93
+ const LABEL_COLON_SHAPE = /^[a-z][a-z0-9_-]*:$/;
94
+
95
+ /**
96
+ * 判断一个字面量值是否算「真凭据」(非空、非掩码、非占位/演示、非主题令牌样式值)。
76
97
  *
77
- * @param raw 原始字面量(可带引号)
78
- * @returns true = 像真凭据(应报);false = 占位符/空值(豁免)
98
+ * @param raw 原始字面量(可带引号,可带 Python bytes/raw 前缀)
99
+ * @returns true = 像真凭据(应报);false = 占位符/空值/主题令牌(豁免)
79
100
  */
80
101
  export function isMeaningfulCredentialValue(raw) {
81
102
  const v = stripQuotes(raw);
@@ -83,6 +104,10 @@ export function isMeaningfulCredentialValue(raw) {
83
104
  if (isPlaceholderText(v)) return false;
84
105
  // 运行时求值($(cmd) / ${VAR} / $VAR)→ 值不在代码里,不是硬编码
85
106
  if (CRED_INTERPOLATED.test(v)) return false;
107
+ // 主题令牌/标签前缀形状(text.secondary / plugin-preset:):变量名撞 token 词的样式枚举。
108
+ // scheme 前缀保护——带 ghp_/sk-/AKIA 等凭据前缀的值即便碰巧撞形状也照报,形状豁免不开后门。
109
+ CRED_SCHEME_PREFIX.lastIndex = 0;
110
+ if (!CRED_SCHEME_PREFIX.test(v) && (THEME_TOKEN_SHAPE.test(v) || LABEL_COLON_SHAPE.test(v))) return false;
86
111
  return !isPlaceholderText(v.replace(CRED_SCHEME_PREFIX, ''));
87
112
  }
88
113
 
@@ -134,8 +159,65 @@ export function checkPlaceholderCredentialAst(text = '', file = '') {
134
159
  return out;
135
160
  }
136
161
 
137
- /** 凭据语义标识符(命名含这些词的变量/字段才纳入判断)。 */
138
- const CRED_IDENT = /(password|passwd|pwd|secret|token|apikey|api_key|accesskey|access_key|cookie|credential|privatekey|private_key)/i;
162
+ /**
163
+ * 凭据语义标识符(命名**以这些词结尾**的变量/字段才纳入判断)。
164
+ *
165
+ * 此前判「名字里含凭据词即可」,外部 Python 仓库实测暴露两类误报:
166
+ * token_pattern = r'…'(正则模式变量)、_ICON_TOKEN_PROP = "_themed_icon_token"(属性名字面量)
167
+ * ——凭据词只是长描述名的**前缀/中段**,变量装的根本不是凭据值。
168
+ * 改为结尾锚定后:APP_UPDATE_TOKEN_SECRET(结尾 SECRET)、API_KEY、db_password、githubToken
169
+ * (camelCase 结尾 Token)这类「名字即凭据」的写法照常命中;
170
+ * password_length / token_pattern / secretCache 这类不再命中。
171
+ * 代价:mytoken2 这类尾部带数字的命名会漏——刻意取此边界(命中集宁窄勿宽,
172
+ * 前缀型真密钥串另有 secret-github-pat 等形状规则兜底)。
173
+ */
174
+ /**
175
+ * 凭据语义名两级判定:
176
+ * strong(词义无歧义:password/secret/credential/apikey/accesskey/privatekey/pwd…)
177
+ * → 右侧是有效字面量即判硬编码(历史行为)。
178
+ * weak(token/cookie/key 这类**常用普通词**:token_pattern=正则模式、_ICON_TOKEN_PROP=属性名、
179
+ * cookieChars=字符表)→ 仅当值本身有凭据置信度(scheme 前缀 ghp_/sk-/AKIA…
180
+ * 或 ≥20 位混合大小写+数字的高熵串)才判硬编码。
181
+ * 背景(外部 Python 仓库实测):把 token 当无歧义凭据名时,主题令牌/标签前缀/模式变量
182
+ * 全线误报(10 条 blocker 全假);而真凭据 APP_UPDATE_TOKEN_SECRET 的强词是 SECRET。
183
+ * 结尾锚定试过并再放宽回分段匹配——SECRET_KEY(强词在**前段**)被锚定漏掉即回归,
184
+ * 分段 + 强弱分级同时解决两者。
185
+ */
186
+ // strong:词义即凭据容器(cookie 的值就是会话凭据,属强词;1.1.4 测试夹具锁死其必报行为)。
187
+ const CRED_NAME_STRONG = /(password|passwd|pwd|secret|credential|cookie|api[_-]?key|access[_-]?key|private[_-]?key|auth[_-]?token|session[_-]?token|refresh[_-]?token)/i;
188
+ // weak:常用普通词(token 常做主题令牌/正则模式变量名、key 常做字典键/琴键名)——要值置信度。
189
+ const CRED_NAME_WEAK = /(token|key)/i;
190
+
191
+ /** 值置信度:scheme 前缀或高熵串(≥20 字符、字符集干净、大小写数字混合)。 */
192
+ const CRED_VALUE_ENTROPY = /^[A-Za-z0-9+/_=.:-]{20,}$/;
193
+
194
+ /** 凭据名分级('strong'|'weak'|null),导出供树提取器与 token 扫描共用同一份定义。 */
195
+ export function credentialNameTier(name) {
196
+ const n = String(name || '');
197
+ if (CRED_NAME_STRONG.test(n)) return 'strong';
198
+ if (CRED_NAME_WEAK.test(n)) return 'weak';
199
+ return null;
200
+ }
201
+
202
+ /**
203
+ * 「名字+值」组合判硬编码(token 路径与树路径共用的唯一判据)。
204
+ * strong 名维持历史口径;weak 名要求值有凭据置信度(scheme/高熵)。
205
+ */
206
+ export function isHardcodedCredentialValue(name, raw) {
207
+ const tier = credentialNameTier(name);
208
+ if (!tier) return false;
209
+ if (!isMeaningfulCredentialValue(raw)) return false;
210
+ if (tier === 'strong') return true;
211
+ const v = stripQuotes(raw);
212
+ CRED_SCHEME_PREFIX.lastIndex = 0;
213
+ if (CRED_SCHEME_PREFIX.test(v)) return true;
214
+ return CRED_VALUE_ENTROPY.test(v) && /[a-z]/.test(v) && /[A-Z]/.test(v) && /\d/.test(v);
215
+ }
216
+
217
+ /** 凭据语义名判定谓词(旧签名,兼容树提取器入参;tier 判定走 credentialNameTier)。 */
218
+ export function isCredentialIdent(name) {
219
+ return credentialNameTier(name) !== null;
220
+ }
139
221
 
140
222
  /**
141
223
  * 在一段 token 序列上判「凭据标识符右侧是否直接是有效字符串字面量」,命中行号写入 out。
@@ -147,7 +229,7 @@ const CRED_IDENT = /(password|passwd|pwd|secret|token|apikey|api_key|accesskey|a
147
229
  function scanCredentialTokens(tokens, out, lineOffset = 0) {
148
230
  for (let i = 0; i < tokens.length; i++) {
149
231
  const t = tokens[i];
150
- if (t.type !== 'ident' || !CRED_IDENT.test(t.value)) continue;
232
+ if (t.type !== 'ident' || !credentialNameTier(t.value)) continue;
151
233
  // 向后找该标识符所在语句的赋值/比较运算符(遇到语句边界就放弃)
152
234
  let opIdx = -1;
153
235
  for (let j = i + 1; j < Math.min(tokens.length, i + 8); j++) {
@@ -168,21 +250,55 @@ function scanCredentialTokens(tokens, out, lineOffset = 0) {
168
250
  const opTok = tokens[opIdx];
169
251
  const next = tokens[opIdx + 1];
170
252
  if (!next) continue;
171
- if (opTok.value === '=') {
172
- // 右侧直接是字符串字面量 → 真硬编码
173
- if (next.type === 'str' && isMeaningfulCredentialValue(next.value)) out.add(t.line + lineOffset);
253
+ // 字面量前缀(Python b"…"/rb'…'、JS 标签 foo`…`):分词器把前缀切成独立 ident,
254
+ // 值仍在紧随的 str/tmpl token 上。不认前缀会让 bytes 真凭据整行漏报
255
+ // (外部仓库实测 SECRET_KEY = b"…" 未被任何路径捕获)。
256
+ // 认前缀的条件:ident 值≤2 字符且紧随的字符串 token **列紧邻**(无前缀与引号之间
257
+ // 只允许一个空格),否则 `token = b; "x"` 这类跨语句会被误并。
258
+ const litTok = literalAfterPrefix(tokens, next, opIdx);
259
+ // 组合判据与树路径同一份(isHardcodedCredentialValue:strong 名直判 / weak 名要值置信度)
260
+ if (opTok.value === '=' && litTok && isHardcodedCredentialValue(t.value, litTok.value)) {
261
+ out.add(t.line + lineOffset);
174
262
  continue;
175
263
  }
176
- if (opTok.value === ':') {
264
+ if (opTok.value === ':' && litTok && isHardcodedCredentialValue(t.value, litTok.value)) {
177
265
  // 对象字面量 `token: 'abc'` → 真硬编码;`token: cfg.token` 是引用,不报
178
- if (next.type === 'str' && isMeaningfulCredentialValue(next.value)) out.add(t.line + lineOffset);
266
+ out.add(t.line + lineOffset);
179
267
  }
180
268
  }
181
269
  }
182
270
 
183
- export function checkCredentialRefAst(text = '') {
271
+ /**
272
+ * 取运算符右侧的「字面量 token」,兼容 Python bytes/raw/f 前缀与 JS 模板标签。
273
+ *
274
+ * 分词器把 `b"abc"` 切成 ident("b") + str("\"abc\""),直接看 next.type 会当成
275
+ * 「右侧是变量」而漏报真凭据。这里在 next 是**短小写 ident**(≤2 字符,形如 b/r/f/rb/fr)
276
+ * 且其后紧跟一个字符串 token、且**列紧邻**(间隔 ≤1 列)时,返回那个字符串 token。
277
+ * 列紧邻是必需的:`token = b; other = "x"` 里 b 与 "x" 分属两条语句,
278
+ * 不加列约束会把无关字符串当成 b 的值(实测跨语句误并报)。
279
+ *
280
+ * @returns 命中的字符串 token,否则原样返回 next(非字面量时为 null/其它类型,由调用方判 type)
281
+ */
282
+ function literalAfterPrefix(tokens, next, opIdx) {
283
+ if (!next) return null;
284
+ if (next.type === 'str' || next.type === 'tmpl') return next;
285
+ if (next.type !== 'ident' || !/^[a-zA-Z]{1,2}$/.test(String(next.value))) return null;
286
+ const after = tokens[opIdx + 2];
287
+ if (!after || (after.type !== 'str' && after.type !== 'tmpl')) return null;
288
+ if (after.line !== next.line) return null;
289
+ if (Math.abs(after.col - (next.col + String(next.value).length)) > 1) return null;
290
+ return after;
291
+ }
292
+
293
+ export function checkCredentialRefAst(text = '', tree = null) {
184
294
  const raw = String(text);
185
295
  const out = new Set();
296
+ // 「有树走树」:tree 为真语法树时,凭据赋值由语法节点判定(参数默认值/复合右值/三元
297
+ // 天然落空),bytes/raw/f-string 前缀也正常识别。树不可用或提取异常 ⇒ 回退 token 级。
298
+ if (tree && tree.rootNode) {
299
+ const fromTree = credentialLinesFromTree(tree, isHardcodedCredentialValue);
300
+ if (fromTree) return fromTree; // 树路径成功(含「无命中」的空集合)——不回退,避免两套判定叠加
301
+ }
186
302
  scanCredentialTokens(tokenize(raw), out);
187
303
  // markdown 行内代码段兜底:`token: "abc"` 里的反引号被分词器当成模板字面量定界符,
188
304
  // 整段合并成一个 tmpl token,内部**不产生** ident/punct/str,直接扫原始 token 会漏报。