dsh-git-push 2.8.6 → 2.9.3

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 (54) hide show
  1. package/README.md +24 -5
  2. package/assets/minihost.sh +35 -0
  3. package/assets/preview.html +36703 -0
  4. package/assets/start.sh +396 -0
  5. package/assets/tree-sitter/LICENSE +21 -0
  6. package/assets/tree-sitter/README.md +69 -0
  7. package/assets/tree-sitter/VERSIONS.txt +1 -0
  8. package/assets/tree-sitter/tree-sitter-javascript.wasm +0 -0
  9. package/assets/tree-sitter/tree-sitter-python.wasm +0 -0
  10. package/assets/tree-sitter/tree-sitter-typescript.wasm +0 -0
  11. package/assets/tree-sitter/tree-sitter.js +3980 -0
  12. package/assets/tree-sitter/tree-sitter.wasm +0 -0
  13. package/lib/app/apply.js +15 -2
  14. package/lib/app/command-registry.js +2 -1
  15. package/lib/app/handlers/workspace-paths.js +107 -0
  16. package/lib/app/http-handlers.js +19 -2
  17. package/lib/app/inject-text.js +1 -1
  18. package/lib/app/tool-call.js +60 -8
  19. package/lib/ast/code-lines.js +52 -0
  20. package/lib/ast/fs-hotspots.js +154 -0
  21. package/lib/ast/index.js +1 -1
  22. package/lib/ast/perf.js +26 -10
  23. package/lib/ast/tokenizer.js +7 -2
  24. package/lib/ast/treesitter.js +208 -0
  25. package/lib/audit/audit-file.js +3 -3
  26. package/lib/audit/collector.js +4 -0
  27. package/lib/audit/orchestrate.js +41 -1
  28. package/lib/audit-rules/audit-rules-cpp.yml +106 -14
  29. package/lib/audit-rules/audit-rules-go.yml +95 -14
  30. package/lib/audit-rules/audit-rules-nodejs.yml +2 -2
  31. package/lib/audit-rules/audit-rules-paths.yml +1 -1
  32. package/lib/audit-rules/audit-rules-performance.yml +39 -9
  33. package/lib/audit-rules/audit-rules-php.yml +93 -14
  34. package/lib/audit-rules/audit-rules-rust.yml +101 -14
  35. package/lib/audit-rules/audit-rules-swift.yml +91 -14
  36. package/lib/checks/dispatch.js +3 -3
  37. package/lib/checks/fs-scanner.js +57 -0
  38. package/lib/checks/index.js +1 -0
  39. package/lib/checks/regex.js +19 -4
  40. package/lib/core/workspace-paths.js +108 -0
  41. package/lib/fs/edit-after-read.js +39 -0
  42. package/lib/rule/compilers/numeric-kinds.js +7 -0
  43. package/lib/rule/registry.js +7 -0
  44. package/lib/self/index.js +1 -1
  45. package/lib/user-requirements.json +2 -1
  46. package/package.json +2 -1
  47. package/scripts/doc-version.mjs +19 -90
  48. package/scripts/readme-gen.mjs +72 -22
  49. package/scripts/scan-fs-hotspots.mjs +107 -0
  50. package/scripts/sync-plugin-install.mjs +84 -21
  51. package/scripts/sync-plugin.mjs +14 -9
  52. package/skills/dev/dsh-git-push.md +18 -1
  53. package/skills/guide/guide-cli-scripts.md +1 -1
  54. package/skills/guide/guide-commit-push.md +33 -0
package/lib/app/apply.js CHANGED
@@ -8,6 +8,7 @@
8
8
  import { VERSION } from '../self/index.js';
9
9
  import { persistGithubToken, persistSshPub, credentialsDir } from '../git/index.js';
10
10
  import { createEnvInjectionText, collectToolPaths, mapWorkspaceDirs } from '../context/index.js';
11
+ import { workspacePathsInjectionText } from '../core/workspace-paths.js';
11
12
  import { defaultConfig, resolveConfig } from '../client/index.js';
12
13
  import { loadDefineTool, registerTools, registerContext, registerHttp, registerPreStepInjection } from '../plugin/index.js';
13
14
  // 【2026-10-02 · DSH 0.2.0-rc.2 适配】0.2.0 删除了 settings.register / settings.get 旧 API
