dsh-git-push 2.18.1 → 2.20.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.gitignore +4 -0
- package/README.md +4 -1
- package/cli.mjs +16 -3
- package/lib/ARCHITECTURE.md +3 -0
- package/lib/app/audit-api.js +1 -1
- package/lib/app/command-registry.js +14 -2
- package/lib/app/inject-text.js +1 -0
- package/lib/app/scope-check.js +69 -0
- package/lib/app/tool-call.js +49 -2
- package/lib/ast/credential.js +130 -14
- package/lib/ast/dataflow.js +127 -10
- package/lib/ast/index.js +2 -0
- package/lib/ast/naming.js +9 -1
- package/lib/ast/scope-collisions.js +228 -0
- package/lib/ast/treesitter.js +142 -1
- package/lib/audit/history.js +1 -1
- package/lib/audit/orchestrate.js +93 -6
- package/lib/audit/scope-policy.js +110 -0
- package/lib/audit-rules/audit-rules-comment.yml +20 -0
- package/lib/audit-rules/audit-rules-dsh.yml +16 -1
- package/lib/audit-rules/audit-rules-nodejs.yml +21 -6
- package/lib/checks/common.js +4 -4
- package/lib/checks/dispatch.js +5 -0
- package/lib/checks/index.js +2 -0
- package/lib/checks/regex.js +2 -2
- package/lib/checks/scope-collision.js +68 -0
- package/lib/cli/commands-audit.mjs +1 -1
- package/lib/commit-push.js +6 -1
- package/lib/exempt/index.js +5 -2
- package/lib/git/ignore.js +6 -4
- package/lib/git/init-compat.js +83 -4
- package/lib/git/push.js +25 -2
- package/lib/git/sensitive.js +30 -1
- package/lib/lint-adapter/detect.js +161 -0
- package/lib/lint-adapter/index.js +50 -0
- package/lib/lint-adapter/runner.js +133 -0
- package/lib/npm/publish.js +61 -11
- package/lib/rule/compilers/structure.js +27 -0
- package/lib/score/index.js +36 -4
- package/lib/self/index.js +1 -1
- package/package.json +20 -1
- package/scripts/audit-ext/dsh-inject-declarations.mjs +209 -0
- package/scripts/bump-version.mjs +20 -5
- package/scripts/check-js-scope.mjs +87 -0
- package/scripts/check.mjs +39 -1
- package/skills/dev/dsh-git-push.md +8 -2
|
@@ -24,6 +24,9 @@ registerCompiler(
|
|
|
24
24
|
message: r.description || r.name || '注释措辞审查',
|
|
25
25
|
dimensions: pickDimensions(r, [DIMENSIONS.文档]),
|
|
26
26
|
extra: {
|
|
27
|
+
// 路径级排除必须放进 extra:ruleOut 只透传固定顶层字段 + extra,
|
|
28
|
+
// 顶层塞 excludePaths 会被静默丢弃(实测:声明了却仍照报归档目录)。
|
|
29
|
+
excludePaths: Array.isArray(r.exclude_paths) ? r.exclude_paths.map(String) : undefined,
|
|
27
30
|
blacklist: Array.isArray(r.blacklist) ? r.blacklist.map((b) => ({ pattern: b.pattern, ...(b.weight !== undefined ? { weight: Number(b.weight) || 0 } : {}) })) : [],
|
|
28
31
|
whitelist: Array.isArray(r.whitelist) ? r.whitelist.map((w) => ({ pattern: w.pattern, ...(w.penalty !== undefined ? { penalty: Number(w.penalty) || 0 } : {}) })) : [],
|
|
29
32
|
additionalFeatures: Array.isArray(r.additional_features) ? r.additional_features.map((a) => ({ pattern: a.pattern, weight: Number(a.weight) || 0 })) : [],
|
|
@@ -78,3 +81,27 @@ registerCompiler(
|
|
|
78
81
|
dimensions: pickDimensions(r, [DIMENSIONS.可部署性]),
|
|
79
82
|
}),
|
|
80
83
|
);
|
|
84
|
+
|
|
85
|
+
/* ───────────────────────── 注册:拼接产物作用域撞名(dsh 槽位,scope-collision) ───────────────────────── */
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 拼接产物作用域撞名(多段 JS 拼进同一作用域时 var/function 静默覆盖)。
|
|
89
|
+
* 认领条件:显式 kind==='scope-collision'。
|
|
90
|
+
*
|
|
91
|
+
* 编译产物**故意不带任何项目契约**(前缀 / 顶层零声明 / 产物文件清单):
|
|
92
|
+
* 规则包是跨仓库共享的(同一份 yml 审计所有仓库),契约必须取自被审项目自己的
|
|
93
|
+
* package.json(lib/audit/scope-policy.js)——写进 yml 会让别人项目也收到
|
|
94
|
+
* 「缺少 dshgp_ 前缀」这类与它无关的告警。
|
|
95
|
+
* 作用域(exts / exclude_paths / file_patterns)仍走统一补齐(lib/rule/registry.js),
|
|
96
|
+
* 本编译器无需自己处理。
|
|
97
|
+
*/
|
|
98
|
+
registerCompiler(
|
|
99
|
+
'scope-collision',
|
|
100
|
+
(r) => r?.kind === 'scope-collision',
|
|
101
|
+
(r) => ruleOut({
|
|
102
|
+
id: r.id, name: r.name || r.id, kind: 'scope-collision', severity: r.severity || 'error',
|
|
103
|
+
level: severityLevel(r.severity || 'error'),
|
|
104
|
+
message: r.description || r.name || '拼接产物作用域撞名',
|
|
105
|
+
dimensions: pickDimensions(r, [DIMENSIONS.健壮性, DIMENSIONS.可维护性]),
|
|
106
|
+
}),
|
|
107
|
+
);
|
package/lib/score/index.js
CHANGED
|
@@ -117,12 +117,15 @@ export function countHitFilesByDimension(findings = []) {
|
|
|
117
117
|
* 防零分塌陷:对数衰减替代线性扣分——10 个错误和 100 个错误有明显分差(不都归 0),floor=0.1 保留微弱区分度。
|
|
118
118
|
* @param {Array} findings
|
|
119
119
|
* @param {object} [weights] 覆盖权重(默认 DEFAULT_WEIGHTS)
|
|
120
|
-
* @param {object} [context] { files?: number, scope?: string
|
|
121
|
-
*
|
|
120
|
+
* @param {object} [context] { files?: number, scope?: string, dimFileCounts?: object, dimRuleCounts?: object }
|
|
121
|
+
* —— files=0(空目录/0 变动)时不评分(score:null + emptyResult:true),防止「没扫到任何文件却直接满分」;
|
|
122
|
+
* dimRuleCounts(维度→生效规则绑定数)给出时,**零规则维度权重记 0**(无检测能力的维度不再贡献满分,
|
|
123
|
+
* 见下方「零规则维度记 0」);缺省则沿用旧口径(不缩放),行为逐位等价。
|
|
124
|
+
* 返回 uncoveredDimensions:被记 0 的维度清单,供报告显式标注「本维度无检测能力」。
|
|
122
125
|
* @returns {{dims: object, score: number|null, level: 'A'|'B'|'C'|'D'|'E'|null, weights: object, emptyResult?: boolean, emptyReason?: string}}
|
|
123
126
|
*/
|
|
124
127
|
export function scoreQuality(findings = [], weights = {}, context = {}) {
|
|
125
|
-
const { files = null, docsScore = null, dimFileCounts = null } = context;
|
|
128
|
+
const { files = null, docsScore = null, dimFileCounts = null, dimRuleCounts = null } = context;
|
|
126
129
|
// 0 文件(空目录 / diff 0 变动)不评分——findings 为空时对数衰减天然给满分,
|
|
127
130
|
// 但「没扫到任何文件」不等于「代码健康」,返回 null 明确区分(调用方展示「未扫描到内容」)。
|
|
128
131
|
if (files !== null && Number(files) === 0) {
|
|
@@ -169,6 +172,24 @@ export function scoreQuality(findings = [], weights = {}, context = {}) {
|
|
|
169
172
|
// 数据文件占比高的仓库里,用总文件数会把代码问题被数据资产数量摊薄(实测某资源仓库
|
|
170
173
|
// 3086 个文本文件中 2701 个是清单 json,可读性权重被稀释到 1/10)。
|
|
171
174
|
// 缺 dimFileCounts(旧调用方/独立调用)→ 回退总文件数,行为与上一版一致。
|
|
175
|
+
// ── 零规则维度记 0(2026-11-06):某维度在本次生效的规则集里**一条规则都没绑定**,
|
|
176
|
+
// 说明它对本仓库**没有检测能力**——此前它按「无命中=满分 10 + 满设定权重」计入总分,
|
|
177
|
+
// 于是「测不到」被算成「质量高」(实测外部仓库:安全性权重 18 仅 3 处规则绑定,
|
|
178
|
+
// 测试覆盖/可观测性/开发者体验 0 处绑定,五维齐满分把分抬到 85/A,而人工核实出 6 个真问题)。
|
|
179
|
+
// 记 0 等价于**把该维度剔出分母**:既不贡献满分、也不因满分稀释其它维度的扣分,
|
|
180
|
+
// 总分只在「真被测过的维度」上归一——口径更诚实且实现最简(不造新规则、不改衰减曲线)。
|
|
181
|
+
// 判据用**生效规则集**(已按仓库语言/槽位过滤后的 grouped),不是全量规则表:
|
|
182
|
+
// 纯 Python 仓库里没有 C# 专属规则属正常,不该因此把「可维护性」记 0。
|
|
183
|
+
// 缺 dimRuleCounts(旧调用方/独立调用)⇒ 不启用本口径,行为与改造前逐位等价。
|
|
184
|
+
const ruleCountOf = (dim) => {
|
|
185
|
+
if (!dimRuleCounts || typeof dimRuleCounts !== 'object') return null;
|
|
186
|
+
const n = Number(dimRuleCounts[dim]);
|
|
187
|
+
return Number.isFinite(n) ? n : 0;
|
|
188
|
+
};
|
|
189
|
+
// 防全塌保护:只有「规则集确实给出了维度绑定信息」(至少一个维度计数>0)时才启用本口径。
|
|
190
|
+
// 极端情形(自定义规则集所有规则都不声明 dimensions ⇒ dimRuleCounts 为 {},十维全 0)
|
|
191
|
+
// 会让分母塌成 0、总分算成 0——那不是「诚实」而是失真,故整条口径退回旧行为(不缩放)。
|
|
192
|
+
const coverageKnown = DIMENSION_ORDER.some((d) => ruleCountOf(d) > 0);
|
|
172
193
|
const denomOf = (dim) => {
|
|
173
194
|
const perDim = Number(dimFileCounts?.[dim]) > 0 ? Number(dimFileCounts[dim]) : 0;
|
|
174
195
|
return perDim || (Number(files) > 0 ? Number(files) : 0);
|
|
@@ -186,7 +207,14 @@ export function scoreQuality(findings = [], weights = {}, context = {}) {
|
|
|
186
207
|
return hf > 0 ? Math.min(1, hf / total) : null; // 无命中 → 不缩放
|
|
187
208
|
};
|
|
188
209
|
const dynamicWeights = {};
|
|
210
|
+
const uncoveredDimensions = [];
|
|
189
211
|
for (const d of DIMENSION_ORDER) {
|
|
212
|
+
// 零规则维度:直接记 0 权重(不进分母),并登记供报告显式标注「本维度无检测能力」
|
|
213
|
+
if (coverageKnown && ruleCountOf(d) === 0) {
|
|
214
|
+
dynamicWeights[d] = 0;
|
|
215
|
+
uncoveredDimensions.push(d);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
190
218
|
const ratio = dynamicRatio(d);
|
|
191
219
|
dynamicWeights[d] = (weightMap[d] || 0) * (ratio === null ? 1 : ratio);
|
|
192
220
|
}
|
|
@@ -198,5 +226,9 @@ export function scoreQuality(findings = [], weights = {}, context = {}) {
|
|
|
198
226
|
? Math.round(((weightedSum / totalWeight) * percentScale) * SCORE_ROUND_FACTOR) / SCORE_ROUND_FACTOR
|
|
199
227
|
: 0;
|
|
200
228
|
const level = score >= LEVEL_A_MIN ? 'A' : score >= LEVEL_B_MIN ? 'B' : score >= LEVEL_C_MIN ? 'C' : score >= LEVEL_D_MIN ? 'D' : 'E';
|
|
201
|
-
return {
|
|
229
|
+
return {
|
|
230
|
+
dims, counts, score, level, weights: weightMap, dynamicWeights,
|
|
231
|
+
// 启用零规则口径时回传清单(空数组=十维都有检测能力);未启用则为 null,调用方据此区分口径
|
|
232
|
+
uncoveredDimensions: coverageKnown ? uncoveredDimensions : null,
|
|
233
|
+
};
|
|
202
234
|
}
|
package/lib/self/index.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
export const VERSION = '2.
|
|
12
|
+
export const VERSION = '2.20.11'; // 2.20.11:修 CI 真因——test-cifs-init 直接 execFileSync 读 `git config --global --get-all safe.directory`,而该键**不存在时退出码为 1**,execFileSync 抛错;CI 是全新 HOME(无该键)必炸,本地开发机早有该键所以一直绿。改用无键容错的 readGlobalSafeDirs()(无键即空列表)。以「全新 HOME」模拟 CI 条件验证 7/7 通过。历史:2.20.10:敏感文件扫描不再享「强制全仓」特权——改为与审计同一开关同一范围:审计关闭(audit=false)时不扫,审计开启时只扫「本次将提交的文件」(按 auditScanScope 的 diff 语义)。新增 scanSensitive 参数贯通 tool-call → commitAndPush → ensureGitignore;缺省 true 仅为兼容直接调用方(CLI/测试)。历史:2.20.9:修「有改动提交卡分钟级」——scanSensitiveFiles 递归读全仓每个文件内容,在 CIFS/SMB 上每文件一次网络往返;724 文件的仓库实测单文件改动卡满 15 分钟仍未返回(0 改动秒回,因为零改动整段跳过)。改为提交路径只扫「本次将提交的文件」(paths 精确模式用 pathList,否则解析 git status --porcelain 的变更集);实测同一仓库从 60 秒跑不完降到 26 毫秒。缺省不传 onlyPaths 时保持原全仓行为(兼容其它调用方)。历史:2.20.8:修 CI 假红——test-cifs-init 的幂等断言把 skipped 文案写死成「已登记」,但这是 CIFS 环境分支;CI 是本地盘、属主与进程同 uid,走的是「属主一致」分支,断言因此恒失败(run 57~61 全红而本地一直绿)。改为按环境分支匹配 /已登记|一致/,并在本地盘条件(/tmp + 同 uid)完整复刻验证通过。历史:2.20.7:修 dataflow/clear-then-access 第六类误报——reset() 被当清空方法。业务代码里 reset() 绝大多数是「恢复默认值/重置状态」,重置后对象仍有内容、读取安全(实测:某配置类 reset()->bool,测试断言 cfg.reset() 后 get("general.theme")=="dark" 取得有效默认值);同语料 13 条命中里 12 条源于此。已从 CLEAR_METHODS 移除,真正的容器清空用 clear()(保留)。历史:2.20.6:修 dataflow/clear-then-access 第五类系统性误报——Python 缩进式函数体从未被识别(区间收集只认 function 关键字与 ') {'),fnRanges 为空导致 mergeFnRanges 退化成「整个文件一个区间」,同文件内任意位置的 clear 与 access 都配成一对(实测 clear 在 invalidate()、访问在 build_index(),相距 177 行仍被报)。新增 collectPythonDefBodies 按缩进解析 def/async def 块并独立成体;闭包(嵌套 def 捕获外层变量)仍合并为一个体(是同一数据流,不该拆)。真实语料 13→1,剩余 1 条属 D3 边界内的合理提示(reset 后另有 _load_settings 重填,跨方法推断不做)。历史:2.20.5:修 dataflow/clear-then-access 四类系统性误报(真实语料实测 11 条命中里 8 条是误报)——①.empty() 被当清空(实为查询,从 CLEAR_METHODS 移除)②写目标 obj[k]=v 被当读访问(配对 ] 后跟 = 即按写回撤销)③类型注解位参与(PEP526 `x: list = []` 的 list 被当对象名、`-> list[str]` 被当访问;`:` 前须为标识符以区分 Python 函数定义冒号)④多目标解包错位(`a, b = [], {}` 把 [] 算给 b)。修复后同批文件 11→3 且剩余 3 条经人工核实均为真命中,真缺陷未被压制(正样本断言)。历史:2.20.4:树化迁移第二条 short-func-name——类方法/对象方法短名此前完全查不到(token 级只认 function 关键字),现走 method_definition 等定义节点判定;get/set 访问器显式排除(name 是属性名非函数名);初筛补方法形态 pattern(allow 精筛前 pattern 必须先命中候选,否则树化无效);TREE_FIRST_KINDS 登记 short-func-name。历史:2.20.3:修 CIFS/SMB 上「建仓成功但仓库对外不可用」——forceuid 挂载把目录属主映射成挂载用户(本机 杜渊/1026)而进程 uid 是套件用户(284371),git 2.55 对所有命令报 dubious ownership;插件内部带 -c safe.directory=* 感觉不到,交出去的仓库用户一敲 git 就挂。实测仓库级 [safe] directory 不生效(所有权检查先于读仓库 config),故新增 registerTrustedRepo/unregisterTrustedRepo 走 global 具体路径登记(只登记该目录,不用 *,同 uid 自动跳过),ensureUsableLocalRepo 三条路径(keep/create/repair)统一补齐。历史:2.20.2:修委托层自身灯下黑——tools/ruff 缺可执行位时旧行为静默返回空,与「项目没配 ruff」在报告里完全无法区分(部署副本迁移实测踩中:cp/同步不保 mode)。新增 detectLinterStatus 输出 unavailable(含具体成因与修复动作),并接进 linted;候选路径四律清单合并为 binCandidates 单一来源(原 resolveBin 与 resolveBinDetailed 各写一份,改一处漏一处会自相矛盾)。历史:2.20.1:新增外部 linter 委托层(方向 A 骨架,lib/lint-adapter/)——探测被审项目自带官方 linter([tool.ruff] 配置 + tools/·PATH 可执行自探测)→ 调用 ruff --output-format json → 适配成统一 finding(规则码→维度映射、路径转相对、来源标记 linter:ruff)。两条硬约束落地:①外部 finding severity 恒封顶 warning,**只进评分与报告、绝不进拦截门禁**(别人的规则集不裁决本仓能否提交);②探不到/崩溃/超时/坏输出一律降级空(含退出码≥2 不得被当成「外部判定无问题」的假阴性)。仅 full 范围委托;linted 委托状态进审计结果(防静默空转);lint-adapter 纳入层边界门禁 AUDIT_DIRS。历史:2.20.0:评分「零规则维度记 0」——本次生效规则集里一条规则都没绑定的维度(无检测能力)权重记 0 剔出分母,并回传 uncoveredDimensions 显式标注「测不到≠质量高」;编排层新增 computeDimRuleCounts,五个评分调用点统一接 dimRuleCounts,含全塌保护与向后兼容。历史:2.19.0:审计「有树走树」(方向 E1-E3)——凭据精筛 credential-value 改吃 tree-sitter 语法树(参数默认值/复合右值/三元不再误报、bytes/raw 前缀真凭据不再漏报、凭据名强弱分级+值置信度),建树触发与 astConfirmSpan 解耦(TREE_FIRST_KINDS),treeUsage 状态进审计结果(防静默回退)。历史:2.18.3:新增 scope_check 工具与 kind=scope-collision 审计规则(拼接产物作用域撞名)。
|
|
13
13
|
// 实测后果:该目录有 package.json ⇒ npm 去打包整棵 DSH 树、输出 2.1MB > spawnSync 默认 maxBuffer 1MB ⇒ ENOBUFS(npm_publish 的体检与真发全部失败);
|
|
14
14
|
// 该目录没有 package.json 时报 ENOENT。现 publish 的两个调用点显式传 cwd=目标包目录,并给 runNpm 加 16MB maxBuffer。
|
|
15
15
|
// 2.8.3:文案修正——「零改动 / 无新提交」明确为**正常成功路径**(注入用法、工具描述、README、skill 同批改),并修 job 输出自相矛盾(cleanSkipCommit 路径补 committed:false,不再显示「已提交,未推送」)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-git-push",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.20.11",
|
|
4
4
|
"description": "DSH git 自动提交推送插件——统一函数入口架构(规则/审计/git/自身/侧边栏/评分/豁免/上下文/HTTP/测试十大总入口)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -97,5 +97,24 @@
|
|
|
97
97
|
"js-yaml": "4.1.0",
|
|
98
98
|
"tree-sitter-wasms": "0.1.13",
|
|
99
99
|
"web-tree-sitter": "0.25.10"
|
|
100
|
+
},
|
|
101
|
+
"dshScopeCheck": {
|
|
102
|
+
"note": "拼接产物作用域检查:files 里每个文件都查「同作用域重名 / 顶层声明 / 命名前缀」。查法:git-sluice scope-check(无参数即读本块 files);其它项目只要在自己的 package.json 写同名字段即可复用同一套判定",
|
|
103
|
+
"files": [
|
|
104
|
+
"lib/client.js"
|
|
105
|
+
],
|
|
106
|
+
"prefix": "dshgp_",
|
|
107
|
+
"allowlist": [
|
|
108
|
+
"module",
|
|
109
|
+
"exports",
|
|
110
|
+
"jsx",
|
|
111
|
+
"react",
|
|
112
|
+
"store",
|
|
113
|
+
"NS",
|
|
114
|
+
"SETTINGS_NS",
|
|
115
|
+
"inject",
|
|
116
|
+
"apply"
|
|
117
|
+
],
|
|
118
|
+
"topLevelMustBeEmpty": true
|
|
100
119
|
}
|
|
101
120
|
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DSH 插件审计扩展:inject 声明与导出面。
|
|
3
|
+
*
|
|
4
|
+
* 与 dsh-useful-tools 的 verify_plugin(lib/core/verify-plugin/dsh-rules.mjs)**同源规则、独立实现**:
|
|
5
|
+
* 两个插件不互相 import,各自维护判定逻辑;规则增删改要两边同步(见 useful-tools 的 CONTRACT C-114)。
|
|
6
|
+
*
|
|
7
|
+
* 为什么用扩展脚本而不是 YAML 正则:这两条都需要**跨行读 inject 声明**(`export const inject = [...]`),
|
|
8
|
+
* 纯逐行正则做不到 —— 只能看「有没有 ctx.xxx」,无法判断 xxx 是否已经声明。
|
|
9
|
+
*
|
|
10
|
+
* 两条规则:
|
|
11
|
+
* dsh/ctx-service-not-injected (blocker)访问 ctx.<服务> 但 inject 没声明该服务
|
|
12
|
+
* dsh/plugin-default-export-hides-inject(blocker)入口同时有 default 与命名 inject/apply
|
|
13
|
+
*/
|
|
14
|
+
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
|
15
|
+
import { extname, join, relative } from 'node:path';
|
|
16
|
+
|
|
17
|
+
/** 参与扫描的扩展名。 */
|
|
18
|
+
const JS_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts']);
|
|
19
|
+
/** 不扫描的目录(第三方依赖、产物、测试夹具、回收站)。 */
|
|
20
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.trash', 'test', 'tests', 'audit-history']);
|
|
21
|
+
/** 扫描上限:单仓库最多看这么多文件,避免大仓拖慢审计。 */
|
|
22
|
+
const MAX_FILES = 400;
|
|
23
|
+
/** 单文件大小上限。 */
|
|
24
|
+
const MAX_FILE_BYTES = 512 * 1024;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* cordis Context 自身的内建成员(不是"服务"):访问它们不需要 inject 声明。
|
|
28
|
+
* 只收确定不会误伤的:事件 API、effect、logger、依赖注入原语、fiber/scope 等。
|
|
29
|
+
*/
|
|
30
|
+
const CORDIS_BUILTIN_MEMBERS = new Set([
|
|
31
|
+
'on', 'once', 'off', 'emit', 'effect', 'logger', 'inject', 'plugin', 'get', 'set', 'provide',
|
|
32
|
+
'accessor', 'root', 'scope', 'fiber', 'reflect', 'registry', 'runtime', 'dispose', 'extend',
|
|
33
|
+
'isolate', 'waterfall', 'bail', 'parallel', 'serial', 'ctx', 'setTimeout', 'clearTimeout',
|
|
34
|
+
'setInterval', 'clearInterval', 'name', 'config', 'options', 'state',
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
/** 已知的「错误字段名」:不是 cordis 服务,由 YAML 规则 dsh/ctx-undeclared-property-read 负责。 */
|
|
38
|
+
const KNOWN_BAD_CTX_FIELDS = new Set([
|
|
39
|
+
'sessionId', 'sessionID', 'conversationId', 'agentId', 'workspaceRoot', 'dshHome', 'DSH_HOME',
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 真实存在、通过 ctx 暴露的 cordis 服务(保守清单)。
|
|
44
|
+
* 为什么需要:`ctx` 是极常见的参数名——HTTP 请求、工具执行上下文、遍历累加器都可能叫 ctx,
|
|
45
|
+
* 只靠 `ctx.xxx` 的写法无法区分语义(实测:真实插件被误报 20 条 / 仓库)。只报清单里的服务名。
|
|
46
|
+
*/
|
|
47
|
+
const KNOWN_CORDIS_SERVICES = new Set([
|
|
48
|
+
'tools', 'fs', 'sessions', 'llm', 'credentials', 'webServer', 'slots', 'locale',
|
|
49
|
+
'storageDomain', 'workspaceRegistry', 'commands', 'sandbox', 'models', 'settings',
|
|
50
|
+
'jobs', 'subagents', 'skills', 'schedule', 'terminals', 'systemPrompt', 'spillStore',
|
|
51
|
+
'pluginManager', 'pluginInventory', 'approval', 'sessionQuery', 'agentLoop',
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
/** 该文件是不是插件入口:只有入口手里那个 ctx 才确定是 cordis Context。 */
|
|
55
|
+
function isPluginEntry(text) {
|
|
56
|
+
return /export\s+(async\s+)?function\s+apply\b/.test(text)
|
|
57
|
+
|| /export\s+const\s+inject\b/.test(text);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 递归列待扫描的 JS 文件(相对仓库根的路径)。 */
|
|
61
|
+
function collectFiles(repo) {
|
|
62
|
+
const out = [];
|
|
63
|
+
const walk = (dir) => {
|
|
64
|
+
if (out.length >= MAX_FILES) return;
|
|
65
|
+
let entries;
|
|
66
|
+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
67
|
+
for (const entry of entries) {
|
|
68
|
+
if (out.length >= MAX_FILES) return;
|
|
69
|
+
if (SKIP_DIRS.has(entry.name)) continue;
|
|
70
|
+
const full = join(dir, entry.name);
|
|
71
|
+
if (entry.isDirectory()) { walk(full); continue; }
|
|
72
|
+
if (!JS_EXTS.has(extname(entry.name))) continue;
|
|
73
|
+
try { if (statSync(full).size > MAX_FILE_BYTES) continue; } catch { continue; }
|
|
74
|
+
out.push({ abs: full, rel: relative(repo, full).replace(/\\/g, '/') });
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
walk(repo);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 取 `export const inject = [...]` 声明的服务名。
|
|
83
|
+
* 用括号配对而非单行正则:兼容多行数组与 `[{ required: [...], optional: [...] }]` 形态。
|
|
84
|
+
*/
|
|
85
|
+
function declaredInjectNames(text) {
|
|
86
|
+
const names = new Set();
|
|
87
|
+
const anchor = /export\s+const\s+inject\s*=\s*/.exec(text);
|
|
88
|
+
if (!anchor) return names;
|
|
89
|
+
const start = anchor.index + anchor[0].length;
|
|
90
|
+
let depth = 0;
|
|
91
|
+
let end = -1;
|
|
92
|
+
for (let i = start; i < text.length; i += 1) {
|
|
93
|
+
const ch = text[i];
|
|
94
|
+
if (ch === '[' || ch === '{') depth += 1;
|
|
95
|
+
else if (ch === ']' || ch === '}') {
|
|
96
|
+
depth -= 1;
|
|
97
|
+
if (depth === 0) { end = i; break; }
|
|
98
|
+
} else if (ch === ';' && depth === 0) { end = i; break; }
|
|
99
|
+
}
|
|
100
|
+
const block = text.slice(start, end === -1 ? Math.min(start + 600, text.length) : end + 1);
|
|
101
|
+
for (const quoted of block.matchAll(/['"`]([^'"`]+)['"`]/g)) names.add(quoted[1]);
|
|
102
|
+
return names;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 去掉行内注释,保留字符串内容(字符串里的 `//` 不能当注释起点)。 */
|
|
106
|
+
function stripTrailingComment(line) {
|
|
107
|
+
let out = '';
|
|
108
|
+
let quote = '';
|
|
109
|
+
for (let i = 0; i < line.length; i += 1) {
|
|
110
|
+
const ch = line[i];
|
|
111
|
+
if (quote) {
|
|
112
|
+
out += ch;
|
|
113
|
+
if (ch === '\\') { out += line[i + 1] || ''; i += 1; continue; }
|
|
114
|
+
if (ch === quote) quote = '';
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (ch === "'" || ch === '"' || ch === '`') { quote = ch; out += ch; continue; }
|
|
118
|
+
if (ch === '/' && line[i + 1] === '/') break;
|
|
119
|
+
if (ch === '/' && line[i + 1] === '*') {
|
|
120
|
+
const close = line.indexOf('*/', i + 2);
|
|
121
|
+
if (close < 0) break;
|
|
122
|
+
i = close + 1;
|
|
123
|
+
out += ' ';
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
out += ch;
|
|
127
|
+
}
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 规则 A:访问 ctx.<服务> 但没在 inject 里声明。返回命中行号数组。 */
|
|
132
|
+
function ctxServiceNotInjectedHits(text) {
|
|
133
|
+
// 只在插件入口检查:非入口文件里的 ctx 多半是别的语义(HTTP 请求 / 工具上下文 / 累加器),
|
|
134
|
+
// 逐一判断不了,宁可漏报也不误报。
|
|
135
|
+
if (!isPluginEntry(text)) return [];
|
|
136
|
+
const declared = declaredInjectNames(text);
|
|
137
|
+
const hits = [];
|
|
138
|
+
const lines = text.split('\n');
|
|
139
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
140
|
+
const raw = lines[i];
|
|
141
|
+
if (/^\s*(\/\/|\*|\/\*)/.test(raw)) continue;
|
|
142
|
+
const code = stripTrailingComment(raw);
|
|
143
|
+
if (!code.includes('ctx')) continue;
|
|
144
|
+
for (const match of code.matchAll(/\bctx\s*\??\.\s*([A-Za-z_$][\w$]*)/g)) {
|
|
145
|
+
const member = match[1];
|
|
146
|
+
if (CORDIS_BUILTIN_MEMBERS.has(member)) continue;
|
|
147
|
+
if (KNOWN_BAD_CTX_FIELDS.has(member)) continue;
|
|
148
|
+
if (!KNOWN_CORDIS_SERVICES.has(member)) continue;
|
|
149
|
+
if (declared.has(member)) continue;
|
|
150
|
+
hits.push({ line: i + 1, text: raw.trim().slice(0, 200) });
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return hits;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** 规则 B:同时有 export default 与命名 inject/apply(DSH 取 default 后命名导出失效)。 */
|
|
158
|
+
function defaultExportConflictLine(text) {
|
|
159
|
+
const hasDefault = /(^|\n)\s*export\s+default\b/.test(text);
|
|
160
|
+
const hasNamedInject = /(^|\n)\s*export\s+(const|let|var)\s+inject\b/.test(text);
|
|
161
|
+
const hasNamedApply = /(^|\n)\s*export\s+(async\s+)?function\s+apply\b/.test(text);
|
|
162
|
+
if (!hasDefault || !(hasNamedInject || hasNamedApply)) return 0;
|
|
163
|
+
const lines = text.split('\n');
|
|
164
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
165
|
+
if (/^\s*(\/\/|\*|\/\*)/.test(lines[i])) continue;
|
|
166
|
+
if (/(^|\n)\s*export\s+default\b/.test(lines[i])) return i + 1;
|
|
167
|
+
}
|
|
168
|
+
return 1;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export const auditExt = {
|
|
172
|
+
name: 'dsh-inject-declarations',
|
|
173
|
+
match: (repo) => Boolean(repo && repo !== '.'),
|
|
174
|
+
run: async (repo) => {
|
|
175
|
+
const findings = [];
|
|
176
|
+
for (const file of collectFiles(repo)) {
|
|
177
|
+
let text = '';
|
|
178
|
+
try { text = readFileSync(file.abs, 'utf8'); } catch { continue; }
|
|
179
|
+
|
|
180
|
+
for (const hit of ctxServiceNotInjectedHits(text)) {
|
|
181
|
+
findings.push({
|
|
182
|
+
file: file.rel,
|
|
183
|
+
line: hit.line,
|
|
184
|
+
rule: 'dsh/ctx-service-not-injected',
|
|
185
|
+
severity: 'blocker',
|
|
186
|
+
scoreImpact: 0,
|
|
187
|
+
message: '访问 ctx 上未 inject 的服务:cordis 会直接抛 cannot get property … without inject,插件整条不激活;'
|
|
188
|
+
+ '需模块级 export const inject = [\'服务名\'],或改用 ctx.get(\'服务名\')',
|
|
189
|
+
dimensions: ['健壮性'],
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const conflictLine = defaultExportConflictLine(text);
|
|
194
|
+
if (conflictLine) {
|
|
195
|
+
findings.push({
|
|
196
|
+
file: file.rel,
|
|
197
|
+
line: conflictLine,
|
|
198
|
+
rule: 'dsh/plugin-default-export-hides-inject',
|
|
199
|
+
severity: 'blocker',
|
|
200
|
+
scoreImpact: 0,
|
|
201
|
+
message: '入口同时存在 export default 与命名 inject/apply:DSH 装载取 module.default || module,'
|
|
202
|
+
+ '有 default 时命名 inject/name 全部失效 ⇒ 访问服务直接抛错、插件不激活;入口只保留命名导出',
|
|
203
|
+
dimensions: ['健壮性'],
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return findings;
|
|
208
|
+
},
|
|
209
|
+
};
|
package/scripts/bump-version.mjs
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* node scripts/bump-version.mjs --message "…" --apply # 真写盘
|
|
16
16
|
* node scripts/bump-version.mjs --to 2.11.0 --message "…" --apply # 指定版本(默认 patch +1)
|
|
17
17
|
* node scripts/bump-version.mjs --message-file /tmp/msg.txt --apply
|
|
18
|
+
* node scripts/bump-version.mjs --message "…" --comment "VERSION 行用的短摘要(可选)" --apply
|
|
18
19
|
*
|
|
19
20
|
* 约定:
|
|
20
21
|
* · **默认 dry-run**——只打印将要改动的三处(旧值 → 新值),不落盘;确认无误再加 --apply。
|
|
@@ -36,13 +37,14 @@ const RELEASES = join(ROOT, 'docs', 'releases.json');
|
|
|
36
37
|
|
|
37
38
|
/** 解析命令行参数(只认 --flag value 与布尔 --apply)。 */
|
|
38
39
|
function parseArgs(argv) {
|
|
39
|
-
const out = { apply: false, to: '', message: '', messageFile: '' };
|
|
40
|
+
const out = { apply: false, to: '', message: '', messageFile: '', comment: '' };
|
|
40
41
|
for (let i = 0; i < argv.length; i++) {
|
|
41
42
|
const a = argv[i];
|
|
42
43
|
if (a === '--apply') { out.apply = true; continue; }
|
|
43
44
|
if (a === '--message' || a === '-m') { out.message = argv[++i] || ''; continue; }
|
|
44
45
|
if (a === '--message-file') { out.messageFile = argv[++i] || ''; continue; }
|
|
45
46
|
if (a === '--to') { out.to = argv[++i] || ''; continue; }
|
|
47
|
+
if (a === '--comment') { out.comment = argv[++i] || ''; continue; }
|
|
46
48
|
}
|
|
47
49
|
return out;
|
|
48
50
|
}
|
|
@@ -71,8 +73,14 @@ function readJson(p) {
|
|
|
71
73
|
* 拼新的 VERSION 行。
|
|
72
74
|
* 旧注释形如:`2.10.4:本次说明。历史:2.10.3:更早说明。` → 把「本次说明」降级进历史链,
|
|
73
75
|
* 只保留最近 2 条,避免每版都把整串历史再抄一遍(实测 2.9.x 之后该行已接近不可读)。
|
|
76
|
+
*
|
|
77
|
+
* ⚠️ **行注释必须单行**:`--message-file` 常带多段落,若原样写进 `//` 后面的注释,
|
|
78
|
+
* 换行会把文件撕成多行 → 整个 lib/self/index.js 语法错误(ESM 加载期就炸,
|
|
79
|
+
* `node cli.mjs` 直接 TypeError)。故此处按「首段首句」压成一行摘要,
|
|
80
|
+
* 正文完整内容仍原样进 docs/releases.json(那边是 JSON 字符串,换行合法)。
|
|
81
|
+
* 需要更长摘要时用 `--comment` 显式给。
|
|
74
82
|
*/
|
|
75
|
-
function buildVersionLine(oldLine, newVer, oldVer, message) {
|
|
83
|
+
function buildVersionLine(oldLine, newVer, oldVer, message, commentOverride = '') {
|
|
76
84
|
const m = /export const VERSION = '([^']+)';\s*\/\/(.*)$/.exec(oldLine);
|
|
77
85
|
const oldComment = m ? m[2].trim() : '';
|
|
78
86
|
// 旧版本的「本次说明」= 历史链之前的那一段
|
|
@@ -82,8 +90,12 @@ function buildVersionLine(oldLine, newVer, oldVer, message) {
|
|
|
82
90
|
// 历史链:新压入的旧版摘要 + 原有最近 1 条
|
|
83
91
|
const prev = oldMain ? [`${oldVer}:${oldMain}`] : [];
|
|
84
92
|
const kept = oldHist ? oldHist.split(/。\s*(?=[\d.]+:)/).slice(0, 1).map((s) => s.replace(/。$/, '')) : [];
|
|
85
|
-
const chain = [...prev, ...kept].join('。');
|
|
86
|
-
|
|
93
|
+
const chain = prev.length || kept.length ? [...prev, ...kept].join('。').replace(/。+/g, '。') : '';
|
|
94
|
+
// 本轮摘要:显式覆盖优先;否则取首段首句,超长截断
|
|
95
|
+
const oneLine = String(commentOverride || message).replace(/\s+/g, ' ').trim();
|
|
96
|
+
const firstSentence = oneLine.split(/。/)[0].trim();
|
|
97
|
+
const summary = firstSentence.length > 160 ? `${firstSentence.slice(0, 160)}…` : firstSentence;
|
|
98
|
+
const comment = `${newVer}:${summary}。` + (chain ? `历史:${chain}。` : '');
|
|
87
99
|
return `export const VERSION = '${newVer}'; // ${comment}`;
|
|
88
100
|
}
|
|
89
101
|
|
|
@@ -107,7 +119,10 @@ const selfLines = selfSrc.split('\n');
|
|
|
107
119
|
const vi = selfLines.findIndex((l) => /^export const VERSION = '/.test(l));
|
|
108
120
|
if (vi < 0) fail('lib/self/index.js 未找到 VERSION 行');
|
|
109
121
|
const oldLine = selfLines[vi];
|
|
110
|
-
const newLine = buildVersionLine(oldLine, target, cur, message);
|
|
122
|
+
const newLine = buildVersionLine(oldLine, target, cur, message, args.comment);
|
|
123
|
+
// 硬门禁:行注释一旦带换行就把整个 lib/self/index.js 撕成多行(ESM 加载期直接抛
|
|
124
|
+
// "Invalid or unexpected token",cli.mjs / 插件入口全部起不来)。宁可在写盘前失败。
|
|
125
|
+
if (/[\r\n]/.test(newLine)) fail('VERSION 行必须是单行(注释里的换行会破坏整个模块语法)');
|
|
111
126
|
|
|
112
127
|
// ── 预览(默认 dry-run)
|
|
113
128
|
console.log(`升版:${cur} → ${target}${args.apply ? '(--apply 真写盘)' : '(dry-run,未写盘)'}`);
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 拼接产物作用域撞名检查(独立 CLI;判定与策略逻辑在 lib/,与 `git-sluice scope-check` 同一份)。
|
|
4
|
+
*
|
|
5
|
+
* 用法:
|
|
6
|
+
* node scripts/check-js-scope.mjs <file.js> [...] [--prefix=dshgp_] [--allowlist=a,b] [--top=true|false] [--json]
|
|
7
|
+
* node scripts/check-js-scope.mjs --config package.json # 读该 package.json 的 dshScopeCheck.files
|
|
8
|
+
*
|
|
9
|
+
* 参数名与 `git-sluice scope-check` 对齐(allowlist,旧写法 --allow 仍认)。
|
|
10
|
+
* 约定按**文件所属项目**取:别人项目没声明 dshScopeCheck 时只查「同帧重名」,
|
|
11
|
+
* 不会拿本项目的 dshgp_ 前缀去要求它(实测:那会刷一屏与它无关的告警)。
|
|
12
|
+
*/
|
|
13
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
14
|
+
import { dirname, join, resolve } from 'node:path';
|
|
15
|
+
import { fileURLToPath } from 'node:url';
|
|
16
|
+
|
|
17
|
+
import { runScopeCheck } from '../lib/app/scope-check.js';
|
|
18
|
+
|
|
19
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
20
|
+
const argv = process.argv.slice(2);
|
|
21
|
+
const VALUE_FLAGS = new Set(['config', 'prefix', 'allowlist', 'allow', 'top']);
|
|
22
|
+
|
|
23
|
+
const { flags, positional } = (() => {
|
|
24
|
+
const out = { flags: new Map(), positional: [] };
|
|
25
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
26
|
+
const token = argv[i];
|
|
27
|
+
if (!token.startsWith('--')) { out.positional.push(token); continue; }
|
|
28
|
+
const body = token.slice(2);
|
|
29
|
+
if (body.includes('=')) {
|
|
30
|
+
const [k, ...rest] = body.split('=');
|
|
31
|
+
out.flags.set(k, rest.join('='));
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (VALUE_FLAGS.has(body) && i + 1 < argv.length && !argv[i + 1].startsWith('--')) {
|
|
35
|
+
out.flags.set(body, argv[i + 1]);
|
|
36
|
+
i += 1;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
out.flags.set(body, 'true');
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
})();
|
|
43
|
+
const wantJson = flags.has('json');
|
|
44
|
+
|
|
45
|
+
/** --config 指定的项目:只用它的 files 列表,**不**把它的 prefix 套给别的项目文件。 */
|
|
46
|
+
function filesFromConfig(path) {
|
|
47
|
+
if (!path || !existsSync(path)) return [];
|
|
48
|
+
try {
|
|
49
|
+
const cfg = JSON.parse(readFileSync(path, 'utf8'))?.dshScopeCheck;
|
|
50
|
+
const base = dirname(resolve(path));
|
|
51
|
+
return Array.isArray(cfg?.files) ? cfg.files.map((f) => resolve(base, f)) : [];
|
|
52
|
+
} catch { return []; }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const configPath = flags.get('config') || '';
|
|
56
|
+
const targets = positional.length ? positional.map((f) => resolve(f)) : filesFromConfig(configPath);
|
|
57
|
+
if (!targets.length) {
|
|
58
|
+
console.error('用法:node scripts/check-js-scope.mjs <file.js> [...] [--prefix=dshgp_] [--allowlist=a,b] [--json]');
|
|
59
|
+
console.error(' 或 node scripts/check-js-scope.mjs --config package.json(读 dshScopeCheck.files)');
|
|
60
|
+
process.exit(2);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const topFlag = flags.get('top');
|
|
64
|
+
const result = runScopeCheck({
|
|
65
|
+
files: targets,
|
|
66
|
+
prefix: flags.get('prefix') || '',
|
|
67
|
+
// allowlist 为主名(与 git-sluice scope-check 对齐),allow 是旧写法别名
|
|
68
|
+
allowlist: String(flags.get('allowlist') || flags.get('allow') || '').split(',').map((x) => x.trim()).filter(Boolean),
|
|
69
|
+
...(topFlag === 'true' || topFlag === 'false' ? { topLevelMustBeEmpty: topFlag === 'true' } : {}),
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
if (wantJson) {
|
|
73
|
+
console.log(JSON.stringify(result, null, 2));
|
|
74
|
+
} else {
|
|
75
|
+
// 输出头自证策略来源:避免「继承了本项目默认值」被误读成对方的约定
|
|
76
|
+
for (const src of result.policySources) console.log(`策略来源:${src}`);
|
|
77
|
+
for (const r of result.reports) {
|
|
78
|
+
const rel = r.file.replace(process.cwd() + '/', '');
|
|
79
|
+
if (r.ok) {
|
|
80
|
+
console.log(`✔ ${rel}:${r.declarations.length} 个声明,无同帧重名`);
|
|
81
|
+
} else {
|
|
82
|
+
console.error(`✗ ${rel}:`);
|
|
83
|
+
for (const v of r.violations) console.error(` - ${v}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
process.exit(result.ok ? 0 : 1);
|
package/scripts/check.mjs
CHANGED
|
@@ -83,6 +83,42 @@ try {
|
|
|
83
83
|
console.error(`✗ 分片构建校验失败:${e.message}`);
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
+
// ── 拼接产物作用域门禁(2026-11-05)───────────────────────────────────
|
|
87
|
+
// 背景:lib/client-parts/*.js 是**平铺拼接**的片段,14 个分片最终落在**同一个 factory
|
|
88
|
+
// 函数作用域**里。JS 的 var/function 提升规则是「同名后者覆盖前者且不报错」——
|
|
89
|
+
// 一处重名就让某分片功能在运行时静默失效,且没有任何报错可查。
|
|
90
|
+
// 构建脚本头部早写了「顶层零声明 + dshgp_ 前缀」两条铁律,但此前**只是注释**:
|
|
91
|
+
// 新鲜度门禁只保证「产物 == 分片拼接」,保证不了「拼出来的不撞名」。
|
|
92
|
+
// 检查项(通用实现在 lib/ast/scope-collisions.js,项目差异走 package.json 的 dshScopeCheck):
|
|
93
|
+
// ① 同作用域重名(var/function 静默覆盖的触发条件,始终检查);
|
|
94
|
+
// ② 文件顶层零声明;③ 共享作用域命名前缀。
|
|
95
|
+
try {
|
|
96
|
+
const { analyzeScopeCollisions } = await import('../lib/ast/scope-collisions.js');
|
|
97
|
+
const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
|
|
98
|
+
const cfg = pkg?.dshScopeCheck;
|
|
99
|
+
const files = Array.isArray(cfg?.files) && cfg.files.length ? cfg.files : [];
|
|
100
|
+
if (!files.length) {
|
|
101
|
+
console.log('✔ 拼接产物作用域:未配置 dshScopeCheck.files,跳过');
|
|
102
|
+
}
|
|
103
|
+
for (const rel of files) {
|
|
104
|
+
const abs = join(ROOT, rel);
|
|
105
|
+
const scope = analyzeScopeCollisions(readFileSync(abs, 'utf8'), {
|
|
106
|
+
prefix: String(cfg.prefix || ''),
|
|
107
|
+
allowlist: Array.isArray(cfg.allowlist) ? cfg.allowlist.map(String) : [],
|
|
108
|
+
topLevelMustBeEmpty: cfg.topLevelMustBeEmpty !== false,
|
|
109
|
+
});
|
|
110
|
+
if (scope.ok) {
|
|
111
|
+
console.log(`✔ ${rel} 作用域契约(顶层零声明 · 共享作用域 ${scope.declarations.filter((d) => d.frameId === scope.sharedFrameId).length} 个声明均合规 · 无同帧重名)`);
|
|
112
|
+
} else {
|
|
113
|
+
fail += 1;
|
|
114
|
+
for (const v of scope.violations) console.error(`✗ ${rel} 作用域:${v}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
} catch (e) {
|
|
118
|
+
fail += 1;
|
|
119
|
+
console.error(`✗ 拼接产物作用域检查失败:${e.message}`);
|
|
120
|
+
}
|
|
121
|
+
|
|
86
122
|
// ── 层边界门禁(2026-10-24)────────────────────────────────────────────
|
|
87
123
|
// 背景:审计引擎与提交推送**决定不拆成两个 npm 包**(拆包的持续成本——双包版本同步、
|
|
88
124
|
// 固定发布顺序、依赖范围——换不到真实收益:外部使用者要的是「提交前拦截」这个整体,
|
|
@@ -92,7 +128,9 @@ try {
|
|
|
92
128
|
// 不变量:
|
|
93
129
|
// ① 审计层任何文件都不得 import git/npm/commit-push 层(方向唯一:git → audit);
|
|
94
130
|
// ② 反向接缝数量有预算上限——允许存在(提交门禁必须调审计),但要能看见它在膨胀。
|
|
95
|
-
|
|
131
|
+
// lint-adapter(外部 linter 委托层)纳入审计层口径:编排层(audit)直接依赖它 ⇒ 它属于审计子图,
|
|
132
|
+
// 同样不得伸手 git 层(委托层只读项目文件 + 跑外部二进制,不需要凭据/git)。
|
|
133
|
+
const AUDIT_DIRS = new Set(['ast', 'audit', 'audit-rules', 'checks', 'exempt', 'rule', 'score', 'lint-adapter']);
|
|
96
134
|
const GIT_DIRS = new Set(['git', 'npm']);
|
|
97
135
|
const GIT_TOP = new Set(['commit-push.js']);
|
|
98
136
|
const AUDIT_TOP = new Set(['audit-defaults.js', 'skip-dirs.js']);
|
|
@@ -11,7 +11,7 @@ generatedBy: deepseek-official/deepseek-v4-flash · EIGHTfs 2026-10-02
|
|
|
11
11
|
> 定位:把「扫描仓库 → 审计门禁 → 一键 commit+push」固化为代码管道(零 token、确定性)。
|
|
12
12
|
> 本手册是使用说明;正常情况优先直接调用插件工具。
|
|
13
13
|
|
|
14
|
-
## 一、
|
|
14
|
+
## 一、21 个工具
|
|
15
15
|
|
|
16
16
|
| 工具 | 参数 | 说明 |
|
|
17
17
|
|---|---|---|
|
|
@@ -30,7 +30,12 @@ generatedBy: deepseek-official/deepseek-v4-flash · EIGHTfs 2026-10-02
|
|
|
30
30
|
| `git_cred_env` | — | 输出凭据环境变量前缀(SSH `GIT_SSH_COMMAND` / HTTPS `GIT_ASKPASS`,不含明文) |
|
|
31
31
|
| `git_gen_ssh_key` | `email`(必填), `force?` | 生成 SSH 密钥对(写入插件配置目录;私钥不出本机,公钥整行回传) |
|
|
32
32
|
| `git_sluice` | `args`(必填) | git 命令透传(凭据自动注入;返回 status + stdout/stderr 原文) |
|
|
33
|
-
| `git_api` | `path?`, `method?`, `query?`, `body?` | **直接调用本插件
|
|
33
|
+
| `git_api` | `path?`, `method?`, `query?`, `body?` | **直接调用本插件 36 条 HTTP API**(内部走 `handleHttp` 同一条代码路径,不另写实现);不传 `path` 则列出全部接口 |
|
|
34
|
+
| `npm_publish` | `dir?`, `dryRun?`(默认 true), `tag?`, `otp?`, `confirm?`, `skipSmoke?`, `localPreview?` | npm 发包(后台 job):默认只体检 + `npm publish --dry-run`;真发必须 `confirm=true` 且 `dryRun=false`;凭据由插件托管(无需 npm login) |
|
|
35
|
+
| `npm_unpublish` | `name`(必填), `version?`, `wholePackage?`, `dryRun?`(默认 true), `confirm?` | 撤包(不可逆):默认只预检(72h 窗口 / dist-tag 悬空 / 唯一版本冷却),真撤需 `dryRun=false` + `confirm=true` |
|
|
36
|
+
| `git_remote_rename` | `repo`(必填), `newName`(必填), `dryRun?`(默认 true), `updateRemotes?` | 远程仓库改名:默认只报告旧名出现位置,确认后 `dryRun=false` 才真改并同步本地 remote |
|
|
37
|
+
| `exempt` | `action`(必填), `repo?`, `path?`, `line?`, `scope?`, `rule?`, `marker?`, `reason?` | 注释豁免:按 `rule` 推导正确标记、写前校验真生效、`check` 识别死标记 |
|
|
38
|
+
| `scope_check` | `files?`, `repo?`, `prefix?`, `allowlist?`, `topLevelMustBeEmpty?` | 拼接产物作用域撞名(按真实作用域帧):同帧重名会**后者静默顶掉前者**;`files` 空=读项目 `dshScopeCheck.files`,前缀/顶层零声明按项目契约(没声明就只查同帧重名,不拿 `dshgp_` 要求别人) |
|
|
34
39
|
|
|
35
40
|
典型流程:`git_scan` 看改动 → `code_audit` 自查 → `git_commit_push`(审计通过才推)。
|
|
36
41
|
|
|
@@ -265,6 +270,7 @@ pnpm add github:EIGHTfs/dsh-git-push#<commit>
|
|
|
265
270
|
| `git_remote_create` | **`repo`**、`visibility?`(默认 private)、`dryRun?` | 同名存在则复用,否则创建并把 origin 指向 API 地址;`ensureRemoteRepo` |
|
|
266
271
|
| `git_set_visibility` | **`repo`**、**`visibility`** | `PATCH /repos/{owner}/{repo}` 的 private 字段;改 public 前须确认无凭据暴露;`setVisibility` |
|
|
267
272
|
| `link_check` | `path?`(缺省 workspaceRoot) | 分级扣分(404/403 −3、DNS −2、超时/5xx −1,flaky 域名 ×0.2);**只 warning 永不 blocker**;并发 10;`checkLinks`/`probeLinks` |
|
|
273
|
+
| `scope_check` | `files?`(逗号分隔,空=项目 `dshScopeCheck.files`)、`repo?`、`prefix?`、`allowlist?`、`topLevelMustBeEmpty?` | 按真实作用域帧查同帧重名;判定 `analyzeScopeCollisions`(`lib/ast/scope-collisions.js`)、契约 `readProjectScopePolicy`(`lib/audit/scope-policy.js`)、执行 `runScopeCheck`(`lib/app/scope-check.js`);违规时 CLI 退出码 1 |
|
|
268
274
|
|
|
269
275
|
**接线层**(`lib/plugin/index.js`,Host 侧四段真实 API):工具 `ctx.inject(['tools'])` → `register(defineTool(spec))`(`output.render` **必须返回块数组**);提示词注入 `inject(['systemPrompt'])` → `section({name, order, text})`;HTTP `inject(['webServer'])` → `register({kind:'prefix', path, handler})`;客户端**不在此注册**(由 package.json `dsh.client` + `exports["./client"]` 自动发现)。
|
|
270
276
|
|