Ver código fonte

chore: sync ZCode source v3.18.0

Source-Commit: cc1f87e46ee496845be243b475bb116c35d952f6
Source-Sync: zcode-open-source-v1
ZCode Source Sync Bot 1 semana atrás
pai
commit
b95ebaffea
100 arquivos alterados com 7159 adições e 1832 exclusões
  1. 1 0
      .agents/skills/ai-elements/SKILL.md
  2. 14 12
      .agents/skills/e2e-case-lifecycle/SKILL.md
  3. 0 243
      .agents/skills/electron/SKILL.md
  4. 84 11
      .agents/skills/feature-boundary-planner/references/zcode-feature-graph.yaml
  5. 1 0
      .agents/skills/react-best-practices/SKILL.md
  6. 2 2
      .agents/skills/zcode-large-task-fixture/scripts/generate-large-task-fixture.mjs
  7. 86 0
      .agents/skills/zcode-large-task-fixture/scripts/generate-large-task-fixture.test.mjs
  8. 6 0
      .gitattributes
  9. 1 0
      .oxfmtrc.json
  10. 112 0
      .oxlintrc.json
  11. 1 0
      AGENTS.md
  12. 4 0
      CONTEXT.md
  13. 51 32
      DESIGN.md
  14. 3 1
      README.en.md
  15. 3 1
      README.md
  16. 35 1
      THIRD-PARTY-NOTICES.md
  17. 11 16
      apps/zcode-cli/docs/bash-shell-provider.md
  18. 83 0
      apps/zcode-cli/docs/design/design-builtin-plugin.md
  19. 60 23
      apps/zcode-cli/docs/design/v2/auth-login.md
  20. 6 0
      apps/zcode-cli/docs/design/v2/compact/plan.md
  21. 120 0
      apps/zcode-cli/docs/design/v2/conversation-input-source.md
  22. 1 1
      apps/zcode-cli/docs/design/v2/debug-observability.md
  23. 79 12
      apps/zcode-cli/docs/design/v2/hooks.md
  24. 1 1
      apps/zcode-cli/docs/design/v2/ink-tui-renderer.md
  25. 250 26
      apps/zcode-cli/docs/design/v2/loop/meta-user-context.md
  26. 1 1
      apps/zcode-cli/docs/design/v2/loop/model-anomaly-fallbacks.md
  27. 99 0
      apps/zcode-cli/docs/design/v2/loop/prompt-snapshot.md
  28. 17 4
      apps/zcode-cli/docs/design/v2/loop/system-prompt-contract.md
  29. 1 1
      apps/zcode-cli/docs/design/v2/loop/turn-steering.md
  30. 20 13
      apps/zcode-cli/docs/design/v2/memory/README.md
  31. 42 0
      apps/zcode-cli/docs/design/v2/model/README.md
  32. 183 34
      apps/zcode-cli/docs/design/v2/model/anthropic-reasoning-history-replay.md
  33. 49 7
      apps/zcode-cli/docs/design/v2/model/anthropic-stream-compat.md
  34. 388 0
      apps/zcode-cli/docs/design/v2/model/assistant-block-order.md
  35. 174 0
      apps/zcode-cli/docs/design/v2/model/context-composition.md
  36. 8 0
      apps/zcode-cli/docs/design/v2/model/http-proxy.md
  37. 53 2
      apps/zcode-cli/docs/design/v2/model/session-features-header.md
  38. 23 11
      apps/zcode-cli/docs/design/v2/model/streaming-tool-execution-and-recovery.md
  39. 3 1
      apps/zcode-cli/docs/design/v2/official-command-endpoint.md
  40. 3 3
      apps/zcode-cli/docs/design/v2/permission-broker.md
  41. 357 3
      apps/zcode-cli/docs/design/v2/plugin-compat.md
  42. 11 1
      apps/zcode-cli/docs/design/v2/rewind-compact.md
  43. 9 12
      apps/zcode-cli/docs/design/v2/sea-cross-target-packaging.md
  44. 7 0
      apps/zcode-cli/docs/design/v2/session-event-store-retention.md
  45. 63 8
      apps/zcode-cli/docs/design/v2/session-persistence.md
  46. 323 19
      apps/zcode-cli/docs/design/v2/tool/00-tool-change-chain.md
  47. 27 0
      apps/zcode-cli/docs/design/v2/tool/04-bash.md
  48. 1 1
      apps/zcode-cli/docs/design/v2/tool/05-webfetch.md
  49. 15 12
      apps/zcode-cli/docs/design/v2/tool/07-subagent-background-plan.md
  50. 219 79
      apps/zcode-cli/docs/design/v2/tool/07-subagent.md
  51. 14 0
      apps/zcode-cli/docs/design/v2/tool/13-websearch.md
  52. 6 2
      apps/zcode-cli/docs/design/v2/tool/17-read-file-state-resume.md
  53. 32 12
      apps/zcode-cli/docs/design/v2/tool/19-tool-search.md
  54. 23 13
      apps/zcode-cli/docs/design/v2/usage-observability.md
  55. 1 0
      apps/zcode-cli/docs/design/v2/zcode-protocol-agent-server.md
  56. 1 0
      apps/zcode-cli/packages/adapters/package.json
  57. 12 1
      apps/zcode-cli/packages/adapters/src/auth/coding-plan-api-key.ts
  58. 9 95
      apps/zcode-cli/packages/adapters/src/auth/credential-cipher.ts
  59. 218 98
      apps/zcode-cli/packages/adapters/src/auth/shared-credentials.ts
  60. 225 16
      apps/zcode-cli/packages/adapters/src/config/config-factory.ts
  61. 195 119
      apps/zcode-cli/packages/adapters/src/config/file-config.adapter.ts
  62. 23 0
      apps/zcode-cli/packages/adapters/src/config/index.ts
  63. 229 0
      apps/zcode-cli/packages/adapters/src/config/plugin-secrets.adapter.ts
  64. 2 5
      apps/zcode-cli/packages/adapters/src/config/project-config.adapter.ts
  65. 28 4
      apps/zcode-cli/packages/adapters/src/context/index.ts
  66. 4 1
      apps/zcode-cli/packages/adapters/src/http/index.ts
  67. 21 2
      apps/zcode-cli/packages/adapters/src/mcp/index.ts
  68. 2 0
      apps/zcode-cli/packages/adapters/src/mcp/official-auth.ts
  69. 9 1
      apps/zcode-cli/packages/adapters/src/mcp/pool.ts
  70. 16 6
      apps/zcode-cli/packages/adapters/src/model/provider-builtin-tool-compat/CONTRACT.md
  71. 144 18
      apps/zcode-cli/packages/adapters/src/model/provider-builtin-tool-compat/compat.ts
  72. 196 103
      apps/zcode-cli/packages/adapters/src/model/reasoning-history-normalization.ts
  73. 14 1
      apps/zcode-cli/packages/adapters/src/model/runner-generate.ts
  74. 50 0
      apps/zcode-cli/packages/adapters/src/model/runner-normalization.ts
  75. 18 5
      apps/zcode-cli/packages/adapters/src/model/runner-stream.ts
  76. 2 0
      apps/zcode-cli/packages/adapters/src/model/tool-search.ts
  77. 50 11
      apps/zcode-cli/packages/adapters/src/model/transform.ts
  78. 15 11
      apps/zcode-cli/packages/adapters/src/network/proxy-fetch.ts
  79. 96 19
      apps/zcode-cli/packages/adapters/src/plugins/atomic-directory.ts
  80. 400 18
      apps/zcode-cli/packages/adapters/src/plugins/helpers.ts
  81. 48 20
      apps/zcode-cli/packages/adapters/src/plugins/hook-sources.ts
  82. 190 313
      apps/zcode-cli/packages/adapters/src/plugins/index.ts
  83. 65 9
      apps/zcode-cli/packages/adapters/src/plugins/markdown-frontmatter.ts
  84. 88 55
      apps/zcode-cli/packages/adapters/src/plugins/marketplace.ts
  85. 29 15
      apps/zcode-cli/packages/adapters/src/plugins/mcp.ts
  86. 45 41
      apps/zcode-cli/packages/adapters/src/plugins/official-marketplace.ts
  87. 283 42
      apps/zcode-cli/packages/adapters/src/plugins/plugin-components.ts
  88. 2 0
      apps/zcode-cli/packages/adapters/src/plugins/types.ts
  89. 34 10
      apps/zcode-cli/packages/adapters/src/plugins/zip-source.ts
  90. 2 1
      apps/zcode-cli/packages/adapters/src/skills/index.ts
  91. 30 62
      apps/zcode-cli/packages/adapters/src/skills/scan.ts
  92. 8 1
      apps/zcode-cli/packages/adapters/src/storage/session-data-files/contract.ts
  93. 75 5
      apps/zcode-cli/packages/adapters/src/storage/session-data-files/index.ts
  94. 117 0
      apps/zcode-cli/packages/adapters/src/storage/session-store/migrations.ts
  95. 255 15
      apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/messages.ts
  96. 4 1
      apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/permission-full-access.ts
  97. 208 1
      apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/sessions.ts
  98. 1 23
      apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/usage.ts
  99. 359 0
      apps/zcode-cli/packages/adapters/src/storage/session-store/schema.baseline.sql
  100. 150 63
      apps/zcode-cli/packages/adapters/src/storage/session-store/sqlite-session-store.ts

+ 1 - 0
.agents/skills/ai-elements/SKILL.md

@@ -1,6 +1,7 @@
 ---
 name: ai-elements
 description: Build AI chat interfaces using ai-elements components — conversations, messages, tool displays, prompt inputs, and more. Use when the user wants to build a chatbot, AI assistant UI, or any AI-powered chat interface.
+disable-model-invocation: true
 ---
 
 <!--

+ 14 - 12
.agents/skills/e2e-case-lifecycle/SKILL.md

@@ -8,6 +8,8 @@ disable-model-invocation: true
 
 Use this skill for the z-code E2E lifecycle: manual-review automation, capture/replay evidence, formal fixture promotion, Docker admission, and CI. It is intentionally domain-neutral: use it for conversation flows, SSH, provider settings, UI workflows, filesystem behavior, remote runtimes, auth/config, and similar product surfaces. Work from the z-code repo root.
 
+目录分类遵循 `docs/testing/e2e-business-scenarios.md`。转正保留业务场景目录,只移除 `manual-review/pending`;fixture 仍按 caseName 索引。
+
 ## Required Reading
 
 Before writing or moving an E2E spec, read the relevant sections of the domain's case catalog, coverage matrix, and workflow docs. For conversation-session work, the default sources are:
@@ -39,14 +41,14 @@ A matrix row may say `covered` only when it cites the artifact of a run in which
 
 For a new candidate case:
 
-1. Put the spec under the domain's `manual-review/pending/` directory. For conversation-session this is `packages/desktop/test/e2e/conversation-session/manual-review/pending/`.
+1. Put the spec under the domain's `manual-review/pending/` directory. For conversation-session this is `packages/desktop/test/e2e/conversation-session/<scenario>/manual-review/pending/`.
 2. Use stable `E2E_*` markers in user prompts and provider matchers.
 3. Prefer existing helpers in `packages/desktop/test/e2e/helpers/`.
 4. Use `buildReadonlyToolPrompt(...)` for high/medium priority completed-history setup unless timing makes tool history counterproductive.
 5. Run manual/capture with:
 
 ```bash
-ZCODE_E2E_MANUAL_REVIEW=1 pnpm --filter @zcode/desktop test:e2e -- --spec './test/e2e/conversation-session/manual-review/pending/<case>.test.ts'
+ZCODE_E2E_MANUAL_REVIEW=1 pnpm --filter @zcode/desktop test:e2e -- --spec './test/e2e/conversation-session/<scenario>/manual-review/pending/<case>.test.ts'
 ```
 
 Manual/capture artifacts are review evidence, not the final test contract.
@@ -54,7 +56,7 @@ Manual/capture artifacts are review evidence, not the final test contract.
 When a feedback reproduction run needs a video artifact, record the Electron
 window from inside the app instead of using OS screen recording. Import
 `startElectronWindowRecording` and `ELECTRON_WINDOW_RECORDING_CAPTURE_MODE` from
-`../../../helpers/electron-window-recorder.js` in conversation
+`#e2e/helpers/electron-window-recorder` in conversation
 `manual-review/pending/` specs, start recording before the user-visible path,
 stop it in `finally`, and write `video_capture_mode:
 ELECTRON_WINDOW_RECORDING_CAPTURE_MODE` to the feedback manifest. Do not use
@@ -66,13 +68,13 @@ the normal evidence path.
 After the user confirms human review, run the promotion dry run first:
 
 ```bash
-pnpm --filter @zcode/desktop e2e:promote -- --spec ./test/e2e/conversation-session/manual-review/pending/<case>.test.ts --reviewed
+pnpm --filter @zcode/desktop e2e:promote -- --spec ./test/e2e/conversation-session/<scenario>/manual-review/pending/<case>.test.ts --reviewed
 ```
 
 Then apply:
 
 ```bash
-pnpm --filter @zcode/desktop e2e:promote -- --spec ./test/e2e/conversation-session/manual-review/pending/<case>.test.ts --reviewed --apply
+pnpm --filter @zcode/desktop e2e:promote -- --spec ./test/e2e/conversation-session/<scenario>/manual-review/pending/<case>.test.ts --reviewed --apply
 ```
 
 The tool moves the spec, fixes common helper imports, creates fixture/manifest scaffolds, and updates the coverage matrix path. It does not decide request semantics.
@@ -111,43 +113,43 @@ After filling fixtures:
 For a pending case, validate the current spec against its canonical formal-target fixture metadata before promotion:
 
 ```bash
-pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ./test/e2e/conversation-session/manual-review/pending/<case>.test.ts
+pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ./test/e2e/conversation-session/<scenario>/manual-review/pending/<case>.test.ts
 ```
 
 The `spec` field in both the case manifest and case-local provider fixture remains
-`./test/e2e/conversation-session/<case>.test.ts` while the current spec is pending. It is the canonical formal target,
+`./test/e2e/conversation-session/<scenario>/<case>.test.ts` while the current spec is pending. It is the canonical formal target,
 not the current physical path. Pending replay remains explicit: pass `E2E_PROVIDER_REPLAY_FIXTURE_PATH` so a normal
 manual-review run still captures the live provider path.
 
 After promotion:
 
 ```bash
-pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ./test/e2e/conversation-session/<case>.test.ts
+pnpm --filter @zcode/desktop e2e:fixture:check -- --spec ./test/e2e/conversation-session/<scenario>/<case>.test.ts
 ```
 
 Prove the case does not depend on legacy shared fixtures:
 
 ```bash
 E2E_PROVIDER_REPLAY_FIXTURE_PATH=packages/desktop/test/e2e/fixtures/upstream/common.json,packages/desktop/test/e2e/fixtures/upstream/conversation-session/<case>.json \
-  pnpm --filter @zcode/desktop exec wdio run wdio.conf.ts --spec './test/e2e/conversation-session/<case>.test.ts'
+  pnpm --filter @zcode/desktop exec wdio run wdio.conf.ts --spec './test/e2e/conversation-session/<scenario>/<case>.test.ts'
 ```
 
 Then run default replay:
 
 ```bash
-pnpm --filter @zcode/desktop exec wdio run wdio.conf.ts --spec './test/e2e/conversation-session/<case>.test.ts'
+pnpm --filter @zcode/desktop exec wdio run wdio.conf.ts --spec './test/e2e/conversation-session/<scenario>/<case>.test.ts'
 ```
 
 Before adding the case to the Docker suite, prove the formal case in isolated replay:
 
 ```bash
-E2E_SPEC=./test/e2e/conversation-session/<case>.test.ts pnpm run test:e2e:container
+E2E_SPEC=./test/e2e/conversation-session/<scenario>/<case>.test.ts pnpm run test:e2e:container
 ```
 
 After that passes, admit it to the Docker conversation preset:
 
 ```bash
-pnpm --filter @zcode/desktop e2e:docker:admit -- --spec ./test/e2e/conversation-session/<case>.test.ts --verified --artifact packages/desktop/.e2e-artifacts/<run-id> --apply
+pnpm --filter @zcode/desktop e2e:docker:admit -- --spec ./test/e2e/conversation-session/<scenario>/<case>.test.ts --verified --artifact packages/desktop/.e2e-artifacts/<run-id> --apply
 pnpm run test:e2e:container:conversation
 ```
 

+ 0 - 243
.agents/skills/electron/SKILL.md

@@ -1,243 +0,0 @@
----
-name: electron
-description: Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include "automate Slack app", "control VS Code", "interact with Discord app", "test this Electron app", "connect to desktop app", or any task requiring automation of a native Electron application.
-allowed-tools: Bash(agent-browser:*), Bash(npx agent-browser:*)
----
-
-<!--
-Derived from vercel-labs/agent-browser (skills/electron/SKILL.md).
-Copyright 2025 Vercel Inc. Licensed under Apache-2.0.
-Modified by ZCode: local integration, formatting and adaptations.
-See THIRD-PARTY-NOTICES.md in the repository root for license and provenance.
--->
-
-# Electron App Automation
-
-Automate any Electron desktop app using agent-browser. Electron apps are built on Chromium and expose a Chrome DevTools Protocol (CDP) port that agent-browser can connect to, enabling the same snapshot-interact workflow used for web pages.
-
-## Core Workflow
-
-1. **Launch** the Electron app with remote debugging enabled
-2. **Connect** agent-browser to the CDP port
-3. **Snapshot** to discover interactive elements
-4. **Interact** using element refs
-5. **Re-snapshot** after navigation or state changes
-
-```bash
-# Launch an Electron app with remote debugging
-open -a "Slack" --args --remote-debugging-port=9222
-
-# Connect agent-browser to the app
-agent-browser connect 9222
-
-# Standard workflow from here
-agent-browser snapshot -i
-agent-browser click @e5
-agent-browser screenshot slack-desktop.png
-```
-
-## Launching Electron Apps with CDP
-
-Every Electron app supports the `--remote-debugging-port` flag since it's built into Chromium.
-
-### macOS
-
-```bash
-# Slack
-open -a "Slack" --args --remote-debugging-port=9222
-
-# VS Code
-open -a "Visual Studio Code" --args --remote-debugging-port=9223
-
-# Discord
-open -a "Discord" --args --remote-debugging-port=9224
-
-# Figma
-open -a "Figma" --args --remote-debugging-port=9225
-
-# Notion
-open -a "Notion" --args --remote-debugging-port=9226
-
-# Spotify
-open -a "Spotify" --args --remote-debugging-port=9227
-```
-
-### Linux
-
-```bash
-slack --remote-debugging-port=9222
-code --remote-debugging-port=9223
-discord --remote-debugging-port=9224
-```
-
-### Windows
-
-```bash
-"C:\Users\%USERNAME%\AppData\Local\slack\slack.exe" --remote-debugging-port=9222
-"C:\Users\%USERNAME%\AppData\Local\Programs\Microsoft VS Code\Code.exe" --remote-debugging-port=9223
-```
-
-**Important:** If the app is already running, quit it first, then relaunch with the flag. The `--remote-debugging-port` flag must be present at launch time.
-
-## Connecting
-
-```bash
-# Connect to a specific port
-agent-browser connect 9222
-
-# Or use --cdp on each command
-agent-browser --cdp 9222 snapshot -i
-
-# Auto-discover a running Chromium-based app
-agent-browser --auto-connect snapshot -i
-```
-
-After `connect`, all subsequent commands target the connected app without needing `--cdp`.
-
-## Tab Management
-
-Electron apps often have multiple windows or webviews. Use tab commands to list and switch between them:
-
-```bash
-# List all available targets (windows, webviews, etc.)
-agent-browser tab
-
-# Switch to a specific tab by index
-agent-browser tab 2
-
-# Switch by URL pattern
-agent-browser tab --url "*settings*"
-```
-
-## Webview Support
-
-Electron `<webview>` elements are automatically discovered and can be controlled like regular pages. Webviews appear as separate targets in the tab list with `type: "webview"`:
-
-```bash
-# Connect to running Electron app
-agent-browser connect 9222
-
-# List targets -- webviews appear alongside pages
-agent-browser tab
-# Example output:
-#   0: [page]    Slack - Main Window     https://app.slack.com/
-#   1: [webview] Embedded Content        https://example.com/widget
-
-# Switch to a webview
-agent-browser tab 1
-
-# Interact with the webview normally
-agent-browser snapshot -i
-agent-browser click @e3
-agent-browser screenshot webview.png
-```
-
-**Note:** Webview support works via raw CDP connection.
-
-## Common Patterns
-
-### Inspect and Navigate an App
-
-```bash
-open -a "Slack" --args --remote-debugging-port=9222
-sleep 3  # Wait for app to start
-agent-browser connect 9222
-agent-browser snapshot -i
-# Read the snapshot output to identify UI elements
-agent-browser click @e10  # Navigate to a section
-agent-browser snapshot -i  # Re-snapshot after navigation
-```
-
-### Take Screenshots of Desktop Apps
-
-```bash
-agent-browser connect 9222
-agent-browser screenshot app-state.png
-agent-browser screenshot --full full-app.png
-agent-browser screenshot --annotate annotated-app.png
-```
-
-### Extract Data from a Desktop App
-
-```bash
-agent-browser connect 9222
-agent-browser snapshot -i
-agent-browser get text @e5
-agent-browser snapshot --json > app-state.json
-```
-
-### Fill Forms in Desktop Apps
-
-```bash
-agent-browser connect 9222
-agent-browser snapshot -i
-agent-browser fill @e3 "search query"
-agent-browser press Enter
-agent-browser wait 1000
-agent-browser snapshot -i
-```
-
-### Run Multiple Apps Simultaneously
-
-Use named sessions to control multiple Electron apps at the same time:
-
-```bash
-# Connect to Slack
-agent-browser --session slack connect 9222
-
-# Connect to VS Code
-agent-browser --session vscode connect 9223
-
-# Interact with each independently
-agent-browser --session slack snapshot -i
-agent-browser --session vscode snapshot -i
-```
-
-## Color Scheme
-
-The default color scheme when connecting via CDP may be `light`. To preserve dark mode:
-
-```bash
-agent-browser connect 9222
-agent-browser --color-scheme dark snapshot -i
-```
-
-Or set it globally:
-
-```bash
-AGENT_BROWSER_COLOR_SCHEME=dark agent-browser connect 9222
-```
-
-## Troubleshooting
-
-### "Connection refused" or "Cannot connect"
-
-- Make sure the app was launched with `--remote-debugging-port=NNNN`
-- If the app was already running, quit and relaunch with the flag
-- Check that the port isn't in use by another process: `lsof -i :9222`
-
-### App launches but connect fails
-
-- Wait a few seconds after launch before connecting (`sleep 3`)
-- Some apps take time to initialize their webview
-
-### Elements not appearing in snapshot
-
-- The app may use multiple webviews. Use `agent-browser tab` to list targets and switch to the right one
-
-### Cannot type in input fields
-
-- Try `agent-browser keyboard type "text"` to type at the current focus without a selector
-- Some Electron apps use custom input components; use `agent-browser keyboard inserttext "text"` to bypass key events
-
-## Supported Apps
-
-Any app built on Electron works, including:
-
-- **Communication:** Slack, Discord, Microsoft Teams, Signal, Telegram Desktop
-- **Development:** VS Code, GitHub Desktop, Postman, Insomnia
-- **Design:** Figma, Notion, Obsidian
-- **Media:** Spotify, Tidal
-- **Productivity:** Todoist, Linear, 1Password
-
-If an app is built with Electron, it supports `--remote-debugging-port` and can be automated with agent-browser.

+ 84 - 11
.agents/skills/feature-boundary-planner/references/zcode-feature-graph.yaml

@@ -17,6 +17,22 @@ rules:
     - "evidence-only"
 
 nodes:
+  - id: "capability.archive-permanent-deletion"
+    kind: "capability"
+    label: "Permanent deletion of archived conversations"
+    aliases: ["永久删除归档会话", "归档真正删除", "archive permanent deletion"]
+    docs: ["docs/superpowers/specs/2026-09-11-archive-management.md"]
+    codeSeeds:
+      - file: "packages/ui/src/project-sidebar/useArchiveManagement.ts"
+        symbol: "useArchiveManagement"
+      - file: "apps/zcode-cli/packages/bootstrap/src/zcode-protocol/session-data/permanent-deletion.ts"
+        symbol: "executeSessionDeletionWith"
+      - file: "apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/sessions.ts"
+        symbol: "purgeSessions"
+    invariants:
+      - "Archive deletion performs physical session cleanup; retain independent forks and still-referenced artifacts, with itemized confirmation."
+      - "Reject running work; revalidate archive membership, identity and retained artifacts before destructive effects."
+      - "Published shares, workspace files and directory-level data stay independent; partial cleanup must not be reported as complete."
   - id: "capability.shared-task-cli"
     kind: "capability"
     label: "Local projectless workspaces share one chat CLI"
@@ -116,11 +132,11 @@ nodes:
     label: "ToolSearch Desktop, CLI/TUI E2E and Runtime HTTP integration"
     docs: ["docs/testing/conversation-session-e2e-coverage-matrix.md"]
     codeSeeds:
-      - file: "packages/desktop/test/e2e/conversation-session/conversation-session-toolsearch-lifecycle.test.ts"
-      - file: "packages/desktop/test/e2e/conversation-session/conversation-session-toolsearch-cli.test.ts"
-      - file: "packages/desktop/test/e2e/conversation-session/conversation-session-toolsearch-tui.test.ts"
-      - file: "packages/desktop/test/e2e/conversation-session/conversation-session-toolsearch-catalog.test.ts"
-      - file: "packages/desktop/test/e2e/conversation-session/conversation-session-tool-discovery-card.test.ts"
+      - file: "packages/desktop/test/e2e/conversation-session/tools/conversation-session-toolsearch-lifecycle.test.ts"
+      - file: "packages/desktop/test/e2e/conversation-session/tools/conversation-session-toolsearch-cli.test.ts"
+      - file: "packages/desktop/test/e2e/conversation-session/tools/conversation-session-toolsearch-tui.test.ts"
+      - file: "packages/desktop/test/e2e/conversation-session/tools/conversation-session-toolsearch-catalog.test.ts"
+      - file: "packages/desktop/test/e2e/conversation-session/tools/conversation-session-tool-discovery-card.test.ts"
 
   - id: "capability.preview-pane-image-actions"
     kind: "capability"
@@ -213,6 +229,20 @@ nodes:
         symbol: "V4InteractionDialogs"
       - file: "packages/ui/src/PermissionDialog.tsx"
         symbol: "PermissionDialog"
+  - id: "capability.agent-plugin-discovery"
+    kind: "capability"
+    label: "Agent discovers official plugins and requests explicit installation"
+    aliases: ["Agent 插件推荐", "SearchPlugins", "SuggestPluginInstall"]
+    docs: ["docs/plugins/agent-plugin-discovery.md"]
+    codeSeeds:
+      - file: "apps/zcode-cli/packages/bootstrap/src/zcode-protocol/plugin-discovery-port.ts"
+        symbol: "createProtocolPluginDiscoveryPort"
+      - file: "packages/ui/src/v4/PluginInstallCard.tsx"
+        symbol: "PluginInstallCard"
+    invariants:
+      - "Only visible zcode-plugins-official entries are discoverable; model input never supplies download locations."
+      - "CLI owns confirmation and installation; no automatic approval, even in yolo mode."
+      - "Installation does not refresh session capabilities; the activation port is a separate boundary."
   - id: "capability.plugin-market-ui"
     kind: "capability"
     label: "Plugin market publisher classification and UI entry points"
@@ -2696,8 +2726,8 @@ nodes:
         file: "packages/ui/src/v4/toolCallRowAdapter.ts"
       - symbol: "ProductProjection"
         file: "apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/product-projection.ts"
-      - symbol: "prepareCuaGroupFlowItems"
-        file: "packages/ui/src/v4/conversationCuaGroups.ts"
+      - symbol: "groupConsecutiveAssistantSummaries"
+        file: "packages/ui/src/v4/conversationAssistantWorkItems.ts"
 
   - id: "surface.ask-user-question-auto-resolution-setting"
     kind: "ui-surface"
@@ -4591,7 +4621,7 @@ nodes:
       - file: "apps/zcode-cli/packages/adapters/tests/mcp-process-lifecycle.test.ts"
       - file: "apps/zcode-cli/packages/adapters/tests/mcp-version-negotiation.test.ts"
       - file: "packages/desktop/test/upstreamReplayServer.test.ts"
-      - file: "packages/desktop/test/e2e/settings/mcp-dual-era-version-negotiation.test.ts"
+      - file: "packages/desktop/test/e2e/settings/mcp/mcp-dual-era-version-negotiation.test.ts"
       - file: "packages/desktop/test/e2e/conversation-session/manual-review/pending/conversation-session-browser-use-iab-multisession.test.ts"
 
   - id: "capability.window-single-host-controller-r1"
@@ -4663,8 +4693,8 @@ nodes:
       - "docs/conversation-session-case-catalog.md"
       - "docs/testing/conversation-session-e2e-coverage-matrix.md"
     codeSeeds:
-      - file: "packages/desktop/test/e2e/conversation-session/conversation-session-ssh-remote-p0.test.ts"
-      - file: "packages/desktop/test/e2e/conversation-session/manual-review/pending/conversation-session-ssh-remote-cancel-retry.test.ts"
+      - file: "packages/desktop/test/e2e/conversation-session/remote/connection/conversation-session-ssh-remote-p0.test.ts"
+      - file: "packages/desktop/test/e2e/conversation-session/remote/connection/manual-review/pending/conversation-session-ssh-remote-cancel-retry.test.ts"
 
   - id: "capability.unified-zcode-lite-server"
     kind: "capability"
@@ -4977,7 +5007,7 @@ nodes:
     kind: "evidence"
     label: "Responsive browser viewport interaction coverage"
     codeSeeds:
-      - file: "packages/desktop/test/e2e/browser-human-viewport-preference.test.ts"
+      - file: "packages/desktop/test/e2e/browser/design/browser-human-viewport-preference.test.ts"
 
   - id: "evidence.browser-use-agent-guidance-tests"
     kind: "evidence"
@@ -5564,7 +5594,34 @@ nodes:
       - symbol: "ConversationShareReadonlyTimeline"
         file: "packages/ui/src/v4/ConversationShareReadonlyTimeline.tsx"
 
+  - id: "capability.plugin-startup-budget"
+    kind: "capability"
+    label: "Plugin startup timeout without plugin capabilities"
+    aliases: ["插件启动预算", "无插件启动", "plugin startup degraded"]
+    docs: ["docs/workspace-capability-discovery-cache.md"]
+    codeSeeds:
+      - file: "apps/zcode-cli/packages/bootstrap/src/app/bundled-plugins.ts"
+        symbol: "createOfficialPluginPreparation"
+      - file: "packages/services/src/zcode-agent/zcodeAgentService.ts"
+        symbol: "onDynamicPluginStartupDegraded"
+      - file: "packages/ui/src/v4/composer/useDraftConfigControl.ts"
+        symbol: "useDraftConfigControl"
+    invariants:
+      - "The Agent process owns the shared budget and degraded latch; queries do not rescan or alter enablement after timeout."
+      - "Existing Runtime snapshots stay frozen; restart creates a new owner. Desktop and mobile subscribe to the same workspace-scoped notification."
+      - "An in-flight directory publication finishes or rolls back before releasing its lock; late results cannot restore capabilities."
+
 edges:
+  - from: "capability.archive-permanent-deletion"
+    to: "surface.archive-management"
+    type: "implemented-in"
+    rank: "must-inspect"
+    condition: "Single, group and filtered bulk deletion show delete/retain/blocked lists, then perform physical cleanup through the original owner."
+  - from: "capability.archive-permanent-deletion"
+    to: "service.project-task-mutation"
+    type: "requires-scoped-routing-through"
+    rank: "must-inspect"
+    condition: "Permanent deletion uses an explicit contract and existing CLI cleanup; ordinary deleteSession and project deletion semantics remain unchanged."
   - from: "capability.shared-task-cli"
     to: "capability.workspace-identity"
     type: "preserves"
@@ -5688,6 +5745,22 @@ edges:
     to: "boundary.plugin-agent-host"
     type: "resolves-skill-from-target"
     rank: "must-inspect"
+  - from: "capability.agent-plugin-discovery"
+    to: "service.plugin-catalog-detail"
+    type: "options-from"
+    rank: "must-inspect"
+  - from: "capability.agent-plugin-discovery"
+    to: "persistence.plugin-marketplace-installed-cache"
+    type: "persists-to"
+    rank: "must-inspect"
+  - from: "capability.agent-plugin-discovery"
+    to: "boundary.web-remote-replayable"
+    type: "recovers-via"
+    rank: "must-inspect"
+  - from: "capability.agent-plugin-discovery"
+    to: "state.plugin-reference-session-catalog"
+    type: "must-not-mutate"
+    rank: "invariant-only"
   - from: "capability.plugin-store-mode-order"
     to: "state.interface-mode"
     type: "selects-order-from"

+ 1 - 0
.agents/skills/react-best-practices/SKILL.md

@@ -5,6 +5,7 @@ license: MIT
 metadata:
   author: vercel
   version: "1.0.0"
+disable-model-invocation: true
 ---
 
 # Vercel React Best Practices

+ 2 - 2
.agents/skills/zcode-large-task-fixture/scripts/generate-large-task-fixture.mjs

@@ -103,7 +103,6 @@ function generateTask({ workspacePath, turnCount, title, backup }) {
       for (let i = 0; i < 60; i += 1) {
         insertTodo.run(sessionId, `Synthetic large task todo ${i}: validate ${["scroll", "search", "tool rendering", "permission", "diff", "mobile replayable"][i % 6]}`, i % 5 === 0 ? "completed" : i % 3 === 0 ? "in_progress" : "pending", ["high", "medium", "low"][i % 3], i, baseTime + i, now);
       }
-      insertEntry.run(`${sessionId}:bash_shell_selection`, sessionId, "runtime/bash_shell_selection", baseTime, now, json({ selection: { path: "/bin/zsh", display: { name: "zsh" } }, createdAt: baseTime }));
       insertEntry.run(`${sessionId}:fixture_note`, sessionId, "perf_fixture/manifest", baseTime, now, json({ sessionId, turnCount, generatedAt: now, workspacePath }));
       cli.prepare("insert into session_target (session_id, target_id, objective, summary_title, status, token_budget, tokens_used, time_used_seconds, time_created, time_updated) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(sessionId, `target_${sessionId}`, "Generate a very large synthetic task for UI and persistence performance testing.", title, "complete", 10000000, 52000000, 7200, baseTime, now);
     });
@@ -126,7 +125,8 @@ function generateTask({ workspacePath, turnCount, title, backup }) {
 }
 
 function insertSession(db, input) {
-  db.prepare(`insert into session (id, project_id, workspace_id, parent_id, trace_id, task_type, slug, directory, path, title, title_source, title_message_id, version, share_url, summary_additions, summary_deletions, summary_files, summary_diffs, revert, permission, time_created, time_updated, time_title_updated, time_compacting, time_archived) values (?, ?, ?, null, ?, 'interactive', ?, ?, ?, ?, 'custom', null, 'perf-fixture', null, ?, ?, ?, ?, null, ?, ?, ?, ?, null, null)`).run(input.sessionId, `perf-${input.workspaceHash}`, input.workspaceHash, input.traceId, slug(input.title), input.workspacePath, input.workspacePath, input.title, 42000, 17000, 1300, json([{ path: "synthetic/perf.ts", additions: 42000, deletions: 17000 }]), json({ defaultMode: "ask" }), input.baseTime, input.baseTime + input.turnCount * 1000, input.baseTime);
+  // 本地会话按目录归属;把目录哈希写成显式身份会使冷恢复报 session-lineage-invalid。
+  db.prepare(`insert into session (id, project_id, workspace_id, parent_id, trace_id, task_type, slug, directory, path, title, title_source, title_message_id, version, share_url, summary_additions, summary_deletions, summary_files, summary_diffs, revert, permission, time_created, time_updated, time_title_updated, time_compacting, time_archived) values (?, ?, ?, null, ?, 'interactive', ?, ?, ?, ?, 'custom', null, 'perf-fixture', null, ?, ?, ?, ?, null, ?, ?, ?, ?, null, null)`).run(input.sessionId, `perf-${input.workspaceHash}`, null, input.traceId, slug(input.title), input.workspacePath, input.workspacePath, input.title, 42000, 17000, 1300, json([{ path: "synthetic/perf.ts", additions: 42000, deletions: 17000 }]), json({ defaultMode: "ask" }), input.baseTime, input.baseTime + input.turnCount * 1000, input.baseTime);
 }
 
 function insertTurn(params) {

+ 86 - 0
.agents/skills/zcode-large-task-fixture/scripts/generate-large-task-fixture.test.mjs

@@ -0,0 +1,86 @@
+import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { DatabaseSync } from "node:sqlite";
+import { afterEach, expect, it, vi } from "vitest";
+
+const fixture = vi.hoisted(() => ({ home: "" }));
+vi.mock("node:os", async (importOriginal) => ({
+  ...(await importOriginal()),
+  homedir: () => fixture.home,
+}));
+
+const originalArgv = process.argv;
+afterEach(async () => {
+  process.argv = originalArgv;
+  vi.restoreAllMocks();
+  if (fixture.home) await rm(fixture.home, { recursive: true, force: true });
+});
+
+it("生成的本地 fixture 使用路径归属,不把目录哈希写成显式身份", async () => {
+  fixture.home = await mkdtemp(join(tmpdir(), "large-task-fixture-"));
+  const workspace = join(fixture.home, "workspace");
+  await mkdir(workspace);
+  const cliPath = join(fixture.home, ".zcode/cli/db/db.sqlite");
+  const indexPath = join(fixture.home, ".zcode/v2/tasks-index.sqlite");
+  for (const [path, schema] of [
+    [cliPath, "apps/zcode-cli/packages/adapters/src/storage/session-store/schema.baseline.sql"],
+    [indexPath, "packages/services/src/project-storage/schema.baseline.sql"],
+  ]) {
+    await mkdir(dirname(path), { recursive: true });
+    const db = new DatabaseSync(path);
+    try {
+      db.exec(await readFile(new URL(`../../../../${schema}`, import.meta.url), "utf8"));
+    } finally {
+      db.close();
+    }
+  }
+
+  const output = vi.spyOn(console, "log").mockImplementation(() => {});
+  process.argv = [
+    process.execPath,
+    "generate-large-task-fixture.mjs",
+    "--workspace",
+    workspace,
+    "--turns",
+    "1",
+    "--no-backup",
+  ];
+  await import("./generate-large-task-fixture.mjs");
+  const manifest = JSON.parse(output.mock.calls.at(-1)[0]);
+  const cli = new DatabaseSync(cliPath, { readOnly: true });
+  const index = new DatabaseSync(indexPath, { readOnly: true });
+  try {
+    expect(
+      cli
+        .prepare("select workspace_id, directory, path from session where id = ?")
+        .get(manifest.sessionId),
+    ).toEqual({
+      workspace_id: null,
+      directory: workspace,
+      path: workspace,
+    });
+    expect(
+      index
+        .prepare(
+          "select workspace_identity, workspace_key, workspace_path from tasks where task_id = ?",
+        )
+        .get(manifest.sessionId),
+    ).toEqual({
+      workspace_identity: null,
+      workspace_key: workspace,
+      workspace_path: workspace,
+    });
+    expect(
+      cli.prepare("select count(*) count from message where session_id = ?").get(manifest.sessionId)
+        .count,
+    ).toBe(2);
+    expect(
+      cli.prepare("select count(*) count from part where session_id = ?").get(manifest.sessionId)
+        .count,
+    ).toBe(manifest.partCount);
+  } finally {
+    cli.close();
+    index.close();
+  }
+});

+ 6 - 0
.gitattributes

@@ -23,3 +23,9 @@ third-party/inventory.json linguist-generated=true
 
 # Gen UI vendor 快照带 sha256 清单,构建时逐字节校验;autocrlf 改写换行会误报漂移,按字节保真。
 apps/zcode-cli/packages/visualize-plugin/skills/visualize/assets/vendor/** -text
+
+# design 内置插件:第三方设计资源保持上游原字节(许可登记按原文哈希校验);
+# SessionStart hook 是 sh/cmd 双写法脚本,CRLF 会让 sh 解析失败,固定 LF。
+apps/zcode-cli/packages/design-plugin/skills/design/design-resources/** -text -whitespace linguist-vendored=true
+apps/zcode-cli/packages/design-plugin/hooks/design-rules text eol=lf
+apps/zcode-cli/packages/design-plugin/hooks/run-hook.cmd text eol=lf

+ 1 - 0
.oxfmtrc.json

@@ -7,6 +7,7 @@
     "packages/zcode-cua/**",
     "packages/desktop/src/renderer/src/plugin-sandbox/genUiTweakRuntime.js",
     "apps/zcode-cli/packages/visualize-plugin/skills/visualize/assets/**",
+    "apps/zcode-cli/packages/design-plugin/skills/design/design-resources/**",
     "THIRD-PARTY-NOTICES.md",
     "third-party/inventory.json",
     "third-party/upstream/**",

+ 112 - 0
.oxlintrc.json

@@ -6,6 +6,118 @@
     "max-lines": ["error", { "max": 800, "skipBlankLines": true, "skipComments": true }]
   },
   "overrides": [
+    {
+      // 在 override 中只增加 Hooks 规则,保留原插件,避免开启全部 React 默认规则。
+      "files": ["**/*.{js,jsx,mjs,cjs,ts,tsx,mts,cts}"],
+      "plugins": ["unicorn", "typescript", "oxc", "react"],
+      "rules": {
+        "react/rules-of-hooks": "error",
+        "react/exhaustive-deps": "warn"
+      }
+    },
+    {
+      // 首次扫描的 20 条存量调用位置诊断仍告警;逐文件修复后删除例外,不扩大到目录。
+      // 依赖诊断与其他规则不降级,详见 docs/testing/react-hooks-lint.md。
+      "files": [
+        "**/packages/desktop/test/e2e/helpers/web-remote-visibility-browser.ts",
+        "**/packages/ui/src/ToolCallBlocks/renderers/resume-workflow-run.tsx",
+        "**/packages/ui/src/hooks/useOnboardingRecordService.ts",
+        "**/packages/ui/src/hooks/useZCodeAgentService.ts",
+        "**/packages/ui/src/hooks/useZCodeSessionService.ts",
+        "**/packages/ui/src/hooks/useZCodeTaskService.ts",
+        "**/packages/ui/src/project-sidebar/grouped/task-row.tsx"
+      ],
+      "plugins": ["unicorn", "typescript", "oxc", "react"],
+      "rules": {
+        "react/rules-of-hooks": "warn"
+      }
+    },
+    {
+      // 会话控制核心只依赖契约和注入端口,禁止把运行环境重新耦合进用例。
+      "files": ["packages/session-control/src/**/*.ts"],
+      "rules": {
+        "no-restricted-imports": [
+          "error",
+          {
+            "patterns": [
+              {
+                "group": [
+                  "node:*",
+                  "node:*/**",
+                  "fs",
+                  "fs/**",
+                  "child_process",
+                  "worker_threads",
+                  "net",
+                  "http",
+                  "https",
+                  "http2",
+                  "dgram",
+                  "dns",
+                  "dns/**",
+                  "tls",
+                  "os",
+                  "path",
+                  "path/**",
+                  "crypto",
+                  "stream",
+                  "stream/**",
+                  "timers",
+                  "timers/**",
+                  "process",
+                  "module",
+                  "vm",
+                  "electron",
+                  "react",
+                  "react/**",
+                  "react-dom",
+                  "react-dom/**",
+                  "zustand",
+                  "zustand/**",
+                  "@zcode/services",
+                  "@zcode/services/**",
+                  "@zcode/shared",
+                  "@zcode/shared/**",
+                  "@zcode/core",
+                  "@zcode/core/**",
+                  "@zcode/bootstrap",
+                  "@zcode/bootstrap/**",
+                  "@zcode/adapters",
+                  "@zcode/adapters/**",
+                  "**/services/src/**",
+                  "**/apps/zcode-cli/**"
+                ],
+                "message": "Session control uses injected ports; environment and host implementations belong in adapters."
+              },
+              {
+                "group": [
+                  "../cli/**",
+                  "../app/**",
+                  "../../cli/**",
+                  "../../app/**",
+                  "@zcode/session-control/cli",
+                  "@zcode/session-control/app",
+                  "#src/application/cli/**",
+                  "#src/application/app/**",
+                  "#session-control/application/cli/**",
+                  "#session-control/application/app/**"
+                ],
+                "message": "CLI and App use cases are independent; share contracts or pure domain rules instead."
+              }
+            ]
+          }
+        ],
+        "no-restricted-globals": [
+          "error",
+          "process",
+          "window",
+          "fetch",
+          "setTimeout",
+          "setInterval",
+          "Date"
+        ]
+      }
+    },
     {
       // 本次上游整合保留既有职责完整的实现;这些文件超 800 行只告警,不机械拆分。
       "files": [

+ 1 - 0
AGENTS.md

@@ -46,6 +46,7 @@ App 业务单测已退役,不新增或恢复 App 业务单测 test/spec 或 `c
 - PR 描述须说明背景、设计意图与修改前后行为;包含 bugfix 时逐项说明触发场景、根因证据、修复机制及回归验证,并尽量关联已有工单链接。未确认的根因或引入提交如实标注,不根据模块或时间接近推断归因。
 - 涉及状态、时序、远端或异步同步的方案,用图展示所有者及事件顺序。
 - 必须执行 `pnpm typecheck` 和 `pnpm lint`,报告真实结果,不将已有失败写成通过。
+- 修改 React 组件或 hooks 后,必须运行 `pnpm lint`(Oxlint),检查 `react/exhaustive-deps` 和 `react/rules-of-hooks`。复核本次改动新增及相关的缺失、多余、不稳定依赖与调用位置诊断,不能因仅告警或退出码为 0 就忽略,也不机械补齐整个对象依赖或禁用规则。被根配置忽略的文件须按 [React Hooks 检查](docs/testing/react-hooks-lint.md) 补做专项扫描;渲染问题仍须运行时验证。
 - 使用异步文件和网络 IO;跨包导入使用公开入口,遵守现有路径别名。
 - 禁止 UI 直接调用 Repo、Service 引用 Runtime 具体实现、跨域导入实现细节及循环依赖。
 

+ 4 - 0
CONTEXT.md

@@ -30,6 +30,10 @@ _Avoid_: 与 Manual Refresh 混用;把它称作"检查更新"(更新角标
 商店页顶栏刷新按钮触发的全市场刷新,不受自动刷新节流影响。
 _Avoid_: 刷新、检查更新(口语可用,文档统一"手动刷新")
 
+**Session Reload(会话重载)**:重建同一任务的运行实例,保留任务身份与历史。安装后的自动重载等待当前工作安全结束;不重放上一条请求。与刷新市场目录分别表述。
+
+**Plugin Readiness(插件就绪)**:当前会话实际可以使用插件能力。安装成功、已启用和会话实例 ready 均不能独立证明插件就绪。
+
 ### 商店页结构
 
 **Public Segment(公开)**:

+ 51 - 32
DESIGN.md

@@ -122,6 +122,8 @@ Default light and dark CSS variables still exist as fallback foundations, but ne
 
 - **Desktop Resize Handle**: `--color-resize-handle` uses sky-500 in light themes and sky-400 in dark themes. Use only for desktop workspace resize indicators; retain the existing geometry and interaction states.
 
+- **Voice Input Recording**: `--color-voice-input-surface` (sky-100 `#e0f2fe` in light themes, sky-950 `#082f49` in dark themes) and `--color-voice-input-wave` (sky-600 `#0284c7` light, sky-300 `#7dd3fc` dark). The tokens hold these hex values directly, because Tailwind 4's oklch sky palette renders slightly different colors. Use only for the composer voice input recording pill: the surface fills the pill, the wave colors the level bars and the stop square.
+
 - **Border**: `--color-border`
   Default border and separator.
 - **Border Hover**: `--color-border-hover`
@@ -200,31 +202,31 @@ feature-scoped token family:
 
 ### Specialized color tokens
 
-| Token | Purpose |
-| --- | --- |
-| `--color-markdown-inline-code` | Markdown 行内代码背景,沿用 tag / label 胶囊层级 |
-| `--color-popover-header` | Popover header |
-| `--color-tab` | Tab 默认背景 |
-| `--color-tab-active` | 当前激活 tab |
-| `--color-tab-border` | Tab 分隔线 |
-| `--color-feedback-privacy-hint` | 反馈截图隐私提醒文字及叹号图标;独立一行,使用辅助说明字号 |
-| `--color-git-none` | Git 无变更状态,沿用普通文件名颜色 |
-| `--color-git-modified` | Git modified,表示已跟踪文件有未提交修改 |
-| `--color-git-added` | Git added,表示新增文件已进入工作树 / 暂存区 |
-| `--color-git-deleted` | Git deleted,表示已跟踪文件被删除 |
-| `--color-git-renamed` | Git renamed,表示已跟踪文件移动或重命名 |
-| `--color-git-untracked` | Git untracked,表示 Git 尚未跟踪的新文件 |
-| `--color-git-ignored` | Git ignored,继承弱化文本层级 |
-| `--color-git-descendant` | Git descendant,表示目录后代包含变更 |
-| `--color-file-node` | 文件 mention node 背景 |
-| `--color-file-node-hover` | 文件 mention node hover 背景 |
-| `--color-file-node-foreground` | 文件 mention node 文字 / 图标 |
-| `--color-skill-node` | Skill mention node 背景 |
-| `--color-skill-node-hover` | Skill mention node hover 背景 |
-| `--color-skill-node-foreground` | Skill mention node 文字 / 图标 |
-| `--color-command-node` | Command mention node 背景 |
-| `--color-command-node-hover` | Command mention node hover 背景 |
-| `--color-command-node-foreground` | Command mention node 文字 / 图标 |
+| Token                             | Purpose                                                    |
+| --------------------------------- | ---------------------------------------------------------- |
+| `--color-markdown-inline-code`    | Markdown 行内代码背景,沿用 tag / label 胶囊层级           |
+| `--color-popover-header`          | Popover header                                             |
+| `--color-tab`                     | Tab 默认背景                                               |
+| `--color-tab-active`              | 当前激活 tab                                               |
+| `--color-tab-border`              | Tab 分隔线                                                 |
+| `--color-feedback-privacy-hint`   | 反馈截图隐私提醒文字及叹号图标;独立一行,使用辅助说明字号 |
+| `--color-git-none`                | Git 无变更状态,沿用普通文件名颜色                         |
+| `--color-git-modified`            | Git modified,表示已跟踪文件有未提交修改                   |
+| `--color-git-added`               | Git added,表示新增文件已进入工作树 / 暂存区               |
+| `--color-git-deleted`             | Git deleted,表示已跟踪文件被删除                          |
+| `--color-git-renamed`             | Git renamed,表示已跟踪文件移动或重命名                    |
+| `--color-git-untracked`           | Git untracked,表示 Git 尚未跟踪的新文件                   |
+| `--color-git-ignored`             | Git ignored,继承弱化文本层级                              |
+| `--color-git-descendant`          | Git descendant,表示目录后代包含变更                       |
+| `--color-file-node`               | 文件 mention node 背景                                     |
+| `--color-file-node-hover`         | 文件 mention node hover 背景                               |
+| `--color-file-node-foreground`    | 文件 mention node 文字 / 图标                              |
+| `--color-skill-node`              | Skill mention node 背景                                    |
+| `--color-skill-node-hover`        | Skill mention node hover 背景                              |
+| `--color-skill-node-foreground`   | Skill mention node 文字 / 图标                             |
+| `--color-command-node`            | Command mention node 背景                                  |
+| `--color-command-node-hover`      | Command mention node hover 背景                            |
+| `--color-command-node-foreground` | Command mention node 文字 / 图标                           |
 
 Git file statuses must use `text-git-*` / `bg-git-*`, rather than borrowing diff or warning tokens.
 Mention tokens belong to prompt-editor and UserPrompt mention nodes; their background, hover,
@@ -551,6 +553,22 @@ Overlay rules:
 - Diff UI must use diff-specific semantic colors, not generic success/destructive colors
 - Dense operational panels are preferred over marketing-card styling
 
+### Extension slots
+
+Extension slots are shell-owned positions where extensions supply data only (spec: `docs/plugins/extension-host.md` §6, §16). The shell component owns all styling; a plugin never provides HTML, SVG, or CSS for a slot. Slot ids come only from `EXTENSION_SLOTS` in the extension host protocol. Slot items are static manifest declarations (top-level `slots`) and stay visible while the extension host is stopped.
+
+- **`composer.status`**: sits directly left of the context-usage ring in the composer toolbar. Ghost `Button` at `size="default"` (`h-7`), `rounded-lg`, `px-1.5`, `gap-1`; a `size-3.5` icon plus text in `text-ui-sm text-foreground-subtle tabular-nums`, capped at `max-w-40` with truncation. The hover description uses `ControlHintTooltip`. It renders only when the extension has set `text`. It is the first item to collapse: collapse tier `extension` hides the text and leaves a `size-7` icon button.
+- **Side pane launcher "Extensions" section**: follows the built-in apps and UI plugins in the new-tab launcher, after the same short divider, with a `text-ui-lg font-semibold` heading. Rows reuse `SidePaneLauncherRow`. Problem rows (`failed`, `invalid`, `incompatible`, and a plugin with an unusable slot item, labelled `invalid`) are static rows without a button or capsule, one per plugin: `CircleAlertIcon`, the plugin name, a `bg-tag` state label, and the reason in the hover title (with the field path when there is one). The "Extensions stopped" row uses `OctagonXIcon` and the secondary "Reload" capsule. Rows do not use destructive or warning fills; the state label carries the meaning as text.
+- **Launcher view items**: `sidePane.launcher` items are ordinary `SidePaneLauncherRow` rows in the same section (whitelisted icon, localized view title, the plugin name as the description, the default "Open" capsule). While the extension host is stopped they stay visible: a `bg-tag` "Extensions stopped" label precedes the plugin name and the capsule becomes "Reload". No disabled or destructive styling.
+- **Extension view tabs**: an `extension-view` side pane tab uses the standard tab trigger with the view's whitelisted icon and its localized title. The body is the plugin's MCP App page in the shared sandbox; the shell only draws the loading, "not running" and error states as centered `text-ui-sm text-foreground-subtle` text. Theme and locale reach the page through the MCP Apps host context (style variables), not through shell CSS.
+- **Extension logs tab**: one `extension-logs` side pane tab per pane (`ScrollTextIcon`, title "Extension logs"), opened from an "Extension logs" `SidePaneLauncherRow` in the launcher "Extensions" section (shown only when a plugin declares `extension` or the host is stopped) and from the command center. A single `border-b` toolbar row (`px-3 py-2`, wraps when narrow): two input-style `Select` filters (source: all, extension host, each plugin id in `font-mono`; level: all, warnings and errors, errors only) on the left; `icon-md` ghost buttons with `ControlHintTooltip` on the right for auto-scroll (`secondary` + `aria-pressed` while on), copy and clear view. Rows are terminal-style `font-mono text-ui-sm` lines: time (`text-foreground-subtlest tabular-nums`), the level word padded to five characters, the source (`text-foreground-subtle`, plugin id or "Extension host gen=N"), then the message, all as one wrapping run (`whitespace-pre-wrap break-words`) with a hanging indent (`pl-9 -indent-6`) so continuation lines use the full width. Warning and error rows use `bg-warning-surface` / `bg-destructive-surface` with the matching `*-surface-foreground` level word; info rows have no fill. Empty, loading and "no match" states are centered `text-ui-sm text-foreground-subtle` text.
+- **`nav.primary`**: rows in the left primary navigation, directly after "Plugin store", one per plugin, sorted by the localized title. Each row is the same ghost `Button` as the built-in rows (`size="lg"`, `w-full justify-start gap-2`) with a `size-4` whitelisted icon and the title truncated in one line. Rows have no selected state (no `aria-pressed`, no `bg-selected`): a click opens the target in the right Side Pane and the main view stays the conversation. A view-target row while the extension host is stopped keeps its title and adds a short `bg-tag` "Stopped" label plus a trailing `text-ui-sm text-foreground-subtle` "Reload"; the hover hint and accessible name carry the full "Extensions stopped · Reload"; the click reloads. The row is narrow, so it uses the short label to keep the title readable. Surface-target (MCP App) rows never show the stopped state. An extension can set an unread badge (spec §18.1 H11): a count renders after the title as the same `bg-tag` label (`text-ui-xs tabular-nums`, `99+` above 99), and `"dot"` renders the task list unread dot (`size-[7px] rounded-full bg-icon-blue`); the accessible name appends "N unread" or "New activity". Hidden in phone remote control, like "Automations" and "Plugin store".
+- **File viewer tabs**: a `file.viewer` view opens as a regular `extension-view` tab per file; the tab title is the file name and the icon is the view's whitelisted icon. A `file.viewer` surface opens as a regular `plugin-ui` tab per file. No extra chrome; the page draws the file.
+- **`composer.mention`**: one group per entry in the composer `@` panel, after the built-in groups. The group header (the entry title) is always shown, even when it is the only visible group. Candidate rows use the skills row density: a `size-3.5` whitelisted icon, the label in `text-ui-base font-medium` (truncated at half the row), the description in `text-ui-xs text-foreground-subtlest`. Loading reuses the panel's skeleton rows; a denied or failed query and "Extensions stopped" reuse the panel's error status row, one line inside the group, so other groups stay usable. A chosen candidate becomes a mention chip in the plugin colour (`text-plugin-node-foreground`) with the generic plugin icon; it serializes to the candidate's `insertText`.
+- **Extension permissions** (spec §17.7): the launcher "Extensions" section shows one "Needs permission" row per plugin whose declared session tiers are not granted yet, right after the "Extensions stopped" row: a `SidePaneLauncherRow` with `KeyRoundIcon`, the plugin name, a `bg-tag` "Needs permission" label, the requested tiers as the description, and a "Grant" capsule that opens the consent dialog. The consent dialog and the enable confirmation reuse the shared `ConfirmDialog` (title names the plugin, the spec text is the description, default confirm button, no keyboard hints); no custom dialog chrome. The plugin details page shows a "Permissions" section after "Information" when the plugin declares or holds tiers: the same `border-b` heading as "Information", a `bg-tag` status label with the tiers, a primary "Grant" or an outline "Revoke" button at `size="sm"`, a one-line `text-ui-sm text-foreground-subtle` note, a "System notifications" row when the notifications tier is granted (spec §18.1 H8: `text-ui-base` label, `text-ui-sm text-foreground-subtle` note under it, the shared default-size `Switch` at the row end, on by default), and "Recent actions" rows in the information grid (`grid-cols-[8rem_minmax(0,1fr)]`, time in `tabular-nums text-foreground-subtle`). No destructive or warning fills. Desktop only.
+- **Icons**: only Lucide names in the extension icon whitelist render (`packages/ui/src/extension-slots/components/extensionIcons.ts`); any other name falls back to `PuzzleIcon`. The whitelist: `activity`, `bell`, `bot`, `chart-bar`, `chart-pie` (alias `pie-chart`), `clock`, `cpu`, `database`, `eye`, `file-text`, `gauge`, `git-branch`, `git-merge`, `git-pull-request`, `globe`, `info`, `layers`, `list`, `log-in`, `log-out`, `message-square`, `puzzle`, `sparkles`, `terminal`, `timer`, `zap`. Add a name in both places; a whitelisted icon uses the same size and `currentColor` as the built-in icons of that slot.
+- **Scope**: desktop only. Web and phone remote control render no slot. Verify in Zai Light and Zai Dark, zh-CN and en-US, at narrow toolbar widths where the composer slot collapses first, and with long navigation titles that must truncate.
+
 ## Elevation and Depth
 
 ZCode should use restrained depth. Layer primarily through background contrast, borders, and radius before relying on heavy shadows.
@@ -593,13 +611,14 @@ Rules:
 
 ### Breakpoint roles
 
-| Breakpoint | Preferred use |
-| --- | --- |
-| `sm:` | Dialog width, button arrangement, small-screen layout corrections |
-| `md:` | Grid columns and form layout expansion |
-| `lg:` | Desktop toolbar visibility and secondary information density |
-| `xl:` | Chat and complex content arrangements |
-| `2xl:` | Wide-screen reading-width caps, not ordinary page behavior |
+| Breakpoint     | Preferred use                                                                                                                                                                                                                                |
+| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `sm:`          | Dialog width, button arrangement, small-screen layout corrections                                                                                                                                                                            |
+| `md:`          | Grid columns and form layout expansion                                                                                                                                                                                                       |
+| `lg:`          | Desktop toolbar visibility and secondary information density                                                                                                                                                                                 |
+| `xl:`          | Chat and complex content arrangements                                                                                                                                                                                                        |
+| `2xl:`         | Wide-screen reading-width caps, not ordinary page behavior                                                                                                                                                                                   |
+| `compact-web:` | Phone and narrow Web (`< 40rem` without a desktop platform class) layout corrections that must not change narrow desktop windows; CSS only, do not copy its condition into JS (see [settings narrow layout](docs/settings-narrow-layout.md)) |
 
 Start with the unprefixed layout, then add the fewest breakpoints needed. Prefer changing
 layout, `max-width`, and visibility to repeatedly switching fixed dimensions or semantic

+ 3 - 1
README.en.md

@@ -15,8 +15,10 @@ ZCode is an AI coding workspace with desktop, browser, and terminal interfaces.
 
 ## Updates
 
-- **2026-11-03**: Updated to ZCode v3.17.2.
+- **2026-11-11**: Updated to ZCode v3.18.0.
+- 2026-11-03: Updated to ZCode v3.17.2.
 - 2026-10-30: Updated to ZCode v3.17.1.
+- 2026-10-29: Updated to ZCode v3.17.0.
 - 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.

+ 3 - 1
README.md

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

Diferenças do arquivo suprimidas por serem muito extensas
+ 35 - 1
THIRD-PARTY-NOTICES.md


+ 11 - 16
apps/zcode-cli/docs/bash-shell-provider.md

@@ -1,8 +1,8 @@
 # Bash Shell Provider 当前实现
 
-更新日期:2026-07-15
+更新日期:2026-11-10
 
-本文最初是 Bash 执行形态的实现计划。实现已经完成并继续扩展到 Windows、session shell snapshot、
+本文最初是 Bash 执行形态的实现计划。实现已经完成并继续扩展到 Windows、runtime shell selection、
 startup source 和 embedded search prelude;下面记录当前事实,不再是待执行 plan。
 
 ## 当前契约
@@ -24,8 +24,7 @@ command: {
 ## Shell 选择
 
 ```text
-session persisted selection(可用)
-  -> user-config selection(仅新 session)
+user-config selection(新 session 与 cold resume 都读取当前设置)
   -> platform auto-detect
   -> legacy system shell fallback
 ```
@@ -46,16 +45,15 @@ Windows:
 
 provider 只注入上面列出的通用变量和 ZCode 自己命名的变量,不引入其他产品命名的环境变量。
 
-## Session snapshot
+## Runtime selection
 
-shell 是 session-start 配置,而不是每个 Bash call 重新读取的全局设置:
+shell 是 runtime 初始化时读取的设置,而不是每个 Bash call 重新读取的全局设置:
 
 - 首次真实用户执行前初始化 `bashShellSelection`;deferred draft 可在首发前刷新 Environment context;
-- selection 保存为 session entry `runtime:bash_shell_selection`;
-- cold resume 优先恢复持久 selection;路径失效时记录 stale,并回落到当前可用选择;
-- shell 设置变化只影响新 session;已有 session 保持创建时选择;
-- 旧 Windows session 无可用 snapshot 且恢复时发生 shell 变化,会插入 provider-visible
-  `shell_environment_change`,避免模型继续按旧 shell 语法工作。
+- cold resume 同样读取当前设置,不恢复 session 创建时的 shell;selection 不落库;
+- runtime 存活期间不热更新;shell 设置变化对新 session 立即生效,对已有 session 在下次 cold resume 时生效;
+- shell 变化由 environment 公告告诉模型:` - Shell: <new> (was <old>)`,随请求写库,冷恢复原位还原,
+  不重复追加。
 
 workspace path/identity 不参与 shell identity;实际 executable 可用性由 Agent 运行环境判断。远程 session
 因此使用远程机器的 shell,而不是 desktop 本机 `$SHELL`。
@@ -95,7 +93,6 @@ background Bash 在 start 时清掉 cwd capture,不更新 session cwd。shell
 - `packages/contracts/src/interfaces/execution.port.ts`
 - `packages/core/src/tool/handlers/bash.ts`
 - `packages/core/src/runtime/methods/session-shell-environment.ts`
-- `packages/core/src/runtime/methods/bash-shell-snapshot.ts`
 - `packages/adapters/src/exec/bash-shell-provider.ts`
 - `packages/adapters/src/exec/bash-startup-script.ts`
 - `packages/adapters/src/exec/cwd-capture.ts`
@@ -104,13 +101,11 @@ background Bash 在 start 时清掉 cwd capture,不更新 session cwd。shell
 - `packages/core/tests/bash-handler.test.ts`
 
 测试覆盖 POSIX bash/zsh 语法、Windows Git Bash/CMD、固定目录和 PATH fallback、legacy fallback、env
-overlay、cwd capture、background behavior、startup source、snapshot restore/stale fallback,以及 generic shell
-不读取 Bash profile。
+overlay、cwd capture、background behavior、startup source、cold resume 读取当前 shell 并公告变化,以及 generic
+shell 不读取 Bash profile。
 
 ## 边界
 
 - shell provider 不承诺用户 rc/profile 的全部交互式行为;启动参数和 source 策略以 adapter 测试为准。
-- persisted executable 在 resume 时可能失效,必须降级并留下 notice,不能因保持历史 shell 而阻止 session
-  恢复。
 - Bash tool 的 provider-visible 行为契约以 `apps/zcode-cli/docs/design/v2/tool/04-bash.md` 为准;本文件只描述
   selection/execution architecture。

+ 83 - 0
apps/zcode-cli/docs/design/design-builtin-plugin.md

@@ -0,0 +1,83 @@
+# 内置插件:design(设计工作流)
+
+> Spec v1 · 2026-11-04
+
+## 目标
+
+`design` 随 ZCode 桌面端与 CLI 一起发布、默认关闭(可启用、可停用、不可卸载),源码在本仓库
+`apps/zcode-cli/packages/design-plugin/`,不依赖 CDN 插件市场。交付物是写入工作区的 HTML 设计稿、
+交互原型或 HTML 演示稿时,Agent 加载 `design` 技能按工作流执行。
+
+## 默认状态与浏览器入口
+
+- 缺少显式设置时 Design 关闭,不注入技能和 SessionStart hook。已有用户/项目的显式启用或停用配置继续生效。
+- 内置资源继续随应用分发;“选择元素”依赖当前工作区的有效 Design 启用状态。未安装或未启用时显示安装提示,确认后打开 `design@zcode-plugins-official` 的插件详情页,由该页执行安装或启用;取消不进入点选。
+- 插件状态来自 CLI 插件管理服务;界面复用其按工作区隔离的查询投影与变更通知,不额外保存启用开关。
+- 交互与验收边界见[内置浏览器设计模式](../../../../docs/browser-use/2026-11-03-browser-design-mode-spec.md)。
+
+## 内容
+
+纯内容型插件:无 MCP、无系统依赖。
+
+| 路径 | 作用 |
+|---|---|
+| `.zcode-plugin/plugin.json`、`.claude-plugin/plugin.json` | 两份宿主清单,逐字节一致;ZCode 读前者,后者供使用 `.claude-plugin` 清单格式的宿主原生加载 |
+| `skills/design/SKILL.md`、`references/*.md`(7 份) | 入口技能与按需读取的规则文件 |
+| `skills/design/scripts/*.mjs` | 画布适配、资源目录生成、设计系统导入、design-lint(零依赖 Node 脚本) |
+| `skills/design/design-resources/` | 第三方设计资源(骨架、设计系统、craft、子技能),按上游字节保留 |
+| `hooks/` | SessionStart hook:`run-hook.cmd`(sh/cmd 双写法)调 POSIX sh 脚本 `design-rules` |
+| `test/` | 插件内容与脚本测试,不随包发布(SEA、桌面 staging、远端复制的白名单都不含 `test/`) |
+
+## SessionStart 注入预算
+
+用户启用后每个会话都带这段注入,所以只放一句指针和路径基准:
+
+```
+For an HTML design, prototype, HTML deck or redesign, load the `design` skill first. Its paths are relative to: <skill dir>
+```
+
+去掉路径约 110 字节(原 0.7.0 市场版约 285 字节)。`test/design-plugin.test.ts` 钉住上限 160 字节,
+入口正文缺失或路径错误时 hook 静默退出 0,不阻塞会话。
+
+## 注册点
+
+内置插件有多个读取入口,漏一处就会出现「列表里有、会话里找不到」(见
+[zcode-guide 内置插件](zcode-guide-builtin-plugin.md) 的 c0120fa 教训)。
+
+| 文件 | 改动 |
+|---|---|
+| `packages/bootstrap/src/app/official-plugin-definitions.ts` | 定义条目,不声明 `defaultEnabled`,listing「Design / 设计」,`OFFICIAL_DESIGN_REQUIRED_SEED_PATHS` 钉入口、7 份规则、3 个脚本与 hook |
+| `packages/cli/scripts/sea-official-plugin-assets.mjs` | SEA 资源,`requiresRuntime: false`,必需文件同上 |
+| `packages/desktop/scripts/prepare-agent-node-bundle.mjs` | Electron 生产包 staging(`packages/desktop/test/runtime-asset-scripts.test.ts` 名单同步) |
+| `packages/server/src/remote/zcodeAgentOfficialPluginAssets.ts` | 远端 Agent 官方插件复制名单与必需文件 |
+| `packages/shared/src/plugin-marketplaces.ts`、`packages/services/src/plugins/officialPluginCache.ts` | Settings / services 侧默认启用集合不包含 design |
+| `packages/ui/src/lib/builtinSkillI18n.ts` | `design` 技能中英描述、内置插件名与路径标记 |
+| `docker/plugin-eval/Dockerfile` | 评测镜像 stage 的纯内容型内置插件 |
+| `.gitattributes` | `design-resources/**` 按字节保存;两个 hook 脚本固定 LF |
+
+版本在 `package.json`、两份 `plugin.json`、definitions、SEA 清单五处一致,由 bootstrap 与 build-sea 测试机械对照。
+
+## 与 CDN 同名条目
+
+官方市场的内置分片与 CDN 分片同名时,合并目录以 CDN 条目为准,内置缓存不删除
+(`adapters/src/plugins/official-marketplace.ts`)。2026-11-04 核对正式 CDN 的 `marketplace.json`:没有 `design` 条目,
+只有另一个设计插件 `designcraft`,所以当前老用户升级后只会拿到内置版本(当前 0.7.2)。之后不要往 CDN 发同名 `design`。
+装过 `designcraft` 的用户会同时有两套设计技能,是否下架或合并 `designcraft` 由插件 owner 决定。
+
+## 第三方许可与竞品词
+
+- `design-resources` 的上游(open-design、html-ppt、Zara Zhang 模板、frontend-slides、gstack 子技能、
+  brand-guidelines、frontend-design、taste-skill)登记在 `third-party/copied-components.json`,各条目按文件
+  Git blob 比对固定了上游 revision,许可原文快照在 `third-party/upstream/`;本地改过的文件带 `Modified by ZCode:`
+  并列入 `modifiedFiles`,来源与改动汇总在 `design-resources/NOTICE.md`。open-design 主体是 Apache-2.0(早先误记为
+  MIT)。competitive-ads-extractor 的上游从没有许可原文,已移除。
+- 第三方原文里的品牌名、工具名按字节保留,按精确路径登记在 `opensource/approved-terms.d/design-plugin.json`;
+  本仓库自有文件(测试、规则)使用中性表述。
+
+## 验证
+
+- `pnpm --filter @zcode/design-plugin test`:插件结构、规则体量与链接、hook 输出、catalog 新鲜度、design-lint、
+  设计系统导入。
+- bootstrap `plugins.test.ts` / `bundled-plugins-resilience.test.ts`、cli `build-sea.test.mjs`、
+  `pnpm test:engineering packages/desktop/test/runtime-asset-scripts.test.ts`。
+- 实机:`zcode plugins list --json` 能看到 `design` 且默认 `enabled: false`;用户启用后真实会话里设计类请求会加载 `design` 技能。

+ 60 - 23
apps/zcode-cli/docs/design/v2/auth-login.md

@@ -8,7 +8,6 @@ the old Key is absent or corrupt, including legacy records without an auth-sourc
 Only explicit manual mode reads the saved Key; it must not depend on an unrelated OAuth
 credential being present or decryptable.
 
-
 Dedicated Key management preserves the CLI's existing default-organization/default-project
 selection, falling back to the first entry without filtering project types. BigModel
 management requests retain the raw login JWT; Z.AI management requests retain Bearer.
@@ -16,7 +15,6 @@ Token issuance uses Bearer for both. The selection policy isolates persisted Key
 from the desktop personal-project policy. Unrelated malformed Key entries are ignored;
 a matching personal Key with no ID fails without creating a duplicate.
 
-
 Account-based Coding Plan key creation explicitly sends `usageScene: 1` for both
 BigModel and Z.AI. This field describes intended usage, independently of `keyType`.
 Manual API key login does not create a server key. List requests keep their current
@@ -26,6 +24,11 @@ defined in [the project credential spec](../../../../../docs/model-provider-proj
 
 ## Scope
 
+The independent CLI discovers the same private `credential-secret` as the Server when
+using the same credentials directory. Explicit managed configuration still takes
+precedence. A successful OS-key initialization pins that directory to its OS source;
+later remote preparation cannot change it before the first credential write.
+
 ZCode CLI login uses the ZCode/Z.AI CLI OAuth device flow and shares the same
 local credential store as the desktop Z Code product. The login boundary is a
 CLI/bootstrap/adapter concern. Core runtime does not open browsers, call OAuth
@@ -42,6 +45,16 @@ This document is the v2 contract for:
 
 ## Storage Contract
 
+Desktop may rebuild a corrupt credential container only after explicit user confirmation
+and a verified byte-for-byte backup. The CLI does not initiate this recovery. The shared
+`credentials.json.recovery-generation` marker contains only a recovery revision, never credentials.
+The container is decoded with fatal UTF-8 validation before JSON parsing, matching Desktop;
+invalid bytes cannot be replaced and silently saved. Async reads recheck the revision before
+returning; mutations capture it at admission and recheck it inside the existing file lock. A stale operation fails instead of returning old
+identity or repopulating the recovered store. Ordinary concurrent saves still merge under
+the same lock. Cross-request OAuth completion retains the initiating revision. CLI captures the store recovery guard before OAuth init and reuses it for both the login credential write and default-connection persistence. A recovery while initializing, polling or resolving access material rejects the old completion; it must not refill the empty store or update the default connection. A newly initiated login captures the current revision and may succeed. Default-config writes validate this revision at their commit point, after taking the config file lock and while holding the credential file lock. The lock order is config → credential; no credential lock is held while waiting for the config lock. This also fences normalization/import writes made by the config repository.
+See [the recovery contract](../../../../../docs/ui/login-page.md#凭据容器损坏后的确认恢复).
+
 Sensitive login state is stored in:
 
 ```text
@@ -54,20 +67,19 @@ The base directory follows the Z Code desktop convention:
 2. `ZCODE_DATA_BASE_DIR`.
 3. `os.homedir()`.
 
-The file is a JSON object whose keys and decrypted values are strings. Values are
-written with the same encryption format used by the desktop credential store:
-
-```text
-enc:v1:<iv>.<authTag>.<cipherText>
-```
-
-Encryption uses AES-256-GCM. The key is `sha256(secret)`, where `secret` is:
-
-1. `ZCODE_CREDENTIAL_SECRET` when present.
-2. `zcode-credential-fallback:${platform}:${homedir}:${username}`.
+The file remains a JSON key/value container. System-backed encryption and migration
+follow [the shared storage contract](../../../../../docs/plans/2026-10-29-system-credential-storage.md).
+Desktop and CLI use one asynchronous cipher implementation. System-store failures
+must preserve existing values and must not be treated as an expired login.
 
-Reads must keep backward compatibility with legacy plaintext values that do not
-start with `enc:v1:`.
+For desktop-managed execution, the CLI delegates credential encryption and
+decryption to the connected Host over `interaction/requestCredentialCipher`;
+the Host delegates to Desktop Main over its private parent port. Only Main
+accesses the system key store. Neither IPC path carries the master key or logs
+credential values. MCP OAuth storage and endpoint routing share this delegated
+store; an unavailable Host must not fall back to direct OS key-store access.
+Standalone CLI retains its own OS identity and caches key access (including a
+denial) for the process lifetime; after unlocking, restart the CLI to retry.
 
 The ZAI OAuth session keys are:
 
@@ -83,11 +95,22 @@ login state and allow the CLI to exchange the Z.AI access token for a Coding
 Plan Project Access Token.
 
 `zcode logout` snapshots shared OAuth keys, account identity/source pointers, and
-only explicitly manual accounts' private model credential keys, then deletes
-only values that still match that snapshot. A concurrent new login must not be
+only explicitly manual accounts' private model credential keys, then compares
+the entire snapshot and deletes the whole group in one file-lock transaction.
+Any changed value rejects the whole deletion; unchanged sibling fields must not
+be deleted separately. A concurrent new login must not be
 erased. Historical OAuth-derived keys (including corrupt ciphertext and records
 without a source marker) are neither decrypted nor deleted during logout.
 
+Host and CLI preserve the existing file format and jointly update
+`oauth:session_revision` on OAuth mutations. Login captures its expected snapshot
+before network authorization; its final commit replaces the active provider,
+tokens and profile together, removes stale provider/refresh fields and rejects a
+changed snapshot. A matching account/token is not sufficient to identify the same
+login generation. Inactive Z.ai cleanup must not remove the active BigModel JWT.
+Older binaries do not participate in this revision protocol; compatibility with
+their stored values does not guarantee safe concurrent writes by old binaries.
+
 OAuth setup stores the stable identity and `auth-source=oauth`; manual setup stores
 `auth-source=manual` and its account-scoped API key. OAuth-derived short-lived
 Tokens are memory-only. Non-secret Key IDs may be persisted by environment,
@@ -115,13 +138,18 @@ https://zcode.z.ai/api/v1
 `zcode login`:
 
 1. Generate a local random `poll_token` with 32 random bytes encoded as hex.
-2. `POST /oauth/cli/init` with `Authorization: Bearer <poll_token>` and
+2. Capture the store recovery guard and session snapshot, then confirm the
+   encryption needed for the login write through the same key path as the first
+   write. An unavailable credential store fails here with its original
+   storage error: no `init` request, no `authorize_url` and no browser. On a
+   usable store this may create the directory's key before authorization.
+3. `POST /oauth/cli/init` with `Authorization: Bearer <poll_token>` and
    `{"provider":"zai"}`.
-3. Show `authorize_url` and try to open it in the system browser.
-4. Poll `GET /oauth/cli/poll/:flow_id` with the same authorization header.
-5. Continue while `status` is `pending`.
-6. On `ready`, persist credentials and patch non-sensitive model config.
-7. On `failed`, timeout, or business error, report a retryable login failure.
+4. Show `authorize_url` and try to open it in the system browser.
+5. Poll `GET /oauth/cli/poll/:flow_id` with the same authorization header.
+6. Continue while `status` is `pending`.
+7. On `ready`, persist credentials and patch non-sensitive model config.
+8. On `failed`, timeout, or business error, report a retryable login failure.
 
 The HTTP response envelope is:
 
@@ -272,12 +300,19 @@ or use a future callback-paste fallback.
 
 ## Tests
 
+Every test that invokes login or logout must inject a credential store in a
+temporary directory, including endpoint and failed-authorization tests. Reading
+a legacy credential store can migrate and rewrite it before OAuth starts; a fake
+HTTP client or `noBrowser` does not isolate persistence.
+
 Required coverage:
 
 - Credential encryption, decrypt, plaintext compatibility, ZAI logout active
   provider behavior, and `ZCODE_DATA_BASE_DIR`.
 - OAuth init/poll headers, envelope business errors, pending/ready/failed,
   and timeout.
+- Failed authorization uses the injected temporary store and preserves its
+  existing credential values through migration.
 - Setup preserves personal providers and selects the built-in model. OAuth must
   not persist short-lived Tokens or read legacy derived Keys.
 - Both families find/create `usageScene=1` dedicated Keys, use the ID for token
@@ -295,3 +330,5 @@ Required coverage:
 Z.AI 前置业务 JWT 的 `ZaiBusinessTokenCache` 采用相同的临时故障分类与 5 秒退避,降级结果必须属于共享 pending。仅在 JWT exp / 响应 TTL 的最早期限内、同一登录且未被 invalidate 时复用旧值;无有效期元数据不降级。保留旧对象身份,确保迟到的 401 仍能将其标记为拒绝;clear/切账号拒绝在途结果。降级只记录固定 `project_token_business_login_refresh_deferred` 事件,不包含 JWT、OAuth 或响应内容。验收覆盖并发、退避恢复、原有效期边界、未知有效期、认证拒绝、取消及在途 clear/invalidate/换账号。
 
 共享换证的生命周期属于 resolver/cache owner:Key ID 定位、PAT 签发/刷新/401 恢复与业务 JWT 换证 HTTP 都不携带单个调用方 signal,也不携带 context.abortSignal;保留 trace/logger,每次 HTTP 请求设置 15 秒超时。`resolve` 与 `resolveMaterial` 为调用方提供独立可取消等待,提前取消不发请求,等待中取消及时拒绝且移除监听器;不能让一个会话取消影响其他等待者或清空有效缓存。所有等待者退出后底层任务仍有超时,晚到失败必须消费;clear/登录代次保护不变。验收覆盖首个/后续等待者取消、并发共享、旧 PAT 刷新、401 恢复、Z.AI JWT 刷新、全员取消后的成功/失败、监听器清理和 logout 竞态。
+
+中国区桌面登录使用 `oauth:zai_cn:*`,关联材料使用 `oauth:linked_bigmodel`。独立 CLI 本期不新增中国区交互入口;开始另一条全局登录或退出时,必须在同一事务删除这些旧会话字段,避免旧关联跨账号保留。

+ 6 - 0
apps/zcode-cli/docs/design/v2/compact/plan.md

@@ -162,6 +162,9 @@ shouldCompact = activeTokenEstimate >= autoThreshold
 - 用户配置关闭 auto compact。
 - `querySource` 是 `compact`、`session_memory`、summary agent、subagent 内部压缩路径。
 - 当前 session 的连续自动 compact 失败数达到 3。
+- 历史不够压缩:入口按全部存储条目判断(至少 2 轮、至少一条 assistant),和 reactive compact 的入口相同;
+  请求投影删除的回复仍然算历史。入口不够时直接跳过,不写 compact 时间线。通过入口后,compact 保留最后一轮,
+  只对其余部分再判断一次,不够时写一条 Skipped 时间线;正常回复的历史也是这样。
 
 测试:
 
@@ -203,6 +206,9 @@ active context 的裁剪、summary 生成、boundary 持久化和 resume/replay
 - 调用 reactive compact:`CompactTrigger.Reactive`,`CompactReason.ProviderOverflow`。
 - reactive compact 成功后重放本轮 provider 请求。
 - 仍失败才把 context overflow 作为用户可见错误抛出。
+- 入口按全部存储条目判断历史是否够压缩(至少 2 轮、至少一条 assistant),和 auto compact 的入口相同。
+  请求投影删除的回复(没有工具调用、只有思考或空白)仍然算历史;入口不够时直接跳过,不写 compact 时间线。
+  通过入口后,compact 保留最后一轮,只对其余部分再判断一次,不够时写一条 Skipped 时间线,再抛出超窗错误。
 - reactive retry guard 的作用域是当前 model-step 重试链:reactive compact 成功后 guard 保持已使用,
   原地重试仍然 context overflow 时直接抛出 `model_context_exceeded`,避免无限重试;只有同一
   product turn 的完整 sibling tool result batch 全部终态、持久化并完成 guide drain 后,才进入下一个

+ 120 - 0
apps/zcode-cli/docs/design/v2/conversation-input-source.md

@@ -0,0 +1,120 @@
+# 会话输入来源(ConversationInputSource)
+
+用户消息可以带一个结构化来源 `source`。界面用它显示「来自插件 X」「来自会话 …」。
+缺省表示用户亲自输入。来源是可信调用方写入的事实,CLI 不从正文推断,也不让模型设置。
+
+本文是 CLI 对来源的完整契约。协议形状在
+`packages/shared/src/zcode-protocol-v4/input-intent.ts`(`conversationInputSourceSchema`),
+CLI 内部形状在 `packages/contracts/src/interfaces/session.port.ts`(`TurnInputSourceMetadata`),
+两处必须一致。
+
+## 1. 来源种类
+
+| kind        | 字段                                        | 由谁设置                                                                                                           |
+| ----------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
+| `pluginUi`  | `pluginId`、`toolCallId`                    | 插件 UI 经 `ui/message` 代用户发送                                                                                 |
+| `genUi`     | `path`、`title?`                            | 交互视图代用户发送                                                                                                 |
+| `session`   | `sessionId`、`title?`(`title` 只读旧数据) | App Host:模型跨会话发送时由 app-control 注入调用方会话                                                            |
+| `extension` | `pluginId`                                  | App Host:扩展网关代插件发送([扩展宿主 §17.8](../../../../../docs/plugins/extension-host.md#178-可见标识与审计)) |
+
+- 每种都是 strict 对象:多一个字段或缺一个必填字段,整条命令按 `proto.invalidPayload` 拒绝。
+- `extension.pluginId` 是非空字符串,与 `pluginUi.pluginId` 同一取值规则。它来自扩展进程自报,只用于展示与归因,不是授权依据(扩展宿主 §7.3)。
+
+## 2. 入口
+
+| 命令                            | 字段     | 说明                                     |
+| ------------------------------- | -------- | ---------------------------------------- |
+| `sendText`                      | `source` | 全部来源                                 |
+| `createSession.firstInput`      | `source` | 全部来源;与 `sendText` 同一条首发写路径 |
+| `editUserQuery` / `retryTurn`   | —        | 沿用被编辑或重试的原 intent 的来源       |
+| `sendQueuedNow`                 | —        | 沿用原 queue item 的来源                 |
+| `createSelectionSideSession` 等 | —        | 不带来源                                 |
+
+## 3. 谁能设置
+
+```text
+模型 / 工具 ──► 会话控制工具(cli_* / app_*)──► strict 入参,没有 source 字段
+                                               └─ App facade 固定 {kind:"session"}
+扩展 ctx.sessions.* ──► Window Host 扩展网关 ──► 注入 {kind:"extension", pluginId}
+渲染进程 / 手机 ────► Host ──► sendText(pluginUi / genUi)
+                         │
+                         ▼  V4 command(stdio,对端只有 Host)
+                       CLI:只从命令 payload 读取 source,原样写入 canonical intent
+```
+
+- 只有 V4 command 通道上的 App Host 能设置来源。CLI 的 stdio 对端只有 Host,CLI 不再区分 Host 内部的调用方。
+- 模型和工具不能设置来源:
+  - 会话控制工具的模型入参是 strict schema,没有 `source` 字段,多带即拒绝;
+  - CLI 运行时、工具执行和模型输出都不构造来源;
+  - CLI 不从正文推断来源。
+- App 侧要求(扩展宿主 P3c App 步骤负责):`extension` 只能由扩展网关注入。Host 必须拒绝渲染进程和手机发来的带 `extension` 来源的 `sendText` / `createSession`。这一条 CLI 无法替 Host 校验。
+
+## 4. 持久化
+
+来源随 canonical input intent 一起写入,不改表结构,不需要 migration:
+
+- 开始执行的输入:用户消息 `metadata.conversationInputIntent.source`(完整事实,读取时按 schema 校验)与 `metadata.inputIntent.source`(旧种子)。两者都在 CLI 会话库 `message` 表的 `data` 列(JSON 文本)里。
+- 排队的输入:session input 账本 `payload.conversationInputIntent.source`,在 `session_input` 表的 `payload` 列(JSON 文本)里。队列本身不跨进程保留(重启时丢弃并留痕)。
+- 冷恢复从 `conversationInputIntent` 读回来源。
+- **批准(用户,2026-11-05)**:`extension` 来源会作为新取值写进上面两列的 JSON。表结构不变,用户已批准。之后凡是数据库改动(表结构、migration、往已有库里写新种类的数据),都要先经用户手动批准。
+
+## 5. 投影
+
+- `userInput` 行带 `source`;`queue.items[]` 带 `source`。
+- live 与冷恢复产出同一份来源。桌面与手机读同一份行。
+- 界面文案(「来自插件 X」)属于 App,不在 CLI。
+
+## 6. 幂等
+
+app-control 命令(commandId 前缀 `app-control-`,模型跨会话工具与扩展写入共用这个 facade)的
+请求身份包含来源(`command-inbox.ts` 的 `requestIdentity`):
+
+- 同一 `commandId` 重试,来源相同:`duplicate`,只产生一条消息。
+- 同一 `commandId`,`pluginId` 不同:`proto.commandConflict`。
+- `session` 来源的展示标题不参与身份(既有规则)。
+
+## 7. 能力位
+
+`runtime/capabilities` 返回 `extensionInputSource: true`。
+
+App 发送带 `extension` 来源的命令之前,必须先确认能力位(`ZCodeAgent.supportsExtensionInputSource`)。没有能力位时,app-control 报 `unavailable`:不发送,也不去掉来源后发送。原因是旧 CLI 对两个入口的行为不同:
+
+| 入口                              | 旧 CLI 的行为                                                                                                                          |
+| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
+| `sendText.source`                 | `discriminatedUnion` 不认识 `extension`,整条命令 `proto.invalidPayload`。失败可见,但原因不清楚。                                     |
+| `createSession.firstInput.source` | `firstInput` 是非 strict 的 `z.object`,`parseCommandEnvelope` 静默剥掉 `source`。会话和首条消息照常创建,消息没有来源。这是静默降级。 |
+
+## 8. 兼容:旧 App 读到新来源
+
+```text
+写入:新 App ──(能力位)──► 新 CLI ──► 持久化 intent.source = extension
+                                         │
+回退:装回旧 App ──► 旧 CLI 冷恢复 ──────┘
+        旧 CLI:conversationInputIntentSchema 不认识 extension → 完整事实整体失败
+              → 退回 metadata.inputIntent 种子(不校验)→ source 原样进入 userInput 行
+        旧 App:
+          有逐行降级(2026-11-04 起,04-sync 规则 13)→ 这一行变成 unreadable 占位行,其他行正常
+          没有逐行降级 → 整个 snapshot 被拒 → fault.subscription.contentRejected,会话打不开
+```
+
+- 默认没有运行中的版本偏斜:本地 CLI 随 App 打包;远端 Source Server 默认只承诺同版本(`minCompatibleVersion` 缺省等于产品版本,见 [R3 远程架构](../../../../../docs/architecture/r3-source-server-remote-architecture.md));手机页面按 `app_version` 分目录发布([Remote v4 静态部署](../../../../../docs/web-remote-control/remote-v4-static-deployment.md))。
+- 逐行降级见 [04-sync 规则 13](../../../../../docs/v4-refactor/04-sync-and-recovery.md)。
+- 偏斜只在回退时出现:用户装回旧 App,旧 App 自带的旧 CLI 读新 CLI 写的历史。
+- 各位置的结果:
+
+| 位置                          | 旧 App(有逐行降级)                                   | 更旧的 App(没有逐行降级)     |
+| ----------------------------- | ------------------------------------------------------ | ------------------------------ |
+| snapshot `rows.window` 中的行 | 这一行变成占位行,正文不显示                           | 整个 snapshot 被拒,会话打不开 |
+| delta 中的行                  | 这一帧被拒,强制 snapshot 后同上                       | 同左后整体失败                 |
+| `rows/range` 历史回补         | 这一行变成占位行                                       | 整页被拒                       |
+| `queue.items[]`(A 区,严格) | 整个 snapshot 被拒;回退后不会出现(队列不跨进程保留) | 同左                           |
+
+- 现有的协商模式不适用:`hostCapabilities`(CLI 按 Host 声明决定发布什么)只能约束新 CLI;回退时读数据的是旧 CLI,新 CLI 不在场。所以不新增协商机制。
+- **决策(用户,2026-11-05):不处理回退。** 已知后果:装回旧版 App 后,带插件来源的消息在有逐行降级的 App 里显示为占位行;更早的 App 打不开这些会话。理由:只有回退时才出现,运行中没有版本偏斜。
+- 考虑过、未采用的缓解:新 CLI 只把 `extension` 来源写进经校验的 `conversationInputIntent`,不写进旧种子 `inputIntent`,旧 CLI 退回种子时消息正常显示、只是不标来源。代价是持久化格式出现一处不对称。以后要支持回退时再评估。
+
+## 9. 测试
+
+- `packages/bootstrap/tests/v4-extension-input-source.test.ts`:能力位;`createSession.firstInput.source` 与 `sendText.source` 落库、进入排队项与 `userInput` 行;冷恢复保持来源;非法来源被拒绝;用基线 schema 复现旧 App 与旧 CLI 的读取结果。
+- `packages/bootstrap/tests/command-inbox.test.ts`:同一请求重试与 `pluginId` 冲突。
+- `packages/core/tests/session-control/tools.test.ts`:会话控制工具不向模型暴露 `source`,带 `source` 的调用被拒绝。

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

@@ -29,7 +29,7 @@
 
 当 logger 识别到开发环境默认 debug 时,runtime 会写出 `event: "context.built"` 的 debug 级日志,其中包含 context sections 的 `name`、`source`、`chars`、`tokens`、`preview` 和 `content`。这是开发期可观测路径;默认非 debug 日志级别不写完整 section content。日志级别不通过 `ZCODE_LOG_LEVEL` 配置;需要这些快照时,应使用 dev 运行形态重新运行被测 CLI。
 
-在每次模型请求前,runtime 还会在 debug 级别写出 `event: "context_usage_snapshot"`。它不是稳定对外 API,而是开发期 JSONL 观测事件,用于 debug app 展示 context 占用。快照至少包含:
+在每次模型请求前,runtime 还会在 debug 级别写出 `event: "context_usage_snapshot"`。它不是稳定对外 API,而是开发期 JSONL 观测事件,用于 debug app 展示 context 占用。需要稳定接口的消费方(如扩展插件)用 [Context 组成](model/context-composition.md) 的查询方法;两者来自同一份分解。快照至少包含:
 
 - `categories[]`:按 system prompt、meta user context、skills、tool prompt、tool schemas、messages 分组的占用。
 - `categoryBreakdown[]`:默认日志只记录每个分组的 contributor 数量与 Top contributors;section contributor 记录 `name`、`source`、`injectionTarget`、`cacheHint`,tool contributor 记录 tool name/server/readOnly/sideEffectScope,skill contributor 记录 skill name/source/scope/path,message role contributor 记录 role/count。该字段用于回答“每轮上下文里分别是谁贡献了大头”,不得写入完整 prompt/message/tool schema 文本,也不得无上限列出所有 contributor。

+ 79 - 12
apps/zcode-cli/docs/design/v2/hooks.md

@@ -46,15 +46,15 @@ Hooks 的目标不是把业务逻辑散落到用户脚本里,而是在 agent l
 
 ## P0 事件集合
 
-| Event                | 触发点                                        | 可阻断             | 可修改                            | 模型可见输出                                        |
-| -------------------- | --------------------------------------------- | ------------------ | --------------------------------- | --------------------------------------------------- |
-| `SessionStart`       | session 创建或 resume 后、首轮 prompt 前      | 否                 | 可追加 session context            | 是,受预算限制                                      |
-| `UserPromptSubmit`   | 用户输入进入 turn 前                          | 是                 | 可追加 context,不改原始用户文本  | 是,受预算限制                                      |
-| `PreToolUse`         | tool input schema 校验后、permission check 前 | 是                 | 可替换完整 tool input             | 可追加 context,批次后附件                          |
-| `PermissionRequest`  | permission service 返回 ask、broker UI 前     | 是                 | 可允许、拒绝或替换完整 input      | 否,除拒绝原因                                      |
-| `PostToolUse`        | tool 成功后、结果序列化给模型前               | 否                 | 可追加 context;P1 再支持替换输出 | 是,批次后附件;Hook stdin 获得完整 `tool_response` |
-| `PostToolUseFailure` | tool 失败后、错误返回模型前                   | 否                 | 可追加 recovery context           | 是,批次后附件                                      |
-| `Stop`               | turn 即将 complete 前                         | 是,可要求继续一轮 | 可追加 feedback context           | 是                                                  |
+| Event                | 触发点                                                            | 可阻断             | 可修改                            | 模型可见输出                                        |
+| -------------------- | ----------------------------------------------------------------- | ------------------ | --------------------------------- | --------------------------------------------------- |
+| `SessionStart`       | session 创建、resume、fork 后的首轮 prompt 前;每次 compaction 后 | 否                 | 可追加 session context            | 是,受预算限制                                      |
+| `UserPromptSubmit`   | 用户输入进入 turn 前                                              | 是                 | 可追加 context,不改原始用户文本  | 是,受预算限制                                      |
+| `PreToolUse`         | tool input schema 校验后、permission check 前                     | 是                 | 可替换完整 tool input             | 可追加 context,批次后附件                          |
+| `PermissionRequest`  | permission service 返回 ask、broker UI 前                         | 是                 | 可允许、拒绝或替换完整 input      | 否,除拒绝原因                                      |
+| `PostToolUse`        | tool 成功后、结果序列化给模型前                                   | 否                 | 可追加 context;P1 再支持替换输出 | 是,批次后附件;Hook stdin 获得完整 `tool_response` |
+| `PostToolUseFailure` | tool 失败后、错误返回模型前                                       | 否                 | 可追加 recovery context           | 是,批次后附件                                      |
+| `Stop`               | turn 即将 complete 前                                             | 是,可要求继续一轮 | 可追加 feedback context           | 是                                                  |
 
 实现状态:
 
@@ -257,7 +257,58 @@ Tool 执行路径:
 - process hook 使用现有执行 adapter 或专用 `HookExecutionPort`,二者都必须支持 timeout、abort、output truncation、cwd、Windows executable resolution。
 - hook runner 只返回结构化 `HookRunResult`,不直接写 UI。
 - runtime lifecycle hooks 通过 `packages/core/src/runtime/methods/hooks.ts` 统一触发,避免把 hook 调用散落在 turn loop 各处。
-- lifecycle hook 的 additional context 以 synthetic user/system reminder 注入 message history;原始用户文本不被 hook 修改。
+- lifecycle hook 的 additional context 以 synthetic user/system reminder 注入 message history;原始用户文本不被 hook 修改。写库和位置见下节。
+
+### 生命周期 Hook 上下文的持久化
+
+`SessionStart`、`UserPromptSubmit`、`Stop` 的 additional context 是 `hook_context` 隐藏提醒。
+它先写库,再进入 message history 和当轮请求。冷恢复按原位置回放,所以热态请求和冷恢复后的请求前缀相同。
+
+| 来源                             | 何时运行                                                       | 何时写库                     | 位置                                                                                   |
+| -------------------------------- | -------------------------------------------------------------- | ---------------------------- | -------------------------------------------------------------------------------------- |
+| `SessionStart` `startup`         | 首轮 context 初始化后                                          | 首轮会话写库后               | 首轮输入之前                                                                           |
+| `SessionStart` `resume` / `fork` | `resumeFromStore` 时                                           | 下一轮会话写库后             | 下一轮输入之前;通知类轮次的输入在轮开始前已写库,这时排在该输入之后                   |
+| `SessionStart` `compact`         | 每次 compaction 生成摘要之后、提交之前(手动、auto、reactive) | 与 compaction 产出同一次提交 | compaction 附件的最后一项(边界、摘要、保留尾部、附件之后)                            |
+| `UserPromptSubmit`               | 用户输入写入前(可阻断)                                       | 本轮第一次输入附件收集       | prompt 之后,本轮输入附件之后、请求前公告(instructions / session_context / date)之前 |
+| `Stop`                           | 准备结束前                                                     | 立即                         | 该次 assistant 之后                                                                    |
+
+规则:
+
+- `SessionStart` 的 startup / resume / fork 结果先放进 runtime 内存里的待写槽,不直接写库。原因:startup 时会话行还没创建;resume 只是打开会话,写库会让每次打开都多一行。
+  下一轮在会话写库(`ensureSessionPersisted`)之后提交待写槽:先写库,再进入历史。
+  只打开会话、不发消息时不写库。runtime 释放时,待写槽一起丢弃。
+- 每个 runtime 只运行一次 `startup` / `resume` / `fork`,所以多次 resume 同一个 runtime 不会重复写入。
+- 提交待写槽之前,先在当前历史里从后往前找最近一条 `SessionStart hook additional context: ` 开头的 `hook_context`。
+  两份正文逐字相同就丢弃待写内容,不写库、不进历史;不同就照常提交。判断只依赖历史,不加新状态。
+  - 原因:常驻池空闲 10 分钟就释放 runtime,每次重开并发消息都会运行一次 resume。输出不变的 hook 若每次都写,上下文会持续累积。
+  - 比较放在提交时,不放在暂存时:重开和下一轮之间可能发生 rewind,切掉最近那一份;提交时的历史才是这一轮真正发给模型的历史。
+  - 待写槽在提交前不在历史里,提交又在本轮请求之前,所以相同的内容不会进入任何请求。
+  - 输出每次都不同的 hook(例如带时间、git 状态)仍会每次重开写一份,只靠去重,不做额外策略。
+- 待写槽只保留最新一次非空结果。
+- `fork`:子会话在 fork 提示之后还没有任何输入(prompt、通知等不是隐藏提醒的 user 行)时,每次打开都用 `fork`;有了第一条输入之后用 `resume`。由历史推出,不另存状态。
+  从父会话复制来的 startup 上下文保留;`fork` 的正文与它相同时,按上面的规则不再写入。
+- `compact`:
+  - 不受每个 runtime 只运行一次的限制,每次 compaction 都运行。
+  - 和其他来源一样先经过 workspace hook admission:每次都调用 `activate("compact")`,重新评估 Trust 状态,并上报一次 `WorkspaceHookAdmissionUpdated` 会话事件。
+  - 摘要生成之后、提交之前运行。结果作为 compaction 附件的最后一项,与边界、摘要、附件同一次提交,并计入压缩后 token。
+    不能在提交之后单独写入:那一步出错会把已提交的 compaction 当作失败,压缩后 token 也算不上它。
+  - 一轮中间的 auto / reactive compaction 直接用压缩后的条目继续本轮请求,下一次请求就带上。
+  - 同样去重:和压缩后保留部分里最近一份 SessionStart 上下文比较,相同就不写。压缩后的历史里,只有保留部分可能含 SessionStart 上下文。
+    手动 compaction 不保留尾部,所以总是写入;只有 auto / reactive 可能因去重不写。
+  - hook 有结果时(包括因去重而不写),compaction 提交成功后丢弃还没提交的 startup / resume 结果;没有结果时保留它们,下一轮照常提交。
+  - hook 在提交前运行:提交失败时 hook 已经运行过;auto 重试会再运行一次。
+  - hook 运行期间用户停止:按取消收尾,compaction 不提交。
+    原因:hook runner 把取消当作单个 hook 失败,不抛错;hook 返回后要再检查一次取消,否则 compaction 照样提交。
+- `UserPromptSubmit` 的上下文只在本轮第一次输入附件收集时写入,工具批次之后的收集不再写。
+- `UserPromptSubmit` 的上下文在 prompt 之后,rewind / retry 切到这个 prompt 时会一起删掉。
+  `SessionStart` 的上下文在 prompt 之前,会保留;同一 runtime 重跑时不再运行 SessionStart,所以不会重复。
+- 新轮通知(task notification、subagent reply)的首个请求不收集输入附件,这类轮次也不运行 `UserPromptSubmit`。
+- 升级前的会话:之前只在内存里的上下文无法找回。旧会话第一次冷恢复时前缀会变化一次,之后稳定。
+
+已知限制:
+
+- prompt 已写库、但这一轮在第一次输入附件收集之前结束(模型创建失败、中止)时,这一轮的 `UserPromptSubmit` 上下文不写入。retry 会重新运行 hook,不受影响。
+- 一轮中间的 auto / reactive compaction 运行的 `compact` SessionStart,Hook 摘要行在实时界面挂在当前轮,冷合并后挂在下一轮。只影响界面,不影响模型请求。
 
 ## Session Event 与观测
 
@@ -302,6 +353,13 @@ Tool 执行路径:
 - hook 超时必须取消子进程,并记录 `hook_timeout`。
 - hook 被取消必须传播 abort signal,不留下 pending promise。
 - 用户/project hooks 后续应接入 workspace trust 或等价安全确认;P0 可以先在 TUI/CLI 中默认要求本地项目配置显式开启 `hooks.enabled`。
+- Workspace Hook Trust 的产品规格见 `docs/specs/workspace-hook-trust.md`。CLI 侧的 Trust identity(D23)只经 `@zcode/adapters/config` 的 `resolveWorkspaceHookTrustIdentityForWorkspace` 计算。它调用 `@zcode/shared/managed-worktree` 的共享 resolver,文件端口由 adapter 提供,数据根目录沿用 `ZCODE_DATA_BASE_DIR`(为空时用 homedir),不新增环境变量。使用位置:
+  - Runtime snapshot:`createZCodeApp` 先算出 identity,再经 `createConfig({ workspaceHookTrustIdentity })` 写入 snapshot;
+  - `zcode hooks trust` 命令与协议 `workspaceHookTrust/grant`:record 键与 policy 评估都用 Trust identity;
+  - 审核控制器:`requestReview`、`respond`、`revokeCurrent` 的 target 带 workspaceKey,先解析成 Trust identity 再与 snapshot 比较;
+  - 同进程内的 Trust 重载通知:按 Trust identity 匹配活跃 session,源仓库授予后它的受管 worktree session 也会重载;跨进程通知由 Host 负责。
+- Security Revision 按 snapshot 的 Trust identity 计数。源仓库与它的受管 worktree 共用同一个 revision 键。
+- 对外字段只发会话所属 workspace 的 key(远程 = identity;本地 = 协议入口传入的 workspace key,受管 worktree 会话是项目 key,独立 CLI 缺省为工作目录),包括 `WorkspaceHookAdmissionUpdated.workspaceIdentity`、审核 request 的 `workspaceIdentity` 和由它们派生的 V4 投影。Trust identity 只用于 Trust record 读写、policy 评估、Security Revision 计数和 snapshot 内部比较。review binding 与命令路由按 workspaceKey 匹配;命令 target 带回的 workspaceKey 由控制器解析成 Trust identity 后再与 snapshot 比较。
 
 ## 实施阶段
 
@@ -322,8 +380,8 @@ Tool 执行路径:
 ### Phase 3: Runtime Lifecycle Hooks
 
 - 在 `AgentRuntime` 保存同一个 `HookRunner`,供 tool executor 和 runtime lifecycle 共享。
-- 接入 `SessionStart`:context 初始化后、首个用户 prompt 进入模型前触发;`source=startup|resume|clear|compact`。
-- 接入 `UserPromptSubmit`:用户输入转成 message history 前触发;可阻断,可追加 context,不允许修改原始 prompt。
+- 接入 `SessionStart`:context 初始化后、首个用户 prompt 进入模型前触发;`source=startup|resume|fork|clear|compact`。
+- 接入 `UserPromptSubmit`:用户输入转成 message history 前触发;可阻断,可追加 context,不允许修改原始 prompt。追加的 context 写在 prompt 之后。
 - 接入 `Stop`:无 client-side tool call 且准备 complete 前触发;可注入 feedback 继续下一轮。
 - 为 lifecycle hooks 添加 focused unit tests 和 headless runtime tests。
 
@@ -374,6 +432,15 @@ Phase 3:
 - `SessionStart` 在首个 turn 前只运行一次,resume 来源可区分。
 - `UserPromptSubmit continue:false` 在写入用户消息和发起模型请求前阻断。
 - `UserPromptSubmit` / `SessionStart` 的 `additionalContext` 会进入下一次模型请求。
+- startup、`UserPromptSubmit`、`Stop` 的上下文在冷恢复前后逐字不变,位置不变;每个来源都返回同一段静态文本时(内置 design 插件),冷恢复后的每次请求与热态逐字相同。
+- resume 的上下文写在下一轮 prompt 之前;resume 后不发消息不写;多次 resume 不重复;下一轮是通知轮时写在通知之后。
+- 带工具调用的一轮只写一份 `UserPromptSubmit` 上下文。
+- startup / resume / fork 的正文与历史里最近一份 SessionStart 上下文相同时不写;不同时写入;重开后 rewind 切掉最近那一份时照常写入。
+- fork 子会话在第一条输入之前用 `fork`,之后用 `resume`。
+- 手动、auto、reactive 三种 compaction 后都运行 `compact`;上下文是 compaction 附件的最后一项,与 compaction 产出同一次提交并计入压缩后 token;与保留部分里最近一份相同时不写;有结果时(包括因去重不写)丢弃待写的 startup / resume 上下文,没有结果时保留;hook 运行期间停止时 compaction 不提交。
+- 静态文本的 SessionStart 在三种 compaction 后都写回一份,压缩后的请求里只有一份,冷恢复后请求逐字不变。
+- 已提交的 SessionStart 上下文不留在待写槽里:被摘要替换后,没有 compact 结果时也不会再写一份。
+- retry 后不留下重复的 hook 上下文。
 - `Stop continue:true + additionalContext` 会继续一轮模型请求,并受连续次数上限保护。
 - `PreToolUse additionalContext` 在 tool 成功、失败和拒绝路径都作为工具批次后的附件进入下一次模型请求。
 

+ 1 - 1
apps/zcode-cli/docs/design/v2/ink-tui-renderer.md

@@ -83,7 +83,7 @@ The controller interface exposes user intents rather than raw rendering details:
 - `setInput(value)`
 - `submitInput(value)`
 - `handleKey(input, key)`
-- `requestPermission(request, options)`
+- `requestPermission(request, options)`(挂载时经 `registerPermissionRequester` 登记一次,不随提交传递)
 - `stop(code)`
 
 Permission and clarification prompts stay promise-based at the runtime boundary,

+ 250 - 26
apps/zcode-cli/docs/design/v2/loop/meta-user-context.md

@@ -47,6 +47,100 @@ non-empty list adds two more newlines, the existing list heading, two newlines,
 and numbered items inside brackets. Provider projection preserves this body for
 both MCS and user-side reminder delivery.
 
+## Total-tokens reminder
+
+The model sees a token budget in two places. The budget is fixed at 15000000;
+there are no modes and no configuration. It applies to every provider and model.
+
+1. The system prompt ends with the line
+   `<total_tokens>15000000 tokens left</total_tokens>`. See
+   [System prompt contract](system-prompt-contract.md). A custom system prompt
+   does not get this line, but the reminders below are still collected.
+2. Input attachment collection adds a `total_tokens_reminder` with the body
+   `<total_tokens>N tokens left</total_tokens>`.
+
+The runtime keeps one counter per runtime: one for the main session and one per
+subagent or workflow child. "Context" is the `input + output` usage of the
+latest assistant entry that has usage, or 0 when there is none (for example
+right after a compaction, whose kept assistants carry no usage). The input
+already includes cache reads and writes. When the output is 0 (old records store
+a missing output as 0), the context is the total if the total is at least the
+input; otherwise it is the input alone.
+
+Two kinds of assistant entries carry no usage, so the counter keeps using the
+earlier usage after them:
+
+- A response with server-side tool rounds. Its usage is the sum of several
+  internal requests, not the size of one context.
+- An assistant that stream recovery builds from the tool calls that finished
+  before the stream failed.
+
+```text
+counter (runtime memory, reset by resumeFromStore)
+  anchor  = rolled + context at the latest re-anchor
+  rolled  = sum of the pre-compaction context of every auto or reactive compaction
+  used    = max(previous used, rolled + context - anchor); a re-anchor sets it to 0
+  N       = max(0, 15000000 - used)
+```
+
+The collection reason decides the outcome. It is recorded where collection is
+requested, not guessed from history:
+
+| Collection reason                                                                                                                                                                                                 | Reminder                      | Re-anchor            |
+| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | -------------------- |
+| `turn_input`, main session, the turn input is a real user prompt: a user input with no input presentation (typed, queued, send-now, modified submit, remote or bot input, expanded slash command, scheduled turn) | yes                           | yes, so N = 15000000 |
+| `turn_input`, other inputs (goal continuation, coordinator input, subagent or workflow task)                                                                                                                      | no                            | no                   |
+| `tool_batch` (after a completed tool batch, also when guides or notifications were drained with it)                                                                                                               | yes, after the drained inputs | no                   |
+| `text_guide` (guides drained after a text-only reply), main session, at least one drained guide was typed by the user (`user_steer`: App, remote or bot input)                                                    | yes                           | yes                  |
+| `text_guide`, other guides only (session mailbox, tool follow-up, coordinator), or a subagent or workflow child                                                                                                   | yes                           | no                   |
+
+A new-turn `task_notification` or `subagent_reply` skips all input attachments
+on its first request, so it gets no reminder and does not re-anchor. Requests
+that resend the same input (Stop hook continuation, model fallback, stream
+recovery, context-exceeded recovery, output-token recovery) do not collect.
+
+Compaction:
+
+- Only auto and reactive compaction add the pre-compaction context to `rolled`.
+  A manual `/compact` does not; the next real prompt re-anchors anyway.
+- The reminder collected before an auto compaction sits in the kept tail. The
+  summary request and the first request after compaction add no new reminder.
+  The next tool batch includes `rolled`.
+
+Resume, fork and idle release start a fresh counter. Until the next real
+prompt, the value counts from 0 (for example, a notification turn that calls a
+tool after resume shows 15000000 minus the whole current context). Rewind does
+not change the counter.
+
+The body is persisted like `silent_turn_reminder` (persist, then commit), so
+resume restores the same bytes and later requests only append. Projection
+follows the common rules: with MCS it joins the run's system message with
+`\n\n` (before `Today's date` on the first request); without MCS it is a
+`<system-reminder>` user block, folded into the tool result on Anthropic and a
+separate user message on OpenAI-compatible protocols.
+
+```text
+<total_tokens>15000000 tokens left</total_tokens>          first request of a turn
+ok\n\n<system-reminder>\n<total_tokens>14998995 tokens left</total_tokens>\n</system-reminder>
+                                                            tool result, MCS off, input 1000 + output 5
+```
+
+A turn can stop after its tool results (user Stop, send-now, modified submit).
+The next turn's reminder follows the same rules. It moves back past the user
+inputs after those results (drained guides, the `[Request interrupted by user]`
+marker, the new prompt) and stops after the tool result. So the last part of the
+stopped request changes: without MCS it folds into the same tool result after
+the earlier reminder, if there is one; with MCS it joins the earlier reminder in
+the run's system message, which now comes after the new prompt. The new prompt
+and the marker stay separate user text, and all other content only appends.
+
+```text
+stopped request   user[ tool_result("ok\n\n<sr>14998995</sr>") ]
+next request      user[ tool_result("ok\n\n<sr>14998995</sr>\n\n<sr>15000000</sr>"), prompt ]     MCS off
+stopped request   user[ tool_result("ok") ], system("<tt>14998995")
+next request      user[ tool_result("ok"), prompt ], system("<tt>14998995\n\n<tt>15000000")    MCS on
+```
+
 ## Ownership and assembly
 
 ContextBuilder renders resolved snapshots; it performs no host IO. Stable and
@@ -175,8 +269,34 @@ no model identity or Git details. The run's additional directories
 (`runtimeConfig.additionalDirectories`, set when the runtime is created or cold
 resumed) follow the repository bullet as ` - Additional working directories:`
 with one `  - <path>` line per path, in configured order; an empty list emits
-nothing. Ordinary subagents do not inherit the list. No worktree, scratchpad,
-or other unsupported capability is advertised.
+nothing. Ordinary subagents do not inherit the list. When the run is shown in
+ZCode Desktop (presentation surface `zcode_desktop`, and the context builder
+adds the `desktop_context` section: not with a custom system prompt, for a
+workflow actor or for a subagent), the environment carries the ZCode Desktop
+part. Its snapshot records `desktopContext: true`; when the host supplies a Gen
+UI output directory, the session's directory follows as
+` - Visualization directory for this session: <path>`; otherwise the bullet is
+absent. After the last bullet, the full block adds a blank line and the ZCode
+Desktop Context text (`docs/desktop/zcode-desktop-context.md`), whose Gen UI
+paragraph has two forms: with a directory and without one. Surface, rollout
+switch, Gen UI availability and the directory are process or session facts, so
+the system prompt holds none of them; a prompt snapshot can stay unchanged
+while they change. A fork writes an update with the child's directory into the child history,
+after the copied messages and before the fork notice. It does not wait for the
+child's next attachment collection: the child's first request can be a
+new-turn notification, which does not collect attachments. When the child runs
+in another working directory (a fork into a managed worktree), the update also
+states the new `Primary working directory`, and the child's directory is
+computed for that working directory: the directory is keyed by the workspace
+identity (or, without one, the workspace path) and the session id, the same key
+the child's own announcements use. A local worktree child has no workspace
+identity, and its workspace path is its working directory. The baseline is the
+latest announcement in the child's model view (after the last compaction). When
+that view has no announcement, the fork writes nothing and the child's next
+announcement is a full block; when it has one without a directory and the fork
+does not move the child to another working directory, the fork also writes
+nothing. No
+worktree, scratchpad, or other unsupported capability is advertised.
 
 `model` describes only the executing Model's existing providerId/modelId using
 `You are powered by the model named <providerId>/<modelId>.`. It is separate
@@ -203,7 +323,9 @@ loop iteration (one model request)
                       -> tool_search_announcement
                       -> agent_listing_delta -> skills_listing -> plan_mode_exit
                       -> runtime_mode -> todo_reminder
-                      -> silent_turn_reminder -> output_style -> memory_update
+                      -> silent_turn_reminder -> total_tokens_reminder
+                      -> output_style -> memory_update
+                      -> hook_context (UserPromptSubmit, first collection of the turn only)
   settled project-memory recall              (memory prefetch after attachments)
   microcompact / auto-compact
   request announcements   context_prefix -> session_context -> date
@@ -213,7 +335,9 @@ loop iteration (one model request)
 Input attachments are collected before compaction, and only at three points:
 the first request for the turn input, the first request after a completed tool
 batch (this includes tool results that stream recovery or model fallback
-settles), and the first request after a text-only reply drains a guide. Items
+settles), and the first request after a text-only reply drains a guide. The
+loop state records which of the three points requested the collection
+(`turn_input`, `tool_batch`, `text_guide`); `total_tokens_reminder` reads it. Items
 produced for the turn input or the last tool batch therefore belong to the
 history that compaction keeps or summarizes. The other loop iterations send the
 same input again and do not collect: Stop hook continuation, model fallback,
@@ -245,9 +369,13 @@ the latest `runtime_mode` / `plan_mode_exit` entry is a `runtime_mode`; the
 in-memory exit flag set on leaving plan mode is an extra trigger.
 The ToolSearch announcement is the deferred-tools delta and sits (after model, before the agent listing); its body, delta
 metadata and persistence follow [ToolSearch](../tool/19-tool-search.md).
-Each item keeps its own persistence. Event-time attachments (rewind, shell or
-goal changes, resume, compact, hooks, tool warnings, prompt attachments) are not
-part of either collector.
+Each item keeps its own persistence. The `UserPromptSubmit` hook context is the
+last item of the first collection of a turn (the hook ran before the input was
+written); later collections of the same turn do not repeat it. Event-time
+attachments (rewind, goal changes, resume, compact, SessionStart and
+Stop hook context, tool warnings, prompt attachments) are not part of either
+collector. Lifecycle hook context rules are in
+[hooks](../hooks.md) ("生命周期 Hook 上下文的持久化").
 
 Request announcements run before every model request, after compaction,
 including output-token recovery. Each source is announced when history has no
@@ -297,8 +425,13 @@ Git details; there is no fallback to full context resolution. A runtime restored
 from the store (cold resume) did not read the stored facts itself, so its first
 environment notice re-reads them through `resolveEnvironment` once, also when the
 directory is unchanged. From that read it takes only the repository boolean;
-platform, shell and OS version keep the history values. A difference is
+platform and OS version keep the history values. A difference is
 announced as an update. A live runtime does not re-read an unchanged directory.
+The shell is the display name of the runtime's Bash shell selection when it has
+one. New and cold-resumed runtimes read the current shell setting, so a shell
+changed between runtimes is announced like a directory change; a live runtime
+keeps its selection
+([Bash Effective Shell Snapshot](../../../../../../docs/runtime-tools/bash-effective-shell-snapshot.md)).
 A config-only
 runtime without a context port can update cwd/shell only; host facts remain
 supplied by its configuration. The cwd and shell are read once before the IO,
@@ -308,15 +441,30 @@ retry: the next request compares the latest announcement with the current
 state and announces the change then.
 
 The first notice is `# Environment`. With a full block still present in active
-history and unchanged platform, shell and OS version, changes to cwd and the
-repository boolean use `# Environment update` and only changed bullets:
+history and unchanged platform and OS version, changes to cwd, the
+repository boolean and the shell use `# Environment update` and only changed bullets:
 ` - Primary working directory: <new> (was <old>)` and
 ` - Is a git repository: <new> (was <old>)`. Additional-directory changes add
 ` - Additional working directories added:` and
 ` - Additional working directories removed:`, each followed by its `  - <path>`
-lines; order is cwd, repository, then directories. Returning to an earlier directory
+lines. A changed visualization directory adds
+` - Visualization directory for this session: <new> (was <old>)`; a new one
+(older metadata has none) adds ` - Visualization directory for this session: <new>`,
+and a removed one adds ` - Visualization directory for this session: none (was <old>)`.
+A changed shell adds ` - Shell: <new> (was <old>)`; when the previous shell is
+empty (older Windows sessions), it adds ` - Shell: <new>`.
+Order is cwd, repository, directories, the visualization directory, then the shell.
+The ZCode Desktop part is compared by its form: none, with a Gen UI directory,
+or without one; older metadata has no `desktopContext` and counts as none. A
+changed form is added after the bullets, with a blank line between: the whole
+ZCode Desktop Context text in the new form or, when the run is no longer shown
+in ZCode Desktop,
+`The ZCode Desktop Context above no longer applies: this session is not shown in ZCode Desktop.`
+When only the Desktop part changed, the update is that text alone, without the
+`# Environment update` heading. A fork that changes only the directory keeps
+the form. Returning to an earlier directory
 compares against the latest announcement, not the initial environment.
-Platform/shell/OS changes require a new full block. Missing, malformed or
+Platform/OS changes require a new full block. Missing, malformed or
 legacy snapshot metadata, or a history with only updates after compaction,
 also requires a full block. Unchanged snapshots emit nothing. Snapshot
 metadata is cloned and validated on restoration and never sent to providers.
@@ -333,19 +481,95 @@ update is in memory only. The stored record keeps its first content and fixes
 only the position, and every load applies the update again. A changed catalog
 therefore changes earlier request bytes once (one prompt-cache miss); an
 unchanged catalog changes nothing. There is no per-skill delta.
-`context_prefix` is announced once when history has none. A running runtime does
-not compare or refresh it: the runtime reads the instruction files and the
-Memory index once, when it starts (no instruction change notice yet). Each time
-history is loaded from the store (cold resume, rewind), the restored
-`context_prefix` entries are updated in place to the runtime's current content,
-the same as `skills_listing`: changed content replaces the old content at the
-same position, and empty current instructions remove them. The update is in
-memory only. The stored record keeps its first content and fixes only the
-position, and every load applies the update again. Thus the model sees the
-Memory index that the runtime read from disk. Read-file state records the same
-content for `MEMORY.md`, so a Write to `MEMORY.md` is checked against the
-content that the model saw. Changed content changes earlier request bytes once
-(one prompt-cache miss); unchanged content changes nothing. Dates always use the runtime clock, including the
+`context_prefix` is never rewritten after it is sent. Changes are announced by
+appending a new `context_prefix` entry (an instruction delta), so the request
+prefix stays byte-stable across cold resume, rewind and later requests.
+
+- **When files are read.** The runtime reads the instruction files and the
+  Memory index when it starts (new session, cold resume) and again at the end
+  of each compaction. It does not read them between those points; an edit in
+  the middle of a runtime is announced only after the next compaction or by
+  the next runtime. Rewind does not read them again. The compaction re-read is
+  adopted only when the compaction commits; a failed or cancelled compaction
+  leaves the held content unchanged.
+- **Read errors.** A file counts as removed only when it is missing. For an
+  instruction file that is not found, a directory or not a regular file, or a
+  path segment that is not a directory. For the Memory index, the file system
+  port codes `not_found`, `is_directory` and `not_file`; the port reports a path
+  segment that is not a directory as `io_error`, so for the Memory index that
+  case is unreadable. Any other read error (permission denied, busy, I/O error) makes
+  the file unreadable; it is not a removal, and the runtime logs a warning
+  (`context.instructions.read_failed`). A path whose existence check fails
+  with such an error is still the candidate; the search does not go on to a
+  parent directory. At a runtime start an unreadable path is never listed in
+  `removed`, so the model keeps the copy it was told; the other files are
+  compared as usual. At the end of a compaction, when an unreadable path is a
+  file the runtime holds, the whole re-read is dropped, the same as a failed
+  re-read (held content and reason stay). An unreadable path that the runtime
+  does not hold does not block the re-read. The next start or compaction reads
+  the file again. Known limit: a file that is unreadable at the runtime start
+  is not held, so a full block that a later compaction places before the
+  summary does not have it until a read succeeds.
+- **Baseline from history.** Each `context_prefix` record stores, in runtime
+  metadata that never reaches the provider, the files it announced:
+  `{ path, type, hash }` for each file (`hash` = sha256 of the trimmed body),
+  plus `removed` paths and a `reason` for a delta. The announced state is the
+  last full record (no `reason`) with every later delta applied in order:
+  `files` replace entries with the same path, `removed` deletes them. A legacy
+  record without this metadata is a full record; its files come from its
+  `Contents of <path> (<type>):` headings.
+- **Every request.** Before each model request the runtime compares the
+  announced state with the files it holds. The held files get their hash once,
+  when the runtime builds them from a read (start, compaction, a config
+  change); a request compares stored hashes and hashes nothing, except a legacy
+  record without metadata, whose headings it splits and hashes. The comparison
+  runs on every request although the held files change only at a read, because
+  history changes between reads (rewind, compaction, a delta that was not
+  saved) and the baseline is derived from history alone. No baseline: announce the full block
+  (unchanged format). A file that is new or whose type or hash differs: append
+  one delta. A baseline path that is no longer current: list it in `removed`.
+  No difference: append nothing. A second cold resume with unchanged files
+  therefore appends nothing.
+- **Reason.** The delta reason is runtime state: `session_start` when the
+  runtime starts, `compaction` from the moment a compaction commits its
+  re-read. A compaction without a re-read (subagent, read failure) does not
+  change it. A resume from the store (also when it reuses the same runtime)
+  sets it back to `session_start`, because the files it compares were read at
+  that resume. A rewind keeps it.
+- **Compaction.** The leading announcements before the summary check the kept
+  tail. For `context_prefix` the kept tail counts only when it holds a full
+  record; a kept delta does not count. So the leading entry is the full block
+  or nothing, never a delta:
+  - kept tail holds a full record: nothing before the summary; a difference is
+    appended as a delta (reason `compaction`) by the next request;
+  - kept tail holds no full record and is not empty: the full block before the
+    summary, built from the re-read content;
+  - kept tail is empty: no leading announcements; the next request announces
+    the full block.
+
+  Known edge: when the kept tail holds only a delta, that delta comes after the
+  leading full block, so the next request sees its older copy as the latest
+  and appends one more delta for the same files.
+
+- **Delta text.** Changed and new files share one sentence:
+  `Instruction files were re-read <reason>; these differ from their earlier copies — each replaces its earlier copy, and the instructions preamble above still applies:`
+  followed by a blank line and the same `Contents of <path> (<type>):` blocks
+  as the full announcement. Each removed path adds a paragraph
+  `Instructions no longer present: <path>`. When only files were removed, the
+  first paragraph is `Instruction files were re-read <reason>.`. Paragraphs are
+  joined by a blank line. `<reason>` is `when this session started`
+  (`session_start`) or `after the conversation was compacted` (`compaction`).
+- **Memory index.** `MEMORY.md` is one file of the same announcement (type
+  `user's auto-memory, persists across conversations`). Read-file state records
+  the content the runtime read (at start, and again after compaction once the
+  compacted read state is installed), which is the latest content the model
+  was told. A Write to `MEMORY.md` is checked against that content.
+
+A delta keeps the `context_prefix` source, so it stays on the user side under
+MCS like the full block. An older CLI that still updates restored
+`context_prefix` entries in place would turn a delta into a second full copy;
+the model then sees the instructions twice, but the session still works.
+Dates always use the runtime clock, including the
 first announcement after compact; the session-start context snapshot date is
 not reused. Subagent runtimes inherit the parent clock.
 
@@ -421,6 +645,6 @@ Tests cover initial placement and order with and without MCS, the newline
 before a real user input, MCS downgrade, consecutive
 requests, executing model changes, date rollover, cross-day compact, resume,
 Skill listing restated by compaction, updated in place after a history load
-(removed for an empty catalog) and not repeated for an unchanged catalog, `context_prefix` updated in place after a history load (cold resume and rewind) with the Memory index that read-file state records, Git reuse by history, Git read after a non-repository start or a non-repository compaction, one file system check per non-repository directory (including a non-repository prefetch), a repository with a hung or missing git still detected, parallel snapshot commands, prefetch only for a new session, custom/subagent
+(removed for an empty catalog) and not repeated for an unchanged catalog, `context_prefix` kept byte-stable after a history load with an appended delta for a changed, new or removed instruction file or Memory index (none for unchanged files, none again on a second cold resume, legacy records without metadata), the compaction re-read (delta with a kept baseline, full block without one, Memory read state after compaction), read errors (an unreadable instruction file or Memory index not announced as removed on resume; a compaction re-read dropped when a held file is unreadable and adopted when the unreadable file is not held; adapter: an unreadable file reported as a read failure, a missing one as nothing, no fallback to a parent file when the check fails), Git reuse by history, Git read after a non-repository start or a non-repository compaction, one file system check per non-repository directory (including a non-repository prefetch), a repository with a hung or missing git still detected, parallel snapshot commands, prefetch only for a new session, custom/subagent
 boundaries, and truncation at both limits. Prompt changes do not alter App input
 or tool execution UI.

+ 1 - 1
apps/zcode-cli/docs/design/v2/loop/model-anomaly-fallbacks.md

@@ -25,7 +25,7 @@
 1. **长程任务优先**:tool call 计数只作为 telemetry/诊断输入,不作为 runtime 闸门;默认不限制调用次数。
 2. **异常兜底可观测**:所有重试、compact、fallback 都要发事件,并携带 `traceId`、`turnId`、`spanId` 或可关联的父子关系。
 3. **模型先自纠偏**:如果未来引入异常 warning,也只能作为模型可见提示,不禁用工具、不抛 `ToolMaxCalls`、不直接结束 turn。
-4. **资源边界仍可硬保护**:工具超时、输出大小、进程取消、权限拒绝、用户中断、不可恢复 provider error 可以硬失败或中断。
+4. **资源边界仍可硬保护**:工具超时、输出大小、进程取消、权限拒绝、用户中断、不可恢复 provider error 可以硬失败或中断。单个工具的资源预算也属于这一类,例如动态工作流子代理每个 ask 的 WebSearch 次数(`tool/13-websearch.md`):超出预算只让该工具回模型可见的错误,不改 tools 列表、不结束 turn,也不计其他工具的调用次数,因此不是 tool call 数量上限。
 5. **不要吞错误**:低层错误保留原始原因;只有 loop 边界负责决定是否转成模型可见 warning、用户提示或 turn error。
 
 模型网络 retry 由 ZCode adapter 自己执行,不使用 AI SDK 内部 retry。默认重试次数为 10,对应事件里的 `maxAttempts = 11`;日志需要同时记录 `maxAttempts` 和派生的 `maxRetries`。退避策略应支持指数退避、jitter、`retry-after-ms` 和 `retry-after`,其中 provider header 只有在等待时间合理时才覆盖本地退避。

+ 99 - 0
apps/zcode-cli/docs/design/v2/loop/prompt-snapshot.md

@@ -0,0 +1,99 @@
+# Prompt Snapshot
+
+Status: current behavior. Scope: main sessions (`querySourceForTask(taskType) === "main_turn"`) with a
+session store. Subagents and workflow actors do not use a snapshot.
+
+## Purpose
+
+Provider prompt caches match the request prefix byte for byte, in the order tools → system →
+messages. Without a snapshot, the system blocks are rendered from the current code on every
+request. A new CLI version that changes a prompt section then changes the prefix of every older
+session after a cold resume. The snapshot records the system blocks a session sent and keeps
+sending them.
+
+Tools are not recorded. Each request sends the tool list prepared from the current registry. MCP
+servers connect after the first request can start and can change their tools during a session, so a
+recorded tool list cannot stay fixed; a changed tool list changes the cache prefix from the tools
+onward.
+
+## Data
+
+One `session_entry` row per session:
+
+- type `runtime/prompt_snapshot`, id `<sessionId>:runtime-prompt-snapshot`, written with
+  `touchSession: false` (it does not change the session list order);
+- data:
+
+```text
+{
+  model:  { providerId, modelId }          the session model the snapshot was rendered for
+  system: [{ role: "system", content, cacheControl? }, ...]   the leading system messages
+}
+```
+
+or the tombstone `{ cleared: true }`. The row is overwritten in place. No table changes are needed:
+`session_entry.type` is free text and `data` is JSON. Older CLI versions read only the entry types
+they know, so they ignore this row.
+
+The snapshot stores no version and no projection flags. Two values that differ per process or per
+session are kept out of the system blocks: the ZCode Desktop part (presentation surface, rollout
+switch, Gen UI availability) and the Gen UI visualization directory are part of the environment
+announcement (see `meta-user-context.md`). The other system content is frozen until compaction by
+design, also when a later launch would render it differently: the memory section (memory root and
+switch), the identity sentence that the output style selects, and a custom system prompt.
+
+## Reading and writing
+
+The runtime loads the row when it restores a session (cold resume). A read failure or an invalid row
+counts as no snapshot and never blocks the restore. A new session starts without one.
+
+- **Use.** A request uses the snapshot when its model has the snapshot's provider id and model id
+  (the reasoning level is not compared).
+- **Record.** When no snapshot applies, a main-loop request records one if its model is the session
+  model selection and the turn is not pinned to an execution model
+  (`modelSelectionScope !== "execution"`). The new row replaces the old one.
+- **Session model change.** A guide input or an off-peak takeover that changes the session model
+  selection is a session model change: the next request records a new snapshot for the new model.
+- **Temporary models.** Model fallback, off-peak execution, compaction summaries, memory
+  extraction and goal verification never write the snapshot. They use it only when their model is
+  the snapshot model.
+
+## System
+
+`rebuildContextPrefix` builds the system messages from the current code, then replaces them with the
+snapshot's system messages when the snapshot applies to the model the prefix is built for. The
+conversation history therefore carries the frozen prefix, and every request that reads the history
+(main loop, compaction, memory extraction) sends the same bytes. Announcements still use the fresh
+build result. A record captures the leading system messages of the request that records it.
+
+## Compaction, fork, rewind
+
+- After a successful compaction (manual, auto or reactive) the snapshot is cleared: the runtime drops
+  its copy, writes the tombstone, and rebuilds the context prefix of the history and of the entries
+  it returns from the current code. The next main-loop request records a new snapshot. A skipped
+  compaction and microcompaction keep the snapshot.
+- A main session writes the tombstone on every successful compaction, also when the runtime holds
+  no copy. A failed read at resume leaves the runtime without a copy while the row still holds the
+  snapshot from before the compaction; without the tombstone, the next cold resume would apply that
+  system to the window after the compaction.
+- A fork copies the parent's current row to the child session (with the child session id). The
+  child's system bytes equal the parent's current system. When the fork point is after the parent's
+  latest compaction, the child's first request can reuse the parent's cached prefix. When the fork
+  point is before that compaction, the copied snapshot belongs to the window after it while the
+  child's history belongs to the window before it: the cached prefix matches only if the system did
+  not change between the two windows. The fork writes an environment update with the child's own
+  visualization directory into the child history, after the copied messages (see
+  `meta-user-context.md`).
+- Rewind does not change the snapshot.
+
+A system section added by a later CLI version (for example the token budget line, see
+`system-prompt-contract.md`) reaches an existing session only after its next successful compaction
+or session model change. Until then the session keeps its recorded system bytes; reminders that the
+new version adds to the history are appended and do not change the sent prefix.
+
+## Failure and compatibility
+
+- A failed write logs a warning and the request continues.
+- Clearing the snapshot and committing the compaction are separate writes. A crash between them
+  leaves the old snapshot until the next compaction or session model change.
+- Cold hydration reads all session entries, so it decodes one snapshot row per session.

+ 17 - 4
apps/zcode-cli/docs/design/v2/loop/system-prompt-contract.md

@@ -4,6 +4,11 @@ ZCode stable system prompt is the long-lived behavioral contract for the main
 agent. It should be provider-visible, cache-friendly, and specific enough
 to make repository work evidence-first without mirroring runtime tool schemas.
 
+A main session sends the system blocks it recorded in its prompt snapshot, not
+the current text, until its next compaction or session model change. Changes
+to this contract reach existing sessions only at those points; see
+[Prompt Snapshot](prompt-snapshot.md).
+
 ## Goals
 
 - Fix the agent identity to `zcode-agent`; callers must not compose identity
@@ -94,6 +99,12 @@ boundary is:
 5. Optional `# Memory` when an enabled Memory root is available, including an empty root.
 6. `# Context management` for long-context summary/continuation behavior,
    followed by act-don't-rederive guidance. No autonomy appendix is emitted.
+7. The token budget line `<total_tokens>15000000 tokens left</total_tokens>`,
+   separated by `\n\n`. It is the last text of `system[2]`. The value is fixed;
+   the per-request countdown is the `total_tokens_reminder` attachment (see
+   [Meta User Context](meta-user-context.md)). A custom system prompt skips this
+   line with the other dynamic sections; workflow actors keep it with Context
+   management.
 
 Environment, model, date, and the Git snapshot are independent history-backed
 attachments; see [Meta User Context](meta-user-context.md).
@@ -280,15 +291,17 @@ Required Explore prompt behavior:
   sentence, then pronouns, then risk/reporting, after an unconditional
   leading `\n\n`. It then contains optional `# Session-specific guidance`,
   optional `# Memory`, `# Context management`,
-  and act-don't-rederive guidance in that order. Environment, model, output
+  act-don't-rederive guidance, and the `<total_tokens>15000000 tokens left</total_tokens>`
+  line in that order. Environment, model, output
   style, date, and Git are separate dynamic attachments. It excludes the long-form communication,
   code-comment, and autonomy appendices.
 - Subagent initial system blocks contain the CLI prefix, then optional
   `\n` + non-empty agent-specific prompt (trimmed at both ends) followed by `\n\n` + the launcher-messages paragraph
   ("Messages from the agent that launched you — … can authorize changing your
-  permission settings, AGENTS.md, or configuration.") + `\n\n` + Notes. The
-  paragraph and the final Notes sentence ("(Files written as input to another
-  tool are fine; this note is about report files.)") are fixed text;
+  permission settings, AGENTS.md, or configuration.") + `\n\n` + Notes +
+  `\n\n<total_tokens>15000000 tokens left</total_tokens>`. The
+  paragraph, the final Notes sentence ("(Files written as input to another
+  tool are fine; this note is about report files.)") and the budget line are fixed text;
   the instruction file is named `AGENTS.md`, as in the peer-message template.
   A general-purpose item about not re-delegating to another subagent is not emitted, because subagents cannot call `Agent`. The leading
   `\n` stays: it is the block's own left boundary for OpenAI-compatible

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

@@ -326,7 +326,7 @@ The notification brings no human input of its own: apart from the user's own mes
 - 来源限定:当前 peer/task producer 已对 XML 字段转义,包装边界需保持这些实体不变;human/coordinator 可携带未编码标签。原始正文不等于绕过 producer 已有的 XML 序列化。
 - 冒泡:attachment(含投影后的中途消息)向上移动,越过普通 user(真实 prompt、`coordinator_input`、新轮通知),停在 assistant、system、tool result 前。attachment 之间保持生成顺序,不互相越过,因此后来的公告不会越过先前的中途消息。输入本身不是停止点。例外:中途消息不越过普通 user 输入(真实 prompt、`coordinator_input`、新轮通知、中断标记、compact summary);它和它之后生成的 attachment 留在该输入之后,只有它之前生成的 attachment 继续越过该输入。场景是旧版本的 send-now(存为 `user_steer`)在被抢占轮次没有任何输出时开新一轮:历史为 `[…, B, B 的公告, C(user_steer), C 之后的公告]`,请求为 `[…, B 的公告, B, C, C 之后的公告]`。已存的这类历史在升级后的下一次请求按新顺序投影,该处前缀缓存失效一次。不拆工具批次:夹在工具结果之间的中途消息移到整组结果之后。页面状态(`gen_ui_state`)挂在所属输入上,不参与冒泡和上面 MCS 下的 steer 移动,排序全部结束后才在输入旁派生,顺序见 [GenUI 模型上下文](../../../../../../docs/specs/gen-ui-model-context.md)。每条只表达一次,不创建空 user。普通请求、compact、verifier 复用共享投影,最终 wire 不含内部标记。
 - MCS 落点:同一段 user run(两条 assistant 之间)里的 MCS 文本按顺序用 `\n\n` 合成一条 system,放在 run 末尾,即下一条 assistant 前或请求末尾,可以越过 run 内的 user(真实 prompt、新轮通知)。run 末尾不是 user/tool 时(例如 text-only assistant 之后只有 MCS 文本),整组降级为一条 user `<system-reminder>`,只包一次。
-- 换行按相邻 user 合并处理,只在会把相邻 user 内容合成一条消息的协议上生效(Anthropic;与并入 tool result 用同一个协议开关)。OpenAI 兼容协议不合并 user,不补换行,否则会改写上一次请求的最后一块。规则:user 输入消息(真实 prompt、`coordinator_input`、新轮通知)紧跟 user 文本时,前一条以换行结尾;前一条是 tool result(含已并入 tool result 的提醒)时不补,换行在并入之后判断;attachment 跟在 user 文本之后不补。OpenAI 兼容协议的已存会话在升级后的下一次请求不再带这个换行,该处前缀缓存失效一次;Anthropic 字节不变。
+- 换行按相邻 user 合并处理,只在会把相邻 user 内容合成一条消息的协议上生效(Anthropic;与并入 tool result 用同一个协议开关)。OpenAI 兼容协议不合并 user,不补换行,否则会改写上一次请求的最后一块。规则:user 输入消息(真实 prompt、`coordinator_input`、新轮通知)紧跟 user 文本时,前一条以换行结尾;输出达到上限后追加的 Continue 提示同样处理(它也会直接接在 user 文本后面:前一条回复只有思考、被删除;零输出截断没有留下 assistant;提醒冒泡到它前面);前一条是 tool result(含已并入 tool result 的提醒)时不补,换行在并入之后判断;attachment 跟在 user 文本之后不补。OpenAI 兼容协议的已存会话在升级后的下一次请求不再带这个换行,该处前缀缓存失效一次;Anthropic 字节不变。
 - 每种 presentation 的角色只在 `incoming-message.ts` 的角色表定义一次:`coordinator_input` 为 prompt,新轮 `task_notification` / `subagent_reply` 为 new_turn,`*_steer` 为 mid_turn。mid_turn 投影为 attachment;带图片等媒体时 attachment 无法承载,保留 user 消息形态:文本块用 `\n` 连接后只包装一次放在首块(加 `<system-reminder>`,MCS 开关相同),媒体按原顺序在后,合并规则仍同 attachment(不补换行、不并入 tool result);prompt 与 new_turn 是普通 user 输入;new_turn 另外决定本轮起点跳过输入附件收集。latest-real-user、Memory 查询等身份规则不变。
 - 2026-10-15 回溯:早先把所有带标记的输入当作冒泡停止点和 MCS 截断点,用来防止后来的 reminder 越过中途消息。根因是中途消息自身不参与冒泡;改为 attachment 之间保持顺序后不再需要停止点。新轮输入作为停止点没有依据,并导致通知轮请求以公告结尾。
 - 新轮 `task_notification` / `subagent_reply` 开启的轮次,首个请求跳过全部输入附件收集;请求前公告(instructions、session_context、date)照常运行并冒泡到通知之前。工具调用之后照常收集。判断只看历史中最后一条非 attachment 消息,不新增状态。详见 [Meta User Context](meta-user-context.md#dynamic-history)。

+ 20 - 13
apps/zcode-cli/docs/design/v2/memory/README.md

@@ -82,7 +82,7 @@ read-only/writable capability,不提供旧配置 alias,也不提供自定义
 Main turn 后的自动 Background Extraction;Main Memory prompt、`MEMORY.md`、Selector/Recall、Dream
 handler、custom-agent Memory 与 session persistence 均保持原行为,也不提供远端 rollout gate。
 
-Desktop/Web Settings 另提供 app-global `memoryEnabled` 开关,默认为 `false`。它是
+Desktop/Web Settings 另提供设备级 `memoryEnabled` 开关,默认为 `false`。它是
 现有 CLI Memory 配置外层的 kill switch:
 
 ```text
@@ -115,8 +115,9 @@ Settings 写入 memoryEnabled
   `true` / `false` 继续保留,不做一次性迁移。
 - 新建根 Session 和应用重启后的真正 cold resume 读取最新值。fork、
   selection side chat 与 subagent 继承父 Runtime 已冻结的值,不再读 Settings。
-- 本地 workspace 由所在 Host 直接读取 SettingService;desktop-attached remote
-  复用 desktop shared Host 的同一 app-global 权威源。relay/main 不保存副本。
+- 本地 workspace 与 R3 远端 workspace 分别由所在 Host 读取自己的 SettingService;
+  Desktop 记忆页可选择设备,经 source-settings 修改远端开关,不同步本机值。
+  relay/main 不保存副本。见 `docs/remote/memory-settings.md`。
 - `memoryEnabled=false` 时,该 Runtime 不创建 project/custom Memory root,不注入
   Main/custom Memory prompt,不运行 Recall、Extraction 或 Dream,也不产生任何
   Memory 专用模型请求。
@@ -342,8 +343,9 @@ prompt 约束;Runtime 不增加
 断点前的尾随空白;断点前的内容不超过 40 字符或没有空白时,改用前 79 个码元去掉尾随空白;
 最后加 `…`。
 Memory 规则仍在 system,索引正文和指令文件保留在 `context_prefix`,其中不再
-混入日期、通用 context intro 或自动附加说明尾句。`context_prefix` 是动态公告:
-运行中不随文件变化刷新;冷恢复与 rewind 时按当前文件原位刷新(见 `loop/meta-user-context.md`)。
+混入日期、通用 context intro 或自动附加说明尾句。`context_prefix` 是动态公告,发出后不再改写:
+运行时启动时和每次 compaction 收尾时读取文件;内容变化时在末尾追加一条增量公告
+(见 `loop/meta-user-context.md`)。
 
 ### 4.1 Foreground 工具权限
 
@@ -490,9 +492,14 @@ user turn
 
 ## 6. Background Extraction
 
-Extraction 只在 `memory.extractionEnabled !== false`、成功、非 remote、无 child `agentId` 的
+Extraction 只在 `memory.extractionEnabled !== false`、成功、无 child `agentId` 的
 Main-equivalent turn 后 fire-and-forget。默认前台答复不等待它。
 
+SSH/WSL/Docker 等 remote workspace 同样提取。remote CLI 运行在远端机器上,是执行 agent loop
+的一侧,不是只做展示和转发的瘦客户端;Extraction 与 Main turn 共用该 Runtime 的 model、
+fileSystemPort 与 sessionStore,结果写入远端的 Project Memory root。是否运行只由该设备的
+`memoryEnabled` 与上面的条件决定,见 `docs/remote/memory-settings.md`。
+
 默认 headless gate 必须早于 enabled-root 解析与 snapshot acquisition:
 
 ```text
@@ -551,9 +558,6 @@ error/abort cursor 规则保持;provider/工具失败仍按现有后台 Extrac
 配合受控 provider,证明主请求已完成且 Extraction 响应被阻塞时进程仍存活,释放响应并落盘后才退出。
 同时覆盖默认 headless 无 Extraction、Memory 关闭的前置失败与 session close 取消回归。
 
-remote 判定由 bootstrap 通过语义化 runtime dependency 注入,并在调用时读取当前
-`workspaceIdentity`;core 不复制 remote identity 解析规则,resume 后也不沿用启动时快照。
-
 ```text
 successful Main turn
   |
@@ -669,6 +673,9 @@ bounded drain 等待取消收口
   consolidation 的 Main-equivalent sessions。
 - gate 和 prompt 使用同一组实际 transcript session id,不使用 SessionStore `updated` 时间替代
   transcript mtime。
+- handler 在 remote workspace 直接返回。remote 判定由 bootstrap 通过语义化 runtime dependency
+  注入,并在调用时读取当前 `workspaceIdentity`;core 不复制 remote identity 解析规则,resume 后
+  也不沿用启动时快照。
 
 project session 归属由 SessionStore 的 workspace identity 判断。model-io writer 与 Dream 使用
 同一个从 `storage.dir` 派生的 `modelIoDir`(development 为 `debug`,其他环境为 `rollout`);
@@ -831,16 +838,16 @@ ZCode 当前没有的工具也属于明确的 tool-inventory 差异;不得为
 | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
 | Config/root            | Settings 默认/持久化;新建/cold resume 重读;active/child 继承;enabled/use;local/remote identity;resume 重算;旧 root 不读取;mkdir failure                                                                                                                                                                         |
 | Retrieval branch       | `false -> default-index`、`true -> semantic-recall`;pointer/index 与 Selector/Recall 两组互斥;原始 boolean 只定义一次                                                                                                                                                                                                |
-| Main prompt/index      | 两种 Main prompt exact fixture;default 分支非空 `MEMORY.md` 的 exact request user-context source;任意非空 instruction source(包括 `MEMORY.md`)使 `context_prefix` 渲染一次指令 preamble;leading frontmatter/顶层 HTML comment 清理;缺失/空/不可读不注入;semantic 分支在读取前跳过;200 行/25,000 字符截断;磁盘原文 read-state 与 partial 标记;运行中不刷新、冷恢复 / rewind 原位刷新、新 session 重读;四种 Main task;三种 child 排除 |
+| Main prompt/index      | 两种 Main prompt exact fixture;default 分支非空 `MEMORY.md` 的 exact request user-context source;任意非空 instruction source(包括 `MEMORY.md`)使 `context_prefix` 渲染一次指令 preamble;leading frontmatter/顶层 HTML comment 清理;缺失/空/不可读不注入;semantic 分支在读取前跳过;200 行/25,000 字符截断;磁盘原文 read-state 与 partial 标记;运行中不刷新、冷恢复与 compaction 后变化时追加增量(已发公告不改写)、新 session 重读;四种 Main task;三种 child 排除 |
 | Permission/file write  | root containment;小写 `.md`;敏感 segment;Write/Edit allow/deny;缺失 originSessionId 时同时补入 `node_type: memory`,已有非空 origin 的文件原样保留;Bash 不变                                                                                                                                                      |
 | Recall default branch  | 保留 pointer/index;Main turn 不扫描、不发 Selector、不注入 `relevant_memory`                                                                                                                                                                                                                                          |
 | Recall semantic branch | 无 pointer/index;branch-aware lifecycle 覆盖 prefetch、完整 tool batch 后 consume、recursive scan、selector schema、order/duplicate、正文限制、stale 与 61,440 gate;不增加 Runtime override                                                                                                                          |
-| Extraction             | success/error/abort;direct write;独立 3-word block;cursor;同边界 snapshot;Rewind 后不取消;running+latest;第 5 turn;header refresh;session close 拒绝新调度、丢弃 pending、abort running 并有界 drain                                                                                                           |
+| Extraction             | success/error/abort;direct write;独立 3-word block;cursor;同边界 snapshot;Rewind 后不取消;running+latest;第 5 turn;header refresh;session close 拒绝新调度、丢弃 pending、abort running 并有界 drain;remote workspace 照常调度                                                                                                       |
 | Headless Extraction    | `-p/--prompt` 与 `--target` 注入内部 `extractionEnabled=false`;Main prompt/index/Recall 保持;不读取 Extraction snapshot、不创建 scheduler、不发 Extraction 请求、不推进 cursor、不写 Memory 文件;TUI/app-server 默认行为不变                                                                                      |
 | Dream                  | 无 active trigger;handler 的 24h/5 transcript mtimes/10m gate;lock;第 50 turn;filesTouched;one-shot memory_update;`/dream` 为 Unknown command                                                                                                                                                                    |
 | Custom agent           | exact enum;三 scope;agent key;empty/truncated index;Write/Edit augmentation;Read intentional diff;disallowedTools                                                                                                                                                                                                |
 | Settings viewer        | 默认关闭不发 catalog 请求;Desktop 本地 profile catalog;空目录过滤;稳定排序;symlink/traversal 拒绝;workspace 切换;虚拟 `MEMORY.md` 父节点;缺失 index;原始正文;5 MiB 单文件预览上限;英文事实数量单复数;显式刷新;查看不发模型请求、不写文件;Web Remote / Mobile 只展示本地查看提示且 catalog 零调用                                                                  |
-| 上下游                 | generateText structured output;stream 不变;Settings 只经 runtime-preference 布尔值进入 Agent;viewer 仅经 Desktop 本地 Host Memory service 读取本地磁盘;desktop continuous/mobile replayable 不传 Memory 正文;remote background 不启动                                                                                |
+| 上下游                 | generateText structured output;stream 不变;Settings 只经 runtime-preference 布尔值进入 Agent;viewer 仅经 Desktop 本地 Host Memory service 读取本地磁盘;desktop continuous/mobile replayable 不传 Memory 正文;remote 照常调度 Extraction,Dream handler 跳过                                                                              |
 
 每个实现 Phase 必须先更新本文或对应 fixture,再补失败测试、实现最小行为、运行聚焦测试并做
 scope review。最终必须执行 CLI workspace typecheck/lint、仓库级 `pnpm typecheck`、`pnpm lint`
@@ -856,7 +863,7 @@ focused tests;它证明这些规则已经在真实 Runtime 链路中正确组
 
 1. Main Memory prompt 出现在每个 Memory-enabled Main provider request,并保留默认分支的
    `MEMORY.md` pointer 文案;session 初始化时非空 `MEMORY.md` 还会以 exact request
-   user-context source 进入开头的 `context_prefix` 公告,运行中保持不变(冷恢复与 rewind 时原位刷新)。该非空
+   user-context source 进入开头的 `context_prefix` 公告,之后不改写(冷恢复与 compaction 后内容变化时追加增量公告)。该非空
    source 自身即使没有 AGENTS.md,也会使 `context_prefix` 渲染一次指令 preamble。
 2. Memory-enabled Main turn 不发 Selector provider request,也不注入 `relevant_memory`;索引消费
    不依赖 Selector。

+ 42 - 0
apps/zcode-cli/docs/design/v2/model/README.md

@@ -389,6 +389,24 @@ OpenAI-compatible 回放一致的契约:
   逗号分隔、字典序、只增不减。没有标签或值不合法时省略;工作区独立请求不发送;provider 静态
   同名 header 被剔除。owner、继承与冷恢复规则见 [session-features-header.md](session-features-header.md)。
 
+模型请求的来源 header(`buildCliZCodeSourceHeaders`,以及 provider endpoint routing 配置 GET
+复用的共享来源 header)中,`X-Client-Language` 按以下优先级取值:
+
+1. 环境变量 `ZCODE_CLIENT_LANGUAGE`:Desktop 启动 Agent 子进程时写入当前界面语言
+   (BCP-47,如 `zh-CN`、`en-US`、`ja-JP`、`ru-RU`、`ko-KR`)。
+   - 用途:Agent 进程的 `Intl` 只代表系统语言;App 从 Finder/Dock 启动时没有 `LANG`,
+     Node ICU 回退为 `en-US`,界面选了日语/俄语/韩语时模型请求仍发 `en-US`。
+   - 取值去掉首尾空白,必须是可打印 ASCII;空值或非法值视为未设置,回落下一项,不报错、不阻断请求。
+   - 只在 spawn 时读取:界面语言切换后,下一次启动的 Agent 进程生效(已有进程不重启)。
+   - 独立 CLI/TUI 不设置该变量;用户手动设置时同样生效。
+2. 进程 `Intl.DateTimeFormat().resolvedOptions().locale`(原有规则)。
+3. 都没有时为 `unknown`。
+
+注入方:本地 Desktop Host 在 `resolveSpawnEnv` 中写入(`resolveClientLanguage`,即 Main 推送的实时界面语言);
+desktop-attached 远端 Host(SSH/WSL/Docker Source Server)是多个 Desktop 共享的常驻 daemon,没有
+Desktop→Agent 的语言通道,仍按第 2 项回落,跨环境同步另行设计。测试:`tests/model-config.test.ts`、
+`tests/provider-endpoint-routing-source-headers.test.ts`。
+
 `turnId`、`spanId`、`parentSpanId` 等细粒度诊断信息只进入 model status event、session event、
 trace span 和结构化日志,不进入 provider-visible HTTP header。上述归因 header 只用于统计、
 诊断与审计,不作为鉴权、计费、限流或业务路由依据。
@@ -866,3 +884,27 @@ npm test
 ## Selection side first input
 
 App 的 `createSelectionSideSession.firstInput.modelSelection` 是可选的完整模型选择,详情见 [副屏契约](../../../../../../docs/ui/conversation-selection-side-chat.md)。存在时由原 fork 创建路径写入 child 的模型配置,首条输入沿用该配置;不更新 parent,也不分开发送切模命令。缺省保持原 runtime 继承;旧客户端继续兼容。
+
+### App 会话选模与 Bot 输入接纳
+
+App 已有会话的 Provider/Model 改选通过 `switchModelConfig` 提交完整 Selection。
+跨模型配置先整体校验 Provider、Model 和 reasoningLevel,再更新 Session Selection;
+非法档位返回失败,不先换模型再尝试补写档位。该命令不修改 Active Model 或已接纳队列。
+
+兼容调用方传入空白 `thought` 时,从目标模型的 Registry 元数据读取默认档位,
+组成完整 Selection 后一次校验、保存并发布事件,不继承旧模型的显式档位。
+不能仅使用身份切换入口:它留下稀疏选择,随后发布事件创建 Model 时仍会失败。
+显式非空档位仍与模型身份一次校验并保存;失败时原 Session Selection 保持不变。
+回归必须经过真实 Provider Registry 与 facade,检查成功事件、持久选择和失败不变性,
+不能仅 mock `setModel`;正在执行轮次和已接纳队列仍使用各自冻结的选择。
+
+Bot 的 `sendText` / 兼容 `session/send` 可附 `modelSelectionBasis`,表示 Host 解析时读取的
+原 Session Selection。接纳时若身份或 reasoningLevel 已变,使用当前 Session Selection;
+否则保留 Host 已解析的 `modelSelection`。依据只用于接纳,不成为队列的动态引用。
+普通显式 Submission 不带该字段,仍使用自己的冻结选择。
+
+```text
+选模命令 → Session Selection → ACK
+Bot 异步解析 → CLI 核对读取依据 → 冻结 Submission → 执行 / 排队
+已执行及已接纳输入 ─────────────────→ 保留原快照
+```

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

@@ -10,30 +10,94 @@ modifying the canonical session history or treating every block without a signat
 
 ## Request projection
 
-The current request uses the assistant message's original `providerId + modelId` as provenance and
-applies these rules to a request-local copy, in order:
+Two layers project a request-local copy of the history. Neither rewrites canonical history.
+
+### Core: which assistant messages exist
+
+The core provider request projection is the only place that removes an assistant message. It does
+this only when the model request capability `dropReasoningOnlyOrBlankAssistants` is true; the
+adapter sets it for the Anthropic Messages API. Other protocols keep these messages.
+
+The projection removes an assistant message that has no tool calls and whose content is a
+non-empty block array where every block is reasoning or text that is blank or `(no content)` after
+trimming, so the reply has no visible content. A reply cut off while thinking (send now, stop), a
+stream that failed after reasoning, or a reply of only reasoning and blank text leaves such a
+message. String content and an empty array are not removed. An empty reply that carries usage is
+stored with empty string content and kept as an estimation anchor (see
+[Assistant Block Order](./assistant-block-order.md) "没有可见内容的回复"); an empty array is excluded
+too, because every block of an empty array matches. The decision uses only the stored content,
+not the target model.
+Cross-model signature stripping stays in the adapter.
+
+The removal is the first projection step. Attachment bubbling, mid-conversation system (MCS)
+placement, the notification text choice, tool-result folding and the newline before a user input
+or a Continue prompt all run as if the message never existed. MCS placement needs this order: it
+puts a system message only before an assistant message or at the end. If the assistant message is
+removed after that, the system message is directly before a user message, and the provider rejects
+the request with HTTP 400.
+
+```text
+history   A1 ─ U2 ─ A2[reasoning only] ─ U3 ─ reminder
+MCS on    A1 ─ U2\n ─ U3 ─ system(reminders)
+MCS off   A1 ─ reminders ─ U2\n ─ U3
+```
+
+Accepted effects:
+
+- The previous request ended at U2. U2 gets `\n`, and with MCS off the reminders move before U2,
+  so the prompt cache misses from that point once.
+- A stored session that already has such a reply sends a different request from that reply on,
+  on its first request after the upgrade. The prompt cache misses once. Signed reasoning after that
+  reply was produced with the old prefix, so a provider that checks the prefix can reject the
+  request once. The signature repair ("Signature rejection") then removes all signed and redacted
+  reasoning before the repaired step, and the marker keeps that removal for later requests. This
+  one-time cost is accepted.
+- A reminder that becomes adjacent to a tool result folds into it.
+- A task notification directly after a removed reply is in the same turn as the user prompt before
+  it, so it uses the same-turn notification text.
+- After a model switch, a reply of only signed reasoning, with or without blank text, is removed;
+  it is not kept as `(no content)`.
+- Caller-built messages (MCP Apps sampling) do not pass through this projection, so nothing removes
+  their assistant messages. A final assistant message with only blank text becomes an empty text
+  block after the Anthropic serializer trims it. The provider rejects that request, and the error
+  goes back to the App as a failed sampling call.
+
+### Adapter: blocks inside each assistant message
+
+The adapter uses the assistant message's original `providerId + modelId` as provenance and applies
+these rules, in order:
 
 1. When the source and target model IDs differ, or their providers are not replay-compatible,
    remove reasoning with a non-empty Anthropic `signature` and reasoning carrying Anthropic
    `redactedData`. Provider compatibility follows the bounded identity rules below.
-2. Remove an assistant message that contains only reasoning and has no tool calls, and merge
-   ordinary user messages that become adjacent (same merge as step 4).
-3. If the final message is an assistant message, remove its consecutive trailing reasoning blocks.
-4. Remove whitespace-only assistant messages and merge ordinary user messages that become adjacent;
-   tool-result carriers retain their message boundary.
-5. Replace an empty non-final assistant message with `(no content)`.
-
-Reasoning block filtering preserves the assistant message envelope. Message removal and empty
-content repair are separate structural passes, rather than letting a
-low-level block filter decide whether a conversation turn still exists.
+2. If the final message is an assistant message, remove its consecutive trailing reasoning blocks.
+3. Replace a non-final assistant message that has no tool calls and whose content is an empty or
+   only-blank-text block array with `(no content)`. Core-projected requests normally do not reach
+   this rule: the core removes replies without visible content, and the empty reply kept as an
+   estimation anchor has empty string content, which this rule does not change. Caller-built
+   messages (MCP Apps sampling) can have such content.
+
+The adapter never removes or merges messages, so the positions that the core projection chose,
+including MCS placement, stay valid.
+
+Assistant entries whose blocks and tool calls all carry `blockIndex` are ordered entries; see
+[Assistant Block Order](./assistant-block-order.md). After step 1, each ordered entry is folded
+block by block in `blockIndex` order. Each new block is added to the previous result, and then two
+rules run on that result: whitespace-only text blocks are dropped unless they sit between two
+reasoning blocks (the filter is skipped when only reasoning would remain), and tool calls move
+after the content unless a reasoning → tool call → reasoning pattern exists. A block that an
+earlier step removed or moved is not restored. Step 2 removes the trailing reasoning of an ordered
+final entry in request order and does not run the entry rules again. These entry rules only remove
+or move blocks; they never merge blocks or messages. Legacy entries keep the rules above unchanged.
 
 A logical model request applies this structural normalization exactly once, before its first
 physical attempt. Ordinary retries reuse that projected request-local history. A signature-repair
 retry derives only by removing rejected signed or redacted reasoning from the same projection; it
 must not run the structural passes again.
 
-Missing or empty signatures are unsigned reasoning. They are preserved unless the block is removed
-by the orphan or trailing rules, or the final serializer-input projection identifies an exact-empty
+Missing or empty signatures are unsigned reasoning. They are preserved unless the core removes the
+reasoning-only message, the trailing rule removes the block, or the final serializer-input
+projection identifies an exact-empty
 stream stub with `text === ""` and no `providerOptions` keys. Whitespace-only reasoning is not an
 empty stub, and provider options are opaque: the presence of any known or unknown key preserves the
 block without inspecting `signature` or another provider-specific field. A missing source model
@@ -106,15 +170,31 @@ the migrated historical rows byte-for-byte unchanged.
 An Anthropic request may return HTTP 400 when a signed or redacted thinking block is rejected. The
 adapter may retry once only when all of these conditions hold:
 
-- the error text identifies a thinking signature that is invalid or cannot be modified;
+- the error text identifies a thinking signature that is invalid or cannot be modified, or a
+  thinking block that is bound to another conversation;
 - no provider-visible stream output has been committed;
 - removing signed or redacted reasoning actually changes the request;
 - the one-shot signature-repair credit has not already been used.
 
-The retry uses a request-local copy, has no backoff, and never updates MessageHistory or persisted
-messages. The rejection repair removes blank text blocks from an assistant it changed. If that
+The error text check is case-insensitive and runs on the raw text and on the text with backticks
+removed, so a provider message such as ``Invalid `signature` in `thinking` block`` matches. It
+accepts these forms: `signature in thinking block`; a thinking block name (`thinking block`,
+`` `thinking` ``, `redacted_thinking`) together with `invalid signature` or `cannot be modified`;
+`bound to a different conversation`; `not created in this conversation`.
+
+The repair warning log (`model.reasoning_signature_repair.retry`) also records the provider error
+text (first 2000 characters) and the `anthropic-thinking-prefix-mismatch` response header when the
+response has one. These fields exist to diagnose why a signature was rejected.
+
+The retry uses a request-local copy and has no backoff. It never rewrites the reasoning already in
+MessageHistory or in persisted parts; later requests keep the removal through the marker described
+in "Keeping removed reasoning out". The rejection repair removes blank text blocks from an
+assistant it changed. If that
 assistant would otherwise be empty or contain only unsigned reasoning and has no tool calls, it
-appends `[Thinking removed]`. Unsigned reasoning itself is not removed.
+appends `[Thinking removed]`. Unsigned reasoning itself is not removed. In an ordered entry the
+placeholder takes the next `blockIndex` after the entry's largest index, and the per-entry
+whitespace and tool-call rules run again on the repaired entry. They are entry rules, not the
+structural passes, so the "no second structural normalization" rule still holds.
 
 The one signature-repair retry does not consume the ordinary provider retry budget. Unrelated HTTP
 400 responses, a second signature failure, or a request containing only unsigned reasoning are
@@ -131,20 +211,67 @@ physical attempt: a rejected attempt, when the existing recorder emits one, show
 request-local messages, while the successful retry shows the repaired messages it actually sent.
 Recording must not fall back to the canonical input request after request-local history changes.
 
+### Keeping removed reasoning out
+
+A rejected block does not become valid again. The provider binds a signed block to the prompt
+prefix that produced it, and a removed block that is sent again also invalidates the reasoning that
+was produced while it was absent. If only the repaired request omitted the blocks, every later
+request would send them again and fail once before its own repair.
+
+When a repaired retry succeeds, the adapter reports `signedReasoningReset: true` on the generate
+result or on the stream `finish` event. Core stores the marker on the assistant message that this
+model step produces: on the live entry message (`ModelInputMessage.signedReasoningReset`) and in
+`AssistantMessageInfo.metadata.signedReasoningReset`. Cold resume restores it from that metadata.
+The metadata key is optional and loose, so older readers ignore it and no migration is needed.
+
+The projection rule has one owner. The last pass of `normalizeReasoningHistory` finds the last
+assistant message with the marker and applies the rejection repair to every message before it:
+signed and redacted reasoning is removed, blank text in a changed assistant is removed, and a
+changed assistant left with only unsigned reasoning and no tool calls gets `[Thinking removed]`.
+The marked message and the messages after it are not changed. Because this pass runs after the
+structural passes, as the repair did, the projected prefix is byte-for-byte the prefix that the
+repaired retry sent. Later requests do not fail again, and their prompt cache continues from the
+repaired retry.
+
+```text
+request N     [A1(T1) … A5(T5)] ─400→ remove signed reasoning ─retry→ 200, signedReasoningReset
+                                                                          │
+              A6.info.metadata.signedReasoningReset = true ◄──────────────┘
+request N+1   [A1 … A5, A6★(T6), …] → last pass removes signed reasoning before A6★
+```
+
+The marker is part of the history, so it follows the history:
+
+- A rewind or branch cut that removes the marked message removes the marker. The reasoning produced
+  while the blocks were absent is removed by the same cut.
+- Compaction that summarizes the marked message removes the marker with it. A preserved segment
+  that keeps the marked message keeps the marker.
+- A fork copies the message metadata, so the child projects the same prefix as the parent.
+- A retry that fails or is cancelled produces no marked message. The next request is rejected once
+  more, and its successful repair records the marker.
+- A marked reply without visible content (no tool calls, only reasoning or blank text) is removed
+  by the core projection, and its marker goes with it. This is intended: the removal stays one rule
+  over the stored content and does not read the marker. The next request sends the rejected blocks
+  again, is rejected once more, and its repair marks the new reply. The first marked reply that has
+  visible content keeps the marker, and later requests do not fail again.
+
+The rule removes all signed and redacted reasoning before the marker, not only the block that the
+provider names. Compatible gateways do not reliably report the position of the rejected block, so
+this is the rule that is correct for every Anthropic-protocol provider. Unsigned reasoning is not
+removed.
+
 ## Invariants
 
 - Same-model signed and redacted reasoning remains unchanged by cross-model compatibility
-  filtering. The explicit orphan and final trailing-reasoning structural rules may still remove it.
+  filtering. The core removal of messages without visible content and the final trailing-reasoning
+  rule may still remove it.
 - Structural normalization runs once per logical model request. Physical attempts, including a
   signature-repair retry, reuse or derive from that request-local projection without normalizing it
   again.
 - Text, tool calls, tool results, and cache metadata remain unchanged except for the explicit blank
-  assistant cleanup above. Message order remains unchanged except for explicit orphan or
-  whitespace-only assistant removal. When orphan or whitespace cleanup makes ordinary user
-  messages adjacent, they are merged to preserve a valid request shape; when both sides meet as
-  text blocks, the earlier text gets a trailing `\n`. Both removals merge only the pair that the
-  removal made adjacent; user messages that were already adjacent stay as they are, because the
-  request layer has already joined them.
+  assistant repair above and the ordered-entry rules in
+  [Assistant Block Order](./assistant-block-order.md). Only the core projection removes assistant
+  messages, as its first step. The adapter keeps the message count and order.
 - Anthropic unsigned reasoning that survives normalization remains in the serializer input using
   the required empty-signature representation, except for an exact-empty block with no provider
   options. Whitespace-only reasoning and any block carrying opaque provider options remain intact.
@@ -152,7 +279,9 @@ Recording must not fall back to the canonical input request after request-local
   desktop/mobile delivery semantics are unchanged. Signature repair is visible only through the
   existing provider-retry UI state; no UI component or interaction behavior is added.
 - Signature repair reuses the existing model retry status, usage, and live-tail projection paths;
-  it does not add protocol fields, persisted retry state, or another retry authority.
+  it does not add protocol fields or another retry authority. Its only persisted state is the
+  optional `signedReasoningReset` key in the metadata of the assistant message that the repaired
+  request produced.
 
 ## Tests
 
@@ -160,14 +289,27 @@ Recording must not fall back to the canonical input request after request-local
   Plan identity groups, exact model matching, custom/unknown provider isolation, and cache metadata.
 - `packages/adapters/tests/runtime-reasoning-provider-replay.test.ts` covers actual SQLite decoding
   and selection migration, Runtime cold resume and live continuation, generate/stream HTTP request
-  bodies, and original stored message/part immutability with a local fake transport.
-- Pure projection tests cover same-model, cross-model, unknown-model, unsigned, redacted, orphan,
-  trailing, empty/whitespace assistant repair, rejection placeholders, tool-call, and immutability
-  cases. Adjacent-user repair also covers cache-control precedence, mixed string/block content, and
-  tool-result carriers on either side of a removed assistant.
+  bodies, and original stored message/part immutability with a local fake transport. It also sends
+  follow-ups after a reasoning-only reply, live and after cold resume, in streaming and
+  non-streaming mode with MCS on, and checks that each request has a system message and none is
+  directly before a user message.
+- `packages/core/tests/provider-request-messages.test.ts` covers the core removal with MCS on and
+  off, reminders that bubble past the removed reply, the kept shapes, and the capability switch.
+  `packages/adapters/tests/request-capabilities.test.ts` covers the capability per API type.
+- Desktop E2E I71 covers the removed reasoning-only reply on the same model and, after a model
+  switch, the removed `[signed reasoning]` and `[signed reasoning, blank text]` replies.
+- Pure projection tests cover same-model, cross-model, unknown-model, unsigned, redacted,
+  trailing, empty and blank-after-stripping assistant repair, rejection placeholders, tool-call,
+  and immutability cases, and that the adapter keeps reasoning-only replies. Marker projection
+  tests prove that
+  the messages before the last marked assistant equal the repaired retry's projection byte for
+  byte, that the marked message and later messages are unchanged, and that unsigned reasoning is
+  kept.
 - Core tests cover live cloning, persisted execution-model provenance, resume hydration, and
   execution-model provenance on terminal-error, partial-stream recovery, streamed-tool recovery,
-  and Start Plan admission-retry paths when the selected model changes in flight.
+  and Start Plan admission-retry paths when the selected model changes in flight. They also cover
+  the `signedReasoningReset` marker on the live assistant entry, in persisted message metadata,
+  after cold resume, and in a forked child.
 - Adapter runner tests cover the exact HTTP 400 classifier, a single repaired retry outside the
   ordinary retry budget, no retry after committed output, no retry when the request does not
   change, canonical-history immutability, the failed/scheduled/started status sequence, and
@@ -175,7 +317,8 @@ Recording must not fall back to the canonical input request after request-local
   ordinary retry and the one-shot signature-repair credit; generate also covers a second signature
   rejection terminating without another repair. A structural regression case keeps an
   empty-assistant placeholder and its surrounding user-turn boundaries unchanged across the
-  repaired retry.
+  repaired retry. Generate and stream report `signedReasoningReset` only when the repaired retry
+  succeeds.
 - Product projection tests cover the signature-repair retry reason through the existing
   `control.apiRetry` live-tail state.
 - Serializer-input projection tests prove that exact-empty metadata-free stubs are omitted while
@@ -184,4 +327,10 @@ Recording must not fall back to the canonical input request after request-local
 - Desktop replay E2E covers standard native `signature_delta`, start-only signature fallback, and
   native-delta precedence across repeated live and cold-resume follow-ups. It also proves that a
   resumed unsigned-only history is sent unchanged and a signature
-  400 that cannot remove any signed or redacted block terminates without retrying.
+  400 that cannot remove any signed or redacted block terminates without retrying. After a
+  successful repair, the next request and the first request after an app restart omit the removed
+  blocks and keep unsigned reasoning, each in one physical attempt.
+- Ordered-entry rules (whitespace text, tool-call reordering and its reasoning → tool call →
+  reasoning exception, trailing reasoning in request order, signature-repair placeholder) and
+  live/cold byte equality for interleaved responses are covered by the tests listed in
+  [Assistant Block Order](./assistant-block-order.md).

+ 49 - 7
apps/zcode-cli/docs/design/v2/model/anthropic-stream-compat.md

@@ -14,8 +14,10 @@ provider fetch 包装为 `createAnthropicCompatFetch()`;`openai-compatible`、
 - **按响应类型处理**:`content-type` 含 `event-stream` 的响应走 SSE transform;
   `application/json` / `+json` 的非流式响应按同样的规则改写 `content` 数组;其他响应原样返回。
 - **Provider 内置工具**:SDK 不认识的 `server_tool_use` 改写成 provider 执行的
-  `mcp_tool_use`,与它配对的裸 `tool_result` 改写成 `mcp_tool_result`,与结构化块重复的
-  markdown 渲染副本按结构确认后去掉,详见下文「Provider 内置工具多轮回放」。
+  `mcp_tool_use`,与它配对的裸 `tool_result` 改写成 `mcp_tool_result`;上游直接下发的
+  `mcp_tool_use` / `mcp_tool_result`(新格式)原样透传,缺 `server_name` 时补上,没有配对调用的
+  `mcp_tool_result` 按 `index` 丢弃。两种格式下与结构化块重复的
+  markdown 渲染副本都按结构确认后去掉,详见下文「Provider 内置工具多轮回放」。
 - **未配对的裸 `tool_result`**:没有对应服务端调用的裸 `tool_result` 仍是非标块,按 `index`
   丢弃 start、delta 和 stop frame(非流式路径直接从 `content` 中去掉)。
 - **透传**:合法 text、SDK 认识的 `server_tool_use`、`web_search_tool_result` 等 typed result、
@@ -55,6 +57,19 @@ thinking → text → text(「**🌐 …」调用头 markdown) → server_tool_u
   → text(「**Output:** …」结果 markdown) → 裸 tool_result → 下一轮 thinking/text/tool_use
 ```
 
+2026-11 起服务端改为下发 Anthropic MCP connector 的原生块(新格式):调用块是带 `server_name`
+的 `mcp_tool_use`,结果块是 `mcp_tool_result`(text 块列表 + `is_error`),结果摘要挪到结果块之后。
+markdown 渲染内容不变;非流式响应没有 markdown 渲染。同一次响应里有多次调用时,所有调用在前、
+结果在后,按 id 配对:
+
+```text
+text(「**🌐 …」) → mcp_tool_use(A) → [text(「**🌐 …」) → mcp_tool_use(B)]
+  → mcp_tool_result(A) → text(「**Output:** …」) → [mcp_tool_result(B) → text(「**Output:** …」)]
+  → 下一轮 thinking/text/tool_use
+```
+
+服务端全量切到新格式前两种格式都可能出现,兼容层同时处理。
+
 旧实现里 AI SDK 丢弃未知名的 `server_tool_use`,兼容层丢弃裸 `tool_result`,
 core 再把所有 text 拼成一个字符串、thinking 挪到最前。下一次请求里只剩一段带
 markdown 的正文:模型看不到结构化的调用和结果,却能看到「调用工具」的文字样例,
@@ -69,12 +84,31 @@ markdown 的正文:模型看不到结构化的调用和结果,却能看到
   (调用头以 `**🌐` 开头、结果以加粗标签开头)一并去掉,界面改由工具卡片展示。
   结果副本必须夹在服务端调用与它的配对 `tool_result` 之间才会被去掉(先缓冲,等下一个块确认),
   只凭加粗前缀不删;服务端缺少配对结果时,紧跟调用的加粗正文原样保留。
-  非流式 JSON 响应只做同样的结构改写,不参与 core 的多轮切轮(见下文「范围」)。
+  新格式的 `mcp_tool_use` / `mcp_tool_result` 是 SDK 原生块,不改写,只去掉 markdown 副本:
+  调用头必须以 `**🌐` 开头且下一个块就是 `mcp_tool_use`。结果摘要必须紧跟配对的 `mcp_tool_result`,
+  以 `**Output:**` 开头,并且紧接着是配对调用的摘要标签 `**<工具名>_result_summary:**`
+  (例如 `**Output:**\n**analyze_image_result_summary:** …`),整块收完时确认;对不上就立即放行。
+  摘要后面没有结构块可以确认(旧格式靠后面的配对 `tool_result` 确认),模型下一轮的正文也会紧跟结果出现,
+  只看前缀会把以 `**Output:**` 开头的模型回答整块删掉,所以要用摘要自带的工具名标签确认身份。
+  旧格式的真实流和服务端文档示例里的摘要都是这个形态;标签换了只会漏删,不会误删。
+  紧跟配对结果的 text 以 `**🌐` 开头时按调用头处理:服务端漏发摘要、结果后直接接下一个调用时,
+  这个调用头照样去掉,与旧格式的覆盖范围一致。
+  配对按调用 id,在本条消息内有效,新旧两种格式共用:旧格式改写出的调用也能配对上游的 `mcp_tool_result`,
+  反之亦然,服务端半迁移时不会把合法结果当成未配对。
+  非流式 JSON 响应做同样的结构改写和下面两条防护,不参与 core 的多轮切轮(见下文「范围」);新格式的非流式
+  响应没有 markdown 渲染,不做副本去除。
+  新格式另有两条防护,不依赖服务端遵守协议:
+  - 缺 `server_name` 的 `mcp_tool_use` 补上 `zcode-provider-builtin`(与旧格式改写用的值相同)。
+    2026-11-05 线上曾漏发这个字段,AI SDK schema 校验失败,整轮报错,图片留在历史里后每轮都失败。
+  - 本条消息里没有配对调用的 `mcp_tool_result` 按 `index` 丢弃 start、delta 和 stop frame。
+    AI SDK 按 id 直接取调用记录,取不到会抛 `TypeError`,整条流失败。
 - **adapter**:AI SDK 的 provider 执行 `tool-result` / `tool-error` 转成
   `provider_tool_result` 流事件。
 - **core**:每遇到 provider 执行的工具调用,就把此前的 reasoning/text 收成一「轮」,
   按流顺序落盘(reasoning/text part → 带 `metadata.providerExecuted` 的 tool part),
   并发出 Scheduled → Started → Result 工具事件,界面显示为 MCP 工具卡片。
+  轮内每段文字各写一个 part;reasoning、文字和服务端工具 part 都带 `blockIndex`,分轮时计数器不重置,
+  冷恢复按 `blockIndex` 排序后再切轮(见 [Assistant 内容块顺序](./assistant-block-order.md))。
   这类调用不进入本地工具调度。它们已切成带结果的前序轮次,不是本 step 的最终调用,所以续写、超窗与
   fileChanges 不计它们(`docs/model-request-output-tokens.md` 的完整 tool call 优先规则对其例外),
   空结果判定仍把它们算作有内容。
@@ -111,10 +145,18 @@ markdown 的正文:模型看不到结构化的调用和结果,却能看到
 
 因此只保留方案 A。
 
-测试覆盖:`packages/adapters/tests/model-execution.test.ts`(流式与非流式改写、
-markdown 副本去除、普通加粗文本保留);`packages/adapters/tests/provider-builtin-tool-rounds.test.ts`
+已接受的取舍:新格式一次响应里有多个并行调用时,服务端内部是一条 assistant 同时发出这些调用,
+方案 A 把它们回放成先后多轮(每个调用各一轮 `assistant(tool_use)` + `user(tool_result)`)。
+2026-11-06 服务端确认仍接受这种回放,所以不为并行调用另做回放。
+
+测试覆盖:`packages/adapters/tests/model-execution.test.ts`(旧格式的流式与非流式改写、
+markdown 副本去除、普通加粗文本保留);`packages/adapters/tests/provider-builtin-tool-compat/`
+(两种格式的改写与副本去除契约,含新格式并行调用、补 `server_name`、丢弃未配对结果、跨格式配对);
+`packages/adapters/tests/provider-builtin-tool-rounds.test.ts`
 用脱敏的真实流 fixture 走完 compat → AI SDK → Runtime,校验下一次请求、落盘顺序、
-工具卡片事件与冷恢复回放。
+工具卡片事件与冷恢复回放;新格式另覆盖缺 `server_name`、并行调用含 `is_error`、未配对结果。
+新格式 fixture(`provider-builtin-analyze-image-mcp.sse`)由旧格式的真实流按
+服务端文档改造:调用块换成 `mcp_tool_use`、结果换成 `mcp_tool_result` 并挪到结果摘要之前,其余帧不变。
 
 ## 背景
 
@@ -140,7 +182,7 @@ model adapter 的 Anthropic provider fetch 边界:
 - 当 `content_block_start.content_block.type === "thinking"` 且其 `signature` 是
   非空字符串时,按 block `index` 暂存该签名。
 - 如果同 index 后续出现原生 `content_block_delta.delta.type ===
-  "signature_delta"`,立即清除暂存签名并原样透传原生 delta,禁止重复合成。
+"signature_delta"`,立即清除暂存签名并原样透传原生 delta,禁止重复合成。
 - 如果同 index 到 `content_block_stop` 仍有暂存签名,在原始 stop frame 之前合成
   一个标准 `content_block_delta`,其 delta 为
   `{ type: "signature_delta", signature }`;随后清除该 index 的暂存状态并原样

+ 388 - 0
apps/zcode-cli/docs/design/v2/model/assistant-block-order.md

@@ -0,0 +1,388 @@
+# Assistant 内容块顺序
+
+Status: Implemented(2026-11-04,基于 `origin/feat/2.1.296` `7749873762`)
+
+## 目标
+
+一次模型响应里有思考、文字和工具调用三类块。本规格定义:
+
+- 按模型输出的顺序保存这些块。
+- 按固定规则把它们放回下一次请求。
+- live 请求和冷恢复请求对同一条消息发出相同的字节。
+- 旧消息(没有顺序信息)发出的请求字节不变。带浏览器轮尾截图的旧消息是例外,见「兼容」。
+
+不改表结构,不做迁移。
+
+## 问题
+
+改动前,一条 assistant 回复存成三部分:
+
+- `reasoning[]`;
+- 一段文字,多个文字块之间直接拼接,没有分隔;
+- `toolCalls`。
+
+回放时固定排成 `[全部思考, 一段文字, 全部 tool_use]`。库里 part 的顺序是写库顺序,不是流顺序:
+只读工具在流中写库,reasoning 和文字在流结束后写库。这带来三个问题:
+
+1. 文字后面还有思考块时,文字被移到这些思考块后面。Anthropic 会校验思考块签名对应的前缀(这个块
+   前面的全部内容)。在执行该校验的渠道上,前缀改变的请求返回 400
+   (`The block is bound to a different conversation`)。真实 provider 回放已经证实:移动文字块、
+   改变思考块前面的内容返回 400;只移动 tool_use 返回 200。
+2. 多个文字块拼成一段,例如 `"Let me check.Now edit."`。
+3. live 界面每个文字块一行,冷恢复后只剩一行。
+
+## 术语
+
+- **块**:一次 provider 响应里的一个 reasoning、text 或 tool 内容块。服务端执行的工具也是块。
+- **blockIndex**:块在这次响应里的到达序号,见下文。
+- **有序消息**:满足下文"有序判定"的 assistant 消息。其他 assistant 消息是**旧消息**。
+- **条目**:MessageHistory 里的一个 assistant entry。含服务端工具的消息会拆成多个条目,
+  见 [Anthropic Stream Compat](./anthropic-stream-compat.md)「Provider 内置工具多轮回放」。
+
+## 数据流
+
+```text
+provider 流事件
+   │  core 组装器为每个块分配 blockIndex(非流式路径由 adapter 按 result.content 分配)
+   ▼
+写库:reasoning / text / tool part 都带 blockIndex(写库时机不变)
+   │
+   ├─► 读取边界(session-store repository):assistant 消息的 part 按 blockIndex 稳定排序
+   │        └─► V4 冷恢复、旧协议映射、services、fork 都拿到流顺序
+   │
+   ├─► live:buildAssistantEntries(有序块) ─┐
+   └─► 冷恢复:hydrator 判定为有序消息 ──────┴─► 同一个构造函数,产出相同条目
+                    ▼
+请求投影:transform 按 blockIndex 排列 content 与 toolCalls(所有 provider)
+          Anthropic:空白文字过滤 + 工具调用后移 + 末尾思考块 ─► 其余交给 AI SDK
+```
+
+## blockIndex
+
+### 含义
+
+- 一次模型响应里块的到达序号,从 0 开始。
+- reasoning、text、tool(包括服务端执行的工具)共用一个序号空间。
+- 序号可以不连续,只用于排序,不表示数量。
+- 服务端工具让响应分成多轮时,计数器不重置。
+
+### 位置
+
+| 位置                                                         | 字段                                                                                            | 校验                                                                                                                               |
+| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
+| 库:`TextPart` / `ReasoningPart` / `ToolPart`                | 顶层可选 `blockIndex?: number`,存在 `part.data` JSON 里,和 `ToolPart.declarationIndex` 同一层 | part 没有 strict schema;不进入 App 协议,message-mapper 只复制已知字段                                                            |
+| 内存:`ModelToolCall` / `ToolCallInput`                      | 可选 `blockIndex`                                                                               | `modelInputMessageJsonSchema` 的 `toolCalls` 是宽松数组                                                                            |
+| 内存:`ModelTextContentBlock` / `ModelReasoningContentBlock` | 可选 `blockIndex`                                                                               | 在 strict 的 `modelInputMessageJsonSchema` text / reasoning 分支里显式声明 `{ type: "integer", minimum: 0 }`;其他未知字段仍被拒绝 |
+
+- 不放进 reasoning 的 `metadata`。hydrator 会把 `metadata` 原样变成 `providerOptions`,放在那里会
+  让空 reasoning 的判定失效,也有进入请求的风险。
+- 内存里的消息不落库,运行时也不校验 `modelInputMessageJsonSchema`。在 schema 里声明这个字段不会造成
+  降级时丢数据。
+- `transform.ts` 逐个字段构造 AI SDK part,`blockIndex` 不进入 provider 请求。
+
+### 分配
+
+只在两处分配:
+
+**流式**(`core/src/runtime/methods/model.ts`,每次模型请求一个计数器):
+
+| 块        | 分配时机                                                                                         |
+| --------- | ------------------------------------------------------------------------------------------------ |
+| reasoning | `getOrCreateReasoningBlock` 新建块时(覆盖没有 start 事件的 delta)                              |
+| text      | `text_start` 新建块时。`text_delta` 找不到对应块,或者该块之后已经分配过其他块,就新开一个块     |
+| tool      | `tool_input_start` 时。没有 start 事件的 `tool_call`(例如 `mcp_tool_use`)在 `tool_call` 时分配 |
+
+- 不使用 provider 的序号。Anthropic 的 `tool_use` 事件 id 是 `toolu_…`,不是块位置。
+- openai-compatible 在工具调用之后不关闭文字块,文字 id 会复用(`txt-0`),所以需要上面的"新开块"规则。
+  这次响应里已经有文字块、新块又没有 `text_start` 时,补发一个 `text_start` 事件,让 live 界面分行。
+  第一个文字块不补发,事件流和改动前相同。
+- 工具调用的 `blockIndex` 在 push、`onStreamToolCall` 和服务端工具分轮之前写入调用对象。
+- 结果和快照新增 `textBlocks`(`RuntimeModelTextResult`、`RuntimeModelStreamSnapshot`、
+  `ProviderToolRound`、contracts `ModelTextResult`)。`text` 仍然是所有文字直接拼接,
+  `modelResponse`、Stop hook、TUI 去重和 turn machine 不变。
+
+**非流式**(`adapters/src/model/runner-generate.ts`):按 AI SDK `result.content` 的顺序给 reasoning、
+text、tool-call 编号,跳过 tool-result、source、file 等其他类型。结构化输出不分配。
+
+### 写入
+
+写库时机不变。每一次写入都带 `blockIndex`:
+
+- reasoning part 带所属块的序号。
+- 文字按 `textBlocks` 每块写一个 text part。空字符串块不写。
+- 服务端工具轮次(`provider-tool-rounds/cards.ts`)里的 reasoning、每段文字和服务端工具 part 都带序号。
+- tool part 的 pending、running、completed / error 每一次写入都带序号。同一个 part 的后续写入在
+  `savePart` 里走冲突更新,整体替换 `data`(只保留 `fromModel` / `toModel` / `model`),漏写一次就会
+  丢失序号。丢失后整条消息按旧消息处理,不报错也不打日志,排序回到改动前的布局。**维护约束**:新增
+  tool part 写入点时,必须带上调用对象的 `blockIndex`。
+- 取消时按快照里的 `textBlocks` 写(`cancelled-stream-persistence.ts`)。
+- automation fallback 替换文字时,只写一个 fallback 文字块,序号取当前最大值加 1。
+- `declarationIndex` 不再写入;读取逻辑保留给旧数据。
+
+浏览器轮尾截图 part(`state.input.source === "browser_turn_end"`)不是模型块,不带 `blockIndex`。
+识别时 `state` 或 `state.input` 缺失(损坏数据)按普通 tool part 处理,一个坏 part 不会中断整个会话的读取。
+
+### 工具执行与结果顺序
+
+本地工具的结果按 `blockIndex` 稳定排序后的顺序提交,排序只在 `executeToolCallsForModelStep` 做一次。
+流中提前执行的只读工具在 `tool_call` 到达时就写 pending part 并开始执行;其余工具的调度、pending part 写入
+和执行也按排序后的顺序进行。正常结束、断流恢复、执行模型回退三条提交路径都经过这里。
+
+- 原因:工具的 `blockIndex` 在 `tool_input_start` 分配,`toolCalls` 却按 `tool_call` 到达排列。两者不同时,
+  live 的结果按到达顺序,冷恢复(`selectToolPartsForHistory`)按 `blockIndex`,请求字节不同。只用一个顺序来源,
+  live 与冷恢复的 tool_use 和结果顺序才一致。
+- 只在所有调用都有合法 `blockIndex` 时排序;旧数据、未编号的非流式结果保持原顺序。
+- Anthropic、Responses 的块依次到达,两种顺序相同,行为不变。openai-compatible 在流结束时按 index 发出
+  全部 `tool_call`,只有后一个调用的名字先到达时两种顺序才不同;这时执行和结果顺序变为块开始的顺序。
+
+## 读取
+
+### 有序判定
+
+一条 assistant 消息满足以下两条时是有序消息:
+
+1. 至少有一个 reasoning、text 或 tool part;
+2. 所有 reasoning / text / tool part 都有合法 `blockIndex`。浏览器轮尾截图 part 不参与判定。
+
+不满足时按旧消息处理。不存在"部分有序"的处理方式。
+
+`blockIndex` 是否合法,库、runtime、请求投影三层都用 contracts 的 `isBlockIndex`(非负整数)判定。
+只有库这一层要求至少一个块 part:没有块 part 的旧消息留在旧路径,空消息的处理不变。
+
+### 读取边界排序
+
+session-store repository 的两个解码点(`messages()`、`messageWithParts()`)对有序消息做稳定排序:
+
+- 只在 reasoning / text / tool part 占用的位置之间按 `blockIndex` 重排。
+- step-start、step-finish、file 等其他 part 的位置不变。
+- 序号相同时保持物理顺序。同一工具调用的重试 part 共用序号,"同一 callID 取最后一个 part"仍然成立。
+- 旧消息保持物理顺序。
+
+### 模型历史恢复
+
+`session-history-hydrator.ts` 对每条 assistant 消息:
+
+1. 先跳过浏览器轮尾截图 part。它不进入模型历史。live 从来不把它放进模型历史;以前冷恢复会把它变成
+   一个工具调用加结果,导致冷恢复请求和 live 不同。UI 仍然从原始 parts 显示它。这一步对新旧消息都生效,
+   带截图的旧消息因此有一次缓存未命中,见「兼容」。
+2. 有序消息:把 part 映射成块,调用统一构造函数 `buildAssistantEntries`。本地工具结果按 `blockIndex`
+   顺序输出。
+3. 旧消息:现有逻辑不变。工具按 `selectToolPartsForHistory` 选择和排序:全部有 `blockIndex` 时按它,
+   否则全部有 `declarationIndex` 时按它,否则按物理顺序。同一 callID 只取最后一个 part。
+
+### 统一构造函数
+
+`buildAssistantEntries({ blocks, model, usage, groupKey, keepEmptyFinal })`
+(`core/src/agent/message-history.ts`)是 live 与冷恢复构造有序 assistant 条目的唯一入口:
+
+- 按 `blockIndex` 稳定排序。
+- 去掉没有内容的 reasoning(`hasAssistantReasoningContent`)和空字符串文字。
+- 遇到服务端工具时分轮,分轮规则不变。
+- 本地工具放进最后一个条目。
+- `content` 是不合并的块数组,`toolCalls` 带 `blockIndex`。
+- usage 只在没有分轮时附加。
+
+live 调用方:`commitAssistantToTurnRequest`、取消路径、streaming coordinator 恢复路径、服务端工具轮次。
+`createRuntimeAssistantEntry` 只用于旧消息、memory agent 和 turn-stop 的空 usage 锚点。它构造的是旧条目,
+不带 `blockIndex`:非流式结果会在原对象上给 reasoning 编号,这里复制时去掉,旧条目不会被当成部分有序。
+
+两个函数共用条目外壳和工具调用复制函数:工具调用只复制 id、name、input、modelCallWrapper,
+`providerExecuted` 等运行时标记不进入历史;有序条目另外带 `blockIndex`。服务端工具的分组键都由
+`withCompactGroupKey` 写入。
+
+## 请求投影
+
+### 排列(所有 provider)
+
+`transform.ts` 构造 assistant 消息时,用 `orderedAssistantItems` 判定和排列:
+
+- 所有内容块和工具调用都有合法 `blockIndex`:放在一起按 `blockIndex` 稳定排序,序号相同时内容块在前。
+- 否则保持旧拼接 `[...content, ...tools]`。
+
+这一步只改变顺序,不合并块。下面的 Anthropic 规则也用 `orderedAssistantItems`,所以两边的有序判定和
+排列结果相同。
+
+### Anthropic 规则
+
+在 `reasoning-history-normalization.ts` 里按条目执行。只处理有序条目,在跨模型过滤之后计算。
+这些规则只删除或移动块,不合并块。
+
+**逐块合并**
+
+规则 a 和 b 不是对整个条目各执行一次,而是按 `blockIndex` 顺序逐块加入:
+
+1. 第一个块单独成为结果。
+2. 之后每加入一个块,对"上一步结果 + 新块"先执行 a,再执行 b,得到新的结果。
+
+前一步已经删除或移动的块不会恢复。所以结果和"对整个条目执行一次"在两种形态上不同:
+
+- 空白文字是当前最后一块时,它后面还没有块,不满足"前后都是思考块",会被删除(只剩思考块时除外)。
+- 工具后面的思考块加入时,如果它前面的内容块不是思考块,工具已经被移到末尾;之后再出现
+  "思考 → tool_use → 思考"也只影响剩余顺序。
+
+**a. 空白文字过滤**
+
+- 去掉纯空白的文字块。前后两个块都是思考块时保留。
+- 过滤后只剩思考块时,放弃这次过滤,使用过滤前的块。
+
+**b. 工具调用后移**
+
+- 第一个 tool_use 后面还有非工具块时,把所有 tool_use 移到末尾,工具之间保持相对顺序。
+- 例外:出现"思考 → tool_use(s) → 思考"时,保持原顺序。
+
+请求里的顺序通过重新编号 `blockIndex` 表达,只改请求副本,不改 canonical history。
+
+| 模型输出                          | 回放                                                                          |
+| --------------------------------- | ----------------------------------------------------------------------------- |
+| `[思考A, 文字P, t1, 文字Q]`       | `[思考A, 文字P, 文字Q, t1]`                                                   |
+| `[思考A, t1, 思考B, t2]`          | 命中例外,原样                                                                |
+| `[思考A, 文字P, t1, 思考B, t2]`   | `[思考A, 文字P, 思考B, t1, t2]`                                               |
+| `[思考A, 文字P, t1, t2]`          | 原样(工具后面没有其他块)                                                    |
+| `[文字P, t1, 思考A, t2, 思考B]`   | `[文字P, 思考A, t1, t2, 思考B]`(加入思考A时 t1 已后移;加入思考B时命中例外) |
+| `[思考A, 空白, 思考B, 文字P, t1]` | 原样(空白在两个思考块之间)                                                  |
+| `[文字P, 思考A, 空白, 思考B, t1]` | `[文字P, 思考A, 思考B, t1]`(加入空白时它是最后一块,被删除)                 |
+| `[空白, 思考A, 文字P, t1]`        | `[思考A, 文字P, t1]`                                                          |
+| `[t1, 文字P, t2]`                 | `[文字P, t1, t2]`                                                             |
+
+**c. 末尾思考块**
+
+`removeTrailingReasoning` 只处理请求里的最后一条消息。对有序条目,按请求顺序删掉末尾连续的思考块,
+不重新执行 a、b。旧条目仍使用原规则。
+
+**签名修复**
+
+`removeRejectedReasoning` 追加的 `[Thinking removed]` 文字块,`blockIndex` 取最大序号加 1,然后重新
+执行逐块合并。`repairEmptyAssistantContent` 不变。
+
+修复成功后的 `signedReasoningReset` 标记([Anthropic Reasoning History Replay](./anthropic-reasoning-history-replay.md))
+对有序条目同样生效:live 在 `buildAssistantEntries` 的结果上用 `markRepairedStep` 标记第一条 assistant;
+冷恢复的有序分支按消息 metadata 对同一个构造结果做同样的标记,两边条目一致。之后的请求删除标记之前的
+签名思考时也调用 `removeRejectedReasoning`,有序条目同样重新执行逐块合并,和修复那次发出的字节一致。
+
+**d. 没有可见内容的回复**
+
+没有工具调用、每个块都是思考或纯空白文字(含 `(no content)`)时,删除这条 assistant,有序条目和旧条目用同一条
+判断。删除在 core 请求投影的第一步,只在 Anthropic Messages 协议执行
+([Anthropic Reasoning History Replay](./anthropic-reasoning-history-replay.md)「Core: which assistant messages exist」)。
+adapter 不删除也不合并消息。字符串 content 和空数组不删除:完全没有输出的回复存成空字符串,带着 usage,
+留作估算锚点;空数组的每个块都满足条件,也单独排除。
+
+- 只有空白文字的有序回复(例如模型只回了 `"\n\n"`)会被删除。这是本次带来的变化:
+  改动前没有思考块的回复 content 是字符串,这条规则只处理数组,所以不生效。live 发出 `"\n\n"`;
+  冷恢复在没有 usage 时跳过这条回复,有 usage 时也发出 `"\n\n"`,两边可能不一致。现在有序条目的
+  content 是数组,live 和冷恢复都删除,两边一致。旧消息仍是字符串,请求字节不变。
+- `[思考A, "\n\n"]` 这类只有思考和空白的回复也删除,和只有思考块的回复相同。改动前它原样进入请求(规则 a
+  删掉空白后只剩思考块,所以放弃过滤);已有这类回复的会话升级后,从这条回复起前缀缓存失效一次;校验前缀的渠道
+  还可能拒绝一次,由签名修复恢复(见 Anthropic Reasoning History Replay 的「Accepted effects」)。
+- 删除按条目判断,不按相邻条目整段判断。相邻的 assistant 条目由 AI SDK 合成一条消息,只有下面两种来源;
+  按条目删除都不会带来新的前缀变化:
+  - 输出上限续写:续写提示只在本轮请求里,不写入历史,所以下一轮两段回复相邻。产出第二段的请求里,只有思考的
+    第一段已经被删除(那时它后面是续写提示)。按条目删除时,第二段思考块前面的内容和产出时一致,只少续写提示
+    (原有差异);整段保留反而会把第一段的思考放回去。
+  - 没有结果的服务端工具:只在中断收口本身失败时出现,而且只在 live 出现(冷恢复回放为 INTERRUPTED 结果,
+    条目带工具调用,不删除)。这时这次调用已经从历史里丢掉,后面思考块前面的内容本来就变了。
+
+### 交给 AI SDK 的行为
+
+ZCode 不自己合并消息或文字块。所有协议都接受 AI SDK 的序列化结果:
+
+- Anthropic:`groupIntoBlocks` 合并相邻 assistant 条目;只有请求的最后一条消息是 assistant 时,它的最后
+  一个文字 part 被 trim;空字符串文字 part 被丢弃;消息级 cache control 只放在最后一个 part 上。服务端工具让一条消息
+  拆成多个条目时,上面的规则只在各自条目内执行,不跨条目移动块。
+- chat-completions:文字由 AI SDK 直接拼接。
+- Responses:按顺序生成多个 item。只影响新消息。
+
+## App 投影
+
+- 冷恢复按排序后的 part 输出行,和 live 一样每个文字块一行。
+- 反馈:`onAssistantFeedbackUpdated` 作用在该 entity 的最后一个文字行。UI 从最后一个文字行读取反馈;
+  以前作用在第一行,多行时反馈不显示。
+- 搜索索引:`zcodeTaskIndexSyncer` 把一条 assistant 消息的所有文字 part 按顺序直接拼接,还原成改动前
+  那一个文字 part 的内容,再按原规则处理(trim、跳过空文字、总长上限)。普通消息的索引内容和改动前相同。
+  服务端工具分轮的消息以前只取最后一个文字 part,现在包含所有轮的文字。
+- session-transcript 和 subagent 查询用 `"\n\n"` 拼接文字 part。多个文字块的消息从 `"AB"` 变成
+  `"A\n\nB"`,和 UI 复制结果一致。
+- bots `/status` 的进度:任务运行中没有实时进度时,读最近一条 assistant 消息按顺序的最后一个块
+  (`readLatestTaskProgress`)。多个文字块的消息现在显示最后一个文字块,以前显示整段文字。
+
+## 兼容
+
+- **旧消息**:走旧逻辑,请求字节不变,升级后没有一次性缓存未命中。例外是带浏览器轮尾截图的旧消息:
+  以前冷恢复把截图回放成一次工具调用加结果,升级后不再回放(和 live 一致),所以从这条消息开始有一次
+  缓存未命中。这是接受的代价。这条消息里其他工具的顺序也会变:截图 part 没有 `declarationIndex`,以前整条
+  消息因此按物理顺序排列工具;跳过截图后,其余工具都有 `declarationIndex`,改按声明顺序排列。这个变化
+  包含在同一次缓存未命中里。
+- **混合消息**:只要有一个模型块 part 缺少 `blockIndex`,整条消息按旧消息处理,不报错也不打日志。
+  当前所有写入点都带序号。混合消息只会来自降级后旧版本改写同一个 part,或者以后新增的写入点漏写
+  (见「写入」的维护约束)。
+- **降级**:旧版本忽略 `blockIndex`。它用 `"\n\n"` 拼接多个文字 part,把思考块放到最前,工具按物理
+  顺序排列:新写入不带 `declarationIndex`,旧版本没有声明序号可用,流中先写库的只读工具排在前面。
+  结果和新版本发出的字节不同,会有一次缓存未命中。如果某条消息里文字后面还有思考块,
+  在执行签名校验的渠道上可能返回 400。旧版界面会多出几行,旧版搜索索引只取最后一段文字。
+
+## 已知差异(不在本规格范围内)
+
+- 服务端工具没有结果时:流结束、失败或取消时先按中断收口([Anthropic Stream Compat](./anthropic-stream-compat.md)
+  「中断收口」),live 与冷恢复都回放为 tool_use + INTERRUPTED 错误结果。只有收口本身失败时,live 才丢掉
+  这次调用,冷恢复仍按 INTERRUPTED 回放。
+- 已有本地工具提交时的断流恢复:live 不带这次 attempt 的服务端轮次,冷恢复却回放它(改动前已存在),见
+  [本地 issue](../../../../../../docs/issues/stream-recovery-provider-round/01-cold-resume-replays-dropped-provider-round.md)。
+- 用户中途停止时:live 不保留本地工具,冷恢复按 INTERRUPTED 回放。
+- 停止时进行中的文字不单独成块。
+- 空文字块(`""`)不写库,也不进入请求。两个思考块之间的空文字块因此不占位置:模型输出
+  `[思考A, "", 思考B, 文字P]` 时,请求是 `[思考A, 思考B, 文字P]`。
+- 在工具调用后移的例外形态下,assistant 条目可能以思考块结尾。这条 assistant 是最后一条非 system
+  消息时,AI SDK 会丢掉消息级 cache control。
+
+## 测试
+
+- contracts / core:`json-schema.test.ts` 接受带 `blockIndex` 的 text / reasoning 块,仍拒绝其他未知字段。
+- core:
+  - 流式分配:Anthropic 事件序列;openai-compatible 工具后复用文字 id 的拆块;没有 start 事件的
+    `tool_call`;服务端工具分轮时计数器不重置。
+  - 每个写库点都写 `blockIndex`,包括 pending → running → completed 的重复写入。
+  - 统一构造函数、hydrator 有序分支、`selectToolPartsForHistory`、截图 part 不进入模型历史。
+  - 请求投影按条目删除:两条相邻 assistant 条目中只删只有思考的那条(输出上限续写的形态)。
+- 字节一致性:真实 SQLite + 抓取 Anthropic 请求体,同一条交错消息 live 请求等于冷恢复请求。
+- 旧数据:工具写库顺序和 `declarationIndex` 不一致、单个文字 part、带 reasoning 的旧消息,冷恢复后的
+  历史与请求体和改动前布局完全相同。
+- adapters:transform 排列且 `blockIndex` 不进入请求;逐块合并的形态表(缩写与 E2E I76 相同)、末尾思考块、
+  adapter 不删除只有思考和空白的有序回复、签名修复(修复标记之前的有序条目在之后的请求里
+  与修复那次重发的字节一致);非流式结果对不上时整条不编号;
+  repository 排序对旧数据和混合数据保持物理顺序,
+  `state` 或 `input` 缺失的损坏 tool part 不中断读取。
+- bootstrap:transcript-hydration 输出多个文字行;反馈落在最后一个文字行。tool-history-order 走真实 SQLite:
+  服务端调用和本地工具共用序号(write=0、native=1、read=2),没有结果的服务端调用回放为中断错误结果,
+  读取边界按 `blockIndex` 返回流顺序,live、冷恢复和回退后的请求相同;断流恢复用例按「已知差异」断言
+  冷恢复多出的服务端轮次。另一个用例让 `tool_input_start` 的顺序
+  和 `tool_call` 的到达顺序相反,live 与冷恢复的 tool_use 和结果都按 `blockIndex` 排列。
+- prompt-trajectory:请求删掉纯空白文字块后,model-io 摘要仍能认出同一条回复,轨迹不拆分。
+- 桌面 E2E(I76,`conversation-session/conversation-session-assistant-block-order`):
+  - 块形态在同一会话回放(S16 单独一个用例):live 与冷恢复的行序;续发请求逐形态块顺序等于上面的规则表;
+    冷恢复前后请求只在末尾追加;全部思考签名原样带回;同一会话的相邻主请求逐个比较抓到的请求体,
+    都只在末尾追加,例外只有 S19 的续写。轨迹工具用 model-io 摘要重建响应,表示不了 S20 的服务端工具
+    分轮,所以不用它判定。除了 Read 的形态,还有:
+    - S18:Write 不是只读工具,流结束后才执行和写库。live 与冷恢复的行序都是文字 P、Write 卡片、文字 Q。
+    - S19:响应因输出上限(`max_tokens`)停止。自动续写的请求按流顺序带回已经输出的块;之后的请求里,
+      续写前后的两段回复按流顺序排列。续写提示不写入历史(TS09-CONTINUE),所以之后的请求去掉续写提示,
+      续写文字接在原 assistant 消息末尾,原有的块不变。
+    - S20:服务端工具(未知名称的 `server_tool_use` 加 `tool_result`)把一次响应分成两轮。序号跨轮不重置,
+      行序和请求都按流顺序。
+  - 停止时已完成的块、反馈落在最后一个文字行并在冷恢复后保留、任务搜索找到第一段文字、手机 `/remote` 行序。
+  - 只有思考和空白的回复(S16)不进入续发请求:思考文字和空白都不发出,前后两条 user 都在请求里,冷恢复前后
+    请求相同。
+  - openai-compatible 在工具调用后继续输出文字:live 与冷恢复都分成两行,续发请求相同。
+  - 旧消息:应用退出期间,把一条已完成的消息改写成改动前的存储格式(去掉 `blockIndex`,多个文字 part
+    合并成一个,工具 part 写回 `declarationIndex`)。重启后的续发请求按旧布局
+    `[全部思考, 一段文字, 全部 tool_use]` 发送。之后在同一会话追加新消息,冷恢复前后请求只在末尾追加,
+    旧消息的字节不变。工具写库顺序和 `declarationIndex` 不一致的旧数据由单测覆盖。
+- 桌面 E2E(`manual-review/pending/conversation-session-browser-use-iab-full-chain`):轮尾截图 part 不进入
+  模型历史。一轮只打开一次页面并正常完成,产生轮尾截图;冷恢复前后各续发一次,请求里只有模型发起的这一次
+  工具调用,冷恢复前后截图这一轮的消息不变。冷恢复前续发的那条 user 消息不比较:live 在内存历史里给它加了
+  内置浏览器上下文,存库只存用户原文,冷恢复后两者不同(改动前已存在,与本规格无关)。
+- 只由单测覆盖(桌面没有触发入口):
+  - 非流式路径:adapter 按 `result.content` 编号,与已规范化的 text / reasoning / toolCalls 对不上时不编号,
+    按旧数据处理。桌面协议端固定 `modelStreaming: "on"`。
+  - 末尾思考块:只在请求的最后一条消息是 assistant 时生效。桌面请求的最后一条是 user 消息、续写提示或工具结果。
+  - 签名修复占位块的 `blockIndex`:占位块总是在最后,有没有序号,请求字节都相同,E2E 无法区分。签名修复的
+    重试流程由 I72 覆盖。

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

@@ -0,0 +1,174 @@
+# Context 组成(Context Composition)
+
+> 状态:P1 第 1 段已实现(CLI 生成、预演、协议、App 侧接口)。总设计见 [扩展进程](../../../../../../docs/plugins/extension-host.md)。
+> 基线:staging `2015563fc3`,实现时按代码重新核对,差异已改进本文。
+
+## 1. 目标
+
+让 App 外的消费方(第一个是扩展插件)读到「当前模型请求里各部分占多少」。
+
+- 只给类别、条目名和大小,不给正文。
+- 发送前(草稿)给出首个请求的预演。预演没有副作用。
+- 变化时通知,通知只带修订号,消费方按需拉取。
+
+## 2. 现状(实现前的事实)
+
+- 每次模型请求前,runtime 已经在算一份分解:`buildContextUsageSnapshot`(`packages/core/src/runtime/methods/context-usage.ts:119-253`),调用点 `model.ts:147-149`。分 7 类,每类带 `chars`、`tokens`、`tokenMethod`、明细。
+- 这份分解有两个出口:
+  - debug 日志 `context_usage_snapshot`(`context-usage.ts:45-57`)。按 [debug-observability](../debug-observability.md) 的定义,它不是稳定 API。
+  - 降维成 `{source, chars}`,作为 `ModelComplete.contextUsageBreakdown` 下发,只在主轮请求(`turn-model-step.ts:749-751`)。App 用它画输入框用量圆环的分段条([分段条 spec](../../../../../../docs/superpowers/specs/2026-06-11-context-usage-breakdown-bar.md))。
+- 圆环线格式的 `source` 是严格枚举,7 个值(`packages/shared/src/zcode-protocol-legacy-types.ts:499-514`)。
+- 没有 context 预演 API。
+
+### 2.1 现有分解的缺口
+
+| 缺口                                                                                                                                                         | 位置                                                  |
+| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------- |
+| 以 `<system-reminder>` 开头的 user 消息被排除出 messages,environment、agent listing、ToolSearch 公告、todo 等提醒漏算;MCS 下提醒变成 system 消息,同样漏算 | `context-usage.ts:147-155`                            |
+| `deferLoading` 工具仍按全量 schema 计入                                                                                                                      | 工具分类处                                            |
+| `app__` 工具被算成内置工具,因为只认 `mcp__` 前缀                                                                                                            | `runtime/helpers/tool-result.ts:144-157`              |
+| compact summary 没有单独类别,归在 messages                                                                                                                  | `compact-active.ts:624-627` 的 `compactBoundary` 消息 |
+| skills 与指令按 builder sections 估算,不读真实 attachment 文本                                                                                              | `context-usage.ts:134-140`                            |
+
+来源信息可用:`buildProviderRequestMessages` 返回与 messages 同索引的 `sourceEntries`(`runtime/helpers/provider-request-messages.ts:33-43,106-113`),`metadata.source` 能区分提醒来源、真实用户输入与 `compactBoundary`(`agent/message-history.ts:63-96`)。MCS 投影出的 system 提醒,`sourceEntries` 指回原 attachment;context 前缀的 system 消息没有 metadata,靠 `latestContextBuildResult.sections` 归因。
+
+## 3. 设计
+
+### 3.1 一份分解,两个出口
+
+`buildContextUsageSnapshot` 改为调用分类纯函数 `classifyContextComposition`,不另建第二套。它产出**细类别**;圆环需要的粗类别由纯函数 `projectContextCompositionToUsageSources` 从细类别投影出来。只有一处计算。
+
+| 细类别 id               | 内容                                                                          | 来源                                                                                | 投影到圆环的粗类别                                              |
+| ----------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------- |
+| `system_prompt`         | 系统提示词                                                                    | sections:`system` 注入、来源不是 `skills`/`tools`                                  | `system_prompt`                                                 |
+| `meta_user_context`     | 指令(AGENTS.md、记忆索引)                                                   | 请求里 `context_prefix` 公告的真实文本;无 metadata 的旧版 `<system-reminder>` 前缀 | `meta_user_context`                                             |
+| `skills`                | 技能列表                                                                      | 请求里 `skills_listing` 公告的真实文本                                              | `skills`                                                        |
+| `tool_prompt`           | 工具说明                                                                      | sections:来源 `tools`                                                              | `tool_prompt`                                                   |
+| `system_tool_schemas`   | 内置工具定义                                                                  | 请求 tools,非 `mcp__`/`app__`、非延迟加载                                          | `system_tool_schemas`                                           |
+| `mcp_tool_schemas`      | MCP 工具定义                                                                  | 请求 tools,`mcp__` 前缀                                                            | `mcp_tool_schemas`                                              |
+| `app_tool_schemas`      | 页面工具定义(`app__` 前缀)                                                  | 请求 tools,`app__` 前缀                                                            | `system_tool_schemas`(与改前一致)                             |
+| `deferred_tool_schemas` | 延迟加载的工具,只计 `{name, description}`                                    | 请求 tools,`deferLoading: true`                                                    | `mcp__` 前缀归 `mcp_tool_schemas`,其余归 `system_tool_schemas` |
+| `reminders`             | 其余提醒(环境、模型、日期、Git、模式、子代理列表、ToolSearch 公告、todo 等) | 请求里其余已知 reminder 来源的消息                                                  | `meta_user_context`                                             |
+| `compact_summary`       | 压缩摘要                                                                      | 带 `metadata.compactBoundary` 的消息                                                | `messages`                                                      |
+| `messages`              | 对话消息                                                                      | 其余消息;`inputPresentation: "task_notification"` 的新轮通知也在此                 | `messages`                                                      |
+
+- 每条消息按 `JSON.stringify({role, content, toolCalls, toolCallId, toolName})` 计 `chars`,用 `estimateTokens` 估 token(与改前 messages 的口径相同)。工具按完整契约 JSON 计;延迟加载工具只计 `{name, description}`。
+- 现有 7 个 id 不改名。圆环线格式的枚举**一字不改**,新类别只出现在 §3.3 的查询结果里。理由:远程工作区的 CLI 版本可以和 App 不同;往严格枚举里加值,旧的一方会解析失败。
+- 修掉缺口后,圆环的数值会更准(提醒计入「其他」,指令按真实文本计),形状和枚举不变。
+- 已知局限:模型能力 `foldRemindersIntoToolResults` 为真时,紧跟工具批次的提醒会并进 tool 消息,这部分计入 `messages`。`sourceEntries` 对合并后的消息只保留代表条目,无法再拆。
+- 细类别的类型来自 shared 线格式(§3.2),`runtime/types.ts` 不改(原设计计划扩 `ContextUsageCategory.source`,实现时改为粗/细两套类型分开,避免 1048 行的文件再变大)。
+- CLI 新代码放 `packages/core/src/runtime/context-composition/`(分类、状态、预演)与 `packages/bootstrap/src/zcode-protocol/context-composition/`(修订号与协议处理)。两个目录与 shared 线格式同属 managed 模块 `context-composition`。
+
+### 3.2 线格式
+
+放 `packages/shared/src/zcode-protocol-v4/context-composition/contract.ts`(managed 模块 `context-composition`),zod schema 是唯一定义,经 `@zcode/shared/zcode-protocol-v4` 导出。
+
+```ts
+interface ContextComposition {
+  sessionId: string;
+  revision: number; // 每会话单调递增,见 §3.4
+  phase: "request" | "draft-preview";
+  measuredAt: number; // 毫秒时间戳
+  model: { providerId: string; modelId: string; contextWindow: number | null };
+  tokenMethod: "estimated";
+  estimatedTokens: number; // 各类别 token 之和
+  providerInputTokens?: number; // 只在 phase=request:该请求服务商报告的 input tokens
+  providerContextTokens?: number; // 只在 phase=request:与输入框用量圆环同一个值(input + 本次 output)
+  freeTokens: number | null; // max(0, contextWindow - estimatedTokens);contextWindow 未知时为 null
+  categories: Array<{
+    id: ContextCompositionCategoryId; // §3.1 的细类别
+    tokens: number;
+    chars: number;
+    items?: Array<{ name: string; tokens: number }>; // 按 token 降序,最多 50 条
+  }>;
+}
+```
+
+- 只给名字和大小:工具名、技能名、指令文件路径、提醒来源名、section 名、消息角色。不给消息正文、工具 schema、提醒正文。
+- 条目名最长 200 字符。0 值类别不返回。
+- token 是估算值(`context/utils.ts:12-18` 的 `estimateTokens`),`providerInputTokens` 供对照,取 `getModelUsageInputWindowTokens(usage)`。
+- `providerContextTokens` 取 `getModelUsageContextTokens(usage)`,与 V4 状态 `usage.contextWindow.usedTokens`(输入框用量圆环)用同一个函数、同一份 usage,所以两者相等。它比 `providerInputTokens` 多出这次请求的 output tokens:这些 token 会进下一次请求的上下文。消费方要和圆环对齐时用它,不要自己用 input 加 output 再算一遍。
+- 兼容:App 侧的 schema 是 strict。新字段可选;查询只来自本机工作区(扩展进程的 `context.get`,见 `docs/plugins/extension-host.md` §16),本机 CLI 与 App 同一个构建,不会出现新 CLI 对旧 App。远程工作区的 CLI 可以比 App 新,以后给远程会话开放这个查询时要先加能力位。
+
+### 3.3 协议
+
+- 查询:`v4/conversation/contextComposition`,参数 `{ sessionId, modelSelection? }`(strict),返回 `{ composition: ContextComposition | null }`。
+  - 会话不在内存时返回 `null`,不为查询冷启动或恢复会话(existing-only)。
+  - 会话没有模型选择、参数也没给时返回 `null`。
+  - 最近一次请求组成有效(§3.4)且模型与所查模型的 `providerId`/`modelId` 相同:返回该请求的组成,`phase: "request"`。思考档位不影响组成,不参与比较。
+  - 否则(草稿、还没发送、刚换模型、请求组成已作废):返回按所查模型预演的下一个请求,`phase: "draft-preview"`。
+  - `modelSelection` 是完整模型选择(含思考档位);省略时用会话当前模型。所查模型在 provider 注册表里不存在时,模型工厂的错误原样返回给调用方。
+- 通知:`v4/conversation/contextCompositionChanged`,参数 `{ sessionId, revision }`。live-only,不进 snapshot。
+- 旧 CLI 不认识方法时返回 method-not-found(-32601)。App 侧把它当作 `null`,界面显示「当前版本不支持」。
+- `transport.ts` 的 `V4_METHODS.conversationContextComposition` / `V4_NOTIFICATIONS.conversationContextCompositionChanged`;`bootstrap/src/zcode-protocol/server.ts` 只加一行 case,逻辑在 `zcode-protocol/context-composition/handler.ts`。
+
+### 3.4 变更触发与修订号
+
+修订号的唯一 owner 是 bootstrap 的 `ContextCompositionRevisionTracker`(每个协议 server 一份)。
+
+- 每会话从 0 开始,CLI 进程内单调递增;runtime 重建(冷恢复)不重置。CLI 进程重启后从 0 重新开始,消费方以通知为准刷新,不跨进程比较。
+- 查询在测量**之前**读修订号。测量期间又有变化时,后到的通知带更大的修订号,消费方按修订号丢弃旧结果。
+- runtime 在下列事件同步调用监听器;tracker 用 `queueMicrotask` 把同一会话同一轮事件循环内的多次触发合并成一次「修订号加一 + 一条通知」,不用定时器。
+
+| 事件                                  | 位置                                                                                             | 请求组成                                              |
+| ------------------------------------- | ------------------------------------------------------------------------------------------------ | ----------------------------------------------------- |
+| 主轮请求的分解算好                    | `model.ts` 的 `runModelTextRequest`                                                              | 记为最近一次请求组成                                  |
+| 该请求完成,服务商 usage 到达(新增) | 同上,返回结果前                                                                                 | 补上 `providerInputTokens` 与 `providerContextTokens` |
+| compact 完成                          | `compact-active.ts` 替换历史之后                                                                 | 作废                                                  |
+| 工具缓存失效(MCP、页面工具变化)     | `config.ts` 的 `invalidateToolCache`                                                             | 作废                                                  |
+| 上下文前缀重建                        | `context-refresh.ts` 的 `rebuildContextPrefix`                                                   | 作废                                                  |
+| 换模型                                | `bootstrap/src/app/session-facade.ts` 的 `setModel` 调 `runtime.markContextCompositionChanged()` | 作废                                                  |
+
+「作废」:这些事件之后下一个请求的组成必然不同,再返回旧请求的组成会误导,所以查询改为预演,直到下一次主轮请求算好分解。轮开始时也会重建前缀,因此每轮首个请求之前的查询都是预演。
+
+事实:MCP 的 `list_changed` 在回合之间不会主动产生事件,只在回合开始时检查(`mcp.ts:222-266`、`turn-loop.ts:94`)。所以回合之间 MCP 工具变化要到下一轮才反映。本版不改。
+
+### 3.5 草稿预演
+
+runtime 方法 `getContextComposition({ modelSelection?, traceContext? })` 在需要预演时按下面顺序走,在 entries 的**副本**上模拟:
+
+1. `ensureContextInitialized(trace, model)`(`context.ts:43-100`)
+2. `initializeMcp`
+3. 按所查模型新建 context builder 并 `build()`,`persistEnvInfo: false`,不写回 `contextBuilder`/`latestContextBuildResult`/历史(不调 `rebuildContextPrefix`)。前缀换成新结果,其后接历史的对话部分。
+4. 用纯函数模拟输入附件与请求前公告,顺序同 `turn-loop.ts`:环境、模型、output style 指令 → ToolSearch 公告(`buildToolSearchAnnouncement`)→ 子代理列表(`collectRuntimeAgentListing`)→ 技能列表(`collectSkillsListing`)→ 计划模式提醒(`buildRuntimeModeReminderBody`)→ output style 提醒 → 指令、Git、日期(`buildRequestAnnouncements`)。
+5. `prepareRuntimeProviderRequest`(内含 `buildToolExposure`)
+6. 用 §3.1 的同一分类函数出结果
+
+**不做**:
+
+- 不调 `persistAnnouncements`。事实:它会落库,草稿上调用会让会话从 deferred 升为 immediate 持久化(`v4-bridge.ts:1273-1320`、`server-operations.ts:3213-3216`)。
+- 不写历史,不发请求,不跑 hooks。
+- 不做 IO 探测:环境公告沿用历史或启动快照(不重新探测 cwd 的仓库属性),Git 公告取启动快照(不调 `resolveGitContext`,也不消费 `sessionStartGitPrefetch`)。
+- 不模拟需要 IO 或会消费一次性状态的提醒:todo 提醒(读 todo)、计划模式退出提醒、silent turn 提醒(只在非首步)、Memory 更新(取出即消费)。
+
+**可接受的副作用**:`ensureContextInitialized` 会启动 MCP 连接、建记忆与 gen-ui 目录、在内存里装好 context 前缀(`context.ts:81,89,97,195`)。已有先例:技能面板也走这条路(`skill-reference-catalog.ts:21-24`)。这些在草稿首次发送时本来也会发生,都不落库。
+
+### 3.6 App 侧
+
+`IZCodeAgentService`(`packages/services/src/zcode-agent/zcodeAgent.ts`)加两个可选方法,实现在 `contextCompositionClient.ts`,`zcodeAgentService.ts` 只做接线:
+
+```ts
+getContextComposition?(
+  params: ZCodeAgentContextCompositionParams, // { workspacePath, workspaceIdentity?, remoteSessionId?, sessionId, modelSelection? }
+): Promise<ContextComposition | null>;
+onDynamicContextCompositionChanged?(
+  target: ZCodeAgentWorkspaceTarget,
+): Event<ContextCompositionChangedEvent>; // { sessionId, revision }
+```
+
+- `getContextComposition` 是 existing-only:工作区没有运行中的 CLI 时返回 `null`,不为查询启动 CLI。CLI 返回 method-not-found 时返回 `null`,不抛错。其他错误照常抛出。
+- 通知按 `sessionId` 路由到工作区;参数不合法时丢弃并记 debug 日志。
+- 只服务本机工作区。远程工作区不接扩展数据泵(由第 2 段的 Window Host 决定)。
+
+## 4. 测试(先写测试再实现)
+
+| #   | 内容                                                                                                                | 测试文件                                                                                                                    |
+| --- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
+| 1   | 分类:提醒(含 MCS system 提醒)、`app__` 工具、延迟加载工具、compact summary、指令与技能真实文本各落到正确的细类别 | `packages/core/tests/context-composition/classifier.test.ts`                                                                |
+| 2   | 投影:粗类别只有现有 7 个值,且每个细类别投影到 §3.1 表里的粗类别                                                   | 同上                                                                                                                        |
+| 3   | 预演无副作用:调用前后会话仍是草稿(未持久化),对话历史条目数不变,没有落库的公告                                  | `packages/core/tests/context-composition/runtime.test.ts`                                                                   |
+| 4   | 修订号:每个 §3.4 事件触发监听器;同一轮内多次触发只发一条通知、修订号只加一                                        | 同上 + `packages/bootstrap/tests/context-composition/tracker.test.ts`                                                       |
+| 5   | 查询:模型相同返回 `request`;换模型后返回 `draft-preview`;会话不在内存返回 `null`                                 | `packages/core/tests/context-composition/runtime.test.ts` + `packages/bootstrap/tests/context-composition/protocol.test.ts` |
+| 6   | 条目上限:超过 50 条只取前 50;条目名截断到 200 字符                                                                | `packages/core/tests/context-composition/classifier.test.ts`                                                                |
+
+协议层集成:`packages/bootstrap/tests/context-composition/protocol.test.ts` 真实走 `ZCodeProtocolAgentServer`,建草稿会话 → 调 `v4/conversation/contextComposition` → 拿到 `draft-preview`,系统提示词与内置工具不为 0 → 断言会话仍是草稿(`record.persistence === "deferred"`,存储里没有会话行)。

+ 8 - 0
apps/zcode-cli/docs/design/v2/model/http-proxy.md

@@ -67,6 +67,14 @@ No Proxy 对以上代理来源都生效,支持 `*`、精确 host、host:port
 
 本阶段是“默认网络出口收敛”,不是不可绕过的系统级防火墙。子进程仍可以在命令内部删除代理环境、使用自带网络栈或通过非 HTTP 协议出网。强制所有网络流量必须经过统一出口,需要后续引入 OS sandbox、容器网络策略或本机防火墙级别能力。
 
+## 取消与资源寿命
+
+请求归一化沿用调用方的有效 signal(init.signal 优先,其次 Request.signal;显式 null 表示不继承)。不能只留下临时 Request 生成的从属 signal:Request 的 controller 被 GC 后,父信号的取消可能不再传入。响应正文未读完时,取消仍须关闭连接。
+
+每次请求的 signal 同时传给代理连接建立层。HTTPS CONNECT 等待响应期间 socket 尚未移交 ClientRequest,单独 destroy ClientRequest 无法释放它。取消必须关闭该 socket,且不能影响其它请求。回归使用本地真实 server,覆盖 GC 后流取消、CONNECT 未响应时取消和并发隔离。
+
+响应正文结束与底层连接收尾是两个独立边界。proxy-aware fetch 的 `ClientRequest` 错误监听随请求对象回收,不能在响应或请求的 `close` 时提前移除,也不能只监听一次:底层 socket 与 TLS 可先后转发错误。HTTP MCP 握手读取失败响应后会立即关闭 transport;此时代理 socket 的取消错误仍可能经过 TLS socket,在请求 `close` 之后传回请求。该错误只结束当前连接,不得成为进程级未捕获异常;响应正文尚未结束时,读取方仍须收到取消错误。模型流也会这样:失败的尝试结束时才统一 abort,此时响应已读完。回归覆盖 HTTPS CONNECT 成功后的取消、正文读完后立即取消并继续发起下一次请求、普通 HTTP 代理下响应读完后调用方才取消,以及单个 MCP 握手失败后另一个 MCP 仍能调用工具。
+
 ## 测试覆盖
 
 - `ZCODE_HTTP_PROXY` 能让模型请求经过本地 HTTP proxy。

+ 53 - 2
apps/zcode-cli/docs/design/v2/model/session-features-header.md

@@ -48,15 +48,45 @@
 | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
 | `workflow_cmd`       | 用户输入的内置 `/workflow` 命令被展开为工作流模板。灰度关闭、命令未展开时不打                                                                                                                                                                                                                              | 能:用户消息原文以 `/workflow` 开头                                                                                                                    |
 | `workflow_auto`      | 模型调用 `CreateWorkflow` 成功启动了后台 run(工具输出 `status: "backgrounded"`)。编译失败、宿主没有 run 端口时不打。GUI 直接启动已保存的工作流不是模型调用,不打                                                                                                                                         | 能:`CreateWorkflow` 工具结果的 display 为 `create_workflow` 且 `ok: true`                                                                             |
+| `workflow_auto_attempt` | 模型调用 `CreateWorkflow` 且这次调用有了结算结果,不论成败:成功启动、编译失败、没有 run 端口、参数校验失败、handler 抛错都打。错误类型为 `permission_denied`(权限确认时拒绝、hook 或规则拦截)或 `tool_not_found`(本会话没有注册该工具)时不打。GUI 直接启动不打(见下文) | 部分能:`CreateWorkflow` 工具 part 状态为 `completed`;`error` 状态的 part 分不出权限拒绝,只靠 entry(见下文) |
 | `tool_search_native` | 主循环请求的 ToolSearch **实际生效**模式为 native。取请求准备结果 `prepared.toolSearch`(`enabled` 为真且 `mode` 为 `native`),不取设置值:设置为 `auto` 时按 Model 解析成 native 或 local;没有 deferred 工具或缺少控制工具时实际关闭,不打                                                              | 不能,只靠 entry(见下文)                                                                                                                             |
 | `tool_search_local`  | 同上,实际生效模式为 local                                                                                                                                                                                                                                                                                 | 不能,只靠 entry                                                                                                                                       |
 | `tool_search_called` | 模型调用 ToolSearch 且执行成功。local 模式下模型看到的名字是 `LocalToolSearch`,执行器统一换成规范名 `ToolSearch`;判断用 `isToolSearchName`。没有匹配结果(`No matching deferred tools found`)也算成功调用。执行失败(例如请求未启用 ToolSearch)不打                                                    | 能:assistant 的工具 part 名满足 `isToolSearchName` 且状态为 `completed`。pending/running 阶段写的是原始名,completed 阶段写的是规范名,两种写法都覆盖 |
 | `browser_use`        | 模型代码经 node_repl 调用了浏览器运行时:`list` 或 `execute` 请求到达 node-repl-host 主线程的浏览器代理 broker 就打,不论结果成功还是失败。模型只在代码里提到、代码没执行到调用时不打;请求在 Worker 里就被拒绝、没有到达 broker 时也不打(见下文)                                                        | 不能,只靠 entry(见下文)                                                                                                                             |
 | `computer_use`       | 模型代码经 node_repl 调用了任一 CUA API:请求到达主线程的 CUA broker 就打,不论成败,在 broker 侧被拒绝也打;只做引导、在 Worker 线程里被拒绝时不打(见下文)。旧版 MCP 工具只认通过官方 CUA 认证注册工具(registry entry 的 `permissionCapabilityGroup` 为 `official_cua`),有结算结果就打,同样不论成败 | 不能,只靠 entry(见下文)                                                                                                                             |
+| `site_deploy`        | 官方命令端点收到本会话的 `POST /api/v1/sites/{siteId}/deployments` 就打,不看结果:没有登录身份、上游不可达、非 2xx 都打。其他方法和路径不打(见下文) | 不能,只靠 entry |
 
 `workflow_auto` 只表示事实"CreateWorkflow 成功过",不排除 `/workflow`。用户先输入 `/workflow`、
 模型再调用 CreateWorkflow 时两个标签同时出现。"由模型自行发起"这类口径由统计方组合得出。
 
+CreateWorkflow 尝试口径的补充规则:
+
+- 为什么新增标签:`workflow_auto` 是"成功启动"口径,调用了 CreateWorkflow 但每次都编译失败、校验失败或
+  抛错的会话不会被统计方选中,样本里的失败率就会偏低(与 BUA/CUA 改用"真实尝试"口径的理由相同)。
+  已发布标签的含义不能改,所以新增 `workflow_auto_attempt`,`workflow_auto` 保持不变。成功启动时两个标签
+  同时出现,`workflow_auto_attempt` 是 `workflow_auto` 的超集。
+- 打点在工具结果结算时(`settleToolResults`),与 `workflow_auto` 同一入口,从下一次请求起带上。参数校验、
+  `resolveInput`(技能门、读盘)、hook 改写后的校验、权限判定都在 executor 内早退,返回的失败结果同样经过
+  结算,不另接打点。
+- 排除 `permission_denied`:能力没有真正用上。结果层面只保留错误类型,分不出拒绝来自谁,所以下面几种
+  一并排除:用户在确认窗拒绝或 Refine;PreToolUse hook 拦截、PermissionRequest hook 应答 deny;
+  disallowedTools、项目 deny 规则、auto 模式;非 guarded 模式下 broker 抛出非 CoreError
+  (`permission-flow.ts` 包成 `Permission request failed`)。
+- 计入的权限阶段失败:guarded 模式下 broker 失败(`tool_execution_failed`、`permission_timeout`、
+  `configuration_error`)、broker 超时(`permission_timeout`),以及等待确认或执行前用户停止
+  (`tool_cancelled`)。模型确实发起了调用,统计方可从完整日志里区分。plan mode 不拦截 CreateWorkflow:
+  它声明了 `alwaysAsk`,任何模式下都弹窗确认,与普通模式相同。
+- 排除 `tool_not_found`:workflow 子 actor 结构性禁用 CreateWorkflow,灰度关闭或按需激活之前也不注册;
+  模型凭空调用时结果的工具名仍是 `CreateWorkflow`,不排除会把这些会话误标。`DeferredToolCall` 包装调用
+  在准入阶段失败时结果保留包装名,本来就不命中。
+- GUI 直接启动已保存的工作流不经过结算:它只写一条带 `workflowLaunch` 元数据的 user 消息,并用合成的
+  描述子登记后台任务,不写 CreateWorkflow 工具 part,所以两个标签都不打,历史推导也不命中。
+- 历史推导只认 `completed` 的 CreateWorkflow 工具 part(成功启动、没有 run 端口、编译失败都落成
+  `completed`),不看 display。`error` 状态的 part 只保存自由文本 `error` 与 `metadata.modelContent`,不保存
+  错误类型;用户的拒绝反馈和 hook 的 reason 都是任意文本,分不出权限拒绝,所以不采用,只靠 entry。
+  影响有限:只有 entry 缺失(读写失败、fork 子会话、升级前的会话)并且每次尝试都以 `error` 结束的会话才
+  少带标签。pending/running 的 part 没有结算结果,不命中。
+
 ToolSearch 标签的补充规则:
 
 - 模式标签只打在主循环请求上,也就是 `turn-loop` 发出的 main_turn / subagent / workflow_child 请求。
@@ -133,6 +163,16 @@ BUA/CUA 标签的补充规则:
   `mcp__computer-use__` / `mcp__computer_use__` 的工具多半来自第三方同名 server。落盘的工具 part 不带认证
   信息,所以这条路径同样推不出历史,只靠 entry。
 
+Sites 部署标签的补充规则:
+
+- 在官方命令端点打(`docs/design/v2/official-command-endpoint.md`)。`zcode-site` CLI 不持有凭证,Sites 接口都经过
+  这个端点,端点按 session token 认出会话。只看是否调用了创建部署的接口,不看结果。
+- 端点收到请求时先回调该 session 的 observer,再取身份、转发,所以 Bash 结束之前标签已经在内存里,之后的
+  第一个模型请求一定带上。CLI 在发请求之前就失败(例如本地检查不通过)时,端点收不到请求,不打。
+- 例外:子 agent 共用父会话的执行端口和端点 token,所以子 agent 里的部署打在父会话上,子 agent 自己的请求
+  不带。
+- 推不出历史:消息里只有命令文本和 CLI 输出,不按文本推导。
+
 ## 状态 owner 与时序
 
 ```text
@@ -140,7 +180,8 @@ BUA/CUA 标签的补充规则:
 ─────────────────────────────────          ───────────────────────────────────────────
 /workflow 展开(bootstrap create-app) ──┐    sessionFeatures: Set(内存,唯一事实源)
 工具结果结算(settleToolResults)     ──┤
-主循环请求准备之后(turn-loop)       ──┴─▶  recordSessionFeature(tag)
+主循环请求准备之后(turn-loop)       ──┤
+官方命令端点收到创建部署(create-app)──┴─▶  recordSessionFeature(tag)
                                               ├ 已有该标签:no-op
                                               ├ 新标签:同步加入 Set
                                               └ 会话已落盘:排队写 session entry
@@ -189,7 +230,8 @@ entry 的读写都是 best-effort,标签只用于统计,不能改变主流
 | app(core) | `core/src/runtime/session-features/`(managed 模块 `session-features`)                                                               | owner:打点入口、entry 读写、冷恢复、从工具结果和历史推导标签                  |
 | app(core) | `core/src/runtime/methods/runtime-model.ts`                                                                                           | runtime 层在每次调用时读取标签;workspace scope 不带                           |
 | adapters    | `adapters/src/model/runner-attribution.ts`、`runner-options.ts`                                                                       | 校验并写出 header,剔除静态同名 header                                         |
-| bootstrap   | `bootstrap/src/app/create-app.ts`                                                                                                     | `/workflow` 展开时打 `workflow_cmd`                                            |
+| bootstrap   | `bootstrap/src/app/create-app.ts`                                                                                                     | `/workflow` 展开时打 `workflow_cmd`;端点回调创建部署时打 `site_deploy`        |
+| bootstrap   | `bootstrap/src/official-command-endpoint/endpoint.ts`                                                                                 | 收到创建部署的请求时回调该 session 的 observer                                 |
 | app(core) | `core/src/runtime/methods/turn-loop.ts`                                                                                               | 主循环请求准备之后按生效模式打 ToolSearch 模式标签                             |
 | node_repl   | `node-repl-host/src/call-ledger/`(managed 模块 `node-repl-call-ledger`,含浏览器代理 broker)、`cua-broker.ts`、`result.ts`          | broker 收到请求时记账;结果组装时删除伪造的同名 key,只按账本 facts 写可信 key |
 
@@ -203,6 +245,12 @@ entry 的读写都是 best-effort,标签只用于统计,不能改变主流
   并发打点后 entry 含全部标签。
 - 推导:`CreateWorkflow` 只有 `backgrounded` 才打 `workflow_auto`;编译失败、无端口不打。历史推导覆盖
   `/workflow` 原文、`CreateWorkflow` 成功 display,以及不应命中的情况。
+- CreateWorkflow 尝试:成功启动、编译失败、无端口、handler 抛错、参数校验失败、取消都打
+  `workflow_auto_attempt`,成功时与 `workflow_auto` 同时出现;`permission_denied`、`tool_not_found` 不打。
+  历史推导认 `completed` 的工具 part(不论 display),`error`、pending、running 的 part 与 GUI 直接启动的
+  消息不命中。端到端:handler 抛错、参数校验失败、编译失败各一轮,结算之后的下一次请求带上标签并写入
+  entry;broker 拒绝时不带;子 agent 只记在自己的会话上,父会话不带;workflow 子 actor 调用未注册的
+  CreateWorkflow 不打。
 - ToolSearch:成功调用(含无匹配结果)打 `tool_search_called`,失败不打;历史只认 completed 的工具 part,
   规范名和 `LocalToolSearch` 都覆盖。生效模式为 native/local 时打对应标签,`enabled` 为假时不打。
   端到端:native 和 local 各一轮,首次请求带模式标签,搜索之后的请求再带 `tool_search_called`,并写入
@@ -213,5 +261,8 @@ entry 的读写都是 best-effort,标签只用于统计,不能改变主流
   写可信 key,模型经 `setResponseMeta`、`emitStructuredResult`、内嵌 `_meta` 写入的同名 key 被删除;cell
   只提到运行时、只做 CUA 引导时不写。真实 Worker:cell 经 `worker_threads` 冒充的结果不带这两个 key。旧版 MCP 工具只认官方认证注册的,成败都打;第三方同名
   server(`computer-use`、`computer_use`)不打;历史推导不出这两个标签。端到端:结算之后的下一次请求带上标签。
+- Sites 部署:端点收到 `POST /api/v1/sites/{siteId}/deployments` 就回调该 token 所属 session 的 observer,响应是
+  2xx 还是 409 都回调;其他方法和路径不回调。端到端:部署请求被上游拒绝时,之后的请求同样带上
+  `site_deploy` 并写入 entry。
 - 冷恢复:只有 entry、只有历史、两者并集;并集比 entry 多时补写;词表外标签被忽略;读取 entry
   抛错时恢复完成、标签来自历史、不补写;之后打新标签时合并回 entry 原有标签;写入前读仍失败时跳过写入。

+ 23 - 11
apps/zcode-cli/docs/design/v2/model/streaming-tool-execution-and-recovery.md

@@ -39,18 +39,26 @@ returns synchronously; pending persistence stays inside the existing early
 execution error boundary. Cancellation aborts the active request and does not retry.
 
 Tool declaration order can therefore differ from first-persistence order. Each
-existing ToolPart write carries an optional `declarationIndex` within its assistant
-message. Provider history hydration first selects the last persisted part for
-each call ID within that assistant, then orders both calls and results by the
-runtime-generated index when all selected indexes are present. Otherwise it
-retains the selected parts' physical order.
-This does not change scheduling, persistence timing, or UI ordering.
+existing ToolPart write carries an optional `blockIndex`: the block's position in
+the provider response, shared with the reasoning and text parts of the same
+assistant (see [Assistant Block Order](./assistant-block-order.md)). Parts written
+before that change carry `declarationIndex` instead, and new writes no longer set
+it. Provider history hydration first selects the last persisted part for each call
+ID within that assistant, then orders both calls and results by `blockIndex` when
+all selected parts have it, otherwise by `declarationIndex` when all selected parts
+have it. Otherwise it retains the selected parts' physical order.
+Persistence timing is unchanged. `executeToolCallsForModelStep` sorts the local
+tool calls by `blockIndex` once, then schedules, persists pending parts, executes,
+and commits results in that order, so live results use the same order as cold
+resume (see "工具执行与结果顺序" in Assistant Block Order). The session-store read
+boundary sorts the parts of an ordered assistant message by `blockIndex`, so UI
+consumers see stream order.
 
 ### Tool part identity across execution failure
 
 End-of-stream fallback and synthetic recovery retain the existing behavior of
-allocating a new part ID. The call ID and declaration index still identify the
-same model declaration. File-state hydration replays snapshots within one
+allocating a new part ID. The call ID and `blockIndex` (`declarationIndex` on older
+parts) still identify the same model declaration. File-state hydration replays snapshots within one
 assistant in live write order (`snapshotIndex` in the snapshot metadata, assigned
 by the executor when the tool records the snapshot), so a fallback Read that
 writes later still wins over an older snapshot. Snapshots without
@@ -64,7 +72,8 @@ early call -> first part (pending / running)
                          +--------------------------------+----------------+
                          v                                                 v
              model hydration: last part per call             file-state hydration:
-             -> declaration order for calls/results          snapshotIndex order
+             -> blockIndex (legacy: declaration)             snapshotIndex order
+                order for calls/results
 ```
 
 Pending persistence remains before execution. Model hydration selects the last
@@ -75,9 +84,12 @@ result. Late updates to an earlier part cannot replace the selected newer part.
 The executor still handles cancellation through its existing abort signal.
 
 This selection also handles historical duplicate attempts without migrating or
-deleting records, changing tool scheduling, retry policy, or public schemas.
+deleting records, or changing retry policy or public schemas.
 Desktop continuous and mobile replayable delivery retain their existing
-boundaries. Raw parts and UI/file-state consumers retain their existing order.
+boundaries. Raw parts reach UI consumers in stream order for ordered assistant
+messages and in physical order otherwise; retry parts of one call share a
+`blockIndex`, so the stable sort keeps their relative order. File-state consumers
+keep using `snapshotIndex`.
 Runtime tests inject write failures and delayed scheduling, then inspect stored
 parts, cold hydration, and the next model request. SQLite tests also cover full
 Read snapshots and subsequent Edit after cold resume and rewind.

+ 3 - 1
apps/zcode-cli/docs/design/v2/official-command-endpoint.md

@@ -47,6 +47,7 @@ command ──Bearer <session token>──▶ endpoint
 - The request body is streamed (`duplex: "half"`) with the original `content-length`. When an HTTP proxy is configured, the proxy fetch buffers the body.
 - Response headers `connection`, `content-encoding`, `content-length`, `keep-alive`, `set-cookie`, `transfer-encoding` are dropped. The body is streamed with backpressure. If the upstream fails midway, the command's connection is destroyed so the command sees an incomplete response.
 - Endpoint-generated errors use the zcode-server envelope `{code: 2007, msg, data: null, logid: ""}` with header `X-ZCode-Official-Endpoint-Error: invalid | auth | network`. The bare 401 carries the same header with `unauthenticated`.
+- `envForSession(sessionId, workspace, observer)` records the observer for the session. When the endpoint receives `POST /api/v1/sites/{siteId}/deployments` from a known session, it calls `observer.onSiteDeploymentRequested()` before it asks for identity and forwards the request, whatever the result. `create-app.ts` records the `site_deploy` session feature from it (`docs/design/v2/model/session-features-header.md`). Subagents share the parent session's token, so their deployments count for the parent session.
 
 ## Lifetime
 
@@ -61,6 +62,7 @@ command ──Bearer <session token>──▶ endpoint
 
 ## Tests
 
-- `packages/bootstrap/tests/official-command-endpoint/endpoint.test.ts`: per-session tokens and private socket dir; each token asks for identity with its own session's workspace; the port builds `workspaceKey` from identity or path and logs `auth_request_failed` when the host rejects; rejected tokens and paths never reach the host; header replacement and streamed 3 MB upload; 401/2007 mapping; unreachable upstream; close removes the socket; `withOfficialCommandEnv` merge, `base: "empty"` and failure behavior; the auth-headers port request shape.
+- `packages/bootstrap/tests/official-command-endpoint/endpoint.test.ts`: per-session tokens and private socket dir; each token asks for identity with its own session's workspace; the port builds `workspaceKey` from identity or path and logs `auth_request_failed` when the host rejects; rejected tokens and paths never reach the host; header replacement and streamed 3 MB upload; 401/2007 mapping; unreachable upstream; close removes the socket; the observer is called for every deployment request of the token's session and for no other call; `withOfficialCommandEnv` merge, `base: "empty"` and failure behavior; the auth-headers port request shape.
+- `packages/bootstrap/tests/session-features-site-deploy.test.ts`: with a real endpoint and a fake zcode-server, a deployment request adds `site_deploy` to the next model request even when zcode-server rejects it.
 - `packages/bootstrap/tests/official-command-endpoint/contract.test.ts`: module manifest and public entrypoint.
 - `packages/zcode-site-plugin/test/zcode-site.test.mjs`: the CLI reads only the two env keys, sends only the session token, maps the `network` error header, and talks HTTP over the socket.

+ 3 - 3
apps/zcode-cli/docs/design/v2/permission-broker.md

@@ -26,7 +26,7 @@ v2 将 `PermissionService` 和 `PermissionBroker` 明确拆开:
 - Core service:`packages/core/src/permission/service.ts` 负责同步 `allow` / `ask` / `deny` 判断,并支持 project `allow` / `ask` / `deny` 规则匹配。
 - Core broker:`packages/core/src/permission/broker.ts` 提供默认 fail-closed `DenyPermissionBroker` 和可检查、可手动 resolve 的 `ManualPermissionBroker`,覆盖 pending、timeout、abort cleanup。
 - Tool executor:`packages/core/src/tool/executor.ts` 在 `ask` 时发布 `permission_requested`,等待 broker 或 `PermissionRequest` hook,发布 `permission_resolved`,支持 `allow` 执行、`modify` 替换完整 input、`deny` 结构化失败、`escalate` 失败,以及 `permissionUpdates` 写入 project permission ruleset。
-- Runtime/TUI:`packages/core/src/runtime/agent-runtime.ts` 把 broker 注入 executor;`packages/tui/src/app-permission.ts` 使用队列式 approval UI,支持 `Allow once`、`Always allow in this project`、`Deny`,并为 `AskUserQuestion` 复用同一 broker 通道展示澄清问题。`packages/cli/src/tui-command.ts` 必须在 `submitPrompt` 和 `sendInput` 两条路径都把当前 TUI `requestPermission` 回调挂到 broker 上,避免忙时输入、resume 后 continuation 或排队输入启动新 turn 时审批 UI 丢失。
+- Runtime/TUI:`packages/core/src/runtime/agent-runtime.ts` 把 broker 注入 executor;`packages/tui/src/app-permission.ts` 使用队列式 approval UI,支持 `Allow once`、`Always allow in this project`、`Deny`,并为 `AskUserQuestion` 复用同一 broker 通道展示澄清问题。TUI 在挂载时经 `registerPermissionRequester` 把审批入口登记到 `packages/cli/src/tui-prompt-handler.ts` 的 broker,卸载时注销;入口不随单次提交切换,所以忙时输入、resume 后 continuation、排队输入、通知驱动的回合和后台会话(`CreateSession` / `ForkSession` 建的根复用同一个 broker,见 [会话工具设计 0.5](../../../../../docs/architecture/zcode-app-control-design.md))都能到达同一个审批队列。未登记时 fail closed。
 - TUI 渲染:普通 approval prompt 优先展示 tool input 中的 `description` 作为用户可读说明;命令类 input 预览只展示 `command` 值,不展示完整 JSON,也不在面板中展示 risk/mode 策略元数据。说明和命令预览必须按当前面板宽度 word wrap,并按渲染行数扩展面板高度,避免窄终端中权限文本覆盖决策选项或帮助行。
 - ZCode app-server:`apps/zcode-cli/packages/bootstrap/src/zcode-protocol-entrypoint.ts` 注入 ZCode app-server broker,普通 tool 通过 ZCode app-server `requestPermission` 转成 `Allow once`、`Always allow in this project` 或 `Deny`;project allow 会返回 `permissionUpdates` 交给 core 写入当前 project ruleset;`AskUserQuestion` 当前走 `zcode.dev` elicitation 扩展请求。
 
@@ -36,7 +36,7 @@ v2 将 `PermissionService` 和 `PermissionBroker` 明确拆开:
 - `packages/core/tests/permission-service.test.ts`:build/plan/yolo 模式、project rules、user-interaction tool 的权限判断。
 - `packages/core/tests/tool-executor-trace.test.ts`:默认无 broker fail closed、broker allow 后执行、project `permissionUpdates` 落盘并被后续调用命中、broker `modify` 替换输入、hook allow/deny。
 - `packages/core/tests/runtime-tool-loop.test.ts`:runtime 等待 broker approval 后才执行 side-effecting tool,并保证 `permission_resolved` 早于 `tool_call_started`。
-- `packages/cli/tests/cli.unit.test.ts`:TUI `submitPrompt` 和 `sendInput` 都会把 approval request 接入 runtime permission broker,防止 approval handler 丢失后 fail-closed。
+- `packages/cli/tests/cli.unit.test.ts`:登记后 TUI `submitPrompt`、`sendInput` 和回合之外的 approval request 都接入 runtime permission broker,未登记时 fail-closed。
 - `packages/tui/tests/tui.unit.test.ts`:TUI approval UI、project allow update、Esc/关闭/取消等交互路径。
 
 剩余边界:session/global 级 permission ruleset 仍不在第一版范围内;ZCode app-server 和 TUI 当前都只暴露 project 级 remember allow,不暴露 reject always;更细粒度的 Bash/WebFetch 规则建议仍应由后续 tool policy 提供。
@@ -110,7 +110,7 @@ Broker 必须支持 `AbortSignal`。如果 turn 被取消,pending permission 
 TUI 作为第一版交互客户端时,只实现 `ask` 请求的最小可用 UI:
 
 - runtime 仍通过 `PermissionBrokerPort.requestPermission` 等待结果,TUI 不直接执行 tool。
-- TUI 在当前 turn busy 状态下展示审批框,包含 `toolName`、`riskLevel`、`sideEffectScope`、`reason` 和截断后的 `input` 预览。
+- TUI 展示审批框不依赖当前 turn 是否 busy,包含 `toolName`、`riskLevel`、`sideEffectScope`、`reason` 和截断后的 `input` 预览;请求的 `sessionId` 不是当前主会话时,在审批框上方标明来源后台会话。
 - 键盘操作使用显式选择确认:审批框展示 `Allow once`、`Always allow in this project` 和 `Deny`。默认选中 `Deny`;`Up`/`Down` 在选项间移动,`Enter` 返回当前选项,`Escape` 返回 `deny`;`Ctrl-C` 继续取消当前 TUI 会话并通过 abort signal 清理 pending。
 - `Always allow in this project` 只返回 project 级 `permissionUpdates`。第一版可以先生成 tool-only 规则;Bash/WebFetch 等更细粒度规则由 tool policy 后续提供建议。
 - TUI 同一时间只展示队首审批请求;如果后续支持并发请求,应在 TUI 层排队,不改变 broker 契约。

+ 357 - 3
apps/zcode-cli/docs/design/v2/plugin-compat.md

@@ -58,6 +58,40 @@ capability comes from validated manifest `ui.surfaces`, including when disabled;
 `category` remains the independent usage category. See the market interaction
 spec in the root `docs/plugins/` directory for presentation and scope semantics.
 
+### Extension summary
+
+Contract: root `docs/plugins/plugin-publishing.md` §4.2–4.3. The CLI passes the
+data through and never judges compatibility; only the App knows its plugin API
+version.
+
+- Catalog `componentTypes` may advertise `extension`. The CLI passes it through
+  to `availablePlugins[].componentTypes` exactly like `ui`. Like `ui`, it is
+  only a catalog claim; installed capability comes from the installed manifest.
+- A catalog entry may carry `extensionSummary: { engines: { zcode }, grants }`.
+  The CLI reads it from the raw entry on every overview (old manifest caches
+  need no migration). It keeps the entry only when `engines.zcode` is a
+  non-empty string, keeps only string `grants` (default `[]`), and drops every
+  other key. It does not validate the range syntax.
+- Manifest synthesis for entries without `plugin.json`
+  (`createManifestFromMarketplaceEntry`) removes `extensionSummary`, the same
+  as the other Store Listing keys. A partial `extension` key must never become
+  manifest content.
+- Version skew: `zcodePluginStoreListingSchema` and the overview result are
+  `.strict()`, and the calling services may be older or newer than the CLI.
+  - `runtime/capabilities` declares `pluginExtensionSummary: true`.
+  - `plugins/overview` accepts `includeExtensionSummary?: boolean`. Services
+    send it only after they see the capability, because old CLIs reject the
+    unknown key.
+  - Only when the request has `includeExtensionSummary: true` does the CLI put
+    the summary into `availablePlugins[].listing.extensionSummary` and
+    `installedPlugins[].listing.extensionSummary`. For an installed plugin it
+    is the summary of the latest catalog entry. Install, uninstall, update and
+    `plugins/resolveSuggestedReference` results never carry it.
+
+Tests: adapters (`parseEntryExtensionSummary`, manifest synthesis strips the
+key), bootstrap (`componentTypes` passthrough, overview with and without the
+flag, capability bit).
+
 ## Storage Layout
 
 ZCode stores plugin state under the CLI storage root:
@@ -114,6 +148,13 @@ replaced when a plugin is updated. `data` is a persistent per-plugin directory
 for MCP servers and tools. Plugin data survives cache replacement and is removed
 only when the final installation is removed.
 
+`plugins/list` reports this directory as the optional `dataPath` of each plugin
+(the same `PluginMetadata.dataPath` that MCP servers and hooks receive as
+`${ZCODE_PLUGIN_DATA}`). The App passes it to the plugin's extension as
+`ctx.extension.dataPath` (docs/plugins/extension-host.md §18.1 H6) and never
+derives the path itself. The CLI does not create the directory when listing;
+the extension host creates it before activation.
+
 ## Uninstall And Teardown
 
 Uninstalling a plugin is a thorough teardown so that a later reinstall starts
@@ -128,8 +169,9 @@ durable state ZCode created for it:
    the "final installation is removed" case from the storage layout: data is kept
    across cache replacement on update, but uninstall deletes it.
 4. The plugin's user config entries `plugins.enabledPlugins[id]` and
-   `plugins.options[id]` in the user `config.json`. After uninstall there is no
-   stale enable flag or saved option left behind.
+   `plugins.options[id]` in the user `config.json`, and the plugin's entries in
+   `plugin-secrets.json` (see Sensitive Option Storage). After uninstall there is
+   no stale enable flag, saved option or secret left behind.
 
 Teardown is centralized so all entry points behave identically. The filesystem
 deletions (record, cache, data) belong to the plugins adapter; the config-entry
@@ -154,9 +196,76 @@ first and only use a root `marketplace.json` fallback for local legacy data.
 
 Startup must seed bundled official plugins before plugin discovery:
 
+Since 2026-10-30, Protocol Agent processes do not enable the plugin startup
+budget: seed and discovery run to completion, seed lock waits keep their shared
+15-second budget, and the process never emits `startup/pluginsDegraded`. A cold
+seed of the bundled official plugins measured about 3.0-3.1 seconds on Windows,
+so a 3-second budget that includes seed degraded every first start after a
+plugin version bump. The budget remains an opt-in owner option; the rest of this
+section is its contract when an owner enables it. Re-enabling it in the
+Protocol Agent requires moving seed out of the budget or another confirmed scope.
+
+When enabled, the owner gives seed and discovery one shared soft budget per
+in-flight batch, including admission waits. If any batch times out, the
+process returns an empty plugin outcome with `plugin_startup_timeout` and stops
+starting plugin scans until restart. It does not change enabled/suppressed
+configuration or installed records, or scan an old cache for this fallback.
+Restoring a bundled plugin after cancellation fails before changing suppression.
+Existing Runtime snapshots retain their capabilities; new Runtime creation can
+continue without plugin skills, commands, MCP servers or hooks.
+
+The owner aborts further work, observes late results, and emits
+`startup/pluginsDegraded` for a workspace-scoped UI warning. A directory
+publication already in progress must finish or roll back before its lock is
+released. The budget cannot cancel an in-flight kernel operation or guarantee
+the entire App starts within the budget. Standalone management commands
+without this process owner retain their existing contract.
+
+### Android tool lookup security (0.1.1)
+
+The Android plugin keeps the project as its MCP working directory, but that
+directory is never a source of SDK tools, Java, or the Windows command interpreter.
+SDK installation paths take precedence over PATH. Lookup does not execute
+`where` or `which`: it enumerates absolute PATH directories, skips empty and
+relative entries, and rejects both lexical paths and real paths inside the
+project (including symbolic links and Windows junctions). Candidates must be
+regular executable files; SDK/JDK roots must be external directories. Child
+PATH entries use the same directory checks. Missing tools report an unavailable
+dependency rather than falling back to a bare command name.
+
+Java runs only through the validated JDK's absolute `bin/java` path.
+Java-based SDK scripts and system Gradle also require a valid JDK before lookup,
+so their own Java fallback cannot reintroduce workspace execution. Windows
+batch files use the validated system directory's absolute `System32/cmd.exe`.
+An explicitly requested build may still run the project's Gradle wrapper;
+project scripts and host dependency discovery remain separate operations.
+
+```text
+SDK candidates → absolute PATH entries → external real path → execute
+                                             ↓ invalid
+                                       skip / report missing
+0.1.1 bundle → versioned cache → new MCP process
+                    ↓ seed failure
+          Android unavailable; no older-version fallback
+```
+
+Package, manifest, Bootstrap, SEA, and MCP server versions move together to
+0.1.1. Android follows the existing fail-closed cache fallback branch: a failed
+update must not reactivate 0.1.0. Existing MCP processes need restarting to use
+the fix. iOS behavior is outside this change.
+
+Regression evidence covers workspace fake tools, SDK priority, relative/empty
+PATH entries, external links into the workspace, SDK/JDK rejection, missing
+Java, Windows interpreter selection, explicit Gradle wrapper execution, and
+failed cache promotion with an older Android version present. Tests use harmless
+marker files to detect execution. Native Windows validation is recorded separately
+from portable path tests.
+
+The normal seeding layout is:
+
 ```text
 packages/android-emulator-plugin/
-  -> ~/.zcode/cli/plugins/cache/zcode-plugins-official/android-emulator/0.1.0/
+  -> ~/.zcode/cli/plugins/cache/zcode-plugins-official/android-emulator/0.1.1/
 packages/ios-simulator-plugin/
   -> ~/.zcode/cli/plugins/cache/zcode-plugins-official/ios-simulator/0.1.0/
 packages/browser-use-plugin/
@@ -176,6 +285,43 @@ built-in skill pack, not a plugin (see `skill.md`, "bundled skill pack"). It is
 never seeded into the official plugin cache, never listed in the marketplace
 partition, and cannot be disabled or uninstalled.
 
+Discovery shares Skill file scans within one query, keyed by root and symbolic
+link policy. Counts and component names retain their separate deduplication
+rules. Missing materials preserve ENOENT/ENOTDIR without another read, and are
+still revalidated before returning. Markdown reads run in batches of at most
+four; the material-cache owner also caps active reads across queries at four.
+Results keep their original order, and invalidation/disposal prevents queued
+stale reads from starting. This does not defer session reference-catalog data.
+
+Discovery 的路径检查由本次查询的 material reader 统一持有。同一路径的并发检查
+共享结果,Skill 扫描复用 reader 已取得的文件类型;符号链接拒绝规则保持不变。
+插件根目录清单及已读取的子目录清单可排除缺失的标准入口,缺失结论依赖相应父目录,
+不再为每个缺失子路径发起独立检查。仅在名称匹配规则确定时使用该优化;大小写等价
+名称保留实际路径检查,目录枚举失败也回到原有检查,不把权限错误当成缺失。
+返回前仍复核实际文件和父目录;目录新增入口、文件变化或目录替换使本次结果失效,
+沿用现有有界重跑。缺失结论不跨查询独立保留,不新增持久化缓存或 watcher。
+
+Filesystem releases compare the installed seed marker's `pluginVersion` with
+the official plugin definition and check the cached manifest and required entry
+paths. A matching usable version is reused without enumerating or hashing the
+source tree, including after a process restart. Resource changes must bump the
+plugin package, manifest, official definition and applicable packaging versions.
+Same-version edits are not detected automatically, including in development;
+remove the corresponding cache or bump the version to rebuild it. Invalidating
+the process preparation state only rechecks this contract. Old marker hashes are
+ignored for filesystem sources; new filesystem markers omit the hash.
+Source files are enumerated only when rebuilding, then each file is read once
+for copying. Validate the staged manifest and required paths before publication.
+
+A definition may declare `buildIdentityPath` when its build output embeds a
+per-build value that does not change the plugin version. node-repl-host uses
+`dist/build-identity.json`, written by its build script, because
+`dist/mcp/server.js` embeds the CUA Helper build id. Source preparation reads
+only that small file and stores its contents in the marker as `buildIdentity`.
+A different value, or a legacy marker without the field, rebuilds the cache like
+a version change. A missing source file compares as no identity and does not
+block seeding.
+
 SEA releases embed the same files as SEA assets and extract them to the same
 official cache path on first startup or when the embedded plugin hash changes.
 The MCP command must point at the seeded cache directory, not the source
@@ -274,6 +420,11 @@ P0 enablement is config-driven:
 configuration unless `enabledPlugins[id]` is `false`. Official cache plugins
 default to disabled unless `enabledPlugins[id]` is `true`.
 
+内置 visualize 默认关闭,并在首次插件配置加载时将旧启用值关闭一次。
+迁移完成标记与开关保存在同一配置文件;用户重新开启后不再重置。
+只读配置或锁失败只输出告警,本次加载按该层关闭继续合并,不能阻断插件查询或会话装配。
+用户级与项目级分别迁移,详见 [Visualize 加载边界](../../../../../docs/specs/visualize-cli-loading.md)。
+
 ## Manifest Discovery
 
 For a plugin root, ZCode reads the first manifest that exists:
@@ -364,6 +515,20 @@ resolve inside the plugin root and become `SkillRoot` entries with
 `source: "plugin"`. The existing `Skill` tool is still responsible for loading
 the full `SKILL.md` body on demand.
 
+显式声明 `skills` 时,只使用声明路径,不补充默认 `skills/`;空数组表示不加载
+技能。只有未声明该字段时,才使用存在的默认 `skills/`。命令等其他组件规则不变。
+
+每个插件技能入口若自身有可加载的 `SKILL.md`,只加载该技能,不再枚举子目录;
+否则按技能集合检查一层子目录。字符串和数组均支持这两种目录布局。需要加载单技能
+入口下的其他技能时,必须另行声明其路径。路径越界、符号链接拒绝和缺失声明诊断
+继续生效;计数、组件详情和运行时加载使用相同规则,用户级及项目级技能扫描不变。
+
+```text
+有声明 → 仅声明路径;无声明 → 默认 skills/
+入口自身有 SKILL.md → 只加载自身
+入口自身无 SKILL.md → 扫描一层子目录
+```
+
 ### Commands
 
 `manifest.commands` may be a relative path or an array of relative paths. Paths
@@ -453,6 +618,16 @@ named `android-emulator` exposes tools such as
 
 ## Variable Expansion
 
+### External user configuration compatibility
+
+The plugin loader normalizes external `userConfig` entries before they reach runtime
+or protocol metadata. Unknown extension fields (for example `options`) are stripped
+from the in-memory projection; source and installed manifest files are not rewritten.
+Supported fields retain the shared protocol's type validation, including `sensitive`.
+An invalid known field rejects only that plugin and emits `plugin_manifest_invalid`
+with its plugin ID. Other plugins remain discoverable. App/Agent response schemas
+remain strict.
+
 Plugin component config may reference:
 
 ```text
@@ -484,6 +659,185 @@ variables remain available in those fields for backward compatibility.
 `userConfig` values follow the same sink boundary: options marked `sensitive`
 may only be expanded in MCP secret sinks.
 
+## Sensitive Option Storage
+
+> 状态:已实现(扩展进程 P2d,用户决策)。总设计见
+> [扩展进程](../../../../../docs/plugins/extension-host.md) §14、§16.7。
+> 代码:`adapters/src/config/plugin-secrets.adapter.ts`(文件 I/O 与 schema)、
+> `bootstrap/src/plugin-secrets.ts`(叠加、保存、清理规则)。
+
+### 现状与问题
+
+敏感值(`userConfig[key].sensitive === true`)和普通值一起明文写在
+`plugins.options[id]` 里:user 层是 `~/.zcode/cli/config.json`,workspace 层是
+`<workspace>/.zcode/config.json`(`bootstrap/src/plugins.ts` 的
+`resolvePluginConfigPath`)。
+
+- workspace 配置可以进 Git,token 会被提交。
+- user 配置常被复制、粘贴、同步,token 会被一起带出去。
+- `plugins/list` 投影时已过滤敏感值(`bootstrap/src/zcode-protocol/plugins.ts`),
+  但文件本身仍是明文。
+
+### 设计
+
+敏感值只存进一个私有文件,`config.json` 里不再写敏感值。
+
+- 路径:`<cli storage root>/plugin-secrets.json`,即默认的
+  `~/.zcode/cli/plugin-secrets.json`。远程工作区的 CLI 在远端主机上,用它自己的文件。
+  文件始终与插件存储目录 `plugins/` 同级:调用方覆盖插件存储目录时(测试、嵌入),
+  文件跟着放在被覆盖目录的父目录里。
+- 写入:`atomicWritePrivateTextFile`(0600),在 `withFileLock` 内读改写。
+  Windows 上没有 POSIX 权限位,文件留在用户目录,权限沿用用户目录的 ACL。
+- 形状(zod schema 校验):
+
+```json
+{
+  "version": 1,
+  "user": { "<pluginId>": { "<key>": "<value>" } },
+  "workspaces": {
+    "<workspace root>": { "<pluginId>": { "<key>": "<value>" } }
+  }
+}
+```
+
+- `<workspace root>` 是 workspace 配置所在目录的绝对路径,即项目配置文件的 baseDir
+  (`<dir>/.zcode/config.json` 与 `<dir>/zcode.json` 都是 `<dir>`)。比较规则与
+  `normalizePluginConfigPathForComparison` 相同;写入时键存规范化后的路径。
+- 读取层与 `config.json` 一一对应:user 层随 user 配置读取(跳过 user 配置时不读);
+  每个被发现的项目配置文件是一个 workspace 层,用它的 baseDir 找私有文件里的条目。
+  workspace scope 的 configure 总会写 `<workspace>/.zcode/config.json`(至少留一个空的
+  `options[id]`),所以保存过的 workspace 敏感值一定有可被发现的层。
+
+规则:
+
+| 操作                           | 敏感键                                                                                     | 普通键                 |
+| ------------------------------ | ------------------------------------------------------------------------------------------ | ---------------------- |
+| configure(写值)              | 写进私有文件的对应 scope;同一 scope 的 `config.json` 里若有同名键,同一次操作删掉(迁移) | 不变,写 `config.json` |
+| configure(`clearOptionKeys`) | 私有文件与 `config.json` 两处都删                                                          | 不变                   |
+| 读取(运行时与投影)           | 每个 scope 先读私有文件,再读 `config.json` 的旧明文值;私有文件优先。scope 优先级不变     | 不变                   |
+| reset                          | 与 `config.json` 同语义:删除该 scope 下这个插件的条目                                     | 不变                   |
+| uninstall                      | 删除 `user` 与全部 `workspaces` 下这个插件的条目                                           | 不变                   |
+
+- **不在启动时迁移**。旧的明文值继续能读;用户下次保存这个插件的设置时,敏感键才迁进
+  私有文件。理由:启动时改写 workspace 配置会在用户仓库里产生意外的 diff。
+- 键是否敏感以当前清单的 `userConfig` 为准。清单把某个键改成敏感后,旧的明文值仍可读,
+  下次保存时迁移。
+- 「下次保存」指这个插件在该 scope 的任意一次非 `dryRun` configure:该 scope 的
+  `config.json` 里所有按当前清单为敏感的旧明文键都迁走,包括这次请求没带的键。理由:
+  UI 不回传敏感值,只保存普通键的请求里本来就没有已存的 secret;只迁请求里的键,旧明文会
+  永远留在文件里。`clearOptionKeys` 里的键不迁,直接两处都删。
+- 写入顺序:先写私有文件,再改 `config.json`。第二步失败时两处都有值,读取以私有文件为准,
+  下次保存再删;不会出现两处都没有的中间态。
+- 投影:`plugins/list` 的 `optionSources` 也列出私有文件里的键(scope 标记照旧),设置页的
+  scope 标记与「清除」按钮因此不受迁移影响;`configuredOptions` 仍过滤敏感值。
+- 私有文件损坏(JSON 或 schema 不符):`backupCorruptFile` 备份后按空文件处理,发出诊断
+  `plugin_secrets_unreadable`(`severity: error`,带文件路径,不含任何值)。受影响的
+  MCP server 按现有规则报 `plugin_variable_missing`。其他读取错误(例如权限)在读取路径上
+  同样按空处理并发出同一诊断,但不备份;写入路径上向上抛,不覆盖读不出的文件。
+  损坏文件在下一次写入时被替换成有效内容(备份留着)。
+- 日志、诊断、错误信息里只出现插件 id 与键名,不出现值。
+
+### App 读取扩展设置
+
+扩展进程的 `settings` 能力要拿到本插件的敏感值(用户决策:只给本插件)。
+`plugins/list` 继续过滤敏感值,另加一个只读方法:
+
+- `plugins/readUserOptions`,参数 `{ pluginId }`,返回 `{ values: Record<string, string | number | boolean> }`。
+- 值是 user 层的有效值:清单默认值,再叠加 user 层选项(含敏感值)。不含 workspace 层:
+  扩展只认用户级启用(扩展进程 spec §13)。
+- 插件未安装返回 `-32602`(invalid params),`data.code` 为 `plugin_not_found`;旧 CLI 返回
+  method-not-found,App 当作「不支持」,扩展只拿到非敏感值。
+- 「已安装」指插件出现在 user 视图的插件发现结果里(inline、official、cache 都算)。
+  已安装但被禁用的插件照常返回值。参数只有 `pluginId`(strict),不带 workspace:
+  扩展是全局的,user 层与工作区无关。
+- 只给 App 用,不进模型可见的工具,也不进 debug 日志。
+- App 侧只在 Window Host 进程内持有:不挂在 `IZCodeAgentService` 上(该服务整个频道经 RPC 暴露给
+  桌面 Renderer 与手机远控),由 `packages/services/src/node.ts` 的 `getPluginUserOptionsReader(services)`
+  取出,作为依赖交给扩展网关;网关只把调用方自己插件的值交给它。任何 RPC 频道都调不到这个读取器。
+- 收到即处理,不排在串行请求队列之后(与 `plugins/list` 同组)。
+
+### 测试(先写测试再实现)
+
+1. configure 敏感键:值进私有文件,文件权限 0600(非 Windows),`config.json` 里没有该键。
+2. 旧明文:`config.json` 里已有的敏感值能被运行时读到;下次 configure 后移进私有文件并从
+   `config.json` 删除。
+3. 运行时展开:`${user_config.KEY}` 在 MCP secret sink 里读到私有文件的值;非 sink 字段
+   仍拒绝。
+4. workspace scope:敏感值按 workspace root 存进私有文件,`<workspace>/.zcode/config.json`
+   里没有;嵌套 workspace 仍按最内层优先。
+5. `plugins/list` 仍过滤敏感值;`plugins/readUserOptions` 返回含敏感值的 user 层有效值。
+6. uninstall 与 reset 清掉私有文件里的对应条目。
+7. 私有文件损坏:备份、按空处理、发出不含值的诊断。
+
+## Composer Mention Items
+
+> 状态:已实现(扩展进程 P2c)。总设计见
+> [扩展进程](../../../../../docs/plugins/extension-host.md) §16.6。
+> 代码:`bootstrap/src/zcode-protocol/plugin-mention-items.ts`;线格式在
+> `packages/shared/src/zcode-protocol/plugin-host-queries/contract.ts`。
+
+清单 `slots["composer.mention"]` 的 `tool` target 由 CLI 执行。Window Host 读清单、校验条目,
+CLI 只负责在会话里调工具、校验结果。CLI 不解析 `slots`。
+
+- 方法:`plugins/mentionItems`,参数 `{ sessionId, pluginId, tool, query }`(strict),
+  返回 `{ items }`。`tool` 是插件 MCP server 上的原始工具名(不是模型可见的
+  `mcp__…` 名)。`query` 可以是空串,最长 1000 字符。
+- 只在内存里的会话上执行:不启动、不恢复会话,也不新建 MCP 连接。会话不在内存 →
+  `-32004`(`zcodeProtocolErrorCodes.sessionUnavailable`)。草稿用 App 的预热会话。
+- 插件身份取会话创建时冻结的 plugin catalog(`getPluginReferenceCatalog()`)。插件不在
+  catalog、未启用、或与同名插件冲突(`conflictingPluginIds` 非空)→
+  `plugin_mention_plugin_unavailable`。
+- 找工具:按 catalog 里这个插件的 MCP server 名(已排序)依次查会话 tools/list,取第一个有
+  `tool` 的 server。都没有 → `plugin_mention_tool_not_found`。工具可见性不含 `app`
+  (只给模型的工具)→ `plugin_mention_tool_not_app_visible`。
+- 调用:与 MCP App 页面的 `mcp/uiCallTool` 走同一条路径——session facade 的
+  `callMcpToolForUi(server, tool, { query })`:工具 schema 校验 → PreToolUse hook → 权限规则 /
+  审批(`ToolExecutor.authorizeAppTool`)→ 连接代际复验 → 会话现有 MCP 端口的
+  `callTool`(`runtimeScope: "main"`,带会话的 trace)。不另开绕过审批的宿主调用路径。
+  参数固定为 `{ query }`;服务器还没连上时按调用失败处理。超时沿用该 server 的 MCP 设置,
+  CLI 不另加。不产生 transcript row。
+- 审批:MCP 工具一律 `needsApproval`。会话第一次调这个工具时,可能在该会话里弹出审批,
+  请求一直等到用户回应(不另设超时);用户选「始终允许」后,同一会话后续调用不再询问。
+  deny 规则、用户拒绝、hook 拒绝(授权链抛 `permission_denied`,或 `permission_escalation`)→
+  `plugin_mention_tool_denied`。每次查询都会跑 PreToolUse hook。
+- 结果:`isError: true` 或调用抛出其他错误 → `plugin_mention_tool_failed`。
+  `structuredContent.items` 按严格 schema 校验,不符 → `plugin_mention_result_invalid`:
+
+| 字段          | 规则                      |
+| ------------- | ------------------------- |
+| `items`       | 数组,最多 50 项          |
+| `id`          | 必填,1–200 字符          |
+| `label`       | 必填,1–120 字符          |
+| `description` | 可选,最多 500 字符       |
+| `icon`        | 可选,1–100 字符          |
+| `insertText`  | 必填,1–4000 字符         |
+| 其他字段      | 拒绝(条目对象是 strict) |
+
+- 错误形态:`ProtocolRequestError`,`data.code` 是上面的稳定码。引用类错误
+  (`plugin_unavailable`、`tool_not_found`、`tool_not_app_visible`)用 `-32602`;执行类错误
+  (`tool_denied`、`tool_failed`、`result_invalid`)用 `-32000`。错误信息只含插件 id、server 名、
+  工具名与 schema 路径,不含 query、拒绝原因与工具返回的内容。
+- 不设计取消。App 每次查询带递增的 `seq`,只采用最新一次的结果;过期的请求照常跑完
+  (等待审批的请求也照常等待,回应后按结果返回)。
+- 收到即处理,不排在串行请求队列之后(与 `plugins/list` 同组)。
+- 日志:每次调用一条 `debug`(插件 id、工具名、server 名、耗时、项数或错误码),不记 query
+  与结果。理由:按键级频率,按根规则走 `debug`。
+- 旧 CLI 返回 method-not-found,App 不显示这一组。
+
+测试(先写测试再实现):
+
+1. 会话不在内存 → `-32004`,不调任何工具。
+2. 插件不在 catalog、未启用、名字冲突 → `plugin_mention_plugin_unavailable`。
+3. 工具不存在 → `plugin_mention_tool_not_found`;工具只给模型 →
+   `plugin_mention_tool_not_app_visible`;两种情况都不调用工具。
+4. 正常:在插件自己的 server 上以 `{ query }` 调用,返回校验后的 `items`。
+5. `isError`、调用抛错 → `plugin_mention_tool_failed`。
+6. 超过 50 项、`insertText` 超长、未知字段、缺 `structuredContent` →
+   `plugin_mention_result_invalid`,错误里不含工具返回的内容。
+7. 授权链拒绝 → `plugin_mention_tool_denied`,错误里不含拒绝原因。
+8. 审批等待中请求不返回;批准后按结果返回。
+9. facade `callMcpToolForUi`:先跑授权链再以批准后的输入调工具;授权链拒绝时不调工具。
+
 ## Trust And Side Effects
 
 Plugin loading itself only reads local files. Starting an MCP server remains a

+ 11 - 1
apps/zcode-cli/docs/design/v2/rewind-compact.md

@@ -129,7 +129,7 @@ compaction 结果的顺序(boundary → 请求前公告 → summary → 保留
 
 ```text
 [context prefix (system)]
-[请求前公告] context_prefix → session_context → date   仅当保留段非空;保留段已有的来源不重复(date 也一样:保留段里有日期公告时,即使已过期也不放,之后的请求在末尾宣告一次变化)
+[请求前公告] context_prefix → session_context → date   仅当保留段非空;保留段已有的来源不重复(date 也一样:保留段里有日期公告时,即使已过期也不放,之后的请求在末尾宣告一次变化)。context_prefix 只认完整块:保留段只有增量时也放完整块;保留段有完整块时不放,内容变化由下一次请求追加增量(reason `compaction`)
 [summary]
 [保留段]
 [compaction 附件] 文件恢复 → plan_file_reference → runtime_mode(计划模式下的完整提醒,保留段已有完整提醒时不发)
@@ -147,6 +147,7 @@ compaction 结果的顺序(boundary → 请求前公告 → summary → 保留
   - 补回内容随 compaction 附件一起持久化,冷恢复读到相同字节,不再重读磁盘;已有的 compaction 不改写。
 
 - 输入附件在 compaction 之前运行,属于保留段或被摘要;同一请求在 compaction 之后不再收集输入附件,只运行按历史去重的请求前公告。保留段为空(manual compact)时,请求前公告由下一次请求追加在末尾。
+- `total_tokens_reminder`(见 `loop/meta-user-context.md`):compaction 不重述它。auto/reactive compaction 前收集的那条在保留段里,摘要请求和 compaction 后的第一个请求不产生新提醒。auto 与 reactive 成功后,runtime 把 compact 前最近一条带 usage 的 assistant 的上下文量加进计数器的 rolled;manual compact 不加,下一条真实用户消息会重新起算。
 - summary 文本:续写提示("Continue the conversation…Pick up the last task as if the break never happened.")之后,保留段非空时再追加 `\n\n` 和尾注 "The messages after this summary are the most recent messages from before compaction, kept verbatim. The summary was written without seeing them, so something it says has not happened yet may already have happened in them."。判定与请求前公告相同(保留段非空);manual compact 不带尾注。尾注随 summary 文本持久化,冷恢复读到相同字节;已有 summary 不改写。
 - summary 是普通 user 消息,按用户输入参与相邻 user 的换行规则:summary 前紧挨的 user 文本(例如保留段非空时的请求前公告)以 `\n` 结尾。判断依据是 `compactBoundary`,不按 `legacy_synthetic` 来源(旧的后台通知也用这个来源)。
 - 压缩提示词包括第 6 节末尾的用户消息归属说明("Only messages that actually came from the user (user-role turns) count as user messages…")和 `</example>` 之后的换行。
@@ -160,6 +161,7 @@ compaction 结果的顺序(boundary → 请求前公告 → summary → 保留
 - 旧版本兼容:不改 strict 的 `compactBoundary` schema。`CompactionPart.metadata` 不进入 App 协议,旧版本按 JSON 读取 part 时忽略它。旧版本冷恢复时,summary 之前的公告不在 `slice(boundaryIndex)` 范围内,会被漏掉;跨过的保留段可能带回上一次的公告。这两种情况只影响上下文内容,不会导致读取失败。
 - git status 与分支:规则只看历史(见 `loop/meta-user-context.md`)。保留段非空且其中没有 `session_context` 时,compaction 通过 `ContextSourcePort.resolveGitContext` 按当前目录重新读取(分支直接读取,不使用轮询缓存),是仓库才在 summary 之前宣告;保留段为空时由下一次请求读取。读到的 Git 只进入公告,不改 runtime 的 context 快照,compact 写库失败时不留任何 Git 事实。没有 context port 的运行时沿用会话起始快照。
 - skills_listing:在 compaction 附件中紧跟 agent_listing_delta。保留段里没有 skills_listing 且当前 skill 目录不为空时重述完整列表,判定与输入附件收集相同;compact 后的第一次请求就带 skill 名单。ZCode 不找回已调用的 skill。已恢复列表的原位更新见 `loop/meta-user-context.md`。
+- 指令文件与 `MEMORY.md`:summary 返回后,与文件恢复并行重读(异步 IO,传入取消信号)。只更新 runtime 持有的指令内容与 Memory 索引,不改工作目录、环境、Git 预取标记。读取失败时沿用原内容并记 warn;取消时整个 compact 取消。重读结果先只用于生成 summary 之前的 context_prefix(见上表);compact 成功落库后才交给 runtime,同时把指令增量的 reason 改为 `compaction`(之后不再改回)。compact 失败或取消时 runtime 的内容和 reason 都不变。保留段为空时由下一次请求宣告完整块。`MEMORY.md` 的读取状态在 compact 读取状态装好之后按重读的内容写入。没有 context port 的运行时(子 agent)不重读。
 
 ### File rewind after compact
 
@@ -289,3 +291,11 @@ Compact boundary 需要记录附件摘要字段,供 debug、fork 和 rewind 
 5. `core: fork-required conversation rewind`
    - compact 前 conversation rewind 创建 fork,而不是污染当前 active chain。
    - 第一版通过 `/fork` 明确触发;后续可以在 message selector 中把 compact-covered conversation rewind 自动转成 fork proposal。
+
+### 辅助对话的 SQLite 批量 fork
+
+辅助对话采用独立副本。`commitForkFromSource` 在一个 SQLite 写事务内提供历史元数据,
+core 同步复用现有分支、稳定边界和身份改写,adapter 用批量 `INSERT SELECT` 搬运原正文。
+不在 JS 中构造完整正文 bundle,不引入共享历史、schema migration 或删除语义变化。
+来源选择和复制使用同一事务视图;回调禁止异步或外部 IO,命令事实和 child 一起提交。
+具体字段保留、兼容文字与验收边界见[辅助对话规格](../../../../../docs/ui/conversation-selection-side-chat.md#sqlite-批量创建)。

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

@@ -40,12 +40,11 @@ ZCode 的默认发布形态仍然是标准 Node.js CLI 包:`dist/zcode.cjs` 
 
 用户接口:
 
-- `pnpm run build:sea`:从仓库根依赖中解析 Turbo,并通过
-  `--cwd apps/zcode-cli` 在 CLI workspace 内用 `--force` 重建 CLI 之外的 package,
-  再直接重建 CLI bundle,最后构建首批全部 target;仓库包含嵌套 pnpm workspace,
-  因此 package 脚本不能用 `--workspace-root` 解析 Turbo,否则会错误限定到缺少该
-  binary 的内层 workspace。该流程既避免复用旧 package `dist`,也不把已有 SEA
-  产物写入 CLI build cache。
+- `pnpm run build:sea`:先在仓库根执行 `build:sea:prepare`,再构建首批全部 target。
+  准备入口先强制编译根 `shared`,再用根 pnpm workspace 按依赖顺序构建 CLI 包及其
+  传递依赖(含根 `model-option-map`、`session-control`),最后单独重建 CLI bundle。
+  CLI 子 workspace 的 Turbo 图看不到根目录的包,不能只用它构建。准备阶段不使用
+  Turbo 缓存,也不缓存已有 SEA 产物。
 - 根目录 `pnpm build:sea:all`:安装依赖后转发到同一个 all-target `build:sea` 入口。
 - `pnpm run sea -- <target 参数>`:只封装当前已有的 `dist/zcode.cjs` 和 runtime
   assets,不负责重新编译 workspace。
@@ -183,9 +182,7 @@ Windows 官方 `node.exe` 通常带 Authenticode 签名。脚本构建 Windows t
 - OpenTUI runtime asset manifest 覆盖 `@zcode/tui`、`@zcode/i18n`、
   `@zcode/contracts` 的 workspace runtime closure,并排除 workspace 源文件。
 - CLI bundle 版本注入读取仓库根 `package.json`,即使 `packages/cli/package.json` 版本不同也不改变 `zcode --version` 的构建时版本。
-- `build:sea` workspace 脚本必须在 `build-sea.mjs --all` 前通过 Turbo `--force`
-  重建 CLI 之外的 workspace,再通过 package-local `pnpm build` 直接重建 CLI;
-  CLI 必须排除在 Turbo build 外,避免把同目录中的已有 SEA 产物写入 `dist/**` cache。
-- package 脚本必须从仓库根解析 Turbo,但将 Turbo 的工作目录保持为
-  `apps/zcode-cli`;dry-run 回归测试需证明命令可执行、任务集合非空且不包含
-  `@zcode/cli`。
+- `build:sea` 脚本必须先调用根 `build:sea:prepare`;回归测试需证明准备入口的根 pnpm
+  依赖图包含 `@zcode/session-control`,且不包含单独构建的 `@zcode/cli`。
+- SEA 检查 workspace 包时只要求 `dist` 目录存在;只有子路径导出的包(如
+  `session-control`)没有 `dist/index.js`,回归测试需证明其产物被打入 SEA。

+ 7 - 0
apps/zcode-cli/docs/design/v2/session-event-store-retention.md

@@ -85,6 +85,13 @@ seq  1               2..N+1                              N+3               N+4 (
 `TRANSIENT_SESSION_EVENT_TYPES = { model_streaming, tool_call_progress, streaming_tool_ledger_updated, model_network_status }`,
 单一出处 `@zcode/contracts`。新增事件类型时若与消息流同频,必须同时加入该集合并补 reducer 忽略断言。
 
+## 调用与回放缓存的独立释放边界
+
+- V4 raw event 缓存入库时复用 `slimRetainedModelRequest`,保留 ID、序号和 messageCount,不修改完整 live 输入。EventStore 替换对象不能释放其它缓存已持有的旧对象,每个持有者必须自行瘦身。
+- 每次模型调用拥有可释放的 status sink。成功、异常、取消离开作用域时清除 runtime、events 和回调引用。ALS 拷贝可以保留 sink 外壳,不能延长 turn 数据寿命。释放后的迟到状态不再写入;释放前已进入 publish 的操作可以完成。
+- 普通调用、compact、标题、目标验证、workspace 文本生成和 sampling 使用相同释放边界。
+- 回归覆盖 raw cache 与 live 输入隔离、连续序号、结束后的迟到状态,以及保留 sink 外壳时 events/runtime 可被 GC 回收。
+
 ## 观测
 
 `getStats()` 返回 `sessions / events / evictedEvents / retainedTransient`,随进程内存本地诊断日志

+ 63 - 8
apps/zcode-cli/docs/design/v2/session-persistence.md

@@ -221,18 +221,22 @@ order by time_created, id;
 ```sql
 select * from part
 where message_id = ?
-order by id;
+order by sequence is null, sequence, time_created, id;
 ```
 
+`sequence` 是第一次写入的顺序,不是模型输出顺序。assistant 消息的 reasoning / text / tool part 都带
+`blockIndex` 时,repository 解码后再按 `blockIndex` 稳定排序这些 part,其他 part 位置不变;否则保持
+`sequence` 顺序。见 [Assistant 内容块顺序](./model/assistant-block-order.md)。
+
 ### Part 类型
 
 | `type` | 关键字段 | 用途 |
 | --- | --- | --- |
-| `text` | `text`, `synthetic?`, `ignored?`, `time?`, `metadata?` | 用户文本或 assistant 文本。 |
-| `reasoning` | `text`, `metadata?`, `time` | reasoning 流。 |
+| `text` | `text`, `synthetic?`, `ignored?`, `time?`, `metadata?`, `blockIndex?` | 用户文本或 assistant 文本。assistant 每个文字块一个 part。 |
+| `reasoning` | `text`, `metadata?`, `time`, `blockIndex?` | reasoning 流。 |
 | `file` | `mime`, `filename?`, `url`, `source?` | 用户上传文件、图片、工具附件引用。 |
 | `agent` | `name`, `source?` | 用户 prompt 中选择的 agent。 |
-| `tool` | `callID`, `tool`, `state`, `metadata?` | 工具调用及状态。 |
+| `tool` | `callID`, `tool`, `state`, `metadata?`, `blockIndex?`, `declarationIndex?` | 工具调用及状态。`declarationIndex` 只在旧数据里出现。 |
 | `step-start` | `snapshot?` | assistant step 开始,可记录快照。 |
 | `step-finish` | `reason`, `snapshot?`, `cost`, `tokens` | assistant step 结束。 |
 | `snapshot` | `snapshot` | 文件系统快照 ID。 |
@@ -403,8 +407,10 @@ project 级权限规则。第一版只做 project scope,不做 session/global
 1. 创建 session 时写 `session`。
 2. 用户提交 prompt 时写一条 `message(role=user)` 和若干 `part(text/file/agent)`。
 3. assistant 开始时写一条 `message(role=assistant)`,再写 `step-start` part。
-4. 文本和 reasoning 流更新同一个 `part`,不要每 token 新建一行。
-5. tool call 只更新同一个 `tool` part 的 state:`pending -> running -> completed/error`。
+4. assistant 回复的每个 reasoning 块、每个文字块各写一个 `part`,带 `blockIndex`(模型输出顺序);
+   不要每 token 新建一行。普通回复在流结束后写入;服务端工具轮次在流中写入。见
+   [Assistant 内容块顺序](./model/assistant-block-order.md)。
+5. tool call 只更新同一个 `tool` part 的 state:`pending -> running -> completed/error`,每次写入都带同一个 `blockIndex`。
 6. assistant 完成时更新 assistant message 的 `time.completed`、cost、tokens、finish,并写 `step-finish` part。
 7. compact、retry、patch、snapshot 都是 part,不新增专门表。
 
@@ -422,7 +428,7 @@ project 级权限规则。第一版只做 project scope,不做 session/global
 
 1. 读 `session`。
 2. 按 `(time_created, id)` 读取 `message`。
-3. 按 `(message_id, id)` 读取每条 message 的 `part`。
+3. 按 `(message_id, sequence)` 读取每条 message 的 `part`;有序 assistant 消息再按 `blockIndex` 排序。
 4. 拼回 `MessageWithParts`。
 5. context builder 再决定哪些 part 进模型上下文,例如忽略 `ignored`、处理 compact summary、裁剪工具输出。
 
@@ -456,7 +462,8 @@ project 级权限规则。第一版只做 project scope,不做 session/global
 Provider-visible 恢复规则:
 
 - `user` message 只拼接未 `ignored` 的 `text` part;第一版对 `file` part 只保留可读占位,后续再接入多模态恢复。
-- `assistant` message 拼接 `text` part;`tool` part 转回 assistant tool call。
+- `assistant` message:有序消息按 `blockIndex` 恢复不合并的 reasoning / text 块和 tool call;旧消息拼接
+  `text` part,`tool` part 转回 assistant tool call。浏览器轮尾截图 tool part 不进入模型上下文。
 - `completed` tool part 转为成功 tool result;有 `state.attachments` 时从 artifact 按顺序重建
   provider-neutral 媒体 block,没有附件时继续使用 `state.output`。
 - `error` tool part 转为失败 tool result。
@@ -563,6 +570,39 @@ fork 不需要复制复杂状态。
 
 第一版建议复制 message/part,简单、可离线、好理解。
 
+#### 会话 cwd 与 workspace 分离(受管 worktree)
+
+产品规格:`docs/git/worktree.md` §1.1、§6.6、§9.3。受管 worktree 只是会话的 cwd:workspace key、CLI 进程和 sessions-index 都属于项目。
+
+| 项 | 规则 |
+| --- | --- |
+| 新建 | V4 `createSession` 可带 `cwd`。会话的 workspace ref = `{ workspaceKey: 由 workspaceId 得到(项目), workspacePath: cwd }`;远程 workspace 带 `cwd` 返回 `guard.worktreeCwdLocalOnly` |
+| 持久化 | `session.directory` / `path` = cwd;`workspace_id` 仍只存远程 identity(本地为空)。session 表不加列 |
+| 归属 | live record 的 `workspace.workspaceKey` 是项目 key,进入项目的 sessions-index。冷列表时目录扫描看不到这些会话,Host 订阅时用 `worktreeSessionIds` 精确提供 id,CLI 只读、并确认会话属于该 workspace 后才返回;`sessionsIndex/reconcile` 用同一判定。属于的判定(`isLocalSessionDirectoryInWorkspace`,文件系统部分在 `classifyLocalSessionDirectory`):cwd 与 workspace 是同一个真实目录(realpath);或 cwd 经受管 worktree resolver 映射回该真实目录;或 cwd 是已删除的受管 worktree,此时才以创建时持久化的 `projectID`(§6.6.3)为准,删除、重命名等 CLI 事实照常回写。projectID 是有损 slug,不作一般归属证明。冷恢复 / 激活校验与冷列表共用这一函数(激活时请求的执行路径也要通过) |
+| 冷恢复 | Host 携带本地 workspace 时:路径与存储目录是同一目录则沿用请求路径;不同则执行路径取存储目录(cwd 创建后不变),key 仍取请求。subscribe 之外会冷恢复的 V4 查询与命令信封也带 Host 注入的 `workspace`(产品规格 §9.3),gateway 原样传给冷恢复 |
+| 反向请求 | 官方 MCP 授权头等发往 Host 的请求用会话的 `workspaceKey`,不按 MCP 的工作目录重新计算;MCP 连接池(含 workspace 级共享连接)仍按 cwd 分组,因为 stdio 进程的工作目录就是 cwd |
+| 项目身份 | 权限 `project_id` 与项目记忆目录按 cwd 映射回源仓库的路径派生(`AgentRuntimeConfig.projectDirectory`),与 Hook Trust 同一 resolver;映射失败按 cwd |
+| 对外 key | Hook Trust admission、审核 request 等对外字段用会话所属 workspace 的 key(`ZCodeAppOptions.workspaceKey`) |
+| 能力 | `runtime/capabilities` 返回 `worktreeCwd: true`;旧 CLI 静默丢弃这些字段,Host 必须先确认 |
+
+"已创建 worktree":`createSession.worktreeCreation = { path, sha, ref, output }` 先记在 runtime,首轮 `ensureSessionPersisted` 之后、`TurnStarted` 之前写成 timeline part(`timelineType: "worktree_creation"`、`display: "worklog"`,`providerVisibility: hidden`,不进模型上下文),并发出 `WorktreeCreated` 事件。投影在首个 `TurnStarted` 时于轮顶(`lightBoundary`)落 `timelineMarker { type: "worktreeCreated" }`;冷恢复从 timeline part 合成同一事件。
+
+#### fork 到受管 worktree(`forkAssistant.targetCwd`)
+
+V4 `forkAssistant` 可带 `targetCwd: { cwd, childSessionId, worktreeCreation }`。不带时行为不变。带上时:
+
+| 项 | 规则 |
+| --- | --- |
+| child ID | 使用 Host 预分配的 `childSessionId` |
+| `directory` / `path` | `cwd` |
+| `workspaceID` | 沿用父会话(本地为空),child 仍属于父会话的 workspace |
+| `projectID` | 按 cwd 映射回源仓库的路径派生(同上) |
+| `permission` | 去掉会话级 `allow` 规则(与父 cwd 绑定);`deny`、`ask`、`mode`、`scope`、`version` 原样保留 |
+| 对话 | 只复制稳定边界前的对话,不回退、不恢复任何 checkpoint;fork 分隔标记所在的宿主消息里追加 `worktree_creation` part |
+| 运行归属 | 同一 workspace 与进程:child 照常在当前 CLI 进程注册,record 的执行路径取 child 持久化的 cwd |
+| 远程 | 父会话在远程 workspace 时返回 `guard.worktreeCwdLocalOnly`,不写入任何数据 |
+| 幂等 | 沿用 `(父 session, sourceCommandId)` 的 command fact |
+
 ### 彻底删除(项目数据删除)
 
 普通删除只写 `time_deleted`。用户在设置 → 项目里勾选「同时删除 ZCode 数据」时,Host 经 `v4/storage/sessionData/purge` 交来会话 ID 与目录(产品规格:`docs/superpowers/specs/2026-10-24-project-management.md`「彻底删除数据」):
@@ -640,3 +680,18 @@ interface SessionStore {
 7. 接入 revert:`session.revert` + snapshot + patch cleanup。
 
 这就是持久化的主线:少量表,message/part JSON 承载业务结构,运行状态留在内存,compact/revert 都通过已有 message/part/session 字段表达。
+
+### 加速卡归属元数据
+
+`metadata.highspeed.ownerKey` 是可选的稳定匿名账号归属,随原对象保存和冷恢复,不加入凭据。CLI声明 `highspeedCardOwner` 后Host才下发此字段;旧端仍接收原schemaVersion=1的元数据。指标更新只合并字段,不丢失ownerKey;未知归属旧记录保持未知。
+
+## 归档会话永久删除
+
+归档管理使用独立的 V4 `storage/sessionData/deletionPreview` 与 `deletionExecute`,不改变旧软删除与项目数据清理语义。产品范围见 [归档规格](../../../../../docs/superpowers/specs/2026-09-11-archive-management.md)。
+
+- CLI 是正文与文件的唯一写者;Host 只校验归档状态并清除自己的索引。预检 revision 固定 owned tree、引用与文件清单,执行前复查。
+- `session_runtime_presence` 登记进程持有的 runtime;其他活进程持有时拒绝删除,不用超时认定进程已退出。本进程检查请求、初始化、运行任务、排队输入和交互。
+- `session_purge` 只保存目标 ID、操作 ID、目录身份、保留附件 ID 和完成状态。SQLite 事务准入与写入触发器阻止新的 runtime、正文写入、派生会话及引用。它不保存消息或标题。
+- `0025_session_permanent_deletion` 保留已发布 SQL 与 checksum。已记账的数据库继续校验后跳过;未记账但已有部分或全部同版结构时,`apply` 仅补缺失的表、索引和触发器,保留现有数据与删除凭据,再由原迁移事务记账。此守卫不改写已有同名对象,也不修复不兼容的表结构。
+- 顺序为准入 → 释放空闲 runtime → 删除私有文件 → 删除 owned tree 数据行 → 标记完成 → 移除 Host 索引。任一步失败保留凭据,用户重试继续清理;无法把部分删除的会话恢复为普通会话。完成后同 ID 不能重建。
+- 独立 fork 保留;仍被保留会话引用的附件文件留下,原对话正文继续删除。已发布分享、工作目录、导出、备份与系统日志不联动。不承诺磁盘取证级擦除。

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

@@ -20,19 +20,105 @@ SendMessage 的 summary 改为可选、超长截断;Agent 描述的后台一
 (ZCode 默认前台运行,后台说明只写这一行)。tools 段升级后缓存失效一次;细节见 07-subagent.md。
 后台 agent 终态通知的文本与 `originMeta.subagentResult` 结构化结果见 07-subagent.md;App 不解析 summary 文本,
 Agent 卡片的“执行失败”hover 仍只显示原文;只影响新产生的通知,已发送的历史不改写。
-运行时校验(2026-10-20):Bash 超时转后台的 `timedOutAfterMs` 与输入 `timeout` 一样允许小数;
-SendMessage 只有空白的 message 在 hook 与权限之前判为输入错误(child 只收到 message),模型收到 `<tool_use_error>message must not be empty</tool_use_error>`。provider schema 与 tools 段字节不变。
-工具 Hook 上下文(2026-10-21):`PreToolUse` / `PostToolUse` / `PostToolUseFailure` 返回的 additionalContext
-不再拼进 tool_result。executor 把每条 context 写成 `<Event>:<ToolName> hook additional context: <context>`
-(例如 `PreToolUse:Bash hook additional context: …`),放进 `ToolExecutionResult.hookAdditionalContexts`;
-结算把每条写成一个 `tool_hook_context` 附件,排在这批 tool result 之后、其他批次提示之前,按 tool result 的顺序分组,
-同一工具 Pre 在前,多个 Hook 不合并、多行原样保留。tool_result 只放工具原文:失败时与没有 Hook 时是同一段错误原文,
-Hook 文本也不占 tool result 预算。MCS 下这些附件和同批其他附件合成同一条 system;非 MCS 下按普通 user 侧提醒投影。
-附件持久化,resume 后位置不变。`tool_call_result` 事件和 App 工具卡不再含 Hook 文本;官方 CUA 帧凭据过滤保留。
-Memory 后台循环(Extraction、Dream)用同一个 `toolBatchModelEntries` 生成这批 entries,批次提示照常送达;
-它的 executor 不配置 hooks,所以没有 Hook 上下文(见 [Memory](../memory/README.md))。
-单条 context 超过 10000 字符时先落盘,附件里只放 `<persisted-output>` 外壳;落盘失败时截到 10000 字符并附原因
-(规则见 hooks.md「聚合规则」)。
+
+- 胶囊单项停止 Agent:模型可见 `Agent`/`TaskStop` schema 不变;runner 在子任务启动事件中
+  提供真实 task 与本次执行身份,V4 `subagents.running.stopControl` 只投影当前 runtime 可操作
+  能力,冷恢复不得从历史 agentId 补造。App 的 `stopSubagent` 命令由父会话 runtime 校验归属、
+  执行身份和运行态,调用原 `SubagentPort.stopTask`;前台回原工具调用停止结果、不发后台通知,
+  后台保留 killed 通知。迟到 Stop 不能停止同一 agentId 的 SendMessage 新执行,完成/停止只提交
+  一个终态。停止产物写入失败不得阻断目标取消与终态事件,事件收口后仍向调用方报告原始
+  文件错误。UI 只显示明确能力,不再从 backgroundWorks 猜测;详情目录不加停止入口。
+  端到端行为见根目录 `docs/subagent-session-directory.md`。
+  运行时校验(2026-10-20):Bash 超时转后台的 `timedOutAfterMs` 与输入 `timeout` 一样允许小数;
+  SendMessage 只有空白的 message 在 hook 与权限之前判为输入错误(child 只收到 message),模型收到 `<tool_use_error>message must not be empty</tool_use_error>`。provider schema 与 tools 段字节不变。
+  工具 Hook 上下文(2026-10-21):`PreToolUse` / `PostToolUse` / `PostToolUseFailure` 返回的 additionalContext
+  不再拼进 tool_result。executor 把每条 context 写成 `<Event>:<ToolName> hook additional context: <context>`
+  (例如 `PreToolUse:Bash hook additional context: …`),放进 `ToolExecutionResult.hookAdditionalContexts`;
+  结算把每条写成一个 `tool_hook_context` 附件,排在这批 tool result 之后、其他批次提示之前,按 tool result 的顺序分组,
+  同一工具 Pre 在前,多个 Hook 不合并、多行原样保留。tool_result 只放工具原文:失败时与没有 Hook 时是同一段错误原文,
+  Hook 文本也不占 tool result 预算。MCS 下这些附件和同批其他附件合成同一条 system;非 MCS 下按普通 user 侧提醒投影。
+  附件持久化,resume 后位置不变。`tool_call_result` 事件和 App 工具卡不再含 Hook 文本;官方 CUA 帧凭据过滤保留。
+  Memory 后台循环(Extraction、Dream)用同一个 `toolBatchModelEntries` 生成这批 entries,批次提示照常送达;
+  它的 executor 不配置 hooks,所以没有 Hook 上下文(见 [Memory](../memory/README.md))。
+  单条 context 超过 10000 字符时先落盘,附件里只放 `<persisted-output>` 外壳;落盘失败时截到 10000 字符并附原因
+  (规则见 hooks.md「聚合规则」)。
+
+## Agent 同步失败附部分报告与 agentId(2026-11-09)
+
+child 事件 → `runExploreAgent` 请求的 `onEvent` → runner 收集本次运行、本 child session 的 `ModelComplete` 与 `model_request_failed` → child turn 报错、task 记 failed
+→ 抛出的错误带 `AgentFailureHandback`(contracts `tools/agent.ts`,不可枚举属性,不在 `context` 里)→ executor handler 失败分支调用
+`ToolEntry.formatErrorModelContent`,经 `createErrorResult` 的 `modelNote` 接在模型可见原文之后 → `ToolExecutionResult.modelContent`
+→ tool part `metadata.modelContent` 持久化,冷恢复重放。
+原来父模型只收到 provider 原文(如 429),拿不到 agentId,已经跑了几十步的子代理无法用 SendMessage 续接:runner 只把 agentId 写在
+wrapper 的 `context` 里,executor 不把 `context` 给模型;子 turn 的错误本身是 CoreError 时还直接透传,连 wrapper 都没有。现在只给模型的文本
+在原文后追加截断说明与部分报告(本次运行有正文时;取正文规则与"同步报告"相同)、`agentId` 行和 `<usage>`。交接数据作为不可枚举属性
+直接加在原错误上,不复制错误、不加 wrapper 层,错误身份与 stack 不变(复制会丢 stack:Node 的 `stack` 是读原对象内部槽的 accessor),
+所以 `error.message` / `code` / `detail` / `stack`、`tool_call_error` 事件、Agent 卡片的
+"执行失败"与 hover 都不变;部分报告不进 `context`,日志里没有它;`message-mapper` 发给 App 前剥掉 `modelContent`。工具 schema、描述、
+权限、registry / metadata / `SubagentStopped` 的 failed 状态都不变;只影响新产生的结果。回归覆盖:子代理写过正文后模型请求失败,
+父模型看到原文、截断说明、部分报告和 `agentId` 行,UI 摘要只有原文;没有正文时只追加 `agentId` 行和 `<usage>`;CoreError 透传时错误对象与
+stack 不变、wrapper 分支同样带交接;watchdog 超时追加且类型仍是超时;启动前失败与用户停止不追加;父模型用拿到的 agentId 经 SendMessage
+续接子代理;用量计入已计费的失败请求,其他 session 的事件不算。规则见 07-subagent.md「同步失败」。
+
+后台运行(显式后台、前台转后台、SendMessage 续接)失败时用同一个收集器:`finalizeBackgroundFailure` 取本次运行最近一段非空 step 正文写进
+失败通知的 `<result>`,不套框架、不加截断说明,没有正文时不写;`task-id` 就是 agentId。原来失败通知不带 `<result>`,后台子代理跑了很多步后
+失败,父模型拿不到已写出的正文。App 侧共享解析器 `parseZCodeBackgroundTaskNotifications`(`packages/shared`)对 failed 且带 `<note>` 的块
+丢弃 `<result>`:只有 local agent 通知带 `<note>`;合并轮没有结构化 error,App 的失败原因会依次退到 `result`,不丢弃时 hover 显示的是半截正文
+而不是失败原因。workflow 失败通知不带 `<note>`,它的 `<result>` 照常读取。回归覆盖:core 后台失败通知带部分报告、没有正文时不带;BG26 合并
+通知用例里先写正文再 429 的子代理,父模型收到的通知带这段 `<result>`,失败 hover 不出现它。规则见 07-subagent.md「后台终态通知」。
+
+## Agent 空报告回退到最近一段正文(2026-11-09)
+
+child turn → `runAgentToCompletion` → `AgentCompletedOutput.content` → Agent 工具结果 / 后台 task-notification:
+报告原来只取 `TurnResult.response`,即最后一个模型 step 的正文。报告写在带工具调用的 step、最后一步只回空
+正文时,父会话收到 "(Subagent completed but returned no output.)",只能再用 SendMessage 唤醒补发。现在
+最后一步正文为空时,从本次运行的 `ModelComplete` 事件倒序取最近一个非空 `content`,与 usage 汇总读同一份事件;
+只认子代理主循环的 step(`querySource: "subagent"`,与 `querySourceForTask` 共用 `SUBAGENT_QUERY_SOURCE`),
+轮中压缩等 sidecar 请求写的 `ModelComplete` 不算,压缩摘要不会被当成报告,压缩前的报告仍能取到。
+只取正文,不取 reasoning。全部为空时仍用原空报告文案。首次运行与 SendMessage 恢复走同一入口;前台工具结果、
+后台通知 `<result>`(App 用它更新后台 Agent 工具卡内容)与输出文件读同一份报告。取消与报错仍由 `executeTurn`
+抛错,不经过回退。工具 schema、描述、权限、事件与 App 协议不变;只影响新产生的结果。回归覆盖子代理先写报告再调用工具、最后一步空正文时
+父会话拿到该报告,以及轮中自动压缩后最后一步为空时拿到压缩前的报告而不是摘要。规则见 07-subagent.md「同步报告」。
+
+## SendMessage 声明为只读(2026-11-09)
+
+`sendMessageToolEntry.metadata.readOnly` → `PermissionService.resolveCapability` → Plan 闸门:`SendMessage` 改为
+`readOnly: true`,与 `Agent` 一致,Plan 下由 `mode.plan.readOnly` 放行。原来被 `mode.plan.nonReadOnly` 拒绝,父会话
+在 Plan 下无法唤醒已结束的子代理补发报告,07-subagent.md 里"恢复的子会话进入 Plan"的路径从模型侧到达不了。
+恢复已结束的子代理时子会话模式按父会话当前状态重算;给运行中的子代理发消息只投递消息,该子代理仍按启动时的
+模式执行,Plan 不约束它(已接受的行为变化)。其他模式的判定
+结果不变(原来经 `mode.build.sessionState` 放行,现在经 `mode.build.readOnly`);调度仍由 `concurrentSafe`
+决定;流式提前执行要求 `sideEffectScope: "none"`,SendMessage 是 `"session"`,不受影响。`readOnly` 不进入
+provider 请求,tools 段字节不变;工具名、schema、描述、`permission` 声明与 App 协议不变。`ToolCallStarted`
+载荷(来自 executor 的 `resolveToolCallCapabilityFlags`)与工具用量遥测(turn-tool-usage / usage-observability)里 SendMessage 的
+`readOnly` 随之变为 `true`,`sideEffectScope` 仍是 `"session"`;bootstrap session-mapper 发给 App 前剥掉这两个
+字段,App 收到的事件不变;动态工作流按 scope 判定,也不受影响。回归覆盖 Plan 父会话
+经模型调用 SendMessage 恢复已结束的子代理:调用放行,子会话在 Plan 下拒绝写命令。规则见根目录
+`docs/plan-mode-approval-boundary.md`。
+
+## 工具 part 的块顺序(2026-11-03)
+
+ToolPart 新增可选 `blockIndex`,与 text / reasoning part 共用一次模型响应里的块到达序号。pending、
+running、completed / error 每次写入都必须带上调用对象的 `blockIndex`:`savePart` 的冲突更新整体替换
+`data`,漏写一次整条消息就按旧消息处理,排序回到改动前的布局,而且不报错、不打日志。新增 tool part
+写入点时按这一条检查。`declarationIndex` 不再写入,只在旧数据里读取。session-store 读取时对有序消息
+按 `blockIndex` 重排块 part;冷恢复按 `blockIndex` 恢复工具调用和结果的顺序;live 在
+`executeToolCallsForModelStep` 按同一个 `blockIndex` 顺序调度、执行并提交结果;浏览器轮尾截图 tool part
+不进入模型历史。工具 schema、权限、事件和 V4 协议字段不变。详见
+[Assistant 内容块顺序](../model/assistant-block-order.md)。
+
+## CMD 自动授权收紧(2026-11-09)
+
+session 固定的 `bashShellSelection` → Bash runtime capability / command permission policy →
+既有审批 → ExecutionPort。明确选择 `cmd` 或 `legacy-shell` 时,不再用 Bash AST 授予只读免审批,
+也不通过其 prefix/wildcard 推导自动 allow;授权建议只保留完整命令。根因是 Bash 会将 `#` 后的
+CMD 命令当成注释,使审批看到的操作少于实际执行的操作。能力事件也传递同一 shell 选择。
+Build/Edit 无明确授权时请求审批,Plan 拒绝;完整命令授权、工具级显式授权及 yolo/guarded
+的既有模式语义保持不变。deny/ask 的既有规则匹配保留,本次不扩展 CMD 解析器,不能据此宣称
+已支持完整 CMD 子命令 deny 匹配。POSIX/Git Bash 和未传 selection 的旧内部调用沿用原行为。
+不改工具 schema、命令执行、权限事件字段或桌面/手机投影。回归覆盖截图形式的命令、普通只读
+CMD、前缀/通配授权不放行、完整授权、Plan 拒绝、审批拒绝前执行端零调用以及能力事件。
+细节见 [Bash](04-bash.md#权限模型)。
 
 ## Bash 注入会话上下文环境变量(2026-11-01)
 
@@ -121,15 +207,41 @@ wrapper 中的 sed 也必须通过同一白名单,项目 allow 不能解除 Pl
 并通过真实 executor 验证拒绝事件和执行端零调用。运行时验收在临时目录检查文件副作用。
 完整边界见 [Bash](04-bash.md) 与 [AST 权限语义](../../../bash-tool-ast-permission-semantics.md)。
 
+## 动态工作流子代理的 WebSearch 预算(2026-11-02)
+
+dwf 子代理每个 ask 的 `WebSearch` 调用次数有上限:默认 128,persona 的 `budget.webSearch` 可设 0–1024
+(编译期 9013 检查)。链路:facade `AgentPersona.budget` → 引擎 `normalizePersona` 保留合法值、
+`personaIdentity` 不计入缓存身份 → driver 建会话时读上限、`startAsk` 归零计数 → runtime factory 注入
+`WorkflowWebSearchBudgetPort` → runtime deps → executor → tool context → WebSearch handler 在发请求前 `charge()`。
+超额时 handler 回 `ToolHandlerFailure`,不发内部请求。工具 schema、描述、权限、tools 段字节、协议与 UI 不变;
+没有端口的会话行为不变。规格见 `13-websearch.md`、根目录 `docs/dynamic-workflow/authoring.md`
+「A subagent's search budget」与 `packages/dynamic-workflow/docs/execution-engine.md`「Search budget」。
+
+## 别的进程持有的工作流 run(2026-11-01)
+
+`FillWorkflowHole` 与 `AmendWorkflow` 在 `resolveInput` 读快照新增的 `liveInThisProcess`:run 未终态而引擎不在本进程时,
+不开确认窗,分别回 `hole_not_waiting` 与 `workflow_run_held_elsewhere`(日志码 30)。此前窗照开,用户批准后才失败。
+工具 schema、描述与 tools 段字节不变;只改权限之前的结果。已结束的 run 仍可从别的会话修订,经确认窗。
+规格见 `docs/dynamic-workflow/launch.md`「Approval」「Amending this session's runs」。
+
 ## 会话 ID 兼容(2026-10-28)
 
 普通新建恢复 `sess_${crypto.randomUUID()}`(UUID v4);已持久化的 `session_` 身份不变。
-Composer session mention → runtime reference reminder → ReadSessionContext schema
-→ 原 ID 的 SessionStore 查询 → 原 ID 的工具结果,兼容两种前缀。
+Composer session mention → runtime reference reminder → `ReadSession`(`sessionId` 写法)
+→ 原 ID 的会话库查询 → 原 ID 的工具结果,兼容两种前缀。2026-11-03 起提醒不再指向已删除的 ReadSessionContext。
 邮箱目录仍按原 ID 隔离;保留路径安全校验、权限、工具超时与返回结构。
 回归覆盖两种历史后缀、混合引用去重、非法 ID 拒绝、准确读取及完整重启后继续对话。
 完整规格见根目录 `docs/session-context-tool.md` 的 Session identity compatibility。
 
+## 删除 ReadSessionContext,新增 ReadTopicResource(2026-11-03)
+
+设计见根目录 [会话工具设计](../../../../../../docs/architecture/zcode-app-control-design.md) 0.8。
+
+- 删除:`contracts/tools/read-session-context.ts`、core handler、`session-context` 中只服务于该工具的抽取与话题原文模块、`read_session_context_*` 模型调用遥测、对应 CLI 测试与 E2E(O07、工具交叉矩阵该项)。`#sess_*` 提醒改为指向 `ReadSession` 的 `sessionId` 写法。
+- 新增 `ReadTopicResource`:受管模块 `topic-resource-tool`(`core/src/tool/topic-resource/`,含 schema、资源读取实现与 CONTRACT.md;handler 在 `tool/handlers/read-topic-resource.ts`)。`contract.ts` 定义输入 `{ inputId?, messageId, index? }` 与输出 `{ status, path, fileName, mime, bytes, messageId, index }`;core handler 复用原话题资源授权与托管落盘;仅在运行时注入 `topicResourcePort` 时注册(App 托管会话),不属于动态工作流灰度门,`shouldDefer: true`;`readOnly: false`、`sideEffectScope: "session"`、无需审批;权限名 `session.topic_resource.read`;workflow actor 禁用。
+- 链路:模型调用 → schema 校验 → 权限 → handler(会话库读可信输入意图 → 资源索引校验 → Host 端口按授权读取 → artifact store 托管二进制)→ tool result 只含路径与元数据 → UI 走通用工具卡片。旧会话中的 ReadSessionContext 调用仍由 App 原只读渲染器显示。
+- 验证:core handler 测试(授权、索引、端口缺失、大小与编码校验)、注册条件测试、bots E2E BOT-E2E-TP-05 改走新工具。
+
 ## 共享 CLI 的工具请求归属(2026-10-27)
 
 定时、闲时工具沿用模型输入、权限、结果和持久化契约。协议 port 从自身 session record
@@ -151,6 +263,13 @@ Edit 写读取状态时记下;冷恢复取自 tool part 的输入,不写进
 的内容变为文件当前内容,只影响新产生的 compaction,已持久化的不改写。规则见
 [rewind-compact.md](../rewind-compact.md) 与 [17-read-file-state-resume.md](17-read-file-state-resume.md)。
 
+## Agent 历史名称恢复(2026-10-27)
+
+持久化 Agent/Task tool input 的 `subagent_type` → transcript hydration 的 agentType →
+SubagentSpawned/Completed → V4 subagent row → App 摘要名称。输出和 metadata 的显式 agentType
+继续优先;input 读取 subagent_type 后兼容 agent / agentType,缺失时保留原 subagent 回退。
+不修改持久化数据、工具 schema、权限或执行行为。回归覆盖纯文本 output 与输出名称优先级。
+
 ## MCP 手动信任(2026-10-23)
 
 工作区直接 MCP 声明 → bootstrap 当前声明快照 → 用户域逐条信任 → MCP port 准入 →
@@ -166,6 +285,41 @@ Edit 写读取状态时记下;冷恢复取自 tool part 的输入,不写进
 新用户输入包含用户 guide/steer;首输入复用初始化读取。配置加载器保留;提示刷新不改变现有连接的准入结果。
 准入提示更新不计为会话活动;冷恢复和授权通知均不得改写 sessions-index 活动时间。
 
+## node_repl 描述只留跨 skill 契约(2026-11-09)
+
+`mcp__node_repl__js` 的 tool description 删掉 Computer Use 与 Browser Use 的专属用法,只保留路由与能力、`title`、
+`timeout_ms`、`nodeRepl.write` / `nodeRepl.emitImage` 与“每次调用都 bootstrap”,长度 2182 → 955 字符;
+server instructions 末句缩为 “Every `js` call starts fresh.”(622 → 530)。CUA 段是 v1 SDK 遗留:要求
+`nodeRepl.write(state.text)` 与 `state.state_id`,与现行 skill 的“观察自行展示、不要再 write”相反(SDK 侧见
+`computer-use-client.mjs` 的 emitText 注释);其余 tab 恢复、坐标、同 cell bootstrap 等句子 skill 已覆盖。
+`nodeRepl.cwd/homeDir/tmpDir/requestMeta/setResponseMeta` 不再列出,运行时仍提供。skill 不改(CUA SKILL.md 距
+14 KiB 上限仅 19 字节,不往里挪内容)。schema、权限、执行、事件、V4 与 UI 不变;tools 段字节变化,升级后第一个
+请求缓存失效一次;node-repl-host 版本不升。合同见根目录 `docs/mcp-stateless-node-repl.md` §2。回归:
+`node-repl-host/test/mcp-server.test.ts` 的 “keeps Browser Use and Computer Use usage rules in their skills”。
+
+## node_repl 描述删除 import 规则(2026-11-06)
+
+`mcp__node_repl__js` 的 tool description 删掉 import 规则整句(`node:*` / 绝对 `file://` URL / 裸包名不解析),
+只保留 “Bootstrap the requested official capability in every call.”。原因:该句仍被读成模块白名单;且
+“裸包名不解析”与实现不符——`require` 来自 `createRequire(cwd)`,裸包名从工作区 `node_modules` 解析。
+官方脚本的 import 写法由 Browser Use / Computer Use skill 的 bootstrap 示例提供,模型不依赖这句。
+schema、权限、执行、事件、V4 与 UI 不变;tools 段字节变化,升级后第一个请求缓存失效一次;node-repl-host 版本不升。
+合同见根目录 `docs/mcp-stateless-node-repl.md` §2。回归:`node-repl-host/test/mcp-server.test.ts` 的描述断言。
+
+## node_repl 描述如实说明能力(2026-11-05)
+
+`mcp__node_repl__js` 的 tool description 与 server instructions 如实说明能力:代码以 agent 权限运行、没有沙箱,
+且不经过 Bash 的危险命令确认;并以此为理由保留路由禁令(“never use it for shell, file, package inspection,
+or data processing work; use the dedicated tools”)。import 说明去掉 “only”,只描述 `node:*` 与绝对 `file://`
+的解析规则。起因是外部安全评估把旧文案读成受限运行时,把加载 `node:child_process` 判为沙箱逃逸。
+审批路径不变也不对齐 Bash:`js` 按 MCP high/system 审批,guarded 下无危险命令匹配、按 YOLO 基础策略放行,
+所以路由禁令不能放宽成建议(MR !3499 评审 CR-01)。
+代码侧同步去掉沙箱命名:`restrictProcess` → `protectProtocolStdio`,`createRestrictedProcessFacade` →
+`createProtocolSafeProcessFacade`,vm context 对象 `sandbox` → `replGlobals`;facade 行为不变,只保护 MCP stdio
+与宿主进程生命周期。schema、权限、执行、事件、V4 与 UI(含审批卡片)不变;tools 段字节变化,升级后第一个请求
+缓存失效一次。node-repl-host 版本不升:server.js 的 buildIdentity 每次构建都变,官方 seed 会重新落盘。
+合同见根目录 `docs/mcp-stateless-node-repl.md` §2。回归:`node-repl-host/test/mcp-server.test.ts` 的描述断言。
+
 ## node_repl 无进展提示(2026-10-26)
 
 只改 node-repl-host 内部:`tools/call(js)` 按 `session_id + turn_id` 计同码、同结果与本 turn 调用量,
@@ -175,6 +329,95 @@ schema、权限、超时、isError、图片顺序、core 的 model-anomaly 与 U
 合同见根目录 `docs/mcp-stateless-node-repl.md`「无进展提示」。回归:`no-progress-guard.test.ts`
 与 `mcp-server.test.ts` 的 MCP 调用序列。
 
+## CLI / App 会话控制工具(2026-10-23)
+
+工具名改为 PascalCase(2026-11-03):12 个名字由 snake*case 改为 `ListSessions`、`ReadSession`、
+`CreateSession`、`ForkSession`、`SendToSession`、`WaitSessions`、`InterruptSession`、`RenameSession`,
+App 另有 `ListProjects`、`OpenSession`、`SetSessionArchived`、`SetSessionPinned`。原因不只是观感:
+App 端 `toolIdentity.ts` 的 `resolveLegacyKindFamily` 按下划线边界匹配历史 `kind`,snake_case 名字因此被
+误判——`read_session` / `open_session` 渲染成读文件卡、`list*\*` 渲染成搜索卡、`create*session`渲染成写文件卡,
+其余落兜底卡并被首字母大写。PascalCase 无下划线,每条规则的`(?:*|$)`边界结构上不可能成立。
+不保留别名;权限规则名`session_control.<method>`不变(改它会第二次作废用户已保存的审批)。
+schema、权限、结果预算、超时与 V4 投影不变,只影响新请求的 tools 段(缓存失效一次)。
+注意构建顺序:bootstrap 测试经`@zcode/core`的 dist 取注册表,改名后必须先`pnpm build` 再跑,否则断言拿到旧名字。
+规格见 [会话控制设计 0.12](../../../../../../docs/architecture/zcode-app-control-design.md)。
+
+统一工具名(2026-11-02):模型只看到一套名字,删除 `cli_` / `app_` 前缀且不保留别名。共有
+`ListSessions`、`ReadSession`、`CreateSession`、`ForkSession`、`SendToSession`、
+`WaitSessions`、`InterruptSession`、`RenameSession` 8 个;App 托管 runtime 另注册
+`ListProjects`、`OpenSession`、`SetSessionArchived`、`SetSessionPinned`。工具声明按名字只有一份,
+输入 schema 按可信装配的运行位置选择(独立 CLI 或 App),权限规则名改为
+`session_control.<method>`。指向已有会话的参数在完整引用之外可只传 `sessionId`(wait 的每个
+operation 同样),二者必须且只能有一个,由可信一侧解析后沿原授权执行。独立 CLI 的
+list/read 读本机 CLI 会话库,不要求 owner;写工具仍只作用于本进程托管的根。ToolSearch、
+deferred 曝光、结果预算与 V4 投影沿原链路,名称变化只影响新请求的 tools 段(缓存失效一次)。
+详见根目录 [会话控制设计](../../../../../../docs/architecture/zcode-app-control-design.md) 第 0 节。
+
+跨项目发现修正:App `listProjects` / `listSessions` 默认读取 Host 授予的已连接来源与项目入口,
+不再按 caller 项目或临时工作区收窄。只读发现范围与正文/执行/组织/导航的 `allowedScopes` 分离;
+显式 project/workspace 只缩小搜索,不能扩权。严格输出增加 `searchScope`,明确实际范围及不可用来源;
+工具说明应说明标题子串匹配、无正文全文搜索,并要求按回执范围解释空结果。按运行位置选择 schema 与
+deferred 曝光不变,所有 App 结果 schema 同步核心、反向 RPC、工具和真实回放断言。
+
+后续纠正:同 Host 内项目不作为操作权限墙,`allowedScopes` 按 Host 绑定;读取正文和界面打开可跨项目,
+其余操作复用原工具审批与 owner guard。默认先搜未归档,无目标再显式搜归档;不新增隐式重查逻辑。
+
+端到端覆盖补齐:App 托管的 12 个和独立 CLI 的 8 个工具逐个通过实际工具入口验证结果,沿用现有 owner、审批和持久存储。App 跨会话发送须由可信 Host 注入来源会话,随 canonical input 持久化并投影到既有气泡来源提示;恢复与手机读取保持相同来源,不能把非用户发送默认为用户亲自输入。测试先覆盖发送来源缺失回归,再修复必要接线;模型 fixture 只决定工具请求,不替代工具结果或业务状态。`ReadSession` 的正文分页从最早消息开始,以 cursor 向后读取,不能复用默认尾部窗口导致首页漏消息。
+
+按根目录 [会话控制设计](../../../../../../docs/architecture/zcode-app-control-design.md) 实施。
+独立 CLI 注册共有 8 个,App 托管 runtime 另注册 App 独有 4 个;运行位置来自可信装配,不接受模型参数切换。
+新工具是 deferred 内置工具,声明严格输入/输出 schema、searchHint、只读/副作用、权限、
+结果预算、超时与取消;沿公共 executor、ToolSearch、工具生命周期和 V4 投影处理,不新增 UI 特例。
+
+```text
+独立 CLI 的工具 → CliSessionControlPort → 本机 CLI 会话库 / 独立 CLI owner
+App 的工具     → AppControlPort → 专用反向 RPC → Host AppControlService → 原业务 owner
+                         ↓
+             @zcode/session-control 的契约、纯规则与各自用例
+```
+
+CLI/App 各自工具操作根会话,不取代 subagent Agent/SendMessage/Task 工具。来源 session、
+workspace、trace、toolCall 与权限由 runtime 注入;目标 scope 由宿主复验,不信任输入自报的
+approved/clientMode/owner。目标会话权限不继承调用者 bypass;跨会话读取属于 world-touching,
+派发执行不能声明为 protocol-only 的 `session` scope。
+
+create/send 返回接纳凭据;wait 按对应 operation 的事实收口,超时/取消只释放等待,不停止目标。
+CLI durable input 接纳后、TurnStarted 前复用 pendingCommands 发布精确 commandId;启动、拒绝、
+取消时由同一 owner 移除,避免 ACK 后空快照被误判为 unknown。该投影不接管输入队列,重启仍按丢弃事实收口。
+interrupt 校验 execution 身份;busy 排队及幂等由已有 owner 决定,新核心不保存第二份队列。
+App 控制命令的请求摘要附着于原 CommandInbox 条目,同 key 改正文/执行策略返回
+`proto.commandConflict`;issuedAt、CAS 水位及轮换鉴权不参与摘要,冷回源仅有 ACK 时不声称完整冲突核验。
+App 控制 fork 在 CLI 原子 bundle 提交前拒绝带会话批准或非 build/Plan 历史配置;普通 UI fork 保持原行为。
+App read/send 不导航,显式 open 才走 UI 导航端口。没有绑定宿主或无法确认独立 CLI owner 时
+返回明确不可用,不通过 mailbox、直接写库或重复恢复绕过。
+
+测试先覆盖核心用例与端口契约,再覆盖工具注册/曝光、权限/context 透传、真实 CLI / Host
+adapter、反向 RPC 和桌面/手机导航。独立核心测试不能替代真实 owner 路由、冷恢复和 UI E2E;
+新 case 按根目录生命周期工作流进入 pending,不自动转正。
+
+## 会话控制:回执送不回来时的重试身份,与 ListModels 的注册条件(2026-11-05)
+
+规格见根目录 [会话控制设计 0.15](../../../../../../docs/architecture/zcode-app-control-design.md)。
+
+**重试身份。** 0.14 让工具层注入 `retryOf ?? toolCallId` 作请求身份、在回执里返回,但调用在 handler
+返回之前超时或取消时没有回执,模型拿不到身份,只能另起新请求,于是重复建会话或重复发消息。链路:
+`ToolEntry.describeUnsettledCall(input, toolCallId)`(可选)→ call-runner 的执行期 `catch` → 仅对
+`ToolTimeout` 与 `ToolCancelled` 两种 CoreError 调用它 → 生成同类型新错误(复制 type、context、
+cause、stack,不改原对象)把说明追加到消息 → `createErrorResult` → 模型可见错误文本。会话控制只给
+接受 `retryOf` 的写工具声明它,说明里给出 `requestId=<id>`。其余工具不声明,行为不变。权限阶段的
+取消在 handler 之前返回,不经过这里。取消文案不再要求「用原始身份对账」。工具 schema、权限、结果
+预算不变;失败文本只在超时/取消时多一句,不影响 tools 段字节。
+
+**ListModels 注册条件。** 它不在 `DYNAMIC_WORKFLOW_TOOL_NAMES` 里(冷恢复判据 `isDynamicWorkflowToolName`
+保持不把它算作用过工作流),但注册门另加一个条件:`includeDynamicWorkflow === false` 且
+`sessionControlKind === undefined` 时跳过——此时它的两个消费者(`CreateWorkflow`、`CreateSession`)
+都不存在。会话控制在场时它不受灰度开关控制;灰度开启时照常注册。tools 段只在「灰度关 + 无会话控制」
+的会话里少一个 deferred 工具。
+
+回归:`packages/core/tests/runtime-tool-allowlist.test.ts` 覆盖 `ListModels` 在三种
+`dynamicWorkflowEnabled` 取值、有无会话控制下的注册结果(含分支刷新);`tests/session-control/`
+覆盖超时与取消时错误文本带回 `requestId`、未声明的工具不受影响。
+
 ## 插件 Agent 源文件定位(2026-10-20)
 
 `Agent` 的插件 profile 沿用组件发现结果中的实际源路径:插件目录 / manifest 目录
@@ -259,7 +502,7 @@ ToolSearch / LocalToolSearch 的共用 `Query forms` 说明明确不支持正则
 仅更新模型可见文案,沿用原搜索算法与输入结构;验证 Native / Local 最终 provider wire。
 
 Local ToolSearch 描述明确搜索后的 `DeferredToolCall {name,input}` 调用方式,只用一个简短的
-TodoWrite 调用示例说明;常驻工具仍直接调用。只经既有曝光入口更新 Local description,
+deferred 工具调用示例说明(现为 TaskStop,参数值为占位符);常驻工具仍直接调用。只经既有曝光入口更新 Local description,
 不改变 Native 文案、结果格式或执行协议。校验示例参数及 CLI/PTY 冷恢复的最终 wire,
 合同见 [模型可见文案](19-tool-search.md#模型可见文案)。
 
@@ -297,9 +540,17 @@ App Settings ToolSearch 模式:配置 schema/patch -> 本地或远程 Host 偏
 runtime-materialization -> runtimeConfig.toolSearch。只在新建/冷恢复取值,热恢复及已有草稿
 不更新;fork/子 Agent 继承。CLI 参数、工具协议/执行/历史均不变。验证 Settings UI 保存到
 最终 provider wire 的真实 E2E,及旧字段缺省、主子作用域、冷恢复与 Host 权威源。
-缺省保持 Off;设置行底部显示实验性与原生模式供应商缓存支持不足时的用量风险,中英文一致,
+缺省 Off(2026-11-05 App 缺省曾改为 Auto,2026-11-09 改回;该构建未正式发布,不迁移;
+CLI 默认 Off 始终不变);设置行底部显示实验性与原生模式供应商缓存支持不足时的用量风险,中英文一致,
 不覆盖用户已保存的模式。复用底部说明区域,验证默认关闭、说明可见与原有保存/恢复链路。
 
+常驻名单扩充(2026-11-05):TodoWrite、WebFetch、WebSearch 去掉 `shouldDefer`,成为常驻工具;
+submit_result 同样去掉 `shouldDefer`,它只在注入 `workflowSubmitPort` 的 actor 会话注册,
+所以只在 actor 会话常驻。链路:handler metadata → `isDeferredTool` 分类 → 请求曝光/公告/
+搜索目录/DeferredToolCall 准入同源变化;执行、权限、预算与 V4 投影不变。ToolSearch 描述里
+点名 TodoWrite 的两处示例都改为 TaskStop(Local 调用示例的参数值为占位符)。验证真实内置目录的首轮名单与 Desktop ToolSearch E2E。
+合同见 [19-tool-search.md](19-tool-search.md#工具和协议)。
+
 Local ToolSearch 扩展沿用 [19-tool-search.md](19-tool-search.md) 的真实引用和发现检查点。
 `--toolsearch-mode` 替代旧 enable flag;Local 将连续引用在结果内合并展开为 functions 文本,
 两次 compact 之间的 tools 不随搜索发现增长;成功 compact 后检查点工具提升为普通 tools。DeferredToolCall 使用 `{name,input}`,仅转发当前允许的 deferred
@@ -430,9 +681,9 @@ Workflow、递归闲时/定时任务和自动记忆提取的限制保留;重
 
 ## 工具内部模型请求的会话归因(2026-09-30)
 
-WebSearch、WebFetch processing、ReadSessionContext 的内部模型请求继承发起工具的宿主
+WebSearch、WebFetch processing 的内部模型请求继承发起工具的宿主
 会话类型,移除调用点的 `modelRequestSessionType: "other"`;由 runtime 模型句柄统一绑定。
-`querySource` 继续表达工具用途,ReadSessionContext 不按被读取的目标会话归因。
+`querySource` 继续表达工具用途。(原 ReadSessionContext 的抽取请求已随工具删除,2026-11-03。)
 链路为 runtime 模型句柄 → tool handler 调用上下文 → adapter → provider HTTP header;
 只调整观测分类,工具 schema、权限、执行、取消/超时、tool result、UI 与远控投递保持现状。
 覆盖 runtime 工具调用与模型边界测试,合同见根目录 Agent 模型请求归因 Header spec。
@@ -489,6 +740,8 @@ desktop continuous 与 web replayable 保持现有交付边界;2026-09-08 按
 
 ## 飞书话题原文回查
 
+2026-11-03 已删除:话题原文改由历史附件提供,资源读取改用 `ReadTopicResource`(见“删除 ReadSessionContext,新增 ReadTopicResource”)。以下为历史记录。
+
 `ReadSessionContext` 增加只读 `topic` 策略及分页 cursor。该策略强制目标为当前 session,仅从可信输入元数据读取已归档话题消息,按消息 ID 或关键词返回原文及覆盖缺口,不调用抽取模型,不把用户正文当作身份。原有 relevant/handoff 保持兼容;输出继续走统一预算、trace、tool result 持久化与 UI 投影。测试覆盖跨 session 拒绝、原文去重、分页及缺口,不用合成结果代替真实飞书验证。
 
 2026-09-22 SaveWorkflow 溯源字段:入参增加可选 `run_id`(本定义是从哪次 run 提炼出来的)。
@@ -760,6 +1013,11 @@ MCP 动态 tool 还需要额外确认:
   target 时才兜底启动 GUI emulator;`android_start_emulator` 只负责启动新的
   GUI emulator,不负责复用既有 target;复用既有真机或 emulator 时,后续
   target 类 tool 应直接传入已知 `serial`。
+- Android plugin 0.1.1 的执行链为 MCP tool → SDK 优先 / 绝对 PATH 查找 →
+  项目外真实路径校验 → 绝对路径执行,不调用 `where/which`,不裸跑 Java 或
+  Windows `cmd.exe`。显式构建仍可执行项目 Gradle wrapper;工具 schema、权限、
+  App 投影和 iOS 插件不变。Bootstrap 更新失败不得回退到漏洞版本。
+  完整边界与回归场景见 [插件兼容](../plugin-compat.md#android-tool-lookup-security-011)。
 
 ## 大内容兜底要求
 
@@ -849,6 +1107,8 @@ Browser use 虽由 `js` REPL 驱动,但其 capability manifest、模型文档
   包,走宿主注入,不要再给模型开配置工具。
 - 模型代码的 import 因此只支持 `node:*` 内置模块与基于 skill root 的绝对 `file://` URL,裸包名
   不解析。两个官方 SDK 的 bootstrap 本来就是这个形态。
+  (2026-11-09 更正:此句只对动态 `import()` 成立。`require` 由 `createRequire(cwd)` 创建,裸包名从工作区
+  `node_modules` 解析;现行规则见根目录 `docs/mcp-stateless-node-repl.md` 的 `### js`。)
 - 删除只作用于可执行路径。历史回放渲染仍依赖 `packages/shared/src/tool-identity.ts` 与
   `packages/ui/src/lib/nodeReplToolDisplay.ts` 里的名称映射:那两处只读取历史 transcript 里的
   toolName,与当前 `tools/list` 无关,删掉会让旧会话的调用块退化成 unknown fallback renderer。
@@ -1715,6 +1975,7 @@ UI/V4 投影:事件日志多一行「并发上限 8 → 2」;并发 chip 不
 V4 普通主任务审批可声明 fullAccess:同一 resolveInteraction 先取得 broker 应答权,
 原子保存任务权限和已接纳未执行队列的权限后,再允许当前工具。Runtime、Composer、
 队列各自保留 Plan;项目 ruleset/default、其他任务、用户问答与独立 workflow 确认不变。
+新投影声明自主模式选项;授权目标随同一事务写入当前会话、队列与回执。自主或完全访问实际提交成功时返回既有 `resolveInteraction.resolvedBy` 结果;未命中仍幂等成功但无授权证明。App 据此更新发起端项目的新会话权限偏好。项目归属读取失败不阻断审批。若同一 interaction 已保存另一模式,失败回执的结构化原因码标明已提交模式,UI 只允许按该模式显式重试;失败回执本身不更新 Recent。
 完整提交、失败恢复、兼容与 PA158 回归清单见根目录
 `docs/working-memory/provider-refactor/steps/todo-158-permission-dialog-full-access-and-queued-mode.md`。
 子代理请求通过父任务展示不意味着父 Runtime 拥有子 Runtime;未实现完整能力不得投放此选项。
@@ -1947,6 +2208,10 @@ botGroupSource 仅表达单条输入来源,不是调用前提;Host 唯一绑
 普通最终回复仍由 Bot 自动发送;仅用户明确要求发送/提及时使用,不能借普通文本恢复 mention 身份。
 工作区与本地/远端身份验证在 Host,群授权及投递幂等在 Bot;不新增 accepted queue。
 
+## Agent 官方插件发现与确认安装
+
+`SearchPlugins` / `SuggestPluginInstall` 经 contracts -> Core handler -> 注入的 PluginDiscoveryPort -> Bootstrap 官方目录/安装适配器;V4 pluginInstall 专用交互由 CLI 发出,桌面/手机通过 resolveInteraction 回应。UI 仅提交选择,安装继续复用 storage lock、内置恢复和 User/Workspace 启用原语。运行时是否向模型开放这两个工具取决于本次输入的可信 attachment;不从 SessionEntry 或其他订阅继承。旧订阅收到可解析的快照和增量;确认命令还要校验本连接能力。工具内部显式确认合同绕过重复通用弹窗,但 project deny/ask 和 plan 限制保留;yolo 也必须点击卡片,绝不套用 AskUserQuestion 自动结束。SearchPlugins 对官方候选使用 BM25,ToolSearch 保持原有排序。两个工具均为 deferred(`shouldDefer`),经 ToolSearch 按需加载;Session-specific guidance 暂不注入插件推荐提示。卡片实际写入后请求同一 session 安全重载:先落盘结果、排空已接纳工作,再通过现有生命周期控制器换代;旧工具结果不能把新实例标为插件 ready。连接能力逐轮校验,旧连接不会收到 pluginInstall 帧。详见 docs/plugins/agent-plugin-discovery.md。
+
 ## 脚本为每个子代理点名模型(2026-09-26)
 
 persona 可以点名子代理跑在哪个模型上:`agent(name, { model: "GLM-5.3-Flash" })`,或先用 facade 的
@@ -2137,6 +2402,10 @@ Agent / Workflow 的执行结果不被浏览器等释放异常覆盖。所属 ow
 正常后台工作结束后自动释放,主动关闭取消并等待;最终关闭依据当前资源释放结果,不重放模型执行。
 MCP 调用取消归 session,物理共享连接归 pool;详见 [生命周期](../session-runtime-lifecycle.md#关闭契约收口review-修订)。
 
+### 草稿 MCP UI 会话清理
+
+V4 `deleteSession` 复用 `closeSessionRuntime` 的统一生命周期 owner:先通知删除并摘除运行实例,再取消该 session 的 UI 工具调用、撤销实例凭证和 App tool 注册,等待 session 前缀的资源退订完成后关闭 App。按实例发起的异步退订不能代替这个等待,否则多 server 退订会与 pool lease 释放竞争。不能依赖共享 MCP 连接退出清理;其他 session 可继续持有同一连接。回归在 `v4-cold-resume.test.ts` 覆盖删除中的调用和共享连接隔离。
+
 ### 浏览器关闭路由修复(2026-10-29)
 
 Browser js → BrowserControlPort → protocol broker 登记已校验路由 → Host/Main 执行。
@@ -2153,6 +2422,14 @@ Browser control scope 的 admission 失败可由下一次业务请求用原 ID 
 只清除失败 flight。关闭优先于新 admission,不自动重放业务命令。Host ambient 无实例 ID 的
 只读 list 汇总同一会话路由的受控页面;模型 execute、取消、释放仍严格隔离实例。
 
+### 默认安装并在当前工作区启用
+
+推荐候选 → `install/workspace` 确认卡片 → 同一插件存储锁内安装并写当前工作区启用 → 校验有效启用态 → 现有安全重载。已安装时仅启用,不改用户级显式禁用及其他工作区覆盖。旧 `install/user` 确认不能被升级授权;失败不冒充已就绪。规格见根 docs/plugins/agent-plugin-discovery.md。
+
+### 插件推荐多语言载荷边界
+
+官方目录 → 共享翻译表裁剪器 → 推荐候选 → 安装交互 → 共享 schema 校验 → 持久化与 V4 投影。名称和描述分别限制语言数量、键/文本长度及 JSON UTF-8 字节数;优先保留全部支持的界面语言与默认文本。协议采用同一组上限,超限原始字段不得进入交互事件;确认、启用和自动 reload 不变。见根 docs/plugins/agent-plugin-discovery.md「多语言载荷边界」。
+
 ### 草稿 MCP UI 会话清理
 
 V4 `deleteSession` 复用 `closeSessionRuntime` 的统一生命周期 owner:先通知删除并摘除运行实例,再取消该 session 的 UI 工具调用、撤销实例凭证和 App tool 注册,等待 session 前缀的资源退订完成后关闭 App。按实例发起的异步退订不能代替这个等待,否则多 server 退订会与 pool lease 释放竞争。不能依赖共享 MCP 连接退出清理;其他 session 可继续持有同一连接。回归在 `v4-cold-resume.test.ts` 覆盖删除中的调用和共享连接隔离。
@@ -2168,3 +2445,30 @@ stdio stderr → adapter 有界缓冲与脱敏 → 已有 `McpServerStatus.error
 界面处理建议只按已有 `failureKind` 国际化,不按错误文本分流;`tools/call`、工具结果、
 权限、重试和错误分类不变。展示契约见根 `docs/settings-mcp-list.md`,CLI 回归在
 `packages/adapters/tests/mcp.test.ts`,App 使用候选 E2E,不恢复业务单测。
+
+## MCP App 授权失败的错误类型(2026-11-05)
+
+`ToolExecutor.authorizeAppTool` 是宿主发起的插件工具调用(`mcp/uiCallTool` 与 `plugins/mentionItems`)
+共用的授权链:schema 校验 → PreToolUse hook → 权限规则 / 审批。失败时改为抛 `CoreError`,保留稳定类型,
+调用方按 `type` 分支,不读错误文本:
+
+| 失败                                     | `type`                                                                                |
+| ---------------------------------------- | ------------------------------------------------------------------------------------- |
+| 输入不合工具 schema(含 hook 改写后)    | `invalid_input`                                                                       |
+| hook 拒绝或要求停止                      | `permission_denied`                                                                   |
+| 权限拒绝(deny 规则、用户拒绝)          | `permission_denied`(沿用执行器的拒绝结果类型)                                       |
+| 其他未放行(取消、升级、规则加载失败等) | 执行器结果里的原类型(如 `tool_cancelled`、`permission_escalation`、`storage_error`) |
+
+链路:宿主调用 → session facade `callMcpToolForUi` → `authorizeAppTool` → 连接代际复验 → `McpPort.callTool`。
+错误信息文本不变;`mcp/uiCallTool` 的协议错误按现有 `toProtocolError` 规则多带 `data.code`(大写的 CoreError code),
+页面不依赖它。工具 schema、权限判定、审批事件、hook、tools 段字节与 UI/V4 投影都不变;
+`plugins/mentionItems` 把 `permission_denied` 映射为 `plugin_mention_tool_denied`(见 [插件兼容](../plugin-compat.md#composer-mention-items))。
+回归:`packages/core/tests/app-tool-authorization.test.ts`(放行、用户拒绝、deny 规则、输入不合 schema)。
+
+## Bash 摘要描述(2026-11-04)
+
+已有可选 input.description 经 V4 input 原样进入 UI;执行摘要优先显示非空描述,缺失时显示命令。独立行、组内子项与活动组头共用 Execute renderer;展开后摘要继续显示非空 description,详情保留命令和输出;权限详情保持实际命令。只修改 UI 展示,不改 schema、执行、权限、事件或持久化。验收见根 docs/ui/tool-display-rendering.md 的 Bash 调用描述与浏览器分组候选。
+
+## legacy 会话事件剥掉后加的字段(2026-11-06)
+
+legacy v1 的 `session/events` 由 `bootstrap/src/zcode-protocol/session-mapper.ts` 整体 spread CLI 事件的 payload,App 侧是 strict schema,整页 `safeParse`。后加到 CLI 事件里、legacy schema 没有声明的字段要在 mapper 里剥掉,不改 App 的 schema(已经装出去的旧桌面同样会整页失败)。这次补上两处:`ToolCallStarted` 的 `readOnly`、`sideEffectScope`(解析后的副作用能力,只给 core 与 dynamic-workflow 用),`PermissionRequested` 的 `fullAccessSupported`(只给 v4 的审批)。漏掉时的后果:App 的 `readSession(view: "summary")` 经事件读 `executionId`,调用过工具、正在运行的会话报 ZodError,中断不了(2026-11-06 PLM-JARVIS-2 的运行时证据;示例插件 Jarvis 已迁出到市场仓库,那个 E2E 已删除)。回归由 `bootstrap/tests/session-mapper-legacy-strip.test.ts` 守住。以后给工具或权限事件加字段,同时决定 legacy mapper 要不要剥。

+ 27 - 0
apps/zcode-cli/docs/design/v2/tool/04-bash.md

@@ -169,6 +169,14 @@ ZCode 应把 shell permission 拆成三个层次:
 
 ### read-only Bash allowlist
 
+运行时明确选择 `cmd` 或 `legacy-shell` 时,Bash AST 不能证明实际命令只读:例如
+`type # & python script.py` 在 Bash AST 中只剩 `type`,CMD 却仍执行后面的 Python。
+这两种 shell 不授予只读免审批,也不使用 Bash AST 推导 prefix/wildcard allow;建议授权只保存
+完整命令。Build/Edit 默认请求审批,Plan 拒绝(完整命令 allow 也不能越过 Plan)。完整命令和
+工具级明确授权、yolo/guarded、已有 deny/ask 匹配保留。此最小修复不增加 CMD 解析能力,
+CMD 子命令 deny 匹配仍有原有语法边界;POSIX/Git Bash 及未传 selection 的旧内部调用不变。
+`ToolCallStarted` 的副作用能力必须携带同一 shell 上下文计算,避免将经审批的 CMD 再标成只读。
+
 `Bash` 只有在 AST 可安全解析、每条 simple command 的参数、赋值和重定向均通过
 readonly policy,且没有 command substitution 等不支持的动态结构时,才会把运行时 capability 降级为
 `readOnly=true`、`sideEffectScope="none"`、`riskLevel="low"`、`needsApproval=false`。
@@ -324,6 +332,25 @@ background commit 由 execution adapter 内的 Bash lifecycle 持有。commit 
 - adapter 应优先走结构化 cancel/terminate 路径,再 fallback 到平台相关的进程树 kill;不能只丢弃内部引用,留下 detached shell 继续运行。
 - Bugfix 记录:POSIX 上 `ExecutionPort` 使用 detached spawn / 独立进程组是为了能通过负 PID 终止整棵命令进程树;如果 CLI 在没有 signal cleanup 的路径中退出,OS 不会自动杀掉该进程组,`npm dev`、Vite、Node server 等长跑子进程会继续存活。因此 `detached` 必须和全局 shutdown cleanup 成对出现。
 
+### 子进程诊断日志
+
+系统侧记录(任务管理器、Windows 资源耗尽事件 2004 等)只认 pid。为了把占用内存或 CPU 的
+进程对回具体的工具调用,Bash 在 CLI 日志里按 info 级写两条结构化记录:
+
+| event                              | 写入时机                       | 字段                                                                        |
+| ---------------------------------- | ------------------------------ | --------------------------------------------------------------------------- |
+| `tool.bash.process.started`        | 子进程 spawn 后(前台和后台)  | `toolCallId`、`pid`、`runInBackground`                                      |
+| `tool.bash.process.exited`         | 前台命令结束                   | `toolCallId`、`pid`、`exitCode`、`signal`、`durationMs`、`executionStatus`、`timedOut`、`cancelled` |
+| `background_task.tracking.terminal` | 已转后台的命令结束(既有日志) | 在既有字段上补 `toolCallId`、`pid`、`exitCode`、`signal`、`durationMs`      |
+
+pid 是 adapter spawn 的根进程:POSIX 上是 `-c` 启动的 shell(也是进程组 id);Windows 上是
+Git Bash 的 `bash.exe` 或 `cmd.exe` 外壳,命令本身是它的子孙进程,需要按进程树对应。
+日志不写命令文本,命令仍只在 trace/transcript 中。
+
+显式后台(`run_in_background: true`)时,adapter 在 `started` 事件里就提交后台,之后
+不再把事件转发给 handler,所以这条启动日志由 handler 在拿到 `backgrounded` 结果后用
+`task.pid` 补写;`auto_on_timeout` 在前台阶段已收到 `started`,同一次调用只写一条。
+
 ## 分阶段目标
 
 ZCode 的 Bash v2 按本项目的 `ExecutionPort`、session event、permission service 和 adapter 边界重写。禁止让 `BashTool` 直接持有子进程、文件描述符、terminal 状态或权限规则实现。

+ 1 - 1
apps/zcode-cli/docs/design/v2/tool/05-webfetch.md

@@ -242,7 +242,7 @@ ZCode 如果支持 WebFetch 摘要,也应把版权和引用限制放在 `WebFe
 - `packages/core/tests/permission-service.test.ts` 覆盖 WebFetch project rule 使用规范化 `domain:<hostname>` 匹配,以及 domain deny 覆盖完整 URL allow。
 - `packages/core/tests/tool-contracts.test.ts` 覆盖 WebFetch tool contract 声明为 `sideEffectScope: network` 且需要审批。
 - `packages/adapters/tests/http.test.ts` 覆盖 `HttpClientPort` trace header、`ZCODE_HTTP_PROXY`、runtime 封存代理、`network.noProxy`、`ZCODE_AGENT_CA_CERT`、标准代理/证书变量过滤、响应大小上限和 unsupported protocol;`packages/adapters/tests/http-response-status.test.ts` 覆盖走代理时上游回 `999` / `204` / `304` 原样带回、不打死进程。
-- `packages/desktop/test/e2e/conversation-session/conversation-session-webfetch.test.ts`
+- `packages/desktop/test/e2e/conversation-session/tools/conversation-session-webfetch.test.ts`
   保留桌面会话 `WebFetch` 成功闭环用例,但当前位于 `manual-review/pending`,不能计入正式自动覆盖。
   fixture 仍位于 `packages/desktop/test/e2e/fixtures/cases/conversation-session/conversation-session-webfetch.json`。
 

+ 15 - 12
apps/zcode-cli/docs/design/v2/tool/07-subagent-background-plan.md

@@ -73,16 +73,16 @@ run_in_background?: boolean
 `AgentOutput` 扩展为 union:
 
 ```ts
-type AgentOutput = AgentCompletedOutput | AgentBackgroundedOutput
+type AgentOutput = AgentCompletedOutput | AgentBackgroundedOutput;
 
 interface AgentBackgroundedOutput {
-  status: "backgrounded"
-  agentId: string
-  agentType: "Explore"
-  description: string
-  prompt: string
-  childSessionId: SessionId
-  backgroundTaskId: string
+  status: "backgrounded";
+  agentId: string;
+  agentType: "Explore";
+  description: string;
+  prompt: string;
+  childSessionId: SessionId;
+  backgroundTaskId: string;
 }
 ```
 
@@ -97,9 +97,12 @@ interface AgentBackgroundedOutput {
 
 ```ts
 interface SubagentPort {
-  run(request: SubagentRunRequest, options?: SubagentRunOptions): Promise<AgentOutput>
-  start?(request: SubagentStartRequest, options?: SubagentStartOptions): Promise<AgentBackgroundedOutput>
-  getTask?(agentId: string): Promise<SubagentTaskSnapshot | undefined>
+  run(request: SubagentRunRequest, options?: SubagentRunOptions): Promise<AgentOutput>;
+  start?(
+    request: SubagentStartRequest,
+    options?: SubagentStartOptions,
+  ): Promise<AgentBackgroundedOutput>;
+  getTask?(agentId: string): Promise<SubagentTaskSnapshot | undefined>;
 }
 ```
 
@@ -128,7 +131,7 @@ interface SubagentPort {
   复制 child transcript。
 - `RespondToCoordinator` 是明确的后续例外:response command 被 parent drain 后,parent session
   保存完整 coordinator response carrier,用于当前投递、hydrate/resume 和后续父模型上下文连续性。
-  它不会进入顶层用户消息列表、session title 或 `ReadSessionContext`,但读取原始 session store
+  它不会进入顶层用户消息列表、session title 或 `ReadSession` 的读取结果,但读取原始 session store
   的导出、诊断和存储预算必须按可能包含完整内容处理;compact 也可能把其语义吸收到摘要中。
 - 所有事件继承同一个 `traceId`,并记录 parent `sessionId`、`turnId`、`toolCallId`、child `sessionId`、`agentId`。
 

+ 219 - 79
apps/zcode-cli/docs/design/v2/tool/07-subagent.md

@@ -6,14 +6,14 @@
 
 `Agent` 不是一个普通函数调用,而是一个小型 agent runtime 入口。它根据输入选择一种执行形态:
 
-| 形态 | 触发条件 | 说明 |
-| --- | --- | --- |
-| fresh subagent | 指定 `subagent_type`,或未启用 fork 时省略 `subagent_type` | 新建独立 agent 对话,只拿到本次 `prompt` 和该 agent 自己的 system prompt |
-| fork subagent | fork gate 开启且省略 `subagent_type` | 子 agent 继承父会话历史、system prompt 和精确 tool pool,用于 prompt cache 共享 |
-| background subagent | `run_in_background`、agent 定义 `background: true`、coordinator、assistant mode、fork gate 或 proactive 强制 | 立即返回 task 引用,完成后以通知重新进入主会话 |
-| worktree subagent | `isolation: "worktree"` 或 agent 定义自带 worktree isolation | 在临时 git worktree 中运行,完成后无变更自动清理,有变更保留路径和 branch |
-| remote agent | `isolation: "remote"` | 远程环境执行;ZCode 当前不支持 |
-| teammate spawn | `team_name` 和 `name` 同时存在 | 这是 agent team/swarm,不是普通 subagent,应作为独立工具或独立模式处理 |
+| 形态                | 触发条件                                                                                                     | 说明                                                                            |
+| ------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- |
+| fresh subagent      | 指定 `subagent_type`,或未启用 fork 时省略 `subagent_type`                                                   | 新建独立 agent 对话,只拿到本次 `prompt` 和该 agent 自己的 system prompt        |
+| fork subagent       | fork gate 开启且省略 `subagent_type`                                                                         | 子 agent 继承父会话历史、system prompt 和精确 tool pool,用于 prompt cache 共享 |
+| background subagent | `run_in_background`、agent 定义 `background: true`、coordinator、assistant mode、fork gate 或 proactive 强制 | 立即返回 task 引用,完成后以通知重新进入主会话                                  |
+| worktree subagent   | `isolation: "worktree"` 或 agent 定义自带 worktree isolation                                                 | 在临时 git worktree 中运行,完成后无变更自动清理,有变更保留路径和 branch       |
+| remote agent        | `isolation: "remote"`                                                                                        | 远程环境执行;ZCode 当前不支持                                                  |
+| teammate spawn      | `team_name` 和 `name` 同时存在                                                                               | 这是 agent team/swarm,不是普通 subagent,应作为独立工具或独立模式处理          |
 
 关键边界:普通 subagent 不是 OS 子进程,而是在同一进程内创建新的子执行上下文,再运行新的 query loop。外部进程、tmux、in-process teammate 和 remote agent 属于 agent team 或 remote task 分支,不应和普通 subagent 混成一个概念。
 
@@ -21,12 +21,12 @@
 
 模型可见基础输入:
 
-| 字段 | 类型 | 必填 | 说明 |
-| --- | --- | --- | --- |
-| `description` | `string` | 是 | 3 到 5 个词的短描述,用于 UI、task 状态、activity 文案 |
-| `prompt` | `string` | 是 | 给子 agent 的任务正文 |
-| `subagent_type` | `string` | 否 | 要使用的 agent 类型。fork gate 关闭时省略则默认为 `general-purpose`,开启时省略则触发 fork |
-| `run_in_background` | `boolean` | 否 | 请求后台运行。后台任务禁用或 fork gate 开启时 schema 会隐藏该字段 |
+| 字段                | 类型      | 必填 | 说明                                                                                       |
+| ------------------- | --------- | ---- | ------------------------------------------------------------------------------------------ |
+| `description`       | `string`  | 是   | 3 到 5 个词的短描述,用于 UI、task 状态、activity 文案                                     |
+| `prompt`            | `string`  | 是   | 给子 agent 的任务正文                                                                      |
+| `subagent_type`     | `string`  | 否   | 要使用的 agent 类型。fork gate 关闭时省略则默认为 `general-purpose`,开启时省略则触发 fork |
+| `run_in_background` | `boolean` | 否   | 请求后台运行。后台任务禁用或 fork gate 开启时 schema 会隐藏该字段                          |
 
 `Agent` 模型可见输入不包含 invocation 级 `model` 覆盖。旧 transcript 可以保留历史
 `model` 字段,但当前输入 schema 会忽略该字段;child runtime 只消费 Settings 或 Markdown
@@ -34,13 +34,13 @@
 
 扩展输入:
 
-| 字段 | 类型 | 适用范围 | 说明 |
-| --- | --- | --- | --- |
-| `name` | `string` | background subagent 或 teammate | 给 spawned agent 起可寻址名称。background subagent 可通过 `SendMessage({ to: name })` 继续 |
-| `team_name` | `string` | agent team | 与 `name` 一起触发 teammate spawn。省略时可使用当前 team context |
-| `mode` | permission mode | agent team | 主要用于 spawned teammate,例如 `plan` 模式。普通 subagent 不应把它当作子 agent permission override |
-| `isolation` | `"worktree" \| "remote"` | subagent | `worktree` 创建临时 git worktree。`remote` 当前不支持 |
-| `cwd` | `string` | gated | 让子 agent 在指定 cwd 中运行。要求绝对路径,并且与 `isolation: "worktree"` 互斥 |
+| 字段        | 类型                     | 适用范围                        | 说明                                                                                                |
+| ----------- | ------------------------ | ------------------------------- | --------------------------------------------------------------------------------------------------- |
+| `name`      | `string`                 | background subagent 或 teammate | 给 spawned agent 起可寻址名称。background subagent 可通过 `SendMessage({ to: name })` 继续          |
+| `team_name` | `string`                 | agent team                      | 与 `name` 一起触发 teammate spawn。省略时可使用当前 team context                                    |
+| `mode`      | permission mode          | agent team                      | 主要用于 spawned teammate,例如 `plan` 模式。普通 subagent 不应把它当作子 agent permission override |
+| `isolation` | `"worktree" \| "remote"` | subagent                        | `worktree` 创建临时 git worktree。`remote` 当前不支持                                               |
+| `cwd`       | `string`                 | gated                           | 让子 agent 在指定 cwd 中运行。要求绝对路径,并且与 `isolation: "worktree"` 互斥                     |
 
 ZCode 需要把 schema gating 做成能力协商结果,而不是在 tool 内散落 feature flag。`cwd` 的绝对路径和与 worktree 的互斥关系也应进入 `validateInput`,不能只放在 prompt description。
 
@@ -48,48 +48,185 @@ ZCode 需要把 schema gating 做成能力协商结果,而不是在 tool 内
 
 公开 output schema 主要有两类:
 
-| `status` | 字段 | 说明 |
-| --- | --- | --- |
-| `completed` | `prompt` 加 `agentToolResultSchema` | 同步完成,返回子 agent 最终文本、usage、tool use 数、耗时和 `agentId` |
-| `async_launched` | `agentId`、`description`、`prompt`、`outputFile`、`canReadOutputFile` | 后台启动成功,结果稍后通过 task notification 返回 |
+| `status`         | 字段                                                                  | 说明                                                                  |
+| ---------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- |
+| `completed`      | `prompt` 加 `agentToolResultSchema`                                   | 同步完成,返回子 agent 最终文本、usage、tool use 数、耗时和 `agentId` |
+| `async_launched` | `agentId`、`description`、`prompt`、`outputFile`、`canReadOutputFile` | 后台启动成功,结果稍后通过 task notification 返回                     |
 
 内部还有两个分支:
 
-| `status` | 说明 |
-| --- | --- |
-| `teammate_spawned` | team/swarm 分支,返回 teammate id、name、team、pane 等信息 |
-| `remote_launched` | remote 分支,返回 remote task id、session URL 和 output file |
+| `status`           | 说明                                                         |
+| ------------------ | ------------------------------------------------------------ |
+| `teammate_spawned` | team/swarm 分支,返回 teammate id、name、team、pane 等信息   |
+| `remote_launched`  | remote 分支,返回 remote task id、session URL 和 output file |
 
 `agentToolResultSchema`:
 
-| 字段 | 类型 | 说明 |
-| --- | --- | --- |
-| `agentId` | `string` | 子 agent ID,也是 transcript/task/output 的关联键 |
-| `agentType` | `string?` | agent 类型。用于 one-shot 内建 agent 跳过 continuation trailer |
-| `content` | `{ type: "text"; text: string }[]` | 子 agent 最终文本块 |
-| `totalToolUseCount` | `number` | 子 agent 内部 tool use 总数 |
-| `totalDurationMs` | `number` | 总耗时 |
-| `totalTokens` | `number` | 最后一条 assistant usage 汇总出的 token 数 |
-| `usage` | provider usage object | input、output、cache、server tool use、service tier 等 |
+| 字段                | 类型                               | 说明                                                           |
+| ------------------- | ---------------------------------- | -------------------------------------------------------------- |
+| `agentId`           | `string`                           | 子 agent ID,也是 transcript/task/output 的关联键              |
+| `agentType`         | `string?`                          | agent 类型。用于 one-shot 内建 agent 跳过 continuation trailer |
+| `content`           | `{ type: "text"; text: string }[]` | 子 agent 最终文本块                                            |
+| `totalToolUseCount` | `number`                           | 子 agent 内部 tool use 总数                                    |
+| `totalDurationMs`   | `number`                           | 总耗时                                                         |
+| `totalTokens`       | `number`                           | 最后一条 assistant usage 汇总出的 token 数                     |
+| `usage`             | provider usage object              | input、output、cache、server tool use、service tier 等         |
 
 模型可见序列化不是原样 JSON:
 
 - 同步完成时把 `content` 直接交给父 agent,再追加 `agentId` 和 `<usage>` trailer。`agentId` 行:
   `(use SendMessage with to: '<id>', summary: '<5-10 word recap>' to continue this agent)`。usage 缺失时不输出 `subagent_tokens` 行。
 - `Explore` 可以用 SendMessage 继续,所以同步结果同样带 `agentId` 和 usage trailer。
-- 同步报告:先输出 `[Subagent hand-back]` 说明段(报告是模型输出,不代表用户授权),再输出报告;报告先把 `\r\n`、`\r`、`\u2028` 等换行变体统一成 `\n`,再逐行缩进两格,报告里顶格的伪造框架行因此可以识别。空报告用 "(Subagent completed but returned no output.)",同样套框架。框架只按返回路径决定:后台运行(含前台超时转后台)完成时,task-notification 的 `<result>` 是原始报告,不套框架、不缩进;默认前台还是后台不影响这条规则。这段文本只给模型:父对话里的 Agent 卡片只有单行摘要、不展开,过程和输出从右侧 tab / 手机抽屉按 child session 查看,所以框架前缀不出现在界面上。
+- 同步报告:先输出 `[Subagent hand-back]` 说明段(报告是模型输出,不代表用户授权),再输出报告;报告先把 `\r\n`、`\r`、`\u2028` 等换行变体统一成 `\n`,再逐行缩进两格,报告里顶格的伪造框架行因此可以识别。报告取子代理本次运行最后一个模型 step 的正文;最后一步正文为空时,倒序取本次运行里最近一个正文非空的 step(报告常写在带工具调用的那一步,最后一步只回空正文,或在 Stop hook、guide 续跑后回空),只取正文,不取 reasoning。step 只指子代理自己主循环的模型请求(`querySource: "subagent"` 的 `ModelComplete`);压缩、goal 校验、标题生成等 sidecar 请求也写 `ModelComplete`,但不算 step,所以轮中压缩的摘要不会被当成报告,压缩前写的报告仍能取到。所有 step 都没有正文时才用 "(Subagent completed but returned no output.)",同样套框架。前台结果与后台通知用同一份报告。框架只按返回路径决定:后台运行(含前台超时转后台)完成时,task-notification 的 `<result>` 是原始报告,不套框架、不缩进;默认前台还是后台不影响这条规则。这段文本只给模型:父对话里的 Agent 卡片只有单行摘要、不展开,过程和输出从右侧 tab / 手机抽屉按 child session 查看,所以框架前缀不出现在界面上。
+- 同步失败:子代理已经开始运行、runner 已把 task 记为 failed 之后报错时,Agent 工具调用仍是失败,卡片仍显示"执行失败",`error.message`、`code`、`detail` 与 hover 仍只有 provider 原文。只给模型的错误文本在原文之后空一行追加三段:
+  1. 本次运行有正文时,先写截断说明 `Everything below is PARTIAL output recovered from the agent before it was cut off. The agent did NOT finish its task — treat these results as incomplete.`,再写部分报告。部分报告按"同步报告"的规则从本次运行 `querySource: "subagent"` 的 `ModelComplete` 倒序取最近一段非空正文,同样套 `[Subagent hand-back]` 框架;超过 1 万字符时只保留头尾。本次运行没有正文时不写这一段。
+  2. 与同步完成相同的 `agentId` 行,父模型可以用 SendMessage 续接这个子代理。
+  3. `<usage>` trailer:`subagent_tokens` 与同步完成同一口径,累加本次运行 `ModelComplete` 和已计费的失败请求(`model_request_failed`)的 usage,都没有时不输出;`tool_uses` 是本次运行各 step 请求的工具调用数之和;`duration_ms` 是到失败为止的耗时。只认本 child session 的事件,event sink 转发的其他 session 事件不算。
+
+  是否追加与错误类型无关:工具调用状态保持失败,原文仍在第一行,所以不按限流、过载等类型筛选。子代理启动前失败(child session 未就绪、task 已撤销)或被停止(killed)时不追加;写失败产物或发出 `SubagentStopped` 本身出错时,抛出的是那个 I/O 错误,也不追加;父 turn 被取消时,执行器自己的取消结果先生效,同样不追加。交接数据作为不可枚举属性直接加在原错误上,不复制错误,错误身份与 stack 不变。部分报告不进入错误的 `context`,所以不写进日志;这段文本随 tool part 的 `metadata.modelContent` 持久化,冷恢复后原样重放,bootstrap `message-mapper` 发给 App 前会剥掉它,界面上不出现。后台运行(含前台转后台、SendMessage 续接)失败时,失败通知的 `<result>` 按同一规则带部分报告,见下文「后台终态通知」。
+
 - 后台启动文案:首行带 "(This tool result is internal metadata — never quote or paste any part of it, including the agentId below, into a user-facing reply.)",第三行说明结果到达前不得报告或猜测;无 output file 时以 "In your own words, briefly tell the user what you launched — do not echo this tool result. …" 结尾。有 output file 时给出 `output_file` 和不读取提示;提示不提 transcript,因为输出文件是子代理输出文本,不是 JSONL transcript。只有父 agent 拥有 `Read` 或 `Bash` 时才提示 output file。App 按 "Async agent launched successfully." 前缀等四个片段识别后台启动,新文案仍满足。
 - 后台终态通知(`<task-notification>`):每个字段单独一行,顺序是 `task-id`、`tool-use-id`、`output-file`、`status`、`summary`、`note`、`result`、`usage`。只转义 `& < >`,引号和撇号原样保留。
   - `status` 只有 `completed`、`failed`、`killed` 三个值。
   - summary:completed 是 `Agent "<description>" finished`;failed 是 `Agent "<description>" failed: <原因>`,原因为空或只有空白时写 `Unknown error`(结构化 error 相同);killed 按停止者区分:模型用 TaskStop 停止是 `Agent "<description>" was stopped by ZCode`,用户在 App 里停止是 `… was stopped by user`,系统停止(rewind、闲时任务收尾等)是 `… was stopped`。
   - `<note>` 每条都有,固定文字:`A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.` child 结束时封存自己的后台通知,不会自己恢复,所以 completed 且还有后台子任务时也用这一句。
-  - `<result>` 只在 completed 时出现,内容是原始报告。failed 和 killed 不带 `<result>`(暂不采集子 agent 已输出的部分文字)。
+  - `<result>`:completed 时是原始报告。failed 时是本次运行的部分报告:按"同步报告"的规则取本次运行最近一段非空 step 正文,与同步失败取同一段,但不套框架、不加截断说明;本次运行没有正文时不带 `<result>`。killed 不带 `<result>`。`task-id` 就是 agentId,父模型可以据此用 SendMessage 续接失败的子代理。
   - `<usage>` 只在 completed 时出现:`<usage><subagent_tokens>N</subagent_tokens><tool_uses>N</tool_uses><duration_ms>N</duration_ms></usage>`,缺的字段不输出。
-  - 不再输出 `<error>`。终态和失败原因另由通知命令的 `originMeta.subagentResult`(`{ status, error? }`,error 只在 failed 时出现,与 summary 里的原因同一字符串;超过 2000 字符时截到 2000 字符并以 `…` 结尾,summary 不截断)结构化下发,随通知消息的 metadata 持久化。App 读状态和失败原因以它为准,不解析 summary;旧会话没有它,读 `<status>` / `<error>`。多条通知合并成一轮时,合成的 originMeta 只保留基字段,不带 subagentResult,失败详情退回该任务自己的整句 summary。App 按 `<task-notification>` 块逐条解析:每块只读块内的标签,按各自的 `tool-use-id` 更新对应的行;只有一个块时才使用 `originMeta.subagentResult`。跨块读取会把下一条通知的 `<result>` 当成前一条失败任务的原因,后面的任务也得不到终态。
+  - 不再输出 `<error>`。终态和失败原因另由通知命令的 `originMeta.subagentResult`(`{ status, error? }`,error 只在 failed 时出现,与 summary 里的原因同一字符串;超过 2000 字符时截到 2000 字符并以 `…` 结尾,summary 不截断)结构化下发,随通知消息的 metadata 持久化。App 读状态和失败原因以它为准,不解析 summary;旧会话没有它,读 `<status>` / `<error>`。多条通知合并成一轮时,合成的 originMeta 只保留基字段,不带 subagentResult,失败详情退回该任务自己的整句 summary。App 按 `<task-notification>` 块逐条解析:每块只读块内的标签,按各自的 `tool-use-id` 更新对应的行;只有一个块时才使用 `originMeta.subagentResult`。跨块读取会把下一条通知的 `<result>` 当成前一条失败任务的原因,后面的任务也得不到终态。failed 且带 `<note>` 的块(只有 local agent 通知带 `<note>`),App 解析时丢弃 `<result>`:它是只给模型的部分报告;合并轮没有结构化 error,App 的失败原因会依次退到 `result`,不丢弃时卡片 output 和失败 hover 显示的是半截正文,而不是 summary 里的失败原因。workflow 失败通知不带 `<note>`,它的 `<result>` 照常读取。
   - 整条通知超过 120 000 字符时截断(防止单条通知过长)。
 - remote 启动时提示父 agent 简短告知用户已启动,然后结束本轮。
 - 子 agent 的结果不会自动展示给最终用户,父 agent 必须负责总结或继续执行。
 
+### 胶囊单项停止
+
+父会话胶囊的前台与后台运行项共用 `stopSubagent` 命令,不改变模型可见的 Agent 或
+TaskStop 工具 schema。runner 发布 child 已持久化后的启动事件时携带可停止的真实 task
+身份及每次执行新建的 `executionId`;V4 `subagents.running.stopControl` 仅在当前 runtime 有
+单项停止能力时提供 `{ taskId, executionId }`,冷恢复、失效、结束时移除。App 不从
+`agentId` 或 `backgroundWorks` 猜测能力。命令在父 runtime 校验归属、运行态和执行实例,
+并在停止提交前再校验一次,防止迟到的 Stop 停止同一 agentId 经 SendMessage 恢复的新执行。
+无能力、无目标、身份不匹配或已终结均明确拒绝。
+
+停止按 task 原有控制器取消,并先确定唯一终态:前台只经原 Agent 工具调用返回停止
+结果,不入后台通知队列、不把 stopped 覆写为 failed;后台继续发 killed 通知和
+SubagentStopped(stopped)。自然完成与停止竞争只能由先提交的一方生效;其他并行 child
+和父执行不受影响。桌面 continuous 与手机 replayable 共享同一 V4 能力投影和父 runtime 门禁。
+
+### 后台 Agent 无进展提醒
+
+原则:运行时只负责「发现并报告」,停掉还是继续等由主代理决定,不做一刀切的超时。主代理结束回合、
+空闲等通知时,否则没有任何渠道发现后台 Agent 卡住。
+
+- 进展:child 的新模型请求或回复、工具调用开始或结束、审批结束。Bash 每秒的 `ToolCallProgress`
+  心跳不算(卡死的命令也在发心跳),流式 token 不单独算(模型流有自己的 idle timeout)。
+  等待用户审批期间不提醒(在等人,界面上已可见)。审批按工具调用计:并行工具组里多个审批同时挂起时,
+  要全部结束(批准、拒绝,或该工具调用以结果/错误结束)才恢复计时。审批请求的发布可能晚于超时、
+  取消后的结束事件:已结束的审批(按 requestId)或工具调用(按 toolCallId)再收到迟到的
+  `PermissionRequested` 时不再挂起。child 事件按所属执行(`executionId`)归属:SendMessage 恢复成新
+  执行后,旧执行的迟到事件不改写新执行的活动快照。
+- 状态:进展事实只写在 `RuntimeTaskRegistry` 的 local_agent 快照上(`activity`:最后进展时间、
+  在途工具及一行摘要、等审批的工具调用,`waitingForPermission` 由它派生),由父 runtime 的 child
+  event sink 写入。停滞钟
+  (`subagent/background-stall.ts`)只持有每个 Agent 的提醒次数,其余从快照派生,registry 变化时
+  对齐唯一的定时器。
+- 节奏:无进展 15 分钟首次提醒;主代理不停止它(即「继续等待」)时,下一次间隔加倍:30 分钟、
+  60 分钟……上限 4 小时。有新进展后计数清零,回到 15 分钟。Agent 结束或会话关闭后不再提醒。
+  `RuntimeConfig.subagents.backgroundStallNotifyMs` / `backgroundStallMaxIntervalMs` 可覆盖。
+- 开发验收用环境变量 `ZCODE_SUBAGENT_STALL_NOTIFY_MS`(bootstrap 读取,只改首次阈值,毫秒):
+  - 优先级低于 `runtimeConfig.subagents.backgroundStallNotifyMs`;
+  - 不是纯数字或 ≤ 0 时不生效,用默认 15 分钟;
+  - 低于 10 秒按 10 秒:每次提醒都会在父会话空闲时开一轮模型调用,间隔从极小值加倍要几十轮才到
+    分钟级,误设会在短时间内产生大量模型请求;
+  - 很大的值(例如想借它「关掉」提醒)照样生效。`setTimeout` 最多只能等 2^31-1 ms(约 24.8 天),
+    超过时 Node 会改成 1 ms;停滞钟每段最多等这么久,到点先判断是否真的到期,没到就再排下一段,
+    不会变成忙循环。`runtimeConfig` 传入的值同样适用;
+  - 生效值记在 runtime 配置日志的 `subagentStallNotifyMs`。
+- 投递:与终态通知同一条后台通知队列(`enqueueBackgroundTaskNotification`):父会话空闲时开一个
+  model-only 新回合,正忙时在回合内插入。`originMeta` 为 `backgroundSource=subagent`、`workId=agentId`、
+  标题「<描述> — no progress for N min」,不带 `subagentResult`,因此不改变 Agent 卡片状态;新增的
+  `subagentStall` 键只供 CLI 把提醒排除在「消费了后台 Agent 结果」的埋点之外,App schema 会剥掉它:
+  - 回合的 `backgroundSource`(App 据此记 `message_source`)只看批内的真实结果;只有提醒的一轮不带
+    来源,不记成 `background_subagent`;
+  - 同批有其它 Agent 的终态通知时,`<task-notification>` 排在提醒前面:App 与 V4 只在整段输入以
+    `<task-notification>` 开头时逐条解析终态并更新工具行。这一轮的标题和代表任务(`workId`)按同一
+    顺序取,标题先列结束的 Agent;
+  - 出队时提醒已不成立就丢弃:Agent 已结束、生成提醒后有了新进展、正在等审批,或已被 SendMessage
+    恢复成新执行(`subagentStall` 带生成时的 `lastProgressAt` 与 `executionId`,出队时对比)。父会话
+    正忙时提醒要排队到回合结束,这期间情况可能已经变了;模型不会读到过时的「无进展」。
+    丢弃的提醒(以及 sealed 子会话里被丢弃的后台 Bash 通知)在 session input 账本里结算为
+    `discarded`,等入账写完再结算;否则残留的 `admitted` 会让会话常驻池一直认为有未处理输入,
+    挡住空闲时的插件自动重载。
+  - 恢复时的上一代对账(下一节)只认 `<task-notification>` 块里的 task-id:收到过提醒、随后随进程
+    崩溃的 Agent 仍然报中断。
+- 正文(description、工具名与摘要在 XML 块和说明里都按 XML 转义;描述单行、限 200 字,轮标题同此;
+  在途工具最多列 5 个,其余只给个数;整条按标准通知上限截断):系统通知横幅 + `<background-agent-stall>` 块(task-id、描述、已运行与无进展时长、最后进展
+  时间、在途工具及摘要、下次报告时间)+ 说明。刻意不用 `<task-notification>`:App 把带
+  tool-use-id 的该标签读成 Agent 终态,未知 status 会落成「已完成」。说明先讲「这是状态报告,
+  不是失败;测试、构建、仿真、带 sleep 的轮询常常更久」,再讲「符合预期就什么都不做、结束回合」,
+  最后才是「只有有具体证据表明卡住时才用 TaskStop」。
+- 主代理的手段:`TaskStop` 停止(已有);`TaskOutput`(`block=false`)对运行中的 local_agent 额外
+  返回 `activity`(与提醒同一份事实,工具名与摘要按 XML 转义),不再只给空输出;不新增「继续等待」工具,不停止即继续等。
+  `SendMessage` 要等 child 下一个工具轮才生效,卡在工具里时不作为手段。
+
+| | 前台 activity watchdog | 后台无进展提醒 |
+| --- | --- | --- |
+| 活动 | 任何 child 事件(含 Bash 心跳) | 模型请求/回复、工具开始/结束、审批结束 |
+| 动作 | 静默一个模型流 idle 窗口后中止(`ToolTimeout`) | 只报告给父会话,由主代理决定 |
+| 原因 | 父回合被前台 Agent 阻塞,必须兜底 | 父会话不被阻塞,交给模型判断 |
+
+### 上一代 runtime 遗留的 Agent
+
+同一个 workspace 的父会话与全部 child 跑在同一个 runtime 进程里。进程意外退出(例如系统可提交
+内存耗尽,Windows 退出码 `0xE0000008`)时 child 随之结束,但不会写 `SubagentStopped`、也不会
+发 task-notification;新进程的 `RuntimeTaskRegistry` 是空的,持久化的 launch ACK 与停在 running 的
+Agent part 也不会被改写。旧行为因此把这些 child 永久投影为 running(胶囊计时一直走、停止找不到
+目标),模型也不知道它们已经没了。
+
+判据(只用本进程可证明的事实,不用超时猜测):
+
+- Agent 的启动时间(本进程 spawn 事件的时间优先,否则用 Agent part 的开始时间)早于本进程启动
+  时间 `performance.timeOrigin`;
+- 本进程没有它的活事实:registry 无该任务、无 child live projection、无本进程的 spawn/stop 事件、
+  不在父 projection 的活动工具调用里;
+- child session 在本进程启动后没有更新(另一个进程仍在运行它时会持续落盘,不判为遗留)。
+
+```text
+旧进程崩溃 ── 新进程启动(timeOrigin)── 父会话恢复 ─────────── 下一轮请求
+   │                                      │                         │
+   └ child 最后落盘 < timeOrigin           ├ sessions 查询:遗留 → ended/lost(胶囊清空)
+                                          └ 对账:未通知且无终态 → 暂存提醒 ─────┘ task_status 提醒落盘送达
+```
+
+- 投影:`projectSessionSubagents` 不再把遗留 Agent 算作 running。终态按以下顺序取,前面的不被后面的
+  改写:background 终态、child projection、工具错误、`SubagentStopped`(本进程内才有)、遗留 Agent 的
+  `metadata.json` 终态(`completed`→success、`failed`→failed、`stopped`→cancelled,结束时间取其中的
+  `completedAt`);都没有、child 也没有最后结果时标 `lost`,结束时间取 child 最后一次落盘。
+  `metadata.json` 由异步层(V4 冷恢复的 `listSessionSubagents`、TUI 观察)用
+  `loadPreviousRuntimeRunMetadata` 预读,只读 launch ACK 早于本进程启动的候选;与恢复时的对账共用
+  core 的 `readSubagentRunMetadata`,两边看到同一份事实。
+- 纯文本 launch ACK 与结构化的 `async_launched` 同义:父 tool part 的 completed 只表示「已启动」,终态看
+  child 的最后结果,没有就是 `lost`。修复原因:之前冷查询里 child 已失败的后台 Agent 被显示为 success。
+- 区分「被崩溃中断」与「已有终态、只是通知没送达」的持久化事实是 Agent 输出目录里的 `metadata.json`:
+  启动与 SendMessage 恢复时写 `running`,完成、失败、停止时改写为 `completed` / `failed` / `stopped`。
+  runtime 正常关闭时 owner 会统一 stopTask,写 `stopped`,通知因关闭被丢弃;只有进程意外退出时停在
+  `running`。`SubagentStopped` 等事件只在进程内存的 event store 里,新进程读不到,不能作为判据。
+- 模型:父会话恢复时,对上述遗留、transcript 中没有这次运行的 `task-id` 通知、`metadata.json` 不是终态
+  (读不到时按 child 判断)、child 也没有终态(最后一条 assistant 带错误,或不含工具调用且已完成;
+  stream recovery 作废的半截回复不算)的后台 Agent,生成标准 local_agent
+  通知(`status=failed`,失败原因固定为
+  `the ZCode runtime process exited before it finished`),前面一段说明「上一代 runtime 意外退出、
+  这些后台 Agent 不会再回报,重新派发前先检查它们已做的改动」。恢复本身不开新轮:打开旧会话不消耗 token,也不在内存仍紧张时立刻
+  重新派发;提醒在下一轮第一次请求前作为 `task_status` 隐藏提醒落盘并进入上下文,之后的恢复按
+  transcript 中 `<task-notification>` 块里的 `task-id` 去重(无进展提醒也带 task-id,不算)。去重按「最近一次运行」:SendMessage 恢复沿用同一个 agentId,并在
+  `metadata.json` 记下 `resumedAt`;只有晚于它的通知才算这次运行已通知,之前那次运行的完成通知不能
+  挡掉恢复后运行的中断。
+- 已有终态(完成、失败、被停止,包括正常关闭时的统一停止)但通知没送达的 child 不在本节范围:它没有
+  被崩溃中断,不发「进程意外退出」提醒,也不改写真实的停止者和错误原因。把这类终态如实补报给模型,
+  属于「关闭期间丢弃终态通知」这一原有问题,另行处理。
+- 两个进程同时打开同一会话(如桌面与终端 TUI)没有跨进程租约;child 仍在落盘的条件避免把另一
+  进程正在运行的 child 判为遗留。已知限制:child 执行一个长时间不落盘的工具时,这条判据挡不住;
+  要严格区分需要跨进程的会话租约,或在 `metadata.json` 里记下运行它的进程并检查存活。
+
 ## Agent 定义契约
 
 ZCode 的用户/项目自定义 Markdown 仅从各自 `agents` 根目录直接文件加载
@@ -98,11 +235,11 @@ ZCode 的用户/项目自定义 Markdown 仅从各自 `agents` 根目录直接
 
 agent definition 有三类来源:
 
-| 来源 | 说明 |
-| --- | --- |
-| built-in | 代码内建,system prompt 动态生成 |
-| custom | 用户、项目、policy、flag settings 中的 markdown 或 JSON agent |
-| plugin | plugin 提供的 agent,agent type 会带 plugin namespace |
+| 来源     | 说明                                                          |
+| -------- | ------------------------------------------------------------- |
+| built-in | 代码内建,system prompt 动态生成                              |
+| custom   | 用户、项目、policy、flag settings 中的 markdown 或 JSON agent |
+| plugin   | plugin 提供的 agent,agent type 会带 plugin namespace         |
 
 agent definition 的核心字段:
 
@@ -133,11 +270,11 @@ agent definition 的核心字段:
 
 ZCode 的 custom agent Markdown 额外支持可选 frontmatter 字段 `injectAgentsMd: boolean`。它只控制 child request 是否注入父 runtime 已解析的 AGENTS.md,不改变 agent system prompt:
 
-| Profile | `injectAgentsMd` 缺省行为 |
-| --- | --- |
-| 内建 `general-purpose` | 注入 |
-| 内建 `Explore` | 不注入 |
-| custom | 注入;显式设为 `false` 时关闭 |
+| Profile                | `injectAgentsMd` 缺省行为     |
+| ---------------------- | ----------------------------- |
+| 内建 `general-purpose` | 注入                          |
+| 内建 `Explore`         | 不注入                        |
+| custom                 | 注入;显式设为 `false` 时关闭 |
 
 child runtime 只接收父 runtime `contextSourceSnapshot.userInstructions` 的快照;父级没有 snapshot 时不注入,也不在 child 中重新读取文件或构造 fallback。provider-visible 位置与 Main 相同,复用 Main 的 Request User Context formatter:
 
@@ -207,7 +344,9 @@ fork 路径例外:fork child 使用父 agent 的精确 tool array,同时继
     watchdog 默认复用模型流 idle timeout 窗口,并在 child session event 上重置;如果 child
     promise 在静默窗口后仍无响应,应以 `ToolTimeout` 结束并写入 `SubagentStopped`。如果父级
     abort 后 child promise 不 settle,应以 `ToolCancelled` 结束,避免 foreground `Agent` 长期
-    停在 running。
+    停在 running。转后台时 watchdog 永久解除:child 仍持有 `reportActivity`,旧实现下一条 child
+    事件会重新挂上中止,后台 Agent 静默一个窗口就被当作失败杀掉。后台无进展只报告,见
+    「后台 Agent 无进展提醒」。
 12. 收集子 agent messages,转发 tool progress、bash/powershell progress、token metrics。
 13. 结束时提取最后 assistant text、usage 和 tool use 总数。
 14. 如 auto mode classifier 开启,对 subagent handoff 做安全复核。
@@ -231,7 +370,7 @@ background subagent:
 4. 后台 lifecycle 消费 child 消息流,持续更新 progress。
 5. 完成后先把 task 标记为 completed,避免 output 读取方被 classifier 或 worktree cleanup 卡住。
 6. 通过 `<task-notification>` 把 status、summary、output file、usage、worktree 信息重新送进主会话。
-7. 停止标记 killed,通知带停止者(`SubagentStopOptions.initiator`:TaskStop 传 `model`,App 停止传 `user`,系统路径不传);其他异常标记 failed。failed notification 必须从异常 cause 链取最接近 provider 的原始 message:summary 写成 `Agent "<description>" failed: <原文>`,不翻译、不映射错误码,也不把失败伪装成 `<result>`。
+7. 停止标记 killed,通知带停止者(`SubagentStopOptions.initiator`:TaskStop 传 `model`,App 停止传 `user`,系统路径不传);其他异常标记 failed。failed notification 必须从异常 cause 链取最接近 provider 的原始 message:summary 写成 `Agent "<description>" failed: <原文>`,不翻译、不映射错误码,失败原因也不写进 `<result>`;failed 的 `<result>` 只放本次运行的部分报告(见上文后台终态通知)。
 8. 父侧 Agent 工具最初的 `completed` 只表示后台任务已成功启动;匹配 `tool-use-id` 的 failed notification 才能覆盖 launch ACK。live event 与 snapshot/restore 都必须用 notification 的 failed 状态和失败原因覆盖,保证现有“执行失败”状态文案和 hover 错误详情在切换任务后不丢失。失败原因取自 `originMeta.subagentResult.error`(旧会话读 `<error>`);单条通知的轮次 hover 只显示原文,不带 `Agent "…" failed:` 前缀;多条通知合并成一轮时没有结构化原因,hover 显示该任务自己的整句 summary(见上文后台终态通知)。V4 投影(桌面、Web、手机)把 `killed` 和旧会话的 `stopped` 都显示为已停止;legacy 快照路径(bots 的 `getTaskSnapshot`、`zcodeSessionProjection`)只用 failed 覆盖 launch ACK,killed 仍显示为完成。
 
 sync 转 background:
@@ -245,16 +384,16 @@ sync 转 background:
 
 子执行上下文默认隔离所有可变状态:
 
-| 状态 | 默认行为 |
-| --- | --- |
-| read file state | 从 parent clone,结束时 clear |
-| abort controller | 新 child controller。同步 Agent 可以显式共享 parent controller,后台 agent 使用独立 controller |
-| app state 读取 | 默认标记为避免权限弹窗,防止后台 agent 弹交互权限 |
-| app state 写入 | 默认 no-op。需要 task 注册和 kill 时只通过 task 专用入口写 root store |
-| response length | 可选择共享,让子 agent 计入父响应 metrics |
-| memory/skill/dynamic triggers | fresh Set |
-| content replacement state | clone parent,fork 用于保持 cache replacement 决策一致 |
-| query tracking | 新 chain id,depth 在 parent 基础上加一 |
+| 状态                          | 默认行为                                                                                       |
+| ----------------------------- | ---------------------------------------------------------------------------------------------- |
+| read file state               | 从 parent clone,结束时 clear                                                                  |
+| abort controller              | 新 child controller。同步 Agent 可以显式共享 parent controller,后台 agent 使用独立 controller |
+| app state 读取                | 默认标记为避免权限弹窗,防止后台 agent 弹交互权限                                              |
+| app state 写入                | 默认 no-op。需要 task 注册和 kill 时只通过 task 专用入口写 root store                          |
+| response length               | 可选择共享,让子 agent 计入父响应 metrics                                                      |
+| memory/skill/dynamic triggers | fresh Set                                                                                      |
+| content replacement state     | clone parent,fork 用于保持 cache replacement 决策一致                                         |
+| query tracking                | 新 chain id,depth 在 parent 基础上加一                                                        |
 
 child 运行时还会:
 
@@ -276,11 +415,11 @@ ZCode 不再写入独立的 `transcript.jsonl` 文件。子 agent 的 messages/p
 
 metadata 至少保存:
 
-| 字段 | 说明 |
-| --- | --- |
-| `agentType` | resume 时恢复原 agent 类型。fork resume 需要知道它是 `fork` |
-| `worktreePath` | worktree agent resume 时恢复 cwd |
-| `description` | notification 用原始描述 |
+| 字段           | 说明                                                        |
+| -------------- | ----------------------------------------------------------- |
+| `agentType`    | resume 时恢复原 agent 类型。fork resume 需要知道它是 `fork` |
+| `worktreePath` | worktree agent resume 时恢复 cwd                            |
+| `description`  | notification 用原始描述                                     |
 
 `SendMessage` 可以继续一个已 spawned subagent:
 
@@ -301,13 +440,13 @@ transcript sidecar。
 
 ZCode 建议拆成两层声明:
 
-| 维度 | 建议 |
-| --- | --- |
-| `orchestrationReadOnly` | `true`,spawn 本身不直接写文件、跑命令或联网 |
-| `effectiveReadOnly` | 动态,取决于 agent tool pool、permission mode、prompt intent、isolation 和 background |
-| `sideEffectScope` | `session`、`workspace`、`git`、`network`、`system`、`userInteraction` 的并集 |
-| `concurrencySafe` | spawn 编排可并发,但同一 worktree/cwd 的写工具仍需由底层工具和 file locks 保护 |
-| `destructive` | 如果 agent 可用写入、shell、git 或 network tool,则应提升为潜在 destructive |
+| 维度                    | 建议                                                                                  |
+| ----------------------- | ------------------------------------------------------------------------------------- |
+| `orchestrationReadOnly` | `true`,spawn 本身不直接写文件、跑命令或联网                                          |
+| `effectiveReadOnly`     | 动态,取决于 agent tool pool、permission mode、prompt intent、isolation 和 background |
+| `sideEffectScope`       | `session`、`workspace`、`git`、`network`、`system`、`userInteraction` 的并集          |
+| `concurrencySafe`       | spawn 编排可并发,但同一 worktree/cwd 的写工具仍需由底层工具和 file locks 保护        |
+| `destructive`           | 如果 agent 可用写入、shell、git 或 network tool,则应提升为潜在 destructive           |
 
 权限规则:
 
@@ -363,9 +502,9 @@ ZCode 应把 hook/MCP/skill 都视为外部 I/O 或扩展边界,必须带 trac
 - agent-specific MCP 初始化失败。
 - child 运行完成后没有 assistant message,结果收尾阶段报错。
 - sync agent AbortError。
-- sync agent 中途异常但已有 assistant message,尽量返回 partial finalized result。
-- async agent AbortError,标记 killed;通知不带 `<result>`(暂不采集已输出的部分文字,见上文后台终态通知)。
-- async agent 普通异常,标记 failed。
+- sync agent 开始运行后异常:工具调用仍为失败,给模型的错误文本附部分报告(有正文时)、`agentId` 行和 `<usage>`,规则见上文「同步失败」。runtime task error(TaskOutput 读它)、`metadata.json` 的 `error`、`output.txt` / `task.output` 和 `SubagentStopped.payload.error` 与后台相同,写从 cause 链取到的 provider 原始 message;外层 `Turn execution failed` 不能覆盖它。
+- async agent AbortError,标记 killed;通知不带 `<result>`(killed 暂不带部分报告,见上文后台终态通知)。
+- async agent 普通异常,标记 failed;本次运行有正文时,通知 `<result>` 带部分报告,App 不展示它。
 - async agent 普通异常的 provider 原始 message 必须同时进入 task notification summary、runtime task error 和 `SubagentStopped.payload.error`;外层 `Turn execution failed` 只能作为 detail 保留,不能覆盖父模型或 Agent 卡片看到的失败原因。
 - worktree cleanup 失败或 worktree 已被外部删除,resume 时回退到 parent cwd。
 - classifier 不可用或判定 handoff 危险,需要把 warning 插入父 agent 可见结果。
@@ -420,6 +559,7 @@ ZCode 应把 hook/MCP/skill 都视为外部 I/O 或扩展边界,必须带 trac
 - 内建 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。
+- `Agent` 与 `SendMessage` 都声明为只读(`readOnly: true`),父会话开启 Plan 时都能调用;子代理的工具按上面算出的子会话模式判定。给运行中的子代理发消息只投递消息,不重算它的模式。修复原因:`SendMessage` 曾声明为非只读,被 Plan 闸门拒绝,父会话在 Plan 下无法唤醒已结束的子代理补发报告,上一条的 Plan 恢复路径从模型侧也无法到达。
 - provider-visible `TaskStop` 可以停止当前 runtime 中已经 background 的 `local_agent` / `local_bash`;`local_agent` 的 result `command` 使用短 `description`,不得回退为完整 `prompt`。
 
 ### Built-in Explore 身份边界
@@ -488,7 +628,7 @@ Child finish    -> no parent MCP cleanup
   success 不表示 parent 已经读取、持久化或回复。
 - response command 被 parent drain 后,完整 `<summary>` / `<message>` carrier 以 source
   `subagent_message`、visibility `model-only` 写入 parent model history 和 session store。它不进入用户
-  可见消息、session title 或 `ReadSessionContext`,但原始 session 导出、诊断、存储预算和 compact
+  可见消息、session title 或 `ReadSession` 的读取结果,但原始 session 导出、诊断、存储预算和 compact
   必须按可能包含该内容处理。
 - synthetic user message source `subagent_message` 不是 `SessionEventType.SubagentMessage`
   lifecycle/progress event,也不是 child transcript 镜像。完整契约见

+ 14 - 0
apps/zcode-cli/docs/design/v2/tool/13-websearch.md

@@ -126,6 +126,20 @@ DuckDuckGo HTML fallback。
 - 内部 provider-native request 的 network status 通过 tool context 继续转发为
   `ModelNetworkStatus` 事件。
 
+### 动态工作流子代理的搜索预算(2026-11-02)
+
+- tool context 可带 `webSearchBudget`(`WorkflowWebSearchBudgetPort`)。只有动态工作流子代理
+  的 runtime 注入它;主会话、`Agent` 子代理、legacy `Workflow` 子代理没有这个端口,也就没有上限。
+- handler 在校验模型能力之后、发出内部请求之前调用 `charge()`。端口回 `exhausted` 时,handler
+  不发请求,返回 `ToolHandlerFailure`(`WEB_SEARCH_BUDGET_EXHAUSTED_ERROR_CODE`),文案取端口给的
+  `message`:本任务的搜索预算已用完,不要再调 WebSearch,用已有信息完成,并在结果里说明搜索被截断。
+- 计数、上限与重置都归 driver:每个 ask 默认 128 次,persona 的 `budget.webSearch` 可改为
+  0–1024;nudge、repair 轮共用同一计数,下一个 ask 归零。合同见
+  `packages/dynamic-workflow/docs/execution-engine.md`「Search budget」与根目录
+  `docs/dynamic-workflow/authoring.md`「A subagent's search budget」。
+- 工具 schema、描述、权限与 tools 段字节不变;被拒的调用照常产生 tool lifecycle 事件,
+  `tool_usage` 记为 error。
+
 ## 删除与迁移
 
 删除或不恢复:

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

@@ -37,8 +37,10 @@ Read 去重与写前检查结果相同;Bash 回填和 Recall 注入的记录
   PostToolUse hook、结果事件等异步步骤)。执行器在工具记录快照时取号,这一步与写 live 状态在同一个
   同步步骤里,所以序号就是 live 的写入顺序。返回 `file_unchanged` 的 Read 不写 live 状态,也不记录快照;
   冷恢复跳过这类结果(包括旧数据里已经存了快照的),由之前那次真实读取恢复同一个视图和时间。之前那次
-  读取不在 active history 里时(例如已被 compact 摘要),这个文件不恢复。模型可见历史仍按 `declarationIndex`,不受影响(见
-  [工具历史顺序修复](../../../../../../docs/design/v2/tool/tool-history-order-repair-proposal.md))。
+  读取不在 active history 里时(例如已被 compact 摘要),这个文件不恢复。模型可见历史按 `blockIndex`
+  (旧数据按 `declarationIndex`),不受影响(见
+  [工具历史顺序修复](../../../../../../docs/design/v2/tool/tool-history-order-repair-proposal.md)、
+  [Assistant 内容块顺序](../model/assistant-block-order.md))。
   同一条消息里的快照都带 `snapshotIndex` 时按它排序,否则(旧数据)保持 part 原顺序。被 token cap
   截断的 `Read` 恢复为 `isPartialView: true`。
 - 成功的 `Write` / `Edit` 用 completed tool part metadata 里持久化的完整快照恢复为当前文件
@@ -75,6 +77,8 @@ compaction 补回文件(`rewind-compact.md` 的“文件恢复”)重读磁
 - 因总量上限被丢掉、读取失败或被跳过的文件:不写记录。
 - 这些记录不落盘:补回附件没有快照,hydrator 只扫描工具结果。重启或 rewind 之后没有这些记录,Read
   返回正文,Edit / Write 要求先读。
+- `MEMORY.md`:compaction 收尾时重读索引,live 表装好补回记录之后,再写入一条按重读内容生成的
+  `seededFromContext` 记录(规则与会话开始时相同)。索引不存在或不可读时不写。
 
 ## ZCode 实现边界
 

+ 32 - 12
apps/zcode-cli/docs/design/v2/tool/19-tool-search.md

@@ -9,9 +9,15 @@
 
 ## App Settings 模式
 
-常规设置提供 `toolSearchMode: auto | local | off`,缺省 `off`。`auto` 按每次请求的
-实际 Model 决定 Native/Local;`local` 固定走 Local,沿用能力校验;`off` 使用全量工具。
-CLI 四值参数及默认 Off 不变,独立 CLI 不读取 App Settings。
+常规设置提供 `toolSearchMode: auto | local | off`,缺省 `off`。
+`auto` 按每次请求的实际 Model 决定 Native/Local:Anthropic Messages + Coding Plan 走 Native,
+其他支持 tool call 的模型走 Local;`local` 固定走 Local,沿用能力校验;`off` 使用全量工具。
+App 缺省值只在 `packages/shared` 的 `DEFAULT_APP_TOOL_SEARCH_MODE` 定义一次,设置 schema、
+Host 偏好响应和设置页初始显示都读它。CLI 四值参数及默认 Off 不变,独立 CLI 不读取 App Settings。
+
+2026-11-05 App 缺省曾改为 `auto`,2026-11-09 改回 `off`。该缺省只进入未正式发布的
+v3.18.0 构建,所以不做迁移;同期把 TodoWrite/WebFetch/WebSearch/submit_result 改为常驻的
+变化保留(见下文常驻名单)。缺省值变化不覆盖用户已保存的任何选择。
 
 工具搜索设置行底部常驻显示实验性说明:模型供应商未完整支持原生 ToolSearch 时,
 使用原生模式可能导致缓存失效并增加 Token 用量。中英文文案含义一致,复用设置行的底部
@@ -229,10 +235,18 @@ Model requestCapabilities.toolSearch 保存 protocolSupported/defaultEnabled;
 toolSearchEnabled。ToolMetadata 增加 shouldDefer/alwaysLoad/searchHint;请求工具增加
 deferLoading;模型内容增加严格的 `{type:"tool_reference",toolName:string}`。
 
-内置常驻名单:Agent/AskUserQuestion/Bash/Edit/Glob/Grep/Read/ReportFindings/Skill/ToolSearch/Write。
+内置常驻名单:Agent/AskUserQuestion/Bash/Edit/Glob/Grep/Read/ReportFindings/Skill/TodoWrite/
+ToolSearch/WebFetch/WebSearch/Write,外加 workflow actor 会话的 submit_result。
 只暴露当前已注册、作用域允许且满足原有可见性规则的工具;当前没有 ReportFindings 实现,
-不因名单而新增工具。其余已注册内置工具统一在各自 metadata 声明 shouldDefer: true,
-包括 ZCode 工作流(含 FillWorkflowHole)、OffPeak、TodoRead、CronUpdate、js 和子 Agent 协作工具。
+不因名单而新增工具。submit_result 只在注入 `workflowSubmitPort` 时注册,因此"常驻"只作用于
+actor 会话,主会话目录不变;每个 actor 都要调用它交付结果,延迟加载只会多一次搜索往返,
+Local 下还会经 DeferredToolCall 包装而丢掉 typed 声明的 strict 约束。
+升级前创建的会话接受以下行为,不做迁移:旧公告里的 TodoWrite/WebFetch/WebSearch 不会被删除公告
+修正,因为删除只对照当前完整作用域目录,这些工具仍可用;模型照 Local 旧历史再发
+`DeferredToolCall {name:"TodoWrite"}` 时,包装入口返回可恢复错误
+"Call TodoWrite directly using its normal tool call",模型改为直接调用即可。
+其余已注册内置工具统一在各自 metadata 声明 shouldDefer: true,
+包括 ZCode 工作流(含 FillWorkflowHole)、OffPeak、TodoRead、CronUpdate、js、escalate 和子 Agent 协作工具。
 ReplyToChannel 保留实现但不默认注册,因此不进入搜索目录或 provider 工具列表。
 Task 兼容入口保持 providerVisible: false,不因 deferred 分类而进入请求或搜索目录。
 不开启 ToolSearch 时保留完整工具集;开启时首轮只发送常驻定义,真实搜索发现后才追加
@@ -268,6 +282,9 @@ runtime schema 仍接受省略 max_results,沿既有执行链先补默认值 5
 
 2026-10-21:Native/Local 共用描述的精确选择示例改为
 `"select:TodoWrite,mcp__byob__browser_navigate" — fetch these exact deferred tools by name`。
+2026-11-05:TodoWrite 改为常驻后,示例改为
+`"select:TaskStop,mcp__byob__browser_navigate" — fetch these exact deferred tools by name`,
+避免示例点名一个常驻工具;选用未废弃的 TaskStop,与 Local 调用示例一致。
 空匹配模型结果固定为以下文本;本次仅调整文案,不修改精确选择、已加载工具或关键词匹配行为:
 
 ```text
@@ -276,8 +293,9 @@ No matching deferred tools found. Loaded tools are not searchable here and need
 
 未搜索不是执行禁令;未发现工具的参数校验失败提示先搜索加载定义。
 
-内置 deferred 工具的 metadata.searchHint 采用以下检索材料,不改 provider description、
-参数、排序权重或常驻工具;MCP 继续使用自身的 searchHint。
+内置工具的 metadata.searchHint 采用以下检索材料,不改 provider description、
+参数或排序权重;MCP 继续使用自身的 searchHint。关键词搜索只搜 deferred 工具,
+WebFetch/WebSearch/TodoWrite 转为常驻后保留 searchHint,但不参与关键词匹配。
 
 | 工具          | searchHint                                                  |
 | ------------- | ----------------------------------------------------------- |
@@ -352,8 +370,10 @@ Native 与 Local 的真实 provider 请求均验证这段说明和参数描述
 Local 描述首句明确 deferred 工具通过 `DeferredToolCall` 调用;搜索与返回格式说明保持
 原有 `<functions>` / `<function>` 结构,明确 `parameters` 描述的是包装调用的 `input`。
 不再声称与 prompt 顶部工具列表具有相同编码,也不使用抽象的 classification 说明。
-常驻工具仍直接调用。只保留一个简短的 TodoWrite `<example>`,展示顶层 `name` 和完整
-`input`,不增加场景对白或 `<commentary>`;不要求已经加载的工具重搜。
+常驻工具仍直接调用。只保留一个简短的 TaskStop `<example>`(2026-11-05 前为 TodoWrite,
+TodoWrite 转为常驻后改用没有注册门控、未废弃的 deferred 工具),展示顶层 `name` 和完整
+`input`;`task_id` 的值写占位符 `<task_id returned when the task started>`,不写虚构 ID,
+避免模型照抄。不增加场景对白或 `<commentary>`;不要求已经加载的工具重搜。
 示例按当前包装及目标工具 schema 校验,CLI/PTY E2E 检查 Local/auto 与冷恢复请求中的
 实际 description,Native 完整文案由既有 wire 测试保护。本次只改 Local 描述,不改变结果
 投影、调用参数、执行逻辑或重复搜索反馈;bench 行为收益需另行验证。
@@ -732,7 +752,7 @@ Local 反馈全部位于 tool_result 内,不再派生结果外的 `Tool loaded
 
 ```text
 <system-reminder>
-Loaded: TodoWrite. Call it now with DeferredToolCall {"name":"<tool name>","input":{...}}, using the exact tool name and filling input according to its schema above. No additional ToolSearch is needed before calling these tools.
+Loaded: TaskOutput. Call it now with DeferredToolCall {"name":"<tool name>","input":{...}}, using the exact tool name and filling input according to its schema above. No additional ToolSearch is needed before calling these tools.
 </system-reminder>
 ```
 
@@ -740,7 +760,7 @@ Loaded: TodoWrite. Call it now with DeferredToolCall {"name":"<tool name>","inpu
 
 ```text
 <system-reminder>
-Loaded: TodoWrite, WebFetch. Call them now with DeferredToolCall {"name":"<tool name>","input":{...}}, using the exact tool name and filling input according to its schema above. No additional ToolSearch is needed before calling these tools.
+Loaded: TaskOutput, TodoRead. Call them now with DeferredToolCall {"name":"<tool name>","input":{...}}, using the exact tool name and filling input according to its schema above. No additional ToolSearch is needed before calling these tools.
 </system-reminder>
 ```
 

+ 23 - 13
apps/zcode-cli/docs/design/v2/usage-observability.md

@@ -2,7 +2,7 @@
 
 ## Goal
 
-Persist short-lived usage facts for `/usage` and local diagnostics. The data answers:
+Persist long-lived usage facts for `/usage` and local diagnostics. The data answers:
 
 - Daily token usage by provider and model.
 - Daily user turn count, similar to an activity heatmap.
@@ -10,8 +10,8 @@ Persist short-lived usage facts for `/usage` and local diagnostics. The data ans
 - Cache hit and cache creation token volume.
 - Error, retry, cancellation, and context-overflow rates.
 
-Usage observability is not a permanent billing ledger. Rows are retained for 30 days and may be
-pruned on startup or after writes.
+Usage observability is not a billing ledger. Model, turn, and tool usage facts are retained
+indefinitely, with no automatic age-based deletion on startup, writes, or queries.
 
 ## Source Of Truth
 
@@ -67,21 +67,28 @@ for activity-style turn counts and loop-level latency.
 One row per tool call. The row tracks tool name, side-effect metadata, approval status, latency,
 output byte counts, truncation, errors, and cancellation flags.
 
-Rollups are intentionally deferred. `/usage` can group over 30 days of facts directly; if the facts
-grow expensive later, daily rollups can be rebuilt from these tables.
+Rollups are intentionally deferred. `/usage` groups facts within the requested time range directly;
+if queries grow expensive later, daily rollups can be rebuilt from the retained facts.
 
 ## Retention
 
-The store prunes rows older than 30 days using:
+`model_usage`, `turn_usage`, and `tool_usage` have no retention cutoff. Writing a new fact or
+updating an existing fact must not delete older facts, including records older than 30 days or a year.
+Closing and reopening the database must preserve the same history.
 
-```sql
-delete from model_usage where started_at < ?;
-delete from turn_usage where started_at < ?;
-delete from tool_usage where started_at < ?;
+```text
+Runtime usage events → CLI-owned SQLite write/upsert → retained usage facts
+                                                    → requested-range aggregation
 ```
 
-The cutoff is `Date.now() - 30 days`. Pruning must never block the model/tool path if it fails; it is
-best-effort observability.
+The store exposes no time-based `pruneUsage` operation. Remove the former 30-day constants, automatic
+pruning calls, store method, and port capability together. Usage write capability detection must
+only require the existing write methods; it must not depend on a removed cleanup method.
+
+Query ranges remain filters, not retention policies: `since=0` includes all retained history, while
+7-day and 30-day queries include only their requested windows. No schema migration is needed.
+Previously pruned data cannot be restored by this change. Explicit session/data deletion keeps its
+existing behavior; indefinite retention means no automatic expiry, not protection from user deletion.
 
 ## Write Points
 
@@ -154,7 +161,10 @@ order by calls desc;
 ## Tests
 
 - SQLite migration creates all usage tables and indexes.
-- SQLite usage repository upserts model, turn, and tool rows and prunes old rows.
+- SQLite usage repository retains model, turn, and tool rows older than a year after writes,
+  updates, and database reopening.
+- All-time queries include historical facts; explicit 30-day queries still exclude them.
+- Runtime usage recording works with a store that has no cleanup capability.
 - Runtime records main-turn model usage, turn usage, and tool usage.
 - Runtime records non-transcript model calls such as session title generation and compact through
   the same `model_usage` path.

+ 1 - 0
apps/zcode-cli/docs/design/v2/zcode-protocol-agent-server.md

@@ -92,6 +92,7 @@ stateDiagram-v2
 ## v1 方法
 
 - session: `create`、`resume`、`list`、`read`、`messages`、`events`、`subscribe`、`send`、`stop`、`setModel`、`setThoughtLevel`、`setMode`、`close`
+- `session/releaseUnderDirectory { directory }`:选出 cwd(`record.workspace.workspacePath`)位于该目录内的全部驻留会话。任一会话忙(驻留阻塞工作、待处理交互或排队命令,与彻底删除数据的判定相同)时全部不卸载,返回 `{ released: [], busy }`;否则全部做驻留去激活,返回 `{ released, busy: [] }`。不删除持久会话,不发 `session.removed`。Host 删除受管 worktree 前使用(`docs/git/worktree.md` §8.3),随 `worktreeCwd` 能力提供。
 - workspace: `readState`
 - process: `childProcesses`——返回 MCP tracker 内存里仍有存活进程的 MCP 子进程 `{ pid, serverName, mcpSource, pluginName? }`。纯内存、无 I/O;`pluginName` 来自 `plugin:<name>:<key>` 命名空间,官方插件由 host CLI 注入的 MCP(如 `node_repl`)按 `OFFICIAL_PLUGIN_DEFINITIONS.hostMcpServerNames` 反查。桌面资源管理器用它把 Host 侧 `ps` 进程树上的 pid 归到内置 / 社区插件(见桌面仓库 `docs/electron/resource-manager.md`),CPU/内存采样不在 CLI 内完成。
 - blocking request: 后续由 `interaction/requestPermission`、`interaction/requestUserInput` 通过 server-to-client request 扩展

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

@@ -127,6 +127,7 @@
     "@types/node": "^24.0.0",
     "@types/semver": "^7.7.0",
     "@types/yauzl": "^2.10.3",
+    "node-forge": "^1.4.0",
     "vitest": "^4.1.5"
   }
 }

+ 12 - 1
apps/zcode-cli/packages/adapters/src/auth/coding-plan-api-key.ts

@@ -10,6 +10,7 @@ import {
   ProjectAccessTokenError,
   ProjectAccessTokenHttpStatusError,
   ProjectAccessTokenTransientError,
+  projectAccessTokenRetryAfterMs,
   resolveBigModelApiOrigin,
   type ProjectAccessTokenMaterial,
 } from "@zcode/shared";
@@ -99,7 +100,17 @@ export function createCodingPlanApiKeyResolver(
     }
     if (response.status === 404) return { code: 404 };
     if (response.status === 429 || (response.status >= 500 && response.status < 600))
-      throw new ProjectAccessTokenTransientError({ kind: "http", status: response.status });
+      throw new ProjectAccessTokenTransientError({
+        kind: "http",
+        status: response.status,
+        ...(response.status === 429
+          ? {
+              retryAfterMs: projectAccessTokenRetryAfterMs(
+                new Headers(response.headers).get("retry-after"),
+              ),
+            }
+          : {}),
+      });
     // Bug 原因(ZCT-2111046389485834240):非临时状态与 2xx 非 JSON 过去都落成
     // project_token_request_failed,无法区分鉴权拒绝与响应损坏。只保留状态码/固定码,不带响应体。
     if (response.status < 200 || response.status >= 300)

+ 9 - 95
apps/zcode-cli/packages/adapters/src/auth/credential-cipher.ts

@@ -1,101 +1,15 @@
-import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
-import { homedir, platform, userInfo } from "node:os";
-
-const ENCRYPTED_VALUE_PREFIX = "enc:v1:";
-const CREDENTIAL_CIPHER_ALGORITHM = "aes-256-gcm";
-const CREDENTIAL_CIPHER_IV_BYTES = 12;
-const CREDENTIAL_CIPHER_AUTH_TAG_BYTES = 16;
-const CREDENTIAL_SECRET_ENV_KEY = "ZCODE_CREDENTIAL_SECRET";
-
-export interface ZCodeCredentialCipher {
-  decrypt(value: string): string;
-  encrypt(value: string): string;
-}
-
+import {
+  createLegacyCredentialCipher,
+  type CredentialCipher,
+} from "@zcode/shared/credential-security";
+export type ZCodeCredentialCipher = CredentialCipher;
 export interface ZCodeCredentialCipherOptions {
   env?: Record<string, string | undefined>;
 }
-
-export function createZCodeCredentialCipher(
-  options: ZCodeCredentialCipherOptions = {},
-): ZCodeCredentialCipher {
-  const key = deriveCipherKey(resolveCredentialSecret(options.env ?? process.env));
-
-  return {
-    decrypt(value: string): string {
-      if (!isEncryptedZCodeCredentialValue(value)) {
-        return value;
-      }
-
-      const payload = value.slice(ENCRYPTED_VALUE_PREFIX.length);
-      const parts = payload.split(".");
-      const [ivRaw, authTagRaw, cipherRaw] = parts;
-
-      if (!ivRaw || !authTagRaw || !cipherRaw || parts.length !== 3) {
-        throw new Error("Credential decrypt failed: invalid ciphertext format");
-      }
-
-      const iv = Buffer.from(ivRaw, "base64url");
-      const authTag = Buffer.from(authTagRaw, "base64url");
-      const cipherText = Buffer.from(cipherRaw, "base64url");
-
-      if (iv.length !== CREDENTIAL_CIPHER_IV_BYTES) {
-        throw new Error("Credential decrypt failed: invalid IV length");
-      }
-      if (authTag.length !== CREDENTIAL_CIPHER_AUTH_TAG_BYTES) {
-        throw new Error("Credential decrypt failed: invalid auth tag length");
-      }
-
-      try {
-        const decipher = createDecipheriv(CREDENTIAL_CIPHER_ALGORITHM, key, iv);
-        decipher.setAuthTag(authTag);
-        const plainText = Buffer.concat([decipher.update(cipherText), decipher.final()]);
-        return plainText.toString("utf-8");
-      } catch (error) {
-        throw new Error("Credential decrypt failed: key mismatch or corrupted ciphertext", {
-          cause: error,
-        });
-      }
-    },
-
-    encrypt(value: string): string {
-      const iv = randomBytes(CREDENTIAL_CIPHER_IV_BYTES);
-      const cipher = createCipheriv(CREDENTIAL_CIPHER_ALGORITHM, key, iv);
-      const encrypted = Buffer.concat([cipher.update(value, "utf-8"), cipher.final()]);
-      const authTag = cipher.getAuthTag();
-
-      return [
-        ENCRYPTED_VALUE_PREFIX,
-        iv.toString("base64url"),
-        ".",
-        authTag.toString("base64url"),
-        ".",
-        encrypted.toString("base64url"),
-      ].join("");
-    },
-  };
+/** 仅兼容旧格式;正式凭据仓库默认使用系统安全存储。 */
+export function createZCodeCredentialCipher(options: ZCodeCredentialCipherOptions = {}) {
+  return createLegacyCredentialCipher(options.env);
 }
-
 export function isEncryptedZCodeCredentialValue(value: string): boolean {
-  return value.startsWith(ENCRYPTED_VALUE_PREFIX);
-}
-
-function deriveCipherKey(secret: string): Buffer {
-  return createHash("sha256").update(secret).digest();
-}
-
-function resolveCredentialSecret(env: Record<string, string | undefined>): string {
-  const configuredSecret = env[CREDENTIAL_SECRET_ENV_KEY]?.trim();
-  if (configuredSecret) {
-    return configuredSecret;
-  }
-
-  let username = "unknown";
-  try {
-    username = userInfo().username;
-  } catch {
-    // Some packaged or sandboxed runtimes cannot resolve OS user info.
-  }
-
-  return `zcode-credential-fallback:${platform()}:${homedir()}:${username}`;
+  return value.startsWith("enc:");
 }

+ 218 - 98
apps/zcode-cli/packages/adapters/src/auth/shared-credentials.ts

@@ -1,19 +1,35 @@
-import { existsSync, readFileSync } from "node:fs";
+import { randomUUID } from "node:crypto";
+import { OAUTH_SESSION_REVISION_KEY, OAUTH_LINKED_BIGMODEL_KEY } from "@zcode/shared";
 import { readFile } from "node:fs/promises";
 import { homedir } from "node:os";
 import { join, resolve } from "node:path";
-import { atomicWritePrivateTextFile, backupCorruptFile, withFileLock } from "@zcode/shared/node";
-import { createZCodeCredentialCipher, type ZCodeCredentialCipher } from "./credential-cipher.js";
+import {
+  atomicWritePrivateTextFile,
+  backupCorruptFile,
+  captureCredentialFileGuard,
+  type CredentialFileGuard,
+  withCredentialFileRead,
+  withCredentialFileMutation,
+  withFileLock,
+} from "@zcode/shared/node";
+import type { ZCodeCredentialCipher } from "./credential-cipher.js";
+import {
+  createSystemCredentialCipher,
+  migrateCredentialRecord,
+} from "@zcode/shared/credential-security";
 
 const ZCODE_DATA_BASE_DIR_ENV_KEY = "ZCODE_DATA_BASE_DIR";
 const ZAI_PROVIDER_ID = "zai";
-const credentialChangeListeners = new Map<
-  string,
-  Set<() => void | Promise<void>>
->();
+const WRITE_PROBE_VALUE = "zcode-credential-write-probe";
+const credentialChangeListeners = new Map<string, Set<() => void | Promise<void>>>();
 
 export const SHARED_ZCODE_CREDENTIAL_KEYS = {
   activeProvider: "oauth:active_provider",
+  sessionRevision: OAUTH_SESSION_REVISION_KEY,
+  linkedBigModel: OAUTH_LINKED_BIGMODEL_KEY,
+  zaiCnAccessToken: "oauth:zai_cn:access_token",
+  zaiCnRefreshToken: "oauth:zai_cn:refresh_token",
+  zaiCnUserInfo: "oauth:zai_cn:user_info",
   bigmodelAccessToken: "oauth:bigmodel:access_token",
   bigmodelRefreshToken: "oauth:bigmodel:refresh_token",
   bigmodelUserInfo: "oauth:bigmodel:user_info",
@@ -43,8 +59,18 @@ export interface ZaiLoginCredentialPayload {
   user: ZaiLoginCredentialUser;
 }
 
+export interface SharedCredentialRecoveryGuard {
+  readonly run: CredentialFileGuard;
+  /** 仅保护其它文件的最终提交;调用方先取得其它文件锁,回调不能再次写凭据库。 */
+  readonly commit: CredentialFileGuard;
+}
+
 export interface SharedZCodeCredentialStore {
   readonly filePath: string;
+  /** 用首次写入的同一密钥路径确认可写;不写凭据文件,不可用时抛出原始安全存储错误。 */
+  assertWritable(): Promise<void>;
+  /** 跨请求流程在启动时捕获,不能等网络返回后领取恢复后的新代次。 */
+  captureRecoveryGuard(): Promise<SharedCredentialRecoveryGuard>;
   clearZaiLoginCredentials(): Promise<void>;
   delete(key: string): Promise<void>;
   deleteIfValue(key: string, expectedValue: string): Promise<boolean>;
@@ -56,13 +82,22 @@ export interface SharedZCodeCredentialStore {
     expectedGuardValue: string,
     keysToDelete: readonly string[],
   ): Promise<boolean>;
+  updateMany(
+    changes: Readonly<Record<string, string | null>>,
+    options?: { expected?: Readonly<Record<string, string | null>>; assertCurrent?: () => void },
+  ): Promise<boolean>;
   load(key: string): Promise<string | null>;
   loadMany(keys: readonly string[]): Promise<Record<string, string | null>>;
+  loadOAuthSessionSnapshot(): Promise<Record<string, string | null>>;
   onDidChange?(listener: () => void | Promise<void>): () => void;
   save(key: string, value: string): Promise<void>;
   saveMany(entries: Readonly<Record<string, string>>): Promise<void>;
   saveReplacing(key: string, value: string, replacedKeys: readonly string[]): Promise<void>;
-  saveZaiLoginCredentials(payload: ZaiLoginCredentialPayload): Promise<void>;
+  saveZaiLoginCredentials(
+    payload: ZaiLoginCredentialPayload,
+    expected?: Readonly<Record<string, string | null>>,
+    assertCurrent?: () => void,
+  ): Promise<void>;
 }
 
 export function createSharedZCodeCredentialStore(
@@ -70,28 +105,138 @@ export function createSharedZCodeCredentialStore(
 ): SharedZCodeCredentialStore {
   const env = options.env ?? process.env;
   const filePath = resolveSharedZCodeCredentialsPath(options);
-  const cipher = options.cipher ?? createZCodeCredentialCipher({ env });
+  const cipher = options.cipher ?? createSystemCredentialCipher({ env, filePath });
+  const readCurrent = async () => {
+    // 普通读取不取得写锁(慢写入曾让登录读取等锁超时),由读取前后的恢复代次校验拒绝旧结果。
+    // 只有仍含旧格式值时才进入变更锁迁移,迁移写入与恢复共用同一代次屏障。
+    const current = await readRawCredentialRecord(filePath);
+    if (!Object.values(current).some((value) => cipher.needsMigration?.(value))) return current;
+    return withCredentialFileMutation(filePath, async () => {
+      const locked = await readRawCredentialRecord(filePath, true);
+      const migrated = await migrateCredentialRecord(locked, cipher);
+      if (migrated)
+        await atomicWritePrivateTextFile(filePath, `${JSON.stringify(migrated, null, 2)}\n`);
+      return migrated ?? locked;
+    });
+  };
+  const mutate = (
+    mutation: (raw: Record<string, string>) => void | boolean | Promise<void | boolean>,
+  ) =>
+    mutateRawCredentialRecord(filePath, async (raw) => {
+      const migrated = await migrateCredentialRecord(raw, cipher);
+      if (migrated) Object.assign(raw, migrated);
+      return mutation(raw);
+    });
+
+  const loadMany = async (keys: readonly string[]): Promise<Record<string, string | null>> => {
+    const raw = await readCurrent();
+    return Object.fromEntries(
+      await Promise.all(
+        keys.map(async (key) => {
+          const value = raw[validateCredentialKey(key)];
+          return [key, value === undefined ? null : await cipher.decrypt(value)];
+        }),
+      ),
+    );
+  };
+  const updateMany: SharedZCodeCredentialStore["updateMany"] = async (changes, options) => {
+    const entries = await Promise.all(
+      Object.entries(changes).map(
+        async ([key, value]) =>
+          [
+            validateCredentialKey(key),
+            value === null ? null : await cipher.encrypt(validateCredentialValue(value)),
+          ] as const,
+      ),
+    );
+    const expected = Object.entries(options?.expected ?? {}).map(
+      ([key, value]) =>
+        [
+          validateCredentialKey(key),
+          value === null ? null : validateCredentialValue(value),
+        ] as const,
+    );
+    let committed = false;
+    await mutate(async (raw) => {
+      for (const [key, value] of expected) {
+        if ((raw[key] === undefined ? null : await cipher.decrypt(raw[key])) !== value)
+          return false;
+      }
+      options?.assertCurrent?.();
+      for (const [key, value] of entries) {
+        if (value === null) delete raw[key];
+        else raw[key] = value;
+      }
+      if (entries.some(([key]) => key === "zcodejwttoken" || key.startsWith("oauth:")))
+        raw[OAUTH_SESSION_REVISION_KEY] = await cipher.encrypt(randomUUID());
+      options?.assertCurrent?.();
+      committed = true;
+    });
+    return committed;
+  };
+
+  const loadOAuthSessionSnapshot = async (): Promise<Record<string, string | null>> => {
+    const raw = await readCurrent();
+    const activeRaw = raw[SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider];
+    const provider = activeRaw === undefined ? null : await cipher.decrypt(activeRaw);
+    const keys = [
+      SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider,
+      SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken,
+      OAUTH_SESSION_REVISION_KEY,
+      ...(provider
+        ? [
+            `oauth:${provider}:access_token`,
+            `oauth:${provider}:refresh_token`,
+            `oauth:${provider}:user_info`,
+          ]
+        : []),
+    ];
+    return Object.fromEntries(
+      await Promise.all(
+        keys.map(async (key) => [
+          key,
+          raw[key] === undefined ? null : await cipher.decrypt(raw[key]),
+        ]),
+      ),
+    );
+  };
 
   return {
     filePath,
+    async assertWritable() {
+      // Bug 原因:空库读取不调用 cipher,首次访问系统库发生在登录授权之后的写入时。
+      // 加密探针值走与首次写入相同的取密钥路径(必要时创建密钥),结果丢弃。
+      await cipher.encrypt(WRITE_PROBE_VALUE);
+    },
+    async captureRecoveryGuard() {
+      const run = await captureCredentialFileGuard(filePath);
+      return { run, commit: (operation) => withFileLock(filePath, () => run(operation)) };
+    },
 
+    updateMany,
+    loadOAuthSessionSnapshot,
     async clearZaiLoginCredentials(): Promise<void> {
-      await mutateRawCredentialRecord(filePath, async (rawCredentials) => {
-        const activeProviderRaw = rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider];
-        const activeProvider = activeProviderRaw ? cipher.decrypt(activeProviderRaw) : null;
-        delete rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken];
-        delete rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zaiRefreshToken];
-        delete rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zaiUserInfo];
-        delete rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken];
-        if (activeProvider === ZAI_PROVIDER_ID) {
-          delete rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider];
-        }
-      });
+      const expected = await loadOAuthSessionSnapshot();
+      await updateMany(
+        {
+          [SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken]: null,
+          [SHARED_ZCODE_CREDENTIAL_KEYS.zaiRefreshToken]: null,
+          [SHARED_ZCODE_CREDENTIAL_KEYS.zaiUserInfo]: null,
+          ...(expected[SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider] === ZAI_PROVIDER_ID
+            ? {
+                [SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider]: null,
+                [SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken]: null,
+                [SHARED_ZCODE_CREDENTIAL_KEYS.linkedBigModel]: null,
+              }
+            : {}),
+        },
+        { expected },
+      );
     },
 
     async delete(key: string): Promise<void> {
       const validatedKey = validateCredentialKey(key);
-      await mutateRawCredentialRecord(filePath, (rawCredentials) => {
+      await mutate(async (rawCredentials) => {
         delete rawCredentials[validatedKey];
       });
     },
@@ -100,11 +245,11 @@ export function createSharedZCodeCredentialStore(
       const validatedKey = validateCredentialKey(key);
       const validatedExpectedValue = validateCredentialValue(expectedValue);
       let deleted = false;
-      await mutateRawCredentialRecord(filePath, (rawCredentials) => {
+      await mutate(async (rawCredentials) => {
         const encryptedValue = rawCredentials[validatedKey];
         if (
           encryptedValue === undefined ||
-          cipher.decrypt(encryptedValue) !== validatedExpectedValue
+          (await cipher.decrypt(encryptedValue)) !== validatedExpectedValue
         ) {
           return;
         }
@@ -122,11 +267,12 @@ export function createSharedZCodeCredentialStore(
       );
       if (validatedEntries.length === 0) return {};
       const deleted: Record<string, boolean> = {};
-      await mutateRawCredentialRecord(filePath, (rawCredentials) => {
+      await mutate(async (rawCredentials) => {
         for (const [key, expectedValue] of validatedEntries) {
           const encryptedValue = rawCredentials[key];
           const matches =
-            encryptedValue !== undefined && cipher.decrypt(encryptedValue) === expectedValue;
+            encryptedValue !== undefined &&
+            (await cipher.decrypt(encryptedValue)) === expectedValue;
           deleted[key] = matches;
           if (matches) delete rawCredentials[key];
         }
@@ -150,11 +296,11 @@ export function createSharedZCodeCredentialStore(
       const validatedExpectedValue = validateCredentialValue(expectedGuardValue);
       const validatedKeys = keysToDelete.map(validateCredentialKey);
       let deleted = false;
-      await mutateRawCredentialRecord(filePath, (rawCredentials) => {
+      await mutate(async (rawCredentials) => {
         const encryptedGuard = rawCredentials[validatedGuardKey];
         if (
           encryptedGuard === undefined ||
-          cipher.decrypt(encryptedGuard) !== validatedExpectedValue
+          (await cipher.decrypt(encryptedGuard)) !== validatedExpectedValue
         ) {
           return;
         }
@@ -165,7 +311,7 @@ export function createSharedZCodeCredentialStore(
     },
 
     async load(key: string): Promise<string | null> {
-      const rawCredentials = await readRawCredentialRecord(filePath);
+      const rawCredentials = await readCurrent();
       const rawValue = rawCredentials[validateCredentialKey(key)];
       if (rawValue === undefined) {
         return null;
@@ -173,16 +319,7 @@ export function createSharedZCodeCredentialStore(
       return cipher.decrypt(rawValue);
     },
 
-    async loadMany(keys: readonly string[]): Promise<Record<string, string | null>> {
-      const validatedKeys = keys.map(validateCredentialKey);
-      const rawCredentials = await readRawCredentialRecord(filePath);
-      return Object.fromEntries(
-        validatedKeys.map((key) => {
-          const rawValue = rawCredentials[key];
-          return [key, rawValue === undefined ? null : cipher.decrypt(rawValue)];
-        }),
-      );
-    },
+    loadMany,
 
     onDidChange(listener: () => void | Promise<void>): () => void {
       let listeners = credentialChangeListeners.get(filePath);
@@ -198,23 +335,11 @@ export function createSharedZCodeCredentialStore(
     },
 
     async save(key: string, value: string): Promise<void> {
-      const validatedKey = validateCredentialKey(key);
-      const encryptedValue = cipher.encrypt(validateCredentialValue(value));
-      await mutateRawCredentialRecord(filePath, (rawCredentials) => {
-        rawCredentials[validatedKey] = encryptedValue;
-      });
+      await updateMany({ [key]: value });
     },
 
     async saveMany(entries: Readonly<Record<string, string>>): Promise<void> {
-      const encryptedEntries = Object.entries(entries).map(
-        ([key, value]) =>
-          [validateCredentialKey(key), cipher.encrypt(validateCredentialValue(value))] as const,
-      );
-      await mutateRawCredentialRecord(filePath, (rawCredentials) => {
-        for (const [key, encryptedValue] of encryptedEntries) {
-          rawCredentials[key] = encryptedValue;
-        }
-      });
+      await updateMany(entries);
     },
 
     async saveReplacing(
@@ -223,9 +348,9 @@ export function createSharedZCodeCredentialStore(
       replacedKeys: readonly string[],
     ): Promise<void> {
       const validatedKey = validateCredentialKey(key);
-      const encryptedValue = cipher.encrypt(validateCredentialValue(value));
+      const encryptedValue = await cipher.encrypt(validateCredentialValue(value));
       const validatedReplacedKeys = replacedKeys.map(validateCredentialKey);
-      await mutateRawCredentialRecord(filePath, (rawCredentials) => {
+      await mutate(async (rawCredentials) => {
         rawCredentials[validatedKey] = encryptedValue;
         for (const replacedKey of validatedReplacedKeys) {
           if (replacedKey !== validatedKey) delete rawCredentials[replacedKey];
@@ -233,48 +358,32 @@ export function createSharedZCodeCredentialStore(
       });
     },
 
-    async saveZaiLoginCredentials(payload: ZaiLoginCredentialPayload): Promise<void> {
-      const encryptedCredentials = {
-        activeProvider: cipher.encrypt(ZAI_PROVIDER_ID),
-        accessToken: cipher.encrypt(validateCredentialValue(payload.accessToken)),
-        jwtToken: cipher.encrypt(validateCredentialValue(payload.jwtToken)),
-        userInfo: cipher.encrypt(JSON.stringify(payload.user)),
-      };
-      await mutateRawCredentialRecord(filePath, (rawCredentials) => {
-        rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider] =
-          encryptedCredentials.activeProvider;
-        rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken] =
-          encryptedCredentials.accessToken;
-        rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken] = encryptedCredentials.jwtToken;
-        rawCredentials[SHARED_ZCODE_CREDENTIAL_KEYS.zaiUserInfo] = encryptedCredentials.userInfo;
-      });
+    async saveZaiLoginCredentials(payload, expected, assertCurrent): Promise<void> {
+      const snapshot = expected ?? (await loadOAuthSessionSnapshot());
+      const committed = await updateMany(
+        {
+          ...Object.fromEntries(
+            Object.values(SHARED_ZCODE_CREDENTIAL_KEYS).map((key) => [key, null]),
+          ),
+          [SHARED_ZCODE_CREDENTIAL_KEYS.activeProvider]: ZAI_PROVIDER_ID,
+          [SHARED_ZCODE_CREDENTIAL_KEYS.zaiAccessToken]: payload.accessToken,
+          [SHARED_ZCODE_CREDENTIAL_KEYS.zcodeJwtToken]: payload.jwtToken,
+          [SHARED_ZCODE_CREDENTIAL_KEYS.zaiUserInfo]: JSON.stringify(payload.user),
+        },
+        { expected: snapshot, assertCurrent },
+      );
+      if (!committed) throw new Error("OAuth session changed before login commit");
     },
   };
 }
 
-export function loadSharedZCodeCredentialSync(
+/** 所有凭据读取均为异步,避免系统密钥库阻塞 UI 或 CLI 事件循环。 */
+export async function loadSharedZCodeCredential(
   key: string,
   options: SharedZCodeCredentialStoreOptions = {},
-): string | undefined {
-  const filePath = resolveSharedZCodeCredentialsPath(options);
-  if (!existsSync(filePath)) {
-    return undefined;
-  }
-
-  try {
-    const raw = readFileSync(filePath, "utf-8");
-    const parsed = JSON.parse(raw);
-    const record = parseCredentialRecord(parsed);
-    const rawValue = record[validateCredentialKey(key)];
-    if (rawValue === undefined) {
-      return undefined;
-    }
-    const cipher = options.cipher ?? createZCodeCredentialCipher({ env: options.env });
-    const decrypted = cipher.decrypt(rawValue);
-    return decrypted.trim().length > 0 ? decrypted : undefined;
-  } catch {
-    return undefined;
-  }
+): Promise<string | undefined> {
+  const value = await createSharedZCodeCredentialStore(options).load(key);
+  return value?.trim() ? value : undefined;
 }
 
 export function resolveSharedZCodeCredentialsPath(
@@ -289,10 +398,18 @@ export function resolveSharedZCodeCredentialsPath(
   return join(resolveUserPath(baseDir), ".zcode", "v2", "credentials.json");
 }
 
-async function readRawCredentialRecord(filePath: string): Promise<Record<string, string>> {
-  let raw: string;
+async function readRawCredentialRecord(
+  filePath: string,
+  locked = false,
+): Promise<Record<string, string>> {
+  if (locked) return readRawCredentialRecordUnchecked(filePath);
+  return withCredentialFileRead(filePath, () => readRawCredentialRecordUnchecked(filePath));
+}
+
+async function readRawCredentialRecordUnchecked(filePath: string): Promise<Record<string, string>> {
+  let raw: Buffer;
   try {
-    raw = await readFile(filePath, "utf-8");
+    raw = await readFile(filePath);
   } catch (error) {
     if (getErrorCode(error) === "ENOENT") {
       return {};
@@ -301,7 +418,8 @@ async function readRawCredentialRecord(filePath: string): Promise<Record<string,
   }
 
   try {
-    return parseCredentialRecord(JSON.parse(raw));
+    // 宽松 UTF-8 解码会把坏字节替换后继续使用或写回,违背与 Desktop 共用的损坏边界。
+    return parseCredentialRecord(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw)));
   } catch (error) {
     // 损坏的凭据文件若被当成空对象继续保存,会一次性抹掉其他进程的全部凭据。
     // 先保留现场再失败,调用方必须显式处理恢复,不能静默覆盖。
@@ -315,15 +433,17 @@ async function readRawCredentialRecord(filePath: string): Promise<Record<string,
 
 async function mutateRawCredentialRecord(
   filePath: string,
-  mutation: (value: Record<string, string>) => void | Promise<void>,
+  mutation: (value: Record<string, string>) => void | boolean | Promise<void | boolean>,
 ): Promise<void> {
   // CLI、设置页和 session 可能位于不同 Node 进程;锁必须覆盖完整的
   // read-modify-write,单独原子 rename 只能防半写,不能防旧快照覆盖新 key。
-  await withFileLock(filePath, async () => {
-    const value = await readRawCredentialRecord(filePath);
-    await mutation(value);
+  const committed = await withCredentialFileMutation(filePath, async () => {
+    const value = await readRawCredentialRecord(filePath, true);
+    if ((await mutation(value)) === false) return false;
     await atomicWritePrivateTextFile(filePath, `${JSON.stringify(value, null, 2)}\n`);
+    return true;
   });
+  if (!committed) return;
   const listeners = [...(credentialChangeListeners.get(filePath) ?? [])];
   // 同进程的 Registry Source 需要在登录返回前观察到新凭据;单个监听者失败不应
   // 把已经原子落盘的 Credential 伪装成写入失败。

+ 225 - 16
apps/zcode-cli/packages/adapters/src/config/config-factory.ts

@@ -1,5 +1,7 @@
 // Config Factory - Load and merge all config sources
 
+import { readFile, realpath, stat } from "node:fs/promises";
+import { homedir } from "node:os";
 import { resolve } from "node:path";
 import type {
   ConfigPort,
@@ -20,8 +22,20 @@ import {
   resolveWorkspaceHookRuntimeRoot,
   type WorkspaceHookRuntimeRoot,
 } from "@zcode/shared/workspace-hook-discovery";
+import {
+  parseManagedWorktreePath,
+  resolveManagedWorktreeRoot,
+  resolveWorkspaceHookTrustIdentity,
+  type WorkspaceHookTrustIdentityFs,
+} from "@zcode/shared/managed-worktree";
 import { createConfigPort } from "./index.js";
-import { loadFileConfig, getDefaultConfigPath, type LoadedConfig } from "./file-config.adapter.js";
+import {
+  loadFileConfig,
+  getDefaultConfigPath,
+  migrateVisualizeDefaultOffInFileConfig,
+  VISUALIZE_PLUGIN_ID,
+  type LoadedConfig,
+} from "./file-config.adapter.js";
 import { parseEnvConfig } from "./env-config.adapter.js";
 import { mergeConfigs, createPrioritizedConfig } from "./config-merger.js";
 import { createNodeLoggerFactory } from "../logging/index.js";
@@ -42,6 +56,12 @@ export interface ConfigFactoryOptions {
   workingDirectory?: string;
   /** Opaque workspace identity supplied by the existing Host resolver; local callers fall back to workspacePath. */
   workspaceIdentity?: string;
+  /**
+   * Hook Trust identity(D23),由调用方经 resolveWorkspaceHookTrustIdentityForWorkspace 预先算好。
+   * createConfig 是同步函数,而 resolver 需要异步读取 .git 链接,所以不在这里解析。
+   * 缺省时沿用旧规则(远程 identity 优先,否则工作目录)。
+   */
+  workspaceHookTrustIdentity?: string;
   /** Environment variables (default: process.env) */
   env?: Record<string, string | undefined>;
   /** CLI overrides (highest priority) */
@@ -110,12 +130,88 @@ export interface PluginConfigSources {
   enabled: Record<string, PluginConfigScope>;
   marketplaces: Record<string, PluginConfigScope>;
   options: Record<string, Record<string, PluginConfigScope>>;
+  /**
+   * 插件选项的原始配置层,按优先级从低到高(user,再按发现顺序的项目配置文件)。
+   * 合并后的 options 分不出值来自哪一层;敏感选项要按层叠加私有文件,所以保留原始层。
+   */
+  optionLayers: PluginOptionLayer[];
   paths: {
     user: string;
     workspace: string | undefined;
   };
 }
 
+export interface PluginOptionLayer {
+  scope: PluginConfigScope;
+  path: string;
+  /** workspace 层配置文件的 baseDir;私有文件按它找 workspace 条目。user 层没有。 */
+  workspaceRoot?: string;
+  options: Record<string, Record<string, string | number | boolean>>;
+}
+
+interface LoadedConfigSources {
+  userConfigResult: LoadedConfig;
+  discoveredProjectConfigs: ProjectConfigDiscovery;
+}
+
+function loadConfigSources(options: ConfigFactoryOptions): LoadedConfigSources {
+  const userConfigResult: LoadedConfig = options.skipUserConfig
+    ? { config: {}, diagnostics: [], path: getDefaultConfigPath(), loaded: false }
+    : loadFileConfig(options.userConfigPath);
+  const discoveredProjectConfigs: ProjectConfigDiscovery = options.workingDirectory
+    ? loadProjectConfigs(options.workingDirectory, options.projectConfigPath)
+    : options.projectConfigPath
+      ? summarizeProjectConfigs([
+          loadProjectConfigFile(options.projectConfigPath, {
+            discoveryOrder: 0,
+            explicitProjectConfig: true,
+          }),
+        ])
+      : summarizeProjectConfigs([]);
+  return { userConfigResult, discoveredProjectConfigs };
+}
+
+/** 复用一次读取的配置层;可选迁移失败只影响该层,不能阻断会话装配。 */
+export async function createConfigWithPluginMigrations(
+  options: ConfigFactoryOptions = {},
+): Promise<ConfigResult> {
+  const sources = loadConfigSources(options);
+  const migrationResults = new Map<string, boolean | undefined>();
+  for (const file of [sources.userConfigResult, ...sources.discoveredProjectConfigs.files]) {
+    if (!file.pendingVisualizeMigration) continue;
+    let enabled: boolean | undefined;
+    if (migrationResults.has(file.path)) {
+      // 同一文件可能同时用于用户层和显式项目层;每次装载只迁移、告警一次。
+      enabled = migrationResults.get(file.path);
+    } else {
+      try {
+        enabled = await migrateVisualizeDefaultOffInFileConfig(file.path);
+      } catch (error) {
+        // 旧实现让只读仓库或文件锁失败连带阻断 App/技能查询。仅在本次配置层关闭,
+        // 不写完成标记;合并仍遵循原有优先级,不能盖掉较高层之后明确开启的值。
+        enabled = false;
+        const failure = error as NodeJS.ErrnoException & { cause?: NodeJS.ErrnoException };
+        const loggerFactory =
+          options.loggerFactory ?? createNodeLoggerFactory({ env: options.env });
+        loggerFactory
+          .createLogger("zcode")
+          .child({ module: "adapters.config" })
+          .warn("Visualize config migration deferred", {
+            event: "config.visualize_migration.deferred",
+            configPath: file.path,
+            errorCode: failure?.code ?? failure?.cause?.code ?? "UNKNOWN",
+          });
+      }
+      migrationResults.set(file.path, enabled);
+    }
+    const enabledPlugins = { ...file.config.plugins?.enabledPlugins };
+    if (enabled === undefined) delete enabledPlugins[VISUALIZE_PLUGIN_ID];
+    else enabledPlugins[VISUALIZE_PLUGIN_ID] = enabled;
+    file.config = { ...file.config, plugins: { ...file.config.plugins, enabledPlugins } };
+  }
+  return assembleConfig(options, sources);
+}
+
 /**
  * Create ConfigPort with all sources merged
  *
@@ -127,16 +223,17 @@ export interface PluginConfigSources {
  * 5. CLI overrides
  */
 export function createConfig(options: ConfigFactoryOptions = {}): ConfigResult {
+  return assembleConfig(options, loadConfigSources(options));
+}
+
+function assembleConfig(options: ConfigFactoryOptions, sources: LoadedConfigSources): ConfigResult {
+  const { userConfigResult, discoveredProjectConfigs } = sources;
   // 1. System defaults
   const configs: ReturnType<typeof createPrioritizedConfig>[] = [
     createPrioritizedConfig(DefaultRuntimeConfig, ConfigScope.System),
   ];
 
   // 2. User config file
-  const userConfigResult: LoadedConfig = options.skipUserConfig
-    ? { config: {}, diagnostics: [], path: getDefaultConfigPath(), loaded: false }
-    : loadFileConfig(options.userConfigPath);
-
   if (userConfigResult.loaded) {
     configs.push(
       createPrioritizedConfig(
@@ -150,16 +247,6 @@ export function createConfig(options: ConfigFactoryOptions = {}): ConfigResult {
   }
 
   // 3. Project config files
-  const discoveredProjectConfigs: ProjectConfigDiscovery = options.workingDirectory
-    ? loadProjectConfigs(options.workingDirectory, options.projectConfigPath)
-    : options.projectConfigPath
-      ? summarizeProjectConfigs([
-          loadProjectConfigFile(options.projectConfigPath, {
-            discoveryOrder: 0,
-            explicitProjectConfig: true,
-          }),
-        ])
-      : summarizeProjectConfigs([]);
   // explicit 配置曾在 auto-discovery 之后手工追加并自行编号,绕过 shared
   // canonical-path dedup;同一文件会进入 snapshot 两次并使既有 Trust 全部 stale。
   // 修法:有 workspace 时由 loadProjectConfigs 统一走 discoverWorkspaceHookConfigPaths,
@@ -218,7 +305,10 @@ export function createConfig(options: ConfigFactoryOptions = {}): ConfigResult {
   ]);
   const workspacePath = resolve(options.workingDirectory ?? process.cwd());
   const workspaceHookSnapshotData = buildWorkspaceHookBundleSnapshot({
-    workspaceIdentity: options.workspaceIdentity?.trim() || workspacePath,
+    workspaceIdentity:
+      options.workspaceHookTrustIdentity?.trim() ||
+      options.workspaceIdentity?.trim() ||
+      workspacePath,
     workspacePath,
     sources: projectSummary.hookCandidates,
     runtimeRoot: workspaceHookRuntimeRoot,
@@ -232,7 +322,9 @@ export function createConfig(options: ConfigFactoryOptions = {}): ConfigResult {
   const merged = mergeConfigs(...configs);
   const pluginConfigSources = resolvePluginConfigSources({
     projectConfig: projectConfigResult.config,
+    projectFiles: projectConfigFiles,
     projectPath: projectConfigResult.path,
+    skipUserConfig: options.skipUserConfig === true,
     userConfig: userConfigResult.config,
     userPath: userConfigResult.path,
   });
@@ -289,7 +381,9 @@ export function createConfig(options: ConfigFactoryOptions = {}): ConfigResult {
 
 function resolvePluginConfigSources(input: {
   projectConfig: RuntimeConfigPatch;
+  projectFiles: readonly ProjectConfigFile[];
   projectPath: string | undefined;
+  skipUserConfig: boolean;
   userConfig: RuntimeConfigPatch;
   userPath: string;
 }): PluginConfigSources {
@@ -326,6 +420,23 @@ function resolvePluginConfigSources(input: {
     enabled,
     marketplaces,
     options,
+    optionLayers: [
+      ...(input.skipUserConfig
+        ? []
+        : [
+            {
+              scope: "user" as const,
+              path: input.userPath,
+              options: input.userConfig.plugins?.options ?? {},
+            },
+          ]),
+      ...input.projectFiles.map((file) => ({
+        scope: "workspace" as const,
+        path: file.path,
+        workspaceRoot: file.baseDir,
+        options: file.config.plugins?.options ?? {},
+      })),
+    ],
     paths: {
       user: input.userPath,
       workspace: input.projectPath,
@@ -464,3 +575,101 @@ function summarizeOptionalProjectConfig(files: ProjectConfigFile[]): OptionalPat
     loaded: true,
   };
 }
+
+// ── Hook Trust identity(docs/specs/workspace-hook-trust.md D23)──
+// 唯一 resolver 在 @zcode/shared/managed-worktree;这里只提供 Node 只读文件端口与数据根目录。
+
+const ZCODE_DATA_BASE_DIR_ENV_KEY = "ZCODE_DATA_BASE_DIR";
+
+/** 与 Host getDataBaseDir 同规则:ZCODE_DATA_BASE_DIR 优先,空值回落 homedir。 */
+export function resolveZCodeDataBaseDir(
+  env: Record<string, string | undefined> = process.env,
+): string {
+  return env[ZCODE_DATA_BASE_DIR_ENV_KEY]?.trim() || homedir();
+}
+
+const nodeTrustIdentityFs: WorkspaceHookTrustIdentityFs = {
+  readFile: (path) => readFile(path, "utf8"),
+  realpath: (path) => realpath(path),
+  stat: async (path) => {
+    try {
+      const info = await stat(path);
+      return { isFile: info.isFile(), isDirectory: info.isDirectory() };
+    } catch (error) {
+      if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+      throw error;
+    }
+  },
+};
+
+/**
+ * 计算 workspace 的 Hook Trust identity。远程 identity 原样返回;本地受管 worktree 严格校验通过后
+ * 归一为源仓库对应路径;其余情况返回 workspacePath(调用方负责传入已规范化的路径)。
+ */
+export function resolveWorkspaceHookTrustIdentityForWorkspace(input: {
+  workspacePath: string;
+  workspaceIdentity?: string;
+  env?: Record<string, string | undefined>;
+}): Promise<string> {
+  return resolveWorkspaceHookTrustIdentity(
+    {
+      workspacePath: input.workspacePath,
+      ...(input.workspaceIdentity ? { workspaceIdentity: input.workspaceIdentity } : {}),
+      dataBaseDir: resolveZCodeDataBaseDir(input.env),
+    },
+    nodeTrustIdentityFs,
+  );
+}
+
+/** 本地会话目录相对 workspace 目录的文件系统关系,见 classifyLocalSessionDirectory。 */
+export type LocalSessionDirectoryRelation = "same" | "worktree" | "removed-worktree" | "other";
+
+/**
+ * 本地会话目录与 workspace 目录的文件系统关系(docs/git/worktree.md §9.3 归属判定):
+ * - same:同一个真实目录(realpath 比较,吸收 Host key 保留的输入大小写与磁盘真实大小写的差异);
+ * - worktree:目录是受管 worktree,严格 resolver 映射回该真实目录;
+ * - removed-worktree:目录位于受管 worktree 布局内但已不存在,文件系统无法证明归属,调用方只能用
+ *   创建时持久化的身份兜底;
+ * - other:不属于。
+ * 只做文件系统判定,不使用 projectID:projectID 是有损 slug(转小写、替换字符、截断),
+ * 不同项目可能相同,不能作为会执行代码的冷恢复/激活路径的归属证明。
+ */
+export async function classifyLocalSessionDirectory(input: {
+  directory: string;
+  workspacePath: string;
+  env?: Record<string, string | undefined>;
+}): Promise<LocalSessionDirectoryRelation> {
+  const directory = resolve(input.directory);
+  const workspacePath = resolve(input.workspacePath);
+  if (directory === workspacePath) return "same";
+  const [realDirectory, realWorkspace] = await Promise.all([
+    realpathOrNull(directory),
+    realpathOrNull(workspacePath),
+  ]);
+  if (realDirectory !== null && realDirectory === realWorkspace) return "same";
+  const dataBaseDir = resolveZCodeDataBaseDir(input.env);
+  if (realDirectory === null) {
+    // 会话 cwd 落盘时就是 realpath;受管根目录本身可能经过软链,两种形态都认。
+    const managedRoot = resolveManagedWorktreeRoot(dataBaseDir);
+    const realManagedRoot = (await realpathOrNull(managedRoot)) ?? managedRoot;
+    return parseManagedWorktreePath(realManagedRoot, directory) ||
+      parseManagedWorktreePath(managedRoot, directory)
+      ? "removed-worktree"
+      : "other";
+  }
+  if (realWorkspace === null) return "other";
+  const mapped = await resolveWorkspaceHookTrustIdentity(
+    { workspacePath: directory, dataBaseDir },
+    nodeTrustIdentityFs,
+  );
+  if (mapped === directory) return "other";
+  return (await realpathOrNull(mapped)) === realWorkspace ? "worktree" : "other";
+}
+
+async function realpathOrNull(path: string): Promise<string | null> {
+  try {
+    return await realpath(path);
+  } catch {
+    return null;
+  }
+}

+ 195 - 119
apps/zcode-cli/packages/adapters/src/config/file-config.adapter.ts

@@ -1,17 +1,12 @@
 // File Config Adapter - Load and patch JSON configuration files
 
-import {
-  existsSync,
-  readFileSync,
-  renameSync,
-  unlinkSync,
-  writeFileSync,
-} from "node:fs";
+import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
 import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
 import { homedir } from "node:os";
 import { basename, dirname, join, resolve } from "node:path";
 import type { RuntimeConfigPatch, UiLocale } from "@zcode/contracts";
 import { z } from "zod";
+import { withFileLock } from "@zcode/shared/node";
 import {
   CANONICAL_CUA_PLUGIN_ID,
   canonicalizePluginId,
@@ -32,6 +27,8 @@ export interface LoadedConfig {
   diagnostics: ConfigDiagnostic[];
   path: string;
   loaded: boolean;
+  /** 已读取的旧开关需要异步迁移;只在加载快照中传递,不写入配置。 */
+  pendingVisualizeMigration?: boolean;
 }
 
 export interface UiLocalePatchResult {
@@ -59,6 +56,9 @@ export interface PluginRemovePatchResult {
   removedOptions: boolean;
 }
 
+export const VISUALIZE_PLUGIN_ID = "visualize@zcode-plugins-official";
+const VISUALIZE_MIGRATION_KEY = "visualizeDefaultOffMigrated";
+
 const DEFAULT_CONFIG_FILE = "config.json";
 const DEFAULT_BASE_DIR = "~/.zcode/cli";
 
@@ -107,6 +107,7 @@ export function loadFileConfig(filePath?: string, options: FileConfigOptions = {
       diagnostics: attachDiagnosticFilePath(result.diagnostics, resolvedPath),
       path: resolvedPath,
       loaded: true,
+      ...(needsVisualizeMigration(parsed) ? { pendingVisualizeMigration: true } : {}),
     };
   } catch (error) {
     return {
@@ -163,10 +164,7 @@ function migratePluginConfigInFile(value: unknown): Record<string, unknown> | un
   return changed ? { ...value, plugins: nextPlugins } : undefined;
 }
 
-function persistPluginConfigMigration(
-  filePath: string,
-  value: Record<string, unknown>,
-): void {
+function persistPluginConfigMigration(filePath: string, value: Record<string, unknown>): void {
   const tempPath = `${filePath}.migrate.${process.pid}.${Date.now()}.tmp`;
   try {
     writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, {
@@ -184,6 +182,35 @@ function persistPluginConfigMigration(
   }
 }
 
+function needsVisualizeMigration(parsed: unknown): boolean {
+  if (!isRecord(parsed) || !isRecord(parsed.plugins)) return false;
+  const plugins = parsed.plugins;
+  const enabled = isRecord(plugins.enabledPlugins) ? plugins.enabledPlugins : {};
+  return (
+    plugins[VISUALIZE_MIGRATION_KEY] !== true && typeof enabled[VISUALIZE_PLUGIN_ID] === "boolean"
+  );
+}
+
+/** 只处理加载时发现的待迁移文件,返回锁内观察到的开关,避免沿用迁移前的旧值。 */
+export async function migrateVisualizeDefaultOffInFileConfig(
+  filePath: string,
+): Promise<boolean | undefined> {
+  const resolvedPath = resolvePath(filePath);
+  return withFileLock(resolvedPath, async () => {
+    // 只锁写入不能防止迟到的启动快照覆盖刚刚重新开启的值,必须在同一文件锁内重读。
+    const current = await readJsonConfigFileOrEmpty(resolvedPath);
+    if (needsVisualizeMigration(current)) {
+      await atomicWriteJson(resolvedPath, patchPluginEnabled(current, VISUALIZE_PLUGIN_ID, false));
+      return false;
+    }
+    const plugins = isRecord(current.plugins) ? current.plugins : {};
+    const enabled = isRecord(plugins.enabledPlugins)
+      ? plugins.enabledPlugins[VISUALIZE_PLUGIN_ID]
+      : undefined;
+    return typeof enabled === "boolean" ? enabled : undefined;
+  });
+}
+
 function createConfigFileInvalidDiagnostic(error: unknown, filePath: string): ConfigDiagnostic {
   return {
     code: "config_file_invalid",
@@ -225,14 +252,16 @@ export async function updateUiLocaleInFileConfig(
   locale: UiLocale,
 ): Promise<UiLocalePatchResult> {
   const resolvedPath = resolvePath(filePath);
-  const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
-  const next = patchUiLocale(parsed, locale);
+  return withFileLock(resolvedPath, async () => {
+    const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
+    const next = patchUiLocale(parsed, locale);
 
-  await atomicWriteJson(resolvedPath, next);
-  return {
-    locale,
-    path: resolvedPath,
-  };
+    await atomicWriteJson(resolvedPath, next);
+    return {
+      locale,
+      path: resolvedPath,
+    };
+  });
 }
 
 /**
@@ -244,15 +273,17 @@ export async function updatePluginEnabledInFileConfig(
   enabled: boolean,
 ): Promise<PluginEnabledPatchResult> {
   const resolvedPath = resolvePath(filePath);
-  const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
-  const next = patchPluginEnabled(parsed, pluginId, enabled);
+  return withFileLock(resolvedPath, async () => {
+    const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
+    const next = patchPluginEnabled(parsed, pluginId, enabled);
 
-  await atomicWriteJson(resolvedPath, next);
-  return {
-    enabled,
-    path: resolvedPath,
-    pluginId,
-  };
+    await atomicWriteJson(resolvedPath, next);
+    return {
+      enabled,
+      path: resolvedPath,
+      pluginId,
+    };
+  });
 }
 
 /**
@@ -267,30 +298,33 @@ export async function enablePluginsByDefaultInFileConfig(
   pluginIds: readonly string[],
 ): Promise<{ enabledIds: string[]; path: string }> {
   const resolvedPath = resolvePath(filePath);
-  if (pluginIds.length === 0) {
-    return { enabledIds: [], path: resolvedPath };
-  }
-  const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
-  const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
-  const enabledPlugins = isRecord(plugins.enabledPlugins) ? plugins.enabledPlugins : {};
-  const enabledIds = pluginIds.filter(
-    (id) => !Object.prototype.hasOwnProperty.call(enabledPlugins, id),
-  );
-  if (enabledIds.length === 0) {
-    return { enabledIds: [], path: resolvedPath };
-  }
-  const next = {
-    ...parsed,
-    plugins: {
-      ...plugins,
-      enabledPlugins: {
-        ...enabledPlugins,
-        ...Object.fromEntries(enabledIds.map((id) => [id, true])),
+  return withFileLock(resolvedPath, async () => {
+    if (pluginIds.length === 0) {
+      return { enabledIds: [], path: resolvedPath };
+    }
+    const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
+    const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
+    const enabledPlugins = isRecord(plugins.enabledPlugins) ? plugins.enabledPlugins : {};
+    const enabledIds = pluginIds.filter(
+      (id) => !Object.prototype.hasOwnProperty.call(enabledPlugins, id),
+    );
+    if (enabledIds.length === 0) {
+      return { enabledIds: [], path: resolvedPath };
+    }
+    const next = {
+      ...parsed,
+      plugins: {
+        ...plugins,
+        ...(enabledIds.includes(VISUALIZE_PLUGIN_ID) ? { [VISUALIZE_MIGRATION_KEY]: true } : {}),
+        enabledPlugins: {
+          ...enabledPlugins,
+          ...Object.fromEntries(enabledIds.map((id) => [id, true])),
+        },
       },
-    },
-  };
-  await atomicWriteJson(resolvedPath, next);
-  return { enabledIds, path: resolvedPath };
+    };
+    await atomicWriteJson(resolvedPath, next);
+    return { enabledIds, path: resolvedPath };
+  });
 }
 
 /**
@@ -303,16 +337,49 @@ export async function updatePluginOptionsInFileConfig(
   clearOptionKeys: string[] = [],
 ): Promise<PluginOptionsPatchResult> {
   const resolvedPath = resolvePath(filePath);
-  const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
-  const next = patchPluginOptions(parsed, pluginId, options, clearOptionKeys);
+  return withFileLock(resolvedPath, async () => {
+    const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
+    const next = patchPluginOptions(parsed, pluginId, options, clearOptionKeys);
 
-  await atomicWriteJson(resolvedPath, next);
-  return {
-    clearedOptionKeys: clearOptionKeys,
-    options,
-    path: resolvedPath,
-    pluginId,
-  };
+    await atomicWriteJson(resolvedPath, next);
+    return {
+      clearedOptionKeys: clearOptionKeys,
+      options,
+      path: resolvedPath,
+      pluginId,
+    };
+  });
+}
+
+/**
+ * 读取单个配置文件里某个插件的原始选项(不合并其它层)。
+ *
+ * 敏感选项迁移要知道「这个 scope 的 config.json 里有哪些旧明文值」;合并后的有效配置分不出
+ * 值来自哪一层,所以这里直接读目标文件。文件不存在时返回空对象。
+ */
+export async function readPluginOptionsFromFileConfig(
+  filePath: string,
+  pluginId: string,
+): Promise<Record<string, string | number | boolean>> {
+  const parsed = await readJsonConfigFileOrEmpty(resolvePath(filePath));
+  const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
+  const options = isRecord(plugins.options) ? plugins.options : {};
+  const canonicalPluginId = canonicalizePluginId(pluginId);
+  const aliases = pluginIdAliases(canonicalPluginId);
+  const legacyPluginId = aliases.length > 1 ? aliases[1] : undefined;
+  const pluginOptions = isRecord(options[canonicalPluginId])
+    ? options[canonicalPluginId]
+    : legacyPluginId && isRecord(options[legacyPluginId])
+      ? options[legacyPluginId]
+      : {};
+  return Object.fromEntries(
+    Object.entries(pluginOptions).filter(
+      (entry): entry is [string, string | number | boolean] =>
+        typeof entry[1] === "string" ||
+        typeof entry[1] === "number" ||
+        typeof entry[1] === "boolean",
+    ),
+  );
 }
 
 /**
@@ -328,18 +395,20 @@ export async function removePluginFromFileConfig(
   pluginId: string,
 ): Promise<PluginRemovePatchResult> {
   const resolvedPath = resolvePath(filePath);
-  const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
-  const { next, removedEnabled, removedOptions } = patchPluginRemoved(parsed, pluginId);
+  return withFileLock(resolvedPath, async () => {
+    const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
+    const { next, removedEnabled, removedOptions } = patchPluginRemoved(parsed, pluginId);
 
-  if (removedEnabled || removedOptions) {
-    await atomicWriteJson(resolvedPath, next);
-  }
-  return {
-    path: resolvedPath,
-    pluginId,
-    removedEnabled,
-    removedOptions,
-  };
+    if (removedEnabled || removedOptions) {
+      await atomicWriteJson(resolvedPath, next);
+    }
+    return {
+      path: resolvedPath,
+      pluginId,
+      removedEnabled,
+      removedOptions,
+    };
+  });
 }
 
 /**
@@ -353,27 +422,29 @@ export async function removePluginEnabledFromFileConfig(
   pluginId: string,
 ): Promise<{ path: string; pluginId: string; removedEnabled: boolean }> {
   const resolvedPath = resolvePath(filePath);
-  const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
-  const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
-  const enabledPlugins = isRecord(plugins.enabledPlugins) ? plugins.enabledPlugins : {};
-  const aliases = pluginIdAliases(pluginId);
-  const removedEnabled = aliases.some((id) =>
-    Object.prototype.hasOwnProperty.call(enabledPlugins, id),
-  );
-  if (!removedEnabled) {
-    return { path: resolvedPath, pluginId, removedEnabled: false };
-  }
+  return withFileLock(resolvedPath, async () => {
+    const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
+    const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
+    const enabledPlugins = isRecord(plugins.enabledPlugins) ? plugins.enabledPlugins : {};
+    const aliases = pluginIdAliases(pluginId);
+    const removedEnabled = aliases.some((id) =>
+      Object.prototype.hasOwnProperty.call(enabledPlugins, id),
+    );
+    if (!removedEnabled) {
+      return { path: resolvedPath, pluginId, removedEnabled: false };
+    }
 
-  const nextEnabled = { ...enabledPlugins };
-  for (const id of aliases) delete nextEnabled[id];
-  await atomicWriteJson(resolvedPath, {
-    ...parsed,
-    plugins: {
-      ...plugins,
-      enabledPlugins: nextEnabled,
-    },
+    const nextEnabled = { ...enabledPlugins };
+    for (const id of aliases) delete nextEnabled[id];
+    await atomicWriteJson(resolvedPath, {
+      ...parsed,
+      plugins: {
+        ...plugins,
+        enabledPlugins: nextEnabled,
+      },
+    });
+    return { path: resolvedPath, pluginId, removedEnabled: true };
   });
-  return { path: resolvedPath, pluginId, removedEnabled: true };
 }
 
 export interface SuppressedBuiltinPatchResult {
@@ -392,23 +463,25 @@ export async function addSuppressedBuiltinInFileConfig(
   pluginId: string,
 ): Promise<SuppressedBuiltinPatchResult> {
   const resolvedPath = resolvePath(filePath);
-  const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
-  const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
-  const canonicalPluginId = canonicalizePluginId(pluginId);
-  const aliases = pluginIdAliases(canonicalPluginId);
-  const current = Array.isArray(plugins.suppressedBuiltins)
-    ? (plugins.suppressedBuiltins as unknown[]).filter((v): v is string => typeof v === "string")
-    : [];
-  const retained = current.filter((id) => !aliases.includes(id));
-  if (retained.length === current.length && current.includes(canonicalPluginId)) {
+  return withFileLock(resolvedPath, async () => {
+    const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
+    const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
+    const canonicalPluginId = canonicalizePluginId(pluginId);
+    const aliases = pluginIdAliases(canonicalPluginId);
+    const current = Array.isArray(plugins.suppressedBuiltins)
+      ? (plugins.suppressedBuiltins as unknown[]).filter((v): v is string => typeof v === "string")
+      : [];
+    const retained = current.filter((id) => !aliases.includes(id));
+    if (retained.length === current.length && current.includes(canonicalPluginId)) {
+      return { path: resolvedPath, pluginId, suppressed: true };
+    }
+    const next = {
+      ...parsed,
+      plugins: { ...plugins, suppressedBuiltins: [...retained, canonicalPluginId] },
+    };
+    await atomicWriteJson(resolvedPath, next);
     return { path: resolvedPath, pluginId, suppressed: true };
-  }
-  const next = {
-    ...parsed,
-    plugins: { ...plugins, suppressedBuiltins: [...retained, canonicalPluginId] },
-  };
-  await atomicWriteJson(resolvedPath, next);
-  return { path: resolvedPath, pluginId, suppressed: true };
+  });
 }
 
 /**
@@ -420,22 +493,24 @@ export async function removeSuppressedBuiltinInFileConfig(
   pluginId: string,
 ): Promise<SuppressedBuiltinPatchResult> {
   const resolvedPath = resolvePath(filePath);
-  const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
-  const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
-  const aliases = pluginIdAliases(pluginId);
-  const current = Array.isArray(plugins.suppressedBuiltins)
-    ? (plugins.suppressedBuiltins as unknown[]).filter((v): v is string => typeof v === "string")
-    : [];
-  const nextSuppressedBuiltins = current.filter((id) => !aliases.includes(id));
-  if (nextSuppressedBuiltins.length === current.length) {
+  return withFileLock(resolvedPath, async () => {
+    const parsed = await readJsonConfigFileOrEmpty(resolvedPath);
+    const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
+    const aliases = pluginIdAliases(pluginId);
+    const current = Array.isArray(plugins.suppressedBuiltins)
+      ? (plugins.suppressedBuiltins as unknown[]).filter((v): v is string => typeof v === "string")
+      : [];
+    const nextSuppressedBuiltins = current.filter((id) => !aliases.includes(id));
+    if (nextSuppressedBuiltins.length === current.length) {
+      return { path: resolvedPath, pluginId, suppressed: false };
+    }
+    const next = {
+      ...parsed,
+      plugins: { ...plugins, suppressedBuiltins: nextSuppressedBuiltins },
+    };
+    await atomicWriteJson(resolvedPath, next);
     return { path: resolvedPath, pluginId, suppressed: false };
-  }
-  const next = {
-    ...parsed,
-    plugins: { ...plugins, suppressedBuiltins: nextSuppressedBuiltins },
-  };
-  await atomicWriteJson(resolvedPath, next);
-  return { path: resolvedPath, pluginId, suppressed: false };
+  });
 }
 
 /**
@@ -513,6 +588,7 @@ function patchPluginEnabled(
     ...parsed,
     plugins: {
       ...plugins,
+      ...(canonicalPluginId === VISUALIZE_PLUGIN_ID ? { [VISUALIZE_MIGRATION_KEY]: true } : {}),
       enabledPlugins: {
         ...nextEnabledPlugins,
         [canonicalPluginId]: enabled,

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

@@ -470,6 +470,7 @@ export {
   enablePluginsByDefaultInFileConfig,
   removePluginEnabledFromFileConfig,
   updatePluginOptionsInFileConfig,
+  readPluginOptionsFromFileConfig,
   removePluginFromFileConfig,
   addSuppressedBuiltinInFileConfig,
   removeSuppressedBuiltinInFileConfig,
@@ -484,8 +485,30 @@ export { parseEnvConfig, getToolConcurrencyConfig } from "./env-config.adapter.j
 export { ZCodeConfigFileSchema, type ZCodeConfigFile } from "./schema.js";
 export { mergeConfigs, createPrioritizedConfig, getScopePriority } from "./config-merger.js";
 export {
+  classifyLocalSessionDirectory,
   createConfig,
+  createConfigWithPluginMigrations,
+  resolveWorkspaceHookTrustIdentityForWorkspace,
   resolveWorkspaceStorageDir,
+  resolveZCodeDataBaseDir,
   type ConfigFactoryOptions,
   type ConfigResult,
+  type PluginConfigScope,
+  type PluginOptionLayer,
+  type LocalSessionDirectoryRelation,
 } from "./config-factory.js";
+export {
+  PLUGIN_SECRETS_FILE_NAME,
+  createEmptyPluginSecretsFile,
+  getPluginSecretsForScope,
+  normalizePluginConfigPathForComparison,
+  readPluginSecretsFile,
+  removePluginSecrets,
+  setPluginSecrets,
+  updatePluginSecretsFile,
+  type PluginSecretValue,
+  type PluginSecretValues,
+  type PluginSecretsFile,
+  type PluginSecretsReadResult,
+  type PluginSecretsScope,
+} from "./plugin-secrets.adapter.js";

+ 229 - 0
apps/zcode-cli/packages/adapters/src/config/plugin-secrets.adapter.ts

@@ -0,0 +1,229 @@
+// Plugin Secrets Adapter - 敏感插件选项的私有文件(plugin-compat.md「Sensitive Option Storage」)。
+//
+// 只负责文件 I/O、schema 与纯数据变换;「哪些键敏感、读取时怎样叠加到配置层」由 bootstrap 决定。
+// 任何错误信息与返回的诊断原因都不带值。
+
+import { readFile } from "node:fs/promises";
+import { resolve, win32 } from "node:path";
+import { z } from "zod";
+import { atomicWritePrivateTextFile, backupCorruptFile, withFileLock } from "@zcode/shared/node";
+
+export const PLUGIN_SECRETS_FILE_NAME = "plugin-secrets.json";
+const PLUGIN_SECRETS_FILE_VERSION = 1;
+const JSON_INDENT = 2;
+const WINDOWS_PLATFORM = "win32";
+
+const pluginOptionValueSchema = z.union([z.string(), z.number(), z.boolean()]);
+const pluginSecretValuesSchema = z.record(
+  z.string(),
+  z.record(z.string(), pluginOptionValueSchema),
+);
+const pluginSecretsFileSchema = z
+  .object({
+    version: z.literal(PLUGIN_SECRETS_FILE_VERSION),
+    user: pluginSecretValuesSchema,
+    workspaces: z.record(z.string(), pluginSecretValuesSchema),
+  })
+  .strict();
+
+export type PluginSecretValue = z.infer<typeof pluginOptionValueSchema>;
+/** pluginId → key → value。 */
+export type PluginSecretValues = z.infer<typeof pluginSecretValuesSchema>;
+export type PluginSecretsFile = z.infer<typeof pluginSecretsFileSchema>;
+export type PluginSecretsScope = { kind: "user" } | { kind: "workspace"; root: string };
+
+/** 读取结果:读不出时一律按空文件处理,原因只区分「损坏」与「I/O 失败」。 */
+export type PluginSecretsReadResult =
+  | { status: "ok"; file: PluginSecretsFile }
+  | { status: "unreadable"; reason: "corrupt" | "io"; file: PluginSecretsFile };
+
+export function createEmptyPluginSecretsFile(): PluginSecretsFile {
+  return { version: PLUGIN_SECRETS_FILE_VERSION, user: {}, workspaces: {} };
+}
+
+/**
+ * 插件配置路径与 workspace root 的比较键:Windows 不区分大小写、分隔符统一为 `/`。
+ * workspace 配置路径匹配与私有文件的 workspace 键共用这一条规则。
+ */
+export function normalizePluginConfigPathForComparison(
+  path: string,
+  platform: NodeJS.Platform = process.platform,
+): string {
+  if (platform !== WINDOWS_PLATFORM) return resolve(path);
+  return win32.resolve(path).replaceAll("\\", "/").toLowerCase();
+}
+
+/**
+ * 读取路径(无锁):写入是原子 rename,读者只会看到旧文件或新文件。
+ * 损坏时先备份再按空处理;备份失败不影响读取(原文件仍在,下次写入前会再备份)。
+ */
+export async function readPluginSecretsFile(path: string): Promise<PluginSecretsReadResult> {
+  let raw: string;
+  try {
+    raw = await readFile(path, "utf8");
+  } catch (error) {
+    if (getErrorCode(error) === "ENOENT") {
+      return { status: "ok", file: createEmptyPluginSecretsFile() };
+    }
+    return { status: "unreadable", reason: "io", file: createEmptyPluginSecretsFile() };
+  }
+  const parsed = parsePluginSecretsFile(raw);
+  if (parsed) return { status: "ok", file: parsed };
+  await backupCorruptFile(path).catch(() => undefined);
+  return { status: "unreadable", reason: "corrupt", file: createEmptyPluginSecretsFile() };
+}
+
+/**
+ * 在文件锁内读改写。损坏的文件先备份(失败则抛错,不覆盖读不出的证据)再按空处理;
+ * 损坏以外的读取错误向上抛。内容不变且原文件有效时不写盘,避免为空操作创建文件。
+ */
+export async function updatePluginSecretsFile(
+  path: string,
+  mutate: (file: PluginSecretsFile) => PluginSecretsFile,
+): Promise<void> {
+  await withFileLock(path, async () => {
+    const current = await readPluginSecretsFileForWrite(path);
+    const next = prunePluginSecretsFile(mutate(current.file));
+    if (!current.corrupt && JSON.stringify(next) === JSON.stringify(current.file)) return;
+    await atomicWritePrivateTextFile(path, `${JSON.stringify(next, null, JSON_INDENT)}\n`);
+  });
+}
+
+/** 某个 scope 下全部插件的私有值;workspace 按规范化后的 root 匹配。 */
+export function getPluginSecretsForScope(
+  file: PluginSecretsFile,
+  scope: PluginSecretsScope,
+): PluginSecretValues {
+  if (scope.kind === "user") return file.user;
+  const target = normalizePluginConfigPathForComparison(scope.root);
+  const merged: PluginSecretValues = {};
+  // 键按规范化比较,兼容手工编辑留下的大小写或分隔符差异。
+  for (const [root, values] of Object.entries(file.workspaces)) {
+    if (normalizePluginConfigPathForComparison(root) !== target) continue;
+    for (const [pluginId, pluginValues] of Object.entries(values)) {
+      merged[pluginId] = { ...merged[pluginId], ...pluginValues };
+    }
+  }
+  return merged;
+}
+
+/** 写入一个插件在某个 scope 的私有值:先删 clearKeys,再写 values(与 config.json 的合并语义一致)。 */
+export function setPluginSecrets(
+  file: PluginSecretsFile,
+  scope: PluginSecretsScope,
+  pluginId: string,
+  values: Record<string, PluginSecretValue>,
+  clearKeys: readonly string[],
+): PluginSecretsFile {
+  const clear = new Set(clearKeys);
+  const current = getPluginSecretsForScope(file, scope)[pluginId] ?? {};
+  const nextPluginValues = {
+    ...Object.fromEntries(Object.entries(current).filter(([key]) => !clear.has(key))),
+    ...values,
+  };
+  if (scope.kind === "user") {
+    return { ...file, user: { ...file.user, [pluginId]: nextPluginValues } };
+  }
+  const target = normalizePluginConfigPathForComparison(scope.root);
+  const scopeValues = { ...getPluginSecretsForScope(file, scope), [pluginId]: nextPluginValues };
+  return {
+    ...file,
+    workspaces: {
+      ...withoutWorkspaceRoot(file.workspaces, target),
+      [target]: scopeValues,
+    },
+  };
+}
+
+/** 删除一个插件的私有值:指定 scope,或 `"all"`(user 与全部 workspaces,用于卸载)。 */
+export function removePluginSecrets(
+  file: PluginSecretsFile,
+  pluginId: string,
+  scope: PluginSecretsScope | "all",
+): PluginSecretsFile {
+  const removeFrom = (values: PluginSecretValues): PluginSecretValues =>
+    Object.fromEntries(Object.entries(values).filter(([id]) => id !== pluginId));
+  if (scope === "all") {
+    return {
+      ...file,
+      user: removeFrom(file.user),
+      workspaces: Object.fromEntries(
+        Object.entries(file.workspaces).map(([root, values]) => [root, removeFrom(values)]),
+      ),
+    };
+  }
+  if (scope.kind === "user") return { ...file, user: removeFrom(file.user) };
+  const target = normalizePluginConfigPathForComparison(scope.root);
+  return {
+    ...file,
+    workspaces: Object.fromEntries(
+      Object.entries(file.workspaces).map(([root, values]) => [
+        root,
+        normalizePluginConfigPathForComparison(root) === target ? removeFrom(values) : values,
+      ]),
+    ),
+  };
+}
+
+function withoutWorkspaceRoot(
+  workspaces: PluginSecretsFile["workspaces"],
+  normalizedRoot: string,
+): PluginSecretsFile["workspaces"] {
+  return Object.fromEntries(
+    Object.entries(workspaces).filter(
+      ([root]) => normalizePluginConfigPathForComparison(root) !== normalizedRoot,
+    ),
+  );
+}
+
+/** 去掉空的插件条目与空的 workspace 条目,卸载或清除后不留空壳。 */
+function prunePluginSecretsFile(file: PluginSecretsFile): PluginSecretsFile {
+  const pruneValues = (values: PluginSecretValues): PluginSecretValues =>
+    Object.fromEntries(
+      Object.entries(values).filter(([, pluginValues]) => Object.keys(pluginValues).length > 0),
+    );
+  return {
+    version: PLUGIN_SECRETS_FILE_VERSION,
+    user: pruneValues(file.user),
+    workspaces: Object.fromEntries(
+      Object.entries(file.workspaces)
+        .map(([root, values]) => [root, pruneValues(values)] as const)
+        .filter(([, values]) => Object.keys(values).length > 0),
+    ),
+  };
+}
+
+async function readPluginSecretsFileForWrite(
+  path: string,
+): Promise<{ file: PluginSecretsFile; corrupt: boolean }> {
+  let raw: string;
+  try {
+    raw = await readFile(path, "utf8");
+  } catch (error) {
+    if (getErrorCode(error) === "ENOENT") {
+      return { file: createEmptyPluginSecretsFile(), corrupt: false };
+    }
+    throw error;
+  }
+  const parsed = parsePluginSecretsFile(raw);
+  if (parsed) return { file: parsed, corrupt: false };
+  await backupCorruptFile(path);
+  return { file: createEmptyPluginSecretsFile(), corrupt: true };
+}
+
+function parsePluginSecretsFile(raw: string): PluginSecretsFile | undefined {
+  let value: unknown;
+  try {
+    value = JSON.parse(raw);
+  } catch {
+    return undefined;
+  }
+  const parsed = pluginSecretsFileSchema.safeParse(value);
+  return parsed.success ? parsed.data : undefined;
+}
+
+function getErrorCode(error: unknown): string | undefined {
+  if (typeof error !== "object" || error === null || !("code" in error)) return undefined;
+  const code = (error as { code?: unknown }).code;
+  return typeof code === "string" ? code : undefined;
+}

+ 2 - 5
apps/zcode-cli/packages/adapters/src/config/project-config.adapter.ts

@@ -10,13 +10,9 @@ import { loadFileConfig, type LoadedConfig } from "./file-config.adapter.js";
 
 const CURRENT_DIRECTORY = ".";
 
-export interface ProjectConfigFile {
+export interface ProjectConfigFile extends LoadedConfig {
   baseDir: string;
-  config: RuntimeConfigPatch;
-  diagnostics: LoadedConfig["diagnostics"];
   hookCandidate?: WorkspaceHookSourceInput;
-  loaded: boolean;
-  path: string;
 }
 
 export interface ProjectConfigDiscovery {
@@ -91,6 +87,7 @@ export function loadProjectConfigFile(
       : {}),
     loaded: result.loaded,
     path: result.path,
+    ...(result.pendingVisualizeMigration ? { pendingVisualizeMigration: true } : {}),
   };
 }
 

+ 28 - 4
apps/zcode-cli/packages/adapters/src/context/index.ts

@@ -5,7 +5,7 @@
 import { readFile, stat } from "node:fs/promises";
 import { arch, homedir, release } from "node:os";
 import { basename, dirname, join, resolve } from "node:path";
-import { formatLocalIsoDate } from "@zcode/contracts";
+import { CONTEXT_SOURCE_INSTRUCTIONS_READ_FAILED, formatLocalIsoDate } from "@zcode/contracts";
 import type {
   ContextSourceDiagnostic,
   ContextSourcePort,
@@ -204,8 +204,11 @@ async function readInstructionSource(
       truncated: info.size > maxBytes,
     };
   } catch (error) {
+    // 修复原因:读取出错原来一律当成文件不存在,调用方把权限、占用等错误宣告成文件已删除。
+    // 只有确实不存在才算没有这个文件;其他错误报诊断,调用方沿用已宣告的内容。
+    if (isMissingFileError(error)) return undefined;
     diagnostics.push({
-      code: "user_instructions_read_failed",
+      code: CONTEXT_SOURCE_INSTRUCTIONS_READ_FAILED,
       message: error instanceof Error ? error.message : "Failed to read user instructions",
       path: candidate.filePath,
     });
@@ -240,7 +243,7 @@ async function findInstructionFile(
   while (true) {
     for (const fileName of priorityFiles) {
       const filePath = join(current, fileName);
-      if (await isFile(filePath)) {
+      if (await isInstructionFileCandidate(filePath)) {
         return { filePath, fileName };
       }
     }
@@ -264,7 +267,7 @@ async function findDefaultUserInstructionFile(
   }
 
   const filePath = join(resolveUserHomeDir(env), ".zcode", "AGENTS.md");
-  if (await isFile(filePath)) {
+  if (await isInstructionFileCandidate(filePath)) {
     return { filePath, fileName: "AGENTS.md" };
   }
 
@@ -352,6 +355,27 @@ async function findProjectRoot(startDir: string): Promise<string | null> {
   return (await findGitRoot(resolve(startDir))) ?? null;
 }
 
+// 路径上没有这个文件的错误码:不存在、是目录、路径中间有一段不是目录。
+const MISSING_FILE_ERROR_CODES = new Set(["ENOENT", "EISDIR", "ENOTDIR"]);
+
+function isMissingFileError(error: unknown): boolean {
+  const code = (error as NodeJS.ErrnoException | undefined)?.code;
+  return code !== undefined && MISSING_FILE_ERROR_CODES.has(code);
+}
+
+/**
+ * 指令文件候选:是普通文件,或检查时出现"不存在"以外的错误。
+ * 修复原因:检查出错(如目录没有访问权限)原来当成不存在,查找继续向上,可能换成父目录的文件;
+ * 现在停在这个候选,由读取步骤报诊断。
+ */
+async function isInstructionFileCandidate(path: string): Promise<boolean> {
+  try {
+    return (await stat(path)).isFile();
+  } catch (error) {
+    return !isMissingFileError(error);
+  }
+}
+
 async function isFile(path: string): Promise<boolean> {
   try {
     const info = await stat(path);

+ 4 - 1
apps/zcode-cli/packages/adapters/src/http/index.ts

@@ -177,7 +177,7 @@ function fetchHttpResponse(
 
   const headers = buildHeaders(request);
   const transport = url.protocol === "https:" ? https : http;
-  const agent = createRequestAgent(url, proxyUrl, tlsCaCertificates);
+  const agent = createRequestAgent(url, proxyUrl, tlsCaCertificates, signal);
   const lookup = publicDnsLookup
     ? createPublicEgressLookup(url.toString(), publicDnsLookup, { signal })
     : undefined;
@@ -243,10 +243,13 @@ function createRequestAgent(
   url: URL,
   proxyUrl: string | undefined,
   tlsCaCertificates: Buffer | undefined,
+  signal: AbortSignal,
 ): http.Agent | undefined {
   if (proxyUrl) {
     return new ProxyAgent({
       ca: tlsCaCertificates,
+      // CONNECT 返回前 ClientRequest.destroy 不持有 socket;让取消同时关闭代理连接。
+      signal,
       getProxyForUrl: () => proxyUrl,
       httpsAgent: tlsCaCertificates ? new https.Agent({ ca: tlsCaCertificates }) : undefined,
     }) as unknown as http.Agent;

+ 21 - 2
apps/zcode-cli/packages/adapters/src/mcp/index.ts

@@ -150,6 +150,11 @@ export interface CreateMcpAdapterOptions {
     workspaceIdentity?: string;
   };
   workingDirectory?: string;
+  /**
+   * 会话所属 workspace 的 key,官方 MCP 授权头请求以它为身份发往 Host。受管 worktree 会话 =
+   * 项目,不等于 workingDirectory(docs/git/worktree.md §9.3)。
+   */
+  workspaceKey?: string;
   /** 有此端口才向 server 宣告 elicitation 能力;缺省时 server 的 elicitation/create 收到 method not found。 */
   elicitation?: McpElicitationPort;
   /** server → client 通知(资源更新 / 列表变化 / 工具列表变化 / 日志)的出口;缺省只记 debug。 */
@@ -223,11 +228,12 @@ export function createMcpAdapterConnectionPool(
   return createMcpConnectionPool({
     logger: options.logger,
     telemetry: options.telemetry,
-    createAdapter: ({ connectionContext, workingDirectory }) =>
+    createAdapter: ({ connectionContext, workingDirectory, workspaceKey }) =>
       createMcpAdapter({
         ...options,
         connectionContext,
         workingDirectory: workingDirectory ?? options.workingDirectory,
+        ...(workspaceKey ? { workspaceKey } : {}),
       }),
   });
 }
@@ -293,6 +299,7 @@ class NodeMcpAdapter implements McpPort {
   >();
   private readonly records = new Map<string, McpServerRecord>();
   private readonly workingDirectory?: string;
+  private readonly workspaceKey?: string;
   private readonly elicitation?: McpElicitationPort;
   private readonly notifications?: McpNotificationPort;
   /** 资源订阅登记表 serverName → uri → subscriberKey;唯一 owner,连接层计数。 */
@@ -317,6 +324,7 @@ class NodeMcpAdapter implements McpPort {
     this.officialMcpAuth = options.officialMcpAuth;
     this.telemetry = options.telemetry;
     this.workingDirectory = options.workingDirectory;
+    this.workspaceKey = options.workspaceKey;
     this.elicitation = options.elicitation;
     this.notifications = options.notifications;
   }
@@ -1076,6 +1084,7 @@ class NodeMcpAdapter implements McpPort {
         ? { workspaceIdentity: this.officialMcpAuth.workspaceIdentity }
         : {}),
       ...(this.workingDirectory ? { workspacePath: this.workingDirectory } : {}),
+      ...(this.workspaceKey ? { workspaceKey: this.workspaceKey } : {}),
       ...(signal ? { signal } : {}),
     });
     if (!resolved.ok) return fail(resolved.reason);
@@ -2059,6 +2068,7 @@ class NodeMcpAdapter implements McpPort {
         ? { workspaceIdentity: this.officialMcpAuth.workspaceIdentity }
         : {}),
       ...(this.workingDirectory ? { workspacePath: this.workingDirectory } : {}),
+      ...(this.workspaceKey ? { workspaceKey: this.workspaceKey } : {}),
     });
   }
 
@@ -2489,16 +2499,25 @@ function createBoundedTextBuffer(maxChars: number): {
   read(): string;
 } {
   let value = "";
+  let truncated = false;
   return {
     append(text: string) {
       if (!text) return;
       value = `${value}${text}`;
       if (value.length > maxChars) {
         value = value.slice(-maxChars);
+        truncated = true;
       }
     },
     read() {
-      return value;
+      // 尾部截断可能把 VE_SPEECH_MCP_TOKEN=... 切成 KEN=...,键名正则匹配不到会泄露值。
+      // 截断后丢弃第一行残片,保证脱敏看到的每一行都完整。
+      // 行边界含 \r(进度条只用 \r 刷新)。尾部完全没有换行时(单个超长行),
+      // 空白/分隔符可能位于带引号的凭证值内部(KEN="a b" 的 b),从那里恢复会丢失键名和引号上下文而泄露后缀,
+      // 没有可靠的字段边界就不输出,只保留传输错误。
+      if (!truncated) return value;
+      const lineEnd = value.search(/[\r\n]/);
+      return lineEnd < 0 ? "" : value.slice(lineEnd + 1);
     },
   };
 }

+ 2 - 0
apps/zcode-cli/packages/adapters/src/mcp/official-auth.ts

@@ -66,6 +66,7 @@ export interface CreateOfficialMcpAuthFetchInput {
   url: string;
   workspaceIdentity?: string;
   workspacePath?: string;
+  workspaceKey?: string;
 }
 
 /** 一次官方 MCP 响应中可用于关联的非敏感事实。不含 body、不含任何 header 值。 */
@@ -162,6 +163,7 @@ export function createOfficialMcpAuthFetch(
           targetOrigin: origin,
           ...(input.workspaceIdentity ? { workspaceIdentity: input.workspaceIdentity } : {}),
           ...(input.workspacePath ? { workspacePath: input.workspacePath } : {}),
+          ...(input.workspaceKey ? { workspaceKey: input.workspaceKey } : {}),
           ...(init?.signal ? { signal: init.signal } : {}),
         });
         resolveDurationMs = Date.now() - resolveStartedAt;

+ 9 - 1
apps/zcode-cli/packages/adapters/src/mcp/pool.ts

@@ -22,6 +22,7 @@ export interface CreateMcpAdapterForPoolInput {
   config: McpServerConfig;
   serverName: string;
   workingDirectory?: string;
+  workspaceKey?: string;
 }
 
 export interface McpConnectionContext {
@@ -298,6 +299,7 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
           config,
           serverName,
           workingDirectory: connectOptions.workingDirectory,
+          ...(connectOptions.workspaceKey ? { workspaceKey: connectOptions.workspaceKey } : {}),
         });
         // 连接归 pool,不能继承第一个 session 的关闭信号,否则会连带中止其他 lease。
         const controller = new AbortController();
@@ -644,9 +646,15 @@ function connectionKey(input: {
   serverName: string;
 }): string {
   // 默认 session isolation;只有明确声明 workspace 的无状态 server 才允许跨 session 复用。
+  // 共享按工作目录分组(stdio 进程的 cwd);会话 key 也进入分组,因为 adapter 在创建时固定 key,
+  // 同一 cwd 下 key 不同的会话(例如受管 worktree 目录又被单独添加为项目)若复用连接,官方 MCP
+  // 授权头会按第一个会话的 key 路由(MR !3520 review SG-01)。
   const scope =
     input.config.isolation === "workspace"
-      ? (resolveWorkspaceKey(input.connectOptions) ?? "")
+      ? [
+          resolveWorkspaceKey(input.connectOptions) ?? "",
+          input.connectOptions.workspaceKey ?? "",
+        ].join("\u0000")
       : input.leaseId;
   return [input.serverName, scope, stableStringify(input.config)].join("\u0000");
 }

+ 16 - 6
apps/zcode-cli/packages/adapters/src/model/provider-builtin-tool-compat/CONTRACT.md

@@ -3,17 +3,27 @@
 服务端执行内置工具后,会在一条 assistant 流里依次下发:调用头 markdown → `server_tool_use`(SDK 不认识的名字)
 → 结果 markdown → 裸 `tool_result` → 下一轮。本模块把结构化块改写成 AI SDK 原生支持的
 `mcp_tool_use` / `mcp_tool_result`(provider 执行),并去掉与之重复的 markdown 渲染。
+服务端新格式直接下发 `mcp_tool_use` → `mcp_tool_result` → 结果 markdown;结构化块原样透传,只去掉 markdown 渲染。
 规格见 `apps/zcode-cli/docs/design/v2/model/anthropic-stream-compat.md`「Provider 内置工具多轮回放」。
 
 不变量:
 
 - 只改写 SDK 不认识的 `server_tool_use`;SDK 已支持的名字(web_search、code_execution 等)原样透传。
-- 裸 `tool_result` 只有和前面的服务端调用 id 配对时才改写;没配对的交给 anthropic-stream-compat 按原规则丢弃。
-- markdown 副本按结构确认,不只凭前缀:调用头必须以 `**🌐` 开头且下一个块就是服务端调用;结果副本必须以加粗开头、
-  紧跟服务端调用,且下一个块就是这次调用的配对 `tool_result`。确认前先缓冲,确认不了就原样放行,
-  所以服务端缺少配对结果时,紧跟调用的加粗正文不会被删。
+  上游下发的 `mcp_tool_use` / `mcp_tool_result` 不改写,只有缺 `server_name` 时补上
+  `PROVIDER_BUILTIN_TOOL_SERVER_NAME`。
+- 配对按调用 id,只在本条消息内有效,新旧格式共用:旧格式改写出的调用和上游的 `mcp_tool_use` 都能配对
+  裸 `tool_result` 或 `mcp_tool_result`。
+- 裸 `tool_result` 只有配对时才改写;没配对的交给 anthropic-stream-compat 按原规则丢弃。
+  没配对的 `mcp_tool_result` 由本模块按 index 丢弃 start、delta 和 stop frame(AI SDK 遇到它会抛错)。
+- markdown 副本按结构确认,不只凭前缀:调用头必须以 `**🌐` 开头且下一个块就是服务端调用(`server_tool_use`
+  或 `mcp_tool_use`);旧格式结果副本必须以加粗开头、紧跟服务端调用,且下一个块就是这次调用的配对 `tool_result`;
+  新格式结果摘要必须紧跟配对的 `mcp_tool_result`,以 `**Output:**` 开头,并紧接着配对调用的摘要标签
+  `**<工具名>_result_summary:**`;紧跟配对结果的 text 以 `**🌐` 开头时改按调用头确认(服务端漏发摘要时)。
+  确认前先缓冲,确认不了就原样放行。所以旧格式缺少配对结果时紧跟调用的加粗正文,以及新格式结果之后
+  不带配对工具摘要标签的正文(包括以 `**Output:**` 开头的模型回答),都原样保留。
 - 状态按 message 维护,`message_start` 时清空;流结束时补发仍在缓冲的帧,不吞内容。
 - 纯协议变换,不做 IO;只由 anthropic-stream-compat 在 Anthropic fetch 边界调用。
 
-行为回归:`apps/zcode-cli/packages/adapters/tests/provider-builtin-tool-compat/`(契约),
-`model-execution.test.ts` 与 `provider-builtin-tool-rounds.test.ts`(经 AI SDK 的端到端)。
+行为回归:`apps/zcode-cli/packages/adapters/tests/provider-builtin-tool-compat/`(契约,两种格式),
+`model-execution.test.ts`(经 AI SDK 的端到端,旧格式)与 `provider-builtin-tool-rounds.test.ts`
+(经 Runtime 的端到端,新旧两种格式 fixture)。

+ 144 - 18
apps/zcode-cli/packages/adapters/src/model/provider-builtin-tool-compat/compat.ts

@@ -6,8 +6,17 @@
 // 只剩 markdown 进入正文和下一次请求,模型会照着文字假装调用工具。
 // 这里把它们改写成 AI SDK 原生支持的 mcp_tool_use / mcp_tool_result(provider 执行、dynamic),
 // 并去掉与结构化块重复的 markdown 渲染;没有配对上的裸 tool_result 仍交给上层丢弃。
+//
+// 服务端新格式直接下发 SDK 原生块,结果摘要挪到结果之后:
+//   text(「**🌐 …」) → mcp_tool_use → mcp_tool_result → text(「**Output:** …」) → 下一轮
+// 原生块原样透传,只去掉两段 markdown 渲染。全量切换前两种格式都会出现。
+// 服务端不一定遵守协议:原生调用缺 server_name 时补上,没有配对调用的 mcp_tool_result 丢弃,
+// 两者都会让 AI SDK 整轮失败(见 docs/design/v2/model/anthropic-stream-compat.md)。
 
-/** 改写后 mcp_tool_use 的 server_name;下游据此识别 provider 内置工具。 */
+/**
+ * 旧格式改写和补齐上游缺失时用的 server_name。AI SDK schema 要求它是字符串;
+ * 下游不依赖它的值(卡片用 core 的 provider-tool-rounds/cards.ts 里的常量)。
+ */
 export const PROVIDER_BUILTIN_TOOL_SERVER_NAME = "zcode-provider-builtin";
 
 // @ai-sdk/anthropic 3.0.81 自己能解析的 server_tool_use 名称,保持原样。
@@ -22,9 +31,10 @@ const SDK_KNOWN_SERVER_TOOL_NAMES = new Set([
   "advisor",
 ]);
 
-// 服务端渲染副本的前缀:调用头以「**🌐」开头,结果以加粗标签开头。不写厂商名。
-const CALL_RENDERING_PREFIX = "**🌐";
-const RESULT_RENDERING_PREFIX = "**";
+// 服务端渲染副本的前缀,按缓冲角色取。不写厂商名。
+// 调用头以「**🌐」开头;旧格式结果以加粗标签开头;新格式结果摘要以「**Output:**」开头,
+// 整块收完后还要用配对调用的摘要标签确认身份(isRenderedSummary)。
+const RENDERING_PREFIX = { call: "**🌐", result: "**", summary: "**Output:**" } as const;
 
 export function isProviderBuiltinServerToolUse(
   block: Record<string, unknown> | undefined,
@@ -37,6 +47,38 @@ export function isProviderBuiltinServerToolUse(
   );
 }
 
+function isUpstreamMcpToolUse(block: Record<string, unknown> | undefined): boolean {
+  return block?.type === "mcp_tool_use" && typeof block.id === "string";
+}
+
+/**
+ * 上游新格式的调用块只补 AI SDK schema 必需的 server_name,已有时原样返回同一个对象。
+ * 修复原因:2026-11-05 线上漏发这个字段,SDK 校验失败让整轮报错,图片留在历史里后每轮都失败。
+ */
+function withServerName(block: Record<string, unknown>): Record<string, unknown> {
+  return typeof block.server_name === "string"
+    ? block
+    : { ...block, server_name: PROVIDER_BUILTIN_TOOL_SERVER_NAME };
+}
+
+/**
+ * 新格式结果摘要的身份:「**Output:**」后面紧跟配对调用的「**<工具名>_result_summary:**」,
+ * 例如「**Output:**\n**analyze_image_result_summary:** …」。
+ * 修复原因(评审 CR-01):摘要后面没有结构块可确认,模型下一轮的正文也会紧跟结果出现;
+ * 只看前缀时,以 **Output:** 开头的模型回答会被整块删掉。旧格式靠后面的配对 tool_result 确认,
+ * 新格式只能靠摘要自带的工具名标签;标签对不上只会漏删,不会误删。
+ */
+function isRenderedSummary(text: string, toolName: string): boolean {
+  const trimmed = text.trimStart();
+  return (
+    trimmed.startsWith(RENDERING_PREFIX.summary) &&
+    trimmed
+      .slice(RENDERING_PREFIX.summary.length)
+      .trimStart()
+      .startsWith(`**${toolName}_result_summary:**`)
+  );
+}
+
 export function toMcpToolUseBlock(block: Record<string, unknown>): Record<string, unknown> {
   return {
     type: "mcp_tool_use",
@@ -81,11 +123,16 @@ interface HeldTextBlock {
   index: number;
   frames: SseFrame[];
   text: string;
-  /** call:可能是调用头副本;result:紧跟服务端调用的第一个 text 块,可能是结果副本。 */
-  role: "call" | "result";
+  /**
+   * call:可能是调用头副本;result:紧跟服务端调用的第一个 text 块,可能是结果副本;
+   * summary:紧跟配对 mcp_tool_result 的第一个 text 块,可能是新格式的结果摘要副本。
+   */
+  role: keyof typeof RENDERING_PREFIX;
   /** result 角色对应的服务端调用;只有紧跟其后的就是这次调用的配对结果时,才确认是副本。 */
   resultForCallId?: string;
-  /** 前缀已匹配且整块已收完,等下一个块开始时按结构确认去留。 */
+  /** summary 角色对应的配对调用工具名;摘要标签必须是这个工具的,才确认是副本。 */
+  summaryForToolName?: string;
+  /** 前缀已匹配且整块已收完,call / result 等下一个块开始时按结构确认去留(summary 收完时就确认)。 */
   complete: boolean;
 }
 
@@ -94,10 +141,18 @@ interface HeldTextBlock {
  * 只处理已解析出 JSON 的帧,其余原样返回。
  */
 export class ProviderBuiltinToolStreamRewriter {
-  private readonly pendingResultIds = new Set<string>();
+  /**
+   * 本条消息里服务端调用的 id → 工具名,等待配对结果。旧格式改写出的调用和上游原生调用共用一个集合,
+   * 服务端半迁移、两种格式混出时也能配上。工具名用来确认新格式的结果摘要;上游没给名字时为 undefined。
+   */
+  private readonly pendingResultIds = new Map<string, string | undefined>();
+  /** 没有配对调用的 mcp_tool_result 所在 index:start、delta、stop 一并丢弃。 */
+  private readonly suppressedIndexes = new Set<number>();
   private held: HeldTextBlock | undefined;
   /** 上一个开始的块是服务端调用时为其 id;只有紧跟其后的 text 才可能是结果副本。 */
   private afterServerToolUseId: string | undefined;
+  /** 上一个开始的块是配对的 mcp_tool_result 时为其调用的工具名;只有紧跟其后的 text 才可能是结果摘要副本。 */
+  private afterMcpToolResultName: string | undefined;
 
   push(input: SseFrame, parsed: Record<string, unknown> | undefined): SseFrame[] {
     // 非 JSON 帧(注释、keepalive)和 ping 不影响块边界,直接放行,不打断缓冲。
@@ -109,10 +164,17 @@ export class ProviderBuiltinToolStreamRewriter {
     if (type === "message_start") {
       const flushed = this.flushHeld();
       this.pendingResultIds.clear();
+      this.suppressedIndexes.clear();
       this.afterServerToolUseId = undefined;
+      this.afterMcpToolResultName = undefined;
       return [...flushed, input];
     }
 
+    if (index !== undefined && this.suppressedIndexes.has(index)) {
+      if (type === "content_block_stop") this.suppressedIndexes.delete(index);
+      return [];
+    }
+
     if (this.held && index === this.held.index) {
       return this.pushHeld(input, parsed, type);
     }
@@ -120,18 +182,51 @@ export class ProviderBuiltinToolStreamRewriter {
     if (type === "content_block_start" && index !== undefined) {
       const block = asRecord(parsed.content_block);
       const afterServerToolUseId = this.afterServerToolUseId;
+      const afterMcpToolResultName = this.afterMcpToolResultName;
       this.afterServerToolUseId = undefined;
+      this.afterMcpToolResultName = undefined;
       if (isProviderBuiltinServerToolUse(block)) {
         // 调用头副本只有紧跟其后的就是服务端调用时才确认是副本。
         this.dropConfirmedCopy("call");
         const flushed = this.flushHeld();
-        this.pendingResultIds.add(block!.id as string);
+        this.pendingResultIds.set(block!.id as string, block!.name as string);
         this.afterServerToolUseId = block!.id as string;
         return [
           ...flushed,
           rewriteFrame(input, { ...parsed, content_block: toMcpToolUseBlock(block!) }),
         ];
       }
+      if (isUpstreamMcpToolUse(block)) {
+        // 新格式原生块不改写;调用头副本同样要紧跟其后的就是服务端调用才确认。
+        // 并行调用时调用后面紧跟下一个调用头,所以这里不把后续 text 当结果副本。
+        this.dropConfirmedCopy("call");
+        const flushed = this.flushHeld();
+        this.pendingResultIds.set(
+          block!.id as string,
+          typeof block!.name === "string" ? block!.name : undefined,
+        );
+        const normalized = withServerName(block!);
+        return [
+          ...flushed,
+          normalized === block
+            ? input
+            : rewriteFrame(input, { ...parsed, content_block: normalized }),
+        ];
+      }
+      if (block?.type === "mcp_tool_result") {
+        const flushed = this.flushHeld();
+        // 修复原因:AI SDK 按 tool_use_id 直接取调用记录,取不到会抛 TypeError,整条流失败。
+        // 服务端不一定保证配对,没配对的结果按 index 整块丢弃;调用一侧由 core 按中断收口。
+        const toolUseId = typeof block.tool_use_id === "string" ? block.tool_use_id : undefined;
+        if (toolUseId === undefined || !this.pendingResultIds.has(toolUseId)) {
+          this.suppressedIndexes.add(index);
+          return flushed;
+        }
+        // 只有紧跟配对结果的 text 才可能是结果摘要副本,摘要标签要对上这次调用的工具名。
+        this.afterMcpToolResultName = this.pendingResultIds.get(toolUseId);
+        this.pendingResultIds.delete(toolUseId);
+        return [...flushed, input];
+      }
       if (block?.type === "tool_result" && typeof block.tool_use_id === "string") {
         const paired = this.pendingResultIds.delete(block.tool_use_id);
         // 结果副本只有紧跟其后的就是配对的 tool_result 时才确认是副本,否则原样放行。
@@ -149,8 +244,9 @@ export class ProviderBuiltinToolStreamRewriter {
           index,
           frames: [input],
           text: typeof block.text === "string" ? block.text : "",
-          role: afterServerToolUseId ? "result" : "call",
+          role: afterServerToolUseId ? "result" : afterMcpToolResultName ? "summary" : "call",
           ...(afterServerToolUseId ? { resultForCallId: afterServerToolUseId } : {}),
+          ...(afterMcpToolResultName ? { summaryForToolName: afterMcpToolResultName } : {}),
           complete: false,
         };
         return [...flushed, ...this.decideHeldPrefix()];
@@ -179,25 +275,39 @@ export class ProviderBuiltinToolStreamRewriter {
     }
     if (type === "content_block_stop") {
       const decided = this.decideHeldPrefix(true);
-      if (this.held === held) held.complete = true;
-      return decided;
+      if (this.held !== held) return decided;
+      held.complete = true;
+      if (held.role !== "summary") return decided;
+      // 新格式的结果摘要后面没有结构块:整块收完时按配对调用的摘要标签确认身份,确认不了立即放行,
+      // 不等下一个块,正文顺序不变。
+      this.held = undefined;
+      return held.summaryForToolName !== undefined &&
+        isRenderedSummary(held.text, held.summaryForToolName)
+        ? []
+        : held.frames;
     }
     return this.decideHeldPrefix();
   }
 
-  /** 前缀不匹配就放行;匹配则继续缓冲,等下一个块开始时按结构确认(dropConfirmedCopy)。 */
+  /** 前缀不匹配就放行;匹配则继续缓冲,按结构确认(dropConfirmedCopy)。 */
   private decideHeldPrefix(stopped = false): SseFrame[] {
     const held = this.held!;
-    const prefix = held.role === "call" ? CALL_RENDERING_PREFIX : RESULT_RENDERING_PREFIX;
     const text = held.text.trimStart();
+    // 服务端漏发摘要、结果后直接接下一个调用时,紧跟结果的是调用头:改按 call 等下一个块确认。
+    // 原因:summary 只认 **Output:**,否则这个调用头会留在正文里,旧格式在同样的顺序下会去掉它。
+    if (held.role === "summary" && text.startsWith(RENDERING_PREFIX.call)) held.role = "call";
+    const prefix = RENDERING_PREFIX[held.role];
     const decidable = stopped || text.length >= prefix.length;
     if (!decidable) return [];
     if (!text.startsWith(prefix)) return this.flushHeld();
     return [];
   }
 
-  /** 下一个块确认了缓冲块就是服务端渲染副本时丢弃它;其余情况由 flushHeld 原样放行。 */
-  private dropConfirmedCopy(role: HeldTextBlock["role"], resultForCallId?: string): void {
+  /**
+   * 下一个块按结构确认了缓冲块就是服务端渲染副本时丢弃它(call / result;summary 在 pushHeld 收完整块时确认);
+   * 其余情况由 flushHeld 原样放行。
+   */
+  private dropConfirmedCopy(role: "call" | "result", resultForCallId?: string): void {
     const held = this.held;
     if (!held?.complete || held.role !== role) return;
     if (role === "result" && held.resultForCallId !== resultForCallId) return;
@@ -240,13 +350,29 @@ export function rewriteProviderBuiltinToolContent(content: readonly unknown[]):
     previousServerToolUseId = undefined;
     if (isProviderBuiltinServerToolUse(block)) {
       const previous = asRecord(output.at(-1));
-      if (isRenderingText(previous, CALL_RENDERING_PREFIX)) output.pop();
+      if (isRenderingText(previous, RENDERING_PREFIX.call)) output.pop();
       pendingResultIds.add(block!.id as string);
       output.push(toMcpToolUseBlock(block!));
       previousServerToolUseId = block!.id as string;
       changed = true;
       continue;
     }
+    // 新格式非流式没有 markdown 渲染,只做与流式相同的两条防护。
+    if (isUpstreamMcpToolUse(block)) {
+      pendingResultIds.add(block!.id as string);
+      const normalized = withServerName(block!);
+      if (normalized !== block) changed = true;
+      output.push(normalized);
+      continue;
+    }
+    if (block?.type === "mcp_tool_result") {
+      if (typeof block.tool_use_id === "string" && pendingResultIds.delete(block.tool_use_id)) {
+        output.push(value);
+      } else {
+        changed = true;
+      }
+      continue;
+    }
     if (block?.type === "tool_result") {
       changed = true;
       if (typeof block.tool_use_id === "string" && pendingResultIds.delete(block.tool_use_id)) {
@@ -258,7 +384,7 @@ export function rewriteProviderBuiltinToolContent(content: readonly unknown[]):
     const next = asRecord(content[position + 1]);
     if (
       afterServerToolUseId !== undefined &&
-      isRenderingText(block, RESULT_RENDERING_PREFIX) &&
+      isRenderingText(block, RENDERING_PREFIX.result) &&
       next?.type === "tool_result" &&
       next.tool_use_id === afterServerToolUseId
     ) {

+ 196 - 103
apps/zcode-cli/packages/adapters/src/model/reasoning-history-normalization.ts

@@ -1,6 +1,5 @@
 import type {
   ModelInputMessage,
-  ModelMessageContent,
   ModelMessageContentBlock,
   ModelReasoningContentBlock,
   ModelId,
@@ -8,9 +7,14 @@ import type {
 } from "@zcode/contracts";
 import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
 import { getStatusCode, unwrapRetryError } from "./failure-inspection.js";
+import { orderedAssistantItems, type OrderedAssistantItem } from "./transform.js";
 
 const EMPTY_ASSISTANT_CONTENT_FALLBACK = "(no content)";
 const REJECTED_REASONING_FALLBACK = "[Thinking removed]";
+// 签名拒绝重试日志里 provider 报错原文的最大字符数:留下定位原因所需的内容,不把整段响应体写进日志。
+const REJECTION_PROVIDER_MESSAGE_MAX_CHARS = 2000;
+// provider 在 thinking 前缀不一致时返回的响应头,写明出错块的位置;只用于日志诊断。
+const THINKING_PREFIX_MISMATCH_HEADER = "anthropic-thinking-prefix-mismatch";
 
 // 旧历史保留 builtin 身份,当前选型已迁到 account 身份;Individual/Team
 // 也会使用不同 ID。只在 reasoning 回放时识别同服务的这些明确身份,不改变选型或鉴权。
@@ -28,21 +32,36 @@ const REASONING_PROVIDER_GROUPS: readonly (readonly string[])[] = [
   ],
 ];
 
+// 这里只过滤、移动或补齐消息里的块,不删除、不合并消息。没有可见内容(只有思考和空白文字)的回复由 core
+// 投影的第一步删除(requestCapabilities.dropReasoningOnlyOrBlankAssistants)。
+// 修复原因:这里原来也删除这类回复,晚于 core 的 MCS 落点;被删回复前面的 system 直接接上 user,
+// provider 返回 400(role 'system' must precede an 'assistant' message)。
 export function normalizeReasoningHistory(
   messages: ModelInputMessage[],
   targetModel?: { modelId: ModelId; providerId: ModelProviderId },
 ): ModelInputMessage[] {
   const compatibleHistory = removeCrossModelReasoning(messages, targetModel);
-  const withoutOrphans = removeAssistantsMergingNeighbors(
-    compatibleHistory,
-    isReasoningOnlyAssistant,
-  );
-  const withoutTrailingReasoning = removeTrailingReasoning(withoutOrphans);
-  const withoutWhitespaceOnlyAssistants = removeAssistantsMergingNeighbors(
-    withoutTrailingReasoning,
-    isWhitespaceOnlyAssistant,
+  // 有序条目的规则在跨模型过滤之后计算,见 docs/design/v2/model/assistant-block-order.md。
+  const orderedHistory = mapMessages(compatibleHistory, applyOrderedAssistantRules);
+  const withoutTrailingReasoning = removeTrailingReasoning(orderedHistory);
+  return removeReasoningBeforeRepairMarker(repairEmptyAssistantContent(withoutTrailingReasoning));
+}
+
+/**
+ * 签名修复后成功的请求会在产出的 assistant 上记 signedReasoningReset。
+ * 修复原因:修复原来只改那一次请求的副本,历史里被拒的签名块下个请求又发出去,
+ * 服务端同样拒绝,于是之后每个请求都先 400 再修一次;块放回后,它缺席期间生成的
+ * thinking 也会失效。这里把最后一个标记之前的消息按修复那次的同一规则处理,
+ * 放在结构 passes 之后(与修复重试的顺序相同),前缀和修复那次发出的逐字节一致。
+ */
+function removeReasoningBeforeRepairMarker(messages: ModelInputMessage[]): ModelInputMessage[] {
+  const markerIndex = messages.findLastIndex(
+    (message) => message.role === "assistant" && message.signedReasoningReset === true,
   );
-  return repairEmptyAssistantContent(withoutWhitespaceOnlyAssistants);
+  if (markerIndex <= 0) return messages;
+  const before = messages.slice(0, markerIndex);
+  const repaired = removeRejectedReasoning(before);
+  return repaired === before ? messages : [...repaired, ...messages.slice(markerIndex)];
 }
 
 export function removeRejectedReasoning(messages: ModelInputMessage[]): ModelInputMessage[] {
@@ -60,9 +79,20 @@ export function removeRejectedReasoning(messages: ModelInputMessage[]): ModelInp
       (block) => block.type !== "text" || block.text.trim().length > 0,
     );
     if (!hasToolCalls(message) && content.every((block) => block.type === "reasoning")) {
-      content = [...content, { type: "text", text: REJECTED_REASONING_FALLBACK }];
+      // 按改写前的消息判断:思考块删光后空内容也会被当成有序。
+      const original = messages[index]!;
+      const ordered = orderedMessageItems(original) !== undefined;
+      content = [
+        ...content,
+        {
+          type: "text",
+          text: REJECTED_REASONING_FALLBACK,
+          // 有序条目的占位块排在最后,条目仍然有序,下面的规则才会重新执行。
+          ...(ordered ? { blockIndex: maxBlockIndex(original) + 1 } : {}),
+        },
+      ];
     }
-    result[index] = { ...message, content };
+    result[index] = applyOrderedAssistantRules({ ...message, content });
   }
   return result;
 }
@@ -74,7 +104,7 @@ export function repairReasoningHistoryAfterSignatureRejection(
   if (!isThinkingSignatureRejection(error)) return undefined;
 
   // 调用方传入的已经是逻辑请求入口完成结构归一化后的副本。这里仅执行签名拒绝清理,
-  // 不能再次运行结构 passes,否则会删除刚补出的 assistant 占位并改变轮次边界。
+  // 不再次运行结构 passes(规格:结构归一化每个逻辑请求只做一次)。
   const repaired = removeRejectedReasoning(projectedMessages);
   return repaired === projectedMessages ? undefined : repaired;
 }
@@ -85,18 +115,45 @@ export function isThinkingSignatureRejection(error: unknown): boolean {
 
   // Provider 没有为该 400 提供独立错误码;这里只匹配已确认的窄化文案,
   // 避免把其他 invalid_request 误当成可修改历史并重试。
+  // 修复原因:网关转发的原文是 "Invalid `signature` in `thinking` block … bound to a different
+  // conversation",反引号把 "invalid signature" 隔开,原来的子串匹配认不出,剥离重试没有触发,
+  // 会话之后的每个请求都失败。现在原文和去掉反引号的文本都检查(`thinking` 这种写法要用原文判断),
+  // 并认出 thinking block 绑定到其他对话的两种说法。
   const message = errorMessage(unwrapped).toLowerCase();
-  if (message.includes("signature in thinking block")) return true;
+  const plain = message.replaceAll("`", "");
+  if (plain.includes("signature in thinking block")) return true;
+  if (
+    message.includes("bound to a different conversation") ||
+    message.includes("not created in this conversation")
+  )
+    return true;
 
   const namesThinkingBlock =
-    message.includes("thinking block") ||
+    plain.includes("thinking block") ||
     message.includes("`thinking`") ||
     message.includes("redacted_thinking");
   const namesSignatureFailure =
-    message.includes("cannot be modified") || message.includes("invalid signature");
+    plain.includes("cannot be modified") || plain.includes("invalid signature");
   return namesThinkingBlock && namesSignatureFailure;
 }
 
+/** 签名拒绝重试日志的诊断字段:provider 原文(截断)与 prefix 不一致响应头。 */
+export function thinkingSignatureRejectionEvidence(
+  error: unknown,
+  responseHeaders: Record<string, string> | undefined,
+): { providerMessage: string; thinkingPrefixMismatch?: string } {
+  const prefixMismatch = Object.entries(responseHeaders ?? {}).find(
+    ([name]) => name.toLowerCase() === THINKING_PREFIX_MISMATCH_HEADER,
+  )?.[1];
+  return {
+    providerMessage: errorMessage(unwrapRetryError(error)).slice(
+      0,
+      REJECTION_PROVIDER_MESSAGE_MAX_CHARS,
+    ),
+    ...(prefixMismatch ? { thinkingPrefixMismatch: prefixMismatch } : {}),
+  };
+}
+
 function removeCrossModelReasoning(
   messages: ModelInputMessage[],
   targetModel: { modelId: ModelId; providerId: ModelProviderId } | undefined,
@@ -148,40 +205,21 @@ function filterReasoningBlocks(
   return result ?? messages;
 }
 
-function removeAssistantsMergingNeighbors(
-  messages: ModelInputMessage[],
-  shouldRemove: (message: ModelInputMessage) => boolean,
-): ModelInputMessage[] {
-  const result: ModelInputMessage[] = [];
-  let removedBefore = false;
-  for (const message of messages) {
-    if (shouldRemove(message)) {
-      removedBefore = true;
-      continue;
-    }
-    const previous = result.at(-1);
-    // 删除后两侧的 user 由下游直接拼接,前一条文本末尾会缺少 "\n",所以在这里合并。
-    // 修复原因:只合并删除点两侧的一对;其他相邻 user 已由请求层拼好,整段重新合并会给每对多补 "\n"。
-    if (removedBefore && canMergeAdjacentUserMessages(previous, message)) {
-      result[result.length - 1] = mergeUserMessagePair(previous, message);
-    } else {
-      result.push(message);
-    }
-    removedBefore = false;
-  }
-  return result.length === messages.length ? messages : result;
-}
-
-function isReasoningOnlyAssistant(message: ModelInputMessage): boolean {
-  if (message.role !== "assistant" || hasToolCalls(message)) return false;
-  if (!Array.isArray(message.content) || message.content.length === 0) return false;
-  return message.content.every((block) => block.type === "reasoning");
-}
-
 function removeTrailingReasoning(messages: ModelInputMessage[]): ModelInputMessage[] {
   const last = messages.at(-1);
   if (last?.role !== "assistant" || !Array.isArray(last.content)) return messages;
 
+  const items = orderedMessageItems(last);
+  if (items) {
+    // 有序条目按请求顺序删掉末尾连续的思考块,不重新执行逐块合并。
+    let end = items.length;
+    while (end > 0 && isReasoningItem(items[end - 1])) end -= 1;
+    if (end === items.length) return messages;
+    const result = messages.slice();
+    result[result.length - 1] = withOrderedItems(last, items.slice(0, end));
+    return result;
+  }
+
   let end = last.content.length;
   while (end > 0 && last.content[end - 1]?.type === "reasoning") {
     end -= 1;
@@ -196,16 +234,119 @@ function removeTrailingReasoning(messages: ModelInputMessage[]): ModelInputMessa
   return result;
 }
 
-function isWhitespaceOnlyAssistant(message: ModelInputMessage): boolean {
-  if (message.role !== "assistant" || hasToolCalls(message)) return false;
-  if (!Array.isArray(message.content) || message.content.length === 0) return false;
-  return message.content.every(
-    (block) =>
-      block.type === "text" &&
-      (block.text.trim().length === 0 || block.text.trim() === EMPTY_ASSISTANT_CONTENT_FALLBACK),
-  );
+/** 有序 assistant 条目按请求顺序排列的块(和 transform 用同一个函数),否则 undefined。 */
+function orderedMessageItems(message: ModelInputMessage): OrderedAssistantItem[] | undefined {
+  return message.role === "assistant" && Array.isArray(message.content)
+    ? orderedAssistantItems(message.content, message.toolCalls)
+    : undefined;
+}
+
+/** 只删除或移动块,不合并块。没有变化时返回原对象,调用方据此判断是否改写了请求。 */
+function applyOrderedAssistantRules(message: ModelInputMessage): ModelInputMessage {
+  const items = orderedMessageItems(message);
+  if (!items) return message;
+  const next = foldOrderedItems(items);
+  return next.length === items.length && next.every((item, index) => item === items[index])
+    ? message
+    : withOrderedItems(message, next);
+}
+
+// 按到达顺序逐块加入,每加入一块对"已有结果 + 新块"执行规则 a、b。
+// 修复原因:对整个条目各执行一次时,最后才出现的思考块会把前面本该后移的工具留在原位,
+// 末尾空白也会因为后面补上的思考块而保留,与逐块合并的结果不同(E2E I76 形态 P 1 A 2 B、P A W B 1)。
+function foldOrderedItems(items: OrderedAssistantItem[]): OrderedAssistantItem[] {
+  let result: OrderedAssistantItem[] = [];
+  for (const item of items) {
+    result =
+      result.length === 0 ? [item] : moveToolUsesToEnd(filterWhitespaceText([...result, item]));
+  }
+  return result;
+}
+
+// 规则 a:去掉纯空白文字块,前后两个块都是思考块时保留;过滤后只剩思考块时放弃这次过滤。
+function filterWhitespaceText(items: OrderedAssistantItem[]): OrderedAssistantItem[] {
+  const filtered = items.filter((item, index) => {
+    if (item.kind !== "content" || item.block.type !== "text") return true;
+    if (item.block.text.length === 0 || item.block.text.trim() !== "") return true;
+    return isReasoningItem(items[index - 1]) && isReasoningItem(items[index + 1]);
+  });
+  return filtered.some((item) => !isReasoningItem(item)) ? filtered : items;
+}
+
+// 规则 b:第一个 tool_use 后面还有非工具块时,把 tool_use 移到末尾并保持相对顺序;
+// 条目里出现"思考 → tool_use(s) → 思考"时保持原顺序。只移动 tool_use 不影响思考签名。
+function moveToolUsesToEnd(items: OrderedAssistantItem[]): OrderedAssistantItem[] {
+  let seenTool = false;
+  let nonToolAfterTool = false;
+  let previousContentIsReasoning = false;
+  let toolSincePreviousContent = false;
+  for (const item of items) {
+    if (item.kind === "tool") {
+      seenTool = true;
+      toolSincePreviousContent = true;
+      continue;
+    }
+    if (seenTool) nonToolAfterTool = true;
+    const reasoning = isReasoningItem(item);
+    if (reasoning && previousContentIsReasoning && toolSincePreviousContent) return items;
+    previousContentIsReasoning = reasoning;
+    toolSincePreviousContent = false;
+  }
+  if (!nonToolAfterTool) return items;
+  return [
+    ...items.filter((item) => item.kind !== "tool"),
+    ...items.filter((item) => item.kind === "tool"),
+  ];
 }
 
+// 按新顺序重新编号,transform 排列后得到同样的顺序。只改请求副本,不改 canonical history。
+function withOrderedItems(
+  message: ModelInputMessage,
+  items: OrderedAssistantItem[],
+): ModelInputMessage {
+  const content: ModelMessageContentBlock[] = [];
+  const toolCalls: NonNullable<ModelInputMessage["toolCalls"]> = [];
+  items.forEach((item, blockIndex) => {
+    if (item.kind === "content")
+      content.push({ ...item.block, blockIndex } as ModelMessageContentBlock);
+    else toolCalls.push({ ...item.call, blockIndex });
+  });
+  return {
+    ...message,
+    content,
+    ...(message.toolCalls ? { toolCalls } : {}),
+  };
+}
+
+function isReasoningItem(item: OrderedAssistantItem | undefined): boolean {
+  return item?.kind === "content" && item.block.type === "reasoning";
+}
+
+function maxBlockIndex(message: ModelInputMessage): number {
+  const contentIndices = Array.isArray(message.content)
+    ? message.content.map((block) => ("blockIndex" in block ? (block.blockIndex ?? -1) : -1))
+    : [];
+  const toolIndices = (message.toolCalls ?? []).map((call) => call.blockIndex ?? -1);
+  return Math.max(-1, ...contentIndices, ...toolIndices);
+}
+
+function mapMessages(
+  messages: ModelInputMessage[],
+  map: (message: ModelInputMessage) => ModelInputMessage,
+): ModelInputMessage[] {
+  let result: ModelInputMessage[] | undefined;
+  messages.forEach((message, index) => {
+    const next = map(message);
+    if (next === message) return;
+    result ??= messages.slice();
+    result[index] = next;
+  });
+  return result ?? messages;
+}
+
+// 非末尾、没有工具调用、内容为空或只剩空白文字的回复补 `(no content)`,不删除这条回复。
+// core 投影的请求一般走不到这里:没有可见内容的回复已被删除,留作估算锚点的空回复存成空字符串,
+// 这里只处理数组。主要是调用方自己拼的消息(MCP Apps sampling)有这种内容。
 function repairEmptyAssistantContent(messages: ModelInputMessage[]): ModelInputMessage[] {
   let result: ModelInputMessage[] | undefined;
 
@@ -214,7 +355,7 @@ function repairEmptyAssistantContent(messages: ModelInputMessage[]): ModelInputM
     if (
       message.role !== "assistant" ||
       !Array.isArray(message.content) ||
-      message.content.length > 0 ||
+      !message.content.every((block) => block.type === "text" && block.text.trim().length === 0) ||
       hasToolCalls(message)
     ) {
       continue;
@@ -230,54 +371,6 @@ function repairEmptyAssistantContent(messages: ModelInputMessage[]): ModelInputM
   return result ?? messages;
 }
 
-function mergeUserMessagePair(
-  previous: ModelInputMessage,
-  message: ModelInputMessage,
-): ModelInputMessage {
-  const merged: ModelInputMessage = {
-    role: "user",
-    content: mergeUserContent(previous.content, message.content),
-  };
-  const cacheControl = message.cacheControl ?? previous.cacheControl;
-  if (cacheControl) merged.cacheControl = { ...cacheControl };
-  return merged;
-}
-
-function canMergeAdjacentUserMessages(
-  previous: ModelInputMessage | undefined,
-  next: ModelInputMessage,
-): previous is ModelInputMessage & { role: "user" } {
-  if (previous?.role !== "user" || next.role !== "user") return false;
-  return !isToolResultUserMessage(previous) && !isToolResultUserMessage(next);
-}
-
-function isToolResultUserMessage(message: ModelInputMessage): boolean {
-  return message.role === "user" && Boolean(message.toolCallId || message.toolName);
-}
-
-function mergeUserContent(
-  previous: ModelMessageContent,
-  next: ModelMessageContent,
-): ModelMessageContentBlock[] {
-  const previousBlocks = contentAsBlocks(previous);
-  const nextBlocks = contentAsBlocks(next);
-  const previousLast = previousBlocks.at(-1);
-  const nextFirst = nextBlocks[0];
-
-  if (previousLast?.type === "text" && nextFirst?.type === "text") {
-    previousBlocks[previousBlocks.length - 1] = {
-      ...previousLast,
-      text: `${previousLast.text}\n`,
-    };
-  }
-
-  return [...previousBlocks, ...nextBlocks];
-}
-
-function contentAsBlocks(content: ModelMessageContent): ModelMessageContentBlock[] {
-  return typeof content === "string" ? [{ type: "text", text: content }] : [...content];
-}
-
 function isSignedOrRedactedReasoning(block: ModelReasoningContentBlock): boolean {
   const anthropic = anthropicOptions(block.providerOptions);
   return (

+ 14 - 1
apps/zcode-cli/packages/adapters/src/model/runner-generate.ts

@@ -15,6 +15,7 @@ import { createGenerateTextOptions } from "./runner-options.js";
 import { detectProviderBusinessFinishError } from "./provider-finish-business-error.js";
 import {
   normalizeReasoning,
+  orderGeneratedContent,
   normalizeSources,
   normalizeToolCalls,
   normalizeToolResults,
@@ -59,7 +60,10 @@ import {
   retryAllowedByFailurePolicy,
 } from "./workflow-model-failure-policy.js";
 import { modelFailureStatusFields, providerRequestIdFromHeaders } from "./runner-telemetry.js";
-import { repairReasoningHistoryAfterSignatureRejection } from "./reasoning-history-normalization.js";
+import {
+  repairReasoningHistoryAfterSignatureRejection,
+  thinkingSignatureRejectionEvidence,
+} from "./reasoning-history-normalization.js";
 import { admitAttempt, type AttemptAdmission } from "./request-admission.js";
 import {
   retryAttemptLoopContinues,
@@ -339,8 +343,13 @@ export async function runGenerateText(input: {
         statusPublishOptions(input, admission),
       );
 
+      // 结构化输出的 text 是序列化结果,不对应模型块,不编号。
+      const textBlocks = input.request.responseJsonSchema
+        ? undefined
+        : orderGeneratedContent(result, { text, reasoning, toolCalls });
       return {
         text,
+        ...(textBlocks ? { textBlocks } : {}),
         finishReason: result.finishReason,
         usage,
         reasoning,
@@ -348,6 +357,8 @@ export async function runGenerateText(input: {
         toolResults,
         sources,
         providerMetadata: result.providerMetadata as Record<string, unknown> | undefined,
+        // 修复后的重试成功:core 在产出的 assistant 上记标记,之后的请求不再发被拒的块。
+        ...(signatureRepairAttempted ? { signedReasoningReset: true } : {}),
       };
     } catch (error) {
       // 合并后鉴权解析进入 attempt try;与 stream 一致保留网络前凭据缺失的类型化错误。
@@ -496,6 +507,8 @@ export async function runGenerateText(input: {
           nextAttempt: attempt + 1,
           requestId: statusContext.requestId,
           status: "waiting",
+          // 记下 provider 原文和 prefix 不一致响应头:写明哪一块、因为什么被拒,排查前缀变化时用。
+          ...thinkingSignatureRejectionEvidence(error, responseHeaders),
         });
         await publishRetryScheduledStatus(
           input,

+ 50 - 0
apps/zcode-cli/packages/adapters/src/model/runner-normalization.ts

@@ -4,6 +4,7 @@ import type {
   ModelReasoningContentBlock,
   ModelSource,
   ModelStreamEvent,
+  ModelTextContentBlock,
   ModelTextResult,
   ModelToolResult,
   ModelUsage,
@@ -59,6 +60,55 @@ export function normalizeReasoning(
     }));
 }
 
+/**
+ * 非流式结果按 AI SDK `result.content` 的顺序给 reasoning、text、tool-call 编号
+ * (docs/design/v2/model/assistant-block-order.md),跳过 tool-result、source、file 等其他类型。
+ * 与已规范化的 text / reasoning / toolCalls 对不上时不编号,按旧数据处理。
+ */
+export function orderGeneratedContent(
+  result: AiSdkGenerateTextResult,
+  normalized: {
+    text: string;
+    reasoning?: ModelReasoningContentBlock[];
+    toolCalls?: ModelTextResult["toolCalls"];
+  },
+): ModelTextContentBlock[] | undefined {
+  const content = (result as unknown as { content?: unknown[] }).content;
+  if (!Array.isArray(content)) return undefined;
+  const reasoning = normalized.reasoning ?? [];
+  const toolCallById = new Map((normalized.toolCalls ?? []).map((call) => [call.id, call]));
+  const textBlocks: ModelTextContentBlock[] = [];
+  const reasoningIndices: number[] = [];
+  const toolIndices = new Map<string, number>();
+  let nextBlockIndex = 0;
+  for (const part of content) {
+    const record = asRecord(part);
+    const type = stringProperty(record, "type");
+    if (type === "reasoning" && typeof record?.text === "string") {
+      reasoningIndices.push(nextBlockIndex++);
+    } else if (type === "text" && typeof record?.text === "string") {
+      textBlocks.push({ type: "text", text: record.text, blockIndex: nextBlockIndex++ });
+    } else if (type === "tool-call") {
+      const toolCallId = stringProperty(record, "toolCallId");
+      if (toolCallId) toolIndices.set(toolCallId, nextBlockIndex);
+      nextBlockIndex++;
+    }
+  }
+  if (
+    reasoningIndices.length !== reasoning.length ||
+    textBlocks.map((block) => block.text).join("") !== normalized.text ||
+    toolIndices.size !== toolCallById.size ||
+    [...toolCallById.keys()].some((id) => !toolIndices.has(id))
+  ) {
+    return undefined;
+  }
+  reasoning.forEach((block, index) => {
+    block.blockIndex = reasoningIndices[index];
+  });
+  for (const [id, blockIndex] of toolIndices) toolCallById.get(id)!.blockIndex = blockIndex;
+  return textBlocks;
+}
+
 export function toModelStreamEvent(chunk: TextStreamPart<ToolSet>): ModelStreamEvent | undefined {
   switch (chunk.type) {
     case "start":

+ 18 - 5
apps/zcode-cli/packages/adapters/src/model/runner-stream.ts

@@ -93,7 +93,10 @@ import {
   providerRequestIdFromHeaders,
   readModelFailureErrorPhase,
 } from "./runner-telemetry.js";
-import { repairReasoningHistoryAfterSignatureRejection } from "./reasoning-history-normalization.js";
+import {
+  repairReasoningHistoryAfterSignatureRejection,
+  thinkingSignatureRejectionEvidence,
+} from "./reasoning-history-normalization.js";
 
 type StreamFailurePhase = "request_setup" | "response_body";
 
@@ -127,6 +130,11 @@ export async function* runStreamText(input: {
   const isDev = isDevelopmentModelIOEnv(input.env);
   let requestMessages = input.request.messages;
   let signatureRepairAttempted = false;
+  // 修复后的重试成功时,在 finish 上告诉 core 记 signedReasoningReset,之后的请求不再发被拒的块。
+  const withRepairMarker = (event: ModelStreamEvent): ModelStreamEvent =>
+    signatureRepairAttempted && event.type === "finish"
+      ? { ...event, signedReasoningReset: true }
+      : event;
   const authRetry = new AccountRequestRetry(input.request, input.resolved, input.logger);
   let emptyCompletionRetryCount = 0;
   // 不认识的业务码在本次请求里连续出现的次数:workflow 策略表据此停下,见 workflow-model-failure-policy.ts。
@@ -219,6 +227,11 @@ export async function* runStreamText(input: {
         nextAttempt: attempt + 1,
         requestId: statusContext.requestId,
         status: "waiting",
+        // 记下 provider 原文和 prefix 不一致响应头:写明哪一块、因为什么被拒,排查前缀变化时用。
+        ...thinkingSignatureRejectionEvidence(
+          error,
+          sanitizeModelNetworkHeaders(getResponseHeaders(unwrapRetryError(error))),
+        ),
       });
       return true;
     };
@@ -422,7 +435,7 @@ export async function* runStreamText(input: {
             emittedRetryBoundaryEvent = true;
             for (const pendingEvent of pendingRetrySafeEvents.splice(0)) {
               emittedEvent = true;
-              yield pendingEvent;
+              yield withRepairMarker(pendingEvent);
             }
             // 无 raw message-block provenance 的 provider 可能直接给完整 tool-call。
             // 先把 inferred block stop 交给隐藏 collector,再传播校验错误,避免 HTTP 重放。
@@ -487,7 +500,7 @@ export async function* runStreamText(input: {
             const observation = observeVisibleStreamEvent(visibleEvent, Date.now() - startedAt);
             await publishVisibleMilestones(observation);
             streamOutputCommitted = streamOutputCommitted || observation.outputCommitted;
-            yield visibleEvent;
+            yield withRepairMarker(visibleEvent);
           }
         }
       }
@@ -514,7 +527,7 @@ export async function* runStreamText(input: {
           const observation = observeVisibleStreamEvent(visibleEvent, Date.now() - startedAt);
           await publishVisibleMilestones(observation);
           streamOutputCommitted = streamOutputCommitted || observation.outputCommitted;
-          yield visibleEvent;
+          yield withRepairMarker(visibleEvent);
         }
       }
 
@@ -523,7 +536,7 @@ export async function* runStreamText(input: {
         const observation = observeVisibleStreamEvent(pendingEvent, Date.now() - startedAt);
         await publishVisibleMilestones(observation);
         streamOutputCommitted = streamOutputCommitted || observation.outputCommitted;
-        yield pendingEvent;
+        yield withRepairMarker(pendingEvent);
       }
 
       if (!emittedError) {

+ 2 - 0
apps/zcode-cli/packages/adapters/src/model/tool-search.ts

@@ -40,5 +40,7 @@ export function resolveModelRequestCapabilities(
     toolSearch: resolveToolSearchCapability(apiType, access),
     // 只在 Anthropic Messages 协议把提醒并入 tool result;OpenAI 兼容协议保持独立的 user 消息。
     foldRemindersIntoToolResults: apiType === ANTHROPIC_MESSAGES_API_TYPE,
+    // Anthropic Messages 的请求不带没有可见内容(只有思考和空白文字)的回复,由 core 投影第一步删除。
+    dropReasoningOnlyOrBlankAssistants: apiType === ANTHROPIC_MESSAGES_API_TYPE,
   };
 }

+ 50 - 11
apps/zcode-cli/packages/adapters/src/model/transform.ts

@@ -5,6 +5,7 @@
 import { type ModelMessage as AiSdkModelMessage, type ToolResultPart } from "ai";
 import {
   ModelErrorCode,
+  isBlockIndex,
   modelMessageContentToText,
   type ModelCacheControl,
   type ModelInputMessage,
@@ -292,20 +293,29 @@ function toAiSdkAssistantContent(
   toolCalls: ModelInputMessage["toolCalls"],
   options: AiSdkAssistantTransformOptions,
 ): AiSdkAssistantContent {
-  const toolCallParts =
-    toolCalls?.map(
-      (toolCall): AiSdkAssistantContentPart => ({
-        type: "tool-call",
-        toolCallId: toolCall.id,
-        toolName: projectToolNameForProvider(toolCall.name, options),
-        input: toolCall.input,
-      }),
-    ) ?? [];
-
-  if (typeof content === "string" && toolCallParts.length === 0) {
+  if (typeof content === "string" && !toolCalls?.length) {
     return content;
   }
+  const toToolCallPart = (toolCall: ModelInputToolCall): AiSdkAssistantContentPart => ({
+    type: "tool-call",
+    toolCallId: toolCall.id,
+    toolName: projectToolNameForProvider(toolCall.name, options),
+    input: toolCall.input,
+  });
+
+  const ordered =
+    typeof content === "string" ? undefined : orderedAssistantItems(content, toolCalls);
+  if (ordered) {
+    // 有序条目(docs/design/v2/model/assistant-block-order.md):按 orderedAssistantItems 的顺序
+    // 输出内容块与工具调用。只改变顺序,不合并块;blockIndex 不进入请求。
+    return ordered.flatMap((item) =>
+      item.kind === "content"
+        ? contentBlockToAiSdkAssistantParts(item.block, options)
+        : [toToolCallPart(item.call)],
+    );
+  }
 
+  const toolCallParts = toolCalls?.map(toToolCallPart) ?? [];
   const contentParts =
     typeof content === "string"
       ? content.length > 0
@@ -316,6 +326,35 @@ function toAiSdkAssistantContent(
   return [...contentParts, ...toolCallParts];
 }
 
+type ModelInputToolCall = NonNullable<ModelInputMessage["toolCalls"]>[number];
+
+/** 有序条目里的一个块:内容块或工具调用,带它的 blockIndex。 */
+export type OrderedAssistantItem =
+  | { kind: "content"; block: ModelMessageContentBlock; blockIndex: number }
+  | { kind: "tool"; call: ModelInputToolCall; blockIndex: number };
+
+/**
+ * 有序条目(docs/design/v2/model/assistant-block-order.md):内容块与工具调用的 blockIndex 都合法时,
+ * 返回按 blockIndex 稳定排序的块,序号相同时内容块在前;否则返回 undefined。
+ * 请求排列和 Anthropic 规则(reasoning-history-normalization.ts)都用它,两边的判定和顺序因此一致。
+ */
+export function orderedAssistantItems(
+  content: readonly ModelMessageContentBlock[],
+  toolCalls: ModelInputMessage["toolCalls"],
+): OrderedAssistantItem[] | undefined {
+  const items: OrderedAssistantItem[] = [];
+  for (const block of content) {
+    const blockIndex = "blockIndex" in block ? block.blockIndex : undefined;
+    if (!isBlockIndex(blockIndex)) return undefined;
+    items.push({ kind: "content", block, blockIndex });
+  }
+  for (const call of toolCalls ?? []) {
+    if (!isBlockIndex(call.blockIndex)) return undefined;
+    items.push({ kind: "tool", call, blockIndex: call.blockIndex });
+  }
+  return items.sort((left, right) => left.blockIndex - right.blockIndex);
+}
+
 function contentBlockToAiSdkAssistantParts(
   block: ModelMessageContentBlock,
   options: AiSdkAssistantTransformOptions,

+ 15 - 11
apps/zcode-cli/packages/adapters/src/network/proxy-fetch.ts

@@ -64,12 +64,7 @@ export function createNetworkProxyFetch(options: NetworkProxyFetchOptions): Netw
 }
 
 function hasNetworkFetchPolicy(options: NetworkProxyFetchOptions): boolean {
-  return Boolean(
-    options.caCertFile ||
-      options.env ||
-      options.httpProxy ||
-      options.noProxy,
-  );
+  return Boolean(options.caCertFile || options.env || options.httpProxy || options.noProxy);
 }
 
 function readFetchInputUrl(input: Parameters<NetworkFetch>[0]): URL | undefined {
@@ -100,7 +95,13 @@ async function normalizeFetchRequest(
     body,
     headers: request.headers,
     method,
-    signal: request.signal,
+    // 临时 Request 的 controller 可被 GC,不能把其从属 signal 留作取消来源。
+    signal:
+      init?.signal !== undefined
+        ? init.signal
+        : input instanceof Request
+          ? input.signal
+          : undefined,
     url: new URL(request.url),
   };
 }
@@ -124,7 +125,6 @@ function fetchWithAgent(
 
     const cleanupAll = (): void => {
       signal?.removeEventListener("abort", onAbort);
-      clientRequest?.off("error", onRequestError);
       clientRequest?.off("close", onRequestClose);
       responseMessage?.off("close", cleanupAll);
       responseMessage?.off("error", onResponseError);
@@ -159,7 +159,7 @@ function fetchWithAgent(
 
     clientRequest = transport.request(
       {
-        agent: createRequestAgent(request.url, options),
+        agent: createRequestAgent(request.url, { ...options, signal }),
         headers: headersToOutgoing(request.headers),
         hostname: request.url.hostname,
         method: request.method,
@@ -186,7 +186,9 @@ function fetchWithAgent(
       },
     );
 
-    clientRequest.once("error", onRequestError);
+    // 响应读完后 MCP 会立即取消代理连接,底层 socket 与 TLS 可在请求 close 后各转发一次错误。
+    // 监听随请求对象回收,不能提前移除或只监听一次,否则单次 MCP 失败会带崩 Agent。
+    clientRequest.on("error", onRequestError);
     clientRequest.once("close", onRequestClose);
     clientRequest.end(request.body);
   });
@@ -204,11 +206,13 @@ function abortReason(signal: AbortSignal | undefined): Error {
 
 function createRequestAgent(
   url: URL,
-  options: { ca?: Buffer; proxyUrl?: string },
+  options: { ca?: Buffer; proxyUrl?: string; signal?: AbortSignal },
 ): http.Agent | https.Agent | ProxyAgent {
   if (options.proxyUrl) {
     return new ProxyAgent({
       ca: options.ca,
+      // CONNECT 返回前 socket 尚未归属 ClientRequest,取消必须抵达建连层。
+      signal: options.signal,
       getProxyForUrl: () => options.proxyUrl ?? "",
       httpsAgent: options.ca ? new https.Agent({ ca: options.ca }) : undefined,
     }) as unknown as http.Agent;

+ 96 - 19
apps/zcode-cli/packages/adapters/src/plugins/atomic-directory.ts

@@ -1,6 +1,6 @@
 import { randomUUID } from "node:crypto";
 import { existsSync, readFileSync, renameSync, rmSync } from "node:fs";
-import { access, cp, mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises";
+import { access, cp, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
 import { basename, dirname, join, resolve } from "node:path";
 import { appendPluginSourceCleanupError, cleanupPluginSourceBestEffort } from "./helpers.js";
 
@@ -59,6 +59,35 @@ function getAtomicRecoveryPaths(targetPath: string): {
   };
 }
 
+/** 读取 standalone 原子文件的完整一代;恢复清理由现有写入口负责,读者不抢占事务。 */
+export async function readStandaloneAtomicFile(targetPath: string): Promise<string> {
+  const { backupPath, transactionPath } = getAtomicRecoveryPaths(targetPath);
+  let preferBackup = false;
+  try {
+    const transaction = JSON.parse(
+      await readFile(transactionPath, "utf8"),
+    ) as Partial<AtomicTransactionRecordV2>;
+    preferBackup =
+      transaction.version === 2 &&
+      transaction.mode === "standalone" &&
+      typeof transaction.ownerId === "string" &&
+      Number.isSafeInteger(transaction.ownerPid) &&
+      (transaction.ownerPid ?? 0) > 0 &&
+      isAtomicTransactionOwnerAlive(transaction as AtomicTransactionRecordV2);
+  } catch {
+    // 没有事务标记时优先读取 target;崩溃留下的 backup 仍可作为缺失回退。
+  }
+  const first = preferBackup ? backupPath : targetPath;
+  const second = preferBackup ? targetPath : backupPath;
+  try {
+    return await readFile(first, "utf8");
+  } catch (error) {
+    if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+    // writer 可以在选定路径之后完成 promote/finalize;只在缺失时读取另一完整文件。
+    return await readFile(second, "utf8");
+  }
+}
+
 export function recoverAtomicTargetSync(targetPath: string): string {
   const parent = dirname(targetPath);
   const name = basename(targetPath);
@@ -68,24 +97,7 @@ export function recoverAtomicTargetSync(targetPath: string): string {
 
   let transaction: AtomicTransactionRecord | undefined;
   try {
-    const parsed = JSON.parse(
-      readFileSync(transactionPath, "utf8"),
-    ) as Partial<AtomicTransactionRecord>;
-    if (parsed.version === 1 && typeof parsed.stageName === "string") {
-      transaction = { stageName: parsed.stageName, version: 1 };
-    } else if (
-      parsed.version === 2 &&
-      typeof parsed.stageName === "string" &&
-      typeof parsed.transactionId === "string" &&
-      typeof parsed.ownerId === "string" &&
-      Number.isSafeInteger(parsed.ownerPid) &&
-      (parsed.ownerPid ?? 0) > 0 &&
-      typeof parsed.hadTarget === "boolean" &&
-      (parsed.mode === "coordinated" || parsed.mode === "standalone") &&
-      (parsed.authorityPath === undefined || typeof parsed.authorityPath === "string")
-    ) {
-      transaction = parsed as AtomicTransactionRecordV2;
-    }
+    transaction = parseAtomicTransaction(JSON.parse(readFileSync(transactionPath, "utf8")));
   } catch {
     transaction = undefined;
   }
@@ -170,6 +182,10 @@ function authorityContainsTransactionSync(authorityPath: string, transactionId:
   } catch {
     return false;
   }
+  return containsTransaction(value, transactionId);
+}
+
+function containsTransaction(value: unknown, transactionId: string): boolean {
   const pending: unknown[] = [value];
   while (pending.length > 0) {
     const current = pending.pop();
@@ -435,3 +451,64 @@ function throwIfAborted(signal: AbortSignal | undefined): void {
   error.name = "AbortError";
   throw error;
 }
+
+function parseAtomicTransaction(value: unknown): AtomicTransactionRecord | undefined {
+  const parsed = value as Partial<AtomicTransactionRecord>;
+  if (typeof parsed !== "object" || parsed === null) return undefined;
+  if (parsed.version === 1 && typeof parsed.stageName === "string") {
+    return { stageName: parsed.stageName, version: 1 };
+  } else if (
+    parsed.version === 2 &&
+    typeof parsed.stageName === "string" &&
+    typeof parsed.transactionId === "string" &&
+    typeof parsed.ownerId === "string" &&
+    Number.isSafeInteger(parsed.ownerPid) &&
+    (parsed.ownerPid ?? 0) > 0 &&
+    typeof parsed.hadTarget === "boolean" &&
+    (parsed.mode === "coordinated" || parsed.mode === "standalone") &&
+    (parsed.authorityPath === undefined || typeof parsed.authorityPath === "string")
+  ) {
+    return parsed as AtomicTransactionRecordV2;
+  }
+  return undefined;
+}
+
+/**
+ * 发现读取完整版本;不接管仍活跃的安装事务。
+ * 已死亡事务的残留在返回前恢复成 target:discovery 的路径会被会话长期持有,
+ * 若直接返回 backup,后续 describe/安装触发的恢复会把它改名为 target,会话里的 Skill/Hook 路径随即 ENOENT。
+ */
+export async function resolveAtomicReadPath(targetPath: string): Promise<string> {
+  const { backupPath, transactionPath } = getAtomicRecoveryPaths(targetPath);
+  let transaction: AtomicTransactionRecord | undefined;
+  try {
+    transaction = parseAtomicTransaction(JSON.parse(await readFile(transactionPath, "utf8")));
+  } catch {
+    transaction = undefined;
+  }
+  const live =
+    activeAtomicTargets.get(resolve(targetPath)) ??
+    (transaction?.version === 2 && isAtomicTransactionOwnerAlive(transaction)
+      ? transaction
+      : undefined);
+  if (live) {
+    let committed = false;
+    if (live.mode === "coordinated" && live.authorityPath) {
+      try {
+        committed = containsTransaction(
+          JSON.parse(await readStandaloneAtomicFile(live.authorityPath)),
+          live.transactionId,
+        );
+      } catch {
+        committed = false;
+      }
+    }
+    if (committed) return targetPath;
+    if (await pathExists(backupPath)) return backupPath;
+    return live.hadTarget && (await pathExists(targetPath)) ? targetPath : backupPath;
+  }
+  // 常态无残留,不进入恢复;只有崩溃残留才走与 describe/activation 相同的同步恢复。
+  if (!transaction && !(await pathExists(backupPath))) return targetPath;
+  // 恢复内部会再检查一次活跃事务:异步检查之后才启动的 writer 不会被抢走 backup。
+  return recoverAtomicTargetSync(targetPath);
+}

+ 400 - 18
apps/zcode-cli/packages/adapters/src/plugins/helpers.ts

@@ -1,7 +1,42 @@
-import { statSync } from "node:fs";
-import { isAbsolute, relative, resolve, sep } from "node:path";
+import { mkdir, readdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
+import { setTimeout as delay } from "node:timers/promises";
+import { randomUUID } from "node:crypto";
+import { type Dirent, statSync } from "node:fs";
+import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
+import { scanSkillFilesUnderRoot } from "../skills/scan.js";
 
-const PLUGIN_SOURCE_CLEANUP_RETRY_DELAYS_MS = [0, 25, 100] as const;
+const PLUGIN_FS_RETRY_DELAYS_MS = [0, 25, 100] as const;
+
+export async function writePluginTextIfChanged(path: string, contents: string): Promise<void> {
+  try {
+    if ((await readFile(path, "utf8")) === contents) return;
+  } catch {
+    // 与原写入语义一致:读失败继续写,让实际写入错误向上传递。
+  }
+  await mkdir(dirname(path), { recursive: true });
+  const temporary = `${path}.tmp-${randomUUID()}`;
+  try {
+    await writeFile(temporary, contents, "utf8");
+    // 异步读写允许查询交错;原子替换避免读者看到半份目录或命令。
+    for (const [index, delayMs] of PLUGIN_FS_RETRY_DELAYS_MS.entries()) {
+      if (delayMs > 0) await delay(delayMs);
+      try {
+        await rename(temporary, path);
+        return;
+      } catch (error) {
+        // Windows 索引器可能短暂占用目标;有界重试仍保留旧文件与原子替换。
+        const code = (error as NodeJS.ErrnoException).code;
+        if (
+          !["EACCES", "EBUSY", "EEXIST", "ENOTEMPTY", "EPERM"].includes(code ?? "") ||
+          index === PLUGIN_FS_RETRY_DELAYS_MS.length - 1
+        )
+          throw error;
+      }
+    }
+  } finally {
+    await rm(temporary, { force: true }).catch(() => undefined);
+  }
+}
 
 export function resolveInside(rootPath: string, rawPath: string): string | null {
   if (isAbsolute(rawPath)) return null;
@@ -37,20 +72,6 @@ export function directoryExists(path: string): boolean {
   }
 }
 
-/**
- * 「路径缺失」只认 ENOENT/ENOTDIR(stat 的精确错误码)。EACCES 等权限错误
- * 不是缺失——调用方不得据此发「不存在」诊断,避免把权限问题误报成 manifest 配错。
- */
-export function isMissingPath(path: string): boolean {
-  try {
-    statSync(path);
-    return false;
-  } catch (error) {
-    const code = (error as { code?: unknown }).code;
-    return code === "ENOENT" || code === "ENOTDIR";
-  }
-}
-
 export function fileExists(path: string): boolean {
   try {
     return statSync(path).isFile();
@@ -70,7 +91,7 @@ export function isNotFoundError(error: unknown): boolean {
 
 export async function cleanupPluginSourceBestEffort(
   cleanup: (() => Promise<void>) | undefined,
-  retryDelaysMs: readonly number[] = PLUGIN_SOURCE_CLEANUP_RETRY_DELAYS_MS,
+  retryDelaysMs: readonly number[] = PLUGIN_FS_RETRY_DELAYS_MS,
 ): Promise<unknown> {
   if (!cleanup) return undefined;
   let cleanupError: unknown;
@@ -103,3 +124,364 @@ export function appendPluginSourceCleanupError(
 export function throwIfAborted(options: { signal?: AbortSignal } | undefined): void {
   if (options?.signal?.aborted) throw new Error("Plugin operation cancelled");
 }
+
+export async function directoryExistsAsync(path: string): Promise<boolean> {
+  try {
+    return (await stat(path)).isDirectory();
+  } catch {
+    return false;
+  }
+}
+export async function fileExistsAsync(path: string): Promise<boolean> {
+  try {
+    return (await stat(path)).isFile();
+  } catch {
+    return false;
+  }
+}
+/**
+ * 「路径缺失」只认 ENOENT/ENOTDIR(stat 的精确错误码)。EACCES 等权限错误
+ * 不是缺失——调用方不得据此发「不存在」诊断,避免把权限问题误报成 manifest 配错。
+ */
+export async function isMissingPathAsync(path: string): Promise<boolean> {
+  try {
+    await stat(path);
+    return false;
+  } catch (error) {
+    const code = (error as NodeJS.ErrnoException).code;
+    return code === "ENOENT" || code === "ENOTDIR";
+  }
+}
+
+const PLUGIN_MATERIAL_ENTRY_LIMIT = 512;
+const PLUGIN_METADATA_BATCH_SIZE = 32;
+export const PLUGIN_MATERIAL_READ_CONCURRENCY = 4;
+const PLUGIN_DIRECTORY_ENTRY_OVERHEAD_BYTES = 128;
+const PLUGIN_MATERIAL_BYTE_LIMIT = 4 * 1024 * 1024;
+const PLUGIN_SOURCE_CHANGED_CODE = "ZCODE_PLUGIN_SOURCES_CHANGED";
+const PLUGIN_STANDARD_ENTRY_NAMES = new Set([
+  ".zcode-plugin",
+  ".claude-plugin",
+  ".codex-plugin",
+  ".mcp.json",
+  "skills",
+  "commands",
+  "agents",
+  "hooks",
+  "hooks.json",
+  "skill.md",
+]);
+
+type PluginPathState =
+  | { fingerprint: string; kind: "file" | "directory" | "other" }
+  | { fingerprint: string; kind: "missing"; code: "ENOENT" | "ENOTDIR" };
+interface PluginMaterialEntry {
+  fingerprint: string;
+  value: unknown;
+  bytes: number;
+}
+export interface PluginMaterialReader {
+  parsed<T>(
+    path: string,
+    kind: "json" | "frontmatter" | "text",
+    parse: (contents: string) => T,
+  ): Promise<T>;
+  json(path: string): Promise<unknown>;
+  text(path: string): Promise<string>;
+  directory(path: string): Promise<Dirent[]>;
+  /** 插件技能入口:自身有技能时停止,否则扫描一层集合。 */
+  skillFiles(path: string, followSymbolicLinks?: boolean): Promise<string[]>;
+  fileExists(path: string): Promise<boolean>;
+  directoryExists(path: string): Promise<boolean>;
+  missing(path: string): Promise<boolean>;
+  observe(path: string): Promise<PluginPathState["kind"]>;
+  validate(): Promise<boolean>;
+}
+
+/** 只保留原始解析材料;每次发现有自己的依赖清单与配置投影,返回值不共享可写引用。 */
+export class PluginMaterialCache {
+  private readonly entries = new Map<string, PluginMaterialEntry>();
+  private readonly reads = new Set<Promise<void>>();
+  private readonly flights = new Map<
+    string,
+    { revision: number; fingerprint: string; promise: Promise<PluginMaterialEntry> }
+  >();
+  private readonly controller = new AbortController();
+  private revision = 0;
+  private bytes = 0;
+  get signal(): AbortSignal {
+    return this.controller.signal;
+  }
+
+  invalidate(): void {
+    this.revision += 1;
+    this.entries.clear();
+    this.flights.clear();
+    this.bytes = 0;
+  }
+  dispose(): void {
+    this.controller.abort();
+    this.invalidate();
+  }
+
+  reader(scope: string): PluginMaterialReader {
+    const revision = this.revision;
+    const observed = new Map<string, PluginPathState>();
+    const inspections = new Map<string, Promise<PluginPathState>>();
+    const directories = new Map<string, Set<string>>();
+    const skillScans = new Map<string, Promise<string[]>>();
+    const assertCurrent = () => {
+      this.controller.signal.throwIfAborted();
+      if (revision !== this.revision) throw pluginSourcesChanged();
+    };
+    const inspect = async (path: string) => {
+      assertCurrent();
+      // 先共享在途检查,避免并发调用在第一次 stat 完成前各查一遍。
+      const previous = inspections.get(path);
+      if (previous) return previous;
+      const inspection = (async (): Promise<PluginPathState> => {
+        for (let parent = dirname(path); ; parent = dirname(parent)) {
+          const names = directories.get(parent);
+          if (names) {
+            const name = relative(parent, path).split(sep)[0]!.toLowerCase();
+            // 只推断标准入口;父目录已加入复核清单,新增入口会使本次结果失效。
+            if (PLUGIN_STANDARD_ENTRY_NAMES.has(name) && !names.has(name))
+              return { kind: "missing", fingerprint: "ENOENT", code: "ENOENT" };
+            break;
+          }
+          if (parent === dirname(parent)) break;
+        }
+        const state = await readPluginPathState(path);
+        assertCurrent();
+        observed.set(path, state);
+        return state;
+      })();
+      inspections.set(path, inspection);
+      return inspection;
+    };
+    const parsed = async <T>(
+      path: string,
+      kind: "json" | "frontmatter" | "text",
+      parse: (contents: string) => T,
+    ): Promise<T> => {
+      const state = await inspect(path);
+      const entry = await this.load(scope, path, kind, state, revision, async () => {
+        const contents = await readFile(path, { encoding: "utf8", signal: this.signal });
+        return { value: parse(contents), bytes: Buffer.byteLength(contents, "utf8") };
+      });
+      assertCurrent();
+      return structuredClone(entry.value) as T;
+    };
+    const exists = async (path: string, kind: "file" | "directory") => {
+      try {
+        return (await inspect(path))?.kind === kind;
+      } catch (error) {
+        rethrowPluginMaterialInterrupt(error);
+        return false;
+      }
+    };
+    const reader: PluginMaterialReader = {
+      parsed,
+      json: (path) => parsed(path, "json", JSON.parse),
+      text: (path) => parsed(path, "text", (value) => value),
+      directory: async (path) => {
+        const state = await inspect(path);
+        const entry = await this.load(scope, path, "directory", state, revision, async () => {
+          const entries = await readdir(path, { withFileTypes: true });
+          return {
+            value: entries.map((item) => Object.freeze(item)),
+            bytes: entries.reduce(
+              (sum, item) =>
+                sum + Buffer.byteLength(item.name, "utf8") + PLUGIN_DIRECTORY_ENTRY_OVERHEAD_BYTES,
+              0,
+            ),
+          };
+        });
+        assertCurrent();
+        const entries = entry.value as Dirent[];
+        // ASCII 标准入口按大小写等价匹配;Unicode/文件系统别名不确定时保留实际探测。
+        if (entries.every((item) => /^[\x20-\x7e]+$/.test(item.name)))
+          directories.set(path, new Set(entries.map((item) => item.name.toLowerCase())));
+        return [...entries];
+      },
+      skillFiles: async (path, followSymbolicLinks = false) => {
+        assertCurrent();
+        const key = JSON.stringify([resolve(path), followSymbolicLinks]);
+        let scan = skillScans.get(key);
+        if (!scan) {
+          // 计数、诊断和详情必须共用本次扫描,但不能把文件列表沿用到下一次查询。
+          scan = scanSkillFilesUnderRoot(path, {
+            followSymbolicLinks,
+            stopAtSkill: true,
+            readDirectory: reader.directory,
+            observe: reader.observe,
+          });
+          skillScans.set(key, scan);
+        }
+        const files = await scan;
+        assertCurrent();
+        return [...files];
+      },
+      fileExists: (path) => exists(path, "file"),
+      directoryExists: (path) => exists(path, "directory"),
+      missing: async (path) => {
+        try {
+          return (await inspect(path)).kind === "missing";
+        } catch (error) {
+          rethrowPluginMaterialInterrupt(error);
+          return false;
+        }
+      },
+      observe: async (path) => {
+        return (await inspect(path)).kind;
+      },
+      validate: async () => {
+        assertCurrent();
+        const paths = [...observed];
+        for (let offset = 0; offset < paths.length; offset += PLUGIN_METADATA_BATCH_SIZE) {
+          const current = await Promise.all(
+            paths
+              .slice(offset, offset + PLUGIN_METADATA_BATCH_SIZE)
+              .map(
+                async ([path, state]) =>
+                  (await readPluginPathState(path)).fingerprint === state.fingerprint,
+              ),
+          );
+          assertCurrent();
+          if (current.includes(false)) return false;
+        }
+        assertCurrent();
+        return true;
+      },
+    };
+    return reader;
+  }
+
+  private async load(
+    scope: string,
+    path: string,
+    kind: string,
+    state: PluginPathState,
+    revision: number,
+    read: () => Promise<{ value: unknown; bytes: number }>,
+  ): Promise<PluginMaterialEntry> {
+    this.signal.throwIfAborted();
+    if (revision !== this.revision) throw pluginSourcesChanged();
+    const key = JSON.stringify([scope, kind, resolve(path)]);
+    const previous = this.entries.get(key);
+    if (previous && previous.fingerprint === state.fingerprint) return previous;
+    if (previous) {
+      this.bytes -= previous.bytes;
+      this.entries.delete(key);
+    }
+    // 缺失路径已经加入本次复核清单,不再为可选文件发起必然失败的读取。
+    if (state.kind === "missing")
+      throw Object.assign(new Error(`Plugin material not found: ${path}`), {
+        code: state.code,
+        path,
+      });
+    let flight = this.flights.get(key);
+    if (!flight || flight.revision !== revision || flight.fingerprint !== state.fingerprint) {
+      const promise = Promise.resolve().then(async () => {
+        // owner 内共享名额,避免多个查询各自四路读取时累加压满文件系统。
+        while (this.reads.size >= PLUGIN_MATERIAL_READ_CONCURRENCY) await Promise.race(this.reads);
+        this.signal.throwIfAborted();
+        if (revision !== this.revision) throw pluginSourcesChanged();
+        const reading = read();
+        const finished = reading.then(
+          () => {},
+          () => {},
+        );
+        this.reads.add(finished);
+        let material: { value: unknown; bytes: number };
+        try {
+          material = await reading;
+        } finally {
+          this.reads.delete(finished);
+        }
+        const after = await readPluginPathState(path);
+        this.signal.throwIfAborted();
+        if (revision !== this.revision || state.fingerprint !== after.fingerprint)
+          throw pluginSourcesChanged();
+        const entry = { ...material, fingerprint: after.fingerprint };
+        // 超预算材料仍可用,只是不保留;无需为本轮增加淘汰策略或后台 watcher。
+        if (
+          this.entries.size < PLUGIN_MATERIAL_ENTRY_LIMIT &&
+          this.bytes + entry.bytes <= PLUGIN_MATERIAL_BYTE_LIMIT
+        ) {
+          this.entries.set(key, entry);
+          this.bytes += entry.bytes;
+        }
+        return entry;
+      });
+      flight = { revision, fingerprint: state.fingerprint, promise };
+      this.flights.set(key, flight);
+      const current = flight;
+      void promise.then(
+        () => {
+          if (this.flights.get(key) === current) this.flights.delete(key);
+        },
+        () => {
+          if (this.flights.get(key) === current) this.flights.delete(key);
+        },
+      );
+    }
+    return flight.promise;
+  }
+}
+
+async function readPluginPathState(path: string): Promise<PluginPathState> {
+  try {
+    const [info, canonical] = await Promise.all([stat(path, { bigint: true }), realpath(path)]);
+    return {
+      kind: info.isFile() ? "file" : info.isDirectory() ? "directory" : "other",
+      fingerprint: JSON.stringify([
+        canonical,
+        String(info.dev),
+        String(info.ino),
+        String(info.size),
+        String(info.mtimeNs),
+        String(info.ctimeNs),
+        String(info.mode),
+      ]),
+    };
+  } catch (error) {
+    const code = (error as NodeJS.ErrnoException).code;
+    if (code === "ENOENT" || code === "ENOTDIR")
+      return { kind: "missing", fingerprint: code, code };
+    throw error;
+  }
+}
+
+export function pluginSourcesChanged(): Error & { code: string } {
+  return Object.assign(new Error("Plugin sources changed during discovery"), {
+    code: PLUGIN_SOURCE_CHANGED_CODE,
+  });
+}
+export function isPluginMaterialChange(error: unknown): boolean {
+  return (error as { code?: string } | undefined)?.code === PLUGIN_SOURCE_CHANGED_CODE;
+}
+export function rethrowPluginMaterialInterrupt(error: unknown): void {
+  if (
+    isPluginMaterialChange(error) ||
+    (error as { name?: string } | undefined)?.name === "AbortError"
+  )
+    throw error;
+}
+
+/** 消费者取消只结束本次等待,不取消其他调用者共用的材料读取。 */
+export async function waitForPluginQuery<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
+  let cancel: (() => void) | undefined;
+  try {
+    return await Promise.race([
+      work,
+      new Promise<never>((_, reject) => {
+        cancel = () => reject(signal.reason);
+        if (signal.aborted) cancel();
+        else signal.addEventListener("abort", cancel, { once: true });
+      }),
+    ]);
+  } finally {
+    if (cancel) signal.removeEventListener("abort", cancel);
+  }
+}

+ 48 - 20
apps/zcode-cli/packages/adapters/src/plugins/hook-sources.ts

@@ -1,8 +1,13 @@
-import { readFileSync, realpathSync } from "node:fs";
+import { readFile, realpath } from "node:fs/promises";
 import { join } from "node:path";
-import type { HookEventName, PluginDiagnostic } from "@zcode/contracts";
+import type { HookEventName, HookPluginContext, PluginDiagnostic } from "@zcode/contracts";
 import { HookEventName as HookEventNameValue } from "@zcode/contracts";
-import { fileExists, isRecord, resolveInside } from "./helpers.js";
+import {
+  fileExistsAsync,
+  isRecord,
+  resolveInside,
+  rethrowPluginMaterialInterrupt,
+} from "./helpers.js";
 import type { LoadedPlugin } from "./types.js";
 
 export const STANDARD_HOOKS_PATH = join("hooks", "hooks.json");
@@ -19,23 +24,26 @@ export interface PluginHookSource {
  * 统一发现插件 hook 来源文件,避免详情枚举和真实 loader 对 `hooks/hooks.json`
  * 与 `manifest.hooks` 的读取口径漂移。
  */
-export function listPluginHookSources(input: {
+export async function listPluginHookSources(input: {
   diagnostics: PluginDiagnostic[];
   loaded: LoadedPlugin;
-}): PluginHookSource[] {
+}): Promise<PluginHookSource[]> {
   const sources: PluginHookSource[] = [];
   const loadedHookPaths = new Set<string>();
   const standardHooksPath = join(input.loaded.rootPath, STANDARD_HOOKS_PATH);
 
-  if (fileExists(standardHooksPath)) {
-    const source = loadPluginHookSource({
+  if (
+    await (input.loaded.materials?.fileExists(standardHooksPath) ??
+      fileExistsAsync(standardHooksPath))
+  ) {
+    const source = await loadPluginHookSource({
       diagnostics: input.diagnostics,
       loaded: input.loaded,
       path: standardHooksPath,
     });
     if (source) {
       sources.push(source);
-      loadedHookPaths.add(realpathOrSelf(standardHooksPath));
+      loadedHookPaths.add(await realpathOrSelf(standardHooksPath));
     }
   }
 
@@ -56,7 +64,9 @@ export function listPluginHookSources(input: {
         });
         continue;
       }
-      if (!fileExists(hookFilePath)) {
+      if (
+        !(await (input.loaded.materials?.fileExists(hookFilePath) ?? fileExistsAsync(hookFilePath)))
+      ) {
         input.diagnostics.push({
           code: "plugin_hook_read_failed",
           message: `Plugin hooks file not found: ${hookSpec}`,
@@ -67,7 +77,7 @@ export function listPluginHookSources(input: {
         continue;
       }
 
-      const realPath = realpathOrSelf(hookFilePath);
+      const realPath = await realpathOrSelf(hookFilePath);
       if (loadedHookPaths.has(realPath)) {
         input.diagnostics.push({
           code: "plugin_hook_invalid",
@@ -79,7 +89,7 @@ export function listPluginHookSources(input: {
         continue;
       }
 
-      const source = loadPluginHookSource({
+      const source = await loadPluginHookSource({
         diagnostics: input.diagnostics,
         loaded: input.loaded,
         path: hookFilePath,
@@ -102,13 +112,13 @@ export function listPluginHookSources(input: {
 }
 
 /** 只抽取 hook 事件名,供 `plugins/describe` 展示;不会构造可执行 hook。 */
-export function listPluginHookEventNames(input: {
+export async function listPluginHookEventNames(input: {
   diagnostics: PluginDiagnostic[];
   loaded: LoadedPlugin;
-}): HookEventName[] {
+}): Promise<HookEventName[]> {
   const eventNames: HookEventName[] = [];
   const seen = new Set<string>();
-  for (const source of listPluginHookSources(input)) {
+  for (const source of await listPluginHookSources(input)) {
     const hooksRoot = source.wrapper
       ? isRecord(source.rawHooks)
         ? source.rawHooks.hooks
@@ -145,21 +155,25 @@ export function listPluginHookEventNames(input: {
   return eventNames;
 }
 
-function loadPluginHookSource(input: {
+async function loadPluginHookSource(input: {
   diagnostics: PluginDiagnostic[];
   loaded: LoadedPlugin;
   path: string;
-}): PluginHookSource | null {
+}): Promise<PluginHookSource | null> {
   try {
     return {
-      rawHooks: JSON.parse(readFileSync(input.path, "utf8")) as unknown,
+      rawHooks: input.loaded.materials
+        ? await input.loaded.materials.json(input.path)
+        : (JSON.parse(await readFile(input.path, "utf8")) as unknown),
       sourcePath: input.path,
       wrapper: true,
     };
   } catch (error) {
+    rethrowPluginMaterialInterrupt(error);
     input.diagnostics.push({
       code: "plugin_hook_read_failed",
-      message: error instanceof Error ? error.message : `Failed to read plugin hooks: ${input.path}`,
+      message:
+        error instanceof Error ? error.message : `Failed to read plugin hooks: ${input.path}`,
       path: input.path,
       pluginId: input.loaded.id,
       severity: "error",
@@ -168,10 +182,24 @@ function loadPluginHookSource(input: {
   }
 }
 
-function realpathOrSelf(path: string): string {
+async function realpathOrSelf(path: string): Promise<string> {
   try {
-    return realpathSync(path);
+    return await realpath(path);
   } catch {
     return path;
   }
 }
+
+export function createHookPluginContext(
+  loaded: LoadedPlugin,
+  dataPath: string,
+  sourcePath?: string,
+): HookPluginContext {
+  return {
+    dataPath,
+    id: loaded.id,
+    name: loaded.manifest.name,
+    rootPath: loaded.rootPath,
+    ...(sourcePath ? { sourcePath } : {}),
+  };
+}

+ 190 - 313
apps/zcode-cli/packages/adapters/src/plugins/index.ts

@@ -1,5 +1,7 @@
-import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { mkdir } from "node:fs/promises";
 import { join, resolve } from "node:path";
+import { z } from "zod";
+import { zcodePluginUserConfigOptionSchema } from "@zcode/shared";
 import type {
   CustomCommandRoot,
   HookConfig,
@@ -14,7 +16,6 @@ import type {
   PluginManifest,
   PluginUiSurfaceDefinition,
   PluginMetadata,
-  PluginOperationOptions,
   PluginPort,
   SkillRoot,
 } from "@zcode/contracts";
@@ -25,27 +26,35 @@ import {
   ZCODE_OFFICIAL_PLUGIN_MARKETPLACE,
 } from "@zcode/contracts";
 import {
-  directoryExists,
-  fileExists,
-  isMissingPath,
+  directoryExistsAsync,
   isNotFoundError,
   isRecord,
   parsePathList,
   resolveInside,
   sanitizePluginId,
   throwIfAborted,
+  PluginMaterialCache,
+  type PluginMaterialReader,
+  pluginSourcesChanged,
+  isPluginMaterialChange,
+  rethrowPluginMaterialInterrupt,
+  waitForPluginQuery,
 } from "./helpers.js";
-import { scanSkillFilesUnderRootSync } from "../skills/scan.js";
 import { loadPluginMcpServerDefinitions, resolvePluginMcpServers } from "./mcp.js";
 import { parsePluginUiSurfaces } from "./ui-surfaces.js";
-import { listPluginHookSources } from "./hook-sources.js";
-import { enumeratePluginComponents } from "./plugin-components.js";
+import { createHookPluginContext, listPluginHookSources } from "./hook-sources.js";
 import {
-  listInstalledPluginRecords,
+  countSkillFiles,
+  materializeCommandMetadataRoot,
+  warnEmptyDeclaredSkillRoots,
+  enumeratePluginComponents,
+} from "./plugin-components.js";
+import {
+  listInstalledPluginRecordsAsync,
   normalizeAuthorValue,
-  resolveInstalledPluginRoot,
+  resolveInstalledPluginRootAsync,
 } from "./marketplace.js";
-import { loadBundledOfficialPluginRootsSync } from "./official-marketplace.js";
+import { loadBundledOfficialPluginRoots } from "./official-marketplace.js";
 import type {
   LoadedPlugin,
   PluginAbortOptions,
@@ -66,6 +75,7 @@ export {
   loadKnownMarketplacesSync,
   loadMarketplaceManifestSync,
   normalizeAuthorValue,
+  parseEntryExtensionSummary,
   parseEntryStoreListing,
   parsePluginIconSources,
   parseMarketplaceSourceInput,
@@ -84,14 +94,15 @@ export {
   type PluginComponentGroup,
   type PluginComponentItem,
   type PluginComponentKind,
+  type PluginExtensionSummary,
   type PluginManifestDisplayMetadata,
   type PluginMarketplaceEntry,
   type PluginMarketplaceManifest,
 } from "./marketplace.js";
 
 export {
-  writeBundledOfficialMarketplacePartitionSync,
-  writeCdnOfficialMarketplacePartitionSync,
+  writeBundledOfficialMarketplacePartition,
+  writeCdnOfficialMarketplacePartition,
 } from "./official-marketplace.js";
 
 export { getPluginSourceDiagnosticCode } from "./source-errors.js";
@@ -106,8 +117,11 @@ const ZCODE_MANIFEST_PATH = join(".zcode-plugin", "plugin.json");
 const CLAUDE_MANIFEST_PATH = join(".claude-plugin", "plugin.json");
 const CODEX_MANIFEST_PATH = join(".codex-plugin", "plugin.json");
 const DEFAULT_VERSION = "0.0.0";
+// 外部清单的扩展字段不能穿透到 strict 协议;复用已知字段校验,尤其不能丢掉 sensitive。
+const pluginUserConfigSchema = z.record(z.string(), zcodePluginUserConfigOptionSchema.strip());
 const FIRST_PLUGIN_PRIORITY = 1_000;
 const PRIORITY_STEP = 10;
+const PLUGIN_DISCOVERY_REBUILD_LIMIT = 3;
 const PLUGIN_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]{0,127}$/;
 const UNSUPPORTED_COMPONENT_KEYS = ["channels", "lspServers", "outputStyles", "settings"] as const;
 const SUPPORTED_HOOK_EVENTS = new Set<string>(Object.values(HookEventNameValue));
@@ -122,24 +136,61 @@ export interface NodePluginAdapterOptions {
 }
 
 export class NodePluginAdapter implements PluginPort {
-  constructor(private readonly options: NodePluginAdapterOptions) {}
+  private readonly materials = new PluginMaterialCache();
+  invalidate(): void {
+    this.materials.invalidate();
+  }
+  dispose(): void {
+    this.materials.dispose();
+  }
 
   async discoverPlugins(
     request: PluginDiscoverRequest,
-    options?: PluginOperationOptions,
+    options?: PluginAbortOptions,
   ): Promise<PluginLoadOutcome> {
-    return this.discoverPluginsSync(request, options);
+    const signal = options?.signal
+      ? AbortSignal.any([options.signal, this.materials.signal])
+      : this.materials.signal;
+    return waitForPluginQuery(this.discoverCurrent(request, options), signal);
   }
 
-  discoverPluginsSync(
+  private async discoverCurrent(
     request: PluginDiscoverRequest,
     options?: PluginAbortOptions,
-  ): PluginLoadOutcome {
+  ): Promise<PluginLoadOutcome> {
+    for (let attempt = 0; attempt < PLUGIN_DISCOVERY_REBUILD_LIMIT; attempt += 1) {
+      this.materials.signal.throwIfAborted();
+      throwIfAborted(options);
+      const scope = JSON.stringify([
+        resolve(request.workingDirectory),
+        request.workspaceIdentity?.trim() || resolve(request.workingDirectory),
+        request.remoteSessionId?.trim() ?? "",
+        resolve(request.storageRoot || this.options.storageRoot),
+      ]);
+      const materials = this.materials.reader(scope);
+      try {
+        const outcome = await this.loadDiscovery(request, options, materials);
+        throwIfAborted(options);
+        if (await materials.validate()) return outcome;
+      } catch (error) {
+        if (!isPluginMaterialChange(error)) throw error;
+      }
+    }
+    throw pluginSourcesChanged();
+  }
+
+  constructor(private readonly options: NodePluginAdapterOptions) {}
+
+  private async loadDiscovery(
+    request: PluginDiscoverRequest,
+    options: PluginAbortOptions | undefined,
+    materials: PluginMaterialReader,
+  ): Promise<PluginLoadOutcome> {
     if (!request.config.enabled) return emptyOutcome();
 
     const diagnostics: PluginDiagnostic[] = [];
     const dataRoot = join(request.storageRoot || this.options.storageRoot, "data");
-    const candidates = this.resolveCandidates(request, diagnostics, options);
+    const candidates = await this.resolveCandidates(request, diagnostics, materials, options);
     const commandRoots: CustomCommandRoot[] = [];
     const hooks: PluginLoadOutcome["hooks"] = {};
     const mcpServers: PluginLoadOutcome["mcpServers"] = {};
@@ -150,7 +201,7 @@ export class NodePluginAdapter implements PluginPort {
 
     for (const candidate of candidates) {
       throwIfAborted(options);
-      const loaded = loadPlugin(candidate, diagnostics);
+      const loaded = await loadPlugin(candidate, diagnostics, materials);
       if (!loaded) continue;
       // 内置(官方)插件被「卸载」后只在 user config 写 suppressedBuiltins 标记。这里在发现层
       // 用插件的权威 id(manifest 名 @ marketplace)过滤,不依赖缓存文件是否已被物理删除——
@@ -182,16 +233,16 @@ export class NodePluginAdapter implements PluginPort {
       // 只从启用后解析出的 component.mcpServers 生成 mcpServerNames,
       // 未启用插件的内置 MCP 就会在管理页完全不可见。这里先读取声明名给 UI 只读展示,
       // 实际 runtime 注入仍只使用 enabled 分支解析出的 component.mcpServers。
-      const mcpServerDefinitions = loadPluginMcpServerDefinitions({ diagnostics, loaded });
+      const mcpServerDefinitions = await loadPluginMcpServerDefinitions({ diagnostics, loaded });
       const hooksRunnable = canRunPluginHooks(loaded);
-      const hookInspection = inspectPluginHooks({
+      const hookInspection = await inspectPluginHooks({
         dataPath,
         diagnostics,
         loaded,
         runnable: hooksRunnable,
       });
       const component = enabled
-        ? resolveEnabledComponents({
+        ? await resolveEnabledComponents({
             dataPath,
             diagnostics,
             env: request.env ?? {},
@@ -212,7 +263,7 @@ export class NodePluginAdapter implements PluginPort {
       commandRoots.push(...component.commandRoots);
       const declaredMcpServerNames = Object.keys(mcpServerDefinitions);
       plugins.push(
-        createPluginMetadata(
+        await createPluginMetadata(
           loaded,
           component,
           dataPath,
@@ -235,11 +286,12 @@ export class NodePluginAdapter implements PluginPort {
     };
   }
 
-  private resolveCandidates(
+  private async resolveCandidates(
     request: Pick<PluginDiscoverRequest, "config" | "officialPluginRoots" | "storageRoot">,
     diagnostics: PluginDiagnostic[],
+    materials: PluginMaterialReader,
     options?: PluginAbortOptions,
-  ): PluginCandidate[] {
+  ): Promise<PluginCandidate[]> {
     const candidates: PluginCandidate[] = [];
     for (const rootPath of request.config.dirs) {
       candidates.push({
@@ -258,18 +310,31 @@ export class NodePluginAdapter implements PluginPort {
       });
     }
     candidates.push(
-      ...scanOfficialCache(request.storageRoot, diagnostics, options).map((rootPath) => ({
-        defaultEnabled: false,
-        marketplace: ZCODE_OFFICIAL_PLUGIN_MARKETPLACE,
-        rootPath,
-        source: "official" as const,
-      })),
+      ...(await scanOfficialCache(request.storageRoot, diagnostics, materials, options)).map(
+        (rootPath) => ({
+          defaultEnabled: false,
+          marketplace: ZCODE_OFFICIAL_PLUGIN_MARKETPLACE,
+          rootPath,
+          source: "official" as const,
+        }),
+      ),
     );
-    for (const installed of listInstalledPluginRecords(request.storageRoot)) {
+    for (const name of [
+      "installed_plugins.json",
+      ".installed_plugins.json.backup",
+      ".installed_plugins.json.transaction.json",
+    ]) {
+      try {
+        await materials.observe(join(request.storageRoot, name));
+      } catch (error) {
+        rethrowPluginMaterialInterrupt(error);
+      }
+    }
+    for (const installed of await listInstalledPluginRecordsAsync(request.storageRoot)) {
       candidates.push({
         defaultEnabled: false,
         marketplace: installed.marketplace,
-        rootPath: resolveInstalledPluginRoot(request.storageRoot, installed),
+        rootPath: await resolveInstalledPluginRootAsync(request.storageRoot, installed),
         source: "cache",
       });
     }
@@ -281,17 +346,19 @@ export function createNodePluginAdapter(options: NodePluginAdapterOptions): Node
   return new NodePluginAdapter(options);
 }
 
-export function discoverNodePluginsSync(
+export async function discoverNodePlugins(
   request: PluginDiscoverRequest,
   options?: PluginAbortOptions,
-): PluginLoadOutcome {
-  return createNodePluginAdapter({ storageRoot: request.storageRoot }).discoverPluginsSync(
-    request,
-    options,
-  );
+): Promise<PluginLoadOutcome> {
+  const adapter = createNodePluginAdapter({ storageRoot: request.storageRoot });
+  try {
+    return await adapter.discoverPlugins(request, options);
+  } finally {
+    adapter.dispose();
+  }
 }
 
-function createPluginMetadata(
+async function createPluginMetadata(
   loaded: LoadedPlugin,
   component: PluginComponents,
   dataPath: string,
@@ -299,7 +366,7 @@ function createPluginMetadata(
   declaredMcpServerNames: string[],
   configuredOptions: Record<string, string | number | boolean>,
   uiSurfaces: PluginUiSurfaceDefinition[],
-): PluginMetadata {
+): Promise<PluginMetadata> {
   // manifest 的 author/homepage 作为详情页信息区的回退来源(商店 listing 优先)。
   const author = normalizeAuthorValue(loaded.manifest.author);
   const homepage =
@@ -316,8 +383,8 @@ function createPluginMetadata(
     // 且 UI join 对停用插件不产出名称(skillsService 里 `if (!enabled) continue`),导致:停用时
     // 整个技能分组消失、启用时只有数量没有名称。这里改为对插件根目录做权威枚举(与启用态无关),
     // 直接把名称+描述随 list 下发,UI 不再需要脆弱的 join。
-    components: enumeratePluginComponents(loaded.rootPath, loaded.manifest, { loaded }),
-    configuredOptions,
+    components: await enumeratePluginComponents(loaded.rootPath, loaded.manifest, { loaded }),
+    configuredOptions: { ...configuredOptions },
     dataPath,
     declaredMcpServerNames,
     description: loaded.manifest.description,
@@ -338,7 +405,7 @@ function createPluginMetadata(
   };
 }
 
-function resolveEnabledComponents(input: {
+async function resolveEnabledComponents(input: {
   dataPath: string;
   diagnostics: PluginDiagnostic[];
   env: Record<string, string | undefined>;
@@ -349,12 +416,12 @@ function resolveEnabledComponents(input: {
   options: Record<string, string | number | boolean>;
   priority: number;
   workingDirectory: string;
-}): PluginComponents {
-  mkdirSync(input.dataPath, { recursive: true });
+}): Promise<PluginComponents> {
+  await mkdir(input.dataPath, { recursive: true });
 
-  const skillRoots = resolveSkillRoots(input, input.priority);
+  const skillRoots = await resolveSkillRoots(input, input.priority);
   return {
-    commandRoots: resolveCommandRoots(input, input.priority + 1),
+    commandRoots: await resolveCommandRoots(input, input.priority + 1),
     hooks: input.hookEvents,
     hookDetails: input.hookDetails,
     mcpServers: resolvePluginMcpServers({
@@ -363,7 +430,7 @@ function resolveEnabledComponents(input: {
     }),
     // 插件页要展示真实技能数量。之前只统计 skills root 数,
     // document-skills 这种一个 root 下有多个 SKILL.md 的插件会被显示成 1。
-    skillCount: countSkillFiles(skillRoots),
+    skillCount: await countSkillFiles(skillRoots, input.loaded.materials),
     skillRoots,
   };
 }
@@ -389,89 +456,37 @@ function warnUnsupportedComponents(loaded: LoadedPlugin, diagnostics: PluginDiag
   }
 }
 
-function resolveSkillRoots(
+async function resolveSkillRoots(
   input: { diagnostics: PluginDiagnostic[]; loaded: LoadedPlugin },
   priority: number,
-): SkillRoot[] {
-  warnEmptyDeclaredSkillRoots(input);
-  return resolveComponentRoots("skills", input, priority);
+): Promise<SkillRoot[]> {
+  await warnEmptyDeclaredSkillRoots(input);
+  return await resolveComponentRoots("skills", input, priority);
 }
 
-/**
- * manifest 显式声明的 skills 路径没有可用技能时发出诊断,避免路径配置错误静默失败。
- * 声明集合独立于 roots 列表计算,默认 skills/ 目录为空时不误报;路径缺失、目录为空和
- * 符号链接越界分别保留可操作的诊断信息,权限错误交给实际扫描链路报告。
- */
-function warnEmptyDeclaredSkillRoots(input: {
-  diagnostics: PluginDiagnostic[];
-  loaded: LoadedPlugin;
-}): void {
-  const declared = parsePathList(input.loaded.manifest.skills);
-  if (declared.length === 0) return;
-  const seenPaths = new Set<string>();
-  for (const rawPath of declared) {
-    const resolved = resolveInside(input.loaded.rootPath, rawPath);
-    if (!resolved || seenPaths.has(resolved)) continue;
-    seenPaths.add(resolved);
-    // 路径缺失判定只认 ENOENT/ENOTDIR(statSync 精确分类),EACCES 等权限
-    // 错误不得误报成「不存在」——此时没有证据下结论,跳过告警,由 skill adapter
-    // 扫描同一目录时发 skill_scan_failed。
-    // message 按原因区分:「路径不存在」是 manifest 配错,「存在但没有技能」
-    // 是内容问题,「symlink 逃逸出插件根」是安全拒绝,三者修复方式不同;
-    // code 保持单一,UI 无需感知分类。
-    if (isMissingPath(resolved)) {
-      input.diagnostics.push({
-        code: "plugin_skill_root_empty",
-        message: `Plugin skills path does not exist: ${rawPath}`,
-        path: resolved,
-        pluginId: input.loaded.id,
-        severity: "warning",
-      });
-      continue;
-    }
-    // 信任边界:声明路径是插件内容,扫描不跟随符号链接(目录级/文件级逃逸
-    // 一并拒绝,含 Windows junction)。链接根/链接 SKILL.md 扫描为空后落入下方
-    // 「没有任何技能」告警,不误报「不存在」(词法路径本身存在)。
-    let skillFiles: string[];
-    try {
-      skillFiles = scanSkillFilesUnderRootSync(resolved, { followSymbolicLinks: false });
-    } catch {
-      continue;
-    }
-    if (skillFiles.length > 0) continue;
-    input.diagnostics.push({
-      code: "plugin_skill_root_empty",
-      message: `Plugin skills path does not contain any skills: ${rawPath}`,
-      path: resolved,
-      pluginId: input.loaded.id,
-      severity: "warning",
-    });
-  }
-}
-
-function resolveCommandRoots(
+async function resolveCommandRoots(
   input: { dataPath: string; diagnostics: PluginDiagnostic[]; loaded: LoadedPlugin },
   priority: number,
-): CustomCommandRoot[] {
-  const roots = resolveComponentRoots<CustomCommandRoot>(
+): Promise<CustomCommandRoot[]> {
+  const roots = await resolveComponentRoots<CustomCommandRoot>(
     "commands",
     input,
     priority,
     createHookPluginContext(input.loaded, input.dataPath),
   );
-  const generatedRoot = materializeCommandMetadataRoot(input, priority + 1);
+  const generatedRoot = await materializeCommandMetadataRoot(input, priority + 1);
   if (generatedRoot) roots.push(generatedRoot);
   return roots;
 }
 
-function inspectPluginHooks(input: {
+async function inspectPluginHooks(input: {
   dataPath: string;
   diagnostics: PluginDiagnostic[];
   loaded: LoadedPlugin;
   runnable: boolean;
-}): PluginHookInspection {
+}): Promise<PluginHookInspection> {
   const inspection = emptyHookInspection();
-  for (const source of listPluginHookSources({
+  for (const source of await listPluginHookSources({
     diagnostics: input.diagnostics,
     loaded: input.loaded,
   })) {
@@ -605,20 +620,6 @@ function toPluginHookDetail(input: {
   return detail;
 }
 
-function createHookPluginContext(
-  loaded: LoadedPlugin,
-  dataPath: string,
-  sourcePath?: string,
-): HookPluginContext {
-  return {
-    dataPath,
-    id: loaded.id,
-    name: loaded.manifest.name,
-    rootPath: loaded.rootPath,
-    ...(sourcePath ? { sourcePath } : {}),
-  };
-}
-
 function attachPluginToHook(hook: HookConfig, plugin: HookPluginContext): HookConfig {
   return {
     ...hook,
@@ -651,38 +652,20 @@ function emptyHookInspection(): PluginHookInspection {
   };
 }
 
-function countSkillFiles(skillRoots: SkillRoot[]): number {
-  // 技能识别规则收敛到共享 scan helper(根自身含
-  // SKILL.md 时根自身是一个技能);同时声明根与
-  // 默认 skills/ 根会命中同一个 SKILL.md,必须按文件路径去重,否则计数翻倍。
-  // 顺带修正漂移:只认 isDirectory() 会漏掉 symlink 技能子目录,统一 helper 后一并计入。
-  // helper 只吞 ENOENT;权限错误(EACCES 等)会抛出,这里按原语义把该根计 0,
-  // 真正的 skill_scan_failed 诊断由 skill adapter 在运行时扫描同一目录时发出。
-  // 信任边界:这里只消费 plugin roots(resolveSkillRoots 产物),不跟随符号链接。
-  const seenFiles = new Set<string>();
-  for (const skillRoot of skillRoots) {
-    try {
-      for (const file of scanSkillFilesUnderRootSync(skillRoot.path, {
-        followSymbolicLinks: skillRoot.source !== "plugin",
-      })) {
-        seenFiles.add(file);
-      }
-    } catch {
-      // 概览计数降级为 0;扫描诊断由 skill adapter 负责。
-    }
-  }
-  return seenFiles.size;
-}
-
-function resolveComponentRoots<T extends CustomCommandRoot | SkillRoot>(
+async function resolveComponentRoots<T extends CustomCommandRoot | SkillRoot>(
   key: "commands" | "skills",
   input: { diagnostics: PluginDiagnostic[]; loaded: LoadedPlugin },
   priority: number,
   plugin?: HookPluginContext,
-): T[] {
+): Promise<T[]> {
   const paths = parsePathList(input.loaded.manifest[key]);
   const defaultPath = join(input.loaded.rootPath, key);
-  if (directoryExists(defaultPath)) {
+  // skills 的显式声明是完整入口清单,不能再补扫未声明的默认目录。
+  if (
+    (key !== "skills" || input.loaded.manifest.skills === undefined) &&
+    (await (input.loaded.materials?.directoryExists(defaultPath) ??
+      directoryExistsAsync(defaultPath)))
+  ) {
     paths.unshift(key);
   }
   const roots: T[] = [];
@@ -713,177 +696,48 @@ function resolveComponentRoots<T extends CustomCommandRoot | SkillRoot>(
   return roots;
 }
 
-function materializeCommandMetadataRoot(
-  input: { dataPath: string; diagnostics: PluginDiagnostic[]; loaded: LoadedPlugin },
-  priority: number,
-): CustomCommandRoot | null {
-  const spec = input.loaded.manifest.commands;
-  if (!isRecord(spec)) return null;
-
-  const generatedRoot = join(input.dataPath, "generated-commands");
-  let wroteCommand = false;
-  mkdirSync(generatedRoot, { recursive: true });
-
-  for (const [rawName, rawMetadata] of Object.entries(spec)) {
-    if (!isRecord(rawMetadata)) {
-      input.diagnostics.push({
-        code: "plugin_manifest_invalid",
-        message: `Plugin command metadata must be an object: ${rawName}`,
-        path: input.loaded.manifestPath,
-        pluginId: input.loaded.id,
-        severity: "error",
-      });
-      continue;
-    }
-
-    const name = normalizeGeneratedCommandName(rawName);
-    if (!name) {
-      input.diagnostics.push({
-        code: "plugin_manifest_invalid",
-        message: `Invalid plugin command name: ${rawName}`,
-        path: input.loaded.manifestPath,
-        pluginId: input.loaded.id,
-        severity: "error",
-      });
-      continue;
-    }
-
-    const source = typeof rawMetadata.source === "string" ? rawMetadata.source : undefined;
-    const content = typeof rawMetadata.content === "string" ? rawMetadata.content : undefined;
-    if ((source && content) || (!source && !content)) {
-      input.diagnostics.push({
-        code: "plugin_manifest_invalid",
-        message: `Plugin command '${rawName}' must provide exactly one of source or content`,
-        path: input.loaded.manifestPath,
-        pluginId: input.loaded.id,
-        severity: "error",
-      });
-      continue;
-    }
-
-    let markdown = content;
-    if (source) {
-      const sourcePath = resolveInside(input.loaded.rootPath, trimRelativePrefix(source));
-      if (!sourcePath) {
-        input.diagnostics.push({
-          code: "plugin_component_path_invalid",
-          message: `Plugin command source escapes plugin root: ${source}`,
-          path: input.loaded.manifestPath,
-          pluginId: input.loaded.id,
-          severity: "error",
-        });
-        continue;
-      }
-      if (!fileExists(sourcePath)) {
-        input.diagnostics.push({
-          code: "plugin_component_path_invalid",
-          message: `Plugin command source file not found: ${source}`,
-          path: sourcePath,
-          pluginId: input.loaded.id,
-          severity: "error",
-        });
-        continue;
-      }
-      markdown = readFileSync(sourcePath, "utf8");
-    }
-    if (markdown === undefined) continue;
-
-    // 市场清单支持 commands object mapping 和 inline content。
-    // ZCode 的 custom command loader 只扫描 markdown 根目录,因此把低风险命令内容
-    // materialize 到插件 data 目录;生成路径不在 plugin root 外暴露,也不执行命令本身。
-    writeFileSync(
-      join(generatedRoot, `${name}.md`),
-      applyCommandMetadataFrontmatter(markdown, rawMetadata),
-      "utf8",
-    );
-    wroteCommand = true;
-  }
-
-  return wroteCommand
-    ? {
-        path: generatedRoot,
-        plugin: createHookPluginContext(input.loaded, input.dataPath),
-        priority,
-        scope: input.loaded.source === "official" ? "system" : "user",
-        source: "plugin",
-      }
-    : null;
-}
-
-function normalizeGeneratedCommandName(name: string): string | null {
-  const normalized = name.trim().replace(/^\/+/, "").toLowerCase();
-  if (!/^[a-z0-9][a-z0-9_:-]{0,63}$/.test(normalized)) return null;
-  return normalized;
-}
-
-function trimRelativePrefix(path: string): string {
-  return path.replace(/^\.\//, "");
-}
-
-function applyCommandMetadataFrontmatter(
-  markdown: string,
-  metadata: Record<string, unknown>,
-): string {
-  const frontmatter = new Map<string, string>();
-  if (typeof metadata.description === "string" && metadata.description.trim()) {
-    frontmatter.set("description", metadata.description.trim());
-  }
-  if (typeof metadata.argumentHint === "string" && metadata.argumentHint.trim()) {
-    frontmatter.set("argument-hint", metadata.argumentHint.trim());
-  }
-  if (typeof metadata.model === "string" && metadata.model.trim()) {
-    frontmatter.set("model", metadata.model.trim());
-  }
-  if (Array.isArray(metadata.allowedTools)) {
-    const allowedTools = metadata.allowedTools
-      .filter((tool): tool is string => typeof tool === "string" && tool.trim().length > 0)
-      .map((tool) => tool.trim());
-    if (allowedTools.length > 0) frontmatter.set("allowed-tools", allowedTools.join(", "));
-  }
-  if (frontmatter.size === 0) return markdown;
-  const body = stripMarkdownFrontmatter(markdown).trimStart();
-  return `---\n${Array.from(frontmatter, ([key, value]) => `${key}: ${value}`).join("\n")}\n---\n\n${body}`;
-}
-
-function stripMarkdownFrontmatter(markdown: string): string {
-  const normalized = markdown.replace(/^\uFEFF/, "");
-  if (!normalized.startsWith("---")) return markdown;
-  const lines = normalized.split(/\r?\n/);
-  if (lines[0]?.trim() !== "---") return markdown;
-  const endIndex = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
-  return endIndex > 0 ? lines.slice(endIndex + 1).join("\n") : markdown;
-}
-
-function scanOfficialCache(
+async function scanOfficialCache(
   storageRoot: string,
   diagnostics: PluginDiagnostic[],
+  materials: PluginMaterialReader,
   options?: PluginAbortOptions,
-): string[] {
+): Promise<string[]> {
   // 官方插件升级会保留旧版本缓存目录;若遍历全部目录再按插件 id
   // “先到先得”,旧版本会抢在 bundled marketplace 指向的当前版本前被加载。
   // bundled 分片是当前随应用发布资产的权威清单;存在时只加载其 cachePath。
   // 不能简单选择最高 semver,否则官方回滚版本时仍会错误加载旧缓存。
-  const bundledRoots = loadBundledOfficialPluginRootsSync(storageRoot);
+  try {
+    await materials.observe(
+      join(
+        storageRoot,
+        "marketplaces",
+        ZCODE_OFFICIAL_PLUGIN_MARKETPLACE,
+        "bundled-marketplace.json",
+      ),
+    );
+  } catch (error) {
+    rethrowPluginMaterialInterrupt(error);
+  }
+  const bundledRoots = await loadBundledOfficialPluginRoots(storageRoot);
   if (bundledRoots !== undefined) {
-    for (const rootPath of bundledRoots) {
-      throwIfAborted(options);
-    }
+    throwIfAborted(options);
     return bundledRoots;
   }
 
   const cacheRoot = join(storageRoot, "cache", ZCODE_OFFICIAL_PLUGIN_MARKETPLACE);
   try {
     const roots: string[] = [];
-    for (const pluginEntry of readdirSync(cacheRoot, { withFileTypes: true })) {
+    for (const pluginEntry of await materials.directory(cacheRoot)) {
       throwIfAborted(options);
       if (!pluginEntry.isDirectory()) continue;
       const pluginDir = join(cacheRoot, pluginEntry.name);
-      for (const versionEntry of readdirSync(pluginDir, { withFileTypes: true })) {
+      for (const versionEntry of await materials.directory(pluginDir)) {
         if (versionEntry.isDirectory()) roots.push(join(pluginDir, versionEntry.name));
       }
     }
     return roots;
   } catch (error) {
+    rethrowPluginMaterialInterrupt(error);
     if (isNotFoundError(error)) return [];
     diagnostics.push({
       code: "plugin_root_not_found",
@@ -895,11 +749,12 @@ function scanOfficialCache(
   }
 }
 
-function loadPlugin(
+async function loadPlugin(
   candidate: PluginCandidate,
   diagnostics: PluginDiagnostic[],
-): LoadedPlugin | null {
-  if (!directoryExists(candidate.rootPath)) {
+  materials: PluginMaterialReader,
+): Promise<LoadedPlugin | null> {
+  if (!(await materials.directoryExists(candidate.rootPath))) {
     diagnostics.push({
       code: "plugin_root_not_found",
       message: `Plugin root does not exist: ${candidate.rootPath}`,
@@ -909,7 +764,13 @@ function loadPlugin(
     return null;
   }
 
-  const manifestPath = findManifest(candidate.rootPath);
+  try {
+    await materials.directory(candidate.rootPath);
+  } catch (error) {
+    // 列目录只是减少缺失入口探测;无枚举权限时仍允许按已知路径读取 manifest。
+    rethrowPluginMaterialInterrupt(error);
+  }
+  const manifestPath = await findManifest(candidate.rootPath, materials);
   if (!manifestPath) {
     diagnostics.push({
       code: "plugin_manifest_not_found",
@@ -920,47 +781,63 @@ function loadPlugin(
     return null;
   }
 
-  const manifest = readManifest(manifestPath, diagnostics);
+  const manifest = await readManifest(manifestPath, diagnostics, materials, candidate.marketplace);
   if (!manifest) return null;
   return {
     id: `${manifest.name}@${candidate.marketplace}`,
     manifest,
     manifestPath,
+    materials,
     marketplace: candidate.marketplace,
     rootPath: candidate.rootPath,
     source: candidate.source,
   };
 }
 
-function findManifest(rootPath: string): string | null {
+async function findManifest(
+  rootPath: string,
+  materials: PluginMaterialReader,
+): Promise<string | null> {
   const zcodePath = join(rootPath, ZCODE_MANIFEST_PATH);
-  if (fileExists(zcodePath)) {
+  if (await materials.fileExists(zcodePath)) {
     return zcodePath;
   }
 
   // 兼容不同 manifest 目录约定,发现阶段按稳定优先级回退。
   const claudePath = join(rootPath, CLAUDE_MANIFEST_PATH);
-  if (fileExists(claudePath)) {
+  if (await materials.fileExists(claudePath)) {
     return claudePath;
   }
   const codexPath = join(rootPath, CODEX_MANIFEST_PATH);
-  return fileExists(codexPath) ? codexPath : null;
+  return (await materials.fileExists(codexPath)) ? codexPath : null;
 }
 
-function readManifest(path: string, diagnostics: PluginDiagnostic[]): PluginManifest | null {
+async function readManifest(
+  path: string,
+  diagnostics: PluginDiagnostic[],
+  materials: PluginMaterialReader,
+  marketplace: string,
+): Promise<PluginManifest | null> {
+  let pluginId: string | undefined;
   try {
-    const parsed = JSON.parse(readFileSync(path, "utf8")) as unknown;
+    const parsed = await materials.json(path);
     if (!isRecord(parsed)) throw new Error("Manifest must be a JSON object");
     const name = typeof parsed.name === "string" ? parsed.name.trim() : "";
     if (!PLUGIN_NAME_PATTERN.test(name)) throw new Error(`Invalid plugin name: ${name}`);
+    pluginId = `${name}@${marketplace}`;
     return {
       ...parsed,
       name,
       version: typeof parsed.version === "string" ? parsed.version : DEFAULT_VERSION,
+      ...(parsed.userConfig !== undefined
+        ? { userConfig: pluginUserConfigSchema.parse(parsed.userConfig) }
+        : {}),
     } as PluginManifest;
   } catch (error) {
+    rethrowPluginMaterialInterrupt(error);
     diagnostics.push({
       code: "plugin_manifest_invalid",
+      ...(pluginId ? { pluginId } : {}),
       message: error instanceof Error ? error.message : `Invalid plugin manifest: ${path}`,
       path,
       severity: "error",

+ 65 - 9
apps/zcode-cli/packages/adapters/src/plugins/markdown-frontmatter.ts

@@ -1,4 +1,24 @@
-import { readFileSync } from "node:fs";
+import {
+  type PluginMaterialReader,
+  rethrowPluginMaterialInterrupt,
+  PLUGIN_MATERIAL_READ_CONCURRENCY,
+} from "./helpers.js";
+import { readFile } from "node:fs/promises";
+
+/** 分批读取避免一次启动所有文件 IO;数组顺序保留同名组件的既有优先级。 */
+export async function readMarkdownFrontmatters(paths: string[], materials?: PluginMaterialReader) {
+  const results = [];
+  for (let offset = 0; offset < paths.length; offset += PLUGIN_MATERIAL_READ_CONCURRENCY) {
+    results.push(
+      ...(await Promise.all(
+        paths
+          .slice(offset, offset + PLUGIN_MATERIAL_READ_CONCURRENCY)
+          .map((path) => readMarkdownFrontmatter(path, materials)),
+      )),
+    );
+  }
+  return results;
+}
 
 /**
  * 轻量 Markdown frontmatter 抽取,支持 YAML 块标量(`>` 折叠 / `|` 字面,及 `+`/`-` chomping 变体)。
@@ -10,14 +30,19 @@ import { readFileSync } from "node:fs";
  *
  * 仅提取 name / description 两个标量键(与 skills/commands 详情展示所需一致),不做完整 YAML 解析。
  */
-export function readMarkdownFrontmatter(filePath: string): {
+export async function readMarkdownFrontmatter(
+  filePath: string,
+  materials?: PluginMaterialReader,
+): Promise<{
   name?: string;
   description?: string;
-} {
+}> {
   let content: string;
   try {
-    content = readFileSync(filePath, "utf8");
-  } catch {
+    if (materials) return await materials.parsed(filePath, "frontmatter", parseMarkdownFrontmatter);
+    content = await readFile(filePath, "utf8");
+  } catch (error) {
+    rethrowPluginMaterialInterrupt(error);
     return {};
   }
   return parseMarkdownFrontmatter(content);
@@ -104,10 +129,7 @@ function readBlockScalar(
     line.trim().length === 0 ? "" : line.slice(indent ?? 0),
   );
   return {
-    value:
-      style === "folded"
-        ? foldBlockScalarLines(contentLines)
-        : contentLines.join("\n").trim(),
+    value: style === "folded" ? foldBlockScalarLines(contentLines) : contentLines.join("\n").trim(),
     nextIndex: index,
   };
 }
@@ -148,3 +170,37 @@ function parseScalar(value: string | undefined): string | undefined {
   }
   return trimmed;
 }
+
+export function applyCommandMetadataFrontmatter(
+  markdown: string,
+  metadata: Record<string, unknown>,
+): string {
+  const frontmatter = new Map<string, string>();
+  if (typeof metadata.description === "string" && metadata.description.trim()) {
+    frontmatter.set("description", metadata.description.trim());
+  }
+  if (typeof metadata.argumentHint === "string" && metadata.argumentHint.trim()) {
+    frontmatter.set("argument-hint", metadata.argumentHint.trim());
+  }
+  if (typeof metadata.model === "string" && metadata.model.trim()) {
+    frontmatter.set("model", metadata.model.trim());
+  }
+  if (Array.isArray(metadata.allowedTools)) {
+    const allowedTools = metadata.allowedTools
+      .filter((tool): tool is string => typeof tool === "string" && tool.trim().length > 0)
+      .map((tool) => tool.trim());
+    if (allowedTools.length > 0) frontmatter.set("allowed-tools", allowedTools.join(", "));
+  }
+  if (frontmatter.size === 0) return markdown;
+  const body = stripMarkdownFrontmatter(markdown).trimStart();
+  return `---\n${Array.from(frontmatter, ([key, value]) => `${key}: ${value}`).join("\n")}\n---\n\n${body}`;
+}
+
+function stripMarkdownFrontmatter(markdown: string): string {
+  const normalized = markdown.replace(/^\uFEFF/, "");
+  if (!normalized.startsWith("---")) return markdown;
+  const lines = normalized.split(/\r?\n/);
+  if (lines[0]?.trim() !== "---") return markdown;
+  const endIndex = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
+  return endIndex > 0 ? lines.slice(endIndex + 1).join("\n") : markdown;
+}

+ 88 - 55
apps/zcode-cli/packages/adapters/src/plugins/marketplace.ts

@@ -1,4 +1,4 @@
-import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, statSync } from "node:fs";
 import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
 import { tmpdir } from "node:os";
 import { basename, dirname, join, resolve } from "node:path";
@@ -20,7 +20,7 @@ import {
 import { enumeratePluginComponents, type PluginComponentGroup } from "./plugin-components.js";
 import { applyNetworkEgressEnv } from "../network/subprocess-env.js";
 import { createNodeWebFetchHttpClientAdapter } from "../http/index.js";
-import { writeCdnOfficialMarketplacePartitionSync } from "./official-marketplace.js";
+import { writeCdnOfficialMarketplacePartition } from "./official-marketplace.js";
 import {
   isZipPluginUrlSource,
   readZipPluginSourceSha256,
@@ -29,6 +29,8 @@ import {
 import {
   activateDirectoryAtomically,
   recoverAtomicTargetSync,
+  readStandaloneAtomicFile,
+  resolveAtomicReadPath,
   writeFileAtomically,
   type AtomicDirectoryActivation,
 } from "./atomic-directory.js";
@@ -68,12 +70,7 @@ const CLAUDE_MARKETPLACE_REFRESH_TIMEOUT_MS = 30_000;
 const MARKETPLACE_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]{0,127}$/;
 const PLUGIN_NAME_PATTERN = /^[a-z0-9][a-z0-9._-]{0,127}$/;
 const SOURCE_SHA256_PATTERN = /^[a-f0-9]{64}$/u;
-const UNSUPPORTED_MANIFEST_FIELDS = [
-  "channels",
-  "lspServers",
-  "outputStyles",
-  "settings",
-] as const;
+const UNSUPPORTED_MANIFEST_FIELDS = ["channels", "lspServers", "outputStyles", "settings"] as const;
 
 export type MarketplaceSource =
   | { source: "url"; headers?: Record<string, string>; url: string }
@@ -346,7 +343,9 @@ export function loadKnownMarketplacesSync(storageRoot: string): KnownMarketplace
   return [];
 }
 
-export function ensureDefaultPluginMarketplaces(storageRoot: string): KnownMarketplaceRecord[] {
+export async function ensureDefaultPluginMarketplaces(
+  storageRoot: string,
+): Promise<KnownMarketplaceRecord[]> {
   const known = loadKnownMarketplacesSync(storageRoot);
   const existingIds = new Set(known.map((record) => record.id));
   const now = new Date().toISOString();
@@ -365,7 +364,8 @@ export function ensureDefaultPluginMarketplaces(storageRoot: string): KnownMarke
   );
   if (missing.length === 0) return known;
   const next = [...known, ...missing];
-  writeKnownMarketplacesSync(storageRoot, next);
+  // 热查询不持锁,首次登记也必须发布完整一代,不能让读者看见半份 JSON。
+  await writeKnownMarketplaces(storageRoot, next);
   return next;
 }
 
@@ -375,7 +375,7 @@ export async function ensureMarketplaceManifestAvailable(input: {
   storageRoot: string;
 }): Promise<KnownMarketplaceRecord | null> {
   throwIfPluginOperationAborted(input.signal);
-  ensureDefaultPluginMarketplaces(input.storageRoot);
+  await ensureDefaultPluginMarketplaces(input.storageRoot);
   if (loadMarketplaceManifestSync(input.storageRoot, input.marketplace)) {
     return (
       loadKnownMarketplacesSync(input.storageRoot).find(
@@ -456,7 +456,7 @@ export async function addMarketplace(input: {
     const persistedManifest =
       loaded.manifest.name === ZCODE_OFFICIAL_PLUGIN_MARKETPLACE
         ? parseRequiredMarketplaceManifest(
-            writeCdnOfficialMarketplacePartitionSync({
+            await writeCdnOfficialMarketplacePartition({
               manifest: loaded.manifest.raw,
               storageRoot: input.storageRoot,
             }),
@@ -701,7 +701,7 @@ export async function updateMarketplace(input: {
   signal?: AbortSignal;
   storageRoot: string;
 }): Promise<KnownMarketplaceRecord[]> {
-  ensureDefaultPluginMarketplaces(input.storageRoot);
+  await ensureDefaultPluginMarketplaces(input.storageRoot);
   const known = loadKnownMarketplacesSync(input.storageRoot);
   const selected = input.marketplace
     ? known.filter((record) => record.id === input.marketplace)
@@ -787,6 +787,16 @@ export function resolveInstalledPluginRoot(
   return recoverAtomicTargetSync(root);
 }
 
+export async function resolveInstalledPluginRootAsync(
+  storageRoot: string,
+  record: InstalledPluginRecord,
+): Promise<string> {
+  const root =
+    record.installPath ||
+    getPluginCacheDir(storageRoot, record.marketplace, record.name, record.version);
+  return resolveAtomicReadPath(root);
+}
+
 export async function installMarketplacePlugin(input: {
   marketplace: string;
   name: string;
@@ -923,12 +933,12 @@ export async function validateMarketplacePlugin(input: {
       storageRoot: input.storageRoot,
     });
     diagnostics.push(
-      ...validatePluginRoot({
+      ...(await validatePluginRoot({
         entry: plugin,
         marketplace: input.marketplace,
         rootPath: resolved.path,
         storageRoot: input.storageRoot,
-      }),
+      })),
     );
   } catch (error) {
     diagnostics.push(toValidationDiagnostic(error, `${input.name}@${input.marketplace}`));
@@ -963,7 +973,7 @@ export async function describeMarketplacePlugin(input: {
   if (installedRecord) {
     const rootPath = resolveInstalledPluginRoot(input.storageRoot, installedRecord);
     if (directoryExists(rootPath)) {
-      const read = readComponentsAtRoot({
+      const read = await readComponentsAtRoot({
         diagnostics,
         marketplace: input.marketplace,
         rootPath,
@@ -1023,7 +1033,7 @@ export async function describeMarketplacePlugin(input: {
       marketplace: input.marketplace,
       storageRoot: input.storageRoot,
     });
-    const read = readComponentsAtRoot({
+    const read = await readComponentsAtRoot({
       diagnostics,
       entry,
       marketplace: input.marketplace,
@@ -1043,12 +1053,12 @@ export async function describeMarketplacePlugin(input: {
 }
 
 /** 读插件根目录的 manifest(失败按 null 降级),再交给纯枚举器列出组件名称+描述。 */
-function readComponentsAtRoot(input: {
+async function readComponentsAtRoot(input: {
   diagnostics: PluginValidationDiagnostic[];
   entry?: PluginMarketplaceEntry;
   marketplace: string;
   rootPath: string;
-}): { components: PluginComponentGroup[]; metadata?: PluginManifestDisplayMetadata } {
+}): Promise<{ components: PluginComponentGroup[]; metadata?: PluginManifestDisplayMetadata }> {
   let loadedManifest: { manifest: PluginManifest; manifestPath?: string } | null = null;
   try {
     loadedManifest = readPluginManifestFromRoot(
@@ -1069,10 +1079,14 @@ function readComponentsAtRoot(input: {
         source: "cache" as const,
       }
     : undefined;
-  const components = enumeratePluginComponents(input.rootPath, loadedManifest?.manifest ?? null, {
-    diagnostics: input.diagnostics as PluginDiagnostic[],
-    ...(loaded ? { loaded } : {}),
-  });
+  const components = await enumeratePluginComponents(
+    input.rootPath,
+    loadedManifest?.manifest ?? null,
+    {
+      diagnostics: input.diagnostics as PluginDiagnostic[],
+      ...(loaded ? { loaded } : {}),
+    },
+  );
   const metadata = loadedManifest ? toManifestDisplayMetadata(loadedManifest.manifest) : undefined;
   return { components, ...(metadata ? { metadata } : {}) };
 }
@@ -1173,12 +1187,12 @@ export async function validateMarketplaceSource(input: {
           storageRoot: input.storageRoot,
         });
         diagnostics.push(
-          ...validatePluginRoot({
+          ...(await validatePluginRoot({
             entry,
             marketplace: loaded.manifest.name,
             rootPath: resolved.path,
             storageRoot: input.storageRoot,
-          }),
+          })),
         );
       } catch (error) {
         diagnostics.push(toValidationDiagnostic(error, `${entry.name}@${loaded.manifest.name}`));
@@ -1221,9 +1235,11 @@ export async function validateLocalPluginPath(input: {
       },
     ];
   }
-  const rootPath = statSync(resolved).isDirectory() ? resolved : resolveManifestRootFromFile(resolved);
+  const rootPath = statSync(resolved).isDirectory()
+    ? resolved
+    : resolveManifestRootFromFile(resolved);
   if (findMarketplaceManifestPath(rootPath)) {
-    return validateMarketplaceSource({
+    return await validateMarketplaceSource({
       signal: input.signal,
       source: { source: "directory", path: rootPath },
       storageRoot: input.storageRoot,
@@ -1256,7 +1272,7 @@ export async function validateLocalPluginPath(input: {
   }
   // 本地目录没有 marketplace 条目:用 manifest 自己的 name 合成一个 strict 条目,
   // 让 validatePluginRoot 走与已安装插件完全相同的 manifest/MCP 校验。
-  return validatePluginRoot({
+  return await validatePluginRoot({
     entry: { name: name || basename(rootPath), raw: {} },
     marketplace: "inline",
     rootPath,
@@ -1709,6 +1725,8 @@ function createManifestFromMarketplaceEntry(
   delete raw.examplePrompts;
   delete raw.examplePrompts_i18n;
   delete raw.requiresPaidPlan;
+  // 扩展摘要也是目录层的信息(docs/plugins/plugin-publishing.md §4.2),不是清单的 extension 键。
+  delete raw.extensionSummary;
   return {
     ...raw,
     name: entry.name,
@@ -2090,26 +2108,6 @@ async function writeKnownMarketplaces(
   });
 }
 
-function writeKnownMarketplacesSync(
-  storageRoot: string,
-  marketplaces: KnownMarketplaceRecord[],
-): void {
-  const path = join(storageRoot, KNOWN_MARKETPLACES_FILE);
-  mkdirSync(dirname(path), { recursive: true });
-  writeFileSync(
-    path,
-    `${JSON.stringify(
-      {
-        version: 1,
-        marketplaces,
-      },
-      null,
-      2,
-    )}\n`,
-    "utf8",
-  );
-}
-
 function defaultMarketplaceSourceFromString(source: string): MarketplaceSource {
   const trimmed = source.trim();
   if (/^[^/]+\/[^/]+(?:[#@].+)?$/u.test(trimmed) && !trimmed.includes(":")) {
@@ -2331,6 +2329,29 @@ export function parseEntryStoreListing(
   return Object.keys(listing).length > 0 ? listing : undefined;
 }
 
+/** 目录条目的扩展摘要(docs/plugins/plugin-publishing.md §4.2)。CLI 只透传,不判断兼容。 */
+export interface PluginExtensionSummary {
+  engines: { zcode: string };
+  grants: string[];
+}
+
+/**
+ * 从目录条目读扩展摘要:只认 engines.zcode 是非空字符串的条目,grants 只留字符串,其余键丢掉。
+ * 协议字段是 strict 的,丢掉未知键才不会让 App 解析失败。范围格式不检查,由 App 判断。
+ */
+export function parseEntryExtensionSummary(
+  entry: Record<string, unknown>,
+): PluginExtensionSummary | undefined {
+  const summary = entry.extensionSummary;
+  if (!isRecord(summary) || !isRecord(summary.engines)) return undefined;
+  const range = summary.engines.zcode;
+  if (typeof range !== "string" || range.trim().length === 0) return undefined;
+  const grants = Array.isArray(summary.grants)
+    ? summary.grants.filter((grant): grant is string => typeof grant === "string")
+    : [];
+  return { engines: { zcode: range }, grants };
+}
+
 /** author 字段兼容 string 与 {name,url}(plugin.json 与目录条目共用此规则)。 */
 export function normalizeAuthorValue(value: unknown): { name?: string; url?: string } | undefined {
   if (typeof value === "string") {
@@ -2427,12 +2448,12 @@ function readPluginManifestFromRoot(
   return null;
 }
 
-function validatePluginRoot(input: {
+async function validatePluginRoot(input: {
   entry: PluginMarketplaceEntry;
   marketplace: string;
   rootPath: string;
   storageRoot: string;
-}): PluginValidationDiagnostic[] {
+}): Promise<PluginValidationDiagnostic[]> {
   const diagnostics: PluginValidationDiagnostic[] = [];
   const pluginId = `${input.entry.name}@${input.marketplace}`;
   let loadedManifest: { manifest: PluginManifest; manifestPath?: string } | null = null;
@@ -2477,7 +2498,7 @@ function validatePluginRoot(input: {
     pluginId,
     source: "cache",
   });
-  pushMcpValidationDiagnostics({
+  await pushMcpValidationDiagnostics({
     diagnostics,
     manifest: loadedManifest.manifest,
     manifestPath,
@@ -2529,7 +2550,7 @@ function pushManifestCompatibilityDiagnostics(input: {
   }
 }
 
-function pushMcpValidationDiagnostics(input: {
+async function pushMcpValidationDiagnostics(input: {
   diagnostics: PluginValidationDiagnostic[];
   manifest: PluginManifest;
   manifestPath: string;
@@ -2537,7 +2558,7 @@ function pushMcpValidationDiagnostics(input: {
   pluginId: string;
   rootPath: string;
   storageRoot: string;
-}): void {
+}): Promise<void> {
   const diagnostics = input.diagnostics as PluginDiagnostic[];
   const loaded = {
     id: input.pluginId,
@@ -2547,7 +2568,7 @@ function pushMcpValidationDiagnostics(input: {
     rootPath: input.rootPath,
     source: "cache" as const,
   };
-  const definitions = loadPluginMcpServerDefinitions({ diagnostics, loaded });
+  const definitions = await loadPluginMcpServerDefinitions({ diagnostics, loaded });
   resolvePluginMcpServers({
     dataPath: join(input.storageRoot, "data", sanitizePluginId(input.pluginId)),
     definitions,
@@ -2864,7 +2885,7 @@ function getPluginCacheDir(
 }
 
 export function getPluginDataDir(storageRoot: string, pluginId: string): string {
-  // 与 NodePluginAdapter.discoverPluginsSync 的 dataPath 解析保持一致:<storageRoot>/data/<sanitized-id>。
+  // 与 NodePluginAdapter.discoverPlugins 的 dataPath 解析保持一致:<storageRoot>/data/<sanitized-id>。
   return join(storageRoot, "data", sanitizePluginId(pluginId));
 }
 
@@ -2944,3 +2965,15 @@ function tryParseUrl(input: string): URL | null {
     return null;
   }
 }
+
+export async function listInstalledPluginRecordsAsync(
+  storageRoot: string,
+): Promise<InstalledPluginRecord[]> {
+  let parsed: unknown;
+  try {
+    parsed = JSON.parse(await readStandaloneAtomicFile(join(storageRoot, INSTALLED_PLUGINS_FILE)));
+  } catch {
+    parsed = undefined;
+  }
+  return normalizeInstalledPluginsState(parsed).plugins;
+}

+ 29 - 15
apps/zcode-cli/packages/adapters/src/plugins/mcp.ts

@@ -1,4 +1,4 @@
-import { readFileSync } from "node:fs";
+import { readFile } from "node:fs/promises";
 import { join } from "node:path";
 import { findOfficialMcpReservedHeaders } from "@zcode/shared";
 import type {
@@ -12,32 +12,38 @@ import type {
 import { ZCODE_OFFICIAL_PLUGIN_MARKETPLACE } from "@zcode/contracts";
 import { ZCODE_PLUGIN_ID_ENV_KEY } from "@zcode/shared";
 import type { LoadedPlugin } from "./types.js";
-import { isNotFoundError, isPluginOptionValue, isRecord, resolveInside } from "./helpers.js";
+import {
+  isNotFoundError,
+  isPluginOptionValue,
+  isRecord,
+  resolveInside,
+  rethrowPluginMaterialInterrupt,
+} from "./helpers.js";
 import { buildOfficialProvenance, parseZCodeOfficialAuth } from "./mcp-official-auth.js";
 
 const SUPPORTED_MCP_TYPES = new Set(["stdio", "http", "sse"]);
 const TEMPLATE_PATTERN = /\$\{([^}]+)\}/g;
 const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
 
-export function loadPluginMcpServerDefinitions(input: {
+export async function loadPluginMcpServerDefinitions(input: {
   diagnostics: PluginDiagnostic[];
   loaded: LoadedPlugin;
-}): Record<string, unknown> {
-  const fromFile = loadMcpServersFromFile(join(input.loaded.rootPath, ".mcp.json"), input);
-  const fromManifest = loadMcpServersFromSpec(input.loaded.manifest.mcpServers, input);
+}): Promise<Record<string, unknown>> {
+  const fromFile = await loadMcpServersFromFile(join(input.loaded.rootPath, ".mcp.json"), input);
+  const fromManifest = await loadMcpServersFromSpec(input.loaded.manifest.mcpServers, input);
   return { ...fromFile, ...fromManifest };
 }
 
 export function resolvePluginMcpServers(input: {
   dataPath: string;
-  definitions?: Record<string, unknown>;
+  definitions: Record<string, unknown>;
   diagnostics: PluginDiagnostic[];
   env: Record<string, string | undefined>;
   loaded: LoadedPlugin;
   options: PluginOptionValues;
   workingDirectory: string;
 }): Record<string, McpServerConfig> {
-  const merged = input.definitions ?? loadPluginMcpServerDefinitions(input);
+  const merged = input.definitions;
   const context = createVariableContext(input);
   const result: Record<string, McpServerConfig> = {};
 
@@ -68,13 +74,13 @@ function toNamespacedServerName(loaded: LoadedPlugin, serverName: string): strin
   return `plugin:${loaded.manifest.name}:${serverName}`;
 }
 
-function loadMcpServersFromSpec(
+async function loadMcpServersFromSpec(
   spec: unknown,
   input: {
     diagnostics: PluginDiagnostic[];
     loaded: LoadedPlugin;
   },
-): Record<string, unknown> {
+): Promise<Record<string, unknown>> {
   if (spec === undefined) return {};
   if (typeof spec === "string") {
     const path = resolveInside(input.loaded.rootPath, spec);
@@ -88,24 +94,32 @@ function loadMcpServersFromSpec(
       });
       return {};
     }
-    return loadMcpServersFromFile(path, input);
+    return await loadMcpServersFromFile(path, input);
   }
   if (Array.isArray(spec)) {
-    return Object.assign({}, ...spec.map((item) => loadMcpServersFromSpec(item, input)));
+    const servers: Record<string, unknown> = {};
+    for (const item of spec) Object.assign(servers, await loadMcpServersFromSpec(item, input));
+    return servers;
   }
   return normalizeMcpServersShape(spec, input);
 }
 
-function loadMcpServersFromFile(
+async function loadMcpServersFromFile(
   path: string,
   input: {
     diagnostics: PluginDiagnostic[];
     loaded: LoadedPlugin;
   },
-): Record<string, unknown> {
+): Promise<Record<string, unknown>> {
   try {
-    return normalizeMcpServersShape(JSON.parse(readFileSync(path, "utf8")), input);
+    return normalizeMcpServersShape(
+      input.loaded.materials
+        ? await input.loaded.materials.json(path)
+        : JSON.parse(await readFile(path, "utf8")),
+      input,
+    );
   } catch (error) {
+    rethrowPluginMaterialInterrupt(error);
     if (isNotFoundError(error)) return {};
     input.diagnostics.push({
       code: "plugin_mcp_read_failed",

+ 45 - 41
apps/zcode-cli/packages/adapters/src/plugins/official-marketplace.ts

@@ -1,5 +1,7 @@
-import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
-import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
+import { readFile } from "node:fs/promises";
+import { isAbsolute, join, relative, resolve, sep } from "node:path";
+import { writePluginTextIfChanged } from "./helpers.js";
+import { withFileLock } from "@zcode/shared/node";
 import { ZCODE_OFFICIAL_PLUGIN_MARKETPLACE } from "@zcode/contracts";
 
 const BUNDLED_PARTITION_FILE = "bundled-marketplace.json";
@@ -11,38 +13,48 @@ interface BundledMarketplacePartition {
   version: 1;
 }
 
-export function writeBundledOfficialMarketplacePartitionSync(input: {
+export async function writeBundledOfficialMarketplacePartition(input: {
   manifest: Record<string, unknown>;
   storageRoot: string;
-}): Record<string, unknown> {
+}): Promise<Record<string, unknown>> {
   assertOfficialManifest(input.manifest);
-  writeJsonFileSync(partitionPath(input.storageRoot, BUNDLED_PARTITION_FILE), {
-    manifest: input.manifest,
-    version: 1,
-  } satisfies BundledMarketplacePartition);
-  return rebuildOfficialMarketplaceSync(input.storageRoot);
+  return publishPartition(input.storageRoot, async () => {
+    await writeJsonFile(partitionPath(input.storageRoot, BUNDLED_PARTITION_FILE), {
+      manifest: input.manifest,
+      version: 1,
+    } satisfies BundledMarketplacePartition);
+  });
 }
 
-export function writeCdnOfficialMarketplacePartitionSync(input: {
+export async function writeCdnOfficialMarketplacePartition(input: {
   manifest: Record<string, unknown>;
   storageRoot: string;
-}): Record<string, unknown> {
+}): Promise<Record<string, unknown>> {
   assertOfficialManifest(input.manifest);
-  writeJsonFileSync(partitionPath(input.storageRoot, CDN_PARTITION_FILE), input.manifest);
-  return rebuildOfficialMarketplaceSync(input.storageRoot);
+  return publishPartition(input.storageRoot, async () => {
+    await writeJsonFile(partitionPath(input.storageRoot, CDN_PARTITION_FILE), input.manifest);
+  });
+}
+
+async function publishPartition(
+  storageRoot: string,
+  write: () => Promise<void>,
+): Promise<Record<string, unknown>> {
+  // 启动 seed 和商店刷新可来自不同进程。分片写入和合并发布同属一次事务,
+  // 使用目录文件本身的锁,不递归获取外层安装锁,也不会锁住普通查询。
+  return withFileLock(partitionPath(storageRoot, MERGED_MARKETPLACE_FILE), async () => {
+    await write();
+    return rebuildOfficialMarketplace(storageRoot);
+  });
 }
 
-export function loadBundledOfficialPluginRootsSync(
+export async function loadBundledOfficialPluginRoots(
   storageRoot: string,
-): string[] | undefined {
-  const bundledPartition = readBundledPartition(storageRoot);
+): Promise<string[] | undefined> {
+  const bundledPartition = await readBundledPartition(storageRoot);
   if (!bundledPartition) return undefined;
 
-  const officialCacheRoot = resolve(
-    storageRoot,
-    "cache",
-    ZCODE_OFFICIAL_PLUGIN_MARKETPLACE,
-  );
+  const officialCacheRoot = resolve(storageRoot, "cache", ZCODE_OFFICIAL_PLUGIN_MARKETPLACE);
   return readPluginEntries(bundledPartition.manifest).flatMap((plugin) => {
     const name = readPluginName(plugin);
     const cachePath = typeof plugin.cachePath === "string" ? plugin.cachePath : undefined;
@@ -60,9 +72,9 @@ export function loadBundledOfficialPluginRootsSync(
   });
 }
 
-function rebuildOfficialMarketplaceSync(storageRoot: string): Record<string, unknown> {
-  const bundledPartition = readBundledPartition(storageRoot);
-  const cdnManifest = readJsonRecord(partitionPath(storageRoot, CDN_PARTITION_FILE));
+async function rebuildOfficialMarketplace(storageRoot: string): Promise<Record<string, unknown>> {
+  const bundledPartition = await readBundledPartition(storageRoot);
+  const cdnManifest = await readJsonRecord(partitionPath(storageRoot, CDN_PARTITION_FILE));
   const bundledManifest = bundledPartition?.manifest;
   const cdnPlugins = readPluginEntries(cdnManifest);
   const cdnPluginNames = new Set(cdnPlugins.map(readPluginName).filter(isDefined));
@@ -81,12 +93,14 @@ function rebuildOfficialMarketplaceSync(storageRoot: string): Record<string, unk
     name: ZCODE_OFFICIAL_PLUGIN_MARKETPLACE,
     plugins: [...cdnPlugins, ...bundledPlugins],
   };
-  writeJsonFileSync(partitionPath(storageRoot, MERGED_MARKETPLACE_FILE), merged);
+  await writeJsonFile(partitionPath(storageRoot, MERGED_MARKETPLACE_FILE), merged);
   return merged;
 }
 
-function readBundledPartition(storageRoot: string): BundledMarketplacePartition | undefined {
-  const value = readJsonRecord(partitionPath(storageRoot, BUNDLED_PARTITION_FILE));
+async function readBundledPartition(
+  storageRoot: string,
+): Promise<BundledMarketplacePartition | undefined> {
+  const value = await readJsonRecord(partitionPath(storageRoot, BUNDLED_PARTITION_FILE));
   if (!value || value.version !== 1 || !isRecord(value.manifest)) return undefined;
   return {
     manifest: value.manifest,
@@ -130,27 +144,17 @@ function partitionPath(storageRoot: string, fileName: string): string {
   return join(storageRoot, "marketplaces", ZCODE_OFFICIAL_PLUGIN_MARKETPLACE, fileName);
 }
 
-function readJsonRecord(path: string): Record<string, unknown> | undefined {
+async function readJsonRecord(path: string): Promise<Record<string, unknown> | undefined> {
   try {
-    const value = JSON.parse(readFileSync(path, "utf8")) as unknown;
+    const value = JSON.parse(await readFile(path, "utf8")) as unknown;
     return isRecord(value) ? value : undefined;
   } catch {
     return undefined;
   }
 }
 
-function writeJsonFileSync(path: string, value: unknown): void {
-  const contents = `${JSON.stringify(value, null, 2)}\n`;
-  mkdirSync(dirname(path), { recursive: true });
-  try {
-    // 官方目录在每次启动都会重建;同内容反复写盘会增加 Windows 上
-    // marketplace 文件被杀毒/索引器占用的概率。只跳过字节完全相同的单文件写入,
-    // 读取失败或内容变化仍执行写入并保留原有失败语义。
-    if (readFileSync(path, "utf8") === contents) return;
-  } catch {
-    // 文件不存在或暂时不可读时继续写,让真实更新失败继续向调用方暴露。
-  }
-  writeFileSync(path, contents, "utf8");
+async function writeJsonFile(path: string, value: unknown): Promise<void> {
+  await writePluginTextIfChanged(path, `${JSON.stringify(value, null, 2)}\n`);
 }
 
 function isRecord(value: unknown): value is Record<string, unknown> {

+ 283 - 42
apps/zcode-cli/packages/adapters/src/plugins/plugin-components.ts

@@ -1,17 +1,32 @@
-import { readdirSync } from "node:fs";
+import { mkdir, readdir, readFile } from "node:fs/promises";
 import { basename, dirname, join } from "node:path";
 import type {
+  CustomCommandRoot,
   PluginComponentGroup,
   PluginComponentItem,
   PluginComponentKind,
   PluginDiagnostic,
   PluginManifest,
+  SkillRoot,
 } from "@zcode/contracts";
-import { directoryExists, isRecord, resolveInside } from "./helpers.js";
-import { listPluginHookEventNames } from "./hook-sources.js";
-import { readMarkdownFrontmatter } from "./markdown-frontmatter.js";
+import {
+  directoryExistsAsync,
+  fileExistsAsync,
+  writePluginTextIfChanged,
+  type PluginMaterialReader,
+  rethrowPluginMaterialInterrupt,
+  isMissingPathAsync,
+  parsePathList,
+  isRecord,
+  resolveInside,
+} from "./helpers.js";
+import { createHookPluginContext, listPluginHookEventNames } from "./hook-sources.js";
+import {
+  applyCommandMetadataFrontmatter,
+  readMarkdownFrontmatters,
+} from "./markdown-frontmatter.js";
 import { loadPluginMcpServerDefinitions } from "./mcp.js";
-import { scanSkillFilesUnderRootSync } from "../skills/scan.js";
+import { scanSkillFilesUnderRoot } from "../skills/scan.js";
 import type { LoadedPlugin } from "./types.js";
 
 // 组件分组类型定义已上移到 @zcode/contracts(PluginMetadata 需要引用),这里再导出保持对外契约稳定。
@@ -22,38 +37,53 @@ export type { PluginComponentGroup, PluginComponentItem, PluginComponentKind };
  * manifest 由调用方读取后传入(可为 null);缺失目录或无 frontmatter 时跳过或省略描述,
  * 不因单个组件异常阻断整体枚举。
  */
-export function enumeratePluginComponents(
+export async function enumeratePluginComponents(
   rootPath: string,
   manifest: PluginManifest | null,
   options: { diagnostics?: PluginDiagnostic[]; loaded?: LoadedPlugin } = {},
-): PluginComponentGroup[] {
+): Promise<PluginComponentGroup[]> {
   const groups: PluginComponentGroup[] = [];
-  const agentItems = collectMarkdownComponents(rootPath, manifest?.agents, "agents");
+  const agentItems = await collectMarkdownComponents(
+    rootPath,
+    manifest?.agents,
+    "agents",
+    options.loaded?.materials,
+  );
   if (agentItems.length > 0) groups.push({ kind: "agent", items: agentItems });
 
-  const commandItems = collectMarkdownComponents(rootPath, manifest?.commands, "commands");
+  const commandItems = await collectMarkdownComponents(
+    rootPath,
+    manifest?.commands,
+    "commands",
+    options.loaded?.materials,
+  );
   if (commandItems.length > 0) groups.push({ kind: "command", items: commandItems });
 
   // 信任边界:组件枚举的 rootPath 就是插件根,扫描无条件不跟随符号链接——
   // 不依赖 loaded 是否凑齐(manifest 解析失败的 marketplace describe 链路同样生效)。
-  const skillItems = collectSkillComponents(rootPath, manifest?.skills);
+  const skillItems = await collectSkillComponents(
+    rootPath,
+    manifest?.skills,
+    options.loaded?.materials,
+  );
   if (skillItems.length > 0) groups.push({ kind: "skill", items: skillItems });
 
-  const hookItems = collectHookComponents(manifest, options);
+  const hookItems = await collectHookComponents(manifest, options);
   if (hookItems.length > 0) groups.push({ kind: "hook", items: hookItems });
 
-  const mcpItems = collectMcpComponents(manifest, options);
+  const mcpItems = await collectMcpComponents(manifest, options);
   if (mcpItems.length > 0) groups.push({ kind: "mcp", items: mcpItems });
 
   return groups;
 }
 
 /** command/agent:默认目录 + manifest 声明的额外路径下的 .md 文件,读 frontmatter name/description。 */
-function collectMarkdownComponents(
+async function collectMarkdownComponents(
   rootPath: string,
   manifestField: unknown,
   defaultDir: "commands" | "agents",
-): PluginComponentItem[] {
+  materials?: PluginMaterialReader,
+): Promise<PluginComponentItem[]> {
   const items: PluginComponentItem[] = [];
   const seen = new Set<string>();
 
@@ -71,20 +101,25 @@ function collectMarkdownComponents(
     }
   }
 
-  const dirs = collectComponentDirs(rootPath, manifestField, defaultDir);
+  const dirs = await collectComponentDirs(rootPath, manifestField, defaultDir, materials);
   for (const dir of dirs) {
     let entries: string[];
     try {
-      entries = readdirSync(dir, { withFileTypes: true })
+      entries = (await (materials?.directory(dir) ?? readdir(dir, { withFileTypes: true })))
         .filter((dirent) => dirent.isFile() && dirent.name.endsWith(".md"))
         .map((dirent) => dirent.name);
-    } catch {
+    } catch (error) {
+      rethrowPluginMaterialInterrupt(error);
       continue;
     }
-    for (const fileName of entries) {
+    const frontmatters = await readMarkdownFrontmatters(
+      entries.map((name) => join(dir, name)),
+      materials,
+    );
+    for (const [index, fileName] of entries.entries()) {
       const baseName = fileName.slice(0, -".md".length);
       const path = join(dir, fileName);
-      const fm = readMarkdownFrontmatter(path);
+      const fm = frontmatters[index]!;
       const name = fm.name ?? baseName;
       if (seen.has(name)) continue;
       seen.add(name);
@@ -99,27 +134,36 @@ function collectMarkdownComponents(
 }
 
 /**
- * skill:默认 skills 目录与 manifest 声明路径下枚举技能,读取 SKILL.md frontmatter。
- * 根自身含 SKILL.md 时根自身是一个技能;按文件路径和最终 name 去重,避免声明根与默认根
- * 重复计数,也避免不同路径下同名技能造成展示结果漂移。
+ * skill:有声明时只使用声明路径,否则使用默认 skills 目录。
+ * 单技能入口不额外扫描子目录;按文件路径和最终 name 去重。
  */
-function collectSkillComponents(rootPath: string, manifestField: unknown): PluginComponentItem[] {
+async function collectSkillComponents(
+  rootPath: string,
+  manifestField: unknown,
+  materials?: PluginMaterialReader,
+): Promise<PluginComponentItem[]> {
   const items: PluginComponentItem[] = [];
   const seenFiles = new Set<string>();
   const seenNames = new Set<string>();
-  const dirs = collectComponentDirs(rootPath, manifestField, "skills");
+  const dirs = await collectComponentDirs(rootPath, manifestField, "skills", materials);
   for (const dir of dirs) {
     let skillFiles: string[];
     try {
-      skillFiles = scanSkillFilesUnderRootSync(dir, { followSymbolicLinks: false });
-    } catch {
+      skillFiles = await (materials?.skillFiles(dir) ??
+        scanSkillFilesUnderRoot(dir, { followSymbolicLinks: false, stopAtSkill: true }));
+    } catch (error) {
+      rethrowPluginMaterialInterrupt(error);
       continue;
     }
-    for (const skillFile of skillFiles) {
-      if (seenFiles.has(skillFile)) continue;
+    const freshFiles = skillFiles.filter((skillFile) => {
+      if (seenFiles.has(skillFile)) return false;
       seenFiles.add(skillFile);
+      return true;
+    });
+    const frontmatters = await readMarkdownFrontmatters(freshFiles, materials);
+    for (const [index, skillFile] of freshFiles.entries()) {
       const fallbackName = basename(dirname(skillFile));
-      const fm = readMarkdownFrontmatter(skillFile);
+      const fm = frontmatters[index]!;
       const name = fm.name ?? fallbackName;
       if (seenNames.has(name)) continue;
       seenNames.add(name);
@@ -130,28 +174,30 @@ function collectSkillComponents(rootPath: string, manifestField: unknown): Plugi
 }
 
 /** hook:复用 loader 的来源发现规则,但只取事件名用于详情展示,不构造可执行 hook。 */
-function collectHookComponents(
+async function collectHookComponents(
   manifest: PluginManifest | null,
   options: { diagnostics?: PluginDiagnostic[]; loaded?: LoadedPlugin },
-): PluginComponentItem[] {
+): Promise<PluginComponentItem[]> {
   if (options.loaded) {
-    return listPluginHookEventNames({
-      diagnostics: options.diagnostics ?? [],
-      loaded: options.loaded,
-    }).map((name) => ({ name }));
+    return (
+      await listPluginHookEventNames({
+        diagnostics: options.diagnostics ?? [],
+        loaded: options.loaded,
+      })
+    ).map((name) => ({ name }));
   }
   if (!manifest) return [];
   return collectInlineHookEvents(manifest.hooks).map((name) => ({ name }));
 }
 
 /** mcp:复用 loader 读取 `.mcp.json` + `manifest.mcpServers` 的纯读解析,只展示原始 server 名。 */
-function collectMcpComponents(
+async function collectMcpComponents(
   manifest: PluginManifest | null,
   options: { diagnostics?: PluginDiagnostic[]; loaded?: LoadedPlugin },
-): PluginComponentItem[] {
+): Promise<PluginComponentItem[]> {
   if (options.loaded) {
     return Object.keys(
-      loadPluginMcpServerDefinitions({
+      await loadPluginMcpServerDefinitions({
         diagnostics: options.diagnostics ?? [],
         loaded: options.loaded,
       }),
@@ -184,12 +230,13 @@ function collectInlineHookEvents(value: unknown): string[] {
   return names;
 }
 
-/** 默认目录约定 + manifest 字符串/数组路径声明,合并成去重的待扫描目录列表。 */
-function collectComponentDirs(
+/** 解析组件目录;skills 显式声明优先,其他组件保留默认目录合并规则。 */
+async function collectComponentDirs(
   rootPath: string,
   manifestField: unknown,
   defaultDir: string,
-): string[] {
+  materials?: PluginMaterialReader,
+): Promise<string[]> {
   const dirs: string[] = [];
   const seen = new Set<string>();
   const add = (raw: string): void => {
@@ -199,10 +246,204 @@ function collectComponentDirs(
     dirs.push(resolvedPath);
   };
   const defaultPath = join(rootPath, defaultDir);
-  if (directoryExists(defaultPath)) add(defaultDir);
+  if (
+    (defaultDir !== "skills" || manifestField === undefined) &&
+    (await (materials?.directoryExists(defaultPath) ?? directoryExistsAsync(defaultPath)))
+  )
+    add(defaultDir);
   if (typeof manifestField === "string") add(manifestField);
   else if (Array.isArray(manifestField)) {
     for (const value of manifestField) if (typeof value === "string") add(value);
   }
   return dirs;
 }
+
+/**
+ * manifest 显式声明的 skills 路径没有可用技能时发出诊断,避免路径配置错误静默失败。
+ * 声明集合独立于 roots 列表计算,默认 skills/ 目录为空时不误报;路径缺失、目录为空和
+ * 符号链接越界分别保留可操作的诊断信息,权限错误交给实际扫描链路报告。
+ */
+export async function warnEmptyDeclaredSkillRoots(input: {
+  diagnostics: PluginDiagnostic[];
+  loaded: LoadedPlugin;
+}): Promise<void> {
+  const declared = parsePathList(input.loaded.manifest.skills);
+  if (declared.length === 0) return;
+  const seenPaths = new Set<string>();
+  for (const rawPath of declared) {
+    const resolved = resolveInside(input.loaded.rootPath, rawPath);
+    if (!resolved || seenPaths.has(resolved)) continue;
+    seenPaths.add(resolved);
+    // 路径缺失判定只认 ENOENT/ENOTDIR(stat 精确分类),EACCES 等权限
+    // 错误不得误报成「不存在」——此时没有证据下结论,跳过告警,由 skill adapter
+    // 扫描同一目录时发 skill_scan_failed。
+    // message 按原因区分:「路径不存在」是 manifest 配错,「存在但没有技能」
+    // 是内容问题,「symlink 逃逸出插件根」是安全拒绝,三者修复方式不同;
+    // code 保持单一,UI 无需感知分类。
+    if (await (input.loaded.materials?.missing(resolved) ?? isMissingPathAsync(resolved))) {
+      input.diagnostics.push({
+        code: "plugin_skill_root_empty",
+        message: `Plugin skills path does not exist: ${rawPath}`,
+        path: resolved,
+        pluginId: input.loaded.id,
+        severity: "warning",
+      });
+      continue;
+    }
+    // 信任边界:声明路径是插件内容,扫描不跟随符号链接(目录级/文件级逃逸
+    // 一并拒绝,含 Windows junction)。链接根/链接 SKILL.md 扫描为空后落入下方
+    // 「没有任何技能」告警,不误报「不存在」(词法路径本身存在)。
+    let skillFiles: string[];
+    try {
+      skillFiles = await (input.loaded.materials?.skillFiles(resolved) ??
+        scanSkillFilesUnderRoot(resolved, { followSymbolicLinks: false, stopAtSkill: true }));
+    } catch (error) {
+      rethrowPluginMaterialInterrupt(error);
+      continue;
+    }
+    if (skillFiles.length > 0) continue;
+    input.diagnostics.push({
+      code: "plugin_skill_root_empty",
+      message: `Plugin skills path does not contain any skills: ${rawPath}`,
+      path: resolved,
+      pluginId: input.loaded.id,
+      severity: "warning",
+    });
+  }
+}
+
+export async function countSkillFiles(
+  skillRoots: SkillRoot[],
+  materials?: PluginMaterialReader,
+): Promise<number> {
+  // 技能识别规则收敛到共享 scan helper;重叠的声明入口仍需按文件路径去重。
+  // 顺带修正漂移:只认 isDirectory() 会漏掉 symlink 技能子目录,统一 helper 后一并计入。
+  // helper 只吞 ENOENT;权限错误(EACCES 等)会抛出,这里按原语义把该根计 0,
+  // 真正的 skill_scan_failed 诊断由 skill adapter 在运行时扫描同一目录时发出。
+  // 信任边界:这里只消费 plugin roots(resolveSkillRoots 产物),不跟随符号链接。
+  const seenFiles = new Set<string>();
+  for (const skillRoot of skillRoots) {
+    try {
+      const files = await (materials?.skillFiles(skillRoot.path, skillRoot.source !== "plugin") ??
+        scanSkillFilesUnderRoot(skillRoot.path, {
+          followSymbolicLinks: skillRoot.source !== "plugin",
+          stopAtSkill: skillRoot.source === "plugin",
+        }));
+      for (const file of files) {
+        seenFiles.add(file);
+      }
+    } catch (error) {
+      rethrowPluginMaterialInterrupt(error);
+      // 概览计数降级为 0;扫描诊断由 skill adapter 负责。
+    }
+  }
+  return seenFiles.size;
+}
+
+export async function materializeCommandMetadataRoot(
+  input: { dataPath: string; diagnostics: PluginDiagnostic[]; loaded: LoadedPlugin },
+  priority: number,
+): Promise<CustomCommandRoot | null> {
+  const spec = input.loaded.manifest.commands;
+  if (!isRecord(spec)) return null;
+
+  const generatedRoot = join(input.dataPath, "generated-commands");
+  let wroteCommand = false;
+  await mkdir(generatedRoot, { recursive: true });
+
+  for (const [rawName, rawMetadata] of Object.entries(spec)) {
+    if (!isRecord(rawMetadata)) {
+      input.diagnostics.push({
+        code: "plugin_manifest_invalid",
+        message: `Plugin command metadata must be an object: ${rawName}`,
+        path: input.loaded.manifestPath,
+        pluginId: input.loaded.id,
+        severity: "error",
+      });
+      continue;
+    }
+
+    const name = normalizeGeneratedCommandName(rawName);
+    if (!name) {
+      input.diagnostics.push({
+        code: "plugin_manifest_invalid",
+        message: `Invalid plugin command name: ${rawName}`,
+        path: input.loaded.manifestPath,
+        pluginId: input.loaded.id,
+        severity: "error",
+      });
+      continue;
+    }
+
+    const source = typeof rawMetadata.source === "string" ? rawMetadata.source : undefined;
+    const content = typeof rawMetadata.content === "string" ? rawMetadata.content : undefined;
+    if ((source && content) || (!source && !content)) {
+      input.diagnostics.push({
+        code: "plugin_manifest_invalid",
+        message: `Plugin command '${rawName}' must provide exactly one of source or content`,
+        path: input.loaded.manifestPath,
+        pluginId: input.loaded.id,
+        severity: "error",
+      });
+      continue;
+    }
+
+    let markdown = content;
+    if (source) {
+      const sourcePath = resolveInside(input.loaded.rootPath, trimRelativePrefix(source));
+      if (!sourcePath) {
+        input.diagnostics.push({
+          code: "plugin_component_path_invalid",
+          message: `Plugin command source escapes plugin root: ${source}`,
+          path: input.loaded.manifestPath,
+          pluginId: input.loaded.id,
+          severity: "error",
+        });
+        continue;
+      }
+      if (
+        !(await (input.loaded.materials?.fileExists(sourcePath) ?? fileExistsAsync(sourcePath)))
+      ) {
+        input.diagnostics.push({
+          code: "plugin_component_path_invalid",
+          message: `Plugin command source file not found: ${source}`,
+          path: sourcePath,
+          pluginId: input.loaded.id,
+          severity: "error",
+        });
+        continue;
+      }
+      markdown = await (input.loaded.materials?.text(sourcePath) ?? readFile(sourcePath, "utf8"));
+    }
+    if (markdown === undefined) continue;
+
+    // 市场清单支持 commands object mapping 和 inline content。
+    // ZCode 的 custom command loader 只扫描 markdown 根目录,因此把低风险命令内容
+    // materialize 到插件 data 目录;生成路径不在 plugin root 外暴露,也不执行命令本身。
+    await writePluginTextIfChanged(
+      join(generatedRoot, `${name}.md`),
+      applyCommandMetadataFrontmatter(markdown, rawMetadata),
+    );
+    wroteCommand = true;
+  }
+
+  return wroteCommand
+    ? {
+        path: generatedRoot,
+        plugin: createHookPluginContext(input.loaded, input.dataPath),
+        priority,
+        scope: input.loaded.source === "official" ? "system" : "user",
+        source: "plugin",
+      }
+    : null;
+}
+
+function normalizeGeneratedCommandName(name: string): string | null {
+  const normalized = name.trim().replace(/^\/+/, "").toLowerCase();
+  if (!/^[a-z0-9][a-z0-9_:-]{0,63}$/.test(normalized)) return null;
+  return normalized;
+}
+
+function trimRelativePrefix(path: string): string {
+  return path.replace(/^\.\//, "");
+}

+ 2 - 0
apps/zcode-cli/packages/adapters/src/plugins/types.ts

@@ -1,3 +1,4 @@
+import type { PluginMaterialReader } from "./helpers.js";
 import type {
   CustomCommandRoot,
   HookEventName,
@@ -17,6 +18,7 @@ export interface PluginCandidate {
 }
 
 export interface LoadedPlugin {
+  materials?: PluginMaterialReader;
   id: string;
   manifest: PluginManifest;
   manifestPath: string;

+ 34 - 10
apps/zcode-cli/packages/adapters/src/plugins/zip-source.ts

@@ -2,6 +2,8 @@ import { createHash } from "node:crypto";
 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
 import { tmpdir } from "node:os";
 import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
+import { isHttpClientPortError } from "@zcode/contracts";
 import * as yauzl from "yauzl";
 import { createNodeWebFetchHttpClientAdapter } from "../http/index.js";
 import {
@@ -180,16 +182,38 @@ async function downloadZipArchive(input: {
   for (let redirectCount = 0; redirectCount <= ZIP_MAX_REDIRECTS; redirectCount += 1) {
     throwIfAborted(input.signal);
     validateZipDownloadUrl(currentUrl);
-    const response = await client.request(
-      {
-        headers: currentHeaders,
-        maxResponseBytes: ZIP_DOWNLOAD_MAX_BYTES,
-        method: "GET",
-        redirect: "manual",
-        url: currentUrl,
-      },
-      { signal: input.signal },
-    );
+    const request = () =>
+      client.request(
+        {
+          headers: currentHeaders,
+          maxResponseBytes: ZIP_DOWNLOAD_MAX_BYTES,
+          method: "GET",
+          redirect: "manual",
+          url: currentUrl,
+        },
+        { signal: input.signal },
+      );
+    const response = await request().catch(async (error: unknown) => {
+      if (
+        !isHttpClientPortError(error) ||
+        (error.code !== "network_error" && error.code !== "proxy_error")
+      )
+        throw error;
+      // 代理 TLS 握手或正文传输可能偶发断开;GET 尚未激活缓存,可安全重试一次。
+      // 原生 fetch 比代理请求多包一层 cause;仅识别连接重置,不重试证书错误或取消。
+      const cause =
+        error.cause instanceof Error && error.cause.cause instanceof Error
+          ? error.cause.cause
+          : error.cause;
+      if (
+        !(cause instanceof Error) ||
+        !("code" in cause) ||
+        (cause.code !== "ECONNRESET" && cause.code !== "UND_ERR_SOCKET")
+      )
+        throw error;
+      await delay(250, undefined, { signal: input.signal });
+      return request();
+    });
 
     if (isRedirectStatus(response.status)) {
       const location = response.headers.location;

+ 2 - 1
apps/zcode-cli/packages/adapters/src/skills/index.ts

@@ -135,11 +135,12 @@ export class NodeSkillAdapter implements SkillPort {
   ): Promise<string[]> {
     try {
       // manifest 的 skills 项既可指向单个技能目录,也可指向包含多个技能的根目录。
-      // 共享 scan helper 会检查根自身的 SKILL.md,再扫描一层子目录,排除策略与桌面端一致。
+      // 插件单技能入口不再隐式带入子技能;用户级、项目级根保留原扫描范围。
       // 信任边界:plugin-scope 内容不可信,不跟随符号链接(目录级与文件级逃逸
       // 一并拒绝);用户级根保持跟随,symlink 技能导入能力不变。
       return await scanSkillFilesUnderRoot(skillRoot.path, {
         followSymbolicLinks: skillRoot.source !== "plugin",
+        stopAtSkill: skillRoot.source === "plugin",
       });
     } catch (error) {
       if (isNotFoundError(error)) {

+ 30 - 62
apps/zcode-cli/packages/adapters/src/skills/scan.ts

@@ -1,12 +1,12 @@
+import type { Dirent } from "node:fs";
 // ============================================================
 // 技能根扫描规则(共享实现)
 // ============================================================
 
 // manifest 的 skills 项既可指向单个技能目录,也可指向一层技能集合。
-// 根目录含 SKILL.md 时先识别根技能,再扫描一层子目录;与桌面发现规则保持一致,
-// 避免把单个技能误当集合而静默漏扫。
-// 插件发现链路(countSkillFiles / collectSkillComponents)是同步代码,技能 adapter 走
-// fs/promises,因此提供 sync/async 两个变体,规则只写一份、由各自实现遵循。
+// 插件根目录含 SKILL.md 时只加载根技能,否则扫描一层子目录;
+// 用户级、项目级根仍同时识别根技能与一层子技能。
+// 插件发现与技能 adapter 共用同一异步实现,保持扫描深度与符号链接规则一致。
 //
 // 错误契约:只吞「常态缺失」——路径不存在(ENOENT)或不是目录时返回空数组;其余错误
 // (如 EACCES 权限、EMFILE)必须向上抛,由调用方决定发 skill_scan_failed 诊断还是
@@ -22,7 +22,6 @@
 // SKILL.md 文件三个粒度全部拒绝链接(拒绝即无逃逸,无需判定链接指向何处)。
 // 用户级技能根(~/.zcode/skills 的 symlink 导入是受支持功能)保持默认跟随。
 
-import { lstatSync, readdirSync, statSync } from "node:fs";
 import { lstat, readdir, stat } from "node:fs/promises";
 import { join } from "node:path";
 import { SKILL_FILE_NAME, shouldWalkSkillDirectoryEntry } from "@zcode/shared";
@@ -34,6 +33,10 @@ export interface ScanSkillFilesOptions {
    * 链接即拒绝逃逸,无需 realpath 判定指向。
    */
   followSymbolicLinks?: boolean;
+  /** 插件入口自身是技能时停止,不探测其附属目录。 */
+  stopAtSkill?: boolean;
+  readDirectory?: (path: string) => Promise<Dirent[]>;
+  observe?: (path: string) => Promise<"file" | "directory" | "other" | "missing">;
 }
 
 /**
@@ -48,18 +51,19 @@ export async function scanSkillFilesUnderRoot(
   // 根自身是链接(含 junction)时,插件扫描直接判空。
   if (!followSymlinks && (await isSymbolicLink(rootPath))) return [];
 
-  const rootInfo = await stat(rootPath).catch((error) => {
-    throwIfUnexpectedScanError(error);
-    return null;
-  });
-  if (!rootInfo?.isDirectory()) return [];
+  if ((await pathKind(rootPath, options.observe)) !== "directory") return [];
 
   const files: string[] = [];
   const own = join(rootPath, SKILL_FILE_NAME);
   // 根自身无 SKILL.md 是常态,继续扫一层子目录。
-  if (await isLoadableSkillFile(own, followSymlinks)) files.push(own);
+  if (await isLoadableSkillFile(own, followSymlinks, options.observe)) {
+    files.push(own);
+    // 单技能的 scripts、agents 等附属目录不是隐式入口,避免额外发现和无效 IO。
+    if (options.stopAtSkill) return files;
+  }
 
-  const entries = await readdir(rootPath, { withFileTypes: true });
+  const entries = await (options.readDirectory?.(rootPath) ??
+    readdir(rootPath, { withFileTypes: true }));
   for (const entry of entries) {
     const walkable = entry.isDirectory() || (followSymlinks && entry.isSymbolicLink());
     if (!walkable) continue;
@@ -68,32 +72,8 @@ export async function scanSkillFilesUnderRoot(
     // 不是技能目录,拼出来的路径不存在;parseSkill 本会静默跳过,但计数与
     // 组件枚举都消费该结果,不校验会把「不存在的技能」算进来。
     const candidate = join(rootPath, entry.name, SKILL_FILE_NAME);
-    if (await isLoadableSkillFile(candidate, followSymlinks)) files.push(candidate);
-  }
-  return files;
-}
-
-/** scanSkillFilesUnderRoot 的同步变体,错误契约相同。 */
-export function scanSkillFilesUnderRootSync(
-  rootPath: string,
-  options: ScanSkillFilesOptions = {},
-): string[] {
-  const followSymlinks = options.followSymbolicLinks ?? true;
-  if (!followSymlinks && isSymbolicLinkSync(rootPath)) return [];
-
-  const rootInfo = statSyncOrNull(rootPath);
-  if (!rootInfo?.isDirectory()) return [];
-
-  const files: string[] = [];
-  const own = join(rootPath, SKILL_FILE_NAME);
-  if (isLoadableSkillFileSync(own, followSymlinks)) files.push(own);
-
-  for (const entry of readdirSync(rootPath, { withFileTypes: true })) {
-    const walkable = entry.isDirectory() || (followSymlinks && entry.isSymbolicLink());
-    if (!walkable) continue;
-    if (!shouldWalkSkillDirectoryEntry(entry.name)) continue;
-    const candidate = join(rootPath, entry.name, SKILL_FILE_NAME);
-    if (isLoadableSkillFileSync(candidate, followSymlinks)) files.push(candidate);
+    if (await isLoadableSkillFile(candidate, followSymlinks, options.observe))
+      files.push(candidate);
   }
   return files;
 }
@@ -102,18 +82,23 @@ export function scanSkillFilesUnderRootSync(
  * SKILL.md 候选的可加载判定:真实文件才收录。不跟随链接时符号链接文件
  * (含 junction)一律拒绝——这是文件级逃逸(SKILL.md -> 外部任意文件)的防线。
  */
-async function isLoadableSkillFile(path: string, followSymlinks: boolean): Promise<boolean> {
+async function isLoadableSkillFile(
+  path: string,
+  followSymlinks: boolean,
+  observe?: ScanSkillFilesOptions["observe"],
+): Promise<boolean> {
   if (!followSymlinks && (await isSymbolicLink(path))) return false;
+  return (await pathKind(path, observe)) === "file";
+}
+
+async function pathKind(path: string, observe: ScanSkillFilesOptions["observe"]) {
+  // material reader 已查到文件类型,复用该事实,避免每个技能再 stat 一遍。
+  if (observe) return observe(path);
   const info = await stat(path).catch((error) => {
     throwIfUnexpectedScanError(error);
     return null;
   });
-  return info?.isFile() ?? false;
-}
-
-function isLoadableSkillFileSync(path: string, followSymlinks: boolean): boolean {
-  if (!followSymlinks && isSymbolicLinkSync(path)) return false;
-  return statSyncOrNull(path)?.isFile() ?? false;
+  return info?.isFile() ? "file" : info?.isDirectory() ? "directory" : info ? "other" : "missing";
 }
 
 async function isSymbolicLink(path: string): Promise<boolean> {
@@ -124,23 +109,6 @@ async function isSymbolicLink(path: string): Promise<boolean> {
   }
 }
 
-function isSymbolicLinkSync(path: string): boolean {
-  try {
-    return lstatSync(path).isSymbolicLink();
-  } catch {
-    return false;
-  }
-}
-
-function statSyncOrNull(path: string): { isFile(): boolean; isDirectory(): boolean } | null {
-  try {
-    return statSync(path);
-  } catch (error) {
-    throwIfUnexpectedScanError(error);
-    return null;
-  }
-}
-
 /** ENOENT(路径不存在)是扫描常态,吞掉;其余错误(EACCES 等)向上抛。 */
 function throwIfUnexpectedScanError(error: unknown): void {
   if (

+ 8 - 1
apps/zcode-cli/packages/adapters/src/storage/session-data-files/contract.ts

@@ -9,9 +9,16 @@ export interface SessionDataDirectory {
  * 会话与目录在 CLI 存储根下的文件。大小只统计真实文件(lstat,不跟随符号链接),
  * remove 返回删除前测得的字节数;路径不存在按 0 处理,因此重复删除幂等。
  */
+export interface SessionDataFile {
+  name: string;
+  relativePath: string;
+  kind: "artifact" | "record";
+  bytes: number;
+}
 export interface SessionDataFilesPort {
+  listSessionFiles?(sessionId: string): Promise<SessionDataFile[]>;
   measureSession(sessionId: string): Promise<number>;
-  removeSession(sessionId: string): Promise<number>;
+  removeSession(sessionId: string, retainedArtifactIds?: readonly string[]): Promise<number>;
   measureMemory(directory: SessionDataDirectory): Promise<number>;
   removeMemory(directory: SessionDataDirectory): Promise<number>;
 }

+ 75 - 5
apps/zcode-cli/packages/adapters/src/storage/session-data-files/index.ts

@@ -1,11 +1,10 @@
 import { lstat, readdir, rm } from "node:fs/promises";
-import { dirname, join, relative, isAbsolute } from "node:path";
+import { basename, dirname, join, relative, isAbsolute } from "node:path";
 
-import type { SessionDataDirectory, SessionDataFilesPort } from "./contract.js";
+import type { SessionDataDirectory, SessionDataFilesPort, SessionDataFile } from "./contract.js";
 
 export type { SessionDataDirectory, SessionDataFilesPort } from "./contract.js";
 
-
 export interface NodeSessionDataFilesOptions {
   cliStorageRoot: string;
   /** 返回 `<cli>/memories/projects/<slug>-<hash>/memory`;删除其父目录。 */
@@ -35,7 +34,13 @@ export function createNodeSessionDataFiles(
     const projects = join(root, ...MEMORY_PROJECTS_PATH);
     const inside = relative(projects, projectFolder);
     // 只允许 memories/projects 的直接子目录,防止解析结果越界删到别处。
-    if (!inside || inside.startsWith("..") || isAbsolute(inside) || inside.includes("/") || inside.includes("\\"))
+    if (
+      !inside ||
+      inside.startsWith("..") ||
+      isAbsolute(inside) ||
+      inside.includes("/") ||
+      inside.includes("\\")
+    )
       throw new Error("session-data.memory-outside-storage");
     return projectFolder;
   };
@@ -47,9 +52,74 @@ export function createNodeSessionDataFiles(
     await Promise.all(paths.map((path) => rm(path, { recursive: true, force: true })));
     return bytes;
   };
+  const listSessionFiles = async (sessionId: string): Promise<SessionDataFile[]> => {
+    const result: SessionDataFile[] = [];
+    for (const path of sessionPaths(sessionId)) {
+      const kind = path === join(root, "artifacts", sessionId) ? "artifact" : "record";
+      const walk = async (current: string): Promise<void> => {
+        let stats;
+        try {
+          stats = await lstat(current);
+        } catch (error) {
+          if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
+          throw error;
+        }
+        if (stats.isSymbolicLink()) {
+          result.push({
+            name: basename(current),
+            relativePath: relative(root, current),
+            kind,
+            bytes: 0,
+          });
+          return;
+        }
+        if (stats.isDirectory()) {
+          for (const entry of await readdir(current)) await walk(join(current, entry));
+          return;
+        }
+        result.push({
+          name: basename(current),
+          relativePath: relative(root, current),
+          kind,
+          bytes: stats.size,
+        });
+      };
+      // 存储类别目录若被换成链接,不能沿祖先链接清理用户文件。
+      const parent = await lstat(dirname(path)).catch((error) => {
+        if (error.code === "ENOENT") return null;
+        throw error;
+      });
+      if (parent?.isSymbolicLink()) throw new Error("session-data.symlink-root");
+      await walk(path);
+    }
+    return result.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
+  };
+  const removeSession = async (
+    sessionId: string,
+    retained: readonly string[] = [],
+  ): Promise<number> => {
+    const paths = sessionPaths(sessionId);
+    const manifest = await listSessionFiles(sessionId);
+    if (!retained.length) {
+      await removeAll(paths);
+      return manifest.reduce((sum, file) => sum + file.bytes, 0);
+    }
+    // 保留 URI 定位所需的附件文件,绝不因为引用而留下正文、执行日志或其他独占附件。
+    const keep = (file: SessionDataFile) =>
+      file.kind === "artifact" && retained.some((id) => file.name.includes(id));
+    let bytes = 0;
+    for (const file of manifest) {
+      if (keep(file)) continue;
+      await rm(join(root, file.relativePath), { force: true });
+      bytes += file.bytes;
+    }
+    for (const path of paths.slice(1)) await rm(path, { recursive: true, force: true });
+    return bytes;
+  };
   return {
     measureSession: async (sessionId) => measureAll(sessionPaths(sessionId)),
-    removeSession: async (sessionId) => removeAll(sessionPaths(sessionId)),
+    removeSession,
+    listSessionFiles,
     measureMemory: async (directory) => measureAll([memoryPath(directory)]),
     removeMemory: async (directory) => removeAll([memoryPath(directory)]),
   };

+ 117 - 0
apps/zcode-cli/packages/adapters/src/storage/session-store/migrations.ts

@@ -984,4 +984,121 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
     `,
   },
   { ...SESSION_DATABASE_IDENTITY_MIGRATION, touchedTables: ["zcode_database_identity"] },
+  {
+    id: "0025_session_permanent_deletion",
+    appVersion: "0.17.1",
+    touchedTables: ["session_purge", "session_runtime_presence"],
+    apply(db) {
+      // 结构已存在但迁移未记账时,只补缺失对象,保留删除凭据和现有触发器。
+      // 原 SQL 已发布且参与 checksum,守卫仅用于执行,避免已升级数据库校验失败。
+      db.exec(this.sql.replaceAll(/create (table|index|trigger) /g, "create $1 if not exists "));
+    },
+    sql: `
+      create table session_purge (
+        session_id text primary key,
+        root_id text not null,
+        operation_id text not null,
+        retained_artifacts text not null,
+        workspace_path text not null,
+        workspace_identity text,
+        state text not null check(state in ('deleting', 'deleted'))
+      );
+      create index session_purge_root_idx on session_purge(root_id);
+      create table session_runtime_presence (
+        session_id text not null,
+        owner_id text not null,
+        process_id integer not null,
+        primary key(session_id, owner_id)
+      );
+      create trigger session_purge_insert_guard before insert on session
+      when exists(select 1 from session_purge where session_id=new.id)
+      begin select raise(abort, 'session-data.deleting'); end;
+      create trigger session_purge_child_guard before insert on session
+      when exists(select 1 from session_purge where session_id=new.parent_id)
+      begin select raise(abort, 'session-data.deleting'); end;
+      create trigger session_purge_update_guard before update on session
+      when exists(select 1 from session_purge where session_id=new.id or (new.parent_id is not old.parent_id and session_id=new.parent_id))
+      begin select raise(abort, 'session-data.deleting'); end;
+      ${["insert", "update"]
+        .map(
+          (action) => `
+        create trigger session_purge_link_${action} before ${action} on session_task_link
+        when ${action === "update" ? "(new.parent_session_id is not old.parent_session_id or new.child_session_id is not old.child_session_id) and new.parent_session_id is not null and" : ""} exists(select 1 from session_purge where session_id=new.parent_session_id or session_id=new.child_session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+      `,
+        )
+        .join("\n")}
+      create trigger session_purge_runtime_guard before insert on session_runtime_presence
+      when exists(select 1 from session_purge where session_id=new.session_id)
+      begin select raise(abort, 'session-data.deleting'); end;
+      ${[
+        "message",
+        "part",
+        "session_input",
+        "session_entry",
+        "todo",
+        "model_usage",
+        "session_target",
+        "turn_usage",
+        "tool_usage",
+        "input_history",
+      ]
+        .flatMap((table) =>
+          ["insert", "update"].map(
+            (action) => `
+        create trigger session_purge_${table}_${action} before ${action} on ${table}
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+      `,
+          ),
+        )
+        .join("\n")}
+      ${["dwf_run", "workflow_run"]
+        .flatMap((table) =>
+          ["insert", "update"].map(
+            (action) => `
+        create trigger session_purge_owner_${table}_${action} before ${action} on ${table}
+        when new.parent_session_id is not null and exists(select 1 from session_purge where session_id=new.parent_session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+      `,
+          ),
+        )
+        .join("\n")}
+      ${[
+        ["dwf_run", "args_json"],
+        ["dwf_run", "result_json"],
+        ["dwf_run", "failure_json"],
+        ["workflow_run", "args_json"],
+        ["workflow_run", "stats_json"],
+        ["workflow_run", "failure_json"],
+        ["dwf_node", "input_json"],
+        ["dwf_node", "result_json"],
+        ["dwf_node", "error_json"],
+        ["dwf_event", "payload_json"],
+        ["dwf_actor", "persona_json"],
+        ["workflow_activity", "prompt"],
+        ["workflow_activity", "opts_json"],
+        ["workflow_activity", "result_json"],
+        ["workflow_activity", "error_json"],
+        ["workflow_event", "payload_json"],
+        ["part", "data"],
+        ["message", "data"],
+        ["session_entry", "data"],
+        ["session_input", "payload"],
+        ["session", "revert"],
+        ["input_history", "attachments"],
+      ]
+        .flatMap(([table, column]) =>
+          ["insert", "update"].map(
+            (action) => `
+        create trigger session_purge_reference_${table}_${column}_${action} before ${action}${action === "update" ? ` of ${column}` : ""} on ${table}
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.${column}, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+      `,
+          ),
+        )
+        .join("\n")}
+    `,
+  },
 ];

+ 255 - 15
apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/messages.ts

@@ -1,12 +1,16 @@
 import type { DatabaseSync } from "node:sqlite";
-import type {
-  MessageId,
-  MessageInfo,
-  MessagePart,
-  MessageWithParts,
-  PartId,
-  SessionId,
-  SessionStorePort,
+import {
+  assistantBlockParts,
+  isAssistantBlockPart,
+  sortByCompleteIndex,
+  type ForkCommitBundle,
+  type MessageId,
+  type MessageInfo,
+  type MessagePart,
+  type MessageWithParts,
+  type PartId,
+  type SessionId,
+  type SessionStorePort,
 } from "@zcode/contracts";
 import { decodeMessageRow, decodePartRow, partCreatedAt } from "../codecs.js";
 import { encodeJson } from "../json.js";
@@ -248,10 +252,10 @@ export function messages(db: DatabaseSync, input: { sessionID: SessionId }): Mes
     partsByMessage.set(row.message_id, list);
   }
 
-  return messageRows.map((row) => ({
-    info: decodeMessageRow(row),
-    parts: partsByMessage.get(row.id) ?? [],
-  }));
+  return messageRows.map((row) => {
+    const info = decodeMessageRow(row);
+    return { info, parts: orderAssistantBlockParts(info, partsByMessage.get(row.id) ?? []) };
+  });
 }
 
 export async function messageWithParts(
@@ -272,8 +276,244 @@ export async function messageWithParts(
       `,
     )
     .all(input.messageID, input.sessionID) as unknown as PartRow[];
-  return {
-    info: decodeMessageRow(messageRow),
-    parts: partRows.map(decodePartRow),
+  const info = decodeMessageRow(messageRow);
+  return { info, parts: orderAssistantBlockParts(info, partRows.map(decodePartRow)) };
+}
+
+/**
+ * 有序 assistant 消息的块 part 按 blockIndex 稳定排序,消费方(V4 冷恢复、services、fork)拿到流顺序,
+ * 而不是写库顺序(只读工具在流中写库,reasoning/text 在流结束后写库)。
+ * 只在块 part 占用的位置之间重排;step-start、step-finish、file、截图等其他 part 位置不变。
+ * 旧消息保持物理顺序。见 apps/zcode-cli/docs/design/v2/model/assistant-block-order.md。
+ */
+function orderAssistantBlockParts(info: MessageInfo, parts: MessagePart[]): MessagePart[] {
+  if (info.role !== "assistant") return parts;
+  // 块 part 只筛一次,判定和排序共用;有块缺合法序号(旧消息、混合消息)时保持物理顺序。
+  const blockParts = sortByCompleteIndex(assistantBlockParts(parts), (part) => part.blockIndex);
+  if (!blockParts) return parts;
+  let next = 0;
+  return parts.map((part) => (isAssistantBlockPart(part) ? blockParts[next++]! : part));
+}
+
+const COPY_BATCH_SIZE = 128;
+const JSON_EDIT_BATCH_SIZE = 128;
+
+/** 正文留在 SQLite;仅将既有 fork 规则需要的元数据交给同步规划器。 */
+export function forkSourceMetadata(db: DatabaseSync, sessionID: SessionId): MessageWithParts[] {
+  const messages = db
+    .prepare(`
+    select id, session_id, json_remove(data, '$.summary.body', '$.summary.diffs', '$.system') as data
+    from message where session_id = ?
+    order by sequence is null, sequence, time_created, rowid
+  `)
+    .all(sessionID) as unknown as MessageRow[];
+  // 旧版隐藏提醒的选型判定仍读文本,不能用截断前缀改变既有语义。
+  const parts = db
+    .prepare(`
+    select p.id, p.message_id, p.session_id,
+      case when json_type(p.data, '$.state.attachments') = 'array' then
+        json_set(projected.data, '$.state.attachments', json((
+          select json_group_array(json_remove(value, '$.url'))
+          from json_each(p.data, '$.state.attachments')
+        ))) else projected.data end as data
+    from part p join (
+      select p0.id, json_remove(case when json_extract(m0.data, '$.role') = 'user'
+          and json_extract(m0.data, '$.semantics.kind') = 'system_reminder'
+          and json_extract(m0.data, '$.semantics.uiVisibility') = 'hidden'
+          then p0.data else json_remove(p0.data, '$.text') end,
+        '$.url', '$.state.input', '$.state.output', '$.state.raw', '$.state.error',
+        '$.prompt', '$.description', '$.files', '$.snapshot'
+      ) as data from part p0 join message m0 on m0.id = p0.message_id and m0.session_id = p0.session_id where p0.session_id = ?
+    ) projected on projected.id = p.id
+    where p.session_id = ?
+    order by p.message_id, p.sequence is null, p.sequence, p.time_created, p.id
+  `)
+    .all(sessionID, sessionID) as unknown as PartRow[];
+  const partsByMessage = new Map<string, MessagePart[]>();
+  for (const row of parts) {
+    const part = decodePartRow(row);
+    const list = partsByMessage.get(row.message_id) ?? [];
+    list.push(part);
+    partsByMessage.set(row.message_id, list);
+  }
+  return messages.map((row) => ({
+    info: decodeMessageRow(row),
+    parts: partsByMessage.get(row.id) ?? [],
+  }));
+}
+
+type JsonObject = Record<string, unknown>;
+interface Changes {
+  remove: string[];
+  set: string[];
+  values: unknown[];
+}
+
+function isObject(value: unknown): value is JsonObject {
+  return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+// 比较同一份轻量投影的克隆前后值,只改引用/可见性等真实差异。不能用 merge-patch:
+// 它会删除显式 null,也不能用全量 JSON 覆盖:那会丢失未读出的正文与旧版快照字段。
+function diffJson(before: unknown, after: unknown, path: string, changes: Changes): void {
+  if (before === after) return;
+  if (isObject(before) && isObject(after)) {
+    for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
+      diffJson(before[key], after[key], `${path}.${JSON.stringify(key)}`, changes);
+    }
+  } else if (Array.isArray(before) && Array.isArray(after) && before.length === after.length) {
+    // orderedMessageIds 可包含整个长对话。标量数组整体改写,避免每个 ID 占一个
+    // JSON 函数参数;附件对象仍逐字段改写,保留投影时省略的 URL/正文。
+    if (after.every((value) => value === null || typeof value !== "object")) {
+      if (after.some((value, index) => value !== before[index])) {
+        changes.set.push(path);
+        changes.values.push(after);
+      }
+      return;
+    }
+    before.forEach((value, index) => diffJson(value, after[index], `${path}[${index}]`, changes));
+  } else if (after === undefined) {
+    changes.remove.push(path);
+  } else {
+    changes.set.push(path);
+    changes.values.push(after);
+  }
+}
+
+interface CopyRow {
+  source: string;
+  id: string;
+  messageId?: string;
+  created: number;
+  updated: number;
+  sequence: number;
+  values: unknown[];
+}
+interface CopyGroup {
+  changes: Changes;
+  rows: CopyRow[];
+}
+
+function addCopy(
+  groups: Map<string, CopyGroup>,
+  before: object,
+  after: object,
+  row: Omit<CopyRow, "values">,
+): void {
+  const changes: Changes = { remove: [], set: [], values: [] };
+  const dataOnly = (value: object) => {
+    const { id: _id, sessionID: _sessionID, messageID: _messageID, ...data } = value as JsonObject;
+    return data;
   };
+  diffJson(dataOnly(before), dataOnly(after), "$", changes);
+  const key = JSON.stringify([changes.remove, changes.set]);
+  const group = groups.get(key) ?? { changes, rows: [] };
+  group.rows.push({ ...row, values: changes.values });
+  groups.set(key, group);
+}
+
+function insertCopies(
+  db: DatabaseSync,
+  table: "message" | "part",
+  groups: Map<string, CopyGroup>,
+  parent: SessionId,
+  child: SessionId,
+): void {
+  for (const { changes, rows } of groups.values()) {
+    let data = "source.data";
+    for (let offset = 0; offset < changes.remove.length; offset += JSON_EDIT_BATCH_SIZE) {
+      data = `json_remove(${data}, ${changes.remove
+        .slice(offset, offset + JSON_EDIT_BATCH_SIZE)
+        .map(() => "?")
+        .join(",")})`;
+    }
+    for (let offset = 0; offset < changes.set.length; offset += JSON_EDIT_BATCH_SIZE) {
+      data = `json_set(${data}, ${changes.set
+        .slice(offset, offset + JSON_EDIT_BATCH_SIZE)
+        .map((_, index) => `?, json(plan.value -> '$.values[${offset + index}]')`)
+        .join(",")})`;
+    }
+    // 普通 JOIN 会被 SQLite 排成 source 在外层,每批重复扫描整个父会话,退化为平方级。
+    // CROSS JOIN 固定 plan 在外层,每个复制项只按源记录主键查询一次。
+    const statement = db.prepare(`
+      insert into ${table} (id, session_id, ${table === "part" ? "message_id," : ""} time_created, time_updated, sequence, data)
+      select json_extract(plan.value, '$.id'), ?, ${table === "part" ? "json_extract(plan.value, '$.messageId')," : ""}
+        json_extract(plan.value, '$.created'), json_extract(plan.value, '$.updated'), json_extract(plan.value, '$.sequence'), ${data}
+      from json_each(?) plan cross join ${table} source on source.id = json_extract(plan.value, '$.source')
+      where source.session_id = ?
+    `);
+    for (let index = 0; index < rows.length; index += COPY_BATCH_SIZE) {
+      const batch = rows.slice(index, index + COPY_BATCH_SIZE);
+      const result = statement.run(
+        child,
+        ...changes.remove,
+        ...changes.set,
+        JSON.stringify(batch),
+        parent,
+      );
+      if (Number(result.changes) !== batch.length) throw new Error("Fork copy source missing");
+    }
+  }
+}
+
+/** 调用方持有 BEGIN IMMEDIATE;严格 INSERT 防止 ID 冲突把其他会话记录改绑到 child。 */
+export function copyForkMessages(
+  db: DatabaseSync,
+  bundle: ForkCommitBundle,
+  source: MessageWithParts[],
+): void {
+  const sources = new Map(source.map((message) => [String(message.info.id), message]));
+  const messageGroups = new Map<string, CopyGroup>();
+  const partGroups = new Map<string, CopyGroup>();
+  const fresh: { message: MessageWithParts; sequence: number }[] = [];
+  const now = Date.now();
+  bundle.messages.forEach((message, sequence) => {
+    const sourceId = bundle.copySources?.messages[message.info.id];
+    if (!sourceId) {
+      fresh.push({ message, sequence });
+      return;
+    }
+    const original = sources.get(sourceId);
+    if (!original) throw new Error("Fork message copy source is not parent-local");
+    addCopy(messageGroups, original.info, message.info, {
+      source: sourceId,
+      id: message.info.id,
+      sequence,
+      created: message.info.time.created,
+      updated:
+        message.info.role === "assistant"
+          ? (message.info.time.completed ?? now)
+          : message.info.time.created,
+    });
+    const originalParts = new Map(original.parts.map((part) => [String(part.id), part]));
+    message.parts.forEach((part, partSequence) => {
+      const partSourceId = bundle.copySources?.parts[part.id];
+      const originalPart = partSourceId && originalParts.get(partSourceId);
+      if (!originalPart) throw new Error("Fork part copy source is not message-local");
+      addCopy(partGroups, originalPart, part, {
+        source: partSourceId,
+        id: part.id,
+        messageId: part.messageID,
+        sequence: partSequence,
+        created: partCreatedAt(part, now),
+        updated: now,
+      });
+    });
+  });
+  insertCopies(db, "message", messageGroups, bundle.child.parentID!, bundle.child.id);
+  insertCopies(db, "part", partGroups, bundle.child.parentID!, bundle.child.id);
+  for (const { message, sequence } of fresh) {
+    // 新建的边界提示没有复制源;显式保留 bundle 顺序,不依赖分组 INSERT 的执行顺序。
+    if (db.prepare("select 1 from message where id = ?").get(message.info.id)) {
+      throw new Error("Fork new message ID already exists");
+    }
+    saveMessage(db, message.info);
+    db.prepare("update message set sequence = ? where id = ?").run(sequence, message.info.id);
+    for (const part of message.parts) {
+      if (db.prepare("select 1 from part where id = ?").get(part.id)) {
+        throw new Error("Fork new part ID already exists");
+      }
+      savePart(db, part);
+    }
+  }
 }

+ 4 - 1
apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/permission-full-access.ts

@@ -1,3 +1,4 @@
+import { executionStateSchema } from "@zcode/shared";
 import type { DatabaseSync } from "node:sqlite";
 import type { SessionStorePort } from "@zcode/contracts";
 import { saveSessionEntry } from "./session-entries.js";
@@ -8,6 +9,8 @@ export async function commitPermissionFullAccess(
   input: Parameters<NonNullable<SessionStorePort["commitPermissionFullAccess"]>>[0],
 ): Promise<void> {
   input.signal?.throwIfAborted();
+  const { mode } = executionStateSchema.parse(input.execution.data);
+  if (mode !== "yolo" && mode !== "guarded") throw new Error("Unsupported permission grant mode");
   if (
     input.execution.sessionID !== input.sessionID ||
     input.receipt.sessionID !== input.sessionID
@@ -39,7 +42,7 @@ export async function commitPermissionFullAccess(
       for (const key of ["intent", "conversationInputIntent"]) {
         const intent = payload[key];
         if (intent && typeof intent === "object" && !Array.isArray(intent)) {
-          payload[key] = { ...intent, mode: "yolo" };
+          payload[key] = { ...intent, mode };
         }
       }
       write.run(JSON.stringify(payload), Date.now(), id, input.sessionID);

+ 208 - 1
apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/sessions.ts

@@ -1,3 +1,4 @@
+import { createHash } from "node:crypto";
 import type { DatabaseSync, SQLInputValue } from "node:sqlite";
 import {
   SESSION_TASK_TYPES,
@@ -12,6 +13,8 @@ import {
   type SessionRevert,
   type UpdateSessionInput,
   type SessionTaskType,
+  type SessionDeletionSnapshot,
+  type SessionDeletionReference,
 } from "@zcode/contracts";
 import { decodeSessionRow } from "../codecs.js";
 import { encodeJson } from "../json.js";
@@ -258,7 +261,10 @@ export async function listSessions(
   db: DatabaseSync,
   input: ListSessionsInput = {},
 ): Promise<SessionInfo[]> {
-  const clauses: string[] = ["time_deleted is null"];
+  const clauses: string[] = [
+    "time_deleted is null",
+    "not exists(select 1 from session_purge where session_id=session.id)",
+  ];
   const values: SQLInputValue[] = [];
 
   if (input.projectID) {
@@ -437,3 +443,204 @@ function mustGetSession(db: DatabaseSync, sessionID: SessionId): SessionInfo {
   }
   return session;
 }
+
+/** 所有进程共享删除屏障。进程存在但状态不明时保守拒绝,不用超时猜它已经退出。 */
+export function inspectSessionDeletion(
+  db: DatabaseSync,
+  root: SessionId,
+  ownerId: string,
+): SessionDeletionSnapshot {
+  const receipt = db
+    .prepare(
+      "select session_id,retained_artifacts,state from session_purge where root_id=? order by session_id",
+    )
+    .all(root) as Array<{ session_id: SessionId; retained_artifacts: string; state: string }>;
+  const ids = receipt.length
+    ? receipt.map((row) => row.session_id)
+    : (listOwnedSessionTrees(db, [root]).get(root) ?? []);
+  const inside = new Set<string>(ids);
+  const forks: SessionDeletionSnapshot["forks"] = [];
+  if (ids.length)
+    for (const row of db
+      .prepare(
+        "select id as sessionId,title,parent_id from session where time_deleted is null order by id",
+      )
+      .iterate() as Iterable<{ sessionId: SessionId; title: string; parent_id: string | null }>) {
+      if (row.parent_id && inside.has(row.parent_id) && !inside.has(row.sessionId))
+        forks.push({ sessionId: row.sessionId, title: row.title });
+    }
+  const references = new Map<string, SessionDeletionReference>();
+  // 引用可能藏在旧分支、输入队列、工具结果或工作流元数据,不能只按 fork 谱系查。
+  const sources = [
+    ["part", "session_id", "data"],
+    ["message", "session_id", "data"],
+    ["session_input", "session_id", "payload"],
+    ["session_entry", "session_id", "data"],
+    ["session", "id", "revert"],
+    ["input_history", "session_id", "attachments"],
+  ] as const;
+  const queries = sources.map(
+    ([table, id, data]) =>
+      `select t.${id} as session_id,t.${data} as body,s.title from ${table} t join session s on s.id=t.${id} where s.time_deleted is null and instr(t.${data}, 'zcode-artifact://')>0`,
+  );
+  // 工作流 journal 里的产物不一定进入消息 part,必须沿 run 的会话归属检查。
+  for (const [table, owner, columns] of [
+    ["dwf_run", null, ["args_json", "result_json", "failure_json"]],
+    ["workflow_run", null, ["args_json", "stats_json", "failure_json"]],
+    ["dwf_node", "dwf_run", ["input_json", "result_json", "error_json"]],
+    ["dwf_event", "dwf_run", ["payload_json"]],
+    ["dwf_actor", "dwf_run", ["persona_json"]],
+    ["workflow_activity", "workflow_run", ["prompt", "opts_json", "result_json", "error_json"]],
+    ["workflow_event", "workflow_run", ["payload_json"]],
+  ] as const) {
+    const body = columns.map((column) => `coalesce(t.${column},'')`).join(" || ' ' || ");
+    queries.push(
+      `select s.id as session_id,${body} as body,s.title from ${table} t ${owner ? `join ${owner} r on r.id=t.run_id` : ""} join session s on s.id=${owner ? "r" : "t"}.parent_session_id where s.time_deleted is null and instr(${body},'zcode-artifact://')>0`,
+    );
+  }
+  for (const query of queries) {
+    const rows = db.prepare(query).iterate() as Iterable<{
+      session_id: SessionId;
+      body: string;
+      title: string;
+    }>;
+    for (const row of rows) {
+      if (inside.has(row.session_id)) continue;
+      for (const match of row.body.matchAll(/zcode-artifact:\/\/([^/"\\\s]+)\/([^"\\\s/?#]+)/g)) {
+        const sessionId = decodeURIComponent(match[1]!) as SessionId;
+        const artifactId = decodeURIComponent(match[2]!);
+        if (!inside.has(sessionId)) continue;
+        const key = `${sessionId}/${artifactId}`;
+        const entry = references.get(key) ?? { sessionId, artifactId, referrers: [] };
+        if (!entry.referrers.some((ref) => ref.sessionId === row.session_id))
+          entry.referrers.push({ sessionId: row.session_id, title: row.title });
+        references.set(key, entry);
+      }
+    }
+  }
+  if (receipt.length)
+    for (const row of receipt)
+      for (const artifactId of JSON.parse(row.retained_artifacts) as string[]) {
+        const key = `${row.session_id}/${artifactId}`;
+        if (!references.has(key))
+          references.set(key, { sessionId: row.session_id, artifactId, referrers: [] });
+      }
+  let foreignRuntime = false;
+  const localRuntimeIds: SessionId[] = [];
+  for (const row of db
+    .prepare("select session_id,owner_id,process_id from session_runtime_presence")
+    .all() as Array<{ session_id: string; owner_id: string; process_id: number }>) {
+    if (!inside.has(row.session_id)) continue;
+    if (row.owner_id === ownerId) {
+      localRuntimeIds.push(row.session_id as SessionId);
+      continue;
+    }
+    let alive = true;
+    try {
+      process.kill(row.process_id, 0);
+    } catch (error) {
+      alive = (error as NodeJS.ErrnoException).code !== "ESRCH";
+    }
+    if (alive) foreignRuntime = true;
+    else
+      db.prepare("delete from session_runtime_presence where session_id=? and owner_id=?").run(
+        row.session_id,
+        row.owner_id,
+      );
+  }
+  const pendingWork =
+    !receipt.length &&
+    ids.some((id) =>
+      Boolean(
+        db
+          .prepare("select 1 from session_input where session_id=? and status='admitted' limit 1")
+          .get(id) ||
+        db
+          .prepare("select 1 from session_target where session_id=? and status='active' limit 1")
+          .get(id),
+      ),
+    );
+  const orderedReferences = [...references.values()].sort((a, b) =>
+    `${a.sessionId}/${a.artifactId}`.localeCompare(`${b.sessionId}/${b.artifactId}`),
+  );
+  for (const ref of orderedReferences)
+    ref.referrers.sort((a, b) => a.sessionId.localeCompare(b.sessionId));
+  const facts = ids.map((id) =>
+    db.prepare("select id,time_updated,time_deleted from session where id=?").get(id),
+  );
+  const revision = createHash("sha256")
+    .update(JSON.stringify({ ids, facts, forks, references: orderedReferences, pendingWork }))
+    .digest("hex");
+  const workspace =
+    db
+      .prepare("select directory as path,workspace_id as identity from session where id=?")
+      .get(root) ??
+    db
+      .prepare(
+        "select workspace_path as path,workspace_identity as identity from session_purge where session_id=?",
+      )
+      .get(root);
+  return {
+    workspacePath: workspace?.path as string | undefined,
+    workspaceIdentity: (workspace?.identity ?? undefined) as string | undefined,
+    revision,
+    sessionIds: ids,
+    forks,
+    references: orderedReferences,
+    foreignRuntime,
+    localRuntimeIds,
+    pendingWork,
+    deleting: receipt.some((row) => row.state === "deleting"),
+    completed: receipt.length > 0 && receipt.every((row) => row.state === "deleted"),
+  };
+}
+
+export function beginSessionDeletion(
+  db: DatabaseSync,
+  root: SessionId,
+  ownerId: string,
+  revision: string,
+  operationId: string,
+  retained: Array<{ sessionId: SessionId; artifactId: string }>,
+): void {
+  db.exec("begin immediate");
+  try {
+    const snapshot = inspectSessionDeletion(db, root, ownerId);
+    if (snapshot.foreignRuntime || snapshot.pendingWork)
+      throw Object.assign(new Error("session-data.running"), { code: "running" });
+    if (!snapshot.deleting && !snapshot.completed) {
+      if (snapshot.revision !== revision || !snapshot.sessionIds.length)
+        throw Object.assign(new Error("session-data.changed"), { code: "changed" });
+      const insert = db.prepare(
+        "insert into session_purge(session_id,root_id,operation_id,retained_artifacts,workspace_path,workspace_identity,state) values(?,?,?,?,?,?,'deleting')",
+      );
+      for (const id of snapshot.sessionIds)
+        insert.run(
+          id,
+          root,
+          operationId,
+          JSON.stringify(
+            retained.filter((ref) => ref.sessionId === id).map((ref) => ref.artifactId),
+          ),
+          snapshot.workspacePath ?? "",
+          snapshot.workspaceIdentity ?? null,
+        );
+    }
+    db.exec("commit");
+  } catch (error) {
+    db.exec("rollback");
+    throw error;
+  }
+}
+
+export function completeSessionDeletion(db: DatabaseSync, root: SessionId): void {
+  // 文件已清理后才删除正文。凭据独立于 session,重启和旧 create/upsert 不能复活同一 ID。
+  const ids = db
+    .prepare("select session_id from session_purge where root_id=?")
+    .all(root) as Array<{ session_id: SessionId }>;
+  purgeSessions(
+    db,
+    ids.map((row) => row.session_id),
+  );
+  db.prepare("update session_purge set state='deleted' where root_id=?").run(root);
+}

+ 1 - 23
apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/usage.ts

@@ -14,9 +14,7 @@ import type {
 } from "@zcode/contracts";
 import { encodeJson } from "../json.js";
 
-const USAGE_RETENTION_DAYS = 30;
-const USAGE_RETENTION_MS = USAGE_RETENTION_DAYS * 24 * 60 * 60 * 1000;
-
+// 用量事实永久保留;查询时间范围只负责筛选,写入时不能清理历史统计。
 export async function recordModelUsage(db: DatabaseSync, input: ModelUsageRecord): Promise<void> {
   const computedTotalTokens =
     input.computedTotalTokens ??
@@ -160,7 +158,6 @@ export async function recordModelUsage(db: DatabaseSync, input: ModelUsageRecord
     encodeJson(input.rawUsage),
     encodeJson(input.providerMetadata),
   );
-  await pruneUsage(db);
 }
 
 export async function upsertTurnUsage(db: DatabaseSync, input: TurnUsageRecord): Promise<void> {
@@ -253,7 +250,6 @@ export async function upsertTurnUsage(db: DatabaseSync, input: TurnUsageRecord):
     input.errorType ?? null,
     input.errorCode ?? null,
   );
-  await pruneUsage(db);
 }
 
 export async function upsertToolUsage(db: DatabaseSync, input: ToolUsageRecord): Promise<void> {
@@ -329,24 +325,6 @@ export async function upsertToolUsage(db: DatabaseSync, input: ToolUsageRecord):
         error_message = coalesce(excluded.error_message, tool_usage.error_message)
       `,
   ).run(...toolUsageValues(input));
-  await pruneUsage(db);
-}
-
-export async function pruneUsage(
-  db: DatabaseSync,
-  input: { beforeTime?: number } = {},
-): Promise<void> {
-  const beforeTime = input.beforeTime ?? Date.now() - USAGE_RETENTION_MS;
-  db.exec("begin immediate");
-  try {
-    db.prepare("delete from model_usage where started_at < ?").run(beforeTime);
-    db.prepare("delete from turn_usage where started_at < ?").run(beforeTime);
-    db.prepare("delete from tool_usage where started_at < ?").run(beforeTime);
-    db.exec("commit");
-  } catch (error) {
-    db.exec("rollback");
-    throw error;
-  }
 }
 
 function toolUsageValues(input: ToolUsageRecord): SQLInputValue[] {

+ 359 - 0
apps/zcode-cli/packages/adapters/src/storage/session-store/schema.baseline.sql

@@ -207,6 +207,23 @@ CREATE TABLE session_input (
         time_updated integer not null
       );
 
+CREATE TABLE session_purge (
+        session_id text primary key,
+        root_id text not null,
+        operation_id text not null,
+        retained_artifacts text not null,
+        workspace_path text not null,
+        workspace_identity text,
+        state text not null check(state in ('deleting', 'deleted'))
+      );
+
+CREATE TABLE session_runtime_presence (
+        session_id text not null,
+        owner_id text not null,
+        process_id integer not null,
+        primary key(session_id, owner_id)
+      );
+
 CREATE TABLE "session_target" (
         session_id text primary key references session(id) on delete cascade,
         target_id text not null,
@@ -471,6 +488,8 @@ CREATE INDEX session_parent_idx on session(parent_id);
 
 CREATE INDEX session_project_idx on session(project_id);
 
+CREATE INDEX session_purge_root_idx on session_purge(root_id);
+
 CREATE INDEX session_task_link_activity_idx
         on session_task_link(activity_id);
 
@@ -546,3 +565,343 @@ CREATE TRIGGER part_sequence_autofill
         )
         where id = new.id;
       end;
+
+CREATE TRIGGER session_purge_child_guard before insert on session
+      when exists(select 1 from session_purge where session_id=new.parent_id)
+      begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_input_history_insert before insert on input_history
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_input_history_update before update on input_history
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_insert_guard before insert on session
+      when exists(select 1 from session_purge where session_id=new.id)
+      begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_link_insert before insert on session_task_link
+        when  exists(select 1 from session_purge where session_id=new.parent_session_id or session_id=new.child_session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_link_update before update on session_task_link
+        when (new.parent_session_id is not old.parent_session_id or new.child_session_id is not old.child_session_id) and new.parent_session_id is not null and exists(select 1 from session_purge where session_id=new.parent_session_id or session_id=new.child_session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_message_insert before insert on message
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_message_update before update on message
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_model_usage_insert before insert on model_usage
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_model_usage_update before update on model_usage
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_owner_dwf_run_insert before insert on dwf_run
+        when new.parent_session_id is not null and exists(select 1 from session_purge where session_id=new.parent_session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_owner_dwf_run_update before update on dwf_run
+        when new.parent_session_id is not null and exists(select 1 from session_purge where session_id=new.parent_session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_owner_workflow_run_insert before insert on workflow_run
+        when new.parent_session_id is not null and exists(select 1 from session_purge where session_id=new.parent_session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_owner_workflow_run_update before update on workflow_run
+        when new.parent_session_id is not null and exists(select 1 from session_purge where session_id=new.parent_session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_part_insert before insert on part
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_part_update before update on part
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_actor_persona_json_insert before insert on dwf_actor
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.persona_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_actor_persona_json_update before update of persona_json on dwf_actor
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.persona_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_event_payload_json_insert before insert on dwf_event
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.payload_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_event_payload_json_update before update of payload_json on dwf_event
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.payload_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_node_error_json_insert before insert on dwf_node
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.error_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_node_error_json_update before update of error_json on dwf_node
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.error_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_node_input_json_insert before insert on dwf_node
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.input_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_node_input_json_update before update of input_json on dwf_node
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.input_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_node_result_json_insert before insert on dwf_node
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.result_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_node_result_json_update before update of result_json on dwf_node
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.result_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_run_args_json_insert before insert on dwf_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.args_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_run_args_json_update before update of args_json on dwf_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.args_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_run_failure_json_insert before insert on dwf_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.failure_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_run_failure_json_update before update of failure_json on dwf_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.failure_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_run_result_json_insert before insert on dwf_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.result_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_dwf_run_result_json_update before update of result_json on dwf_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.result_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_input_history_attachments_insert before insert on input_history
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.attachments, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_input_history_attachments_update before update of attachments on input_history
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.attachments, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_message_data_insert before insert on message
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.data, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_message_data_update before update of data on message
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.data, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_part_data_insert before insert on part
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.data, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_part_data_update before update of data on part
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.data, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_session_entry_data_insert before insert on session_entry
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.data, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_session_entry_data_update before update of data on session_entry
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.data, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_session_input_payload_insert before insert on session_input
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.payload, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_session_input_payload_update before update of payload on session_input
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.payload, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_session_revert_insert before insert on session
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.revert, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_session_revert_update before update of revert on session
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.revert, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_activity_error_json_insert before insert on workflow_activity
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.error_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_activity_error_json_update before update of error_json on workflow_activity
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.error_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_activity_opts_json_insert before insert on workflow_activity
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.opts_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_activity_opts_json_update before update of opts_json on workflow_activity
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.opts_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_activity_prompt_insert before insert on workflow_activity
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.prompt, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_activity_prompt_update before update of prompt on workflow_activity
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.prompt, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_activity_result_json_insert before insert on workflow_activity
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.result_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_activity_result_json_update before update of result_json on workflow_activity
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.result_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_event_payload_json_insert before insert on workflow_event
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.payload_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_event_payload_json_update before update of payload_json on workflow_event
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.payload_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_run_args_json_insert before insert on workflow_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.args_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_run_args_json_update before update of args_json on workflow_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.args_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_run_failure_json_insert before insert on workflow_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.failure_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_run_failure_json_update before update of failure_json on workflow_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.failure_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_run_stats_json_insert before insert on workflow_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.stats_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_reference_workflow_run_stats_json_update before update of stats_json on workflow_run
+        when exists(select 1 from session_purge where state='deleting'
+          and instr(new.stats_json, 'zcode-artifact://' || session_id || '/')>0)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_runtime_guard before insert on session_runtime_presence
+      when exists(select 1 from session_purge where session_id=new.session_id)
+      begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_session_entry_insert before insert on session_entry
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_session_entry_update before update on session_entry
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_session_input_insert before insert on session_input
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_session_input_update before update on session_input
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_session_target_insert before insert on session_target
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_session_target_update before update on session_target
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_todo_insert before insert on todo
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_todo_update before update on todo
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_tool_usage_insert before insert on tool_usage
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_tool_usage_update before update on tool_usage
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_turn_usage_insert before insert on turn_usage
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_turn_usage_update before update on turn_usage
+        when exists(select 1 from session_purge where session_id=new.session_id)
+        begin select raise(abort, 'session-data.deleting'); end;
+
+CREATE TRIGGER session_purge_update_guard before update on session
+      when exists(select 1 from session_purge where session_id=new.id or (new.parent_id is not old.parent_id and session_id=new.parent_id))
+      begin select raise(abort, 'session-data.deleting'); end;

+ 150 - 63
apps/zcode-cli/packages/adapters/src/storage/session-store/sqlite-session-store.ts

@@ -1,3 +1,4 @@
+import { randomUUID } from "node:crypto";
 import type { MigrationResult } from "@zcode/shared/sqlite-migrations";
 import { mkdir } from "node:fs/promises";
 import { dirname } from "node:path";
@@ -15,6 +16,7 @@ import type {
   FileDiff,
   MessageCommitBundle,
   ForkCommitBundle,
+  ForkFromSourceInput,
   ForkChildSessionMetadata,
   GoalStatus,
   InputHistoryAttachment,
@@ -253,7 +255,10 @@ export class SqliteSessionStore
     this.forkCommitFaultAt = options.forkCommitFaultAt;
   }
 
-  static async open(options: SqliteSessionStoreOptions = {}, migrationOptions?: AsyncSqliteMigrationOptions): Promise<SqliteSessionStore> {
+  static async open(
+    options: SqliteSessionStoreOptions = {},
+    migrationOptions?: AsyncSqliteMigrationOptions,
+  ): Promise<SqliteSessionStore> {
     const dbPath = options.dbPath ?? getDefaultSessionDbPath();
     const startupLockTimeoutMs =
       options.startupLockTimeoutMs ?? DEFAULT_SQLITE_STARTUP_LOCK_TIMEOUT_MS;
@@ -273,23 +278,77 @@ export class SqliteSessionStore
       });
     }
     try {
-      const migration = await runSqliteSessionMigrationsAsync(db, dbPath, migrationOptions ?? { lockWaitTimeoutMs: startupLockTimeoutMs });
+      const migration = await runSqliteSessionMigrationsAsync(
+        db,
+        dbPath,
+        migrationOptions ?? { lockWaitTimeoutMs: startupLockTimeoutMs },
+      );
       return new SqliteSessionStore(db, dbPath, options, migration);
     } catch (error) {
-      try { db.close(); } catch { /* 关闭失败不能覆盖迁移错误。 */ }
+      try {
+        db.close();
+      } catch {
+        /* 关闭失败不能覆盖迁移错误。 */
+      }
       throw error;
     }
   }
 
-  static async openStartup(options: SqliteSessionStoreOptions = {}, migrationOptions: AsyncSqliteMigrationOptions = {}) {
+  static async openStartup(
+    options: SqliteSessionStoreOptions = {},
+    migrationOptions: AsyncSqliteMigrationOptions = {},
+  ) {
     return SqliteSessionStore.open(options, migrationOptions);
   }
 
+  private readonly runtimeOwnerId = `${process.pid}:${randomUUID()}`;
+
+  async assertSessionNotDeleting(id: SessionId): Promise<void> {
+    if (this.db.prepare("select 1 from session_purge where session_id=?").get(id))
+      throw new Error("session-data.deleting");
+  }
+  async registerSessionRuntime(id: SessionId): Promise<void> {
+    this.db
+      .prepare(
+        "insert or ignore into session_runtime_presence(session_id,owner_id,process_id) values(?,?,?)",
+      )
+      .run(id, this.runtimeOwnerId, process.pid);
+  }
+  async unregisterSessionRuntime(id: SessionId): Promise<void> {
+    this.db
+      .prepare("delete from session_runtime_presence where session_id=? and owner_id=?")
+      .run(id, this.runtimeOwnerId);
+  }
+  async inspectSessionDeletion(id: SessionId) {
+    return sessionRepository.inspectSessionDeletion(this.db, id, this.runtimeOwnerId);
+  }
+  async beginSessionDeletion(
+    id: SessionId,
+    revision: string,
+    operationId: string,
+    retained: Array<{ sessionId: SessionId; artifactId: string }>,
+  ): Promise<void> {
+    sessionRepository.beginSessionDeletion(
+      this.db,
+      id,
+      this.runtimeOwnerId,
+      revision,
+      operationId,
+      retained,
+    );
+  }
+  async completeSessionDeletion(id: SessionId): Promise<void> {
+    sessionRepository.completeSessionDeletion(this.db, id);
+  }
+
   getDatabasePath(): string {
     return this.dbPath;
   }
 
   close(): void {
+    this.db
+      .prepare("delete from session_runtime_presence where owner_id=?")
+      .run(this.runtimeOwnerId);
     this.db.close();
   }
 
@@ -377,10 +436,44 @@ export class SqliteSessionStore
     }
   }
 
+  async commitForkFromSource(input: ForkFromSourceInput): Promise<SessionInfo> {
+    this.throwBeforeWrite();
+    this.db.exec("begin immediate");
+    try {
+      const session = sessionRepository.getSession(this.db, input.sessionID);
+      if (!session) throw new Error(`Session not found: ${input.sessionID}`);
+      const source = messageRepository.forkSourceMetadata(this.db, input.sessionID);
+      // 保留比较基准,不能让规划器修改输入后把变更误判成“未改动”。正文不进入此快照。
+      const bundle = input.build({ session, messages: structuredClone(source) });
+      if (bundle && typeof (bundle as unknown as { then?: unknown }).then === "function") {
+        throw new Error("Fork source builder must be synchronous");
+      }
+      if (bundle.child.parentID !== input.sessionID) throw new Error("Fork source parent mismatch");
+      const child = this.writeForkBundle(bundle, source);
+      this.db.exec("commit");
+      return child;
+    } catch (error) {
+      this.db.exec("rollback");
+      throw error;
+    }
+  }
+
   async commitForkBundle(bundle: ForkCommitBundle): Promise<SessionInfo> {
     // DatabaseSync 事务属于整个连接:BEGIN 到提交/回滚之间不能 await,
     // 否则其他会话的成功写入会被 fork 回滚误删,重启后无法再打开。
     this.throwBeforeWrite();
+    this.db.exec("begin immediate");
+    try {
+      const child = this.writeForkBundle(bundle);
+      this.db.exec("commit");
+      return child;
+    } catch (error) {
+      this.db.exec("rollback");
+      throw error;
+    }
+  }
+
+  private writeForkBundle(bundle: ForkCommitBundle, source?: MessageWithParts[]): SessionInfo {
     const { child, commandFact, initialInput } = bundle;
     if (
       !child.parentID ||
@@ -391,27 +484,27 @@ export class SqliteSessionStore
       throw new Error("Fork commit bundle identity is invalid");
     }
     const entryId = `v4_command_fact:child:${commandFact.parentSessionId}:${commandFact.sourceCommandId}`;
-    this.db.exec("begin immediate");
-    try {
-      const existing = sessionEntryRepository
-        .sessionEntries(this.db, {
-          sessionID: child.parentID,
-          type: "v4/command_fact",
-        })
-        .find((entry) => entry.id === entryId);
-      if (existing) {
-        const existingChildId = forkChildSessionId(existing);
-        const existingChild = existingChildId
-          ? sessionRepository.getSession(this.db, existingChildId)
-          : null;
-        if (!existingChild) throw new Error(`Fork bundle command fact is corrupt: ${entryId}`);
-        this.db.exec("commit");
-        return existingChild;
-      }
+    const existing = sessionEntryRepository
+      .sessionEntries(this.db, {
+        sessionID: child.parentID,
+        type: "v4/command_fact",
+      })
+      .find((entry) => entry.id === entryId);
+    if (existing) {
+      const existingChildId = forkChildSessionId(existing);
+      const existingChild = existingChildId
+        ? sessionRepository.getSession(this.db, existingChildId)
+        : null;
+      if (!existingChild) throw new Error(`Fork bundle command fact is corrupt: ${entryId}`);
+      return existingChild;
+    }
 
-      assertForkBundleChildLocal(bundle);
-      const persistedChild = sessionRepository.createSession(this.db, child);
-      this.maybeThrowForkCommitFault("afterChild");
+    assertForkBundleChildLocal(bundle);
+    const persistedChild = sessionRepository.createSession(this.db, child);
+    this.maybeThrowForkCommitFault("afterChild");
+    if (source) {
+      messageRepository.copyForkMessages(this.db, bundle, source);
+    } else {
       for (const message of bundle.messages) {
         const messageSource = bundle.copySources?.messages[message.info.id];
         messageRepository.saveMessage(
@@ -428,43 +521,39 @@ export class SqliteSessionStore
           );
         }
       }
-      this.maybeThrowForkCommitFault("afterMessages");
-      if (bundle.goal) {
-        cloneSessionTargetForFork(this.db, {
-          source: bundle.goal.source,
-          sessionID: child.id,
-          status: bundle.goal.status,
-        });
-      }
-      this.maybeThrowForkCommitFault("afterGoal");
-      for (const entry of bundle.entries) {
-        sessionEntryRepository.saveSessionEntry(this.db, entry);
-      }
-      this.maybeThrowForkCommitFault("afterEntries");
-      if (initialInput) {
-        sessionInputRepository.saveSessionInput(this.db, initialInput);
-      }
-      this.maybeThrowForkCommitFault("afterInput");
-      const now = Date.now();
-      sessionEntryRepository.saveSessionEntry(this.db, {
-        id: entryId,
-        sessionID: child.parentID,
-        type: "v4/command_fact",
-        time: { created: now, updated: now },
-        data: {
-          source: "child",
-          ack: commandFact.ack,
-          metadata: commandFact.metadata,
-        },
+    }
+    this.maybeThrowForkCommitFault("afterMessages");
+    if (bundle.goal) {
+      cloneSessionTargetForFork(this.db, {
+        source: bundle.goal.source,
+        sessionID: child.id,
+        status: bundle.goal.status,
       });
-      this.maybeThrowForkCommitFault("afterCommandFact");
-      this.maybeThrowForkCommitFault("beforeCommit");
-      this.db.exec("commit");
-      return persistedChild;
-    } catch (error) {
-      this.db.exec("rollback");
-      throw error;
     }
+    this.maybeThrowForkCommitFault("afterGoal");
+    for (const entry of bundle.entries) {
+      sessionEntryRepository.saveSessionEntry(this.db, entry);
+    }
+    this.maybeThrowForkCommitFault("afterEntries");
+    if (initialInput) {
+      sessionInputRepository.saveSessionInput(this.db, initialInput);
+    }
+    this.maybeThrowForkCommitFault("afterInput");
+    const now = Date.now();
+    sessionEntryRepository.saveSessionEntry(this.db, {
+      id: entryId,
+      sessionID: child.parentID,
+      type: "v4/command_fact",
+      time: { created: now, updated: now },
+      data: {
+        source: "child",
+        ack: commandFact.ack,
+        metadata: commandFact.metadata,
+      },
+    });
+    this.maybeThrowForkCommitFault("afterCommandFact");
+    this.maybeThrowForkCommitFault("beforeCommit");
+    return persistedChild;
   }
 
   async commitMessageBundle(bundle: MessageCommitBundle): Promise<void> {
@@ -628,6 +717,8 @@ export class SqliteSessionStore
   }
 
   async getSession(sessionID: SessionId): Promise<SessionInfo | null> {
+    if (this.db.prepare("select 1 from session_purge where session_id=?").get(sessionID))
+      return null;
     return sessionRepository.getSession(this.db, sessionID);
   }
 
@@ -893,10 +984,6 @@ export class SqliteSessionStore
     return usageRepository.upsertToolUsage(this.db, input);
   }
 
-  async pruneUsage(input?: { beforeTime?: number }): Promise<void> {
-    return usageRepository.pruneUsage(this.db, input);
-  }
-
   async queryAppUsage(input: AppUsageQueryInput): Promise<AppUsageQueryResult> {
     return usageRepository.queryAppUsage(this.db, input);
   }

Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff