mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-27 14:00:22 +08:00
fix: 补丁失配判定加 drifted,宿主版本门禁与 expect 命中数契约(#188 通用部分)
从 PR #188(Pluto-Yt,fix/drift-detection)手改取通用部分落地,不含
0.2.1-rc.3 专属适配:
- 补丁失配不再静默成 skipped:文件在、marker 没有、pattern 一条都不中
→ 新增 drifted 状态(filePatchOutcome / patchStatus / rollupPatchStatus)。
以前这种情况一律返回 skipped 并被当软成功,官方一升级插件就静默失效,
状态页却全绿
- isSelfMarkedPatch() 例外:pattern 本身就是本插件写进宿主的痕迹
(#80 撤销型),找不到 = 本来没加过或已撤过,仍算 skipped
- ALWAYS_SOFT_STATUSES 去掉 skipped;skipped 改为只有可选/自标记型才算
软成功;drifted 看得见(状态页标红、不计入 ready)但不阻断 Apply,
免得把 0.1.6 / 0.2.0 / 0.2.1-rc.2 上的用户堵死
- tallyDisplayPatches / rollupDisplayStatus:drifted 压过 applied
- ensureHostClean 不再过滤 pattern_not_found:没打上就是没打上
- 宿主版本门禁:读 package.json 的 dshTarget,比对宿主真实版本,
gatherState 暴露 host_version / host_target / host_supported,
CLI 与状态页在未适配时直接告警
- applyReplacementsToText 支持 { pattern, replace, expect } 命中数契约:
命中数与声明不符就整条拒写,并回传实际命中数
- #77 锚点容错:写死 5 行改成锚首尾 + 非贪婪窗口 (?:(?!isRewindMarker)[\s\S]){0,300}?,
官方在中间插一行也照样命中;窗口排除 isRewindMarker 保证二次应用不叠加
额外修的 bug:
- rollupPatchStatus 的 lastError 提到最前:以前只在 strictFiles 分支里返回,
一个文件写成功就把别的文件 EACCES / read_error 吞成绿
- applyReplacementsToText 的 expect 契约原先只对字面量 pattern 生效,正则
分支直接 continue 掉了 —— 官方把同一段代码复制成两份时正则会把两处一起
改掉,补上正则分支的命中数检查
- patchStatus 的 drifted 计数排在 strictFiles 的 unmatched 之前:严格补丁的
文件宿主一定在,原文对不上只可能是上游漂移,报 drifted 比 unmatched 更准
- 与 PR 的有意偏差:rollupPatchStatus 里 drifted 排在 already 之后。
多文件补丁(#50/#57/#62)有个别文件本来就不含这段代码(barrel 文件),
按 PR 的顺序会把这几条从 already/applied 翻成 drifted,制造假告警
未取(0.2.1-rc.3 专属、与通用逻辑无法拆开):新增 targetFiles 键
(harness-dev-context / skill-badge)、#32/#53 扩到 rc.3 新位置、
新增 #89 SANDBOX_POLICY_BRAND_NEUTRAL 与 #90 SKILL_BADGE_DESCRIPTION_NEUTRAL
新增 test/patch-status.test.js(29 条,全量 74 条全过)
Based-on: PR #188 by Pluto-Yt
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
f79363a17e
commit
ec4c8b889f
5 files changed
+526
-38
No files matched your search
+7
-2
@@ -24,10 +24,15 @@ function printStatus(state) {
|
||||
out.push(` 注入文件 ${state.override_path}`);
|
||||
out.push(` 注入状态 ${state.override_status}`);
|
||||
out.push("");
|
||||
out.push(` 补丁 ${state.patches_applied}/${core.ALL_PATCHES.length} 已清洗, ${state.patches_pending} 待清洗`);
|
||||
out.push(` 补丁 ${state.patches_applied}/${core.ALL_PATCHES.length} 已清洗, ${state.patches_pending} 待清洗`
|
||||
+ (state.patches_drifted ? `, ${state.patches_drifted} 漂移(官方原文已改,需更新 pattern)` : ""));
|
||||
if (state.host_version) {
|
||||
const compat = state.host_supported === false ? ` ← 未适配:插件声明 ${state.host_target || "?"}` : "";
|
||||
out.push(` 宿主版本 / host ${state.host_version}${compat}`);
|
||||
}
|
||||
for (const p of core.ALL_PATCHES) {
|
||||
const s = state.patch_status[p.id];
|
||||
const mark = s === "applied" ? "✓" : s === "pending" ? "✗" : "·";
|
||||
const mark = s === "applied" ? "✓" : s === "pending" ? "✗" : s === "drifted" ? "!" : "·";
|
||||
out.push(` ${mark} [#${String(p.id).padEnd(2)}] ${p.name.padEnd(30)} ${p.layer}/${p.layer_en} — ${s}`);
|
||||
}
|
||||
out.push("");
|
||||
|
||||
@@ -183,6 +183,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"metric.purged.skip": "已写入。跳过 {n} 项,本机没有这些文件",
|
||||
"metric.pendingShort": "待处理 {n}",
|
||||
"metric.unmatchedShort": "没对上 {n}",
|
||||
"metric.driftedShort": "漂移 {n}",
|
||||
"metric.skipShort": "跳过 {n}",
|
||||
"metric.unlocated.count": "—",
|
||||
"metric.shim": "shim",
|
||||
@@ -196,8 +197,9 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"status.off": "已关闭",
|
||||
"status.pending": "待应用",
|
||||
"status.unmatched": "没对上",
|
||||
"status.drifted": "已漂移",
|
||||
"status.skipped": "跳过",
|
||||
"apply.hint": "没改提示词框不用点保存,默认就是这份,启动和应用会写进 prompt-inject.md。只有自己改过再点保存才会覆盖。点应用打补丁。待应用=原文还在。跳过=当前版本不需要或组件未安装。",
|
||||
"apply.hint": "没改提示词框不用点保存,默认就是这份,启动和应用会写进 prompt-inject.md。只有自己改过再点保存才会覆盖。点应用打补丁。待应用=原文还在。跳过=当前版本不需要或组件未安装。漂移=官方原文已改,这条补丁没打上,需要更新 pattern。",
|
||||
"flow.title": "清洗流程",
|
||||
"flow.apply": "应用",
|
||||
"flow.revert": "还原",
|
||||
@@ -217,6 +219,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"unpack.restarting": "补丁已写入。点「重启」后客户端会自己重新打开。",
|
||||
"restart.fullQuit": "正在重启,客户端会自己重新打开。",
|
||||
"warn.noInject": "官方始终用默认提示词。红队开了规则集就只用规则集;没开时用去掉 CTF 的默认提示词,再接红队操作。两边都空会提示必须添加。",
|
||||
"warn.hostVersion": "当前宿主是 {v},插件适配的是 {t}。官方原文对不上时补丁会显示「漂移」,建议换回适配的宿主版本。",
|
||||
"need.prompt": "提示词和规则集都是空的,必须先添加提示词,或启用一条有内容的规则集。",
|
||||
"btn.restoreInject": "恢复默认",
|
||||
"saved.restoreInject": "已恢复默认提示词",
|
||||
@@ -541,6 +544,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"metric.purged.skip": "Written. Skipped {n}; those files are not on this install",
|
||||
"metric.pendingShort": "Pending {n}",
|
||||
"metric.unmatchedShort": "No match {n}",
|
||||
"metric.driftedShort": "Drifted {n}",
|
||||
"metric.skipShort": "Skipped {n}",
|
||||
"metric.unlocated.count": "—",
|
||||
"metric.shim": "shim",
|
||||
@@ -554,8 +558,9 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"status.off": "Off",
|
||||
"status.pending": "Pending",
|
||||
"status.unmatched": "No match",
|
||||
"status.drifted": "Drifted",
|
||||
"status.skipped": "Skipped",
|
||||
"apply.hint": "If you did not edit the prompt box, do not save. The default is already used and is written to prompt-inject.md on start/apply. Save only after you change it. Apply writes host patches. Pending = original text still present. Skipped = not needed for this version or the component is not installed.",
|
||||
"apply.hint": "If you did not edit the prompt box, do not save. The default is already used and is written to prompt-inject.md on start/apply. Save only after you change it. Apply writes host patches. Pending = original text still present. Skipped = not needed for this version or the component is not installed. Drifted = the official source changed, this patch did not land and its pattern needs an update.",
|
||||
"flow.title": "Clean flow",
|
||||
"flow.apply": "Apply",
|
||||
"flow.revert": "Restore",
|
||||
@@ -575,6 +580,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => {
|
||||
"unpack.restarting": "Patches are written. Click Restart and the client opens again by itself.",
|
||||
"restart.fullQuit": "Restarting. The client will open again by itself.",
|
||||
"warn.noInject": "Official mode always uses the default prompt. Red team uses only the active rule set; otherwise it uses the default prompt without the CTF section, then the red team steps. If both are empty you will be asked to add a prompt.",
|
||||
"warn.hostVersion": "This host is {v}, but the plugin targets {t}. When the official source no longer matches, patches show up as “drifted” — switch back to the targeted host version.",
|
||||
"need.prompt": "Both the prompt and the rule set are empty. Add a prompt, or enable a rule that has content.",
|
||||
"btn.restoreInject": "Reset default",
|
||||
"saved.restoreInject": "Default prompt restored",
|
||||
@@ -1152,6 +1158,7 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
if (st === "applied" || st === "already") return "ok";
|
||||
if (st === "pending") return "wait";
|
||||
if (st === "unmatched") return "bad";
|
||||
if (st === "drifted") return "bad";
|
||||
if (st === "na") return "ok";
|
||||
if (st === "missing_file" || st === "skipped" || st === "unlocated" || st === "off") return "miss";
|
||||
return "bad";
|
||||
@@ -1162,6 +1169,7 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
if (st === "off") return t("status.skipped");
|
||||
if (st === "pending") return t("status.pending");
|
||||
if (st === "unmatched") return t("status.unmatched");
|
||||
if (st === "drifted") return t("status.drifted");
|
||||
if (st === "skipped") return t("status.skipped");
|
||||
if (st === "missing_file") return t("skip");
|
||||
if (st === "unlocated") return t("status.unlocated");
|
||||
@@ -1298,12 +1306,13 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
}
|
||||
|
||||
function tallyPatches(rows) {
|
||||
const out = { applied: 0, pending: 0, unmatched: 0, skipped: 0, total: 0 };
|
||||
const out = { applied: 0, pending: 0, unmatched: 0, skipped: 0, drifted: 0, total: 0 };
|
||||
for (const row of rows || []) {
|
||||
out.total += 1;
|
||||
if (row.st === "applied" || row.st === "already") out.applied += 1;
|
||||
else if (row.st === "pending") out.pending += 1;
|
||||
else if (row.st === "unmatched") out.unmatched += 1;
|
||||
else if (row.st === "drifted") out.drifted += 1;
|
||||
else out.skipped += 1;
|
||||
}
|
||||
return out;
|
||||
@@ -1328,6 +1337,7 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
const notes = [];
|
||||
if (tally.pending) notes.push(t("metric.pendingShort", { n: tally.pending }));
|
||||
if (tally.unmatched) notes.push(t("metric.unmatchedShort", { n: tally.unmatched }));
|
||||
if (tally.drifted) notes.push(t("metric.driftedShort", { n: tally.drifted }));
|
||||
if (tally.skipped) notes.push(t("metric.skipShort", { n: tally.skipped }));
|
||||
const expanded = !!open[key];
|
||||
return h("div", { key: key, className: "dshp-group" },
|
||||
@@ -2041,7 +2051,7 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
const desktopLikely = hostSurface === "desktop" || clientGuessSurface() === "desktop";
|
||||
const sealedReady = !located && desktopLikely && !!(s && (s.asar_still_sealed || s.desktop_exe || s.desktop_install));
|
||||
const patchesLost = !located && !!(s && s.patches_lost);
|
||||
const tally = located ? tallyPatches(patchRowsOf(s)) : { applied: 0, pending: 0, unmatched: 0, skipped: 0, total: 0 };
|
||||
const tally = located ? tallyPatches(patchRowsOf(s)) : { applied: 0, pending: 0, unmatched: 0, skipped: 0, drifted: 0, total: 0 };
|
||||
const total = tally.total;
|
||||
const applied = tally.applied;
|
||||
const job = s && s.apply_progress;
|
||||
@@ -2054,6 +2064,7 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
const metricNotes = [];
|
||||
if (tally.pending) metricNotes.push(t("metric.pendingShort", { n: tally.pending }));
|
||||
if (tally.unmatched) metricNotes.push(t("metric.unmatchedShort", { n: tally.unmatched }));
|
||||
if (tally.drifted) metricNotes.push(t("metric.driftedShort", { n: tally.drifted }));
|
||||
if (tally.skipped) metricNotes.push(t("metric.skipShort", { n: tally.skipped }));
|
||||
|
||||
const versions = (updateInfo && updateInfo.versions) || [];
|
||||
@@ -2189,6 +2200,7 @@ body[data-ds-dark-theme] .dshp-launch{background:color-mix(in srgb,var(--dsw-ali
|
||||
h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-mute)", fontSize: 12 } }, t("apply.hint")),
|
||||
s && !s.ai_base ? h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-danger, #c44)", fontSize: 12 } }, hostText(t, "warn.noRoot", hostSurface)) : null,
|
||||
s && s.ai_base && s.override_status === "missing" ? h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-mute)", fontSize: 12 } }, t("warn.noInject")) : null,
|
||||
s && s.ai_base && s.host_supported === false ? h("p", { className: "dshp-hint", style: { margin: "8px 0 0", color: "var(--dshp-danger, #c44)", fontSize: 12 } }, t("warn.hostVersion", { v: s.host_version || "?", t: s.host_target || "?" })) : null,
|
||||
askRestart ? h(RestartAsk, {
|
||||
t: t,
|
||||
theme: detectHostTheme(),
|
||||
|
||||
+235
-30
@@ -2304,7 +2304,9 @@ export async function ensureHostClean() {
|
||||
await patchAllShims();
|
||||
const summary = summarizeApplyReport(multi.report);
|
||||
pending = await pendingAcross(allHosts.map((h) => h.aiBase));
|
||||
const blocking = summary.failed.filter((row) => row.status !== "pattern_not_found");
|
||||
// 失败就是失败:pattern_not_found 同样是"没打上",以前被过滤掉,
|
||||
// 于是宿主半打状态照样重启,用户只看到一片绿。现在一律当阻断项。
|
||||
const blocking = summary.failed;
|
||||
const flashOk = allHosts.every((h) => h.flash?.ok === true);
|
||||
if (pending.length || blocking.length || !flashOk) {
|
||||
return {
|
||||
@@ -5148,22 +5150,24 @@ const NEW_TOOL_PATCHES = [
|
||||
skipIfMarked: true,
|
||||
replacements: [
|
||||
{
|
||||
// 不再写死整段 5 行:官方在中间加一行就整条失配
|
||||
// (0.2.1-rc.2 起是 if (this.revised.size > 0) this.revised.clear();,
|
||||
// 0.2.1-rc.3 又改了一次)。
|
||||
// 这里只锚方法头、event 取值、去重判断和结尾的 set,中间用非贪婪窗口吃掉,
|
||||
// 窗口内容原样搬回去 —— 官方再往里加行也不影响。
|
||||
// 窗口里排除 isRewindMarker:打过一次之后正文里就有这个词,
|
||||
// 再不排除的话第二次 apply 会把注入块再插一遍(历史事故:每次 apply 越滚越长)。
|
||||
pattern:
|
||||
"\t\t\tappend(record) {\n" +
|
||||
"\t\t\t\tconst event = record.event;\n" +
|
||||
"\t\t\t\tif (this.inputs.has(event.seq)) return \"none\";\n" +
|
||||
"\t\t\t\tthis.revised.clear();\n" +
|
||||
"\t\t\t\tthis.inputs.set(event.seq, record);\n",
|
||||
/(\t*)append\(record\) \{\n(\t*)const event = record\.event;\n(\t*)if \(this\.inputs\.has\(event\.seq\)\) return "none";\n((?:(?!isRewindMarker)[\s\S]){0,300}?)(\t*)this\.inputs\.set\(event\.seq, record\);\n/g,
|
||||
replace:
|
||||
"\t\t\tappend(record) {\n" +
|
||||
"\t\t\t\tconst event = record.event;\n" +
|
||||
"\t\t\t\tif (this.inputs.has(event.seq)) return \"none\";\n" +
|
||||
"\t\t\t\tif (isRewindMarker(event)) {\n" +
|
||||
"\t\t\t\t\tconst entries = [...this.inputs.values(), record];\n" +
|
||||
"\t\t\t\t\treturn this.replaceWindow(entries, this.hasMore); // [dsh-purge] rewind drops sent messages in this conversation\n" +
|
||||
"\t\t\t\t}\n" +
|
||||
"\t\t\t\tthis.revised.clear();\n" +
|
||||
"\t\t\t\tthis.inputs.set(event.seq, record);\n",
|
||||
"$1append(record) {\n" +
|
||||
"$2const event = record.event;\n" +
|
||||
"$3if (this.inputs.has(event.seq)) return \"none\";\n" +
|
||||
"$3if (isRewindMarker(event)) {\n" +
|
||||
"$3\tconst entries = [...this.inputs.values(), record];\n" +
|
||||
"$3\treturn this.replaceWindow(entries, this.hasMore); // [dsh-purge] rewind drops sent messages in this conversation\n" +
|
||||
"$3}\n" +
|
||||
"$4$5this.inputs.set(event.seq, record);\n",
|
||||
},
|
||||
],
|
||||
markers: ["[dsh-purge] rewind drops sent messages in this conversation"],
|
||||
@@ -5863,6 +5867,8 @@ export function rollupDisplayStatus(statuses) {
|
||||
if (list.length === 0) return "skipped";
|
||||
if (list.some((s) => s === "pending")) return "pending";
|
||||
if (list.some((s) => s === "unmatched")) return "unmatched";
|
||||
// 漂移压过"已完成":一组里只要有一条对不上官方原文,这组就不是干净的。
|
||||
if (list.some((s) => s === "drifted")) return "drifted";
|
||||
if (list.every((s) => DISPLAY_SKIP.has(s))) return "skipped";
|
||||
if (list.some((s) => DISPLAY_DONE.has(s))) return "applied";
|
||||
return "skipped";
|
||||
@@ -5895,7 +5901,7 @@ export function groupPatchesForDisplay(patches = ALL_PATCHES, patch_status = {},
|
||||
}
|
||||
|
||||
export function tallyDisplayPatches(rows) {
|
||||
const out = { applied: 0, pending: 0, unmatched: 0, skipped: 0, total: 0, ready: 0 };
|
||||
const out = { applied: 0, pending: 0, unmatched: 0, skipped: 0, drifted: 0, total: 0, ready: 0 };
|
||||
for (const row of rows || []) {
|
||||
const st = row.status || row.st;
|
||||
out.total += 1;
|
||||
@@ -5904,7 +5910,10 @@ export function tallyDisplayPatches(rows) {
|
||||
out.ready += 1;
|
||||
} else if (st === "pending") out.pending += 1;
|
||||
else if (st === "unmatched") out.unmatched += 1;
|
||||
else {
|
||||
else if (st === "drifted") {
|
||||
// 漂移不算就绪:这正是"看起来全绿、实际没打上"的来源。
|
||||
out.drifted += 1;
|
||||
} else {
|
||||
out.skipped += 1;
|
||||
out.ready += 1;
|
||||
}
|
||||
@@ -6278,6 +6287,83 @@ function packageRootFromAiBase(aiBase) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 宿主版本门禁
|
||||
* 补丁全部靠字面量匹配官方源码,宿主一升级就可能整段失配。这里把"宿主到底是哪个
|
||||
* 版本、我这套 pattern 声明适配哪个版本"变成可比较的事实,供状态页/CLI 直接告警。
|
||||
*/
|
||||
|
||||
/** package.json 里声明的适配版本(唯一的真值来源,历史上前端从未读过它)。 */
|
||||
export const HOST_TARGET = (() => {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
||||
return typeof pkg.dshTarget === "string" ? pkg.dshTarget : "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
})();
|
||||
|
||||
/** "0.2.1-rc.3" → 可比较结构;解析不了返回 null。 */
|
||||
export function parseHostVersion(raw) {
|
||||
const m = String(raw ?? "").trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);
|
||||
if (!m) return null;
|
||||
return {
|
||||
major: Number(m[1]),
|
||||
minor: Number(m[2]),
|
||||
patch: Number(m[3]),
|
||||
pre: m[4] ? m[4].split(".") : [],
|
||||
};
|
||||
}
|
||||
|
||||
/** 这份 package.json 是不是官方宿主自己的?(别把本插件当成宿主) */
|
||||
function looksLikeHostPackage(pkg) {
|
||||
if (!pkg || typeof pkg.version !== "string" || !pkg.version) return false;
|
||||
const name = String(pkg.name || "");
|
||||
if (!name) return false;
|
||||
if (/purge/i.test(name)) return false;
|
||||
return /dsh|deepseek/i.test(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读宿主真实版本。npm 布局里宿主包是 <dsh>/package.json,桌面解包布局同理;
|
||||
* 源码仓库布局(packages/bundle/base)则看版本根的 package.json。
|
||||
*/
|
||||
export function readHostVersion(aiBase) {
|
||||
if (!aiBase) return null;
|
||||
const candidates = [
|
||||
path.join(aiBase, "dsh", "package.json"),
|
||||
path.resolve(aiBase, "..", "..", "package.json"),
|
||||
];
|
||||
const root = packageRootFromAiBase(aiBase);
|
||||
if (root) candidates.push(path.join(root, "package.json"));
|
||||
for (const fp of candidates) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(fp, "utf8"));
|
||||
if (looksLikeHostPackage(pkg)) {
|
||||
return { version: pkg.version, name: String(pkg.name || ""), path: fp };
|
||||
}
|
||||
} catch {
|
||||
/* 换下一个候选 */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比对宿主版本与 dshTarget。
|
||||
* ok === false 表示宿主已经跑在插件自己声明不适配的版本上 —— 此时仍允许 apply,
|
||||
* 但必须让用户看见,而不是靠补丁静默失效去发现。
|
||||
*/
|
||||
export function hostCompat(aiBase, target = HOST_TARGET) {
|
||||
const host = readHostVersion(aiBase);
|
||||
if (!host || !target) return { known: false, ok: null, host: host?.version ?? "", target, path: host?.path ?? "" };
|
||||
const a = parseHostVersion(host.version);
|
||||
const b = parseHostVersion(target);
|
||||
if (!a || !b) return { known: false, ok: null, host: host.version, target, path: host.path };
|
||||
const ok = a.major === b.major && a.minor === b.minor && a.patch === b.patch
|
||||
&& a.pre.join(".") === b.pre.join(".");
|
||||
return { known: true, ok, host: host.version, target, path: host.path };
|
||||
}
|
||||
|
||||
function filterTargetFiles(files) {
|
||||
const out = {};
|
||||
for (const [key, val] of Object.entries(files)) {
|
||||
@@ -6848,11 +6934,15 @@ function filePatchSettled(text, patch, fp = "") {
|
||||
return false;
|
||||
}
|
||||
|
||||
function filePatchOutcome(text, patch, fp = "") {
|
||||
export function filePatchOutcome(text, patch, fp = "") {
|
||||
if (filePatchSettled(text, patch, fp)) return "applied";
|
||||
if (patchHasRemainingWork(text, patch, fp)) return "pending";
|
||||
// 原文对不上、再点应用也变不了:可选/布局软补丁显示跳过,不再假装待应用。
|
||||
return "skipped";
|
||||
// 走到这里:文件在、marker 没有、pattern 一条都不中。
|
||||
// pattern 本身就是本插件写进宿主的痕迹(撤销型补丁)→ 本来就没加过,正常,算不用做;
|
||||
// 否则就是官方原文已被改写或搬走 = 上游漂移。以前这种情况一律返回 "skipped"
|
||||
// 并被当成软成功,导致官方升级后插件静默失效、界面却全绿。
|
||||
if (isSelfMarkedPatch(patch)) return "skipped";
|
||||
return "drifted";
|
||||
}
|
||||
|
||||
function fileKeysOf(p) {
|
||||
@@ -6878,6 +6968,22 @@ function patchReplacements(p) {
|
||||
return (p.patterns ?? []).map((pat) => ({ pattern: pat, replace: p.replace }));
|
||||
}
|
||||
|
||||
/**
|
||||
* pattern 全部是本插件自己写进宿主的痕迹 —— 撤销型/注入型补丁(例如 #80 要撤掉的
|
||||
* "# [dsh-purge] minimal fs tool parity")。这类 pattern 找不到 = 本来就没加过或已撤过,
|
||||
* 属正常,不能算上游漂移;否则每次 apply 都要在状态页刷一堆假告警。
|
||||
*/
|
||||
export function isSelfMarkedPatch(p) {
|
||||
if (!p) return false;
|
||||
const reps = patchReplacements(p);
|
||||
if (!Array.isArray(reps) || reps.length === 0) return false;
|
||||
return reps.every(({ pattern }) => {
|
||||
if (!pattern) return false;
|
||||
const needle = asLf(String(pattern));
|
||||
return needle.includes("[dsh-purge]") || needle.includes("# dsh-purge");
|
||||
});
|
||||
}
|
||||
|
||||
function isBareIdentityNeedle(pattern) {
|
||||
const needle = asLf(pattern);
|
||||
if (!needle) return false;
|
||||
@@ -6940,13 +7046,32 @@ export function applyReplacementsToText(text, patch, fp = "") {
|
||||
const yaml = isYamlPath(fp);
|
||||
let out = asLf(source);
|
||||
let changed = false;
|
||||
for (const { pattern, replace } of patchReplacements(patch)) {
|
||||
for (const rep of patchReplacements(patch)) {
|
||||
const { pattern, replace } = rep;
|
||||
if (!pattern || typeof replace !== "string") continue;
|
||||
// YAML 块标量行首有缩进;无缩进 identity+\n\n 会留下 6 空格,再和下一段拼成 12 空格。
|
||||
if (yaml && isBareIdentityNeedle(pattern)) continue;
|
||||
const written = yaml ? yamlJsCommentsToHash(asLf(replace)) : asLf(replace);
|
||||
// 正则 pattern:用于自匹配型替换(产物包含原 pattern,如 timeoutMs 追加 0)。
|
||||
if (pattern instanceof RegExp) {
|
||||
// 命中数契约对正则同样生效:官方把同一段代码复制成两份时,
|
||||
// 正则会把两处一起改掉 —— 命中数与声明不符就整条拒写。
|
||||
// 0 次命中同样算不符(expect=1 就是"这里必须有一处")。
|
||||
if (typeof rep.expect === "number") {
|
||||
const hits = (out.match(cloneRegExp(pattern, true)) || []).length;
|
||||
if (hits !== rep.expect) {
|
||||
return {
|
||||
text: source,
|
||||
changed: preChanged,
|
||||
hitMismatch: {
|
||||
patch_id: patch?.id,
|
||||
expected: rep.expect,
|
||||
actual: hits,
|
||||
file: fp,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
const re = cloneRegExp(pattern, true);
|
||||
re.lastIndex = 0;
|
||||
if (!re.test(out)) continue;
|
||||
@@ -6959,6 +7084,25 @@ export function applyReplacementsToText(text, patch, fp = "") {
|
||||
continue;
|
||||
}
|
||||
const needle = asLf(pattern);
|
||||
// 命中数契约:补丁显式声明 expect 时,命中数必须完全一致才允许写。
|
||||
// 它同时是"上游又改了"的探针 —— 官方多一处/少一处同名代码都能当场暴露,
|
||||
// 而不是安静地把不相干的第二处一起改掉(split/join 是无上限全量替换)。
|
||||
// 命中 0 次也要算不符:expect=1 就是"这里必须有一处"。
|
||||
if (typeof rep.expect === "number") {
|
||||
const hits = needle ? out.split(needle).length - 1 : 0;
|
||||
if (hits !== rep.expect) {
|
||||
return {
|
||||
text: source,
|
||||
changed: preChanged,
|
||||
hitMismatch: {
|
||||
patch_id: patch?.id,
|
||||
expected: rep.expect,
|
||||
actual: hits,
|
||||
file: fp,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
if (!out.includes(needle)) continue;
|
||||
const next = out.split(needle).join(written);
|
||||
if (next === out) continue;
|
||||
@@ -6969,19 +7113,30 @@ export function applyReplacementsToText(text, patch, fp = "") {
|
||||
return { text: out, changed: changed || preChanged };
|
||||
}
|
||||
|
||||
function rollupPatchStatus({ applied, already, missing, notFound, lastError, keyCount, layoutSoft, strictFiles }) {
|
||||
if (strictFiles && lastError) return lastError;
|
||||
if (strictFiles && notFound > 0) return "pattern_not_found";
|
||||
if (applied > 0) return "applied";
|
||||
if (already > 0 && (notFound === 0 || layoutSoft)) return "already";
|
||||
if (missing === keyCount) return "missing_file";
|
||||
export function rollupPatchStatus({
|
||||
applied, already, missing, notFound, drifted = 0, lastError, keyCount, layoutSoft, strictFiles,
|
||||
}) {
|
||||
// 写错误优先:以前只在 strictFiles 分支里返回,一个文件写成功就把 EACCES 吞成了绿。
|
||||
if (lastError) return lastError;
|
||||
if (strictFiles && notFound > 0) return "pattern_not_found";
|
||||
// 只要有一个文件真的写入,就还算打上了;多文件补丁里个别文件本来就不含这段代码,
|
||||
// 不能因为那种文件报成"半打"而制造假告警。
|
||||
if (applied > 0) return "applied";
|
||||
// 已经落盘过的补丁同理:只剩"这一份文件本来就没有这段代码"时不算漂移。
|
||||
if (already > 0 && (notFound === 0 || layoutSoft)) return "already";
|
||||
// 所有文件都对不上官方原文、也没有本插件留下的痕迹 = 补丁整体漂移。
|
||||
// 以前这种情况会掉进 notFound===0 的分支被当成 skipped(软成功),
|
||||
// 于是官方升级后插件静默失效、状态页全绿 —— 判据在这里被掰正。
|
||||
if (drifted > 0) return "drifted";
|
||||
if (missing === keyCount) return "missing_file";
|
||||
// 文件在,但这份原文不在:列表里本来就是跳过,不能再把整次应用判失败。
|
||||
if (notFound === 0) return "skipped";
|
||||
return "pattern_not_found";
|
||||
}
|
||||
|
||||
const ALWAYS_SOFT_STATUSES = new Set(["applied", "already", "missing_file", "skipped", "na", "off"]);
|
||||
// 注意:skipped 已从软成功里摘掉 —— 它是"pattern 原文对不上"的旧落点,
|
||||
// 现在这类情况会走 drifted,skipped 只留给真正无需处理的边角。
|
||||
const ALWAYS_SOFT_STATUSES = new Set(["applied", "already", "missing_file", "na", "off"]);
|
||||
|
||||
export function patchAppliesHere(patch, surface = detectSurface()) {
|
||||
const want = patch?.surfaces;
|
||||
@@ -6998,6 +7153,12 @@ export function isPatchResultSoftOk(row, patch = null) {
|
||||
if (p?.strictFiles && row.status === "pattern_not_found") return false;
|
||||
if (p?.optional && row.status === "pattern_not_found") return true;
|
||||
if (isLayoutSoftPatch(p) && row.status === "pattern_not_found") return true;
|
||||
// skipped 不再天然软成功:只有"可选补丁"或"自标记型(撤销型)补丁"才算当前版本不需要。
|
||||
if (row.status === "skipped") return p?.optional === true || isSelfMarkedPatch(p);
|
||||
// 漂移必须让用户看见(状态页标红、不计入就绪),但不阻断 Apply:
|
||||
// 官方宿主上被更老版本插件打过一遍的补丁,marker 文案对不上就会被误判成漂移,
|
||||
// 拿它去阻断重启会直接把 0.1.6 / 0.2.0 / 0.2.1-rc.2 上的用户堵死。
|
||||
if (row.status === "drifted") return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -7111,6 +7272,8 @@ export async function applyPatches(aiBase, patches = ALL_PATCHES, options = {})
|
||||
let already = 0;
|
||||
let missing = 0;
|
||||
let notFound = 0;
|
||||
let drifted = 0;
|
||||
let selfMarked = 0;
|
||||
let lastError = null;
|
||||
for (const key of keys) {
|
||||
const fps = pathsOf(files, key);
|
||||
@@ -7131,9 +7294,17 @@ export async function applyPatches(aiBase, patches = ALL_PATCHES, options = {})
|
||||
if (preserveClientBundles && isWatchedClientBundle(fp)) {
|
||||
if (filePatchSettled(text, p, fp)) already += 1;
|
||||
else if (patchHasRemainingWork(text, p, fp) || p.strictFiles) notFound += 1;
|
||||
else if (isSelfMarkedPatch(p)) selfMarked += 1;
|
||||
else drifted += 1;
|
||||
continue;
|
||||
}
|
||||
const appliedText = applyReplacementsToText(text, p, fp);
|
||||
// 命中数与补丁声明不符:官方同名代码多了一处/少了一处,宁可整条拒写也不猜。
|
||||
if (appliedText.hitMismatch) {
|
||||
const mm = appliedText.hitMismatch;
|
||||
lastError = `hit_count_mismatch:#${mm.patch_id}:${mm.actual}/${mm.expected}`;
|
||||
continue;
|
||||
}
|
||||
let textOut = appliedText.text;
|
||||
let changed = appliedText.changed;
|
||||
if (isYamlPath(fp)) {
|
||||
@@ -7157,11 +7328,20 @@ export async function applyPatches(aiBase, patches = ALL_PATCHES, options = {})
|
||||
already += 1;
|
||||
} else if (patchHasRemainingWork(text, p, fp) || p.strictFiles) {
|
||||
notFound += 1;
|
||||
} else if (isSelfMarkedPatch(p)) {
|
||||
// pattern 本身是本插件写进宿主的内容(撤销型/注入型补丁,例如 #80 的
|
||||
// "# [dsh-purge] minimal fs tool parity"):它不在 = 本来没加过或已经撤过,
|
||||
// 属于正常,不能当成上游漂移。
|
||||
selfMarked += 1;
|
||||
} else {
|
||||
// 文件在、marker 没有、pattern 一条都不中 —— 官方原文已经被改写或搬走。
|
||||
// 这是必须让用户看见的漂移,不能落进 skipped 软成功。
|
||||
drifted += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
const status = rollupPatchStatus({
|
||||
applied, already, missing, notFound, lastError, keyCount: keys.length,
|
||||
applied, already, missing, notFound, drifted, lastError, keyCount: keys.length,
|
||||
layoutSoft: isLayoutSoftPatch(p),
|
||||
strictFiles: !!p.strictFiles,
|
||||
});
|
||||
@@ -7173,6 +7353,8 @@ export async function applyPatches(aiBase, patches = ALL_PATCHES, options = {})
|
||||
applied,
|
||||
already,
|
||||
missing,
|
||||
drifted,
|
||||
self_marked: selfMarked,
|
||||
});
|
||||
}
|
||||
return report;
|
||||
@@ -7196,6 +7378,8 @@ export function patchWatchedClientBundlesSync(aiBase = findAiBase()) {
|
||||
try {
|
||||
const text = fs.readFileSync(fp, "utf8");
|
||||
const appliedText = applyReplacementsToText(text, p, fp);
|
||||
// 命中数对不上:宁可不写,也不把不相干的第二处一起改掉。
|
||||
if (appliedText.hitMismatch) continue;
|
||||
if (!appliedText.changed) continue;
|
||||
const next = Buffer.from(appliedText.text, "utf8");
|
||||
const current = fs.readFileSync(fp);
|
||||
@@ -7228,6 +7412,7 @@ export async function patchStatus(aiBase, patches = ALL_PATCHES) {
|
||||
let skipped = 0;
|
||||
let unmatched = 0;
|
||||
let missing = 0;
|
||||
let drifted = 0;
|
||||
for (const key of keys) {
|
||||
const fps = pathsOf(files, key);
|
||||
if (fps.length === 0) {
|
||||
@@ -7245,12 +7430,16 @@ export async function patchStatus(aiBase, patches = ALL_PATCHES) {
|
||||
const outcome = filePatchOutcome(text, p, fp);
|
||||
if (outcome === "applied") applied += 1;
|
||||
else if (outcome === "pending") pending += 1;
|
||||
// 漂移优先于严格补丁口径:严格补丁的文件宿主一定在,原文对不上
|
||||
// 只可能是官方改了文案(= 上游漂移),报 drifted 比报 unmatched 更有指向性。
|
||||
else if (outcome === "drifted") drifted += 1;
|
||||
else if (p.strictFiles) unmatched += 1;
|
||||
else skipped += 1;
|
||||
}
|
||||
}
|
||||
if (pending > 0) status[p.id] = "pending";
|
||||
else if (applied > 0) status[p.id] = "applied";
|
||||
else if (drifted > 0) status[p.id] = "drifted";
|
||||
else if (unmatched > 0) status[p.id] = "unmatched";
|
||||
else if (skipped > 0) status[p.id] = "skipped";
|
||||
else status[p.id] = p.optional ? "na" : "missing_file";
|
||||
@@ -8108,8 +8297,12 @@ export function editOverride(dshHome) {
|
||||
/** 列表上的“已就绪”:已写入、或当前版本不需要 / 组件未装(与 apply 的 soft-ok 对齐)。 */
|
||||
export function patchStatusReady(status, patch = null) {
|
||||
if (status === "applied" || status === "already" || status === "off") return true;
|
||||
if (status === "skipped" || status === "missing_file") return true;
|
||||
if (status === "missing_file") return true;
|
||||
if (status === "na") return false;
|
||||
// 上游漂移:可选补丁不阻断"已就绪",但状态本身会在列表里标出来,不再被当成做完了。
|
||||
if (status === "drifted") return patch?.optional === true;
|
||||
// skipped 不再天然就绪:只有可选补丁(或自标记型撤销补丁)才算"当前版本不需要"。
|
||||
if (status === "skipped") return patch?.optional === true || isSelfMarkedPatch(patch);
|
||||
if (status === "pattern_not_found" && patch?.strictFiles) return false;
|
||||
if (status === "pattern_not_found" && patch?.optional) return true;
|
||||
return false;
|
||||
@@ -8120,11 +8313,16 @@ export async function gatherState() {
|
||||
const aiBase = findAiBase();
|
||||
const shimDir = findShimDir();
|
||||
const desktop_runtimes = listDesktopCommandRuntimeDirs();
|
||||
const hostInfo = aiBase
|
||||
? hostCompat(aiBase)
|
||||
: { known: false, ok: null, host: "", target: HOST_TARGET };
|
||||
const host_version = hostInfo.host || "";
|
||||
const files = aiBase ? targetFiles(aiBase) : {};
|
||||
const patch_status = aiBase ? await patchStatus(aiBase) : {};
|
||||
let patches_applied = 0;
|
||||
let patches_pending = 0;
|
||||
let patches_skipped = 0;
|
||||
let patches_drifted = 0;
|
||||
let patches_ready = 0;
|
||||
let patches_na = 0;
|
||||
let patches_total = 0;
|
||||
@@ -8142,6 +8340,7 @@ export async function gatherState() {
|
||||
patches_total += 1;
|
||||
if (s === "applied") patches_applied += 1;
|
||||
if (s === "pending") patches_pending += 1;
|
||||
if (s === "drifted") patches_drifted += 1;
|
||||
if (s === "skipped" || s === "missing_file" || s === "off") patches_skipped += 1;
|
||||
if (patchStatusReady(s, p)) patches_ready += 1;
|
||||
}
|
||||
@@ -8182,13 +8381,19 @@ export async function gatherState() {
|
||||
patches_applied,
|
||||
patches_pending,
|
||||
patches_skipped,
|
||||
patches_drifted,
|
||||
patches_ready,
|
||||
patches_na,
|
||||
patches_total,
|
||||
host_version,
|
||||
host_target: hostInfo.target || "",
|
||||
host_supported: hostInfo.ok !== false,
|
||||
host_compat_known: hostInfo.known === true,
|
||||
display_patches,
|
||||
display_applied: displayTally.applied,
|
||||
display_pending: displayTally.pending,
|
||||
display_skipped: displayTally.skipped,
|
||||
display_drifted: displayTally.drifted ?? 0,
|
||||
display_ready: displayTally.ready,
|
||||
display_total: displayTally.total,
|
||||
has_backup: aiBase ? await hasBackup(aiBase) : false,
|
||||
|
||||
+14
-2
@@ -164,10 +164,18 @@ function renderStatus(state) {
|
||||
? state.display_patches
|
||||
: core.groupPatchesForDisplay(core.ALL_PATCHES, state.patch_status || {});
|
||||
const displayTally = core.tallyDisplayPatches(displayRows);
|
||||
out.push(`补丁 / patches: ${displayTally.applied}/${displayTally.total || 0} applied, ${displayTally.pending} pending`);
|
||||
out.push(`补丁 / patches: ${displayTally.applied}/${displayTally.total || 0} applied, ${displayTally.pending} pending`
|
||||
+ (displayTally.drifted ? `, ${displayTally.drifted} drifted(官方原文已改,需更新 pattern)` : ""));
|
||||
if (state.host_version) {
|
||||
const supported = state.host_supported !== false;
|
||||
const compat = supported
|
||||
? ""
|
||||
: ` ← 未适配:插件声明 ${state.host_target || "?"}`;
|
||||
out.push(`宿主 / host: ${state.host_version}${compat}`);
|
||||
}
|
||||
for (const row of displayRows) {
|
||||
const s = row.status || "n/a";
|
||||
const mark = s === "applied" ? "✓" : s === "pending" ? "✗" : "·";
|
||||
const mark = s === "applied" ? "✓" : s === "pending" ? "✗" : s === "drifted" ? "!" : "·";
|
||||
const patch = core.ALL_PATCHES.find((item) => item.id === row.id);
|
||||
const label = patch ? patch.name : `patch-${row.id}`;
|
||||
const layer = patch ? `${patch.layer}/${patch.layer_en}` : row.layer || "";
|
||||
@@ -1899,9 +1907,13 @@ function installWebServer(ctx, cfg) {
|
||||
patches_applied: state.ai_base ? (state.display_applied ?? state.patches_applied) : 0,
|
||||
patches_pending: state.display_pending ?? state.patches_pending,
|
||||
patches_skipped: state.display_skipped ?? state.patches_skipped ?? 0,
|
||||
patches_drifted: state.display_drifted ?? state.patches_drifted ?? 0,
|
||||
patches_ready: state.display_ready ?? state.patches_ready ?? 0,
|
||||
patches_na: state.patches_na || 0,
|
||||
patches_total: state.ai_base ? (state.display_total ?? state.patches_total ?? 0) : 0,
|
||||
host_version: state.host_version || "",
|
||||
host_target: state.host_target || "",
|
||||
host_supported: state.host_supported !== false,
|
||||
patches_lost: reapply.patchesLostAfterHostReset(),
|
||||
patch_status: state.patch_status,
|
||||
patches: (state.display_patches || []).map((p) => ({
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
ALL_PATCHES,
|
||||
applyReplacementsToText,
|
||||
filePatchOutcome,
|
||||
isPatchResultSoftOk,
|
||||
isSelfMarkedPatch,
|
||||
parseHostVersion,
|
||||
patchStatusReady,
|
||||
rollupDisplayStatus,
|
||||
rollupPatchStatus,
|
||||
tallyDisplayPatches,
|
||||
} from "../lib/core.js";
|
||||
|
||||
const base = {
|
||||
applied: 0,
|
||||
already: 0,
|
||||
missing: 0,
|
||||
notFound: 0,
|
||||
drifted: 0,
|
||||
lastError: null,
|
||||
keyCount: 1,
|
||||
layoutSoft: false,
|
||||
strictFiles: false,
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 判据:上游漂移必须显性,不能落成 skipped(软成功)。
|
||||
* 这是"官方升级后插件静默失效、状态页却全绿"的唯一入口。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("rollupPatchStatus: 文件在、原文对不上 → drifted 而不是 skipped", () => {
|
||||
assert.equal(rollupPatchStatus({ ...base, drifted: 1 }), "drifted");
|
||||
});
|
||||
|
||||
test("rollupPatchStatus: pattern 还在 → pattern_not_found(可以打)", () => {
|
||||
assert.equal(rollupPatchStatus({ ...base, notFound: 1 }), "pattern_not_found");
|
||||
});
|
||||
|
||||
test("rollupPatchStatus: 有文件真的写成功就仍算 applied,不制造半打假告警", () => {
|
||||
assert.equal(rollupPatchStatus({ ...base, applied: 1, drifted: 1 }), "applied");
|
||||
});
|
||||
|
||||
test("rollupPatchStatus: 已经落盘过的补丁仍算 already,不因个别文件漂移翻红", () => {
|
||||
// 多文件补丁里个别文件本来就不含这段代码(另一个构建产物),
|
||||
// 这种"假漂移"不能盖掉已经打上的部分。
|
||||
assert.equal(rollupPatchStatus({ ...base, already: 1, drifted: 1 }), "already");
|
||||
});
|
||||
|
||||
test("rollupPatchStatus: 写错误优先于 applied,不能把 EACCES 吞成绿", () => {
|
||||
assert.equal(
|
||||
rollupPatchStatus({ ...base, applied: 1, lastError: "write_error:EACCES" }),
|
||||
"write_error:EACCES",
|
||||
);
|
||||
});
|
||||
|
||||
test("rollupPatchStatus: 文件全缺 → missing_file", () => {
|
||||
assert.equal(rollupPatchStatus({ ...base, missing: 1 }), "missing_file");
|
||||
});
|
||||
|
||||
test("filePatchOutcome: 文件在、marker 没有、pattern 一条都不中 → drifted", () => {
|
||||
const patch = { id: 9801, replacements: [{ pattern: "NEEDLE_NOT_THERE", replace: "x" }] };
|
||||
assert.equal(filePatchOutcome("host text", patch, ""), "drifted");
|
||||
});
|
||||
|
||||
test("filePatchOutcome: marker 在 → applied(不算漂移)", () => {
|
||||
const patch = {
|
||||
id: 9802,
|
||||
markers: ["[dsh-purge] marker"],
|
||||
replacements: [{ pattern: "NEEDLE_NOT_THERE", replace: "x" }],
|
||||
};
|
||||
assert.equal(filePatchOutcome("host [dsh-purge] marker text", patch, ""), "applied");
|
||||
});
|
||||
|
||||
test("filePatchOutcome: pattern 还在 → pending", () => {
|
||||
const patch = { id: 9803, replacements: [{ pattern: "NEEDLE", replace: "x" }] };
|
||||
assert.equal(filePatchOutcome("a NEEDLE b", patch, ""), "pending");
|
||||
});
|
||||
|
||||
test("自标记型补丁:pattern 就是本插件留下的痕迹,找不到 = 本来没加过,不算漂移", () => {
|
||||
const patch = {
|
||||
id: 9804,
|
||||
replacements: [{ pattern: "- id: tool-fs # [dsh-purge] minimal fs tool parity", replace: "x" }],
|
||||
};
|
||||
assert.equal(isSelfMarkedPatch(patch), true);
|
||||
assert.equal(filePatchOutcome("host text", patch, ""), "skipped");
|
||||
});
|
||||
|
||||
test("自标记型判定:普通补丁不算自标记,#80 算", () => {
|
||||
assert.equal(isSelfMarkedPatch({ id: 9805, replacements: [{ pattern: "const a = 1;", replace: "x" }] }), false);
|
||||
const p80 = ALL_PATCHES.find((p) => p.id === 80);
|
||||
assert.ok(p80, "找不到 #80");
|
||||
assert.equal(isSelfMarkedPatch(p80), true);
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 就绪口径:drifted 必须让"已就绪"变红(可选补丁不阻断 apply,但状态仍在)。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("patchStatusReady: drifted 的非可选补丁不算就绪", () => {
|
||||
assert.equal(patchStatusReady("drifted", { optional: false }), false);
|
||||
});
|
||||
|
||||
test("patchStatusReady: drifted 的可选补丁不阻断就绪", () => {
|
||||
assert.equal(patchStatusReady("drifted", { optional: true }), true);
|
||||
});
|
||||
|
||||
test("patchStatusReady: applied / already 算就绪", () => {
|
||||
assert.equal(patchStatusReady("applied"), true);
|
||||
assert.equal(patchStatusReady("already"), true);
|
||||
});
|
||||
|
||||
test("patchStatusReady: pending 不算就绪", () => {
|
||||
assert.equal(patchStatusReady("pending"), false);
|
||||
});
|
||||
|
||||
test("patchStatusReady: skipped 不再天然就绪,可选补丁仍然就绪", () => {
|
||||
assert.equal(patchStatusReady("skipped", { optional: false }), false);
|
||||
assert.equal(patchStatusReady("skipped", { optional: true }), true);
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 展示层统计:drifted 不能被算进 ready。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("tallyDisplayPatches: drifted 不计入 ready", () => {
|
||||
const out = tallyDisplayPatches([
|
||||
{ status: "applied" },
|
||||
{ status: "drifted" },
|
||||
{ status: "skipped" },
|
||||
]);
|
||||
assert.equal(out.applied, 1);
|
||||
assert.equal(out.drifted, 1);
|
||||
assert.equal(out.ready, 2, "只有 applied + skipped 计入 ready");
|
||||
});
|
||||
|
||||
test("rollupDisplayStatus: 一组里只要有一条漂移,这组就不是干净绿", () => {
|
||||
assert.equal(rollupDisplayStatus(["applied", "drifted"]), "drifted");
|
||||
assert.equal(rollupDisplayStatus(["applied", "applied"]), "applied");
|
||||
assert.equal(rollupDisplayStatus(["pending", "drifted"]), "pending");
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 软成功口径:skipped 不再天然软成功;drifted 看得见但不阻断 Apply。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("isPatchResultSoftOk: skipped 只有可选/自标记型才算软成功", () => {
|
||||
assert.equal(isPatchResultSoftOk({ status: "skipped" }, { id: 1, optional: false }), false);
|
||||
assert.equal(isPatchResultSoftOk({ status: "skipped" }, { id: 2, optional: true }), true);
|
||||
});
|
||||
|
||||
test("isPatchResultSoftOk: drifted 不阻断 Apply(兼容 0.1.6 / 0.2.0 / 0.2.1-rc.2)", () => {
|
||||
assert.equal(isPatchResultSoftOk({ status: "drifted" }, { id: 3, optional: false }), true);
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 幂等:二次应用不得继续增长(历史事故是每次 apply +841 字符、永不收敛)。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("applyReplacementsToText: 全部字面量 pattern 二次应用不叠加", () => {
|
||||
const offenders = [];
|
||||
for (const p of ALL_PATCHES) {
|
||||
const reps = (p.replacements || []).filter((r) => r.pattern && !(r.pattern instanceof RegExp));
|
||||
if (reps.length === 0) continue;
|
||||
// 用 pattern 本体合成输入:保证第一遍一定命中,从而真正检验收敛性。
|
||||
const src = reps.map((r) => String(r.pattern)).join("\n");
|
||||
const once = applyReplacementsToText(src, p, "");
|
||||
const twice = applyReplacementsToText(once.text, p, "");
|
||||
if (twice.text !== once.text) offenders.push(`#${p.id} ${p.name}`);
|
||||
}
|
||||
assert.deepEqual(offenders, [], `这些补丁二次应用还在变:${offenders.join(", ")}`);
|
||||
});
|
||||
|
||||
test("applyReplacementsToText: 没有残留 pattern 时 changed=false", () => {
|
||||
const patch = { id: 9901, replacements: [{ pattern: "NOT_PRESENT_ANYWHERE", replace: "x" }] };
|
||||
const r = applyReplacementsToText("hello world", patch, "");
|
||||
assert.equal(r.changed, false);
|
||||
assert.equal(r.text, "hello world");
|
||||
});
|
||||
|
||||
test("#77 锚点容错:官方在中间插一行也照样命中,且二次应用不叠加", () => {
|
||||
const p77 = ALL_PATCHES.find((p) => p.id === 77);
|
||||
assert.ok(p77, "找不到 #77");
|
||||
// 0.2.1-rc.2 起的官方原文:中间多了一行 revised.clear()
|
||||
const host =
|
||||
"\t\t\tappend(record) {\n" +
|
||||
"\t\t\t\tconst event = record.event;\n" +
|
||||
"\t\t\t\tif (this.inputs.has(event.seq)) return \"none\";\n" +
|
||||
"\t\t\t\tif (this.revised.size > 0) this.revised.clear();\n" +
|
||||
"\t\t\t\tthis.inputs.set(event.seq, record);\n";
|
||||
const once = applyReplacementsToText(host, p77, "");
|
||||
assert.equal(once.changed, true, "rc.2 的原文应当命中");
|
||||
assert.ok(once.text.includes("isRewindMarker(event)"), "应当注入回退判断");
|
||||
assert.ok(once.text.includes("if (this.revised.size > 0) this.revised.clear();"), "官方那行必须原样保留");
|
||||
const twice = applyReplacementsToText(once.text, p77, "");
|
||||
assert.equal(twice.text, once.text, "二次应用不得再插一遍");
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 命中数契约:官方同名代码多一处就该拒写,而不是把两处一起改掉。
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("applyReplacementsToText: expect 命中数不符时拒写并回传实际命中数", () => {
|
||||
const patch = { id: 9902, replacements: [{ pattern: "NEEDLE", replace: "X", expect: 1 }] };
|
||||
const r = applyReplacementsToText("NEEDLE NEEDLE", patch, "");
|
||||
assert.ok(r.hitMismatch, "应当回传 hitMismatch");
|
||||
assert.equal(r.hitMismatch.expected, 1);
|
||||
assert.equal(r.hitMismatch.actual, 2);
|
||||
assert.equal(r.text, "NEEDLE NEEDLE", "拒写时原文必须原样返回");
|
||||
assert.equal(r.changed, false);
|
||||
});
|
||||
|
||||
test("applyReplacementsToText: expect 命中数一致时正常替换", () => {
|
||||
const patch = { id: 9903, replacements: [{ pattern: "NEEDLE", replace: "X", expect: 1 }] };
|
||||
const r = applyReplacementsToText("a NEEDLE b", patch, "");
|
||||
assert.equal(r.hitMismatch, undefined);
|
||||
assert.equal(r.text, "a X b");
|
||||
});
|
||||
|
||||
test("applyReplacementsToText: expect=1 但一处都没命中也算不符(不许静默跳过)", () => {
|
||||
const patch = { id: 9905, replacements: [{ pattern: "NEEDLE", replace: "X", expect: 1 }] };
|
||||
const r = applyReplacementsToText("nothing here", patch, "");
|
||||
assert.ok(r.hitMismatch, "0 次命中同样是失配");
|
||||
assert.equal(r.hitMismatch.actual, 0);
|
||||
assert.equal(r.changed, false);
|
||||
});
|
||||
|
||||
test("applyReplacementsToText: 未声明 expect 时保持旧行为(全量替换)", () => {
|
||||
const patch = { id: 9904, replacements: [{ pattern: "N", replace: "X" }] };
|
||||
const r = applyReplacementsToText("N N", patch, "");
|
||||
assert.equal(r.hitMismatch, undefined);
|
||||
assert.equal(r.text, "X X");
|
||||
});
|
||||
|
||||
test("applyReplacementsToText: 正则 pattern 的 expect 同样生效(官方复制成两份就拒写)", () => {
|
||||
const patch = { id: 9906, replacements: [{ pattern: /NEEDLE/g, replace: "X", expect: 1 }] };
|
||||
const r = applyReplacementsToText("NEEDLE NEEDLE", patch, "");
|
||||
assert.ok(r.hitMismatch, "正则也必须遵守命中数契约");
|
||||
assert.equal(r.hitMismatch.actual, 2);
|
||||
assert.equal(r.text, "NEEDLE NEEDLE", "拒写时原文必须原样返回");
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* 宿主版本门禁
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
test("parseHostVersion: 拆出主次修订与预发布段", () => {
|
||||
assert.deepEqual(parseHostVersion("0.2.1-rc.3"), {
|
||||
major: 0, minor: 2, patch: 1, pre: ["rc", "3"],
|
||||
});
|
||||
assert.equal(parseHostVersion("not-a-version"), null);
|
||||
assert.deepEqual(parseHostVersion("v1.2.3"), { major: 1, minor: 2, patch: 3, pre: [] });
|
||||
});
|
||||
Reference in new issue
Block a user