dsh-git-push 2.20.19 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/cli-tool.mjs +2 -4
- package/cli.mjs +7 -1
- package/lib/app/apply.js +4 -4
- package/lib/app/command-registry.js +22 -17
- package/lib/app/handlers/meta.js +2 -2
- package/lib/app/handlers/preprocess.js +107 -0
- package/lib/app/handlers/repo-actions.js +2 -2
- package/lib/app/http-handlers.js +13 -42
- package/lib/app/index.js +2 -1
- package/lib/app/inject-text.js +3 -3
- package/lib/app/preprocess-client.js +136 -0
- package/lib/app/repo-ownership.js +1 -1
- package/lib/app/schema.js +3 -3
- package/lib/app/severity.js +14 -0
- package/lib/app/slash-commands.js +5 -164
- package/lib/app/tool-call.js +73 -144
- package/lib/cli/commands-preprocess.mjs +74 -0
- package/lib/cli/commands-tool.mjs +3 -2
- package/lib/cli/commands-vcs.mjs +4 -4
- package/lib/cli/shared.mjs +35 -9
- package/lib/commit-push/pre-commit-engine.js +57 -10
- package/lib/commit-push.js +71 -27
- package/lib/{exempt/index.js → git/exempt-markers.js} +8 -1
- package/lib/git/ignore.js +1 -1
- package/lib/git/repos.js +2 -2
- package/lib/git/sensitive.js +1 -1
- package/lib/npm/publish.js +20 -5
- package/lib/plugin/auto-push.js +2 -2
- package/lib/preprocess/providers.js +191 -0
- package/lib/self/index.js +1 -1
- package/lib/skip-dirs.js +14 -55
- package/package.json +29 -37
- package/scripts/build-client.mjs +2 -0
- package/scripts/check.mjs +4 -2
- package/scripts/local-registry.mjs +2 -1
- package/cli-audit.mjs +0 -141
- package/lib/app/audit-api.js +0 -173
- package/lib/app/handlers/audit.js +0 -150
- package/lib/app/host-doc-checks.js +0 -25
- package/lib/app/scope-check.js +0 -69
- package/lib/ast/brace.js +0 -120
- package/lib/ast/callgraph.js +0 -135
- package/lib/ast/code-lines.js +0 -175
- package/lib/ast/consts.js +0 -12
- package/lib/ast/control-flow.js +0 -470
- package/lib/ast/credential.js +0 -315
- package/lib/ast/dataflow.js +0 -391
- package/lib/ast/dup-code.js +0 -165
- package/lib/ast/fs-hotspots.js +0 -154
- package/lib/ast/index.js +0 -38
- package/lib/ast/io-risk-const.js +0 -95
- package/lib/ast/io-risk-fn.js +0 -208
- package/lib/ast/io-risk-loop.js +0 -308
- package/lib/ast/io-risk.js +0 -314
- package/lib/ast/lang.js +0 -156
- package/lib/ast/line-count.js +0 -52
- package/lib/ast/magic-number.js +0 -272
- package/lib/ast/naming.js +0 -292
- package/lib/ast/perf.js +0 -488
- package/lib/ast/scope-collisions.js +0 -228
- package/lib/ast/scope.js +0 -241
- package/lib/ast/shell.js +0 -131
- package/lib/ast/size.js +0 -448
- package/lib/ast/symbol-index.js +0 -399
- package/lib/ast/tokenizer.js +0 -421
- package/lib/ast/treesitter.js +0 -413
- package/lib/audit/analysis-coverage.js +0 -98
- package/lib/audit/audit-file.js +0 -205
- package/lib/audit/auditignore-rules.js +0 -148
- package/lib/audit/checks.js +0 -17
- package/lib/audit/client-entry.js +0 -93
- package/lib/audit/collector.js +0 -610
- package/lib/audit/ext-runner.js +0 -80
- package/lib/audit/file-context.js +0 -391
- package/lib/audit/finding.js +0 -101
- package/lib/audit/gitignore-match.js +0 -113
- package/lib/audit/glob.js +0 -63
- package/lib/audit/history-report.js +0 -100
- package/lib/audit/history.js +0 -126
- package/lib/audit/ignore-blind.js +0 -102
- package/lib/audit/index.js +0 -33
- package/lib/audit/orchestrate.js +0 -672
- package/lib/audit/public.js +0 -24
- package/lib/audit/repo-level.js +0 -30
- package/lib/audit/report-yaml.js +0 -90
- package/lib/audit/scope-policy.js +0 -110
- package/lib/audit/slot.js +0 -66
- package/lib/audit-rules/audit-rules-comment.yml +0 -199
- package/lib/audit-rules/audit-rules-cpp.yml +0 -114
- package/lib/audit-rules/audit-rules-csharp.yml +0 -82
- package/lib/audit-rules/audit-rules-docs.yml +0 -32
- package/lib/audit-rules/audit-rules-dsh.yml +0 -177
- package/lib/audit-rules/audit-rules-filehealth.yml +0 -42
- package/lib/audit-rules/audit-rules-folder.yml +0 -99
- package/lib/audit-rules/audit-rules-frontend.yml +0 -335
- package/lib/audit-rules/audit-rules-go.yml +0 -103
- package/lib/audit-rules/audit-rules-i18n.yml +0 -45
- package/lib/audit-rules/audit-rules-java.yml +0 -105
- package/lib/audit-rules/audit-rules-nodejs.yml +0 -662
- package/lib/audit-rules/audit-rules-npm.yml +0 -187
- package/lib/audit-rules/audit-rules-paths.yml +0 -98
- package/lib/audit-rules/audit-rules-performance.yml +0 -245
- package/lib/audit-rules/audit-rules-php.yml +0 -101
- package/lib/audit-rules/audit-rules-private.yml +0 -24
- package/lib/audit-rules/audit-rules-python.yml +0 -106
- package/lib/audit-rules/audit-rules-robustness.yml +0 -31
- package/lib/audit-rules/audit-rules-rust.yml +0 -109
- package/lib/audit-rules/audit-rules-structure.yml +0 -158
- package/lib/audit-rules/audit-rules-swift.yml +0 -99
- package/lib/audit-rules/audit-rules-template.yml +0 -108
- package/lib/audit-ui-sdk/contract.js +0 -117
- package/lib/audit-ui-sdk/index.js +0 -17
- package/lib/checks/button-bind.js +0 -347
- package/lib/checks/common.js +0 -170
- package/lib/checks/credential-file.js +0 -43
- package/lib/checks/dataflow.js +0 -40
- package/lib/checks/dispatch.js +0 -117
- package/lib/checks/dup-code.js +0 -69
- package/lib/checks/dup-const.js +0 -232
- package/lib/checks/file-health.js +0 -150
- package/lib/checks/filter.js +0 -137
- package/lib/checks/folder.js +0 -173
- package/lib/checks/fs-scanner.js +0 -57
- package/lib/checks/hardcoded-path.js +0 -98
- package/lib/checks/index.js +0 -49
- package/lib/checks/io.js +0 -66
- package/lib/checks/magic-number.js +0 -42
- package/lib/checks/npm-json.js +0 -273
- package/lib/checks/private.js +0 -64
- package/lib/checks/regex.js +0 -298
- package/lib/checks/scope-collision.js +0 -68
- package/lib/checks/semantic.js +0 -134
- package/lib/checks/structural.js +0 -281
- package/lib/cli/commands-audit.mjs +0 -142
- package/lib/cli/commands-doc.mjs +0 -127
- package/lib/client-parts/audit/audit.js +0 -301
- package/lib/exempt/tool.js +0 -198
- package/lib/git/module-splitter.js +0 -47
- package/lib/link-check/index.js +0 -187
- package/lib/lint-adapter/detect.js +0 -161
- package/lib/lint-adapter/index.js +0 -50
- package/lib/lint-adapter/runner.js +0 -133
- package/lib/preprocess/audit.js +0 -98
- package/lib/preprocess/index.js +0 -78
- package/lib/rule/compilers/credential.js +0 -62
- package/lib/rule/compilers/dataflow.js +0 -38
- package/lib/rule/compilers/file-health.js +0 -75
- package/lib/rule/compilers/frontend.js +0 -86
- package/lib/rule/compilers/func.js +0 -35
- package/lib/rule/compilers/helpers.js +0 -71
- package/lib/rule/compilers/index.js +0 -29
- package/lib/rule/compilers/link-semantic.js +0 -45
- package/lib/rule/compilers/list-kinds.js +0 -12
- package/lib/rule/compilers/numeric-kinds.js +0 -73
- package/lib/rule/compilers/regex.js +0 -78
- package/lib/rule/compilers/structure.js +0 -107
- package/lib/rule/compilers.js +0 -17
- package/lib/rule/homoglyph.js +0 -45
- package/lib/rule/loader.js +0 -274
- package/lib/rule/registry.js +0 -122
- package/lib/rule/scope.js +0 -67
- package/lib/score/docs-score.js +0 -166
- package/lib/score/index.js +0 -234
- package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
- package/scripts/audit-ext/_example-readme-present.mjs +0 -34
- package/scripts/audit-ext/dsh-inject-declarations.mjs +0 -209
- package/scripts/audit-ext/variable-min-length.mjs +0 -102
- package/scripts/audit-gate.mjs +0 -235
- package/scripts/audit-runner.mjs +0 -35
- package/scripts/audit-runtime-check.mjs +0 -129
- package/scripts/browser-page-probe.mjs +0 -271
- package/scripts/check-js-scope.mjs +0 -87
- package/scripts/clean-date-comments.py +0 -102
- package/scripts/cpu-sample.mjs +0 -188
- package/scripts/doc-drift.mjs +0 -200
- package/scripts/hot-path-probe-cjs.cjs +0 -71
- package/scripts/hot-path-probe-fs-shim.mjs +0 -28
- package/scripts/hot-path-probe-fsp-shim.mjs +0 -31
- package/scripts/hot-path-probe.mjs +0 -153
- package/scripts/module-splitter.py +0 -800
- package/scripts/picker-repro.mjs +0 -115
- package/scripts/platform-scan.mjs +0 -168
- package/scripts/probe-recheck.mjs +0 -47
- package/scripts/rename-locator.mjs +0 -97
- package/scripts/rule-switch.mjs +0 -97
- package/scripts/rules-solo-audit.mjs +0 -173
- package/scripts/scan-file-io.mjs +0 -717
- package/scripts/scan-fs-hotspots.mjs +0 -107
- package/scripts/symbol-index.mjs +0 -85
- package/scripts/verify-prestep.mjs +0 -100
- package/skills/dev/audit-rule-authoring.md +0 -58
- package/skills/guide/guide-audit.md +0 -270
- /package/lib/{audit → app}/ownership.js +0 -0
- /package/lib/app/{schema-audit.js → schema-preprocess.js} +0 -0
- /package/lib/{audit-defaults.js → git/defaults.js} +0 -0
package/lib/app/schema.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
import { createRequire } from 'node:module';
|
|
11
11
|
|
|
12
12
|
// 审计侧设置键单独成文件(文件隔离阶段;展开合并后仍是同一个 Config 对象)
|
|
13
|
-
import { auditConfigShape } from './schema-
|
|
13
|
+
import { auditConfigShape } from './schema-preprocess.js';
|
|
14
14
|
// 引擎默认超时取单一来源(与运行期兜底共用),避免 schema 默认值漂移
|
|
15
15
|
import { PRE_COMMIT_TIMEOUT_MS_DEFAULT } from './constants.js';
|
|
16
16
|
|
|
@@ -87,7 +87,7 @@ export const Config = Schema.object({
|
|
|
87
87
|
workspaceRoot: Schema.string().default('').description('扫描根目录(空=DSH workspaceRoot)'),
|
|
88
88
|
extraRepos: Schema.array(Schema.string()).default([]).description('额外仓库路径(数组)'),
|
|
89
89
|
extraReposFile: Schema.string().default('').description('额外仓库清单文件(每行一个绝对路径,# 注释;运行时实时读取)'),
|
|
90
|
-
// —— 审计侧设置键(集中在 lib/app/schema-
|
|
90
|
+
// —— 审计侧设置键(集中在 lib/app/schema-preprocess.js,此处展开合并)——
|
|
91
91
|
...auditConfigShape(Schema),
|
|
92
92
|
maxCloneFileMB: Schema.number().default(10).description('clone 单文件体积上限(MB),0=不限'),
|
|
93
93
|
cloneConcurrency: Schema.number().default(6).description('clone 并发下载数'),
|
|
@@ -96,7 +96,7 @@ export const Config = Schema.object({
|
|
|
96
96
|
// 注意本项是**高级文件配置**,不进 UI 设置项;解析顺序见 pre-commit-engine.js 的 resolvePreCommitConfig。
|
|
97
97
|
preCommit: Schema.object({
|
|
98
98
|
command: Schema.string().default('').description('审计引擎命令(空=内置 node;走 PATH 自探测,找不到会显式报错而不是静默降级)'),
|
|
99
|
-
args: Schema.array(Schema.string()).default([]).description('
|
|
99
|
+
args: Schema.array(Schema.string()).default([]).description('引擎参数(空=审计包 CLI);相对路径按插件根解析'),
|
|
100
100
|
timeoutMs: Schema.number().default(PRE_COMMIT_TIMEOUT_MS_DEFAULT).description('引擎超时毫秒(超时按执行失败处理,fail-closed)'),
|
|
101
101
|
}).description('提交前预处理引擎(空=内置;换引擎只改这里)'),
|
|
102
102
|
pushMethod: Schema.string().default('ssh').description('推送通道:ssh(默认,推本地 HEAD、远端 sha 与本地一致)| api(Git Data API 重建提交)| auto(有私钥走 ssh,否则 api)'),
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「拦截级」严重度判定(宿主侧同步快照)
|
|
3
|
+
*
|
|
4
|
+
* 语义与审计包 `lib/engine/finding.js` 的 `isBlockerFinding` 相同:`blocker` 与 `error` 都算拦截级。
|
|
5
|
+
* 为什么宿主还留一份:调用点是**同步**的(HTTP handler 内即时过滤 findings),
|
|
6
|
+
* 而审计包只能异步加载。**不是又一处双份真相,是带对拍门禁的快照**——
|
|
7
|
+
* test/app/test-audit-severity-parity.mjs 会比对两边结果,分叉即红。
|
|
8
|
+
* @param {object} finding
|
|
9
|
+
* @returns {boolean}
|
|
10
|
+
*/
|
|
11
|
+
export function isBlockerSeverity(finding) {
|
|
12
|
+
const severity = finding?.severity;
|
|
13
|
+
return severity === 'blocker' || severity === 'error';
|
|
14
|
+
}
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* 插件入口层 · 用户输入框斜杠命令
|
|
3
3
|
*
|
|
4
4
|
* 官方通道:ctx.inject(['commands']) → commands.register({ name, description, input, handler })。
|
|
5
|
-
* 人在输入框打 /git-
|
|
5
|
+
* 人在输入框打 /git-scan 等命令,直接跑代码、不进模型。
|
|
6
|
+
* 注:审计类斜杠命令(/git-audit、/git-io-scan、/link-check)已随审计能力迁出宿主。
|
|
6
7
|
*
|
|
7
8
|
* ── 只注册「只读」命令 ──
|
|
8
9
|
* 这里挂的每条命令都零副作用:不写文件、不改远端、不发提交。写类操作
|
|
@@ -21,6 +22,9 @@ import { callTool } from './tool-call.js';
|
|
|
21
22
|
|
|
22
23
|
/* ───────────────────────── 通用工具 ───────────────────────── */
|
|
23
24
|
|
|
25
|
+
/** 路径不存在时的统一前缀(多个斜杠命令共用)。 */
|
|
26
|
+
const ERR_PATH_NOT_FOUND = '路径不存在: ';
|
|
27
|
+
|
|
24
28
|
/** 会话工作区路径。空 = 指挥家「未分类」(header.cwd 缺失)。 */
|
|
25
29
|
export function sessionCwdOf(invocation) {
|
|
26
30
|
const cwd = invocation?.agent?.session?.header?.cwd;
|
|
@@ -34,7 +38,6 @@ export function sessionCwdOf(invocation) {
|
|
|
34
38
|
*/
|
|
35
39
|
/** git 仓库向上探测的最大深度(超过即放弃,防深目录逐级 existsSync 拖慢)。 */
|
|
36
40
|
const GIT_ROOT_MAX_DEPTH = 20;
|
|
37
|
-
const BLOCKERS_LIST_MAX = 20; // /git-audit 拦截文件列表上限
|
|
38
41
|
const PREVIEW_LIST_MAX = 15; // /git-clone-preview 预览列表条数上限(防刷屏)
|
|
39
42
|
const LIST_PRINT_MAX = 20; // 通用列表打印上限(拦截文件/坏链接等,防刷屏)
|
|
40
43
|
|
|
@@ -94,78 +97,6 @@ function rejectRepo(usage, example, detail) {
|
|
|
94
97
|
return { kind: 'error', text: `${detail}\n${usage}${example ? '\n' + example : ''}` };
|
|
95
98
|
}
|
|
96
99
|
|
|
97
|
-
/* ───────────────────────── /git-audit ───────────────────────── */
|
|
98
|
-
|
|
99
|
-
const AUDIT_USAGE = '用法: /git-audit [路径] [--full] [--force]';
|
|
100
|
-
const AUDIT_EXAMPLE = '示例: /git-audit /path/to/repo --full;/git-audit /path/to/dir --force(非 git 目录强制全量扫描)';
|
|
101
|
-
/** 路径不存在错误前缀(4 个命令共用,统一文案防漂移)。 */
|
|
102
|
-
const ERR_PATH_NOT_FOUND = '路径不存在: ';
|
|
103
|
-
|
|
104
|
-
/** 兼容旧名(外部/测试可能仍在用)。 */
|
|
105
|
-
export function parseGitAuditInput(raw = '') {
|
|
106
|
-
const parsed = parseCommandInput(raw, ['--full', '--force'], AUDIT_USAGE);
|
|
107
|
-
if (parsed.error) return { path: '', scope: 'diff', error: parsed.error };
|
|
108
|
-
return { path: parsed.path, scope: parsed.opts.full ? 'full' : 'diff', force: parsed.opts.force === true };
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/** 兼容旧名。 */
|
|
112
|
-
export function resolveAuditRepo(rawPath, opts) {
|
|
113
|
-
return resolveTargetPath(rawPath, opts);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* 把 code_audit 结果收成输入框可显示的短文本(含 blocker 文件列表)。
|
|
118
|
-
* @param {object} r callTool('code_audit') 返回值
|
|
119
|
-
*/
|
|
120
|
-
export function formatGitAuditCommandText(r = {}) {
|
|
121
|
-
if (!r || r.ok === false) return r?.error || '审计失败';
|
|
122
|
-
// 修(回归):code_audit 1.11.5 后返回改版(无 block/findings——默认精简)——
|
|
123
|
-
// 旧实现依赖 r.block/r.findings → lines 空 → 输出「审计完成(无摘要)」。改用新返回
|
|
124
|
-
// summary(计数)+ quality(评分)+ blocked(拦截列表,含 2.0.4 includeFindings 前的结构)。
|
|
125
|
-
const lines = [];
|
|
126
|
-
const s = r.summary || {};
|
|
127
|
-
const quality = r.quality || {};
|
|
128
|
-
lines.push(`审计 ${r.repo || ''}(${r.scope === 'full' ? '全量' : '变动'})`);
|
|
129
|
-
lines.push(`评分 ${quality.score ?? '?'}/${quality.level ?? '?'} · ${s.blocker ?? 0} 拦截 / ${s.warning ?? 0} 警告 / ${s.notice ?? 0} 提示`);
|
|
130
|
-
const blockers = Array.isArray(r.blocked) ? r.blocked : [];
|
|
131
|
-
if (blockers.length) {
|
|
132
|
-
lines.push(`拦截 ${blockers.length} 个:`);
|
|
133
|
-
for (const b of blockers.slice(0, BLOCKERS_LIST_MAX)) {
|
|
134
|
-
const loc = b.line ? `${b.file}:${b.line}` : String(b.file || '');
|
|
135
|
-
lines.push(` ${loc}(${b.rule || ''})`);
|
|
136
|
-
}
|
|
137
|
-
if (blockers.length > BLOCKERS_LIST_MAX) lines.push(` …另有 ${blockers.length - BLOCKERS_LIST_MAX} 条`);
|
|
138
|
-
}
|
|
139
|
-
return lines.join('\n') || '审计完成';
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/** /git-audit handler 主体(可单测,不依赖 cordis)。 */
|
|
143
|
-
export async function runGitAuditCommand({ rawInput = '', invocation = null, env = {}, cfg = {}, log = null } = {}) {
|
|
144
|
-
const parsed = parseGitAuditInput(rawInput);
|
|
145
|
-
if (parsed.error) return { kind: 'error', text: parsed.error };
|
|
146
|
-
const sessionCwd = sessionCwdOf(invocation);
|
|
147
|
-
if (!parsed.path && !sessionCwd) {
|
|
148
|
-
return { kind: 'error', text: `当前会话未绑定工作区(未分类)。请指定 git 仓库路径。\n${AUDIT_USAGE}\n${AUDIT_EXAMPLE}` };
|
|
149
|
-
}
|
|
150
|
-
if (parsed.path && !isAbsolute(parsed.path) && !sessionCwd) {
|
|
151
|
-
return { kind: 'error', text: `相对路径需要会话工作区。请给绝对路径。\n${AUDIT_USAGE}\n${AUDIT_EXAMPLE}` };
|
|
152
|
-
}
|
|
153
|
-
const target = resolveTargetPath(parsed.path, { sessionCwd });
|
|
154
|
-
if (!target || !existsSync(target)) return { kind: 'error', text: `${ERR_PATH_NOT_FOUND}${target || '(空)'}` };
|
|
155
|
-
let repo = findGitRoot(target);
|
|
156
|
-
if (!repo) {
|
|
157
|
-
// 非 git 目录默认拒绝(全量扫非仓库目录可能打爆进程);--force 显式放行——
|
|
158
|
-
// code_audit 工具对非 git 目录自动走 auditFull(scope 强制 full,不依赖 git 元数据)
|
|
159
|
-
if (!parsed.force) {
|
|
160
|
-
return rejectRepo(AUDIT_USAGE, AUDIT_EXAMPLE, `不是 git 仓库: ${target}。拒绝全量扫非仓库目录(会把进程打爆);加 --force 强制扫描。`);
|
|
161
|
-
}
|
|
162
|
-
repo = target;
|
|
163
|
-
}
|
|
164
|
-
const r = await callTool('code_audit', { repo, scope: parsed.scope }, env, cfg, log);
|
|
165
|
-
if (!r || r.ok === false) return { kind: 'error', text: r?.error || '审计失败' };
|
|
166
|
-
return { kind: 'success', text: formatGitAuditCommandText(r) };
|
|
167
|
-
}
|
|
168
|
-
|
|
169
100
|
/* ───────────────────────── /git-scan ───────────────────────── */
|
|
170
101
|
|
|
171
102
|
const SCAN_USAGE = '用法: /git-scan [路径]';
|
|
@@ -207,93 +138,6 @@ export async function runGitScanCommand({ rawInput = '', invocation = null, env
|
|
|
207
138
|
return { kind: 'success', text: formatGitScanCommandText(r) };
|
|
208
139
|
}
|
|
209
140
|
|
|
210
|
-
/* ───────────────────────── /git-io-scan ───────────────────────── */
|
|
211
|
-
|
|
212
|
-
const IOSCAN_USAGE = '用法: /git-io-scan [路径] [--write]';
|
|
213
|
-
const IOSCAN_EXAMPLE = '示例: /git-io-scan --write';
|
|
214
|
-
|
|
215
|
-
/**
|
|
216
|
-
* 把 I/O 扫描结果收成输入框可显示的短文本。
|
|
217
|
-
* 数据形态:{ total, sync, byRisk:{high,medium,low,safe}, files:[{file,count}], items:[...] }
|
|
218
|
-
*/
|
|
219
|
-
export function formatIoScanCommandText(r = {}) {
|
|
220
|
-
if (!r || r.ok === false) return r?.error || 'I/O 扫描失败';
|
|
221
|
-
const total = Number(r.total) || 0;
|
|
222
|
-
if (!total) return `扫描根: ${r.root || '(会话工作区)'}\n未发现文件 I/O 调用。`;
|
|
223
|
-
const b = r.byRisk || {};
|
|
224
|
-
const lines = [
|
|
225
|
-
`扫描根: ${r.root || '(会话工作区)'}`,
|
|
226
|
-
`文件 I/O 调用 ${total} 处(同步 ${r.sync || 0} / 异步 ${total - (r.sync || 0)})`,
|
|
227
|
-
'',
|
|
228
|
-
'风险分布:',
|
|
229
|
-
` 🔴 高 ${b.high || 0} 🟠 中 ${b.medium || 0} 🟡 低 ${b.low || 0} 🟢 安全 ${b.safe || 0}`,
|
|
230
|
-
];
|
|
231
|
-
const items = Array.isArray(r.items) ? r.items : [];
|
|
232
|
-
const top = items.filter((hit) => hit.risk === 'high').slice(0, 10);
|
|
233
|
-
if (top.length) {
|
|
234
|
-
lines.push('', '高风险(改造优先级):');
|
|
235
|
-
for (const hit of top) {
|
|
236
|
-
const ctxs = [];
|
|
237
|
-
if (hit.inAsync) ctxs.push('异步路径');
|
|
238
|
-
if (hit.inLoop) ctxs.push('循环内');
|
|
239
|
-
if (hit.inRequest) ctxs.push('请求路径');
|
|
240
|
-
lines.push(` ${hit.file}:${hit.line} ${hit.call || hit.op || ''} ${ctxs.join('+') || '—'}`);
|
|
241
|
-
}
|
|
242
|
-
const highTotal = b.high || 0;
|
|
243
|
-
if (highTotal > top.length) lines.push(` …另有 ${highTotal - top.length} 处高危`);
|
|
244
|
-
}
|
|
245
|
-
return lines.join('\n');
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
/**
|
|
249
|
-
* /git-io-scan handler:扫描脚本里读写文件的调用与路径。
|
|
250
|
-
* 复用 scripts/scan-file-io.mjs(AST 四级分级,与审计 io-risk 同标准),
|
|
251
|
-
* 不另写一套扫描逻辑。
|
|
252
|
-
*/
|
|
253
|
-
export async function runGitIoScanCommand({ rawInput = '', invocation = null, env = {}, cfg = {}, log = null } = {}) {
|
|
254
|
-
const parsed = parseCommandInput(rawInput, ['--write'], IOSCAN_USAGE);
|
|
255
|
-
if (parsed.error) return { kind: 'error', text: parsed.error };
|
|
256
|
-
const sessionCwd = sessionCwdOf(invocation);
|
|
257
|
-
const target = resolveTargetPath(parsed.path, { sessionCwd });
|
|
258
|
-
if (parsed.path && !target) {
|
|
259
|
-
return { kind: 'error', text: `相对路径需要会话工作区。请给绝对路径。\n${IOSCAN_USAGE}` };
|
|
260
|
-
}
|
|
261
|
-
if (target && !existsSync(target)) return { kind: 'error', text: `${ERR_PATH_NOT_FOUND}${target}` };
|
|
262
|
-
const r = await callTool('io_scan', { repo: target || sessionCwd, writeOnly: parsed.opts.write === true }, env, cfg, log);
|
|
263
|
-
if (!r || r.ok === false) return { kind: 'error', text: r?.error || 'I/O 扫描失败' };
|
|
264
|
-
return { kind: 'success', text: formatIoScanCommandText(r) };
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
/* ───────────────────────── /link-check ───────────────────────── */
|
|
268
|
-
|
|
269
|
-
const LINK_USAGE = '用法: /link-check [文件或目录]';
|
|
270
|
-
const LINK_EXAMPLE = '示例: /link-check README.md';
|
|
271
|
-
|
|
272
|
-
/** 把链接检查结果收成短文本。 */
|
|
273
|
-
export function formatLinkCheckCommandText(r = {}) {
|
|
274
|
-
if (!r || r.ok === false) return r?.error || '链接检查失败';
|
|
275
|
-
const findings = Array.isArray(r.findings) ? r.findings : [];
|
|
276
|
-
if (!findings.length) return `共检查链接 ${r.count || 0} 个,全部有效。`;
|
|
277
|
-
const bad = findings.filter((f) => f && f.ok === false);
|
|
278
|
-
const lines = [`共检查 ${r.count || findings.length} 个链接,其中 ${bad.length} 个无效:`, ''];
|
|
279
|
-
for (const f of bad.slice(0, LIST_PRINT_MAX)) {
|
|
280
|
-
lines.push(` ✗ ${f.url || f.link || '(空)'}${f.error ? ` — ${f.error}` : ''}`);
|
|
281
|
-
}
|
|
282
|
-
if (bad.length > LIST_PRINT_MAX) lines.push(` …另有 ${bad.length - LIST_PRINT_MAX} 个`);
|
|
283
|
-
return lines.join('\n');
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
export async function runLinkCheckCommand({ rawInput = '', invocation = null, env = {}, cfg = {}, log = null } = {}) {
|
|
287
|
-
const parsed = parseCommandInput(rawInput, [], LINK_USAGE);
|
|
288
|
-
if (parsed.error) return { kind: 'error', text: parsed.error };
|
|
289
|
-
const sessionCwd = sessionCwdOf(invocation);
|
|
290
|
-
const target = resolveTargetPath(parsed.path, { sessionCwd }) || env.workspaceRoot || '';
|
|
291
|
-
if (target && !existsSync(target)) return { kind: 'error', text: `${ERR_PATH_NOT_FOUND}${target}` };
|
|
292
|
-
const r = await callTool('link_check', { path: target }, env, cfg, log);
|
|
293
|
-
if (!r || r.ok === false) return { kind: 'error', text: r?.error || '链接检查失败' };
|
|
294
|
-
return { kind: 'success', text: formatLinkCheckCommandText(r) };
|
|
295
|
-
}
|
|
296
|
-
|
|
297
141
|
/* ───────────────────────── /git-account ───────────────────────── */
|
|
298
142
|
|
|
299
143
|
const ACCOUNT_USAGE = '用法: /git-account';
|
|
@@ -356,10 +200,7 @@ export async function runGitClonePreviewCommand({ rawInput = '', env = {}, cfg =
|
|
|
356
200
|
* keep: 便于测试断言注册集合,避免漏挂/多挂。
|
|
357
201
|
*/
|
|
358
202
|
export const SLASH_COMMANDS = [
|
|
359
|
-
{ name: 'git-audit', description: '审计当前会话工作区(未分类须写路径;--full 全量)', input: { hint: '[路径] [--full]' }, run: runGitAuditCommand },
|
|
360
203
|
{ name: 'git-scan', description: '列出各仓库分支/未提交/未推送(只读)', input: { hint: '[路径]' }, run: runGitScanCommand },
|
|
361
|
-
{ name: 'git-io-scan', description: '扫描脚本里读写文件的调用与路径,标四级风险(只读)', input: { hint: '[路径] [--write]' }, run: runGitIoScanCommand },
|
|
362
|
-
{ name: 'link-check', description: '检查文档内链接有效性(只读)', input: { hint: '[文件或目录]' }, run: runLinkCheckCommand },
|
|
363
204
|
{ name: 'git-account', description: '校验 GitHub 账号与凭据(只读)', input: { hint: '' }, run: runGitAccountCommand },
|
|
364
205
|
{ name: 'git-clone-preview', description: '预览 clone 将下载/跳过哪些文件,不落盘(只读)', input: { hint: '<owner/repo> [--branch 名]' }, run: runGitClonePreviewCommand },
|
|
365
206
|
];
|
package/lib/app/tool-call.js
CHANGED
|
@@ -13,10 +13,7 @@ import { access } from 'node:fs/promises';
|
|
|
13
13
|
import { join, resolve, dirname } from 'node:path';
|
|
14
14
|
import { fileURLToPath } from 'node:url';
|
|
15
15
|
import { spawnSync } from 'node:child_process';
|
|
16
|
-
|
|
17
|
-
import { auditWithScope, auditFull, summarize, isBlockerFinding } from '../audit/index.js';
|
|
18
|
-
import { formatAnalysisCoverageLine } from '../audit/analysis-coverage.js';
|
|
19
|
-
import { scoreQuality } from '../score/index.js';
|
|
16
|
+
// 评分统一经中间层(唯一调用 scoreQuality 的地方);工具侧只传权重覆盖
|
|
20
17
|
import {
|
|
21
18
|
pushInitialContent,
|
|
22
19
|
cloneViaApi, previewClone, resolveMaxCloneFileMB, ensureRemoteRepo, setVisibility, renameRepo, maintainRepoIndex, updateRepoIndex, resolveToken, commitAndPush,
|
|
@@ -24,16 +21,13 @@ import {
|
|
|
24
21
|
refreshAccountStatus,
|
|
25
22
|
} from '../git/index.js';
|
|
26
23
|
import { runAudit } from '../commit-push.js';
|
|
24
|
+
// 审计能力统一经客户端调审计包(拆包后审计实现不在本仓库;此处只做参数映射与结果转交)
|
|
25
|
+
import * as auditClient from './preprocess-client.js';
|
|
27
26
|
|
|
28
27
|
/* ───────── 工具调用常量 ───────── */
|
|
29
28
|
import { defaultConfig } from '../client/index.js';
|
|
30
|
-
import { checkLinks, sumLinkPenalty } from '../link-check/index.js';
|
|
31
|
-
import { scanFileIo } from '../../scripts/scan-file-io.mjs';
|
|
32
|
-
import { runModuleSplitter } from '../git/module-splitter.js';
|
|
33
29
|
import { callIdentityRewrite } from './handlers/identity-rewrite.js';
|
|
34
30
|
import { MSG_REPO_REQUIRED } from './constants.js';
|
|
35
|
-
import { buildAuditApiGuide } from './inject-text.js';
|
|
36
|
-
import { exemptStatsOf, GROUP_BY_KEYS } from './audit-api.js';
|
|
37
31
|
import { setLastSlotHitStats } from './slot-stats.js';
|
|
38
32
|
import { getDefaultScanRoot } from './scan-root.js';
|
|
39
33
|
import { probeRepoOwnership } from './repo-ownership.js';
|
|
@@ -408,8 +402,8 @@ async function callCommitPush(args, env, cfg, log, jobs, exec) {
|
|
|
408
402
|
slots: undefined, // auditRuleOrder 是「加载顺序」不是白名单 ✗(详见 lib/commit-push.js 注释;禁用槽位用 auditDisabledSlots ✓)
|
|
409
403
|
cfg,
|
|
410
404
|
// 本次提交的按文件临时豁免(不落盘):列入的文件 finding 不参与拦截判定(含 blocker)
|
|
411
|
-
|
|
412
|
-
|
|
405
|
+
auditExemptPaths: Array.isArray(args.auditExemptPaths) ? args.auditExemptPaths : [],
|
|
406
|
+
auditExemptReason: args.auditExemptReason,
|
|
413
407
|
});
|
|
414
408
|
if (!auditGate.ok) return auditGate; // { ok:false, blocked:true, audit }
|
|
415
409
|
const doPush = () => pushWithPostSteps(args, env, cfg);
|
|
@@ -472,13 +466,15 @@ function buildAuditOpts(args, cfg, scope) {
|
|
|
472
466
|
*/
|
|
473
467
|
async function runHistoryAuditTool(args, env, cfg, jobs, exec, weights) {
|
|
474
468
|
const repo = args.repo;
|
|
475
|
-
|
|
476
|
-
const { resolveReportDir } = await import('../audit/history-report.js');
|
|
469
|
+
// 历史审计的遍历与评分都在审计包内;宿主只决定「是否起后台 job / 报告目录」
|
|
477
470
|
const auditOpts = buildAuditOpts(args, cfg, 'full');
|
|
478
|
-
|
|
471
|
+
let reportDir = '';
|
|
479
472
|
const doHistory = async () => {
|
|
480
|
-
const r = await
|
|
481
|
-
|
|
473
|
+
const r = await withAuditPackage(() => auditClient.auditHistory({
|
|
474
|
+
repo, since: args.since, until: args.until, outDir: args.outDir || '', auditOpts, weights,
|
|
475
|
+
}));
|
|
476
|
+
reportDir = r?.reportDir || '';
|
|
477
|
+
return { status: r?.ok ? 'completed' : 'failed', detail: r?.ok ? 'history audit done' : String(r?.error || 'failed'), output: JSON.stringify(r) };
|
|
482
478
|
};
|
|
483
479
|
if (!jobs || typeof jobs.start !== 'function') {
|
|
484
480
|
const r = await doHistory();
|
|
@@ -512,48 +508,26 @@ async function callCodeAudit(args, env, cfg, log, jobs, exec) {
|
|
|
512
508
|
return runStandardAuditTool(args, env, cfg, log, weights);
|
|
513
509
|
}
|
|
514
510
|
|
|
515
|
-
/** standard 模式:diff/full 审计 + 评分 + block
|
|
511
|
+
/** standard 模式:diff/full 审计 + 评分 + block 总结(审计与报告整形都在审计包内)。 */
|
|
516
512
|
async function runStandardAuditTool(args, env, cfg, log, weights) {
|
|
517
513
|
const repo = args.repo;
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
:
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
.map((f) => ({ file: f.file, line: f.line, rule: f.rule, message: String(f.message || '').slice(0, MAX_MSG_PREVIEW) }));
|
|
536
|
-
// 审计输出改为「级别数量 + 评分 + API 查询用法」——审计明细由聚合 API
|
|
537
|
-
// (/api/git-push/audit)查询,不再内联输出 findings/审计内容(有聚合 API 消费审计结果)。
|
|
538
|
-
const apiGuide = buildAuditApiGuide(repo, { scope: auditResult.scope, summary, quality, exemptStats, blocked, groupByTypes: GROUP_BY_KEYS });
|
|
539
|
-
// 分析覆盖率由审计编排层统一计算(CLI 与工具同一口径,见 lib/audit/orchestrate.js),这里只做透传与展示。
|
|
540
|
-
const analysisCoverage = auditResult.analysisCoverage || null;
|
|
541
|
-
// 缓存按规则包命中数供给 HTTP /rule-slots(侧边栏规则包列表显示实际命中数)
|
|
542
|
-
if (auditResult.slotStats) setLastSlotHitStats(auditResult.slotStats, repo);
|
|
543
|
-
log?.info?.(`code_audit ${repo} → ${quality.emptyResult ? '未评分(0 文件)' : quality.score + '/' + quality.level}(blocker ${summary.blocker} / warning ${summary.warning} / notice ${summary.notice})`);
|
|
544
|
-
// 默认**返回全量审计结果**(findings + yaml):调用方(AI/脚本)拿到的就该是能直接读的问题明细,
|
|
545
|
-
// 而不是只有分数再自己去查聚合 API —— 多一跳就多一次漏看的可能。
|
|
546
|
-
// 需要精简(大仓库结果过大、或只要结论)时显式传 includeFindings=false / summaryOnly=true。
|
|
547
|
-
const withFindings = args.includeFindings !== false && args.summaryOnly !== true;
|
|
548
|
-
const out = { ok: true, scope: auditResult.scope, files: auditResult.files, summary, quality, exemptStats, blocked, groupByTypes: GROUP_BY_KEYS, apiGuide, slotStats: auditResult.slotStats };
|
|
549
|
-
if (analysisCoverage) {
|
|
550
|
-
out.analysisCoverage = analysisCoverage;
|
|
551
|
-
out.apiGuide = `${apiGuide}\n${formatAnalysisCoverageLine(analysisCoverage)}`;
|
|
552
|
-
}
|
|
553
|
-
if (withFindings) {
|
|
554
|
-
out.findings = auditResult.findings;
|
|
555
|
-
if (auditResult.yaml) out.yaml = auditResult.yaml;
|
|
556
|
-
}
|
|
514
|
+
// 审计包的 auditReport 已按同样口径处理「非 git 目录退化成 full」与「0 文件不评分」
|
|
515
|
+
const out = await withAuditPackage(() => auditClient.auditReport({
|
|
516
|
+
repo,
|
|
517
|
+
scope: args.scope === 'full' ? 'full' : 'diff',
|
|
518
|
+
weights,
|
|
519
|
+
rulesetDir: args.rulesetDir || '',
|
|
520
|
+
maxScanFiles: cfg?.maxScanFiles,
|
|
521
|
+
slots: Array.isArray(args.slots) ? args.slots : undefined,
|
|
522
|
+
disabledSlots: Array.isArray(cfg?.auditDisabledSlots) ? cfg.auditDisabledSlots : undefined,
|
|
523
|
+
includeFindings: args.includeFindings !== false && args.summaryOnly !== true,
|
|
524
|
+
// 覆盖率是信息项(不影响 summary/quality);工具参数 coverage:false 时关掉
|
|
525
|
+
...(args.coverage === false ? { coverage: false } : {}),
|
|
526
|
+
}));
|
|
527
|
+
if (out?.ok === false) return out;
|
|
528
|
+
// 宿主侧副作用:缓存按规则包命中数,供 HTTP /rule-slots 在侧边栏显示实际命中数
|
|
529
|
+
if (out.slotStats) setLastSlotHitStats(out.slotStats, repo);
|
|
530
|
+
log?.info?.(`code_audit ${repo} → ${out.quality?.emptyResult ? '未评分(0 文件)' : `${out.quality?.score}/${out.quality?.level}`}(blocker ${out.summary?.blocker} / warning ${out.summary?.warning} / notice ${out.summary?.notice})`);
|
|
557
531
|
return out;
|
|
558
532
|
}
|
|
559
533
|
|
|
@@ -574,20 +548,18 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
|
|
|
574
548
|
case 'git_commit_push':
|
|
575
549
|
return callCommitPush(args, env, cfg, log, jobs, exec);
|
|
576
550
|
case 'exempt': {
|
|
577
|
-
// 注释豁免工具:add/remove/list/check
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
if (action === 'check') return checkExempt({ repoPath });
|
|
590
|
-
return { ok: false, error: `未知 action:${action || '(空)'}(add/remove/list/check)` };
|
|
551
|
+
// 注释豁免工具:add/remove/list/check —— 实现归审计包(标记映射与审计判定同源)
|
|
552
|
+
return withAuditPackage(() => auditClient.exemptAction({
|
|
553
|
+
action: String(args.action || ''),
|
|
554
|
+
repo: String(args.repo || process.cwd()),
|
|
555
|
+
path: args.path,
|
|
556
|
+
line: args.line,
|
|
557
|
+
scope: args.scope,
|
|
558
|
+
rule: args.rule,
|
|
559
|
+
marker: args.marker,
|
|
560
|
+
reason: args.reason,
|
|
561
|
+
dryRun: args.dryRun === true,
|
|
562
|
+
}));
|
|
591
563
|
}
|
|
592
564
|
case 'code_audit':
|
|
593
565
|
return callCodeAudit(args, env, cfg, log, jobs, exec);
|
|
@@ -652,18 +624,10 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
|
|
|
652
624
|
dryRun: args.dryRun !== false, updateRemotes: args.updateRemotes !== false,
|
|
653
625
|
});
|
|
654
626
|
case 'io_scan': {
|
|
655
|
-
//
|
|
656
|
-
// 不在此另写扫描逻辑,避免两套判定漂移。
|
|
627
|
+
// IO 风险扫描:实现在审计包(AST 四级分级,与 robustness/io-risk 同一份)
|
|
657
628
|
const root = args.repo || env.workspaceRoot;
|
|
658
629
|
if (!root) return { ok: false, error: 'repo 必填(或用会话工作区)' };
|
|
659
|
-
|
|
660
|
-
targets: [root],
|
|
661
|
-
writeOnly: args.writeOnly === true,
|
|
662
|
-
});
|
|
663
|
-
const byRisk = { high: 0, medium: 0, low: 0, safe: 0 };
|
|
664
|
-
for (const hit of hits) if (byRisk[hit.risk] != null) byRisk[hit.risk] += 1;
|
|
665
|
-
const sync = hits.filter((hit) => hit.type === 'sync').length;
|
|
666
|
-
return { ok: true, root, total: hits.length, sync, byRisk, items: hits };
|
|
630
|
+
return withAuditPackage(() => auditClient.ioScan({ root, writeOnly: args.writeOnly === true }));
|
|
667
631
|
}
|
|
668
632
|
case 'git_clone_preview': {
|
|
669
633
|
if (!args.target) return { ok: false, error: 'target 必填' };
|
|
@@ -676,22 +640,7 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
|
|
|
676
640
|
}
|
|
677
641
|
case 'link_check': {
|
|
678
642
|
const path = args.path || env.workspaceRoot;
|
|
679
|
-
|
|
680
|
-
return { ok: true, count: links.length, penalty: sumLinkPenalty(links), findings: links };
|
|
681
|
-
}
|
|
682
|
-
case 'module_splitter': {
|
|
683
|
-
// 巨型单文件拆分(复用 scripts/module-splitter.py,python3 零依赖)。
|
|
684
|
-
// python3 调用逻辑抽到 lib/git/module-splitter.js(与 cli cmdModuleSplitter 共用),
|
|
685
|
-
// 此处只做参数映射与结果返回。
|
|
686
|
-
const command = String(args.command || '').trim();
|
|
687
|
-
const target = String((command === 'analyze' ? args.file : args.plan) || '').trim();
|
|
688
|
-
if (!target) {
|
|
689
|
-
return { ok: false, error: command === 'analyze' ? 'analyze 需要 file(待拆 .js 路径)' : `${command} 需要 plan(plan.json 文件路径)` };
|
|
690
|
-
}
|
|
691
|
-
if (!existsSync(target)) return { ok: false, error: `目标不存在:${target}` };
|
|
692
|
-
const r = runModuleSplitter({ sub: command, target, dryRun: args.dryRun === true });
|
|
693
|
-
if (!r.ok) return { ok: false, error: r.error };
|
|
694
|
-
return { ok: true, command: r.sub, target: r.target, dryRun: r.dryRun, output: r.output };
|
|
643
|
+
return withAuditPackage(() => auditClient.linkCheck({ path }));
|
|
695
644
|
}
|
|
696
645
|
case 'git_account_check': {
|
|
697
646
|
if (args.sshPub) persistSshPub(String(args.sshPub), { workspaceRoot: env.workspaceRoot });
|
|
@@ -730,13 +679,13 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
|
|
|
730
679
|
const endpoints = [...new Set(src.match(/case '\/api\/git-push\/[A-Za-z0-9/_-]+'/g) || [])]
|
|
731
680
|
.map((s) => s.replace("case '/api/git-push/", '').replace(/'$/, ''))
|
|
732
681
|
.sort();
|
|
733
|
-
// path
|
|
734
|
-
// ① 短名 `rule-slots`
|
|
735
|
-
// ② 前缀相对 `
|
|
736
|
-
// ③ 完整路径 `/api/
|
|
682
|
+
// path 三种写法都认(AI 面契约:短名不写死前缀,也别让调用方记全路径):
|
|
683
|
+
// ① 短名 `rule-slots` → 走 /api/git-push/rule-slots(git/共享侧)
|
|
684
|
+
// ② 前缀相对 `preprocess/rule-slots` → /api/preprocess/rule-slots(预处理侧,推荐写法)
|
|
685
|
+
// ③ 完整路径 `/api/preprocess/rule-slots` → 原样
|
|
737
686
|
const rawPath = String(args.path || '').trim();
|
|
738
687
|
const ep = rawPath.replace(/^\/+/, '').replace(/^api\//, '');
|
|
739
|
-
if (!ep) return { ok: true, count: endpoints.length, endpoints, note: '传 path 调用具体接口(如 path=status
|
|
688
|
+
if (!ep) return { ok: true, count: endpoints.length, endpoints, note: '传 path 调用具体接口(如 path=status;预处理接口推荐 path=preprocess/audit)' };
|
|
740
689
|
const method = String(args.method || 'GET').toUpperCase();
|
|
741
690
|
let query = {};
|
|
742
691
|
let body;
|
|
@@ -750,8 +699,8 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
|
|
|
750
699
|
const bodyText = body === undefined ? '' : JSON.stringify(body);
|
|
751
700
|
const out = await handleHttp({
|
|
752
701
|
method,
|
|
753
|
-
// 已带前缀(
|
|
754
|
-
url: `/api/${/^(
|
|
702
|
+
// 已带前缀(preprocess/… 或 git-push/…)就用它;短名默认走 git-push(git/共享侧)
|
|
703
|
+
url: `/api/${/^(preprocess|git-push)\//.test(ep) ? ep : `git-push/${ep}`}${qs ? '?' + qs : ''}`,
|
|
755
704
|
origin: 'http://localhost', // 内部调用 = 本机同源(写类接口的 CSRF 门禁据此放行)
|
|
756
705
|
headers: { host: 'localhost', 'content-length': String(bodyText.length) },
|
|
757
706
|
body: bodyText,
|
|
@@ -759,55 +708,35 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
|
|
|
759
708
|
return { ok: out?.status === 200 && out?.body?.ok !== false, status: out?.status, endpoint: ep, result: out?.body };
|
|
760
709
|
}
|
|
761
710
|
case 'scope_check': {
|
|
762
|
-
//
|
|
763
|
-
//
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
const repoRoot = resolve(String(args.repo || env.workspaceRoot || process.cwd()));
|
|
768
|
-
const splitList = (value) => String(value || '').split(/[,;\s]+/).map((s) => s.trim()).filter(Boolean);
|
|
769
|
-
let targets = splitList(args.files).map((f) => resolve(repoRoot, f));
|
|
770
|
-
if (!targets.length) {
|
|
771
|
-
// 缺省取项目自己声明的产物清单(dshScopeCheck.files)——不猜文件名,
|
|
772
|
-
// 否则「哪些文件是拼接产物」这件事会散成两处判断(本文件 + package.json)。
|
|
773
|
-
const policy = readProjectScopePolicy(join(repoRoot, 'package.json'));
|
|
774
|
-
const base = policy.configPath ? dirname(policy.configPath) : repoRoot;
|
|
775
|
-
targets = policy.files.map((f) => resolve(base, f));
|
|
776
|
-
if (!targets.length) {
|
|
777
|
-
return { ok: false, error: `未指定 files,且 ${join(repoRoot, 'package.json')} 未声明 dshScopeCheck.files` };
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
const result = runScopeCheck({
|
|
781
|
-
files: targets,
|
|
711
|
+
// 拼接产物作用域撞名:判定(ast/scope-collisions)+ 契约(engine/scope-policy)都在审计包,
|
|
712
|
+
// 本处只做参数映射与错误包装。
|
|
713
|
+
return withAuditPackage(() => auditClient.scopeCheck({
|
|
714
|
+
repo: String(args.repo || env.workspaceRoot || process.cwd()),
|
|
715
|
+
files: args.files,
|
|
782
716
|
prefix: String(args.prefix || ''),
|
|
783
|
-
allowlist:
|
|
717
|
+
allowlist: args.allowlist,
|
|
784
718
|
...(typeof args.topLevelMustBeEmpty === 'boolean' ? { topLevelMustBeEmpty: args.topLevelMustBeEmpty } : {}),
|
|
785
|
-
});
|
|
786
|
-
const lines = result.policySources.map((src) => `策略来源:${src}`);
|
|
787
|
-
for (const report of result.reports) {
|
|
788
|
-
const rel = report.file.startsWith(`${repoRoot}/`) ? report.file.slice(repoRoot.length + 1) : report.file;
|
|
789
|
-
if (report.ok) {
|
|
790
|
-
lines.push(`✔ ${rel}:${(report.declarations || []).length} 个声明,无同帧重名`);
|
|
791
|
-
continue;
|
|
792
|
-
}
|
|
793
|
-
lines.push(`✗ ${rel}:`);
|
|
794
|
-
for (const violation of report.violations || []) lines.push(` - ${violation}`);
|
|
795
|
-
}
|
|
796
|
-
const violationCount = result.reports.reduce((sum, report) => sum + (report.violations || []).length, 0);
|
|
797
|
-
return {
|
|
798
|
-
ok: result.ok,
|
|
799
|
-
count: result.reports.length,
|
|
800
|
-
violations: violationCount,
|
|
801
|
-
policySources: result.policySources,
|
|
802
|
-
reports: result.reports,
|
|
803
|
-
lines,
|
|
804
|
-
};
|
|
719
|
+
}));
|
|
805
720
|
}
|
|
806
721
|
default:
|
|
807
722
|
return { ok: false, error: `未知工具: ${toolName}` };
|
|
808
723
|
}
|
|
809
724
|
}
|
|
810
725
|
|
|
726
|
+
/**
|
|
727
|
+
* 调审计包的统一包装:把「包加载失败」变成工具可见的 `{ ok:false, error }`。
|
|
728
|
+
* 为什么不在每处 try/catch:五个工具用同一份错误格式,AI 才能一致地判读失败原因。
|
|
729
|
+
* @param {Function} call 实际调用(返回 Promise 或值)
|
|
730
|
+
* @returns {Promise<object>}
|
|
731
|
+
*/
|
|
732
|
+
async function withAuditPackage(call) {
|
|
733
|
+
try {
|
|
734
|
+
return await call();
|
|
735
|
+
} catch (e) {
|
|
736
|
+
return { ok: false, error: `审计包不可用:${e?.message || e}` };
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
811
740
|
/** 按 shell 规则拆分参数串(支持单双引号包裹含空格的路径)。 */
|
|
812
741
|
function shellSplit(input) {
|
|
813
742
|
const out = [];
|