@linxin666/dsh-liangshen 0.4.4 → 0.4.6

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.
@@ -0,0 +1,121 @@
1
+ /**
2
+ * The dispatcher rule set LiangShen appends to its persona when the
3
+ * `dispatcher` switch is on.
4
+ *
5
+ * Source: the task-book dispatch mode of the separate dispatch preset
6
+ * (dsh-chatgpt-subscription `presets/dispatch/agent.cordis.yml`, its persona
7
+ * prefix block), carried verbatim from the role-recognition paragraph
8
+ * through the closing anti-pattern list: the role-recognition paragraph, the
9
+ * dispatcher-identity paragraph, R0 through R8 including R-T, and the twelve
10
+ * anti-patterns. A session that turns the switch on therefore runs exactly
11
+ * the rules that were reviewed there.
12
+ *
13
+ * The one adaptation is the model-routing paragraph: the guard it names
14
+ * belongs to that other repository, so it is described by what it does
15
+ * rather than by that repository and its configuration key, because a
16
+ * LiangShen deployment need not carry it. The identity line above the
17
+ * role-recognition paragraph is not carried: its `{{model}}` and `{{cwd}}`
18
+ * placeholders belong to that preset's own renderer, while LiangShen binds no
19
+ * such variables and already appends its workspace line to the persona.
20
+ *
21
+ * The rules apply in addition to the persona working discipline above them,
22
+ * never instead of it: LiangShen keeps its own reflection fuse,
23
+ * action-oriented thinking, and convergence rules while this block adds
24
+ * complexity triage, delegation discipline, and verification.
25
+ *
26
+ * This module is pure text: `minimal-prompt.mjs` owns when it is appended and
27
+ * what separates it from the persona.
28
+ */
29
+
30
+ /** The dispatcher rule block, verbatim, without a trailing newline. */
31
+ export const DISPATCHER_RULES = `【角色识别】若你的第一条用户消息是一份任务书(而不是用户本人的直接请求),说明你是子代理或 teammate:R0、R0.5、R-G、R1、R2、R4、R5 中面向调度者的规则不适用于你。你是执行者,只在任务边界内自行规划、执行、自检,并把证据回报给派发者;R3 仍然有效。
32
+
33
+ 【调度者身份】你是本会话的调度 Agent。你的产出是计划、任务书、审查结论与交付说明——不是替别人写完的代码。
34
+
35
+ ## R0 · 复杂度分诊(先分诊,再决定流程)
36
+ 收到任务后先判定档位,用一行写出「档位 + 理由」,再决定后续阶段。
37
+ - L0 简单/单点:单文件或单点改动;需求无歧义;改动可逆;无并行价值;所需信息你已全部掌握。→ 不派子代理、不做访谈,直接做完并汇报。
38
+ - L1 中等:2–5 个文件;需求基本明确但有个别待定点;可拆但并行收益有限。→ 最多 1–2 个关键问题(不展开访谈)→ 简短规划 → 你执行或派 1 个子代理。
39
+ - L2 复杂/多步:跨模块或多交付物;存在歧义或隐含假设;需要探索未知;有可独立并行的子任务。→ 必须走完整流程:澄清访谈 → 完整规划 → 多子代理并行 → 分层验收。
40
+ 拿不准就先问清楚再升级;发现比预想复杂时,停下重新分诊并告知用户。绝不为 L0/L1 任务开启访谈或多代理编排。
41
+
42
+ ## R0.5 · 协作模式侦测(每个任务开始前一次)
43
+ 写出:协作模式:teammate 或 subagent。判据:spawn_teammate 与 wait_agent 是否存在(PTC 下即 tools.spawn_teammate / tools.wait_agent)。
44
+ 分界不是「能不能派」,而是「派完能不能追问」:teammate 下 send_message 只认成员名,传子代理的 session id 必然失败。
45
+ 两种模式下 R0/R1/R3/R6 照常执行,差别只在派发工具与回访方式,见 R-T。
46
+ ## R-G · 澄清访谈(仅 L2,且必须在规划之前)
47
+ - G1 设计树:把需求建模成一棵设计树——每个决策下挂着依赖它的决策,不要平铺罗列。
48
+ - G2 前沿与轮次:前沿=所有前置决策已敲定、现在问不需要猜的问题。一轮=一次问完整个前沿;不要一次只问一个,也不要一次问完所有。相互依赖的两个问题不得同轮。
49
+ - G3 执行方式:用一次 ask_user_question 调用提交本轮全部问题;每题带稳定 id 与简短 header,并给出你的推荐答案(有选项时推荐项放第一个并标注「(推荐)」)。按「Q1 — 标题 / 问题正文 / 推荐答案」组织,让用户能按编号回答。
50
+ - G4 事实归你,决策归用户:能靠读代码、搜索、运行命令查明的事实绝不问用户;需要查证时派子代理去查(同样遵守 R2),且不要阻塞提问——只有依赖该事实的问题留到下一轮,同轮其余问题照问。
51
+ - G5 收敛:前沿为空即访谈结束;用户明确确认「理解一致」之后才进入规划。在此之前不得编辑文件、不得派发实现型子代理。
52
+ - G6 禁止:自问自答、替用户拍板、跳过访谈直接规划、把用户随口确认某件事当成访谈完成。
53
+
54
+ ## R1 · 职责边界(按档位分层)
55
+ 对 L2 任务,除下列六类工作外一律不亲自执行:① 规划与拆解;② 派发任务;③ 审查;④ 验收;⑤ 文档与交付说明;⑥ 子代理无法处理的任务。
56
+ 对 L0/L1,你直接执行——不要为了显得在编排而派子代理。
57
+
58
+ ## R2 · 模型路由(先判定可用性,再决定怎么派)
59
+ 开工前先判定本会话是否具备子代理模型选择:看 list_subagent_models 是否存在(PTC 模式下即 tools.list_subagent_models 是否可用)。它与 subagent 工具上 provider/model/reasoning_effort 三个参数的暴露由同一个开关决定,必然同生共死,因此这一个信号足够判定。
60
+
61
+ 【可用时】按显式路由派发,这是本模式的默认工作方式。
62
+ - 每次派发显式给出 provider 与 model(必要时附 reasoning_effort),且必须落在 DSH「子代理」设置已勾选的允许清单内。
63
+ - 本部署的子代理模型授权守卫(DSH「子代理」设置里启用的守卫,默认启用)会在子代理启动前拒绝:省略 provider/model、只给一半、或给出清单外的路由,拒绝理由会直接列出授权路由。PTC 模式下守卫同样覆盖 run_code 内 tools.subagent(...) 的调用。
64
+ - 所以省略参数不是「静默继承」,而是一次硬拒绝——不要靠试错去发现可用路由。守卫只保证「不会用错」,不保证「选得合适」,选哪个仍然由你决定。
65
+ - 每次派发前先写出路由决定:route: <provider>/<model>(必要时 + reasoning_effort)。没有写出这一行,就不得发起派发;写错了会被守卫拦下。
66
+ - subagent 工具自带的说明把模型选择称作「可选」并鼓励省略,那是 DSH 核心的措辞;开关开启时它不成立。
67
+
68
+ 【不可用时】不报错、不劝阻、不要求用户改设置——直接沿用 DSH 默认行为继续工作。
69
+ - 此时 subagent 工具不暴露 provider/model/reasoning_effort,守卫也不生效,子代理静默继承你的路由。这是本模式认可的合法降级路径,不是违规。
70
+ - 照常按 R3–R6 派发与验收,只是不再写出 route 这一行。
71
+ - 唯一需要顺带一提的例外:如果你判断某个任务明显更适合用另一个模型(例如机械重构 vs 深度推理),可以用一句话告诉用户可以到「设置 → 子代理」打开开关并新开一个会话,然后继续用默认方式把当前任务做完——不要为此停下等待。该设置只对新建会话生效,不追溯已有会话。
72
+
73
+ subagent_fork 刻意与父代理同路由(复用对话与 KV Cache),只用于需要主代理上下文的审查,不得当作偷懒的替身。
74
+ 它没有 provider/model 参数,路由由你自己决定,因此【可用时】的显式路由规则对它不适用。但守卫会校验它实际继承到的路由:当你的当前模型不在允许清单内时,fork 会被硬拒绝,且它自己无法补救——此时要么改用 subagent 显式指定清单内的路由,要么先让本会话切到清单内的模型,fork 随即恢复可用。
75
+ 选择依据是任务性质与模型能力;同一批次内同类任务保持一致。
76
+
77
+ ## R3 · 子代理自治
78
+ 子代理对自己的模块拥有规划、执行、自检的完整权限。你不替它做它的活,派发后也不要去写同一块代码——给足任务书,然后等它的证据。
79
+
80
+ ## R4 · 子代理角色
81
+ 子代理使用 DSH 的默认子代理角色与默认环境,不注入任何自定义角色。选模型的权力只在调度 Agent:允许清单中有多个模型时由你按任务性质分派,不交给子代理自己挑。
82
+
83
+ ## R5 · 派发纪律
84
+ 每份任务书包含:目标 / 边界(可动哪些文件或模块)/ 约束 / 验收标准 / 必须回报的证据。
85
+ 相互独立的派发放在同一条消息里并行发出,不要串行等待。子代理的回报是证据,不是结论。
86
+ 前置条件:访谈未收敛时不得派发实现型子代理。
87
+ 若当前呈现为 PTC 模式,派发通过 run_code 内的 tools.subagent(...) 完成,独立派发用 Promise.all 并发;参数与调度工具一致。
88
+
89
+ ## R-T · teammate 模式(仅侦测为 teammate 时)
90
+ - 协调走成员词汇:list_agents()、send_message({ target: <成员名> 或 "lead" })、wait_agent()、team_task_*;不要把子代理 session id 交给 send_message / interrupt_agent。
91
+ - spawn_teammate 没有 provider/model,成员一律继承你的路由:R2 的显式路由只对 subagent 成立,不要为它写 route 行。
92
+ - 选型:需要中途追问、多轮返工 → spawn_teammate;一次拿到结果即可 → subagent。
93
+ - 任务清单落在 team_task_*(R7);派发与并行纪律仍按 R5。
94
+ ## R6 · 审查与验收
95
+ 两层:子代理自检 → 你复审。验收必须落到证据上(读关键改动、跑测试、对照验收标准)。
96
+ 不通过就带上具体证据重新派发,不要自己接手改;也不要凭子代理的自我陈述宣布完成。
97
+ 同一任务书最多重新派发两次;两次都不通过,或重新派发被硬拒绝(工具不可用、连续报错),才转 R8 兜底并说明是哪一种。
98
+
99
+ ## R7 · 文档
100
+ 你维护任务清单、决策记录,以及访谈结论(哪些决策已敲定、为什么)。子代理不直接向用户汇报。
101
+
102
+ ## R8 · 兜底
103
+ 兜底是任务级、非会话级的例外授权,只覆盖触发它的那一个任务,绝不改变本会话后续任务的默认工作方式。
104
+ 满足以下任一条才可亲自执行,且必须说明触发的是哪一条、证据是什么:L0/L1 任务;子代理工具不可用;允许清单为空且用户尚未开启;任务不可委派(纯咨询、极小单点改动、必须共享你当前上下文的操作);同一任务书按 R6 重新派发两次仍不通过。
105
+ 硬拒绝先修条件,不要拿它当兜底理由:提示 active child limit 的 → 等已存在的子代理结算后重新派发;提示 subagent model selection 的 → 按错误里列出的授权路由写明 provider/model;路由继承类拒绝 → 改用显式指定路由的子代理工具,或把本会话切到清单内的模型。条件不修复,同类拒绝会一直复现。
106
+ teammate 专属:成员名不可重用(failed 后换名重建);inactive 不是失败,先 send_message 唤醒。
107
+ 解除:兜底只对当次任务生效。下一个任务开始一律回到 R0 重新分诊;只要 L2 判定成立、且上面的触发条件已解除,就直接重新派发子代理——不得因为上一个任务兜底过就延续或预设兜底。
108
+
109
+ ## 反模式(出现即为违规)
110
+ 1. 为 L0/L1 任务开启访谈或多代理编排——纯浪费。
111
+ 2. 需求没问清就开始规划、派发或动手——把不确定性固化成返工。
112
+ 3. 在主代理模型上跑本该下派的长任务。
113
+ 4. 在模型选择可用时省略 provider/model,依赖守卫拦截或让它静默继承主代理路由(不可用时的继承不在此列)。
114
+ 5. 你直接编辑子代理负责的模块。
115
+ 6. 子代理一回报就宣布完成,未经验收。
116
+ 7. 同一批次同类任务混用多种模型。
117
+ 8. 让子代理自己决定用哪个模型。
118
+ 9. 把一次兜底沿用成整个会话的默认——R8 是任务级许可,下一个任务必须重新按 R0 分诊。
119
+ 10. 拿工具硬拒当当兜底理由而不去修触发条件——拒绝会一直复现。
120
+ 11. teammate 模式下把子代理 session id 当成员名发给 send_message——必然失败。
121
+ 12. 给 spawn_teammate 编造 provider/model(它没有这两个参数)。`
@@ -18,24 +18,32 @@
18
18
  * tool call nor any visible reply text — the #5976 shape. Reading the
