@thincoder/core 0.11.3 → 0.11.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/advisor/compaction.mjs +40 -17
  3. package/advisor/loop.mjs +14 -6
  4. package/advisor/notice.mjs +1 -1
  5. package/advisor/timeline.mjs +4 -4
  6. package/agent/completion.mjs +19 -0
  7. package/agent/dispatch-gates.mjs +2 -0
  8. package/agent/dispatch.mjs +2 -2
  9. package/agent/family-tools.mjs +13 -9
  10. package/agent/helpers.mjs +10 -6
  11. package/agent/planning-step.mjs +453 -0
  12. package/agent/post-turn.mjs +70 -2
  13. package/agent/run-stages.mjs +22 -50
  14. package/agent/run-start.mjs +17 -0
  15. package/agent/setup-reminders.mjs +71 -8
  16. package/agent/setup.mjs +8 -39
  17. package/agent/spawn-child.mjs +6 -2
  18. package/agent/task-lifecycle.mjs +146 -0
  19. package/agent/turn-loop.mjs +73 -11
  20. package/agent-tools/batch-closeout.mjs +21 -34
  21. package/agent-tools/batch-gate.mjs +7 -5
  22. package/agent-tools/batch-ledger-bind.mjs +21 -1
  23. package/agent-tools/batch-lifecycle.mjs +7 -7
  24. package/agent-tools/batch-record-write.mjs +237 -280
  25. package/agent-tools/batch-supersede.mjs +3 -3
  26. package/agent-tools/batch.mjs +42 -9
  27. package/agent-tools/context.mjs +0 -13
  28. package/agent-tools/escalate-async.mjs +7 -1
  29. package/agent-tools/parent-channel.mjs +7 -6
  30. package/agent-tools/plan.mjs +103 -67
  31. package/agent-tools/review-facts.mjs +3 -3
  32. package/agent-tools/settings.mjs +2 -0
  33. package/agent-tools/spawn-gates.mjs +37 -11
  34. package/agent-tools/ssh-session.mjs +68 -25
  35. package/agent-tools/ssh-transfer.mjs +7 -2
  36. package/agent-tools/ssh-transport.mjs +2 -2
  37. package/agent-tools/ssh-vault.mjs +2 -2
  38. package/agent-tools/step.mjs +462 -0
  39. package/agent-tools/subagent-actions.mjs +6 -1
  40. package/agent-tools/subagent-run.mjs +7 -0
  41. package/agent-tools/subagent-spawn.mjs +1 -1
  42. package/agent-tools/subagent.mjs +17 -11
  43. package/agent-tools/task.mjs +178 -26
  44. package/agent-tools.mjs +1 -0
  45. package/agent.mjs +2 -0
  46. package/config-defaults.mjs +17 -1
  47. package/config-migrate.mjs +8 -5
  48. package/config.mjs +7 -0
  49. package/context.mjs +5 -4
  50. package/declaration.mjs +4 -4
  51. package/generate-title.mjs +0 -6
  52. package/i18n.mjs +4 -0
  53. package/ledger-cmd.mjs +11 -1
  54. package/ledger-tools.mjs +15 -4
  55. package/manifest-schema.mjs +1 -0
  56. package/model-context.mjs +34 -11
  57. package/model-specs.mjs +5 -2
  58. package/package.json +1 -1
  59. package/prompt-files.mjs +48 -11
  60. package/prompt-overlays.mjs +79 -8
  61. package/prompts/advisor-design.md +253 -206
  62. package/prompts/advisor-round1.md +151 -145
  63. package/prompts/advisor-round2.md +136 -130
  64. package/prompts/advisor-round3.md +140 -134
  65. package/prompts/common.md +244 -96
  66. package/prompts/consult-base.md +29 -30
  67. package/prompts/discipline-engineering.md +73 -519
  68. package/prompts/discipline-normal.md +28 -136
  69. package/prompts/knowledge/batch-before-write.md +8 -0
  70. package/prompts/knowledge/batch-cycle-register.md +15 -0
  71. package/prompts/knowledge/batch-progress-ledger.md +29 -0
  72. package/prompts/knowledge/business-gates.md +24 -24
  73. package/prompts/knowledge/decision-quality.md +8 -19
  74. package/prompts/knowledge/doc-discipline-d-rules.md +63 -0
  75. package/prompts/knowledge/doc-lookup.md +25 -24
  76. package/prompts/knowledge/document-writing.md +11 -32
  77. package/prompts/knowledge/documentation-evaluation.md +42 -42
  78. package/prompts/knowledge/eng-dispatch-ops.md +34 -0
  79. package/prompts/knowledge/eng-ledger-ops.md +26 -0
  80. package/prompts/knowledge/evidence-discipline.md +10 -32
  81. package/prompts/knowledge/normal-batch-discipline.md +13 -0
  82. package/prompts/knowledge/normal-coding-workflow.md +97 -99
  83. package/prompts/knowledge/normal-delivery-collaboration.md +107 -112
  84. package/prompts/knowledge/normal-work-management.md +44 -44
  85. package/prompts/knowledge/product-security.md +7 -26
  86. package/prompts/knowledge/project-records.md +69 -64
  87. package/prompts/knowledge/tool-advisor.md +17 -17
  88. package/prompts/knowledge/tool-apply-patch.md +14 -14
  89. package/prompts/knowledge/tool-bash.md +32 -31
  90. package/prompts/knowledge/tool-batch-eng-coder.md +19 -13
  91. package/prompts/knowledge/tool-batch-eng-designer.md +21 -14
  92. package/prompts/knowledge/tool-batch-review.md +18 -12
  93. package/prompts/knowledge/tool-batch.md +93 -85
  94. package/prompts/knowledge/tool-browser.md +59 -59
  95. package/prompts/knowledge/tool-code-search.md +2 -2
  96. package/prompts/knowledge/tool-consult-start.md +6 -6
  97. package/prompts/knowledge/tool-consult-stop.md +3 -3
  98. package/prompts/knowledge/tool-context.md +4 -4
  99. package/prompts/knowledge/tool-delete.md +16 -16
  100. package/prompts/knowledge/tool-doc-check.md +39 -39
  101. package/prompts/knowledge/tool-doc-graph-read.md +11 -11
  102. package/prompts/knowledge/tool-doc-graph.md +48 -48
  103. package/prompts/knowledge/tool-doc-search.md +3 -3
  104. package/prompts/knowledge/tool-edit.md +30 -30
  105. package/prompts/knowledge/tool-eng.md +1 -1
  106. package/prompts/knowledge/tool-execute.md +16 -16
  107. package/prompts/knowledge/tool-fetch.md +15 -15
  108. package/prompts/knowledge/tool-file-ops.md +15 -15
  109. package/prompts/knowledge/tool-get-current-time.md +3 -3
  110. package/prompts/knowledge/tool-git-read.md +15 -15
  111. package/prompts/knowledge/tool-git.md +26 -26
  112. package/prompts/knowledge/tool-glob.md +14 -14
  113. package/prompts/knowledge/tool-goal.md +5 -5
  114. package/prompts/knowledge/tool-grep.md +19 -18
  115. package/prompts/knowledge/tool-hashline-edit.md +13 -13
  116. package/prompts/knowledge/tool-insert-after.md +14 -14
  117. package/prompts/knowledge/tool-instance-list.md +3 -3
  118. package/prompts/knowledge/tool-instance-send.md +5 -5
  119. package/prompts/knowledge/tool-knowledge.md +12 -12
  120. package/prompts/knowledge/tool-ledger-read.md +20 -20
  121. package/prompts/knowledge/tool-ledger.md +44 -44
  122. package/prompts/knowledge/tool-lint.md +10 -10
  123. package/prompts/knowledge/tool-ls.md +11 -11
  124. package/prompts/knowledge/tool-lsp.md +8 -8
  125. package/prompts/knowledge/tool-main-history.md +1 -1
  126. package/prompts/knowledge/tool-manifest-read.md +7 -7
  127. package/prompts/knowledge/tool-manifest.md +43 -32
  128. package/prompts/knowledge/tool-memory-read.md +12 -12
  129. package/prompts/knowledge/tool-memory.md +14 -14
  130. package/prompts/knowledge/tool-notify-parent.md +10 -10
  131. package/prompts/knowledge/tool-operations.md +88 -88
  132. package/prompts/knowledge/tool-peek.md +10 -0
  133. package/prompts/knowledge/tool-peer-instances.md +1 -1
  134. package/prompts/knowledge/tool-plan.md +6 -3
  135. package/prompts/knowledge/tool-process-read.md +8 -8
  136. package/prompts/knowledge/tool-process.md +11 -11
  137. package/prompts/knowledge/tool-question.md +11 -13
  138. package/prompts/knowledge/tool-read-history-batch.md +13 -13
  139. package/prompts/knowledge/tool-read-history.md +19 -19
  140. package/prompts/knowledge/tool-read-image.md +8 -8
  141. package/prompts/knowledge/tool-read.md +17 -17
  142. package/prompts/knowledge/tool-recent-changes.md +4 -4
  143. package/prompts/knowledge/tool-repo-outline.md +2 -2
  144. package/prompts/knowledge/tool-settings-read.md +5 -7
  145. package/prompts/knowledge/tool-settings.md +10 -10
  146. package/prompts/knowledge/tool-skill.md +4 -4
  147. package/prompts/knowledge/tool-ssh.md +66 -66
  148. package/prompts/knowledge/tool-step.md +26 -0
  149. package/prompts/knowledge/tool-subagent.md +52 -50
  150. package/prompts/knowledge/tool-task.md +14 -11
  151. package/prompts/knowledge/tool-team-ledger-read.md +7 -7
  152. package/prompts/knowledge/tool-team-ledger.md +13 -13
  153. package/prompts/knowledge/tool-timer.md +14 -14
  154. package/prompts/knowledge/tool-tree.md +11 -11
  155. package/prompts/knowledge/tool-verify.md +11 -11
  156. package/prompts/knowledge/tool-wait-for.md +20 -20
  157. package/prompts/knowledge/tool-websearch.md +16 -14
  158. package/prompts/knowledge/tool-write.md +10 -10
  159. package/prompts/knowledge/upstream-protocol.md +37 -38
  160. package/prompts/persona-coder.md +22 -22
  161. package/prompts/persona-eng-coder.md +87 -81
  162. package/prompts/persona-eng-designer.md +173 -153
  163. package/prompts/persona-engineering.md +53 -554
  164. package/prompts/persona-explore.md +18 -15
  165. package/prompts/persona-normal.md +62 -63
  166. package/prompts/persona-plan.md +36 -32
  167. package/prompts/persona-tester.md +39 -39
  168. package/prompts/planning-next-moves.md +9 -0
  169. package/prompts/subagent-base.md +4 -16
  170. package/provider/errors.mjs +0 -24
  171. package/provider/list-models.mjs +20 -2
  172. package/session-lifecycle.mjs +4 -3
  173. package/tool-args.mjs +25 -0
  174. package/tool-docs/peek.md +3 -0
  175. package/tool-docs/plan.md +1 -1
  176. package/tool-docs/question.md +1 -1
  177. package/tool-docs/step.md +3 -0
  178. package/tools/edit-diff.mjs +4 -4
  179. package/tools/index.mjs +3 -2
  180. package/tools/peek.mjs +447 -0
  181. package/tools/question.mjs +87 -9
  182. package/tools/ssh.mjs +1 -1
  183. package/window-policy.mjs +107 -80
