Ver código fonte

chore: sync ZCode source

Source-Commit: 1f4d7f01beb143df0ec1224f0ed4236f42d0fd13
Source-Sync: zcode-open-source-v1
ZCode Source Sync Bot 1 mês atrás
pai
commit
0a1fc56d27
100 arquivos alterados com 4773 adições e 2346 exclusões
  1. 9 1
      .agents/skills/architecture-governance/SKILL.md
  2. 6 0
      .agents/skills/architecture-governance/references/policy-schema.md
  3. 5 1
      .agents/skills/architecture-governance/references/rule-catalog.md
  4. 3 0
      .agents/skills/architecture-governance/references/troubleshooting.md
  5. 5 5
      .agents/skills/feature-boundary-planner/references/zcode-domain-cross-products.md
  6. 778 55
      .agents/skills/feature-boundary-planner/references/zcode-feature-graph.yaml
  7. 95 0
      .agents/skills/session-management/SKILL.md
  8. 9 0
      .gitattributes
  9. 2 0
      .gitignore
  10. 4 0
      .oxfmtrc.json
  11. 32 1
      .oxlintrc.json
  12. 15 12
      AGENTS.md
  13. 11 7
      CONTEXT.md
  14. 46 22
      DESIGN.md
  15. 3 0
      README.en.md
  16. 3 2
      README.md
  17. 2 0
      THIRD-PARTY-NOTICES.md
  18. 32 30
      apps/dev-docs/test/capabilityMapComplexity.test.ts
  19. 0 66
      apps/dev-docs/test/capabilityMapCurrentFeatures.test.ts
  20. 0 36
      apps/dev-docs/test/capabilityMapGeometry.test.ts
  21. 0 93
      apps/dev-docs/test/capabilityMapOfficeComputerUse.test.ts
  22. 0 30
      apps/dev-docs/test/featureBoundaryGraph.test.ts
  23. 3 0
      apps/zcode-cli/.gitignore
  24. 1 1
      apps/zcode-cli/AGENTS.md
  25. 16 317
      apps/zcode-cli/README.md
  26. 4 0
      apps/zcode-cli/docs/design/v2/commands.md
  27. 3 0
      apps/zcode-cli/docs/design/v2/ink-tui-renderer.md
  28. 10 1
      apps/zcode-cli/docs/design/v2/local-setting-migrations.md
  29. 1 0
      apps/zcode-cli/docs/design/v2/loop/turn-steering.md
  30. 30 0
      apps/zcode-cli/docs/design/v2/message-attachments.md
  31. 79 26
      apps/zcode-cli/docs/design/v2/model/provider-endpoint-routing.md
  32. 34 0
      apps/zcode-cli/docs/design/v2/model/stream-error-retry.md
  33. 4 2
      apps/zcode-cli/docs/design/v2/multi-workspace.md
  34. 13 0
      apps/zcode-cli/docs/design/v2/plugin-compat.md
  35. 199 3
      apps/zcode-cli/docs/design/v2/tool/00-tool-change-chain.md
  36. 9 0
      apps/zcode-cli/docs/design/v2/tool/01-read.md
  37. 736 0
      apps/zcode-cli/docs/design/v2/tool/19-tool-search.md
  38. 1 0
      apps/zcode-cli/docs/design/v2/tool/README.md
  39. 8 3
      apps/zcode-cli/docs/design/v2/tui-model-selection.md
  40. 4 0
      apps/zcode-cli/docs/design/v2/usage-observability.md
  41. 30 0
      apps/zcode-cli/docs/plan/trajectory/model-io-to-anthropic-trajectory-tool.md
  42. 71 0
      apps/zcode-cli/docs/usage/01-quickstart.md
  43. 61 0
      apps/zcode-cli/docs/usage/02-cli-reference.md
  44. 96 0
      apps/zcode-cli/docs/usage/03-config.md
  45. 36 0
      apps/zcode-cli/docs/usage/04-tools.md
  46. 35 0
      apps/zcode-cli/docs/usage/05-permissions.md
  47. 34 0
      apps/zcode-cli/docs/usage/06-sessions.md
  48. 38 0
      apps/zcode-cli/docs/usage/07-mcp.md
  49. 42 0
      apps/zcode-cli/docs/usage/08-skills.md
  50. 84 0
      apps/zcode-cli/docs/usage/09-hooks.md
  51. 72 0
      apps/zcode-cli/docs/usage/10-plugins.md
  52. 34 0
      apps/zcode-cli/docs/usage/11-memory.md
  53. 31 0
      apps/zcode-cli/docs/usage/12-troubleshooting.md
  54. 101 0
      apps/zcode-cli/docs/usage/13-automation.md
  55. 33 0
      apps/zcode-cli/docs/usage/README.md
  56. 4 3
      apps/zcode-cli/package.json
  57. 15 4
      apps/zcode-cli/packages/adapters/src/commands/index.ts
  58. 14 1
      apps/zcode-cli/packages/adapters/src/commands/roots.ts
  59. 4 10
      apps/zcode-cli/packages/adapters/src/config/schema.ts
  60. 25 1
      apps/zcode-cli/packages/adapters/src/fs/text-metadata.ts
  61. 29 5
      apps/zcode-cli/packages/adapters/src/fs/text-range-reader.ts
  62. 7 0
      apps/zcode-cli/packages/adapters/src/mcp/descriptor.ts
  63. 12 0
      apps/zcode-cli/packages/adapters/src/mcp/index.ts
  64. 18 0
      apps/zcode-cli/packages/adapters/src/mcp/pool.ts
  65. 4 0
      apps/zcode-cli/packages/adapters/src/model/errors.ts
  66. 5 0
      apps/zcode-cli/packages/adapters/src/model/model.ts
  67. 10 10
      apps/zcode-cli/packages/adapters/src/model/provider-endpoint-routing-fetch.ts
  68. 1 0
      apps/zcode-cli/packages/adapters/src/model/provider-endpoint-routing-options.ts
  69. 70 2
      apps/zcode-cli/packages/adapters/src/model/runner-diagnostics.ts
  70. 17 0
      apps/zcode-cli/packages/adapters/src/model/runner-generate.ts
  71. 7 2
      apps/zcode-cli/packages/adapters/src/model/runner-options.ts
  72. 16 0
      apps/zcode-cli/packages/adapters/src/model/runner-stream.ts
  73. 8 0
      apps/zcode-cli/packages/adapters/src/model/runner.ts
  74. 1 0
      apps/zcode-cli/packages/adapters/src/model/tool-result-media-projection.ts
  75. 30 0
      apps/zcode-cli/packages/adapters/src/model/tool-search.ts
  76. 7 2
      apps/zcode-cli/packages/adapters/src/model/tool-transform.ts
  77. 38 3
      apps/zcode-cli/packages/adapters/src/model/transform.ts
  78. 3 0
      apps/zcode-cli/packages/adapters/src/plugins/marketplace.ts
  79. 13 14
      apps/zcode-cli/packages/adapters/src/plugins/mcp.ts
  80. 2 4
      apps/zcode-cli/packages/adapters/src/skills/index.ts
  81. 14 1
      apps/zcode-cli/packages/adapters/src/skills/roots.ts
  82. 2 1
      apps/zcode-cli/packages/adapters/src/storage/session-store/codecs.ts
  83. 70 173
      apps/zcode-cli/packages/adapters/src/storage/session-store/migration-runner.ts
  84. 70 13
      apps/zcode-cli/packages/adapters/src/storage/session-store/migrations.ts
  85. 1 11
      apps/zcode-cli/packages/adapters/src/storage/session-store/paths.ts
  86. 82 110
      apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/sessions.ts
  87. 2 5
      apps/zcode-cli/packages/adapters/src/storage/session-store/rows.ts
  88. 548 0
      apps/zcode-cli/packages/adapters/src/storage/session-store/schema.baseline.sql
  89. 42 47
      apps/zcode-cli/packages/adapters/src/storage/session-store/sqlite-session-store.ts
  90. 30 17
      apps/zcode-cli/packages/adapters/tests/async-migration-startup.test.ts
  91. 315 0
      apps/zcode-cli/packages/adapters/tests/attachment-resume-wire.test.ts
  92. 3 1
      apps/zcode-cli/packages/adapters/tests/auth.test.ts
  93. 14 3
      apps/zcode-cli/packages/adapters/tests/builtin-mcs-search-wire.test.ts
  94. 29 0
      apps/zcode-cli/packages/adapters/tests/commands.test.ts
  95. 40 1005
      apps/zcode-cli/packages/adapters/tests/config.test.ts
  96. 6 0
      apps/zcode-cli/packages/adapters/tests/connectivity-probe-wire.test.ts
  97. 116 149
      apps/zcode-cli/packages/adapters/tests/dwf-journal-store.test.ts
  98. 16 16
      apps/zcode-cli/packages/adapters/tests/empty-tool-name-projection.test.ts
  99. 0 9
      apps/zcode-cli/packages/adapters/tests/env-model-config.test.ts
  100. 0 10
      apps/zcode-cli/packages/adapters/tests/exec.test.ts

+ 9 - 1
.agents/skills/architecture-governance/SKILL.md

@@ -15,7 +15,7 @@ Use this skill before editing code in the ZCode repository. It is a design guide
 4. For changes to mutable state, asynchronous behavior, or module boundaries, make the relevant design decisions before coding:
 4. For changes to mutable state, asynchronous behavior, or module boundaries, make the relevant design decisions before coding:
    - **One owner:** name the single component that owns each piece of mutable state. Other layers read through its contract and send commands; they do not keep a second accepted queue, cache, or derived truth.
    - **One owner:** name the single component that owns each piece of mutable state. Other layers read through its contract and send commands; they do not keep a second accepted queue, cache, or derived truth.
    - **One path:** reuse an existing command, service, hook, adapter, or contract when it already expresses the behavior. Do not create a parallel helper for the same responsibility.
    - **One path:** reuse an existing command, service, hook, adapter, or contract when it already expresses the behavior. Do not create a parallel helper for the same responsibility.
-   - **Explicit boundaries:** choose the layer for every new file and the public contract for every cross-module edge. Keep `ui → hooks/services → app → domain → adapters` and keep IO out of domain.
+   - **Explicit boundaries:** choose the layer for every new file and the public contract for every cross-module edge. Layers from low to high are `contract < domain < app < adapters < ui`; a file may import only its own layer or lower ones through their public surface. `domain` is pure (no IO, no `await` on the world), `app` decides side effects through ports, `adapters` executes them, `ui` depends only on this module's `contract.ts`. Quick test: needs `await`? not domain. Knows it is sqlite / MessagePort / a timer? adapters.
    - **Explicit time:** for asynchronous or remote behavior, write the event order, owner/lease, idempotency key, stale-result rule, replay/resume boundary, and desktop versus mobile delivery kind before implementation.
    - **Explicit time:** for asynchronous or remote behavior, write the event order, owner/lease, idempotency key, stale-result rule, replay/resume boundary, and desktop versus mobile delivery kind before implementation.
    - **Bounded context:** use the relevant contracts, specs, and tests. A generated reading package helps when dependencies are unclear; do not require a whole-module reading pass for every local edit.
    - **Bounded context:** use the relevant contracts, specs, and tests. A generated reading package helps when dependencies are unclear; do not require a whole-module reading pass for every local edit.
 5. If the change alters a public contract, ownership, or allowed dependency, record that decision in the relevant spec/contract before implementation. Editing files in two modules alone does not require a new document. Use the root task boundary for when to consult the user; ordinary authorized implementation choices proceed autonomously.
 5. If the change alters a public contract, ownership, or allowed dependency, record that decision in the relevant spec/contract before implementation. Editing files in two modules alone does not require a new document. Use the root task boundary for when to consult the user; ordinary authorized implementation choices proceed autonomously.
@@ -42,6 +42,14 @@ mobile: replayable ─ snapshot + gap repair ┘
 
 
 The executable policy is `architecture-policy.yaml`; keep its detailed rule definitions there. Check the actual managed-module coverage before claiming the gate verifies a boundary: a passing result does not prove unconfigured modules or runtime semantics are correct. Use `pnpm architecture:baseline:update` only when a reviewed change intentionally changes the accepted legacy baseline. CI never refreshes baseline automatically.
 The executable policy is `architecture-policy.yaml`; keep its detailed rule definitions there. Check the actual managed-module coverage before claiming the gate verifies a boundary: a passing result does not prove unconfigured modules or runtime semantics are correct. Use `pnpm architecture:baseline:update` only when a reviewed change intentionally changes the accepted legacy baseline. CI never refreshes baseline automatically.
 
 
+Every new source file under `packages/` or `apps/` must belong to a managed module (rule `unmanaged-new-file`). When the change needs a directory that is not managed yet, register it first:
+
+```text
+pnpm architecture:adopt <module-id> --root <dir> [--root <dir2>] --layer <domain|app|adapters|ui> [--owner <group>]
+```
+
+`adopt` infers `requires` from the real imports, scaffolds the five artifacts if missing, and registers the module in `architecture-policy.yaml` without touching existing comments. Fill `contract.ts` and `CONTRACT.md` before adding behavior; keep the module's public surface to one intent per method.
+
 For a new managed module, provide `module.ts`, `contract.ts`, `contract.example.ts`, `contract.test.ts`, and a short `CONTRACT.md`. Keep runtime and persistence details behind the contract. Prefer typed service calls for one-to-one interactions, commands for state changes, and typed events for broadcast facts.
 For a new managed module, provide `module.ts`, `contract.ts`, `contract.example.ts`, `contract.test.ts`, and a short `CONTRACT.md`. Keep runtime and persistence details behind the contract. Prefer typed service calls for one-to-one interactions, commands for state changes, and typed events for broadcast facts.
 
 
 See [policy-schema.md](references/policy-schema.md), [module-contract.md](references/module-contract.md), and [rule-catalog.md](references/rule-catalog.md) when the change needs their detailed guidance. The [golden-module](references/golden-module) fixture is the smallest compliant example.
 See [policy-schema.md](references/policy-schema.md), [module-contract.md](references/module-contract.md), and [rule-catalog.md](references/rule-catalog.md) when the change needs their detailed guidance. The [golden-module](references/golden-module) fixture is the smallest compliant example.

+ 6 - 0
.agents/skills/architecture-governance/references/policy-schema.md

@@ -4,4 +4,10 @@
 
 
 Each module has an `id`, one or more `roots`, optional `managed: true`, `requires`, `provides`, `publicEntrypoints`, and an optional `owner`. Existing modules may remain unmanaged while they are in baseline migration.
 Each module has an `id`, one or more `roots`, optional `managed: true`, `requires`, `provides`, `publicEntrypoints`, and an optional `owner`. Existing modules may remain unmanaged while they are in baseline migration.
 
 
+Global keys: `maxFileLines`, `maxContractLines`, `maxPublicMethods`, `forbidCycles`, `forbidDeepImports`, `managedOnly`, `newFilesRequireManagedModule` (default true), `newFileScopes` (default `[packages, apps]`) and `newFilesEnforcedSince` (date; tracked files first added before it are not subject to `unmanaged-new-file`, untracked files always are). Canonical layer names are `contract`, `domain`, `app`, `adapters`, `ui`; `layerOrder` lists them from lowest to highest and a layer may only import lower layers.
+
 The policy owns path and layer topology. A module's `module.ts` owns its local dependency declaration. Do not add a second hand-maintained dependency graph.
 The policy owns path and layer topology. A module's `module.ts` owns its local dependency declaration. Do not add a second hand-maintained dependency graph.
+
+`global.acceptedUpstreamCommits` optionally records reviewed upstream admissions as `{ commit, previousHead, reason }`. Both hashes must be full commit SHAs already merged into HEAD. Only paths introduced by that upstream relative to `previousHead`, with identical Git content and modes in both index and working tree, are exempt from `unmanaged-new-file`. Local additions, edits, renames, untracked files and later edits of previously admitted files remain subject to module registration. Other architecture rules and the real push/CI diff scope are unchanged. See `docs/architecture/architecture-governance.md` for the admission contract.
+
+`global.acceptedUpstreamSnapshot` optionally points to a generated repository-relative JSON manifest for a separately exported Git history. It is mutually exclusive with nonempty `acceptedUpstreamCommits`. The manifest records public source paths, fixed Git blob IDs and modes, introduced paths, and historical source snapshots from before the enforcement date; both index and working tree must still match. Historical snapshots only preserve the original date scope and do not admit lint diagnostics. It does not admit changed content or waive other rules. See `docs/testing/opensource-export-validation.md` for export generation and regression requirements.

+ 5 - 1
.agents/skills/architecture-governance/references/rule-catalog.md

@@ -10,8 +10,12 @@
 | `max-public-methods` | A contract exposes too many methods | Split the capability or introduce a narrower read/write contract |
 | `max-public-methods` | A contract exposes too many methods | Split the capability or introduce a narrower read/write contract |
 | `layer-direction` | A layer imports a higher implementation layer | Depend on a lower layer port or move the integration owner |
 | `layer-direction` | A layer imports a higher implementation layer | Depend on a lower layer port or move the integration owner |
 | `domain-io` | Domain code imports process, network, filesystem, or timer APIs | Move IO to an adapter and pass a typed port into the domain |
 | `domain-io` | Domain code imports process, network, filesystem, or timer APIs | Move IO to an adapter and pass a typed port into the domain |
-| `ui-implementation-import` | UI imports a repository, runtime, or service implementation | Call a UI hook backed by the service contract |
+| `ui-implementation-import` | A file in a `ui` layer imports a repository, runtime, or service implementation | Depend on the module port / read model exposed by `contract.ts` |
 | `missing-module-artifact` | A managed module lacks its manifest or contract fixtures | Add the required module contract, example, test, and CONTRACT.md |
 | `missing-module-artifact` | A managed module lacks its manifest or contract fixtures | Add the required module contract, example, test, and CONTRACT.md |
 | `disable-count` | Managed code adds a lint suppression | Fix the underlying violation or add a reviewed expiring exception |
 | `disable-count` | Managed code adds a lint suppression | Fix the underlying violation or add a reviewed expiring exception |
+| `unmanaged-new-file` | A newly added source file under `packages/` or `apps/` is not inside a managed module | Put it in a managed module, or run `pnpm architecture:adopt <id> --root <dir>` to register its directory (tests, `.d.ts` and test directories are exempt) |
+| `manifest-policy-mismatch` | `module.ts` `requires` disagrees with `architecture-policy.yaml` or names an unknown module | Update both declarations in the same change; the policy owns topology, the manifest owns the local declaration |
 
 
 Existing violations are suppressible only through `.architecture-baseline.json`; new violations remain blocking.
 Existing violations are suppressible only through `.architecture-baseline.json`; new violations remain blocking.
+
+Import edges are resolved the way Node and TypeScript resolve them: relative paths, `package.json` `imports` (`#src/*`), `tsconfig.json` `paths` (`@/*`), and workspace package names with `exports` (conditional exports and `dist/` targets map back to `src/`). `--changed` compares against a real base (explicit `--base`, CI merge-request variables, pre-push stdin, upstream, then the default branch merge-base), so committed changes are checked in CI and pre-push, not only the dirty working tree.

+ 3 - 0
.agents/skills/architecture-governance/references/troubleshooting.md

@@ -3,4 +3,7 @@
 - `module-dependency`: import the target module's public contract, or add the dependency to `module.ts` and policy after confirming the integration owner.
 - `module-dependency`: import the target module's public contract, or add the dependency to `module.ts` and policy after confirming the integration owner.
 - `deep-import`: replace an internal path with the target module's declared public entrypoint.
 - `deep-import`: replace an internal path with the target module's declared public entrypoint.
 - `cycle`: move the shared type into a contract or create an application/integration owner; do not silence the cycle.
 - `cycle`: move the shared type into a contract or create an application/integration owner; do not silence the cycle.
+- `unmanaged-new-file`: the file is new relative to the diff base and sits in a legacy root. Either move it into an existing managed module or register its directory with `pnpm architecture:adopt <id> --root <dir> --layer <domain|app|adapters|ui>`; adopt scaffolds the five artifacts and infers `requires` from real imports.
+- `manifest-policy-mismatch`: edit `module.ts` and `architecture-policy.yaml` together; unknown ids usually mean the dependency has not been registered yet.
+- unexpected base: run `pnpm architecture:check -- --changed --base <sha>` to pin the comparison; the report prints the chosen base.
 - baseline mismatch: run the check without changing baseline, then use `architecture:baseline:update` only in a reviewed migration PR.
 - baseline mismatch: run the check without changing baseline, then use `architecture:baseline:update` only in a reviewed migration PR.

+ 5 - 5
.agents/skills/feature-boundary-planner/references/zcode-domain-cross-products.md

@@ -39,10 +39,10 @@ Use this reference after `zcode-feature-graph.yaml` when scanning or planning an
 | Session messages and active turn | ZCode Agent runtime/session store | UI projection, task snapshot, replay mirror | protocol event, session snapshot, UI message tree |
 | Session messages and active turn | ZCode Agent runtime/session store | UI projection, task snapshot, replay mirror | protocol event, session snapshot, UI message tree |
 | Task list metadata | Host task sqlite index | UI task list cache, optimistic overlay | `tasks-index.sqlite` row, service list result, UI list |
 | Task list metadata | Host task sqlite index | UI task list cache, optimistic overlay | `tasks-index.sqlite` row, service list result, UI list |
 | Runtime recovery fields | Host runtime response-time snapshot | Mobile replayable UI store | `getTaskSnapshot.runtime`, stream watermark, pending permission/command UI |
 | Runtime recovery fields | Host runtime response-time snapshot | Mobile replayable UI store | `getTaskSnapshot.runtime`, stream watermark, pending permission/command UI |
-| Desktop queued prompt | Renderer local store | none durable by default | UI queue item, send/drain logs |
-| Mobile accepted queued prompt | Host runtime command queue | `pendingCommands` snapshot | enqueue ack, owner command, runtime snapshot |
-| Model selected for request | Agent runtime `defaultModelRef` | toolbar value, task config, task meta, workspace default, provider registry | `session/setModel` response, protocol snapshot settings, request/model trace |
-| Provider registry for remote workspace | Local desktop app-global provider service, explicitly synced to remote runtime | remote runtime overlay/cache | registry revision, remote session id, runtime model config |
+| Desktop/mobile accepted queued prompt | One CLI/runtime CommandInbox with serialized admission | client projection and pending optimistic overlay | original command ID, queue/guided/transcript/explicit terminal result, ACK/query and snapshot |
+| Unsubmitted prompt draft | Renderer draft owner | local draft persistence | draft payload and workspace/pane identity; not an accepted queue |
+| Model selected for request | Target Environment ModelFactory creates a Model from the admitted selection and current Registry | toolbar value, session selection, configured default | actual request/model trace; existing Model static facts remain frozen, subsequent ordinary turn creates a new Model |
+| Provider registry for remote workspace | Remote Environment Config, Account Source and Registry | remote Host/Worker Registry instances | target store/Registry revision, remote session id, Model creation; Local-to-Remote Provisioning writes formal stores rather than injecting Registry snapshots |
 | Workspace isolation key | `workspaceIdentity?.trim() || workspacePath` | tab/task/plugin/skill/cache keys | state bucket key, remote identity, path execution target |
 | Workspace isolation key | `workspaceIdentity?.trim() || workspacePath` | tab/task/plugin/skill/cache keys | state bucket key, remote identity, path execution target |
 | Theme and locale | Renderer local preference plus broadcast for app windows | DOM classes, settings UI, mobile localStorage | settings value, DOM class, i18n text |
 | Theme and locale | Renderer local preference plus broadcast for app windows | DOM classes, settings UI, mobile localStorage | settings value, DOM class, i18n text |
 | Telemetry | Declared event channel owner | transport queue/backend | event payload shape, sampling/aggregation rule, privacy filter |
 | Telemetry | Declared event channel owner | transport queue/backend | event payload shape, sampling/aggregation rule, privacy filter |
@@ -55,7 +55,7 @@ Use these as prompts for pairwise coverage. Do not explode every axis; prune wit
 | --- | --- |
 | --- | --- |
 | model switch x active task send x provider registry | Should send wait for pending `session/setModel`, fail fast, or continue with the old runtime model? |
 | model switch x active task send x provider registry | Should send wait for pending `session/setModel`, fail fast, or continue with the old runtime model? |
 | model switch x mobile replayable restore | Is restored mobile model display read-only history, active runtime config, or a new switch target? |
 | model switch x mobile replayable restore | Is restored mobile model display read-only history, active runtime config, or a new switch target? |
-| model/provider x remote workspace reconnect | After remote runtime restarts, which local provider registry revision must be reapplied before send? |
+| model/provider x remote workspace reconnect | Has the new remoteSessionId registered the latest Local-to-Remote provisioning, and which target Registry facts does the next Model read? Keep initial-ready failure and reconnect warning semantics separate. |
 | queue x stop/interrupted x autoDrain | After stop, should queued prompts remain held, auto-drain, or require explicit send-now? |
 | queue x stop/interrupted x autoDrain | After stop, should queued prompts remain held, auto-drain, or require explicit send-now? |
 | queue x edit/fork/compact | Does the action preserve, discard, copy, or reorder future queued intent? |
 | queue x edit/fork/compact | Does the action preserve, discard, copy, or reorder future queued intent? |
 | mobile remote x permission/elicitation | If a phone reconnects after a gap, should pending blockers render from snapshot, stream replay, or both? |
 | mobile remote x permission/elicitation | If a phone reconnects after a gap, should pending blockers render from snapshot, stream replay, or both? |

Diferenças do arquivo suprimidas por serem muito extensas
+ 778 - 55
.agents/skills/feature-boundary-planner/references/zcode-feature-graph.yaml


+ 95 - 0
.agents/skills/session-management/SKILL.md

@@ -0,0 +1,95 @@
+---
+name: session-management
+description: 修改 ZCode 会话管理(左侧任务列表、tasks-index.sqlite、sessions-index、CLI session store、标题/状态/置顶/归档/未读/删除、虚拟项目与 roots、workspace 身份、相关 migration)之前必读。它把 2026-09 「虚拟项目与数据归属收口」重构及分组恢复的设计理由、历史 bug 根因与不变量蒸馏成检查清单,让后来者知道为什么这样设计、哪些线不能踩。
+---
+
+# Session 管理设计蒸馏
+
+改动范围命中下列任一项时使用本 skill:`packages/services/src/session/taskIndexRepo.ts`、`packages/services/src/zcode-agent/zcodeTaskIndexSyncer.ts`、`zcodeTaskServiceAdapter.ts`、`packages/ui` 侧栏 / 任务列表 / 项目树、`apps/zcode-cli/packages/adapters/src/storage/session-store/*`、sessions-index 协议、workspace / project / roots 数据结构、两库 migration。
+
+权威 spec:`docs/superpowers/specs/2026-09-09-virtual-project-design.md` 与 `docs/ui/task-grouped-view.md`。2026-10-13 分组恢复裁决覆盖历史 Group 合并 Project 方案。本 skill 不重复 spec,只讲「为什么」和「怎么不踩坑」。
+
+## 1. 一句话原则
+
+**会话事实归 CLI,组织态归 Host;每个字段只有一个写者。**
+
+```text
+CLI  db.sqlite      存在性(软删除 time_deleted)、title+title_source、time_created/updated、last_outcome、正文、goal、fork、trace
+Host tasks-index    project_id、pinned、archived、unread_at(+CAS)、sort_order、projects/roots/hosts、定时/闲时;控制端另存跨设备分组成员与顺序
+                    cli_* 列 = CLI 事实的只读镜像,唯一写者 taskIndexSyncer
+禁止:CLI 写 app 库;Host 写 db.sqlite;Host 对任何 cli_* 列写 Date.now() 或从 snapshot 推导的值
+```
+
+### 为什么
+
+重构前 title / status 相关 Bugfix 注释有 30 多处(`rg "Bugfix" packages/services/src/zcode-agent/zcodeTaskIndexSyncer.ts packages/services/src/session/taskIndexRepo.ts`),几乎全部属于两类:
+
+1. Host 替 CLI 写会话事实:`updated_at = Date.now()`(rename / 状态变更)与 CLI 的 `time_updated` 分叉,导致排序跳动,UI 被迫只信 sessions-index 的 `lastActivityAt`;rename 先写本地再 best-effort 通知 CLI,失败只 warn,两边「是否手动标题」不一致;`task_status` 从 snapshot 反推,冷启动恒为 completed,残留 running 只能靠 UI 规则吸收。
+2. CLI 替 Host 决定行集合:3.4.0 曾因 sessions-index 快照缺 summary 导致历史任务在 Grouped 视图消失(`docs/superpowers/specs/2026-07-20-sidebar-task-row-authority-design.md`);CLI 冷种子会复活 app 已删的 session,app 只能靠 tombstone 压制。
+
+结论:不是「哪个库更好」,而是「谁第一手知道这个事实」。会话发生了什么只有 CLI 知道;用户对列表做了什么只有 Host/UI 知道;CLI 是每 workspace 一进程且可不在线,跨 workspace 的列表必须有 Host 侧落盘(`onDynamicWorkspaceEvent` 注释明确禁止为列表拉起 Agent)。
+
+## 2. 不变量(改代码前逐条对照)
+
+| #   | 不变量                                                                                                                                                                      | 违反时的典型症状                                                    |
+| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
+| I1  | `workspaceKey = workspaceIdentity?.trim() \|\| workspacePath` 只表达身份隔离;执行路径永远用 `workspacePath` / `root_path`                                                  | 远程 identity 被写进 cwd(3.4.2 事故)                              |
+| I2  | session 绑定目录(cwd)创建后永不变;项目移动只改 `project_id`,分组移动只改成员与顺序                                                                                      | 冷启动后 provider / memory / permissions 找不到                     |
+| I3  | 项目其余 roots 只作为 `additionalDirectories` 供 skills / commands / subagents / 可写范围;AGENTS.md、settings、MCP、hooks、plugins、memory、permissions 只按绑定目录链解析 | 另一目录的可执行配置混进当前会话;同名 MCP/hook 冲突                |
+| I4  | CLI 不感知项目;协议里只有目录列表                                                                                                                                          | CLI 出现 project 概念 = 设计漂移                                    |
+| I5  | 行集合由 app 库决定,sessions-index 只补实时字段(phase、lastActivityAt、pending interaction)                                                                              | 任务在列表里消失 / 复活                                             |
+| I6  | 排序时间只取 CLI 创建/活动时间镜像;沿用 running/prewarming 优先、运行层创建时间稳定排序及普通层创建/更新时间偏好;pin / archive / rename / 未读不改时间                    | 重命名后跳到顶部                                                    |
+| I7  | 未读用 CAS(`expectedUnreadAt`),只有 Host 显式 `unreadSignal` 才制造未读                                                                                                  | 手机已读被桌面覆盖;每轮完成全表闪烁                                |
+| I8  | 标题优先级:用户 override(`title_source=custom`) > 模型生成 > 首条 prompt > 占位 "New session";快照永不覆盖 override                                                       | 手动标题闪回                                                        |
+| I9  | 删除 = CLI 软删除(`time_deleted`),app `deleted` 是镜像;冷种子 / listSessions / TUI 必须过滤                                                                             | 已删 session 复活                                                   |
+| I10 | 两库 schema 只加不删不改旧列语义;新列可空或带默认;`ON CONFLICT(workspace_key, task_id)` 的唯一约束必须保留                                                                | 降级后旧版本崩溃                                                    |
+| I11 | 派生目录 hash(`sessions/{hash}`、`agent-config/{provider}/{hash}`、CLI memory)输入是真实目录 + identity,与项目无关,不迁移                                               | 升级后配置 / 记忆丢失                                               |
+| I12 | 手机远控 bridge / queue / snapshot key 只用 workspaceKey;桌面 continuous 与手机 replayable 边界不变                                                                        | 远控串会话                                                          |
+| I13 | Host 组织态只存在原列,不做副本;旧列 `deleted` / `title_overridden` 是「待交接给 CLI 的意图」,每次启动全表对账,不能只补 NULL                                             | 降级期删除 / 重命名在再升级后丢失                                   |
+| I14 | sessions-index snapshot 缺席不等于删除;删除只能来自 `session.removed` 或 `sessionsIndex/reconcile` 返回 deleted                                                            | 事件丢失后任务复活或误删                                            |
+| I15 | 恢复 CLI 库备份必须关闭外键并校验行数 / 哈希;`message`/`part` 对 `session` 是 ON DELETE CASCADE,裸 DELETE 会清空正文                                                      | 恢复后消息全丢                                                      |
+| I16 | 附加目录由 Host 统一解析并贯穿 create / 显式 resume / V4 subscribe 冷恢复;排除的是 session cwd 不是主要目录;运行实例存在时不刷新                                          | 桌面打开历史任务拿不到附加目录;换主要目录后老会话目录范围错乱      |
+| I17 | 空归属 session 只在首次发现时判定一次归位(bit 8);不自动建项目;不归入者在任务区、时间线或分组中可见。app 行缺失 = 未归类 `[]`,项目缺失 / 读取失败 = 显式报错            | 已移除的 workspace 复活;会话后来被悄悄挪进项目;TUI 新建会话打不开 |
+
+## 3. 关键裁决速查(详见 spec 第 3 节)
+
+- 2026-10-10 远程裁决:本地/远程项目平铺,Host 不作为分组;远程先建单目录项目再建会话,不允许无项目创建或拖拽追加目录。统一项目顺序归控制端侧栏偏好。详见 `docs/superpowers/specs/2026-10-10-session-manage-upstream-integration.md`。
+- 侧栏 = 全局置顶区(session + 置顶项目)→ 项目区 → 任务区(`project_id IS NULL`,任意 cwd);`~/.zcode/workspace/*` 只作为全局新建任务的默认执行目录。筛选含按项目 / 按分组 / 最近更新;真实目录不是节点,不恢复旧两级切换器。
+- 项目:本地 0..n 个同 host 的 roots + 一个主要目录,远程恰好一个固定目录;同一目录可属多个项目;新建 session cwd = 主要目录;仅本地 0 root 时自动建 `~/.zcode/workspace/<ts>` 并加为主要 root。
+- 本地项目及在线远端权威项目删除 = 软删除容器,session 保留归属,时间线可见;新建 roots 集合完全相等的项目时提示恢复;不提供彻底删除。远程项目离线删除只移除本机入口与缓存,不触发远端软删除或恢复。
+- 本地项目移除 root / 换主要目录不影响已创建 session、定时任务、闲时任务、Bots(它们在创建时固化 cwd 与附加目录);roots 变更对运行中 session 下次 resume 生效。
+- 同名 skill / subagent 来自不同 root 时并存,由 CLI 赋限定名 `<rootName>/<name>`。
+- 分组:控制端 Host 唯一持有跨设备分组,手机复用该 Host;不按 workspace 建组,不将分组转换为项目。分组不改变 cwd、项目、CLI 时间、配置或权限。读取只读,单节点移动在事务内复检来源/锚点,缺席不删除;系统任务只首次归组,手工移出后不拉回。
+- 展示偏好:有效新版 view 优先,否则沿用旧 organizeBy;旧 grouped 默认进入按分组。新建任务固化 draft 的分组 placement,首次发送后幂等提交,不在导航时猜测。
+- 远程:项目与任务组织态留在远端 app 库;本机持久化 host 连接记录、用户已添加的项目入口及基础信息缓存。离线不可展开、改名或编辑 roots,项目操作仅允许移除本机入口与缓存,远端项目与会话保留,无待同步删除队列。远程只允许创建时确定的一个固定 root,host 上限 20,启动自动连接已保存 host。
+- 重连只刷新本机仍存在的入口,迟到响应不得 upsert 已移除入口;setting.json 从本机入口列表派生,不反向重建已移除入口。重新添加远程项目须由用户主动选择,或由在线创建成功显式添加;删除本机 host 只移除连接及所属入口。
+- 设置页 agent 配置管理按真实目录(roots 去重平铺);定时 / 闲时 / Bots 选虚拟项目。
+
+## 4. 数据与迁移纪律
+
+- 版本化 migration runner 两库共用(抽自 `apps/zcode-cli/.../session-store/migration-runner.ts`):`schema_migration(id, checksum, app_version)`,checksum 不可变,未知 id 忽略。
+- 每条 migration 显式声明 `touchedTables`;runner 在同一读事务里只备份这些表(`ATTACH + CREATE TABLE AS SELECT`);备份只为迁移失败恢复,正常流程只产生不消费,不做整库快照(本机整库 770MB vs 表级 16MB)。
+- 每条 migration 一个单测:fixture 前后对全部表做内容哈希,只允许 `touchedTables` 变化。`schema.baseline.sql` 由 CI 做只增 diff。
+- 兼容退场三阶段:V1 只读新列、旧列只写不读;V2 写 `schema_floor` 并停双写;V3 物理删退场列 / `time_archived` 并重建主键。分组表已恢复为运行态,不能按旧计划删除。不要在任何阶段引入「永久」兼容分支。
+- 降级靠加法 schema,不靠备份;首次迁移遗留、旧版本新增或 CLI 首次发现的未归属 session 只判定一次:目录唯一匹配同 host 下未删除项目才归入,零个或多个匹配保留 NULL 并进入任务区,不自动建项目。唯一例外是远端 Source Server 的首次迁移:远端自身没有旧 workspace 清单,按历史任务目录建单 root 项目(虚拟项目 spec 2026-10-15 裁决)。旧 group、空组、系统组、颜色、成员和顺序继续读取;旧 Group → Project 转换取消,workspace → Project 保留。
+- `project_id IS NULL` 是合法未归类状态,不是待迁移标记。启动时先识别 `host_id IS NULL` 的旧版本新增行,再在同一事务补齐身份与首次归属;新版本创建或首次插入行时原子写入身份和归属。已处理的 NULL 行不因启动、对账或新增同目录项目而自动归入;全局新建任务显式保持未归类。
+- 迁移复用同一 SQL / Repo,启动门禁在 Host Worker 完成后才初始化业务服务;异步等待锁,迁移事务提交后再发布 ready,失败 fail-closed(重试 / 打开备份目录)。不得另造迁移实现。
+
+## 5. 改动前检查清单
+
+1. 这个字段的**唯一写者**是谁?如果你要在另一侧写它,先回到第 1 节重新判断,通常应改为发命令(`renameSession` / `deleteSession`)再等镜像。
+2. 你写入的时间戳来自 CLI 事件还是 `Date.now()`?后者只允许写 Host 组织态自己的时间列(`pinned_at`、`meta_updated_at`),不允许进任何排序依据。
+3. 是否会让 sessions-index 决定行的存在或消失?不允许。
+4. 是否用 `workspacePath` 做了身份判等或建 key?远程必须带 `workspaceIdentity`。
+5. 新增列 / 表是否可空或带默认、是否更新了 `schema.baseline.sql` 与 migration 的 `touchedTables`、是否有逐表哈希单测?
+6. 改了 CLI 配置发现逻辑?只允许在 skills / subagents / 路径策略三处消费 `additionalDirectories`;其余保持只按 `workingDirectory`。
+7. 涉及标题 / 状态 / 未读 / 归档 / 删除的行为变化,e2e 是否覆盖了「桌面 + 手机远控」「本地 + SSH/WSL」两组交叉?
+8. 涉及 schema 的改动,是否跑过「旧 fixture 升级 → 旧代码路径读写(含修改既有行:删除、重命名)→ 再升级」的 e2e?
+9. 触碰删除 / 标题的代码,是否保持了「意图位 → 惰性交接 → 镜像回写」三段,以及 orphan 的处理?
+
+## 6. 参考实现与文档
+
+- 现状事实:`docs/task/task-sqlite-index.md`、`docs/v4-refactor/14-sessions-index.md`、`docs/ui/task-title-authority.md`、`docs/ui/task-unread-state.md`、`docs/task-list-refresh-semantics.md`、`docs/wsl-task-status-inconsistency.md`(订阅被静默替换的根因)。
+- 历史决策:`docs/superpowers/specs/2026-07-13-v4-sidebar-task-state-authority-design.md`、`2026-07-20-sidebar-task-row-authority-design.md`、`docs/local-workspace-path-cold-resume-identity.md`。
+- 当前分组与视图:`docs/ui/task-grouped-view.md`、`docs/ui/sidebar-task-view-switcher.md`。
+- 已废弃(保留仅供降级理解):`docs/grouped-task-workspace-bootstrap.md`、`apps/zcode-cli/docs/design/v2/multi-workspace.md`。

+ 9 - 0
.gitattributes

@@ -2,8 +2,14 @@
 *.mjs text eol=lf
 *.mjs text eol=lf
 *.sh  text eol=lf
 *.sh  text eol=lf
 
 
+# schema baseline 与运行时 dump 逐字节比对;Windows autocrlf 检出成 CRLF 会被
+# db:schema:check 误报为 schema 差异并阻断 pre-push,强制 LF。
+*.baseline.sql text eol=lf
+
 # E2E PDF fixture 含规范 xref 尾空格,必须按二进制处理,避免 diff --check 误报。
 # E2E PDF fixture 含规范 xref 尾空格,必须按二进制处理,避免 diff --check 误报。
 packages/desktop/test/e2e/fixtures/fs/**/*.pdf binary
 packages/desktop/test/e2e/fixtures/fs/**/*.pdf binary
+# 文档查看器测试 PDF 同理:按字节解析 xref,换行转换会破坏偏移。
+apps/zcode-cli/packages/office-runtime/fixtures/*.pdf binary
 
 
 # 上游许可原文与生成的声明按字节保存,不能自动转换换行或裁剪空白。
 # 上游许可原文与生成的声明按字节保存,不能自动转换换行或裁剪空白。
 # 原文中的 License / ======= 是 Markdown 标题,不是合并冲突。
 # 原文中的 License / ======= 是 Markdown 标题,不是合并冲突。
@@ -14,3 +20,6 @@ third-party/runtime/*.txt -text -whitespace
 docs/knip/docs/LICENSE -text -whitespace
 docs/knip/docs/LICENSE -text -whitespace
 docs/knip/docs/licenses/** -text -whitespace
 docs/knip/docs/licenses/** -text -whitespace
 third-party/inventory.json linguist-generated=true
 third-party/inventory.json linguist-generated=true
+
+# Gen UI vendor 快照带 sha256 清单,构建时逐字节校验;autocrlf 改写换行会误报漂移,按字节保真。
+apps/zcode-cli/packages/visualize-plugin/skills/visualize/assets/vendor/** -text

+ 2 - 0
.gitignore

@@ -69,6 +69,8 @@ binding.Makefile
 packages/desktop/resources/macos-window-bounds/
 packages/desktop/resources/macos-window-bounds/
 # CUA Helper SEA 基座下载缓存(scripts/cua-helper-sea-base.mjs 落盘的官方 Node 22 运行时,纯下载产物)
 # CUA Helper SEA 基座下载缓存(scripts/cua-helper-sea-base.mjs 落盘的官方 Node 22 运行时,纯下载产物)
 /.tmp/
 /.tmp/
+# R3 服务器部署时写入的实际 commit 标记(harness/remote/deploy-server.sh 产出,随环境变化)
+.deployed-commit
 # Python 字节码(docker/plugin-eval/summarize.py 在主机上跑会生成)。
 # Python 字节码(docker/plugin-eval/summarize.py 在主机上跑会生成)。
 __pycache__/
 __pycache__/
 *.pyc
 *.pyc

+ 4 - 0
.oxfmtrc.json

@@ -1,6 +1,10 @@
 {
 {
   "$schema": "./node_modules/oxfmt/configuration_schema.json",
   "$schema": "./node_modules/oxfmt/configuration_schema.json",
   "ignorePatterns": [
   "ignorePatterns": [
+    ".gitlab/**/*.yml",
+    "apps/zcode-cli/tests/gb2312.js",
+    "docs/electron/docs/fiddles/**/*.html",
+    "packages/zcode-cua/**",
     "packages/desktop/src/renderer/src/plugin-sandbox/genUiTweakRuntime.js",
     "packages/desktop/src/renderer/src/plugin-sandbox/genUiTweakRuntime.js",
     "apps/zcode-cli/packages/visualize-plugin/skills/visualize/assets/**",
     "apps/zcode-cli/packages/visualize-plugin/skills/visualize/assets/**",
     "THIRD-PARTY-NOTICES.md",
     "THIRD-PARTY-NOTICES.md",

+ 32 - 1
.oxlintrc.json

@@ -3,9 +3,39 @@
   "plugins": null,
   "plugins": null,
   "categories": {},
   "categories": {},
   "rules": {
   "rules": {
-    "max-lines": ["error", { "max": 400, "skipBlankLines": true, "skipComments": true }]
+    "max-lines": ["error", { "max": 800, "skipBlankLines": true, "skipComments": true }]
   },
   },
   "overrides": [
   "overrides": [
+    {
+      // 本次上游整合保留既有职责完整的实现;这些文件超 800 行只告警,不机械拆分。
+      "files": [
+        // 插件市场沿用上游存量大文件,只补充目录字段投影;不为行数机械拆分安装流程。
+        "**/apps/zcode-cli/packages/adapters/src/plugins/marketplace.ts",
+        // MCP 连接入口沿用上游存量实现;连接屏障修复不为行数重排整个 adapter。
+        "**/apps/zcode-cli/packages/adapters/src/mcp/index.ts",
+        "**/apps/zcode-cli/packages/bootstrap/src/plugins.ts",
+        "**/apps/zcode-cli/packages/adapters/src/storage/session-store/migrations.ts",
+        "**/apps/zcode-cli/packages/adapters/src/storage/session-store/sqlite-session-store.ts",
+        "**/apps/zcode-cli/packages/bootstrap/src/app/create-app.ts",
+        "**/apps/zcode-cli/packages/bootstrap/src/app/session-facade.ts",
+        "**/apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/v4-gateway.ts",
+        "**/apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server.ts",
+        "**/apps/zcode-cli/packages/bootstrap/src/zcode-protocol/session-mapper.ts",
+        "**/apps/zcode-cli/packages/bootstrap/src/zcode-protocol/v4-bridge.ts",
+        "**/apps/zcode-cli/packages/contracts/src/interfaces/session-store.port.ts",
+        "**/apps/zcode-cli/packages/core/src/runtime/methods/steering.ts",
+        "**/apps/zcode-cli/packages/core/src/runtime/methods/turn.ts",
+        "**/apps/zcode-cli/packages/core/src/runtime/methods/turn-model-step.ts",
+        // core 包内以 --no-ignore 运行时,oxlint 按 cwd 相对路径匹配同一组存量文件。
+        "src/runtime/methods/steering.ts",
+        "src/runtime/methods/turn.ts",
+        "src/runtime/methods/turn-model-step.ts",
+        "**/packages/ui/src/remote-connection-flow/index.ts"
+      ],
+      "rules": {
+        "max-lines": ["warn", { "max": 800, "skipBlankLines": true, "skipComments": true }]
+      }
+    },
     {
     {
       // 测试文件天然会堆叠大量场景与断言,继续复用生产代码的行数上限会造成误报,
       // 测试文件天然会堆叠大量场景与断言,继续复用生产代码的行数上限会造成误报,
       // 因此只对 test/spec 文件关闭 max-lines,避免放宽业务代码约束。
       // 因此只对 test/spec 文件关闭 max-lines,避免放宽业务代码约束。
@@ -62,6 +92,7 @@
     ".agents/skills",
     ".agents/skills",
     "packages/formal-proof",
     "packages/formal-proof",
     "apps/zcode-cli",
     "apps/zcode-cli",
+    "packages/zcode-cua",
     "docs/electron"
     "docs/electron"
   ]
   ]
 }
 }

+ 15 - 12
AGENTS.md

@@ -11,18 +11,20 @@
 
 
 以下命令从仓库根目录执行:
 以下命令从仓库根目录执行:
 
 
-| 用途             | 命令                                      |
-| ---------------- | ----------------------------------------- |
-| 类型检查         | `pnpm typecheck`                          |
-| Lint             | `pnpm lint` / `pnpm lint:fix`             |
-| 格式检查         | `pnpm fmt:check`                          |
-| 桌面开发         | `pnpm dev:desktop`                        |
-| Web 开发         | `pnpm dev:web`                            |
-| 提交前检查       | `pnpm verify:pre-push`(Lint 与架构检查) |
-| 架构检查         | `pnpm architecture:check --changed`       |
-| 模块阅读包       | `pnpm architecture:context <module-id>`   |
-| 未使用依赖与导出 | `pnpm knip`                               |
-| 导出引用查询     | `pnpm dep:refs --list-exports <file>`     |
+| 用途             | 命令                                                 |
+| ---------------- | ---------------------------------------------------- |
+| 类型检查         | `pnpm typecheck`                                     |
+| Lint             | `pnpm lint` / `pnpm lint:fix`                        |
+| 格式检查         | `pnpm fmt:check`                                     |
+| 桌面开发         | `pnpm dev:desktop`                                   |
+| Web 开发         | `pnpm dev:web`                                       |
+| 提交前检查       | `pnpm verify:pre-push`(Lint、架构检查与受影响单测) |
+| 架构检查         | `pnpm architecture:check --changed`                  |
+| 模块阅读包       | `pnpm architecture:context <module-id>`              |
+| 未使用依赖与导出 | `pnpm knip`                                          |
+| 导出引用查询     | `pnpm dep:refs --list-exports <file>`                |
+
+affected 使用 Vitest 官方选择,只运行选中的根 UT;选中整个套件时说明并跳过 UT,成功退出,不因此阻止 Push;不替代 CLI 测试或桌面 E2E。全量使用 `pnpm test` / `pnpm test:unit`,仅在用户明确要求时调用。范围与输出合同见 [pre-push 说明](docs/testing/pre-push-hook.md)。
 
 
 测试入口以目标包当前的 `package.json` 和实际测试文件为准,不假定存在统一的单测或 E2E 命令。
 测试入口以目标包当前的 `package.json` 和实际测试文件为准,不假定存在统一的单测或 E2E 命令。
 
 
@@ -41,6 +43,7 @@
 - 避免重复状态和多条写入路径。明确唯一所有者、接口、依赖方向、事件顺序与幂等边界,不能用超时掩盖同步问题。
 - 避免重复状态和多条写入路径。明确唯一所有者、接口、依赖方向、事件顺序与幂等边界,不能用超时掩盖同步问题。
 - 有行为改动时先补充对应测试;交互改动需要 E2E 场景。检查测试与实现是否一致,并实际执行可用的验证。未执行或环境受限时如实说明。
 - 有行为改动时先补充对应测试;交互改动需要 E2E 场景。检查测试与实现是否一致,并实际执行可用的验证。未执行或环境受限时如实说明。
 - 修复 bug 时用中文注释说明原因和修复依据。发现设计缺陷时先与用户对齐,不不断增加兜底分支。
 - 修复 bug 时用中文注释说明原因和修复依据。发现设计缺陷时先与用户对齐,不不断增加兜底分支。
+- PR 描述须说明背景、设计意图与修改前后行为;包含 bugfix 时逐项说明触发场景、根因证据、修复机制及回归验证,并尽量关联已有工单链接。未确认的根因或引入提交如实标注,不根据模块或时间接近推断归因。
 - 涉及状态、时序、远端或异步同步的方案,用图展示所有者及事件顺序。
 - 涉及状态、时序、远端或异步同步的方案,用图展示所有者及事件顺序。
 - 必须执行 `pnpm typecheck` 和 `pnpm lint`,报告真实结果,不将已有失败写成通过。
 - 必须执行 `pnpm typecheck` 和 `pnpm lint`,报告真实结果,不将已有失败写成通过。
 - 使用异步文件和网络 IO;跨包导入使用公开入口,遵守现有路径别名。
 - 使用异步文件和网络 IO;跨包导入使用公开入口,遵守现有路径别名。

+ 11 - 7
CONTEXT.md

@@ -33,9 +33,12 @@ _Avoid_: 刷新、检查更新(口语可用,文档统一"手动刷新")
 ### 商店页结构
 ### 商店页结构
 
 
 **Public Segment(公开)**:
 **Public Segment(公开)**:
-商店列表页的分段之一,展示且仅展示官方市场的目录(Featured + 分类区块)。
+商店列表页的分段之一,展示官方市场中由产品团队维护的条目;发布字段 `publisherType` 为 `official`,旧目录未提供时默认公开。
 _Avoid_: 官方 tab、商店 tab
 _Avoid_: 官方 tab、商店 tab
 
 
+**Community Segment(社区)**:
+官方市场收录的外部维护插件;从 `external_plugins/` 发布为 `publisherType: community`,与用途分类独立。
+
 **Personal Segment(个人)**:
 **Personal Segment(个人)**:
 商店列表页的另一分段,展示全部个人来源的目录,按市场分组。
 商店列表页的另一分段,展示全部个人来源的目录,按市场分组。
 _Avoid_: 第三方 tab、我的 tab
 _Avoid_: 第三方 tab、我的 tab
@@ -48,13 +51,14 @@ _Avoid_: 与 Recommended 混用
 个人分段顶部的策展区,名单由仓内 `recommendedPlugins.json` 维护(当前推 claude-plugins-official 的精选插件)。仅存在于个人分段。
 个人分段顶部的策展区,名单由仓内 `recommendedPlugins.json` 维护(当前推 claude-plugins-official 的精选插件)。仅存在于个人分段。
 _Avoid_: 与 Featured 混用
 _Avoid_: 与 Featured 混用
 
 
-**Installed Strip(已安装条)**:
-列表页顶部的一排已安装插件图标,点击图标进入详情页。
-_Avoid_: 已安装列表(那是 Manage Installed 视图的事)
+**Manage Installed View(插件管理)**:
+市场右上角的“插件管理”进入同一页面内的管理视图;保留全局默认和项目覆盖,可返回浏览并保留搜索、来源与管理范围。更多菜单仅暂停/启用与卸载,更新和恢复继承使用独立操作。
+
+**UI Plugin(界面插件)**:
+清单声明有效的 `ui.surfaces`,发布目录携带 `componentTypes: ["ui", …]`。未安装时使用目录能力,安装后以实际清单为准;暂停不改变分类。归属、用途和 UI 能力是独立维度。UI 专区和搜索均限定当前来源分段。
 
 
-**Manage Installed View(管理已安装视图)**:
-已安装条右侧齿轮进入的管理界面,承载插件级启停开关、更新、卸载、启用状态筛选。
-_Avoid_: Installed tab(旧 IA 术语,已废弃)
+**Default UI Recommendations(默认界面推荐)**:
+Side Pane 的独立精选名单,由客户端配置接口的 `uiPluginRecommendations` 下发,关联完整市场目录展示,未安装、未启用也可推荐;点击后分别安装、启用或打开真实面板。开发安装和用户安装不自动加入,与市场内完整 UI 专区不同。
 
 
 ### 元数据
 ### 元数据
 
 

+ 46 - 22
DESIGN.md

@@ -14,6 +14,7 @@ This file is meant for coding agents. When generating or editing UI in this repo
 The dedicated `text-ui-*` scale is a mandatory repository-wide constraint for application interface typography:
 The dedicated `text-ui-*` scale is a mandatory repository-wide constraint for application interface typography:
 
 
 - UI components must use `text-ui-xl`, `text-ui-lg`, `text-ui-base`, `text-ui-caption`, `text-ui-sm`, or `text-ui-xs`.
 - UI components must use `text-ui-xl`, `text-ui-lg`, `text-ui-base`, `text-ui-caption`, `text-ui-sm`, or `text-ui-xs`.
+- The shared Settings section heading may use the dedicated `text-ui-settings-title` / `lg:text-ui-settings-title-lg` role defined below.
 - Do not introduce Tailwind's built-in `text-base`, `text-sm`, or `text-xs` for application UI.
 - Do not introduce Tailwind's built-in `text-base`, `text-sm`, or `text-xs` for application UI.
 - Do not introduce arbitrary UI font sizes such as `text-[13px]` or inline `font-size` values.
 - Do not introduce arbitrary UI font sizes such as `text-[13px]` or inline `font-size` values.
 - The only content-level exceptions are code, Diff, and terminal rendering that consume their independent numeric font-size settings. Their surrounding controls, labels, headers, and metadata must still use `text-ui-*`.
 - The only content-level exceptions are code, Diff, and terminal rendering that consume their independent numeric font-size settings. Their surrounding controls, labels, headers, and metadata must still use `text-ui-*`.
@@ -89,6 +90,8 @@ Default light and dark CSS variables still exist as fallback foundations, but ne
   Low-elevation container surface.
   Low-elevation container surface.
 - **Surface Hover**: `--color-surface-hover`
 - **Surface Hover**: `--color-surface-hover`
   Hover state for low-elevation surfaces.
   Hover state for low-elevation surfaces.
+- **Remote Continuity Panel**: `--color-remote-continuity-panel`, `--color-remote-continuity-panel-surface`, `--color-remote-continuity-panel-foreground`, `--color-remote-continuity-panel-subtle`
+  Reserved for the first-connect local-offline / remote-running comparison. It stays dark in both themes so the handoff remains visually stable; do not reuse it as a generic dark card.
 - **Card**: `--color-card`
 - **Card**: `--color-card`
   Standard content card background.
   Standard content card background.
 - **Card Selected**: `--color-card-selected`
 - **Card Selected**: `--color-card-selected`
@@ -117,6 +120,8 @@ Default light and dark CSS variables still exist as fallback foundations, but ne
 
 
 ### Border colors
 ### Border colors
 
 
+- **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.
+
 - **Border**: `--color-border`
 - **Border**: `--color-border`
   Default border and separator.
   Default border and separator.
 - **Border Hover**: `--color-border-hover`
 - **Border Hover**: `--color-border-hover`
@@ -132,6 +137,9 @@ Default light and dark CSS variables still exist as fallback foundations, but ne
 - **Success**: `--color-success` with `--color-success-foreground`
 - **Success**: `--color-success` with `--color-success-foreground`
 - **Warning**: `--color-warning` with `--color-warning-foreground`
 - **Warning**: `--color-warning` with `--color-warning-foreground`
 - **Destructive**: `--color-destructive` with `--color-destructive-foreground`
 - **Destructive**: `--color-destructive` with `--color-destructive-foreground`
+- **Success surface**: `--color-success-surface` with `--color-success-surface-foreground`
+- **Warning surface**: `--color-warning-surface` with `--color-warning-surface-foreground`
+- **Destructive surface**: `--color-destructive-surface` with `--color-destructive-surface-foreground`
 - **Idle-time task**: `--color-idle-task` with `--color-idle-task-surface`
 - **Idle-time task**: `--color-idle-task` with `--color-idle-task-surface`
   Use only for idle-time queue and paused tags so they remain visually distinct
   Use only for idle-time queue and paused tags so they remain visually distinct
   from the green scheduled-task treatment.
   from the green scheduled-task treatment.
@@ -139,6 +147,7 @@ Default light and dark CSS variables still exist as fallback foundations, but ne
 - **Diff Removed**: `--color-diff-removed` with `--color-diff-removed-foreground`
 - **Diff Removed**: `--color-diff-removed` with `--color-diff-removed-foreground`
 
 
 Use semantic colors only for actual semantic states. Do not borrow success, warning, or destructive colors just to make a block feel louder.
 Use semantic colors only for actual semantic states. Do not borrow success, warning, or destructive colors just to make a block feel louder.
+Use `*-surface` for translucent state chips and banners; pair it with the matching `*-surface-foreground` and never add ad-hoc alpha in a component. Surface foreground values must preserve at least 4.5:1 contrast across shipped themes.
 
 
 ### Blocking interaction colors
 ### Blocking interaction colors
 
 
@@ -260,21 +269,28 @@ Each `text-ui-*` utility maps to the corresponding `--text-ui-*` CSS token.
 
 
 All interface typography must use the dedicated `text-ui-*` scale. The Appearance setting controls `--ui-font-size`, whose default is `14px`:
 All interface typography must use the dedicated `text-ui-*` scale. The Appearance setting controls `--ui-font-size`, whose default is `14px`:
 
 
-| Token | Formula | Default |
-| --- | --- | ---: |
-| `text-ui-xl` | `--ui-font-size + 4px` | 18px |
-| `text-ui-lg` | `--ui-font-size + 2px` | 16px |
-| `text-ui-base` | `--ui-font-size` | 14px |
-| `text-ui-caption` | `--ui-font-size - 1px` | 13px |
-| `text-ui-sm` | `--ui-font-size - 2px` | 12px |
-| `text-ui-xs` | `--ui-font-size - 4px` | 10px |
-| `text-ui-2xs` | `--ui-font-size - 5px` | 9px |
+| Token             | Formula                | Default |
+| ----------------- | ---------------------- | ------: |
+| `text-ui-xl`      | `--ui-font-size + 4px` |    18px |
+| `text-ui-lg`      | `--ui-font-size + 2px` |    16px |
+| `text-ui-base`    | `--ui-font-size`       |    14px |
+| `text-ui-caption` | `--ui-font-size - 1px` |    13px |
+| `text-ui-sm`      | `--ui-font-size - 2px` |    12px |
+| `text-ui-xs`      | `--ui-font-size - 4px` |    10px |
+| `text-ui-2xs`     | `--ui-font-size - 5px` |     9px |
 
 
 `text-ui-2xs` is a restricted exception below the `text-ui-xs` floor: it is permitted
 `text-ui-2xs` is a restricted exception below the `text-ui-xs` floor: it is permitted
 only for graph **axis furniture** — timebase tick labels, channel codes, and unit
 only for graph **axis furniture** — timebase tick labels, channel codes, and unit
 suffixes in the workflow timeline — never for content, labels, or metadata.
 suffixes in the workflow timeline — never for content, labels, or metadata.
 Treat any other use as a design-system defect.
 Treat any other use as a design-system defect.
 
 
+The shared Settings section heading uses `text-ui-settings-title` with
+`lg:text-ui-settings-title-lg`: `--ui-font-size + 10px` / `+ 16px` (24px / 30px
+at the default setting), with line-height ratios of `4 / 3` / `1.2` (32px / 36px
+by default). These tokens preserve the larger responsive heading while following
+the interface font setting. They are reserved for this page heading; ordinary
+section titles and controls retain the standard scale.
+
 `text-mobile-input-safe` is a fixed 16px platform-compatibility token. It is
 `text-mobile-input-safe` is a fixed 16px platform-compatibility token. It is
 reserved for editable controls on mobile Web surfaces where iOS focus zoom must
 reserved for editable controls on mobile Web surfaces where iOS focus zoom must
 be prevented, and therefore does not scale with `--ui-font-size`.
 be prevented, and therefore does not scale with `--ui-font-size`.
@@ -288,14 +304,14 @@ be prevented, and therefore does not scale with `--ui-font-size`.
 
 
 The `text-ui-*` scale expresses stable semantic roles. Choose a token by content role rather than by isolated visual preference:
 The `text-ui-*` scale expresses stable semantic roles. Choose a token by content role rather than by isolated visual preference:
 
 
-| Token | Primary roles |
-| --- | --- |
-| `text-ui-xl` | Markdown `h1` and equivalent first-level reading headings |
-| `text-ui-lg` | Markdown `h2` and equivalent second-level reading headings |
-| `text-ui-base` | Markdown `h3`-`h6`, body copy, common buttons, workspace and section titles, and other primary UI text |
+| Token             | Primary roles                                                                                                |
+| ----------------- | ------------------------------------------------------------------------------------------------------------ |
+| `text-ui-xl`      | Markdown `h1` and equivalent first-level reading headings                                                    |
+| `text-ui-lg`      | Markdown `h2` and equivalent second-level reading headings                                                   |
+| `text-ui-base`    | Markdown `h3`-`h6`, body copy, common buttons, workspace and section titles, and other primary UI text       |
 | `text-ui-caption` | Compact supporting copy that must remain one step below body text, such as the New Task feature announcement |
 | `text-ui-caption` | Compact supporting copy that must remain one step below body text, such as the New Task feature announcement |
-| `text-ui-sm` | Secondary copy, supporting information, helper text, Tooltip copy, and Markdown inline code |
-| `text-ui-xs` | Tooltip keyboard shortcuts, badges, compact labels, counters, and very weak metadata |
+| `text-ui-sm`      | Secondary copy, supporting information, helper text, Tooltip copy, and Markdown inline code                  |
+| `text-ui-xs`      | Tooltip keyboard shortcuts, badges, compact labels, counters, and very weak metadata                         |
 
 
 - Markdown `h3`-`h6` share `text-ui-base`; distinguish their hierarchy through weight: `h3`-`h4` use `font-semibold`, `h5` uses `font-medium`, and `h6` uses `font-normal`.
 - Markdown `h3`-`h6` share `text-ui-base`; distinguish their hierarchy through weight: `h3`-`h4` use `font-semibold`, `h5` uses `font-medium`, and `h6` uses `font-normal`.
 - Body copy and common controls normally use `text-ui-base font-normal`; titles and labels may strengthen weight without changing their semantic size role.
 - Body copy and common controls normally use `text-ui-base font-normal`; titles and labels may strengthen weight without changing their semantic size role.
@@ -380,11 +396,11 @@ These exceptions do not automatically grant `2xl` to nested controls or content
 
 
 Buttons, menu trigger buttons, ordinary Input, Textarea, and Select triggers default to `rounded-lg`. Adjust them according to the nearest rounded parent container:
 Buttons, menu trigger buttons, ordinary Input, Textarea, and Select triggers default to `rounded-lg`. Adjust them according to the nearest rounded parent container:
 
 
-| Nearest rounded parent | Control radius |
-| --- | --- |
-| None, or `rounded-xl` and above | `rounded-lg` |
-| `rounded-lg` | `rounded-md` |
-| `rounded-md` / `rounded-sm` | `rounded-sm` |
+| Nearest rounded parent          | Control radius |
+| ------------------------------- | -------------- |
+| None, or `rounded-xl` and above | `rounded-lg`   |
+| `rounded-lg`                    | `rounded-md`   |
+| `rounded-md` / `rounded-sm`     | `rounded-sm`   |
 
 
 Control size and primary/secondary action emphasis do not independently change radius.
 Control size and primary/secondary action emphasis do not independently change radius.
 
 
@@ -594,7 +610,7 @@ adding breakpoint overrides.
 ## Accessibility and Internationalization
 ## Accessibility and Internationalization
 
 
 - Support keyboard navigation as a first-class interaction path.
 - Support keyboard navigation as a first-class interaction path.
-- Preserve visible focus behavior through the repo's established focus styling patterns.
+- Preserve the repo's established component focus styling. Do not add a shared `!important` outline to dialog descendants, remote controls, or settings navigation. Composite inputs use their existing outer border or ring without an additional inner outline. This also applies in forced-colors mode; test IDs are not styling contracts.
 - Ensure contrast remains safe in light, dark, and Zai modes.
 - Ensure contrast remains safe in light, dark, and Zai modes.
 - Write layouts that tolerate longer translations.
 - Write layouts that tolerate longer translations.
 - Avoid icon-only meaning when a text label is practical.
 - Avoid icon-only meaning when a text label is practical.
@@ -628,3 +644,11 @@ adding breakpoint overrides.
 - use semantic error or success colors for non-semantic decoration
 - use semantic error or success colors for non-semantic decoration
 - create components that only look correct in one theme
 - create components that only look correct in one theme
 - trade clarity for visual novelty in tool-heavy screens
 - trade clarity for visual novelty in tool-heavy screens
+
+## Remote connection progress (RDUX-03)
+
+`--color-progress-surface` / `--color-progress-surface-foreground` express work in progress, including connecting, automatic recovery and updating. Use `bg-progress-surface` with `text-progress-surface-foreground`; the foreground can also color progress indicators and borders. Four themes define the pair and all parent backgrounds must retain a 4.5:1 text contrast.
+
+Remote state mapping: connected → success (neutral cloud in project rows); connecting/updating → progress; disconnected → neutral surface/subtle foreground; needs attention → warning; failed → destructive. SSH/WSL/Docker tokens are reserved for connection type labels, never connection status. Always include visible status text outside the connected state; recovery attempts are visible text. See the remote device UX specification for the authoritative mapping and glossary.
+
+远程可读辅助文字:`--color-remote-foreground-muted` / `text-remote-foreground-muted` 用于远程向导、设备卡和日志辅助文字、侧栏设备标签与设置导航;侧栏共享的任务/项目视图切换、分组操作及搜索快捷键也沿用此可读辅助文字等级,浅色 `#595959`、深色 `#b3b3b3`,在 sidebar / popover / surface / card / selected / background 上保持至少 4.5:1。Zai Light SSH 类型标签前景为 `#0867ce`,保持与 `#ebf4ff` 底色至少 4.5:1。

+ 3 - 0
README.en.md

@@ -15,6 +15,7 @@ ZCode is an AI coding workspace with desktop, browser, and terminal interfaces.
 
 
 ## Updates
 ## Updates
 
 
+- **2026-10-16**: Updated to ZCode v3.16.1.
 - 2026-10-10: Updated to ZCode v3.15.1.
 - 2026-10-10: Updated to ZCode v3.15.1.
 - 2026-9-23: Updated to ZCode v3.14.3.
 - 2026-9-23: Updated to ZCode v3.14.3.
 
 
@@ -103,6 +104,8 @@ See Packaging below for build instructions. `pnpm build:zcode` only creates the
 
 
 ### CLI Source Development
 ### CLI Source Development
 
 
+See the [CLI usage guide (Chinese)](apps/zcode-cli/docs/usage/README.md) for model configuration, non-interactive runs, tools and extensions, batch evaluation, and trajectory capture.
+
 Use the source entry when developing the TUI or Agent:
 Use the source entry when developing the TUI or Agent:
 
 
 ```bash
 ```bash

+ 3 - 2
README.md

@@ -11,12 +11,11 @@
   简体中文 | <a href="README.en.md">English</a>
   简体中文 | <a href="README.en.md">English</a>
 </p>
 </p>
 
 
-
-
 ZCode 是 AI 编程工作台,提供桌面应用、浏览器界面和终端 Agent。本仓库包含客户端、后端服务、共享 UI,以及 Agent CLI 与运行时源码。
 ZCode 是 AI 编程工作台,提供桌面应用、浏览器界面和终端 Agent。本仓库包含客户端、后端服务、共享 UI,以及 Agent CLI 与运行时源码。
 
 
 ## 更新
 ## 更新
 
 
+- **2026-10-16**:更新至 ZCode v3.16.1 版本。
 - 2026-10-10:更新至 ZCode v3.15.1 版本。
 - 2026-10-10:更新至 ZCode v3.15.1 版本。
 - 2026-9-23:更新至 ZCode v3.14.3 版本。
 - 2026-9-23:更新至 ZCode v3.14.3 版本。
 
 
@@ -109,6 +108,8 @@ Web 模式默认工作目录为当前目录,监听 `127.0.0.1`,默认不启
 
 
 ### CLI 源码开发
 ### CLI 源码开发
 
 
+CLI 的模型配置、非交互调用、工具与扩展、批量评测和轨迹记录见 [CLI 使用指南](apps/zcode-cli/docs/usage/README.md)。
+
 直接开发 TUI 或 Agent 时,运行源码入口:
 直接开发 TUI 或 Agent 时,运行源码入口:
 
 
 ```bash
 ```bash

+ 2 - 0
THIRD-PARTY-NOTICES.md

@@ -2518,6 +2518,8 @@ Electron/Chromium target-specific notices are shipped separately under Resources
 
 
 ## Modified npm packages
 ## Modified npm packages
 
 
+- @radix-ui/react-collapsible@1.1.12: modified by ZCode; the changes are recorded in patches/@radix-ui__react-collapsible@1.1.12.patch in the source repository.
+
 - vitest@4.1.7: modified by ZCode; the changes are recorded in patches/vitest@4.1.7.patch in the source repository.
 - vitest@4.1.7: modified by ZCode; the changes are recorded in patches/vitest@4.1.7.patch in the source repository.
 
 
 - wdio-electron-service@9.2.1: modified by ZCode; the changes are recorded in patches/wdio-electron-service@9.2.1.patch in the source repository.
 - wdio-electron-service@9.2.1: modified by ZCode; the changes are recorded in patches/wdio-electron-service@9.2.1.patch in the source repository.

+ 32 - 30
apps/dev-docs/test/capabilityMapComplexity.test.ts

@@ -1,35 +1,37 @@
-import { describe, expect, it } from "vitest";
-import { capabilityEdges } from "@/data/productCapabilityMap.js";
-import {
-  getCapabilityGroupComplexity,
-  groupComplexityById,
-  nodeById,
-} from "@/capability-map/capabilityMapTypes.js";
+import { describe, expect, it, vi } from "vitest";
+import { groupComplexityById } from "@/capability-map/capabilityMapTypes.js";
+
+// 原测试依赖当前能力图,并把缺失端点误计为跨群边,导致 136 != 137。
+// 使用固定小图独立声明期望,不让文档节点增删或统计实现决定测试答案。
+vi.mock("@/data/productCapabilityMap.js", () => ({
+  capabilityGroups: [{ id: "a" }, { id: "b" }, { id: "c" }, { id: "empty" }],
+  capabilityNodes: [
+    { id: "a1", groupId: "a" },
+    { id: "a2", groupId: "a" },
+    { id: "b1", groupId: "b" },
+    { id: "c1", groupId: "c" },
+    { id: "orphan", groupId: "missing-group" },
+  ],
+  capabilityEdges: [
+    { source: "a1", target: "b1" },
+    { source: "b1", target: "a1" },
+    { source: "b1", target: "c1" },
+    { source: "a1", target: "a2" },
+    { source: "missing-node", target: "b1" },
+    { source: "a1", target: "missing-node" },
+    { source: "orphan", target: "b1" },
+  ],
+  capabilitySystems: [],
+  capabilityRelationNames: {},
+}));
 
 
 describe("能力群复杂度", () => {
 describe("能力群复杂度", () => {
   it("只把跨群有向边计入入度和出度", () => {
   it("只把跨群有向边计入入度和出度", () => {
-    const crossGroupEdgeCount = capabilityEdges.filter(
-      (edge) =>
-        nodeById.get(edge.source)?.groupId !==
-        nodeById.get(edge.target)?.groupId,
-    ).length;
-    const totalInDegree = [...groupComplexityById.values()].reduce(
-      (sum, complexity) => sum + complexity.inDegree,
-      0,
-    );
-    const totalOutDegree = [...groupComplexityById.values()].reduce(
-      (sum, complexity) => sum + complexity.outDegree,
-      0,
-    );
-
-    expect(totalInDegree).toBe(crossGroupEdgeCount);
-    expect(totalOutDegree).toBe(crossGroupEdgeCount);
-  });
-
-  it("智能体核心统计与当前权威关系图一致", () => {
-    expect(getCapabilityGroupComplexity("agent-core")).toEqual({
-      inDegree: 12,
-      outDegree: 7,
-    });
+    expect([...groupComplexityById]).toEqual([
+      ["a", { inDegree: 1, outDegree: 1 }],
+      ["b", { inDegree: 1, outDegree: 2 }],
+      ["c", { inDegree: 1, outDegree: 0 }],
+      ["empty", { inDegree: 0, outDegree: 0 }],
+    ]);
   });
   });
 });
 });

+ 0 - 66
apps/dev-docs/test/capabilityMapCurrentFeatures.test.ts

@@ -1,66 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { capabilityEdges, capabilityNodes } from "@/data/productCapabilityMap.js";
-
-function node(id: string) {
-  const result = capabilityNodes.find((candidate) => candidate.id === id);
-  expect(result, `能力节点 ${id} 应存在`).toBeDefined();
-  return result!;
-}
-
-function edge(source: string, target: string) {
-  const result = capabilityEdges.find(
-    (candidate) => candidate.source === source && candidate.target === target,
-  );
-  expect(result, `能力边 ${source} -> ${target} 应存在`).toBeDefined();
-  return result!;
-}
-
-describe("能力地图当前功能事实", () => {
-  it("记录 Office 只读预览与未来原生编辑的边界", () => {
-    expect(node("office-document-preview").scope).toEqual(expect.stringContaining("DOCX/DOC"));
-    expect(node("office-document-preview").scope).toEqual(expect.stringContaining("XLSX"));
-    expect(edge("office-document-preview", "file-service")).toMatchObject({
-      type: "delivery",
-    });
-  });
-
-  it("记录视频媒体、Hook 摘要和 /plan 的对话入口", () => {
-    expect(node("sent-media-preview").scope).toMatch(/image\/video|视频/);
-    expect(node("hook-turn-summary").scope).toContain("client-visible");
-    expect(node("plan-shortcut").scope).toContain("/plan");
-    expect(edge("product-projection", "hook-turn-summary")).toMatchObject({
-      type: "state",
-    });
-    expect(edge("hook-turn-summary", "desktop-continuous")).toMatchObject({
-      type: "delivery",
-    });
-    expect(edge("hook-turn-summary", "mobile-replayable")).toMatchObject({
-      type: "delivery",
-    });
-    expect(edge("composer", "plan-shortcut")).toMatchObject({
-      type: "shared",
-    });
-  });
-
-  it("记录 MCP 诊断、官方 Server MCP 与浏览器 Tab 生命周期", () => {
-    expect(node("mcp-settings-diagnostics").scope).toContain("pluginId");
-    expect(node("official-server-mcp").scope).toMatch(/auth|quota/);
-    expect(node("browser-tab-residency").scope).toContain("32-tab");
-    expect(edge("mcp-settings-diagnostics", "mcp-runtime")).toMatchObject({
-      type: "state",
-    });
-    expect(edge("official-server-mcp", "plan-identity")).toMatchObject({
-      type: "state",
-    });
-    expect(edge("browser-tab-residency", "embedded-browser-host")).toMatchObject({
-      type: "delivery",
-    });
-  });
-
-  it("把 Document Skills 的格式范围与模型有效模态写清楚", () => {
-    expect(node("document-skills").scope).toContain("PPTX/XLSX");
-    expect(node("model-modalities").scope).toContain("video");
-    expect(node("model-modalities").scope).toContain("provider wire");
-    expect(node("model-selector").scope).toMatch(/模态|vision|reasoning/i);
-  });
-});

+ 0 - 36
apps/dev-docs/test/capabilityMapGeometry.test.ts

@@ -1,36 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
-  CAPABILITY_GROUP_CONTENT_TOP,
-  CAPABILITY_GROUP_FRAME_BORDER_WIDTH,
-  CAPABILITY_GROUP_HEADER_HEIGHT,
-  CAPABILITY_HEADER_CONTENT_GAP,
-  CAPABILITY_SYSTEM_CONTENT_TOP,
-  CAPABILITY_SYSTEM_FRAME_BORDER_WIDTH,
-  CAPABILITY_SYSTEM_HEADER_HEIGHT,
-} from "@/capability-map/capabilityMapGeometry.js";
-
-describe("能力图父子元素间距", () => {
-  it.each([
-    {
-      contentTop: CAPABILITY_SYSTEM_CONTENT_TOP,
-      frameBorderWidth: CAPABILITY_SYSTEM_FRAME_BORDER_WIDTH,
-      headerHeight: CAPABILITY_SYSTEM_HEADER_HEIGHT,
-      level: "顶层区域",
-    },
-    {
-      contentTop: CAPABILITY_GROUP_CONTENT_TOP,
-      frameBorderWidth: CAPABILITY_GROUP_FRAME_BORDER_WIDTH,
-      headerHeight: CAPABILITY_GROUP_HEADER_HEIGHT,
-      level: "能力群",
-    },
-  ])(
-    "$level 子元素不会覆盖标题区",
-    ({ contentTop, frameBorderWidth, headerHeight }) => {
-      const effectiveClearance =
-        contentTop - frameBorderWidth - headerHeight;
-      expect(effectiveClearance).toBeGreaterThanOrEqual(
-        CAPABILITY_HEADER_CONTENT_GAP,
-      );
-    },
-  );
-});

+ 0 - 93
apps/dev-docs/test/capabilityMapOfficeComputerUse.test.ts

@@ -1,93 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { capabilityEdges, capabilityGroups, capabilityNodes } from "@/data/productCapabilityMap.js";
-
-describe("办公套件与 Computer Use 孵化能力", () => {
-  it("在 Renderer 中保留独立能力群,并只统计当前代码量", () => {
-    const group = capabilityGroups.find(
-      (candidate) => candidate.id === "office-computer-use-incubation",
-    );
-    const nodes = capabilityNodes.filter((node) => node.groupId === group?.id);
-
-    expect(group).toMatchObject({
-      systemId: "renderer",
-      codeEstimate: {
-        productionLines: 1_200,
-      },
-    });
-    expect(nodes.map((node) => node.id)).toEqual([
-      "office-document-preview",
-      "office-spreadsheet-workbench",
-      "office-presentation-workbench",
-      "office-native-editing",
-      "computer-use-task-ux",
-      "computer-use-takeover",
-    ]);
-    expect(nodes.some((node) => node.scope.includes("当前:"))).toBe(true);
-    expect(nodes.some((node) => node.scope.includes("规划:"))).toBe(true);
-  });
-
-  it("把 Renderer 体验连接到 Host 和 CLI 的当前支撑能力", () => {
-    expect(capabilityNodes).toEqual(
-      expect.arrayContaining([
-        expect.objectContaining({
-          id: "office-document-service",
-          groupId: "workbench-services",
-        }),
-        expect.objectContaining({
-          id: "document-skills",
-          groupId: "extension-runtime",
-        }),
-        expect.objectContaining({
-          id: "computer-use-mcp",
-          groupId: "extension-runtime",
-        }),
-        expect.objectContaining({
-          id: "cua-helper-lifecycle",
-          groupId: "browser-platform",
-        }),
-      ]),
-    );
-    expect(capabilityEdges).toEqual(
-      expect.arrayContaining([
-        expect.objectContaining({
-          source: "document-skills",
-          target: "office-native-editing",
-        }),
-        expect.objectContaining({
-          source: "computer-use-mcp",
-          target: "computer-input-execution",
-        }),
-        expect.objectContaining({
-          source: "mobile-remote",
-          target: "cua-helper-lifecycle",
-          type: "invariant",
-        }),
-      ]),
-    );
-  });
-
-  it("把 Windows 按工具触发的顶部提示记录为当前本地 Host 投影能力", () => {
-    expect(capabilityNodes.find((node) => node.id === "computer-use-task-ux")).toMatchObject({
-      scope: expect.stringContaining("Windows 顶部操作提示"),
-      authority: "Desktop Main native projection + Renderer tool projection",
-    });
-    expect(capabilityNodes.find((node) => node.id === "computer-use-task-ux")?.scope).toContain(
-      "computer-use/operation-event",
-    );
-    expect(capabilityEdges).toEqual(
-      expect.arrayContaining([
-        expect.objectContaining({
-          source: "local-host",
-          target: "computer-use-task-ux",
-          type: "state",
-          label: expect.stringContaining("computer-use/operation-event"),
-        }),
-      ]),
-    );
-    expect(
-      capabilityEdges.find(
-        (edge) => edge.source === "local-host" && edge.target === "computer-use-task-ux",
-      )?.label,
-    ).toContain("computer-use/operation-event");
-  });
-});

+ 0 - 30
apps/dev-docs/test/featureBoundaryGraph.test.ts

@@ -120,34 +120,4 @@ describe("feature boundary graph helpers", () => {
       ["capability.mcp-oauth-authorization", "persistence.desktop-user-data-root"],
       ["capability.mcp-oauth-authorization", "persistence.desktop-user-data-root"],
     );
     );
   });
   });
-
-  it("危险命令 V1 关联真实代码起点和隔离边界", async () => {
-    const source = await readFile(
-      resolve(
-        process.cwd(),
-        "../../.agents/skills/feature-boundary-planner/references/zcode-feature-graph.yaml",
-      ),
-      "utf8",
-    );
-    const graph = normalizeFeatureBoundaryGraph(parseYaml(source));
-    const capabilityId = "capability.dangerous-command-approval";
-    const capability = graph.nodes.find((node) => node.id === capabilityId);
-    expect(capability?.docs).toContain("docs/dangerous-command-approval-v1-plan.md");
-    expect(capability?.codeSeeds).toEqual([
-      "matchDangerousCommand · apps/zcode-cli/packages/core/src/tool/handlers/guarded/command.ts",
-      "resolveToolPermission · apps/zcode-cli/packages/core/src/tool/executor/permission-flow.ts",
-      "buildProtocolPermissionOptions · apps/zcode-cli/packages/bootstrap/src/permission-options.ts",
-      "getZCodeAgentAvailableModes · packages/shared/src/zcode-agent-model-state.ts",
-      "buildAutomationModeOption · packages/ui/src/settings/automationAgentConfigOptions.ts",
-      "filterModeOptions · apps/zcode-cli/packages/tui/src/app-mode-command.ts",
-    ]);
-    expect(graph.edges.filter((edge) => edge.from === capabilityId).map((edge) => edge.to)).toEqual(
-      [
-        "surface.parent-task-blocking-interaction",
-        "boundary.desktop-continuous",
-        "boundary.web-remote-replayable",
-        "boundary.workspace-key",
-      ],
-    );
-  });
 });
 });

+ 3 - 0
apps/zcode-cli/.gitignore

@@ -21,3 +21,6 @@ packages/**/tests/**/*.d.ts.map
 .VSCodeCounter
 .VSCodeCounter
 vendor
 vendor
 !packages/visualize-plugin/skills/visualize/assets/vendor/
 !packages/visualize-plugin/skills/visualize/assets/vendor/
+
+# Lowering 的人工可审查契约快照不是 tsc 产物,干净 checkout 也必须可运行测试。
+!packages/dynamic-workflow/tests/lowering/expected/*.js

+ 1 - 1
apps/zcode-cli/AGENTS.md

@@ -10,7 +10,7 @@
 - 功能文档更新到最终行为,复用已有 spec;bugfix 用回归证据留痕,非显然根因和防回归约束在修复点留中文注释。
 - 功能文档更新到最终行为,复用已有 spec;bugfix 用回归证据留痕,非显然根因和防回归约束在修复点留中文注释。
 - agent 友好的项目,留好日志或者接口,让 agent 能完全接手操作
 - agent 友好的项目,留好日志或者接口,让 agent 能完全接手操作
 - 长程任务优先:核心 agent loop 默认面向可持续运行的复杂任务设计,不用 tool call 次数做硬停止。资源与安全边界应由 token/context limit 自动 compact、用户取消、权限拒绝、工具超时、输出截断、provider retry 上限等明确条件承担。
 - 长程任务优先:核心 agent loop 默认面向可持续运行的复杂任务设计,不用 tool call 次数做硬停止。资源与安全边界应由 token/context limit 自动 compact、用户取消、权限拒绝、工具超时、输出截断、provider retry 上限等明确条件承担。
-- 单个源文件默认不能超过 400 行;超过时必须优先按高内聚低耦合拆分模块,不能用大文件继续堆职责。
+- 单个源文件默认上限为 800 行。已确认的存量超限文件由根 `.oxlintrc.json` 精确登记为行数告警;不要为满足行数机械拆分,职责分离确有收益时再重构。其他检查仍严格执行。
 - 字符串、数字等常量应提取为命名变量或常量,不要在业务逻辑中直接散落字面量,便于一处修改、统一维护。
 - 字符串、数字等常量应提取为命名变量或常量,不要在业务逻辑中直接散落字面量,便于一处修改、统一维护。
 - 修改数据库结构时必须同步 CLI 负责人,仔细设计 migration
 - 修改数据库结构时必须同步 CLI 负责人,仔细设计 migration
 - 键盘操作优先,核心逻辑都可以走键盘操作。鼠标操作是增益能力
 - 键盘操作优先,核心逻辑都可以走键盘操作。鼠标操作是增益能力

+ 16 - 317
apps/zcode-cli/README.md

@@ -1,326 +1,25 @@
-# zcode-cli
+# ZCode CLI
 
 
-TypeScript + Node.js 24.14.0 CLI starter. The default artifact is a normal Node CLI bundle, and SEA is kept as an optional packaging path.
-
-## Why This Shape
-
-- Runtime code has zero production dependencies.
-- The CLI uses Node built-ins for argument parsing and terminal control.
-- `npm run build` produces `dist/zcode.cjs`, which works anywhere Node.js 24.14.0 is installed.
-- `npm run sea` attempts to turn that same bundle into a single executable.
-- If SEA breaks on a platform, the normal CLI artifact is still the fallback.
-
-## Commands
-
-```sh
-npm run bootstrap
-npm run dev -- --help
-npm run build
-npm run start -- doctor --json
-npm test
-npm run sea
-npm run sea -- --target linux-x64 --target win-x64
-npm run sea -- --all
-```
-
-## Project Layout
-
-```txt
-src/
-  cli/       command parsing and process wiring
-  core/      reusable runtime logic
-  ui/        terminal UI layer
-scripts/    build and optional SEA packaging scripts
-tests/      subprocess-level CLI tests
-```
-
-## Bootstrap
-
-Run `npm run bootstrap` after cloning the repository. It checks the local Node.js version, installs dependencies, and runs the full project check.
-
-## Plugin Development
-
-zcode plugins are local bundles that can contribute skills, custom commands, and MCP servers. The plugin surface is compatible with the Claude Code plugin layout, so existing plugin content can be reused with minimal changes.
-
-Plugin state lives under `~/.zcode/cli/plugins`:
-
-- `cache/`: installed marketplace plugin code and static files.
-- `data/<plugin-id>/`: persistent plugin data. MCP servers should write runtime output here, not into the plugin source directory.
-- `marketplaces/zcode-plugins-official/`: bundled and CDN partitions plus the merged metadata for the single official marketplace.
-
-This repository also ships built-in official plugins as workspace packages. The bundled Browser Use, Document Skills, Skill Creator, and ZCode Guide content plugins are default-enabled and appear as `browser-use@zcode-plugins-official`, `document-skills@zcode-plugins-official`, `skill-creator@zcode-plugins-official`, and `zcode-guide@zcode-plugins-official`. Runtime-heavy official plugins, and local-data migration plugins such as `ios-simulator@zcode-plugins-official`, `android-emulator@zcode-plugins-official`, and `restore-legacy-sessions@zcode-plugins-official`, are discovered by zcode but stay disabled until the user enables them.
+ZCode's Agent CLI provides an interactive terminal and non-interactive task execution. It is part of this pnpm workspace; build it from the repository root with the Node and pnpm versions in [mise.toml](../../mise.toml).
 
 
 ```sh
 ```sh
-zcode plugins list
-zcode plugins enable ios-simulator
-zcode plugins disable browser-use
-zcode plugins enable restore-legacy-sessions
-zcode plugins disable ios-simulator
-```
-
-For local plugin development, put the plugin in any directory, then add it to the user config. Local plugin dirs default to enabled for that config.
-
-```json
-{
-  "plugins": {
-    "enabled": true,
-    "dirs": ["/absolute/path/to/my-plugin"]
-  }
-}
-```
-
-### Manifest Compatibility
-
-zcode discovers the first manifest that exists:
-
-1. `.zcode-plugin/plugin.json`
-2. `.claude-plugin/plugin.json`
-
-`.zcode-plugin/plugin.json` uses the same field names as Claude Code. Use it only when zcode needs different metadata or runtime wiring. If the Claude manifest already works, a plugin can ship only `.claude-plugin/plugin.json`.
-
-MCP config can live directly in `.zcode-plugin/plugin.json` through `mcpServers`. This is useful when the Claude-compatible `.mcp.json` points at a different runtime, such as Bun source files, while zcode should run a built Node.js server from `dist/`. A plugin may provide both `.mcp.json` and manifest `mcpServers`; when the same server name appears in both places, `mcpServers` from the selected manifest wins.
-
-Supported fields in the current zcode plugin surface:
-
-- `name`, `version`, `description`, `author`, `license`
-- `skills`: relative folder or folders containing `SKILL.md` files
-- `commands`: relative folder or folders containing markdown custom commands
-- `mcpServers`: inline MCP server config, or a relative path to one
-- `userConfig`: option defaults used by `${user_config.key}` expansion
-
-Example `.zcode-plugin/plugin.json` with inline MCP config:
-
-```json
-{
-  "name": "ios-simulator",
-  "version": "0.1.0",
-  "skills": "skills",
-  "commands": "commands",
-  "mcpServers": {
-    "ios-simulator": {
-      "command": "node",
-      "args": ["${ZCODE_PLUGIN_ROOT}/dist/mcp/server.js"],
-      "cwd": "${ZCODE_PROJECT_DIR}",
-      "env": {
-        "PLUGIN_DATA": "${ZCODE_PLUGIN_DATA}",
-        "DEFAULT_DEVICE": "${user_config.default_device}"
-      }
-    }
-  },
-  "userConfig": {
-    "default_device": {
-      "type": "string",
-      "default": "iPhone 16"
-    }
-  }
-}
-```
-
-zcode also reads plugin `.mcp.json` using Claude Code's wrapper shape. Use this when the same MCP config should be shared by Claude Code and zcode:
-
-```json
-{
-  "mcpServers": {
-    "my-server": {
-      "command": "node",
-      "args": ["${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"]
-    }
-  }
-}
-```
-
-Unsupported Claude plugin fields are ignored with diagnostics rather than executed. This includes `hooks`, `agents`, `outputStyles`, `lspServers`, `channels`, and `dependencies`.
-
-### Variables
-
-Plugin MCP config can use both zcode and Claude-compatible variable names:
-
-- `${ZCODE_PLUGIN_ROOT}` and `${CLAUDE_PLUGIN_ROOT}`
-- `${ZCODE_PLUGIN_DATA}` and `${CLAUDE_PLUGIN_DATA}`
-- `${ZCODE_PROJECT_DIR}` and `${CLAUDE_PROJECT_DIR}`
-- `${user_config.key}`
-- `${ZCODE_SOME_ENV}`
-
-Only environment variables with the `ZCODE_` prefix are expanded. Missing variables disable the affected MCP server and produce a plugin diagnostic.
-
-### Recommended Layout
-
-```txt
-my-plugin/
-  .claude-plugin/plugin.json
-  .zcode-plugin/plugin.json
-  .mcp.json
-  skills/
-    my-skill/SKILL.md
-  commands/
-    my-command.md
-  src/
-```
-
-Keep reusable content in Claude-compatible locations. Add a `.zcode-plugin/plugin.json` only for zcode-specific package names, built artifacts, or command paths. For MCP servers, prefer Node's normal package build and `bin` output when targeting zcode-cli, and keep all process/file/network side effects inside the MCP server boundary.
-
-## MCP Configuration
-
-zcode reads MCP servers from the main JSON config. The default user config path is `~/.zcode/cli/config.json`; MCP entries live under `mcp.servers`. MCP is enabled by default, so `features.mcp` only needs to be set when you want an explicit on/off switch. The current CLI does not auto-discover standalone `mcp.json` or `.mcp.json` files outside enabled plugins.
-
-```json
-{
-  "features": {
-    "mcp": true
-  },
-  "mcp": {
-    "servers": {
-      "filesystem": {
-        "type": "stdio",
-        "command": "npx",
-        "args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
-        "cwd": ".",
-        "timeoutMs": 30000
-      },
-      "docs": {
-        "type": "http",
-        "url": "https://mcp.example.com/mcp",
-        "headers": {
-          "Authorization": "Bearer <token>"
-        }
-      },
-      "legacy-sse": {
-        "type": "sse",
-        "url": "https://mcp.example.com/sse",
-        "enabled": false
-      }
-    }
-  }
-}
+pnpm install --frozen-lockfile
+pnpm --filter @zcode/cli... build
+node apps/zcode-cli/packages/cli/dist/zcode.cjs doctor --json
 ```
 ```
 
 
-Supported server types:
-
-- `stdio`: requires `command`; accepts `args`, `cwd`, `env`, `enabled`, and `timeoutMs`. `cwd` is resolved from the active working directory, and the server process inherits zcode's environment plus any `env` overrides.
-- `http`: requires `url`; accepts `headers`, `enabled`, and `timeoutMs`.
-- `sse`: requires `url`; accepts `headers`, `enabled`, and `timeoutMs`.
-
-MCP tools are registered before the first model request and exposed as `mcp__<server>__<tool>`. Use `/mcp list`, `/mcp status`, `/mcp connect <server>`, and `/mcp disconnect <server>` inside the CLI to inspect or manage configured servers for the current session.
+The default artifact is a Node.js bundle with adjacent runtime resources. SEA packaging is optional. The Agent CLI differs from the root distribution launcher, which also supports Web startup.
 
 
-## Hooks Configuration
+See the [CLI usage guide (中文)](docs/usage/README.md) for setup, model configuration, permissions, sessions, MCP, skills, hooks, plugins, and reproducible batch tasks. The guide distinguishes current source behavior from older binaries and documents its verification limits.
 
 
-zcode reads hooks from the same main JSON config file as MCP, usually `~/.zcode/cli/config.json`. Hooks are disabled by default; set `hooks.enabled` to `true` and add process hooks under `hooks.events`.
-
-Supported hook events:
-
-- `SessionStart`: runs after session context is initialized and before the first normal prompt reaches the model. It can add context. Its matcher sees the source, such as `startup` or `resume`.
-- `UserPromptSubmit`: runs before the user prompt is written to message history or sent to the model. It can block the prompt with `continue: false` or add context. Its matcher sees the raw prompt text.
-- `PreToolUse`: runs before a client-side tool executes. It can deny, ask, allow, replace tool input, or add model-visible context. Its matcher sees the tool name.
-- `PermissionRequest`: runs when a tool needs approval. It can allow, deny, update permissions, or modify the pending tool input. Its matcher sees the tool name.
-- `PostToolUse`: runs after a tool succeeds and before the tool result is returned to the model. It can add context. Its matcher sees the tool name.
-- `PostToolUseFailure`: runs after a tool fails and before the failure is returned to the model. It can add recovery context. Its matcher sees the tool name.
-- `Stop`: runs when a turn is about to complete without another client-side tool call. It can add feedback and request one more model step with `continue: true`. Empty `continue: true` output is ignored, and repeated continuations are capped to avoid loops.
-
-Example:
-
-```json
-{
-  "hooks": {
-    "enabled": true,
-    "timeoutMs": 60000,
-    "maxOutputBytes": 32768,
-    "events": {
-      "SessionStart": [
-        {
-          "matcher": "startup|resume",
-          "hooks": [
-            {
-              "type": "process",
-              "command": "node",
-              "args": ["./scripts/session-start-hook.mjs"]
-            }
-          ]
-        }
-      ],
-      "PreToolUse": [
-        {
-          "matcher": "^(Bash|Write|Edit)$",
-          "hooks": [
-            {
-              "type": "process",
-              "command": "node",
-              "args": ["./scripts/pre-tool-hook.mjs"],
-              "timeoutMs": 5000
-            }
-          ]
-        }
-      ],
-      "Stop": [
-        {
-          "hooks": [
-            {
-              "type": "process",
-              "command": "node",
-              "args": ["./scripts/stop-hook.mjs"]
-            }
-          ]
-        }
-      ]
-    }
-  }
-}
-```
-
-Configuration shape:
-
-- `modelStream.idleTimeoutMs`: initial idle timeout between model SSE events. Defaults to `600000`.
-- `hooks.enabled`: enables configured hook execution. Defaults to `false`.
-- `hooks.timeoutMs`: default timeout for each hook process. Defaults to `60000`.
-- `hooks.maxOutputBytes`: stdout/stderr capture limit for hook processes. Defaults to `32768`.
-- `hooks.events.<EventName>`: an array of matcher groups. Groups run in config order.
-- `matcher`: optional JavaScript regular expression string. If omitted, the group matches all inputs for that event.
-- `hooks`: process hook list for the matcher group. Hooks run in order.
-- `type`: currently only `process` is supported.
-- `command`: executable to run, using argv execution rather than a shell string.
-- `args`: optional argv array.
-- `timeoutMs`: optional per-hook timeout override.
-- `statusMessage`: optional status label for future UI projection.
-
-Each process hook receives one JSON hook input on stdin and may print one JSON object to stdout. Empty stdout is treated as no-op. Non-JSON stdout, schema-invalid stdout, timeouts, and non-zero exits other than exit code `2` are recorded as hook failures and do not crash the turn by default. Exit code `2` is treated as an explicit block/deny request.
-
-Common stdout examples:
-
-```json
-{
-  "hookSpecificOutput": {
-    "hookEventName": "SessionStart",
-    "additionalContext": "Use the internal API migration checklist for this repository."
-  }
-}
-```
-
-```json
-{
-  "continue": false,
-  "reason": "Do not run destructive shell commands in this workspace.",
-  "hookSpecificOutput": {
-    "hookEventName": "PreToolUse",
-    "permissionDecision": "deny",
-    "permissionDecisionReason": "Blocked by project hook."
-  }
-}
-```
-
-```json
-{
-  "continue": true,
-  "hookSpecificOutput": {
-    "hookEventName": "Stop",
-    "additionalContext": "Before finalizing, verify that the answer mentions test coverage."
-  }
-}
-```
+Useful entry points:
 
 
-## Packaging Strategy
+- [Quick start and packaging](docs/usage/01-quickstart.md)
+- [Model and runtime configuration](docs/usage/03-config.md)
+- [Plugin development](docs/usage/10-plugins.md)
+- [Hooks and workspace trust](docs/usage/09-hooks.md)
+- [Batch tasks and trajectory capture](docs/usage/13-automation.md)
+- [Design specifications](docs/design/v2/)
+- [Contributor instructions](AGENTS.md)
 
 
-1. Start with the normal Node CLI bundle from `npm run build`.
-2. `npm run sea` builds the current host target by default.
-3. Use `npm run sea -- --target <platform-arch>` or `npm run sea -- --all` for cross-target SEA packaging.
-4. SEA target Node.js binaries are downloaded from the official Node.js release for the current `process.versions.node` and verified against `SHASUMS256.txt`.
-5. Keep native addons and runtime dynamic imports out of the core CLI until SEA compatibility is proven.
-6. Add richer TUI libraries later only behind a compatibility spike.
+Run `pnpm --filter @zcode/cli dev` for source development. CLI code validation follows the contributor instructions; CLI tests are separate from the root unit-test suite.

+ 4 - 0
apps/zcode-cli/docs/design/v2/commands.md

@@ -62,6 +62,10 @@ ZCode protocol client 通过协议原生能力承载 session/config 操作,因
 - `goal`: 对应 `/goal [pause|resume|clear|replace <objective>|<objective>]`,由 bootstrap 本地读写 session goal;已有目标时 `/goal <objective>` 与 `/goal replace <objective>` 都按替换处理,并继续通过兼容 `target_changed` / `_meta.zcode.target` 投影状态;`/target` 只作为输入兼容别名,不广播给新客户端。
 - `goal`: 对应 `/goal [pause|resume|clear|replace <objective>|<objective>]`,由 bootstrap 本地读写 session goal;已有目标时 `/goal <objective>` 与 `/goal replace <objective>` 都按替换处理,并继续通过兼容 `target_changed` / `_meta.zcode.target` 投影状态;`/target` 只作为输入兼容别名,不广播给新客户端。
 - `skill`: 对应 `/skill <name> [task]`,由 bootstrap 改写成显式 `Skill` tool 调用要求;ZCode app-server 侧 skill discovery 仍由协议原生 skill UI 承载,不把 `/skill` 裸命令解释成列表。
 - `skill`: 对应 `/skill <name> [task]`,由 bootstrap 改写成显式 `Skill` tool 调用要求;ZCode app-server 侧 skill discovery 仍由协议原生 skill UI 承载,不把 `/skill` 裸命令解释成列表。
 
 
+App 的「计划模式」是 Composer 本地列表操作,选中复用标准 Plan 开关;协议目录不再广播
+`/plan [task]`,CLI 不提供对应的 prompt 展开。`plan` 保持保留名,避免自定义命令接管该入口。
+App 的具体交互见 [计划模式快捷入口](../../../../../docs/plan-slash-command.md)。
+
 ZCode app-server `/help` 只展示 ZCode app-server 已广播的命令,不能把 local-only 的 `/mode`、`/model`、`/resume`、`/mcp` 等命令混入,避免 client 看到不可执行的本地 TUI 操作。
 ZCode app-server `/help` 只展示 ZCode app-server 已广播的命令,不能把 local-only 的 `/mode`、`/model`、`/resume`、`/mcp` 等命令混入,避免 client 看到不可执行的本地 TUI 操作。
 
 
 `/btw` 暂不进入 ZCode app-server `available_commands_update`。ZCode app-server 客户端需要 side-result UI 后,应通过 `zcode.dev/session/sideQuestion` 扩展方法请求旁路回答,而不是把 `/btw` 作为普通 prompt command 广播或注入主会话。
 `/btw` 暂不进入 ZCode app-server `available_commands_update`。ZCode app-server 客户端需要 side-result UI 后,应通过 `zcode.dev/session/sideQuestion` 扩展方法请求旁路回答,而不是把 `/btw` 作为普通 prompt command 广播或注入主会话。

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

@@ -102,6 +102,9 @@ capability checks:
 - Ctrl+C exits the fullscreen TUI only after the user presses it twice in the
 - Ctrl+C exits the fullscreen TUI only after the user presses it twice in the
   confirmation window. The first press shows `Press Ctrl-C again to exit.`, and
   confirmation window. The first press shows `Press Ctrl-C again to exit.`, and
   the confirmed second press aborts active work before closing the UI.
   the confirmed second press aborts active work before closing the UI.
+- The startup screen owns Ctrl+C only while initialization is pending. Before
+  mounting the ready app, unmount the startup tree and release its keyboard
+  listener. After handoff, only the app handles the two-press exit sequence.
 - Escape never exits the fullscreen TUI. It pauses active output by cancelling
 - Escape never exits the fullscreen TUI. It pauses active output by cancelling
   the active turn when one is running, keeps approval/selection local cancel
   the active turn when one is running, keeps approval/selection local cancel
   semantics, and is otherwise a no-op status hint.
   semantics, and is otherwise a no-op status hint.

+ 10 - 1
apps/zcode-cli/docs/design/v2/local-setting-migrations.md

@@ -39,6 +39,14 @@ Older builds may have written `user/default/model/reasoningLevel`. Current code
 
 
 SQLite migrations use a ledger table:
 SQLite migrations use a ledger table:
 
 
+R3 的 `0024_session_database_identity` 接管 Source Server 曾直接创建的
+`zcode_database_identity`。Agent 与 Source 通过 `@zcode/shared/sqlite-migrations`
+复用冻结 SQL 和记账原语,保持已有 migration 的 checksum 算法与错误类型。
+Source 在 Agent 尚未启动时只应用该独立附加表迁移;后续 Agent 初始化补齐自己的
+其他版本。两种先后顺序都在同一 `schema_migration` 中记录一次。结构接管保留既有
+identity,不生成新代际;generation 的选择、备份谱系和恢复规则仍属于 Source 合并计划。
+事务内 SQL 或记账失败均回滚;历史记录不修改、不手工补写成功状态。
+
 ```sql
 ```sql
 create table schema_migration (
 create table schema_migration (
   id text primary key,
   id text primary key,
@@ -51,7 +59,8 @@ create table schema_migration (
 Migration rules:
 Migration rules:
 
 
 - Migrations are append-only and run in deterministic order.
 - Migrations are append-only and run in deterministic order.
-- Each migration declares the app version that introduced it; future migrations use their own version while historical entries keep their original version.
+- The CLI migration registry uses unique full IDs and unique four-digit numeric prefixes in increasing order. Registry tests enforce these rules before release.
+- Each migration declares the CLI version that introduced it; future migrations use their own version while historical entries keep their original version. This is not the running desktop version.
 - Each migration is wrapped in `begin immediate` / `commit` so concurrent CLI startups serialize schema writes.
 - Each migration is wrapped in `begin immediate` / `commit` so concurrent CLI startups serialize schema writes.
 - Applied migrations are checked by `id` and `checksum`. A checksum mismatch is a startup error because historical migration SQL must not be edited in place.
 - Applied migrations are checked by `id` and `checksum`. A checksum mismatch is a startup error because historical migration SQL must not be edited in place.
 - Migration SQL must be idempotent where practical, because old databases can already contain tables created by pre-ledger builds.
 - Migration SQL must be idempotent where practical, because old databases can already contain tables created by pre-ledger builds.

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

@@ -198,6 +198,7 @@ user row 之后。
 - `expectedTurnId` mismatch 被拒绝并发 `turn_steer_rejected`。
 - `expectedTurnId` mismatch 被拒绝并发 `turn_steer_rejected`。
 - empty input 被拒绝。
 - empty input 被拒绝。
 - compact/rewind turn 被拒绝为 `turn_not_steerable`。
 - compact/rewind turn 被拒绝为 `turn_not_steerable`。
+- 模型创建失败轮只落库已接纳输入,不进入 model step,guide 无法被消费;同样拒绝为 `turn_not_steerable`,调用方改走队列。
 - queued/drained events 顺序稳定,payload 包含 pending input id 和 target turn id。
 - queued/drained events 顺序稳定,payload 包含 pending input id 和 target turn id。
 - reducer 能从 queued/drained/discarded 重建 `pendingSteerInputs` 作为 live/diagnostic projection。
 - reducer 能从 queued/drained/discarded 重建 `pendingSteerInputs` 作为 live/diagnostic projection。
 - resume 不恢复 queued-but-not-drained input,也不能把历史 queued event 注入下一次 model request。
 - resume 不恢复 queued-but-not-drained input,也不能把历史 queued event 注入下一次 model request。

+ 30 - 0
apps/zcode-cli/docs/design/v2/message-attachments.md

@@ -502,6 +502,36 @@ ZCode app-server 当前支持 `text` 和 `resource_link`。下一步:
 
 
 ## Session Store 与恢复
 ## Session Store 与恢复
 
 
+### 首发与冷恢复一致性
+
+同一模型配置、相同可恢复附件事实下,普通发送、队列消费和 resume / rewind / fork
+恢复必须共用用户消息组装逻辑。正文在前,普通附件按提交顺序排列,粘贴图片在后;
+文本文件仍投影为独立 `prompt_attachment`,不改变 synthetic reminder 或空正文锚点语义。
+图片是否来自粘贴由持久化的附件来源决定,不能由恢复后的临时媒体 `source.kind` 判断。
+
+```text
+CLI / Desktop / mobile 输入 → Agent 解析 → 统一用户消息组装 → provider 投影
+                                  ↓
+                        TextPart + FilePart(唯一持久事实)
+                                  ↓
+resume / rewind / fork → hydrate 内容 → 同一用户消息组装 → provider 投影
+```
+
+路径引用附件保存 `metadata.pathReferenceText`,内容是首次发送给模型的完整三行说明,
+包括路径、降级原因和读取提示。恢复优先使用这份原文,不重新读取文件,也不根据当前
+解析规则重新生成文案。`preview` 仍表示文件内容预览,不复用为附件说明字段。
+该可选字段随既有 FilePart JSON 保存,无需数据库迁移;消费时校验它为字符串。
+
+旧消息同样使用统一顺序。若没有有效的 `pathReferenceText`,保留既有单行占位,
+不猜测丢失的原因、不回填或重写历史。旧历史首次切换到修复后的投影可能改变缓存前缀;
+新保存的消息必须在热态与冷恢复后的最终 provider 请求中保持附件顺序和说明文本一致。
+媒体 artifact 缺失、模型能力变化和 compact 的既有降级规则仍适用。
+
+回归覆盖路径引用、剪贴板文本、PDF、本地图片与粘贴图片混排、video、纯文本及附件单独发送;
+同时覆盖队列消费、MCS 开关、实际 SQLite 关闭重开以及最终 provider payload。
+Desktop 冷恢复通过发送附件、继续对话、重启并续发验证;mobile replayable 使用同一 Agent
+持久事实,不新增客户端消息组装状态。
+
 持久化时:
 持久化时:
 
 
 - 用户原文保存为 text part。
 - 用户原文保存为 text part。

+ 79 - 26
apps/zcode-cli/docs/design/v2/model/provider-endpoint-routing.md

@@ -31,10 +31,10 @@ bootstrap process registry(endpoint origin + network policy)
 
 
 静态实现保持既有开源网关行为:
 静态实现保持既有开源网关行为:
 
 
-| 精确匹配的 HTTPS 端点 | 当前 runtime ZCode origin 下的目标路径 |
-| --- | --- |
-| `open.bigmodel.cn/api/anthropic/v1/messages` | `/api/v1/ultra/anthropic/v1/messages` |
-| `api.z.ai/api/anthropic/v1/messages` | `/api/v1/ultra-zai/anthropic/v1/messages` |
+| 精确匹配的 HTTPS 端点                        | 当前 runtime ZCode origin 下的目标路径    |
+| -------------------------------------------- | ----------------------------------------- |
+| `open.bigmodel.cn/api/anthropic/v1/messages` | `/api/v1/ultra/anthropic/v1/messages`     |
+| `api.z.ai/api/anthropic/v1/messages`         | `/api/v1/ultra-zai/anthropic/v1/messages` |
 
 
 默认端口、主机大小写、末尾 `/` 与 query 的处理遵循下文匹配规则;其它协议、端口、路径、子域和
 默认端口、主机大小写、末尾 `/` 与 query 的处理遵循下文匹配规则;其它协议、端口、路径、子域和
 第三方 Provider 不改写。origin 复用 `resolveRuntimeZCodeEndpointOrigin`,不增加用户配置或环境变量。
 第三方 Provider 不改写。origin 复用 `resolveRuntimeZCodeEndpointOrigin`,不增加用户配置或环境变量。
@@ -67,11 +67,13 @@ GET https://zcode.z.ai/api/v1/agent/configs
       "mapping": [
       "mapping": [
         {
         {
           "from": "https://open.bigmodel.cn/api/anthropic/v1/messages",
           "from": "https://open.bigmodel.cn/api/anthropic/v1/messages",
-          "to": "https://zcode.z.ai/api/v1/proxy/anthropic/v1/messages"
+          "to": "https://zcode.z.ai/api/v1/ultra/anthropic/v1/messages",
+          "zcodeAuthorizationHeader": "X-Zcode-Authorization"
         },
         },
         {
         {
           "from": "https://api.z.ai/api/anthropic/v1/messages",
           "from": "https://api.z.ai/api/anthropic/v1/messages",
-          "to": "https://zcode.z.ai/api/v1/proxy/anthropic/v1/messages"
+          "to": "https://zcode.z.ai/api/v1/ultra-zai/anthropic/v1/messages",
+          "zcodeAuthorizationHeader": "X-Zcode-Authorization"
         }
         }
       ]
       ]
     }
     }
@@ -79,6 +81,35 @@ GET https://zcode.z.ai/api/v1/agent/configs
 }
 }
 ```
 ```
 
 
+### ZCode 网关身份头
+
+mapping 条目的可选字段 `zcodeAuthorizationHeader` 表示命中该条目时向最终 ZCode 网关请求附加
+登录身份。字段值大小写不敏感地必须等于 `X-ZCode-Authorization`;客户端始终使用规范名称:
+
+```http
+X-ZCode-Authorization: Bearer <zcodejwt>
+```
+
+身份头仅允许发送到当前 runtime ZCode origin 下的两个路径族:
+
+- `/api/v1/ultra` 本身及其子路径;
+- `/api/v1/ultra-zai` 本身及其子路径。
+
+路径按 URL segment 判断;`/api/v1/ultra-other` 不属于 `/api/v1/ultra`。携带身份字段的条目如果
+目标 origin 或路径不满足限制,整份新快照拒绝并保持上一份可用快照。没有该字段的既有 mapping
+继续遵循原路由规则。
+
+JWT 唯一来源是当前 Environment 凭据存储中的 `zcodejwttoken`。路由命中后按请求读取,不缓存 JWT:
+
+- 有非空 JWT 时附加身份头;已带 `Bearer` 前缀时不重复添加;
+- 未登录、JWT 缺失/空白或凭据读取失败时仍完成既有 URL 路由,但不附加身份头;
+- JWT 表示当前 Environment 的 ZCode 登录身份,与模型 Provider Token/API Key 相互独立,不要求账号代次一致;
+- 直连请求、未声明身份字段的 mapping 和其它 ZCode API 不读取或发送 JWT。
+
+SSH、WSL 与 Docker 的目标 Environment 已通过 Provider Provisioning 的凭据 allowlist 同步
+`zcodejwttoken`,因此远程 Source Server 与本地 CLI 使用相同的目标端读取逻辑;不新增
+Host 到 CLI 的协议字段,也不修改 OAuth 凭据格式、登录回滚或 Provider 请求鉴权材料。
+
 ## 边界
 ## 边界
 
 
 | 项目         | 约束                                                                                     |
 | 项目         | 约束                                                                                     |
@@ -88,7 +119,7 @@ GET https://zcode.z.ai/api/v1/agent/configs
 | 不生效请求   | WebFetch、MCP、OAuth、插件、Bash/tool、Desktop/Web renderer、`custom` provider transport |
 | 不生效请求   | WebFetch、MCP、OAuth、插件、Bash/tool、Desktop/Web renderer、`custom` provider transport |
 | 配置 owner   | ZCode CLI 进程内共享 routing registry                                                    |
 | 配置 owner   | ZCode CLI 进程内共享 routing registry                                                    |
 | 持久化       | 无;进程重启后重新读取                                                                   |
 | 持久化       | 无;进程重启后重新读取                                                                   |
-| 协议/配置    | 私有 requestAuth 增加可选 apiKeyId,不新增用户配置或环境变量                             |
+| 协议/配置    | 私有 requestAuth 仅保留既有可选 apiKeyId,不新增协议字段、用户配置或环境变量             |
 
 
 桌面 `desktop-continuous` 与手机 `web-remote-replayable` 仍只描述 session/task 消息交付。
 桌面 `desktop-continuous` 与手机 `web-remote-replayable` 仍只描述 session/task 消息交付。
 本能力只修改 Agent 到模型 provider 的最终 HTTP 目的地,不改变 stream、snapshot、queue、owner、
 本能力只修改 Agent 到模型 provider 的最终 HTTP 目的地,不改变 stream、snapshot、queue、owner、
@@ -134,6 +165,7 @@ ProviderEndpointRoutingPort.resolve
 - 配置请求最长 3 秒、响应体最长 256 KiB。
 - 配置请求最长 3 秒、响应体最长 256 KiB。
 - 刷新失败后 30 秒内不再发起配置请求;已有快照可继续使用到下一次成功刷新,冷启动无快照则直连。
 - 刷新失败后 30 秒内不再发起配置请求;已有快照可继续使用到下一次成功刷新,冷启动无快照则直连。
 - 单个模型请求取消时必须立刻停止等待,但不能取消其他请求共享的配置刷新。
 - 单个模型请求取消时必须立刻停止等待,但不能取消其他请求共享的配置刷新。
+- 身份 mapping 命中后的 JWT 读取属于同一请求取消边界;取消必须立即拒绝,迟到的读取结果不得继续发送请求。
 
 
 ## 配置请求与校验
 ## 配置请求与校验
 
 
@@ -185,6 +217,8 @@ requestAuth.apiKeyId --explicit ID only-----------------+--> agent/configs GET
 3. `data` 是对象;`proxyEndpoint` 缺失或 `mapping` 为空表示合法空快照。
 3. `data` 是对象;`proxyEndpoint` 缺失或 `mapping` 为空表示合法空快照。
 4. mapping 最多 256 条,且整份通过校验;坏项、重复 `from` 或超限时整份拒绝。
 4. mapping 最多 256 条,且整份通过校验;坏项、重复 `from` 或超限时整份拒绝。
 5. `from` 与 `to` 都是 HTTPS URL,不含 username、password、query 或 fragment。
 5. `from` 与 `to` 都是 HTTPS URL,不含 username、password、query 或 fragment。
+6. `zcodeAuthorizationHeader` 缺失/空白时不附加身份;非空时必须是固定名称,且 `to` 必须命中当前
+   runtime ZCode origin 的 `/api/v1/ultra` 或 `/api/v1/ultra-zai` 路径族。
 
 
 `data` 中与本功能无关的字段允许存在。`to` 是受信控制面的任意 HTTPS 目标;这意味着命中时原模型
 `data` 中与本功能无关的字段允许存在。`to` 是受信控制面的任意 HTTPS 目标;这意味着命中时原模型
 鉴权头与请求内容会发送到该目标,服务端配置发布权限必须按敏感控制面管理。
 鉴权头与请求内容会发送到该目标,服务端配置发布权限必须按敏感控制面管理。
@@ -195,7 +229,9 @@ requestAuth.apiKeyId --explicit ID only-----------------+--> agent/configs GET
 - URL parser 负责 scheme/hostname 大小写和默认端口归一化;除根路径外,末尾 `/` 视为等价。
 - URL parser 负责 scheme/hostname 大小写和默认端口归一化;除根路径外,末尾 `/` 视为等价。
 - 匹配忽略模型请求 query;命中后用完整 `to` 替换目标,并把原 query 原样附加到 `to`。
 - 匹配忽略模型请求 query;命中后用完整 `to` 替换目标,并把原 query 原样附加到 `to`。
 - 不做 hostname-only、前缀或通配匹配,避免一个映射意外接管同域其它 API。
 - 不做 hostname-only、前缀或通配匹配,避免一个映射意外接管同域其它 API。
-- method、headers、body、AbortSignal 和响应 stream 必须保持不变;最终 `Host` 由 fetch 按目标 URL 生成。
+- method、既有 headers、body、AbortSignal 和响应 stream 必须保持不变;最终 `Host` 由 fetch 按目标 URL 生成。
+- 路由决策声明的身份 header 必须覆盖 Request、URL、string 三种 fetch 输入形态,包括没有
+  `init.headers` 的调用;不得依赖 SDK 恰好提供 headers。
 - URL 重写必须早于 HTTP proxy/No Proxy 解析,使出口策略按最终目标判断。
 - URL 重写必须早于 HTTP proxy/No Proxy 解析,使出口策略按最终目标判断。
 - 后续 Model 创建使用的新 provider/model 配置不能丢失注入的 routing port;已创建 Model 的执行事实保持冻结。
 - 后续 Model 创建使用的新 provider/model 配置不能丢失注入的 routing port;已创建 Model 的执行事实保持冻结。
 
 
@@ -204,18 +240,18 @@ requestAuth.apiKeyId --explicit ID only-----------------+--> agent/configs GET
 - 新快照与上一快照内容变化时记录一次 `info`,只包含 mapping 数量。
 - 新快照与上一快照内容变化时记录一次 `info`,只包含 mapping 数量。
 - 刷新失败按 30 秒冷却窗口记录 `warn`,只包含错误类别和配置 endpoint host。
 - 刷新失败按 30 秒冷却窗口记录 `warn`,只包含错误类别和配置 endpoint host。
 - 单次命中只允许记录 `debug`,只包含源/目标 host 和规范化 path。
 - 单次命中只允许记录 `debug`,只包含源/目标 host 和规范化 path。
-- 禁止记录配置响应原文、query、headers、API Key、OAuth token、模型 body 或模型输出。
+- 禁止记录配置响应原文、query、headers、API Key、OAuth token、JWT、模型 body 或模型输出。
 
 
 ## Impact Brief
 ## Impact Brief
 
 
-| Field            | Value                                                                                                   |
-| ---------------- | ------------------------------------------------------------------------------------------------------- |
-| Developer intent | 通过同一个 port 装配动态路由或静态网关,保持公共模型请求链一致                                           |
-| Capability       | provider endpoint routing                                                                               |
-| Change layer     | commit-effect / persistence / recovery                                                                  |
-| Operating mode   | implementation-handoff                                                                                  |
+| Field            | Value                                                                                                      |
+| ---------------- | ---------------------------------------------------------------------------------------------------------- |
+| Developer intent | 通过同一个 port 装配动态路由或静态网关,保持公共模型请求链一致                                             |
+| Capability       | provider endpoint routing                                                                                  |
+| Change layer     | commit-effect / persistence / recovery                                                                     |
+| Operating mode   | implementation-handoff                                                                                     |
 | Primary seeds    | `createProviderEndpointRoutingPort`, `createProviderEndpointRoutingFetch`, `AiSdkModelExecution.bindModel` |
 | Primary seeds    | `createProviderEndpointRoutingPort`, `createProviderEndpointRoutingFetch`, `AiSdkModelExecution.bindModel` |
-| Out of scope     | UI、provider 配置持久化、非 provider 网络出口                                                           |
+| Out of scope     | UI、provider 配置持久化、非 provider 网络出口                                                              |
 
 
 本能力没有 UI surface、草稿状态或用户提交动作。权威 owner 是进程内 routing registry;
 本能力没有 UI surface、草稿状态或用户提交动作。权威 owner 是进程内 routing registry;
 Model execution、workflow child 与 script workflow child 只持有同一个 port 引用。必须检查的下游是
 Model execution、workflow child 与 script workflow child 只持有同一个 port 引用。必须检查的下游是
@@ -230,13 +266,13 @@ provider fetch 组合顺序和所有默认 model adapter 创建路径;WebFetch
 
 
 新增实现替换验收:
 新增实现替换验收:
 
 
-| Case | Setup / Action | Assertions |
-| --- | --- | --- |
-| PER-019 | 两个官方端点、默认端口、末尾斜线、query | 静态目标路径正确,query 不变,远端配置调用数为零 |
-| PER-020 | 不同 scheme/host/port/path 和第三方 URL | 静态实现原样返回,不扩大匹配范围 |
-| PER-021 | 静态 port 经公共 wrapper 发送 Request/URL/string | method/body/auth/signal/response 不变,旧 Host 删除 |
-| PER-022 | 同 endpoint/network 重复创建,或改变 network | 工厂共享或隔离符合现有进程 registry 契约 |
-| PER-023 | 替换 edition 后构建并实际发送模型请求 | 默认装配走静态网关,动态源码缺席,公共调用链与测试保留 |
+| Case    | Setup / Action                                   | Assertions                                             |
+| ------- | ------------------------------------------------ | ------------------------------------------------------ |
+| PER-019 | 两个官方端点、默认端口、末尾斜线、query          | 静态目标路径正确,query 不变,远端配置调用数为零       |
+| PER-020 | 不同 scheme/host/port/path 和第三方 URL          | 静态实现原样返回,不扩大匹配范围                       |
+| PER-021 | 静态 port 经公共 wrapper 发送 Request/URL/string | method/body/auth/signal/response 不变,旧 Host 删除    |
+| PER-022 | 同 endpoint/network 重复创建,或改变 network     | 工厂共享或隔离符合现有进程 registry 契约               |
+| PER-023 | 替换 edition 后构建并实际发送模型请求            | 默认装配走静态网关,动态源码缺席,公共调用链与测试保留 |
 
 
 PER-019—023 与以下动态用例先于实现更新。动态测试继续覆盖缓存、失败、取消和 ID 隔离;
 PER-019—023 与以下动态用例先于实现更新。动态测试继续覆盖缓存、失败、取消和 ID 隔离;
 本次没有 UI 交互变更,以真实 HTTP/模型执行集成与导出树运行验证入口,不新增 conversation 产品状态。
 本次没有 UI 交互变更,以真实 HTTP/模型执行集成与导出树运行验证入口,不新增 conversation 产品状态。
@@ -262,6 +298,18 @@ PER-019—023 与以下动态用例先于实现更新。动态测试继续覆盖
 | PER-017 | 来源 header builder 被错误注入敏感或未声明 header              | 冷启动刷新            | 只发送来源 allowlist;`x-api-key-id` 仍只能来自触发请求 |
 | PER-017 | 来源 header builder 被错误注入敏感或未声明 header              | 冷启动刷新            | 只发送来源 allowlist;`x-api-key-id` 仍只能来自触发请求 |
 | PER-018 | 携带 ID 的首个 waiter 取消,另一个 waiter 仍等待 single-flight | 刷新进行中取消        | 取消不终止共享 GET;配置 GET 使用启动刷新时的 ID        |
 | PER-018 | 携带 ID 的首个 waiter 取消,另一个 waiter 仍等待 single-flight | 刷新进行中取消        | 取消不终止共享 GET;配置 GET 使用启动刷新时的 ID        |
 
 
+身份头用例:
+
+| Case    | Setup / Action                            | Assertions                     |
+| ------- | ----------------------------------------- | ------------------------------ |
+| PER-024 | ultra mapping 声明身份字段,目标端有 JWT  | 最终请求携带固定 Bearer header |
+| PER-025 | ultra-zai mapping 声明大小写变体字段      | 规范化为固定 header 名         |
+| PER-026 | 未登录、JWT 空白或读取失败                | 仍路由,但不附加身份 header    |
+| PER-027 | mapping 未声明身份字段                    | 不读取 JWT,不附加 header      |
+| PER-028 | 身份字段指向其它 origin 或其它 ZCode path | 整份快照拒绝,旧快照保持       |
+| PER-029 | JWT 在两次请求之间变化                    | 下一次请求读取新值,不缓存身份 |
+| PER-030 | Request、URL、string 且无 init.headers    | 身份 header 均到达最终请求     |
+
 ### 测试维度与剪枝
 ### 测试维度与剪枝
 
 
 | 维度       | 等价类                                                  | 代表用例                           |
 | 维度       | 等价类                                                  | 代表用例                           |
@@ -270,9 +318,14 @@ PER-019—023 与以下动态用例先于实现更新。动态测试继续覆盖
 | ID 来源    | 有效 requestAuth.apiKeyId / 手工 Key / 来源 header 注入 | PER-011、PER-012、PER-017          |
 | ID 来源    | 有效 requestAuth.apiKeyId / 手工 Key / 来源 header 注入 | PER-011、PER-012、PER-017          |
 | ID 形态    | 显式参数 / 空白 / 控制字符或非 ASCII                    | PER-013、PER-014                   |
 | ID 形态    | 显式参数 / 空白 / 控制字符或非 ASCII                    | PER-013、PER-014                   |
 | 并发与取消 | 单请求 / single-flight 多 waiter / 单 waiter 取消       | PER-011、PER-003、PER-018          |
 | 并发与取消 | 单请求 / single-flight 多 waiter / 单 waiter 取消       | PER-011、PER-003、PER-018          |
-| fetch 输入 | URL/string / Request / Request + RequestInit override   | PER-012、PER-011、PER-013          |
-
-个人、团队账号和手工 Provider 使用实际 HTTP 回归:账号配置 GET 携带真实 ID,模型请求只携带 PAT;手工配置 GET 不携带凭据,模型请求仍用手工 Key。缓存过期后切换 ID,不能复用前一请求的 ID。Desktop/TUI/workflow 共享同一 adapter 与进程级 port,并由 bootstrap 协议测试覆盖 ID 透传。
+| fetch 输入 | URL/string / Request / Request + RequestInit override   | PER-012、PER-011、PER-013、PER-030 |
+| 身份状态   | 已登录 / 未登录 / 空白 / 读取失败 / 登录态变化          | PER-024、PER-026、PER-029          |
+| 身份目标   | ultra / ultra-zai / 其它 origin / 其它 path             | PER-024、PER-025、PER-028          |
+
+个人、团队账号和手工 Provider 使用实际 HTTP 回归:账号配置 GET 携带真实 ID;命中声明身份字段的
+ultra/ultra-zai mapping 时,目标 Environment 已登录则额外携带当前 ZCode JWT,未登录则保持原模型
+鉴权。手工配置 GET 仍不携带凭据,模型请求仍用手工 Key。缓存过期后切换 ID,不能复用前一请求的
+ID。Desktop/TUI/workflow 与 SSH/WSL/Docker Source Server 共享同一 adapter、目标端凭据和进程级 port。
 
 
 本功能不改变 conversation 产品状态,不进入 conversation case catalog、coverage matrix 或 formal-proof。
 本功能不改变 conversation 产品状态,不进入 conversation case catalog、coverage matrix 或 formal-proof。
 
 

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

@@ -14,6 +14,31 @@ app-server 模式默认开启模型流式输出。Vercel AI SDK 的 `streamText(
   completion,并自动重试 **最多 1 次**。该重试复用统一退避和状态事件,但不占用
   completion,并自动重试 **最多 1 次**。该重试复用统一退避和状态事件,但不占用
   core stream recovery budget;如果 adapter 的 `maxAttempts` 已禁止下一次物理请求,
   core stream recovery budget;如果 adapter 的 `maxAttempts` 已禁止下一次物理请求,
   则不重试。
   则不重试。
+- 新增例外只覆盖上下文超限、拒绝和内容过滤:`finishReason` 或 `rawFinishReason` 命中
+  `context_exceeded`、`context_length_exceeded`、`context_window_exceeded`、
+  `model_context_exceeded`、`model_context_window_exceeded`、`prompt_too_long`,
+  或 `refusal`、`content-filter`、`content_filter` 时,
+  即使 text/reasoning/tool/usage 全为零,也不得叠加 generic empty completion retry。
+  判据只做 trim 和大小写归一化,不靠任意错误文本的模糊匹配扩展范围。
+  非流式请求读取 SDK 顶层 `rawFinishReason`,兼容已有 `providerMetadata.rawFinishReason`;
+  流式 finish 同样支持这两种来源;用于空响应判定,不修改原有 metadata 透传及业务错误识别。
+  原有 `stop`、`tool-calls`、`tool_calls` 的空响应处理保持不变。
+  普通 `length`、`max_tokens`、`max_output_tokens` 及 `other`/`unknown`
+  保持此前判定。缺少 finish 的 EOF 检测与恢复不变。
+- 明确上下文超限且没有正文、有效 reasoning(包括 opaque metadata)或完整工具调用时,
+  Adapter 在成功 finish/completed 前转换成已有 `ModelContextExceeded`,发布一次
+  `model_request_failed`,由 Core 原有 catch 决定 Reactive Compact 和重试,不追加 Continue。
+  判定与 usage 是否为零无关。其余响应保持原样,包括任何带有效输出的上下文限制响应;
+  Adapter 不判断 Continue,不迁移或删除 Core 原有成功响应兼容分支。
+  错误保留 provider 已报告 usage,由既有失败事件记账;不伪造 `ModelComplete`。
+  compact 自身复用现有错误/fallback 边界,不改变恢复次数及取消语义。
+
+```text
+provider completion -> adapter 检查终止原因
+                       | 明确上下文超限 + 无有效输出 -> failed -> core 既有 catch / Reactive Compact
+                       | 其余响应 -> 原有空响应重试判定及调用方处理
+```
+
 - generic empty completion 的第一次 attempt 在重试前不得向 core 释放 `start`、
 - generic empty completion 的第一次 attempt 在重试前不得向 core 释放 `start`、
   `finish` 或其他仅属于该 attempt 的事件;第二次仍为空时保持现有行为,由 core
   `finish` 或其他仅属于该 attempt 的事件;第二次仍为空时保持现有行为,由 core
   生成 `empty_model_response` 可见错误。非流式 `generateText` 与流式 SSE 使用同一
   生成 `empty_model_response` 可见错误。非流式 `generateText` 与流式 SSE 使用同一
@@ -131,6 +156,15 @@ core recovery 的可观测性要求:
   成功时最终只看到第二次的有效输出,第二次仍为空时仍生成 `empty_model_response`。
   成功时最终只看到第二次的有效输出,第二次仍为空时仍生成 `empty_model_response`。
 - 非流式 `generateText` 返回同样的 zero-output empty completion 时,应只重试一次;
 - 非流式 `generateText` 返回同样的 zero-output empty completion 时,应只重试一次;
   第二次成功返回有效结果,或第二次仍为空并把既有空响应错误交给 core。
   第二次成功返回有效结果,或第二次仍为空并把既有空响应错误交给 core。
+- 流式和非流式的零输出 `rawFinishReason=model_context_window_exceeded` 不产生
+  adapter retry,转为一次超窗失败,保留已报告 usage;normalized finish 为 `length`
+  或 `other` 时均成立。上下文超限同义标记同样处理;有有效输出时无论 finish 是否可续写均原样返回。
+  拒绝、内容过滤、普通输出限制与未知标记保持原行为。
+- 桌面 I73 从无账号态通过 Personal Provider UI 建立回放前置,不播种无关的假 OAuth 凭据,
+  避免登录过期弹窗遮挡被测交互。Provider 只初始化一次,每个场景通过 UI 新建任务并选择模型,
+  不要求与重试语义无关的思考档位。同时验证明确上下文限制的空 SSE:先准备可压缩历史,
+  再严格执行超窗失败 → compact → 恢复三次请求,不追加 Continue;最终正常回复并回到 idle,
+  失败请求、compact 和恢复请求的 usage 独立记录、汇总不重不漏。
 - compact `preserveProviderStreamBoundaries=true` 的空 completion 不得因普通主请求
 - compact `preserveProviderStreamBoundaries=true` 的空 completion 不得因普通主请求
   规则增加额外重试。
   规则增加额外重试。
 - 重试后的第二次 stream 成功时,最终只向 core 产出成功事件。
 - 重试后的第二次 stream 成功时,最终只向 core 产出成功事件。

+ 4 - 2
apps/zcode-cli/docs/design/v2/multi-workspace.md

@@ -1,5 +1,7 @@
 # Multi-Workspace / `--add-dir` 设计草案 v2
 # Multi-Workspace / `--add-dir` 设计草案 v2
 
 
+> 历史草案:2026-09 虚拟项目重构没有采用本文的多工作区模型。现行方案是 Host 解析项目 roots 后经协议只传目录列表(`additionalDirectories`),CLI 不感知项目,附加目录仅供 skills / commands / subagents 与可写范围消费;见 `docs/superpowers/specs/2026-09-09-virtual-project-design.md` 第 4.3 节。下文只作历史记录。
+
 ## 目标
 ## 目标
 
 
 给 ZCode CLI 增加显式多工作区能力,让一次 session 可以同时面向一个主工作区和多个额外工作区。
 给 ZCode CLI 增加显式多工作区能力,让一次 session 可以同时面向一个主工作区和多个额外工作区。
@@ -63,9 +65,9 @@
 type WorkspaceRootRole = "primary" | "additional";
 type WorkspaceRootRole = "primary" | "additional";
 
 
 interface WorkspaceRoot {
 interface WorkspaceRoot {
-  path: string;          // canonical absolute path
+  path: string; // canonical absolute path
   role: WorkspaceRootRole;
   role: WorkspaceRootRole;
-  label?: string;        // basename by default
+  label?: string; // basename by default
 }
 }
 
 
 interface WorkspaceScope {
 interface WorkspaceScope {

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

@@ -45,6 +45,19 @@ ready Android target, then start a GUI Android Emulator only when no target is
 ready. P0 does not expose a user-configurable UI backend; UI automation uses
 ready. P0 does not expose a user-configurable UI backend; UI automation uses
 Android SDK `adb` and UI Automator commands.
 Android SDK `adb` and UI Automator commands.
 
 
+## Marketplace classification
+
+The catalog's optional `publisherType` (`official` or `community`) describes who
+maintains a plugin within the ZCode marketplace. It does not grant trust or
+change installation identity, paths, or user/workspace configuration. Personal
+marketplaces remain personal regardless of their self-declared publisher type.
+
+Catalog `componentTypes` may advertise `ui` before installation. Installed UI
+capability comes from validated manifest `ui.surfaces`, including when disabled;
+`plugins/listUiSurfaces` continues to return only enabled entries. Store listing
+`category` remains the independent usage category. See the market interaction
+spec in the root `docs/plugins/` directory for presentation and scope semantics.
+
 ## Storage Layout
 ## Storage Layout
 
 
 ZCode stores plugin state under the CLI storage root:
 ZCode stores plugin state under the CLI storage root:

+ 199 - 3
apps/zcode-cli/docs/design/v2/tool/00-tool-change-chain.md

@@ -1,5 +1,157 @@
 # Tool Change Chain Spec
 # Tool Change Chain Spec
 
 
+## 自定义 Agent Memory 工具投影(2026-10-15)
+
+Runtime 从当前父轮 Agent definitions 快照派生有效工具,启动配置、注入 reader 和 Host
+每轮加载的 profiles 必须经过同一投影。Memory 启用且允许使用时,为声明 memory scope
+及显式 tools 的 profile 补齐 Write/Edit;未声明 tools 保持继承,disallowedTools 和权限过滤
+仍生效。不修改 Host 原始快照,不跨轮缓存工具,不增加延时或重试。回归检查三种配置来源、
+连续父轮、Memory 关闭和禁用工具;Desktop MEM08 验证 custom-agent 真实写入 Memory 文件。
+
+合并后登记工具结果结算、渠道回复及留白填充入口的模块边界;复用原契约与公开路径,不改变工具执行和持久化行为。
+
+上游新增的 FillWorkflowHole 与 ReplyToChannel 沿用非常驻内置工具的 deferred 分类。
+
+Local ToolSearch 描述明确搜索后的 `DeferredToolCall {name,input}` 调用方式,只用一个简短的
+TodoWrite 调用示例说明;常驻工具仍直接调用。只经既有曝光入口更新 Local description,
+不改变 Native 文案、结果格式或执行协议。校验示例参数及 CLI/PTY 冷恢复的最终 wire,
+合同见 [模型可见文案](19-tool-search.md#模型可见文案)。
+
+Local 逐项反馈与 compact 提升:引用投影按模型调用批次前可见定义去重,新展开 schema 的
+结果在 tool_result 内给出调用指引,纯重复结果给出已加载提醒。发现扫描同时读取有效 compact
+检查点;曝光、搜索、公告及包装准入
+共用提升后的分类,成功 compact 后以普通 tools 恢复已发现工具。保持真实引用持久化、
+Native/Off、执行生命周期和 Continue 记录链不变。验收详见 [ToolSearch spec](19-tool-search.md#local-逐项反馈与-compact-后提升)。
+已加载指引在 tool_result 内使用公共 `<system-reminder>` 包装;不生成 attachment,
+MCS 开关不改变其位置或角色。验证混合/纯重复/冷恢复的最终请求及模式对应的提示数量。
+首次展开的 deferred 定义在同一 tool_result 内合并追加 Loaded 调用指引,明确顶层 name/input;
+单工具使用 `Call it now`,多工具使用 `Call them now`;其余保留统一的
+`<tool name>` 占位、精确名称指引与复数结尾;
+只加强模型行动指引,不改变执行、结果成功状态或已加载提醒,不承诺定义永久有效。
+复用引用投影,Local 不再派生结果外成功提示;Native 保持原有提示。实际请求、Continue/compact
+记录共用同一投影标记,不改变常驻选择、Native/Off 或历史持久化。验证多工具去重、
+Hook 顺序、MCS、compact 提升及真实进程冷恢复的最终 wire。
+
+ToolSearch 四项补齐:Native 有效搜索结果在整批 tool_result 后派生成功提示;未发现 deferred 参数
+错误补精确 select、当前 schema 和模式调用方式;公告使用严格来源 attachment 参与 MCS 并
+保留增量 metadata;MCP select 支持原始/规范化短名。复用既有遍历、持久化和执行链,
+保持 callID、用户/媒体归属、Continue/compact 和桌面/手机交付边界。历史定义快照和
+unavailable schema 保留延期,不增加存储字段或改变引用过滤。合同见 [19-tool-search.md](19-tool-search.md)。
+Continue/compact 的请求记录重建复用本次投影的有效搜索结果 callID,避免漏掉派生成功提示;
+不增加历史扫描、深拷贝或存储字段,实际请求与执行链不变。
+未发现 deferred 工具的参数错误保留完整纠错段落:说明定义未加载与参数类型退化的关系,
+再给出精确 select 和当前 schema;仅 Local 追加包装调用说明。完整文本回归同时保护
+原始校验错误及已发现/Off/不存在工具的既有行为,不改变准入或执行。
+
+ToolSearch 删除/恢复公告仅描述当前可用性,不推断 MCP 连接状态或变化原因。
+正常与受限 turn 的增量比较、持久化、compact 及权限筛选保持原状;精确文案测试覆盖
+内置工具恢复、MCP 分组、30/31 个删除名称和混合增删,确保不附加未经证实的原因。
+
+App Settings ToolSearch 模式:配置 schema/patch -> 本地或远程 Host 偏好响应 -> Bootstrap
+runtime-materialization -> runtimeConfig.toolSearch。只在新建/冷恢复取值,热恢复及已有草稿
+不更新;fork/子 Agent 继承。CLI 参数、工具协议/执行/历史均不变。验证 Settings UI 保存到
+最终 provider wire 的真实 E2E,及旧字段缺省、主子作用域、冷恢复与 Host 权威源。
+缺省保持 Off;设置行底部显示实验性与原生模式供应商缓存支持不足时的用量风险,中英文一致,
+不覆盖用户已保存的模式。复用底部说明区域,验证默认关闭、说明可见与原有保存/恢复链路。
+
+Local ToolSearch 扩展沿用 [19-tool-search.md](19-tool-search.md) 的真实引用和发现检查点。
+`--toolsearch-mode` 替代旧 enable flag;Local 将连续引用在结果内合并展开为 functions 文本,
+两次 compact 之间的 tools 不随搜索发现增长;成功 compact 后检查点工具提升为普通 tools。DeferredToolCall 使用 `{name,input}`,仅转发当前允许的 deferred
+目标,在公共准入归一化为普通目标调用;内部历史与持久化只增加 modelCallWrapper 字面量,
+请求出口恢复原始包装,删除重复保存的 modelToolCall input。V4 scheduled 定稿目标身份;
+断流未调度时,已有 tool_call_closed 仅补齐包装工具行的目标名称与输入,不推进业务状态。
+Todo/microcompact/工具卡复用普通调用判断。重点验证原始参数隔离、调度/权限/Hook/媒体/turn-stop、
+pending 到终态重存、冷恢复/分支、六向模式切换和 Continue/compact 的原有生命周期。
+不保存 schema 快照、不新增 schema reminder、DB migration 或测试专用生产接口。
+流式预览与 Core 事件时序保持原状;展示层不从半截包装参数推测已准入目标。验证无 Scheduled
+的断流恢复、实时与冷恢复身份、普通工具及失效事件隔离、continuous/replayable 的完整行更新。
+请求内的引用过滤与 Local 展开共用一次历史投影;只复制内容实际变化的工具结果,
+同一工具定义在本次请求内只编码一次。发现集合仍先独立扫描,最终 provider render
+保留隔离拷贝;不改变公告时序、引用顺序或引入跨请求缓存。
+
+ToolSearch 的默认关闭、显式模式覆盖、结构化引用与冷恢复合同见
+[19-tool-search.md](19-tool-search.md)。发现状态仅从真实结果和有效 compact 检查点推导;
+关闭只修改请求投影,不新增数据库表列,不改变 MCP 初始化或主子权限边界。
+公共 tool metadata 同时接受既有字符串 modelContent 和 ToolSearch 结构化数组,避免失败 MCP
+工具在 V4 transcript 冷恢复时丢失 display;ToolSearch 写入与发现恢复仍严格校验数组。
+请求组装统一经 `prepareRuntimeProviderRequest` 执行一次 ToolSearch 准备,主/子 Agent、
+Goal、Memory 与 Compact 提供各自完整工具目录;消息投影不再隐式猜测启用状态。
+media 保持独立环节;公告在正常提醒阶段由原历史 owner 提交后再取请求快照,纯 max-token
+Continue 不检查或生成公告。Compact 根据保留历史与继续执行的工具作用域独立重建公告;
+请求准备只投影已有公告。公告正文与增量 metadata 随隐藏 synthetic 历史持久化,
+fork/resume/rewind 按有效历史原位恢复,不新增 session 级缓存。验证续写去重、配套 wire、Goal SQLite 状态和恢复边界。
+重试按 canonical 原始输入 ID 截断,公告及 Todo 等隐藏提醒不能成为重试边界;回归检查模型请求与冷恢复没有重复输入。
+公告 metadata 只记录 addedNames/removedNames/readdedNames 增量;从保留历史顺序推导
+当前已公告与曾完整列名集合,正文与 metadata 同源。删除按完整作用域工具池判断,
+避免 compact 保留增量尾部漏补名称、deferred 转 alwaysLoad 误报删除。内置 deferred 工具
+补齐 searchHint,不改变搜索排序、真实引用或发现检查点。
+内置工具仅 Agent/AskUserQuestion/Bash/Edit/Glob/Grep/Read/ReportFindings/Skill/ToolSearch/Write
+保留常驻资格;名单外工具在各自 metadata 声明 shouldDefer,不增加分类映射层。
+ReportFindings 尚未实现,Task 兼容入口继续对 provider 隐藏;注册、灰度、权限和执行不变。
+覆盖真实内置目录首轮曝光、搜索加载与关闭回退;MCP、provider 原生工具维持原有规则。
+Native ToolSearch 的 provider description、参数说明及增删/恢复公告文案使用默认配置。
+公告沿用 30 个删除名称阈值、
+MCP server 分组与 ambient 提示;仅修改模型文案,不扩展 MCP 生命周期或公告状态。
+ToolSearch 的 provider schema 将 query/max_results 都标为 required;执行链仍先通过
+runtime schema 补默认值 5。验证最终 wire required 和省略 max_results 的真实执行结果。
+ToolSearch 的引用块不参与普通文本截断;初次结果与 Hook 追加后的预算投影均保留引用和
+块顺序,仅限制文本。展示内容和字节统计由最终块派生,completed metadata 与冷恢复
+沿用真实结果;覆盖超过 100 KB 的搜索、批量 select、Hook 及 SQLite 恢复,不收紧输入范围。
+Compact 仅在候选工具支持实际启用 ToolSearch 时使用新策略;关闭时保留普通工具数量阈值,覆盖禁用、alwaysLoad 与 100 个工具边界的 Runtime 请求。
+插件 MCP 的 `.mcp.json`/manifest 经各 transport 配置转换时必须保留 `alwaysLoad`;
+验证插件发现到最终请求 schema 的透传,不改变 MCP 初始化、鉴权或工具权限。
+App MCP 配置转协议 DTO 同样保留布尔 `alwaysLoad`,覆盖 stdio/HTTP/SSE;
+未配置或非法值不生成字段,验证 JSON 传输与现有严格协议 schema,不扩张会话配置路径。
+
+2026-09-18 ToolSearch 测试补齐:PTY force/resume/continue 走真实终端输入;动态目录与
+尾部连续 compact 使用独立 Runtime/HTTP 集成 fixture,覆盖 streaming on/off 并检查原始历史。
+macOS 与 Windows 原生进程证据及手机待验证边界见根目录 coverage matrix;不改产品入口。
+同日补充 executor 执行边界、真实 Hook 结果 SQLite 冷恢复、搜索细分输入、开启状态空引用
+投影的单测。E2E/单测不得为测试修改生产实现或新增测试专用入口;只复用既有依赖契约。
+
+## Skill 通用名称埋点(2026-10-14)
+
+所有 `tool_name=Skill` 的 `agent_step` 增加 `skill_name`。不提取调度输入的请求名称,
+Skill handler 解析后通过既有 metadata 回调提供真实 `metadata.name`,沿
+`ToolCallResult/Error → tool.lifecycle.skillName → agent_step.skill_name` 传递。
+加载前失败/拒绝/停止、名称未解析或不符合遥测名称规则时使用 `unknown`。
+CLI fact、UI 兼容 metadata 与最终 `/report` 共用名称校验,禁止任意请求参数进入遥测;
+验收覆盖路径、URL、换行、模拟凭据与超长字符串的最终 HTTP 请求体。
+不调整模型输入输出、权限或工具执行;不新增状态 owner,桌面 continuous 与手机 replayable
+边界不变。字段、兼容与验收见根目录 `docs/monitoring/skill-agent-step-telemetry.md`。
+
+## TaskStop 查找失败提示
+
+`TaskStop` 精确查找未命中时,统一返回以下模型可见错误;不增加前缀匹配或 ID 格式校验:
+
+```text
+Invalid task ID "<id>". This lookup failure does not mean the task has completed or stopped; use the full task_id returned when the task started to stop it.
+```
+
+链路:`background_task_not_found → handler error (code: 1) → executor success: false → model isError: true`。
+查找失败不能证明目标任务已完成或停止;模型应使用启动时返回的完整 `task_id`。
+完整 ID 命中后的停止行为、其他错误、schema、权限、协议与 App 交互保持原样。
+回归覆盖短 ID、未知完整 ID 的失败文案及模型错误标记,并保留成功停止和其他失败分支断言。
+
+## 闲时后台执行(实施中)
+
+按根目录 `docs/off-peak-task/background-lifecycle-plan.md` 实施:Agent 显式、profile 默认及超时转后台,
+SendMessage 运行中投递/终态恢复,以及 Bash 显式/超时后台复用普通工具链。
+票据生命周期独立于工具执行:3102 使后续模型请求等待新票,本地 Bash 继续保存输出;
+换票只重试尚未提交结果的模型请求,不重放工具或原始 prompt。主轮结束后继续接收既有通知。
+真实用户输入接管后,新后台轮读取 Session Selection;已运行子轮保留本轮模型。
+输入 schema、权限、结果预算、通知包装、子轮 Bash 清理和桌面/手机交付边界不变。
+Workflow、递归闲时/定时任务和自动记忆提取的限制保留;重启不恢复后台进程或通知。
+验证覆盖换票并发、旧票迟到、用户接管、停止与任务取消、后台通知到达边界及两端交互。
+
+## 冷打开历史先显示(2026-10-09)
+
+持久化 tool 摘要由现有 V4 reducer 在 runtime 初始化前显示;工具详情、附件读取、App 交互
+与执行入口等待 runtime ready。工具声明、模型可见输入输出、权限和执行语义保持原样。
+初始化失败保留历史,显式重试复用完整 resume hook。状态与传输边界见根目录
+`docs/v4-refactor/17-cold-resume-runtime-activation.md`,桌面 continuous 与手机 replayable
+仍复用同一个 publisher,各自维持既有序号恢复语义。
+
 ## 工具内部模型请求的会话归因(2026-09-30)
 ## 工具内部模型请求的会话归因(2026-09-30)
 
 
 WebSearch、WebFetch processing、ReadSessionContext 的内部模型请求继承发起工具的宿主
 WebSearch、WebFetch processing、ReadSessionContext 的内部模型请求继承发起工具的宿主
@@ -98,7 +250,6 @@ interrupted 冷恢复,不保证原始输出。Desktop continuous 与手机 rep
 完整顺序见 [streaming recovery](../model/streaming-tool-execution-and-recovery.md#tool-result-settlement)。
 完整顺序见 [streaming recovery](../model/streaming-tool-execution-and-recovery.md#tool-result-settlement)。
 回归覆盖图片 Stop、真实 SQLite 锁、批次中途保存失败、媒体与 usage 失败、冷恢复和 checkpoint 取消。
 回归覆盖图片 Stop、真实 SQLite 锁、批次中途保存失败、媒体与 usage 失败、冷恢复和 checkpoint 取消。
 
 
-
 ## 目的
 ## 目的
 
 
 改动 tool 不是只改一个 handler 或 schema。tool 是 NL->Code 的核心边界,任何新增、删除、重命名、字段调整、执行语义调整、权限变化、输出变化、provider-native 化、后台化或 UI 展示变化,都必须沿同一条端到端链路核对。
 改动 tool 不是只改一个 handler 或 schema。tool 是 NL->Code 的核心边界,任何新增、删除、重命名、字段调整、执行语义调整、权限变化、输出变化、provider-native 化、后台化或 UI 展示变化,都必须沿同一条端到端链路核对。
@@ -136,8 +287,12 @@ desktop continuous 的 live 统计不能通过手机 replayable 恢复补发。
 ## 总原则
 ## 总原则
 
 
 离线 prompt-trajectory 转换只影响调试产物:从相邻真实请求补全 response 摘要遗漏的
 离线 prompt-trajectory 转换只影响调试产物:从相邻真实请求补全 response 摘要遗漏的
-thinking,并识别末尾 user block 追加。保留真实历史改写的分段,不改生产 tool descriptor、
-执行、缓存、权限或 UI 链路;合同见 [Model-IO trajectory](../../../plan/trajectory/model-io-to-anthropic-trajectory-tool.md)。
+thinking,并识别末尾 user block 追加。默认保留真实历史改写的分段;显式
+`--ignore-tool-search-changes` 仅在离线比较中忽略 ToolSearch 引用、占位文本、目录公告及
+成功引用结果批次后的对应 `Tool loaded.` 提示,普通同名文本仍参与比较;
+目录公告识别覆盖当前 Native/Local 文案,并保留旧日志格式的兼容性。
+输出仍保留最后真实请求并标注合成模式。不改生产 tool descriptor、执行、缓存、权限或
+UI 链路;合同见 [Model-IO trajectory](../../../plan/trajectory/model-io-to-anthropic-trajectory-tool.md)。
 
 
 CR-01(来源提示包装):SendMessage、RespondToCoordinator 与后台任务产出的正文只在
 CR-01(来源提示包装):SendMessage、RespondToCoordinator 与后台任务产出的正文只在
 provider user reminder 包装时复用 source sanitizer 中和嵌套 `system-reminder` 标签。
 provider user reminder 包装时复用 source sanitizer 中和嵌套 `system-reminder` 标签。
@@ -355,6 +510,7 @@ MCP 动态 tool 还需要额外确认:
 - 文件保真:`Edit` 是否保持原编码和原换行风格,`Write` 是否按完整内容写入,并且所有文件 I/O 都通过 `FileSystemPort`。
 - 文件保真:`Edit` 是否保持原编码和原换行风格,`Write` 是否按完整内容写入,并且所有文件 I/O 都通过 `FileSystemPort`。
 - 文件内容契约:`FileSystemPort.readTextFile` 返回给 core 的 text content 应是 LF 规范化后的 Unicode 逻辑内容,并通过 metadata 暴露原始 `encoding` 与 `lineEndings`;`Edit` / `Write` / `ApplyPatch` 需要保真写回时必须把这些 metadata 传回 adapter,而不是在 handler 中直接接触底层 bytes。
 - 文件内容契约:`FileSystemPort.readTextFile` 返回给 core 的 text content 应是 LF 规范化后的 Unicode 逻辑内容,并通过 metadata 暴露原始 `encoding` 与 `lineEndings`;`Edit` / `Write` / `ApplyPatch` 需要保真写回时必须把这些 metadata 传回 adapter,而不是在 handler 中直接接触底层 bytes。
 - 文本编码边界:filesystem adapter 负责 BOM、UTF-8、UTF-16LE 以及常见中文 legacy 编码(GB2312 / GBK / GB18030)的检测、解码和写回。模型可见工具说明只表达“复制 Read 的逻辑文本即可”,不要要求模型猜测或传入编码参数。新增编码能力必须覆盖读、范围读、编辑、完整写入、结构化 patch、不可编码字符失败和二进制误判保护。
 - 文本编码边界:filesystem adapter 负责 BOM、UTF-8、UTF-16LE 以及常见中文 legacy 编码(GB2312 / GBK / GB18030)的检测、解码和写回。模型可见工具说明只表达“复制 Read 的逻辑文本即可”,不要要求模型猜测或传入编码参数。新增编码能力必须覆盖读、范围读、编辑、完整写入、结构化 patch、不可编码字符失败和二进制误判保护。
+- 大文本采样边界:`4096` 字节样本末尾的 UTF-8 候选按缺少字节数补读后再严格校验;未完成状态不能直接确认 UTF-8,非法续字节进入原有 legacy 检测。正文继续共用流式 decoder。按 [Read 文本大文件预算](01-read.md#文本大文件预算) 覆盖短读、EOF、ASCII 前缀后的 GB 字符与附件最终 provider 请求;不把有限采样视为全文件编码保证。
 - 错误契约:未读、partial read、stale file、匹配失败、多处匹配、notebook、权限拒绝和文件过大必须有稳定错误码,不能依赖英文错误文本判断流程。
 - 错误契约:未读、partial read、stale file、匹配失败、多处匹配、notebook、权限拒绝和文件过大必须有稳定错误码,不能依赖英文错误文本判断流程。
 - 模型结果序列化:文件变更成功时只返回短确认文本;完整内容、diff 和 patch 留给内部 output、事件、UI projection 或 artifact。
 - 模型结果序列化:文件变更成功时只返回短确认文本;完整内容、diff 和 patch 留给内部 output、事件、UI projection 或 artifact。
 - Read 模型可见序列化:文本读取结果必须用专用 `formatModelContent` 输出 cat-n 风格行号文本,不得回退到 JSON 字符串化,否则 tab、换行等会被转义并污染后续 `Edit.old_string` 精确匹配。
 - Read 模型可见序列化:文本读取结果必须用专用 `formatModelContent` 输出 cat-n 风格行号文本,不得回退到 JSON 字符串化,否则 tab、换行等会被转义并污染后续 `Edit.old_string` 精确匹配。
@@ -1053,6 +1209,16 @@ replayable 保持原有交付链路。验证包含协议候选严格校验、Rea
 
 
 SendMessage / RespondToCoordinator 的来源呈现遵循 `../loop/turn-steering.md`:更新 coordinator 识别提示,保留历史前缀兼容与已有回复/继续工作合同。参数、权限、执行目标、background batch 与可见性边界不扩展;child 不获得 SendMessage,parent peer 的回复目标来自绑定 agent-id。验证工具描述、真实父子 Runtime 请求、冷恢复及 BG25/O18/O19 fixture。
 SendMessage / RespondToCoordinator 的来源呈现遵循 `../loop/turn-steering.md`:更新 coordinator 识别提示,保留历史前缀兼容与已有回复/继续工作合同。参数、权限、执行目标、background batch 与可见性边界不扩展;child 不获得 SendMessage,parent peer 的回复目标来自绑定 agent-id。验证工具描述、真实父子 Runtime 请求、冷恢复及 BG25/O18/O19 fixture。
 
 
+### 2026-09-18 ToolSearch E2E 补齐
+
+仅扩展测试与文档:真实入口 → 搜索执行 → 最终 HTTP body → compact/fork/重启后的第一条请求;包含关闭请求以验证降级和恢复。产品 schema、权限、SQLite 和 App 协议均不变。验收场景见根目录 conversation-session coverage matrix 的 TS 子场景。
+
+### 2026-09-18 ToolSearch E2E 正式准入
+
+本次及此前 8 个 spec(29 项)经用户确认转正,case-local fixture 成为实际模型响应来源,
+原请求阶段、取消屏障与产品断言保持不变。只修改测试和文档;不新增生产接口或修改
+数据库、协议。正式路径与运行证据见根目录 coverage matrix,Docker 准入单独记录。
+
 ## CreateWorkflow 修订续跑的会话内免确认(2026-09-13)
 ## CreateWorkflow 修订续跑的会话内免确认(2026-09-13)
 
 
 ```text
 ```text
@@ -1620,3 +1786,33 @@ interrupted result。修复不改变工具 schema、权限、执行时机、协
 
 
 身份定位补充:conversation-quotes 将原始有序 text/mention 节点逐条映射到模型专用
 身份定位补充:conversation-quotes 将原始有序 text/mention 节点逐条映射到模型专用
 材料,保留同名手打文字与原生提及的区别,不改持久化正文或发送 ref 的授权边界。
 材料,保留同名手打文字与原生提及的区别,不改持久化正文或发送 ref 的授权边界。
+
+2026-10-09 子代理模型的 provider 边界:`subagent_model` 与脚本 `model` 名字的解析(core `model-reference.ts`)
+不再让裸 `modelId` 落到会话 provider 以外的条目上——裸名只在当前 provider 下找,只在别处有即
+`other_provider` 业务失败并列出全称;跨 provider 只有全称一种写法,而技能、两个工具的字段描述与
+`docs/dynamic-workflow/launch.md`「`subagent_model`」都改为:绝不自行把子代理换到用户没点名的另一个
+provider 的模型上。起因是主代理照技能示例自选「轻量」模型,把子代理送去了另一张账单。目录无
+`current` 条目时保持旧的「唯一就取、多个即 ambiguous」。全称仍能跨 provider,所以权限补上一道:
+`AmendWorkflow` 的 resolveInput 最后一步(绑定表落定之后)算出 `predecessor.introduces_providers`——
+这次将用的 provider(归一化后的 `subagent_model` 与 `model_bindings`)减去会话模型与前驱 `run-launched`
+上用过的 provider,非空才在场;契约谓词 `isAmendWorkflowOwnedPredecessor` 见它在场即不给本会话 run
+免确认,权限服务照常 ask(`tool.alwaysAsk`),Deny 不动前驱。同 provider 换模型、沿用前驱的选择仍免
+确认;只改并发的就地调整与 `not_live` 落回不引入模型,不受影响。CreateWorkflow 本来就总开窗,不变。
+schema 只多这个回填键(模型面 JSON schema 不列,带 `predecessor` 的调用照旧在校验被拒);事件与
+UI 不变,桌面只从前驱块读 `status` / `name`,旧客户端不受新键影响。
+
+## 插件使用归属
+
+ToolEntry 的 MCP pluginId 在执行准入时捕获,沿工具成功/失败事件、V4 tool.lifecycle、既有 agent_step 传递。保持 Skill 原字段兼容;普通 MCP 和未知归属留空,不从名字解析、不复制执行事件。仅增加可选 metadata,不改变工具执行、权限、存储和 continuous/replayable 交付。
+
+## UI 插件后台首次创建
+
+成功 MCP UI 工具结果沿现有 V4 投影提交后,以 `v4/plugin-ui/tool-result` 通知本地桌面宿主,
+不依赖 conversation 订阅或工具卡片挂载。复用已校验的 display.ui 和投影输入;失败、取消、
+MCP isError 和历史 hydration 不触发创建。工具执行、权限、原始结果和持久化不变;
+手机 replayable 不消费创建副作用。测试覆盖无订阅实时结果、重复事件、历史恢复、后台建页与返回复用。
+宿主执行/保留规则见根目录 `docs/plugin-ui-background-execution.md`。
+
+### 文档插件多窗口视图修复(2026-10-16)
+
+MCP app-only report_view 增加可选 viewId,release_view 释放指定窗口;模型 get_view 可选 viewId,缺省且存在多个上报窗口时返回歧义与清单。状态唯一归属 DocumentOwner,不由页面决定其他窗口的视图;旧客户端缺省 viewId 仍走 legacy 槽。show_in_viewer 保持专用 surface 路由并明确工具描述。导入仍为 app-only workspace 副作用;串行 admission、10 分钟未活动过期与部分文件清扫归 importer,完成副本不清理。覆盖 schema 到真实 MCP/AppBridge 的多窗口回归。

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

@@ -191,6 +191,15 @@ ZCode 的图片 `Read` 采用多阶段保护策略,最长边使用
 
 
 ### 文本大文件预算
 ### 文本大文件预算
 
 
+超过 `10MiB` 的文本范围读取使用前 `4096` 字节探测编码。样本边界不是文件结束:
+若末尾是未完成的 UTF-8 候选序列,根据首字节与已收到的字节数计算缺少数量,只补读该序列
+所缺的 `1–3` 字节,再严格校验整个样本;不能因流式解码暂未报错就接受 UTF-8。
+补读遇到非法续字节时进入既有 legacy 检测,短读继续读取,EOF 后仍未完整的序列不能通过
+UTF-8 校验。完整字符边界不额外扩样,不丢弃末尾字节,也不固定把样本延长到另一个截断点。
+采样仍是启发式判断:补齐 UTF-8 候选不保证真实编码是 UTF-8,也不验证后续整个文件。
+BOM 与中文 legacy 编码识别顺序不变。正文从头读取,复用同一个流式 decoder 拼接跨块字符,
+不改变行范围和输出预算。附件合成 Read 共用此行为。
+
 ZCode 文本 `Read` 使用两层预算:
 ZCode 文本 `Read` 使用两层预算:
 
 
 - `READ_MAX_FILE_SIZE_BYTES = 256 * 1024`。未显式传 `limit` 时,adapter 先按文件总大小检查;超过上限时返回 `too_large` / `read_file_too_large` 类错误,提示使用 `offset` 和 `limit`。
 - `READ_MAX_FILE_SIZE_BYTES = 256 * 1024`。未显式传 `limit` 时,adapter 先按文件总大小检查;超过上限时返回 `too_large` / `read_file_too_large` 类错误,提示使用 `offset` 和 `limit`。

+ 736 - 0
apps/zcode-cli/docs/design/v2/tool/19-tool-search.md

@@ -0,0 +1,736 @@
+# ToolSearch:启用、持久化与冷恢复
+
+## App Settings 模式
+
+常规设置提供 `toolSearchMode: auto | local | off`,缺省 `off`。`auto` 按每次请求的
+实际 Model 决定 Native/Local;`local` 固定走 Local,沿用能力校验;`off` 使用全量工具。
+CLI 四值参数及默认 Off 不变,独立 CLI 不读取 App Settings。
+
+工具搜索设置行底部常驻显示实验性说明:模型供应商未完整支持原生 ToolSearch 时,
+使用原生模式可能导致缓存失效并增加 Token 用量。中英文文案含义一致,复用设置行的底部
+说明区域与主题文字样式。缺省 Off 不覆盖用户已保存的 Auto/Local 选择,不改变现有生效时机。
+
+```text
+Settings -> Host SettingService / setting.json
+  -> session/requestRuntimePreferences (runtime-materialization)
+  -> 创建或冷恢复时固定 runtimeConfig.toolSearch.mode
+  -> 现有请求投影、工具执行和子 Agent 继承
+```
+
+设置修改只写 App 设置,不广播运行态策略。已有 Runtime(包括预创建草稿、热 resume)
+保持原值;新建和冷恢复读取最新值。fork 继承父 Runtime 策略,子 Agent 沿现有链路继承。
+本地、desktop-attached remote 和手机 shared-host 使用所属 Host 的同一设置权威源,
+不增加 RPC、逐轮读取、session 模式持久化或数据库 migration。旧 Host 响应缺省字段按 Off。
+桌面 continuous 与手机 replayable 的交付边界保持不变。
+
+验收:三值读写及非法值拒绝;旧设置/协议缺省 Off;新建/冷恢复读取新值、热恢复不变;
+fork/子 Agent 继承;本地/远程 Host 透传。Desktop E2E 通过真实设置 UI 保存并检查最终
+provider wire:Off 全量、Auto 的 Coding Plan Native 与普通 provider Local、显式 Local
+搜索和包装调用成功,以及修改后当前会话保持原值、冷恢复按新值投影已有引用。
+
+验证(2026-09-23):macOS Electron TS11 通过,报告
+`packages/desktop/.e2e-artifacts/desktop-e2e-20260923134550055-p73032-ec695c13f4b1f2a3/summary.md`。
+App 相关单测 229 项、Core 回归 23 项、CLI 参数 13 项通过;Bootstrap 109/111,
+两项 Cron denylist / Account Config 失败在 HEAD 原版实现同样复现。根及 Bootstrap
+typecheck、根 lint、架构检查通过;CLI 聚合脚本缺 turbo,使用包级检查,既有 max-lines
+错误按此前约定排除后 lint 通过。改动格式检查通过,`services/src/node.ts` 仅增加一个字段,
+保留该文件既有格式差异。手机真机、Windows/Linux 及真实远程工作区未运行;远程 Host 有单测,
+新 E2E 保持 pending,未自动转正。
+
+## Local ToolSearch 与三种请求投影
+
+CLI 唯一入口为 `--toolsearch-mode auto|native|local|off`,移除 `--enable-toolsearch` 和
+旧 force 值,不保留别名。未传参数默认为 off,所有 provider 使用完整工具目录。
+显式 auto 按当前实际 Model 选择:Coding Plan Anthropic 使用 native,
+其余支持普通工具调用的 Model 使用 local。显式 native/local 遇到不支持的能力在发送前报错。
+CLI 启动覆盖支持 prompt/target/TUI/resume/continue,子 Agent 继承,不保存到 session 或用户配置。
+
+Native 保持原生引用和已发现 deferred schema;Local 在两次 compact 之间固定发送常驻工具、ToolSearch 和
+DeferredToolCall,普通搜索不会向 tools 加入目标 schema;成功 compact 的发现检查点将当前允许的
+原 deferred 工具提升为本上下文的普通 tools。Off 发送完整目录并隐藏搜索控制工具。
+无 deferred 工具或搜索控制工具不可用时关闭搜索并记录原因。ModelRequest.toolSearchEnabled
+仅代表 Native 协议,不因 Local 开启而发送 beta/defer_loading/tool_reference。
+
+Local 从同一份当前允许的 Model 工具目录,在真实结果位置展开连续引用:
+
+```text
+引用 A、引用 B -> <functions>
+<function>{"description":"…","name":"A","parameters":{…}}</function>
+<function>{"description":"…","name":"B","parameters":{…}}</function>
+</functions>
+```
+
+不跨结果或中间文本合并;保留顺序和 Hook 文本,不输出空容器。失效引用沿用移除/占位规则。
+原始历史和 state.metadata.modelContent 仍保存真实引用,不保存 schema 快照或重复展开正文。
+最终投影参与 token 估算、缓存和媒体处理;不截断 schema JSON,不新增 schema reminder。
+定义未变时搜索新增不改旧前缀;定义/权限/可用性真实变化可以改变投影。
+
+请求准备先扫描有效发现集合,再以一个共用循环完成 Native/Local/Off 的引用投影;
+Local 不再在通用过滤后单独扫描历史。未变化的 entry/message/content 复用不可变引用,
+仅在删除或展开引用时复制对应结果。Local 的 schema 编码只在请求内按工具定义复用,
+不同结果保持各自容器与顺序;下一请求重新读取定义,不引入跨请求缓存或失效状态。
+公告收集时序与最终 provider render 的隔离拷贝保持原有合同。
+
+DeferredToolCall 入参严格为 `{name: string, input: object}`,共用外层 callID。只接受当前
+请求允许的 client-executed deferred 工具;常驻、alwaysLoad、控制工具和 provider 原生工具
+不可转发。常驻目标返回普通工具错误并提示直接调用,不执行目标 Hook/审批/handler。
+未搜索不是执行禁令,普通直接调用保持现有规则。包装解包后复用普通调用的调度、校验、
+权限、Hook、超时、取消、后台任务、结果格式、媒体和 turn-stop,不递归运行第二套 executor。
+
+```text
+原始包装调用 -> 公共准入 -> 同 callID 的目标调用 + modelCallWrapper 标记
+                       -> 内部历史 / 普通调度执行 / 目标事件 / SQLite
+SQLite -> hydrate 目标调用与结果 -> 请求渲染时恢复原始包装 -> Model
+```
+
+内部调用与结果统一使用目标名称,包装标记仅为 `modelCallWrapper: "DeferredToolCall"`。
+目标 part 从 pending 起在 metadata 保存该严格字面量,`tool` / `state.input` 保存原始目标
+名称与内层参数;重存、历史复制和分支恢复必须保留。执行参数与历史隔离,Hook、审批和
+handler 不得修改历史原始输入。不重复存储包装 input;删除开发阶段旧 modelToolCall 格式,
+不保留兼容读取或数据迁移。准入失败只保存包装失败记录。
+请求渲染在已有遍历中恢复包装调用及结果名,剥离内部标记;不新增历史扫描或 callID 缓存。
+Todo 等业务判断直接使用内部目标身份;microcompact 用 sourceEntries 分类,仍用投影后的
+消息估算 token。V4 以 scheduled 目标事件定稿工具行,迟到原始流不得覆盖已定稿输入;
+桌面 continuous 与手机 replayable 使用同一目标行,不在各个 UI 消费者解包。
+完整调用后断流可能没有 scheduled;V4 此时消费已有 tool_call_closed,在同一 callID
+的工具行仍为 DeferredToolCall 时,仅用 Core 确认的目标名称和完整输入补齐展示身份。
+不新增工具行、不重置状态、不提前更新 Todo/审批或执行状态;普通行、准入失败、缺少输入、
+其他 ledger 状态、过期 turn 和父会话中的子 Agent 镜像事件不参与补齐。重复事件不重复更新。
+原始模型流、参数预览及 Core 调度时序保持原状,不增加增量 JSON 解析或从展示数据反推权限。
+工具名称、input、inputText 通过同一次完整 row upsert 交付,冷恢复仍由持久化目标 part 重建。
+无需数据库表列或 migration。Native/Local/Off 切换只修改请求
+投影,保留原始结果、公告及包装调用,不伪造直接调用。compact 保存发现名称、
+重建名称公告;Local 用有效检查点提升当前允许的工具,保留尾部的引用继续投影,不合成搜索结果。
+Explore 的 direct/embedded 两个白名单都包含搜索控制入口,保留原目标工具范围;缺少控制入口的自定义 scope 仍按既有规则关闭搜索。
+纯 Continue 不刷新公告。Desktop continuous 与手机 replayable 保持原交付边界。
+
+验收覆盖多引用与混合文本、六向模式切换、作用域/分类变化、直接和包装执行对照、并发/取消、
+真实 SQLite 重开与新 Runtime 的 fork/rewind/compact 恢复、最终 wire 和稳定前缀。模拟 provider
+测试不等于真实模型能力或缓存命中验证;不增加测试专用生产入口。
+
+### 边界归一化验证(2026-09-23)
+
+- 先复现历史标记丢失、重复 input 落盘和产品工具身份错误,再修改公共边界。定向回归共 43 个文件、678 项通过,包含真实 SQLite 重开、fork/rewind、参数修改隔离、Todo 提醒、microcompact 和 continuous/replayable 投影。
+- macOS Local CLI/PTY E2E 5/5,通过真实 Anthropic/OpenAI HTTP 请求验证包装纠错、成功执行、紧凑 metadata、冷恢复和模式切换;报告 `packages/desktop/.e2e-artifacts/desktop-e2e-20260923083224384-p82053-9fe19005d39623fa/summary.md`。
+- Desktop 默认 Off 与冷恢复用例通过,报告 `packages/desktop/.e2e-artifacts/desktop-e2e-20260923082900087-p78208-c6f3fa5bd67ce86b/summary.md`。该批次 Local 最初失败:新增 completed 断言发现旧 good fixture 使用不支持的 activeForm;修正为 priority 并补实际成功断言后,以上 Local 批次通过。不能用旧“仅有 result”的断言证明工具执行成功。
+- 根及 CLI 各 package typecheck、Desktop E2E typecheck 通过;架构检查 0 违规。CLI 顶层脚本缺 turbo,使用 package 原脚本替代;全量 lint 仅有既有 max-lines 错误,按本任务已确认范围忽略该规则后受影响生产目录无 error。
+- 未运行 Windows/Linux、手机真机 relay 或 Desktop Local 包装审批 UI;手机验证止于协议投影。未修改 UI 样式、工具权限、数据库结构或新增测试生产接口,pending 用例未转正。
+
+### Local 初版验证记录(边界归一化之前)
+
+- 定向 Core/Adapter/Bootstrap 40 文件、514/514;覆盖执行/审批/Hook/媒体/turn-stop、流式中断、Continue/compact、Memory/Explore、SQLite 重开/分支及最终 wire。
+- CLI 单测 188/190;两个 provider registry 用例在 HEAD 原版 CLI 源码上同样失败。新模式参数、默认 off、旧参数拒绝及各入口传递断言通过。
+- macOS 正式 WDIO 合并批次:9 spec、34/34(既有 29 项 + 新增 Local CLI/TUI 5 项)。报告:`packages/desktop/.e2e-artifacts/desktop-e2e-20260922160802850-p98628-e8d69b77464ad70e/summary.md`。新 spec 保持 pending,fixture/manifest 检查通过,未新增 Docker 准入。
+- 根及 CLI typecheck 通过;根 lint 无 error;架构检查 0 违规;改动格式及 diff 检查通过。CLI 全量 lint 仍有既有 max-lines 失败,受影响生产目录排除该规则后无 error。
+- CLI 全量套件未全绿:CUA 缺相邻 producer checkout,其他 provider/bootstrap/打包等用例也有失败或未结束,未全部完成基线归因。Core 五项非 ToolSearch 失败及上述 CLI 两项已在 HEAD 源码复现;定向复跑不再出现 ToolSearch 持久化超时。
+- 真实第三方 Anthropic/OpenAI 尝试因已配置 API 连接拒绝(ECONNREFUSED)未取得响应;没有真实缓存 usage 证据。固定 tools/历史前缀断言不代表服务端缓存命中。
+- 本轮未运行 Windows/Linux、手机真实 relay 或 Desktop Local 包装审批 UI;Desktop 无新增模式设置,默认 Off 的工具卡、恢复及切换 E2E 已运行。协议和 continuous/replayable 实现未修改。
+
+## 边界与所有者
+
+Native 模式使用工具引用协议。默认 off;显式 auto/native/local 的选择规则见上文。
+Runtime 使用启动时确定的模式,子 Agent 继承,不写入 session;App 设置与 CLI 覆盖的来源见上文。
+无 deferred 或必要控制工具
+被禁用时恢复全量定义并记录原因。MCP 保持现有初始化;不实现异步就绪、搜索等待、
+OpenAI 原生引用、auto:N 或历史调用自动补装。
+
+```mermaid
+flowchart TD
+  M[当前 Model 与启动覆盖] --> P[Runtime 请求暴露决策]
+  T[作用域允许工具] --> P
+  H[真实历史和有效 compact 检查点] --> P
+  P --> R[配套 tools / messages / 启用标记]
+  P --> E[同一候选目录交给 executor]
+  R --> A[Adapter 编码]
+  E --> O[真实结果提交并保存]
+  O --> H
+```
+
+Registry 保存完整工具,Runtime 唯一负责请求决策。候选经过 Model、可见性、allowlist/denylist、
+主子作用域过滤。未提交/取消/丢弃结果不成为发现事实。改变 Model 时重建请求,正在执行请求不改写。
+
+### 独立请求准备环节
+
+`prepareRuntimeProviderRequest` 是主/子 Agent、Goal verifier、Memory Extraction/Dream 和
+Compact 组装真实请求的共享入口。内部仅执行一次 ToolSearch 准备,再调用已有消息投影;
+media 能力、聚合预算及各入口的执行/重试流程保持独立。
+
+```text
+本次 Model / 启动策略 / 作用域完整工具目录 / 原始 entries
+  -> ToolSearch:启用判定、发现集合、schema 与历史引用/公告投影(不生成新公告)
+  -> 消息投影(保留最新真实用户归属,按需追加验证/摘要 prompt)
+  -> 配套 request { messages, tools, toolSearchEnabled }
+  -> 既有 media 策略 -> Adapter
+```
+
+- 调用方必须提供未经过 deferred 裁剪的完整候选目录;旧位置不再重复准备。
+  Registry 只补全候选工具的元数据,不扩张权限或作用域。
+- 消息投影不再根据 Model 或启动配置猜测 ToolSearch 状态;纯展示/记录/估算投影不执行搜索准备。
+- Goal 使用空工具目录自动降级;Memory 使用调度时的目录(不含 ToolSearch),保留原有
+  model/启动覆盖边界,并在后续循环沿用准备后的工具与启用标记。Compact 保留自己的候选策略。
+- 显式 native/local 的接口能力校验在发送前执行;不向原本未继承 flag 的辅助调用扩散覆盖。
+- 准备结果包含 executor 使用的搜索 context,不生成或返回新公告,不写历史、DB 或全局状态。
+  Compact/Memory/Goal 的请求投影不写回 Main。
+- 历史引用、有效 compact 检查点和公告必须在内部 metadata 被移除前处理。异步消费者
+  固定历史成员和 Model 快照;降级不修改 canonical 历史,不另建发现缓存。
+- 同模型的传输重试复用配套请求;切换 Model 或重新选择 compact 历史时从原始输入重建。
+- 回归覆盖首次无发现、权限/目录变化、重复准备防回归、公告顺序与原始历史隔离;
+  使用真实 SQLite/runtime 验证搜索后 Goal 判定未完成不进入 fail-open complete,
+  同时检查 Memory 多轮请求、Compact fallback 及现有冷恢复/provider 切换。
+  Desktop continuous 与手机 replayable 的持久化/事件交付边界不变。
+
+## 工具和协议
+
+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。
+只暴露当前已注册、作用域允许且满足原有可见性规则的工具;当前没有 ReportFindings 实现,
+不因名单而新增工具。其余已注册内置工具统一在各自 metadata 声明 shouldDefer: true,
+包括 ZCode 工作流(含 FillWorkflowHole)、ReplyToChannel、OffPeak、TodoRead、CronUpdate、js 和子 Agent 协作工具。
+Task 兼容入口保持 providerVisible: false,不因 deferred 分类而进入请求或搜索目录。
+不开启 ToolSearch 时保留完整工具集;开启时首轮只发送常驻定义,真实搜索发现后才追加
+相应 deferred schema(Native);Local 在真实结果位置展开定义并通过 DeferredToolCall 调用。权限、执行、灰度和 embedded search 筛选保持原状。
+MCP 默认延迟,支持
+server alwaysLoad 与 `_meta["anthropic/alwaysLoad"]`、`_meta["anthropic/searchHint"]`。
+这些元数据不构成授权或官方信任。Provider 原生工具保持现有协议。
+
+验收使用真实内置注册目录(含动态工厂、typed submit_result 和 js 分支):检查首轮工具名单、
+公告包含其余允许工具、执行 ToolSearch 后下一请求携带对应 schema 和 deferLoading,
+关闭或禁用 ToolSearch 时恢复完整定义,Task 兼容入口仍不进入模型目录。
+
+插件 `.mcp.json` 与 manifest 的 server `alwaysLoad` 由插件配置转换器统一解析并透传,
+覆盖 stdio、普通 HTTP/SSE 和官方鉴权 HTTP 分支;仅接受布尔值,保留 false,
+未配置或非布尔值沿用插件可选字段规则作为 undefined,不做字符串真值转换。
+该字段只控制模型请求中的 schema 曝光,不改变 MCP 初始化、异步就绪、鉴权或权限。
+回归覆盖各配置来源/transport,以及真实插件发现 → MCP 工具列表 → 注册 → 请求准备 →
+Anthropic wire:无搜索历史时常驻工具有完整 schema 且不带 defer_loading,默认工具仍延迟。
+
+App 的 `ZCodeAgentMcpServer` 类型与现有配置转换函数必须在 stdio/HTTP/SSE 中透传
+布尔 `alwaysLoad`,保留 false;缺失或非布尔值不输出字段,不做真值转换。
+回归从 App 转换入口验证 JSON 往返及严格协议 schema;Agent 接收端沿用现有透传。
+当前 App 调用方是 MCP 设置页连接/状态查询,不新增普通会话创建的 MCP DTO 注入;
+不修改持久化、MCP 初始化、Desktop continuous 或手机 replayable 边界。
+
+输入 query:string、max_results?:number(默认 5,无额外整数范围);支持 select:A,B、canonical/
+alias、MCP 前缀、关键词和 +required。直接选择不截断;关键词只搜 deferred,精确名称可选常驻。
+对模型的 JSON Schema 将 query 和 max_results 同时标为 required;
+runtime schema 仍接受省略 max_results,沿既有执行链先补默认值 5,再校验 JSON Schema。
+仅在 ToolSearch 导出 schema 上补齐声明,不改通用转换器或其他工具;wire 与 executor 分别验证。
+搜索按分词、权重、稳定排序与去重生成结果。输出 matches/query/total_deferred_tools;成功模型结果为
+有序引用,空匹配为文本。只读、并发安全、无外部副作用,复用权限/Hook/trace/预算/取消链。
+未搜索不是执行禁令;未发现工具的参数校验失败提示先搜索加载定义。
+
+内置 deferred 工具的 metadata.searchHint 采用以下检索材料,不改 provider description、
+参数、排序权重或常驻工具;MCP 继续使用自身的 searchHint。
+
+| 工具          | searchHint                                                  |
+| ------------- | ----------------------------------------------------------- |
+| WebFetch      | fetch and extract content from a URL                        |
+| WebSearch     | search the web for current information                      |
+| TodoWrite     | manage the session task checklist                           |
+| EnterPlanMode | switch to plan mode to design an approach before coding     |
+| ExitPlanMode  | present plan for approval and start coding (plan mode only) |
+| TaskOutput    | read output/logs from a background task                     |
+| TaskStop      | kill a running background task                              |
+| SendMessage   | send messages to agent teammates                            |
+| CronCreate    | schedule a recurring or one-shot prompt                     |
+| CronList      | list active cron jobs                                       |
+| CronDelete    | cancel a scheduled cron job                                 |
+
+Native 发送常驻及已发现 deferred 的完整 schema,仅后者 deferLoading;其他工具只公告名称。
+目录变化才追加增删公告。关闭去掉 ToolSearch/DeferredToolCall/公告/字段,删除引用块,空结果替换为
+`[Tool references removed - tool search not enabled]`,保留 call/result 配对。开启时删除
+不可用引用,空结果使用 tools no longer available 占位。所有删除仅作用于请求投影。
+Adapter 原生输出 tool_reference/tool_name 和 defer_loading,禁止 JSON 字符串化,开启附加
+advanced-tool-use-2025-11-20 beta,不用服务端搜索。媒体/缓存/token 估算消费同一最终投影。
+
+结果预算对齐引用块语义:包含真实 `tool_reference` 的文本/引用数组,100 KB 预算只约束
+文本,引用完整保留且顺序不变。初次序列化和 Hook 追加后使用同一投影;文本超限时给出
+截断提示,不能把引用数组降级成工具名字符串。展示文本从最终块派生,字节统计仍按现有
+文本序列化口径计入工具名,不因引用免于截断而漏记;`truncated` 仅反映实际文本裁剪。
+普通文本、媒体和官方 CUA 的预算合同不变。不收紧 `max_results` 或 `select:`:大目录结果
+仍可包含大量引用,对应 schema 进入后续请求。验收覆盖超过 100 KB 的真实 executor 输出、
+超长 Hook 文本、最终 Anthropic wire,以及 completed part 原子保存与真实 SQLite 冷恢复。
+
+### 模型可见文案
+
+Native ToolSearch description、query/max_results 参数说明与名称增删/恢复公告使用固定文案。
+不增加模型判断、实验配置或 runtime 状态。
+
+- Native 描述保留 `<functions>` / `<function>` 的模型侧 schema 展开说明;客户端仍发送真实
+  `tool_reference`,不合成 XML 或 tool call/result。
+- 新增公告完整列名;恢复公告按 MCP server 汇总名称及数量,其他工具保留原名。
+- 删除名称不超过 30 个时逐行列出,超过时按同样方式汇总;删除段后追加 ambient-context 提示。
+- 各公告段用空行分隔,沿用 `<system-reminder>` 包装和现有增量 metadata。
+- 恢复/删除公告只描述当前作用域内的可用性,不推断 MCP 断连、重连或其他变化原因。
+  工具因本轮限制暂时隐藏时仍按现有增量逻辑公告;相同目录不重复追加。
+  不增加 pending/failed/鉴权诊断、异步初始化或搜索等待。
+- 只改变文案渲染:`增量事实 -> 文案 -> 既有提交/快照/请求投影`;纯 Continue 不生成公告。
+  不改持久化、App 协议、Desktop continuous 或手机 replayable 交付边界。
+
+Local 描述首句明确 deferred 工具通过 `DeferredToolCall` 调用;搜索与返回格式说明保持
+原有 `<functions>` / `<function>` 结构,明确 `parameters` 描述的是包装调用的 `input`。
+不再声称与 prompt 顶部工具列表具有相同编码,也不使用抽象的 classification 说明。
+常驻工具仍直接调用。只保留一个简短的 TodoWrite `<example>`,展示顶层 `name` 和完整
+`input`,不增加场景对白或 `<commentary>`;不要求已经加载的工具重搜。
+示例按当前包装及目标工具 schema 校验,CLI/PTY E2E 检查 Local/auto 与冷恢复请求中的
+实际 description,Native 完整文案由既有 wire 测试保护。本次只改 Local 描述,不改变结果
+投影、调用参数、执行逻辑或重复搜索反馈;bench 行为收益需另行验证。
+
+搜索语料使用经过 model contract 投影、包含 modelInstructions 的最终 description。
+不因接口名称不同构造第二份搜索语料。已有工具说明不在此处重写;例如 TaskOutput 已采用
+对应说明,Cron 则保留持久化 automation 等 ZCode 特有行为的描述。
+
+验证固定完整 description/参数说明,以及新增、单个/多个恢复、MCP 分组、30/31 个删除名称
+与混合增删正文;真实 Runtime -> Anthropic wire 检查文案和续写去重,继续复用 compact/SQLite 回归。
+
+2026-09-17 文案验证:先复现 6 项旧文案失败;修改后 Node 24.14.0 下 10 文件 / 55 项通过。
+提取 CC 原始函数独立比较,默认 description 及 120 组公告正文完全相同;仓库测试不依赖
+本机 CC 文件。CLI/根目录 typecheck、根 lint(43 条既有 warning)、改动生产文件 lint、
+格式和架构检查通过。本轮未重跑 Desktop/手机 E2E 或真实远端 provider。
+
+Compact 开启采用 Read/ToolSearch/MCP 候选再过滤,关闭保留现有摘要策略,不新增摘要执行循环。
+该分支必须同时满足当前 Model/flag、候选内 ToolSearch 可用及存在 deferred 工具;
+ToolSearch 被禁用或候选全部 alwaysLoad 时,按普通工具目录(不计 ToolSearch)应用原阈值:
+不超过 100 个保留完整定义,超过 100 个发送空工具目录。回归检查实际 Runtime compact 请求。
+
+### 公告收集与续写时序
+
+公告沿用 attachment 收集边界,由 Runtime 历史 owner 提交,
+请求投影仅消费已有公告,不能在准备每次请求时追加提醒。
+
+```text
+正常输入 / 完整工具批次 -> 收集并提交公告 -> 复制原始请求快照 -> 请求投影
+纯 max-token Continue -> 沿用快照,追加 Partial / Continue -> 请求投影
+Compact 成功 -> 按保留历史重建公告 -> 替换上下文 -> 后续请求
+```
+
+- 正常提醒阶段与 Todo 一样跳过 output-token recovery;公告先进入 canonical 与 turn-local
+  历史,再复制 requestEntries。纯 Continue 不调用公告生成器,已有公告随快照保留。
+- 目录在纯 Continue 期间变化时,增删公告等待下一次正常收集;每次请求的 schema、
+  引用、权限与启用判断仍执行。不扩展 MCP pending/failed/鉴权状态。
+- Compact 在摘要成功后调用同一纯公告生成器:full 使用空保留历史,保留尾部的 compact
+  使用 preservedEntries 比较。公告加入 postCompactReminderEntries;失败、取消或跳过不提交。
+  Auto/Reactive 在 Continue 期间触发时同样重建,不依赖下一次正常提醒收集。
+- Compact 公告读取继续执行的工具目录,不能使用摘要请求裁剪后的候选工具。
+  内部 getContinuationTools 回调复用本轮工具作用域筛选;手动 compact 使用当前 Runtime/Model。
+  不改变摘要工具策略,不为 scope 建立第二份状态。
+- 公告仍是内存历史中的派生提醒,不新增持久化字段;冷启动首次正常收集时重建。
+  已发现工具仍仅由真实引用和 compact 检查点恢复,P/C、App 协议及多端交付边界不变。
+- 回归捕获真实 Runtime 的 Model 请求与 canonical 历史:连续三次续写及下一输入均只有一份
+  首次公告;目录变化、正常工具批次、full/保留尾部/续写期间 compact、失败取消、scope、
+  provider 切换及 SQLite 冷恢复均保持该边界,覆盖 streaming on/off 与最终 adapter 请求体。
+
+### 公告增量记录
+
+RuntimeMessageMetadata.toolSearchAnnouncement 仅记录本条公告的事实:
+
+```ts
+toolSearchAnnouncement?: {
+  addedNames: readonly string[];
+  removedNames: readonly string[];
+  readdedNames: readonly string[];
+};
+```
+
+三个数组始终存在、去重、排序;readdedNames 是 addedNames 的子集。
+不保存完整目录 snapshot 或 addedLines;完整列名为 addedNames − readdedNames。
+历史复制分别复制三个数组,不能共享可变引用。
+
+```text
+当前保留的增量公告
+  -> 顺序 added / removed -> 当前已公告可用 A
+  -> 合并 added - readded -> 曾完整列名 L
+当前作用域:全部工具 T,deferred 工具 D
+  -> added = (D - A) ∪ (D - L)
+  -> readded = (D - A) ∩ L
+  -> removed = A - T
+  -> 同一计算结果生成正文与 metadata
+```
+
+正常收集和 compact 使用同一生成器,只扫描当前有效历史。正文按上面的模型可见文案渲染,
+恢复可用单独提示;名称事实仍来自增量集合,不从公告文案推导状态。
+没有变化不提交公告。
+Bug 根因:旧 metadata 为全量目录但正文只列增量,compact 保留后一条时误以为旧名称仍在
+上下文中;旧删除判断只看 deferred 集合,又会把仍常驻的工具公告为不可用。
+增量事实支持尾部补列,删除改看完整工具池;deferred → alwaysLoad → deferred 不误报。
+
+公告正文及增量 metadata 随隐藏 synthetic message/text part 持久化,使用既有 JSON
+metadata,不新增 DB 表列、migration、session 缓存或公告检查点。正常收集先保存公告,
+再提交 Runtime 历史和请求快照;纯 Continue 不新增公告。Compact 重建的公告随成功历史
+替换保存,失败时与 summary 一起回滚。Fork/resume/rewind 沿用有效分支和 compact 边界,
+原位恢复公告正文与严格校验的增量字段,目录未变时不再次宣告工具尚未加载。
+公告接入 tool_search_announcement attachment/MCS,不支持时使用 user reminder,UI/transcript 隐藏;关闭 ToolSearch 仅在请求
+投影中隐藏公告,不删除存储事实。真实 modelContent 与 preCompactDiscoveredTools 不变。
+旧会话未存储的公告不回填、不从搜索结果推测,仍沿用原有首次收集重建;本次不扩展兼容策略。
+
+```text
+正常收集 / compact 成功 → 公告正文 + 增量 metadata → 现有 Session Store
+                                                     ↓ 有效分支 / fork 边界
+下一请求 ← 从公告推导增量 ← hydrate 原位恢复正文 + metadata
+```
+
+回归使用真实 SQLite:关闭并重开数据库、创建新 Runtime,覆盖搜索后 fork/冷恢复、
+compact 后恢复、边界后的公告不继承、关闭 provider 投影及三次 Continue 不重复公告。
+验收覆盖增删/恢复/仅保留恢复公告、增量尾部与连续 compact 的实际 Model 请求、历史副本隔离,
+并用真实内置目录验证 checklist/cancel/active 与 +required 命中。临时 CC 纯函数差分验证
+不成为仓库运行依赖;Desktop continuous 与手机 replayable 的现有边界保持不变。
+
+本轮验证(2026-09-17):
+
+- 新契约先验证旧实现失败,再通过 5 文件 / 48 项测试。扩大 ToolSearch、continuation、compact、
+  主子作用域和 wire 回归后,23 文件 / 233 项中 232 项通过;Explore 后台完成通知测试
+  `can launch Explore in the background and inject completion on a later turn` 在
+  `subagent-explore.test.ts:4424` 仍失败(期待没有 system-reminder 包装),通过隔离加载
+  本轮修改前源码复现同一失败,未扩张本次修改范围。
+- 生产公告生成器与提取的 CC FDs 在 729 条三步状态序列、各保留历史后缀及后继目录上做
+  52,488 次比较全部一致。固定一个 deferred 工具维持启用;该验证不覆盖启用开关或 MCP 诊断。
+- CLI 全包及根目录 typecheck、Desktop E2E typecheck、17 个修改文件格式检查、架构检查通过。
+  根 lint 无错误、43 条既有 warning;core lint 仍有基线超行等问题。本轮 10 个生产文件
+  前后同规则比较只命中 message-history 的既有 max-lines(445 → 455),无新增诊断类别。
+- 现有 Desktop TS01/TS04 搜索、执行与冷恢复冒烟首次通过:
+  `packages/desktop/.e2e-artifacts/desktop-e2e-20260917092805624-p37188-32ac7469c9f8c8f7/summary.md`。
+  本轮未重跑真实 provider 或手机 UI;App/远控协议未改动。
+
+## 持久化与恢复
+
+不改 SQLite 表列/migration。终态 part 的 state.metadata.modelContent 可选保存有序 text/引用
+数组,与 completed 同次 upsert;schemaVersion 保持 1。output 是展示文本,媒体沿用 attachments/
+layout。不另存 loadedTools 或 schema。保存经过现有结果处理后的最终模型内容。
+公共 metadata 解析也用于 error part,必须保留既有字符串 modelContent 的兼容性,避免 V4
+transcript 冷恢复丢弃同一 metadata 中的 display。ToolSearch 写入与 hydrate 仍只接受严格校验的
+文本/引用数组;字符串和失败结果不产生发现记录。
+Cold hydrate 先选 active branch/有效 compact,按 callID/声明序恢复;合法 modelContent 优先,
+缺失/损坏走媒体/output,损坏记录诊断。中断/失败不产生发现;不按当前 provider 提前清洗引用。
+
+Compact 从原始有效历史与上一检查点合并真实发现名,写已有 preCompactDiscoveredTools,关闭期间
+也保存。仅成功生效 boundary 参与恢复。live/cold 使用同一函数把 boundaryId/发现名挂到 summary
+entry 内部 metadata,不进入正文、不伪造调用。复制/rewind/fork 保留 metadata,不扫描废弃分支。
+请求取发现名与当前允许 deferred 的交集,使用当前 schema;发现记录不保证定义仍展开在上下文。
+
+## 搜索结果提示与公告投影(2026-09-24)
+
+本轮只补成功提示、参数错误指引、公告提醒投影和 MCP 短名称选择。定义快照、不可用工具
+历史 schema 保留及其缓存稳定性延期单独实现;不增加 metadata 字段或 migration,不改变
+当前 schema/引用过滤、启用条件、执行目录和权限。
+
+```text
+真实 ToolSearch 结果 → Native 引用过滤 → 有效结果 callID → 结果批次外 Tool loaded.
+                   → Local 展开 → 结果内 Loaded 指引 / 已加载提醒
+正常公告收集 → 原始 attachment + 增量 metadata → 持久化/恢复 → MCS 或 user reminder
+```
+
+Native 成功且投影后仍有有效引用的每条搜索结果,派生一条 `Tool loaded.`,位于 tool_result 外、
+整批结果之后。Local 仅使用结果内的加载和调用指引,不追加外部提示(见下文逐项反馈合同)。
+提示不写 canonical 历史或数据库,Off、错误、无匹配
+及引用全部失效不生成。复用现有引用和消息遍历,保留媒体真实用户索引、sourceEntries 与缓存标记。
+Continue 与 compact 过滤 query-local Continue 后重建请求记录时,复用本次引用投影已计算的
+有效结果 callID 集合;成功提示的位置和数量与实际请求一致,不重新扫描引用或持久化提示。
+回归同时检查实际 Model 请求、ModelRequest 事件及主轮状态快照,保留 Continue 不进入记录的规则。
+
+参数校验失败且目标为当前未发现 deferred 工具时,在原有错误后以空行追加完整纠错段落:
+说明定义尚未进入已发现集合,以及数组、数字、布尔值被当作字符串输出时会导致参数校验失败;
+随后给出精确 `select:<canonicalName>`、重试指引和当前完整 input schema。
+Native 使用公共段落;Local 在段落末尾另起一行保留 DeferredToolCall 调用说明。
+回归断言完整段落及其与原始校验错误的拼接,不仅检查关键词。
+未搜索不成为执行禁令;已发现/Off/不存在工具维持原有错误。
+
+公告使用 `tool_search_announcement` attachment 来源参与既有 MCS 投影;不支持时输出
+普通 system-reminder。正文只存一次,增量 metadata 冷恢复保留;仅有合法公告 metadata
+的旧 synthetic 公告才适配,不推断用户正文。公告只列名称,不加载 schema,不引入 tool_addition、
+nameOnlyAnnouncements 或 strippedReferences。Continue 不收集,成功 compact 才重建的时序不变。
+
+select 优先 canonical/alias,未命中再匹配 MCP 原始短名和既有命名规则规范化后的短名;
+多个 server 全部匹配且按目录顺序去重,不复制规范化规则,不改变排序、数量或作用域。
+
+验收覆盖最终 wire 提示、混合/并行/失效引用、模式切换、MCS/非 MCS、真实 SQLite 冷恢复及
+Continue/compact、不存在工具错误、MCP 同名/alias 冲突。Desktop continuous 和手机 replayable
+交付边界不变,不修改 UI、auto-compact 估算或 MCP 连接生命周期。
+
+## 影响面与验收
+
+### E2E 正式准入(2026-09-18)
+
+用户已确认本次及此前 8 个 ToolSearch spec 转正(29 项:7 Desktop、14 CLI/TUI、
+8 Runtime/HTTP 集成)。保留原断言和执行入口,不改变生产实现,不增加测试专用生产接口。
+
+模型响应移到各 spec 的 case-local provider fixture,manifest 的请求清单逐项镜像 fixture
+的 id 和 metadata。Desktop 数据面代理与 CLI 的隔离 HTTP server 必须实际读取这些响应;
+仅保存一份未被消费的 fixture 不算回放。动态目录、错误/取消及 streaming on/off 的阶段
+选择继续由原测试 harness 编排,fixture 只拥有响应内容;未知响应 id 直接失败,不兜底。
+
+```text
+真实 UI / CLI / PTY / Runtime 输入 → 原测试 harness 识别请求阶段
+    → case-local fixture 原样响应 → 产品工具执行 / SQLite / 请求投影
+    → 既有 HTTP、UI 与原始历史断言
+```
+
+通过 fixture check、转正 dry run 与 apply 的事务审计后进入正式 direct-root 目录,
+运行默认 E2E 验收并更新引用。修正准入所需的既有文档索引及生成统计,不放宽审计规则。
+Docker preset 仍需额外的容器隔离验证,不将本次本地转正自动等同于 Docker 准入。
+
+### 单测补齐合同(2026-09-18)
+
+本轮只增加测试与文档。所有 E2E/单测均不得为测试修改生产实现、增加测试专用开关、
+导出或注入入口;复用既有 executor、Hook、ModelFactory 与 SessionStore 契约。
+发现产品缺陷时记录失败,不修改生产代码或放宽断言来使测试通过。
+
+| 场景               | 必须断言                                                                                                                                                                                |
+| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 执行边界           | 未发现的 deferred 工具合法调用仍执行且不生成发现;已发现工具参数错误不再提示搜索;关闭或缺失搜索 context 时 ToolSearch 失败且无引用                                                     |
+| Hook 结果冷恢复    | 真实搜索经 PostToolUse 追加文本后,最终有序引用/文本与 completed 同次保存;关闭 SQLite、新 Runtime hydrate 后保持 callID/块顺序,首请求带原生引用与已发现 schema;覆盖 streaming on/off |
+| 搜索细分输入       | 显式 MCP metadata 的分词、多项 required 的交集、正则特殊字符按字面匹配、名称/hint/description 竞争的完整排序与截断                                                                      |
+| 开启时引用全部失效 | 保持 ToolSearch 开启且移除结果中所有目标时,空结果使用 tools no longer available 占位;保留 call/result 配对,原始历史与发现事实不变                                                    |
+
+```text
+真实 ToolSearch → PostToolUse 文本 → 既有结果处理 → completed part / SQLite
+    → 关闭数据库 → 新 Runtime hydrate → 首个 Model 请求的引用 / schema
+```
+
+测试只编排 Model 响应和既有依赖,不替换结果处理、持久化或 hydrate 实现;不改变
+App 协议、Desktop continuous、手机 replayable 或之前的 E2E 验收边界。
+
+本轮新增 16 项单测(4 个测试文件),连同 ToolSearch、adapter wire、通用 executor、
+hydrate、消息历史和 Memory 作用域回归共 19 文件 / 275 项通过。搜索相关采集文件行覆盖率
+100%、分支覆盖率 97.09%;该数字不代表全仓覆盖率或所有功能分支均已覆盖。
+根目录 typecheck、lint(0 error,43 条既有 warning)、新增测试 lint、格式与架构检查通过。
+CLI 聚合 typecheck 因当前环境缺少 `turbo` 无法启动,改用工作区递归执行各 CLI 包的
+`typecheck`,全部通过。本轮未重跑 E2E;此前 E2E 证据与平台边界保持不变。
+
+未执行 codegraph 扫描(工具不可用);源码核对 CLI/bootstrap/runtime/executor/adapter/storage/
+hydrate/compact/subagent。App/TUI 复用展示,无新设置/队列;Desktop continuous 与手机 replayable
+使用原链路,workspace 身份隔离不变。
+
+| ID   | 已接受场景                    | 断言                                        |
+| ---- | ----------------------------- | ------------------------------------------- |
+| TS01 | 首次搜索并调用                | 首轮无未发现 schema,原生引用与后续定义配套 |
+| TS02 | 自动/强制/provider 切换       | on/off/on 保留原历史,force 不支持接口报错  |
+| TS03 | 搜索后重开 SQLite/runtime     | callID/块顺序/下一请求定义一致              |
+| TS04 | 开启或关闭期间 compact 后冷启 | 有效 boundary 恢复发现                      |
+| TS05 | rewind/fork/权限/目录变化     | 废弃分支和不可用工具不暴露                  |
+| TS06 | 取消/并发/旧记录/坏字段       | 无幽灵发现,兼容旧恢复                      |
+| TS07 | CLI 各入口及重启              | flag 本次生效,重启不带恢复 auto            |
+| TS08 | Desktop/手机                  | 既有展示与交付边界不变                      |
+
+先测试后代码。真实 SQLite 重开、新 runtime 和最终请求体是恢复验收面。真实 Coding Plan、force
+非 Coding Plan Anthropic、Desktop E2E 分别记录证据,不以 mock 冒充 live。运行受影响单测、
+typecheck、lint、格式、架构与相关 E2E;正式用例沿用 pending/review/promotion 流程。
+
+Memory Extraction / Dream 沿用已有受限执行策略,ToolSearch 不在其可执行作用域内;请求保留完整普通工具 schema,并对继承历史中的引用做请求级降级,不修改 Main 历史。
+
+## 实施验证(2026-09-15)
+
+### 插件 MCP alwaysLoad 透传修复
+
+修复前新增回归复现:布尔配置在插件转换中丢失,实际 Anthropic 请求缺少常驻工具。
+修复后插件来源/transport 矩阵及本地真实 HTTP MCP → Anthropic wire 两条链路通过;
+连同既有插件、鉴权、来源与 ToolSearch 测试,共 8 文件 / 113 项通过。
+Adapters 与根目录 typecheck、根目录 lint、架构和改动文件格式检查通过。
+修复前 Adapters 全量基线已有 58 项失败及 1 个加载失败的 suite;独立 lint 亦有既有问题,
+本次修改文件仅保留原 max-lines 诊断,计数由 402 降至 401,未扩展修复无关问题。
+未改 UI/协议、数据库或 MCP 初始化方式;本轮未重跑 Desktop/手机 UI 或真实 provider。
+
+### 请求准备环节重构验证
+
+- 先用真实 SQLite/runtime 和 Adapter 消息转换复现:搜索后无工具 Goal verifier 报错,目标被
+  fail-open 保存为 complete;迁移共享准备入口后同一用例保持 active,真实引用及 callID 不变。
+- 本轮 Core 相关回归 20 个文件、426 项通过,包含 Memory 多轮、主子作用域、Compact fallback、
+  SQLite 冷恢复、provider 切换和输出 token continuation;Adapter wire/capability/MCP 9 项通过。
+- Core 与根仓 typecheck、Desktop E2E typecheck、根仓 lint、架构检查、改动文件格式检查通过。
+  Core 独立 lint 仍为修改前已有的 30 项 max-lines 错误和 10 项 warning;本轮改动文件仅命中
+  Compact 原有的超行数和未使用变量诊断,无新增诊断。
+- 现有 Desktop pending ToolSearch E2E 首次通过,搜索执行与重启恢复均成功。报告:
+  `packages/desktop/.e2e-artifacts/desktop-e2e-20260915144451763-p6294-0cc136517acd90ac/summary.md`。
+  未提升用例状态;本轮未重跑真实远端 Coding Plan/强制 provider 或手机实机 UI。
+
+### 公告时序修复验证(2026-09-17)
+
+- 修复前 Runtime 回归捕获首次请求、三次 Continue、下一输入的公告数为 `[1,1,1,1,4]`;
+  修复后为 `[1,1,1,1,1]`,canonical 历史仅一份公告。streaming on/off 与原生 Anthropic
+  wire body 均验证;SQLite 重开后首次请求及其三次续写同样不累积公告。
+- 20 个相关测试文件、163 项通过;补跑既有权限/automation 相关 7 项通过。
+  覆盖正常工具批次、目录变化、full/保留尾部/Auto/Reactive compact、失败取消及本轮 scope。
+- 根仓与 CLI 各 package typecheck、架构和改动文件格式检查通过。CLI turbo 包装命令因
+  本地缺少 turbo 无法启动,改为 pnpm 逐 package 执行 typecheck,全部成功。
+- 根仓 lint 0 error、43 条原有 warning;CLI 改动文件单独 lint 与修改前快照对照均为
+  4 项既有 max-lines error、2 条既有未使用变量 warning,无新增诊断类别或文件。
+- Desktop pending ToolSearch 搜索/执行/重启恢复冒烟通过,未提升用例状态。报告:
+  `packages/desktop/.e2e-artifacts/desktop-e2e-20260917034554193-p29480-01ab7933dc1352e5/summary.md`。
+  本轮未单独运行手机实机 UI 或真实远端 provider;未改多端交付协议、数据库或 P/C 规则。
+
+### 初版能力验证
+
+- 新增搜索语义、暴露决策、并发/取消、子 Agent、SQLite 冷恢复、MCP metadata、原生 wire body 和 CLI 入口测试。
+  SQLite 用例覆盖 stream on/off、force 启动后不带 flag 重启、关闭期间 compact、真实 atomic fork 后重开数据库。
+- Core 相关回归:276 项中 275 通过;唯一失败为原有 Explore 后台通知 wrapper 断言。导出 HEAD 源码复测同例也失败(42 项中 41 通过)。
+- Adapter 相关回归:42 项全部通过,包括媒体降级仍保留原生引用。CLI:184 项中 182 通过;两个 provider registry 精确参数断言在 HEAD 同样失败(177 项中 175 通过),本次新增 7 项均通过。
+- 根仓按改动源文件运行 Vitest related:965 个测试文件、10,376 项通过,6 项跳过。额外验证 continuous/shared-host/replayable 相关 91 项全部通过;手机实机 UI 未运行。
+- Desktop pending E2E 已通过。用例检查首请求、原生引用、延迟 schema、TodoWrite 成功结果、重启后的 ToolSearch 卡片及下一请求;mock 使用现有 HTTPS capture proxy,不修改签名要求。
+  最终 artifact:`packages/desktop/.e2e-artifacts/desktop-e2e-20260915120842415-p20103-a333174b85e72492/summary.md`。
+  用例仍处于 pending,未经人工评审不提升为正式用例。
+- 真实网络闭环:BigModel Coding Plan API(GLM-5.3,自动开启)和 ZAPI Anthropic(GLM-5.3,CLI --enable-toolsearch)均返回成功。
+  两者 SQLite 中均有 completed ToolSearch、原生 TodoWrite 引用及 completed TodoWrite;使用隔离配置和既有凭据,未修改用户设置。
+  可核对 `.cache/toolsearch-verification/20260915/live-results.json` 与同目录两份 SQLite。
+- 根仓 typecheck、Agent contracts/core/adapters/bootstrap/cli typecheck、根仓 lint 和架构检查通过(0 架构违规)。
+  根 lint 原本排除 CLI;额外移除排除后当前和 HEAD 均为 13 项已有 max-lines 错误、6 项已有 warning,无新增违规类别/文件。
+  `pnpm --dir apps/zcode-cli` 的 turbo 包装脚本因本地无 turbo 不可用,改为逐包执行以上检查。
+- 全仓 fmt:check 因已有未格式化内容及 docs/electron 示例 HTML 语法错误未通过;本次全部改动文件格式检查通过,git diff --check 通过。
+  affected runner 只比较提交,HEAD..HEAD 会跳过未提交内容,因此使用显式 changed source 的 Vitest related,未将跳过算作测试通过。
+
+复跑 Desktop:
+
+```bash
+ZCODE_E2E_MANUAL_REVIEW=1 pnpm --filter @zcode/desktop test:e2e -- --spec test/e2e/conversation-session/manual-review/pending/conversation-session-toolsearch.test.ts
+```
+
+### 提交前复核(2026-09-17)
+
+- 当前源码复跑 ToolSearch / MCP / transcript hydration:15 文件、138 项通过;shared MCP 配置
+  18 项通过。此前同版源码的 continuation、compact、SQLite、主子作用域等回归保持有效。
+- Desktop TS01/TS04 冒烟一次通过,覆盖实际搜索、延迟 schema、TodoWrite 执行和重启恢复;
+  provider 使用 mock,不将其计作真实网络验证。报告:
+  `packages/desktop/.e2e-artifacts/desktop-e2e-20260917124733222-p7632-d2b8d8eb7bd890d7/summary.md`。
+- 独立复跑真实 BigModel Coding Plan 自动开启和 ZAPI Anthropic 强制开启,两条路径均成功。
+  SQLite 均确认 completed ToolSearch、TodoWrite 原生引用和 completed TodoWrite;结果及数据库:
+  `.cache/toolsearch-verification/20260917-ship/`。使用隔离配置,未修改用户设置。
+- 根目录、受影响 CLI 包及 Desktop E2E typecheck 通过;CLI 聚合命令缺少本地 turbo,使用逐包
+  typecheck。根 lint 为 0 error / 43 条既有 warning;架构检查 0 违规;全部 106 个改动文件
+  格式检查及 git diff --check 通过。此前记录的全仓格式和 CLI lint 基线问题未纳入本次修改。
+- 本次未运行手机实机及 Windows/Linux 验证;没有修改 continuous/replayable 状态机。
+  E2E 保留 pending 状态,不进行未经人工评审的用例提升。
+
+### E2E 补齐边界(2026-09-18)
+
+补充真实 CLI process 与 Desktop 请求级验收,场景以根目录 `docs/testing/conversation-session-e2e-coverage-matrix.md` 的 TS 子场景为准。冷恢复检查第一条请求;provider 降级请求也必须被捕获,不能用“包含 ToolSearch schema”筛选而漏掉关闭分支。测试 provider 只编排响应,不注入 Runtime 历史或已发现集合。新增候选保持 pending,运行结果不与既有单测混计。
+
+本轮最终完整批次 6 个 spec、20/20 通过(新增 19 个场景),报告 `packages/desktop/.e2e-artifacts/desktop-e2e-20260917170825511-p87277-d34516349bddc10a/summary.md`。受控 provider,不代表所有平台/入口已覆盖;当前缺口以根目录 coverage matrix 为准。
+
+后续新增 TUI PTY 1 项与目录/连续 compact/分类变化 Runtime/HTTP 集成 8 项(streaming on/off)。
+macOS 正式 WDIO 合并回归 29/29,最终 TUI helper 单独复验 1/1;Windows 原生进程批次
+22/22(14 CLI/TUI E2E + 8 集成),不代表 Windows Electron GUI。报告及剩余边界见根目录
+coverage matrix 的“后续补测结果”。仅测试目录使用 registry 注入构造动态目录,未新增 MCP
+热更新产品能力;手机 shared-host/replayable UI 仍待登录配对环境。
+
+### E2E 转正验证(2026-09-18)
+
+本次及此前 8 个 ToolSearch spec 全部转入正式目录,fixture/check/promote 事务审计通过。
+正式默认 E2E 入口 29/29 通过,无失败或跳过;报告为
+`packages/desktop/.e2e-artifacts/desktop-e2e-20260918072918357-p60083-5a0baf60295a16ca/summary.md`。
+模型响应实际读取 8 份 case-local JSON;阶段选择与取消时序仍由原 harness 驱动。
+仅测试和文档改动,未修改生产代码。没有新增 Docker 准入;Windows/手机边界见根目录 matrix。
+
+## Local 逐项反馈与 compact 后提升
+
+Local 按当前有效历史顺序判断定义是否已经可见;比较 canonical 名称,不要求连续搜索。
+真实用户输入与其他工具调用不清空已加载集合。同一 assistant 批次的所有搜索使用批次前集合,
+不把并行兄弟结果视为已经交付给模型。未来结果不能反向改变此前反馈。
+
+| 搜索结果                      | tool_result 投影                        | 结果批次后 |
+| ----------------------------- | --------------------------------------- | ---------- |
+| A、B 均为未加载 deferred      | A、B schema + 合并 Loaded 调用指引      | 无提示     |
+| A 为已加载 deferred,B 未加载 | B schema + B Loaded 指引 + A 已加载提醒 | 无提示     |
+| A、B 均为已加载 deferred      | 合并提醒,无重复 schema                 | 无提示     |
+| A 常驻(含 compact 提升)     | A schema,仍直接调用                    | 无提示     |
+| A 常驻、B 为已加载 deferred   | A schema + B 已加载提醒                 | 无提示     |
+| 错误、无匹配、全部引用失效    | 原有文本/错误/占位                      | 无提示     |
+
+Local 反馈全部位于 tool_result 内,不再派生结果外的 `Tool loaded.`;Native 仍按有效成功
+结果在整批 tool_result 后追加该提示。现有引用投影只为 Native 收集外部成功提示 callID,
+实际请求、Continue 和 compact 记录重建共用同一集合;不改变发现集合、成功状态或持久化。
+提醒在该结果内按名称去重一次,说明定义已经可见,使用 `DeferredToolCall {name,input}` 执行,
+搜索本身不会执行工具。提醒文本使用公共 `<system-reminder>` 包装,仍属于当前 tool_result,
+不生成 attachment 或独立 system 消息;MCS 开关不改变其位置、角色或 `Tool loaded.` 规则。
+首次实际展开 deferred 定义时,也在同一 tool_result 的 functions 内容之后追加一条调用指引:
+
+```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.
+</system-reminder>
+```
+
+多个新增工具仅调整开头为 `Call them now`,其余模板保持相同:
+
+```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.
+</system-reminder>
+```
+
+名称仅包含本次实际展开的 deferred 工具,按引用顺序去重并合并一条;`input` 占位需要按
+对应 schema 填写。常驻、compact 提升、失效引用和失败结果不生成此指引。混合新旧结果先给出
+新增定义的指引,再保留原来的已加载提醒;纯重复结果只有已加载提醒,不追加 `Tool loaded.`。
+只在现有引用投影中派生,不新增历史遍历或持久化字段;后续请求、Continue 和冷恢复重新投影
+时不累积。文案直接引导下一步执行,但不自动发起调用,也不承诺定义永不失效。Native/Off 保持原状。
+连续的新定义共用 functions 容器,不跨文本或结果合并;Hook 原序保留,
+不能通过匹配 Hook 中的 functions 文本判断是否加载成功。常驻精确名称、alias、select 选择
+仍正常返回 schema;关键词只搜索当前 deferred 分类。
+
+```text
+有效历史 -> 发现扫描(发现集合 + compact 检查点)
+         -> 当前作用域分类(Local 提升检查点内原 deferred)
+         -> 引用投影(批次前可见集合 -> schema + Loaded 指引 / 已加载提醒)
+         -> 请求渲染 / Continue / compact 记录重建
+成功 compact -> 新检查点 + 保留尾部 -> 重建公告 -> 提交历史 -> 下次请求普通 tools
+```
+
+提升只作用于 Local 当前上下文:检查点名称与当前允许、可用的原 deferred 目录求交集,
+普通 schema 不带 defer_loading。曝光、关键词搜索、公告和包装准入共用分类;已提升工具
+包装调用沿用“直接调用”错误且不执行目标。所有 deferred 已提升时仍保留 Local 两个控制入口。
+提升依据成功生效的检查点,full/tail compact 一致,失败/取消不提交。新搜索直到下次 compact
+才提升。不修改 registry、alwaysLoad、权限或历史包装调用。
+
+原始结果仍存完整真实引用;请求投影决定去重和提醒,不增加 DB 字段、schema 快照、session
+状态、跨请求缓存或全历史遍历。Native/Off 不变。冷恢复、fork、rewind 使用有效分支检查点;
+Local/Native/Off 切换仍不承诺缓存连续。保留定义变化/工具消失的既有过滤行为,不实现
+unavailable schema 保留,不调整 UI、auto-compact 估算或多端交付边界。
+
+验收:组合表、并行/非连续/alias/短名、Hook 保序、失效引用、前缀稳定、提升后的普通调用与
+包装拒绝(零执行)、全量提升、作用域、Continue/compact 成败取消、SQLite 冷恢复和分支。
+真实进程 E2E 输出 model-io,再用 prompt trajectory 检查数量、位置和配对;模拟前缀断言
+不能代替真实 bench 的任务成功率、重复搜索率或服务端 cache usage。
+
+### 本轮验证(2026-09-28)
+
+- 2026-09-29 Local 移除结果外提示:调整断言先复现 18 项失败;实现后 Core ToolSearch
+  186 项、adapter wire 5 项通过。WDIO 31 项中 30 项通过,覆盖 Native/Local、两种接口、
+  streaming、MCS、模式切换、SQLite 冷恢复及 Continue/Auto/Reactive compact 请求记录。
+  TS10-TUI 独立复验仍超时:终端确认 `/model` 和 `/effort disabled` 均成功,随后普通 prompt
+  被既有登录检查拦截,提示 `Model not set, send /login to login.`,Mock 收到 0 次请求。
+  未进入搜索阶段,未改动该路径,不能将本轮 E2E 报为全绿。主报告:
+  `packages/desktop/.e2e-artifacts/desktop-e2e-20260929-150638-717/summary.md`;复验:
+  `packages/desktop/.e2e-artifacts/desktop-e2e-20260929-151813-512/summary.md`。
+  主报告同目录的 `prompt-trajectory/` 与 `trajectory-audit.json`:34 次真实主请求严格转换,
+  Local 外部提示为零,内部指引保留;仅 compact 分段,call/result 完整配对。
+  根/CLI/E2E typecheck、根 lint、改动代码格式及架构检查通过;CLI lint 被既有 max-lines
+  阻塞。未跑其他操作系统、手机实机或远端 bench,不声称真实模型重复搜索率改善。
+
+- 2026-09-29 首搜调用指引:新增断言先出现 7 项失败,实现后 Core ToolSearch 186 项、
+  adapter wire 5 项通过,TS13 真实进程 E2E 4/4。严格转换实际 model-io 的 34 次主请求,
+  普通/冷恢复保持连续,仅 compact 处分段;提醒内容、位置及 call/result 配对均通过。
+  报告与轨迹:`packages/desktop/.e2e-artifacts/desktop-e2e-20260929-144809-083/`。
+  根/CLI/E2E 类型检查、根 lint、改动代码格式及架构检查通过;CLI lint 仍有既有 max-lines。
+  未运行 Windows/Linux/手机真机或远端 bench,不据此推断重复搜索率或真实缓存命中。
+
+- 内联提醒包装补充验证:MCS 开/关两条新增断言先失败;修复后相关 6 个测试文件、107 项通过,
+  TS13 真实进程 E2E 4/4。新 model-io 经严格转换后 34 次主请求仅在 compact 处分段,
+  提醒标签位于原 tool_result 内,call/result 完整配对。报告与轨迹:
+  `packages/desktop/.e2e-artifacts/desktop-e2e-20260928080047472-p86891-f421a8f3bd4c6de0/`。
+- 先运行新增失败断言,旧实现 9 项失败;最终 Node 24.14.0 下 Core 33 个文件、391 项通过,
+  覆盖 ToolSearch、Continue/记录、compact 成败取消、SQLite 冷恢复/提升后 fork/rewind 和媒体回归。
+- macOS 正式 WDIO:4 个 spec、31/31。新增 TS13 四项保留 pending;既有 TS10/TS12 共 27 项回归通过。
+  CLI on 覆盖真实进程退出/重开 SQLite;streaming off 与显式 compact 使用真实 Runtime 子进程/HTTP。
+  报告:`packages/desktop/.e2e-artifacts/desktop-e2e-20260928-062536-147/summary.md`。
+- 四组新 model-io 经 prompt-trajectory 严格转换(未开启 ignore-tool-search-changes),34 次主请求,
+  仅 compact 场景各两次 `post-compaction` 分段,无非预期 non-incremental-change,调用/结果全部配对。
+  复核脚本和结果:同报告目录的 `audit-local-feedback.mjs`、`trajectory-audit.json`、`prompt-trajectories/`。
+- CLI(从根目录 turbo 入口,30 项任务)和根目录 typecheck 通过;根 lint、架构、E2E fixture 校验、
+  conversation 覆盖索引审计、改动代码/fixture 格式及 diff whitespace 检查通过。
+- CLI 全量 lint 仍被已有 max-lines 等诊断阻塞;本轮涉及 compact-active 的既有超行数和
+  executionMaxOutputTokens 未使用诊断未顺带处理。根 fmt:check 扫描到既有文档/隐藏工作树中的
+  HTML 语法及二进制问题;两个目录索引的已有排版问题保留,只格式化新增段落以免扩大 diff。
+  完整检查输出保存在报告目录 `validation/`,不宣称全仓门禁全部通过。
+- 未运行 Windows/Linux、手机真机或真实 provider。用户确认 bench 位于本机不可访问的局域网机器;
+  重复搜索率、任务成功率、token 开销及服务端 cache usage 待该环境验证。受控响应不证明模型会减少搜索。
+- 生产变更仅 4 个文件,不新增测试生产接口、数据库字段或 UI/多端链路。未提交、未推送。

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

@@ -22,6 +22,7 @@
 12. [WebSearch](13-websearch.md)
 12. [WebSearch](13-websearch.md)
 13. [Workflow](15-workflow.md)
 13. [Workflow](15-workflow.md)
 14. [EnterPlanMode / ExitPlanMode](16-plan-mode.md)
 14. [EnterPlanMode / ExitPlanMode](16-plan-mode.md)
+15. [ToolSearch](19-tool-search.md)
 
 
 ## 公共 tool 形态
 ## 公共 tool 形态
 
 

+ 8 - 3
apps/zcode-cli/docs/design/v2/tui-model-selection.md

@@ -35,9 +35,14 @@ contract.
 
 
 ## State Boundary
 ## State Boundary
 
 
-TUI must not own model selection state. It may keep a render projection of the
-current provider, model, and thought level, just like it keeps the current mode
-and traceId, but session model state lives in bootstrap/core/session storage.
+TUI 不拥有选型状态,只渲染 Bootstrap 的每会话 `cliDefaultSelection`。CLI 装配显式使用
+`modelSelectionMode: "cli-default"`;`/model` 和 `/effort` 修改并持久化下一条用户消息的默认选择,
+不提前改变 Core Session Selection。CLI 用户消息在入口补齐 Selection,实际接受后成为 Session
+续跑选择。App/Bot 的现有显式配置入口不因 CLI 装配改变语义。
+
+新 CLI 会话从 Provider Config 的 `config.defaultModelSelection` 初始化默认值,恢复会话读现有
+`runtime/model_selection` entry。全局保存继续复用现有命令路径,不引入新配置文件或迁移。
+后台唤起和 Goal 直接使用 Session Selection;不会从 CLI 默认值补模型。闲时临时选择不写普通用户 entry。
 
 
 The TUI sends `/model ...` through the same submit callback as other slash commands. The command center asks the app/server for current model state, available model options, and applies the selected model through an explicit app-level method. The TUI renders the returned command text and updates its session metadata projection from the returned `model` and `thoughtLevel` fields.
 The TUI sends `/model ...` through the same submit callback as other slash commands. The command center asks the app/server for current model state, available model options, and applies the selected model through an explicit app-level method. The TUI renders the returned command text and updates its session metadata projection from the returned `model` and `thoughtLevel` fields.
 
 

+ 4 - 0
apps/zcode-cli/docs/design/v2/usage-observability.md

@@ -87,6 +87,10 @@ best-effort observability.
 
 
 - Runtime writes `model_usage` after every successful `ModelComplete` and after model request
 - Runtime writes `model_usage` after every successful `ModelComplete` and after model request
   failures when a request reached the runtime boundary.
   failures when a request reached the runtime boundary.
+- 明确超窗且无有效输出的 finish 在 Adapter 归一为失败;若 provider 已报告 usage,将其保留在
+  `model_request_failed.usage`。既有失败记账消费该事实,不添加额外 usage 数组。
+  Turn 和 Subagent 汇总计入失败事件的 usage;成功响应仍只从 `ModelComplete` 计入,避免双计。
+  记账在 Reactive Compact 前完成,压缩成功、失败、禁用和取消均不得遗漏原请求。
 - Runtime writes `turn_usage` at turn completion or turn error.
 - Runtime writes `turn_usage` at turn completion or turn error.
 - Runtime writes `tool_usage` from tool lifecycle events:
 - Runtime writes `tool_usage` from tool lifecycle events:
   `tool_call_scheduled`, `permission_requested`, `permission_resolved`,
   `tool_call_scheduled`, `permission_requested`, `permission_resolved`,

+ 30 - 0
apps/zcode-cli/docs/plan/trajectory/model-io-to-anthropic-trajectory-tool.md

@@ -42,6 +42,36 @@ pnpm --filter @zcode/prompt-trajectory model-io -- \
 - `manifest.json`:沿用现有 derive manifest。
 - `manifest.json`:沿用现有 derive manifest。
 - `trajectories/*.openai_request_body.json` 与 `trajectories/*.anthropic_request_body.json`:沿用现有 per-trajectory 调试产物。
 - `trajectories/*.openai_request_body.json` 与 `trajectories/*.anthropic_request_body.json`:沿用现有 per-trajectory 调试产物。
 
 
+### ToolSearch 合成模式
+
+`model-io` 和 `derive` 可选 `--ignore-tool-search-changes`,默认关闭,仅用于 provider
+已负责工具变化处理时的离线轨迹合成。顶层 `tools` 本就不参与连续性比较;此开关只放宽
+消息中的 ToolSearch 投影差异,不修改生产请求、日志、缓存策略或会话持久化。
+
+```text
+原始请求(保持不变) → 比较副本忽略 ToolSearch 投影 → 连续性判定
+                                                ↓
+                        合成片段使用最后真实请求 + 最终回复
+```
+
+- 比较时忽略真实 `ToolSearch` callID 对应的原生 `tool_result.content` 数组中的
+  `tool_reference` 及两种精确占位文本:`[Tool references removed - tools no longer available]`、
+  `[Tool references removed - tool search not enabled]`。引用增删、恢复和顺序变化不分段。
+- 比较时忽略 user 消息中独立的 ToolSearch 新增、移除、恢复目录 `system-reminder` block;
+  识别 Native/Local 当前文案及旧日志中的连接原因文案,其他 reminder 与用户正文保留。
+  公告独占的消息可在比较副本中省略;回归使用当前公告生成器输出验证识别规则。
+- 比较时忽略成功且含原生引用的 ToolSearch 结果批次后派生的 `Tool loaded.`,每个有效结果
+  最多对应一条提示;支持并行结果及相邻 user 合并形态。普通正文、其他工具输出、失败或
+  无引用结果后的同名文本仍严格比较,导出内容继续保留最后真实请求中的提示。
+- ToolSearch 的 callID、调用名、输入、结果错误状态、普通结果文本,以及其他工具结果、
+  thinking、普通正文、Continue 和 compact 历史变化仍严格比较。不通用忽略所有 tool 消息。
+- 开关只影响比较;导出内容仍使用该片段最后一条真实请求,保留其 tools、引用、公告、
+  占位文本及最终响应,不合并工具 schema、不复活被过滤的历史引用、不伪造调用或结果。
+- manifest 仅在开启时记录 `ignoreToolSearchChanges: true`,默认输出契约不变。合成产物
+  不代表逐轮 wire 相同或缓存已命中;原始 model-io/ledger 继续作为逐轮事实源。
+- 回归覆盖默认严格分段、开启后移除/恢复合并、公告迁移、mixed text/reference 保序、
+  call/result 身份及非 ToolSearch 负例、thinking 补全、delta/sidecar、CLI 两入口与文件输出。
+
 ## 验收
 ## 验收
 
 
 ### 连续性判定(2026-09-12)
 ### 连续性判定(2026-09-12)

+ 71 - 0
apps/zcode-cli/docs/usage/01-quickstart.md

@@ -0,0 +1,71 @@
+# 01 · 快速开始
+
+## 从源码构建
+
+准备 Git、Node.js 24.14.0 和 pnpm 10.33.2;以仓库根目录的 [mise.toml](../../../../mise.toml) 为准。以下命令在仓库根目录执行:
+
+```sh
+pnpm install --frozen-lockfile
+pnpm --filter @zcode/cli... build
+node apps/zcode-cli/packages/cli/dist/zcode.cjs --version
+node apps/zcode-cli/packages/cli/dist/zcode.cjs doctor --json
+```
+
+`@zcode/cli...` 包含 CLI 的 workspace 依赖。首次安装会执行仓库的资源准备步骤,需要能访问包和资源下载源。不要把安装脚本被跳过的目录当作完整发行包。
+
+需要单文件可执行产物时,在完成构建后执行:
+
+```sh
+pnpm --filter @zcode/cli sea --target linux-x64
+```
+
+目标包括 `darwin-arm64`、`darwin-x64`、`linux-arm64`、`linux-x64`、`win-arm64`、`win-x64`。产物在 `apps/zcode-cli/packages/cli/dist/`;Windows 文件名使用 `zcode-windows-<arch>.exe`。交叉打包不等于目标平台运行验证。
+
+后文以 `zcode` 代表 CLI 命令。使用普通 Node bundle 时,替换为 `node /absolute/path/to/zcode.cjs`,并保留构建生成的相邻资源。SEA 内嵌 Node,不依赖系统 Node 版本;MCP、Hook 或插件启动的外部程序仍须单独安装。
+
+## 使用可执行文件
+
+macOS/Linux 给可信产物添加执行权限,然后直接使用绝对路径:
+
+```sh
+chmod +x /absolute/path/to/zcode-darwin-arm64
+/absolute/path/to/zcode-darwin-arm64 doctor --json
+```
+
+Windows PowerShell 示例:
+
+```powershell
+& 'C:\tools\zcode-windows-x64.exe' doctor --json
+```
+
+不要使用不匹配的系统或 CPU 架构。macOS 若拦截未签名产物,先确认来源,再通过系统设置允许运行;不要对未知文件批量移除安全属性。
+
+## 自检与模型设置
+
+```sh
+zcode --version
+zcode --help
+zcode doctor --json
+zcode plugins list --json
+zcode skills list --json
+```
+
+`doctor` 用于检查版本、平台、CPU、Node、执行路径和 SEA 状态;它不证明模型凭据、网络或工具调用已经可用。插件清单可以独立查询,不要求先发一次付费模型请求。
+
+当前源码的个人模型设置保存在 `~/.zcode/v2/provider_config.json`;运行与扩展设置仍在 `~/.zcode/cli/config.json`。按[配置](03-config.md)建立个人 provider,或在受支持的账号路径上执行 `zcode login`。远程终端可用 `zcode login --no-browser` 显示登录 URL;浏览器回调仍可能要求与 CLI 位于同一机器。
+
+## 第一次非交互调用
+
+```sh
+zcode --prompt "只用一句话回复 ready,不调用工具" --cwd /absolute/path/to/project --mode plan --json --no-color
+```
+
+普通 prompt 成功时返回 `sessionId`、`response` 和相关运行信息。然后在一次性测试目录中验证所需工具,检查真实文件或命令结果。模型回复“成功”不等于工具已执行。
+
+需要执行命令、修改文件的自动化任务通常显式使用 `--mode yolo`,并由任务容器或操作系统限制可访问范围。`--prompt` 缺省也采用 `yolo`。这不是只读模式,也不是沙箱。批量执行前继续阅读[工具](04-tools.md)和[权限](05-permissions.md)。
+
+## 隔离运行环境
+
+并发任务应使用独立工作目录、用户目录和数据基目录。在子进程环境中同时设置 `HOME`、`USERPROFILE`、`ZCODE_DATA_BASE_DIR` 为本次运行的临时目录;不要修改调用者的全局环境。这样可隔离凭据、个人模型配置、会话、插件和记忆。`ZCODE_STORAGE_DIR` 只控制部分存储路径,不能单独代表完整隔离。
+
+可复制的跨平台子进程例子见[批量任务](13-automation.md)。配置文件和密钥也须写入该隔离环境;不能依赖开发机原有登录态。

+ 61 - 0
apps/zcode-cli/docs/usage/02-cli-reference.md

@@ -0,0 +1,61 @@
+# 02 · 命令行参考
+
+## 常用入口
+
+```sh
+zcode
+zcode --prompt "任务说明" --cwd /absolute/path/to/project --mode yolo --json
+zcode doctor --json
+zcode skills list --json
+zcode commands list --json
+zcode plugins list --json
+zcode hooks trust status --workspace /absolute/path/to/project --json
+```
+
+无参数进入 TUI。`--prompt`/`-p` 必须带非空文本;不要把 `-p` 当作无需值的开关,也不要用裸位置参数替代 prompt。`app-server` 是协议服务入口,不是批量任务的普通问答命令。
+
+## 参数
+
+- `--cwd <path>`:本次调用的有效工作目录,用于项目配置、技能发现和会话归属。
+- `--mode plan|build|edit|yolo|guarded`:显式指定权限模式。`--prompt` 缺省为 `yolo`;旧构建可能缺少 guarded。
+- `--attach <path>`:添加本地附件,可重复。实际媒体支持还受所选模型限制。
+- `--resume <sessionId>`:恢复指定会话;`--continue`/`-c` 恢复当前目录最近的会话。两者互斥。
+- `--target <objective>`:设置或推进会话目标,与 `--prompt` 互斥;替换已有目标使用 `--target-replace`。
+- `--disallowed-tools <names>` / `--disallowedTools <names>`:本次运行移除整项工具,逗号或空格分隔;不持久化。`Bash(git *)` 仍移除整个 `Bash`,不是命令匹配规则。
+- `--json`:命令支持时输出 JSON;并非所有子命令或错误路径都返回 JSON。
+- `--output-format text|json|stream-json`:控制普通 prompt 的输出,优先于 `--json`。
+- `--workflow-mode disabled|onDemand|alwaysOn`:当前源码中用于 prompt、target 和 TUI;默认 `disabled`。旧构建可能拒绝此参数。
+- `--memory-bench`:仅配合 `--prompt`,开启自动记忆提取并等待提取结束;须先启用记忆。
+- `--browser-use=headless`:显式启用 CLI 管理的无界面浏览器;可用 `--browser-executable <absolute-path>` 指定浏览器。后者不能单独使用。
+- `--locale auto|en-US|zh-CN`、`--no-color`、`--verbose`:语言、颜色与附加诊断。
+- `--version`/`-v`:版本;`-v` 不是 verbose。
+
+插件命令还支持 `--scope`、`--available`、`--all`、`--keep-data` 等选项,见[插件](10-plugins.md)。`--force-mcs` 是 Anthropic 接口的专项诊断选项,不是通用评测开关。
+
+不要使用未经解析器支持的 `--print`、`--model`、`--settings`、`--max-turns`、`--allowed-tools` 或 `--permission-mode`。若需要运行时限,由评测进程管理器控制;不要杜撰 CLI token 或轮数预算参数。
+
+## JSON 与流式输出
+
+普通 prompt 的 JSON 示例仅展示结构,具体字段可随构建变化:
+
+```json
+{
+  "sessionId": "sess_example",
+  "traceId": "trace_example",
+  "response": "ready",
+  "eventCount": 4,
+  "projection": { "status": "idle", "turnCount": 1 }
+}
+```
+
+`stream-json` 是 NDJSON:逐行输出事件,正常结束时输出 `type: "result"` 的结果行。逐行 `JSON.parse`,不要把整个文件当作一个 JSON 对象。遇到未知事件类型应保留原始记录;不要按固定事件数量判断成功。
+
+`--prompt "/help"` 等本地命令可以提前返回文本,即使传了 `--output-format json` 也不代表一定有普通 prompt 的结果结构。此类调用只能验证参数被接受,不能验证完整输出协议。
+
+stdout 保存业务输出,stderr 单独保存诊断。异常路径可能只有 stderr;先检查进程退出状态,再解析结果。进程成功结束也不等于任务评分通过,须结合工具执行、文件产物和独立判题结果。
+
+## 退出与取消
+
+常见参数或运行错误返回退出码 `1`;成功入口通常返回 `0`。信号取消要记录原始 exit code、signal 和超时标记,不要只归一化为“没有输出”。权限拒绝可能作为工具错误交给模型后继续一轮,因此也不能只靠进程退出码检测工具失败。
+
+恢复、goal 和后台工作流的结束语义见[会话](06-sessions.md)。

+ 96 - 0
apps/zcode-cli/docs/usage/03-config.md

@@ -0,0 +1,96 @@
+# 03 · 配置
+
+## 两类配置文件
+
+当前源码把模型配置和运行配置分开管理:
+
+```text
+个人 provider、模型选择 → ~/.zcode/v2/provider_config.json
+运行、权限、MCP、Hook、插件 → ~/.zcode/cli/config.json
+项目运行设置 → <project>/zcode.json、<project>/.zcode/config.json
+账号登录凭据 → 凭据存储,不作为普通模型配置公开
+```
+
+`ZCODE_DATA_BASE_DIR` 改变 provider/凭据等数据基目录。个人模型文件可显式用 `ZCODE_PERSONAL_PROVIDER_CONFIG_FILE` 指定。不同构建的路径和兼容入口可能不同,先核对本次 CLI 的行为。
+
+运行配置一般按内置默认、用户、项目、环境变量及入口参数叠加。同名 MCP server 的用户配置具有更高优先级;项目 Hook 还必须通过独立的工作区信任。不能用一条“后写覆盖前写”规则概括所有字段。
+
+## 个人模型配置示例
+
+以下是当前文件格式。它用于自定义 OpenAI Chat Completions 兼容服务,地址、模型名和 Key 必须替换。`api.baseUrl` 的拼写与旧格式的 `options.baseURL` 不同。
+
+```json
+{
+  "schemaVersion": 1,
+  "config": {
+    "providerConfigRules": {
+      "providerRules": [
+        {
+          "providerId": "example",
+          "providerName": "Example API",
+          "config": {
+            "group": "standard-personal",
+            "access": { "type": "api-key", "apiKey": "REPLACE_WITH_API_KEY" },
+            "api": {
+              "type": "openai-chat-completions",
+              "baseUrl": "https://api.example.com/v1"
+            },
+            "personalModelIds": ["example-model"]
+          }
+        }
+      ]
+    },
+    "modelConfigRules": {
+      "providerModelRules": [],
+      "manualProviderModelRules": []
+    },
+    "defaultModelSelection": {
+      "providerId": "example",
+      "modelId": "example-model"
+    }
+  }
+}
+```
+
+支持的 API 类型为 `openai-chat-completions`、`openai-responses`、`anthropic-messages`。服务必须支持所选协议及任务需要的工具调用。模型能力、推理选项和输出限制还受模型规则约束;不要仅改一个模型名称就假设所有选项兼容。
+
+自定义 API Key 可以由启动器从受控凭据来源写入临时配置。该文件含明文 Key,应限制文件权限,不提交到 Git,不放入评测结果归档。配置读取不承诺对 `apiKey` 字符串做 `${ENV}` 替换。
+
+`providerModelRules` 用于模型规则覆盖;`manualProviderModelRules` 用于完整手动模型定义,同一 provider/model 不能同时出现在两者。精确 schema 见 [provider 文件编解码](../../../../packages/provider-node/src/provider-config-file-codec.ts)及[模型规则](../../../../packages/provider/src/config/rule-data-schema.ts)。默认模型选择的 `options` 可保存模型支持的选项,不能填写该模型不支持的 reasoning 档位。
+
+## 从旧配置迁移
+
+旧构建使用 `~/.zcode/cli/config.json` 中的 `model` 和 `provider`。当前 standalone CLI 在个人模型文件不存在时尝试一次性导入旧用户配置;它不是每次启动都重新覆盖个人文件。
+
+```text
+个人模型文件不存在 → 尝试导入旧用户配置 → 保存个人配置
+个人模型文件已存在 → 读取个人配置 → 后续修改个人配置
+```
+
+因此,迁移后继续改旧文件中的 `model`/`provider`,不能作为可靠的切换方式。项目级旧 provider、旧 `ZCODE_MODEL`/`ZCODE_API_KEY` 环境变量也不能当成新格式的通用覆盖入口。`ZCODE_BASE_URL` 在当前代码中还与产品服务端点有关,不能把模型 API 地址填进去代替 `api.baseUrl`。
+
+旧模型配置可能包含无法迁移的字段;发现错误时先保留原文件并查看诊断,不要删除个人配置来反复强制导入。
+
+## 运行配置示例
+
+```json
+{
+  "features": { "mcp": false, "subagent": false, "memory": false, "skill": false },
+  "memory": { "use": false },
+  "plugins": { "enabled": false },
+  "skills": { "enabled": false },
+  "hooks": { "enabled": false },
+  "ui": { "locale": "zh-CN" },
+  "modelStream": { "idleTimeoutMs": 600000 }
+}
+```
+
+这是减少扩展干扰的评测配置,不是通用功能默认值。需要 MCP、技能或插件的任务应显式开启并记录配置。JSON 不支持注释。错误字段可能导致整份配置失效或部分配置被跳过,不能把“进程启动成功”当作配置生效证明。
+
+## 环境变量与网络
+
+常用运行变量包括 `ZCODE_STORAGE_DIR`、`ZCODE_SESSION_DB_PATH`、`ZCODE_LOG_DIR`、`ZCODE_LOG_CONSOLE=1`、`ZCODE_HTTP_PROXY`、`ZCODE_NO_PROXY`、`ZCODE_AGENT_CA_CERT` 和 `ZCODE_MAX_TOOL_CONCURRENCY`。`ZCODE_LOG_LEVEL` 不是受支持的日志级别设置。
+
+CLI 会从有效工作目录向上查找 `.env`,既有环境变量不被覆盖。评测工作区及其父目录不要遗留意外的 `.env`。使用 `network.httpProxy` 或 `ZCODE_HTTP_PROXY` 配置 CLI 网络;不要假设调用者的所有标准代理、证书或 telemetry 变量会原样进入运行时。
+
+完整隔离需要同时考虑用户目录、数据基目录、工作目录和已有环境变量,见[批量任务](13-automation.md)。

+ 36 - 0
apps/zcode-cli/docs/usage/04-tools.md

@@ -0,0 +1,36 @@
+# 04 · 工具与评测配置
+
+工具集合由构建、模型能力、运行配置、插件、MCP 和宿主共同决定。不要把某次运行的工具数量写成固定产品契约,也不要把模型自行列出的工具名称当作注册清单。
+
+## 确认工具是否可用
+
+常见能力包括文件读取与编辑、命令执行、网页访问、技能、子任务和会话控制。实际名称以发送给 provider 的请求和运行事件为准。需要严格比较工具面时,在受控测试 provider 上记录请求的 `tools` 字段,并保存工具 schema;生产请求可能包含任务内容与凭据相关信息,归档前必须处理敏感数据。
+
+工具出现、权限允许和执行成功是三个条件:
+
+```text
+配置与注册过滤 → 模型请求中的工具声明 → 模型发起调用
+→ 参数校验、权限与 Hook → 实际执行 → 工具结果 → 模型回复
+```
+
+内嵌搜索分支在 Bash 可用时可以隐藏独立的 Glob/Grep 工具。禁用 Bash 后搜索工具面可能变化;禁用一项工具不能据此推断某种能力完全消失。
+
+## 非交互任务模板
+
+```sh
+zcode --prompt "任务说明" --cwd /absolute/path/to/task --mode yolo --disallowed-tools "AskUserQuestion EnterPlanMode ExitPlanMode" --json --no-color
+```
+
+普通 `--prompt` 没有交互式审批客户端。需要提问或审批的工具可能失败。对无需人工干预的任务,移除上述工具可避免进入计划或提问流程;这会改变实验条件,应记录在评测配置中。`yolo` 也不保证所有声明了强制确认的工具都能运行。
+
+按任务协议决定是否禁用子任务、记忆、技能、MCP、插件和工作流。禁用子任务时可同时关闭 `features.subagent` 并移除 `Agent Task`。当前源码可用 `--workflow-mode disabled`;旧构建先检测参数支持,不要无条件添加。
+
+`--disallowed-tools` 在工具注册层移除完整工具,适合固定实验工具面。配置中的 `permission.disallowedTools` 属于权限判定,不应当作它的等价替代;尤其不能假设所有权限配置都约束 `yolo`。
+
+移除 WebSearch/WebFetch 不能断网:Bash、MCP、插件或浏览器也可能访问网络。网络、文件系统、进程和资源限制应由任务容器或操作系统实施。
+
+## 最小验收
+
+在一次性工作区执行一个指定文件写入任务和一个命令任务。检查文件实际内容、工具结果和进程状态,再由独立脚本判定是否成功。另跑一次拒绝场景,确认限制确实生效。评测评分不能依赖模型最后一句“已完成”。
+
+训练数据应保留真实工具调用与结果,包括拒绝、超时和失败;不要把模型对工具的转述补成一次成功调用。输出与轨迹说明见[批量任务](13-automation.md)。

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

@@ -0,0 +1,35 @@
+# 05 · 权限
+
+启动非交互任务时显式指定 `--mode`,不要依赖用户配置或交互终端的默认值。`--prompt` 缺省使用 `yolo`。
+
+## 模式语义
+
+- `plan`:限制普通写入和命令执行,主要用于分析。它不是操作系统级只读沙箱;当前实现还允许部分非破坏性 MCP 和会话控制能力。
+- `build`:常规写入及有副作用的工具通常需要审批。
+- `edit`:工作区文件编辑通常免审批,其余沿用 build 判定。
+- `yolo`:普通工具跳过权限提示,适合已隔离的无人值守任务。
+- `guarded`:当前源码支持。普通调用采用宽松策略,危险命令仍需逐次批准;不适合作为无人值守任务的“自动批准”模式。旧构建可能不支持。
+
+`auto` 是内部保留值,不是可用的 CLI 自动模式。
+
+## 为什么 yolo 仍可能拒绝
+
+工具级交互要求、`alwaysAsk`、独立 Plan 状态、工作区 Hook 信任和 Hook 拦截都有自己的规则。不能把 yolo 简化成“任何代码都无条件执行”。配置中的普通 deny/allow 规则也不能替代操作系统隔离。
+
+```text
+工具未注册 → 无法调用
+工具已注册 → 校验与权限判定 → allow / ask / deny
+ask + 无审批客户端 → 工具失败
+allow + Hook 阻断 → 工具失败
+执行成功 → 仍需验证任务产物
+```
+
+这张图说明用户可观察的结果,不代表内部每个检查的严格调用顺序。细节以[权限服务](../../packages/core/src/permission/service.ts)及工具执行器为准。
+
+## 验证权限
+
+用一次性目录测试 Read、Write 和 Bash。对普通内置文件工具,plan 应拒绝写入,edit 可写文件;build 的写入审批在无客户端的 prompt 中可能失败。使用自定义工具、插件或 MCP 时,须分别验证其能力声明和权限规则。
+
+出现 `No permission client configured` 时,检查当前模式和工具是否需要交互。不要仅通过重复提示模型来解决。移除不需要的交互工具,或选择具备审批客户端的交互入口。
+
+工具拒绝后模型仍可能继续回答,进程也可能返回 `0`。同时检查流式事件、工具结果和文件产物。需要按参数拦截某类工具时可使用同步 `PreToolUse` Hook,但简单命令正则不是完整沙箱,见[Hooks](09-hooks.md)。

+ 34 - 0
apps/zcode-cli/docs/usage/06-sessions.md

@@ -0,0 +1,34 @@
+# 06 · 会话
+
+## 新建与恢复
+
+普通 `--prompt` 默认创建新会话。成功的 JSON 输出包含 `sessionId`;恢复时保存并显式传回它:
+
+```sh
+zcode --prompt "继续检查上一步的文件" --resume sess_example --cwd /absolute/path/to/task --mode yolo --json
+```
+
+保持相同的数据目录和有效工作目录。`--continue`/`-c` 选择当前目录最近的会话,与 `--resume` 互斥;并发任务不要依赖“最近”来关联结果。
+
+```text
+首次 prompt → 新 session → 保存 sessionId 与运行记录
+后续 prompt + resume → 加载历史 → 新 turn → 保存本次运行记录
+```
+
+恢复不意味着工作区文件、外部服务和插件状态自动回到历史时刻。需要精确复现时,另行保存仓库提交、文件快照和任务环境。`traceId`、`turnId` 应按每次输出原样记录,不要自行假定跨进程恢复后所有标识保持不变。
+
+## 目标与工作流
+
+`--target "目标"` 与 `--prompt` 互斥;已有目标需要替换时显式使用 `--target-replace`。它不是“执行一次普通 prompt”的等价写法。评测通常使用普通 prompt;需要持续推进目标或工作流时,应另设终止条件并保存其事件。
+
+当前源码的工作流模式为 `disabled`、`onDemand`、`alwaysOn`,默认 disabled。不同模式会改变模型可见工具及运行过程,不要在一组比较实验中混用。
+
+## 持久化与用量
+
+默认 CLI 会话数据库位于 `~/.zcode/cli/db/db.sqlite`,可通过配置或环境变量重定向。数据库结构属于实现细节;不要把旧手册中的 SQL 表结构当成稳定 API,更不要直接删除或修改行来“重置任务”。
+
+需要分析数据库时使用只读连接;备份活跃 SQLite 数据库使用 SQLite backup API,或先停止相关进程并处理 WAL 文件。只复制主文件可能漏掉尚未 checkpoint 的记录。
+
+JSON 中的 `usage` 反映本次输出提供的用量统计。不同 provider 对缓存和推理 token 的上报可能不同,缺失值不等于零。不要用本次结果推算整段会话、后台任务或账号账单。
+
+TUI 的斜杠命令与 headless 分发不同。自动化切换会话使用 `--resume`,模型使用[配置文件](03-config.md),不要默认把 TUI 中的所有斜杠命令塞进 `--prompt` 都会执行。

+ 38 - 0
apps/zcode-cli/docs/usage/07-mcp.md

@@ -0,0 +1,38 @@
+# 07 · MCP
+
+MCP 为 CLI 提供外部工具。运行配置使用 `mcp.servers`,每个 server 必须声明传输类型。先确保 `features.mcp` 已启用。
+
+## 配置示例
+
+```json
+{
+  "features": { "mcp": true },
+  "mcp": {
+    "servers": {
+      "example": {
+        "type": "stdio",
+        "command": "node",
+        "args": ["/absolute/path/to/mcp-server.mjs"],
+        "enabled": true,
+        "timeoutMs": 30000
+      }
+    }
+  }
+}
+```
+
+`mcp-server.mjs` 应是符合 MCP 协议的服务,不是普通输出 JSON 的脚本。stdio 服务的 stdout 专用于协议,诊断写 stderr。`command` 对应的程序及其依赖须在目标机器安装;CLI 的 SEA 产物不会为外部脚本自动提供 Node 命令。
+
+远程服务可使用 `type: "http"`,配合 `url`、可选 `headers`、`oauth` 和 `timeoutMs`;旧 SSE 传输使用 `type: "sse"`。协议选择 `protocolVersion` 支持 `auto`、`legacy`、`2026-07-28`,只在服务兼容性需要时显式设置。精确字段见[配置 schema](../../packages/adapters/src/config/schema.ts)。
+
+同名 server 的用户配置优先于项目配置。定位“改了项目配置却没生效”时,先检查用户配置和插件是否也声明了该服务。
+
+## 验证与评测
+
+用最小无副作用工具测试连接、schema 和返回结果。检查请求中的实际工具名,不要仅凭模型声称“能访问 MCP”判断成功。常见名称包含 `mcp__` 前缀;插件服务可能添加命名空间,以本次注册结果为准。
+
+工具能注册不等于鉴权完成,也不等于有执行权限。非交互任务应预先完成所需凭据配置;授权过程中要求用户交互的服务不能直接视为批处理就绪。
+
+MCP 的可见性、工具过滤和权限是不同层。移除 MCP 工具时记录全名;需要完全禁用此能力可关闭 `features.mcp`,并检查插件、浏览器或其他工具是否仍提供等价通道。
+
+评测记录服务版本、工具 schema 和必要的非敏感配置。密钥、Authorization header 和 OAuth 凭据不进入数据集。

+ 42 - 0
apps/zcode-cli/docs/usage/08-skills.md

@@ -0,0 +1,42 @@
+# 08 · Skills 与自定义命令
+
+Skill 是按需加载的任务说明;它不会自动增加操作系统权限。技能中的命令仍受当前工具、权限和运行环境约束。
+
+## 编写一个技能
+
+在项目中创建 `.agents/skills/greet/SKILL.md`:
+
+```markdown
+---
+name: greet
+description: 用户要求问候时使用,用一句话问候。
+---
+
+请用一句话问候用户,并在末尾加上 READY。
+```
+
+当前默认发现路径包括用户及项目的 `.zcode/skills` 和 `.agents/skills`。Git 工作区中会向工作树根查找技能目录;同级 `.zcode` 优先于 `.agents`。启用的插件也可贡献技能。重复名称和 metadata 预算会影响最终可见集合,使用清单核对来源:
+
+```sh
+zcode skills list --cwd /absolute/path/to/project --json
+zcode commands list --cwd /absolute/path/to/project --json
+```
+
+`skills.roots` 可以增加技能根目录。运行配置中的 `features.skill`、`skills.enabled`、插件启用态以及单项覆盖都会影响结果。修改后用新进程验证;不要把磁盘上有 SKILL.md 当成已加载。
+
+## 调用与自定义命令
+
+普通 prompt 可以描述任务,让模型按技能说明使用;显式调用格式及命令是否存在,以 `commands list`、`skills list` 和对应构建的帮助为准。插件中的 `commands/hello.md` 可定义自定义斜杠命令:
+
+```markdown
+---
+description: 简短问候
+argument-hint: "[名字]"
+---
+
+请对 $ARGUMENTS 说一句问候。
+```
+
+插件加载后可用 `zcode --prompt "/hello reader"`。自定义命令会展开为指令参与模型调用,不应与 `/help` 等本地返回命令的输出混为一谈。
+
+批量任务应固定技能版本和启用清单。需要无技能对照组时,同时检查用户目录、项目目录与插件贡献,避免开发机环境污染结果。

+ 84 - 0
apps/zcode-cli/docs/usage/09-hooks.md

@@ -0,0 +1,84 @@
+# 09 · Hooks
+
+Hook 是在会话或工具事件上运行的本地程序,可记录事件、补充上下文或阻断调用。用户配置、项目配置和插件都可能提供 Hook;项目 Hook 需要额外信任。
+
+## 事件与最小配置
+
+支持 `SessionStart`、`UserPromptSubmit`、`PreToolUse`、`PermissionRequest`、`PostToolUse`、`PostToolUseFailure`、`Stop`。在运行配置中显式启用:
+
+```json
+{
+  "hooks": {
+    "enabled": true,
+    "events": {
+      "PreToolUse": [
+        {
+          "matcher": "Bash",
+          "hooks": [
+            {
+              "type": "process",
+              "command": "node",
+              "args": ["/absolute/path/to/guard.mjs"],
+              "timeoutMs": 10000
+            }
+          ]
+        }
+      ]
+    }
+  }
+}
+```
+
+此示例要求外部 Node。`guard.mjs` 读取 stdin JSON,以下示例用于验证拒绝路径,会拒绝全部匹配的 Bash 调用:
+
+```js
+let input = "";
+for await (const chunk of process.stdin) input += chunk;
+const event = JSON.parse(input);
+if (event.hook_event_name === "PreToolUse") {
+  process.stdout.write(
+    JSON.stringify({
+      hookSpecificOutput: {
+        hookEventName: "PreToolUse",
+        permissionDecision: "deny",
+        permissionDecisionReason: "本次测试禁止 Bash。",
+      },
+    }),
+  );
+}
+```
+
+这是 Hook 协议示例,不是完整安全策略。其他工具仍可能产生文件或网络副作用。
+
+## 项目 Hook 信任
+
+放在项目运行配置中的 Hook 默认未信任。开启 `hooks.enabled`、打开项目或使用 yolo 都不会自动信任它。
+
+```sh
+zcode hooks trust review --workspace /absolute/path/to/project --json
+zcode hooks trust grant --workspace /absolute/path/to/project --hook-digest SHA256_FROM_REVIEW
+zcode hooks trust status --workspace /absolute/path/to/project --json
+zcode hooks trust revoke --workspace /absolute/path/to/project --hook-digest SHA256_FROM_REVIEW
+```
+
+先审查命令和来源,再使用 review 返回的 digest。需要批量授权当前声明时,使用 `--all-current --bundle-digest SHA256_FROM_REVIEW`;不要省略绑定到当前内容的 digest。
+
+```text
+发现项目 Hook → 未信任,跳过执行 → review → grant
+→ 下一次自然事件可执行
+声明改变 → digest 改变 → 再次未信任
+```
+
+信任绑定工作区身份和声明内容。已跳过的 SessionStart 不会在当前任务中补跑,验证时创建新会话。信任存储损坏会 fail closed,`status` 返回原因;先备份并按诊断恢复存储,不要把损坏当作“已授权”。
+
+## 输入、输出与错误
+
+stdin 包含事件名、会话、工作目录和相关工具信息;兼容字段可能同时包含 camelCase 和 snake_case。只读取当前事件需要的字段。
+
+同步 `PreToolUse` 可返回 `allow`、`ask`、`deny`、`updatedInput` 和 `additionalContext`。退出码 `2` 表达阻断;其他失败、超时及非法输出会产生诊断,不能把所有异常都当作可靠拒绝。多个 Hook 需要通过事件记录核对最终结果。
+
+`type: "command"` 支持 shell 命令及异步执行。`async: true` 的后台输出不能用于同步阻断或改写本次工具输入;需要这些作用时使用同步 Hook。`timeoutMs` 单位为毫秒,兼容字段 `timeout` 单位为秒。
+
+matcher 不总是正则:`Write|Edit` 走精确工具名列表;包含其他正则语法时才进入正则匹配。事件的匹配对象不同,工具事件匹配工具名,SessionStart 匹配启动来源。
+
+插件也可贡献可执行 Hook。排查时同时检查插件启用状态和 Hook 来源;不要仅凭用户配置中的开关推断所有插件 Hook 都已关闭。批量任务应记录实际加载的声明和信任状态。

+ 72 - 0
apps/zcode-cli/docs/usage/10-plugins.md

@@ -0,0 +1,72 @@
+# 10 · Plugins
+
+插件用于分发技能、自定义命令、Hook 和 MCP 等扩展。CLI 支持安装和市场管理,不再限于本地目录。插件数量、版本和默认启用状态会变化,以清单为准。
+
+## 常用命令
+
+```sh
+zcode plugins list --json
+zcode plugins list --available --json
+zcode plugins marketplace list --json
+zcode plugins marketplace add /absolute/path/to/marketplace
+zcode plugins install example-plugin@example-market --scope user
+zcode plugins enable example-plugin@example-market
+zcode plugins disable example-plugin@example-market
+zcode plugins update example-plugin@example-market
+zcode plugins uninstall example-plugin@example-market --keep-data
+zcode plugins marketplace update example-market
+zcode plugins marketplace remove example-market
+```
+
+示例市场和插件须先存在。`--scope` 支持 `user` 和 `project`;修改项目启用配置时指定对应工作目录。安装、启用、更新和卸载是不同操作,完成后重新查看清单,并用新进程验证。
+
+`plugins list` 可以独立触发内置插件准备,无需先运行一次模型对话。全局关闭插件、缺少资源或准备失败也可能导致列表为空;先看诊断,不要用付费 prompt 作为初始化步骤。
+
+## 本地插件
+
+```text
+example-plugin/
+  .zcode-plugin/plugin.json
+  skills/greet/SKILL.md
+  commands/hello.md
+```
+
+manifest 示例:
+
+```json
+{
+  "name": "example-plugin",
+  "version": "0.1.0",
+  "description": "示例技能与命令",
+  "skills": "skills",
+  "commands": "commands"
+}
+```
+
+技能和命令内容见[Skills](08-skills.md)。运行配置启用本地目录:
+
+```json
+{
+  "plugins": {
+    "enabled": true,
+    "dirs": ["/absolute/path/to/example-plugin"]
+  }
+}
+```
+
+验证:
+
+```sh
+zcode plugins validate /absolute/path/to/example-plugin --json
+zcode plugins list --json
+zcode skills list --json
+zcode commands list --json
+```
+
+插件可携带本地可执行内容。安装前审查其 Hook、MCP 命令、依赖和数据访问范围。validate 只检查结构与诊断,不证明插件安全或所有功能可用。兼容 manifest 中的字段也不一定具有运行时实现;以加载诊断为准。
+
+## 数据与复现
+
+默认目录为 `~/.zcode/cli/plugins/`:市场索引、安装记录、`cache/` 中的版本内容,以及 `data/` 中的持久数据分别管理。启用态还保存在运行配置中。只复制缓存不能完整恢复安装和启用状态。
+
+插件需要持久写入时使用插件数据目录,不要改插件代码目录。卸载前确认是否保留数据,批量实验固定版本并归档非敏感清单。不要在比较实验中自动更新市场或插件。

+ 34 - 0
apps/zcode-cli/docs/usage/11-memory.md

@@ -0,0 +1,34 @@
+# 11 · 指令与记忆
+
+`AGENTS.md` 是用户或项目提供的指令,Memory 是运行过程中存取的记忆。二者都可能影响模型输入,但控制方式不同。
+
+## AGENTS.md
+
+当前指令装配会合并用户目录中的 `~/.zcode/AGENTS.md` 与工作区查找得到的项目 `AGENTS.md`,先用户、后项目。工作区范围与当前有效目录影响查找结果;不要默认每个父目录中的指令文件都会叠加,也不要默认其他产品的指令文件名会自动导入。
+
+验证指令是否进入上下文时,使用受控的无敏感标记或检查实际请求,避免依靠模型声称“已阅读”。并发评测应使用隔离用户目录和固定工作区,记录这两处指令文件的内容哈希。
+
+## Memory 开关
+
+记忆总能力由 `features.memory` 控制,使用行为还受 `memory.use` 控制。需要无记忆对照组时,在运行配置中显式关闭二者:
+
+```json
+{
+  "features": { "memory": false },
+  "memory": { "use": false }
+}
+```
+
+普通 `--prompt` 和 `--target` 不默认开启自动记忆提取;这不等于已有记忆不会被读取或影响上下文。需要隔离时,同时使用全新的用户目录和数据基目录。
+
+## 记忆实验
+
+```sh
+zcode --prompt "执行本次记忆实验任务" --memory-bench --mode yolo --json
+```
+
+`--memory-bench` 仅用于 prompt,要求先启用记忆。它开启自动提取,并在返回结果前等待提取工作结束。默认没有固定的提取等待截止时间;实验启动器应设置自己的运行时限并记录取消状态。
+
+主任务成功不保证提取成功。分别观察主任务结果、提取诊断和后续召回表现。单轮结果、跨轮学习和跨任务复用应分别设计实验,避免把上一个样本的记忆带入下一个独立样本。
+
+不要直接编辑活跃会话数据库来清理记忆。优先为实验创建新的数据目录;需要保留记忆做跨轮实验时显式复用,并记录复用关系。

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

@@ -0,0 +1,31 @@
+# 12 · 排障
+
+## 先收集最小证据
+
+保存 `--version`、`doctor --json`、构建提交或产物 SHA-256、完整参数数组、有效工作目录、退出码、signal、stdout、stderr,以及脱敏的配置。先用隔离环境复现,避免改动日常开发的配置和会话。
+
+## 启动或配置失败
+
+- `Unknown option`:参数不属于该构建。确认是否把其他 CLI 的 `--model`、`--settings`、`--max-turns` 等参数带进来了;新源码的参数也可能尚未进入旧产物。
+- 模型缺失或改配置无效:检查个人 provider 文件、默认模型选择、API 类型和 Key;已迁移的源码构建不会每次重读旧 `model/provider` 设置。见[配置](03-config.md)。
+- 配置部分被忽略:检查 JSON 语法和字段诊断。MCP、Hook 等字段有独立校验,不要将所有问题归为凭据错误。
+- 构建能启动但资源缺失:保留 bundle 相邻资源,确认依赖和准备步骤完整;`doctor` 不会验证全部插件、模型或外部程序。
+- 平台或执行失败:核对 CPU 架构、系统版本和执行权限。Windows 使用 `.exe`;外部 Hook/MCP 依赖另行安装。
+
+## 工具没有产生结果
+
+- `No permission client configured`:本次调用需要审批,但 prompt 没有交互客户端。检查模式、工具及 Hook 决策。
+- 只输出计划:检查是否触发了计划模式;无人值守任务按[工具配置](04-tools.md)移除不需要的计划和提问工具。
+- 项目 Hook 不执行:检查 enabled、matcher、信任状态和事件是否自然发生;信任后不会补跑已跳过的 SessionStart。
+- 插件清单为空:检查插件总开关、资源准备与诊断。当前版本可直接 list,不要求先发模型请求。
+- MCP 注册后调用失败:分别检查服务鉴权、协议、外部依赖、权限和超时;模型列出的工具名不构成执行证据。
+
+## 输出与运行记录
+
+`/help` 等本地命令可能返回文本,不能用它验证普通 prompt 的 JSON 结构。`stream-json` 应逐行解析并检查最终 result 行。异常退出、被取消或输出被截断时,不要拼出一个虚假的成功结果。
+
+调试日志可能包含任务文本、路径、工具输出和模型请求。默认 model-io 日志存在压缩、裁剪和保留上限;缺失历史不能从摘要中恢复。见[运行记录与训练轨迹](13-automation.md)。
+
+轨迹转换出现 `model-io request.body must contain a messages array.` 时,检查原始记录是否保留了 `request.body.messages`。本次对当前默认日志已复现该错误;不能把转换失败的文件作为完整训练样本,也不能用另一层的消息结构强行补齐。需要完整数据时,在采集端保留实际 provider 请求和响应。
+
+提交问题时提供最小可复现任务和脱敏证据。删除 API Key、登录 token、Cookie 和私人内容;保留字段结构、错误码和必要的工具结果。

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

@@ -0,0 +1,101 @@
+# 13 · 批量任务与运行记录
+
+CLI 可以作为任务执行器;数据准备、环境隔离、资源预算和评分由外部启动器负责。现成 benchmark 的容器、超时、补丁提取和评分协议仍须单独适配,不能把一次 prompt 成功当作 benchmark 集成完成。
+
+## 每个样本固定哪些条件
+
+保存构建提交或二进制 SHA-256、CLI 版本与 doctor 输出、平台、模型与 provider 协议、非敏感模型选项、任务输入、工作区提交、扩展清单、工具过滤、权限模式和运行时限。API Key 与登录凭据不要归档。
+
+每个独立样本使用独立的工作目录、用户目录和数据基目录。只换 sessionId 或只设置 `ZCODE_STORAGE_DIR` 不足以隔离个人配置、插件、记忆和用户指令。允许跨轮复用的实验应显式记录复用关系。
+
+## 跨平台启动方式
+
+以下 Node.js 片段展示参数数组与子进程环境。由调用方传入真实路径和任务文本;不要把模型输出拼接为 shell 命令。示例假定模型配置和运行配置已写入 `runHome` 对应目录,具体格式见[配置](03-config.md)。
+
+```js
+import { spawn } from "node:child_process";
+
+// 这些值由任务启动器提供,不从模型输出中执行。
+const executable = process.argv[2]; // SEA 的绝对路径;Node bundle 则使用 Node 路径
+const workdir = process.argv[3];
+const runHome = process.argv[4];
+const prompt = process.argv[5];
+if (![executable, workdir, runHome, prompt].every(Boolean)) {
+  throw new Error("需要 executable、workdir、runHome、prompt");
+}
+
+// 实际任务中从受控的环境变量白名单构造,不继承个人凭据。
+const env = {};
+for (const [key, value] of Object.entries(process.env)) {
+  if (/^(path|systemroot|windir|comspec|pathext|temp|tmp|tmpdir)$/i.test(key)) {
+    env[key] = value;
+  }
+}
+Object.assign(env, { HOME: runHome, USERPROFILE: runHome, ZCODE_DATA_BASE_DIR: runHome });
+
+const args = [
+  // 使用 Node bundle 时,在这里先加入 zcode.cjs 的绝对路径。
+  "--prompt",
+  prompt,
+  "--cwd",
+  workdir,
+  "--mode",
+  "yolo",
+  "--disallowed-tools",
+  "AskUserQuestion EnterPlanMode ExitPlanMode",
+  "--output-format",
+  "stream-json",
+  "--no-color",
+];
+const child = spawn(executable, args, { cwd: workdir, env, shell: false });
+child.stdout.pipe(process.stdout);
+child.stderr.pipe(process.stderr);
+child.on("error", (error) => {
+  process.stderr.write(`${error.message}\n`);
+  process.exitCode = 1;
+});
+child.on("close", (code, signal) => {
+  process.stderr.write(`${JSON.stringify({ code, signal })}\n`);
+  process.exitCode = code ?? 1;
+});
+```
+
+这只是启动片段。生产启动器还要持续写入 stdout/stderr 文件、记录开始结束时间、限制磁盘用量,并由容器或进程管理器设置运行时限、终止整个进程树。不能只杀父进程后假设所有 Bash、MCP 和后台任务都结束。按目标系统验证进程树清理。
+
+## 如何判定一次运行
+
+```text
+启动失败 / 被取消 / 超时 → 保存失败证据,不判成功
+正常结束 → 解析输出 → 检查工具错误与任务产物 → 独立评分
+独立评分完成 → 生成样本状态与分数
+```
+
+保留 `sessionId`、`traceId`、`turnId`、原始退出码、signal 和超时状态。JSON 的 response 是最终回答;stream-json 包含事件和最终 result。二者都不等价于完整 provider 请求/响应,更不自动等价于可训练对话。
+
+恢复任务应显式使用 `--resume`,并保持同一隔离数据目录;不要让并发样本争用 `--continue` 的“最近会话”。
+
+## 训练轨迹与 model-io
+
+默认 model-io 日志用于诊断,可能使用 full/delta/tail 表达、字段裁剪和按文件大小保留。standalone CLI 不应被假定启用了 App 的完整 model-io 保留选项。生产默认有限保留通常为每个文件 64 MiB、保留最近 3 个会话文件;开发默认上限不同。采集开始前核对当前构建的[保留策略](../../../../docs/model-io-full-retention-setting.md)。
+
+源码仓库提供独立的测试辅助工具,未打包进生产 SEA。对兼容格式的已有日志,转换命令为:
+
+```sh
+pnpm --filter @zcode/prompt-trajectory model-io -- --input /absolute/path/to/model-io-session.jsonl --out /absolute/path/to/derived
+```
+
+转换器默认关注主轮次,展开可恢复的增量并按连续片段处理;它无法补回已裁剪、覆盖或缺失的请求。非增量请求也不能直接解释为 provider 缓存未命中。输出格式及记录工具说明见[轨迹工具](../../tools/prompt-trajectory/README.md)。
+
+本次对当前源码生成的默认日志执行上述命令,得到 `model-io request.body must contain a messages array.`:记录中的 `request.body.messages` 已被裁掉,转换器要求该字段。此路径未通过实际转换验收,不能直接用作训练数据流水线。保留原始日志和错误;不要把内部 `request.messages` 强行填回 provider 请求体来伪造完整记录。默认日志在本次运行中位于隔离数据目录的 `.zcode/cli/rollout/`。
+
+同一辅助包的 `record:prompt` 在本次源码基线上也未通过:启动时报 `createModelAdapter requires executionConfig`,尚未发出模型请求。它需要单独修复后再验收,不能作为当前可用的采集命令交付。
+
+需要训练数据时,明确采集层、协议、消息顺序、tool call 与 tool result 对应关系、失败样本策略以及隐私处理。使用受控 provider 记录完整请求/响应,并验证与 CLI 工具事件一致;不要只收集最终答案或让模型转述轨迹。
+
+采集时将[个人模型配置](03-config.md)中的 `api.baseUrl` 指向自己管理的、兼容所选协议的记录服务,再使用普通 CLI 执行任务。记录服务负责转发和保存真实请求/响应;保留流式分片顺序,按 tool call ID 关联调用与结果,并排除鉴权 header。先用一个可检查的工具任务验证记录完整,再运行批量任务。这条流程不依赖上述仓库辅助包。
+
+## 验证范围
+
+本指南在 2026-10-14 对照当前源码核对。已在 macOS arm64 构建 CLI,并用本地模拟 Chat Completions 服务验证个人 provider 配置、普通 JSON、stream-json、显式会话恢复、Bash 执行、plan 拒绝及同步 Hook 拒绝。还验证了本地插件结构、技能与命令发现、项目 Hook 信任的 review/grant/revoke。模拟服务验证接线与格式,不代表真实模型效果。默认 model-io 日志转换和辅助包 record:prompt 未通过,原因见上文。
+
+本次验证在源码工作区执行,未另行构建完整开源导出树。Windows、Linux、全部 SEA 目标、真实 provider、MCP 远程授权和完整 benchmark 评分未在本次文档更新中逐项验收。使用前按目标环境执行最小任务;不要将本指南理解为所有平台与扩展均已实测的声明。

+ 33 - 0
apps/zcode-cli/docs/usage/README.md

@@ -0,0 +1,33 @@
+# ZCode CLI 使用指南
+
+本指南面向从开源仓库构建 CLI 的使用者,重点介绍非交互调用、扩展配置和任务评测。无参数启动的 TUI 也可用于交互操作。本文随源码维护;不要仅凭 `0.16.x` 版本号判断两个构建的能力相同。
+
+## 从哪里开始
+
+1. [快速开始](01-quickstart.md):源码构建、可执行文件、自检和第一次调用。
+2. [命令行参考](02-cli-reference.md):参数、输出格式和退出码。
+3. [配置](03-config.md):运行配置、个人模型配置、旧配置迁移和环境变量。
+4. [工具与评测配置](04-tools.md):工具可见性、非交互限制和评测边界。
+5. [权限](05-permissions.md):权限模式、拒绝行为和执行证据。
+6. [会话](06-sessions.md):新建、恢复、目标、用量和持久化。
+7. [MCP](07-mcp.md):连接外部工具服务。
+8. [Skills](08-skills.md):技能发现、调用和自定义命令。
+9. [Hooks](09-hooks.md):生命周期脚本与工作区信任。
+10. [Plugins](10-plugins.md):安装、市场、本地插件和数据目录。
+11. [指令与记忆](11-memory.md):`AGENTS.md`、记忆隔离与提取。
+12. [排障](12-troubleshooting.md):启动、配置、权限和输出问题。
+13. [批量任务与运行记录](13-automation.md):可复现运行、结果判定和轨迹导出。
+
+## 版本与验证
+
+每次运行至少保存 `zcode --version`、`zcode doctor --json`、构建提交号或二进制 SHA-256。记录插件版本、模型 ID、模型配置和任务工作区。模型目录或插件市场可能独立更新,因此相同 CLI 版本不等于相同运行条件。
+
+本指南描述当前源码接口。旧构建可能缺少 `--workflow-mode`,或仍使用旧模型配置。先用对应章节的小型自检确定能力;`--help` 可能没有展示解析器支持的全部参数,不能只靠帮助文本判定。
+
+本次核对日期为 2026-10-14。具体验证范围和未验证项见[运行记录](13-automation.md#验证范围)。
+
+## 开源构建的范围
+
+源码构建需要本仓库的 workspace 依赖和运行资源。不要只复制 `zcode.cjs` 就假设插件、模型配置和原生工具资源齐全。Computer Use 在开源导出中使用占位实现,不能据此宣称开源构建具备完整的原生桌面控制能力。Browser Use 是独立能力,仍需可用的 Chrome/Chromium 和对应插件。
+
+示例中的服务地址、API Key、模型 ID 和绝对路径必须换成自己的值。示例不会提供可用凭据。通用模型接口配置与账号登录是不同入口,应按实际使用的 provider 选择。

+ 4 - 3
apps/zcode-cli/package.json

@@ -1,6 +1,6 @@
 {
 {
   "name": "zcode-cli",
   "name": "zcode-cli",
-  "version": "0.16.9",
+  "version": "0.17.0",
   "private": true,
   "private": true,
   "description": "A cross-platform TypeScript Node.js CLI with a small TUI and optional SEA packaging.",
   "description": "A cross-platform TypeScript Node.js CLI with a small TUI and optional SEA packaging.",
   "type": "module",
   "type": "module",
@@ -16,7 +16,7 @@
     "dev": "pnpm --filter @zcode/cli dev",
     "dev": "pnpm --filter @zcode/cli dev",
     "format": "oxfmt --write package.json \"packages/**/*.json\" \"packages/**/*.ts\" \"packages/**/*.mjs\"",
     "format": "oxfmt --write package.json \"packages/**/*.json\" \"packages/**/*.ts\" \"packages/**/*.mjs\"",
     "format:check": "oxfmt --check package.json \"packages/**/*.json\" \"packages/**/*.ts\" \"packages/**/*.mjs\"",
     "format:check": "oxfmt --check package.json \"packages/**/*.json\" \"packages/**/*.ts\" \"packages/**/*.mjs\"",
-    "lint": "turbo run lint",
+    "lint": "node ../../scripts/run-cli-lint.mjs",
     "lint:count": "node scripts/count-ts-lines.mjs",
     "lint:count": "node scripts/count-ts-lines.mjs",
     "lint:fix": "turbo run lint:fix",
     "lint:fix": "turbo run lint:fix",
     "prompt-trajectory:model-io": "pnpm --filter @zcode/prompt-trajectory model-io --",
     "prompt-trajectory:model-io": "pnpm --filter @zcode/prompt-trajectory model-io --",
@@ -27,6 +27,7 @@
     "release": "node ../../node_modules/release-it/bin/release-it.js --config .release-it.json",
     "release": "node ../../node_modules/release-it/bin/release-it.js --config .release-it.json",
     "release:dry": "pnpm run release --release-version",
     "release:dry": "pnpm run release --release-version",
     "sea": "pnpm --filter @zcode/cli sea",
     "sea": "pnpm --filter @zcode/cli sea",
+    "pretest": "pnpm --dir ../.. --filter @zcode/model-option-map build",
     "test": "turbo run test",
     "test": "turbo run test",
     "test:e2e:memory": "pnpm --dir e2e/memory run e2e:build",
     "test:e2e:memory": "pnpm --dir e2e/memory run e2e:build",
     "test:browser-headless": "pnpm --filter @zcode/browser-use-plugin... build && pnpm --filter @zcode/browser-use-plugin exec vitest run test/headless-browser.e2e.test.ts",
     "test:browser-headless": "pnpm --filter @zcode/browser-use-plugin... build && pnpm --filter @zcode/browser-use-plugin exec vitest run test/headless-browser.e2e.test.ts",
@@ -38,9 +39,9 @@
     "proxy-agent": "^8.0.1"
     "proxy-agent": "^8.0.1"
   },
   },
   "devDependencies": {
   "devDependencies": {
-    "@withfig/autocomplete": "2.692.3",
     "@types/node": "^24.0.0",
     "@types/node": "^24.0.0",
     "@vitest/coverage-v8": "^4.1.5",
     "@vitest/coverage-v8": "^4.1.5",
+    "@withfig/autocomplete": "2.692.3",
     "c8": "^11.0.0",
     "c8": "^11.0.0",
     "esbuild": "^0.25.0",
     "esbuild": "^0.25.0",
     "oxfmt": "^0.47.0",
     "oxfmt": "^0.47.0",

+ 15 - 4
apps/zcode-cli/packages/adapters/src/commands/index.ts

@@ -90,7 +90,12 @@ export class NodeCustomCommandAdapter implements CustomCommandPort {
   }
   }
 
 
   async loadCommand(
   async loadCommand(
-    request: { maxBytes?: number; name: string; roots?: CustomCommandRoot[]; workingDirectory: string },
+    request: {
+      maxBytes?: number;
+      name: string;
+      roots?: CustomCommandRoot[];
+      workingDirectory: string;
+    },
     options?: CustomCommandOperationOptions,
     options?: CustomCommandOperationOptions,
   ): Promise<CustomCommandContent> {
   ): Promise<CustomCommandContent> {
     throwIfAborted(options);
     throwIfAborted(options);
@@ -209,7 +214,7 @@ export class NodeCustomCommandAdapter implements CustomCommandPort {
       disableNonInteractive: parseBoolean(parsed.values["disable-noninteractive"]),
       disableNonInteractive: parseBoolean(parsed.values["disable-noninteractive"]),
       frontmatterKeys: parsed.keys,
       frontmatterKeys: parsed.keys,
       model: parseScalar(parsed.values.model),
       model: parseScalar(parsed.values.model),
-      name,
+      name: root.namespace ? `${root.namespace.toLowerCase()}/${name}` : name,
       path,
       path,
       plugin: root.plugin,
       plugin: root.plugin,
       rootPath: root.path,
       rootPath: root.path,
@@ -259,7 +264,8 @@ async function scanMarkdownFiles(
   } catch (error) {
   } catch (error) {
     diagnostics.push({
     diagnostics.push({
       code: "custom_command_scan_failed",
       code: "custom_command_scan_failed",
-      message: error instanceof Error ? error.message : `Failed to scan command directory: ${directory}`,
+      message:
+        error instanceof Error ? error.message : `Failed to scan command directory: ${directory}`,
       path: directory,
       path: directory,
       severity: "warning",
       severity: "warning",
     });
     });
@@ -362,7 +368,12 @@ function parseList(value: string | undefined): string[] {
 function extractDescription(body: string): string | undefined {
 function extractDescription(body: string): string | undefined {
   const line = body
   const line = body
     .split(/\r?\n/)
     .split(/\r?\n/)
-    .map((candidate) => candidate.replace(/^#+\s*/, "").replace(/^[-*]\s*/, "").trim())
+    .map((candidate) =>
+      candidate
+        .replace(/^#+\s*/, "")
+        .replace(/^[-*]\s*/, "")
+        .trim(),
+    )
     .find(Boolean);
     .find(Boolean);
   return line ? truncate(line, MAX_DESCRIPTION_LENGTH) : undefined;
   return line ? truncate(line, MAX_DESCRIPTION_LENGTH) : undefined;
 }
 }

+ 14 - 1
apps/zcode-cli/packages/adapters/src/commands/roots.ts

@@ -1,6 +1,6 @@
 import { stat } from "node:fs/promises";
 import { stat } from "node:fs/promises";
 import { homedir } from "node:os";
 import { homedir } from "node:os";
-import { dirname, isAbsolute, join, resolve } from "node:path";
+import { basename, dirname, isAbsolute, join, resolve } from "node:path";
 import type { CustomCommandRoot, CustomCommandSource } from "@zcode/contracts";
 import type { CustomCommandRoot, CustomCommandSource } from "@zcode/contracts";
 
 
 const COMMANDS_DIR = "commands";
 const COMMANDS_DIR = "commands";
@@ -11,6 +11,7 @@ const ZCODE_DIR = ".zcode";
 const AGENTS_DIR = ".agents";
 const AGENTS_DIR = ".agents";
 
 
 export interface CustomCommandRootResolutionOptions {
 export interface CustomCommandRootResolutionOptions {
+  additionalDirectories?: readonly string[];
   extraRoots?: string[];
   extraRoots?: string[];
   extraResolvedRoots?: CustomCommandRoot[];
   extraResolvedRoots?: CustomCommandRoot[];
   homeDirectory?: string;
   homeDirectory?: string;
@@ -53,6 +54,18 @@ export async function resolveDefaultCustomCommandRoots(
     }
     }
   }
   }
 
 
+  for (const directory of new Set(
+    (options.additionalDirectories ?? []).map((path) => resolve(path)),
+  )) {
+    if (directory === resolvedWorkingDirectory) continue;
+    roots.push(
+      ...commandRootsForBase(directory, "project", nextPriority).map((item) => ({
+        ...item,
+        namespace: basename(directory),
+      })),
+    );
+  }
+
   roots.push(...(options.extraResolvedRoots ?? []));
   roots.push(...(options.extraResolvedRoots ?? []));
 
 
   return roots;
   return roots;

+ 4 - 10
apps/zcode-cli/packages/adapters/src/config/schema.ts

@@ -44,6 +44,7 @@ const memorySchema = z.object({
 });
 });
 
 
 const mcpServerBaseSchema = {
 const mcpServerBaseSchema = {
+  alwaysLoad: z.boolean().optional(),
   // 设置页和 MCP adapter 已支持协议选择;配置入口漏掉该字段会因 strict 校验丢弃整个 server。
   // 设置页和 MCP adapter 已支持协议选择;配置入口漏掉该字段会因 strict 校验丢弃整个 server。
   protocolVersion: z.enum(["auto", "legacy", "2026-07-28"]).optional(),
   protocolVersion: z.enum(["auto", "legacy", "2026-07-28"]).optional(),
   enabled: z.boolean().optional(),
   enabled: z.boolean().optional(),
@@ -165,10 +166,7 @@ const pluginsSchema = z.object({
   dirs: z.array(z.string().min(1)).optional(),
   dirs: z.array(z.string().min(1)).optional(),
   enabledPlugins: z.record(z.string(), z.boolean()).optional(),
   enabledPlugins: z.record(z.string(), z.boolean()).optional(),
   extraKnownMarketplaces: z
   extraKnownMarketplaces: z
-    .record(
-      z.string().min(1),
-      z.object({ source: pluginMarketplaceSourceSchema }).strict(),
-    )
+    .record(z.string().min(1), z.object({ source: pluginMarketplaceSourceSchema }).strict())
     .optional(),
     .optional(),
   options: z.record(z.string(), z.record(z.string(), pluginOptionValueSchema)).optional(),
   options: z.record(z.string(), z.record(z.string(), pluginOptionValueSchema)).optional(),
   suppressedBuiltins: z.array(z.string().min(1)).optional(),
   suppressedBuiltins: z.array(z.string().min(1)).optional(),
@@ -439,12 +437,8 @@ function normalizePluginConfig(
   }
   }
   const suppressedBuiltins = plugins.suppressedBuiltins
   const suppressedBuiltins = plugins.suppressedBuiltins
     ? plugins.suppressedBuiltins.reduce<string[]>((ids, id) => {
     ? plugins.suppressedBuiltins.reduce<string[]>((ids, id) => {
-        const canonicalId =
-          id === LEGACY_CUA_PLUGIN_ID ? CANONICAL_CUA_PLUGIN_ID : id;
-        if (
-          canonicalId === CANONICAL_CUA_PLUGIN_ID &&
-          ids.includes(CANONICAL_CUA_PLUGIN_ID)
-        ) {
+        const canonicalId = id === LEGACY_CUA_PLUGIN_ID ? CANONICAL_CUA_PLUGIN_ID : id;
+        if (canonicalId === CANONICAL_CUA_PLUGIN_ID && ids.includes(CANONICAL_CUA_PLUGIN_ID)) {
           return ids;
           return ids;
         }
         }
         ids.push(canonicalId);
         ids.push(canonicalId);

+ 25 - 1
apps/zcode-cli/packages/adapters/src/fs/text-metadata.ts

@@ -12,6 +12,7 @@ const UTF16LE_BOM = [0xff, 0xfe] as const;
 const LEGACY_CHINESE_ENCODINGS = ["gb2312", "gbk", "gb18030"] as const;
 const LEGACY_CHINESE_ENCODINGS = ["gb2312", "gbk", "gb18030"] as const;
 const BINARY_CONTROL_BYTE_THRESHOLD = 0.3;
 const BINARY_CONTROL_BYTE_THRESHOLD = 0.3;
 const MAX_DETECTION_TRAILING_DROP_BYTES = 3;
 const MAX_DETECTION_TRAILING_DROP_BYTES = 3;
+const MAX_UTF8_SEQUENCE_BYTES = 4;
 const NON_TEXT_ENCODINGS = new Set(["base64", "base64url", "hex"]);
 const NON_TEXT_ENCODINGS = new Set(["base64", "base64url", "hex"]);
 
 
 type LegacyChineseEncoding = (typeof LEGACY_CHINESE_ENCODINGS)[number];
 type LegacyChineseEncoding = (typeof LEGACY_CHINESE_ENCODINGS)[number];
@@ -133,7 +134,11 @@ function roundTripsWithOptionalTrailingDrop(
   encoding: LegacyChineseEncoding,
   encoding: LegacyChineseEncoding,
 ): boolean {
 ): boolean {
   if (buffer.length === 0) return true;
   if (buffer.length === 0) return true;
-  for (let drop = 0; drop <= Math.min(MAX_DETECTION_TRAILING_DROP_BYTES, buffer.length); drop += 1) {
+  for (
+    let drop = 0;
+    drop <= Math.min(MAX_DETECTION_TRAILING_DROP_BYTES, buffer.length);
+    drop += 1
+  ) {
     const candidate = drop === 0 ? buffer : buffer.subarray(0, buffer.length - drop);
     const candidate = drop === 0 ? buffer : buffer.subarray(0, buffer.length - drop);
     if (candidate.length === 0) continue;
     if (candidate.length === 0) continue;
     const decoded = iconv.decode(candidate, encoding);
     const decoded = iconv.decode(candidate, encoding);
@@ -143,8 +148,27 @@ function roundTripsWithOptionalTrailingDrop(
   return false;
   return false;
 }
 }
 
 
+export function getUtf8CompletionBytes(buffer: Buffer): number {
+  // 这里只计算尾部候选所缺的字节;补齐后仍须严格校验,不能据此确认编码。
+  let start = buffer.length - 1;
+  const earliestStart = Math.max(0, buffer.length - MAX_UTF8_SEQUENCE_BYTES);
+  while (start > earliestStart && (buffer[start]! & 0xc0) === 0x80) start -= 1;
+  const lead = buffer[start];
+  if (lead === undefined) return 0;
+  const sequenceBytes =
+    lead >= 0xc2 && lead <= 0xdf
+      ? 2
+      : lead >= 0xe0 && lead <= 0xef
+        ? 3
+        : lead >= 0xf0 && lead <= 0xf4
+          ? 4
+          : 0;
+  return Math.max(0, sequenceBytes - (buffer.length - start));
+}
+
 function isValidUtf8(buffer: Buffer): boolean {
 function isValidUtf8(buffer: Buffer): boolean {
   try {
   try {
+    // stream 模式会把 GBK 的 D6 暂存为 UTF-8 候选;必须补齐后严格校验,拒绝 D6 D0 等非法序列。
     new TextDecoder("utf-8", { fatal: true }).decode(buffer);
     new TextDecoder("utf-8", { fatal: true }).decode(buffer);
     return true;
     return true;
   } catch {
   } catch {

+ 29 - 5
apps/zcode-cli/packages/adapters/src/fs/text-range-reader.ts

@@ -12,6 +12,7 @@ import {
   decodeTextBuffer,
   decodeTextBuffer,
   detectLineEndings,
   detectLineEndings,
   detectTextEncoding,
   detectTextEncoding,
+  getUtf8CompletionBytes,
   normalizeLineEndings,
   normalizeLineEndings,
   shouldNormalizeLineEndings,
   shouldNormalizeLineEndings,
 } from "./text-metadata.js";
 } from "./text-metadata.js";
@@ -167,9 +168,26 @@ async function detectEncodingFromHead(
   throwIfAborted(signal);
   throwIfAborted(signal);
   const handle = await open(path, "r");
   const handle = await open(path, "r");
   try {
   try {
-    const sample = Buffer.alloc(ENCODING_SAMPLE_BYTES);
-    const { bytesRead } = await handle.read(sample, 0, sample.byteLength, 0);
-    return detectTextEncoding(sample.subarray(0, bytesRead));
+    let sample = Buffer.alloc(ENCODING_SAMPLE_BYTES);
+    let totalBytesRead = 0;
+    while (totalBytesRead < sample.byteLength) {
+      throwIfAborted(signal);
+      const { bytesRead } = await handle.read(
+        sample,
+        totalBytesRead,
+        sample.byteLength - totalBytesRead,
+        totalBytesRead,
+      );
+      if (bytesRead === 0) break;
+      totalBytesRead += bytesRead;
+      if (totalBytesRead === ENCODING_SAMPLE_BYTES) {
+        // 样本可能切在 UTF-8 字符中间;只补足当前候选,固定扩样会再次切开后一个字符。
+        const missingBytes = getUtf8CompletionBytes(sample);
+        if (missingBytes > 0) sample = Buffer.concat([sample, Buffer.alloc(missingBytes)]);
+      }
+    }
+    throwIfAborted(signal);
+    return detectTextEncoding(sample.subarray(0, totalBytesRead), path);
   } finally {
   } finally {
     await handle.close();
     await handle.close();
   }
   }
@@ -184,9 +202,15 @@ function normalizeLimitLines(limitLines: number | undefined): number | undefined
   return Math.max(0, Math.trunc(limitLines));
   return Math.max(0, Math.trunc(limitLines));
 }
 }
 
 
-function selectLines(lines: string[], offsetLine: number, limitLines: number | undefined): string[] {
+function selectLines(
+  lines: string[],
+  offsetLine: number,
+  limitLines: number | undefined,
+): string[] {
   const limit = normalizeLimitLines(limitLines);
   const limit = normalizeLimitLines(limitLines);
-  return limit === undefined ? lines.slice(offsetLine) : lines.slice(offsetLine, offsetLine + limit);
+  return limit === undefined
+    ? lines.slice(offsetLine)
+    : lines.slice(offsetLine, offsetLine + limit);
 }
 }
 
 
 function shouldSelectLine(
 function shouldSelectLine(

+ 7 - 0
apps/zcode-cli/packages/adapters/src/mcp/descriptor.ts

@@ -12,13 +12,20 @@ export function normalizeMcpToolDescriptor(
   tool: unknown,
   tool: unknown,
   timeoutMs?: number,
   timeoutMs?: number,
   official?: boolean,
   official?: boolean,
+  alwaysLoad?: boolean,
 ): McpToolDescriptor {
 ): McpToolDescriptor {
   const record = isRecord(tool) ? tool : {};
   const record = isRecord(tool) ? tool : {};
+  const meta = isRecord(record._meta) ? record._meta : {};
   const toolName = typeof record.name === "string" ? record.name : "unknown";
   const toolName = typeof record.name === "string" ? record.name : "unknown";
   // 插件 UI:tools/list 的 `_meta` 只在这里读一次,归一化成 descriptor.ui;下游不再碰原始 _meta。
   // 插件 UI:tools/list 的 `_meta` 只在这里读一次,归一化成 descriptor.ui;下游不再碰原始 _meta。
   const ui = normalizeMcpToolUiMeta(record._meta);
   const ui = normalizeMcpToolUiMeta(record._meta);
   return {
   return {
     serverName,
     serverName,
+    alwaysLoad: alwaysLoad === true || meta["anthropic/alwaysLoad"] === true,
+    searchHint:
+      typeof meta["anthropic/searchHint"] === "string"
+        ? meta["anthropic/searchHint"].replace(/\s+/g, " ").trim()
+        : undefined,
     toolName,
     toolName,
     name: `mcp__${sanitizeMcpName(serverName)}__${sanitizeMcpName(toolName)}`,
     name: `mcp__${sanitizeMcpName(serverName)}__${sanitizeMcpName(toolName)}`,
     description: typeof record.description === "string" ? record.description : undefined,
     description: typeof record.description === "string" ? record.description : undefined,

+ 12 - 0
apps/zcode-cli/packages/adapters/src/mcp/index.ts

@@ -1583,6 +1583,7 @@ class NodeMcpAdapter implements McpPort {
           // 原判据是 `type !== "sse"`,把 stdio 一起放了进来,等于这道门槛在 stdio 上为零。
           // 原判据是 `type !== "sse"`,把 stdio 一起放了进来,等于这道门槛在 stdio 上为零。
           // 注意这不是在挡凭证外泄(那由 origin 校验负责),而是在挡**结果伪造**。
           // 注意这不是在挡凭证外泄(那由 origin 校验负责),而是在挡**结果伪造**。
           config.type === "http" && config.auth?.type === ZCODE_OFFICIAL_MCP_AUTH_TYPE,
           config.type === "http" && config.auth?.type === ZCODE_OFFICIAL_MCP_AUTH_TYPE,
+          config.alwaysLoad,
         ),
         ),
       );
       );
       const negotiatedProtocolEra = client.getProtocolEra();
       const negotiatedProtocolEra = client.getProtocolEra();
@@ -2194,6 +2195,17 @@ class NodeMcpAdapter implements McpPort {
       if (!listeners.size) this.appConnectionListeners.delete(name);
       if (!listeners.size) this.appConnectionListeners.delete(name);
     };
     };
   }
   }
+  async waitForAppConnection(
+    name: string,
+  ): Promise<{ identity: string; generation: number } | null> {
+    const record = this.records.get(name);
+    if (!record) return null;
+    const generation = this.connectionGenerations.get(name) ?? 0;
+    // 会话恢复先于 MCP 握手完成;复用已有连接任务,避免首次打开把 connecting 误判为失败。
+    await record.connecting;
+    return this.isCurrentConnection(name, generation) ? this.appConnectionSnapshot(name) : null;
+  }
+
   appConnectionSnapshot(name: string): { identity: string; generation: number } | null {
   appConnectionSnapshot(name: string): { identity: string; generation: number } | null {
     const record = this.records.get(name);
     const record = this.records.get(name);
     if (!record?.client || record.status.status !== "connected") return null;
     if (!record?.client || record.status.status !== "connected") return null;

+ 18 - 0
apps/zcode-cli/packages/adapters/src/mcp/pool.ts

@@ -346,6 +346,24 @@ export function createMcpConnectionPool(options: McpConnectionPoolOptions): McpC
     };
     };
 
 
     return {
     return {
+      async waitForAppConnection(serverName) {
+        const key = leased.get(serverName);
+        if (!key) return null;
+        const entry = entries.get(key);
+        if (!entry) return null;
+        const connecting = entry.connecting;
+        await connecting;
+        const source = entry.adapter.waitForAppConnection
+          ? await entry.adapter.waitForAppConnection(serverName)
+          : (entry.adapter.appConnectionSnapshot?.(serverName) ?? null);
+        // 共享连接可能仍被其它会话持有;等待结束不能复活已释放或换源的本会话 lease。
+        return !leaseClosed &&
+          leased.get(serverName) === key &&
+          entries.get(key) === entry &&
+          entry.connecting === connecting
+          ? source
+          : null;
+      },
       appConnectionSnapshot(serverName) {
       appConnectionSnapshot(serverName) {
         const key = leased.get(serverName);
         const key = leased.get(serverName);
         return key ? (entries.get(key)?.adapter.appConnectionSnapshot?.(serverName) ?? null) : null;
         return key ? (entries.get(key)?.adapter.appConnectionSnapshot?.(serverName) ?? null) : null;

+ 4 - 0
apps/zcode-cli/packages/adapters/src/model/errors.ts

@@ -7,6 +7,7 @@ import {
   type ErrorAttribution,
   type ErrorAttribution,
   type ModelErrorCode,
   type ModelErrorCode,
   type ModelId,
   type ModelId,
+  type ModelUsage,
 } from "@zcode/contracts";
 } from "@zcode/contracts";
 
 
 export const ModelErrorSource = {
 export const ModelErrorSource = {
@@ -42,12 +43,14 @@ export function createLocalProviderConfigurationErrorContext(
 export interface AiSdkModelAdapterErrorOptions {
 export interface AiSdkModelAdapterErrorOptions {
   cause?: unknown;
   cause?: unknown;
   context?: Record<string, unknown>;
   context?: Record<string, unknown>;
+  usage?: ModelUsage;
 }
 }
 
 
 export class AiSdkModelAdapterError extends Error {
 export class AiSdkModelAdapterError extends Error {
   readonly code: ModelErrorCode;
   readonly code: ModelErrorCode;
   readonly cause?: unknown;
   readonly cause?: unknown;
   readonly context?: Record<string, unknown>;
   readonly context?: Record<string, unknown>;
+  readonly usage?: ModelUsage;
 
 
   constructor(code: ModelErrorCode, message: string, options?: AiSdkModelAdapterErrorOptions) {
   constructor(code: ModelErrorCode, message: string, options?: AiSdkModelAdapterErrorOptions) {
     super(message);
     super(message);
@@ -55,6 +58,7 @@ export class AiSdkModelAdapterError extends Error {
     this.code = code;
     this.code = code;
     this.cause = options?.cause;
     this.cause = options?.cause;
     this.context = options?.context;
     this.context = options?.context;
+    this.usage = options?.usage;
   }
   }
 
 
   enrichContext(context: Record<string, unknown>): this {
   enrichContext(context: Record<string, unknown>): this {

+ 5 - 0
apps/zcode-cli/packages/adapters/src/model/model.ts

@@ -24,6 +24,7 @@ export interface ModelExecutor {
 }
 }
 
 
 export interface CreateModelOptions {
 export interface CreateModelOptions {
+  requestCapabilities?: Model["requestCapabilities"];
   providerId: ModelProviderId;
   providerId: ModelProviderId;
   modelId: ModelId;
   modelId: ModelId;
   displayName?: string;
   displayName?: string;
@@ -38,6 +39,7 @@ export function createModel(input: CreateModelOptions): Model {
 }
 }
 
 
 class ExecutableModel implements Model {
 class ExecutableModel implements Model {
+  readonly requestCapabilities?: Model["requestCapabilities"];
   readonly providerId: ModelProviderId;
   readonly providerId: ModelProviderId;
   readonly modelId: ModelId;
   readonly modelId: ModelId;
   readonly displayName?: string;
   readonly displayName?: string;
@@ -47,6 +49,7 @@ class ExecutableModel implements Model {
   private readonly executor: ModelExecutor;
   private readonly executor: ModelExecutor;
 
 
   constructor(input: CreateModelOptions) {
   constructor(input: CreateModelOptions) {
+    this.requestCapabilities = input.requestCapabilities;
     this.providerId = input.providerId;
     this.providerId = input.providerId;
     this.modelId = input.modelId;
     this.modelId = input.modelId;
     this.displayName = input.displayName;
     this.displayName = input.displayName;
@@ -59,6 +62,7 @@ class ExecutableModel implements Model {
   bind(options?: ModelOptions): Model {
   bind(options?: ModelOptions): Model {
     if (!options || Object.keys(options).length === 0) return this;
     if (!options || Object.keys(options).length === 0) return this;
     return new ExecutableModel({
     return new ExecutableModel({
+      requestCapabilities: this.requestCapabilities,
       providerId: this.providerId,
       providerId: this.providerId,
       modelId: this.modelId,
       modelId: this.modelId,
       displayName: this.displayName,
       displayName: this.displayName,
@@ -82,6 +86,7 @@ class ExecutableModel implements Model {
     validateRequestProperties(this.properties, request);
     validateRequestProperties(this.properties, request);
     const requestOptions = request.options ?? {};
     const requestOptions = request.options ?? {};
     return {
     return {
+      toolSearchEnabled: request.toolSearchEnabled,
       messages: request.messages,
       messages: request.messages,
       tools: request.tools,
       tools: request.tools,
       responseJsonSchema: request.responseJsonSchema,
       responseJsonSchema: request.responseJsonSchema,

+ 10 - 10
apps/zcode-cli/packages/adapters/src/model/provider-endpoint-routing-fetch.ts

@@ -28,24 +28,24 @@ export function createProviderEndpointRoutingFetch(options: {
     }
     }
 
 
     const rewrittenInput = rewriteInput(input, decision.url);
     const rewrittenInput = rewriteInput(input, decision.url);
-    if (rewrittenInput instanceof Request) {
-      rewrittenInput.headers.delete("host");
-    }
-    return await options.fetch(rewrittenInput, withoutHostHeader(init));
+    return await options.fetch(rewrittenInput, routedRequestInit(input, init, decision.headers));
   };
   };
 }
 }
 
 
-function withoutHostHeader(
+function routedRequestInit(
+  input: Parameters<ProviderEndpointRoutingFetch>[0],
   init: Parameters<ProviderEndpointRoutingFetch>[1],
   init: Parameters<ProviderEndpointRoutingFetch>[1],
+  decisionHeaders: Readonly<Record<string, string>> | undefined,
 ): Parameters<ProviderEndpointRoutingFetch>[1] {
 ): Parameters<ProviderEndpointRoutingFetch>[1] {
-  if (!init?.headers) {
-    return init;
-  }
-  const headers = new Headers(init.headers);
-  if (!headers.has("host")) {
+  const inputHeaders = input instanceof Request ? input.headers : undefined;
+  if (!init?.headers && !inputHeaders && !decisionHeaders) {
     return init;
     return init;
   }
   }
+  const headers = new Headers(init?.headers ?? inputHeaders);
   headers.delete("host");
   headers.delete("host");
+  for (const [name, value] of Object.entries(decisionHeaders ?? {})) {
+    headers.set(name, value);
+  }
   return { ...init, headers };
   return { ...init, headers };
 }
 }
 
 

+ 1 - 0
apps/zcode-cli/packages/adapters/src/model/provider-endpoint-routing-options.ts

@@ -6,6 +6,7 @@ export interface ProviderEndpointRoutingFactoryOptions {
   appVersion?: string;
   appVersion?: string;
   httpClient: HttpClientPort;
   httpClient: HttpClientPort;
   logger?: Logger;
   logger?: Logger;
+  readZCodeJwt?: () => Promise<string | null>;
   sourceHeaders?: () =>
   sourceHeaders?: () =>
     | Promise<Readonly<Record<string, string>>>
     | Promise<Readonly<Record<string, string>>>
     | Readonly<Record<string, string>>;
     | Readonly<Record<string, string>>;

+ 70 - 2
apps/zcode-cli/packages/adapters/src/model/runner-diagnostics.ts

@@ -1,7 +1,8 @@
 import { summarizeRequestVerificationHeaders } from "@zcode/shared";
 import { summarizeRequestVerificationHeaders } from "@zcode/shared";
 import type { LanguageModelUsage } from "ai";
 import type { LanguageModelUsage } from "ai";
 import type { Logger, ModelUsage } from "@zcode/contracts";
 import type { Logger, ModelUsage } from "@zcode/contracts";
-import { ModelFailureReason as ModelFailureReasonValue } from "@zcode/contracts";
+import { ModelErrorCode, ModelFailureReason as ModelFailureReasonValue } from "@zcode/contracts";
+import { AiSdkModelAdapterError } from "./errors.js";
 import type { ClassifiedModelFailure } from "./failure-classifier.js";
 import type { ClassifiedModelFailure } from "./failure-classifier.js";
 import { detectProviderBusinessFinishError } from "./provider-finish-business-error.js";
 import { detectProviderBusinessFinishError } from "./provider-finish-business-error.js";
 import type { AiSdkGenerateTextResult } from "./runner-runtime.js";
 import type { AiSdkGenerateTextResult } from "./runner-runtime.js";
@@ -31,6 +32,7 @@ interface StreamDiagnostics {
   lastFinishChunk?: unknown;
   lastFinishChunk?: unknown;
   rawFinishReason?: unknown;
   rawFinishReason?: unknown;
   reasoningDeltaChars: number;
   reasoningDeltaChars: number;
+  hasReasoningContent: boolean;
   textDeltaChars: number;
   textDeltaChars: number;
   toolCallCount: number;
   toolCallCount: number;
   usage?: ModelUsage;
   usage?: ModelUsage;
@@ -41,6 +43,7 @@ export function createStreamDiagnostics(): StreamDiagnostics {
     chunkCounts: {},
     chunkCounts: {},
     errorChunkCount: 0,
     errorChunkCount: 0,
     reasoningDeltaChars: 0,
     reasoningDeltaChars: 0,
+    hasReasoningContent: false,
     textDeltaChars: 0,
     textDeltaChars: 0,
     toolCallCount: 0,
     toolCallCount: 0,
   };
   };
@@ -57,8 +60,14 @@ export function recordStreamChunkDiagnostic(diagnostics: StreamDiagnostics, chun
     return;
     return;
   }
   }
 
 
+  if (chunkType.startsWith("reasoning-")) {
+    // 空文本可能携带有效的 reasoning 签名,不能当作空超窗丢弃。
+    diagnostics.hasReasoningContent ||= Object.keys(asRecord(record.providerMetadata)).length > 0;
+  }
   if (chunkType === "reasoning-delta") {
   if (chunkType === "reasoning-delta") {
     diagnostics.reasoningDeltaChars += stringProperty(record, "text")?.length ?? 0;
     diagnostics.reasoningDeltaChars += stringProperty(record, "text")?.length ?? 0;
+    diagnostics.hasReasoningContent ||=
+      (stringProperty(record, "delta") ?? stringProperty(record, "text") ?? "").length > 0;
     return;
     return;
   }
   }
 
 
@@ -69,7 +78,8 @@ export function recordStreamChunkDiagnostic(diagnostics: StreamDiagnostics, chun
 
 
   if (chunkType === "finish") {
   if (chunkType === "finish") {
     diagnostics.finishReason = stringProperty(record, "finishReason") ?? diagnostics.finishReason;
     diagnostics.finishReason = stringProperty(record, "finishReason") ?? diagnostics.finishReason;
-    diagnostics.rawFinishReason = record.rawFinishReason;
+    diagnostics.rawFinishReason =
+      record.rawFinishReason ?? asRecord(record.providerMetadata).rawFinishReason;
     diagnostics.lastFinishChunk = chunk;
     diagnostics.lastFinishChunk = chunk;
     diagnostics.usage = normalizeUsage(
     diagnostics.usage = normalizeUsage(
       (record.totalUsage ?? record.usage) as Partial<LanguageModelUsage> | undefined,
       (record.totalUsage ?? record.usage) as Partial<LanguageModelUsage> | undefined,
@@ -413,13 +423,71 @@ export function isSuspiciousStreamDiagnostics(diagnostics: StreamDiagnostics): b
   });
   });
 }
 }
 
 
+const CONTEXT_LIMIT_FINISH_REASONS = new Set([
+  "context_exceeded",
+  "context_length_exceeded",
+  "context_window_exceeded",
+  "model_context_exceeded",
+  "model_context_window_exceeded",
+  "prompt_too_long",
+]);
+
+const EMPTY_COMPLETION_RETRY_EXCLUSIONS = new Set([
+  ...CONTEXT_LIMIT_FINISH_REASONS,
+  "refusal",
+  "content-filter",
+  "content_filter",
+]);
+
+export function createEmptyContextExceededError(input: {
+  finishReason?: string;
+  rawFinishReason?: unknown;
+  hasAssistantContent: boolean;
+  toolCallCount: number;
+  usage?: ModelUsage;
+}): AiSdkModelAdapterError | undefined {
+  // 只转换无有效输出的明确超窗;任何 partial 都保留给原调用方,不能迁移 Core 的续写策略。
+  if (input.hasAssistantContent || input.toolCallCount > 0) return undefined;
+  if (
+    ![input.finishReason, input.rawFinishReason].some(
+      (reason) =>
+        typeof reason === "string" && CONTEXT_LIMIT_FINISH_REASONS.has(reason.trim().toLowerCase()),
+    )
+  )
+    return undefined;
+  // 在成功终态前走既有失败链,避免无效 Continue 和遗留的成功请求身份;已报告用量随失败结算。
+  return new AiSdkModelAdapterError(
+    ModelErrorCode.ModelContextExceeded,
+    "Model request exceeded the provider context window.",
+    {
+      usage: input.usage,
+      context: { finishReason: input.finishReason, rawFinishReason: input.rawFinishReason },
+    },
+  );
+}
+
+function excludesEmptyCompletionRetry(value: unknown): boolean {
+  return (
+    typeof value === "string" && EMPTY_COMPLETION_RETRY_EXCLUSIONS.has(value.trim().toLowerCase())
+  );
+}
+
 export function isZeroOutputModelCompletion(input: {
 export function isZeroOutputModelCompletion(input: {
   finishReason?: string;
   finishReason?: string;
+  rawFinishReason?: unknown;
   reasoningLength: number;
   reasoningLength: number;
   textLength: number;
   textLength: number;
   toolCallCount: number;
   toolCallCount: number;
   usage?: ModelUsage;
   usage?: ModelUsage;
 }): boolean {
 }): boolean {
+  // 上下文超限、拒绝和内容过滤已有明确原因;此前零输出会先被原样重试。
+  // 这三类结果直接交给 core;普通输出额度和其他原因保持现有空响应重试边界。
+  if (
+    excludesEmptyCompletionRetry(input.finishReason) ||
+    excludesEmptyCompletionRetry(input.rawFinishReason)
+  ) {
+    return false;
+  }
   return (
   return (
     input.finishReason !== undefined &&
     input.finishReason !== undefined &&
     input.reasoningLength === 0 &&
     input.reasoningLength === 0 &&

+ 17 - 0
apps/zcode-cli/packages/adapters/src/model/runner-generate.ts

@@ -26,6 +26,7 @@ import {
   shouldRecordModelIO,
   shouldRecordModelIO,
 } from "./runner-debug.js";
 } from "./runner-debug.js";
 import {
 import {
+  createEmptyContextExceededError,
   getGenerateTextResultMetadata,
   getGenerateTextResultMetadata,
   isZeroOutputModelCompletion,
   isZeroOutputModelCompletion,
   logGenerateTextDiagnostics,
   logGenerateTextDiagnostics,
@@ -223,6 +224,18 @@ export async function runGenerateText(input: {
         ? serializeStructuredOutput(result)
         ? serializeStructuredOutput(result)
         : result.text;
         : result.text;
       const reasoning = normalizeReasoning(result.reasoning);
       const reasoning = normalizeReasoning(result.reasoning);
+      const contextError = createEmptyContextExceededError({
+        finishReason: result.finishReason,
+        rawFinishReason: result.rawFinishReason ?? result.providerMetadata?.rawFinishReason,
+        hasAssistantContent:
+          text.length > 0 ||
+          (reasoning ?? []).some(
+            (block) => block.text.length > 0 || Object.keys(block.providerOptions ?? {}).length > 0,
+          ),
+        toolCallCount: toolCalls?.length ?? 0,
+        usage,
+      });
+      if (contextError) throw contextError;
       const reasoningLength = (reasoning ?? []).reduce(
       const reasoningLength = (reasoning ?? []).reduce(
         (total, block) => total + block.text.length,
         (total, block) => total + block.text.length,
         0,
         0,
@@ -231,6 +244,9 @@ export async function runGenerateText(input: {
         input.request.preserveProviderStreamBoundaries !== true &&
         input.request.preserveProviderStreamBoundaries !== true &&
         isZeroOutputModelCompletion({
         isZeroOutputModelCompletion({
           finishReason: result.finishReason,
           finishReason: result.finishReason,
+          rawFinishReason:
+            result.rawFinishReason ??
+            (result.providerMetadata as Record<string, unknown> | undefined)?.rawFinishReason,
           reasoningLength,
           reasoningLength,
           textLength: text.length,
           textLength: text.length,
           toolCallCount: toolCalls?.length ?? 0,
           toolCallCount: toolCalls?.length ?? 0,
@@ -429,6 +445,7 @@ export async function runGenerateText(input: {
           ...modelFailureStatusFields(error, failure, options ? "response" : "prepare"),
           ...modelFailureStatusFields(error, failure, options ? "response" : "prepare"),
           timestamp: new Date(completedAt).toISOString(),
           timestamp: new Date(completedAt).toISOString(),
           type: "model_request_failed",
           type: "model_request_failed",
+          ...(error instanceof AiSdkModelAdapterError && error.usage ? { usage: error.usage } : {}),
         },
         },
         {
         {
           ...statusPublishOptions(input, admission),
           ...statusPublishOptions(input, admission),

+ 7 - 2
apps/zcode-cli/packages/adapters/src/model/runner-options.ts

@@ -1,6 +1,7 @@
 import { Output, jsonSchema } from "ai";
 import { Output, jsonSchema } from "ai";
 import type { ModelToolChoice } from "@zcode/contracts";
 import type { ModelToolChoice } from "@zcode/contracts";
 import type { EnvRecord } from "./model-execution.js";
 import type { EnvRecord } from "./model-execution.js";
+import { toolSearchHeaders } from "./tool-search.js";
 import { toAiSdkMessages } from "./transform.js";
 import { toAiSdkMessages } from "./transform.js";
 import { toAiSdkTools } from "./tool-transform.js";
 import { toAiSdkTools } from "./tool-transform.js";
 import type {
 import type {
@@ -60,12 +61,14 @@ export function createGenerateTextOptions(input: {
   return removeUndefined({
   return removeUndefined({
     model: input.resolved.model,
     model: input.resolved.model,
     messages: toAiSdkMessages(input.request.messages, {
     messages: toAiSdkMessages(input.request.messages, {
+      toolSearchEnabled: input.request.toolSearchEnabled,
       apiFormat: resolveProviderApiFormat(providerOptions),
       apiFormat: resolveProviderApiFormat(providerOptions),
       providerOptions,
       providerOptions,
       providerKind: input.resolved.providerKind,
       providerKind: input.resolved.providerKind,
       inputFormat: input.resolved.properties?.inputFormat,
       inputFormat: input.resolved.properties?.inputFormat,
     }),
     }),
     tools: toAiSdkTools(input.request.tools, {
     tools: toAiSdkTools(input.request.tools, {
+      toolSearchEnabled: input.request.toolSearchEnabled,
       providerKind: input.resolved.providerKind,
       providerKind: input.resolved.providerKind,
       modelId: input.resolved.modelId,
       modelId: input.resolved.modelId,
       requiresMfjsToolSchema: input.resolved.properties.requiresMfjsToolSchema,
       requiresMfjsToolSchema: input.resolved.properties.requiresMfjsToolSchema,
@@ -85,7 +88,7 @@ export function createGenerateTextOptions(input: {
     providerOptions: requestProviderOptions,
     providerOptions: requestProviderOptions,
     abortSignal: input.request.abortSignal,
     abortSignal: input.request.abortSignal,
     headers: mergeRequestHeaders(
     headers: mergeRequestHeaders(
-      input.resolved.headers,
+      toolSearchHeaders(input.resolved.headers, input.request.toolSearchEnabled),
       createModelRequestAttributionHeaders(input.statusContext),
       createModelRequestAttributionHeaders(input.statusContext),
     ),
     ),
     // ZCode owns system-message construction in core/context. Keep AI SDK from
     // ZCode owns system-message construction in core/context. Keep AI SDK from
@@ -121,12 +124,14 @@ export function createStreamTextOptions(input: {
   return removeUndefined({
   return removeUndefined({
     model: input.resolved.model,
     model: input.resolved.model,
     messages: toAiSdkMessages(input.request.messages, {
     messages: toAiSdkMessages(input.request.messages, {
+      toolSearchEnabled: input.request.toolSearchEnabled,
       apiFormat: resolveProviderApiFormat(providerOptions),
       apiFormat: resolveProviderApiFormat(providerOptions),
       providerOptions,
       providerOptions,
       providerKind: input.resolved.providerKind,
       providerKind: input.resolved.providerKind,
       inputFormat: input.resolved.properties?.inputFormat,
       inputFormat: input.resolved.properties?.inputFormat,
     }),
     }),
     tools: toAiSdkTools(input.request.tools, {
     tools: toAiSdkTools(input.request.tools, {
+      toolSearchEnabled: input.request.toolSearchEnabled,
       providerKind: input.resolved.providerKind,
       providerKind: input.resolved.providerKind,
       modelId: input.resolved.modelId,
       modelId: input.resolved.modelId,
       requiresMfjsToolSchema: input.resolved.properties.requiresMfjsToolSchema,
       requiresMfjsToolSchema: input.resolved.properties.requiresMfjsToolSchema,
@@ -143,7 +148,7 @@ export function createStreamTextOptions(input: {
     providerOptions: requestProviderOptions,
     providerOptions: requestProviderOptions,
     abortSignal: input.request.abortSignal,
     abortSignal: input.request.abortSignal,
     headers: mergeRequestHeaders(
     headers: mergeRequestHeaders(
-      input.resolved.headers,
+      toolSearchHeaders(input.resolved.headers, input.request.toolSearchEnabled),
       createModelRequestAttributionHeaders(input.statusContext),
       createModelRequestAttributionHeaders(input.statusContext),
     ),
     ),
     // ZCode owns system-message construction in core/context. Keep AI SDK from
     // ZCode owns system-message construction in core/context. Keep AI SDK from

+ 16 - 0
apps/zcode-cli/packages/adapters/src/model/runner-stream.ts

@@ -30,6 +30,7 @@ import {
   resolveModelStreamIdleTimeoutMs,
   resolveModelStreamIdleTimeoutMs,
 } from "./stream-idle-timeout.js";
 } from "./stream-idle-timeout.js";
 import {
 import {
+  createEmptyContextExceededError,
   createStreamDiagnostics,
   createStreamDiagnostics,
   isZeroOutputModelCompletion,
   isZeroOutputModelCompletion,
   isSuspiciousStreamDiagnostics,
   isSuspiciousStreamDiagnostics,
@@ -38,6 +39,7 @@ import {
   logStreamFailureDiagnostics,
   logStreamFailureDiagnostics,
   recordStreamChunkDiagnostic,
   recordStreamChunkDiagnostic,
 } from "./runner-diagnostics.js";
 } from "./runner-diagnostics.js";
+import { AiSdkModelAdapterError } from "./errors.js";
 import { canRetryEmptyCompletion, scheduleEmptyCompletionRetry } from "./empty-completion-retry.js";
 import { canRetryEmptyCompletion, scheduleEmptyCompletionRetry } from "./empty-completion-retry.js";
 import { createStreamTextOptions } from "./runner-options.js";
 import { createStreamTextOptions } from "./runner-options.js";
 import {
 import {
@@ -390,12 +392,24 @@ export async function* runStreamText(input: {
           }
           }
           throw error;
           throw error;
         }
         }
+        if (event.visibleEvents.some((visibleEvent) => visibleEvent.type === "finish")) {
+          const contextError = createEmptyContextExceededError({
+            finishReason: diagnostics.finishReason,
+            rawFinishReason: diagnostics.rawFinishReason,
+            hasAssistantContent: diagnostics.textDeltaChars > 0 || diagnostics.hasReasoningContent,
+            toolCallCount: toolCallAssembler.snapshotNormalizedToolCalls().length,
+            usage: diagnostics.usage,
+          });
+          // 先于 yield finish 进入既有 catch,每个请求只发布一个失败终态。
+          if (contextError) throw contextError;
+        }
         const shouldHoldEmptyCompletionEvents =
         const shouldHoldEmptyCompletionEvents =
           !event.emittedError &&
           !event.emittedError &&
           event.visibleEvents.some((visibleEvent) => visibleEvent.type === "finish") &&
           event.visibleEvents.some((visibleEvent) => visibleEvent.type === "finish") &&
           input.request.preserveProviderStreamBoundaries !== true &&
           input.request.preserveProviderStreamBoundaries !== true &&
           isZeroOutputModelCompletion({
           isZeroOutputModelCompletion({
             finishReason: diagnostics.finishReason,
             finishReason: diagnostics.finishReason,
+            rawFinishReason: diagnostics.rawFinishReason,
             reasoningLength: diagnostics.reasoningDeltaChars,
             reasoningLength: diagnostics.reasoningDeltaChars,
             textLength: diagnostics.textDeltaChars,
             textLength: diagnostics.textDeltaChars,
             toolCallCount: diagnostics.toolCallCount,
             toolCallCount: diagnostics.toolCallCount,
@@ -544,6 +558,7 @@ export async function* runStreamText(input: {
             input.request.preserveProviderStreamBoundaries !== true &&
             input.request.preserveProviderStreamBoundaries !== true &&
             isZeroOutputModelCompletion({
             isZeroOutputModelCompletion({
               finishReason: diagnostics.finishReason,
               finishReason: diagnostics.finishReason,
+              rawFinishReason: diagnostics.rawFinishReason,
               reasoningLength: diagnostics.reasoningDeltaChars,
               reasoningLength: diagnostics.reasoningDeltaChars,
               textLength: diagnostics.textDeltaChars,
               textLength: diagnostics.textDeltaChars,
               toolCallCount: diagnostics.toolCallCount,
               toolCallCount: diagnostics.toolCallCount,
@@ -788,6 +803,7 @@ export async function* runStreamText(input: {
           ...modelFailureStatusFields(error, failure, errorPhase),
           ...modelFailureStatusFields(error, failure, errorPhase),
           timestamp: new Date(completedAt).toISOString(),
           timestamp: new Date(completedAt).toISOString(),
           type: "model_request_failed",
           type: "model_request_failed",
+          ...(error instanceof AiSdkModelAdapterError && error.usage ? { usage: error.usage } : {}),
         },
         },
         {
         {
           ...statusPublishOptions(input, admission),
           ...statusPublishOptions(input, admission),

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

@@ -43,6 +43,7 @@ import {
   type AiSdkModelTextRequest,
   type AiSdkModelTextRequest,
   type ResolvedAiSdkModel,
   type ResolvedAiSdkModel,
 } from "./runner-runtime.js";
 } from "./runner-runtime.js";
+import { resolveToolSearchCapability } from "./tool-search.js";
 import { createModel, type ModelExecutionRequest } from "./model.js";
 import { createModel, type ModelExecutionRequest } from "./model.js";
 import { refreshOffPeakRequestAuth } from "./off-peak-request-auth.js";
 import { refreshOffPeakRequestAuth } from "./off-peak-request-auth.js";
 
 
@@ -215,6 +216,7 @@ export class AiSdkModelAdapter {
             }))
             }))
           : undefined;
           : undefined;
       return {
       return {
+        toolSearchEnabled: request.toolSearchEnabled,
         messages: request.messages,
         messages: request.messages,
         tools: request.tools,
         tools: request.tools,
         responseJsonSchema: request.responseJsonSchema,
         responseJsonSchema: request.responseJsonSchema,
@@ -283,6 +285,12 @@ export class AiSdkModelAdapter {
           });
           });
     };
     };
     return createModel({
     return createModel({
+      requestCapabilities: {
+        toolSearch: resolveToolSearchCapability(
+          options.providerConfig.api.type,
+          options.providerConfig.access,
+        ),
+      },
       providerId: resolved.providerId,
       providerId: resolved.providerId,
       modelId: resolved.modelId,
       modelId: resolved.modelId,
       displayName: options.displayName,
       displayName: options.displayName,

+ 1 - 0
apps/zcode-cli/packages/adapters/src/model/tool-result-media-projection.ts

@@ -192,6 +192,7 @@ function contentBlockToUserMediaParts(
 
 
     case "text":
     case "text":
     case "reasoning":
     case "reasoning":
+    case "tool_reference":
     case "resource_link":
     case "resource_link":
       return [];
       return [];
   }
   }

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

@@ -0,0 +1,30 @@
+import { TOOL_SEARCH_BETA, type ToolSearchCapability } from "@zcode/contracts";
+
+export function resolveToolSearchCapability(
+  apiType: string,
+  access: { type: string; mode?: string },
+): ToolSearchCapability {
+  const protocolSupported = apiType === "anthropic-messages";
+  const codingPlan =
+    access.type === "zhipu-coding-plan-api-key" ||
+    (access.type === "zhipu-account" &&
+      (access.mode === "individual-coding-plan" || access.mode === "team-coding-plan"));
+  return Object.freeze({ protocolSupported, defaultEnabled: protocolSupported && codingPlan });
+}
+
+export function toolSearchHeaders(headers: Record<string, string> | undefined, enabled?: boolean) {
+  if (!enabled) return headers;
+  const result = { ...headers };
+  const key =
+    Object.keys(result).find((name) => name.toLowerCase() === "anthropic-beta") ?? "anthropic-beta";
+  result[key] = [
+    ...new Set([
+      ...(result[key]
+        ?.split(",")
+        .map((value) => value.trim())
+        .filter(Boolean) ?? []),
+      TOOL_SEARCH_BETA,
+    ]),
+  ].join(",");
+  return result;
+}

+ 7 - 2
apps/zcode-cli/packages/adapters/src/model/tool-transform.ts

@@ -9,6 +9,7 @@ import { AiSdkModelAdapterError } from "./errors.js";
 import { isAnthropicFirstPartyModelId, toStrictToolSchema } from "./strict-tool-schema.js";
 import { isAnthropicFirstPartyModelId, toStrictToolSchema } from "./strict-tool-schema.js";
 
 
 export interface AiSdkToolTransformOptions {
 export interface AiSdkToolTransformOptions {
+  toolSearchEnabled?: boolean;
   requiresMfjsToolSchema?: boolean;
   requiresMfjsToolSchema?: boolean;
   supportsNativeWebSearch?: boolean;
   supportsNativeWebSearch?: boolean;
   providerKind?: "openai" | "anthropic" | "openai-compatible" | "gateway" | "custom";
   providerKind?: "openai" | "anthropic" | "openai-compatible" | "gateway" | "custom";
@@ -43,7 +44,7 @@ export function toAiSdkTools(
       ),
       ),
       ...(strictSchema === undefined ? {} : { strict: true }),
       ...(strictSchema === undefined ? {} : { strict: true }),
       needsApproval: contract.needsApproval,
       needsApproval: contract.needsApproval,
-      ...providerOptionsForClientTool(options),
+      ...providerOptionsForClientTool(options, contract),
     };
     };
 
 
     if (!contract.execute) {
     if (!contract.execute) {
@@ -222,7 +223,10 @@ function asPlainRecord(value: unknown): Record<string, unknown> | undefined {
     : undefined;
     : undefined;
 }
 }
 
 
-function providerOptionsForClientTool(options: AiSdkToolTransformOptions): {
+function providerOptionsForClientTool(
+  options: AiSdkToolTransformOptions,
+  contract: ModelToolContract,
+): {
   providerOptions?: Record<string, Record<string, boolean>>;
   providerOptions?: Record<string, Record<string, boolean>>;
 } {
 } {
   if (options.providerKind !== "anthropic") {
   if (options.providerKind !== "anthropic") {
@@ -237,6 +241,7 @@ function providerOptionsForClientTool(options: AiSdkToolTransformOptions): {
     providerOptions: {
     providerOptions: {
       anthropic: {
       anthropic: {
         eagerInputStreaming: false,
         eagerInputStreaming: false,
+        ...(options.toolSearchEnabled && contract.deferLoading ? { deferLoading: true } : {}),
       },
       },
     },
     },
   };
   };

+ 38 - 3
apps/zcode-cli/packages/adapters/src/model/transform.ts

@@ -25,6 +25,7 @@ import { dataUrlToDataContent, unsupportedInputMediaText } from "./media-transfo
 import { normalizeOpenAiCompatibleSystemMessages } from "./system-message-compat.js";
 import { normalizeOpenAiCompatibleSystemMessages } from "./system-message-compat.js";
 
 
 export interface AiSdkMessageTransformOptions {
 export interface AiSdkMessageTransformOptions {
+  toolSearchEnabled?: boolean;
   apiFormat?: string;
   apiFormat?: string;
   providerOptions?: Record<string, unknown>;
   providerOptions?: Record<string, unknown>;
   providerKind?: "openai" | "anthropic" | "openai-compatible" | "gateway" | "custom";
   providerKind?: "openai" | "anthropic" | "openai-compatible" | "gateway" | "custom";
@@ -170,15 +171,25 @@ function toAiSdkToolResultOutput(
 
 
   if (typeof content === "string") return { type: "text", value: content };
   if (typeof content === "string") return { type: "text", value: content };
 
 
-  if (textifyStructuredContent) {
+  const hasToolReferences = content.some((block) => block.type === "tool_reference");
+  if (textifyStructuredContent && !hasToolReferences) {
     return { type: "text", value: toStructuredToolResultText(content, options) };
     return { type: "text", value: toStructuredToolResultText(content, options) };
   }
   }
 
 
-  if (options.stripMedia) {
+  if (options.stripMedia && !hasToolReferences) {
     return { type: "text", value: modelMessageContentToText(content) };
     return { type: "text", value: modelMessageContentToText(content) };
   }
   }
 
 
-  const value = content.flatMap((block) => contentBlockToAiSdkToolResultParts(block, options));
+  // 工具引用不是媒体:媒体降级不能把引用变成名字文本,否则服务端无法展开定义。
+  const value = content.flatMap((block) => {
+    if (block.type !== "tool_reference" && (textifyStructuredContent || options.stripMedia)) {
+      const text = textifyStructuredContent
+        ? toStructuredToolResultText([block], options)
+        : modelMessageContentToText([block]);
+      return text ? [{ type: "text" as const, text }] : [];
+    }
+    return contentBlockToAiSdkToolResultParts(block, options);
+  });
   return value.length > 0
   return value.length > 0
     ? { type: "content", value }
     ? { type: "content", value }
     : { type: "text", value: modelMessageContentToText(content) };
     : { type: "text", value: modelMessageContentToText(content) };
@@ -192,6 +203,20 @@ function contentBlockToAiSdkToolResultParts(
     case "text":
     case "text":
       return block.text.length > 0 ? [{ type: "text", text: block.text }] : [];
       return block.text.length > 0 ? [{ type: "text", text: block.text }] : [];
 
 
+    case "tool_reference":
+      if (options.providerKind !== "anthropic" || !options.toolSearchEnabled) {
+        throw new AiSdkModelAdapterError(
+          ModelErrorCode.InvalidModelRequest,
+          "Tool references require active Anthropic ToolSearch",
+        );
+      }
+      return [
+        {
+          type: "custom",
+          providerOptions: { anthropic: { type: "tool-reference", toolName: block.toolName } },
+        },
+      ];
+
     case "reasoning":
     case "reasoning":
       return [];
       return [];
 
 
@@ -296,6 +321,11 @@ function contentBlockToAiSdkAssistantParts(
   options: AiSdkAssistantTransformOptions,
   options: AiSdkAssistantTransformOptions,
 ): AiSdkAssistantContentPart[] {
 ): AiSdkAssistantContentPart[] {
   switch (block.type) {
   switch (block.type) {
+    case "tool_reference":
+      throw new AiSdkModelAdapterError(
+        ModelErrorCode.InvalidModelRequest,
+        "Tool references must appear inside tool results",
+      );
     case "text":
     case "text":
       return block.text.length > 0 ? [{ type: "text", text: block.text }] : [];
       return block.text.length > 0 ? [{ type: "text", text: block.text }] : [];
 
 
@@ -405,6 +435,11 @@ function contentBlockToAiSdkUserParts(
   options: AiSdkMessageTransformOptions,
   options: AiSdkMessageTransformOptions,
 ): Extract<AiSdkUserContent, unknown[]> {
 ): Extract<AiSdkUserContent, unknown[]> {
   switch (block.type) {
   switch (block.type) {
+    case "tool_reference":
+      throw new AiSdkModelAdapterError(
+        ModelErrorCode.InvalidModelRequest,
+        "Tool references must appear inside tool results",
+      );
     case "text":
     case "text":
       return block.text.length > 0 ? [{ type: "text", text: block.text }] : [];
       return block.text.length > 0 ? [{ type: "text", text: block.text }] : [];
 
 

+ 3 - 0
apps/zcode-cli/packages/adapters/src/plugins/marketplace.ts

@@ -2284,6 +2284,9 @@ export function parseEntryStoreListing(
   };
   };
 
 
   const listing: PluginStoreListing = {};
   const listing: PluginStoreListing = {};
+  if (entry.publisherType === "official" || entry.publisherType === "community") {
+    listing.publisherType = entry.publisherType;
+  }
   const displayName = readString("displayName");
   const displayName = readString("displayName");
   if (displayName) listing.displayName = displayName;
   if (displayName) listing.displayName = displayName;
   const displayNameI18n = readStringMap("displayName_i18n");
   const displayNameI18n = readStringMap("displayName_i18n");

+ 13 - 14
apps/zcode-cli/packages/adapters/src/plugins/mcp.ts

@@ -4,7 +4,7 @@ import { findOfficialMcpReservedHeaders } from "@zcode/shared";
 import type {
 import type {
   McpOAuthConfig,
   McpOAuthConfig,
   McpServerConfig,
   McpServerConfig,
-  McpServerRuntimeSource,
+  McpServerConfigBase,
   PluginDiagnostic,
   PluginDiagnostic,
   PluginManifest,
   PluginManifest,
   PluginOptionValues,
   PluginOptionValues,
@@ -181,10 +181,15 @@ function resolveMcpServerConfig(
   if (!isRecord(server)) throw new Error("MCP server config must be an object");
   if (!isRecord(server)) throw new Error("MCP server config must be an object");
   const type = typeof server.type === "string" ? server.type : inferMcpType(server);
   const type = typeof server.type === "string" ? server.type : inferMcpType(server);
   if (!SUPPORTED_MCP_TYPES.has(type)) throw new Error(`Unsupported MCP transport: ${type}`);
   if (!SUPPORTED_MCP_TYPES.has(type)) throw new Error(`Unsupported MCP transport: ${type}`);
-  // ZCode 官方市场同时包含随应用装载的 Builtin Plugin 与按需安装的 CDN Plugin;后者运行时
-  // source 为 `cache`,因此必须按 marketplace 身份归类,不能只看 loader source。
-  const source: McpServerRuntimeSource = {
-    kind: context.loaded.marketplace === ZCODE_OFFICIAL_PLUGIN_MARKETPLACE ? "builtin" : "plugin",
+  // 修复原因:各 transport 分别重建配置曾漏传 alwaysLoad,导致插件常驻工具被延迟。
+  // 通用字段只在此解析;source 按 marketplace 归类,兼容 source 为 cache 的官方 CDN 插件。
+  const baseConfig: McpServerConfigBase = {
+    alwaysLoad: typeof server.alwaysLoad === "boolean" ? server.alwaysLoad : undefined,
+    enabled: typeof server.enabled === "boolean" ? server.enabled : undefined,
+    timeoutMs: typeof server.timeoutMs === "number" ? server.timeoutMs : undefined,
+    source: {
+      kind: context.loaded.marketplace === ZCODE_OFFICIAL_PLUGIN_MARKETPLACE ? "builtin" : "plugin",
+    },
   };
   };
 
 
   // zcode_official 允许 http 与 stdio,sse 出现即禁用该 MCP,不静默忽略——静默会让配置作者以为鉴权已生效。
   // zcode_official 允许 http 与 stdio,sse 出现即禁用该 MCP,不静默忽略——静默会让配置作者以为鉴权已生效。
@@ -224,6 +229,7 @@ function resolveMcpServerConfig(
     // 内置插件的 broker 凭据。manifest env spread 之后覆写,确保 user/manifest 无法覆盖。
     // 内置插件的 broker 凭据。manifest env spread 之后覆写,确保 user/manifest 无法覆盖。
     env[ZCODE_PLUGIN_ID_ENV_KEY] = context.loaded.id;
     env[ZCODE_PLUGIN_ID_ENV_KEY] = context.loaded.id;
     return {
     return {
+      ...baseConfig,
       type: "stdio",
       type: "stdio",
       command: resolveTemplate(command, context, { allowSensitive: false }),
       command: resolveTemplate(command, context, { allowSensitive: false }),
       args: Array.isArray(server.args)
       args: Array.isArray(server.args)
@@ -235,10 +241,7 @@ function resolveMcpServerConfig(
         typeof server.cwd === "string"
         typeof server.cwd === "string"
           ? resolveTemplate(server.cwd, context, { allowSensitive: false })
           ? resolveTemplate(server.cwd, context, { allowSensitive: false })
           : undefined,
           : undefined,
-      enabled: typeof server.enabled === "boolean" ? server.enabled : undefined,
       env,
       env,
-      source,
-      timeoutMs: typeof server.timeoutMs === "number" ? server.timeoutMs : undefined,
       ...(officialAuth
       ...(officialAuth
         ? {
         ? {
             auth: officialAuth,
             auth: officialAuth,
@@ -271,26 +274,22 @@ function resolveMcpServerConfig(
       );
       );
     }
     }
     return {
     return {
+      ...baseConfig,
       type: "http",
       type: "http",
       url: resolveTemplate(url, context, { allowSensitive: false }),
       url: resolveTemplate(url, context, { allowSensitive: false }),
-      enabled: typeof server.enabled === "boolean" ? server.enabled : undefined,
       headers,
       headers,
       auth: officialAuth,
       auth: officialAuth,
-      source,
       // provenance 由宿主生成;即便 .mcp.json 里写了 official 字段也会被此处覆盖。
       // provenance 由宿主生成;即便 .mcp.json 里写了 official 字段也会被此处覆盖。
       official: buildOfficialProvenance(identity),
       official: buildOfficialProvenance(identity),
-      timeoutMs: typeof server.timeoutMs === "number" ? server.timeoutMs : undefined,
     };
     };
   }
   }
 
 
   return {
   return {
+    ...baseConfig,
     type,
     type,
     url: resolveTemplate(url, context, { allowSensitive: false }),
     url: resolveTemplate(url, context, { allowSensitive: false }),
-    enabled: typeof server.enabled === "boolean" ? server.enabled : undefined,
     headers,
     headers,
     oauth,
     oauth,
-    source,
-    timeoutMs: typeof server.timeoutMs === "number" ? server.timeoutMs : undefined,
   } as McpServerConfig;
   } as McpServerConfig;
 }
 }
 
 

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

@@ -223,6 +223,7 @@ export class NodeSkillAdapter implements SkillPort {
       description,
       description,
       whenToUse: parseScalar(parsed.values.when_to_use),
       whenToUse: parseScalar(parsed.values.when_to_use),
       ...pluginAlias,
       ...pluginAlias,
+      ...(root.namespace ? { qualifiedName: `${root.namespace}/${name}` } : {}),
       path,
       path,
       directory: dirname(path),
       directory: dirname(path),
       rootPath: root.path,
       rootPath: root.path,
@@ -370,10 +371,7 @@ function readBlockScalar(
     line.trim().length === 0 ? "" : line.slice(indent ?? 0),
     line.trim().length === 0 ? "" : line.slice(indent ?? 0),
   );
   );
   return {
   return {
-    value:
-      style === "folded"
-        ? foldBlockScalarLines(contentLines)
-        : contentLines.join("\n").trim(),
+    value: style === "folded" ? foldBlockScalarLines(contentLines) : contentLines.join("\n").trim(),
     nextIndex: index,
     nextIndex: index,
   };
   };
 }
 }

+ 14 - 1
apps/zcode-cli/packages/adapters/src/skills/roots.ts

@@ -1,6 +1,6 @@
 import { stat } from "node:fs/promises";
 import { stat } from "node:fs/promises";
 import { homedir } from "node:os";
 import { homedir } from "node:os";
-import { dirname, isAbsolute, join, resolve } from "node:path";
+import { basename, dirname, isAbsolute, join, resolve } from "node:path";
 import type { SkillRoot, SkillSource } from "@zcode/contracts";
 import type { SkillRoot, SkillSource } from "@zcode/contracts";
 
 
 const GIT_MARKER = ".git";
 const GIT_MARKER = ".git";
@@ -12,6 +12,7 @@ const AGENTS_DIR = ".agents";
 
 
 export interface SkillRootResolutionOptions {
 export interface SkillRootResolutionOptions {
   homeDirectory?: string;
   homeDirectory?: string;
+  additionalDirectories?: readonly string[];
   extraRoots?: string[];
   extraRoots?: string[];
   extraResolvedRoots?: SkillRoot[];
   extraResolvedRoots?: SkillRoot[];
   includeZcodeSkills?: boolean;
   includeZcodeSkills?: boolean;
@@ -53,6 +54,18 @@ export async function resolveDefaultSkillRoots(
     }
     }
   }
   }
 
 
+  for (const directory of new Set(
+    (options.additionalDirectories ?? []).map((path) => resolve(path)),
+  )) {
+    if (directory === resolvedWorkingDirectory) continue;
+    roots.push(
+      ...skillRootsForBase(directory, "project", nextPriority).map((item) => ({
+        ...item,
+        namespace: basename(directory),
+      })),
+    );
+  }
+
   roots.push(...(options.extraResolvedRoots ?? []));
   roots.push(...(options.extraResolvedRoots ?? []));
 
 
   return roots;
   return roots;

+ 2 - 1
apps/zcode-cli/packages/adapters/src/storage/session-store/codecs.ts

@@ -60,6 +60,7 @@ export function decodeSessionRow(row: SessionRow): SessionInfo {
     directory: row.directory,
     directory: row.directory,
     path: row.path ?? undefined,
     path: row.path ?? undefined,
     title: row.title,
     title: row.title,
+    lastOutcome: row.last_outcome ?? undefined,
     titleSource: decodeSessionTitleSource(row.title_source),
     titleSource: decodeSessionTitleSource(row.title_source),
     titleMessageID: row.title_message_id ? (row.title_message_id as MessageId) : undefined,
     titleMessageID: row.title_message_id ? (row.title_message_id as MessageId) : undefined,
     version: row.version,
     version: row.version,
@@ -75,7 +76,7 @@ export function decodeSessionRow(row: SessionRow): SessionInfo {
       updated: row.time_updated,
       updated: row.time_updated,
       titleUpdated: row.time_title_updated ?? undefined,
       titleUpdated: row.time_title_updated ?? undefined,
       compacting: row.time_compacting ?? undefined,
       compacting: row.time_compacting ?? undefined,
-      archived: row.time_archived ?? undefined,
+      deleted: row.time_deleted ?? undefined,
     },
     },
   };
   };
 }
 }

+ 70 - 173
apps/zcode-cli/packages/adapters/src/storage/session-store/migration-runner.ts

@@ -1,3 +1,6 @@
+import { dirname, join, basename } from "node:path";
+import { sqliteMigrations, MigrationChecksumError } from "@zcode/shared/sqlite-migrations";
+import type { MigrationResult } from "@zcode/shared/sqlite-migrations";
 import {
 import {
   classifyDatabaseStartupError,
   classifyDatabaseStartupError,
   databaseMigrationIdSchema,
   databaseMigrationIdSchema,
@@ -6,16 +9,19 @@ import {
 } from "@zcode/shared";
 } from "@zcode/shared";
 import { createHash } from "node:crypto";
 import { createHash } from "node:crypto";
 import type { DatabaseSync } from "node:sqlite";
 import type { DatabaseSync } from "node:sqlite";
+import {
+  ensureSqliteSchemaMigrationTable,
+  SqliteSchemaMigrationChecksumError,
+} from "@zcode/shared/sqlite-migrations";
 import { SqliteSessionMigrationError } from "./errors.js";
 import { SqliteSessionMigrationError } from "./errors.js";
 import { SQLITE_MIGRATIONS } from "./migrations.js";
 import { SQLITE_MIGRATIONS } from "./migrations.js";
-import type { SchemaMigrationRow } from "./rows.js";
+type SchemaMigrationRow = { id: string; checksum: string };
 
 
 export const DEFAULT_SQLITE_STARTUP_LOCK_TIMEOUT_MS = 5_000;
 export const DEFAULT_SQLITE_STARTUP_LOCK_TIMEOUT_MS = 5_000;
 
 
 const SQLITE_BUSY = 5;
 const SQLITE_BUSY = 5;
 const WAL_RETRY_INITIAL_DELAY_MS = 10;
 const WAL_RETRY_INITIAL_DELAY_MS = 10;
 const WAL_RETRY_MAX_DELAY_MS = 200;
 const WAL_RETRY_MAX_DELAY_MS = 200;
-const waitBuffer = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
 
 
 export type SqliteMigrationPhase =
 export type SqliteMigrationPhase =
   | "checking"
   | "checking"
@@ -44,190 +50,77 @@ export interface AsyncSqliteMigrationOptions {
 
 
 export const DEFAULT_SQLITE_MIGRATION_WAIT_MS = 60 * 60_000;
 export const DEFAULT_SQLITE_MIGRATION_WAIT_MS = 60 * 60_000;
 const ASYNC_NATIVE_BUSY_TIMEOUT_MS = 25;
 const ASYNC_NATIVE_BUSY_TIMEOUT_MS = 25;
-type MigrationStep = SqliteMigrationProgress | { delayMs: number };
 
 
-export function runSqliteSessionMigrations(
-  db: DatabaseSync,
-  dbPath: string,
-  lockTimeoutMs = DEFAULT_SQLITE_STARTUP_LOCK_TIMEOUT_MS,
-): void {
-  for (const step of migrationSteps(db, dbPath, lockTimeoutMs)) {
-    if ("delayMs" in step) waitSync(step.delayMs);
-  }
+export async function runSqliteSessionMigrations(
+  db: DatabaseSync, dbPath: string, lockTimeoutMs = DEFAULT_SQLITE_STARTUP_LOCK_TIMEOUT_MS,
+): Promise<MigrationResult> {
+  return runSqliteSessionMigrationsAsync(db, dbPath, { lockWaitTimeoutMs: lockTimeoutMs });
 }
 }
 
 
 export async function runSqliteSessionMigrationsAsync(
 export async function runSqliteSessionMigrationsAsync(
-  db: DatabaseSync,
-  dbPath: string,
-  options: AsyncSqliteMigrationOptions = {},
-): Promise<void> {
-  // 同步 SQLite 仅短暂等待一次;真正的启动等待让出事件循环,通知可以先 flush。
-  // 业务连接不能继承升级的一小时等待预算。迁移结束(含失败)恢复原有 5 秒策略。
-  db.exec(`pragma busy_timeout = ${ASYNC_NATIVE_BUSY_TIMEOUT_MS}`);
-  const steps = migrationSteps(
-    db,
-    dbPath,
-    options.lockWaitTimeoutMs ?? DEFAULT_SQLITE_MIGRATION_WAIT_MS,
-  );
-  let failed = false;
-  try {
-    for (const step of steps) {
-      if ("delayMs" in step)
-        await new Promise<void>((resolve) => setTimeout(resolve, step.delayMs));
-      else if (step.phase === "failed") {
-        try {
-          await options.onProgress?.(step);
-        } catch {
-          /* 错误通知失败不能覆盖原数据库异常。 */
-        }
-      } else await options.onProgress?.(step);
-    }
-  } catch (error) {
-    failed = true;
-    throw error;
-  } finally {
-    // 通知传输失败也会关闭 generator 的事务,不能将半迁移连接交给业务。
-    try {
-      steps.return();
-      db.exec(`pragma busy_timeout = ${DEFAULT_SQLITE_STARTUP_LOCK_TIMEOUT_MS}`);
-    } catch (error) {
-      if (!failed) throw error;
-    }
-  }
-}
-
-function* migrationSteps(
-  db: DatabaseSync,
-  dbPath: string,
-  lockTimeoutMs: number,
-): Generator<MigrationStep, void> {
+  db: DatabaseSync, dbPath: string, options: AsyncSqliteMigrationOptions = {},
+): Promise<MigrationResult> {
   const startedAt = Date.now();
   const startedAt = Date.now();
-  const deadline = startedAt + Math.max(0, lockTimeoutMs);
-  let migrationFacts: DatabaseMigrationFacts | undefined;
-  const progress = (phase: SqliteMigrationPhase): SqliteMigrationProgress => ({
-    phase,
-    elapsedMs: Date.now() - startedAt,
-    ...(migrationFacts ? { migration: { ...migrationFacts } } : {}),
-  });
-  let transactionStarted = false;
-  function* acquire(operation: () => void): Generator<MigrationStep, void> {
-    // 每个拿锁阶段独立报告:预检前的未知等待不能吞掉确认迁移后的等待。
-    let waitingReported = false;
-    let retryDelayMs = WAL_RETRY_INITIAL_DELAY_MS;
-    while (true) {
-      try {
-        operation();
-        return;
-      } catch (error) {
-        // SQLITE_LOCKED 常指同连接/共享缓存冲突;只重试外部写者竞争的 SQLITE_BUSY。
+  const deadline = startedAt + (options.lockWaitTimeoutMs ?? DEFAULT_SQLITE_MIGRATION_WAIT_MS);
+  let migration: DatabaseMigrationFacts | undefined;
+  let migrationId: string | undefined;
+  let progressError: unknown;
+  const progress = async (phase: SqliteMigrationPhase, extra: Partial<SqliteMigrationProgress> = {}) => {
+    try { await options.onProgress?.({ phase, elapsedMs: Date.now() - startedAt, ...(migration ? { migration: { ...migration } } : {}), ...extra }); }
+    catch (error) { progressError = error; throw error; }
+  };
+  const acquire = async (operation: () => void) => {
+    let waiting = false;
+    let delay = WAL_RETRY_INITIAL_DELAY_MS;
+    for (;;) {
+      try { operation(); return; } catch (error) {
         if (!isSqliteBusyError(error)) throw error;
         if (!isSqliteBusyError(error)) throw error;
-        const remainingMs = deadline - Date.now();
-        if (remainingMs <= 0) throw lockTimeoutError(error, dbPath);
-        if (!waitingReported) {
-          waitingReported = true;
-          yield progress("waiting_for_lock");
-        }
-        yield { delayMs: Math.min(remainingMs, retryDelayMs) };
-        retryDelayMs = Math.min(WAL_RETRY_MAX_DELAY_MS, retryDelayMs * 2);
+        const remaining = deadline - Date.now();
+        if (remaining <= 0) throw lockTimeoutError(error, dbPath);
+        if (!waiting) { waiting = true; await progress("waiting_for_lock"); }
+        await new Promise<void>((resolve) => setTimeout(resolve, Math.min(delay, remaining)));
+        delay = Math.min(WAL_RETRY_MAX_DELAY_MS, delay * 2);
       }
       }
     }
     }
-  }
+  };
+  db.exec(`pragma busy_timeout = ${ASYNC_NATIVE_BUSY_TIMEOUT_MS}`);
   try {
   try {
-    yield progress("checking");
+    await progress("checking");
     db.exec("pragma foreign_keys = on");
     db.exec("pragma foreign_keys = on");
-    yield* acquire(() => {
+    await acquire(() => {
       const current = readJournalMode(db);
       const current = readJournalMode(db);
       if (current === "wal" || isMemoryJournalMode(dbPath, current)) return;
       if (current === "wal" || isMemoryJournalMode(dbPath, current)) return;
       const mode = readJournalMode(db, true);
       const mode = readJournalMode(db, true);
-      if (mode !== "wal" && !isMemoryJournalMode(dbPath, mode)) {
-        throw new SqliteSessionMigrationError(
-          `SQLite refused WAL journal mode for ${dbPath}; received ${mode}`,
-          { dbPath, kind: "sql_failed" },
-        );
-      }
+      if (mode !== "wal" && !isMemoryJournalMode(dbPath, mode))
+        throw new SqliteSessionMigrationError(`SQLite refused WAL journal mode for ${dbPath}; received ${mode}`, { dbPath, kind: "sql_failed" });
     });
     });
-    // 预检只决定展示;真正执行仍在拿锁后逐项核对,其他窗口完成后不会重复迁移。
-    yield* acquire(() => {
-      migrationFacts = {
-        kind: inspectMigrationKind(db, dbPath),
-        executedCount: 0,
-        committedCount: 0,
-      };
-    });
-    yield progress("checking");
-    // SQLite 是唯一协调者;拿锁后读取真实账本,等待者不会重复迁移已提交项。
-    yield* acquire(() => db.exec("begin immediate"));
-    transactionStarted = true;
-    db.exec(`create table if not exists schema_migration (
-      id text primary key, checksum text not null, app_version text, time_applied integer not null
-    )`);
-    // 拿锁后记录起点,避免预检时其他写者尚未提交;后续迁移不得覆盖它。
+    await acquire(() => { migration = { kind: inspectMigrationKind(db, dbPath), executedCount: 0, committedCount: 0 }; });
+    await progress("checking");
+    await acquire(() => db.exec("begin immediate"));
+    ensureSqliteSchemaMigrationTable(db);
     const baseline = db.prepare("SELECT id FROM schema_migration ORDER BY id DESC LIMIT 1").get();
     const baseline = db.prepare("SELECT id FROM schema_migration ORDER BY id DESC LIMIT 1").get();
-    if (migrationFacts)
-      migrationFacts.lastAppliedMigrationId = baseline
-        ? databaseMigrationIdSchema.safeParse(baseline.id).data
-        : null;
-    let completed = 0;
-    for (const migration of SQLITE_MIGRATIONS) {
-      try {
-        const checksum = migrationChecksum(migration.sql);
-        const applied = readAppliedMigration(db, migration.id);
-        if (applied) {
-          ensureMigrationChecksum(migration.id, applied.checksum, checksum, dbPath);
-          completed++;
-          continue;
-        }
-        // 预检后出现新待执行项时,以锁内账本为准提升种类,不能带 none 执行 SQL。
-        if (migrationFacts?.kind === "none") migrationFacts.kind = "upgrade";
-        yield {
-          ...progress("migrating"),
-          migrationId: migration.id,
-          completed,
-          total: SQLITE_MIGRATIONS.length,
-        };
-        // 本 hotfix 只调整启动等待;执行与账本校验共用冻结原 SQL,避免维护两套转换语义。
-        db.exec(migration.sql);
-        if (migrationFacts) migrationFacts.executedCount++;
-        db.prepare(
-          "insert into schema_migration (id, checksum, app_version, time_applied) values (?, ?, ?, ?)",
-        ).run(migration.id, checksum, migration.appVersion, Date.now());
-        completed++;
-      } catch (error) {
-        throw normalizeMigrationError(error, dbPath, migration.id);
-      }
-    }
-    yield progress("committing");
-    db.exec("commit");
-    transactionStarted = false;
-    if (migrationFacts) migrationFacts.committedCount = migrationFacts.executedCount;
-    yield progress("ready");
+    migration!.lastAppliedMigrationId = baseline ? databaseMigrationIdSchema.safeParse(baseline.id).data : null;
+    const directory = dirname(dbPath);
+    const dataRoot = basename(directory) === "db" && basename(dirname(directory)) === "cli" ? dirname(dirname(directory)) : directory;
+    const result = await sqliteMigrations.migrate(db, SQLITE_MIGRATIONS, {
+      database: "cli", transactionOpen: true, appliedAtColumn: "time_applied", backupDirectories: [join(dataRoot, "backup")],
+      onBeforeApply: async (id) => { migrationId = id; if (migration!.kind === "none") migration!.kind = "upgrade"; await progress("migrating", { migrationId: id, completed: migration!.executedCount, total: SQLITE_MIGRATIONS.length }); },
+      onApplied: () => { migration!.executedCount++; },
+      onCommitting: () => progress("committing"),
+      onBackupSkipped: () => process.emitWarning(`SQLite migration backup skipped: ${dbPath}`, { code: "ZCODE_MIGRATION_BACKUP_SKIPPED" }),
+    });
+    migration!.committedCount = migration!.executedCount;
+    await progress("ready");
+    return result;
   } catch (error) {
   } catch (error) {
-    // 先回滚,再通知失败;通知不能让业务看到仍在事务内的 failed。
-    if (transactionStarted && db.isTransaction) {
-      try {
-        db.exec("rollback");
-      } catch {
-        /* 关闭连接时恢复,保留原始异常。 */
-      }
-    }
-    transactionStarted = false;
-    const normalized = normalizeMigrationError(error, dbPath);
-    yield {
-      ...progress("failed"),
-      errorCode: normalized.kind,
-      ...databaseStartupErrorDetails(normalized),
-      migrationId: normalized.migrationId,
-    };
-    throw normalized;
-  } finally {
-    if (transactionStarted && db.isTransaction) {
-      try {
-        db.exec("rollback");
-      } catch {
-        /* 调用方关闭连接,保留原始异常。 */
-      }
-    }
-  }
+    if (db.isTransaction) { try { db.exec("rollback"); } catch { /* 保留首个错误。 */ } }
+    const normalized = error instanceof MigrationChecksumError
+      ? new SqliteSessionMigrationError(error.message, { cause: error, dbPath, kind: "checksum_mismatch", migrationId: error.migrationId })
+      : normalizeMigrationError(error, dbPath, migrationId);
+    try { await progress("failed", { errorCode: normalized.kind, ...databaseStartupErrorDetails(normalized), migrationId: normalized.migrationId }); } catch { /* 通知失败不覆盖数据库错误。 */ }
+    // 通知端口的异常保留原始对象,不能被数据库错误包装或 close 掩盖。
+    throw error === progressError ? error : normalized;
+  } finally { if (db.isOpen) db.exec(`pragma busy_timeout = ${DEFAULT_SQLITE_STARTUP_LOCK_TIMEOUT_MS}`); }
 }
 }
 
 
 function isSqliteBusyError(error: unknown): boolean {
 function isSqliteBusyError(error: unknown): boolean {
@@ -252,9 +145,6 @@ function readJournalMode(db: DatabaseSync, enableWal = false): string {
   return typeof mode === "string" ? mode.toLowerCase() : "unknown";
   return typeof mode === "string" ? mode.toLowerCase() : "unknown";
 }
 }
 
 
-function waitSync(delayMs: number): void {
-  Atomics.wait(waitBuffer, 0, 0, Math.max(1, Math.ceil(delayMs)));
-}
 
 
 function normalizeMigrationError(
 function normalizeMigrationError(
   error: unknown,
   error: unknown,
@@ -262,6 +152,13 @@ function normalizeMigrationError(
   migrationId?: string,
   migrationId?: string,
 ): SqliteSessionMigrationError {
 ): SqliteSessionMigrationError {
   if (error instanceof SqliteSessionMigrationError) return error;
   if (error instanceof SqliteSessionMigrationError) return error;
+  if (error instanceof SqliteSchemaMigrationChecksumError) {
+    return new SqliteSessionMigrationError(error.message, {
+      dbPath,
+      kind: "checksum_mismatch",
+      migrationId: error.migrationId,
+    });
+  }
   if (isSqliteBusyError(error)) return lockTimeoutError(error, dbPath, migrationId);
   if (isSqliteBusyError(error)) return lockTimeoutError(error, dbPath, migrationId);
   return new SqliteSessionMigrationError(
   return new SqliteSessionMigrationError(
     migrationId
     migrationId

+ 70 - 13
apps/zcode-cli/packages/adapters/src/storage/session-store/migrations.ts

@@ -1,15 +1,24 @@
+import type { SqliteMigration } from "@zcode/shared/sqlite-migrations";
+export type { SqliteMigration } from "@zcode/shared/sqlite-migrations";
 import { PROVIDER_MODEL_SELECTION_MIGRATION_SQL } from "./migrations/0020-provider-model-selection.js";
 import { PROVIDER_MODEL_SELECTION_MIGRATION_SQL } from "./migrations/0020-provider-model-selection.js";
+import { SESSION_DATABASE_IDENTITY_MIGRATION } from "@zcode/shared/sqlite-migrations";
 
 
-export interface SqliteMigration {
-  appVersion: string;
-  id: string;
-  sql: string;
-}
+import { OFFICIAL_GLM_SELECTION_MIGRATION_SQL } from "./migrations/0021-official-glm-selection.js";
+import { BACKFILLED_SESSION_REASONING_MIGRATION_SQL } from "./migrations/0022-backfilled-session-reasoning.js";
 
 
 export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
 export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.2.0",
     appVersion: "0.2.0",
     id: "0001_base_session_store",
     id: "0001_base_session_store",
+    touchedTables: [
+      "input_history",
+      "message",
+      "part",
+      "permission",
+      "session",
+      "session_entry",
+      "todo",
+    ],
     sql: `
     sql: `
       create table if not exists session (
       create table if not exists session (
         id text primary key,
         id text primary key,
@@ -112,6 +121,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.2.0",
     appVersion: "0.2.0",
     id: "0002_local_setting",
     id: "0002_local_setting",
+    touchedTables: ["local_setting"],
     sql: `
     sql: `
       create table if not exists local_setting (
       create table if not exists local_setting (
         scope text not null,
         scope text not null,
@@ -135,6 +145,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.2.0",
     appVersion: "0.2.0",
     id: "0003_backfill_permission_local_setting",
     id: "0003_backfill_permission_local_setting",
+    touchedTables: ["local_setting"],
     sql: `
     sql: `
       insert or ignore into local_setting (
       insert or ignore into local_setting (
         scope,
         scope,
@@ -162,6 +173,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.7.0",
     appVersion: "0.7.0",
     id: "0004_session_target",
     id: "0004_session_target",
+    touchedTables: ["session_target"],
     sql: `
     sql: `
       create table if not exists session_target (
       create table if not exists session_target (
         session_id text primary key references session(id) on delete cascade,
         session_id text primary key references session(id) on delete cascade,
@@ -176,6 +188,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.7.0",
     appVersion: "0.7.0",
     id: "0005_session_target_accounting",
     id: "0005_session_target_accounting",
+    touchedTables: ["session_target", "session_target_next"],
     sql: `
     sql: `
       create table if not exists session_target_next (
       create table if not exists session_target_next (
         session_id text primary key references session(id) on delete cascade,
         session_id text primary key references session(id) on delete cascade,
@@ -219,6 +232,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.11.0",
     appVersion: "0.11.0",
     id: "0006_input_history_attachments",
     id: "0006_input_history_attachments",
+    touchedTables: ["input_history"],
     sql: `
     sql: `
       alter table input_history add column attachments text;
       alter table input_history add column attachments text;
     `,
     `,
@@ -226,6 +240,14 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.13.0",
     appVersion: "0.13.0",
     id: "0007_workflow_script_runtime",
     id: "0007_workflow_script_runtime",
+    touchedTables: [
+      "session",
+      "session_task_link",
+      "workflow_activity",
+      "workflow_definition",
+      "workflow_event",
+      "workflow_run",
+    ],
     sql: `
     sql: `
       alter table session add column task_type text not null default 'interactive';
       alter table session add column task_type text not null default 'interactive';
 
 
@@ -368,6 +390,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.13.0",
     appVersion: "0.13.0",
     id: "0008_workflow_definition_scope",
     id: "0008_workflow_definition_scope",
+    touchedTables: ["workflow_definition"],
     sql: `
     sql: `
       alter table workflow_definition
       alter table workflow_definition
         add column scope text not null default 'explicit'
         add column scope text not null default 'explicit'
@@ -377,6 +400,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.14.0",
     appVersion: "0.14.0",
     id: "0009_session_title_metadata",
     id: "0009_session_title_metadata",
+    touchedTables: ["session"],
     sql: `
     sql: `
       alter table session
       alter table session
         add column title_source text not null default 'first_input'
         add column title_source text not null default 'first_input'
@@ -392,6 +416,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.15.0",
     appVersion: "0.15.0",
     id: "0010_usage_observability",
     id: "0010_usage_observability",
+    touchedTables: ["model_usage", "tool_usage", "turn_usage"],
     sql: `
     sql: `
       create table if not exists model_usage (
       create table if not exists model_usage (
         id text primary key,
         id text primary key,
@@ -519,6 +544,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.15.0",
     appVersion: "0.15.0",
     id: "0011_session_target_summary_title",
     id: "0011_session_target_summary_title",
+    touchedTables: ["session_target"],
     sql: `
     sql: `
       alter table session_target add column summary_title text;
       alter table session_target add column summary_title text;
     `,
     `,
@@ -526,6 +552,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.15.0",
     appVersion: "0.15.0",
     id: "0012_session_trace_id",
     id: "0012_session_trace_id",
+    touchedTables: ["session"],
     sql: `
     sql: `
       alter table session add column trace_id text;
       alter table session add column trace_id text;
 
 
@@ -535,6 +562,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.15.0",
     appVersion: "0.15.0",
     id: "0013_session_target_active_run_accounting",
     id: "0013_session_target_active_run_accounting",
+    touchedTables: ["session_target"],
     sql: `
     sql: `
       alter table session_target add column active_input_id text;
       alter table session_target add column active_input_id text;
       alter table session_target add column active_run_started_at integer;
       alter table session_target add column active_run_started_at integer;
@@ -544,6 +572,7 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.15.0",
     appVersion: "0.15.0",
     id: "0014_message_part_sequence",
     id: "0014_message_part_sequence",
+    touchedTables: ["message", "part"],
     sql: `
     sql: `
       alter table message add column sequence integer;
       alter table message add column sequence integer;
       alter table part add column sequence integer;
       alter table part add column sequence integer;
@@ -595,7 +624,8 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.15.2",
     appVersion: "0.15.2",
     id: "0015_message_part_sequence_backfill_and_guard",
     id: "0015_message_part_sequence_backfill_and_guard",
-    // 背景:0014 backfill 之后仍持续出现 NULL sequence
+    touchedTables: ["message", "part"],
+    // 背景(16-timeline-authority-plan P0):0014 backfill 之后仍持续出现 NULL sequence
     // (本机观测 message 1,690 / part 5,933 行,跨 331 sessions),主要嫌疑是旧版本二进制
     // (本机观测 message 1,690 / part 5,933 行,跨 331 sessions),主要嫌疑是旧版本二进制
     // 并存写同一 DB(其 INSERT 不含 sequence 列)。本迁移做两件事:
     // 并存写同一 DB(其 INSERT 不含 sequence 列)。本迁移做两件事:
     // 1. 增量 backfill:只补 NULL 行,序号从各 scope 现有 max(sequence)+1 起、按
     // 1. 增量 backfill:只补 NULL 行,序号从各 scope 现有 max(sequence)+1 起、按
@@ -683,8 +713,9 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.15.2",
     appVersion: "0.15.2",
     id: "0016_session_input_ledger",
     id: "0016_session_input_ledger",
-    // session_input 账本:输入的 durable 生命周期
-    // admitted -> promoted / cancelled / discarded。队列/唤醒的存在性若只在
+    touchedTables: ["session_input"],
+    // session_input 账本(16-timeline-authority-plan P3):输入的 durable 生命周期
+    // admitted -> promoted / cancelled / discarded。旧实现里队列/唤醒的存在性只在
     // 进程内存(事件日志也是内存的),崩溃即静默丢;账本让「queue 消失但不进
     // 进程内存(事件日志也是内存的),崩溃即静默丢;账本让「queue 消失但不进
     // history」不可能静默发生,并为输入类 command 提供 durable 幂等。
     // history」不可能静默发生,并为输入类 command 提供 durable 幂等。
     sql: `
     sql: `
@@ -712,7 +743,8 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.15.2",
     appVersion: "0.15.2",
     id: "0017_session_input_start_now_delivery",
     id: "0017_session_input_start_now_delivery",
-    // 所有 input command 都在执行前落 durable admission,startNow 也需要独立
+    touchedTables: ["session_input", "session_input_before_start_now"],
+    // 05C:所有 input command 都在执行前落 durable admission,startNow 也需要独立
     // delivery,不能伪装成 queue。SQLite 不能原地修改 CHECK,必须重建表并保全账本。
     // delivery,不能伪装成 queue。SQLite 不能原地修改 CHECK,必须重建表并保全账本。
     sql: `
     sql: `
       alter table session_input rename to session_input_before_start_now;
       alter table session_input rename to session_input_before_start_now;
@@ -754,7 +786,8 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.15.2",
     appVersion: "0.15.2",
     id: "0018_session_input_failed_status",
     id: "0018_session_input_failed_status",
-    // fork bundle 提交后 child runtime 仍可能同步启动失败。该输入已经被 parent
+    touchedTables: ["session_input", "session_input_before_failed_status"],
+    // Bugfix:fork bundle 提交后 child runtime 仍可能同步启动失败。该输入已经被 parent
     // accepted fact 接受,不能伪装成 cancelled/discarded;新增 durable failed 终态,并通过
     // accepted fact 接受,不能伪装成 cancelled/discarded;新增 durable failed 终态,并通过
     // 重建 CHECK 保证旧库升级后也能写入,重启不会再次消费或改写它。
     // 重建 CHECK 保证旧库升级后也能写入,重启不会再次消费或改写它。
     sql: `
     sql: `
@@ -797,7 +830,8 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
   {
   {
     appVersion: "0.16.5",
     appVersion: "0.16.5",
     id: "0019_dwf_journal",
     id: "0019_dwf_journal",
-    // dynamic-workflow 执行引擎的 durable journal。
+    touchedTables: ["dwf_run", "dwf_actor", "dwf_artifact", "dwf_node", "dwf_event"],
+    // dynamic-workflow 执行引擎的 durable journal(docs/execution-engine.md 的 "Journal & storage")。
     // legacy 的 workflow_* 表只是模板不是家:dwf_* 自成一套,与既有 workflow 机制彼此独立。
     // legacy 的 workflow_* 表只是模板不是家:dwf_* 自成一套,与既有 workflow 机制彼此独立。
     //
     //
     // 本条是 beta 前把开发期 0019–0030 十二条迁移**压成的单一基线**:四张表一次建齐、形状即
     // 本条是 beta 前把开发期 0019–0030 十二条迁移**压成的单一基线**:四张表一次建齐、形状即
@@ -914,17 +948,40 @@ export const SQLITE_MIGRATIONS: readonly SqliteMigration[] = [
     appVersion: "0.16.5",
     appVersion: "0.16.5",
     id: "0020_provider_model_selection",
     id: "0020_provider_model_selection",
     sql: PROVIDER_MODEL_SELECTION_MIGRATION_SQL,
     sql: PROVIDER_MODEL_SELECTION_MIGRATION_SQL,
+    touchedTables: ["message", "part", "session_entry"],
   },
   },
   {
   {
     appVersion: "0.16.5",
     appVersion: "0.16.5",
     id: "0021_official_glm_selection",
     id: "0021_official_glm_selection",
     sql: OFFICIAL_GLM_SELECTION_MIGRATION_SQL,
     sql: OFFICIAL_GLM_SELECTION_MIGRATION_SQL,
+    touchedTables: ["session_entry"],
   },
   },
   {
   {
     appVersion: "0.16.5",
     appVersion: "0.16.5",
     id: "0022_backfilled_session_reasoning",
     id: "0022_backfilled_session_reasoning",
     sql: BACKFILLED_SESSION_REASONING_MIGRATION_SQL,
     sql: BACKFILLED_SESSION_REASONING_MIGRATION_SQL,
+    touchedTables: ["session_entry"],
   },
   },
+  {
+    appVersion: "0.16.9",
+    id: "0023_session_soft_delete_outcome",
+    previousIds: ["0020_session_soft_delete_outcome"],
+    touchedTables: ["session"],
+    apply: (db) => {
+      const columns = new Set(
+        db
+          .prepare("pragma table_info(session)")
+          .all()
+          .map((row) => row.name),
+      );
+      if (!columns.has("time_deleted"))
+        db.exec("alter table session add column time_deleted integer");
+      if (!columns.has("last_outcome")) db.exec("alter table session add column last_outcome text");
+    },
+    sql: `
+      alter table session add column time_deleted integer;
+      alter table session add column last_outcome text;
+    `,
+  },
+  { ...SESSION_DATABASE_IDENTITY_MIGRATION, touchedTables: ["zcode_database_identity"] },
 ];
 ];
-import { OFFICIAL_GLM_SELECTION_MIGRATION_SQL } from "./migrations/0021-official-glm-selection.js";
-import { BACKFILLED_SESSION_REASONING_MIGRATION_SQL } from "./migrations/0022-backfilled-session-reasoning.js";

+ 1 - 11
apps/zcode-cli/packages/adapters/src/storage/session-store/paths.ts

@@ -1,16 +1,6 @@
-import { existsSync, mkdirSync } from "node:fs";
 import { homedir } from "node:os";
 import { homedir } from "node:os";
-import { dirname, join } from "node:path";
-import { maybeThrowStorageFsFault } from "../fs-fault-injection.js";
+import { join } from "node:path";
 
 
 export function getDefaultSessionDbPath(): string {
 export function getDefaultSessionDbPath(): string {
   return join(homedir(), ".zcode", "cli", "db", "db.sqlite");
   return join(homedir(), ".zcode", "cli", "db", "db.sqlite");
 }
 }
-
-export function ensureParentDir(filePath: string): void {
-  const parent = dirname(filePath);
-  if (!existsSync(parent)) {
-    maybeThrowStorageFsFault({ operation: "mkdir", path: parent });
-    mkdirSync(parent, { recursive: true });
-  }
-}

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

@@ -17,24 +17,20 @@ import { decodeSessionRow } from "../codecs.js";
 import { encodeJson } from "../json.js";
 import { encodeJson } from "../json.js";
 import type { SessionRow } from "../rows.js";
 import type { SessionRow } from "../rows.js";
 
 
-export function createSession(
-  db: DatabaseSync,
-  input: CreateSessionInput,
-): SessionInfo {
+export function createSession(db: DatabaseSync, input: CreateSessionInput): SessionInfo {
   const now = Date.now();
   const now = Date.now();
   const timeCreated = input.time?.created ?? now;
   const timeCreated = input.time?.created ?? now;
   const timeUpdated = input.time?.updated ?? timeCreated;
   const timeUpdated = input.time?.updated ?? timeCreated;
 
 
-  db
-    .prepare(
-      `
+  db.prepare(
+    `
       insert into session (
       insert into session (
         id, project_id, workspace_id, parent_id, trace_id, task_type, slug, directory, path,
         id, project_id, workspace_id, parent_id, trace_id, task_type, slug, directory, path,
         title, title_source, title_message_id, version,
         title, title_source, title_message_id, version,
         share_url, summary_additions, summary_deletions, summary_files, summary_diffs,
         share_url, summary_additions, summary_deletions, summary_files, summary_diffs,
         revert, permission, time_created, time_updated, time_title_updated,
         revert, permission, time_created, time_updated, time_title_updated,
-        time_compacting, time_archived
-      ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, null, null, null, null, null, ?, ?, ?, ?, null, null)
+        time_compacting
+      ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, null, null, null, null, null, ?, ?, ?, ?, null)
       on conflict(id) do update set
       on conflict(id) do update set
         project_id = excluded.project_id,
         project_id = excluded.project_id,
         workspace_id = excluded.workspace_id,
         workspace_id = excluded.workspace_id,
@@ -53,27 +49,26 @@ export function createSession(
         time_title_updated = excluded.time_title_updated,
         time_title_updated = excluded.time_title_updated,
         time_updated = excluded.time_updated
         time_updated = excluded.time_updated
       `,
       `,
-    )
-    .run(
-      input.id,
-      input.projectID,
-      input.workspaceID ?? null,
-      input.parentID ?? null,
-      input.traceID ?? null,
-      input.taskType ?? "interactive",
-      input.slug,
-      input.directory,
-      input.path ?? null,
-      input.title,
-      input.titleSource ?? "first_input",
-      input.titleMessageID ?? null,
-      input.version,
-      input.shareURL ?? null,
-      encodeJson(input.permission),
-      timeCreated,
-      timeUpdated,
-      input.titleSource || input.titleMessageID ? timeUpdated : null,
-    );
+  ).run(
+    input.id,
+    input.projectID,
+    input.workspaceID ?? null,
+    input.parentID ?? null,
+    input.traceID ?? null,
+    input.taskType ?? "interactive",
+    input.slug,
+    input.directory,
+    input.path ?? null,
+    input.title,
+    input.titleSource ?? "first_input",
+    input.titleMessageID ?? null,
+    input.version,
+    input.shareURL ?? null,
+    encodeJson(input.permission),
+    timeCreated,
+    timeUpdated,
+    input.titleSource || input.titleMessageID ? timeUpdated : null,
+  );
 
 
   return mustGetSession(db, input.id);
   return mustGetSession(db, input.id);
 }
 }
@@ -82,87 +77,67 @@ export async function updateSession(
   db: DatabaseSync,
   db: DatabaseSync,
   input: UpdateSessionInput,
   input: UpdateSessionInput,
 ): Promise<SessionInfo> {
 ): Promise<SessionInfo> {
-  const current = await getSession(db, input.id);
-  if (!current) {
-    throw new Error(`Session not found: ${input.id}`);
+  const fields: string[] = [];
+  const values: SQLInputValue[] = [];
+  const set = (column: string, value: SQLInputValue | undefined) => {
+    if (value === undefined) return;
+    fields.push(`${column} = ?`);
+    values.push(value);
+  };
+  // Bug 根因:先读整行再 await 会用旧快照覆盖并发标题、权限和结果;只更新本次输入拥有的列。
+  set("directory", input.directory);
+  set("path", input.path);
+  set("title", input.title);
+  set("title_source", input.titleSource);
+  set("title_message_id", input.titleMessageID);
+  set("share_url", input.shareURL);
+  set("last_outcome", input.lastOutcome);
+  if (input.summary !== undefined) {
+    set("summary_additions", input.summary?.additions ?? null);
+    set("summary_deletions", input.summary?.deletions ?? null);
+    set("summary_files", input.summary?.files ?? null);
+    set("summary_diffs", encodeJson(input.summary?.diffs));
   }
   }
-
-  const summary =
-    input.summary === undefined
-      ? {
-          additions: current.summaryAdditions,
-          deletions: current.summaryDeletions,
-          files: current.summaryFiles,
-          diffs: current.summaryDiffs,
-        }
-      : input.summary;
-  const now = Date.now();
+  if (input.revert !== undefined) set("revert", encodeJson(input.revert));
+  if (input.permission !== undefined) set("permission", encodeJson(input.permission));
+  set("time_compacting", input.timeCompacting);
   if (
   if (
-    input.title !== undefined &&
-    input.expectedTitleSources &&
-    input.expectedTitleSources.length > 0 &&
-    !input.expectedTitleSources.includes(current.titleSource ?? "first_input")
+    input.title !== undefined ||
+    input.titleSource !== undefined ||
+    input.titleMessageID !== undefined
   ) {
   ) {
-    return current;
+    set("time_title_updated", Date.now());
+  }
+  // 标题及组织态不代表会话活动;活动时间只由消息/终态显式提交,且禁止回退。
+  if (input.timeUpdated !== undefined) {
+    fields.push("time_updated = max(time_updated, ?)");
+    values.push(input.timeUpdated);
+  }
+  if (fields.length) {
+    values.push(input.id);
+    const sources = input.title !== undefined ? input.expectedTitleSources : undefined;
+    const guard = sources?.length
+      ? ` and coalesce(title_source, 'first_input') in (${sources.map(() => "?").join(",")})`
+      : "";
+    if (sources?.length) values.push(...sources);
+    db.prepare(`update session set ${fields.join(",")} where id=?${guard}`).run(...values);
   }
   }
-  const titleChanged = input.title !== undefined && input.title !== current.title;
-  const nextTitleSource = input.titleSource ?? current.titleSource ?? "first_input";
-
-  db
-    .prepare(
-      `
-      update session set
-        directory = ?,
-        path = ?,
-        title = ?,
-        title_source = ?,
-        title_message_id = ?,
-        share_url = ?,
-        summary_additions = ?,
-        summary_deletions = ?,
-        summary_files = ?,
-        summary_diffs = ?,
-        revert = ?,
-        permission = ?,
-        time_title_updated = ?,
-        time_compacting = ?,
-        time_archived = ?,
-        -- 修复原因:路径自愈可能携带并发读取前的旧时间,不能回退真实活动时间。
-        time_updated = max(time_updated, ?)
-      where id = ?
-      `,
-    )
-    .run(
-      input.directory ?? current.directory,
-      input.path === undefined ? (current.path ?? null) : input.path,
-      input.title ?? current.title,
-      nextTitleSource,
-      input.titleMessageID === undefined
-        ? (current.titleMessageID ?? null)
-        : input.titleMessageID,
-      input.shareURL === undefined ? (current.shareURL ?? null) : input.shareURL,
-      summary === null ? null : (summary.additions ?? null),
-      summary === null ? null : (summary.deletions ?? null),
-      summary === null ? null : (summary.files ?? null),
-      summary === null ? null : encodeJson(summary.diffs),
-      input.revert === undefined ? encodeJson(current.revert) : encodeJson(input.revert),
-      input.permission === undefined ? encodeJson(current.permission) : encodeJson(input.permission),
-      titleChanged || input.titleSource !== undefined || input.titleMessageID !== undefined
-        ? now
-        : (current.time.titleUpdated ?? null),
-      input.timeCompacting === undefined ? (current.time.compacting ?? null) : input.timeCompacting,
-      input.timeArchived === undefined ? (current.time.archived ?? null) : input.timeArchived,
-      input.timeUpdated ?? now,
-      input.id,
-    );
-
   return mustGetSession(db, input.id);
   return mustGetSession(db, input.id);
 }
 }
 
 
-export function getSession(
+export function softDeleteSession(
   db: DatabaseSync,
   db: DatabaseSync,
   sessionID: SessionId,
   sessionID: SessionId,
-): SessionInfo | null {
+  timeDeleted: number,
+): void {
+  // 软删除保持幂等,并保留 message/part 及活动时间;旧 create/upsert 不能清除此字段。
+  db.prepare("update session set time_deleted = coalesce(time_deleted, ?) where id = ?").run(
+    timeDeleted,
+    sessionID,
+  );
+}
+
+export function getSession(db: DatabaseSync, sessionID: SessionId): SessionInfo | null {
   const row = db.prepare("select * from session where id = ?").get(sessionID) as
   const row = db.prepare("select * from session where id = ?").get(sessionID) as
     | SessionRow
     | SessionRow
     | undefined;
     | undefined;
@@ -173,7 +148,7 @@ export async function listSessions(
   db: DatabaseSync,
   db: DatabaseSync,
   input: ListSessionsInput = {},
   input: ListSessionsInput = {},
 ): Promise<SessionInfo[]> {
 ): Promise<SessionInfo[]> {
-  const clauses: string[] = [];
+  const clauses: string[] = ["time_deleted is null"];
   const values: SQLInputValue[] = [];
   const values: SQLInputValue[] = [];
 
 
   if (input.projectID) {
   if (input.projectID) {
@@ -214,10 +189,6 @@ export async function listSessions(
     values.push(...taskTypes);
     values.push(...taskTypes);
   }
   }
 
 
-  if (!input.includeArchived) {
-    clauses.push("time_archived is null");
-  }
-
   const where = clauses.length > 0 ? `where ${clauses.join(" and ")}` : "";
   const where = clauses.length > 0 ? `where ${clauses.join(" and ")}` : "";
   const limitValue = input.limit && input.limit > 0 ? input.limit : undefined;
   const limitValue = input.limit && input.limit > 0 ? input.limit : undefined;
   const limit = limitValue === undefined ? "" : " limit ?";
   const limit = limitValue === undefined ? "" : " limit ?";
@@ -337,9 +308,10 @@ export async function clearRevert(db: DatabaseSync, sessionID: SessionId): Promi
 }
 }
 
 
 export function touchSession(db: DatabaseSync, sessionID: SessionId, timeUpdated: number): void {
 export function touchSession(db: DatabaseSync, sessionID: SessionId, timeUpdated: number): void {
-  db
-    .prepare("update session set time_updated = max(time_updated, ?) where id = ?")
-    .run(timeUpdated, sessionID);
+  db.prepare("update session set time_updated = max(time_updated, ?) where id = ?").run(
+    timeUpdated,
+    sessionID,
+  );
 }
 }
 
 
 function normalizeSessionTaskTypes(taskTypes: readonly SessionTaskType[] | undefined): string[] {
 function normalizeSessionTaskTypes(taskTypes: readonly SessionTaskType[] | undefined): string[] {

+ 2 - 5
apps/zcode-cli/packages/adapters/src/storage/session-store/rows.ts

@@ -24,6 +24,8 @@ export interface SessionRow {
   time_title_updated: number | null;
   time_title_updated: number | null;
   time_compacting: number | null;
   time_compacting: number | null;
   time_archived: number | null;
   time_archived: number | null;
+  time_deleted: number | null;
+  last_outcome: "completed" | "error" | "interrupted" | null;
 }
 }
 
 
 export interface MessageRow {
 export interface MessageRow {
@@ -75,11 +77,6 @@ export interface LocalSettingRow {
   value: string;
   value: string;
 }
 }
 
 
-export interface SchemaMigrationRow {
-  checksum: string;
-  id: string;
-}
-
 export interface InputHistoryRow {
 export interface InputHistoryRow {
   id: string;
   id: string;
   project_id: string;
   project_id: string;

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

@@ -0,0 +1,548 @@
+CREATE TABLE dwf_actor (
+        id integer primary key autoincrement,
+        run_id text not null references dwf_run(id) on delete cascade,
+        site_id text not null,
+        ordinal integer not null,
+        name text,
+        persona_json text,
+        resolved_model text,
+        session_id text,
+        time_created integer not null,
+        time_updated integer not null,
+        unique(run_id, site_id, ordinal)
+      );
+
+CREATE TABLE dwf_event (
+        id integer primary key autoincrement,
+        run_id text not null references dwf_run(id) on delete cascade,
+        sequence integer not null,
+        type text not null,
+        payload_json text not null,
+        time_created integer not null,
+        unique(run_id, sequence)
+      );
+
+CREATE TABLE dwf_node (
+        id integer primary key autoincrement,
+        run_id text not null references dwf_run(id) on delete cascade,
+        site_id text not null,
+        ordinal integer not null,
+        kind text not null check(kind in ('ask', 'world-read', 'world-run', 'report', 'artifact')),
+        actor_site_id text,
+        actor_ordinal integer,
+        actor_seq integer,
+        input_hash text not null,
+        input_json text,
+        status text not null check(status in ('running', 'completed', 'failed')),
+        result_json text,
+        error_json text,
+        stats_json text,
+        message_boundary integer,
+        artifact_id text,
+        time_created integer not null,
+        time_updated integer not null,
+        unique(run_id, site_id, ordinal)
+      );
+
+CREATE TABLE dwf_run (
+        id text primary key,
+        parent_session_id text,
+        cwd text,
+        name text,
+        script_text text,
+        script_hash text,
+        args_json text,
+        tool_call_id text,
+        resumed_from text,
+        caps_max_concurrency integer not null,
+        spent_tokens integer not null default 0,
+        status text not null check(status in (
+          'pending',
+          'running',
+          'completed',
+          'failed',
+          'cancelled'
+        )),
+        result_json text,
+        failure_json text,
+        time_created integer not null,
+        time_updated integer not null
+      );
+
+CREATE TABLE input_history (
+        id text primary key,
+        project_id text not null,
+        session_id text,
+        text text not null,
+        kind text not null,
+        time_created integer not null
+      , attachments text);
+
+CREATE TABLE local_setting (
+        scope text not null,
+        scope_id text not null,
+        namespace text not null,
+        key text not null,
+        value text not null,
+        schema_version integer not null,
+        time_created integer not null,
+        time_updated integer not null,
+        primary key(scope, scope_id, namespace, key)
+      );
+
+CREATE TABLE message (
+        id text primary key,
+        session_id text not null references session(id) on delete cascade,
+        time_created integer not null,
+        time_updated integer not null,
+        data text not null
+      , sequence integer);
+
+CREATE TABLE model_usage (
+        id text primary key,
+        logical_request_id text not null,
+        attempt_index integer not null default 0,
+        session_id text not null references session(id) on delete cascade,
+        turn_id text,
+        trace_id text,
+        span_id text,
+        assistant_message_id text,
+        parent_user_message_id text,
+        query_source text not null,
+        provider_id text not null,
+        model_id text not null,
+        variant text,
+        agent text,
+        mode text,
+        task_type text,
+        status text not null check(status in ('running', 'completed', 'error', 'cancelled')),
+        started_at integer not null,
+        first_token_at integer,
+        completed_at integer,
+        duration_ms integer,
+        time_to_first_token_ms integer,
+        finish_reason text,
+        tool_call_count integer not null default 0,
+        input_tokens integer not null default 0,
+        output_tokens integer not null default 0,
+        reasoning_tokens integer not null default 0,
+        cache_creation_input_tokens integer not null default 0,
+        cache_read_input_tokens integer not null default 0,
+        provider_total_tokens integer,
+        computed_total_tokens integer not null default 0,
+        retry_count integer not null default 0,
+        retryable integer not null default 0 check(retryable in (0, 1)),
+        cancelled_by_user integer not null default 0 check(cancelled_by_user in (0, 1)),
+        context_exceeded integer not null default 0 check(context_exceeded in (0, 1)),
+        error_type text,
+        error_code text,
+        error_message text,
+        raw_usage_json text,
+        provider_metadata_json text
+      );
+
+CREATE TABLE part (
+        id text primary key,
+        message_id text not null references message(id) on delete cascade,
+        session_id text not null,
+        time_created integer not null,
+        time_updated integer not null,
+        data text not null
+      , sequence integer);
+
+CREATE TABLE permission (
+        project_id text primary key,
+        time_created integer not null,
+        time_updated integer not null,
+        data text not null
+      );
+
+CREATE TABLE "schema_migration" (id text primary key, checksum text not null, app_version text, "time_applied" integer not null);
+
+CREATE TABLE session (
+        id text primary key,
+        project_id text not null,
+        workspace_id text,
+        parent_id text,
+        slug text not null,
+        directory text not null,
+        path text,
+        title text not null,
+        version text not null,
+        share_url text,
+        summary_additions integer,
+        summary_deletions integer,
+        summary_files integer,
+        summary_diffs text,
+        revert text,
+        permission text,
+        time_created integer not null,
+        time_updated integer not null,
+        time_compacting integer,
+        time_archived integer
+      , task_type text not null default 'interactive', title_source text not null default 'first_input'
+        check(title_source in ('default', 'first_input', 'generated', 'custom')), title_message_id text, time_title_updated integer, trace_id text, time_deleted integer, last_outcome text);
+
+CREATE TABLE session_entry (
+        id text primary key,
+        session_id text not null references session(id) on delete cascade,
+        type text not null,
+        time_created integer not null,
+        time_updated integer not null,
+        data text not null
+      );
+
+CREATE TABLE session_input (
+        id text primary key,
+        session_id text not null references session(id) on delete cascade,
+        kind text not null,
+        delivery text not null check(delivery in ('startNow', 'guide', 'queue')),
+        payload text not null,
+        admitted_sequence integer not null,
+        promoted_sequence integer,
+        promoted_message_id text,
+        status text not null check(status in ('admitted', 'promoted', 'cancelled', 'discarded', 'failed')),
+        status_reason text,
+        time_created integer not null,
+        time_updated integer not null
+      );
+
+CREATE TABLE "session_target" (
+        session_id text primary key references session(id) on delete cascade,
+        target_id text not null,
+        objective text not null,
+        status text not null check(status in ('active', 'paused', 'budget_limited', 'complete')),
+        token_budget integer,
+        tokens_used integer not null default 0,
+        time_used_seconds integer not null default 0,
+        time_created integer not null,
+        time_updated integer not null
+      , summary_title text, active_input_id text, active_run_started_at integer, active_run_last_seen_at integer);
+
+CREATE TABLE session_task_link (
+        id text primary key,
+        root_workflow_run_id text references workflow_run(id) on delete cascade,
+        parent_link_id text references session_task_link(id) on delete cascade,
+        activity_id text references workflow_activity(id) on delete set null,
+        parent_session_id text references session(id) on delete set null,
+        child_session_id text not null references session(id) on delete cascade,
+        role text not null,
+        depth integer not null default 0,
+        path text not null,
+        phase text,
+        label text,
+        agent_type text,
+        model text,
+        status text not null,
+        time_created integer not null,
+        time_updated integer not null,
+        unique(child_session_id)
+      );
+
+CREATE TABLE todo (
+        session_id text not null references session(id) on delete cascade,
+        content text not null,
+        status text not null,
+        priority text not null,
+        position integer not null,
+        time_created integer not null,
+        time_updated integer not null,
+        primary key(session_id, position)
+      );
+
+CREATE TABLE tool_usage (
+        id text primary key,
+        session_id text not null references session(id) on delete cascade,
+        turn_id text,
+        trace_id text,
+        tool_call_id text not null,
+        tool_name text not null,
+        side_effect_scope text,
+        read_only integer check(read_only in (0, 1)),
+        destructive integer check(destructive in (0, 1)),
+        approval_status text,
+        status text not null check(status in ('running', 'completed', 'error', 'cancelled')),
+        started_at integer not null,
+        first_output_at integer,
+        completed_at integer,
+        duration_ms integer,
+        time_to_first_output_ms integer,
+        exit_code integer,
+        output_bytes integer not null default 0,
+        stdout_bytes integer not null default 0,
+        stderr_bytes integer not null default 0,
+        truncated integer not null default 0 check(truncated in (0, 1)),
+        retry_count integer not null default 0,
+        retryable integer not null default 0 check(retryable in (0, 1)),
+        cancelled_by_user integer not null default 0 check(cancelled_by_user in (0, 1)),
+        error_type text,
+        error_code text,
+        error_message text
+      );
+
+CREATE TABLE turn_usage (
+        session_id text not null references session(id) on delete cascade,
+        turn_id text not null,
+        trace_id text,
+        user_message_id text,
+        status text not null check(status in ('running', 'completed', 'error', 'cancelled')),
+        started_at integer not null,
+        first_model_start_at integer,
+        first_token_at integer,
+        completed_at integer,
+        duration_ms integer,
+        time_to_first_token_ms integer,
+        model_request_count integer not null default 0,
+        model_retry_count integer not null default 0,
+        tool_call_count integer not null default 0,
+        tool_error_count integer not null default 0,
+        input_tokens integer not null default 0,
+        output_tokens integer not null default 0,
+        reasoning_tokens integer not null default 0,
+        cache_creation_input_tokens integer not null default 0,
+        cache_read_input_tokens integer not null default 0,
+        computed_total_tokens integer not null default 0,
+        retryable integer not null default 0 check(retryable in (0, 1)),
+        cancelled_by_user integer not null default 0 check(cancelled_by_user in (0, 1)),
+        context_exceeded integer not null default 0 check(context_exceeded in (0, 1)),
+        error_type text,
+        error_code text,
+        primary key(session_id, turn_id)
+      );
+
+CREATE TABLE workflow_activity (
+        id text primary key,
+        run_id text not null references workflow_run(id) on delete cascade,
+        parent_activity_id text,
+        call_index integer not null,
+        call_path text not null,
+        attempt integer not null default 1,
+        type text not null,
+        phase text,
+        label text,
+        input_hash text not null,
+        prompt text,
+        opts_json text,
+        status text not null check(status in (
+          'queued',
+          'running',
+          'completed',
+          'failed',
+          'skipped',
+          'cancelled',
+          'cached',
+          'lost'
+        )),
+        child_session_id text references session(id) on delete set null,
+        result_json text,
+        error_json text,
+        time_created integer not null,
+        time_started integer,
+        time_updated integer not null,
+        time_completed integer,
+        unique(run_id, call_path, attempt)
+      );
+
+CREATE TABLE workflow_definition (
+        id text primary key,
+        name text not null,
+        source text not null check(source in ('builtin', 'user')),
+        trusted integer not null default 0 check(trusted in (0, 1)),
+        enabled integer not null default 1 check(enabled in (0, 1)),
+        script_path text,
+        script_hash text not null,
+        meta_json text not null,
+        time_created integer not null,
+        time_updated integer not null
+      , scope text not null default 'explicit'
+        check(scope in ('builtin', 'explicit', 'project', 'user')));
+
+CREATE TABLE workflow_event (
+        id text primary key,
+        run_id text not null references workflow_run(id) on delete cascade,
+        sequence integer not null,
+        type text not null,
+        phase text,
+        activity_id text references workflow_activity(id) on delete set null,
+        payload_json text,
+        time_created integer not null,
+        unique(run_id, sequence)
+      );
+
+CREATE TABLE workflow_run (
+        id text primary key,
+        definition_id text,
+        name text not null,
+        kind text not null default 'script',
+        parent_session_id text references session(id) on delete set null,
+        cwd text not null,
+        script_path text,
+        script_hash text not null,
+        args_json text,
+        args_hash text,
+        status text not null check(status in (
+          'pending',
+          'running',
+          'paused',
+          'completed',
+          'failed',
+          'cancelled'
+        )),
+        current_phase text,
+        budget_total integer,
+        budget_spent integer not null default 0,
+        stats_json text,
+        failure_json text,
+        time_created integer not null,
+        time_started integer,
+        time_updated integer not null,
+        time_completed integer
+      );
+
+CREATE TABLE zcode_database_identity (
+      scope TEXT PRIMARY KEY,
+      identity TEXT NOT NULL
+    );
+
+CREATE INDEX dwf_actor_run_idx on dwf_actor(run_id);
+
+CREATE INDEX dwf_event_artifact_idx
+        on dwf_event(run_id, json_extract(payload_json, '$.artifactId'), sequence);
+
+CREATE INDEX dwf_node_artifact_idx on dwf_node(run_id, artifact_id);
+
+CREATE INDEX dwf_node_run_idx on dwf_node(run_id);
+
+CREATE INDEX dwf_run_cwd_idx on dwf_run(cwd, time_updated);
+
+CREATE INDEX input_history_project_time_idx
+        on input_history(project_id, time_created desc, id desc);
+
+CREATE INDEX input_history_time_idx
+        on input_history(time_created desc, id desc);
+
+CREATE INDEX local_setting_namespace_key_idx
+        on local_setting(namespace, key);
+
+CREATE INDEX local_setting_scope_idx
+        on local_setting(scope, scope_id);
+
+CREATE INDEX message_session_sequence_idx
+        on message(session_id, sequence, time_created, id);
+
+CREATE INDEX message_session_time_created_id_idx
+        on message(session_id, time_created, id);
+
+CREATE INDEX model_usage_query_source_idx
+        on model_usage(query_source);
+
+CREATE INDEX model_usage_session_turn_idx
+        on model_usage(session_id, turn_id);
+
+CREATE INDEX model_usage_started_model_idx
+        on model_usage(started_at, provider_id, model_id);
+
+CREATE INDEX model_usage_trace_idx
+        on model_usage(trace_id);
+
+CREATE INDEX part_message_id_id_idx on part(message_id, id);
+
+CREATE INDEX part_message_sequence_idx
+        on part(message_id, sequence, time_created, id);
+
+CREATE INDEX part_session_idx on part(session_id);
+
+CREATE INDEX part_session_message_sequence_idx
+        on part(session_id, message_id, sequence);
+
+CREATE INDEX session_entry_session_idx on session_entry(session_id);
+
+CREATE INDEX session_entry_session_type_idx on session_entry(session_id, type);
+
+CREATE INDEX session_entry_time_created_idx on session_entry(time_created);
+
+CREATE INDEX session_input_session_admitted_idx
+        on session_input(session_id, admitted_sequence);
+
+CREATE INDEX session_input_session_status_idx
+        on session_input(session_id, status);
+
+CREATE INDEX session_parent_idx on session(parent_id);
+
+CREATE INDEX session_project_idx on session(project_id);
+
+CREATE INDEX session_task_link_activity_idx
+        on session_task_link(activity_id);
+
+CREATE INDEX session_task_link_parent_idx
+        on session_task_link(parent_link_id);
+
+CREATE INDEX session_task_link_root_workflow_idx
+        on session_task_link(root_workflow_run_id, depth, path);
+
+CREATE INDEX session_task_type_idx on session(task_type);
+
+CREATE INDEX session_trace_idx on session(trace_id);
+
+CREATE INDEX session_workspace_idx on session(workspace_id);
+
+CREATE INDEX todo_session_idx on todo(session_id);
+
+CREATE UNIQUE INDEX tool_usage_session_tool_call_idx
+        on tool_usage(session_id, tool_call_id);
+
+CREATE INDEX tool_usage_session_turn_idx
+        on tool_usage(session_id, turn_id);
+
+CREATE INDEX tool_usage_started_tool_idx
+        on tool_usage(started_at, tool_name);
+
+CREATE INDEX turn_usage_started_idx
+        on turn_usage(started_at);
+
+CREATE INDEX workflow_activity_child_session_idx
+        on workflow_activity(child_session_id);
+
+CREATE INDEX workflow_activity_run_status_idx
+        on workflow_activity(run_id, status, call_index);
+
+CREATE INDEX workflow_definition_source_idx
+        on workflow_definition(source, enabled);
+
+CREATE INDEX workflow_event_run_sequence_idx
+        on workflow_event(run_id, sequence);
+
+CREATE INDEX workflow_run_cwd_status_idx
+        on workflow_run(cwd, status, time_updated desc);
+
+CREATE INDEX workflow_run_definition_idx
+        on workflow_run(definition_id);
+
+CREATE INDEX workflow_run_parent_session_idx
+        on workflow_run(parent_session_id);
+
+CREATE TRIGGER message_sequence_autofill
+      after insert on message
+      when new.sequence is null
+      begin
+        update message
+        set sequence = (
+          select coalesce(max(sequence), -1) + 1
+          from message
+          where session_id = new.session_id
+        )
+        where id = new.id;
+      end;
+
+CREATE TRIGGER part_sequence_autofill
+      after insert on part
+      when new.sequence is null
+      begin
+        update part
+        set sequence = (
+          select coalesce(max(sequence), -1) + 1
+          from part
+          where message_id = new.message_id
+        )
+        where id = new.id;
+      end;

+ 42 - 47
apps/zcode-cli/packages/adapters/src/storage/session-store/sqlite-session-store.ts

@@ -1,3 +1,6 @@
+import type { MigrationResult } from "@zcode/shared/sqlite-migrations";
+import { mkdir } from "node:fs/promises";
+import { dirname } from "node:path";
 import * as permissionFullAccessRepository from "./repositories/permission-full-access.js";
 import * as permissionFullAccessRepository from "./repositories/permission-full-access.js";
 import { DatabaseSync } from "node:sqlite";
 import { DatabaseSync } from "node:sqlite";
 import type {
 import type {
@@ -78,7 +81,6 @@ import {
 import { SqliteSessionMigrationError } from "./errors.js";
 import { SqliteSessionMigrationError } from "./errors.js";
 import {
 import {
   DEFAULT_SQLITE_STARTUP_LOCK_TIMEOUT_MS,
   DEFAULT_SQLITE_STARTUP_LOCK_TIMEOUT_MS,
-  runSqliteSessionMigrations,
   runSqliteSessionMigrationsAsync,
   runSqliteSessionMigrationsAsync,
   type AsyncSqliteMigrationOptions,
   type AsyncSqliteMigrationOptions,
 } from "./migration-runner.js";
 } from "./migration-runner.js";
@@ -87,7 +89,7 @@ import type {
   SessionStoreDebugCounts,
   SessionStoreDebugCounts,
   SqliteSessionStoreOptions,
   SqliteSessionStoreOptions,
 } from "./options.js";
 } from "./options.js";
-import { ensureParentDir, getDefaultSessionDbPath } from "./paths.js";
+import { getDefaultSessionDbPath } from "./paths.js";
 import { maybeThrowStorageFsFault } from "../fs-fault-injection.js";
 import { maybeThrowStorageFsFault } from "../fs-fault-injection.js";
 import * as debugRepository from "./repositories/debug.js";
 import * as debugRepository from "./repositories/debug.js";
 import { createDwfJournalStore } from "./repositories/dwf-journal.js";
 import { createDwfJournalStore } from "./repositories/dwf-journal.js";
@@ -220,7 +222,6 @@ function assertForkBundleChildLocal(bundle: ForkCommitBundle): void {
   }
   }
 }
 }
 
 
-const deferredStartup = Symbol("deferredSqliteStartup");
 
 
 export class SqliteSessionStore
 export class SqliteSessionStore
   implements
   implements
@@ -235,58 +236,47 @@ export class SqliteSessionStore
   private readonly forkCommitFaultAt?: ForkCommitFaultStage;
   private readonly forkCommitFaultAt?: ForkCommitFaultStage;
   private dwfJournalStore?: JournalStorePort;
   private dwfJournalStore?: JournalStorePort;
 
 
-  constructor(options: SqliteSessionStoreOptions = {}, startupToken?: symbol) {
-    this.dbPath = options.dbPath ?? getDefaultSessionDbPath();
+  private constructor(
+    db: DatabaseSync,
+    dbPath: string,
+    options: SqliteSessionStoreOptions,
+    readonly migrationResult: MigrationResult,
+  ) {
+    this.db = db;
+    this.dbPath = dbPath;
     this.forkCommitFaultAt = options.forkCommitFaultAt;
     this.forkCommitFaultAt = options.forkCommitFaultAt;
+  }
+
+  static async open(options: SqliteSessionStoreOptions = {}, migrationOptions?: AsyncSqliteMigrationOptions): Promise<SqliteSessionStore> {
+    const dbPath = options.dbPath ?? getDefaultSessionDbPath();
     const startupLockTimeoutMs =
     const startupLockTimeoutMs =
       options.startupLockTimeoutMs ?? DEFAULT_SQLITE_STARTUP_LOCK_TIMEOUT_MS;
       options.startupLockTimeoutMs ?? DEFAULT_SQLITE_STARTUP_LOCK_TIMEOUT_MS;
+    let db: DatabaseSync;
     try {
     try {
-      ensureParentDir(this.dbPath);
-      maybeThrowStorageFsFault({ operation: "sqliteOpen", path: this.dbPath });
-      // 多个本地或远程 Agent 会共享同一个 session DB;timeout 必须在执行首条
-      // PRAGMA 前生效,否则并发启动会在 migration prelude 直接抛 database is locked。
-      this.db = new DatabaseSync(this.dbPath, { timeout: startupLockTimeoutMs });
+      if (dbPath !== ":memory:") {
+        maybeThrowStorageFsFault({ operation: "mkdir", path: dirname(dbPath) });
+        await mkdir(dirname(dbPath), { recursive: true });
+      }
+      maybeThrowStorageFsFault({ operation: "sqliteOpen", path: dbPath });
+      db = new DatabaseSync(dbPath, { timeout: startupLockTimeoutMs });
     } catch (error) {
     } catch (error) {
-      throw new SqliteSessionMigrationError(
-        `Failed to open SQLite session database at ${this.dbPath}`,
-        {
-          cause: error,
-          dbPath: this.dbPath,
-          kind: "open_failed",
-        },
-      );
+      throw new SqliteSessionMigrationError(`Failed to open SQLite session database at ${dbPath}`, {
+        cause: error,
+        dbPath,
+        kind: "open_failed",
+      });
     }
     }
     try {
     try {
-      if (startupToken !== deferredStartup)
-        runSqliteSessionMigrations(this.db, this.dbPath, startupLockTimeoutMs);
+      const migration = await runSqliteSessionMigrationsAsync(db, dbPath, migrationOptions ?? { lockWaitTimeoutMs: startupLockTimeoutMs });
+      return new SqliteSessionStore(db, dbPath, options, migration);
     } catch (error) {
     } catch (error) {
-      try {
-        this.db.close();
-      } catch {
-        /* 保留原始迁移失败。 */
-      }
+      try { db.close(); } catch { /* 关闭失败不能覆盖迁移错误。 */ }
       throw error;
       throw error;
     }
     }
   }
   }
 
 
-  static async openStartup(
-    options: SqliteSessionStoreOptions = {},
-    migrationOptions: AsyncSqliteMigrationOptions = {},
-  ): Promise<SqliteSessionStore> {
-    // 未迁移的实例只保留在这个工厂内部;所有 Repo/业务只可能拿到 COMMIT 后的连接。
-    const store = new SqliteSessionStore(options, deferredStartup);
-    try {
-      await runSqliteSessionMigrationsAsync(store.db, store.dbPath, migrationOptions);
-      return store;
-    } catch (error) {
-      // close 也可能因 IO 失败;迁移的原始 cause 才是用户应处理的原因。
-      try {
-        store.close();
-      } catch {
-        /* 保留原始迁移失败。 */
-      }
-      throw error;
-    }
+  static async openStartup(options: SqliteSessionStoreOptions = {}, migrationOptions: AsyncSqliteMigrationOptions = {}) {
+    return SqliteSessionStore.open(options, migrationOptions);
   }
   }
 
 
   getDatabasePath(): string {
   getDatabasePath(): string {
@@ -581,6 +571,11 @@ export class SqliteSessionStore
     return sessionRepository.updateSession(this.db, input);
     return sessionRepository.updateSession(this.db, input);
   }
   }
 
 
+  async softDeleteSession(sessionID: SessionId, timeDeleted = Date.now()): Promise<void> {
+    this.throwBeforeWrite();
+    sessionRepository.softDeleteSession(this.db, sessionID, timeDeleted);
+  }
+
   async getSession(sessionID: SessionId): Promise<SessionInfo | null> {
   async getSession(sessionID: SessionId): Promise<SessionInfo | null> {
     return sessionRepository.getSession(this.db, sessionID);
     return sessionRepository.getSession(this.db, sessionID);
   }
   }
@@ -1009,14 +1004,14 @@ export class SqliteSessionStore
 
 
 export function createSqliteSessionStore(
 export function createSqliteSessionStore(
   options: SqliteSessionStoreOptions = {},
   options: SqliteSessionStoreOptions = {},
-): SqliteSessionStore {
-  return new SqliteSessionStore(options);
+): Promise<SqliteSessionStore> {
+  return SqliteSessionStore.open(options);
 }
 }
 
 
 export function openStartupSqliteSessionStore(
 export function openStartupSqliteSessionStore(
   options: SqliteSessionStoreOptions = {},
   options: SqliteSessionStoreOptions = {},
-): SqliteSessionStore {
-  return new SqliteSessionStore(options);
+): Promise<SqliteSessionStore> {
+  return SqliteSessionStore.open(options);
 }
 }
 
 
 export { getDefaultSessionDbPath };
 export { getDefaultSessionDbPath };

+ 30 - 17
apps/zcode-cli/packages/adapters/tests/async-migration-startup.test.ts

@@ -58,7 +58,9 @@ describe("Todo144:迁移启动状态与真实 SQLite 锁", () => {
     expect(states.at(-1)?.phase).toBe("ready");
     expect(states.at(-1)?.phase).toBe("ready");
     expect(states.at(-1)?.migration?.lastAppliedMigrationId).toBeNull();
     expect(states.at(-1)?.migration?.lastAppliedMigrationId).toBeNull();
     // 本 hotfix 不改迁移算法;状态通知不能让执行路径偏离账本对应的冻结原 SQL。
     // 本 hotfix 不改迁移算法;状态通知不能让执行路径偏离账本对应的冻结原 SQL。
-    const frozenSql = SQLITE_MIGRATIONS.map((migration) => migration.sql);
+    const frozenSql = SQLITE_MIGRATIONS.filter((migration) => !migration.apply).map(
+      (migration) => migration.sql,
+    );
     expect(exec.mock.calls.map(([sql]) => sql).filter((sql) => frozenSql.includes(sql))).toEqual(
     expect(exec.mock.calls.map(([sql]) => sql).filter((sql) => frozenSql.includes(sql))).toEqual(
       frozenSql,
       frozenSql,
     );
     );
@@ -73,7 +75,11 @@ describe("Todo144:迁移启动状态与真实 SQLite 锁", () => {
       },
       },
     });
     });
     expect(replay.some((s) => s.phase === "migrating")).toBe(false);
     expect(replay.some((s) => s.phase === "migrating")).toBe(false);
-    expect(replay.at(-1)?.migration?.lastAppliedMigrationId).toBe(SQLITE_MIGRATIONS.at(-1)?.id);
+    expect(replay.at(-1)?.migration?.lastAppliedMigrationId).toBe(
+      SQLITE_MIGRATIONS.map((m) => m.id)
+        .sort()
+        .at(-1),
+    );
   });
   });
 
 
   it("同库持锁超过旧 5 秒,异步等待不阻塞持有者提交;异库独立就绪", async () => {
   it("同库持锁超过旧 5 秒,异步等待不阻塞持有者提交;异库独立就绪", async () => {
@@ -81,7 +87,7 @@ describe("Todo144:迁移启动状态与真实 SQLite 锁", () => {
     dirs.push(dir);
     dirs.push(dir);
     const path = join(dir, "db.sqlite");
     const path = join(dir, "db.sqlite");
     const holder = open(path);
     const holder = open(path);
-    runSqliteSessionMigrations(holder, path);
+    await runSqliteSessionMigrations(holder, path);
     holder.exec("BEGIN IMMEDIATE");
     holder.exec("BEGIN IMMEDIATE");
     const waiter = open(path);
     const waiter = open(path);
     const phases: string[] = [];
     const phases: string[] = [];
@@ -130,7 +136,7 @@ describe("Todo144:迁移启动状态与真实 SQLite 锁", () => {
     dirs.push(dir);
     dirs.push(dir);
     const path = join(dir, "db.sqlite");
     const path = join(dir, "db.sqlite");
     const holder = open(path);
     const holder = open(path);
-    runSqliteSessionMigrations(holder, path);
+    await runSqliteSessionMigrations(holder, path);
     holder.exec("BEGIN IMMEDIATE");
     holder.exec("BEGIN IMMEDIATE");
     const waiter = open(path);
     const waiter = open(path);
     const phases: string[] = [];
     const phases: string[] = [];
@@ -150,13 +156,12 @@ describe("Todo144:迁移启动状态与真实 SQLite 锁", () => {
 it("openStartup 保留迁移原始错误,即使 close 也失败", async () => {
 it("openStartup 保留迁移原始错误,即使 close 也失败", async () => {
   const { SqliteSessionStore } =
   const { SqliteSessionStore } =
     await import("../src/storage/session-store/sqlite-session-store.js");
     await import("../src/storage/session-store/sqlite-session-store.js");
-  const originalClose = SqliteSessionStore.prototype.close;
-  vi.spyOn(SqliteSessionStore.prototype, "close").mockImplementation(
-    function (this: InstanceType<typeof SqliteSessionStore>) {
-      originalClose.call(this);
-      throw new Error("secondary close failure");
-    },
-  );
+  // 迁移失败发生在 store 实例返回前;应在真正持有连接的 DatabaseSync 上注入关闭失败。
+  const originalClose = DatabaseSync.prototype.close;
+  vi.spyOn(DatabaseSync.prototype, "close").mockImplementation(function (this: DatabaseSync) {
+    originalClose.call(this);
+    throw new Error("secondary close failure");
+  });
   const original = Object.assign(new Error("primary storage failure"), { errcode: 13 });
   const original = Object.assign(new Error("primary storage failure"), { errcode: 13 });
   await expect(
   await expect(
     SqliteSessionStore.openStartup(
     SqliteSessionStore.openStartup(
@@ -194,7 +199,9 @@ it("SILENTDB-02/04: reports real migration kind and counts only committed SQL as
     kind: "none",
     kind: "none",
     executedCount: 0,
     executedCount: 0,
     committedCount: 0,
     committedCount: 0,
-    lastAppliedMigrationId: SQLITE_MIGRATIONS.at(-1)?.id,
+    lastAppliedMigrationId: SQLITE_MIGRATIONS.map((m) => m.id)
+      .sort()
+      .at(-1),
   });
   });
   db.exec("DELETE FROM schema_migration WHERE id >= '0020'");
   db.exec("DELETE FROM schema_migration WHERE id >= '0020'");
   const failed: SqliteMigrationProgress[] = [];
   const failed: SqliteMigrationProgress[] = [];
@@ -219,7 +226,7 @@ it("SILENTDB-03: another writer can finish the observed migrations without this
   dirs.push(dir);
   dirs.push(dir);
   const path = join(dir, "db.sqlite");
   const path = join(dir, "db.sqlite");
   const holder = open(path);
   const holder = open(path);
-  runSqliteSessionMigrations(holder, path);
+  await runSqliteSessionMigrations(holder, path);
   holder.exec("DELETE FROM schema_migration WHERE id >= '0020'; BEGIN IMMEDIATE");
   holder.exec("DELETE FROM schema_migration WHERE id >= '0020'; BEGIN IMMEDIATE");
   const waiter = open(path);
   const waiter = open(path);
   const states: SqliteMigrationProgress[] = [];
   const states: SqliteMigrationProgress[] = [];
@@ -230,7 +237,7 @@ it("SILENTDB-03: another writer can finish the observed migrations without this
       if (state.phase === "waiting_for_lock") {
       if (state.phase === "waiting_for_lock") {
         expect(state.migration?.kind).toBe("upgrade");
         expect(state.migration?.kind).toBe("upgrade");
         holder.exec("COMMIT");
         holder.exec("COMMIT");
-        runSqliteSessionMigrations(holder, path);
+        await runSqliteSessionMigrations(holder, path);
       }
       }
     },
     },
   });
   });
@@ -238,13 +245,19 @@ it("SILENTDB-03: another writer can finish the observed migrations without this
     kind: "upgrade",
     kind: "upgrade",
     executedCount: 0,
     executedCount: 0,
     committedCount: 0,
     committedCount: 0,
-    lastAppliedMigrationId: SQLITE_MIGRATIONS.at(-1)?.id,
+    lastAppliedMigrationId: SQLITE_MIGRATIONS.map((m) => m.id)
+      .sort()
+      .at(-1),
   });
   });
   expect(exec.mock.calls.some(([sql]) => SQLITE_MIGRATIONS.some((m) => m.sql === sql))).toBe(false);
   expect(exec.mock.calls.some(([sql]) => SQLITE_MIGRATIONS.some((m) => m.sql === sql))).toBe(false);
   expect(
   expect(
     states.find((s) => s.phase === "waiting_for_lock")?.migration?.lastAppliedMigrationId,
     states.find((s) => s.phase === "waiting_for_lock")?.migration?.lastAppliedMigrationId,
   ).toBeUndefined();
   ).toBeUndefined();
-  expect(states.at(-1)?.migration?.lastAppliedMigrationId).toBe(SQLITE_MIGRATIONS.at(-1)?.id);
+  expect(states.at(-1)?.migration?.lastAppliedMigrationId).toBe(
+    SQLITE_MIGRATIONS.map((m) => m.id)
+      .sort()
+      .at(-1),
+  );
 });
 });
 
 
 it("publishes confirmed migration demand when lock contention recurs after precheck", async () => {
 it("publishes confirmed migration demand when lock contention recurs after precheck", async () => {
@@ -278,7 +291,7 @@ it("publishes confirmed migration demand when lock contention recurs after prech
 
 
 it("does not send malformed ledger IDs as telemetry or fail an otherwise prepared database", async () => {
 it("does not send malformed ledger IDs as telemetry or fail an otherwise prepared database", async () => {
   const db = open();
   const db = open();
-  runSqliteSessionMigrations(db, ":memory:");
+  await runSqliteSessionMigrations(db, ":memory:");
   db.prepare("INSERT INTO schema_migration VALUES (?, 'external', NULL, 0)").run(
   db.prepare("INSERT INTO schema_migration VALUES (?, 'external', NULL, 0)").run(
     "private / unexpected ID",
     "private / unexpected ID",
   );
   );

+ 315 - 0
apps/zcode-cli/packages/adapters/tests/attachment-resume-wire.test.ts

@@ -0,0 +1,315 @@
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createAnthropic } from "@ai-sdk/anthropic";
+import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
+import { generateText } from "ai";
+import { describe, expect, it } from "vitest";
+import {
+  createMessageId,
+  createProjectId,
+  createSessionId,
+  type AttachmentStorageMetadata,
+  type ModelInputMessage,
+  type TurnAttachment,
+} from "@zcode/contracts";
+import { MessageHistoryImpl } from "../../core/src/agent/message-history.js";
+import { hydrateMessageHistoryFromSession } from "../../core/src/agent/session-history-hydrator.js";
+import { resolveTurnAttachments } from "../../core/src/runtime/helpers/attachments.js";
+import { resolvedPathReferenceAttachment } from "../../core/src/runtime/helpers/attachment-path-reference.js";
+import { buildRuntimeUserEntriesFromTurn } from "../../core/src/runtime/helpers/conversation.js";
+import { projectMessagesWithMediaAttachmentPaths } from "../../core/src/runtime/helpers/media-attachment-path.js";
+import { buildProviderRequestMessages } from "../../core/src/runtime/helpers/provider-request-messages.js";
+import { persistUserPrompt } from "../../core/src/runtime/methods/message-persistence.js";
+import type { AgentRuntimeInternal } from "../../core/src/runtime/internal.js";
+import { createNodeFileSystemAdapter } from "../src/fs/index.js";
+import { toAiSdkMessages } from "../src/model/transform.js";
+import { createNodeToolArtifactStore, createSqliteSessionStore } from "../src/storage/index.js";
+
+const png =
+  "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aDo0AAAAASUVORK5CYII=";
+const pdf = `data:application/pdf;base64,${Buffer.from("%PDF-1.7\nfixture").toString("base64")}`;
+const scenarios: Array<{ name: string; attachments: TurnAttachment[] }> = [
+  { name: "binary path", attachments: [{ type: "file", path: "bundle.zip" }] },
+  {
+    name: "clipboard path",
+    attachments: [{ type: "file", path: "pasted.txt", sourceKind: "clipboard-text" }],
+  },
+  { name: "PDF", attachments: [{ type: "pdf", filename: "report.pdf", content: pdf }] },
+  {
+    name: "mixed media",
+    attachments: [
+      { type: "image", content: png },
+      { type: "pdf", filename: "report.pdf", content: pdf },
+      { type: "video", content: "data:video/mp4;base64,dmlkZW8=" },
+      { type: "image", content: png },
+    ],
+  },
+  { name: "text file", attachments: [{ type: "file", path: "notes.md" }] },
+  { name: "inline text", attachments: [{ type: "file", content: "inline notes" }] },
+  { name: "no attachment", attachments: [] },
+];
+
+async function captureWire(messages: ModelInputMessage[], kind: "anthropic" | "openai") {
+  let captured: unknown;
+  const fetch = async (_input: unknown, init?: RequestInit) => {
+    captured = JSON.parse(String(init?.body));
+    return Response.json(
+      kind === "anthropic"
+        ? {
+            id: "fixture",
+            type: "message",
+            role: "assistant",
+            model: "fixture",
+            content: [{ type: "text", text: "done" }],
+            stop_reason: "end_turn",
+            stop_sequence: null,
+            usage: { input_tokens: 1, output_tokens: 1 },
+          }
+        : {
+            id: "fixture",
+            object: "chat.completion",
+            created: 1,
+            model: "fixture",
+            choices: [
+              { index: 0, message: { role: "assistant", content: "done" }, finish_reason: "stop" },
+            ],
+            usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
+          },
+    );
+  };
+  const options = { apiKey: "fixture-key", baseURL: "https://provider.example/v1", fetch };
+  const model =
+    kind === "anthropic"
+      ? createAnthropic(options)("fixture")
+      : createOpenAICompatible({ ...options, name: "fixture" })("fixture");
+  await generateText({
+    model,
+    maxRetries: 0,
+    messages: toAiSdkMessages(messages, {
+      inputFormat: { supportsImage: true, supportsPdf: true, supportsVideo: true },
+    }),
+  });
+  expect(captured).toBeDefined();
+  return captured;
+}
+
+async function fixture() {
+  const root = await mkdtemp(join(tmpdir(), "attachment-resume-"));
+  const dbPath = join(root, "session.sqlite");
+  const sessionId = createSessionId("attachment-resume");
+  let store = await createSqliteSessionStore({ dbPath });
+  await store.createSession({
+    id: sessionId,
+    projectID: createProjectId("fixture"),
+    slug: "fixture",
+    directory: root,
+    title: "fixture",
+    version: "1",
+  });
+  await Promise.all([
+    writeFile(join(root, "bundle.zip"), "binary fixture"),
+    writeFile(join(root, "pasted.txt"), "clipboard text"),
+    writeFile(join(root, "notes.md"), "# Notes\nKeep exact text."),
+    writeFile(join(root, "local.png"), Buffer.from(png.split(",")[1]!, "base64")),
+  ]);
+  const artifactStore = createNodeToolArtifactStore({
+    rootDir: join(root, "artifacts"),
+    imageCacheRootDir: join(root, "images"),
+    videoCacheRootDir: join(root, "videos"),
+  });
+  const history = new MessageHistoryImpl();
+  history.init("system fixture");
+  const runtime = {
+    sessionId,
+    sessionStore: store,
+    messageHistory: history,
+    artifactStore,
+    fileSystemPort: createNodeFileSystemAdapter(),
+    workingDirectory: root,
+    config: { agentName: "fixture", systemPrompt: "system fixture" },
+    getTools: () => [],
+    getSessionModelSelection: () => undefined,
+    persistMessage: (message: Parameters<typeof store.saveMessage>[0]) =>
+      store.saveMessage(message),
+    persistPart: (part: Parameters<typeof store.savePart>[0]) => store.savePart(part),
+  } as unknown as AgentRuntimeInternal;
+  runtime.persistUserPrompt = persistUserPrompt.bind(runtime);
+  return {
+    root,
+    runtime,
+    history,
+    artifactStore,
+    async cold() {
+      store.close();
+      store = await createSqliteSessionStore({ dbPath });
+      const messages = await store.messages({ sessionID: sessionId });
+      const cold = new MessageHistoryImpl();
+      cold.init("system fixture");
+      await hydrateMessageHistoryFromSession({ history: cold, messages, artifactStore });
+      return { history: cold, messages };
+    },
+    async close() {
+      store.close();
+      await rm(root, { recursive: true, force: true });
+    },
+  };
+}
+
+describe("attachment history across durable cold resume", () => {
+  for (const scenario of scenarios) {
+    it.each(scenario.attachments.length ? ["Summarize the attachment.", ""] : ["Text only."])(
+      `${scenario.name}, prompt=%j: preserves final SDK request`,
+      async (prompt) => {
+        const f = await fixture();
+        try {
+          const resolved = await resolveTurnAttachments(scenario.attachments, {
+            ...f.runtime,
+            traceContext: { traceId: "fixture" },
+          });
+          f.history.addEntries(buildRuntimeUserEntriesFromTurn(prompt, resolved));
+          await f.runtime.persistUserPrompt(createMessageId("first"), prompt, resolved, {
+            traceId: "fixture",
+          });
+          const cold = await f.cold();
+          for (const attachment of resolved.filter((a) => a.metadata.storageKind === "local_ref")) {
+            const part = cold.messages[0]!.parts.find(
+              (p) => p.type === "file" && p.url === attachment.url,
+            );
+            expect(part).toMatchObject({
+              metadata: {
+                pathReferenceText:
+                  attachment.contentBlock.type === "text"
+                    ? attachment.contentBlock.text
+                    : undefined,
+              },
+            });
+          }
+          for (const useMidConversationSystem of [false, true]) {
+            const requests = await Promise.all(
+              [f.history, cold.history].map(async (history) => {
+                const entries = [
+                  ...history.toRuntimeEntries(),
+                  { message: { role: "assistant" as const, content: "done" } },
+                  {
+                    message: { role: "user" as const, content: "Continue." },
+                    metadata: { source: "real_user" as const },
+                  },
+                ];
+                const { messages } = buildProviderRequestMessages({
+                  entries,
+                  useMidConversationSystem,
+                  applyCacheControl: true,
+                });
+                return projectMessagesWithMediaAttachmentPaths(messages, f.artifactStore);
+              }),
+            );
+            for (const provider of ["anthropic", "openai"] as const) {
+              expect(await captureWire(requests[1]!, provider)).toEqual(
+                await captureWire(requests[0]!, provider),
+              );
+            }
+          }
+          expect((await f.cold()).history.toRuntimeEntries()).toEqual(
+            cold.history.toRuntimeEntries(),
+          );
+        } finally {
+          await f.close();
+        }
+      },
+    );
+  }
+
+  it.each([
+    ["image/png", "image_too_large"],
+    ["application/pdf", "pdf_too_large"],
+    ["video/mp4", "video_too_large"],
+    ["text/plain", "text_too_large"],
+    ["text/plain", "deferred_topic_history"],
+  ] as const)("restores %s path text for %s without preview or source IO", async (mime, reason) => {
+    const f = await fixture();
+    try {
+      const path = join(f.root, "missing-attachment");
+      const attachment = resolvedPathReferenceAttachment({ type: "file", path }, path, {
+        mime,
+        reason,
+        source: { type: "file", path, text: { value: path, start: 0, end: path.length } },
+      });
+      expect(attachment.metadata.preview).toBeUndefined();
+      f.history.addEntries(buildRuntimeUserEntriesFromTurn("Inspect.", [attachment]));
+      await f.runtime.persistUserPrompt(createMessageId("path-text"), "Inspect.", [attachment], {
+        traceId: "fixture",
+      });
+      expect((await f.cold()).history.toRuntimeEntries()).toEqual(f.history.toRuntimeEntries());
+    } finally {
+      await f.close();
+    }
+  });
+
+  it("keeps local images in submission order even when hydration rebuilds their media source as inline", async () => {
+    const f = await fixture();
+    try {
+      const resolved = await resolveTurnAttachments(
+        [
+          { type: "image", content: png },
+          { type: "image", path: "local.png" },
+          { type: "pdf", content: pdf, filename: "report.pdf" },
+        ],
+        { ...f.runtime, traceContext: { traceId: "fixture" } },
+      );
+      f.history.addEntries(buildRuntimeUserEntriesFromTurn("Compare.", resolved));
+      await f.runtime.persistUserPrompt(createMessageId("mixed-local"), "Compare.", resolved, {
+        traceId: "fixture",
+      });
+      const cold = await f.cold();
+      // 这里只比较媒体与正文合同;local path 到 artifact 派生 path 的既有投影单独测试。
+      const requests = [f.history, cold.history].map(
+        (h) => buildProviderRequestMessages({ entries: h.toRuntimeEntries() }).messages,
+      );
+      const transformOptions = {
+        inputFormat: { supportsImage: true, supportsPdf: true, supportsVideo: true },
+      };
+      const first = toAiSdkMessages(requests[0]!, transformOptions);
+      expect(toAiSdkMessages(requests[1]!, transformOptions)).toEqual(first);
+      const user = requests[0]!.find((m) => m.role === "user")!;
+      expect(Array.isArray(user.content) && user.content.map((b) => b.type)).toEqual([
+        "text",
+        "image",
+        "file",
+        "image",
+      ]);
+    } finally {
+      await f.close();
+    }
+  });
+
+  it.each([undefined, 42, { text: "invalid" }])(
+    "keeps the legacy placeholder when saved path text is %j",
+    async (pathReferenceText) => {
+      const f = await fixture();
+      try {
+        const resolved = await resolveTurnAttachments([{ type: "file", path: "bundle.zip" }], {
+          ...f.runtime,
+          traceContext: { traceId: "fixture" },
+        });
+        resolved[0]!.metadata = {
+          ...resolved[0]!.metadata,
+          pathReferenceText,
+        } as AttachmentStorageMetadata;
+        await f.runtime.persistUserPrompt(createMessageId("legacy"), "Prompt", resolved, {
+          traceId: "fixture",
+        });
+        const cold = await f.cold();
+        expect(
+          buildProviderRequestMessages({ entries: cold.history.toRuntimeEntries() }).messages.at(-1)
+            ?.content,
+        ).toEqual([
+          { type: "text", text: "Prompt" },
+          { type: "text", text: "[Attached application/octet-stream: bundle.zip]" },
+        ]);
+      } finally {
+        await f.close();
+      }
+    },
+  );
+});

+ 3 - 1
apps/zcode-cli/packages/adapters/tests/auth.test.ts

@@ -507,8 +507,10 @@ describe("Coding Plan API key resolver", () => {
     ).resolves.toBe("project-token");
     ).resolves.toBe("project-token");
     expect(httpClient.requests[0]?.url).toBe("https://api.z.ai/api/auth/z/login");
     expect(httpClient.requests[0]?.url).toBe("https://api.z.ai/api/auth/z/login");
     expect(httpClient.requests[1]?.headers).toMatchObject({
     expect(httpClient.requests[1]?.headers).toMatchObject({
-      authorization: "Bearer zai-biz-token",
+      authorization: "zai-biz-token",
     });
     });
+    for (const request of httpClient.requests.slice(2))
+      expect(request.headers).toMatchObject({ authorization: "Bearer zai-biz-token" });
   });
   });
 
 
   it("resolves a BigModel OAuth access token through project access token issuance", async () => {
   it("resolves a BigModel OAuth access token through project access token issuance", async () => {

+ 14 - 3
apps/zcode-cli/packages/adapters/tests/builtin-mcs-search-wire.test.ts

@@ -37,14 +37,14 @@ describe("Published MCS and search final Anthropic wire", () => {
       "https://zcode.z.ai/api/v1/off-peak/anthropic",
       "https://zcode.z.ai/api/v1/off-peak/anthropic",
       "GLM-5.3-Flash",
       "GLM-5.3-Flash",
       true,
       true,
-      true,
+      false,
     ],
     ],
     [
     [
       "account:bigmodel-offpeak-idle-plan",
       "account:bigmodel-offpeak-idle-plan",
       "https://zcode.z.ai/api/v1/off-peak/anthropic",
       "https://zcode.z.ai/api/v1/off-peak/anthropic",
       "GLM-5.3-Flash",
       "GLM-5.3-Flash",
       true,
       true,
-      true,
+      false,
     ],
     ],
     ["fixture", "https://api.anthropic.com/v1", "claude-sonnet-5", false, true],
     ["fixture", "https://api.anthropic.com/v1", "claude-sonnet-5", false, true],
     ["fixture", "https://proxy.invalid/v1", "vendor/claude-opus-4-8", true, false],
     ["fixture", "https://proxy.invalid/v1", "vendor/claude-opus-4-8", true, false],
@@ -91,7 +91,17 @@ describe("Published MCS and search final Anthropic wire", () => {
       });
       });
     });
     });
     try {
     try {
-      const adapter = new AiSdkModelAdapter({ env: {}, retry: { maxAttempts: 1 } });
+      const adapter = new AiSdkModelAdapter({
+        env: {},
+        retry: { maxAttempts: 1 },
+        // 本用例验证模型配置与 wire;安全端口注入离线透传,独立安全契约用例覆盖官方版本校验。
+        requestSecurityState: {
+          createExecution: () => ({
+            protectTransport: ({ transport }) => transport,
+            take: () => [],
+          }),
+        },
+      });
       const model = adapter.createModel({
       const model = adapter.createModel({
         providerId: createModelProviderId(providerId),
         providerId: createModelProviderId(providerId),
         modelId: createModelId(modelId),
         modelId: createModelId(modelId),
@@ -102,6 +112,7 @@ describe("Published MCS and search final Anthropic wire", () => {
           reasoningLevel: config.optionSpecs!.reasoningLevel!.values!.at(-1)!,
           reasoningLevel: config.optionSpecs!.reasoningLevel!.values!.at(-1)!,
         },
         },
       });
       });
+      expect(model.properties.supportsNativeWebSearch).toBe(search);
       await model.generateText({
       await model.generateText({
         messages: buildProviderRequestMessages({
         messages: buildProviderRequestMessages({
           useMidConversationSystem: model.properties.supportsMidConversationSystem,
           useMidConversationSystem: model.properties.supportsMidConversationSystem,

+ 29 - 0
apps/zcode-cli/packages/adapters/tests/commands.test.ts

@@ -255,3 +255,32 @@ async function writeCommand(dir: string, name: string, description: string): Pro
     ["---", `description: ${description}`, "---", "", "# Body"].join("\n"),
     ["---", `description: ${description}`, "---", "", "# Body"].join("\n"),
   );
   );
 }
 }
+
+it("附加目录命令使用目录限定名并保留原 cwd 命令", async () => {
+  const root = await mkdtemp(join(tmpdir(), "zcode-additional-commands-"));
+  try {
+    const main = join(root, "frontend"),
+      extra = join(root, "backend");
+    for (const dir of [main, extra]) {
+      await mkdir(join(dir, ".zcode", "commands"), { recursive: true });
+      await writeFile(
+        join(dir, ".zcode", "commands", "review.md"),
+        `---\ndescription: review\n---\n${dir}`,
+      );
+    }
+    const adapter = createNodeCustomCommandAdapter({
+      homeDirectory: join(root, "home"),
+      additionalDirectories: [extra],
+    });
+    expect(
+      (await adapter.discoverCommands({ workingDirectory: main })).commands
+        .map((c) => c.name)
+        .sort(),
+    ).toEqual(["backend/review", "review"]);
+    expect(
+      (await adapter.loadCommand({ workingDirectory: main, name: "backend/review" })).content,
+    ).toContain(extra);
+  } finally {
+    await rm(root, { recursive: true, force: true });
+  }
+});

+ 40 - 1005
apps/zcode-cli/packages/adapters/tests/config.test.ts

@@ -1,11 +1,5 @@
 import { describe, expect, it } from "vitest";
 import { describe, expect, it } from "vitest";
-import { ConfigScope, DefaultRuntimeConfig } from "@zcode/contracts";
-import {
-  createConfig,
-  updateCodingPlanProviderInFileConfig,
-  updateModelSelectionInFileConfig,
-  updateUiLocaleInFileConfig,
-} from "../src/config/index.js";
+import { createConfig, updateUiLocaleInFileConfig } from "../src/config/index.js";
 import { parseEnvConfig } from "../src/config/env-config.adapter.js";
 import { parseEnvConfig } from "../src/config/env-config.adapter.js";
 import {
 import {
   addSuppressedBuiltinInFileConfig,
   addSuppressedBuiltinInFileConfig,
@@ -15,7 +9,6 @@ import {
   updatePluginEnabledInFileConfig,
   updatePluginEnabledInFileConfig,
   updatePluginOptionsInFileConfig,
   updatePluginOptionsInFileConfig,
 } from "../src/config/file-config.adapter.js";
 } from "../src/config/file-config.adapter.js";
-import { ModelCatalogService } from "../src/model/catalog.js";
 import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
 import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
 import { tmpdir } from "node:os";
 import { tmpdir } from "node:os";
 import { join } from "node:path";
 import { join } from "node:path";
@@ -116,12 +109,11 @@ describe("config adapters", () => {
         ).suppressed,
         ).suppressed,
       ).toBe(false);
       ).toBe(false);
       expect(
       expect(
-        (
-          await removePluginFromFileConfig(configPath, "computer-use@zcode-plugins-official")
-        ).removedEnabled,
+        (await removePluginFromFileConfig(configPath, "computer-use@zcode-plugins-official"))
+          .removedEnabled,
       ).toBe(true);
       ).toBe(true);
       expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({
       expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({
-        plugins: { enabledPlugins: {}, suppressedBuiltins: [] },
+        plugins: { enabledPlugins: {}, suppressedBuiltins: [], options: {} },
       });
       });
     } finally {
     } finally {
       await rm(dir, { force: true, recursive: true });
       await rm(dir, { force: true, recursive: true });
@@ -310,11 +302,6 @@ describe("config adapters", () => {
     }
     }
   });
   });
 
 
-  it("keeps Plugin scope priority aligned with User then Workspace", () => {
-    expect(ConfigScope.User).toBe("user");
-    expect(ConfigScope.Project).toBe("project");
-  });
-
   it("parses the supported ZCODE environment surface", () => {
   it("parses the supported ZCODE environment surface", () => {
     const config = parseEnvConfig({
     const config = parseEnvConfig({
       ZCODE_STORAGE_DIR: "/tmp/zcode",
       ZCODE_STORAGE_DIR: "/tmp/zcode",
@@ -337,30 +324,6 @@ describe("config adapters", () => {
     expect(config.logging?.level).toBeUndefined();
     expect(config.logging?.level).toBeUndefined();
   });
   });
 
 
-  it("defaults the session database to db/db.sqlite", () => {
-    const result = createConfig({ env: {}, skipUserConfig: true });
-
-    expect(result.config.model).toBeUndefined();
-    expect(DefaultRuntimeConfig.storage.sessionDbPath).toBe("~/.zcode/cli/db/db.sqlite");
-    expect(result.config.storage.sessionDbPath).toBe("~/.zcode/cli/db/db.sqlite");
-  });
-
-  it("defaults model stream idle timeout to ten minutes", () => {
-    const result = createConfig({ env: {}, skipUserConfig: true });
-
-    expect(DefaultRuntimeConfig.modelStream.idleTimeoutMs).toBe(600_000);
-    expect(result.config.modelStream.idleTimeoutMs).toBe(600_000);
-  });
-
-  it("defaults the supported memory switches to enabled", () => {
-    const result = createConfig({ env: {}, skipUserConfig: true });
-
-    expect(result.config.features.memory).toBe(true);
-    expect(result.config.memory).toEqual({
-      use: true,
-    });
-  });
-
   it("loads the supported memory config fields", async () => {
   it("loads the supported memory config fields", async () => {
     const dir = await mkdtemp(join(tmpdir(), "zcode-config-memory-"));
     const dir = await mkdtemp(join(tmpdir(), "zcode-config-memory-"));
     const path = join(dir, "config.json");
     const path = join(dir, "config.json");
@@ -1800,977 +1763,49 @@ describe("config adapters", () => {
     }
     }
   });
   });
 
 
-  it("rejects inline model target config from file", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          model: {
-            provider: "default-deepseek",
-            model: "deepseek-V4-Pro",
-            baseURL: "https://api.deepseek.com",
-            apiKey: "secret",
-            headers: {
-              "X-Title": "Z Code",
-            },
-          },
-        }),
-      );
-
-      const result = loadFileConfig(path);
-
-      expect(result.loaded).toBe(false);
-      expect(result.config).toEqual({});
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("loads main and lite model references from provider-first config", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          model: {
-            main: "deepseek/deepseek-v4-pro",
-            lite: "deepseek/deepseek-chat",
-          },
-          provider: {
-            deepseek: {
-              kind: "openai-compatible",
-              name: "DeepSeek",
-              options: {
-                baseURL: "https://api.deepseek.com",
-                apiKey: "secret",
-              },
-              models: {
-                "deepseek-v4-pro": {
-                  name: "DeepSeek V4 Pro",
-                },
-                "deepseek-chat": {
-                  name: "DeepSeek Chat",
-                },
-              },
-            },
-          },
-        }),
-      );
-
-      const result = loadFileConfig(path);
-
-      expect(result.loaded).toBe(true);
-      expect(result.config.model?.main).toMatchObject({
-        provider: "deepseek",
-        model: "deepseek-v4-pro",
-        kind: "openai-compatible",
-        baseURL: "https://api.deepseek.com",
-        apiKey: "secret",
-      });
-      expect(result.config.model?.lite?.model).toBe("deepseek-chat");
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("patches string model selection in file config without dropping other fields", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          model: "deepseek/deepseek-chat",
-          mcp: {
-            servers: {
-              local: {
-                type: "stdio",
-                command: "node",
-              },
-            },
-          },
-          provider: {
-            deepseek: {
-              kind: "openai-compatible",
-              options: {
-                baseURL: "https://api.deepseek.com",
-                apiKey: "secret",
-              },
-              models: {
-                "deepseek-chat": {},
-                "deepseek-v4-pro": {},
-              },
-            },
-          },
-        }),
-      );
-
-      await updateModelSelectionInFileConfig(path, "deepseek/deepseek-v4-pro");
-
-      const updated = JSON.parse(await readFile(path, "utf-8"));
-      expect(updated.model).toBe("deepseek/deepseek-v4-pro");
-      expect(updated.mcp.servers.local.command).toBe("node");
-      expect(updated.provider.deepseek.options.apiKey).toBe("secret");
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("patches object model main in file config without changing lite", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          model: {
-            main: "deepseek/deepseek-chat",
-            lite: "deepseek/deepseek-lite",
-          },
-          provider: {
-            deepseek: {
-              kind: "openai-compatible",
-              options: {
-                baseURL: "https://api.deepseek.com",
-              },
-              models: {
-                "deepseek-chat": {},
-                "deepseek-lite": {},
-                "deepseek-v4-pro": {},
-              },
-            },
-          },
-        }),
-      );
-
-      await updateModelSelectionInFileConfig(path, "deepseek/deepseek-v4-pro");
-
-      const updated = JSON.parse(await readFile(path, "utf-8"));
-      expect(updated.model).toEqual({
-        main: "deepseek/deepseek-v4-pro",
-        lite: "deepseek/deepseek-lite",
-      });
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("patches ZAI Coding Plan provider config with an API key", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          provider: {
-            zai: {
-              kind: "openai-compatible",
-              options: {
-                apiKey: "legacy-secret",
-                baseURL: "https://legacy.example/v1",
-                timeout: 30000,
-              },
-              models: {
-                "glm-5.1": {
-                  contextWindow: 200000,
-                },
-              },
-            },
-            deepseek: {
-              kind: "openai-compatible",
-              options: {
-                apiKey: "deepseek-secret",
-                baseURL: "https://api.deepseek.example",
-              },
-              models: {
-                "deepseek-chat": {},
-              },
-            },
-          },
-          model: {
-            main: "deepseek/deepseek-chat",
-            lite: "deepseek/deepseek-chat",
-          },
-        }),
-      );
-
-      const result = await updateCodingPlanProviderInFileConfig({
-        apiKey: "zai-coding-key",
-        filePath: path,
-        providerId: "zai",
-      });
-      const updated = JSON.parse(await readFile(path, "utf-8"));
-
-      expect(result).toEqual({
-        mainModel: "zai/glm-5.1",
-        path,
-        providerId: "zai",
-      });
-      expect(updated.provider.zai.kind).toBe("anthropic");
-      expect(updated.provider.zai.options).toEqual({
-        apiKey: "zai-coding-key",
-        apiKeyRequired: true,
-        baseURL: "https://api.z.ai/api/anthropic",
-        timeout: 30000,
-      });
-      expect(updated.provider.zai.models["glm-5.1"]).toEqual({
-        contextWindow: 200000,
-        name: "GLM-5.1",
-      });
-      expect(updated.provider.deepseek.options.apiKey).toBe("deepseek-secret");
-      expect(updated.model).toEqual({
-        main: "zai/glm-5.1",
-        lite: "deepseek/deepseek-chat",
-      });
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("creates default Coding Plan configs when the file is missing", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await updateCodingPlanProviderInFileConfig({
-        apiKey: "bigmodel-coding-key",
-        filePath: path,
-        providerId: "bigmodel",
-      });
-
-      const updated = JSON.parse(await readFile(path, "utf-8"));
-      expect(updated.model).toEqual({
-        main: "bigmodel/glm-5.1",
-        lite: "bigmodel/glm-4.7",
-      });
-      expect(updated.provider.bigmodel).toMatchObject({
-        kind: "anthropic",
-        name: "BigModel Coding Plan",
-        options: {
-          apiKey: "bigmodel-coding-key",
-          apiKeyRequired: true,
-          baseURL: "https://open.bigmodel.cn/api/anthropic",
-        },
-      });
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("loads provider map config with model metadata", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          $schema: "https://zcode.ai/schema/config-v2.json",
-          provider: {
-            "provider-auth-zai": {
-              kind: "openai-compatible",
-              name: "Z.AI",
-              options: {
-                baseURL: "https://api.z.ai/api/coding/v1",
-                apiKey: "secret",
-                includeUsage: false,
-              },
-              models: {
-                "glm-5": {
-                  name: "GLM-5",
-                  reasoning: {
-                    enabled: true,
-                    levels: ["low", "medium", "high"],
-                    defaultLevel: "medium",
-                    providerOptionsByLevel: {
-                      high: {
-                        reasoningEffort: "high",
-                      },
-                    },
-                  },
-                  modalities: {
-                    input: ["text", "image", "pdf", "video"],
-                    output: ["text"],
-                  },
-                  limit: {
-                    context: 200000,
-                    output: 8192,
-                  },
-                  tool_call: true,
-                  options: {
-                    reasoningSummary: "auto",
-                  },
-                },
-                "glm-4.7": {
-                  name: "GLM-4.7",
-                  attachment: false,
-                  reasoning: false,
-                  limit: {
-                    context: 128000,
-                    output: 4096,
-                  },
-                },
-              },
-            },
-          },
-          model: {
-            main: "provider-auth-zai/glm-5",
-            lite: "provider-auth-zai/glm-4.7",
-          },
-        }),
-      );
-
-      const result = loadFileConfig(path);
-
-      expect(result.loaded).toBe(true);
-      expect(result.config.model?.main).toEqual({
-        provider: "provider-auth-zai",
-        model: "glm-5",
-        kind: "openai-compatible",
-        providerName: "Z.AI",
-        baseURL: "https://api.z.ai/api/coding/v1",
-        apiKey: "secret",
-        includeUsage: false,
-        providerOptions: {
-          openaiCompatible: {
-            reasoningSummary: "auto",
-          },
-        },
-      });
-      expect(result.config.model?.lite?.model).toBe("glm-4.7");
-      expect(result.config.model?.lite?.baseURL).toBe("https://api.z.ai/api/coding/v1");
-      expect(
-        result.config.model?.available?.map((target) => `${target.provider}/${target.model}`),
-      ).toEqual(["provider-auth-zai/glm-5", "provider-auth-zai/glm-4.7"]);
-      expect(result.config.modelCatalog?.overrides?.["provider-auth-zai/glm-5"]).toEqual({
-        name: "GLM-5",
-        contextWindow: 200000,
-        maxOutputTokens: 8192,
-        supportsImages: true,
-        supportsPdf: true,
-        supportsVideo: true,
-        supportsReasoning: true,
-        supportsToolCall: true,
-        reasoning: {
-          enabled: true,
-          levels: ["low", "medium", "high"],
-          defaultLevel: "medium",
-          providerOptionsByLevel: {
-            high: {
-              openaiCompatible: {
-                reasoningEffort: "high",
-              },
-            },
-          },
-        },
-      });
-      expect(result.config.modelCatalog?.overrides?.["provider-auth-zai/glm-4.7"]).toEqual({
-        name: "GLM-4.7",
-        contextWindow: 128000,
-        maxOutputTokens: 4096,
-        supportsImages: false,
-        supportsReasoning: false,
-        reasoning: {
-          enabled: false,
-        },
-      });
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("maps top-level model maxOutputTokens into the existing model capability override", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-model-output-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          provider: {
-            "axec-proxy": {
-              kind: "anthropic",
-              name: "AxecProxy",
-              options: {
-                apiKey: "test-key",
-                baseURL: "https://api.infra.example.invalid/v1",
-              },
-              models: {
-                "tob-glm-5.2-cc": {
-                  contextWindow: 1_000_000,
-                  maxOutputTokens: 64_000,
-                  name: "tob-glm-5.2-cc",
-                },
-              },
-            },
-          },
-          model: "axec-proxy/tob-glm-5.2-cc",
-        }),
-      );
-
-      const result = loadFileConfig(path);
-
-      expect(result.loaded).toBe(true);
-      expect(result.config.modelCatalog.overrides["axec-proxy/tob-glm-5.2-cc"]).toMatchObject({
-        contextWindow: 1_000_000,
-        maxOutputTokens: 64_000,
-      });
-      expect(result.config.model?.main).toMatchObject({
-        model: "tob-glm-5.2-cc",
-        provider: "axec-proxy",
-      });
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("resolves output budget with limit before options.max_tokens before top-level", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-model-output-precedence-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          provider: {
-            compatible: {
-              kind: "openai-compatible",
-              models: {
-                "limit-wins": {
-                  limit: { output: 64_000 },
-                  maxOutputTokens: 16_000,
-                  options: { max_tokens: 32_000 },
-                },
-                "options-wins": {
-                  maxOutputTokens: 16_000,
-                  options: { max_tokens: 48_000 },
-                },
-              },
-            },
-          },
-          model: "compatible/limit-wins",
-        }),
-      );
-
-      const result = loadFileConfig(path);
-
-      expect(result.config.modelCatalog.overrides["compatible/limit-wins"]?.maxOutputTokens).toBe(
-        64_000,
-      );
-      expect(result.config.modelCatalog.overrides["compatible/options-wins"]?.maxOutputTokens).toBe(
-        48_000,
-      );
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("uses kind-aware Anthropic defaults for configured thinking models", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          provider: {
-            zai: {
-              kind: "anthropic",
-              options: {
-                baseURL: "https://api.z.ai/api/anthropic/v1",
-                apiKey: "secret",
-              },
-              models: {
-                "deepseek-v4-pro": {},
-                "glm-5.1": {},
-                "glm-5.2": {},
-                "deepseek-v4-toB-glm-5.3-route": {},
-                "glm-0531[1m]": {},
-                "glm-0606[1m]": {},
-                "kimi-k3": {},
-                k3: {},
-                "k3-256k": {},
-              },
-            },
-          },
-          model: "zai/glm-5.1",
-        }),
-      );
-
-      const result = loadFileConfig(path);
-
-      expect(result.loaded).toBe(true);
-      expect(result.config.modelCatalog?.overrides?.["zai/glm-5.1"]).toEqual({
-        supportsReasoning: true,
-        reasoning: {
-          enabled: true,
-          levels: ["enabled", "disabled"],
-          defaultLevel: "enabled",
-          providerOptionsByLevel: {
-            enabled: {
-              anthropic: {
-                thinking: {
-                  budgetTokens: 1024,
-                  type: "enabled",
-                },
-              },
-            },
-            disabled: {
-              anthropic: {
-                thinking: {
-                  type: "disabled",
-                },
-              },
-            },
-          },
-        },
-      });
-      expect(result.config.modelCatalog?.overrides?.["zai/deepseek-v4-pro"]).toEqual({
-        supportsReasoning: true,
-        reasoning: {
-          enabled: true,
-          levels: ["high", "max"],
-          defaultLevel: "max",
-          providerOptionsByLevel: {
-            high: {
-              anthropic: {
-                effort: "high",
-                thinking: {
-                  budgetTokens: 1024,
-                  type: "enabled",
-                },
-              },
-            },
-            max: {
-              anthropic: {
-                effort: "max",
-                thinking: {
-                  budgetTokens: 1024,
-                  type: "enabled",
-                },
-              },
-            },
-          },
-        },
-      });
-      expect(result.config.modelCatalog?.overrides?.["zai/glm-5.2"]).toEqual({
-        supportsReasoning: true,
-        reasoning: {
-          enabled: true,
-          levels: ["max", "high", "nothink"],
-          defaultLevel: "max",
-          providerOptionsByLevel: {
-            high: {
-              anthropic: {
-                effort: "high",
-                thinking: {
-                  budgetTokens: 16_000,
-                  type: "enabled",
-                },
-              },
-            },
-            max: {
-              anthropic: {
-                effort: "max",
-                thinking: {
-                  budgetTokens: 32_000,
-                  type: "enabled",
-                },
-              },
-            },
-            nothink: {
-              anthropic: {
-                thinking: {
-                  type: "disabled",
-                },
-              },
-            },
-          },
-        },
-      });
-      expect(result.config.modelCatalog?.overrides?.["zai/deepseek-v4-toB-glm-5.3-route"]).toEqual({
-        supportsReasoning: true,
-        reasoning: {
-          enabled: true,
-          levels: ["low", "high", "max"],
-          defaultLevel: "max",
-          providerOptionsByLevel: {
-            low: {
-              anthropic: {
-                effort: "low",
-                thinking: { budgetTokens: 8_000, type: "enabled" },
-              },
-            },
-            high: {
-              anthropic: {
-                effort: "high",
-                thinking: { budgetTokens: 16_000, type: "enabled" },
-              },
-            },
-            max: {
-              anthropic: {
-                effort: "max",
-                thinking: { budgetTokens: 32_000, type: "enabled" },
-              },
-            },
-          },
-        },
-      });
-      expect(result.config.modelCatalog?.overrides?.["zai/glm-0531[1m]"]?.reasoning).toEqual(
-        result.config.modelCatalog?.overrides?.["zai/glm-5.2"]?.reasoning,
-      );
-      expect(result.config.modelCatalog?.overrides?.["zai/glm-0606[1m]"]?.reasoning).toEqual(
-        result.config.modelCatalog?.overrides?.["zai/glm-5.2"]?.reasoning,
-      );
-      expect(result.config.modelCatalog?.overrides?.["zai/kimi-k3"]).toEqual({
-        supportsReasoning: true,
-        reasoning: {
-          enabled: true,
-          levels: ["low", "high", "max"],
-          defaultLevel: "max",
-          providerOptionsByLevel: {
-            low: { anthropic: { effort: "low" } },
-            high: { anthropic: { effort: "high" } },
-            max: { anthropic: { effort: "max" } },
-          },
-        },
-      });
-      expect(result.config.modelCatalog?.overrides?.["zai/k3"]).toEqual(
-        result.config.modelCatalog?.overrides?.["zai/kimi-k3"],
-      );
-      expect(result.config.modelCatalog?.overrides?.["zai/k3-256k"]).toEqual(
-        result.config.modelCatalog?.overrides?.["zai/kimi-k3"],
-      );
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("maps ox-alpha reasoning by configured transport without injecting unrelated defaults", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-ox-alpha-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          provider: {
-            "openrouter-chat": {
-              kind: "openai-compatible",
-              models: {
-                "vendor/ox-alpha-preview": {},
-                "GLM-X-PREVIEW-F": {},
-                "X-pReViEw-F-fReE": {},
-              },
-            },
-            "openrouter-anthropic": {
-              kind: "anthropic",
-              models: {
-                "ox-alpha": {},
-                "gLm-X-pReViEw-F": {},
-                "x-PrEvIeW-f-FrEe": {},
-              },
-            },
-            "openrouter-responses": {
-              kind: "openai",
-              models: { "ox-alpha": {}, "GlM-x-PrEvIeW-f": {} },
-            },
-          },
-          model: "openrouter-chat/vendor/ox-alpha-preview",
-        }),
-      );
-
-      const result = loadFileConfig(path);
-
-      expect(
-        result.config.modelCatalog.overrides["openrouter-chat/vendor/ox-alpha-preview"],
-      ).toEqual({
-        reasoning: {
-          defaultLevel: "max",
-          enabled: true,
-          levels: ["low", "high", "max"],
-          providerOptionsByLevel: {
-            low: { openaiCompatible: { reasoningEffort: "low" } },
-            high: { openaiCompatible: { reasoningEffort: "high" } },
-            max: { openaiCompatible: { reasoningEffort: "max" } },
-          },
-        },
-        supportsReasoning: true,
-      });
-      expect(result.config.modelCatalog.overrides["openrouter-anthropic/ox-alpha"]).toEqual({
-        reasoning: {
-          defaultLevel: "max",
-          enabled: true,
-          levels: ["low", "high", "max"],
-          providerOptionsByLevel: {
-            low: { anthropic: { effort: "low", thinking: { type: "adaptive" } } },
-            high: { anthropic: { effort: "high", thinking: { type: "adaptive" } } },
-            max: { anthropic: { effort: "max", thinking: { type: "adaptive" } } },
-          },
+  // Provider/Model 配置已归 Registry 管理;通用配置忽略退场字段,不得重新推导模型选择。
+  it.each([
+    { model: { provider: "example", model: "example-model", apiKey: "fixture" } },
+    { model: { main: "example/main", lite: "example/lite" } },
+    { model: "example/main", modelSmall: "example/small", smallModel: "example/small" },
+    {
+      provider: {
+        example: {
+          kind: "unsupported",
+          npm: "fixture",
+          models: { tiny: { limit: { context: "invalid" } } },
         },
         },
-        supportsReasoning: true,
-      });
-      expect(result.config.modelCatalog.overrides["openrouter-responses/ox-alpha"]).toEqual({
-        supportsReasoning: false,
-      });
-      expect(result.config.modelCatalog.overrides["openrouter-chat/GLM-X-PREVIEW-F"]).toEqual(
-        result.config.modelCatalog.overrides["openrouter-chat/vendor/ox-alpha-preview"],
-      );
-      expect(result.config.modelCatalog.overrides["openrouter-anthropic/gLm-X-pReViEw-F"]).toEqual(
-        result.config.modelCatalog.overrides["openrouter-anthropic/ox-alpha"],
-      );
-      expect(result.config.modelCatalog.overrides["openrouter-chat/X-pReViEw-F-fReE"]).toEqual(
-        result.config.modelCatalog.overrides["openrouter-chat/vendor/ox-alpha-preview"],
-      );
-      expect(result.config.modelCatalog.overrides["openrouter-anthropic/x-PrEvIeW-f-FrEe"]).toEqual(
-        result.config.modelCatalog.overrides["openrouter-anthropic/ox-alpha"],
-      );
-      expect(result.config.modelCatalog.overrides["openrouter-responses/GlM-x-PrEvIeW-f"]).toEqual(
-        result.config.modelCatalog.overrides["openrouter-responses/ox-alpha"],
-      );
-
-      const catalog = new ModelCatalogService({
-        modelsDev: false,
-        overrides: result.config.modelCatalog.overrides,
-      });
-      expect(catalog.getCapability("openrouter-responses", "ox-alpha")).toMatchObject({
-        reasoning: { enabled: false, levels: [] },
-        supportsReasoning: false,
-      });
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("rejects legacy small model config keys", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const smallModelPath = join(dir, "small-model.json");
-    const modelSmallPath = join(dir, "model-small.json");
-
-    try {
-      await writeFile(
-        smallModelPath,
-        JSON.stringify({
-          provider: {
-            openai: {
-              kind: "openai",
-            },
-          },
-          model: "openai/gpt-4o",
-          small_model: "openai/gpt-4o-mini",
-        }),
-      );
-      await writeFile(
-        modelSmallPath,
-        JSON.stringify({
-          provider: {
-            openai: {
-              kind: "openai",
-            },
-          },
-          model: {
-            main: "openai/gpt-4o",
-            small: "openai/gpt-4o-mini",
-          },
-        }),
-      );
-
-      expect(loadFileConfig(smallModelPath).loaded).toBe(false);
-      expect(loadFileConfig(modelSmallPath).loaded).toBe(false);
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("loads selectable models from multiple configured providers", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          provider: {
-            zai: {
-              kind: "openai-compatible",
-              name: "Z.AI",
-              options: {
-                baseURL: "https://api.z.ai/api/coding/v1",
-                apiKey: "zai-secret",
-              },
-              models: {
-                "glm-5.1": {
-                  name: "GLM-5.1",
-                },
-                "glm-4.7": {
-                  name: "GLM-4.7",
-                },
-              },
-            },
-            deepseek: {
-              kind: "openai-compatible",
-              name: "DeepSeek",
-              options: {
-                apiKey: "deepseek-secret",
-                baseURL: "https://api.deepseek.example",
-              },
-              models: {
-                "deepseek-v4-pro": {
-                  name: "DeepSeek V4 Pro",
-                },
-              },
-            },
-          },
-          model: "zai/glm-5.1",
-        }),
-      );
-
-      const result = loadFileConfig(path);
-
-      expect(result.loaded).toBe(true);
-      expect(
-        result.config.model?.available?.map((target) => `${target.provider}/${target.model}`),
-      ).toEqual(["zai/glm-5.1", "zai/glm-4.7", "deepseek/deepseek-v4-pro"]);
-      expect(
-        result.config.model?.available?.find((target) => target.provider === "deepseek"),
-      ).toMatchObject({
-        kind: "openai-compatible",
-        apiKey: "deepseek-secret",
-        baseURL: "https://api.deepseek.example",
-      });
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("rejects file config that fails the zod schema", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const path = join(dir, "config.json");
+      },
+    },
+    { modelCatalog: { overrides: { "example/model": { supportsReasoning: true } } } },
+  ])(
+    "ignores retired provider config while preserving active configuration: %j",
+    async (legacy) => {
+      const dir = await mkdtemp(join(tmpdir(), "zcode-config-retired-model-"));
+      try {
+        const path = join(dir, "config.json");
+        await writeFile(path, JSON.stringify({ ...legacy, features: { memory: false } }));
+        const result = loadFileConfig(path);
+        expect(result.loaded).toBe(true);
+        expect(result.config).toMatchObject({ features: { memory: false } });
+        for (const key of ["model", "provider", "modelCatalog", "modelSmall", "smallModel"])
+          expect(result.config).not.toHaveProperty(key);
+      } finally {
+        await rm(dir, { recursive: true, force: true });
+      }
+    },
+  );
 
 
+  it("rejects invalid active configuration", async () => {
+    const dir = await mkdtemp(join(tmpdir(), "zcode-config-invalid-"));
     try {
     try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          provider: {
-            local: {
-              models: {
-                tiny: {
-                  limit: {
-                    context: "large",
-                  },
-                },
-              },
-            },
-          },
-          model: "local/tiny",
-        }),
-      );
-
+      const path = join(dir, "config.json");
+      await writeFile(path, JSON.stringify({ network: { timeout: "invalid" } }));
       const result = loadFileConfig(path);
       const result = loadFileConfig(path);
-
       expect(result.loaded).toBe(false);
       expect(result.loaded).toBe(false);
       expect(result.config).toEqual({});
       expect(result.config).toEqual({});
     } finally {
     } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("rejects unsupported provider kinds and npm-based provider config", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const unsupportedKindPath = join(dir, "unsupported-kind.json");
-    const npmPath = join(dir, "npm-provider.json");
-
-    try {
-      await writeFile(
-        unsupportedKindPath,
-        JSON.stringify({
-          provider: {
-            local: {
-              kind: "gateway",
-              models: {
-                tiny: { name: "Tiny" },
-              },
-            },
-          },
-          model: "local/tiny",
-        }),
-      );
-      await writeFile(
-        npmPath,
-        JSON.stringify({
-          provider: {
-            local: {
-              npm: "@ai-sdk/openai-compatible",
-              models: {
-                tiny: { name: "Tiny" },
-              },
-            },
-          },
-          model: "local/tiny",
-        }),
-      );
-
-      expect(loadFileConfig(unsupportedKindPath).loaded).toBe(false);
-      expect(loadFileConfig(npmPath).loaded).toBe(false);
-    } finally {
-      await rm(dir, { force: true, recursive: true });
-    }
-  });
-
-  it("loads model catalog reasoning overrides from file config", async () => {
-    const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
-    const path = join(dir, "config.json");
-
-    try {
-      await writeFile(
-        path,
-        JSON.stringify({
-          modelCatalog: {
-            overrides: {
-              "openai/glm-4.7": {
-                supportsReasoning: true,
-                reasoning: {
-                  enabled: true,
-                  levels: ["low", "medium", "high"],
-                  defaultLevel: "medium",
-                  providerOptionsByLevel: {
-                    high: {
-                      reasoningEffort: "high",
-                    },
-                  },
-                },
-              },
-            },
-          },
-        }),
-      );
-
-      const result = loadFileConfig(path);
-
-      expect(result.loaded).toBe(true);
-      expect(result.config.modelCatalog?.overrides?.["openai/glm-4.7"]).toEqual({
-        supportsReasoning: true,
-        reasoning: {
-          enabled: true,
-          levels: ["low", "medium", "high"],
-          defaultLevel: "medium",
-          providerOptionsByLevel: {
-            high: {
-              reasoningEffort: "high",
-            },
-          },
-        },
-      });
-    } finally {
-      await rm(dir, { force: true, recursive: true });
+      await rm(dir, { recursive: true, force: true });
     }
     }
   });
   });
 
 

+ 6 - 0
apps/zcode-cli/packages/adapters/tests/connectivity-probe-wire.test.ts

@@ -34,6 +34,12 @@ describe("connectivity probe wire contract", () => {
           },
           },
         },
         },
         {
         {
+          requestSecurityState: {
+            createExecution: () => ({
+              protectTransport: ({ transport }) => transport,
+              take: () => [],
+            }),
+          },
           // 离线拦截所有请求,包含意外的鉴权/控制面请求;绝不回落真实账号网络。
           // 离线拦截所有请求,包含意外的鉴权/控制面请求;绝不回落真实账号网络。
           transport: async (input, init) => {
           transport: async (input, init) => {
             const request = new Request(input, init);
             const request = new Request(input, init);

+ 116 - 149
apps/zcode-cli/packages/adapters/tests/dwf-journal-store.test.ts

@@ -1,3 +1,8 @@
+import {
+  applySqliteSchemaMigration,
+  ensureSqliteSchemaMigrationTable,
+} from "@zcode/shared/sqlite-migrations";
+import { SQLITE_MIGRATIONS } from "../src/storage/session-store/migrations.js";
 /**
 /**
  * SQLite 版 JournalStorePort(dwf_* 表)的测试。
  * SQLite 版 JournalStorePort(dwf_* 表)的测试。
  *
  *
@@ -29,7 +34,11 @@ const openDatabases: DatabaseSync[] = [];
 function openJournalDb(dbPath = ":memory:"): { db: DatabaseSync; journal: JournalStorePort } {
 function openJournalDb(dbPath = ":memory:"): { db: DatabaseSync; journal: JournalStorePort } {
   const db = new DatabaseSync(dbPath);
   const db = new DatabaseSync(dbPath);
   openDatabases.push(db);
   openDatabases.push(db);
-  runSqliteSessionMigrations(db, dbPath);
+  // Journal 同步工厂只装载冻结 schema;异步启动、备份与锁由迁移专用测试验证。
+  db.exec("BEGIN IMMEDIATE");
+  ensureSqliteSchemaMigrationTable(db);
+  for (const migration of SQLITE_MIGRATIONS) applySqliteSchemaMigration(db, migration);
+  db.exec("COMMIT");
   return { db, journal: createDwfJournalStore(db) };
   return { db, journal: createDwfJournalStore(db) };
 }
 }
 
 
@@ -43,7 +52,6 @@ afterAll(() => {
   }
   }
 });
 });
 
 
-
 runJournalStoreContract(() => openJournalDb().journal);
 runJournalStoreContract(() => openJournalDb().journal);
 
 
 const CAPS: Caps = { maxConcurrency: 4 };
 const CAPS: Caps = { maxConcurrency: 4 };
@@ -90,7 +98,7 @@ describe("SQLite dwf journal store", () => {
     const dbPath = join(tempRoot, "session.sqlite");
     const dbPath = join(tempRoot, "session.sqlite");
 
 
     try {
     try {
-      const first = createSqliteSessionStore({ dbPath });
+      const first = await createSqliteSessionStore({ dbPath });
       const journal = first.workflowJournalStore();
       const journal = first.workflowJournalStore();
       journal.createRun(RUN);
       journal.createRun(RUN);
       journal.putActor(ACTOR);
       journal.putActor(ACTOR);
@@ -101,7 +109,7 @@ describe("SQLite dwf journal store", () => {
       journal.updateRunUsage(RUN.runId, 120);
       journal.updateRunUsage(RUN.runId, 120);
       first.close();
       first.close();
 
 
-      const second = createSqliteSessionStore({ dbPath });
+      const second = await createSqliteSessionStore({ dbPath });
       const resumed = second.workflowJournalStore();
       const resumed = second.workflowJournalStore();
 
 
       expect(resumed.getRun(RUN.runId)).toEqual({ ...RUN, spentTokens: 120 });
       expect(resumed.getRun(RUN.runId)).toEqual({ ...RUN, spentTokens: 120 });
@@ -116,7 +124,9 @@ describe("SQLite dwf journal store", () => {
       // 事件序号跨重开继续增长(engine-assigned、monotonic across resumes)。
       // 事件序号跨重开继续增长(engine-assigned、monotonic across resumes)。
       // 断言用 toMatchObject:追加还会带回写入时刻(StoredEvent.timeCreated),而这条用例
       // 断言用 toMatchObject:追加还会带回写入时刻(StoredEvent.timeCreated),而这条用例
       // 说的是序号,不是时钟——时钟由契约套件的 timeCreated 用例钉住。
       // 说的是序号,不是时钟——时钟由契约套件的 timeCreated 用例钉住。
-      expect(resumed.appendEvent(RUN.runId, { type: "log", message: "after resume" })).toMatchObject({
+      expect(
+        resumed.appendEvent(RUN.runId, { type: "log", message: "after resume" }),
+      ).toMatchObject({
         sequence: 2,
         sequence: 2,
         event: { type: "log", message: "after resume" },
         event: { type: "log", message: "after resume" },
       });
       });
@@ -139,7 +149,7 @@ describe("SQLite dwf journal store", () => {
     const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-journal-caps-"));
     const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-journal-caps-"));
     const dbPath = join(tempRoot, "session.sqlite");
     const dbPath = join(tempRoot, "session.sqlite");
     try {
     try {
-      const first = createSqliteSessionStore({ dbPath });
+      const first = await createSqliteSessionStore({ dbPath });
       const journal = first.workflowJournalStore();
       const journal = first.workflowJournalStore();
       journal.createRun(RUN);
       journal.createRun(RUN);
       journal.updateRunUsage(RUN.runId, 120);
       journal.updateRunUsage(RUN.runId, 120);
@@ -153,7 +163,7 @@ describe("SQLite dwf journal store", () => {
       });
       });
       first.close();
       first.close();
 
 
-      const second = createSqliteSessionStore({ dbPath });
+      const second = await createSqliteSessionStore({ dbPath });
       expect(second.workflowJournalStore().getRun(RUN.runId)?.caps).toEqual({ maxConcurrency: 2 });
       expect(second.workflowJournalStore().getRun(RUN.runId)?.caps).toEqual({ maxConcurrency: 2 });
       second.close();
       second.close();
     } finally {
     } finally {
@@ -161,7 +171,7 @@ describe("SQLite dwf journal store", () => {
     }
     }
   });
   });
 
 
-  it("cascades a run delete to its actors, nodes and events", () => {
+  it("cascades a run delete to its actors, nodes and events", async () => {
     const { db, journal } = openJournalDb();
     const { db, journal } = openJournalDb();
     journal.createRun(RUN);
     journal.createRun(RUN);
     journal.createRun({ ...RUN, runId: "dwf_run_2" });
     journal.createRun({ ...RUN, runId: "dwf_run_2" });
@@ -180,7 +190,7 @@ describe("SQLite dwf journal store", () => {
     expect(journal.listActors("dwf_run_2", { withPersona: true })).toHaveLength(1);
     expect(journal.listActors("dwf_run_2", { withPersona: true })).toHaveLength(1);
   });
   });
 
 
-  it("rejects an actor belonging to no run", () => {
+  it("rejects an actor belonging to no run", async () => {
     // FK 是开着的(migration runner 设 pragma foreign_keys = on),孤儿写入必须当场失败,
     // FK 是开着的(migration runner 设 pragma foreign_keys = on),孤儿写入必须当场失败,
     // 而不是留下一条永远读不回来的记录。孤儿事件与 null/absent result 的语义已由共享契约
     // 而不是留下一条永远读不回来的记录。孤儿事件与 null/absent result 的语义已由共享契约
     // 套件在两个实现上一起把关,这里只补 FK 本身确实生效这一点。
     // 套件在两个实现上一起把关,这里只补 FK 本身确实生效这一点。
@@ -188,23 +198,12 @@ describe("SQLite dwf journal store", () => {
     expect(() => journal.putActor({ ...ACTOR, runId: "ghost" })).toThrow();
     expect(() => journal.putActor({ ...ACTOR, runId: "ghost" })).toThrow();
   });
   });
 
 
-  // run 产物的列。内存实现表达不了「列存在」与「旧行解码」这两件事。
-  it("dwf_run 带 result_json 列", () => {
-    const { db } = openJournalDb();
-    const columns = (
-      db.prepare("select name from pragma_table_info('dwf_run')").all() as unknown as {
-        name: string;
-      }[]
-    ).map((row) => row.name);
-    expect(columns).toContain("result_json");
-  });
-
   it("run 产物跨重开数据库文件存活", async () => {
   it("run 产物跨重开数据库文件存活", async () => {
     const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-result-"));
     const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-result-"));
     const dbPath = join(tempRoot, "session.sqlite");
     const dbPath = join(tempRoot, "session.sqlite");
 
 
     try {
     try {
-      const first = createSqliteSessionStore({ dbPath });
+      const first = await createSqliteSessionStore({ dbPath });
       const journal = first.workflowJournalStore();
       const journal = first.workflowJournalStore();
       journal.createRun(RUN);
       journal.createRun(RUN);
       journal.updateRunStatus(RUN.runId, "completed", {
       journal.updateRunStatus(RUN.runId, "completed", {
@@ -213,7 +212,7 @@ describe("SQLite dwf journal store", () => {
       first.close();
       first.close();
 
 
       // 桌面实测 bug 的持久化面:进程一退,产物必须仍能从 journal 读回来。
       // 桌面实测 bug 的持久化面:进程一退,产物必须仍能从 journal 读回来。
-      const second = createSqliteSessionStore({ dbPath });
+      const second = await createSqliteSessionStore({ dbPath });
       const resumed = second.workflowJournalStore().getRun(RUN.runId);
       const resumed = second.workflowJournalStore().getRun(RUN.runId);
       expect(resumed?.status).toBe("completed");
       expect(resumed?.status).toBe("completed");
       expect(resumed?.result).toEqual({ report: "done", steps: [1, 2, 3] });
       expect(resumed?.result).toEqual({ report: "done", steps: [1, 2, 3] });
@@ -223,7 +222,7 @@ describe("SQLite dwf journal store", () => {
     }
     }
   });
   });
 
 
-  it("result_json 为 NULL 的旧行解码不炸且 result 缺席", () => {
+  it("result_json 为 NULL 的旧行解码不炸且 result 缺席", async () => {
     // 0020 之前落库的 run 行:列是新加的、值为 NULL。decodeRun 必须回一条没有 result 键的
     // 0020 之前落库的 run 行:列是新加的、值为 NULL。decodeRun 必须回一条没有 result 键的
     // 记录,而不是 undefined 值或抛错——否则升级后所有历史 run 都读不出来。
     // 记录,而不是 undefined 值或抛错——否则升级后所有历史 run 都读不出来。
     const { db, journal } = openJournalDb();
     const { db, journal } = openJournalDb();
@@ -235,18 +234,7 @@ describe("SQLite dwf journal store", () => {
     expect("result" in (record ?? {})).toBe(false);
     expect("result" in (record ?? {})).toBe(false);
   });
   });
 
 
-  // actor 的档位解析结果。同样是内存实现表达不了的两件事。
-  it("dwf_actor 带 resolved_model 列", () => {
-    const { db } = openJournalDb();
-    const columns = (
-      db.prepare("select name from pragma_table_info('dwf_actor')").all() as unknown as {
-        name: string;
-      }[]
-    ).map((row) => row.name);
-    expect(columns).toContain("resolved_model");
-  });
-
-  it("resolved_model 为 NULL 的旧行解码不炸且 resolvedModel 缺席", () => {
+  it("resolved_model 为 NULL 的旧行解码不炸且 resolvedModel 缺席", async () => {
     // 0023 之前落库的 actor 行(以及宿主还没解析过的行):必须解成没有 resolvedModel 键的
     // 0023 之前落库的 actor 行(以及宿主还没解析过的行):必须解成没有 resolvedModel 键的
     // 记录,而不是 undefined 值或抛错。persona 里的档位与这一列各自独立缺席。
     // 记录,而不是 undefined 值或抛错。persona 里的档位与这一列各自独立缺席。
     const { db, journal } = openJournalDb();
     const { db, journal } = openJournalDb();
@@ -261,7 +249,7 @@ describe("SQLite dwf journal store", () => {
     expect(record?.persona?.system).toBe("plan carefully");
     expect(record?.persona?.system).toBe("plan carefully");
   });
   });
 
 
-  it("同键重写只换 resolved_model,persona 与 session_id 原样保留", () => {
+  it("同键重写只换 resolved_model,persona 与 session_id 原样保留", async () => {
     // 生产里这正是 driver 侧 `journalActorResolvedModel` 的读改写形状:putActor 是整条替换,
     // 生产里这正是 driver 侧 `journalActorResolvedModel` 的读改写形状:putActor 是整条替换,
     // 所以「只更新解析结果」必须由调用方带齐其余字段,而存储层要如实照写。
     // 所以「只更新解析结果」必须由调用方带齐其余字段,而存储层要如实照写。
     const { journal } = openJournalDb();
     const { journal } = openJournalDb();
@@ -276,42 +264,20 @@ describe("SQLite dwf journal store", () => {
     expect(journal.listActors(RUN.runId, { withPersona: true })).toHaveLength(1);
     expect(journal.listActors(RUN.runId, { withPersona: true })).toHaveLength(1);
   });
   });
 
 
-  it("终态与产物一笔写:单条 UPDATE 同时落 status 与 result_json", () => {
+  it("终态与产物一笔写:单条 UPDATE 同时落 status 与 result_json", async () => {
     // 分两笔写会造出「completed 但产物丢失」的崩溃窗口,正是本列要关死的损失类别。
     // 分两笔写会造出「completed 但产物丢失」的崩溃窗口,正是本列要关死的损失类别。
     const { db, journal } = openJournalDb();
     const { db, journal } = openJournalDb();
     journal.createRun(RUN);
     journal.createRun(RUN);
     journal.updateRunStatus(RUN.runId, "completed", { result: "artifact text" });
     journal.updateRunStatus(RUN.runId, "completed", { result: "artifact text" });
 
 
-    const row = db.prepare("select status, result_json from dwf_run where id = ?").get(RUN.runId) as
-      | { result_json: string | null; status: string }
-      | undefined;
+    const row = db
+      .prepare("select status, result_json from dwf_run where id = ?")
+      .get(RUN.runId) as { result_json: string | null; status: string } | undefined;
     expect(row?.status).toBe("completed");
     expect(row?.status).toBe("completed");
     expect(row?.result_json).toBe(JSON.stringify("artifact text"));
     expect(row?.result_json).toBe(JSON.stringify("artifact text"));
   });
   });
 
 
-  // `kind` 的 CHECK 含 'report'——只有对着真库才能验,内存实现连 CHECK 都没有。
-  it("dwf_node 接受 kind:\"report\" 并原样回读", () => {
-    const { journal } = openJournalDb();
-    journal.createRun(RUN);
-    const report: NodeRecord = {
-      runId: RUN.runId,
-      siteId: "report#1",
-      ordinal: 1,
-      kind: "report",
-      inputHash: "h1",
-      status: "completed",
-      result: { finding: "两处重复实现", paths: ["src/a.ts", "src/b.ts"] },
-    };
-    journal.putNode(report);
-
-    // 整条 toEqual:actor 三列必须缺席地回来(report 没有 actor),status 恒为 completed。
-    expect(journal.getNode(RUN.runId, "report#1", 1)).toEqual(report);
-    const stored = journal.getNode(RUN.runId, "report#1", 1);
-    expect(stored !== undefined && "actorSeq" in stored).toBe(false);
-    expect(stored !== undefined && "actorSiteId" in stored).toBe(false);
-  });
-
-  it("CHECK 仍然拒绝一个不存在的 kind", () => {
+  it("CHECK 仍然拒绝一个不存在的 kind", async () => {
     // 重建 CHECK 的意义在于它**还在拦**:放开一个值不等于把闸门拆了。
     // 重建 CHECK 的意义在于它**还在拦**:放开一个值不等于把闸门拆了。
     const { journal } = openJournalDb();
     const { journal } = openJournalDb();
     journal.createRun(RUN);
     journal.createRun(RUN);
@@ -327,9 +293,8 @@ describe("SQLite dwf journal store", () => {
     ).toThrow();
     ).toThrow();
   });
   });
 
 
-
   // `kind` 的 CHECK 含 'world-run'(world.run 的 journal 化命令执行,docs/dynamic-workflow/authoring.md)。
   // `kind` 的 CHECK 含 'world-run'(world.run 的 journal 化命令执行,docs/dynamic-workflow/authoring.md)。
-  it("dwf_node 接受 kind:\"world-run\" 并原样回读", () => {
+  it('dwf_node 接受 kind:"world-run" 并原样回读', async () => {
     const { journal } = openJournalDb();
     const { journal } = openJournalDb();
     journal.createRun(RUN);
     journal.createRun(RUN);
     const worldRun: NodeRecord = {
     const worldRun: NodeRecord = {
@@ -345,7 +310,7 @@ describe("SQLite dwf journal store", () => {
     expect(journal.getNode(RUN.runId, "world-read#3", 2)).toEqual(worldRun);
     expect(journal.getNode(RUN.runId, "world-read#3", 2)).toEqual(worldRun);
   });
   });
 
 
-  it("dwf_node 带 input_json 列:有界输入原样回读,ask 行缺席", () => {
+  it("dwf_node 带 input_json 列:有界输入原样回读,ask 行缺席", async () => {
     // 工作区 transcript 的「what ran」(docs/dynamic-workflow/transcript-and-notifications.md)。
     // 工作区 transcript 的「what ran」(docs/dynamic-workflow/transcript-and-notifications.md)。
     const { db, journal } = openJournalDb();
     const { db, journal } = openJournalDb();
     journal.createRun(RUN);
     journal.createRun(RUN);
@@ -377,7 +342,7 @@ describe("SQLite dwf journal store", () => {
     expect(ask !== undefined && "input" in ask).toBe(false);
     expect(ask !== undefined && "input" in ask).toBe(false);
   });
   });
 
 
-  it("input_json 为 NULL 的旧行解码不炸且 input 缺席", () => {
+  it("input_json 为 NULL 的旧行解码不炸且 input 缺席", async () => {
     const { db, journal } = openJournalDb();
     const { db, journal } = openJournalDb();
     journal.createRun(RUN);
     journal.createRun(RUN);
     db.prepare(
     db.prepare(
@@ -390,7 +355,7 @@ describe("SQLite dwf journal store", () => {
     expect(row?.result).toBe("file body");
     expect(row?.result).toBe("file body");
   });
   });
 
 
-  it("listWorldNodes 只回 world-read / world-run 行,按落库先后,带时间戳与正文字节数、不带正文", () => {
+  it("listWorldNodes 只回 world-read / world-run 行,按落库先后,带时间戳与正文字节数、不带正文", async () => {
     const { journal } = openJournalDb();
     const { journal } = openJournalDb();
     const queries = journal as unknown as DwfRunIntrospectionQueries;
     const queries = journal as unknown as DwfRunIntrospectionQueries;
     journal.createRun(RUN);
     journal.createRun(RUN);
@@ -438,7 +403,7 @@ describe("SQLite dwf journal store", () => {
     expect(queries.listWorldNodes("dwfrun-unknown")).toEqual([]);
     expect(queries.listWorldNodes("dwfrun-unknown")).toEqual([]);
   });
   });
 
 
-  it("listWorldNodes 用 SQLite 的 JSON 函数在库内算摘要:数组计数、run 的 exitCode 与输出字节数", () => {
+  it("listWorldNodes 用 SQLite 的 JSON 函数在库内算摘要:数组计数、run 的 exitCode 与输出字节数", async () => {
     const { journal } = openJournalDb();
     const { journal } = openJournalDb();
     const queries = journal as unknown as DwfRunIntrospectionQueries;
     const queries = journal as unknown as DwfRunIntrospectionQueries;
     journal.createRun(RUN);
     journal.createRun(RUN);
@@ -493,16 +458,17 @@ describe("SQLite dwf journal store", () => {
     expect("resultCount" in rows[2]!).toBe(false);
     expect("resultCount" in rows[2]!).toBe(false);
     expect("exitCode" in rows[2]!).toBe(false);
     expect("exitCode" in rows[2]!).toBe(false);
     // 失败行没有正文:什么摘要都没有,只有 error。
     // 失败行没有正文:什么摘要都没有,只有 error。
-    expect(rows[3]).toMatchObject({ status: "failed", error: { code: "DriverError", message: "boom" } });
+    expect(rows[3]).toMatchObject({
+      status: "failed",
+      error: { code: "DriverError", message: "boom" },
+    });
     expect("resultBytes" in rows[3]!).toBe(false);
     expect("resultBytes" in rows[3]!).toBe(false);
     expect("exitCode" in rows[3]!).toBe(false);
     expect("exitCode" in rows[3]!).toBe(false);
   });
   });
 
 
-
-
   // dwf_event 上的表达式索引不只要存在,还得**真的被用上**:它存在的全部理由是让看板取数
   // dwf_event 上的表达式索引不只要存在,还得**真的被用上**:它存在的全部理由是让看板取数
   // 不必扫完一条长 run 的整张事件表(那是最大的一张表)。查询计划变了这里就会响。
   // 不必扫完一条长 run 的整张事件表(那是最大的一张表)。查询计划变了这里就会响。
-  it("dwf_event 的表达式索引真的服务于按 artifactId 取事件", () => {
+  it("dwf_event 的表达式索引真的服务于按 artifactId 取事件", async () => {
     const { db } = openJournalDb();
     const { db } = openJournalDb();
     const plan = (
     const plan = (
       db
       db
@@ -558,7 +524,7 @@ describe("SQLite dwf journal store — listNonTerminalRuns", () => {
     });
     });
   }
   }
 
 
-  it("只回本父会话的非终态行", () => {
+  it("只回本父会话的非终态行", async () => {
     const journal = openSweepableJournal();
     const journal = openSweepableJournal();
     seed(journal, { parentSessionId: PARENT, runId: "run_running", status: "running" });
     seed(journal, { parentSessionId: PARENT, runId: "run_running", status: "running" });
     seed(journal, { parentSessionId: PARENT, runId: "run_pending", status: "pending" });
     seed(journal, { parentSessionId: PARENT, runId: "run_pending", status: "pending" });
@@ -577,7 +543,7 @@ describe("SQLite dwf journal store — listNonTerminalRuns", () => {
     expect(rows.find((row) => row.runId === "run_running")?.status).toBe("running");
     expect(rows.find((row) => row.runId === "run_running")?.status).toBe("running");
   });
   });
 
 
-  it("收敛写入之后同一个查询返回空(幂等的 SQL 侧依据)", () => {
+  it("收敛写入之后同一个查询返回空(幂等的 SQL 侧依据)", async () => {
     const journal = openSweepableJournal();
     const journal = openSweepableJournal();
     seed(journal, { parentSessionId: PARENT, runId: "run_orphan", status: "running" });
     seed(journal, { parentSessionId: PARENT, runId: "run_orphan", status: "running" });
 
 
@@ -589,7 +555,7 @@ describe("SQLite dwf journal store — listNonTerminalRuns", () => {
     expect(journal.listNonTerminalRuns(PARENT)).toEqual([]);
     expect(journal.listNonTerminalRuns(PARENT)).toEqual([]);
   });
   });
 
 
-  it("未知父会话返回空数组", () => {
+  it("未知父会话返回空数组", async () => {
     const journal = openSweepableJournal();
     const journal = openSweepableJournal();
     seed(journal, { parentSessionId: PARENT, runId: "run_running", status: "running" });
     seed(journal, { parentSessionId: PARENT, runId: "run_running", status: "running" });
 
 
@@ -670,7 +636,7 @@ function seedRun(
 }
 }
 
 
 describe("SQLite dwf journal store — dwf_run.name 与 cwd 索引", () => {
 describe("SQLite dwf journal store — dwf_run.name 与 cwd 索引", () => {
-  it("dwf_run 带 name 列,且 dwf_run_cwd_idx 的形状正对枚举查询", () => {
+  it("dwf_run 带 name 列,且 dwf_run_cwd_idx 的形状正对枚举查询", async () => {
     const { db } = openJournalDb();
     const { db } = openJournalDb();
     const columns = (
     const columns = (
       db.prepare("select name from pragma_table_info('dwf_run')").all() as unknown as {
       db.prepare("select name from pragma_table_info('dwf_run')").all() as unknown as {
@@ -688,7 +654,7 @@ describe("SQLite dwf journal store — dwf_run.name 与 cwd 索引", () => {
     expect(indexed).toEqual(["cwd", "time_updated"]);
     expect(indexed).toEqual(["cwd", "time_updated"]);
   });
   });
 
 
-  it("name 为 NULL 的旧行解码不炸且 name 缺席", () => {
+  it("name 为 NULL 的旧行解码不炸且 name 缺席", async () => {
     // 0021 之前落库的 run 行:列是新加的、值为 NULL(不做回填)。decodeRun 必须回一条没有
     // 0021 之前落库的 run 行:列是新加的、值为 NULL(不做回填)。decodeRun 必须回一条没有
     // name 键的记录,否则升级后所有历史 run 都读不出来。
     // name 键的记录,否则升级后所有历史 run 都读不出来。
     const { db, journal } = openJournalDb();
     const { db, journal } = openJournalDb();
@@ -699,25 +665,12 @@ describe("SQLite dwf journal store — dwf_run.name 与 cwd 索引", () => {
     expect(record).toEqual(RUN);
     expect(record).toEqual(RUN);
     expect("name" in (record ?? {})).toBe(false);
     expect("name" in (record ?? {})).toBe(false);
   });
   });
-
-  it("updateRunStatus 不改写 name 列", () => {
-    // name 只在 createRun 那一刻写入(引擎独占的元数据路)。结算语句若把 name 也列进去,
-    // run 一结算就会丢名字。
-    const { db, journal } = openJournalDb();
-    journal.createRun({ ...RUN, name: "triage the flake" });
-    journal.updateRunStatus(RUN.runId, "completed", { result: "ok" });
-
-    const row = db.prepare("select name from dwf_run where id = ?").get(RUN.runId) as
-      | { name: string | null }
-      | undefined;
-    expect(row?.name).toBe("triage the flake");
-  });
 });
 });
 
 
 describe("SQLite dwf journal store — 基线形状", () => {
 describe("SQLite dwf journal store — 基线形状", () => {
   // docs/dynamic-workflow/authoring.md:预算构造整体移除。基线 0019 直接以终态建表,这里钉住
   // docs/dynamic-workflow/authoring.md:预算构造整体移除。基线 0019 直接以终态建表,这里钉住
   // 「两列不存在、用量列叫 spent_tokens」,以及老形状的 run 记录经 store 读回时 caps 只剩 maxConcurrency。
   // 「两列不存在、用量列叫 spent_tokens」,以及老形状的 run 记录经 store 读回时 caps 只剩 maxConcurrency。
-  it("dwf_run 没有节点上限 / 预算列,用量列叫 spent_tokens", () => {
+  it("dwf_run 没有节点上限 / 预算列,用量列叫 spent_tokens", async () => {
     const { db } = openJournalDb();
     const { db } = openJournalDb();
     const columns = (db.prepare("pragma table_info(dwf_run)").all() as Array<{ name: string }>).map(
     const columns = (db.prepare("pragma table_info(dwf_run)").all() as Array<{ name: string }>).map(
       (c) => c.name,
       (c) => c.name,
@@ -744,7 +697,7 @@ describe("SQLite dwf journal store — 基线形状", () => {
 describe("SQLite dwf journal store — listRuns", () => {
 describe("SQLite dwf journal store — listRuns", () => {
   const CWD = "/repo/project";
   const CWD = "/repo/project";
 
 
-  it("只回本 cwd 的 run,按 time_updated 倒序", () => {
+  it("只回本 cwd 的 run,按 time_updated 倒序", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_old", cwd: CWD, timeUpdated: 1_000 });
     seedRun(db, journal, { runId: "run_old", cwd: CWD, timeUpdated: 1_000 });
     seedRun(db, journal, { runId: "run_new", cwd: CWD, timeUpdated: 3_000 });
     seedRun(db, journal, { runId: "run_new", cwd: CWD, timeUpdated: 3_000 });
@@ -757,7 +710,7 @@ describe("SQLite dwf journal store — listRuns", () => {
     expect(rows.map((row) => row.runId)).toEqual(["run_new", "run_mid", "run_old"]);
     expect(rows.map((row) => row.runId)).toEqual(["run_new", "run_mid", "run_old"]);
   });
   });
 
 
-  it("cwd 是字面匹配,不做路径规范化", () => {
+  it("cwd 是字面匹配,不做路径规范化", async () => {
     // 与 submit 写入同源(context.workingDirectory 原样落库、原样查询)。在读侧单方面
     // 与 submit 写入同源(context.workingDirectory 原样落库、原样查询)。在读侧单方面
     // 规范化只会造出单侧不匹配。
     // 规范化只会造出单侧不匹配。
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
@@ -767,7 +720,7 @@ describe("SQLite dwf journal store — listRuns", () => {
     expect(journal.listRuns({ cwd: CWD, limit: 20 })).toHaveLength(1);
     expect(journal.listRuns({ cwd: CWD, limit: 20 })).toHaveLength(1);
   });
   });
 
 
-  it("limit 只截最新的那几条", () => {
+  it("limit 只截最新的那几条", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     for (let i = 0; i < 5; i++) {
     for (let i = 0; i < 5; i++) {
       seedRun(db, journal, { runId: `run_${i}`, cwd: CWD, timeUpdated: 1_000 + i });
       seedRun(db, journal, { runId: `run_${i}`, cwd: CWD, timeUpdated: 1_000 + i });
@@ -782,7 +735,7 @@ describe("SQLite dwf journal store — listRuns", () => {
     expect(journal.listRuns({ cwd: CWD, limit: 0 })).toEqual([]);
     expect(journal.listRuns({ cwd: CWD, limit: 0 })).toEqual([]);
   });
   });
 
 
-  it("statuses 过滤到给定子集", () => {
+  it("statuses 过滤到给定子集", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_running", cwd: CWD, status: "running" });
     seedRun(db, journal, { runId: "run_running", cwd: CWD, status: "running" });
     seedRun(db, journal, { runId: "run_pending", cwd: CWD, status: "pending" });
     seedRun(db, journal, { runId: "run_pending", cwd: CWD, status: "pending" });
@@ -800,7 +753,7 @@ describe("SQLite dwf journal store — listRuns", () => {
     expect(journal.listRuns({ cwd: CWD, limit: 20, statuses: [] })).toEqual([]);
     expect(journal.listRuns({ cwd: CWD, limit: 20, statuses: [] })).toEqual([]);
   });
   });
 
 
-  it("name 过滤下推到 SQL,且与 statuses 可叠加(GUI 中枢按工作流名归属运行历史)", () => {
+  it("name 过滤下推到 SQL,且与 statuses 可叠加(GUI 中枢按工作流名归属运行历史)", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_a1", cwd: CWD, name: "release-check", timeUpdated: 3 });
     seedRun(db, journal, { runId: "run_a1", cwd: CWD, name: "release-check", timeUpdated: 3 });
     seedRun(db, journal, { runId: "run_a2", cwd: CWD, name: "release-check", timeUpdated: 1 });
     seedRun(db, journal, { runId: "run_a2", cwd: CWD, name: "release-check", timeUpdated: 1 });
@@ -828,13 +781,23 @@ describe("SQLite dwf journal store — listRuns", () => {
     expect(journal.listRuns({ cwd: CWD, limit: 20 })).toHaveLength(5);
     expect(journal.listRuns({ cwd: CWD, limit: 20 })).toHaveLength(5);
   });
   });
 
 
-  it("cwd 缺省即跨所有项目枚举(全局工作流的运行历史跨 cwd),行带 cwd", () => {
+  it("cwd 缺省即跨所有项目枚举(全局工作流的运行历史跨 cwd),行带 cwd", async () => {
     // 全局工作流在不同项目里被发起,dwf_run.cwd 记的是各自实际运行的项目。`workflows/runs`
     // 全局工作流在不同项目里被发起,dwf_run.cwd 记的是各自实际运行的项目。`workflows/runs`
     // 的全局变体不按 cwd 过滤,把该名字在所有项目里的历史一并取出,行带 cwd 供 GUI 标项目
     // 的全局变体不按 cwd 过滤,把该名字在所有项目里的历史一并取出,行带 cwd 供 GUI 标项目
     // (docs/dynamic-workflow/launch.md「Data path」)。
     // (docs/dynamic-workflow/launch.md「Data path」)。
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
-    seedRun(db, journal, { runId: "run_a", cwd: "/repo/one", name: "deep-research", timeUpdated: 3 });
-    seedRun(db, journal, { runId: "run_b", cwd: "/repo/two", name: "deep-research", timeUpdated: 2 });
+    seedRun(db, journal, {
+      runId: "run_a",
+      cwd: "/repo/one",
+      name: "deep-research",
+      timeUpdated: 3,
+    });
+    seedRun(db, journal, {
+      runId: "run_b",
+      cwd: "/repo/two",
+      name: "deep-research",
+      timeUpdated: 2,
+    });
     seedRun(db, journal, { runId: "run_c", cwd: "/repo/one", name: "other", timeUpdated: 5 });
     seedRun(db, journal, { runId: "run_c", cwd: "/repo/one", name: "other", timeUpdated: 5 });
     seedRun(db, journal, { runId: "run_cwdless", name: "deep-research", timeUpdated: 1 });
     seedRun(db, journal, { runId: "run_cwdless", name: "deep-research", timeUpdated: 1 });
 
 
@@ -845,15 +808,17 @@ describe("SQLite dwf journal store — listRuns", () => {
     expect(byId.get("run_a")?.cwd).toBe("/repo/one");
     expect(byId.get("run_a")?.cwd).toBe("/repo/one");
     expect(byId.get("run_b")?.cwd).toBe("/repo/two");
     expect(byId.get("run_b")?.cwd).toBe("/repo/two");
     // cwd 为 NULL 的行不带 cwd 键(新列不回填,缺席可分辨)。
     // cwd 为 NULL 的行不带 cwd 键(新列不回填,缺席可分辨)。
-    expect(byId.get("run_cwdless") !== undefined && "cwd" in (byId.get("run_cwdless") ?? {})).toBe(false);
+    expect(byId.get("run_cwdless") !== undefined && "cwd" in (byId.get("run_cwdless") ?? {})).toBe(
+      false,
+    );
 
 
     // 给了 cwd 就仍只回本项目那份(与全局变体互斥,行为逐字不变)。
     // 给了 cwd 就仍只回本项目那份(与全局变体互斥,行为逐字不变)。
-    expect(journal.listRuns({ cwd: "/repo/one", limit: 20, name: "deep-research" }).map((r) => r.runId)).toEqual([
-      "run_a",
-    ]);
+    expect(
+      journal.listRuns({ cwd: "/repo/one", limit: 20, name: "deep-research" }).map((r) => r.runId),
+    ).toEqual(["run_a"]);
   });
   });
 
 
-  it("枚举行带 args(实参是小 JSON 袋,中枢的运行历史要展示它);无实参的行键缺席", () => {
+  it("枚举行带 args(实参是小 JSON 袋,中枢的运行历史要展示它);无实参的行键缺席", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, {
     seedRun(db, journal, {
       runId: "run_args",
       runId: "run_args",
@@ -868,12 +833,12 @@ describe("SQLite dwf journal store — listRuns", () => {
     expect(byId.get("run_bare")).not.toHaveProperty("args");
     expect(byId.get("run_bare")).not.toHaveProperty("args");
   });
   });
 
 
-  it("空结果回空数组", () => {
+  it("空结果回空数组", async () => {
     const { journal } = openIntrospectableJournal();
     const { journal } = openIntrospectableJournal();
     expect(journal.listRuns({ cwd: "/never/seen", limit: 20 })).toEqual([]);
     expect(journal.listRuns({ cwd: "/never/seen", limit: 20 })).toEqual([]);
   });
   });
 
 
-  it("每行带齐下游合成真相所需的字段,但不驮 result/failure", () => {
+  it("每行带齐下游合成真相所需的字段,但不驮 result/failure", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, {
     seedRun(db, journal, {
       runId: "run_1",
       runId: "run_1",
@@ -906,7 +871,7 @@ describe("SQLite dwf journal store — listRuns", () => {
     expect(row !== undefined && "failure" in row).toBe(false);
     expect(row !== undefined && "failure" in row).toBe(false);
   });
   });
 
 
-  it("name 缺席的行不带 name 键", () => {
+  it("name 缺席的行不带 name 键", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: CWD, scriptText: "log('hi');" });
     seedRun(db, journal, { runId: "run_1", cwd: CWD, scriptText: "log('hi');" });
 
 
@@ -916,7 +881,7 @@ describe("SQLite dwf journal store — listRuns", () => {
 });
 });
 
 
 describe("SQLite dwf journal store — getRunRow", () => {
 describe("SQLite dwf journal store — getRunRow", () => {
-  it("回完整记录 + journal 时间戳", () => {
+  it("回完整记录 + journal 时间戳", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, {
     seedRun(db, journal, {
       runId: "run_1",
       runId: "run_1",
@@ -939,7 +904,7 @@ describe("SQLite dwf journal store — getRunRow", () => {
     expect(typeof row?.timeCreated).toBe("number");
     expect(typeof row?.timeCreated).toBe("number");
   });
   });
 
 
-  it("未知 runId 回 undefined", () => {
+  it("未知 runId 回 undefined", async () => {
     const { journal } = openIntrospectableJournal();
     const { journal } = openIntrospectableJournal();
     expect(journal.getRunRow("nope")).toBeUndefined();
     expect(journal.getRunRow("nope")).toBeUndefined();
   });
   });
@@ -957,7 +922,7 @@ describe("SQLite dwf journal store — countNodesByStatus", () => {
     journal.putNode({ runId, siteId, ordinal, kind: "ask", inputHash: "h", status });
     journal.putNode({ runId, siteId, ordinal, kind: "ask", inputHash: "h", status });
   }
   }
 
 
-  it("按三态计数,且只数本 run 的节点", () => {
+  it("按三态计数,且只数本 run 的节点", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
@@ -970,7 +935,7 @@ describe("SQLite dwf journal store — countNodesByStatus", () => {
     expect(journal.countNodesByStatus("run_1")).toEqual({ running: 1, completed: 2, failed: 1 });
     expect(journal.countNodesByStatus("run_1")).toEqual({ running: 1, completed: 2, failed: 1 });
   });
   });
 
 
-  it("无节点(含未知 run)回三个 0,而不是缺键", () => {
+  it("无节点(含未知 run)回三个 0,而不是缺键", async () => {
     // 下游要拿它直接算 nodesObserved;缺键会让「还没有节点」和「没有这个 run」都变成 NaN。
     // 下游要拿它直接算 nodesObserved;缺键会让「还没有节点」和「没有这个 run」都变成 NaN。
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
@@ -981,7 +946,7 @@ describe("SQLite dwf journal store — countNodesByStatus", () => {
 });
 });
 
 
 describe("SQLite dwf journal store — listRecentLogEvents", () => {
 describe("SQLite dwf journal store — listRecentLogEvents", () => {
-  it("只取 log 事件的末 N 条,按时序回", () => {
+  it("只取 log 事件的末 N 条,按时序回", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     journal.appendEvent("run_1", { type: "run-started", runId: "run_1", caps: CAPS });
     journal.appendEvent("run_1", { type: "run-started", runId: "run_1", caps: CAPS });
@@ -1003,7 +968,7 @@ describe("SQLite dwf journal store — listRecentLogEvents", () => {
     expect(tail.map((e) => e.sequence)).toEqual([3, 5, 7]);
     expect(tail.map((e) => e.sequence)).toEqual([3, 5, 7]);
   });
   });
 
 
-  it("limit 超过条数时给出全部 log 事件", () => {
+  it("limit 超过条数时给出全部 log 事件", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     journal.appendEvent("run_1", { type: "log", message: "only" });
     journal.appendEvent("run_1", { type: "log", message: "only" });
@@ -1012,7 +977,7 @@ describe("SQLite dwf journal store — listRecentLogEvents", () => {
     expect(journal.listRecentLogEvents("run_1", 20).map((e) => e.event.type)).toEqual(["log"]);
     expect(journal.listRecentLogEvents("run_1", 20).map((e) => e.event.type)).toEqual(["log"]);
   });
   });
 
 
-  it("没有 log 事件(含未知 run、limit 0)回空数组", () => {
+  it("没有 log 事件(含未知 run、limit 0)回空数组", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     journal.appendEvent("run_1", { type: "run-started", runId: "run_1", caps: CAPS });
     journal.appendEvent("run_1", { type: "run-started", runId: "run_1", caps: CAPS });
@@ -1022,7 +987,7 @@ describe("SQLite dwf journal store — listRecentLogEvents", () => {
     expect(journal.listRecentLogEvents("run_1", 0)).toEqual([]);
     expect(journal.listRecentLogEvents("run_1", 0)).toEqual([]);
   });
   });
 
 
-  it("按 runId 隔离", () => {
+  it("按 runId 隔离", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
@@ -1076,7 +1041,7 @@ describe("SQLite dwf journal store — listRunsByParentSession", () => {
     });
     });
   }
   }
 
 
-  it("只回本父会话的行,完整解码(含 toolCallId 与 failure)", () => {
+  it("只回本父会话的行,完整解码(含 toolCallId 与 failure)", async () => {
     const journal = openEnumerableJournal();
     const journal = openEnumerableJournal();
     seed(journal, {
     seed(journal, {
       parentSessionId: PARENT,
       parentSessionId: PARENT,
@@ -1122,7 +1087,7 @@ describe("SQLite dwf journal store — listRunsByParentSession", () => {
     expect(rows[0]?.runId).toBe("run_old"); // 刚被触碰过 → 最近更新
     expect(rows[0]?.runId).toBe("run_old"); // 刚被触碰过 → 最近更新
   });
   });
 
 
-  it("未知父会话返回空数组;limit 0 返回空", () => {
+  it("未知父会话返回空数组;limit 0 返回空", async () => {
     const journal = openEnumerableJournal();
     const journal = openEnumerableJournal();
     seed(journal, { parentSessionId: PARENT, runId: "run_a", status: "running" });
     seed(journal, { parentSessionId: PARENT, runId: "run_a", status: "running" });
     expect(journal.listRunsByParentSession("ses_never_seen", 10)).toEqual([]);
     expect(journal.listRunsByParentSession("ses_never_seen", 10)).toEqual([]);
@@ -1130,7 +1095,7 @@ describe("SQLite dwf journal store — listRunsByParentSession", () => {
   });
   });
 
 
   // 窄投影:枚举面报 updatedAt,所以行必须带 journal 时间戳(`RunRecord` 自己不带时间)。
   // 窄投影:枚举面报 updatedAt,所以行必须带 journal 时间戳(`RunRecord` 自己不带时间)。
-  it("行带 journal 时间戳(createdAt/updatedAt 的来源)", () => {
+  it("行带 journal 时间戳(createdAt/updatedAt 的来源)", async () => {
     const journal = openEnumerableJournal();
     const journal = openEnumerableJournal();
     seed(journal, { parentSessionId: PARENT, runId: "run_timed", status: "running" });
     seed(journal, { parentSessionId: PARENT, runId: "run_timed", status: "running" });
 
 
@@ -1152,10 +1117,10 @@ describe("SQLite dwf journal store — listRunsByParentSession", () => {
    *
    *
    * 反过来 `failure_json` 必须在 SQL 里:resumable 的谓词依赖 failure.code(见下一个用例)。
    * 反过来 `failure_json` 必须在 SQL 里:resumable 的谓词依赖 failure.code(见下一个用例)。
    */
    */
-  it("枚举查询的 SQL 取 failure_json 而不取 result_json", () => {
+  it("枚举查询的 SQL 取 failure_json 而不取 result_json", async () => {
     const db = new DatabaseSync(":memory:");
     const db = new DatabaseSync(":memory:");
     openDatabases.push(db);
     openDatabases.push(db);
-    runSqliteSessionMigrations(db, ":memory:");
+    await runSqliteSessionMigrations(db, ":memory:");
     const prepared: string[] = [];
     const prepared: string[] = [];
     // prepare 的旁路记录器:只为了看见这条查询真正发出的列清单。
     // prepare 的旁路记录器:只为了看见这条查询真正发出的列清单。
     const recordingDb = new Proxy(db, {
     const recordingDb = new Proxy(db, {
@@ -1184,7 +1149,7 @@ describe("SQLite dwf journal store — listRunsByParentSession", () => {
   });
   });
 
 
   /** failure 必须活过窄投影:Interrupted 是 resume 门认可的可恢复形态。 */
   /** failure 必须活过窄投影:Interrupted 是 resume 门认可的可恢复形态。 */
-  it("窄投影仍解出 failure(resumable 谓词的输入)", () => {
+  it("窄投影仍解出 failure(resumable 谓词的输入)", async () => {
     const journal = openEnumerableJournal();
     const journal = openEnumerableJournal();
     seed(journal, { parentSessionId: PARENT, runId: "run_dead", status: "running" });
     seed(journal, { parentSessionId: PARENT, runId: "run_dead", status: "running" });
     journal.updateRunStatus("run_dead", "stopped", {
     journal.updateRunStatus("run_dead", "stopped", {
@@ -1230,7 +1195,7 @@ describe("SQLite dwf journal store — listArtifactRows", () => {
     });
     });
   }
   }
 
 
-  it("只回本 run 的产物行,按落库先后", () => {
+  it("只回本 run 的产物行,按落库先后", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
@@ -1288,7 +1253,7 @@ describe("SQLite dwf journal store — listArtifactRows", () => {
     expect(rows[2]?.result).toEqual({ id: "book", kind: "file", version: 2, bytes: 20 });
     expect(rows[2]?.result).toEqual({ id: "book", kind: "file", version: 2, bytes: 20 });
   });
   });
 
 
-  it("失败的发布照样在结果里(带 error、无 result)", () => {
+  it("失败的发布照样在结果里(带 error、无 result)", async () => {
     // 筛掉失败行等于让一个用户可见的失败在每张表面上都不存在。
     // 筛掉失败行等于让一个用户可见的失败在每张表面上都不存在。
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
@@ -1301,7 +1266,7 @@ describe("SQLite dwf journal store — listArtifactRows", () => {
     expect(row !== undefined && "result" in row).toBe(false);
     expect(row !== undefined && "result" in row).toBe(false);
   });
   });
 
 
-  it("无产物(含未知 run)回空数组", () => {
+  it("无产物(含未知 run)回空数组", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     expect(journal.listArtifactRows("run_1")).toEqual([]);
     expect(journal.listArtifactRows("run_1")).toEqual([]);
@@ -1310,7 +1275,7 @@ describe("SQLite dwf journal store — listArtifactRows", () => {
 });
 });
 
 
 describe("SQLite dwf journal store — countTaggedReports", () => {
 describe("SQLite dwf journal store — countTaggedReports", () => {
-  it("counts tagged report rows per artifact id in SQL, ignoring untagged rows, other kinds and other runs", () => {
+  it("counts tagged report rows per artifact id in SQL, ignoring untagged rows, other kinds and other runs", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
@@ -1368,7 +1333,7 @@ describe("SQLite dwf journal store — listArtifactItems", () => {
     }).sequence;
     }).sequence;
   }
   }
 
 
-  it("按 sequence 升序回该 id 的条目,带站点坐标与原值", () => {
+  it("按 sequence 升序回该 id 的条目,带站点坐标与原值", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     const s0 = seedTaggedReport(journal, "run_1", "report#1", 1, { round: 1 }, "perf");
     const s0 = seedTaggedReport(journal, "run_1", "report#1", 1, { round: 1 }, "perf");
@@ -1383,7 +1348,7 @@ describe("SQLite dwf journal store — listArtifactItems", () => {
     });
     });
   });
   });
 
 
-  it("排除未打标签的 report、别的 id、别种事件与别的 run", () => {
+  it("排除未打标签的 report、别的 id、别种事件与别的 run", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
@@ -1406,7 +1371,7 @@ describe("SQLite dwf journal store — listArtifactItems", () => {
     expect(page.hasMore).toBe(false);
     expect(page.hasMore).toBe(false);
   });
   });
 
 
-  it("afterSequence 是严格大于的游标", () => {
+  it("afterSequence 是严格大于的游标", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     const s0 = seedTaggedReport(journal, "run_1", "report#1", 1, 1, "perf");
     const s0 = seedTaggedReport(journal, "run_1", "report#1", 1, 1, "perf");
@@ -1420,7 +1385,7 @@ describe("SQLite dwf journal store — listArtifactItems", () => {
     expect(after(s1)).toEqual({ items: [], hasMore: false });
     expect(after(s1)).toEqual({ items: [], hasMore: false });
   });
   });
 
 
-  it("limit 逐字兑现,hasMore 由存储层判定:页之后还有没有条目", () => {
+  it("limit 逐字兑现,hasMore 由存储层判定:页之后还有没有条目", async () => {
     // 存储层不加自己的天花板,也不要调用方多取一条来猜:页尾后面那一行存在与否就是 hasMore。
     // 存储层不加自己的天花板,也不要调用方多取一条来猜:页尾后面那一行存在与否就是 hasMore。
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
@@ -1439,7 +1404,7 @@ describe("SQLite dwf journal store — listArtifactItems", () => {
     expect(page(99).items).toHaveLength(5);
     expect(page(99).items).toHaveLength(5);
   });
   });
 
 
-  it("字节界:再加一条就超界时收尾并报 hasMore,第一条总是带上", () => {
+  it("字节界:再加一条就超界时收尾并报 hasMore,第一条总是带上", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     const pad = "x".repeat(1000);
     const pad = "x".repeat(1000);
@@ -1464,7 +1429,7 @@ describe("SQLite dwf journal store — listArtifactItems", () => {
     expect(tiny.hasMore).toBe(true);
     expect(tiny.hasMore).toBe(true);
   });
   });
 
 
-  it("limit ≤ 0 是空页,未知 run / 未知 id 同样", () => {
+  it("limit ≤ 0 是空页,未知 run / 未知 id 同样", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedTaggedReport(journal, "run_1", "report#1", 1, { round: 1 }, "perf");
     seedTaggedReport(journal, "run_1", "report#1", 1, { round: 1 }, "perf");
@@ -1484,7 +1449,7 @@ describe("SQLite dwf journal store — listArtifactItems", () => {
     );
     );
   });
   });
 
 
-  it("条目原值原样回来:null、标量与数组都不被加工", () => {
+  it("条目原值原样回来:null、标量与数组都不被加工", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedTaggedReport(journal, "run_1", "report#1", 1, null, "perf");
     seedTaggedReport(journal, "run_1", "report#1", 1, null, "perf");
@@ -1523,7 +1488,7 @@ describe("SQLite dwf journal store — listArtifactItems with fields", () => {
     });
     });
   }
   }
 
 
-  it("回点名的字段、不回整条 item;JSON 的 null 在表里,走不通的路径不在", () => {
+  it("回点名的字段、不回整条 item;JSON 的 null 在表里,走不通的路径不在", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seed(journal, "run_1", [
     seed(journal, "run_1", [
@@ -1550,7 +1515,7 @@ describe("SQLite dwf journal store — listArtifactItems with fields", () => {
     expect(page.items[0]).not.toHaveProperty("item");
     expect(page.items[0]).not.toHaveProperty("item");
   });
   });
 
 
-  it("像整数的段在数组上是下标、在对象上是键,与渲染器的路径规则相同", () => {
+  it("像整数的段在数组上是下标、在对象上是键,与渲染器的路径规则相同", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seed(journal, "run_1", [
     seed(journal, "run_1", [
@@ -1579,7 +1544,7 @@ describe("SQLite dwf journal store — listArtifactItems with fields", () => {
     });
     });
   });
   });
 
 
-  it("键里带引号与反斜杠照样取得到", () => {
+  it("键里带引号与反斜杠照样取得到", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seed(journal, "run_1", [{ 'say"hi': 1, "back\\slash": 2, 中文: 3 }]);
     seed(journal, "run_1", [{ 'say"hi': 1, "back\\slash": 2, 中文: 3 }]);
@@ -1588,7 +1553,7 @@ describe("SQLite dwf journal store — listArtifactItems with fields", () => {
     expect(entry?.fields).toEqual({ 'say"hi': 1, "back\\slash": 2, 中文: 3 });
     expect(entry?.fields).toEqual({ 'say"hi': 1, "back\\slash": 2, 中文: 3 });
   });
   });
 
 
-  it("超过值的字节上界的值回成截短的字符串,一个大值不会整段进 JavaScript", () => {
+  it("超过值的字节上界的值回成截短的字符串,一个大值不会整段进 JavaScript", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seed(journal, "run_1", [
     seed(journal, "run_1", [
@@ -1603,7 +1568,7 @@ describe("SQLite dwf journal store — listArtifactItems with fields", () => {
     expect(list).toHaveLength(1001);
     expect(list).toHaveLength(1001);
   });
   });
 
 
-  it("页按取出的字段值计字节:大 item 里只取一个小字段时一页装得下很多条", () => {
+  it("页按取出的字段值计字节:大 item 里只取一个小字段时一页装得下很多条", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seed(
     seed(
@@ -1630,7 +1595,7 @@ describe("SQLite dwf journal store — listArtifactItems with fields", () => {
 });
 });
 
 
 describe("SQLite dwf journal store — listEventPage", () => {
 describe("SQLite dwf journal store — listEventPage", () => {
-  it("全部类型、item 原样,按条数分页并判定 hasMore", () => {
+  it("全部类型、item 原样,按条数分页并判定 hasMore", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     journal.appendEvent("run_1", { type: "log", message: "a" });
     journal.appendEvent("run_1", { type: "log", message: "a" });
@@ -1653,7 +1618,7 @@ describe("SQLite dwf journal store — listEventPage", () => {
     expect(rest).toEqual({ events: all.slice(2), hasMore: false });
     expect(rest).toEqual({ events: all.slice(2), hasMore: false });
   });
   });
 
 
-  it("字节界同看板条目:带大 item 的事件让页提前收尾,但每页至少一条", () => {
+  it("字节界同看板条目:带大 item 的事件让页提前收尾,但每页至少一条", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
     for (let ordinal = 1; ordinal <= 3; ordinal += 1) {
     for (let ordinal = 1; ordinal <= 3; ordinal += 1) {
@@ -1700,7 +1665,7 @@ describe("SqliteDwfJournalStore 终态编码(零迁移)", () => {
     ).run(runId, PARENT, "/repo", 4, 0, status, failureJson, 1, timeUpdated);
     ).run(runId, PARENT, "/repo", 4, 0, status, failureJson, 1, timeUpdated);
   }
   }
 
 
-  it("历史行按表解码:cancelled→stopped(user),failed+Interrupted→stopped(interrupted),其余 failed→errored", () => {
+  it("历史行按表解码:cancelled→stopped(user),failed+Interrupted→stopped(interrupted),其余 failed→errored", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     insertPhysicalRow(db, "old_pending", "pending", null);
     insertPhysicalRow(db, "old_pending", "pending", null);
     insertPhysicalRow(db, "old_running", "running", null);
     insertPhysicalRow(db, "old_running", "running", null);
@@ -1791,7 +1756,7 @@ describe("SqliteDwfJournalStore 终态编码(零迁移)", () => {
     expect("failure" in journal.getRun("old_cancelled")!).toBe(false);
     expect("failure" in journal.getRun("old_cancelled")!).toBe(false);
   });
   });
 
 
-  it("新写入的 stopped 落成 cancelled + 信封,errored 落成 failed + 原样失败;往返逐字段相等", () => {
+  it("新写入的 stopped 落成 cancelled + 信封,errored 落成 failed + 原样失败;往返逐字段相等", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     for (const runId of ["s_user", "s_model", "s_provider", "s_interrupted", "e_script"]) {
     for (const runId of ["s_user", "s_model", "s_provider", "s_interrupted", "e_script"]) {
       journal.createRun({
       journal.createRun({
@@ -1876,7 +1841,7 @@ describe("SqliteDwfJournalStore 终态编码(零迁移)", () => {
     expect("stopReason" in journal.getRun("s_provider")!).toBe(false);
     expect("stopReason" in journal.getRun("s_provider")!).toBe(false);
   });
   });
 
 
-  it("statuses 过滤在 SQL 里分清 errored 与 stopped(共享物理 failed)", () => {
+  it("statuses 过滤在 SQL 里分清 errored 与 stopped(共享物理 failed)", async () => {
     const { db, journal } = openIntrospectableJournal();
     const { db, journal } = openIntrospectableJournal();
     insertPhysicalRow(db, "p_cancelled", "cancelled", null, 5);
     insertPhysicalRow(db, "p_cancelled", "cancelled", null, 5);
     insertPhysicalRow(
     insertPhysicalRow(
@@ -1958,7 +1923,7 @@ describe("SQLite dwf journal store — listRunLifeSpans", () => {
     return { db, journal };
     return { db, journal };
   }
   }
 
 
-  it("单世:从 run-started 到这一世最后一条事件", () => {
+  it("单世:从 run-started 到这一世最后一条事件", async () => {
     const { db, journal } = seedLifeRun();
     const { db, journal } = seedLifeRun();
     journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
     journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
     journal.appendEvent(RUN_ID, { type: "log", message: "工作中" });
     journal.appendEvent(RUN_ID, { type: "log", message: "工作中" });
@@ -1967,10 +1932,12 @@ describe("SQLite dwf journal store — listRunLifeSpans", () => {
     stampEvent(db, 1, 5_000);
     stampEvent(db, 1, 5_000);
     stampEvent(db, 2, 61_000);
     stampEvent(db, 2, 61_000);
 
 
-    expect(journal.listRunLifeSpans(RUN_ID)).toEqual([{ startedAt: 1_000, lastActivityAt: 61_000 }]);
+    expect(journal.listRunLifeSpans(RUN_ID)).toEqual([
+      { startedAt: 1_000, lastActivityAt: 61_000 },
+    ]);
   });
   });
 
 
-  it("多世:每一世各算一段,世与世之间的空档不出现在任何一段里", () => {
+  it("多世:每一世各算一段,世与世之间的空档不出现在任何一段里", async () => {
     const { db, journal } = seedLifeRun();
     const { db, journal } = seedLifeRun();
     // 第一世:跑了一小时后被重启打断(没有 run-settled)。
     // 第一世:跑了一小时后被重启打断(没有 run-settled)。
     journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
     journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
@@ -1996,7 +1963,7 @@ describe("SQLite dwf journal store — listRunLifeSpans", () => {
     expect(activeMs).toBe(3_600_000 + 120_000);
     expect(activeMs).toBe(3_600_000 + 120_000);
   });
   });
 
 
-  it("一世里只有 run-started 一条事件:区间退化成 0,不是 null", () => {
+  it("一世里只有 run-started 一条事件:区间退化成 0,不是 null", async () => {
     const { db, journal } = seedLifeRun();
     const { db, journal } = seedLifeRun();
     journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
     journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
     stampEvent(db, 0, 7_000);
     stampEvent(db, 0, 7_000);
@@ -2004,7 +1971,7 @@ describe("SQLite dwf journal store — listRunLifeSpans", () => {
     expect(journal.listRunLifeSpans(RUN_ID)).toEqual([{ startedAt: 7_000, lastActivityAt: 7_000 }]);
     expect(journal.listRunLifeSpans(RUN_ID)).toEqual([{ startedAt: 7_000, lastActivityAt: 7_000 }]);
   });
   });
 
 
-  it("没有 run-started 的 run 与未知 run 都回空数组(无证据,不是 0 时长)", () => {
+  it("没有 run-started 的 run 与未知 run 都回空数组(无证据,不是 0 时长)", async () => {
     const { journal } = seedLifeRun();
     const { journal } = seedLifeRun();
     journal.appendEvent(RUN_ID, { type: "log", message: "只有日志" });
     journal.appendEvent(RUN_ID, { type: "log", message: "只有日志" });
 
 
@@ -2012,7 +1979,7 @@ describe("SQLite dwf journal store — listRunLifeSpans", () => {
     expect(journal.listRunLifeSpans("run_never_seen")).toEqual([]);
     expect(journal.listRunLifeSpans("run_never_seen")).toEqual([]);
   });
   });
 
 
-  it("只看本 run 的事件:另一条 run 的世不混进来", () => {
+  it("只看本 run 的事件:另一条 run 的世不混进来", async () => {
     const { db, journal } = seedLifeRun();
     const { db, journal } = seedLifeRun();
     journal.createRun({ runId: "run_other", caps: CAPS, spentTokens: 0, status: "running" });
     journal.createRun({ runId: "run_other", caps: CAPS, spentTokens: 0, status: "running" });
     journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
     journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });

+ 16 - 16
apps/zcode-cli/packages/adapters/tests/empty-tool-name-projection.test.ts

@@ -55,22 +55,22 @@ describe("empty tool name provider projection", () => {
     expect((openAiCompatible[1] as any).content[0].toolName).toBe("empty_tool_name");
     expect((openAiCompatible[1] as any).content[0].toolName).toBe("empty_tool_name");
   });
   });
 
 
-  it.each([
-    { toolCallId: undefined, toolName: "Read" },
-    { toolCallId: TOOL_CALL_ID, toolName: undefined },
-  ])("keeps rejecting incomplete tool-result identity %#", ({ toolCallId, toolName }) => {
-    expect(() =>
-      toAiSdkMessages([
-        {
-          role: "tool",
-          content: MODEL_CONTENT,
-          isError: true,
-          toolCallId,
-          toolName,
-        } as never,
-      ]),
-    ).toThrow("Tool model messages require toolCallId and toolName");
-  });
+  it.each([{ toolCallId: undefined, toolName: "Read" }])(
+    "keeps rejecting incomplete tool-result identity %#",
+    ({ toolCallId, toolName }) => {
+      expect(() =>
+        toAiSdkMessages([
+          {
+            role: "tool",
+            content: MODEL_CONTENT,
+            isError: true,
+            toolCallId,
+            toolName,
+          } as never,
+        ]),
+      ).toThrow("Tool model messages require toolCallId and toolName");
+    },
+  );
 
 
   it.each([undefined, null, 42, { invalid: true }])(
   it.each([undefined, null, 42, { invalid: true }])(
     "rejects non-string tool name %j at both projection call sites",
     "rejects non-string tool name %j at both projection call sites",

+ 0 - 9
apps/zcode-cli/packages/adapters/tests/env-model-config.test.ts

@@ -15,15 +15,6 @@ describe("env model config", () => {
     expect(config).not.toHaveProperty("model");
     expect(config).not.toHaveProperty("model");
   });
   });
 
 
-  it("does not validate legacy model environment variables", () => {
-    const config = parseEnvConfig({
-      ZCODE_BASE_URL: "https://api.z.ai/api/anthropic",
-      ZCODE_MODEL: "zai/",
-    });
-
-    expect(config).not.toHaveProperty("model");
-  });
-
   it("does not let legacy env or file model config enter RuntimeConfig", async () => {
   it("does not let legacy env or file model config enter RuntimeConfig", async () => {
     const dir = await mkdtemp(join(tmpdir(), "zcode-env-model-"));
     const dir = await mkdtemp(join(tmpdir(), "zcode-env-model-"));
     const path = join(dir, "config.json");
     const path = join(dir, "config.json");

+ 0 - 10
apps/zcode-cli/packages/adapters/tests/exec.test.ts

@@ -109,11 +109,6 @@ describe("NodeExecutionAdapter", () => {
     const capable = adapter as BashBackgroundLifecycleCapableAdapter;
     const capable = adapter as BashBackgroundLifecycleCapableAdapter;
 
 
     try {
     try {
-      const removedMethodName = ["run", "Backgroundable"].join("");
-      expect(removedMethodName in adapter).toBe(false);
-      expect(capable.runBashWithBackgroundLifecycle).toBeTypeOf("function");
-      expect(capable.waitForBackgroundTask).toBeTypeOf("function");
-
       const result = await capable.runBashWithBackgroundLifecycle!(
       const result = await capable.runBashWithBackgroundLifecycle!(
         {
         {
           command: {
           command: {
@@ -618,9 +613,6 @@ describe("NodeExecutionAdapter", () => {
     const capable = adapter as BashBackgroundLifecycleCapableAdapter;
     const capable = adapter as BashBackgroundLifecycleCapableAdapter;
 
 
     try {
     try {
-      expect(capable.runBashWithBackgroundLifecycle).toBeTypeOf("function");
-      expect(capable.waitForBackgroundTask).toBeTypeOf("function");
-
       const result = await capable.runBashWithBackgroundLifecycle!(
       const result = await capable.runBashWithBackgroundLifecycle!(
         {
         {
           command: {
           command: {
@@ -661,8 +653,6 @@ describe("NodeExecutionAdapter", () => {
     const capable = adapter as BashBackgroundLifecycleCapableAdapter;
     const capable = adapter as BashBackgroundLifecycleCapableAdapter;
 
 
     try {
     try {
-      expect(capable.runBashWithBackgroundLifecycle).toBeTypeOf("function");
-
       const result = await capable.runBashWithBackgroundLifecycle!(
       const result = await capable.runBashWithBackgroundLifecycle!(
         {
         {
           command: {
           command: {

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