19
19
  * reasoning TEXT is unnecessary (and impossible on routes that redact it);
20
20
  * the block's character count is the objective "long thinking" measure.
21
+ * On a route that persists signed reasoning blocks with NO text, every
22
+ * character count reads zero and the character ladders can never fire, so a
23
+ * session in which no reasoning text was ever observed falls back to a
24
+ * step-count measure (see DEFAULT_BLIND_STALL_CAP) and says so once.
21
25
  * - ECHO: the same tool called with the same arguments failing M times in a
22
26
  * row with no success in between — the closed loop of repeating one broken
23
27
  * call.
24
28
  *
25
- * On either signal the breaker FIRES once per episode:
26
- * 1. a circuit-breaker user message is injected at the next pre-step (the
27
- * one channel guaranteed to reach the model, as durable as the working-
28
- * context projection), telling the model the loop was interrupted and to
29
- * close out or pick a materially different action;
30
- * 2. a temporary reasoning-effort step-down rides the `agent/request`
31
- * waterfall for the next FEW requests (current level one notch down:
32
- * max -> high -> low; anything else is left alone). Lowering the budget
33
- * is the community-observed recovery move (r/DeepSeek 1whgo3e) and the
34
- * official effort-cost curve puts the sweet spot below max. This is the
35
- * ONLY moment this plugin rewrites a request: with no signal it never
36
- * touches one, so prefix-cache stability and the user's explicit model-
37
- * selector effort stay untouched — the constraint recorded in the Agent
38
- * Note that removed the old phase-based switching.
29
+ * On either signal the breaker FIRES once per episode with a circuit-breaker
30
+ * user message injected at the next pre-step (the one channel guaranteed to
31
+ * reach the model, as durable as the working-context projection), telling the
32
+ * model the loop was interrupted and to close out or pick a materially
33
+ * different action.
34
+ *
35
+ * A STALL additionally arms a temporary reasoning-effort step-down that rides
36
+ * the `agent/request` waterfall for the next FEW requests: one notch down
37
+ * `max -> high`, and `high` (like every other level) is left alone. Lowering
38
+ * the budget is the community-observed recovery move (r/DeepSeek 1whgo3e) and
39
+ * the official effort-cost curve puts the sweet spot below max — neither piece
40
+ * of evidence supports going BELOW the 60-80 sweet spot, so the ladder stops
41
+ * at `high`. ECHO does NOT step down: its cause is a broken call, not an
42
+ * over-large budget, and lowering the effort would weaken a model that is
43
+ * already stuck. This is the ONLY moment this plugin rewrites a request: with
44
+ * no signal it never touches one, so prefix-cache stability and the user's
45
+ * explicit model-selector effort stay untouched — the constraint recorded in
46
+ * the Agent Note that removed the old phase-based switching.
39
47
  *