@@ -98,7 +99,12 @@ export async function apply(ctx, config = {}) {
98
99
  const envInjectText = (cwdOverride) => {
99
100
  if (!cfg.injectSystemPrompt) return '';
100
101
  const root = cwdOverride || env.workspaceRoot || process.cwd();
101
- if (envInjectCache instanceof Map && envInjectCache.has(root)) return envInjectCache.get(root);
102
+ // AI 自设工作区(可多个)优先于会话 cwd:会话 header 里可能是**陈旧路径**(实测注入出
103
+ // 0.1.6-alpha.1 的旧工作区 ✗)⇒ 有自设就显示自设那份(这就是「AI 自己提醒自己」的实际作用 ✓)
104
+ const aiPaths = workspacePathsInjectionText();
105
+ // 缓存键必须带上自设清单:否则改完清单后注入不刷新 ✗(同一 root 会命中旧缓存)
106
+ const cacheKey = aiPaths ? `${root}\u0000${aiPaths}` : root;
107
+ if (envInjectCache instanceof Map && envInjectCache.has(cacheKey)) return envInjectCache.get(cacheKey);
102
108
  let text = '';
103
109
  try {
104
110
  // 工具清单:lib/tool-probes.json 模板(只 key,跨平台裸名)→ which/where 实测
@@ -119,8 +125,15 @@ export async function apply(ctx, config = {}) {
119
125
  log?.warn?.(`环境注入探测失败,降级静态清单:${e?.message || e}`);
120
126
  text = createEnvInjectionText({ cwd: root, projectRoot: root });
121
127
  }
128
+ // 自设工作区块放在**最前**:AI 每轮先看到自己登记的路径 ✓
129
+ // 同时把基座里的会话 cwd 行标注为「仅兜底」——它取自会话文件,实测可能是陈旧路径 ✗,
130
+ // 不标注就会与上方自设清单并存、继续误导(两处表达同一事实 ⇒ 必须区分主次)
131
+ if (aiPaths && text) {
132
+ text = text.replace(/^- 当前工作目录 cwd:/m, '- 会话 cwd(仅兜底,可能陈旧;以本段上方的「AI 自设工作区」为准):');
133
+ text = `${aiPaths}\n${text}`;
134
+ }
122
135
  if (!(envInjectCache instanceof Map)) envInjectCache = new Map();
123
- envInjectCache.set(root, text);
136
+ envInjectCache.set(cacheKey, text);
124
137
  return text;
125
138
  };
126
139
 
@@ -127,6 +127,7 @@ export const TOOL_REGISTRY = [
127
127
  { flag: 'old', type: 'string', desc: '要被替换的字面文本(含空白,必须精确匹配;别名 old_string)' },
128
128
  { flag: 'new', type: 'string', desc: "替换后的文本(别名 new_string);**必传**,要删除请显式传空串 ''" },
129
129
  { flag: 'all', type: 'boolean', desc: '替换全部匹配(默认 false:要求唯一匹配;别名 replace_all)' },
130
+ { flag: 'allowDuplicate', type: 'boolean', desc: '放行「替换后产物包含整份原文 / 原文出现多次」的写入(默认拒绝:该形态会把文档写重;确认无误再开)' },
130
131
  ],
131
132
  },
132
133
  {
@@ -175,7 +176,7 @@ export const TOOL_REGISTRY = [
175
176
  ],
176
177
  },
177
178
  {
178
- name: 'git_api', cli: 'api', description: '直接调用本插件的 HTTP API(34 条接口,与浏览器/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 等)内部调用按本机同源放行。',
179
+ 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 等)内部调用按本机同源放行。',
179
180
  params: [
180
181
  { flag: 'path', type: 'string', positional: 0, desc: '接口名(缺省 = 列出全部接口)' },
181
182
  { flag: 'method', type: 'string', desc: 'HTTP 方法(默认 GET;写操作传 POST)' },
@@ -0,0 +1,107 @@
1
+ /**
2
+ * HTTP 处理层 · AI 自设工作区路径端点(workspace-paths)
3
+ *
4
+ * 一个端点两种方法(handleHttp 的 switch 按路径分发,方法在 ctx.method 里):
5
+ * · GET /api/git-push/workspace-paths
6
+ * 读回当前自设清单 + 注入文本预览(AI 用它自查「我登记的路径对不对」✓)
7
+ * · POST /api/git-push/workspace-paths
8
+ * 写自设清单。body 支持三种形态(都走同一套校验):
9
+ * { "paths": ["<绝对路径>", …] } 默认 set(整份替换)
10
+ * { "paths": [...], "mode": "add" } 追加(去重)
11
+ * { "paths": [...], "mode": "remove" } 移除
12
+ * { "path": "<绝对路径>", "mode": "add" } 单条简写
13
+ * 也支持 { "clear": true } 清空(回到「无自设 ⇒ 注入回退会话 cwd」)。
14
+ *
15
+ * 为什么要这个端点:环境注入里的 cwd 原先取自会话文件,实测会注入**陈旧路径**(本机注入出
16
+ * `…/0.1.6-alpha.1/工作区/…`,而真实工作区在别处)⇒ 让 AI 自己登记真实路径,注入优先显示它。
17
+ * 这正是「AI 自己提醒自己」的实现方式:注入里显示的就是 AI 自己写下的那份 ✓
18
+ */
19
+ import {
20
+ loadWorkspacePaths, saveWorkspacePaths, workspacePathsInjectionText, workspacePathsFile, MAX_WORKSPACE_PATHS,
21
+ } from '../../core/workspace-paths.js';
22
+
23
+ /** 从 body 取待处理路径数组(paths 数组优先;兼容单条 path 字符串)。 */
24
+ function pathsFromBody(body) {
25
+ if (Array.isArray(body?.paths)) return body.paths.map((x) => String(x || ''));
26
+ if (typeof body?.path === 'string' && body.path.trim()) return [body.path];
27
+ return [];
28
+ }
29
+
30
+ /** GET /api/git-push/workspace-paths —— 读自设清单 + 注入预览。 */
31
+ export function handleWorkspacePathsGet() {
32
+ const cur = loadWorkspacePaths();
33
+ const text = workspacePathsInjectionText();
34
+ return {
35
+ status: 200,
36
+ body: {
37
+ ok: true,
38
+ paths: cur.paths,
39
+ count: cur.paths.length,
40
+ updatedAt: cur.updatedAt,
41
+ updatedBy: cur.updatedBy,
42
+ file: workspacePathsFile(),
43
+ maxPaths: MAX_WORKSPACE_PATHS,
44
+ injection: text, // 注入时会显示成什么样(AI 自查用 ✓)
45
+ injectionActive: !!text, // false = 无自设 ⇒ 注入回退会话 cwd
46
+ usage: "POST 同路径写入:body {\"paths\":[\"<绝对路径>\", …], \"mode\":\"set|add|remove\"};{\"clear\":true} 清空",
47
+ },
48
+ };
49
+ }
50
+
51
+ /** POST /api/git-push/workspace-paths —— 写自设清单(set / add / remove / clear)。 */
52
+ export function handleWorkspacePathsSet(ctx) {
53
+ // body 容错:工具路径传的是**已解析对象**(tool-call 里 JSON.parse 后转字符串再交给 handleHttp),
54
+ // CLI 路径实测传进来的是**JSON 字符串**(`--body '{…}'` 原样)⇒ 两种都接受,
55
+ // 否则 CLI 调用会报「缺少 paths」而实际是 body 没被解析 ✗(2026-10-15 实测踩到)。
56
+ let body = ctx?.body;
57
+ if (typeof body === 'string') {
58
+ try { body = JSON.parse(body || '{}'); } catch { body = {}; }
59
+ }
60
+ if (!body || typeof body !== 'object' || Array.isArray(body)) body = {};
61
+ const mode = String(body.mode || 'set').toLowerCase();
62
+ const cur = loadWorkspacePaths();
63
+
64
+ if (body.clear === true || mode === 'clear') {
65
+ const r = saveWorkspacePaths([], { by: 'ai' });
66
+ return { status: r.ok ? 200 : 500, body: { ok: r.ok, mode: 'clear', paths: r.paths, error: r.rejected[0]?.reason } };
67
+ }
68
+
69
+ const input = pathsFromBody(body);
70
+ if (!input.length) {
71
+ return { status: 400, body: { ok: false, error: '缺少 paths(数组)或 path(字符串);清空请传 {"clear":true}' } };
72
+ }
73
+ if (!['set', 'add', 'remove'].includes(mode)) {
74
+ return { status: 400, body: { ok: false, error: `不支持的 mode: ${mode}(仅 set/add/remove/clear)` } };
75
+ }
76
+
77
+ if (mode === 'remove') {
78
+ // 移除按「字符串相等」比对(用户/AI 写进来的原样路径),避免因 resolve 差异删不掉
79
+ const want = new Set(input.map((x) => String(x).trim()).filter(Boolean));
80
+ const kept = cur.paths.filter((p) => !want.has(p));
81
+ const r = saveWorkspacePaths(kept, { by: 'ai' });
82
+ return {
83
+ status: r.ok ? 200 : 500,
84
+ body: { ok: r.ok, mode, removed: cur.paths.length - kept.length, paths: r.paths, error: r.rejected[0]?.reason },
85
+ };
86
+ }
87
+
88
+ const next = mode === 'add' ? [...cur.paths, ...input] : input;
89
+ const r = saveWorkspacePaths(next, { by: 'ai' });
90
+ // 全部条目被拒(如全是相对路径/不存在的目录)⇒ 必须报错,不能"成功但空"✗
91
+ // —— 否则调用方会以为写进去了,下一轮注入却什么都没有(实测过的误判形态)
92
+ const allRejected = r.paths.length === 0 && input.length > 0;
93
+ const okFinal = r.ok && !allRejected;
94
+ return {
95
+ status: okFinal ? 200 : 400,
96
+ body: {
97
+ ok: okFinal,
98
+ mode,
99
+ paths: r.paths,
100
+ count: r.paths.length,
101
+ rejected: r.rejected, // 被拒的路径 + 原因(相对路径 / 不存在 / 超上限)
102
+ file: r.file,
103
+ injection: workspacePathsInjectionText(),
104
+ error: okFinal ? undefined : (r.rejected[0]?.reason || '写入失败'),
105
+ },
106
+ };
107
+ }
@@ -27,6 +27,9 @@ import {
27
27
  import {
28
28
  handleSettingsGet, handleSettingsSet,
29
29
  } from './handlers/settings.js';
30
+ import {
31
+ handleWorkspacePathsGet, handleWorkspacePathsSet,
32
+ } from './handlers/workspace-paths.js';
30
33
  import {
31
34
  handleNpmAccount, handleNpmCheck, handleNpmOwned, handleNpmPackages, handleNpmInstall, handleNpmPublish,
32
35
  } from './handlers/npm.js';
@@ -56,10 +59,21 @@ export async function adaptHttpHandler(req, res, env, cfg) {
56
59
  return httpResult;
57
60
  }
58
61
 
59
- /** POST JSON 体:只接受非数组对象,其它一律当空对象。 */
62
+ /** POST JSON 体:接受对象,**也接受 JSON 字符串**(内部调用传的是字符串)。 */
60
63
  function readBody(req) {
61
64
  const raw = req && req['body'];
62
- return (raw && typeof raw === 'object' && !Array.isArray(raw)) ? raw : {};
65
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) return raw;
66
+ // 内部调用(git_api 工具 / CLI)把 body 以 **JSON 字符串** 传入(tool-call.js 里
67
+ // `body: bodyText`);原先一律当空对象 ⇒ **所有 POST 端点的 body 被静默丢弃** ✗
68
+ // (实测 2026-10-15:workspace-paths 的 POST 经工具/CLI 调用时 body 恒为空,
69
+ // 而浏览器路径走 adaptHttpHandler 的 readJsonBody ⇒ 正常 ✓ ⇒ 两条路径行为分叉)
70
+ if (typeof raw === 'string' && raw.trim()) {
71
+ try {
72
+ const j = JSON.parse(raw);
73
+ return (j && typeof j === 'object' && !Array.isArray(j)) ? j : {};
74
+ } catch { return {}; }
75
+ }
76
+ return {};
63
77
  }
64
78
 
65
79
  /** 统一构造 handler 上下文(各 handler 签名 handleXxx(ctx))。 */
@@ -125,6 +139,9 @@ export async function handleHttp(req = {}, env = {}, cfg = defaultConfig()) {
125
139
  case '/api/git-push/gen-ssh-key': return handleGenSshKey(ctx);
126
140
  case '/api/git-push/settings-get': return handleSettingsGet(ctx);
127
141
  case '/api/git-push/settings-set': return await handleSettingsSet(ctx);
142
+ // AI 自设工作区路径:同一路径按 HTTP 方法分发(GET 读清单 / POST 写清单)
143
+ case '/api/git-push/workspace-paths':
144
+ return method === 'POST' ? handleWorkspacePathsSet(ctx) : handleWorkspacePathsGet(ctx);
128
145
  default:
129
146
  return { status: 404, body: { ok: false, code: 'NOT_FOUND', message: `无此端点: ${method} ${path}` } };
130
147
  }
@@ -42,7 +42,7 @@ export const FUNCTION_USAGE_HINT = [
42
42
  '【凭据由插件托管,不要到处找凭据】GitHub token 与 SSH 公钥存放在插件 config.json(git-push/config.json 的 githubToken、sshPub 键,0600);SSH 私钥仍为文件(git-push/id_rsa),由插件的推送/校验流程自动读取与选择通道(默认 SSH,token 401 回退 SSH)。',
43
43
  '需要判断登录态 → 调 git_account_check;需要推送 → 调 git_commit_push。不要遍历用户目录找 token、不要把凭据抄进命令行或文档、不要在回复里明文输出凭据。',
44
44
  '【调用纪律】提交类操作先 git_scan 确认目标仓库;提交前核对 README(功能表/版本记录/用法);审计拦截 blocker 时先修复再提交;用户未要求推送时不要 push。',
45
- '· message 参数:**只能传字符串**(宿主在进插件前按工具 schema 校验,只认标量类型——数组/对象会被直接拒 ✗);要写结构化多条目请用配套参数 `messageItems`(数组:元素为字符串,或 {what,type?,scope?,why?,verify?,refs?};仅 what 必填)——它作为要点与正文,message 则作标题 ✓',
45
+ '· message 参数:**只能传字符串**(宿主在进插件前按工具 schema 校验,只认标量类型——数组/对象会被直接拒 ✗)。**推荐用法**:`message` 传标题字符串 + `messageItems` 传要点数组(元素为字符串,或 {what,type?,scope?,why?,verify?,refs?};仅 what 必填)⇒ 渲染成「标题 + 要点 + why/verify/refs 正文」✓。**该用它的信号**:① 一次提交含多个要点 ② 需要 why/verify 溯源;简单一句话就能说清时用字符串即可(不必强行结构化 ✗)',
46
46
  '(这些纪律只在**会产生新提交/要推送**时才起作用;工作区没改动时直接调用 git_commit_push 也不会报错——不要因为「没东西可提交」就绕开插件手敲 git。)',
47
47
  ].join('\n');
48
48
 
@@ -6,7 +6,7 @@
6
6
  * 与 HTTP 处理分开:两条入口(工具 / HTTP)的鉴权与返回形态完全不同。
7
7
  */
8
8
 
9
- import { existsSync, readFileSync } from 'node:fs';
9
+ 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 走审计明细)。 */
@@ -70,6 +70,30 @@ async function pushWithPostSteps(args, env, cfg) {
70
70
  // 精确 add 路径(逗号分隔,相对 repo);空 = git add -A 全量
71
71
  paths: String(args.paths || ''),
72
72
  });
