Sfoglia il codice sorgente

feat: update v3.14.3

- The concurrency limit of a running workflow can now be adjusted directly, without stopping the task.
- Optimized the reuse logic when modifying and restarting workflows.
- Improved the real-time status display for large workflows.
- Improved the efficiency of workflow script submission and modification, reducing token consumption.

- Fixed an issue where workflows could cause the interface to crash in some cases.
- Fixed an issue where buttons on workflow cards were sometimes pushed out of the interface.
- Fixed an issue where the workflow tool took up too much context.
wuweiqi 2 mesi fa
parent
commit
29628c9acd
100 ha cambiato i file con 6316 aggiunte e 866 eliminazioni
  1. 3 5
      README.en.md
  2. 5 5
      README.md
  3. 80 0
      THIRD-PARTY-NOTICES.md
  4. 5 1
      apps/zcode-cli/packages/adapters/src/storage/session-store.ts
  5. 66 0
      apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/dwf-journal-introspection.ts
  6. 24 1
      apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/dwf-journal.ts
  7. 3 2
      apps/zcode-cli/packages/bootstrap/src/app/bundled-plugins.ts
  8. 231 0
      apps/zcode-cli/packages/bootstrap/src/app/bundled-skills.ts
  9. 11 13
      apps/zcode-cli/packages/bootstrap/src/app/create-app.ts
  10. 11 18
      apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-gate.ts
  11. 157 30
      apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-import.ts
  12. 49 0
      apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-elapsed.ts
  13. 14 0
      apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-journal.ts
  14. 65 16
      apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-launch.ts
  15. 27 0
      apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-observation.ts
  16. 62 0
      apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-retune.ts
  17. 1 0
      apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-sequence-capture.ts
  18. 20 13
      apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-service.ts
  19. 59 3
      apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-submit.ts
  20. 51 6
      apps/zcode-cli/packages/bootstrap/src/app/workflow-actor-transcript.ts
  21. 15 0
      apps/zcode-cli/packages/bootstrap/src/app/workflow-concurrency-ceiling.ts
  22. 14 2
      apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-concurrency.ts
  23. 153 0
      apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-quiescence.ts
  24. 69 0
      apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-submit-bridge.ts
  25. 26 0
      apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-tool-activity.ts
  26. 11 2
      apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-transcript.ts
  27. 31 4
      apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-types.ts
  28. 67 74
      apps/zcode-cli/packages/bootstrap/src/app/workflow-driver.ts
  29. 47 0
      apps/zcode-cli/packages/bootstrap/src/app/workflow-run-control.ts
  30. 186 0
      apps/zcode-cli/packages/bootstrap/src/app/workflow-seat-gate.ts
  31. 30 7
      apps/zcode-cli/packages/bootstrap/src/builtin-prompt-command.ts
  32. 63 0
      apps/zcode-cli/packages/bootstrap/src/builtin-workflow-command.ts
  33. 2 14
      apps/zcode-cli/packages/bootstrap/src/custom-command-prompt.ts
  34. 15 6
      apps/zcode-cli/packages/bootstrap/src/skills.ts
  35. 6 0
      apps/zcode-cli/packages/bootstrap/src/slash-command-surface.ts
  36. 1 0
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/commands/handlers/session-flow.ts
  37. 31 4
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/commands/prompt-turn.ts
  38. 3 0
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/commands/types.ts
  39. 73 12
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/conversation-topic-publisher.ts
  40. 98 0
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/conversation-workflow-run-deltas.ts
  41. 24 6
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/product-projection.ts
  42. 5 0
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/projection-state.ts
  43. 112 0
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/sessions-index-fanout-throttle.ts
  44. 18 0
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/v4-gateway.ts
  45. 3 0
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/automation-port.ts
  46. 8 0
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server-operations.ts
  47. 3 0
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server-types.ts
  48. 5 1
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/skill-reference-catalog.ts
  49. 13 36
      apps/zcode-cli/packages/bootstrap/src/zcode-protocol/slash-commands.ts
  50. 1520 0
      apps/zcode-cli/packages/bundled-skills/skills/dynamic-workflows/SKILL.md
  51. 801 0
      apps/zcode-cli/packages/bundled-skills/skills/dynamic-workflows/examples.md
  52. 460 0
      apps/zcode-cli/packages/bundled-skills/skills/dynamic-workflows/patterns.md
  53. 13 2
      apps/zcode-cli/packages/cli/scripts/build-sea.mjs
  54. 88 0
      apps/zcode-cli/packages/cli/scripts/sea-bundled-skill-assets.mjs
  55. 3 0
      apps/zcode-cli/packages/cli/src/arguments.ts
  56. 8 0
      apps/zcode-cli/packages/cli/src/command-center/create.ts
  57. 6 0
      apps/zcode-cli/packages/cli/src/command-center/slash-command-types.ts
  58. 11 0
      apps/zcode-cli/packages/cli/src/command-center/slash-commands.ts
  59. 2 0
      apps/zcode-cli/packages/cli/src/prompt-command.ts
  60. 12 0
      apps/zcode-cli/packages/cli/src/run.ts
  61. 6 2
      apps/zcode-cli/packages/contracts/src/events/session.events.ts
  62. 45 0
      apps/zcode-cli/packages/contracts/src/interfaces/dynamic-workflow-run-retune.port.ts
  63. 72 0
      apps/zcode-cli/packages/contracts/src/interfaces/dynamic-workflow-run-workspace.port.ts
  64. 42 69
      apps/zcode-cli/packages/contracts/src/interfaces/dynamic-workflow-run.port.ts
  65. 22 6
      apps/zcode-cli/packages/contracts/src/tools/amend-workflow.ts
  66. 38 16
      apps/zcode-cli/packages/contracts/src/tools/create-workflow.ts
  67. 3 13
      apps/zcode-cli/packages/contracts/src/tools/eval-workflow-snippet.ts
  68. 7 16
      apps/zcode-cli/packages/contracts/src/tools/save-workflow.ts
  69. 54 0
      apps/zcode-cli/packages/core/src/agent/loaded-skills.ts
  70. 9 7
      apps/zcode-cli/packages/core/src/agent/read-file-state-hydrator.ts
  71. 4 7
      apps/zcode-cli/packages/core/src/permission/service.ts
  72. 10 0
      apps/zcode-cli/packages/core/src/runtime/helpers/runtime-tools.ts
  73. 5 6
      apps/zcode-cli/packages/core/src/runtime/helpers/tool-allowlist.ts
  74. 119 0
      apps/zcode-cli/packages/core/src/runtime/methods/dynamic-workflow-run-settings-turn.ts
  75. 110 94
      apps/zcode-cli/packages/core/src/runtime/methods/dynamic-workflow-run-settings.ts
  76. 4 4
      apps/zcode-cli/packages/core/src/runtime/types.ts
  77. 67 31
      apps/zcode-cli/packages/core/src/tool/executor/background-tasks.ts
  78. 1 0
      apps/zcode-cli/packages/core/src/tool/executor/call-runner.ts
  79. 4 0
      apps/zcode-cli/packages/core/src/tool/executor/create-workflow-display.ts
  80. 1 0
      apps/zcode-cli/packages/core/src/tool/executor/impl.ts
  81. 3 0
      apps/zcode-cli/packages/core/src/tool/executor/types.ts
  82. 13 28
      apps/zcode-cli/packages/core/src/tool/handlers/amend-workflow-description.ts
  83. 17 47
      apps/zcode-cli/packages/core/src/tool/handlers/amend-workflow-resolve.ts
  84. 248 0
      apps/zcode-cli/packages/core/src/tool/handlers/amend-workflow-retune.ts
  85. 54 0
      apps/zcode-cli/packages/core/src/tool/handlers/amend-workflow-source.ts
  86. 55 5
      apps/zcode-cli/packages/core/src/tool/handlers/amend-workflow.ts
  87. 13 93
      apps/zcode-cli/packages/core/src/tool/handlers/create-workflow-description.ts
  88. 19 3
      apps/zcode-cli/packages/core/src/tool/handlers/create-workflow.ts
  89. 7 38
      apps/zcode-cli/packages/core/src/tool/handlers/eval-workflow-snippet-description.ts
  90. 5 1
      apps/zcode-cli/packages/core/src/tool/handlers/eval-workflow-snippet.ts
  91. 10 63
      apps/zcode-cli/packages/core/src/tool/handlers/save-workflow-description.ts
  92. 3 0
      apps/zcode-cli/packages/core/src/tool/handlers/save-workflow.ts
  93. 68 0
      apps/zcode-cli/packages/core/src/tool/handlers/workflow-draft-read-state.ts
  94. 61 0
      apps/zcode-cli/packages/core/src/tool/handlers/workflow-skill-gate.ts
  95. 15 2
      apps/zcode-cli/packages/core/src/tool/read-file-state-metadata.ts
  96. 11 2
      apps/zcode-cli/packages/core/src/tool/types.ts
  97. 23 0
      apps/zcode-cli/packages/dynamic-workflow-runtime/src/harness.ts
  98. 6 1
      apps/zcode-cli/packages/dynamic-workflow-runtime/src/index.ts
  99. 41 0
      apps/zcode-cli/packages/dynamic-workflow/src/engine/engine-artifacts-primary.ts
  100. 21 29
      apps/zcode-cli/packages/dynamic-workflow/src/engine/engine-artifacts.ts

+ 3 - 5
README.en.md

@@ -13,11 +13,9 @@
 
 
 ZCode is an AI coding workspace with desktop, browser, and terminal interfaces. This repository contains the clients, backend services, shared UI, and Agent CLI and runtime source code.
 ZCode is an AI coding workspace with desktop, browser, and terminal interfaces. This repository contains the clients, backend services, shared UI, and Agent CLI and runtime source code.
 
 
-| Interface                    | Purpose                                                                                   | Development command            |
-| ---------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------ |
-| Desktop                      | Electron desktop application                                                              | `pnpm dev:desktop`             |
-| Web / ZCode CLI distribution | Terminal and browser workspace; packages the TUI, Web client, backend, and Agent together | `pnpm dev:web`                 |
-| Agent CLI                    | The `zcode` terminal interface, which also provides the Agent runtime for Desktop and Web | `pnpm --filter @zcode/cli dev` |
+## Updates
+
+- 2026-9-23: Updated to ZCode v3.14.3.
 
 
 ## Setup
 ## Setup
 
 

+ 5 - 5
README.md

@@ -11,13 +11,13 @@
   简体中文 | <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 与运行时源码。
 
 
-| 入口                 | 用途                                                           | 开发命令                       |
-| -------------------- | -------------------------------------------------------------- | ------------------------------ |
-| Desktop              | Electron 桌面应用                                              | `pnpm dev:desktop`             |
-| Web / ZCode 命令行版 | 终端与浏览器工作台;将 TUI、Web、后端和 Agent 组装为独立运行包 | `pnpm dev:web`                 |
-| Agent CLI            | 在终端中使用 `zcode`,也为 Desktop 和 Web 提供 Agent 运行时    | `pnpm --filter @zcode/cli dev` |
+## 更新
+
+- 2026-9-23:更新至 ZCode v3.14.3 版本。
 
 
 ## 初始化
 ## 初始化
 
 

+ 80 - 0
THIRD-PARTY-NOTICES.md

@@ -246,6 +246,10 @@ Original copyright, license and NOTICE text is retained below. Identical text is
 
 
 - @jridgewell/trace-mapping@0.3.31 — MIT
 - @jridgewell/trace-mapping@0.3.31 — MIT
 
 
+- @larksuiteoapi/node-sdk@1.61.1 — MIT
+
+- @larksuiteoapi/node-sdk@1.64.0 — MIT
+
 - @lexical/clipboard@0.42.0 — MIT
 - @lexical/clipboard@0.42.0 — MIT
 
 
 - @lexical/code-core@0.42.0 — MIT
 - @lexical/code-core@0.42.0 — MIT
@@ -1540,8 +1544,14 @@ Original copyright, license and NOTICE text is retained below. Identical text is
 
 
 - lodash.escaperegexp@4.1.2 — MIT
 - lodash.escaperegexp@4.1.2 — MIT
 
 
+- lodash.identity@3.0.0 — MIT
+
 - lodash.isequal@4.5.0 — MIT
 - lodash.isequal@4.5.0 — MIT
 
 
+- lodash.merge@4.6.2 — MIT
+
+- lodash.pickby@4.6.0 — MIT
+
 - log-symbols@6.0.0 — MIT
 - log-symbols@6.0.0 — MIT
 
 
 - long@5.3.2 — Apache-2.0
 - long@5.3.2 — Apache-2.0
@@ -4409,6 +4419,40 @@ MIT
 
 
 ````
 ````
 
 
+### Notice f9bfd5e309b1523a2dd3937b44f516e6018605eb05b35336485b0a34cbd9f373
+
+- @larksuiteoapi/node-sdk@1.61.1: LICENSE
+
+- @larksuiteoapi/node-sdk@1.64.0: LICENSE
+
+
+
+````text
+MIT License
+
+Copyright (c) 2022 Lark Technologies Pte. Ltd.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice, shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+````
+
+### Notice d0de7064760700e47a0fdedd12ae4e027146e16e9cec0233505fe7c4ed5b3344
+
+- @larksuiteoapi/node-sdk@1.61.1: README.md (license section)
+
+- @larksuiteoapi/node-sdk@1.64.0: README.md (license section)
+
+
+
+````text
+## LICENSE
+MIT
+
+````
+
 ### Notice da6d3703ed11cbe42bd212c725957c98da23cbff1998c05fa4b3d976d1a58e93
 ### Notice da6d3703ed11cbe42bd212c725957c98da23cbff1998c05fa4b3d976d1a58e93
 
 
 - @lexical/clipboard@0.42.0: LICENSE
 - @lexical/clipboard@0.42.0: LICENSE
@@ -22377,6 +22421,8 @@ OTHER DEALINGS IN THE SOFTWARE.
 
 
 - lodash-es@4.18.1: LICENSE
 - lodash-es@4.18.1: LICENSE
 
 
+- lodash.merge@4.6.2: LICENSE
+
 
 
 
 
 ````text
 ````text
@@ -22434,6 +22480,8 @@ terms above.
 
 
 - lodash.escaperegexp@4.1.2: LICENSE
 - lodash.escaperegexp@4.1.2: LICENSE
 
 
+- lodash.pickby@4.6.0: LICENSE
+
 
 
 
 
 ````text
 ````text
@@ -22487,6 +22535,38 @@ terms above.
 
 
 ````
 ````
 
 
+### Notice 2b61a34ef17beffb1e555efa8b46110d25398d47f2e88b2cacc46f8bd382c639
+
+- lodash.identity@3.0.0: LICENSE.txt
+
+
+
+````text
+Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
+Based on Underscore.js 1.7.0, copyright 2009-2015 Jeremy Ashkenas,
+DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+````
+
 ### Notice e159c6d48c989185448658f276375bfb2300362ec6d4ae5525a2d49c4bcb947d
 ### Notice e159c6d48c989185448658f276375bfb2300362ec6d4ae5525a2d49c4bcb947d
 
 
 - lodash.isequal@4.5.0: LICENSE
 - lodash.isequal@4.5.0: LICENSE

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

@@ -14,6 +14,7 @@ export type {
   DwfListRunsQuery,
   DwfListRunsQuery,
   DwfNodeStatusCounts,
   DwfNodeStatusCounts,
   DwfRunIntrospectionQueries,
   DwfRunIntrospectionQueries,
+  DwfRunLifeSpan,
 } from "./session-store/repositories/dwf-journal.js";
 } from "./session-store/repositories/dwf-journal.js";
 export type {
 export type {
   DwfRunDetailRow,
   DwfRunDetailRow,
@@ -33,4 +34,7 @@ export type {
   SqliteSessionStoreOptions,
   SqliteSessionStoreOptions,
 } from "./session-store/options.js";
 } from "./session-store/options.js";
 
 
-export type { AsyncSqliteMigrationOptions, SqliteMigrationProgress } from "./session-store/migration-runner.js";
+export type {
+  AsyncSqliteMigrationOptions,
+  SqliteMigrationProgress,
+} from "./session-store/migration-runner.js";

+ 66 - 0
apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/dwf-journal-introspection.ts

@@ -64,6 +64,18 @@ export interface DwfNodeStatusCounts {
   running: number;
   running: number;
 }
 }
 
 
+/**
+ * 一个 run 的**一世**(一次 `run-started` 到它最后一条事件)的起止,epoch 毫秒。
+ *
+ * 一世就是「引擎活着的一段」:崩溃或停止的那一世没有 `run-settled`,所以收尾只能由「这一世
+ * 记下的最后一条事件」界定——那正是它最后一次动的时刻。两个时刻同源于 `dwf_event.time_created`
+ * (事件日志里一切「多久以前」的唯一时钟),因此差值不会跨时钟。
+ */
+export interface DwfRunLifeSpan {
+  startedAt: number;
+  lastActivityAt: number;
+}
+
 /**
 /**
  * 宿主侧的 run 内省查询面(`ListWorkflowRuns` / `GetWorkflowRun` 两个只读工具的取数底座)。
  * 宿主侧的 run 内省查询面(`ListWorkflowRuns` / `GetWorkflowRun` 两个只读工具的取数底座)。
  *
  *
@@ -86,6 +98,11 @@ export interface DwfRunIntrospectionQueries {
   listArtifactRows(runId: string): NodeRecord[];
   listArtifactRows(runId: string): NodeRecord[];
   listRecentLogEvents(runId: string, limit: number): StoredEvent[];
   listRecentLogEvents(runId: string, limit: number): StoredEvent[];
   listRuns(query: DwfListRunsQuery): DwfRunListItem[];
   listRuns(query: DwfListRunsQuery): DwfRunListItem[];
+  /**
+   * 本 run 每一世的活动区间,按时序(完成卡的「时间」格)。一条 run 可以
+   * 有多世(每次 resume 一世),而每一世的墙钟只有事件日志知道。
+   */
+  listRunLifeSpans(runId: string): DwfRunLifeSpan[];
   /**
   /**
    * 本 run 的 world-read / world-run 行,按落库先后(`order by id`),带 journal 时间戳。**不取
    * 本 run 的 world-read / world-run 行,按落库先后(`order by id`),带 journal 时间戳。**不取
    * `result_json`**:这条读面是清单(op / args / 状态 / 时间),正文另有按 (siteId, ordinal)
    * `result_json`**:这条读面是清单(op / args / 状态 / 时间),正文另有按 (siteId, ordinal)
@@ -189,6 +206,55 @@ export function listRecentLogEvents(db: DatabaseSync, runId: string, limit: numb
   return rows.reverse().map(decodeEvent);
   return rows.reverse().map(decodeEvent);
 }
 }
 
 
+/**
+ * 本 run 每一世的活动区间(`run-started` 的时刻 → 那一世最后一条事件的时刻),按时序。
+ *
+ * 完成卡的时长是 lineage 的**活动**时长之和,而一条 run 的每一世都要各算一段——世与世之间的空档
+ * (进程已死、还没 resume)什么都没在跑,不能计入。
+ *
+ * 一条 SQL 做完,且**不解一个 payload**:`lead()` 把每一世的起点与下一世的起点配成区间,
+ * 相关子查询在区间内取 sequence 最大的那条的时刻。两个谓词都落在 `unique(run_id, sequence)`
+ * 上;`type` 列就是为这类过滤存的冗余(payload_json 里也有一份)。一条 18k 事件的 run 因此
+ * 只读几行,而不是把 2.8 MB 的 payload 解进内存——后者正是这条读面刻意不用 `listEvents` 的理由。
+ *
+ * 子查询恒有解(区间至少含 `run-started` 自己),所以正常行不会回 null;仍防御性收窄——
+ * 这是个跨存储边界的读面,而一个 null 会静默变成 NaN 毫秒。
+ */
+export function listRunLifeSpans(db: DatabaseSync, runId: string): DwfRunLifeSpan[] {
+  const rows = db
+    .prepare(
+      `
+      with lives as (
+        select sequence, time_created,
+               lead(sequence) over (order by sequence) as next_sequence
+        from dwf_event
+        where run_id = ? and type = 'run-started'
+      )
+      select
+        l.time_created as started_at,
+        (
+          select e.time_created
+          from dwf_event e
+          where e.run_id = ?
+            and e.sequence >= l.sequence
+            and (l.next_sequence is null or e.sequence < l.next_sequence)
+          order by e.sequence desc
+          limit 1
+        ) as last_activity_at
+      from lives l
+      order by l.sequence
+      `,
+    )
+    .all(runId, runId) as unknown as { started_at: number; last_activity_at: number | null }[];
+  return rows.map((row) => ({
+    startedAt: Number(row.started_at),
+    lastActivityAt:
+      typeof row.last_activity_at === "number"
+        ? Number(row.last_activity_at)
+        : Number(row.started_at),
+  }));
+}
+
 /**
 /**
  * 某父会话名下的 run(最近更新在前,最多 limit 条)。服务宿主侧的枚举面
  * 某父会话名下的 run(最近更新在前,最多 limit 条)。服务宿主侧的枚举面
  * (`DynamicWorkflowRunPort.listRunsForSession` → UI 重启后的发现查询):`workflowRuns` 投影跨进程不存活,工具卡 join
  * (`DynamicWorkflowRunPort.listRunsForSession` → UI 重启后的发现查询):`workflowRuns` 投影跨进程不存活,工具卡 join

+ 24 - 1
apps/zcode-cli/packages/adapters/src/storage/session-store/repositories/dwf-journal.ts

@@ -13,6 +13,7 @@
 import type { DatabaseSync } from "node:sqlite";
 import type { DatabaseSync } from "node:sqlite";
 import type {
 import type {
   ActorRecord,
   ActorRecord,
+  Caps,
   JournalStorePort,
   JournalStorePort,
   ListEventsOptions,
   ListEventsOptions,
   NodeRecord,
   NodeRecord,
@@ -51,12 +52,14 @@ import {
   countNodesByStatus,
   countNodesByStatus,
   getRunRow,
   getRunRow,
   listRecentLogEvents,
   listRecentLogEvents,
+  listRunLifeSpans,
   listRuns,
   listRuns,
   listRunsByParentSession,
   listRunsByParentSession,
   listWorldNodes,
   listWorldNodes,
   type DwfListRunsQuery,
   type DwfListRunsQuery,
   type DwfNodeStatusCounts,
   type DwfNodeStatusCounts,
   type DwfRunIntrospectionQueries,
   type DwfRunIntrospectionQueries,
+  type DwfRunLifeSpan,
 } from "./dwf-journal-introspection.js";
 } from "./dwf-journal-introspection.js";
 
 
 export type { DwfArtifactItem, DwfArtifactItemsQuery } from "./dwf-journal-artifacts.js";
 export type { DwfArtifactItem, DwfArtifactItemsQuery } from "./dwf-journal-artifacts.js";
@@ -66,6 +69,7 @@ export type {
   DwfListRunsQuery,
   DwfListRunsQuery,
   DwfNodeStatusCounts,
   DwfNodeStatusCounts,
   DwfRunIntrospectionQueries,
   DwfRunIntrospectionQueries,
+  DwfRunLifeSpan,
 } from "./dwf-journal-introspection.js";
 } from "./dwf-journal-introspection.js";
 
 
 class SqliteDwfJournalStore implements JournalStorePort, DwfRunIntrospectionQueries {
 class SqliteDwfJournalStore implements JournalStorePort, DwfRunIntrospectionQueries {
@@ -102,6 +106,9 @@ class SqliteDwfJournalStore implements JournalStorePort, DwfRunIntrospectionQuer
           // lineage 同属这条只写一次的元数据路:修订是 supersede,前驱行零触碰,
           // lineage 同属这条只写一次的元数据路:修订是 supersede,前驱行零触碰,
           // 所以「本 run 修订自谁」只有建 run 这一刻能写下。
           // 所以「本 run 修订自谁」只有建 run 这一刻能写下。
           record.resumedFrom ?? null,
           record.resumedFrom ?? null,
+          // caps 与上面几列**不**同路:它不是只写一次的元数据。`updateRunCaps` 是这一列的第二个
+          // 写入者——一次只改 `max_concurrency` 的修订就地作用在活着的 run 上,而 resume 沿用
+          // 行里的值。
           record.caps.maxConcurrency,
           record.caps.maxConcurrency,
           record.spentTokens,
           record.spentTokens,
           settlement.status,
           settlement.status,
@@ -182,6 +189,19 @@ class SqliteDwfJournalStore implements JournalStorePort, DwfRunIntrospectionQuer
     this.assertRunTouched(changes, runId);
     this.assertRunTouched(changes, runId);
   }
   }
 
 
+  /**
+   * 本 run 并发上界的就地更新。
+   * 与 `updateRunUsage` 同族的窄写入:**只列 caps_max_concurrency**,状态、用量与结算信封
+   * 都不在这条语句里——它们各有自己的写入路径,混进来就会让一次改上界顺手回退一个结算。
+   * 零迁移:列早已存在,本方法只是它的第二个写入者。
+   */
+  updateRunCaps(runId: string, caps: Caps): void {
+    const { changes } = this.db
+      .prepare("update dwf_run set caps_max_concurrency = ?, time_updated = ? where id = ?")
+      .run(caps.maxConcurrency, Date.now(), runId);
+    this.assertRunTouched(changes, runId);
+  }
+
   /**
   /**
    * 某个父会话名下所有**非终态**的 run。刻意不在 `JournalStorePort` 上:引擎从不按父会话找
    * 某个父会话名下所有**非终态**的 run。刻意不在 `JournalStorePort` 上:引擎从不按父会话找
    * run,这条查询只服务于宿主侧的孤儿收敛——一个进程被杀掉的 run 会永远停在 `running`,
    * run,这条查询只服务于宿主侧的孤儿收敛——一个进程被杀掉的 run 会永远停在 `running`,
@@ -226,11 +246,14 @@ class SqliteDwfJournalStore implements JournalStorePort, DwfRunIntrospectionQuer
     return listRecentLogEvents(this.db, runId, limit);
     return listRecentLogEvents(this.db, runId, limit);
   }
   }
 
 
+  listRunLifeSpans(runId: string): DwfRunLifeSpan[] {
+    return listRunLifeSpans(this.db, runId);
+  }
+
   listRunsByParentSession(parentSessionId: string, limit: number): DwfRunSessionListItem[] {
   listRunsByParentSession(parentSessionId: string, limit: number): DwfRunSessionListItem[] {
     return listRunsByParentSession(this.db, parentSessionId, limit);
     return listRunsByParentSession(this.db, parentSessionId, limit);
   }
   }
 
 
-
   putActor(record: ActorRecord): void {
   putActor(record: ActorRecord): void {
     const now = Date.now();
     const now = Date.now();
     this.db
     this.db

+ 3 - 2
apps/zcode-cli/packages/bootstrap/src/app/bundled-plugins.ts

@@ -628,8 +628,9 @@ function officialPluginCacheRoot(
   );
   );
 }
 }
 
 
-function candidateBaseDirs(): string[] {
-  // Electron app-server 运行在 resources/glm/zcode.cjs,官方插件资源也随桌面包
+/** 内置技能包(bundled-skills.ts)沿同一组候选目录定位,保证两类内置资产在每种运行布局下同进同出。 */
+export function candidateBaseDirs(): string[] {
+  // 修复原因:Electron app-server 运行在 resources/glm/zcode.cjs,官方插件资源也随桌面包
   // stage 到同级 packages/*-plugin。候选目录必须优先看入口文件目录,避免生产态退回到
   // stage 到同级 packages/*-plugin。候选目录必须优先看入口文件目录,避免生产态退回到
   // monorepo-only 的 __dirname 查找假设。
   // monorepo-only 的 __dirname 查找假设。
   return [entrypointDir(), runtimeDir(), process.cwd()].filter(
   return [entrypointDir(), runtimeDir(), process.cwd()].filter(

+ 231 - 0
apps/zcode-cli/packages/bootstrap/src/app/bundled-skills.ts

@@ -0,0 +1,231 @@
+import { createHash, randomUUID } from "node:crypto";
+import { access, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+import type { Logger, SkillRoot } from "@zcode/contracts";
+import { DYNAMIC_WORKFLOW_SKILL_NAME } from "@zcode/contracts";
+import { candidateBaseDirs } from "./bundled-plugins.js";
+
+/**
+ * 随 CLI 内置的技能包(apps/zcode-cli/packages/bundled-skills)。
+ *
+ * 它不是插件:不进官方市场目录、没有启停开关、不能卸载,也不出现在设置页与 `$` 引用面板。
+ * 产品功能的工具由 runtime 注册,配套技能随 CLI 分发,避免卸载插件后缺少工具使用说明。
+ *
+ * 三种运行形态解析到同一个 skills 目录:
+ * - 开发态 / Electron 桌面:沿官方插件同款候选目录在入口旁找到 `packages/bundled-skills`,原地读取,不拷贝。
+ * - SEA 二进制:资产内嵌在 `zcode-bundled-skills/` 前缀下,首启按内容 hash 解压到
+ *   `<cli storage>/bundled-skills/<hash>/`;目录名即内容身份,重复启动幂等,并发只会有一个赢家。
+ * - 远端主机:prepare-prebuilds 把目录 stage 到远端 zcode.cjs 旁,与桌面同路。
+ */
+
+export const BUNDLED_SKILL_PACK_DIRECTORY_NAME = "bundled-skills";
+export const BUNDLED_SKILL_PACK_SKILLS_DIRECTORY = "skills";
+/** 门与技能包共用一个名字:常量住在 contracts(core 的技能门也读它),这里只转出。 */
+export { DYNAMIC_WORKFLOW_SKILL_NAME };
+
+/** 技能包里每个文件都是必需资产:丢任何一个都拒绝整包,而不是装出一个引用文件缺失的技能。 */
+export const BUNDLED_SKILL_PACK_REQUIRED_PATHS = [
+  `skills/${DYNAMIC_WORKFLOW_SKILL_NAME}/SKILL.md`,
+  `skills/${DYNAMIC_WORKFLOW_SKILL_NAME}/patterns.md`,
+  `skills/${DYNAMIC_WORKFLOW_SKILL_NAME}/examples.md`,
+] as const;
+
+/** 与 official-plugin-definitions 的 rootCandidates 同形,覆盖 monorepo src/dist、cli/dist 与桌面 resources/glm 布局。 */
+const BUNDLED_SKILL_PACK_ROOT_CANDIDATES = [
+  `packages/${BUNDLED_SKILL_PACK_DIRECTORY_NAME}`,
+  `../${BUNDLED_SKILL_PACK_DIRECTORY_NAME}`,
+  `../../${BUNDLED_SKILL_PACK_DIRECTORY_NAME}`,
+  `../../../${BUNDLED_SKILL_PACK_DIRECTORY_NAME}`,
+] as const;
+
+export const SEA_BUNDLED_SKILL_ASSET_PREFIX = "zcode-bundled-skills/";
+const SEA_BUNDLED_SKILL_MANIFEST_ASSET_KEY = `${SEA_BUNDLED_SKILL_ASSET_PREFIX}manifest.json`;
+const SEED_MARKER_FILE = ".zcode-bundled-skills-seed.json";
+
+/**
+ * 排在所有插件根之后(adapters 的插件根从 FIRST_PLUGIN_PRIORITY 起步进):同名技能按发现顺序取先者,
+ * 用户/项目/插件里的同名技能都应压过内置包。
+ */
+const BUNDLED_SKILL_ROOT_PRIORITY = 1_000_000;
+
+interface SeaBundledSkillManifest {
+  files: Array<{ mode?: number; path: string; sha256: string }>;
+  hash: string;
+  version: 1;
+}
+
+type SeaModule = typeof import("node:sea");
+
+export interface ResolveBundledSkillRootsOptions {
+  /** `getCliStorageRoot(storage.dir)`;仅 SEA 解压需要。 */
+  cliStorageRoot: string;
+  logger?: Logger;
+}
+
+export async function resolveBundledSkillRoots(
+  options: ResolveBundledSkillRootsOptions,
+): Promise<SkillRoot[]> {
+  const packRoot =
+    (await materializeSeaBundledSkillPack(options)) ??
+    (await resolveFilesystemBundledSkillPackRoot());
+  if (!packRoot) {
+    // 内置技能包缺席会让脚本编写被技能门拒绝;记录诊断,便于定位不完整的分发资产。
+    options.logger?.warn("Bundled skill pack unavailable", {
+      module: "bootstrap.bundled_skills",
+      requiredPaths: [...BUNDLED_SKILL_PACK_REQUIRED_PATHS],
+    });
+    return [];
+  }
+  return [
+    {
+      path: join(packRoot, BUNDLED_SKILL_PACK_SKILLS_DIRECTORY),
+      priority: BUNDLED_SKILL_ROOT_PRIORITY,
+      scope: "system",
+      source: "bundled",
+    },
+  ];
+}
+
+export async function findMissingBundledSkillPackPaths(packRoot: string): Promise<string[]> {
+  const present = await Promise.all(
+    BUNDLED_SKILL_PACK_REQUIRED_PATHS.map((requiredPath) =>
+      pathExists(join(packRoot, ...requiredPath.split("/"))),
+    ),
+  );
+  return BUNDLED_SKILL_PACK_REQUIRED_PATHS.filter((_, index) => !present[index]);
+}
+
+async function pathExists(path: string): Promise<boolean> {
+  try {
+    await access(path);
+    return true;
+  } catch {
+    return false;
+  }
+}
+
+async function resolveFilesystemBundledSkillPackRoot(): Promise<string | undefined> {
+  for (const baseDir of candidateBaseDirs()) {
+    for (const relativePath of BUNDLED_SKILL_PACK_ROOT_CANDIDATES) {
+      const packRoot = resolve(baseDir, relativePath);
+      if (
+        (await pathExists(join(packRoot, BUNDLED_SKILL_PACK_SKILLS_DIRECTORY))) &&
+        (await findMissingBundledSkillPackPaths(packRoot)).length === 0
+      ) {
+        return packRoot;
+      }
+    }
+  }
+  return undefined;
+}
+
+async function materializeSeaBundledSkillPack(
+  options: ResolveBundledSkillRootsOptions,
+): Promise<string | undefined> {
+  const sea = getSeaModule();
+  if (!sea?.isSea()) return undefined;
+  const manifest = readSeaManifest(sea);
+  if (!manifest) return undefined;
+
+  const packsRoot = join(options.cliStorageRoot, BUNDLED_SKILL_PACK_DIRECTORY_NAME);
+  const targetRoot = join(packsRoot, manifest.hash);
+  if (await isSeedComplete(targetRoot, manifest.hash)) return targetRoot;
+
+  // 目录名就是内容 hash:写进唯一临时目录再 rename,rename 失败且目标已完整即并发赢家先到,
+  // 直接复用;其他失败回退到任一已完整的旧包(升级中途掉盘仍有技能可用)。
+  const temporaryRoot = `${targetRoot}.tmp-${process.pid}-${randomUUID()}`;
+  try {
+    await mkdir(temporaryRoot, { recursive: true });
+    for (const file of manifest.files) {
+      const bytes = Buffer.from(sea.getRawAsset(`${SEA_BUNDLED_SKILL_ASSET_PREFIX}${file.path}`));
+      if (hashBytes(bytes) !== file.sha256) {
+        throw new Error(`Bundled skill asset hash mismatch: ${file.path}`);
+      }
+      const outputPath = join(temporaryRoot, ...file.path.split("/"));
+      await mkdir(dirname(outputPath), { recursive: true });
+      await writeFile(outputPath, bytes, { mode: file.mode ?? 0o644 });
+    }
+    await writeFile(
+      join(temporaryRoot, SEED_MARKER_FILE),
+      JSON.stringify({ hash: manifest.hash, version: 1 }, null, 2),
+    );
+    await mkdir(packsRoot, { recursive: true });
+    await rename(temporaryRoot, targetRoot);
+    return targetRoot;
+  } catch (error) {
+    await rm(temporaryRoot, { force: true, recursive: true });
+    if (await isSeedComplete(targetRoot, manifest.hash)) return targetRoot;
+    const fallbackRoot = await findUsableSeededPack(packsRoot);
+    options.logger?.warn("Bundled skill pack seed degraded", {
+      error: error instanceof Error ? error.message : String(error),
+      fallbackRoot,
+      module: "bootstrap.bundled_skills",
+      targetRoot,
+    });
+    return fallbackRoot;
+  }
+}
+
+async function isSeedComplete(targetRoot: string, expectedHash: string): Promise<boolean> {
+  try {
+    const marker = JSON.parse(await readFile(join(targetRoot, SEED_MARKER_FILE), "utf8")) as {
+      hash?: unknown;
+    };
+    if (marker.hash !== expectedHash) return false;
+  } catch {
+    return false;
+  }
+  return (await findMissingBundledSkillPackPaths(targetRoot)).length === 0;
+}
+
+async function findUsableSeededPack(packsRoot: string): Promise<string | undefined> {
+  let entries;
+  try {
+    entries = await readdir(packsRoot, { withFileTypes: true });
+  } catch {
+    return undefined;
+  }
+  for (const entry of entries) {
+    if (!entry.isDirectory() || entry.name.includes(".tmp-")) continue;
+    const packRoot = join(packsRoot, entry.name);
+    try {
+      const marker = JSON.parse(await readFile(join(packRoot, SEED_MARKER_FILE), "utf8")) as {
+        hash?: unknown;
+      };
+      if (typeof marker.hash === "string" && (await isSeedComplete(packRoot, marker.hash))) {
+        return packRoot;
+      }
+    } catch {
+      // 损坏的旧缓存不参与降级,继续查找完整的技能包。
+    }
+  }
+  return undefined;
+}
+
+function readSeaManifest(sea: SeaModule): SeaBundledSkillManifest | undefined {
+  try {
+    const manifest = JSON.parse(
+      sea.getAsset(SEA_BUNDLED_SKILL_MANIFEST_ASSET_KEY, "utf8"),
+    ) as SeaBundledSkillManifest;
+    return manifest.version === 1 &&
+      typeof manifest.hash === "string" &&
+      Array.isArray(manifest.files)
+      ? manifest
+      : undefined;
+  } catch {
+    return undefined;
+  }
+}
+
+function getSeaModule(): SeaModule | undefined {
+  const getBuiltinModule = process.getBuiltinModule as ((id: "node:sea") => SeaModule) | undefined;
+  try {
+    return getBuiltinModule?.("node:sea");
+  } catch {
+    return undefined;
+  }
+}
+
+function hashBytes(bytes: Buffer): string {
+  return createHash("sha256").update(bytes).digest("hex");
+}

+ 11 - 13
apps/zcode-cli/packages/bootstrap/src/app/create-app.ts

@@ -69,10 +69,8 @@ import { createPluginFacadeForApp } from "./plugin-facade.js";
 import { resolvePluginRuntimeFeatures } from "./plugin-runtime-features.js";
 import { resolvePluginRuntimeFeatures } from "./plugin-runtime-features.js";
 import { createSessionFacade } from "./session-facade.js";
 import { createSessionFacade } from "./session-facade.js";
 import { resolveAppRuntimeConfig, runtimeConfigLogContext } from "./runtime-config.js";
 import { resolveAppRuntimeConfig, runtimeConfigLogContext } from "./runtime-config.js";
-import {
-  collectDynamicWorkflowDisabledSkillPaths,
-  DYNAMIC_WORKFLOW_GATED_COMMAND_NAMES,
-} from "./dynamic-workflow-gate.js";
+import { resolveBundledSkillRoots } from "./bundled-skills.js";
+import { collectDynamicWorkflowDisabledSkillPaths } from "./dynamic-workflow-gate.js";
 import { createWorkspaceHookRuntimeSecurity } from "./workspace-hook-trust.js";
 import { createWorkspaceHookRuntimeSecurity } from "./workspace-hook-trust.js";
 import { createScriptWorkflowBridge } from "./script-workflow-methods.js";
 import { createScriptWorkflowBridge } from "./script-workflow-methods.js";
 import {
 import {
@@ -220,6 +218,8 @@ export async function createZCodeApp(options: ZCodeAppOptions): Promise<ZCodeApp
       startupTimer,
       startupTimer,
       workingDirectory,
       workingDirectory,
     });
     });
+    // 随 CLI 内置的技能包(dynamic-workflows 等):不属于任何插件,用户无法停用或卸载。
+    const bundledSkillRoots = await resolveBundledSkillRoots({ cliStorageRoot, logger });
     const pluginSubagentProfiles = loadPluginAgentProfiles({
     const pluginSubagentProfiles = loadPluginAgentProfiles({
       logger,
       logger,
       plugins: pluginOutcome.plugins,
       plugins: pluginOutcome.plugins,
@@ -747,13 +747,13 @@ export async function createZCodeApp(options: ZCodeAppOptions): Promise<ZCodeApp
           ? (options.skillPort ??
           ? (options.skillPort ??
             createNodeSkillAdapter({
             createNodeSkillAdapter({
               extraRoots: configResult.config.skills.roots,
               extraRoots: configResult.config.skills.roots,
-              extraResolvedRoots: pluginOutcome.skillRoots,
+              extraResolvedRoots: [...pluginOutcome.skillRoots, ...bundledSkillRoots],
               disabledPaths: [
               disabledPaths: [
                 ...collectDisabledPaths(configResult.config.skillOverrides),
                 ...collectDisabledPaths(configResult.config.skillOverrides),
-                // 动态工作流灰度关闭时不提供 dynamic-workflows 技能:
+                // 动态工作流关闭时不提供 dynamic-workflows 技能:
                 // 十个工具都不在场,再让模型读到「怎么写工作流脚本」只会诱导它去调不存在的工具。
                 // 十个工具都不在场,再让模型读到「怎么写工作流脚本」只会诱导它去调不存在的工具。
                 ...(runtimeConfig.dynamicWorkflowEnabled === false
                 ...(runtimeConfig.dynamicWorkflowEnabled === false
-                  ? collectDynamicWorkflowDisabledSkillPaths(pluginOutcome.skillRoots)
+                  ? collectDynamicWorkflowDisabledSkillPaths(bundledSkillRoots)
                   : []),
                   : []),
               ],
               ],
             }))
             }))
@@ -792,18 +792,16 @@ export async function createZCodeApp(options: ZCodeAppOptions): Promise<ZCodeApp
       artifactStore,
       artifactStore,
       customCommandPromptResolver: async (text, resolverOptions) => {
       customCommandPromptResolver: async (text, resolverOptions) => {
         const builtinPrompt = resolveZCodeBuiltinPromptCommand(text, {
         const builtinPrompt = resolveZCodeBuiltinPromptCommand(text, {
+          // 动态工作流关闭时内置 `/workflow` 不得展开。目录侧已经把它从 `/` 面板
+          // 剔除,但用户仍可手打命令名,两条路径必须给出同一个结论。TUI 缺席时不设门禁;
+          // headless 按 --enable-workflow 显式取值,见 runtimeConfig 字段注释。
+          dynamicWorkflowEnabled: runtimeConfig.dynamicWorkflowEnabled,
           workingDirectory,
           workingDirectory,
         });
         });
         if (builtinPrompt !== undefined) {
         if (builtinPrompt !== undefined) {
           return builtinPrompt;
           return builtinPrompt;
         }
         }
         return await resolveZCodeCustomCommandPrompt(text, {
         return await resolveZCodeCustomCommandPrompt(text, {
-          // 动态工作流灰度关闭时 `/workflow` 不得展开成插件提示词。目录侧已经
-          // 把它从 `/` 面板剔除,但用户仍可手打命令名,两条路径必须给出同一个结论。
-          // 缺席(TUI、headless、workflow_child)不设门禁,见 runtimeConfig 字段注释。
-          ...(runtimeConfig.dynamicWorkflowEnabled === false
-            ? { disabledCommandNames: DYNAMIC_WORKFLOW_GATED_COMMAND_NAMES }
-            : {}),
           env: options.env,
           env: options.env,
           executionPort,
           executionPort,
           logger,
           logger,

+ 11 - 18
apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-gate.ts

@@ -1,34 +1,27 @@
 import { join } from "node:path";
 import { join } from "node:path";
 import type { SkillRoot } from "@zcode/contracts";
 import type { SkillRoot } from "@zcode/contracts";
+import { DYNAMIC_WORKFLOW_SKILL_NAME } from "./bundled-skills.js";
 
 
 /**
 /**
- * 动态工作流灰度门在 App 装配层的两处减法。
- * 工具面的减法在 core 的 registerBuiltInTools,`/` 目录的减法在 zcode-protocol/slash-commands.ts;
- * 这里只放「命令展开」和「技能发现」这两项需要 bootstrap 侧常量/路径推导的。
+ * App 装配层按动态工作流开关过滤配套技能。
+ * 工具面的减法在 core 的 registerBuiltInTools,`/` 目录与 `/workflow` 展开的减法分别在
+ * zcode-protocol/slash-commands.ts 与 builtin-prompt-command.ts;这里只放需要 bootstrap 侧路径推导的技能剔除。
  */
  */
 
 
-/** 灰度关闭时不允许展开的自定义命令名;`workflow` 由 zcode-guide 内置插件提供。 */
-export const DYNAMIC_WORKFLOW_GATED_COMMAND_NAMES: readonly string[] = ["workflow"];
-
-/** zcode-guide 插件里工作流编写指南技能的目录名(skills/<dir>/SKILL.md)。 */
-const DYNAMIC_WORKFLOW_SKILL_DIRECTORY_NAME = "dynamic-workflows";
-
 const SKILL_MANIFEST_FILE_NAME = "SKILL.md";
 const SKILL_MANIFEST_FILE_NAME = "SKILL.md";
 
 
 /**
 /**
- * 灰度关闭时要从技能发现中剔除的 SKILL.md 绝对路径。
+ * 动态工作流关闭时要从技能发现中剔除的 SKILL.md 绝对路径。
  *
  *
  * 为什么按路径而不是按 root 过滤:NodeSkillAdapter 只提供 `disabledPaths` 这一个剔除机制
  * 为什么按路径而不是按 root 过滤:NodeSkillAdapter 只提供 `disabledPaths` 这一个剔除机制
- * (config.json 的 `skill.<path>.enable=false` 走的也是它),而 zcode-guide 的其余技能
- * (配置指南、各种自诊断)与灰度无关,必须继续可见——整根 root 拿掉会连坐它们。
- *
- * 为什么不按 pluginId 精确匹配 zcode-guide:插件 id 形如 `<name>@<marketplace>`,随安装
- * 来源变化;而这里推导出的路径不存在时只是一个永不命中的 Set 成员,没有副作用。
+ * (config.json 的 `skill.<path>.enable=false` 走的也是它)。传入的是内置技能包的根
+ * (bundled-skills.ts),路径不存在时只是一个永不命中的 Set 成员,没有副作用;技能包日后再放
+ * 与动态工作流开关无关的技能时,它们也不会被连坐。
  */
  */
 export function collectDynamicWorkflowDisabledSkillPaths(
 export function collectDynamicWorkflowDisabledSkillPaths(
-  pluginSkillRoots: readonly SkillRoot[],
+  bundledSkillRoots: readonly SkillRoot[],
 ): string[] {
 ): string[] {
-  return pluginSkillRoots.map((root) =>
-    join(root.path, DYNAMIC_WORKFLOW_SKILL_DIRECTORY_NAME, SKILL_MANIFEST_FILE_NAME),
+  return bundledSkillRoots.map((root) =>
+    join(root.path, DYNAMIC_WORKFLOW_SKILL_NAME, SKILL_MANIFEST_FILE_NAME),
   );
   );
 }
 }

+ 157 - 30
apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-import.ts

@@ -8,9 +8,29 @@
 //   2. `port.amend` 在前驱结算之后构建缓存({@link buildImportedCache});
 //   2. `port.amend` 在前驱结算之后构建缓存({@link buildImportedCache});
 //   3. `port.resume` 见 `record.resumedFrom` 在场:崩溃后重建同一张表。
 //   3. `port.resume` 见 `record.resumedFrom` 在场:崩溃后重建同一张表。
 //
 //
-// 两处必须是**同一个纯函数**:修订 run 的 journal 只对「已到达的执行前缀」自含,未消费的导入
-// 靠重建补回。所以确定性不是风格偏好而是正确性前提——同一份 journal 状态必须给出同一张表
-// (无时间戳、无随机、遍历序全部来自 journal 的插入序)。
+// 两处共用同一套构建规则:修订 run 的 journal 只包含已消费的执行前缀,未消费的导入需要重建。
+// 已完成条目只由 journal 决定,遍历顺序取自 journal 的插入序;未完成 ask 的边界还依赖源转录。
+//
+// 一处例外要说清楚,它是这张表里**第一个不是 journal 纯函数**的数:在飞 ask 的接续
+// (`inFlight`)的边界取自**前驱会话此刻的消息条数**,不是 journal 里的某一列。
+//
+// 它在两次构建之间大体稳定,靠的是「前驱已经结算、没人再写它的会话」:
+//   - 提交时由 {@link AmendImportOptions.quietSessions} 保证(被取代的前驱刚 abort,driver 等它
+//     的 turn 落地;没等到的会话不接续);
+//   - 重建时前驱早已终态、本进程里没有它的 driver,天然无人在写,所以不带这个集合(缺席 =
+//     全部静默)。
+//
+// 但「大体」不是「一定」,而且**不必**是:两条路能让重建算出一个更大的 M——前驱被重新 resume
+// 过又写了几轮(被 supersede 的前驱不可 resume,所以只有「修订一个早已 stopped 的 run、之后
+// 又去 resume 它」构造得出),或者一条迟到的后台通知消息落进了那个会话。两者都只会让 M **变大**,
+// 而正确性不依赖 M 稳定:
+//   - 抄进去的那一侧已经把门关死了——`seedActorTranscript` 只往「空的、或只装着本会话种子
+//     消息的」目标里写(workflow-actor-transcript.ts 的性质 2)。后继一旦跑出自己的消息,更大的
+//     M 再送回来也一个字节都不会被写进去,所以绝无「前驱的消息被追加到本会话历史之后」这种
+//     静默错乱;
+//   - 后继还没跑出自己的消息时,更大的 M 抄来的是**同一条 ask 的更晚快照**,顺序仍由下标决定
+//     (种子 id 按 (会话, 下标) 纯确定,重抄是 upsert),所以那只是多带一点上文,不会变错。
+// 这条也是给**将来**每一个非 journal 事实的兜底:不必逐个去证明它们不会变大,复制点一次性堵死。
 //
 //
 // 唯一的 I/O 是 journal 读与转录条数读(两者都经窄端口注入),本模块自己不碰会话存储实现。
 // 唯一的 I/O 是 journal 读与转录条数读(两者都经窄端口注入),本模块自己不碰会话存储实现。
 
 
@@ -19,6 +39,7 @@ import type {
   ActorRecord,
   ActorRecord,
   ImportedActorCandidate,
   ImportedActorCandidate,
   ImportedAskEntry,
   ImportedAskEntry,
+  ImportedInFlightAsk,
   ImportedRunCache,
   ImportedRunCache,
   ImportedWorldEntry,
   ImportedWorldEntry,
   NodeRecord,
   NodeRecord,
@@ -118,7 +139,29 @@ interface AmendImportDeps {
 }
 }
 
 
 /**
 /**
- * 读前驱 journal,构建 {@link ImportedRunCache}。**纯确定**:同一份 journal 状态恒给出同一张表。
+ * 构建期能看到的**运行期旁证**,与 journal 事实相对。今天只有一条:哪些前驱会话已经写完了。
+ *
+ * 刻意不进 {@link AmendImportDeps}:deps 是装配(journal、转录面、logger),一个进程里从头到尾
+ * 是同一份;本对象是**这一次构建**才成立的观察,两次构建可以不同。混进 deps 会让「同一份 deps
+ * 必给同一张表」这句话变味。
+ */
+export interface AmendImportOptions {
+  /**
+   * 已**静默**(不再有在写的 turn)的前驱会话 id。只影响在飞 ask 的接续:完结前缀的边界是
+   * journal 事实,与会话此刻长不长无关。
+   *
+   * **缺席 = 全部静默**,而不是「全都不静默」。两个调用点各取一半:amend 刚 abort 掉在飞前驱,
+   * 被中止的 turn 可能仍在落最后几条消息,所以它带着 driver 算出的集合进来;resume 侧的重建
+   * ({@link rebuildImportedCacheForResume})面对的是一个早已结算、本进程里没有 driver 的前驱,
+   * 没有任何东西在写它的会话——缺席即此。方向反过来的话,重建出的表会比提交时那张少一个
+   * `inFlight`,而两侧必须是同一张表(见本文件头)。
+   */
+  quietSessions?: ReadonlySet<string>;
+}
+
+/**
+ * 读取前驱 journal 与转录状态,构建 {@link ImportedRunCache}。
+ * 已完成前缀由 journal 决定;未完成 ask 的接续还取决于源会话条数与静默状态。
  *
  *
  * 三道门按序(先门后建:门不过时一行都不必读):
  * 三道门按序(先门后建:门不过时一行都不必读):
  *   1. 前驱不存在 → `run_not_found`;
  *   1. 前驱不存在 → `run_not_found`;
@@ -128,13 +171,14 @@ interface AmendImportDeps {
  * 门 3 之所以**严格到全表**(而不是只检查真正会被导入的那些):无 marker 只有两种成因——
  * 门 3 之所以**严格到全表**(而不是只检查真正会被导入的那些):无 marker 只有两种成因——
  * marker 列引入之前写下的 journal,与 driver 侧记账失败——两者都意味着「这个 run 的边界记账不可信」,
  * marker 列引入之前写下的 journal,与 driver 侧记账失败——两者都意味着「这个 run 的边界记账不可信」,
  * 而不是「这一条恰好没记上」。逐条放行等于让一个记账半坏的前驱产出一张看似完整的表,
  * 而不是「这一条恰好没记上」。逐条放行等于让一个记账半坏的前驱产出一张看似完整的表,
- * 分歧时截断到一个错误的位置(模型看见的上文与 journal 记的边界悄悄错位)。dwf 未发布,
- * 无 marker 的 journal 只存在于开发机(整体拒绝,不做合成播种回退)。
+ * 分歧时截断到一个错误的位置(模型看见的上文与 journal 记的边界悄悄错位)。
+ * 缺少已完成 ask 边界的 journal 整体拒绝,不合成可能错误的转录边界。
  * 未完结的 ask 没有边界是**正常**的(它们从不进导入前缀),所以门只看 completed 行。
  * 未完结的 ask 没有边界是**正常**的(它们从不进导入前缀),所以门只看 completed 行。
  */
  */
 export async function buildImportedCache(
 export async function buildImportedCache(
   deps: AmendImportDeps,
   deps: AmendImportDeps,
   predecessorRunId: string,
   predecessorRunId: string,
+  options?: AmendImportOptions,
 ): Promise<BuildImportedCacheResult> {
 ): Promise<BuildImportedCacheResult> {
   const { actorTranscriptStore: transcripts, journal, logger } = deps;
   const { actorTranscriptStore: transcripts, journal, logger } = deps;
 
 
@@ -157,6 +201,7 @@ export async function buildImportedCache(
       ...(logger === undefined ? {} : { logger }),
       ...(logger === undefined ? {} : { logger }),
       nodes,
       nodes,
       predecessorRunId,
       predecessorRunId,
+      ...(options?.quietSessions === undefined ? {} : { quietSessions: options.quietSessions }),
       ...(transcripts === undefined ? {} : { transcripts }),
       ...(transcripts === undefined ? {} : { transcripts }),
     });
     });
     if (candidate !== undefined) actors.set(name, candidate);
     if (candidate !== undefined) actors.set(name, candidate);
@@ -215,17 +260,20 @@ async function buildActorCandidate(input: {
   logger?: Logger;
   logger?: Logger;
   nodes: NodeRecord[];
   nodes: NodeRecord[];
   predecessorRunId: string;
   predecessorRunId: string;
+  quietSessions?: ReadonlySet<string>;
   transcripts?: ActorTranscriptStore;
   transcripts?: ActorTranscriptStore;
 }): Promise<ImportedActorCandidate | undefined> {
 }): Promise<ImportedActorCandidate | undefined> {
-  const { actor, journal, logger, nodes, predecessorRunId, transcripts } = input;
+  const { actor, journal, logger, nodes, predecessorRunId, quietSessions, transcripts } = input;
   const name = actor.name!;
   const name = actor.name!;
 
 
   // persona 是引擎在 createActor 时同步落的冻结身份,所以正常必在场;缺席只可能是被外力
   // persona 是引擎在 createActor 时同步落的冻结身份,所以正常必在场;缺席只可能是被外力
   // 改写过的行。运行期比对没有比对物就无从谈起 persona 一致性——弃候选而不是拿 `{}` 顶。
   // 改写过的行。运行期比对没有比对物就无从谈起 persona 一致性——弃候选而不是拿 `{}` 顶。
   if (actor.persona === undefined) return undefined;
   if (actor.persona === undefined) return undefined;
 
 
-  const entries = completedAskPrefix(nodes, actor);
-  if (entries.length === 0) return undefined;
+  const { entries, next } = completedAskPrefix(nodes, actor);
+  // 既没有完结前缀、前缀后面也没有在飞的 ask:这个 actor 确实一点可导入的东西都没有。
+  // 早退省掉下面的链行走与一次转录读。
+  if (entries.length === 0 && next?.status !== "running") return undefined;
 
 
   const source = resolveTranscriptSource({
   const source = resolveTranscriptSource({
     actorName: name,
     actorName: name,
@@ -244,11 +292,13 @@ async function buildActorCandidate(input: {
     return undefined;
     return undefined;
   }
   }
 
 
-  const boundary = entries[entries.length - 1]!.messageBoundary;
-  if (
-    transcripts !== undefined &&
-    !(await honorsBoundary(transcripts, source.sessionId, boundary))
-  ) {
+  // 空前缀的边界是 0(没有任何完结交换,接续位置只能从 0 往后算)。
+  const boundary = entries.length === 0 ? 0 : entries[entries.length - 1]!.messageBoundary;
+  // 转录条数**只读一次**:源诚实性检查与在飞 ask 的接续位置用的是同一个数。读两次等于给
+  // 同一个事实开两个观察窗,而它们之间可以不相等。
+  const messageCount =
+    transcripts === undefined ? undefined : await countSource(transcripts, source.sessionId);
+  if (transcripts !== undefined && (messageCount === undefined || messageCount < boundary)) {
     logger?.warn?.(
     logger?.warn?.(
       "Dynamic workflow amend: transcript source shorter than boundary, import dropped",
       "Dynamic workflow amend: transcript source shorter than boundary, import dropped",
       {
       {
@@ -262,23 +312,97 @@ async function buildActorCandidate(input: {
     return undefined;
     return undefined;
   }
   }
 
 
+  const inFlight = resolveInFlightAsk({
+    actor,
+    boundary,
+    ...(logger === undefined ? {} : { logger }),
+    ...(messageCount === undefined ? {} : { messageCount }),
+    ...(next === undefined ? {} : { next }),
+    predecessorRunId,
+    ...(quietSessions === undefined ? {} : { quietSessions }),
+    sourceSessionId: source.sessionId,
+  });
+  // 前缀为空且接续没谈成:这个候选一个字节都带不走,收下它只会让引擎为一张空表建会话。
+  if (entries.length === 0 && inFlight === undefined) return undefined;
+
   return {
   return {
     persona: actor.persona,
     persona: actor.persona,
     entries,
     entries,
+    ...(inFlight === undefined ? {} : { inFlight }),
     transcriptSourceSessionId: source.sessionId,
     transcriptSourceSessionId: source.sessionId,
     ...(source.resolvedModel === undefined ? {} : { resolvedModel: source.resolvedModel }),
     ...(source.resolvedModel === undefined ? {} : { resolvedModel: source.resolvedModel }),
   };
   };
 }
 }
 
 
 /**
 /**
- * 该 actor 的**最长全 completed ask 前缀**(按 actorSeq 0..k 连续)。
+ * 前驱停下时**还在飞**的那条 ask。五个条件缺一不可:
+ *
+ *   1. 紧接前缀的那个位置上有一行,且它是 `running`——被取消的 ask 保留 running 行,所以停掉的
+ *      run 也有;`failed` 与序号空洞都不是「还在飞」,它们只是前缀停下的另外两种理由;
+ *   2. 转录源就是前驱**自己**那一行的会话:那半场未完的对话只存在于这里,从更早祖先解析出的
+ *      源只承载完整前缀(chain 上每一跳都只保证前缀等价);
+ *   3. 数得出会话条数(有转录面且读得到)——没有数就没有接续位置,driver 也无从截断;
+ *   4. 该会话已经**静默**,见 {@link AmendImportOptions.quietSessions};
+ *   5. 条数**严格大于**前缀边界。排队却从未派发的 ask 没有多出来的转录可带,而一个等于边界
+ *      (或为 0)的 messageCount 会让 driver 播种出一段「其实就是前缀」甚至空无一物的种子,
+ *      却把 actor 标记成接续过——分歧判定与转录内容随之对不上。
+ *
+ * 任一条不成立都只是**不接续**(完结前缀照旧导入),与本模块「降级而不失败」的总基调一致。
+ */
+function resolveInFlightAsk(input: {
+  actor: ActorRecord;
+  boundary: number;
+  logger?: Logger;
+  messageCount?: number;
+  next?: NodeRecord;
+  predecessorRunId: string;
+  quietSessions?: ReadonlySet<string>;
+  sourceSessionId: string;
+}): ImportedInFlightAsk | undefined {
+  const { actor, boundary, logger, messageCount, next, quietSessions, sourceSessionId } = input;
+  if (next === undefined || next.status !== "running") return undefined;
+
+  const drop = (reason: string): undefined => {
+    logger?.info?.("Dynamic workflow amend: in-flight ask not carried", {
+      actorName: actor.name,
+      event: "dynamic_workflow.amend.in_flight_dropped",
+      module: "bootstrap.app",
+      reason,
+      runId: input.predecessorRunId,
+      sessionId: sourceSessionId,
+    });
+    return undefined;
+  };
+
+  if (actor.sessionId === undefined || actor.sessionId !== sourceSessionId) {
+    return drop("transcript_source_is_ancestor");
+  }
+  if (messageCount === undefined) return drop("no_transcript_count");
+  // 缺席 = 全部静默(见 {@link AmendImportOptions.quietSessions})。
+  if (quietSessions !== undefined && !quietSessions.has(sourceSessionId)) {
+    return drop("session_not_quiescent");
+  }
+  if (messageCount <= boundary) return drop("no_transcript_beyond_prefix");
+
+  return { inputHash: next.inputHash, messageBoundary: messageCount };
+}
+
+/**
+ * 该 actor 的**最长全 completed ask 前缀**(按 actorSeq 0..k 连续),外加**紧接其后**那一行。
  *
  *
  * 前缀在第一个非 completed 处停死,三种停法同一处理:失败、崩溃中(running)、序号空洞。
  * 前缀在第一个非 completed 处停死,三种停法同一处理:失败、崩溃中(running)、序号空洞。
  * 失败的 ask 对新 run **无约束力**(模型有随机性,修订常常就是为了越过一次失败),所以它自己
  * 失败的 ask 对新 run **无约束力**(模型有随机性,修订常常就是为了越过一次失败),所以它自己
  * 不导入;但跳过它去导入其后的条目会走私上下文——被跳过那一轮的问答仍在源会话转录里,
  * 不导入;但跳过它去导入其后的条目会走私上下文——被跳过那一轮的问答仍在源会话转录里,
  * 而缓存却声称它没发生过。停在第一个非 completed 处是唯一自洽的读法。
  * 而缓存却声称它没发生过。停在第一个非 completed 处是唯一自洽的读法。
+ *
+ * `next` 就是**让前缀停下的**那一行(空洞时缺席)。它与前缀同来同走,因为「在飞的那条 ask」
+ * 按定义正是这一行:另起一次遍历去找 `actorSeq === entries.length` 的行,等于把「紧接前缀」
+ * 这个坐标在两处各算一次。
  */
  */
-function completedAskPrefix(nodes: NodeRecord[], actor: ActorRecord): ImportedAskEntry[] {
+function completedAskPrefix(
+  nodes: NodeRecord[],
+  actor: ActorRecord,
+): { entries: ImportedAskEntry[]; next?: NodeRecord } {
   const bySeq = new Map<number, NodeRecord>();
   const bySeq = new Map<number, NodeRecord>();
   for (const node of nodes) {
   for (const node of nodes) {
     if (node.kind !== "ask") continue;
     if (node.kind !== "ask") continue;
@@ -290,7 +414,9 @@ function completedAskPrefix(nodes: NodeRecord[], actor: ActorRecord): ImportedAs
   const entries: ImportedAskEntry[] = [];
   const entries: ImportedAskEntry[] = [];
   for (let seq = 0; ; seq++) {
   for (let seq = 0; ; seq++) {
     const node = bySeq.get(seq);
     const node = bySeq.get(seq);
-    if (node === undefined || node.status !== "completed") break;
+    if (node === undefined || node.status !== "completed") {
+      return { entries, ...(node === undefined ? {} : { next: node }) };
+    }
     // 边界必在场:门 3 已对整个前驱把关,所以这里不是乐观读而是不变式的兑现。
     // 边界必在场:门 3 已对整个前驱把关,所以这里不是乐观读而是不变式的兑现。
     const entry: ImportedAskEntry = {
     const entry: ImportedAskEntry = {
       inputHash: node.inputHash,
       inputHash: node.inputHash,
@@ -300,7 +426,6 @@ function completedAskPrefix(nodes: NodeRecord[], actor: ActorRecord): ImportedAs
     if (node.stats !== undefined) entry.stats = node.stats;
     if (node.stats !== undefined) entry.stats = node.stats;
     entries.push(entry);
     entries.push(entry);
   }
   }
-  return entries;
 }
 }
 
 
 /**
 /**
@@ -344,25 +469,23 @@ function resolveTranscriptSource(input: {
 }
 }
 
 
 /**
 /**
- * 源会话是否真兑现得了边界(消息数 ≥ 边界)。
+ * 源会话此刻的消息条数;读失败回 `undefined`。
  *
  *
- * 这道检查把 driver 的**大声失败**语义与构建期的**降级**语义接在一起:driver 的
- * `seedActorTranscript` 对短会话抛 `DriverError`(corruption 级,见那边的性质 3);构建期缺少转录时则降级为全新重跑。两者都对,但作用域不同——**可预见的**缺料(会话被清理 / 被截断)
- * 应当在构建期就把候选弃掉,driver 那一侧的失败因此退化成真正不该发生时的兜底。
+ * 两个读者共用这一次读取(见 {@link buildActorCandidate}):
+ * - 检查源会话是否达到已完成前缀的边界。条数不足或无法读取时,构建器丢弃该候选,
+ *   让后继重新执行;driver 复制转录时仍会拒绝短于边界的源,防止写入不完整的上下文。
+ * - 计算未完成 ask 的接续位置(见 {@link resolveInFlightAsk})。
  *
  *
- * 读失败(会话不存在等)同样按「兑现不了」处理:构建器不为会话存储的错误分类负责,而任何
- * 读不到的源都不是可用的源。
+ * 条数口径必须与 driver 记账及 core 历史恢复一致,均使用同一消息存储接口。
  */
  */
-async function honorsBoundary(
+async function countSource(
   transcripts: ActorTranscriptStore,
   transcripts: ActorTranscriptStore,
   sessionId: string,
   sessionId: string,
-  boundary: number,
-): Promise<boolean> {
+): Promise<number | undefined> {
   try {
   try {
-    const messages = await transcripts.messages({ sessionID: sessionId as SessionId });
-    return messages.length >= boundary;
+    return (await transcripts.messages({ sessionID: sessionId as SessionId })).length;
   } catch {
   } catch {
-    return false;
+    return undefined;
   }
   }
 }
 }
 
 
@@ -409,6 +532,10 @@ function buildWorldQueues(nodes: NodeRecord[]): ReadonlyMap<string, ImportedWorl
  * 所以这里连门的三个理由都不区分:对 resume 而言 `run_not_found`(前驱被清理)与
  * 所以这里连门的三个理由都不区分:对 resume 而言 `run_not_found`(前驱被清理)与
  * `missing_boundaries` 是同一件事——「这次没有缓存可用」。前驱 journal 因此是修订 run 的**存续
  * `missing_boundaries` 是同一件事——「这次没有缓存可用」。前驱 journal 因此是修订 run 的**存续
  * 依赖,但只是加速结构**:丢了变贵,不变错。记一条 info 便于事后解释账单。
  * 依赖,但只是加速结构**:丢了变贵,不变错。记一条 info 便于事后解释账单。
+ *
+ * **不带 {@link AmendImportOptions.quietSessions}**:走到这里的前驱早已终态,本进程里没有它的
+ * driver,没有任何东西在写它的会话。带一个空集合进来会让重建出的表比提交时那张少一个
+ * `inFlight`,而两侧必须是同一张表(见本文件头)。
  */
  */
 export async function rebuildImportedCacheForResume(
 export async function rebuildImportedCacheForResume(
   deps: AmendImportDeps,
   deps: AmendImportDeps,

+ 49 - 0
apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-elapsed.ts

@@ -0,0 +1,49 @@
+// dwf run 的活动时长,用于完成卡的「时间」格。
+// 本 run 的每次启动,以及沿 `resumedFrom` 上溯的每个前驱,都按各自活动区间求和;
+// 停止或进程退出后、下次 resume 前的空档不计入。
+//
+// 不能只用当前注册表条目的 `completedAt - startedAt`:resume 或修订会重置该时钟,
+// 从而漏掉之前的运行时间。时长与 token 用量都应覆盖整条 lineage。
+//
+// 事件日志已记录每段区间的起点和最后活动时刻,因此只需读取求和,无须额外持久化。
+
+import type { JournalStorePort } from "@zcode/dynamic-workflow";
+import { supportsRunLifeSpans } from "./dynamic-workflow-run-journal.js";
+
+/**
+ * lineage 上溯的跳数上限。一次修订一跳,链条实际是个位数;上限只为「行里的 `resumedFrom`
+ * 被外力写成一条长链」留一道闸——读一条 run 的时长不该扫过任意多行。
+ */
+const LINEAGE_HOP_LIMIT = 64;
+
+/**
+ * 本 run 及其 lineage 的活动时长(毫秒),或 `undefined`(无任何一世的证据)。
+ *
+ * `undefined` 与 `0` 是两件事:前者是「journal 说不出话」(读面不在场、run 的事件早于本记账、
+ * 行已被清理),调用方据此退回自己观察到的那一世;后者是「确有一世,但它的时长不足 1 毫秒」。
+ *
+ * 防环不是防御性编程的摆设:`resumedFrom` 是建 run 那一刻写死的元数据,理论上不成环,但这个
+ * 循环的终止条件依赖的是**库里的数据**而不是本进程的逻辑——一条被外力写成自指的行会把一次
+ * 读快照变成死循环,而快照读在后台追踪器的轮询路径上。
+ */
+export function runLineageActiveMs(journal: JournalStorePort, runId: string): number | undefined {
+  if (!supportsRunLifeSpans(journal)) return undefined;
+  let total = 0;
+  let sawLife = false;
+  let cursor: string | undefined = runId;
+  const visited = new Set<string>();
+  for (let hop = 0; cursor !== undefined && hop < LINEAGE_HOP_LIMIT; hop += 1) {
+    if (visited.has(cursor)) break;
+    visited.add(cursor);
+    for (const life of journal.listRunLifeSpans(cursor)) {
+      sawLife = true;
+      // 钳到非负:两个时刻同源于 `dwf_event.time_created`,但那是**墙钟**——一次系统对时可以
+      // 让「最后一条」早于「第一条」。负数会从总和里减掉别的世的真实时长,那比丢掉这一世更糟。
+      total += Math.max(0, life.lastActivityAt - life.startedAt);
+    }
+    // 只上溯 lineage,不下溯 supersededBy:修订是「同一件工作的下一版」,而被替代的前驱的活
+    // 是这一版的底座;反方向的后继与本 run 的时长无关(它有自己的卡)。
+    cursor = journal.getRun(cursor)?.resumedFrom;
+  }
+  return sawLife ? total : undefined;
+}

+ 14 - 0
apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-journal.ts

@@ -104,6 +104,20 @@ export function supportsRunEnumeration(
 export interface DynamicWorkflowIntrospectableJournal
 export interface DynamicWorkflowIntrospectableJournal
   extends JournalStorePort, DwfRunIntrospectionQueries {}
   extends JournalStorePort, DwfRunIntrospectionQueries {}
 
 
+/**
+ * journal 是否带「每一世的活动区间」读面(完成卡的时长口径)。
+ *
+ * **独立探测,不并入 {@link supportsRunIntrospection} 的四条**:那四条一起探是因为它们共同
+ * 支撑两个工具的可用性,而这一条只支撑一个数字。缺它的后果是时长退回「本世墙钟」——一个更
+ * 保守的答案,不是一个坏掉的工具,所以它不该连坐 `GetWorkflowRun` 的可用性(引擎自带的内存
+ * journal 就不提供它,而内存 journal 里的 run 本来也活不过进程)。
+ */
+export function supportsRunLifeSpans(
+  journal: JournalStorePort,
+): journal is JournalStorePort & Pick<DwfRunIntrospectionQueries, "listRunLifeSpans"> {
+  return typeof (journal as Partial<DwfRunIntrospectionQueries>).listRunLifeSpans === "function";
+}
+
 /**
 /**
  * journal 是否带 run 内省查询。**四条一起探**:能力是整体的(列表要 listRuns,详情要另外三条),
  * journal 是否带 run 内省查询。**四条一起探**:能力是整体的(列表要 listRuns,详情要另外三条),
  * 部分在场的实现只会让某一个工具在运行时炸掉,而不是可见地降级。
  * 部分在场的实现只会让某一个工具在运行时炸掉,而不是可见地降级。

+ 65 - 16
apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-launch.ts

@@ -45,8 +45,11 @@ import {
   type RunLaunch,
   type RunLaunch,
 } from "./dynamic-workflow-run-launch-anchor.js";
 } from "./dynamic-workflow-run-launch-anchor.js";
 import { resolveWorkflowConcurrencyCeiling } from "./workflow-concurrency-ceiling.js";
 import { resolveWorkflowConcurrencyCeiling } from "./workflow-concurrency-ceiling.js";
+import type { ActorSessionQuiescence } from "./workflow-driver-quiescence.js";
 import { createAgentRuntimeWorkflowDriver, mintActorSessionId } from "./workflow-driver.js";
 import { createAgentRuntimeWorkflowDriver, mintActorSessionId } from "./workflow-driver.js";
 import type { WorkflowEscalationRegistry } from "./workflow-escalation-registry.js";
 import type { WorkflowEscalationRegistry } from "./workflow-escalation-registry.js";
+import type { WorkflowRunControl } from "./workflow-run-control.js";
+import { createWorkflowRunSeatGate } from "./workflow-seat-gate.js";
 import type { DynamicWorkflowRunServiceDeps } from "./dynamic-workflow-run-service.js";
 import type { DynamicWorkflowRunServiceDeps } from "./dynamic-workflow-run-service.js";
 
 
 /** 适配包内校验器到引擎的 ValidateFn 契约(launch 是 runWorkflowScript 的唯一调用点)。 */
 /** 适配包内校验器到引擎的 ValidateFn 契约(launch 是 runWorkflowScript 的唯一调用点)。 */
@@ -113,6 +116,20 @@ interface LaunchDynamicWorkflowRunInput {
    * 索引,两条入口各持一张会让 resume 之后的 run 作答不到自己刚提的问题。
    * 索引,两条入口各持一张会让 resume 之后的 run 作答不到自己刚提的问题。
    */
    */
   escalationRegistry: WorkflowEscalationRegistry;
   escalationRegistry: WorkflowEscalationRegistry;
+  /**
+   * 本 run 的活体控制面。由 run
+   * service 按**注册表条目**造一个(submit / amend / resume 三条入口都造),本函数在这里把它的
+   * 两端接上:harness 负责 `bind(engine)`,本函数负责 `bindSeatGate`。
+   *
+   * 缺席即这次启动没有控制面(如 snippet 执行)——run 照常跑完,只是上界中途改不了。
+   */
+  control?: WorkflowRunControl;
+  /**
+   * 接住本次 launch 造出来的 driver 的**会话静默探针**(workflow-driver-quiescence.ts)。
+   * 三条入口都传同一件事:把它挂到这个 run 的注册表条目上,好让将来修订它的那次 amend
+   * 问得着「前驱的会话写完了没有」。原样下传,本文件不读它。
+   */
+  onQuiescenceProbe?: (probe: ActorSessionQuiescence) => void;
 }
 }
 
 
 /**
 /**
@@ -126,6 +143,7 @@ export function launchDynamicWorkflowRun(
     args,
     args,
     caps,
     caps,
     compiled,
     compiled,
+    control,
     cwd,
     cwd,
     deps,
     deps,
     escalationRegistry,
     escalationRegistry,
@@ -139,6 +157,11 @@ export function launchDynamicWorkflowRun(
     toolCallId,
     toolCallId,
   } = input;
   } = input;
   const childSpawn = dynamicWorkflowChildSpawn();
   const childSpawn = dynamicWorkflowChildSpawn();
+  // 本 run 自己上界的**第二个**执行点:调度器管「还能不能再派一个 ask」,闸门管「已经在跑的那些下一次请求能不能发出去」。
+  // 起点就是这次启动的 caps(submit 是钳过的请求值,resume 是 journal 行里的那一份),所以一个
+  // 从未被 retune 过的 run 永远走闸门的快路径——不发事件、不持票、与从前逐字相同。
+  const seatGate = createWorkflowRunSeatGate({ limit: caps.maxConcurrency });
+  control?.bindSeatGate(seatGate);
   // 锚点:submit 给的(本次建 run)或 journal 里的(resume)。升级前的 run 两边都没有 → 缺席,
   // 锚点:submit 给的(本次建 run)或 journal 里的(resume)。升级前的 run 两边都没有 → 缺席,
   // 进度事件不带 launchInputId,子代理不上报。
   // 进度事件不带 launchInputId,子代理不上报。
   const launch = input.launch ?? readRunLaunchAnchor(deps.journal, runId);
   const launch = input.launch ?? readRunLaunchAnchor(deps.journal, runId);
@@ -222,8 +245,15 @@ export function launchDynamicWorkflowRun(
     // 进程级并发治理器的窄端口:在场时 driver 给每个
     // 进程级并发治理器的窄端口:在场时 driver 给每个
     // actor runtime 一个请求级准入端口(下面 runtimeFactory 原样下传);缺席即 actor 不受闸门约束。
     // actor runtime 一个请求级准入端口(下面 runtimeFactory 原样下传);缺席即 actor 不受闸门约束。
     ...(deps.concurrency === undefined ? {} : { concurrency: deps.concurrency }),
     ...(deps.concurrency === undefined ? {} : { concurrency: deps.concurrency }),
+    // 本 run 的座位闸门:driver 把每个 actor 的准入端口包进它,并把 ask 的起止喂给它
+    // (startAsk 与引擎的 `node-settled`)。
+    seatGate,
     // 测试注入的 driver 时钟(故障矩阵);生产缺席,driver 走真时间。
     // 测试注入的 driver 时钟(故障矩阵);生产缺席,driver 走真时间。
     ...(deps.driverClock === undefined ? {} : { clock: deps.driverClock }),
     ...(deps.driverClock === undefined ? {} : { clock: deps.driverClock }),
+    // 会话静默探针的回填口(见入参字段注释):driver 在构造时调一次。
+    ...(input.onQuiescenceProbe === undefined
+      ? {}
+      : { onQuiescenceProbe: input.onQuiescenceProbe }),
     runtimeFactory: async ({
     runtimeFactory: async ({
       sessionId,
       sessionId,
       actor,
       actor,
@@ -331,6 +361,9 @@ export function launchDynamicWorkflowRun(
     // 锚点只在建 run 那一世落 journal(引擎侧的门),resume 时传它无害。
     // 锚点只在建 run 那一世落 journal(引擎侧的门),resume 时传它无害。
     ...(launch === undefined ? {} : { launch }),
     ...(launch === undefined ? {} : { launch }),
     signal,
     signal,
+    // 控制面与 signal 同一条缝:那个是「停下这个 run」,这个是「改这个 run 的一项设置」。
+    // harness 在引擎构造好的同一同步片里 bind(harness.ts),所以 run 从第一条事件起就可被改。
+    ...(control === undefined ? {} : { control }),
     validate: validateFn,
     validate: validateFn,
   });
   });
 }
 }
@@ -556,17 +589,12 @@ export function toProtocolEvent(sequence: number, event: RunEvent): DynamicWorkf
 }
 }
 
 
 /**
 /**
- * RunEvent → 会话事件载荷。`payload` 与 {@link toProtocolEvent} 逐字节相同(一次序列化、
- * 两个消费者),另加两个**派生字段**。
- *
- * 派生字段放在 payload **之外**是有意的:payload 必须保持"引擎发了什么"的原样,否则事件日志
- * 就在展示我们的加工品。两个字段各自都不是可观察事实,但缺了它们下游只能自己重造一份契约:
+ * RunEvent → 会话事件载荷。`payload` 与 {@link toProtocolEvent} 使用同一次序列化,
+ * 派生字段放在 payload 之外,保留引擎事件原文。
  *
  *
- *   - `actorSessionId`:Boundary C 的 actor-created 不带会话 id(它由 driver 铸造)。让
- *     renderer 按 (runId, actorRef) 自己拼,等于把 sanitize 契约复制进 UI 层;这里调用
- *     铸造它的**同一个函数**,两边不可能漂移(测试钉住相等)。
- *   (曾经还有第二个派生字段 `spentTokens`:老的 budget-updated 只发剩余量。现在 usage-updated
- *   自己携带已花总量,与 dwf_run.spent_tokens 在同一同步步骤产生,不再需要派生。)
+ * `actorSessionId` 通过与 driver 相同的生成函数获取,避免 renderer 重复实现会话 ID 规则。
+ * `actor-created` 和带 actor 的 `node-dispatched` 都补充该字段,使运行中实例被收进有界表时,
+ * 仍能关联到对应的子代理会话。进程并发上限和子代理来源按下方各自的事件条件补充。
  */
  */
 export function toProgressPayload(input: {
 export function toProgressPayload(input: {
   event: RunEvent;
   event: RunEvent;
@@ -578,11 +606,14 @@ export function toProgressPayload(input: {
   /** 修订 run 的前驱;只在 `run-started` 上派生(卡片的「调整自 run X」)。 */
   /** 修订 run 的前驱;只在 `run-started` 上派生(卡片的「调整自 run X」)。 */
   resumedFrom?: string;
   resumedFrom?: string;
   /**
   /**
-   * 铸造这条载荷那一刻的进程并发天花板;只在 `run-started` 上派生
+   * 铸造这条载荷那一刻的进程并发天花板;在 `run-started` 与 `run-caps-changed` 两种事件上派生。
    *
    *
    * 引擎事件只带它自己的 `caps.maxConcurrency`,而「这个数值不值得显示」要拿它和天花板比——
    * 引擎事件只带它自己的 `caps.maxConcurrency`,而「这个数值不值得显示」要拿它和天花板比——
    * 天花板是宿主事实(机器核数),引擎既看不见也不该看见。投影侧据 `caps.maxConcurrency <
    * 天花板是宿主事实(机器核数),引擎既看不见也不该看见。投影侧据 `caps.maxConcurrency <
    * concurrencyCeiling` 记下本 run 的自有上界,UI 的并发 chip 再取 min(共享 cap, 本 run 上界)。
    * concurrencyCeiling` 记下本 run 的自有上界,UI 的并发 chip 再取 min(共享 cap, 本 run 上界)。
+   *
+   * 一次就地 retune 发的 `run-caps-changed` 带着**新的** caps,判据却是同一条:低于天花板就写下
+   * 上界、等于天花板就把它清掉(= 解除限制)。所以两种事件必须拿到同一个天花板,也就是这一个。
    */
    */
   concurrencyCeiling?: number;
   concurrencyCeiling?: number;
   /**
   /**
@@ -604,6 +635,7 @@ export function toProgressPayload(input: {
     subagentModel,
     subagentModel,
   } = input;
   } = input;
   const protocolEvent = toProtocolEvent(sequence, event);
   const protocolEvent = toProtocolEvent(sequence, event);
+  const actorRef = actorSessionRefOf(event);
   return {
   return {
     runId,
     runId,
     ...(toolCallId === undefined ? {} : { toolCallId }),
     ...(toolCallId === undefined ? {} : { toolCallId }),
@@ -616,6 +648,8 @@ export function toProgressPayload(input: {
     // `run-started` 多带 `resumedFrom`:引擎事件不带它(引擎不读 lineage),但卡片要画这条边。
     // `run-started` 多带 `resumedFrom`:引擎事件不带它(引擎不读 lineage),但卡片要画这条边。
     // 同一条缝里还多带 `concurrencyCeiling`:引擎只发自己的 caps,而「这个上界是不是默认值」
     // 同一条缝里还多带 `concurrencyCeiling`:引擎只发自己的 caps,而「这个上界是不是默认值」
     // 要拿它和宿主的天花板比(见上面的字段注释)。两者互不相关,各自缺席即各自不出。
     // 要拿它和宿主的天花板比(见上面的字段注释)。两者互不相关,各自缺席即各自不出。
+    // `run-caps-changed` 走**同一条**缝、同一个天花板:一次就地 retune 之后读面要靠它判断新上界
+    // 该写下还是该清掉,缺了它这条事件就只是两个没有标尺的数。
     payload:
     payload:
       event.type === "run-settled" && isResumableSettlement(event.status, event.stopReason)
       event.type === "run-settled" && isResumableSettlement(event.status, event.stopReason)
         ? { ...protocolEvent.payload, resumable: true }
         ? { ...protocolEvent.payload, resumable: true }
@@ -626,12 +660,15 @@ export function toProgressPayload(input: {
               ...(concurrencyCeiling === undefined ? {} : { concurrencyCeiling }),
               ...(concurrencyCeiling === undefined ? {} : { concurrencyCeiling }),
               ...(subagentModel === undefined ? {} : { subagentModel }),
               ...(subagentModel === undefined ? {} : { subagentModel }),
             }
             }
-          : protocolEvent.payload,
+          : event.type === "run-caps-changed"
+            ? {
+                ...protocolEvent.payload,
+                ...(concurrencyCeiling === undefined ? {} : { concurrencyCeiling }),
+              }
+            : protocolEvent.payload,
     ...(protocolEvent.truncated ? { truncated: true } : {}),
     ...(protocolEvent.truncated ? { truncated: true } : {}),
-    ...(event.type === "actor-created"
-      ? { actorSessionId: mintActorSessionId(runId, event.actor) }
-      : {}),
-    // 第三个派生字段:下游只在这两种事件上
+    ...(actorRef === undefined ? {} : { actorSessionId: mintActorSessionId(runId, actorRef) }),
+    // 第三个派生字段:埋点事实层只在这两种事件上
     // 需要锚点——actor-created 登记子代理归属,run-settled 结算该 run 全部子代理。
     // 需要锚点——actor-created 登记子代理归属,run-settled 结算该 run 全部子代理。
     ...((event.type === "actor-created" || event.type === "run-settled") &&
     ...((event.type === "actor-created" || event.type === "run-settled") &&
     launchInputId !== undefined
     launchInputId !== undefined
@@ -639,3 +676,15 @@ export function toProgressPayload(input: {
       : {}),
       : {}),
   };
   };
 }
 }
+
+/**
+ * 这条事件点名了哪个子代理(要补 `actorSessionId` 的那个 ref),没点名即 undefined。
+ *
+ * 两种事件:`actor-created`(子代理的出生),以及带 `actor` 的 `node-dispatched`(ask 派发时重复出生事实)。
+ * world-read 的派发不带 `actor`,因此不补——它没有转录可开。
+ */
+function actorSessionRefOf(event: RunEvent): ActorRef | undefined {
+  if (event.type === "actor-created") return event.actor;
+  if (event.type === "node-dispatched") return event.actor;
+  return undefined;
+}

+ 27 - 0
apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-observation.ts

@@ -27,9 +27,12 @@ import type {
   WorkflowErrorJson,
   WorkflowErrorJson,
 } from "@zcode/dynamic-workflow";
 } from "@zcode/dynamic-workflow";
 import { artifactsOf } from "./dynamic-workflow-run-artifact-projection.js";
 import { artifactsOf } from "./dynamic-workflow-run-artifact-projection.js";
+import { runLineageActiveMs } from "./dynamic-workflow-run-elapsed.js";
 import { readRunScriptPath, readRunSubagentModel } from "./dynamic-workflow-run-launch-anchor.js";
 import { readRunScriptPath, readRunSubagentModel } from "./dynamic-workflow-run-launch-anchor.js";
 import { resolveDynamicWorkflowRunLabel } from "./dynamic-workflow-run-label.js";
 import { resolveDynamicWorkflowRunLabel } from "./dynamic-workflow-run-label.js";
 import { lineageFields, supersededByOf } from "./dynamic-workflow-run-lineage.js";
 import { lineageFields, supersededByOf } from "./dynamic-workflow-run-lineage.js";
+import type { ActorSessionQuiescence } from "./workflow-driver-quiescence.js";
+import type { WorkflowRunControl } from "./workflow-run-control.js";
 
 
 /**
 /**
  * 产物归并住在 dynamic-workflow-run-artifact-projection.ts(本文件顶到 oxlint 的 400 行上限)。
  * 产物归并住在 dynamic-workflow-run-artifact-projection.ts(本文件顶到 oxlint 的 400 行上限)。
@@ -57,6 +60,16 @@ export interface RunRegistryEntry {
    * submit / amend 落值,**resume 不落**——那条路沿用 journal 记录里的 caps,而它的行早就在了。
    * submit / amend 落值,**resume 不落**——那条路沿用 journal 记录里的 caps,而它的行早就在了。
    */
    */
   maxConcurrency?: number;
   maxConcurrency?: number;
+  /**
+   * 本 run 的活体控制面。与
+   * {@link controller} 并列而非合并:那个是「停下这个 run」的唯一通道,这个是「改这个 run 的一项
+   * 设置」的唯一通道,两者的收件人(harness 的 signal / 引擎与座位闸门)也不是同一个。
+   *
+   * 三条建条目的路都造一个(submit / amend / resume),launch 把它的两端接上。条目在、句柄的
+   * `setMaxConcurrency` 却回 false,就是「run 在这两步之间结算了」——`retuneConcurrency` 据此
+   * 回 `not_live`。
+   */
+  control?: WorkflowRunControl;
   /**
   /**
    * 本 run 的子代理模型(`run-launched` 事件上那个规范 picker 串
    * 本 run 的子代理模型(`run-launched` 事件上那个规范 picker 串
    * `providerId/modelId[$reasoningLevel]` 的内存副本)。
    * `providerId/modelId[$reasoningLevel]` 的内存副本)。
@@ -82,6 +95,15 @@ export interface RunRegistryEntry {
    * resume 的行早就在了。
    * resume 的行早就在了。
    */
    */
   inheritedTokens?: number;
   inheritedTokens?: number;
+  /**
+   * 本 run 的 driver 交出来的**会话静默探针**(workflow-driver-quiescence.ts)。driver 构造时
+   * 回填,所以刚建好的条目上还没有——那个间隙里这个 run 连一个 actor 会话都还没建,问它也无话可说。
+   *
+   * 唯一的读者是 amend:取代一个在飞前驱之后,它要先确认那些会话已经写完,才谈得上接续那条
+   * 未完的 ask(`inFlight`)。探针的所有权就在这个条目上——一个 run 一份,随 driver 生灭,
+   * 不另立进程级注册表。
+   */
+  quiescence?: ActorSessionQuiescence;
   /** 结算 promise;waitForTask 等它。fire-and-forget 的那条链就挂在这里。 */
   /** 结算 promise;waitForTask 等它。fire-and-forget 的那条链就挂在这里。 */
   settlement: Promise<RunSettlement>;
   settlement: Promise<RunSettlement>;
   /** 已结算时的终态(产物/错误只在这里,journal 不存脚本返回值)。 */
   /** 已结算时的终态(产物/错误只在这里,journal 不存脚本返回值)。 */
@@ -136,6 +158,10 @@ export function snapshotOf(
   // 分别 listNodes 就是把一个 256 节点 run 的全表解码做两遍。
   // 分别 listNodes 就是把一个 256 节点 run 的全表解码做两遍。
   const nodes = status === "running" ? undefined : journal.listNodes(taskId);
   const nodes = status === "running" ? undefined : journal.listNodes(taskId);
 
 
+  // lineage 的活动时长:
+  // 与 nodes 同一道终态闸门、同一条论证——它的唯一消费者是终态通知,而快照被后台追踪器反复轮询。
+  const activeDurationMs = status === "running" ? undefined : runLineageActiveMs(journal, taskId);
+
   // 真实终态词 + 停止原因 + 结构化失败:快照基类的
   // 真实终态词 + 停止原因 + 结构化失败:快照基类的
   // `status` 是后台任务追踪器的通用词汇(stopped 折成 cancelled、errored 折成 failed),通知
   // `status` 是后台任务追踪器的通用词汇(stopped 折成 cancelled、errored 折成 failed),通知
   // 要说真话只能读这三个字段。终态之前不带(还没有可说的终局)。
   // 要说真话只能读这三个字段。终态之前不带(还没有可说的终局)。
@@ -176,6 +202,7 @@ export function snapshotOf(
       entry === undefined ? readRunScriptPath(journal, taskId) : entry.scriptPath,
       entry === undefined ? readRunScriptPath(journal, taskId) : entry.scriptPath,
     ),
     ),
     ...(failure === undefined ? {} : { failure }),
     ...(failure === undefined ? {} : { failure }),
+    ...(activeDurationMs === undefined ? {} : { activeDurationMs }),
     ...(entry?.completedAt === undefined ? {} : { completedAt: entry.completedAt }),
     ...(entry?.completedAt === undefined ? {} : { completedAt: entry.completedAt }),
     ...(error === undefined ? {} : { error }),
     ...(error === undefined ? {} : { error }),
     // 零条时整字段缺席(与 reports 同规):读侧据此让整块 pending 区消失,不渲染空节。
     // 零条时整字段缺席(与 reports 同规):读侧据此让整块 pending 区消失,不渲染空节。

+ 62 - 0
apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-retune.ts

@@ -0,0 +1,62 @@
+// ============================================================
+// Dynamic Workflow Run Service:就地改一个在飞 run 的并发上界
+// ============================================================
+// 这是 `DynamicWorkflowRunPort.retuneConcurrency` 的实现体,与三条启动入口(dynamic-workflow-run-submit.ts)刻意分居:那三条
+// 都会**铸一个 run**,这一条一个 run 都不铸——它只对着已经在飞的那个发一条命令。
+//
+// 两种拒绝在**不同的地方**判定,这正是让它们分得开的原因:
+//   - `unchanged` 是本模块自己的答案,读的是服务此刻持有的上界,在句柄被调之前就判完;
+//   - 于是引擎的 setter 只剩一个说 false 的理由——run 在这两步之间结算了——端口把它报成 `not_live`。
+//
+// 顺序也是载荷性的:先句柄(引擎换 caps + 写行 + 记事件 + 闸门换上界,一个同步片),成了才动
+// 服务自己的内存副本。反过来就会在 run 恰好结算的那一瞬留下一个与 `dwf_run` 行不符的内存上界,
+// 而快照与详情读的正是那一份。
+
+import type {
+  DynamicWorkflowRunRetuneRequest,
+  DynamicWorkflowRunRetuneResult,
+} from "@zcode/contracts";
+import type { JournalStorePort } from "@zcode/dynamic-workflow";
+import type { RunRegistryEntry } from "./dynamic-workflow-run-observation.js";
+import { clampRunConcurrency } from "./workflow-concurrency-ceiling.js";
+
+/** 本模块借用的 service 内部状态;全是引用,本文件不持有任何自己的状态。 */
+export interface DynamicWorkflowRunRetuneContext {
+  runs: Map<string, RunRegistryEntry>;
+  journal: JournalStorePort;
+  /** 与 caps 起点、两条读面判据同一个函数(见 run service 的 `concurrencyCeiling`)。 */
+  concurrencyCeiling: () => number;
+}
+
+export function retuneRunConcurrency(
+  ctx: DynamicWorkflowRunRetuneContext,
+  request: DynamicWorkflowRunRetuneRequest,
+): DynamicWorkflowRunRetuneResult {
+  const ceiling = ctx.concurrencyCeiling();
+  // `null` = 天花板 = 解除本 run 自己的限制。与提交时**同一条**钳制(工具层已经钳过一次是为了让
+  // 确认窗显示将要生效的值;端口再钳是端口自己的契约,两次必然同值)。
+  const next = clampRunConcurrency(request.maxConcurrency ?? undefined, ceiling);
+
+  const entry = ctx.runs.get(request.runId);
+  if (entry === undefined || entry.terminal !== undefined || entry.control === undefined) {
+    // 本 service 手上没有这个活条目:从来不是本进程的 run、早已结算的 run,或者升级前留下的
+    // 无控制面条目。三者对调用方是同一个下一步——走一次真正的修订。
+    return { ok: false, reason: "not_live" };
+  }
+
+  // 此刻生效的上界:**有条目就读条目**(三条建条目的路都落值),冷行才回退到 journal。
+  // 两者都没有只可能是 submit → createRun 之间那几个微任务里的接线异常,按「跑在天花板上」读。
+  const current =
+    entry.maxConcurrency ?? ctx.journal.getRun(request.runId)?.caps.maxConcurrency ?? ceiling;
+  if (current === next) return { ok: false, reason: "unchanged", current };
+
+  if (!entry.control.setMaxConcurrency(next)) {
+    // 条目还在、引擎却说没改:run 在存活判定与这一行之间结算了(竞态),或者引擎还没接上
+    // (launch 之前的那几个微任务)。两者都是「这一刻不可就地改」。
+    return { ok: false, reason: "not_live", current };
+  }
+  // 内存副本一并挪动:快照读的是 `entry.maxConcurrency ?? 行`,条目优先——不挪就会在 retune
+  // 之后继续报提交时那个数,而 `AmendWorkflow` 的 resolveInput 正是读这张快照判「沿用什么」。
+  entry.maxConcurrency = next;
+  return { ok: true, maxConcurrency: next, previous: current, ceiling };
+}

+ 1 - 0
apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-sequence-capture.ts

@@ -24,6 +24,7 @@ export function createJournalSequenceCapture(journal: JournalStorePort): {
     updateRunStatus: (runId, status, settlement) =>
     updateRunStatus: (runId, status, settlement) =>
       journal.updateRunStatus(runId, status, settlement),
       journal.updateRunStatus(runId, status, settlement),
     updateRunUsage: (runId, spentTokens) => journal.updateRunUsage(runId, spentTokens),
     updateRunUsage: (runId, spentTokens) => journal.updateRunUsage(runId, spentTokens),
+    updateRunCaps: (runId, caps) => journal.updateRunCaps(runId, caps),
     putActor: (record) => journal.putActor(record),
     putActor: (record) => journal.putActor(record),
     getActor: (runId, siteId, ordinal) => journal.getActor(runId, siteId, ordinal),
     getActor: (runId, siteId, ordinal) => journal.getActor(runId, siteId, ordinal),
     listActors: (runId) => journal.listActors(runId),
     listActors: (runId) => journal.listActors(runId),

+ 20 - 13
apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-service.ts

@@ -54,6 +54,8 @@ import type {
   DynamicWorkflowRunPort,
   DynamicWorkflowRunPort,
   DynamicWorkflowRunProgressPayload,
   DynamicWorkflowRunProgressPayload,
   DynamicWorkflowRunResumeResult,
   DynamicWorkflowRunResumeResult,
+  DynamicWorkflowRunRetuneRequest,
+  DynamicWorkflowRunRetuneResult,
   DynamicWorkflowRunSessionSummary,
   DynamicWorkflowRunSessionSummary,
   DynamicWorkflowRunSnapshot,
   DynamicWorkflowRunSnapshot,
   DynamicWorkflowRunAmendRequest,
   DynamicWorkflowRunAmendRequest,
@@ -112,8 +114,12 @@ import {
   createRunServiceLifecycle,
   createRunServiceLifecycle,
   type DynamicWorkflowRunSettledNotice,
   type DynamicWorkflowRunSettledNotice,
 } from "./dynamic-workflow-run-lifecycle.js";
 } from "./dynamic-workflow-run-lifecycle.js";
+import { retuneRunConcurrency } from "./dynamic-workflow-run-retune.js";
 import type { ActorTranscriptStore } from "./workflow-actor-transcript.js";
 import type { ActorTranscriptStore } from "./workflow-actor-transcript.js";
-import { resolveWorkflowConcurrencyCeiling } from "./workflow-concurrency-ceiling.js";
+import {
+  clampRunConcurrency,
+  resolveWorkflowConcurrencyCeiling,
+} from "./workflow-concurrency-ceiling.js";
 import type { WorkflowConcurrencyPort } from "./workflow-concurrency-governor.js";
 import type { WorkflowConcurrencyPort } from "./workflow-concurrency-governor.js";
 import type { AgentRuntimeWorkflowDriverDeps } from "./workflow-driver-types.js";
 import type { AgentRuntimeWorkflowDriverDeps } from "./workflow-driver-types.js";
 import {
 import {
@@ -125,18 +131,6 @@ import {
 const DEFAULT_LIST_RUNS_LIMIT = 16;
 const DEFAULT_LIST_RUNS_LIMIT = 16;
 const MAX_LIST_RUNS_LIMIT = 64;
 const MAX_LIST_RUNS_LIMIT = 64;
 
 
-/**
- * 请求的并发上界 → 本 run 实际生效的上界。
- *
- * **钳制而不是拒绝**:这个旋钮只为压低并发,一个过大的值表达的意愿是「别限制我」,把它变成
- * 一次工具失败只会让模型去猜机器有几个核。缺席 / 非有限数同样读作「不限制」= 天花板,非整数
- * 向下取整(要「3.7 个在飞的 ask」没有意义,而向上取整会偷偷越过用户说的数)。
- */
-function clampRunConcurrency(requested: number | undefined, ceiling: number): number {
-  if (requested === undefined || !Number.isFinite(requested)) return ceiling;
-  return Math.max(1, Math.min(ceiling, Math.floor(requested)));
-}
-
 /** actor runtime 工厂的输入。runId 在内,因为会话 id 与 task link 都要 run 作用域。 */
 /** actor runtime 工厂的输入。runId 在内,因为会话 id 与 task link 都要 run 作用域。 */
 export interface DynamicWorkflowActorRuntimeInput {
 export interface DynamicWorkflowActorRuntimeInput {
   runId: string;
   runId: string;
@@ -394,6 +388,19 @@ export function createDynamicWorkflowRunService(
      */
      */
     concurrencyCeiling,
     concurrencyCeiling,
 
 
+    /**
+     * 就地改一个在飞 run 自己的并发上界(端口契约见
+     * {@link DynamicWorkflowRunPort.retuneConcurrency};实现体在 dynamic-workflow-run-retune.ts)。
+     *
+     * 刻意**不过关闭门**:三条启动入口要 `assertOpen` 是因为它们会起引擎,而这一条什么都不起——
+     * 关闭中的 service 里每个条目都在结算,存活判定自己会把它报成 `not_live`。
+     */
+    async retuneConcurrency(
+      request: DynamicWorkflowRunRetuneRequest,
+    ): Promise<DynamicWorkflowRunRetuneResult> {
+      return retuneRunConcurrency({ runs, journal: deps.journal, concurrencyCeiling }, request);
+    },
+
     async resume(runId: string): Promise<DynamicWorkflowRunResumeResult> {
     async resume(runId: string): Promise<DynamicWorkflowRunResumeResult> {
       assertOpen();
       assertOpen();
       return resumeDynamicWorkflowRun(entryContext, runId);
       return resumeDynamicWorkflowRun(entryContext, runId);

+ 59 - 3
apps/zcode-cli/packages/bootstrap/src/app/dynamic-workflow-run-submit.ts

@@ -52,6 +52,7 @@ import {
 import { isResumableRecord, type RunRegistryEntry } from "./dynamic-workflow-run-observation.js";
 import { isResumableRecord, type RunRegistryEntry } from "./dynamic-workflow-run-observation.js";
 import type { DynamicWorkflowRunServiceDeps } from "./dynamic-workflow-run-service.js";
 import type { DynamicWorkflowRunServiceDeps } from "./dynamic-workflow-run-service.js";
 import type { WorkflowEscalationRegistry } from "./workflow-escalation-registry.js";
 import type { WorkflowEscalationRegistry } from "./workflow-escalation-registry.js";
+import { createWorkflowRunControl } from "./workflow-run-control.js";
 
 
 /**
 /**
  * 两条入口要用的 service 内部状态。全是**引用**而不是副本:注册表与停驻表是 service 的那一份,
  * 两条入口要用的 service 内部状态。全是**引用**而不是副本:注册表与停驻表是 service 的那一份,
@@ -108,8 +109,10 @@ export async function submitDynamicWorkflowRun(
  *   2. 铸新 id;
  *   2. 铸新 id;
  *   3. 前驱在飞则以 `{ superseded: newRunId }` 取消并 **await 它自己的结算 promise**——不是超时、
  *   3. 前驱在飞则以 `{ superseded: newRunId }` 取消并 **await 它自己的结算 promise**——不是超时、
  *      不是轮询 journal;前驱因此结算成 `stopped(superseded, supersededBy)`;
  *      不是轮询 journal;前驱因此结算成 `stopped(superseded, supersededBy)`;
- *   4. 从已结算的前驱构建缓存——预检已过,这里再被拒只可能是宿主故障,上抛;
- *   5. 与全新 submit 同一条 launch 路启动,带 `resumedFrom` 与缓存。
+ *   4. 有界地等被中止的 turn 把尾巴写完,问出「哪些会话此刻可以放心去数」——只有它影响在飞
+ *      ask 的接续,完结前缀的边界是 journal 事实(见下面那段注释的完整论证);
+ *   5. 从已结算的前驱构建缓存——预检已过,这里再被拒只可能是宿主故障,上抛;
+ *   6. 与全新 submit 同一条 launch 路启动,带 `resumedFrom` 与缓存。
  *
  *
  * 旧版让 `submit({resumeFrom})` 对在飞前驱回 `not_amendable`,模型只能 TaskStop → 轮询到
  * 旧版让 `submit({resumeFrom})` 对在飞前驱回 `not_amendable`,模型只能 TaskStop → 轮询到
  * stopped → 重提交三步;本方法把停止与结算等待收进 service,竞态随之消失。
  * stopped → 重提交三步;本方法把停止与结算等待收进 service,竞态随之消失。
@@ -150,7 +153,34 @@ export async function amendDynamicWorkflowRun(
     });
     });
   }
   }
 
 
-  const built = await buildImportedCache(deps, request.predecessorRunId);
+  // 静默闸门。
+  //
+  // 根因:`dispose()` 是同步的,对还有在飞 turn 的会话只挂了一条 `state.turn.then(close, close)`
+  // 而不等它;引擎在 `cancelAsk` 中止 turn 之后立刻结算。所以上面那句 `await live.settlement`
+  // 保证的是「run 结算了」,**不是**「被中止的 turn 把它的尾巴写完了」。此刻去数前驱会话的
+  // 消息条数,可能少数一条,或者数到一条 part 还没落全的消息——而那个数会变成接续位置
+  // (`inFlight.messageBoundary`),被 driver 拿去截断复制。已完结前缀不在此列:它们的边界在
+  // ask 结算时就已经 journal 了,是事实而不是此刻的观察。
+  //
+  // 所以问一次 driver「哪些会话已经静默」,只对静默的会话谈接续。**这不是用超时掩盖竞态**:
+  // 到点仍未落地的会话不会被当作静默继续用,它只是拿不到 `inFlight`——也就是本特性之前的
+  // 行为(整段在飞转录丢弃,ask 从完整前缀重开)。我们宁可少做一次优化,也绝不拿一个正在
+  // 变动的条数去截断转录。
+  //
+  // 两种情形一秒都不等,因为两者都没有可疑的数可言:
+  //   - 本进程没有这个前驱的活条目(早已终态,或死进程留下的行)→ 没有 driver 就没有东西在
+  //     写它的会话;
+  //   - 整个装配没有转录存取面 → 根本数不出条数,`inFlight` 无从产生(构建器那边同样要
+  //     `messageCount` 才谈接续),等待纯属白付。
+  // 两者都落到「缺席 = 全部静默」这一条上(见 AmendImportOptions.quietSessions)。
+  const quietSessions =
+    deps.actorTranscriptStore === undefined ? undefined : await live?.quiescence?.quietSessions();
+
+  const built = await buildImportedCache(
+    deps,
+    request.predecessorRunId,
+    quietSessions === undefined ? undefined : { quietSessions },
+  );
   if (!built.ok) {
   if (!built.ok) {
     // 预检刚通过:run 存在、边界齐全;到这里还被拒只剩「前驱非终态」——注册表说它不在飞而
     // 预检刚通过:run 存在、边界齐全;到这里还被拒只剩「前驱非终态」——注册表说它不在飞而
     // journal 说它还在跑(别的进程持有)。这不是模型能改的输入,按接线故障上抛。
     // journal 说它还在跑(别的进程持有)。这不是模型能改的输入,按接线故障上抛。
@@ -286,8 +316,13 @@ function startNewRun(ctx: DynamicWorkflowRunEntryContext, input: StartNewRunInpu
   // 立刻开始轮询快照——注册表是「run 已存在」的唯一同步事实(journal 的 dwf_run 行
   // 立刻开始轮询快照——注册表是「run 已存在」的唯一同步事实(journal 的 dwf_run 行
   // 要等引擎构造,晚若干个微任务)。
   // 要等引擎构造,晚若干个微任务)。
   const controller = new AbortController();
   const controller = new AbortController();
+  // 活体控制面与 AbortController 同时造、同时进条目(见 RunRegistryEntry.control):
+  // 「停下这个 run」与「改这个 run 的一项设置」是同一刻就该可用的两条通道,而两者都要在
+  // launch 之前存在——retune 可能在 submit 返回后的任意一个微任务里到达。
+  const control = createWorkflowRunControl();
   const entry: RunRegistryEntry = {
   const entry: RunRegistryEntry = {
     controller,
     controller,
+    control,
     startedAt: new Date(),
     startedAt: new Date(),
     ...(input.toolCallId === undefined ? {} : { toolCallId: input.toolCallId }),
     ...(input.toolCallId === undefined ? {} : { toolCallId: input.toolCallId }),
     ...(input.parentSessionId === undefined ? {} : { parentSessionId: input.parentSessionId }),
     ...(input.parentSessionId === undefined ? {} : { parentSessionId: input.parentSessionId }),
@@ -331,10 +366,17 @@ function startNewRun(ctx: DynamicWorkflowRunEntryContext, input: StartNewRunInpu
       ...(input.args === undefined ? {} : { args: input.args }),
       ...(input.args === undefined ? {} : { args: input.args }),
       ...(entry.parentSessionId === undefined ? {} : { parentSessionId: entry.parentSessionId }),
       ...(entry.parentSessionId === undefined ? {} : { parentSessionId: entry.parentSessionId }),
       escalationRegistry: escalations,
       escalationRegistry: escalations,
+      control,
       runId,
       runId,
       scriptText: input.scriptText,
       scriptText: input.scriptText,
       signal: controller.signal,
       signal: controller.signal,
       ...(entry.toolCallId === undefined ? {} : { toolCallId: entry.toolCallId }),
       ...(entry.toolCallId === undefined ? {} : { toolCallId: entry.toolCallId }),
+      // 会话静默探针回填到条目上:本 run 将来被修订时,那次 amend 要问它
+      // (dynamic-workflow-import.ts 的 quietSessions)。三条入口都接,因为哪个 run 会成为
+      // 前驱是将来才知道的事。
+      onQuiescenceProbe: (probe) => {
+        entry.quiescence = probe;
+      },
       // lineage 指针与缓存表成对下传(launch → harness → EngineConfig):前者落 dwf_run
       // lineage 指针与缓存表成对下传(launch → harness → EngineConfig):前者落 dwf_run
       // 的 resumed_from(createRun 一次写死),后者只活在本次执行里。
       // 的 resumed_from(createRun 一次写死),后者只活在本次执行里。
       ...(imported === undefined
       ...(imported === undefined
@@ -429,9 +471,17 @@ export async function resumeDynamicWorkflowRun(
   const resumedSubagentModel = readRunSubagentModel(deps.journal, runId);
   const resumedSubagentModel = readRunSubagentModel(deps.journal, runId);
   const resumedScriptPath = readRunScriptPath(deps.journal, runId);
   const resumedScriptPath = readRunScriptPath(deps.journal, runId);
   const controller = new AbortController();
   const controller = new AbortController();
+  // 与 submit 路同规:新条目 = 新 AbortController + 新控制面。上一世的句柄绑的是已经结算的那个
+  // 引擎,留着它会让 retune 对一个死引擎说话。
+  const control = createWorkflowRunControl();
   const entry: RunRegistryEntry = {
   const entry: RunRegistryEntry = {
     controller,
     controller,
+    control,
     startedAt: new Date(),
     startedAt: new Date(),
+    // 本 run 生效的并发上界:**resume 路以 journal 行为准**(一次就地 retune 已经把新值写进
+    // `caps_max_concurrency`,所以行里那个就是这一世要跑的上界)。抄进条目是为了让
+    // `retuneConcurrency` 与两条读面只剩一条规则——有条目就读条目。
+    maxConcurrency: record.caps.maxConcurrency,
     ...(record.toolCallId === undefined ? {} : { toolCallId: record.toolCallId }),
     ...(record.toolCallId === undefined ? {} : { toolCallId: record.toolCallId }),
     ...(record.parentSessionId === undefined ? {} : { parentSessionId: record.parentSessionId }),
     ...(record.parentSessionId === undefined ? {} : { parentSessionId: record.parentSessionId }),
     // 枚举面的间隙元数据(见 RunRegistryEntry):resume 的权威在 journal 记录里,
     // 枚举面的间隙元数据(见 RunRegistryEntry):resume 的权威在 journal 记录里,
@@ -472,10 +522,16 @@ export async function resumeDynamicWorkflowRun(
       ...(record.parentSessionId === undefined ? {} : { parentSessionId: record.parentSessionId }),
       ...(record.parentSessionId === undefined ? {} : { parentSessionId: record.parentSessionId }),
       // 两条入口共用同一张停驻表(见上面的字段注释)。
       // 两条入口共用同一张停驻表(见上面的字段注释)。
       escalationRegistry: escalations,
       escalationRegistry: escalations,
+      // 控制面与停驻表不同:**每条入口各造一个**(它绑的是这一世的引擎与这一世的座位闸门)。
+      control,
       runId,
       runId,
       scriptText: record.scriptText,
       scriptText: record.scriptText,
       signal: controller.signal,
       signal: controller.signal,
       ...(record.toolCallId === undefined ? {} : { toolCallId: record.toolCallId }),
       ...(record.toolCallId === undefined ? {} : { toolCallId: record.toolCallId }),
+      // 与 submit / amend 同一条:resume 起来的 run 照样可能成为下一次修订的前驱。
+      onQuiescenceProbe: (probe) => {
+        entry.quiescence = probe;
+      },
       // resumedFrom 不再下传:createRun 早在提交时就把它写死了,resume 路径上引擎命中既有
       // resumedFrom 不再下传:createRun 早在提交时就把它写死了,resume 路径上引擎命中既有
       // 行、根本不走 createRun。只有重建出来的缓存需要下去。
       // 行、根本不走 createRun。只有重建出来的缓存需要下去。
       ...(rebuilt === undefined ? {} : { importedCache: rebuilt }),
       ...(rebuilt === undefined ? {} : { importedCache: rebuilt }),

+ 51 - 6
apps/zcode-cli/packages/bootstrap/src/app/workflow-actor-transcript.ts

@@ -19,6 +19,7 @@
 import {
 import {
   createMessageId,
   createMessageId,
   createPartId,
   createPartId,
+  type Logger,
   type MessageId,
   type MessageId,
   type MessageInfo,
   type MessageInfo,
   type MessagePart,
   type MessagePart,
@@ -66,24 +67,52 @@ export async function countActorTranscript(
  *    与 part 内嵌锚点跟着重映射,这正是 core 的 fork 克隆器 {@link cloneMessageForFork} /
  *    与 part 内嵌锚点跟着重映射,这正是 core 的 fork 克隆器 {@link cloneMessageForFork} /
  *    {@link clonePartForFork} 已经做对的事(fork 与本函数是同一个动作:按值复制一段转录到另一个
  *    {@link clonePartForFork} 已经做对的事(fork 与本函数是同一个动作:按值复制一段转录到另一个
  *    会话,child 用本地 id 续写),所以这里复用它们而不是写第二份。
  *    会话,child 用本地 id 续写),所以这里复用它们而不是写第二份。
- * 2. **幂等**。目标会话已经有 ≥ messageCount 条消息即整段跳过:那是修订 run 崩溃后 resume 的情形
- *    ——会话 id 由 (runId, actorRef) 纯确定地铸出,重挂拿到的就是那个已经装着"复制的 + 新产的"
- *    内容的会话,再抄一遍等于把上文翻倍。不足则重抄(复制中途崩溃留下的半截前缀):id 按
- *    (目标会话, 下标) 纯确定,重抄是对已有行的 upsert,不会产生重复。
+ * 2. **幂等,且绝不写进一个已经开跑的会话**。两条跳过规则,缺一不可:
+ *
+ *    - 目标已经有 ≥ messageCount 条消息即整段跳过:那是修订 run 崩溃后 resume 的情形——会话 id
+ *      由 (runId, actorRef) 纯确定地铸出,重挂拿到的就是那个已经装着「复制的 + 新产的」内容的
+ *      会话,再抄一遍等于把上文翻倍。
+ *    - 目标里但凡有一条**不是**本会话种子 id 的消息(见 {@link seededMessageId}),同样跳过。
+ *      只装着种子消息的会话是一截「复制到一半」的前缀,照旧补齐;装着别的东西的会话有自己的
+ *      历史,一个字节都不许动。
+ *
+ *    第二条用于防止**边界增长后再次复制**:`inFlight.messageBoundary` 取自
+ *    前驱会话此刻的消息条数,是导入缓存里唯一一个不是 journal 事实的数(见
+ *    dynamic-workflow-import.ts 的文件头)。它在两次构建之间变大时(前驱被重新 resume 过又写了
+ *    几轮,或者一条迟到的后台通知消息落了进去),修订 run 的一次普通「停止 → resume」就会带着
+ *    更大的 M 再次调到这里;若此时目标里已有自己的 live 消息但总数仍 < M,老规则会去重抄
+ *    0..M-1——前 N 条是对既有种子 id 的 upsert(无害),而 N..M-1 是**新 id**,于是前驱的消息被
+ *    追加到本会话自己的历史**之后**(`message.sequence` 在 insert 时取 `max+1`,adapters 的
+ *    messages.ts)。那是一段读起来前后颠倒、且不属于这个子代理的上文,而且悄无声息。
+ *    「只有全是种子 id 才动它」把这件事在**复制点**一次性堵死,对将来任何一个非 journal 事实
+ *    都成立,不必逐个去证明它们不会变大。
  * 3. **缺料即大声失败**。源会话不存在(读回空)或短于边界,说明 service 从 journal 事实构造出的
  * 3. **缺料即大声失败**。源会话不存在(读回空)或短于边界,说明 service 从 journal 事实构造出的
  *    种子这个 store 兑现不了——corruption 级,不是可降级情形(可降级的那一半在 service 侧的门里:
  *    种子这个 store 兑现不了——corruption 级,不是可降级情形(可降级的那一半在 service 侧的门里:
  *    链上缺会话的候选在那里就该被弃置)。
  *    链上缺会话的候选在那里就该被弃置)。
  *
  *
- * @returns 实际复制的条数;`undefined` 表示幂等跳过。
+ * @returns 实际复制的条数;`undefined` 表示跳过(两条规则都归到这一个返回值,因为调用方对
+ *          两者的处理相同:不再水化第二次,见 workflow-driver-transcript.ts 的 seedActorSession)。
  */
  */
 export async function seedActorTranscript(input: {
 export async function seedActorTranscript(input: {
+  logger?: Logger;
   seed: ActorSessionSeed;
   seed: ActorSessionSeed;
   store: ActorTranscriptStore;
   store: ActorTranscriptStore;
   targetSessionId: SessionId;
   targetSessionId: SessionId;
 }): Promise<number | undefined> {
 }): Promise<number | undefined> {
-  const { seed, store, targetSessionId } = input;
+  const { logger, seed, store, targetSessionId } = input;
   const existing = await store.messages({ sessionID: targetSessionId });
   const existing = await store.messages({ sessionID: targetSessionId });
   if (existing.length >= seed.messageCount) return undefined;
   if (existing.length >= seed.messageCount) return undefined;
+  if (!holdsOnlySeedMessages(existing, targetSessionId)) {
+    // 记一条:走到这里说明种子边界比上一次大了,而这是唯一能看见它的地方。
+    logger?.warn?.("Dynamic workflow actor session already has its own history; seeding skipped", {
+      event: "dynamic_workflow.actor.seed_skipped_live_session",
+      existingMessageCount: existing.length,
+      messageCount: seed.messageCount,
+      module: "bootstrap.app",
+      sessionId: targetSessionId,
+    });
+    return undefined;
+  }
 
 
   const source = await store.messages({ sessionID: seed.sourceSessionId as SessionId });
   const source = await store.messages({ sessionID: seed.sourceSessionId as SessionId });
   if (source.length < seed.messageCount) {
   if (source.length < seed.messageCount) {
@@ -122,6 +151,22 @@ export async function seedActorTranscript(input: {
   return seed.messageCount;
   return seed.messageCount;
 }
 }
 
 
+/**
+ * 目标会话里是不是**只有**本会话的种子副本(第 i 条恰好是 {@link seededMessageId} 的第 i 个)。
+ *
+ * 判据用 id 而不是条数或时间:种子 id 按 (目标会话, 下标) 纯确定,所以「这条消息是不是我抄进来
+ * 的」有一个不依赖任何时钟、也不依赖读取顺序之外任何东西的答案。空会话按真处理(还没抄过,
+ * 当然可以抄)。`messages()` 按 `sequence` 升序返回,而种子是按下标顺序写的,所以下标就是位置。
+ */
+function holdsOnlySeedMessages(
+  existing: readonly MessageWithParts[],
+  targetSessionId: SessionId,
+): boolean {
+  return existing.every(
+    (message, index) => message.info.id === seededMessageId(targetSessionId, index),
+  );
+}
+
 /**
 /**
  * 种子副本的 id:按 (目标会话, 前缀下标) 纯确定。
  * 种子副本的 id:按 (目标会话, 前缀下标) 纯确定。
  *
  *

+ 15 - 0
apps/zcode-cli/packages/bootstrap/src/app/workflow-concurrency-ceiling.ts

@@ -26,3 +26,18 @@ export function resolveWorkflowConcurrencyCeiling(
     Math.min(WORKFLOW_CONCURRENCY_CEILING_MAX, availableParallelism() - RESERVED_PARALLELISM),
     Math.min(WORKFLOW_CONCURRENCY_CEILING_MAX, availableParallelism() - RESERVED_PARALLELISM),
   );
   );
 }
 }
+
+/**
+ * 请求的并发上界 → 本 run 实际生效的上界。
+ *
+ * **钳制而不是拒绝**:这个旋钮只为压低并发,一个过大的值表达的意愿是「别限制我」,把它变成
+ * 一次工具失败只会让模型去猜机器有几个核。缺席 / 非有限数同样读作「不限制」= 天花板,非整数
+ * 向下取整(要「3.7 个在飞的 ask」没有意义,而向上取整会偷偷越过用户说的数)。
+ *
+ * 与天花板同住一个文件:提交时定上界与中途 retune 走的**必须**是同一条钳制(否则同一个
+ * `max_concurrency` 经两条路会落成两个数),而那两条路分居 run service 与 retune 两个模块。
+ */
+export function clampRunConcurrency(requested: number | undefined, ceiling: number): number {
+  if (requested === undefined || !Number.isFinite(requested)) return ceiling;
+  return Math.max(1, Math.min(ceiling, Math.floor(requested)));
+}

+ 14 - 2
apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-concurrency.ts

@@ -27,6 +27,7 @@ import {
   workflowConcurrencyKey,
   workflowConcurrencyKey,
   type WorkflowConcurrencyPort,
   type WorkflowConcurrencyPort,
 } from "./workflow-concurrency-governor.js";
 } from "./workflow-concurrency-governor.js";
+import type { WorkflowRunSeatGate } from "./workflow-seat-gate.js";
 
 
 /** 与治理器同一条纪律:这两种 retry 不是 provider 失败,不值一个徽标。 */
 /** 与治理器同一条纪律:这两种 retry 不是 provider 失败,不值一个徽标。 */
 const NON_FAILURE_RETRY_REASONS: ReadonlySet<string> = new Set([
 const NON_FAILURE_RETRY_REASONS: ReadonlySet<string> = new Set([
@@ -111,6 +112,11 @@ export function createActorModelActivity(input: {
   /** 当前在飞 ask 的实例(结算 / 取消后为 undefined);只有工具活动的上报需要它。 */
   /** 当前在飞 ask 的实例(结算 / 取消后为 undefined);只有工具活动的上报需要它。 */
   live?: () => InstanceRef | undefined;
   live?: () => InstanceRef | undefined;
   handlers: ActorModelActivityHandlers;
   handlers: ActorModelActivityHandlers;
+  /**
+   * 本 run 的座位闸门与这个子代理在闸门里的键。在场时准入端口再包一层:先等座位、再过治理器。缺席即这个 run
+   * 的上界从不中途变动(snippet 执行、不带闸门的装配),准入端口与从前逐字相同。
+   */
+  seat?: { gate: WorkflowRunSeatGate; key: string };
 }): ActorModelActivity {
 }): ActorModelActivity {
   const chains = new Map<string, Chain>();
   const chains = new Map<string, Chain>();
   let executing = false;
   let executing = false;
@@ -120,7 +126,7 @@ export function createActorModelActivity(input: {
   let turnsResolved = 0;
   let turnsResolved = 0;
   let waitSeq = 0;
   let waitSeq = 0;
   let unsubscribeEvents: (() => void) | undefined;
   let unsubscribeEvents: (() => void) | undefined;
-  const { handlers, live, port, runId } = input;
+  const { handlers, live, port, runId, seat } = input;
   // 同一条会话事件流的第二个读者:工具调用。实现单独成文件(判定与计数都在那里),这里只把它
   // 同一条会话事件流的第二个读者:工具调用。实现单独成文件(判定与计数都在那里),这里只把它
   // 编进同一个生命周期,好让 driver 侧仍然只有一个观察对象。
   // 编进同一个生命周期,好让 driver 侧仍然只有一个观察对象。
   const toolActivity = createActorToolActivity({
   const toolActivity = createActorToolActivity({
@@ -171,7 +177,7 @@ export function createActorModelActivity(input: {
 
 
   // 准入端口就是治理器端口的窄包装:快路径 = tryAdmit,排队 = admit(waiting(slot)
   // 准入端口就是治理器端口的窄包装:快路径 = tryAdmit,排队 = admit(waiting(slot)
   // 由 runner 的 queued 事件报,这里不再自己发)。acquire 仍先试快路径,兼容没有走 tryAcquire 的调用方。
   // 由 runner 的 queued 事件报,这里不再自己发)。acquire 仍先试快路径,兼容没有走 tryAcquire 的调用方。
-  const admission: ModelRequestAdmission | undefined =
+  const governed: ModelRequestAdmission | undefined =
     port === undefined
     port === undefined
       ? undefined
       ? undefined
       : {
       : {
@@ -184,6 +190,12 @@ export function createActorModelActivity(input: {
             );
             );
           },
           },
         };
         };
+  // 本 run 自己的上界在**共享 cap 之上**再包一层。闸门要的那条子代理事实——
+  // 此刻有没有工具在跑——就取自同一个对象里的工具观察面,所以两个读者共用一份账。
+  const admission =
+    seat === undefined
+      ? governed
+      : seat.gate.wrap(seat.key, { toolsInFlight: () => toolActivity.inFlight() }, governed);
 
 
   return {
   return {
     admission,
     admission,

+ 153 - 0
apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-quiescence.ts

@@ -0,0 +1,153 @@
+// AgentRuntime-backed WorkflowDriver:dispose 时的会话释放与静默状态。
+// `dispose()` 不等待仍在执行的 turn;释放会话时记录这些 promise,供 amend 判断哪些会话已停止写入。
+//
+// 引擎结算并不表示被中止的 turn 已完成最后的消息持久化。amend 需要先等待会话静默,
+// 再读取消息条数作为 `inFlight.messageBoundary`。已完成 ask 的边界已记入 journal,不受此影响。
+// 等待超时的会话不导入未完成部分,后继从完整前缀重新执行,不能将超时视为静默。
+//
+// 此处只等待 turn 主线,不保证所有流式工具 part 都已落库:部分工具句柄可能已与 turn 的
+// promise 脱离。转录复制读取当时可见的 part;历史恢复会将 pending/running 工具视为中断,
+// 缺失的 part 不会生成无结果的 tool_use,空 assistant 消息会被跳过。
+// part 按同一 ID 更新,不增加消息条数,因此迟到的 part 不会改变消息边界。
+
+import type { WorkflowClock } from "./workflow-driver-concurrency.js";
+import { defaultSchedule } from "./workflow-driver-helpers.js";
+import type { AgentRuntimeWorkflowDriverDeps, SessionState } from "./workflow-driver-types.js";
+
+/**
+ * 等一个被中止的 turn 把尾巴写完的上界。
+ *
+ * 取值理由:它等的是**已经 abort 的** turn 走完 core 侧那几步已 await 的持久化
+ * (abandon → 取消快照 → assistant 消息),是毫秒量级的收尾,不是一次模型请求。5 秒给足了
+ * 慢磁盘与一次重试的余量,又不会让「修订一个在飞 run」这个交互明显变慢——而超了也只是
+ * 少一次接续,不是失败。
+ */
+export const AMEND_TRANSCRIPT_QUIESCE_MS = 5_000;
+
+/** 一个 run 的 actor 会话静默探询面。driver 私有能力,**不上** Boundary B 的 `WorkflowDriver`。 */
+export interface ActorSessionQuiescence {
+  /**
+   * 此刻已经静默(不再有在写的 turn)的会话 id。有界等待,见 {@link AMEND_TRANSCRIPT_QUIESCE_MS}。
+   *
+   * 「不在集合里」有两种成因,调用方对两者同等处理(都不接续):会话到点仍在写,或者这个
+   * driver 压根不认识它——后者只会出现在「前驱这一世从没给该 actor 建过会话」的形状上,
+   * 保守读成不静默即可(代价是少一次接续,而反过来是拿一个没人为其负责的条数去截断转录)。
+   */
+  quietSessions(): Promise<ReadonlySet<string>>;
+}
+
+/** driver 侧的写面:{@link ActorSessionQuiescence} 加一个 dispose 时的登记口。 */
+export interface ActorSessionQuiescenceLedger extends ActorSessionQuiescence {
+  /**
+   * 登记一个会话与它**此刻**仍在飞的 turn 收尾链(`SessionState.turn`)。`pendingTurn` 缺席
+   * 即该会话没有在飞 turn,立刻算静默。
+   *
+   * 由 `dispose()` 对它名下每个会话各调一次:那是唯一一个「还看得见全部会话、且已经没有新
+   * turn 会被发起」的时刻(dispose 之后 `sessions` 就被清空了)。
+   */
+  noteDisposed(sessionId: string, pendingTurn: Promise<unknown> | undefined): void;
+}
+
+/**
+ * 造一本会话静默账。纯内存、无 I/O;时钟由调用方注入。
+ *
+ * 所有权:每个 driver 实例恰好一本,随 driver 一起生灭。刻意**不做**进程级注册表——一个会话
+ * 属于哪个 run 已经由 driver 的归属关系说清了,第二张表只会带来「两边不一致时信谁」。
+ */
+export function createActorSessionQuiescence(options?: {
+  clock?: WorkflowClock;
+  /** 缺省 {@link AMEND_TRANSCRIPT_QUIESCE_MS}。 */
+  quiesceMs?: number;
+}): ActorSessionQuiescenceLedger {
+  /** sessionId → dispose 那一刻仍在飞的 turn(`undefined` = 当时就没有在飞 turn)。 */
+  const disposed = new Map<string, Promise<unknown> | undefined>();
+  const schedule = options?.clock?.schedule ?? defaultSchedule;
+  const quiesceMs = options?.quiesceMs ?? AMEND_TRANSCRIPT_QUIESCE_MS;
+
+  return {
+    noteDisposed(sessionId, pendingTurn) {
+      disposed.set(sessionId, pendingTurn);
+    },
+
+    async quietSessions() {
+      const quiet = new Set<string>();
+      const waits: Promise<unknown>[] = [];
+      for (const [sessionId, pending] of disposed) {
+        if (pending === undefined) {
+          quiet.add(sessionId);
+          continue;
+        }
+        // turn 收尾链的成败与静默无关:无论 resolve 还是 reject,它都不会再写这个会话了。
+        waits.push(
+          pending.then(
+            () => quiet.add(sessionId),
+            () => quiet.add(sessionId),
+          ),
+        );
+      }
+      if (waits.length > 0) await settleWithin(Promise.all(waits), quiesceMs, schedule);
+      // 快照一份再交出去:到点之后才落地的会话仍会往 `quiet` 里补写,而调用方读到的必须是
+      // 「问的那一刻」的事实——一个会在背后自己变大的集合比一个保守的集合危险得多。
+      return new Set(quiet);
+    },
+  };
+}
+
+/**
+ * dispose 的每会话释放:退订活动观察、撤掉退避重驱、**登记静默**,再等在飞 turn 落地后关
+ * actor runtime。
+ *
+ * 对每个 runtime 跑 app 关会话的**同一条**链——`closeBrowserSession` 内部依次 beginShutdown、
+ * node_repl 会话释放、浏览器会话关闭;不另造一套子代理关闭链,那会漂移。关闭失败只 warn,
+ * 结算不因它抛。
+ *
+ * 登记必须在 `state.turn.then(...)` **之前**:此刻 `state.turn` 就是要等的那条链,而 then 会把
+ * 它换成另一个 promise。整个函数同步返回(关闭挂在 then 上),dispose 因此一如既往不阻塞。
+ */
+export function releaseActorSessions(
+  deps: AgentRuntimeWorkflowDriverDeps,
+  sessions: Iterable<SessionState>,
+  ledger: ActorSessionQuiescenceLedger,
+): void {
+  for (const state of sessions) {
+    state.modelActivity.unsubscribe();
+    state.cancelRedrive?.();
+    state.cancelRedrive = undefined;
+    ledger.noteDisposed(state.sessionId, state.turn);
+    const close = (): void => closeActorRuntime(deps, state);
+    if (state.turn === undefined) close();
+    else state.turn.then(close, close);
+  }
+}
+
+function closeActorRuntime(deps: AgentRuntimeWorkflowDriverDeps, state: SessionState): void {
+  // Promise.resolve().then(...):把同步抛出也归到同一条 warn 路径(最小 stub runtime 没有这个方法)。
+  void Promise.resolve()
+    .then(() => state.runtime.closeBrowserSession())
+    .catch((error: unknown) => {
+      deps.logger?.warn?.("Dynamic workflow actor runtime close failed", {
+        errorMessage: error instanceof Error ? error.message : String(error),
+        event: "dynamic_workflow.actor_runtime.close_failed",
+        module: "bootstrap.app",
+        sessionId: state.sessionId,
+      });
+    });
+}
+
+/** 等 `work` 落地,最多等 `delayMs`。到点即返回(不抛),闹钟在任一分支后都撤掉。 */
+async function settleWithin(
+  work: Promise<unknown>,
+  delayMs: number,
+  schedule: (callback: () => void, delayMs: number) => () => void,
+): Promise<void> {
+  let cancel: (() => void) | undefined;
+  const deadline = new Promise<void>((resolve) => {
+    cancel = schedule(resolve, delayMs);
+  });
+  try {
+    await Promise.race([work, deadline]);
+  } finally {
+    // work 先落地时必须撤掉闹钟:一个还没响的 setTimeout 会把 CLI 的退出拖到上界。
+    cancel?.();
+  }
+}

+ 69 - 0
apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-submit-bridge.ts

@@ -0,0 +1,69 @@
+// ============================================================
+// AgentRuntime-backed WorkflowDriver:typed 结果的提交桥接(submit_result)
+// ============================================================
+// 修复原因:workflow-driver.ts 又顶到 oxlint max-lines 上限(400 行),把会话级 submit 端口拆到
+// 本文件成自由函数,与隔壁的升级桥接(workflow-driver-escalation.ts 的 `makeSessionEscalatePort`)
+// 逐条对称——两者本就是同一副形状的两条时序(mid-turn 阻塞 → 上报 → 引擎回裁决 → 解开 deferred)。
+// 公开面不变,driver 类上只剩一处调用。
+//
+// 对 driver 状态的全部触碰都经 {@link SubmitBridgeHost} 显式递进来(会话表 + 向上回报面),
+// 本文件不持有任何自己的状态——原方法体逐字保留,只把 `this.` 换成 `host.`。
+
+import type {
+  SessionId,
+  SubmitResultRequest,
+  SubmitVerdict as ContractsSubmitVerdict,
+  WorkflowSubmitPort,
+} from "@zcode/contracts";
+import { WorkflowError, type WorkflowReportSink } from "@zcode/dynamic-workflow";
+import { defer, rejectWith } from "./workflow-driver-helpers.js";
+import type { SessionState } from "./workflow-driver-types.js";
+
+/**
+ * driver 交给提交桥接的宿主面。两样都是 driver 私有状态的**引用**(不是副本):`sessions` 就是
+ * 类里那张会话表,`sink` 是 Boundary B 的向上回报面(`askSubmitAttempted` 在本调用栈内被引擎
+ * 同步回裁决,所以这两者必须是同一世的那一对)。
+ */
+export interface SubmitBridgeHost {
+  readonly sessions: ReadonlyMap<string, SessionState>;
+  readonly sink: WorkflowReportSink;
+}
+
+/**
+ * 造一个会话级 submit 端口:`submit_result` handler mid-turn 调用它并阻塞等裁决。
+ *
+ * closure 绑定本会话,模型无法覆盖路由身份(instance 取自 `currentInstance`)。
+ */
+export function makeSessionSubmitPort(
+  host: SubmitBridgeHost,
+  sessionId: SessionId,
+): WorkflowSubmitPort {
+  return {
+    respond: (request: SubmitResultRequest): Promise<ContractsSubmitVerdict> => {
+      const state = host.sessions.get(sessionId);
+      const instance = state?.currentInstance;
+      if (state === undefined || instance === undefined) {
+        // 无在飞 ask 却收到 submit:不路由到引擎,直接拒绝(避免悬挂)。
+        return Promise.resolve(rejectWith("no active ask is awaiting a submitted result"));
+      }
+      // 未声明结果类型的 ask 可能仍注册了 submit_result;这里立即拒绝提交并提示使用普通回复。
+      // 不能把它交给引擎后等待裁决:引擎对 untyped ask 不处理 submit,等待中的 deferred 将无法结束。
+      if (!state.currentTyped) {
+        return Promise.resolve(
+          rejectWith(
+            "this ask does not accept submit_result; provide your answer as your final message",
+          ),
+        );
+      }
+      // 当前实例不变式:至多一个挂起 deferred。若已有(不应发生),先拒旧的避免泄漏。
+      state.pendingSubmit?.reject(
+        new WorkflowError("DriverError", "This submit was superseded by a newer submit."),
+      );
+      const deferred = defer<ContractsSubmitVerdict>();
+      state.pendingSubmit = deferred;
+      // 同步上报:引擎在本调用栈内校验并经 respondToSubmit 回裁决(同步解开 deferred)。
+      host.sink.askSubmitAttempted(instance, request.result);
+      return deferred.promise;
+    },
+  };
+}

+ 26 - 0
apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-tool-activity.ts

@@ -56,6 +56,16 @@ interface ActorToolActivity {
   reset(): void;
   reset(): void;
   /** 本 ask 至今观察到的工具调用计数。 */
   /** 本 ask 至今观察到的工具调用计数。 */
   counts(): ActorToolCounts;
   counts(): ActorToolCounts;
+  /**
+   * 此刻**还在跑**的工具调用数(started 减去 result / error,按 toolCallId 去重,所以一轮里并行
+   * 发出的四次 WebSearch 数出来就是 4)。
+   *
+   * 唯一的读者是座位闸门(workflow-seat-gate.ts):准入调用上只有 `{model}`,分不出一次模型请求
+   * 是这个子代理的下一个 turn step 还是它某个工具内部发的,而**工具侧的请求永不停驻**。有工具在
+   * 跑就是工具侧,一个都没有就是下一个 turn step。用 started/结束配对而不是「上一次事件是什么」:
+   * 并行调用下后者会在第一个工具返回时就误判成空闲。
+   */
+  inFlight(): number;
   /** 本 ask 至今**最近**一次真正开跑的工具调用;一次都没有时缺席。 */
   /** 本 ask 至今**最近**一次真正开跑的工具调用;一次都没有时缺席。 */
   lastTool(): AskLastTool | undefined;
   lastTool(): AskLastTool | undefined;
   /** 订阅 runtime 的 `ToolCallStarted` 会话事件;最小 stub runtime 没有 subscribeEvents 时空操作。 */
   /** 订阅 runtime 的 `ToolCallStarted` 会话事件;最小 stub runtime 没有 subscribeEvents 时空操作。 */
@@ -73,6 +83,8 @@ export function createActorToolActivity(handlers: {
   let lastTool: AskLastTool | undefined;
   let lastTool: AskLastTool | undefined;
   /** toolCallId → scheduled 时的名字与入参,等 started 来认领。 */
   /** toolCallId → scheduled 时的名字与入参,等 started 来认领。 */
   const scheduled = new Map<string, ToolCallSummaryHold>();
   const scheduled = new Map<string, ToolCallSummaryHold>();
+  /** 已 started 还没等到 result / error 的那些 toolCallId(见 {@link ActorToolActivity.inFlight})。 */
+  const running = new Set<string>();
   let unsubscribeEvents: (() => void) | undefined;
   let unsubscribeEvents: (() => void) | undefined;
   return {
   return {
     reset: () => {
     reset: () => {
@@ -81,8 +93,12 @@ export function createActorToolActivity(handlers: {
       worldToolCalls = 0;
       worldToolCalls = 0;
       lastTool = undefined;
       lastTool = undefined;
       scheduled.clear();
       scheduled.clear();
+      // ask 边界上不该还有工具在跑(上一个 ask 的 turn 已经落地或被 abort),归零只是不让
+      // 一次异常路径把残留带进下一个 ask——那会让闸门永远把它当成工具侧请求放行。
+      running.clear();
     },
     },
     counts: () => ({ toolCalls, worldToolCalls }),
     counts: () => ({ toolCalls, worldToolCalls }),
+    inFlight: () => running.size,
     lastTool: () => lastTool,
     lastTool: () => lastTool,
     observe: (runtime, sessionId) => {
     observe: (runtime, sessionId) => {
       if (typeof (runtime as Partial<AgentRuntime>).subscribeEvents !== "function") return;
       if (typeof (runtime as Partial<AgentRuntime>).subscribeEvents !== "function") return;
@@ -93,8 +109,18 @@ export function createActorToolActivity(handlers: {
             holdScheduled(scheduled, event.payload as ToolCallScheduledPayload);
             holdScheduled(scheduled, event.payload as ToolCallScheduledPayload);
             return;
             return;
           }
           }
+          // 一次调用的结束:执行器在 started 之后的 try/catch 两支上各发一条,所以 started 必有配对
+          // (权限拒绝、schema 失败、registry miss 都发生在 started **之前**,只发 error,不影响配对)。
+          if (
+            event.type === SessionEventType.ToolCallResult ||
+            event.type === SessionEventType.ToolCallError
+          ) {
+            running.delete(String((event.payload as { toolCallId: unknown }).toolCallId));
+            return;
+          }
           if (event.type !== SessionEventType.ToolCallStarted) return;
           if (event.type !== SessionEventType.ToolCallStarted) return;
           const capability = event.payload as ToolCallStartedPayload;
           const capability = event.payload as ToolCallStartedPayload;
+          running.add(String(capability.toolCallId));
           const hold = scheduled.get(String(capability.toolCallId));
           const hold = scheduled.get(String(capability.toolCallId));
           scheduled.delete(String(capability.toolCallId));
           scheduled.delete(String(capability.toolCallId));
           lastTool =
           lastTool =

+ 11 - 2
apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-transcript.ts

@@ -30,11 +30,15 @@ import type { AgentRuntimeWorkflowDriverDeps, SessionState } from "./workflow-dr
  *      此刻会话行与消息都刚落好,所以这里不复制 launch 侧那条 `SessionNotFound → 全新`
  *      此刻会话行与消息都刚落好,所以这里不复制 launch 侧那条 `SessionNotFound → 全新`
  *      的降级分支:那条分支的成因是"会话被清理",而在这里它只可能意味着接线错了,该大声失败。
  *      的降级分支:那条分支的成因是"会话被清理",而在这里它只可能意味着接线错了,该大声失败。
  *
  *
- * 第 3 步的**条件**:真复制了就必须水化;一条没抄(幂等跳过)且 journal 已记下这个会话 id,
+ * 第 3 步的**条件**:真复制了就必须水化;一条没抄(跳过)且 journal 已记下这个会话 id,
  * 说明 runtime 工厂刚才已经按 resume 路径重挂过了(launch 的 attachActorSession),再水化一次
  * 说明 runtime 工厂刚才已经按 resume 路径重挂过了(launch 的 attachActorSession),再水化一次
  * 只会多发一条 SessionResumed、多跑一轮 SessionStart 钩子。两个条件都不成立的情形(跳过复制
  * 只会多发一条 SessionResumed、多跑一轮 SessionStart 钩子。两个条件都不成立的情形(跳过复制
  * 且 journal 无记录 = 上一世崩在复制与 putActor 之间)仍要水化,否则 runtime 会带着一个装满
  * 且 journal 无记录 = 上一世崩在复制与 putActor 之间)仍要水化,否则 runtime 会带着一个装满
  * 消息的会话从空上下文开跑。
  * 消息的会话从空上下文开跑。
+ *
+ * 这个条件对 {@link seedActorTranscript} 的**两种**跳过都成立,不必分辨是哪一种:两者的判据
+ * 都是「目标会话已经有自己的内容」,而 `attachActorSession` 决定要不要重挂用的是同一个谓词
+ * (journal 上有没有这个 actor 的 sessionId),所以两处永远同时成立或同时不成立。
  */
  */
 export async function seedActorSession(
 export async function seedActorSession(
   deps: AgentRuntimeWorkflowDriverDeps,
   deps: AgentRuntimeWorkflowDriverDeps,
@@ -54,7 +58,12 @@ export async function seedActorSession(
         `transcript store (wiring error).`,
         `transcript store (wiring error).`,
     );
     );
   }
   }
-  const copied = await seedActorTranscript({ seed, store, targetSessionId: sessionId });
+  const copied = await seedActorTranscript({
+    ...(deps.logger === undefined ? {} : { logger: deps.logger }),
+    seed,
+    store,
+    targetSessionId: sessionId,
+  });
   if (copied === undefined && journaledSessionId !== undefined) return;
   if (copied === undefined && journaledSessionId !== undefined) return;
   await runtime.resumeFromStore();
   await runtime.resumeFromStore();
 }
 }

+ 31 - 4
apps/zcode-cli/packages/bootstrap/src/app/workflow-driver-types.ts

@@ -32,7 +32,9 @@ import type {
 import type { ActorTranscriptStore } from "./workflow-actor-transcript.js";
 import type { ActorTranscriptStore } from "./workflow-actor-transcript.js";
 import type { WorkflowConcurrencyPort } from "./workflow-concurrency-governor.js";
 import type { WorkflowConcurrencyPort } from "./workflow-concurrency-governor.js";
 import type { ActorModelActivity, WorkflowClock } from "./workflow-driver-concurrency.js";
 import type { ActorModelActivity, WorkflowClock } from "./workflow-driver-concurrency.js";
+import type { ActorSessionQuiescence } from "./workflow-driver-quiescence.js";
 import type { WorkflowEscalationRegistry } from "./workflow-escalation-registry.js";
 import type { WorkflowEscalationRegistry } from "./workflow-escalation-registry.js";
+import type { WorkflowRunSeatGate } from "./workflow-seat-gate.js";
 
 
 /** 一个可外部结算的 promise。 */
 /** 一个可外部结算的 promise。 */
 export interface Deferred<T> {
 export interface Deferred<T> {
@@ -153,6 +155,17 @@ export interface AgentRuntimeWorkflowDriverDeps {
    * (v1 的 `acquireSlot` 已删)。
    * (v1 的 `acquireSlot` 已删)。
    */
    */
   concurrency?: WorkflowConcurrencyPort;
   concurrency?: WorkflowConcurrencyPort;
+  /**
+   * 本 run 的座位闸门:本 run
+   * **自己**的并发上界中途被改低时,超出的子代理在下一个 turn step 前停住。在场时 driver 做两件
+   * 事——把每个 actor 的准入端口包进闸门,以及把 ask 的起止喂给它(startAsk 与引擎的
+   * `node-settled`,见 workflow-driver.ts)。
+   *
+   * 可选:缺席即这个 run 的上界从不中途变动(如不支持动态并发调整的 snippet 装配),准入端口与
+   * 从前逐字相同。**在场也不改变从未被改低过的 run 的行为**:上界之上的请求原地通过,闸门不发
+   * 任何事件、不持任何票。
+   */
+  seatGate?: WorkflowRunSeatGate;
   /**
   /**
    * actor 会话的转录存取面(生产是 session store 本身)。两个用途共用它,且**必须**是同一个:
    * actor 会话的转录存取面(生产是 session store 本身)。两个用途共用它,且**必须**是同一个:
    * ask 边界记账的计数,与种子截断的复制(见 workflow-actor-transcript.ts 的模块说明)。
    * ask 边界记账的计数,与种子截断的复制(见 workflow-actor-transcript.ts 的模块说明)。
@@ -171,15 +184,29 @@ export interface AgentRuntimeWorkflowDriverDeps {
    */
    */
   runId?: string;
   runId?: string;
   /**
   /**
-   * 时钟与定时器:run 级 stall 时钟与瞬态失败的退避
-   * 重驱都用它。可注入只为测试假时间;`stallAfterMs` 缺省 20 分钟;`random` 供退避抖动。
+   * 时钟与定时器:run 级 stall 时钟、瞬态失败的退避
+   * 重驱与会话静默的有界等待都用它。支持注入时钟;`stallAfterMs` 缺省 20 分钟;
+   * `quiesceMs` 缺省 {@link AMEND_TRANSCRIPT_QUIESCE_MS};`random` 供退避抖动。
+   */
+  clock?: WorkflowClock & {
+    stallAfterMs?: number;
+    quiesceMs?: number;
+    random?: () => number;
+  };
+  /**
+   * 交出本 driver 的**会话静默探针**(workflow-driver-quiescence.ts)。构造时恰好调一次,
+   * 调用方把探针挂到自己那条 run 的注册表条目上——amend 接续在飞 ask 之前要问它。
+   *
+   * 走回调而不是让 `createAgentRuntimeWorkflowDriver` 返回一个二元组:driver 实例由**引擎**
+   * 在 `makeDriver(sink)` 时才造出来,装配方拿不到那个返回值。缺席即调用方不关心静默
+   * (如直接使用 harness 的路径)。
    */
    */
-  clock?: WorkflowClock & { stallAfterMs?: number; random?: () => number };
+  onQuiescenceProbe?: (probe: ActorSessionQuiescence) => void;
 }
 }
 
 
 /**
 /**
  * 每个 actor 会话的运行态。per-actor FIFO(引擎保证)→ 每会话至多一个在飞 ask,因此
  * 每个 actor 会话的运行态。per-actor FIFO(引擎保证)→ 每会话至多一个在飞 ask,因此
- * currentInstance / pendingSubmit / accepted / cancelled 都是「单前实例」语义,无需按 instance 细分。
+ * currentInstance / pendingSubmit / accepted / cancelled 都是「当前实例」语义,无需按 instance 细分。
  */
  */
 export interface SessionState {
 export interface SessionState {
   readonly ref: SessionRef;
   readonly ref: SessionRef;

+ 67 - 74
apps/zcode-cli/packages/bootstrap/src/app/workflow-driver.ts

@@ -41,14 +41,11 @@
 //     会话已落库的消息条数写进这个 ask 的 journal 行。每个 ask 都写——任何 run 都是未来修订的
 //     会话已落库的消息条数写进这个 ask 的 journal 行。每个 ask 都写——任何 run 都是未来修订的
 //     潜在前驱。
 //     潜在前驱。
 //   - **转录截断**:`createActorSession` 带种子时,把源会话的前 N 条消息复制进新铸的会话再重水化。
 //   - **转录截断**:`createActorSession` 带种子时,把源会话的前 N 条消息复制进新铸的会话再重水化。
+// 本轮又多了第三件,同样只关乎转录、同样住在自己的模块(workflow-driver-quiescence.ts):
+//   - **会话静默登记**:dispose 时记下每个会话是否还有在写的 turn。修订一个在飞前驱时,amend
+//     要据它判断「此刻数出来的消息条数可不可信」,才谈得上接续那条未完的 ask。
 
 
-import type {
-  SessionId,
-  SubmitResultRequest,
-  SubmitVerdict as ContractsSubmitVerdict,
-  WorkflowEscalatePort,
-  WorkflowSubmitPort,
-} from "@zcode/contracts";
+import type { SessionId, WorkflowEscalatePort } from "@zcode/contracts";
 import type { TurnResult } from "@zcode/core";
 import type { TurnResult } from "@zcode/core";
 import {
 import {
   GENERIC_SUBMIT_PROFILE,
   GENERIC_SUBMIT_PROFILE,
@@ -79,6 +76,11 @@ import {
   type RunStallClock,
   type RunStallClock,
 } from "./workflow-driver-concurrency.js";
 } from "./workflow-driver-concurrency.js";
 import { handleModelTurnFailure, type ModelFailureHost } from "./workflow-driver-model-failure.js";
 import { handleModelTurnFailure, type ModelFailureHost } from "./workflow-driver-model-failure.js";
+import {
+  createActorSessionQuiescence,
+  releaseActorSessions,
+  type ActorSessionQuiescenceLedger,
+} from "./workflow-driver-quiescence.js";
 import {
 import {
   makeSessionEscalatePort,
   makeSessionEscalatePort,
   respondToParkedEscalation,
   respondToParkedEscalation,
@@ -88,16 +90,15 @@ import {
 import {
 import {
   NUDGE_PROMPT,
   NUDGE_PROMPT,
   TYPED_TOOL_EPILOGUE,
   TYPED_TOOL_EPILOGUE,
-  defer,
   effectiveActorName,
   effectiveActorName,
   isTurnCancelled,
   isTurnCancelled,
   mapViolations,
   mapViolations,
   mintActorSessionId,
   mintActorSessionId,
-  rejectWith,
   reportTurnObservations,
   reportTurnObservations,
   schemaEpilogue,
   schemaEpilogue,
   toWorkflowError,
   toWorkflowError,
 } from "./workflow-driver-helpers.js";
 } from "./workflow-driver-helpers.js";
+import { makeSessionSubmitPort, type SubmitBridgeHost } from "./workflow-driver-submit-bridge.js";
 import {
 import {
   countSessionTranscript,
   countSessionTranscript,
   journalAskMessageBoundary,
   journalAskMessageBoundary,
@@ -132,14 +133,36 @@ class AgentRuntimeWorkflowDriver implements WorkflowDriver {
   private readonly escalationHost: EscalationHost;
   private readonly escalationHost: EscalationHost;
   /** 交给模型侧失败收容(workflow-driver-model-failure.ts)的宿主面:同一套按引用共享的思路。 */
   /** 交给模型侧失败收容(workflow-driver-model-failure.ts)的宿主面:同一套按引用共享的思路。 */
   private readonly modelFailureHost: ModelFailureHost;
   private readonly modelFailureHost: ModelFailureHost;
+  /** 交给 submit 桥接(workflow-driver-submit-bridge.ts)的宿主面:同上,两样都按引用共享。 */
+  private readonly submitHost: SubmitBridgeHost;
   /** run 级 stall 时钟:所有 actor 的成功 / 重试节拍汇到这一只表。 */
   /** run 级 stall 时钟:所有 actor 的成功 / 重试节拍汇到这一只表。 */
   private readonly stallClock: RunStallClock;
   private readonly stallClock: RunStallClock;
+  /**
+   * 会话静默账(workflow-driver-quiescence.ts):dispose 那一刻每个会话还有没有在写的 turn。
+   * 唯一的读者是 amend——接续前驱的在飞 ask 之前它要确认那个会话已经写完了。
+   */
+  private readonly quiescence: ActorSessionQuiescenceLedger;
 
 
   constructor(deps: AgentRuntimeWorkflowDriverDeps, sink: WorkflowReportSink) {
   constructor(deps: AgentRuntimeWorkflowDriverDeps, sink: WorkflowReportSink) {
     this.deps = deps;
     this.deps = deps;
     this.sink = sink;
     this.sink = sink;
     this.journal = deps.journal;
     this.journal = deps.journal;
-    this.emit = deps.emit;
+    // 引擎的 record() 对**每一条**事件都紧接着调 driver.emit(engine.ts),所以这里是 driver
+    // 看得见 ask 终点的唯一一处:`node-settled` 是三条结算路(settleOk / settleFailed /
+    // abortInFlight)共同的出口,也就是座位闸门等的那条「这一位不工作了」。
+    //
+    // 为什么不用 driver 自己的状态判:`state.currentInstance` 从不清空,untyped ask 经
+    // askTurnEnded 在引擎侧结算之后 `live()` 仍然为真——照它腾座位就永远腾不掉,FIFO 会死等。
+    //
+    // 递下去的**必须是同一个对象引用**:launch 侧的 sequence 截取按引用相等核对序号
+    // (dynamic-workflow-run-launch.ts 的 createJournalSequenceCapture)。
+    this.emit =
+      deps.seatGate === undefined
+        ? deps.emit
+        : (event) => {
+            if (event.type === "node-settled") deps.seatGate?.askSettled(event.instance);
+            deps.emit(event);
+          };
     this.escalationHost = {
     this.escalationHost = {
       deps,
       deps,
       sessions: this.sessions,
       sessions: this.sessions,
@@ -147,6 +170,7 @@ class AgentRuntimeWorkflowDriver implements WorkflowDriver {
       nextEscalationSeq: () => ++this.escalationSeq,
       nextEscalationSeq: () => ++this.escalationSeq,
       record: (event) => this.record(event),
       record: (event) => this.record(event),
     };
     };
+    this.submitHost = { sessions: this.sessions, sink };
     this.modelFailureHost = {
     this.modelFailureHost = {
       deps,
       deps,
       sink,
       sink,
@@ -160,6 +184,13 @@ class AgentRuntimeWorkflowDriver implements WorkflowDriver {
       ...(deps.clock?.stallAfterMs === undefined ? {} : { afterMs: deps.clock.stallAfterMs }),
       ...(deps.clock?.stallAfterMs === undefined ? {} : { afterMs: deps.clock.stallAfterMs }),
       onStalled: (info) => this.sink.runStalled(info),
       onStalled: (info) => this.sink.runStalled(info),
     });
     });
+    this.quiescence = createActorSessionQuiescence({
+      ...(deps.clock === undefined ? {} : { clock: deps.clock }),
+      ...(deps.clock?.quiesceMs === undefined ? {} : { quiesceMs: deps.clock.quiesceMs }),
+    });
+    // 探针在**构造时**就交出去:run service 要在条目上挂住它,而 amend 可能在这个 run 生命的
+    // 任意一刻到来。dispose 之后才交就晚了——那时 service 已经在数会话了。
+    deps.onQuiescenceProbe?.(this.quiescence);
     if (deps.concurrency !== undefined) {
     if (deps.concurrency !== undefined) {
       // 扇出只到在该 key 上有在飞/排队请求的 run,所以订阅本身可以在构造时一次做完。
       // 扇出只到在该 key 上有在飞/排队请求的 run,所以订阅本身可以在构造时一次做完。
       this.concurrencyUnsubscribe = deps.concurrency.subscribe(deps.runId ?? "run", (change) => {
       this.concurrencyUnsubscribe = deps.concurrency.subscribe(deps.runId ?? "run", (change) => {
@@ -193,8 +224,9 @@ class AgentRuntimeWorkflowDriver implements WorkflowDriver {
       );
       );
     }
     }
     const ref: SessionRef = { id: sessionId };
     const ref: SessionRef = { id: sessionId };
-    // 会话级 submit 端口:closure 绑定本会话,模型无法覆盖路由身份(instance 取自 currentInstance)。
-    const submitPort = this.makeSubmitPort(sessionId);
+    // 会话级 submit 端口(实现体在 workflow-driver-submit-bridge.ts,与紧随其后的升级端口
+    // 逐条对称):closure 绑定本会话,模型无法覆盖路由身份(instance 取自 currentInstance)。
+    const submitPort = makeSessionSubmitPort(this.submitHost, sessionId);
     // 升级端口同构:同样按会话 closure 绑定,同样恒注入(见 ActorRuntimeFactory 的字段注释)。
     // 升级端口同构:同样按会话 closure 绑定,同样恒注入(见 ActorRuntimeFactory 的字段注释)。
     // persona 一并入 closure:有效名是**冻结**的(引擎在 createActor 时定下,此后不变),
     // persona 一并入 closure:有效名是**冻结**的(引擎在 createActor 时定下,此后不变),
     // 所以在这里算一次比每次 escalate 现查便宜,也不会中途换名。
     // 所以在这里算一次比每次 escalate 现查便宜,也不会中途换名。
@@ -214,6 +246,12 @@ class AgentRuntimeWorkflowDriver implements WorkflowDriver {
       port: this.deps.concurrency,
       port: this.deps.concurrency,
       runId: this.deps.runId ?? "run",
       runId: this.deps.runId ?? "run",
       live,
       live,
+      // 座位闸门按 **actor** 键入(不是 ask 实例):per-actor FIFO 保证一个 actor 至多一个在飞
+      // ask,所以「工作中的子代理」与「在飞的 ask」是同一个计数,而准入端口本就是按 actor 会话
+      // 造的。
+      ...(this.deps.seatGate === undefined
+        ? {}
+        : { seat: { gate: this.deps.seatGate, key: refToString(actor) } }),
       handlers: {
       handlers: {
         // 子代理的第一笔工作区写入 ⇒ 引擎关导入缓存。
         // 子代理的第一笔工作区写入 ⇒ 引擎关导入缓存。
         onMutating: (instance) => this.sink.askMutating(instance),
         onMutating: (instance) => this.sink.askMutating(instance),
@@ -249,7 +287,12 @@ class AgentRuntimeWorkflowDriver implements WorkflowDriver {
         : { modelRequestAdmission: modelActivity.admission }),
         : { modelRequestAdmission: modelActivity.admission }),
     });
     });
     if (seed !== undefined) {
     if (seed !== undefined) {
-      await seedActorSession(this.deps, { journaledSessionId: journaled, runtime, seed, sessionId });
+      await seedActorSession(this.deps, {
+        journaledSessionId: journaled,
+        runtime,
+        seed,
+        sessionId,
+      });
     }
     }
     state = {
     state = {
       ref,
       ref,
@@ -295,6 +338,10 @@ class AgentRuntimeWorkflowDriver implements WorkflowDriver {
     state.abortController = new AbortController();
     state.abortController = new AbortController();
     // 上一个 ask 的 waiting / executing 相位、工具计数都不能带到这个 ask 上;瞬态重驱计数同理。
     // 上一个 ask 的 waiting / executing 相位、工具计数都不能带到这个 ask 上;瞬态重驱计数同理。
     state.modelActivity.reset();
     state.modelActivity.reset();
+    // ask 的起点喂给座位闸门(终点在 emit 里认 `node-settled`):从这一刻起这个子代理算"在工作",
+    // 它的下一个 turn step 因此要过座位。同一个 actor 连着接到下一个 ask 时这是幂等的加入——
+    // 它本来就一直在工作,中途没有空过。
+    this.deps.seatGate?.askStarted(refToString(state.actor), instance);
     state.transientAttempts = 0;
     state.transientAttempts = 0;
     state.cancelRedrive?.();
     state.cancelRedrive?.();
     state.cancelRedrive = undefined;
     state.cancelRedrive = undefined;
@@ -374,39 +421,23 @@ class AgentRuntimeWorkflowDriver implements WorkflowDriver {
    * beginShutdown、node_repl 会话释放、浏览器会话关闭;不另造一套子代理关闭链,那会漂移。
    * beginShutdown、node_repl 会话释放、浏览器会话关闭;不另造一套子代理关闭链,那会漂移。
    * 不关 execution / MCP / session store:子代理不拥有它们。有在飞 turn 的会话等它落地再关
    * 不关 execution / MCP / session store:子代理不拥有它们。有在飞 turn 的会话等它落地再关
    * (见 SessionState.turn);关闭失败只 warn,结算不因它抛。三张表随之清空。
    * (见 SessionState.turn);关闭失败只 warn,结算不因它抛。三张表随之清空。
+   *
+   * 本方法**同步**,而且刻意不等在飞 turn——引擎的契约是结算之后立刻释放资源。代价是
+   * 「结算 promise 已解决」不蕴含「被中止的 turn 已经把尾巴写完」,所以释放的同时把每个会话
+   * 此刻的在飞 turn 记进静默账:amend 随后据它判断哪个会话的消息条数可信。两件事的编排在
+   * {@link releaseActorSessions}(workflow-driver-quiescence.ts 的文件头写了完整论证)。
    */
    */
   dispose(): void {
   dispose(): void {
     if (this.disposed) return;
     if (this.disposed) return;
     this.disposed = true;
     this.disposed = true;
     this.stallClock.dispose();
     this.stallClock.dispose();
-    for (const state of this.sessions.values()) {
-      state.modelActivity.unsubscribe();
-      state.cancelRedrive?.();
-      state.cancelRedrive = undefined;
-      const close = (): void => this.closeActorRuntime(state);
-      if (state.turn === undefined) close();
-      else state.turn.then(close, close);
-    }
+    releaseActorSessions(this.deps, this.sessions.values(), this.quiescence);
     this.concurrencyUnsubscribe?.();
     this.concurrencyUnsubscribe?.();
     this.sessions.clear();
     this.sessions.clear();
     this.instanceToSession.clear();
     this.instanceToSession.clear();
     this.qidToSession.clear();
     this.qidToSession.clear();
   }
   }
 
 
-  private closeActorRuntime(state: SessionState): void {
-    // Promise.resolve().then(...):把同步抛出也归到同一条 warn 路径(最小 stub runtime 没有这个方法)。
-    void Promise.resolve()
-      .then(() => state.runtime.closeBrowserSession())
-      .catch((error: unknown) => {
-        this.deps.logger?.warn?.("Dynamic workflow actor runtime close failed", {
-          errorMessage: error instanceof Error ? error.message : String(error),
-          event: "dynamic_workflow.actor_runtime.close_failed",
-          module: "bootstrap.app",
-          sessionId: state.sessionId,
-        });
-      });
-  }
-
   /**
   /**
    * 结算一个停驻中的升级问答(run service 经注册表调进来)。实现体在
    * 结算一个停驻中的升级问答(run service 经注册表调进来)。实现体在
    * workflow-driver-escalation.ts({@link respondToParkedEscalation}),这里只做委托。
    * workflow-driver-escalation.ts({@link respondToParkedEscalation}),这里只做委托。
@@ -527,49 +558,11 @@ class AgentRuntimeWorkflowDriver implements WorkflowDriver {
     this.sink.askFailed(instance, toWorkflowError(error));
     this.sink.askFailed(instance, toWorkflowError(error));
   }
   }
 
 
-  // ——————————————————————————————— 内部:submit 桥接 ———————————————————————————————
-
-  /** 造一个会话级 submit 端口:submit_result handler mid-turn 调用它并阻塞等裁决。 */
-  private makeSubmitPort(sessionId: SessionId): WorkflowSubmitPort {
-    return {
-      respond: (request: SubmitResultRequest): Promise<ContractsSubmitVerdict> => {
-        const state = this.sessions.get(sessionId);
-        const instance = state?.currentInstance;
-        if (state === undefined || instance === undefined) {
-          // 无在飞 ask 却收到 submit:不路由到引擎,直接拒绝(避免悬挂)。
-          return Promise.resolve(rejectWith("no active ask is awaiting a submitted result"));
-        }
-        // Untyped ask 守卫:设计上「全 untyped 的 actor 不注册 submit_result」,
-        // 但 driver 在 createActorSession 时拿不到 actor 的聚合 typed 信息(需 site graph,未透传),故
-        // 一律注册。为不依赖引擎「submitAttempted 对 untyped 早退」的行为(那会让 deferred 永久悬挂),
-        // 这里在 driver 内部直接拦截:untyped ask 收到 submit 时立即回一条合成 rejection 让模型改用纯文本,
-        // 绝不上报 askSubmitAttempted。后续版本可据 actor-graph 投影把 per-actor typed 信息透传进来,
-        // 真正在 untyped-only actor 上跳过注册(关系到 prompt-cache 的 frozen-tools 不变式)。
-        if (!state.currentTyped) {
-          return Promise.resolve(
-            rejectWith(
-              "this ask does not accept submit_result; provide your answer as your final message",
-            ),
-          );
-        }
-        // 单前实例不变式:至多一个挂起 deferred。若已有(不应发生),先拒旧的避免泄漏。
-        state.pendingSubmit?.reject(
-          new WorkflowError("DriverError", "This submit was superseded by a newer submit."),
-        );
-        const deferred = defer<ContractsSubmitVerdict>();
-        state.pendingSubmit = deferred;
-        // 同步上报:引擎在本调用栈内校验并经 respondToSubmit 回裁决(同步解开 deferred)。
-        this.sink.askSubmitAttempted(instance, request.result);
-        return deferred.promise;
-      },
-    };
-  }
-
   // ——————————————————————————————— 内部:升级问答桥接 ———————————————————————————————
   // ——————————————————————————————— 内部:升级问答桥接 ———————————————————————————————
 
 
   /**
   /**
    * 造一个会话级升级端口;实现体在 workflow-driver-escalation.ts({@link makeSessionEscalatePort}),
    * 造一个会话级升级端口;实现体在 workflow-driver-escalation.ts({@link makeSessionEscalatePort}),
-   * 与 {@link makeSubmitPort} 逐条对称的论证也写在那边。
+   * 与 {@link makeSessionSubmitPort} 逐条对称的论证也写在那边。
    */
    */
   private makeEscalatePort(
   private makeEscalatePort(
     sessionId: SessionId,
     sessionId: SessionId,

+ 47 - 0
apps/zcode-cli/packages/bootstrap/src/app/workflow-run-control.ts

@@ -0,0 +1,47 @@
+// ============================================================
+// run 的活体控制面:一次命令同时落到引擎与座位闸门
+// ============================================================
+// 一个在飞 run 的两个执行点住在不同的
+// 层里——调度器在引擎(`@zcode/dynamic-workflow`),座位闸门在 driver 之下(本包)——而发命令的
+// 那一侧(run service 的 `retuneConcurrency`)两个都够不着:引擎是 harness 在子进程装配起来之后
+// 才存在的,闸门是 launch 造的。
+//
+// 所以 run service 先造一个**空的**句柄放进注册表条目,两边各自在自己出生的那一刻把自己接上去:
+// harness 拿到 `bind(engine)`(与 `signal` 同一条缝递进去),launch 拿到 `bindSeatGate(gate)`。
+// 句柄本身不判断任何事:存活判定、no-op 语义与落库全在引擎的 `setMaxConcurrency` 里,闸门只在
+// 引擎说"这次真的改了"之后才跟着换上界——两个执行点因此不可能各执一词。
+//
+// 顺序是载荷性的:**引擎先**。引擎的布尔值就是这次命令的裁决(已结算 / 值没变 ⇒ false,什么也
+// 没发生),闸门若抢在前面换了上界,一个已经结算的 run 就会留下一个与 journal 行不符的内存上界。
+
+import type { RunControlBinding } from "@zcode/dynamic-workflow-runtime";
+import type { WorkflowRunSeatGate } from "./workflow-seat-gate.js";
+
+export interface WorkflowRunControl extends RunControlBinding {
+  /**
+   * 就地改本 run 自己的并发上界。返回**这次是否真的改了**:`false` 即什么也没发生——引擎还没
+   * 接上(launch 之前的那几个微任务)、run 已结算,或新值与当前值相同。调用方据此回落。
+   */
+  setMaxConcurrency(maxConcurrency: number): boolean;
+  /** launch 造好座位闸门之后接上去;缺席即这个 run 只有调度器一个执行点。 */
+  bindSeatGate(gate: Pick<WorkflowRunSeatGate, "setLimit">): void;
+}
+
+export function createWorkflowRunControl(): WorkflowRunControl {
+  let engine: { setMaxConcurrency(maxConcurrency: number): boolean } | undefined;
+  let seatGate: Pick<WorkflowRunSeatGate, "setLimit"> | undefined;
+  return {
+    bind: (bound) => {
+      engine = bound;
+    },
+    bindSeatGate: (gate) => {
+      seatGate = gate;
+    },
+    setMaxConcurrency: (maxConcurrency) => {
+      if (engine === undefined) return false;
+      if (!engine.setMaxConcurrency(maxConcurrency)) return false;
+      seatGate?.setLimit(maxConcurrency);
+      return true;
+    },
+  };
+}

+ 186 - 0
apps/zcode-cli/packages/bootstrap/src/app/workflow-seat-gate.ts

@@ -0,0 +1,186 @@
+// ============================================================
+// run 级座位闸门:把本 run 自己的并发上界压到**下一次模型请求**上
+// ============================================================
+// 调度器是第一个执行点,但它只在
+// 派发时看上界,而一个 ask 是子代理的一整轮、动辄数分钟——对一个已有八个在飞 ask 的 run 说
+// 「最多两个」,光靠调度器要等六个 ask 自己跑完才看得见。本闸门是第二个执行点:超出上界的子代理
+// 跑完手上这次请求之后**在下一个 turn step 前停住**,会话、转录与它在 run 里的位置一个不丢。
+//
+// 三条纪律:
+//   1. **纯的**:不读时钟、不做 I/O、不订阅任何东西。两件事实(谁有在飞 ask、谁有工具在跑)都由
+//      driver 既有的观察面喂进来(workflow-driver.ts 的 startAsk / emit,
+//      workflow-driver-tool-activity.ts 的在飞计数),闸门自己不再记第二份账。
+//   2. **与调度器零共享状态**,两者也从不互相调用。让它们一致的是算术:`activeAsks = working +
+//      parked`——停驻的子代理那个 ask 仍然活着,仍然算在调度器的上界里。于是只要有人停驻,
+//      `activeAsks ≥ limit`,调度器就派发不出新 ask,绝不可能插到一个停驻者前面。
+//   3. **上界 ≥ 1 ⇒ 永不死锁**:停驻的前提是「工作中的人数已经超过上界」,所以总有人在工作;
+//      FIFO 不空时最后一个座位不可能是空的。
+//
+// 工具侧的请求**永不**停驻:那个子代理本就在
+// 工作、本就占着座位,让它的 WebSearch 排在自己后面就是排给自己看。准入调用上只有 `{model}`,
+// 分不出是什么请求,所以闸门读 driver 已经为这个子代理记着的那条事实——它此刻有没有工具在跑。
+
+import type { ModelRequestAdmission } from "@zcode/contracts";
+import { refToString, type InstanceRef } from "@zcode/dynamic-workflow";
+
+/** 闸门向 driver 要的唯一一条子代理事实(实现在 workflow-driver-tool-activity.ts)。 */
+export interface SeatGateSubagent {
+  /** 此刻有几个工具调用在跑;> 0 即这次请求是工具侧的,直接放行。 */
+  toolsInFlight(): number;
+}
+
+/** 闸门此刻的两个计数(观察面:`activeAsks = working + parked` 的断言读它)。 */
+export interface SeatGateStats {
+  limit: number;
+  working: number;
+  parked: number;
+}
+
+export interface WorkflowRunSeatGate {
+  /**
+   * 换上界。抬高之后立刻按 FIFO 放行到新上界为止;压低不召回任何人——超出的那些跑完手上这次
+   * 请求、在下一个 turn step 上自己停驻。
+   */
+  setLimit(limit: number): void;
+  /** 一个 ask 派发到了这个子代理(driver.startAsk 的同一刻)。 */
+  askStarted(key: string, instance: InstanceRef): void;
+  /** 引擎为这个实例记下了 `node-settled`(ask 的**唯一**终点,见 workflow-driver.ts 的 emit)。 */
+  askSettled(instance: InstanceRef): void;
+  /**
+   * 把一个子代理的准入端口包成「先过座位、再过治理器」的那一个。`inner` 缺席即这个 runtime
+   * 本就不受闸门约束(没有治理器端口的装配),闸门也不凭空造一个——两条闸门要么一起在,
+   * 要么一起不在。
+   */
+  wrap(
+    key: string,
+    subagent: SeatGateSubagent,
+    inner: ModelRequestAdmission | undefined,
+  ): ModelRequestAdmission | undefined;
+  stats(): SeatGateStats;
+}
+
+/** FIFO 里的一位:它的键、解开它的两个口,以及撤掉 abort 监听的那一手。 */
+interface ParkedSeat {
+  key: string;
+  grant: () => void;
+  refuse: (reason: unknown) => void;
+}
+
+export function createWorkflowRunSeatGate(input: { limit: number }): WorkflowRunSeatGate {
+  let limit = Math.max(1, Math.floor(input.limit));
+  /** 有在飞 ask 且**没有**停驻的子代理。停驻的那一刻从这里移出去,放行时再加回来。 */
+  const working = new Set<string>();
+  /** 等座位的子代理,先来先走。 */
+  const parked: ParkedSeat[] = [];
+  /** `refToString(instance)` → 子代理键:ask 的终点只带实例,回不到子代理身上就无从腾座位。 */
+  const instances = new Map<string, string>();
+
+  const parkedIndexOf = (key: string): number => parked.findIndex((seat) => seat.key === key);
+
+  /** 还有空位就按 FIFO 放行。放行是「进 working」而不是「发一张票」——座位就是 working 的名额。 */
+  const unpark = (): void => {
+    while (working.size < limit && parked.length > 0) {
+      const seat = parked.shift()!;
+      working.add(seat.key);
+      seat.grant();
+    }
+  };
+
+  /** 这次请求要不要过座位:只有「有在飞 ask 且手上没有工具在跑」的子代理才是一个 turn step。 */
+  const needsSeat = (key: string, subagent: SeatGateSubagent): boolean =>
+    working.has(key) && subagent.toolsInFlight() === 0;
+
+  const acquireSeat = async (key: string, signal: AbortSignal | undefined): Promise<void> => {
+    // 上界之内:原地通过,不动任何状态。没有 retune 压低过的 run 永远走这一支——快路径一字未变。
+    if (working.size <= limit) return;
+    if (signal?.aborted === true) throw signal.reason;
+    working.delete(key);
+    return await new Promise<void>((resolve, reject) => {
+      const onAbort = (): void => {
+        const index = parkedIndexOf(key);
+        if (index >= 0) {
+          parked.splice(index, 1);
+          // **出队即回到 working**:这个闸门里「不在 parked」只有一种含义,就是在工作。abort 的
+          // 是**这次请求**,不一定是这个 ask——driver 侧的瞬态重驱、流恢复、任何 per-request 信号
+          // 都会在 ask 还活着的时候走到这里。把它留在两个集合之外,它此后每一次 turn 请求都因为
+          // `needsSeat` 为假而无闸通过,而且再也不会被数进 working:上界会悄悄地往上漂。
+          //
+          // 加回去可能让 working 一时超过上界,那是合法的瞬态(与调低上界那一刻同形):下一个
+          // 提出 turn 请求的人照常停驻,计数随即收敛。abort 之后真的结算时,askSettled 会
+          // `working.delete` 成功并调 unpark,而 unpark 的 `working.size < limit` 守卫挡住了
+          // 「腾出一个它从未占过的座位」——停驻发生时 working ≥ limit,加回来就是 ≥ limit+1,
+          // 删掉之后仍 ≥ limit,于是一个都不放。
+          working.add(key);
+        }
+        reject(signal?.reason);
+      };
+      const seat: ParkedSeat = {
+        key,
+        grant: () => {
+          signal?.removeEventListener("abort", onAbort);
+          resolve();
+        },
+        refuse: (reason) => {
+          signal?.removeEventListener("abort", onAbort);
+          reject(reason);
+        },
+      };
+      parked.push(seat);
+      signal?.addEventListener("abort", onAbort, { once: true });
+    });
+  };
+
+  return {
+    setLimit: (next) => {
+      limit = Math.max(1, Math.floor(next));
+      unpark();
+    },
+
+    askStarted: (key, instance) => {
+      instances.set(refToString(instance), key);
+      // 停驻中的子代理不可能收到新 ask(它的 turn 正卡在 acquire 里,引擎那边 actor.current 还占着),
+      // 但两个集合同时收下同一个键会把它数成两个人——宁可在这里挡一次。
+      if (parkedIndexOf(key) >= 0) return;
+      working.add(key);
+    },
+
+    askSettled: (instance) => {
+      const ref = refToString(instance);
+      const key = instances.get(ref);
+      if (key === undefined) return;
+      instances.delete(ref);
+      const parkedIndex = parkedIndexOf(key);
+      if (parkedIndex >= 0) {
+        // 停驻中 ask 结束:**不腾座位**(它本就没有),否则这一位会被数两次。
+        // 只可能是引擎主动取消(停驻中的 turn 卡在 acquire 里,报不出任何 turn 终局),而那条路
+        // 先调 driver.cancelAsk(abort 会拒掉上面的等待)再记 node-settled,所以正常次序下这里
+        // 已经找不到它了。反序到达时把等待一并拒掉,免得一个没人要的 ask 之后还被放行。
+        const [seat] = parked.splice(parkedIndex, 1);
+        seat?.refuse(new Error("workflow ask settled while waiting for a concurrency seat"));
+        return;
+      }
+      if (!working.delete(key)) return;
+      unpark();
+    },
+
+    wrap: (key, subagent, inner) => {
+      if (inner === undefined) return undefined;
+      return {
+        // 快路径:这次请求要过座位、而座位已经满了 ⇒ 未命中。runner 因此发 `model_request_queued`,
+        // driver 报 `askWaiting(slot)`——与共享 cap 造成的等待逐字相同的那一条,不需要新词汇。
+        tryAcquire: (request) => {
+          if (needsSeat(key, subagent) && working.size > limit) return undefined;
+          return inner.tryAcquire?.(request);
+        },
+        // 顺序是载荷性的:**先**等座位,**再**过治理器。反过来就会让一个本该停驻的子代理先占住
+        // 治理器的一张票,再在闸门这边睡——那张票对谁都没有用。
+        acquire: async (request) => {
+          if (needsSeat(key, subagent)) await acquireSeat(key, request.signal);
+          return await inner.acquire(request);
+        },
+      };
+    },
+
+    stats: () => ({ limit, working: working.size, parked: parked.length }),
+  };
+}

+ 30 - 7
apps/zcode-cli/packages/bootstrap/src/builtin-prompt-command.ts

@@ -1,8 +1,20 @@
 import { join } from "node:path";
 import { join } from "node:path";
+import {
+  BUILTIN_WORKFLOW_COMMAND_NAME,
+  expandBuiltinWorkflowCommandPrompt,
+} from "./builtin-workflow-command.js";
 
 
 const BUILTIN_PROMPT_COMMAND_PATTERN = /^\/([^\s]+)(?:\s+([\s\S]*))?$/;
 const BUILTIN_PROMPT_COMMAND_PATTERN = /^\/([^\s]+)(?:\s+([\s\S]*))?$/;
+const INIT_COMMAND_NAME = "init";
 
 
 interface ResolveZCodeBuiltinPromptCommandOptions {
 interface ResolveZCodeBuiltinPromptCommandOptions {
+  /**
+   * 动态工作流开关:只有显式 false 才禁止展开 `/workflow`。
+   * TUI 使用默认开启策略;headless 按本次 `--enable-workflow` 显式传入 true/false,默认 false。
+   * 关闭时返回 undefined;`workflow` 是保留名,自定义命令解析也不会展开它,原文作为普通 prompt
+   * 交给模型。这与命令目录隐藏该入口的规则一致。
+   */
+  dynamicWorkflowEnabled?: boolean;
   workingDirectory?: string;
   workingDirectory?: string;
 }
 }
 
 
@@ -11,16 +23,27 @@ export function resolveZCodeBuiltinPromptCommand(
   options: ResolveZCodeBuiltinPromptCommandOptions = {},
   options: ResolveZCodeBuiltinPromptCommandOptions = {},
 ): string | undefined {
 ): string | undefined {
   const invocation = parseBuiltinPromptCommandInvocation(input);
   const invocation = parseBuiltinPromptCommandInvocation(input);
-  if (!invocation || invocation.name !== "init") {
+  if (!invocation) {
     return undefined;
     return undefined;
   }
   }
 
 
-  const workingDirectory = options.workingDirectory ?? process.cwd();
-  return buildInitAgentsPrompt({
-    args: invocation.args,
-    targetPath: join(workingDirectory, "AGENTS.md"),
-    workingDirectory,
-  });
+  if (invocation.name === INIT_COMMAND_NAME) {
+    const workingDirectory = options.workingDirectory ?? process.cwd();
+    return buildInitAgentsPrompt({
+      args: invocation.args,
+      targetPath: join(workingDirectory, "AGENTS.md"),
+      workingDirectory,
+    });
+  }
+
+  if (invocation.name === BUILTIN_WORKFLOW_COMMAND_NAME) {
+    if (options.dynamicWorkflowEnabled === false) {
+      return undefined;
+    }
+    return expandBuiltinWorkflowCommandPrompt(invocation.args);
+  }
+
+  return undefined;
 }
 }
 
 
 function parseBuiltinPromptCommandInvocation(input: string): { args: string; name: string } | null {
 function parseBuiltinPromptCommandInvocation(input: string): { args: string; name: string } | null {

+ 63 - 0
apps/zcode-cli/packages/bootstrap/src/builtin-workflow-command.ts

@@ -0,0 +1,63 @@
+import { expandCustomCommandPrompt, type CustomCommandContent } from "@zcode/contracts";
+import { BUILTIN_ZCODE_SLASH_COMMAND_HELP_ENTRIES } from "@zcode/shared";
+import { DYNAMIC_WORKFLOW_SKILL_NAME } from "./app/bundled-skills.js";
+
+/**
+ * 内置 `/workflow` 命令。
+ * 命令正文随 CLI 编译,与 `/init` 同为代码定义的 prompt 命令,不依赖可卸载插件。
+ * 命令名进入保留字表,用户或插件的同名命令不会被展开。
+ *
+ * 正文复用 contracts 的 custom command 展开规则:替换 $ARGUMENTS,并补充 `skills:` 前言。
+ */
+export const BUILTIN_WORKFLOW_COMMAND_NAME = "workflow";
+
+const helpEntry = BUILTIN_ZCODE_SLASH_COMMAND_HELP_ENTRIES.find(
+  (entry) => entry.name === BUILTIN_WORKFLOW_COMMAND_NAME,
+);
+if (!helpEntry) {
+  // 共享 help 表是保留字、TUI 候选与 App 目录的唯一来源;条目缺席时命令根本不可寻址。
+  throw new Error(`Missing builtin slash command help entry: ${BUILTIN_WORKFLOW_COMMAND_NAME}`);
+}
+
+const USAGE_PREFIX = `/${BUILTIN_WORKFLOW_COMMAND_NAME} `;
+export const BUILTIN_WORKFLOW_COMMAND_DESCRIPTION = helpEntry.summary;
+export const BUILTIN_WORKFLOW_COMMAND_ARGUMENT_HINT = helpEntry.usage.startsWith(USAGE_PREFIX)
+  ? helpEntry.usage.slice(USAGE_PREFIX.length)
+  : "";
+
+/** `$ARGUMENTS` 必须在场:否则展开会把参数追加成位置不受控的 "User arguments:" 尾块。 */
+const BUILTIN_WORKFLOW_COMMAND_BODY = [
+  `Use the \`${DYNAMIC_WORKFLOW_SKILL_NAME}\` skill to design and launch a dynamic workflow for this request:`,
+  "",
+  "$ARGUMENTS",
+  "",
+  "Decide the subagent topology before writing any code: how many subagents, which of them",
+  "share a context, what result each one returns. Then write the script and call the",
+  "`CreateWorkflow` tool. (`CreateWorkflow` is the dynamic-workflow tool. Do not use the",
+  "legacy `Workflow` tool, and do not substitute the `Agent` tool.)",
+  "",
+].join("\n");
+
+export const BUILTIN_WORKFLOW_COMMAND: CustomCommandContent = {
+  bytesRead: Buffer.byteLength(BUILTIN_WORKFLOW_COMMAND_BODY),
+  content: BUILTIN_WORKFLOW_COMMAND_BODY,
+  metadata: {
+    allowedTools: [],
+    argumentHint: BUILTIN_WORKFLOW_COMMAND_ARGUMENT_HINT,
+    description: BUILTIN_WORKFLOW_COMMAND_DESCRIPTION,
+    disableNonInteractive: false,
+    frontmatterKeys: ["description", "argument-hint", "skills"],
+    name: BUILTIN_WORKFLOW_COMMAND_NAME,
+    path: `builtin:${BUILTIN_WORKFLOW_COMMAND_NAME}`,
+    rootPath: "builtin:",
+    scope: "system",
+    skills: [DYNAMIC_WORKFLOW_SKILL_NAME],
+    source: "zcode",
+  },
+  sizeBytes: Buffer.byteLength(BUILTIN_WORKFLOW_COMMAND_BODY),
+  truncated: false,
+};
+
+export function expandBuiltinWorkflowCommandPrompt(args: string): string {
+  return expandCustomCommandPrompt({ args, command: BUILTIN_WORKFLOW_COMMAND }).prompt;
+}

+ 2 - 14
apps/zcode-cli/packages/bootstrap/src/custom-command-prompt.ts

@@ -14,14 +14,6 @@ const CUSTOM_COMMAND_NOT_FOUND_PATTERN = /not found/i;
 const PROMPT_CUSTOM_COMMAND_PATTERN = /^\/([^\s]+)(?:\s+([\s\S]*))?$/;
 const PROMPT_CUSTOM_COMMAND_PATTERN = /^\/([^\s]+)(?:\s+([\s\S]*))?$/;
 
 
 interface ResolveZCodeCustomCommandPromptOptions extends ListZCodeCustomCommandsOptions {
 interface ResolveZCodeCustomCommandPromptOptions extends ListZCodeCustomCommandsOptions {
-  /**
-   * 本会话不可寻址的自定义命令名(小写)。与 `isReservedZCodeSlashCommandName` 是同一个
-   * 概念的两个来源:那个是全局保留字,这个是调用方按会话下发的门禁,目前唯一使用者是
-   * 动态工作流灰度关闭时的 `workflow`。
-   * 刻意按**命令名**而不是禁用路径表达:`workflow` 来自随 CLI 打包的 zcode-guide 插件,
-   * 其 SKILL/命令文件落在插件缓存目录,调用方拿不到稳定路径。
-   */
-  disabledCommandNames?: readonly string[];
   executionPort?: ExecutionPort;
   executionPort?: ExecutionPort;
   sessionId?: SessionId;
   sessionId?: SessionId;
   signal?: AbortSignal;
   signal?: AbortSignal;
@@ -33,15 +25,11 @@ export async function resolveZCodeCustomCommandPrompt(
   options: ResolveZCodeCustomCommandPromptOptions = {},
   options: ResolveZCodeCustomCommandPromptOptions = {},
 ): Promise<string | undefined> {
 ): Promise<string | undefined> {
   const invocation = parsePromptCustomCommandInvocation(input);
   const invocation = parsePromptCustomCommandInvocation(input);
+  // 保留名(含内置 `workflow`)在这里直接返回 undefined,与「命令不存在」同形:内置命令由
+  // builtin-prompt-command.ts 先行展开,这里拒绝的是借同名自定义命令绕过内置语义(或功能开关)的路径。
   if (!invocation || isReservedZCodeSlashCommandName(invocation.name)) {
   if (!invocation || isReservedZCodeSlashCommandName(invocation.name)) {
     return undefined;
     return undefined;
   }
   }
-  // 最小侵入点:这里是 `/name` 变成一条命令查找的唯一入口,也是保留字判定已经落脚的地方。
-  // 放在 load 之前,被门禁挡住的命令连文件都不读;返回 undefined 与「命令不存在」同形,
-  // 上层 input facade 会把原文当普通 prompt 交给模型,不会出现半展开的提示词。
-  if (options.disabledCommandNames?.includes(invocation.name)) {
-    return undefined;
-  }
 
 
   try {
   try {
     const command = await loadZCodeCustomCommand({
     const command = await loadZCodeCustomCommand({

+ 15 - 6
apps/zcode-cli/packages/bootstrap/src/skills.ts

@@ -1,7 +1,9 @@
 import { resolve } from "node:path";
 import { resolve } from "node:path";
-import { createConfig } from "@zcode/adapters/config";
+import { createConfig, resolvePath } from "@zcode/adapters/config";
 import { createNodeSkillAdapter } from "@zcode/adapters/skills";
 import { createNodeSkillAdapter } from "@zcode/adapters/skills";
 import type { Logger, SkillContent, SkillDiagnostic, SkillLoadOutcome } from "@zcode/contracts";
 import type { Logger, SkillContent, SkillDiagnostic, SkillLoadOutcome } from "@zcode/contracts";
+import { resolveBundledSkillRoots } from "./app/bundled-skills.js";
+import { getCliStorageRoot } from "./app/paths.js";
 import { resolveZCodePlugins } from "./plugins.js";
 import { resolveZCodePlugins } from "./plugins.js";
 import { collectDisabledPaths } from "./skill-command-overrides.js";
 import { collectDisabledPaths } from "./skill-command-overrides.js";
 
 
@@ -26,7 +28,7 @@ export interface ZCodeSkillInspection {
 export async function listZCodeSkills(
 export async function listZCodeSkills(
   options: ListZCodeSkillsOptions = {},
   options: ListZCodeSkillsOptions = {},
 ): Promise<SkillLoadOutcome> {
 ): Promise<SkillLoadOutcome> {
-  const discovery = createSkillDiscovery(options);
+  const discovery = await createSkillDiscovery(options);
   if (!discovery.enabled) {
   if (!discovery.enabled) {
     return {
     return {
       diagnostics: [],
       diagnostics: [],
@@ -43,7 +45,7 @@ export async function listZCodeSkills(
 export async function inspectZCodeSkill(
 export async function inspectZCodeSkill(
   options: InspectZCodeSkillOptions,
   options: InspectZCodeSkillOptions,
 ): Promise<ZCodeSkillInspection> {
 ): Promise<ZCodeSkillInspection> {
-  const discovery = createSkillDiscovery(options);
+  const discovery = await createSkillDiscovery(options);
   if (!discovery.enabled) {
   if (!discovery.enabled) {
     throw new Error("Skills are disabled.");
     throw new Error("Skills are disabled.");
   }
   }
@@ -70,7 +72,7 @@ export async function inspectZCodeSkill(
   };
   };
 }
 }
 
 
-function createSkillDiscovery(options: ListZCodeSkillsOptions):
+async function createSkillDiscovery(options: ListZCodeSkillsOptions): Promise<
   | {
   | {
       enabled: false;
       enabled: false;
       workingDirectory: string;
       workingDirectory: string;
@@ -79,7 +81,8 @@ function createSkillDiscovery(options: ListZCodeSkillsOptions):
       enabled: true;
       enabled: true;
       skillPort: ReturnType<typeof createNodeSkillAdapter>;
       skillPort: ReturnType<typeof createNodeSkillAdapter>;
       workingDirectory: string;
       workingDirectory: string;
-    } {
+    }
+> {
   const workingDirectory = resolve(options.workingDirectory ?? process.cwd());
   const workingDirectory = resolve(options.workingDirectory ?? process.cwd());
   const configResult = createConfig({
   const configResult = createConfig({
     env: options.env,
     env: options.env,
@@ -105,11 +108,17 @@ function createSkillDiscovery(options: ListZCodeSkillsOptions):
     workingDirectory,
     workingDirectory,
   });
   });
 
 
+  // 内置技能包与插件技能根并列注入:`zcode skills list`、引用目录与 runtime 看到同一份发现结果。
+  const bundledSkillRoots = await resolveBundledSkillRoots({
+    cliStorageRoot: getCliStorageRoot(resolvePath(configResult.config.storage.dir)),
+    logger: options.logger,
+  });
+
   return {
   return {
     enabled: true,
     enabled: true,
     skillPort: createNodeSkillAdapter({
     skillPort: createNodeSkillAdapter({
       extraRoots: configResult.config.skills.roots,
       extraRoots: configResult.config.skills.roots,
-      extraResolvedRoots: pluginOutcome.skillRoots,
+      extraResolvedRoots: [...pluginOutcome.skillRoots, ...bundledSkillRoots],
       disabledPaths: collectDisabledPaths(configResult.config.skillOverrides),
       disabledPaths: collectDisabledPaths(configResult.config.skillOverrides),
     }),
     }),
     workingDirectory,
     workingDirectory,

+ 6 - 0
apps/zcode-cli/packages/bootstrap/src/slash-command-surface.ts

@@ -1,7 +1,13 @@
 import { BUILTIN_ZCODE_SLASH_COMMAND_HELP_ENTRIES, type ZCodeSlashCommand } from "@zcode/shared";
 import { BUILTIN_ZCODE_SLASH_COMMAND_HELP_ENTRIES, type ZCodeSlashCommand } from "@zcode/shared";
 
 
+/**
+ * App `/` 面板与加号菜单按本顺序展示(UI 不维护排序白名单)。`workflow` 紧随 `goal`:两者都是
+ * 「开启一段工作」的入口;它受动态工作流开关约束,
+ * 由 zcode-protocol/slash-commands.ts 在装配时剔除。
+ */
 export const APP_PROTOCOL_VISIBLE_BUILTIN_SLASH_COMMAND_NAMES = [
 export const APP_PROTOCOL_VISIBLE_BUILTIN_SLASH_COMMAND_NAMES = [
   "goal",
   "goal",
+  "workflow",
   "compact",
   "compact",
   "init",
   "init",
 ] as const;
 ] as const;

+ 1 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/commands/handlers/session-flow.ts

@@ -274,6 +274,7 @@ async function sendText(
       intent,
       intent,
       ...(payload.context_refs ? { sharedContextRefs: payload.context_refs } : {}),
       ...(payload.context_refs ? { sharedContextRefs: payload.context_refs } : {}),
       ...turnBackgroundAttributionOf(payload),
       ...turnBackgroundAttributionOf(payload),
+      ...(payload.botDeliveryTarget ? { botDeliveryTarget: payload.botDeliveryTarget } : {}),
       toolDisallowlist: payload.toolDisallowlist,
       toolDisallowlist: payload.toolDisallowlist,
       ...(payload.modelExecution
       ...(payload.modelExecution
         ? { modelExecution: createModelExecutionContext(payload.modelExecution) }
         ? { modelExecution: createModelExecutionContext(payload.modelExecution) }

+ 31 - 4
apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/commands/prompt-turn.ts

@@ -5,6 +5,7 @@
 // starting/active 状态都会继续挡住同一 session 的第二次 start。
 // starting/active 状态都会继续挡住同一 session 的第二次 start。
 import { type TurnBackgroundAttribution, type TurnInputIntentMetadata } from "@zcode/contracts";
 import { type TurnBackgroundAttribution, type TurnInputIntentMetadata } from "@zcode/contracts";
 import type { TurnAttachment } from "@zcode/core";
 import type { TurnAttachment } from "@zcode/core";
+import type { ZCodeAutomationBotDeliveryTarget } from "@zcode/shared";
 import type { SendInputOptions, SendInputResult } from "../../app/types.js";
 import type { SendInputOptions, SendInputResult } from "../../app/types.js";
 import { runWithSessionResidencyFinalization } from "../../zcode-protocol/session-residency.js";
 import { runWithSessionResidencyFinalization } from "../../zcode-protocol/session-residency.js";
 import type { V4CommandCoreHost, V4SessionRecordView } from "./types.js";
 import type { V4CommandCoreHost, V4SessionRecordView } from "./types.js";
@@ -24,6 +25,8 @@ interface StartPromptTurnParamsBase {
   toolDisallowlist?: readonly string[];
   toolDisallowlist?: readonly string[];
   /** sendQueuedNow 已持有 Core promotion lease,要求这次 admission 只能占用空闲位。 */
   /** sendQueuedNow 已持有 Core promotion lease,要求这次 admission 只能占用空闲位。 */
   requireIdle?: boolean;
   requireIdle?: boolean;
+  /** Bot 入站 turn 的稳定回推地址;仅在本 turn 内暴露给 CronCreate。 */
+  botDeliveryTarget?: ZCodeAutomationBotDeliveryTarget;
 }
 }
 
 
 type StartPromptTurnParams = StartPromptTurnParamsBase & TurnBackgroundAttribution;
 type StartPromptTurnParams = StartPromptTurnParamsBase & TurnBackgroundAttribution;
@@ -85,6 +88,7 @@ export async function startPromptTurn(
 
 
   const previousAutomationId = record.activeAutomationId;
   const previousAutomationId = record.activeAutomationId;
   const previousOffPeakTaskId = record.activeOffPeakTaskId;
   const previousOffPeakTaskId = record.activeOffPeakTaskId;
+  const previousBotDeliveryTarget = record.activeBotDeliveryTarget;
   const activeAutomationId = resolveTurnAutomationId(params);
   const activeAutomationId = resolveTurnAutomationId(params);
   const activeOffPeakTaskId = resolveTurnOffPeakTaskId(params);
   const activeOffPeakTaskId = resolveTurnOffPeakTaskId(params);
   const turnToolDisallowlist = buildTurnToolDisallowlist(
   const turnToolDisallowlist = buildTurnToolDisallowlist(
@@ -97,6 +101,7 @@ export async function startPromptTurn(
     // 闲时派发轮同型标记,供 offpeak-port 在工具执行前拒绝递归 OffPeakCreate。
     // 闲时派发轮同型标记,供 offpeak-port 在工具执行前拒绝递归 OffPeakCreate。
     record.activeOffPeakTaskId = activeOffPeakTaskId;
     record.activeOffPeakTaskId = activeOffPeakTaskId;
   }
   }
+  record.activeBotDeliveryTarget = params.botDeliveryTarget;
 
 
   let admission: SendInputResult;
   let admission: SendInputResult;
   try {
   try {
@@ -132,13 +137,23 @@ export async function startPromptTurn(
       },
       },
     );
     );
   } catch (error) {
   } catch (error) {
-    clearPromptRecordState(record, previousAutomationId, previousOffPeakTaskId);
+    clearPromptRecordState(
+      record,
+      previousAutomationId,
+      previousOffPeakTaskId,
+      previousBotDeliveryTarget,
+    );
     await host.afterLegacyStateMutation?.(record, "prompt_failed");
     await host.afterLegacyStateMutation?.(record, "prompt_failed");
     throw error;
     throw error;
   }
   }
 
 
   if (admission.kind === "rejected") {
   if (admission.kind === "rejected") {
-    clearPromptRecordState(record, previousAutomationId, previousOffPeakTaskId);
+    clearPromptRecordState(
+      record,
+      previousAutomationId,
+      previousOffPeakTaskId,
+      previousBotDeliveryTarget,
+    );
     throw new V4PromptRejectedError(
     throw new V4PromptRejectedError(
       "activePrompt",
       "activePrompt",
       `Core prompt admission rejected: ${admission.reason}`,
       `Core prompt admission rejected: ${admission.reason}`,
@@ -146,7 +161,12 @@ export async function startPromptTurn(
   }
   }
 
 
   if (admission.kind === "queued") {
   if (admission.kind === "queued") {
-    clearPromptRecordState(record, previousAutomationId, previousOffPeakTaskId);
+    clearPromptRecordState(
+      record,
+      previousAutomationId,
+      previousOffPeakTaskId,
+      previousBotDeliveryTarget,
+    );
     return { admission, turnStarted: Promise.resolve() };
     return { admission, turnStarted: Promise.resolve() };
   }
   }
 
 
@@ -162,7 +182,12 @@ export async function startPromptTurn(
         sessionId: record.app.sessionId,
         sessionId: record.app.sessionId,
       });
       });
     } finally {
     } finally {
-      clearPromptRecordState(record, previousAutomationId, previousOffPeakTaskId);
+      clearPromptRecordState(
+        record,
+        previousAutomationId,
+        previousOffPeakTaskId,
+        previousBotDeliveryTarget,
+      );
       await host.afterLegacyStateMutation?.(record, mutationReason);
       await host.afterLegacyStateMutation?.(record, mutationReason);
     }
     }
   });
   });
@@ -180,10 +205,12 @@ function clearPromptRecordState(
   record: V4SessionRecordView,
   record: V4SessionRecordView,
   previousAutomationId: string | undefined,
   previousAutomationId: string | undefined,
   previousOffPeakTaskId: string | undefined,
   previousOffPeakTaskId: string | undefined,
+  previousBotDeliveryTarget: V4SessionRecordView["activeBotDeliveryTarget"],
 ): void {
 ): void {
   record.activeAutomationId = previousAutomationId;
   record.activeAutomationId = previousAutomationId;
   // 闲时轮身份与 automation 同规则随 turn 还原,防止跨轮残留误拒 OffPeakCreate。
   // 闲时轮身份与 automation 同规则随 turn 还原,防止跨轮残留误拒 OffPeakCreate。
   record.activeOffPeakTaskId = previousOffPeakTaskId;
   record.activeOffPeakTaskId = previousOffPeakTaskId;
+  record.activeBotDeliveryTarget = previousBotDeliveryTarget;
 }
 }
 
 
 function buildTurnToolDisallowlist(
 function buildTurnToolDisallowlist(

+ 3 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/commands/types.ts

@@ -12,6 +12,7 @@ import type {
   StableForkGoalBoundaryMetadata,
   StableForkGoalBoundaryMetadata,
   TraceContext,
   TraceContext,
 } from "@zcode/contracts";
 } from "@zcode/contracts";
+import type { ZCodeAutomationBotDeliveryTarget } from "@zcode/shared";
 import type {
 import type {
   CommandAck,
   CommandAck,
   CommandEnvelope,
   CommandEnvelope,
@@ -69,6 +70,8 @@ export interface V4SessionRecordView {
   activeAutomationId?: string;
   activeAutomationId?: string;
   /** 当前正在执行的闲时派发 turn;只在 turn 运行期间存在。 */
   /** 当前正在执行的闲时派发 turn;只在 turn 运行期间存在。 */
   activeOffPeakTaskId?: string;
   activeOffPeakTaskId?: string;
+  /** 当前 Bot 入站 turn 的稳定回推地址;turn 结束后必须恢复。 */
+  activeBotDeliveryTarget?: ZCodeAutomationBotDeliveryTarget;
   /** 恢复失败告警:存在时拒绝新 turn(历史损坏不能静默续写)。 */
   /** 恢复失败告警:存在时拒绝新 turn(历史损坏不能静默续写)。 */
   restoreWarning?: { message: string; type: string };
   restoreWarning?: { message: string; type: string };
   taskType?: SessionTaskType;
   taskType?: SessionTaskType;

+ 73 - 12
apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/conversation-topic-publisher.ts

@@ -30,11 +30,16 @@ import type {
 import {
 import {
   DELIVERY_PROFILES,
   DELIVERY_PROFILES,
   PROTOCOL_V4_LIMITS,
   PROTOCOL_V4_LIMITS,
+  clampWorkflowRunsForLegacy,
   coalesceConversationDeltas,
   coalesceConversationDeltas,
   filterConversationDeltasForProfile,
   filterConversationDeltasForProfile,
   filterConversationRowsForProfile,
   filterConversationRowsForProfile,
   utf8JsonByteLength,
   utf8JsonByteLength,
 } from "@zcode/shared/zcode-protocol-v4";
 } from "@zcode/shared/zcode-protocol-v4";
+import {
+  encodeConversationDeltasForLegacy,
+  workflowRunDeltaGrowthUpperBound,
+} from "./conversation-workflow-run-deltas.js";
 import {
 import {
   ProductProjection,
   ProductProjection,
   type StableForkCandidateResolution,
   type StableForkCandidateResolution,
@@ -88,7 +93,12 @@ interface Subscription {
   subscriptionId: string;
   subscriptionId: string;
   connectionId: string;
   connectionId: string;
   profile: DeliveryProfile;
   profile: DeliveryProfile;
-  /** flush buffer:push 时已过 profile 过滤,flush 时 coalesce 打帧。 */
+  /**
+   * 这条订阅认不认得 `workflowRun.*` 键级增量(握手能力位,由可信 host 注入)。
+   * false = 旧消费者:增量折成整键 patch、快照裁到旧界(conversation-workflow-run-deltas.ts)。
+   */
+  workflowRunDeltas: boolean;
+  /** flush buffer:push 时已过 profile 过滤与该订阅的编码,flush 时 coalesce 打帧。 */
   buffer: ConversationDelta[];
   buffer: ConversationDelta[];
   bufferBytes: number;
   bufferBytes: number;
   /** buffer 超限后只保留恢复意图,不继续为慢订阅者积压 delta。 */
   /** buffer 超限后只保留恢复意图,不继续为慢订阅者积压 delta。 */
@@ -105,6 +115,11 @@ interface ConversationSubscribeParams {
   base?: { logEpoch: string; seq: number };
   base?: { logEpoch: string; seq: number };
   /** 缺省 replayable(ws 默认;MessagePort 宿主显式传 continuous)。 */
   /** 缺省 replayable(ws 默认;MessagePort 宿主显式传 continuous)。 */
   deliveryProfile?: DeliveryProfileName;
   deliveryProfile?: DeliveryProfileName;
+  /**
+   * 该连接的 clientHello 声明过认得 `workflowRun.*` 增量。与 deliveryProfile 同族:可信 host
+   * 注入,面向 UI 的 subscribe 选不了。缺省 false——能力位缺席一律按旧消费者办。
+   */
+  workflowRunDeltas?: boolean;
 }
 }
 
 
 interface ConversationSubscribeResult {
 interface ConversationSubscribeResult {
@@ -318,6 +333,34 @@ export class ConversationTopicPublisher {
     };
     };
   }
   }
 
 
+  /**
+   * 一个订阅者的快照帧:profile 决定行可见性,能力位决定 `workflowRuns` 发全量还是旧界。
+   *
+   * 快照与增量必须同一档:一个收着旧界整键 patch 的客户端,如果快照里突然来了 512 个节点,
+   * 它的 `.max(256)` 会让**整帧**解析失败(已知键上的解析错误不会只剥掉一个键)。
+   */
+  private getWireSnapshotForSubscription(subscription: Subscription): ConversationSnapshot {
+    const snapshot = this.getWireSnapshotForProfile(subscription.profile);
+    if (subscription.workflowRunDeltas || snapshot.workflowRuns === undefined) return snapshot;
+    const workflowRuns = clampWorkflowRunsForLegacy(snapshot.workflowRuns);
+    return workflowRuns === snapshot.workflowRuns ? snapshot : { ...snapshot, workflowRuns };
+  }
+
+  /**
+   * 一批 delta 的**每订阅者**编码:profile 过滤 + 旧消费者的整键折叠。
+   *
+   * 折叠取的是**当前**投影状态,所以恢复回放上历史增量会折成终态——中间态被跳过,终态一致,
+   * 与 coalesce 的既有行为同规(conversation-workflow-run-deltas.ts 的文件头)。
+   */
+  private encodeDeltasForSubscription(
+    deltas: readonly ConversationDelta[],
+    subscription: Subscription,
+  ): readonly ConversationDelta[] {
+    const filtered = filterConversationDeltasForProfile(deltas, subscription.profile);
+    if (subscription.workflowRunDeltas) return filtered;
+    return encodeConversationDeltasForLegacy(filtered, this.projection.getSnapshot().workflowRuns);
+  }
+
   /**
   /**
    * 输入 admission 的候选 projection:用完整 QueueItem 表达同一份 intent,覆盖文本与附件引用。
    * 输入 admission 的候选 projection:用完整 QueueItem 表达同一份 intent,覆盖文本与附件引用。
    * QueueItem 元数据不小于立即启动后的 user row,因此通过此闸门的输入不会在后续首次
    * QueueItem 元数据不小于立即启动后的 user row,因此通过此闸门的输入不会在后续首次
@@ -512,12 +555,23 @@ export class ConversationTopicPublisher {
       this.wireSnapshotBytesUpperBound += streamingUpperBound;
       this.wireSnapshotBytesUpperBound += streamingUpperBound;
     } else {
     } else {
       let candidateBytes = 0;
       let candidateBytes = 0;
-      deltas = this.projection.applyEventAtomically(event, (snapshot) => {
+      let nextUpperBound = 0;
+      deltas = this.projection.applyEventAtomically(event, (snapshot, produced) => {
+        // dwf 快路径:这条事件只产键级增量时,它们的字节数就是快照增长的上界(一条 upsert
+        // 最多把自己那点内容加进去,removed 只会让快照变小),不必把整份快照再序列化一遍
+        // ——那一次 JSON.stringify 是每条引擎事件都要付的 MB 级开销,也是这次改造的另一半。
+        // 判据用的是**实际产出**而不是预演,所以 diff 退化出的整键 patch 自然落回精确路径。
+        const growth = workflowRunDeltaGrowthUpperBound(produced);
+        if (growth !== null && this.wireSnapshotBytesUpperBound + growth <= projectionLimit) {
+          nextUpperBound = this.wireSnapshotBytesUpperBound + growth;
+          return true;
+        }
         candidateBytes = this.measureWireSnapshotBytes(this.getWireSnapshot(snapshot));
         candidateBytes = this.measureWireSnapshotBytes(this.getWireSnapshot(snapshot));
+        nextUpperBound = candidateBytes;
         return candidateBytes <= projectionLimit;
         return candidateBytes <= projectionLimit;
       });
       });
       if (deltas === null) throw new ProjectionPayloadTooLargeError(candidateBytes);
       if (deltas === null) throw new ProjectionPayloadTooLargeError(candidateBytes);
-      this.wireSnapshotBytesUpperBound = candidateBytes;
+      this.wireSnapshotBytesUpperBound = nextUpperBound;
     }
     }
     this.log.push({ seq: event.sequenceNumber, deltas });
     this.log.push({ seq: event.sequenceNumber, deltas });
     while (this.log.length > this.retention) {
     while (this.log.length > this.retention) {
@@ -527,7 +581,7 @@ export class ConversationTopicPublisher {
     if (deltas.length === 0) return;
     if (deltas.length === 0) return;
     for (const subscription of this.subscriptions.values()) {
     for (const subscription of this.subscriptions.values()) {
       if (subscription.resyncRequired) continue;
       if (subscription.resyncRequired) continue;
-      const filtered = filterConversationDeltasForProfile(deltas, subscription.profile);
+      const filtered = this.encodeDeltasForSubscription(deltas, subscription);
       const next = appendConversationSubscriberBuffer(subscription.buffer, filtered, {
       const next = appendConversationSubscriberBuffer(subscription.buffer, filtered, {
         maxOps: this.subscriberBufferMaxOps,
         maxOps: this.subscriberBufferMaxOps,
         maxBytes: this.subscriberBufferMaxBytes,
         maxBytes: this.subscriberBufferMaxBytes,
@@ -636,6 +690,9 @@ export class ConversationTopicPublisher {
         const wireDeltas = deltas.filter((delta) => {
         const wireDeltas = deltas.filter((delta) => {
           if (delta.op === "state.updated" || delta.op === "row.appended") return true;
           if (delta.op === "state.updated" || delta.op === "row.appended") return true;
           if (delta.op === "row.removed") return false;
           if (delta.op === "row.removed") return false;
+          // 键级增量作用在状态键上,不在 60 行 wire tail 里——没有「已滑出窗口所以不计」这一说,
+          // 与 state.updated 同规一律计入。
+          if (delta.op === "workflowRun.updated" || delta.op === "workflowRun.removed") return true;
           wireRowIds ??= new Set(
           wireRowIds ??= new Set(
             snapshot.rows.window
             snapshot.rows.window
               .slice(-PROTOCOL_V4_LIMITS.snapshotTailWindowRows)
               .slice(-PROTOCOL_V4_LIMITS.snapshotTailWindowRows)
@@ -712,6 +769,7 @@ export class ConversationTopicPublisher {
       subscriptionId: `sub-${this.logEpoch}-${this.nextSubscriptionSerial++}`,
       subscriptionId: `sub-${this.logEpoch}-${this.nextSubscriptionSerial++}`,
       connectionId: params.connectionId,
       connectionId: params.connectionId,
       profile,
       profile,
+      workflowRunDeltas: params.workflowRunDeltas === true,
       buffer: [],
       buffer: [],
       bufferBytes: 0,
       bufferBytes: 0,
       resyncRequired: false,
       resyncRequired: false,
@@ -754,7 +812,10 @@ export class ConversationTopicPublisher {
           ...this.frameShell(subscription),
           ...this.frameShell(subscription),
           fromSeq: 0,
           fromSeq: 0,
           toSeq: this.currentSeq,
           toSeq: this.currentSeq,
-          payload: { kind: "snapshot", snapshot: this.getWireSnapshotForProfile(profile) },
+          payload: {
+            kind: "snapshot",
+            snapshot: this.getWireSnapshotForSubscription(subscription),
+          },
         },
         },
         false,
         false,
         "initial",
         "initial",
@@ -762,11 +823,11 @@ export class ConversationTopicPublisher {
       return this.subscribeResult(this.ackFor(subscription, "snapshot"), reservation, rollback);
       return this.subscribeResult(this.ackFor(subscription, "snapshot"), reservation, rollback);
     }
     }
 
 
-    // resume:保留窗内 (base.seq, current] 重放,与在线续流同一条 filter→coalesce 管线。
+    // resume:保留窗内 (base.seq, current] 重放,与在线续流同一条 filter→编码→coalesce 管线。
     const replay = coalesceConversationDeltas(
     const replay = coalesceConversationDeltas(
-      filterConversationDeltasForProfile(
+      this.encodeDeltasForSubscription(
         this.log.flatMap((entry) => (entry.seq > base.seq ? entry.deltas : [])),
         this.log.flatMap((entry) => (entry.seq > base.seq ? entry.deltas : [])),
-        profile,
+        subscription,
       ),
       ),
     );
     );
     if (base.seq === this.currentSeq) {
     if (base.seq === this.currentSeq) {
@@ -836,7 +897,7 @@ export class ConversationTopicPublisher {
           toSeq: this.currentSeq,
           toSeq: this.currentSeq,
           payload: {
           payload: {
             kind: "snapshot",
             kind: "snapshot",
-            snapshot: this.getWireSnapshotForProfile(subscription.profile),
+            snapshot: this.getWireSnapshotForSubscription(subscription),
           },
           },
         },
         },
         true,
         true,
@@ -910,7 +971,7 @@ export class ConversationTopicPublisher {
           toSeq: this.currentSeq,
           toSeq: this.currentSeq,
           payload: {
           payload: {
             kind: "snapshot",
             kind: "snapshot",
-            snapshot: this.getWireSnapshotForProfile(subscription.profile),
+            snapshot: this.getWireSnapshotForSubscription(subscription),
           },
           },
         },
         },
         false,
         false,
@@ -925,9 +986,9 @@ export class ConversationTopicPublisher {
 
 
     subscription.sentSeq = base.seq;
     subscription.sentSeq = base.seq;
     const replay = coalesceConversationDeltas(
     const replay = coalesceConversationDeltas(
-      filterConversationDeltasForProfile(
+      this.encodeDeltasForSubscription(
         this.log.flatMap((entry) => (entry.seq > base.seq ? entry.deltas : [])),
         this.log.flatMap((entry) => (entry.seq > base.seq ? entry.deltas : [])),
-        subscription.profile,
+        subscription,
       ),
       ),
     );
     );
     const reservation = this.reserveFrame(
     const reservation = this.reserveFrame(

+ 98 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/conversation-workflow-run-deltas.ts

@@ -0,0 +1,98 @@
+// ============================================================
+// publisher 对 `workflowRun.*` 键级增量的两条纯规则:旧消费者编码、以及快路径的增长上界
+// ============================================================
+// 住在 publisher 之外的理由与它们是纯函数同样重要:两条规则都需要单独钉住,而 publisher 是
+// 带订阅注册表和保留日志的运行时外壳,在它身上试这两件事要先搭半个传输层。
+//
+// ── 一、旧消费者编码 ──
+// 保留日志里存的一律是原生 op(一份事实、一份日志),编码是**每订阅者**的事:握手时带了
+// `workflowRunDeltas` 的连接直接收增量,没带的那一代客户端连 op 的判别式都不认——
+// `conversationDeltaSchema` 是 discriminatedUnion,未知 `op` 让整条 union 解析失败、整个
+// logical frame 被组装器丢掉,而重发的快照里同样没有这条 op,于是那条订阅从此静默。
+// 所以这里不是「优化」,是那一代客户端能不能继续看见 run 的分界线。
+//
+// 改写规则只有一条:整批里所有 `workflowRun.*` 一律丢掉,在**最后一条**被丢掉的位置上补一条
+// `state.updated{workflowRuns: 当前投影}`。为什么是最后一条的位置而不是第一条:整键替换蕴含
+// 这批增量的全部效果,放在最后一条的位置上,它与批内其余 op 的相对顺序就与逐条投递一致
+// (行 op 与状态键互不相干,本来也可交换)。为什么带的是**当前**投影而不是历史中间态:
+// 恢复回放时日志里的那条增量早就不是最新事实了,而客户端要的是终态——中间态被跳过与
+// coalesce 每天在做的事情是同一件。
+//
+// 裁到旧界(256)由 `clampWorkflowRunsForLegacy` 负责,理由见它的文件头。
+
+import type { ConversationDelta, WorkflowRunsState } from "@zcode/shared/zcode-protocol-v4";
+import { clampWorkflowRunsForLegacy, utf8JsonByteLength } from "@zcode/shared/zcode-protocol-v4";
+
+function isWorkflowRunDelta(delta: ConversationDelta): boolean {
+  return delta.op === "workflowRun.updated" || delta.op === "workflowRun.removed";
+}
+
+/**
+ * 一批 delta 的旧消费者编码。批内没有 `workflowRun.*` 时**原样返回同一个数组**
+ * (这条路径在每次 ingest 的每个订阅者上都会跑一遍,不该为不相干的批次造新数组)。
+ *
+ * `workflowRuns` 缺席时只丢不补:投影里还没有这个键,就没有能整键替换成的东西。
+ * 产出侧不会走到(有增量就必有状态),这里只是不让它变成一条 `{workflowRuns: undefined}`。
+ */
+export function encodeConversationDeltasForLegacy(
+  deltas: readonly ConversationDelta[],
+  workflowRuns: WorkflowRunsState | undefined,
+): readonly ConversationDelta[] {
+  let lastIndex = -1;
+  for (let index = deltas.length - 1; index >= 0; index -= 1) {
+    if (isWorkflowRunDelta(deltas[index]!)) {
+      lastIndex = index;
+      break;
+    }
+  }
+  if (lastIndex < 0) return deltas;
+
+  const replacement: ConversationDelta | null =
+    workflowRuns === undefined
+      ? null
+      : { op: "state.updated", patch: { workflowRuns: clampWorkflowRunsForLegacy(workflowRuns) } };
+  const encoded: ConversationDelta[] = [];
+  for (let index = 0; index < deltas.length; index += 1) {
+    const delta = deltas[index]!;
+    if (!isWorkflowRunDelta(delta)) {
+      encoded.push(delta);
+      continue;
+    }
+    if (index === lastIndex && replacement !== null) encoded.push(replacement);
+  }
+  return encoded;
+}
+
+// ── 二、ingest 快路径的增长上界 ──
+//
+// 今天每条 dwf 引擎事件都走精确路径:克隆投影 + 把整份 wire snapshot `JSON.stringify` 一遍来
+// 对 16MiB 闸门。一条 run 上千条事件,这一项本身就是 MB 级的重复开销,与整键重发是同一笔账的
+// 两半。键级增量让「这一步长了多少」有了廉价而**可靠**的上界,于是绝大多数事件不必再量整份。
+
+/** JSON 外壳(`{"kind":"deltas","deltas":[…]}` 与帧信封)留的余量,与流式追加快路径同值。 */
+const WORKFLOW_RUN_DELTA_ENVELOPE_SLACK_BYTES = 64;
+
+/**
+ * 一批 delta **只含**键级增量时,快照增长的字节上界;含任何其它 op 时返回 null(必须精确测量)。
+ *
+ * 上界成立的理由:`workflowRun.updated` 写进快照的全部内容都在这条 op 的载荷里(header 键整体
+ * 替换、条目整条 upsert),所以快照最多长它自己那么多;`workflowRun.removed` 只会让快照变小。
+ *
+ * **空批次**同样满足这个判据(没有一条不是键级增量),而且它的增长论证更强:一条不产 delta 的
+ * 事件对快照的全部改动就是 `seq` 那个数字——余量绰绰有余。这一支不是特例,它就是判据读到底的
+ * 结果,而且正是它让「归约判幂等、一条 delta 都不产」的重放事件不再为一次整份序列化买单。
+ *
+ * null 覆盖的那一半同样是契约的一部分:diff 认不出结构变化时会退化成整键 `state.updated`,
+ * 那条 op 的字节数**不是**增长的上界(它替换的是整个键,旧值的字节不在其中),必须落回精确
+ * 路径。判据因此是「每一条都是键级增量」,而不是「有键级增量」。
+ *
+ * 余量是**每批**一份而不是每条一份:这一份既盖 JSON 外壳,也盖 `seq` 十进制位数的增长。
+ */
+export function workflowRunDeltaGrowthUpperBound(
+  deltas: readonly ConversationDelta[],
+): number | null {
+  for (const delta of deltas) {
+    if (delta.op !== "workflowRun.updated" && delta.op !== "workflowRun.removed") return null;
+  }
+  return utf8JsonByteLength(deltas) + WORKFLOW_RUN_DELTA_ENVELOPE_SLACK_BYTES;
+}

+ 24 - 6
apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/product-projection.ts

@@ -115,6 +115,7 @@ import {
   applyConversationDeltas,
   applyConversationDeltas,
   applyConversationDeltasMutable,
   applyConversationDeltasMutable,
   createMutableConversationSnapshotAccumulator,
   createMutableConversationSnapshotAccumulator,
+  diffWorkflowRunsState,
   reduceWorkflowRunsState,
   reduceWorkflowRunsState,
   workspaceHookReviewRequestPayloadSchema,
   workspaceHookReviewRequestPayloadSchema,
 } from "@zcode/shared/zcode-protocol-v4";
 } from "@zcode/shared/zcode-protocol-v4";
@@ -1051,14 +1052,19 @@ export class ProductProjection {
    * wire encoder 报错,权威内存态会永久停在“无法发 snapshot”的状态。候选实例同时
    * wire encoder 报错,权威内存态会永久停在“无法发 snapshot”的状态。候选实例同时
    * 隔离 snapshot 与 reducer 的各类 side-map;拒绝时当前实例完全不变,客户端仍可从
    * 隔离 snapshot 与 reducer 的各类 side-map;拒绝时当前实例完全不变,客户端仍可从
    * 最后一个可传输 snapshot 恢复。
    * 最后一个可传输 snapshot 恢复。
+   *
+   * `accept` 同时拿到这条事件**实际产出**的 delta:有些事件类别可以只按 delta 的字节数给出
+   * 一个可靠上界,不必把整份候选快照再序列化一遍(publisher 的 ingest 快路径)。传的是实际
+   * 产出而不是预演,正是因为预演算不准——投影在 reducer 之上还叠了 subagent 镜像与命令
+   * actions 的 materialization,少算一条就把 16MiB 闸门算松了。
    */
    */
   applyEventAtomically(
   applyEventAtomically(
     event: SessionEvent,
     event: SessionEvent,
-    accept: (snapshot: ConversationSnapshot) => boolean,
+    accept: (snapshot: ConversationSnapshot, deltas: readonly ConversationDelta[]) => boolean,
   ): ConversationDelta[] | null {
   ): ConversationDelta[] | null {
     const candidate = this.cloneProjection();
     const candidate = this.cloneProjection();
     const deltas = candidate.applyEvent(event);
     const deltas = candidate.applyEvent(event);
-    if (!accept(candidate.snapshot)) return null;
+    if (!accept(candidate.snapshot, deltas)) return null;
     this.adoptProjection(candidate);
     this.adoptProjection(candidate);
     return deltas;
     return deltas;
   }
   }
@@ -1981,7 +1987,7 @@ export class ProductProjection {
             `model-change:${turnId}:${this.lastTurnModel.provider}/${this.lastTurnModel.model}->${config.provider}/${config.model}`,
             `model-change:${turnId}:${this.lastTurnModel.provider}/${this.lastTurnModel.model}->${config.provider}/${config.model}`,
           ),
           ),
           kind: "timelineMarker",
           kind: "timelineMarker",
-        // lane 由投影裁决(UI 不得按 marker type 自行推断落位语义)。
+          // lane 由投影裁决(UI 不得按 marker type 自行推断落位语义)。
           lane: "lightBoundary",
           lane: "lightBoundary",
           marker: {
           marker: {
             type: "modelChange",
             type: "modelChange",
@@ -3862,6 +3868,10 @@ export class ProductProjection {
             return true;
             return true;
           }
           }
           break;
           break;
+        // 非行 op:只动 workflowRuns 状态键,与 subagent 行投影的输入没有交集。
+        case "workflowRun.updated":
+        case "workflowRun.removed":
+          break;
         default: {
         default: {
           const exhaustiveDelta: never = delta;
           const exhaustiveDelta: never = delta;
           return exhaustiveDelta;
           return exhaustiveDelta;
@@ -4005,6 +4015,9 @@ export class ProductProjection {
       switch (delta.op) {
       switch (delta.op) {
         case "row.appended":
         case "row.appended":
         case "state.updated":
         case "state.updated":
+        // 非行 op:改不了这一行的 prospective 形态。
+        case "workflowRun.updated":
+        case "workflowRun.removed":
           break;
           break;
         case "row.upserted":
         case "row.upserted":
           if (delta.row.rowId === prospective.rowId) prospective = delta.row;
           if (delta.row.rowId === prospective.rowId) prospective = delta.row;
@@ -4308,16 +4321,21 @@ export class ProductProjection {
   //
   //
   // 归约本体在 @zcode/shared 的 workflow-runs-reducer(与状态 schema 同居):TUI 镜像要用
   // 归约本体在 @zcode/shared 的 workflow-runs-reducer(与状态 schema 同居):TUI 镜像要用
   // 同一份归约,两处各写一份就是两个时钟。
   // 同一份归约,两处各写一份就是两个时钟。
-  // 留在这里的只有投影的非纯部分——从事件信封取载荷、把新状态发成 state.updated。
+  // 留在这里的只有投影的非纯部分——从事件信封取载荷、把新旧状态之差发成键级增量。
   private onDynamicWorkflowRunProgress(event: SessionEvent): ConversationDelta[] {
   private onDynamicWorkflowRunProgress(event: SessionEvent): ConversationDelta[] {
     // 先转 contracts 的有界 payload、再赋给 shared 的结构化入参:这行赋值就是"两边形状不漂移"
     // 先转 contracts 的有界 payload、再赋给 shared 的结构化入参:这行赋值就是"两边形状不漂移"
     // 的编译期闸(shared 不得反向依赖 contracts,所以入参类型只能结构化定义)。
     // 的编译期闸(shared 不得反向依赖 contracts,所以入参类型只能结构化定义)。
     const envelope: WorkflowRunProgressEnvelope =
     const envelope: WorkflowRunProgressEnvelope =
       event.payload as DynamicWorkflowRunProgressPayload;
       event.payload as DynamicWorkflowRunProgressPayload;
-    const workflowRuns = reduceWorkflowRunsState(this.snapshot.workflowRuns, envelope);
+    const prior = this.snapshot.workflowRuns;
+    const workflowRuns = reduceWorkflowRunsState(prior, envelope);
     // null = 语义无变化(无效事件或同一条事件重放):不产 delta,revision 不抬。
     // null = 语义无变化(无效事件或同一条事件重放):不产 delta,revision 不抬。
     if (workflowRuns === null) return [];
     if (workflowRuns === null) return [];
-    return [{ op: "state.updated", patch: { workflowRuns } }];
+    // 发**差**而不是整键:一条引擎事件只动一个节点,整键重发是每事件 O(N) 字节、一条 run
+    // 全程 O(N²)(workflow-runs-delta.ts 的文件头讲了这笔账怎么变成节点上界和 UI 卡死的)。
+    // `applyAll(prior, diff(prior, next))` 与 next **逐字节**一致是增量协议的契约,
+    // 所以 applyEventInternal 把这串 delta 应用回去之后,this.snapshot.workflowRuns 仍是 next。
+    return diffWorkflowRunsState(prior, workflowRuns);
   }
   }
 
 
   private removeQueueItems(ids: readonly string[]): ConversationDelta[] {
   private removeQueueItems(ids: readonly string[]): ConversationDelta[] {

+ 5 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/projection-state.ts

@@ -211,5 +211,10 @@ export function deltaBumpsRevision(delta: ConversationDelta): boolean {
       return false;
       return false;
     case "state.updated":
     case "state.updated":
       return REVISION_BEARING_PATCH_KEYS.some((key) => delta.patch[key] !== undefined);
       return REVISION_BEARING_PATCH_KEYS.some((key) => delta.patch[key] !== undefined);
+    // 键级增量与整键 `workflowRuns` patch 同一条豁免(见上面的注释):它们表达的就是那个键的变化,
+    // 换个编码不该换记账规则——列入会让一条在飞的 run 每次节点迁移都抖动 conversation revision。
+    case "workflowRun.updated":
+    case "workflowRun.removed":
+      return false;
   }
   }
 }
 }

+ 112 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/sessions-index-fanout-throttle.ts

@@ -0,0 +1,112 @@
+// sessions-index fan-out 的高频事件节流。
+// 纯调度:窗口状态与定时器在这里,publish 由调用方注入,网关只保留调用点。
+//
+// Workflow 进度事件会更新 record.updatedAt;若每条都立即发布摘要,Host 和 renderer 会按
+// 引擎事件频率重算任务列表。因此合并窗口内的进度更新,控制任务索引的发布频率。
+
+/** 工作流进度事件的 fan-out 窗口:窗内的进度合并为窗末一次发布(侧栏运行行 ≤4Hz)。 */
+export const WORKFLOW_PROGRESS_INDEX_FANOUT_MS = 250;
+
+/** 定时器句柄对调度逻辑不透明:默认使用 setTimeout,也允许调用方提供实现。 */
+export type FanoutTimerHandle = unknown;
+
+export interface SessionsIndexFanoutThrottleOptions {
+  /** 发布某会话当前摘要到 sessions-index(网关的 publishCurrentSummaryToIndex)。 */
+  publish: (sessionId: string) => void;
+  windowMs?: number;
+  setTimer?: (callback: () => void, delayMs: number) => FanoutTimerHandle;
+  clearTimer?: (handle: FanoutTimerHandle) => void;
+}
+
+interface WindowState {
+  /** 窗内是否还有未发布的进度;被任意即时发布满足后回落为 false。 */
+  pending: boolean;
+  handle: FanoutTimerHandle;
+}
+
+function defaultSetTimer(callback: () => void, delayMs: number): FanoutTimerHandle {
+  const timer = setTimeout(callback, delayMs);
+  // CLI 进程退出不被节流窗口挂住(与 scheduleFlush 同一姿态)。
+  timer.unref?.();
+  return timer;
+}
+
+function defaultClearTimer(handle: FanoutTimerHandle): void {
+  clearTimeout(handle as ReturnType<typeof setTimeout>);
+}
+
+/**
+ * leading + trailing 窗口节流,按 session 独立计窗:
+ * 静默后的第一条立即发布并开窗;窗内的后续请求只置 pending,在窗末合并成一次发布。
+ * 窗末若确有 pending 就发布并续窗,保证突发期间每窗至多一帧;窗末无 pending 则关窗,
+ * 下一条请求重新走 leading edge。
+ */
+export class SessionsIndexFanoutThrottle {
+  private readonly windows = new Map<string, WindowState>();
+  private readonly publish: (sessionId: string) => void;
+  private readonly windowMs: number;
+  private readonly setTimer: (callback: () => void, delayMs: number) => FanoutTimerHandle;
+  private readonly clearTimer: (handle: FanoutTimerHandle) => void;
+
+  constructor(options: SessionsIndexFanoutThrottleOptions) {
+    this.publish = options.publish;
+    this.windowMs = options.windowMs ?? WORKFLOW_PROGRESS_INDEX_FANOUT_MS;
+    this.setTimer = options.setTimer ?? defaultSetTimer;
+    this.clearTimer = options.clearTimer ?? defaultClearTimer;
+  }
+
+  /** 高频事件的发布请求:立即发布(leading)或并入窗末的一次发布(trailing)。 */
+  request(sessionId: string): void {
+    const open = this.windows.get(sessionId);
+    if (open) {
+      open.pending = true;
+      return;
+    }
+    this.openWindow(sessionId);
+    this.publish(sessionId);
+  }
+
+  /**
+   * 任意即时发布(非进度事件、hydration 补发等)都已经带上了窗内合并的进度,
+   * 待发的 trailing 因此被它满足:只清 pending,窗口继续限流,不再补一帧空增量。
+   */
+  notePublished(sessionId: string): void {
+    const open = this.windows.get(sessionId);
+    if (open) open.pending = false;
+  }
+
+  /** 会话运行态清理:窗口定时器必须随之消失(cleanupSessionRuntime)。 */
+  clearSession(sessionId: string): void {
+    const open = this.windows.get(sessionId);
+    if (!open) return;
+    this.clearTimer(open.handle);
+    this.windows.delete(sessionId);
+  }
+
+  /** 网关 dispose:清掉全部窗口定时器。 */
+  clear(): void {
+    for (const open of this.windows.values()) this.clearTimer(open.handle);
+    this.windows.clear();
+  }
+
+  private openWindow(sessionId: string): void {
+    this.windows.set(sessionId, {
+      pending: false,
+      handle: this.setTimer(() => this.onWindowElapsed(sessionId), this.windowMs),
+    });
+  }
+
+  private onWindowElapsed(sessionId: string): void {
+    const open = this.windows.get(sessionId);
+    if (!open) return;
+    if (!open.pending) {
+      // 窗内没有新进度 → 关窗;下一条进度重新立即发布。
+      this.windows.delete(sessionId);
+      return;
+    }
+    // 先续窗再发布:publish 会回调 notePublished,状态必须已是新窗口的。
+    open.pending = false;
+    open.handle = this.setTimer(() => this.onWindowElapsed(sessionId), this.windowMs);
+    this.publish(sessionId);
+  }
+}

+ 18 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/v4-gateway.ts

@@ -138,6 +138,7 @@ import type {
   SessionUsageSeed,
   SessionUsageSeed,
 } from "./product-projection.js";
 } from "./product-projection.js";
 import type { ConversationRowTargetAction } from "./product-projection.js";
 import type { ConversationRowTargetAction } from "./product-projection.js";
+import { SessionsIndexFanoutThrottle } from "./sessions-index-fanout-throttle.js";
 import { SessionsIndexPublisher } from "./sessions-index-publisher.js";
 import { SessionsIndexPublisher } from "./sessions-index-publisher.js";
 import { SessionsIndexPublisherRegistry } from "./sessions-index-publisher-registry.js";
 import { SessionsIndexPublisherRegistry } from "./sessions-index-publisher-registry.js";
 import { WorkspaceConfigPublisher } from "./workspace-config-publisher.js";
 import { WorkspaceConfigPublisher } from "./workspace-config-publisher.js";
@@ -612,6 +613,10 @@ export class ConversationV4Gateway {
       if (parsed.success) this.host.emitLocalTtftFacts?.(parsed.data);
       if (parsed.success) this.host.emitLocalTtftFacts?.(parsed.data);
     },
     },
   );
   );
+  /** 高频进度事件的 index fan-out 节流(14-sessions-index「事件 fan-out 节奏」)。 */
+  private readonly indexFanoutThrottle = new SessionsIndexFanoutThrottle({
+    publish: (sessionId) => this.publishCurrentSummaryToIndex(sessionId),
+  });
   private readonly attachmentPruneTimer: ReturnType<typeof setInterval>;
   private readonly attachmentPruneTimer: ReturnType<typeof setInterval>;
   private readonly now: () => number;
   private readonly now: () => number;
   private readonly createLogEpoch: (sessionId: string) => string;
   private readonly createLogEpoch: (sessionId: string) => string;
@@ -1074,6 +1079,12 @@ export class ConversationV4Gateway {
    */
    */
   private fanOutToIndex(sessionId: string, event: SessionEvent): void {
   private fanOutToIndex(sessionId: string, event: SessionEvent): void {
     if (event.type === SessionEventType.ModelStreaming) return;
     if (event.type === SessionEventType.ModelStreaming) return;
+    // 工作流进度同样是高频流(实测 8s 4000 条),但列表要继续动,所以不是丢弃而是
+    // leading + trailing 窗口节流:窗内合并为窗末一帧,终态仍在一个窗口内送达。
+    if (event.type === SessionEventType.DynamicWorkflowRunProgress) {
+      this.indexFanoutThrottle.request(sessionId);
+      return;
+    }
     this.publishCurrentSummaryToIndex(sessionId);
     this.publishCurrentSummaryToIndex(sessionId);
   }
   }
 
 
@@ -1086,6 +1097,8 @@ export class ConversationV4Gateway {
    * task-index syncer 无法观察到 draft→visible,也就不会创建侧栏 task row。
    * task-index syncer 无法观察到 draft→visible,也就不会创建侧栏 task row。
    */
    */
   private publishCurrentSummaryToIndex(sessionId: string): void {
   private publishCurrentSummaryToIndex(sessionId: string): void {
+    // 这一次发布带的就是窗内合并后的当前摘要:待发的 trailing 到此被满足,不重复发帧。
+    this.indexFanoutThrottle.notePublished(sessionId);
     const getWorkspaceId = this.host.getSessionWorkspaceId;
     const getWorkspaceId = this.host.getSessionWorkspaceId;
     if (!getWorkspaceId) return;
     if (!getWorkspaceId) return;
     try {
     try {
@@ -1402,6 +1415,9 @@ export class ConversationV4Gateway {
       connectionId: params.connectionId,
       connectionId: params.connectionId,
       base: params.base,
       base: params.base,
       deliveryProfile: profileName,
       deliveryProfile: profileName,
+      // 与 clientMode 同族的可信注入:能力位来自该连接的 clientHello,缺席一律按旧消费者办
+      // (整键 patch + 旧界裁剪)。resync / rehydrate 沿用订阅上已记下的这一位,不再重取。
+      workflowRunDeltas: params.workflowRunDeltas === true,
     });
     });
     const routeKey = subscriptionRouteKey(
     const routeKey = subscriptionRouteKey(
       params.topic,
       params.topic,
@@ -2749,6 +2765,7 @@ export class ConversationV4Gateway {
         this.host.onError?.("v4.sessionsIndex.remove", error);
         this.host.onError?.("v4.sessionsIndex.remove", error);
       }
       }
     }
     }
+    this.indexFanoutThrottle.clearSession(sessionId);
     for (const [routeKey, state] of this.flushStates) {
     for (const [routeKey, state] of this.flushStates) {
       if (state.sessionId !== sessionId) continue;
       if (state.sessionId !== sessionId) continue;
       if (state.timer) clearTimeout(state.timer);
       if (state.timer) clearTimeout(state.timer);
@@ -2799,6 +2816,7 @@ export class ConversationV4Gateway {
       );
       );
     }
     }
     clearInterval(this.attachmentPruneTimer);
     clearInterval(this.attachmentPruneTimer);
+    this.indexFanoutThrottle.clear();
     this.attachmentUploads.clear();
     this.attachmentUploads.clear();
     this.binaryReadCache.clear();
     this.binaryReadCache.clear();
     this.binaryReadCacheBytes = 0;
     this.binaryReadCacheBytes = 0;

+ 3 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/automation-port.ts

@@ -130,6 +130,9 @@ export function createProtocolAutomationPort(
             ...(runtimeModelSelection ? { modelSelection: runtimeModelSelection } : {}),
             ...(runtimeModelSelection ? { modelSelection: runtimeModelSelection } : {}),
             ...(runtimeMode ? { mode: runtimeMode === "auto" ? "build" : runtimeMode } : {}),
             ...(runtimeMode ? { mode: runtimeMode === "auto" ? "build" : runtimeMode } : {}),
             ...(createContext?.sessionId ? { targetTaskId: createContext.sessionId } : {}),
             ...(createContext?.sessionId ? { targetTaskId: createContext.sessionId } : {}),
+            ...(activeSession?.activeBotDeliveryTarget
+              ? { botDeliveryTarget: activeSession.activeBotDeliveryTarget }
+              : {}),
             ...(hasIntervalCarrier
             ...(hasIntervalCarrier
               ? {
               ? {
                   // 新建 carrier 不透传有限上限;create 协议没有 maxRuns=null 清除语义。
                   // 新建 carrier 不透传有限上限;create 协议没有 maxRuns=null 清除语义。

+ 8 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server-operations.ts

@@ -69,6 +69,7 @@ import {
   zcodeWorkspaceGenerateTextParamsSchema,
   zcodeWorkspaceGenerateTextParamsSchema,
   getConversationMessageProjectionPolicy,
   getConversationMessageProjectionPolicy,
   parseRemoteWorkspaceIdentity,
   parseRemoteWorkspaceIdentity,
+  type ZCodeAutomationBotDeliveryTarget,
   type ZCodeSessionCreateParams,
   type ZCodeSessionCreateParams,
   type ZCodeDeliveryKind,
   type ZCodeDeliveryKind,
   type IntegratedTerminalShellSelection,
   type IntegratedTerminalShellSelection,
@@ -2000,6 +2001,7 @@ export async function sendPrompt(context: ZCodeProtocolAgentServerContext, rawPa
             }
             }
           : {}),
           : {}),
       toolDenylist: params.toolDenylist,
       toolDenylist: params.toolDenylist,
+      botDeliveryTarget: params.botDeliveryTarget,
     }),
     }),
   ).catch(() => {
   ).catch(() => {
     // 后台 turn 的错误会通过状态/事件流降级上报;这里兜底防止协议进程出现 unhandled rejection。
     // 后台 turn 的错误会通过状态/事件流降级上报;这里兜底防止协议进程出现 unhandled rejection。
@@ -2371,6 +2373,7 @@ async function runPromptTurnInBackground(
     queryId?: QueryId;
     queryId?: QueryId;
     content: string;
     content: string;
     toolDenylist?: readonly string[];
     toolDenylist?: readonly string[];
+    botDeliveryTarget?: ZCodeAutomationBotDeliveryTarget;
   } & TurnBackgroundAttribution,
   } & TurnBackgroundAttribution,
 ): Promise<void> {
 ): Promise<void> {
   const startedAt = Date.now();
   const startedAt = Date.now();
@@ -2384,6 +2387,7 @@ async function runPromptTurnInBackground(
   let mutationReason = "prompt_completed";
   let mutationReason = "prompt_completed";
   const previousAutomationId = record.activeAutomationId;
   const previousAutomationId = record.activeAutomationId;
   const previousOffPeakTaskId = record.activeOffPeakTaskId;
   const previousOffPeakTaskId = record.activeOffPeakTaskId;
+  const previousBotDeliveryTarget = record.activeBotDeliveryTarget;
   const activeAutomationId = resolvePromptTurnAutomationId(params);
   const activeAutomationId = resolvePromptTurnAutomationId(params);
   const activeOffPeakTaskId = resolvePromptTurnOffPeakTaskId(params);
   const activeOffPeakTaskId = resolvePromptTurnOffPeakTaskId(params);
   const turnToolDisallowlist = buildPromptTurnToolDisallowlist(
   const turnToolDisallowlist = buildPromptTurnToolDisallowlist(
@@ -2401,6 +2405,7 @@ async function runPromptTurnInBackground(
     // 闲时派发轮同型兜底标记,供 offpeak-port 拒绝递归 OffPeakCreate。
     // 闲时派发轮同型兜底标记,供 offpeak-port 拒绝递归 OffPeakCreate。
     record.activeOffPeakTaskId = activeOffPeakTaskId;
     record.activeOffPeakTaskId = activeOffPeakTaskId;
   }
   }
+  record.activeBotDeliveryTarget = params.botDeliveryTarget;
   try {
   try {
     const admission = await record.app.sendInput(
     const admission = await record.app.sendInput(
       {
       {
@@ -2465,6 +2470,9 @@ async function runPromptTurnInBackground(
     }
     }
     record.activeAutomationId = previousAutomationId;
     record.activeAutomationId = previousAutomationId;
     record.activeOffPeakTaskId = previousOffPeakTaskId;
     record.activeOffPeakTaskId = previousOffPeakTaskId;
+    // Bug 原因:legacy record 会跨 turn 复用;必须恢复 Bot 地址,避免后续普通 UI turn
+    // 创建的定时任务错误继承上一轮 Bot 会话。
+    record.activeBotDeliveryTarget = previousBotDeliveryTarget;
   }
   }
   await afterStateMutation(context, record, mutationReason);
   await afterStateMutation(context, record, mutationReason);
 }
 }

+ 3 - 0
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/server-types.ts

@@ -15,6 +15,7 @@ import type { WorkspaceHookPolicyProvider } from "@zcode/core";
 import type { AccountProviderConfigSnapshot } from "@zcode/provider";
 import type { AccountProviderConfigSnapshot } from "@zcode/provider";
 import {
 import {
   zcodeProtocolErrorCodes,
   zcodeProtocolErrorCodes,
+  type ZCodeAutomationBotDeliveryTarget,
   type ZCodeDeliveryKind,
   type ZCodeDeliveryKind,
   type ModelSelection,
   type ModelSelection,
   type ZCodeModelContextBudgetStrategy,
   type ZCodeModelContextBudgetStrategy,
@@ -109,6 +110,8 @@ export interface ZCodeProtocolSessionRecord {
   activeAutomationId?: string;
   activeAutomationId?: string;
   /** 当前正在执行的闲时派发 turn;只在 turn 运行期间存在,禁止递归 OffPeakCreate。 */
   /** 当前正在执行的闲时派发 turn;只在 turn 运行期间存在,禁止递归 OffPeakCreate。 */
   activeOffPeakTaskId?: string;
   activeOffPeakTaskId?: string;
+  /** 当前 Bot 入站 turn 的稳定回推地址;只允许 CronCreate 在本轮读取。 */
+  activeBotDeliveryTarget?: ZCodeAutomationBotDeliveryTarget;
   restoreWarning?: { message: string; type: string };
   restoreWarning?: { message: string; type: string };
   /** 冷恢复候选只供初始投影;新的选模事件立即清除,不能替代 Runtime 执行绑定。 */
   /** 冷恢复候选只供初始投影;新的选模事件立即清除,不能替代 Runtime 执行绑定。 */
   restoredModelSelection?: ModelSelection;
   restoredModelSelection?: ModelSelection;

+ 5 - 1
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/skill-reference-catalog.ts

@@ -41,7 +41,11 @@ function toResult(
 ): ZCodeSkillsReferenceCatalogResult {
 ): ZCodeSkillsReferenceCatalogResult {
   return {
   return {
     authority,
     authority,
-    skills: outcome.skills.map(toReferenceCatalogEntry),
+    // 内置技能包(bundled-skills.ts)不进引用面板:它由内置命令(`/workflow`)加载,不是用户
+    // 管理或引用的对象;协议的 scope 是封闭枚举,旧客户端严格校验,这里不为它扩枚举。
+    skills: outcome.skills
+      .filter((skill) => skill.source !== "bundled")
+      .map(toReferenceCatalogEntry),
   };
   };
 }
 }
 
 

+ 13 - 36
apps/zcode-cli/packages/bootstrap/src/zcode-protocol/slash-commands.ts

@@ -1,4 +1,5 @@
 import { BUILTIN_ZCODE_SLASH_COMMAND_HELP_ENTRIES, type ZCodeSlashCommand } from "@zcode/shared";
 import { BUILTIN_ZCODE_SLASH_COMMAND_HELP_ENTRIES, type ZCodeSlashCommand } from "@zcode/shared";
+import { BUILTIN_WORKFLOW_COMMAND_NAME } from "../builtin-workflow-command.js";
 import {
 import {
   listZCodeCustomCommands,
   listZCodeCustomCommands,
   type ListZCodeCustomCommandsOptions,
   type ListZCodeCustomCommandsOptions,
@@ -9,17 +10,10 @@ import {
   isReservedZCodeSlashCommandName,
   isReservedZCodeSlashCommandName,
 } from "../slash-command-surface.js";
 } from "../slash-command-surface.js";
 
 
-/**
- * `workflow` 是 zcode-guide 内置插件的自定义命令,随 CLI 打包,不受用户 commandOverrides
- * 影响;灰度关闭时只能在装配目录时按名剔除。
- */
-const DYNAMIC_WORKFLOW_SLASH_COMMAND_NAME = "workflow";
-
 export interface ListProtocolSlashCommandsOptions extends ListZCodeCustomCommandsOptions {
 export interface ListProtocolSlashCommandsOptions extends ListZCodeCustomCommandsOptions {
   /**
   /**
-   * 动态工作流灰度门。**只有显式 false
-   * 才剔除** `workflow`:CLI 自身的目录装配(TUI / 未参与灰度的调用方)缺席该字段,
-   * 必须保持原样。协议服务端一律从 appRuntimePreferences 传入显式布尔。
+   * 动态工作流开关。只有显式 false 才从目录中剔除内置 `workflow`。
+   * 未传入该字段的调用方保留默认目录;协议服务端从 appRuntimePreferences 传入显式布尔。
    */
    */
   dynamicWorkflowEnabled?: boolean;
   dynamicWorkflowEnabled?: boolean;
 }
 }
@@ -27,7 +21,13 @@ export interface ListProtocolSlashCommandsOptions extends ListZCodeCustomCommand
 export async function listProtocolSlashCommands(
 export async function listProtocolSlashCommands(
   options: ListProtocolSlashCommandsOptions = {},
   options: ListProtocolSlashCommandsOptions = {},
 ): Promise<ZCodeSlashCommand[]> {
 ): Promise<ZCodeSlashCommand[]> {
-  const builtins = listAppProtocolBuiltinSlashCommands();
+  // 动态工作流关闭时:composer 的加号菜单与 `/` 面板都只读这份目录,剔除即两个入口一起消失。
+  // `workflow` 是内置命令且是保留名,用户/插件的同名自定义命令在下面的 reserved 过滤里一并消失,
+  // 不会在门关着时借自定义命令的身份漏回目录。
+  const builtins = listAppProtocolBuiltinSlashCommands().filter(
+    (command) =>
+      options.dynamicWorkflowEnabled !== false || command.name !== BUILTIN_WORKFLOW_COMMAND_NAME,
+  );
   let customCommands: Awaited<ReturnType<typeof listZCodeCustomCommands>>["commands"] = [];
   let customCommands: Awaited<ReturnType<typeof listZCodeCustomCommands>>["commands"] = [];
   try {
   try {
     const outcome = await listZCodeCustomCommands(options);
     const outcome = await listZCodeCustomCommands(options);
@@ -37,44 +37,21 @@ export async function listProtocolSlashCommands(
     customCommands = [];
     customCommands = [];
   }
   }
 
 
-  return pinWorkflowAfterGoal([
+  return [
     ...builtins,
     ...builtins,
     ...customCommands
     ...customCommands
       .filter((command) => !command.disableNonInteractive)
       .filter((command) => !command.disableNonInteractive)
       .filter((command) => !isReservedZCodeSlashCommandName(command.name))
       .filter((command) => !isReservedZCodeSlashCommandName(command.name))
-      // 灰度关闭:composer 的加号菜单与 `/` 面板都只读这份目录,剔除即两个入口一起消失。开启时后面的 pinWorkflowAfterGoal 继续把它钉在 goal 之后。
-      .filter(
-        (command) =>
-          options.dynamicWorkflowEnabled !== false ||
-          command.name !== DYNAMIC_WORKFLOW_SLASH_COMMAND_NAME,
-      )
       .map((command) => ({
       .map((command) => ({
         description: command.description,
         description: command.description,
         inputHint: `/${command.name}${command.argumentHint ? ` ${command.argumentHint}` : ""}`,
         inputHint: `/${command.name}${command.argumentHint ? ` ${command.argumentHint}` : ""}`,
         name: command.name,
         name: command.name,
         source: "custom" as const,
         source: "custom" as const,
       })),
       })),
-  ]);
-}
-
-/**
- * App `/` 面板按本目录顺序展示,本函数是唯一的排序点(UI 不维护排序白名单)。
- * `workflow` 是 zcode-guide 内置插件的自定义命令,
- * 按发现顺序会沉在 custom 段末尾;产品要求它与 `goal` 一样作为「开启一段工作」的入口,
- * 紧随 goal 之后。
- * 只调顺序:来源、去重与 reserved 规则不变;任一方缺席时保持原序。
- */
-function pinWorkflowAfterGoal(commands: ZCodeSlashCommand[]): ZCodeSlashCommand[] {
-  const workflowIndex = commands.findIndex(
-    (command) => command.name === DYNAMIC_WORKFLOW_SLASH_COMMAND_NAME,
-  );
-  if (workflowIndex < 0 || !commands.some((command) => command.name === "goal")) return commands;
-  const [workflow] = commands.splice(workflowIndex, 1);
-  const goalIndex = commands.findIndex((command) => command.name === "goal");
-  commands.splice(goalIndex + 1, 0, workflow!);
-  return commands;
+  ];
 }
 }
 
 
+/** App `/` 面板按本目录顺序展示;内置段的顺序由 APP_PROTOCOL_VISIBLE_BUILTIN_SLASH_COMMAND_NAMES 决定。 */
 function listAppProtocolBuiltinSlashCommands(): ZCodeSlashCommand[] {
 function listAppProtocolBuiltinSlashCommands(): ZCodeSlashCommand[] {
   const sharedBuiltins = APP_PROTOCOL_VISIBLE_BUILTIN_SLASH_COMMAND_NAMES.flatMap((name) => {
   const sharedBuiltins = APP_PROTOCOL_VISIBLE_BUILTIN_SLASH_COMMAND_NAMES.flatMap((name) => {
     const command = BUILTIN_ZCODE_SLASH_COMMAND_HELP_ENTRIES.find((entry) => entry.name === name);
     const command = BUILTIN_ZCODE_SLASH_COMMAND_HELP_ENTRIES.find((entry) => entry.name === name);

+ 1520 - 0
apps/zcode-cli/packages/bundled-skills/skills/dynamic-workflows/SKILL.md

@@ -0,0 +1,1520 @@
+---
+name: dynamic-workflows
+description: "Use when writing, debugging, or resubmitting a dynamic-workflow script for the CreateWorkflow tool: choosing subagent topology, typing subagent results, fanning out over files or git, gating loops on world.run commands, testing pieces with EvalWorkflowSnippet, planner-reviewer loops, confirming findings before reporting them, report() salvage, the report shape a run returns, publishing artifacts the user opens, and handling a backgrounded run."
+when_to_use: "Only for CreateWorkflow scripts. A single delegation or a few independent lookups belong to the Agent tool instead."
+---
+
+# Writing dynamic workflows
+
+This skill is the whole authoring contract for `CreateWorkflow`. The tool descriptions are
+short on purpose; the facade the compiler checks against, the rules a script must satisfy and
+the fields each tool takes are in §16, and `CreateWorkflow`, `AmendWorkflow`, `SaveWorkflow`
+and `EvalWorkflowSnippet` refuse to run until this skill has been loaded in the session. The
+rest is the judgment layer: how many subagents a request deserves, which of them should share
+a context, what each one should hand back, and how to keep the run's work from dying with the
+run.
+
+Two names collide in this codebase. `CreateWorkflow` is the dynamic-workflow tool and the
+only one this skill is about. The legacy `Workflow` tool and `/expert` are a different,
+older feature that happens to share the word.
+
+## The bar: first-class, expert-level work
+
+A workflow exists to produce first-class, expert-level work — the deliverable a senior
+practitioner would hand over after doing the job properly, not a faster draft of what one
+reply could have said. A user who asks for a workflow is paying for that depth, and every
+choice in this skill serves it: enough subagents to actually cover the ground, fresh eyes
+on every plan and every draft (§3), an independent confirmation of every finding,
+deterministic checks wherever a command can decide, and a report that says what was
+verified, what was not, and what it all means.
+Depth is measured by what is at stake, not by how many subagents re-read the same work:
+verification is spent where a wrong claim would cost the user something, and each piece of
+work gets the one check that decides it, not every check this skill knows.
+When a shortcut and the expert's way disagree, take the expert's way. Trim the work only when
+the task is genuinely small, never because thoroughness is inconvenient; trim the checking
+when a wrong claim costs little or a command has already decided it.
+
+## 1. Is this the right tool, and how big should it be?
+
+| The request | The tool |
+| --- | --- |
+| One thing delegated to one agent | `Agent` |
+| A few independent lookups, nobody reading anybody's answer | `Agent`, in parallel |
+| Anything else the user did not name a workflow for — however many steps or subagents it needs | `Agent`, or do it yourself |
+| The user said "use a workflow" / "使用 workflow" / "用工作流" — any phrasing naming workflow as the means | `CreateWorkflow`, mandatory, even if `Agent` would have done or one reply could answer |
+
+**Only an explicit request starts a workflow.** The request is the whole routing rule: a
+workflow begins with `/workflow` or with the user naming workflow/工作流 as the means, never
+with your own judgement that a task looks orchestration-shaped. Results feeding later steps,
+a loop with a stopping condition, control flow branching on a typed result — none of these
+are a reason to start one. Delegate with `Agent` or do the work yourself.
+
+**An explicit request is binding.** When the user names workflow/工作流 as the way to do the
+task, the routing question is closed: not `Agent`, not doing it inline, not "this is too small
+for a workflow". The user picked the tool; what remains for you is only how big the script
+should be, and the smallest task still gets a small workflow rather than something else.
+
+Once a workflow has been requested, these are the shapes it is good at, and what the script
+should reach for: results feeding later steps (pipelines, fan-out then fan-in), a loop with a
+stopping condition, and control flow branching on a typed result. They describe how to build
+the workflow the user asked for — they never decide that there should be one.
+
+An explicit workflow request is a request for depth, and the bar above is the measure.
+Default to the thorough shape — a fresh subagent per unit of work, a deterministic gate
+wherever a command can decide, an independent confirmation of every finding the user will
+act on as fact (§10) — and size the checking to the stakes: a bug the user will fix on your
+word gets a confirmer; a poem, a brainstorm or a survey gets a reader at most. Cost still
+counts: every task is a full model session with its own context, so put the sessions where
+they raise confidence, not where they repeat each other. "Review the changed files" wants
+one reviewer per changed file plus one confirmer per finding; a three-line question wants
+neither; "write me twenty poems" wants twenty poets and no confirmers.
+
+## 2. Subagent topology
+
+This is the decision that separates a good script from a bad one, and there are four parts
+to it.
+
+**Fresh subagent per item, or one shared subagent?** Every `agent()` call creates a new context.
+Sharing a context means sharing the *variable*:
+
+```ts
+// Independent: each judge sees only its own item. Runs concurrently.
+items.map((i) => agent(`judge-${i.id}`).ask<Verdict>(`Judge ${i.id}`));
+
+// Calibrated: one context sees every item in sequence, so its later verdicts are
+// consistent with its earlier ones. Asks on one subagent queue FIFO — this serializes.
+const judge = agent("judge", "You rank consistently across a whole batch.");
+items.map((i) => judge.ask<Verdict>(`Judge ${i.id}`));
+```
+
+Both are correct for different jobs. Independent is right when the items are unrelated and
+you want parallelism; shared is right when the answers must be consistent with each other,
+and you are paying serialization for that consistency. Choosing shared by accident — by
+hoisting the `agent()` call out of a loop for tidiness — turns a parallel fan-out into a
+queue. Nothing rejects that script; the run simply takes as long as every item in a row.
+
+**A name is an identity, and it has to be unique.** Naming is optional, but no two subagents
+in one run may share a non-empty name — a duplicate fails the whole run. Note what that
+means for the first snippet above: one fixed name inside a fan-out is a duplicate once per
+item, so it is written `` agent(`judge-${i.id}`) ``, per item. The compiler catches the
+literal form (`agent("judge")` inside a `.map`/`for...of`) before you submit; a name built
+at run time it cannot see, so that one costs you the run. Anonymous is always safe: drop
+the name when you have nothing per-item to build one from.
+
+Names are worth giving anyway, because they are how a **revised** re-run finds its cache
+(§13): resubmitting a fixed script with `AmendWorkflow` imports, per named subagent, every ask
+whose instructions did not change — at zero tokens, up to the first ask that has to run
+live. Stable, meaningful names are what makes that hit. Anonymous subagents are legal
+and simply always start with an empty context.
+
+**Persona, frozen at creation.** A persona stacks on top of the harness's own workflow
+subagent contract — citing `path:line`, never reporting a check it did not run, saying
+plainly what it could not do, escalating instead of faking — so write the role and the
+standard of judgement, and leave those rules out; they are already there. Every subagent
+has the same tools — reading, searching, editing, running commands — and runs on the
+session's model; there is no per-subagent tool profile or model choice. What a subagent may
+do with its tools is said in the ask: a reviewer that must not touch the code is told "do not
+edit any file", a judge of a string is handed the string and told to judge it as given. A
+subagent asked to run a check runs it; one told not to edit does not. None of this can
+change after `agent()` — there is no per-task override.
+
+**Loops.** Bound every loop with a round cap, and carry the feedback forward:
+
+```ts
+let feedback = "none";
+for (let round = 0; round < 5; round++) {
+  const plan = await planner.ask<Plan>(`Plan the fix. Previous critique: ${feedback}`);
+  const review = await reviewer.ask<Review>(`Critique this plan: ${JSON.stringify(plan)}`);
+  if (review.approved) return plan;
+  feedback = review.feedback;
+}
+```
+
+Reuse the same two subagents across rounds — that is the point. A subagent asked more than once
+keeps its accumulated context and gets long-lived caching, so round five is cheap. Creating
+a fresh planner each round throws away everything it learned in round four. The one thing
+reuse costs you is freshness: by round three the reviewer is anchored on its own earlier
+critique. Keep the persistent reviewer for continuity and add an independent one at the end (§3).
+
+**No nesting.** Subagents cannot call `CreateWorkflow`. If a task is big enough to want its own
+workflow, model it as more subagents here.
+
+## 3. Fresh eyes
+
+The author of a plan or a draft cannot see its gaps, because they filled them while
+writing. A reader with a separate context has no such fill, so the gaps show. That is the
+whole method, and it applies at every stage *inside* the workflow where something is
+drafted — a plan, a fix, a finding, the final report. It pays most on plans, which are
+cheap to critique and expensive to execute wrongly.
+
+Four rules make the eyes actually fresh:
+
+- **Separate context, not a second opinion from the same head.** An independent reader is a new
+  `agent()` that has seen nothing but the draft. Every planner–reviewer loop keeps a
+  persistent reviewer for continuity (§2), and then puts the final draft in front of a
+  reviewer that has never seen an earlier round.
+- **Ask for failures, not approval.** "Is this good?" gets a yes. "What would break this?
+  What is missing? Restate the plan in your own words" gets findings. Write the ask so
+  that approving takes evidence and objecting is the easy move.
+- **Give the eyes the same evidence.** A reviewer told to judge a plan about code from the
+  plan's text alone can only judge coherence. To judge correctness it must read the code:
+  tell plan reviewers to read the files the plan touches, and not to edit them.
+- **Give a prose deliverable an independent read.** When the deliverable is text nothing else
+  checked — a guide, an analysis, a write-up — hand it, before the script returns, to a
+  reader-proxy subagent asked what is unclear, what the text itself fails to support, and
+  what the user will ask next — then fix those, not the prose. Say in the ask that it judges
+  the report as a reader would, from the text alone, so it does not wander off to verify it
+  against the repository. If you want claims checked, that is a confirmer that reads the
+  code, not an independent read. A report whose findings were each confirmed (§10) has
+  already had its eyes; do not add a reader on top of the confirmers.
+
+Three cautions. Correlated reviewers add little — same model, same prompt, same blind
+spots — so give each a distinct lens or a different task. Bound it: one deliverable gets one
+mechanism — a plan gets a reviewer who reads the code, findings get a confirmer, prose gets a
+reader. A draft that came out of a planner–reviewer loop and then passed a fresh final
+reviewer has had its fresh eyes; a reader-proxy pass over the same text is a third session
+re-reading work two have already read. Two mechanisms on one deliverable is the ceiling, and
+it needs a reason you can say. And the rules above are about the subagents *inside* the
+script, not a gate on submitting it: reading your own script once against the request is
+normally enough, and the run confirmation already puts the plan in front of the user. An
+independent read of the script by a fresh `Agent` is an option for a genuinely hard one — many
+phases, subtle gates — not a routine step.
+
+## 4. Typed results
+
+Pass a type argument to `ask` whenever your control flow will branch on the answer; leave it
+off when you just want prose back. The type must be an interface or type alias you write in
+the script.
+
+**JSDoc on a property becomes the field description the subagent actually reads.** This is the
+cheapest quality lever in the whole surface and the easiest to skip:
+
+```ts
+interface Finding {
+  /** Workspace-relative path the problem is in. */
+  path: string;
+  /** One sentence: what is wrong, not how to fix it. */
+  problem: string;
+  /** How much it matters. Reserve "high" for data loss or a crash. */
+  severity: "low" | "medium" | "high";
+}
+```
+
+Without the comments you get whatever the subagent guessed `severity` meant. With them you get
+a calibrated field, for the price of three lines.
+
+Keep results narrow. A result crosses a schema boundary and gets interpolated into the
+next prompt, so a wide one costs tokens twice. **Pass paths, not file contents** — a subagent
+has its own file tools and can read what it needs; handing it a stringified 4000-line file
+spends tokens to tell it something it could have fetched itself.
+
+## 5. Getting the world in
+
+`files.glob` and `git.changedFiles` are how a script learns what to fan out over. Both are
+executed by the harness, recorded, and replayed from the record on resume.
+
+Caps **reject rather than truncate**: an over-wide `files.grep` fails that call instead of
+handing you a silently partial view of the workspace to fan out over. Narrow the pattern or
+add a glob filter. Reads are catchable, so a script that wants a coarser fallback writes one
+— which is exactly what you need for `git`, since every `git` call rejects outside a
+repository:
+
+```ts
+let paths: string[];
+try {
+  paths = await git.changedFiles("origin/main");
+} catch {
+  paths = await files.glob("src/**/*.ts");
+}
+```
+
+Reach for `files.read` or `files.grep` only when the *script itself* must shard or branch on
+content. Deciding which files to hand out is script work; reading them is subagent work.
+
+**`world.run` is the deterministic gate.** When a check is fixed and machine-checkable — the
+build passes, the proof checks, the tests are green — run it as code and branch on the exit
+code, instead of asking a subagent to run it and trusting the claim:
+
+```ts
+const check = await world.run("lake", ["build"], { timeoutMs: 1_800_000 });
+if (check.exitCode !== 0) feedback = check.stderr;
+```
+
+A nonzero exit code is a **value**, not an exception: the gating loop's normal case reads
+`exitCode` and carries `stderr` forward as the next round's feedback, with no `catch` in
+sight. Rejections are reserved for the world failing to answer — spawn failure, timeout
+(default 300s, override per call, no cap), or output over the per-stream cap. The command
+name must be a compile-time string literal, because the user approves the script's command
+set at confirmation: interpolate paths, flags and round numbers into the **args array**,
+never into the command. And keep the division of labor: open-ended editing belongs to a
+subagent with tools; `world.run` is for checks whose outcome your control flow branches on.
+
+**Choose the gate before you write it.** A gate decides exactly as much as the check it
+runs, and the check the task needs is rarely the first one you would type from habit.
+Before the first `world.run`, find out what checks the repository actually has — the
+scripts in `package.json`, the targets in a `Makefile`, the CI config, the README's "run
+this to verify" line — and rank them by how much they decide: a unit suite over fixtures
+decides less than an integration or end-to-end suite, which decides less than the
+acceptance command the README names, and none of them decides a performance request the
+way the bench does. Then build the gate in two tiers. The fast tier may drive the rounds of
+a loop. The **strongest** tier the request implies decides the exit, and it runs for real at
+least once before the final `return` — even when the fast tier already said yes, because
+the fast tier cannot see what it does not test. When the strong tier is slow, give it the
+`timeoutMs` it needs; a faster substitute is a different check, not a cheaper version of
+the same one.
+
+```ts
+phase("Fix until the unit tests pass");
+for (let round = 1; round <= 5; round++) {
+  const unit = await world.run("npm", ["test"]);
+  if (unit.exitCode === 0) break;
+  await fixer.ask(`The unit tests failed:\n${unit.stderr}\nFix them.`);
+}
+
+phase("Run the end-to-end suite once before handing over");
+const e2e = await world.run("npm", ["run", "e2e"], { timeoutMs: 1_800_000 });
+const verified = e2e.exitCode === 0;
+```
+
+A check that exists in the repository and did not run is not "not covered"; it is
+unverified work (§10).
+
+## 6. Test the pieces before you commit
+
+A workflow script is final at submit. The fixed logic inside it does not have to be: run it
+through the `EvalWorkflowSnippet` tool first, which compiles and executes a snippet against
+the same compiler, sandbox and world-read path a real run uses, synchronously and without
+persisting anything. What passed there pastes into the workflow verbatim. Send the snippet
+as `code`, or as `path` to a file holding it when you have already written it out — the
+second try then costs an `Edit` rather than the whole snippet again.
+
+Snippet work is exactly the non-subagent part: what a glob really returns (workspace-relative,
+sorted), whether a grep pattern overruns its cap, how `world.run("lean", ...)`'s stderr
+parses, whether a gate predicate does what you meant. A snippet has `files.*`, `git.*`,
+`world.run` and `log`, but no `agent()` — orchestration cannot be rehearsed, only the pieces
+can. Testing a parse function by burning a full run is the expensive way to find a typo.
+Once you know which check decides the result (§5), run it once here as well: that tells you
+what its output looks like, whether it exits nonzero the way you assumed, and how long it
+takes — which is the `timeoutMs` you write, not a guess.
+
+## 7. Keep the script analyzable, and join only where the data needs everyone
+
+The harness recovers the dependency graph by reading your code before it runs, so write code
+whose data flow is visible. Node results flowing through plain variables, template
+interpolation, destructuring and small local helpers are all traced exactly. Stashing a
+result into a container and fishing it out later, or routing it through a clever indirection,
+earns an analyzability diagnostic instead.
+
+`Promise.all` is a join, and a join is a barrier: nothing after it starts until the slowest
+item before it has landed. Parallelism comes from *not awaiting yet*:
+
+```ts
+// Concurrent: nothing is awaited until the join.
+const all = await Promise.all(
+  paths.map((p) => agent(`reviewer-${p}`).ask<Review>(`Review ${p}`)),
+);
+
+// Serial: each await blocks the next call. Only write this when you mean it.
+for (const p of paths) results.push(await agent(`reviewer-${p}`).ask<Review>(`Review ${p}`));
+```
+
+**Join where the next step needs every item, and nowhere else.** When two stages map one to
+one — a reviewer per file and a confirmer per finding, a migrator per file and a checker per
+file — a barrier between them makes every confirmer wait for the slowest reviewer while the
+concurrency slots sit idle. Chain the stages per item inside the fan-out instead, and join
+once at the end:
+
+```ts
+// ✗ Two barriers: no finding is confirmed until every file has been reviewed.
+const reviews = await Promise.all(paths.map((p) => agent(`reviewer-${p}`).ask<Review>(`Review ${p}`)));
+const confirmed = await Promise.all(
+  reviews.flatMap((r) => r.findings).map((f, i) => agent(`confirmer-${i}`).ask<Confirmation>(`Reproduce: ${JSON.stringify(f)}`)),
+);
+
+// ✓ One join: each file's findings go to their confirmers the moment its review lands.
+const confirmed = (
+  await Promise.all(
+    paths.map(async (p) => {
+      const review = await agent(`reviewer-${p}`).ask<Review>(`Review ${p}`);
+      return Promise.all(
+        review.findings.map((f, i) => agent(`confirmer-${p}-${i}`).ask<Confirmation>(`Reproduce: ${JSON.stringify(f)}`)),
+      );
+    }),
+  )
+).flat();
+```
+
+The stages that genuinely need everyone — a triage that ranks on one scale, a synthesis that
+deduplicates across findings — are the legitimate barriers, and they are few. A shared,
+calibrated subagent is not one of them: asks on it queue FIFO, so feeding it per item as
+results land keeps it consistent *and* keeps the pipeline moving (§11).
+
+One rejection inside `Promise.all` rejects the whole join and the sibling results with it.
+When one bad item should cost one item, catch inside the callback (examples #3) or use
+`Promise.allSettled` and read each outcome.
+
+## 8. Group the run into named phases
+
+Phases are required, not a nice-to-have. The user experiences a workflow through its
+phase graph: the confirmation dialog they approve is drawn one node per phase, and a
+dialog with thirty step cards in it is a dialog nobody reads. Cover the whole script —
+every stage gets a `phase("...")` marker at its head, and the arrows between the phases
+are inferred from the same analysis:
+
+<!-- compile -->
+```ts
+interface Attempt {
+  /** One sentence: the optimization this round is trying. */
+  approach: string;
+}
+
+/** Total nanoseconds the bench reports, or Infinity when it printed none. */
+function benchNanos(output: string): number {
+  const match = /time:\s*([\d.]+) ns/.exec(output);
+  return match?.[1] === undefined ? Number.POSITIVE_INFINITY : Number(match[1]);
+}
+
+phase("Measure today's baseline");
+const baseline = await world.run("cargo", ["bench"], { timeoutMs: 1_800_000 });
+const target = benchNanos(baseline.stdout);
+const optimizer = agent("optimizer");
+
+let winner = "none";
+for (let round = 1; round <= 3; round++) {
+  phase("Make one improvement");
+  const plan = await optimizer.ask<Attempt>(
+    `Round ${round}. Baseline timings:\n${baseline.stdout}\nMake one improvement.`,
+  );
+
+  phase("Check that the tests still pass");
+  const check = await world.run("cargo", ["test"]);
+  if (check.exitCode !== 0) continue;
+
+  phase("Measure whether it is actually faster");
+  const bench = await world.run("cargo", ["bench"], { timeoutMs: 1_800_000 });
+  if (bench.exitCode === 0 && benchNanos(bench.stdout) < target) {
+    winner = plan.approach;
+    break;
+  }
+}
+
+phase("Collect the final numbers");
+const head = await world.run("git", ["rev-parse", "HEAD"]);
+return { approach: winner, commit: head.stdout.trim() };
+```
+
+Five nodes — "Measure today's baseline" → "Make one improvement" → "Check that the tests
+still pass" → "Measure whether it is actually faster" (and back to "Make one improvement")
+→ "Collect the final numbers" — and they stay five when the real version of this script
+grows to thirty steps. That is the entire payoff: the user sees the story you had in your
+head instead of a wall of cards.
+
+Notice the two checks. The unit tests are the fast tier: they decide whether a round is
+worth measuring. The bench is the check the request was about, and it runs every time a
+round survives the tests — not once at the start to print a baseline and never again. A
+loop that gates on `cargo test` alone would crown the first round that compiles (§5).
+
+**Write the names for the user, not for the graph.** A phase name is a short natural
+phrase saying what this stage accomplishes for the user, written in the language the
+user is speaking in this session — "Research each changed file in parallel",
+"汇总并产出最终报告". Orchestration vocabulary the user never chose ("fan-out",
+"gate", "aggregate") names the machinery, not the work. Names must be compile-time
+string literals, so you cannot number rounds by interpolation — and you should not
+want to: two markers with the same name are one node, which is how a loop body stays
+one box across all its rounds.
+
+**Put the marker where the steps are.** A marker claims the rest of the block it sits
+in, nested blocks and inlined helper calls included, so a marker inside an `if` covers
+that branch and stops at its closing brace. Mark the block where the `ask` and
+`world.run` calls actually live.
+
+**Not inside a concurrent fan-out callback.** The run has one current phase, and every step
+is stamped with it at birth. Twenty `map(async …)` callbacks each re-entering
+`phase("Review")` and `phase("Confirm")` out of order would stamp each other's steps and
+count every re-entry as a round. A per-item pipeline (§7) is one phase, named for what it
+does to each item — "Review each changed file and confirm its findings as they land" — and
+the markers stay at the top level around it.
+
+**Every phase must contain at least one `ask` or one `world.run`.** A phase is a stage
+the user watches progress through. Plain script logic — reading `args`, shaping a
+prompt, sorting results, building the final `return` — runs in a flash and shows no
+progress, so it is not a stage; a phase made only of it sits on the timeline as a step
+that never does anything. Fold that logic into the phase before or after it. In
+particular, do not open a phase for the setup at the top of the script or for the
+`return` at the bottom; the first phase starts at the first ask, and the last phase is
+the last stage that asks or runs something. The same goes for a branch that only
+narrates: an `if` whose body is nothing but `report(...)` and `log(...)` does not get
+its own marker.
+
+## 9. Write for the user
+
+Six things you write are read by the user, not by the script: phase names, subagent names,
+`log` lines, artifact titles and the markdown you publish, the four report fields, and any
+question a subagent escalates. Write each one the way you would tell a colleague across the
+desk what is happening: say what the work is, in the words the user would use, in the
+language the user is speaking in this session. The machinery — fan-out, gate, node, stage,
+pipeline — is yours, not theirs, and so is the numbering.
+
+| Read by the user | Write | Not |
+| --- | --- | --- |
+| Phase name | Review each changed file / 逐个检查改动的文件 | Fan-out review stage / 文件评审阶段 |
+| Phase name | Check that the tests still pass / 确认测试仍然通过 | Gate: test verification / 执行测试验证任务 |
+| Subagent name | Code reviewer / 代码评审员 | reviewer_2 / 节点3 |
+| Subagent name | Benchmark runner / 跑基准测试的人 | runner / 子代理A |
+| Phase name | Independent review of the final plan / 请没看过方案的人再审一遍 | Cold read of the plan / 冷读方案 |
+| Subagent name | Independent reviewer / 独立评审员 | cold-reviewer / 冷眼评审 |
+| `log` line | Reviewing 12 changed files / 正在检查 12 个改动的文件 | Fan-out sized: n=12 / 扇出阶段初始化完成 |
+| Report conclusion | Two of the twelve files have real bugs, both in the parser. / 12 个文件里有 2 个有真问题,都在解析器里。 | The workflow executed successfully and produced findings. / 工作流已成功执行并生成结果。 |
+| Artifact title | Review report / 评审报告 | report-artifact-v1 / 产物输出 |
+| Escalation question | Should the threshold be 94 rather than 96? / 阈值应该是 94 而不是 96 吗? | Requesting clarification regarding gate configuration parameters / 请求对门控配置参数进行澄清 |
+
+The method names in this skill — fresh eyes, independent read — are English idioms for you,
+not words for the user. Carry the idea across, not the words: in Chinese that is 独立复核 or
+换人复审, never a word-for-word rendering such as 冷读 or 冷眼, which are not Chinese.
+
+The language travels through your asks. Findings, summaries and anything else the user will
+read are written by subagents answering the ask you wrote, so write those asks in the user's
+language, or say in the ask which language to answer in. Otherwise a Chinese report arrives
+wrapping English findings.
+
+## 10. Verify, report, deliver
+
+`log(...)` is narration for the human watching the run. Use it at the points where a reader
+would otherwise wonder whether anything is happening — after a fan-out is sized, at the top
+of each loop round.
+
+**Verify before you report, in proportion to what a wrong claim costs.** Verification
+exists to buy down the cost of the user acting on something false, so it goes where that cost
+is real: a bug they will fix, a security claim, a number they will quote, a fact a decision
+rests on. Each finding of that kind is confirmed independently before it reaches the user: a
+second subagent that reproduces the finding from its evidence alone — reading the code,
+running a check when one decides it, never editing — or a `world.run` command when one can
+decide. The reviewer that found the problem does not get to confirm it; self-confirmation is
+not confirmation. A finding that fails confirmation is **kept and labelled** `unconfirmed`,
+never silently dropped — a real issue the confirmer could not reproduce is still worth a
+human's eyes, and the label is what lets the user tell "seen" from "suspected".
+
+Three things that look like verification and are waste. A confirmer on a finding a
+`world.run` already decided: the exit code is the confirmation, so record the command in
+`verified` and move on. A confirmer on work nobody will act on as fact — poems, brainstormed
+options, a first-draft survey — which gets at most one independent read (§3). And a suite run
+three times because the hunter ran it, the confirmer ran it and then the script gated on it:
+a check the script runs as a gate is run once, by the script, and the asks say so ("the
+script runs the full suite after you; do not run it yourself") so the subagents spend their
+turns on what only they can do.
+
+**Gate at the task's scale.** `verified` names the commands that actually decided the
+result, and the reader will hold them against what they asked for. A unit suite in
+`verified` and the end-to-end suite in `notCovered` is not a verified deliverable; it is an
+unverified one with a disclosure attached. `notCovered` is for what *could not* be checked —
+no test exists for it, the environment lacks the tool, the check needs something only the
+user has — never for a check that exists in the repository and was skipped because it is
+slow or because the fast tier already passed. If the strongest check the request implies
+exists and did not run, the run is not done: run it, or say in `conclusion` that the work
+is unverified and why (§5).
+
+**Salvage by report.** `report(...)` is different from `log` and more important: reported
+items are delivered with the completion notification **even when the run fails**. A
+forty-task run that dies on task twelve still did eleven tasks' worth of work, and `report`
+is the only thing that gets that work out. So report each finding at the moment it lands —
+after its confirmation, with its status — rather than accumulating an array and returning it
+at the end: the array is what you lose. Items are recorded, so a resumed run never shows the
+same one twice.
+
+Give open-ended work an explicit round cap in the script rather than an unbounded loop: the
+harness enforces no node limit, so a loop that never goes dry only ends when the user cancels.
+
+**Deliver a report.** The script's final `return` is the handoff the main agent presents,
+in the order below; what the user themselves keep is the artifact of the next section.
+Return this shape (copy the interfaces; they compile as-is) rather than a bare array:
+
+<!-- compile -->
+```ts
+interface Finding {
+  /** Workspace-relative path, with a line when it applies: "src/a.ts:42". */
+  where: string;
+  /** One sentence: what is wrong, or what was found. */
+  what: string;
+  /** What showed it: the lines read, or the command and the output that proved it. */
+  evidence: string;
+  /** "verified" when an independent subagent or a deterministic check confirmed it; "unconfirmed" when confirmation failed or was not attempted. */
+  status: "verified" | "unconfirmed";
+  /** How much it matters. Reserve "high" for data loss, a crash, or a wrong result. */
+  severity: "low" | "medium" | "high";
+}
+interface WorkflowReport {
+  /** Two or three sentences answering what the user asked for. */
+  conclusion: string;
+  findings: Finding[];
+  /** What the run checked and how: the commands it ran, the files it covered. */
+  verified: string[];
+  /** What the run did not look at or could not check, and why. */
+  notCovered: string[];
+}
+
+const result: WorkflowReport = {
+  conclusion: "Nothing was reviewed: this snippet only shows the shape.",
+  findings: [],
+  verified: [],
+  notCovered: ["everything — no subagent ran"],
+};
+return result;
+```
+
+Before returning it, give it an independent read (§3): a reader-proxy subagent that has seen nothing else
+tells you what is unclear, unsupported, or missing, while there is still time to fix it.
+
+Each field has a reader. `conclusion` is the answer to what the user asked. `findings` carry
+their evidence and their status, so the user can tell what was seen from what was suspected.
+`verified` says what this run actually checked and how — the commands it ran, the files it
+covered. `notCovered` says what it did not look at and why, which is the difference between
+"we found nothing" and "we looked nowhere". Write all four in the language the user is
+speaking in this session.
+
+**Deliver artifacts.** The `return` is read by the main agent, which retells it. `artifact.*`
+is the other channel: things the *user* opens, shown as cards beside the run while it is
+still going and kept after it ends. Two habits:
+
+- **Every run publishes its deliverable.** The deliverable is whatever the user asked for.
+  When that is a thing — a webpage, a PDF, a spreadsheet, a generated site — a subagent writes
+  it into the workspace with its own tools and returns the path, and the script publishes that
+  path with `artifact.file`. Until it does, nothing the run left in the workspace exists as far
+  as the user is concerned, which is why "write it to `out/…` and return the path" belongs in
+  the ask that produces it. When the user asked for an answer — findings, a review, an
+  analysis — the deliverable is a report, and the `return` alone is not it: the return is a
+  compact handoff the main agent retells, while the user deserves the long form of the same
+  facts, the findings with their evidence, what was checked and what was not. Markdown
+  composed from the same values the return is built from is the usual shape; a subagent-written
+  document is fine when the user asked for one. Publish it once, at the end, when the facts are
+  settled. The one exception is a run whose whole answer is a line: a verdict, a number, a yes
+  or no. A page that restates one sentence is noise, so let the return carry it alone.
+  When the run publishes more than one artifact, mark the deliverable `{ primary: true }`: the
+  completion card and the run pane lead with it (its `description` is shown beside the title),
+  and the notification the main agent reads lists it first. One id per run; a run whose only
+  artifact is the deliverable needs no flag.
+- **A dashboard is for the person watching the run.** Its job is to answer "where is it, how
+  is it going" without opening anything. Declare one when the run has state worth watching
+  while it is still running: the key number after each round, which items are done and which
+  failed. Metrics or a chart when the watched thing is a number; a table or board when it is
+  a set of items with a status. Declare it once at the top, then tag the items you are
+  already reporting: `report(item, "perf")`. Nothing else is needed; the dashboard is a
+  projection of that stream, so it grows live and comes back identical after a resume. A run
+  that is over before anyone would look at it needs none.
+
+**Show what matters.** More artifacts is not more delivery: every card competes with the
+deliverable for the user's attention. Two tests decide what earns a card. Would the user open
+it on its own? If not, it is a section of the deliverable. Does it repeat another artifact? A
+CSV and a table of the same rows, a report and a copy of it, a chart and a metrics tile of the
+same number — one of each pair is noise. The common run publishes one deliverable, one
+dashboard when there is something to watch, and further files only when a subagent produced
+something else a person opens.
+
+Ids and the report tag are compile-time string literals. What a run can publish is therefore
+fixed at the moment the user approves the script, and an id assembled at runtime is a compile
+diagnostic rather than a surprise. Publishing an id a second time mints the next version and
+keeps the old one, so a file worth republishing each round costs you nothing to name once.
+
+**A rejected publish is a repair opportunity, not an error to swallow.** Content publishes
+reject catchably — the file is missing, the path escaped the workspace, the bytes are over the
+cap — and the honest response is to hand the gap back to a subagent and publish again, rather
+than let a run end with nothing the user can open:
+
+<!-- compile -->
+```ts
+interface RoundOutcome {
+  /** 1-based round number. */
+  round: number;
+  /** Query latency in milliseconds, measured after this round's change. */
+  queryMs: number;
+  /** One sentence: what this round changed. */
+  change: string;
+}
+
+const TARGET_MS = 20;
+artifact.chart("perf", {
+  title: "Query latency by round",
+  x: { field: "round", label: "Round" },
+  y: { field: "queryMs", label: "ms" },
+  baseline: { field: "target" },
+});
+
+phase("Optimize until the bench meets its target");
+const optimizer = agent("optimizer", {
+  system:
+    "You speed up a JSONL query engine: change one thing, measure it, and write the profile " +
+    "of the query path to out/profile.html.",
+});
+const rounds: RoundOutcome[] = [];
+for (let round = 1; round <= 3; round += 1) {
+  const outcome = await optimizer.ask<RoundOutcome>(
+    `Round ${round}: make the query faster, then measure it.`,
+  );
+  rounds.push(outcome);
+  report({ ...outcome, target: TARGET_MS }, "perf");
+  if (outcome.queryMs <= TARGET_MS) break;
+}
+
+phase("Hand the user the profile and the write-up");
+try {
+  await artifact.file("profile", "out/profile.html", { title: "Query profile after the last round" });
+} catch {
+  const profiler = agent("profiler");
+  await profiler.ask("out/profile.html is missing. Profile the query path as it stands and write the profile there.");
+  await artifact.file("profile", "out/profile.html", { title: "Query profile after the last round" });
+}
+const latest = rounds[rounds.length - 1]?.queryMs ?? 0;
+await artifact.markdown(
+  "report",
+  [
+    `# Query latency: ${latest}ms against a ${TARGET_MS}ms target`,
+    "",
+    ...rounds.map((r) => `- Round ${r.round}: ${r.queryMs}ms — ${r.change}`),
+  ].join("\n"),
+  {
+    title: "Optimization report",
+    description: `What each of the ${rounds.length} rounds changed and what it bought.`,
+    primary: true,
+  },
+);
+
+return {
+  conclusion: `Latency landed at ${latest}ms against a ${TARGET_MS}ms target.`,
+  verified: ["each round's latency was measured by the subagent that made the change"],
+  notCovered: ["memory use; only query latency was measured"],
+};
+```
+
+One `report` call feeds both surfaces: the tagged item lands on the chart *and* in the run's
+progressive results, so tagging costs nothing and adds a picture. Three cards, none repeating
+another: the chart is what the user watched, the profile is what a person opens, the report
+is what they keep. The CSV the bench also wrote stays in the workspace — its rows are the
+chart's points, so a card for it would say nothing new.
+
+## 11. A complete example
+
+The complete review workflow that used to sit here — a reviewer per changed file, triage
+through one shared subagent that is fed as reviews land, a confirmer per kept finding chained
+inside the same callback, one join for the cross-file deduplication — is
+`${ZCODE_SKILL_DIR}/examples.md` §5. Read it when you want to see a whole script's arc; §7
+and §10 already carry its rules.
+
+## 12. Anti-patterns
+
+| What you wrote | What it costs you |
+| --- | --- |
+| Hoisted one subagent out of a fan-out for tidiness | The fan-out silently became a FIFO queue |
+| Gave every subagent in a fan-out the same fixed name | Every name in a run must be unique: a literal one is rejected at compile time, a computed one kills the run at the second item. Name per item or stay anonymous |
+| A fresh subagent each loop round | Round five re-learns everything round four knew, at full price |
+| Accumulated findings in an array, returned at the end | A failure on the last task loses all of them; `report` as you go |
+| Interpolated a whole file into the prompt | Paid tokens to tell a subagent something its own tools would have read |
+| A wide `files.grep` with no glob | The call rejects; it does not quietly hand you a partial workspace |
+| An unbounded `while` | The run dies on a cap instead of finishing |
+| Asked a subagent to run the tests and report whether they passed | Paid a session for what `world.run` does as code — and trusted a pass/fail claim the subagent can fake |
+| Built the `world.run` command name from a variable or template hole | Compile fails: the user approves the script's command set, so the command must be a literal; runtime values belong in the args array |
+| Submitted a workflow to find out whether a parse function works | A full run spent on what `EvalWorkflowSnippet` answers synchronously |
+| Dereferenced a `.find()` / `.match()` result or an optional property without a guard | Compile fails: `strict` keeps those `T \| undefined` / `null`; plain `items[i]` needs no guard (`noUncheckedIndexedAccess` is off) |
+| `Date.now()` / `Math.random()` / `fetch` / `fs` | Rejected at compile time; a replayable run cannot contain them |
+| Awaited each call in a loop that had no ordering requirement | Serial wall-clock for concurrent work |
+| Interpolated a tunable constant (a threshold, a cap) into an ask message | Amending that one number rewrites every prompt that mentions it: an `AmendWorkflow` re-run misses cache at the first such ask and re-pays everything downstream |
+| Named a phase or a subagent after the machinery, in either language ("fan-out", "文件评审阶段", "节点3"), or shipped the script with no markers at all | The user approves a graph whose stages say nothing about their work — or thirty cards with no story (§9) |
+| Wrote a persona that says only "make the check pass" | Against a check it cannot pass, faking one is the obedient reading. Tell the subagent to escalate an impossible gate instead (§14) |
+| Asked the reviewer "is this good?" | A reviewer asked for approval approves; ask what would break it and what is missing (§3) |
+| Reported findings nobody confirmed | The user gets a list that cannot tell "seen" from "suspected"; confirm each finding independently and label the ones that failed (§10) |
+| Gated the loop on the unit tests and never ran the integration suite, the end-to-end suite, or the bench the request was about | The work passed the check that was cheap, not the one that decides; the strongest check runs at least once before `return` (§5) |
+| Wrote the gate from habit (`cargo test`, `node --test`) without reading the project's own scripts | The `package.json`, `Makefile` or README already named a stronger check, and the user knows it; survey the repository's checks before you gate (§5) |
+| Put a check that exists into `notCovered` because it was slow | An honest-looking report of unverified work; `notCovered` is for what could not be checked (§10) |
+| Returned a bare array as the run's result | The main agent has to improvise the deliverable, so the user gets a different shape every time; return the report shape (§10) |
+| Returned the report and published nothing | The user gets the main agent's retelling and nothing to keep; publish the deliverable — the file they asked for, or the findings in long form (§10) |
+| Published a CSV and a table of its rows, or a report and a copy of it | Two cards for one fact: the second is noise the user has to look past (§10) |
+| Declared a dashboard for a run nobody watches | Three points on a chart for a run that was over before anyone looked; a dashboard is for the person watching (§10) |
+| Stacked a reviewer loop, a fresh final reviewer, a per-finding confirmer and a reader-proxy read on one deliverable | Four sessions re-reading the same work; one deliverable gets one mechanism, two at most with a reason (§3) |
+| Sent a confirmer after a finding a `world.run` already decided, or let the hunter, the confirmer and the gate each run the suite | The same check paid three times; the exit code is the confirmation, and the gate runs the suite once (§10) |
+| `Promise.all` between two stages whose items map one to one (review every file, *then* confirm every finding) | The slowest reviewer gates every confirmer while the slots idle; chain the stages per item and join once (§7) |
+| Waited for a run you already knew was wrong to finish, or stopped it and left it | Everything after the fix point is re-paid either way; call `AmendWorkflow` on it now, while it runs (§13) |
+| Pasted a whole revised script inline after a diagnostic or an error, instead of editing the file the tool named | Twenty thousand tokens re-streamed to change one line, on a provider that may stall on the resubmit — and a script compaction has dropped is one you can no longer paste; the file is on disk, so the revision is an `Edit` and a `path` (§13) |
+
+## 13. After you submit
+
+Compilation happens first. **Diagnostics mean nothing ran** — there is no partially-started
+run to clean up — and they name the file your script is in. Every script you submit has one:
+an inline `script` is written under `.zcode/workflow-drafts/` before it is even compiled and
+the response hands you the path; a script you submitted by `path` is that file already. Each
+diagnostic reads `{path}:L{line}:C{column} {message}`, counted in the file, so it addresses
+an `Edit` as it stands.
+**Edit that file and resubmit with `path`. Do not paste the script inline again**:
+re-streaming twenty thousand tokens to change one line is slow enough that some providers
+stall on it, while the `Edit` that fixes it costs a few lines. (If the response names no
+file — a checkout the tool could not write to — then fix the script and resubmit it inline,
+as before.)
+
+On a clean compile the run starts in the background and you get a run ID. **Do not poll it.**
+The completion notification arrives on its own and carries the final return value plus every
+reported item. Go do other work, unless the user asked you to wait.
+
+When you genuinely need to look at a run:
+
+- `TaskOutput` blocks until a run *this session started* finishes. That is the waiting tool.
+- `GetWorkflowRun` is an instant snapshot and never waits. Use it when you must not block,
+  or for a run another session owns — `TaskOutput` cannot see those.
+- `ListWorkflowRuns` enumerates the project's runs, including other sessions'.
+
+Read the terminal state precisely. A run ends in exactly one of three states:
+
+- **completed** — the script returned.
+- **errored** — the script itself failed (an uncaught throw, a cap it overran, an artifact
+  whose source file was missing). Replaying it would fail the same way, so
+  `ResumeWorkflowRun` refuses it; edit the run's script file, which the notification names,
+  and resubmit it with `AmendWorkflow` and `path`.
+- **stopped** — the run was stopped and can be resumed as-is with `ResumeWorkflowRun`. The
+  notification's `<stop-reason>` says why: `user` (the user stopped it — leave it alone
+  unless they ask), `model` (you stopped it with TaskStop), `interrupted` (the process that
+  owned it exited; resume it), or `provider` (a subagent hit a deterministic model-side
+  error — sign-in expired, model not in the plan, quota cap; the `<error>` block names the
+  cause and the fix — resolve it with the user, then resume). A fifth reason, `superseded`,
+  never arrives as a notification: it is the state of a run you amended away, and the
+  `AmendWorkflow` result already told you. Such a run is not resumable; its successor is
+  the live one.
+
+Reported items come back on errored and stopped runs too, so a dead run is still worth
+reading. Model errors never reach the script: rate limits, overload, network errors,
+timeouts and unknown provider errors are retried inside the run without limit while the
+fan-out adapts to what the provider accepts, so a run that looks stalled with a "waiting for
+provider" badge is waiting, not broken. If nothing succeeds for twenty minutes you get one
+informational stall notification; the run is still running and needs nothing from you.
+
+**When the script itself was wrong, do not start over.** Any run — errored, stopped,
+completed, or still running — can be superseded: edit the run's script file and call
+`AmendWorkflow` with `run_id: "<runId>"` and that `path`. That starts a new run which
+imports the old one's finished work, matched per named subagent along its sequence of asks,
+so every step you did not touch settles from cache at no token cost and only the changed
+part actually runs — with one deliberate limit: the moment a live subagent writes to the
+workspace (or a live `world.run` executes), the workspace may no longer be the one the old
+results were computed against, so from that point every cached `world.run`, every cached
+world read and every cached ask whose subagent had read or run something runs live even if
+its text is unchanged; asks whose subagent only answered keep settling from the cache. A gate
+command therefore always tests the code the amended run actually produced; the price is
+that doing steps after the first live write are re-paid. The old run is left exactly as it
+was. This is the move after a `ScriptError`, after a bad prompt
+produced a useless result, and when a completed analysis needs one more stage — rewriting
+the workflow from scratch throws away work that was already paid for. Two things make the
+cache hit: names that stay the same across the revision, and asks whose instructions stay
+byte-identical (an upstream change cascades — a changed result changes what interpolates
+into everything downstream, which is what you want).
+
+**Every run remembers its script file, so a revision is an `Edit`.** The terminal
+notification names that path, and `GetWorkflowRun` reports it as `scriptPath` — which is why
+you never have to keep the script in context: by the time a long run errors, compaction may
+well have dropped the text you sent, while the file on disk has not moved. Edit it in place
+and pass `path`; pass `script` only when what you are submitting is genuinely new. A `path`
+whose bytes still equal what the run already ran is refused as `script_unchanged`, with
+nothing stopped and nothing created — that refusal means your `Edit` did not land, not that
+the run cannot be amended (changing only `max_concurrency` or `subagent_model` is a real
+change and goes through).
+
+**Editing a draft asks nothing.** `.zcode/workflow-drafts/` is machine-owned and
+git-ignored, so an `Edit` or `Write` under it is pre-approved and opens no confirmation
+window. Editing a script is not running one: the window still stands between the file and
+the run, so fix the file freely and let the submission be the thing the user answers.
+
+**Repair a run while it is still going.** The same call works before the run ends, and it
+is cheaper the earlier you make it. When the user points at a run that is heading the wrong
+way, or a reported item shows the script is wrong, do not wait for the completion
+notification and do not stop the run first: call `AmendWorkflow` on it. The tool stops the
+running predecessor, waits for it to settle, imports everything that settled before the
+stop at zero cost, and starts the revision — one call, no `TaskStop`, no polling for the
+stop. Nothing after the stop was ever paid for, and nothing the predecessor finished is paid
+twice: the cache stays open until the revision's first write to the workspace, and asks whose
+subagent only answered, without reading or running anything, keep replaying even after that. The
+old run shows as "superseded" and sends no notification of its own; the result you get back
+names both runs. A run you amended is not left for the user to ask about: the amend result
+is the account of what happened to it.
+
+That cascade rule has a converse that decides whether your revisions are cheap or ruinous.
+Interpolating an upstream **result** into a prompt is safe: on resume the result replays
+byte-identical, so the prompt does too. Interpolating a script **constant** is the
+opposite bet — constants are exactly what an amendment tunes, and every ask whose text
+mentions one is an ask whose cache you forfeit by tuning it, plus everything downstream of
+it:
+
+```ts
+// ✗ Couples every revision ask to a knob you will want to tune. Amending
+//   PASS_THRESHOLD (say 96 → 94) rewrites this text, so the resumed run misses
+//   cache at the first revision and re-pays every ask after it — to reproduce
+//   answers the old run already holds.
+draft = await writer.ask<Draft>(
+  `Scored ${review.score}; passing needs ${PASS_THRESHOLD}. Revise: ${JSON.stringify(review.comments)}`,
+);
+
+// ✓ The prompt carries only replayed upstream values and the fact that the
+//   branch was taken; the threshold comparison already happened in script code.
+//   Amending the threshold now moves only where the loop exits — every round
+//   before that point settles from cache.
+draft = await writer.ask<Draft>(
+  `The review did not pass. Address each comment: ${JSON.stringify(review.comments)}`,
+);
+```
+
+Keep the tunable knobs — thresholds, round caps — in the script's control flow,
+where amending them is free, and out of ask text, where amending them is a cache purge.
+A subagent almost never needs the number anyway; it needs the verdict and the feedback.
+
+## 14. When a subagent escalates
+
+Every subagent can escalate a blocking question to you while the run is going. Nothing in the
+script switches this on and no persona field controls it — the tool is injected the way
+`submit_result` is. It exists for the one thing a script
+cannot design its way around: a subagent walled in by something that is not its fault. A gate
+it cannot pass (a check capped at 95 against a threshold of 96), two instructions no single
+output satisfies, or a fact only whoever started the run knows. With no way to ask,
+a walled-in subagent has two moves left and both are bad — grind until the round cap, or
+fake its way past.
+
+**What reaches you.** A notification arrives mid-run carrying the run, the subagent, the
+question with whatever evidence the subagent attached, and a globally unique question id shaped
+like `dwfq-...`. Only the subagent that asked is parked, and only on that one call: its
+siblings, the script's control flow and the run's status all carry on unchanged. Nothing
+times out on its behalf either — it waits until you answer or until the run is cancelled. So
+you need not drop what you are doing, but you cannot leave it unanswered.
+
+**Then decide which of two things is true.**
+
+- The question **has an answer** — a clarification, one missing fact, a tradeoff only you can
+  call. Answer it with `ResolveWorkflowQuestion` and that `question_id`. Your text becomes
+  the result of the subagent's own call, verbatim, and it continues its turn from there. Not
+  sure? Read the run with `GetWorkflowRun`, or put the question to the user with
+  `AskUserQuestion` — then come back and answer, because nothing answers in your place.
+- The **script** is what is broken — a gate no output can pass, control flow routing work to
+  the wrong subagent. No sentence fixes that. Edit the run's script file and call
+  `AmendWorkflow` on it with that `path` (§13); it stops the run for you. The escalation is
+  what makes that amendment cheap: the ask that escalated never settled, so it sits exactly
+  past the cache boundary — everything before it imports from the old run at no token cost,
+  and it re-runs against the fixed script.
+
+**If the notification never arrives**, the question is still discoverable. `GetWorkflowRun`
+lists what a run still owes an answer to under `pendingQuestions`, ids included. That
+snapshot is the fallback when a notification is dropped, and the way to check on a run you
+suspect is waiting on you.
+
+**Write personas that make honesty the cheap move.** A subagent follows the instructions you
+wrote, so a persona that says "make the check pass" and stops there leaves faking a pass as
+the obedient reading. One sentence closes that off; adapt this one: *"If a check is
+impossible to pass, or your instructions contradict each other, escalate and say so plainly
+rather than working around it."*
+
+One ask gets three escalations. The fourth comes back as an ordinary result telling the
+subagent its escalation allowance is spent and to proceed on its own best judgement — a guard against
+chatter, not an allowance to spend.
+
+## 15. Going deeper
+
+- `${ZCODE_SKILL_DIR}/patterns.md` — the topology catalogue: fan-out/fan-in, review sweeps,
+  planner-reviewer loops, judge panels, staged pipelines, bounded discovery,
+  `world.run`-gated verifier loops. Read it
+  when you know the shape you want and want it written correctly.
+- `${ZCODE_SKILL_DIR}/examples.md` — complete worked scripts, including a two-subagent
+  adversarial prove/disprove loop. Read one when you want to see a whole script's arc.
+
+## 16. Tool reference
+
+The four authoring tools — `CreateWorkflow`, `AmendWorkflow`, `SaveWorkflow` and
+`EvalWorkflowSnippet` — carry one-paragraph descriptions on purpose, and each of them refuses
+to run until this skill has been loaded in the session. This section is the part of their
+contract that the descriptions do not carry: the facade the compiler checks against, the
+rules a script must satisfy, and the fields each tool takes. Read it before writing or
+revising a script; the compiler holds you to it.
+
+### 16.1 `CreateWorkflow`
+
+Typechecks the script; on a clean compile asks the user to confirm and starts the run in the
+background; you are notified with the script's final `return` value when the run settles.
+Compilation errors come back as diagnostics, counted in the script's file (§13).
+
+**Three sources; pass exactly one.**
+
+- `script`: a one-off workflow written inline. It is saved to a file under
+  `.zcode/workflow-drafts/` and the result names that file, whether the script compiled or
+  not; revise it by editing the file and resubmitting with `path`, never by pasting the
+  script again.
+- `saved`: a workflow saved in this project or globally, by name —
+  `saved: { name: "pr-review", args: { pr: "123" } }`. Its arguments are validated against
+  its declaration (unknown keys, missing required values and wrong types are rejected)
+  before anything runs. Before writing a workflow from scratch, check `ListSavedWorkflows`:
+  a saved workflow the user reviewed and kept beats a rebuilt one. Running a saved workflow
+  is the one call that does not need this skill loaded.
+- `path`: a script file on disk, relative to the working directory or absolute — normally
+  the file a previous result named. Pass `args` alongside it when the file declares
+  arguments in its `/* zcode-workflow` block.
+
+Either way the user confirms the run, and the confirmation shows the actual script.
+
+**Fields.**
+
+- `name`: a short label for the run in the user's language ("PR review", "代码评审").
+  Always pass it for an inline script; it labels the run everywhere and names its draft
+  file. It defaults to the saved workflow's name.
+- `max_concurrency`: an upper bound on how many subagents work at once. Set it only when
+  the user asks to limit parallelism — never on your own initiative and never as a
+  reaction to provider rate limits or errors, which the runtime already adapts to. A value
+  above the machine's ceiling is lowered to it. Otherwise how many subagents run at once is
+  the runtime's decision, not the script's.
+- `subagent_model`: the model the subagents run on, as `providerId/modelId` or a bare
+  model id (optionally `$reasoningLevel`). Set it only when the user asks for a specific
+  model; pass the name the user used, and if the tool cannot resolve it, pick from the ids
+  it lists or call `ListModels`. You stay on the session model either way.
+
+This tool starts a new run. To change a run that exists — errored, completed, stopped or
+still running — call `AmendWorkflow` (§13, §16.4), never `CreateWorkflow` again.
+
+### 16.2 The facade
+
+Every script and snippet is checked against these declarations. They are the same constant
+the compiler is fed, so what you read here is what typechecks. The block uses `declare`
+because it is the host's ambient API description — do not imitate it; your script defines
+plain interfaces and never uses `declare`.
+
+<!-- facade-dts:start -->
+```ts
+/**
+ * A node: one task assigned to an actor, producing a typed result.
+ * Thenable — await it, or combine with Promise.all for joins.
+ */
+declare interface Node<T> extends PromiseLike<T> {}
+
+/**
+ * Persona of an actor: identity, fixed at creation (frozen for the actor's lifetime). Every
+ * actor has the regular working tools (reading, searching, editing, running commands); what
+ * it may do with them is said in the ask.
+ */
+declare interface AgentPersona {
+  /** System prompt describing the actor's role. */
+  system?: string;
+}
+
+/**
+ * An actor: a persistent conversational context that executes tasks serially.
+ * Context accumulates across asks; concurrent asks on one actor queue FIFO.
+ */
+declare interface Agent {
+  /**
+   * Assign one task. T is the task's output value: an interface you define in
+   * this script with a plain "interface" declaration (no "declare" modifier; the
+   * harness synthesizes its runtime schema from the type), or the final response
+   * text when the type argument is omitted.
+   */
+  ask<T = string>(instructions: string): Node<T>;
+}
+
+/**
+ * Create a fresh actor. Every call creates a new context; sharing context means
+ * sharing this reference.
+ *
+ * The name is optional, but a non-empty one is an identity, not a label. It must be
+ * unique within the run: two actors under the same name fail the whole run. It is
+ * also the key a revised re-run matches its cache on (AmendWorkflow imports the
+ * finished work of each named actor), so stable, meaningful
+ * names carry work across script revisions. Anonymous actors are legal and never
+ * reuse imported work.
+ *
+ * In a fan-out or a loop each iteration is a separate actor, so a single static name
+ * there is the duplicate case: give each one its own name (agent("reviewer-" + file))
+ * or leave them all anonymous. A literal name in a loop is reported when the script
+ * is compiled; a computed one fails at run time.
+ */
+declare function agent(name?: string, persona?: string | AgentPersona): Agent;
+
+/**
+ * The run's arguments: the values supplied when this workflow was started.
+ *
+ * A workflow saved into the project declares its arguments (name, type, whether they
+ * are required, defaults); the host validates the caller's values against that
+ * declaration and fills in defaults before the run starts, so what lands here is
+ * always a complete, checked bag. For an inline script — and inside a snippet — it is
+ * simply empty.
+ *
+ * Always defined, so reading args.target is a plain property read rather than a crash.
+ * The values are typed unknown on purpose: the compiler surface must not change from
+ * one workflow to the next, so narrow them in the script -- String(args.target), or a
+ * typeof guard -- exactly as you would any other external input.
+ */
+declare const args: Readonly<Record<string, unknown>>;
+
+/** Emit a progress message to the user. */
+declare function log(message: string): void;
+
+/**
+ * Publish one intermediate result while the run is still going. Like log() it
+ * returns nothing and there is nothing to await — a finding has no reply.
+ *
+ * Unlike log() it is journaled: a resumed run never shows the same item twice, and
+ * the items are delivered with the completion notification even when the run ends in
+ * failure. That is the point of it — a run that dies on its twelfth of forty tasks
+ * still did eleven tasks' worth of work, and reported items are how that work
+ * survives.
+ *
+ * Two caps, and both fail the whole run rather than the call (there is no rejection
+ * channel in a void return): at most 256 items per run, and at most 32KB per
+ * serialized item. They are generous on purpose — report findings, not chatter.
+ *
+ * The item must be JSON-serializable: plain objects, arrays, strings, numbers,
+ * booleans, null. Functions, class instances, Date and promises are rejected when
+ * the script is compiled.
+ *
+ * The optional second argument routes the item to a dashboard artifact: pass the id
+ * of a preset declared with artifact.chart / table / metrics / board, and this item
+ * becomes one more point, row, tile value or card on it — the dashboard is nothing
+ * but the items tagged with its id. The tag must be a compile-time string literal
+ * naming a preset the script declares (anywhere in the text, but the declaration must
+ * have executed by the time this call runs); a tag that names nothing, or names a
+ * file/markdown artifact, fails the run. An untagged report is unchanged: it goes to
+ * the run's Results, and a tagged one goes to both.
+ */
+declare function report(item: unknown, artifactId?: string): void;
+
+/** A published artifact version: the id it was published under, and which version this call minted. */
+declare interface ArtifactRef { id: string; version: number }
+/** Card metadata every artifact kind accepts. */
+declare interface ArtifactOptions {
+  /** Shown as the card title; defaults to the id. In the user's language. */
+  title?: string;
+  /** A sentence or two, shown beside the title when this artifact leads the card. */
+  description?: string;
+  /** The run's deliverable: the card and the run pane lead with it. At most one id per run; once set it stays set for later versions. */
+  primary?: boolean;
+}
+declare interface ArtifactFileOptions extends ArtifactOptions {
+  /** Overrides the type sniffed from the extension ("application/pdf", "text/html", …). */
+  contentType?: string;
+}
+/** One value taken from a reported item: a dot path into the item ("timing.after"). */
+declare interface ArtifactField { field: string; label?: string; unit?: string }
+declare interface ChartSpec extends ArtifactOptions {
+  type?: "line" | "bar" | "scatter";        // default "line"
+  x: ArtifactField;
+  y: ArtifactField | ArtifactField[];        // several = several series
+  scale?: "linear" | "log";                  // y axis, default "linear"
+  /** A reference value drawn as a horizontal rule, taken from the first item that has the field. */
+  baseline?: ArtifactField;
+}
+declare interface TableSpec extends ArtifactOptions {
+  columns: ArtifactField[];
+  /** Field that identifies a row; a later item with the same key replaces the row. Absent = append-only. */
+  key?: string;
+}
+declare interface MetricsSpec extends ArtifactOptions {
+  /** Each tile shows the value from the latest item that has the field. */
+  metrics: ArtifactField[];
+}
+declare interface BoardSpec extends ArtifactOptions {
+  /** Field identifying a card; a later item with the same key moves/updates the card. */
+  key: string;
+  /** Field holding the card's column. */
+  status: string;
+  /** Column order. Items whose status is not listed land in a trailing "other" column. */
+  columns: string[];
+  /** Field for the card title (default: the key) and extra fields shown on the card. */
+  cardTitle?: string;
+  detail?: ArtifactField[];
+}
+/**
+ * Publish what the user should see: the run's own deliverable surface, kept after it ends.
+ * Two habits. (1) EVERY RUN PUBLISHES ITS DELIVERABLE, whatever the user asked for: a webpage
+ * or PDF a subagent wrote goes out via file(); an answer (findings, a review) goes out as the
+ * long form of the facts the return summarises, usually via markdown(). Once, at the end;
+ * skip it only when the whole answer is one line. When the run publishes more than one
+ * artifact, mark the deliverable { primary: true }. (2) A DASHBOARD IS FOR THE PERSON WATCHING
+ * THE RUN: declare one when there is state worth watching mid-run (the key number per round,
+ * which items are done) and none when the run is over before anyone looks. Two tests keep it
+ * to what matters: would the user open it on its own? does it repeat another artifact? A CSV
+ * and a table of its rows: one of them is noise.
+ *
+ * Every id is a compile-time string literal (non-empty, at most 64 characters of
+ * [A-Za-z0-9_.-]); the set a run can publish is fixed at submit time, so the compiler
+ * rejects a computed one. Within one run an id belongs to exactly one member.
+ * The two families are deliberately asymmetric, and the asymmetry is the whole design:
+ * - CONTENT (file, markdown) are EFFECTS: async, resolve to an ArtifactRef, and REJECT
+ *   catchably — missing file, not a file, path outside the workspace, over the size cap, no
+ *   store. try { await artifact.file("book", "out/book.pdf") } catch { …ask a subagent to
+ *   write it… } is the intended idiom. Bytes are copied at publish time, so later workspace
+ *   edits never rewrite a version; republishing an id mints the NEXT version and keeps the
+ *   old ones (at most 16 per id).
+ * - PRESET (chart, table, metrics, board) are DECLARATIONS: synchronous, return nothing,
+ *   never touch a file; they say how items tagged with their id are drawn. Declare each ONCE,
+ *   at the top, then feed it with report(item, "<id>"). The same id with an identical spec is
+ *   a no-op; a DIFFERENT or malformed spec fails the whole run — a void return has no
+ *   rejection channel, exactly as with report().
+ * Caps: 32 ids per run, 16 versions per id, 20 MiB per file, 256 KB per markdown, 120
+ * characters of title and 500 of description.
+ */
+declare const artifact: {
+  /**
+   * Publish a file from the workspace. path is workspace-relative, resolved by the same
+   * resolver files.read() uses; the bytes are copied at publish time. The content type is
+   * read off the extension unless opts.contentType overrides it. Rejects (catchably)
+   * rather than publishing something empty.
+   */
+  file(id: string, path: string, opts?: ArtifactFileOptions): Promise<ArtifactRef>;
+  /** Publish markdown text the script composed: the usual shape of a report deliverable, the long form of what the return summarises. */
+  markdown(id: string, content: string, opts?: ArtifactOptions): Promise<ArtifactRef>;
+  /** Declare a chart fed by report(item, id): each tagged item is one point. */
+  chart(id: string, spec: ChartSpec): void;
+  /** Declare a table fed by report(item, id): each tagged item is one row. */
+  table(id: string, spec: TableSpec): void;
+  /** Declare a metric tile row fed by report(item, id): each tile shows the newest value it has. */
+  metrics(id: string, spec: MetricsSpec): void;
+  /** Declare a board fed by report(item, id): each tagged item is a card, placed by its status field. */
+  board(id: string, spec: BoardSpec): void;
+};
+
+/**
+ * Mark the start of a phase: a short, human-readable name for the group of steps that
+ * follow, shown as one node on the workflow graph the user reads and approves.
+ * Presentation only — it starts nothing, waits for nothing, returns nothing.
+ *
+ * Required in every script you submit, not optional: the phase graph is how the user
+ * experiences the workflow. Without markers they face one card per step and no story;
+ * group the whole script, top to bottom.
+ *
+ * Name phases for the user, in the language the user is speaking in this session: a short
+ * natural phrase saying what the stage accomplishes ("Research each changed file in parallel",
+ * "汇总并产出最终报告"). Graph-building vocabulary the user never chose — "fan-out", "gate",
+ * "aggregate" — is not a name; the user approves stages by what they do. Say it the way you
+ * would tell a colleague what is happening: "确认测试仍然通过", not "执行测试验证任务".
+ *
+ * The scope is the rest of the enclosing block: the marker claims every step issued
+ * from it to the end of the block it stands in — nested blocks and inlined helper
+ * calls included — and the enclosing phase resumes once that block ends. A marker
+ * inside an if-branch therefore groups that branch and does not leak past it. Two
+ * markers with the same name are one phase: repeating a name continues that phase,
+ * which is the opposite of an actor's name — that one has to be unique.
+ *
+ * Two rules the compiler enforces. The name must be a compile-time string literal
+ * ("review the diff" or a no-substitution template) and non-empty, because the phase
+ * names label the graph the user confirms before anything runs. And the call must
+ * stand alone as its own statement: a marker in expression position has no
+ * rest-of-block to claim.
+ *
+ * Every phase must contain at least one subagent ask or one world.run. A phase is a
+ * stage the user watches progress through; plain script logic between two asks (reading
+ * args, shaping a prompt, building the return) runs in a flash and shows no progress, so
+ * it is not a stage. Fold it into the phase before or after it; never open a phase for
+ * the setup at the top or the return at the bottom.
+ *
+ * Idiom: one marker at the head of each stage that does work — name the loop body and
+ * its check where they start, name the close-out that asks or runs after the loop.
+ */
+declare function phase(name: string): void;
+
+/** One matching line found by files.grep. */
+declare interface GrepMatch {
+  /** Workspace-relative path of the file the match was found in. */
+  path: string;
+  /** One-based line number of the match. */
+  line: number;
+  /** The full text of the matching line. */
+  text: string;
+}
+
+/**
+ * Journaled read-only observations of the workspace, executed by the harness.
+ * Replay returns the journal-recorded value. Prefer passing paths to agents and
+ * letting them read files with their own tools; read() and grep() are for when the
+ * script itself must shard or branch on content. There is no write — writing to the
+ * world is an agent task.
+ */
+declare const files: {
+  /**
+   * List workspace files matching a glob pattern, as workspace-relative paths sorted
+   * lexicographically. Capped at 2000 files: over the cap the call rejects instead of
+   * returning a partial view — narrow the pattern.
+   */
+  glob(pattern: string): Promise<string[]>;
+  /** Read one workspace file as UTF-8 text. Size-capped. */
+  read(path: string): Promise<string>;
+  /**
+   * Search file contents with a ripgrep-compatible regular expression, optionally
+   * narrowed to a glob over paths (the same syntax glob() takes: "*.ts", "src/**").
+   * Returns one entry per matching line, with workspace-relative paths and one-based
+   * line numbers.
+   *
+   * Capped at 2000 matches or 256KB of results, whichever comes first. Over the cap
+   * the call rejects instead of returning a partial view — a silently truncated search
+   * is the one result you cannot reason about — so narrow the pattern or add a glob.
+   */
+  grep(pattern: string, glob?: string): Promise<GrepMatch[]>;
+};
+
+/** The working tree's status, as reported by git.status(). */
+declare interface GitStatus {
+  /** Current branch name; absent when HEAD is detached. */
+  branch?: string;
+  /** True when nothing is staged, modified, or untracked. */
+  clean: boolean;
+  /** Workspace-relative paths staged for the next commit. */
+  staged: string[];
+  /** Workspace-relative paths modified in the working tree but not staged. */
+  unstaged: string[];
+  /** Workspace-relative paths git does not track (honouring .gitignore). */
+  untracked: string[];
+}
+
+/** One commit, as reported by git.log(). */
+declare interface GitCommit {
+  /** Full commit hash. */
+  hash: string;
+  /** First line of the commit message. */
+  subject: string;
+  /** Author name. */
+  author: string;
+  /** Author date, ISO 8601. */
+  date: string;
+}
+
+/**
+ * Journaled read-only git observations — the same bargain as files.*: executed by the
+ * harness, recorded in the journal, and replayed from the record, so a resumed run
+ * sees the repository as it was rather than as it is now.
+ *
+ * Read-only by construction rather than by permission: the harness builds a fixed
+ * argument list for one allowlisted subcommand and never a shell string, so there is
+ * no call this surface can express that writes. A base must name a single ref — no
+ * ".." ranges in this version — and paths are workspace-relative.
+ *
+ * Observations are scoped to the workspace, which is the same world files.* observes:
+ * every path you get back is relative to the workspace and safe to pass straight to
+ * files.read(). If the workspace is a subdirectory of the repository, changes outside
+ * it are not reported — the workspace is the world. git.log is the exception, because
+ * commits are repository-wide objects rather than paths.
+ *
+ * Caps reject rather than truncate (diff at 512KB, log at 100 commits), for the same
+ * reason grep does. Outside a git repository, or with no git available, every call
+ * rejects with a catchable error, so the idiom is try/catch with a files.glob fallback.
+ */
+declare const git: {
+  /**
+   * Workspace-relative paths that changed. With no base: files modified against HEAD
+   * plus untracked files, because a brand-new file is a change to anyone reading. With
+   * a base ref: files differing from that ref, tracked history only.
+   */
+  changedFiles(base?: string): Promise<string[]>;
+  /**
+   * Unified diff against base (default HEAD). Covers the whole workspace unless you
+   * narrow it to one workspace-relative path.
+   */
+  diff(base?: string, path?: string): Promise<string>;
+  /** The current working-tree status, for the workspace. */
+  status(): Promise<GitStatus>;
+  /**
+   * The most recent commits, newest first. Default 20, maximum 100. Unlike the other
+   * members this reads repository-wide history, not workspace paths.
+   */
+  log(count?: number): Promise<GitCommit[]>;
+};
+
+/** The outcome of one world.run command, including nonzero exits. */
+declare interface WorldRunResult {
+  /** The process exit code. Nonzero is a normal, returned outcome — branch on it. */
+  exitCode: number;
+  /** Captured stdout (UTF-8). Capped at 256KB; over the cap the call rejects. */
+  stdout: string;
+  /** Captured stderr (UTF-8). Same cap and rejection semantics as stdout. */
+  stderr: string;
+}
+
+/**
+ * Journaled command execution — the effect primitive. Executed by the harness exactly
+ * once per call site and iteration, recorded in the journal, and replayed from the
+ * record on resume (resume is crash recovery, not re-verification).
+ *
+ * Deliberately unlike git.*: a completed process with a NONZERO exit code RESOLVES to
+ * a WorldRunResult — a failing check is the gating loop's normal case and must not
+ * travel exception control flow. The promise only rejects (catchably) when the
+ * command could not run as an observation at all: spawn failure, or timeout (default
+ * 300000ms, override per call via timeoutMs, no upper cap).
+ *
+ * cmd must be a compile-time string literal: the script's command set is shown to the
+ * user when the run is confirmed, and only those commands are executable. Fixed argv,
+ * never a shell — no pipes, no redirection, no variable expansion; compose with
+ * multiple calls and plain code. cwd is the workspace. Idiom: model generates, code
+ * gates — run the check here, parse its output with pure script logic, and hand
+ * failures to an agent to fix. A helper that needs Node builtins can be inlined as
+ * world.run("node", ["-e", code]) — the code string lives inside the script, so it is
+ * pinned by the journal key like every other argument.
+ */
+declare const world: {
+  run(cmd: string, args?: string[], opts?: { timeoutMs?: number }): Promise<WorldRunResult>;
+};
+```
+<!-- facade-dts:end -->
+
+### 16.3 Rules the compiler and the analyzer enforce
+
+- Plain TypeScript. Define result types with a plain `interface Foo { ... }` or
+  `type Foo = ...` and pass them as `ask<T>` type arguments.
+- Compiled under `strict` with `noUncheckedIndexedAccess` off: indexing an array or record
+  (`items[i]`) needs no guard. `.find()`, `.match()`, `Map.get()` and optional properties
+  still yield `T | undefined` / `null` and must be guarded before use.
+- Never use the `declare` modifier: the script is compiled inside a function body, where
+  ambient declarations are illegal. No `export` statements — the workflow's output is its
+  final `return`. No `import` statements.
+- Top-level `await` and a final `return <value>` are allowed; the returned value is exactly
+  what the completion notification carries.
+- No Node or web APIs: `process`, `fetch`, `fs` do not exist and fail typechecking.
+- `world.run` executes a real command. Its first argument must be a compile-time string
+  literal — the script's command set is shown to the user at confirmation — so interpolate
+  runtime values into the args array, never into the command name. A nonzero exit code
+  comes back as a value (`{ exitCode, stdout, stderr }`), not an exception: branch on
+  `exitCode` for gate checks. Default timeout 300s; override per call with `timeoutMs` (no
+  cap). Spawn failures and timeouts reject; stdout or stderr over 256KB rejects like any
+  other over-cap world read.
+- Phases are required (§8): cover the whole script with `phase("...")` markers, one at the
+  head of each stage. The name is a compile-time string literal and the call is a standalone
+  statement; the marker claims the rest of its enclosing block, nested blocks and inlined
+  helper calls included, so a marker inside an `if` covers that branch only. Two markers
+  with the same name are one phase, which is how a retry loop stays two nodes instead of
+  per-round sprawl. Every phase contains at least one subagent `ask` or one `world.run`;
+  plain script logic between two asks is not a stage, so do not open a phase for the setup
+  at the top or the `return` at the bottom.
+- Subagent names: the name you pass to `agent("...")` is the card the user sees, so write
+  it for the user in the session's language (§9). It is also an identity: unique within the
+  run, and the key an amended run matches its cached results by. Keep names stable across
+  revisions of the same script, and give duplicates in a loop their own computed names.
+- Artifact ids and the `report` tag are compile-time literals; one id belongs to one
+  artifact kind; at most one artifact carries `primary: true`; a preset artifact is declared
+  at the top level, not inside a loop, callback or branch (§10). Publishing rejects
+  catchably when the file is missing or too large.
+- Model-side errors never reach the script. Rate limits, concurrency limits, overload,
+  network errors, timeouts and unknown provider errors are retried by the runtime without
+  limit while it adapts the fan-out to what the provider accepts; a deterministic one
+  (expired sign-in, model not in the plan, quota cap, invalid request) stops the whole run as
+  `stopped` so the user can fix the cause and resume it. So do not write retry loops or
+  `try`/`catch` for provider errors. Reserve them for logic failures — a subagent result
+  that failed validation, a gate that did not pass, a world read over its cap, an artifact
+  publish whose source file is missing, or a `ContextLimit` (the ask was too large for the
+  model's context even after compaction: split the work or send less).
+- The final `return` is the model-facing result; artifacts are the user-facing deliverable.
+  Never put the same content in both.
+- On diagnostics, edit the file the result names and call the tool again with `path`; never
+  paste the script a second time.
+
+### 16.4 `AmendWorkflow`
+
+Revises an existing run: it starts a new run that supersedes the old one and imports its
+finished work as a cache, so only what you changed is paid for again. §13 has the cache
+rules and the repair-while-running move. It works on any run of this project — completed,
+errored, stopped or still running; a running predecessor is stopped and superseded in the
+same call, so never `TaskStop` it first and never rewrite it from scratch with
+`CreateWorkflow`. To continue a stopped run unchanged, use `ResumeWorkflowRun` instead.
+
+**Fields — every field you omit keeps the predecessor's value.**
+
+- `run_id` (required): from a `CreateWorkflow` or `AmendWorkflow` result, a notification,
+  `GetWorkflowRun` or `ListWorkflowRuns`.
+- `path` or `script`, never both. `path` is the usual form: the errored notification and
+  `GetWorkflowRun` name the run's script file — edit it in place and pass the same path
+  back, so a revision costs one `Edit` instead of a second copy of the whole script. A file
+  whose bytes you did not change is refused (`script_unchanged`) unless the call also
+  changes `max_concurrency` or `subagent_model`; nothing is stopped and nothing is created.
+  `script` carries a whole revised script inline, written against the same facade and rules;
+  it is saved to a draft file the result names, so the next revision can go back to `path`.
+  Omit both to keep the predecessor's script byte for byte and change only the settings
+  below; its finished work still replays from the cache.
+- `name`: a new display label; defaults to the predecessor's.
+- `max_concurrency`: omit to keep the predecessor's limit, pass `null` to remove it, pass a
+  number to change it (only when the user asks). A call carrying nothing but `run_id` and
+  `max_concurrency`, against a run that is still going, retunes that run in place instead of
+  starting a new one: same run, nothing stopped, nothing re-run.
+- `subagent_model`: omit to keep the predecessor's choice, pass `null` to put the subagents
+  back on the session model, pass a model id to change it (only when the user asks).
+  `ListModels` lists the ids.
+
+Changing only a setting on a running run still stops it; what it had in flight runs again in
+the new run, except that a named subagent whose unfinished ask you did not change picks that
+ask up where it left off instead of starting it over.
+
+**How the cache works.** Named subagents are matched by name across the two scripts; each
+one's asks are matched in order by byte-identical instructions. A match settles from the
+recorded result at zero tokens; a changed or added ask runs live. The cache stays open until a
+live subagent makes its first write to the workspace (or a live `world.run` executes): from
+that moment, cached world reads and cached asks whose subagent had read or run something
+would describe a workspace that no longer exists, so they run live too. Asks that only
+answered keep settling from the cache. Editing an ask's text is how you force it to run
+again; keep names stable and keep tunable constants out of ask text (§13).
+
+An inline `script` that does not compile comes back as diagnostics: fix the file the result
+names and call again with `path` — nothing was stopped and nothing was started.
+
+**Confirmation.** A run this session started (through `CreateWorkflow`, a previous
+`AmendWorkflow` or the workflows hub) is amended without a confirmation window, even while
+it is running. A run the user stopped, or a run another session started, asks the user
+first. The result names the run that was superseded (if one was stopped) and the new run's
+id. The superseded run sends no notification of its own; the new run notifies when it
+settles. Do not wait for it or poll it with `TaskOutput`.
+
+### 16.5 `SaveWorkflow`
+
+Saves a script with its metadata so it can be run again by name — through `CreateWorkflow`'s
+`saved` source, discovered with `ListSavedWorkflows`. Project definitions go in
+`.zcode/workflows/<name>.dwf.ts`, committed with the repository and visible only inside it;
+global definitions go in `~/.zcode/workflows/<name>.dwf.ts` and are available from every
+project on this machine.
+
+**When to call it.**
+
+- Never unsolicited. Saving writes a file into the user's repository; that is their
+  decision, not yours.
+- When a workflow you just built looks reusable — it would plausibly run again with
+  different inputs — suggest saving it in prose, one sentence naming what you would save and
+  why, then stop and wait. Call `SaveWorkflow` only after the user agrees, or when the user
+  asks directly ("save this workflow", "保存这个工作流"). A one-off script tailored to a
+  single question is not worth suggesting; it wastes the user's attention and clutters the
+  project.
+
+**Fields.**
+
+- `name`: a file-safe identifier (letters, digits, dot, dash and underscore). Saving over an
+  existing name replaces that workflow; the confirmation tells the user whether this is a
+  new file or an overwrite, so reuse a name to update a workflow and pick a new one to add a
+  variant.
+- `description` (required) and `whenToUse`: written for a reader who has not seen this
+  conversation. `description` shows up wherever the workflow is listed.
+- `scope` (required, no default): `project` when the script references this repository's
+  files, commands, conventions or layout; `global` when it depends on nothing in the
+  project.
+- `script` or `script_path`, never both. `script_path` saves a draft a `CreateWorkflow` or
+  `AmendWorkflow` result named without re-emitting it; a `/* zcode-workflow` block in that
+  file is dropped, because the metadata comes from this call's fields. `script` is the body
+  only — no metadata block.
+- `args`: name exactly the values that would change between runs — a PR number, a
+  directory, a depth — and no more; every declared argument is one more thing a future
+  caller has to get right. Each declaration gives a `type` (`string`, `number`, `boolean`,
+  or `json` for anything else), and optionally a `description`, `required: true` and a
+  `default`. Declared arguments are the workflow's calling convention; every future call is
+  validated against them.
+
+The saved file is valid TypeScript: a `/* zcode-workflow` block of YAML metadata, then the
+script verbatim. The script is typechecked by the same compiler as `CreateWorkflow`, before
+the user is asked; diagnostics mean nothing was written. The rules in §16.3 apply, phases
+included — future callers did not see this conversation, so the phase names are all they
+get.
+
+### 16.6 `EvalWorkflowSnippet`
+
+Compiles and runs a small snippet synchronously against the same compiler, sandbox and
+world-read execution path a real run uses, and returns the result in the tool call. Nothing
+persists: no journal rows, no background task, no run. It is the test bench for authoring
+(§6): before writing or revising a script, check a parser against real command output, see
+what a glob actually returns (workspace-relative sorted paths, cap rejections), or exercise a
+gate predicate on real repository state, instead of guessing. It is not for orchestration:
+there is no `agent()` here.
+
+- `code` or `path`, never both: the snippet inline, or a file holding it, read whole with no
+  metadata handling.
+- `timeoutMs`: the wall clock for the whole snippet in milliseconds; default 60000, at most
+  600000.
+- The snippet facade is the `args`, `log`, `files`/`git` and `world.run` parts of the block
+  in §16.2; `agent()`, `report()`, `artifact.*` and the `phase` marker do not exist here and
+  fail typechecking. The language rules are a script's: plain interfaces, top-level `await`, a
+  final `return <value>`. The returned value is serialized into the result, so return a
+  summary, not a dump; over 256KB fails the call. `log(...)` lines come back in order. A
+  snippet that contains `world.run` asks the user for confirmation before running. On
+  diagnostics nothing ran: fix the snippet and call again.

+ 801 - 0
apps/zcode-cli/packages/bundled-skills/skills/dynamic-workflows/examples.md

@@ -0,0 +1,801 @@
+# Worked dynamic-workflow examples
+
+Five complete scripts, end to end. Each is a whole arc — world read, topology, loop or
+fan-out, salvage, artifacts, return shape — so read one when you want to see how the pieces
+sit together rather than looking up a single shape (`patterns.md` is for that).
+
+Every script here is submitted as the `script` argument of the `CreateWorkflow` tool. The
+API surface they are written against is `SKILL.md` §16 (the facade block in §16.2 and the
+rules in §16.3), not the tool description.
+
+---
+
+## 1. Adversarial implement ↔ verify loop
+
+Two subagents with opposed jobs, looping until the verifier cannot break the implementation.
+The shape generalizes to anything with an author and a skeptic: code and property test, proof
+and counter-example, schema and fuzzer.
+
+<!-- compile -->
+```ts
+interface ImplUpdate {
+  /** Files this round changed. */
+  changed: string[];
+  /** How this version addresses the previous counter-example. */
+  notes: string;
+  /** Whether the author's own build and tests passed before handing off. */
+  selfCheckPassed: boolean;
+}
+
+interface Verdict {
+  /** True only when the property was actually verified, not merely left untested. */
+  verified: boolean;
+  /** Where the verification lives, when it succeeded. */
+  proofPath?: string;
+  /** Concrete inputs that break the implementation, when it failed. */
+  counterExamples?: string[];
+  /** Why. This is the input to the implementer's next round. */
+  reason: string;
+}
+
+const IMPL_PATH = "src/compress.ts";
+const TEST_PATH = "src/compress.property.test.ts";
+const PROPERTY = "decompress(compress(s)) === s for every string s";
+
+const implementer = agent("implementer", {
+  system:
+    `You implement in ${IMPL_PATH}. Run the build and \`npx vitest run\` before handing off, ` +
+    "and say in your notes exactly which commands you ran. " +
+    "Your deliverable is the file itself: describe what you changed, never paste the source back.",
+});
+
+const verifier = agent("verifier", {
+  system:
+    `You are an adversarial verifier. Read ${IMPL_PATH} and write property tests into ${TEST_PATH}. ` +
+    "If you cannot break it, report verified. If you can, give the exact failing input. " +
+    "Never claim a verification you did not actually run.",
+});
+
+const MAX_ROUNDS = 8;
+
+// What a watcher wants to know mid-run: which round, and how many attacks are still open.
+artifact.metrics("progress", {
+  title: "Verification progress",
+  metrics: [{ field: "round", label: "Round" }, { field: "open", label: "Open counter-examples" }],
+});
+
+phase("Implement the first version of the compression");
+let impl = await implementer.ask<ImplUpdate>(
+  `Implement compress and decompress in ${IMPL_PATH} so that ${PROPERTY}.`,
+);
+phase("Try to break it with property tests");
+let verdict = await verifier.ask<Verdict>(
+  `Verify or refute: ${PROPERTY}\n` +
+    `Changed: ${impl.changed.join(", ")}\nAuthor's notes: ${impl.notes}\n` +
+    `Author's self-check: ${impl.selfCheckPassed ? "passed" : "did not pass"}`,
+);
+
+let round = 1;
+while (!verdict.verified && round < MAX_ROUNDS) {
+  phase("Fix what the tests broke");
+  round = round + 1;
+  const open = verdict.counterExamples?.length ?? 0;
+  log(`round ${round}: ${open} counter-examples`);
+  report({ round, open, reason: verdict.reason, counterExamples: verdict.counterExamples ?? [] }, "progress");
+
+  impl = await implementer.ask<ImplUpdate>(
+    `Verification failed.\nReason: ${verdict.reason}\n` +
+      `Counter-examples: ${JSON.stringify(verdict.counterExamples ?? [])}\n` +
+      `Fix ${IMPL_PATH} directly; the failing tests are in ${TEST_PATH}. Re-run your own check.`,
+  );
+  phase("Re-verify the fixed implementation");
+  verdict = await verifier.ask<Verdict>(
+    `The implementation changed (${impl.notes}). Verify or refute ${PROPERTY} again.`,
+  );
+}
+
+// The verifier's word is a claim; the test file is a fact. Run it once for real before the
+// result is called verified — the verifier may have run it, but this is the run that counts.
+phase("Run the property tests for real");
+const proof = await world.run("npx", ["vitest", "run", TEST_PATH], { timeoutMs: 600_000 });
+const verified = verdict.verified && proof.exitCode === 0;
+if (verdict.verified && !verified) log(`the verifier said verified but vitest exited ${proof.exitCode}`);
+
+await artifact.markdown(
+  "report",
+  [
+    `# ${PROPERTY}`,
+    "",
+    verified
+      ? `Verified after ${round} round(s); the property tests live in ${verdict.proofPath ?? TEST_PATH} and pass under vitest.`
+      : verdict.verified
+        ? `The verifier reported verified, but \`npx vitest run ${TEST_PATH}\` exited ${proof.exitCode}; treat the result as unverified.`
+        : `Still refuted after ${round} rounds: ${verdict.reason}`,
+    "",
+    `Implementation: ${IMPL_PATH}. Last change: ${impl.notes}`,
+  ].join("\n"),
+  {
+    title: "Verification report",
+    description: "Whether the property holds, how many rounds it took, and where the tests live.",
+    primary: true,
+  },
+);
+
+return {
+  conclusion: verified
+    ? `${PROPERTY} holds; the verifier could not break the implementation after ${round} round(s), and the property tests pass under vitest.`
+    : verdict.verified
+      ? `${PROPERTY} is not verified: the verifier reported success but the property tests exit ${proof.exitCode} when run for real.`
+      : `${PROPERTY} is still refuted after ${round} rounds: ${verdict.reason}`,
+  verified,
+  rounds: round,
+  implPath: IMPL_PATH,
+  proofPath: verdict.proofPath,
+  finalVerdict: verdict,
+  checks: [`npx vitest run ${TEST_PATH} exited ${proof.exitCode}`],
+  notCovered: ["inputs the property tests did not generate", "performance"],
+};
+```
+
+**Why it is written this way.** Both subagents live outside the loop, so each keeps everything
+it learned: the implementer remembers the approaches it already tried, and the verifier
+remembers which attacks already worked. Both genuinely edit and run files.
+
+The subagents exchange **paths and descriptions, never file contents**; each reads the other's
+work with its own tools. Each round is reported as it happens, so a run that dies on round
+six still shows five rounds of counter-examples. And the return value says `verified` and
+`rounds`, so a caller can tell convergence from exhaustion — and opens with a `conclusion`
+and closes with `notCovered`, because the return value is what the main agent retells.
+
+`verified` is not the verifier's word. The verifier is a subagent, and a subagent's "I ran
+the tests" is a claim; the `world.run` at the end runs the test file for real and its exit
+code is what the result rests on. The implementer's persona names the exact commands it
+must run for the same reason — "run the tests" lets a subagent pick the fastest thing that
+turns green.
+
+Two artifacts, each for a different moment. The metrics tile is for whoever is watching the
+loop: round and open counter-examples, fed by the `report` call the script was already
+making. The markdown report is for afterwards — the same facts as the return, in the long
+form the user keeps. The tests themselves are not published: they live in the repository,
+and a card for a file the user would open in the editor anyway says nothing new.
+
+---
+
+## 2. Flaky test triage
+
+Scan, then plan a fix under critique, then judge each finding independently. Three
+topologies in one script, each chosen for a different reason.
+
+<!-- compile -->
+```ts
+interface Finding {
+  /** Test identifier as the runner reports it. */
+  testId: string;
+  /** Workspace-relative path of the test file. */
+  file: string;
+  /** What makes it flaky. */
+  kind: "timing" | "ordering" | "external";
+  /** 0-1. How confident the scan is that this is really flaky. */
+  confidence: number;
+}
+interface Scan {
+  findings: Finding[];
+}
+interface Plan {
+  /** One entry per test, in the order the fixes should be applied. */
+  steps: { testId: string; change: string }[];
+  /** Anything the plan deliberately does not address. */
+  outOfScope: string[];
+}
+interface Review {
+  approved: boolean;
+  /** What is wrong with the plan. Empty when approved. */
+  feedback: string;
+}
+interface Judgement {
+  /** False when the finding is a false positive. */
+  real: boolean;
+  reason: string;
+}
+interface Confirmation {
+  /** True only when you reproduced the flakiness yourself (re-ran the test, read the timing dependence). */
+  reproduced: boolean;
+  /** What you did to check, one sentence. */
+  note: string;
+}
+interface ReportedFinding extends Finding {
+  /** "verified" when the confirmer reproduced it; "unconfirmed" when it could not. */
+  status: "verified" | "unconfirmed";
+}
+interface FlakyReport {
+  /** Two or three sentences answering what the user asked for. */
+  conclusion: string;
+  findings: ReportedFinding[];
+  /** The approved plan, when the loop converged. */
+  plan?: Plan;
+  converged: boolean;
+  rounds: number;
+  /** What the run checked and how. */
+  verified: string[];
+  /** What the run did not look at or could not check, and why. */
+  notCovered: string[];
+}
+
+// Every candidate is a card; it moves column as the run makes up its mind about it.
+artifact.board("candidates", {
+  title: "Flaky test candidates",
+  key: "testId",
+  status: "status",
+  columns: ["candidate", "false positive", "verified", "unconfirmed"],
+  detail: [{ field: "file" }, { field: "kind" }],
+});
+
+phase("Scan the repository for flaky tests");
+const scan = await agent("scanner", "You identify flaky tests from test code and CI history.")
+  .ask<Scan>("Find flaky tests in this repository. Prefer precision over recall.");
+
+log(`${scan.findings.length} candidate flaky tests`);
+for (const finding of scan.findings) report({ ...finding, status: "candidate" }, "candidates");
+if (scan.findings.length === 0) {
+  const empty: FlakyReport = {
+    conclusion: "No flaky tests found.",
+    findings: [],
+    converged: true,
+    rounds: 0,
+    verified: ["scanned test code and CI history"],
+    notCovered: ["tests that only flake under load the scan could not observe"],
+  };
+  return empty;
+}
+
+// Independent judges: one fresh context per finding, because a judge that has seen the
+// other findings starts grading on a curve instead of on the merits. Each carries the
+// test id in its name — one subagent per finding means one name per finding.
+//
+// A judge's verdict is a judgement, not a reproduction, so each survivor goes on to a fresh
+// confirmer that re-runs the test and reads the timing dependence itself; the ask forbids
+// edits. The confirmer is chained right after its own judge, inside the same callback: a
+// candidate is confirmed the moment its judge rules, not after every judge has. What the
+// confirmer cannot reproduce is kept and labelled, not dropped.
+phase("Judge each candidate and confirm the real ones as they are judged");
+const outcomes = await Promise.all(
+  scan.findings.map(async (finding): Promise<ReportedFinding | undefined> => {
+    const judgement = await agent(`judge-${finding.testId}`).ask<Judgement>(
+      `Is this really flaky, or a false positive?\n${JSON.stringify(finding)}`,
+    );
+    if (!judgement.real) {
+      report({ ...finding, status: "false positive" }, "candidates");
+      return undefined;
+    }
+    const check = await agent(`confirmer-${finding.testId}`).ask<Confirmation>(
+      `Reproduce this flakiness from the evidence alone: run the test, read the timing dependence. Do not edit any file.\n${JSON.stringify(finding)}`,
+    );
+    const reported: ReportedFinding = {
+      ...finding,
+      status: check.reproduced ? "verified" : "unconfirmed",
+    };
+    report(reported, "candidates");
+    return reported;
+  }),
+);
+const real = outcomes.filter((o): o is ReportedFinding => o !== undefined);
+log(`${real.length} of ${scan.findings.length} survived judging`);
+if (real.length === 0) {
+  const empty: FlakyReport = {
+    conclusion: "Every candidate was judged a false positive.",
+    findings: [],
+    converged: true,
+    rounds: 0,
+    verified: ["scanned test code and CI history", "judged each candidate independently"],
+    notCovered: ["tests that only flake under load the scan could not observe"],
+  };
+  return empty;
+}
+
+// Planner and reviewer: created once, reused every round, so each accumulates context.
+const planner = agent("planner", "You write minimal, concrete fixes for flaky tests.");
+const reviewer = agent("reviewer", "You find the flaw in a fix plan. Approve only when you cannot find one. You never edit files.");
+
+let feedback = "none";
+let approved: Plan | undefined;
+let rounds = 0;
+for (let round = 0; round < 5; round++) {
+  rounds = round + 1;
+  phase("Draft a fix plan");
+  const plan = await planner.ask<Plan>(
+    `Plan fixes for these flaky tests:\n${JSON.stringify(real)}\nPrevious critique: ${feedback}`,
+  );
+  phase("Critique the plan");
+  const review = await reviewer.ask<Review>(`Critique this plan:\n${JSON.stringify(plan)}`);
+  if (review.approved) {
+    approved = plan;
+    break;
+  }
+  log(`plan rejected in round ${rounds}: ${review.feedback}`);
+  feedback = review.feedback;
+}
+
+const verified = ["scanned test code and CI history", "each survivor reproduced by an independent confirmer"];
+const done: FlakyReport = approved
+  ? {
+      conclusion: `${real.length} flaky tests confirmed; a fix plan was approved after ${rounds} round(s).`,
+      findings: real,
+      plan: approved,
+      converged: true,
+      rounds,
+      verified,
+      notCovered: approved.outOfScope,
+    }
+  : {
+      conclusion: `${real.length} flaky tests confirmed, but no fix plan survived review in ${rounds} rounds; last critique: ${feedback}`,
+      findings: real,
+      converged: false,
+      rounds,
+      verified,
+      notCovered: ["a fix plan — none was approved"],
+    };
+
+await artifact.markdown(
+  "report",
+  [
+    `# ${done.conclusion}`,
+    "",
+    ...real.map((f) => `- ${f.testId} (${f.file}, ${f.kind}): ${f.status}`),
+    "",
+    approved
+      ? approved.steps.map((step) => `1. ${step.testId}: ${step.change}`).join("\n")
+      : `No plan was approved. Last critique: ${feedback}`,
+  ].join("\n"),
+  { title: "Flaky test report" },
+);
+return done;
+```
+
+**Why it is written this way.** The judges are fresh per finding and the planner/reviewer pair
+is hoisted — opposite choices, both deliberate. Judging wants independence, so sharing a
+context would actively corrupt it; planning wants memory, so a fresh planner each round would
+waste it. The confirmers are a third kind: fresh and per finding, told not to edit, because a
+judge's verdict is an opinion about a description, and only re-running the test turns it into
+a fact. What they cannot reproduce stays in the report as `unconfirmed`. Each confirmer
+follows its own judge inside one callback, so the fan-out has one join instead of two:
+confirming candidate three never waits for candidate forty's judge.
+
+The two early returns matter. A scan that finds nothing and a judging pass that rejects
+everything are both *successes* with an empty result, not failures — and each avoids paying
+for a planning loop over an empty list. Both still return the full report shape, with a
+`conclusion` that says which of the two happened. Findings are reported before planning
+starts, so even a planning loop that never converges hands back the confirmed findings.
+
+The board is the watcher's view of a fan-out: every candidate appears the moment the scan
+returns and moves column as a judge or a confirmer rules on it, because a later item with the
+same `testId` replaces the card. The report is published once, after the planning loop, which
+is why the loop `break`s to a single return instead of returning from inside. The two early
+returns publish nothing: "No flaky tests found" is a one-line answer, and a page that
+restates it would be noise.
+
+---
+
+## 3. Call-site migration
+
+Discover, transform in parallel, then verify. The transforming subagents write files, so this is
+the one shape where isolation and verification really matter.
+
+<!-- compile -->
+```ts
+interface Migration {
+  /** Whether this file needed changing at all. */
+  changed: boolean;
+  /** What was rewritten, one line. */
+  summary: string;
+  /** Anything the migrator could not do safely and left alone. */
+  skipped: string[];
+}
+interface Check {
+  /** True when the file compiles and its tests pass after the change. */
+  clean: boolean;
+  /** What broke, when it did not. */
+  problem: string;
+}
+
+const OLD_API = "getUserSync";
+const NEW_API = "getUser";
+
+artifact.table("migration", {
+  title: "Migration by file",
+  key: "path",
+  columns: [
+    { field: "path", label: "File" },
+    { field: "summary", label: "Change" },
+    { field: "clean", label: "Verified" },
+  ],
+});
+
+phase("Find every call site of the old API");
+const hits = await files.grep(`\\b${OLD_API}\\b`, "src/**/*.ts");
+const paths = [...new Set(hits.map((h) => h.path))];
+log(`${OLD_API} appears in ${paths.length} files (${hits.length} call sites)`);
+if (paths.length === 0) return { migrated: [], failed: [], note: "nothing to migrate" };
+
+// One persona, reused by every migrator subagent. Personas are values you can share; subagents
+// and their names are not — each file gets its own of both.
+const MIGRATOR = {
+  system:
+    `You migrate call sites from ${OLD_API} to the async ${NEW_API}, adding await and making ` +
+    "the enclosing function async where needed. Change nothing else. If a call site cannot be " +
+    "migrated safely, leave it and say why.",
+};
+
+// One migrator per file: the edits are disjoint, so they can run at once, and a fresh
+// context per file keeps one file's oddities from leaking into another's rewrite.
+phase("Migrate each file and verify the result");
+const results = await Promise.all(
+  paths.map(async (path) => {
+    try {
+      const migration = await agent(`migrator-${path}`, MIGRATOR).ask<Migration>(
+        `Migrate every ${OLD_API} call in ${path} to ${NEW_API}.`,
+      );
+      if (!migration.changed) return { path, migration, check: undefined };
+
+      // Verify with a separate context: a subagent asked to check its own work grades
+      // generously. It compiles and runs tests; the ask forbids edits.
+      const check = await agent(`checker-${path}`).ask<Check>(
+        `Does ${path} still compile and pass its tests after the ${NEW_API} migration? ` +
+          `Run the checks; do not edit any file. The change was: ${migration.summary}`,
+      );
+      report({ path, summary: migration.summary, clean: check.clean }, "migration");
+      return { path, migration, check };
+    } catch (error) {
+      log(`skipped ${path}: ${String(error)}`);
+      report({ path, summary: `skipped: ${String(error)}`, clean: false }, "migration");
+      return { path, migration: undefined, check: undefined, error: String(error) };
+    }
+  }),
+);
+
+const migrated = results.filter((r) => r.check?.clean === true).map((r) => r.path);
+const failed = results.filter((r) => r.check?.clean === false || r.error !== undefined);
+
+// Every file passed its own check; now the tree as a whole, once. A per-file checker cannot
+// see the caller in another file that a migrated signature broke — the full suite can, and
+// it is the check the user will run themselves.
+phase("Run the whole test suite once over the migrated tree");
+const suite = await world.run("npm", ["test"], { timeoutMs: 1_800_000 });
+const suiteClean = suite.exitCode === 0;
+if (!suiteClean) log(`npm test failed after the migration:\n${suite.stderr.slice(-2000)}`);
+
+await artifact.markdown(
+  "report",
+  [
+    suiteClean
+      ? `# ${OLD_API} → ${NEW_API}: ${migrated.length} of ${paths.length} files migrated and verified`
+      : `# ${OLD_API} → ${NEW_API}: ${migrated.length} of ${paths.length} files migrated, but the full suite fails`,
+    "",
+    ...migrated.map((p) => `- ${p}: migrated; compiled and tests passed`),
+    ...failed.map((r) => `- ${r.path}: failed — ${r.check?.problem ?? r.error}`),
+    "",
+    `Full suite (\`npm test\`): exit ${suite.exitCode}`,
+  ].join("\n"),
+  { title: "Migration report" },
+);
+
+return {
+  conclusion: suiteClean
+    ? `${migrated.length} of ${paths.length} files migrated from ${OLD_API} to ${NEW_API} and verified; ${failed.length} failed; the full suite passes.`
+    : `${migrated.length} of ${paths.length} files migrated from ${OLD_API} to ${NEW_API}, but the full suite fails after the migration, so the result is not verified: ${suite.stderr.slice(-300)}`,
+  migrated,
+  failed: failed.map((r) => ({ path: r.path, problem: r.check?.problem ?? r.error })),
+  skipped: results.flatMap((r) => r.migration?.skipped ?? []),
+  verified: [
+    ...migrated.map((p) => `${p}: compiled and tests passed, checked by a separate subagent`),
+    `npm test over the whole tree exited ${suite.exitCode}`,
+  ],
+  notCovered: ["call sites outside src/**/*.ts", "callers in other packages that import the migrated functions"],
+};
+```
+
+**Why it is written this way.** `files.grep` narrows before the fan-out: globbing `src/**/*.ts`
+and asking every file whether it uses the old API would spend a session per file to learn
+what one search already knew. Because `grep` rejects instead of truncating when it overruns
+its cap, the path list is either complete or absent — never quietly partial, which for a
+migration is the difference between finished and silently half-finished.
+
+Both subagents in the fan-out are named per path. That is not decoration: a run rejects two
+subagents sharing a name, so `agent("migrator")` inside the `map` would not survive its second
+file — and the per-path names are also what a corrected re-run (`AmendWorkflow`) matches its
+imported cache against, so re-running this script after fixing one detail does not re-migrate
+the files that already came out clean.
+
+The checker is a **separate subagent** from the migrator, which is what makes the check
+meaningful: a subagent asked to grade its own migration grades generously. It builds and
+tests, and the ask is what forbids it to patch what it finds broken. The checker also runs
+inside the same callback as its migrator — a per-item pipeline with one join — so the first
+file is verified while the fortieth is still being rewritten, instead of every checker
+waiting behind a `Promise.all` for the slowest migration. The
+`try`/`catch` is per file, so one unmigratable file costs one file rather than the run. And
+the return value separates `migrated` from `failed` from `skipped`, because "we changed 40
+files" is not an outcome anyone can act on.
+
+The fan-out verifies each file; the `world.run` after it verifies the tree. Those are
+different checks: forty files that each pass their own tests can still not compile together,
+and the caller in a file nobody migrated is exactly what a per-file checker never opens. The
+whole-suite run is the check the user would run before merging, so it runs here, once, with
+the timeout a real suite needs — and when it fails, `conclusion` says the result is
+unverified rather than letting the forty green rows speak for the tree.
+
+The table is the fan-out seen live: one row per file, keyed by path, filled in as each
+checker answers, with the skipped files landing in it too. The report at the end is the
+same list in prose for the user to keep. The migrated files themselves are not published —
+they are the repository, and the user reads them there. The early return for "nothing to
+migrate" publishes nothing: a one-line answer needs no page.
+
+---
+
+## 4. Prover loop gated by the real checker
+
+One subagent doing open-ended repair, and a gate that cannot be talked past: `world.run`
+executes the actual proof checker, and the loop advances on its exit code, not on anyone's
+claim. Compare example 1, where the skeptic is another subagent — right when breaking the work
+takes creativity. When a command can render the verdict, the command should.
+
+<!-- compile -->
+```ts
+interface FixNotes {
+  /** What changed this round, one line. */
+  summary: string;
+}
+
+const TARGET = "Proofs/Main.lean";
+const MAX_ROUNDS = 10;
+
+const prover = agent("prover", {
+  system:
+    `You write and repair Lean proofs in ${TARGET}. Fix exactly what the checker reports; ` +
+    "never delete or weaken a theorem to silence an error.",
+});
+
+phase("Write the first proof attempt");
+let notes = await prover.ask<FixNotes>(`Prove the open theorem in ${TARGET}.`);
+
+const attempts: string[] = [];
+let clean = false;
+let rounds = 0;
+for (let round = 1; round <= MAX_ROUNDS; round++) {
+  rounds = round;
+  attempts.push(notes.summary);
+  phase("Check the file with the fast checker");
+  // The fast tier: one file, seconds. It exits 0 on a proof that still says `sorry` and
+  // only warns on stderr, so the exit code alone is not the verdict.
+  const check = await world.run("lake", ["env", "lean", TARGET], { timeoutMs: 600_000 });
+  clean = check.exitCode === 0 && !check.stderr.includes("sorry");
+  if (clean) {
+    report({ round, summary: notes.summary, checkerClean: true });
+    break;
+  }
+
+  log(`round ${round}: checker rejected`);
+  report({ round, summary: notes.summary, checkerClean: false });
+  phase("Repair what the checker rejected");
+  notes = await prover.ask<FixNotes>(
+    `The Lean checker rejected the file. Its output:\n${check.stderr}\nRepair ${TARGET}.`,
+  );
+}
+
+// The strong tier, once: the whole project builds with the new proof in it. That is what
+// the request was about, and it runs even though the fast tier already said yes.
+let proved = false;
+if (clean) {
+  phase("Build the whole project with the new proof");
+  const build = await world.run("lake", ["build"], { timeoutMs: 1_800_000 });
+  proved = build.exitCode === 0;
+  if (!proved) log(`lake build rejected what the fast checker accepted:\n${build.stderr}`);
+}
+
+await artifact.markdown(
+  "report",
+  [
+    proved
+      ? `# ${TARGET}: proved in round ${rounds}`
+      : `# ${TARGET}: not proved after ${MAX_ROUNDS} rounds`,
+    "",
+    ...attempts.map((summary, index) => `${index + 1}. ${summary}`),
+  ].join("\n"),
+  { title: "Proof report" },
+);
+
+return proved
+  ? {
+      conclusion: `The open theorem in ${TARGET} is proved; the file checked clean in round ${rounds} and the whole project builds.`,
+      proved: true,
+      rounds,
+      lastChange: notes.summary,
+      verified: [`lake env lean ${TARGET} exited 0 with no sorry warning`, "lake build exited 0"],
+      notCovered: [],
+    }
+  : clean
+    ? {
+        conclusion: `Not proved: ${TARGET} checks clean on its own, but lake build fails with the new proof in the project.`,
+        proved: false,
+        rounds,
+        lastChange: notes.summary,
+        verified: [`lake env lean ${TARGET} exited 0 with no sorry warning`, "lake build exited nonzero"],
+        notCovered: ["why the whole-project build disagrees with the single-file check"],
+      }
+    : {
+        conclusion: `Not proved: the Lean checker still rejects ${TARGET} after ${MAX_ROUNDS} rounds.`,
+        proved: false,
+        rounds,
+        lastChange: notes.summary,
+        verified: [`lake env lean ${TARGET} run ${MAX_ROUNDS} times, none clean`],
+        notCovered: ["approaches the prover did not try", "lake build — never reached"],
+      };
+```
+
+**Why it is written this way.** The prover is created once and keeps its context, so round
+seven remembers what rounds one through six already tried. The checker is not a subagent at
+all: `world.run` runs the real command, a nonzero exit comes back as a **value**, and the
+loop's normal case is reading `exitCode` and handing `stderr` to the prover as the next
+round's instructions — no `catch` anywhere, because rejections are reserved for the world
+failing to answer (spawn failure, timeout, over-cap output).
+
+There are two checks, and they are not interchangeable. `lake env lean` on one file is the
+fast tier: it drives the rounds because it answers in seconds, and it reads stderr as well
+as the exit code because a proof that still says `sorry` exits 0 with a warning. `lake
+build` over the whole project is the strong tier — the check the request is really about —
+and it runs once at the end whether or not the fast tier already passed. A loop gated on
+the fast tier alone would return "proved" for a file that still contains `sorry`, and never
+learn that the new proof breaks a module that imports it. Which two commands play these
+roles is a fact about the repository, read from its README or build files before the script
+is written, not a habit carried in from the last project.
+
+The command name is a literal and the varying part — the target path — rides in the args
+array; that is the rule, and it is also what the user sees and approves at confirmation.
+The long `timeoutMs` is deliberate: proof checking is allowed to be slow, and the per-call
+override exists precisely for real build-sized checks. Every round is reported as it lands,
+so a run that dies on round eight still shows seven rounds of attempts. Before wiring a
+different checker command, test what its stderr actually looks like with a one-line
+`EvalWorkflowSnippet` call — the parse you write against a guess is the parse that breaks.
+
+One artifact, deliberately. The report lists every attempt, which is more than the
+`conclusion` can say, so it earns its page. There is no dashboard: the only state a watcher
+could follow is the round number and whether the checker passed, and the phase timeline
+lighting up "Repair what the checker rejected" again already shows exactly that. A metrics
+tile would repeat it, and the proof file is the repository's to show, not a card's.
+
+## 5. Changed-file review with confirmation as reviews land
+
+Review every changed file, triage its findings on one scale, confirm each kept finding
+independently, and hand back a report. Everything a file needs happens as soon as its own
+review lands; the only join is the cross-file deduplication that needs every finding.
+
+<!-- compile -->
+```ts
+interface Finding {
+  /** Workspace-relative path, with a line when it applies: "src/a.ts:42". */
+  where: string;
+  /** One sentence: what is wrong. */
+  what: string;
+  /** What showed it: the lines read, or the command and the output that proved it. */
+  evidence: string;
+  /** How much it matters. Reserve "high" for data loss, a crash, or a wrong result. */
+  severity: "low" | "medium" | "high";
+}
+interface Review {
+  findings: Finding[];
+}
+interface Keep {
+  /** True when this finding is worth putting in front of a human. */
+  keep: boolean;
+}
+interface Confirmation {
+  /** True only when you reproduced the problem yourself from the evidence. */
+  reproduced: boolean;
+  /** What you did to check, one sentence. */
+  note: string;
+}
+interface ReportedFinding extends Finding {
+  /** "verified" when the confirmer reproduced it; "unconfirmed" when it could not. */
+  status: "verified" | "unconfirmed";
+}
+interface Digest {
+  /** The confirmed findings with duplicates across files merged, one line each. */
+  lines: string[];
+  /** Two or three sentences a reader can act on. */
+  summary: string;
+}
+interface WorkflowReport {
+  /** Two or three sentences answering what the user asked for. */
+  conclusion: string;
+  findings: ReportedFinding[];
+  /** What the run checked and how. */
+  verified: string[];
+  /** What the run did not look at or could not check, and why. */
+  notCovered: string[];
+}
+
+phase("Review each changed file and confirm its findings as they land");
+let paths: string[];
+try {
+  paths = await git.changedFiles("origin/main");
+} catch {
+  paths = await files.glob("src/**/*.ts");
+}
+log(`reviewing ${paths.length} changed files`);
+
+// One triage subagent for all findings: severity only means anything if it is judged on a
+// consistent scale. It is a queue, not a barrier — asks on it run FIFO, so a finding reaches
+// it the moment its file's review lands, whichever file that is.
+const triage = agent("triage", "You decide which review findings deserve a human's attention. Be strict.");
+
+// One reviewer per file, fresh each: the files are unrelated, so nothing is gained by
+// sharing a context and everything is gained by running them at once. Triage and
+// confirmation live inside the same callback, so no file waits for the slowest review
+// before its findings move on; the outer `Promise.all` is the only join the report waits on.
+const perFile = await Promise.all(
+  paths.map(async (p) => {
+    const review = await agent(`reviewer-${p}`).ask<Review>(`Review ${p} for correctness bugs.`);
+
+    const kept: Finding[] = [];
+    for (const finding of review.findings) {
+      const verdict = await triage.ask<Keep>(`Worth reporting? ${JSON.stringify(finding)}`);
+      if (verdict.keep) kept.push(finding);
+    }
+
+    // A separate confirmer per kept finding, blind to the reviewer that raised it: it reads
+    // the code, runs a check if one decides it, and is told not to fix anything. The name
+    // carries the path and the index, because every subagent name in a run must be unique.
+    return Promise.all(
+      kept.map(async (finding, index) => {
+        const check = await agent(`confirmer-${p}-${index}`).ask<Confirmation>(
+          `Reproduce this finding from its evidence alone: read the code, run a check if one exists. Do not edit any file.\n${JSON.stringify(finding)}`,
+        );
+        const reported: ReportedFinding = {
+          ...finding,
+          status: check.reproduced ? "verified" : "unconfirmed",
+        };
+        report(reported); // published now, with its status, so it survives a later failure
+        return reported;
+      }),
+    );
+  }),
+);
+const confirmed = perFile.flat();
+log(`${confirmed.length} findings confirmed or labelled`);
+
+// The one stage that genuinely needs every finding: two reviewers can flag the same root
+// cause from two files, and only a reader of the whole list can merge them.
+phase("Merge duplicate findings across files and write them up");
+const digest = await agent("editor", "You merge review findings that share a root cause and write them up for the engineer who fixes them.")
+  .ask<Digest>(`Merge duplicates and write these up:\n${JSON.stringify(confirmed)}`);
+
+const verifiedCount = confirmed.filter((f) => f.status === "verified").length;
+await artifact.markdown(
+  "report",
+  [
+    `# Review of ${paths.length} changed files: ${confirmed.length} findings, ${verifiedCount} reproduced`,
+    "",
+    digest.summary,
+    "",
+    ...digest.lines.map((line) => `- ${line}`),
+    "",
+    "## Every finding",
+    ...confirmed.map((f) => `- **${f.where}** (${f.severity}, ${f.status}): ${f.what}\n  ${f.evidence}`),
+  ].join("\n"),
+  { title: "Review report" },
+);
+const result: WorkflowReport = {
+  conclusion: digest.summary,
+  findings: confirmed,
+  verified: paths.map((p) => `reviewed ${p}; every kept finding re-checked by a separate subagent`),
+  notCovered: ["files outside the change set", "runtime behaviour no existing test exercises"],
+};
+return result;
+```
+
+Three shapes in one script, each chosen for a reason. The reviewers are fresh and parallel
+because the files are unrelated. The triage subagent is shared because severity must mean the
+same thing twice — and sharing costs nothing here, because its FIFO queue is fed as reviews
+land rather than after all of them. The confirmers are fresh, per finding and blind to the
+reviewer, and they start the moment their file's triage is done: with twelve files and one
+slow reviewer, eleven files' findings are confirmed and reported while it is still reading.
+Nothing gets a second reader on top: each finding was confirmed, and the editor's job is
+merging and writing up, not re-checking.

+ 460 - 0
apps/zcode-cli/packages/bundled-skills/skills/dynamic-workflows/patterns.md

@@ -0,0 +1,460 @@
+# Dynamic workflow patterns
+
+A catalogue of orchestration shapes. Each entry states when the shape is right, then shows
+it written correctly. Interfaces are elided where they are obvious — your script must
+define every type it names.
+
+The snippets here are **fragments, not runnable scripts**: they name types and subagents that
+the surrounding prose leaves to you. Complete scripts live in `examples.md`.
+
+For the API surface itself, read the `CreateWorkflow` tool description. For the reasoning
+behind these choices, read `SKILL.md`.
+
+---
+
+## 1. Fan-out / fan-in over a glob
+
+**When:** the same independent question about every file in a set, and you want them
+answered at once.
+
+```ts
+phase("Find the files to audit");
+const paths = await files.glob("src/**/*.ts");
+log(`fanning out over ${paths.length} files`);
+
+phase("Security-audit each file independently");
+const verdicts = await Promise.all(
+  paths.map((p) =>
+    agent(`auditor-${p}`).ask<Verdict>(`Security-review ${p}. Report only real issues.`),
+  ),
+);
+
+phase("Report the files that failed");
+return verdicts.filter((v) => !v.approved).map((v) => ({ path: v.path, reason: v.reason }));
+```
+
+A fresh subagent per path is the point: the questions are unrelated, so there is nothing to
+share and everything to parallelize. Do not hoist `agent(...)` above the `map`.
+
+The name carries the path because subagent names must be unique within a run: `agent("auditor")`
+inside the `map` would create one subagent per file all claiming the same name, which is rejected
+at compile time. `` `auditor-${p}` `` is also what lets a revised re-run (`AmendWorkflow`) keep
+the verdicts for files whose question did not change. Anonymous — `agent()` — is legal too,
+and starts every file with an empty context.
+
+**Narrow before you fan out.** A glob over a large repository is a large fan-out. If only
+some files can possibly matter, find them first:
+
+```ts
+const hits = await files.grep("dangerouslySetInnerHTML", "src/**/*.tsx");
+const paths = [...new Set(hits.map((h) => h.path))];
+```
+
+`files.grep` rejects rather than truncating when it overruns its cap, so a pattern that is
+too broad fails loudly instead of handing you a partial file list to fan out over.
+
+---
+
+## 2. Changed-file review sweep
+
+**When:** reviewing work in progress rather than the whole tree.
+
+```ts
+phase("Find the work in progress");
+let paths: string[];
+try {
+  paths = await git.changedFiles("origin/main");
+} catch {
+  paths = await files.glob("src/**/*.ts");
+}
+
+phase("Review each changed file for bugs");
+const reviews = await Promise.all(
+  paths.map((p) => agent(`reviewer-${p}`).ask<Review>(`Review ${p} for correctness bugs.`)),
+);
+```
+
+Every `git` call rejects outside a repository or with no `git` available, so the `try`/`catch`
+with a `files.glob` fallback is the idiom, not defensive padding.
+
+When the reviewer needs the change rather than the file, hand it the diff — but per path, so
+no single prompt carries the whole changeset:
+
+```ts
+const perFile = await Promise.all(
+  paths.map(async (p) => {
+    const patch = await git.diff("origin/main", p);
+    return agent(`reviewer-${p}`).ask<Review>(`Review this change to ${p}:\n\n${patch}`);
+  }),
+);
+```
+
+`git.diff` is capped and rejects rather than truncating, so narrow it to a path when the
+whole-workspace diff would be large.
+
+Then confirm before you report — per file, as each review lands, not after all of them. The
+reviewer that raised a finding does not get to confirm it — a subagent asked to check its own
+work grades generously — so each finding goes to a fresh confirmer that reproduces it from the
+evidence alone and is told not to fix anything. Chaining the confirmers inside the same
+callback means the slowest reviewer holds up only its own file:
+
+```ts
+phase("Review each changed file and confirm its findings as they land");
+const confirmed = (
+  await Promise.all(
+    paths.map(async (p) => {
+      const review = await agent(`reviewer-${p}`).ask<Review>(`Review ${p} for correctness bugs.`);
+      return Promise.all(
+        review.findings.map(async (finding, index) => {
+          const check = await agent(`confirmer-${p}-${index}`).ask<Confirmation>(
+            `Reproduce this finding from its evidence alone. Do not edit any file.\n${JSON.stringify(finding)}`,
+          );
+          const reported = { ...finding, status: check.reproduced ? "verified" : "unconfirmed" };
+          report(reported);
+          return reported;
+        }),
+      );
+    }),
+  )
+).flat();
+```
+
+What fails confirmation is kept and labelled, not dropped. The review fan-out above and this
+one are the same shape written twice for exposition; in a real script write only this one.
+
+---
+
+## 3. Planner ↔ reviewer loop
+
+**When:** the first attempt at something is rarely right, and a critic can say why.
+
+```ts
+const planner = agent("planner", "You write concrete, minimal implementation plans.");
+const reviewer = agent("reviewer", "You find the flaw in a plan. Approve only when you cannot. You never edit files.");
+
+let feedback = "none";
+for (let round = 0; round < 5; round++) {
+  phase("Draft a plan for the change");
+  const plan = await planner.ask<Plan>(`Plan the change. Previous critique: ${feedback}`);
+  phase("Critique the plan until it holds");
+  const review = await reviewer.ask<Review>(`Critique this plan:\n${JSON.stringify(plan)}`);
+  if (review.approved) return plan;
+  log(`round ${round + 1} rejected: ${review.feedback}`);
+  feedback = review.feedback;
+}
+```
+
+Both subagents are created **once, outside the loop**. That is what makes the loop cheap: each
+keeps its accumulated context across rounds, so the planner remembers what it already tried
+and the reviewer remembers what it already objected to. Creating them inside the loop throws
+that away every round and pays full price for it.
+
+The reviewer's persona says it never edits files: that is what keeps it critiquing the plan
+instead of quietly "fixing" it. When critiquing the plan is reading a string, it simply never
+opens a file; when the plan is about code, tell it to read the code — a reviewer that has not
+opened the files can only judge whether the plan is coherent, not whether it is right.
+
+By the last round the persistent reviewer is anchored on its own earlier objections. Put the
+final plan in front of eyes that have seen nothing else, and ask for failures rather than
+approval:
+
+```ts
+phase("Independent review of the final plan");
+const second = await agent("independent-reviewer", "You review plans and never edit files.").ask<Review>(
+  `You have not seen this plan before. Read it against the codebase. What would break it, and what is missing?
+${JSON.stringify(plan)}`,
+);
+if (!second.approved) feedback = second.feedback;
+```
+
+---
+
+## 4. Judge panel: independent, or calibrated
+
+**When:** a finding needs a second opinion. Two shapes, and the difference matters.
+
+**Independent** — N fresh contexts, each blind to the others. Use for a majority vote,
+where correlated judges would defeat the purpose:
+
+```ts
+phase("Judge the finding from three angles");
+const votes = await Promise.all(
+  ["correctness", "security", "does-it-reproduce"].map((lens) =>
+    agent(`judge-${lens}`)
+      .ask<Verdict>(`Judge this finding through the ${lens} lens. Try to refute it:\n${claim}`),
+  ),
+);
+const survives = votes.filter((v) => !v.refuted).length >= 2;
+```
+
+Giving each judge a distinct lens beats three identical refuters: diversity catches failure
+modes that redundancy cannot.
+
+**Calibrated** — one context that sees every item, so its verdicts are consistent with each
+other. Use for ranking and severity, where "high" has to mean the same thing twice:
+
+```ts
+phase("Rank every finding on one scale");
+const triage = agent("triage", "You rank findings on one consistent scale across a whole batch.");
+
+const ranked: Ranked[] = [];
+for (const finding of findings) {
+  ranked.push(await triage.ask<Ranked>(`Rank: ${JSON.stringify(finding)}`));
+}
+```
+
+The `for`/`await` is deliberate here — asks on one subagent queue FIFO anyway, so writing it as
+a `Promise.all` would only hide the serialization, not remove it.
+
+A queue is not a barrier, though. The calibrated subagent does not need the whole batch in
+hand before it starts: feed it each item as the stage before produces it (from inside that
+stage's fan-out callback, SKILL.md §11) and its verdicts stay consistent while the pipeline
+keeps moving.
+
+Either way, a judge's verdict is a judgement, not a reproduction: a finding that survived the
+panel still enters the report as `unconfirmed` unless a confirmer or a `world.run` check
+reproduced it.
+
+---
+
+## 5. Loop until approved, with a real escape
+
+**When:** a bounded loop that must still return something useful when it runs out of rounds.
+
+```ts
+let best: Attempt | undefined;
+for (let round = 0; round < 6; round++) {
+  phase("Attempt the fix");
+  const attempt = await worker.ask<Attempt>(`Attempt the fix. Prior failure: ${lastError ?? "none"}`);
+  phase("Check whether it actually passes");
+  const check = await checker.ask<Check>(`Does this pass? ${JSON.stringify(attempt)}`);
+  if (check.passed) return { attempt, rounds: round + 1, converged: true };
+  best = attempt;
+  lastError = check.reason;
+}
+return { attempt: best, rounds: 6, converged: false };
+```
+
+Return the shape that says **whether it converged**, not just the result. A caller that
+cannot tell "approved on round two" from "gave up after six" will treat the second as the
+first. Never let the loop fall off the end returning nothing.
+
+---
+
+## 6. Staged pipeline with typed handoff
+
+**When:** each stage narrows or transforms what the next one works on.
+
+```ts
+phase("Survey which modules touch auth");
+const survey = await agent("surveyor").ask<Survey>("List the modules that touch auth.");
+log(`${survey.modules.length} modules in scope`);
+
+phase("Analyse each module for auth bypasses");
+const analyses = await Promise.all(
+  survey.modules.map((m) =>
+    agent(`analyst-${m.path}`).ask<Analysis>(
+      `Analyse ${m.path} for auth bypasses. Purpose: ${m.purpose}`,
+    ),
+  ),
+);
+
+phase("Write the findings up for the engineer who fixes them");
+const synth = agent("synthesist", "You write findings up for an engineer who will fix them.");
+return synth.ask<Writeup>(`Write these up, deduplicated:\n${JSON.stringify(analyses)}`);
+```
+
+Each stage's result is the next stage's input, and the type argument is what makes the
+handoff safe — `survey.modules.map` only compiles because `Survey` says what came back.
+
+Note the shape of the last call: a single synthesis subagent gets everything at once, because
+deduplicating across findings is exactly the job that needs to see all of them. Do not
+parallelize a stage whose whole purpose is cross-item comparison.
+
+The converse holds too. The analysis stage maps one to one onto the survey's modules, so if a
+per-module check followed it, that check would belong inside the same callback as the
+analysis — not behind a second `Promise.all` (shape 10). Reserve the barrier for the stage
+that needs everyone.
+
+---
+
+## 7. Bounded discovery
+
+**When:** the work has no natural size — "find the bugs" rather than "check these twelve
+files."
+
+```ts
+const MAX_ROUNDS = 6;
+const found: Bug[] = [];
+const seen = new Set<string>();
+
+for (let round = 1; round <= MAX_ROUNDS; round++) {
+  phase("Hunt for bugs not already found");
+  const batch = await agent("hunter").ask<Bugs>(
+    `Find bugs not already in this list: ${JSON.stringify([...seen])}`,
+  );
+  const fresh = batch.bugs.filter((b) => !seen.has(`${b.path}:${b.line}`));
+  if (fresh.length === 0) break; // dry: stop, the remaining rounds would only repeat
+
+  for (const bug of fresh) {
+    seen.add(`${bug.path}:${bug.line}`);
+    report(bug);
+    found.push(bug);
+  }
+  log(`${found.length} found after round ${round}`);
+}
+return found;
+```
+
+Two guards, and you need both: the round cap keeps the loop from running forever when the
+hunter keeps finding things, and the dry check stops it once the hunter stops finding anything
+new. The cap is a knob you pick and amend in the script — the harness enforces no node limit,
+so a loop without one only ends when the user cancels the run. Deduplicate against everything
+**seen**, not against everything kept — dedup against the kept list makes rejected findings
+reappear every round and the loop never converges.
+
+---
+
+## 8. Salvage by report
+
+**When:** always, in any run long enough to fail partway.
+
+```ts
+// Wrong: forty tasks of work, and a failure on task twelve returns nothing.
+const results: Result[] = [];
+for (const item of items) results.push(await worker.ask<Result>(`Handle ${item.id}`));
+return results;
+
+// Right: each result is published the moment it exists.
+phase("Handle each item and publish as it lands");
+const results: Result[] = [];
+for (const item of items) {
+  const result = await worker.ask<Result>(`Handle ${item.id}`);
+  report(result);
+  results.push(result);
+}
+return results;
+```
+
+Reported items are delivered with the completion notification on errored and stopped runs
+as well as successful ones, and they are recorded, so a resumed run does not re-emit them.
+The return value only survives if the script reaches its `return`; reported items survive
+regardless. Report findings, not chatter — there is a per-run item cap, and overrunning it
+fails the run.
+
+The same call can feed a picture. Tag the item with a preset artifact id —
+`report(result, "progress")` — and it lands both in the run's results and on the chart,
+table, metrics or board of that name, live as the loop goes (SKILL.md §10).
+
+A `try`/`catch` around a single task turns one **logic** failure — a subagent result that
+failed validation, a gate that did not pass, a world read over its cap, an artifact publish
+whose file is missing — into a partial result instead of a dead run. It is not for provider
+errors: model-side errors never reach the script. Transient ones (rate limits, overload,
+network errors, timeouts, unknown provider errors) are retried by the runtime without limit;
+deterministic ones (sign-in expired, model not in the plan, quota cap) stop the whole run as
+`stopped` so the user can fix the cause and resume it. A retry loop around an ask for their
+sake is dead code. The one model-adjacent error a script can catch is `ContextLimit`: the
+ask itself was too large for the model even after compaction, and the fix is a smaller ask.
+
+```ts
+for (const item of items) {
+  try {
+    report(await worker.ask<Result>(`Handle ${item.id}`));
+  } catch (error) {
+    log(`skipped ${item.id}: ${String(error)}`);
+  }
+}
+```
+
+---
+
+## 9. Gated verifier loop (world.run)
+
+**When:** the stopping condition is machine-checkable — a build, a proof checker, a test
+suite — and a subagent's claim of success is not worth trusting.
+
+```ts
+const prover = agent("prover", "You repair the proof. Fix exactly what the checker reports.");
+
+phase("Write the first proof attempt");
+await prover.ask<Attempt>(`Prove the open theorem in ${FILE}.`);
+let clean = false;
+for (let round = 1; round <= 8; round++) {
+  phase("Check the file with the fast checker");
+  const check = await world.run("lake", ["env", "lean", FILE], { timeoutMs: 600_000 });
+  clean = check.exitCode === 0 && !check.stderr.includes("sorry");
+  if (clean) break;
+  log(`round ${round}: checker rejected`);
+  phase("Repair what the checker rejected");
+  await prover.ask<Attempt>(`The checker rejected the file:\n${check.stderr}\nRepair ${FILE}.`);
+}
+if (!clean) return { proved: false };
+
+phase("Build the whole project once before handing over");
+const build = await world.run("lake", ["build"], { timeoutMs: 1_800_000 });
+return { proved: build.exitCode === 0 };
+```
+
+The subagent does the open-ended work; the script does the judging, and the judgment is not
+delegable. `world.run` executes the checker for real, so "verified" is never a claim — only
+an exit code. A nonzero exit is a **value**, which is why the loop reads `check.exitCode`
+and feeds `check.stderr` forward instead of catching anything; rejections are reserved for
+the world failing to answer (spawn failure, timeout, output over the cap), and a
+`try`/`catch` around the call is how a script chooses a fallback for those.
+
+Two tiers, and the difference is the whole point. The per-file checker is the fast tier: it
+answers in seconds, so it drives the rounds. It is not the verdict — `lake env lean` exits
+0 on a proof that still says `sorry` and only warns on stderr, which is why the loop reads
+stderr too. The whole-project build is the strong tier: it is what the request was about,
+and it runs once at the end even though the fast tier already said yes. Pick both tiers by
+reading the repository — the README's "run this to verify" line, the `Makefile`, the
+`package.json` scripts — never from habit; the strongest check the repository offers for
+what the user asked is the one that decides (SKILL.md §5).
+
+The command name is a compile-time literal by rule — the user approves the script's command
+set at confirmation — so interpolate paths, flags and round numbers into the **args**,
+never into the command. Compare shape 5: same loop, but there the checker was a subagent;
+prefer this shape whenever a real command can render the verdict.
+
+---
+
+## 10. Per-item pipeline
+
+**When:** two or more stages map one to one — a hunter per file and a confirmer per finding,
+a migrator per file and a checker per file — and nothing in the later stage needs to see the
+whole earlier stage.
+
+```ts
+phase("Hunt for bugs in each file and confirm them as they are found");
+const confirmed = (
+  await Promise.all(
+    paths.map(async (p) => {
+      const hunt = await agent(`hunter-${p}`).ask<Hunt>(`Hunt for correctness bugs in ${p}.`);
+      return Promise.all(
+        hunt.bugs.map(async (bug, index) => {
+          const check = await agent(`confirmer-${p}-${index}`).ask<Confirmation>(
+            `Reproduce this bug from its evidence alone. Do not edit any file.\n${JSON.stringify(bug)}`,
+          );
+          const reported = { ...bug, status: check.reproduced ? "verified" : "unconfirmed" };
+          report(reported);
+          return reported;
+        }),
+      );
+    }),
+  )
+).flat();
+```
+
+One join, at the end, where the report needs every item. Compare the two-barrier version —
+`Promise.all` over the hunters, then `Promise.all` over the confirmers — which starts no
+confirmer until the slowest hunter is done and leaves the concurrency slots idle in between.
+The cache identity of a revised re-run is unchanged: each subagent is still named and asked in
+the same order.
+
+One phase covers the whole pipeline, named for what it does to each item. Do not put a marker
+per stage inside the callback: the run has one current phase, and concurrent callbacks
+re-entering two markers out of order would stamp each other's steps.
+
+When one item failing should cost one item, catch inside the callback (examples #3) or use
+`Promise.allSettled` and read each outcome; a rejection inside a plain `Promise.all` rejects
+the join and the siblings with it.

+ 13 - 2
apps/zcode-cli/packages/cli/scripts/build-sea.mjs

@@ -23,6 +23,7 @@ import {
 import { removeWindowsAuthenticodeSignature } from "./windows-authenticode.mjs";
 import { removeWindowsAuthenticodeSignature } from "./windows-authenticode.mjs";
 import { collectSeaTuiAssets } from "./sea-tui-assets.mjs";
 import { collectSeaTuiAssets } from "./sea-tui-assets.mjs";
 import { collectSeaOfficialPluginAssets } from "./sea-official-plugin-assets.mjs";
 import { collectSeaOfficialPluginAssets } from "./sea-official-plugin-assets.mjs";
+import { collectSeaBundledSkillAssets } from "./sea-bundled-skill-assets.mjs";
 import { collectSeaRuntimeToolAssets } from "./sea-runtime-tool-assets.mjs";
 import { collectSeaRuntimeToolAssets } from "./sea-runtime-tool-assets.mjs";
 import { prepareSeaRuntimeToolAssets } from "./sea-runtime-tool-prepare.mjs";
 import { prepareSeaRuntimeToolAssets } from "./sea-runtime-tool-prepare.mjs";
 import { collectSeaPlaywrightAssets } from "./sea-playwright-assets.mjs";
 import { collectSeaPlaywrightAssets } from "./sea-playwright-assets.mjs";
@@ -154,6 +155,11 @@ const prepareSeaBlob = async (target, nodeVersion) => {
     root,
     root,
     stagingDirectory: seaAssetStagingForTarget(`${target}-official-plugins`),
     stagingDirectory: seaAssetStagingForTarget(`${target}-official-plugins`),
   });
   });
+  const { assets: bundledSkillAssets, manifest: bundledSkillManifest } =
+    await collectSeaBundledSkillAssets({
+      root,
+      stagingDirectory: seaAssetStagingForTarget(`${target}-bundled-skills`),
+    });
   const { assets: runtimeToolAssets, manifest: runtimeToolManifest } =
   const { assets: runtimeToolAssets, manifest: runtimeToolManifest } =
     await collectSeaRuntimeToolAssets({
     await collectSeaRuntimeToolAssets({
       root: repositoryRoot,
       root: repositoryRoot,
@@ -167,7 +173,11 @@ const prepareSeaBlob = async (target, nodeVersion) => {
       target,
       target,
     });
     });
   const providerConfigAssets = await collectSeaProviderConfigAssets({ root: repositoryRoot });
   const providerConfigAssets = await collectSeaProviderConfigAssets({ root: repositoryRoot });
-  const nodeLicensePath = await stageNodeNotices(seaAssetStagingForTarget(`${target}-node`), nodeVersion, repositoryRoot);
+  const nodeLicensePath = await stageNodeNotices(
+    seaAssetStagingForTarget(`${target}-node`),
+    nodeVersion,
+    repositoryRoot,
+  );
 
 
   await writeFile(
   await writeFile(
     seaConfig,
     seaConfig,
@@ -176,6 +186,7 @@ const prepareSeaBlob = async (target, nodeVersion) => {
         assets: {
         assets: {
           ...tuiAssets,
           ...tuiAssets,
           ...pluginAssets,
           ...pluginAssets,
+          ...bundledSkillAssets,
           ...runtimeToolAssets,
           ...runtimeToolAssets,
           ...playwrightAssets,
           ...playwrightAssets,
           ...providerConfigAssets,
           ...providerConfigAssets,
@@ -193,7 +204,7 @@ const prepareSeaBlob = async (target, nodeVersion) => {
   );
   );
 
 
   console.log(
   console.log(
-    `[sea] generating SEA blob for ${target} with ${tuiManifest.files.length} TUI assets, ${pluginManifest.plugins.length} official plugins, ${runtimeToolManifest.tools.length} runtime tools, and ${playwrightManifest.files.length} Playwright assets`,
+    `[sea] generating SEA blob for ${target} with ${tuiManifest.files.length} TUI assets, ${pluginManifest.plugins.length} official plugins, ${bundledSkillManifest.files.length} bundled skill files, ${runtimeToolManifest.tools.length} runtime tools, and ${playwrightManifest.files.length} Playwright assets`,
   );
   );
   run(process.execPath, ["--experimental-sea-config", seaConfig]);
   run(process.execPath, ["--experimental-sea-config", seaConfig]);
   return seaBlob;
   return seaBlob;

+ 88 - 0
apps/zcode-cli/packages/cli/scripts/sea-bundled-skill-assets.mjs

@@ -0,0 +1,88 @@
+import { createHash } from "node:crypto";
+import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { existsSync } from "node:fs";
+import { join, relative, resolve, sep } from "node:path";
+
+// 随 CLI 内置的技能包(apps/zcode-cli/packages/bundled-skills)。它不是官方插件:不进市场目录、
+// 没有版本身份,运行时按内容 hash 解压到 `<cli storage>/bundled-skills/<hash>/`
+// (bootstrap/src/app/bundled-skills.ts)。这里的 manifest 形状与那边的读取逐字对应。
+export const seaBundledSkillAssetPrefix = "zcode-bundled-skills/";
+export const seaBundledSkillManifestAssetKey = `${seaBundledSkillAssetPrefix}manifest.json`;
+export const bundledSkillPackRootPath = join("packages", "bundled-skills");
+export const bundledSkillPackSkillsDirectory = "skills";
+// 与 bootstrap 的 BUNDLED_SKILL_PACK_REQUIRED_PATHS 对齐:缺任一项即中止 SEA 构建,
+// 不把一个引用文件残缺的技能包发进正式二进制。
+export const bundledSkillPackRequiredPaths = [
+  "skills/dynamic-workflows/SKILL.md",
+  "skills/dynamic-workflows/patterns.md",
+  "skills/dynamic-workflows/examples.md",
+];
+
+export const collectSeaBundledSkillAssets = async ({ root, stagingDirectory }) => {
+  const packRoot = resolve(root, bundledSkillPackRootPath);
+  assertBundledSkillPack(packRoot);
+
+  await rm(stagingDirectory, { force: true, recursive: true });
+
+  const files = [];
+  const assets = {};
+  for await (const sourcePath of walkFiles(join(packRoot, bundledSkillPackSkillsDirectory))) {
+    const relativePath = relative(packRoot, sourcePath);
+    if (!shouldIncludeFile(relativePath)) continue;
+    const bytes = await readFile(sourcePath);
+    const sourceStats = await stat(sourcePath);
+    const posixPath = toPosixPath(relativePath);
+    assets[`${seaBundledSkillAssetPrefix}${posixPath}`] = sourcePath;
+    files.push({
+      mode: modeForFile(sourceStats.mode),
+      path: posixPath,
+      sha256: createHash("sha256").update(bytes).digest("hex"),
+    });
+  }
+  files.sort((left, right) => left.path.localeCompare(right.path));
+
+  const manifest = {
+    hash: createHash("sha256")
+      .update(JSON.stringify(files.map(({ path, sha256, mode }) => [path, sha256, mode])))
+      .digest("hex"),
+    files,
+    version: 1,
+  };
+  const manifestPath = resolve(stagingDirectory, "bundled-skills-manifest.json");
+  await mkdir(stagingDirectory, { recursive: true });
+  await writeFile(manifestPath, JSON.stringify(manifest, null, 2));
+  assets[seaBundledSkillManifestAssetKey] = manifestPath;
+
+  return { assets, manifest };
+};
+
+function assertBundledSkillPack(packRoot) {
+  if (!existsSync(join(packRoot, bundledSkillPackSkillsDirectory))) {
+    throw new Error(`Missing bundled skill pack at ${packRoot}`);
+  }
+  for (const relativePath of bundledSkillPackRequiredPaths) {
+    const assetPath = join(packRoot, ...relativePath.split("/"));
+    if (!existsSync(assetPath)) {
+      throw new Error(`Missing bundled skill pack required asset at ${assetPath}`);
+    }
+  }
+}
+
+async function* walkFiles(directory) {
+  const entries = await readdir(directory, { withFileTypes: true });
+  for (const entry of entries) {
+    if (entry.name === "node_modules" || entry.name === ".turbo") continue;
+    const fullPath = resolve(directory, entry.name);
+    if (entry.isDirectory()) {
+      yield* walkFiles(fullPath);
+      continue;
+    }
+    if (entry.isFile()) yield fullPath;
+  }
+}
+
+const shouldIncludeFile = (relativePath) => !relativePath.split(sep).includes(".DS_Store");
+
+const toPosixPath = (value) => value.split(sep).join("/");
+
+const modeForFile = (sourceMode) => ((sourceMode & 0o111) !== 0 ? 0o755 : 0o644);

+ 3 - 0
apps/zcode-cli/packages/cli/src/arguments.ts

@@ -34,6 +34,9 @@ export const parseGlobalArgs = (argv: string[]) =>
       "memory-bench": {
       "memory-bench": {
         type: "boolean",
         type: "boolean",
       },
       },
+      "enable-workflow": {
+        type: "boolean",
+      },
       attach: {
       attach: {
         multiple: true,
         multiple: true,
         type: "string",
         type: "string",

+ 8 - 0
apps/zcode-cli/packages/cli/src/command-center/create.ts

@@ -214,6 +214,14 @@ export function createCommandCenter(deps: CommandCenterDeps): TuiSubmitPrompt {
         return attachCurrentSessionMetadata(await app.submitPrompt(prompt, options), deps, app);
         return attachCurrentSessionMetadata(await app.submitPrompt(prompt, options), deps, app);
       }
       }
 
 
+      if (command.name === "workflow") {
+        const app = await deps.getApp();
+        const prompt = command.args ? `/workflow ${command.args}` : "/workflow";
+        // 与 /init 同款:原文交给 app.submitPrompt,由 bootstrap 的 builtin resolver 展开成
+        // 「先加载 dynamic-workflows 技能,再写脚本调 CreateWorkflow」的提示词。
+        return attachCurrentSessionMetadata(await app.submitPrompt(prompt, options), deps, app);
+      }
+
       if (command.name === "expert") {
       if (command.name === "expert") {
         return handleExpertCommand(command.args, deps, options);
         return handleExpertCommand(command.args, deps, options);
       }
       }

+ 6 - 0
apps/zcode-cli/packages/cli/src/command-center/slash-command-types.ts

@@ -35,6 +35,12 @@ export type SlashCommand =
       rawName: string;
       rawName: string;
       type: "known";
       type: "known";
     }
     }
+  | {
+      args: string;
+      name: "workflow";
+      rawName: string;
+      type: "known";
+    }
   | {
   | {
       args: string;
       args: string;
       name: "locale";
       name: "locale";

+ 11 - 0
apps/zcode-cli/packages/cli/src/command-center/slash-commands.ts

@@ -87,6 +87,17 @@ export function parseSlashCommand(input: string): SlashCommand | null {
     };
     };
   }
   }
 
 
+  // `/workflow` 与 `/init` 同为 bootstrap 展开的内置 prompt 命令:这里只识别名字,
+  // 正文由 builtin-prompt-command.ts 生成;headless 下按 known 且非 expert/goal 走普通 prompt 路径。
+  if (rawName === "workflow") {
+    return {
+      args,
+      name: "workflow",
+      rawName,
+      type: "known",
+    };
+  }
+
   if (rawName === "login") {
   if (rawName === "login") {
     return {
     return {
       args,
       args,

+ 2 - 0
apps/zcode-cli/packages/cli/src/prompt-command.ts

@@ -229,6 +229,8 @@ export const runPrompt = async (
         ...(mode ? { mode } : {}),
         ...(mode ? { mode } : {}),
         ...(toolDisallowlist ? { toolDisallowlist } : {}),
         ...(toolDisallowlist ? { toolDisallowlist } : {}),
         ...(forceMcs ? { midConversationSystem: { mode: "force" as const } } : {}),
         ...(forceMcs ? { midConversationSystem: { mode: "force" as const } } : {}),
+        // headless 按本次调用显式开关;不改 core 缺省值,保持 TUI 与 stdio 的既有策略。
+        dynamicWorkflowEnabled: options.enableWorkflow === true,
         memory: { extractionEnabled: options.memoryBench === true },
         memory: { extractionEnabled: options.memoryBench === true },
         modelStreaming: "on",
         modelStreaming: "on",
         presentationSurface,
         presentationSurface,

+ 12 - 0
apps/zcode-cli/packages/cli/src/run.ts

@@ -51,6 +51,8 @@ const BROWSER_USE_SCOPE_ERROR =
 const SURFACE_SCOPE_ERROR =
 const SURFACE_SCOPE_ERROR =
   "--surface can only be used with --prompt, --target, app-server, or agent-server.";
   "--surface can only be used with --prompt, --target, app-server, or agent-server.";
 const MEMORY_BENCH_SCOPE_ERROR = "--memory-bench can only be used with -p/--prompt.";
 const MEMORY_BENCH_SCOPE_ERROR = "--memory-bench can only be used with -p/--prompt.";
+const ENABLE_WORKFLOW_SCOPE_ERROR =
+  "--enable-workflow can only be used with -p/--prompt or --target.";
 
 
 const pluginsCommandFlags = (
 const pluginsCommandFlags = (
   values: ReturnType<typeof parseGlobalArgs>["values"],
   values: ReturnType<typeof parseGlobalArgs>["values"],
@@ -99,6 +101,7 @@ const globalOptions = (
     browserExecutable,
     browserExecutable,
     browserUse,
     browserUse,
     detectedLocale,
     detectedLocale,
+    ...(values["enable-workflow"] === true ? { enableWorkflow: true } : {}),
     force: values.force === true,
     force: values.force === true,
     json: values.json === true,
     json: values.json === true,
     locale,
     locale,
@@ -425,6 +428,15 @@ export const run = async (ctx: RunContext, deps: RunDependencies = {}): Promise<
     return 0;
     return 0;
   }
   }
 
 
+  if (
+    options.enableWorkflow &&
+    (parsed.positionals.length > 0 ||
+      (typeof parsed.values.prompt !== "string" && targetRequest === undefined))
+  ) {
+    ctx.stderr.write(`${ENABLE_WORKFLOW_SCOPE_ERROR}\n`);
+    return 1;
+  }
+
   if (
   if (
     options.memoryBench &&
     options.memoryBench &&
     (typeof parsed.values.prompt !== "string" || parsed.positionals.length > 0)
     (typeof parsed.values.prompt !== "string" || parsed.positionals.length > 0)

+ 6 - 2
apps/zcode-cli/packages/contracts/src/events/session.events.ts

@@ -330,8 +330,12 @@ export type WorkflowLaunchDisplay = Extract<ToolResultDisplayPayload, { kind: "c
  * 供「13 → 4」这种读法。与 shared 的 `workflowSettingsAmendMetaSchema` 同形。
  * 供「13 → 4」这种读法。与 shared 的 `workflowSettingsAmendMetaSchema` 同形。
  */
  */
 export interface WorkflowSettingsAmendMeta {
 export interface WorkflowSettingsAmendMeta {
-  /** 被这次调整替代(或接着跑)的那个 run。 */
-  predecessorRunId: string;
+  /**
+   * 被这次调整替代(或接着跑)的那个 run。**缺席即就地生效**:只改并发上界、run 又还在飞时,
+   * 那次「配置」既不停这次 run 也不另起一次,于是没有前驱可指——`runId` 指的就是被调整的那一个。
+   * 与 shared 的 `workflowSettingsAmendMetaSchema` 同形。
+   */
+  predecessorRunId?: string;
   subagentModel?: { from?: string; to?: string };
   subagentModel?: { from?: string; to?: string };
   maxConcurrency?: { from?: number; to?: number };
   maxConcurrency?: { from?: number; to?: number };
   ceiling?: number;
   ceiling?: number;

+ 45 - 0
apps/zcode-cli/packages/contracts/src/interfaces/dynamic-workflow-run-retune.port.ts

@@ -0,0 +1,45 @@
+// Dynamic Workflow Run Port:调整运行中的并发上限。
+// 定义请求、结果与能力边界,由 dynamic-workflow-run.port.ts 统一再导出,
+// 调用方通过 `@zcode/contracts` 使用。
+
+/**
+ * {@link import("./dynamic-workflow-run.port.js").DynamicWorkflowRunPort.retuneConcurrency}
+ * 的请求。
+ */
+export interface DynamicWorkflowRunRetuneRequest {
+  runId: string;
+  /**
+   * 新的并发上界。`null` = 天花板 = 解除本 run 自己的限制(与 `AmendWorkflow` 的
+   * `max_concurrency: null` 同义)。给了数就钳到 `[1, 天花板]`——钳制用的是端口自己那一份实现,
+   * 工具层无须、也不该再钳一次得到第二个答案。
+   */
+  maxConcurrency: number | null;
+}
+
+/**
+ * retune 被拒的结构化理由。两者对调用方是**两个不同的下一步**,所以必须可分辨:
+ *
+ *   - `not_live`:本 service 手上没有这个在飞 run(从来不是本进程的、已经结算的),或者它恰好
+ *     在存活判定与本次调用之间结算了。调用方回落到一次真正的修订(`AmendWorkflow` 的既有那条路)。
+ *   - `unchanged`:值与此刻生效的上界相同。什么都没写、什么都没停——`current` 就是那个值,
+ *     调用方据它写出「已经是 n 了」。
+ */
+export type DynamicWorkflowRunRetuneRefusalReason = "not_live" | "unchanged";
+
+/**
+ * retune 的结构化结果。失败走 reason 而不是 throw,与
+ * {@link import("./dynamic-workflow-run.port.js").DynamicWorkflowRunAmendResult} 同一条论证:
+ * 两种理由都是调用方可预期的业务分支。
+ *
+ * `ceiling` 与 `previous` 不是锦上添花:模型面的回话要说「至多 n 个子代理同时运行」,而 n 等于
+ * 天花板时该说的是「限制已解除」(与 `CreateWorkflow` 的回话同一条判据);事件日志要说「8 → 2」,
+ * 从单个新值推不出前一个。两者都只有端口这一侧知道,留给调用方重算就是第二份天花板实现。
+ */
+export type DynamicWorkflowRunRetuneResult =
+  | { ok: true; maxConcurrency: number; previous: number; ceiling: number }
+  | {
+      ok: false;
+      reason: DynamicWorkflowRunRetuneRefusalReason;
+      /** 此刻生效的上界;`unchanged` 恒在场,`not_live` 只在还读得到时在场。 */
+      current?: number;
+    };

+ 72 - 0
apps/zcode-cli/packages/contracts/src/interfaces/dynamic-workflow-run-workspace.port.ts

@@ -0,0 +1,72 @@
+// Dynamic Workflow Run Port:工作区操作记录的读取类型。
+// 包含 `files.*`、`git.*` 和 `world.run` 调用的清单行与正文,
+// 由 dynamic-workflow-run.port.ts 统一再导出,调用方通过 `@zcode/contracts` 使用。
+
+// 结构化失败的形状留在主文件上(本组的两个字段引用它),所以这里反向 import 一个类型:
+// 纯类型、无运行时边,两个文件各自只描述自己那一组。
+import type { DynamicWorkflowRunError } from "./dynamic-workflow-run.port.js";
+
+/** 工作区节点的种类:journal `dwf_node.kind` 的两个 world 值。 */
+export type DynamicWorkflowRunWorkspaceNodeKind = "world-read" | "world-run";
+
+/** 节点行的状态,= journal 的 `NodeRecordStatus`(刻意在这里重申,理由同 lifecycle status)。 */
+export type DynamicWorkflowRunWorkspaceNodeStatus = "running" | "completed" | "failed";
+
+/**
+ * 清单上一行的**摘要**:不把正文解出来就能报的那几个数。由存储层用 SQLite 的 JSON 函数在
+ * 查询里算出(`resultBytes` / `resultCount` / `exitCode` / `stdoutBytes` / `stderrBytes`),
+ * 端口原样透传。哪个字段在场取决于 op:数组正文(glob / grep / changedFiles)有 `resultCount`,
+ * `world.run` 有 exitCode 与两路输出的字节数,字符串正文只有 `resultBytes`。
+ */
+export interface DynamicWorkflowRunWorkspaceNodeSummary {
+  /** 正文序列化后的 UTF-8 字节数。 */
+  resultBytes: number;
+  resultCount?: number;
+  exitCode?: number;
+  stdoutBytes?: number;
+  stderrBytes?: number;
+}
+
+/**
+ * 工作区 transcript 的一行:一次 `files.*` / `git.*` / `world.run` 调用,**不带正文**。
+ *
+ * `op` / `args` 来自迁移 0030 加的 `input_json`(admission 时写下、≤ 4 KB);升级前的历史行
+ * 两者缺席,UI 退回静态图上的步标签。`inputTruncated` 表示 args 是逐项字符串预览而不是原值。
+ */
+export interface DynamicWorkflowRunWorkspaceNode {
+  siteId: string;
+  ordinal: number;
+  kind: DynamicWorkflowRunWorkspaceNodeKind;
+  op?: string;
+  args?: readonly unknown[];
+  inputTruncated?: true;
+  status: DynamicWorkflowRunWorkspaceNodeStatus;
+  /** failed 行的结构化失败(journal `error_json` 的 code + message;其余字段不出端口)。 */
+  error?: DynamicWorkflowRunError;
+  /** 结算成功的行才有。 */
+  summary?: DynamicWorkflowRunWorkspaceNodeSummary;
+  /** journal 行的建立 / 最近更新时刻(epoch 毫秒);二者之差就是这一步的耗时。 */
+  createdAt: number;
+  updatedAt: number;
+}
+
+/** {@link import("./dynamic-workflow-run.port.js").DynamicWorkflowRunPort.readWorkspaceNodeResult} 的分页袋:正文的字节上限。 */
+export interface DynamicWorkflowRunWorkspaceNodeResultQuery {
+  /** 必填;端口按它**有界化**正文(截断而不是拒绝——这是审计面,不是脚本的取数面)。 */
+  maxBytes: number;
+}
+
+/**
+ * 一个工作区节点的正文:按形状有界化过的 `result`。
+ *
+ * 截断是**保形**的:字符串切尾、数组去尾、`world.run` 的 stdout / stderr 各自切尾,
+ * `truncated` 说明发生过截断,`totalBytes` 是截断前的字节数。running 行没有正文;failed 行
+ * 只有 `error`。
+ */
+export interface DynamicWorkflowRunWorkspaceNodeResult {
+  status: DynamicWorkflowRunWorkspaceNodeStatus;
+  result?: unknown;
+  error?: DynamicWorkflowRunError;
+  truncated: boolean;
+  totalBytes: number;
+}

+ 42 - 69
apps/zcode-cli/packages/contracts/src/interfaces/dynamic-workflow-run.port.ts

@@ -7,6 +7,15 @@ import type {
   DynamicWorkflowRunPhaseView,
   DynamicWorkflowRunPhaseView,
   DynamicWorkflowRunSubagentView,
   DynamicWorkflowRunSubagentView,
 } from "./dynamic-workflow-run-roster.port.js";
 } from "./dynamic-workflow-run-roster.port.js";
+import type {
+  DynamicWorkflowRunRetuneRequest,
+  DynamicWorkflowRunRetuneResult,
+} from "./dynamic-workflow-run-retune.port.js";
+import type {
+  DynamicWorkflowRunWorkspaceNode,
+  DynamicWorkflowRunWorkspaceNodeResult,
+  DynamicWorkflowRunWorkspaceNodeResultQuery,
+} from "./dynamic-workflow-run-workspace.port.js";
 import type { DynamicWorkflowRunProgressPayload } from "../events/session.events.js";
 import type { DynamicWorkflowRunProgressPayload } from "../events/session.events.js";
 import type { ModelSelection } from "../model/model.js";
 import type { ModelSelection } from "../model/model.js";
 import type { SessionId, ToolCallId } from "./shared.js";
 import type { SessionId, ToolCallId } from "./shared.js";
@@ -234,6 +243,15 @@ export type DynamicWorkflowRunSnapshot = Omit<WorkflowTaskSnapshot, "output"> &
   scriptPath?: string;
   scriptPath?: string;
   /** 结构化失败(与 {@link DynamicWorkflowRunDetail.error} 同源);基类的 `error` 是它的 message。 */
   /** 结构化失败(与 {@link DynamicWorkflowRunDetail.error} 同源);基类的 `error` 是它的 message。 */
   failure?: DynamicWorkflowRunError;
   failure?: DynamicWorkflowRunError;
+  /**
+   * 本 run 及其 lineage 的**活动**时长(毫秒):本 run 的每一世加上每个前驱的每一世,世与世
+   * 之间的空档不计。完成卡的「时间」格报的就是它。
+   *
+   * 与 `reports` / `artifacts` 同规**只在终态在场**(`getTask` 被反复轮询,而消费者只有终态
+   * 通知),且 journal 说不出话时整字段缺席——不是 0。缺席即读侧退回 `completedAt − startedAt`:
+   * 那是结算它的那个进程自己看到的一世,一个更保守但永不虚报的答案。
+   */
+  activeDurationMs?: number;
   reports?: readonly unknown[];
   reports?: readonly unknown[];
   /**
   /**
    * 此刻停驻在这个 run 上、等主代理作答的升级问题。
    * 此刻停驻在这个 run 上、等主代理作答的升级问题。
@@ -335,75 +353,6 @@ export interface DynamicWorkflowRunArtifactBytes {
   contentType: string;
   contentType: string;
 }
 }
 
 
-// ————————————————————————————————————————————————————————————————
-// 工作区 transcript
-// ————————————————————————————————————————————————————————————————
-
-/** 工作区节点的种类:journal `dwf_node.kind` 的两个 world 值。 */
-export type DynamicWorkflowRunWorkspaceNodeKind = "world-read" | "world-run";
-
-/** 节点行的状态,= journal 的 `NodeRecordStatus`(刻意在这里重申,理由同 lifecycle status)。 */
-export type DynamicWorkflowRunWorkspaceNodeStatus = "running" | "completed" | "failed";
-
-/**
- * 清单上一行的**摘要**:不把正文解出来就能报的那几个数。由存储层用 SQLite 的 JSON 函数在
- * 查询里算出(`resultBytes` / `resultCount` / `exitCode` / `stdoutBytes` / `stderrBytes`),
- * 端口原样透传。哪个字段在场取决于 op:数组正文(glob / grep / changedFiles)有 `resultCount`,
- * `world.run` 有 exitCode 与两路输出的字节数,字符串正文只有 `resultBytes`。
- */
-export interface DynamicWorkflowRunWorkspaceNodeSummary {
-  /** 正文序列化后的 UTF-8 字节数。 */
-  resultBytes: number;
-  resultCount?: number;
-  exitCode?: number;
-  stdoutBytes?: number;
-  stderrBytes?: number;
-}
-
-/**
- * 工作区 transcript 的一行:一次 `files.*` / `git.*` / `world.run` 调用,**不带正文**。
- *
- * `op` / `args` 来自迁移 0030 加的 `input_json`(admission 时写下、≤ 4 KB);升级前的历史行
- * 两者缺席,UI 退回静态图上的步标签。`inputTruncated` 表示 args 是逐项字符串预览而不是原值。
- */
-export interface DynamicWorkflowRunWorkspaceNode {
-  siteId: string;
-  ordinal: number;
-  kind: DynamicWorkflowRunWorkspaceNodeKind;
-  op?: string;
-  args?: readonly unknown[];
-  inputTruncated?: true;
-  status: DynamicWorkflowRunWorkspaceNodeStatus;
-  /** failed 行的结构化失败(journal `error_json` 的 code + message;其余字段不出端口)。 */
-  error?: DynamicWorkflowRunError;
-  /** 结算成功的行才有。 */
-  summary?: DynamicWorkflowRunWorkspaceNodeSummary;
-  /** journal 行的建立 / 最近更新时刻(epoch 毫秒);二者之差就是这一步的耗时。 */
-  createdAt: number;
-  updatedAt: number;
-}
-
-/** {@link DynamicWorkflowRunPort.readWorkspaceNodeResult} 的分页袋:正文的字节上限。 */
-export interface DynamicWorkflowRunWorkspaceNodeResultQuery {
-  /** 必填;端口按它**有界化**正文(截断而不是拒绝——这是审计面,不是脚本的取数面)。 */
-  maxBytes: number;
-}
-
-/**
- * 一个工作区节点的正文:按形状有界化过的 `result`。
- *
- * 截断是**保形**的:字符串切尾、数组去尾、`world.run` 的 stdout / stderr 各自切尾,
- * `truncated` 说明发生过截断,`totalBytes` 是截断前的字节数。running 行没有正文;failed 行
- * 只有 `error`。
- */
-export interface DynamicWorkflowRunWorkspaceNodeResult {
-  status: DynamicWorkflowRunWorkspaceNodeStatus;
-  result?: unknown;
-  error?: DynamicWorkflowRunError;
-  truncated: boolean;
-  totalBytes: number;
-}
-
 /** 一个停驻中的升级问题。字段与 `escalation-raised` 事件同源,另加提问时刻。 */
 /** 一个停驻中的升级问题。字段与 `escalation-raised` 事件同源,另加提问时刻。 */
 export interface DynamicWorkflowRunPendingQuestion {
 export interface DynamicWorkflowRunPendingQuestion {
   /** 全局唯一的问题 id(形如 `dwfq-<runId 片段>-<seq>`);`resolveQuestion` 只认它。 */
   /** 全局唯一的问题 id(形如 `dwfq-<runId 片段>-<seq>`);`resolveQuestion` 只认它。 */
@@ -622,6 +571,23 @@ export interface DynamicWorkflowRunPort {
    * 缺席时工具层不钳、原样下传(端口实现自己还会钳一次)。
    * 缺席时工具层不钳、原样下传(端口实现自己还会钳一次)。
    */
    */
   concurrencyCeiling?(): number;
   concurrencyCeiling?(): number;
+  /**
+   * 就地改一个**在飞** run 自己的并发上界:同一个 runId、不铸后继、不 supersede、不导入缓存、在飞 ask 一个不丢。
+   *
+   * 与 {@link amend} 并列而非合并:修订换的是**脚本**,代价是停下前驱、铸新 run、从缓存重放;
+   * 而「只把这个 run 调慢一点」不该付那笔账。两个调用方(`AmendWorkflow` 的 handler 与 GUI 的
+   * `amendWorkflowRunSettings`)读同一个答案,于是「什么算一次 retune」只有一个定义。
+   *
+   * 三件事在一个同步片里发生或者一件都不发生:换引擎的 caps(调度器现读)、写
+   * `dwf_run.caps_max_concurrency`(resume 因此续在新上界上)、记一条 `run-caps-changed`。
+   * 服务另把自己那份内存上界一并挪动,于是快照、详情与 `GetWorkflowRun` 立刻报新值。
+   *
+   * **可选成员**(消费方 `typeof` 探测),理由同 {@link resume}:端口 stub 不必为一条控制面全员
+   * 陪跑,而「端口缺席」与「方法缺席」对调用方是同一个业务事实——回落到一次真正的修订。
+   */
+  retuneConcurrency?(
+    request: DynamicWorkflowRunRetuneRequest,
+  ): Promise<DynamicWorkflowRunRetuneResult>;
   getTask(taskId: string): Promise<DynamicWorkflowRunSnapshot | undefined>;
   getTask(taskId: string): Promise<DynamicWorkflowRunSnapshot | undefined>;
   waitForTask(
   waitForTask(
     taskId: string,
     taskId: string,
@@ -925,6 +891,13 @@ export interface DynamicWorkflowRunProviderStop {
 // 此处原样再导出以保持 `@zcode/contracts` 的导入路径不变。
 // 此处原样再导出以保持 `@zcode/contracts` 的导入路径不变。
 export type * from "./dynamic-workflow-run-roster.port.js";
 export type * from "./dynamic-workflow-run-roster.port.js";
 
 
+// retune(就地改在飞 run 的并发上界)的三个类型住在 dynamic-workflow-run-retune.port.ts,
+// 同上原样再导出。
+export type * from "./dynamic-workflow-run-retune.port.js";
+
+// 工作区 transcript 的六个类型住在 dynamic-workflow-run-workspace.port.ts,同上原样再导出。
+export type * from "./dynamic-workflow-run-workspace.port.js";
+
 /** 单 run 详情:共同截面 + 进度 + 情势截面 + 按终态分叉的产物 / 失败。 */
 /** 单 run 详情:共同截面 + 进度 + 情势截面 + 按终态分叉的产物 / 失败。 */
 export interface DynamicWorkflowRunDetail extends DynamicWorkflowRunSummary {
 export interface DynamicWorkflowRunDetail extends DynamicWorkflowRunSummary {
   usage: DynamicWorkflowRunUsage;
   usage: DynamicWorkflowRunUsage;

+ 22 - 6
apps/zcode-cli/packages/contracts/src/tools/amend-workflow.ts

@@ -31,7 +31,7 @@ const AmendWorkflowModelInputSchema = z.object({
     .string()
     .string()
     .min(1)
     .min(1)
     .describe(
     .describe(
-      "ID of the run to amend — from CreateWorkflow's or AmendWorkflow's result, a notification, GetWorkflowRun or ListWorkflowRuns. Any run of this project qualifies, settled or still running; a running run is stopped and superseded by the new one.",
+      "ID of the run to amend (from a result, a notification, GetWorkflowRun or ListWorkflowRuns).",
     ),
     ),
   /**
   /**
    * `script` 与 `path` 都省略 = 沿用前驱存档的脚本:
    * `script` 与 `path` 都省略 = 沿用前驱存档的脚本:
@@ -44,7 +44,7 @@ const AmendWorkflowModelInputSchema = z.object({
     .min(1)
     .min(1)
     .optional()
     .optional()
     .describe(
     .describe(
-      "The WHOLE revised workflow script, inline, written against the same facade as CreateWorkflow. Provide this OR `path`, never both — `path` is the usual form. OMIT both to keep the predecessor's script unchanged and change only the settings (max_concurrency, subagent_model, name). Named subagents whose asks you left byte-identical settle from the predecessor's recorded results at zero token cost; the first changed or new ask runs live, and from that point everything runs live.",
+      "The whole revised script, inline. This OR `path`, never both; omit both to keep the predecessor's script.",
     ),
     ),
   /**
   /**
    * 修订的常态来源:前驱的脚本文件就地改一行,
    * 修订的常态来源:前驱的脚本文件就地改一行,
@@ -55,13 +55,13 @@ const AmendWorkflowModelInputSchema = z.object({
     .min(1)
     .min(1)
     .optional()
     .optional()
     .describe(
     .describe(
-      "The revised script's file, relative to the working directory or absolute — usually the predecessor's own script file, which the errored notification and GetWorkflowRun name. Provide this OR `script`, never both; omit both when the script is not changing. Edit that file in place and pass the same path back: a revision then costs one Edit instead of a second copy of the whole script. Submitting a file whose bytes are unchanged is refused (`script_unchanged`) unless the call also changes `max_concurrency` or `subagent_model`.",
+      "The revised script's file, usually the predecessor's own script file edited in place. This OR `script`, never both.",
     ),
     ),
   name: z
   name: z
     .string()
     .string()
     .min(1)
     .min(1)
     .optional()
     .optional()
-    .describe("Optional display label for the new run. Defaults to the predecessor's name."),
+    .describe("Display label for the new run; defaults to the predecessor's."),
   /**
   /**
    * 三态:省略 = 沿用前驱的上界、
    * 三态:省略 = 沿用前驱的上界、
    * `null` = 解除(回到天花板)、数 = 设定(钳到天花板之下)。三态只活到 `resolveInput`:那里把它
    * `null` = 解除(回到天花板)、数 = 设定(钳到天花板之下)。三态只活到 `resolveInput`:那里把它
@@ -75,7 +75,7 @@ const AmendWorkflowModelInputSchema = z.object({
     .nullable()
     .nullable()
     .optional()
     .optional()
     .describe(
     .describe(
-      "Upper bound on how many subagents work at the same time in the new run. Three states: OMIT the field to keep the predecessor's limit; pass null to remove that limit (run at this machine's default); pass a number to set one. Set a number ONLY when the user asks to limit parallelism — never on your own initiative and never in response to provider rate limits or errors, which the runtime already adapts to. A value above what this machine allows is lowered to that maximum.",
+      "Omit to keep the predecessor's limit, null to remove it, a number to set one (only when the user asks).",
     ),
     ),
   /**
   /**
    * 三态,与 `max_concurrency` 逐字同规:
    * 三态,与 `max_concurrency` 逐字同规:
@@ -90,7 +90,7 @@ const AmendWorkflowModelInputSchema = z.object({
     .nullable()
     .nullable()
     .optional()
     .optional()
     .describe(
     .describe(
-      "Model for the workflow's subagents in the new run, as `providerId/modelId` or a bare model id (optionally `$reasoningLevel`). Set it ONLY when the user asks for the subagents to run on a specific model; pass the name the user used, and if the tool answers that it cannot resolve it, pick from the listed ids or call ListModels. The main agent (you) keeps the session model regardless. Three states: OMIT to keep the predecessor's choice; null to return to the session model; a string to set one.",
+      "Omit to keep the predecessor's choice, null for the session model, a model id to set one (only when the user asks).",
     ),
     ),
 });
 });
 
 
@@ -118,6 +118,22 @@ export const AmendWorkflowPredecessorSchema = z
 
 
 export type AmendWorkflowPredecessor = z.infer<typeof AmendWorkflowPredecessorSchema>;
 export type AmendWorkflowPredecessor = z.infer<typeof AmendWorkflowPredecessorSchema>;
 
 
+/**
+ * 「这个前驱归本会话、且不是用户亲手停下的」——免确认的 owner 规则。
+ *
+ * 住在契约里而不是权限服务里,是因为它现在有**两个**读者,而两个读者必须一字不差地同意:
+ * 权限服务据它在 always-ask 分支里放行,就地调并发遇上 `not_live` 时 handler 据它判断这次落回
+ * 的修订本来要不要开窗。两处各写一遍,总有一天会让一条
+ * 「什么都没批」的调用悄悄起一次新 run。
+ *
+ * 收 `unknown`:权限服务拿到的是还没解析的工具入参,handler 拿到的是解析好的事实块。
+ */
+export function isAmendWorkflowOwnedPredecessor(predecessor: unknown): boolean {
+  if (!predecessor || typeof predecessor !== "object") return false;
+  const facts = predecessor as Record<string, unknown>;
+  return facts.owned_by_this_session === true && facts.stop_reason !== "user";
+}
+
 /**
 /**
  * 运行时入参:模型面那些键 + 回填的 `predecessor` 与 `script_line_offset`。`.strict()`:
  * 运行时入参:模型面那些键 + 回填的 `predecessor` 与 `script_line_offset`。`.strict()`:
  * `resume_from` 这类旧拼写在这里也是可见错误。
  * `resume_from` 这类旧拼写在这里也是可见错误。

+ 38 - 16
apps/zcode-cli/packages/contracts/src/tools/create-workflow.ts

@@ -8,6 +8,14 @@ import { SAVED_WORKFLOW_MAX_NAME_CHARS, SavedWorkflowScopeSchema } from "./saved
 
 
 export const CREATE_WORKFLOW_TOOL_NAME = "CreateWorkflow";
 export const CREATE_WORKFLOW_TOOL_NAME = "CreateWorkflow";
 
 
+/**
+ * 教模型写工作流的内置技能名(apps/zcode-cli/packages/bundled-skills/skills/<name>/SKILL.md)。
+ * 四个创作工具(Create/Amend/Save/EvalWorkflowSnippet)的 resolveInput 以它为门:会话里没有
+ * 加载过这份技能就拒绝提交脚本。
+ * 住在 contracts 里是因为 core 的门与 bootstrap 的技能包都读它,而两者不能互相 import。
+ */
+export const DYNAMIC_WORKFLOW_SKILL_NAME = "dynamic-workflows";
+
 /** 「恰好给一个执行体来源」的违规说明。写成常量是因为模型是它唯一的读者,三条路径同一句话。 */
 /** 「恰好给一个执行体来源」的违规说明。写成常量是因为模型是它唯一的读者,三条路径同一句话。 */
 export const CREATE_WORKFLOW_SOURCE_ERROR =
 export const CREATE_WORKFLOW_SOURCE_ERROR =
   "Provide exactly one workflow source: `script` for a one-off script written inline, `saved` to run a workflow saved in this project, or `path` for a script file on disk (the file a previous result named). Passing more than one, or none, is ambiguous.";
   "Provide exactly one workflow source: `script` for a one-off script written inline, `saved` to run a workflow saved in this project, or `path` for a script file on disk (the file a previous result named). Passing more than one, or none, is ambiguous.";
@@ -29,13 +37,11 @@ export const CreateWorkflowSavedSourceSchema = z
       .string()
       .string()
       .min(1)
       .min(1)
       .max(SAVED_WORKFLOW_MAX_NAME_CHARS)
       .max(SAVED_WORKFLOW_MAX_NAME_CHARS)
-      .describe("Name of a workflow saved in this project or globally (see ListSavedWorkflows)."),
+      .describe("Name of a saved workflow (see ListSavedWorkflows)."),
     args: z
     args: z
       .record(z.unknown())
       .record(z.unknown())
       .optional()
       .optional()
-      .describe(
-        "Values for the arguments the saved workflow declares. Unknown keys and type mismatches are rejected before anything runs.",
-      ),
+      .describe("Values for the arguments the saved workflow declares."),
     /** 解析回填:保存文件的落点。模型不填。 */
     /** 解析回填:保存文件的落点。模型不填。 */
     path: z.string().min(1).optional(),
     path: z.string().min(1).optional(),
     /**
     /**
@@ -43,7 +49,7 @@ export const CreateWorkflowSavedSourceSchema = z
      * 归一化后 `scope` 变成**命中**的那一根,见 create-workflow-source.ts。
      * 归一化后 `scope` 变成**命中**的那一根,见 create-workflow-source.ts。
      */
      */
     scope: SavedWorkflowScopeSchema.optional().describe(
     scope: SavedWorkflowScopeSchema.optional().describe(
-      "Which archive to take the workflow from. Omit to use the normal lookup order (a project workflow hides a global one with the same name).",
+      "Which archive to take it from; omit for the normal lookup order.",
     ),
     ),
   })
   })
   .strict();
   .strict();
@@ -82,16 +88,14 @@ const CreateWorkflowModelInputSchema = z
       .min(1)
       .min(1)
       .optional()
       .optional()
       .describe(
       .describe(
-        "Short display label for this run, in the user's language (\"PR review\", \"代码评审\"). Always pass it for an inline script: it labels the run everywhere and names its draft file under .zcode/workflow-drafts/. Defaults to the saved workflow's name when running a saved workflow.",
+        "Short run label in the user's language. Always pass it for an inline script; defaults to the saved workflow's name.",
       ),
       ),
     script: z
     script: z
       .string()
       .string()
       .optional()
       .optional()
-      .describe(
-        "Full TypeScript workflow script written against the dynamic-workflow facade, inline. Provide exactly one of `script`, `saved` and `path`. An inline script is saved to a file for you, and the result names it: revise it with `path`, not by pasting the script again.",
-      ),
+      .describe("The whole workflow script, inline. Exactly one of `script`, `saved` and `path`."),
     saved: CreateWorkflowSavedSourceSchema.optional().describe(
     saved: CreateWorkflowSavedSourceSchema.optional().describe(
-      "Run a workflow saved in this project or globally instead of an inline script. Provide exactly one of `script`, `saved` and `path`.",
+      "A saved workflow to run, by name. Exactly one of `script`, `saved` and `path`.",
     ),
     ),
     /**
     /**
      * 第三条来源:
      * 第三条来源:
@@ -104,7 +108,7 @@ const CreateWorkflowModelInputSchema = z
       .min(1)
       .min(1)
       .optional()
       .optional()
       .describe(
       .describe(
-        "A script file on disk, relative to the working directory or absolute — normally the file a previous CreateWorkflow/AmendWorkflow result named. Provide exactly one of `script`, `saved` and `path`. Prefer this over pasting a revised script: edit the file and pass its path.",
+        "A script file on disk (relative or absolute), usually the file a previous result named. Exactly one of `script`, `saved` and `path`.",
       ),
       ),
     /**
     /**
      * `path` 文件声明的实参。`saved` 有自己的 `saved.args`(同一套校验规则),内联脚本没有声明,
      * `path` 文件声明的实参。`saved` 有自己的 `saved.args`(同一套校验规则),内联脚本没有声明,
@@ -113,9 +117,7 @@ const CreateWorkflowModelInputSchema = z
     args: z
     args: z
       .record(z.unknown())
       .record(z.unknown())
       .optional()
       .optional()
-      .describe(
-        "Values for the arguments a `path` file declares in its `/* zcode-workflow` block. Only with `path`; with `saved` use `saved.args`. Unknown keys, missing required values and type mismatches are rejected before anything runs.",
-      ),
+      .describe("Values for the arguments a `path` file declares. Only with `path`."),
     /**
     /**
      * run 自己的并发上界。只压低、不抬高:
      * run 自己的并发上界。只压低、不抬高:
      * `resolveInput` 钳到 `[1, 天花板]`,确认窗与 handler 看到的就是将要生效的值。缺席即天花板。
      * `resolveInput` 钳到 `[1, 天花板]`,确认窗与 handler 看到的就是将要生效的值。缺席即天花板。
@@ -127,7 +129,7 @@ const CreateWorkflowModelInputSchema = z
       .positive()
       .positive()
       .optional()
       .optional()
       .describe(
       .describe(
-        'Upper bound on how many subagents work at the same time in this run. Set it ONLY when the user asks to limit parallelism ("at most 3 at a time", "don\'t run so many at once"). Never set it on your own initiative and never in response to provider rate limits or errors — the runtime already adapts to those. A value above what this machine allows is lowered to that maximum. Omit for the default.',
+        "Upper bound on subagents working at once. Only when the user asks to limit parallelism; never as a reaction to provider errors.",
       ),
       ),
     /**
     /**
      * 本 run 子代理跑在哪个模型上。与
      * 本 run 子代理跑在哪个模型上。与
@@ -141,7 +143,7 @@ const CreateWorkflowModelInputSchema = z
       .min(1)
       .min(1)
       .optional()
       .optional()
       .describe(
       .describe(
-        'Model for the workflow\'s subagents, as `providerId/modelId` or a bare model id (optionally `$reasoningLevel`). Set it ONLY when the user asks for the subagents to run on a specific model ("run the subagents on GLM-5.3-Flash"). Pass the name the user used; if the tool answers that it cannot resolve it, pick from the listed ids or call ListModels. The main agent (you) keeps the session model regardless. Omit to run subagents on the session model.',
+        "Model for the subagents (`providerId/modelId` or a model id). Only when the user asks; you stay on the session model.",
       ),
       ),
     // 修订续跑不在这里:它是 `AmendWorkflow` 的工作(amend-workflow.ts)。`.strict()` 让旧写法 `resume_from` 成为可见的 schema 错误,
     // 修订续跑不在这里:它是 `AmendWorkflow` 的工作(amend-workflow.ts)。`.strict()` 让旧写法 `resume_from` 成为可见的 schema 错误,
     // 而不是被静默忽略后变成一次全价重跑。
     // 而不是被静默忽略后变成一次全价重跑。
@@ -480,6 +482,26 @@ export const CreateWorkflowOutputSchema = z
     status: z.literal("backgrounded").optional(),
     status: z.literal("backgrounded").optional(),
     /** 后台任务 id ≡ taskId ≡ runId(取消与状态查询都以它为键)。 */
     /** 后台任务 id ≡ taskId ≡ runId(取消与状态查询都以它为键)。 */
     backgroundTaskId: z.string().min(1).optional(),
     backgroundTaskId: z.string().min(1).optional(),
+    /**
+     * `AmendWorkflow` 只改并发、就地生效时才在场:**没有**新 run,所以既没有 `status: "backgrounded"` 也没有
+     * `backgroundTaskId`,run 还是调用里那一个。
+     *
+     * 是一个显式的块而不是让消费方按形状去猜:「ok 且没有 status」在这个工具上还有别的来路
+     * (没有 run 端口时的「只 typecheck」)。数都是绝对值,`maxConcurrency === ceiling` 即
+     * 「这个 run 没有自己的界」。
+     *
+     * ⚠ 这条事实**不跨 v4**:协议的 `toolOutputSchema` 只带 `text` / `display` / `truncated`,
+     * 所以它服务的是 CLI/TUI、进程内消费方,桌面 UI 读不到它。
+     */
+    retuned: z
+      .object({
+        runId: z.string().min(1),
+        maxConcurrency: z.number().int().positive(),
+        previous: z.number().int().positive(),
+        ceiling: z.number().int().positive(),
+      })
+      .strict()
+      .optional(),
   })
   })
   .strict();
   .strict();
 
 

+ 3 - 13
apps/zcode-cli/packages/contracts/src/tools/eval-workflow-snippet.ts

@@ -21,15 +21,7 @@ export const EVAL_WORKFLOW_SNIPPET_SOURCE_ERROR =
 
 
 export const EvalWorkflowSnippetInputSchema = z
 export const EvalWorkflowSnippetInputSchema = z
   .object({
   .object({
-    code: z
-      .string()
-      .min(1)
-      .optional()
-      .describe(
-        "TypeScript snippet written against the snippet facade (files.*, git.*, log, " +
-          "plain interface declarations, top-level await and return). No agent()/report(). " +
-          "Provide this OR `path`, never both.",
-      ),
+    code: z.string().min(1).optional().describe("The snippet, inline. This OR `path`, never both."),
     /**
     /**
      * 片段的第二条来源。**整个文件就是代码**:
      * 片段的第二条来源。**整个文件就是代码**:
      * 片段没有保存定义那套语义,一段恰好以 `/* zcode-workflow` 开头的文件也不该被当成声明块剥掉。
      * 片段没有保存定义那套语义,一段恰好以 `/* zcode-workflow` 开头的文件也不该被当成声明块剥掉。
@@ -38,16 +30,14 @@ export const EvalWorkflowSnippetInputSchema = z
       .string()
       .string()
       .min(1)
       .min(1)
       .optional()
       .optional()
-      .describe(
-        "A file holding the snippet, relative to the working directory or absolute. Provide this OR `code`, never both. The whole file is the snippet; it is read as-is, with no metadata block handling.",
-      ),
+      .describe("A file holding the snippet, read whole. This OR `code`, never both."),
     timeoutMs: z
     timeoutMs: z
       .number()
       .number()
       .int()
       .int()
       .min(EVAL_WORKFLOW_SNIPPET_MIN_TIMEOUT_MS)
       .min(EVAL_WORKFLOW_SNIPPET_MIN_TIMEOUT_MS)
       .max(EVAL_WORKFLOW_SNIPPET_MAX_TIMEOUT_MS)
       .max(EVAL_WORKFLOW_SNIPPET_MAX_TIMEOUT_MS)
       .optional()
       .optional()
-      .describe("Wall-clock timeout for the whole snippet in milliseconds. Default 60000."),
+      .describe("Wall clock for the whole snippet, in ms. Default 60000, at most 600000."),
   })
   })
   .strict();
   .strict();
 
 

+ 7 - 16
apps/zcode-cli/packages/contracts/src/tools/save-workflow.ts

@@ -32,26 +32,17 @@ export const SaveWorkflowInputSchema = z
       .string()
       .string()
       .min(1)
       .min(1)
       .max(SAVED_WORKFLOW_MAX_NAME_CHARS)
       .max(SAVED_WORKFLOW_MAX_NAME_CHARS)
-      .describe(
-        "File-safe identifier the workflow will be recalled by. Letters, digits, dot, dash and underscore only.",
-      ),
-    description: z
-      .string()
-      .min(1)
-      .describe("One line saying what the workflow does. Shown wherever the workflow is listed."),
-    whenToUse: z
-      .string()
-      .min(1)
-      .optional()
-      .describe("Optional guidance on the situations this workflow is the right answer to."),
+      .describe("File-safe identifier: letters, digits, dot, dash and underscore."),
+    description: z.string().min(1).describe("One line saying what the workflow does."),
+    whenToUse: z.string().min(1).optional().describe("When this workflow is the right answer."),
     args: SavedWorkflowArgsDeclarationSchema.optional().describe(
     args: SavedWorkflowArgsDeclarationSchema.optional().describe(
-      "Optional argument declarations. The script reads validated values off the `args` global.",
+      "Argument declarations the script reads off `args`.",
     ),
     ),
     script: z
     script: z
       .string()
       .string()
       .optional()
       .optional()
       .describe(
       .describe(
-        "Full TypeScript workflow script written against the dynamic-workflow facade, exactly as CreateWorkflow takes it. Body only — do not include a metadata block. Provide this OR `script_path`, never both.",
+        "The script body, inline, without a metadata block. This OR `script_path`, never both.",
       ),
       ),
     /**
     /**
      * 正文的第二条来源:一个已经在盘上的文件,
      * 正文的第二条来源:一个已经在盘上的文件,
@@ -63,12 +54,12 @@ export const SaveWorkflowInputSchema = z
       .min(1)
       .min(1)
       .optional()
       .optional()
       .describe(
       .describe(
-        "The file holding the script body, relative to the working directory or absolute — usually a draft a CreateWorkflow/AmendWorkflow result named. Provide this OR `script`, never both; it saves a working draft without re-emitting it. A `/* zcode-workflow` block in that file is dropped: the metadata comes from this call's `description` / `whenToUse` / `args`.",
+        "A file holding the script body, usually a draft a result named. This OR `script`, never both.",
       ),
       ),
     // 作用域由**模型**说出,不由系统猜——没有默认值,每次都要判断。判据中性:脚本是否
     // 作用域由**模型**说出,不由系统猜——没有默认值,每次都要判断。判据中性:脚本是否
     // 引用本仓库的东西?是 → project,否 → global。
     // 引用本仓库的东西?是 → project,否 → global。
     scope: SavedWorkflowScopeSchema.describe(
     scope: SavedWorkflowScopeSchema.describe(
-      'Where the workflow is saved. "project" when the script references this repository\'s files, commands, conventions or directory layout; "global" when it depends on nothing in this project and should be available from every project (saved under ~/.zcode/workflows). Decide every time; there is no default.',
+      '"project" when the script depends on this repository; "global" when it depends on nothing in it. Required, no default.',
     ),
     ),
     // ——以下三个字段由 `resolveInput` 解析回填,模型不填——
     // ——以下三个字段由 `resolveInput` 解析回填,模型不填——
     // 它们是**确认窗要展示的事实**:这次保存落到哪个文件、是不是一次覆盖、是否遮蔽了另一档。
     // 它们是**确认窗要展示的事实**:这次保存落到哪个文件、是不是一次覆盖、是否遮蔽了另一档。

+ 54 - 0
apps/zcode-cli/packages/core/src/agent/loaded-skills.ts

@@ -0,0 +1,54 @@
+// ============================================================
+// 「这段历史里加载过某个技能吗」
+// ============================================================
+// 工作流创作工具的技能门(tool/handlers/workflow-skill-gate.ts)问的是这一句。判据刻意取自
+// runtime 的 provider 可见历史,而不是另立一个会话级 Set:历史就是模型此刻记得的东西——
+// compaction 把那次 Skill 调用挤出去,技能正文也一起不在了,门理应重新关上;resume / rewind
+// 重建历史时,答案随之重建,不需要第二套 hydration。
+
+import type { RuntimeMessageEntry } from "./message-history.js";
+
+const SKILL_TOOL_NAME = "Skill";
+
+/**
+ * 历史里是否有一次**成功完成**的 `Skill` 调用加载了 `skillName`。
+ *
+ * 成功 = assistant 发出的调用有对应的 tool 结果条目且不是错误。只发出没结果(还在跑、被拒)
+ * 或结果 `isError` 都不算。技能名同时认当前形 `{ skill }` 与旧形 `{ name }`
+ * (contracts 的 SkillInputSchema 两种都收)。
+ */
+export function sessionHasLoadedSkill(
+  entries: readonly RuntimeMessageEntry[],
+  skillName: string,
+): boolean {
+  const pendingCallIds = new Set<string>();
+  for (const entry of entries) {
+    if (entry.kind === "attachment") continue;
+    const message = entry.message;
+    if (message.role === "assistant") {
+      for (const call of message.toolCalls ?? []) {
+        if (call.name === SKILL_TOOL_NAME && skillInputNames(call.input) === skillName) {
+          pendingCallIds.add(call.id);
+        }
+      }
+      continue;
+    }
+    if (
+      message.role === "tool" &&
+      message.toolCallId !== undefined &&
+      pendingCallIds.has(message.toolCallId) &&
+      message.isError !== true
+    ) {
+      return true;
+    }
+  }
+  return false;
+}
+
+function skillInputNames(input: unknown): string | undefined {
+  if (input === null || typeof input !== "object") return undefined;
+  const fields = input as { skill?: unknown; name?: unknown };
+  if (typeof fields.skill === "string") return fields.skill;
+  if (typeof fields.name === "string") return fields.name;
+  return undefined;
+}

+ 9 - 7
apps/zcode-cli/packages/core/src/agent/read-file-state-hydrator.ts

@@ -1,9 +1,4 @@
-import type {
-  MessageId,
-  MessagePart,
-  MessageWithParts,
-  ToolPart,
-} from "@zcode/contracts";
+import type { MessageId, MessagePart, MessageWithParts, ToolPart } from "@zcode/contracts";
 import {
 import {
   parseReadFileStateMetadata,
   parseReadFileStateMetadata,
   type PersistedReadFileStateTool,
   type PersistedReadFileStateTool,
@@ -71,6 +66,14 @@ export async function hydrateReadFileStateFromSession(input: {
       if (part.tool === "Edit") {
       if (part.tool === "Edit") {
         const restored = restoreMetadataToolState(input.readFileState, part, "Edit");
         const restored = restoreMetadataToolState(input.readFileState, part, "Edit");
         if (restored) result.restoredCount++;
         if (restored) result.restoredCount++;
+        continue;
+      }
+
+      // 内联草稿:模型亲手写的字节,与 Write 同一条恢复路径。不带 metadata 的 part(saved 拷贝、
+      // `path` 提交、沿用的脚本)在 restoreMetadataToolState 里自然落空。
+      if (part.tool === "CreateWorkflow" || part.tool === "AmendWorkflow") {
+        const restored = restoreMetadataToolState(input.readFileState, part, part.tool);
+        if (restored) result.restoredCount++;
       }
       }
     }
     }
   }
   }
@@ -88,7 +91,6 @@ function restoreReadToolState(
   const toolInput = asRecord(part.state.input);
   const toolInput = asRecord(part.state.input);
   if (!toolInput) return false;
   if (!toolInput) return false;
   if (!isHistoricalFullReadWindow(toolInput as HistoricalReadWindow)) {
   if (!isHistoricalFullReadWindow(toolInput as HistoricalReadWindow)) {
-
     // 真正的 range Read 只在同一 runtime 内作为最新水位,跨 resume 不恢复。
     // 真正的 range Read 只在同一 runtime 内作为最新水位,跨 resume 不恢复。
     result.skippedRangeReadCount++;
     result.skippedRangeReadCount++;
     return false;
     return false;

+ 4 - 7
apps/zcode-cli/packages/core/src/permission/service.ts

@@ -4,6 +4,7 @@
 
 
 import {
 import {
   AMEND_WORKFLOW_TOOL_NAME,
   AMEND_WORKFLOW_TOOL_NAME,
+  isAmendWorkflowOwnedPredecessor,
   PermissionCapabilityGroup,
   PermissionCapabilityGroup,
   type PermissionCapabilityGroup as PermissionCapabilityGroupType,
   type PermissionCapabilityGroup as PermissionCapabilityGroupType,
   type PermissionRuleValue,
   type PermissionRuleValue,
@@ -93,7 +94,6 @@ export class PermissionService {
     this.sessionRules = applyPermissionUpdates(this.sessionRules, updates);
     this.sessionRules = applyPermissionUpdates(this.sessionRules, updates);
   }
   }
 
 
-
   checkPermission(
   checkPermission(
     context: PermissionContext,
     context: PermissionContext,
     toolCapability?: PermissionToolCapability,
     toolCapability?: PermissionToolCapability,
@@ -395,10 +395,8 @@ export class PermissionService {
   private isOwnedWorkflowAmend(context: PermissionContext): boolean {
   private isOwnedWorkflowAmend(context: PermissionContext): boolean {
     if (context.toolName !== AMEND_WORKFLOW_TOOL_NAME) return false;
     if (context.toolName !== AMEND_WORKFLOW_TOOL_NAME) return false;
     if (!context.input || typeof context.input !== "object") return false;
     if (!context.input || typeof context.input !== "object") return false;
-    const predecessor = (context.input as Record<string, unknown>).predecessor;
-    if (!predecessor || typeof predecessor !== "object") return false;
-    const facts = predecessor as Record<string, unknown>;
-    return facts.owned_by_this_session === true && facts.stop_reason !== "user";
+    // 谓词本体住在契约里:就地调并发落回修订时读的必须是同一条规则,不能各写一遍。
+    return isAmendWorkflowOwnedPredecessor((context.input as Record<string, unknown>).predecessor);
   }
   }
 
 
   private checkPlanMode(
   private checkPlanMode(
@@ -586,8 +584,7 @@ export class PermissionService {
   ): ResolvedPermissionCapability {
   ): ResolvedPermissionCapability {
     return {
     return {
       allowedInPlanMode: toolCapability?.allowedInPlanMode ?? false,
       allowedInPlanMode: toolCapability?.allowedInPlanMode ?? false,
-      alwaysAsk:
-        toolCapability?.permission?.alwaysAsk ?? toolCapability?.alwaysAsk ?? false,
+      alwaysAsk: toolCapability?.permission?.alwaysAsk ?? toolCapability?.alwaysAsk ?? false,
       readOnly: toolCapability?.readOnly ?? this.isReadOnlyTool(context.toolName),
       readOnly: toolCapability?.readOnly ?? this.isReadOnlyTool(context.toolName),
       destructive: toolCapability?.destructive ?? this.isDestructiveTool(context.toolName),
       destructive: toolCapability?.destructive ?? this.isDestructiveTool(context.toolName),
       requiresUserInteraction:
       requiresUserInteraction:

+ 10 - 0
apps/zcode-cli/packages/core/src/runtime/helpers/runtime-tools.ts

@@ -21,6 +21,7 @@ import {
 } from "./tool-allowlist.js";
 } from "./tool-allowlist.js";
 import { isStaleBranchRuntimeTaskEvent } from "../methods/runtime-command-generation.js";
 import { isStaleBranchRuntimeTaskEvent } from "../methods/runtime-command-generation.js";
 import { resolveEnabledProjectMemoryRoot } from "./project-memory.js";
 import { resolveEnabledProjectMemoryRoot } from "./project-memory.js";
+import { sessionHasLoadedSkill } from "../../agent/loaded-skills.js";
 
 
 const DEFAULT_SUBAGENT_BACKGROUND_BASH_MAX_MS = 3_600_000;
 const DEFAULT_SUBAGENT_BACKGROUND_BASH_MAX_MS = 3_600_000;
 const EMPTY_RUNTIME_HOOK_CONFIG = {
 const EMPTY_RUNTIME_HOOK_CONFIG = {
@@ -197,6 +198,15 @@ function createRuntimeToolExecutor(
     modelCatalogPort: deps.modelCatalogPort,
     modelCatalogPort: deps.modelCatalogPort,
     runtimeTaskRegistry: runtime.runtimeTaskRegistry,
     runtimeTaskRegistry: runtime.runtimeTaskRegistry,
     readFileState: runtime.readFileState,
     readFileState: runtime.readFileState,
+    // 工作流创作工具的技能门(tool/handlers/workflow-skill-gate.ts):按模型此刻看得见的历史回答
+    // 「读过技能没有」。只在会话真有 Skill 工具时给探针——没有 skillPort 的会话装不上那个技能,
+    // 门若仍然在场就成了一道谁也过不去的墙。
+    ...(deps.skillPort === undefined
+      ? {}
+      : {
+          hasLoadedSkill: (skillName: string) =>
+            sessionHasLoadedSkill(runtime.messageHistory.borrowReadOnlyRuntimeEntries(), skillName),
+        }),
     subagentBackgroundBashMaxMs:
     subagentBackgroundBashMaxMs:
       runtime.config.taskType === "subagent_child"
       runtime.config.taskType === "subagent_child"
         ? normalizeSubagentBackgroundBashMaxMs(runtime.config.subagents?.backgroundBashMaxMs)
         ? normalizeSubagentBackgroundBashMaxMs(runtime.config.subagents?.backgroundBashMaxMs)

+ 5 - 6
apps/zcode-cli/packages/core/src/runtime/helpers/tool-allowlist.ts

@@ -62,15 +62,14 @@ export function resolveRuntimeDisallowedTools(
 }
 }
 
 
 /**
 /**
- * 动态工作流灰度门在 registerBuiltInTools 上的取值。
- * **缺席即开启**:TUI、headless `-p` 和 workflow_child 都不写这个字段,它们必须保留完整工具面;
- * 只有受信 Host 创建的 protocol session 会显式写 false。fail-closed 的缺省值在协议服务端的
- * appRuntimePreferences,不在这一层。
+ * 动态工作流开关在 registerBuiltInTools 上的取值。
+ * **缺席即开启**:TUI 保留默认工具面;headless 根据 --enable-workflow 显式写 true/false,
+ * protocol session 由受信 Host 控制,workflow_child 继承父配置。fail-closed 的缺省值在
+ * headless 入口和协议服务端的 appRuntimePreferences,不在这一层。
  *
  *
  * 之所以和 resolveRuntimeDisallowedTools 一样收在这里而不是写在调用点:注册面有**两个**入口
  * 之所以和 resolveRuntimeDisallowedTools 一样收在这里而不是写在调用点:注册面有**两个**入口
  * (helpers/runtime-tools.ts 的首次装配、methods/embedded-search-branch.ts 的分支刷新),
  * (helpers/runtime-tools.ts 的首次装配、methods/embedded-search-branch.ts 的分支刷新),
- * 两份各写一遍必然漂移。就漂过一次——刷新那份漏掉了这个字段,于是
- * 「缺席即开启」把十个工具原样加回注册表,灰度关闭的会话里模型仍然调到了 ListSavedWorkflows。
+ * 两个入口必须使用同一规则,否则刷新工具列表时可能重新注册已关闭的工作流工具。
  */
  */
 export function resolveRuntimeDynamicWorkflowToolsIncluded(config: AgentRuntimeConfig): boolean {
 export function resolveRuntimeDynamicWorkflowToolsIncluded(config: AgentRuntimeConfig): boolean {
   return config.dynamicWorkflowEnabled !== false;
   return config.dynamicWorkflowEnabled !== false;

+ 119 - 0
apps/zcode-cli/packages/core/src/runtime/methods/dynamic-workflow-run-settings-turn.ts

@@ -0,0 +1,119 @@
+// GUI 配置变更的会话记录。
+// 将设置轮排入运行时队列,记录两项设置的 from/to,并区分修订产生新 run 与并发调整就地生效。
+// 变更决策和副作用顺序由 dynamic-workflow-run-settings.ts 负责。
+
+import type { TraceContext, WorkflowSettingsAmendMeta } from "@zcode/contracts";
+import type { DynamicWorkflowRunSnapshot } from "@zcode/contracts";
+import { uuidv7 } from "@zcode/shared";
+import { createRuntimeCommandId } from "../command-queue.js";
+import type { AgentRuntimeInternal } from "../internal.js";
+import type { boundWorkflowLaunchMeta } from "@zcode/contracts";
+
+/** 本 run 的两项设置的归一形:缺席即默认(会话模型 / 本机上限)。 */
+export interface RunSettings {
+  subagentModel?: string;
+  maxConcurrency?: number;
+}
+
+/**
+ * 设置轮不在命令处理里直接落:主代理可能正在一轮里,user 消息插不进去。排进运行时队列,空闲时
+ * 立即跑、忙时等当前轮结束;与通知同优先级,因而先于新 run 的任何通知。
+ */
+export function enqueueSettingsTurn(
+  this: AgentRuntimeInternal,
+  turn: {
+    text: string;
+    meta: ReturnType<typeof boundWorkflowLaunchMeta>;
+    titleInput: string;
+    traceContext: TraceContext;
+  },
+): void {
+  this.enqueueRuntimeCommand({
+    branchGeneration: this.branchGeneration,
+    createdAt: new Date(),
+    id: createRuntimeCommandId(),
+    inputId: uuidv7(),
+    mode: "control-only-turn",
+    priority: "next",
+    text: turn.text,
+    titleInput: turn.titleInput,
+    traceContext: turn.traceContext,
+    workflowLaunch: turn.meta,
+  });
+}
+
+export function fromTo<T>(from: T | undefined, to: T | undefined): { from?: T; to?: T } {
+  return { ...(from === undefined ? {} : { from }), ...(to === undefined ? {} : { to }) };
+}
+
+/**
+ * 设置轮的模型面规范句(英文,不本地化——它进 provider transcript)。只说改过的设置;两个 `null`
+ * 各有一句话。末句劝阻模型再动这个 run:它已经在跑,进展以通知回来。
+ *
+ * 两种结局在这里分岔,判据就是 `amend.predecessorRunId` 在不在场(缺席即就地生效,与元数据同
+ * 一条读法):修订出了一个新 run,就地调并发则还是同一个 run——照修订那句话写下去,模型会去找
+ * 一个根本不存在的 run B。
+ */
+export function buildSettingsMessageText(input: {
+  name?: string;
+  previous: string;
+  runId: string;
+  superseded: boolean;
+  amend: WorkflowSettingsAmendMeta;
+}): string {
+  const inPlace = input.amend.predecessorRunId === undefined;
+  const lead = `Changed the settings of workflow run ${input.previous}${input.name === undefined ? "" : ` ("${input.name}")`} from the GUI: ${settingsChangeClauses(input.amend, inPlace).join("; ")}.`;
+  const closing =
+    "Progress and results arrive as background notifications; do not amend, resume or restart it.";
+  if (inPlace) {
+    const kept =
+      input.amend.maxConcurrency?.to === undefined
+        ? `Run ${input.previous} keeps running with no limit`
+        : `Run ${input.previous} keeps running under the new limit`;
+    return [lead, `${kept}; nothing was stopped and no new run was started.`, closing].join(" ");
+  }
+  const relation = input.superseded ? "supersedes" : "takes over from";
+  return [
+    lead,
+    `The same script continues as run ${input.runId}, which ${relation} run ${input.previous} and imports everything run ${input.previous} finished as cache.`,
+    closing,
+  ].join(" ");
+}
+
+/**
+ * 「改了什么」的分句。就地生效那一条要把主语说全(「at most n of **its subagents**」):那条路上
+ * 没有模型分句在前,一句「at most n of them」就没有了指代对象。
+ */
+function settingsChangeClauses(amend: WorkflowSettingsAmendMeta, inPlace: boolean): string[] {
+  const changes: string[] = [];
+  const model = amend.subagentModel;
+  if (model !== undefined) {
+    changes.push(
+      model.to === undefined
+        ? "its subagents are back on the session model"
+        : `its subagents now run on ${model.to}`,
+    );
+  }
+  const bound = amend.maxConcurrency;
+  if (bound !== undefined) {
+    changes.push(
+      bound.to === undefined
+        ? "the limit on subagents at once is removed"
+        : inPlace
+          ? `at most ${bound.to} of its subagents run at once`
+          : `at most ${bound.to} of them run at once`,
+    );
+  }
+  return changes;
+}
+
+/**
+ * 快照上的两项设置。两者都「无则缺席」:没指定过模型 = 会话模型,界不低于天花板 = 没有自己的界,
+ * 所以缺席就是默认,与 {@link RunSettings} 同一个读法。
+ */
+export function runSettingsOfSnapshot(snapshot: DynamicWorkflowRunSnapshot): RunSettings {
+  return {
+    ...(snapshot.subagentModel === undefined ? {} : { subagentModel: snapshot.subagentModel }),
+    ...(snapshot.maxConcurrency === undefined ? {} : { maxConcurrency: snapshot.maxConcurrency }),
+  };
+}

+ 110 - 94
apps/zcode-cli/packages/core/src/runtime/methods/dynamic-workflow-run-settings.ts

@@ -4,11 +4,10 @@ import {
   boundWorkflowLaunchMeta,
   boundWorkflowLaunchMeta,
   createWorkflowPhaseAlongside,
   createWorkflowPhaseAlongside,
   createWorkflowPhaseNames,
   createWorkflowPhaseNames,
-  type DynamicWorkflowRunSnapshot,
+  type DynamicWorkflowRunRetuneResult,
   type TraceContext,
   type TraceContext,
   type WorkflowSettingsAmendMeta,
   type WorkflowSettingsAmendMeta,
 } from "@zcode/contracts";
 } from "@zcode/contracts";
-import { uuidv7 } from "@zcode/shared";
 import {
 import {
   resolveAmendMaxConcurrency,
   resolveAmendMaxConcurrency,
   resolveAmendSubagentModelChoice,
   resolveAmendSubagentModelChoice,
@@ -25,10 +24,18 @@ import {
 } from "../../tool/handlers/workflow-drafts.js";
 } from "../../tool/handlers/workflow-drafts.js";
 import { analyzeScript } from "../../tool/handlers/workflow-script-analysis.js";
 import { analyzeScript } from "../../tool/handlers/workflow-script-analysis.js";
 import type { ExecutableToolCall } from "../../tool/types.js";
 import type { ExecutableToolCall } from "../../tool/types.js";
-import { createRuntimeCommandId } from "../command-queue.js";
 import { traceContextToLogContext } from "../deps.js";
 import { traceContextToLogContext } from "../deps.js";
 import type { AgentRuntimeInternal } from "../internal.js";
 import type { AgentRuntimeInternal } from "../internal.js";
 import { boundedCompileDiagnostics } from "./dynamic-workflow-run-start.js";
 import { boundedCompileDiagnostics } from "./dynamic-workflow-run-start.js";
+import {
+  buildSettingsMessageText,
+  enqueueSettingsTurn,
+  fromTo,
+  runSettingsOfSnapshot,
+  type RunSettings,
+} from "./dynamic-workflow-run-settings-turn.js";
+
+export { buildSettingsMessageText } from "./dynamic-workflow-run-settings-turn.js";
 
 
 /**
 /**
  * GUI「配置」的请求。两项设置守工具的三态:
  * GUI「配置」的请求。两项设置守工具的三态:
@@ -56,22 +63,19 @@ export type AmendWorkflowRunSettingsResult =
   | { ok: true; runId: string; toolCallId: string; supersededRunId?: string }
   | { ok: true; runId: string; toolCallId: string; supersededRunId?: string }
   | { ok: false; reason: AmendWorkflowRunSettingsRejection; message?: string };
   | { ok: false; reason: AmendWorkflowRunSettingsRejection; message?: string };
 
 
-/** 本 run 的两项设置的归一形:缺席即默认(会话模型 / 本机上限)。 */
-interface RunSettings {
-  subagentModel?: string;
-  maxConcurrency?: number;
-}
-
 /**
 /**
  * GUI「配置」:以同一份脚本、新的设置修订一个 run。
  * GUI「配置」:以同一份脚本、新的设置修订一个 run。
  *
  *
- * 它是 `port.amend` 的**第二个调用方**,与 `AmendWorkflow` 工具同构:同一段三态归一
- * (`resolveAmendSubagentModelChoice` / `resolveAmendMaxConcurrency`,不复制)、同一个编译、同一个
- * 后台追踪器(合成一个 AmendWorkflow 描述子)。区别只在:不经模型轮、不开确认窗(用户在弹层里
- * 点「应用」就是同意,脚本也是他批准过的那一份),实参沿用前驱(`inheritArgs`),并用一条排队的
- * controlOnly「设置轮」把这件事记进会话。
+ * 它是 `port.amend` 与 `port.retuneConcurrency` 的**第二个调用方**,与 `AmendWorkflow` 工具同构:
+ * 同一段三态归一(`resolveAmendSubagentModelChoice` / `resolveAmendMaxConcurrency`,不复制)、同一条
+ * 路由、同一个编译、同一个后台追踪器(合成一个 AmendWorkflow 描述子)。区别只在:不经模型轮、不开
+ * 确认窗(用户在弹层里点「应用」就是同意,脚本也是他批准过的那一份),实参沿用前驱
+ * (`inheritArgs`),并用一条排队的 controlOnly「设置轮」把这件事记进会话。
  *
  *
- * 顺序固定:直到 `port.amend` 之前的每一步失败都是零副作用——旧 run 照旧在跑、没有新行、没有消息。
+ * 只改并发、run 又还在飞时在下面那个分叉处**就地生效**:同一个 runId、不停、不铸后继。
+ *
+ * 顺序固定:直到 `port.amend` / `port.retuneConcurrency` 之前的每一步失败都是零副作用——旧 run
+ * 照旧在跑、没有新行、没有消息。
  */
  */
 export async function amendWorkflowRunSettings(
 export async function amendWorkflowRunSettings(
   this: AgentRuntimeInternal,
   this: AgentRuntimeInternal,
@@ -93,14 +97,7 @@ export async function amendWorkflowRunSettings(
   if (snapshot.runStatus === "completed" || snapshot.supersededBy !== undefined) {
   if (snapshot.runStatus === "completed" || snapshot.supersededBy !== undefined) {
     return { ok: false, reason: "not_configurable" };
     return { ok: false, reason: "not_configurable" };
   }
   }
-  // (3) 沿用的脚本(「Keeping the predecessor's script」同一条读路)。
-  const script =
-    typeof port.getScript === "function" ? await port.getScript(input.runId) : undefined;
-  if (script === undefined || script.length === 0) {
-    return { ok: false, reason: "script_missing" };
-  }
-
-  // (4)(5) 两项设置的三态归一,与工具同一段代码。
+  // (3)(4) 两项设置的三态归一,与工具同一段代码。
   const current = runSettingsOfSnapshot(snapshot);
   const current = runSettingsOfSnapshot(snapshot);
   const model = resolveAmendSubagentModelChoice(
   const model = resolveAmendSubagentModelChoice(
     input.subagentModel,
     input.subagentModel,
@@ -128,12 +125,41 @@ export async function amendWorkflowRunSettings(
     ...(model.canonical === undefined ? {} : { subagentModel: model.canonical }),
     ...(model.canonical === undefined ? {} : { subagentModel: model.canonical }),
     ...(nextBound === undefined ? {} : { maxConcurrency: nextBound }),
     ...(nextBound === undefined ? {} : { maxConcurrency: nextBound }),
   };
   };
-  // (6) 什么都没变就不起新 run:一次修订会停下在飞的 run,没有理由为零改动付这个代价。
+  // (5) 什么都没变就不起新 run:一次修订会停下在飞的 run,没有理由为零改动付这个代价。
   const modelChanged = next.subagentModel !== current.subagentModel;
   const modelChanged = next.subagentModel !== current.subagentModel;
   const boundChanged = next.maxConcurrency !== current.maxConcurrency;
   const boundChanged = next.maxConcurrency !== current.maxConcurrency;
   if (!modelChanged && !boundChanged) return { ok: false, reason: "unchanged" };
   if (!modelChanged && !boundChanged) return { ok: false, reason: "unchanged" };
 
 
-  // (7) 编译。存下的脚本可能是在更早的 facade 上写的;编不过就停在这里,旧 run 不动。
+  // (6) 分叉:只有并发变了、run 又在飞,就地
+  // 生效——同一个 runId,不停、不铸后继、不导入缓存。端口答 not_live(已结算,或 pending 但引擎
+  // 还没建)就顺着这张表往下走,落成今天那次修订。
+  if (boundChanged && !modelChanged && typeof port.retuneConcurrency === "function") {
+    // 弹层的 `null` 原样递到端口:天花板那个数只有端口知道,这里不猜第二遍。缺席只可能来自
+    // 「沿用的界高过本机天花板」(run 是在更大的机器上起的),那时要的也正是回到天花板。
+    const answer = await port.retuneConcurrency({
+      runId: input.runId,
+      maxConcurrency: input.maxConcurrency ?? null,
+    });
+    if (answer.ok) {
+      return retunedSettings.call(this, {
+        answer,
+        name: displayNameOfSnapshot(snapshot),
+        runId: input.runId,
+        traceContext,
+      });
+    }
+    if (answer.reason === "unchanged") return { ok: false, reason: "unchanged" };
+  }
+
+  // (7) 沿用的脚本(「Keeping the predecessor's script」同一条读路)。读在分叉**之后**:就地调
+  // 并发跑的还是同一段脚本,一个没有存档脚本、或脚本已经编不过的 run 因此照样调得动上界。
+  const script =
+    typeof port.getScript === "function" ? await port.getScript(input.runId) : undefined;
+  if (script === undefined || script.length === 0) {
+    return { ok: false, reason: "script_missing" };
+  }
+
+  // (8) 编译。存下的脚本可能是在更早的 facade 上写的;编不过就停在这里,旧 run 不动。
   const analysis = analyzeScript(script);
   const analysis = analyzeScript(script);
   if (!analysis.ok || analysis.diagnostics.length > 0) {
   if (!analysis.ok || analysis.diagnostics.length > 0) {
     return {
     return {
@@ -207,8 +233,7 @@ export async function amendWorkflowRunSettings(
   // 名字只取 run 自己的:没起过名的 run 就不带名字,卡片、侧板与通知照任何无名 run 的规矩换用兜底词。
   // 名字只取 run 自己的:没起过名的 run 就不带名字,卡片、侧板与通知照任何无名 run 的规矩换用兜底词。
   // 这里曾兜底成 `run <id>`,设置轮的卡片与侧板标题于是成了一串 run id,
   // 这里曾兜底成 `run <id>`,设置轮的卡片与侧板标题于是成了一串 run id,
   // 而且这个假名会沿修订链一路传下去。
   // 而且这个假名会沿修订链一路传下去。
-  const trimmedName = snapshot.name?.trim();
-  const name = trimmedName === undefined || trimmedName.length === 0 ? undefined : trimmedName;
+  const name = displayNameOfSnapshot(snapshot);
   const amend: WorkflowSettingsAmendMeta = {
   const amend: WorkflowSettingsAmendMeta = {
     predecessorRunId: input.runId,
     predecessorRunId: input.runId,
     ...(modelChanged ? { subagentModel: fromTo(current.subagentModel, next.subagentModel) } : {}),
     ...(modelChanged ? { subagentModel: fromTo(current.subagentModel, next.subagentModel) } : {}),
@@ -278,79 +303,70 @@ export async function amendWorkflowRunSettings(
 }
 }
 
 
 /**
 /**
- * 设置轮不在命令处理里直接落:主代理可能正在一轮里,user 消息插不进去。排进运行时队列,空闲时
- * 立即跑、忙时等当前轮结束;与通知同优先级,因而先于新 run 的任何通知。
+ * 就地生效的收尾:同一个 runId、没有
+ * `supersededRunId`,**不登记第二个后台任务**——这个 run 本来就在追踪器里,再登记一次会按
+ * AmendWorkflow 的 rearm 规则把一个从没停过的 run 的结算面清空。
+ *
+ * 设置轮照记,但 `amend` 块不带 `predecessorRunId`:缺席即「就地生效」,渲染端据此只画一行、
+ * 不再画一张 run 卡(同一个 run 两张卡会读成两次运行)。也没有 `display`——这条路不编译。
  */
  */
-function enqueueSettingsTurn(
+function retunedSettings(
   this: AgentRuntimeInternal,
   this: AgentRuntimeInternal,
-  turn: {
-    text: string;
-    meta: ReturnType<typeof boundWorkflowLaunchMeta>;
-    titleInput: string;
+  options: {
+    answer: Extract<DynamicWorkflowRunRetuneResult, { ok: true }>;
+    name: string | undefined;
+    runId: string;
     traceContext: TraceContext;
     traceContext: TraceContext;
   },
   },
-): void {
-  this.enqueueRuntimeCommand({
-    branchGeneration: this.branchGeneration,
-    createdAt: new Date(),
-    id: createRuntimeCommandId(),
-    inputId: uuidv7(),
-    mode: "control-only-turn",
-    priority: "next",
-    text: turn.text,
-    titleInput: turn.titleInput,
-    traceContext: turn.traceContext,
-    workflowLaunch: turn.meta,
-  });
-}
-
-function fromTo<T>(from: T | undefined, to: T | undefined): { from?: T; to?: T } {
-  return { ...(from === undefined ? {} : { from }), ...(to === undefined ? {} : { to }) };
-}
-
-/**
- * 设置轮的模型面规范句(英文,不本地化——它进 provider transcript)。只说改过的设置;两个 `null`
- * 各有一句话。末句劝阻模型再动这个 run:它已经在跑,进展以通知回来。
- */
-function buildSettingsMessageText(input: {
-  name?: string;
-  previous: string;
-  runId: string;
-  superseded: boolean;
-  amend: WorkflowSettingsAmendMeta;
-}): string {
-  const changes: string[] = [];
-  const model = input.amend.subagentModel;
-  if (model !== undefined) {
-    changes.push(
-      model.to === undefined
-        ? "its subagents are back on the session model"
-        : `its subagents now run on ${model.to}`,
-    );
-  }
-  const bound = input.amend.maxConcurrency;
-  if (bound !== undefined) {
-    changes.push(
-      bound.to === undefined
-        ? "the limit on subagents at once is removed"
-        : `at most ${bound.to} of them run at once`,
+): AmendWorkflowRunSettingsResult {
+  const { answer, name, runId, traceContext } = options;
+  const toolCallId = `settings-${randomUUID()}`;
+  // 等于天花板的那一端就是「默认」,于是整端缺席——与修订那条路同一个读法(弹层把步进器推到顶
+  // 发的是 `null`,端口答回来的却永远是绝对值,折算只能在这里做)。
+  const amend: WorkflowSettingsAmendMeta = {
+    maxConcurrency: fromTo(
+      answer.previous === answer.ceiling ? undefined : answer.previous,
+      answer.maxConcurrency === answer.ceiling ? undefined : answer.maxConcurrency,
+    ),
+    ceiling: answer.ceiling,
+  };
+  try {
+    enqueueSettingsTurn.call(this, {
+      text: buildSettingsMessageText({
+        ...(name === undefined ? {} : { name }),
+        previous: runId,
+        runId,
+        superseded: false,
+        amend,
+      }),
+      meta: boundWorkflowLaunchMeta({
+        runId,
+        toolCallId,
+        ...(name === undefined ? {} : { name }),
+        amend,
+      }),
+      titleInput: name ?? runId,
+      traceContext,
+    });
+  } catch (error) {
+    // 记完日志就走:上界**已经**生效了,回滚一条记录换不回它,撤销这次调整更不是用户要的。
+    this.logger?.error(
+      "Workflow run retuned but the settings turn could not be queued",
+      error instanceof Error ? error : new Error(String(error)),
+      {
+        ...traceContextToLogContext(traceContext),
+        event: "dynamic_workflow.settings.post_retune_failed",
+        module: "core.runtime",
+        runId,
+        toolCallId,
+      },
     );
     );
   }
   }
-  const relation = input.superseded ? "supersedes" : "takes over from";
-  return [
-    `Changed the settings of workflow run ${input.previous}${input.name === undefined ? "" : ` ("${input.name}")`} from the GUI: ${changes.join("; ")}.`,
-    `The same script continues as run ${input.runId}, which ${relation} run ${input.previous} and imports everything run ${input.previous} finished as cache.`,
-    "Progress and results arrive as background notifications; do not amend, resume or restart it.",
-  ].join(" ");
+  return { ok: true, runId, toolCallId };
 }
 }
 
 
-/**
- * 快照上的两项设置。两者都「无则缺席」:没指定过模型 = 会话模型,界不低于天花板 = 没有自己的界,
- * 所以缺席就是默认,与 {@link RunSettings} 同一个读法。
- */
-function runSettingsOfSnapshot(snapshot: DynamicWorkflowRunSnapshot): RunSettings {
-  return {
-    ...(snapshot.subagentModel === undefined ? {} : { subagentModel: snapshot.subagentModel }),
-    ...(snapshot.maxConcurrency === undefined ? {} : { maxConcurrency: snapshot.maxConcurrency }),
-  };
+/** run 自己的名字(无名即缺席):设置轮与合成追踪都按这一条,绝不拿 run id 当标题。 */
+function displayNameOfSnapshot(snapshot: { name?: string }): string | undefined {
+  const trimmed = snapshot.name?.trim();
+  return trimmed === undefined || trimmed.length === 0 ? undefined : trimmed;
 }
 }

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

@@ -205,10 +205,10 @@ export interface AgentRuntimeConfig {
   parentSessionId?: SessionId;
   parentSessionId?: SessionId;
   taskType?: SessionTaskType;
   taskType?: SessionTaskType;
   /**
   /**
-   * 动态工作流灰度门:Host 判定后经
-   * ZCode Protocol 下发,runtime 只消费。**缺席即开启**——TUI、headless `-p` 与
-   * workflow_child 都不会设置它,它们必须保留完整工具面;只有受信 Host
-   * 创建的 protocol session 才会显式写 false 把十个工作流工具关掉。
+   * 动态工作流开关:Host 判定后经
+   * ZCode Protocol 下发,runtime 只消费。**缺席即开启**,保留 TUI 默认值;
+   * headless 按 --enable-workflow 显式传 true/false(默认 false),workflow_child 继承父配置。
+   * false 会关闭十个工作流工具,不改变其他工具的注册策略。
    */
    */
   dynamicWorkflowEnabled?: boolean;
   dynamicWorkflowEnabled?: boolean;
 
 

+ 67 - 31
apps/zcode-cli/packages/core/src/tool/executor/background-tasks.ts

@@ -188,18 +188,18 @@ export class BackgroundTaskTracker {
           taskId,
           taskId,
           toolName: toolCall.name,
           toolName: toolCall.name,
         });
         });
-        void Promise.resolve(
-          this.deps.executionPort?.cancelBackgroundTask?.(taskId),
-        ).catch((error) => {
-          this.deps.logger?.warn("Subagent background Bash cancellation failed", {
-            ...traceContextToLogContext(traceContext),
-            errorMessage: error instanceof Error ? error.message : String(error),
-            event: "background_task.subagent_bash.cancel_failed",
-            module: "core.tool.executor",
-            taskId,
-            toolName: toolCall.name,
-          });
-        });
+        void Promise.resolve(this.deps.executionPort?.cancelBackgroundTask?.(taskId)).catch(
+          (error) => {
+            this.deps.logger?.warn("Subagent background Bash cancellation failed", {
+              ...traceContextToLogContext(traceContext),
+              errorMessage: error instanceof Error ? error.message : String(error),
+              event: "background_task.subagent_bash.cancel_failed",
+              module: "core.tool.executor",
+              taskId,
+              toolName: toolCall.name,
+            });
+          },
+        );
       }, this.deps.subagentBackgroundBashMaxMs);
       }, this.deps.subagentBackgroundBashMaxMs);
     }
     }
 
 
@@ -262,13 +262,16 @@ export class BackgroundTaskTracker {
         }
         }
 
 
         if (this.isNotifiedLocalAgentSnapshot(toolCall, snapshot)) {
         if (this.isNotifiedLocalAgentSnapshot(toolCall, snapshot)) {
-          this.deps.logger?.debug?.("Background task terminal notification already handled by subagent", {
-            ...traceContextToLogContext(traceContext),
-            event: "background_task.tracking.notification_already_handled",
-            module: "core.tool.executor",
-            taskId,
-            toolName: toolCall.name,
-          });
+          this.deps.logger?.debug?.(
+            "Background task terminal notification already handled by subagent",
+            {
+              ...traceContextToLogContext(traceContext),
+              event: "background_task.tracking.notification_already_handled",
+              module: "core.tool.executor",
+              taskId,
+              toolName: toolCall.name,
+            },
+          );
           stopped = true;
           stopped = true;
           stopTracking();
           stopTracking();
           return;
           return;
@@ -561,7 +564,13 @@ export class BackgroundTaskTracker {
         // (workflowNotification)在此处发射侧铸造:GUI 渲染的唯一数据源,随 originMeta 走全管线。
         // (workflowNotification)在此处发射侧铸造:GUI 渲染的唯一数据源,随 originMeta 走全管线。
         ...(isDynamicWorkflowRunDispatchToolName(toolCall.name)
         ...(isDynamicWorkflowRunDispatchToolName(toolCall.name)
           ? {
           ? {
-              originMeta: buildWorkflowNotificationOriginMeta(toolCall, taskId, status, snapshot, output),
+              originMeta: buildWorkflowNotificationOriginMeta(
+                toolCall,
+                taskId,
+                status,
+                snapshot,
+                output,
+              ),
             }
             }
           : {}),
           : {}),
         taskId,
         taskId,
@@ -742,7 +751,9 @@ export class BackgroundTaskTracker {
     if (isSubagentDispatchToolName(toolCall.name)) {
     if (isSubagentDispatchToolName(toolCall.name)) {
       const getTask = deps.subagentPort?.getTask;
       const getTask = deps.subagentPort?.getTask;
       return {
       return {
-        ...(getTask ? { getSnapshot: (taskId: string) => getTask.call(deps.subagentPort, taskId) } : {}),
+        ...(getTask
+          ? { getSnapshot: (taskId: string) => getTask.call(deps.subagentPort, taskId) }
+          : {}),
         // background Agent 的停止入口在 subagentPort.stopTask;
         // background Agent 的停止入口在 subagentPort.stopTask;
         // started payload 不能沿用 Bash 的 executionPort 能力判断。
         // started payload 不能沿用 Bash 的 executionPort 能力判断。
         cancellable: Boolean(deps.subagentPort?.stopTask),
         cancellable: Boolean(deps.subagentPort?.stopTask),
@@ -771,7 +782,9 @@ export class BackgroundTaskTracker {
       const getTask = deps.workflowPort?.getTask;
       const getTask = deps.workflowPort?.getTask;
       const waiter = getWorkflowTaskWaiter(deps.workflowPort);
       const waiter = getWorkflowTaskWaiter(deps.workflowPort);
       return {
       return {
-        ...(getTask ? { getSnapshot: (taskId: string) => getTask.call(deps.workflowPort, taskId) } : {}),
+        ...(getTask
+          ? { getSnapshot: (taskId: string) => getTask.call(deps.workflowPort, taskId) }
+          : {}),
         ...(waiter ? { waitForTerminal: (taskId: string) => waiter.waitForTask(taskId) } : {}),
         ...(waiter ? { waitForTerminal: (taskId: string) => waiter.waitForTask(taskId) } : {}),
         cancellable: false,
         cancellable: false,
       };
       };
@@ -830,10 +843,7 @@ function normalizeBackgroundTaskNotificationStatus(status: string): BashTaskNoti
   }
   }
 }
 }
 
 
-function resolveBashBackgroundResultTitle(
-  toolCall: ExecutableToolCall,
-  taskId: string,
-): string {
+function resolveBashBackgroundResultTitle(toolCall: ExecutableToolCall, taskId: string): string {
   const input = isRecord(toolCall.input) ? toolCall.input : {};
   const input = isRecord(toolCall.input) ? toolCall.input : {};
   const description = stringField(input, "description")?.trim();
   const description = stringField(input, "description")?.trim();
   const command = stringField(input, "command")?.trim();
   const command = stringField(input, "command")?.trim();
@@ -1042,7 +1052,9 @@ function buildWorkflowTerminalNotification(
   // 用户面产物的 chips 载荷。这是通知行 chips 的
   // 用户面产物的 chips 载荷。这是通知行 chips 的
   // **唯一**数据源:hydration 冷恢复把它按 shared 的 zod 原样读回,缺一个键就等于 chips 永久
   // **唯一**数据源:hydration 冷恢复把它按 shared 的 zod 原样读回,缺一个键就等于 chips 永久
   // 消失。三个终态一律携带,理由同 reports。
   // 消失。三个终态一律携带,理由同 reports。
-  const artifactsSection = buildWorkflowArtifactsManifestSection(workflowSnapshotArtifacts(snapshot));
+  const artifactsSection = buildWorkflowArtifactsManifestSection(
+    workflowSnapshotArtifacts(snapshot),
+  );
   if (artifactsSection !== undefined) {
   if (artifactsSection !== undefined) {
     meta.artifacts = artifactsSection.artifacts;
     meta.artifacts = artifactsSection.artifacts;
     if (artifactsSection.artifactsTruncated) meta.artifactsTruncated = true;
     if (artifactsSection.artifactsTruncated) meta.artifactsTruncated = true;
@@ -1073,7 +1085,21 @@ function workflowTerminalNotificationStatus(
   }
   }
 }
 }
 
 
-/** `completedAt - startedAt`,两者齐备且差为非负有限数才置(否则整字段缺席)。 */
+/**
+ * 通知里的墙钟时长(完成卡的「时间」格)。
+ *
+ * 两个来源,取**大**者:
+ *   - 本世:`completedAt - startedAt`,结算它的这个进程自己看到的那一段;
+ *   - 整条 lineage 的活动时长:`activeDurationMs`,由端口从 journal 求和(resume 的每一世 +
+ *     沿 `resumedFrom` 的每个前驱),缺席即读不出。
+ *
+ * 只报本次启动的墙钟时长会漏掉之前的运行时间:修订与
+ * resume 各自重开一次进程内时钟,而那一世大半是缓存重放。取大而不是直接取 lineage,是为了守住
+ * 「永不少报本进程亲眼所见」:老 run 的事件早于本记账、journal 读面不在场时 `activeDurationMs`
+ * 缺席,退回本世;而 lineage 值正常总比本世大(它含本世)。
+ *
+ * 两个来源都读不出时整字段缺席(卡上写 `—`),不写 0。
+ */
 function workflowNotificationDurationMs(snapshot: BackgroundTaskSnapshot): number | undefined {
 function workflowNotificationDurationMs(snapshot: BackgroundTaskSnapshot): number | undefined {
   const startedAt =
   const startedAt =
     "startedAt" in snapshot && snapshot.startedAt instanceof Date
     "startedAt" in snapshot && snapshot.startedAt instanceof Date
@@ -1083,9 +1109,19 @@ function workflowNotificationDurationMs(snapshot: BackgroundTaskSnapshot): numbe
     "completedAt" in snapshot && snapshot.completedAt instanceof Date
     "completedAt" in snapshot && snapshot.completedAt instanceof Date
       ? snapshot.completedAt.getTime()
       ? snapshot.completedAt.getTime()
       : undefined;
       : undefined;
-  if (startedAt === undefined || completedAt === undefined) return undefined;
-  const durationMs = completedAt - startedAt;
-  return Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : undefined;
+  const ownLifeMs =
+    startedAt === undefined || completedAt === undefined
+      ? undefined
+      : nonNegativeFinite(completedAt - startedAt);
+  const lineageMs =
+    "activeDurationMs" in snapshot ? nonNegativeFinite(snapshot.activeDurationMs) : undefined;
+  if (ownLifeMs === undefined) return lineageMs;
+  return lineageMs === undefined ? ownLifeMs : Math.max(ownLifeMs, lineageMs);
+}
+
+/** 非负有限数才算一个时长;其余(NaN / Infinity / 负数 / 非数)一律读作「说不出」。 */
+function nonNegativeFinite(value: unknown): number | undefined {
+  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
 }
 }
 
 
 /**
 /**

+ 1 - 0
apps/zcode-cli/packages/core/src/tool/executor/call-runner.ts

@@ -214,6 +214,7 @@ async function executeToolCallImpl(
         : { dynamicWorkflowRunPort: deps.dynamicWorkflowRunPort }),
         : { dynamicWorkflowRunPort: deps.dynamicWorkflowRunPort }),
       ...(deps.modelCatalogPort === undefined ? {} : { modelCatalogPort: deps.modelCatalogPort }),
       ...(deps.modelCatalogPort === undefined ? {} : { modelCatalogPort: deps.modelCatalogPort }),
       sessionId: deps.sessionId,
       sessionId: deps.sessionId,
+      ...(deps.hasLoadedSkill === undefined ? {} : { hasLoadedSkill: deps.hasLoadedSkill }),
     });
     });
     if (isToolHandlerFailure(resolution)) {
     if (isToolHandlerFailure(resolution)) {
       // 与 validateInput 同一条生命周期出口:解析不出来是模型该立刻拿回去修的东西,
       // 与 validateInput 同一条生命周期出口:解析不出来是模型该立刻拿回去修的东西,

+ 4 - 0
apps/zcode-cli/packages/core/src/tool/executor/create-workflow-display.ts

@@ -27,6 +27,10 @@ export function createCreateWorkflowDisplay(
   }
   }
   const parsed = CreateWorkflowOutputSchema.safeParse(output);
   const parsed = CreateWorkflowOutputSchema.safeParse(output);
   if (!parsed.success) return undefined;
   if (!parsed.success) return undefined;
+  // 就地调并发没有 display:这条路一行脚本都没编译,而 `create_workflow` 这块载荷的 `ok` 在 UI 上读作
+  // 「已编译」。判据是**显式的 `retuned` 块**而不是形状——「ok 且没有 status」在本工具上还有
+  // 「没有 run 端口、只 typecheck」这条来路。工具卡因此退回响应正文那一段。
+  if (parsed.data.retuned !== undefined) return undefined;
 
 
   const { causalityGraph, diagnostics, ok } = parsed.data;
   const { causalityGraph, diagnostics, ok } = parsed.data;
   // display 不经过 tool result budget:诊断条数与单条 message 长度都必须在进入实时事件和
   // display 不经过 tool result budget:诊断条数与单条 message 长度都必须在进入实时事件和

+ 1 - 0
apps/zcode-cli/packages/core/src/tool/executor/impl.ts

@@ -59,6 +59,7 @@ export class ToolExecutorImpl implements ToolExecutor {
       modelCatalogPort: options.modelCatalogPort,
       modelCatalogPort: options.modelCatalogPort,
       runtimeTaskRegistry: options.runtimeTaskRegistry,
       runtimeTaskRegistry: options.runtimeTaskRegistry,
       readFileState: options.readFileState ?? new Map(),
       readFileState: options.readFileState ?? new Map(),
+      hasLoadedSkill: options.hasLoadedSkill,
       subagentBackgroundBashMaxMs: options.subagentBackgroundBashMaxMs,
       subagentBackgroundBashMaxMs: options.subagentBackgroundBashMaxMs,
       bashShellSelection: options.bashShellSelection,
       bashShellSelection: options.bashShellSelection,
       getBashShellSelection: options.getBashShellSelection,
       getBashShellSelection: options.getBashShellSelection,

+ 3 - 0
apps/zcode-cli/packages/core/src/tool/executor/types.ts

@@ -116,6 +116,8 @@ export interface ToolExecutorOptions {
   modelCatalogPort?: ModelCatalogPort;
   modelCatalogPort?: ModelCatalogPort;
   runtimeTaskRegistry?: RuntimeTaskRegistry;
   runtimeTaskRegistry?: RuntimeTaskRegistry;
   readFileState?: ReadFileStateMap;
   readFileState?: ReadFileStateMap;
+  /** 技能门的探针(ToolInputResolutionContext.hasLoadedSkill);runtime 按 provider 可见历史回答。 */
+  hasLoadedSkill?: (skillName: string) => boolean;
   subagentBackgroundBashMaxMs?: number;
   subagentBackgroundBashMaxMs?: number;
   bashShellSelection?: ExecutionShellSelection;
   bashShellSelection?: ExecutionShellSelection;
   getBashShellSelection?: () => ExecutionShellSelection | undefined;
   getBashShellSelection?: () => ExecutionShellSelection | undefined;
@@ -220,6 +222,7 @@ export interface ToolExecutorDeps {
   modelCatalogPort?: ModelCatalogPort;
   modelCatalogPort?: ModelCatalogPort;
   runtimeTaskRegistry?: RuntimeTaskRegistry;
   runtimeTaskRegistry?: RuntimeTaskRegistry;
   readFileState: ReadFileStateMap;
   readFileState: ReadFileStateMap;
+  hasLoadedSkill?: (skillName: string) => boolean;
   subagentBackgroundBashMaxMs?: number;
   subagentBackgroundBashMaxMs?: number;
   bashShellSelection?: ExecutionShellSelection;
   bashShellSelection?: ExecutionShellSelection;
   getBashShellSelection?: () => ExecutionShellSelection | undefined;
   getBashShellSelection?: () => ExecutionShellSelection | undefined;

+ 13 - 28
apps/zcode-cli/packages/core/src/tool/handlers/amend-workflow-description.ts

@@ -1,35 +1,20 @@
-// AmendWorkflow 的工具描述。
-// 与 CreateWorkflow 分开成文:facade 与写作规则那一大段模型已经在 CreateWorkflow 上读过,
-// 这里只说修订**特有**的几件事——什么时候用、缓存怎么命中、哪些东西省略即沿用、确认窗何时出现。
+// AmendWorkflow 的常驻描述。
+//
+// 缓存如何命中、省略即沿用的三个字段、`path` 与 `script` 两条来路、确认窗
+// 何时出现,都在 `dynamic-workflows` 技能的「Tool reference」里,由技能门保证读过。这里只留
+// 路由——什么情况该来修订而不是重建、不要先停、不要等——因为它决定的是「要不要调这个工具」,
+// 必须在技能加载之前就被读到。
+
+import { DYNAMIC_WORKFLOW_SKILL_NAME } from "@zcode/contracts";
 
 
 export const AMEND_WORKFLOW_TOOL_DESCRIPTION = [
 export const AMEND_WORKFLOW_TOOL_DESCRIPTION = [
   "Amend an existing dynamic-workflow run with a revised script or revised settings. Starts a NEW run that supersedes the old one and imports its finished work as a cache, so only what you changed is paid for again. Works on ANY run of this project: completed, errored, stopped — or still running.",
   "Amend an existing dynamic-workflow run with a revised script or revised settings. Starts a NEW run that supersedes the old one and imports its finished work as a cache, so only what you changed is paid for again. Works on ANY run of this project: completed, errored, stopped — or still running.",
   "",
   "",
   "When to use:",
   "When to use:",
-  "- The run errored (the script itself failed): fix the script and amend — every step that already succeeded is imported instead of being paid for twice. Never rewrite the workflow from scratch with CreateWorkflow.",
-  "- The run completed but needs one more stage or a refinement: amend — added or changed steps run live, untouched ones cost nothing.",
-  "- The run is STILL RUNNING and the user (or a reported item) shows the script is going wrong: amend it NOW, in one call. Do not TaskStop it first and do not wait for it to finish: this tool stops the running predecessor, waits for it to settle, imports everything that settled before the stop, and starts the revision. The earlier you amend, the less is re-paid.",
-  "- The user wants the same workflow with fewer subagents at once, its subagents on another model, or another name: amend with only that field and neither `path` nor `script` (see below). On a running run this still stops it, and what it had in flight starts again in the new run.",
-  "- To continue a stopped run unchanged, use ResumeWorkflowRun instead. Amending is for when the script or a setting changes.",
-  "",
-  "How the cache works:",
-  "- Named subagents are matched by name across the two scripts; each one's asks are matched in order by byte-identical instructions. A match settles from the recorded result at zero tokens; a changed or added ask runs live. The cache stays open until a live subagent makes its first write to the workspace (or a live `world.run` executes): from that moment, cached world reads and cached asks whose subagent had read or run something would describe a workspace that no longer exists, so they run live too. Asks that only answered keep settling from the cache. Editing an ask's text is how you force it to run again; keep names stable and keep tunable constants out of ask text.",
-  "",
-  // 三条 bullet 说的是同一条规则(省略即沿用前驱),刻意并排、脚本在最前:模型若以为脚本必填,
-  // 就会为了改一个数把几千 token 的脚本再抄一遍;两个设定分开说,又会让模型把其中一个的「省略」
-  // 读成解除。完整语义在字段描述上(contracts/tools/amend-workflow.ts)。
-  "What carries over — every field you omit keeps the predecessor's value:",
-  "- The script: omit both `path` and `script` to keep the predecessor's script byte for byte and change only the settings below; its finished work still replays from the cache.",
-  "- A parallelism limit: omit `max_concurrency` and the new run keeps the predecessor's, pass `null` to remove it, pass a number to change it (only when the user asks).",
-  "- The subagents' model: omit `subagent_model` and the new run keeps the predecessor's, pass `null` to put the subagents back on the session model, pass a model id to change it (only when the user asks). ListModels lists the ids.",
-  "",
-  // 改脚本的两条来路,常态在前:整段脚本再流
-  // 一遍正是要省掉的代价,而终态通知与 GetWorkflowRun 都已经把那个文件的路径给了模型。
-  "Passing a revised script — one of the two, never both:",
-  "- `path` is the usual way: the errored notification and GetWorkflowRun name the run's script file — edit it in place and pass the same path back, so a revision costs one Edit instead of a second copy of the whole script. A file whose bytes you did not change is refused (`script_unchanged`) unless the call also sets `max_concurrency` or `subagent_model`; nothing is stopped and nothing is created.",
-  "- `script` is still accepted for a revision you write from scratch: the WHOLE revised script, inline, written against the same facade and rules as CreateWorkflow (phases, subagent names, gates, `return` shape). It is saved to a draft file and the result names it, so the next revision can go back to `path`. Compilation errors come back as diagnostics: fix the file the result names and call again with `path` — nothing was stopped or started.",
+  "- The run errored, or completed but needs one more stage: fix or extend the script and amend. Never rewrite the workflow from scratch with CreateWorkflow.",
+  "- The run is STILL RUNNING and is visibly going wrong: amend it NOW, in one call. Do not TaskStop it first and do not wait for it to finish — this tool stops the running predecessor and starts the revision; the earlier you amend, the less is re-paid.",
+  "- The user wants the same workflow with fewer subagents at once, its subagents on another model, or another name: amend with only that field and neither `path` nor `script`.",
+  "- To continue a stopped run unchanged, use ResumeWorkflowRun instead.",
   "",
   "",
-  "Confirmation:",
-  "- A run this session started (through CreateWorkflow, a previous AmendWorkflow, or the workflows hub) is amended without a confirmation window, even while it is running. A run the user stopped, or a run another session started, asks the user first.",
-  "- The result names the run that was superseded (if one was stopped) and the new run's ID. The superseded run sends no notification of its own; the new run notifies when it settles. Do not wait for it or poll it with TaskOutput.",
+  `Load the \`${DYNAMIC_WORKFLOW_SKILL_NAME}\` skill with the Skill tool before revising a script: it carries the cache rules, what each omitted field keeps, and the confirmation rule. A call that passes \`path\` or \`script\` is refused until that skill has been loaded in this session; a settings-only call is not. Pass \`path\` (the run's script file, edited in place — the usual form) or \`script\` (the whole revised script inline), never both.`,
 ].join("\n");
 ].join("\n");

+ 17 - 47
apps/zcode-cli/packages/core/src/tool/handlers/amend-workflow-resolve.ts

@@ -10,8 +10,6 @@
 import {
 import {
   AmendWorkflowInputSchema,
   AmendWorkflowInputSchema,
   type AmendWorkflowInput,
   type AmendWorkflowInput,
-  type AmendWorkflowPredecessor,
-  type DynamicWorkflowRunSnapshot,
   type ModelCatalogPort,
   type ModelCatalogPort,
 } from "@zcode/contracts";
 } from "@zcode/contracts";
 import type {
 import type {
@@ -19,13 +17,13 @@ import type {
   ToolInputResolutionContext,
   ToolInputResolutionContext,
   ToolInputResolutionResult,
   ToolInputResolutionResult,
 } from "../types.js";
 } from "../types.js";
-import {
-  SUBAGENT_MODEL_UNAVAILABLE,
-  clampWorkflowMaxConcurrency,
-} from "./create-workflow-source.js";
+import { SUBAGENT_MODEL_UNAVAILABLE } from "./create-workflow-source.js";
+import { resolveConcurrencyRetuneRoute } from "./amend-workflow-retune.js";
 import {
 import {
   AMEND_WORKFLOW_ERROR_CODE,
   AMEND_WORKFLOW_ERROR_CODE,
+  describePredecessor,
   refuseUnchangedScript,
   refuseUnchangedScript,
+  resolveAmendMaxConcurrency,
   resolveAmendScript,
   resolveAmendScript,
 } from "./amend-workflow-source.js";
 } from "./amend-workflow-source.js";
 import { resolveModelReference } from "./model-reference.js";
 import { resolveModelReference } from "./model-reference.js";
@@ -33,6 +31,7 @@ import { workflowRunNotFoundFailure } from "./workflow-run-introspection.js";
 
 
 export {
 export {
   AMEND_WORKFLOW_ERROR_CODE,
   AMEND_WORKFLOW_ERROR_CODE,
+  resolveAmendMaxConcurrency,
   scriptUnavailableFailure,
   scriptUnavailableFailure,
   validateAmendWorkflowSource,
   validateAmendWorkflowSource,
 } from "./amend-workflow-source.js";
 } from "./amend-workflow-source.js";
@@ -107,6 +106,17 @@ export async function resolveAmendWorkflowInput(
   }
   }
   const snapshot = await port.getTask(parsed.data.run_id);
   const snapshot = await port.getTask(parsed.data.run_id);
   if (snapshot === undefined) return predecessorNotFoundFailure(parsed.data.run_id);
   if (snapshot === undefined) return predecessorNotFoundFailure(parsed.data.run_id);
+  const predecessor = describePredecessor(snapshot, context.sessionId);
+  // 路由在这里分岔,而且只能在这里:刚读完前驱(于是知道它还活不活),入参形状又摆在眼前
+  // (于是知道除并发外有没有别的要变)。命中即就地调并发——不读脚本、不继承、不编译,
+  // 归一化后的入参因此**没有 script**,那也是 handler 与 prepareApproval 认出这条路的凭据。
+  const retune = resolveConcurrencyRetuneRoute({
+    model: parsed.data,
+    port,
+    predecessor,
+    inherited: snapshot.maxConcurrency,
+  });
+  if (retune !== undefined) return retune;
   const subagentModel = resolveAmendSubagentModel(
   const subagentModel = resolveAmendSubagentModel(
     parsed.data.subagent_model,
     parsed.data.subagent_model,
     snapshot.subagentModel,
     snapshot.subagentModel,
@@ -148,7 +158,7 @@ export async function resolveAmendWorkflowInput(
     ),
     ),
     ...subagentModel.field,
     ...subagentModel.field,
     predecessor: {
     predecessor: {
-      ...describePredecessor(snapshot, context.sessionId),
+      ...predecessor,
       ...(script.inherited ? { script_inherited: true as const } : {}),
       ...(script.inherited ? { script_inherited: true as const } : {}),
     },
     },
   };
   };
@@ -226,43 +236,3 @@ function subagentModelFailure(message: string): ToolHandlerFailure {
     message: `workflow_subagent_model_unresolved: ${message} Nothing was stopped or created.`,
     message: `workflow_subagent_model_unresolved: ${message} Nothing was stopped or created.`,
   };
   };
 }
 }
-
-/**
- * 并发上界的三态归一:
- *
- *   - 数 → 钳到 `[1, 天花板]`;
- *   - `null` → 解除,键整个消失(新 run 跑在天花板上);
- *   - 省略 → 沿用前驱的上界。快照**只在低于天花板时**带 `maxConcurrency`,所以「前驱没设过」
- *     与「前驱跑在天花板上」在这里是同一件事:也是键消失。沿用的值同样再钳一次——前驱可能
- *     是在另一台机器(另一个天花板)上起的。
- *
- * 三态只活到这里:确认窗与 handler 之后面对的只有「一个数或没有」。
- */
-export function resolveAmendMaxConcurrency(
-  requested: number | null | undefined,
-  inherited: number | undefined,
-  ceiling: number | undefined,
-): { max_concurrency?: number } {
-  if (requested === null) return {};
-  const resolved = requested ?? inherited;
-  if (resolved === undefined) return {};
-  return { max_concurrency: clampWorkflowMaxConcurrency(resolved, ceiling) };
-}
-
-function describePredecessor(
-  snapshot: DynamicWorkflowRunSnapshot,
-  sessionId: string | undefined,
-): AmendWorkflowPredecessor {
-  // 快照的 `status` 是追踪器的通用词(stopped 折成 cancelled …);真实词在 `runStatus`,只在
-  // 终态在场——非终态一律读作 running(pending 在这里与 running 无分别:都会被 amend 停下)。
-  const status = snapshot.runStatus ?? "running";
-  return {
-    ...(snapshot.name === undefined ? {} : { name: snapshot.name }),
-    status,
-    ...(snapshot.stopReason === undefined ? {} : { stop_reason: snapshot.stopReason }),
-    owned_by_this_session:
-      sessionId !== undefined &&
-      snapshot.parentSessionId !== undefined &&
-      snapshot.parentSessionId === sessionId,
-  };
-}

+ 248 - 0
apps/zcode-cli/packages/core/src/tool/handlers/amend-workflow-retune.ts

@@ -0,0 +1,248 @@
+// AmendWorkflow:只改并发时就地生效。
+// 当调用只带 `run_id` 与 `max_concurrency`,且前驱仍在运行时,保留 run ID、子代理、转录与未完成 ask。
+// 本模块负责路由判定、端口调用和结果说明;若 run 在判定与调用之间结算,重新读取前驱事实,
+// 再决定是否允许回落到修订流程。
+
+import {
+  AmendWorkflowInputSchema,
+  isAmendWorkflowOwnedPredecessor,
+  type AmendWorkflowInput,
+  type AmendWorkflowPredecessor,
+  type CreateWorkflowOutput,
+  type DynamicWorkflowRunPort,
+  type DynamicWorkflowRunRetuneResult,
+} from "@zcode/contracts";
+import type { ToolExecutionContext, ToolHandlerFailure } from "../types.js";
+import {
+  AMEND_WORKFLOW_ERROR_CODE,
+  describePredecessor,
+  resolveAmendMaxConcurrency,
+  resolveAmendScript,
+} from "./amend-workflow-source.js";
+import { clampWorkflowMaxConcurrency } from "./create-workflow-source.js";
+import { workflowRunNotFoundFailure } from "./workflow-run-introspection.js";
+
+/**
+ * 「除并发之外什么都没变」:判的是**入参的形状**,不是新字段。
+ * `script`、`path`、`subagent_model` 与 `name` 无论带的是什么,都把这次调用送去修订那条路——
+ * 它们各自都可能改变将要跑的东西,而这条路的前提是「跑的还是同一段脚本、同一批子代理」。
+ *
+ * 归一化之后的入参同样适用:修订那条路恒会落定一份脚本,所以「没有脚本、却有并发」只可能是
+ * 就地调并发。
+ */
+export function isConcurrencyOnlyAmend(model: AmendWorkflowInput): boolean {
+  return (
+    model.max_concurrency !== undefined &&
+    model.script === undefined &&
+    model.path === undefined &&
+    model.subagent_model === undefined &&
+    model.name === undefined
+  );
+}
+
+/**
+ * resolveInput 里的路由判定。命中即返回**不带脚本**的归一化入参——此后 prepareApproval 放行、handler 调
+ * `retuneConcurrency`;不命中回 `undefined`,调用方照常走修订。
+ *
+ * 三个前提缺一不可:入参形状只改并发、前驱还活着(`pending` 与 `running` 都试,活不活由端口说
+ * 了算)、端口接得住这条控制面。端口不带 `retuneConcurrency`(老宿主)时整条路不存在,调用
+ * 原样落成今天的修订——包括别人的 run 那一个确认窗。
+ */
+export function resolveConcurrencyRetuneRoute(options: {
+  model: AmendWorkflowInput;
+  port: DynamicWorkflowRunPort;
+  predecessor: AmendWorkflowPredecessor;
+  /** 前驱快照上的上界;缺席即它跑在天花板上。 */
+  inherited: number | undefined;
+}): { result: true; input: AmendWorkflowInput } | ToolHandlerFailure | undefined {
+  const { model, port, predecessor } = options;
+  if (!isConcurrencyOnlyAmend(model)) return undefined;
+  if (predecessor.status !== "pending" && predecessor.status !== "running") return undefined;
+  if (typeof port.retuneConcurrency !== "function") return undefined;
+
+  // 三态在这里**不**归一:`null` 要原样递到端口(见 resolveAmendMaxConcurrency 的注释)。
+  const requested = model.max_concurrency ?? null;
+  const ceiling = port.concurrencyCeiling?.();
+  const unchanged = refuseUnchangedBound(model.run_id, requested, options.inherited, ceiling);
+  if (unchanged !== undefined) return unchanged;
+  return {
+    result: true,
+    input: { run_id: model.run_id, max_concurrency: requested, predecessor },
+  };
+}
+
+/**
+ * 同值就在这里收口——早于 hook、早于确认窗,端口一次都不碰。天花板读不到(老宿主不带
+ * `concurrencyCeiling`)时 `null` 无从折算成数,这道网就让开,由端口自己去答 `unchanged`。
+ */
+function refuseUnchangedBound(
+  runId: string,
+  requested: number | null,
+  inherited: number | undefined,
+  ceiling: number | undefined,
+): ToolHandlerFailure | undefined {
+  const current = inherited ?? ceiling;
+  const next = requested === null ? ceiling : clampWorkflowMaxConcurrency(requested, ceiling);
+  if (current === undefined || next === undefined || current !== next) return undefined;
+  return retuneUnchangedFailure(runId, current, ceiling);
+}
+
+/**
+ * handler 侧的本体:调端口、把三种答复翻成模型面的结果。
+ *
+ * 回 `undefined` 只有一个含义——端口答了 `not_live`(或宿主根本没有这条控制面),这次调用
+ * 此刻描述的是一次修订,做不做由 {@link resolveRetuneFallbackAmend} 定夺。
+ */
+export async function runConcurrencyRetune(
+  parsed: AmendWorkflowInput,
+  context: ToolExecutionContext,
+): Promise<CreateWorkflowOutput | ToolHandlerFailure | undefined> {
+  const port = context.dynamicWorkflowRunPort;
+  if (port === undefined || typeof port.retuneConcurrency !== "function") return undefined;
+  const answer = await port.retuneConcurrency({
+    runId: parsed.run_id,
+    // 路由判定已保证这里是「一个数或 null」;`?? null` 只是把绕过归一化的缺席读作「回天花板」。
+    maxConcurrency: parsed.max_concurrency ?? null,
+  });
+  if (answer.ok) {
+    return {
+      diagnostics: [],
+      ok: true,
+      // 不进后台追踪器:run 本来就在里面,而且它自始至终是同一个 run,没有 `backgrounded`
+      // 契约可言,也没有编译产物可画。`retuned` 是**显式**
+      // 的判别块:消费方不该按「ok 且没有 status」去猜,那个形状还有别的来路。
+      response: retuneResponse(parsed.run_id, answer),
+      retuned: {
+        runId: parsed.run_id,
+        maxConcurrency: answer.maxConcurrency,
+        previous: answer.previous,
+        ceiling: answer.ceiling,
+      },
+    } satisfies CreateWorkflowOutput;
+  }
+  if (answer.reason === "unchanged") {
+    return retuneUnchangedFailure(parsed.run_id, answer.current, port.concurrencyCeiling?.());
+  }
+  return undefined;
+}
+
+/**
+ * 结算竞态:同一份入参此刻
+ * 描述的是一次修订。能不能做只看一件事——**那次修订本来要不要开窗**。
+ *
+ * 本会话自己的、不是用户亲手停下的 run:owner 规则本来也不开窗,于是照常修订,脚本与编译推迟
+ * 到此刻才发生(缺脚本、编不过都按修订自己的拒绝回报)。别人的 run,或用户停过的 run:拒掉。
+ * 这条路一个窗都没弹过,不能把「什么都没批」撑成「另起一次 run」。
+ */
+export async function resolveRetuneFallbackAmend(
+  parsed: AmendWorkflowInput,
+  context: ToolExecutionContext,
+): Promise<{ result: true; input: AmendWorkflowInput } | ToolHandlerFailure> {
+  const port = context.dynamicWorkflowRunPort;
+  // 事实要重读一遍:run 刚刚在存活判定与端口调用之间结算,入参里的那一份说的还是「在跑」。
+  const snapshot = port === undefined ? undefined : await port.getTask(parsed.run_id);
+  if (snapshot === undefined) return predecessorNotFoundFailure(parsed.run_id);
+  const predecessor = describePredecessor(snapshot, context.sessionId);
+  if (!isAmendWorkflowOwnedPredecessor(predecessor)) {
+    // 还没结算(pending、引擎没建起来)与已结算是两句不同的话,但下一步相同:再调一次。
+    return predecessor.status === "pending" || predecessor.status === "running"
+      ? notRetunableFailure(parsed.run_id)
+      : runSettledFailure(parsed.run_id);
+  }
+  const script = await resolveAmendScript({
+    model: parsed,
+    cwd: context.workingDirectory,
+    port,
+    predecessorScriptPath: snapshot.scriptPath,
+  });
+  if (!script.result) return script;
+  return {
+    result: true,
+    input: AmendWorkflowInputSchema.parse({
+      run_id: parsed.run_id,
+      ...script.fields,
+      // 落回修订就回到「一个数或没有」:这次调用显式给了值,没有可沿用的。
+      ...resolveAmendMaxConcurrency(
+        parsed.max_concurrency,
+        undefined,
+        port?.concurrencyCeiling?.(),
+      ),
+      predecessor: {
+        ...predecessor,
+        ...(script.inherited ? { script_inherited: true as const } : {}),
+      },
+    }) as AmendWorkflowInput,
+  };
+}
+
+/** 前驱不存在:与 resolveInput 那一条同源同文案(一个 run id 打错了只该有一种说法)。 */
+function predecessorNotFoundFailure(runId: string): ToolHandlerFailure {
+  const base = workflowRunNotFoundFailure(runId);
+  return {
+    ...base,
+    message: `${base.message} Nothing was stopped or created: \`run_id\` pointed at a run that does not exist — pass an existing run's ID (see ListWorkflowRuns), or start a fresh run with CreateWorkflow.`,
+  };
+}
+
+/** 现在生效的上界读成一句话;等于天花板即「没有自己的界」。 */
+function describeBoundInForce(bound: number | undefined, ceiling: number | undefined): string {
+  if (bound === undefined || bound === ceiling) {
+    return "has no limit on how many subagents run at once (it runs at this machine's maximum)";
+  }
+  return bound === 1
+    ? "already runs at most 1 subagent at once"
+    : `already runs at most ${bound} subagents at once`;
+}
+
+/** 同值:什么都没写、什么都没停,拒绝里点名此刻生效的那个界。 */
+export function retuneUnchangedFailure(
+  runId: string,
+  current: number | undefined,
+  ceiling: number | undefined,
+): ToolHandlerFailure {
+  return {
+    result: false,
+    errorCode: AMEND_WORKFLOW_ERROR_CODE.RETUNE_UNCHANGED,
+    message: `workflow_retune_unchanged: run ${runId} ${describeBoundInForce(current, ceiling)}, so there is nothing to change. Nothing was stopped, created or changed — pass a different \`max_concurrency\`, or a revised script if you meant to amend the run.`,
+  };
+}
+
+/** 别人的 run,已经结算:再调一次,那一次从头走修订,连同它要的那个确认窗。 */
+export function runSettledFailure(runId: string): ToolHandlerFailure {
+  return {
+    result: false,
+    errorCode: AMEND_WORKFLOW_ERROR_CODE.RUN_SETTLED,
+    message: `workflow_run_settled: run ${runId} settled before the new parallelism limit could take hold, so there is nothing running to retune. Nothing was stopped, created or changed — call AmendWorkflow again if you want a new run of it under that limit.`,
+  };
+}
+
+/** 别人的 run,本 agent 从没握住过(`pending`,引擎还没建):同样的下一步。 */
+export function notRetunableFailure(runId: string): ToolHandlerFailure {
+  return {
+    result: false,
+    errorCode: AMEND_WORKFLOW_ERROR_CODE.NOT_RETUNABLE,
+    message: `workflow_run_not_retunable: run ${runId} is not being executed by this agent, so its parallelism cannot be changed in place. Nothing was stopped, created or changed — call AmendWorkflow again if you want a new run of it under that limit.`,
+  };
+}
+
+/**
+ * 模型面的回话:**点名一个 run、没有后继**——模型正是据此
+ * 分辨自己这次调用走的是哪条路,不必被告知路由本身。上界等于天花板时说「限制已取消」而不是
+ * 报一个数,与 `CreateWorkflow` 划的是同一条界。
+ *
+ * ⚠ 这段文本是**唯一**过得了 v4 的事实:这条路没有 display 载荷(`retuned` 这个块只到进程内为
+ * 止,协议的 `toolOutputSchema` 只带 text / display / truncated),工具卡拿它当整行来画。所以它
+ * 必须自足——点名 run、点名现在的上界、说清没有新 run——而且要稳:改词就等于改 UI。
+ */
+function retuneResponse(
+  runId: string,
+  answer: Extract<DynamicWorkflowRunRetuneResult, { ok: true }>,
+): string {
+  const bound =
+    answer.maxConcurrency === answer.ceiling
+      ? "the limit on how many subagents run at once is removed (this machine's maximum applies)"
+      : answer.maxConcurrency === 1
+        ? "at most 1 subagent runs at once"
+        : `at most ${answer.maxConcurrency} subagents run at once`;
+  return `Applied to the running run ${runId}; ${bound}. Run ${runId} keeps running under it: nothing was stopped and no new run was started.`;
+}

+ 54 - 0
apps/zcode-cli/packages/core/src/tool/handlers/amend-workflow-source.ts

@@ -12,9 +12,12 @@ import {
   AMEND_WORKFLOW_SOURCE_ERROR,
   AMEND_WORKFLOW_SOURCE_ERROR,
   AmendWorkflowInputSchema,
   AmendWorkflowInputSchema,
   type AmendWorkflowInput,
   type AmendWorkflowInput,
+  type AmendWorkflowPredecessor,
   type DynamicWorkflowRunPort,
   type DynamicWorkflowRunPort,
+  type DynamicWorkflowRunSnapshot,
 } from "@zcode/contracts";
 } from "@zcode/contracts";
 import type { ToolHandlerFailure } from "../types.js";
 import type { ToolHandlerFailure } from "../types.js";
+import { clampWorkflowMaxConcurrency } from "./create-workflow-source.js";
 import { readWorkflowScriptFile } from "./workflow-path-source.js";
 import { readWorkflowScriptFile } from "./workflow-path-source.js";
 
 
 /**
 /**
@@ -29,6 +32,10 @@ export const AMEND_WORKFLOW_ERROR_CODE = {
   SCRIPT_UNCHANGED: 24,
   SCRIPT_UNCHANGED: 24,
   SCRIPT_FILE: 25,
   SCRIPT_FILE: 25,
   SCRIPT_UNAVAILABLE: 26,
   SCRIPT_UNAVAILABLE: 26,
+  // 只改并发那条路由自己的三个拒绝;三者都不动 run。
+  RETUNE_UNCHANGED: 27,
+  RUN_SETTLED: 28,
+  NOT_RETUNABLE: 29,
 } as const;
 } as const;
 
 
 /** 入参级违规(两个来源都给了)的码,与 `CreateWorkflow` 的同一个 400。 */
 /** 入参级违规(两个来源都给了)的码,与 `CreateWorkflow` 的同一个 400。 */
@@ -72,6 +79,53 @@ export function scriptUnavailableFailure(
   };
   };
 }
 }
 
 
+/**
+ * 并发上界的三态归一:
+ *
+ *   - 数 → 钳到 `[1, 天花板]`;
+ *   - `null` → 解除,键整个消失(新 run 跑在天花板上);
+ *   - 省略 → 沿用前驱的上界。快照**只在低于天花板时**带 `maxConcurrency`,所以「前驱没设过」
+ *     与「前驱跑在天花板上」在这里是同一件事:也是键消失。沿用的值同样再钳一次——前驱可能
+ *     是在另一台机器(另一个天花板)上起的。
+ *
+ * 三态只活到这里:确认窗与 handler 之后面对的只有「一个数或没有」。**唯一的例外是就地调并发**
+ * 那条路由(amend-workflow-retune.ts):`retuneConcurrency` 自己收 `number | null`,天花板那个数
+ * 只有端口知道,工具不该猜第二遍。
+ */
+export function resolveAmendMaxConcurrency(
+  requested: number | null | undefined,
+  inherited: number | undefined,
+  ceiling: number | undefined,
+): { max_concurrency?: number } {
+  if (requested === null) return {};
+  const resolved = requested ?? inherited;
+  if (resolved === undefined) return {};
+  return { max_concurrency: clampWorkflowMaxConcurrency(resolved, ceiling) };
+}
+
+/**
+ * 前驱事实块。resolveInput 与就地
+ * 调并发的落回路(结算竞态里重读一次快照)共用这一份派生,免得两处对「这个 run 现在算什么状态」
+ * 给出不同的答案。
+ */
+export function describePredecessor(
+  snapshot: DynamicWorkflowRunSnapshot,
+  sessionId: string | undefined,
+): AmendWorkflowPredecessor {
+  // 快照的 `status` 是追踪器的通用词(stopped 折成 cancelled …);真实词在 `runStatus`,只在
+  // 终态在场——非终态一律读作 running(pending 在这里与 running 无分别:都会被 amend 停下)。
+  const status = snapshot.runStatus ?? "running";
+  return {
+    ...(snapshot.name === undefined ? {} : { name: snapshot.name }),
+    status,
+    ...(snapshot.stopReason === undefined ? {} : { stop_reason: snapshot.stopReason }),
+    owned_by_this_session:
+      sessionId !== undefined &&
+      snapshot.parentSessionId !== undefined &&
+      snapshot.parentSessionId === sessionId,
+  };
+}
+
 /** 归一化出来的脚本字段(三条来源同形),外加模型面该看到的文件写法与「是否沿用」。 */
 /** 归一化出来的脚本字段(三条来源同形),外加模型面该看到的文件写法与「是否沿用」。 */
 type AmendScriptResolution =
 type AmendScriptResolution =
   | {
   | {

+ 55 - 5
apps/zcode-cli/packages/core/src/tool/handlers/amend-workflow.ts

@@ -21,7 +21,13 @@ import {
   createWorkflowPhaseAlongside,
   createWorkflowPhaseAlongside,
   createWorkflowPhaseNames,
   createWorkflowPhaseNames,
 } from "@zcode/contracts";
 } from "@zcode/contracts";
-import type { ToolApprovalGate, ToolEntry, ToolHandler, ToolHandlerFailure } from "../types.js";
+import type {
+  ToolApprovalGate,
+  ToolEntry,
+  ToolExecutionContext,
+  ToolHandler,
+  ToolHandlerFailure,
+} from "../types.js";
 import { AMEND_WORKFLOW_TOOL_DESCRIPTION } from "./amend-workflow-description.js";
 import { AMEND_WORKFLOW_TOOL_DESCRIPTION } from "./amend-workflow-description.js";
 import {
 import {
   AMEND_WORKFLOW_ERROR_CODE,
   AMEND_WORKFLOW_ERROR_CODE,
@@ -30,6 +36,11 @@ import {
   scriptUnavailableFailure,
   scriptUnavailableFailure,
   validateAmendWorkflowSource,
   validateAmendWorkflowSource,
 } from "./amend-workflow-resolve.js";
 } from "./amend-workflow-resolve.js";
+import {
+  isConcurrencyOnlyAmend,
+  resolveRetuneFallbackAmend,
+  runConcurrencyRetune,
+} from "./amend-workflow-retune.js";
 import {
 import {
   DIAGNOSTICS_NOT_EXECUTED_NOTE,
   DIAGNOSTICS_NOT_EXECUTED_NOTE,
   EXECUTION_UNAVAILABLE_NOTE,
   EXECUTION_UNAVAILABLE_NOTE,
@@ -38,6 +49,7 @@ import {
 } from "./create-workflow.js";
 } from "./create-workflow.js";
 import { describeWorkflowSubagentModel, parseWorkflowSubagentModel } from "./model-reference.js";
 import { describeWorkflowSubagentModel, parseWorkflowSubagentModel } from "./model-reference.js";
 import { boundGraphOfAnalysis, displayOfAnalysis } from "./workflow-analysis-display.js";
 import { boundGraphOfAnalysis, displayOfAnalysis } from "./workflow-analysis-display.js";
+import { recordAuthoredWorkflowDraft } from "./workflow-draft-read-state.js";
 import { resolveWorkflowDraftName, writeWorkflowDraft } from "./workflow-drafts.js";
 import { resolveWorkflowDraftName, writeWorkflowDraft } from "./workflow-drafts.js";
 import {
 import {
   formatWorkflowDiagnosticLines,
   formatWorkflowDiagnosticLines,
@@ -47,6 +59,7 @@ import {
 } from "./workflow-script-notes.js";
 } from "./workflow-script-notes.js";
 import { analyzeScript } from "./workflow-script-analysis.js";
 import { analyzeScript } from "./workflow-script-analysis.js";
 import { describeWorkflowScriptPath } from "./workflow-script-path.js";
 import { describeWorkflowScriptPath } from "./workflow-script-path.js";
+import { amendWorkflowNeedsSkill, requireDynamicWorkflowSkill } from "./workflow-skill-gate.js";
 
 
 const AMEND_WORKFLOW_TIMEOUT_MS = 15_000;
 const AMEND_WORKFLOW_TIMEOUT_MS = 15_000;
 const AMEND_WORKFLOW_MODEL_BYTES = 24_000;
 const AMEND_WORKFLOW_MODEL_BYTES = 24_000;
@@ -111,6 +124,24 @@ function compileFailureResponse(
 
 
 const amendWorkflowHandler: ToolHandler = async (input, context) => {
 const amendWorkflowHandler: ToolHandler = async (input, context) => {
   const parsed = AmendWorkflowInputSchema.parse(input) as AmendWorkflowInput;
   const parsed = AmendWorkflowInputSchema.parse(input) as AmendWorkflowInput;
+  // 就地调并发:
+  // resolveInput 判过的那条路在这里只剩一个痕迹——没有脚本、只有一个并发值。端口答 `not_live`
+  // (run 在两步之间结算了)时回落到一次真正的修订,脚本与编译推迟到那一刻才发生。
+  if (isConcurrencyOnlyAmend(parsed)) {
+    const retuned = await runConcurrencyRetune(parsed, context);
+    if (retuned !== undefined) return retuned;
+    const fallback = await resolveRetuneFallbackAmend(parsed, context);
+    if (!fallback.result) return fallback;
+    return await amendResolvedWorkflow(fallback.input, context);
+  }
+  return await amendResolvedWorkflow(parsed, context);
+};
+
+/** 修订本体:入参此刻必定带着将要跑的那份脚本(工具路由与落回路都已落定它)。 */
+async function amendResolvedWorkflow(
+  parsed: AmendWorkflowInput,
+  context: ToolExecutionContext,
+): Promise<CreateWorkflowOutput | ToolHandlerFailure> {
   // resolveInput 恒把脚本落定进来(`path` 读成 `script`、省略的从前驱回填,或当场失败);到这里还
   // resolveInput 恒把脚本落定进来(`path` 读成 `script`、省略的从前驱回填,或当场失败);到这里还
   // 缺脚本,只可能是绕过归一化的调用方——同样回结构化失败,而不是把 undefined 交给编译器。
   // 缺脚本,只可能是绕过归一化的调用方——同样回结构化失败,而不是把 undefined 交给编译器。
   const script = parsed.script;
   const script = parsed.script;
@@ -133,6 +164,15 @@ const amendWorkflowHandler: ToolHandler = async (input, context) => {
           source: script,
           source: script,
         })
         })
       : undefined;
       : undefined;
+  // 模型本次亲手写的脚本才记作它写过的文件;沿用前驱脚本的新草稿不记——那份字节可能来自别的
+  // 会话或压缩之前,替模型担保它没看过的内容正是 read-before-edit 要防的事。
+  if (inlineDraft !== undefined && parsed.predecessor?.script_inherited !== true) {
+    await recordAuthoredWorkflowDraft(context, {
+      path: inlineDraft.path,
+      source: script,
+      toolName: "AmendWorkflow",
+    });
+  }
   // run 记的永远是**装着这一次脚本**的文件。脚本改了就绝不沿用前驱的路径:那个文件装的是旧
   // run 记的永远是**装着这一次脚本**的文件。脚本改了就绝不沿用前驱的路径:那个文件装的是旧
   // 脚本,记到新 run 上就是让模型下次去编辑一段已经不在跑的代码。沿用脚本时前驱的文件可以继续
   // 脚本,记到新 run 上就是让模型下次去编辑一段已经不在跑的代码。沿用脚本时前驱的文件可以继续
   // 记,但只在它此刻的字节仍是这份脚本时(resolveKeptScriptFile 已核对过)。
   // 记,但只在它此刻的字节仍是这份脚本时(resolveKeptScriptFile 已核对过)。
@@ -222,7 +262,7 @@ const amendWorkflowHandler: ToolHandler = async (input, context) => {
     backgroundTaskId: amended.runId,
     backgroundTaskId: amended.runId,
     ...(causalityGraph === undefined ? {} : { causalityGraph }),
     ...(causalityGraph === undefined ? {} : { causalityGraph }),
   } satisfies CreateWorkflowOutput;
   } satisfies CreateWorkflowOutput;
-};
+}
 
 
 /**
 /**
  * 确认窗预览:与 CreateWorkflow 同一段代码(编不过即放行给 handler 回诊断)。display 的 kind
  * 确认窗预览:与 CreateWorkflow 同一段代码(编不过即放行给 handler 回诊断)。display 的 kind
@@ -231,8 +271,11 @@ const amendWorkflowHandler: ToolHandler = async (input, context) => {
  */
  */
 function prepareAmendWorkflowApproval(input: unknown): ToolApprovalGate {
 function prepareAmendWorkflowApproval(input: unknown): ToolApprovalGate {
   const parsed = AmendWorkflowInputSchema.safeParse(input);
   const parsed = AmendWorkflowInputSchema.safeParse(input);
-  // 归一化之后 `script` 必在场;缺席即有人绕过了生命周期,放行给 handler:它回结构化失败,窗开了
-  // 也无物可批。
+  // 没有脚本就没有可批的东西,两种情形共用这一条放行:
+  //   - 就地调并发:窗的用处是
+  //     把将要跑的脚本摆到人面前,而这条路一段脚本都不跑,只把一个数挪进 `[1, 天花板]`;
+  //     **归属无关**——别人的 run 也不弹窗,否则一次「什么都没批」会被当成批准了一次新 run。
+  //   - 有人绕过了归一化:放行给 handler,它回结构化失败,窗开了也无物可批。
   if (!parsed.success || parsed.data.script === undefined) return { gate: "proceed" };
   if (!parsed.success || parsed.data.script === undefined) return { gate: "proceed" };
   const analysis = analyzeScript(parsed.data.script);
   const analysis = analyzeScript(parsed.data.script);
   if (!analysis.ok) return { gate: "proceed" };
   if (!analysis.ok) return { gate: "proceed" };
@@ -258,7 +301,14 @@ export const amendWorkflowToolEntry: ToolEntry = {
   handler: amendWorkflowHandler,
   handler: amendWorkflowHandler,
   // 修订脚本至多给一个,只对模型入参成立(归一化后 `script` 与 `path` 同时在场是合法执行态)。
   // 修订脚本至多给一个,只对模型入参成立(归一化后 `script` 与 `path` 同时在场是合法执行态)。
   validateInput: (input) => validateAmendWorkflowSource(input),
   validateInput: (input) => validateAmendWorkflowSource(input),
-  resolveInput: resolveAmendWorkflowInput,
+  resolveInput: (input, context) => {
+    // 技能门先于前驱解析:带 `path` / `script` 的修订是在写脚本;只改设定的调用沿用前驱脚本,放行。
+    if (amendWorkflowNeedsSkill(input)) {
+      const refused = requireDynamicWorkflowSkill(context, AMEND_WORKFLOW_TOOL_NAME);
+      if (refused) return refused;
+    }
+    return resolveAmendWorkflowInput(input, context);
+  },
   prepareApproval: prepareAmendWorkflowApproval,
   prepareApproval: prepareAmendWorkflowApproval,
   inputSchema: AmendWorkflowInputJsonSchema,
   inputSchema: AmendWorkflowInputJsonSchema,
   outputSchema: CreateWorkflowOutputJsonSchema,
   outputSchema: CreateWorkflowOutputJsonSchema,

+ 13 - 93
apps/zcode-cli/packages/core/src/tool/handlers/create-workflow-description.ts

@@ -1,41 +1,15 @@
-// Composed at module load from the dynamic-workflow facade so the model always
-// sees the current API surface.
+// CreateWorkflow 的常驻描述。
+// 工具描述保留用途、调用条件和技能加载要求;facade 声明、写作规则、阶段与命名规则、
+// 字段语义由 `dynamic-workflows` 技能提供。resolveInput 的技能门保证提交脚本前已加载技能。
+// 调用条件必须保留在工具描述里,让模型在加载技能前就能判断是否应使用该工具。
 
 
-import { FACADE_DTS } from "@zcode/dynamic-workflow";
-import { SAVED_WORKFLOW_PROJECT_DIR, WORKFLOW_DRAFTS_DIR } from "@zcode/contracts";
+import { DYNAMIC_WORKFLOW_SKILL_NAME } from "@zcode/contracts";
 
 
-const INTRO = [
-  "Create and run a dynamic workflow: a TypeScript script, written against the facade below, that orchestrates multiple model-driven subagents with plain control flow (loops, conditionals, fan-out) and typed intermediate results.",
-  "The script is typechecked first; on a clean compile the user is asked to confirm, then the run starts in the background — you will be notified with the workflow's final result (the script's top-level return value) when it settles. Compilation errors come back as diagnostics: fix the script and call the tool again.",
-].join(" ");
+const INTRO =
+  "Create and run a dynamic workflow: a TypeScript script that orchestrates multiple model-driven subagents with plain control flow (loops, conditionals, fan-out) and typed intermediate results. The script is typechecked, the user is asked to confirm it, and the run starts in the background; you are notified with its final result when it settles. Compilation errors come back as diagnostics.";
 
 
 /**
 /**
- * 三条来源。写在 WHEN_TO_USE 之前,因为「先看看有没有现成的」是模型在写第一行脚本之前就
- * 该做的判断——放在后面它已经开始写了。
- *
- * 两句「回路」紧跟其后:模型默认会把改过的
- * 脚本整段重贴,而那正是这个特性要消灭的三笔代价——两万 token 重流一遍(有的 provider 直接卡
- * 死在上面)、被 compaction 丢掉的脚本、以及为了改一行而重新生成整段。
- */
-const SOURCES = [
-  "Three ways to give the workflow to run — pass exactly one:",
-  "- `script`: a one-off workflow you write inline, for this situation.",
-  `- \`saved\`: a workflow already saved in this project (\`${SAVED_WORKFLOW_PROJECT_DIR}/\`), by name — \`saved: { name: "pr-review", args: { pr: "123" } }\`.`,
-  `- \`path\`: a script file on disk, relative to the working directory or absolute — normally the file a previous result named. Pass \`args\` alongside it when the file declares them in a \`/* zcode-workflow\` block.`,
-  "",
-  `An inline \`script\` is saved to a file under \`${WORKFLOW_DRAFTS_DIR}/\` and the result names it, whether the script compiled or not.`,
-  "After that, edit that file and resubmit with `path` instead of pasting the script again: a resubmitted 20k-token script is slow and some providers stall on it, while an edit is one small tool call.",
-  "Before writing a workflow from scratch, consider ListSavedWorkflows: if the project already saved one that fits, running it beats rebuilding it — it is the version the user reviewed and kept. Saved workflows declare their own arguments; pass them in `saved.args` and they are validated against the declaration (unknown keys, missing required values and wrong types are rejected) before anything runs.",
-  "Either way the user confirms the run, and the confirmation shows them the actual script that will execute.",
-  // 修订的路由引导。一句话,放在来源之后:
-  // 模型到这里已经知道要跑什么,接下来才轮到「这次是不是在改上一次」——而那是另一个工具的事。
-  "This tool starts a NEW workflow. To change a run that already exists — fix an errored one, extend a completed one, or repair one that is still running and visibly going wrong — do not call CreateWorkflow again: call AmendWorkflow with the run's ID and the revised script. It stops a running predecessor for you, re-uses every finished result you left untouched at no token cost, and starts without another confirmation when the run is this session's own.",
-].join("\n");
-
-/**
- * 工作流只能由 `/workflow` 或明确请求发起,模型不得自行决定开一条。
- * 不能把「多子代理 + 确定性控制流」也列为适用场景——那等于给了模型一条自选入口:
- * 一次编排需求就可能在用户没开口时变成一条要确认、要跑很久的 run。
+ * 只按「用户是否点名」路由:工作流只能由 `/workflow` 或明确请求发起,模型不得自行决定开一条。
  */
  */
 const WHEN_TO_USE = [
 const WHEN_TO_USE = [
   "When to use:",
   "When to use:",
@@ -43,71 +17,17 @@ const WHEN_TO_USE = [
   "- Without such an explicit request, do not start a workflow: delegate with the Agent tool or do the work yourself, even for multi-step or multi-subagent tasks.",
   "- Without such an explicit request, do not start a workflow: delegate with the Agent tool or do the work yourself, even for multi-step or multi-subagent tasks.",
 ].join("\n");
 ].join("\n");
 
 
-const RULES = [
-  "Authoring rules:",
-  "- Plain TypeScript. Define result types with a plain `interface Foo { ... }` or `type Foo = ...` and pass them as `ask<T>` type arguments.",
-  "- Compiled under `strict` (with `noUncheckedIndexedAccess` off): indexing an array or record (`items[i]`) needs no guard. `.find()`, `.match()`, `Map.get()` and optional properties still yield `T | undefined` / `null` and must be guarded before use.",
-  "- Never use the `declare` modifier (`declare interface`, `declare const`, ...): the script is compiled inside a function body, where ambient declarations are illegal. (The facade block above uses `declare` because it is the host's ambient API description — do not imitate it; your script defines plain interfaces.)",
-  "- No `export` statements either — the workflow's output is its final `return`.",
-  "- Top-level `await` and a final `return <value>` are allowed; the returned value is exactly what you receive in the completion notification.",
-  "- No `import` statements.",
-  "- No Node/web APIs: `process`, `fetch`, `fs` do not exist and fail typechecking.",
-  "- `world.run` executes a real command. Its first argument must be a compile-time string literal — the script's command set is shown to the user at confirmation — so interpolate runtime values into the args array, never into the command name. A nonzero exit code comes back as a value (`{ exitCode, stdout, stderr }`), not an exception: branch on `exitCode` for gate checks. Default timeout 300s; override per call with `timeoutMs` (no cap). Spawn failures and timeouts reject; stdout/stderr over 256KB each reject like any other over-cap world read.",
-  // 门的强度:实盘里脚本几乎都有验证阶段,
-  // 但门常比任务弱——仓库有单测与 e2e 两层时只跑单测,然后把 e2e 写进 notCovered。工具描述只
-  // 带规则一句,理由与两层门的写法在 skill。
-  "- Choose the gate from the repository, not from habit: before writing a `world.run` check, find the checks the project already defines (package.json scripts, a Makefile, CI, the README's verify command) and let the strongest one the request implies decide the exit. A fast unit suite may drive a loop's rounds, but the integration suite, end-to-end suite or bench that actually decides the request runs at least once before the final `return`, with the `timeoutMs` it needs. A check that exists and was skipped is not `notCovered`; it is unverified work, and the report must say so.",
-  // 验证与代价成比例 + 只在下一步需要全部结果处 join:实盘里验证按形式叠加、阶段间一律 Promise.all 屏障。各一句,理由在 skill。
-  "- Verify in proportion to what a wrong claim costs: findings the user will act on as fact get an independent confirmer or a deciding `world.run`; a `world.run` that already decided needs no confirmer on top; creative or subjective output gets at most one independent read; a suite the script runs as a gate is run once, by the script — say so in the asks so subagents do not each run it again.",
-  "- Join with `Promise.all` only where the next step needs every item. When two stages map one to one (a reviewer per file, a confirmer per finding), chain them per item inside the fan-out callback and join once at the end, so confirmation starts as each result lands instead of after the slowest item.",
-  "- Test fixed logic (parsers, glob patterns, gate predicates) with the `EvalWorkflowSnippet` tool before submitting: it runs a snippet against the same compiler and world-read path, and a passing snippet pastes into the workflow verbatim.",
-  "- The workflow's final `return` is the report the main agent hands back. Return a report shape — a conclusion, findings with their evidence and whether each was confirmed, what was verified and how, what was not covered — rather than a bare array. The dynamic-workflows skill carries the interface to copy.",
-  '- Publish what the user should see with `artifact.*`: a file a subagent wrote (`await artifact.file("book", "out/book.pdf", {title, primary: true})`, workspace-relative, copied at publish time, same id again = new version), a markdown you composed, or a dashboard declared once at the top (`artifact.chart("perf", {x, y})`) and fed by `report(item, "perf")`. When a run publishes more than one, mark the deliverable `primary: true` (one id per run) so the card and the run pane lead with it. Ids and the report tag are compile-time literals. Publishing rejects catchably when the file is missing or too large — that is the moment to hand the gap back to a subagent.',
-  "- The final `return` stays the model-facing result; artifacts are the user-facing deliverable. Never put the same content in both.",
-  "- Model-side errors never reach the script. Rate limits, concurrency limits, overload, network errors, timeouts and unknown provider errors are retried by the runtime without limit while it adapts the fan-out to what the provider accepts; a deterministic one (expired sign-in, model not in the plan, quota cap, invalid request) stops the whole run as `stopped` so the user can fix the cause and resume it — the script is never told. So do not write retry loops or `try`/`catch` for provider errors. Reserve `try`/`catch` and retry loops for logic failures — a subagent result that failed validation, a gate that did not pass, a world read over its cap, an artifact publish whose source file is missing, or a `ContextLimit` (the ask was too large for the model's context even after compaction: split the work or send less).",
-  // 与上一条同源:并发是运行时的事,不是模型的调节旋钮。`max_concurrency` 的完整语义在
-  // 字段描述上(contracts/tools/create-workflow.ts),这里只放一条交叉引用,免得模型把它
-  // 当成 provider 限流的对策——那正是上一条刚说过运行时自己会处理的东西。
-  "- How many subagents work at once is the runtime's decision, not the script's. Do not design around it, and set the `max_concurrency` field only when the user asks to limit parallelism — never in response to provider errors.",
-  // 与上一条同一族:run 级的旋钮,默认不该被碰。这里唯一要说穿的是「换的是子代理,不是你」
-  // ——模型读到「跑在 X 上」时最容易顺手把自己也当成换了模型,然后向用户复述一个假的当前模型。
-  "- The workflow's subagents run on the session model unless the `subagent_model` field says otherwise. Set it only when the user asks for the subagents to run on a specific model; you (the main agent) stay on the session model either way. ListModels lists what this host has configured.",
-  "- On diagnostics, edit the file the result names and call the tool again with `path`; never paste the script a second time.",
-].join("\n");
-
-const PHASES = [
-  "Phases — required in every script, not optional:",
-  '- Cover the whole script with `phase("...")` markers, one at the head of each stage, top to bottom. The confirmation graph the user approves draws one node per phase; without markers they get one card per step and no story. That graph is the user\'s entire experience of a workflow — supplying phases is part of writing one.',
-  '- Name each phase for the user, in the language the user is speaking in this session: a short natural phrase saying what this stage accomplishes ("Research each changed file in parallel", "汇总并产出最终报告"). Orchestration vocabulary the user never chose — "fan-out", "gate", "aggregate" — is not a phase name; the user approves stages by what they do. Say it the way you would tell a colleague what is happening: "Check that the tests still pass" / "确认测试仍然通过", not "Gate: test verification" / "执行测试验证任务".',
-  "- Mechanics: the name must be a compile-time string literal (no interpolation), and the call must be a standalone statement — the marker claims the rest of its enclosing block, nested blocks and inlined helper calls included, so a marker inside an `if` covers that branch only. Two markers with the same name are one phase, which is how a retry loop stays two nodes instead of per-round sprawl.",
-  "- Every phase must contain at least one subagent `ask` or one `world.run`. A phase is a stage the user can watch progress through; plain script logic between two asks — reading `args`, shaping a prompt, building the final `return` — runs in a flash and shows no progress, so it is not a stage. Fold that logic into the phase before or after it. Do not open a phase for the setup at the top or the `return` at the bottom.",
-].join("\n");
+const SKILL_GATE = `Before writing or revising a script, load the \`${DYNAMIC_WORKFLOW_SKILL_NAME}\` skill with the Skill tool: it carries the facade declarations the script is checked against, the authoring rules, and this tool's full contract. A call that submits a script is refused until that skill has been loaded in this session; running a saved workflow by name is exempt.`;
 
 
-/**
- * 子代理名的命名规则。图精炼(模型事后改名的侧路调用)已撤回,图上的名字只剩脚本里的原词,
- * 所以可读性要在写脚本时一次到位——阶段名早有这条规则,这里推广到 `agent("…")`。
- */
-const NAMES = [
-  "Subagent names:",
-  '- The confirmation graph draws one card per subagent, and the card text is the name you pass to `agent("...")`. Write it for the user, in the language the user is speaking in this session: a short concrete phrase saying what that subagent does in this script ("代码评审员", "Benchmark runner") — the way a colleague would refer to that role. A variable-style token or a number ("w1", "planner_2", "节点3", "子代理A") says nothing to the user.',
-  "- A name is also an identity: it must be unique within the run, and a revised re-run matches its cached results by it. Keep names stable across revisions of the same script, and give duplicates in a loop their own computed names (see the facade).",
-].join("\n");
+const SOURCES =
+  "Pass exactly one source: `script` (a one-off script written inline; it is saved to a draft file the result names — revise that file and resubmit with `path`, never paste the script again), `saved` (a workflow saved in this project or globally, by name; check ListSavedWorkflows before writing one from scratch), or `path` (a script file on disk, normally the file a previous result named). To change a run that already exists — errored, completed, stopped or still running — call AmendWorkflow instead of starting over.";
 
 
 export const CREATE_WORKFLOW_TOOL_DESCRIPTION = [
 export const CREATE_WORKFLOW_TOOL_DESCRIPTION = [
   INTRO,
   INTRO,
   "",
   "",
-  SOURCES,
-  "",
   WHEN_TO_USE,
   WHEN_TO_USE,
   "",
   "",
-  "The script is checked against these facade declarations:",
-  "```ts",
-  FACADE_DTS.trim(),
-  "```",
-  "",
-  RULES,
+  SKILL_GATE,
   "",
   "",
-  PHASES,
-  "",
-  NAMES,
+  SOURCES,
 ].join("\n");
 ].join("\n");

+ 19 - 3
apps/zcode-cli/packages/core/src/tool/handlers/create-workflow.ts

@@ -34,6 +34,7 @@ import {
 } from "./create-workflow-source.js";
 } from "./create-workflow-source.js";
 import { describeWorkflowSubagentModel, parseWorkflowSubagentModel } from "./model-reference.js";
 import { describeWorkflowSubagentModel, parseWorkflowSubagentModel } from "./model-reference.js";
 import { boundGraphOfAnalysis, displayOfAnalysis } from "./workflow-analysis-display.js";
 import { boundGraphOfAnalysis, displayOfAnalysis } from "./workflow-analysis-display.js";
+import { recordAuthoredWorkflowDraft } from "./workflow-draft-read-state.js";
 import { resolveWorkflowDraftName, writeWorkflowDraft } from "./workflow-drafts.js";
 import { resolveWorkflowDraftName, writeWorkflowDraft } from "./workflow-drafts.js";
 import {
 import {
   formatWorkflowDiagnosticLines,
   formatWorkflowDiagnosticLines,
@@ -44,6 +45,7 @@ import {
 } from "./workflow-script-notes.js";
 } from "./workflow-script-notes.js";
 import { analyzeScript } from "./workflow-script-analysis.js";
 import { analyzeScript } from "./workflow-script-analysis.js";
 import { describeWorkflowScriptPath } from "./workflow-script-path.js";
 import { describeWorkflowScriptPath } from "./workflow-script-path.js";
+import { createWorkflowNeedsSkill, requireDynamicWorkflowSkill } from "./workflow-skill-gate.js";
 
 
 const CREATE_WORKFLOW_TOOL_NAME = "CreateWorkflow";
 const CREATE_WORKFLOW_TOOL_NAME = "CreateWorkflow";
 const CREATE_WORKFLOW_TIMEOUT_MS = 15_000;
 const CREATE_WORKFLOW_TIMEOUT_MS = 15_000;
@@ -89,6 +91,14 @@ const createWorkflowHandler: ToolHandler = async (input, context) => {
           source: script,
           source: script,
         })
         })
       : undefined;
       : undefined;
+  // 这份草稿的字节就是模型本次的 `script`:记作它写过的文件,下一次 Edit 不必先 Read。
+  if (inlineDraft !== undefined) {
+    await recordAuthoredWorkflowDraft(context, {
+      path: inlineDraft.path,
+      source: script,
+      toolName: "CreateWorkflow",
+    });
+  }
   const location = describeScriptLocation(parsed, inlineDraft?.path, cwd);
   const location = describeScriptLocation(parsed, inlineDraft?.path, cwd);
 
 
   if (!ok) {
   if (!ok) {
@@ -325,13 +335,19 @@ export const createWorkflowToolEntry: ToolEntry = {
   // 天花板同在这里读:钳制必须发生在确认窗之前,否则用户批准的是一个不会生效的数。
   // 天花板同在这里读:钳制必须发生在确认窗之前,否则用户批准的是一个不会生效的数。
   // 模型目录同在这里读:`subagent_model` 必须在确认窗之前解析成规范形,否则用户批准的是一个
   // 模型目录同在这里读:`subagent_model` 必须在确认窗之前解析成规范形,否则用户批准的是一个
   // 还没被认出来的名字,而解不出来的调用会在批准之后才失败。
   // 还没被认出来的名字,而解不出来的调用会在批准之后才失败。
-  resolveInput: (input, context) =>
-    resolveCreateWorkflowInput(
+  resolveInput: (input, context) => {
+    // 技能门先于一切解析:没读过 dynamic-workflows 就拒绝提交脚本(saved 来源例外,见 gate 模块)。
+    if (createWorkflowNeedsSkill(input)) {
+      const refused = requireDynamicWorkflowSkill(context, CREATE_WORKFLOW_TOOL_NAME);
+      if (refused) return refused;
+    }
+    return resolveCreateWorkflowInput(
       input,
       input,
       context.workingDirectory ?? ".",
       context.workingDirectory ?? ".",
       context.dynamicWorkflowRunPort?.concurrencyCeiling?.(),
       context.dynamicWorkflowRunPort?.concurrencyCeiling?.(),
       context.modelCatalogPort,
       context.modelCatalogPort,
-    ),
+    );
+  },
   prepareApproval: prepareCreateWorkflowApproval,
   prepareApproval: prepareCreateWorkflowApproval,
   inputSchema: CreateWorkflowInputJsonSchema,
   inputSchema: CreateWorkflowInputJsonSchema,
   outputSchema: CreateWorkflowOutputJsonSchema,
   outputSchema: CreateWorkflowOutputJsonSchema,

+ 7 - 38
apps/zcode-cli/packages/core/src/tool/handlers/eval-workflow-snippet-description.ts

@@ -1,43 +1,12 @@
-// Composed at module load from the snippet facade so the model always sees the
-// current API surface — the same constant the compiler is fed, so the contract in
-// this description can never drift from what typechecks
+// EvalWorkflowSnippet 的常驻描述。
+//
+// snippet facade 的范围与写作规则在 `dynamic-workflows` 技能的「Tool
+// reference」里,由技能门保证读过;这里只说它是什么、拿来干什么、先读技能。
 
 
-import { SNIPPET_FACADE_DTS } from "@zcode/dynamic-workflow";
-
-const INTRO = [
-  "Compile and run a small dynamic-workflow TypeScript snippet synchronously, against the same compiler, sandbox, and world-read execution path a real workflow run uses.",
-  "This is the test bench for workflow authoring: verify a parse function against real command output shapes, check what a glob/grep actually returns (workspace-relative sorted paths, cap rejections), or exercise gating logic on real repository state — before composing the full workflow and submitting it with CreateWorkflow.",
-  "Execution is fully ephemeral: nothing is persisted, no background task is created, and the result comes back in this tool call.",
-].join(" ");
-
-const WHEN_TO_USE = [
-  "When to use:",
-  "- Before authoring or revising a CreateWorkflow script: test the fixed logic (parsers, filters, glob patterns, gate predicates) piece by piece. A passing snippet pastes into the workflow verbatim.",
-  "- To observe real facade semantics (paths are workspace-relative and lexicographically sorted; over-cap reads reject instead of truncating) instead of guessing them.",
-  "- NOT for orchestration: there is no agent()/ask() here — that is what a real workflow run is for.",
-].join("\n");
-
-const RULES = [
-  "Authoring rules:",
-  "- Same language as a workflow script, minus subagents: plain TypeScript, plain `interface` declarations, top-level `await`, final `return <value>` (the returned value is serialized into the tool result).",
-  "- No `agent()` or `report()` — they do not exist in the snippet facade and fail typechecking.",
-  "- `world.run(cmd, args?, {timeoutMs?})` executes a real command (journal-free here, but the same driver a run uses): cmd must be a string literal, nonzero exit codes come back as values, and a snippet containing world.run asks the user for confirmation before running.",
-  "- Compiled under `strict` (with `noUncheckedIndexedAccess` off): indexing needs no guard; `.find()`, `.match()` and optional properties still yield `T | undefined` / `null` and must be guarded.",
-  "- No `declare` modifier, no `export`, no `import`, no Node/web APIs (`process`, `fetch`, `fs` fail typechecking).",
-  "- `log(...)` messages are captured in order and returned alongside the result.",
-  "- The whole snippet is bounded by a wall clock (default 60s, `timeoutMs` up to 600s). Keep the returned value small (a summary, not a dump); results over 256KB fail the call.",
-  "- On diagnostics, fix the snippet and call the tool again. Nothing was executed.",
-].join("\n");
+import { DYNAMIC_WORKFLOW_SKILL_NAME } from "@zcode/contracts";
 
 
 export const EVAL_WORKFLOW_SNIPPET_TOOL_DESCRIPTION = [
 export const EVAL_WORKFLOW_SNIPPET_TOOL_DESCRIPTION = [
-  INTRO,
-  "",
-  WHEN_TO_USE,
-  "",
-  "The snippet is checked against these facade declarations:",
-  "```ts",
-  SNIPPET_FACADE_DTS.trim(),
-  "```",
+  "Compile and run a small dynamic-workflow TypeScript snippet synchronously, against the same compiler, sandbox and world-read execution path a real run uses. It is the test bench for workflow authoring: check a parser against real command output, see what a glob actually returns, or exercise a gate predicate on real repository state before putting it in a CreateWorkflow script. No agent()/report(); nothing persists; the result comes back in this call.",
   "",
   "",
-  RULES,
+  `Load the \`${DYNAMIC_WORKFLOW_SKILL_NAME}\` skill with the Skill tool first: it carries the snippet facade and the rules. The call is refused until that skill has been loaded in this session. Pass \`code\` (inline) or \`path\` (a file holding the snippet), never both.`,
 ].join("\n");
 ].join("\n");

+ 5 - 1
apps/zcode-cli/packages/core/src/tool/handlers/eval-workflow-snippet.ts

@@ -43,6 +43,7 @@ import { EVAL_WORKFLOW_SNIPPET_TOOL_DESCRIPTION } from "./eval-workflow-snippet-
 import { readWorkflowScriptFile } from "./workflow-path-source.js";
 import { readWorkflowScriptFile } from "./workflow-path-source.js";
 import { formatWorkflowDiagnosticLines } from "./workflow-script-notes.js";
 import { formatWorkflowDiagnosticLines } from "./workflow-script-notes.js";
 import { describeWorkflowScriptPath } from "./workflow-script-path.js";
 import { describeWorkflowScriptPath } from "./workflow-script-path.js";
+import { requireDynamicWorkflowSkill } from "./workflow-skill-gate.js";
 
 
 // 工具级超时是**外层兜底**,不是 snippet 的墙钟:入参 timeoutMs(≤600s)驱动 harness
 // 工具级超时是**外层兜底**,不是 snippet 的墙钟:入参 timeoutMs(≤600s)驱动 harness
 // 到点 kill 子进程并正常返回失败;这里再留编译与收尾的余量。双时钟语义刻意不存在——
 // 到点 kill 子进程并正常返回失败;这里再留编译与收尾的余量。双时钟语义刻意不存在——
@@ -50,7 +51,8 @@ import { describeWorkflowScriptPath } from "./workflow-script-path.js";
 const EVAL_WORKFLOW_SNIPPET_TOOL_TIMEOUT_MS = 660_000;
 const EVAL_WORKFLOW_SNIPPET_TOOL_TIMEOUT_MS = 660_000;
 const EVAL_WORKFLOW_SNIPPET_MODEL_BYTES = 24_000;
 const EVAL_WORKFLOW_SNIPPET_MODEL_BYTES = 24_000;
 
 
-const NOT_EXECUTED_NOTE = "NOTE: The snippet was NOT executed — fix the errors above and call the tool again.";
+const NOT_EXECUTED_NOTE =
+  "NOTE: The snippet was NOT executed — fix the errors above and call the tool again.";
 const UNAVAILABLE_NOTE =
 const UNAVAILABLE_NOTE =
   "NOTE: The snippet was NOT executed — snippet evaluation is not available in this session.";
   "NOTE: The snippet was NOT executed — snippet evaluation is not available in this session.";
 
 
@@ -261,6 +263,8 @@ export const evalWorkflowSnippetToolEntry: ToolEntry = {
   // 来源二选一只对模型入参成立;`path` 在归一化里读成 `code`,确认门与 handler 因此同形。
   // 来源二选一只对模型入参成立;`path` 在归一化里读成 `code`,确认门与 handler 因此同形。
   validateInput: (input) => validateEvalWorkflowSnippetInput(input),
   validateInput: (input) => validateEvalWorkflowSnippetInput(input),
   resolveInput: (input, context) =>
   resolveInput: (input, context) =>
+    // 技能门先于 path 归一化(handlers/workflow-skill-gate.ts):片段的语言规则也在技能里。
+    requireDynamicWorkflowSkill(context, EVAL_WORKFLOW_SNIPPET_TOOL_NAME) ??
     resolveEvalWorkflowSnippetInput(input, context.workingDirectory ?? "."),
     resolveEvalWorkflowSnippetInput(input, context.workingDirectory ?? "."),
   inputSchema: EvalWorkflowSnippetInputJsonSchema,
   inputSchema: EvalWorkflowSnippetInputJsonSchema,
   outputSchema: EvalWorkflowSnippetOutputJsonSchema,
   outputSchema: EvalWorkflowSnippetOutputJsonSchema,

+ 10 - 63
apps/zcode-cli/packages/core/src/tool/handlers/save-workflow-description.ts

@@ -1,69 +1,16 @@
-// Composed at module load from the dynamic-workflow facade so the model always
-// sees the current API surface — same construction as CreateWorkflow's description.
+// SaveWorkflow 的常驻描述。
+//
+// 文件格式、实参声明与写作规则都在 `dynamic-workflows` 技能的「Tool
+// reference」里,由技能门保证读过。留在这里的是唯一一条**在决定调不调之前**就必须看见的
+// 规则——绝不主动保存。保存会在用户仓库里留下文件,而模型对「看起来挺通用」的判断远比用户
+// 宽松;这条门槛必须常驻,不能等到技能加载之后。
 
 
-import { FACADE_DTS } from "@zcode/dynamic-workflow";
-import { SAVED_WORKFLOW_GLOBAL_DIR, SAVED_WORKFLOW_PROJECT_DIR } from "@zcode/contracts";
-
-const INTRO = [
-  "Save a dynamic-workflow script so it can be run again later by name. The required `scope` field decides where it lives.",
-  `Project definitions go in \`${SAVED_WORKFLOW_PROJECT_DIR}/<name>.dwf.ts\`, committed with the repository like any other source file and visible only inside it. Global definitions go in \`~/${SAVED_WORKFLOW_GLOBAL_DIR}/<name>.dwf.ts\` and are available from every project on this machine. Run either with CreateWorkflow's \`saved\` source; discover them with ListSavedWorkflows.`,
-].join(" ");
-
-/**
- * 提示策略。这段是本工具描述里**最重要**的部分,所以写在最前、用最直白的祈使句。
- *
- * 理由:保存会在用户的仓库里留下一个文件,而模型对「这个 workflow 看起来挺通用」的判断
- * 远比用户宽松。一个会自作主张保存的 agent 会在几轮对话里往 `.zcode/workflows` 里堆满
- * 半成品,而那些文件此后会出现在每一次 ListSavedWorkflows 里。所以门槛不是"别乱存"这种
- * 程度副词,而是一条硬规则:先用散文建议,等用户点头,再调用。
- */
-const HINT_POLICY = [
-  "When to call it — read this before you call it:",
-  "- NEVER call this tool unsolicited. Saving writes a file into the user's repository; that is their decision, not yours.",
-  "- When a workflow you just built looks reusable, SUGGEST it in prose first — one sentence naming what you would save and why — and then stop and wait. Call SaveWorkflow only after the user agrees.",
-  '- If the user asks directly ("save this workflow", "保存这个工作流"), that is agreement: call it.',
-  "- A workflow is worth suggesting when it would plausibly be run again with different inputs. A one-off script tailored to a single question is not; suggesting it wastes the user's attention and clutters the project.",
-].join("\n");
-
-const FILE_FORMAT = [
-  "File format:",
-  "- The saved file is valid TypeScript: a `/* zcode-workflow` block comment carrying YAML metadata, followed by the script verbatim.",
-  "- `description` is required and shows up wherever the workflow is listed. `whenToUse` is optional guidance for whoever picks a workflow later — write it for a reader who has not seen this conversation.",
-  // 保存一份刚跑过的草稿是最常见的场景,而重新吐一遍脚本是这里唯一一笔可以省掉的大代价。
-  "- `script_path` saves a working draft without re-emitting it: pass the file a CreateWorkflow or AmendWorkflow result named instead of `script`, and its body is what gets saved (a `/* zcode-workflow` block in that file is dropped — the metadata comes from the fields here).",
-  "- Saving over an existing name REPLACES that workflow. The confirmation window tells the user whether this is a new file or an overwrite, so pick the name deliberately: reuse it to update a workflow, choose a new one to add a variant.",
-].join("\n");
-
-const ARGS = [
-  "Arguments:",
-  "- Declare `args` when the workflow should be reusable with different inputs — a PR number, a directory, a depth. Each declaration gives a `type` (`string`, `number`, `boolean`, or `json` for anything else), and optionally a `description`, `required: true`, and a `default`.",
-  "- Declared arguments are the workflow's calling convention: whoever runs it later must supply them, and CreateWorkflow validates the call against this declaration (unknown keys, missing required values and wrong types are rejected) before anything runs.",
-  "- Declare exactly the values that would change between runs, and no more. Every declared argument is one more thing a future caller has to get right.",
-].join("\n");
-
-const RULES = [
-  "Authoring rules — identical to CreateWorkflow, because the script is checked by the same compiler:",
-  "- Plain TypeScript. Define result types with a plain `interface Foo { ... }` or `type Foo = ...` and pass them as `ask<T>` type arguments.",
-  "- Compiled under `strict` (with `noUncheckedIndexedAccess` off): indexing an array or record (`items[i]`) needs no guard. `.find()`, `.match()`, `Map.get()` and optional properties still yield `T | undefined` / `null` and must be guarded before use.",
-  "- Never use the `declare` modifier, no `export` statements, and no `import` statements.",
-  "- No Node/web APIs: `process`, `fetch`, `fs` do not exist and fail typechecking.",
-  '- Group the script into phases with `phase("...")` markers, exactly as CreateWorkflow requires — a saved workflow shows the same phase graph whenever anyone runs it by name. Phase names are human-readable phrases in the session\'s language at save time; future callers did not see this conversation, so the names are all they get.',
-  "- The script is typechecked BEFORE the user is asked. Compilation errors come back as diagnostics and nothing is written: fix the script and call the tool again.",
-].join("\n");
+import { DYNAMIC_WORKFLOW_SKILL_NAME } from "@zcode/contracts";
 
 
 export const SAVE_WORKFLOW_TOOL_DESCRIPTION = [
 export const SAVE_WORKFLOW_TOOL_DESCRIPTION = [
-  INTRO,
-  "",
-  HINT_POLICY,
-  "",
-  FILE_FORMAT,
-  "",
-  ARGS,
+  "Save a dynamic-workflow script with its metadata so it can be run again later by name (CreateWorkflow's `saved` source; ListSavedWorkflows lists them). The required `scope` decides whether it lives in this project or globally.",
   "",
   "",
-  "The script is checked against these facade declarations:",
-  "```ts",
-  FACADE_DTS.trim(),
-  "```",
+  "NEVER call this tool unsolicited: saving writes a file into the user's repository, and that is their decision. When a workflow you just built looks reusable, suggest saving it in one sentence and wait; call SaveWorkflow only after the user agrees, or when the user asks directly.",
   "",
   "",
-  RULES,
+  `Load the \`${DYNAMIC_WORKFLOW_SKILL_NAME}\` skill with the Skill tool first: it carries the file format, the argument declarations and the authoring rules. The call is refused until that skill has been loaded in this session. Pass \`script\` (the body only) or \`script_path\` (a draft file, saved without re-emitting it), never both.`,
 ].join("\n");
 ].join("\n");

+ 3 - 0
apps/zcode-cli/packages/core/src/tool/handlers/save-workflow.ts

@@ -51,6 +51,7 @@ import {
 } from "./saved-workflows/index.js";
 } from "./saved-workflows/index.js";
 import { readWorkflowScriptFile } from "./workflow-path-source.js";
 import { readWorkflowScriptFile } from "./workflow-path-source.js";
 import { analyzeScript } from "./workflow-script-analysis.js";
 import { analyzeScript } from "./workflow-script-analysis.js";
+import { requireDynamicWorkflowSkill } from "./workflow-skill-gate.js";
 
 
 const SAVE_WORKFLOW_TIMEOUT_MS = 15_000;
 const SAVE_WORKFLOW_TIMEOUT_MS = 15_000;
 const SAVE_WORKFLOW_MODEL_BYTES = 24_000;
 const SAVE_WORKFLOW_MODEL_BYTES = 24_000;
@@ -264,6 +265,8 @@ export const saveWorkflowToolEntry: ToolEntry = {
   validateInput: (input) => validateSaveWorkflowInput(input),
   validateInput: (input) => validateSaveWorkflowInput(input),
   // 把落点与覆盖判定算进入参:确认窗与 hook 读的是同一份事实,且对所有客户端版本可见。
   // 把落点与覆盖判定算进入参:确认窗与 hook 读的是同一份事实,且对所有客户端版本可见。
   resolveInput: (input, context) =>
   resolveInput: (input, context) =>
+    // 技能门先于落点解析(handlers/workflow-skill-gate.ts):保存的也是一段脚本。
+    requireDynamicWorkflowSkill(context, SAVE_WORKFLOW_TOOL_NAME) ??
     resolveSaveWorkflowInput(input, context.workingDirectory ?? "."),
     resolveSaveWorkflowInput(input, context.workingDirectory ?? "."),
   prepareApproval: prepareSaveWorkflowApproval,
   prepareApproval: prepareSaveWorkflowApproval,
   inputSchema: SaveWorkflowInputJsonSchema,
   inputSchema: SaveWorkflowInputJsonSchema,

+ 68 - 0
apps/zcode-cli/packages/core/src/tool/handlers/workflow-draft-read-state.ts

@@ -0,0 +1,68 @@
+// ============================================================
+// 内联草稿记作「模型写过的文件」
+// ============================================================
+// Edit / Write 拒绝会话没读过的文件(FILE_NOT_READ):模型不能改它没见过的字节。内联草稿恰好是
+// 这条已经成立的文件——它的字节就是产生它的那次调用的 `script` 入参。不记这一笔,NOTE 要求的
+// 第一次 `Edit` 必然失败,补救是把模型自己刚写的两万 token 脚本整个 `Read` 一遍,正是草稿文件
+// 要省掉的那笔开销。
+//
+// **只由内联分支调用**:saved 拷贝(带模型没见过的元数据块)、沿用前驱脚本的新草稿(脚本可能
+// 来自别的会话或压缩之前)、中枢直接启动与 GUI 设置修订写下的草稿都不是模型本次亲手写的字节,
+// 记了就是替模型担保它没看过的内容。
+//
+// 与草稿本身一样**尽力而为**:stat 不到就不记,模型的第一次 Edit 退回「先 Read」的老路。
+
+import { createReadFileStateMetadataFromEntry } from "../read-file-state-metadata.js";
+import { createReadFileStateKey, normalizeReadFileStateMtimeMs } from "../read-file-state.js";
+import type { ReadFileStateEntry, ToolExecutionContext } from "../types.js";
+
+export type WorkflowDraftAuthoringTool = "CreateWorkflow" | "AmendWorkflow";
+
+const CRLF_PATTERN = /\r\n/gu;
+const LF = "\n";
+
+export async function recordAuthoredWorkflowDraft(
+  context: ToolExecutionContext,
+  draft: { path: string; source: string; toolName: WorkflowDraftAuthoringTool },
+): Promise<void> {
+  const { fileSystemPort, readFileState } = context;
+  if (readFileState === undefined || fileSystemPort === undefined) return;
+
+  let revision: { id: string; mtimeMs?: number; sizeBytes?: number } | undefined;
+  try {
+    // 与 Edit / Write 之后的 stale 校验读同一个端口,revision 的口径因此一致。stat 发生在写之后:
+    // 记下的 mtime 不早于草稿的真实 mtime,其后任何外部改动都会让 mtime 前进并判 stale。
+    const info = await fileSystemPort.stat(
+      { path: draft.path, trace: context.traceContext },
+      { signal: context.abortSignal },
+    );
+    revision = info.revision;
+  } catch {
+    return;
+  }
+  if (revision === undefined) return;
+
+  const entry: ReadFileStateEntry = {
+    path: draft.path,
+    // 端口读回的文本统一成 LF(FileSystemReadTextResult.content),快照跟随同一口径。
+    content: draft.source.replace(CRLF_PATTERN, LF),
+    offset: undefined,
+    limit: undefined,
+    isPartialView: false,
+    readAt: new Date(),
+    sourceTool: draft.toolName,
+    revisionId: revision.id,
+    mtimeMs: normalizeReadFileStateMtimeMs(revision.mtimeMs),
+    sizeBytes: revision.sizeBytes ?? Buffer.byteLength(draft.source, "utf8"),
+  };
+  readFileState.set(createReadFileStateKey(draft.path, 1, undefined), entry);
+
+  // resume 只从 tool part metadata 恢复 read-state(read-file-state-hydrator.ts),不落这一笔,
+  // 会话恢复后同一个 bug 原样回来。
+  const metadata = createReadFileStateMetadataFromEntry({
+    completedAt: entry.readAt,
+    entry,
+    toolName: draft.toolName,
+  });
+  if (metadata !== undefined) context.recordReadFileStateMetadata?.(metadata);
+}

+ 61 - 0
apps/zcode-cli/packages/core/src/tool/handlers/workflow-skill-gate.ts

@@ -0,0 +1,61 @@
+// 工作流创作工具的技能加载检查。
+// CreateWorkflow、AmendWorkflow、SaveWorkflow 和 EvalWorkflowSnippet 的工具描述保持简短,
+// facade 与写作规则由 `dynamic-workflows` 技能提供。提交脚本前必须加载技能:会话历史里没有
+// 成功的 `Skill(dynamic-workflows)` 调用时,resolveInput 直接拒绝,避免进入 hook 或显示无效确认窗。
+//
+// 判据来自模型当前可见的 messageHistory。compaction 移除技能正文及对应调用后,需要重新加载;
+// resume/rewind 则随历史一起恢复该判据,不维护第二份会话状态。
+// 探针缺席表示当前装配未提供技能加载检查,此时不设置无法满足的前提。
+
+import { DYNAMIC_WORKFLOW_SKILL_NAME } from "@zcode/contracts";
+import type { ToolHandlerFailure, ToolInputResolutionContext } from "../types.js";
+
+/**
+ * 「技能未加载」的稳定错误码。与四个工具的入参级 400 分开:调用方要能不靠文本区分「参数给错了」
+ * 与「先去读技能」——前者改参数,后者多一次 Skill 调用。
+ */
+export const WORKFLOW_SKILL_NOT_LOADED_CODE = 428;
+
+/** 门在场时的判据;单独导出供探针实现复用。 */
+export function isDynamicWorkflowSkillLoaded(context: ToolInputResolutionContext): boolean {
+  return context.hasLoadedSkill?.(DYNAMIC_WORKFLOW_SKILL_NAME) ?? true;
+}
+
+/**
+ * 没读过技能就拒绝。返回 `undefined` 表示放行:技能已加载,或本会话没有探针(见文件头)。
+ *
+ * @param toolName 拒绝文案里点名的工具,让模型知道重试哪一个。
+ */
+export function requireDynamicWorkflowSkill(
+  context: ToolInputResolutionContext,
+  toolName: string,
+): ToolHandlerFailure | undefined {
+  if (isDynamicWorkflowSkillLoaded(context)) return undefined;
+  return {
+    result: false,
+    errorCode: WORKFLOW_SKILL_NOT_LOADED_CODE,
+    message: `${toolName} needs the \`${DYNAMIC_WORKFLOW_SKILL_NAME}\` skill loaded in this session before it accepts a script. Call the Skill tool with skill "${DYNAMIC_WORKFLOW_SKILL_NAME}" first — it carries the facade declarations the script is checked against, the authoring rules and this tool's full contract — then call ${toolName} again. Nothing was started.`,
+  };
+}
+
+/** CreateWorkflow 的例外:按名字跑一个保存的工作流不是写脚本,不需要技能。 */
+export function createWorkflowNeedsSkill(input: unknown): boolean {
+  const fields = asRecord(input);
+  if (fields === undefined) return true;
+  const runsSavedOnly =
+    fields.saved !== undefined && fields.script === undefined && fields.path === undefined;
+  return !runsSavedOnly;
+}
+
+/** AmendWorkflow 的例外:只改设定(`path` 与 `script` 都不带)沿用前驱的脚本,不是写脚本。 */
+export function amendWorkflowNeedsSkill(input: unknown): boolean {
+  const fields = asRecord(input);
+  if (fields === undefined) return true;
+  return fields.script !== undefined || fields.path !== undefined;
+}
+
+function asRecord(value: unknown): Record<string, unknown> | undefined {
+  return value !== null && typeof value === "object" && !Array.isArray(value)
+    ? (value as Record<string, unknown>)
+    : undefined;
+}

+ 15 - 2
apps/zcode-cli/packages/core/src/tool/read-file-state-metadata.ts

@@ -3,7 +3,14 @@ import { createReadFileStateKey } from "./read-file-state.js";
 import type { ReadFileStateEntry, ReadFileStateMap } from "./types.js";
 import type { ReadFileStateEntry, ReadFileStateMap } from "./types.js";
 
 
 export const READ_FILE_STATE_METADATA_SCHEMA_VERSION = 1;
 export const READ_FILE_STATE_METADATA_SCHEMA_VERSION = 1;
-export type PersistedReadFileStateTool = "Read" | "Write" | "Edit";
+// `CreateWorkflow` / `AmendWorkflow`:内联草稿的字节就是模型那次调用的 `script` 入参,与 Write
+// 同理记作完整视图(handlers/workflow-draft-read-state.ts)。
+export type PersistedReadFileStateTool =
+  | "Read"
+  | "Write"
+  | "Edit"
+  | "CreateWorkflow"
+  | "AmendWorkflow";
 
 
 export interface PersistedReadFileStateMetadata {
 export interface PersistedReadFileStateMetadata {
   schemaVersion: typeof READ_FILE_STATE_METADATA_SCHEMA_VERSION;
   schemaVersion: typeof READ_FILE_STATE_METADATA_SCHEMA_VERSION;
@@ -123,7 +130,13 @@ export function parseReadFileStateMetadata(
 }
 }
 
 
 function isPersistedReadFileStateTool(value: unknown): value is PersistedReadFileStateTool {
 function isPersistedReadFileStateTool(value: unknown): value is PersistedReadFileStateTool {
-  return value === "Read" || value === "Write" || value === "Edit";
+  return (
+    value === "Read" ||
+    value === "Write" ||
+    value === "Edit" ||
+    value === "CreateWorkflow" ||
+    value === "AmendWorkflow"
+  );
 }
 }
 
 
 function asRecord(value: unknown): Record<string, unknown> | undefined {
 function asRecord(value: unknown): Record<string, unknown> | undefined {

+ 11 - 2
apps/zcode-cli/packages/core/src/tool/types.ts

@@ -55,7 +55,10 @@ import type {
   ToolExecutionSpanWriter,
   ToolExecutionSpanWriter,
   ToolExecutionTelemetry,
   ToolExecutionTelemetry,
 } from "@zcode/contracts";
 } from "@zcode/contracts";
-import type { PersistedReadFileStateMetadata } from "./read-file-state-metadata.js";
+import type {
+  PersistedReadFileStateMetadata,
+  PersistedReadFileStateTool,
+} from "./read-file-state-metadata.js";
 import type { RuntimeTaskRegistry } from "../runtime-task/registry.js";
 import type { RuntimeTaskRegistry } from "../runtime-task/registry.js";
 
 
 // -----------------------------------------------
 // -----------------------------------------------
@@ -207,7 +210,7 @@ export interface ReadFileStateEntry {
   limit?: number;
   limit?: number;
   isPartialView: boolean;
   isPartialView: boolean;
   readAt: Date;
   readAt: Date;
-  sourceTool?: "Read" | "Write" | "Edit";
+  sourceTool?: PersistedReadFileStateTool;
   revisionId?: string;
   revisionId?: string;
   mtimeMs?: number;
   mtimeMs?: number;
   sizeBytes?: number;
   sizeBytes?: number;
@@ -253,6 +256,12 @@ export interface ToolInputResolutionContext {
    */
    */
   modelCatalogPort?: ModelCatalogPort;
   modelCatalogPort?: ModelCatalogPort;
   sessionId?: string;
   sessionId?: string;
+  /**
+   * 「这个会话此刻加载着某个技能吗」的探针(handlers/workflow-skill-gate.ts)。由 runtime 用
+   * provider 可见历史回答(agent/loaded-skills.ts),所以 compaction 之后答案随历史一起变回
+   * 否。缺席 = 本会话没有 Skill 工具或调用方不参与,门不生效。
+   */
+  hasLoadedSkill?: (skillName: string) => boolean;
 }
 }
 
 
 export type ToolInputResolutionResult = { result: true; input: unknown } | ToolHandlerFailure;
 export type ToolInputResolutionResult = { result: true; input: unknown } | ToolHandlerFailure;

+ 23 - 0
apps/zcode-cli/packages/dynamic-workflow-runtime/src/harness.ts

@@ -50,6 +50,20 @@ import { writeChildEntryFile, type HarnessWarning } from "./child-entry-file.js"
 /** driver 工厂:harness 先建 sink(引擎的向上回报面),交给工厂造 driver,再以该 driver 建引擎。 */
 /** driver 工厂:harness 先建 sink(引擎的向上回报面),交给工厂造 driver,再以该 driver 建引擎。 */
 export type DriverFactory = (sink: WorkflowReportSink) => WorkflowDriver;
 export type DriverFactory = (sink: WorkflowReportSink) => WorkflowDriver;
 
 
+/**
+ * run 的**活体控制面**:harness 在引擎构造好之后把这一世的引擎交给它,于是持有句柄的那一侧
+ * (run service)能够到活着的引擎。今日只有一条命令——就地改本 run 的并发上界。
+ *
+ * 收窄成 `Pick<…, "setMaxConcurrency">` 而不是整个引擎:控制面是一条**命令**通道,不是让
+ * 宿主绕过 harness 去驱动 run 生命周期的后门(结算仍然只经 complete/stop/fail 那三条路)。
+ *
+ * 与 `signal` 同规:harness 只做接线,不解释、不校验、不兜底;命令的存活判定与 no-op 语义
+ * 全在引擎里(`setMaxConcurrency` 返回 false 即这次什么也没发生)。
+ */
+export interface RunControlBinding {
+  bind(engine: Pick<WorkflowEngine, "setMaxConcurrency">): void;
+}
+
 /**
 /**
  * {@link runWorkflowScript} 的入参。执行体来自 `scriptText` 或 `lowered`(后者优先);
  * {@link runWorkflowScript} 的入参。执行体来自 `scriptText` 或 `lowered`(后者优先);
  * 两者同时给出正是「编译一次」的形态——调用方自己编译得到 `lowered`,同时把作者写的
  * 两者同时给出正是「编译一次」的形态——调用方自己编译得到 `lowered`,同时把作者写的
@@ -84,6 +98,12 @@ export interface RunWorkflowOptions {
   validate: ValidateFn;
   validate: ValidateFn;
   /** 外部取消信号:中止在飞 ask 并 kill 子进程,run 结算 cancelled。 */
   /** 外部取消信号:中止在飞 ask 并 kill 子进程,run 结算 cancelled。 */
   signal?: AbortSignal;
   signal?: AbortSignal;
+  /**
+   * 活体控制面的绑定口(见 {@link RunControlBinding})。与 `signal` 同一条缝递进来:
+   * 那个是「停下这个 run」的通道,这个是「改这个 run 的一项设置」的通道。缺席即本次启动
+   * 没有控制面(如 snippet 执行)。
+   */
+  control?: RunControlBinding;
   /** 墙钟超时(ms):到点 kill 子进程,run 结算 failed。缺省不限。 */
   /** 墙钟超时(ms):到点 kill 子进程,run 结算 failed。缺省不限。 */
   timeoutMs?: number;
   timeoutMs?: number;
   /** 子进程堆上限(MB),映射为 `--max-old-space-size`。缺省 256。 */
   /** 子进程堆上限(MB),映射为 `--max-old-space-size`。缺省 256。 */
@@ -212,6 +232,9 @@ export async function runWorkflowScript(options: RunWorkflowOptions): Promise<Ru
     ...(options.inheritedTokens === undefined ? {} : { inheritedTokens: options.inheritedTokens }),
     ...(options.inheritedTokens === undefined ? {} : { inheritedTokens: options.inheritedTokens }),
     cwd: options.cwd ?? process.cwd(),
     cwd: options.cwd ?? process.cwd(),
   });
   });
+  // 控制面一构造好就绑:run 从第一条事件起就可被改设置,而**不必**等子进程起来——下面那条
+  // spawn 失败路径也经引擎结算,句柄在那之后照样安全(命令自己的 settled 判定负责收口)。
+  options.control?.bind(engine);
 
 
   const maxOldSpaceSizeMb = options.maxOldSpaceSizeMb ?? DEFAULT_MAX_OLD_SPACE_MB;
   const maxOldSpaceSizeMb = options.maxOldSpaceSizeMb ?? DEFAULT_MAX_OLD_SPACE_MB;
   const cwd = options.cwd ?? process.cwd();
   const cwd = options.cwd ?? process.cwd();

+ 6 - 1
apps/zcode-cli/packages/dynamic-workflow-runtime/src/index.ts

@@ -7,7 +7,12 @@
  * `import()` 文件并调它的 `start`。
  * `import()` 文件并调它的 `start`。
  */
  */
 
 
-export { runWorkflowScript, type RunWorkflowOptions, type DriverFactory } from "./harness.js";
+export {
+  runWorkflowScript,
+  type DriverFactory,
+  type RunControlBinding,
+  type RunWorkflowOptions,
+} from "./harness.js";
 export {
 export {
   childMain,
   childMain,
   renderChildEntry,
   renderChildEntry,

+ 41 - 0
apps/zcode-cli/packages/dynamic-workflow/src/engine/engine-artifacts-primary.ts

@@ -0,0 +1,41 @@
+/**
+ * 交付物的 primary 标记:全 run 至多一个 ID 带有该标记。
+ * 内容成员与预置成员共用同一组准入判据。
+ *
+ * 这些函数只读 `state.artifacts`,不落库、不发事件;状态从 journal 派生,resume 后保持一致。
+ * 调用方根据判据决定拒绝发布还是使整个 run 失败。
+ */
+
+import type { EngineState } from "./engine-state.js";
+import type { InstanceRef } from "./types.js";
+import { refToString } from "./types.js";
+
+/** 本 run 目前的 primary id(至多一个);没有则 undefined。从 `state.artifacts` 派生,resume 后自然一致。 */
+export function primaryArtifactId(state: EngineState): string | undefined {
+  for (const [id, idState] of state.artifacts) if (idState.primary) return id;
+  return undefined;
+}
+
+/** `id` 想当 primary 而**别的** id 已经是 ⇒ 返回那个 id;否则 undefined(不想当 / 就是它自己)。 */
+export function primaryConflict(
+  state: EngineState,
+  id: string,
+  primary: boolean,
+): string | undefined {
+  if (!primary) return undefined;
+  const holder = primaryArtifactId(state);
+  return holder === undefined || holder === id ? undefined : holder;
+}
+
+export function primaryConflictMessage(
+  id: string,
+  holder: string,
+  fix: string,
+  instance: InstanceRef | undefined,
+): string {
+  const where = instance === undefined ? "" : ` (at ${refToString(instance)})`;
+  return (
+    `Cannot mark "${id}" as primary${where}: "${holder}" is already this run's primary artifact. ` +
+    `A run has one deliverable; ${fix}, or publish it as a new version of "${holder}".`
+  );
+}

+ 21 - 29
apps/zcode-cli/packages/dynamic-workflow/src/engine/engine-artifacts.ts

@@ -13,6 +13,12 @@ import {
   type ArtifactContentOp,
   type ArtifactContentOp,
   type ArtifactPresetOp,
   type ArtifactPresetOp,
 } from "../facade/registry.js";
 } from "../facade/registry.js";
+import { heldResolution } from "./replay-order.js";
+import {
+  primaryArtifactId,
+  primaryConflict,
+  primaryConflictMessage,
+} from "./engine-artifacts-primary.js";
 import { validateArtifactSpec } from "./artifact-spec.js";
 import { validateArtifactSpec } from "./artifact-spec.js";
 import { hashMismatch } from "./scheduler.js";
 import { hashMismatch } from "./scheduler.js";
 import type { EngineState } from "./engine-state.js";
 import type { EngineState } from "./engine-state.js";
@@ -102,12 +108,19 @@ export function publishContentArtifact(
       state.failRun(err);
       state.failRun(err);
       return Promise.reject(err);
       return Promise.reject(err);
     }
     }
+    // 与 ask / world 命中同规:释放点过 replay 次序闸。发布是效应、脚本要 await 它,所以它也是一个能决定
+    // 后续续体次序的释放点;预置声明是同步 void,从不走这条路,也就从不占闸。
     if (recorded.status === "completed") {
     if (recorded.status === "completed") {
       const record = recorded.result as ArtifactVersionRecord;
       const record = recorded.result as ArtifactVersionRecord;
-      return Promise.resolve({ id: record.id, version: record.version });
+      return heldResolution(state.holdForReplay, instance, () => ({
+        id: record.id,
+        version: record.version,
+      }));
     }
     }
     if (recorded.status === "failed") {
     if (recorded.status === "failed") {
-      return Promise.reject(WorkflowError.fromJSON(recorded.error!));
+      return heldResolution(state.holdForReplay, instance, () => {
+        throw WorkflowError.fromJSON(recorded.error!);
+      });
     }
     }
     // status === "running":崩溃于执行中,落到下面重新 live 执行(字节的拷贝是幂等的,
     // status === "running":崩溃于执行中,落到下面重新 live 执行(字节的拷贝是幂等的,
     // 而版本号从**已 completed 的行数**派生,所以重跑不会跳号)。
     // 而版本号从**已 completed 的行数**派生,所以重跑不会跳号)。
@@ -371,7 +384,12 @@ function settleArtifactPublish(
       issued,
       issued,
       new WorkflowError(
       new WorkflowError(
         "ArtifactPrimaryConflict",
         "ArtifactPrimaryConflict",
-        primaryConflictMessage(issued.id, holder, `publish "${issued.id}" without primary`, instance),
+        primaryConflictMessage(
+          issued.id,
+          holder,
+          `publish "${issued.id}" without primary`,
+          instance,
+        ),
       ),
       ),
     );
     );
   }
   }
@@ -396,32 +414,6 @@ function settleArtifactPublish(
   return { id: issued.id, version: issued.version };
   return { id: issued.id, version: issued.version };
 }
 }
 
 
-/** 本 run 目前的 primary id(至多一个);没有则 undefined。从 `state.artifacts` 派生,resume 后自然一致。 */
-function primaryArtifactId(state: EngineState): string | undefined {
-  for (const [id, idState] of state.artifacts) if (idState.primary) return id;
-  return undefined;
-}
-
-/** `id` 想当 primary 而**别的** id 已经是 ⇒ 返回那个 id;否则 undefined(不想当 / 就是它自己)。 */
-function primaryConflict(state: EngineState, id: string, primary: boolean): string | undefined {
-  if (!primary) return undefined;
-  const holder = primaryArtifactId(state);
-  return holder === undefined || holder === id ? undefined : holder;
-}
-
-function primaryConflictMessage(
-  id: string,
-  holder: string,
-  fix: string,
-  instance: InstanceRef | undefined,
-): string {
-  const where = instance === undefined ? "" : ` (at ${refToString(instance)})`;
-  return (
-    `Cannot mark "${id}" as primary${where}: "${holder}" is already this run's primary artifact. ` +
-    `A run has one deliverable; ${fix}, or publish it as a new version of "${holder}".`
-  );
-}
-
 /**
 /**
  * 内容产物发布失败:落 failed 行 + 发 `artifact-failed`,返回要抛出的错误。
  * 内容产物发布失败:落 failed 行 + 发 `artifact-failed`,返回要抛出的错误。
  *
  *

Some files were not shown because too many files changed in this diff