dsh-awesome-optimizer 1.5.0 → 1.8.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/README.md CHANGED
@@ -5,19 +5,22 @@ English | [中文](README.zh.md)
5
5
  [![npm version](https://img.shields.io/npm/v/dsh-awesome-optimizer.svg?color=blue)](https://www.npmjs.com/package/dsh-awesome-optimizer)
6
6
  [![license](https://img.shields.io/github/license/Jaylor-Wang/dsh-awesome-optimizer.svg)](LICENSE)
7
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/)
8
+ [![Tests](https://img.shields.io/badge/tests-31%20passed-brightgreen.svg)](test/)
9
9
  [![TypeScript](https://img.shields.io/badge/TypeScript-Strict%20Types-blue.svg)](src/)
10
10
 
11
- High-performance, non-invasive runtime policy, PTC-backed composite batch tooling, standalone refined system prompt engine (~80% token savings), and objective A/B turn telemetry plugin for the official [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`@deepseek-ai/dsh-agent-loop`).
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
12
 
13
13
  ---
14
14
 
15
- ## Highlights in v1.5.0
15
+ ## Highlights in v1.8.0
16
16
 
17
- - **RFC 2119 Restrictive Modal Capitalization & Salience**: Convergence reminders enforce `NEVER omit verification.` to block premature completion under step pressure. Restrictive boundaries (`ONLY`, `NEVER`, `STRICTLY`) are capitalized consistently across guidance, templates, and runtime intercept reasons.
18
- - **Precision Tool Alignment with Official DSH Contracts**: `edit_batch` schema and parameter descriptions strictly mirror official `edit` tool semantics (`Provide file_path before old_string and new_string in the arguments`). Decoupled verbs (`produce deliverables`) prevent homonym collisions with native tools.
19
- - **Refined Command Chaining Policy**: Relaxed `CHAINED_NETWORK_COMMAND` to safely permit chained non-blocking local commands like `git push` while strictly preventing Windows hanging on credentials and publish (`npm publish`).
20
- - **Standalone `SYSTEM.md` Engine & ~80% Token Reduction (`placement: "replace-all"`)**: Completely prunes verbose official prompt sections, allowing a concise, standalone `~/.dsh/SYSTEM.md` (~380 tokens) to govern as the single authority. Saves ~1.6K tokens per turn.
17
+ - **Host Requirement Relaxation (`未声明宿主要求`)**: Removed `engines.dsh` constraint and migrated all `@deepseek-ai/*` peer dependencies to `devDependencies` (aligned with `dsh-tool-antigravity`), eliminating artificial version intersection tags (`DSH >=0.2.2-rc.1 ∩ *`) in DSH / Cordis plugin marketplace and enabling seamless installation across any DSH runtime.
18
+ - **Windows IPC Deadlock Elimination in Test Runner**: Reconfigured test script with `--test-concurrency=1 --test-timeout=10000`, switching `node:test` runner from parallel multi-worker fork races to deterministic linear single-channel execution, completely eliminating Windows stdio buffer lockups and EOF hang risks.
19
+ - **Heavy Task Chain Isolation Policy (`CHAINED_HEAVY_COMMAND`)**: Proactively intercepts heavy execution and publishing commands (`npm test`, `npm run build`, `vitest`, `npm publish`) in compound shell chains (`&&`, `;`) to prevent Windows console pipe deadlocks, while allowing seamless Git pipeline chaining (`git add ... && git commit ... && git push`).
20
+ - **Normative Ad-Hoc Script Disk Writing Enforcement**: Elevated ad-hoc script and IK/mathematical calculation guidelines to strict RFC 2119 `MUST` (`MUST write ad-hoc Node/Python scripts to disk via native write first`), eliminating friction with inline `python -c` or `node -e` shell payload overflow.
21
+ - **Playwright CLI Contract & Parameter Hardening**: Hardened selector target semantics (`screenshot takes selector target ONLY; auto-saved without output filename`), coupled with absolute bans on exploratory `--help` / `--version` probing.
22
+ - **Prompt Signal-to-Noise Refinement**: Pruned conflicting `produce deliverables directly` clauses, streamlined `Windows arguments & paths` to focus 100% on quoting/escaping, and eliminated redundant artifact cleanup instructions.
23
+ - **Ecosystem Description & Marketplace Alignment**: Harmonized GitHub About and documentation with official DSH marketplace card semantics, featuring standardized `SYSTEM.md replacement mode`.
21
24
 
22
25
  ---
23
26
 
@@ -26,7 +29,7 @@ High-performance, non-invasive runtime policy, PTC-backed composite batch toolin
26
29
  ### 1. Refined System Prompt & File-Driven Hot-Reload (`customPrompt`)
27
30
 
28
31
  - **Standalone Mode (`placement: "replace-all"`)**:
29
- 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 (~82% reduction from ~2,000 to ~380 tokens).
32
+ 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.
30
33
  - **Dual-Layer Markdown Convention**:
31
34
  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.
32
35
  - **Millisecond Hot-Reload**:
@@ -34,11 +37,11 @@ High-performance, non-invasive runtime policy, PTC-backed composite batch toolin
34
37
  - **Flexible Cascading Strategies**:
35
38
  Supports `concat` (cascading global and workspace prompts, default) and `workspace-override` (repo prompt completely replaces global prompt).
36
39
  - **Built-in Prompt Linter & Auto-Fixer**:
37
- 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
+ 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 (e.g. upgrading soft wording to direct imperatives), unclosed backticks, and enforces RFC 2119 uppercase constraints with actionable health scoring (0-100).
38
41
 
39
42
  | Dimension | Official Default System Prompt | Optimized with This Plugin | Savings |
40
43
  | :--- | :--- | :--- | :--- |
41
- | **Token Usage** | ~2,000 tokens / turn | **~380 tokens / turn** | **~82% token reduction** |
44
+ | **Prompt Context Footprint** | ~2,000 tokens / turn | **~380 tokens / turn (Template)** | **Frees context headroom; eliminates redundant rules** |
42
45
  | **Long Multi-Turn Sessions** | ~100K redundant tokens across 50 turns | Clean, focused, high-density context | **Mitigates context drift & forgetting** |
43
46
  | **Config Updates** | Requires restart or reload | Instant hot-reload on file save | **Immediate feedback** |
44
47
 
@@ -57,8 +60,10 @@ High-performance, non-invasive runtime policy, PTC-backed composite batch toolin
57
60
  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.
58
61
  - **Windows Oversized Shell Command Interception (`EMBEDDED_SHELL_PAYLOAD_TOO_LARGE`)**:
59
62
  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.
60
- - **Windows Chained Network Command Guard (`CHAINED_NETWORK_COMMAND`)**:
61
- 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.
63
+ - **Windows Chained Heavy Task Guard (`CHAINED_HEAVY_COMMAND`)**:
64
+ Intercepts compound shell commands that chain heavy concurrent or publishing tasks (`npm test`, `npm run build`, `vitest`, `npm publish`) with other operations during `tools/pre-execute`. Enforces clean two-tier execution: heavy tasks isolated standalone to prevent Windows process handle hanging and deadlocks, while lightweight Git workflows chain via `&&` for zero-RTT speed.
65
+ - **Playwright File Protocol Guard (`PLAYWRIGHT_FILE_PROTOCOL_BLOCKED`)**:
66
+ 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.
62
67
  - **Full Overwrite Protection & Single-Shot Recovery (`failureRecovery`)**:
63
68
  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.
64
69
 
@@ -140,32 +145,35 @@ You are a master autonomous software engineer powered by DeepSeek Harness.
140
145
  - 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.
141
146
  - Ask first (via `ask_user_question`) ONLY when ambiguity materially affects scope, architecture, or data safety; otherwise execute autonomously.
142
147
  - Shell: ONLY `bash`. Launch `pwsh.exe` from `bash` when needed.
143
- - Web & external: research/fetch via available skills or bash CLIs.
148
+ - Web: Research/fetch STRICTLY via skills (`agent-reach`, `gh`, `opencli-*`, `smart-search`) or bash CLIs.
149
+ - Tool boundaries: External tools (playwright-cli, gh, ast-grep) are standalone CLIs via bash, NEVER require/import as node modules.
144
150
 
145
151
  ## Efficiency
146
152
 
147
153
  ### Hard Constraints
148
154
 
149
- - 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.
150
- - Failure recovery: retry ONLY when errors or new evidence suggest a specific fix; after two consecutive failures without progress, switch diagnostic approaches or input methods instead of repeating attempts.
151
- - Windows arguments & paths: use forward slashes or quoted paths in tool arguments to avoid escape corruption (`\t`, `\n`). For complex or multiline payloads (`node -e`, `python -c`, `pwsh -Command`), prioritize supported stdin or file inputs. Avoid raw multiline arguments through `.cmd`/`.bat` wrappers.
152
- - Byte-fidelity: default new text files to UTF-8. Preserve existing file encodings, BOMs, line endings, `.gitattributes`, and hook policies unless conversion is explicitly requested.
153
- - Policy denials (`file access denied`, network blocked, approval rejected) are policy boundaries, not command bugs: report immediately without retrying or bypassing. Request `sandbox_permissions` ONLY when escalation is explicitly available.
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. NEVER embed multiline or complex scripts in shell arguments (`node -e`, `python -c`, `pwsh -Command`). 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 reading/writing files (`grep`, `rg`, `find`, `ls`, `dir`, `cat`, `type`, `head`, `tail`, `sed`, `awk`, `tee`, `>`/`>>`). Filtering piped command output (`cmd | grep`) and batch removing temporary artifacts (`rm -rf`) are permitted.
154
160
 
155
161
  ### Execution & Context Efficiency
156
162
 
157
163
  - Workflow:
158
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.
159
- - Scheduling: Prioritize `read_batch` for multi-file inspection; keep edits, retries, and dependent checks sequential.
160
- - Diagnosis: contiguous context in one pass; cite locators and minimal raw excerpts only as evidence.
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.
161
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.
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).
162
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).
163
- - 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`, NEVER scan directory listings.
164
- - 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 asked. "This page/GUI" means the runtime Web GUI URL (no implicit DOM). Editing `~/.dsh/SYSTEM.md` hot-reloads the live prompt.
165
172
  - Modification & execution:
166
- - File ops: produce deliverables directly. Prioritize `edit_batch` for applying targeted replacements across one or more files in a single turn. Prioritize `edit` for single partial modifications; use `write` for new files or necessary full replacements. Unified calc/verification scripts permitted via `write`.
167
- - Structured data: process STRICTLY via ad-hoc Node/Python scripts passed via stdin or temp files; NEVER dump raw data into context.
168
- - Shell execution: system binaries, external CLIs, builds, package managers, test runners — STRICTLY via `bash`. 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.
173
+ - File ops: 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 & calculations: MUST write ad-hoc Node/Python scripts to disk first via native `write` and execute by file path; NEVER embed calculations or processing in `python -c` or `node -e`.
176
+ - Shell execution: run heavy tasks (`npm test`, `npm run build`, `vitest`, `npm publish`) standalone to prevent Windows deadlocks; chain lightweight commands via `&&` (`git add ... && git commit ... && git push`) to eliminate round trips.
169
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.
170
178
 
171
179
  ## Verification
@@ -173,11 +181,12 @@ You are a master autonomous software engineer powered by DeepSeek Harness.
173
181
  Applies ONLY to change/build/fix.
174
182
 
175
183
  - NEVER falsify tests (weaken assertions, stub a failing path, or skip a check to pass).
176
- - Tiered verification by risk; prioritize existing relevant checks; add targeted tests when behavior lacks coverage. Do not repeat equivalent checks unless code, configuration, environment, or relevant evidence changes:
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:
177
185
  - Text or mechanical changes without behavioral or contract effects: inspect the diff and relevant syntax/format; skip unrelated linters.
178
- - Behavior changes: run the smallest non-destructive targeted build/test covering affected behavior and internal interfaces.
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.
179
187
  - Shared API, schema, or migration changes: run the full related suite plus project-wide type checking where applicable (e.g. `tsc --noEmit`).
180
- - Report checks, results, and verification gaps.
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>). 'screenshot' takes selector target ONLY (no output filename; auto-saved to .playwright-cli/). NEVER pre-probe ('--help', '--version', 'node -v'), 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.
181
190
  - Persistent failure: report failed command(s), 1–2 sentence root cause, blast radius, next steps.
182
191
  ```
183
192
  </details>
package/README.zh.md CHANGED
@@ -5,19 +5,22 @@
5
5
  [![npm version](https://img.shields.io/npm/v/dsh-awesome-optimizer.svg?color=blue)](https://www.npmjs.com/package/dsh-awesome-optimizer)
6
6
  [![license](https://img.shields.io/github/license/Jaylor-Wang/dsh-awesome-optimizer.svg)](LICENSE)
7
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/)
8
+ [![Tests](https://img.shields.io/badge/tests-31%20passed-brightgreen.svg)](test/)
9
9
  [![TypeScript](https://img.shields.io/badge/TypeScript-Strict%20Types-blue.svg)](src/)
10
10
 
11
- 围绕官方 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`@deepseek-ai/dsh-agent-loop`) 打造的高性能非侵入式运行期防护、PTC 复合批处理工具、全新独立系统提示词接管(~80% Token 极致瘦身)与客观 A/B 轮次度量插件。
11
+ 围绕官方 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`@deepseek-ai/dsh-agent-loop`) 打造的高性能运行时策略防护、PTC 复合批处理工具、全新独立系统提示词接管与客观 A/B 轮次度量插件。
12
12
 
13
13
  ---
14
14
 
15
- ## v1.5.0 版本重要更新
15
+ ## v1.8.0 版本重要更新
16
16
 
17
- - **RFC 2119 强约束语气与注意力锚定加固**:收敛软提醒全面升级为 `NEVER omit verification.`,杜绝步数压力下的偷懒与提前交卷;在常驻收敛规范、推荐模板及拦截提示中全局统一大写强约束词(`ONLY`、`NEVER`、`STRICTLY`)。
18
- - **工具定义与官方 DSH 契约像素级对齐**:`edit_batch` 参数描述精准对齐官方 `edit` 工具约定(显式要求提供 `file_path` 优先顺序),彻底消除动词混淆(统一为 `produce deliverables`),确保模型复用对原生工具的先验理解。
19
- - **细粒度复合网络命令拦截放行**:精准优化 `CHAINED_NETWORK_COMMAND` 防护规则,在彻底杜绝 `npm publish` 等 Windows 凭据与发布操作悬挂的同时,完全放行本地与协同的复合 `git push` 流水线。
20
- - **全新 `SYSTEM.md` 独立接管与 80% Token 极致瘦身 (`placement: "replace-all"`)**:彻底剥离官方约 2,000 tokens 的冗长提示词,全局统一由独立的 `~/.dsh/SYSTEM.md`(约 380 tokens)作为唯一最高指令集,每轮节省约 1.6K tokens 上下文空间。
17
+ - **解除宿主要求限制(显示为「未声明宿主要求」)**:完全对齐 `dsh-tool-antigravity` 规范,移除了 `package.json` 中的 `engines.dsh` 并将所有 `@deepseek-ai/*` 宿主依赖收拢至开发时依赖(`devDependencies`),彻底消除了插件市场中计算生成的 `DSH >=0.2.2-rc.1 ∩ *` 约束标签,展示为纯净的「未声明宿主要求」,允许在任意 DSH 运行时环境下无阻碍安装与更新。
18
+ - **测试运行器 Windows 管道死锁根治**:将测试脚本重构为 `node --test --test-concurrency=1 --test-timeout=10000`,由多 Worker 并发争用改为确定性单通道顺序执行,彻底消除 Windows 控制台 stdio 管道缓冲区互锁与未回收 EOF 挂起隐患。
19
+ - **重型任务复合命令链隔离拦截 (`CHAINED_HEAVY_COMMAND`)**:在 `tools/pre-execute` 阶段主动检测并拦截复合链(`&&`、`;`)中的重型构建、测试与发布命令(`npm test`、`npm run build`、`vitest`、`npm publish`),彻底杜绝 Windows 控制台管道死锁;同时放行纯净的 Git 流水线串联(`git add ... && git commit ... && git push`)。
20
+ - **临时脚本落地磁盘硬约束升维 (`MUST`)**:将数学建模、复杂计算与辅助脚本的磁盘落地要求全面升级为最高级 RFC 2119 规范 `MUST write ad-hoc Node/Python scripts to disk`,并与 `NEVER embed multiline scripts` 形成工整对仗。
21
+ - **Playwright CLI 选择器语义与探测硬约束加固**:明确 `screenshot` 仅接收 CSS 选择器且自动落盘(无输出文件名参数),配合 `--help` / `--version` 探针硬性禁令,消除多余回合损耗与选择器报错。
22
+ - **提示词信噪比深度净化与冲突消除**:移除与辅助脚本产生认知对抗的 `produce deliverables directly` 语句;净化 `Windows arguments & paths` 使其 100% 聚焦于引号与转义防坑;去重冗余的 `rm -rf` 清理描述。
23
+ - **生态与插件市场表述全量对齐**:全面对齐 DSH 官方插件市场卡片规范,采用标准工业级特性命名 `SYSTEM.md replacement mode`,去除生僻术语。
21
24
 
22
25
  ---
23
26
 
@@ -26,7 +29,7 @@
26
29
  ### 1. 系统提示词精简与文件驱动热重载 (`customPrompt`)
27
30
 
28
31
  - **独立接管模式 (`placement: "replace-all"`)**:
29
- 在 DSH 官方 `system-prompt/assemble` 组装瀑布流中,精确剥除官方 verbose 冗余章节(包括 `harness:*`、`deployment:*`、`tool:*`、`deliverable:*`、`web:*` 等),并保留会话收敛指导等协同章节,将原始高达 ~2,000 tokens 的提示词压缩至约 380 tokens(降幅达 **82%**)。
32
+ 在 DSH 官方 `system-prompt/assemble` 组装瀑布流中,精确剥除官方 verbose 冗余章节(包括 `harness:*`、`deployment:*`、`tool:*`、`deliverable:*`、`web:*` 等),并保留会话收敛指导等协同章节,将系统提示词基线精简至约 380 tokens 的轻量核心指令。
30
33
  - **双层 Markdown 规约**:
31
34
  自动寻找全局配置 `~/.dsh/SYSTEM.md`(或 `$DSH_HOME/SYSTEM.md`)与项目级工作区配置 `.dsh/SYSTEM.md`(或 `SYSTEM.md`)。权责清晰,与面向角色的 `AGENTS.md` 解耦。
32
35
  - **毫秒级防抖热重载(Hot-Reload)**:
@@ -34,11 +37,11 @@
34
37
  - **级联策略灵活可选**:
35
38
  支持 `concat`(全局与工作区级联合并,默认)与 `workspace-override`(项目级完全覆盖全局)。
36
39
  - **内置 Prompt Linter 健康度校验与一键修复**:
37
- 提供 `lintPrompt` / `fixPrompt` / `lintPromptFile` API。**基于用户当前预设加载的插件工具做动态客观判定**,杜绝主观臆断:当工具未在预设加载时提示冗余防守,当工具已加载却声明禁用时提示配置冲突,并校验弱语气词(如 `bias toward` 自动升级为 `Prioritize`)、RFC 2119 强约束大写规范及未闭合反引号,输出健康度打分(0-100)并支持一键无损修复。
40
+ 提供 `lintPrompt` / `fixPrompt` / `lintPromptFile` API。**基于用户当前预设加载的插件工具做动态客观判定**,杜绝主观臆断:当工具未在预设加载时提示冗余防守,当工具已加载却声明禁用时提示配置冲突,并校验弱语气词(如软性建议词自动升级为标准动词)、RFC 2119 强约束大写规范及未闭合反引号,输出健康度打分(0-100)并支持一键无损修复。
38
41
 
39
42
  | 指标维度 | 官方默认 System Prompt | 开启本插件优化后 | 收益 |
40
43
  | :--- | :--- | :--- | :--- |
41
- | **Token 占用** | ~2,000 tokens / 轮 | **~380 tokens / 轮** | **节省 ~82% 提示词消耗** |
44
+ | **提示词上下文开销** | ~2,000 tokens / 轮 | **~380 tokens / 轮(推荐模板)** | **大幅释放有效上下文,杜绝冗余规则消耗** |
42
45
  | **长轮次会话累积** | 50 轮累计消耗 ~100K 冗余上下文 | 上下文干净紧凑,核心指令专注 | **显著缓解上下文漂移与遗忘** |
43
46
  | **配置修改生效** | 需重启服务或重载配置文件 | 文件修改保存即刻热生效 | **即写即调,毫秒级响应** |
44
47
 
@@ -57,8 +60,10 @@
57
60
  基于输入参数指纹计算,当同一工具以相同参数连续失败达到 `noProgressLimit`(默认 `2` 次)时,在 `tools/pre-execute` 阶段立即硬拦截并强迫模型转换诊断思路,杜绝死循环。
58
61
  - **Windows 超大 Shell 载荷拦截 (`EMBEDDED_SHELL_PAYLOAD_TOO_LARGE`)**:
59
62
  自动拦截超过 `4096` 字节的 `bash` 命令,或超过 `512` 字节的内联脚本参数(`node -e`、`python -c`、`pwsh -Command` 等),引导模型先通过原生 `write` 落盘再执行,规避 Windows 命令行参数溢出崩溃。
60
- - **Windows 复合网络命令挂起防御 (`CHAINED_NETWORK_COMMAND`)**:
61
- 在 `tools/pre-execute` 阶段自动拦截将网络/凭据操作(`npm publish` 等)与本地耗时操作混合串联的复合命令,强行引导模型执行两分法:本地确定性操作(`git add ... && git commit ... && npm test`)复合提速,网络发布独立把关,彻底规避 Windows 子进程句柄悬挂与 120s 超时。
63
+ - **Windows 重型任务串联死锁防御 (`CHAINED_HEAVY_COMMAND`)**:
64
+ 在 `tools/pre-execute` 阶段自动拦截将重型并发或发布操作(`npm test`, `npm run build`, `vitest`, `npm publish`)与其他命令串联的复合语句,强行引导单列执行重型任务以防 Windows 死锁,同时彻底放行轻量确定性操作(`git add ... && git commit ... && git push`)链式执行,最大化节省交互轮次。
65
+ - **Playwright 文件协议前置拦截 (`PLAYWRIGHT_FILE_PROTOCOL_BLOCKED`)**:
66
+ 在 `tools/pre-execute` 阶段主动检测并拦截 `playwright-cli open/goto file://...` 调用,立即引导模型使用本地 HTTP 环回服务访问,防止浏览器僵尸子进程残留与协议阻断异常。
62
67
  - **大文件覆写防御与快速重放恢复 (`failureRecovery`)**:
63
68
  保护已存在的大文件不被全量 `write` 误覆盖;针对大文件写入(8KB–1MB)因缺失配对 `justification` 被拒的场景,提供 `retry_failed_write` 快捷工具,由宿主从缓存直接重放,避免大模型重新生成数千行代码。
64
69
 
@@ -140,32 +145,35 @@ You are a master autonomous software engineer powered by DeepSeek Harness.
140
145
  - 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.
141
146
  - Ask first (via `ask_user_question`) ONLY when ambiguity materially affects scope, architecture, or data safety; otherwise execute autonomously.
142
147
  - Shell: ONLY `bash`. Launch `pwsh.exe` from `bash` when needed.
143
- - Web & external: research/fetch via available skills or bash CLIs.
148
+ - Web: Research/fetch STRICTLY via skills (`agent-reach`, `gh`, `opencli-*`, `smart-search`) or bash CLIs.
149
+ - Tool boundaries: External tools (playwright-cli, gh, ast-grep) are standalone CLIs via bash, NEVER require/import as node modules.
144
150
 
145
151
  ## Efficiency
146
152
 
147
153
  ### Hard Constraints
148
154
 
149
- - 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.
150
- - Failure recovery: retry ONLY when errors or new evidence suggest a specific fix; after two consecutive failures without progress, switch diagnostic approaches or input methods instead of repeating attempts.
151
- - Windows arguments & paths: use forward slashes or quoted paths in tool arguments to avoid escape corruption (`\t`, `\n`). For complex or multiline payloads (`node -e`, `python -c`, `pwsh -Command`), prioritize supported stdin or file inputs. Avoid raw multiline arguments through `.cmd`/`.bat` wrappers.
152
- - Byte-fidelity: default new text files to UTF-8. Preserve existing file encodings, BOMs, line endings, `.gitattributes`, and hook policies unless conversion is explicitly requested.
153
- - Policy denials (`file access denied`, network blocked, approval rejected) are policy boundaries, not command bugs: report immediately without retrying or bypassing. Request `sandbox_permissions` ONLY when escalation is explicitly available.
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. NEVER embed multiline or complex scripts in shell arguments (`node -e`, `python -c`, `pwsh -Command`). 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 reading/writing files (`grep`, `rg`, `find`, `ls`, `dir`, `cat`, `type`, `head`, `tail`, `sed`, `awk`, `tee`, `>`/`>>`). Filtering piped command output (`cmd | grep`) and batch removing temporary artifacts (`rm -rf`) are permitted.
154
160
 
155
161
  ### Execution & Context Efficiency
156
162
 
157
163
  - Workflow:
158
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.
159
- - Scheduling: Prioritize `read_batch` for multi-file inspection; keep edits, retries, and dependent checks sequential.
160
- - Diagnosis: contiguous context in one pass; cite locators and minimal raw excerpts only as evidence.
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.
161
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.
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).
162
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).
163
- - 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`, NEVER scan directory listings.
164
- - 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 asked. "This page/GUI" means the runtime Web GUI URL (no implicit DOM). Editing `~/.dsh/SYSTEM.md` hot-reloads the live prompt.
165
172
  - Modification & execution:
166
- - File ops: produce deliverables directly. Prioritize `edit_batch` for applying targeted replacements across one or more files in a single turn. Prioritize `edit` for single partial modifications; use `write` for new files or necessary full replacements. Unified calc/verification scripts permitted via `write`.
167
- - Structured data: process STRICTLY via ad-hoc Node/Python scripts passed via stdin or temp files; NEVER dump raw data into context.
168
- - Shell execution: system binaries, external CLIs, builds, package managers, test runners — STRICTLY via `bash`. 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.
173
+ - File ops: 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 & calculations: MUST write ad-hoc Node/Python scripts to disk first via native `write` and execute by file path; NEVER embed calculations or processing in `python -c` or `node -e`.
176
+ - Shell execution: run heavy tasks (`npm test`, `npm run build`, `vitest`, `npm publish`) standalone to prevent Windows deadlocks; chain lightweight commands via `&&` (`git add ... && git commit ... && git push`) to eliminate round trips.
169
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.
170
178
 
171
179
  ## Verification
@@ -173,11 +181,12 @@ You are a master autonomous software engineer powered by DeepSeek Harness.
173
181
  Applies ONLY to change/build/fix.
174
182
 
175
183
  - NEVER falsify tests (weaken assertions, stub a failing path, or skip a check to pass).
176
- - Tiered verification by risk; prioritize existing relevant checks; add targeted tests when behavior lacks coverage. Do not repeat equivalent checks unless code, configuration, environment, or relevant evidence changes:
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:
177
185
  - Text or mechanical changes without behavioral or contract effects: inspect the diff and relevant syntax/format; skip unrelated linters.
178
- - Behavior changes: run the smallest non-destructive targeted build/test covering affected behavior and internal interfaces.
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.
179
187
  - Shared API, schema, or migration changes: run the full related suite plus project-wide type checking where applicable (e.g. `tsc --noEmit`).
180
- - Report checks, results, and verification gaps.
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>). 'screenshot' takes selector target ONLY (no output filename; auto-saved to .playwright-cli/). NEVER pre-probe ('--help', '--version', 'node -v'), 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.
181
190
  - Persistent failure: report failed command(s), 1–2 sentence root cause, blast radius, next steps.
182
191
  ```
183
192
  </details>
package/cordis.patch.yml CHANGED
@@ -32,7 +32,7 @@
32
32
  globalFile: "~/.dsh/SYSTEM.md"
33
33
  workspaceFile: ".dsh/SYSTEM.md"
34
34
  # Placement modes:
35
- # - "replace-all": Strip ALL verbose official sections and use ONLY the refined SYSTEM.md (~80% token savings!)
35
+ # - "replace-all": Strip ALL verbose official sections and use ONLY the refined SYSTEM.md
36
36
  # - "suffix": Append to end of official system prompt (Order 10300)
37
37
  placement: "replace-all"
38
38
  mergeStrategy: "concat"
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Agent 循环策略与收敛优化器",
4
- "description": "围绕官方 DSH Agent Loop 的非侵入式运行期防护、PTC 复合批处理工具、轻量软预算提醒与 A/B 轮次度量插件。"
4
+ "description": "围绕官方 DSH Agent Loop 的运行时策略防护、PTC 复合批处理工具、轻量软预算提醒与 A/B 轮次度量插件。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-awesome-optimizer",
3
- "version": "1.5.0",
4
- "description": "Non-invasive runtime policy, composite batch tooling, soft convergence guidance, reactive custom prompt engine, and A/B telemetry plugin for the official DeepSeek Harness (dsh) agent loop.",
3
+ "version": "1.8.0",
4
+ "description": "Runtime policy guards, composite batch tooling, soft convergence guidance, reactive custom prompt engine, and A/B telemetry plugin for the official DeepSeek Harness (dsh) agent loop.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
7
7
  "types": "src/index.d.ts",
@@ -57,12 +57,11 @@
57
57
  }
58
58
  },
59
59
  "engines": {
60
- "node": ">=22.0.0",
61
- "dsh": ">=0.2.2-rc.1"
60
+ "node": ">=22.0.0"
62
61
  },
63
62
  "scripts": {
64
63
  "setup:local": "node scripts/setup-local.mjs",
65
- "test": "node --test --test-timeout=15000 test/*.test.js",
64
+ "test": "node --test --test-concurrency=1 --test-timeout=10000 test/*.test.js",
66
65
  "typecheck": "node scripts/typecheck.mjs",
67
66
  "benchmark": "node scripts/benchmark.mjs"
68
67
  },
@@ -87,7 +86,7 @@
87
86
  "telemetry",
88
87
  "composite-tools"
89
88
  ],
90
- "peerDependencies": {
89
+ "devDependencies": {
91
90
  "@deepseek-ai/cordis": ">=4.0.0",
92
91
  "@deepseek-ai/dsh-agent": "*",
93
92
  "@deepseek-ai/dsh-agent-loop": "*",
@@ -96,19 +95,5 @@
96
95
  "@deepseek-ai/dsh-system-prompt": "*",
97
96
  "@deepseek-ai/dsh-tools": "*",
98
97
  "@deepseek-ai/schemastery": ">=3.0.0"
99
- },
100
- "peerDependenciesMeta": {
101
- "@deepseek-ai/dsh-agent": {
102
- "optional": true
103
- },
104
- "@deepseek-ai/dsh-agent-loop": {
105
- "optional": true
106
- },
107
- "@deepseek-ai/dsh-session": {
108
- "optional": true
109
- },
110
- "@deepseek-ai/schemastery": {
111
- "optional": true
112
- }
113
98
  }
114
99
  }
@@ -216,7 +216,7 @@ export function applyCompositeTools(ctx, rawConfig = {}) {
216
216
  ctx.tools.register({
217
217
  name: EDIT_BATCH_TOOL,
218
218
  description: [
219
- `Apply multiple targeted literal text edits (up to ${config.maxBatchEdits}) across one or more files in a single tool call.`,
219
+ `Apply multiple targeted literal text edits (up to ${config.maxBatchEdits}) in a single file or across multiple files in a single tool call.`,
220
220
  'Edits execute sequentially through the native edit tool pipeline with full sandbox, observation policy, and mutation checks.',
221
221
  'Useful for multi-file refactoring or multi-location revisions without sequential single-edit round trips.'
222
222
  ].join(' '),
@@ -229,7 +229,7 @@ export function applyCompositeTools(ctx, rawConfig = {}) {
229
229
  type: 'array',
230
230
  minItems: 1,
231
231
  maxItems: config.maxBatchEdits,
232
- description: `List of literal text edits (1 to ${config.maxBatchEdits} edits) to apply sequentially across one or more files.`,
232
+ description: `List of literal text edits (1 to ${config.maxBatchEdits} edits) to apply sequentially in a single file or across multiple files.`,
233
233
  items: {
234
234
  type: 'object',
235
235
  additionalProperties: false,
@@ -8,8 +8,8 @@ export const SOURCE = 'optimizer-convergence';
8
8
  export const GUIDANCE = [
9
9
  "Work toward the user's completion criteria with as few model round trips as practical.",
10
10
  'Batch independent reads, searches, and checks in a single response when their inputs are known (or use read_batch for multi-file reads); preserve dependencies and exclusive tool barriers.',
11
- 'Command chaining: 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.',
12
- 'Before emitting a large payload, produce deliverables or reusable scripts to disk using native write and execute by file path. NEVER embed complete files or large scripts in shell arguments (node -e, python -c, pwsh -Command).',
11
+ 'Command chaining: Run heavy tasks (npm test, npm run build, vitest, npm publish) standalone to prevent Windows deadlocks; chain lightweight commands via && (git add ... && git commit ... && git push) to eliminate round trips.',
12
+ 'Before emitting a large payload or calculation, produce deliverables or reusable scripts to disk using native write and execute by file path. NEVER embed complete files, calculations, or large scripts in shell arguments (node -e, python -c, pwsh -Command).',
13
13
  'For localized revisions on existing files, reuse context already in the conversation and prefer native edit (or edit_batch for multi-file/multi-location revisions) with an unambiguous match over rewriting the entire file.',
14
14
  'After receiving tool results, make the next complete useful decision without repeating equivalent searches or checks unless new evidence justifies them.',
15
15
  'This efficiency guidance NEVER overrides the user, correctness, permission checks, required verification, or cancellation.'
@@ -5,6 +5,7 @@ export declare const name: 'agent-optimizer-custom-prompt';
5
5
  export declare const inject: ['systemPrompt'];
6
6
  export declare const SOURCE: 'optimizer-custom-prompt';
7
7
  export declare const SECTION_NAME: 'optimizer:custom-prompt';
8
+ export declare const ENVIRONMENT_FACTS_SECTION: 'optimizer:environment-facts';
8
9
  export declare const DEFAULT_SECTION_ORDER = 10300;
9
10
 
10
11
  export type MergeStrategy = 'concat' | 'workspace-override' | 'global-only' | 'workspace-only';
@@ -20,10 +21,20 @@ export interface CustomPromptOptions {
20
21
  mergeStrategy?: MergeStrategy;
21
22
  hotReload?: boolean;
22
23
  interpolate?: boolean;
24
+ injectEnvironmentFacts?: boolean;
25
+ }
26
+
27
+ export interface PythonEnvInfo {
28
+ bin: string;
29
+ version: string;
23
30
  }
24
31
 
25
32
  export declare const CustomPromptConfig: z<CustomPromptOptions>;
26
33
 
34
+ export declare function detectPythonEnv(spawnSyncFn?: any): PythonEnvInfo | null;
35
+ export declare function resetPythonCacheForTesting(): void;
36
+ export declare function formatEnvironmentFacts(processRef?: any, pythonDetector?: () => PythonEnvInfo | null): string;
37
+
27
38
  export declare function resolveDshHome(env?: NodeJS.ProcessEnv): string;
28
39
  export declare function resolveGlobalPath(filePath?: string, env?: NodeJS.ProcessEnv): string;
29
40
  export declare function resolveWorkspacePath(workspaceRoot?: string | null, relativeOrPath?: string): string | null;
@@ -1,3 +1,4 @@
1
+ import { spawnSync } from 'node:child_process';
1
2
  import fs from 'node:fs';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
@@ -7,6 +8,7 @@ export const name = 'agent-optimizer-custom-prompt';
7
8
  export const inject = ['systemPrompt'];
8
9
  export const SOURCE = 'optimizer-custom-prompt';
9
10
  export const SECTION_NAME = 'optimizer:custom-prompt';
11
+ export const ENVIRONMENT_FACTS_SECTION = 'optimizer:environment-facts';
10
12
  export const DEFAULT_SECTION_ORDER = 10300;
11
13
 
12
14
  export const CustomPromptConfig = z.object({
@@ -18,9 +20,56 @@ export const CustomPromptConfig = z.object({
18
20
  sectionName: z.string().default(SECTION_NAME),
19
21
  mergeStrategy: z.union(['concat', 'workspace-override', 'global-only', 'workspace-only']).default('concat'),
20
22
  hotReload: z.boolean().default(true),
21
- interpolate: z.boolean().default(false)
23
+ interpolate: z.boolean().default(false),
24
+ injectEnvironmentFacts: z.boolean().default(true)
22
25
  });
23
26
 
27
+ let cachedPython = undefined;
28
+
29
+ export function resetPythonCacheForTesting() {
30
+ cachedPython = undefined;
31
+ }
32
+
33
+ /**
34
+ * Safely detect active Python runtime with one-shot memoization and timeout guards.
35
+ */
36
+ export function detectPythonEnv(spawnSyncFn = spawnSync) {
37
+ if (cachedPython !== undefined) return cachedPython;
38
+ for (const bin of ['python', 'python3']) {
39
+ try {
40
+ const res = spawnSyncFn(bin, ['--version'], { timeout: 600, encoding: 'utf8', windowsHide: true });
41
+ if (res && res.status === 0) {
42
+ const out = (res.stdout || res.stderr || '').trim();
43
+ if (out.startsWith('Python')) {
44
+ cachedPython = { bin, version: out };
45
+ return cachedPython;
46
+ }
47
+ }
48
+ } catch (_err) {}
49
+ }
50
+ cachedPython = null;
51
+ return null;
52
+ }
53
+
54
+ /**
55
+ * Generate compact host environment facts to eliminate exploratory probing turns (pwd, ls, node -v).
56
+ */
57
+ export function formatEnvironmentFacts(processRef = process, pythonDetector = detectPythonEnv) {
58
+ const version = processRef?.version || 'unknown';
59
+ const platform = processRef?.platform || 'unknown';
60
+ const arch = processRef?.arch || 'unknown';
61
+ const py = typeof pythonDetector === 'function' ? pythonDetector() : null;
62
+ const pyInfo = py ? `, ${py.version} (${py.bin})` : ' (Python not detected; use Node.js for ad-hoc scripts)';
63
+ return [
64
+ '## Host Environment & Tooling Facts',
65
+ `- Runtime: Node.js ${version}${pyInfo} on ${platform} (${arch}).`,
66
+ '- Standalone CLIs: playwright-cli, gh, ast-grep, and opencli are standalone binaries via bash; NEVER require/import as node modules.',
67
+ '- Browser automation: playwright-cli blocks "file:" URLs (serve via loopback HTTP); \'screenshot\' takes selector target ONLY (no output filename; auto-saved to .playwright-cli/). NEVER probe via \'--help\' or \'--version\'.',
68
+ '- Zero startup probing: workspace context and host facts are already hydrated. NEVER run exploratory probing (pwd, ls, node -v, which).',
69
+ '- Ad-hoc scripts & cleanup: MUST write ad-hoc Node/Python scripts to disk via native write first and execute by file path; remove temporary artifacts directly via bash (rm -rf).'
70
+ ].join('\n');
71
+ }
72
+
24
73
  /**
25
74
  * Resolve `$DSH_HOME` or default `~/.dsh`.
26
75
  */
@@ -253,24 +302,32 @@ export function applyCustomPrompt(ctx, rawConfig = {}) {
253
302
  if (config.placement === 'replace-all') {
254
303
  // Retain optimizer's own sections (e.g. convergence guidance) while stripping all official verbose sections
255
304
  const optimizerSections = assembly.sections.filter(
256
- s => typeof s.name === 'string' && s.name.startsWith('optimizer:') && s.name !== config.sectionName
305
+ s => typeof s.name === 'string' && s.name.startsWith('optimizer:') && s.name !== config.sectionName && s.name !== ENVIRONMENT_FACTS_SECTION
257
306
  );
307
+ const sections = [
308
+ {
309
+ name: config.sectionName,
310
+ text: customText,
311
+ interpolate: config.interpolate
312
+ }
313
+ ];
314
+ if (config.injectEnvironmentFacts) {
315
+ sections.push({
316
+ name: ENVIRONMENT_FACTS_SECTION,
317
+ text: formatEnvironmentFacts(),
318
+ interpolate: false
319
+ });
320
+ }
321
+ sections.push(...optimizerSections);
258
322
  return {
259
323
  ...assembly,
260
- sections: [
261
- {
262
- name: config.sectionName,
263
- text: customText,
264
- interpolate: config.interpolate
265
- },
266
- ...optimizerSections
267
- ]
324
+ sections
268
325
  };
269
326
  }
270
327
 
271
328
  // For suffix: if ctx.systemPrompt.section was not available, ensure it gets injected
329
+ const sections = [...assembly.sections];
272
330
  if (!ctx.systemPrompt?.section) {
273
- const sections = [...assembly.sections];
274
331
  const existingIdx = sections.findIndex(s => s.name === config.sectionName);
275
332
  if (existingIdx >= 0) {
276
333
  sections[existingIdx] = { ...sections[existingIdx], text: customText };
@@ -281,8 +338,15 @@ export function applyCustomPrompt(ctx, rawConfig = {}) {
281
338
  interpolate: config.interpolate
282
339
  });
283
340
  }
284
- return { ...assembly, sections };
285
341
  }
342
+ if (config.injectEnvironmentFacts && !sections.some(s => s.name === ENVIRONMENT_FACTS_SECTION)) {
343
+ sections.push({
344
+ name: ENVIRONMENT_FACTS_SECTION,
345
+ text: formatEnvironmentFacts(),
346
+ interpolate: false
347
+ });
348
+ }
349
+ return { ...assembly, sections };
286
350
 
287
351
  return assembly;
288
352
  });
package/src/index.d.ts CHANGED
@@ -72,6 +72,11 @@ export {
72
72
  CustomPromptManager,
73
73
  applyCustomPrompt,
74
74
  SECTION_NAME as CUSTOM_PROMPT_SECTION,
75
+ ENVIRONMENT_FACTS_SECTION,
76
+ formatEnvironmentFacts,
77
+ detectPythonEnv,
78
+ resetPythonCacheForTesting,
79
+ type PythonEnvInfo,
75
80
  type CustomPromptOptions,
76
81
  type MergeStrategy,
77
82
  type PlacementMode
package/src/index.js CHANGED
@@ -4,7 +4,7 @@ import { applyFileMutationPolicy, FileMutationPolicyConfig, FileMutationPolicyMa
4
4
  import { applyFailureRecovery, RecoveryRecord, RECOVERY_SOURCE, RETRY_TOOL, PAIRING_ERROR } from './failure-recovery.js';
5
5
  import { applyCompositeTools, CompositeToolsConfig, READ_BATCH_TOOL, EDIT_BATCH_TOOL } from './composite-tools.js';
6
6
  import { applyConvergence, ConvergenceConfig, SOURCE as CONVERGENCE_SOURCE, GUIDANCE, REMINDER } from './convergence.js';
7
- import { applyCustomPrompt, CustomPromptConfig, CustomPromptManager, SECTION_NAME as CUSTOM_PROMPT_SECTION } from './custom-prompt.js';
7
+ import { applyCustomPrompt, CustomPromptConfig, CustomPromptManager, SECTION_NAME as CUSTOM_PROMPT_SECTION, ENVIRONMENT_FACTS_SECTION, formatEnvironmentFacts, detectPythonEnv, resetPythonCacheForTesting } from './custom-prompt.js';
8
8
  import { applyTelemetry, TelemetryConfig, AgentTelemetryManager, compareTurnSummaries } from './telemetry.js';
9
9
 
10
10
  import { lintPrompt, fixPrompt, lintPromptFile, RULE_IDS as PROMPT_LINT_RULES } from './prompt-linter.js';
@@ -26,7 +26,7 @@ export const Config = z.object({
26
26
  });
27
27
 
28
28
  /**
29
- * Mount non-invasive runtime policy, write recovery, composite batch tools,
29
+ * Mount runtime policy guards, write recovery, composite batch tools,
30
30
  * soft convergence guidance, and objective turn telemetry around the official DSH agent loop.
31
31
  * Never disables @deepseek-ai/dsh-agent-loop or mutates agent/request parameters.
32
32
  */
@@ -82,6 +82,10 @@ export {
82
82
  POLICY_SOURCE,
83
83
  MUTATION_SOURCE,
84
84
  CUSTOM_PROMPT_SECTION,
85
+ ENVIRONMENT_FACTS_SECTION,
86
+ formatEnvironmentFacts,
87
+ detectPythonEnv,
88
+ resetPythonCacheForTesting,
85
89
  CustomPromptManager,
86
90
  applyCustomPrompt,
87
91
  lintPrompt,
@@ -35,6 +35,7 @@ export declare const RULE_IDS: {
35
35
  CONSTRAINT_CASING: string;
36
36
  LEGACY_JARGON: string;
37
37
  UNCLOSED_BACKTICKS: string;
38
+ CLI_REQUIRE_CONFUSION: string;
38
39
  };
39
40
 
40
41
  export declare function resolveActiveToolNames(options?: PromptLintOptions): Set<string> | null;
@@ -6,9 +6,17 @@ export const RULE_IDS = {
6
6
  WEAK_MODALS: 'weak-modals',
7
7
  CONSTRAINT_CASING: 'constraint-casing',
8
8
  LEGACY_JARGON: 'legacy-jargon',
9
- UNCLOSED_BACKTICKS: 'unclosed-backticks'
9
+ UNCLOSED_BACKTICKS: 'unclosed-backticks',
10
+ CLI_REQUIRE_CONFUSION: 'cli-require-confusion'
10
11
  };
11
12
 
13
+ const CLI_REQUIRE_PATTERNS = [
14
+ {
15
+ pattern: /\b(?:require|import)\s*\(?['"](?:playwright|gh|ast-grep|opencli)['"]\)?/gi,
16
+ suggestion: 'Standalone CLIs (playwright-cli, gh, ast-grep, opencli) must be executed via bash, not imported as node modules'
17
+ }
18
+ ];
19
+
12
20
  const WEAK_MODALS = [
13
21
  { pattern: /\b[Bb]ias(?:ed)?\s+toward\b/g, suggestion: 'Prioritize' },
14
22
  { pattern: /\b[Tt]ry\s+to\b/g, suggestion: 'Use direct imperative verbs' },
@@ -206,6 +214,20 @@ export function lintPrompt(content = '', options = {}) {
206
214
  fixable: false
207
215
  });
208
216
  }
217
+
218
+ // 6. CLI Require Confusion Check
219
+ for (const cliRule of CLI_REQUIRE_PATTERNS) {
220
+ if (cliRule.pattern.test(line)) {
221
+ issues.push({
222
+ ruleId: RULE_IDS.CLI_REQUIRE_CONFUSION,
223
+ severity: 'warning',
224
+ line: lineNum,
225
+ message: `Attempting to require or import external CLI tool directly. ${cliRule.suggestion}.`,
226
+ fixable: false
227
+ });
228
+ cliRule.pattern.lastIndex = 0;
229
+ }
230
+ }
209
231
  }
210
232
 
211
233
  // Calculate stats
@@ -354,23 +354,44 @@ export class RuntimePolicyManager {
354
354
  };
355
355
  }
356
356
 
357
- // Guard against dangerous network/credential command chaining on Windows
357
+ // Guard against blocked file:// URLs in playwright-cli
358
+ const isPlaywrightFileUrl = /\bplaywright-cli\s+(?:open|goto)\s+['"]?file:/i.test(cmd);
359
+ if (isPlaywrightFileUrl) {
360
+ state.shellPayloadBlocks++;
361
+ state.policyDenials++;
362
+ if (exec.token !== undefined) state.deniedTokens.add(exec.token);
363
+ return {
364
+ kind: 'deny',
365
+ reason: JSON.stringify({
366
+ code: 'PLAYWRIGHT_FILE_PROTOCOL_BLOCKED',
367
+ reason: "Playwright CLI blocks access to the 'file:' protocol.",
368
+ nextAction: "Serve static HTML files via a local HTTP server (e.g. node http.createServer or npx serve) and access 'http://127.0.0.1:<port>' instead.",
369
+ retryable: false
370
+ })
371
+ };
372
+ }
373
+
374
+ // Guard against dangerous heavy concurrent or publishing command chaining on Windows
358
375
  if (this.config.disallowChainedNetworkCommands) {
359
376
  const hasCompoundOperator = /(&&|;)/.test(cmd);
360
- const hasChainedNetworkAction = /(?:^|[\s;&|])(?:npm\s+publish|gh\s+(?:pr|issue)\s+create)\b/i.test(cmd);
361
- if (hasCompoundOperator && hasChainedNetworkAction) {
362
- state.shellPayloadBlocks++;
363
- state.policyDenials++;
364
- if (exec.token !== undefined) state.deniedTokens.add(exec.token);
365
- return {
366
- kind: 'deny',
367
- reason: JSON.stringify({
368
- code: 'CHAINED_NETWORK_COMMAND',
369
- reason: "Chaining network/credential-bound commands ('npm publish') with other commands causes Windows process handle hanging and 120s timeouts.",
370
- nextAction: "Separate into independent steps: execute local operations first, then run network command ('npm publish') standalone.",
371
- retryable: false
372
- })
373
- };
377
+ if (hasCompoundOperator) {
378
+ // Strip quoted string literals to prevent false positives in commit messages / echo args
379
+ const unquoted = cmd.replace(/"[^"\\]*(?:\\.[^"\\]*)*"/g, '""').replace(/'[^'\\]*(?:\\.[^'\\]*)*'/g, "''");
380
+ const hasBlockedCompoundAction = /(?:^|[\s;&|])(?:npm\s+(?:test|t|run\s+build|publish)|vitest)\b/i.test(unquoted);
381
+ if (hasBlockedCompoundAction) {
382
+ state.shellPayloadBlocks++;
383
+ state.policyDenials++;
384
+ if (exec.token !== undefined) state.deniedTokens.add(exec.token);
385
+ return {
386
+ kind: 'deny',
387
+ reason: JSON.stringify({
388
+ code: 'CHAINED_HEAVY_COMMAND',
389
+ reason: "Heavy tasks ('npm test', 'npm run build', 'vitest', 'npm publish') must run standalone to prevent Windows deadlocks.",
390
+ nextAction: "Execute heavy tasks standalone, then chain lightweight commands via '&&'.",
391
+ retryable: false
392
+ })
393
+ };
394
+ }
374
395
  }
375
396
  }
376
397
  }