73
+ // ── 鼓励使用结构化提交信息(messageItems):提醒 + 采用率留痕 ──────────────────
74
+ // 为什么需要:默认路径(单串 message)更省事,结构化参数长期无人用 ⇒ 两件事互补:
75
+ // ① **该用时提醒**:调用方只传单串、且它偏长或含换行 ⇒ 结果里带 usageHint(随 job 结果 JSON 回到调用方)
76
+ // ② **采用率留痕**:每次调用追加一行 JSON 到 <DSH_HOME>/git-push/commit-usage.log ⇒ 用数据判断是否有效
77
+ // 判定信号 = 「多要点」或「需要 why/verify 溯源」;简单一句话提交用字符串完全正确 ✓(不强行结构化 ✗)
78
+ const msgStr = typeof args.message === 'string' ? args.message : '';
79
+ const itemList = Array.isArray(args.messageItems) ? args.messageItems : null;
80
+ const looksStructured = msgStr.includes('\n') || msgStr.length > 150;
81
+ if (r && !itemList && looksStructured) {
82
+ r.usageHint = '本次提交信息是**单串**且偏长;若含多个要点或需要 why/verify 溯源,建议改用 messageItems'
83
+ + '(数组:元素为字符串或 {what,type?,scope?,why?,verify?,refs?},仅 what 必填)'
84
+ + '——message 作标题、条目渲染成要点与正文 ✓';
85
+ }
86
+ try {
87
+ if (process.env.DSH_HOME) {
88
+ appendFileSync(join(process.env.DSH_HOME, 'git-push', 'commit-usage.log'), JSON.stringify({
89
+ t: new Date().toISOString(),
90
+ structured: !!itemList,
91
+ items: itemList ? itemList.length : 0,
92
+ msgLen: msgStr.length,
93
+ repo: String(args.repo || '').slice(-60),
94
+ }) + '\n');
95
+ }
96
+ } catch { /* 留痕失败不影响提交 ✓ */ }
73
97
  if (r?.ok && r?.pushed) {
74
98
  try {
75
99
  // 统一走 updateRepoIndex(mode='rebuild' 合并不全量覆盖),
@@ -267,13 +291,39 @@ async function callNpmPublishJob(args = {}, jobs, exec, log, env = {}, cfg = {})
267
291
  otp: args.otp || '',
268
292
  confirm: args.confirm === true,
269
293
  });
