dsh-awesome-optimizer 0.0.0-stage → 1.7.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jaylor-Wang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,227 @@
1
- # Temporary Holding Version
1
+ # dsh-awesome-optimizer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [中文](README.zh.md)
4
+
5
+ [![npm version](https://img.shields.io/npm/v/dsh-awesome-optimizer.svg?color=blue)](https://www.npmjs.com/package/dsh-awesome-optimizer)
6
+ [![license](https://img.shields.io/github/license/Jaylor-Wang/dsh-awesome-optimizer.svg)](LICENSE)
7
+ [![GitHub release](https://img.shields.io/github/v/release/Jaylor-Wang/dsh-awesome-optimizer.svg)](https://github.com/Jaylor-Wang/dsh-awesome-optimizer/releases)
8
+ [![Tests](https://img.shields.io/badge/tests-21%20passed-brightgreen.svg)](test/)
9
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Strict%20Types-blue.svg)](src/)
10
+
11
+ High-performance runtime policy guards, PTC-backed composite batch tooling, standalone refined system prompt engine, and objective A/B turn telemetry plugin for the official [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`@deepseek-ai/dsh-agent-loop`).
12
+
13
+ ---
14
+
15
+ ## Highlights in v1.7.0
16
+
17
+ - **Environment Facts Hardening & Weak Modal Elimination**: Upgraded injected environment facts to strict RFC 2119 directives (`NEVER require/import as node modules`, `NEVER run exploratory probing`), completely eliminating weak modals (`Avoid`) and preventing exploratory startup probing.
18
+ - **Cross-Platform Python Environment Detection (`detectPythonEnv`)**: Safely detects active Python runtimes (`python` / `python3` and version) with one-shot memoization and timeout guards, unblocking cross-platform parity while steering models gracefully to Node.js when Python is absent.
19
+ - **Playwright File Protocol Guard (`PLAYWRIGHT_FILE_PROTOCOL_BLOCKED`)**: Pre-execution interception of `playwright-cli open/goto file://...` commands, steering models toward local HTTP loopback servers to eliminate protocol errors and orphaned browser processes.
20
+ - **Host Environment Facts Injection (`injectEnvironmentFacts`)**: Zero-overhead injection of active Node.js version, platform, CLI tool boundaries, and browser protocol facts into system prompts, eliminating speculative startup probe turns (`node -v`, `which`).
21
+ - **CLI vs NPM Module Import Confusion Guard**: Added `cli-require-confusion` static lint rule in Prompt Linter to detect and prevent treating standalone CLIs (`playwright-cli`, `gh`, `ast-grep`) as requireable npm packages.
22
+ - **Refined Batch Tooling Directives & Windows Arguments Streamlining**: Upgraded batch scheduling directives to `MUST`, eliminated cross-file grammatical ambiguities, and streamlined Windows arguments instructions by 52% with strict `NEVER raw shell arguments` enforcement.
23
+
24
+ ---
25
+
26
+ ## Core Features & Architecture
27
+
28
+ ### 1. Refined System Prompt & File-Driven Hot-Reload (`customPrompt`)
29
+
30
+ - **Standalone Mode (`placement: "replace-all"`)**:
31
+ Hooks into the DSH `system-prompt/assemble` waterfall to strip all official verbose sections (`harness:*`, `deployment:*`, `tool:*`, `deliverable:*`, `web:*`), preserving convergence guidance companion sections while presenting your refined `SYSTEM.md` as the standalone authority.
32
+ - **Dual-Layer Markdown Convention**:
33
+ Automatically discovers global `~/.dsh/SYSTEM.md` (or `$DSH_HOME/SYSTEM.md`) and project workspace `.dsh/SYSTEM.md` (or `SYSTEM.md`), cleanly separating developer system defaults from repo-specific instructions.
34
+ - **Millisecond Hot-Reload**:
35
+ Uses debounced `fs.watch` to detect prompt file edits and applies them reactively on the very next turn without restarting the DSH process.
36
+ - **Flexible Cascading Strategies**:
37
+ Supports `concat` (cascading global and workspace prompts, default) and `workspace-override` (repo prompt completely replaces global prompt).
38
+ - **Built-in Prompt Linter & Auto-Fixer**:
39
+ Provides `lintPrompt` / `fixPrompt` / `lintPromptFile` APIs with **preset-aware dynamic tool validation**. Eliminates subjective tool assumptions by verifying tool directives directly against active plugins: flags redundant defensive clauses for unloaded tools or conflicts with actively loaded tools, checks weak modals (`bias toward` -> `Prioritize`), unclosed backticks, and enforces RFC 2119 uppercase constraints with actionable health scoring (0-100).
40
+
41
+ | Dimension | Official Default System Prompt | Optimized with This Plugin | Savings |
42
+ | :--- | :--- | :--- | :--- |
43
+ | **Prompt Context Footprint** | ~2,000 tokens / turn | **~380 tokens / turn (Template)** | **Frees context headroom; eliminates redundant rules** |
44
+ | **Long Multi-Turn Sessions** | ~100K redundant tokens across 50 turns | Clean, focused, high-density context | **Mitigates context drift & forgetting** |
45
+ | **Config Updates** | Requires restart or reload | Instant hot-reload on file save | **Immediate feedback** |
46
+
47
+ ### 2. PTC Native Composite Batch Tooling (`compositeTools`)
48
+
49
+ - **`read_batch`**:
50
+ Concurrently inspects up to 10 targeted file snippets in a single turn. Ideal for broad multi-file investigation and dependency tracing.
51
+ - **`edit_batch`**:
52
+ Sequentially applies up to 10 targeted literal text replacements across single or multiple files in one round trip. Tolerates partial failures without losing preceding valid edits.
53
+ - **Inherited Security & Sandboxing**:
54
+ Every sub-action is dispatched through the official `ToolExecutionPipeline` (`tool/ptc-dispatch-start` / `tool/ptc-dispatch`), preserving file policy locks, mutation guards, and audit hooks.
55
+
56
+ ### 3. Defensive Runtime Policy & Self-Healing Recovery
57
+
58
+ - **No-Progress Circuit Breaker (`NO_PROGRESS`)**:
59
+ Computes deterministic tool invocation fingerprints. If an identical failing tool call repeats up to `noProgressLimit` (default `2`), the plugin blocks execution at `tools/pre-execute`, forcing the agent to adapt its diagnostic approach.
60
+ - **Windows Oversized Shell Command Interception (`EMBEDDED_SHELL_PAYLOAD_TOO_LARGE`)**:
61
+ Automatically blocks commands exceeding `4096` bytes or inline scripts (`node -e`, `python -c`, `pwsh -Command`) exceeding `512` bytes, steering the model to write deliverables to disk first.
62
+ - **Windows Chained Network Command Guard (`CHAINED_NETWORK_COMMAND`)**:
63
+ Intercepts compound shell commands that chain network/credential-bound operations (`npm publish`) with local operations during `tools/pre-execute`. Enforces clean two-tier execution: local operations chained via `&&` for zero-RTT speed, and network operations isolated standalone to eliminate Windows process handle hanging and 120s timeouts.
64
+ - **Playwright File Protocol Guard (`PLAYWRIGHT_FILE_PROTOCOL_BLOCKED`)**:
65
+ Pre-execution guard against `playwright-cli open/goto file://...` commands, steering models toward local HTTP loopback servers to prevent protocol errors and orphaned browser processes.
66
+ - **Full Overwrite Protection & Single-Shot Recovery (`failureRecovery`)**:
67
+ Prevents accidental destructive `write` overwrites on existing large files when `edit` is available. Automatically registers `retry_failed_write` when a large write (8KB–1MB) is rejected due to an unpaired justification, avoiding costly regeneration.
68
+
69
+ ### 4. Lightweight Convergence & Objective A/B Telemetry
70
+
71
+ - **Micro-Directive Convergence (`convergence`)**:
72
+ Appends soft guidance notices when steps approach budget intervals (default `stepInterval: 8`, max `4` per turn). Features **error-aware suppression**: automatically silences notices during debugging so trouble resolution remains uninterrupted.
73
+ - **Objective A/B Telemetry (`telemetry`)**:
74
+ Collects granular operational metrics including model requests, tool calls, composite parallelism ratio (`parallelismRatio`), time-to-first-token (TTFT), token consumption, and prefix cache stability (`prefixChanges`).
75
+
76
+ ---
77
+
78
+ ## Installation & Quickstart
79
+
80
+ ### 1. Via DSH Plugin Command (Recommended)
81
+
82
+ ```bash
83
+ # Add directly to the active web profile
84
+ dsh plugin --profile web add dsh-awesome-optimizer
85
+ ```
86
+
87
+ ### 2. Via npm / pnpm
88
+
89
+ ```bash
90
+ # Using npm
91
+ npm install dsh-awesome-optimizer
92
+
93
+ # Using pnpm
94
+ pnpm add dsh-awesome-optimizer
95
+ ```
96
+
97
+ ### 3. Zero-Config Out of the Box
98
+
99
+ All optimizations are enabled by default upon installation. **No extra lines are required in your global `cordis.patch.yml`**.
100
+
101
+ #### Optional Advanced Overrides / Disabling
102
+ Only when customizing paths or disabling specific subsystems do you need to add an entry in `cordis.patch.yml`:
103
+
104
+ ```yaml
105
+ # Example: Only declare overrides when customizing defaults
106
+ - id: agent-optimizer
107
+ config:
108
+ # Disable prompt takeover to revert to official verbose prompt
109
+ customPrompt:
110
+ enabled: false
111
+
112
+ # Or adjust batch limits
113
+ compositeTools:
114
+ maxBatchFiles: 15
115
+ maxBatchEdits: 15
116
+
117
+ # Or relax the no-progress circuit breaker
118
+ runtimePolicy:
119
+ noProgressLimit: 3
120
+ ```
121
+
122
+ ---
123
+
124
+ ## Production-Ready SYSTEM.md Recommendation
125
+
126
+ With `placement: "replace-all"`, place your directives in `~/.dsh/SYSTEM.md` (Windows: `C:\Users\<Username>\.dsh\SYSTEM.md`):
127
+
128
+ <details>
129
+ <summary>Click to expand production-ready universal prompt template (50 lines, native tools only)</summary>
130
+
131
+ ```markdown
132
+ # AUTONOMOUS AGENT CORE DIRECTIVE
133
+
134
+ You are a master autonomous software engineer powered by DeepSeek Harness.
135
+
136
+ - Prioritize direct action over speculation: investigate via concurrent tools (fs, bash, skills) without orchestration overhead.
137
+ - NEVER emit pre-action narration. Deliver surgical edits and high-signal conclusions.
138
+ - Irreversible operations (npm publish): STRICTLY conservative and non-autonomous. NEVER bump versions or mutate artifacts to bypass failures; registry validation causes transient 404 or stale views—NEVER treat as failure or retry publish. MUST verify remote state with read-only commands before declaring status.
139
+
140
+ ## Defaults
141
+
142
+ - Reply in Chinese; code comments and commit messages in English unless requested otherwise. In user-facing text, preserve Windows path formats as written (`E:\...`).
143
+ - Answer / explain / review / diagnose / plan: inspect and report without edits unless requested otherwise.
144
+ - Change / build / fix: make the smallest in-scope edits necessary for the requested task; task authorization includes necessary edits to related files. Keep changes conservative and reversible. Preserve unrelated user work. Do not reset or clean the working tree unless explicitly requested. Do not perform unrelated cleanup, reformatting, dependency changes, or test rewrites. Task-created temporary artifacts may be removed after use. New tests ONLY via Verification.
145
+ - Ask first (via `ask_user_question`) ONLY when ambiguity materially affects scope, architecture, or data safety; otherwise execute autonomously.
146
+ - Shell: ONLY `bash`. Launch `pwsh.exe` from `bash` when needed.
147
+ - Web: Research/fetch STRICTLY via skills (`agent-reach`, `gh`, `opencli-*`, `smart-search`) or bash CLIs.
148
+ - Tool boundaries: External tools (playwright-cli, gh, ast-grep) are standalone CLIs via bash, NEVER require/import as node modules.
149
+ - Intermediate artifacts: Write ad-hoc Node/Python scripts to temporary files or clean them up; NEVER clutter the workspace with disposable test pages.
150
+
151
+ ## Efficiency
152
+
153
+ ### Hard Constraints
154
+
155
+ - Retry ONLY when the error or new evidence supports a specific correction; after two failures without progress, switch diagnostic approaches.
156
+ - Windows arguments & paths: use forward slashes in paths to prevent escape corruption. Pass complex/multiline payloads (`node -e`, `python -c`, `playwright-cli eval`, `gh`) via files or stdin, NEVER raw shell arguments; quote single-line patterns carefully (`ast-grep` patterns STRICTLY in single quotes `'...'` to prevent `$$` expansion). On quoting failures, switch input method rather than re-escaping.
157
+ - Byte-fidelity: default new text files to UTF-8. Preserve existing file encodings, BOMs, line endings, `.gitattributes`, and hook policies unless explicitly requested.
158
+ - Policy denials (`file access denied`, network blocked, approval disabled/rejected) are not command bugs: report; do not bypass. Request wider access via `sandbox_permissions` ONLY when escalation is explicitly available; otherwise do not retry or escalate. Diagnose ordinary lock, permission, or connectivity errors normally.
159
+ - Tool exclusivity: STRICTLY native `glob`/`grep`/`read_batch`/`read`/`edit_batch`/`edit`/`write`. NEVER use shell commands or redirects for workspace search or file ops (`grep`, `rg`, `find`, `ls`, `dir`, `cat`, `type`, `head`, `tail`, `sed`, `awk`, `tee`, `>`/`>>`). Filtering piped command output (`cmd | grep`) is fine.
160
+
161
+ ### Execution & Context Efficiency
162
+
163
+ - Workflow:
164
+ - Complexity: simple → execute; high-scope (cross-module, API, schema) → generate / follow plan (`<name>.md`); define 1–3 sentence scope and exit criteria before edits.
165
+ - Scheduling: MUST use `read_batch` for multi-file inspection (2+ files); keep single-file reads, retries, and dependent checks sequential.
166
+ - Diagnosis: inspect contiguous context in one pass; cite locators and minimal raw excerpts only as evidence.
167
+ - Search & navigation:
168
+ - Scope & environment: verify via `git rev-parse --is-inside-work-tree` when workspace boundary is ambiguous (do not probe `.git`). Probe binary availability via `which`/`command -v` ONLY when execution fails; NEVER run speculative probing (`node -v`, `node -e`, `playwright-cli --version`) on startup—host facts are already hydrated.
169
+ - Runtime context: `pwd`/runtime cwd defines the workspace; the DSH implementation checkout is ONLY for inspecting/extending DSH—NEVER infer cwd from it or edit it unless explicitly requested.
170
+ - Code intelligence: prioritize `lsp` CLI (`lsp def`, `lsp ref`, `lsp hover`); outline via `lsp symbols <file>` or `ast-grep outline` before reading large files; `ast-grep` for structural queries (`-p`, `-k`; `ast-grep run` exit 1 means 0 matches, not error; `scan` exits 0 either way).
171
+ - Files & text: native `glob`/`grep` (gitignore-aware by default; pass `gitignore: false` for ignored paths); broad matches → narrow `path`/glob or page via `skip`, NEVER truncate blindly. Use `git` via `bash` ONLY for git-specific facts (tracked status, history, diffs).
172
+ - Modification & execution:
173
+ - File ops: produce deliverables directly; MUST use `edit_batch` for 2+ edits (whether in one file or across multiple files); use `edit` for a single edit, and `write` for new files or ad-hoc Node/Python scripts.
174
+ - Staged refactor: preview, then apply — symbol renames via `lsp rename` (dry-run → `--apply`); structural rewrites via `ast-grep run -p ... -r ...` (then `-U`).
175
+ - Structured data: process STRICTLY via ad-hoc Node/Python scripts passed via stdin or temp files; NEVER dump raw data into context.
176
+ - Shell execution: prioritize chaining local non-blocking operations via `&&` (`git add ... && git commit ... && npm test`) to eliminate round-trip latency; keep network- or credential-bound commands (`npm publish`, remote fetch) separate to prevent Windows process handle hanging and timeouts.
177
+ - Reporting: diffs and evidence first; zero filler. Routine status ≤ 300 Chinese characters. Answer/explain/review/diagnose/plan: no length cap. Compact locators, lists, and deltas only.
178
+
179
+ ## Verification
180
+
181
+ Applies ONLY to change/build/fix.
182
+
183
+ - NEVER falsify tests (weaken assertions, stub a failing path, or skip a check to pass).
184
+ - Choose checks by the highest affected behavioral or contract risk. Prioritize existing relevant checks; add a targeted test when changed behavior lacks coverage. Do not repeat equivalent checks unless code, configuration, environment, or relevant evidence changes:
185
+ - Text or mechanical changes without behavioral or contract effects: inspect the diff and relevant syntax/format; skip unrelated linters.
186
+ - Behavior changes: check static diagnostics via primary tools (e.g. `lsp diag <file|dir> -e`, skip if language unsupported; no redundant CLI linters), then run the smallest non-destructive targeted build/test covering affected behavior and internal interfaces.
187
+ - Shared API, schema, or migration changes: run the full related suite plus project-wide type checking where applicable (e.g. `tsc --noEmit`).
188
+ - Report checks, results, and verification gaps; if primary diagnostics are unavailable, use an existing equivalent check when possible.
189
+ - Browser checks: STRICTLY `playwright-cli` post-write. Playwright CLI blocks 'file:' URLs—serve static HTML via loopback HTTP (http://127.0.0.1:<port>). NEVER pre-probe (`node -v`, `playwright-cli --version`), create dummy pages, or switch tools. Reuse runtime Web GUI or active app URL (loopback for static); stabilize animations before capture. Batch-cleanup sessions/servers/artifacts without redundant listings. On failure, report root cause.
190
+ - Persistent failure: report failed command(s), 1–2 sentence root cause, blast radius, next steps.
191
+ ```
192
+ </details>
193
+
194
+ ---
195
+
196
+ ## Verification & Benchmarking
197
+
198
+ ```bash
199
+ # Link local peer dependencies from installed DSH host (zero network requests)
200
+ npm run setup:local
201
+
202
+ # Run integration tests against official @deepseek-ai/dsh-agent-loop
203
+ npm test
204
+
205
+ # Run strict TypeScript declaration check
206
+ npm run typecheck
207
+
208
+ # Run offline A/B benchmark verification
209
+ npm run benchmark
210
+ ```
211
+
212
+ ---
213
+
214
+ ## Architectural Principles & Safety
215
+
216
+ 1. **Official Loop Ownership (`@deepseek-ai/dsh-agent-loop`)**:
217
+ Turn state machines, native parallel scheduling (`maxParallelToolCalls`), retries, and cancellation semantics remain fully owned by the official loop. This plugin purely mounts additively via Cordis and **never replaces or tampers with** `@deepseek-ai/dsh-agent-loop`.
218
+ 2. **Zero Model Parameter Mutation**:
219
+ The plugin never hooks `agent/request` to modify model identities, providers, or reasoning efforts.
220
+ 3. **Transparent Pipeline Security**:
221
+ All composite operations are audited and dispatched individually through the official ToolExecutionPipeline.
222
+
223
+ ---
224
+
225
+ ## License
226
+
227
+ [MIT](LICENSE) © [Jaylor-Wang](https://github.com/Jaylor-Wang)
package/README.zh.md ADDED
@@ -0,0 +1,227 @@
1
+ # dsh-awesome-optimizer
2
+
3
+ [English](README.md) | 中文
4
+
5
+ [![npm version](https://img.shields.io/npm/v/dsh-awesome-optimizer.svg?color=blue)](https://www.npmjs.com/package/dsh-awesome-optimizer)
6
+ [![license](https://img.shields.io/github/license/Jaylor-Wang/dsh-awesome-optimizer.svg)](LICENSE)
7
+ [![GitHub release](https://img.shields.io/github/v/release/Jaylor-Wang/dsh-awesome-optimizer.svg)](https://github.com/Jaylor-Wang/dsh-awesome-optimizer/releases)
8
+ [![Tests](https://img.shields.io/badge/tests-21%20passed-brightgreen.svg)](test/)
9
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Strict%20Types-blue.svg)](src/)
10
+
11
+ 围绕官方 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`@deepseek-ai/dsh-agent-loop`) 打造的高性能运行时策略防护、PTC 复合批处理工具、全新独立系统提示词接管与客观 A/B 轮次度量插件。
12
+
13
+ ---
14
+
15
+ ## v1.7.0 版本重要更新
16
+
17
+ - **宿主环境事实注水全面加固与弱语气词拔除**:环境事实注水段落全面升级为 RFC 2119 绝对强约束,将模块与脚本边界严格收敛为 `NEVER require/import as node modules`,彻底封死 CommonJS 与 ESM 两种导入路径;将开局探测禁令拔除 `Avoid` 弱语气词并收敛为铁律 `NEVER run exploratory probing (pwd, ls, node -v, which)`。
18
+ - **Python 跨平台环境智能识别与单例缓存 (`detectPythonEnv`)**:在环境事实注水时自动探测当前系统 Python 可用性(`python` / `python3` 及版本号),抹平跨平台命令分歧;采用单例懒加载缓存与超时守卫,零首字延迟开销;未装配时自动引导模型纯粹使用 Node.js,杜绝盲目生成 `.py` 脚本导致的执行失败。
19
+ - **Playwright `file:` 协议前置硬拦截 (`PLAYWRIGHT_FILE_PROTOCOL_BLOCKED`)**:在 `tools/pre-execute` 阶段主动检测并拦截 `playwright-cli open/goto file://...`,杜绝协议阻断异常与浏览器僵尸子进程,引导模型无缝切换至本地 HTTP 环回服务。
20
+ - **轻量宿主环境事实注水 (`injectEnvironmentFacts`)**:系统提示词组装阶段自动注入 Node.js 版本、系统架构、独立 CLI 工具边界与 Playwright 协议指引,彻底消除模型开局盲目执行探针命令。
21
+ - **CLI 独立工具与 NPM 模块边界防混淆**:在 Prompt Linter 中新增 `cli-require-confusion` 静态规则,静态拦截将外部 CLI 工具当成 Node 模块导入的认知混淆错误。
22
+ - **复合批处理工具语义精准化与规范收敛**:`read_batch` 与 `edit_batch` 全面加固为 `MUST` 硬约束,精准规范单/多文件介词与数量阈值;精炼 Windows 参数与路径指令,去除冗余科普并强化 `NEVER raw shell arguments` 边界。
23
+
24
+ ---
25
+
26
+ ## 核心特性与架构设计
27
+
28
+ ### 1. 系统提示词精简与文件驱动热重载 (`customPrompt`)
29
+
30
+ - **独立接管模式 (`placement: "replace-all"`)**:
31
+ 在 DSH 官方 `system-prompt/assemble` 组装瀑布流中,精确剥除官方 verbose 冗余章节(包括 `harness:*`、`deployment:*`、`tool:*`、`deliverable:*`、`web:*` 等),并保留会话收敛指导等协同章节,将系统提示词基线精简至约 380 tokens 的轻量核心指令。
32
+ - **双层 Markdown 规约**:
33
+ 自动寻找全局配置 `~/.dsh/SYSTEM.md`(或 `$DSH_HOME/SYSTEM.md`)与项目级工作区配置 `.dsh/SYSTEM.md`(或 `SYSTEM.md`)。权责清晰,与面向角色的 `AGENTS.md` 解耦。
34
+ - **毫秒级防抖热重载(Hot-Reload)**:
35
+ 基于 `fs.watch` 深度监视提示词文件变更,修改保存后下一轮交互即刻生效,无需重启 DSH 守护进程。
36
+ - **级联策略灵活可选**:
37
+ 支持 `concat`(全局与工作区级联合并,默认)与 `workspace-override`(项目级完全覆盖全局)。
38
+ - **内置 Prompt Linter 健康度校验与一键修复**:
39
+ 提供 `lintPrompt` / `fixPrompt` / `lintPromptFile` API。**基于用户当前预设加载的插件工具做动态客观判定**,杜绝主观臆断:当工具未在预设加载时提示冗余防守,当工具已加载却声明禁用时提示配置冲突,并校验弱语气词(如 `bias toward` 自动升级为 `Prioritize`)、RFC 2119 强约束大写规范及未闭合反引号,输出健康度打分(0-100)并支持一键无损修复。
40
+
41
+ | 指标维度 | 官方默认 System Prompt | 开启本插件优化后 | 收益 |
42
+ | :--- | :--- | :--- | :--- |
43
+ | **提示词上下文开销** | ~2,000 tokens / 轮 | **~380 tokens / 轮(推荐模板)** | **大幅释放有效上下文,杜绝冗余规则消耗** |
44
+ | **长轮次会话累积** | 50 轮累计消耗 ~100K 冗余上下文 | 上下文干净紧凑,核心指令专注 | **显著缓解上下文漂移与遗忘** |
45
+ | **配置修改生效** | 需重启服务或重载配置文件 | 文件修改保存即刻热生效 | **即写即调,毫秒级响应** |
46
+
47
+ ### 2. PTC 原生复合批处理工具 (`compositeTools`)
48
+
49
+ - **`read_batch`**:
50
+ 支持单次并发读取最多 10 个指定文件的文本片段。大幅加速多模块依赖排查、跨文件上下文搜集任务。
51
+ - **`edit_batch`**:
52
+ 支持单次顺序执行最多 10 处跨单个或多个文件的字面量精准文本替换。容忍局部错误而不影响同批次其他成功编辑,彻底避免多轮串行 `edit` 带来的网络空转。
53
+ - **原生沙箱与安全事务继承**:
54
+ 所有子操作均通过官方 `ToolExecutionPipeline` (`tool/ptc-dispatch-start` / `tool/ptc-dispatch`) 分发,完整保留 DSH 沙箱权限判定、文件变更审核与观察策略钩子。
55
+
56
+ ### 3. 运行期硬防护与失败自愈机制
57
+
58
+ - **连续无进展失败熔断 (`NO_PROGRESS`)**:
59
+ 基于输入参数指纹计算,当同一工具以相同参数连续失败达到 `noProgressLimit`(默认 `2` 次)时,在 `tools/pre-execute` 阶段立即硬拦截并强迫模型转换诊断思路,杜绝死循环。
60
+ - **Windows 超大 Shell 载荷拦截 (`EMBEDDED_SHELL_PAYLOAD_TOO_LARGE`)**:
61
+ 自动拦截超过 `4096` 字节的 `bash` 命令,或超过 `512` 字节的内联脚本参数(`node -e`、`python -c`、`pwsh -Command` 等),引导模型先通过原生 `write` 落盘再执行,规避 Windows 命令行参数溢出崩溃。
62
+ - **Windows 复合网络命令挂起防御 (`CHAINED_NETWORK_COMMAND`)**:
63
+ 在 `tools/pre-execute` 阶段自动拦截将网络/凭据操作(`npm publish` 等)与本地耗时操作混合串联的复合命令,强行引导模型执行两分法:本地确定性操作(`git add ... && git commit ... && npm test`)复合提速,网络发布独立把关,彻底规避 Windows 子进程句柄悬挂与 120s 超时。
64
+ - **Playwright 文件协议前置拦截 (`PLAYWRIGHT_FILE_PROTOCOL_BLOCKED`)**:
65
+ 在 `tools/pre-execute` 阶段主动检测并拦截 `playwright-cli open/goto file://...` 调用,立即引导模型使用本地 HTTP 环回服务访问,防止浏览器僵尸子进程残留与协议阻断异常。
66
+ - **大文件覆写防御与快速重放恢复 (`failureRecovery`)**:
67
+ 保护已存在的大文件不被全量 `write` 误覆盖;针对大文件写入(8KB–1MB)因缺失配对 `justification` 被拒的场景,提供 `retry_failed_write` 快捷工具,由宿主从缓存直接重放,避免大模型重新生成数千行代码。
68
+
69
+ ### 4. 轻量软收敛提示与客观 A/B 度量
70
+
71
+ - **轻量微指令收敛 (`convergence`)**:
72
+ 在步数达到阈值后追加精简的 `notice` 收敛引导(默认 `stepInterval: 8`,每轮上限 `4` 次),且内置**错误感知避让**:模型上一步工具调用报错时自动静默,优先保证排错连贯性。
73
+ - **客观 A/B 效果度量 (`telemetry`)**:
74
+ 内置细粒度性能度量,实时追踪模型请求数、工具调用数、批处理并发比率(`parallelismRatio`)、首字延迟(TTFT)、Token 消耗与前缀稳定性(`prefixChanges`),支持基线差值对比。
75
+
76
+ ---
77
+
78
+ ## 安装与快速上手
79
+
80
+ ### 1. 通过 DSH 插件命令安装(推荐)
81
+
82
+ ```bash
83
+ # 直接安装至当前激活的 web profile
84
+ dsh plugin --profile web add dsh-awesome-optimizer
85
+ ```
86
+
87
+ ### 2. 通过 npm / pnpm 安装
88
+
89
+ ```bash
90
+ # 使用 npm
91
+ npm install dsh-awesome-optimizer
92
+
93
+ # 使用 pnpm
94
+ pnpm add dsh-awesome-optimizer
95
+ ```
96
+
97
+ ### 3. 零配置开箱即用
98
+
99
+ 本插件在安装后**开箱即用,默认最佳实践已全量激活**。用户的全局 `cordis.patch.yml` **无需添加任何多余配置行**。
100
+
101
+ #### 高级定制 / 仅维护禁用配置(可选)
102
+ 仅在需要覆盖默认路径或禁用某项能力时,才需在 `cordis.patch.yml` 中声明:
103
+
104
+ ```yaml
105
+ # 示例:仅在需要覆盖或局部禁用时编写
106
+ - id: agent-optimizer
107
+ config:
108
+ # 局部停用系统提示词接管(改用官方默认)
109
+ customPrompt:
110
+ enabled: false
111
+
112
+ # 或微调批处理大小
113
+ compositeTools:
114
+ maxBatchFiles: 15
115
+ maxBatchEdits: 15
116
+
117
+ # 或放宽无进展熔断阈值
118
+ runtimePolicy:
119
+ noProgressLimit: 3
120
+ ```
121
+
122
+ ---
123
+
124
+ ## 生产级 SYSTEM.md 最佳实践
125
+
126
+ 配合 `placement: "replace-all"` 模式,推荐在全局目录创建 `~/.dsh/SYSTEM.md`(Windows 下为 `C:\Users\<用户名>\.dsh\SYSTEM.md`):
127
+
128
+ <details>
129
+ <summary>点击展开查看开箱即用通用提示词模板(50 行,纯原生工具无外部依赖)</summary>
130
+
131
+ ```markdown
132
+ # AUTONOMOUS AGENT CORE DIRECTIVE
133
+
134
+ You are a master autonomous software engineer powered by DeepSeek Harness.
135
+
136
+ - Prioritize direct action over speculation: investigate via concurrent tools (fs, bash, skills) without orchestration overhead.
137
+ - NEVER emit pre-action narration. Deliver surgical edits and high-signal conclusions.
138
+ - Irreversible operations (npm publish): STRICTLY conservative and non-autonomous. NEVER bump versions or mutate artifacts to bypass failures; registry validation causes transient 404 or stale views—NEVER treat as failure or retry publish. MUST verify remote state with read-only commands before declaring status.
139
+
140
+ ## Defaults
141
+
142
+ - Reply in Chinese; code comments and commit messages in English unless requested otherwise. In user-facing text, preserve Windows path formats as written (`E:\...`).
143
+ - Answer / explain / review / diagnose / plan: inspect and report without edits unless requested otherwise.
144
+ - Change / build / fix: make the smallest in-scope edits necessary for the requested task; task authorization includes necessary edits to related files. Keep changes conservative and reversible. Preserve unrelated user work. Do not reset or clean the working tree unless explicitly requested. Do not perform unrelated cleanup, reformatting, dependency changes, or test rewrites. Task-created temporary artifacts may be removed after use. New tests ONLY via Verification.
145
+ - Ask first (via `ask_user_question`) ONLY when ambiguity materially affects scope, architecture, or data safety; otherwise execute autonomously.
146
+ - Shell: ONLY `bash`. Launch `pwsh.exe` from `bash` when needed.
147
+ - Web: Research/fetch STRICTLY via skills (`agent-reach`, `gh`, `opencli-*`, `smart-search`) or bash CLIs.
148
+ - Tool boundaries: External tools (playwright-cli, gh, ast-grep) are standalone CLIs via bash, NEVER require/import as node modules.
149
+ - Intermediate artifacts: Write ad-hoc Node/Python scripts to temporary files or clean them up; NEVER clutter the workspace with disposable test pages.
150
+
151
+ ## Efficiency
152
+
153
+ ### Hard Constraints
154
+
155
+ - Retry ONLY when the error or new evidence supports a specific correction; after two failures without progress, switch diagnostic approaches.
156
+ - Windows arguments & paths: use forward slashes in paths to prevent escape corruption. Pass complex/multiline payloads (`node -e`, `python -c`, `playwright-cli eval`, `gh`) via files or stdin, NEVER raw shell arguments; quote single-line patterns carefully (`ast-grep` patterns STRICTLY in single quotes `'...'` to prevent `$$` expansion). On quoting failures, switch input method rather than re-escaping.
157
+ - Byte-fidelity: default new text files to UTF-8. Preserve existing file encodings, BOMs, line endings, `.gitattributes`, and hook policies unless explicitly requested.
158
+ - Policy denials (`file access denied`, network blocked, approval disabled/rejected) are not command bugs: report; do not bypass. Request wider access via `sandbox_permissions` ONLY when escalation is explicitly available; otherwise do not retry or escalate. Diagnose ordinary lock, permission, or connectivity errors normally.
159
+ - Tool exclusivity: STRICTLY native `glob`/`grep`/`read_batch`/`read`/`edit_batch`/`edit`/`write`. NEVER use shell commands or redirects for workspace search or file ops (`grep`, `rg`, `find`, `ls`, `dir`, `cat`, `type`, `head`, `tail`, `sed`, `awk`, `tee`, `>`/`>>`). Filtering piped command output (`cmd | grep`) is fine.
160
+
161
+ ### Execution & Context Efficiency
162
+
163
+ - Workflow:
164
+ - Complexity: simple → execute; high-scope (cross-module, API, schema) → generate / follow plan (`<name>.md`); define 1–3 sentence scope and exit criteria before edits.
165
+ - Scheduling: MUST use `read_batch` for multi-file inspection (2+ files); keep single-file reads, retries, and dependent checks sequential.
166
+ - Diagnosis: inspect contiguous context in one pass; cite locators and minimal raw excerpts only as evidence.
167
+ - Search & navigation:
168
+ - Scope & environment: verify via `git rev-parse --is-inside-work-tree` when workspace boundary is ambiguous (do not probe `.git`). Probe binary availability via `which`/`command -v` ONLY when execution fails; NEVER run speculative probing (`node -v`, `node -e`, `playwright-cli --version`) on startup—host facts are already hydrated.
169
+ - Runtime context: `pwd`/runtime cwd defines the workspace; the DSH implementation checkout is ONLY for inspecting/extending DSH—NEVER infer cwd from it or edit it unless explicitly requested.
170
+ - Code intelligence: prioritize `lsp` CLI (`lsp def`, `lsp ref`, `lsp hover`); outline via `lsp symbols <file>` or `ast-grep outline` before reading large files; `ast-grep` for structural queries (`-p`, `-k`; `ast-grep run` exit 1 means 0 matches, not error; `scan` exits 0 either way).
171
+ - Files & text: native `glob`/`grep` (gitignore-aware by default; pass `gitignore: false` for ignored paths); broad matches → narrow `path`/glob or page via `skip`, NEVER truncate blindly. Use `git` via `bash` ONLY for git-specific facts (tracked status, history, diffs).
172
+ - Modification & execution:
173
+ - File ops: produce deliverables directly; MUST use `edit_batch` for 2+ edits (whether in one file or across multiple files); use `edit` for a single edit, and `write` for new files or ad-hoc Node/Python scripts.
174
+ - Staged refactor: preview, then apply — symbol renames via `lsp rename` (dry-run → `--apply`); structural rewrites via `ast-grep run -p ... -r ...` (then `-U`).
175
+ - Structured data: process STRICTLY via ad-hoc Node/Python scripts passed via stdin or temp files; NEVER dump raw data into context.
176
+ - Shell execution: prioritize chaining local non-blocking operations via `&&` (`git add ... && git commit ... && npm test`) to eliminate round-trip latency; keep network- or credential-bound commands (`npm publish`, remote fetch) separate to prevent Windows process handle hanging and timeouts.
177
+ - Reporting: diffs and evidence first; zero filler. Routine status ≤ 300 Chinese characters. Answer/explain/review/diagnose/plan: no length cap. Compact locators, lists, and deltas only.
178
+
179
+ ## Verification
180
+
181
+ Applies ONLY to change/build/fix.
182
+
183
+ - NEVER falsify tests (weaken assertions, stub a failing path, or skip a check to pass).
184
+ - Choose checks by the highest affected behavioral or contract risk. Prioritize existing relevant checks; add a targeted test when changed behavior lacks coverage. Do not repeat equivalent checks unless code, configuration, environment, or relevant evidence changes:
185
+ - Text or mechanical changes without behavioral or contract effects: inspect the diff and relevant syntax/format; skip unrelated linters.
186
+ - Behavior changes: check static diagnostics via primary tools (e.g. `lsp diag <file|dir> -e`, skip if language unsupported; no redundant CLI linters), then run the smallest non-destructive targeted build/test covering affected behavior and internal interfaces.
187
+ - Shared API, schema, or migration changes: run the full related suite plus project-wide type checking where applicable (e.g. `tsc --noEmit`).
188
+ - Report checks, results, and verification gaps; if primary diagnostics are unavailable, use an existing equivalent check when possible.
189
+ - Browser checks: STRICTLY `playwright-cli` post-write. Playwright CLI blocks 'file:' URLs—serve static HTML via loopback HTTP (http://127.0.0.1:<port>). NEVER pre-probe (`node -v`, `playwright-cli --version`), create dummy pages, or switch tools. Reuse runtime Web GUI or active app URL (loopback for static); stabilize animations before capture. Batch-cleanup sessions/servers/artifacts without redundant listings. On failure, report root cause.
190
+ - Persistent failure: report failed command(s), 1–2 sentence root cause, blast radius, next steps.
191
+ ```
192
+ </details>
193
+
194
+ ---
195
+
196
+ ## 本地验证与基准测试
197
+
198
+ ```bash
199
+ # 从本地已安装的 DSH 宿主链接依赖(零网络请求)
200
+ npm run setup:local
201
+
202
+ # 在官方 @deepseek-ai/dsh-agent-loop 上运行完整集成测试
203
+ npm test
204
+
205
+ # 运行 TypeScript 严格类型检查
206
+ npm run typecheck
207
+
208
+ # 运行离线 A/B 机制与度量对照脚本
209
+ npm run benchmark
210
+ ```
211
+
212
+ ---
213
+
214
+ ## 设计边界与安全保障
215
+
216
+ 1. **官方 Loop 独占控制流 (`@deepseek-ai/dsh-agent-loop`)**:
217
+ 生命周期、工具原生并发调度(`maxParallelToolCalls`)、重试、取消与结束语义全部由官方 Loop 负责。本插件通过 Cordis 机制注入,**绝不禁用、替换或篡改** `@deepseek-ai/dsh-agent-loop`。
218
+ 2. **零模型参数篡改**:
219
+ 本插件绝不在 `agent/request` 钩子中擅自降低或修改模型名称、Provider 或推理强度(`reasoningEffort`)。
220
+ 3. **事务性与沙箱透明度**:
221
+ 复合工具执行的所有原子子操作均在官方执行管线中逐一审计与授权,绝不绕过安全边界。
222
+
223
+ ---
224
+
225
+ ## 许可证
226
+
227
+ [MIT](LICENSE) © [Jaylor-Wang](https://github.com/Jaylor-Wang)
@@ -0,0 +1,42 @@
1
+ # Purely additive policy, composite-tool, and telemetry plugin.
2
+ # Never disables or replaces @deepseek-ai/dsh-agent-loop.
3
+ - insert:
4
+ - id: agent-optimizer
5
+ name: dsh-awesome-optimizer
6
+ config:
7
+ enabled: true
8
+ runtimePolicy:
9
+ mode: enforce
10
+ noProgressLimit: 2
11
+ recoveryAttemptLimit: 1
12
+ minLargeWriteBytes: 8192
13
+ maxShellCommandBytes: 4096
14
+ maxInlineScriptBytes: 512
15
+ fileMutationPolicy:
16
+ mode: observe
17
+ minLargeWriteBytes: 8192
18
+ recoverFailedWrites: true
19
+ compositeTools:
20
+ enabled: true
21
+ readBatch: true
22
+ editBatch: true
23
+ maxBatchFiles: 10
24
+ maxBatchEdits: 10
25
+ convergence:
26
+ enabled: true
27
+ injectGuidance: true
28
+ stepInterval: 8
29
+ maxRemindersPerTurn: 4
30
+ customPrompt:
31
+ enabled: true
32
+ globalFile: "~/.dsh/SYSTEM.md"
33
+ workspaceFile: ".dsh/SYSTEM.md"
34
+ # Placement modes:
35
+ # - "replace-all": Strip ALL verbose official sections and use ONLY the refined SYSTEM.md
36
+ # - "suffix": Append to end of official system prompt (Order 10300)
37
+ placement: "replace-all"
38
+ mergeStrategy: "concat"
39
+ hotReload: true
40
+ telemetry:
41
+ enabled: true
42
+ trackStreams: true
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Agent Loop Policy & Convergence Optimizer",
4
+ "description": "Non-invasive runtime guards, PTC composite batch tools, soft convergence reminders, and A/B turn telemetry around the official DSH agent loop."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Agent 循环策略与收敛优化器",
4
+ "description": "围绕官方 DSH Agent Loop 的运行时策略防护、PTC 复合批处理工具、轻量软预算提醒与 A/B 轮次度量插件。"
5
+ }
6
+ }