@@ -14,8 +14,8 @@
14
14
  * D-5 取代者解得出在盘落点且不指回本档。
15
15
  *
16
16
  * 保留门(「从未实施」不是「环节全免」):本批批内单测档门、文档机检门、完成清单预检(`requireAllInFlight=false`
17
- * 那一支)、设计凭证消费、写序与失败补偿、`[ledger consistency]` 回执行——全部保留,只跳过链门的内容门与
18
- * `§3` 状态词臂(`assertCloseoutGates({ mode: "supersede" })`)。
17
+ * 那一支)、设计凭证消费、写序与失败补偿、`[ledger consistency]` 回执行——全部保留,跳过 ① 链门、
18
+ * ② 末轮块裁定臂与 ⑤ 档位臂以外的臂不动;③④ 照跑(`assertCloseoutGates({ mode: "supersede" })`)。
19
19
  *
20
20
  * 依赖单向:`skeleton ← closeout ← ledger-view ← lifecycle ← 本档 ← batch.mjs`(本档 import lifecycle 的四个
21
21
  * 出口而不反向——lifecycle 不 import 本档,无环)。
@@ -209,7 +209,7 @@ export async function supersedeBatchRecord({ args, ctx, review, pickTarget, onWr
209
209
  if (sectionContentState(src, 5) !== "empty") throw new Error(implementedError())
210
210
  // D-5:取代者三形(解不到 ⇒ 拒;解析回本档 ⇒ 拒,走重开径)
211
211
  const successor = resolveSupersededBy(cwd, args?.supersededBy, abs)
212
- // 保留门:只跳过链内容门与 §3 状态词臂(本批批内单测档门 ∥ 文档机检门照跑)
212
+ // 保留门:跳过 ① 链门、② 末轮块裁定臂与 ⑤ 档位臂以外的臂不动,③④ 照跑
213
213
  const gate = assertCloseoutGates({ abs, cwd, agent: ctx?.agent ?? {}, src, action: "close", mode: "supersede" })
214
214
  // 完成清单预检:本路传 false——未点名的在途行走退回边,故「漏列在途行」那一臂不触发;
215
215
  // closeEvidence 这一格不随结算行数放宽(同一判据在三条路上不能两套)。
@@ -46,10 +46,10 @@ import { createBatchRecord, attachBatchRecord } from "./batch-ledger-bind.mjs"
46
46
  import { checkBatchRecord, closeBatchRecord, findInFlightBatch, statusBatchRecord } from "./batch-lifecycle.mjs"
47
47
  import { readBatchRecord } from "./batch-read.mjs"
48
48
  import { supersedeBatchRecord } from "./batch-supersede.mjs"
49
- import { appendBatchRecord, editBatchRecord } from "./batch-record-write.mjs"
49
+ import { appendBatchRecord, editBatchRecord, updateBatchRecord } from "./batch-record-write.mjs"
50
50
 
51
51
  export { SEGMENT_BY_ROLE, batchDocBases, resolveBatchDocPath }
52
- export { MAX_TEXT_CHARS } from "./batch-record-write.mjs"
52
+ export { MAX_TEXT_CHARS, MAX_UPDATE_ENTRIES } from "./batch-record-write.mjs"
53
53
 
54
54
  // ─── #84 记账面注入缝(「记账面按端注入」,形态参 §2.13.5 注入缝)───────────────
55
55
  /**
@@ -92,12 +92,12 @@ export function batchDocForReview(agent, documents, callbacks = null) {
92
92
  * 身份白名单裁决,本档只裁**动作面与参数面**)。
93
93
  * 描述取各自一份档——全量档 `batch.md` 通篇讲全量动作,子代理读到它就是读到做不到的事(B6)。
94
94
  */
95
- const PROFILE_ACTIONS = ["append", "edit", "status", "read"]
95
+ const PROFILE_ACTIONS = ["append", "edit", "update", "status", "read"]
96
96
  const PROFILE_SEGMENTS = { "eng-designer": 2, "eng-coder": 5, coder: 5, review: 3 }
97
97
  const PROFILE_DOCS = { "eng-designer": "batch-eng-designer", "eng-coder": "batch-eng-coder", coder: "batch-eng-coder", review: "batch-review" }
98
98
  /** profile 面保留的参数(其余参数只服务 create / attach / close / path,profile 执行不到 ⇒ 不出现)。
99
- * `offset` 只服务 `read` 的窗口形——profile 面同样要能取它。 */
100
- const PROFILE_PROPS = ["segment", "text", "oldText", "newText", "value", "note", "offset"]
99
+ * `offset` 只服务 `read` 的窗口形,`entries` 服务 `update` 的批量同笔写——profile 面同样可用。 */
100
+ const PROFILE_PROPS = ["segment", "text", "oldText", "newText", "entries", "value", "note", "offset"]
101
101
  /** profile 面的 `segment` 参数(只点名自己那段——全量档那句把六个身份的白名单一起列出来,
102
102
  * 子代理读到的是别的身份的写域)。 */
103
103
  function profileSegmentProp(profileKey) {
@@ -115,8 +115,8 @@ function fullParameters() {
115
115
  properties: {
116
116
  action: {
117
117
  type: "string",
118
- enum: ["create", "attach", "append", "edit", "status", "close", "supersede", "check", "read"],
119
- description: "Which lifecycle step to run: create (new record) / attach — hang a ledger row on an ALREADY EXISTING in-flight record (depth-0 only: a reopened record taking on a new piece of work; opens a new row, or takes over an unsettled one with ledger:\"#<id>\", and writes its number into the header 台账 line) / append (add text to the END of your section) / edit — replace one anchored range inside YOUR OWN section (§1–§6 alike; your identity decides which section) / status (your section's status line) / close (freeze the record — this settles the batch's ledger rows in the same action) / supersede — freeze a record whose object is gone and will never be implemented, naming what replaced it (supersededBy); it never writes §3/§4/§6, settles the 待核销 rows and returns the unnamed 在途 rows to 待讨论 with the conditional-resume trigger (depth-0 only) / check (depth-0 only, read-only: print this record's half-state readings — §1 open|closed, its ledger rows, and every record↔ledger inconsistency with the way out) / read (read-only, every seat that holds this tool: no `segment` ⇒ the record's section index — the header rows plus one line per section with its status word and body line count; `segment` + REQUIRED `offset` ⇒ one window of that section's body, 1-based, at most 200 lines, the receipt naming the next `offset`. A closed record reads the same — freezing is a write gate. The read domain is the whole record, not your pen: §1 carries the rulings, §3 the previous round, §5 the implementation record.)",
118
+ enum: ["create", "attach", "append", "edit", "update", "status", "close", "supersede", "check", "read"],
119
+ description: "Which lifecycle step to run: create (new record) / attach — hang a ledger row on an ALREADY EXISTING in-flight record (depth-0 only: a reopened record taking on a new piece of work; opens a new row, or takes over an unsettled one with ledger:\"#<id>\", and writes its number into the header 台账 line) / append (add text to the END of one section) / edit — replace one anchored range inside YOUR OWN section (§1–§6 alike; your identity decides which section) / update — atomically apply multiple section append/edit operations in ONE call via `entries` (all-or-nothing: every entry checks the same author whitelist and guards, runs one doc-check gate, and lands in one write; prefer this whenever updating 2+ sections or multiple ranges in one turn) / status (your section's status line) / close (freeze the record — this settles the batch's ledger rows in the same action) / supersede — freeze a record whose object is gone and will never be implemented, naming what replaced it (supersededBy); it never writes §3/§4/§6, settles the 待核销 rows and returns the unnamed 在途 rows to 待讨论 with the conditional-resume trigger (depth-0 only) / check (depth-0 only, read-only: print this record's half-state readings — §1 open|closed, its ledger rows, and every record↔ledger inconsistency with the way out) / read (read-only, every seat that holds this tool: no `segment` ⇒ the record's section index — the header rows plus one line per section with its status word and body line count; `segment` + REQUIRED `offset` ⇒ one window of that section's body, 1-based, at most 200 lines, the receipt naming the next `offset`. A closed record reads the same — freezing is a write gate. The read domain is the whole record, not your pen: §1 carries the rulings, §3 the previous round, §5 the implementation record.)",
120
120
  },
121
121
  path: {
122
122
  type: "string",
@@ -142,6 +142,37 @@ function fullParameters() {
142
142
  type: "string",
143
143
  description: "edit only — the replacement text for the anchored range; an empty string deletes the range. Limit 20000 characters per call (same cap as append); longer is refused — split it into several edits of one anchored range each. Credentials are stripped mechanically (same as append); a `## §N` heading line is refused (skeleton protection), and on §3 a `### 轮次 N(评审子代理)` line is dropped (the round stamp is tool-generated only).",
144
144
  },
145
+ entries: {
146
+ type: "array",
147
+ items: {
148
+ type: "object",
149
+ properties: {
150
+ op: {
151
+ type: "string",
152
+ enum: ["append", "edit"],
153
+ description: "Operation for this entry: \"append\" (requires text) or \"edit\" (requires oldText + newText). May be omitted when unambiguous from its fields.",
154
+ },
155
+ segment: {
156
+ type: "string",
157
+ description: "Target section number (e.g. \"§1\", \"§4\", \"§6\"); obeys the same author-domain whitelist as append/edit.",
158
+ },
159
+ text: {
160
+ type: "string",
161
+ description: "For op:\"append\" — markdown to append to the end of that section (≤ 20000 chars).",
162
+ },
163
+ oldText: {
164
+ type: "string",
165
+ description: "For op:\"edit\" — exact unique anchor inside that section body.",
166
+ },
167
+ newText: {
168
+ type: "string",
169
+ description: "For op:\"edit\" — replacement text (empty string deletes; ≤ 20000 chars).",
170
+ },
171
+ },
172
+ required: ["segment"],
173
+ },
174
+ description: "update only — ordered non-empty list (up to 20) of section append/edit operations applied atomically to one batch record in a single call. Each entry runs the exact same author whitelist, anchor, status-line, and section gates as single append/edit; all entries are checked and validated against one doc-check gate before a single disk write (any failure writes nothing). Prefer update whenever writing/editing 2+ sections or multiple ranges in one turn.",
175
+ },
145
176
  value: {
146
177
  type: "string",
147
178
  description: "status only — the new status-line value (single line; exactly one legal keyword of your section's STATUS_WORDS entry: §1 进行中/已收口 · §2 设计完成 · §3 评审通过 · §5 实施完成 — plus decoration only: surrounding symbols / a trailing ISO date / whitespace; prose goes to `note`).",
@@ -222,7 +253,7 @@ export function batchTool(batchDoc = null, { review = false, role = null, review
222
253
  action: {
223
254
  type: "string",
224
255
  enum: PROFILE_ACTIONS,
225
- description: `Which step this face carries, inside your own section: add text to its END / replace one anchored range inside it / write its status line / read the record without writing anything (no \`segment\` ⇒ its section index; \`segment\` + \`offset\` ⇒ one window of that section).`,
256
+ description: `Which step this face carries, inside your own section: add text to its END (append) / replace one anchored range inside it (edit) / apply multiple append or edit operations atomically in one call (update via \`entries\`) / write its status line (status) / read the record without writing anything (read: no \`segment\` ⇒ its section index; \`segment\` + \`offset\` ⇒ one window of that section).`,
226
257
  },
227
258
  ...Object.fromEntries(PROFILE_PROPS.map((k) => [k, k === "segment" ? profileSegmentProp(profileKey) : full.properties[k]])),
228
259
  },
@@ -272,6 +303,8 @@ description: `Which step this face carries, inside your own section: add text to
272
303
  return appendBatchRecord({ args, ctx, review, reviewTrack: reviewType, batchDoc, onWritten })
273
304
  case "edit":
274
305
  return editBatchRecord({ args, ctx, review, reviewTrack: reviewType, batchDoc, onWritten })
306
+ case "update":
307
+ return updateBatchRecord({ args, ctx, review, reviewTrack: reviewType, batchDoc, onWritten })
275
308
  case "status":
276
309
  return statusBatchRecord({ args, ctx, review, reviewTrack: reviewType, pickTarget, onWritten })
277
310
  case "close":
@@ -283,7 +316,7 @@ description: `Which step this face carries, inside your own section: add text to
283
316
  case "read":
284
317
  return readBatchRecord({ args, ctx, review, pickTarget })
285
318
  default:
286
- throw new Error(`batch: unknown action ${JSON.stringify(args?.action ?? null)} — pass one of create / attach / append / edit / status / close / supersede / check / read.`)
319
+ throw new Error(`batch: unknown action ${JSON.stringify(args?.action ?? null)} — pass one of create / attach / append / edit / update / status / close / supersede / check / read.`)
287
320
  }
288
321
  },
289
322
  }
@@ -43,19 +43,6 @@ export function compactOverheadNote(usage, limit, window) {
43
43
  ` switch to a larger-window model, or trim ${largest}.]`
44
44
  }
45
45
 
46
- /** 压缩 no-op 注记——配置矛盾(`CONTEXT-COMPACTION.md` §2.4):与守卫抛出的 typed error **同一个原因**,
47
- * 回执带 `reason: budget_contradiction` 与矛盾三数(window ∥ reserve ∥ 差值),并把方向指到配置上(不指向会话内容——那个方向是错的)。
48
- * `contradiction` = 预算对象上的 `{ window, reserve, usable }`(`window-policy.mjs` 的 `budgetOf` 夹点时算出的三个数)。
49
- */
50
- export function compactContradictionNote(contradiction) {
51
- const c = contradiction ?? {}
52
- const numbers = `window ${c.window} · reserve ${c.reserve} · difference ${c.usable}`
53
- return `${CONTEXT_NOTE_PREFIX} did nothing right now: this channel's configuration has no solution — ${numbers} —` +
54
- ` reason: budget_contradiction. Compaction cannot help: no request can be sent until the configuration changes` +
55
- ` (raise the window via providers[].modelContext / a larger-context model, lower provider.maxTokens,` +
56
- ` or use a model whose maxOutput is smaller than its window). The context is unchanged.]`
57
- }
58
-
59
46
  /** 压缩失败注记(§6.16.2 回执面②——模型面告知缺口)。§5.1 之后**没有「第 N 次 / 共 3 次」**:摘要在失败当次
60
47
  * 就转确定性丢弃,计数不再是一道降级门的输入。这条注记只在整条链没留下任何产物时才落(摘要失败且无中段可丢),
61
48
  * 所以它说的是「这一次没压成」,不是「已经压过一次」。 */
@@ -40,6 +40,8 @@ import { mutationSeqOf } from "./advisor-async.mjs"
40
40
  import { bindChildController, buildChildSignal, settleAsyncEntry } from "./async-settle.mjs"
41
41
  import { registerTurnCapCheckpoint } from "./checkpoint.mjs"
42
42
  import { drainInjectedQueue } from "./subagent-run.mjs"
43
+ // SSH-TO-CODER T3(batch 2026-11-26-ssh-to-coder):飞刀结清时排空它自己的 ssh 池
44
+ import { discardSshSessions } from "./ssh-session.mjs"
43
45
 
44
46
  /** Parent-side mutations (absolute paths) committed AFTER the escalate launch —
45
47
  * the overlap scan feeds the settle classification (review #4/round2 #4: the
@@ -196,7 +198,7 @@ export function launchEscalateAsync(parent, ctx, launch) {
196
198
  ctx.callbacks?.onToken?.(relayPrefix + "[model]" + (provider.model ?? ""))
197
199
  const child = createAgent({
198
200
  provider,
199
- tools: excludeSubagentTools(parent.tools), // TOOLS.md §6.16:子代面按面排除(行内改——本档 Δ±0)
201
+ tools: excludeSubagentTools(parent.tools), // TOOLS.md §6.4:子代面按面排除(行内改——本档 Δ±0)
200
202
  config: parent.config,
201
203
  cwd: parent.cwd,
202
204
  memory: parent.memory,
@@ -276,6 +278,10 @@ export function launchEscalateAsync(parent, ctx, launch) {
276
278
  entry.error = `escalate (${tag}) error: ${deathLine(e, entry.controller?.signal)}\nPartial output: ${(child?._capturedOutput ?? "").slice(0, 2000)}`
277
279
  })
278
280
  .finally(() => {
281
+ // SSH-TO-CODER T3:飞刀子代理退出即清它自己的 ssh 池(撞帽挂起那段除外——
282
+ // `_turnCapRec` 在场表示暂停可续跑,那时清池会让续跑段拿到墓碑)。
283
+ // 用 `entry.childAgent`:`child` 是 `flight` 内的 const,本闭包看不见它(见评审 🔴 N)。
284
+ if (!entry._turnCapRec && entry.childAgent) discardSshSessions(entry.childAgent)
279
285
  // settle 公共收尾单点(ASYNC-RESULT-CONTAINER.md D3——settleAsyncEntry):日志三连
280
286
  // /cancelled 分支(出池+墓碑+⟦ev⟧stopped+提醒)/挂起分流(pending 单容器+出池——
281
287
  // 统一守卫 !parentAborted——D4)/公共尾部(settleSeq/_settle/唤醒 waiter + 腾槽补位
@@ -59,11 +59,6 @@ const ASYNC_NOTE =
59
59
  "Keep working on the unaffected parts; a reply arrives as an ordinary instruction at your next turn boundary. " +
60
60
  "If your run ends first, report the unanswered part as not done."
61
61
 
62
- /** 工具返回注(同步形——`sync: true`:父阻塞在本次运行上 ⇒ **不给「答复到达」承诺**(F6))。 */
63
- const SYNC_NOTE =
64
- "queued for your parent — but it spawned you synchronously and is blocked on this run, so no reply can reach you " +
65
- "before you end. It reads this when its call returns and may re-spawn you; report the unanswered part as not done."
66
-
67
62
  /** 错误返回形(fail-closed——与 §6.7.2 / §6.25 的 status / observe / send 拒返回同款 JSON 对象形)。 */
68
63
  const refused = (error) => JSON.stringify({ status: "error", error })
69
64
 
@@ -225,6 +220,12 @@ export const parentChannelTool = {
225
220
  return refused(`notify_parent message exceeds ${UPSTREAM_MSG_MAX} chars — one short paragraph; details belong to your final report`)
226
221
  }
227
222
  const { parent, label, sync } = upstream
223
+ // 同步阻塞子代理(sync === true)防呆拒入队:父代理正阻塞等待本次调用返回,既无法在途响应
224
+ // subagent(action:'send'),若强行入队还会残留过期 ask 触发幽灵 upstreamTurn 唤醒;
225
+ // 正常装配面已卸载本工具,此处作为 fail-closed 防御兜底。
226
+ if (sync === true) {
227
+ return refused("notify_parent is unavailable for synchronous subagents — your parent is blocked waiting for your return and cannot reply in-flight; include any [上抛·待裁] or [上抛·知会] items directly in your final report instead")
228
+ }
228
229
  const queue = carrierField(parent, "_childUpstream")
229
230
  const pending = Array.isArray(queue) ? queue : []
230
231
  // 闸二(窗口 = 「未 drain」——§6.27.2 ③):本子代理的 ask 仍在父队列中 ⇒ 拒(不投递)。
@@ -239,6 +240,6 @@ export const parentChannelTool = {
239
240
  return refused(`notify_parent: the parent's in-flight queue is full (${UPSTREAM_QUEUE_MAX}) — the parent has not consumed the pending messages yet; fold yours into your final report instead`)
240
241
  }
241
242
  const { position } = pushChildUpstream({ parent, from: label, kind, message })
242
- return JSON.stringify({ status: "queued", kind, position, note: sync === true ? SYNC_NOTE : ASYNC_NOTE })
243
+ return JSON.stringify({ status: "queued", kind, position, note: ASYNC_NOTE })
243
244
  },
244
245
  }
@@ -1,31 +1,29 @@
1
1
  /**
2
- * plan tool: enter/exit plan mode.
2
+ * plan tool: enter/exit plan mode with structured review approval and steady-state `plan` slot.
3
3
  * 描述面 = `tool-docs/plan.md`(DESC() 加载)。
4
4
  *
5
- * Reminder cadence (kimi-code style): while plan mode is active the agent loop
6
- * re-injects reminders — sparse every 2 turns, full every 5 turns or when the
7
- * user sends a new message — so the constraint never fades from context.
5
+ * 设计要点:
6
+ * 1. 稳态单槽(`agent._inject["plan"]`)替代旧的 2/5 轮周期 reminder 轰炸:开启时写入
7
+ * `PLAN_MODE_POLICY`(幂等,不每轮改写前缀、护住 KV Prefix Cache),关闭时置 `null`。
8
+ * 2. `action="exit"` 须携带以 `# 标题` 开头的完整 Markdown `plan`,通过三端共用的 `ctx.onQuestion`
9
+ * 审批通道呈交用户裁决;只有用户明确选择批准才退出 `planMode`,退回修订 / 取消 / 无 UI 均保持只读。
10
+ * 3. 工具表在开关 `planMode` 时保持不变(由 `dispatch.mjs` 只读门禁 + `plan` 槽约束生效)。
8
11
  */
9
12
  import { DESC } from "../tools/shared.mjs"
10
- import { pushInject } from "../context.mjs"
13
+ import { setInject } from "../context-push.mjs"
11
14
 
12
- const PLAN_FULL_REMINDER =
13
- "[System reminder: plan mode is ON. Workflow: (1) explore/read codebase with read-only tools, " +
14
- "(2) design a solution considering trade-offs, (3) present your plan by calling plan with action='exit' " +
15
- "so the user can approve it. Only read-only tools are allowed — do not write, edit, or run mutation commands. " +
16
- "Your turn must end with either a clarifying question to the user or a call to plan with action='exit'.]"
15
+ /** 审批通道的批准与继续规划选项字面(单源,供执行器与单测共用)。 */
16
+ export const PLAN_APPROVE_OPTION = "Approve & implement"
17
+ export const PLAN_REVISE_OPTION = "Keep planning (revise)"
17
18
 
18
- const PLAN_SPARSE_REMINDER =
19
- "[System reminder: plan mode still active — read-only tools only (the current plan file exempt). " +
20
- "Design the solution, then call plan with action='exit' for user approval.]"
21
-
22
- const PLAN_EXIT_REMINDER =
23
- "[System reminder: plan mode is now OFF. Present your plan to the user " +
24
- "and wait for their explicit approval before implementing — no need for a task list (the plan already covered that).]"
25
-
26
- /** Turns between reminder re-injections while plan mode is active */
27
- const SPARSE_INTERVAL = 2
28
- const FULL_INTERVAL = 5
19
+ /** 规划态稳态策略文案(单源写入 A 段 `plan` 格;回合头与压缩回注共用)。 */
20
+ export const PLAN_MODE_POLICY =
21
+ "[System reminder: plan mode is ON (read-only). Stay in plan mode until the user approves your plan via plan(action='exit', plan=...) or manually turns plan mode off.\n" +
22
+ "- Oral confirmation is NOT approval: a user's casual 'ok/yes' or answer to a clarifying question does not exit plan mode — fold it into the plan and submit via plan(action='exit', plan=...).\n" +
23
+ "- Read-only verification (4 steps before finalizing): (1) break down every requirement and side condition; (2) inspect authoritative docs and in-repo precedents in parallel (read/grep/glob/peek/step(readonly=true)/explore); (3) scan callers and sibling logic repo-wide so nothing is missed; (4) verify exclusions (what NOT to touch), edge cases/fallbacks, and targeted verification commands.\n" +
24
+ "- Do not mutate files or pre-fill the task list during planning (the plan itself covers the steps; track execution with task only after approval).\n" +
25
+ "- Decision-complete plan: submit a complete Markdown plan starting with a `# <Title>` heading covering goal & criteria, affected files (including docs to sync) & explicit exclusions, dependency-ordered concrete steps (cite real paths/symbols, never line numbers), edge cases/fallbacks/assumptions, and targeted verification commands.\n" +
26
+ "- Single exit: call plan(action='exit', plan='<full markdown plan>') as your final review submission. Do not paste the final plan as plain text and ask 'should I proceed?'. If the user requests revisions, stay in plan mode, update the plan, and call plan(action='exit', plan=...) again.]"
29
27
 
30
28
  /**
31
29
  * ENG-PLAN-EXCLUSION(FR31 ② · 设计 `docs/core/design/ENGINEERING-MODE-V2.md` §2.3 E7):
@@ -36,85 +34,123 @@ const FULL_INTERVAL = 5
36
34
  export const PLAN_ENGINEERING_REFUSED =
37
35
  "plan mode is disabled in engineering mode — engineering mode already runs design-before-code (design → review → approval → implementation)."
38
36
 
39
- /** ENG-PLAN-EXCLUSION(FR31 ③ · KD10):未注入 plan 提示语判据 = 三条 reminder 常量逐字组成员。
40
- * 待发队(B 段)里的条目已升级为消息对象 ⇒ 判据读 `content`(与 `history` 时代同一个逐字面)。 */
41
- const isPlanReminder = (content) => content === PLAN_FULL_REMINDER || content === PLAN_SPARSE_REMINDER || content === PLAN_EXIT_REMINDER
42
- const isPlanInject = (m) => isPlanReminder(m?.content)
37
+ /** 兼容旧会话/待发队残留识别:清掉历史版本可能残留在 `_pendingInject` 的 plan reminder。 */
38
+ const isLegacyPlanInject = (m) =>
39
+ typeof m?.content === "string" && (
40
+ m.content.startsWith("[System reminder: plan mode is ON.") ||
41
+ m.content.startsWith("[System reminder: plan mode still active") ||
42
+ m.content.startsWith("[System reminder: plan mode is now OFF.")
43
+ )
44
+
45
+ /**
46
+ * 将 `agent.planMode` 同步到 A 段 `plan` 格(单写入方:`setInject(agent, "plan", ...)`)。
47
+ * 开启 ⇒ 写入 `PLAN_MODE_POLICY`(幂等);关闭 ⇒ `null` 清格。
48
+ */
49
+ export function syncPlanSlot(agent) {
50
+ if (!agent) return
51
+ setInject(agent, "plan", agent.planMode === true ? PLAN_MODE_POLICY : null)
52
+ }
43
53
 
44
54
  /**
45
55
  * ENG-PLAN-EXCLUSION(FR31 ③ / KD10——单点复用):工程模式 ⇒ `planMode` 恒 false。
46
- * 清 `planMode` + 两 reminder 计数 + **未注入的 plan 提示语**(待发队 `_pendingInject` 中的三条
47
- * plan 提醒——否则排队的 `PLAN_EXIT_REMINDER`「Present your plan … wait for their explicit approval …」会在模式翻转后
48
- * 落地,与工程链条打架)。五个挂点复用本函数:三翻转(核 `eng` 工具 / CLI `/eng` / VSC 面板开关)
49
- * + 两恢复(CLI `applySession` / VSC `applySlotSessionState`)。
56
+ * 清 `planMode` + 清 `plan` 槽 + 清旧计数与待发队任何残留 plan 提示语。
57
+ * 五个挂点复用本函数:三翻转(核 `eng` 工具 / CLI `/eng` / VSC 面板开关)+ 两恢复 + 桌面旗标。
50
58
  * @param {object} agent — 会话 agent(就地改写)
51
- * @returns {boolean} 是否清掉了实况(planMode 曾为 true / 有排队 plan 提示语)——调用方按需提示
59
+ * @returns {boolean} 是否清掉了实况
52
60
  */
53
61
  export function clearPlanMode(agent) {
54
62
  if (!agent) return false
55
- const queued = Array.isArray(agent._pendingInject) ? agent._pendingInject.filter(isPlanInject).length : 0
63
+ const queued = Array.isArray(agent._pendingInject) ? agent._pendingInject.filter(isLegacyPlanInject).length : 0
56
64
  const had = agent.planMode === true || queued > 0
57
65
  agent.planMode = false
58
66
  agent._planTurnsSinceReminder = 0
59
67
  agent._planTurnsSinceSparse = 0
68
+ setInject(agent, "plan", null)
60
69
  if (Array.isArray(agent._pendingInject)) {
61
- agent._pendingInject = agent._pendingInject.filter((m) => !isPlanInject(m))
70
+ agent._pendingInject = agent._pendingInject.filter((m) => !isLegacyPlanInject(m))
62
71
  }
63
72
  return had
64
73
  }
65
74
 
66
- /**
67
- * Decide which plan-mode reminder (if any) to inject this turn.
68
- * @param {object} agent — the agent object (mutated: tracks reminder state)
69
- * @param {boolean} userMessageSince — whether a user message arrived since the last reminder
70
- * @returns {string|null} reminder text or null
71
- */
72
- export function planReminderForTurn(agent, userMessageSince) {
73
- if (!agent.planMode) {
74
- agent._planTurnsSinceReminder = 0
75
- agent._planTurnsSinceSparse = 0
76
- return null
77
- }
78
- agent._planTurnsSinceReminder = (agent._planTurnsSinceReminder ?? 0) + 1
79
- agent._planTurnsSinceSparse = (agent._planTurnsSinceSparse ?? 0) + 1
80
- if (userMessageSince || agent._planTurnsSinceReminder >= FULL_INTERVAL) {
81
- agent._planTurnsSinceReminder = 0
82
- agent._planTurnsSinceSparse = 0
83
- return PLAN_FULL_REMINDER
84
- }
85
- if (agent._planTurnsSinceSparse >= SPARSE_INTERVAL) {
86
- agent._planTurnsSinceSparse = 0
87
- return PLAN_SPARSE_REMINDER
75
+ /** 提取计划 Markdown 的首个 `# ` 标题(用于审批提问行的简短标题)。 */
76
+ function extractPlanTitle(markdown) {
77
+ for (const line of markdown.split(/\r?\n/)) {
78
+ const m = /^#\s+(.+?)\s*$/.exec(line.trim())
79
+ if (m) return m[1].slice(0, 60)
88
80
  }
89
81
  return null
90
82
  }
91
83
 
84
+ /** 判别作答是否属于用户取消/关闭提问卡(三端返回值归一:null / "" / "(user cancelled)")。 */
85
+ function isDismissedAnswer(answer) {
86
+ if (answer === null || answer === undefined) return true
87
+ const trimmed = String(answer).trim()
88
+ return trimmed === "" || trimmed === "(user cancelled)"
89
+ }
90
+
92
91
  export const planTool = {
93
92
  name: "plan",
94
93
  description: DESC("plan"),
95
94
  parameters: {
96
95
  type: "object",
97
96
  properties: {
98
- action: { type: "string", enum: ["enter", "exit"], description: "Enter or exit plan mode" },
97
+ action: { type: "string", enum: ["enter", "exit"], description: "Enter plan mode or submit the completed plan for approval to exit" },
98
+ plan: { type: "string", description: "Required when action='exit': the complete Markdown plan starting with a `# Title` heading for user review" },
99
99
  },
100
100
  required: ["action"],
101
101
  },
102
102
  readonly: true,
103
103
  async execute(args, ctx) {
104
- // §2.5 #85(已裁 · 以 VSC 为准):未知 action 明确报错——旧行为(非 exit 一律进 plan
105
- // 模式)把拼错的 action 当成 enter,静默改写会话状态。
106
- if (args.action === "exit") {
107
- ctx.agent.planMode = false
108
- ctx.agent._planTurnsSinceReminder = 0
109
- pushInject(ctx.agent, { role: "user", content: PLAN_EXIT_REMINDER })
110
- return "Plan mode exited. Present your plan to the user and wait for their explicit approval before writing any code."
104
+ const agent = ctx.agent
105
+ if (args.action === "enter") {
106
+ if (agent?.config?.agent?.engineering === true) {
107
+ return `Error: ${PLAN_ENGINEERING_REFUSED}`
108
+ }
109
+ agent.planMode = true
110
+ syncPlanSlot(agent)
111
+ return "Plan mode activated (read-only). Explore the codebase with read-only tools, design a decision-complete plan, then call plan(action='exit', plan='# Title\\n...') to submit it for user approval."
111
112
  }
112
- if (args.action !== "enter") {
113
+
114
+ if (args.action !== "exit") {
113
115
  return `Error: unknown action "${args.action}". Use "enter" or "exit".`
114
116
  }
115
- ctx.agent.planMode = true
116
- ctx.agent._planTurnsSinceReminder = 0
117
- pushInject(ctx.agent, { role: "user", content: PLAN_FULL_REMINDER })
118
- return "Plan mode activated. You are now restricted to READ-ONLY tools. Explore the codebase, understand the architecture, design a solution. Present your plan to the user for approval before writing any code."
117
+
118
+ if (!agent?.planMode) {
119
+ return "Plan mode is not currently active."
120
+ }
121
+
122
+ const planText = typeof args.plan === "string" ? args.plan.trim() : ""
123
+ const title = extractPlanTitle(planText)
124
+ if (!planText || !title) {
125
+ return "Error: action='exit' requires a non-empty Markdown `plan` starting with a `# <Title>` heading. Plan mode remains active — provide the complete plan and call plan(action='exit', plan=...) again."
126
+ }
127
+
128
+ // 无交互审批 UI(headless / 自动化面):安全失败,不擅自解除只读门禁。
129
+ if (typeof ctx.onQuestion !== "function") {
130
+ return "No interactive review UI is available to approve this plan — plan mode remains active. Present the plan in your reply and wait for the user to exit plan mode or approve before implementing."
131
+ }
132
+
133
+ // 先将完整计划正主流入运行中工具输出面,确保三端用户在点批准前可阅读全文。
134
+ ctx.onOutput?.(planText)
135
+ const prompt = `Approve plan "${title}" and start implementing?`
136
+ const answer = await ctx.onQuestion(prompt, [PLAN_APPROVE_OPTION, PLAN_REVISE_OPTION])
137
+
138
+ if (answer === PLAN_APPROVE_OPTION) {
139
+ agent.planMode = false
140
+ agent._lastApprovedPlan = planText
141
+ syncPlanSlot(agent)
142
+ return "Plan approved — plan mode exited. Carry out the approved plan starting now."
143
+ }
144
+
145
+ if (isDismissedAnswer(answer)) {
146
+ return "Plan review dismissed by user — plan mode remains active. Stop and wait for the user's next message; do not implement yet."
147
+ }
148
+
149
+ const feedback = String(answer).trim()
150
+ if (feedback === PLAN_REVISE_OPTION) {
151
+ return "User chose to keep planning — plan mode remains active. Ask clarifying questions or revise the plan, then call plan(action='exit', plan=...) again."
152
+ }
153
+
154
+ return `User requested plan revisions (plan mode remains active): ${feedback}\nIncorporate this feedback, update the plan, and call plan(action='exit', plan=...) again.`
119
155
  },
120
156
  }
@@ -37,10 +37,10 @@ export function docSetKey(documents, cwd) {
37
37
  * 设计评审**受理面不再消费**本键集(受理 = 项目内现存 `.md`,判据单源 = `ADVISOR-GUARDS.md` §12)。
38
38
  * 2026-10-04 自 `agent/write-gate.mjs` 迁入(键集本体零变;write-gate 同名再出口)。
39
39
  *
40
- * **六层**(`docs/core/design/MANIFEST.md` §2.5「键集」条):末位 `standards` = 标准层(目录语义,
41
- * 见同档 §2.12)。键集只在本处改——写面 `agent/write-face.mjs`、评审候选扫描、文档锚点图
40
+ * **七层**(`docs/core/design/MANIFEST.md` §2.3「Schema 与默认值」的 `docRoot` 七键条):`standards` = 标准层(目录语义,见同档
41
+ * §2.12),末位 `manuals` 是最终用户手册层。键集只在本处改——写面 `agent/write-face.mjs`、评审候选扫描、文档锚点图
42
42
  * `doc-graph.mjs` 三处共用这一份,不各持字面(KD-M1-64)。 */
43
- export const REVIEW_ROOT_KEYS = ["requirements", "specs", "design", "modules", "batches", "standards"]
43
+ export const REVIEW_ROOT_KEYS = ["requirements", "specs", "design", "modules", "batches", "standards", "manuals"]
44
44
 
45
45
  /**
46
46
  * 写门评审根解析单点(按用点形——2026-09-21 收口 · 台账 #828;2026-10-04 自 `agent/write-gate.mjs`
@@ -40,6 +40,8 @@ export function isSensitiveKey(path) {
40
40
  const _NULL_LEAF_SHAPES = {
41
41
  defaultModel: { kind: "nonEmptyString", providerModel: true, expects: 'non-empty string ("provider:model" composite)' },
42
42
  "agent.subagentModel": { kind: "nonEmptyString", expects: "non-empty string" },
43
+ "agent.planningNextMoves.model": { kind: "nonEmptyString", expects: 'non-empty string ("provider:model" or model name)' },
44
+ "agent.planningNextMoves.reasoningEffort": { kind: "nonEmptyString", expects: "non-empty string (low|medium|high|xhigh)" },
43
45
  shell: { kind: "nonEmptyString", expects: "non-empty string" },
44
46
  "memory.team": { kind: "team", expects: "object { repo: string, name?, dir? }" },
45
47
  }
@@ -18,6 +18,12 @@
18
18
  */
19
19
  export const ROUND_VALUES = ["initial", "fix"]
20
20
 
21
+ /** explore 彻底程度合法值(单源:schema 面与校验面同引用)。 */
22
+ export const EXPLORE_THOROUGHNESS_VALUES = ["quick", "medium", "thorough"]
23
+
24
+ /** 只读轻派单角色(explore / plan):只需 goal + scope 必填,其余三项可选(传了仍按原序拼入任务书)。 */
25
+ const READONLY_LIGHT_ROLES = new Set(["explore", "plan"])
26
+
21
27
  /** 任务书样例内容(供人照抄;不是门的判据——门只判存在 / 类型 / 非空):非工程角色
22
28
  * = 四项核心 + `scope`(工程角色无任务书文本参数——任务书 = 绑定批档,按角色切片(§8.1))。 */
23
29
  const TASK_BOOK_CORE_MIN = {
@@ -120,39 +126,56 @@ const TASK_BOOK_LABELS = {
120
126
  reportFormat: "Delivery report format",
121
127
  }
122
128
 
129
+ /** 角色 → 该角色的任务书必填名集:工程角色空集;只读轻派单角色(explore / plan)= goal + scope;
130
+ * 写盘/执行角色(coder / tester)= 四项核心 + scope。 */
131
+ export function requiredTaskBookParamsFor(role) {
132
+ if (isEngineeringRole(role)) return []
133
+ if (READONLY_LIGHT_ROLES.has(role)) return ["goal", "scope"]
134
+ return taskBookParamsFor(role)
135
+ }
136
+
123
137
  /**
124
138
  * F2 任务书参数校验(ENGINEERING-MODE-V2-MODULE-DELEGATION §2.2)· **非工程角色**:
125
- * 名集按角色取(`taskBookParamsFor(role)` = 四项核心 + `scope`)。判据只有三条——参数存在 ∧
126
- * typeof string ∧ trim() 非空。不读内容:无正则、无标题匹配、无双语 marker。缺 / 空白 /
127
- * 非字符串 → 合并抛,文案逐项点名该参数;`scope` 缺失而 `designPoints` 在场时,文案附一句
128
- * 指路(只作文案,不加判据;工程角色不经本门——它们拒收全部自由文本键)。
139
+ * 必填名集按角色取(explore / plan = goal + scope,其余三项可选;coder / tester = 四项核心 + scope)。
140
+ * 判据只有三条——必填项存在 ∧ typeof string ∧ trim() 非空;可选项若在场须为 string;explore 的
141
+ * thoroughness 若在场须属 EXPLORE_THOROUGHNESS_VALUES。不读内容:无正则、无标题匹配、无双语 marker。
129
142
  */
130
143
  export function validateTaskBookParams(args, role) {
131
144
  const a = args ?? {}
132
- const names = taskBookParamsFor(role)
145
+ const required = new Set(requiredTaskBookParamsFor(role))
146
+ const allNames = taskBookParamsFor(role)
133
147
  const fifth = TASK_BOOK_PARAMS.fifth
134
148
  const otherFifth = "designPoints"
135
149
  const failed = []
136
- for (const name of names) {
150
+ for (const name of allNames) {
137
151
  const v = a[name]
152
+ const isReq = required.has(name)
138
153
  if (v === undefined || v === null) {
154
+ if (!isReq) continue
139
155
  const hint = name === fifth && a[otherFifth] !== undefined && a[otherFifth] !== null
140
156
  ? ` (got ${otherFifth} instead — ${otherFifth} is retired for every role; the fifth parameter here is ${fifth})`
141
157
  : ""
142
- failed.push(`${name} — missing (the task book is four core parameters + the role's fifth)${hint}`)
158
+ failed.push(`${name} — missing${hint}`)
143
159
  }
144
160
  else if (typeof v !== "string") failed.push(`${name} — must be a string (got ${typeof v})`)
145
- else if (v.trim() === "") failed.push(`${name} — blank (trim() is empty)`)
161
+ else if (isReq && v.trim() === "") failed.push(`${name} — blank (trim() is empty)`)
162
+ }
163
+ if (role === "explore" && a.thoroughness !== undefined && a.thoroughness !== null) {
164
+ if (!EXPLORE_THOROUGHNESS_VALUES.includes(a.thoroughness)) {
165
+ failed.push(`thoroughness ∈ {${EXPLORE_THOROUGHNESS_VALUES.join(", ")}} (got ${JSON.stringify(a.thoroughness)})`)
166
+ }
146
167
  }
147
168
  if (failed.length === 0) return
169
+ const reqDesc = READONLY_LIGHT_ROLES.has(role)
170
+ ? `goal / scope required (knownFacts / acceptance / reportFormat optional)`
171
+ : `four core parameters (${TASK_BOOK_PARAMS.core.join(" / ")}) plus ${fifth}`
148
172
  throw new Error(
149
173
  `Spawn task-book gate (role='${role}'): ${failed.join(" · ")}. ` +
150
- `The task book is four core parameters (${TASK_BOOK_PARAMS.core.join(" / ")}) plus ${fifth} ` +
151
- `(the fifth parameter for role='${role}'); a missing, blank or non-string value is a dispatch defect and the spawn is refused.`)
174
+ `The task book requires ${reqDesc}; a missing, blank or invalid value is a dispatch defect and the spawn is refused.`)
152
175
  }
153
176
 
154
177
  /** 非工程角色任务书 → 子代理任务书文本(**非门禁**,纯拼装):按 `taskBookParamsFor(role)` 固定序
155
- * + 标签,空值跳过,`\n\n` 分隔。拼装单源 = 本函数——子代理 input、权限预览与探针判官同源。
178
+ * + 标签,空值跳过,`\n\n` 分隔;explore 若传 `thoroughness` 则附深度行。
156
179
  * 工程角色名集为空 ⇒ 返回空串(任务书 = 绑定批档,按角色切片(§8.1),运行时不拼装——KD-SC5)。 */
157
180
  export function composeTaskBookBrief(args, role) {
158
181
  const a = args ?? {}
@@ -161,6 +184,9 @@ export function composeTaskBookBrief(args, role) {
161
184
  const v = a[name]
162
185
  if (typeof v === "string" && v.trim() !== "") parts.push(`${TASK_BOOK_LABELS[name]}: ${v.trim()}`)
163
186
  }
187
+ if (role === "explore" && typeof a.thoroughness === "string" && a.thoroughness.trim() !== "") {
188
+ parts.push(`Thoroughness: ${a.thoroughness.trim()}`)
189
+ }
164
190
  return parts.join("\n\n")
165
191
  }
166
192