270
- const outcome = (r) => (r && r.ok
271
- // 完成态必须用宿主认可的枚举值:`completed`(不是 `done` ✗)——
272
- // 历史缺陷:这里写 `status:'done'`,宿主 job_output 的校验只认
273
- // running|stopping|completed|killed|failed ⇒ 已完成的 job 一律读不出(报
274
- // `"value.job.status" must be one of [...]`),表现为「等了很久,结果似乎没成功」✗。
275
- ? { status: 'completed', output: JSON.stringify(r) }
276
- : { status: 'failed', detail: String((r && (r.error || r.blocked)) || 'npm publish 失败'), output: JSON.stringify(r || {}) });
294
+ /**
295
+ * 把发包结果映射成宿主 job 的 {status, detail, output} —— **成功也必须给 detail**。
296
+ *
297
+ * 历史缺陷(2026-10-16 实测):成功分支只写了 `output`(JSON 字符串),没写 `detail`
298
+ * ⇒ 宿主 job 的完成回执里没有可读结果,`job_output` 读出来是「(no new output)」✗,
299
+ * 只能去翻插件日志与 registry 侧面确认(clone / commit+push 都有 detail ⇒ 只有 npm 空 ✗)。
300
+ *
301
+ * 完成态枚举值同理:宿主只认 completed(不是 done ✗,见下方历史注释)。
302
+ * detail 里附带**判读提示**,避免把「发布延迟」当失败、把「staged」当发布成功。
303
+ */
304
+ const outcome = (r) => {
305
+ const o = r || {};
306
+ if (o.ok) {
307
+ const what = [o.name, o.version].filter(Boolean).join('@') || '(未知包)';
308
+ const bits = [
309
+ o.dryRun ? '**未写入 registry**(dry-run)' : `已发布到 ${o.registry || cfg?.npmRegistry || 'registry.npmjs.org'}`,
310
+ what,
311
+ o.tag ? `tag ${o.tag}` : '',
312
+ Array.isArray(o.packList) ? `文件 ${o.packList.length}` : '',
313
+ o.packSize ? `packed ${(Number(o.packSize) / 1048576).toFixed(2)}MB` : '',
314
+ ].filter(Boolean).join(' · ');
315
+ const tail = o.dryRun
316
+ ? '真发需同时传 confirm=true 与 dryRun=false(不可撤销)'
317
+ : '⚠️ 刚发完在 registry 查不到多为**发布延迟**(等 3~5 分钟复测,不是失败);'
318
+ + '若 npm 账号开了 2FA 而未带 otp,发布会进 **staged**(需在 npm 网站批准或带 otp 重发)';
319
+ return { status: 'completed', detail: `${bits}。${tail}`, output: JSON.stringify(o) };
320
+ }
321
+ const err = String(o.error || o.blocked || 'npm publish 失败');
322
+ const hint = /EOTP|one-time pass/i.test(err) ? '(需要一次性口令:传 otp=<6 位码> 重发)'
323
+ : /E409|previously (published|staged)/i.test(err) ? '(该版本已存在或在 staged:改版本号,或先处理 staged 记录)'
324
+ : /E403/i.test(err) ? '(权限/2FA:检查 token 是否具备该包发布权限)' : '';
325
+ return { status: 'failed', detail: `${err}${hint}`, output: JSON.stringify(o) };
326
+ };
277
327
  if (!jobs || typeof jobs.start !== 'function') {
278
328
  const r = await doPublish();
279
329
  return { ok: true, async: false, result: r };
@@ -560,6 +610,8 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
560
610
  old: args.old ?? args.old_string,
561
611
  new: args.new ?? args.new_string,
562
612
  all: (args.all ?? args.replace_all) === true,
613
+ // 逃生阀:默认拒绝「替换后产物包含整份原文 / 原文出现多次」(那种形态会把文档写重)
614
+ allowDuplicate: args.allowDuplicate === true,
563
615
  });