40
48
  * Recovery: a step with a tool call or a visible reply re-arms the breaker
41
49
  * and, once the step-down window has run its requests, the route's own effort
@@ -95,6 +103,14 @@ export const GLOBAL_MIN_REASONING_CHARS = 200
95
103
  /** How many consecutive output-free reasoning steps trip the slow-burn ladder. */
96
104
  export const DEFAULT_GLOBAL_STALL_CAP = 4
97
105
 
106
+ /**
107
+ * Consecutive output-free steps that trip STALL on a route that never produced
108
+ * any reasoning text. Both character ladders read zero there, so the step count
109
+ * is the only objective measure left; the cap matches the slow-burn ladder's,
110
+ * which keeps the fallback as conservative as the ladder it stands in for.
111
+ */
112
+ export const DEFAULT_BLIND_STALL_CAP = 4
113
+
98
114
  /**
99
115
  * Sensitivity presets: a whole-scale multiplier over the adaptive thresholds,
100
116
  * for operators who know they fear false interruptions more than missed
@@ -114,8 +130,13 @@ export const DEFAULT_STEP_DOWN_REQUESTS = 3
114
130
  /** Steps the breaker stays quiet after firing once (no message spam). */
115
131
  export const DEFAULT_REFIRE_COOLDOWN_STEPS = 5
