@gluztm/dsh-guard 2.4.2 → 2.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -1,46 +1,44 @@
1
1
  # @gluztm/dsh-guard
2
2
 
3
- > Cross-platform configuration, extension, and snapshot companion plugin for **DeepSeek Harness (DSH)**. Runs directly inside DSH Web and CLI without external installers: toggle plugins & MCP servers with automatic backups, repair broken symlinks, inspect `llm-pi-ai` providers, blind-write `.credentials.yaml` refs, and compare/restore local YAML/JSON snapshots.
3
+ > Cross-platform DSH control plane and companion governance plugin for **DeepSeek Harness (DSH)**. Runs directly inside DSH Web and Desktop without external installers: **auto-detects the running host profile (`desktop` on Desktop, `web` on Web)** with zero cross-profile noise, toggles plugins/MCP & tunes timeouts with local loopback probing, governs Skills/context footprint, blind-writes `.credentials.yaml` refs, and maintains pinned YAML/JSON snapshots with redacted audit logs.
4
4
 
5
- [中文文档](./README.md) · [GitHub Repository](https://github.com/gluztm/DSHGuard) · [Releases](https://github.com/gluztm/DSHGuard/releases/tag/2.4.2)
5
+ [中文文档](./README.md) · [GitHub Repository](https://github.com/gluztm/DSHGuard) · [Roadmap](https://github.com/gluztm/DSHGuard/blob/main/docs/ROADMAP-COMPANION.md) · [Releases](https://github.com/gluztm/DSHGuard/releases/tag/2.4.3)
6
6
 
7
- ![@gluztm/dsh-guard v2.4.2 Companion Panel Preview](https://raw.githubusercontent.com/gluztm/DSHGuard/main/docs/screenshots/242-companion-sidebar.png)
7
+ ![@gluztm/dsh-guard Companion Panel Preview](https://raw.githubusercontent.com/gluztm/DSHGuard/main/docs/screenshots/242-companion-sidebar.png)
8
8
 
9
9
  ## Built-In Capabilities
10
10
 
11
- 1. **Plugin & MCP Toggle Switchboard (Web & Desktop tracks)**
12
- - Resolves per-package `loaderId` declarations via `dsh.bundle.patch` / `cordis.patch.yml` and detects `@deepseek-ai/dsh-mcp-client` servers.
13
- - Protects core `@deepseek-ai/*` modules and the companion plugin itself from accidental disablement.
14
- - Creates an automatic pre-change snapshot before modifying `cordis.patch.yml` using strict YAML quoting rules.
15
- 2. **Profile Drift & Broken Symlink Repair**
16
- - Audits `profiles/web` and `profiles/desktop` for missing `dsh.bundles` dependencies and hash drift.
17
- - Detects broken symlinks / NTFS junctions under `node_modules` and relinks valid targets from `.dsh-module-fallback` or sibling profiles in pure Node.js.
18
- 3. **`llm-pi-ai` Inspection & One-Way `.credentials.yaml` Blind Write**
19
- - Displays provider protocols (`anthropic-messages`, `openai-completions`, `google-generative-ai`), `baseURL`, model counts, and key readiness badges.
20
- - **Zero secret readback**: writes user-entered API keys strictly one-way into `.credentials.yaml` `refs:` while preserving `version`, `records`, comments, and protected `*_ACCOUNT_*` OAuth blocks. Never reads back or transmits plaintext values (`redLines: []`, `secretTouches: []` in `dsh-trust-check`).
21
- 4. **Native Config Snapshots, Live SHA256 Diff & Whitelist Rollback**
22
- - Backs up `cordis.patch.yml`, `cordis.yml`, `package.json`, and `settings.yaml` into `~/.dsh/guard-snapshots` (**strictly excluding** `.credentials.yaml` and secret files).
23
- - Computes live SHA256 file diff status against disk and restores whitelisted YAML/JSON configs in 1 click (with an automatic `pre-restore` backup).
24
- 5. **Agent Tools, Slash Command & CLI**
25
- - Tools: `dsh_guard_status`, `dsh_guard_snapshots`, `dsh_guard_backup`, `dsh_guard_open`
26
- - Slash command: `/guard [status|snapshots|backup [web|desktop|all]|open]`
27
- - CLI: `dsh-guard status [--json]`, `dsh-guard snapshots`, `dsh-guard backup [web|desktop]`, `dsh-guard repair [web|desktop]`
11
+ 1. **Single-Track Host Auto-Detection & Broken Symlink Repair**
12
+ - Automatically locks onto the active DSH host track (`desktop` when launched inside DSH Desktop, `web` when launched in DSH Web), omitting `headless`, custom directories, and cross-profile drift alerts.
13
+ - Detects broken symlinks / NTFS junctions under `node_modules` and relinks valid targets from `.dsh-module-fallback` or sibling profiles in pure Node.js; any unresolvable links return HTTP 200 with a clear list instead of failing with HTTP 400.
14
+ 2. **Plugin & MCP Switchboard, Timeout Tuning & Safe Local Probe**
15
+ - Resolves `dsh.bundle.patch` / `cordis.patch.yml` loader IDs and `@deepseek-ai/dsh-mcp-client` entries while protecting core `@deepseek-ai/*` modules and the companion plugin itself.
16
+ - Losslessly tunes per-MCP `toolCallTimeoutMs` (`5000`–`600000 ms`) with automatic pre-change `auto-mcp` snapshots.
17
+ - Probes MCP health safely without side effects: HTTP/SSE servers are probed **strictly on loopback addresses** (`127.0.0.1` / `localhost` / `::1`, SSRF-safe) via TCP connect; `stdio` entries are checked on disk for executable and script path readiness.
18
+ 3. **Startup Context Footprint Audit & Skills Visibility Governance**
19
+ - Estimates the active profile's startup token overhead across active third-party plugins, enabled MCP servers, visible Skills, and permanent prompt files (`prompt-inject.md`, `MEMORY.md`, `prompts/*.md`, `system-prompt`).
20
+ - Scans `~/.dsh/skills`, `~/.agents/skills`, and read-only plugin skills (`SKILL.md`), allowing lossless toggles of `disable-model-invocation` and `user-invocable` frontmatter flags with SHA256 fingerprint conflict detection.
21
+ 4. **`llm-pi-ai` Inspection & One-Way `.credentials.yaml` Blind Write**
22
+ - Displays configured providers, protocols, endpoints, model counts, and key readiness for the active profile; includes 7 mainstream provider env-key presets in the add-key drawer.
23
+ - **Zero secret readback**: writes user-entered API keys strictly one-way into `.credentials.yaml` `refs:` while preserving `version`, `records`, comments, and protected `*_ACCOUNT_*` OAuth blocks (`redLines: []`, `secretTouches: []` in `dsh-trust-check`).
24
+ 5. **Pinned Snapshots, Live SHA256 Diff Rollback & Redacted Audit Log**
25
+ - Backs up `cordis.patch.yml`, `cordis.yml`, `package.json`, and `settings.yaml` into `~/.dsh/guard-snapshots` (strictly excluding `.credentials.yaml`), supports **📌 Pin** protection against auto-pruning, 1-click whitelist rollback, and redacted mutation tracking in `~/.dsh/guard-state/audit.jsonl`.
26
+ 6. **6 Agent Tools, Slash Command & CLI**
27
+ - Tools: `dsh_guard_status`, `dsh_guard_context_audit`, `dsh_guard_mcp_probe`, `dsh_guard_snapshots`, `dsh_guard_backup`, `dsh_guard_open`
28
+ - Slash command: `/guard [status|context|mcp|snapshots|backup [web|desktop]|open]`
29
+ - CLI: `dsh-guard status [--target web|desktop] [--json]`, `dsh-guard context [--json]`, `dsh-guard mcp-probe [--json]`, `dsh-guard snapshots`, `dsh-guard backup [web|desktop]`, `dsh-guard repair [web|desktop]`, `dsh-guard audit [--json]`
28
30
 
29
31
  ---
30
32
 
31
33
  ## Architecture & Security Boundaries (When Native Desktop App Is Needed)
32
34
 
33
- Routine plugin toggling, credential key entry, link repair, and YAML config snapshots all run directly inside `@gluztm/dsh-guard`. A smaller set of OS-level / out-of-band workflows cannot safely execute inside a live DSH host plugin and live exclusively in the standalone **[DSHGuard Desktop (Windows)](https://github.com/gluztm/DSHGuard/releases/tag/2.4.2)** app:
35
+ Routine active-profile inspection, extension & context governance, local MCP probing, blind-write credential setup, and YAML config snapshots all run directly inside `@gluztm/dsh-guard`. A smaller set of OS-level / out-of-band workflows cannot safely execute inside a live DSH host plugin and live exclusively in the standalone **[DSHGuard Desktop (Windows)](https://github.com/gluztm/DSHGuard/releases/tag/2.4.3)** app:
34
36
 
35
37
  | Area | Handled Inside Companion Plugin | Exclusive to Native Desktop App (Why) |
36
38
  | :--- | :--- | :--- |
37
- | **Extension Lifecycle** | Toggle plugins & MCP entries, repair symlinks | **Fresh install / full uninstall / force kill locks**: running `npm install` or deleting `node_modules` inside the live host tears loaded modules and hits file locks; plugins should also never pull remote installers or terminate the host process. |
39
+ | **Extension Lifecycle** | Toggle plugins, MCP & Skills; tune MCP timeouts; local probe; repair symlinks | **Fresh install / full uninstall / force kill locks**: running `npm install` or deleting `node_modules` inside the live host tears loaded modules and hits file locks; plugins should also never pull remote installers or terminate the host process. |
38
40
  | **Secrets & Migration** | Key existence audit + one-way write to `.credentials.yaml` | **Plaintext vault, Windows DPAPI & CC Switch import**: Web UI plugins with `fetch` are barred from reading back secrets; hardware-bound DPAPI encryption and cross-tool migrations rely on native Windows security APIs. |
39
- | **System Rollback** | Live diff & rollback of YAML/JSON configs | **Full `node_modules` ZIP recovery & crash recovery**: restoring full package trees and relaunching DSH requires an external supervisor running out of process. |
41
+ | **System Rollback** | Live diff, pinning & rollback of YAML/JSON configs | **Full `node_modules` ZIP recovery & crash recovery**: restoring full package trees and relaunching DSH requires an external supervisor running out of process. |
40
42
 
41
43
  - When `DSHGuard.exe` is detected locally on Windows, the header shows an unobtrusive **Open Desktop** action.
42
- - Windows users who need those out-of-band capabilities can obtain [DSHGuard-Setup-2.4.2.exe](https://github.com/gluztm/DSHGuard/releases/download/2.4.2/DSHGuard-Setup-2.4.2.exe) from [Release v2.4.2](https://github.com/gluztm/DSHGuard/releases/tag/2.4.2).
43
-
44
- ## License
45
-
46
- MIT © gluztm
44
+ - Windows users who need those out-of-band capabilities can obtain [DSHGuard-Setup-2.4.3.exe](https://github.com/gluztm/DSHGuard/releases/download/2.4.3/DSHGuard-Setup-2.4.3.exe) from [Release v2.4.3](https://github.com/gluztm/DSHGuard/releases/tag/2.4.3).
package/README.md CHANGED
@@ -1,46 +1,49 @@
1
1
  # @gluztm/dsh-guard
2
2
 
3
- > 面向 **DeepSeek Harness (DSH)** 的跨平台伴生配置与扩展管理插件:无需额外安装独立软件,直接在 Web 侧边栏与全屏页面内完成 **插件 / MCP 开关(变更前自动备份)**、**断裂依赖修复**、**`llm-pi-ai` 巡检与 `.credentials.yaml` 单向盲写** 及 **本地 YAML/JSON 配置快照 + SHA256 差异回滚**。
3
+ > 面向 **DeepSeek Harness (DSH)** 的跨平台运行时底座治理与伴生控制面板:无需额外安装独立软件,**自动识别当前宿主运行端(桌面端仅看 `desktop`、Web 端仅看 `web`)**,直接在 Web 侧边栏与 CLI 内完成 **健康巡检与断链自愈**、**插件/MCP 启停与超时调优及本地探活**、**上下文与 Skills 可见性治理**、**`.credentials.yaml` 单向盲写** 及 **本地配置快照置顶 + 脱敏审计回滚**。
4
4
 
5
- [English Documentation](./README.en.md) · [GitHub 仓库](https://github.com/gluztm/DSHGuard) · [Releases](https://github.com/gluztm/DSHGuard/releases/tag/2.4.2)
5
+ [English Documentation](./README.en.md) · [GitHub 仓库](https://github.com/gluztm/DSHGuard) · [演进计划书](https://github.com/gluztm/DSHGuard/blob/main/docs/ROADMAP-COMPANION.md) · [Releases](https://github.com/gluztm/DSHGuard/releases/tag/2.4.3)
6
6
 
7
- ![@gluztm/dsh-guard v2.4.2 侧边栏实景:插件启停、凭据盲写与快照回滚](https://raw.githubusercontent.com/gluztm/DSHGuard/main/docs/screenshots/242-companion-sidebar.png)
7
+ ![@gluztm/dsh-guard 侧边栏实景:插件启停、凭据盲写与快照回滚](https://raw.githubusercontent.com/gluztm/DSHGuard/main/docs/screenshots/242-companion-sidebar.png)
8
8
 
9
9
  ## 伴生插件内置核心能力
10
10
 
11
- 1. **插件与 MCP 实时启停开关(Web / Desktop 双轨)**
12
- - 自动解析各插件包 `dsh.bundle.patch` / `cordis.patch.yml` 的 `loaderId` 及 `mcp-client` 条目。
13
- - 搜索过滤 MCP 服务与已安装插件;内置保护标记(禁止误关 `@deepseek-ai/*` 核心组件或插件自身)。
14
- - 每次切换开关前都会自动保存一份配置快照(`auto-toggle`),按 Cordis 规则安全引用 `- id:`。
15
- 2. **双轨健康巡检与一键断链修复**
16
- - 对比 `profiles/web` 与 `profiles/desktop` 的 `dependencies`、`dsh.bundles` 漂移与 `cordis.patch.yml` 哈希。
17
- - 检测并直接修复 `node_modules` 下失效的符号链接 / NTFS Junction,自动链接至 `.dsh-module-fallback` 或兄弟档案。
18
- 3. **模型提供商巡检与 `.credentials.yaml` 纯单向盲写**
19
- - 汇总 `llm-pi-ai` 中配置的各家协议(`anthropic-messages` / `openai-completions` / `google-generative-ai`)、`baseURL`、模型数量与环境变量就绪状态。
20
- - **零明文回显**:可在前端为提供商或自定义环境变量名设置 API Key,服务端采用「只写入 `refs:`、保留 `version`/`records`/`*_ACCOUNT_*` OAuth 块、响应绝不返回明文」的单向盲写模型(通过 `dsh-trust-check` 静态扫描零红线)。
21
- 4. **原生插件快照与实时文件 SHA256 差异回滚**
22
- - 将 `cordis.patch.yml`、`cordis.yml`、`package.json`、`settings.yaml` 备份至 `~/.dsh/guard-snapshots`(**严格排除** `.credentials.yaml` 等任何敏感文件)。
23
- - 与磁盘现行配置实时比对 SHA256 状态(`一致` / `已变更` / `已删除`),支持白名单内配置文件一键安全还原(还原前自动二次备份 `pre-restore`)。
24
- 5. **内置 4 个 Agent 工具 + `/guard` 斜杠命令 + CLI**
25
- - Agent 工具:`dsh_guard_status`、`dsh_guard_snapshots`、`dsh_guard_backup`、`dsh_guard_open`
26
- - 斜杠命令:`/guard`、`/guard status`、`/guard snapshots`、`/guard backup [web|desktop|all]`、`/guard open`
27
- - CLI:`dsh-guard status [--json]`、`dsh-guard snapshots`、`dsh-guard backup [web|desktop]`、`dsh-guard repair [web|desktop]`
11
+ 1. **当前运行端自动识别与断链自愈**
12
+ - 自动识别当前 DSH 宿主运行端(桌面端运行自动绑定 `desktop`,Web 端运行自动绑定 `web`),仅聚焦展示并管理当前活跃档案,不扫描 `headless` 或私有目录,彻底消除跨端对比冗余与漂移噪音。
13
+ - 检测 `node_modules` 下失效的符号链接 / NTFS Junction,自动从 `.dsh-module-fallback` 或兄弟档案恢复;若个别断链已无法从本地找到有效源,仍安全完成可修项目并返回清晰清单提示(不再报 HTTP 400)。
14
+ 2. **插件与 MCP 全生命周期启停、超时微调与本地安全探活**
15
+ - 自动解析 `dsh.bundle.patch` / `cordis.patch.yml` 的 `loaderId` 及 `@deepseek-ai/dsh-mcp-client` 服务,保护 `@deepseek-ai/*` 核心组件与插件自身。
16
+ - 支持无损调节单个 MCP 的 `toolCallTimeoutMs`(`5000`–`600000 ms`),改动前自动保留 `auto-mcp` 快照。
17
+ - 提供只读本地 MCP 探活:HTTP/SSE 型**严格限制仅探测回环地址**(`127.0.0.1` / `localhost` / `::1`)防 SSRF;`stdio` 型校验本地命令与入口脚本文件存在性,不执行第三方命令。
18
+ 3. **上下文负担体检与 Skills 可见性治理**
19
+ - 汇总当前运行端启用的第三方插件、MCP 工具与常驻提示词(`prompt-inject.md`、`MEMORY.md`、`prompts/*.md`、`system-prompt`)估算基线 Token 与负担等级,提供精简建议。
20
+ - 扫描 `~/.dsh/skills`、`~/.agents/skills` 与插件内置 `SKILL.md`(插件内只读保护),允许对用户技能无损切换 `disable-model-invocation` 与 `user-invocable` 前置元数据开关(保存前比对 SHA256 指纹并保留原换行符/BOM)。
21
+ 4. **模型提供商巡检与 `.credentials.yaml` 纯单向盲写**
22
+ - 汇总当前运行档案中的 `llm-pi-ai` 协议(`anthropic-messages` / `openai-completions` / `google-generative-ai`)、`baseURL` 与凭据就绪状态;内置 7 套通用主流平台预设快速填入环境变量名。
23
+ - **零明文回显**:保留 `version`、`records`、`*_ACCOUNT_*` 受保护 OAuth 块,响应报文绝不返回密钥字符(通过 `dsh-trust-check` 静态扫描零红线)。
24
+ 5. **配置快照置顶、SHA256 差异回滚与脱敏审计流水**
25
+ - 备份 `cordis.patch.yml`、`cordis.yml`、`package.json`、`settings.yaml` 至 `~/.dsh/guard-snapshots`(严格排除密钥文件),支持 **📌 置顶保护**(免受自动轮转清理)与白名单一键还原。
26
+ - 每次通过伴生插件完成的变更自动写入 `~/.dsh/guard-state/audit.jsonl`(纯结构化脱敏记录,绝不含密钥值)。
27
+ 6. **内置 6 个 Agent 工具 + `/guard` 斜杠命令 + CLI**
28
+ - Agent 工具:`dsh_guard_status`、`dsh_guard_context_audit`、`dsh_guard_mcp_probe`、`dsh_guard_snapshots`、`dsh_guard_backup`、`dsh_guard_open`
29
+ - 斜杠命令:`/guard`、`/guard status`、`/guard context`、`/guard mcp`、`/guard snapshots`、`/guard backup [web|desktop]`、`/guard open`
30
+ - CLI:`dsh-guard status [--target web|desktop] [--json]`、`dsh-guard context [--json]`、`dsh-guard mcp-probe [--json]`、`dsh-guard snapshots`、`dsh-guard backup [web|desktop]`、`dsh-guard repair [web|desktop]`、`dsh-guard audit [--json]`
28
31
 
29
32
  ---
30
33
 
31
34
  ## 技术与安全边界说明(何时需要原生桌面端)
32
35
 
33
- 本伴生插件已经覆盖日常高频的开关、密钥盲写与 YAML 配置备份回滚需求;以下能力由于操作系统或安全架构限制,**无法在运行中的 DSH Node 宿主插件内部安全实现**,仅在独立进程外原生程序 **[DSHGuard Desktop (Windows)](https://github.com/gluztm/DSHGuard/releases/tag/2.4.2)** 中提供:
36
+ 本伴生插件已经覆盖当前运行端的日常巡检、扩展与上下文治理、MCP 本地探活、密钥盲写与配置快照回滚需求;以下能力由于操作系统或安全架构限制,**无法在运行中的 DSH Node 宿主插件内部安全实现**,仅在独立进程外原生程序 **[DSHGuard Desktop (Windows)](https://github.com/gluztm/DSHGuard/releases/tag/2.4.3)** 中提供:
34
37
 
35
38
  | 能力领域 | 伴生插件内置能力 | 仅独立原生桌面端提供(及原因) |
36
39
  | :--- | :--- | :--- |
37
- | **插件包生命周期** | 安全切换插件/MCP 开关、断链修复 | **全新安装 / 彻底卸载 / 强杀锁死进程**:运行时在宿主进程内删除或重装 `node_modules` 会撕裂已加载模块并触发文件占用锁死;且插件不应持有远端包拉取与进程强杀权。 |
40
+ | **插件包生命周期** | 安全切换插件/MCP/Skills 开关、超时调优、本地探活、断链修复 | **全新安装 / 彻底卸载 / 强杀锁死进程**:运行时在宿主进程内删除或重装 `node_modules` 会撕裂已加载模块并触发文件占用锁死;且插件不应持有远端包拉取与进程强杀权。 |
38
41
  | **凭据安全与导入** | `.credentials.yaml` 键名审计 + 单向盲写 | **明文编辑 / Windows DPAPI 硬件加密库 / CC Switch 导入**:Web 插件拥有前端请求能力,依据安全合规禁止反向回显明文;DPAPI 与跨工具配置迁移依赖 Windows 原生安全 API。 |
39
- | **系统级备份恢复** | YAML/JSON 配置文件实时对比与回滚 | **整包扩展目录 ZIP 归档 + 主程序崩溃带外恢复**:涵盖整套 `node_modules` 与主程序启停的重型恢复必须脱离 DSH 宿主进程独立调度。 |
42
+ | **系统级备份恢复** | YAML/JSON 配置文件实时对比、置顶保护与白名单回滚 | **整包扩展目录 ZIP 归档 + 主程序崩溃带外恢复**:涵盖整套 `node_modules` 与主程序启停的重型恢复必须脱离 DSH 宿主进程独立调度。 |
40
43
 
41
44
  - 若本机已安装 Windows 原生桌面端,插件右上角会自动显示「打开桌面端」快捷入口。
42
- - 仅需要上述带外桌面功能时,可在 [GitHub Release v2.4.2](https://github.com/gluztm/DSHGuard/releases/tag/2.4.2) 获取 [DSHGuard-Setup-2.4.2.exe](https://github.com/gluztm/DSHGuard/releases/download/2.4.2/DSHGuard-Setup-2.4.2.exe)(源码可审计,基于 .NET 8 + WPF 原生构建)。
45
+ - 仅需要上述带外桌面功能时,可在 [GitHub Release v2.4.3](https://github.com/gluztm/DSHGuard/releases/tag/2.4.3) 获取 [DSHGuard-Setup-2.4.3.exe](https://github.com/gluztm/DSHGuard/releases/download/2.4.3/DSHGuard-Setup-2.4.3.exe)(源码可审计,基于 .NET 10 + WPF 原生构建)。
43
46
 
44
47
  ## 许可协议
45
48
 
46
- MIT © gluztm
49
+ GPL-3.0 © gluztm
package/bin/dsh-guard.mjs CHANGED
@@ -2,11 +2,18 @@
2
2
  import {
3
3
  PACKAGE_VERSION,
4
4
  createSnapshot,
5
+ detectActiveProfile,
6
+ formatContextAuditText,
5
7
  formatHealthText,
8
+ formatMcpProbeText,
6
9
  formatSnapshotsText,
10
+ inspectContextAudit,
7
11
  inspectHealth,
8
12
  inspectSnapshots,
13
+ normalizeProfileTarget,
9
14
  openGuard,
15
+ probeMcpServers,
16
+ readAuditLog,
10
17
  repairBrokenModuleLinks,
11
18
  resolveDshHome,
12
19
  } from '../lib/inspector.mjs'
@@ -16,7 +23,7 @@ function parseArgs(argv) {
16
23
  command: 'status',
17
24
  json: false,
18
25
  launch: false,
19
- target: 'all',
26
+ target: '',
20
27
  limit: 20,
21
28
  dshHome: undefined,
22
29
  guardHome: undefined,
@@ -54,22 +61,34 @@ function parseArgs(argv) {
54
61
  if (positionals.length > 0) {
55
62
  opts.command = positionals[0].toLowerCase()
56
63
  }
57
- if (positionals.length > 1 && (opts.command === 'backup' || opts.command === 'repair')) {
58
- opts.target = positionals[1].toLowerCase()
64
+ if (
65
+ positionals.length > 1 &&
66
+ (opts.command === 'backup' || opts.command === 'repair' || opts.command === 'context' || opts.command === 'mcp-probe')
67
+ ) {
68
+ opts.target = positionals[1]
59
69
  }
60
70
  return opts
61
71
  }
62
72
 
73
+ function resolveCliTarget(rawTarget, dshHome) {
74
+ const explicit = normalizeProfileTarget(rawTarget)
75
+ if (explicit) return explicit
76
+ return detectActiveProfile({ dshHome, preferExistingOnCli: true })
77
+ }
78
+
63
79
  function printHelp() {
64
80
  console.log(
65
81
  [
66
- `dsh-guard v${PACKAGE_VERSION} — DSH 伴生管理工具`,
82
+ `dsh-guard v${PACKAGE_VERSION} — DSH 单端自动感知伴生管理工具`,
67
83
  '',
68
84
  '用法:',
69
- ' dsh-guard status [--target all|web|desktop] [--dsh-home PATH] [--json]',
70
- ' dsh-guard snapshots [--target all|web|desktop] [--limit N] [--json]',
71
- ' dsh-guard backup [web|desktop|all] [--dsh-home PATH] [--json]',
72
- ' dsh-guard repair [web|desktop] [--dsh-home PATH] [--json]',
85
+ ' dsh-guard status [--target desktop|web] [--dsh-home PATH] [--json]',
86
+ ' dsh-guard context [--target desktop|web] [--dsh-home PATH] [--json]',
87
+ ' dsh-guard mcp-probe [--target desktop|web] [--dsh-home PATH] [--json]',
88
+ ' dsh-guard snapshots [--target desktop|web] [--limit N] [--json]',
89
+ ' dsh-guard backup [desktop|web] [--dsh-home PATH] [--json]',
90
+ ' dsh-guard repair [desktop|web] [--dsh-home PATH] [--json]',
91
+ ' dsh-guard audit [--limit N] [--dsh-home PATH] [--json]',
73
92
  ' dsh-guard open [--launch] [--json]',
74
93
  ].join('\n'),
75
94
  )
@@ -82,20 +101,50 @@ async function main() {
82
101
  return
83
102
  }
84
103
 
104
+ const dshHome = resolveDshHome(opts.dshHome)
105
+ const activeTarget = resolveCliTarget(opts.target, dshHome)
106
+
85
107
  if (opts.command === 'snapshots' || opts.command === 'snap') {
86
108
  const report = inspectSnapshots({
87
- dshHome: opts.dshHome,
109
+ dshHome,
88
110
  guardHome: opts.guardHome,
89
- target: opts.target,
111
+ target: activeTarget,
90
112
  limit: opts.limit,
91
113
  })
92
114
  console.log(opts.json ? JSON.stringify(report, null, 2) : formatSnapshotsText(report))
93
115
  return
94
116
  }
95
117
 
118
+ if (opts.command === 'context' || opts.command === 'ctx') {
119
+ const health = inspectHealth({ dshHome, guardHome: opts.guardHome, activeProfile: activeTarget })
120
+ const report = inspectContextAudit(dshHome, health, activeTarget)
121
+ console.log(opts.json ? JSON.stringify(report, null, 2) : formatContextAuditText(report))
122
+ return
123
+ }
124
+
125
+ if (opts.command === 'mcp-probe' || opts.command === 'mcp') {
126
+ const health = inspectHealth({ dshHome, guardHome: opts.guardHome, activeProfile: activeTarget })
127
+ const report = await probeMcpServers(dshHome, health.extensions, activeTarget)
128
+ console.log(opts.json ? JSON.stringify(report, null, 2) : formatMcpProbeText(report))
129
+ return
130
+ }
131
+
132
+ if (opts.command === 'audit') {
133
+ const records = readAuditLog(dshHome, opts.limit)
134
+ if (opts.json) {
135
+ console.log(JSON.stringify({ total: records.length, records }, null, 2))
136
+ } else if (records.length === 0) {
137
+ console.log('暂无变更审计记录。')
138
+ } else {
139
+ for (const r of records) {
140
+ console.log(`[${r.ts}] (${r.action}/${r.target}) ${r.summary}${r.snapshotId ? ` [snap=${r.snapshotId}]` : ''}`)
141
+ }
142
+ }
143
+ return
144
+ }
145
+
96
146
  if (opts.command === 'backup') {
97
- const t = opts.target === 'desktop' || opts.target === 'all' ? opts.target : 'web'
98
- const res = createSnapshot(resolveDshHome(opts.dshHome), t, 'manual', 'CLI dsh-guard backup')
147
+ const res = createSnapshot(dshHome, activeTarget, 'manual', 'CLI dsh-guard backup')
99
148
  if (opts.json) {
100
149
  console.log(JSON.stringify(res, null, 2))
101
150
  } else {
@@ -105,12 +154,11 @@ async function main() {
105
154
  }
106
155
 
107
156
  if (opts.command === 'repair') {
108
- const t = opts.target === 'desktop' ? 'desktop' : 'web'
109
- const res = repairBrokenModuleLinks(resolveDshHome(opts.dshHome), t)
157
+ const res = repairBrokenModuleLinks(dshHome, activeTarget)
110
158
  if (opts.json) {
111
159
  console.log(JSON.stringify(res, null, 2))
112
160
  } else {
113
- console.log(`断链修复 (${res.target}): 已修复 ${res.repairedCount},未解析 ${res.unresolvableCount}`)
161
+ console.log(res.message || `断链修复 (${res.target}): 已修复 ${res.repairedCount},未解析 ${res.unresolvableCount}`)
114
162
  }
115
163
  return
116
164
  }
@@ -121,7 +169,7 @@ async function main() {
121
169
  return
122
170
  }
123
171
 
124
- const health = inspectHealth({ dshHome: opts.dshHome, guardHome: opts.guardHome, target: opts.target })
172
+ const health = inspectHealth({ dshHome, guardHome: opts.guardHome, activeProfile: activeTarget })
125
173
  console.log(opts.json ? JSON.stringify(health, null, 2) : formatHealthText(health))
126
174
  }
127
175