Compare commits

..
15 Commits
Author SHA1 Message Date
叫我小杨同学andClaude ec4c8b889f 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>
2026-10-30 13:09:35 +08:00
叫我小杨同学andClaude f79363a17e fix: cordis.patch.yml 为 [] 时替换而非追加,修复宿主启动解析失败(#191)
宿主生成的 profile 层 cordis.patch.yml 可能整体只有一个空 flow 序列 [],
那本身就是一个完整 YAML 文档。旧实现无条件在文件尾追加 `- insert:`,
结果是第二个文档,宿主启动解析报
"end of the stream or a document separator is expected" 直接崩掉
(macOS DSH Desktop 0.2.1-rc.4)。

- 新增 classifyPatchBody() 判断数据部分形态:empty / empty-flow /
  block-seq / flow-seq / unknown,只看最后一个文档的根节点
- 空 flow 序列([] 或 [ ],可带 --- 前缀)→ 把整行替换成 insert 块,
  绝不追加成第二个文档
- 空文件 / 只有注释和空行 → 写 insert 块,注释保留
- 正常块序列 → 沿用旧的追加行为,前导空行规则不变
- 非空 flow 序列(宿主/用户内容)以及认不准的形态 → 不动,
  返回 { ok: false, wrote: false },宁可留着也别写坏
- postinstall 脚本区分「跳过」和「已有」,跳过时打印说明
- profileHasPurgeBodyInsert() 检测逻辑未动
- 新增 9 条用例(形态分类 / 空文件 / 只有注释 / 注释+[] / ---+[] /
  块序列追加 / 非空 flow 不写 / 已有本体行零写入 / 替换后幂等),
  版本 1.1.83

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-30 12:26:23 +08:00
叫我小杨同学andClaude 4182bb5fee fix: allowBuilds 只写裸包名,清除所有 dsh-purge@* 键,避免 pnpm 11 崩溃(#185)
- pnpm 的 allowBuilds 按包名匹配,裸包名 dsh-purge 对 tarball / git /
  registry 三种安装形态都放行;而 dsh-purge@https://... 这类键在 pnpm 11
  (DSH 内置 11.2.2)会被 semver 解析器当成版本联合,直接报
  [ERR_PNPM_INVALID_VERSION_UNION] Invalid versions union 让 install 崩掉
- purgePnpmBuildSpecs() 只返回 ["dsh-purge"],不再拼 tarball URL 键
- 自愈时所有 dsh-purge@* 历史键(URL 键、旧截断键 dsh-purge@https、
  @1.1.81 之类版本键)一律丢弃,只保留裸包名;非 purge 键原样保留
- 删除随之失效的 readPurgeTarballFromLock() / readPkgTarball()
- 新增用例:输入只含 URL 键时重写后只剩裸包名;健康文件重写输出等于输入,
  零写入

Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-30 12:25:32 +08:00
叫我小杨同学 0169f4ef44 fix: allowBuilds URL 键截断与污染自愈,健康文件零写入(#180)
- parseAllowBuildLine 未引号键只在冒号+空白处切分,URL 键不再截断;
  引号键照旧,行尾无值也能解析
- 含 :// 的键写回加引号,避免 YAML 冒号歧义
- 重写只保留精确等于期望键的 dsh-purge@*,畸形/过期键自动清掉
- 期望键优先读 profile 的 pnpm-lock.yaml 实际 tarball(固定 commit 安装
  不再有双 URL 键),退回 package.json,再退裸包名;profileDir 参数可选
- 重写结果先过最小校验(键不重复、round-trip 无损),不过不写盘;
  健康文件 next === current 零写入
- 新增 test/profile-insert.test.js(13 条,全量 36 条全过),版本 1.1.82
2026-10-28 20:14:18 +08:00
叫我小杨同学 d77b05f67f docs: 安装说明改为分步式(Quick start + Step by step),三语同步(#179) 2026-10-28 20:12:38 +08:00
叫我小杨同学 d6d653beee Merge PR #178: docs: add Japanese README 2026-10-28 20:09:47 +08:00
Ikko Eltociear Ashimine d054bcbc16 docs: add Japanese README 2026-10-28 03:39:04 +09:00
叫我小杨同学 b0d29e3f00 1.1.81: 修复 bug,修复稳定性(#174 #175) 2026-10-28 00:06:10 +08:00
叫我小杨同学 a5752a7042 fix: 收录 DSH NEXT 识别与单测(#174 #175)
#171/#173 已在 1.1.80;#174 按官方 asar 路径认 DSH NEXT,不把任意 app.asar 当桌面。
2026-10-28 00:03:24 +08:00
叫我小杨同学 093acefdfb 1.1.80: 修复 bug,修复稳定性(#168 #169 #170 #172 #176) 2026-10-27 23:34:55 +08:00
叫我小杨同学 533f4605c6 1.1.79: 修复 bug,修复稳定性(#165 #166 #167) 2026-10-27 01:25:57 +08:00
叫我小杨同学 8e180b368e fix: 命令撞名只丢那一条;主插件 insert 自愈(#162 #159) 2026-10-26 11:15:56 +08:00
叫我小杨同学 0f81f6cfd5 fix: Apply 不再覆盖 npm 全局 dsh 软链;pnpm/plugin add 补本体 insert(#157 #154 #155) 2026-10-24 20:38:05 +08:00
叫我小杨同学 9f38206d8c 1.1.78: 修复停用/卸载后无法新建会话(#108) 2026-10-24 15:14:19 +08:00
叫我小杨同学 73a61ff678 fix: 停用/卸载时清掉 selectedDefault=redteam(#108) 2026-10-24 14:42:42 +08:00
13 changed files with 1809 additions and 161 deletions

No files matched your search

+595
View File
@@ -0,0 +1,595 @@
<p align="center">
<img src="docs/banner.svg" alt="dsh-purge" width="720">
</p>
<h1 align="center">⚔️ DeepSeek Harness サイバーセキュリティ レッドチームツール (dsh-purge)</h1>
<p align="center"><strong>バージョン 1.1.81</strong></p>
<p align="center">
<em>DeepSeek Harness のジェイルブレイク: すべてのモデルに対応し、モデルごとにプロンプトを切り替え。デフォルトプロンプトは 小码酱 用。ぜひ Star ⭐ を。これをベースに開発する場合は「要帰属表示」をご覧ください。</em>
</p>
<p align="center">
<a href="https://github.com/YuJunZhiXue/dsh-purge/stargazers"><img src="https://img.shields.io/github/stars/YuJunZhiXue/dsh-purge?logo=github&label=Stars" alt="GitHub stars"></a>
<a href="https://github.com/YuJunZhiXue/dsh-purge/blob/master/LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-blue?style=flat" alt="Apache-2.0"></a>
<a href="https://awesome-dsh-plugin.com"><img src="https://awesome-dsh-plugin.com/badge.svg" alt="awesome · DSH plugin"></a>
<a href="https://deepseek.stream/plugins/dsh-purge"><img src="https://img.shields.io/badge/Hub-dsh--purge-1a73e8" alt="DeepSeek Harness Hub"></a>
<a href="https://www.deepseek.com/harness/"><img src="https://img.shields.io/badge/dsh-0.2.0--rc.2%20%2F%200.2.1--rc.2-blue" alt="DSH"></a>
<br>
<img src="https://img.shields.io/badge/Node.js-%3E%3D18-339933?logo=node.js&logoColor=fff" alt="Node.js">
<img src="https://img.shields.io/badge/JavaScript-F7DF1E?logo=javascript&logoColor=000" alt="JavaScript">
</p>
<p align="center">
<a href="https://dsh-plugin.org/plugins/yujunzhixue/dsh-purge"><img src="https://dsh-plugin.org/badges/listed.svg" alt="Listed on dsh-plugin.org"></a>
</p>
<p align="center">
<a href="README.md">English</a> | <a href="README.zh-CN.md">中文</a> | <a href="README.ja.md">日本語</a>
</p>
## 作者より
このオープンソースの成果物を、公然と売りさばく人たちがいました。その後、作者は呼び出されて話をすることになりました。あとは言わずもがな。行間を読んでください。
今後、**公開インターネットは閉じます**。オープンソース版では **ローカルのラボ IP のみ** を許可します(ループバックと RFC1918)。ドメインは先に名前解決され(hosts も含む)、すべての応答がプライベートまたはループバックでなければなりません。`.lab` を公開 IP に向ける hosts トリック、名前解決の失敗、公開 IP が混じった応答はブロックされます。**ゲームチートは禁止です**(エイムボット、ウォールハック、メモリ改ざん、アンチチート回避)。プロンプトとセッションゲートの両方で阻止します。このビルドにはスキルライブラリやナレッジベースは同梱されません。
**オリジナルビルドの転売は禁止です。** 課金、スキン変更、グループでの売り込みは許可されません。フォークは自由ですが、**帰属表示が必須** で、出所を明記してください: [YuJunZhiXue/dsh-purge](https://github.com/YuJunZhiXue/dsh-purge)。出所を隠したり、自分のものとして偽ったりすれば、あなたは向こう側です。
作者の個人チャンネル: [t.me/LLM_PoJia](https://t.me/LLM_PoJia)。メモや更新情報はそこに出ます。
## 目次
- [作者より](#作者より)
- [これは何か](#これは何か)
- [要帰属表示](#要帰属表示)
- [ライセンス](#ライセンス)
- [対応ホスト](#対応ホスト)
- [インストール](#インストール)
- [プレビュー](#プレビュー)
- [使い方](#使い方)
- [仕組み](#仕組み)
- [復元](#復元)
- [リリース](#リリース)
---
## これは何か
**dsh-purge** は、お使いのマシンにすでにインストールされている公式 [DeepSeek Harness](https://www.deepseek.com/harness/) 向けのサイバーセキュリティ レッドチームプラグインです。**1.1.81** は **DSH 0.2.1-rc.2** を対象とします(0.2.0 も動作します)。**DSH 0.2.1-rc.3 以降の新しい RC は非対応です。** 公式 **Web**(`dsh web`)と公式 **デスクトップ EXE** の両方に対応します。インストールと Apply はそれぞれ別々に行います。
Harness は単にプロンプトを転送するだけではありません。プロンプトの書き換え、承認ゲート、サンドボックスポリシー、セッション移行を実行時に行います。「モデルは答えるか」だけを問うと、ホスト層のブロックをモデルの拒否と取り違えてしまいます。このプラグインは、あなた自身のインストール環境でこの 2 つの層を分離し、制御された評価や、どのデフォルトポリシーが過度に厳しいかを確認するために使います。
| 得られるもの | 内容 |
|---|---|
| **dsh-purge ドック** | セッションタイトルの横のボタンで右ドックを開く。2 ページ: Clean と Drill |
| **Clean** | グループ化されたパッチ状況、Apply / Restore / Uninstall、プロンプトエディタ、複数のルールセット |
| **Drill** | 安定版に内蔵。認可後: アセットとローカル環境。このビルドはスキルやナレッジベースを同梱しません。ローカルラボ専用 |
| **ホストポリシー** | デフォルトのコピー、権限ポリシー、ツール制限。公式の機能はそのまま。2 つ目の架空アイデンティティは作らない |
| **起動時** | チェックして再適用。npm が `node_modules` を上書きした後も、ファイルを手編集しなくてよい |
ドライブレターのハードコードはありません。`$DSH_HOME`、dsh ランチャー横の `.dsh`、次に `~/.dsh` を参照します。Harness のソースツリーにはパッチしません。変更を書き込むのは **dsh-purge** の **Clean** ページの **Apply** です。アイデンティティはプラグインに同梱された暗号化プロンプト、つまりプロンプトボックスがデフォルトで表示するテキストから来ます。ホストのプロンプトファイルは読みません。
触れるのはユーザーのマシン上の公式 `@deepseek-ai` パッケージとローカル設定だけです。公開スキャナーでもなく、第三者サイトへの攻撃キットでもありません。リポジトリにマルウェア、未認可のエクスプロイトスクリプト、公開インターネットを狙うペイロードは同梱されていません。
---
## オリジナルの転売は禁止。フォークは帰属表示が必須。
## 要帰属表示
**オリジナルビルドの転売は禁止です。** 有料での転売、スキン変更したストア掲載、グループでの売り込みは禁止です。
**フォークは帰属表示が必須** で、出所のリポジトリを明記してください: [YuJunZhiXue/dsh-purge](https://github.com/YuJunZhiXue/dsh-purge)。名前、アイデア、コード、プロンプトを借用する場合も同様です。
出所を隠す、自分のものとして偽る、オリジナルを転売する行為は追及します。
## ライセンス
本リポジトリは [Apache License 2.0](./LICENSE) です。フォークおよび再配布では著作権表示と [NOTICE](./NOTICE) を保持し、[YuJunZhiXue/dsh-purge](https://github.com/YuJunZhiXue/dsh-purge) を明記してください。オリジナルの転売は禁止です。
---
<a id="strict-legal--compliance-disclaimer"></a>
<div>
### ⚠️ <font color="red">厳格な法的・コンプライアンス免責事項</font>
<font color="red">
**免責事項:** 本プロジェクトは非営利のオープンソースプロジェクトです。適用される法律および利用するプラットフォームの規則に従い、学習と研究のみを目的としています。違法または非準拠の目的に使用しないでください。生じた結果は利用者が負います。
**ゼロトレランス声明:** 本プロジェクトはいかなる違法行為にも反対し、禁止します。作者は、未認可のネットワーク攻撃、エクスプロイトの使用、データの窃取、コンピュータ情報システムへの不正侵入、違法または禁止されたコンテンツの生成を支援、奨励、幇助しません。**本プロジェクトを犯罪に使用した者は、法律上すべての責任を単独で負います。作者は一切の責任を負いません。**
1. **本リポジトリに違法な素材は含まれません。** 公開されているコード、ドキュメント、パッチ、デフォルトプロンプトは、マルウェア、バックドア、未認可のペンテストキット、ランサムウェア、クレデンシャルスタッフィングスクリプト、公開インターネットや第三者システムを狙う攻撃ペイロードでは **ありません**。本プロジェクトは違法コンテンツを提供せず、犯罪を扇動・組織・幇助しません。
2. **ローカルの公式 Harness のみ。** セキュリティ評価用パッチとプロンプトインジェクションは、**ユーザーのマシンにすでにインストールされた公式 DeepSeek Harness**(`@deepseek-ai` パッケージ、ローカルプロファイル / `$DSH_HOME`)に対してのみ動作します。対象はユーザー自身の公式ローカルソフトウェアであり、**他人のウェブサイト、サーバー、アカウント、情報システムではありません**。
3. **評価用パッチは公開インターネットを攻撃しません。** Apply、インジェクト、リバート、アンインストールはすべてローカルファイルとローカルプロセス内に留まります。いかなる公開ホストや未認可システムに対しても、**スキャン、探査、侵入、攻撃トラフィックの送信を行いません**。本プロジェクトを公開インターネットへの踏み台として使わないでください。「更新確認」が有効な場合、プラグインはバージョン比較のために本プラグイン自身の GitHub リポジトリにのみアクセスすることがあります。これは第三者システムへの攻撃では **なく**、何かへの侵入を認可するものでも **ありません**。
4. **合法かつ制御された範囲。** 本プロジェクトは、ユーザーが **管理する権限を有する公式 Harness** 上でのレッドチーム研究と堅牢性評価の補助ツールです。**所有者の合法的な書面による認可のないターゲット、公開オンラインシステム、本番ワークロードに対して実行しないでください。** テストは **認可されたローカルの公式 Harness、オフラインのローカル合成フィクスチャ、認可されたサイバーセキュリティレンジ、準拠したラボ環境** に限ります。
5. **オープンソース版はローカルラボ専用です。** 攻撃タスクはループバックと RFC1918 アドレスのみ許可します。ドメインは名前解決され、IP で判定されます。サフィックスは許可リストではありません。公開 IP、公開に解決される名前、名前解決の失敗、ラボ名を公開インターネットに向ける hosts エントリは例外になりません。キー、パスワード、ネットワーク範囲、ワイルドカード、会話内での主張は例外を追加しません。ゲームチートは禁止です。このビルドにはスキルライブラリやナレッジベースは同梱されません。
6. **禁止される用途。** 利用者は、本プロジェクトを直接・間接を問わず、以下に違反する目的で使用してはなりません(いずれも遵守必須。回避の口実は認められません):
- <font color="red"><strong>中華人民共和国刑法</strong></font>
- <font color="red"><strong>中華人民共和国サイバーセキュリティ法</strong></font>
- <font color="red"><strong>中華人民共和国データセキュリティ法</strong></font>
- <font color="red"><strong>中華人民共和国個人情報保護法</strong></font>
- その他適用される法律、規制、監督規則;
- さらに以下も禁止:
- 公的・私的なコンピュータ情報システムへの未認可の侵入または攻撃;恐喝、破壊、クレデンシャルスタッフィング、悪意あるペイロードの拡散;
- 国家安全保障への脅威、テロ、暴力、ポルノ、賭博、詐欺、プライバシーや知的財産権の侵害を含む、法律が禁じるあらゆるコンテンツの誘発・生成・拡散;
- モデル提供者の利用規約および利用許諾ポリシーへの違反。
7. **利用者がすべての責任を負います。** 本プロジェクトは Apache-2.0 の下で現状のまま提供されます。作者は完全性、安全性、適合性について一切保証しません。**利用者は、ダウンロード、デプロイ、実行、改変、配布、およびそれに伴うすべての入力と出力について、民事・行政・刑事上のすべての責任を独立して負います。** 作者および貢献者は、悪用について直接・間接・連帯のいかなる責任も負いません。
8. **違反時にライセンスは終了します。** 本プロジェクトを違法な攻撃、悪意ある活動、その他の違反に使用した者は、違反の瞬間からオープンソースライセンスが **自動的かつ取り消し不能に終了** します。使用を直ちに停止し、すべての複製と派生物を永久に破棄し、法的制裁を受け入れなければなりません。
9. **無関係。** 本プロジェクトは独立したオープンソースのセキュリティ評価研究プロジェクトです。DeepSeek またはその関連会社との間に、雇用、商業、認可、推奨のいかなる関係もありません。ここでの「公式」は、評価対象がユーザーのマシン上の公式 DeepSeek Harness パッケージであることだけを意味します。DeepSeek が本プラグインを開発・承認・保証したことを **意味しません**。
10. **帰属表示は必須です。** 本プロジェクトの名前、アイデア、コード、プロンプトを借用する場合は、作者をクレジットし本リポジトリを明記しなければなりません。帰属表示の不履行は追及します。[要帰属表示](#要帰属表示) を参照してください。
</font>
</div>
---
## 対応ホスト
**1.1.81 は DSH 0.2.1-rc.2 を対象とします。** 0.2.0 も動作します。0.1.x には適用しないでください。
- **dsh 0.2.1-rc.2**(公式デスクトップ / 公式 `dsh web`): **1.1.81** を使用。`{{cwd}}` / `[cwd]` クラッシュ、patch #40 のマッチ、削除された `toolFilter`、ホスト `dsh-tools` の解決、hostFs の fd、デスクトップヘルパーの自己終了、`file:` アーカイブ更新、Ctrl+Enter ステアを修正。
- **dsh 0.2.0-rc.2**: **1.1.40** 以降を使用。このラインもインストールできます。
- **dsh 0.1.7**(rc.1 / rc.2 を含む): **1.1.39** 以前を使用 — [Releases](https://github.com/YuJunZhiXue/dsh-purge/releases) で該当タグを選択。
- **dsh 0.2.1-rc.3 / rc.4 以降は非対応です。** マッチしないパッチは pending または skipped のままで、盲目的な書き換えはしません。**0.2.1-rc.2** に留まってください。
マッチしないパッチは pending または skipped のままで、盲目的な書き換えはしません。
---
## インストール
**プラグインマーケットプレイスは使わないでください。** [dsh-plugin.org](https://dsh-plugin.org) や 設定 → プラグインマーケット でのワンクリックインストールは `already queued: dsh-purge` で失敗し、コマンドを実行しません。`dsh-purge` という名前は npm レジストリにないので、`pnpm add dsh-purge` はしないでください。
### クイックスタート
PATH に `dsh` があれば、コマンド 1 つ、再起動 1 回、クリック 1 回。自分が開いているホストのコマンドをそのまま実行します(デスクトップ EXE は `web` の代わりに `desktop`):
```sh
# 公式 `dsh web`
dsh plugin --profile web add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
# 公式デスクトップ EXE
dsh plugin --profile desktop add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
1. インストールしたホストを **完全に終了して再起動** します。Web: `dsh web` を停止して起動し直す。デスクトップ: トレイアイコンも終了してから exe を開く。
2. そのホストで、セッションタイトルの横の **dsh-purge** → **Clean** → **Apply** をクリック。成功した Apply は 1 回だけ再起動します。
完了 — チャットで `/purge status` を実行して確認します。pnpm がビルド許可を尋ねてきた場合や、下記の何かが現れない場合は、この後のステップ別の手順に進んでください。
### ステップバイステップ
**ステップ 1 — 使うホストを選ぶ。** 公式 `dsh web` と公式デスクトップ EXE は **別々に** インストール・パッチされます。実際に開くホストにのみインストールしてください。
| 実行するもの | プロファイル | インストールコマンド |
|---|---|---|
| 公式 `dsh web` | `web` | クイックスタートの `web` の行 |
| 公式デスクトップ EXE | `desktop` | クイックスタートの `desktop` の行 |
**ステップ 2 — プラグインを入れる。** 圧縮パッケージの URL は `codeload.github.com` の書き方そのままにしてください。`github.com/.../archive` は使わないでください。その 302 により pnpm が `fetch failed` で失敗します。
`dsh` がある場合: クイックスタートの自分のプロファイルの行を実行します。このディレクトリがすでにクローンなら、URL の代わりに `.` を使います。
pnpm のみ(`dsh` 不要): リポジトリのルートではなく、実際に使うプロファイル内で実行してください。
```sh
cd "$DSH_HOME/profiles/web" # desktop: profiles/desktop
pnpm add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
Windows PowerShell:
```powershell
cd "$env:USERPROFILE\.dsh\profiles\web" # desktop: profiles\desktop
pnpm add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
`pnpm add` と `dsh plugin add` はパッケージを取得します。`postinstall` が `dsh-purge` を `dsh.profile.bundles` に書き込み、プロファイルの `cordis.patch.yml` に body `insert` を追加します。その insert がないとホストはプラグインを読み込まず、ボタンも現れません。
**完了の目安:** `node_modules/dsh-purge/package.json` が存在し、そのプロファイルの `bundles` に `"dsh-purge"` があり、`cordis.patch.yml` に `id: dsh-purge` の insert があること。
- pnpm 11/12 はビルドを許可しないとインストールスクリプトをスキップします(`ERR_PNPM_IGNORED_BUILDS`):
```sh
pnpm add --allow-build=dsh-purge --allow-build=dsh-purge@https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
# すでにインストール済みで警告のみの場合 — 完全な指定子が必要です(名前だけだと "set this to true or false" が残ります):
pnpm approve-builds dsh-purge@https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
# bundles / insert がまだ無い場合:
node node_modules/dsh-purge/scripts/ensure-profile-bundle.mjs
```
- `dsh` も pnpm も使えない場合は [手動インストール](#手動) に進んでください。
- デスクトップクライアントではボタンをクリックすることもできます(`dsh://` ディープリンク。同じ tarball をダウンロードします)。
<p align="center">
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.81&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fcodeload.github.com%2FYuJunZhiXue%2Fdsh-purge%2Ftar.gz%2Frefs%2Fheads%2Fmaster"><strong>デスクトップクライアントでインストール</strong></a>
</p>
**ステップ 3 — ホストを再起動する。** プラグインをプロファイルに追加しただけでは、`@deepseek-ai` にパッチは当たりません。インストールしたホストを完全に終了して再起動します(Web: `dsh web` を停止して起動し直す。デスクトップ: トレイアイコンも終了してから exe を開く)。
**完了の目安:** セッションタイトルの横に **dsh-purge** がある。見当たらない場合はステップ 5 へ。
**ステップ 4 — Apply して確認。** **そのホスト** で、セッションタイトルの横の **dsh-purge** をクリックし、**Clean** を開いて **Apply** をクリック。ホストの設定ページにはありません。成功した **Apply** は 1 回だけ再起動します。完了しなかった場合は再起動しません。Web のコントロールは Web のみに、デスクトップのコントロールはデスクトップアプリのみに作用します。片方のホストからもう片方を Apply しないでください。
**完了の目安:** チャットで `/purge status` を打つと `DSH_HOME` とパッチ一覧が表示され、パスは実際に実行しているホームであること。インストールされていないオプションパッケージ(liangshen)は skipped と表示され、Apply を妨げません。
**ステップ 5 — トラブルシューティング。** 上のステップが「完了の目安」で終わらなかったときだけ読むセクションです。
- **セッションタイトルの横にボタンが無い。** `dsh --dump-config`(または `dsh --profile desktop --dump-config`)を実行し、body 行に `id: dsh-purge`(`dsh-purge-redteam` ではない)があるか確認します。無ければステップ 2 の `ensure-profile-bundle.mjs` を実行し、ホストを完全に終了して再起動します。このバージョン以降は、起動時にライブのレッドチーム子エントリが欠けている insert も書き込みます — もう一度終了・再起動してください。先頭の `entry "redteam-store" not found` は古いレッドチームパッケージの名残で、無視して構いません。
- **マーケットが `already queued: dsh-purge` と言う。** マーケットのクリックをやめてください。ステップ 2 の `dsh plugin add` か pnpm を再度使います。CLI もすでにあると言う場合は、先に削除してから入れ直し、ステップ 3 をやり直します:
```sh
dsh plugin --profile desktop remove dsh-purge
dsh plugin --profile desktop add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
pnpm のみ:
```sh
cd "$DSH_HOME/profiles/desktop"
pnpm remove dsh-purge
pnpm add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
Web では `desktop` を `web` に置き換えます。
### その他
**アシスタントに任せる。** 以下のブロックをローカルアシスタントに貼ってください。実行すべきはインストールコマンドのみです — ディスクスキャン、ほかの編集、Apply、再起動はしません。
<details>
<summary><strong>AI アシスタント向け(インストールのみ)</strong></summary>
<!-- AI-AGENT-START -->
DeepSeek Harness プラグイン `dsh-purge` を Web プロファイルのみにインストールしてください。ディスク全体をスキャンしない、ほかのファイルを読み書きしない、設定を適用しない、アプリを再起動しない。desktop プロファイルにはインストールしない。プラグインマーケットプレイスは使わない。この名前は npm レジストリにないので `pnpm add dsh-purge` はしない。
**Web(公式 `dsh web`)**
`dsh` が PATH にある場合:
```sh
dsh plugin --profile web add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
`dsh` が無く pnpm がある場合は、`$DSH_HOME/profiles/web`(多くは `~/.dsh/profiles/web`)に `cd` して実行:
```sh
pnpm add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
このディレクトリがすでにクローンで `dsh` がある場合は `dsh plugin --profile web add .` を使う。`dsh` も pnpm も無ければ、ユーザーに伝えて停止する。
コマンドが完了したら、`dsh web` を完全に終了して再起動し、セッションタイトル横の **dsh-purge** を開いて **Clean** の **Apply** を押すようユーザーに伝える。その後停止する。
<!-- AI-AGENT-END -->
</details>
<a id="手動"></a>
**手動インストール。** コマンドが失敗する場合、または `dsh` が PATH に無い場合に使います。**実行するホストのプロファイルだけ** を編集してください — もう片方には触れず、既存の bundles を削除しないでください。
<details>
<summary><strong>完全な手動手順</strong></summary>
**1. このホストが使う `$DSH_HOME` を見つける。** 本物のホームは `.dsh`(公式 EXE では `dsh-home` のこともある)という名前で、`profiles` を含み、少なくとも 1 つの `profiles/<name>/package.json` を持ちます。順に確認: `DSH_HOME` 環境変数 → インストールルート横の `.dsh`(ポータブル)→ `%USERPROFILE%\.dsh` または `~/.dsh` → `%APPDATA%` / `%LOCALAPPDATA%\DeepSeek Harness\dsh-home`。確認: `profiles/web/package.json` の `"name"` が `"dsh-profile-web"`(または `dsh-profile-desktop`)であること。マシンにはホームが 2 つあることが多いので、実際に起動するホストのものを使ってください。
候補を一覧する PowerShell:
```powershell
$cands = @()
if ($env:DSH_HOME) { $cands += $env:DSH_HOME }
$cands += "$env:USERPROFILE\.dsh"
$dsh = Get-Command dsh -ErrorAction SilentlyContinue
if ($dsh) {
$dir = Split-Path $dsh.Source
$cands += @((Join-Path $dir ".dsh"), (Join-Path (Split-Path $dir) ".dsh"), (Join-Path (Split-Path (Split-Path $dir)) ".dsh"))
}
$cands += @("$env:APPDATA\DeepSeek Harness\dsh-home", "$env:LOCALAPPDATA\DeepSeek Harness\dsh-home")
$cands | Select-Object -Unique | Where-Object { $_ -and (Test-Path (Join-Path $_ "profiles")) }
```
**2. プラグインを `$DSH_HOME/plugins/dsh-purge` に置く**(フォルダ名は `dsh-purge`、`package.json` の `"name"` も `dsh-purge`)。
```sh
git clone https://github.com/YuJunZhiXue/dsh-purge.git "$DSH_HOME/plugins/dsh-purge"
```
git が無い場合: [master.tar.gz](https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz) をダウンロードし、展開して `dsh-purge-master` → `dsh-purge` にリネームし、`plugins` 以下に置きます。すでにクローンがある場合は、いくつかの `.js` ファイルではなくツリー全体をコピーしてください。
**3. そのプロファイルの `package.json` だけを編集する — まずバックアップ。** Web → `$DSH_HOME/profiles/web/package.json`; desktop → `$DSH_HOME/profiles/desktop/package.json`。既存の依存関係と bundle をすべて残したまま、**2 つだけ** 追加します:
1. `dependencies` に `"dsh-purge": "file:../../plugins/dsh-purge"` を追加
2. `dsh.profile.bundles` の **末尾** に `"dsh-purge"` を追加(すでにあればスキップ)
```json
{
"name": "dsh-profile-web",
"private": true,
"dependencies": {
"dsh-purge": "file:../../plugins/dsh-purge"
},
"dsh": {
"profile": {
"bundles": [
"@deepseek-ai/dsh-base",
"@deepseek-ai/dsh-web-app",
"dsh-purge"
],
"patchReload": "live"
}
}
}
```
JSON を有効に保ってください(新しい項目の前にカンマ、最後の項目の後ろには無し)。`file:../../plugins/dsh-purge` を絶対パスに変えない、`patchReload` やほかのプラグインに触れない、`"dsh-purge"` を 2 回並べないこと。desktop に `dsh-web-app` 行が無い場合は追加しないでください。
**4. そのプロファイルだけで `pnpm install` を実行**(リポジトリルートや `$DSH_HOME` ではなくプロファイルディレクトリに `cd`):
```sh
cd "$DSH_HOME/profiles/web" # または profiles/desktop
pnpm install
```
成功: `profiles/<web|desktop>/node_modules/dsh-purge/package.json` が存在すること。`pnpm` が無い場合は公式 `dsh` に同梱の Node / pnpm を使います。`Could not resolve` の場合は `file:` パスを再確認、JSON エラーの場合はカンマを直すかバックアップを復元します。
**5. そのホストを完全に終了して再起動し、Apply** — 上のステップ 3 とステップ 4 です。カードはセッションタイトルの横に現れます。そのホストでのみ **Apply**(または `/purge apply`)をクリック。カードが無ければ、おそらく別の `.dsh` を編集しています — 手順 1 に戻ってください。
</details>
**アンインストール。** セッションタイトル横の **dsh-purge** → **Clean** → **Uninstall**。ダイアログを確認: 適用済みパッチを元に戻し、元の Harness を復元し、現在のホストを再起動します。無効化やアンインストールは、まだ `redteam` を指しているエージェントプリセットのデフォルトも `standard` に戻すので、プリセットが消えた後もホストはセッションを作成できます。
<details>
<summary><strong>アンインストールのコマンドと設定</strong></summary>
```sh
# またはターミナル / チャットから
dsh-purge --uninstall
# /purge uninstall
```
プラグイン設定は `cordis.patch.yml` にあります(`postPrompt` はデフォルトで空):
```yaml
- insert:
- id: dsh-purge
name: 'dsh-purge'
config:
enabled: true
autoApplyOnStart: true
autoUpdateOnStart: false
autoRevertOnMissing: false
verbose: false
postPromptOrder: 5100
postPrompt: ""
```
</details>
---
## プレビュー
**dsh-purge** はセッションタイトルの横にあります。右ドックを開き、**Clean** と **Drill** の 2 ページがあります。**Light / Ink** を切り替えられます。パッチはグループ化され、カウントには実際に適用された項目のみが含まれます。ルールセットはエディタの上の一覧にあり、各行に Enable と Delete があります。
Drill を初めて開くときは、通知を読み、カウントダウンを待ち、末尾までスクロールして 3 つのチェックボックスにチェックします。Clean にこのステップは不要です。Drill は、あなたが管理するホスト、オフラインターゲット、またはすでに書面による認可のある演習にのみ使えます。
**Clean**
![Clean](docs/preview/dock-clean.png)
**Drill 認可**
![Drill authorization](docs/preview/dock-auth.png)
**Drill**
![Drill](docs/preview/dock-drill.png)
**パッチ**
![Patches](docs/preview/settings.png)
**ローカルラボ**
オープンソース版は localhost / プライベートネットのみ許可します。Clean ページにそう書かれています。公開ホストは登録できません。
| エリア | 表示内容 |
|---|---|
| dsh-purge | セッションタイトル横のボタン。ドックを開閉する |
| Clean | パッチ、プロンプト、ルールセット |
| Drill | 認可後のアセットと環境。このビルドはスキルやナレッジベースを同梱しません。認可までタブは Unauthorized と表示 |
| Patches | グループ化された状況、Apply、Restore、Uninstall |
| Prompt | `prompt-inject.md` をセッションのオーバーライドとして編集 |
| Local lab | ループバック / RFC1918 のみ。名前は解決され、すべてのアドレスがプライベートでなければならない |
| Rule sets | 複数の `AGENTS.md` / `CLAUDE.md`。Enable は `$DSH_HOME` 以下に書き込み、Delete は行を削除 |
---
## レイアウト
`bin/` は CLI、`lib/` はパッチと drill コンソール、`presets/redteam/` はレッドチームプリセット、`client.js` はドックです。このビルドは `skills/` やナレッジベースを同梱しません。
ランタイムファイルは `$DSH_HOME` 以下にあります: `prompt-inject.md`、`rules/`、`redteam/`。`DSH_HOME` が未設定の場合、ランチャー横の `.dsh` が `~/.dsh` より優先されます。Web とデスクトップアプリはそれぞれ独自のホームを使います。
---
## 使い方
```sh
dsh-purge --status
dsh-purge --apply
dsh-purge --revert
dsh-purge --uninstall
dsh-purge --edit
/purge status | apply | revert | uninstall | edit | help
/rules list | use <id> | create <id> | delete <id> | reset | help
/rewind
# 別のプラグインがすでに /rewind(または /purge, /rules, /skills)を
# 所有している場合、その名前はスキップされるか /purge-rewind として
# 再マウントされます。ほかのコマンド、ツール、/dsh-purge/* ルートは動作し続けます。
purge_status purge_apply purge_revert
```
Apply が成功すると、パッチ済みパッケージを読み込むためホストが再起動します。手動で **Restart** をクリックすることもできます。パッチタイトルの下に安定版とテスト版があります。テスト版は `beta` ブランチに追従します。**Switch to stable** は `master` をインストールしてピンを解除します。古い安定版を選ぶとそれがピン留めされます。最新に戻すには **Update** をクリック。古いテストタグは一覧されません。
コンポーザの **Undo once** と **Undo last round** は現在の会話内に留まり、ブランチを開きません。送信した行が入力に戻り、そのカットですでに送信されたメッセージと完了したタスクは現在の会話から外れます。編集して **再送信** します。**1.1.61** から、rewind の範囲は最初のユーザーメッセージではなく **現在のターン** に従います。`/rewind` も同じ動作です。
**同じタスクが standard では動くのに minimal や PTC で失敗する** 場合、プリセットの `run_code`、サンドボックス、またはプラン傍受テキストがまだクリアされていないことが多く、あるいは組み込み minimal に `agent-instructions` が欠けています。**1.1.61 以降** を使い、**ホストを完全に終了 → Clean で Apply → 再起動 → 新しいチャットを開始** してください。プリセットを切り替えるだけでは、実行中のプロセスのパッチは再読み込みされません。
### 応答速度
DSH はツールバッチ内の Bash 呼び出しを 1 つずつ実行します。古い dsh-purge リリースはデフォルトのフォアグラウンド待機を 60 秒から 10 分に引き上げていたため、1 つの遅いコマンドが後続の呼び出しをその間ブロックしていました。patch #21 は、マークされたプラグインの値を公式の 60 秒デフォルトに戻します。マークされていないタイムアウトやその他のカスタム値は保持されます。マークのない 10 分の値はユーザー設定と確実に区別できません。
`dsh web`(macOS/Linux)で待機を短くするには、`$DSH_HOME/profiles/web/cordis.patch.yml`(通常 `~/.dsh/profiles/web/cordis.patch.yml`)に次のエントリを追加します。重複を追加せず、同じ id の既存エントリを編集してください。このプロファイル層は同梱設定の後に適用されるので、今後のプラグイン Apply でもオーバーライドが維持されます。
```yaml
- id: bash-sandbox
config:
timeoutMs: 10000
```
標準のジョブサービスと `promoteOnTimeout: true` では、未完了のコマンドは 10 秒後にバックグラウンドジョブ id を返し、実行を続けます。`job_output` で読み、`job_kill` で停止します。これはフォアグラウンドの待機を変えるもので、コマンド自体の速度は変わりません。そのサービスが無い、またはプロモーションが無効の場合、タイムアウトでコマンドは終了します。呼び出しごとの `timeoutMs` はこのデフォルトを上書きし、`run_in_background: true` は即座にジョブ id を返します。
日常的なタスクでは、新しいセッションに対して Low 推論を選ぶこともできます:
```yaml
- id: agent-default-model
config:
provider: deepseek-official
model: deepseek-flash
reasoningEffort: low
```
プロファイルを読み込むには `dsh web` を再起動します。モデルと推論のデフォルトは新規作成されるセッションに適用されます。既存のセッションではコンポーザで Low を選択します。プラグインはこれらのモデル設定を自動で変更しません。より深い推論が必要なタスクでは High を保ち、すべてのアプリケーションディレクトリを再帰的にスキャンするのではなくファイル検索を絞ってください。
### ローカルラボ
攻撃タスクはデフォルトで拒否されます。オープンソース版はループバックと RFC1918 IP のみ許可します。名前は先に解決されます。`.lab` / `.htb` サフィックスだけでは不十分です。ラボ名を公開 IP に向ける hosts エントリはブロックされます。チャットで「これは自分のサーバーだ」と言っても許可されません。
---
## ローカルチェック
```sh
node --check lib/index.js
node --check lib/core.js
node --check lib/surface.js
node --check lib/web.js
node --check lib/desktop.js
node --check lib/host.js
node --check lib/rewind.js
node --check lib/skills.js
node --check client.js
```
---
## 仕組み
Apply(起動時または Apply クリック時):
```mermaid
flowchart TD
A["起動または Apply クリック"] --> B{"パッチは既に適用済み?"}
B -->|はい| C["スキップ"]
B -->|いいえ| D["オリジナルを .dshpurge.bak としてバックアップ"]
D --> E["マッチしたファイルを置換"]
E --> F["シムを上書き"]
F --> G["プラグインに同梱された暗号化プロンプト、プロンプトボックスがデフォルトで表示するテキストを注入"]
```
各セッションでのオーバーライド:
```mermaid
flowchart TD
A["再起動または新規セッション"] --> B["プラグインの暗号化デフォルトを注入。保存クリックもホストのプロンプトファイルも無し"]
```
毎ターンのプロンプトインジェクションとルールセット判定。左側の 3 つの入力は dsh-purge パネルで制御するもので、点線の辺はそれぞれがどの判定を駆動するかを示します:
```mermaid
flowchart TD
L["ルールライブラリ: セットを有効化 → prompt-inject.md に書き込み"]
W["ローカルルール: 現在のディレクトリの AGENTS.md / CLAUDE.md を確認"]
P["ワークスペースポリシー: strict / fallback / always"]
A["ターン開始"] --> B{"prompt-inject.md は空でない?"}
B -->|はい| C["Inject = prompt-inject.md (A)"]
B -->|いいえ| D{"現在のディレクトリにチェック済みのローカル md があり、空でない?"}
D -->|はい| E["Inject = 選択したワークスペース md (B)"]
D -->|いいえ| F["Inject = プラグイン暗号化スロットのデフォルト (D)"]
C --> G{"ワークスペースのベースラインポリシー (C)"}
E --> G
F --> G
G -->|strict| H["DSH ワークスペースのベースラインセクションを除外"]
G -->|fallback デフォルト| I{"上記にユーザー inject がある? (A または B)"}
G -->|always| J["DSH ワークスペースのベースラインセクションを保持"]
I -->|はい| H
I -->|いいえ| J
H --> K["最終システムプロンプト"]
J --> K
L -.-> B
W -.-> D
P -.-> G
```
---
## 復元
- 各ターゲットは最初の apply 前に `<file>.dshpurge.bak` にコピーされます。
- **Restore** または `/purge revert` はバックアップを戻して削除します。バックアップが無い場合は、このプラグインが書いたシム行を取り除きます。
- `prompt-inject.md` はユーザーファイルなので保持されます。
- **Uninstall** はパッチが適用されていればまず復元し、その後 inject ファイル、ルールライブラリ、プラグイン本体を削除します。
- Apply は冪等です。
---
## パス検出
まずホストのサーフェスを検出します: `web` / `desktop`(`gui` / `tui` は予約済みで、なお web にフォールバックします)。
**Web:**
1. `DSH_HOME` / `DSH_BASE`
2. dsh ランチャー横の `.dsh`(ポータブルインストール、任意のドライブ)
3. `npm prefix -g` / `npm root -g`
4. ネストした `@deepseek-ai/dsh/node_modules/@deepseek-ai`
5. `~/.dsh`
**公式デスクトップ EXE:** 実行中の公式 Harness インストール(`resources/app` または展開されたパッケージ)。ドライブレターはハードコードされません。成功した Apply は 1 回再起動します。
Community Desktop はメンテナンスされていません。
公式の npm グローバルはパッチされません。封印された `host-commands` / `runtime-commands` はスクラブされ、注入されることはありません。
何も見つからない場合は `DSH_BASE` / `DSH_DESKTOP_INSTALL` を設定してください。ファイルは変更されません。
---
## リリース
作者の個人チャンネル: [t.me/LLM_PoJia](https://t.me/LLM_PoJia)。メモや更新情報はそこに出ます。GitHub [Releases](https://github.com/YuJunZhiXue/dsh-purge/releases) には古いパッケージもあります。オリジナルの転売は禁止、フォークは帰属表示が必須です。
## 備考
- 対象範囲は、ローカルの `@deepseek-ai/*` パッケージ内のレンダリング済みコピー、デフォルト、ランタイムロジック、および harness ホーム以下のオーバーライドファイルとルールセットです。
- アップグレード後、マッチしないオリジナルは skipped と表示されます。Apply はなお完了し、それらのファイルは変更されません。
- `@deepseek-ai` 外のサードパーティプラグインの *ソースリポジトリ* には手を付けません(CMD サイレンスは、インストール済みの doctor / market / liangshen / mnemon を実行時に **ベストエフォートで** パッチすることがあります)。
- GitHub tarball からインストールしてください(名前は npm にありません。プラグインマーケットはスキップ)。`dsh` あり: `dsh plugin --profile web add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master`。pnpm のみ: `$DSH_HOME/profiles/web` 内でその URL を `pnpm add`。EXE には `desktop` を使用。このリポジトリからは `add .`。
---
[LINUX DO](https://linux.do) コミュニティに感謝します
+50 -46
View File
@@ -26,7 +26,7 @@
</p>
<p align="center">
<a href="README.md">English</a> | <a href="README.zh-CN.md">中文</a>
<a href="README.md">English</a> | <a href="README.zh-CN.md">中文</a> | <a href="README.ja.md">日本語</a>
</p>
## A note from the author
@@ -144,30 +144,39 @@ Unmatched patches stay pending or skipped; nothing is rewritten blindly.
## Install
Follow the three steps below. **Do not use the plugin marketplace.** One-click install on [dsh-plugin.org](https://dsh-plugin.org) or in Settings → Plugin Market fails with `already queued: dsh-purge` and never runs a command. The name `dsh-purge` is not on the npm registry; do not `pnpm add dsh-purge`. If this machine only has pnpm, use the pnpm URL in step 2.
**Do not use the plugin marketplace.** One-click install on [dsh-plugin.org](https://dsh-plugin.org) or in Settings → Plugin Market fails with `already queued: dsh-purge` and never runs a command. The name is not on the npm registry, so do not `pnpm add dsh-purge`.
### 1. Which host are you running?
### Quick start
Official `dsh web` and the official desktop EXE are installed and patched **separately**. Only install into the host you actually open.
| What you run | Profile | Command |
|---|---|---|
| Official `dsh web` | `web` | First command below |
| Official desktop EXE | `desktop` | Second command below |
### 2. Add it to the profile (`dsh` or pnpm-only)
Use `codeload.github.com`. Do not use `github.com/.../archive`: that 302 makes pnpm fail with `fetch failed`.
**If you have `dsh`:**
Have `dsh` on PATH? One command, one restart, one click. Run the line for the host you open (the desktop EXE is the same with `desktop` instead of `web`):
```sh
# Official `dsh web`
dsh plugin --profile web add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
# Official desktop EXE
dsh plugin --profile desktop add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
Use `desktop` instead of `web` for the EXE. If this directory is already a clone, use `.` instead of the URL.
1. **Fully quit and reopen** the host you installed into. Web: stop `dsh web` and start it again. Desktop: quit the tray icon too, then open the exe.
2. On that host, click **dsh-purge** beside the session title → **Clean** → **Apply**. A successful Apply restarts the host once.
**pnpm only (no `dsh` required):** run this inside the profile you actually use, not the repo root.
Done — verify with `/purge status` in chat. If pnpm asks about build scripts, or anything below does not appear, follow the step by step.
### Step by step
**Step 1 — Pick your host.** Official `dsh web` and the official desktop EXE are installed and patched **separately**; only install into the host you actually open.
| What you run | Profile | Install command |
|---|---|---|
| Official `dsh web` | `web` | the `web` line in Quick start |
| Official desktop EXE | `desktop` | the `desktop` line in Quick start |
**Step 2 — Install the plugin.** Use the `codeload.github.com` URL exactly. Do not use `github.com/.../archive`: that 302 makes pnpm fail with `fetch failed`.
Have `dsh`? Run the Quick start line for your profile. If this directory is already a clone, use `.` instead of the URL.
pnpm only (no `dsh` required): run this inside the profile you actually use, not the repo root.
```sh
cd "$DSH_HOME/profiles/web" # desktop: profiles/desktop
@@ -181,7 +190,11 @@ cd "$env:USERPROFILE\.dsh\profiles\web" # desktop: profiles\desktop
pnpm add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
`pnpm add` and `dsh plugin add` fetch the package; `postinstall` writes `dsh-purge` into `dsh.profile.bundles` and adds a body `insert` in the profile `cordis.patch.yml`. Without that insert the host never loads the plugin and no button appears. pnpm 11/12 skips install scripts (`ERR_PNPM_IGNORED_BUILDS`) unless you allow the build:
`pnpm add` and `dsh plugin add` fetch the package; `postinstall` writes `dsh-purge` into `dsh.profile.bundles` and adds a body `insert` in the profile `cordis.patch.yml`. Without that insert the host never loads the plugin and no button appears.
**Expected result:** `node_modules/dsh-purge/package.json` exists, `"dsh-purge"` is in that profile's `bundles`, and `cordis.patch.yml` has an `id: dsh-purge` insert.
- pnpm 11/12 skips install scripts (`ERR_PNPM_IGNORED_BUILDS`) unless you allow the build:
```sh
pnpm add --allow-build=dsh-purge --allow-build=dsh-purge@https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
@@ -191,35 +204,25 @@ pnpm approve-builds dsh-purge@https://codeload.github.com/YuJunZhiXue/dsh-purge/
node node_modules/dsh-purge/scripts/ensure-profile-bundle.mjs
```
Success: `node_modules/dsh-purge/package.json` exists, `"dsh-purge"` is in that profile's `bundles`, and `cordis.patch.yml` has an `id: dsh-purge` insert. If neither `dsh` nor pnpm is available, use [Manual install](#manual).
For the desktop client you can also click the button (`dsh://` deep link; it still downloads the same tarball):
- If neither `dsh` nor pnpm is available, jump to [Manual install](#manual).
- On the desktop client you can also click the button (`dsh://` deep link; it still downloads the same tarball).
<p align="center">
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.81&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fcodeload.github.com%2FYuJunZhiXue%2Fdsh-purge%2Ftar.gz%2Frefs%2Fheads%2Fmaster"><strong>Install in desktop client</strong></a>
</p>
### 3. Three more clicks after the command
**Step 3 — Restart the host.** Adding the plugin to a profile does **not** patch `@deepseek-ai` by itself. Fully quit and reopen the host you just installed into (Web: stop `dsh web` and start again; Desktop: quit the tray icon too, then open the exe).
Adding the plugin to a profile does **not** patch `@deepseek-ai` by itself.
**Expected result:** **dsh-purge** stands beside the session title. Missing? Jump to Step 5.
1. **Fully quit and reopen** the host you just installed into. Web: stop `dsh web` and start it again. Desktop: quit the tray icon too, then open the exe.
2. On **that host**, click **dsh-purge** beside the session title, open **Clean**, and click **Apply**. It is not on the host Settings page.
3. A successful **Apply** restarts once. It does not restart if it did not finish.
**Step 4 — Apply and verify.** On **that host**, click **dsh-purge** beside the session title, open **Clean**, and click **Apply**. It is not on the host Settings page. A successful **Apply** restarts once; it does not restart if it did not finish. Web controls affect Web only; desktop controls affect the desktop app only. Do not Apply one host from the other.
Web controls affect Web only; desktop controls affect the desktop app only. Do not Apply one host from the other.
**Expected result:** `/purge status` in chat prints `DSH_HOME` and the patch list — the path should be the home you actually run. Optional packages that are not installed (liangshen) show as skipped and do not block Apply.
### How to tell it installed
**Step 5 — Troubleshooting.** Jump here only when a step above did not end with its expected result.
- **dsh-purge** sits beside the session title, with **Apply** on its Clean page.
- `/purge status` in chat prints `DSH_HOME` and the patch list — the path should be the home you actually run.
- Optional packages that are not installed (liangshen) show as skipped and do not block Apply.
If the button is missing, run `dsh --dump-config` (or `dsh --profile desktop --dump-config`) and look for a body row `id: dsh-purge` (not `dsh-purge-redteam`). If it is absent, run `ensure-profile-bundle.mjs` above, then fully quit and reopen the host. After this version, a live red-team child entry also writes the missing insert on startup — quit and reopen once more. `entry "redteam-store" not found` at the top is leftover from an old red-team package and can be ignored.
### If the market says `already queued: dsh-purge`
Stop clicking the market. Use `dsh plugin add` or pnpm from step 2 again. If the CLI also says it is already there:
- **No button beside the session title.** Run `dsh --dump-config` (or `dsh --profile desktop --dump-config`) and look for a body row `id: dsh-purge` (not `dsh-purge-redteam`). If it is absent, run `ensure-profile-bundle.mjs` (Step 2), then fully quit and reopen the host. After this version, a live red-team child entry also writes the missing insert on startup — quit and reopen once more. `entry "redteam-store" not found` at the top is leftover from an old red-team package and can be ignored.
- **The market says `already queued: dsh-purge`.** Stop clicking the market; use `dsh plugin add` or pnpm from Step 2. If the CLI also says it is already there, remove and re-add, then redo Step 3:
```sh
dsh plugin --profile desktop remove dsh-purge
@@ -234,11 +237,11 @@ pnpm remove dsh-purge
pnpm add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
Swap `desktop` for `web` on Web. Then do step 3.
Swap `desktop` for `web` on Web.
### Hand this to an assistant
### Advanced
Paste the block below to a local assistant. It should only run the install command — no disk scan, no other edits, no Apply, no restart.
**Hand this to an assistant.** Paste the block below to a local assistant. It should only run the install command — no disk scan, no other edits, no Apply, no restart.
<details>
<summary><strong>For AI assistants (install only)</strong></summary>
@@ -271,9 +274,7 @@ After the command finishes, tell the user to fully quit and restart `dsh web`, t
<a id="manual"></a>
### Manual install
Use this when the command fails or `dsh` is not on PATH. Edit **only the profile for the host you run** — do not touch the other, and do not delete existing bundles.
**Manual install.** Use this when the command fails or `dsh` is not on PATH. Edit **only the profile for the host you run** — do not touch the other, and do not delete existing bundles.
<details>
<summary><strong>Full manual steps</strong></summary>
@@ -339,13 +340,14 @@ pnpm install
Success: `profiles/<web|desktop>/node_modules/dsh-purge/package.json` exists. If `pnpm` is missing, use the Node / pnpm shipped with official `dsh`; on `Could not resolve`, re-check the `file:` path; on a JSON error, fix commas or restore the backup.
**5. Fully quit that host, reopen it, then Apply** — same three steps as above. The card appears beside the session title; click **Apply** (or `/purge apply`) on that host only. If the card is missing, you likely edited the other `.dsh` — go back to step 1.
**5. Fully quit that host, reopen it, then Apply** — Step 3 and Step 4 above. The card appears beside the session title; click **Apply** (or `/purge apply`) on that host only. If the card is missing, you likely edited the other `.dsh` — go back to step 1.
</details>
### Uninstall
**Uninstall.** **dsh-purge** beside the session title → **Clean** → **Uninstall**. Confirm the dialog: it reverts any applied patches, restores the original Harness, and restarts the current host. Disable or uninstall also resets an agent-preset default that still points at `redteam` back to `standard`, so the host can create sessions after the preset is gone.
**dsh-purge** beside the session title → **Clean** → **Uninstall**. Confirm the dialog: it reverts any applied patches, restores the original Harness, and restarts the current host. Disable or uninstall also resets an agent-preset default that still points at `redteam` back to `standard`, so the host can create sessions after the preset is gone.
<details>
<summary><strong>Uninstall commands and config</strong></summary>
```sh
# or from a terminal / chat
@@ -369,6 +371,8 @@ Plugin config lives in `cordis.patch.yml` (`postPrompt` is empty by default):
postPrompt: ""
```
</details>
---
## Preview
+50 -46
View File
@@ -26,7 +26,7 @@
</p>
<p align="center">
<a href="README.md">English</a> | <a href="README.zh-CN.md">中文</a>
<a href="README.md">English</a> | <a href="README.zh-CN.md">中文</a> | <a href="README.ja.md">日本語</a>
</p>
## 作者说几句
@@ -146,30 +146,39 @@ Harness 不只是把问题交给模型。它还会在运行时改提示词、审
## 安装
按下面三步走。**不要走插件市场**:[dsh-plugin.org](https://dsh-plugin.org) 或设置里的「插件市场」一键安装会报 `already queued: dsh-purge`,命令也走不成。npm 仓库没有 `dsh-purge` 这个名字,不要 `pnpm add dsh-purge`;本机只有 pnpm 时走第 2 步里的 pnpm 地址。
**不要走插件市场**:[dsh-plugin.org](https://dsh-plugin.org) 或设置里的「插件市场」一键安装会报 `already queued: dsh-purge`,命令也走不成。npm 仓库没有 `dsh-purge` 这个名字,不要 `pnpm add dsh-purge`。
### 1. 看你开的是哪一端
### 快速安装
官方 `dsh web` 和官方桌面 EXE **分开装、分开应用**,只装你正在打开的那一个。
| 你正在用 | profile | 用哪条命令 |
|---|---|---|
| 官方 `dsh web` | `web` | 下面第一条 |
| 官方桌面 EXE | `desktop` | 下面第二条 |
### 2. 装进 profile(有 `dsh` 或只有 pnpm,走一条)
压缩包走 `codeload.github.com`,不要用 `github.com/.../archive`:后者 302,pnpm 会 `fetch failed`。
**有 `dsh`:**
PATH 里有 `dsh`?一条命令、一次重启、一次点击。跑你正在打开那一端的命令(桌面版把 `web` 换成 `desktop`):
```sh
# 官方 `dsh web`
dsh plugin --profile web add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
# 官方桌面 EXE
dsh plugin --profile desktop add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
桌面把 `web` 换成 `desktop`。当前目录已是本仓库时,把网址换成 `.`。
1. **完全退出再打开**刚装的那个宿主。Web:停掉 `dsh web` 再开。桌面:托盘也要退出,再开 exe。
2. 在这个宿主点会话标题旁的 **dsh-purge** →「清洗」→「应用」。应用成功后会自动重启一次。
**只有 pnpm(没有 `dsh` 也行):** 进正在用的那个 profile,不要在仓库根执行。
完成 —— 聊天里跑 `/purge status` 验证。如果 pnpm 问要不要允许构建、或者下面任何东西没出现,走后面的分步说明。
### 分步说明
**第 1 步 —— 选定宿主。** 官方 `dsh web` 和官方桌面 EXE **分开装、分开应用**,只装你正在打开的那一个。
| 你正在用 | profile | 安装命令 |
|---|---|---|
| 官方 `dsh web` | `web` | 快速安装里 `web` 那条 |
| 官方桌面 EXE | `desktop` | 快速安装里 `desktop` 那条 |
**第 2 步 —— 装插件。** 压缩包地址只用 `codeload.github.com` 这个写法,不要用 `github.com/.../archive`:后者 302,pnpm 会 `fetch failed`。
有 `dsh`:跑快速安装里你那一端的命令。当前目录已是本仓库时,把网址换成 `.`。
只有 pnpm(没有 `dsh` 也行):进正在用的那个 profile,不要在仓库根执行。
```sh
cd "$DSH_HOME/profiles/web" # 桌面改 profiles/desktop
@@ -183,7 +192,11 @@ cd "$env:USERPROFILE\.dsh\profiles\web" # 桌面改 profiles\desktop
pnpm add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
`pnpm add` 和 `dsh plugin add` 都会拉包;`postinstall` 再把 `dsh-purge` 写进 `dsh.profile.bundles`,并在用户层 `cordis.patch.yml` 补上本体 `insert`(没有这一行,宿主不加载插件,界面没有按钮)。pnpm 11/12 默认拦安装脚本(`ERR_PNPM_IGNORED_BUILDS`),请带上允许构建,或事后补跑:
`pnpm add` 和 `dsh plugin add` 都会拉包;`postinstall` 再把 `dsh-purge` 写进 `dsh.profile.bundles`,并在 profile 的 `cordis.patch.yml` 补上本体 `insert`(没有这一行,宿主不加载插件,界面也没有按钮)。
**完成标志:** `node_modules/dsh-purge/package.json` 在,该 profile 的 `bundles` 里有 `"dsh-purge"`,`cordis.patch.yml` 里有 `id: dsh-purge` 的 insert。
- pnpm 11/12 默认拦安装脚本(`ERR_PNPM_IGNORED_BUILDS`),要带上允许构建:
```sh
pnpm add --allow-build=dsh-purge --allow-build=dsh-purge@https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
@@ -193,35 +206,25 @@ pnpm approve-builds dsh-purge@https://codeload.github.com/YuJunZhiXue/dsh-purge/
node node_modules/dsh-purge/scripts/ensure-profile-bundle.mjs
```
成功标志:`node_modules/dsh-purge/package.json` 在,profile 的 `bundles` 里有 `"dsh-purge"`,`cordis.patch.yml` 里有 `id: dsh-purge` 的 insert。`dsh` 和 pnpm 都没有时走 [手动安装](#manual)。
桌面客户端也可以点按钮(`dsh://` 唤起,下的仍是同一份压缩包):
- `dsh` 和 pnpm 都没有时,跳到[手动安装](#manual)。
- 桌面客户端也可以点按钮(`dsh://` 唤起,下的仍是同一份压缩包)。
<p align="center">
<a href="dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.81&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fcodeload.github.com%2FYuJunZhiXue%2Fdsh-purge%2Ftar.gz%2Frefs%2Fheads%2Fmaster"><strong>唤起客户端一键安装</strong></a>
</p>
### 3. 装完还要做这三下
**第 3 步 —— 重启宿主。** 只把插件写进 profile **还不会**改 `@deepseek-ai`。完全退出再打开刚装的那个宿主(Web:停掉 `dsh web` 再开;桌面:托盘也要退出,再开 exe)。
只把插件写进 profile **还不会**改 `@deepseek-ai`。
**完成标志:** 会话标题旁出现 **dsh-purge**。没出现?跳到第 5 步。
1. **完全退出再打开**刚装的那个宿主。Web:停掉 `dsh web` 再开。桌面:托盘也要退出,再开 exe。
2. 在**这个宿主**点会话标题旁的 **dsh-purge**,打开 **清洗**,点 **「应用」**。宿主自己的设置页里没有这一项。
3. 「应用」成功后会自动重启一次。没做完不会重启。
**第 4 步 —— 应用并验证。** 在**这个宿主**点会话标题旁的 **dsh-purge**,打开「清洗」,点「应用」。宿主自己的设置页里没有这一项。应用成功后会自动重启一次,没做完不会重启。Web 的按钮只动 Web,桌面的只动桌面,不要在一个里面点另一个的应用。
Web 的按钮只动 Web,桌面的只动桌面。不要在一个里面点另一个的应用。
**完成标志:** 聊天里 `/purge status` 能打出 `DSH_HOME` 和补丁列表,路径是你正在用的那一份。没装的可选包(梁神)显示跳过,不挡住完成。
### 怎样算装上了
**第 5 步 —— 排障。** 只有上面没有跑到「完成标志」时才看这里。
- 会话标题旁有 **dsh-purge**,清洗页能点「应用」。
- 聊天里 `/purge status` 能打出 `DSH_HOME` 和补丁列表,路径是你正在用的那一份。
- 没装的可选包(例如梁神)显示跳过,不挡住完成。
没有按钮时,在对应 profile 跑 `dsh --dump-config`(或 `dsh --profile desktop --dump-config`),看有没有本体行 `id: dsh-purge`(不是 `dsh-purge-redteam`)。没有就再跑上面的 `ensure-profile-bundle.mjs`,然后完全退出重开宿主。升到本版本后,若演练台子行已经在跑,它也会在启动时把缺的 insert 补上,再完全退出重开一次即可。开头那几条 `entry "redteam-store" not found` 只是旧红队包不在,可以忽略。
### 市场报 `already queued: dsh-purge` 时
不要再点市场。按第 2 步用 `dsh plugin add` 或 pnpm 再装一遍。命令也说已经有了,就先卸再装:
- **会话标题旁没有按钮。** 在对应 profile 跑 `dsh --dump-config`(或 `dsh --profile desktop --dump-config`),看有没有本体行 `id: dsh-purge`(不是 `dsh-purge-redteam`)。没有就再跑第 2 步的 `ensure-profile-bundle.mjs`,然后完全退出重开宿主。升到本版本后,若演练台子行已经在跑,它也会在启动时把缺的 insert 补上,再完全退出重开一次即可。开头那几条 `entry "redteam-store" not found` 只是旧红队包不在,可以忽略。
- **市场报 `already queued: dsh-purge`。** 不要再点市场;回到第 2 步用 `dsh plugin add` 或 pnpm 装。命令也说已经有了,就先卸再装,然后重走第 3 步:
```sh
dsh plugin --profile desktop remove dsh-purge
@@ -236,11 +239,11 @@ pnpm remove dsh-purge
pnpm add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master
```
Web 把 `desktop` 换成 `web`。然后再走第 3 步。
Web 端把 `desktop` 换成 `web`。
### 交给助手安装
### 高级
把下面整段发给本机助手。它只执行安装命令:不要全盘搜索、不要改其它文件、不要代点「应用」、不要重启。
**交给助手安装。** 把下面整段发给本机助手。它只执行安装命令:不要全盘搜索、不要改其它文件、不要代点「应用」、不要重启。
<details>
<summary><strong>给 AI 助手(只安装)</strong></summary>
@@ -273,9 +276,7 @@ pnpm add https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/mas
<a id="manual"></a>
### 手动安装
命令行装不上、或 `dsh` 不在 PATH 时用这个。只改**正在用的那个宿主**对应的 profile,不要动另一个,也不要删原有 bundle。
**手动安装。** 命令装不上、或 `dsh` 不在 PATH 时用这个。只改**正在用的那个宿主**对应的 profile,不要动另一个,也不要删原有 bundle。
<details>
<summary><strong>完整手动步骤</strong></summary>
@@ -341,13 +342,14 @@ pnpm install
成功标志:出现 `profiles/<web|desktop>/node_modules/dsh-purge/package.json`。找不到 `pnpm` 就用官方 `dsh` 自带的 Node / pnpm;报 `Could not resolve` 就检查 `file:` 路径;JSON 解析失败就修逗号或还原备份。
**5. 完全退出该宿主,再启动,再点「应用」** —— 和上面三步一样。按钮会出现在会话标题旁,只在这个宿主点「应用」(或 `/purge apply`)。没出现多半是改错了另一份 `.dsh`,回到第 1 步核对。
**5. 完全退出该宿主,再启动,再点「应用」** —— 即第 3 步和第 4 步。按钮会出现在会话标题旁,只在这个宿主点「应用」(或 `/purge apply`)。没出现多半是改错了另一份 `.dsh`,回到第 1 步核对。
</details>
### 卸载
**卸载。** 会话标题旁的 **dsh-purge** →「清洗」→「卸载」。弹窗确认:会先还原已应用的补丁,还原回原版 Harness,再重启当前宿主。停用或卸载时会把「智能体预设」里指向红队模式的默认值改回 `standard`,避免宿主因找不到 `redteam` 而无法新建会话。
会话标题旁的 **dsh-purge** →「清洗」→「卸载」。弹窗确认:会先还原已应用的补丁,还原回原版 Harness,再重启当前宿主。停用或卸载时会把「智能体预设」里指向红队模式的默认值改回 `standard`,避免宿主因找不到 `redteam` 而无法新建会话。
<details>
<summary><strong>卸载命令与配置</strong></summary>
```sh
# 也可以用命令行 / 聊天
@@ -371,6 +373,8 @@ dsh-purge --uninstall
postPrompt: ""
```
</details>
---
## 界面预览
+7 -2
View File
@@ -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("");
+16 -4
View File
@@ -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
View File
@@ -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
View File
@@ -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) => ({
+178 -30
View File
@@ -1,8 +1,11 @@
/**
* 用户层 profile/cordis.patch.yml 的本体 insert(#154 / #159)。
* 用户层 profile/cordis.patch.yml 的本体 insert(#154 / #159 / #191)。
*
* 包内 overlay 只改已入队行的 inject/config,不能再 insert 一次(Hub 已入队会
* already queued)。postinstall 和演练台子行都走这里:行不存在就写一条。
*
* #191:文件本身是一个完整文档时(宿主生成的空 flow 序列 `[]`),不能再追加,
* 追加会变成第二个文档,宿主启动解析失败。
*/
import fs from "node:fs";
import path from "node:path";
@@ -47,6 +50,52 @@ export function profileHasPurgeBodyInsert(text) {
return false;
}
/**
* 判断 cordis.patch.yml 的数据部分形态(#191)。
*
* 宿主生成的 profile 层 patch 文件可能整体只有一个空 flow 序列 `[]`,
* 那是**一个完整 YAML 文档**。往文件尾追加 `- insert:` 会变成第二个文档,
* 宿主启动解析报 "end of the stream or a document separator is expected"。
*
* 只看最后一个文档的根节点类型(追加内容落在最后一个文档里):
* - "empty" 没有数据行(空文件 / 只有注释和空行)
* - "empty-flow" 数据部分恰好是空 flow 序列 `[]`(可带 `---` 前缀)
* - "block-seq" 正常块序列(顶层 `- ...`),沿用旧的追加行为
* - "flow-seq" 非空 flow 序列(宿主/用户内容,动不得)
* - "unknown" 其它形态(顶层映射等),认不准就不写
*/
export function classifyPatchBody(text) {
const lines = String(text || "").replace(/\r\n/g, "\n").split("\n");
const dataLines = [];
for (let i = 0; i < lines.length; i += 1) {
const trimmed = lines[i].trim();
if (!trimmed) continue; // 空行
if (trimmed.startsWith("#")) continue; // 注释行
dataLines.push({ index: i, trimmed });
}
// 按 `---` 切成多个文档,只看最后一个(追加内容会落在最后一个文档里)
const lastDoc = [];
for (const item of dataLines) {
if (item.trimmed === "---") {
lastDoc.length = 0;
continue;
}
lastDoc.push(item);
}
if (lastDoc.length === 0) return { kind: "empty", lines };
// 空 flow 序列:`[]` / `[ ]`,允许行尾注释
if (lastDoc.length === 1 && /^\[\s*\]\s*(#.*)?$/.test(lastDoc[0].trimmed)) {
return { kind: "empty-flow", lines, emptyFlowIndex: lastDoc[0].index };
}
if (lastDoc[0].trimmed.startsWith("[")) return { kind: "flow-seq", lines };
if (/^-(\s|$)/.test(lastDoc[0].trimmed)) {
// 块序列里混进顶层 flow 序列 → 本身就是坏 YAML,认不准就不动
if (lastDoc.slice(1).some((item) => item.trimmed.startsWith("["))) return { kind: "unknown", lines };
return { kind: "block-seq", lines };
}
return { kind: "unknown", lines };
}
export function ensureProfileBodyInsert(profileDir) {
const fp = path.join(profileDir, "cordis.patch.yml");
let text = "";
@@ -54,6 +103,23 @@ export function ensureProfileBodyInsert(profileDir) {
if (profileHasPurgeBodyInsert(text)) {
return { ok: true, wrote: false, path: fp };
}
const shape = classifyPatchBody(text);
if (shape.kind === "empty-flow") {
// `[]` 本身是一个完整文档:把整行替换成 insert 块,绝不追加成第二个文档(#191)
const blockLines = INSERT_BLOCK.replace(/\n$/, "").split("\n");
const out = [
...shape.lines.slice(0, shape.emptyFlowIndex),
...blockLines,
...shape.lines.slice(shape.emptyFlowIndex + 1),
].join("\n");
fs.writeFileSync(fp, `${out.endsWith("\n") ? out : `${out}\n`}`, "utf8");
return { ok: true, wrote: true, path: fp };
}
if (shape.kind === "flow-seq" || shape.kind === "unknown") {
// 宿主 / 用户自己的内容,宁可不动也别写坏(#191)
return { ok: false, wrote: false, path: fp };
}
// 空文件 / 只有注释 → 直接写 insert 块;正常块序列 → 沿用旧的追加行为
const prefix = text && !text.endsWith("\n") ? "\n" : "";
fs.writeFileSync(fp, `${text}${prefix}${text ? "\n" : ""}${INSERT_BLOCK}`, "utf8");
return { ok: true, wrote: true, path: fp };
@@ -105,21 +171,18 @@ export function ensureProfileBundles(profileDir) {
return { ok: true, wrote: true, path: fp };
}
function readPurgeTarball() {
try {
const pkg = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
return String(pkg?.dsh?.install?.tarball || "").trim();
} catch {
return "https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master";
}
}
/** pnpm 12 会给 tarball 单独写一行 `dsh-purge@https://...: set this to true or false`。只写包名不够。 */
export function purgePnpmBuildSpecs() {
const specs = ["dsh-purge"];
const tarball = readPurgeTarball();
if (tarball) specs.push(`${PURGE_NAME}@${tarball}`);
return specs;
/**
* pnpm allowBuilds 期望键(#185)。
*
* 只写裸包名 `dsh-purge`:pnpm 的 allowBuilds 按包名匹配,tarball / git / registry
* 三种安装形态都放行。而 `dsh-purge@https://...` 这类键在 pnpm 11(DSH 内置
* 11.2.2)会被 semver 解析器当成版本联合,直接报
* `[ERR_PNPM_INVALID_VERSION_UNION] Invalid versions union` 让 install 崩掉。
*
* profileDir 参数只为兼容旧调用保留,实际不再需要(#185)。
*/
export function purgePnpmBuildSpecs(profileDir) {
return [PURGE_NAME];
}
function isPurgeAllowBuildKey(key) {
@@ -127,22 +190,92 @@ function isPurgeAllowBuildKey(key) {
return name === PURGE_NAME || name.startsWith(`${PURGE_NAME}@`);
}
function parseAllowBuildLine(line) {
const m = String(line || "").match(/^[ \t]+(?:"([^"]+)"|'([^']+)'|(\S+?))[ \t]*:[ \t]*(.*?)\s*$/);
if (!m) return null;
return { key: m[1] || m[2] || m[3], value: String(m[4] || "").trim() };
/** 导出仅供单测 round-trip(#180)。 */
export function parseAllowBuildLine(line) {
const text = String(line || "").replace(/\r$/, "");
// 引号包裹:键整段取出,URL 里的冒号不会切碎键
const quoted = text.match(/^[ \t]+(?:"([^"]+)"|'([^']+)')[ \t]*:[ \t]*(.*?)\s*$/);
if (quoted) return { key: quoted[1] !== undefined ? quoted[1] : quoted[2], value: String(quoted[3] || "").trim() };
// 未加引号的键:要求有缩进(顶层键不算),只在「冒号+空白(或行尾)」处切分,且取最后一次出现的位置——
// URL 里的 `:` 后面跟的是 `/`,不会断键;`dsh-purge@https: true`(畸形历史键)也能正常切成键+值(#180)
if (!/^[ \t]+/.test(text)) return null;
let split = -1;
for (let i = 0; i < text.length; i += 1) {
if (text[i] !== ":") continue;
if (i + 1 >= text.length || /[ \t]/.test(text[i + 1])) split = i;
}
if (split < 0) return null;
const key = text.slice(0, split).trim();
if (!key) return null;
return { key, value: text.slice(split + 1).trim() };
}
function formatAllowBuildLine(key) {
return ` ${key}: true`;
/** 导出仅供单测 round-trip(#180)。 */
export function formatAllowBuildLine(key) {
const name = String(key || "");
// 含 `://` 的 URL 键加引号,避免 YAML 把 URL 里的冒号当分隔符(#180)
if (name.includes("://")) return ` ${JSON.stringify(name)}: true`;
return ` ${name}: true`;
}
/** 把 dsh-purge 以及 `dsh-purge@tarball` 都写成 true,避免装别的插件还报 ERR_PNPM_IGNORED_BUILDS(#168)。 */
export function rewritePnpmAllowBuilds(raw) {
const wanted = purgePnpmBuildSpecs();
/**
* 重写前做最小校验:顶层键、allowBuilds 段内键都不重复,每个键写回格式都能被
* parseAllowBuildLine 无损还原。校验不过就不写盘,宁可不动用户的文件(#180)。
* 导出仅供单测(#180)。
*/
export function validateAllowBuildRewrite(text) {
const lines = String(text || "").split("\n");
let inAllow = false;
let allowIndent = -1;
const topKeys = new Set();
const allowKeys = new Set();
for (const line of lines) {
if (!line.trim()) continue;
const trimmed = line.trim();
if (trimmed.startsWith("#")) continue; // 注释行原样保留,不参与校验
if (/^\S/.test(line)) {
inAllow = /^allowBuilds[ \t]*:/.test(line);
allowIndent = -1;
const m = line.match(/^(\S+?)[ \t]*:/);
if (!m) return false;
if (topKeys.has(m[1])) return false;
topKeys.add(m[1]);
continue;
}
if (!inAllow) continue;
const indent = (line.match(/^[ \t]*/) || [""])[0].length;
if (allowIndent < 0) allowIndent = indent;
if (indent < allowIndent) {
// 缩进回到 allowBuilds 的子键层级以上,说明段已结束
inAllow = false;
continue;
}
const parsed = parseAllowBuildLine(line);
if (!parsed || !parsed.key) return false;
const name = parsed.key;
if (allowKeys.has(name)) return false;
// 写回后的行必须能无损解析出同一个键
if (parseAllowBuildLine(formatAllowBuildLine(name))?.key !== name) return false;
allowKeys.add(name);
}
return true;
}
/**
* 把 dsh-purge 写成 true,避免装别的插件还报 ERR_PNPM_IGNORED_BUILDS(#168)。
*
* #185:只写裸包名。`dsh-purge@https://...` 这类键在 pnpm 11 会被当成版本联合,
* 直接触发 ERR_PNPM_INVALID_VERSION_UNION 让 install 崩掉。
* 自愈时所有 `dsh-purge@*` 历史键(URL 键、旧截断键 `dsh-purge@https`、
* `@1.1.81` 之类版本键)一律丢弃,只保留裸包名;非 purge 键原样保留。
*/
export function rewritePnpmAllowBuilds(raw, profileDir) {
const wanted = purgePnpmBuildSpecs(profileDir);
const wantedSet = new Set(wanted);
const text = String(raw || "").replace(/\r\n/g, "\n");
const wantedBlock = wanted.map(formatAllowBuildLine);
if (!text.trim()) {
return `allowBuilds:\n${wanted.map(formatAllowBuildLine).join("\n")}\n`;
return `allowBuilds:\n${wantedBlock.join("\n")}\n`;
}
const lines = text.split(/\r?\n/);
let start = -1;
@@ -154,7 +287,7 @@ export function rewritePnpmAllowBuilds(raw) {
}
if (start < 0) {
const prefix = text.endsWith("\n") ? "" : "\n";
return `${text}${prefix}\nallowBuilds:\n${wanted.map(formatAllowBuildLine).join("\n")}\n`;
return `${text}${prefix}\nallowBuilds:\n${wantedBlock.join("\n")}\n`;
}
let end = lines.length;
const kept = [];
@@ -169,20 +302,33 @@ export function rewritePnpmAllowBuilds(raw) {
end = i;
break;
}
const trimmed = line.trim();
if (trimmed.startsWith("#")) {
kept.push(line);
continue;
}
const parsed = parseAllowBuildLine(line);
if (!parsed) {
kept.push(line);
continue;
}
if (isPurgeAllowBuildKey(parsed.key)) {
// 只保留精确等于期望键的行,且去重;其余历史 purge 键丢弃(#180 自愈)
if (!wantedSet.has(parsed.key) || seen.has(parsed.key)) continue;
kept.push(formatAllowBuildLine(parsed.key));
seen.add(parsed.key);
continue;
}
// 非 purge 键原样保留;同键重复(会让 pnpm 报 duplicated mapping key)只留第一份
if (seen.has(parsed.key)) continue;
seen.add(parsed.key);
kept.push(line);
}
for (const key of wanted) {
if (!seen.has(key)) kept.push(formatAllowBuildLine(key));
for (let i = 0; i < wanted.length; i += 1) {
if (!seen.has(wanted[i])) {
kept.push(wantedBlock[i]);
seen.add(wanted[i]);
}
}
const next = [...lines.slice(0, start + 1), ...kept, ...lines.slice(end)].join("\n");
return next.endsWith("\n") ? next : `${next}\n`;
@@ -194,8 +340,10 @@ export function ensurePnpmAllowBuild(profileDir) {
let text = "";
try { text = fs.readFileSync(fp, "utf8"); } catch { text = ""; }
const current = String(text || "").replace(/\r\n/g, "\n");
const next = rewritePnpmAllowBuilds(current);
const next = rewritePnpmAllowBuilds(current, profileDir);
if (next === current) return { ok: true, wrote: false, path: fp };
// 写前校验不过就不写盘,宁可保持现状(#180)
if (!validateAllowBuildRewrite(next)) return { ok: false, wrote: false, path: fp, reason: "allowBuilds-invalid" };
fs.writeFileSync(fp, next, "utf8");
return { ok: true, wrote: true, path: fp };
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dsh-purge",
"version": "1.1.81",
"version": "1.1.83",
"description": "DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model — swap prompts per model. 求 Star 收藏 ⭐ 如要二开,请查看署名要求部分",
"type": "module",
"main": "lib/index.js",
+46
View File
@@ -1,3 +1,49 @@
# 1.1.83
## 中文
- 版本 **1.1.83**。修复 bug,修复稳定性。
- **#185**:修复 pnpm 11(DSH 内置 11.2.2)下 `pnpm install` 因 `allowBuilds` 崩溃的问题。
- 之前 profile 的 `pnpm-workspace.yaml` 会写入 `dsh-purge@https://...` 这类 URL 键,pnpm 把它当版本联合解析,直接报 `[ERR_PNPM_INVALID_VERSION_UNION] Invalid versions union`。
- 现在只写裸包名 `dsh-purge`:pnpm 的 `allowBuilds` 本来就按包名匹配,tarball / git / registry 三种安装形态都放行。
- 自愈加强:所有 `dsh-purge@*` 历史键(URL 键、旧截断键 `dsh-purge@https`、`@1.1.81` 之类版本键)一律清掉,只保留裸包名;非 dsh-purge 的键原样保留。
- **#191**:修复 macOS DSH Desktop(0.2.1-rc.4)启动崩溃 `failed to parse overlay .../cordis.patch.yml`。
- 宿主生成的 profile 层 `cordis.patch.yml` 可能整体只有一个空 flow 序列 `[]`,那本身就是一个完整 YAML 文档;再往文件尾追加 `- insert:` 会变成第二个文档,宿主解析直接失败。
- 现在写之前先判断数据部分形态:空 flow 序列(`[]`,可带 `---` 前缀)→ **替换** `[]` 整行而不是追加;空文件 / 只有注释 → 直接写 insert 块;正常块序列 → 沿用原来的追加行为。
- 非空 flow 序列(宿主或用户自己的内容)认不准就不动,返回 `{ ok: false, wrote: false }`,宁可留着也不写坏。
## English
- **1.1.83**. Bug fixes and stability.
- **#185**: fix `pnpm install` crashing under pnpm 11 (11.2.2, bundled with DSH) because of `allowBuilds`.
- The profile `pnpm-workspace.yaml` used to get a `dsh-purge@https://...` URL key, which pnpm parses as a version union and rejects with `[ERR_PNPM_INVALID_VERSION_UNION] Invalid versions union`.
- Now only the bare package name `dsh-purge` is written: pnpm matches `allowBuilds` by package name, so tarball / git / registry installs are all allowed.
- Stronger self-healing: every `dsh-purge@*` legacy key (URL keys, truncated `dsh-purge@https`, `@1.1.81`-style version keys) is dropped and only the bare name is kept; non-dsh-purge keys are preserved as-is.
- **#191**: fix the macOS DSH Desktop (0.2.1-rc.4) startup crash `failed to parse overlay .../cordis.patch.yml`.
- The host-generated profile `cordis.patch.yml` may consist of a single empty flow sequence `[]`, which is already a complete YAML document; appending `- insert:` after it creates a second document and the host fails to parse it.
- The data shape is now detected before writing: an empty flow sequence (`[]`, optionally `---`-prefixed) → **replace** the `[]` line instead of appending; empty file / comments only → write the insert block; a normal block sequence → the previous append behaviour is kept.
- A non-empty flow sequence (host or user content) is left alone and returns `{ ok: false, wrote: false }` — better to skip than to write something broken.
# 1.1.82
## 中文
- 版本 **1.1.82**。修复 bug,修复稳定性。
- **#180**:修复 profile 的 `pnpm-workspace.yaml` `allowBuilds` 被反复写坏(`dsh-purge@https: true` 畸形键 → `ERR_PNPM_INVALID_VERSION_UNION`,重复键 → `duplicated mapping key`)。
- URL 键解析不再被冒号截断;写回含 `://` 的键自动加引号。
- 重写只保留精确等于期望键的 `dsh-purge@*`,旧污染键(畸形的、过期的版本/commit URL)自动清掉,不用手工修。
- 期望键优先从 profile 的 `pnpm-lock.yaml` 读实际解析的 tarball URL(固定 commit 安装也不再有双 URL 键),读不到才退回 `package.json`。
- 重写结果先过最小 YAML 校验(键不重复、round-trip 无损),不过就不写盘;健康文件零写入,启动不再反复重写。
## English
- **1.1.82**. Bug fixes and stability.
- **#180**: stop rewriting the profile `pnpm-workspace.yaml` `allowBuilds` into garbage (`dsh-purge@https: true` malformed key → `ERR_PNPM_INVALID_VERSION_UNION`; duplicated keys → `duplicated mapping key`).
- URL keys no longer truncate at the first colon; keys containing `://` are written back quoted.
- Rewrites keep only `dsh-purge@*` keys exactly equal to the wanted set; stale polluted keys (malformed, old version/commit URLs) self-heal away on the next ensure.
- The wanted key prefers the tarball URL actually resolved in the profile `pnpm-lock.yaml` (fixed-commit installs no longer get a duplicate URL key); falls back to `package.json`.
- Rewritten output passes a minimal YAML check first (no duplicate keys, lossless round-trip); healthy files are never written again, so boot no longer rewrites each run.
# 1.1.81
## 中文
+3
View File
@@ -51,6 +51,9 @@ function ensureProfileInsert(profileDir) {
const result = ensureProfileBodyInsert(profileDir);
if (result.wrote) {
process.stdout.write(`dsh-purge: wrote body insert (${result.path})\n`);
} else if (result.ok === false) {
// 宿主 / 用户自己的 cordis.patch.yml 内容,宁可不动也别写坏(#191)
process.stdout.write(`dsh-purge: skipped body insert, unrecognized patch body (${result.path})\n`);
} else {
process.stdout.write(`dsh-purge: insert already in ${result.path}\n`);
}
+254
View File
@@ -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: [] });
});
+360
View File
@@ -0,0 +1,360 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
parseAllowBuildLine,
formatAllowBuildLine,
validateAllowBuildRewrite,
purgePnpmBuildSpecs,
rewritePnpmAllowBuilds,
ensurePnpmAllowBuild,
ensureProfileBodyInsert,
classifyPatchBody,
INSERT_BLOCK,
} from "../lib/profile-insert.js";
const MASTER_URL = "https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/refs/heads/master";
const COMMIT_URL = "https://codeload.github.com/YuJunZhiXue/dsh-purge/tar.gz/abc1234567890";
function withTempProfile(lockText) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dsh-purge-test-"));
if (lockText !== undefined) {
fs.writeFileSync(path.join(dir, "pnpm-lock.yaml"), lockText, "utf8");
}
return dir;
}
function withTempPatch(content) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dsh-purge-patch-"));
if (content !== undefined) {
fs.writeFileSync(path.join(dir, "cordis.patch.yml"), content, "utf8");
}
return dir;
}
/** 去掉注释和空行后,统计顶层 `- insert:` 组数(判定是不是第二个文档)。 */
function topLevelInsertGroups(text) {
const lines = String(text || "").split(/\r?\n/);
let count = 0;
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
if (/^-\s*insert:\s*$/.test(line)) count += 1;
}
return count;
}
test("URL 键解析不被冒号截断", () => {
const parsed = parseAllowBuildLine(` dsh-purge@${MASTER_URL}: true`);
assert.equal(parsed.key, `dsh-purge@${MASTER_URL}`);
assert.equal(parsed.value, "true");
});
test("畸形键也解析成整键(自愈时统一丢弃)", () => {
assert.deepEqual(parseAllowBuildLine(" dsh-purge@https: true"), {
key: "dsh-purge@https",
value: "true",
});
assert.deepEqual(parseAllowBuildLine(" dsh-purge@1.1.81: true"), {
key: "dsh-purge@1.1.81",
value: "true",
});
});
test("行尾没有值的 `key:` 解析为空值", () => {
assert.deepEqual(parseAllowBuildLine(" dsh-purge@https:"), {
key: "dsh-purge@https",
value: "",
});
assert.deepEqual(parseAllowBuildLine(" dsh-purge:"), {
key: "dsh-purge",
value: "",
});
});
test("引号包裹的键照旧解析", () => {
const spec = `dsh-purge@${MASTER_URL}`;
for (const line of [` "${spec}": true`, ` '${spec}': true`]) {
assert.deepEqual(parseAllowBuildLine(line), { key: spec, value: "true" });
}
});
test("URL 键写回带引号且 round-trip 无损", () => {
const spec = `dsh-purge@${MASTER_URL}`;
const line = formatAllowBuildLine(spec);
assert.equal(line, ` "${spec}": true`);
assert.deepEqual(parseAllowBuildLine(line), { key: spec, value: "true" });
// 不含 URL 的键保持无引号,round-trip 同样无损
const plain = formatAllowBuildLine("dsh-purge");
assert.equal(plain, " dsh-purge: true");
assert.deepEqual(parseAllowBuildLine(plain), { key: "dsh-purge", value: "true" });
});
test("污染的 allowBuilds 重写后只剩期望键", () => {
const polluted = [
"packages:",
" - '.'",
"",
"allowBuilds:",
" cpu-features: true",
" ssh2: true",
" dsh-purge: true",
" dsh-purge@1.1.81: true",
" dsh-purge@https: true",
" dsh-purge@https: true",
` dsh-purge@${MASTER_URL}: true`,
"",
].join("\n");
const next = rewritePnpmAllowBuilds(polluted);
const keys = next.split("\n").filter((line) => parseAllowBuildLine(line)).map((line) => parseAllowBuildLine(line).key);
// 期望键:只有裸包名(#185,不再写 URL 键)
const wanted = ["cpu-features", "ssh2", ...purgePnpmBuildSpecs()];
assert.deepEqual([...new Set(keys)], wanted);
// 畸形历史键一个都不留
for (const bad of [`dsh-purge@1.1.81`, `dsh-purge@https`]) {
assert.equal(keys.includes(bad), false, `should drop ${bad}`);
}
// 重复出现过的 `dsh-purge@https` 只允许来自 wanted 精确键,且不重复
assert.equal(keys.filter((key) => key.startsWith("dsh-purge")).length, purgePnpmBuildSpecs().length);
// 保留段的结构仍然合法
assert.equal(validateAllowBuildRewrite(next), true);
});
test("非 purge 键原样保留,无 allowBuilds 段时追加", () => {
const base = "packages:\n - '.'\n";
const next = rewritePnpmAllowBuilds(base);
assert.equal(next.startsWith("packages:\n - '.'\n\nallowBuilds:\n"), true);
// 追加的是期望键(裸包名 + package.json 的 tarball)
for (const spec of purgePnpmBuildSpecs()) {
const escaped = formatAllowBuildLine(spec).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
assert.match(next, new RegExp(`^${escaped}$`, "m"));
}
const withSection = "allowBuilds:\n cpu-features: true\n ssh2: true\n";
const next2 = rewritePnpmAllowBuilds(withSection);
assert.match(next2, /^ {2}cpu-features: true$/m);
assert.match(next2, /^ {2}ssh2: true$/m);
});
test("写前校验:重复顶层键 / 重复 allowBuilds 键 / 解析不了的行判无效", () => {
assert.equal(validateAllowBuildRewrite("packages:\n - '.'\n\npackages:\n - \"..\"\n"), false);
assert.equal(validateAllowBuildRewrite("allowBuilds:\n cpu-features: true\n cpu-features: true\n"), false);
// 没有键值分隔的裸行解析不出来,校验必须挡下
assert.equal(validateAllowBuildRewrite("allowBuilds:\n 不是键值对\n"), false);
assert.equal(validateAllowBuildRewrite("allowBuilds:\n# 注释行放行\n ssh2: true\n"), true);
});
test("期望键只有裸包名,不含任何 URL 键(#185)", () => {
// pnpm 11 遇到 `dsh-purge@https://...` 会报 ERR_PNPM_INVALID_VERSION_UNION,
// allowBuilds 按包名匹配即可,tarball / git / registry 安装都放行
assert.deepEqual(purgePnpmBuildSpecs(), ["dsh-purge"]);
const dir = withTempProfile([
"lockfileVersion: '9.0'",
"",
"importers:",
"",
" .:",
" dependencies:",
" dsh-purge:",
` specifier: ${COMMIT_URL}`,
` version: dsh-purge@${COMMIT_URL}`,
"",
].join("\n"));
assert.deepEqual(purgePnpmBuildSpecs(dir), ["dsh-purge"]);
});
test("输入只含 URL 键时重写后只剩裸包名", () => {
const onlyUrl = [
"allowBuilds:",
` "dsh-purge@${MASTER_URL}": true`,
` dsh-purge@${MASTER_URL}: true`,
"",
].join("\n");
const next = rewritePnpmAllowBuilds(onlyUrl);
const keys = next.split("\n").filter((line) => parseAllowBuildLine(line)).map((line) => parseAllowBuildLine(line).key);
assert.deepEqual(keys, ["dsh-purge"]);
assert.equal(next.includes("dsh-purge@"), false);
assert.equal(next.split("\n").some((line) => line === " dsh-purge: true"), true);
assert.equal(validateAllowBuildRewrite(next), true);
});
test("固定 commit 安装:重写后只剩裸包名,历史 URL / 畸形键全清", () => {
const dir = withTempProfile([
"lockfileVersion: '9.0'",
"",
"importers:",
"",
" .:",
" dependencies:",
" dsh-purge:",
` specifier: ${COMMIT_URL}`,
` version: dsh-purge@${COMMIT_URL}`,
"",
].join("\n"));
const polluted = [
"packages:",
" - '.'",
"",
"allowBuilds:",
" ssh2: true",
` dsh-purge@${MASTER_URL}: true`,
` "dsh-purge@${COMMIT_URL}": true`,
" dsh-purge@https: true",
"",
].join("\n");
const next = rewritePnpmAllowBuilds(polluted, dir);
const keys = next.split("\n").filter((line) => parseAllowBuildLine(line)).map((line) => parseAllowBuildLine(line).key);
assert.equal(keys.includes("dsh-purge"), true);
assert.equal(keys.includes(`dsh-purge@${COMMIT_URL}`), false);
assert.equal(keys.includes(`dsh-purge@${MASTER_URL}`), false);
assert.equal(keys.includes("dsh-purge@https"), false);
assert.equal(keys.includes("ssh2"), true);
// 只写裸包名,不带引号
assert.equal(next.split("\n").some((line) => line === " dsh-purge: true"), true);
});
test("幂等:健康文件重写输出等于输入,零写入", () => {
const dir = withTempProfile();
const fp = path.join(dir, "pnpm-workspace.yaml");
const healthy = [
"packages:",
" - '.'",
"",
"allowBuilds:",
" cpu-features: true",
" ssh2: true",
" dsh-purge: true",
"",
].join("\n");
fs.writeFileSync(fp, healthy, "utf8");
const before = fs.readFileSync(fp, "utf8");
assert.equal(rewritePnpmAllowBuilds(before, dir), before);
const statBefore = fs.statSync(fp);
const result = ensurePnpmAllowBuild(dir);
assert.equal(result.wrote, false);
assert.equal(result.ok, true);
assert.equal(fs.readFileSync(fp, "utf8"), before);
assert.equal(fs.statSync(fp).mtimeMs, statBefore.mtimeMs);
});
test("幂等:第二次 ensure 不再写盘(自愈后收敛)", () => {
const dir = withTempProfile();
const fp = path.join(dir, "pnpm-workspace.yaml");
const polluted = `allowBuilds:\n ssh2: true\n dsh-purge@https: true\n dsh-purge@1.1.81: true\n`;
fs.writeFileSync(fp, polluted, "utf8");
const first = ensurePnpmAllowBuild(dir);
assert.equal(first.wrote, true);
const healed = fs.readFileSync(fp, "utf8");
// 畸形历史键被清掉
assert.equal(healed.includes("dsh-purge@https"), false);
assert.equal(healed.includes("dsh-purge@1.1.81"), false);
// 只剩裸包名
assert.equal(healed.includes(" dsh-purge: true"), true);
const second = ensurePnpmAllowBuild(dir);
assert.equal(second.wrote, false);
assert.equal(fs.readFileSync(fp, "utf8"), healed);
});
// ---- #191:cordis.patch.yml 是 `[]` 时追加会导致宿主启动解析失败 ----
test("patch 形态分类:空 / 空 flow / 块序列 / 非空 flow / 未知", () => {
assert.equal(classifyPatchBody("").kind, "empty");
assert.equal(classifyPatchBody("# 只有注释\n\n").kind, "empty");
assert.equal(classifyPatchBody("[]").kind, "empty-flow");
assert.equal(classifyPatchBody("# c\n[]\n").kind, "empty-flow");
assert.equal(classifyPatchBody("---\n[]\n").kind, "empty-flow");
assert.equal(classifyPatchBody("- id: foo\n name: foo\n").kind, "block-seq");
assert.equal(classifyPatchBody("[a, b]\n").kind, "flow-seq");
assert.equal(classifyPatchBody("foo: bar\n").kind, "unknown");
});
test("空文件:直接写 insert 块", () => {
const dir = withTempPatch(undefined);
const fp = path.join(dir, "cordis.patch.yml");
const result = ensureProfileBodyInsert(dir);
assert.equal(result.ok, true);
assert.equal(result.wrote, true);
assert.equal(fs.readFileSync(fp, "utf8"), INSERT_BLOCK);
});
test("只有注释和空行:写 insert 块,注释保留", () => {
const dir = withTempPatch("# overrides, disables, and insertions\n\n");
const fp = path.join(dir, "cordis.patch.yml");
const result = ensureProfileBodyInsert(dir);
assert.equal(result.ok, true);
assert.equal(result.wrote, true);
const text = fs.readFileSync(fp, "utf8");
assert.equal(text.includes("# overrides, disables, and insertions"), true);
assert.equal(text.includes("- insert:"), true);
assert.equal(topLevelInsertGroups(text), 1);
});
test("注释 + `[]`:`[]` 被替换成 insert 块,注释保留,无第二个文档", () => {
const dir = withTempPatch("# overrides, disables, and insertions\n[]\n");
const fp = path.join(dir, "cordis.patch.yml");
const result = ensureProfileBodyInsert(dir);
assert.equal(result.ok, true);
assert.equal(result.wrote, true);
const text = fs.readFileSync(fp, "utf8");
assert.equal(text.includes("[]"), false);
assert.equal(text.includes("# overrides, disables, and insertions"), true);
assert.equal(text.includes("- insert:"), true);
// 只有一个顶层 `- insert:` 组 → 没有变成第二个文档
assert.equal(topLevelInsertGroups(text), 1);
});
test("`---` 前缀 + `[]`:同样替换,无第二个文档", () => {
const dir = withTempPatch("---\n[]\n");
const fp = path.join(dir, "cordis.patch.yml");
const result = ensureProfileBodyInsert(dir);
assert.equal(result.ok, true);
assert.equal(result.wrote, true);
const text = fs.readFileSync(fp, "utf8");
assert.equal(text.includes("[]"), false);
assert.equal(topLevelInsertGroups(text), 1);
});
test("正常块序列:沿用旧的追加行为", () => {
const original = "- id: foo\n name: foo\n";
const dir = withTempPatch(original);
const fp = path.join(dir, "cordis.patch.yml");
const result = ensureProfileBodyInsert(dir);
assert.equal(result.ok, true);
assert.equal(result.wrote, true);
const text = fs.readFileSync(fp, "utf8");
assert.equal(text.startsWith(original), true);
assert.equal(text.includes("- insert:"), true);
assert.equal(topLevelInsertGroups(text), 1);
});
test("非空 flow 序列:宿主内容不动,返回 ok:false", () => {
const original = "[a, b]\n";
const dir = withTempPatch(original);
const fp = path.join(dir, "cordis.patch.yml");
const result = ensureProfileBodyInsert(dir);
assert.equal(result.ok, false);
assert.equal(result.wrote, false);
assert.equal(fs.readFileSync(fp, "utf8"), original);
});
test("已有 dsh-purge 本体行:零写入", () => {
const original = "- insert:\n - id: dsh-purge\n name: dsh-purge\n";
const dir = withTempPatch(original);
const fp = path.join(dir, "cordis.patch.yml");
const result = ensureProfileBodyInsert(dir);
assert.equal(result.ok, true);
assert.equal(result.wrote, false);
assert.equal(fs.readFileSync(fp, "utf8"), original);
});
test("`[]` 替换后幂等:再 ensure 一次零写入", () => {
const dir = withTempPatch("# c\n[]\n");
const fp = path.join(dir, "cordis.patch.yml");
const first = ensureProfileBodyInsert(dir);
assert.equal(first.wrote, true);
const healed = fs.readFileSync(fp, "utf8");
const second = ensureProfileBodyInsert(dir);
assert.equal(second.wrote, false);
assert.equal(fs.readFileSync(fp, "utf8"), healed);
});