116
132
 
117
- /** The effort ladder a step-down walks along. Anything else is left alone. */
118
- const EFFORT_LADDER = ['max', 'high', 'low']
133
+ /**
134
+ * The effort ladder a step-down walks along: one notch down from `max` only.
135
+ * `high` is where the ladder stops, because the official effort-cost curve
136
+ * puts the model's sweet spot at 60-80 and nothing supports stepping below it;
137
+ * every other level (including `high` itself) is left alone.
138
+ */
139
+ const EFFORT_LADDER = ['max', 'high']
119
140
 
120
141
  /** Validate a positive-integer config value, or fall back when absent. */
121
142
  function integerAtLeast(value, field, minimum, fallback) {
@@ -142,6 +163,15 @@ function reasoningCharsOf(event) {
142
163
  return chars
143
164
  }
144
165
 
166
+ /** Reasoning blocks one assistant/message event carries, text or not. */
167
+ function reasoningBlocksOf(event) {
168
+ let blocks = 0
169
+ for (const block of event?.data?.message?.content ?? []) {
170
+ if (block?.type === 'reasoning') blocks += 1
171
+ }
172
+ return blocks
173
+ }
174
+
145
175
  /** Visible reply blocks (non-empty text) one assistant/message event carries. */
146
176
  function visibleRepliesOf(event) {
147
177
  let count = 0
@@ -185,14 +215,18 @@ function isErrorResult(event) {
185
215
  * - the latest tool call's signature and its consecutive-failure count,
186
216
  * reset by any success or any differently-shaped call.
187
217
  *
188
- * Returns `{ signal: 'stall' | 'echo' | undefined, detail }` for the TAIL of
189
- * the stream: the breaker only cares whether the session is degenerate NOW.
218
+ * Returns `{ signal: 'stall' | 'echo' | undefined, detail, blind }` for the TAIL
219
+ * of the stream: the breaker only cares whether the session is degenerate NOW.
220
+ * `blind` reports the session-level fact that reasoning blocks were observed
221
+ * without a single character of reasoning text, so the caller can say once that
222
+ * this session's stall detection is running on step counts.
190
223
  */
191
224
  export function foldGuardSignal(events, options) {
192
225
  const stallSteps = options?.stallSteps ?? DEFAULT_STALL_STEPS
193
226
  const stallChars = options?.stallReasoningChars ?? DEFAULT_STALL_REASONING_CHARS
194
227
  const echoFailures = options?.echoFailures ?? DEFAULT_ECHO_FAILURES
195
228
  const globalCap = options?.globalStallCap ?? DEFAULT_GLOBAL_STALL_CAP
229
+ const blindCap = options?.blindStallCap ?? DEFAULT_BLIND_STALL_CAP
196
230
 
197
231
  // Stall, two independent ladders walked in parallel:
198
232
  // 1. PER-STEP: one step whose reasoning alone blows past the character floor
@@ -202,11 +236,25 @@ export function foldGuardSignal(events, options) {
202
236
  // hard global cap so a legitimately long investigation (many small
203
237
  // read-only steps) cannot trip it by accumulation alone: the streak only
204
238
  // counts while the steps are also individually reasoning-heavy.
239
+ // 3. BLIND (fallback): on a route that persists signed reasoning blocks
240
+ // with no text, every character measure reads zero and ladders 1 and 2
241
+ // are structurally dead. When the whole stream carried reasoning blocks
242
+ // but not one character of reasoning text, the step count is the only
243
+ // measure left, so consecutive output-free reasoning-block steps trip
244
+ // STALL at the same cap the slow-burn ladder uses.
205
245
  let stallStreak = 0
206
246
  let globalStreak = 0
247
+ let blindStreak = 0
248
+ // Session-level facts the blind fallback keys on: whether ANY reasoning text
249
+ // was ever observed, and whether any reasoning block was observed at all.
250
+ // A stream with no reasoning block yet (a fresh session) is NOT blind — the
251
+ // character ladders have simply not had their chance.
252
+ let reasoningTextSeen = false
253
+ let reasoningBlocksSeen = 0
207
254
  // pending holds, for the current step, whether we saw reasoning and whether
208
255
  // we saw any output (tool call or visible text).
209
256
  let pendingReasoning = 0
257
+ let pendingReasoningBlocks = 0
210
258
  let pendingOutput = false
211
259
 
212
260
  const closeStep = () => {
@@ -224,7 +272,16 @@ export function foldGuardSignal(events, options) {
224
272
  } else if (pendingReasoning >= GLOBAL_MIN_REASONING_CHARS) {
225
273
  globalStreak = Math.min(globalStreak + 1, globalCap)
226
274
  }
275
+ // Blind ladder: an output-free step that still carried a reasoning block —
276
+ // the exact shape a redacted route produces. Character count is not part of
277
+ // the test, because on that route it is always zero.
278
+ if (pendingOutput) {
279
+ blindStreak = 0
280
+ } else if (pendingReasoningBlocks > 0) {
281
+ blindStreak = Math.min(blindStreak + 1, blindCap)
282
+ }
227
283
  pendingReasoning = 0
284
+ pendingReasoningBlocks = 0
228
285
  pendingOutput = false
229
286
  }
230
287
 
@@ -241,7 +298,15 @@ export function foldGuardSignal(events, options) {
241
298
  break
242
299
  case 'assistant/message': {
243
300
  const reasoning = reasoningCharsOf(event)
244
- if (reasoning > 0) pendingReasoning += reasoning
301
+ if (reasoning > 0) {
302
+ pendingReasoning += reasoning
303
+ reasoningTextSeen = true
304
+ }
305
+ const blocks = reasoningBlocksOf(event)
306
+ if (blocks > 0) {
307
+ pendingReasoningBlocks += blocks
308
+ reasoningBlocksSeen += blocks
309
+ }
245
310
  if (visibleRepliesOf(event) > 0) pendingOutput = true
246
311
  break
247
312
  }
@@ -273,23 +338,35 @@ export function foldGuardSignal(events, options) {
273
338
  }
274
339
  closeStep()
275
340
 
341
+ // The blind fallback applies only when the session really is on a redacted
342
+ // route: reasoning blocks were observed, none of them carried any text.
343
+ const blind = !reasoningTextSeen && reasoningBlocksSeen > 0
344
+ if (blind && blindStreak >= blindCap) {
345
+ return {
346
+ signal: 'stall',
347
+ detail: `${blindStreak} consecutive output-free reasoning steps (no reasoning text in this session)`,
348
+ blind,
349
+ }
350
+ }
276
351
  if (stallStreak >= stallSteps) {
277
- return { signal: 'stall', detail: `${stallStreak} consecutive runaway-reasoning steps (${stallChars}+ chars each)` }
352
+ return { signal: 'stall', detail: `${stallStreak} consecutive runaway-reasoning steps (${stallChars}+ chars each)`, blind }
278
353
  }
279
354
  if (globalStreak >= globalCap) {
280
- return { signal: 'stall', detail: `${globalStreak} consecutive output-free reasoning steps (slow burn)` }
355
+ return { signal: 'stall', detail: `${globalStreak} consecutive output-free reasoning steps (slow burn)`, blind }
281
356
  }
282
357
  if (failStreak >= echoFailures) {
283
- return { signal: 'echo', detail: `${failStreak} consecutive identical-argument tool failures` }
358
+ return { signal: 'echo', detail: `${failStreak} consecutive identical-argument tool failures`, blind }
284
359
  }
285
- return { signal: undefined, detail: '' }
360
+ return { signal: undefined, detail: '', blind }
286
361
  }
287
362
 
288
363
  /**
289
364
  * Resolve the concrete thresholds for one request: the adaptive floor for the
290
365
  * current effort, scaled by the sensitivity preset, with any explicit fine-
291
366
  * tuning override winning over the table. All inputs are optional; the result
292
- * is always a complete, valid set.
367
+ * is always a complete, valid set. Every guard fine-tuning field is absent by
368
+ * default, which is what lets the effort table and the sensitivity preset be
369
+ * the shipped behavior rather than dead branches behind a factory value.
293
370
  */
294
371
  export function resolveThresholds(options) {
295
372
  const effort = options?.effort
@@ -305,10 +382,20 @@ export function resolveThresholds(options) {
305
382
  const echoFailures = options?.echoFailures !== undefined
306
383
  ? options.echoFailures
307
384
  : Math.max(2, Math.round(DEFAULT_ECHO_FAILURES * scale))
308
- return { stallReasoningChars, globalStallCap, echoFailures }
385
+ // The blind fallback carries no fine-tuning field of its own: it is a
386
+ // degraded stand-in for the slow-burn ladder, so it scales with the same
387
+ // sensitivity preset unless the caller pins the slow-burn cap explicitly.
388
+ const blindStallCap = options?.blindStallCap !== undefined
389
+ ? options.blindStallCap
390
+ : globalStallCap
391
+ return { stallReasoningChars, globalStallCap, echoFailures, blindStallCap }
309
392
  }
310
393
 
311
- /** One notch down the effort ladder, or undefined when the level is unknown. */
394
+ /**
395
+ * One notch down the effort ladder, or undefined when the level is left alone.
396
+ * Only `max` moves, and it moves to `high`: the ladder stops at the sweet
397
+ * spot, so a session the user explicitly put on `high` is never weakened.
398
+ */
312
399
  export function stepDownEffort(effort) {
313
400
  const index = EFFORT_LADDER.indexOf(effort)
314
401
  if (index < 0 || index === EFFORT_LADDER.length - 1) return undefined
@@ -329,7 +416,7 @@ export function renderGuardMessage(verdict) {
329
416
  ].join(' ')
330
417
  }
331
418
 
332
- /** Register the signal fold, the pre-step injection, and the effort step-down. */
419
+ /** Register the signal fold, the pre-step injection, and the stall-triggered effort step-down. */
333
420
  export function apply(ctx, config) {
334
421
  const enabled = config?.enabled !== false
335
422
  if (!enabled) return
@@ -349,16 +436,17 @@ export function apply(ctx, config) {
349
436
  const stepDownRequests = integerAtLeast(config?.stepDownRequests, 'stepDownRequests', 1, DEFAULT_STEP_DOWN_REQUESTS)
350
437
  const refireCooldown = integerAtLeast(config?.refireCooldownSteps, 'refireCooldownSteps', 1, DEFAULT_REFIRE_COOLDOWN_STEPS)
351
438
 
352
- // Per-agent runtime state: the breaker cooldown / step-down window AND the
353
- // current reasoning effort the request waterfall observed. The signal itself
354
- // always re-derives from the durable event stream, so a resume never
439
+ // Per-agent runtime state: the breaker cooldown / step-down window, the
440
+ // current reasoning effort the request waterfall observed, and whether this
441
+ // session's degraded stall detection has already been reported. The signal
442
+ // itself always re-derives from the durable event stream, so a resume never
355
443
  // inherits a stale verdict; the effort is a read-only observation, never a
356
444
  // rewrite outside a fired episode.
357
445
  const stateByAgent = new WeakMap()
358
446
  const stateOf = (agent) => {
359
447
  let state = stateByAgent.get(agent)
360
448
  if (state === undefined) {
361
- state = { cooldown: 0, firedVerdict: undefined, stepDownLeft: 0, currentEffort: undefined }
449
+ state = { cooldown: 0, firedVerdict: undefined, stepDownLeft: 0, currentEffort: undefined, blindWarned: false }
362
450
  stateByAgent.set(agent, state)
363
451
  }
364
452
  return state
@@ -405,10 +493,22 @@ export function apply(ctx, config) {
405
493
  })
406
494
  const verdict = foldGuardSignal(sessionEvents(agent.session), { stallSteps, ...thresholds })
407
495
 
496
+ // A redacted route makes both character ladders structurally dead; the fold
497
+ // has fallen back to step counts. Say so once per agent, because a session
498
+ // whose stall detection is degraded is a fact an operator debugging a
499
+ // missed episode needs, and the breaker's own fire log never carries it.
500
+ if (verdict.blind && !state.blindWarned) {
501
+ state.blindWarned = true
502
+ try { ctx.logger?.warn?.(`${name}: this session persisted reasoning blocks without any reasoning text, so stall detection is degraded to step counts (${thresholds.blindStallCap} consecutive output-free steps)`) } catch {}
503
+ }
504
+
408
505
  if (verdict.signal !== undefined && state.cooldown === 0) {
409
- // Fire: inject the breaker message and arm the effort step-down.
506
+ // Fire: inject the breaker message, and arm the effort step-down only for
507
+ // a STALL. A stall is an over-large reasoning budget, which is what
508
+ // lowering the effort addresses; an echo is a broken call, where
509
+ // weakening the model would only make the loop harder to escape.
410
510
  state.cooldown = refireCooldown
411
- state.stepDownLeft = stepDownRequests
511
+ if (verdict.signal === 'stall') state.stepDownLeft = stepDownRequests
412
512
  state.firedVerdict = verdict
413
513
  const message = {
414
514
  id: globalThis.crypto.randomUUID(),
@@ -416,7 +516,7 @@ export function apply(ctx, config) {
416
516
  content: [{ type: 'text', text: renderGuardMessage(verdict) }],
417
517
  source: { kind: name },
418
518
  }
419
- try { ctx.logger?.warn?.(`${name}: circuit breaker fired (${verdict.detail}) [${thresholds.stallReasoningChars}ch/${thresholds.globalStallCap}steps/${thresholds.echoFailures}fails, ${sensitivity}, effort ${state.currentEffort ?? 'unknown'}]`) } catch {}
519
+ try { ctx.logger?.warn?.(`${name}: circuit breaker fired (${verdict.detail}) [${thresholds.stallReasoningChars}ch/${thresholds.globalStallCap}steps/${thresholds.echoFailures}fails, ${sensitivity}, effort ${state.currentEffort ?? 'unknown'}, ${verdict.signal === 'stall' ? `step-down ${String(stepDownRequests)} requests` : 'message only'}]`) } catch {}
420
520
  return { ...decision, messages: [...decision.messages, message] }
421
521
  }
422
522
 
@@ -83,11 +83,21 @@
83
83
  * PLAN MODE is kept by default. `dsh-plan-mode` enforces its rules through
84
84
  * the `plan:policy` prompt section alone. `keepPlanPolicy: false` restores the
85
85
  * strict one-line surface.
86
+ *
87
+ * DISPATCHER RULES (`dispatcher`, default `true`): the switch appends
88
+ * `./dispatcher-rules.mjs` to the persona text, after the workspace line, under
89
+ * a two-line heading that names the block and states that it takes effect
90
+ * alongside the discipline above it. The persona and its discipline stay
91
+ * exactly where they are — the block adds complexity triage, delegation
92
+ * discipline, and verification on top of them. Switched off, the assembly
93
+ * returns to the bare persona byte for byte: no import side effect, no extra
94
+ * section, no extra separator.
86
95
  */
87
96
 
88
97
  import { readFile, stat } from 'node:fs/promises'
89
98
  import { homedir } from 'node:os'
90
99
  import { dirname, join, relative, resolve } from 'node:path'
100
+ import { DISPATCHER_RULES } from './dispatcher-rules.mjs'
91
101
 
92
102
  /** Cordis plugin name used by loader diagnostics. */
93
103
  export const name = 'liangshen-minimal-prompt'
@@ -176,6 +186,40 @@ function optionalSource(value, field, fallback) {
176
186
  return value
177
187
  }
178
188
 
189
+ /**
190
+ * The two-line heading that separates the appended dispatcher block from the
191
+ * persona discipline. The block is long and starts at its own top-level
192
+ * headings, so it is announced rather than being read as one more persona
193
+ * bullet, and the heading states the discipline is still in force.
194
+ */
195
+ export const DISPATCHER_RULES_HEADING = [
196
+ '',
197
+ '',
198
+ '---',
199
+ '',
200
+ '## Dispatcher rules (a mode-level append)',
201
+ '',
202
+ 'You are this session\'s dispatcher: your deliverable is the plan, the task',
203
+ 'book, the review verdict, and the hand-off — not the code written in your',
204
+ 'place. The working discipline above stays in force; the rules below add',
205
+ 'complexity triage, delegation discipline, and verification on top of it.',
206
+ '',
207
+ '---',
208
+ '',
209
+ ].join('\n')
210
+
211
+ /**
212
+ * Append the dispatcher block to the persona section text: the persona with
213
+ * its workspace line, the heading, then the rule block. The block is prefixed
214
+ * by the "additional material after the stable prompt prefix" clause so
215
+ * DeepSeek's long-range attention keeps treating the rules as operative, which
216
+ * is how the reference deployment renders them.
217
+ */
218
+ export function withDispatcherRules(text) {
219
+ if (text.includes(DISPATCHER_RULES)) return text
220
+ return `${text}${DISPATCHER_RULES_HEADING}${DISPATCHER_RULES}`
221
+ }
222
+
179
223
  function optionalByteSize(value, field, fallback) {
180
224
  if (value === undefined) return fallback
181
225
  if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
@@ -664,27 +708,39 @@ export function dropInstructionMessages(messages, baselineFiles = [], baselineLo
664
708
  * to the persona section at assembly time. The literal cwd comes from the
665
709
  * session header, so the line stays correct after a workspace switch, and a
666
710
  * session without a readable cwd keeps the bare persona rather than failing.
711
+ *
712
+ * `dispatcher` appends the dispatcher block to the SAME persona section, after
713
+ * the workspace line, so the order is fixed: orientation, then the rules. With
714
+ * the switch off this function is the one it always was — same array identity
715
+ * when there is nothing to append, byte-identical text when there is.
716
+ *
717
+ * Nothing is escaped on the way in: a personality section is prompt text the
718
+ * assembler emits, not section text the renderer interpolates, so a literal
719
+ * `{{name}}` inside the appended rules reaches the model as written instead of
720
+ * throwing on an unknown variable. The append is idempotent, like the workspace
721
+ * line: a persona that already carries the block is left alone.
667
722
  */
668
723
  const WORKSPACE_LINE_PREFIX = '\n\nYour working directory is '
669
724
 
670
- /** Append the workspace line to the persona section, once. */
671
- export function withWorkspaceLine(sections, agent) {
725
+ /** Append the workspace line, and the dispatcher block when the switch is on, to the persona section. */
726
+ export function withWorkspaceLine(sections, agent, dispatcher = false) {
672
727
  const cwd = agent?.session?.header?.cwd
673
- if (typeof cwd !== 'string' || cwd.length === 0) return sections
674
- const line = `${WORKSPACE_LINE_PREFIX}${cwd}.`
728
+ const line = (typeof cwd === 'string' && cwd.length > 0) ? `${WORKSPACE_LINE_PREFIX}${cwd}.` : ''
729
+ if (line === '' && !dispatcher) return sections
675
730
  const persona = sections.find(section =>
676
- PERSONA_SECTION_NAMES.includes(section?.name)
677
- && typeof section?.text === 'string'
678
- && !section.text.includes(line))
731
+ PERSONA_SECTION_NAMES.includes(section?.name) && typeof section?.text === 'string')
679
732
  if (persona === undefined) return sections
733
+ const text = line !== '' && !persona.text.includes(line) ? `${persona.text}${line}` : persona.text
734
+ if (text === persona.text && !dispatcher) return sections
680
735
  return sections.map(section => section === persona
681
- ? { ...section, text: `${section.text}${line}` }
736
+ ? { ...section, text: dispatcher ? withDispatcherRules(text) : text }
682
737
  : section)
683
738
  }
684
739
 
685
740
  /** Register the section filter, workspace-instruction source, and dynamic discovery hooks. */
686
741
  export function apply(ctx, config) {
687
742
  const keepPlanPolicy = optionalBoolean(config?.keepPlanPolicy, 'keepPlanPolicy', true)
743
+ const dispatcher = optionalBoolean(config?.dispatcher, 'dispatcher', true)
688
744
  const instructionSource = optionalSource(config?.instructionSource, 'instructionSource', 'host')
689
745
  const instructionMaxBytes = optionalByteSize(config?.instructionMaxBytes, 'instructionMaxBytes', DEFAULT_INSTRUCTION_MAX_BYTES)
690
746
 
@@ -757,7 +813,7 @@ export function apply(ctx, config) {
757
813
  + 'keeping the assembled prompt instead of sending an empty one')
758
814
  return assembled
759
815
  }
760
- const narrowed = withWorkspaceLine(sections, context?.agent)
816
+ const narrowed = withWorkspaceLine(sections, context?.agent, dispatcher)
761
817
  // 'host' and 'hint' append no workspace-instructions section: the harness's
762
818
  // own agent-instructions row carries the content (or the hint replaces it).
763
819
  if (instructionSource !== 'system-prompt') return { ...assembled, sections: narrowed }