dsh-git-push 0.0.0-stage → 2.8.6
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/.auditignore +30 -0
- package/.gitignore +39 -0
- package/LICENSE +21 -0
- package/README.md +1486 -2
- package/cli.mjs +360 -0
- package/cordis.patch.yml +14 -0
- package/lib/ARCHITECTURE.md +34 -0
- package/lib/BUGFIX-NOTES-2026-09-14.md +278 -0
- package/lib/app/apply.js +275 -0
- package/lib/app/audit-api.js +158 -0
- package/lib/app/command-registry.js +266 -0
- package/lib/app/constants.js +16 -0
- package/lib/app/handlers/account.js +166 -0
- package/lib/app/handlers/clone.js +168 -0
- package/lib/app/handlers/http-constants.js +9 -0
- package/lib/app/handlers/identity-rewrite.js +94 -0
- package/lib/app/handlers/meta.js +175 -0
- package/lib/app/handlers/npm.js +169 -0
- package/lib/app/handlers/repo-actions.js +143 -0
- package/lib/app/handlers/repos.js +231 -0
- package/lib/app/handlers/settings.js +62 -0
- package/lib/app/host-doc-checks.js +25 -0
- package/lib/app/http-handlers.js +131 -0
- package/lib/app/index.js +30 -0
- package/lib/app/inject-text.js +192 -0
- package/lib/app/scan-root.js +23 -0
- package/lib/app/schema.js +150 -0
- package/lib/app/settings-bridge.js +167 -0
- package/lib/app/slash-commands.js +395 -0
- package/lib/app/slot-stats.js +35 -0
- package/lib/app/tool-call.js +672 -0
- package/lib/app/tools.js +34 -0
- package/lib/ast/brace.js +105 -0
- package/lib/ast/callgraph.js +135 -0
- package/lib/ast/code-lines.js +114 -0
- package/lib/ast/consts.js +12 -0
- package/lib/ast/control-flow.js +461 -0
- package/lib/ast/credential.js +199 -0
- package/lib/ast/dataflow.js +274 -0
- package/lib/ast/dup-code.js +165 -0
- package/lib/ast/index.js +36 -0
- package/lib/ast/io-risk-const.js +95 -0
- package/lib/ast/io-risk-fn.js +208 -0
- package/lib/ast/io-risk-loop.js +308 -0
- package/lib/ast/io-risk.js +314 -0
- package/lib/ast/lang.js +156 -0
- package/lib/ast/line-count.js +52 -0
- package/lib/ast/magic-number.js +272 -0
- package/lib/ast/naming.js +284 -0
- package/lib/ast/perf.js +472 -0
- package/lib/ast/scope.js +241 -0
- package/lib/ast/shell.js +131 -0
- package/lib/ast/size.js +378 -0
- package/lib/ast/symbol-index.js +399 -0
- package/lib/ast/tokenizer.js +341 -0
- package/lib/audit/analysis-coverage.js +98 -0
- package/lib/audit/audit-file.js +182 -0
- package/lib/audit/checks.js +17 -0
- package/lib/audit/client-entry.js +93 -0
- package/lib/audit/collector.js +477 -0
- package/lib/audit/ext-runner.js +80 -0
- package/lib/audit/file-context.js +138 -0
- package/lib/audit/finding.js +50 -0
- package/lib/audit/gitignore-match.js +113 -0
- package/lib/audit/glob.js +63 -0
- package/lib/audit/history-report.js +100 -0
- package/lib/audit/history.js +126 -0
- package/lib/audit/ignore-blind.js +101 -0
- package/lib/audit/index.js +33 -0
- package/lib/audit/orchestrate.js +476 -0
- package/lib/audit/public.js +24 -0
- package/lib/audit/repo-level.js +30 -0
- package/lib/audit/report-yaml.js +86 -0
- package/lib/audit/slot.js +65 -0
- package/lib/audit-defaults.js +18 -0
- package/lib/audit-rules/audit-rules-comment.yml +247 -0
- package/lib/audit-rules/audit-rules-cpp.yml +22 -0
- package/lib/audit-rules/audit-rules-docs.yml +32 -0
- package/lib/audit-rules/audit-rules-dsh.yml +162 -0
- package/lib/audit-rules/audit-rules-filehealth.yml +42 -0
- package/lib/audit-rules/audit-rules-folder.yml +99 -0
- package/lib/audit-rules/audit-rules-frontend.yml +335 -0
- package/lib/audit-rules/audit-rules-go.yml +22 -0
- package/lib/audit-rules/audit-rules-i18n.yml +45 -0
- package/lib/audit-rules/audit-rules-java.yml +105 -0
- package/lib/audit-rules/audit-rules-nodejs.yml +647 -0
- package/lib/audit-rules/audit-rules-npm.yml +187 -0
- package/lib/audit-rules/audit-rules-paths.yml +92 -0
- package/lib/audit-rules/audit-rules-performance.yml +215 -0
- package/lib/audit-rules/audit-rules-php.yml +22 -0
- package/lib/audit-rules/audit-rules-private.yml +24 -0
- package/lib/audit-rules/audit-rules-python.yml +106 -0
- package/lib/audit-rules/audit-rules-robustness.yml +27 -0
- package/lib/audit-rules/audit-rules-rust.yml +22 -0
- package/lib/audit-rules/audit-rules-structure.yml +159 -0
- package/lib/audit-rules/audit-rules-swift.yml +22 -0
- package/lib/audit-rules/audit-rules-template.yml +108 -0
- package/lib/checks/button-bind.js +276 -0
- package/lib/checks/common.js +170 -0
- package/lib/checks/credential-file.js +43 -0
- package/lib/checks/dataflow.js +40 -0
- package/lib/checks/dispatch.js +112 -0
- package/lib/checks/dup-code.js +69 -0
- package/lib/checks/dup-const.js +232 -0
- package/lib/checks/file-health.js +150 -0
- package/lib/checks/filter.js +137 -0
- package/lib/checks/folder.js +173 -0
- package/lib/checks/hardcoded-path.js +98 -0
- package/lib/checks/index.js +46 -0
- package/lib/checks/io.js +66 -0
- package/lib/checks/magic-number.js +42 -0
- package/lib/checks/npm-json.js +273 -0
- package/lib/checks/private.js +63 -0
- package/lib/checks/regex.js +256 -0
- package/lib/checks/semantic.js +134 -0
- package/lib/checks/structural.js +274 -0
- package/lib/cli/commands-account.mjs +107 -0
- package/lib/cli/commands-audit.mjs +144 -0
- package/lib/cli/commands-doc.mjs +127 -0
- package/lib/cli/commands-vcs.mjs +175 -0
- package/lib/client/index.js +162 -0
- package/lib/client-parts/00-loader.js +33 -0
- package/lib/client-parts/01-const.js +207 -0
- package/lib/client-parts/02-utils.js +62 -0
- package/lib/client-parts/03-icons.js +12 -0
- package/lib/client-parts/10-account.js +83 -0
- package/lib/client-parts/11-browser.js +95 -0
- package/lib/client-parts/20-repo.js +374 -0
- package/lib/client-parts/21-audit.js +301 -0
- package/lib/client-parts/22-settings.js +146 -0
- package/lib/client-parts/23-npm.js +383 -0
- package/lib/client-parts/30-page.js +56 -0
- package/lib/client-parts/40-controller.js +1092 -0
- package/lib/client-parts/41-actions.js +279 -0
- package/lib/client-parts/99-apply.js +72 -0
- package/lib/client.js +3195 -0
- package/lib/commit-push.js +148 -0
- package/lib/context/index.js +363 -0
- package/lib/core/atomic-json.js +98 -0
- package/lib/core/config.js +40 -0
- package/lib/core/credentials.js +274 -0
- package/lib/core/endpoints.js +109 -0
- package/lib/core/exec.js +162 -0
- package/lib/exempt/index.js +292 -0
- package/lib/fs/edit-after-read.js +103 -0
- package/lib/fsx.js +87 -0
- package/lib/git/account-status.js +140 -0
- package/lib/git/account.js +233 -0
- package/lib/git/api.js +136 -0
- package/lib/git/atomic-json.js +6 -0
- package/lib/git/browse.js +38 -0
- package/lib/git/clone-download.js +397 -0
- package/lib/git/clone-history-mode.js +143 -0
- package/lib/git/clone-history.js +175 -0
- package/lib/git/clone-jobs.js +250 -0
- package/lib/git/clone-replay-io.js +172 -0
- package/lib/git/clone-replay.js +275 -0
- package/lib/git/clone.js +445 -0
- package/lib/git/cloud.js +46 -0
- package/lib/git/commit-message.js +141 -0
- package/lib/git/config.js +6 -0
- package/lib/git/cred-env.js +88 -0
- package/lib/git/credentials.js +6 -0
- package/lib/git/endpoints.js +6 -0
- package/lib/git/exec.js +6 -0
- package/lib/git/identity-rewrite.js +297 -0
- package/lib/git/identity.js +150 -0
- package/lib/git/ignore.js +69 -0
- package/lib/git/index.js +41 -0
- package/lib/git/module-splitter.js +47 -0
- package/lib/git/post-push.js +101 -0
- package/lib/git/push-diagnose.js +142 -0
- package/lib/git/push.js +476 -0
- package/lib/git/remote-resolve.js +146 -0
- package/lib/git/remote.js +128 -0
- package/lib/git/repo-index.js +512 -0
- package/lib/git/repos.js +235 -0
- package/lib/git/scan-runner.js +159 -0
- package/lib/git/sensitive.js +134 -0
- package/lib/git/transport.js +430 -0
- package/lib/git/visibility.js +35 -0
- package/lib/git/wrapped-git.js +68 -0
- package/lib/http/index.js +170 -0
- package/lib/index.js +24 -0
- package/lib/link-check/index.js +187 -0
- package/lib/npm/account.js +64 -0
- package/lib/npm/install.js +211 -0
- package/lib/npm/npmrc.js +56 -0
- package/lib/npm/publish.js +171 -0
- package/lib/npm/registry.js +168 -0
- package/lib/plugin/auto-detect.js +92 -0
- package/lib/plugin/auto-push.js +154 -0
- package/lib/plugin/index.js +250 -0
- package/lib/readme-templates/readme.yml +38 -0
- package/lib/rule/compilers/credential.js +62 -0
- package/lib/rule/compilers/dataflow.js +38 -0
- package/lib/rule/compilers/file-health.js +75 -0
- package/lib/rule/compilers/frontend.js +86 -0
- package/lib/rule/compilers/func.js +35 -0
- package/lib/rule/compilers/helpers.js +71 -0
- package/lib/rule/compilers/index.js +29 -0
- package/lib/rule/compilers/link-semantic.js +45 -0
- package/lib/rule/compilers/list-kinds.js +12 -0
- package/lib/rule/compilers/numeric-kinds.js +66 -0
- package/lib/rule/compilers/regex.js +78 -0
- package/lib/rule/compilers/structure.js +80 -0
- package/lib/rule/compilers.js +17 -0
- package/lib/rule/homoglyph.js +45 -0
- package/lib/rule/loader.js +270 -0
- package/lib/rule/registry.js +115 -0
- package/lib/rule/scope.js +67 -0
- package/lib/score/docs-score.js +166 -0
- package/lib/score/index.js +140 -0
- package/lib/self/index.js +196 -0
- package/lib/skip-dirs.js +64 -0
- package/lib/tool-probes.json +50 -0
- package/lib/user-requirements.json +14 -0
- package/lib/vendor/js-yaml/LICENSE +21 -0
- package/lib/vendor/js-yaml/js-yaml.mjs +3073 -0
- package/package.json +95 -4
- package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
- package/scripts/audit-ext/_example-readme-present.mjs +34 -0
- package/scripts/audit-ext/variable-min-length.mjs +102 -0
- package/scripts/audit-runner.mjs +35 -0
- package/scripts/audit-runtime-check.mjs +129 -0
- package/scripts/browser-page-probe.mjs +271 -0
- package/scripts/build-client.mjs +119 -0
- package/scripts/check.mjs +88 -0
- package/scripts/clean-date-comments.py +102 -0
- package/scripts/cpu-sample.mjs +188 -0
- package/scripts/doc-drift.mjs +200 -0
- package/scripts/doc-func.mjs +212 -0
- package/scripts/doc-tree.mjs +456 -0
- package/scripts/doc-version.mjs +220 -0
- package/scripts/frontend-preview-check.mjs +124 -0
- package/scripts/hot-path-probe-cjs.cjs +71 -0
- package/scripts/hot-path-probe-fs-shim.mjs +28 -0
- package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
- package/scripts/hot-path-probe.mjs +153 -0
- package/scripts/module-splitter.py +800 -0
- package/scripts/platform-scan.mjs +168 -0
- package/scripts/preview-gen.mjs +489 -0
- package/scripts/preview-local-runner.mjs +55 -0
- package/scripts/preview-server-direct.mjs +116 -0
- package/scripts/preview-server.mjs +305 -0
- package/scripts/preview-slot-data.mjs +123 -0
- package/scripts/probe-recheck.mjs +47 -0
- package/scripts/readme-gen.mjs +268 -0
- package/scripts/rename-locator.mjs +97 -0
- package/scripts/rule-switch.mjs +97 -0
- package/scripts/rules-solo-audit.mjs +173 -0
- package/scripts/scan-file-io.mjs +713 -0
- package/scripts/scan-hardcoded-paths.mjs +125 -0
- package/scripts/scan-repos.mjs +167 -0
- package/scripts/scan-version.mjs +122 -0
- package/scripts/scrub-user-wording.mjs +420 -0
- package/scripts/symbol-index.mjs +85 -0
- package/scripts/sync-plugin-install.mjs +223 -0
- package/scripts/sync-plugin.mjs +279 -0
- package/scripts/verify-prestep.mjs +100 -0
- package/skills/dev/audit-rule-authoring.md +58 -0
- package/skills/dev/dsh-git-push.md +323 -0
- package/skills/dev/git-push-live-fix.md +45 -0
- package/skills/dsh-repo-index.md +35 -0
- package/skills/guide/guide-audit.md +167 -0
- package/skills/guide/guide-cli-scripts.md +104 -0
- package/skills/guide/guide-clone-repos.md +173 -0
- package/skills/guide/guide-commit-push.md +156 -0
- package/skills/guide/guide-inject-ui.md +166 -0
- package/skills/guide/guide-slash-completion.md +118 -0
- package/skills/workflow/README.md +21 -0
- package/skills/workflow/git-commit-discipline.md +68 -0
- package/skills/workflow/git-project-startup.md +85 -0
- package/skills/workflow/git-rebuild-process.md +57 -0
- package/skills/workflow/github-operations.md +91 -0
- package/skills/workflow/readme-sync-git-md.md +28 -0
- package/skills/workflow/task-completion-report.md +73 -0
- package/skills/workflow/tool-json-add-ask.md +35 -0
- package/skills/workflow/versioning-rule.md +211 -0
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 检查层 · 语义类规则
|
|
3
|
+
*
|
|
4
|
+
* 职责:由规则 yml 声明的语义检查(如 patch insert 语义、仓库级语义规则)。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { makeFinding, CODE_EXTS } from '../audit/index.js';
|
|
8
|
+
import { HINT_QUALITY } from './common.js';
|
|
9
|
+
|
|
10
|
+
/** 顶层 `- id:` 行(缩进 0 的覆盖),或缩进 1 的 insert 块内列表项。 */
|
|
11
|
+
const ID_TOP_RE = /^- id:\s*["']?([^"'\s]+)["']?\s*$/;
|
|
12
|
+
const ID_INDENT_RE = /^\s+- id:\s*["']?([^"'\s]+)["']?\s*$/;
|
|
13
|
+
|
|
14
|
+
/** 检查语义规则(semantic:占位消费——无静态可判定性时按路径/命名提示,不做臆测)。 */
|
|
15
|
+
/**
|
|
16
|
+
* semantic 占位规则检查:无法自动判定、需人工确认的规则(安全/a11y/dependency 类)。
|
|
17
|
+
*
|
|
18
|
+
* 语义(修):
|
|
19
|
+
* ① 只对**代码文件**生效——.gitignore/README/yml/json 没有「用户输入路径/依赖/按钮」
|
|
20
|
+
* 可判定语义,逐文件报属纯噪音。
|
|
21
|
+
* ② **仓库级规则只报一次**——npm audit(dependency/known-vulnerability)、
|
|
22
|
+
* 路径穿越人工核查(security/no-path-traversal)、a11y(button/label)都是
|
|
23
|
+
* 「整个仓库」的属性,不是「某个文件」的属性。逐文件报会在 4 个文件上产出
|
|
24
|
+
* 16 条同义提示(4 文件 × 4 规则),把真实问题淹没。
|
|
25
|
+
* 判定依据:规则只声明 name/description、**无任何可执行字段**(无 pattern/
|
|
26
|
+
* threshold/kind/detection)→ 本 engine 无法评估,交人工按仓库维度核查一次。
|
|
27
|
+
* 多文件时报在**文件路径字典序最小**的那个文件上(稳定可复现),其余文件静默。
|
|
28
|
+
* ③ 单文件审计(如 diff 范围的末尾批次)拿不到全仓列表时退回逐文件提示,
|
|
29
|
+
* 由调用方(auditFull/auditChanged)传 repoLevel 去重,保证不丢提示。
|
|
30
|
+
*
|
|
31
|
+
* @param {object} args { file, relPath, rules, repoLevelRules? }
|
|
32
|
+
* repoLevelRules:调用方判定为「仓库级、已报过」的规则 id 集合(Set),命中则跳过。
|
|
33
|
+
* @returns {Array} findings
|
|
34
|
+
*/
|
|
35
|
+
export function checkSemantic({ file, relPath, rules, repoLevelRules }) {
|
|
36
|
+
const findings = [];
|
|
37
|
+
const target = String(relPath || file || '');
|
|
38
|
+
// ① 非代码文件没有可判定的语义对象
|
|
39
|
+
const ext = target.split('.').pop().toLowerCase();
|
|
40
|
+
if (!CODE_EXTS.has(ext)) return findings;
|
|
41
|
+
for (const rule of rules || []) {
|
|
42
|
+
// 文件系统上下文类:期望存在同名 test 文件 / 语言包文件(engine 无法读目录时跳过,交调用方仓库级处理)
|
|
43
|
+
if (rule.detectionMethod === 'test-file-exists' || /test-file/i.test(rule.id || '')
|
|
44
|
+
|| rule.detectionMethod === 'locale-file-exists' || /locale-file/i.test(rule.id || '')) {
|
|
45
|
+
continue; // 需文件系统上下文,由 auditFull 层处理(避免此处臆测)
|
|
46
|
+
}
|
|
47
|
+
// ② 仓库级规则已报过 → 本文件不再重复
|
|
48
|
+
if (repoLevelRules && repoLevelRules.has(rule.id)) continue;
|
|
49
|
+
findings.push(makeFinding({
|
|
50
|
+
file, line: 1, rule: rule.id, kind: 'semantic',
|
|
51
|
+
severity: 'notice',
|
|
52
|
+
message: rule.message || rule.name || '语义规则提示(需人工确认)',
|
|
53
|
+
dimensions: rule.dimensions || ['健壮性'],
|
|
54
|
+
exemptHint: HINT_QUALITY,
|
|
55
|
+
scoreImpact: 0,
|
|
56
|
+
}));
|
|
57
|
+
}
|
|
58
|
+
return findings;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 判定规则是否为「仓库级语义占位」——无任何可执行检测字段、需人工按仓库维度核查。
|
|
63
|
+
* 这类规则只应报一次(否则每文件一条同义提示)。
|
|
64
|
+
* 判定:semantic kind 且既无 pattern(s)、无 threshold / min 长度 / max 深度等数值字段、
|
|
65
|
+
* 无 detectionMethod、无 blacklist/whitelist 等清单字段。
|
|
66
|
+
* @param {object} rule 编译后规则对象
|
|
67
|
+
* @returns {boolean}
|
|
68
|
+
*/
|
|
69
|
+
export function isRepoLevelSemanticRule(rule) {
|
|
70
|
+
if (!rule || rule.kind !== 'semantic') return false;
|
|
71
|
+
if (rule.detectionMethod) return false;
|
|
72
|
+
const hasPattern = rule.pattern !== undefined || (Array.isArray(rule.patterns) && rule.patterns.length > 0);
|
|
73
|
+
const numericFields = ['threshold', 'minLength', 'maxDepth', 'maxLines', 'maxComplexity', 'minOccurrences', 'minLines'];
|
|
74
|
+
const hasNumeric = numericFields.some((k) => rule[k] !== undefined && rule[k] !== null);
|
|
75
|
+
const listFields = ['blacklist', 'whitelist', 'additionalFeatures', 'requiredPatterns'];
|
|
76
|
+
const hasList = listFields.some((k) => Array.isArray(rule[k]) && rule[k].length > 0);
|
|
77
|
+
return !hasPattern && !hasNumeric && !hasList;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* cordis.patch.yml insert 语义检查(patch-insert kind)。
|
|
82
|
+
* 旧实现是 regex「命中 insert: 行即提示」——纯 insert(只新建、不覆盖任何行)
|
|
83
|
+
* 也会被报,如 dsh-skill-scoreboard 的 patch(insert 新建 skill-scoreboard loader,
|
|
84
|
+
* 基座没有同名行可覆盖)被误报成 duplicate-id 风险。
|
|
85
|
+
* 语义判定:解析 yml 文本——
|
|
86
|
+
* 1) insert 块(`- insert:` 后缩进列表)内的 id 集合
|
|
87
|
+
* 2) 顶层(缩进 0)`- id:` 覆盖行的 id 集合
|
|
88
|
+
* 3) 仅当两集合有交集(insert 新建的 id 与按 id 覆盖行同 id)才报 duplicate-id 双挂风险
|
|
89
|
+
* 纯 insert 或 id 无交集 → 不报。
|
|
90
|
+
* @param {object} p { file, text, rules } rules=编译后的 patch-insert 规则
|
|
91
|
+
* @returns {Array} findings
|
|
92
|
+
*/
|
|
93
|
+
export function checkPatchInsert({ file, text, rules }) {
|
|
94
|
+
const findings = [];
|
|
95
|
+
const lines = String(text || '').split('\n');
|
|
96
|
+
const insertIds = []; // { id, line }
|
|
97
|
+
const overrideIds = []; // { id, line }
|
|
98
|
+
let inInsert = false;
|
|
99
|
+
for (let i = 0; i < lines.length; i++) {
|
|
100
|
+
const raw = lines[i];
|
|
101
|
+
const t = raw.trim();
|
|
102
|
+
if (!t || t.startsWith('#')) continue; // 空行/注释(README 对照示例多为注释,不算)
|
|
103
|
+
if (ID_TOP_RE.test(t) && /^- id:/.test(raw)) {
|
|
104
|
+
// 缩进 0 的 - id 行 = 顶层覆盖已有 loader 行(无论当前是否在 insert 块内,都终结 insert 块)
|
|
105
|
+
const id = t.match(ID_TOP_RE)[1];
|
|
106
|
+
overrideIds.push({ id, line: i + 1 });
|
|
107
|
+
inInsert = false;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (inInsert && ID_INDENT_RE.test(raw)) {
|
|
111
|
+
const id = raw.trim().match(ID_TOP_RE)[1];
|
|
112
|
+
insertIds.push({ id, line: i + 1 });
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (/^- insert:\s*$/.test(t)) { inInsert = true; continue; }
|
|
116
|
+
// 离开 insert 块:insert 块内列表项以缩进(空格开头)为特征;缩进 0 的非 insert 行结束块
|
|
117
|
+
if (inInsert && !/^\s/.test(raw)) inInsert = false;
|
|
118
|
+
}
|
|
119
|
+
for (const rule of rules || []) {
|
|
120
|
+
for (const ins of insertIds) {
|
|
121
|
+
if (overrideIds.some((o) => o.id === ins.id)) {
|
|
122
|
+
findings.push(makeFinding({
|
|
123
|
+
file, line: ins.line, rule: rule.id, kind: 'patch-insert',
|
|
124
|
+
severity: rule.level === 'blocker' ? 'blocker' : rule.severity || 'warning',
|
|
125
|
+
message: `${rule.message || rule.name}(insert 新建 id「${ins.id}」与顶层覆盖行同 id,会 duplicate-id 双挂)`,
|
|
126
|
+
dimensions: rule.dimensions || ['健壮性'],
|
|
127
|
+
exemptHint: HINT_QUALITY,
|
|
128
|
+
scoreImpact: 1,
|
|
129
|
+
}));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return findings;
|
|
134
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 检查层 · 结构类规则
|
|
3
|
+
*
|
|
4
|
+
* 职责:函数长度、复杂度、嵌套深度、文件行数、重复字符串、同步 fs、空 catch。
|
|
5
|
+
* 本层为薄包装:判定逻辑在 lib/ast/*,此处只把结果转成 finding。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { makeFinding } from '../audit/index.js';
|
|
9
|
+
import { checkSyncFs, checkEmptyCatchAst, checkFuncLinesAst, checkFuncDensityAst, checkNameLengthAst, checkComplexityAst, checkNestingDepthAst, checkFileLines, checkRepeatedStringsAst, checkCommentDensityAst, maxFunctionLength } from '../ast/index.js';
|
|
10
|
+
import { classifyFunctionPath, analyzeFunctionalScope } from '../ast/scope.js';
|
|
11
|
+
|
|
12
|
+
/* ───────── 结构检查默认阈值 ───────── */
|
|
13
|
+
// FUNC_LINES_DEFAULT 改为从 lib/audit-defaults.js 取单一来源(此前与 lib/rule/compilers/func.js
|
|
14
|
+
// 各写一份 50,两处必须永远相等,漏改一处就静默不一致——自审 duplicate-constant 报的真重复)
|
|
15
|
+
import { FUNC_LINES_DEFAULT } from '../audit-defaults.js';
|
|
16
|
+
const MAX_LINES_DEFAULT = 500; // 规则未配 threshold 时的文件行数默认阈值
|
|
17
|
+
import { resolveScopeAction } from '../rule/scope.js';
|
|
18
|
+
import { capSeverity, HINT_QUALITY } from './common.js';
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
/** 检查 func-lines:单函数超长(AST 精确行数 + 语句密度互补,单行海量语句也检出)。 */
|
|
22
|
+
export function checkFuncLines({ file, text, rules }) {
|
|
23
|
+
const findings = [];
|
|
24
|
+
const rule = rules?.[0];
|
|
25
|
+
if (!rule) return findings;
|
|
26
|
+
const threshold = rule.threshold || FUNC_LINES_DEFAULT;
|
|
27
|
+
const blockThreshold = rule.blockThreshold || threshold * 2;
|
|
28
|
+
// AST 版:括号平衡精确统计函数体行数(修行数启发式假阴性)
|
|
29
|
+
const astHits = checkFuncLinesAst(text, { warn: threshold, block: blockThreshold });
|
|
30
|
+
const fnScope = rule.scopeRules?.length ? analyzeFunctionalScope(text) : new Map(); // P4:闭包双重作用域(public 不豁免)
|
|
31
|
+
for (const hit of astHits) {
|
|
32
|
+
// 作用域豁免(P1):规则声明 scope_rules 且函数为启动路径(apply/init/main 等)→ exempt;P4:public(被 return/挂 this/exports 暴露)按模块级不豁免
|
|
33
|
+
if (rule.scopeRules?.length && fnScope.get(hit.name) !== 'public' && resolveScopeAction(rule.scopeRules, { path: classifyFunctionPath(hit.name), functionName: hit.name }) === 'exempt') continue;
|
|
34
|
+
findings.push(makeFinding({
|
|
35
|
+
file, line: hit.line, rule: rule.id, kind: 'func-lines',
|
|
36
|
+
severity: hit.level === 'blocker' || rule.level === 'blocker' ? 'blocker' : 'warning',
|
|
37
|
+
// 长度按非注释部分(hit.codeLen);与总行数不同时才附注释行说明
|
|
38
|
+
message: (hit.commentLines > 0
|
|
39
|
+
? `单函数 ${hit.codeLen} 行代码(总 ${hit.len} 行,其中注释 ${hit.commentLines} 行,阈值 ${threshold})——应拆分`
|
|
40
|
+
: `单函数 ${hit.codeLen} 行(阈值 ${threshold})——应拆分`),
|
|
41
|
+
dimensions: rule.dimensions,
|
|
42
|
+
exemptHint: 'dsh-skip-func-length(文件头=全文件 / 函数定义行=单函数)',
|
|
43
|
+
scoreImpact: hit.level === 'blocker' ? 2 : 1,
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
46
|
+
// 语句密度补充(架构收敛):**判定全部在 AST 层**(checkFuncDensityAst),
|
|
47
|
+
// 本层只把结果转成 finding,不再自己找函数起点、自己数花括号、自己判行数。
|
|
48
|
+
// 历史违规:此处曾是第二套独立实现(正则找起点 + 手数括号 + 自判行数),与 AST 版各判各的,
|
|
49
|
+
// 既重复报同一函数,又因未剥离字面量把含 `\{` 正则的函数算成 242 行 blocker。
|
|
50
|
+
// 跳过条件:已被行数判定报出的函数(reportedByLines)不再按密度重复报。
|
|
51
|
+
const reportedByLines = new Set(astHits.map((h) => h.line));
|
|
52
|
+
const densityHits = checkFuncDensityAst(text, {
|
|
53
|
+
threshold, blockThreshold, skipLines: reportedByLines,
|
|
54
|
+
});
|
|
55
|
+
for (const d of densityHits) {
|
|
56
|
+
findings.push(makeFinding({
|
|
57
|
+
file, line: d.line, rule: rule.id, kind: 'func-lines',
|
|
58
|
+
severity: d.level === 'blocker' || rule.level === 'blocker' ? 'blocker' : 'warning',
|
|
59
|
+
message: `单函数 ${d.stmtCount} 语句挤在 ${d.bodyLines} 行(平均 ${d.density.toFixed(1)} 条/行,阈值 ${threshold} 条)——单行海量语句应拆分`,
|
|
60
|
+
dimensions: rule.dimensions,
|
|
61
|
+
exemptHint: 'dsh-skip-func-length(文件头=全文件 / 函数定义行=单函数)',
|
|
62
|
+
scoreImpact: d.level === 'blocker' ? 2 : 1,
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
return findings;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 检查 sync-fs:async 路径中的 fs 同步调用(AST 级,修 named import 假阴性)。 */
|
|
69
|
+
export function checkSyncFsInFile({ file, text }) {
|
|
70
|
+
const findings = [];
|
|
71
|
+
for (const hit of checkSyncFs(text)) {
|
|
72
|
+
findings.push(makeFinding({
|
|
73
|
+
file, line: hit.line, rule: 'quality/sync-fs', kind: 'sync-fs',
|
|
74
|
+
severity: 'warning',
|
|
75
|
+
message: `async 路径中的同步 fs 调用 ${hit.call}(${hit.via})——阻塞事件循环,应换异步版`,
|
|
76
|
+
dimensions: ['性能'],
|
|
77
|
+
exemptHint: HINT_QUALITY,
|
|
78
|
+
scoreImpact: 0, // 重复字面量=「建议配置化」提示,同魔数口径不扣分(避免重复串全项目误扣)
|
|
79
|
+
}));
|
|
80
|
+
}
|
|
81
|
+
return findings;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 检查空 catch(AST 级括号平衡:多行空块/仅注释块均命中)。 */
|
|
85
|
+
export function checkEmptyCatch({ file, text }) {
|
|
86
|
+
const findings = [];
|
|
87
|
+
for (const hit of checkEmptyCatchAst(text)) {
|
|
88
|
+
findings.push(makeFinding({
|
|
89
|
+
file, line: hit.line, rule: 'quality/empty-catch', kind: 'empty-catch',
|
|
90
|
+
severity: 'warning',
|
|
91
|
+
message: '空 catch 静默吞错——应加 log 或注释原因',
|
|
92
|
+
dimensions: ['健壮性', '可观测性'],
|
|
93
|
+
exemptHint: HINT_QUALITY,
|
|
94
|
+
scoreImpact: 0, // 重复字面量=「建议配置化」提示,同魔数口径不扣分(避免重复串全项目误扣)
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
return findings;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 检查命名长度(min-length)。 */
|
|
101
|
+
export function checkMinLength({ file, text, rules }) {
|
|
102
|
+
const findings = [];
|
|
103
|
+
const rule = (rules || [])[0];
|
|
104
|
+
// 空规则短路(修复):filterRulesByExt 裁剪后 min-length 可能是**空数组**
|
|
105
|
+
// (truthy)——如 JS 文件只剩 exts=[java,kt]/[py] 的 java/python 规则时数组被裁空,
|
|
106
|
+
// 但 dispatch 的 `if (grouped['min-length'])` 对空数组仍真 → 本检查器拿空 rules 照跑
|
|
107
|
+
// (threshold 默认 2)→ 对当前文件报「裸 min-length 短名」(rule.id 空 → fallback),
|
|
108
|
+
// Pawchive test/tools 实测 27 条全为此根因。与 checkComplexity/checkMaxLines 同短路。
|
|
109
|
+
if (!rule) return findings;
|
|
110
|
+
const threshold = rule?.threshold || 2;
|
|
111
|
+
for (const hit of checkNameLengthAst(text, { min: threshold })) {
|
|
112
|
+
findings.push(makeFinding({
|
|
113
|
+
file, line: hit.line, rule: rule?.id || 'min-length', kind: 'min-length',
|
|
114
|
+
severity: 'warning',
|
|
115
|
+
message: `${hit.type === 'function' ? '函数' : '变量'}名「${hit.name}」过短(< ${threshold})——应可读命名`,
|
|
116
|
+
dimensions: rule?.dimensions || ['可读性'],
|
|
117
|
+
exemptHint: HINT_QUALITY,
|
|
118
|
+
scoreImpact: 0, // 重复字面量=「建议配置化」提示,同魔数口径不扣分(避免重复串全项目误扣)
|
|
119
|
+
}));
|
|
120
|
+
}
|
|
121
|
+
return findings;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 检查圈复杂度(max-complexity)。 */
|
|
125
|
+
export function checkComplexity({ file, text, rules }) {
|
|
126
|
+
const findings = [];
|
|
127
|
+
const rule = (rules || [])[0];
|
|
128
|
+
if (!rule) return findings; // 规则被 exts/exclude_paths 过滤为空时短路(防 rule.severity 崩溃)
|
|
129
|
+
const threshold = rule?.threshold || 10;
|
|
130
|
+
// blocker 阈值:yml 可配 block_complexity(如 50),缺省 = threshold*2
|
|
131
|
+
const blockThreshold = rule?.block || threshold * 2;
|
|
132
|
+
const fnScope2 = rule.scopeRules?.length ? analyzeFunctionalScope(text) : new Map(); // P4
|
|
133
|
+
for (const hit of checkComplexityAst(text, { warn: threshold, block: blockThreshold })) {
|
|
134
|
+
// 作用域豁免(P1):启动路径函数豁免圈复杂度;P4:public 不豁免
|
|
135
|
+
if (rule.scopeRules?.length && fnScope2.get(hit.name) !== 'public' && resolveScopeAction(rule.scopeRules, { path: classifyFunctionPath(hit.name), functionName: hit.name }) === 'exempt') continue;
|
|
136
|
+
// 分档提示(用户口径):11~20 中等 / 21~50 高风险应拆分 / 50+ 极难维护(拦)
|
|
137
|
+
const grade = hit.complexity > blockThreshold
|
|
138
|
+
? '极难维护(几乎不可测)'
|
|
139
|
+
: (hit.complexity > 20 ? '高风险' : '中等(开始难测)');
|
|
140
|
+
findings.push(makeFinding({
|
|
141
|
+
file, line: hit.line, rule: rule?.id || 'max-complexity', kind: 'max-complexity',
|
|
142
|
+
severity: capSeverity(rule.severity, hit.level),
|
|
143
|
+
message: `函数 ${hit.name} 圈复杂度 ${hit.complexity}(阈值 ${threshold},${grade})`
|
|
144
|
+
+ (hit.level === 'blocker' ? '——极难维护,应拆分(拦提交)' : '——应拆分'),
|
|
145
|
+
dimensions: rule?.dimensions || ['可维护性'],
|
|
146
|
+
exemptHint: HINT_QUALITY,
|
|
147
|
+
scoreImpact: hit.level === 'blocker' ? 2 : 1,
|
|
148
|
+
}));
|
|
149
|
+
}
|
|
150
|
+
return findings;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** 检查嵌套深度(max-depth)。 */
|
|
154
|
+
export function checkDepth({ file, text, rules }) {
|
|
155
|
+
const findings = [];
|
|
156
|
+
const rule = (rules || [])[0];
|
|
157
|
+
if (!rule) return findings; // 规则被 exts/exclude_paths 过滤为空时短路(防 rule.severity 崩溃)
|
|
158
|
+
const threshold = rule?.threshold || 4;
|
|
159
|
+
for (const hit of checkNestingDepthAst(text, { warn: threshold, block: threshold + 2 })) {
|
|
160
|
+
findings.push(makeFinding({
|
|
161
|
+
file, line: hit.line, rule: rule?.id || 'max-depth', kind: 'max-depth',
|
|
162
|
+
severity: capSeverity(rule.severity, hit.level),
|
|
163
|
+
message: `嵌套深度 ${hit.depth}(阈值 ${threshold})——应提取早返回`,
|
|
164
|
+
dimensions: rule?.dimensions || ['可读性'],
|
|
165
|
+
exemptHint: HINT_QUALITY,
|
|
166
|
+
scoreImpact: 0, // 重复字面量=「建议配置化」提示,同魔数口径不扣分(避免重复串全项目误扣)
|
|
167
|
+
}));
|
|
168
|
+
}
|
|
169
|
+
return findings;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 检查文件行数(max-lines)。fileScope 由调度层按仓库事实推导(见 lib/checks/dispatch.js 的 resolveFileScope)。 */
|
|
173
|
+
export function checkMaxLines({ file, text, rules, fileScope = '' }) {
|
|
174
|
+
const rule = (rules || [])[0];
|
|
175
|
+
if (!rule) return []; // 规则被 exts/exclude_paths 过滤为空时短路(防 rule.severity 崩溃)
|
|
176
|
+
const threshold = rule?.threshold || MAX_LINES_DEFAULT;
|
|
177
|
+
const { lines, codeLines, commentLines, level } = checkFileLines(text, { warn: threshold, block: threshold * 2 });
|
|
178
|
+
if (!level) return [];
|
|
179
|
+
// 作用域优先(**声明驱动**):规则 yml 的 scope_rules 命中本文件作用域时按 action 处理。
|
|
180
|
+
// exempt → 跳过(不出现在报告);downgrade → 降为提示(仍报、不扣分)。
|
|
181
|
+
const action = resolveScopeAction(rule.scopeRules, { fileScope });
|
|
182
|
+
if (action === 'exempt') return [];
|
|
183
|
+
// 平台约束优先:DSH 客户端单文件(不可拆分)→ 降级为提示(仍报、不扣分)
|
|
184
|
+
if (action === 'downgrade') {
|
|
185
|
+
return [makeFinding({
|
|
186
|
+
file, line: 1, rule: rule?.id || 'max-lines', kind: 'max-lines',
|
|
187
|
+
severity: 'info',
|
|
188
|
+
message: `文件 ${codeLines} 行代码(总 ${lines} 行,其中注释 ${commentLines} 行,阈值 ${threshold})——`
|
|
189
|
+
+ 'DSH 要求客户端为**单文件**(dsh.client / exports["./client"] 指向同一文件),不可按模块拆分,故降级为提示',
|
|
190
|
+
dimensions: rule?.dimensions || ['可维护性'],
|
|
191
|
+
exemptHint: 'dsh-skip-size(文件头,文件级属性)',
|
|
192
|
+
scoreImpact: 0,
|
|
193
|
+
})];
|
|
194
|
+
}
|
|
195
|
+
// 聚合型 vs 臃肿型(用户设计):先罚函数再考虑文件——函数是执行单元、
|
|
196
|
+
// 文件是组织单元。文件超行数但最大函数 ≤ 50 行(聚合型:函数都合规,文件大只是
|
|
197
|
+
// 函数多/数据多)→ 降级 info(提示不扣分);文件超行数且存在 > 50 行函数(臃肿型:
|
|
198
|
+
// 文件大是因为藏着大函数)→ 保持 warning/blocker(先拆函数再拆文件)。
|
|
199
|
+
const maxFuncLen = maxFunctionLength(text);
|
|
200
|
+
const FUNC_COMPLIANT_LIMIT = 50;
|
|
201
|
+
// 聚合型需「有函数且都合规」:无函数的纯脚本/数据文件(顶层语句堆叠)没有「函数多」
|
|
202
|
+
// 作证据,不豁免(保持 warning——脚本型大文件同样是拆模块债务)。
|
|
203
|
+
if (maxFuncLen > 0 && maxFuncLen <= FUNC_COMPLIANT_LIMIT) {
|
|
204
|
+
return [makeFinding({
|
|
205
|
+
file, line: 1, rule: rule?.id || 'max-lines', kind: 'max-lines',
|
|
206
|
+
severity: 'info',
|
|
207
|
+
message: `文件 ${codeLines} 行代码(总 ${lines} 行,其中注释 ${commentLines} 行,阈值 ${threshold})——`
|
|
208
|
+
+ `最大函数仅 ${maxFuncLen} 行,函数都合规,属聚合型(函数多而非函数长),文件边界只是导航成本,可接受`,
|
|
209
|
+
dimensions: rule?.dimensions || ['可维护性'],
|
|
210
|
+
exemptHint: 'dsh-skip-size(文件头,文件级属性)',
|
|
211
|
+
scoreImpact: 0,
|
|
212
|
+
})];
|
|
213
|
+
}
|
|
214
|
+
return [makeFinding({
|
|
215
|
+
file, line: 1, rule: rule?.id || 'max-lines', kind: 'max-lines',
|
|
216
|
+
severity: capSeverity(rule.severity, level),
|
|
217
|
+
// 判定按非注释部分(codeLines);总行数/注释行数一并展示便于判断拆分空间
|
|
218
|
+
message: `文件 ${codeLines} 行代码(总 ${lines} 行,其中注释 ${commentLines} 行,阈值 ${threshold})——`
|
|
219
|
+
+ `最大函数 ${maxFuncLen} 行(臃肿型:文件大因藏着超大函数),应拆分`,
|
|
220
|
+
dimensions: rule?.dimensions || ['可维护性'],
|
|
221
|
+
exemptHint: 'dsh-skip-size(文件头,文件级属性)',
|
|
222
|
+
scoreImpact: level === 'blocker' ? 2 : 1,
|
|
223
|
+
})];
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** 检查注释冗余密度(comment-density,,评审规则①)。
|
|
227
|
+
* 变量即注释——语义明确的代码里变量名已表达内容,额外的行注释不加深理解;
|
|
228
|
+
* 应只保留隐性约束/复杂设计/外部契约/非显然决策的**块注释**,减少行注释。
|
|
229
|
+
* 判定:行注释行数 ÷ 有效代码行数 > 阈值(规则 threshold 或默认 0.4)→ 提示。
|
|
230
|
+
* 块注释(斜杠星号、JSDoc、docstring)不计入(设计说明保留);只 warning 不拦截。
|
|
231
|
+
*/
|
|
232
|
+
export function checkCommentDensity({ file, text, rules }) {
|
|
233
|
+
const rule = (rules || [])[0];
|
|
234
|
+
if (!rule) return [];
|
|
235
|
+
const threshold = rule?.threshold != null ? rule.threshold : 0.4;
|
|
236
|
+
const hits = checkCommentDensityAst(text, { warn: threshold });
|
|
237
|
+
if (!hits.length) return [];
|
|
238
|
+
const h = hits[0];
|
|
239
|
+
return [makeFinding({
|
|
240
|
+
file, line: 1, rule: rule?.id || 'comment-density', kind: 'comment-density',
|
|
241
|
+
severity: capSeverity(rule.severity, 'warning'),
|
|
242
|
+
message: `行注释 ${h.commentLines} 行 ÷ 代码 ${h.codeLines} 行 = ${(h.ratio * 100).toFixed(0)}%(阈值 ${Math.round(threshold * 100)}%)——语义明确的代码变量即注释,行注释过多可能复述代码;只保留解释「为什么」的块注释`,
|
|
243
|
+
dimensions: rule?.dimensions || ['可读性'],
|
|
244
|
+
exemptHint: 'dsh-skip-quality(文件头=整文件)',
|
|
245
|
+
scoreImpact: 1,
|
|
246
|
+
})];
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** 检查重复硬编码串/数值(repeated-string / min-occurrences,两 kind 合并去重,)。 */
|
|
250
|
+
export function checkRepeated({ file, text, rules }) {
|
|
251
|
+
const findings = [];
|
|
252
|
+
// 多个规则(repeated-string + min-occurrences)合并传入时:
|
|
253
|
+
// · 阈值取最小(任一规则达到即报,不放过)
|
|
254
|
+
// · ignore 集合并
|
|
255
|
+
// · 同一文本只报一条(取第一条命中规则的 id)——修「同一文本被两个 kind 双报」
|
|
256
|
+
const thresholds = (rules || []).map((r) => Number(r.threshold) || 3);
|
|
257
|
+
const threshold = thresholds.length ? Math.min(...thresholds) : 3;
|
|
258
|
+
const ignore = [...new Set((rules || []).flatMap((r) => r.ignoreValues || []))];
|
|
259
|
+
const seen = new Set();
|
|
260
|
+
for (const hit of checkRepeatedStringsAst(text, { min: threshold, ignore })) {
|
|
261
|
+
if (seen.has(hit.value)) continue; // 同文本只报一次
|
|
262
|
+
seen.add(hit.value);
|
|
263
|
+
const rule = (rules || []).find((r) => Number(r.threshold || 3) <= hit.count) || (rules || [])[0];
|
|
264
|
+
findings.push(makeFinding({
|
|
265
|
+
file, line: hit.line, rule: rule?.id || 'repeated-string', kind: rule?.kind || 'repeated-string',
|
|
266
|
+
severity: 'warning',
|
|
267
|
+
message: `硬编码文本「${hit.value}」重复 ${hit.count} 次(阈值 ${threshold})——应配置化`,
|
|
268
|
+
dimensions: rule?.dimensions || ['可维护性'],
|
|
269
|
+
exemptHint: HINT_QUALITY,
|
|
270
|
+
scoreImpact: 0, // 重复字面量=「建议配置化」提示,同魔数口径不扣分(避免重复串全项目误扣)
|
|
271
|
+
}));
|
|
272
|
+
}
|
|
273
|
+
return findings;
|
|
274
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI 命令 · 账号 / 凭据 / 远端(从 cli.mjs 抽出)
|
|
3
|
+
*
|
|
4
|
+
* 为什么拆出来:cli.mjs 802 行超单文件阈值(400 行代码),本组 5 个命令
|
|
5
|
+
* (account-check / cred-env / remote-create / set-visibility / gen-ssh-key)
|
|
6
|
+
* 是独立的能力域(GitHub 账号与凭据操作),与审计/扫描/文档类命令无共享状态。
|
|
7
|
+
*
|
|
8
|
+
* 保持薄引用:命令只做「传参 + 格式化输出」,逻辑在 lib/git/*(与插件工具同源)。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { checkGithubAccount, formatGithubAccountBlock } from '../git/account.js';
|
|
12
|
+
import { ensureRemoteRepo, setVisibility } from '../git/remote.js';
|
|
13
|
+
import { generateSshKey } from '../git/credentials.js';
|
|
14
|
+
import { parseGithubOwnerRepo } from '../git/api.js';
|
|
15
|
+
import { execFileSync } from 'node:child_process';
|
|
16
|
+
|
|
17
|
+
/** 子命令失败输出前缀。 */
|
|
18
|
+
const FAIL_PREFIX = '❌ 失败:';
|
|
19
|
+
/** 子命令失败输出(统一格式:前缀 + 错误信息)。 */
|
|
20
|
+
const failOf = (r) => `${FAIL_PREFIX} ${r.error || ''}`;
|
|
21
|
+
|
|
22
|
+
/** 子命令:account-check — 校验 GitHub 账号与凭据(token 在线校验 + SSH 公钥指纹)。 */
|
|
23
|
+
export async function cmdAccountCheck(flags) {
|
|
24
|
+
const r = await checkGithubAccount({ token: flags.token || '', checkSsh: flags.checkSsh !== false });
|
|
25
|
+
if (flags.json) { console.log(JSON.stringify(r, null, 2)); return r.ok === false ? 1 : 0; }
|
|
26
|
+
// 复用插件的格式化输出(保证 CLI 与侧边栏账号面板口径一致)
|
|
27
|
+
console.log(formatGithubAccountBlock(r));
|
|
28
|
+
if (r.sshPub) console.log(`\n公钥内容:\n${r.sshPub}`);
|
|
29
|
+
return r.ok === false ? 1 : 0;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 子命令:cred-env — 输出插件保管凭据的环境变量前缀(AI 执行外部 git 时粘贴使用,无明文)。 */
|
|
33
|
+
export async function cmdCredEnv(flags) {
|
|
34
|
+
const { buildCredEnv } = await import('../git/cred-env.js');
|
|
35
|
+
const r = buildCredEnv({});
|
|
36
|
+
if (flags.json) { console.log(JSON.stringify(r, null, 2)); return 0; }
|
|
37
|
+
if (!r.provided.length) { console.log(`❌ ${r.hint}`); return 1; }
|
|
38
|
+
console.log('凭据传递(插件保管,以下只有路径/命令串,无 token/私钥明文):');
|
|
39
|
+
for (const ch of r.provided) {
|
|
40
|
+
const chCfg = r[ch];
|
|
41
|
+
console.log(`\n[${ch === 'ssh' ? 'SSH 通道' : 'HTTPS 通道'}]`);
|
|
42
|
+
console.log(` envPrefix: ${chCfg.envPrefix}`);
|
|
43
|
+
console.log(` 用法示例: ${chCfg.example}`);
|
|
44
|
+
}
|
|
45
|
+
console.log(`\n提示:${r.hint}`);
|
|
46
|
+
return 0;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 子命令:remote-create — 按项目文件夹在 GitHub 建远端仓库(已存在则复用)。 */
|
|
50
|
+
export async function cmdRemoteCreate(repo, flags) {
|
|
51
|
+
if (!repo) { console.error('缺少 <repo>(用法: git-sluice remote-create <repo> [--visibility public|private])'); return 1; }
|
|
52
|
+
const r = await ensureRemoteRepo({
|
|
53
|
+
repoPath: repo,
|
|
54
|
+
owner: flags.owner || '',
|
|
55
|
+
visibility: flags.visibility || 'private',
|
|
56
|
+
dryRun: flags.dryRun === true,
|
|
57
|
+
});
|
|
58
|
+
if (flags.json) { console.log(JSON.stringify(r, null, 2)); return r.ok ? 0 : 1; }
|
|
59
|
+
if (!r.ok) { console.error(failOf(r)); return 1; }
|
|
60
|
+
if (r.dryRun) { console.log(`预演:将创建 ${r.owner}/${r.name}(${r.visibility})`); return 0; }
|
|
61
|
+
if (r.exists) { console.log(`✅ 远端已存在,直接复用:${r.owner}/${r.name}(${r.visibility})`); return 0; }
|
|
62
|
+
console.log(`✅ 已创建远端仓库:${r.owner}/${r.name}(${r.visibility})`);
|
|
63
|
+
console.log(` origin → ${r.origin || ''}`);
|
|
64
|
+
return 0;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** 子命令:set-visibility — 切换仓库公开/私有。 */
|
|
68
|
+
export async function cmdSetVisibility(repo, flags) {
|
|
69
|
+
const vis = String(flags.visibility || '').toLowerCase();
|
|
70
|
+
if (!repo || (vis !== 'public' && vis !== 'private')) {
|
|
71
|
+
console.error('用法: git-sluice set-visibility <repo> --visibility public|private');
|
|
72
|
+
return 1;
|
|
73
|
+
}
|
|
74
|
+
// 用 local remote 反推 owner/repo(与插件 git_set_visibility 同一路径)
|
|
75
|
+
const pr = await resolveRepoOwnerName(repo);
|
|
76
|
+
if (!pr.ok) { console.error(`❌ ${pr.error}`); return 1; }
|
|
77
|
+
const r = await setVisibility({ owner: pr.owner, repo: pr.name, visibility: vis });
|
|
78
|
+
if (flags.json) { console.log(JSON.stringify({ ...r, owner: pr.owner, repo: pr.name }, null, 2)); return r.ok ? 0 : 1; }
|
|
79
|
+
if (!r.ok) { console.error(failOf(r)); return 1; }
|
|
80
|
+
console.log(`✅ ${pr.owner}/${pr.name} 可见性已切换为 ${vis}`);
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 子命令:gen-ssh-key — 生成 SSH 密钥对(公钥回传,私钥不出本机)。 */
|
|
85
|
+
export async function cmdGenSshKey(flags) {
|
|
86
|
+
const email = flags.email || '';
|
|
87
|
+
if (!email) { console.error('缺少 --email <x@y.z>(用法: git-sluice gen-ssh-key --email you@example.com [--force])'); return 1; }
|
|
88
|
+
const r = await generateSshKey(email, { force: flags.force === true });
|
|
89
|
+
if (flags.json) { console.log(JSON.stringify(r, null, 2)); return r.ok ? 0 : 1; }
|
|
90
|
+
if (!r.ok) { console.error(failOf(r)); return 1; }
|
|
91
|
+
console.log(`✅ SSH 密钥已生成(${email})`);
|
|
92
|
+
if (r.pubPath) console.log(` 公钥文件:${r.pubPath}`);
|
|
93
|
+
if (r.privPath) console.log(` 私钥文件:${r.privPath}(权限 0600,不上传)`);
|
|
94
|
+
if (r.pub) console.log(`\n公钥(整行复制到 GitHub → Settings → SSH keys):\n${r.pub}`);
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 从本地 remote 反推 owner/repo(set-visibility 用)。 */
|
|
99
|
+
async function resolveRepoOwnerName(repoPath) {
|
|
100
|
+
let url = '';
|
|
101
|
+
try {
|
|
102
|
+
url = execFileSync('git', ['-C', repoPath, 'remote', 'get-url', 'origin'], { encoding: 'utf8' }).trim();
|
|
103
|
+
} catch { return { ok: false, error: `读不到 origin:${repoPath}` }; }
|
|
104
|
+
const pr = parseGithubOwnerRepo(url);
|
|
105
|
+
if (!pr) return { ok: false, error: `无法从 origin 解析 owner/repo:${url}` };
|
|
106
|
+
return { ok: true, owner: pr.owner, name: pr.repo };
|
|
107
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI 命令 · 审计域(audit/scan + 插件配置对齐工具)(从 cli.mjs 抽出)
|
|
3
|
+
*
|
|
4
|
+
* 为什么拆出来:cli.mjs 578 行代码超单文件阈值(400),审计命令族 + 配置对齐工具
|
|
5
|
+
* (cliPluginConfig / pluginEqualAuditOpts / pluginEqualWeights / pathExists)是
|
|
6
|
+
* 「与插件 code_audit 结果一致」的独立能力域,被 cmdAudit/cmdScan/cmdCommit 共享。
|
|
7
|
+
*
|
|
8
|
+
* 保持薄引用:审计逻辑在 lib/audit/*(与插件 code_audit 同源)。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { auditWithScope, auditFull } from '../audit/index.js';
|
|
12
|
+
import { formatAnalysisCoverageLine } from '../audit/analysis-coverage.js';
|
|
13
|
+
import { scoreQuality } from '../score/index.js';
|
|
14
|
+
import { readSettings, applySettingsToCfg } from '../app/settings-bridge.js';
|
|
15
|
+
import { defaultConfig } from '../client/index.js';
|
|
16
|
+
import { access } from 'node:fs/promises';
|
|
17
|
+
import { join } from 'node:path';
|
|
18
|
+
|
|
19
|
+
/** 审计 full 扫描 findings 打印条数上限(防刷屏)。 */
|
|
20
|
+
const AUDIT_PRINT_LIMIT = 20;
|
|
21
|
+
|
|
22
|
+
/** 读插件同一份配置(config.json)→ 运行期 cfg(与插件启动回读同一映射)。
|
|
23
|
+
* 注意:applySettingsToCfg 是**原地修改** cfg、返回 { changedSystemPrompt } 状态对象
|
|
24
|
+
* (与插件 apply.js 用法一致:`const changed = applySettingsToCfg(cfg, saved)`)。
|
|
25
|
+
* 绝不能把它的返回值当 cfg 用——那会让 auditLevel/maxScanFiles/weightOverrides 等全变
|
|
26
|
+
* undefined,CLI 结果与插件不一致。 */
|
|
27
|
+
export function cliPluginConfig() {
|
|
28
|
+
const cfg = defaultConfig();
|
|
29
|
+
try {
|
|
30
|
+
const saved = readSettings({});
|
|
31
|
+
applySettingsToCfg(cfg, saved || {}); // 原地改 cfg,忽略返回值
|
|
32
|
+
} catch {
|
|
33
|
+
/* 配置缺失/损坏 → 保留 defaultConfig(与插件首启一致) */
|
|
34
|
+
}
|
|
35
|
+
return cfg;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 构造与插件 code_audit **完全相同**的审计参数(保证 CLI 与插件结果一致)。
|
|
40
|
+
* 对齐点:auditLevel、maxScanFiles、规则包顺序 slots、禁用槽位 disabledSlots、
|
|
41
|
+
* includeIgnored、rulesetDir、权重(weightOverrides)。CLI 显式传参优先于配置。
|
|
42
|
+
*/
|
|
43
|
+
export function pluginEqualAuditOpts(cfg, flags, { scope = 'diff' } = {}) {
|
|
44
|
+
const rulesetDir = flags.ruleset || '';
|
|
45
|
+
return {
|
|
46
|
+
scope,
|
|
47
|
+
rulesetDir,
|
|
48
|
+
maxScanFiles: cfg.maxScanFiles,
|
|
49
|
+
slots: cfg.auditRuleOrder && cfg.auditRuleOrder.length ? cfg.auditRuleOrder : undefined,
|
|
50
|
+
disabledSlots: Array.isArray(cfg.auditDisabledSlots) ? cfg.auditDisabledSlots : [],
|
|
51
|
+
includeIgnored: flags.includeIgnored === true,
|
|
52
|
+
// 分析覆盖率信息项(与插件 code_audit 同口径,由审计编排层计算;见 lib/audit/orchestrate.js)
|
|
53
|
+
coverage: flags.coverage !== false,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** CLI 审计权重:显式 --weights > 插件配置 weightOverrides > 默认权重表(与 code_audit 同序)。 */
|
|
58
|
+
export function pluginEqualWeights(cfg, flags) {
|
|
59
|
+
const src = flags.weights || (typeof cfg.weightOverrides === 'string' ? cfg.weightOverrides : '');
|
|
60
|
+
if (!src) return {};
|
|
61
|
+
try { return JSON.parse(src); } catch { return {}; }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 路径是否存在(异步,避免在 async 命令里做同步 I/O)。 */
|
|
65
|
+
async function pathExists(p) {
|
|
66
|
+
try { await access(p); return true; } catch { return false; }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 子命令:audit — 审计目录(**与插件 code_audit 结果一致**)。 */
|
|
70
|
+
export async function cmdAudit(root, flags) {
|
|
71
|
+
// 拆分:history 模式与 standard 模式各自独立函数(圈复杂度 18→各 <10)
|
|
72
|
+
if (flags.history === true) return runHistoryAuditCmd(root, flags);
|
|
73
|
+
return runStandardAudit(root, flags);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** history 模式:历史提交审计(逐提交快照全量审计 + 落盘报告)。 */
|
|
77
|
+
async function runHistoryAuditCmd(root, flags) {
|
|
78
|
+
const cfg = cliPluginConfig();
|
|
79
|
+
const { runHistoryAudit } = await import('../audit/history.js');
|
|
80
|
+
const opts = pluginEqualAuditOpts(cfg, flags, { scope: 'full' });
|
|
81
|
+
const weights = pluginEqualWeights(cfg, flags);
|
|
82
|
+
const r = await runHistoryAudit(root || '.', {
|
|
83
|
+
since: flags.since, until: flags.until, outDir: flags.out,
|
|
84
|
+
auditOpts: opts, weights,
|
|
85
|
+
onCommit: (p) => { if (!flags.json) console.log(` [${p.index}/${p.total}] ${p.short} ${p.ok ? '✓' : '✗ ' + (p.error || '')}`); },
|
|
86
|
+
});
|
|
87
|
+
if (!r.ok) { console.error(`❌ ${r.error || '历史审计失败'}`); return 1; }
|
|
88
|
+
if (flags.json) { console.log(JSON.stringify(r, null, 2)); return 0; }
|
|
89
|
+
console.log(`历史审计完成:${r.total} 个提交(处理 ${r.processed},失败 ${r.failed}${r.aborted ? ',已中断' : ''})`);
|
|
90
|
+
console.log(`报告目录:${r.reportDir}`);
|
|
91
|
+
return 0;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** standard 模式:full/diff 审计 + 评分 + 结果输出。 */
|
|
95
|
+
async function runStandardAudit(root, flags) {
|
|
96
|
+
const cfg = cliPluginConfig();
|
|
97
|
+
const full = flags.full === true || !(await pathExists(join(root || '.', '.git')));
|
|
98
|
+
const opts = pluginEqualAuditOpts(cfg, flags, { scope: full ? 'full' : 'diff' });
|
|
99
|
+
const weights = pluginEqualWeights(cfg, flags);
|
|
100
|
+
const auditResult = full ? await auditFull(root, opts) : await auditWithScope(root, opts);
|
|
101
|
+
const quality = scoreQuality(auditResult.findings, weights, { files: auditResult.files });
|
|
102
|
+
if (flags.json) {
|
|
103
|
+
console.log(JSON.stringify({ ok: true, repo: root, scope: auditResult.scope, summary: auditResult.summary, quality, findings: auditResult.findings, files: auditResult.files, analysisCoverage: auditResult.analysisCoverage || null, yaml: auditResult.yaml }, null, 2));
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
printAuditResult(root, auditResult, opts, weights, quality);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** standard 审计结果的可读输出(文案集中一处)。 */
|
|
110
|
+
function printAuditResult(root, auditResult, opts, weights, quality) {
|
|
111
|
+
console.log(`审计 ${root}(scope=${auditResult.scope}${opts.rulesetDir ? ', ruleset=' + opts.rulesetDir : ''}${opts.includeIgnored ? ', include-ignored' : ''})`);
|
|
112
|
+
console.log(` summary: ${JSON.stringify(auditResult.summary)}`);
|
|
113
|
+
if (quality.emptyResult) {
|
|
114
|
+
console.log(` quality: ${quality.emptyReason}(files=${auditResult.files})`);
|
|
115
|
+
} else {
|
|
116
|
+
console.log(` quality: ${quality.score}/100(${quality.level})`);
|
|
117
|
+
}
|
|
118
|
+
if (Object.keys(weights).length) console.log(` 权重覆盖(来自插件配置 weightOverrides): ${JSON.stringify(weights)}`);
|
|
119
|
+
// 文档加分制(0 分起、上限 10)——结构信号 + 交叉验证,不进问题计数
|
|
120
|
+
const ds = auditResult.docsScore;
|
|
121
|
+
if (ds && Array.isArray(ds.items)) {
|
|
122
|
+
const total = ds.items.filter((i) => i.hit).reduce((a, i) => a + (Number(i.score) || 0), 0);
|
|
123
|
+
console.log(` 文档加分:命中 ${ds.hits?.length ?? 0}/${ds.items.length}(+${total.toFixed(1)}/10)`);
|
|
124
|
+
if (Array.isArray(ds.review) && ds.review.length) console.log(` 建议人工复核:${ds.review.join(';')}`);
|
|
125
|
+
}
|
|
126
|
+
// 分析覆盖率(信息项,不进评分)——与插件 code_audit 同一口径,让「到底解析到多少」可见
|
|
127
|
+
if (auditResult.analysisCoverage) console.log(` ${formatAnalysisCoverageLine(auditResult.analysisCoverage)}`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** 子命令:scan — 全量扫描目录(**与插件 code_audit 结果一致**)。
|
|
131
|
+
* 修复:此前 CLI 只传 scope+depth,完全不带插件配置(auditLevel / maxScanFiles /
|
|
132
|
+
* 规则包启停 auditDisabledSlots / 权重 weightOverrides)→ 审计结果与插件不一致
|
|
133
|
+
* (实测「CLI 全量扫描分更低、文件更多」:跑了已禁用规则包 + 默认权重 + 不同文件上限)。
|
|
134
|
+
* 现在 CLI 读**同一份** config.json($DSH_HOME/git-push/config.json),用与插件 code_audit
|
|
135
|
+
* 完全相同的 auditOpts 与入口(auditFull),保证功能与结果一致。 */
|
|
136
|
+
export async function cmdScan(root, flags) {
|
|
137
|
+
const depth = flags.depth ?? 3;
|
|
138
|
+
const scanResult = await auditWithScope(root, { scope: 'full', depth });
|
|
139
|
+
console.log(`扫描 ${root}(full,depth=${depth})`);
|
|
140
|
+
console.log(` findings: ${scanResult.summary.total}(blocker ${scanResult.summary.blocker} / warning ${scanResult.summary.warning})`);
|
|
141
|
+
for (const f of scanResult.findings.slice(0, AUDIT_PRINT_LIMIT)) {
|
|
142
|
+
console.log(` [${f.severity}] ${f.rule} ${f.file}:${f.line} ${f.message || ''}`);
|
|
143
|
+
}
|
|
144
|
+
}
|