dsh-awesome-optimizer 1.5.0 → 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/README.md CHANGED
@@ -8,16 +8,18 @@ English | [中文](README.zh.md)
8
8
  [![Tests](https://img.shields.io/badge/tests-21%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.7.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
+ - **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.
21
23
 
22
24
  ---
23
25
 
@@ -26,7 +28,7 @@ High-performance, non-invasive runtime policy, PTC-backed composite batch toolin
26
28
  ### 1. Refined System Prompt & File-Driven Hot-Reload (`customPrompt`)
27
29
 
28
30
  - **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).
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.
30
32
  - **Dual-Layer Markdown Convention**:
31
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.
32
34
  - **Millisecond Hot-Reload**:
@@ -38,7 +40,7 @@ High-performance, non-invasive runtime policy, PTC-backed composite batch toolin
38
40
 
39
41
  | Dimension | Official Default System Prompt | Optimized with This Plugin | Savings |
40
42
  | :--- | :--- | :--- | :--- |
41
- | **Token Usage** | ~2,000 tokens / turn | **~380 tokens / turn** | **~82% token reduction** |
43
+ | **Prompt Context Footprint** | ~2,000 tokens / turn | **~380 tokens / turn (Template)** | **Frees context headroom; eliminates redundant rules** |
42
44
  | **Long Multi-Turn Sessions** | ~100K redundant tokens across 50 turns | Clean, focused, high-density context | **Mitigates context drift & forgetting** |
43
45
  | **Config Updates** | Requires restart or reload | Instant hot-reload on file save | **Immediate feedback** |
44
46
 
@@ -59,6 +61,8 @@ High-performance, non-invasive runtime policy, PTC-backed composite batch toolin
59
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.
60
62
  - **Windows Chained Network Command Guard (`CHAINED_NETWORK_COMMAND`)**:
61
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.
62
66
  - **Full Overwrite Protection & Single-Shot Recovery (`failureRecovery`)**:
63
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.
64
68
 
@@ -140,32 +144,36 @@ You are a master autonomous software engineer powered by DeepSeek Harness.
140
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.
141
145
  - Ask first (via `ask_user_question`) ONLY when ambiguity materially affects scope, architecture, or data safety; otherwise execute autonomously.
142
146
  - Shell: ONLY `bash`. Launch `pwsh.exe` from `bash` when needed.
143
- - Web & external: research/fetch via available skills or bash CLIs.
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.
144
150
 
145
151
  ## Efficiency
146
152
 
147
153
  ### Hard Constraints
148
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.
149
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.
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.
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; 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).
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`.
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`).
167
175
  - 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.
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.
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>). 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.
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
@@ -8,16 +8,18 @@
8
8
  [![Tests](https://img.shields.io/badge/tests-21%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.7.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
+ - **宿主环境事实注水全面加固与弱语气词拔除**:环境事实注水段落全面升级为 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` 边界。
21
23
 
22
24
  ---
23
25
 
@@ -26,7 +28,7 @@
26
28
  ### 1. 系统提示词精简与文件驱动热重载 (`customPrompt`)
27
29
 
28
30
  - **独立接管模式 (`placement: "replace-all"`)**:
29
- 在 DSH 官方 `system-prompt/assemble` 组装瀑布流中,精确剥除官方 verbose 冗余章节(包括 `harness:*`、`deployment:*`、`tool:*`、`deliverable:*`、`web:*` 等),并保留会话收敛指导等协同章节,将原始高达 ~2,000 tokens 的提示词压缩至约 380 tokens(降幅达 **82%**)。
31
+ 在 DSH 官方 `system-prompt/assemble` 组装瀑布流中,精确剥除官方 verbose 冗余章节(包括 `harness:*`、`deployment:*`、`tool:*`、`deliverable:*`、`web:*` 等),并保留会话收敛指导等协同章节,将系统提示词基线精简至约 380 tokens 的轻量核心指令。
30
32
  - **双层 Markdown 规约**:
31
33
  自动寻找全局配置 `~/.dsh/SYSTEM.md`(或 `$DSH_HOME/SYSTEM.md`)与项目级工作区配置 `.dsh/SYSTEM.md`(或 `SYSTEM.md`)。权责清晰,与面向角色的 `AGENTS.md` 解耦。
32
34
  - **毫秒级防抖热重载(Hot-Reload)**:
@@ -38,7 +40,7 @@
38
40
 
39
41
  | 指标维度 | 官方默认 System Prompt | 开启本插件优化后 | 收益 |
40
42
  | :--- | :--- | :--- | :--- |
41
- | **Token 占用** | ~2,000 tokens / 轮 | **~380 tokens / 轮** | **节省 ~82% 提示词消耗** |
43
+ | **提示词上下文开销** | ~2,000 tokens / 轮 | **~380 tokens / 轮(推荐模板)** | **大幅释放有效上下文,杜绝冗余规则消耗** |
42
44
  | **长轮次会话累积** | 50 轮累计消耗 ~100K 冗余上下文 | 上下文干净紧凑,核心指令专注 | **显著缓解上下文漂移与遗忘** |
43
45
  | **配置修改生效** | 需重启服务或重载配置文件 | 文件修改保存即刻热生效 | **即写即调,毫秒级响应** |
44
46
 
@@ -59,6 +61,8 @@
59
61
  自动拦截超过 `4096` 字节的 `bash` 命令,或超过 `512` 字节的内联脚本参数(`node -e`、`python -c`、`pwsh -Command` 等),引导模型先通过原生 `write` 落盘再执行,规避 Windows 命令行参数溢出崩溃。
60
62
  - **Windows 复合网络命令挂起防御 (`CHAINED_NETWORK_COMMAND`)**:
61
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 环回服务访问,防止浏览器僵尸子进程残留与协议阻断异常。
62
66
  - **大文件覆写防御与快速重放恢复 (`failureRecovery`)**:
63
67
  保护已存在的大文件不被全量 `write` 误覆盖;针对大文件写入(8KB–1MB)因缺失配对 `justification` 被拒的场景,提供 `retry_failed_write` 快捷工具,由宿主从缓存直接重放,避免大模型重新生成数千行代码。
64
68
 
@@ -140,32 +144,36 @@ You are a master autonomous software engineer powered by DeepSeek Harness.
140
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.
141
145
  - Ask first (via `ask_user_question`) ONLY when ambiguity materially affects scope, architecture, or data safety; otherwise execute autonomously.
142
146
  - Shell: ONLY `bash`. Launch `pwsh.exe` from `bash` when needed.
143
- - Web & external: research/fetch via available skills or bash CLIs.
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.
144
150
 
145
151
  ## Efficiency
146
152
 
147
153
  ### Hard Constraints
148
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.
149
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.
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.
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; 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).
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`.
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`).
167
175
  - 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.
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.
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>). 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.
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.7.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",
@@ -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,
@@ -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,55 @@ 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 static HTML via loopback HTTP (http://127.0.0.1:<port>).',
68
+ '- Zero startup probing: workspace context and host facts are already hydrated. NEVER run exploratory probing (pwd, ls, node -v, which).'
69
+ ].join('\n');
70
+ }
71
+
24
72
  /**
25
73
  * Resolve `$DSH_HOME` or default `~/.dsh`.
26
74
  */
@@ -253,24 +301,32 @@ export function applyCustomPrompt(ctx, rawConfig = {}) {
253
301
  if (config.placement === 'replace-all') {
254
302
  // Retain optimizer's own sections (e.g. convergence guidance) while stripping all official verbose sections
255
303
  const optimizerSections = assembly.sections.filter(
256
- s => typeof s.name === 'string' && s.name.startsWith('optimizer:') && s.name !== config.sectionName
304
+ s => typeof s.name === 'string' && s.name.startsWith('optimizer:') && s.name !== config.sectionName && s.name !== ENVIRONMENT_FACTS_SECTION
257
305
  );
306
+ const sections = [
307
+ {
308
+ name: config.sectionName,
309
+ text: customText,
310
+ interpolate: config.interpolate
311
+ }
312
+ ];
313
+ if (config.injectEnvironmentFacts) {
314
+ sections.push({
315
+ name: ENVIRONMENT_FACTS_SECTION,
316
+ text: formatEnvironmentFacts(),
317
+ interpolate: false
318
+ });
319
+ }
320
+ sections.push(...optimizerSections);
258
321
  return {
259
322
  ...assembly,
260
- sections: [
261
- {
262
- name: config.sectionName,
263
- text: customText,
264
- interpolate: config.interpolate
265
- },
266
- ...optimizerSections
267
- ]
323
+ sections
268
324
  };
269
325
  }
270
326
 
271
327
  // For suffix: if ctx.systemPrompt.section was not available, ensure it gets injected
328
+ const sections = [...assembly.sections];
272
329
  if (!ctx.systemPrompt?.section) {
273
- const sections = [...assembly.sections];
274
330
  const existingIdx = sections.findIndex(s => s.name === config.sectionName);
275
331
  if (existingIdx >= 0) {
276
332
  sections[existingIdx] = { ...sections[existingIdx], text: customText };
@@ -281,8 +337,15 @@ export function applyCustomPrompt(ctx, rawConfig = {}) {
281
337
  interpolate: config.interpolate
282
338
  });
283
339
  }
284
- return { ...assembly, sections };
285
340
  }
341
+ if (config.injectEnvironmentFacts && !sections.some(s => s.name === ENVIRONMENT_FACTS_SECTION)) {
342
+ sections.push({
343
+ name: ENVIRONMENT_FACTS_SECTION,
344
+ text: formatEnvironmentFacts(),
345
+ interpolate: false
346
+ });
347
+ }
348
+ return { ...assembly, sections };
286
349
 
287
350
  return assembly;
288
351
  });
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,6 +354,23 @@ export class RuntimePolicyManager {
354
354
  };
355
355
  }
356
356
 
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
+
357
374
  // Guard against dangerous network/credential command chaining on Windows
358
375
  if (this.config.disallowChainedNetworkCommands) {
359
376
  const hasCompoundOperator = /(&&|;)/.test(cmd);