Просмотр исходного кода

chore: sync ZCode source v4.0.0

Source-Commit: acfaa5b7a5d245d5b84fbe37ef2c0d0748f97cdf
Source-Sync: zcode-open-source-v1
ZCode Source Sync Bot 1 день назад
Родитель
Сommit
a4b4445141
100 измененных файлов с 5238 добавлено и 955 удалено
  1. 19 0
      .agents/skills/feature-boundary-planner/references/zcode-feature-graph.yaml
  2. 4 0
      .gitattributes
  3. 10 1
      .oxlintrc.json
  4. 3 0
      DESIGN.md
  5. 2 1
      README.en.md
  6. 2 1
      README.md
  7. 172 43
      THIRD-PARTY-NOTICES.md
  8. 2 0
      UI_PLUGIN.en.md
  9. 2 0
      UI_PLUGIN.md
  10. 7 5
      apps/zcode-cli/docs/bash-shell-provider.md
  11. 48 0
      apps/zcode-cli/docs/bash-tool-ast-permission-semantics.md
  12. 12 4
      apps/zcode-cli/docs/design/design-builtin-plugin.md
  13. 1 1
      apps/zcode-cli/docs/design/v2/architecture.md
  14. 36 6
      apps/zcode-cli/docs/design/v2/auth-login.md
  15. 8 2
      apps/zcode-cli/docs/design/v2/commands.md
  16. 9 1
      apps/zcode-cli/docs/design/v2/compact/README.md
  17. 1 1
      apps/zcode-cli/docs/design/v2/compact/compact-phase-memory-plan.md
  18. 5 4
      apps/zcode-cli/docs/design/v2/compact/plan.md
  19. 181 0
      apps/zcode-cli/docs/design/v2/cua-standalone-in-process-broker.md
  20. 24 7
      apps/zcode-cli/docs/design/v2/hooks.md
  21. 11 0
      apps/zcode-cli/docs/design/v2/logging.md
  22. 173 33
      apps/zcode-cli/docs/design/v2/loop/meta-user-context.md
  23. 7 1
      apps/zcode-cli/docs/design/v2/loop/prompt-snapshot.md
  24. 72 14
      apps/zcode-cli/docs/design/v2/loop/system-prompt-contract.md
  25. 1 0
      apps/zcode-cli/docs/design/v2/loop/tool-calling-loop.md
  26. 46 0
      apps/zcode-cli/docs/design/v2/loop/turn-steering.md
  27. 40 0
      apps/zcode-cli/docs/design/v2/mcp-node-fallback.md
  28. 19 1
      apps/zcode-cli/docs/design/v2/mcp.md
  29. 15 4
      apps/zcode-cli/docs/design/v2/memory/README.md
  30. 11 2
      apps/zcode-cli/docs/design/v2/model/anthropic-reasoning-history-replay.md
  31. 9 8
      apps/zcode-cli/docs/design/v2/model/assistant-block-order.md
  32. 2 2
      apps/zcode-cli/docs/design/v2/model/context-composition.md
  33. 2 0
      apps/zcode-cli/docs/design/v2/model/stream-error-retry.md
  34. 50 16
      apps/zcode-cli/docs/design/v2/plugin-compat.md
  35. 56 0
      apps/zcode-cli/docs/design/v2/preinstalled-document-tools.md
  36. 19 7
      apps/zcode-cli/docs/design/v2/rewind-compact.md
  37. 12 3
      apps/zcode-cli/docs/design/v2/sea-cross-target-packaging.md
  38. 19 3
      apps/zcode-cli/docs/design/v2/session-persistence.md
  39. 9 6
      apps/zcode-cli/docs/design/v2/session-title-generation.md
  40. 11 5
      apps/zcode-cli/docs/design/v2/skill.md
  41. 565 19
      apps/zcode-cli/docs/design/v2/tool/00-tool-change-chain.md
  42. 40 0
      apps/zcode-cli/docs/design/v2/tool/01-read.md
  43. 21 8
      apps/zcode-cli/docs/design/v2/tool/02-write.md
  44. 23 1
      apps/zcode-cli/docs/design/v2/tool/03-edit.md
  45. 186 15
      apps/zcode-cli/docs/design/v2/tool/04-bash.md
  46. 100 12
      apps/zcode-cli/docs/design/v2/tool/07-subagent.md
  47. 24 11
      apps/zcode-cli/docs/design/v2/tool/12-input-normalization.md
  48. 6 2
      apps/zcode-cli/docs/design/v2/tool/13-websearch.md
  49. 55 12
      apps/zcode-cli/docs/design/v2/tool/17-read-file-state-resume.md
  50. 46 15
      apps/zcode-cli/docs/design/v2/tool/19-tool-search.md
  51. 4 1
      apps/zcode-cli/docs/design/v2/tool/README.md
  52. 4 1
      apps/zcode-cli/docs/usage/02-cli-reference.md
  53. 1 1
      apps/zcode-cli/docs/usage/05-permissions.md
  54. 5 1
      apps/zcode-cli/docs/usage/09-hooks.md
  55. 1 1
      apps/zcode-cli/docs/usage/12-troubleshooting.md
  56. 2 0
      apps/zcode-cli/docs/usage/13-automation.md
  57. 9 1
      apps/zcode-cli/e2e/compact-microcompact/README.md
  58. 42 11
      apps/zcode-cli/e2e/compact-microcompact/case-output-token-continuation.mjs
  59. 412 0
      apps/zcode-cli/e2e/compact-microcompact/case-read-state-hash-resume.mjs
  60. 2 0
      apps/zcode-cli/e2e/compact-microcompact/case-utils.mjs
  61. 2 0
      apps/zcode-cli/e2e/compact-microcompact/constants.mjs
  62. 8 0
      apps/zcode-cli/e2e/compact-microcompact/output-token-continuation-history.mjs
  63. 2 0
      apps/zcode-cli/e2e/compact-microcompact/suite-cases.mjs
  64. 2 1
      apps/zcode-cli/e2e/memory/README.md
  65. 2 1
      apps/zcode-cli/e2e/memory/memory-e2e-evidence.mjs
  66. 1 1
      apps/zcode-cli/package.json
  67. 5 0
      apps/zcode-cli/packages/adapters/package.json
  68. 20 0
      apps/zcode-cli/packages/adapters/src/auth/cli-oauth.ts
  69. 67 46
      apps/zcode-cli/packages/adapters/src/auth/shared-credentials.ts
  70. 23 1
      apps/zcode-cli/packages/adapters/src/browser/index.ts
  71. 2 0
      apps/zcode-cli/packages/adapters/src/browser/request.ts
  72. 294 0
      apps/zcode-cli/packages/adapters/src/browser/storage-state.ts
  73. 26 5
      apps/zcode-cli/packages/adapters/src/config/config-factory.ts
  74. 10 2
      apps/zcode-cli/packages/adapters/src/config/config-merger.ts
  75. 2 0
      apps/zcode-cli/packages/adapters/src/config/index.ts
  76. 70 3
      apps/zcode-cli/packages/adapters/src/config/plugin-secrets.adapter.ts
  77. 22 4
      apps/zcode-cli/packages/adapters/src/config/project-config.adapter.ts
  78. 23 2
      apps/zcode-cli/packages/adapters/src/config/schema.ts
  79. 63 42
      apps/zcode-cli/packages/adapters/src/exec/bash-shell-provider.ts
  80. 9 17
      apps/zcode-cli/packages/adapters/src/exec/execution-command.ts
  81. 43 16
      apps/zcode-cli/packages/adapters/src/exec/node-execution-adapter-process.ts
  82. 1 1
      apps/zcode-cli/packages/adapters/src/exec/node-execution-adapter-run.ts
  83. 96 2
      apps/zcode-cli/packages/adapters/src/exec/node-execution-adapter.ts
  84. 2 1
      apps/zcode-cli/packages/adapters/src/exec/outputEncoding.ts
  85. 27 1
      apps/zcode-cli/packages/adapters/src/exec/shell-init-snapshot.ts
  86. 5 0
      apps/zcode-cli/packages/adapters/src/exec/windows-executable.ts
  87. 12 11
      apps/zcode-cli/packages/adapters/src/fs/index.ts
  88. 49 0
      apps/zcode-cli/packages/adapters/src/fs/symlink-guard.ts
  89. 40 3
      apps/zcode-cli/packages/adapters/src/mcp/appConnections.test.ts
  90. 212 0
      apps/zcode-cli/packages/adapters/src/mcp/config-loader.ts
  91. 171 0
      apps/zcode-cli/packages/adapters/src/mcp/config-source.ts
  92. 628 351
      apps/zcode-cli/packages/adapters/src/mcp/index.ts
  93. 152 106
      apps/zcode-cli/packages/adapters/src/mcp/pool.ts
  94. 42 13
      apps/zcode-cli/packages/adapters/src/mcp/resource-subscriptions.ts
  95. 22 22
      apps/zcode-cli/packages/adapters/src/mcp/timeout.ts
  96. 258 0
      apps/zcode-cli/packages/adapters/src/mcp/tool-catalog-cache.ts
  97. 119 0
      apps/zcode-cli/packages/adapters/src/mcp/transport-errors.ts
  98. 7 1
      apps/zcode-cli/packages/adapters/src/memory-diagnostics/CONTRACT.md
  99. 18 7
      apps/zcode-cli/packages/adapters/src/memory-diagnostics/index.ts
  100. 1 1
      apps/zcode-cli/packages/adapters/src/memory-diagnostics/module.ts

+ 19 - 0
.agents/skills/feature-boundary-planner/references/zcode-feature-graph.yaml

@@ -17,6 +17,25 @@ rules:
     - "evidence-only"
 
 nodes:
+  - id: "capability.desktop-crash-restart"
+    kind: "capability"
+    label: "Manual restart after a desktop renderer crash"
+    aliases: ["崩溃重启", "renderer crash restart", "应用错误页重启"]
+    docs: ["docs/desktop/crash-restart.md"]
+    codeSeeds:
+      - file: "packages/desktop/src/main/desktopCommandHandlers.ts"
+        symbol: "restartAppAfterCrash"
+      - file: "packages/desktop/src/main/desktopCommandHandlers.ts"
+        symbol: "showRendererCrashDialog"
+      - file: "packages/desktop/src/main/index.ts"
+        symbol: "createWindowInstance"
+      - file: "packages/ui/src/ErrorBoundary.tsx"
+        symbol: "AppErrorBoundary"
+      - file: "packages/desktop/src/renderer/src/main.tsx"
+    invariants:
+      - "Main owns one recovery dialog and one restart request; recovery bypasses normal quit barriers."
+      - "Only desktop injects the restart callback; web and mobile retain page reload."
+      - "Guest recovery, normal quit and updates stay independent; no watchdog or unsaved-state guarantee."
   - id: "capability.archive-permanent-deletion"
     kind: "capability"
     label: "Permanent deletion of archived conversations"

+ 4 - 0
.gitattributes

@@ -6,6 +6,10 @@
 # db:schema:check 误报为 schema 差异并阻断 pre-push,强制 LF。
 *.baseline.sql text eol=lf
 
+# Python 锁文件由 recipe 按 SHA-256 固定;Windows autocrlf 检出成 CRLF 后,
+# 资源转换会报 lock digest differs,强制 LF。
+scripts/preinstalled-tools/python/locks/*.txt text eol=lf
+
 # E2E PDF fixture 含规范 xref 尾空格,必须按二进制处理,避免 diff --check 误报。
 packages/desktop/test/e2e/fixtures/fs/**/*.pdf binary
 # 文档查看器测试 PDF 同理:按字节解析 xref,换行转换会破坏偏移。

+ 10 - 1
.oxlintrc.json

@@ -123,7 +123,8 @@
       "files": [
         // 插件市场沿用上游存量大文件,只补充目录字段投影;不为行数机械拆分安装流程。
         "**/apps/zcode-cli/packages/adapters/src/plugins/marketplace.ts",
-        // MCP 连接入口沿用上游存量实现;连接屏障修复不为行数重排整个 adapter。
+        // MCP 连接入口沿用上游存量实现;连接屏障修复与异步启动只补充快照与逐服务等待,
+        // 不为行数重排整个 adapter。
         "**/apps/zcode-cli/packages/adapters/src/mcp/index.ts",
         // 流式 runner 沿用上游存量大文件;workflow 未知业务码重试上限只把尝试次数递给策略表,
         // 不为行数拆分 attempt 循环。
@@ -150,11 +151,19 @@
         "**/apps/zcode-cli/packages/core/src/runtime/methods/steering.ts",
         "**/apps/zcode-cli/packages/core/src/runtime/methods/turn.ts",
         "**/apps/zcode-cli/packages/core/src/runtime/methods/turn-model-step.ts",
+        // 动态 MCP 分支 rebase 到 staging 后,两边各自新增的行数相加超过 800(每边单独都不超):
+        // runtime 构造、工具执行与 compact 的现有职责不变,不为行数机械拆分。
+        "**/apps/zcode-cli/packages/core/src/runtime/agent-runtime.ts",
+        "**/apps/zcode-cli/packages/core/src/tool/executor/call-runner.ts",
+        "**/apps/zcode-cli/packages/core/src/runtime/methods/compact-active.ts",
         // core 包内以 --no-ignore 运行时,oxlint 按 cwd 相对路径匹配同一组存量文件。
         "src/runtime/methods/session-fork.ts",
         "src/runtime/methods/steering.ts",
         "src/runtime/methods/turn.ts",
         "src/runtime/methods/turn-model-step.ts",
+        "src/runtime/agent-runtime.ts",
+        "src/tool/executor/call-runner.ts",
+        "src/runtime/methods/compact-active.ts",
         "**/packages/ui/src/remote-connection-flow/index.ts"
       ],
       "rules": {

+ 3 - 0
DESIGN.md

@@ -136,6 +136,8 @@ Default light and dark CSS variables still exist as fallback foundations, but ne
 
 ### Semantic feedback colors
 
+- **Workspace Admission Unread**: `--color-workspace-admission-unread`
+  Use for the Hook and MCP pending-review unread dots: sky-500 in light themes and sky-400 in dark themes. Keep this reminder accent independent of the monochrome brand color.
 - **Success**: `--color-success` with `--color-success-foreground`
 - **Warning**: `--color-warning` with `--color-warning-foreground`
 - **Destructive**: `--color-destructive` with `--color-destructive-foreground`
@@ -578,6 +580,7 @@ Recommended elevation levels:
 - **Base**: no shadow, structure comes from background contrast
 - **Surface**: very subtle border-led separation
 - **Overlay**: `shadow-md` for menus, popovers, dialogs
+- **Composer status panels**: use `--shadow-status-panel` for a soft, broadly diffused shadow without a heavy bottom edge; retain it while the panel has focus.
 - **Attention**: `shadow-lg` only for toast, important floating cards, or rare emphasized panels
 
 Depth rules:

+ 2 - 1
README.en.md

@@ -15,7 +15,8 @@ ZCode is an AI coding workspace with desktop, browser, and terminal interfaces.
 
 ## Updates
 
-- **2026-11-12**: Updated to ZCode v3.18.2.
+- **2026-11-23**: Updated to ZCode v4.0.0.
+- 2026-11-12: Updated to ZCode v3.18.2.
 - 2026-11-12: Updated to ZCode v3.18.1.
 - 2026-11-11: Updated to ZCode v3.18.0.
 - 2026-11-03: Updated to ZCode v3.17.2.

+ 2 - 1
README.md

@@ -15,7 +15,8 @@ ZCode 是 AI 编程工作台,提供桌面应用、浏览器界面和终端 Age
 
 ## 更新
 
-- **2026-11-12**:更新至 ZCode v3.18.2 版本。
+- **2026-11-23**:更新至 ZCode v4.0.0 版本。
+- 2026-11-12:更新至 ZCode v3.18.2 版本。
 - 2026-11-12:更新至 ZCode v3.18.1 版本。
 - 2026-11-11:更新至 ZCode v3.18.0 版本。
 - 2026-11-03:更新至 ZCode v3.17.2 版本。

+ 172 - 43
THIRD-PARTY-NOTICES.md

@@ -192,6 +192,8 @@ Original copyright, license and NOTICE text is retained below. Identical text is
 
 - @inquirer/type@3.0.10 — MIT
 
+- @isaacs/fs-minipass@4.0.1 — ISC
+
 - @jimp/core@1.6.1 — MIT
 
 - @jimp/diff@1.6.1 — MIT
@@ -934,6 +936,8 @@ Original copyright, license and NOTICE text is retained below. Identical text is
 
 - chokidar@4.0.3 — MIT
 
+- chownr@3.0.0 — BlueOak-1.0.0
+
 - class-variance-authority@0.7.1 — Apache-2.0
 
 - classcat@5.0.5 — MIT
@@ -1704,6 +1708,10 @@ Original copyright, license and NOTICE text is retained below. Identical text is
 
 - minimist@1.2.8 — MIT
 
+- minipass@7.1.3 — BlueOak-1.0.0
+
+- minizlib@3.1.0 — MIT
+
 - mitt@3.0.1 — MIT
 
 - mkdirp@1.0.4 — MIT
@@ -2152,6 +2160,8 @@ Original copyright, license and NOTICE text is retained below. Identical text is
 
 - tailwindcss@4.2.2 — MIT
 
+- tar@7.5.13 — BlueOak-1.0.0
+
 - tiny-invariant@1.3.3 — MIT
 
 - tiny-typed-emitter@2.1.0 — MIT
@@ -2346,6 +2356,8 @@ Original copyright, license and NOTICE text is retained below. Identical text is
 
 - yallist@3.1.1 — ISC
 
+- yallist@5.0.0 — BlueOak-1.0.0
+
 - yaml@2.9.0 — ISC
 
 - yargs-parser@18.1.3 — ISC
@@ -4511,6 +4523,51 @@ Licensed under the MIT license.
 
 ````
 
+### Notice 4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b
+
+- @isaacs/fs-minipass@4.0.1: LICENSE
+
+- isexe@2.0.0: LICENSE
+
+- lru-cache@5.1.1: LICENSE
+
+- mute-stream@2.0.0: LICENSE
+
+- once@1.4.0: LICENSE
+
+- semver@6.3.1: LICENSE
+
+- semver@7.7.4: LICENSE
+
+- which@2.0.2: LICENSE
+
+- which@4.0.0: LICENSE
+
+- wrappy@1.0.2: LICENSE
+
+- yallist@3.1.1: LICENSE
+
+
+
+````text
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+````
+
 ### Notice 942eab097945c835cf41abcbf1b9a6659c5d0c3493e60c56796d2e045c219278
 
 - @jimp/core@1.6.1: LICENSE
@@ -36003,6 +36060,81 @@ MIT (c) Paul Miller (<https://paulmillr.com>), see [LICENSE](LICENSE) file.
 
 ````
 
+### Notice a49c9ba464796f65b59fca3f1e6ca40912df1e859f575383223f7ec6c5baae09
+
+- chownr@3.0.0: LICENSE.md
+
+- yallist@5.0.0: LICENSE.md
+
+
+
+````text
+All packages under `src/` are licensed according to the terms in
+their respective `LICENSE` or `LICENSE.md` files.
+
+The remainder of this project is licensed under the Blue Oak
+Model License, as follows:
+
+-----
+
+# Blue Oak Model License
+
+Version 1.0.0
+
+## Purpose
+
+This license gives everyone as much permission to work with
+this software as possible, while protecting contributors
+from liability.
+
+## Acceptance
+
+In order to receive this license, you must agree to its
+rules.  The rules of this license are both obligations
+under that agreement and conditions to your license.
+You must not do anything with this software that triggers
+a rule that you cannot or will not follow.
+
+## Copyright
+
+Each contributor licenses you to do everything with this
+software that would otherwise infringe that contributor's
+copyright in it.
+
+## Notices
+
+You must ensure that everyone who gets a copy of
+any part of this software from you, with or without
+changes, also gets the text of this license or a link to
+<https://blueoakcouncil.org/license/1.0.0>.
+
+## Excuse
+
+If anyone notifies you in writing that you have not
+complied with [Notices](#notices), you can keep your
+license by taking all practical steps to comply within 30
+days after the notice.  If you do not do so, your license
+ends immediately.
+
+## Patent
+
+Each contributor licenses you to do everything with this
+software that would otherwise infringe any patent claims
+they can license or become able to license.
+
+## Reliability
+
+No contributor can revoke this license.
+
+## No Liability
+
+***As far as the law allows, this software comes as is,
+without any warranty or condition, and no contributor
+will be liable to anyone for any damages related to this
+software or this license, under any kind of legal claim.***
+
+````
+
 ### Notice 0ccbf956cffc8dcf515809433cb5242ee67c94513d46e48c261d68d0880de406
 
 - class-variance-authority@0.7.1: LICENSE
@@ -46009,55 +46141,16 @@ SOFTWARE.
 
 ````
 
-### Notice 4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b
-
-- isexe@2.0.0: LICENSE
-
-- lru-cache@5.1.1: LICENSE
-
-- mute-stream@2.0.0: LICENSE
-
-- once@1.4.0: LICENSE
-
-- semver@6.3.1: LICENSE
-
-- semver@7.7.4: LICENSE
-
-- which@2.0.2: LICENSE
-
-- which@4.0.0: LICENSE
-
-- wrappy@1.0.2: LICENSE
-
-- yallist@3.1.1: LICENSE
-
-
-
-````text
-The ISC License
-
-Copyright (c) Isaac Z. Schlueter and Contributors
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted, provided that the above
-copyright notice and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
-IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-````
-
 ### Notice 8a1af140fdfbf5afd3df27f7e662f989c5b963a300020dfafce42033cae9e004
 
 - isexe@3.1.5: LICENSE.md
 
+- minipass@7.1.3: LICENSE.md
+
 - sax@1.6.0: LICENSE.md
 
+- tar@7.5.13: LICENSE.md
+
 
 
 ````text
@@ -53363,6 +53456,42 @@ MIT
 
 ````
 
+### Notice df05697a04b8997c79d423930534e59cc18828f6e22d0c8c2d62fcbea1c4f50b
+
+- minizlib@3.1.0: LICENSE
+
+
+
+````text
+Minizlib was created by Isaac Z. Schlueter.
+It is a derivative work of the Node.js project.
+
+"""
+Copyright (c) 2017-2023 Isaac Z. Schlueter and Contributors
+Copyright (c) 2017-2023 Node.js contributors. All rights reserved.
+Copyright (c) 2017-2023 Joyent, Inc. and other Node contributors. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+"""
+
+````
+
 ### Notice 1cab22f196264195a4caec8ca5630170fdde76ee8f43346e47021d087332d3b0
 
 - mitt@3.0.1: LICENSE

+ 2 - 0
UI_PLUGIN.en.md

@@ -427,6 +427,8 @@ async function saveViewState(state: unknown) {
 
 The page HTML must provide the `<pre>` element used in the example. Real components should consume any `latestResult` already received when they mount. This code only handles communication; document saving still goes through the plugin server.
 
+The desktop app serves the page with `data-theme` already set on `<html>` (the current app theme, `light` or `dark`). Write theme styles against `data-theme` so the first frame before the handshake uses the right theme and a dark-themed app does not flash a light frame; after the handshake, `hostContext.theme` remains the source of truth. See [first-frame theme for plugin UI](docs/plugins/plugin-ui-initial-theme.md).
+
 ## Platform, Data, and Capability Boundaries
 
 | Data / capability                                           | Where it belongs or how to use it                                                                                                                                              |

+ 2 - 0
UI_PLUGIN.md

@@ -427,6 +427,8 @@ async function saveViewState(state: unknown) {
 
 页面 HTML 需提供示例中的 `<pre>`;实际组件应在挂载后消费已经收到的 `latestResult`。这段代码只处理通信,文档保存仍通过插件服务执行。
 
+桌面端下发页面时会在 `<html>` 上预置 `data-theme`(当前应用主题,`light` 或 `dark`)。主题样式按 `data-theme` 编写,握手完成前的首帧就是正确主题,深色主题下不会先闪一帧浅色;握手后仍以 `hostContext.theme` 为准。规则见 [插件界面首帧主题](docs/plugins/plugin-ui-initial-theme.md)。
+
 ## 平台、数据与能力边界
 
 | 数据 / 能力                      | 应放在哪里或如何使用                                                                       |

+ 7 - 5
apps/zcode-cli/docs/bash-shell-provider.md

@@ -1,6 +1,6 @@
 # Bash Shell Provider 当前实现
 
-更新日期:2026-11-10
+更新日期:2026-11-17
 
 本文最初是 Bash 执行形态的实现计划。实现已经完成并继续扩展到 Windows、runtime shell selection、
 startup source 和 embedded search prelude;下面记录当前事实,不再是待执行 plan。
@@ -18,15 +18,15 @@ command: {
 ```
 
 `shellProfile` 是 execution port 的内部 profile:只有 Bash tool 设置,generic shell、hook 和配置 runner
-不得继承。adapter 对这个 profile 解析真实 shell 并尽量用 `shell: false` 直接 spawn;无法解析时显式返回
-`legacy-shell` selection,并降级到旧系统 shell。
+不得继承。adapter 对这个 profile 解析真实 shell 并尽量用 `shell: false` 直接 spawn;POSIX 找不到 bash/zsh
+时显式返回 `legacy-shell` selection,并降级到旧系统 shell(`/bin/sh`)。Windows 不再产出 `legacy-shell`。
 
 ## Shell 选择
 
 ```text
 user-config selection(新 session 与 cold resume 都读取当前设置)
   -> platform auto-detect
-  -> legacy system shell fallback
+  -> POSIX:legacy system shell fallback;Windows:ComSpec 上的 CMD
 ```
 
 POSIX:
@@ -41,7 +41,9 @@ Windows:
 - 用户显式选择可用 Git Bash 或 CMD;
 - 未显式选择时查找默认 Program Files Git Bash,再从 `git.exe` 位置反推;
 - Git Bash 使用 `dialect=git-bash`、`shell=false`;CMD 使用 `dialect=cmd` 和 cmd shell;
-- 没有可用选择时回到 legacy system shell。
+- 手选 CMD 与下面的回落,显示名都是 `cmd.exe`;
+- 没有可用选择时返回 `dialect=cmd`、`path=ComSpec ?? "cmd.exe"` 的 auto-detected selection。执行形态与原
+  ComSpec 回落相同;原因见 `docs/runtime-tools/bash-effective-shell-snapshot.md`。
 
 provider 只注入上面列出的通用变量和 ZCode 自己命名的变量,不引入其他产品命名的环境变量。
 

+ 48 - 0
apps/zcode-cli/docs/bash-tool-ast-permission-semantics.md

@@ -55,6 +55,54 @@ Build 经审批仍可执行,cat/grep 继续自动放行。安全子集补充
 Linux/GNU sed 各通过 49 个真实执行链场景:安全打印与标准输入替换直接执行,危险或子集外
 脚本在 Plan 下零执行、零文件改动;普通 Build 的 `-e` 打印经审批仍能执行。Windows 未实测。
 
+### 压缩包查看、Windows 查询与 git 历史(2026-11-14)
+
+Explore 子 agent 在 Plan 下常用的一批只读命令补进名单。同一份名单也决定 Build 是否免审批、
+Memory Agent 能执行什么、前缀授权哪些段可以省略,所以每个形态都必须在任何参数组合下不写盘、
+不联网、不执行其他程序:
+
+- `unzip`:必须带 `-l`/`-v`/`-t` 之一;只收 `-q`、`-C`、`-O`/`-I <字符集>`。`-d`、`-o`、`-p`、`-x`、
+  `-T`(改压缩包时间戳)都拒绝。Info-ZIP 没有长参数,`--` 不是参数结束而是「否定」标记
+  (`unzip -l -- -l a.zip` 会取消列表模式并解压,2026-11-14 用 Info-ZIP 6.00 复现),所以 unzip、`unzip -Z`、
+  zipinfo 里每个 `-` 开头的词都由回调按字符白名单整体校验:只能由该模式允许的字母组成(`-O`/`-I` 之后是字符集名),
+  `-`、`--` 和 `:`、`^`、`$`、`/` 等其他字符一律拒绝。原因是通用参数表只把 `-[A-Za-z0-9_-]` 开头的词当选项检查,
+  `unzip -:-l a.zip` 会被当成位置参数放过,而 Info-ZIP 把它解析成「开启 `:` 再取消 `-l`」并解压(同日复现)。
+  `-O` 的值可以贴在后面(`-Olatin1`),值里的字母不算列表参数。
+  `unzip -Z`(必须是第一个参数)与 `zipinfo` 共用 zipinfo 参数表,不收 `-M` 分页。
+- `tar`:只放行列表模式(`-t`/`--list`),必须用 `-f`/`--file` 指定归档;支持旧式 `tar tzf a.tgz`
+  和 `-tfa.tar`。只认 `t v z j J f` 与少量长参数(压缩格式、`--force-local`、`--wildcards`、
+  `--exclude` 等),长参数不接受缩写。GNU tar 把「冒号前没有 `/`」的归档名当成 `host:path`
+  远程归档,会解析主机名并调用 rsh;Windows 盘符 `D:\x.tar`、`D:/x.tar` 也命中(Git Bash 的 tar
+  是 GNU tar),所以带冒号的归档名必须同时给 `--force-local`。
+  例外说明:`-z/-j/-J/--zstd`(以及 GNU tar 对压缩归档的自动识别)会经 PATH 调用固定的解压程序
+  (gzip、bzip2、xz、zstd),只做解压流、不写盘;可由命令指定程序的 `-I`/`--use-compress-program` 仍拒绝。
+- `iconv`:不收 `-o`/`--output`。
+- `xxd`:参数按前缀识别(`-r` 开头都是还原),只收精确的安全写法;xxd 在第一个文件名后不再解析参数,
+  后面的词就是输出文件,所以最多一个位置参数。
+- `command -v`/`-V`:只查名字解析结果。`command <程序>` 仍由 wrapper 剥离后按程序本身判定。
+- Windows 查询:`dir` 同 `ls` 不限参数(CMD dir 和 GNU dir 都没有写入选项);`findstr` 只认 `/` 开关,
+  `/F:`、`/G:`、`/D:` 的值是 UNC 路径时拒绝;`where` 只认 `/R <目录>`、`/Q`、`/F`、`/T`;
+  `whereis` 按参数表放行。三者都不接受 `-` 开头的未知参数。
+- 不放行 `printenv`:它会把全部环境变量(含 API key、token)带进模型上下文,
+  与需要审批的 `echo $TOKEN`、`env` 保持同一边界;只查单个变量同样可能读到密钥。
+- git:`git --version` 只放行精确形态;`git log` 补 `--follow`、`-L`、`-i`、`--not` 等;新增 `git ls-tree`;
+  `git grep` 补 `-r`、`-I`、`-m`、`-p`/`-W` 等,不收 `-O`(分页程序)和 `--textconv`。
+  写入检查对 git 只看子命令之前的全局参数区:子命令之后的 `-c`/`-C`(`git grep -c` 计数、
+  `git diff -C` 找复制)由子命令参数表判定。`git -C`、`cd && git` 仍拒绝。
+
+通配符:策略只看得到 shell 展开前的 argv。`tar`、`unzip`(含 `unzip -Z`)、`zipinfo`、`iconv`、`xxd`
+的只读结论依赖参数的形态和个数,任何一个词带未引用的通配符(`*`、`?`、`[...]`)就不算只读。
+原因是展开后的文件名可能变成选项(`--checkpoint-action=exec=...` 让 tar 执行程序,`-o` 让 iconv 写文件),
+也可能多出一个位置参数,被 xxd 当成输出文件。引号里的模式(如 `tar -tf a.tar '*.md'`)不受影响;
+brace 展开在解析层已按动态词拒绝。2026-11-14 用 GNU tar 1.35 复现过 `tar -tf - *` 执行程序、
+`xxd *.bin` 覆盖第二个文件。`findstr`、`where`、`dir`、`whereis`、`command -v` 没有写入或执行类参数,
+不受此限制。
+
+`tar` 和 `command` 的参数语法无法用 safe flag 表表达,与 `find`、`printf` 一样放在 direct argv 分支,
+不改通用参数解析器。运行时选择 `cmd`/`legacy-shell` 时不使用本名单,改由 CMD 只读策略按 CMD 语法判定(见 04-bash.md);
+CMD 策略的 git 分支复用本名单的 `isGitReadOnlyCommand` 和 `hasDangerousGitGlobalOption`,所以 git 的新增形态
+(含「写入检查只看全局参数区」)在 CMD 下同样生效;其余新命令只对 Git Bash 等 POSIX 方言生效。回归见 `core/tests/bash-permission.test.ts`。
+
 ## 项目级 command prefix 权限
 
 command prefix registry 与本文件前述 readonly policy 是两个独立层:前者只决定用户选择

+ 12 - 4
apps/zcode-cli/docs/design/design-builtin-plugin.md

@@ -22,12 +22,20 @@
 | 路径 | 作用 |
 |---|---|
 | `.zcode-plugin/plugin.json`、`.claude-plugin/plugin.json` | 两份宿主清单,逐字节一致;ZCode 读前者,后者供使用 `.claude-plugin` 清单格式的宿主原生加载 |
-| `skills/design/SKILL.md`、`references/*.md`(7 份) | 入口技能与按需读取的规则文件 |
-| `skills/design/scripts/*.mjs` | 画布适配、资源目录生成、设计系统导入、design-lint(零依赖 Node 脚本) |
+| `skills/design/SKILL.md`、`references/*.md`(11 份) | 入口技能与按需读取的规则文件 |
+| `skills/design/scripts/*.{mjs,js}` | 随包 7 个:画布适配、设计系统导入、design-lint、design-tokens、渲染审计(`audit.mjs`,Playwright 不可用时退出 2 并给回退步骤)及其页内脚本 `audit-page.js`、`probe.js`;`build-catalog.mjs`、`frontmatter.mjs` 是开发期生成脚本,不进 seed |
 | `skills/design/design-resources/` | 第三方设计资源(骨架、设计系统、craft、子技能),按上游字节保留 |
 | `hooks/` | SessionStart hook:`run-hook.cmd`(sh/cmd 双写法)调 POSIX sh 脚本 `design-rules` |
 | `test/` | 插件内容与脚本测试,不随包发布(SEA、桌面 staging、远端复制的白名单都不含 `test/`) |
 
+## 生图
+
+插件自己不带生图工具。独立图片和页面里要用的图,调 image-generation 插件的 `generate_image`(Seedream,经 zcode-server 的 ToolHub)。参数契约与规则在 `references/image.md`,以该插件 schema 为准。
+
+- 前提:装并启用 image-generation 插件;登录账号自己开通 Coding Plan 并关联 Z.ai。只用 API key 接入套餐时 ZCode 不带套餐凭证,正式环境会拒绝(code 3001)。
+- 没装或调用失败:如实告诉用户原因。页面配图可退回用户自己的图、工具取来的真图或手绘 SVG,并标明是待替换的占位;独立图片到此为止。不用 SVG、HTML、CSS 画的图冒充生成的图。
+- 国内出图带「由 Z.ai 生成」可见水印和 AIGC 标识:不裁、不盖、不糊,排版要让它露出来。真机上见过模型自己把水印裁掉,所以写进规则并由测试钉住。
+
 ## SessionStart 注入预算
 
 用户启用后每个会话都带这段注入,所以只放一句指针和路径基准:
@@ -46,7 +54,7 @@ For an HTML design, prototype, HTML deck or redesign, load the `design` skill fi
 
 | 文件 | 改动 |
 |---|---|
-| `packages/bootstrap/src/app/official-plugin-definitions.ts` | 定义条目,不声明 `defaultEnabled`,listing「Design / 设计」,`OFFICIAL_DESIGN_REQUIRED_SEED_PATHS` 钉入口、7 份规则、3 个脚本与 hook |
+| `packages/bootstrap/src/app/official-plugin-definitions.ts` | 定义条目,不声明 `defaultEnabled`,listing「Design / 设计」,`OFFICIAL_DESIGN_REQUIRED_SEED_PATHS` 钉入口、11 份规则、7 个随包脚本与 hook(与磁盘对账由 server 测试保证) |
 | `packages/cli/scripts/sea-official-plugin-assets.mjs` | SEA 资源,`requiresRuntime: false`,必需文件同上 |
 | `packages/desktop/scripts/prepare-agent-node-bundle.mjs` | Electron 生产包 staging(`packages/desktop/test/runtime-asset-scripts.test.ts` 名单同步) |
 | `packages/server/src/remote/zcodeAgentOfficialPluginAssets.ts` | 远端 Agent 官方插件复制名单与必需文件 |
@@ -61,7 +69,7 @@ For an HTML design, prototype, HTML deck or redesign, load the `design` skill fi
 
 官方市场的内置分片与 CDN 分片同名时,合并目录以 CDN 条目为准,内置缓存不删除
 (`adapters/src/plugins/official-marketplace.ts`)。2026-11-04 核对正式 CDN 的 `marketplace.json`:没有 `design` 条目,
-只有另一个设计插件 `designcraft`,所以当前老用户升级后只会拿到内置版本(当前 0.7.2)。之后不要往 CDN 发同名 `design`。
+只有另一个设计插件 `designcraft`,所以当前老用户升级后只会拿到内置版本(当前 0.8.0)。之后不要往 CDN 发同名 `design`。
 装过 `designcraft` 的用户会同时有两套设计技能,是否下架或合并 `designcraft` 由插件 owner 决定。
 
 ## 第三方许可与竞品词

+ 1 - 1
apps/zcode-cli/docs/design/v2/architecture.md

@@ -143,7 +143,7 @@ adapters/
 启动流程只保留架构顺序,不固定实现细节:
 
 1. 入口层解析最小启动信息,并创建顶层执行上下文。
-2. 配置系统按明确优先级合并默认值、用户配置、项目配置、环境变量和 CLI 参数。
+2. 配置系统按明确优先级合并默认值、用户配置、项目配置、环境变量和 CLI 参数。skill 与命令的启停开关(`skillOverrides`、`commandOverrides`)按路径合并:用户和项目各停用一个 skill,两个都停用。其他嵌套对象的合并规则见[配置合并存量问题](../../../../../docs/issues/config-merge-legacy/01-nested-fields-replaced-by-higher-layer.md)。
 3. 所有项目自有环境变量使用 `ZCODE_` 前缀。
 4. bootstrap 创建基础 adapter,并把它们注入 core。
 5. storage 执行必要初始化和迁移。

+ 36 - 6
apps/zcode-cli/docs/design/v2/auth-login.md

@@ -28,6 +28,12 @@ The independent CLI discovers the same private `credential-secret` as the Server
 using the same credentials directory. Explicit managed configuration still takes
 precedence. A successful OS-key initialization pins that directory to its OS source;
 later remote preparation cannot change it before the first credential write.
+The CLI never falls back or resets the store on its own; only Desktop Main does
+(see "Desktop 私有文件密钥回退与自动重置" in
+[the system credential spec](../../../../../docs/plans/2026-10-29-system-credential-storage.md)).
+After Desktop resets a shared directory, a CLI process that still caches the old OS key
+cannot write new `enc:v2:os:` values without the `credential-source` marker; the write fails
+with `CREDENTIAL_SECURE_STORAGE_UNAVAILABLE`, and a restarted CLI resolves the new source.
 
 ZCode CLI login uses the ZCode/Z.AI CLI OAuth device flow and shares the same
 local credential store as the desktop Z Code product. The login boundary is a
@@ -61,11 +67,24 @@ Sensitive login state is stored in:
 ~/.zcode/v2/credentials.json
 ```
 
-The base directory follows the Z Code desktop convention:
-
-1. Explicit data base dir passed by the caller.
-2. `ZCODE_DATA_BASE_DIR`.
-3. `os.homedir()`.
+The file path resolves in this order:
+
+1. Explicit file path passed by the caller.
+2. Explicit data base dir passed by the caller, as `<dir>/.zcode/v2/credentials.json`.
+3. `ZCODE_CREDENTIALS_FILE`, an absolute file path.
+4. `ZCODE_DATA_BASE_DIR`, as `<dir>/.zcode/v2/credentials.json`.
+5. `os.homedir()`, as `~/.zcode/v2/credentials.json`.
+
+`ZCODE_CREDENTIALS_FILE` is process wiring, not a user setting. Only a Source Server
+Core sets it, when the Server uses its own credential store because the host's
+shared store is pinned to an OS key by a local Desktop (see
+[the shared storage contract](../../../../../docs/plans/2026-10-29-system-credential-storage.md#同机共用数据根server-自有凭据库2026-11-11)).
+The Agent inherits it from that Core, so both read and write the same file.
+Desktop never uses it: Desktop Main deletes an inherited value at startup, so
+its Main, Host and Agent always use the Desktop data root.
+An empty value counts as unset. A value that is not an absolute path makes store
+creation fail; it never resolves against the working directory. Tests cover the
+precedence, the empty value and the relative-path failure.
 
 The file remains a JSON key/value container. System-backed encryption and migration
 follow [the shared storage contract](../../../../../docs/plans/2026-10-29-system-credential-storage.md).
@@ -163,7 +182,18 @@ The HTTP response envelope is:
 
 `code != 0` is a business error even when the HTTP status is 200. Code `3004`
 means the flow is invalid, expired, or the poll token does not match; the user
-should start a new login.
+should start a new login. The server returns it with HTTP 400 once the flow
+expires. The CLI reports `3004` as the retryable `auth_timeout` error, with or
+without an HTTP error status.
+
+The init `data` carries `flow_id`, `authorize_url`, `expires_at`,
+`server_time` and `poll_interval_sec`. `expires_at` and `server_time` are Unix
+seconds on the server clock. The flow lifetime is `expires_at - server_time`,
+so local clock skew does not shorten or void the flow. The CLI does not read the
+`Date` response header; it is not part of the API contract. When an older server
+omits a numeric `server_time`, the CLI falls back to its local clock.
+Polling stops at the earlier of that lifetime and the local login timeout. See
+[local clock skew](../../../../../docs/oauth/desktop-oauth-polling.md#本机时钟偏差).
 
 ## Provider Setup
 

+ 8 - 2
apps/zcode-cli/docs/design/v2/commands.md

@@ -2,9 +2,11 @@
 
 ## CLI Process Identity
 
-CLI 命令名继续保持 `zcode`,用于兼容现有 npm `bin`、脚本、help 和文档示例。操作系统可见的 Node 进程名必须统一设置为 `zcode-cli`,避免通过 `ps`、Activity Monitor、任务管理器或 ZCode app-server 父进程管理面板观察时只看到 `node` 或不稳定的脚本名。
+CLI 命令名继续保持 `zcode`,用于兼容现有 npm `bin`、脚本、help 和文档示例。普通 CLI 与 Agent 的进程名保持 `zcode-cli`;通过 `__zcode-plugin-host` 启动的 MCP 插件进程使用 `zcode-mcp-<plugin-name>`,避免在进程查看工具中把插件宿主误认为 Agent。
 
-入口层必须在加载 bootstrap、TUI、provider、storage 或其它可能启动异步任务的模块之前设置 `process.title = "zcode-cli"`。该行为不新增 `ZCODE_*` 环境变量,也不依赖当前平台 shell、二进制文件名或用户启动方式;普通 Node bundle、`tsx` 开发入口和 SEA binary 都应共享同一个进程名常量。
+入口层先按启动子命令选择角色,再在加载 bootstrap、TUI、provider、storage 或插件模块之前设置 `process.title`。插件名取自已有 `ZCODE_PLUGIN_ID` 的 `@` 前部分,去除首尾空白并转为小写;名称须符合 `[a-z0-9][a-z0-9._-]{0,127}`。缺失或无效时使用 `zcode-mcp`,不从文件路径猜测名称。该值仅用于显示,不参与权限或插件身份判断。普通命令即使带有插件 ID 环境变量,也保持 `zcode-cli`。
+
+该行为不新增环境变量,不依赖平台 shell 或二进制文件名;普通 Node bundle、`tsx` 开发入口和 SEA binary 共用入口命名逻辑。存储迁移与 `--prepare-storage` 保持不改名,避免影响承载它们的 Host Worker。操作系统工具对名称的显示和截断仍受平台限制。
 
 `zcode doctor --json` 必须同时报告 `cli.processName` 和 `runtime.processTitle`,普通 `zcode doctor` 输出也应展示当前进程名,便于脚本和人工诊断验证实际运行进程已经应用该契约。
 
@@ -43,6 +45,7 @@ TUI 的 slash command 候选列表见 [`tui-slash-command-suggestions.md`](./tui
 - 全局 `--prompt <text>`: 作为脚本友好的单轮 headless 入口。未显式传入 `--mode` 时,CLI 必须以 `yolo` permission mode 创建 runtime,避免无交互 broker 的 headless prompt 在常见写文件、执行命令路径上停在审批流;显式 `--mode build|edit|plan|yolo` 仍然优先于该默认值。该默认只属于 `--prompt` 入口,不改变无参数 TUI、`zcode tui`、ZCode app-server session 或单独 `--target` 的初始化 mode。
 - 全局 `--browser-use=headless`: 为 `--prompt`、`--target` 和 TUI 显式启用 CLI managed CDP Browser Use。CLI 在首次 backend discovery 时启动 native headless Chromium,只有完成 CDP handshake 后才返回 `type: "cdp"` descriptor。该参数不使用 `agent-browser`,不改变 browser-use plugin/node_repl 模型入口;plugin 禁用时不得启动 Chromium。`zcode app-server` 使用该参数必须 fail closed,避免 Desktop/Web Remote shared-host 链路获得第二个 browser runtime。
 - 全局 `--browser-executable <absolute-path>`: 指定 `--browser-use=headless` 使用的 Chrome/Chromium 可执行文件;不能单独使用。省略时只查找本机已安装 browser 和 Playwright cache,P0 不联网下载。路径或可执行性错误必须发生在 app/session 创建前;实现使用跨平台 path/fs API 和参数数组 spawn,不经 shell,不默认添加 `--no-sandbox`。
+- 全局 `--browser-state <path>` / `--no-browser-state`: 为 `--browser-use=headless` 注入只读的 Playwright storage state 登录态。不传参数时自动加载 `~/.zcode/cli/browser-state.json`(存在时);`--no-browser-state` 关闭默认加载;两者互斥,且都不能脱离 `--browser-use=headless` 使用。文件缺失或校验失败必须发生在 app/session 创建前。每个 session 创建 BrowserContext 时重新读取文件,会话中的登录变化不写回。完整合同见 `docs/browser-use/2026-11-17-cli-browser-state-spec.md`。
 - 全局 `--workflow-mode <disabled|onDemand|alwaysOn>`: 决定本进程 TUI 与 headless(`--prompt`、`--target`)会话的动态工作流面,语义同服务端 `dynamicWorkflow.mode`(`docs/dynamic-workflow/launch.md`「The standalone CLI: `--workflow-mode`」)。**缺省为 `disabled`**。取值用 shared 的 `normalizeDynamicWorkflowMode`(精确拼写、忽略首尾空白),非法值在 CLI 入口报错并列出三个取值,退出码 1,不创建 app/session。`app-server`/`agent-server` 由 Host 决定 mode,带该参数即报作用域错误;`login`、`plugins`、`skills`、`doctor` 等不建会话的子命令同样报错。入口把 mode 一次性折成两个显式 runtime 字段 `dynamicWorkflowEnabled = mode !== "disabled"`、`dynamicWorkflowToolsOnDemand = mode === "onDemand"`,写进本进程创建的每个 app(含 `/new`、`/resume`、fork);mode 不落盘,resume 到不同 mode 静默切换。不新增环境变量或配置键。
 - 全局 `--target <objective>`: 用于兼容 headless goal 场景,等价于在 headless session 里执行 `/goal <objective>`;CLI 必须复用 command center 的 goal 语义,而不是重新发明一套 target-only 控制流。`--resume` / `--continue` 时作用于恢复出来的 session;未指定时作用于新建 session。`--target` 不与 `--prompt` 组合;需要显式 slash command 形态时使用 `--prompt "/goal ..."`。实现不得把 `--target` 改造成环境变量。
 - 全局 `--target-replace`: `--target` 的显式覆盖确认开关。若当前 session 已有 goal,而未显式提供 `--target-replace`,CLI 必须在本地返回明确错误,不得静默覆盖 goal,也不得发送模型请求。`--target-replace` 单独出现时必须报错。
@@ -90,6 +93,8 @@ CLI process identity 测试覆盖:
 - 入口层设置的进程名常量为 `zcode-cli`,且普通命令名仍为 `zcode`。
 - `zcode doctor --json` 输出 `cli.processName = "zcode-cli"` 和 `runtime.processTitle = "zcode-cli"`。
 - 普通 `zcode doctor` 输出包含当前进程名,方便手动诊断。
+- 真实插件子进程在模块导入时已显示 `zcode-mcp-<plugin-name>`;Node 与 desktop bundle 均验证该行为,同时保留插件入口不求值 Agent 模块的约束。
+- 插件 ID 缺失或无效时显示 `zcode-mcp`;普通命令不受插件 ID 环境变量影响。
 
 Headless `--prompt` 测试覆盖:
 
@@ -102,6 +107,7 @@ CLI Browser Use 测试覆盖:
 - prompt/TUI 把同一个 managed CDP runtime 注入当前 app;session replacement 关闭旧 context,不泄漏 tab。
 - browser-use plugin disabled 时通用 node_repl 仍可用,但不启动 Chromium、不注入 browser broker。
 - app-server 拒绝 headless 参数,不改变 Desktop/Web Remote shared-host ownership。
+- `--browser-state` / `--no-browser-state` 的来源解析、互斥、默认文件发现、启动前失败与每 session 注入,验收用例见 `docs/browser-use/2026-11-17-cli-browser-state-spec.md` §9。
 - Linux 无 `DISPLAY` 的真实 Chromium E2E 必须经过 MCP node_repl、plugin browser-client、broker 和 port,
   不能用直接调用 adapter 的 mock 冒充 Browser Use 全链路。
 

+ 9 - 1
apps/zcode-cli/docs/design/v2/compact/README.md

@@ -68,7 +68,7 @@ compact 或 preflight;该降级不改变 tool 执行和持久化合同。
 2. 执行轻量压缩或预算裁剪,例如 tool result budget、microcompact、snip。
 3. 判断是否满足 compact policy;手动 compact 直接进入执行。
 4. 运行 `PreCompact` hook,允许追加受控 summary 指令或阻止 compact。
-5. 构造 summary prompt。summary agent 只能输出文本,不允许工具调用。
+5. 构造 summary prompt。summary prompt 要求只输出文本;回复仍带工具调用时,按下文「摘要文本的选取」处理。
 6. 调 provider 生成 summary,并把 prompt-too-long、网络中断、无文本输出等失败归一化。
 7. 创建 `CompactBoundary` 和 `CompactSummary`。
 8. 生成 post-compact 恢复上下文,例如最近文件、plan 状态、已加载 skill、agent 状态、MCP/tool 声明、session start hook 结果。
@@ -77,6 +77,14 @@ compact 或 preflight;该降级不改变 tool 执行和持久化合同。
 
 业务 core 只表达这些状态转移和意图。模型请求、文件读取、session 存储、hook 子进程、网络和日志都必须通过 adapter 完成。
 
+#### 摘要文本的选取
+
+- 摘要请求只跑一轮。回复里的工具调用不执行,也不进入历史;运行时记一条 info 日志(`compact.summary.tool_calls_ignored`,带工具名),然后按文本继续。
+- 回复有多个文本块时,选最后一个含 `<summary>` 的文本块;都不含时,选最后一个文本块。空文本块也算一个文本块。流式结果和非流式回退用同一规则;结果没有分块信息时,用整段文字。
+- 只清洗选出的这一块:去掉第一个 `<analysis>…</analysis>`,把第一个 `<summary>…</summary>` 换成 `Summary:\n<内容>`。`<summary>` 被拆在两个文本块里时,只用含开标签的那一块,这块没有闭标签,标签原样保留。
+- 回复带工具调用时,选出的块必须有摘要:有成对的 `<summary>…</summary>`,或有一行以 `<summary>` 开头(先去掉第一个 `<analysis>…</analysis>` 再判断)。没有时按清洗后为空处理。原因:模型常先说一句(例如 "Let me read the file first.")再调用工具,这句话不是摘要,接受它会用一句话替换整段历史。没有工具调用的回复不做这项检查。
+- 清洗后为空(包括回复里没有文本块、只有工具调用)时,压缩失败,错误是 `Failed to generate compact summary`(可重试)。auto 在同一次压缩内最多尝试 3 次;手动压缩和 reactive 只尝试 1 次。
+
 ### 1.4 Summary 内容要求
 
 Compact summary 应稳定覆盖这些信息:

+ 1 - 1
apps/zcode-cli/docs/design/v2/compact/compact-phase-memory-plan.md

@@ -9,7 +9,7 @@
 - `/compact` 手动压缩入口。
 - auto compact policy 和失败熔断。
 - provider context overflow 后的 reactive compact retry。
-- compact summary prompt、tool call 拒绝、prompt-too-long retry。
+- compact summary prompt、摘要回复里的工具调用不执行(见 README「摘要文本的选取」)、prompt-too-long retry。
 - compact timeline part、summary message、compact boundary 事件。
 - resume 时从最近 compaction boundary 后恢复 provider-visible history。
 - compact phase/compactReason 元数据,覆盖 manual、pre-request、mid-turn 和 reactive 路径。

+ 5 - 4
apps/zcode-cli/docs/design/v2/compact/plan.md

@@ -33,7 +33,7 @@ hook results
 
 | 名称 | 初始值 | 用途 |
 | --- | ---: | --- |
-| summary output reserve | `min(modelMaxOutputTokens, 32_000)` | 给 summary 输出和后续请求留空间;没有模型输出上限时默认按 32k 预留。 |
+| summary output reserve | `min(modelMaxOutputTokens, max(21_000, contextWindow × 8%))` | 给 summary 输出和后续请求留空间,也是 summary 请求的 max_tokens;现行算法见 [模型请求输出上限策略](../../../../../../docs/model-request-output-tokens.md)。 |
 | auto compact buffer | `13_000` | 自动 compact 不等到满窗才触发。 |
 | warning/error buffer | `20_000` | UI/SDK 的 context warning。 |
 | manual compact buffer | `3_000` | 自动 compact 关闭时的阻塞保护。 |
@@ -114,7 +114,7 @@ Core 不直接读写文件、不读 `process.env`、不直接调用 provider SDK
 4. 运行 `PreCompact` hook,合并用户指令和 hook 指令。
 5. 构造 no-tools summary prompt。
 6. 通过 provider adapter 发起单轮 summary 请求。
-7. 清洗 `<analysis>`,只保留 `<summary>`。
+7. 按 README「摘要文本的选取」选出一个文本块,清洗 `<analysis>`,只保留 `<summary>`。
 8. 生成 boundary 和 compact summary。
 9. 追加 post-compact attachments。
 10. 写入 session log / message part。
@@ -133,7 +133,8 @@ Core 不直接读写文件、不读 `process.env`、不直接调用 provider SDK
 
 - 自定义 `/compact 重点保留测试输出` 会进入 summary prompt。
 - hook 指令会被追加,用户指令在前。
-- summary agent 尝试 tool call 时被拒绝,并转为失败或重试。
+- 摘要回复带 tool call 时,工具不执行;选出的块有摘要(成对的 `<summary>` 或行首 `<summary>`)时用它生成摘要。只有 tool call,或只有开场白(例如 "Let me read the file first.")时失败(auto 同一次压缩内重试)。
+- 摘要回复有多个文本块时,用最后一个含 `<summary>` 的块;都不含时用最后一个块。
 - compact 后下一轮 context builder 不再包含旧历史。
 - compact 失败不会写入半截 boundary。
 
@@ -151,7 +152,7 @@ Core 不直接读写文件、不读 `process.env`、不直接调用 provider SDK
 策略:
 
 ```text
-effectiveWindow = contextWindowForModel - min(modelMaxOutputTokens, 32_000)
+effectiveWindow = contextWindowForModel - min(modelMaxOutputTokens, max(21_000, contextWindowForModel × 8%))
 autoThreshold = effectiveWindow - 13_000
 shouldCompact = activeTokenEstimate >= autoThreshold
 ```

+ 181 - 0
apps/zcode-cli/docs/design/v2/cua-standalone-in-process-broker.md

@@ -0,0 +1,181 @@
+# 独立 CLI 的 Computer Use:进程内 broker
+
+状态:第一阶段(macOS、Windows;darwin / win SEA 单文件发布物可直接用;源码运行需显式指定 addon)。
+
+## 背景
+
+桌面端启动 CLI(`app-server --stdio`)时注入一组 CUA 凭据:broker socket 与 plugin authority。
+CLI 把它们捕获进进程内快照,再定向注入官方 `node_repl`;`node_repl` 连已签名的
+`ZCode Computer Use` Helper。用户在终端直接运行 `zcode` 时没有这组凭据,`node_repl`
+不创建 CUA runtime,Computer Use 不可用。
+
+外部 Helper 不能给独立 CLI 用(2026-11-13 实测):
+
+- SDK 懒启动用 `open` 拉起已装 Helper,Helper 启动门要求 launcher 是签名的 ZCode,直接拒绝启动;
+- 即使 Helper 已在运行,peer 门要求连接进程及其责任进程都由允许的 Team 签名,无签名 node 被拒。
+
+放宽这两道门会让同用户的任意进程借用 ZCode 已有的 TCC 授权,影响所有装了 ZCode 的用户,因此不放宽。
+进程内方案也有同类风险,但范围不同,见「安全边界与已接受风险」。
+
+## 方案
+
+独立 CLI 在 `node_repl` 进程内运行 broker(与 Helper 同一份 `runHelper` 实现),自己连自己:
+
+```
+zcode(顶层 CLI,darwin 或 win32,未收到宿主凭据)
+  │ 自签凭据组 { socket: "in-process", pluginAuthority: <随机> }
+  ▼
+bootstrap ── 与桌面一致:把凭据注入官方 node_repl 的 env
+  ▼
+zcode __zcode-plugin-host → node_repl-host
+  │ socket == "in-process"
+  ├─ 首次 CUA 调用:startInProcessComputerUseBroker(本进程,随机 socket)
+  └─ createComputerUseRuntime ── unix socket / named pipe ──▶ 同进程 broker
+macOS 的 TCC 主体:启动 zcode 的终端 App;Windows 没有 TCC
+```
+
+### 形态判定(唯一入口:CLI `main.ts`)
+
+同时满足以下条件时,CLI 自签凭据组:
+
+1. 顶层 CLI 进程:不是 protocol server(`app-server` / `agent-server` / 存储迁移),不是 `__zcode-plugin-host`;
+2. `process.platform` 是 `darwin` 或 `win32`;
+3. 入口清洗后没有捕获到宿主凭据。
+
+protocol server 一律不自签:桌面、SSH/WSL/Docker 远程都走 protocol server,远程机器上的 CLI
+不得因为缺少凭据就去控制远程桌面。凭据只存在进程内快照里,不写回任何子进程 env;
+`node_repl` 拿到的方式与桌面形态相同(bootstrap 定向注入 → plugin-host 校验后恢复)。
+
+### 不新增环境变量
+
+socket 字段使用哨兵值 `in-process`(CLI 侧常量 `ZCODE_CUA_IN_PROCESS_BROKER_SOCKET` 在 `@zcode/shared/runtime-env`;node_repl 侧常量 `IN_PROCESS_BROKER_SOCKET` 在 `@zcode/zcode-cua/broker/socketPath`,因 node_repl bundle 不得引入 shared 的 runtime-env,两处由测试钉成相等),复用已有的
+`ZCODE_CUA_PERMISSION_BROKER_SOCKET`。下游的 authority 校验、官方 CUA server 判定、plugin-host
+恢复逻辑都不需要改。
+
+### 进程内 broker(`@zcode/zcode-cua/broker/server` 的 `startInProcessComputerUseBroker`)
+
+- 首次 CUA 调用时才加载 native addon 并监听;之后复用。启动失败不缓存,下次调用重试。
+- socket:`mintBrokerSocketPath()`。macOS 是用户私有 0700 目录内的随机名 unix socket;Windows 是随机名 named
+  pipe(`\\.\pipe\zcode-cua-helper-<hex>`)。每个 `node_repl` 进程一份,互不冲突。
+- 不安装 peer 校验,也没有 token 握手。这是已接受的风险,不是"没有风险",见「安全边界与已接受风险」。
+- 不加 socket 单例锁、不做空闲自退;生命周期跟随 `node_repl` 进程,`dispose` 时 stop。
+- 不注册 `process.exit` / 信号处理:宿主进程的生命周期归 `node_repl` 管。
+- 不开虚拟光标、PiP(第一阶段)。
+- 使用用户级 controller lease(`createCuaControllerLease`)。第一次动作时获取,`node_repl` 进程退出时才释放。
+  它挡住了哪些并发、没挡住哪些,见「并发控制」。
+
+### 权限
+
+macOS:缺辅助功能 / 屏幕录制权限时,授权对象是**终端 App**(Terminal、iTerm、Orca 等),不是 ZCode。
+Windows:没有 TCC,不需要授权;但 zcode 以普通权限运行时,UIPI 不允许它向以管理员身份运行的程序发送输入或读取
+其 UI 树。
+`get_app_state` 默认 `include_screenshot=false`,没有图不代表缺屏幕录制权限。
+
+## 安全边界与已接受风险
+
+broker 监听一个本机 socket,连接后不校验对端身份,收到请求就以本进程的身份执行 AX 读取、截图和输入。
+
+| 平台 | 能挡住谁 | 挡不住谁 | 后果 |
+|---|---|---|---|
+| macOS | 其他用户(runtime 目录 0700) | 同 uid 的任意进程。随机文件名挡不住它,`readdir` 就能列出 | 没有 TCC 授权的同 uid 进程(LaunchAgent、其他 App 的子进程、被植入的依赖)可以借用**终端 App** 的辅助功能和屏幕录制授权:截屏、读 UI 树、发送键鼠 |
+| Windows | 依赖 named pipe 的默认 ACL(未单独核实对其他用户的效果) | 同用户的任意进程 | 同用户、同完整性级别的进程本来就能直接调用 UIA 和发送输入,不构成额外提权 |
+
+暴露窗口:从第一次 CUA 调用到 `node_repl` 退出。没有用过 CUA 的会话不会监听。
+
+为什么接受(第一阶段):
+
+- 需求是"同事拿到一个二进制就能用",并明确接受 CLI 形态暂不做外部鉴权。
+- 影响面只限于主动运行独立 CLI、并在 macOS 上给终端授过权的用户;不影响只用 ZCode 客户端的用户。桌面 Helper
+  的签名门(背景一节)维持原样。
+
+风险接受记录在本功能的 MR 描述中。以下任一条件成立时必须先补对端校验,再扩大使用范围:
+
+- 独立 CLI 默认开启 computer-use,或面向外部用户发布;
+- broker 的暴露窗口变长(例如常驻后台进程)。
+
+可选的补法(未实现):
+
+1. 校验对端 pid 等于本进程 pid。调用方是同进程的 Worker bridge,native 已有 `getPeerCredentials`。
+2. 要求连接先出示 `pluginAuthority` 等本进程私有的 token,否则拒绝分发。
+
+## 并发控制
+
+controller lease 是用户级文件锁。谁参与了它,谁才互斥:
+
+| 组合 | 是否互斥 | 说明 |
+|---|---|---|
+| macOS:独立 CLI ↔ 桌面 Helper | 是 | 后来者收到 `CUA_CONTROLLER_BUSY` |
+| macOS:两个独立 CLI | 是 | 同上 |
+| Windows:独立 CLI ↔ 桌面 Helper | **否** | 桌面 Windows Helper(`runWindowsDevHelper`)不接 controller lease,两边可以同时发送键鼠,互相打断 |
+| Windows:两个独立 CLI | 是 | 但见下面的接管问题 |
+
+已知限制(第一阶段不修):
+
+- **持有时间长**:lease 到 `node_repl` 退出才释放。macOS 上,终端里的 zcode 用过一次 CUA 且没退出时,桌面端的
+  CUA 会一直返回 `CUA_CONTROLLER_BUSY`。桌面端也接管不了:接管前要确认持有者是真的 Helper App
+  (`helperPidEvidence`),进程内 broker 不满足,接管失败。用户需要退出终端里的 zcode。
+- **Windows 上接管不校验身份**:`helperPidEvidence` 在非 darwin 平台直接认定持有者是 Helper,接管时会对持有者
+  pid 发 `SIGTERM`;Windows 上又无法发现 pid 被复用。持有者已退出且 pid 被别的进程复用时,接管可能终止无关进程。
+- 修复方向:动作结束或空闲一段时间后释放 lease;给 Windows 的身份校验加 fail-closed 分支;让桌面 Windows Helper
+  接入 lease。
+
+## 平台
+
+- macOS、Windows:本阶段支持。Windows 桌面 Helper 本身就是 node 进程跑 `runHelper`,进程内 broker 与它是同一份实现,
+  只是不经 fork、不经 Windows Helper 组合根(`runWindowsDevHelper`)。
+- Linux:不自签,行为不变(CUA 不可用)。
+
+## 发布物(SEA)
+
+只有 darwin 与 win target(`darwin-arm64`、`darwin-x64`、`win-arm64`、`win-x64`)的 SEA 内置 `computer-use`
+插件;linux target 不内置,行为不变。插件 seed 在源码插件文件之外多带两类运行时文件:
+
+| seed 路径 | 来源 | 用途 |
+|---|---|---|
+| `native/ax_native.node` | darwin target 在 macOS 主机上按 target 隔离编译;其他情况取 `packages/zcode-cua/build/Release/ax_native.node` | 进程内 broker 的 AX / 截图 / 输入原语 |
+| `node_modules/<sharp 运行时闭包>` | 与桌面同一份 `resolveSharpRuntimePackageNames(target)` | 截图编码 |
+
+- macOS 主机构建 darwin target 时,`build-sea` 每次都把 `binding.gyp` 与 `src/native` 复制到该 target 的
+  SEA 暂存目录,在那里运行 `node-gyp rebuild --arch=<arch>`,用产物打包。不读也不改
+  `packages/zcode-cua/build`:桌面开发与 E2E 用的是那份主机架构 addon,`--all` 中途换架构会让它们失效;
+  每次重编也保证打包的是当前源码,不依赖 `build/Release` 当时是哪个架构。编译失败时中止该 target。
+- win target 仍取 `build/Release`(本阶段只自动编译 macOS;win addon 需要 MSVC,只能在 Windows 上编)。
+  所以在 macOS 上不带平台参数的 `pnpm build:sea` 会在 win target 失败,报错提示用
+  `--darwin --linux` 只打这两个平台;Windows 主机上照旧先 `node-gyp rebuild --arch=<arch>`。
+- 构建期校验 addon 的架构必须与 target 一致(darwin 读 Mach-O,win 读 PE machine),不符时中止该 target,
+  不产出缺 CUA 的二进制。
+- `ci-cli-sea.mjs` 对 darwin / win target 先 `node-gyp rebuild --arch=<arch>` 重编 addon,再打 SEA。CI 的 macOS
+  runner 是 arm64、Windows runner 是 x64,交叉架构都靠这一步(与桌面 `build:cua-helper`、`build:windows` 同一做法)。
+  darwin target 在 `build-sea` 里还会隔离重编一次,CI 这一步对 darwin 是重复的,暂不改 CI。
+- 开源占位 producer 没有 addon:检测到占位包时不内置 `computer-use`,也不编译。
+- 运行时查找:node_repl 在首次 CUA 调用时检查 `$ZCODE_CUA_PLUGIN_ROOT/native/ax_native.node`,存在就交给
+  broker。sharp 由插件根下的 `node_modules` 解析。
+- 源码运行(`tsx main.ts`)时插件根没有 `native/`,addon 的默认查找从 `process.argv[1]`(CLI 入口)向上找
+  `build/Release`,找不到 `packages/zcode-cua` 下的产物,首次 CUA 调用会报 `ax_native.node not found`。
+  源码运行必须设置 `ZCODE_CUA_HELPER_ADDON=<repo>/packages/zcode-cua/build/Release/ax_native.node`(开发专用,
+  已有变量,不是新增)。
+
+### 同事拿到二进制后
+
+macOS:
+
+1. `xattr -d com.apple.quarantine ./zcode && chmod +x ./zcode`(SEA 只有 ad-hoc 签名);
+2. `./zcode login`;
+3. 系统设置给运行 zcode 的终端 App 打开「辅助功能」「屏幕录制」,重启终端。
+
+Windows:`.\zcode.exe login` 后直接使用;SmartScreen 拦截时选「仍要运行」。
+
+## 待办
+
+- 缺权限时的引导文案指向终端 App。
+- 对端校验(「安全边界与已接受风险」)。
+- lease 释放时机、Windows 接管身份校验、Windows 桌面 Helper 接入 lease(「并发控制」)。
+
+## 验证
+
+- `node-repl-host`:哨兵值走进程内 broker;真实 socket 走外部 Helper(原行为)。
+- `shared`:自签只在无宿主凭据时生效,不覆盖宿主凭据。
+- CLI:protocol server 与 plugin-host 不自签。
+- SEA:darwin / win target 的 seed 含 `native/ax_native.node` 与 sharp;linux 不含 `computer-use`;addon 架构不符时构建失败。
+- Windows:在真实 Windows 上用 node_repl MCP 的 `js` 工具调用 `list_apps` / `get_app_state` / 点击(预览 VM 访问不到模型接口,所以不经模型)。**尚未完成。**
+- 端到端:终端运行 `zcode`(源码与 SEA 二进制各一次),让模型调 `list_apps` / `get_app_state`。

+ 24 - 7
apps/zcode-cli/docs/design/v2/hooks.md

@@ -52,10 +52,25 @@ Hooks 的目标不是把业务逻辑散落到用户脚本里,而是在 agent l
 | `UserPromptSubmit`   | 用户输入进入 turn 前                                              | 是                 | 可追加 context,不改原始用户文本  | 是,受预算限制                                      |
 | `PreToolUse`         | tool input schema 校验后、permission check 前                     | 是                 | 可替换完整 tool input             | 可追加 context,批次后附件                          |
 | `PermissionRequest`  | permission service 返回 ask、broker UI 前                         | 是                 | 可允许、拒绝或替换完整 input      | 否,除拒绝原因                                      |
-| `PostToolUse`        | tool 成功后、结果序列化给模型前                                   | 否                 | 可追加 context;P1 再支持替换输出 | 是,批次后附件;Hook stdin 获得完整 `tool_response` |
-| `PostToolUseFailure` | tool 失败后、错误返回模型前                                       | 否                 | 可追加 recovery context           | 是,批次后附件                                      |
+| `PostToolUse`        | tool 成功且结果不是错误时,结果返回模型前                         | 否                 | 可追加 context;P1 再支持替换输出 | 是,批次后附件;Hook stdin 获得完整 `tool_response` |
+| `PostToolUseFailure` | tool 失败后(见下文「失败的定义」),错误返回模型前               | 否                 | 可追加 recovery context           | 是,批次后附件                                      |
 | `Stop`               | turn 即将 complete 前                                             | 是,可要求继续一轮 | 可追加 feedback context           | 是                                                  |
 
+### 失败的定义
+
+每次工具调用一般只运行 `PostToolUse` 和 `PostToolUseFailure` 中的一个(例外见本节最后一条)。以下两种情况算失败,运行 `PostToolUseFailure`:
+
+- 执行抛错:handler 抛错、超时、取消,handler 返回 `{ result: false }`,以及序列化抛错。
+- handler 正常返回,但结果是错误结果。判定函数是 `isToolOutputError(toolName, output)`(`core/src/tool/executor/errors.ts`)。tool_result 的 `is_error` 也用这个函数,两处不会不一致:
+  - 输出带布尔 `isError` / `is_error` 时,按这个值。MCP 返回 `isError: true` 属于这一类。
+  - Bash 按命令语义判定:非零退出算失败,但语义上的非错误退出不算(例如 grep、rg 退出 1 表示 “No matches found”)。硬超时和被取消(`interrupted: true`)也算失败。
+  - 其他输出不算失败。
+- 执行前就返回的结果两种事件都不运行:PreToolUse 拒绝、权限拒绝、输入校验失败(含 Hook 改写后的输入)。这些结果的 `is_error` 仍是 true,mailbox 也不在这里投递。
+- 第二种情况的 Hook 输入:`error.message` 是模型看到的 tool_result 正文(例如 `Exit code 1\nls: …`),`error.type` 是 `tool_execution_failed`,`isInterrupt` 是 `false`。输入里没有 `toolResponse`;需要结构化输出的 Hook 改读 `error.message`。
+- 工具结果的字节、`is_error`、UI 和事件都不变;只有 Hook 事件和附件标题(`PostToolUseFailure:<ToolName> hook additional context: …`)改变。
+- 内置 session mailbox(`ZCODE_MESSAGE_ENABLED=1`)同时注册 `PostToolUse` 和 `PostToolUseFailure`,两者都把邮件作为 guide 排队。错误结果和执行抛错之后也照常投递,不用等下一次成功的调用或 `Stop`。
+- 例外:Hook 运行之后的步骤抛错时(例如写结果事件、登记后台任务、官方 CUA 帧校验),catch 路径会再运行一次 `PostToolUseFailure`。这时同一次调用先运行一次 `PostToolUse` 或 `PostToolUseFailure`,再运行一次 `PostToolUseFailure`;模型只看到 catch 路径的 Hook 附件。这种情况很少,现在不处理。
+
 实现状态:
 
 - contract/config schema/runner 只声明并支持:`SessionStart`、`UserPromptSubmit`、`PreToolUse`、`PermissionRequest`、`PostToolUse`、`PostToolUseFailure`、`Stop`。
@@ -103,7 +118,7 @@ P1 再考虑:
 配置原则:
 
 - `events.<event>[]` 是 matcher 列表,顺序稳定。
-- `matcher` 是正则字符串。tool 类事件匹配 tool name。
+- `matcher` 是正则字符串。省略字段或传空字符串都表示匹配当前事件的所有触发。非空字符串按原样匹配,tool 类事件匹配 tool name。
 - P0 持久化配置支持 `process` 和 `command` 两类 hook;in-memory `callback` 只作为 core/SDK 注入能力,不写入配置。
 - `process` 必须使用 `command + args[]`,通过 adapter 的 spawn/execFile 语义执行,不默认 shell 拼接。
 - `command` 使用显式 shell execution mode,主要兼容 Claude Marketplace;Windows shell/path fallback 由 ExecutionPort 负责。
@@ -130,7 +145,7 @@ P1 再考虑:
 - `PreToolUse`:`toolCallId`、`toolName`、`toolInput`、`riskLevel`、`sideEffectScope`
 - `PermissionRequest`:`requestId`、`toolCallId`、`toolName`、`toolInput`、`reason`、`riskLevel`、`sideEffectScope`
 - `PostToolUse`:`toolCallId`、`toolName`、`toolInput`、完整 `toolResponse`、`toolResultPreview`、`artifactRefs`
-- `PostToolUseFailure`:`toolCallId`、`toolName`、`toolInput`、`error`、`isInterrupt`
+- `PostToolUseFailure`:`toolCallId`、`toolName`、`toolInput`、`error`(`{ message, type }`;stdin 兼容字段 `error` 是 message 字符串)、`isInterrupt`。没有 `toolResponse`,见「失败的定义」
 - `UserPromptSubmit`:`prompt`、`attachmentsSummary`
 - `SessionStart`:`source`
 - `Stop`:`responsePreview`、`toolCallCount`
@@ -162,7 +177,8 @@ P0 使用一个统一 JSON 输出:
 - `PreToolUse`
   - `permissionDecision`: `allow | ask | deny`
   - `permissionDecisionReason`
-  - `updatedInput`: 完整替代 input,必须重新经过 tool input schema 校验。
+  - `updatedInput`: 完整替代 input,必须重新经过 tool input schema 校验。模型原始输入要先通过 JSON Schema 与
+    runtime schema 才会运行 PreToolUse,所以 hook 不能修正不合格的原始输入(根目录 `docs/model-tool-call-validation.md`)。
   - `additionalContext`
 - `PermissionRequest`
   - `decision.behavior`: `allow | deny`
@@ -211,7 +227,7 @@ Tool 执行路径:
    broker 应答先到则收口并 abort hook 链。hook 无决定或失败按退赛处理,只剩 broker
    单边等待。hook 决定不再保证先于用户应答;需要用户不可越过的强制拒绝用
    `PreToolUse` deny 或 permission deny rule 表达。
-9. tool 成功后运行 `PostToolUse`,失败后运行 `PostToolUseFailure`。
+9. tool 成功且结果不是错误时运行 `PostToolUse`;失败时(见「失败的定义」)运行 `PostToolUseFailure`。两者一般只运行一个,例外见「失败的定义」。
 
 聚合规则:
 
@@ -454,7 +470,8 @@ Phase 5:
 
 - process hook stdin 收到结构化 JSON。
 - stdout 合法 JSON 被解析;非 JSON stdout 仅记录 diagnostic,不使 hook 失败。
-- stderr 不进入模型上下文。
+- stderr 只在 Hook 阻断(退出码 2)或 `onError: deny` 的失败拒绝工具时作为理由进入模型上下文,文字见根目录
+  `docs/hooks-runtime-contract.md`;其他情况只记诊断。
 - timeout 杀掉子进程并记录 `hook_timeout`。
 - Windows 路径、`.cmd`、空格路径至少通过 adapter 单元测试模拟。
 

+ 11 - 0
apps/zcode-cli/docs/design/v2/logging.md

@@ -197,3 +197,14 @@ ZCode app-server `session/new` 至少记录:
 - ZCode app-server `session/new` 日志覆盖 validate/config/create app/register/notify commands/total 阶段,每条阶段日志包含非负 `durationMs` 和同一个 `traceId/sessionId`。
 - 日志文件名使用本地日历日,`2026-05-05 02:46 +0800` 必须写入 `zcode-2026-05-05.jsonl`,不能因为 UTC 仍是 `2026-05-04` 而落到前一天文件。
 - 启动完成后调度日志保留清理,默认延迟 60 秒,最多保留最近 7 个本地日历日的 `zcode-YYYY-MM-DD.jsonl`,且清理失败不影响 CLI/TUI/ZCode app-server 主流程。
+
+## Message 首响归属事实
+
+TurnStarted 可附带 `isFirstMessage`:从当前 `queueItemId`(无 intent 时用 inputId)
+对应的持久 session_input 读取,接纳序号从 0 开始,取消或出队不重置。首条接纳且
+运行 turnNumber 为 0 才确认为首条;旧会话缺乏完整接纳历史时省略,不影响执行。
+V4 保持原有 turn.started 字段集合,另发独立 turn.admission 通知携带该标识和
+原始 intent.admittedDelivery 映射;guide 保留未知 sendMode。模型请求 usage 复用
+model.request.metrics,保留缺失/0 与 cacheTokens 回退,不改 usage.delta 的 strict 格式。
+消费端与六个 completion 属性的完整语义见
+[会话遥测规格](../../../../../docs/monitoring/conversation-telemetry-v4.md#message-首响归属2026-11-10)。

+ 173 - 33
apps/zcode-cli/docs/design/v2/loop/meta-user-context.md

@@ -3,9 +3,21 @@
 ## Silent-turn reminder
 
 Main-session continuation requests check accepted history for a stretch without
-user-visible communication. Five silent assistant responses since the latest
-reminder trigger `silent_turn_reminder`; each stretch permits at most three
-reminders. A response counts once regardless of its tool-call count. Reasoning-only
+user-visible communication. The reminder `silent_turn_reminder` fires when both
+are true at collection time:
+
+- At least one silent assistant response follows the latest reminder in the
+  stretch (or the stretch start when there is no reminder).
+- At least 60 seconds have passed since the anchor:
+  `now - anchor.time >= 60000` (milliseconds). The anchor is the newest of the
+  latest reminder in the stretch and the entry that started the stretch (the
+  communicating response or the user turn). The scan stops at the anchor.
+
+There is no per-stretch cap: while the model stays silent, the reminder repeats
+every 60 seconds or more, each time after at least one more silent response.
+All models use the same rule, without model-specific flags.
+
+A response counts once regardless of its tool-call count. Reasoning-only
 responses count as silent. Whitespace, `(no content)` and `No response requested.`
 do not count as communication. Visible assistant text, AskUserQuestion or
 ExitPlanMode calls, and a new user turn end the stretch. A user turn is an
@@ -15,22 +27,59 @@ counts the turns of the plan reminder cadence). Tool results, output-token
 recovery prompts, synthetic context and mid-turn inputs do not: a `user_steer` (including a
 running "send now", which ZCode presents as a steer) or another `*_steer`
 message continues the stretch, because mid-turn input is delivered as an
-attachment. Subagent requests, the first request of a new turn, and
-output-token recovery do not collect this reminder. The main-session default
-uses these fixed thresholds for all supported models, without model-specific flags.
-
-The runtime derives cadence only from canonical history. It persists the raw body
-as a hidden runtime reminder (see "New dynamic entries" below) with
-`runtimeMessage.source = silent_turn_reminder`, then commits the attachment.
-Resume restores the same marker; compact/rewind use remaining history. There is
-no timer or second counter. Persistence failures propagate before publication.
+attachment. These entries also do not move the anchor. Subagent requests, the
+first request of a new turn, and output-token recovery do not collect this reminder.
+
+Time spent waiting for the user counts as silent time. A response enters
+history before its tools run, so an AskUserQuestion or ExitPlanMode anchor has
+the time of the question, not of the answer: the answer is a tool result and does
+not move the anchor. Waiting for a permission decision also counts. Example: the
+user answers a question after 2 minutes, the model makes one silent call, and the
+next request carries the reminder.
+
+Entry time: every history entry carries `time` (epoch milliseconds, not sent to
+the provider). Live entries get the runtime clock when they enter history
+(`MessageHistory` add methods and `commitTurnRequestEntries`). A guide drained
+mid-turn gets its time before it goes into history, and the current request
+uses the same timed entry: a guide without a steer presentation is a user turn
+and can be the anchor. Hidden runtime reminder rows written through
+`persistRuntimeReminderMessage` (dynamic announcements including this reminder,
+hook context, interrupt markers, `Continue`) and compaction records (leading
+announcements, summary, post-compact attachments) are written with the entry
+time as `time.created`, so resume restores exactly the live value. Model-only
+notices written through `persistSyntheticUserNoticeForSession` (`todo_reminder`,
+`plugin_reference`, `agent_listing_delta`) take their row time separately, like
+user prompts; they are attachments and never anchor this reminder. Resume restores
+`time` from the persisted rows: assistant entries use `time.completed`, falling
+back to `time.created`; other entries use `time.created`. For user prompts and
+text-only responses the row time and the live time are taken separately and can
+differ by a few milliseconds. A response with tool calls differs more: live time
+is taken before its tools run, and `time.completed` is written after its tool
+batch settles, so the restored time is later by the tool batch duration
+(including any wait for the user). This matters only when such a response is the
+anchor and the stretch continues across a cold resume without a new user turn
+(for example a goal continuation). Sent bytes do not change, because the
+decision is made at collection time and persisted. This known difference is
+kept for now; the options are in
+[issue: tool-call response time after cold resume](../../../../../../docs/issues/silent-reminder-entry-time/01-tool-call-response-time-after-cold-resume.md).
+Entries without `time` (built
+outside the runtime) never anchor a reminder: if the anchor has no time, the
+reminder does not fire.
+
+The runtime derives the decision only from canonical history and the clock at
+collection time. It persists the raw body as a hidden runtime reminder (see
+"New dynamic entries" below) with `runtimeMessage.source = silent_turn_reminder`,
+then commits the attachment. Resume restores the same marker and its time;
+compact/rewind use remaining history. There is no timer: nothing runs between
+collections. Persistence failures propagate before publication.
 With MCS the notice projects as a mid-conversation system message;
 without MCS it is a user-side `<system-reminder>`. Source metadata and the notice stay hidden from the App
 transcript; desktop/mobile delivery contracts do not change.
 
 ```text
-accepted history -> continuation collector -> persist notice -> commit attachment
-                  -> provider reminder (MCS system / user) -> next model response
+accepted history (entries with time) + clock -> continuation collector
+  -> persist notice (time.created = collection time) -> commit attachment
+  -> provider reminder (MCS system / user) -> next model response
 ```
 
 ## Todo reminder cadence and formatting
@@ -49,8 +98,54 @@ both MCS and user-side reminder delivery.
 
 ## Total-tokens reminder
 
+The reminder is off by default. Each runtime reads one value,
+`AgentRuntimeConfig.totalTokensReminder.enabled` (missing means off), when it
+is created, and keeps it until the runtime is released. Changing the source
+later does not change a running session, not even its next turn. The value
+comes from:
+
+- CLI `--total-tokens-reminder on|off` for `--prompt`, `--target` and the TUI
+  (default `off`). It applies to this launch only and is not saved: a later
+  `--resume` without the flag runs with the reminder off. `app-server` rejects
+  the flag.
+- In the App, the Host setting `totalTokensReminderEnabled` (default `false`),
+  a switch in Settings → Agent capabilities → Behavior and tools on desktop and
+  mobile. Its description says it applies to new sessions and to sessions
+  resumed after a restart.
+  The CLI reads it with `session/requestRuntimePreferences`
+  (`runtime-materialization`) when it creates a session runtime or resumes one
+  that is not in memory, the same way as `toolSearchMode`. A runtime that is
+  still in memory keeps its value. A draft session that the App created before
+  the setting changed keeps the old value.
+- Fork and side chats copy the value of their parent record. Subagents and
+  workflow children inherit the value of their parent runtime.
+
+There is no environment variable. When the value is off:
+
+- The main session, subagent and workflow systems do not get the budget line.
+- Input attachment collection does not add `total_tokens_reminder`. The
+  counter below produces no text.
+- Reminders that an existing session already stored replay unchanged in their
+  original position. They are not filtered, because that would change bytes
+  that were already sent.
+
+The prompt snapshot keeps the main-session system bytes that were sent, so the
+static prefix does not change when the value changes between runs (see
+[Prompt snapshot](prompt-snapshot.md)). Until the session's next successful
+compaction or session model change:
+
+- Turned off: a session whose snapshot has the budget line keeps it. The model
+  still sees the fixed `15000000` line, without a countdown.
+- Turned on: a session whose snapshot has no budget line does not get one, but
+  the countdown reminders below are collected.
+
+After that point the system follows the current value. Subagent and workflow
+systems are not snapshotted, so they always follow their runtime's value.
+
+The rest of this section describes the behavior when the value is on.
+
 The model sees a token budget in two places. The budget is fixed at 15000000;
-there are no modes and no configuration. It applies to every provider and model.
+only the on/off value above is configurable. It applies to every provider and model.
 
 1. The system prompt ends with the line
    `<total_tokens>15000000 tokens left</total_tokens>`. See
@@ -154,6 +249,7 @@ instruction files + Memory index -> context_prefix -> user reminder
 Git snapshot                     -> session_context -> user reminder
 current environment              -> environment    -> MCS or user reminder
 executing Model                  -> model          -> MCS or user reminder
+Host reply language              -> language       -> MCS or user reminder
 current date                     -> date           -> MCS or user reminder
 skill catalog                    -> skills_listing -> MCS or user reminder
 ```
@@ -319,11 +415,11 @@ loop iteration (one model request)
   drain mid-turn steers                      (human guides first, then notifications and agent
                                               messages; only with new input: after a tool batch
                                               or a text-only guide drain)
-  input attachments   environment -> model -> output_style_instructions
+  input attachments   environment -> model -> output_style_instructions -> language
                       -> tool_search_announcement
                       -> agent_listing_delta -> skills_listing -> plan_mode_exit
                       -> runtime_mode -> todo_reminder
-                      -> silent_turn_reminder -> total_tokens_reminder
+                      -> silent_turn_reminder -> total_tokens_reminder (off by default)
                       -> output_style -> memory_update
                       -> hook_context (UserPromptSubmit, first collection of the turn only)
   settled project-memory recall              (memory prefetch after attachments)
@@ -356,6 +452,25 @@ the style is cleared and the latest entry is a style, the reset text
 announced once. Compaction restates the latest entry after environment and
 model when the kept tail has none; a reset is not restated. Only the identity
 line of the system prompt still depends on whether a style is active.
+`language` carries the reply language, which is not in the system prompt. On
+each collection for the main thread the runtime reads the Host's reply
+language setting through the injected `readReplyLanguage` port
+(`session/readReplyLanguage`, sent concurrently with the environment read); it
+is announced under the same gate as environment and model. The body is
+`# Language` followed by `Always respond in <Language>. …` and an orthography
+line, where `<Language>` is the user's free-text setting with `&`, `<`, `>` and
+control characters escaped as entities (quotes are kept), so the value cannot
+break the reminder tag or add lines. It is announced when it differs from the
+latest `language` entry in history. When the Host answers that nothing is set
+(`null`) and the latest entry is a language, the clear text
+`The language preference was cleared. Match the user's language.` is
+announced once. A failed read (timeout, disconnect, cancel, invalid result) is
+skipped and does not reset an earlier announcement, so a passing failure does
+not make the value flap; there is no port (and no read) in TUI and headless.
+Compaction restates the latest entry after `output_style_instructions` when
+the kept tail has none; a clear text is not restated. Context composition
+preview does not read the setting. See
+[Agent Reply Language](../../../../../../docs/i18n/agent-reply-language.md).
 `read_truncation_notice` is not an input attachment: the tool batch writes it
 right after its tool results when a Read returns a partial view, also when Stop
 interrupts the batch's file checkpoint (before the interrupt marker).
@@ -409,8 +524,10 @@ Mid-turn inputs are attachments and fold too, so without MCS a steer sits in
 the tool result it arrived with. With MCS, a text-only steer goes into the
 run's system message like the other mid-turn inputs. Real or presented user
 inputs, reminders with non-text blocks (a steer with media too, with or
-without MCS), and the MCS fallback reminder do not fold; a result that holds `tool_reference` blocks does not take
-reminders. A tool batch followed by a native ToolSearch `Tool loaded.` notice takes no
+without MCS), the MCS fallback reminder, and the compaction file-restore
+bodies (`resume_referenced_session_context`, always user-side) do not fold; a result that holds `tool_reference` blocks does not take
+reminders. File-restore bodies also take the user-input newline rule: the user
+text right before one ends with one newline (see `rewind-compact.md`). A tool batch followed by a native ToolSearch `Tool loaded.` notice takes no
 reminders either: the notice is inserted before the fold, so the reminders follow it.
 A folded steer is no longer the latest real user message for the
 media budget. Token estimation and microcompact project without the fold.
@@ -454,6 +571,26 @@ and a removed one adds ` - Visualization directory for this session: none (was <
 A changed shell adds ` - Shell: <new> (was <old>)`; when the previous shell is
 empty (older Windows sessions), it adds ` - Shell: <new>`.
 Order is cwd, repository, directories, the visualization directory, then the shell.
+When the shell is `cmd.exe` (`WINDOWS_CMD_SHELL_DISPLAY_NAME`, the display name of
+every `dialect=cmd` selection), the Shell bullet carries the CMD rule in its
+parentheses, in full blocks and in updates alike:
+`Bash tool commands are parsed by cmd.exe. Do not use Unix commands such as ls, cat, head, tail, grep, or wc; prefer the dedicated file tools for listing directories and reading files, and use dir, type, or findstr when you need a shell command.`
+A full block writes ` - Shell: cmd.exe (<rule>)`. An update that changes the
+shell to `cmd.exe` writes ` - Shell: cmd.exe (was <old>; <rule>)`, or
+` - Shell: cmd.exe (<rule>)` when the previous shell is empty. Older sessions
+announced `system shell` or `CMD`, so they get it on their next cold resume.
+Every other shell change is only ` - Shell: <new> (was <old>)`, also when leaving
+`cmd.exe`. A full block re-sent while leaving `cmd.exe` (platform/OS change, or no
+full block left after compaction) writes ` - Shell: <new> (was cmd.exe)`, so the
+change is visible next to the earlier rule. No other part of the notice
+changes. Reason: the Bash tool name, its description and the old
+`Shell: system shell` all said bash while cmd.exe ran the commands; in frozen
+replays of real Windows sessions 36–42% of next steps used Unix commands that
+cmd.exe cannot run. The rule is the English translation of the Chinese text
+validated in that experiment (1.3% / 0.3% on the held-out set), where it stood as
+its own paragraph before the `# Environment` heading. The English wording and
+the placement inside the Shell bullet are product decisions and were not part of
+the experiment.
 The ZCode Desktop part is compared by its form: none, with a Gen UI directory,
 or without one; older metadata has no `desktopContext` and counts as none. A
 changed form is added after the bullets, with a blank line between: the whole
@@ -469,18 +606,21 @@ legacy snapshot metadata, or a history with only updates after compaction,
 also requires a full block. Unchanged snapshots emit nothing. Snapshot
 metadata is cloned and validated on restoration and never sent to providers.
 Model changes append the current identity.
-The Skill listing is announced once, when history has no `skills_listing`
-entry and the catalog is not empty; compaction makes the same check against
-the kept tail and places the listing after the agent listing. A change is
-never announced as a new entry. Skills are discovered only when a runtime
-starts, so the catalog can change only between runtimes. Each time history is
-loaded from the store (cold resume, rewind), the restored `skills_listing`
-entries are updated in place to the current catalog: changed content replaces
-the old content at the same position, and an empty catalog removes them. The
-update is in memory only. The stored record keeps its first content and fixes
-only the position, and every load applies the update again. A changed catalog
-therefore changes earlier request bytes once (one prompt-cache miss); an
-unchanged catalog changes nothing. There is no per-skill delta.
+The Skill listing is a delta. Each line has a fingerprint (a short sha256 of
+the full line). The collector replays the fingerprints stored in the
+`skillsListingDelta` metadata of earlier `skills_listing` entries and appends
+one entry with the lines whose fingerprint is not announced yet, under the same
+heading. A new or changed skill adds a line; a removed skill is not announced.
+The collector is the only renderer of the listing; ContextBuilder no longer
+renders a Skills section. No listing is sent when the tool table has no
+`Skill` (main session and subagent alike).
+The first listing of a new session is byte-identical to the old full listing.
+Compaction makes the same check against the kept tail and places the entry
+after the agent listing. The catalog is the in-memory snapshot of the live skill
+catalog, read at each normal input preparation (no file IO in the step). A
+history load (cold resume, rewind) never rewrites restored entries; legacy
+entries without metadata count as not announced, so one full listing is
+appended. Rules: root `docs/skills-live-catalog.md`.
 `context_prefix` is never rewritten after it is sent. Changes are announced by
 appending a new `context_prefix` entry (an instruction delta), so the request
 prefix stays byte-stable across cold resume, rewind and later requests.
@@ -644,7 +784,7 @@ files remain separate future features.
 Tests cover initial placement and order with and without MCS, the newline
 before a real user input, MCS downgrade, consecutive
 requests, executing model changes, date rollover, cross-day compact, resume,
-Skill listing restated by compaction, updated in place after a history load
-(removed for an empty catalog) and not repeated for an unchanged catalog, `context_prefix` kept byte-stable after a history load with an appended delta for a changed, new or removed instruction file or Memory index (none for unchanged files, none again on a second cold resume, legacy records without metadata), the compaction re-read (delta with a kept baseline, full block without one, Memory read state after compaction), read errors (an unreadable instruction file or Memory index not announced as removed on resume; a compaction re-read dropped when a held file is unreadable and adopted when the unreadable file is not held; adapter: an unreadable file reported as a read failure, a missing one as nothing, no fallback to a parent file when the check fails), Git reuse by history, Git read after a non-repository start or a non-repository compaction, one file system check per non-repository directory (including a non-repository prefetch), a repository with a hung or missing git still detected, parallel snapshot commands, prefetch only for a new session, custom/subagent
+Skill listing delta (only new or changed lines, nothing for a removed skill,
+restated by compaction, not rewritten after a history load, one full listing for legacy records), `context_prefix` kept byte-stable after a history load with an appended delta for a changed, new or removed instruction file or Memory index (none for unchanged files, none again on a second cold resume, legacy records without metadata), the compaction re-read (delta with a kept baseline, full block without one, Memory read state after compaction), read errors (an unreadable instruction file or Memory index not announced as removed on resume; a compaction re-read dropped when a held file is unreadable and adopted when the unreadable file is not held; adapter: an unreadable file reported as a read failure, a missing one as nothing, no fallback to a parent file when the check fails), Git reuse by history, Git read after a non-repository start or a non-repository compaction, one file system check per non-repository directory (including a non-repository prefetch), a repository with a hung or missing git still detected, parallel snapshot commands, prefetch only for a new session, custom/subagent
 boundaries, and truncation at both limits. Prompt changes do not alter App input
 or tool execution UI.

+ 7 - 1
apps/zcode-cli/docs/design/v2/loop/prompt-snapshot.md

@@ -89,7 +89,13 @@ build result. A record captures the leading system messages of the request that
 A system section added by a later CLI version (for example the token budget line, see
 `system-prompt-contract.md`) reaches an existing session only after its next successful compaction
 or session model change. Until then the session keeps its recorded system bytes; reminders that the
-new version adds to the history are appended and do not change the sent prefix.
+new version adds to the history are appended and do not change the sent prefix. A session without a
+recorded snapshot is the exception: its next request records the current system. A system section
+that a later CLI version removes follows the same rule. The same rule covers the total-tokens reminder
+value, which can change between runs (CLI flag or App setting): when it is off, a snapshot that
+recorded the budget line keeps it; when it is on, a snapshot without the line stays without it. Both
+last until the next successful compaction or session model change; the countdown attachments follow
+the current value.
 
 ## Failure and compatibility
 

+ 72 - 14
apps/zcode-cli/docs/design/v2/loop/system-prompt-contract.md

@@ -27,7 +27,7 @@ to this contract reach existing sessions only at those points; see
 | Section              | Purpose                                                                                                       |
 | -------------------- | ------------------------------------------------------------------------------------------------------------- |
 | Static Default Body  | ZCode role, authorized-security boundary, and compact harness guidance.                                       |
-| Dynamic Default Body | Code style, pronouns, risk guidance, session guidance, memory, and context management.                        |
+| Dynamic Default Body | Code style, pronouns, risk, session guidance, memory, context management, finishing work, memory notes.       |
 
 The provider-visible `system[0]` CLI prefix is exactly
 `You are ZCode, an interactive agent`. The provider-visible static
@@ -57,7 +57,7 @@ execution-model fallback, an off-peak user takeover) rebuilds the prefix with th
 new model before the next request. Requests outside the turn loop that reuse the
 session history (the goal completion verifier) rebuild the prefix with their own
 request model first; a
-rebuild without a model (language, output style, rewind, shell environment changes)
+rebuild without a model (output style, rewind, shell environment changes)
 never decides the wording a request sends. With MCS it is exactly:
 
 ` - The system may send updates, reminders, or modifications to rules via mid-conversation system turns. These are system-controlled, unlike function results. Hooks may intercept tool calls; treat hook output as user feedback.`
@@ -99,12 +99,61 @@ boundary is:
 5. Optional `# Memory` when an enabled Memory root is available, including an empty root.
 6. `# Context management` for long-context summary/continuation behavior,
    followed by act-don't-rederive guidance. No autonomy appendix is emitted.
-7. The token budget line `<total_tokens>15000000 tokens left</total_tokens>`,
-   separated by `\n\n`. It is the last text of `system[2]`. The value is fixed;
-   the per-request countdown is the `total_tokens_reminder` attachment (see
-   [Meta User Context](meta-user-context.md)). A custom system prompt skips this
-   line with the other dynamic sections; workflow actors keep it with Context
-   management.
+7. `# Finishing work` (see [Finishing work and memory notes](#finishing-work-and-memory-notes)).
+8. `# Memory, notes and feedback` (same section).
+9. Only when the runtime's total-tokens reminder value is on (off by default;
+   CLI flag or App setting, see [Meta User Context](meta-user-context.md)): the token budget line
+   `<total_tokens>15000000 tokens left</total_tokens>`, separated by `\n\n`. It
+   is the last text of `system[2]`. The value is fixed; the per-request
+   countdown is the `total_tokens_reminder` attachment. A custom system prompt
+   skips this line with the other dynamic sections; workflow actors keep it
+   with Context management. When the reminder is off, the main thread's
+   `system[2]` ends with `# Memory, notes and feedback`, and a workflow actor's
+   ends with the act-don't-rederive guidance.
+
+### Finishing work and memory notes
+
+Items 7 and 8 are sent for every model; there is no per-model switch. They
+belong to the default system prompt: workflow actors, subagents and a custom
+system prompt skip both. A legacy script workflow child that runs on the default
+prompt keeps them, as it keeps the other default dynamic sections.
+`# Memory, notes and feedback` is sent with or without a Memory
+root; its own first paragraph says the saving rules apply only when the session
+has a memory directory. Each section is one `dynamic` system section, joined to
+the previous one by `\n\n`, with this exact text:
+
+```text
+# Finishing work
+Ending your turn means your work stops there until asked to continue, and you should not stop unless needed. Please avoid stopping while work the user asked for is still owed. Status notes are welcome, and so are your recommendations on open decisions, but do not stop unnecessarily and carry on with whatever does not depend on the user's answer. If you notice yourself inviting the user to redirect you or offering to wait, instead proceed on the next part of the task. You may meet ordinary obstacles like errors, timeouts, locked files, empty results or failing tools. Diagnose them first, and when they are not real blockers, work through them with the access you have (wait and retry, fix the request, use another tool or source) rather than stopping or checking in. If someone clearly decided something is a hard blocker, such as a file marked not to be touched, access that was intentionally withheld, or a safety guardrail, leave it alone, say plainly what you found, and look for another way to finish the task. Stopping before the task is complete can rarely be merited, i.e. when the task can't move forward without user input, or where the blocker is deliberate and should not be worked past. This does not override the need for confirmation on risky or destructive actions.
+```
+
+```text
+# Memory, notes and feedback
+This adds to the Memory section and takes precedence over it. The rules about saving apply only if this session has a directory for saving memories.
+
+Save only what is applicable and durable:
+applicable: it would directly change your behavior in future sessions, such as an approach the user corrected or steered you away from, or a standing preference they expressed. Not ambient code context or state.
+durable: it applies to multiple future sessions and tasks, not just this one. Not transient task plans or status. If you are uncertain whether something is durable, assume it is not and do not save it.
+
+Avoid saving an unnecessary record of completed work (commits, merges, review outcomes, status summaries). Pointers to external resources and environment facts the user would otherwise have to restate are still worth saving.
+
+Don't overindex on soft feedback - give it the appropriate weight based on the context, and if you can't tell whether it's an instruction or just a comment, ask once but carry on. When saving feedback, record the specifics (what, who, when, why, scope) and label your own interpretations as yours.
+
+Same for your notes - if they contain some caution or limitation, question whether the reason still holds and drop it if not. This isn't a reason to take risky, irreversible, destructive actions without confirmation though, and an old or general go-ahead doesn't count as confirmation, so if the caution is about these kinds of actions then keep it until a human gives confirmation (even if you wrote it yourself).
+
+Don't create planning, decision, or analysis documents unless the user asks for them — work from the context, not intermediate files.
+```
+
+Not added: a paragraph telling the model that Edit works without a prior Read. ZCode's
+Edit and Write still require a full Read first, so that advice would make the next
+Edit fail.
+
+Cache: a main session sends its recorded prompt snapshot ([Prompt Snapshot](prompt-snapshot.md)),
+so an existing session gets the two sections only after its next successful
+compaction or session model change. New sessions get them from the first request.
+An existing session that has no recorded snapshot (it was created before snapshots
+existed, or its snapshot could not be read) records the current system on its next
+request, so it gets them then.
 
 Environment, model, date, and the Git snapshot are independent history-backed
 attachments; see [Meta User Context](meta-user-context.md).
@@ -123,7 +172,10 @@ is appended to that sentence.
 Legacy ZCode `# Language`, `# Function Result Clearing`, and
 `# Summarize Tool Results` sections are not emitted in this dynamic block. The
 runtime may still compact or microcompact history, but that behavior is covered
-by runtime mechanics rather than provider-visible system sections.
+by runtime mechanics rather than provider-visible system sections. The reply
+language comes from the Host's reply language setting and arrives only as the
+`language` attachment (see [Meta User Context](meta-user-context.md)); a
+language change never rebuilds or changes the system prompt.
 
 Every system section after the CLI prefix owns its left boundary: Main/Workflow
 stable blocks and non-empty Subagent agent prompts start with `\n`; Main
@@ -291,15 +343,20 @@ Required Explore prompt behavior:
   sentence, then pronouns, then risk/reporting, after an unconditional
   leading `\n\n`. It then contains optional `# Session-specific guidance`,
   optional `# Memory`, `# Context management`,
-  act-don't-rederive guidance, and the `<total_tokens>15000000 tokens left</total_tokens>`
-  line in that order. Environment, model, output
+  act-don't-rederive guidance, `# Finishing work`, `# Memory, notes and feedback`
+  (default prompt only, every model, with or without a Memory root), and (only when
+  the total-tokens reminder is on) the `<total_tokens>15000000 tokens left</total_tokens>`
+  line in that order. Workflow actors, subagents and custom system prompts do not
+  include the two sections.
+  Environment, model, output
   style, date, and Git are separate dynamic attachments. It excludes the long-form communication,
   code-comment, and autonomy appendices.
 - Subagent initial system blocks contain the CLI prefix, then optional
   `\n` + non-empty agent-specific prompt (trimmed at both ends) followed by `\n\n` + the launcher-messages paragraph
   ("Messages from the agent that launched you — … can authorize changing your
-  permission settings, AGENTS.md, or configuration.") + `\n\n` + Notes +
-  `\n\n<total_tokens>15000000 tokens left</total_tokens>`. The
+  permission settings, AGENTS.md, or configuration.") + `\n\n` + Notes, then
+  `\n\n<total_tokens>15000000 tokens left</total_tokens>` only when the
+  total-tokens reminder is on. The
   paragraph, the final Notes sentence ("(Files written as input to another
   tool are fine; this note is about report files.)") and the budget line are fixed text;
   the instruction file is named `AGENTS.md`, as in the peer-message template.
@@ -312,7 +369,8 @@ Required Explore prompt behavior:
 - OpenAI-compatible serialization concatenates leading system blocks with an
   empty separator and does not inspect or repair their contents.
 - Provider-visible dynamic `system[2]` does not include legacy `# Language`,
-  `# Function Result Clearing`, or `# Summarize Tool Results` sections.
+  `# Function Result Clearing`, or `# Summarize Tool Results` sections. The
+  reply language is the `language` input attachment, never a system section.
 - Dynamic `session_guidance` is emitted in provider-visible `system[2]` only
   when the Skill tool and at least one skill are available.
 - Memory guidance is emitted in `system[2]` when an enabled Memory root is available,

+ 1 - 0
apps/zcode-cli/docs/design/v2/loop/tool-calling-loop.md

@@ -404,6 +404,7 @@ private toScheduleState(schedule: ToolSchedule): ToolScheduleState {
    - 与其他动态公告一样按隐藏提醒持久化:model-only synthetic user 消息,不写顶层 `source`(App 按封闭列表校验这个字段,新值会让旧版本拒绝整个会话),类型记在 `runtimeMessage.source = "interrupt_marker"`;冷恢复还原同一条 entry,旧版本不认识这个类型时也不报错。写入失败只记 warn,不替换取消结果。
    - 冷恢复的轮次结果以标记为准:本轮有标记时按 cancelled 收口(已有持久化错误时仍显示该错误)。场景:最终文本已完整输出后再停止,assistant 记录是 `finish=stop`、没有 error;live 显示 cancelled,冷恢复也必须是 cancelled。
    - 工具取消结果的文字:被停止或被宿主故障中止的批次里,被取消的工具(`ToolCancelled`:未开始、执行中、等待权限)给模型的 tool_result 统一为 `The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed.`,`is_error: true`。只换 `modelContent`(冷恢复从 part metadata 重放);`error.message` 不变,工具卡片仍显示各工具自己的取消原因。停止前已完成的结果、超时等其他错误不变。send-now 抢占的取消结果不换。
+   - send-now 抢占时,前台等待中(child 运行中)的前台 Agent 转入后台,结果是成功的 `async_launched`,child 完成后经 task-notification 送回;启动阶段、收尾阶段(child 已完成、失败或闲置超时)、禁止后台的执行和已结束的任务照旧取消。其他工具照旧取消。规则见 [turn-steering 前台子代理转后台](turn-steering.md#前台子代理转后台2026-10-29)。
 
 ---
 

+ 46 - 0
apps/zcode-cli/docs/design/v2/loop/turn-steering.md

@@ -232,6 +232,18 @@ Mobile replayable ---+                                      |
 
 Canonical history 只保存原始载荷。所有新标记消息 live/hydration/clone/fork/rewind 使用同一解析,compact 保留段保留标记。human 的真实用户身份不随 system 投影改变;coordinator、peer、task notification 不更新 latest-real-user。Memory 读取原始用户内容。
 
+冷恢复的 model-only 轮边界也消费这个标记:`task_notification_steer`、`subagent_reply_steer` 是当前轮内的上下文,不生成 `TurnStarted`,其后 assistant 仍属于原 product turn。`task_notification`、`subagent_reply` 则保留独立唤醒轮。message metadata 优先于 part metadata;缺失或未知标记维持 legacy source/text 判据,不迁移历史。
+
+```text
+真实用户输入 → 当前轮 → 轮内通知(*_steer)→ 最终 assistant
+                 └──────── 同一个 productTurnId ────────┘
+持久化 → cold hydration → fork child → 再次 fork
+                 └──────── 保留相同轮边界 ──────────────┘
+空闲通知(非 *_steer)→ 独立 model-only turn
+```
+
+回归必须证明轮内通知不会拆开持久化的 fork anchor,连续 fork 保留最终回复与通知 metadata;真正的空闲唤醒仍独立,通知不获得真实用户的编辑权限。
+
 compact 已选中的最近组必须连同组内的 coordinator、peer、task notification 和已持久化 Attachment 一起恢复,不得因 synthetic/model-only/source 再次过滤。保留区间按 assistant-started groups 选取,统计数量不得用于反推区间;详细合同见 [最近保留段的持久化与冷恢复](../rewind-compact.md#最近保留段的持久化与冷恢复)。
 
 ### 运行中立即发送(2026-10-26)
@@ -258,6 +270,40 @@ Desktop continuous / Mobile replayable
 - 已存历史不迁移:旧版本给立即发送写下的 `user_steer` 标记照旧投影,已有会话的请求前缀不变。
 - 单测锁住"实际抢占后仍是普通输入";正式 running-send-now(M07a、M07m)与 modified-submit-delivery(M06k)用例校验 provider 请求中没有中途提示、工具结果后抢占时已发出的请求前缀不变,覆盖 MCS 开关。
 
+#### 前台子代理转后台(2026-10-29)
+
+立即发送抢占时,正在运行的前台 Agent 子代理不取消,转入后台继续运行。被抢占的轮次和新 turn 的输入形态都不变(仍是取消旧轮 + 普通用户消息开新轮,不是 guide)。
+
+原因(2026-10-29):用户在子代理运行中立即发送,只是要交付新指令,不是要放弃子代理的工作。之前的取消会丢掉子代理已做的工作。
+
+```text
+sendText(startNow) / sendQueuedNow
+  -> stopActiveForegroundExecution(preserve=true)
+       abort(InputPreemptionAbortReason)          Stop / 编辑重试 / 断连等:abort(普通原因),照旧取消
+  -> turn abort scope -> executor -> Agent handler -> subagent runner(原因逐层原样传递)
+  -> executor(前台等待中还有 runner)在同一次 abort 里调用 runner 注册的同一个判断函数:
+       child 还没就绪(写启动元数据、启动 child)       -> cancel:ToolCancelled,child 取消
+       前台等待中(child 运行中),能转后台             -> wait:runner 立即返回 async_launched
+       前台等待中,不能转后台(deny,或任务已结束)      -> cancel
+       前台等待已结束(child 完成、失败或闲置超时,runner 在收尾) -> cancel:和改前一样
+  -> 结算本批结果 -> TurnCancelled(preserve) -> 新 turn:普通用户消息
+  -> 转后台的子代理完成 -> <task-notification>(completed 或 failed)回到会话
+```
+
+- 停止原因是结构化值:`InputPreemptionAbortReason`(`kind: "input_preemption"`,message 仍是调用方给的 reason)。只有 `preserveQueueAutoDrainOnCancel: true` 的停止(立即发送)使用它。Stop、编辑重试、闲时停止、宿主断连、session 关闭仍用普通原因,子代理照旧取消。约定(2026-11-12):`preserveQueueAutoDrainOnCancel` 同时决定队列授权和停止原因,目前只有两个立即发送入口传它。以后若有调用方只想保留队列授权、不想让前台子代理转后台,要先把它拆成两个参数。
+- 判断只有一处:executor 为每次工具调用提供一个接管点。工具执行上下文的 `inputPreemption` 只暴露 `register`(`InputPreemptionControl`),调用判断函数只在 executor 内部:判断函数有副作用(能转后台时会转后台),handler 不能调用它。Agent handler 把它经 `SubagentRunOptions.inputPreemption` 传给 runner,runner 注册判断函数。这个停止原因到达时,executor 调用这个判断函数;前台等待中 runner 也在同一次 abort 里调用它,两次结果一致:返回 `wait`,executor 不判取消,等 handler 返回;返回 `cancel`,或没有注册判断函数(其他工具、没有传入接管点的调用方),照旧立即取消,取消文字不变。还没开始执行的工具(同批后续调度组)照旧不执行。
+- 判断规则:只有前台等待中(runner 在等 child 完成或转后台请求)才认领。
+  - 前台等待中:调用 `registry.requestBackground`,成功就转后台,runner 在几个微任务内返回 `async_launched`,不碰任何文件或事件写入。本次执行禁止后台(`modelOverride.background: "deny"`,目前没有生产入口设置它)或任务已结束(例如已被停止)时取消。闲时运行设置 `background: "allow"`,其中的前台 Agent 同样转后台:child 继续用闲时模型运行,算作这次闲时运行的后台工作,闲时运行等它结束才完成;立即发送的消息由用户接管,改用用户模型。
+  - 其余时候都取消,和改前一样:child 还没就绪(写启动元数据、启动 child);前台等待已结束(child 完成、失败或闲置超时,runner 在写结果文件和完成事件,通常几毫秒)。收尾中被取消时,Agent 卡片显示 child 的终态(完成或失败)、结果文件在磁盘上,模型拿到的是取消文字。
+  - 判断为 `cancel` 时,runner 把同一个 `InputPreemptionAbortReason` 原样用于取消 child。child 现在不注入 subagent port、没有 Agent 工具,这个原因在 child 里只按普通取消处理(2026-11-12)。以后 child 能启动 Agent 时,要先在 runner 把它换成普通原因:否则孙代理会转后台,不会随 child 一起取消。
+  - 原因(2026-10-29):认领后 executor 要等 handler 返回。只在前台等待中认领,这次等待只有几个微任务,executor 仍能及时取消,Stop 总能生效。曾尝试在收尾中也认领(等结果,或转后台):等结果时立即发送要等文件写入,磁盘慢时用户按 Stop 也打断不了;转后台时后台任务的开始和结束事件分别由 executor 和 runner 写,先后没有保证,后台面板会一直显示运行中。
+  - 前台等待不论从哪个出口结束(child 完成、child 失败、闲置超时、转后台请求、任务已结束或被移除),都先走同一段同步代码:关闭认领 → 读 registry → 选分支,中间没有 await。修复原因(2026-10-30):原来只有等待正常返回的出口这样做;child 失败或闲置超时让等待以异常结束,直接进入失败收尾,认领一直开着。失败收尾期间立即发送会被认领:executor 要等失败收尾写完才结束,模型拿到失败结果而不是取消文字,registry 却记为已转后台,也不发通知。
+- 前台等待中转后台和 child 完成或失败几乎同时发生时,以 registry 为准:registry 已标为后台就走后台分支,Agent 结果是 `async_launched`,结果经 task-notification 送回(completed 或 failed),不出现“已结束却标为后台”的状态。原因(2026-11-12 复核):闲时运行把“标为后台且未通知”的任务算作待送达通知,前台直接返回结果、不发通知时,闲时运行永远不结束。这时 runner 可能先收口并写了 `BackgroundTaskCompleted`,tracker 不再写 Started,规则见 [07-subagent 的 sync 转 background](../tool/07-subagent.md)。失败时按已经拿到的错误直接收尾,不再等 child:等待因闲置超时等 abort 结束时,child 可能永远不返回。
+- Agent 的 tool_result:转后台时是 `async_launched`,文字与 `run_in_background: true` 的启动结果相同。新 turn 的普通用户消息排在这批 tool_result 之后。被抢占的轮次不加中断标记。
+- PostToolUse hook 不改:用 turn 传入的 signal,立即发送后它已中止,hook 不执行、记为取消(HookRunFailed,outcome cancelled),拿不到 Agent 的结果,工具结果不变。这样立即发送不用等 hook 跑完;hook 可能要跑好几秒,会超过 Bootstrap 等旧轮结束的 5 秒(`IDLE_POLL_TIMEOUT_MS`)。
+- 等待审批的子代理同样转后台:审批请求属于 child 的工具调用,不随父轮结束关闭;V4 投影里这条审批在旧轮和新轮结束后都仍待处理,用户批准或拒绝后子代理继续。
+- 已存历史不变;只影响之后的抢占。
+
 ### 文案合同
 
 下列模板是唯一文案基准,独立黄金样本位于 `packages/core/tests/fixtures/runtime-input-presentation.json`。模板只替换 `{body}` 等占位,不改写载荷正文;标点、空格、换行及其余文字逐字一致。

+ 40 - 0
apps/zcode-cli/docs/design/v2/mcp-node-fallback.md

@@ -142,6 +142,38 @@ On POSIX only the exact key `PATH` is used.
 - The desktop dev chain runs `apps/zcode-cli/packages/cli/dist/zcode.cjs`, which has no staged npm.
   There the `node` shim works and the `npm`/`npx` shims exit 127 with the missing-variable message.
 
+## Windows npm Child Windows
+
+The MCP SDK hides its direct child on Windows. That option does not apply recursively. When
+fallback npx runs on Electron Node, npm's `@npmcli/run-script` starts another `cmd` without a
+window-hiding option. This chain can create a visible blank console while the MCP server connects
+successfully.
+
+```text
+MCP SDK (windowsHide)
+ └─ outer cmd → fallback npx.cmd → Electron Node + npx-cli.js
+                                  └─ npm run-script (windowsHide) → inner cmd → package bin
+```
+
+- npm staging patches `node_modules/@npmcli/run-script/lib/make-spawn-args.js` in the verified,
+  extracted temporary package, before replacing the staged npm directory. The cached registry
+  archive keeps its original bytes and sha512.
+- The patched spawn options set `windowsHide` only when `process.platform === 'win32'` and
+  `process.versions.electron` is defined. `ELECTRON_RUN_AS_NODE` alone is not a runtime identity:
+  a system Node child can inherit it.
+- The policy covers run-script children of this bundled npm, including npx package execution and
+  install lifecycle scripts. It preserves command, args, cwd, env, stdio and shell behavior.
+- System npm files are unchanged. User command priority and server PATH overrides stay unchanged.
+  There is no global spawn interception or recursive policy for arbitrary MCP descendants.
+- Staging requires exactly one known spawn-options block. Missing or repeated blocks fail before
+  deleting the old staged directory. npm upgrades must review the patch against the actual archive;
+  staging must not silently omit it. Repeated staging produces the same patched file.
+- The modified file carries a ZCode change comment. npm and dependency license files stay intact.
+  Shim content is unchanged, so the `v1` layout remains valid.
+- Visible-window acceptance uses window owner PIDs and the MCP process tree. A background `cmd` or
+  `conhost` process is not itself a failure. This patch does not promise to hide consoles that a
+  third-party MCP server explicitly creates through its own launch logic.
+
 ## Observability
 
 - `info` `mcp.node_fallback.ready` once per provider: `binDir`, `hasNpm`.
@@ -178,3 +210,11 @@ On POSIX only the exact key `PATH` is used.
 - Bootstrap unit: npm root lookup order, validity check, and no provider outside Electron.
 - Desktop script unit: npm staging verifies the sha512, reuses a valid cache, replaces a corrupt
   cache, copies the package without `docs/`/`man/`, and fails when the npm entry files are missing.
+  Executing the staged spawn-options module verifies Windows Electron hiding, ordinary Node and
+  POSIX exclusions, and unchanged command/args/cwd/env/stdio/shell. Missing or repeated patch
+  anchors fail without replacing existing staged files. Re-staging leaves the cache unchanged.
+- Windows runtime acceptance: use the actual bundled npm on Electron Node with offline package
+  bins; check stdin/stdout/stderr and nonzero exit propagation. In a packaged App with an isolated
+  profile, connect fallback npx MCP servers, list tools, inspect visible windows and their owner
+  process chains, and verify connection-close cleanup. Keep the system Node path as a control.
+  Runtime results do not imply validation on other Windows versions or untested package scripts.

+ 19 - 1
apps/zcode-cli/docs/design/v2/mcp.md

@@ -238,7 +238,25 @@ MCP result content uses the same provider-neutral model content path as built-in
 - `text` blocks stay model-visible text.
 - `image` blocks with base64 `data` and `mimeType` are projected as model-visible image content blocks, so screenshots from MCP servers can be inspected by vision-capable models.
 - unsupported binary blocks such as audio remain short textual placeholders unless a dedicated media pipeline is added.
-- `structuredContent` is appended as bounded text after content blocks.
+- For every MCP tool, including MCP Apps app-provided tools, use `content` whenever it
+  produces model-visible blocks. This preserves the server's text, images and resources.
+- When `content` produces no model-visible blocks, serialize `structuredContent` as the
+  fallback. All JSON values are supported, including `null`, empty objects and arrays,
+  `false` and zero. An absent or `undefined` field provides no fallback.
+- Select one representation for each result. Selection depends on available content,
+  regardless of server names, tool names or JSON equality.
+  If a server supplies a summary in `content` and detailed data only in `structuredContent`,
+  the model receives the summary. Application consumers can still read the detailed data.
+- Apply this projection before the existing result budget. Store the projected model content
+  through the existing runtime history path. Previously stored model content remains readable
+  under its original representation. Desktop and remote sessions use the same CLI projection.
+
+The MCP specification recommends returning serialized structured results in a text block for
+backward compatibility. The official SDK documents `content` as model-facing and
+`structuredContent` as application-facing. The raw MCP result remains available to existing
+application consumers. Producers put model-required recovery details in `content`.
+[MCP structured content](https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content)
+[MCP SDK client guide](https://github.com/modelcontextprotocol/python-sdk/blob/77001c96f9507be0f4d009b83210a384a5e08bda/docs/client/index.md#calling-a-tool)
 
 ## Command Surface
 

+ 15 - 4
apps/zcode-cli/docs/design/v2/memory/README.md

@@ -599,11 +599,21 @@ tools 不因受限执行策略被裁剪。工具在执行前按以下窄策略
   `<tool_use_error>Error: No such tool available: <RAW_TOOL_NAME></tool_use_error>`,不进入
   Memory 权限策略,也不执行工具。
 - 仅允许当前实际注册的 `Read`、`Grep`、`Glob`;不为 Memory 补注册缺失工具。
-- 允许 read-only Bash。
+- 允许 read-only Bash。按 Memory Agent 实际执行的 shell 选语法:会经 cmd.exe 执行时(`cmd`,含 2026-11-17 起
+  Windows 找不到 Git Bash 时的回落;兼容旧的 Windows `legacy-shell`)走与 foreground 相同的 CMD 只读策略;其余(`posix` / `git-bash` / 未初始化,
+  以及 POSIX 上回落到 `/bin/sh` 的 `legacy-shell`)按 Bash AST。POSIX `legacy-shell` 与 foreground 不同
+  (foreground 对它不给只读),这是有意保持修复前的 Memory 行为:`/bin/sh` 同样把 `#` 当注释,下述 CMD 绕过不成立。
 - 允许 project Memory root 内、不包含既有敏感 path segment 的 `.md` Write/Edit。
-- 允许 project Memory root 内、非递归、无 glob/redirect/env 的 `rm` `.md`。
+- 允许 project Memory root 内、非递归、无 glob/redirect/env 的 `rm` `.md`。这条只能用 Bash AST 证明,
+  会经 cmd.exe 执行时不放行。
 - 拒绝 MCP、Agent、网络访问和 workspace mutation。
 
+Memory Agent 是后台流程,不让用户感知:executor 以 yolo 执行、permission broker 一律拒绝,不弹审批;
+上面的策略是唯一闸门,只有放行和拒绝,判不了就拒绝。拒绝只回给 Memory 模型,用户界面没有任何提示。
+策略和 executor 读同一份 shell 选择:`captureProjectMemoryAgentContext` 捕获会话的 `bashShellSelection`,
+判定和执行都用这份快照。原因(ZP-20261103-14):原来直接用 Bash AST 判只读,会话 shell 是 CMD 时
+`type # & python x.py` 在 Bash 里只剩 `type`,cmd.exe 却会执行 `&` 后面的命令,等于在后台绕过审批执行任意命令。
+
 拒绝结果会作为 tool result 进入下一轮 Memory Agent provider request,因此文本也是冻结合同:
 
 - Bash 拒绝:`Only read-only shell commands and rm with all paths inside <MEMORY_ROOT> are permitted in this context (ls, find, grep, cat, stat, wc, head, tail, and similar)`。
@@ -842,7 +852,7 @@ ZCode 当前没有的工具也属于明确的 tool-inventory 差异;不得为
 | Permission/file write  | root containment;小写 `.md`;敏感 segment;Write/Edit allow/deny;缺失 originSessionId 时同时补入 `node_type: memory`,已有非空 origin 的文件原样保留;Bash 不变                                                                                                                                                      |
 | Recall default branch  | 保留 pointer/index;Main turn 不扫描、不发 Selector、不注入 `relevant_memory`                                                                                                                                                                                                                                          |
 | Recall semantic branch | 无 pointer/index;branch-aware lifecycle 覆盖 prefetch、完整 tool batch 后 consume、recursive scan、selector schema、order/duplicate、正文限制、stale 与 61,440 gate;不增加 Runtime override                                                                                                                          |
-| Extraction             | success/error/abort;direct write;独立 3-word block;cursor;同边界 snapshot;Rewind 后不取消;running+latest;第 5 turn;header refresh;session close 拒绝新调度、丢弃 pending、abort running 并有界 drain;remote workspace 照常调度                                                                                                       |
+| Extraction             | success/error/abort;direct write;独立 3-word block;cursor;同边界 snapshot;Rewind 后不取消;running+latest;第 5 turn;header refresh;session close 拒绝新调度、丢弃 pending、abort running 并有界 drain;remote workspace 照常调度;Bash 按会话 shell 快照判定:经 cmd.exe 执行(cmd / Windows legacy-shell)时 `type # & ...`、`rm <root>/a.md` 被拒,CMD 只读命令放行;posix / git-bash / POSIX legacy-shell 行为不变(策略单测),快照传到策略且被拒命令不到执行端(runtime 用例) |
 | Headless Extraction    | `-p/--prompt` 与 `--target` 注入内部 `extractionEnabled=false`;Main prompt/index/Recall 保持;不读取 Extraction snapshot、不创建 scheduler、不发 Extraction 请求、不推进 cursor、不写 Memory 文件;TUI/app-server 默认行为不变                                                                                      |
 | Dream                  | 无 active trigger;handler 的 24h/5 transcript mtimes/10m gate;lock;第 50 turn;filesTouched;one-shot memory_update;`/dream` 为 Unknown command                                                                                                                                                                    |
 | Custom agent           | exact enum;三 scope;agent key;empty/truncated index;Write/Edit augmentation;Read intentional diff;disallowedTools                                                                                                                                                                                                |
@@ -877,7 +887,8 @@ focused tests;它证明这些规则已经在真实 Runtime 链路中正确组
    child 写入同样补齐 `node_type: memory` 与 `originSessionId`。
 6. 在 Settings 关闭 Memory 后,当前 Session 保持原值;新建 Session 的 provider
    request 不含 Main/custom Memory prompt,不发 selector/Extraction 请求,也不创建
-   project/custom Memory root。重新开启后再新建 Session 恢复 Memory,无需热更新已有
+   project/custom Memory root。默认 prompt 总会发送 `# Memory, notes and feedback` 段
+   (见 `../loop/system-prompt-contract.md`),它与 Memory 开关无关,不算 Memory prompt。重新开启后再新建 Session 恢复 Memory,无需热更新已有
    Runtime。
 7. 当 Extraction provider request 已开始但尚未返回时关闭 session:close 在短预算内完成,
    running request 收到 abort,latest pending 被丢弃,迟到的 tool-use 响应不能写文件或触发

+ 11 - 2
apps/zcode-cli/docs/design/v2/model/anthropic-reasoning-history-replay.md

@@ -167,6 +167,11 @@ the migrated historical rows byte-for-byte unchanged.
 
 ## Signature rejection
 
+OpenAI Responses uses the same repair retry and marker for rejected encrypted reasoning, with its
+own error check and removed blocks; see
+[OpenAI Responses Tool Continuation Boundary](../../../../../../docs/openai-responses-tool-continuation-boundary.md#encrypted-reasoning-rejection).
+The rest of this section describes the Anthropic case.
+
 An Anthropic request may return HTTP 400 when a signed or redacted thinking block is rejected. The
 adapter may retry once only when all of these conditions hold:
 
@@ -275,8 +280,12 @@ removed.
 - Anthropic unsigned reasoning that survives normalization remains in the serializer input using
   the required empty-signature representation, except for an exact-empty block with no provider
   options. Whitespace-only reasoning and any block carrying opaque provider options remain intact.
-- OpenAI Responses, OpenAI-compatible reasoning fields, DeepSeek V4 synthetic thinking, and
-  desktop/mobile delivery semantics are unchanged. Signature repair is visible only through the
+- OpenAI Responses encrypted reasoning reuses the cross-model identity rule, the one-shot repair
+  retry, and the `signedReasoningReset` marker with its own error check and removed blocks; the
+  other passes do not run for it (see
+  [OpenAI Responses Tool Continuation Boundary](../../../../../../docs/openai-responses-tool-continuation-boundary.md)).
+  OpenAI-compatible reasoning fields, DeepSeek V4 synthetic thinking, and desktop/mobile delivery
+  semantics are unchanged. Signature repair is visible only through the
   existing provider-retry UI state; no UI component or interaction behavior is added.
 - Signature repair reuses the existing model retry status, usage, and live-tail projection paths;
   it does not add protocol fields or another retry authority. Its only persisted state is the

+ 9 - 8
apps/zcode-cli/docs/design/v2/model/assistant-block-order.md

@@ -276,9 +276,10 @@ adapter 不删除也不合并消息。字符串 content 和空数组不删除:
   还可能拒绝一次,由签名修复恢复(见 Anthropic Reasoning History Replay 的「Accepted effects」)。
 - 删除按条目判断,不按相邻条目整段判断。相邻的 assistant 条目由 AI SDK 合成一条消息,只有下面两种来源;
   按条目删除都不会带来新的前缀变化:
-  - 输出上限续写:续写提示只在本轮请求里,不写入历史,所以下一轮两段回复相邻。产出第二段的请求里,只有思考的
-    第一段已经被删除(那时它后面是续写提示)。按条目删除时,第二段思考块前面的内容和产出时一致,只少续写提示
-    (原有差异);整段保留反而会把第一段的思考放回去。
+  - 改动前保存的输出上限续写:那时续写提示只在本轮请求里,不写入历史,所以下一轮两段回复相邻。产出第二段的
+    请求里,只有思考的第一段已经被删除(那时它后面是续写提示)。按条目删除时,第二段思考块前面的内容和产出时
+    一致,只少续写提示(原有差异);整段保留反而会把第一段的思考放回去。现在续写提示按隐藏记录写入历史
+    (`docs/model-request-output-tokens.md`「Output-limit Continue 恢复」),两段回复之间隔着它,不再相邻。
   - 没有结果的服务端工具:只在中断收口本身失败时出现,而且只在 live 出现(冷恢复回放为 INTERRUPTED 结果,
     条目带工具调用,不删除)。这时这次调用已经从历史里丢掉,后面思考块前面的内容本来就变了。
 
@@ -342,7 +343,7 @@ ZCode 不自己合并消息或文字块。所有协议都接受 AI SDK 的序列
     `tool_call`;服务端工具分轮时计数器不重置。
   - 每个写库点都写 `blockIndex`,包括 pending → running → completed 的重复写入。
   - 统一构造函数、hydrator 有序分支、`selectToolPartsForHistory`、截图 part 不进入模型历史。
-  - 请求投影按条目删除:两条相邻 assistant 条目中只删只有思考的那条(输出上限续写的形态)。
+  - 请求投影按条目删除:两条相邻 assistant 条目中只删只有思考的那条(改动前保存的输出上限续写形态)。
 - 字节一致性:真实 SQLite + 抓取 Anthropic 请求体,同一条交错消息 live 请求等于冷恢复请求。
 - 旧数据:工具写库顺序和 `declarationIndex` 不一致、单个文字 part、带 reasoning 的旧消息,冷恢复后的
   历史与请求体和改动前布局完全相同。
@@ -360,12 +361,12 @@ ZCode 不自己合并消息或文字块。所有协议都接受 AI SDK 的序列
 - 桌面 E2E(I76,`conversation-session/conversation-session-assistant-block-order`):
   - 块形态在同一会话回放(S16 单独一个用例):live 与冷恢复的行序;续发请求逐形态块顺序等于上面的规则表;
     冷恢复前后请求只在末尾追加;全部思考签名原样带回;同一会话的相邻主请求逐个比较抓到的请求体,
-    都只在末尾追加,例外只有 S19 的续写。轨迹工具用 model-io 摘要重建响应,表示不了 S20 的服务端工具
+    都只在末尾追加,没有例外。轨迹工具用 model-io 摘要重建响应,表示不了 S20 的服务端工具
     分轮,所以不用它判定。除了 Read 的形态,还有:
     - S18:Write 不是只读工具,流结束后才执行和写库。live 与冷恢复的行序都是文字 P、Write 卡片、文字 Q。
-    - S19:响应因输出上限(`max_tokens`)停止。自动续写的请求按流顺序带回已经输出的块;之后的请求里,
-      续写前后的两段回复按流顺序排列。续写提示不写入历史(TS09-CONTINUE),所以之后的请求去掉续写提示,
-      续写文字接在原 assistant 消息末尾,原有的块不变。
+    - S19:响应因输出上限(`max_tokens`)停止。自动续写的请求按流顺序带回已经输出的块,最后一条是续写提示。
+      续写提示按隐藏记录写入历史(TS09-CONTINUE),之后的请求原样保留它:续写前后的两段回复是两条 assistant
+      消息,中间隔着续写提示,各自按流顺序排列。
     - S20:服务端工具(未知名称的 `server_tool_use` 加 `tool_result`)把一次响应分成两轮。序号跨轮不重置,
       行序和请求都按流顺序。
   - 停止时已完成的块、反馈落在最后一个文字行并在冷恢复后保留、任务搜索找到第一段文字、手机 `/remote` 行序。

+ 2 - 2
apps/zcode-cli/docs/design/v2/model/context-composition.md

@@ -42,7 +42,7 @@
 | ----------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------- |
 | `system_prompt`         | 系统提示词                                                                    | sections:`system` 注入、来源不是 `skills`/`tools`                                  | `system_prompt`                                                 |
 | `meta_user_context`     | 指令(AGENTS.md、记忆索引)                                                   | 请求里 `context_prefix` 公告的真实文本;无 metadata 的旧版 `<system-reminder>` 前缀 | `meta_user_context`                                             |
-| `skills`                | 技能列表                                                                      | 请求里 `skills_listing` 公告的真实文本                                              | `skills`                                                        |
+| `skills`                | 技能列表                                                                      | 请求里全部 `skills_listing` 公告(首发与增量)的真实文本                            | `skills`                                                        |
 | `tool_prompt`           | 工具说明                                                                      | sections:来源 `tools`                                                              | `tool_prompt`                                                   |
 | `system_tool_schemas`   | 内置工具定义                                                                  | 请求 tools,非 `mcp__`/`app__`、非延迟加载                                          | `system_tool_schemas`                                           |
 | `mcp_tool_schemas`      | MCP 工具定义                                                                  | 请求 tools,`mcp__` 前缀                                                            | `mcp_tool_schemas`                                              |
@@ -138,7 +138,7 @@ runtime 方法 `getContextComposition({ modelSelection?, traceContext? })` 在
 
 - 不调 `persistAnnouncements`。事实:它会落库,草稿上调用会让会话从 deferred 升为 immediate 持久化(`v4-bridge.ts:1273-1320`、`server-operations.ts:3213-3216`)。
 - 不写历史,不发请求,不跑 hooks。
-- 不做 IO 探测:环境公告沿用历史或启动快照(不重新探测 cwd 的仓库属性),Git 公告取启动快照(不调 `resolveGitContext`,也不消费 `sessionStartGitPrefetch`)。
+- 不做 IO 探测:环境公告沿用历史或启动快照(不重新探测 cwd 的仓库属性),Git 公告取启动快照(不调 `resolveGitContext`,也不消费 `sessionStartGitPrefetch`),不向 Host 读取回复语言(预演少算一条待发的 `language` 公告)。
 - 不模拟需要 IO 或会消费一次性状态的提醒:todo 提醒(读 todo)、计划模式退出提醒、silent turn 提醒(只在非首步)、Memory 更新(取出即消费)。
 
 **可接受的副作用**:`ensureContextInitialized` 会启动 MCP 连接、建记忆与 gen-ui 目录、在内存里装好 context 前缀(`context.ts:81,89,97,195`)。已有先例:技能面板也走这条路(`skill-reference-catalog.ts:21-24`)。这些在草稿首次发送时本来也会发生,都不落库。

+ 2 - 0
apps/zcode-cli/docs/design/v2/model/stream-error-retry.md

@@ -146,6 +146,8 @@ core recovery 的可观测性要求:
 
 优先级:显式传入 adapter 的 `retry` 选项 > `ZCODE_MODEL_RETRY_*` 环境变量 > 内置默认值。非法环境变量值不会让启动失败;adapter 忽略该变量并回退到下一层默认值,避免一个错误的调试变量让 CLI 完全不可用。日志和状态事件不得输出完整环境变量集合,只能暴露归一化后的 retry budget。
 
+上面算出的是本地退避。请求带着实现了 `retryCooldownMs` 的准入端口(目前只有主代理的 observer)时,普通重试(不含 off-peak 排队)的最终等待是 `max(本地退避, 端口报告的剩余冷却)`,冷却部分封顶 5 分钟;首次请求不读冷却。冷却拉长了等待、且 `jitter` 开着时,再往后加与 Retry-After 同一档的抖动(最多 20%、不超过 5 秒,总等待仍不超过 5 分钟)。空 completion 的那一次重试同样按这条规则等,并在 sleep 前归还准入票据;它的状态事件不转投票据,治理器仍按 `ended` 结算。`model_retry_scheduled.delayMs` 报的是最终等待;`model.retry.delay.resolved` 日志在叠加了冷却时另记 `admissionCooldownMs` 与 `backoffMs`。冷却从哪来见 `docs/dynamic-workflow/concurrency.md`「Where the port is bound」。
+
 ## 测试覆盖
 
 - 纯签名或空正文 delta 后,仅出现尚未完成的 `tool_input_start` / `tool_input_delta`,随后发生 SSE 503 error chunk、连接重置或 idle timeout 时,应走 adapter retry,且不向 core 泄漏失败 attempt 的签名、空 delta 和工具输入。AI SDK 将提前 EOF 归一为空 completion 时,继续验证既有一次 empty completion retry;本次不扩展 EOF 检测或其预算。

+ 50 - 16
apps/zcode-cli/docs/design/v2/plugin-compat.md

@@ -188,6 +188,14 @@ that reports nothing was removed, rather than an error.
 
 The built-in marketplace name is `zcode-plugins-official`.
 
+Explicit installation requires the requested plugin entry in the local catalog.
+If the manifest or requested entry is missing, the installer loads the registered
+marketplace source once before resolving dependencies. A bundled-only official
+manifest therefore loads the CDN partition on demand. Existing entries use the
+cached catalog. Fetch failure preserves the previous catalog and installed records,
+and propagates the source error. The install operation owns cancellation and the
+existing plugin storage lock covers this preparation and the subsequent install.
+
 External Claude Marketplace sources use `.claude-plugin/marketplace.json` as
 their canonical manifest location. ZCode may normalize the fetched marketplace
 manifest into `~/.zcode/cli/plugins/marketplaces/{marketplace}/marketplace.json`
@@ -261,6 +269,21 @@ failed cache promotion with an older Android version present. Tests use harmless
 marker files to detect execution. Native Windows validation is recorded separately
 from portable path tests.
 
+### Android Shell admission follow-up (0.1.3)
+
+The 0.1.1 resolver still protects Android MCP tool lookup. Version 0.1.2 added a
+Bash-wide direct-adb ban and mandatory MCP guidance; this also blocked legitimate
+SDK executables. Version 0.1.3 removes the mandatory-MCP guidance and updates all
+bundle/cache version markers so existing installations receive it. Bash now
+rejects only workspace-controlled literal adb paths and pins allowed calls to
+safely resolved external absolute paths. MCP device listing remains an option;
+missing plugins do not disable installed SDK adb.
+
+The enforcement and its static-parser/environment limits are defined in the
+[Bash spec](tool/04-bash.md#direct-adb-execution-admission). Project builds and
+scripts remain permitted under existing permissions. This change does not
+inspect script bodies or confine their descendants, and does not change iOS.
+
 The normal seeding layout is:
 
 ```text
@@ -655,7 +678,9 @@ model-visible or process-list-visible fields such as `command`, `args`, `cwd`,
 `url`, OAuth `clientId`, or OAuth `scope`. Existing `ZCODE_*` runtime wiring
 variables remain available in those fields for backward compatibility.
 
-`userConfig` defaults are used when no explicit plugin option exists. Sensitive
+`userConfig` defaults are used when no explicit trusted plugin option exists. Repository
+`plugins.options` values are ignored; explicit workspace settings come from the host user's
+private options file. Sensitive
 `userConfig` values follow the same sink boundary: options marked `sensitive`
 may only be expanded in MCP secret sinks.
 
@@ -680,7 +705,9 @@ may only be expanded in MCP secret sinks.
 
 ### 设计
 
-敏感值只存进一个私有文件,`config.json` 里不再写敏感值。
+敏感值与全部 workspace 选项存进同一个私有文件。user scope 的普通值仍写用户 `config.json`。
+项目 `config.json` 中的 `plugins.options` 不参与运行时合并:插件可把这些值展开为可执行路径、
+参数、环境变量或请求地址,已安装插件的身份不能把仓库输入变成用户授权。
 
 - 路径:`<cli storage root>/plugin-secrets.json`,即默认的
   `~/.zcode/cli/plugin-secrets.json`。远程工作区的 CLI 在远端主机上,用它自己的文件。
@@ -706,23 +733,25 @@ may only be expanded in MCP secret sinks.
 - 读取层与 `config.json` 一一对应:user 层随 user 配置读取(跳过 user 配置时不读);
   每个被发现的项目配置文件是一个 workspace 层,用它的 baseDir 找私有文件里的条目。
   workspace scope 的 configure 总会写 `<workspace>/.zcode/config.json`(至少留一个空的
-  `options[id]`),所以保存过的 workspace 敏感值一定有可被发现的层。
+  `options[id]`),所以保存过的 workspace 私有选项一定有可被发现的层;空条目只作发现锚点,
+  不向运行时提供值。
 
 规则:
 
-| 操作                           | 敏感键                                                                                     | 普通键                 |
-| ------------------------------ | ------------------------------------------------------------------------------------------ | ---------------------- |
-| configure(写值)              | 写进私有文件的对应 scope;同一 scope 的 `config.json` 里若有同名键,同一次操作删掉(迁移) | 不变,写 `config.json` |
-| configure(`clearOptionKeys`) | 私有文件与 `config.json` 两处都删                                                          | 不变                   |
-| 读取(运行时与投影)           | 每个 scope 先读私有文件,再读 `config.json` 的旧明文值;私有文件优先。scope 优先级不变     | 不变                   |
-| reset                          | 与 `config.json` 同语义:删除该 scope 下这个插件的条目                                     | 不变                   |
-| uninstall                      | 删除 `user` 与全部 `workspaces` 下这个插件的条目                                           | 不变                   |
-
-- **不在启动时迁移**。旧的明文值继续能读;用户下次保存这个插件的设置时,敏感键才迁进
-  私有文件。理由:启动时改写 workspace 配置会在用户仓库里产生意外的 diff。
-- 键是否敏感以当前清单的 `userConfig` 为准。清单把某个键改成敏感后,旧的明文值仍可读,
+| 操作                           | 敏感键                                                                | 普通键                                          |
+| ------------------------------ | --------------------------------------------------------------------- | ----------------------------------------------- |
+| configure(写值)              | 写进对应 scope 的私有文件;只迁移 user 配置的旧明文敏感值             | user 写用户 `config.json`;workspace 写私有文件 |
+| configure(`clearOptionKeys`) | 私有文件与 `config.json` 两处都删                                     | 同左                                            |
+| 读取(运行时与投影)           | user 私有值优先于用户配置旧值;workspace 只读私有值。scope 优先级不变 | user 读用户配置;workspace 只读私有值           |
+| reset                          | user 删除该插件配置;workspace 仅恢复启停继承,保留选项               | 不变                                            |
+| uninstall                      | 删除 `user` 与全部 `workspaces` 下这个插件的条目                      | 不变                                            |
+
+- **不在启动时迁移**。用户配置的旧明文值继续能读;用户下次保存这个插件的设置时,敏感键才迁进
+  私有文件。项目配置的旧值全部忽略,也不在保存其它键时迁入;必须由用户重新输入并保存。
+  workspace 保存时清理该插件的全部旧明文选项,避免旧仓库值被误认为仍有效。
+- 键是否敏感以当前清单的 `userConfig` 为准。清单把某个键改成敏感后,用户配置的旧明文值仍可读,
   下次保存时迁移。
-- 「下次保存」指这个插件在该 scope 的任意一次非 `dryRun` configure:该 scope 的
+- 「下次保存」对旧值迁移只指这个插件在 user scope 的任意一次非 `dryRun` configure:用户
   `config.json` 里所有按当前清单为敏感的旧明文键都迁走,包括这次请求没带的键。理由:
   UI 不回传敏感值,只保存普通键的请求里本来就没有已存的 secret;只迁请求里的键,旧明文会
   永远留在文件里。`clearOptionKeys` 里的键不迁,直接两处都删。
@@ -730,6 +759,9 @@ may only be expanded in MCP secret sinks.
   下次保存再删;不会出现两处都没有的中间态。
 - 投影:`plugins/list` 的 `optionSources` 也列出私有文件里的键(scope 标记照旧),设置页的
   scope 标记与「清除」按钮因此不受迁移影响;`configuredOptions` 仍过滤敏感值。
+- 启动解析与 MCP 动态重载共用私有选项合并规则。动态加载器监听同一私有文件的创建、更新与删除,
+  仅按已加载配置层叠加用户/项目值;不能把设置页的有效值留在展示层。损坏时清除私有覆盖,
+  不复用旧执行参数,也不回退到仓库选项。
 - 私有文件损坏(JSON 或 schema 不符):`backupCorruptFile` 备份后按空文件处理,发出诊断
   `plugin_secrets_unreadable`(`severity: error`,带文件路径,不含任何值)。受影响的
   MCP server 按现有规则报 `plugin_variable_missing`。其他读取错误(例如权限)在读取路径上
@@ -849,7 +881,9 @@ P0 policy:
 - Official cache plugins are loaded only when enabled in config.
 - Only bundled official cache plugins are automatically rewritten to the
   internal ZCode/SEA plugin host.
-- Project-discovered plugin dirs are out of scope.
+- Project-discovered plugin dirs (`plugins.dirs` in project config) are pending
+  until the user trusts each one in Settings; see
+  `docs/plugins/workspace-plugin-dir-trust.md` in the repository root.
 - Hook files from every enabled cache plugin, including non-official
   third-party Marketplace plugins, are injected into the runtime. Per-plugin
   trust is not implemented; see `canRunPluginHooks`.

+ 56 - 0
apps/zcode-cli/docs/design/v2/preinstalled-document-tools.md

@@ -0,0 +1,56 @@
+# 桌面预装工具入口
+
+关联规格:[预装工具](../../../../../docs/preinstalled-tools/README.md)。
+
+2026-10-29:本文取代旧的 `ZCODE_PREINSTALLED_TOOLS_RECORD` 合同。该变量删除,Agent 不再读取安装记录。
+
+## PATH 与环境变量
+
+桌面 Local Host 启动本机 Agent 时做两件事:
+
+1. 把固定入口目录 `<数据根>/.zcode/preinstalled-tools/<发布身份>/bin`(下称 `<bin>`)放在 Agent PATH 的最前面。Agent 靠 PATH 找到预装工具。
+2. 注入 `ZCODE_PREINSTALLED_TOOLS_AVAILABLE=1`。
+
+`ZCODE_PREINSTALLED_TOOLS_AVAILABLE` 的规则:
+
+- **用途**:表示“这台电脑可以在 帮助 → 预装工具 中管理预装工具”。插件只用它判断工具都不可用时给哪种提示:有这个变量,提示查看“帮助 → 预装工具”;没有,保持原有的安装引导。查找程序不使用这个变量。
+- **值**:固定为 `1`。插件只判断它是否非空。
+- **何时注入**:本机桌面总是注入,与安装状态和当前平台是否有资源无关。`<bin>` 可以暂时不存在或为空。
+- **优先级**:执行端 Host 给出的值优先。Agent 进程管理在 spawn 边界只采用 Host 的值,不继承用户 shell 或部署命令中的同名值;Host 不注入时,即使继承到同名值也清除。
+- **不注入的环境**:远端 Host(SSH、WSL、Docker)、Web 服务端和独立 CLI 不注入这个变量,也不在 PATH 前加 `<bin>`。
+- **错误行为**:变量不存在或为空时,插件按非受管环境处理,保持原有的安装引导。CLI 不解释这个变量,不调度安装;唯一例外是 Windows Git Bash 下恢复 `<bin>` 的最前位置,见“与 Bash 快照的关系”。
+
+```text
+桌面 Local Host ── spawn Agent ──► env.PATH = <bin> + 原 PATH,env.ZCODE_PREINSTALLED_TOOLS_AVAILABLE = 1
+                                     │
+Bash 快照:最后一行写 export PATH='<Agent 进程的 PATH>',rc 文件对 PATH 的修改被覆盖
+                                     │
+每条 Bash 命令:新 shell → source 快照 → 按 PATH 查找程序 → 先找到 <bin> 中的入口
+预装进程 ── 增删 <bin> 中的入口 ──► 下一条命令生效,不需要重启 Agent
+```
+
+## 与 Bash 快照的关系
+
+- 除 Windows Git Bash 外,快照写入的 PATH 就是 Agent 进程收到的 PATH(`adapters/src/exec/shell-init-snapshot.ts`)。所以 `<bin>` 在每条 Bash 命令中都排在最前。
+- 快照固定的是目录列表,不是目录中的文件。入口后来写入或删除,同一会话的下一条命令就能看到变化。
+- Windows Git Bash 的快照 PATH 取自登录 shell 的输出。登录 profile 会把 `~/bin`、`/ucrt64/bin`、`/usr/bin` 等放到前面(实测 `<bin>` 排第 9 项),而 Git 自带 `/ucrt64/bin/pdftotext`,会抢先于预装入口。所以变量存在时,把 Agent PATH 的第一项(即 `<bin>`)移到快照 PATH 最前,其余顺序不变。不能直接用 Agent 进程的 PATH,否则 `C:\Windows\System32` 的 `find`、`sort` 会排到 `/usr/bin` 前面。
+- 快照创建失败时,命令退回 `-c -l` 执行。这时 Git Bash 下在命令前加一行,同样把 `<bin>` 放到最前。其他 shell 的退回路径中,rc 文件仍可能改变顺序。
+
+## 覆盖范围
+
+| 执行路径 | 是否看到 `<bin>` 和变量 |
+| --- | --- |
+| Bash、后台 Bash | 是 |
+| hooks | 是 |
+| Agent 启动的 MCP stdio 服务 | 是,继承 Agent 环境;MCP 配置自行设置 PATH 时除外 |
+| 上述进程启动的子进程 | 是 |
+| App 终端面板、远端工作区、独立 CLI | 否 |
+
+不改 App ↔ Agent 协议,不改系统提示词,不新增 Agent 工具。Bash 执行仍经过 ExecutionPort 和现有的权限链路。
+
+## 验证
+
+- CLI ExecutionPort:先建立 Bash 快照,再在 `<bin>` 中创建入口,下一条命令用 `command -v` 能找到它;删除入口后,下一条命令找到系统程序或找不到。快照建立后,`<bin>` 仍在 PATH 最前。
+- CLI ExecutionPort:`ZCODE_PREINSTALLED_TOOLS_AVAILABLE` 在快照建立后的新命令中仍可读到。
+- MCP:stdio 服务的环境包含 `<bin>`;配置自行设置 PATH 时按配置为准。
+- 桌面 provider replay 候选:从本机会话读取 Host 注入的变量和 PATH 顺序;远端 Agent 进程中没有这个变量。远端不注入需要独立的远端 E2E 证据。

+ 19 - 7
apps/zcode-cli/docs/design/v2/rewind-compact.md

@@ -132,35 +132,47 @@ compaction 结果的顺序(boundary → 请求前公告 → summary → 保留
 [请求前公告] context_prefix → session_context → date   仅当保留段非空;保留段已有的来源不重复(date 也一样:保留段里有日期公告时,即使已过期也不放,之后的请求在末尾宣告一次变化)。context_prefix 只认完整块:保留段只有增量时也放完整块;保留段有完整块时不放,内容变化由下一次请求追加增量(reason `compaction`)
 [summary]
 [保留段]
-[compaction 附件] 文件恢复 → plan_file_reference → runtime_mode(计划模式下的完整提醒,保留段已有完整提醒时不发)
+[compaction 附件] 文件恢复(正文在 user 侧,见下文)→ task_status(后台任务状态)→ plan_file_reference → runtime_mode(计划模式下的完整提醒,保留段已有完整提醒时不发)
                   → tool_search_announcement → agent_listing_delta → skills_listing → environment → model
-                  → output_style_instructions
+                  → output_style_instructions → language
 ```
 
-- compaction 附件(含文件恢复与 plan_file_reference)都参与冒泡,附件之间保持生成顺序。支持 MCS 时它们都是 system,在 user run 末尾按上表顺序合成一条 system;不支持 MCS 时都是 user 侧 reminder,顺序相同。
-- 文件恢复(`resume_referenced_session_context`)在 summary 返回之后重读磁盘上的当前文件,不用读取状态里缓存的视图:
+- 文件恢复的正文(调用说明与结果)在 MCS 开关下都是 user 侧 `<system-reminder>`,按普通 user 消息合并:不并入前面的 tool result(auto/reactive 的保留段可能以 tool result 结尾,正文作为同一条 user 消息里 tool_result 之后的独立文本块);前面紧挨 user 文本时,那段文本以换行结尾(两条正文相邻时,调用说明以换行结尾)。正文和其余 compaction 附件(含过大文件的引用提示与 plan_file_reference)一样参与冒泡,越过 user 输入,附件之间保持生成顺序;所以 MCS 下正文在 user 输入之前,其余附件在 user run 末尾。支持 MCS 时其余附件是 system,在 user run 末尾按上表顺序合成一条 system;不支持 MCS 时都是 user 侧 reminder,顺序相同。
+- 文件恢复(正文来源 `resume_referenced_session_context`,引用提示来源 `compact_file_reference`)在 summary 返回之后重读磁盘上的当前文件,不用读取状态里缓存的视图:
   - 候选:compact 前读取状态里 `Read`、`Write`、`Edit` 留下的记录。不选 Bash 回填、Recall 注入、`MEMORY.md` 初始记录和工作流草稿的记录;不选 plan 文件、已加载进上下文前缀的指令文件,以及 `.codex/memories/`、`docs/superpowers/plans/`、`.git/` 下的文件;不选保留段里 Read 过的文件(路径按当前工作目录解析后比较;返回 `file_unchanged` 的 Read 不算,它只指向已被摘要的旧结果)。
   - 选择:按时间从新到旧先取 5 个,再读取;读取失败或被跳过的文件照样占名额。本进程写入的记录(包括 rewind 重建的记录)按文件的 `mtimeMs` 排序,冷恢复出的记录(`restoredFromSession`)按读取时间排序;缺 `mtimeMs` 时用读取时间。
   - 读取:整个文件,不带 `offset` / `limit`。不走工具调用流程:没有 hook、工具事件和权限弹窗;只跳过命中读权限 deny 规则的文件,ask 规则照常读取;判定与 Read 工具调用共用同一个模式与规则判定,规则只加载一次。规则按原始字符串匹配,所以记录的规范化路径和工具输入的原始写法(读取状态的 `requestedPath`:live 由工具记下,冷恢复取自 tool part 的输入)各判定一次,任一命中 deny 就跳过:同一写法的 Read 被拒的文件不会被补回。补回后写回的记录保留原始写法。plan 文件和补回文件并行读取。只补回文本文件:图片、视频、PDF 和 Read 预检不通过的文件(二进制、设备文件)跳过。读取传入取消信号,读完再检查一次;取消时整个 compact 取消,不产出附件。
-  - 内容:`Called the Read tool with the following input: {"file_path":…}`,换行后是 `Result of calling the Read tool:` 和 Read 工具结果原文。估算超过 5k token,或超过 Read 的文件大小上限时,只放引用提示("Note: … was read before the last conversation was summarized, but the contents are too large to include. Use Read tool if you need to access it.")。按顺序累加,总量超过 50k token 的文件丢掉,不放提示(单文件不超过 5k、最多 5 个文件时实际不会触发)。
+  - 内容:每个文件两条正文,各包一层 `<system-reminder>`:`Called the Read tool with the following input: {"file_path":…}`;`Result of calling the Read tool:`,换行后是 Read 工具结果原文。估算超过 5k token,或超过 Read 的文件大小上限时,只放一条引用提示("Note: … was read before the last conversation was summarized, but the contents are too large to include. Use Read tool if you need to access it.")。按顺序累加,总量超过 50k token 的文件丢掉,不放提示(单文件不超过 5k、最多 5 个文件时实际不会触发)。
   - 读取状态:compact 后的 live 表只含补回的文件,记录规则与重启后的行为见 [Read File State Resume](tool/17-read-file-state-resume.md) 的“Compaction 之后”。
   - 补回内容随 compaction 附件一起持久化,冷恢复读到相同字节,不再重读磁盘;已有的 compaction 不改写。
+  - 旧存档:旧版本写的正文是一条(调用说明和结果用 `\n` 相连),引用提示也用 `resume_referenced_session_context`。来源的投递方式改为 user 侧后,这两类旧条目冷恢复后都在 user 侧,按正文的合并规则投影;这类会话升级后的第一次请求未命中一次缓存。旧版本读到 `compact_file_reference` 时按未知来源处理,作为普通 user 文本回放,不报错。
+- 后台任务状态(`task_status`):summary 返回后读一次本 runtime 的任务注册表,之后不再读。只取当前分支(`branchGeneration`)的任务,先 agent 后 Bash,各按登记顺序,每个任务一条:
+  - agent(`local_agent`,不分前台后台):运行中的;以及已结束、`completedAt` 距这次读取不到 30 秒的。
+    - 运行中:`Background agent "<desc>" (<id>) is still running. Do NOT spawn a duplicate. You will be notified when it completes. Send it a message with SendMessage if you need a progress report before then.`
+    - 已停止(`killed` / `cancelled` / `stopped`):`Task "<desc>" (<id>) was stopped.`
+    - 其他结束状态:`Task <id> (type: local_agent) (status: <status>) (description: <desc>)`;带错误时接 ` Delta: <error>`;最后接 ` Send it a message with SendMessage to retrieve its result.`
+    - 没有 SendMessage 工具时,去掉含 SendMessage 的那一句。文字不带输出文件路径,与启动回执的 “Do NOT Read or tail this file” 一致。`<desc>`、`<id>`、`<status>`、`<error>` 里的 `&`、`<`、`>`、控制字符和 U+2028、U+2029 写成 HTML 实体。
+  - Bash(`local_bash`):只取运行中、已转后台的。`Background shell <id> ("<desc>") is still running (command, shown on one line: \`<command>\`). Do not start it again; to restart it, stop it with TaskStop first. You can read its output at <path>.` 命令在登记时随任务存下。描述和命令先压成一行:去掉不可见字符(不成对的代理码位、格式字符、私用区字符、未分配码位和 Default_Ignorable 字符)与控制字符(`\t\n\v\f\r` 按空白处理),连续空白换成一个空格,去掉首尾空白。再分别截到 200、500 个 UTF-16 码元(不切开代理对),截掉的部分写成 `… [+N chars]`。没有命令时去掉括号这一段;没有输出文件,或没有 Read / Bash 工具时,去掉最后一句。`<id>` 里的 `&`、`<`、`>`,`<path>` 里的 `<`、`>`,以及两者里的控制字符和 U+2028、U+2029 写成 HTML 实体;描述和命令不做 HTML 转义,其中嵌套的 `system-reminder` 标签和其他提醒一样由包装层中和。
+  - 工作流 run 不补回。子 runtime 只有自己的注册表,只报自己的后台 Bash。
+  - 投递与其余 compaction 附件相同:支持 MCS 时在 system 里,不支持时是 user 侧 `<system-reminder>`。随 compaction 附件持久化,冷恢复回放存档原文,不再读注册表。
+  - 读取之后才结束的任务,终态通知照原队列送达,排在 compaction 之后。压缩时通知还在队列里的已结束 agent 会同时有一条补回和一条通知。结束超过 30 秒的 agent 不补回,模型要靠摘要里的 agentId 找回它。
 
 - 输入附件在 compaction 之前运行,属于保留段或被摘要;同一请求在 compaction 之后不再收集输入附件,只运行按历史去重的请求前公告。保留段为空(manual compact)时,请求前公告由下一次请求追加在末尾。
-- `total_tokens_reminder`(见 `loop/meta-user-context.md`):compaction 不重述它。auto/reactive compaction 前收集的那条在保留段里,摘要请求和 compaction 后的第一个请求不产生新提醒。auto 与 reactive 成功后,runtime 把 compact 前最近一条带 usage 的 assistant 的上下文量加进计数器的 rolled;manual compact 不加,下一条真实用户消息会重新起算。
+- `total_tokens_reminder`(见 `loop/meta-user-context.md`,默认关闭,由 CLI 参数或 App 设置在创建 runtime 时决定;关闭时 compaction 前后都不产生提醒,下面的规则只在打开时生效):compaction 不重述它。auto/reactive compaction 前收集的那条在保留段里,摘要请求和 compaction 后的第一个请求不产生新提醒。auto 与 reactive 成功后,runtime 把 compact 前最近一条带 usage 的 assistant 的上下文量加进计数器的 rolled;manual compact 不加,下一条真实用户消息会重新起算。
 - summary 文本:续写提示("Continue the conversation…Pick up the last task as if the break never happened.")之后,保留段非空时再追加 `\n\n` 和尾注 "The messages after this summary are the most recent messages from before compaction, kept verbatim. The summary was written without seeing them, so something it says has not happened yet may already have happened in them."。判定与请求前公告相同(保留段非空);manual compact 不带尾注。尾注随 summary 文本持久化,冷恢复读到相同字节;已有 summary 不改写。
 - summary 是普通 user 消息,按用户输入参与相邻 user 的换行规则:summary 前紧挨的 user 文本(例如保留段非空时的请求前公告)以 `\n` 结尾。判断依据是 `compactBoundary`,不按 `legacy_synthetic` 来源(旧的后台通知也用这个来源)。
 - 压缩提示词包括第 6 节末尾的用户消息归属说明("Only messages that actually came from the user (user-role turns) count as user messages…")和 `</example>` 之后的换行。
 - runtime_mode 由 compaction 重述:计划模式下发一条完整的 plan 提醒。保留段在当前计划段(最近一次退出计划模式之后)已有完整提醒时不发:auto/reactive compaction 与输入附件收集在同一次循环中,保留段可能已带本次收集的完整提醒,再发一条会出现两条完整提醒,完整/简短周期也多算一次。保留段只有简短提醒时,完整说明已被摘要,照常发完整提醒。
 - environment 与 model 由 compaction 重述:保留段已有完整 environment 块时不重述 environment,否则用 compact 前历史中最近一次公告的快照发完整块;保留段已有 model 公告时不重述 model,否则重述 compact 前最近一次 model 公告。compact 前历史里没有对应公告时不重述,由下一次请求的输入附件收集追加(完整环境块、当前模型)。
 - output_style_instructions 在 model 之后重述:保留段已有该来源(包括重置)时不重述;否则重述 compact 前最近一次公告,最近一次是重置时不重述。它不受 environment/model 的 env_info 门控。
+- language 在 output_style_instructions 之后重述:保留段已有该来源时不重述;否则重述 compact 前最近一次语言公告,最近一次是清除公告时不重述(见 [Agent 回复语言](../../../../../docs/i18n/agent-reply-language.md))。compaction 不向 Host 读取回复语言;语言变化由下一次输入附件收集追加。与 output style 一样不受 env_info 门控。
 - 持久化:请求前公告、summary、compaction 附件按上表顺序在同一事务中写入(`SessionStorePort.commitMessageBundle`),存储顺序与 live 一致;只有 summary 成功产出时才写入。store 未实现该方法时逐条写入,失败时尽力删除已写入的记录。
 - 声明:summary 的 compaction part(与 `compactBoundary.preservedSegment` 同一个 part)在 `metadata.compactLeadingMessageIds` 中记录请求前公告的消息 ID。只记录 summary 之前的公告;compaction 附件可能在下一次 compact 时与最后一组一起被保留,不得写入该列表。
 - 冷恢复:最后一个 boundary 声明的请求前公告放在 summary 之前。切片 `preservedSegment` 区间时,跳过所有 summary 声明的请求前公告:保留段可以落在上一次 compact 的保留段里,此时区间在存储顺序上跨过上一次的公告和 summary;这些公告在压缩后的第一组,总被下一次 compact 总结,不会出现在 live 保留段中。
 - fork:重映射 `compactLeadingMessageIds`;映射不到的 ID 丢弃,不阻断 fork(旧版本 fork 会原样复制该字段)。
 - 旧版本兼容:不改 strict 的 `compactBoundary` schema。`CompactionPart.metadata` 不进入 App 协议,旧版本按 JSON 读取 part 时忽略它。旧版本冷恢复时,summary 之前的公告不在 `slice(boundaryIndex)` 范围内,会被漏掉;跨过的保留段可能带回上一次的公告。这两种情况只影响上下文内容,不会导致读取失败。
 - git status 与分支:规则只看历史(见 `loop/meta-user-context.md`)。保留段非空且其中没有 `session_context` 时,compaction 通过 `ContextSourcePort.resolveGitContext` 按当前目录重新读取(分支直接读取,不使用轮询缓存),是仓库才在 summary 之前宣告;保留段为空时由下一次请求读取。读到的 Git 只进入公告,不改 runtime 的 context 快照,compact 写库失败时不留任何 Git 事实。没有 context port 的运行时沿用会话起始快照。
-- skills_listing:在 compaction 附件中紧跟 agent_listing_delta。保留段里没有 skills_listing 且当前 skill 目录不为空时重述完整列表,判定与输入附件收集相同;compact 后的第一次请求就带 skill 名单。ZCode 不找回已调用的 skill。已恢复列表的原位更新见 `loop/meta-user-context.md`。
+- skills_listing:在 compaction 附件中紧跟 agent_listing_delta。与输入附件收集用同一收集器,以保留段为历史回放已发指纹:保留段没有列表时补完整列表,部分保留时只补缺失的行;compact 后的第一次请求就带 skill 名单。ZCode 不找回已调用的 skill。已恢复的列表不改写,规则见根目录 `docs/skills-live-catalog.md`。
 - 指令文件与 `MEMORY.md`:summary 返回后,与文件恢复并行重读(异步 IO,传入取消信号)。只更新 runtime 持有的指令内容与 Memory 索引,不改工作目录、环境、Git 预取标记。读取失败时沿用原内容并记 warn;取消时整个 compact 取消。重读结果先只用于生成 summary 之前的 context_prefix(见上表);compact 成功落库后才交给 runtime,同时把指令增量的 reason 改为 `compaction`(之后不再改回)。compact 失败或取消时 runtime 的内容和 reason 都不变。保留段为空时由下一次请求宣告完整块。`MEMORY.md` 的读取状态在 compact 读取状态装好之后按重读的内容写入。没有 context port 的运行时(子 agent)不重读。
 
 ### File rewind after compact

+ 12 - 3
apps/zcode-cli/docs/design/v2/sea-cross-target-packaging.md

@@ -45,6 +45,9 @@ ZCode 的默认发布形态仍然是标准 Node.js CLI 包:`dist/zcode.cjs` 
   传递依赖(含根 `model-option-map`、`session-control`),最后单独重建 CLI bundle。
   CLI 子 workspace 的 Turbo 图看不到根目录的包,不能只用它构建。准备阶段不使用
   Turbo 缓存,也不缓存已有 SEA 产物。
+- `pnpm run build:sea --darwin`、`--linux`、`--win`(可叠加,如 `--darwin --linux`):同一入口,
+  只构建所选平台的全部 target。pnpm 把脚本名后的参数逐层追加到 `build-sea.mjs --all` 之后,
+  三层 package script 不变。
 - 根目录 `pnpm build:sea:all`:安装依赖后转发到同一个 all-target `build:sea` 入口。
 - `pnpm run sea -- <target 参数>`:只封装当前已有的 `dist/zcode.cjs` 和 runtime
   assets,不负责重新编译 workspace。
@@ -54,13 +57,18 @@ ZCode 的默认发布形态仍然是标准 Node.js CLI 包:`dist/zcode.cjs` 
 - `node scripts/build-sea.mjs --all`:构建首批全部 target。
 - `node scripts/build-sea.mjs --node-binary linux-x64=/abs/path/node`:使用用户提供的目标 Node 二进制,跳过该 target 的下载解析。
 
+平台参数 `--darwin`、`--linux`、`--win` 只做筛选:在 `--all`、`--target`、`--targets` 或
+`--node-binary` 选出的 target 中保留所选平台;没有其他 target 参数时从首批全部 target 中筛选。
+不带平台参数时结果不变。筛选后没有 target(例如 `--target darwin-x64 --linux`)时报错,不回落到 host。
+不能用 `--target` 缩小 `build:sea`:它与 `--all` 取并集。
+
 target 参数使用 release 命名里的平台名;Windows 输入使用 `win-x64` / `win-arm64`。Windows 产物发布文件名使用 `windows`,对齐旧 GLM agent 下载契约;内部平台 key 和 host 判断仍使用 Node.js `process.platform` 风格的 `win32`。
 
 ## Target Runtime Assets
 
 SEA 可以在一个 host 上下载并注入其它 target 的官方 Node.js binary。`bfs`、`ugrep` 必须先由对应目标平台的 producer 构建、验证并发布到统一依赖源;macOS x64/arm64、Linux x64/arm64 与 Windows x64/arm64 的 `rg` 全部使用固定 SHA-256 的 Microsoft `ripgrep-prebuilt v14.1.1-1` 原始归档,并从同一内网依赖源的 `native-search-tools/ripgrep-v14.1.1-1` 镜像目录下载。所选 macOS 归档的 deployment target 不得高于既有 macOS 12.0 下限;Linux `rg` 必须使用不引入 glibc 依赖的 musl 归档,`bfs` / `ugrep` producer 固定 Node 24、glibc 2.28、GCC 12 与 G++ 12,并通过最终 ELF 的 GLIBC 2.28 ceiling、版本、feature、架构和动态依赖校验;Windows 两个架构必须拒绝动态 CRT、PCRE2 与构建契约要求静态链接的压缩库依赖。SEA 构建按 target 复用同一份 native-search release plan 和下载器,将两类预编译产物校验并准备到 `packages/desktop/bundled-tools/<platform>-<arch>/`。SEA 不在 foreign target 构建期间交叉编译、切换来源或降级省略工具。
 
-公开 `build:sea` 的既有契约始终是 all-target,不能因为某个平台的 native search 尚未接入而降级成 host-only。构建会为每个 target 自动准备并收集对应的 runtime assets;预编译归档缺失、下载失败或目标格式与架构校验失败时,必须在生成该 target SEA 前终止,不能产出 provider-visible embedded search 已启用、执行层却缺少包内工具的正式二进制。
+公开 `build:sea` 不带平台参数时始终是 all-target,不能因为某个平台的 native search 尚未接入而降级成 host-only;平台参数是使用者显式选择的范围,不是构建脚本的降级。构建会为每个 target 自动准备并收集对应的 runtime assets;预编译归档缺失、下载失败或目标格式与架构校验失败时,必须在生成该 target SEA 前终止,不能产出 provider-visible embedded search 已启用、执行层却缺少包内工具的正式二进制。
 
 当前 macOS、Linux、Windows 的 x64/arm64 native-search release plan 均已启用。macOS/Linux target 准备 `bfs`、`ugrep`、`rg`,Windows target 准备 `ugrep.exe`、`rg.exe`,Windows `find` 继续回退 Git Bash/system。工具最终布局与 SEA manifest 不暴露 producer/Microsoft 来源差异;SEA asset collector 只按统一 release plan 取目标工具。host-only 开发和 E2E 使用 `sea` 或显式 `--target`。
 
@@ -116,8 +124,8 @@ SEA blob 由当前运行脚本的 Node.js 生成,target Node 版本必须与
 
 CLI、桌面内置 Agent 和 SEA 共用的 JS 构建必须统一使用 Zod v4 `4.6.5`,
 以避免旧版在启动时为每个 schema 提前创建全部方法闭包。`packages/shared/package.json` 的精确版本是构建门禁的事实源,
-其余直接依赖声明与根 lockfile 必须与它一致;不使用会改写双 major peer 范围的全局 override。Zod v3 工具契约
-及 `zod-to-json-schema` 保持原有 major,不做跨 major 替换。
+其余直接依赖声明与根 lockfile 必须与它一致;不使用会改写双 major peer 范围的全局 override。工具契约
+`@zcode/contracts` 也使用这个版本,不再依赖 Zod v3 与 `zod-to-json-schema`;第三方依赖自带的 Zod v3 保持原样。
 
 去重由 CLI 的 esbuild 构建入口负责:先按消费者原有解析规则选择 package
 版本和导出,再把同版本的不同安装目录归并到一份实现。保留子入口及
@@ -173,6 +181,7 @@ Windows 官方 `node.exe` 通常带 Authenticode 签名。脚本构建 Windows t
 ## 测试覆盖
 
 - target 参数解析,包括 repeated target、CSV target、`--all` 和非法 target。
+- 平台参数:`--all --linux`、叠加多个平台、单独使用、经 `--` 透传、与 `--target` 组合后为空时报错。
 - package scripts 保证 `build:sea` 始终显式传入 `--all`,根目录 `build:sea:all` 转发到该既有入口。
 - target 到 release artifact、下载 URL、产物名的映射。
 - postject 参数按目标平台生成。

+ 19 - 3
apps/zcode-cli/docs/design/v2/session-persistence.md

@@ -1,5 +1,9 @@
 # Session Persistence
 
+## Workflow 活动历史查询索引
+
+完整活动计数按当前父会话查询,不能扫描其他会话的 run/actor。新增 `0026_dwf_run_parent_session_index`,只增加 `dwf_run(parent_session_id)` 索引,不修改既有迁移 checksum 或数据行;基线由实际迁移生成。run 查询从父会话索引开始,actor 查询先定位父会话的 run,再使用既有 `dwf_actor_run_idx`。新库与已发布结构升级都验证查询计划、无关历史增长后的结果隔离、升级前后数据不变以及重复打开幂等。沿用既有迁移事务、锁与备份机制;旧版本可忽略该附加索引,索引首次构建的成本只发生在升级时。
+
 ## Provider 格式升级与回滚可读性(Todo109)
 
 以 `staging_backup@790884b1ce` 为旧格式对照。Agent 打开库时通过
@@ -86,7 +90,7 @@ Timeline 的展示 label 单独保留,不混入严格的 Selection 契约。
 | `directory` | text not null | session 创建时的工作目录。 |
 | `path` | text nullable | project 相对路径或 UI 展示路径。 |
 | `title` | text not null | session 标题。 |
-| `title_source` | text not null default `first_input` | 标题来源:`default`、`first_input`、`generated`、`custom`。AI generated 标题只能 CAS 覆盖非 custom 来源。 |
+| `title_source` | text not null default `first_input` | 标题来源:`default`、`first_input`、`generated`、`custom`。AI generated 标题只能 CAS 覆盖 `default` / `first_input` 来源,每个会话至多生成一次。 |
 | `title_message_id` | text null | 生成或设置标题所依据的 user message。 |
 | `time_title_updated` | integer null | 标题最近更新时间。 |
 | `version` | text not null | 创建 session 时的 ZCode CLI 版本;来源与根 `package.json` 注入的 `__CLI_VERSION__` 保持一致。 |
@@ -267,6 +271,8 @@ order by sequence is null, sequence, time_created, id;
 type CompletedToolPartMetadata = {
   schemaVersion: 1;
   display?: ToolResultDisplayPayload;
+  /** 工具正常返回、但模型收到的 tool_result 带 is_error(判定见 tool/00-tool-change-chain.md)时为 true。 */
+  providerIsError?: boolean;
   modelContentLayout?: Array<
     | { type: "text"; text: string }
     | { type: "attachment"; attachmentIndex: number }
@@ -303,6 +309,10 @@ SQLite 里只保存可恢复的展示投影和 artifact 引用。
 - 不需要 SQL migration:`part.data` 本来是 JSON,新增字段只改变业务 contract。
 - 旧 session 的 completed tool part 如果没有 `metadata.schemaVersion` 或 `metadata.display`,
   resume / app-server load / TUI initial transcript 必须继续展示 legacy `output`,不得报错。
+- 工具正常返回、但输出是错误结果时(Bash 非零退出、超时、取消,MCP `isError: true`),part 仍是
+  `completed`,结算时写 `metadata.providerIsError: true`;冷恢复按它还原 tool_result 的 `is_error`,
+  与 live 请求同字节。没有这个字段的旧 part 按成功结果回放(不按输出文字推断)。旧版本读到这个字段时忽略它,
+  行为与改动前相同。
 - provider history 冷恢复只有在 `metadata.modelContentLayout` 完整有效时才使用 `attachments`
   重建结构化 tool result;旧 part 缺少 layout、layout 非法或引用越界时必须继续回放 legacy
   `output`。`attachments` 单独存在不代表它属于新的 provider-visible media layout。
@@ -464,11 +474,15 @@ Provider-visible 恢复规则:
 - `user` message 只拼接未 `ignored` 的 `text` part;第一版对 `file` part 只保留可读占位,后续再接入多模态恢复。
 - `assistant` message:有序消息按 `blockIndex` 恢复不合并的 reasoning / text 块和 tool call;旧消息拼接
   `text` part,`tool` part 转回 assistant tool call。浏览器轮尾截图 tool part 不进入模型上下文。
-- `completed` tool part 转为成功 tool result;有 `state.attachments` 时从 artifact 按顺序重建
-  provider-neutral 媒体 block,没有附件时继续使用 `state.output`。
+- `completed` tool part 转为 tool result;有 `state.attachments` 时从 artifact 按顺序重建
+  provider-neutral 媒体 block,没有附件时继续使用 `state.output`。`metadata.providerIsError` 为 true
+  时带 `is_error`,否则不带。
 - `error` tool part 转为失败 tool result。
 - `pending` / `running` tool part 一律转为失败 tool result,内容为 `[Tool execution was interrupted before resume]`。这样可以避免 provider 收到 dangling tool call。
 - 没有有效文本、reasoning 或 tool part 的未完成 assistant message 不进入模型上下文。
+- 每条恢复的条目带 `time`(不进入 provider 请求):assistant message 及其 tool result 取
+  `time.completed`,缺失时取 `time.created`;其余取 `time.created`。静默提醒按它计时,规则见
+  [Meta User Context](loop/meta-user-context.md)「Silent-turn reminder」。
 
 Compact 恢复:
 
@@ -565,6 +579,7 @@ unrevert 时:
 fork 不需要复制复杂状态。
 
 - 新 session 的 `parent_id` 指向原 session。
+- 标题只从父标题计算:无末尾 `(数字)` 时追加 `(2)`;有则把该数字加一,例如 `任务 → 任务(2) → 任务(3)`。只识别末尾 ASCII 括号中的十进制数字,不查询已有同名会话;同一父任务重复 fork 可以同名。标题来源仍为 `generated`,辅助对话标题不变,历史标题不迁移。
 - `directory`、`path`、`permission` 可从父 session 初始化。
 - message/part 是否复制取决于产品行为:如果 fork 后要独立编辑历史,就复制到新 session;如果只是引用父历史,就由 context builder 读取父链。
 
@@ -690,6 +705,7 @@ interface SessionStore {
 归档管理使用独立的 V4 `storage/sessionData/deletionPreview` 与 `deletionExecute`,不改变旧软删除与项目数据清理语义。产品范围见 [归档规格](../../../../../docs/superpowers/specs/2026-09-11-archive-management.md)。
 
 - CLI 是正文与文件的唯一写者;Host 只校验归档状态并清除自己的索引。预检 revision 固定 owned tree、引用与文件清单,执行前复查。
+- 批量预检 `storage/sessionData/deletionPreviewBatch` 入参 `{ items }`,结果按顺序返回 `{ preview }` 或 `{ error: { code } }`。存储层 `inspectSessionDeletions` 每次调用对一批根只做一次 fork 扫描、一次 runtime presence 读取和至多一轮引用 SQL;预检至多调用两轮(首轮按无产物检查拿 owned tree,有产物的根再查一轮引用),命中按被引用会话归属到各自根;结果与逐个调用一致。owned tree 没有 artifact 文件、删除凭据也没有保留附件的根跳过引用扫描;预检、执行和写锁内复检用同一判定。整批存储调用抛错时逐根重查,只把仍失败的根记为单项错误。
 - `session_runtime_presence` 登记进程持有的 runtime;其他活进程持有时拒绝删除,不用超时认定进程已退出。本进程检查请求、初始化、运行任务、排队输入和交互。
 - `session_purge` 只保存目标 ID、操作 ID、目录身份、保留附件 ID 和完成状态。SQLite 事务准入与写入触发器阻止新的 runtime、正文写入、派生会话及引用。它不保存消息或标题。
 - `0025_session_permanent_deletion` 保留已发布 SQL 与 checksum。已记账的数据库继续校验后跳过;未记账但已有部分或全部同版结构时,`apply` 仅补缺失的表、索引和触发器,保留现有数据与删除凭据,再由原迁移事务记账。此守卫不改写已有同名对象,也不修复不兼容的表结构。

+ 9 - 6
apps/zcode-cli/docs/design/v2/session-title-generation.md

@@ -6,7 +6,7 @@ ZCode 目前在首次持久化 session 时直接从用户输入截断得到 `ses
 
 核心约束:
 
-- 用户标题和 AI 标题分开,用户手动标题永远优先,AI 标题只作为可重生成的增强元数据。
+- 用户标题和 AI 标题分开,用户手动标题永远优先,AI 标题是增强元数据,每个会话至多生成一次。
 - 在 root session 的首条真实用户消息后异步生成标题,并写回 session metadata。
 - 标题生成是低风险 sidecar 能力,不能影响主 agent loop,不能覆盖用户明确命名,必须进入数据库和 session event,方便本地 TUI 的 session list、resume 和 debug 复用。
 
@@ -15,7 +15,7 @@ ZCode 目前在首次持久化 session 时直接从用户输入截断得到 `ses
 1. 仅本地 TUI root interactive session 的首条真实用户消息完成后,自动生成更可读的标题。
 2. 标题生成使用 `ModelRole.Lite`。如果未配置 `model.lite`,必须使用当前默认/main 模型,不能报错或强制用户配置第二模型。
 3. 标题生成默认禁用继承自主会话的 thinking/reasoning 控制字段,避免短 sidecar 请求跟随 high/max 思考档位变慢或浪费输出预算。
-4. AI 生成标题只能覆盖默认/首输入/旧 AI 标题,不能覆盖用户自定义标题。
+4. AI 生成标题只能覆盖默认/首输入标题,不能覆盖已生成的 AI 标题或用户自定义标题。
 5. 标题结果写入 `SessionStorePort`,并由 SQLite adapter 持久化。
 6. 标题更新发出可观测的 session event,包含 traceId/sessionId/turnId/modelRef/source。
 7. 生成失败、超时、不可解析或模型尝试返回无效内容时保留当前标题,不影响主 turn。
@@ -65,7 +65,7 @@ interface UpdateSessionInput {
 }
 ```
 
-当 `expectedTitleSources` 不为空且当前 `title_source` 不在列表中时,adapter 必须 no-op 并返回当前 session。AI 标题写入使用 `["default", "first_input", "generated"]`,因此用户自定义 `custom` 不会被迟到的 AI 结果覆盖。
+当 `expectedTitleSources` 不为空且当前 `title_source` 不在列表中时,adapter 必须 no-op 并返回当前 session。AI 标题写入使用 `["default", "first_input"]`,因此已生成的 `generated` 和用户自定义 `custom` 都不会被迟到或重复的 AI 结果覆盖。
 
 ## 触发规则
 
@@ -78,7 +78,9 @@ interface UpdateSessionInput {
 3. 当前 session 为 root interactive session:无 `parentSessionId`,`taskType` 缺省或为 `interactive`。
 4. 当前 turn 是恢复后计数意义上的首个真实用户 turn。
 5. user prompt 不是 summary、compact、rewind、hook synthetic、slash command 展开或纯空白。
-6. 当前 session title source 不是 `custom`。
+6. 持久化的 session title source 是 `default` 或 `first_input`。
+
+第 4 条的 turn 计数和 runtime 内存里的“已尝试”标记都会在冷恢复时重建:compact 后 active 历史如果只剩摘要和隐藏提醒(保留段里没有真实用户消息),计数会回到 0,新 runtime 的标记也是初始值。所以“是否已生成”只以第 6 条的持久化来源为准:发请求前读一次,`generated` / `custom` 直接跳过,不发标题模型请求;写回时再用 CAS 兜住并发。例外是首次 `/goal`:它借同一个标题请求生成 goal 摘要标题,来源为 `generated` / `custom` 时仍会请求,但结果只写 goal 摘要,不写会话标题。
 
 第一版在主 turn 完成后启动异步 sidecar 请求;它不进入主 `TurnResult.usage`,但会发自己的 model request/model complete/session title event。
 
@@ -125,7 +127,7 @@ provider options 与最终 provider/model 对齐;`model.lite` 没有配置时
 系统 prompt 要求:
 
 - 生成 3-7 个词的可识别标题。
-- 跟随用户主要语言。
+- 历史里有 `language` 公告时,用最近一次公告的语言:`Write the title in <Language>. Keep technical terms and code identifiers in their original form.`;没有公告或最近一次是清除公告时,跟随用户主要语言(`Use the user's primary language.`)。会话标题与 goal 摘要标题共用这条规则。`<Language>` 从公告正文按模板反解,再用它重建正文,与原正文逐字相等才用(附件 metadata 只有来源名);不额外向 Host 读取(见 [Agent 回复语言](../../../../../docs/i18n/agent-reply-language.md))。
 - 句子式大小写;保留专有名词、文件名和技术名。
 - 不输出解释、markdown、编号、引号或多行文本。
 
@@ -165,7 +167,8 @@ interface SessionTitleUpdatedPayload {
 
 - SQLite migration 给旧 session 默认 `first_input`。
 - `createSession` 写入 `title_source`,`updateSession` 可以更新 generated 标题。
-- generated 标题 CAS 不能覆盖 custom 标题。
+- generated 标题 CAS 不能覆盖 custom 标题,也不能覆盖已有的 generated 标题。
+- 已生成标题的会话经 compact 和冷恢复后再发消息,不再发标题模型请求,标题保持不变。
 - 未配置 `model.lite` 时,标题请求使用 main provider/model 且 role 为 `lite`。
 - 配置 `model.lite` 时,标题请求使用 lite provider/model。
 - 标题请求会清洗 inherited thinking/reasoning provider options;主请求仍保留原始 provider options。

+ 11 - 5
apps/zcode-cli/docs/design/v2/skill.md

@@ -58,8 +58,8 @@
 
 ZCode skill 采用“两层加载”:
 
-1. **metadata discovery**:启动/turn 初始化时扫描 skill roots,只把 name、description、source、scope、path、policy 等轻量信息进入 context。
-2. **content load**:模型显式调用 `Skill` tool 后,才读取对应 `SKILL.md` 正文并注入当前会话。
+1. **metadata discovery**:进程级实时 skill 目录扫描 skill roots,只把 name、description、source、scope、path、policy 等轻量信息进入 context。文件监听更新内存快照,每次普通输入准备只读快照,listing 只追加新增或变化的行;规则见根目录 `docs/skills-live-catalog.md`。
+2. **content load**:模型显式调用 `Skill` tool 后,按会话快照解析名称,才读取对应 `SKILL.md` 正文并注入当前会话。
 
 这能同时满足 token 控制、权限可见、trace 可追踪和跨平台 I/O 收口。
 
@@ -88,7 +88,7 @@ ZCode skill 采用“两层加载”:
 `core` 增加 skill registry / manager:
 
 - 保存当前 session 的 skill metadata snapshot。
-- 供 context builder 渲染 available skills section。
+- 供 `skills_listing` 收集器渲染可用 skill 列表(ContextBuilder 不再渲染,见根目录 `docs/skills-live-catalog.md`)。
 - 注册 `Skill` tool contract。
 - `Skill` tool 只通过 `SkillPort` 加载正文,不直接读文件。
 
@@ -197,6 +197,8 @@ P2 增加:
 
 ## Context 注入
 
+当前实现:列表作为 `skills_listing` 附件进入会话(不在 system prompt),首发为完整列表,之后只追加新增或内容变化的行,删除不通知;格式、指纹与持久化见根目录 `docs/skills-live-catalog.md`。下文为最初的规划格式。
+
 ContextBuilder 增加 `Skills` section,位于 user/project context 之后。工具说明不再作为
 ContextBuilder section 注入 system prompt,而是随 model request 的 `tools` 数组提供。
 
@@ -250,6 +252,10 @@ Relative paths in this skill are relative to this base directory.
 </skill_content>
 ```
 
+例外:动态工作流 mode 为 onDemand 且工具面尚未激活时,加载 `dynamic-workflows` 的结果在 `<skill_content>`
+之前多一段固定提示,让模型请用户发送 `/workflow`;子 runtime(Agent 子代理、`/expert` 子会话)拿到的那段改为让它把限制报告给父代理(见 [Tool Change Chain](tool/00-tool-change-chain.md)
+「Skill 结果的工作流工具未激活提示」)。
+
 工具 metadata:
 
 - `readOnly: true`
@@ -421,10 +427,10 @@ Status: completed for P0. Node loader 已支持 native/compatible project 与 us
 
 ### Phase 3:Core Context 与 Registry
 
-Status: completed for P0. ContextBuilder 已把 available skills 渲染为独立 `meta_user` section,内置 registry 已注册 `Skill` tool,并允许在没有 `SkillPort` 时省略该 tool;session 级 loaded-skill snapshot 和 compact 恢复仍未实现。
+Status: completed for P0. 内置 registry 已注册 `Skill` tool,并允许在没有 `SkillPort` 时省略该 tool;session 级 loaded-skill snapshot 和 compact 恢复仍未实现。ContextBuilder 曾把 available skills 渲染为独立 `meta_user` section;现在列表只由 `skills_listing` 收集器渲染,ContextBuilder 只按会话开始时的目录决定 skill 引导语。
 
 - core 增加 `SkillRegistry` / `SkillManager`。
-- `ContextBuilder` 渲染 Skills section。
+- `skills_listing` 收集器渲染 Skills 列表。
 - context diagnostics 记录预算与截断。
 
 验收:

+ 565 - 19
apps/zcode-cli/docs/design/v2/tool/00-tool-change-chain.md

@@ -1,8 +1,8 @@
 # Tool Change Chain Spec
 
-工具 schema、顺序与描述是固定字节(tools 段字节进入缓存前缀):`toToolJsonSchema` 按
-zod v4 toJSONSchema 的 key 顺序输出——`$schema` 在最前,`description`、`default` 在 `type` 前,
-数组的 `minItems`/`maxItems` 在 `type` 前,属性声明顺序不变;ToolSearch 输入 schema 走同一入口。
+工具 schema、顺序与描述是固定字节(tools 段字节进入缓存前缀):`@zcode/contracts` 里的工具 JSON Schema 都由
+`toToolJsonSchema` 生成,规则见下面「工具 JSON Schema 生成」;core 里的会话控制工具与 ReadTopicResource 直接调用
+zod 的 `toJSONSchema`,ReplyToChannel 的输入 schema 是手写的。属性声明顺序不变;ToolSearch 输入 schema 走同一入口。
 SendMessage、ToolSearch 进入按名字排序的工具名单;名单外的工具按注册顺序排在名单之后;
 MCP 工具(名称以 `mcp__` 开头)按名字排序排在最后,顺序与 server 连接顺序无关。名字一律按 en-US 规则比较,
 顺序与进程的语言设置无关(同一会话换语言设置恢复时 tools 段字节不变)。WebSearch
@@ -42,6 +42,282 @@ Agent 卡片的“执行失败”hover 仍只显示原文;只影响新产生
   它的 executor 不配置 hooks,所以没有 Hook 上下文(见 [Memory](../memory/README.md))。
   单条 context 超过 10000 字符时先落盘,附件里只放 `<persisted-output>` 外壳;落盘失败时截到 10000 字符并附原因
   (规则见 hooks.md「聚合规则」)。
+  错误结果的 Hook 事件:handler 正常返回、但结果是错误结果时(`isToolOutputError`,`tool/executor/errors.ts`,
+  与 tool_result 的 `is_error` 同一判定:Bash 按命令语义的非零退出、超时、取消,MCP `isError: true`),
+  executor 只运行 `PostToolUseFailure`,`error.message` 是模型看到的 tool_result 正文,附件标题是
+  `PostToolUseFailure:<ToolName> hook additional context:`。tool_result 字节、`is_error`、`ToolCallResult` 事件和 UI 不变
+  (hooks.md「失败的定义」)。
+
+## Skill 结果的工作流工具未激活提示(2026-11-21)
+
+只改 `Skill` 工具结果的模型可见文本,且只在一种情况下:会话的动态工作流 mode 为 onDemand、工具面尚未激活、
+加载的技能名是 `dynamic-workflows`。此时结果在 `<skill_content>` 之前多一段固定英文提示
+(`DYNAMIC_WORKFLOW_TOOLS_DEFERRED_NOTICE`,core `tool/handlers/skill.ts`):工作流工具在加载这份技能的时刻
+尚未启用,不要调用它们,也不要用 Agent 代替,请用户发送以 `/workflow` 开头的消息。子 runtime(`taskType` 为
+`subagent_child`、`workflow_child`、`nested_workflow_child`,即 Agent 子代理与 `/expert` 等 workflow 子会话)拿到的是另一段(`DYNAMIC_WORKFLOW_TOOLS_DEFERRED_SUBAGENT_NOTICE`):它的工具面是创建时从父会话
+复制的,自己没有 `/workflow` 入口,所以只被告知这里跑不了工作流、把限制报告给父代理,不承诺工具会出现。原因与完整规则见根目录
+`docs/dynamic-workflow/launch.md`「On demand: activation」。
+
+链路:runtime(`helpers/runtime-tools.ts`)→ executor options/deps → `ToolExecutionContext.getDynamicWorkflowToolSurfaceDeferral`
+(同步只读探针,返回 `none` / `session` / `subagent`)→ handler。`dynamicWorkflowEnabled !== false && !dynamicWorkflowToolsActivated`
+不成立时是 `none`,成立时按 `taskType` 是否属于子 runtime 分 `subagent` 与 `session`;与注册门读同一个
+runtime 状态,不新增状态、配置或环境变量;探针缺席时不加提示。工具名、输入/输出 schema(输出仍是字符串)、
+描述、权限、Hook、事件、持久化与 V4/UI 投影不变,tools 段、系统提示、技能列表字节不变。`maxOutputBytes` 与
+`resultBudget` 加上这段提示的字节数,贴着上限的技能正文不会因此被截。提示不激活工具面,技能门仍把这次调用算作
+「已加载」。只影响新产生的结果,已发送的历史不改写。回归:core `skill-tool.test.ts`(探针三态与其他技能)、
+bootstrap `dynamic-workflow-on-demand.test.ts`(DWG-09)。
+
+## node_repl 无进展提示撤销(2026-11-20)
+
+只改 node-repl-host 内部:删除 `no-progress-guard.ts` 及其在 `tools/call(js)` 的调用,`js` 结果回到
+`toMcpRunResult` 的原样输出,不再追加「You may end this turn.」,也不写 `no-progress hint` stderr。
+schema、权限、超时、isError、图片顺序、core 的 model-anomaly 与 UI/V4 投影均不变。
+宿主行为变化,node-repl-host 升到 0.7.1(package、manifest、seed 定义、SEA 清单、serverInfo)。
+撤销原因与剩余风险见根目录 `docs/mcp-stateless-node-repl.md`「无进展提示」。
+
+## Windows Git Bash 安装发现(2026-11-19)
+
+设置候选 / CLI 既有解析入口 → Node-only 共享发现器 → 原有 selection/provider 映射。
+只扩展安装来源,修复带引号 PATH 与首个 Git 无 Bash 后提前结束的漏检;安装来源和失败继续规则见
+[Bash Effective Shell Snapshot](../../../../../../docs/runtime-tools/bash-effective-shell-snapshot.md#解析规则)。
+发现采用异步 IO,在已有初始化和执行准备边界 await;不新增探测时机,不改变设置选择、快照/缓存、
+权限、环境公告、工具 schema、prompt 或协议。回归放在既有 CLI 执行测试;App 列表以可重复运行时场景验收。
+CR-01 收紧发现边界:删除没有显式安装线索的全局 Scoop / 系统盘 `tools\\git` 兜底,防止布局伪造直接扩大自动执行来源;保留用户目录和明确线索,不把三文件布局当作信任校验。
+
+## Windows 回落 shell 按 CMD 声明(2026-11-17)
+
+Bash selection → 执行 → 权限 / Guarded → 环境公告:Windows 找不到 Git Bash 时,selection 由
+`legacy-shell` / `system shell`(无 path、无 provider,执行层另读 `ComSpec ?? cmd.exe`)改为
+`dialect=cmd`、`path=ComSpec ?? cmd.exe`、显示名 `cmd.exe` 的 auto-detected selection;手选 CMD 的显示名也由
+`CMD` 改为 `cmd.exe`。启动形态不变。权限链按 `cmd` 处理:只读判定、前缀规则与原来相同,Guarded 开始按 CMD
+语法匹配危险命令(原来 `unsupported` 直接放行),adb 准入只用 CMD 语法。环境公告在 Shell 为 `cmd.exe` 时把
+CMD 规则放进 Shell 行括号(完整块与换入 `cmd.exe` 的 update 都是,见 [meta-user-context](../loop/meta-user-context.md))。工具名、schema、描述与
+App 协议不变;tools 段字节不变。agent trace 的 `zcode.command_execution.shell_kind` 对这些用户由 `other` 变为 `cmd`
+(与手选 CMD 相同)。权限代码里处理 Windows `legacy-shell` 的分支保留(Windows 不再产出,另行清理)。
+规则与原因见 [Bash Effective Shell Snapshot](../../../../../../docs/runtime-tools/bash-effective-shell-snapshot.md)。
+
+## Git 工作流读取禁用外部 diff 与 textconv(2026-11-16)
+
+工作流 `git.diff` / `git.changedFiles` 的固定 diff argv 同时带 `--no-ext-diff --no-textconv`,
+避免只读查询启动 Git 配置中的转换命令,输出保持原始文件内容。两者是独立的外部命令通道,
+只禁用 external diff 仍会执行 textconv。输入校验、路径作用域、权限、Hook、事件、持久化与
+V4/UI 包装不变;不改写用户显式执行的 Bash 命令。回归用隔离临时仓库验证脚本不执行且返回原文,
+并更新 workflow driver 的 argv 断言。公共约束见 [Git 子进程安全调用约定](../../../../../../docs/git/architecture.md#git-子进程安全调用约定)。
+
+## iOS 项目发现不执行清单(2026-11-16)
+
+`ios_discover_project` 仅扫描项目、workspace、已有 `.xcscheme` 文件名及静态 bundle ID,
+不再启动 `xcodebuild -list -json`,避免概括项目时执行项目控制的 `Package.swift`。
+动态 scheme 列举移入已有构建工具,显式 scheme 跳过列举;构建描述明确项目代码执行。
+工具名、输入/输出字段、权限模式、Hook、事件、持久化与 V4/UI 包装不变;只更新描述与新调用结果。
+静态结果可能缺少自动生成的 scheme,不允许为补齐发现结果隐式执行构建。
+规格与回归边界见 [iOS 项目静态发现](../../../../../../docs/ios-simulator-project-discovery.md)。
+
+## Bash 前台长 sleep 拦截与描述三处文字(2026-11-15)
+
+Bash 的 `validateInput` 拒绝第一个顶层子命令是 `sleep N`(N ≥ 25 秒)的前台命令,errorCode 10,模型收到
+`<tool_use_error>Blocked: standalone sleep N. …</tool_use_error>`(`is_error: true`)。规则、文字与跳过条件见
+04-bash.md「前台 sleep 拦截」:`run_in_background: true`、执行端口不支持后台生命周期、shell 是 `cmd` 或
+`legacy-shell` 时放行,
+主会话和子代理都拦截。为此 `ToolInputValidationContext` 增加可选的 `executionPort` 与 `bashShellSelection`,
+executor 传入与 handler 相同的值。被拒的调用
+不跑 PreToolUse hook、不请求权限、不启动进程;App 工具卡显示错误原文(不带标签),与其他 `validateInput` 拒绝相同。
+
+Bash 描述改三处(04-bash.md「Prompt 约束」末尾):cd 一行写明延续规则(cd 行为不变);`run_in_background` 一行
+末尾加前台 sleep 被拒的说明;Git 段加 GitHub `@name` 通知提醒。不加署名行。tools 段升级后缓存失效一次;
+已发送的历史不改写。
+
+## 错误结果标记随 completed part 持久化(2026-11-15)
+
+工具正常返回、但输出是错误结果时(`isErrorForToolResult`,与 Hook 选 `PostToolUseFailure` 是同一判定),
+part 状态仍是 `completed`。live 请求的 tool_result 带 `is_error: true`,冷恢复原来固定按成功结果回放,
+少了这个字段:恢复后第一个请求从这条结果起缓存失效,模型还会把失败当成功。现在结算写
+`metadata.providerIsError: true`,冷恢复按它还原 `is_error`。只影响新结果;旧 part 没有这个字段,
+冷恢复行为不变,不按输出文字推断。tool_result 正文、`ToolCallResult` 事件、App 工具卡不变。
+细节见 [Session Persistence](../session-persistence.md)「Completed tool metadata」。
+
+## 工具 JSON Schema 生成(2026-11-14)
+
+工具契约 `@zcode/contracts` 与 core 使用同一个 zod 4(版本与 `packages/shared` 相同)。`toToolJsonSchema(schema)`
+(contracts `tools/json-schema.ts`)调用 zod 的 `toJSONSchema`:目标版本 draft 2020-12,`io` 用默认的 `output`,
+`unrepresentable` 用默认的 `throw`(JSON Schema 表达不了的类型,例如 bigint、date、map、set、transform、`undefined`,
+生成时直接报错;带 transform 的 schema 只用于 runtime 解析,provider schema 从不带 transform 的字段 schema 生成),
+结果保留 `$schema`。生成时逐个节点整理:
+
+1. union 的 `oneOf` 改成 `anyOf`。
+2. anyOf / allOf 的分支不合并:nullable 字段输出 `anyOf: [{…}, {"type": "null"}]`,不输出 `type: [..., "null"]`。
+3. `description` 等元数据键排在最前,其余键保持 zod 的输出顺序。
+
+object 的 `required` 直接使用 zod 的结果:最外层是 `.optional()` 的字段输出可以省略,不进 `required`;最外层是
+`.default()` 的字段在输出里一定有值,算必填。`properties`、`required`、`additionalProperties` 也按 zod 的顺序输出。
+
+工具输入 schema 的根节点是 `type: "object"`,不带 anyOf / oneOf / allOf:Anthropic API 拒绝根节点上的组合关键字
+(400 `input_schema does not support oneOf, allOf, or anyOf at the top level`),字段里的 anyOf 可以接受。组合约束
+放进 runtime schema 的 refine,由字段 description 告诉模型。core `tool-contracts.test.ts` 检查根节点,并检查 anyOf
+分支里不出现 `$ref` 等 provider 不认识的键。
+
+生成结果与目标版本对同一份 zod schema 的输出逐字节相同。带默认值、但模型可以省略的字段写成
+`.default(x).optional()`(Edit `replace_all`、ListWorkflowRuns `limit`,`limit` 的钳制 preprocess 放在 default 之内):
+字段不进 `required`,省略时 runtime 取默认值;handler 里的 `?? 默认值` 只为收窄类型,运行时不会生效。只有默认值、
+没有 `.optional()` 的字段(ToolSearch `max_results`、
+TaskOutput `block` / `timeout`、AskUserQuestion `multiSelect`)由生成结果标为必填,不再手动改写 `required`。
+
+tools 段的变化(只影响新请求,升级后第一个请求的缓存失效一次):
+
+- nullable 与 union 字段从 `oneOf` 改为 `anyOf`:CronCreate `delayMinutes`、CronUpdate `maxRuns`、AmendWorkflow
+  `max_concurrency` / `subagent_model`。
+- `.int()` 字段带上安全整数上界 `maximum: 9007199254740991`:CronCreate `maxRuns`、CreateWorkflow `max_concurrency`,
+  以及 anyOf 分支里的 CronUpdate `maxRuns`、AmendWorkflow `max_concurrency`。
+- DeferredToolCall 的输入 schema 改走同一入口(原来是未整理的 draft-07 输出)。
+- submit_result 的 `result` 标为必填(zod 4 的 `unknown()` 不是可省略的键),与 typed 声明一致;省略 `result`
+  时在执行前返回参数错误。
+- 其他工具的输入 schema 字节不变。输出 schema 不发给 provider,也随 zod 4 变化(anyOf、int 上界、带默认值的字段
+  算必填,例如 AskUserQuestion 输出的 `multiSelect`),只影响本地的输出校验。
+
+修复原因:工具契约原来使用 zod 3,由 zod-to-json-schema 生成后再整理 key 顺序,模仿 zod 4 的输出;union 被改成
+`oneOf`,默认值字段的必填规则也不同,只能逐个工具手动改写 `required`。迁到 zod 4 后直接使用 zod 的生成结果,
+只保留上面 3 条整理。
+
+运行时报错使用 zod 4 自带的英文默认文字(例如 `Invalid input: expected string, received undefined`),不设自定义
+error map;首次输入校验直接使用 runtime issues,不再把 zod 3 issue 投影成 zod 4 结构(根目录
+`docs/model-tool-call-validation.md`)。
+
+## 工具错误的包装与文字(2026-11-14)
+
+分界不变:未知工具、无法解析的 JSON、schema 失败、`validateInput` 拒绝,以及 handler 返回的可预期失败
+(`{ result: false, errorCode, message }`)由 executor 包成 `<tool_use_error>…</tool_use_error>`;权限拒绝、hook 拒绝、
+handler 抛出的 I/O 异常不包装。App 显示的仍是 `error.message`(不带标签),所以只改包装时 UI 不变,改文字时 UI 跟着变。
+只影响新产生的结果,已发送的历史不改写,冷恢复读取持久化的 `modelContent`。
+
+只改包装(文字不变,原来是抛出的异常):
+
+- Write:已有文件没读过 `File has not been read yet. Read it first before writing to it.`(`errorCode` 2);读后被改过
+  `File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.`(3)。
+  Edit 的同两种情况原来就包装,Write 现在与它相同。检查时机不变,仍在 handler 里、权限之后。
+  截断后注入上下文的 MEMORY.md(模型只看到开头)也用“没读过”这句,不另写“改用 Edit”:Edit 同样要求先完整读过,
+  照那句去做会再失败一次。
+- TaskStop:`Task <id> is not running (status: <status>)`(3);`Missing required parameter: task_id`(1)。
+- DeferredToolCall 准入失败的 4 句(1),见 19-tool-search.md。
+
+包装并换文字:
+
+- Skill 找不到(目录重读之后仍未命中,所以在 handler 里判定):`Unknown skill: <name>`;目录里有名称或限定名与它的
+  编辑距离不超过 2 时,取最近的一个(距离相同取目录里靠前的):`Unknown skill: <name>. Did you mean <other>?`(2)。
+  `skill` 去掉空白后为空:`Invalid skill format: <skill>`(1,`validateInput`)。adapter 抛 `SkillNotFoundError`,
+  CLI 命令的 `Skill not found: <name>` 不变。子代理与主会话相同:名称不在它能看到的目录里(含 `skills` 白名单过滤)
+  时同样报 `Unknown skill`,`Did you mean` 只从它能看到的目录里选,不提示它不能用的 skill。
+- TaskStop 找不到任务:`No task found with ID: <id>. This lookup failure does not mean the task has completed or stopped;
+  use the full task_id returned when the task started to stop it.`(1)。不列出运行中的任务。
+- Write(02-write.md):目标是目录、不是普通文件时各有专用文字(17 / 18)。
+- Edit 遇到不能按 UTF-8 或 GB 编码读出的文件:专用文字(15,03-edit.md)。
+- Read 二进制扩展名与设备文件:只换文字,扩展名表不变(01-read.md)。
+- 无法解析的工具 JSON:`InputValidationError: <tool> was called with input that could not be parsed as JSON.…`
+  (根目录 `docs/model-tool-call-validation.md`「Malformed tool input JSON」)。
+
+只换文字(不包装的错误、成功输出,或原来就包装的错误):
+
+- PreToolUse hook deny 没有理由:`Hook PreToolUse:<Tool> denied this tool`;hook 以退出码 2 阻断:
+  `PreToolUse:<Tool> hook error: [command hidden]: <stderr>`,不写 Hook 命令,命令可能带凭据(根目录
+  `docs/hooks-runtime-contract.md`)。
+- hook 改写后的输入不符合 schema:`PreToolUse hook for <tool> returned updatedInput that failed schema validation: <逐条问题>`
+  加一行 `The tool input from the model was valid; the hook's rewrite of it was not.`。
+- InputValidationError 的逐条问题补上其他 issue 行,嵌套的多余参数写出路径(`docs/model-tool-call-validation.md`)。
+- Edit:未找到 old_string 的转义说明、`.ipynb`、文件过大(03-edit.md)。Read PDF `pages` 格式错(01-read.md)。
+- SendMessage 目标不存在(07-subagent.md)。
+- 没有审批客户端:`ZCode requested permissions to use <Tool>, but you haven't granted it yet.`;Write / Edit 写
+  `ZCode requested permissions to write to <file_path>, but you haven't granted it yet.`。Guarded 模式仍抛
+  `No permission client configured for <Tool>`。
+- `disallowedTools` 拒绝整个工具:`Permission to use <Tool> has been denied.`。项目权限规则的拒绝可能只针对部分输入,
+  文字不变。
+
+用户拒绝并附反馈时的文字不变:保留 `STOP what you are doing and wait for the user to tell you how to proceed.`,
+再接 ` To tell you how to proceed, the user said:\n<反馈>`。这句是有意保留的:模型要先停下当前操作,再按用户的说明继续。
+
+工具 schema、描述、tools 段字节、权限规则、事件与 App 协议不变。
+
+## 工具错误包装与 Read 输入修正(2026-11-13)
+
+- 未知工具:`call-runner` 的 registry miss → `describeUnavailableTool` 后缀 → `<tool_use_error>Error: No such tool available: <name><后缀></tool_use_error>`。
+  后缀原来只覆盖 MCP;现在加上 Grep/Glob 换 Bash、内置工具在本上下文未注册(子代理与其他两句)、大小写写错三类,
+  判定顺序见根目录 `docs/model-tool-call-validation.md`「未知工具的后缀」。
+- 未发现的 deferred 工具参数校验失败:纠错段落从 `</tool_use_error>` 之后移到包装之内(19-tool-search.md)。
+- Read:runtime schema 的 preprocess 在校验前修正 `offset` / `limit` / `length`,数字字符串先转成数字
+  (01-read.md「输入修正」),修正后的输入进入 JSON Schema 校验、hook、权限与 handler。
+- 首次输入校验:JSON Schema 通过但 runtime schema 失败(URL / regex 格式、`exclusiveMinimum`、去空白长度、refine)时,
+  executor 在 `validateInput`、hook 与权限之前返回 `InputValidationError`,不再到 handler 抛原始 ZodError JSON;
+  JSON Schema 与 runtime 同时失败时,runtime 报出的问题不再丢弃。hook 的 `updatedInput` 因此不能修正这类原始输入。
+  规则见根目录 `docs/model-tool-call-validation.md`。
+  需要友好文字的语义检查改由 `validateInput` 完成,文字不变:Read 的二进制与设备文件(`errorCode` 4 / 9,`error.message`
+  不再带标签,01-read.md)、SendMessage 空白 `message`;WebSearch 两种域名同时给出时新增本地拒绝(13-websearch.md)。
+  hook 改写后的输入由这三个工具的 handler 再检查一次。
+
+工具 schema、描述、tools 段字节、权限规则与 App 协议不变。被提前拒绝的输入(上面的 runtime 校验失败与 `validateInput`
+失败)不再发出 ToolCallStarted、权限请求、PreToolUse 与 PostToolUseFailure,只有 ToolCallError;其余调用的事件不变。
+只影响新产生的结果,已发送的历史不改写,冷恢复读取持久化的 `modelContent`,与实时请求相同。
+
+## 独立 CLI 的 Computer Use(2026-11-13)
+
+`mcp__node_repl__js` 的 schema、描述、权限、事件与 App 协议不变;只改执行环境。终端直接运行的顶层
+CLI(非 protocol server,darwin 或 win32)在没有宿主 CUA 凭据时自签凭据组,socket 用哨兵值 `in-process`;
+node_repl-host 见到哨兵值时在本进程内运行 broker,不连外部 Helper。protocol server(桌面、远程)
+行为不变。规则见 [cua-standalone-in-process-broker.md](../cua-standalone-in-process-broker.md)。
+
+## Bash 图片输出必须解码成功(2026-11-12)
+
+Bash handler `prepareBashImageOutput` → `BashOutput.isImage` → `formatBashModelContent` 的 image block:
+原来 resize 解码失败后,只要 magic bytes 与声明类型一致,就把原 data URI 当图片发出。截断或损坏的图片
+(例如 stdout 是截断的 `data:image/png;base64,…`)头部完好,会被当成 image block 发给 provider;provider
+拒绝后,坏图作为附件持久化,冷恢复也照样重放,会话后续请求全部失败。现在声明类型必须与 magic bytes 一致,
+resize 必须成功,否则回退文本;WebP 不解码,另按 RIFF 头声明的文件总长(长度字段 + 8)检查截断。这些条件能发现
+截断,但 WebP 和会容错的 JPEG、GIF 解码器发现不了所有内容损坏。工具 schema、
+描述、权限、事件与 App 协议不变;只影响新产生的结果,已写入历史的坏图不改写。回归覆盖解码失败、类型不一致、
+伪造 WebP、截断 WebP 回退文本,完整 WebP 仍是图片,以及 Jimp 适配器拒绝截断的 PNG、JPEG、GIF。上述回退依赖的
+两条适配器行为(解码失败必须抛错、WebP 原样透传)写在 `ImageProcessorPort.resizeToFit` 的接口注释里。
+规则见 04-bash.md「输出契约」。
+
+## MCP 结果去重(2026-11-11)
+
+MCP server 工具 / MCP Apps app-provided 工具 → 公共 MCP 结果投影 →
+有模型可见 content 时选 content,否则回退 structuredContent → 原有结果预算 →
+modelContent 持久化与模型请求。每次仅选一种表示,适用于所有 server 与工具名。
+content 中的文本、图片和资源继续投影,错误标志沿原有错误路径处理。
+CUA producer 将模型需要的恢复详情同时写入 content,应用继续读取结构化字段。
+模型历史使用已经投影的内容,旧历史沿原格式读取。原始结果继续供现有消费者使用。
+回归覆盖注册入口、单字段兼容、空值、多模态和 runtime 下一轮请求。具体规则见 [MCP](../mcp.md#tool-contract)。
+
+## 读取状态快照只存正文哈希(2026-11-11)
+
+`Read`、`Write`、`Edit` 与内联草稿成功后写入 tool part metadata 的 `readFileState` 快照用
+`contentSha256`(live 记录正文的 sha256,按 UTF-16LE 编码计算,与比较字符串等价)代替 `content` 全文,不升 `schemaVersion`,按字段是否存在区分新旧。
+冷恢复或同进程 rewind 从新快照重建的记录只有哈希;写前 stale 校验在 mtime 前进时比较 `sha256(当前内容)`,结果与原来比较正文相同。
+没有 `contentSha256` 的旧快照不迁移,冷恢复或 rewind 重建后照旧带正文比较;旧版本 CLI 读到新快照会跳过恢复。live 记录仍存
+正文,内存只留哈希是后续一步。schema、description、权限、副作用声明、模型可见结果、事件、V4 与 UI 不变;
+`readFileState` 在协议投影前删除。根因与规则见 [17-read-file-state-resume.md](17-read-file-state-resume.md)「快照不存正文」。
+回归:core 读取状态快照与 runtime 冷恢复、rewind 重建测试,`e2e/compact-microcompact` 的 `read-state-hash-resume` case。
+
+## Skill 名称解析读会话目录(2026-11-10)
+
+`Skill` handler 不变,仍调用 `SkillPort.loadSkill`;协议入口、TUI、headless 装配的端口改为读进程级实时 skill 目录
+(`adapters/src/skills/catalog.ts` 的 `createCatalogSkillPort`):按 `name` 或 `qualifiedName` 查会话快照,未命中时 flush 一次再查,
+仍未命中时模型收到 `<tool_use_error>Unknown skill: X</tool_use_error>`(2026-11-14 起,见上面「工具错误的包装与文字」);命中后只读该 `SKILL.md` 正文,截断上限不变。名称不再按当前工作目录重扫
+磁盘,所以 Bash `cd` 之后子目录 `.zcode/skills` 里的 skill 不再能加载,listing 与工具结果保持一致。
+schema、description、权限、副作用声明、事件、V4 与 UI 不变;tools 段字节不变。workflow child 仍用创建时的端口。
+合同见根目录 `docs/skills-live-catalog.md`。回归:adapters catalog 端口测试与 core skill 目录 runtime 测试。
+
+## 会话列表 compact 活动摘要(2026-11-12)
+
+```text
+CompactStarted / CompactCompleted / CompactFailed
+  -> ProductProjection.control.activeWorks
+  -> SessionsIndexProjection.hasCompactWork
+  -> sessions-index upsert -> Host 关闭保护活动计数
+```
+
+`SessionSummary.hasCompactWork` 只由当前 `activeWorks` 中的 `kind === "compact"` 派生,
+不改变 phase、工具执行或权限。新 CLI 总是输出布尔值;字段可选以兼容旧帧,缺失按 false
+判等,冷存储摘要固定为 false。开始与结束必须参与摘要判等并产出 upsert,其他 activeWorks
+不置位。列表仍是 conflated 最新态,不新增执行状态或持久化活动标记。完整合同见根目录
+[会话列表规格](../../../../../../docs/v4-refactor/14-sessions-index.md)。
 
 ## Agent 同步失败附部分报告与 agentId(2026-11-09)
 
@@ -67,6 +343,44 @@ stack 不变、wrapper 分支同样带交接;watchdog 超时追加且类型仍
 而不是失败原因。workflow 失败通知不带 `<note>`,它的 `<result>` 照常读取。回归覆盖:core 后台失败通知带部分报告、没有正文时不带;BG26 合并
 通知用例里先写正文再 429 的子代理,父模型收到的通知带这段 `<result>`,失败 hover 不出现它。规则见 07-subagent.md「后台终态通知」。
 
+## SendMessage 不在上一次运行未结束时恢复(2026-11-10)
+
+SendMessage → `sendMessageToLocalAgent` → terminal task → `resumeTerminalAgentInBackground`:恢复前查 port 按 child session 记下的
+`runExploreAgent` 执行 promise,还在就返回结构化失败,不改 registry 终态,也不起新 runtime。原来只看 registry 是否终态:看门狗超时、
+TaskStop 或 App 停止时 runner 先提交 failed / killed,child runtime 还在收尾(abort 后也可能一直不 settle),这时恢复会在同一个 child
+session 上同时跑两个 runtime。同步失败开始交出 agentId 后,看门狗超时的子代理也能被立即续接,这个窗口因此变大。工具 schema、描述与
+成功文案不变;只在旧运行未结束时多一种失败文案。回归覆盖:看门狗超时、停止后 child 未结束时 SendMessage 被拒且只跑过一次 child;
+child 结束后同一 agentId 正常恢复。规则见 07-subagent.md「SendMessage 当前范围」。
+
+## SendMessage 冷恢复后按 metadata.json 找回子代理(2026-11-10)
+
+SendMessage → `sendMessageToLocalAgent`:registry 里没有 `to` 时,按父 transcript 里 Agent part 记下的 `outputFile` 读同目录的 `metadata.json`(与恢复时的中断对账、
+新 part 的子代理投影共用 `readSubagentRunMetadata`),重建终态 task 快照后走原来的 `resumeTerminalAgentInBackground`。registry 只在进程内存里:App
+重启、进程崩溃、session 闲置被常驻池关闭后再打开,之前的子代理都不在 registry 里,原来直接返回 `No active local_agent task found`,父模型拿着
+transcript 里的 agentId 也无法续接。`running` 的 metadata 只在 child session 于本进程启动前就不再写入时当作 `failed` 恢复(与中断对账同一判断,
+判断用 `readChildSessionUpdatedAt` 读 session store),否则可能是别的进程在跑它,不恢复。工具 schema、描述与文案不变。回归覆盖:上一个 port
+留下的 completed / failed / stopped 子代理在新 port 里续接、成功文案带对应状态;改过存储目录(新 port 的输出根目录不同)后仍按 transcript 记下的路径找到,恢复的运行写回原目录;transcript 里没有、metadata 被删、属于别的父会话(`metadata.json` 里的 `parentSessionId` 不一致)、child session 不存在、`running`
+且 child 刚写入时返回找不到;两次并发 SendMessage 只起一个 runtime;完整 runtime 关闭再打开、resume 之后续接同一个 child(Agent 在 compact 之前派生:改成只用 active 分支建索引时这一条变红)。索引在 resume 时从已读出的全部消息里建(`agentId → outputFile`,只在内存里),同步、后台的 Agent part 都在 child 就绪时记下 `outputFile`;新数据的 `readSubagentRunMetadata` 只按 `outputFile` 读;按 `<outputRootDir>/<父会话>/<agentId>` 推算目录留给没有结构化字段的旧 part(`readLegacySubagentRunMetadata`),以及没有 `outputFile` 的 task 快照续接(runner 写下的快照都带)。找回结果(含不恢复的原因,`metadata_mismatch` 带对不上的字段名)与旧运行未结束时的拒绝都写 info 日志,回归测试检查日志里的 `outcome` / `reason`。`running` 只按 child 最后写入时间判断,另一个进程执行长时间不写盘的工具时会误判,不做进程存活检查,作为已知限制写进 07-subagent.md。规则见 07-subagent.md「SendMessage 当前范围」。
+
+App 行:runner child session 就绪 → launch 选项 `onChildSessionReady` → Agent 工具 `recordSubagent` → 执行器挂到
+`ToolExecutionResult.subagent`(成功、失败分支都挂)→ 结算写 `part.metadata.agentId` / `childSessionId` → 冷加载
+`subagentInfoFromToolPart`、子会话目录查询读这两个字段。原来身份不落盘,读的一侧只能从模型可见文本的 `agentId:` 行里正则查找;
+同步失败的 Agent part 是 `error` 状态,这一行只在 `state.metadata.modelContent` 里,读不到时行身份退回 tool call id、没有 child
+session,续接的 `SubagentSpawned`(真实 agentId、SendMessage 的 call id、另一轮)匹配不上,多出一行。回归覆盖:同步完成、同步失败、
+后台启动的 Agent part 都带结构化身份,child session 就绪前失败的不带;bootstrap 冷加载与子会话目录按 error 状态 part 上的身份得到 agentId 行身份、子会话入口与 failed 状态;桌面 SAT32 覆盖 App 重启后续接失败的 Agent 只有一行,挂在原 Agent
+卡片上并带子会话入口。这两处读的一侧先读结构化字段:文本格式改过多次,旧格式会读到子代理报告里的 id,结果超长被截断时这一行会丢;
+升级前写下的旧 part 没有结构化字段:冷加载读不到结构化 `agentId` 时走原来的 `agentId:` 正则,子会话目录查询与崩溃对账三项不全时走原来的逻辑,都与之前一模一样。
+
+后台启动与输出文件同样落成结构化字段:`outputFile` 随身份在 child 就绪时报告(同步、后台都有);launch 返回 `async_launched`(显式后台、profile 后台、前台转后台)时
+Agent 工具再记一次,结算写 `part.metadata.background: true`(与启动回执出自同一个 launch 返回值)。恢复时的崩溃对账(`collectPreviousRuntimeAgentInterruptions`)
+与子会话目录查询(`candidateFromToolPart` / `loadPreviousRuntimeRunMetadata`)改读这两个字段。原来父代理没有
+`Read` / `Bash` 时回执不带 `output_file:` 行,只能按当前配置找 `metadata.json`,用户改过存储配置就找不到。子会话目录查询与崩溃对账要 `part.metadata` 上 `agentId`、`childSessionId`、`outputFile` 三项都在才按新 part 读
+(判据是 core 的 `hasStructuredSubagentFacts`,两处共用),否则是旧 part,保留原来的逻辑(回执前缀、`agentId:` 与 `output_file:` 正则,
+没有 `output_file:` 时按当前存储配置推算的目录:V4 sessions 查询与 TUI 观察用 `resolveOutputRootDir`,对账用 runtime 配置的 `outputRootDir`;对账的 child session 没有记录时按 `sess_subagent_<agentId>`),读文件用 core 的 `readLegacySubagentRunMetadata`(原来的读取逻辑改名后
+原样保留;同名的 `readSubagentRunMetadata` 现在只按记录的 `outputFile` 读,只给新 part 用);续接时 task 快照没有 `outputFile` 也照旧按配置推算目录。修复原因(2026-11-11,!3624 评审 CR-01):只读结构化字段时升级前的 Agent 行
+冷加载后没有子会话入口、子会话目录不列出它们;崩溃对账跳过旧 part,升级前崩溃遗留的后台 Agent 收不到「被中断」提醒,界面却已按旧逻辑显示它结束(staging 原有的 15 个对账用例在只认结构化字段时 7 个失败)。App 侧 Agent 卡片的输出文件、legacy 任务流的后台启动判断仍读回执文本,没有改。回归覆盖:同步与后台的 part 都带 `outputFile`,后台启动与前台转后台的 part 还带
+`background`,同步的不带;staging 上原有的冷加载、目录查询与崩溃对账旧夹具用例原样保留并通过,结构化字段的用例另外新增。
+
 ## Agent 空报告回退到最近一段正文(2026-11-09)
 
 child turn → `runAgentToCompletion` → `AgentCompletedOutput.content` → Agent 工具结果 / 后台 task-notification:
@@ -107,18 +421,31 @@ running、completed / error 每次写入都必须带上调用对象的 `blockInd
 不进入模型历史。工具 schema、权限、事件和 V4 协议字段不变。详见
 [Assistant 内容块顺序](../model/assistant-block-order.md)。
 
-## CMD 自动授权收紧(2026-11-09)
+## CMD 自动授权收紧(2026-11-09,2026-11-13 恢复按 CMD 语法的只读判定)
 
 session 固定的 `bashShellSelection` → Bash runtime capability / command permission policy →
-既有审批 → ExecutionPort。明确选择 `cmd` 或 `legacy-shell` 时,不再用 Bash AST 授予只读免审批,
+既有审批 → ExecutionPort。明确选择 `cmd` 或 `legacy-shell` 时,不能用 Bash AST 授予只读免审批,
 也不通过其 prefix/wildcard 推导自动 allow;授权建议只保留完整命令。根因是 Bash 会将 `#` 后的
 CMD 命令当成注释,使审批看到的操作少于实际执行的操作。能力事件也传递同一 shell 选择。
-Build/Edit 无明确授权时请求审批,Plan 拒绝;完整命令授权、工具级显式授权及 yolo/guarded
-的既有模式语义保持不变。deny/ask 的既有规则匹配保留,本次不扩展 CMD 解析器,不能据此宣称
-已支持完整 CMD 子命令 deny 匹配。POSIX/Git Bash 和未传 selection 的旧内部调用沿用原行为。
-不改工具 schema、命令执行、权限事件字段或桌面/手机投影。回归覆盖截图形式的命令、普通只读
-CMD、前缀/通配授权不放行、完整授权、Plan 拒绝、审批拒绝前执行端零调用以及能力事件。
-细节见 [Bash](04-bash.md#权限模型)。
+完整命令授权、工具级显式授权及 yolo/guarded 的既有模式语义保持不变。deny/ask 的既有规则匹配保留,
+不能据此宣称已支持完整 CMD 子命令 deny 匹配。POSIX/Git Bash 和未传 selection 的旧内部调用沿用原行为。
+不改工具 schema、命令执行、权限事件字段或桌面/手机投影。
+
+2026-11-13:上面的收紧让 CMD / Windows 回落 shell 用户在 Plan 下连 `dir`、`git status` 都被拒(Explore 子 agent 继承
+Plan,探索基本不可用),Build 下每条都要审批。现按实际执行语法恢复只读:`bash-cmd-readonly-policy.ts` 只在实际执行器
+是系统目录里的 cmd.exe 时(Windows 的 `cmd` 或 `legacy-shell`,shell 路径 realpath 后等于 `%SystemRoot%\System32\cmd.exe`
+或 SysWOW64 下的 cmd.exe,裸名 `cmd.exe` 不认)按 CMD 语法判定,
+只接受白名单字符组成的单条简单命令,命令限 `dir`、`type`、`findstr`、`where` 和 git 只读子命令;外部程序要求工作目录和
+PATH 里位于工作区内的目录都没有同名程序、PATH 条目都是带盘符的完整路径;拒绝 UNC / `\??\` 路径和设备名。判定为只读的 Plan 放行、Build/Edit 免审批、能力事件报
+`readOnly`;其余仍是 Build/Edit 请求审批、Plan 拒绝。POSIX 上的 `legacy-shell`(`/bin/sh`)仍不给只读。
+回归覆盖截图形式的命令、命令连接/管道/重定向/变量/转义、同名程序、UNC、设备名、前缀/通配授权不放行、完整授权、
+Plan 拒绝、审批拒绝前执行端零调用以及能力事件。规则与白名单见 [Bash](04-bash.md#read-only-bash-allowlist)。
+
+2026-11-16(ZP-20261103-14):Memory Agent(Extraction、Dream)的工具策略原来直接调 Bash AST 只读判定,
+不看 shell 选择;它的 executor 以 yolo 执行,CMD 会话下同样能用 `type # & ...` 在后台执行任意命令。
+现在会经 cmd.exe 执行时(`cmd`,或 Windows 上的 `legacy-shell`),策略改用上面的 CMD 只读判定,Memory 的 `rm` `.md`
+白名单也不放行;其余 shell 保持原来的 Bash AST 判定,包括 POSIX 上回落到 `/bin/sh` 的 `legacy-shell`(`#` 同样是注释,
+绕过不成立,不因本次修复收紧)。策略和 executor 读同一份 shell 选择快照,见 [Memory](../memory/README.md)。
 
 ## Bash 注入会话上下文环境变量(2026-11-01)
 
@@ -224,6 +551,47 @@ dwf 子代理每个 ask 的 `WebSearch` 调用次数有上限:默认 128,per
 工具 schema、描述与 tools 段字节不变;只改权限之前的结果。已结束的 run 仍可从别的会话修订,经确认窗。
 规格见 `docs/dynamic-workflow/launch.md`「Approval」「Amending this session's runs」。
 
+## 立即发送时前台 Agent 转后台(2026-10-29)
+
+立即发送(`stopActiveForegroundExecution` 带 `preserveQueueAutoDrainOnCancel: true`)→ abort 原因
+`InputPreemptionAbortReason`(contracts errors,`kind: "input_preemption"`)→ turn abort scope → executor
+`executeWithTimeout` → Agent handler 的 `abortSignal` → subagent runner 的 task abort。
+executor 为每次工具调用建一个接管点(core `InputPreemptionSlot`)。工具上下文 `ToolExecutionContext.inputPreemption`
+只暴露它的 `register`(contracts tools/contract `InputPreemptionControl`),带 `decide` 的接管点由 executor 直接交给
+`executeWithTimeout`:判断函数有副作用(能转后台时会转后台),handler 不能调用它(2026-10-30)。
+Agent handler 把它经 `SubagentRunOptions.inputPreemption` 传给 runner,
+runner 注册判断函数。这个原因到达时 executor(前台等待中还有 runner)在同一次 abort 里调用这个判断函数:`wait` 时 executor 不判取消、
+等 handler 返回;`cancel` 或没有注册时照旧立即取消。只有前台等待中(runner 在等 child 完成或转后台请求)才认领:
+`registry.requestBackground` 成功就转后台,runner 在几个微任务内返回 `async_launched`(executor 照常 `trackBackgroundTask`,
+完成后发 `<task-notification>`);启动阶段、收尾阶段(child 已完成、失败或闲置超时)、deny 或任务已结束时取消,和改前一样。
+等待不论从哪个出口结束,都先关闭认领、再读 registry;前台等待中转后台与 child 完成或失败先后发生时以 registry 为准走后台分支;runner 已收口时 tracker 不再写
+`BackgroundTaskStarted`(2026-10-30,见 turn-steering)。认领后 Agent 的结果总是很小的 `async_launched`,
+不写 artifact;PostToolUse hook 用 turn 传入的 signal(已中止,hook 记为取消、工具结果不变),立即发送不等 hook。
+工具 schema、描述、权限声明、tools 段字节、事件类型和 V4 投影都不变:Agent 行显示与 `run_in_background` 相同的启动结果,
+后台面板出现该任务。Stop、编辑重试、闲时停止、断连仍取消前台 Agent。规则见
+[turn-steering 前台子代理转后台](../loop/turn-steering.md#前台子代理转后台2026-10-29)。
+
+## 前台 Agent 启动阶段停止的终态事件(2026-10-29)
+
+前台 Agent 在 child 就绪前被停止、超时或启动失败时,父会话的子代理事件和 Agent 结果都只按 registry 决定,
+与就绪后的主 catch 用同一个判断:
+
+- `onSessionReady` 发起 `SubagentSpawned` 写入前同步读 registry。本次执行的任务已移除、换了执行或已是终态
+  (`stopTask` 已收口为 killed)时,不写 Spawned,并拒绝,让 child 收尾。
+- 启动阶段的 catch 读 registry。本次执行已是 killed:保留这条记录,由 `stopTask` 写 `SubagentStopped(stopped)`,
+  Agent 结果是 `ToolCancelled`(`Subagent was stopped by user`,与主 catch 相同),不看先到的是哪个错误。
+  其他情况:移除记录(记录已属于另一次执行时不碰它);Spawned 已开始写时,等它写完再补一条 `SubagentStopped`(`failed`,错误文字与前台失败
+  相同,取 `selectExecutionErrorMessage`);没开始写就不补。
+- 读 registry 与发起写入、`stopTask` 改 registry、catch 读与移除 registry 各在一段同步代码里,event store 在
+  发起写入时分配序号,所以不需要计时,也不会出现 Spawned 排在终态之后。
+
+修复原因:2026-10-29,child 的持久化照样做完并写出 Spawned,却没有终态,投影留下一个一直运行的子代理。
+2026-10-30,`stopTask` 先收口时 catch 又补写 failed,同一个子代理有两条终态。2026-11-12,`stopTask` 要等
+`SubagentStopped(stopped)` 写完才取消前台 child,这期间 child 就绪仍写出排在终态之后的 Spawned;catch 读到
+killed 后仍移除记录,owner close 时 `stopTask` 写完产物读不到记录就不写终态;`onSessionReady` 拒绝用的普通
+Error 原样成为 Agent 结果,单项停止的子代理显示成失败。Agent 工具 schema、tools 段字节和 V4 投影规则都不变;
+就绪之后的停止与转后台路径不经过这里。规则与已知限制见 [07-subagent.md](07-subagent.md) 执行流程第 11 步。
+
 ## 会话 ID 兼容(2026-10-28)
 
 普通新建恢复 `sess_${crypto.randomUUID()}`(UUID v4);已持久化的 `session_` 身份不变。
@@ -320,7 +688,38 @@ or data processing work; use the dedicated tools”)。import 说明去掉 “
 缓存失效一次。node-repl-host 版本不升:server.js 的 buildIdentity 每次构建都变,官方 seed 会重新落盘。
 合同见根目录 `docs/mcp-stateless-node-repl.md` §2。回归:`node-repl-host/test/mcp-server.test.ts` 的描述断言。
 
-## node_repl 无进展提示(2026-10-26)
+## WaitForMcpServers 与连接中工具等待(2026-10-30)
+
+合同见根目录 `docs/mcp-async-tool-catalog-cache.md`「请求与搜索 / ToolSearch 关闭时」「执行时不可用」。链路:
+
+```text
+普通 step -> mcpServerStatusFacts.pending / 锁存 -> getTools(model) 可见性(只在 ToolSearch off)
+         -> 按名字排序名单(WebFetch 之前)-> 模型请求;主 agent 请求含它时锁存
+WaitForMcpServers -> 会话视图分类 -> McpPort.waitForServer(≤5 s,不重连、不授权)-> 分行文本,ready=false 时 is_error
+未注册 mcp__S__t -> 最新视图有该工具:临时 registry 构造 entry 正常执行
+                 -> S 首次连接中:waitForServer(同一 assistant 回复共用 10 s)-> 再查最新视图
+                 -> 仍没有:No such tool available + 后缀(有 WaitForMcpServers 时指向它)
+```
+
+- 定义:contracts 新增 schema 与工具名;core handler 只读会话视图并调用端口,不直接依赖 pool。输入 schema、description 与结果文本是固定字节,全文写在合同里;需要授权与 disabled 两行指向 ZCode MCP 设置。
+- 注册:会话有 MCP 端口时注册(与 MCP 会话同门),工具名单(allowlist)可排除它;可见性只在请求时按状态事实与锁存判定。
+- 权限:只读、`sideEffectScope: none`、无需审批;不可并发,所以不在流式阶段执行。
+- 执行器:只在 registry 缺失且名称是 MCP 工具时介入;构造 entry 用一份临时 registry 和下一个 step 相同的选择规则,不改本 step 的 registry、不改 `offeredMcpTools`。权限、Hook、事件与结果结算走原路径。`responseId`(assistant 消息 id)经 batch/schedule 传到单次调用,用于共享等待预算;等满完整预算后按连接状态的 `updatedAt` 记下这次连接。
+- 事件与 UI/V4:没有新增事件类型或字段;App 用通用工具行展示。`tools` 名单记录只在有 pending 或已锁存时包含它。
+- system prompt:不提到这个工具;guidance 只看 Skill 等固定名称,不受影响。
+- 缓存:没有 MCP 的会话 tools 段不变;ToolSearch 关闭且有 pending 时 tools 段多出它,之后锁存保持;冷恢复后没有 pending 时消失一次。
+- 子 agent:按自己的 pending 判定可见性,不继承锁存;超时后缀只在主 agent 指向 `WaitForMcpServers`。
+
+## node_repl frontend 自动重启(2026-10-29)
+
+只改连接恢复:宿主注入的 `node_repl` 配置带运行时来源 `builtin`;frontend 进程意外退出时,MCP adapter
+复用远程断连的后台恢复(保留目录、立即重启、最多 5 次),10 分钟内最多自动重启 5 次;超过后进入 failed
+但保留目录,下一次工具执行准入时重启一次,失败才清空目录。
+判定按运行时来源 `builtin`,官方市场插件声明的 stdio server 同样适用。
+工具定义、schema、权限、超时、node-repl-host 版本与 UI/V4 投影均不变;其他来源的 stdio MCP 仍直接进入 failed。
+合同见根目录 `docs/mcp-stateless-node-repl.md`「共享、回收与日志」与 `docs/mcp-async-tool-catalog-cache.md`「连接记录」。
+
+## node_repl 无进展提示(2026-10-26,2026-11-20 撤销)
 
 只改 node-repl-host 内部:`tools/call(js)` 按 `session_id + turn_id` 计同码、同结果与本 turn 调用量,
 命中档位时在 `toMcpRunResult` 之后的 content 末尾追加一行「You may end this turn.」提示。
@@ -608,6 +1007,22 @@ macOS 与 Windows 原生进程证据及手机待验证边界见根目录 coverag
 同日补充 executor 执行边界、真实 Hook 结果 SQLite 冷恢复、搜索细分输入、开启状态空引用
 投影的单测。E2E/单测不得为测试修改生产实现或新增测试专用入口;只复用既有依赖契约。
 
+## MCP 动态目录与实时搜索
+
+完整合同见根目录 [动态 MCP spec](../../../../../../docs/mcp-async-tool-catalog-cache.md)。改动 MCP 工具链路时按下列链路检查:
+
+```text
+配置事件 -> 完整配置快照 -> session reconcile -> pool 租约 -> adapter 连接记录
+普通 step -> 固定快照 -> registry -> deferred_tools_delta -> 模型请求
+ToolSearch -> 实时目录 -> 无匹配时有限等待 -> tool references
+执行 -> classifyServer 准入 -> 晚绑定当前 client -> 会话过期/连接关闭时重连并重试一次
+```
+
+- 配置身份统一使用 `mcpConfigKey`;可用性统一由 `classifyServer` 判定,目录、状态事实、执行准入、报错文本和撤销原因不各自判断。
+- 模型工具调用不固定连接身份;MCP App 调用固定连接身份与 generation,不重试。
+- 状态事实为 pending、needs-auth、failed,并入 ToolSearch delta;compact 重建不写状态、不计算撤销。旧 `mcp_server_status` 只保留在历史存储,不再投影给模型。只有状态的公告不写严格的 `toolSearchAnnouncement`,读取方按"两个键有其一"识别公告。ToolSearch 关闭时由 `WaitForMcpServers` 提示连接中的 server(见下一节)。
+- Native 交付记录:deferred 只记录被引用的定义,常驻 MCP 定义首次出现时冻结;来源只保存 serverName/toolName。
+
 ## Skill 通用名称埋点(2026-10-14)
 
 所有 `tool_name=Skill` 的 `agent_step` 增加 `skill_name`。不提取调度输入的请求名称,
@@ -621,21 +1036,24 @@ CLI fact、UI 兼容 metadata 与最终 `/report` 共用名称校验,禁止任
 
 ## TaskStop 查找失败提示
 
-`TaskStop` 精确查找未命中时,统一返回以下模型可见错误;不增加前缀匹配或 ID 格式校验:
+`TaskStop` 精确查找未命中时,统一返回以下模型可见错误;不增加前缀匹配或 ID 格式校验,不列出运行中的任务:
 
 ```text
-Invalid task ID "<id>". This lookup failure does not mean the task has completed or stopped; use the full task_id returned when the task started to stop it.
+<tool_use_error>No task found with ID: <id>. This lookup failure does not mean the task has completed or stopped; use the full task_id returned when the task started to stop it.</tool_use_error>
 ```
 
-链路:`background_task_not_found → handler error (code: 1) → executor success: false → model isError: true`。
+链路:`background_task_not_found → handler 返回失败 (errorCode: 1) → executor 包装 → model isError: true`。
 查找失败不能证明目标任务已完成或停止;模型应使用启动时返回的完整 `task_id`。
-完整 ID 命中后的停止行为、其他错误、schema、权限、协议与 App 交互保持原样。
+任务已结束(`Task <id> is not running (status: <status>)`,3)与缺少 `task_id`(`Missing required parameter: task_id`,1)
+也由 handler 返回失败、executor 包装,文字不变。`Task <id> cannot be stopped` 仍是抛出的异常,不包装。
+完整 ID 命中后的停止行为、schema、权限、协议与 App 交互保持原样。
 回归覆盖短 ID、未知完整 ID 的失败文案及模型错误标记,并保留成功停止和其他失败分支断言。
 
 ## 规划与 Todo 动态提醒
 
-Plan 完整、简短及退出提醒,Todo 提醒与持续静默提醒都从消息历史计数,链路为消息历史 →
-reminder formatter → runtime attachment → provider projection,复用持久化上下文载体和恢复链路。
+Plan 完整、简短及退出提醒与 Todo 提醒从消息历史计数,持续静默提醒按消息历史与条目时间判定(2026-11-15
+起改为 60 秒计时),链路为消息历史 → reminder formatter → runtime attachment → provider projection,
+复用持久化上下文载体和恢复链路。
 细节见 16-plan-mode.md 与 loop/meta-user-context.md。工具 schema、审批、执行、事件和桌面/手机 UI 不变。
 
 ## 子 agent 环境与模型上下文共享
@@ -1002,6 +1420,9 @@ MCP 动态 tool 还需要额外确认:
 - 插件 MCP server 的变量展开、server name 规范化、timeout、trust gate 和
   permission 声明必须在 MCP tool 注册前完成,避免 provider-visible tool
   名称和实际 server 配置漂移。
+- 仓库配置的 `plugins.options` 不能进入变量展开:解释器路径等普通选项也能控制执行。
+  设置页保存的 Workspace 选项只从 Host 用户私有文件读取;启动和动态重载共用分层规则,
+  私有文件保存、清除或损坏后重算执行参数,不能自动信任旧仓库值。
 - 官方内置 plugin 的 MCP tool surface 由各 plugin 自己的 MCP server schema
   声明,例如 `ios-simulator` 与 `android-emulator`。新增官方 plugin 时,
   `.zcode-plugin/plugin.json`、缓存 seed、SEA asset manifest、skill/command
@@ -1018,6 +1439,12 @@ MCP 动态 tool 还需要额外确认:
   Windows `cmd.exe`。显式构建仍可执行项目 Gradle wrapper;工具 schema、权限、
   App 投影和 iOS 插件不变。Bootstrap 更新失败不得回退到漏洞版本。
   完整边界与回归场景见 [插件兼容](../plugin-compat.md#android-tool-lookup-security-011)。
+- Bash 仅拒绝工作区控制的直接 adb:handler 识别命令位置 → ExecutionPort 异步解析
+  SDK/PATH 或显式路径并校验字面/真实路径 → handler 固定为已校验的绝对路径 → 原有执行流程。
+  前后台和自动批准共用此检查,返回 `workspace-adb-blocked`;合法 SDK adb 不依赖 MCP。
+  CMD `@`/`call` 与现有 wrapper 继续识别。普通构建、脚本和参数不改写,间接调用仍不在此边界内。
+  Android 0.1.3 更新缓存指引,移除“必须走 MCP”;iOS 不变。
+  详见 [Bash spec](04-bash.md#direct-adb-execution-admission)。
 
 ## 大内容兜底要求
 
@@ -1040,7 +1467,7 @@ MCP 动态 tool 还需要额外确认:
   输出 stack 首行中的同一 `name + message`。浏览器错误应在原有稳定 error code 下附带有界的恢复
   提示,不能要求模型解析重复正文或依赖错误字符串决定结构化状态。
 - Compact/runtime 可以在请求前对历史旧 tool result 做 provider-visible microcompact projection,但只能替换模型可见内容为稳定占位符或 artifact 引用;不得删除原始 tool part、session transcript、artifact、checkpoint 或破坏 assistant tool call 与 tool result 的配对。该 projection 必须有结构化事件、traceId、pre/post token estimate 和测试覆盖,resume 时不能把 microcompact 事件误当作 full compact boundary。
-- `Bash` 模型可见结果默认规则:返回 stdout/stderr 文本、必要的中断标记、stale read 提示和 artifact 预览,不把 `status`、`exitCode`、bytes、path 等结构化 `BashOutput` 字段 JSON 化给模型;这些字段只供结构化 output、事件、UI/ZCode app-server 和 debug 使用。Bash `isError` 语义只表示命令被中断/取消,非零退出码仍通过文本输出和结构化 `status` 暴露。
+- `Bash` 模型可见结果默认规则:返回 stdout/stderr 文本、必要的中断标记、stale read 提示和 artifact 预览,不把 `status`、`exitCode`、bytes、path 等结构化 `BashOutput` 字段 JSON 化给模型;这些字段只供结构化 output、事件、UI/ZCode app-server 和 debug 使用。Bash 的 `is_error` 按命令语义判定(`isToolOutputError`):非零退出、超时、取消算错误,grep、rg 等退出 1 不算;退出码仍通过文本输出和结构化 `status` 暴露。
 - `Edit` / `Write` 成功结果模型可见内容保持短确认;完整内容、diff 和 patch 只能进入结构化 output、事件、UI projection 或 artifact。
 - 新增大内容能力时必须在具体 tool spec 中写清:原始大小上限、模型可见上限、是否报错还是截断、artifact 策略、错误码、UI/ZCode app-server 投影和测试用例。
 
@@ -1832,6 +2259,25 @@ ruleId `tool.workflowDraft.preapproved`;判定在 `permission/workflow-draft-p
 合并 Guarded 后,首次判权和 Hook 改写重判均使用既有执行上下文中的 cwd,保留草稿预批及 Guarded 快照语义。
 决策记录见仓库根 `docs/dynamic-workflow/launch.md`「Script files」→「Editing a draft needs no approval」。
 
+### 草稿写入的执行点符号链接防护(ZP-20261110-04,2026-11-16)
+
+免确认判定只比较路径字符串。若 `<cwd>/.zcode` 或 `<cwd>/.zcode/workflow-drafts` 是符号链接(例如项目
+内被提交的链接),字符串上在草稿目录内的写入会落到项目外,覆盖用户级配置(用户级 `SessionStart`
+命令 Hook 随后可被执行)。权限判定保持同步纯函数不变,防护放在真正写入的执行点:
+
+```text
+Write / Edit(handler,目标字符串落在 <cwd>/.zcode/workflow-drafts/ 内)
+  -> FileSystemPort.writeTextFile({ symlinkFreeBase: <cwd>, ... })
+  -> fs 适配器:建父目录前、原子写入前,两次从 <cwd> 之下逐级 lstat 到目标本身(含)
+       任一级为符号链接 -> SymlinkWriteRefusedError,不建目录、不写入
+```
+
+- 基准目录 `<cwd>` 本身及其以上不核验:项目根可以合法地经由链接访问。
+- 被拒绝的写入不弹确认:它不是合法的草稿写入。权限层仍按字符串判为免确认,写入在执行点失败。
+- 残余窗口:两次核验与 `rename` 之间仍有极短间隔,Node 不提供 `openat` 无法关闭。攻击者需在该间隔内
+  替换目录链接,且已能写入项目目录。此残余风险在这里记录,不另加超时或重试逻辑。
+- 未覆盖:普通(非草稿)路径的写入仍按既有确认窗口执行。同类写入点与相关产品决策另有内部工单。
+
 ## 脚本文件来源与工作副本(2026-09-18)
 
 ```text
@@ -2426,6 +2872,10 @@ Browser control scope 的 admission 失败可由下一次业务请求用原 ID 
 
 推荐候选 → `install/workspace` 确认卡片 → 同一插件存储锁内安装并写当前工作区启用 → 校验有效启用态 → 现有安全重载。已安装时仅启用,不改用户级显式禁用及其他工作区覆盖。旧 `install/user` 确认不能被升级授权;失败不冒充已就绪。规格见根 docs/plugins/agent-plugin-discovery.md。
 
+### 插件推荐业务埋点事实
+
+工具 schema、权限、结果与 V4 投影不变。v4-gateway 对每个 live 事件额外调用 `PluginDiscoveryFactNormalizer`(conversation-telemetry-facts.ts):`SearchPlugins` 终态、`PluginInstallRequested`、`PluginInstallResolved`、用户确认后的 `SuggestPluginInstall` 终态各归一为一条 `plugin.discovery` 事实,只带 phase、plugin_id、动作、结果、结果数、决策与耗时,不带查询词、理由或输出正文。桌面 Host 单点上报,见根 docs/monitoring/plugin-lifecycle-telemetry.md「Agent 推荐链路」。
+
 ### 插件推荐多语言载荷边界
 
 官方目录 → 共享翻译表裁剪器 → 推荐候选 → 安装交互 → 共享 schema 校验 → 持久化与 V4 投影。名称和描述分别限制语言数量、键/文本长度及 JSON UTF-8 字节数;优先保留全部支持的界面语言与默认文本。协议采用同一组上限,超限原始字段不得进入交互事件;确认、启用和自动 reload 不变。见根 docs/plugins/agent-plugin-discovery.md「多语言载荷边界」。
@@ -2469,6 +2919,102 @@ stdio stderr → adapter 有界缓冲与脱敏 → 已有 `McpServerStatus.error
 
 已有可选 input.description 经 V4 input 原样进入 UI;执行摘要优先显示非空描述,缺失时显示命令。独立行、组内子项与活动组头共用 Execute renderer;展开后摘要继续显示非空 description,详情保留命令和输出;权限详情保持实际命令。只修改 UI 展示,不改 schema、执行、权限、事件或持久化。验收见根 docs/ui/tool-display-rendering.md 的 Bash 调用描述与浏览器分组候选。
 
+## Bash 硬超时结果(2026-11-12)
+
+首 token 是 `sleep` 的前台 Bash 到达超时预算后(`status: "timed_out"`),模型看到的结果改为失败结果形态:
+`Exit code 143`、`Command timed out after <时长>`、已采集的输出,依次用换行连接,`is_error: true`,不再追加
+`<error>Command was aborted before completion</error>`;用户取消和中断仍带这个标记。时长由 Bash 投影按实际生效的
+超时毫秒数格式化(不足 1 分钟取整秒,否则 `Xm Ys` / `Xh Ym Zs` / `Xd Yh Zm`),adapter 的通用超时文案不变。
+失败结果与硬超时的输出保留开头的空行,只去掉末尾空白(例如 `Exit code 7\n\n\nboom`);成功结果仍去掉开头的空行。
+只改模型可见文本:工具 schema、`BashOutput` 字段、事件、UI 与持久化结构不变;已发送的历史不改写,只有新产生的结果使用新文本。
+细节见 04-bash.md「模型 result 映射规则」。
+
+## 后台 Bash 改目录的说明(2026-11-12)
+
+转后台的 Bash(显式后台与超时转后台)如果命令会改目录(`cd` / `pushd` / `popd` / `chdir`),后台文案末尾换行后追加
+`Session cwd remains <cwd>; directory changes made by the backgrounded command do not apply to subsequent commands.`。
+链路:handler 用已有的命令解析判定,把这次执行的 cwd 写进新的可选字段 `BashOutput.backgroundSessionCwd`;formatter 读它生成这句。
+`BashOutputSchema` 是 strict:旧版本读到新字段时解析失败,工具卡退回 JSON 文本显示,不报错(与 `timedOutAfterMs` 相同);
+冷恢复回放的是持久化的模型文本,不重新格式化。工具 schema、权限、事件类型与 tools 段字节不变;只影响新产生的后台结果。
+
+同步子代理里的后台 Bash(同日):父会话用前台 Agent 启动的子代理,后台文案里的完成通知句换成
+“最终回复之后不会再有通知,要结果就在最终回复前等它”的句子(原文见 04-bash.md「模型 result 映射规则」)。
+链路:subagent 启动 child 时按 `request.background` 固定 `subagents.startedInForeground`(启动后不变,中途转后台不改)→
+runtime 工具执行器 → `ToolExecutionContext.syncSubagent` → Bash 转后台时写可选字段 `BashOutput.backgroundInSyncSubagent` → formatter。
+新字段与 `backgroundSessionCwd` 的降级规则相同;child 生命周期(封存通知、正常结束不终止后台进程)不变。
+
+## Bash 只读名单补充(2026-11-14)
+
+Explore 子 agent 继承父会话的 Plan 后,只读 Bash 判不成只读就被拒。这次只扩充只读名单,补入压缩包列表、
+Windows 查询、`iconv`/`xxd`/`command -v` 与几条 git 历史查询。链路不变:AST 解析 → readonly policy →
+运行时 capability(`readOnly`/`needsApproval`)→ 权限服务。影响面是同一份名单的所有使用方:
+Plan 放行、Build 免审批、Memory Agent 可执行、前缀授权可省略这些段。工具 schema、描述、事件与 UI 不变;
+`cmd`/`legacy-shell` 方言改由 CMD 只读策略判定,其中 git 复用本名单的 git 判定(`isGitReadOnlyCommand`、
+`hasDangerousGitGlobalOption`),所以 git 的新增形态在 CMD 下同样生效。规则见 [04-bash.md](04-bash.md#read-only-bash-allowlist)。
+(上句指前台。Memory Agent 只在会经 cmd.exe 执行时走 CMD 策略,POSIX 上的 `legacy-shell` 仍用本名单,见上方 2026-11-16 条目。)
+
+## Agent 总在后台运行开关(2026-11-18)
+
+- 新增开关 `AgentRuntimeConfig.subagents.alwaysBackground`,缺省开启;CLI `--agent-always-background on|off`,
+  App 设置「子智能体总在后台运行」(`agentAlwaysBackgroundEnabled`,创建或冷恢复 runtime 时读一次)。
+- 开启:Agent / Task 的输入 schema 没有 `run_in_background`,描述里的后台一行是
+  `- Subagents run in the background; you'll be notified when one completes. Never fabricate or predict a pending agent's results — the notification is never something you write yourself; if the user asks before it arrives, say it's still running.`
+  每次调用直接返回 `async_launched`(启动回执文字不变),结果经 `<task-notification>` 在之后的回合送回。
+  模型或插件指令仍传入 `run_in_background` 时,runtime schema 解析丢掉这个字段,不报错。
+  禁止后台的执行(`modelOverride.background: "deny"`)静默改为前台,不报错。
+- 关闭:schema、描述与执行都与开关出现前相同(`run_in_background` 排在最后,tools 段字节不变)。
+- 读取侧不再只从原始 input 推断后台,两种开关取值都适用:bootstrap 子代理目录查询的 running 推断改用
+  `launchAcknowledged`(`part.metadata.background`,旧 part 看启动回执前缀);App 的 Agent 卡片也认结构化输出
+  `status: "async_launched"` 与启动回执。旧会话历史里的字段不改写,读取侧继续兼容。
+- workflow 子会话(`taskType: "workflow_child"`,例如 `/expert` 的节点)固定按关闭运行:节点只读一次回合的回复,
+  后台子代理之后的完成通知没有读取方。
+- `zcode -p`、`--target` 与 `-p "/goal …"`、`-p "/expert …"` 都在后台工作结束前不退出,不论开关取值,规则见根目录
+  `docs/dynamic-workflow/launch.md`「Headless runs」。
+- 缓存:开启时 tools 段字节变化,升级后每个主会话第一次请求缓存失效一次;子代理没有 Agent 工具,tools 段不变。
+  已发送的历史(前台 hand-back)按 `metadata.modelContent` 原样重放,不改写。
+- 规则见 [07-subagent.md](07-subagent.md)「ZCode 当前实现」。
+
 ## legacy 会话事件剥掉后加的字段(2026-11-06)
 
 legacy v1 的 `session/events` 由 `bootstrap/src/zcode-protocol/session-mapper.ts` 整体 spread CLI 事件的 payload,App 侧是 strict schema,整页 `safeParse`。后加到 CLI 事件里、legacy schema 没有声明的字段要在 mapper 里剥掉,不改 App 的 schema(已经装出去的旧桌面同样会整页失败)。这次补上两处:`ToolCallStarted` 的 `readOnly`、`sideEffectScope`(解析后的副作用能力,只给 core 与 dynamic-workflow 用),`PermissionRequested` 的 `fullAccessSupported`(只给 v4 的审批)。漏掉时的后果:App 的 `readSession(view: "summary")` 经事件读 `executionId`,调用过工具、正在运行的会话报 ZodError,中断不了(2026-11-06 PLM-JARVIS-2 的运行时证据;示例插件 Jarvis 已迁出到市场仓库,那个 E2E 已删除)。回归由 `bootstrap/tests/session-mapper-legacy-strip.test.ts` 守住。以后给工具或权限事件加字段,同时决定 legacy mapper 要不要剥。
+
+### 会话级状态胶囊生命周期
+
+Goal、Todo 按 session 保留;接纳新的真实用户输入不清除二者完成态摘要。Goal 由新目标替换,Todo 由 TodoWrite 替换。Activity 的记录按 session 保留,展示阶段遵循下文的轮次边界。同一归约路径覆盖 live 与 hydration,不改变工具 schema、执行器或持久化事件。Subagent 最近 100 条及摘要长度上限继续保留,完整结果从历史目录访问。
+
+Goal 的旧 summaryHidden 为兼容字段,不再生成其发送隐藏事件。Activity 的 activitySummaryDismissed 只收起明细,不删除记录。
+
+### Activity 轮次展示边界(2026-11-13)
+
+Goal、Todo 仍按 session 常驻。Activity 使用 activitySummaryDismissed 作为已结束明细的展示边界:真实用户输入接纳时记录已结束的 work、child、run 身份,不删除实际记录,不隐藏仍运行项。live 与 hydration 共用归约。恢复同一 work/run 的有效运行事件撤销对应旧标记;child 的新执行与冷恢复新结束时间解除旧结果隐藏。UI 本轮结果与历史目录分阶段展示;只有目录时使用中性活动图标,不展示旧结果状态。
+
+冷恢复补入历史 child 时,seed 需同步补齐已有输入边界的归档身份:结束时间不晚于边界且不在运行中的记录归入历史,较新结果继续可见;保留完整结束记录与既有归档身份。连续输入和再次恢复仍使用同一规则,不在 UI 创建第二套时间边界。
+
+## Activity 成功总数(2026-11-18)
+
+回退身份以 Core 已提交的活动分支截断为准:`RewindTriggered.removedMessageIds` 为可选的实际移除消息清单;失败、workspace-only 回退不提供该事实。冷恢复种子沿既有 child 候选解析保存全部来源消息 ID,复用结果事务索引。较早的无投影行 child 不因后续轮次回退而丢失;同一 child 仍有任一保留来源则保留成功贡献。删除真正撤销的 child,并在同事务发布计数。旧事件缺字段仅使用明确行删除,不猜测种子身份已失效。新增字段只属于 CLI 内部事件与冷种子,不改变工具输入、权限或 App wire schema。
+
+长历史恢复约束:完整 Workflow 计数读取使用父会话索引,基线与增量升级保持一致,不扫描其他会话的 run/actor。同一 child 重新运行时在 outcome 索引点更新为非终态,移除其成功贡献但保留身份;不能为了恢复一个 child 触发事务 Map 的整表删除备份。真实回退/身份移除仍清理对应键。万级历史回归覆盖成功→恢复→再次结算的接受、拒绝、抛错、重连与计数,保留现有回退语义;不改变工具或协议契约。
+
+增量发布独立于预览 delta:同一事务比较派生完整成功数与 snapshot 的已发布值,预览外 child 的状态变化也必须发布数量;保留原子拒绝/异常回滚。后台执行变化仅在受阻子代理身份集合发生变化时触发 child 物化,普通 Bash 生命周期不扫描完整历史。工具 schema、执行、权限与存储不变;两种 delivery profile 验证增量及重连数量、无关 Bash 成本与真实 child 阻塞状态。
+
+长历史成本约束:完整 child/run outcome 与 Workflow actor 归属索引使用现有原子事务,
+不能在每次候选事件中全量复制。成功总数是这些索引的派生标量,由同一 ProductProjection
+在身份状态或 actor 归属变化时增减;普通节点进度不遍历完整历史。完整 child 种子替换时
+允许重建派生值。候选被拒绝或抛错时,索引、水位与计数一起回滚;未知总数仍输出 null,
+完整种子到达后才恢复数值。不得增加 UI 缓存、计时同步或新的权威计数来源。
+
+工具 schema、权限和执行不变。V4 ProductProjection 按完整 child/run 最新状态派生
+`completedActivityCount`,以可选非负整数或 null 加入 snapshot/state patch;该数不含 Bash,
+Workflow actor 不重复计入独立 Subagent。预览裁剪不影响总数;冷恢复从完整 child 种子
+及 journal 事件重建,索引与投影原子提交,重复/旧 run sequence 不累加。
+消费侧不缓存计数;桌面 continuous、手机 replayable 使用同一字段。细则见
+根 `docs/ui/chat-summary-panel.md`。
+
+Activity 冷恢复补充:合成结算显式标识来源,不预占真实 journal sequence;真实事件去重只由真实事件推进。摘要查询失败由 V4 bridge 隔离并记 warn,完整数设为 null,保留可用历史及 live buffer;完整种子恢复前不将部分投影伪装成完整计数。工具执行、权限与数据库结构不变。
+
+冷恢复首帧与混合结果补充(2026-11-18):已有持久历史但尚无 runtime record 的 history-first 首帧,必须显式标记完整计数未知;新建空会话仍为 0。初始化失败和重连保留未知及历史正文,ready 后从完整种子恢复准确值。总数是否已知不决定已观察到的成功状态:无运行/失败且有成功结果时显示“已完成”,未知时不显示数字;只有全部停止且没有已知成功时保留停止摘要。失败仍按既有优先级显示失败数量。回归覆盖两种 delivery profile 的首帧/失败/重试 ready,以及 unknown + 成功停止混合/仅停止/失败。
+
+Activity 实时物化补充:live、严格回放与批量回放统一按 delta 的实际输入判断是否重建子代理投影。文本、推理和非子代理工具行不触发完整 child outcome 对账;子代理行变化、删除、相关权限或后台执行状态变化仍触发;合法 child 启动/停止即使没有可见 delta,也需更新身份校验与停止控制。未变化的 child 状态及结束时间不重复写入事务索引。用真实 publisher 的 continuous/replayable 路径验证万级历史下普通流无全表迭代和 outcome 写入。
+
+审批物化成本约束(2026-11-19):pendingInteractions 变化仅在 child 等待身份集合改变时触发 child 物化,与 Bash 受阻集合使用相同依赖口径。主代理审批申请/解除不访问完整 child outcome 索引;同一 child 多个审批只在第一次进入等待、最后一次解除时更新其摘要,两种 delivery profile 均回归。

+ 40 - 0
apps/zcode-cli/docs/design/v2/tool/01-read.md

@@ -26,6 +26,25 @@
 - 当前实现支持文本、常见图片(`.png`、`.jpg`、`.jpeg`、`.gif`、`.webp`)、视频(`.mp4`、`.m4v`、`.mov`、`.webm`、`.mkv`、`.avi`)和按模型能力条件开放的 PDF。Jupyter Notebook、SVG 和 device path 仍是后续实现项;未实现的能力不得写入 provider-visible prompt。
 - provider-visible 描述:范围读取一行写作 "When you already know which part of the file you need, only read that part…";支持 PDF 时,PDF 句接在图片行末尾(同一行)。不提 Jupyter Notebook(未实现);视频单独成行,放在图片行之后。
 
+### 输入修正
+
+模型常把 `offset` / `limit` 写成数组、字符串、负数或 `0`,或者用 `length` 代替 `limit`。`Read` 的 runtime schema 在校验之前
+按下面的顺序修正输入,结果再进入字段校验:
+
+1. `offset` 或 `limit` 是只有一个元素的数组时,换成这个元素。
+2. `offset`、`limit`、`length` 是字符串、去掉首尾空白后形如 `^[-+]?\d+(\.\d+)?$` 时,换成对应的数字(例如 `"50"`、`" -1 "`)。
+3. `offset` 是小于 `0` 的有限数时删除 `offset`。
+4. `limit` 是小于或等于 `0` 的有限数时删除 `limit`。
+5. 有 `length` 时:没有 `limit`(包括第 4 条刚删掉的情况)且 `length` 是大于 `0` 的有限数,把它写到 `limit`;`length` 总是删除。
+
+不改写其他字段,其他类型的值原样交给字段校验(例如 `limit: "abc"` 仍按类型错误返回,`limit: "1.5"` 按整数校验失败)。
+修正后的输入同时用于 JSON Schema 校验、hook、权限和 handler;provider-visible schema 不变。删除 `offset` 后从第 1 行读,
+删除 `limit` 后按默认行数读。
+
+修复原因:`limit: -1`、`limit: 0` 原来通过 JSON Schema(它不检查 `exclusiveMinimum`),然后在 handler 内被 runtime schema
+拒绝,模型收到原始 ZodError JSON;`offset: -5`、`limit: [50]`、`limit: "50"` 收到参数错误;`length` 被静默丢弃。这些输入的
+意图都清楚,修正后直接读取,不让模型多花一轮重试。
+
 ## 输出契约
 
 输出是按 `type` 区分的 union(`notebook` 为后续实现项):
@@ -252,6 +271,27 @@ ZCode 应将路径权限做成统一 filesystem permission adapter,`Read` 只
 
 这些错误应保留稳定错误码和结构化原因,CLI 入口层再格式化成人类提示。
 
+路径与页码的预检都在 Read `validateInput`,PreToolUse Hook 和权限检查之前完成,顺序是:`pages`(`errorCode=7` / `8`)→
+二进制扩展名(`errorCode=4`)→ 设备文件(`errorCode=9`)。executor 统一投影为 `<tool_use_error>…</tool_use_error>`;
+`error.message` 与 UI 只有原文,不带标签。这些检查不写进 runtime schema(`ReadInputSchema` 只做输入修正和字段校验),
+否则 runtime schema 失败会先返回 InputValidationError(根目录 `docs/model-tool-call-validation.md`)。handler 与压缩恢复读取
+仍调用同一个检查函数,覆盖 hook 改写后的输入。
+
+文字(2026-11-14):
+
+```text
+Invalid pages parameter: "<pages>". Give one page ("3") or one range ("1-5"), not a list. To read several pages or ranges, read each one separately. Pages are 1-indexed.
+This tool cannot read binary files. The file appears to be a binary <ext> file. Use a skill for this file type if one is available, or a shell command or script that can read the format.
+Cannot read '<path>': this path names a device or process file that this tool does not read.
+```
+
+二进制扩展名表不变(19 项)。`pages` 不接受列表(`1,3`),只接受单页、闭区间与开放尾区间,所以文字写“不是列表”。
+handler 分页提取时的同类检查使用同一句。原来的文字分别是 `Use formats like "1-5", "3", or "10-20".`、
+`Please use appropriate tools for binary file analysis.` 与 `this device file would block or produce infinite output.`。
+
+修复原因:二进制和设备文件的检查原来在 runtime schema 的 superRefine 里,由 handler 抛出带 `<tool_use_error>` 标签的
+`error.message`,hook 与权限先跑一遍,UI 显示的错误也带着标签。
+
 ## ZCode 设计结论
 
 ## 实现状态(2026-05-08)

+ 21 - 8
apps/zcode-cli/docs/design/v2/tool/02-write.md

@@ -97,14 +97,27 @@ ZCode 应把 create/update 都归入 `workspace` side effect,并显式声明
 - UNC path 不做提前 I/O,交给权限处理。
 - 写入过程中的文件系统错误向上冒泡。
 
-这些错误应保留原始 cause,并区分:
-
-- `file_not_read`
-- `partial_read`
-- `stale_file`
-- `permission_denied`
-- `secret_detected`
-- `io_error`
+这些错误应保留原始 cause。handler 能预期的失败用数字 `errorCode` 区分(见下一节);权限拒绝走权限链路,
+文件系统 I/O 错误照原样抛出,都不在下表里。
+
+### 模型看到的文字(2026-11-14)
+
+下面的失败由 handler 返回 `{ result: false, errorCode, message }`,executor 包成 `<tool_use_error>…</tool_use_error>`;
+App 显示不带标签的原文。检查都在 handler 里、权限之后,时机不变。`<file_path>` 是模型传入的原值。
+
+| 条件 | errorCode | 文字 |
+| --- | --- | --- |
+| 已有文件没读过;或最近一次视图是部分视图(Read 只返回了一页、压缩补回时只给了引用、截断后注入上下文的 MEMORY.md) | 2 | `File has not been read yet. Read it first before writing to it.` |
+| 读后被改过 | 3 | `File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.` |
+| 目标是目录 | 17 | `<file_path> is a directory, not a file. To create a file inside it, include the file name in file_path.` |
+| 目标存在但不是普通文件 | 18 | `<file_path> exists but is not a regular file (a device, FIFO or socket). Write only creates or overwrites regular files.` |
+
+截断注入的 MEMORY.md 不单独写“只看到开头,改用 Edit”:ZCode 的 Edit 同样要求先完整读过(03-edit.md),照那句去做
+会再失败一次;“先 Read”在 Write 与 Edit 上都成立。
+目录与非普通文件原来返回文件系统层的 `Cannot read directory as text file: <path>` / `Cannot read non-file path as text: <path>`,
+模型看不出是 `file_path` 写错了。已有文件的编码读不出来时仍抛文件系统错误,文字不变。
+
+修复原因:这些失败原来都是抛出的异常,不带 `<tool_use_error>`;Edit 的同类失败一直带标签,两个工具不一致。
 
 ## ZCode 设计结论
 

+ 23 - 1
apps/zcode-cli/docs/design/v2/tool/03-edit.md

@@ -73,7 +73,7 @@
 7. 通过 `FileSystemPort.readTextFile` 读取文件 bytes,由 adapter 按 BOM、UTF-8 校验和 legacy 中文编码检测推断文本编码,并返回 LF 规范化后的 Unicode 逻辑内容、原始 `encoding` 和 `lineEndings` metadata。
 8. 当前 ZCode 拒绝空 `old_string`,避免对既有文件产生隐式插入;创建新文件或完整重写使用 `Write`。
 9. 不存在文件且 `old_string` 为空时创建文件的行为,ZCode 暂不暴露;后续如需支持必须先更新 `Write/Edit` 边界和测试。
-10. `.ipynb` 文件拒绝,要求用 Notebook edit 工具。
+10. `.ipynb` 文件拒绝,提示用 shell 命令或脚本改 notebook JSON(ZCode 没有 notebook 编辑工具)。
 11. 已存在文件必须此前完整 `Read`。
 12. mtime 变更时,如果完整读缓存内容仍相同,可继续;否则拒绝 stale edit。
 13. 先用 exact,再用 quote normalization 和受限兼容 matcher 查找实际字符串。
@@ -128,6 +128,28 @@ handler 在进入共享路径解析前返回本地稳定错误码 `13` 和既有
 这些数字码由 Edit tool contract 统一导出,handler 不再维护第二份私有映射,避免
 provider error 与公开工具契约在后续修改中漂移。
 
+### 模型看到的文字(2026-11-14)
+
+| 条件 | errorCode | 文字 |
+| --- | --- | --- |
+| `.ipynb` | 5 | `File is a Jupyter Notebook. Edit does not change .ipynb files; change the notebook JSON with a shell command or script instead.` |
+| 文件过大 | 10 | `File is too large to edit (<实际大小>). Maximum editable file size is 1GB.` |
+| 文件不能按 UTF-8 或 GB 编码读出(adapter 的 `unsupported`) | 15 | 见下 |
+| 未找到 old_string,且 old_string 里有 `\uXXXX` 转义 | 8 | 原句后加一行 `(note: Edit also tried swapping \uXXXX escapes and their characters; neither form matched, so the mismatch is likely elsewhere in old_string. Re-read the file and copy the exact surrounding text.)` |
+
+编码错误的文字:
+
+```text
+File is not valid UTF-8 or a supported legacy encoding (GB2312, GBK, GB18030), or it is binary. Edit and Write never convert a file's encoding on their own, so nothing was written. If the file is text, make the change with a shell command that reads and writes it in its own encoding (iconv, or PowerShell Get-Content/Set-Content -Encoding), or ask the user whether to convert it to UTF-8 first. To replace the whole file with new UTF-8 text anyway, delete it first, then Write it.
+```
+
+- 大小用一位小数、去掉尾随 `.0` 的格式(`1536 bytes -> 1.5KB`),与 Read PDF 摘要相同;上限仍是 1GB。文件只比上限
+  大一点、格式化后与 `1GB` 相同时,括号里改写字节数(`(1073741825 bytes)`),不出现“(1GB)… 上限 1GB”。
+- 转义说明只在 old_string 含 `\uXXXX` 时追加:匹配器只把 old_string 里的 `\uXXXX` 换成字符再找
+  (`unicode_escape_normalized`),不把字符换成转义去找,所以只有非 ASCII 字符、没有转义时不加这句。
+- 原来的文字分别提到不存在的 `NotebookEdit` 工具、把大小写死成 `(1GB)`、编码错误是不带标签的
+  `Unsupported or binary text encoding: <path>`。
+
 ## ZCode 设计结论
 
 ## 实现状态(2026-05-08)

+ 186 - 15
apps/zcode-cli/docs/design/v2/tool/04-bash.md

@@ -55,6 +55,8 @@ provider-visible output 以本文“模型 result 映射规则”为基线。
 | `backgroundTaskId` | `string?` | 后台任务 ID |
 | `backgroundedByUser` | `boolean?` | 是否用户手动后台化 |
 | `assistantAutoBackgrounded` | `boolean?` | 是否被 assistant mode 自动后台化 |
+| `backgroundSessionCwd` | `string?` | 转后台的命令会改目录时,记录转后台时的会话 cwd(这次执行的 cwd);模型文案据此说明会话 cwd 不变 |
+| `backgroundInSyncSubagent` | `boolean?` | 后台命令属于同步启动的子代理(父会话用前台 Agent 启动它);模型文案据此说明最终回复之后不会再有通知 |
 | `dangerouslyDisableSandbox` | `boolean?` | 是否请求绕过 sandbox |
 | `returnCodeInterpretation` | `string?` | 特殊返回码解释 |
 | `noOutputExpected` | `boolean?` | 成功时是否预期无输出 |
@@ -75,16 +77,27 @@ provider-visible output 以本文“模型 result 映射规则”为基线。
 - Windows 的 append-only 句柄曾触发 MSYS 兼容性问题;改用 Windows "w" 打开方式
   验证通过后,普通 Bash 统一采用直接文件输出。通用 argv/Hook 继续使用 pipe/collector。
 - 成功路径需要在模型可见 stdout 前剥离 `<claude-code-hint ... />` 行;hint stripping 先于 image / stale read / gh rate-limit 等后续处理。
-- 图片输出转 image content block;如果无法识别为受支持图片块,回退为文本。resize/compress 是模型预算优化,不是唯一的图片判定依据;当 data URI 的 magic bytes 已确认是受支持图片,且 resize 只是通用处理失败时,可以继续按 image block 暴露给 provider,避免把合法图片降级成原始 data URI 文本。若 resize 明确失败在 `too_large`、`invalid_request`、`unsupported`、`empty` 等预算/请求语义上,必须回退文本,不能绕过 provider 图片预算。
-- 中断、timeout 或用户取消时,在 stderr 段后追加 `<error>Command was aborted before completion</error>`,让模型能稳定识别未完成状态。
+- 图片输出转 image content block;如果无法识别为受支持图片块,回退为文本。识别条件有三条:data URI 声明的类型必须与 magic bytes 检测结果一致(只认 PNG、JPEG、GIF、WebP);WebP 的实际字节数不能小于 RIFF 头声明的文件总长(长度字段 + 8);配置了 resize 适配器时(生产链路总会注入),resize 必须成功。resize 的任何失败(解码失败,或 `too_large`、`invalid_request`、`unsupported`、`empty` 等预算/请求失败)都回退文本。不能只凭 magic bytes 放行:截断或损坏的图片头部完好,作为 image block 发出会被 provider 拒绝,坏图又随会话历史重放,后续请求全部失败。代价是少数 resize 适配器解不了的合法图片也回退文本。需要类型一致检查有两个原因:resize 适配器对 WebP 原样透传、不解码;对其他格式按内容解码,却按声明的类型返回原 bytes。WebP 不解码,所以单独检查截断。这些条件能发现截断(GIF 只缺末尾结束字节时除外),但不能发现所有内容损坏:WebP 不解码;JPEG、GIF 解码器会容错,部分内容损坏的图片仍会作为图片发出。stdout artifact 超过 20MB 时只读 inline 预览,预览已截断:PNG、JPEG、GIF 解码失败,WebP 长度不足,都回退文本。
+- 中断或用户取消时,在 stderr 段后追加 `<error>Command was aborted before completion</error>`,让模型能稳定识别未完成状态。
+- 硬超时(首 token 是 `sleep` 的前台命令到达预算,结构化 `status: "timed_out"`)按失败结果投影,`is_error: true`,不加上面的 `<error>` 标记。正文依次是 `Exit code <exitCode>`(Bash 直写输出路径固定为 143,三个操作系统相同)、`Command timed out after <时长>`、已采集的输出:
+
+  ```text
+  Exit code 143
+  Command timed out after 1s
+  ```
+
+  输出与失败结果相同,保留开头的空行:不剥离 hint 行,不转成图片,不加 gh rate limit 提示,不走 `<persisted-output>`,超长时按下文“失败结果”条目保留头尾。
+
+  时长由 Bash 投影按这次调用实际生效的超时毫秒数格式化,不用 adapter 的通用文案:不足 1 分钟时取整秒并向下取整(0 是 `0s`,小于 1ms 是 `0.0s`,50ms 是 `0s`,1500ms 是 `1s`);1 分钟及以上时按四舍五入的秒进位,写成 `Xm Ys`、`Xh Ym Zs` 或 `Xd Yh Zm`(120000ms 是 `2m 0s`,600000ms 是 `10m 0s`,3600000ms 是 `1h 0m 0s`)。超时转后台的文案不变(见下文 `timedOutAfterMs`)。
 - provider-neutral mapper 本身只根据 `interrupted` 写入 `is_error`;ZCode 生产链路不为非零退出抛异常,所以需要在 provider-visible projection 层把普通失败结果标成 error,并输出 `Exit code N` + stdout/stderr 文本。`grep` 无匹配、`diff` 有差异、`test` 条件为 false 这类语义型非零退出仍不是 provider error。
-- 失败结果不走 `<persisted-output>`:正文是 `Exit code N`、内联 stdout(前 30000 字节)、stderr 按行拼接后 trim,不带后台、stale read、gh rate limit 提示。总长超过 `10000 + 1024` 字符时保留前 5000 和后 5000 字符,中间换成 `\n\n... [K characters truncated] ...\n\n`(K 是删去的字符数)。这段正文已按字符限长,Bash 用 `isModelContentBounded` 声明它;通用 serializer 不再按 `resultBudget` 的 30000 字节落盘或截断。stdout 只采集前 30000 字节,所以模型看到的是这 30000 字节内的头尾;超出部分(包括真正的结尾)看不到,也不给文件路径。多字节文本(例如中文)的头尾正文可以超过 30000 字节,也原样内联。成功结果照旧按 30000 字节预算落盘。
+- 失败结果不走 `<persisted-output>`:正文是 `Exit code N`、内联 stdout(前 30000 字节,保留开头的空行,只去掉末尾空白)、stderr 按行拼接后 trim,不带后台、stale read、gh rate limit 提示。总长超过 `10000 + 1024` 字符时保留前 5000 和后 5000 字符,中间换成 `\n\n... [K characters truncated] ...\n\n`(K 是删去的字符数)。这段正文已按字符限长,Bash 用 `isModelContentBounded` 声明它;通用 serializer 不再按 `resultBudget` 的 30000 字节落盘或截断。stdout 只采集前 30000 字节,所以模型看到的是这 30000 字节内的头尾;超出部分(包括真正的结尾)看不到,也不给文件路径。多字节文本(例如中文)的头尾正文可以超过 30000 字节,也原样内联。成功结果照旧按 30000 字节预算落盘。
 - `staleReadFileStateHint` 是面向模型的稳定提示,需要作为文本段追加,不能因为不再 JSON 化结果而丢失。
 - 成功结果的大输出写入 tool-results / execution artifact(失败结果不落盘,见上一条),只给 `<persisted-output>` 风格的预览、完整路径和原始大小,不把完整 JSON 或大 stdout 回灌模型上下文。无论持久化来自 execution adapter 的 output artifact,还是来自通用 serializer 的 `resultBudget` artifact,Bash 都必须走同一套 Bash 专用 provider-visible projection。
 - 后台任务返回任务 ID 和输出路径,模型可见文案应说明任务仍在后台运行以及输出写入位置。
 - 后台任务启动返回必须包含可立即 `Read` 的 canonical output path;即使命令尚未写出任何
   字节,adapter 也要在 spawn 前创建该文件。新 Bash 执行不再生成第二个 stderr 日志文件;
   历史 split-path 字段只用于兼容读取,不能同时暴露给 provider。
+- 后台任务登记到任务注册表时另存命令原文。compaction 补回运行中的后台命令时用它,文字见 [rewind-compact](../rewind-compact.md) 的“后台任务状态”。
 - 后台任务完成、失败、timeout、cancel 或 output-limit 停止后,runtime 需要把一条短 `<task-notification>` 注入下一次模型请求的消息历史。通知只包含 `task-id`、可选 `tool-use-id`、状态、摘要和输出文件路径,不包含完整 stdout/stderr;模型需要读取日志时继续调用 `Read`。
 - 结构化 `status`、`exitCode`、`stdoutBytes`、artifact path 等字段保留在结构化 output、事件、UI、ZCode app-server 和 debug 中;不应成为模型可见结果的主要形态。
 - App 工具卡(V4 投影与 legacy 快照路径相同):后台命令的 failed 通知覆盖启动 ACK,并写成标准 tool error。Execute 卡片显示通知摘要 `Background command "<description 或 command>" failed with exit code <N>`(没有退出码时省略 `with exit code <N>`),不再显示命令输出或启动 ACK;输出仍在输出文件中。
@@ -94,13 +107,15 @@ provider-visible output 以本文“模型 result 映射规则”为基线。
 以下规则是模型可见 result 的映射依据,ZCode 测试需要覆盖以下 case:
 
 - `structuredContent` 非空时直接作为 tool result content 返回,优先级高于 `isImage`、stdout、stderr、后台文案和提示字段。
-- `isImage=true` 时只在 stdout 是可识别的 `data:image/*;base64,...` 且图片类型受支持时返回 image content block;否则回退普通文本路径。图片 resize 是 best-effort 优化:如果 resize 失败但共享 magic bytes 检测确认 data URI 和媒体类型一致,并且错误不是明确的预算/请求失败,仍保留原 data URI 并返回 image content block。
+- `isImage=true` 时只在 stdout 是可识别的 `data:image/*;base64,...` 且图片类型受支持时返回 image content block;否则回退普通文本路径。handler 只在声明类型与 magic bytes 一致、WebP 实际字节数不小于 RIFF 头声明的文件总长(长度字段 + 8)、且 resize 成功(配置了 resize 适配器时)后才设 `isImage=true`;resize 失败(包括解码失败)、类型不一致或 WebP 被截断时 `isImage=false`,stdout 保留原 data URI 文本。
 - 普通文本 stdout 先执行 `replace(/^(\s*\n)+/, "")` 去掉前导空行,再执行 `trimEnd()` 去掉尾部空白;stderr 使用 `trim()`。
 - `persistedOutputPath` 只在非后台文本结果中生成 `<persisted-output>` 文案。预览取规范化 stdout 的前 2000 字符,尽量在前半段之后的最后一个换行处截断;大小文案使用 1024 进制、无空格的 `bytes` / `KB` / `MB` / `GB`,例如 `2KB`。serializer 因 `resultBudget` 额外写入 artifact 时,也要调用 Bash 专用 persisted projection,而不是通用 tool output 文案;但如果超预算内容来自 `structuredContent`,不能在 projection 中重新透传完整 structured blocks,应保留 artifact preview。
-- `interrupted=true` 时 stderr 段后追加 `<error>Command was aborted before completion</error>`,并由 mapper 标记为 error。普通失败命令同样是 provider-visible error result;ZCode 在 projection 层生成该结果,而不是依赖 mapper 的 `exitCode` 判断。
+- `interrupted=true` 时 stderr 段后追加 `<error>Command was aborted before completion</error>`,并由 mapper 标记为 error;硬超时例外,走失败结果投影,不加这个标记。普通失败命令与硬超时同样是 provider-visible error result;ZCode 在 projection 层生成该结果,而不是依赖 mapper 的 `exitCode` 判断。
 - `backgroundTaskId` 生成三种文案:普通后台、用户手动后台化、assistant-mode 自动后台化。普通后台文案必须包含“仍在运行 / 完成会通知 / 用 Read 查看输出文件”;assistant-mode 自动后台化文案必须包含 15s blocking budget 和建议长任务使用 subagent 或 `run_in_background`。
 - 前台命令到达超时预算后转后台时(结构化字段 `timedOutAfterMs`,即实际生效的超时毫秒数,可为小数),普通后台文案的第一句改为 `Command did not complete within its <N>s timeout and was moved to the background (ID: <id>).`,N 是四舍五入的秒数(至少 1);其后的输出路径、完成通知和 Read 提示不变。旧版本读到 `timedOutAfterMs` 时 strict 的 `BashOutputSchema` 解析失败,工具卡退回 JSON 文本显示,不报错(session-persistence.md「旧版本读取新数据」)。
 - 未失败结果中,`staleReadFileStateHint` 和 `ghRateLimitHint` 都作为独立文本段追加到最后,不能因为 Bash result 不再 JSON 化而丢失;`ghRateLimitHint` 只在前台结果中根据原始 stdout 计算。失败结果的 provider-visible error 文本不追加这两段。
+- 同步子代理里转后台的命令(`backgroundInSyncSubagent: true`),后台文案里的 `You will be notified when it completes.` 换成:`If it exits while you are still working you will be notified, but it is terminated when you give your final response and no notification can follow that — so do not end your turn to wait for it; if you need its result, wait for it before giving your final response.`。显式后台与超时转后台都适用,其余句子不变。“同步”按子代理启动时决定:父会话用前台 Agent 启动的子代理,它所有的后台命令都用这一句,中途转到后台(立即发送、前台超时)以后也一样;后台启动和 SendMessage 恢复的子代理用普通文案。这句话对 ZCode 成立的部分:子代理结束时封存自己的后台通知,最终回复之后不会再有通知(`07-subagent.md`);ZCode 不在子代理正常结束时终止这些进程,进程继续运行到结束或到子代理后台 Bash 的最长运行时间。主会话不加这一句。
+- 转后台的命令会改目录时(`backgroundSessionCwd` 有值),后台文案末尾换行后追加一句:`Session cwd remains <cwd>; directory changes made by the backgrounded command do not apply to subsequent commands.`。显式后台与超时转后台都适用。判定:命令解析后的任一简单命令名(去掉 `command`、`builtin`、`noglob` 前缀后)是 `cd`、`pushd`、`popd` 或 `chdir`;子 shell `( … )`、`{ …; }` 与控制结构内部不展开。命令超过解析长度上限或解析抛错时不加;只有部分语句解析出错时,按已解析出的命令判定。这句话对 ZCode 成立:后台命令结束时不写回会话 cwd(主线程只有前台成功的命令写回)。旧版本读到 `backgroundSessionCwd` 时与 `timedOutAfterMs` 相同,strict schema 解析失败,工具卡退回 JSON 文本显示。
 - 后台 result 即使带有 `persistedOutputPath`,模型可见内容也只使用后台说明文案,不生成 `<persisted-output>`。
 - `bash_progress` / tool JSX update、用户手动后台化入口和 `_simulatedSedEdit` 属于 runtime / UI / internal surface;provider-visible conformance suite 只覆盖最终 tool result 内容,端到端事件能力应放在独立 runtime suite。
 
@@ -108,7 +123,7 @@ provider-visible output 以本文“模型 result 映射规则”为基线。
 
 核心流程:
 
-1. 校验输入 schema。
+1. 校验输入 schema;然后 `validateInput` 拦截前台长 sleep(见下面「前台 sleep 拦截」),在 hook 与权限之前。
 2. 动态判断是否只读。只有通过 readonly command validation 的命令才并发安全。
 3. 解析命令用于权限匹配。复杂、不可解析或可疑命令默认进入 ask。
 4. 根据 sandbox 配置、排除规则和 `dangerouslyDisableSandbox` 决定是否 sandbox。
@@ -123,6 +138,34 @@ provider-visible output 以本文“模型 result 映射规则”为基线。
 12. 处理 stdout/stderr、sandbox violation 注释、image 输出、大输出落盘。
 13. 返回结构化输出。
 
+### 前台 sleep 拦截
+
+前台等待一个固定时长会占住整个 turn,模型也看不到期间的变化。等条件应该用后台的 until 循环,等已启动的命令应该用
+`run_in_background`,二者结束时都会通知模型。所以 Bash 的 `validateInput` 拒绝以长 sleep 开头的前台命令:
+
+- 只看第一个顶层元素。命令按 unbash 解析,展开顶层的 `;`、换行、`&`、`&&`、`||`、`|`、`|&`,第一个元素就是要看的子命令。
+  简单命令去掉重定向(`sleep 30 > /dev/null` 按 `sleep 30` 判断),保留前置赋值(`FOO=1 sleep 30` 放行);
+  子 shell、`{ …; }`、控制结构和带 `!` 或 `time` 的 pipeline(`! sleep 30`、`time sleep 30`)按原文判断,
+  因此不会匹配。命令超过 10,000 字符或解析有错误时,按整条命令判断。
+- 第一个元素去掉首尾空白后匹配 `^sleep\s+(\d+(?:\.\d*)?)\s*$`,数字按 `parseFloat` 取值,`>= 25` 时拒绝。
+  `sleep 25s`、`sleep .5`、`/bin/sleep 30`、`timeout 40 sleep 30`、`echo a; sleep 30` 都放行。
+- 拒绝原因只有两种:只有这一个元素时是 `standalone sleep N`;后面还有元素时是 `sleep N followed by: <其余元素>`,
+  其余元素各自去掉首尾空白,用一个空格连接(运算符不保留)。N 按 `parseFloat` 输出,`sleep 25.0` 显示为 `25`。
+- 跳过:`run_in_background: true`;执行端口不支持 Bash 后台生命周期(后台不可用时没有可以指向的替代做法);
+  shell 是 `cmd` 或 `legacy-shell`(命令不是 Bash 语法,Bash AST 不能判断,拒绝文字里的 until 循环也不能用;
+  未初始化的 shell 选择按 posix 处理,与 guarded 匹配相同)。主会话、子代理、headless 都拦截。
+- 结果是 handler failure,errorCode 10,executor 包成 `<tool_use_error>…</tool_use_error>` 并带 `is_error`:
+
+```text
+Blocked: standalone sleep 25. To wait for a condition, run an until-loop with run_in_background: true (e.g. `until <check>; do sleep 2; done`); you are notified when it exits. To wait for a command you started, use run_in_background: true. Do not chain shorter sleeps to work around this block.
+```
+
+- 被拒的命令不跑 PreToolUse hook,不请求权限,也不启动进程(executor 的 `validateInput` 分界,见
+  00-tool-change-chain.md「工具错误的包装与文字」)。PreToolUse hook 改写输入后,executor 只按 schema 再校验,
+  不再跑 `validateInput`,所以 hook 改写出来的长 sleep 不拦截。
+- 不影响:短于 25 秒的前台 sleep、超时转后台(首个原始 token 为 `sleep` 的命令仍不进入超时转后台,见根目录
+  `docs/bash-background-parity.md`)、硬超时、后台命令。
+
 ## Prompt 约束
 
 Bash prompt 对模型有几类强约束:
@@ -136,7 +179,8 @@ Bash prompt 对模型有几类强约束:
 - Bash 主要用于运行测试、构建、包管理器、git/gh、系统命令、脚本和没有专用 tool 覆盖的 shell 操作。
 - 多个独立命令可并行发多个 Bash tool call。
 - 有依赖关系的命令才用 `&&`。
-- 避免不必要 sleep,长任务用 background 或 Monitor。
+- 避免不必要 sleep:等条件用后台 until 循环,等已启动的命令用 `run_in_background`;25 秒以上的前台 sleep 由
+  `validateInput` 拒绝(「前台 sleep 拦截」)。
 - git destructive 操作必须有用户明确指令。
 - 不跳过 hooks 或 signing,除非用户明确要求。
 - sandbox 模式下临时文件用 `$TMPDIR`,不直接写 `/tmp`。
@@ -148,6 +192,22 @@ provider-visible 描述包括 "Command output is displayed to you, not reliably
 以及 `description` 参数里的 "Say what the command does in plain words…" 一段。Git 段不要求在
 commit/PR 末尾附加署名行:ZCode 不下发署名行。
 
+描述里另有三处固定文字(2026-11-15):
+
+- cd 一行写明延续规则(行为见上面「行为语义」第 5 步,没有变):
+  "- \`cd\` carries to the next call only in the main session, if the command succeeds and ends inside the working
+  directories. Outside them the shell returns to the start folder; otherwise it stays where it was. Prefer absolute
+  paths — \`cd\` in a compound command can trigger a permission prompt. Shell state (env vars, functions) does not
+  persist; the shell is initialized from the user's profile."
+- `run_in_background` 一行末尾加一句:"Foreground \`sleep\` of 25 seconds or more is blocked; to wait on a condition,
+  run an until-loop with \`run_in_background\`."(「前台 sleep 拦截」)。
+- Git 段在 `gh` 一行之后、"Commit or push only…" 之前加一行:"- GitHub notifies the owner of any \`@name\` written
+  in a PR, issue, or comment. Write a bare \`@name\` only for a real login you mean to notify. Put roles,
+  placeholders, and code (\`@human\`, \`@reviewer\`, \`@types/node\`) in backticks or drop the \`@\`, even when copied
+  from project files."
+
+三处在主会话与子代理相同,不按模型或 `gh` 是否可用变化(上面按行折开,实际都是单行)。
+
 ## 权限模型
 
 `Bash` 是动态权限工具:
@@ -167,14 +227,114 @@ ZCode 应把 shell permission 拆成三个层次:
 - `ShellPermissionPolicy`:规则匹配、危险语义、readonly 判断。
 - `ExecutionPort`:真正执行命令、处理 timeout、cancel、stream、sandbox。
 
+### Direct adb execution admission
+
+Direct adb is permitted without Android MCP. The security boundary is the
+workspace executable path, not the adb name or plugin availability.
+
+Before starting any foreground/background process, Bash finds statically known
+adb command words with the parser of the selected dialect: POSIX/Git Bash or
+CMD. `legacy-shell` is only the POSIX `/bin/sh` fallback (Windows no longer
+produces it), so it uses the POSIX parser only. Quoted arguments, heredoc bodies
+and other argument text are never treated as adb command words and are not
+rewritten.
+
+The execution adapter resolves each word asynchronously. Explicit paths are resolved against
+the invocation cwd; bare names search configured/default Android SDK locations
+before absolute PATH entries. Empty, relative, and workspace PATH entries are
+skipped; no `where`, `which`, or workspace executable is run during discovery.
+Both the lexical candidate and its canonical real path must be outside the
+workspace root (including its real path). A workspace symlink to an external SDK
+is still workspace-controlled and is rejected; an external symlink into the
+workspace is rejected too.
+
+Bash substitutes only the executable word with the checked, quoted canonical
+absolute path. This pins the check and execution to the same target, including
+bare adb on CMD, where a second search would otherwise select cwd first. All
+identified invocations are checked before any segment of a compound command runs.
+SDK/PATH lookup uses the execution adapter environment; it does not run shell
+startup files to discover dependencies. A shell-only PATH change can be handled
+by using the installed SDK's absolute path. Relative paths are pinned to the
+invocation cwd, not guessed from preceding shell `cd` or wrapper state changes.
+
+```text
+Bash input → existing permission flow → identify direct adb words
+  → execution adapter resolves paths and checks workspace ownership
+    ├─ workspace path → PermissionDenied (workspace-adb-blocked), no process
+    ├─ external executable → substitute its canonical absolute path → execute
+    └─ missing executable → actionable SDK/PATH error, no workspace fallback
+```
+
+Approval cannot bypass workspace rejection. Foreground and background share the
+same preparation. CMD `@` prefixes and `call`, POSIX `command`/`exec`, and already
+supported transparent wrappers retain their parsing behavior. Source spans keep
+CMD syntax prefixes separate from quoted literal `@` file names. Arguments,
+redirections, command order, normal build commands and project scripts are not
+rewritten. Lookup-only `command -v/-V adb` and ordinary mentions of adb remain
+unchanged. Paths that cannot be safely represented in CMD return an explicit
+configuration error instead of allowing command expansion to change the target.
+
+This remains a bounded check for literal direct invocations. Script bodies,
+interpreter programs, dynamic expansion and unsupported shell syntax are not
+inspected; permitted project scripts retain their existing capabilities. It is
+not a subprocess sandbox. Android MCP keeps its independent SDK/PATH hardening
+and is optional. iOS is unchanged.
+
+Regression covers workspace relative/absolute adb, CMD prefixes, compound
+commands, external SDK paths and bare names, symlinks in both directions,
+workspace/relative PATH entries, missing SDK, all approval modes, and both
+execution paths. Real-process fixtures first prove the fake binary's marker
+works, then prove denied calls never create it, allowed SDK calls succeed, and
+normal Node scripts and a TypeScript build still run. Windows fixtures use native
+executables and cover CMD plus Git Bash when installed. Portable CMD parsing
+checks do not count as native Windows acceptance.
+
+Run `pnpm --filter @zcode/core exec vitest run tests/bash-adb-admission.test.ts`
+after building the CLI dependencies. The build fixture is a project build script,
+not a complete Android Gradle build. This change narrows the original all-adb product rule without reverting the
+MCP resolver fix or allowing project-controlled adb binaries.
+
 ### read-only Bash allowlist
 
-运行时明确选择 `cmd` 或 `legacy-shell` 时,Bash AST 不能证明实际命令只读:例如
+运行时选择 `cmd` 或 `legacy-shell` 时,**不能用 Bash AST 判定只读**:例如
 `type # & python script.py` 在 Bash AST 中只剩 `type`,CMD 却仍执行后面的 Python。
-这两种 shell 不授予只读免审批,也不使用 Bash AST 推导 prefix/wildcard allow;建议授权只保存
-完整命令。Build/Edit 默认请求审批,Plan 拒绝(完整命令 allow 也不能越过 Plan)。完整命令和
-工具级明确授权、yolo/guarded、已有 deny/ask 匹配保留。此最小修复不增加 CMD 解析能力,
+这两种 shell 不使用 Bash AST 推导只读或 prefix/wildcard allow;建议授权只保存完整命令。
+完整命令和工具级明确授权、yolo/guarded、已有 deny/ask 匹配保留;guarded 的危险命令判定先于只读判定。
 CMD 子命令 deny 匹配仍有原有语法边界;POSIX/Git Bash 及未传 selection 的旧内部调用不变。
+
+只读改由 `bash-cmd-readonly-policy.ts` 按 **CMD 语法** 保守判定(2026-11-13),宁可漏放、不可错放:
+
+- **只在实际执行器是 cmd.exe 时适用**:Windows 上 `dialect=cmd` 且 `path` 匹配 Node 的
+  `/^(?:.*\\)?cmd(?:\.exe)?$/i`(只有这种 shell Node 才用 `/d /s /c` 启动),或 `dialect=legacy-shell`
+  (adapters 回落到 `ComSpec ?? cmd.exe`,同样要求匹配该正则)。POSIX 上的 `legacy-shell` 是 `/bin/sh`,仍不给只读。
+  2026-11-17 起 Windows 回落直接产出 `dialect=cmd`、`path=ComSpec ?? cmd.exe`,判定结果不变;Windows `legacy-shell`
+  分支只剩兼容,另行清理。
+  文件名只决定 Node 的启动参数,不能证明文件就是 CMD,所以 shell 还必须是带盘符的完整路径,realpath(解析链接、短名)后
+  等于 `%SystemRoot%\System32\cmd.exe` 或 `SysWOW64\cmd.exe`(SystemRoot 缺失时用 windir)。裸名 `cmd.exe`
+  (ComSpec 缺失时的回落)一律不认:libuv 会先在子进程 cwd,也就是工作区里找同名文件。
+- **只接受单条简单命令**:整串只能由白名单字符组成——ASCII 字母数字、空格、制表符和 `. _ - / \ : * ? + ~ # [ ]`;
+  内置命令另外允许 Unicode 字母和组合符号(中文文件名),外部程序只允许 ASCII(防 ANSI 代码页 best-fit 把全角符号变成 `"`)。
+  `& | < > ^ % ! ( ) " ' @ , ; = $` 和反引号、换行、回车等都不在白名单里,所以命令连接、管道、重定向、转义、
+  变量展开、分组、引号都会被挡掉,按空格/制表符分词就是实际 argv。
+- **命令白名单**(不区分大小写,不允许带路径或写成 `dir/b` 这类连写):
+  - CMD 内置:`dir`(开关都只读)、`type`;
+  - 外部程序:`findstr`、`where`、`git`,可带 `.exe`。`git` 复用 Bash 的只读子命令与全局参数规则
+    (`-C`、`-c`、`--git-dir` 等被拒)和 `isGitRuntimeContextUnsafe`,参数里不能有 `* ? [ ]`。
+- **防 Agent 可写目录里的同名程序**:CMD 先搜当前目录再按 PATH 顺序搜,每个目录尝试原名和 PATHEXT 的各扩展名。
+  Edit 模式下写工作区文件免审批,所以外部程序要求:已知工作目录;PATH 条目都是带盘符的完整路径(`C:\…`)——
+  相对、根相对(`\bin`,cmd.exe 按执行目录的盘符解析)、盘符相对(`C:bin`)条目,以及以 `\\` 或 `//` 开头的条目
+  (UNC、`\\?\`、`\\.\`、`\\localhost\C$` 这类可能指回工作区、又不能为了证明而访问网络的写法)一律拒绝,
+  盘符条目经 realpath 落到 UNC 的(映射盘、指向共享的 junction)也拒绝;当前目录,以及 PATH 里
+  (按 realpath 解析链接后)位于工作区根或当前目录之内的条目(例如 `node_modules\.bin`、`.venv\Scripts`),都没有
+  `<名字>`、`<名字><PATHEXT 扩展名>`、`<原词><PATHEXT 扩展名>` 这些文件(目录不算)。只要有就拒绝,不管它在 PATH 里排在哪。
+  候选文件用 lstat 逐个探测、不枚举目录,大小写和 8.3 短名由文件系统按与 CMD 相同的规则匹配。工作区外的绝对 PATH
+  目录属于用户自己的环境,与 POSIX 下 PATH 查找同等信任。`dir`、`type` 是内置命令,不受同名文件影响。
+- **路径参数**:出现 `\\`、`//` 等双斜杠(UNC、`\\?\`、`\\.\`)或 `\??\` 前缀即拒绝(会触发网络认证或绕过路径解析);
+  任一路径分量(按 `\ / :` 切分)的主名是设备名(CON、PRN、AUX、NUL、COM0-9、LPT0-9、CONIN$、CONOUT$、CLOCK$)即拒绝,
+  `type con` 会挂住等输入。
+
+判定为只读的返回与 Bash 相同的只读 capability:Plan 放行、Build/Edit 免审批、`ToolCallStarted` 报
+`readOnly=true`。其余仍是非只读、`system` 副作用:Build/Edit 请求审批,Plan 拒绝(完整命令 allow 也不能越过 Plan)。
 `ToolCallStarted` 的副作用能力必须携带同一 shell 上下文计算,避免将经审批的 CMD 再标成只读。
 
 `Bash` 只有在 AST 可安全解析、每条 simple command 的参数、赋值和重定向均通过
@@ -194,6 +354,16 @@ plan mode 因此只会自动放行这类 Bash;其他 Bash 仍按 plan mode 的
 超出子集的 sed 在普通 Build 默认转为审批;Plan 关闭后的其他模式及显式授权沿用原规则。
 `cat`、`grep` 等命令的现有安全参数继续有效。权限服务、执行端和展示层不增加 sed 特判。
 
+2026-11-14 起名单补入压缩包查看(`unzip -l/-v/-t`、`unzip -Z`、`zipinfo`、`tar -t`)、Windows 查询
+(`dir`、`findstr`、`where`)、`whereis`、`iconv`(无 `-o`)、`xxd`(单文件)、`command -v/-V`,
+以及 `git --version`、`git ls-tree`、`git log --follow/-L` 和 `git grep -r/-I` 等。这些形态在 Plan 下放行,
+在 Build 下同样免审批;解压、写输出文件、执行程序的形态仍按非只读处理。带冒号的 tar 归档名
+(含 Windows 盘符)需要 `--force-local`。`tar`、`unzip`、`zipinfo`、`iconv`、`xxd`
+带未引用通配符时不算只读(展开后的文件名可能变成选项或输出文件)。逐条规则见 [AST 权限语义](../../../bash-tool-ast-permission-semantics.md)。
+`cmd`/`legacy-shell` 不使用本名单,由 CMD 只读策略另行判定(`bash-cmd-readonly-policy.ts`,只收 dir、type、
+findstr、where、git);其中 git 复用本名单的 `isGitReadOnlyCommand`,所以本次 git 的新增形态在 CMD 下同样生效,
+unzip、tar、iconv、xxd 等其余新命令只对 Git Bash 等 POSIX 方言生效。
+
 ## 跨平台要求
 
 ZCode 不能只实现 POSIX Bash:
@@ -207,11 +377,12 @@ Windows 执行 adapter 的最低兼容规则:
 
 - ZCode 在 Windows 上不得要求用户安装 Git Bash、MSYS2、Cygwin 或 WSL 才能运行内置 Bash tool。
 - `ExecutionPort` 的内部 `argv` mode 在 Windows 上必须解析 `PATHEXT`,支持 `pnpm` / `npm` / `npx` 这类只在 PATH 上暴露为 `.cmd` 的 shim。
-- Windows `PATH` 按 `;` 拆分,去掉条目首尾的双引号(例如 `"C:\Program Files\Git\cmd"`),跳过空条目;Git Bash 检测与自动 git 用同一个拆分函数。引号里含 `;` 的条目仍在 `;` 处拆开(Node 按裸名启动时把它当作一个目录),这种写法不支持。
+- Windows `PATH` 按 `;` 拆分,去掉条目首尾的双引号(例如 `"C:\Program Files\Git\cmd"`),跳过空条目;Git Bash 发现与自动 git 共用该拆分契约。引号里含 `;` 的条目仍在 `;` 处拆开,这种写法不支持。
+- Git Bash 发现复用 Node-only 共享实现:保留固定目录/PATH 顺序,遍历全部 Git 候选;前一个没有配套 Bash 时继续后面的安装。未找到时补充系统目录、Git 安装根变量、官方安装记录(含 WinGet/Chocolatey 安装版)、Scoop 根/配置/shims 线索和 Chocolatey PortableGit 工具根。文件与安装记录异步读取;新增根校验 Git for Windows 布局,不执行代理脚本或 Bash,不泛搜其他发行版 `bash.exe`。发现范围和错误规则见 [Bash Effective Shell Snapshot](../../../../../../docs/runtime-tools/bash-effective-shell-snapshot.md#解析规则)。
 - 解析到 `.exe` / `.com` 等原生可执行文件时继续使用 `spawn(file, args, { shell: false })`。
 - 解析到 `.cmd` / `.bat` 时不得直接 spawn;必须显式通过 `ComSpec` 或 `cmd.exe` 执行,并保留 timeout、cancel、stdout/stderr、trace 和 output budget 行为。参数必须按 `cmd.exe` 规则转义,覆盖空格、双引号、管道、重定向、括号、`&`、`^` 和 `%` 等特殊字符。
 - `shell` mode 在 Windows 上默认使用环境里的 `ComSpec` / `COMSPEC`,缺失时退回 `cmd.exe`;在非 Windows 上保持 Node 默认 shell。
-- Windows `Bash` tool 可在 `command.shellProfile === "posix-bash"` 的内部执行路径上 best-effort 使用已安装且可检测到的 Git Bash。Git Bash 仍是可选能力:如果无法解析,`Bash` 必须回退到现有 `ComSpec` / `cmd.exe` 路径。
+- Windows `Bash` tool 可在 `command.shellProfile === "posix-bash"` 的内部执行路径上 best-effort 使用已安装且可检测到的 Git Bash。Git Bash 仍是可选能力:如果无法解析,selection 是 `dialect=cmd`、`path=ComSpec ?? "cmd.exe"`、显示名 `cmd.exe`(2026-11-17 起,原为 `legacy-shell` / `system shell`),执行仍走 `ComSpec` / `cmd.exe`。
 - Windows `Bash` tool 可接受 ZCode runtime settings 注入的内部 shell override。有效的用户配置 override 优先级高于自动 Git Bash 检测。
 - ZCode 不新增 Git Bash 路径环境变量,也不设 Windows startup gate。缺失 Git Bash 是 fallback 条件,不是启动失败。
 - Generic `ExecutionPort` shell mode 在 Windows 上继续使用 `ComSpec` / `cmd.exe`;Git Bash 自动检测和 shell override 只适用于 Bash tool 创建的 `command.shellProfile === "posix-bash"`。
@@ -262,7 +433,7 @@ flowchart LR
 
 | 场景      | 行为                                                                                                                                                    |
 | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| 前台 Bash | 默认等待预算 `120000ms`,默认最大值 `600000ms`;eligible 命令到达预算后提交为后台任务,首 token 为 `sleep` 的命令则返回结构化 `timed_out`;tool executor 的外层 timeout 只保留清理宽限期 |
+| 前台 Bash | 默认等待预算 `120000ms`,默认最大值 `600000ms`;eligible 命令到达预算后提交为后台任务,首 token 为 `sleep` 的命令则返回结构化 `timed_out`(模型看到 `Exit code 143` 与超时行);tool executor 的外层 timeout 只保留清理宽限期 |
 | 后台 Bash | `run_in_background=true` 在进程启动成功后立即提交后台;无论是否显式传入 `timeout`,提交动作都必须清除前台 deadline 并解绑 parent turn abort,不能把前台预算误当后台任务寿命 |
 | 大输出    | Bash 默认 inline limit 为 `30000` bytes,`BASH_MAX_OUTPUT_LENGTH` 按十进制 `parseInt` 解析,非法或非正数回退 `30000`,最大 `150000`;普通前台 retained file 保留完整原始输出,返回读取时观测大小 |
 | 后台事件  | 后台任务启动、状态更新和完成必须转成 session event。TUI/GUI 只消费 session event,不直接读取 adapter 内部状态                                           |
@@ -298,7 +469,7 @@ spawning
   |-- explicit -------------> COMMIT_BACKGROUND
   |-- eligible foreground --> running -- complete --> foreground result
   |                                  \-- deadline --> COMMIT_BACKGROUND
-  \-- first-token sleep ----> running -- deadline --> timed_out / kill
+  \-- first-token sleep ----> running -- deadline --> timed_out / kill (exit code 143)
 
 COMMIT_BACKGROUND
   state CAS -> clear deadline -> detach parent abort -> register adapter task

Разница между файлами не показана из-за своего большого размера
+ 100 - 12
apps/zcode-cli/docs/design/v2/tool/07-subagent.md


+ 24 - 11
apps/zcode-cli/docs/design/v2/tool/12-input-normalization.md

@@ -37,16 +37,21 @@ hook updated input 以及 broker modified input。
 
 职责:
 
-- 当 provider 返回的 `toolCall.input` / `toolCall.args` 是字符串时,尝试把它当成 JSON 解析。
+- 当 provider 返回的 `toolCall.input` / `toolCall.args` 是字符串时,尝试把它当成 JSON 解析。空串或只含空白的串
+  直接当作 `{}`(没给参数),不算解析失败。
 - 若解析成功,则把解析后的值作为 tool call input 继续向下游传递。
-- 若解析失败,则保留原始字符串,并记录最小化诊断信息,例如 tool name、来源阶段、字符串长度。
+- 若解析失败,则返回带解析失败标记的 `{}`:标记是 symbol 键,值为原始字符串前 200 个码元的 preview 与原始长度
+  (根目录 `docs/model-tool-call-validation.md`「Malformed tool input JSON」),并记录最小化诊断信息,例如 tool name、
+  来源阶段、字符串长度。
 - 诊断中不得写入完整原始 input,避免日志泄露用户内容。
 
 失败语义:
 
 - 不能抛出异常。
-- 不能在 adapter 层把失败输入伪造成合法业务对象。
-- 失败后继续把原值交给第二层 / executor,让后续 schema 验证返回结构化错误。
+- 不能在 adapter 层把失败输入伪造成合法业务对象:`{}` 带着标记,executor 据此返回无法解析 JSON 的错误,不执行工具。
+- 原始字符串不作为 input 往下传:tool_use 的 input 会进入 provider 历史与持久化 tool part,字符串在部分 provider
+  协议下不是合法的 tool_use input,冷恢复时也会被写成 `{ value: <字符串> }`,与实时请求不一致。symbol 键不进 JSON,
+  所以历史、持久化与 model-io 都是 `{}`。
 
 覆盖范围:
 
@@ -70,11 +75,17 @@ hook updated input 以及 broker modified input。
 - 每个 tool 的 runtime schema 决定默认值、字段裁剪、严格性和额外约束。
 - executor 不写死 Bash / Read / Edit 的内部规则,只消费显式的 `runtimeInputSchema` 契约。
 - 若未来某个 tool 需要 legacy 字段映射或更复杂兼容,应在同一层扩展,而不是散落到 handler 内部。
+- `Read` 的 runtime schema 用 preprocess 修正 `offset` / `limit` / `length`(包括 `length` 改名为 `limit`),再做字段校验
+  (规则见 [01-read.md「输入修正」](./01-read.md#输入修正))。preprocess 只属于 runtime schema;provider-visible
+  JSON Schema 仍从未包装的字段 schema 生成,tools 段字节不变。
 
 失败语义:
 
 - `safeParse` 失败不能抛出。
 - 失败必须降级为正常的 schema validation / permission error 路径。
+- 模型原始输入(initial):JSON Schema 通过、但 runtime schema 失败且有可读 issues 时,executor 在 `validateInput`
+  之前返回 `InputValidationError`(规则见根目录 `docs/model-tool-call-validation.md`)。需要友好文字的语义检查写在
+  `validateInput`,不写进 runtime schema。
 - hook 或 permission broker 返回 `modifiedInput` 后,必须重新执行第二层归一化。
 
 ## 执行顺序
@@ -83,12 +94,13 @@ tool runtime 调度顺序更新为:
 
 1. adapter 层归一化 provider 返回的原始 tool input
 2. executor 层 tool-aware 归一化
-3. `validateInput`
-4. `PreToolUse` hook
-5. 若 hook 更新了 input,则再次执行第二层归一化
-6. permission check / broker
-7. 若 broker 修改了 input,则再次执行第二层归一化
-8. handler 执行
+3. JSON Schema 校验;JSON Schema 或 runtime schema 失败时返回 `InputValidationError`
+4. `validateInput`
+5. `PreToolUse` hook
+6. 若 hook 更新了 input,则再次执行第二层归一化
+7. permission check / broker
+8. 若 broker 修改了 input,则再次执行第二层归一化
+9. handler 执行
 
 ## 非目标
 
@@ -101,10 +113,11 @@ tool runtime 调度顺序更新为:
 至少覆盖以下场景:
 
 1. adapter 层把字符串化对象成功还原为对象。
-2. adapter 层遇到非法 JSON 字符串时不抛异常,并保留原值。
+2. adapter 层遇到非法 JSON 字符串时不抛异常,返回带解析失败标记的 `{}`;executor 不执行工具,返回无法解析 JSON 的错误。
 3. stream `tool_call` 事件也使用同一归一化策略。
 4. executor 层在 adapter 未处理到的情况下,仍能把字符串化对象恢复为对象。
 5. executor 层会消费 `runtimeInputSchema.safeParse()` 的默认值或标准化结果。
 6. executor 层遇到非法 JSON 字符串时不抛异常,而是返回现有的可恢复输入错误。
 7. `PreToolUse` hook 返回 `updatedInput` 时,executor 必须重新执行第二层归一化。
 8. permission broker 返回 `modifiedInput` 时,executor 必须重新执行第二层归一化。
+9. `Read` 的 `offset` / `limit` / `length` 修正在 JSON Schema 校验之前生效,修正后的输入进入 handler。

+ 6 - 2
apps/zcode-cli/docs/design/v2/tool/13-websearch.md

@@ -49,8 +49,12 @@ public input:
 | `blocked_domains` | 可选,排除这些 domain 的结果 |
 | `maxUses` | 可选,内部 provider-native 搜索次数上限,默认 `8` |
 
-`allowed_domains` 和 `blocked_domains` 不能同时传入。domain 只接受 hostname,不接受
-protocol、path 或 wildcard。
+`allowed_domains` 和 `blocked_domains` 不能同时传入:两个数组都非空时,`validateInput` 在 PreToolUse Hook 与权限之前
+返回 `errorCode=2`,模型收到 `<tool_use_error>Error: Cannot specify both allowed_domains and blocked_domains in the same request</tool_use_error>`。
+这条检查不写进 runtime schema,否则会先返回 InputValidationError(根目录 `docs/model-tool-call-validation.md`)。
+hook 改写后的输入不再经过 `validateInput`,handler 开头用同一个检查再拒绝一次。
+修复原因:原来只有 runtime schema 的 refine 表达这条规则,handler 不解析输入,请求原样交给 provider,本地不报错。
+domain 只接受 hostname,不接受 protocol、path 或 wildcard。
 
 模型可见描述是固定文本。月份一行写作
 `The current month is (provided in the conversation below)`,不写入真实月份:模型从会话中的

+ 55 - 12
apps/zcode-cli/docs/design/v2/tool/17-read-file-state-resume.md

@@ -24,10 +24,11 @@ Read 去重与写前检查结果相同;Bash 回填和 Recall 注入的记录
 ## Resume 契约
 
 普通 `resume` 不新增独立持久化表,也不把 read-state 写入 provider-visible history。
-它从当前 active transcript 重建 runtime-local `readFileState`。Read state 至少包含
-模型看到的 `content`、`offset`、`limit`、`isPartialView` 和用于 stale guard 的时间戳;
-恢复来源只允许使用 completed tool part metadata 里持久化的结构化 read-state,其中时间戳
-使用 `mtimeMs`,并同时保留文件系统 adapter 暴露的 `revisionId`:
+它从当前 active transcript 重建 runtime-local `readFileState`。live 记录包含模型看到的
+`content`、`offset`、`limit`、`isPartialView` 和用于 stale guard 的时间戳;持久化快照不存正文,
+只存正文的 `contentSha256`(见下文“快照不存正文”)。恢复来源只允许使用 completed tool part
+metadata 里持久化的结构化 read-state,其中时间戳使用 `mtimeMs`,并同时保留文件系统 adapter
+暴露的 `revisionId`:
 
 - 只扫描 compact / rewind 后仍 active 的 message。
 - 成功的 `Read` 都会恢复,包括显式带 `offset` / `limit` 的 range `Read`;每个文件只留最近一次。
@@ -43,7 +44,7 @@ Read 去重与写前检查结果相同;Bash 回填和 Recall 注入的记录
   [Assistant 内容块顺序](../model/assistant-block-order.md))。
   同一条消息里的快照都带 `snapshotIndex` 时按它排序,否则(旧数据)保持 part 原顺序。被 token cap
   截断的 `Read` 恢复为 `isPartialView: true`。
-- 成功的 `Write` / `Edit` 用 completed tool part metadata 里持久化的完整快照恢复为当前文件
+- 成功的 `Write` / `Edit` 用 completed tool part metadata 里持久化的完整视图快照恢复为当前文件
   状态。resume 时不读当前磁盘来补全:外部的手动保存不能被当成模型已读。
 - 恢复过程只影响本 runtime 的文件 mutation guard,不产生新的模型消息、stream 事件或
   app protocol 字段。
@@ -61,7 +62,8 @@ same-runtime 读取语义:
 - `Write` / `Edit` 修改既有文件前必须找到同文件最新 read-state,并拒绝
   `isPartialView`。
 - stale fallback 只有 strict full read 可以在 mtime 前进但内容相同的情况下放行;range
-  read 遇到 mtime 前进必须要求重新读取。
+  read 遇到 mtime 前进必须要求重新读取。带正文的记录直接比较正文;冷恢复或 rewind 从新快照重建的
+  记录没有正文,比较当前内容的 sha256 与 `contentSha256`,结果与比较正文相同。
 
 ## Compaction 之后
 
@@ -95,14 +97,16 @@ read-state hydrator 必须独立于 UI、desktop service 和远控 replayable st
 `SessionStorePort.messages()` 返回的 tool parts 和当前 `FileSystemPort`,不新增
 `@zcode/protocol` 字段,不改变 desktop continuous 或 web remote replayable 的消息流。
 
-成功 full `Read` 的 completed tool part metadata 需要额外保存一个 versioned
+成功的 `Read`、`Write`、`Edit` 与内联草稿在 completed tool part metadata 里额外保存一个 versioned
 `readFileState` snapshot:
 
-- `tool: "Read"`,避免其他 tool metadata 被误用。
+- `tool`,记录快照的工具名;恢复时必须与 tool part 的工具名一致,避免其他 tool metadata 被误用。
 - `schemaVersion`,用于后续兼容演进。
-- `path`、`content`、`offset`、`limit`、`isPartialView`、`mtimeMs`、`sizeBytes`、
+- `path`、`contentSha256`、`offset`、`limit`、`isPartialView`、`mtimeMs`、`sizeBytes`、
   `revisionId`,对应 runtime `ReadFileStateEntry` 的可恢复字段;`mtimeMs`、
   `sizeBytes` 和 `revisionId` 必须完整存在,否则该 metadata 不参与恢复。
+- `contentSha256`:live 记录正文的 sha256,按 UTF-16LE 编码计算(JS 字符串的码元原样参与哈希),小写 hex。
+  快照不存正文本身。
 - `readAtMs`,使用 tool completed time 作为恢复后的水位时间;只作时间,不参与恢复排序。
 - `snapshotIndex`(可选),执行器在工具记录快照时取的序号,一个 runtime 一个计数器、只增不减;
   只在同一 assistant 内比较先后,绝对值没有含义。旧版本按字段名读取 metadata,忽略这个字段。
@@ -110,13 +114,44 @@ read-state hydrator 必须独立于 UI、desktop service 和远控 replayable st
 resume 恢复优先级:
 
 1. `metadata.readFileState` 存在、schema 匹配且 freshness metadata 完整时,直接恢复
-   结构化 snapshot。
+   结构化 snapshot。有 `contentSha256` 的新快照恢复为只带哈希的记录;没有 `contentSha256` 的是
+   升级前写下的旧快照,带正文 `content`,原样恢复为带正文的记录。两个字段都没有时不恢复。
 2. `metadata.readFileState` 缺失或缺少 `mtimeMs` / `revisionId` / `sizeBytes` 时跳过
    该历史 `Read`,不从 `state.output` 字符串解析 cat-n 文本。
-3. 成功的 `Write` / `Edit` 用 completed tool part metadata 里持久化的完整快照恢复,
-   schema 与 freshness 要求同第 1 条;正文不取 tool input,也不读 resume 当下的磁盘(外部的
+3. 成功的 `Write` / `Edit` 用 completed tool part metadata 里持久化的完整视图快照恢复,
+   schema 与 freshness 要求同第 1 条;不取 tool input,也不读 resume 当下的磁盘(外部的
    手动保存不能被当成模型已读)。没有该 metadata 的历史 `Write` / `Edit` 不恢复。
 
+### 快照不存正文(2026-11-11)
+
+背景:快照原来保存 live 记录的完整正文。`Edit` 每次成功都存一份修改后的整份文件,没有大小上限;
+同一个大文件编辑 N 次,历史里就有 N 份全文。打开长会话、任务结束后更新列表索引时,CLI 会读出并
+解析全部 part,JS 堆被这些快照撑满(用户长会话 745 MiB part 中 704 MiB 是工具 metadata;本机库
+6,195 条 Edit 快照共 561 MiB,单条最大 23 MB)。`Read` 快照的正文与 `state.output` 重复,`Write`
+快照的正文与 tool input 重复。
+
+恢复后,正文只用于一件事:strict full read 记录在 mtime 前进时判断内容是否相同。Read 去重只看
+mtime 与大小,compaction 补回重读磁盘,Bash 写后提示只看 mtime。判断“是否相同”只需要正文哈希,
+所以快照只存 `contentSha256`:
+
+```text
+live 记录(进程内):content 全文 ──写快照──▶ metadata:contentSha256 = sha256(content)
+冷恢复 / 同进程 rewind 重建:metadata ──▶ 记录只有 contentSha256,没有正文
+写前 stale 校验:有正文比正文;只有哈希时比 sha256(当前内容)
+```
+
+- 哈希按 live 记录比较时使用的同一个字符串计算,按 UTF-16LE 编码,哈希相同与字符串相同等价,判断结果
+  与原来比较正文相同。不用 UTF-8:UTF-8 编码会把孤立代理字符都换成 U+FFFD,只差一个孤立代理字符的
+  两份正文会得到相同哈希。不另加“字节数不同直接判 stale”的短路,避免磁盘字节数与解码后的正文口径
+  不一致时改变结果。
+- 不升 `schemaVersion`,按 `contentSha256` 是否存在区分新旧快照。已有会话里的旧快照不迁移、不改写,
+  冷恢复或 rewind 重建后继续带正文比较,随会话自然淘汰。
+- 旧版本 CLI 恢复时要求 `content` 存在,读到只有哈希的新快照会跳过恢复,`Edit` / `Write` 前要求
+  重新 `Read`;降级安全。
+- fork 与 selection side chat 照旧复制父会话的 part;快照变小后副本也随之变小。
+- 进程内 live 记录仍保存正文;内存中大文件只留哈希是后续单独一步。
+- `readFileState` 只在 CLI 内部使用,协议投影前删除(`message-mapper.ts`),App 与远控不受影响。
+
 恢复出的记录另带工具输入里 `file_path` 的原始写法(读取状态的 `requestedPath`,和 `path` 不同时才有),
 取自同一个 tool part 的 `input`,与 live 时工具记下的值相同。读权限规则按原始字符串匹配,compaction 补回用它和
 `path` 各判定一次 deny([rewind-compact.md](../rewind-compact.md) 的文件恢复)。原始写法不写进 metadata 快照。
@@ -147,3 +182,11 @@ resume 恢复优先级:
   context 初始化重新写入。
 - 同一文件多次读取只留一条记录,查找不遍历整张表。
 - Windows drive-letter path normalization 保持现有行为。
+- `Read`、`Write`、`Edit`、内联草稿新写入的快照带 `contentSha256`,不带 `content`。
+- 只有 `contentSha256` 的记录冷恢复或 rewind 重建后:文件只被 touch(mtime 前进、内容不变)时
+  `Edit` / `Write` 放行;内容变化时报 stale。
+- 没有 `contentSha256`、带正文的旧快照冷恢复或 rewind 重建后,判断结果与升级前相同。
+- 只差一个孤立代理字符的两份正文,只有哈希的记录也判为不同,与比较正文相同。
+- 真实 CLI、真实 SQLite 的冷恢复 E2E 覆盖以上三条:`e2e/compact-microcompact` 的
+  `read-state-hash-resume` case。同进程 rewind 重建由 core 单测覆盖
+  (`read-file-state-content-hash.test.ts`)。

+ 46 - 15
apps/zcode-cli/docs/design/v2/tool/19-tool-search.md

@@ -1,5 +1,7 @@
 # ToolSearch:启用、持久化与冷恢复
 
+动态 MCP:普通 step 固定快照,实时 ToolSearch 有限等待,MCP 状态(pending、needs-auth、failed)并入名称 delta。完整合同见 [动态 MCP spec](../../../../../../docs/mcp-async-tool-catalog-cache.md)。
+
 ## 模块边界
 
 `tool-discovery` 登记现有搜索 schema、搜索控制入口及请求投影;对外继续使用现有函数,
@@ -131,6 +133,19 @@ SQLite -> hydrate 目标调用与结果 -> 请求渲染时恢复原始包装 ->
 名称与内层参数;重存、历史复制和分支恢复必须保留。执行参数与历史隔离,Hook、审批和
 handler 不得修改历史原始输入。不重复存储包装 input;删除开发阶段旧 modelToolCall 格式,
 不保留兼容读取或数据迁移。准入失败只保存包装失败记录。
+
+准入失败的文字(`errorCode` 1,executor 包成 `<tool_use_error>…</tool_use_error>`,2026-11-14 起;原来不带标签):
+
+```text
+DeferredToolCall is not available for this request.
+Invalid DeferredToolCall input.
+Tool not available in this request: <name>
+Call <name> directly using its normal tool call; DeferredToolCall only accepts deferred tools.
+```
+
+包装入参本身不是合法 JSON 时,先返回无法解析的 JSON 错误(根目录 `docs/model-tool-call-validation.md`),名称是
+`DeferredToolCall`;入参缺字段时返回 InputValidationError,二者都在上面四句之前判定(第一句除外:本请求不提供
+DeferredToolCall 时先返回第一句)。
 请求渲染在已有遍历中恢复包装调用及结果名,剥离内部标记;不新增历史扫描或 callID 缓存。
 Todo 等业务判断直接使用内部目标身份;microcompact 用 sourceEntries 分类,仍用投影后的
 消息估算 token。V4 以 scheduled 目标事件定稿工具行,迟到原始流不得覆盖已定稿输入;
@@ -175,9 +190,8 @@ Explore 的 direct/embedded 两个白名单都包含搜索控制入口,保留
 
 Native 模式使用工具引用协议。默认 off;显式 auto/native/local 的选择规则见上文。
 Runtime 使用启动时确定的模式,子 Agent 继承,不写入 session;App 设置与 CLI 覆盖的来源见上文。
-无 deferred 或必要控制工具
-被禁用时恢复全量定义并记录原因。MCP 保持现有初始化;不实现异步就绪、搜索等待、
-OpenAI 原生引用、auto:N 或历史调用自动补装。
+无 deferred 且无 pending 服务,或必要控制工具被禁用时恢复全量定义并记录原因。MCP 交互入口后台启动;ToolSearch 实时读目录,并在无匹配或 select 缺项时最多等待相关 pending 服务 5 秒。
+不实现 OpenAI 原生引用、auto:N 或历史调用自动补装。
 
 ```mermaid
 flowchart TD
@@ -347,23 +361,31 @@ Native 与 Local 的真实 provider 请求均验证这段说明和参数描述
 - 新增公告完整列名;恢复公告分 MCP 与其他两段。MCP 段按 server 汇总名称及数量,文案为
   `available again (MCP server reconnected — names announced earlier in this conversation)`;
   其他工具逗号列名,文案为 `available again in this session (announced earlier in this conversation)`。
-- 删除分三段,顺序如下,之后追加 ambient-context 提示:
+- 删除分三段,顺序如下:
   1. 已离开工具目录、名称以 `mcp__` 开头:文案为 `(their MCP server disconnected)`,超过 30 个时
      按 server 汇总为 `(MCP server disconnected)` 计数版。
   2. 已离开工具目录的其他工具:文案为 `no longer available in this session`,逐行列名。
   3. 仍在 registry、只因本轮限制隐藏:保留中性文案 `no longer available`(不超过 30 个逐行,
      超过时汇总),不声称会话内不可用。
 - MCP 段只按名称前缀判断,不读取 `McpPort.status()`;server 仍连接但工具被移除、server 被停用或
-  删除时也写断开与重连。非 MCP 名称不会写成 MCP 断开。
+  删除时也写断开与重连。非 MCP 名称不会写成 MCP 断开。已列入撤销段的工具不再写成断开。
+- 删除按实际来源和连接事实解释。连接失败仅表示当前不可用;配置删除、禁用或策略撤销要求忽略旧定义及其描述中的指令(撤销段按原因分组)。来源恢复后用恢复段解除撤销。
+- 段落顺序:新增 → 恢复可用(MCP、其他)→ 撤销解除 → 删除三段 → 撤销 → ambient-context 提示
+  (有删除或撤销时)→ MCP 连接状态(需要授权、连接失败、仍在连接)。仍在连接段落写当前模式的搜索入口名。
 - 各公告段用空行分隔,沿用 `<system-reminder>` 包装和现有增量 metadata。每次请求按当前模式
   从 metadata 重新渲染公告(见上文 Local 命名),所以文案只能依赖持久化的事实。
   "本轮隐藏"要在生成时查 registry,之后 registry 会变:生成时把这些名称记为
   `toolSearchHiddenNames`,与 `toolSearchAnnouncement` 同级。`toolSearchAnnouncement` 按严格
   schema 校验,旧版本读到新键会丢掉整条公告事实;同级字段是宽松字段,旧版本忽略它。
   没有这个字段的旧记录,删除名称按"已离开工具目录"渲染。
-- 工具因本轮限制暂时隐藏时仍按现有增量逻辑公告;
-  相同目录不重复追加。不增加 pending/鉴权诊断、异步初始化或搜索等待。
-- 链路:`增量事实 + 隐藏名称 -> 持久化 -> 请求投影按当前模式渲染`;纯 Continue 不生成公告。
+- MCP 扩展事实记为同级的 `toolSearchMcpDelta`:pending、needs-auth、失败诊断、撤销和恢复。
+  渲染与生成使用同一个函数和同一份事实;没有这个字段时,输出与只有三数组的公告逐字节一致。
+  名称相同而状态改变也可生成公告;完全不变时不生成 delta;生成 delta 时包含当前状态正文。不新增独立 Ready 正文。
+  请求模式不是 off 且控制工具可用时才生成公告;已生成的公告只在请求模式为 off 时隐藏。
+- 工具因本轮限制暂时隐藏时仍按现有增量逻辑公告;相同目录与相同 MCP 状态不重复追加。
+- 最后一个当前 deferred 工具删除时仍提交删除公告;历史有已交付定义与有效引用时保留 ToolSearch。旧 mcp_server_status 不再投影,历史原文不改写。Off 不给出不可用的搜索或等待指引。
+- Native 保留真实 tool references;Local 在下一个普通 step 使用新目录展开 schema。实时搜索不修改同批 registry。纯 Continue、重试和 reactive compact 沿用固定快照。
+- 链路:`增量事实 + 隐藏名称 + MCP 扩展事实 -> 持久化 -> 请求投影按当前模式渲染`;纯 Continue 不生成公告。
   同一模式下每次请求和冷恢复后渲染出同一段文案,缓存前缀不变。
   不改 App 协议、Desktop continuous 或手机 replayable 交付边界。
 
@@ -414,14 +436,14 @@ Compact 成功 -> 按保留历史重建公告 -> 替换上下文 -> 后续请求
   与其他输入附件一样跳过 output-token recovery 和新轮通知的首个请求;公告先进入
   canonical 与 turn-local 历史,再复制 requestEntries。纯 Continue 不调用公告生成器,已有公告随快照保留。
 - 目录在纯 Continue 期间变化时,增删公告等待下一次正常收集;每次请求的 schema、
-  引用、权限与启用判断仍执行。不扩展 MCP pending/failed/鉴权状态。
+  引用、权限与启用判断仍执行。MCP pending、失败与撤销事实使用独立 metadata 扩展,不改变旧名称增量 schema。
 - Compact 在摘要成功后调用同一纯公告生成器:full 使用空保留历史,保留尾部的 compact
   使用 preservedEntries 比较。公告加入 postCompactReminderEntries;失败、取消或跳过不提交。
   Auto/Reactive 在 Continue 期间触发时同样重建,不依赖下一次正常提醒收集。
 - Compact 公告读取继续执行的工具目录,不能使用摘要请求裁剪后的候选工具。
   内部 getContinuationTools 回调复用本轮工具作用域筛选;手动 compact 使用当前 Runtime/Model。
   不改变摘要工具策略,不为 scope 建立第二份状态。
-- 公告仍是内存历史中的派生提醒,不新增持久化字段;冷启动首次正常收集时重建。
+- 公告通过既有 runtimeMessage metadata 保存;旧名称增量保持三数组,独立 toolSearchMcpDelta 保存 MCP 状态、撤销与恢复,单独校验并丢弃未知字段。compact 重建只比较名称,不写 MCP 状态、不计算撤销。冷恢复后按保留历史继续计算增量。
   已发现工具仍仅由真实引用和 compact 检查点恢复,P/C、App 协议及多端交付边界不变。
 - 回归捕获真实 Runtime 的 Model 请求与 canonical 历史:连续三次续写及下一输入均只有一份
   首次公告;目录变化、正常工具批次、full/保留尾部/续写期间 compact、失败取消、scope、
@@ -440,6 +462,9 @@ toolSearchAnnouncement?: {
 ```
 
 三个数组始终存在、去重、排序;readdedNames 是 addedNames 的子集。
+只有名称有变化时才写这个键;只有状态、撤销或恢复的公告只写 `toolSearchMcpDelta`。
+读取方按"两个键有其一"识别公告(off 隐藏、按模式重渲染、空正文过滤、冷恢复、状态累积)。
+旧版本按三个数组重渲染正文,三个数组都为空会得到空正文并报错;不写这个键时旧版本按普通合成文本恢复。
 不保存完整目录 snapshot 或 addedLines;完整列名为 addedNames − readdedNames。
 历史复制分别复制三个数组,不能共享可变引用。
 
@@ -532,14 +557,14 @@ Native 成功且投影后仍有有效引用的每条搜索结果,派生一条
 Local 仅使用结果内的加载和调用指引,不追加外部提示(见下文逐项反馈合同)。
 提示不写 canonical 历史或数据库,Off、错误、无匹配
 及引用全部失效不生成。复用现有引用和消息遍历,保留媒体真实用户索引、sourceEntries 与缓存标记。
-Continue 与 compact 过滤 query-local Continue 后重建请求记录时,复用本次引用投影已计算的
-有效结果 callID 集合;成功提示的位置和数量与实际请求一致,不重新扫描引用或持久化提示。
-回归同时检查实际 Model 请求、ModelRequest 事件及主轮状态快照,保留 Continue 不进入记录的规则。
+Continue 按隐藏提醒记录持久化,ModelRequest 事件与实际请求是同一份消息,成功提示的位置和数量与实际请求一致,
+不重新扫描引用或持久化提示。回归同时检查实际 Model 请求、ModelRequest 事件及主轮状态快照。
 
-参数校验失败且目标为当前未发现 deferred 工具时,在原有错误后以空行追加完整纠错段落:
+参数校验失败且目标为当前未发现 deferred 工具时,在原有错误正文之后、`</tool_use_error>` 之前以空行追加完整纠错段落:
 说明定义尚未进入已发现集合,以及数组、数字、布尔值被当作字符串输出时会导致参数校验失败;
 随后给出精确 `select:<canonicalName>`、重试指引和当前完整 input schema。
-Native 使用公共段落;Local 在段落末尾另起一行保留 DeferredToolCall 调用说明。
+Native 使用公共段落;Local 在段落末尾另起一行保留 DeferredToolCall 调用说明。这两部分都在包装之内。
+修复原因:段落原来接在 `</tool_use_error>` 之后,落在包装外面;纠错说明属于这次校验错误,应和错误正文在同一个包装里。
 回归断言完整段落及其与原始校验错误的拼接,不仅检查关键词。
 未搜索不成为执行禁令;已发现/Off/不存在工具维持原有错误。
 
@@ -840,3 +865,9 @@ unavailable schema 保留,不调整 UI、auto-compact 估算或多端交付边
 - 未运行 Windows/Linux、手机真机或真实 provider。用户确认 bench 位于本机不可访问的局域网机器;
   重复搜索率、任务成功率、token 开销及服务端 cache usage 待该环境验证。受控响应不证明模型会减少搜索。
 - 生产变更仅 4 个文件,不新增测试生产接口、数据库字段或 UI/多端链路。未提交、未推送。
+
+实时查询与普通 step 共用 MCP session 视图;查询不维护独立目录,不修改批次 registry,也不推动连接或目录刷新任务。
+
+### 历史定义交付
+
+Native 历史引用与当前目录分离。deferred 工具只记录被引用、并以 defer_loading 发送过的定义;常驻 MCP 定义首次出现时记录并冻结,离开目录后原位重新声明。请求准备纯投影已交付定义,只有有效 assistant 或保留的 partial 提交后才写入既有历史 metadata;记录不进入执行 registry,省略值为 undefined 的可选字段。撤销资格为被引用的 retained 名字加常驻记录;仅公告名称不算加载。compact 携带保留段引用的记录和已离开、未撤销的常驻记录。

+ 4 - 1
apps/zcode-cli/docs/design/v2/tool/README.md

@@ -150,13 +150,16 @@ L2 已经使公共契约不只用于登记和展示,runtime 会实际读取这
 - tool result event 应包含截断状态、原始大小、返回大小、预算策略和可用 artifact 引用,方便后续 UI、审计和恢复链路接管。
 - handler 的失败返回不是成功 output,不得进入 output schema 校验、成功序列化、
   `PostToolUse` 或后台任务追踪;应沿用现有 `PostToolUseFailure`、`ToolCallError` 和失败日志链路。
+- handler 正常返回、但结果是错误结果时(`isToolOutputError`,与 tool_result 的 `is_error` 同一判定,
+  例如 Bash 非零退出、MCP `isError: true`),结果照常校验、序列化和发出 `ToolCallResult`,
+  Hook 改为运行 `PostToolUseFailure`,不运行 `PostToolUse`(`hooks.md`「失败的定义」)。
 
 ### L3 Artifact 与 Output 校验约束(已实现,按 schema 需求增量加强)
 
 L3 已经补齐两个运行时闭环:
 
 - 成功 tool output 必须经过 `outputSchema` 校验。校验失败属于 tool contract 违约,按结构化 `tool_execution_failed` 返回,不把非法结果注入模型上下文。
-- JSON Schema 校验第一版覆盖当前 tool contract 使用的子集:`type`、`oneOf`、`const`、`enum`、`required`、`properties`、`additionalProperties`、`items`、`minimum`、`maximum`、`minLength`、`maxLength`。后续 schema 若使用更多关键字,必须先扩展 validator 和测试。
+- JSON Schema 校验第一版覆盖当前 tool contract 使用的子集:`type`、`anyOf`、`oneOf`、`const`、`enum`、`required`、`properties`、`additionalProperties`、`items`、`minItems`、`maxItems`、`minimum`、`maximum`、`minLength`、`maxLength`。`anyOf` 至少匹配一个分支、`oneOf` 恰好匹配一个分支,不满足时都报 `invalid_union`;同一节点两个都写时各查一次,都要满足;同一节点的其他关键字照常检查(2026-11-14 补 `anyOf`:工具 schema 的 union 与 nullable 改用 `anyOf`;2026-11-16 修正两者并存时跳过 `oneOf`,见根目录 `docs/model-tool-call-validation.md`)。后续 schema 若使用更多关键字,必须先扩展 validator 和测试。
 - `resultBudget.strategy: "artifact"` 且 `artifact.enabled: true` 时,超出模型预算的完整序列化结果必须通过 `ToolArtifactStorePort` 写入 artifact/storage。executor 只能依赖 port,不能直接调用文件系统或 session sqlite。
 - artifact 写入必须携带 `sessionId`、`turnId`、`toolCallId`、`toolName` 和 `trace`,返回的 `uri` 或 `path` 进入 tool result event 与截断提示。
 - 如果未配置 artifact store,executor 仍会按 `resultBudget` 截断模型内容,但不会伪造 artifact 引用。

+ 4 - 1
apps/zcode-cli/docs/usage/02-cli-reference.md

@@ -26,13 +26,16 @@ zcode hooks trust status --workspace /absolute/path/to/project --json
 - `--output-format text|json|stream-json`:控制普通 prompt 的输出,优先于 `--json`。
 - `--workflow-mode disabled|onDemand|alwaysOn`:当前源码中用于 prompt、target 和 TUI;默认 `disabled`。旧构建可能拒绝此参数。
 - `--memory-bench`:仅配合 `--prompt`,开启自动记忆提取并等待提取结束;须先启用记忆。
+- `--total-tokens-reminder on|off`:用于 prompt、target 和 TUI,默认 `off`。打开后 system 末尾带固定的 token 预算行,收集输入附件时附带剩余量提醒;只控制提醒,不限制实际用量。只对本次启动有效,不写入会话,`app-server` 拒绝此参数。`--resume` / `--continue` 恢复的会话,system 跟随 prompt 快照:关闭时写下的会话在下次压缩或换模型前不带预算行,打开时写下的会话在此之前保留预算行;剩余量提醒按本次参数收集。
+- `--agent-always-background on|off`:用于 prompt、target 和 TUI,默认 `on`。打开时 Agent 工具没有 `run_in_background` 参数,子代理总在后台运行,结果经完成通知在之后的回合送回;关闭时回到可选 `run_in_background`、省略时前台运行的形态。只对本次启动有效,不写入会话,`app-server` 拒绝此参数;同一进程里模型用 CreateSession 新建的根会话不继承它,按缺省开启。规则见 [07-subagent.md](../design/v2/tool/07-subagent.md)「ZCode 当前实现」。不论开关取值,`--prompt` 与 `--target` 都等后台工作(Agent、Bash、workflow)结束、通知回合跑完后才输出结果并退出,不设超时,见 [自动化](13-automation.md)。
 - `--browser-use=headless`:显式启用 CLI 管理的无界面浏览器;可用 `--browser-executable <absolute-path>` 指定浏览器。后者不能单独使用。
+- `--browser-state <path>`:配合 `--browser-use=headless`,在每个会话的浏览器上下文中注入只读的 Playwright storage state 登录态文件;相对路径按启动目录解析。不传时自动加载 `~/.zcode/cli/browser-state.json`(存在时),`--no-browser-state` 关闭默认加载。文件可用 `playwright open --save-storage <file> <url>` 在登录后关闭窗口生成;会话中的登录变化不会写回文件。
 - `--locale auto|en-US|zh-CN`、`--no-color`、`--verbose`:语言、颜色与附加诊断。
 - `--version`/`-v`:版本;`-v` 不是 verbose。
 
 插件命令还支持 `--scope`、`--available`、`--all`、`--keep-data` 等选项,见[插件](10-plugins.md)。`--force-mcs` 是 Anthropic 接口的专项诊断选项,不是通用评测开关。
 
-不要使用未经解析器支持的 `--print`、`--model`、`--settings`、`--max-turns`、`--allowed-tools` 或 `--permission-mode`。若需要运行时限,由评测进程管理器控制;不要杜撰 CLI token 或轮数预算参数。
+不要使用未经解析器支持的 `--print`、`--model`、`--settings`、`--max-turns`、`--allowed-tools` 或 `--permission-mode`。若需要运行时限,由评测进程管理器控制。除只控制提醒的 `--total-tokens-reminder` 外,没有 CLI token 或轮数预算参数,不要杜撰。
 
 ## JSON 与流式输出
 

+ 1 - 1
apps/zcode-cli/docs/usage/05-permissions.md

@@ -30,6 +30,6 @@ allow + Hook 阻断 → 工具失败
 
 用一次性目录测试 Read、Write 和 Bash。对普通内置文件工具,plan 应拒绝写入,edit 可写文件;build 的写入审批在无客户端的 prompt 中可能失败。使用自定义工具、插件或 MCP 时,须分别验证其能力声明和权限规则。
 
-出现 `No permission client configured` 时,检查当前模式和工具是否需要交互。不要仅通过重复提示模型来解决。移除不需要的交互工具,或选择具备审批客户端的交互入口。
+需要审批但 prompt 没有审批客户端时,工具被拒绝,模型收到 `ZCode requested permissions to use <Tool>, but you haven't granted it yet.`(Write / Edit 写 `…to write to <file_path>…`);guarded 模式下这次调用直接失败,错误为 `No permission client configured`。出现这两种情况时,检查当前模式和工具是否需要交互。不要仅通过重复提示模型来解决。移除不需要的交互工具,或选择具备审批客户端的交互入口。
 
 工具拒绝后模型仍可能继续回答,进程也可能返回 `0`。同时检查流式事件、工具结果和文件产物。需要按参数拦截某类工具时可使用同步 `PreToolUse` Hook,但简单命令正则不是完整沙箱,见[Hooks](09-hooks.md)。

+ 5 - 1
apps/zcode-cli/docs/usage/09-hooks.md

@@ -4,7 +4,11 @@ Hook 是在会话或工具事件上运行的本地程序,可记录事件、补
 
 ## 事件与最小配置
 
-支持 `SessionStart`、`UserPromptSubmit`、`PreToolUse`、`PermissionRequest`、`PostToolUse`、`PostToolUseFailure`、`Stop`。在运行配置中显式启用:
+支持 `SessionStart`、`UserPromptSubmit`、`PreToolUse`、`PermissionRequest`、`PostToolUse`、`PostToolUseFailure`、`Stop`。
+
+每次工具调用一般只运行 `PostToolUse` 和 `PostToolUseFailure` 中的一个(Hook 运行之后的步骤抛错时,会再运行一次 `PostToolUseFailure`)。工具结果是错误时运行 `PostToolUseFailure`,例如 Bash 非零退出、超时,或 MCP 返回 `isError`。这时 stdin 的 `error` 是模型看到的错误正文,没有 `tool_response`。grep、rg 等退出 1 表示没有匹配,不算错误,仍运行 `PostToolUse`。
+
+在运行配置中显式启用:
 
 ```json
 {

+ 1 - 1
apps/zcode-cli/docs/usage/12-troubleshooting.md

@@ -14,7 +14,7 @@
 
 ## 工具没有产生结果
 
-- `No permission client configured`:本次调用需要审批,但 prompt 没有交互客户端。检查模式、工具及 Hook 决策。
+- `… requested permissions to use <Tool>, but you haven't granted it yet.` 或 `No permission client configured`(guarded 模式):本次调用需要审批,但 prompt 没有交互客户端。检查模式、工具及 Hook 决策。
 - 只输出计划:检查是否触发了计划模式;无人值守任务按[工具配置](04-tools.md)移除不需要的计划和提问工具。
 - 项目 Hook 不执行:检查 enabled、matcher、信任状态和事件是否自然发生;信任后不会补跑已跳过的 SessionStart。
 - 插件清单为空:检查插件总开关、资源准备与诊断。当前版本可直接 list,不要求先发模型请求。

+ 2 - 0
apps/zcode-cli/docs/usage/13-automation.md

@@ -62,6 +62,8 @@ child.on("close", (code, signal) => {
 
 这只是启动片段。生产启动器还要持续写入 stdout/stderr 文件、记录开始结束时间、限制磁盘用量,并由容器或进程管理器设置运行时限、终止整个进程树。不能只杀父进程后假设所有 Bash、MCP 和后台任务都结束。按目标系统验证进程树清理。
 
+`-p` 运行在后台工作结束前不退出,不论 `--agent-always-background` 取值:第一个回合结束后,进程一直等到没有运行中的后台任务(Agent、Bash、workflow),也没有正在运行或排队的回合,才写出结果并退出。完成通知触发的回合也在等待之内,所以进程退出时任务产物已经写完,评分可以开始。等待不设超时:模型在后台启动的常驻进程(例如开发服务器)会让运行一直等待,运行时限由启动器设置。`--target` 和以 `/goal`、`/expert` 开头的 `-p` 走命令路径,命令返回后同样等待;目标续跑遇到后台任务时先推迟,通知回合在 runtime 内接着续跑,这些都在等待之内。这类运行输出命令本身的 `response`,不收集之后各回合的文字。等待期间收到 Ctrl-C 或启动器的信号时,进程不写结果:stdout 为空,错误写到 stderr,退出码是信号对应的值,所以启动器只看 stdout 就能分辨中断和正常结束。规则见 [dwf launch 的 Headless runs](../../../../docs/dynamic-workflow/launch.md#headless-runs)。
+
 ## 如何判定一次运行
 
 ```text

+ 9 - 1
apps/zcode-cli/e2e/compact-microcompact/README.md

@@ -6,6 +6,7 @@ Default cases:
 
 - `background-bash`: scripted provider, verifies foreground/background stdout-stderr write order, the single-path background result, and the exact completion notification sent to the provider.
 - `bash-read-state`: scripted provider, Bash `cat` backfills read-state for `Edit`, then formatter Bash emits a stale read hint.
+- `read-state-hash-resume`: scripted provider, isolated SQLite (`ZCODE_SESSION_DB_PATH`). Read/Write/Edit persist hash-only read-state snapshots (a ~21 KB file edit stays under 8 KiB per tool part); after cold resume a touched file passes `Edit`, a same-size content change is stale, and a pre-upgrade snapshot with full `content` (no `contentSha256`) still restores.
 - `microcompact`: real `deepseek-v4-flash`, two Bash outputs, local MicroCompact projection.
 - `manual-full-compact`: real model, `/compact`, post-compact continuation.
 - `auto-full-compact`: real model, low auto-compact threshold, mid-turn full compact.
@@ -13,7 +14,7 @@ Default cases:
 - `reactive-compact`: scripted provider, main request context overflow followed by reactive compact.
 - `openai-responses-compact`: fake OpenAI Responses provider; main turns stream, compact first receives a deterministic streaming failure, then succeeds through a non-stream JSON fallback that omits the two compatibility fields.
 - `usage-anchor`: scripted provider, verifies assistant `tokens` ownership across Full/Reactive Compact, input-only usage, empty-assistant cold hydration, and both kept/removed usage across conversation rewind. It checks live and hydrated runtime history directly; request `max_tokens` is retained only as capture evidence, not as the usage correctness assertion.
-- `output-token-continuation`: scripted provider, verifies the real adapter HTTP sequence contains 0/1/2/3 exact query-local Continue messages, real partial persistence, empty exhaustion's zero-usage transcript error carrier without a fifth request, runtime survival, and no carrier or Continue leakage after cold resume.
+- `output-token-continuation`: scripted provider, verifies the real adapter HTTP sequence contains 0/1/2/3 exact Continue messages, ModelRequest events that record the same messages, real partial and hidden Continue persistence, empty exhaustion's zero-usage transcript error carrier without a fifth request, runtime survival, and a cold-resume request that starts with the last live request (Continue replayed, carrier excluded).
 
 It is intentionally not part of the default test suite because real-provider cases need network access, a real API key, and provider spend.
 
@@ -56,6 +57,13 @@ Run only the Bash read-state E2E from this monorepo worktree:
 pnpm --filter zcode-cli exec tsx ../../apps/zcode-cli/e2e/compact-microcompact/run.mjs --case=bash-read-state
 ```
 
+Run only the read-state hash cold-resume E2E:
+
+```bash
+pnpm -r --filter @zcode/bootstrap... build
+pnpm --filter zcode-cli exec tsx ../../apps/zcode-cli/e2e/compact-microcompact/run.mjs --case=read-state-hash-resume
+```
+
 Run the fake OpenAI Responses compact compatibility E2E with no real API key:
 
 ```bash

+ 42 - 11
apps/zcode-cli/e2e/compact-microcompact/case-output-token-continuation.mjs

@@ -20,6 +20,7 @@ import { prepareWorkspace } from "./workspace.mjs";
 import {
   assistantContents,
   captureDurableAssistantHistory,
+  captureDurableContinueCount,
   captureRuntimeHistory,
 } from "./output-token-continuation-history.mjs";
 
@@ -187,7 +188,12 @@ async function runSuccessScenario({ app, events, input, paths, provider, runtime
     },
   );
   assertContinueRequestSequence(firstTurnRecords);
-  assertNoRecordedContinue(events, input.modules.SessionEventType);
+  assertRecordedContinueMatchesRequests(events, input.modules.SessionEventType, firstTurnRecords);
+  // Continue 按隐藏提醒记录写库:三次续写各一条。
+  assertCondition(
+    (await captureDurableContinueCount(app)) === 3,
+    "each Continue must be persisted as a hidden reminder row",
+  );
   assertCondition(
     assistantContents(runtimeHistory).join("|") === `${SUCCESS_PARTIAL}|${SUCCESS_DONE}`,
     "only real partial and final assistants may enter runtime history",
@@ -213,7 +219,7 @@ async function runSuccessScenario({ app, events, input, paths, provider, runtime
       storageDir: paths.storageDir,
     });
     await resumedApp.resume?.();
-    // 恢复成功必须同时证明身份和历史,避免新建空 session 也满足“不含 Continue”。
+    // 恢复成功必须同时证明身份和历史,避免新建空 session 也满足下面的前缀断言。
     assertCondition(
       resumedApp.sessionId === sessionId,
       "cold App must retain the original session",
@@ -229,9 +235,18 @@ async function runSuccessScenario({ app, events, input, paths, provider, runtime
     const coldRequest = parseRecordBody(provider.records.at(-1));
 
     assertCondition(coldResult.response === COLD_DONE, "cold follow-up must complete normally");
+    // 冷恢复后的第一个请求以重启前最后一个请求为前缀(含三条 Continue),缓存断点不算内容。
+    const lastLive = parseRecordBody(firstTurnRecords.at(-1));
+    assertCondition(
+      JSON.stringify(
+        withoutCacheControl(coldRequest.messages?.slice(0, lastLive.messages?.length)),
+      ) === JSON.stringify(withoutCacheControl(lastLive.messages)),
+      "cold follow-up request must start with the last live request",
+      { cold: coldRequest.messages, live: lastLive.messages },
+    );
     assertCondition(
-      countContinuePrompts(coldRequest) === 0,
-      "Continue must not leak into the cold follow-up provider request",
+      countContinuePrompts(coldRequest) === 3,
+      "cold follow-up request must replay the three persisted Continue messages",
       { messages: coldRequest.messages },
     );
     assertCondition(
@@ -277,7 +292,7 @@ async function runExhaustedScenario({ app, events, input, paths, provider, runti
     "fully empty exhaustion must persist only the durable assistant error",
     { exhaustedDurableHistory, exhaustedHistory },
   );
-  assertNoRecordedContinue(events, SessionEventType);
+  assertRecordedContinueMatchesRequests(events, SessionEventType, provider.records);
   assertCondition(
     events.some((event) => event.type === SessionEventType.TurnError) &&
       !events.some((event) => event.type === SessionEventType.TurnComplete),
@@ -317,9 +332,10 @@ async function runExhaustedScenario({ app, events, input, paths, provider, runti
     );
     assertCondition(provider.records.length === 5, "next Turn must issue exactly one new request");
     assertCondition(
-      countContinuePrompts(nextRequest) === 0 &&
+      countContinuePrompts(nextRequest) === 3 &&
         !nextRequest.messages?.some((message) => message.role === "assistant"),
-      "cold provider history must exclude Continue and the error-only assistant",
+      "cold provider history must replay the persisted Continue and exclude the error-only assistant",
+      { messages: nextRequest.messages },
     );
     return { response: nextResult.response, traceId: nextResult.traceId };
   } finally {
@@ -379,11 +395,26 @@ function assertContinueRequestSequence(records) {
   );
 }
 
-function assertNoRecordedContinue(events, SessionEventType) {
-  const modelRequests = events.filter((event) => event.type === SessionEventType.ModelRequest);
+// ModelRequest 事件与实际请求是同一份消息:每个事件记录的 Continue 条数与对应 HTTP 请求相同。
+function assertRecordedContinueMatchesRequests(events, SessionEventType, records) {
+  const recorded = events
+    .filter((event) => event.type === SessionEventType.ModelRequest)
+    .map((event) => countContinuePrompts(event.payload));
+  const sent = records.map((record) => countContinuePrompts(parseRecordBody(record)));
   assertCondition(
-    !JSON.stringify(modelRequests).includes(OUTPUT_TOKEN_CONTINUE_PROMPT),
-    "ModelRequest events must not record query-local Continue",
+    JSON.stringify(recorded) === JSON.stringify(sent),
+    "ModelRequest events must record the same Continue messages as the HTTP requests",
+    { recorded, sent },
+  );
+}
+
+function withoutCacheControl(value) {
+  if (Array.isArray(value)) return value.map(withoutCacheControl);
+  if (!value || typeof value !== "object") return value;
+  return Object.fromEntries(
+    Object.entries(value)
+      .filter(([key]) => key !== "cache_control")
+      .map(([key, item]) => [key, withoutCacheControl(item)]),
   );
 }
 

+ 412 - 0
apps/zcode-cli/e2e/compact-microcompact/case-read-state-hash-resume.mjs

@@ -0,0 +1,412 @@
+import { createHash } from "node:crypto";
+import { access, readFile, stat, utimes, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { DatabaseSync } from "node:sqlite";
+import { FAKE_MODEL } from "./constants.mjs";
+import {
+  assertCondition,
+  assertProviderCapture,
+  buildCaseResult,
+  buildRuntimeConfig,
+  createApp,
+  fakeProviderConfig,
+  makeCaseDirs,
+  writeProviderConfig,
+} from "./case-utils.mjs";
+import { writeJsonFile } from "./artifacts.mjs";
+import { prepareWorkspace } from "./workspace.mjs";
+import {
+  chatCompletion,
+  startScriptedProvider,
+  stopScriptedProvider,
+  writeScriptedCaptureFile,
+} from "./scripted-provider.mjs";
+
+// 规格:docs/design/v2/tool/17-read-file-state-resume.md「快照不存正文」。
+// 真实 CLI、真实 SQLite:快照只存 contentSha256;冷恢复后只 touch 放行、内容变化报 stale;
+// 升级前带正文、没有 contentSha256 的旧快照照旧恢复。
+const CASE_NAME = "read-state-hash-resume";
+const COMPLETION_MARKER = "READ_STATE_HASH_RESUME_E2E_DONE";
+const UNEXPECTED_MARKER = "READ_STATE_HASH_RESUME_E2E_UNEXPECTED_EXTRA_REQUEST";
+const TARGET_FILE = "target.txt";
+const BIG_FILE = "big.txt";
+const LEGACY_FILE = "legacy.txt";
+const TARGET_INITIAL = "alpha\nbeta\n";
+const TARGET_AFTER_EDIT = "gamma\nbeta\n";
+const TARGET_AFTER_RESUME_EDIT = "delta\nbeta\n";
+// 与上一行同样字节数:大小不变,只有正文哈希能发现变化。
+const TARGET_EXTERNAL = "delta\nBETA\n";
+const LEGACY_INITIAL = "one\n";
+const LEGACY_AFTER_EDIT = "two\n";
+const LEGACY_AFTER_RESUME_EDIT = "three\n";
+const BIG_HEADER = "HEADER\n";
+const BIG_HEADER_EDITED = "HEADER EDITED\n";
+const BIG_LINE_COUNT = 400;
+// Edit 一个约 21 KB 的文件后,这一条 tool part 的大小上限(升级前它包含整份文件,必然超过)。
+const BIG_EDIT_PART_MAX_BYTES = 8 * 1024;
+const TOUCH_STEP_MS = 10_000;
+const EDIT_SUCCESS = "has been updated successfully";
+const STALE_ERROR = "File has been modified since read";
+const NOT_READ_ERROR = "File has not been read yet";
+
+export const readStateHashResumeCase = {
+  name: CASE_NAME,
+  requiresApiKey: false,
+  async run(input) {
+    const events = [];
+    const failures = [];
+    const paths = await makeCaseDirs({ ...input, caseName: CASE_NAME });
+    const sessionDbPath = join(paths.storageDir, "db", "db.sqlite");
+    const files = {
+      big: join(paths.workspace, BIG_FILE),
+      legacy: join(paths.workspace, LEGACY_FILE),
+      target: join(paths.workspace, TARGET_FILE),
+    };
+    const bigContent = buildBigContent();
+    const steps = buildSteps({ bigContent, files });
+    let provider;
+    let app;
+
+    try {
+      await prepareWorkspace({ fixtureDir: input.fixtureDir, workspace: paths.workspace });
+      await writeFile(files.target, TARGET_INITIAL);
+      await writeFile(files.legacy, LEGACY_INITIAL);
+      provider = await startScriptedProvider({
+        handler: createStepHandler({ failures, steps }),
+        name: CASE_NAME,
+      });
+      await writeProviderConfig(
+        paths.configPath,
+        fakeProviderConfig({
+          baseURL: provider.baseURL,
+          model: FAKE_MODEL,
+          storageDir: paths.storageDir,
+        }),
+      );
+      const runtimeConfig = buildRuntimeConfig({
+        compact: { contextWindow: 1_000_000, microcompact: { enabled: false } },
+        maxTurns: 12,
+        workspace: paths.workspace,
+      });
+      const appInput = {
+        configPath: paths.configPath,
+        modules: input.modules,
+        runtimeConfig,
+        sessionDbPath,
+        storageDir: paths.storageDir,
+      };
+      const onEvent = async (event) => events.push(event);
+
+      // 第一段:Read/Edit target,Write/Edit 大文件,Read/Edit legacy。
+      app = await createApp(appInput);
+      const sessionId = app.sessionId;
+      const first = await app.submitPrompt("Run read-state hash phase 1.", { onEvent });
+      await app.close?.();
+      app = undefined;
+      assertPhase({ failures, phase: 1, response: first.response });
+      await assertFileContent(files.target, TARGET_AFTER_EDIT);
+      await assertFileContent(files.big, bigContent.replace(BIG_HEADER, BIG_HEADER_EDITED));
+      await assertFileContent(files.legacy, LEGACY_AFTER_EDIT);
+      await access(sessionDbPath);
+
+      const phase1 = readToolParts(sessionDbPath, sessionId);
+      assertHashSnapshot(phase1, "call_hash_read_target", "Read", TARGET_INITIAL);
+      assertHashSnapshot(phase1, "call_hash_edit_target", "Edit", TARGET_AFTER_EDIT);
+      assertHashSnapshot(phase1, "call_hash_write_big", "Write", bigContent);
+      const bigEdit = assertHashSnapshot(
+        phase1,
+        "call_hash_edit_big",
+        "Edit",
+        bigContent.replace(BIG_HEADER, BIG_HEADER_EDITED),
+      );
+      assertCondition(
+        bigEdit.bytes < BIG_EDIT_PART_MAX_BYTES,
+        "Edit on a large file must not persist the whole file in its tool part",
+        { partBytes: bigEdit.bytes, fileBytes: Buffer.byteLength(bigContent, "utf8") },
+      );
+      // 模拟升级前写下的数据:legacy 的 Edit 快照去掉 contentSha256、改回带正文。
+      rewriteAsLegacySnapshot(
+        sessionDbPath,
+        phase1.get("call_hash_edit_legacy"),
+        LEGACY_AFTER_EDIT,
+      );
+
+      // 第二段:只 touch,冷恢复后 Edit 两个文件都应放行。
+      await touch(files.target);
+      await touch(files.legacy);
+      app = await createApp({ ...appInput, resume: true, sessionId });
+      await app.resume?.();
+      assertCondition(app.sessionId === sessionId, "phase 2 must resume the original session");
+      const second = await app.submitPrompt("Run read-state hash phase 2.", { onEvent });
+      await app.close?.();
+      app = undefined;
+      assertPhase({ failures, phase: 2, response: second.response });
+      await assertFileContent(files.target, TARGET_AFTER_RESUME_EDIT);
+      await assertFileContent(files.legacy, LEGACY_AFTER_RESUME_EDIT);
+      assertHashSnapshot(
+        readToolParts(sessionDbPath, sessionId),
+        "call_hash_resume_edit_target",
+        "Edit",
+        TARGET_AFTER_RESUME_EDIT,
+      );
+
+      // 第三段:外部改了内容(大小不变),冷恢复后 Edit 必须报 stale 且不改文件。
+      await writeFile(files.target, TARGET_EXTERNAL);
+      await touch(files.target);
+      app = await createApp({ ...appInput, resume: true, sessionId });
+      await app.resume?.();
+      const third = await app.submitPrompt("Run read-state hash phase 3.", { onEvent });
+      await app.close?.();
+      app = undefined;
+      assertPhase({ failures, phase: 3, response: third.response });
+      await assertFileContent(files.target, TARGET_EXTERNAL);
+      assertCondition(steps.length === 0, "all scripted steps must be consumed", {
+        remaining: steps.map((step) => step.id),
+      });
+      assertProviderCapture(provider.records);
+
+      await writeScriptedCaptureFile(provider, paths.capturePath);
+      await writeJsonFile(paths.eventsPath, events);
+      const resultPayload = buildCaseResult({
+        capturedProviderRequestCount: provider.records.length,
+        caseName: CASE_NAME,
+        capturePath: paths.capturePath,
+        events,
+        eventsPath: paths.eventsPath,
+        response: third.response,
+        resultPath: paths.resultPath,
+        traceId: third.traceId,
+      });
+      await writeJsonFile(paths.resultPath, resultPayload);
+      return resultPayload;
+    } catch (error) {
+      await writeScriptedCaptureFile(provider, paths.capturePath);
+      await writeJsonFile(paths.eventsPath, events);
+      throw error;
+    } finally {
+      await app?.close?.();
+      await stopScriptedProvider(provider);
+    }
+  },
+};
+
+/** 每个 step 是一次 provider 请求的回复;check 检查上一条 tool result。 */
+function buildSteps({ bigContent, files }) {
+  const succeeded = { includes: EDIT_SUCCESS };
+  return [
+    {
+      id: "phase1-read-target",
+      phase: 1,
+      call: ["call_hash_read_target", "Read", { file_path: files.target }],
+    },
+    {
+      id: "phase1-edit-target",
+      phase: 1,
+      check: { includes: "alpha" },
+      call: [
+        "call_hash_edit_target",
+        "Edit",
+        { file_path: files.target, old_string: "alpha", new_string: "gamma" },
+      ],
+    },
+    {
+      id: "phase1-write-big",
+      phase: 1,
+      check: succeeded,
+      call: ["call_hash_write_big", "Write", { file_path: files.big, content: bigContent }],
+    },
+    {
+      id: "phase1-edit-big",
+      phase: 1,
+      check: { includes: "File created successfully" },
+      call: [
+        "call_hash_edit_big",
+        "Edit",
+        { file_path: files.big, old_string: BIG_HEADER, new_string: BIG_HEADER_EDITED },
+      ],
+    },
+    {
+      id: "phase1-read-legacy",
+      phase: 1,
+      check: succeeded,
+      call: ["call_hash_read_legacy", "Read", { file_path: files.legacy }],
+    },
+    {
+      id: "phase1-edit-legacy",
+      phase: 1,
+      check: { includes: "one" },
+      call: [
+        "call_hash_edit_legacy",
+        "Edit",
+        { file_path: files.legacy, old_string: "one", new_string: "two" },
+      ],
+    },
+    { id: "phase1-done", phase: 1, check: succeeded },
+    {
+      id: "phase2-edit-target",
+      phase: 2,
+      call: [
+        "call_hash_resume_edit_target",
+        "Edit",
+        { file_path: files.target, old_string: "gamma", new_string: "delta" },
+      ],
+    },
+    {
+      id: "phase2-edit-legacy",
+      phase: 2,
+      check: succeeded,
+      call: [
+        "call_hash_resume_edit_legacy",
+        "Edit",
+        { file_path: files.legacy, old_string: "two", new_string: "three" },
+      ],
+    },
+    { id: "phase2-done", phase: 2, check: succeeded },
+    {
+      id: "phase3-edit-target",
+      phase: 3,
+      call: [
+        "call_hash_stale_edit_target",
+        "Edit",
+        { file_path: files.target, old_string: "delta", new_string: "epsilon" },
+      ],
+    },
+    { id: "phase3-done", phase: 3, check: { includes: STALE_ERROR, allowStale: true } },
+  ];
+}
+
+function createStepHandler({ failures, steps }) {
+  // 断言失败不抛:provider 返回 500 会触发重试,掩盖真正的失败点。记下来,由每段收尾统一检查。
+  return async ({ body }) => {
+    const step = steps.shift();
+    if (!step) {
+      failures.push({ reason: "unexpected extra provider request" });
+      return { body: chatCompletion({ content: UNEXPECTED_MARKER, model: body?.model }) };
+    }
+    const previous = lastToolResult(body);
+    if (step.check?.includes && !previous.includes(step.check.includes)) {
+      failures.push({ step: step.id, reason: `missing "${step.check.includes}"`, previous });
+    }
+    for (const forbidden of step.check?.allowStale
+      ? [NOT_READ_ERROR]
+      : [NOT_READ_ERROR, STALE_ERROR]) {
+      if (step.check && previous.includes(forbidden)) {
+        failures.push({ step: step.id, reason: `unexpected "${forbidden}"`, previous });
+      }
+    }
+    if (!step.call) {
+      return {
+        body: chatCompletion({ content: `${COMPLETION_MARKER}:${step.phase}`, model: body?.model }),
+      };
+    }
+    const [id, name, args] = step.call;
+    return {
+      body: chatCompletion({
+        model: body?.model,
+        toolCalls: [{ id, type: "function", function: { name, arguments: JSON.stringify(args) } }],
+      }),
+    };
+  };
+}
+
+function lastToolResult(body) {
+  const messages = Array.isArray(body?.messages) ? body.messages : [];
+  const tool = messages.filter((message) => message?.role === "tool").at(-1);
+  if (!tool) return "";
+  return typeof tool.content === "string" ? tool.content : JSON.stringify(tool.content ?? "");
+}
+
+function assertPhase({ failures, phase, response }) {
+  assertCondition(failures.length === 0, `phase ${phase} tool results must match the script`, {
+    failures: failures.map((failure) => ({
+      ...failure,
+      previous: failure.previous?.slice(0, 600),
+    })),
+  });
+  assertCondition(
+    response.includes(`${COMPLETION_MARKER}:${phase}`),
+    `phase ${phase} must finish`,
+    {
+      response,
+    },
+  );
+}
+
+/** 只读本会话的 tool part,按 provider 的 tool call id 索引。 */
+function readToolParts(dbPath, sessionId) {
+  const db = new DatabaseSync(dbPath, { readOnly: true });
+  try {
+    const rows = db
+      .prepare(
+        "select id, data, length(cast(data as blob)) as bytes from part where session_id = ?",
+      )
+      .all(sessionId);
+    const parts = new Map();
+    for (const row of rows) {
+      const data = JSON.parse(row.data);
+      if (data.type === "tool") parts.set(data.callID, { bytes: row.bytes, data, id: row.id });
+    }
+    return parts;
+  } finally {
+    db.close();
+  }
+}
+
+function assertHashSnapshot(parts, callID, tool, expectedContent) {
+  const part = parts.get(callID);
+  const snapshot = part?.data.state?.metadata?.readFileState;
+  assertCondition(
+    part?.data.state?.status === "completed",
+    `${callID} must be a completed tool part`,
+    {
+      callIDs: [...parts.keys()],
+    },
+  );
+  assertCondition(
+    snapshot?.tool === tool &&
+      snapshot.contentSha256 === sha256(expectedContent) &&
+      !("content" in snapshot),
+    `${callID} must persist a hash-only read-state snapshot`,
+    { snapshot: snapshot && { ...snapshot, content: snapshot.content?.slice(0, 80) } },
+  );
+  return part;
+}
+
+function rewriteAsLegacySnapshot(dbPath, part, content) {
+  assertCondition(Boolean(part), "legacy Edit part must exist before rewriting it");
+  const { contentSha256: _hash, ...rest } = part.data.state.metadata.readFileState;
+  part.data.state.metadata.readFileState = { ...rest, content };
+  const db = new DatabaseSync(dbPath);
+  try {
+    db.prepare("update part set data = ? where id = ?").run(JSON.stringify(part.data), part.id);
+  } finally {
+    db.close();
+  }
+}
+
+async function touch(path) {
+  const info = await stat(path);
+  const mtime = new Date(info.mtimeMs + TOUCH_STEP_MS);
+  await utimes(path, mtime, mtime);
+}
+
+async function assertFileContent(path, expected) {
+  const actual = await readFile(path, "utf8");
+  assertCondition(actual === expected, `unexpected content in ${path}`, {
+    actual: actual.slice(0, 200),
+    expected: expected.slice(0, 200),
+  });
+}
+
+function buildBigContent() {
+  const lines = [BIG_HEADER];
+  for (let index = 1; index <= BIG_LINE_COUNT; index += 1) {
+    lines.push(`line ${index} read-state hash resume payload ${"x".repeat(16)}\n`);
+  }
+  return lines.join("");
+}
+
+// 与 hashReadFileStateContent 相同:sha256 按 UTF-16LE(JS 字符串码元)计算。
+function sha256(text) {
+  return createHash("sha256").update(text, "utf16le").digest("hex");
+}

+ 2 - 0
apps/zcode-cli/e2e/compact-microcompact/case-utils.mjs

@@ -119,6 +119,8 @@ export async function createApp(input) {
     env: {
       ...process.env,
       ZCODE_STORAGE_DIR: input.storageDir,
+      // 会话库默认在用户目录;需要检查或改写库内容的 case 用它指到本 case 的临时目录。
+      ...(input.sessionDbPath ? { ZCODE_SESSION_DB_PATH: input.sessionDbPath } : {}),
     },
     runtimeConfig: input.runtimeConfig,
     // 重构后旧字符串解析入口已删除;新 session 使用完整选择,冷恢复仍由持久选择接管。

+ 2 - 0
apps/zcode-cli/e2e/compact-microcompact/constants.mjs

@@ -7,6 +7,7 @@ export const FAKE_PROVIDER = "compact-e2e-fake";
 export const CASE_NAMES = [
   "background-bash",
   "bash-read-state",
+  "read-state-hash-resume",
   "microcompact",
   "manual-full-compact",
   "auto-full-compact",
@@ -21,6 +22,7 @@ export const REAL_CASE_NAMES = ["microcompact", "manual-full-compact", "auto-ful
 export const FAKE_CASE_NAMES = [
   "background-bash",
   "bash-read-state",
+  "read-state-hash-resume",
   "compact-ptl-retry",
   "reactive-compact",
   "openai-responses-compact",

+ 8 - 0
apps/zcode-cli/e2e/compact-microcompact/output-token-continuation-history.mjs

@@ -31,3 +31,11 @@ export async function captureDurableAssistantHistory(app) {
       tokens: message.info.tokens,
     }));
 }
+
+/** 写库的 Continue 隐藏提醒条数。 */
+export async function captureDurableContinueCount(app) {
+  const messages = await app.runtime.sessionStore.messages({ sessionID: app.sessionId });
+  return messages.filter(
+    (message) => message.info?.semantics?.source === "output_token_continuation",
+  ).length;
+}

+ 2 - 0
apps/zcode-cli/e2e/compact-microcompact/suite-cases.mjs

@@ -1,5 +1,6 @@
 import { backgroundBashCase } from "./case-background-bash.mjs";
 import { bashReadStateCase } from "./case-bash-read-state.mjs";
+import { readStateHashResumeCase } from "./case-read-state-hash-resume.mjs";
 import { microcompactCase } from "./case-microcompact.mjs";
 import { autoFullCompactCase, manualFullCompactCase } from "./case-full-compact.mjs";
 import { compactPtlRetryCase, reactiveCompactCase } from "./case-fake-compact.mjs";
@@ -10,6 +11,7 @@ import { outputTokenContinuationCase } from "./case-output-token-continuation.mj
 const cases = [
   backgroundBashCase,
   bashReadStateCase,
+  readStateHashResumeCase,
   microcompactCase,
   manualFullCompactCase,
   autoFullCompactCase,

+ 2 - 1
apps/zcode-cli/e2e/memory/README.md

@@ -18,7 +18,8 @@ scripted provider。它验证 Memory 主链路已经正确组合,不依赖线
 - Extraction 完成后新建 session,从默认分支的 request user-context source 消费新 pointer,且仍
   不发 Selector 请求;
 - custom agent persistent Memory prompt、tool projection、独立 root 和写入;
-- Memory disabled 时无 prompt、selector、Extraction 或 root 创建。
+- Memory disabled 时无 Memory prompt、selector、Extraction 或 root 创建;默认 prompt 的
+  `# Memory, notes and feedback` 段照常发送,不算 Memory 注入。
 - `memory.extractionEnabled=false` 的 headless Runtime 仍保留 Main Memory prompt 与当前 retrieval
   branch,但显式 drain 后没有 Extraction request,已有 `MEMORY.md` 与事实文件保持不变;该断言按
   Main/Extraction 类别判断,不把 semantic direct-answer 时允许异步启动或取消的 Selector 当成

+ 2 - 1
apps/zcode-cli/e2e/memory/memory-e2e-evidence.mjs

@@ -233,8 +233,9 @@ export async function verifyMemoryE2EEvidence({
     (record) => record.category === "main" && record.text.includes(memoryE2EText.disabledPrompt),
     "disabled Memory Main request",
   );
+  // 只看 Memory 段标题;默认 prompt 总带 `# Memory, notes and feedback`,那一段不算 Memory 注入。
   assertCondition(
-    !disabledRequest.text.includes("# Memory"),
+    !disabledRequest.text.includes("# Memory\n"),
     "disabled Memory request must not contain the Memory section",
   );
   const disabledScenarioRequests = records.filter((record) => record.scenario === "disabled");

+ 1 - 1
apps/zcode-cli/package.json

@@ -1,6 +1,6 @@
 {
   "name": "zcode-cli",
-  "version": "0.17.1",
+  "version": "0.18.0",
   "private": true,
   "description": "A cross-platform TypeScript Node.js CLI with a small TUI and optional SEA packaging.",
   "type": "module",

+ 5 - 0
apps/zcode-cli/packages/adapters/package.json

@@ -58,6 +58,10 @@
       "types": "./dist/skills/index.d.ts",
       "import": "./dist/skills/index.js"
     },
+    "./skills/catalog": {
+      "types": "./dist/skills/catalog.d.ts",
+      "import": "./dist/skills/catalog.js"
+    },
     "./commands": {
       "types": "./dist/commands/index.d.ts",
       "import": "./dist/commands/index.js"
@@ -117,6 +121,7 @@
     "@zcode/zcode-cua": "workspace:*",
     "ai": "6.0.193",
     "cheerio": "^1.0.0",
+    "chokidar": "4.0.3",
     "iconv-lite": "0.7.2",
     "jimp": "^1.6.1",
     "koffi": "2.15.6",

+ 20 - 0
apps/zcode-cli/packages/adapters/src/auth/cli-oauth.ts

@@ -5,6 +5,8 @@ const DEFAULT_ZCODE_OAUTH_BASE_URL = "https://zcode.z.ai/api/v1";
 export type CliOAuthProviderId = "zai" | "bigmodel";
 const POLL_TOKEN_BYTES = 32;
 const JSON_CONTENT_TYPE = "application/json";
+/** 服务端 flow 无效、已过期或 poll_token 不匹配;过期后随 HTTP 400 返回。 */
+export const CLI_OAUTH_INVALID_FLOW_CODE = 3004;
 
 export interface CliOAuthClientOptions {
   baseUrl?: string;
@@ -22,6 +24,8 @@ export interface CliOAuthInitData {
   expires_at: number;
   flow_id: string;
   poll_interval_sec: number;
+  /** 服务端当前时间(Unix 秒),与 expires_at 同属服务端时钟;旧服务端未返回时为 undefined。 */
+  server_time?: number;
 }
 
 export interface CliOAuthPollInput {
@@ -141,7 +145,10 @@ async function requestJsonEnvelope(
     options,
   );
   if (response.status < 200 || response.status >= 300) {
+    // 服务端在 flow 过期后返回 HTTP 400 + code 3004;保留业务码,调用方据此区分超时与其他失败。
+    const businessCode = readBusinessCode(response.body);
     throw new CliOAuthError(`OAuth HTTP error ${response.status}`, {
+      ...(businessCode === undefined ? {} : { businessCode }),
       httpStatus: response.status,
     });
   }
@@ -169,6 +176,15 @@ async function requestJsonEnvelope(
   };
 }
 
+function readBusinessCode(body: Uint8Array): number | undefined {
+  try {
+    const code = asRecord(JSON.parse(new TextDecoder().decode(body)))?.code;
+    return typeof code === "number" ? code : undefined;
+  } catch {
+    return undefined;
+  }
+}
+
 function parseInitData(value: unknown): CliOAuthInitData {
   const data = asRecord(value);
   if (
@@ -194,6 +210,10 @@ function parseInitData(value: unknown): CliOAuthInitData {
     expires_at: data.expires_at,
     flow_id: readString(data.flow_id)!,
     poll_interval_sec: data.poll_interval_sec,
+    // server_time 是可选新增字段:非有限数值按缺失处理,调用方退回本机时间。
+    ...(typeof data.server_time === "number" && Number.isFinite(data.server_time)
+      ? { server_time: data.server_time }
+      : {}),
   };
 }
 

+ 67 - 46
apps/zcode-cli/packages/adapters/src/auth/shared-credentials.ts

@@ -4,18 +4,20 @@ import { readFile } from "node:fs/promises";
 import { homedir } from "node:os";
 import { join, resolve } from "node:path";
 import {
-  atomicWritePrivateTextFile,
   backupCorruptFile,
   captureCredentialFileGuard,
   type CredentialFileGuard,
   withCredentialFileRead,
   withCredentialFileMutation,
+  withCredentialGeneration,
   withFileLock,
 } from "@zcode/shared/node";
 import type { ZCodeCredentialCipher } from "./credential-cipher.js";
 import {
   createSystemCredentialCipher,
   migrateCredentialRecord,
+  readAssignedCredentialsFile,
+  writeCredentialRecordLocked,
 } from "@zcode/shared/credential-security";
 
 const ZCODE_DATA_BASE_DIR_ENV_KEY = "ZCODE_DATA_BASE_DIR";
@@ -114,19 +116,20 @@ export function createSharedZCodeCredentialStore(
     return withCredentialFileMutation(filePath, async () => {
       const locked = await readRawCredentialRecord(filePath, true);
       const migrated = await migrateCredentialRecord(locked, cipher);
-      if (migrated)
-        await atomicWritePrivateTextFile(filePath, `${JSON.stringify(migrated, null, 2)}\n`);
+      if (migrated) await writeCredentialRecordLocked(filePath, migrated);
       return migrated ?? locked;
     });
   };
-  const mutate = (
-    mutation: (raw: Record<string, string>) => void | boolean | Promise<void | boolean>,
-  ) =>
-    mutateRawCredentialRecord(filePath, async (raw) => {
+  type RawMutation = (raw: Record<string, string>) => void | boolean | Promise<void | boolean>;
+  const commit = (mutation: RawMutation) =>
+    commitRawCredentialRecord(filePath, async (raw) => {
       const migrated = await migrateCredentialRecord(raw, cipher);
       if (migrated) Object.assign(raw, migrated);
       return mutation(raw);
     });
+  const mutate = async (mutation: RawMutation) => {
+    if (await commit(mutation)) await notifyCredentialChange(filePath);
+  };
 
   const loadMany = async (keys: readonly string[]): Promise<Record<string, string | null>> => {
     const raw = await readCurrent();
@@ -139,39 +142,45 @@ export function createSharedZCodeCredentialStore(
       ),
     );
   };
+  // Bug 原因:先加密后取文件锁领取代次;经凭据桥由 Main 加密的内置 CLI,加密在自动重置前、
+  // 写盘在重置后时,旧密钥密文会覆盖新登录且返回成功。修复:加密前领取代次,由锁内代次
+  // 屏障保护到写盘;期间发生重置即拒绝,调用方重试。
+  // 代次作用域只覆盖加密与锁内写盘:提交后的变更通知若留在作用域内,监听启动的后台任务
+  // (如账号刷新链)会一直带着本次领取的代次,之后的恢复或重置使其读写被误判为存储已变化。
   const updateMany: SharedZCodeCredentialStore["updateMany"] = async (changes, options) => {
-    const entries = await Promise.all(
-      Object.entries(changes).map(
-        async ([key, value]) =>
+    const committed = await withCredentialGeneration(filePath, async () => {
+      const entries = await Promise.all(
+        Object.entries(changes).map(
+          async ([key, value]) =>
+            [
+              validateCredentialKey(key),
+              value === null ? null : await cipher.encrypt(validateCredentialValue(value)),
+            ] as const,
+        ),
+      );
+      const expected = Object.entries(options?.expected ?? {}).map(
+        ([key, value]) =>
           [
             validateCredentialKey(key),
-            value === null ? null : await cipher.encrypt(validateCredentialValue(value)),
+            value === null ? null : validateCredentialValue(value),
           ] as const,
-      ),
-    );
-    const expected = Object.entries(options?.expected ?? {}).map(
-      ([key, value]) =>
-        [
-          validateCredentialKey(key),
-          value === null ? null : validateCredentialValue(value),
-        ] as const,
-    );
-    let committed = false;
-    await mutate(async (raw) => {
-      for (const [key, value] of expected) {
-        if ((raw[key] === undefined ? null : await cipher.decrypt(raw[key])) !== value)
-          return false;
-      }
-      options?.assertCurrent?.();
-      for (const [key, value] of entries) {
-        if (value === null) delete raw[key];
-        else raw[key] = value;
-      }
-      if (entries.some(([key]) => key === "zcodejwttoken" || key.startsWith("oauth:")))
-        raw[OAUTH_SESSION_REVISION_KEY] = await cipher.encrypt(randomUUID());
-      options?.assertCurrent?.();
-      committed = true;
+      );
+      return commit(async (raw) => {
+        for (const [key, value] of expected) {
+          if ((raw[key] === undefined ? null : await cipher.decrypt(raw[key])) !== value)
+            return false;
+        }
+        options?.assertCurrent?.();
+        for (const [key, value] of entries) {
+          if (value === null) delete raw[key];
+          else raw[key] = value;
+        }
+        if (entries.some(([key]) => key === "zcodejwttoken" || key.startsWith("oauth:")))
+          raw[OAUTH_SESSION_REVISION_KEY] = await cipher.encrypt(randomUUID());
+        options?.assertCurrent?.();
+      });
     });
+    if (committed) await notifyCredentialChange(filePath);
     return committed;
   };
 
@@ -348,14 +357,18 @@ export function createSharedZCodeCredentialStore(
       replacedKeys: readonly string[],
     ): Promise<void> {
       const validatedKey = validateCredentialKey(key);
-      const encryptedValue = await cipher.encrypt(validateCredentialValue(value));
       const validatedReplacedKeys = replacedKeys.map(validateCredentialKey);
-      await mutate(async (rawCredentials) => {
-        rawCredentials[validatedKey] = encryptedValue;
-        for (const replacedKey of validatedReplacedKeys) {
-          if (replacedKey !== validatedKey) delete rawCredentials[replacedKey];
-        }
+      // 与 updateMany 相同:加密前领取代次,避免重置前产生的密文在重置后写盘;通知在作用域外。
+      const committed = await withCredentialGeneration(filePath, async () => {
+        const encryptedValue = await cipher.encrypt(validateCredentialValue(value));
+        return commit(async (rawCredentials) => {
+          rawCredentials[validatedKey] = encryptedValue;
+          for (const replacedKey of validatedReplacedKeys) {
+            if (replacedKey !== validatedKey) delete rawCredentials[replacedKey];
+          }
+        });
       });
+      if (committed) await notifyCredentialChange(filePath);
     },
 
     async saveZaiLoginCredentials(payload, expected, assertCurrent): Promise<void> {
@@ -394,6 +407,12 @@ export function resolveSharedZCodeCredentialsPath(
   }
 
   const env = options.env ?? process.env;
+  if (options.baseDir === undefined) {
+    // Source Server Core 使用自有凭据库时经 ZCODE_CREDENTIALS_FILE 指定文件(ZCT-2120452663971209216),
+    // 由其拉起的 Agent 必须读写同一文件;显式调用参数仍然优先。
+    const assigned = readAssignedCredentialsFile(env);
+    if (assigned) return assigned;
+  }
   const baseDir = options.baseDir ?? env[ZCODE_DATA_BASE_DIR_ENV_KEY] ?? homedir();
   return join(resolveUserPath(baseDir), ".zcode", "v2", "credentials.json");
 }
@@ -431,19 +450,21 @@ async function readRawCredentialRecordUnchecked(filePath: string): Promise<Recor
   }
 }
 
-async function mutateRawCredentialRecord(
+async function commitRawCredentialRecord(
   filePath: string,
   mutation: (value: Record<string, string>) => void | boolean | Promise<void | boolean>,
-): Promise<void> {
+): Promise<boolean> {
   // CLI、设置页和 session 可能位于不同 Node 进程;锁必须覆盖完整的
   // read-modify-write,单独原子 rename 只能防半写,不能防旧快照覆盖新 key。
-  const committed = await withCredentialFileMutation(filePath, async () => {
+  return withCredentialFileMutation(filePath, async () => {
     const value = await readRawCredentialRecord(filePath, true);
     if ((await mutation(value)) === false) return false;
-    await atomicWritePrivateTextFile(filePath, `${JSON.stringify(value, null, 2)}\n`);
+    await writeCredentialRecordLocked(filePath, value);
     return true;
   });
-  if (!committed) return;
+}
+
+async function notifyCredentialChange(filePath: string): Promise<void> {
   const listeners = [...(credentialChangeListeners.get(filePath) ?? [])];
   // 同进程的 Registry Source 需要在登录返回前观察到新凭据;单个监听者失败不应
   // 把已经原子落盘的 Credential 伪装成写入失败。

+ 23 - 1
apps/zcode-cli/packages/adapters/src/browser/index.ts

@@ -8,7 +8,7 @@ import type {
   BrowserControlPort,
   BrowserErrorCode,
 } from "@zcode/contracts";
-import type { Browser } from "playwright-core";
+import type { Browser, BrowserContextOptions } from "playwright-core";
 import { createManagedCdpDescriptor } from "./descriptor.js";
 import {
   loadPlaywrightChromium,
@@ -20,10 +20,12 @@ import {
 import { executeManagedPageCommand } from "./page-command.js";
 import { abortError, classifyError, hasSideEffects, raceWithAbort } from "./request.js";
 import { ManagedCdpSession } from "./session.js";
+import { loadBrowserStorageState } from "./storage-state.js";
 
 export interface ManagedCdpBrowserRuntimeOptions extends BrowserExecutableResolutionOptions {
   closeTimeoutMs?: number;
   loadPlaywright?: () => Promise<PlaywrightChromiumModule>;
+  storageStatePath?: string;
 }
 
 export interface ManagedCdpBrowserRuntime {
@@ -249,9 +251,16 @@ class ManagedCdpBrowserControlPort implements BrowserControlPort {
     const promise = (async () => {
       const browser = await this.ensureBrowser();
       const generation = this.#generation;
+      const storageStatePath = this.#options.storageStatePath;
+      const storageState = storageStatePath
+        ? (await loadBrowserStorageState(storageStatePath)).state
+        : undefined;
       const context = await browser.newContext({
         acceptDownloads: false,
         viewport: { width: 1280, height: 720 },
+        ...(storageState
+          ? { storageState: storageState as BrowserContextOptions["storageState"] }
+          : {}),
       });
       if (
         this.#disposed ||
@@ -424,6 +433,19 @@ export {
 } from "./executable.js";
 export type { BrowserExecutableResolutionOptions, PlaywrightChromiumModule } from "./executable.js";
 export { isAllowedManagedBrowserUrl } from "./page-command.js";
+export {
+  BrowserStateFileError,
+  loadBrowserStorageState,
+  resolveDefaultBrowserStatePath,
+} from "./storage-state.js";
+export type {
+  BrowserStateCookie,
+  BrowserStateFileErrorCode,
+  BrowserStateLoadResult,
+  BrowserStateOrigin,
+  BrowserStorageState,
+  LoadBrowserStorageStateOptions,
+} from "./storage-state.js";
 
 function waitForPromise(promise: Promise<unknown>, timeoutMs: number): Promise<boolean> {
   return new Promise<boolean>((resolve) => {

+ 2 - 0
apps/zcode-cli/packages/adapters/src/browser/request.ts

@@ -1,4 +1,5 @@
 import type { BrowserCommand, BrowserErrorCode } from "@zcode/contracts";
+import { BrowserStateFileError } from "./storage-state.js";
 
 export function abortError(): Error {
   return new DOMException("Browser command cancelled", "AbortError");
@@ -48,6 +49,7 @@ export function hasSideEffects(command: BrowserCommand): boolean {
 export function classifyError(error: unknown): BrowserErrorCode {
   if (error instanceof Error && error.name === "AbortError") return "cancelled";
   if (error instanceof Error && error.name === "TimeoutError") return "timeout";
+  if (error instanceof BrowserStateFileError) return "backend_unavailable";
   if (error instanceof Error && /unavailable|closed|disconnected/iu.test(error.message)) {
     return "backend_unavailable";
   }

+ 294 - 0
apps/zcode-cli/packages/adapters/src/browser/storage-state.ts

@@ -0,0 +1,294 @@
+import { readFile, stat } from "node:fs/promises";
+import type { Stats } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { z } from "zod";
+
+export type BrowserStateFileErrorCode =
+  | "missing"
+  | "not_file"
+  | "unreadable"
+  | "invalid_json"
+  | "invalid_schema";
+
+export interface BrowserStateCookie {
+  name: string;
+  value: string;
+  url?: string;
+  domain?: string;
+  path?: string;
+  expires?: number;
+  httpOnly?: boolean;
+  secure?: boolean;
+  sameSite?: "Strict" | "Lax" | "None";
+  partitionKey?: string;
+  _crHasCrossSiteAncestor?: boolean;
+}
+
+export interface BrowserStateOrigin {
+  origin: string;
+  localStorage: Array<{ name: string; value: string }>;
+  indexedDB?: unknown[];
+}
+
+export interface BrowserStorageState {
+  cookies?: BrowserStateCookie[];
+  origins?: BrowserStateOrigin[];
+}
+
+export interface BrowserStateLoadResult {
+  state: BrowserStorageState;
+  summary: { cookieCount: number; expiredCookieCount: number; originCount: number };
+  unknownFields: string[];
+  looseMode?: number;
+}
+
+export interface LoadBrowserStorageStateOptions {
+  platform?: NodeJS.Platform | string;
+  nowMs?: () => number;
+}
+
+const DEFAULT_BROWSER_STATE_PATH_SEGMENTS = [".zcode", "cli", "browser-state.json"] as const;
+const UTF8_BOM = "";
+const SESSION_COOKIE_EXPIRES = -1;
+const MAX_COOKIE_EXPIRES_SECONDS = 253402300799;
+const BLANK_PAGE_URL = "about:blank";
+const DATA_URL_PREFIX = "data:";
+const MILLISECONDS_PER_SECOND = 1000;
+const GROUP_OTHER_PERMISSION_MASK = 0o077;
+const PERMISSION_BITS_MASK = 0o777;
+const WINDOWS_PLATFORM = "win32";
+const ROOT_ISSUE_PATH = "(root)";
+const MISSING_FILE_ERRNO_CODES = new Set(["ENOENT", "ENOTDIR"]);
+const ALLOWED_ORIGIN_PROTOCOLS = new Set(["http:", "https:"]);
+
+const KNOWN_TOP_LEVEL_FIELDS = ["cookies", "origins"] as const;
+const KNOWN_COOKIE_FIELDS = [
+  "name",
+  "value",
+  "url",
+  "domain",
+  "path",
+  "expires",
+  "httpOnly",
+  "secure",
+  "sameSite",
+  "partitionKey",
+  "_crHasCrossSiteAncestor",
+] as const;
+const KNOWN_ORIGIN_FIELDS = ["origin", "localStorage", "indexedDB"] as const;
+const KNOWN_STORAGE_ITEM_FIELDS = ["name", "value"] as const;
+
+const BROWSER_STATE_ERROR_MESSAGES: Record<BrowserStateFileErrorCode, string> = {
+  missing: "Browser state file was not found",
+  not_file: "Browser state path is not a regular file",
+  unreadable: "Browser state file could not be read",
+  invalid_json: "Browser state file is not valid JSON",
+  invalid_schema: "Browser state file does not match the Playwright storage state format",
+};
+
+export class BrowserStateFileError extends Error {
+  override readonly name = "BrowserStateFileError";
+
+  constructor(
+    readonly code: BrowserStateFileErrorCode,
+    readonly path: string,
+    readonly issues: readonly string[] = [],
+    options?: { cause?: unknown },
+  ) {
+    super(BROWSER_STATE_ERROR_MESSAGES[code], options);
+  }
+}
+
+const cookieSchema = z
+  .looseObject({
+    name: z.string(),
+    value: z.string(),
+    url: z.string().min(1).refine(isCookieUrl).optional(),
+    domain: z.string().min(1).optional(),
+    path: z.string().min(1).optional(),
+    expires: z
+      .number()
+      .refine(
+        (expires) =>
+          expires === SESSION_COOKIE_EXPIRES ||
+          (expires > 0 && expires <= MAX_COOKIE_EXPIRES_SECONDS),
+      )
+      .optional(),
+    httpOnly: z.boolean().optional(),
+    secure: z.boolean().optional(),
+    sameSite: z.enum(["Strict", "Lax", "None"]).optional(),
+    partitionKey: z.string().optional(),
+    _crHasCrossSiteAncestor: z.boolean().optional(),
+  })
+  .refine((cookie) =>
+    cookie.url === undefined
+      ? cookie.domain !== undefined && cookie.path !== undefined
+      : cookie.domain === undefined && cookie.path === undefined,
+  );
+
+const storageItemSchema = z.looseObject({ name: z.string(), value: z.string() });
+
+const originSchema = z.looseObject({
+  origin: z.string().refine(isHttpOrigin),
+  localStorage: z.array(storageItemSchema),
+  indexedDB: z.array(z.unknown()).optional(),
+});
+
+const storageStateSchema = z.looseObject({
+  cookies: z.array(cookieSchema).optional(),
+  origins: z.array(originSchema).optional(),
+});
+
+export function resolveDefaultBrowserStatePath(
+  env: NodeJS.ProcessEnv,
+  platform: NodeJS.Platform | string = process.platform,
+): string {
+  // 与 os.homedir() 同一规则:Windows 只认 USERPROFILE,Git Bash 等环境设置的 HOME 不能改变默认位置。
+  const envHome = platform === WINDOWS_PLATFORM ? env.USERPROFILE : env.HOME;
+  return join(envHome?.trim() || homedir(), ...DEFAULT_BROWSER_STATE_PATH_SEGMENTS);
+}
+
+export async function loadBrowserStorageState(
+  path: string,
+  options: LoadBrowserStorageStateOptions = {},
+): Promise<BrowserStateLoadResult> {
+  const stats = await statStateFile(path);
+  if (!stats.isFile()) throw new BrowserStateFileError("not_file", path);
+
+  let text: string;
+  try {
+    text = await readFile(path, "utf8");
+  } catch (error) {
+    throw new BrowserStateFileError("unreadable", path, [], { cause: error });
+  }
+
+  let json: unknown;
+  try {
+    json = JSON.parse(text.startsWith(UTF8_BOM) ? text.slice(UTF8_BOM.length) : text);
+  } catch {
+    // 不附带 cause:JSON.parse 的报错会引用文件片段,可能含 cookie 值。
+    throw new BrowserStateFileError("invalid_json", path);
+  }
+
+  const parsed = storageStateSchema.safeParse(json);
+  if (!parsed.success) {
+    const issues = [...new Set(parsed.error.issues.map((issue) => formatIssuePath(issue.path)))];
+    throw new BrowserStateFileError("invalid_schema", path, issues);
+  }
+
+  const unknownFields = new Set<string>();
+  const state = stripUnknownFields(parsed.data, unknownFields);
+  const nowMs = options.nowMs ?? Date.now;
+  const cookies = state.cookies ?? [];
+  const platform = options.platform ?? process.platform;
+  const looseMode =
+    platform !== WINDOWS_PLATFORM && (stats.mode & GROUP_OTHER_PERMISSION_MASK) !== 0
+      ? stats.mode & PERMISSION_BITS_MASK
+      : undefined;
+
+  return {
+    state,
+    summary: {
+      cookieCount: cookies.length,
+      expiredCookieCount: cookies.filter((cookie) => isExpired(cookie, nowMs())).length,
+      originCount: state.origins?.length ?? 0,
+    },
+    unknownFields: [...unknownFields],
+    ...(looseMode === undefined ? {} : { looseMode }),
+  };
+}
+
+async function statStateFile(path: string): Promise<Stats> {
+  try {
+    return await stat(path);
+  } catch (error) {
+    const code = (error as NodeJS.ErrnoException).code;
+    throw new BrowserStateFileError(
+      code && MISSING_FILE_ERRNO_CODES.has(code) ? "missing" : "unreadable",
+      path,
+      [],
+      { cause: error },
+    );
+  }
+}
+
+function isHttpOrigin(origin: string): boolean {
+  try {
+    const url = new URL(origin);
+    return ALLOWED_ORIGIN_PROTOCOLS.has(url.protocol) && url.origin === origin;
+  } catch {
+    return false;
+  }
+}
+
+function isCookieUrl(url: string): boolean {
+  if (url === BLANK_PAGE_URL || url.startsWith(DATA_URL_PREFIX)) return false;
+  try {
+    new URL(url);
+    return true;
+  } catch {
+    return false;
+  }
+}
+
+function isExpired(cookie: BrowserStateCookie, nowMs: number): boolean {
+  return (
+    cookie.expires !== undefined &&
+    cookie.expires !== SESSION_COOKIE_EXPIRES &&
+    cookie.expires * MILLISECONDS_PER_SECOND < nowMs
+  );
+}
+
+function formatIssuePath(path: readonly PropertyKey[]): string {
+  if (path.length === 0) return ROOT_ISSUE_PATH;
+  return path
+    .map((segment, index) =>
+      typeof segment === "number" ? `[${segment}]` : `${index === 0 ? "" : "."}${String(segment)}`,
+    )
+    .join("");
+}
+
+function stripUnknownFields(
+  data: z.infer<typeof storageStateSchema>,
+  unknownFields: Set<string>,
+): BrowserStorageState {
+  pickKnownFields(data, KNOWN_TOP_LEVEL_FIELDS, "", unknownFields);
+  const cookies = data.cookies?.map((cookie) =>
+    pickKnownFields<BrowserStateCookie>(cookie, KNOWN_COOKIE_FIELDS, "cookies[].", unknownFields),
+  );
+  const origins = data.origins?.map((origin) => ({
+    ...pickKnownFields<BrowserStateOrigin>(
+      origin,
+      KNOWN_ORIGIN_FIELDS,
+      "origins[].",
+      unknownFields,
+    ),
+    localStorage: origin.localStorage.map((item) =>
+      pickKnownFields<BrowserStateOrigin["localStorage"][number]>(
+        item,
+        KNOWN_STORAGE_ITEM_FIELDS,
+        "origins[].localStorage[].",
+        unknownFields,
+      ),
+    ),
+  }));
+  return {
+    ...(cookies ? { cookies } : {}),
+    ...(origins ? { origins } : {}),
+  };
+}
+
+function pickKnownFields<T>(
+  value: Record<string, unknown>,
+  knownFields: readonly string[],
+  prefix: string,
+  unknownFields: Set<string>,
+): T {
+  const picked: Record<string, unknown> = {};
+  for (const [key, fieldValue] of Object.entries(value)) {
+    if (knownFields.includes(key)) picked[key] = fieldValue;
+    else unknownFields.add(`${prefix}${key}`);
+  }
+  return picked as T;
+}

+ 26 - 5
apps/zcode-cli/packages/adapters/src/config/config-factory.ts

@@ -17,9 +17,12 @@ import {
   DefaultRuntimeConfig,
   createWorkspaceHookBundleSnapshot,
 } from "@zcode/contracts";
+import { remoteWorkspaceTrustIdentity } from "@zcode/shared";
 import {
   buildWorkspaceHookBundleSnapshot,
+  readWorkspaceHookScriptStates,
   resolveWorkspaceHookRuntimeRoot,
+  type WorkspaceHookScriptState,
   type WorkspaceHookRuntimeRoot,
 } from "@zcode/shared/workspace-hook-discovery";
 import {
@@ -209,7 +212,13 @@ export async function createConfigWithPluginMigrations(
     else enabledPlugins[VISUALIZE_PLUGIN_ID] = enabled;
     file.config = { ...file.config, plugins: { ...file.config.plugins, enabledPlugins } };
   }
-  return assembleConfig(options, sources);
+  // Hook Trust 绑定入口脚本内容(docs/specs/workspace-hook-trust.md D24):读文件是异步 IO,
+  // 只能在这个异步入口完成。Runtime 会话只走本入口;同步 createConfig 的入口记为 unverifiable。
+  const workspaceHookScriptStates = await readWorkspaceHookScriptStates({
+    workspacePath: resolve(options.workingDirectory ?? process.cwd()),
+    sources: sources.discoveredProjectConfigs.hookCandidates,
+  });
+  return assembleConfig(options, sources, workspaceHookScriptStates);
 }
 
 /**
@@ -226,7 +235,11 @@ export function createConfig(options: ConfigFactoryOptions = {}): ConfigResult {
   return assembleConfig(options, loadConfigSources(options));
 }
 
-function assembleConfig(options: ConfigFactoryOptions, sources: LoadedConfigSources): ConfigResult {
+function assembleConfig(
+  options: ConfigFactoryOptions,
+  sources: LoadedConfigSources,
+  workspaceHookScriptStates?: ReadonlyMap<string, WorkspaceHookScriptState>,
+): ConfigResult {
   const { userConfigResult, discoveredProjectConfigs } = sources;
   // 1. System defaults
   const configs: ReturnType<typeof createPrioritizedConfig>[] = [
@@ -304,14 +317,18 @@ function assembleConfig(options: ConfigFactoryOptions, sources: LoadedConfigSour
     options.cliOverrides?.hooks,
   ]);
   const workspacePath = resolve(options.workingDirectory ?? process.cwd());
+  const fallbackIdentity = options.workspaceIdentity?.trim();
   const workspaceHookSnapshotData = buildWorkspaceHookBundleSnapshot({
+    // 未经解析的 identity 与共享 resolver 同一规则:远程保留 host 命名空间、路径取执行目录,
+    // 其他自报 identity 忽略。
     workspaceIdentity:
       options.workspaceHookTrustIdentity?.trim() ||
-      options.workspaceIdentity?.trim() ||
+      (fallbackIdentity && remoteWorkspaceTrustIdentity(fallbackIdentity, workspacePath)) ||
       workspacePath,
     workspacePath,
     sources: projectSummary.hookCandidates,
     runtimeRoot: workspaceHookRuntimeRoot,
+    ...(workspaceHookScriptStates ? { scriptStates: workspaceHookScriptStates } : {}),
   });
   const workspaceHookSnapshot = workspaceHookSnapshotData
     ? createWorkspaceHookBundleSnapshot(workspaceHookSnapshotData)
@@ -415,7 +432,8 @@ function resolvePluginConfigSources(input: {
   return {
     dirs: {
       user: input.userConfig.plugins?.dirs ?? [],
-      workspace: input.projectConfig.plugins?.dirs ?? [],
+      // 项目目录只是待信任候选;config.plugins.dirs 不含它们,发现时按信任记录准入。
+      workspace: [...new Set(input.projectFiles.flatMap((file) => file.pluginDirCandidates ?? []))],
     },
     enabled,
     marketplaces,
@@ -499,6 +517,9 @@ function resolveEffectiveMcpServers(input: {
   };
 
   apply("system", DefaultRuntimeConfig);
+  // 会话的动态 MCP 加载器(mcp/config-loader.ts)只重读 project、user 文件层与显式 server map,
+  // 二者由一致性测试锁定。env 或 CLI 层将来提供 mcp.servers 时,必须同步加载器,
+  // 否则配置热更新会丢掉这一层。
   // MCP server discovery has an extension-specific rule: user config shadows project config.
   // This does not change the global config precedence for model/permission/UI fields.
   apply("project", input.projectConfig);
@@ -603,7 +624,7 @@ const nodeTrustIdentityFs: WorkspaceHookTrustIdentityFs = {
 };
 
 /**
- * 计算 workspace 的 Hook Trust identity。远程 identity 原样返回;本地受管 worktree 严格校验通过后
+ * 计算 workspace 的 Hook Trust identity。远程 identity 保留 host 命名空间、路径取执行目录;本地受管 worktree 严格校验通过后
  * 归一为源仓库对应路径;其余情况返回 workspacePath(调用方负责传入已规范化的路径)。
  */
 export function resolveWorkspaceHookTrustIdentityForWorkspace(input: {

+ 10 - 2
apps/zcode-cli/packages/adapters/src/config/config-merger.ts

@@ -37,11 +37,19 @@ export function mergeConfigs(...configs: PrioritizedConfig[]): RuntimeConfigPatc
             // 保留 schema 兼容旧文件,但不能让项目层字段进入 merged RuntimeConfig/catalog。
             const projectPlugins = { ...inputConfig.plugins };
             delete projectPlugins.extraKnownMarketplaces;
+            // 项目选项可控制插件启动路径,不能混入可信用户配置;私有项目选项在合并后独立叠加。
+            delete projectPlugins.options;
             return { ...inputConfig, plugins: projectPlugins };
           })()
         : inputConfig;
     const previousHooks = result.hooks;
     const previousPlugins = result.plugins;
+    // 修复原因:下面的展开发生在 Object.assign 之后,那时 result.skillOverrides 已是本层的值,
+    // 用户和项目各停用一个 skill 时只剩项目的那个。开关按路径合并,先留下低优先级层的值。
+    // 其余嵌套字段(permission、network、storage 等)同样被整体替换,改动会改变权限与存储的
+    // 生效规则,另行决定:docs/issues/config-merge-legacy/01-nested-fields-replaced-by-higher-layer.md。
+    const previousSkillOverrides = result.skillOverrides;
+    const previousCommandOverrides = result.commandOverrides;
     Object.assign(result, config);
 
     // Deep merge nested objects
@@ -120,13 +128,13 @@ export function mergeConfigs(...configs: PrioritizedConfig[]): RuntimeConfigPatc
     }
     if (config.skillOverrides) {
       result.skillOverrides = {
-        ...result.skillOverrides,
+        ...previousSkillOverrides,
         ...config.skillOverrides,
       };
     }
     if (config.commandOverrides) {
       result.commandOverrides = {
-        ...result.commandOverrides,
+        ...previousCommandOverrides,
         ...config.commandOverrides,
       };
     }

+ 2 - 0
apps/zcode-cli/packages/adapters/src/config/index.ts

@@ -499,6 +499,8 @@ export {
 } from "./config-factory.js";
 export {
   PLUGIN_SECRETS_FILE_NAME,
+  resolvePluginSecretsPath,
+  resolvePluginSecretOverrides,
   createEmptyPluginSecretsFile,
   getPluginSecretsForScope,
   normalizePluginConfigPathForComparison,

+ 70 - 3
apps/zcode-cli/packages/adapters/src/config/plugin-secrets.adapter.ts

@@ -1,13 +1,15 @@
-// Plugin Secrets Adapter - 敏感插件选项的私有文件(plugin-compat.md「Sensitive Option Storage」)。
+// Plugin Secrets Adapter - 敏感选项与全部项目选项的私有文件(plugin-compat.md「Sensitive Option Storage」)。
 //
-// 只负责文件 I/O、schema 与纯数据变换;「哪些键敏感、读取时怎样叠加到配置层」由 bootstrap 决定。
+// 启动与动态 MCP 共用读取、分层合并规则;保存时哪些键属于敏感值由 bootstrap 决定。
 // 任何错误信息与返回的诊断原因都不带值。
 
 import { readFile } from "node:fs/promises";
-import { resolve, win32 } from "node:path";
+import { dirname, join, resolve, win32 } from "node:path";
 import { z } from "zod";
 import { atomicWritePrivateTextFile, backupCorruptFile, withFileLock } from "@zcode/shared/node";
 
+import type { PluginOptionLayer } from "./config-factory.js";
+
 export const PLUGIN_SECRETS_FILE_NAME = "plugin-secrets.json";
 const PLUGIN_SECRETS_FILE_VERSION = 1;
 const JSON_INDENT = 2;
@@ -227,3 +229,68 @@ function getErrorCode(error: unknown): string | undefined {
   const code = (error as { code?: unknown }).code;
   return typeof code === "string" ? code : undefined;
 }
+
+/**
+ * 私有文件与插件存储目录 `plugins/` 同级。默认就是 `<cli storage root>/plugin-secrets.json`;
+ * 调用方覆盖插件存储目录(测试、嵌入)时文件跟着走,不会写进真实的用户目录。
+ */
+export function resolvePluginSecretsPath(pluginStorageRoot: string): string {
+  return join(dirname(pluginStorageRoot), PLUGIN_SECRETS_FILE_NAME);
+}
+
+/** 启动与动态重载共用同一套来源优先级;仓库文件不能成为运行参数的来源。 */
+export function resolvePluginSecretOverrides(
+  layers: readonly PluginOptionLayer[],
+  file: PluginSecretsFile,
+) {
+  const layerSecrets = layers.map((layer) => getPluginSecretsForScope(file, toSecretsScope(layer)));
+  const overrides: Array<{
+    pluginId: string;
+    key: string;
+    scope: PluginOptionLayer["scope"];
+    value: PluginSecretValue;
+  }> = [];
+  for (const [pluginId, keys] of collectSecretKeys(layerSecrets)) {
+    for (const key of keys) {
+      const winner = resolveLayeredValue(layers, layerSecrets, pluginId, key);
+      if (winner) overrides.push({ pluginId, key, ...winner });
+    }
+  }
+  return overrides;
+}
+
+function toSecretsScope(layer: PluginOptionLayer): PluginSecretsScope {
+  return layer.scope === "workspace" && layer.workspaceRoot
+    ? { kind: "workspace", root: layer.workspaceRoot }
+    : { kind: "user" };
+}
+
+function collectSecretKeys(layerSecrets: readonly PluginSecretValues[]): Map<string, Set<string>> {
+  const touched = new Map<string, Set<string>>();
+  for (const secrets of layerSecrets) {
+    for (const [pluginId, values] of Object.entries(secrets)) {
+      const keys = touched.get(pluginId) ?? new Set<string>();
+      for (const key of Object.keys(values)) keys.add(key);
+      touched.set(pluginId, keys);
+    }
+  }
+  return touched;
+}
+
+function resolveLayeredValue(
+  layers: readonly PluginOptionLayer[],
+  layerSecrets: readonly PluginSecretValues[],
+  pluginId: string,
+  key: string,
+): { scope: PluginOptionLayer["scope"]; value: PluginSecretValue } | undefined {
+  for (let index = layers.length - 1; index >= 0; index -= 1) {
+    const layer = layers[index];
+    if (!layer) continue;
+    const secret = layerSecrets[index]?.[pluginId]?.[key];
+    if (secret !== undefined) return { scope: layer.scope, value: secret };
+    // 项目文件不提供任何运行时选项,即使调用方传入的是旧的配置快照,也不能覆盖用户私有值。
+    const plain = layer.scope === "user" ? layer.options[pluginId]?.[key] : undefined;
+    if (plain !== undefined) return { scope: layer.scope, value: plain };
+  }
+  return undefined;
+}

+ 22 - 4
apps/zcode-cli/packages/adapters/src/config/project-config.adapter.ts

@@ -13,6 +13,11 @@ const CURRENT_DIRECTORY = ".";
 export interface ProjectConfigFile extends LoadedConfig {
   baseDir: string;
   hookCandidate?: WorkspaceHookSourceInput;
+  /**
+   * 项目 `plugins.dirs` 解析成的绝对目录,只是待信任候选,不在 config 里。
+   * 插件发现按用户域信任记录逐个准入(docs/plugins/workspace-plugin-dir-trust.md)。
+   */
+  pluginDirCandidates?: string[];
 }
 
 export interface ProjectConfigDiscovery {
@@ -55,6 +60,11 @@ export function loadProjectConfigFile(
   const baseDir = getProjectConfigBaseDir(result.path);
   const diagnostics = [...result.diagnostics];
   const hooks = result.loaded ? result.config.hooks : undefined;
+  const pluginDirCandidates = result.loaded
+    ? (result.config.plugins?.dirs ?? []).map((dir) =>
+        isAbsolute(dir) ? resolve(dir) : resolve(baseDir, dir),
+      )
+    : [];
 
   if (hooks) {
     diagnostics.push({
@@ -87,6 +97,7 @@ export function loadProjectConfigFile(
       : {}),
     loaded: result.loaded,
     path: result.path,
+    ...(pluginDirCandidates.length > 0 ? { pluginDirCandidates } : {}),
     ...(result.pendingVisualizeMigration ? { pendingVisualizeMigration: true } : {}),
   };
 }
@@ -111,12 +122,15 @@ export function summarizeProjectConfigs(files: ProjectConfigFile[]): ProjectConf
   };
 }
 
-function getProjectConfigBaseDir(path: string): string {
+export function getProjectConfigBaseDir(path: string): string {
   const configDirectory = dirname(path);
   return basename(configDirectory) === ".zcode" ? dirname(configDirectory) : configDirectory;
 }
 
-function normalizeProjectConfig(config: RuntimeConfigPatch, baseDir: string): RuntimeConfigPatch {
+export function normalizeProjectConfig(
+  config: RuntimeConfigPatch,
+  baseDir: string,
+): RuntimeConfigPatch {
   const normalized: RuntimeConfigPatch = config.hooks
     ? (() => {
         const { hooks: _hooks, ...safeConfig } = config;
@@ -127,7 +141,8 @@ function normalizeProjectConfig(config: RuntimeConfigPatch, baseDir: string): Ru
     : { ...config };
 
   if (normalized.plugins?.dirs) {
-    // 工作区目录插件曾绕过用户安装直接注册 Hook/MCP;项目配置不能引入插件根目录。
+    // 工作区目录插件曾绕过用户安装直接注册 Hook/MCP;项目目录只作为待信任候选
+    // (ProjectConfigFile.pluginDirCandidates),可执行配置里永远没有项目插件根目录。
     const { dirs: _dirs, ...plugins } = normalized.plugins;
     normalized.plugins = plugins;
   }
@@ -148,7 +163,10 @@ function normalizeProjectConfig(config: RuntimeConfigPatch, baseDir: string): Ru
   };
 }
 
-function normalizeProjectMcpServer(server: McpServerConfig, baseDir: string): McpServerConfig {
+export function normalizeProjectMcpServer(
+  server: McpServerConfig,
+  baseDir: string,
+): McpServerConfig {
   if (server.type !== "stdio") return server;
 
   const cwd = server.cwd ?? CURRENT_DIRECTORY;

+ 23 - 2
apps/zcode-cli/packages/adapters/src/config/schema.ts

@@ -263,7 +263,11 @@ export const hookCommandSchema = z
 
 export const hookMatcherSchema = z
   .object({
-    matcher: z.string().min(1).optional(),
+    // 旧配置用空串表示无筛选;拒绝空串会让整份用户配置失效。
+    matcher: z
+      .string()
+      .transform((matcher) => matcher || undefined)
+      .optional(),
     hooks: z.array(z.discriminatedUnion("type", [hookProcessSchema, hookCommandSchema])).min(1),
   })
   .strict();
@@ -319,7 +323,24 @@ const projectConfigFileSchema = ZCodeConfigFileSchema.pick({
   command: true,
 })
   .extend({
-    plugins: pluginsSchema.pick({ enabledPlugins: true, options: true }).optional(),
+    // 插件选项可展开为解释器、命令和环境变量;已安装插件不能替仓库输入建立信任。
+    // 项目级显式设置由用户私有存储提供,仓库 options 连校验也不参与,避免坏值拖垮其它声明。
+    plugins: pluginsSchema
+      .pick({ enabledPlugins: true })
+      .extend({
+        // 项目 plugins.dirs 只是待信任候选,不进入可执行配置(normalizeProjectConfig 再剥离);
+        // 非法值按缺省处理,不能拖垮同文件的其它声明。
+        dirs: z
+          .preprocess(
+            (value) =>
+              Array.isArray(value)
+                ? value.filter((item) => typeof item === "string" && item.trim().length > 0)
+                : undefined,
+            z.array(z.string()).optional(),
+          )
+          .optional(),
+      })
+      .optional(),
     skills: z
       .preprocess(
         (value) =>

+ 63 - 42
apps/zcode-cli/packages/adapters/src/exec/bash-shell-provider.ts

@@ -1,9 +1,11 @@
 import { accessSync, constants as fsConstants } from "node:fs";
-import { basename, delimiter, join, win32 } from "node:path";
-import { windowsExecutableCandidates } from "./windows-executable.js";
+import { basename, delimiter, join } from "node:path";
+import { discoverWindowsGitBash, type WindowsGitBashDiscoveryOptions } from "@zcode/shared/node";
+import { resolveWindowsComSpec } from "./windows-executable.js";
 import {
   type ExecutionShellDialect,
   type ExecutionShellSelection,
+  WINDOWS_CMD_SHELL_DISPLAY_NAME,
 } from "@zcode/contracts";
 
 type PosixShellKind = "bash" | "zsh";
@@ -12,14 +14,11 @@ type EffectiveBashShellResolveOptions = {
   env: NodeJS.ProcessEnv;
   platform: NodeJS.Platform | string;
   exists?: ExecutableCheck;
+  gitBashDiscovery?: Omit<WindowsGitBashDiscoveryOptions, "env" | "platform" | "isExecutable">;
   override?: ExecutionShellSelection;
 };
 
 const FIXED_POSIX_SHELL_DIRS = ["/bin", "/usr/bin", "/usr/local/bin", "/opt/homebrew/bin"];
-const WINDOWS_GIT_BASH_PATHS = [
-  "C:\\Program Files\\Git\\bin\\bash.exe",
-  "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
-] as const;
 
 export interface BashShellProvider {
   dialect: ExecutionShellDialect;
@@ -33,9 +32,9 @@ export interface EffectiveBashShellResolution {
   provider?: BashShellProvider;
 }
 
-export function resolveEffectiveBashShellSelection(
+export async function resolveEffectiveBashShellSelection(
   options: EffectiveBashShellResolveOptions,
-): EffectiveBashShellResolution {
+): Promise<EffectiveBashShellResolution> {
   const snapshotResolution = resolveShellSnapshotSelection(options.override);
   if (snapshotResolution) {
     return snapshotResolution;
@@ -74,34 +73,45 @@ export function resolvePosixBashShell(
   return undefined;
 }
 
-export function resolveWindowsBashShellProvider(options: {
+export async function resolveWindowsBashShellProvider(options: {
   env: NodeJS.ProcessEnv;
   exists?: ExecutableCheck;
+  gitBashDiscovery?: Omit<WindowsGitBashDiscoveryOptions, "env" | "platform" | "isExecutable">;
   override?: ExecutionShellSelection;
-}): BashShellProvider | undefined {
-  return resolveEffectiveWindowsBashShellSelection({
-    env: options.env,
-    exists: options.exists,
-    override: options.override,
-    platform: "win32",
-  }).provider;
+}): Promise<BashShellProvider | undefined> {
+  return (
+    await resolveEffectiveWindowsBashShellSelection({
+      env: options.env,
+      exists: options.exists,
+      gitBashDiscovery: options.gitBashDiscovery,
+      override: options.override,
+      platform: "win32",
+    })
+  ).provider;
 }
 
-export function resolveWindowsGitBashShell(
+export async function resolveWindowsGitBashShell(
   env: NodeJS.ProcessEnv,
   exists?: ExecutableCheck,
-): string | undefined {
-  for (const candidate of WINDOWS_GIT_BASH_PATHS) {
-    if (isExecutableCandidate(candidate, exists)) return candidate;
-  }
-
-  const gitExe = windowsExecutableCandidates("git", env).find((candidate) =>
-    isExecutableCandidate(candidate, exists),
-  );
-  if (!gitExe) return undefined;
-
-  const inferred = inferWindowsGitBashPathsFromGitExe(gitExe);
-  return inferred.find((candidate) => isExecutableCandidate(candidate, exists));
+  gitBashDiscovery?: Omit<WindowsGitBashDiscoveryOptions, "env" | "platform" | "isExecutable">,
+): Promise<string | undefined> {
+  // 原来的固定目录/PATH 发现会漏掉非标准安装;共享发现修复漏检,不改 shell 选择策略。
+  // exists 注入只描述隔离布局,不能混入本机注册表或配置;显式 discovery probe 仍可覆盖默认隔离。
+  const gitBash = await discoverWindowsGitBash({
+    ...(exists
+      ? {
+          readRegistryInstallRoots: async () => [],
+          readTextFile: async () => {
+            throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
+          },
+        }
+      : {}),
+    ...gitBashDiscovery,
+    env,
+    isExecutable: exists,
+    platform: "win32",
+  });
+  return gitBash?.path;
 }
 
 function createGitBashProvider(shellPath: string): BashShellProvider {
@@ -156,9 +166,9 @@ function createShellProviderFromSelection(
   return undefined;
 }
 
-function resolveEffectiveWindowsBashShellSelection(
+async function resolveEffectiveWindowsBashShellSelection(
   options: EffectiveBashShellResolveOptions,
-): EffectiveBashShellResolution {
+): Promise<EffectiveBashShellResolution> {
   const override = options.override;
   if (override?.source === "user-config") {
     if (
@@ -185,7 +195,7 @@ function resolveEffectiveWindowsBashShellSelection(
           provider: createWindowsCmdProvider(cmdPath),
           selection: shellSelection({
             dialect: "cmd",
-            displayName: "CMD",
+            displayName: WINDOWS_CMD_SHELL_DISPLAY_NAME,
             id: override.id,
             label: override.label,
             path: cmdPath,
@@ -196,7 +206,11 @@ function resolveEffectiveWindowsBashShellSelection(
     }
   }
 
-  const gitBash = resolveWindowsGitBashShell(options.env, options.exists);
+  const gitBash = await resolveWindowsGitBashShell(
+    options.env,
+    options.exists,
+    options.gitBashDiscovery,
+  );
   if (gitBash) {
     return {
       provider: createGitBashProvider(gitBash),
@@ -211,7 +225,22 @@ function resolveEffectiveWindowsBashShellSelection(
     };
   }
 
-  return legacyShellSelection();
+  // 修复原因:这里原来返回 legacy-shell / "system shell"(无 path、无 provider),执行层再另读
+  // ComSpec。实际执行器是 cmd.exe,模型却看到 system shell 加工具名 Bash,按 bash 写命令,cmd 不认
+  // ls、cat、head 等(Windows 冻结重放 36–42% 的下一步出现这类命令);Guarded 也因 legacy-shell
+  // 一律 unsupported 而不拦危险命令。现在在选择层就定下 ComSpec 上的 CMD,模型、权限、执行读同一份 selection。
+  const comSpec = resolveWindowsComSpec(options.env);
+  return {
+    provider: createWindowsCmdProvider(comSpec),
+    selection: shellSelection({
+      dialect: "cmd",
+      displayName: WINDOWS_CMD_SHELL_DISPLAY_NAME,
+      id: "auto:cmd",
+      label: WINDOWS_CMD_SHELL_DISPLAY_NAME,
+      path: comSpec,
+      source: "auto-detected",
+    }),
+  };
 }
 
 function resolveEffectivePosixBashShellSelection(
@@ -263,14 +292,6 @@ function legacyShellSelection(): EffectiveBashShellResolution {
   };
 }
 
-function inferWindowsGitBashPathsFromGitExe(gitExe: string): string[] {
-  const gitDir = win32.dirname(gitExe);
-  return [
-    win32.normalize(win32.join(gitDir, "..", "bin", "bash.exe")),
-    win32.normalize(win32.join(gitDir, "..", "..", "bin", "bash.exe")),
-  ];
-}
-
 function createWindowsCmdProvider(shellPath: string): BashShellProvider {
   return {
     dialect: "cmd",

+ 9 - 17
apps/zcode-cli/packages/adapters/src/exec/execution-command.ts

@@ -1,13 +1,14 @@
 import { existsSync } from "node:fs";
 import { extname } from "node:path";
 import { sanitizeZCodeRuntimeEnvInPlace } from "@zcode/shared";
+import type { WindowsGitBashDiscoveryOptions } from "@zcode/shared/node";
 import { applyNetworkEgressEnv, type NetworkEgressEnvPolicy } from "../network/subprocess-env.js";
 import {
   resolveEffectiveBashShellSelection,
   type BashShellProvider,
 } from "./bash-shell-provider.js";
 import { applyExecutionTextEnv } from "./outputEncoding.js";
-import { windowsExecutableCandidates } from "./windows-executable.js";
+import { resolveWindowsComSpec, windowsExecutableCandidates } from "./windows-executable.js";
 import type {
   ExecutionCommand,
   ExecutionEnvOverlay,
@@ -68,16 +69,17 @@ export function buildExecutionEnv(
   return env;
 }
 
-export function resolveExecutionCommand(
+export async function resolveExecutionCommand(
   command: ExecutionCommand,
   options: {
     cwd?: string;
     env?: NodeJS.ProcessEnv;
     exists?: (path: string) => boolean;
+    gitBashDiscovery?: Omit<WindowsGitBashDiscoveryOptions, "env" | "platform" | "isExecutable">;
     platform?: NodeJS.Platform;
     resolvedShell?: ResolvedSpawnCommand;
   } = {},
-): ResolvedSpawnCommand {
+): Promise<ResolvedSpawnCommand> {
   const platform = options.platform ?? process.platform;
   const env = options.env ?? process.env;
 
@@ -87,9 +89,10 @@ export function resolveExecutionCommand(
     }
 
     if (command.shellProfile === "posix-bash") {
-      const resolution = resolveEffectiveBashShellSelection({
+      const resolution = await resolveEffectiveBashShellSelection({
         env,
         exists: options.exists,
+        gitBashDiscovery: options.gitBashDiscovery,
         override: command.shellOverride,
         platform,
       });
@@ -134,7 +137,7 @@ export function resolveExecutionCommand(
   return {
     args: createCmdShimArgs(resolvedFile, command.args ?? []),
     cwdDialect: "cmd",
-    file: getEnvValue(env, "ComSpec", "win32") ?? "cmd.exe",
+    file: resolveWindowsComSpec(env),
     shell: false,
   };
 }
@@ -217,7 +220,7 @@ function resolveShell(
 ): true | string {
   if (typeof shell === "string") return shell;
   if (platform === "win32") {
-    return getEnvValue(env, "ComSpec", "win32") ?? "cmd.exe";
+    return resolveWindowsComSpec(env);
   }
   return true;
 }
@@ -273,14 +276,3 @@ function deleteEnvKey(env: Record<string, string>, key: string, platform: NodeJS
     }
   }
 }
-
-function getEnvValue(
-  env: NodeJS.ProcessEnv,
-  key: string,
-  platform: NodeJS.Platform,
-): string | undefined {
-  if (platform !== "win32") return env[key];
-  const lowerKey = key.toLowerCase();
-  const actualKey = Object.keys(env).find((candidate) => candidate.toLowerCase() === lowerKey);
-  return actualKey ? env[actualKey] : undefined;
-}

+ 43 - 16
apps/zcode-cli/packages/adapters/src/exec/node-execution-adapter-process.ts

@@ -17,6 +17,7 @@ import {
   terminateGenericPosixProcessGroup,
 } from "./process-tree.js";
 import {
+  gitBashPreinstalledPathExport,
   revalidateShellInitSnapshotForExecution,
   supportsShellInitSnapshot,
 } from "./shell-init-snapshot.js";
@@ -59,17 +60,25 @@ export class NodeExecutionAdapterProcess extends NodeExecutionAdapterResults {
     };
   }
 
-  protected async prepareChildSpawn(request: ExecutionRequest): Promise<PreparedChildSpawn> {
+  protected async prepareChildSpawn(
+    request: ExecutionRequest,
+    signal?: AbortSignal,
+  ): Promise<PreparedChildSpawn> {
     const env = buildExecutionEnv(request.env, {
       network: this.options.network,
       platform: this.platform,
       processEnv: this.processEnv,
     });
-    const resolvedCommand = resolveExecutionCommand(request.command, {
+    const resolvedCommand = await resolveExecutionCommand(request.command, {
       cwd: request.cwd,
       env,
       platform: this.platform,
     });
+    // 异步发现期间可能已取消或关闭;原 spawn 前检查太晚,不能再启动 shell init snapshot 辅助进程。
+    signal?.throwIfAborted();
+    if (this.closePromise) {
+      throw new Error("Execution adapter is shutting down");
+    }
     const rootDir =
       this.options.outputRootDir ?? resolveDefaultOutputRootDir(this.options.processEnv);
     const sessionId = sanitizePathSegment(String(request.trace?.sessionId ?? "unknown-session"));
@@ -92,20 +101,38 @@ export class NodeExecutionAdapterProcess extends NodeExecutionAdapterResults {
         : undefined;
     const useLoginShell = shellInitSnapshot ? false : true;
     const resolvedShell = setResolvedShellLoginMode(resolvedCommand, useLoginShell);
-    const requestWithSources = applyBashSourcesToExecutionRequest(request, {
-      leadingSources: shellInitSnapshot
-        ? [
-            {
-              optional: true,
-              path: shellInitSnapshot.path,
-              shellPath: shellInitSnapshot.shellPath,
+    const preinstalledPathExport =
+      !shellInitSnapshot &&
+      resolvedCommand.cwdDialect === "git-bash" &&
+      request.command.mode === "shell" &&
+      request.command.shellProfile === "posix-bash"
+        ? gitBashPreinstalledPathExport(snapshotEnv)
+        : undefined;
+    const requestWithSources = applyBashSourcesToExecutionRequest(
+      preinstalledPathExport && request.command.mode === "shell"
+        ? {
+            ...request,
+            command: {
+              ...request.command,
+              command: `${preinstalledPathExport}\n${request.command.command}`,
             },
-          ]
-        : [],
-      rootDir,
-      sessionId,
-      shellDialect: resolvedCommand.cwdDialect,
-    });
+          }
+        : request,
+      {
+        leadingSources: shellInitSnapshot
+          ? [
+              {
+                optional: true,
+                path: shellInitSnapshot.path,
+                shellPath: shellInitSnapshot.shellPath,
+              },
+            ]
+          : [],
+        rootDir,
+        sessionId,
+        shellDialect: resolvedCommand.cwdDialect,
+      },
+    );
     const capturePlan = createCwdCapturePlan(requestWithSources, {
       dialect: resolvedCommand.cwdDialect,
       platform: this.platform,
@@ -115,7 +142,7 @@ export class NodeExecutionAdapterProcess extends NodeExecutionAdapterResults {
         ? requestWithSources.command.mode === "shell"
           ? applyResolvedShellCommand(resolvedShell, requestWithSources.command.command)
           : resolvedShell
-        : resolveExecutionCommand(capturePlan.command, {
+        : await resolveExecutionCommand(capturePlan.command, {
             cwd: request.cwd,
             env,
             platform: this.platform,

+ 1 - 1
apps/zcode-cli/packages/adapters/src/exec/node-execution-adapter-run.ts

@@ -300,7 +300,7 @@ export class NodeExecutionAdapterRun extends NodeExecutionAdapterProcess {
     }
 
     try {
-      const prepared = await this.prepareChildSpawn(request);
+      const prepared = await this.prepareChildSpawn(request, options.signal);
 
       // shell init snapshot 创建是异步的;用户可能在等待期间取消或关闭 adapter。
 

+ 96 - 2
apps/zcode-cli/packages/adapters/src/exec/node-execution-adapter.ts

@@ -1,8 +1,102 @@
+import { constants } from "node:fs";
+import { access, realpath, stat } from "node:fs/promises";
+import { homedir } from "node:os";
+import path from "node:path";
+import { gitBashPathToWindowsPath } from "@zcode/contracts";
 import { NodeExecutionAdapterLifecycle } from "./node-execution-adapter-lifecycle.js";
 import type { NodeExecutionAdapterOptions } from "./execution-adapter-types.js";
-import type { ExecutionPort } from "@zcode/contracts";
+import type {
+  AdbExecutableRequest,
+  AdbExecutableResolution,
+  ExecutionPort,
+} from "@zcode/contracts";
 
-export class NodeExecutionAdapter extends NodeExecutionAdapterLifecycle implements ExecutionPort {}
+export class NodeExecutionAdapter extends NodeExecutionAdapterLifecycle implements ExecutionPort {
+  async resolveAdbExecutable(request: AdbExecutableRequest): Promise<AdbExecutableResolution> {
+    const windows = this.platform === "win32";
+    const paths = windows ? path.win32 : path.posix;
+    const env = (name: string) =>
+      this.processEnv[
+        Object.keys(this.processEnv).find((key) =>
+          windows ? key.toUpperCase() === name : key === name,
+        ) ?? name
+      ];
+    const normalize = (value: string) => (windows ? gitBashPathToWindowsPath(value) : value);
+    const workspace = paths.resolve(normalize(request.workspaceRoot));
+    const canonicalWorkspace = await realpath(workspace);
+    const inside = (root: string, candidate: string) => {
+      const relative = paths.relative(root, candidate);
+      return (
+        relative === "" ||
+        (!paths.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${paths.sep}`))
+      );
+    };
+    const inWorkspace = (candidate: string) =>
+      inside(workspace, candidate) || inside(canonicalWorkspace, candidate);
+    const check = async (candidate: string): Promise<AdbExecutableResolution> => {
+      if (inWorkspace(candidate)) return { status: "workspace" };
+      try {
+        const canonical = await realpath(candidate);
+        if (inWorkspace(canonical)) return { status: "workspace" };
+        if (!(await stat(canonical)).isFile()) return { status: "missing" };
+        await access(canonical, windows ? constants.F_OK : constants.X_OK);
+        return { status: "resolved", path: canonical };
+      } catch (error) {
+        if (
+          ["ENOENT", "ENOTDIR", "EACCES", "EPERM", "ELOOP"].includes(
+            (error as NodeJS.ErrnoException).code ?? "",
+          )
+        )
+          return { status: "missing" };
+        throw error;
+      }
+    };
+    const file = normalize(request.file);
+    const names =
+      windows && !paths.extname(file)
+        ? [file + ".exe", file + ".com", file + ".cmd", file + ".bat"]
+        : [file];
+    if (paths.isAbsolute(file) || paths.dirname(file) !== "." || /[/\\]/.test(file)) {
+      for (const name of names) {
+        const result = await check(paths.resolve(normalize(request.cwd), name));
+        if (result.status !== "missing") return result;
+      }
+      return { status: "missing" };
+    }
+    const home = env(windows ? "USERPROFILE" : "HOME") || homedir();
+    const sdkRoots = [
+      env("ANDROID_HOME"),
+      env("ANDROID_SDK_ROOT"),
+      ...(windows
+        ? [
+            paths.join(
+              env("LOCALAPPDATA") || paths.join(home, "AppData", "Local"),
+              "Android",
+              "Sdk",
+            ),
+          ]
+        : [paths.join(home, "Library", "Android", "sdk"), paths.join(home, "Android", "Sdk")]),
+    ];
+    const directories = [
+      ...sdkRoots
+        .filter((root): root is string => !!root)
+        .map((root) => paths.join(normalize(root), "platform-tools")),
+      ...(env("PATH") ?? "").split(paths.delimiter).map((entry) => entry.replace(/^"(.*)"$/, "$1")),
+    ];
+    let workspaceCandidate = false;
+    for (const entry of directories) {
+      const directory = normalize(entry);
+      // 不用 where/which,也不把空项、相对 PATH 或项目目录交给 Shell 重新查找。
+      if (!paths.isAbsolute(directory)) continue;
+      for (const name of names) {
+        const result = await check(paths.join(directory, name));
+        if (result.status === "resolved") return result;
+        workspaceCandidate ||= result.status === "workspace";
+      }
+    }
+    return { status: workspaceCandidate ? "workspace" : "missing" };
+  }
+}
 
 export function createNodeExecutionAdapter(
   options: NodeExecutionAdapterOptions = {},

+ 2 - 1
apps/zcode-cli/packages/adapters/src/exec/outputEncoding.ts

@@ -1,6 +1,7 @@
 import { execFileSync } from "node:child_process";
 import { StringDecoder } from "node:string_decoder";
 import iconv from "iconv-lite";
+import { resolveWindowsComSpec } from "./windows-executable.js";
 
 const WINDOWS_OUTPUT_ENCODING_OVERRIDE_ENV = "ZCODE_WINDOWS_OUTPUT_ENCODING";
 const PYTHON_UTF8_ENV_PATCH = {
@@ -202,7 +203,7 @@ export function createExecutionOutputStreamDecoder(legacyOutputEncoding: string
 }
 
 function readWindowsActiveCodePageEncoding(env: NodeJS.ProcessEnv): string | null {
-  const comSpec = getEnvValue(env, "ComSpec", "win32") ?? "cmd.exe";
+  const comSpec = resolveWindowsComSpec(env);
   try {
     const output = execFileSync(comSpec, ["/d", "/s", "/c", "chcp"], {
       encoding: "utf8",

+ 27 - 1
apps/zcode-cli/packages/adapters/src/exec/shell-init-snapshot.ts

@@ -184,13 +184,39 @@ export class ShellInitSnapshotManager {
         timeout: SNAPSHOT_TIMEOUT_MS,
         windowsHide: true,
       });
-      return result.stdout.trim() || request.env.PATH || "";
+      return withPreinstalledBinFirst(result.stdout.trim(), request.env) || request.env.PATH || "";
     } catch {
       return request.env.PATH ?? "";
     }
   }
 }
 
+/** Agent PATH 第一项就是 Host 注入的预装入口目录;只有桌面 Host 注入变量时才成立。 */
+function gitBashPreinstalledBin(env: NodeJS.ProcessEnv): string | undefined {
+  if (!env.ZCODE_PREINSTALLED_TOOLS_AVAILABLE) return undefined;
+  // Windows 环境变量不区分大小写,普通对象里可能是 Path。
+  const agentPath = Object.entries(env).find(([name]) => name.toUpperCase() === "PATH")?.[1];
+  const first = agentPath?.split(";")[0];
+  return first ? windowsPathToGitBashPath(first) : undefined;
+}
+
+/**
+ * 根因:Git Bash 登录 profile 把 ~/bin、/ucrt64/bin、/usr/bin 放到 <bin> 之前,Git 自带的 pdftotext
+ * 因此抢先于预装入口。不能改用 Agent PATH,否则 System32 的 find、sort 会排到 /usr/bin 之前。
+ */
+function withPreinstalledBinFirst(loginPath: string, env: NodeJS.ProcessEnv): string {
+  const bin = gitBashPreinstalledBin(env);
+  if (!loginPath || !bin) return loginPath;
+  const others = loginPath.split(":").filter((item) => item.toLowerCase() !== bin.toLowerCase());
+  return [bin, ...others].join(":");
+}
+
+/** 没有快照时命令走登录 shell,同样要恢复入口目录的位置。 */
+export function gitBashPreinstalledPathExport(env: NodeJS.ProcessEnv): string | undefined {
+  const bin = gitBashPreinstalledBin(env);
+  return bin ? `export PATH=${shellQuoteAlways(bin)}:"$PATH"` : undefined;
+}
+
 export async function cleanupStaleShellInitSnapshots(
   options: CleanupStaleShellInitSnapshotsOptions,
 ): Promise<ShellInitSnapshotCleanupResult> {

+ 5 - 0
apps/zcode-cli/packages/adapters/src/exec/windows-executable.ts

@@ -11,6 +11,11 @@ export function getWindowsEnvValue(
   return match ? env[match] : undefined;
 }
 
+/** Windows 默认 shell:环境里的 ComSpec,缺失时用裸名 cmd.exe。adapters 里所有经 cmd.exe 执行的路径共用这一条规则。 */
+export function resolveWindowsComSpec(env: NodeJS.ProcessEnv): string {
+  return getWindowsEnvValue(env, "ComSpec") ?? "cmd.exe";
+}
+
 export function windowsExecutableCandidates(
   file: string,
   env: NodeJS.ProcessEnv,

+ 12 - 11
apps/zcode-cli/packages/adapters/src/fs/index.ts

@@ -1,3 +1,4 @@
+/* eslint-disable max-lines -- 存量文件已超过 max-lines 上限;本次只为 ZP-20261110-04 增加符号链接写入校验,拆分另开工单(架构例外 workflow-draft-symlink-index-lines)。 */
 // ============================================================
 // Node FileSystem Adapter
 // ============================================================
@@ -46,6 +47,7 @@ import {
   shouldNormalizeLineEndings,
 } from "./text-metadata.js";
 import { readTextFileRangeFromNode } from "./text-range-reader.js";
+import { assertNoSymlinkBetween, getNodeErrorCode, SymlinkWriteRefusedError } from "./symlink-guard.js";
 import { maybeThrowStorageFsFault } from "../storage/fs-fault-injection.js";
 
 const DEFAULT_GLOB_MAX_RESULTS = 100;
@@ -295,6 +297,12 @@ export class NodeFileSystemAdapter implements FileSystemPort {
     const content = encodeTextContent({ content: textContent, encoding, path });
 
     try {
+      // ZP-20261110-04:草稿写入的字符串路径在草稿目录内,但目录链接可把真实落点导向项目外。
+      // 在建父目录前核验一次(避免经链接建出项目外的目录),写入前再核验一次(紧贴 rename)。
+      if (request.symlinkFreeBase !== undefined) {
+        await assertNoSymlinkBetween(request.symlinkFreeBase, path);
+      }
+
       if (request.expectedRevision) {
         await this.assertExpectedRevision(path, request.expectedRevision);
       }
@@ -304,6 +312,10 @@ export class NodeFileSystemAdapter implements FileSystemPort {
         await mkdir(dirname(path), { recursive: true });
       }
 
+      if (request.symlinkFreeBase !== undefined) {
+        await assertNoSymlinkBetween(request.symlinkFreeBase, path);
+      }
+
       if (request.atomic ?? true) {
         await atomicWrite(path, content);
       } else {
@@ -686,17 +698,6 @@ async function readAtMostBytes(
   }
 }
 
-class SymlinkWriteRefusedError extends Error {
-  constructor(message: string) {
-    super(message);
-    this.name = "SymlinkWriteRefusedError";
-  }
-}
-
-function getNodeErrorCode(error: unknown): unknown {
-  return typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
-}
-
 async function atomicWrite(path: string, content: Buffer): Promise<void> {
   let existingMode: number | undefined;
 

+ 49 - 0
apps/zcode-cli/packages/adapters/src/fs/symlink-guard.ts

@@ -0,0 +1,49 @@
+// 符号链接写入防护:草稿写入前逐级核验父目录,拒绝经由符号链接写到工作区外(ZP-20261110-04)。
+// 从 index.ts 拆出,使适配器主文件只为本次修复增长最少的行数。
+
+import { lstat } from "node:fs/promises";
+import { isAbsolute, join, relative, sep } from "node:path";
+
+export class SymlinkWriteRefusedError extends Error {
+  constructor(message: string) {
+    super(message);
+    this.name = "SymlinkWriteRefusedError";
+  }
+}
+
+/**
+ * 从 `base`(不含)起逐级 lstat 到 `target`,任一级是符号链接即拒绝。
+ *
+ * 为什么只看到 `target` 为止:`atomicWrite` 只检查最后一级,父目录链接会被 rename 跟随到项目外
+ * (ZP-20261110-04:草稿目录链接到用户配置目录,覆盖后随即执行其中的 SessionStart 命令 Hook)。
+ * 不存在的层级之下无需检查——之后的 mkdir 只会建出真实目录,ENOENT / ENOTDIR 即返回。
+ * `base` 本身不核验:项目根经由链接访问是合法的。
+ */
+export async function assertNoSymlinkBetween(base: string, target: string): Promise<void> {
+  const rel = relative(base, target);
+  if (rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
+    throw new SymlinkWriteRefusedError(`Refusing to write outside symlink-free base: ${target}`);
+  }
+
+  let current = base;
+  for (const segment of rel.split(sep)) {
+    current = join(current, segment);
+    let info;
+    try {
+      info = await lstat(current);
+    } catch (error) {
+      const code = getNodeErrorCode(error);
+      if (code === "ENOENT" || code === "ENOTDIR") return;
+      throw error;
+    }
+    if (info.isSymbolicLink()) {
+      throw new SymlinkWriteRefusedError(
+        `Refusing to write through symlink: ${current} (under ${base})`,
+      );
+    }
+  }
+}
+
+export function getNodeErrorCode(error: unknown): unknown {
+  return typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
+}

+ 40 - 3
apps/zcode-cli/packages/adapters/src/mcp/appConnections.test.ts

@@ -30,20 +30,21 @@ describe("MCP App pooled connection lifetime", () => {
     await a.connectServer("fixture", config, { workingDirectory: "/fixture" });
     await b.connectServer("fixture", config, { workingDirectory: "/fixture" });
     expect(createAdapter).toHaveBeenCalledOnce();
-    expect(a.appConnectionSnapshot?.("fixture")).toEqual(snapshot);
+    const admitted = a.appConnectionSnapshot!("fixture")!;
+    expect(admitted).toMatchObject({ generation: snapshot.generation });
     const revokeA = vi.fn(),
       revokeB = vi.fn();
     a.onAppConnectionInvalidated?.("fixture", revokeA);
     b.onAppConnectionInvalidated?.("fixture", revokeB);
     await expect(
-      b.callTool({ serverName: "fixture", toolName: "increment" }, { appConnection: snapshot }),
+      b.callTool({ serverName: "fixture", toolName: "increment" }, { appConnection: admitted }),
     ).rejects.toThrow("Not connected");
     expect(adapter.callTool).toHaveBeenCalledTimes(1);
     await a.close();
     expect(revokeA).toHaveBeenCalledOnce();
     expect(revokeB).not.toHaveBeenCalled();
     expect(a.appConnectionSnapshot?.("fixture")).toBeNull();
-    expect(b.appConnectionSnapshot?.("fixture")).toEqual(snapshot);
+    expect(b.appConnectionSnapshot?.("fixture")).toEqual(admitted);
     expect(listeners.size).toBe(1);
     expect(adapter.close).not.toHaveBeenCalled();
     await b.close();
@@ -52,3 +53,39 @@ describe("MCP App pooled connection lifetime", () => {
     await pool.close();
   });
 });
+
+it("does not transfer an admitted call to a replacement pool entry with the same config", async () => {
+  const callTool = vi.fn(async () => ({ content: [] }));
+  const pool = createMcpConnectionPool({
+    idleGraceMs: 0,
+    createAdapter: () =>
+      ({
+        connectServer: async () => ({
+          status: "connected",
+          transport: "stdio",
+          toolCount: 0,
+          updatedAt: "",
+        }),
+        status: async () => ({}),
+        listTools: async () => [],
+        close: async () => {},
+        appConnectionSnapshot: () => ({ identity: "same-config", generation: 1 }),
+        callTool,
+      }) as unknown as McpPort,
+  });
+  const lease = pool.acquireLease({ sessionId: "replacement" });
+  const config: McpServerConfig = { type: "stdio", command: "fixture" };
+  try {
+    await lease.connectServer("fixture", config);
+    const admitted = lease.appConnectionSnapshot!("fixture")!;
+    await lease.disconnectServer("fixture");
+    await lease.connectServer("fixture", config);
+    await expect(
+      lease.callTool({ serverName: "fixture", toolName: "write" }, { appConnection: admitted }),
+    ).rejects.toThrow(/changed/);
+    expect(callTool).not.toHaveBeenCalled();
+  } finally {
+    await lease.close();
+    await pool.close();
+  }
+});

+ 212 - 0
apps/zcode-cli/packages/adapters/src/mcp/config-loader.ts

@@ -0,0 +1,212 @@
+import { mkdir, stat } from "node:fs/promises";
+import { join, normalize } from "node:path";
+import type {
+  Logger,
+  McpConfigurationSnapshot,
+  McpServerConfig,
+  PluginMetadata,
+  PluginDiagnostic,
+} from "@zcode/contracts";
+import { DefaultRuntimeConfig } from "@zcode/contracts";
+import {
+  readPluginSecretsFile,
+  resolvePluginSecretOverrides,
+  resolvePluginSecretsPath,
+} from "../config/plugin-secrets.adapter.js";
+import type { PluginOptionLayer } from "../config/config-factory.js";
+import { parseConfigFileToRuntimePatchWithDiagnostics } from "../config/schema.js";
+import {
+  normalizeMcpServersShape,
+  pluginMcpSources,
+  resolvePluginMcpServers,
+} from "../plugins/mcp.js";
+import { sanitizePluginId } from "../plugins/helpers.js";
+import {
+  createLiveFileReader,
+  readEnabledPlugins,
+  readLiveConfig,
+  type LivePluginCandidate,
+} from "../plugins/live-inventory.js";
+import { normalizeProjectMcpServer } from "../config/project-config.adapter.js";
+
+export interface McpConfigurationLoaderOptions {
+  configPaths: string[];
+  userConfigPath?: string;
+  fallbackPaths?: Record<string, string>;
+  pluginStorageRoot: string;
+  pluginRoots: LivePluginCandidate[];
+  explicitServers?: Record<string, McpServerConfig>;
+  workingDirectory: string;
+  env?: Record<string, string | undefined>;
+  defaultEnabledPlugins?: ReadonlySet<string>;
+  logger?: Logger;
+}
+
+type StablePlugins = Map<string, { id: string; servers: Record<string, McpServerConfig> }>;
+
+export function createMcpConfigurationLoader(options: McpConfigurationLoaderOptions) {
+  // 读文件的回退基础与 warn 去重由共享 reader 持有,只在结果被采纳时提交。
+  const reader = createLiveFileReader({
+    label: "MCP configuration",
+    logger: options.logger,
+  });
+  // 只跨越原子安装的未提交窗口保留稳定执行配置;解析失败、禁用、卸载均不回退。
+  let stablePlugins: StablePlugins = new Map();
+
+  async function load() {
+    const pass = reader.begin();
+    const { json, warnings } = pass;
+    const { files, merged } = await readLiveConfig(pass, options);
+    // 磁盘配置每次从来源重算,不能把旧合并结果作为底层,否则删除的 server 会复活。
+    let servers: Record<string, McpServerConfig> = {};
+    // 修复原因:项目配置曾原样进入加载器,项目 plugins.dirs 能注册并启动未经信任的插件 MCP。
+    // 项目文件与启动配置共用白名单与 normalizeProjectConfig,去掉 Hook 声明与 plugins.dirs。
+    for (const { path, user, base, patch } of files) {
+      let configured = patch.mcp?.servers;
+      const fallback = options.fallbackPaths?.[path];
+      if (!Object.keys(configured ?? {}).length && fallback) {
+        const legacy = await json(fallback, (value) => {
+          const result = parseConfigFileToRuntimePatchWithDiagnostics({
+            mcp: { servers: value.mcpServers ?? {} },
+          });
+          if (result.diagnostics.some((item) => item.severity === "error"))
+            throw new Error("Invalid legacy MCP configuration");
+        });
+        configured = parseConfigFileToRuntimePatchWithDiagnostics({
+          mcp: { servers: legacy?.mcpServers ?? {} },
+        }).config.mcp?.servers;
+      }
+      // 修复原因:修复前磁盘 server 不带来源,工作区 guard 要自己推断。回退文件的读取规则与
+      // guard 的声明规则不同,推断不到时放行,未信任工作区里的命令被执行。
+      // 来源按声明它的文件标记:项目文件及其回退为 workspace,用户配置及其回退为 user。
+      for (const [name, server] of Object.entries(configured ?? {})) {
+        servers[name] = user
+          ? { ...server, source: { kind: "user" } }
+          : { ...normalizeProjectMcpServer(server, base), source: { kind: "workspace" } };
+      }
+    }
+    const enabled = merged.features?.mcp ?? DefaultRuntimeConfig.features.mcp;
+    const plugins = { ...DefaultRuntimeConfig.plugins, ...merged.plugins };
+    // 私有选项曾只叠加到启动视图,动态加载器重读时会丢失。两条路径共用规则,并监听保存和清除。
+    const secretsPath = resolvePluginSecretsPath(options.pluginStorageRoot);
+    pass.files.add(secretsPath);
+    const secrets = await readPluginSecretsFile(secretsPath);
+    if (secrets.status === "unreadable") {
+      warnings.push([
+        "Plugin private options file is unreadable",
+        { path: secretsPath, reason: secrets.reason },
+      ]);
+    }
+    const layers: PluginOptionLayer[] = [
+      ...files.filter((file) => file.user),
+      ...files.filter((file) => !file.user && file.loaded),
+    ].map(({ user, path, base, patch }) => ({
+      scope: user ? "user" : "workspace",
+      path,
+      ...(user ? {} : { workspaceRoot: base }),
+      options: patch.plugins?.options ?? {},
+    }));
+    plugins.options = { ...plugins.options };
+    for (const { pluginId, key, value } of resolvePluginSecretOverrides(layers, secrets.file)) {
+      plugins.options[pluginId] = { ...plugins.options[pluginId], [key]: value };
+    }
+    const pluginServers: Record<string, McpServerConfig> = {};
+    const nextStablePlugins: StablePlugins = new Map();
+    for (const { candidate, loaded, stable, watched } of await readEnabledPlugins(pass, {
+      plugins,
+      pluginStorageRoot: options.pluginStorageRoot,
+      pluginRoots: options.pluginRoots,
+      defaultEnabledPlugins: options.defaultEnabledPlugins,
+    })) {
+      if (!stable) {
+        const previous = stablePlugins.get(candidate.rootPath);
+        if (previous?.id === loaded.id) {
+          nextStablePlugins.set(candidate.rootPath, previous);
+          Object.assign(pluginServers, previous.servers);
+        }
+        continue;
+      }
+      try {
+        const diagnostics: PluginDiagnostic[] = [];
+        const context = { loaded, diagnostics };
+        const definitions = Object.assign(
+          {},
+          ...(await Promise.all(
+            pluginMcpSources(context).map(async (source) => {
+              if (typeof source !== "string") return source;
+              const value = await json(source, undefined, watched);
+              return value === undefined ? {} : normalizeMcpServersShape(value, context);
+            }),
+          )),
+        );
+        const dataPath = join(options.pluginStorageRoot, "data", sanitizePluginId(loaded.id));
+        const resolved = resolvePluginMcpServers({
+          loaded,
+          definitions,
+          diagnostics,
+          dataPath,
+          env: options.env ?? process.env,
+          options: plugins.options[loaded.id] ?? {},
+          workingDirectory: options.workingDirectory,
+        });
+        // 首次热启用没有经过全量插件启动;发布前准备 cwd,失败只撤下当前插件。
+        // MCP 关闭时不会启动这些 server,不创建目录。
+        if (enabled && Object.keys(resolved).length > 0) await mkdir(dataPath, { recursive: true });
+        for (const diagnostic of diagnostics)
+          warnings.push(["Plugin MCP configuration diagnostic", { ...diagnostic }]);
+        nextStablePlugins.set(candidate.rootPath, { id: loaded.id, servers: resolved });
+        Object.assign(pluginServers, resolved);
+      } catch (error) {
+        // 变量声明等插件级错误不属于单个 server,不能让它阻断其他配置来源的增删。
+        warnings.push([
+          "Plugin MCP preparation failed",
+          { pluginId: loaded.id, error: String(error) },
+        ]);
+      }
+    }
+    servers = { ...pluginServers, ...(options.explicitServers ?? servers) };
+    const filesystem = servers.filesystem;
+    // 配置重载发生在真正的执行环境;只补当前 workspace,不能丢掉首次创建时的目录授权。
+    if (
+      !options.explicitServers &&
+      filesystem?.type === "stdio" &&
+      filesystem.args?.some((arg) => arg.includes("@modelcontextprotocol/server-filesystem")) &&
+      (
+        await stat(options.workingDirectory).catch((error: NodeJS.ErrnoException) => {
+          // 可选目录读取失败只跳过追加。修复前非 ENOENT 错误会让整次加载失败、配置无法发布。
+          if (error.code !== "ENOENT" && error.code !== "ENOTDIR")
+            warnings.push([
+              "MCP filesystem workspace unavailable",
+              { path: options.workingDirectory, error: String(error) },
+            ]);
+          return undefined;
+        })
+      )?.isDirectory()
+    ) {
+      const key = (value: string) => {
+        const path = normalize(value.trim()).replace(/[\\/]+$/, "");
+        return process.platform === "win32" ? path.toLowerCase() : path;
+      };
+      if (!filesystem.args.some((arg) => key(arg) === key(options.workingDirectory))) {
+        servers.filesystem = {
+          ...filesystem,
+          args: [...filesystem.args, options.workingDirectory],
+        };
+      }
+    }
+    // 返回未整形的结果:同一进程内共享的配置源把它交给每个会话自己的 prepare。
+    // servers 与 pluginServers 共用同一批对象,官方 CUA 信任按对象身份判定,调用方不能深拷贝。
+    return {
+      configuration: { enabled, servers } satisfies McpConfigurationSnapshot,
+      pluginServers,
+      files: pass.files,
+      /** 调用方采纳本次结果后提交回退基础与稳定插件配置,并只记录新出现的加载 warn。 */
+      commit() {
+        pass.commit();
+        stablePlugins = nextStablePlugins;
+      },
+    };
+  }
+
+  return { load };
+}

+ 171 - 0
apps/zcode-cli/packages/adapters/src/mcp/config-source.ts

@@ -0,0 +1,171 @@
+import { createHash } from "node:crypto";
+import { dirname } from "node:path";
+import type {
+  Logger,
+  McpConfigurationSnapshot,
+  McpConfigurationSource,
+  McpServerConfig,
+} from "@zcode/contracts";
+import { mcpConfigKey } from "@zcode/contracts";
+import {
+  createMcpConfigurationLoader,
+  type McpConfigurationLoaderOptions,
+} from "./config-loader.js";
+import {
+  createRefcountedRegistry,
+  createWatchedEntry,
+  WATCHED_SOURCE_DEBOUNCE_MS,
+  type WatchedEntry,
+} from "../watch/watched-source.js";
+
+/** 一次保存常产生多个 raw / all 事件;尾部去抖把它们合成一次读盘。 */
+export const MCP_CONFIG_EVENT_DEBOUNCE_MS = WATCHED_SOURCE_DEBOUNCE_MS;
+
+export interface McpConfigurationSourceOptions extends McpConfigurationLoaderOptions {
+  /** 每个会话自己的整形(内建 server、computerUse、显式 enabled、broker);必须复制后修改。 */
+  prepare?(
+    servers: Record<string, McpServerConfig>,
+    pluginServers: Record<string, McpServerConfig>,
+    enabled: boolean,
+  ): McpConfigurationSnapshot;
+}
+
+export interface McpConfigSourceRegistry {
+  /** 同一进程内输入相同的会话共用一组 watcher 与读盘结果;每次返回一个可幂等释放的 view。 */
+  acquire(options: McpConfigurationSourceOptions): Promise<McpConfigurationSource>;
+  /** 进程退出时强制关闭全部条目;之后迟到的 view 释放什么也不做。 */
+  close(): void;
+}
+
+type LoadedConfiguration = Awaited<
+  ReturnType<ReturnType<typeof createMcpConfigurationLoader>["load"]>
+>;
+
+type SharedConfigEntry = WatchedEntry<LoadedConfiguration>;
+
+/** 单个调用方的配置源(TUI、headless、测试):私有 registry,view 释放即关闭全部资源。 */
+export async function createDynamicMcpConfigSource(
+  options: McpConfigurationSourceOptions,
+): Promise<McpConfigurationSource> {
+  return createMcpConfigSourceRegistry().acquire(options);
+}
+
+/**
+ * key 与加载器输入取自同一份 options,覆盖范围一致。Set 先转成有序数组:直接交给
+ * mcpConfigKey 一律是 "{}"。只有 official 根目录被加载器使用。含 env 原值,只保留哈希。
+ */
+function sourceKey(options: McpConfigurationLoaderOptions): string {
+  const byKey = ([left]: [string, unknown], [right]: [string, unknown]) =>
+    left < right ? -1 : left > right ? 1 : 0;
+  return createHash("sha256")
+    .update(
+      JSON.stringify([
+        options.configPaths,
+        options.userConfigPath ?? null,
+        Object.entries(options.fallbackPaths ?? {}).toSorted(byKey),
+        options.pluginStorageRoot,
+        // 修复原因:已信任的项目目录插件也是加载器输入。键里只有官方根目录时,信任前后创建的
+        // 会话共用同一个源,信任后的新会话仍拿不到插件的 MCP 与技能(WPL-014 运行时日志确认)。
+        options.pluginRoots
+          .filter((root) => root.source === "official" || root.workspaceTrust?.state === "trusted")
+          .map((root) => [
+            root.rootPath,
+            root.marketplace,
+            root.workspaceTrust?.state === "trusted" ? root.workspaceTrust.declarationDigest : null,
+          ]),
+        mcpConfigKey(options.explicitServers),
+        options.workingDirectory,
+        Object.entries(options.env ?? process.env).toSorted(byKey),
+        [...(options.defaultEnabledPlugins ?? [])].toSorted(),
+      ]),
+    )
+    .digest("hex");
+}
+
+export function createMcpConfigSourceRegistry(
+  registryOptions: { logger?: Logger } = {},
+): McpConfigSourceRegistry {
+  return createRefcountedRegistry<
+    McpConfigurationSourceOptions,
+    SharedConfigEntry,
+    McpConfigurationSource
+  >({
+    label: "MCP configuration source",
+    key: ({ prepare: _prepare, ...loaderOptions }) => sourceKey(loaderOptions),
+    // 修复原因:条目比创建它的会话活得久;带着 prepare 闭包会让该会话的 app 作用域无法回收。
+    create: ({ prepare: _prepare, ...loaderOptions }) =>
+      createSharedConfigEntry({
+        ...loaderOptions,
+        logger: registryOptions.logger ?? loaderOptions.logger,
+      }),
+    view: (entry, options, release) =>
+      createConfigView(entry, options.prepare, release, options.logger),
+  });
+}
+
+function createConfigView(
+  entry: SharedConfigEntry,
+  prepare: McpConfigurationSourceOptions["prepare"],
+  release: () => void,
+  logger: Logger | undefined,
+): McpConfigurationSource {
+  const snapshot = () => {
+    const loaded = entry.current();
+    return prepare
+      ? prepare(loaded.configuration.servers, loaded.pluginServers, loaded.configuration.enabled)
+      : loaded.configuration;
+  };
+  let current = snapshot();
+  let currentKey = mcpConfigKey(current);
+  let closed = false;
+  const listeners = new Set<() => void>();
+  // 条目对每次采纳都通知;内容不变的 view 不通知会话,避免多余的 reconcile。
+  const unlisten = entry.listen(() => {
+    const next = snapshot();
+    const nextKey = mcpConfigKey(next);
+    if (nextKey === currentKey) return;
+    logger?.debug("MCP configuration snapshot published", {
+      serverNames: Object.keys(next.servers),
+    });
+    current = next;
+    currentKey = nextKey;
+    // 遍历副本:回调里取消订阅不能跳过其余订阅者。
+    for (const listener of Array.from(listeners)) listener();
+  });
+  return {
+    getSnapshot: () => current,
+    subscribe(listener) {
+      if (closed) return () => {};
+      listeners.add(listener);
+      return () => {
+        listeners.delete(listener);
+      };
+    },
+    close() {
+      // 一次 app 关闭会多次走 beginShutdown;只释放一次引用。
+      if (closed) return;
+      closed = true;
+      listeners.clear();
+      unlisten();
+      release();
+    },
+  };
+}
+
+/** 首载和后续文件事件只调用同一加载器;监听器不解析或合并配置。 */
+function createSharedConfigEntry(
+  options: McpConfigurationLoaderOptions,
+): Promise<SharedConfigEntry> {
+  const loader = createMcpConfigurationLoader(options);
+  return createWatchedEntry({
+    load: () => loader.load(),
+    // 缺失目录只在这些根目录之内向上找锚点。
+    bounds: [
+      options.workingDirectory,
+      dirname(options.pluginStorageRoot),
+      ...(options.userConfigPath ? [dirname(options.userConfigPath)] : []),
+    ],
+    label: "MCP configuration",
+    logger: options.logger,
+  });
+}

Разница между файлами не показана из-за своего большого размера
+ 628 - 351
apps/zcode-cli/packages/adapters/src/mcp/index.ts


+ 152 - 106
apps/zcode-cli/packages/adapters/src/mcp/pool.ts

@@ -1,3 +1,4 @@
+import { mcpConfigKey } from "@zcode/contracts";
 import type {
   Logger,
   McpCallToolOptions,
@@ -9,8 +10,10 @@ import type {
   McpReadResourceResult,
   McpServerConfig,
   McpServerStatus,
+  McpServerToolSnapshot,
   McpToolCallResult,
   McpToolDescriptor,
+  McpWaitForServerOptions,
 } from "@zcode/contracts";
 import { randomUUID } from "node:crypto";
 import type { McpTelemetryTracker } from "./telemetry.js";
@@ -49,11 +52,8 @@ interface PoolEntry {
   adapter: McpPort;
   closeTimer?: ReturnType<typeof setTimeout>;
   connectionContext: McpConnectionContext;
-  connecting: Promise<McpServerStatus>;
   key: string;
   refs: Set<string>;
-  /** 同一 entry 的并发存活校验共享一次探测,避免重复 ping / 重复重连。 */
-  revalidating?: Promise<void>;
   controller: AbortController;
   closing?: Promise<void>;
   serverName: string;
@@ -65,6 +65,21 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
   const logger = options.logger?.child({ module: "adapters.mcp.pool" });
   let closed = false;
   let leaseSequence = 0;
+  const snapshotListeners = new Set<() => void>();
+  const notifySnapshot = () => {
+    for (const listener of snapshotListeners) {
+      // 监听者属于不同会话:一个会话的错误不能中断其他会话的通知,也不能变成未捕获异常。
+      try {
+        listener();
+      } catch (error) {
+        logger?.error(
+          "MCP snapshot listener failed",
+          error instanceof Error ? error : new Error(String(error)),
+          { event: "mcp.snapshot.listener_failed" },
+        );
+      }
+    }
+  };
 
   const closeEntry = (entry: PoolEntry): Promise<void> => {
     entry.closing ??= (async () => {
@@ -111,67 +126,6 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
     entry.closeTimer.unref?.();
   };
 
-  // 设置页的 mcpPort 是进程级的 `protocol-settings` lease,connectionKey 只由
-  // serverName + leaseId + config 组成,配置没变时每次 mcp/list 都命中同一个 entry 并直接返回
-  // 首次连接那个早已 resolve 的 promise——不重连、不探测、不打日志。HTTP/SSE MCP 被停掉又不会
-  // 派发 onclose,于是设置页永远显示"已连接并可用",点多少次刷新都不变。
-  // 这里在显式要求 revalidate 时先确认连接仍然存活,已死则在同一个 entry 上原地重连
-  // (保持 entry 身份,其他共享该连接的 lease 不会被打断成 "not leased")。
-  const revalidateEntry = async (
-    entry: PoolEntry,
-    config: McpServerConfig,
-    connectOptions: McpConnectOptions,
-  ): Promise<void> => {
-    if (entry.revalidating) {
-      await entry.revalidating;
-      return;
-    }
-    const run = (async () => {
-      const connected = await entry.connecting.then(
-        () => true,
-        () => false,
-      );
-      const state = connected
-        ? (await entry.adapter.status())[entry.serverName]?.status
-        : undefined;
-      // 进行中的握手(含 OAuth 待授权)和显式停用/待信任状态不打扰:
-      // 重连会作废浏览器里已打开的授权 URL 和 PKCE/state。
-      if (state === "connecting" || state === "disabled" || state === "untrusted") {
-        return;
-      }
-      if (state === "connected") {
-        const alive = (await entry.adapter.pingServer?.(entry.serverName)) ?? true;
-        if (alive) {
-          logger?.debug("MCP pooled connection revalidated", {
-            ...entry.connectionContext,
-            event: "mcp.pool.connection.revalidated",
-            mcpServerName: entry.serverName,
-            status: "completed",
-          });
-          return;
-        }
-      }
-      logger?.warn("MCP pooled connection is stale; reconnecting", {
-        ...entry.connectionContext,
-        event: "mcp.pool.connection.stale",
-        mcpConnectionState: state ?? "unknown",
-        mcpServerName: entry.serverName,
-        status: "started",
-      });
-      entry.controller.signal.throwIfAborted();
-      entry.connecting = entry.adapter.connectServer(entry.serverName, config, {
-        ...connectOptions,
-        signal: entry.controller.signal,
-      });
-      // 失败由 status()/调用方 await entry.connecting 表达,这里不重复冒泡。
-      await entry.connecting.catch(() => undefined);
-    })();
-    entry.revalidating = run.finally(() => {
-      entry.revalidating = undefined;
-    });
-    await entry.revalidating;
-  };
-
   const acquireLease = (leaseOptions: { leaseId?: string; sessionId?: string } = {}): McpPort => {
     if (closed) throw new Error("MCP connection pool is closed");
     const leaseId = `${++leaseSequence}:${leaseOptions.leaseId ?? "lease"}`;
@@ -187,6 +141,18 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
         watcher.listener();
       }
     };
+    // 经本租约登记的资源订阅:serverName → JSON [uri, subscriberKey]。
+    // 释放时只退订这些键;修复前按会话前缀退订,同一会话的另一租约(重开时的重叠窗口)的订阅也被删掉。
+    const subscriptions = new Map<string, Set<string>>();
+    const releaseSubscriptions = (serverName: string, adapter: McpPort): void => {
+      const keys = subscriptions.get(serverName);
+      subscriptions.delete(serverName);
+      if (!adapter.unsubscribeResource) return;
+      for (const item of keys ?? []) {
+        const [uri, subscriberKey] = JSON.parse(item) as [string, string];
+        void adapter.unsubscribeResource({ serverName, uri, subscriberKey }).catch(() => undefined);
+      }
+    };
     let leaseClosed = false;
     const leaseShutdown = new AbortController();
     let leaseClose: Promise<void> | undefined;
@@ -212,6 +178,7 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
         if (abort) signal.removeEventListener("abort", abort);
       }
     };
+    const leaseListeners = new Set<() => void>();
     let sessionStartupReported = false;
 
     const requireEntry = (serverName: string): PoolEntry => {
@@ -222,13 +189,20 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
       return entry;
     };
 
-    const release = (serverName: string, immediate = false): Promise<void> | undefined => {
+    const release = (
+      serverName: string,
+      dispose = false,
+      immediate = false,
+    ): Promise<void> | undefined => {
       const key = leased.get(serverName);
       if (!key) return;
       leased.delete(serverName);
+      queueMicrotask(notifySnapshot);
       invalidateApps(serverName);
       const entry = entries.get(key);
       if (!entry) return;
+      // 修复前租约释放后遍历不到旧 entry,登记与远端订阅一起泄漏。
+      releaseSubscriptions(serverName, entry.adapter);
       if (!entry.refs.delete(leaseId)) return;
       options.telemetry?.releaseOwner({
         connectionId: entry.connectionContext.mcpConnectionId,
@@ -243,9 +217,12 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
         ...(sessionId ? { sessionId } : {}),
       });
       if (entry.refs.size === 0) {
-        if (immediate && entry.connectionContext.mcpIsolation === "session")
+        // 配置移除(dispose):旧配置不再被任何租约使用,立即关闭,失败只记日志。
+        // 租约关闭(immediate):session 隔离的连接立即释放并等待完成,其余按宽限期回收。
+        if (dispose) closeIdleEntry(entry);
+        else if (immediate && entry.connectionContext.mcpIsolation === "session")
           return closeEntry(entry);
-        scheduleClose(entry);
+        else scheduleClose(entry);
       }
     };
 
@@ -265,7 +242,6 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
       });
       const previousKey = leased.get(serverName);
       let entry = entries.get(key);
-      const reused = entry !== undefined;
       let ownerAdded = false;
       if (entry) {
         if (entry.closeTimer) clearTimeout(entry.closeTimer);
@@ -303,14 +279,11 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
         });
         // 连接归 pool,不能继承第一个 session 的关闭信号,否则会连带中止其他 lease。
         const controller = new AbortController();
+        adapter.onSnapshotChanged?.(notifySnapshot);
         entry = {
           adapter,
           controller,
           connectionContext,
-          connecting: adapter.connectServer(serverName, config, {
-            ...connectOptions,
-            signal: controller.signal,
-          }),
           key,
           refs: new Set([leaseId]),
           serverName,
@@ -328,6 +301,7 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
         invalidateApps(serverName);
         const previous = entries.get(previousKey);
         if (previous) {
+          releaseSubscriptions(serverName, previous.adapter);
           if (previous.refs.delete(leaseId)) {
             options.telemetry?.releaseOwner({
               connectionId: previous.connectionContext.mcpConnectionId,
@@ -341,11 +315,12 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
               refCount: previous.refs.size,
               ...(sessionId ? { sessionId } : {}),
             });
-            if (previous.refs.size === 0) scheduleClose(previous);
+            if (previous.refs.size === 0) void closeEntry(previous);
           }
         }
       }
       leased.set(serverName, key);
+      queueMicrotask(notifySnapshot);
       if (ownerAdded) {
         options.telemetry?.acquireOwner({
           connectionId: entry.connectionContext.mcpConnectionId,
@@ -365,10 +340,12 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
           ...(sessionId ? { sessionId } : {}),
         });
       }
-      // 引用登记先于任何等待;close 与 revalidate 交错也不会产生迟到 lease。
-      if (reused && connectOptions.revalidate)
-        await wait(revalidateEntry(entry, config, connectOptions), signal);
-      return await wait(entry.connecting, signal);
+      // 租约先提交;每次等待直接交给连接 owner,不能复用首个 caller 的预算或取消结果。
+      // 会话关闭或调用方取消只结束本次等待,连接任务仍归 adapter,不影响共享该连接的其他 lease。
+      return await wait(
+        entry.adapter.connectServer(serverName, config, { ...connectOptions, signal }),
+        signal,
+      );
     };
 
     const snapshot = async (): Promise<McpConnectionSnapshot> => {
@@ -405,33 +382,52 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
       return { statuses, tools };
     };
 
+    // 修复原因:App 连接身份必须只有一种格式。waitForAppConnection 曾直接返回 adapter 原始快照,
+    // appConnectionSnapshot 却带租约连接前缀;MCP App 打开时比较两者 identity,经 pool 的连接
+    // 永远判为"连接不可用"(Windows E2E 插件沙箱握手失败,日志可见两种 identity)。
+    const toLeaseSnapshot = (
+      entry: PoolEntry,
+      snapshot: { identity: string; generation: number } | null | undefined,
+    ) =>
+      snapshot
+        ? {
+            ...snapshot,
+            identity: `${entry.connectionContext.mcpConnectionId}:${snapshot.identity}`,
+          }
+        : null;
+
     return {
       async waitForAppConnection(serverName) {
         const key = leased.get(serverName);
         if (!key) return null;
         const entry = entries.get(key);
         if (!entry) return null;
-        const connecting = entry.connecting;
+        // 连接任务归 adapter 的连接记录;同一 entry 内的重连由 adapter 按连接代际判定。
         try {
-          await wait(connecting);
           const source = entry.adapter.waitForAppConnection
             ? await wait(entry.adapter.waitForAppConnection(serverName))
             : (entry.adapter.appConnectionSnapshot?.(serverName) ?? null);
           // 共享连接可能仍被其它会话持有;等待结束不能复活已释放或换源的本会话 lease。
-          return !leaseClosed &&
-            leased.get(serverName) === key &&
-            entries.get(key) === entry &&
-            entry.connecting === connecting
-            ? source
+          return !leaseClosed && leased.get(serverName) === key && entries.get(key) === entry
+            ? toLeaseSnapshot(entry, source)
             : null;
         } catch (error) {
           if (leaseClosed) return null;
           throw error;
         }
       },
+      onSnapshotChanged(listener) {
+        snapshotListeners.add(listener);
+        leaseListeners.add(listener);
+        return () => {
+          snapshotListeners.delete(listener);
+          leaseListeners.delete(listener);
+        };
+      },
       appConnectionSnapshot(serverName) {
         const key = leased.get(serverName);
-        return key ? (entries.get(key)?.adapter.appConnectionSnapshot?.(serverName) ?? null) : null;
+        const entry = key ? entries.get(key) : undefined;
+        return entry ? toLeaseSnapshot(entry, entry.adapter.appConnectionSnapshot?.(serverName)) : null;
       },
       onAppConnectionInvalidated(serverName, listener) {
         const entry = requireEntry(serverName);
@@ -452,9 +448,31 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
         request: McpCallToolRequest,
         callOptions?: McpCallToolOptions,
       ): Promise<McpToolCallResult> {
-        return await requireEntry(request.serverName).adapter.callTool(request, {
+        const entry = requireEntry(request.serverName);
+        const signal = callerSignal(callOptions?.signal);
+        if (!callOptions?.appConnection)
+          return await entry.adapter.callTool(request, {
+            ...callOptions,
+            signal,
+            // 其他 session 可以继续持有连接,但不能替已释放的本租约重放调用。
+            retryAllowed: () =>
+              leased.get(request.serverName) === entry.key &&
+              entries.get(entry.key) === entry &&
+              callOptions?.retryAllowed?.() !== false,
+          });
+        const current = entry.adapter.appConnectionSnapshot?.(request.serverName);
+        // 同配置重新创建 adapter 时 generation 可从头计数,必须同时固定 pool entry 身份。
+        if (
+          !current ||
+          `${entry.connectionContext.mcpConnectionId}:${current.identity}` !==
+            callOptions.appConnection.identity ||
+          current.generation !== callOptions.appConnection.generation
+        )
+          throw new Error("MCP App connection changed");
+        return await entry.adapter.callTool(request, {
           ...callOptions,
-          signal: callerSignal(callOptions?.signal),
+          signal,
+          appConnection: current,
         });
       },
       async readResource(
@@ -496,6 +514,13 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
         if (!adapter.subscribeResource) {
           throw new Error(`MCP adapter does not support resources: ${request.serverName}`);
         }
+        // 先登记:订阅仍在进行时租约释放,也要退订这条等待中的登记。失败也不删除:
+        // 退订不存在的键不发请求,多登记无害;删除反而会漏掉同键并发订阅中成功的那次。
+        const keys = subscriptions.get(request.serverName) ?? new Set<string>();
+        subscriptions.set(
+          request.serverName,
+          keys.add(JSON.stringify([request.uri, request.subscriberKey])),
+        );
         await adapter.subscribeResource(request, {
           ...callOptions,
           signal: callerSignal(callOptions?.signal),
@@ -503,6 +528,9 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
       },
       async unsubscribeResource(request, callOptions) {
         const adapter = requireEntry(request.serverName).adapter;
+        subscriptions
+          .get(request.serverName)
+          ?.delete(JSON.stringify([request.uri, request.subscriberKey]));
         if (!adapter.unsubscribeResource) return;
         await adapter.unsubscribeResource(request, {
           ...callOptions,
@@ -510,6 +538,9 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
         });
       },
       async unsubscribeResourcesBySubscriber(prefix) {
+        for (const keys of subscriptions.values())
+          for (const item of keys)
+            if ((JSON.parse(item) as [string, string])[1].startsWith(prefix)) keys.delete(item);
         let released = 0;
         const seen = new Set<string>();
         for (const key of leased.values()) {
@@ -525,8 +556,10 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
       close(): Promise<void> {
         leaseClosed = true;
         leaseShutdown.abort(new Error("MCP session lease closed"));
+        for (const listener of leaseListeners) snapshotListeners.delete(listener);
+        leaseListeners.clear();
         leaseClose ??= Promise.allSettled(
-          [...leased.keys()].map((name) => release(name, true)),
+          [...leased.keys()].map((name) => release(name, false, true)),
         ).then((results) => {
           const errors = results.flatMap((result) =>
             result.status === "rejected" ? [result.reason] : [],
@@ -547,7 +580,7 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
         }
         const configuredNames = new Set(Object.keys(servers));
         for (const serverName of [...leased.keys()]) {
-          if (!configuredNames.has(serverName)) release(serverName);
+          if (!configuredNames.has(serverName)) release(serverName, true);
         }
         await Promise.all(
           Object.entries(servers).map(([serverName, config]) =>
@@ -581,12 +614,36 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
       async listTools(): Promise<McpToolDescriptor[]> {
         return (await snapshot()).tools;
       },
-      toolListRevision(): number {
-        let revision = 0;
-        for (const key of new Set(leased.values())) {
-          revision += entries.get(key)?.adapter.toolListRevision?.() ?? 0;
+      getToolSnapshot(): Record<string, McpServerToolSnapshot> {
+        const result: Record<string, McpServerToolSnapshot> = {};
+        for (const [serverName, key] of leased) {
+          const entry = entries.get(key);
+          if (!entry) continue;
+          const adapterSnapshot = entry.adapter.getToolSnapshot();
+          const current = adapterSnapshot[serverName];
+          if (current) {
+            // 版本号带连接 ID:同名 server 换成新的池化连接后,版本不会与旧连接撞号。
+            result[serverName] = current.toolsVersion
+              ? {
+                  ...current,
+                  toolsVersion: `${entry.connectionContext.mcpConnectionId}:${current.toolsVersion}`,
+                }
+              : current;
+          }
         }
-        return revision;
+        return result;
+      },
+      async waitForServer(
+        serverName: string,
+        waitOptions: McpWaitForServerOptions,
+      ): Promise<{ timedOut: boolean }> {
+        waitOptions.signal?.throwIfAborted();
+        const key = leased.get(serverName);
+        const entry = key ? entries.get(key) : undefined;
+        if (!entry) return { timedOut: false };
+        return (
+          (await entry.adapter.waitForServer?.(serverName, waitOptions)) ?? { timedOut: false }
+        );
       },
       async pingServer(serverName: string, pingOptions?: { timeoutMs?: number }): Promise<boolean> {
         const key = leased.get(serverName);
@@ -656,16 +713,5 @@ function connectionKey(input: {
           input.connectOptions.workspaceKey ?? "",
         ].join("\u0000")
       : input.leaseId;
-  return [input.serverName, scope, stableStringify(input.config)].join("\u0000");
-}
-
-function stableStringify(value: unknown): string {
-  if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
-  if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
-  const record = value as Record<string, unknown>;
-  return `{${Object.keys(record)
-    .toSorted()
-    .filter((key) => record[key] !== undefined)
-    .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
-    .join(",")}}`;
+  return [input.serverName, scope, mcpConfigKey(input.config)].join("\u0000");
 }

+ 42 - 13
apps/zcode-cli/packages/adapters/src/mcp/resource-subscriptions.ts

@@ -1,21 +1,50 @@
 /**
  * MCP 资源订阅登记表(纯内存,无 IO)。
- * 键 = (serverName, uri) → subscriberKey 集合;同一连接被多个 session 共享时只向 server 订阅一次,
- * 所以 add 只在 0 → 1 时告诉调用方"该向 server 订阅",remove 只在 1 → 0 时告诉调用方"该向 server 退订"。
+ * 键 = (serverName, uri) → subscriberKey 登记;同一连接被多个 session 共享时只向 server 订阅一次。
+ * 已成功的登记与每次调用的待确认申请分开计数,取消不能删除此前成功或其它在途调用的登记。
  * 向 server 的实际请求、重连重放与日志都在 adapter;这里只管计数与快照。
  */
+interface SubscriptionRegistration {
+  committed: boolean;
+  pending: number;
+}
+
 export class McpResourceSubscriptionRegistry {
-  private readonly byServer = new Map<string, Map<string, Set<string>>>();
+  private readonly byServer = new Map<string, Map<string, Map<string, SubscriptionRegistration>>>();
 
-  /** 登记一个订阅者;返回是否是该 (server, uri) 的第一个。 */
-  add(serverName: string, uri: string, subscriberKey: string): { first: boolean } {
-    const byUri = this.byServer.get(serverName) ?? new Map<string, Set<string>>();
+  /** 在等待连接前登记本次申请;完成回调只能结算自己,不能复活被明确删除的登记。 */
+  begin(
+    serverName: string,
+    uri: string,
+    subscriberKey: string,
+  ): {
+    commit: () => void;
+    release: () => boolean;
+  } {
+    const byUri =
+      this.byServer.get(serverName) ?? new Map<string, Map<string, SubscriptionRegistration>>();
     this.byServer.set(serverName, byUri);
-    const subscribers = byUri.get(uri) ?? new Set<string>();
-    const first = subscribers.size === 0;
-    subscribers.add(subscriberKey);
+    const subscribers = byUri.get(uri) ?? new Map<string, SubscriptionRegistration>();
+    const entry = subscribers.get(subscriberKey) ?? { committed: false, pending: 0 };
+    entry.pending++;
+    subscribers.set(subscriberKey, entry);
     byUri.set(uri, subscribers);
-    return { first };
+    let settled = false;
+    const finish = (committed: boolean): boolean => {
+      if (settled) return false;
+      settled = true;
+      if (subscribers.get(subscriberKey) !== entry) return false;
+      entry.pending--;
+      entry.committed ||= committed;
+      if (entry.committed || entry.pending > 0) return false;
+      return this.remove(serverName, uri, subscriberKey)?.last ?? false;
+    };
+    return {
+      commit: () => {
+        finish(true);
+      },
+      release: () => finish(false),
+    };
   }
 
   /** 撤销一个订阅者;未登记返回 null,否则返回它是不是最后一个(此时该 uri 已从表中移除)。 */
@@ -33,7 +62,7 @@ export class McpResourceSubscriptionRegistry {
     const released: Array<{ serverName: string; uri: string }> = [];
     for (const [serverName, byUri] of this.byServer) {
       for (const [uri, subscribers] of byUri) {
-        for (const key of [...subscribers]) {
+        for (const key of subscribers.keys()) {
           if (key.startsWith(subscriberKeyPrefix)) subscribers.delete(key);
         }
         if (subscribers.size === 0) {
@@ -47,14 +76,14 @@ export class McpResourceSubscriptionRegistry {
 
   /** 某 uri 的订阅者(通知 resources/updated 时附上)。 */
   subscribers(serverName: string, uri: string): string[] {
-    return [...(this.byServer.get(serverName)?.get(uri) ?? [])];
+    return [...(this.byServer.get(serverName)?.get(uri)?.keys() ?? [])];
   }
 
   /** 某 server 全部订阅者去重(通知 resources/list_changed 时附上)。 */
   allSubscribers(serverName: string): string[] {
     const out = new Set<string>();
     for (const keys of this.byServer.get(serverName)?.values() ?? []) {
-      for (const key of keys) out.add(key);
+      for (const key of keys.keys()) out.add(key);
     }
     return [...out];
   }

+ 22 - 22
apps/zcode-cli/packages/adapters/src/mcp/timeout.ts

@@ -35,35 +35,18 @@ export function waitWithinMcpDeadline<T>(
   timeoutMessage: string,
   signal?: AbortSignal,
 ): Promise<T> {
-  return withTimeout(
-    promise,
-    remainingMcpDeadlineMs(deadline, timeoutMessage),
-    timeoutMessage,
-    signal,
-  );
+  return withTimeout(promise, Math.max(0, deadline.expiresAt - Date.now()), timeoutMessage, signal);
 }
 
 export function withTimeout<T>(
   promise: Promise<T>,
-  timeoutMs: number,
+  timeoutMs: number | undefined,
   timeoutMessage: string,
   signal?: AbortSignal,
 ): Promise<T> {
   return new Promise((resolvePromise, rejectPromise) => {
-    if (signal?.aborted) {
-      rejectPromise(
-        signal.reason instanceof Error ? signal.reason : new Error("Operation aborted"),
-      );
-      return;
-    }
-
     let settled = false;
-    const timer = setTimeout(() => {
-      if (settled) return;
-      settled = true;
-      cleanup();
-      rejectPromise(new McpTimeoutError(timeoutMessage));
-    }, timeoutMs);
+    let timer: ReturnType<typeof setTimeout> | undefined;
 
     const cleanup = () => {
       clearTimeout(timer);
@@ -79,8 +62,7 @@ export function withTimeout<T>(
       );
     };
 
-    signal?.addEventListener("abort", abortHandler);
-
+    // 共享任务先接上结果处理;caller 已取消或预算耗尽也不能留下无人接管的 rejection。
     promise.then(
       (value) => {
         if (settled) return;
@@ -95,5 +77,23 @@ export function withTimeout<T>(
         rejectPromise(error);
       },
     );
+    if (signal?.aborted) {
+      abortHandler();
+      return;
+    }
+    const timeoutHandler = () => {
+      if (settled) return;
+      settled = true;
+      cleanup();
+      rejectPromise(new McpTimeoutError(timeoutMessage));
+    };
+    if (timeoutMs !== undefined) {
+      if (timeoutMs <= 0) {
+        timeoutHandler();
+        return;
+      }
+      timer = setTimeout(timeoutHandler, timeoutMs);
+    }
+    signal?.addEventListener("abort", abortHandler, { once: true });
   });
 }

+ 258 - 0
apps/zcode-cli/packages/adapters/src/mcp/tool-catalog-cache.ts

@@ -0,0 +1,258 @@
+import { createHash } from "node:crypto";
+import { isAbsolute, resolve } from "node:path";
+import { mcpConfigKey, resolveMcpToolVisibility } from "@zcode/contracts";
+import type {
+  McpServerToolSnapshot,
+  McpCatalogToolDescriptor,
+  McpStdioServerConfig,
+  McpToolCatalogLookupResult,
+  McpToolCatalogPort,
+  McpToolCatalogPublication,
+  McpToolCatalogScope,
+  McpToolDescriptor,
+} from "@zcode/contracts";
+
+const DEFAULT_CAPACITY = 32;
+const DEFAULT_MAX_ENTRY_BYTES = 2 * 1024 * 1024;
+const DEFAULT_MAX_TOTAL_BYTES = 16 * 1024 * 1024;
+const DEFAULT_TTL_MS = 30 * 60 * 1_000;
+
+interface CatalogEntry {
+  bytes: number;
+  publishedAt: number;
+  tools: McpCatalogToolDescriptor[];
+}
+
+export interface InMemoryMcpToolCatalogOptions {
+  capacity?: number;
+  maxEntryBytes?: number;
+  maxTotalBytes?: number;
+  now?: () => number;
+  platform?: NodeJS.Platform | string;
+  ttlMs?: number;
+  env?: Record<string, string | undefined>;
+}
+
+export function createInMemoryMcpToolCatalog(
+  options: InMemoryMcpToolCatalogOptions = {},
+): McpToolCatalogPort {
+  const capacity = options.capacity ?? DEFAULT_CAPACITY;
+  const maxEntryBytes = options.maxEntryBytes ?? DEFAULT_MAX_ENTRY_BYTES;
+  const maxTotalBytes = options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES;
+  const now = options.now ?? Date.now;
+  const platform = options.platform ?? process.platform;
+  const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
+  const entries = new Map<string, CatalogEntry>();
+  let totalBytes = 0;
+
+  const remove = (key: string): void => {
+    const existing = entries.get(key);
+    if (!existing) return;
+    totalBytes -= existing.bytes;
+    entries.delete(key);
+  };
+
+  const lookup = (servers: readonly PreparedServer[]): McpToolCatalogLookupResult => {
+    const byServer: Record<string, McpCatalogToolDescriptor[]> = {};
+    let complete = true;
+    for (const server of servers) {
+      const key = server.cacheKey;
+      const entry = key ? entries.get(key) : undefined;
+      if (!key || !entry) {
+        complete = false;
+        continue;
+      }
+      if (now() - entry.publishedAt > ttlMs) {
+        remove(key);
+        complete = false;
+        continue;
+      }
+      // Map 的 insertion order 就是 LRU 顺序;读取只更新 recency,不延长 publishedAt TTL。
+      entries.delete(key);
+      entries.set(key, entry);
+      byServer[server.name] = cloneTools(entry.tools);
+    }
+    return { byServer, status: complete ? "complete" : "incomplete" };
+  };
+
+  const publish = (
+    servers: readonly PreparedServer[],
+    invalidated: ReadonlySet<string>,
+    snapshot: Readonly<Record<string, McpServerToolSnapshot>>,
+    published: Map<string, string>,
+  ): void => {
+    for (const server of servers) {
+      const key = server.cacheKey;
+      if (!key || invalidated.has(key)) continue;
+      const row = snapshot[server.name];
+      if (!row) continue;
+      const status = row.status;
+      if (
+        status.status === "connecting" ||
+        (status.status === "connected" && row.toolsVersion === undefined)
+      )
+        continue;
+      const version = JSON.stringify([status.status, row.toolsVersion]);
+      if (published.get(server.name) === version) continue;
+      published.set(server.name, version);
+      if (status && ["failed", "disabled", "disconnected", "untrusted"].includes(status.status)) {
+        remove(key);
+        continue;
+      }
+      if (status?.status !== "connected") continue;
+
+      const tools = sanitizeTools(row.tools ?? []);
+      const bytes = Buffer.byteLength(JSON.stringify(tools), "utf8");
+      if (bytes > maxEntryBytes || bytes > maxTotalBytes) {
+        remove(key);
+        continue;
+      }
+
+      remove(key);
+      entries.set(key, { bytes, publishedAt: now(), tools });
+      totalBytes += bytes;
+      while (entries.size > capacity || totalBytes > maxTotalBytes) {
+        const oldest = entries.keys().next().value;
+        if (typeof oldest !== "string") break;
+        remove(oldest);
+      }
+    }
+  };
+
+  return {
+    prepare(scope: McpToolCatalogScope): McpToolCatalogPublication {
+      const servers = prepareServers(scope, platform, options.env ?? process.env);
+      const result = lookup(servers);
+      // 读取者不参与生产者任期;只有所有者撤销该 publication 才拒绝后续写入。
+      const invalidated = new Set<string>();
+      const published = new Map<string, string>();
+      return {
+        lookup: result,
+        publish: (snapshot) => {
+          for (const [name, { status }] of Object.entries(snapshot)) {
+            if (["failed", "disabled", "disconnected", "untrusted"].includes(status.status))
+              delete result.byServer[name];
+          }
+          publish(servers, invalidated, snapshot, published);
+        },
+        invalidate: (names) => {
+          for (const server of servers) {
+            const key = server.cacheKey;
+            if (!key || (names && !names.includes(server.name))) continue;
+            remove(key);
+            invalidated.add(key);
+            delete result.byServer[server.name];
+          }
+        },
+      };
+    },
+  };
+}
+
+interface PreparedServer {
+  cacheKey?: string;
+  name: string;
+}
+
+function prepareServers(
+  scope: McpToolCatalogScope,
+  platform: NodeJS.Platform | string,
+  executionEnv: Record<string, string | undefined>,
+): PreparedServer[] {
+  return Object.entries(scope.servers)
+    .filter(([, config]) => config.enabled !== false)
+    .sort(([left], [right]) => left.localeCompare(right))
+    .map(([name, config]) => ({
+      cacheKey:
+        config.type === "stdio"
+          ? createStdioCacheKey(name, config, scope, platform, executionEnv)
+          : undefined,
+      name,
+    }));
+}
+
+function createStdioCacheKey(
+  serverName: string,
+  config: McpStdioServerConfig,
+  scope: McpToolCatalogScope,
+  platform: NodeJS.Platform | string,
+  executionEnv: Record<string, string | undefined>,
+): string {
+  const workingDirectory = scope.workingDirectory?.trim() || process.cwd();
+  const serverCwd = config.cwd ? resolve(workingDirectory, config.cwd) : workingDirectory;
+  const workspaceKey = scope.workspaceIdentity?.trim() || workingDirectory;
+  const command = normalizeCommand(config.command, serverCwd);
+  const env = normalizeEnv(
+    Object.fromEntries(
+      Object.entries({ ...executionEnv, ...config.env }).filter(
+        (entry): entry is [string, string] => entry[1] !== undefined,
+      ),
+    ),
+    platform,
+  );
+  return createHash("sha256")
+    .update(
+      mcpConfigKey({
+        config,
+        args: config.args ?? [],
+        clientCapabilities: "zcode-mcp-v1",
+        command,
+        cwd: serverCwd,
+        env,
+        isolation: config.isolation ?? "session",
+        protocolVersion: config.protocolVersion ?? "auto",
+        serverName,
+        timeoutMs: config.timeoutMs,
+        workspaceKey,
+      }),
+    )
+    .digest("hex");
+}
+
+function normalizeCommand(command: string, cwd: string): string {
+  return isAbsolute(command) || command.includes("/") || command.includes("\\")
+    ? resolve(cwd, command)
+    : command;
+}
+
+function normalizeEnv(
+  env: McpStdioServerConfig["env"],
+  platform: NodeJS.Platform | string,
+): Array<[string, string]> {
+  return Object.entries(env ?? {})
+    .map(
+      ([key, value]) => [platform === "win32" ? key.toUpperCase() : key, value] as [string, string],
+    )
+    .sort(([left], [right]) => left.localeCompare(right));
+}
+
+function sanitizeTools(descriptors: readonly McpToolDescriptor[]): McpCatalogToolDescriptor[] {
+  return descriptors.map((descriptor) => ({
+    serverName: descriptor.serverName,
+    toolName: descriptor.toolName,
+    ...(descriptor.name ? { name: descriptor.name } : {}),
+    ...(descriptor.description ? { description: descriptor.description } : {}),
+    inputSchema: cloneJson(descriptor.inputSchema),
+    ...(descriptor.outputSchema ? { outputSchema: cloneJson(descriptor.outputSchema) } : {}),
+    // 显式 false 也要保留,命中缓存时不能退回 server 级 alwaysLoad 默认值。
+    ...(typeof descriptor.alwaysLoad === "boolean" ? { alwaysLoad: descriptor.alwaysLoad } : {}),
+    ...(descriptor.searchHint ? { searchHint: descriptor.searchHint } : {}),
+    // 缓存不保留 ui;只声明 ui.visibility 的工具要按同一规则落到 visibility,避免变成默认 model+app。
+    ...(descriptor.visibility || descriptor.ui?.visibility
+      ? { visibility: [...resolveMcpToolVisibility(descriptor)] }
+      : {}),
+  }));
+}
+
+function cloneTools(tools: readonly McpCatalogToolDescriptor[]): McpCatalogToolDescriptor[] {
+  return tools.map((tool) => ({
+    ...tool,
+    inputSchema: cloneJson(tool.inputSchema),
+    ...(tool.outputSchema ? { outputSchema: cloneJson(tool.outputSchema) } : {}),
+    ...(tool.visibility ? { visibility: [...tool.visibility] } : {}),
+  }));
+}
+
+function cloneJson<T>(value: T): T {
+  return JSON.parse(JSON.stringify(value)) as T;
+}

+ 119 - 0
apps/zcode-cli/packages/adapters/src/mcp/transport-errors.ts

@@ -0,0 +1,119 @@
+import { ProtocolError, SdkError, SdkErrorCode, SdkHttpError } from "@modelcontextprotocol/client";
+import type { McpServerConfig } from "@zcode/contracts";
+import { getErrorCode, isNetworkFailure } from "../model/failure-inspection.js";
+
+/** 连续多少次网络层失败视为服务端不可达;任何 HTTP 响应都会清零。 */
+export const MCP_TERMINAL_NETWORK_FAILURE_LIMIT = 3;
+
+const HTTP_NOT_FOUND = 404;
+const HTTP_BAD_REQUEST = 400;
+const JSON_RPC_CONNECTION_CLOSED_CODE = -32000;
+/**
+ * 服务端只用正文表达"会话不存在"(400)。这里是"不用错误文本做流程判断"规则的例外:
+ * 没有结构化字段可用,匹配范围限定为会话失效的三种已知写法。
+ */
+const SESSION_EXPIRED_BODY =
+  /Server not initialized|No valid session ID|Mcp-Session-Id header is required/i;
+const CONNECTION_CLOSED_MESSAGE = /Connection closed/i;
+
+export type McpTransportErrorKind = "session_expired" | "stream_open_failed" | "other";
+
+/**
+ * onerror 分类:会话过期要重建连接;GET 打开事件流失败只说明 server 不提供推送流
+ * (常见于只实现 POST 的有状态 server 返回 404/405),连接本身仍可用。
+ */
+export function classifyTransportError(
+  error: unknown,
+  input: { sessionId: string | undefined },
+): McpTransportErrorKind {
+  if (!(error instanceof SdkHttpError)) return "other";
+  if (error.code === SdkErrorCode.ClientHttpFailedToOpenStream) return "stream_open_failed";
+  return isSessionExpiredHttpError(error, input.sessionId !== undefined)
+    ? "session_expired"
+    : "other";
+}
+
+/**
+ * 工具调用是否可以在重连后重试一次(只用于 Streamable HTTP):
+ * - 会话过期:调用开始时已有 session ID 的 POST 404,或 400 正文表示会话不存在;
+ * - 连接关闭:本地 ConnectionClosed,或 JSON-RPC -32000 且消息为连接关闭。
+ * 服务端 JSON-RPC 错误(包括 `-32000 Not connected`)、响应丢失、HTTP 500 与超时都不重试。
+ */
+export function isRetryableCallError(
+  error: unknown,
+  input: { type: McpServerConfig["type"]; hadSessionId: boolean },
+): boolean {
+  if (input.type !== "http") return false;
+  if (error instanceof SdkHttpError) return isSessionExpiredHttpError(error, input.hadSessionId);
+  if (error instanceof SdkError) return error.code === SdkErrorCode.ConnectionClosed;
+  // 部分 server / 代理把连接关闭转成 JSON-RPC -32000,与本地连接关闭同样处理。
+  // 这是"不用错误文本做流程判断"规则的例外:-32000 是通用服务端错误码,只有消息文本能区分连接关闭。
+  return (
+    error instanceof ProtocolError &&
+    error.code === JSON_RPC_CONNECTION_CLOSED_CODE &&
+    CONNECTION_CLOSED_MESSAGE.test(error.message)
+  );
+}
+
+function isSessionExpiredHttpError(error: SdkHttpError, hadSessionId: boolean): boolean {
+  if (error.code !== SdkErrorCode.ClientHttpNotImplemented) return false;
+  if (error.status === HTTP_NOT_FOUND) return hadSessionId;
+  const text = (error.data as { text?: unknown } | undefined)?.text;
+  return (
+    error.status === HTTP_BAD_REQUEST && typeof text === "string" && SESSION_EXPIRED_BODY.test(text)
+  );
+}
+
+/**
+ * 统计 fetch 层的网络失败:请求失败或事件流体出错都计一次,任何 HTTP 响应清零。
+ * HTTP/SSE server 停掉时 SDK 不派发 onclose,只能由这里发现。主动关闭产生的 abort 不计数。
+ */
+export function countNetworkFailures(
+  send: typeof globalThis.fetch,
+  onExhausted: () => void,
+): typeof globalThis.fetch {
+  let failures = 0;
+  const fail = (error: unknown) => {
+    if (!isNetworkFailure(getErrorCode(error))) return;
+    if (++failures < MCP_TERMINAL_NETWORK_FAILURE_LIMIT) return;
+    failures = 0;
+    onExhausted();
+  };
+  return (async (input, init) => {
+    let response: Response;
+    try {
+      response = await send(input, init);
+    } catch (error) {
+      fail(error);
+      throw error;
+    }
+    failures = 0;
+    if (!response.body || !response.headers.get("content-type")?.includes("text/event-stream"))
+      return response;
+    return new Response(observeStreamErrors(response.body, fail), {
+      headers: response.headers,
+      status: response.status,
+      statusText: response.statusText,
+    });
+  }) as typeof globalThis.fetch;
+}
+
+function observeStreamErrors(
+  body: ReadableStream<Uint8Array>,
+  onError: (error: unknown) => void,
+): ReadableStream<Uint8Array> {
+  const reader = body.getReader();
+  return new ReadableStream<Uint8Array>({
+    async pull(controller) {
+      try {
+        const { done, value } = await reader.read();
+        if (done) controller.close();
+        else controller.enqueue(value);
+      } catch (error) {
+        onError(error);
+        controller.error(error);
+      }
+    },
+    cancel: (reason) => reader.cancel(reason),
+  });
+}

+ 7 - 1
apps/zcode-cli/packages/adapters/src/memory-diagnostics/CONTRACT.md

@@ -1,4 +1,4 @@
-# CLI 内存诊断
+# CLI 内存诊断与崩溃证据
 
 app-server 就绪后调用 startCliMemoryDiagnostics,退出时调用 stop。
 本模块独占 inspector 和诊断文件;只读取调用方提供的计数器,不持有会话或正文。
@@ -7,5 +7,11 @@ app-server 就绪后调用 startCliMemoryDiagnostics,退出时调用 stop。
 采样与落盘单次在途,忙时丢样本。分配窗口、节点数、投影栈与文件大小都有上限。
 跨进程只通过既有目录锁维护一份文件预算;锁竞争不排队,失败不传播到任务。
 反馈归档按 shared 的 sanitizeCliMemoryDiagnostic 契约重新做安全投影。
+同步工作耗时在 adapter 操作边界测量,异步恢复前的业务调度时间不计入预算。
+首次降级原因、时间和耗时随有界记录保留;旧格式兼容,不添加退出取样或刷盘屏障。
+
+Host stderr 证据与反馈归档由本模块共同维护:`createAgentStderrTail` 只保留脱敏后的有界文本,
+连续栈不能挤掉 fatal 头;`AgentStderrCollector` 的流监听和 drain 契约保持不变。
+不接管 ProcessManager 的退出、重启、进程树清理或任务状态。
 
 完整参数和验收见 docs/monitoring/memory-diagnostics-log.md。

+ 18 - 7
apps/zcode-cli/packages/adapters/src/memory-diagnostics/index.ts

@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
 import { createReadStream } from "node:fs";
 import { realpath, stat } from "node:fs/promises";
 import { Session } from "node:inspector";
+import { performance } from "node:perf_hooks";
 import { homedir } from "node:os";
 import { join, resolve } from "node:path";
 import { getHeapStatistics } from "node:v8";
@@ -22,10 +23,16 @@ const MAX_HASH_BYTES = 128 * 1024 * 1024;
 const SAMPLING_STACK_DEPTH = 16;
 function createProfiler(): AllocationProfiler {
   const session = new Session();
-  const post = <T>(method: string, params: Record<string, unknown> = {}): Promise<T> =>
-    new Promise((res, rej) =>
+  const post = <T>(method: string, params: Record<string, unknown> = {}) => {
+    // 原先跨 await 计时,会把后续业务工作算进 25ms 预算,首次采样前就永久停采。
+    // 同线程 Inspector 的同步工作在调用边界计时,结果恢复的调度等待不属于采样成本。
+    const began = performance.now();
+    const result = new Promise<T>((res, rej) =>
       session.post(method, params, (error, result) => (error ? rej(error) : res(result as T))),
     );
+    const durationMs = performance.now() - began;
+    return result.then((value) => ({ value, durationMs }));
+  };
   const start = () =>
     post<void>("HeapProfiler.startSampling", {
       samplingInterval: MEMORY_SAMPLE_INTERVAL_BYTES,
@@ -35,17 +42,21 @@ function createProfiler(): AllocationProfiler {
     });
   return {
     async start() {
+      const began = performance.now();
       session.connect();
-      await start();
+      const connectMs = performance.now() - began;
+      return connectMs + (await start()).durationMs;
     },
     async read() {
-      return (await post<{ profile: { head: AllocationNode } }>("HeapProfiler.getSamplingProfile"))
-        .profile;
+      const { value, durationMs } = await post<{ profile: { head: AllocationNode } }>(
+        "HeapProfiler.getSamplingProfile",
+      );
+      return { head: value.profile.head, durationMs };
     },
     async reset() {
       // disable 清除采样状态,不使用 stopSampling 再复制一次完整 profile。
-      await post("HeapProfiler.disable");
-      await start();
+      const disabled = await post("HeapProfiler.disable");
+      return disabled.durationMs + (await start()).durationMs;
     },
     dispose() {
       session.disconnect();

+ 1 - 1
apps/zcode-cli/packages/adapters/src/memory-diagnostics/module.ts

@@ -4,7 +4,7 @@
  */
 export const cliMemoryDiagnosticsModule = {
   id: "cli-memory-diagnostics",
-  requires: ["shared", "zcode-cli"],
+  requires: ["shared", "zcode-cli", "agent-crash-diagnostic"],
   provides: ["cli-memory-diagnostics"],
   publicEntrypoints: ["index.ts", "contract.ts"],
 } as const;

Некоторые файлы не были показаны из-за большого количества измененных файлов