564
616
  return r.ok
565
617
  ? { ok: true, path: r.path, replaced: r.replaced, bytesBefore: r.bytesBefore, bytesAfter: r.bytesAfter }
@@ -46,6 +46,58 @@ export function makeCodeLineFilter(text = '', candidateLines = [], opts = {}) {
46
46
  };
47
47
  }
48
48
 
49
+ /* ───────────────────────── 列级精筛(行级判定的加强版) ───────────────────────── */
50
+
51
+ /**
52
+ * 正则初筛 → **列级** token 精筛。
53
+ *
54
+ * 为什么需要:行级判定只能回答「这一行有没有代码 token」,回答不了
55
+ * 「正则命中的**那一处**是不是落在字符串/注释里」。实测遗留误报:
56
+ *
57
+ * const hang = await provider.execute(session, { script: 'while (true) {}' });
58
+ *
59
+ * 该行确实含 ident(script / provider 等)⇒ 行级判定放行 ⇒
60
+ * performance/busy-wait-loop 把字符串字面量里的 while(true) 当成真实死循环报出 ✗。
61
+ *
62
+ * 做法:在行级判定之上,用 tokenizer 的 str/tmpl/comment token 构造「不透明区间」,
63
+ * 命中列落在区间内 ⇒ 判为「不是代码」。
64
+ *
65
+ * @param {string} text 文件全文
66
+ * @param {number[]} candidateLines 候选行(1-based)
67
+ * @param {{file?:string}} [opts]
68
+ * @returns {{isCode:(line:number)=>boolean, isCodeHit:(line:number, col:number)=>boolean}}
69
+ * isCodeHit 的 col 为 **1-based 列**(正则 exec 的 index + 1);
70
+ * 列缺失/非法时**退化为行级判定**(宁可放行,不因拿不到列而误杀)。
71
+ */
72
+ export function makeCodeSpanFilter(text = '', candidateLines = [], opts = {}) {
73
+ const base = makeCodeLineFilter(text, candidateLines, opts);
74
+ // 不透明区间只取**单行 token**:跨行 token(三引号/多行块注释)的 col 是续行内位置,
75
+ // 用它构造区间会算错。跨行场景本就由行级判定覆盖——续行不产 ident/num ⇒ 不算代码行。
76
+ const opaque = new Map(); // line → [[startCol, endColExclusive), ...]
77
+ for (const t of tokenize(text)) {
78
+ if (t.type !== 'str' && t.type !== 'tmpl' && t.type !== 'comment') continue;
79
+ const v = String(t.value);
80
+ if (v.includes('\n')) continue;
81
+ const col = Number(t.col);
82
+ if (!Number.isFinite(col) || col < 1) continue;
83
+ const arr = opaque.get(t.line) || [];
84
+ arr.push([col, col + v.length]);
85
+ opaque.set(t.line, arr);
86
+ }
87
+ return {
88
+ isCode: base.isCode,
89
+ isCodeHit: (line, col) => {
90
+ if (!base.isCode(line)) return false;
91
+ const ranges = opaque.get(line);
92
+ if (!ranges || !ranges.length) return true;
93
+ const c = Number(col);
94
+ if (!Number.isFinite(c) || c < 1) return true; // 拿不到列 ⇒ 退化为行级判定
95
+ for (const [s, e] of ranges) if (c >= s && c < e) return false;
96
+ return true;
97
+ },
98
+ };
99
+ }
100
+
49
101
  /**
50
102
  * 是否散文体文档 —— **只按扩展名判定**。
51
103
  *
@@ -0,0 +1,154 @@
1
+ /**
2
+ * AST 层 · FS 热点抽取(**单一实现**,供两处消费)
3
+ *
4
+ * ① 审计规则 `performance/multi-file-scanners`(仓库级:扫描实现 > 阈值 ⇒ notice)
5
+ * ② 独立 CLI `scripts/scan-fs-hotspots.mjs`(①stat 热点排序 + ④遍历入口 + ②③⑤ 明细)
6
+ *
7
+ * 【为什么要单独一个模块】同一份判据若在「审计规则」和「CLI」各写一套 ⇒ 必然漂移 ✗
8
+ * (本项目反复踩的坑)。这里只写一份,两边只做「取数 + 呈现」。
9
+ *
10
+ * 【口径来源】移植自 bench-template 的 scripts/scan-fs-hotspots.mjs(2026-10-16 交接),
11
+ * 但**函数边界用插件自己的 collectFuncRanges**(真括号配对)⇒ 比原脚本的正则更准 ✓
12
+ *
13
+ * ⚠️ 计数纪律:每个调用**只计一次**(先整文件扫一遍,再按字符位置归属到所属函数)。
14
+ * 反面教材(本文件第一版):先整文件收一遍、再每个函数各收一遍 ⇒ 同一调用被计两次 ✗
15
+ * ⇒ CLI 打出来 stat 48 而基线是 25 ✗(实测发现的真 bug)。
16
+ *
17
+ * 判据(六类,与交接文档一致):
18
+ * ① stat 调用点 —— 每个 stat 调用的 文件:行 + 所属函数 + 原始表达式(每条只出现一次)
19
+ * ② 重复 stat —— 同一函数内**同一表达式** stat ≥2 次(可合并成一次)
20
+ * ③ 重复 readdir —— 同一函数内同一表达式 readdir ≥2 次
21
+ * ④ 遍历入口 —— 函数体内有 readdir,且「自递归」或调用已知 walker 名
22
+ * ⑤ 逐文件扫描实现 —— 函数体内同时出现 readdir 与 stat ⇒ 一个「扫描器」实现
23
+ * ⑥ 汇总 —— 给调用方直接用的 totals
24
+ */
25
+ import { collectFuncRanges } from './perf.js';
26
+
27
+ /** 统计类调用(① 热点排序 / ⑤ 扫描器判定)。 */
28
+ const STAT_RE = /(?:^|[^\w$.])(?:fs\s*\.\s*)?(statSync|stat|lstatSync|lstat)\s*\(([^()]*)\)/g;
29
+ /** 目录列举类调用(③⑤④)。 */
30
+ const READDIR_RE = /(?:^|[^\w$.])(?:fs\s*\.\s*)?(readdirSync|readdir)\s*\(([^()]*)\)/g;
31
+ /** 已知遍历入口名(交接文档 §四.3 明说:这是名字白名单,新命名需补进来)。 */
32
+ export const FS_WALKERS = ['recursiveScanAll', 'walkWithIndex', 'scanDirShallow', 'recursiveScan', 'walkDir'];
33
+
34
+ /** 同函数内「同一表达式」的键:`statSync(dir)` —— 实参去空白。 */
35
+ const callKey = (name, args) => `${name}(${String(args).replace(/\s+/g, '')})`;
36
+
37
+ /** 字符偏移 → 行号(1-based)。 */
38
+ function lineAt(text, idx) {
39
+ let line = 1;
40
+ for (let i = 0; i < idx && i < text.length; i += 1) if (text[i] === '\n') line += 1;
41
+ return line;
42
+ }
43
+
44
+ /**
45
+ * 扫描单个文件的 FS 热点(每个调用只计一次)。
46
+ * @param {string} text 文件全文
47
+ * @param {string} [relPath] 相对路径(回填进结果,便于上层聚合与展示)
48
+ * @returns {{file:string, stats:Array, readdirs:Array, dupStats:Array, dupReaddirs:Array, walkers:Array, scanners:Array}}
49
+ */
50
+ export function scanFsHotspotsText(text = '', relPath = '') {
51
+ const s = String(text || '');
52
+ const out = {
53
+ file: relPath, stats: [], readdirs: [], dupStats: [], dupReaddirs: [], walkers: [], scanners: [],
54
+ };
55
+ const fns = collectFuncRanges(s);
56
+
57
+ /** 整文件扫一遍(**只此一次**):返回 {name,args,line,at,expr}。 */
58
+ const collect = (re) => {
59
+ const res = [];
60
+ re.lastIndex = 0;
61
+ let m;
62
+ while ((m = re.exec(s)) !== null) {
63
+ const at = m.index + (m[0].length - m[0].trimStart().length);
64
+ res.push({ name: m[1], args: m[2] || '', line: lineAt(s, at), at, expr: callKey(m[1], m[2] || '') });
65
+ }
66
+ return res;
67
+ };
68
+ /** 归属函数名(不在任何函数内 ⇒ '' = 顶层)。 */
69
+ const fnNameAt = (at) => {
70
+ const hit = fns.find((f) => at >= f.a && at <= f.b);
71
+ return hit ? hit.name : '';
72
+ };
73
+
74
+ for (const c of collect(STAT_RE)) out.stats.push({ ...c, fn: fnNameAt(c.at) });
75
+ for (const c of collect(READDIR_RE)) out.readdirs.push({ ...c, fn: fnNameAt(c.at) });
76
+
77
+ /** 同一组内「同一表达式出现 ≥2 次(且不同行)」⇒ 可合并。 */
78
+ const dups = (calls) => {
79
+ const seen = new Map();
80
+ const res = [];
81
+ for (const c of calls) {
82
+ if (seen.has(c.expr)) {
83
+ if (seen.get(c.expr) !== c.line) res.push(c);
84
+ } else seen.set(c.expr, c.line);
85
+ }
86
+ return res;
87
+ };
88
+
89
+ // 按「所属函数」分组(顶层同名归一组 ''),一次算出 ②③④⑤
90
+ const groups = new Map();
91
+ const groupOf = (fn, at) => {
92
+ const k = fn || '';
93
+ if (!groups.has(k)) groups.set(k, { fn: k, stats: [], readdirs: [], start: at });
94
+ return groups.get(k);
95
+ };
96
+ for (const c of out.stats) groupOf(c.fn, c.at).stats.push(c);
97
+ for (const c of out.readdirs) groupOf(c.fn, c.at).readdirs.push(c);
98
+
99
+ for (const g of groups.values()) {
100
+ out.dupStats.push(...dups(g.stats).map((c) => ({ ...c, fn: g.fn })));
101
+ out.dupReaddirs.push(...dups(g.readdirs).map((c) => ({ ...c, fn: g.fn })));
102
+ if (g.fn && g.readdirs.length && g.stats.length) {
103
+ out.scanners.push({ fn: g.fn, line: g.readdirs[0].line, readdir: g.readdirs[0].line, stat: g.stats[0].line });
104
+ }
105
+ // ④ 遍历入口:有 readdir,且(自递归 或 调用了已知 walker)
106
+ if (g.fn && g.readdirs.length) {
107
+ const r = fns.find((f) => f.name === g.fn);
108
+ if (r) {
109
+ const body = s.slice(r.a, r.b + 1);
110
+ const selfRe = new RegExp(`(?:^|[^\\w$.])${String(g.fn).replace(/\$/g, '\\$')}\\s*\\(`);
111
+ const walker = FS_WALKERS.find((w) => new RegExp(`(?:^|[^\\w$.])${w}\\s*\\(`).test(body));
112
+ if (selfRe.test(body) || walker) {
113
+ out.walkers.push({ fn: g.fn, line: lineAt(s, r.a), calls: walker || '(self)' });
114
+ }
115
+ }
116
+ }
117
+ }
118
+ return out;
119
+ }
120
+
121
+ /**
122
+ * 仓库级聚合:把每个文件的结果合并成「仓库视角」的汇总。
123
+ * @param {Array<{path:string, text:string}>} fileTexts
124
+ * @returns {{totals:object, files:Array, scanners:Array, dupStats:Array, dupReaddirs:Array, walkers:Array, hot:Array}}
125
+ */
126
+ export function scanFsHotspots(fileTexts = []) {
127
+ const files = [];
128
+ const scanners = [];
129
+ const dupStats = [];
130
+ const dupReaddirs = [];
131
+ const walkers = [];
132
+ const totals = { files: 0, stats: 0, readdirs: 0, dupStats: 0, dupReaddirs: 0, walkerCalls: 0, scanners: 0 };
133
+ for (const { path, text } of fileTexts) {
134
+ const r = scanFsHotspotsText(text, path);
135
+ files.push(r);
136
+ totals.files += 1;
137
+ totals.stats += r.stats.length;
138
+ totals.readdirs += r.readdirs.length;
139
+ totals.walkerCalls += r.walkers.length;
140
+ for (const x of r.scanners) scanners.push({ file: path, ...x });
141
+ for (const x of r.dupStats) dupStats.push({ file: path, ...x });
142
+ for (const x of r.dupReaddirs) dupReaddirs.push({ file: path, ...x });
143
+ for (const x of r.walkers) walkers.push({ file: path, ...x });
144
+ }
145
+ totals.scanners = scanners.length;
146
+ totals.dupStats = dupStats.length;
147
+ totals.dupReaddirs = dupReaddirs.length;
148
+ // ① stat 热点排序:按 stat 调用点数降序(CLI 用;审计规则不用)
149
+ const hot = files
150
+ .map((f) => ({ file: f.file, stats: f.stats.length, readdirs: f.readdirs.length }))
151
+ .filter((x) => x.stats > 0 || x.readdirs > 0)
152
+ .sort((a, b) => (b.stats - a.stats) || (b.readdirs - a.readdirs));
153
+ return { totals, files, scanners, dupStats, dupReaddirs, walkers, hot };
154
+ }
package/lib/ast/index.js CHANGED
@@ -22,7 +22,7 @@ export { checkSyncFs, checkEmptyCatchAst, checkComplexityAst, checkNestingDepthA
22
22
  export { checkFuncLinesAst, checkFuncDensityAst, funcRangesAst, maxFunctionLength, checkFileLines, countCommentLines, checkRepeatedStringsAst, checkCommentDensityAst } from './size.js';
23
23
  export { checkNameLengthAst, checkShortFunctionNameAst, checkSmallFileReadAst, checkConsoleLogJsonAst } from './naming.js';
24
24
  export { javaKtFuncRanges, detectLang } from './lang.js';
25
- export { makeCodeLineFilter, codeStringLiterals } from './code-lines.js';
25
+ export { makeCodeLineFilter, makeCodeSpanFilter, codeStringLiterals } from './code-lines.js';
26
26
  export { shellCdDynamicLines, writeIntoGitignoredLines } from './shell.js';
27
27
  export { checkMagicNumberSmartAst } from './magic-number.js';
28
28
  export {
package/lib/ast/perf.js CHANGED
@@ -122,6 +122,15 @@ export function loopBodyLines(text = '') {
122
122
  * 实测不加这层收窄时,本仓库 184 个文件里误报 218 处(log/push/emit/readFile 等重复调用
123
123
  * 多是有意为之)。
124
124
  */
125
+ /**
126
+ * fs「属性/目录」查询类调用名(2026-10-16 判据②并入后新增的收窄白名单)。
127
+ * 为什么单列一份:这些调用每次都是一次真实系统调用 —— `statSync(p)` 在同一函数里写两遍
128
+ * 纯粹是浪费(可直接合并成一次 ✓),而 `resolve/findX` 那类只是"可能开销不小"。
129
+ * 只收**无副作用的查询型**(stat/lstat/readdir/exists/access/realpath,含 Sync 变体);
130
+ * 不收 readFile/write/unlink 等有副作用的 —— 重复调用可能是有意为之 ✗。
131
+ */
132
+ const FS_LIKE_RE = /(?:^|\.)?(?:stat|statSync|lstat|lstatSync|readdir|readdirSync|exists|existsSync|access|accessSync|realpath|realpathSync)$/;
133
+
125
134
  const LOOKUP_LIKE_RE = /(?:^|\.)?(?:resolve|lookup|canonical|toPath|find[A-Z]|get[A-Z]|parse[A-Z]|normalize[A-Z]|compute[A-Z]|build[A-Z]|read[A-Z])/;
126
135
 
127
136
  /**
@@ -141,23 +150,25 @@ function innermostLoopRanges(text) {
141
150
 
142
151
  /**
143
152
  * astConfirmKind: "repeat-identical-call" 的 **allow** 集合 ——
144
- * 同一个循环体内 ≥2 次**实参完全相同**的函数调用所在行。
153
+ * 同一**循环体**或同一**函数体**内 ≥2 次**实参完全相同**的函数调用所在行。
145
154
  *
146
155
  * 背景(真实案例):外部项目里 `resolveModuleToFilePath` 在解析循环中被调用 8762 次(约 180 次/文件),
147
156
  * 累计 4581ms 占全量扫描 89%;而 fs 探测只有 191 次/11ms —— 瓶颈是**重复纯计算**,
148
157
  * 加一层记忆化后该函数 4581ms → 344ms、整体 5143ms → 763ms。
149
158
  *
150
159
  * 判据与边界(宁可漏报不误报):
151
- * · 只看循环体内(复用 loopBodyLines);
160
+ * · 作用域 = 最内层循环体 ∪ 函数体(2026-10-16 扩:原只判循环内;FS 热点判据②并入本规则,
161
+ * 同一函数内同一表达式被 stat/readdir ≥2 次同样可合并成一次 ⇒ 由「函数体」这一档覆盖);
152
162
  * · 比较「函数名 + 实参文本(去空白)」完全相同 —— 实参不同的重复调用(如同名函数不同入参)
153
163
  * 不报,因为无法静态判断哪个更贵;
154
164
  * · 只匹配**无嵌套括号**的调用(保守,嵌套实参的调用一律不判);
155
165
  * · 排除注释/字符串里的示例。
156
166
  * 注意:本规则是**代理特征**——它抓「完全重复的调用」,而案例里更常见的是「入参部分重叠」,
157
167
  * 那类只能靠运行时探针(分阶段计时 + 调用计数)定位。
158
- * 收窄:只判**查询/解析类**函数名(resolve/lookup/findX/getX/parseX/normalizeX/computeX/buildX)——
159
- * 这类通常纯函数且可能开销不小;而 log/push/emit/readFile 之类重复调用多是有意为之
160
- * (实测不加这层收窄时,本仓库 184 个文件里误报 218 处)。
168
+ * 收窄:只判**查询/解析类**函数名(resolve/lookup/findX/getX/parseX/normalizeX/computeX/buildX)
169
+ * 与 **fs 属性类**(stat/lstat/readdir/exists/access/realpath 及其 Sync 变体)——
170
+ * 前者通常纯函数且可能开销不小,后者每次都是一次真实系统调用(重复即为纯浪费 ✓);
171
+ * 而 log/push/emit 之类重复调用多是有意为之(实测不加收窄时,本仓库 184 个文件里误报 218 处)。
161
172
  * @param {string} text 文件全文
162
173
  * @returns {Set<number>} 命中行号集合
163
174
  */
@@ -165,14 +176,14 @@ export function repeatIdenticalCallLines(text = '') {
165
176
  const s = String(text || '');
166
177
  const out = new Set();
167
178
  const tokens = tokenize(s);
168
- // 只比最内层循环区间:外层区间会把不同内层循环里文本相同的调用误判成重复(实测误报已修)
169
- for (const [a, b] of innermostLoopRanges(s)) {
179
+ /** 在 [a,b] 区间内收集「同键重复调用」的行号(键 = 函数名 + 去空白实参)。 */
180
+ const scanRange = (a, b) => {
170
181
  const body = s.slice(a, b + 1);
171
182
  const seen = new Map();
172
183
  const re = /([A-Za-z_$][\w.$]*)\s*\(([^()]*)\)/g;
173
184
  let m;
174
185
  while ((m = re.exec(body)) !== null) {
175
- if (!LOOKUP_LIKE_RE.test(m[1])) continue;
186
+ if (!LOOKUP_LIKE_RE.test(m[1]) && !FS_LIKE_RE.test(m[1])) continue;
176
187
  const line = lineOf(s, a + m.index);
177
188
  if (inCommentOrString(tokens, line, m[0])) continue;
178
189
  const key = `${m[1]}(${m[2].replace(/\s+/g, '')})`;
@@ -182,7 +193,12 @@ export function repeatIdenticalCallLines(text = '') {
182
193
  seen.set(key, line);
183
194
  }
184
195
  }
185
- }
196
+ };
197
+ // ① 最内层循环区间:外层区间会把不同内层循环里文本相同的调用误判成重复(实测误报已修)
198
+ for (const [a, b] of innermostLoopRanges(s)) scanRange(a, b);
199
+ // ② 函数体区间(判据②并入:同一函数内重复的 fs 属性调用同样可合并 ⇒ 一次系统调用省一次)
200
+ // 注意 collectFuncRanges 返回的是 [{name,a,b}](不是 [a,b] 对)
201
+ for (const { a, b } of collectFuncRanges(s)) scanRange(a, b);
186
202
  return out;
187
203
  }
188
204
 
@@ -223,7 +239,7 @@ export function loopFullCollectionLines(text = '') {
223
239
  // ============================================================
224
240
 
225
241
  /** 收集函数块体区间:function 声明 + 箭头函数块体。返回 [{name, a, b}](a/b 为块体内部区间)。 */
226
- function collectFuncRanges(text) {
242
+ export function collectFuncRanges(text) {
227
243
  const out = [];
228
244
  const re = /(?:async\s+)?function\s*([\w$]*)\s*\([^)]*\)\s*\{/g;
229
245
  let m;