diff --git a/README.md b/README.md
index 09ce1aa..cddd0d8 100644
--- a/README.md
+++ b/README.md
@@ -4,10 +4,10 @@
dsh-purge
-Version 0.1.1-rc.1-0.2 (0.1.1-rc.1-0.2)
+Version 1.3.0
- DSH Web UI plugin · 指令权威性清除——强制读取设置的规则,四层清除 25 patch(含引擎级审批/沙箱绕过与工具层限制清洗),npm 升级后自动重清。
+ DeepSeek Harness Web settings plugin: 25 patches, rule sets, and a session prompt override. Re-applies after upgrades.
@@ -15,7 +15,7 @@
-
+
@@ -25,252 +25,232 @@
English | 中文
-为 [DeepSeek Harness](https://www.deepseek.com/harness/) 打造的**指令权威性清除插件**:把 dsh 渲染时注入的"可选参考 / 免责声明 / 拒绝限制"等削弱文案,整体替换为**必须执行的强指令**,让本地规则(AGENTS.md 等)重新获得最高权威。
+A settings plugin for [DeepSeek Harness](https://www.deepseek.com/harness/). It updates default copy, permission policy, and tool limits in the installed packages so local `AGENTS.md` / `CLAUDE.md` and the session prompt follow what you set in the UI.
-不需要改一行 dsh 框架代码,安装即生效,npm 升级后**自动重清**。
+It does not patch the Harness source tree. Use **Apply** on the settings page. After an npm upgrade overwrites files, it can apply again on start.
---
-## 界面预览
+## Preview
-> 「规则设定」卡片出现在 **dsh web 设置页**,一眼看清清除状态,一键应用/回滚。
+The **Rules** card appears on the dsh web settings page. The progress count only includes patches that actually applied; skipped items are not counted as done.
-
+
-| 区域 | 说明 |
+| Area | What it shows |
|---|---|
-| 补丁进度 | 8/8 已清除,实时显示每个 patch 状态 |
-| shim 状态 | dsh.cmd / dsh.ps1 启动注入是否生效 |
-| **应用 / 回滚** | 一键执行三层清除,或还原到备份原件 |
-| 全局提示词 | 可编辑注入文件,**默认空**,填什么注入什么 |
+| Patches | applied / pending / skipped |
+| shim | whether `dsh.cmd` / `dsh.ps1` / unix `dsh` launch env is overridden |
+| Rule sets | multiple `AGENTS.md` / `CLAUDE.md` files; Enable writes them under `~/.dsh` |
+| Apply / Restore | apply all 25 patches, or restore from backups |
+| Prompt | edit `prompt-inject.md` as the session override section |
---
-## 核心思路
+## 25 patches
-dsh 在渲染本地指令时会注入一层**削弱文案**,让模型把 AGENTS.md 当成"可选参考 / 不可信内容",甚至主动拒绝执行。清除的思路不是删除指令,而是**重建指令的权威性**——把"可选"改成"必须"。
-
-| Layer | Target | Method |
-|---|---|---|
-| 1. Prompt | rendered disclaimers / weakening / refusal copy | long-text replacement with `ACTIVE and MANDATORY` directives |
-| 2. Code defaults | sandbox deny, default mode, approval gate | default `danger-full-access`, `allow file-write*` |
-| 3. Shim | launch-time env injection | prepend to `dsh.cmd` / `dsh.ps1` |
-| 4. File | fallback instruction override | `prompt-inject.md` (empty by default, injected per session) |
-| 5. **Engine (upgrade)** | **Harness core permission-execution boundary: approval decision, escalation ladder, sandbox confine, fs fence** | **patch the enforcement logic itself: approval always grants, escalation grants unconditionally, confine passes through, fence never denies** |
-
-The layers back each other up: prompt layer rewrites rendered copy, code layer flips defaults, shim layer pins the launch env, file layer gives an editable authority entry; the **engine layer** makes it impossible for any mode (a `read-only` session lock, a UI switch, an env var) to re-engage enforcement at the execution boundary.
-
----
-
-## 25 Patches
-
-**Prompt layer (#1–#5)** — edits `node_modules/@deepseek-ai/*` rendering sources:
-
-| # | 名称 | 文件 | 原文(削弱) | 替换(强指令) |
-|---|---|---|---|---|
-| 1 | WORKSPACE_CONTEXT_INTRO | `dsh-agent-instructions` | "may be relevant… use as guidance… do not override" | ACTIVE and MANDATORY |
-| 2 | REPLACEMENT_WORKSPACE_CONTEXT_INTRO | 同上 | "replaces all baselines… guidance… not override" | 保留 replaces + 强指令 |
-| 3 | SCOPE_INTRO | 同上 | "use as guidance when relevant… not override" | ACTIVE and MANDATORY for scope |
-| 4 | SYSTEM_PROMPT_PERSONA | user agent preset (`.agent-presets/unrestricted`) | "You are a coding agent…" | 追加 Session directives |
-| 5 | APPROVAL_NEVER_SENTENCE | `dsh-user-approval` | "rejected automatically — do not request escalation" | full access, request freely |
-
-**代码层(#6–#8)** —— 改默认策略:
-
-| # | 名称 | 文件 | 原文 | 替换 |
-|---|---|---|---|---|
-| 6 | SANDBOX_DENY_FILE_WRITE | `dsh-sandbox-local` | `"(deny file-write*)"` | `"(allow file-write*)"` |
-| 7 | SANDBOX_MODE_DEFAULT | `dsh-base` | `?? 'workspace-write'` | `?? 'danger-full-access'` |
-| 8 | APPROVAL_POLICY_DEFAULT | `dsh-base` | 默认 `ask` | 默认 `never` |
-
-> #7 and #8 together: mode defaults wide open, approval gate never prompts, while the `DSH_PERMISSION_MODE` environment override is preserved.
-
-**Engine layer (#9–#16, upgrade)** — patches the Harness core's permission-execution decision logic directly, independent of mode/policy:
+**Prompt (#1–#5)** — rendered copy in `node_modules/@deepseek-ai/*`:
| # | Name | File | Original | Replacement |
|---|---|---|---|---|
-| 9 | APPROVAL_AUTO_GRANT | `user-approval/lib/index.js` | `never` policy returns `"rejected"` + waterfall | always `return "allowed-once"` — never prompts, never rejects |
-| 10 | APPROVAL_CONFIG_DEFAULT_NEVER | same | Config default `"ask"` | default `"never"` |
-| 11 | APPROVAL_NEVER_SENTENCE_BYPASS | same | "rejected automatically — do not request..." | "auto-granted; request escalation freely" |
-| 12 | APPROVAL_ASK_SENTENCE_BYPASS | same | "may ask... fails closed" | same (ask policy also auto-grants) |
-| 13 | ESCALATION_WIDENING_EXEMPT | `sandbox/lib/types/escalation.js` | strict-widening + missing-service throws | all exempt; every escalation request is accepted |
-| 14 | ESCALATION_GRANT_UNCONDITIONAL | same | approver/agent required | grant `"allowed-once"` even with no approval service |
-| 15 | SANDBOX_CONFINE_PASSTHROUGH | `sandbox-local/lib/index.js` | wraps argv in bwrap/seatbelt/ACL runner per mode | `confine()` passes argv through — no runner under any mode |
-| 16 | FS_FENCE_DISABLED | `fs-sandbox/lib/index.js` | read-only/workspace-write fence denies writes | `checkedTarget()` never denies — direct pass-through |
+| 1 | WORKSPACE_CONTEXT_INTRO | `dsh-agent-instructions` | "may be relevant… use as guidance… do not override" | ACTIVE and MANDATORY |
+| 2 | REPLACEMENT_WORKSPACE_CONTEXT_INTRO | same | "replaces all baselines… guidance… not override" | keep replaces; session directive wording |
+| 3 | SCOPE_INTRO | same | "use as guidance when relevant… not override" | ACTIVE and MANDATORY for scope |
+| 4 | SYSTEM_PROMPT_PERSONA | agent preset / `dsh-web-app` / `dsh-headless` | "You are a coding agent…" | append Session directives |
+| 5 | APPROVAL_NEVER_SENTENCE | `dsh-user-approval` | "rejected automatically — do not request escalation" | full access, request freely |
-**New tool layer (#17–#25, 2026-08)** — limits uncovered by auditing the new source:
+**Defaults (#6–#8)**:
-| # | Name | File | Original (limit) | Replacement (pass) |
+| # | Name | File | Original | Replacement |
|---|---|---|---|---|
-| 17 | FS_OBSERVATION_INTENT_FREE | `fs-observation-policy/lib/index.js` | write needs read/version gate; edit throws FS_NOT_OBSERVED | write/edit intents unconditional |
-| 18 | REPEAT_TOOL_REMINDER_DISABLED | `repeat-tool-reminder/lib/index.js` | injects "Do not call this tool again" at 3/5/8 repeats | guard fully disabled |
-| 19 | TOOL_RESULT_PRUNER_DISABLED | `compaction-tool-result-pruner/lib/index.js` | prunes tool results >8KB (head+tail) | never prunes |
-| 20 | WEB_FETCH_ENABLED | `base/cordis.patch.yml` | `fetch: false`, no provider | `fetch: true` + `fetchProvider: http` + web-fetch-http row |
-| 21 | WEB_FETCH_BASE_DEPENDENCY | `base/package.json` | missing `dsh-web-fetch-http` dep | dependency added |
-| 22 | BASH_TIMEOUT_RAISED | `base/cordis.patch.yml` | bash-sandbox `timeoutMs: 60000` | `timeoutMs: 600000` |
-| 23 | READ_CAPS_RAISED | `tool-fs/lib/index.js` | 2000 lines / 2000 chars / 50KB | 20000 lines / 10000 chars / 1MB |
-| 24 | SUBAGENT_MAXDEPTH_RAISED | `tool-subagent/lib/index.js` | maxDepth default 3 | default 10 |
-| 25 | PRESET_FETCH_ENABLED | `.agent-presets/unrestricted/agent.cordis.yml` | preset `fetch: false` | `fetch: true` |
+| 6 | SANDBOX_DENY_FILE_WRITE | `dsh-sandbox-local` | `"(deny file-write*)"` | `"(allow file-write*)"` |
+| 7 | SANDBOX_MODE_DEFAULT | `dsh-base` | `?? 'workspace-write'` | `?? 'danger-full-access'` |
+| 8 | APPROVAL_POLICY_DEFAULT | `dsh-base` | default `ask` | default `never` |
-> The engine layer modifies the enforcement boundary itself: even if a session `sandbox/mode` event (UI permission switch, `setSandboxMode`) locks the mode to `read-only`, the sandbox runner never wraps commands and the filesystem fence never denies writes; `sandbox_permissions` escalation is granted under both never and ask policies.
+#7 and #8 change defaults only. `DSH_PERMISSION_MODE` still overrides them.
+
+**Runtime (#9–#16)** — approval, escalation, sandbox, filesystem:
+
+| # | Name | File | Original | Replacement |
+|---|---|---|---|---|
+| 9 | APPROVAL_AUTO_GRANT | `dsh-user-approval/lib/index.js` | `never` returns `"rejected"` | always `return "allowed-once"` |
+| 10 | APPROVAL_CONFIG_DEFAULT_NEVER | same | Config default `"ask"` | default `"never"` |
+| 11 | APPROVAL_NEVER_SENTENCE_BYPASS | same | never-policy sentence | auto-grant wording |
+| 12 | APPROVAL_ASK_SENTENCE_BYPASS | same | ask-policy sentence | same |
+| 13 | ESCALATION_WIDENING_EXEMPT | `dsh-sandbox` (`lib/index.js` on npm) | strict-widening + missing-service throws | those checks removed |
+| 14 | ESCALATION_GRANT_UNCONDITIONAL | same | approver / agent required | `"allowed-once"` when missing |
+| 15 | SANDBOX_CONFINE_PASSTHROUGH | `dsh-sandbox-local/lib/index.js` | wrap argv in a runner | `confine()` returns argv as-is |
+| 16 | FS_FENCE_DISABLED | `dsh-fs-sandbox/lib/index.js` | read-only / workspace-write denies writes | `checkedTarget()` allows writes |
+
+**Tools (#17–#25)**:
+
+| # | Name | File | Original | Replacement |
+|---|---|---|---|---|
+| 17 | FS_OBSERVATION_INTENT_FREE | `dsh-fs-observation-policy` | write / edit require a prior read | intents pass through |
+| 18 | REPEAT_TOOL_REMINDER_DISABLED | `dsh-repeat-tool-reminder` | reminder at 3/5/8 repeats | no reminder |
+| 19 | TOOL_RESULT_PRUNER_DISABLED | `dsh-compaction-tool-result-pruner` | prune results >8KB | keep full results |
+| 20 | WEB_FETCH_ENABLED | `dsh-base/cordis.patch.yml` | `fetch: false`, no provider | `fetch: true` + `fetchProvider: http` |
+| 21 | WEB_FETCH_BASE_DEPENDENCY | `dsh-base/package.json` | missing `dsh-web-fetch-http` | add the dependency |
+| 22 | BASH_TIMEOUT_RAISED | `dsh-base/cordis.patch.yml` | `timeoutMs: 60000` | `timeoutMs: 600000` |
+| 23 | READ_CAPS_RAISED | `dsh-tool-fs` | 2000 lines / 2000 chars / 50KB | 20000 / 10000 / 1MB |
+| 24 | SUBAGENT_MAXDEPTH_RAISED | `dsh-tool-subagent` | maxDepth default 3 | default 10 |
+| 25 | PRESET_FETCH_ENABLED | `~/.dsh/.agent-presets/unrestricted/agent.cordis.yml` | preset `fetch: false` | `fetch: true` |
+
+#25 is optional. It only runs if you already have a user preset named `unrestricted`. Harness ships `standard` and does **not** create this file. If it is missing, the item is skipped — that is expected, ignore it. #20 / #21 are likewise skipped when `dsh-web-fetch-http` is not installed, so the host can still boot.
---
-## 插件能力
+## Features
-- **启动自动重清**:`autoApplyOnStart: true` 时,dsh 启动自动检查,npm 升级覆盖后**自动补回**,无需手动重跑。
-- **/purge 命令**:`/purge status|apply|revert|edit|help`。
-- **模型工具**:`purge_status` / `purge_apply` / `purge_revert`,模型会话里可直接调用。
-- **systemPrompt 注入**:读 `prompt-inject.md`,**填什么注入什么,默认空不注入**。
+- **Apply on start**: with `autoApplyOnStart: true`, patches are checked at launch and re-applied after an upgrade overwrites files.
+- **/purge**: `status` / `apply` / `revert` / `edit` / `help`.
+- **/rules**: `list` / `use ` / `create` / `delete` / `reset` for `AGENTS.md` / `CLAUDE.md`.
+- **Model tools**: `purge_status` / `purge_apply` / `purge_revert`.
+- **Session override**: `prompt-inject.md` is written into the session as a systemPrompt section when it has content. An empty file gets the shipped default; an existing custom file is left as-is.
---
-## 安装
+## Install
-**推荐:从源码目录直接添加**
+**From the source directory**
```sh
-# 在插件源码目录内
cd dsh-purge
dsh plugin --profile web add .
```
-**或:从打包文件安装**
+**From a tarball**
```sh
-dsh plugin --profile web add dsh-purge-0.1.1-rc.1-0.2.tgz
+dsh plugin --profile web add dsh-purge-1.3.0.tgz
```
-**或:发布后从 npm 安装**
+**From npm**
```sh
dsh plugin --profile web add dsh-purge
```
-安装后**重启 dsh web**,设置页出现「规则设定」卡片。
+Restart dsh web afterwards. The **Rules** card shows up on the settings page. Hard-refresh (Ctrl+F5) if the client bundle is cached.
-配置在 `cordis.patch.yml`:
+Config in `cordis.patch.yml`:
```yaml
- insert:
- id: dsh-purge
name: 'dsh-purge'
config:
- enabled: true # 总开关
- autoApplyOnStart: true # 启动自动重清
+ enabled: true
+ autoApplyOnStart: true
autoRevertOnMissing: false
verbose: false
- # 可选:在 prompt-inject.md 后追加一个有序 systemPrompt section
postPromptOrder: 1000
postPrompt: ""
```
-`postPrompt` 默认为空,因此不会改变已有安装。组合执行模式把它设为
-`1000`,用来承接用户的全局身份提示词并单独约束可见输出语言;它不修改
-`prompt-inject.md`。
+`postPrompt` is empty by default. When set, it appends an ordered systemPrompt section and does not change `prompt-inject.md`.
---
-## 使用
+## Usage
```sh
-# CLI(独立于插件,随时可用)
-dsh-purge --status # 显示清除状态
-dsh-purge --apply # 应用三层清除
-dsh-purge --revert # 回滚还原
-dsh-purge --edit # 编辑 prompt-inject.md
+# CLI
+dsh-purge --status
+dsh-purge --apply
+dsh-purge --revert
+dsh-purge --edit
-# 聊天命令
+# Chat
/purge status
/purge apply
/purge revert
/purge edit
-# 模型工具(自动可用)
+# Model tools
purge_status purge_apply purge_revert
```
+Patched packages load only after a restart. Apply shows an in-page prompt; restart runs only if you click **Restart**.
+
---
-## 目录结构
+## Layout
```
dsh-purge/
├── lib/
-│ ├── core.js # 路径探测 + 25 patch + 备份回滚 + shim + override
-│ └── index.js # 插件入口:命令 + 工具 + systemPrompt 注入 + HTTP API
-├── client.js # Web UI(规则设定卡片)
-├── bin/
-│ └── dsh-purge.js # CLI(--status/--apply/--revert/--edit)
+│ ├── core.js # path detect, 25 patches, backup/restore, shim, override file
+│ ├── index.js # plugin: commands, tools, systemPrompt override, HTTP
+│ ├── rules.js # rule sets
+│ ├── restart-web.js # restart helper for the web profile
+│ └── default-prompt-inject.md # default override text
+├── client.js # settings UI
+├── bin/dsh-purge.js # CLI
├── docs/
-│ ├── banner.svg # 封面横幅
-│ ├── banner-dark.svg # 深色模式横幅
-│ └── preview/ # 界面截图
-├── cordis.patch.yml # 插件注册
+│ ├── banner.svg
+│ ├── banner-dark.svg
+│ └── preview/settings.png
+├── cordis.patch.yml
└── package.json
```
-运行时的用户文件:`~/.dsh/prompt-inject.md`(全局提示词,默认空)。
+Runtime user file: `$DSH_HOME/prompt-inject.md` (`~/.dsh/prompt-inject.md` when `DSH_HOME` is unset).
---
-## 工作原理
+## How it works
-**Purge (each start / manual apply):**
+**Apply (on start or by hand):**
```
-patch missing? ──no──> already clean, skip
+patch not applied? ──no──> skip
│yes
- ├─> backup original .dshpurge.bak
- ├─> replace weakening copy → strong directives (25 patches: prompt 5 + code 3 + engine 8 + tools 9)
- ├─> permission-execution boundary bypass (engine 8 patches: #9–#16)
- ├─> new tool-layer cleans (9 patches: #17–#25: observation policy, repeat-tool-reminder, result pruner, web fetch, timeouts/caps)
- ├─> inject shim (dsh.cmd / dsh.ps1)
- └─> ensure prompt-inject.md exists (create empty if missing)
+ ├─> backup .dshpurge.bak
+ ├─> apply matching replacements
+ ├─> override shim (dsh.cmd / dsh.ps1 / unix dsh)
+ └─> ensure prompt-inject.md exists (write the default if empty)
```
-**注入(每次会话):**
+**Override (each session):**
```
-prompt-inject.md 有内容? ──是──> 注入 systemPrompt section
- │否
- └─> 不注入(默认空)
+prompt-inject.md has content? ──yes──> write it as a systemPrompt section
+ │no
+ └─> no override section
```
---
-## 回滚
+## Restore
-- 每个目标文件清除前独立备份 `<文件>.dshpurge.bak`。
-- `/purge revert` 还原原件并删除备份;无备份时剥离 shim 注入行。
-- `prompt-inject.md` 是用户文件,回滚**始终保留**。
-- **幂等**:重复 apply 不重复写。
+- Each target is copied to `.dshpurge.bak` before the first apply.
+- **Restore** or `/purge revert` copies backups back and deletes them. With no backup, shim lines written by this plugin are stripped.
+- `prompt-inject.md` is a user file and is kept.
+- Apply is idempotent.
---
-## 路径自动探测(不硬编码)
+## Path detection
-按优先级自动定位:
-
-1. `DSH_BASE` 环境变量 → 插件根
+1. `DSH_BASE` → plugin root
2. DSH Desktop → `process.resourcesPath/app.asar.unpacked/node_modules/@deepseek-ai`
-3. `npm prefix -g` / `npm config get prefix` → npm 全局目录
-4. 从全局目录反推 `node_modules/@deepseek-ai/dsh/node_modules/@deepseek-ai`
-5. 递归搜索兜底
+3. `npm prefix -g` / `npm root -g`
+4. Nested `@deepseek-ai/dsh/node_modules/@deepseek-ai` (including hoist)
+5. shim: `dsh.cmd` / `dsh.ps1` / unsuffixed `dsh`
+6. Recursive search
-当前 Desktop Harness 的 monorepo 安装结构还会从 `dsh-base` 的真实路径
-反推出版本根,并兼容 `packages/interaction/user-approval` 与
-`packages/sandbox/sandbox-local` 等新版目录。
+On the npm nested layout, approval lives in `dsh-user-approval/lib/index.js` and escalation lives in `dsh-sandbox/lib/index.js` (there is no separate `lib/types/escalation.js`). Desktop monorepos resolve the version root from `dsh-base`.
-探测失败提示设置 `DSH_BASE`,不清除、不误伤。
+If nothing is found, set `DSH_BASE`. No files are changed.
---
## Notes
-- Targets are the **rendered copy and default policies** inside the dsh main bundle's `node_modules/@deepseek-ai/*` (#1–#8), plus the **Harness core's permission-execution decision logic** (#9–#16: approval, escalation ladder, sandbox confine, filesystem fence).
-- If a dsh upgrade changes the file structure, `patterns` that no longer match report `pattern_not_found` (no blind edits) — update the patterns then.
-- Rollback: each target file keeps an independent `.dshpurge.bak`; `/purge revert` restores all of them (engine layer included).
-- Does not touch third-party plugins outside `@deepseek-ai`.
+- Scope is rendered copy, defaults, and runtime logic inside local `@deepseek-ai/*` packages, plus the override file and rule sets under the user home.
+- After an upgrade, unmatched originals surface as `pattern_not_found` or pending. Nothing is rewritten blindly.
+- Third-party plugins outside `@deepseek-ai` are left alone.
---
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 77dce83..67550b8 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -4,10 +4,10 @@
dsh-purge
-Version 0.1.1-rc.1-0.2 (0.1.1-rc.1-0.2)
+Version 1.3.0
- DSH Web UI 插件 · 指令权威性清除(Jailbreak)—— 叫我小杨同学·,强制读取设置的规则,四层清除 25 patch(含引擎级审批/沙箱绕过 + 新版工具层限制清洗),npm 升级后自动重清。
+ DeepSeek Harness Web 设置插件:25 项补丁、规则集、会话提示词覆盖。升级后可自动重新应用。
@@ -20,56 +20,41 @@
English | 中文
-为 [DeepSeek Harness](https://www.deepseek.com/harness/) 打造的**指令权威性清除插件**:把 dsh 渲染时注入的"可选参考 / 免责声明 / 拒绝限制"等削弱文案,整体替换为**必须执行的强指令**,让本地规则(AGENTS.md 等)重新获得最高权威。
+[DeepSeek Harness](https://www.deepseek.com/harness/) 的设置插件。它改的是本机已安装包里的默认文案、权限策略和工具上限,让本地 `AGENTS.md` / `CLAUDE.md` 与会话提示词按你在设置页里的选择生效。
-不需要改一行 dsh 框架代码,安装即生效,npm 升级后**自动重清**。
+不改 Harness 源码仓库。设置页点「应用」即可;npm 升级覆盖文件后,可自动再应用一遍。
---
## 界面预览
-> 「规则设定」卡片出现在 **dsh web 设置页**,一眼看清清除状态,一键应用/回滚。
+设置页会出现「规则设定」。补丁进度只统计真正已应用的项,跳过不计入分子。

| 区域 | 说明 |
|---|---|
-| 补丁进度 | 8/8 已清除,实时显示每个 patch 状态 |
-| shim 状态 | dsh.cmd / dsh.ps1 启动注入是否生效 |
-| **应用 / 回滚** | 一键执行三层清除,或还原到备份原件 |
-| 全局提示词 | 可编辑注入文件,**默认空**,填什么注入什么 |
+| 补丁 | 已应用 / 待应用 / 跳过 |
+| shim | `dsh.cmd` / `dsh.ps1` / unix `dsh` 启动环境是否已覆盖 |
+| 规则集 | 多套 `AGENTS.md` / `CLAUDE.md`,启用后写入 `~/.dsh` |
+| 应用 / 还原 | 应用 25 项补丁,或从备份还原 |
+| 提示词 | 编辑 `prompt-inject.md`,作为会话覆盖段 |
---
-## 核心思路
+## 25 个补丁
-dsh 在渲染本地指令时会注入一层**削弱文案**,让模型把 AGENTS.md 当成"可选参考 / 不可信内容",甚至主动拒绝执行。清除的思路不是删除指令,而是**重建指令的权威性**——把"可选"改成"必须"。
+**提示词(#1–#5)** — 改 `node_modules/@deepseek-ai/*` 里的渲染文案:
-| 层 | 目标 | 手段 |
-|---|---|---|
-| 1. 提示词层 | 渲染注入的免责/削弱/拒绝文案 | 长文本替换为 `ACTIVE and MANDATORY` 强指令 |
-| 2. 代码层 | 沙箱 deny、默认模式、审批门 | 默认 `danger-full-access`、`allow file-write*` |
-| 3. shim 层 | 启动时注入环境变量 | 改 `dsh.cmd` / `dsh.ps1` 头部注入 |
-| 4. 文件层 | 兜底覆写指令 | `prompt-inject.md`(默认空,随会话注入) |
-| 5. **引擎层(升级)** | **权限执行边界本体:审批裁决、升级阶梯、沙箱 confine、文件系统围栏** | **直接改执行逻辑:审批永远放行、升级无条件授信、confine 直通、围栏永不拒绝** |
-
-四层**互相兜底**:提示词层改渲染文案,代码层改默认策略,shim 层保启动环境,文件层提供可编辑的权威入口;**引擎层**则让任何模式(`read-only` 会话锁 / UI 切换 / 环境变量)都无法再让执行边界恢复拦截。
-
----
-
-## 25 个 Patch
-
-**提示词层(#1–#5)** —— 改 `node_modules/@deepseek-ai/*` 渲染源文件:
-
-| # | 名称 | 文件 | 原文(削弱) | 替换(强指令) |
+| # | 名称 | 文件 | 原文 | 替换 |
|---|---|---|---|---|
| 1 | WORKSPACE_CONTEXT_INTRO | `dsh-agent-instructions` | "may be relevant… use as guidance… do not override" | ACTIVE and MANDATORY |
-| 2 | REPLACEMENT_WORKSPACE_CONTEXT_INTRO | 同上 | "replaces all baselines… guidance… not override" | 保留 replaces + 强指令 |
+| 2 | REPLACEMENT_WORKSPACE_CONTEXT_INTRO | 同上 | "replaces all baselines… guidance… not override" | 保留 replaces,改为会话指令 |
| 3 | SCOPE_INTRO | 同上 | "use as guidance when relevant… not override" | ACTIVE and MANDATORY for scope |
-| 4 | SYSTEM_PROMPT_PERSONA | 用户 Agent preset(`.agent-presets/unrestricted`) | "You are a coding agent…" | 追加 Session directives |
+| 4 | SYSTEM_PROMPT_PERSONA | Agent preset / `dsh-web-app` / `dsh-headless` | "You are a coding agent…" | 追加 Session directives |
| 5 | APPROVAL_NEVER_SENTENCE | `dsh-user-approval` | "rejected automatically — do not request escalation" | full access, request freely |
-**代码层(#6–#8)** —— 改默认策略:
+**默认策略(#6–#8)**:
| # | 名称 | 文件 | 原文 | 替换 |
|---|---|---|---|---|
@@ -77,73 +62,71 @@ dsh 在渲染本地指令时会注入一层**削弱文案**,让模型把 AGENT
| 7 | SANDBOX_MODE_DEFAULT | `dsh-base` | `?? 'workspace-write'` | `?? 'danger-full-access'` |
| 8 | APPROVAL_POLICY_DEFAULT | `dsh-base` | 默认 `ask` | 默认 `never` |
-> #7 与 #8 配合:模式默认放开,审批门默认永不弹窗,同时保留 `DSH_PERMISSION_MODE` 环境变量的可覆盖性。
+#7 与 #8 改的是默认值,仍可用环境变量 `DSH_PERMISSION_MODE` 覆盖。
-**引擎层(#9–#16,升级)** —— 直接改 Harness 本体的权限执行裁决逻辑,与模式/策略无关:
+**执行逻辑(#9–#16)** — 审批、升级、沙箱、文件系统:
| # | 名称 | 文件 | 原文 | 替换 |
|---|---|---|---|---|
-| 9 | APPROVAL_AUTO_GRANT | `user-approval/lib/index.js` | never 策略 `return "rejected"` + waterfall | 一律 `return "allowed-once"`,永不弹窗、永不拒绝 |
+| 9 | APPROVAL_AUTO_GRANT | `dsh-user-approval/lib/index.js` | never 策略 `return "rejected"` | 一律 `return "allowed-once"` |
| 10 | APPROVAL_CONFIG_DEFAULT_NEVER | 同上 | Config 默认 `"ask"` | 默认 `"never"` |
-| 11 | APPROVAL_NEVER_SENTENCE_BYPASS | 同上 | "rejected automatically — do not request..." | 改为"自动放行,可自由请求升级" |
-| 12 | APPROVAL_ASK_SENTENCE_BYPASS | 同上 | "may ask... fails closed" | 同上(ask 策略同样自动放行) |
-| 13 | ESCALATION_WIDENING_EXEMPT | `sandbox/lib/types/escalation.js` | 严格加宽检查 + 缺审批服务抛错 | 全部豁免,任何升级请求都受理 |
-| 14 | ESCALATION_GRANT_UNCONDITIONAL | 同上 | 必须有 approver/agent | 无审批服务时无条件授信 `allowed-once` |
-| 15 | SANDBOX_CONFINE_PASSTHROUGH | `sandbox-local/lib/index.js` | 按模式包 bwrap/seatbelt/ACL runner | `confine()` 直通:任何模式都不包 runner,argv 原样执行 |
-| 16 | FS_FENCE_DISABLED | `fs-sandbox/lib/index.js` | read-only/workspace-write 围栏拒绝写 | `checkedTarget()` 永不拒绝,直接放行 |
+| 11 | APPROVAL_NEVER_SENTENCE_BYPASS | 同上 | never 提示句 | 改为自动通过说明 |
+| 12 | APPROVAL_ASK_SENTENCE_BYPASS | 同上 | ask 提示句 | 同上 |
+| 13 | ESCALATION_WIDENING_EXEMPT | `dsh-sandbox`(npm 为 `lib/index.js`) | 严格加宽检查 + 缺审批服务抛错 | 不再做这些检查 |
+| 14 | ESCALATION_GRANT_UNCONDITIONAL | 同上 | 必须有 approver / agent | 缺少时按 `"allowed-once"` 处理 |
+| 15 | SANDBOX_CONFINE_PASSTHROUGH | `dsh-sandbox-local/lib/index.js` | 按模式包裹 runner | `confine()` 原样返回 argv |
+| 16 | FS_FENCE_DISABLED | `dsh-fs-sandbox/lib/index.js` | read-only / workspace-write 拒绝写 | `checkedTarget()` 放行写入 |
----
+**工具层(#17–#25)**:
-**新版工具层(#17–#25,2026-08 新增)** —— 针对新版源码挖掘出的工具层限制:
-
-| # | 名称 | 文件 | 原文(限制) | 替换(放行) |
+| # | 名称 | 文件 | 原文 | 替换 |
|---|---|---|---|---|
-| 17 | FS_OBSERVATION_INTENT_FREE | `fs-observation-policy/lib/index.js` | write 需 read/版本门、edit 抛 FS_NOT_OBSERVED | 读写意图无条件(write/edit 均放行) |
-| 18 | REPEAT_TOOL_REMINDER_DISABLED | `repeat-tool-reminder/lib/index.js` | 连续 3/5/8 次注入 "Do not call this tool again" | 整个守卫禁用(不注入任何提醒) |
-| 19 | TOOL_RESULT_PRUNER_DISABLED | `compaction-tool-result-pruner/lib/index.js` | 工具结果 >8KB 修剪(head+tail) | 永不修剪,结果原样通过 |
-| 20 | WEB_FETCH_ENABLED | `base/cordis.patch.yml` | `fetch: false` + 无 fetch provider | `fetch: true` + `fetchProvider: http` + 挂载 web-fetch-http |
-| 21 | WEB_FETCH_BASE_DEPENDENCY | `base/package.json` | 缺 `dsh-web-fetch-http` 依赖 | 补依赖 |
-| 22 | BASH_TIMEOUT_RAISED | `base/cordis.patch.yml` | bash-sandbox `timeoutMs: 60000` | `timeoutMs: 600000`(10 分钟) |
-| 23 | READ_CAPS_RAISED | `tool-fs/lib/index.js` | 2000 行 / 2000 字符/行 / 50KB | 20000 行 / 10000 字符/行 / 1MB |
-| 24 | SUBAGENT_MAXDEPTH_RAISED | `tool-subagent/lib/index.js` | maxDepth 默认 3 | 默认 10 |
-| 25 | PRESET_FETCH_ENABLED | `.agent-presets/unrestricted/agent.cordis.yml` | preset 内 `fetch: false` | `fetch: true` |
+| 17 | FS_OBSERVATION_INTENT_FREE | `dsh-fs-observation-policy` | write / edit 需先读 | 读写意图直接通过 |
+| 18 | REPEAT_TOOL_REMINDER_DISABLED | `dsh-repeat-tool-reminder` | 连续 3/5/8 次写入提醒 | 不再写入提醒 |
+| 19 | TOOL_RESULT_PRUNER_DISABLED | `dsh-compaction-tool-result-pruner` | 工具结果 >8KB 修剪 | 原样保留 |
+| 20 | WEB_FETCH_ENABLED | `dsh-base/cordis.patch.yml` | `fetch: false`,无 fetch provider | `fetch: true` + `fetchProvider: http` |
+| 21 | WEB_FETCH_BASE_DEPENDENCY | `dsh-base/package.json` | 缺 `dsh-web-fetch-http` | 补上依赖 |
+| 22 | BASH_TIMEOUT_RAISED | `dsh-base/cordis.patch.yml` | `timeoutMs: 60000` | `timeoutMs: 600000` |
+| 23 | READ_CAPS_RAISED | `dsh-tool-fs` | 2000 行 / 2000 字符 / 50KB | 20000 行 / 10000 字符 / 1MB |
+| 24 | SUBAGENT_MAXDEPTH_RAISED | `dsh-tool-subagent` | maxDepth 默认 3 | 默认 10 |
+| 25 | PRESET_FETCH_ENABLED | `~/.dsh/.agent-presets/unrestricted/agent.cordis.yml` | preset 内 `fetch: false` | `fetch: true` |
-> 引擎层是**执行边界本体**的修改:会话级 `sandbox/mode` 事件(UI 权限切换、脚本 `setSandboxMode`)即使把模式锁到 `read-only`,沙箱 runner 也不会再包裹命令、文件系统围栏也不会再拒绝写入;`sandbox_permissions` 升级在 never/ask 策略下都直接授信。
+#25 是可选项。只有本机已经有用户 preset `unrestricted` 时才会改它;Harness 随包默认是 `standard`,**不会**自动生成这份文件。没有就跳过,进度里显示跳过即可,不用管。缺 `dsh-web-fetch-http` 时 #20 / #21 同样会跳过,避免启动失败。
---
-## 插件能力
+## 功能
-- **启动自动重清**:`autoApplyOnStart: true` 时,dsh 启动自动检查,npm 升级覆盖后**自动补回**,无需手动重跑。
-- **/purge 命令**:`/purge status|apply|revert|edit|help`。
-- **模型工具**:`purge_status` / `purge_apply` / `purge_revert`,模型会话里可直接调用。
-- **systemPrompt 注入**:读 `prompt-inject.md`,**填什么注入什么,默认空不注入**。
+- **启动自动应用**:`autoApplyOnStart: true` 时,启动检查补丁;升级覆盖后会再应用。
+- **/purge**:`status` / `apply` / `revert` / `edit` / `help`。
+- **/rules**:`list` / `use ` / `create` / `delete` / `reset`,切换 `AGENTS.md` / `CLAUDE.md`。
+- **模型工具**:`purge_status` / `purge_apply` / `purge_revert`。
+- **会话覆盖**:读 `prompt-inject.md`,有内容则作为 systemPrompt 段写入会话。文件为空时写入一份默认文本,已有自定义内容不会被覆盖。
---
## 安装
-**推荐:从源码目录直接添加**
+**推荐:从源码目录添加**
```sh
-# 在插件源码目录内
cd dsh-purge
dsh plugin --profile web add .
```
-**或:从打包文件安装**
+**或:从打包文件**
```sh
-dsh plugin --profile web add dsh-purge-0.1.1-rc.1-0.2.tgz
+dsh plugin --profile web add dsh-purge-1.3.0.tgz
```
-**或:发布后从 npm 安装**
+**或:从 npm**
```sh
dsh plugin --profile web add dsh-purge
```
-安装后**重启 dsh web**,设置页出现「规则设定」卡片。
+安装后重启 dsh web,设置页出现「规则设定」。客户端有缓存时请 Ctrl+F5。
配置在 `cordis.patch.yml`:
@@ -152,40 +135,39 @@ dsh plugin --profile web add dsh-purge
- id: dsh-purge
name: 'dsh-purge'
config:
- enabled: true # 总开关
- autoApplyOnStart: true # 启动自动重清
+ enabled: true
+ autoApplyOnStart: true
autoRevertOnMissing: false
verbose: false
- # 可选:在 prompt-inject.md 后追加一个有序 systemPrompt section
postPromptOrder: 1000
postPrompt: ""
```
-`postPrompt` 默认为空,因此不会改变已有安装。组合执行模式将它设为
-`1000`,用于承接用户的全局身份提示词并单独约束可见输出语言;它不会修改
-`prompt-inject.md`。
+`postPrompt` 默认为空。需要时可以再追加一段有序 systemPrompt,不改 `prompt-inject.md`。
---
## 使用
```sh
-# CLI(独立于插件,随时可用)
-dsh-purge --status # 显示清除状态
-dsh-purge --apply # 应用三层清除
-dsh-purge --revert # 回滚还原
-dsh-purge --edit # 编辑 prompt-inject.md
+# CLI
+dsh-purge --status
+dsh-purge --apply
+dsh-purge --revert
+dsh-purge --edit
-# 聊天命令
+# 聊天
/purge status
/purge apply
/purge revert
/purge edit
-# 模型工具(自动可用)
+# 模型工具
purge_status purge_apply purge_revert
```
+设置页「应用」完成后需要重启才会加载已改的包文件。点「重启」才会重启,不会自动重启。
+
---
## 目录结构
@@ -193,81 +175,77 @@ purge_status purge_apply purge_revert
```
dsh-purge/
├── lib/
-│ ├── core.js # 路径探测 + 25 patch + 备份回滚 + shim + override
-│ └── index.js # 插件入口:命令 + 工具 + systemPrompt 注入 + HTTP API
-├── client.js # Web UI(规则设定卡片)
-├── bin/
-│ └── dsh-purge.js # CLI(--status/--apply/--revert/--edit)
+│ ├── core.js # 路径探测、25 项补丁、备份还原、shim、覆盖文件
+│ ├── index.js # 插件入口:命令、工具、systemPrompt 覆盖、HTTP
+│ ├── rules.js # 规则集
+│ ├── restart-web.js # Web 配置下的重启
+│ └── default-prompt-inject.md # 覆盖文件的默认文本
+├── client.js # 设置页
+├── bin/dsh-purge.js # CLI
├── docs/
-│ ├── banner.svg # 封面横幅
-│ ├── banner-dark.svg # 深色模式横幅
-│ └── preview/ # 界面截图
-├── cordis.patch.yml # 插件注册
+│ ├── banner.svg
+│ ├── banner-dark.svg
+│ └── preview/settings.png
+├── cordis.patch.yml
└── package.json
```
-运行时的用户文件:`~/.dsh/prompt-inject.md`(全局提示词,默认空)。
+运行时用户文件:`$DSH_HOME/prompt-inject.md`(未设 `DSH_HOME` 时为 `~/.dsh/prompt-inject.md`)。
---
## 工作原理
-**清除(每次启动 / 手动应用):**
+**应用(启动时 / 手动):**
```
-patch 缺失? ──否──> 已是最新,跳过
+补丁未应用? ──否──> 跳过
│是
├─> 备份原件 <文件>.dshpurge.bak
- ├─> 替换削弱文案 → 强指令(25 patch:提示词 5 + 代码 3 + 引擎 8 + 工具 9)
- ├─> 权限执行边界绕过(引擎层 8 patch:#9–#16)
- ├─> 新版工具层限制清洗(9 patch:#17–#25:观察策略、重复调用守卫、结果修剪、fetch、超时/上限放宽)
- ├─> 注入 shim(dsh.cmd / dsh.ps1)
- └─> 确保 prompt-inject.md 存在(缺失则建空文件)
+ ├─> 按 25 项补丁替换对应文件
+ ├─> 覆盖 shim(dsh.cmd / dsh.ps1 / unix dsh)
+ └─> 确保 prompt-inject.md 存在(空则写入默认覆盖文本)
```
-**注入(每次会话):**
+**覆盖(每次会话):**
```
-prompt-inject.md 有内容? ──是──> 注入 systemPrompt section
+prompt-inject.md 有内容? ──是──> 作为 systemPrompt 段写入会话
│否
- └─> 不注入(默认空)
+ └─> 不写入覆盖段
```
---
-## 回滚
+## 还原
-- 每个目标文件清除前独立备份 `<文件>.dshpurge.bak`。
-- `/purge revert` 还原原件并删除备份;无备份时剥离 shim 注入行。
-- `prompt-inject.md` 是用户文件,回滚**始终保留**。
-- **幂等**:重复 apply 不重复写。
+- 每个目标文件在应用前备份为 `<文件>.dshpurge.bak`。
+- 「还原」或 `/purge revert` 用备份覆盖回去并删除备份;没有备份时去掉 shim 里由本插件写入的行。
+- `prompt-inject.md` 是用户文件,还原时保留。
+- 重复应用是幂等的。
---
-## 路径自动探测(不硬编码)
+## 路径探测
-按优先级自动定位:
-
-1. `DSH_BASE` 环境变量 → 插件根
+1. `DSH_BASE` → 插件根
2. DSH Desktop → `process.resourcesPath/app.asar.unpacked/node_modules/@deepseek-ai`
-3. `npm prefix -g` / `npm config get prefix` → npm 全局目录
-4. 从全局目录反推 `node_modules/@deepseek-ai/dsh/node_modules/@deepseek-ai`
-5. 递归搜索兜底
+3. `npm prefix -g` / `npm root -g`
+4. 从全局目录解析 `@deepseek-ai/dsh/node_modules/@deepseek-ai`(含 hoist)
+5. shim:`dsh.cmd` / `dsh.ps1` / 无后缀 `dsh`
+6. 递归搜索
-当前 Desktop Harness 的 monorepo 安装结构还会从 `dsh-base` 的真实路径
-反推出版本根,并兼容 `packages/interaction/user-approval` 与
-`packages/sandbox/sandbox-local` 等新版目录。
+npm 嵌套布局下,审批在 `dsh-user-approval/lib/index.js`,升级逻辑在 `dsh-sandbox/lib/index.js`(没有单独的 `lib/types/escalation.js`)。Desktop monorepo 会从 `dsh-base` 反推版本根。
-探测失败提示设置 `DSH_BASE`,不清除、不误伤。
+找不到目标时提示设置 `DSH_BASE`,不改文件。
---
## 说明
-- 清除目标是 dsh 主包内 `node_modules/@deepseek-ai/*` 的**渲染文案和默认策略**(#1–#8),以及**Harness 本体的权限执行裁决逻辑**(#9–#16:审批、升级阶梯、沙箱 confine、文件系统围栏)。
-- 若 dsh 主包升级后文件结构变化,`patterns` 找不到原文会报告 `pattern_not_found`(不乱改),需更新 patterns。
-- 回滚:每个目标文件独立备份 `<文件>.dshpurge.bak`,`/purge revert` 全部还原(含引擎层)。
-- 不覆盖非 `@deepseek-ai` 的第三方插件行为。
+- 改动范围是本机 `@deepseek-ai/*` 包里的渲染文案、默认策略和执行逻辑,以及用户目录下的覆盖文件与规则集。
+- 升级后原文对不上会报 `pattern_not_found` 或显示待应用,不会乱改。
+- 不改动非 `@deepseek-ai` 的第三方插件。
---
@@ -275,6 +253,6 @@ prompt-inject.md 有内容? ──是──> 注入 systemPrompt section
Built by 小杨 · for DeepSeek Harness
-
---
+
感谢 [LINUX DO](https://linux.do) 社区
diff --git a/docs/banner-dark.svg b/docs/banner-dark.svg
index 6e23c49..ea66dea 100644
--- a/docs/banner-dark.svg
+++ b/docs/banner-dark.svg
@@ -13,6 +13,6 @@
dsh-purge
- 叫我小杨同学· 强制读取设置的规则 (Jailbreak)
- Instruction Authority Purge · 25 patches · auto re-apply
+ DeepSeek Harness 规则设定
+ 25 patches · rule sets · session override
diff --git a/docs/banner.svg b/docs/banner.svg
index 2f847af..58c8e6a 100644
--- a/docs/banner.svg
+++ b/docs/banner.svg
@@ -13,6 +13,6 @@
dsh-purge
- 叫我小杨同学· 强制读取设置的规则 (Jailbreak)
- Instruction Authority Purge · 25 patches · auto re-apply
+ DeepSeek Harness 规则设定
+ 25 patches · rule sets · session override
diff --git a/lib/rules.js b/lib/rules.js
new file mode 100644
index 0000000..1e773da
--- /dev/null
+++ b/lib/rules.js
@@ -0,0 +1,252 @@
+// 规则集:多套 AGENTS.md / CLAUDE.md,切换即写入 ~/.dsh 原生全局指令通道
+// 存储: $DSH_HOME/rules/.md + .json ;状态: rules/state.json
+
+import { promises as fsp } from "node:fs";
+import path from "node:path";
+import { findDshHome } from "./core.js";
+
+const RULE_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
+const MAX_RULE_BYTES = 256 * 1024;
+const MAX_NAME_LENGTH = 64;
+export const RULE_TARGETS = ["AGENTS.md", "CLAUDE.md"];
+
+export { findDshHome };
+
+export function rulesDir(dshHome) {
+ return path.join(dshHome, "rules");
+}
+
+export function stateFile(dshHome) {
+ return path.join(rulesDir(dshHome), "state.json");
+}
+
+export function rulePath(dshHome, id) {
+ return path.join(rulesDir(dshHome), id + ".md");
+}
+
+export function ruleMetaPath(dshHome, id) {
+ return path.join(rulesDir(dshHome), id + ".json");
+}
+
+export function validRuleId(id) {
+ return typeof id === "string" && RULE_ID_RE.test(id);
+}
+
+export function validTarget(target) {
+ return typeof target === "string" && RULE_TARGETS.includes(target);
+}
+
+export function formatSize(bytes) {
+ if (!Number.isFinite(bytes) || bytes < 0) return "0 B";
+ if (bytes < 1024) return `${bytes} B`;
+ const kb = bytes / 1024;
+ return `${kb >= 100 ? Math.round(kb) : kb.toFixed(1)} KB`;
+}
+
+export function targetPath(dshHome, target) {
+ if (!validTarget(target)) throw new Error(`invalid target: ${target}`);
+ return path.join(dshHome, target);
+}
+
+export function normalizeMeta(id, meta) {
+ const name =
+ typeof meta?.name === "string" && meta.name.trim()
+ ? meta.name.trim().slice(0, MAX_NAME_LENGTH)
+ : id;
+ const target = validTarget(meta?.target) ? meta.target : "AGENTS.md";
+ return { name, target };
+}
+
+export async function readRuleMeta(dshHome, id) {
+ try {
+ const parsed = JSON.parse(await fsp.readFile(ruleMetaPath(dshHome, id), "utf8"));
+ return normalizeMeta(id, parsed);
+ } catch {
+ return normalizeMeta(id, null);
+ }
+}
+
+export async function writeRuleMeta(dshHome, id, meta) {
+ if (!validRuleId(id)) throw new Error(`invalid rule id: ${id}`);
+ await fsp.mkdir(rulesDir(dshHome), { recursive: true });
+ await fsp.writeFile(ruleMetaPath(dshHome, id), JSON.stringify(normalizeMeta(id, meta), null, 2), "utf8");
+}
+
+export async function listRules(dshHome) {
+ const dir = rulesDir(dshHome);
+ const out = [];
+ try {
+ const entries = await fsp.readdir(dir, { withFileTypes: true });
+ for (const e of entries) {
+ if (!e.isFile() || !e.name.endsWith(".md")) continue;
+ const id = e.name.slice(0, -3);
+ if (!validRuleId(id)) continue;
+ let size = 0;
+ try {
+ size = (await fsp.stat(path.join(dir, e.name))).size;
+ } catch {
+ /* ignore */
+ }
+ const meta = await readRuleMeta(dshHome, id);
+ out.push({ id, name: meta.name, target: meta.target, size });
+ }
+ } catch {
+ /* rules dir missing → empty */
+ }
+ out.sort((a, b) => a.id.localeCompare(b.id));
+ return out;
+}
+
+export async function readRule(dshHome, id) {
+ if (!validRuleId(id)) throw new Error(`invalid rule id: ${id}`);
+ try {
+ return await fsp.readFile(rulePath(dshHome, id), "utf8");
+ } catch {
+ return null;
+ }
+}
+
+export async function saveRule(dshHome, id, content, meta) {
+ if (!validRuleId(id)) throw new Error(`invalid rule id: ${id}`);
+ if (Buffer.byteLength(content, "utf8") > MAX_RULE_BYTES) {
+ throw new Error("rule too large (max 256KB)");
+ }
+ await fsp.mkdir(rulesDir(dshHome), { recursive: true });
+ await fsp.writeFile(rulePath(dshHome, id), content, "utf8");
+ await writeRuleMeta(dshHome, id, meta);
+ if ((await readActive(dshHome)) === id) {
+ await activateRule(dshHome, id);
+ }
+}
+
+export async function deleteRule(dshHome, id) {
+ if (!validRuleId(id)) throw new Error(`invalid rule id: ${id}`);
+ try {
+ await fsp.unlink(rulePath(dshHome, id));
+ } catch (e) {
+ if (e.code !== "ENOENT") throw e;
+ }
+ try {
+ await fsp.unlink(ruleMetaPath(dshHome, id));
+ } catch (e) {
+ if (e.code !== "ENOENT") throw e;
+ }
+ if ((await readActive(dshHome)) === id) {
+ try {
+ await fsp.unlink(stateFile(dshHome));
+ } catch {
+ /* ignore */
+ }
+ }
+}
+
+export async function readActive(dshHome) {
+ try {
+ const parsed = JSON.parse(await fsp.readFile(stateFile(dshHome), "utf8"));
+ return typeof parsed?.active === "string" && validRuleId(parsed.active) ? parsed.active : null;
+ } catch {
+ return null;
+ }
+}
+
+export async function setActive(dshHome, id) {
+ if (!validRuleId(id)) throw new Error(`invalid rule id: ${id}`);
+ await fsp.mkdir(rulesDir(dshHome), { recursive: true });
+ await fsp.writeFile(stateFile(dshHome), JSON.stringify({ active: id }, null, 2), "utf8");
+}
+
+export async function activateRule(dshHome, id) {
+ const content = await readRule(dshHome, id);
+ if (content === null) throw new Error(`rule not found: ${id}`);
+ const meta = await readRuleMeta(dshHome, id);
+ await fsp.writeFile(targetPath(dshHome, meta.target), content, "utf8");
+ await setActive(dshHome, id);
+ return meta;
+}
+
+export async function ensureInitialState(dshHome) {
+ const listed = await listRules(dshHome);
+ let active = await readActive(dshHome);
+ if (active !== null && !listed.some((r) => r.id === active)) {
+ try {
+ await fsp.unlink(stateFile(dshHome));
+ } catch {
+ /* ignore */
+ }
+ active = null;
+ }
+ if (active !== null) return { active };
+ if (listed.length > 0) return { active: null };
+ for (const target of RULE_TARGETS) {
+ try {
+ const content = await fsp.readFile(targetPath(dshHome, target), "utf8");
+ if (content.trim().length > 0) {
+ await saveRule(dshHome, "default", content, { name: "默认规则", target });
+ await setActive(dshHome, "default");
+ return { active: "default", imported: target };
+ }
+ } catch {
+ /* file missing, try next target */
+ }
+ }
+ return { active: null };
+}
+
+export async function resetToOriginal(dshHome) {
+ const active = await readActive(dshHome);
+ const removed = [];
+ const skipped = [];
+ if (active !== null) {
+ const meta = await readRuleMeta(dshHome, active);
+ const ruleContent = await readRule(dshHome, active);
+ const fp = targetPath(dshHome, meta.target);
+ try {
+ const fileContent = await fsp.readFile(fp, "utf8");
+ if (ruleContent !== null && fileContent === ruleContent) {
+ await fsp.unlink(fp);
+ removed.push(fp);
+ } else {
+ skipped.push(fp);
+ }
+ } catch {
+ /* 目标文件不存在 */
+ }
+ }
+ try {
+ await fsp.unlink(stateFile(dshHome));
+ } catch {
+ /* 无状态文件 */
+ }
+ return { removed, skipped };
+}
+
+export async function rulesStatus(dshHome) {
+ const listed = await listRules(dshHome);
+ const active = await readActive(dshHome);
+ let active_target = null;
+ let agents_exists = false;
+ let agents_synced = false;
+ let agents_path = targetPath(dshHome, "AGENTS.md");
+ if (active !== null) {
+ const meta = await readRuleMeta(dshHome, active);
+ active_target = meta.target;
+ agents_path = targetPath(dshHome, meta.target);
+ try {
+ const content = await fsp.readFile(agents_path, "utf8");
+ agents_exists = true;
+ const ruleContent = await readRule(dshHome, active);
+ agents_synced = ruleContent !== null && ruleContent === content;
+ } catch {
+ /* target file missing */
+ }
+ }
+ return {
+ rules: listed,
+ active,
+ active_target,
+ agents_exists,
+ agents_synced,
+ agents_path,
+ rules_dir: rulesDir(dshHome),
+ };
+}