dsh-context-truth 0.3.4 → 0.4.1

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,86 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.1
4
+
5
+ * **修 `handoff` 模式折叠后从不激活轮次:命令通道读错了宿主的返回值形状。** 现场(Linux,stock 部署,
6
+ realm 里没有可注入的 `compaction` 服务,命令通道是唯一能折的路):`/compact` 真的折了 1295 条 /
7
+ ~506,473 tokens,`command/done` 明确 `{kind: "success", sourceEventSeq: 3436}`,但会话停在 idle,
8
+ **没有激活轮**,`state.json` 停在 `foldNo: 0 / ready 未消费 / pending: null`。
9
+ 根因:`dsh-commands` 的 `settle()` 返回 `Object.freeze({ commandId, result })`(类型 `CommandExecution`),
10
+ `sourceEventSeq` 在 `result` 里;`requestFold()` 直接读 `execution.sourceEventSeq`,恒为 `undefined`,
11
+ 于是每次成功折叠都被判成"没有可折叠范围"(`folded: false`)→ 不记 `foldNo`、不建 `pending`、不 `followup`。
12
+ * 一处修三件事(`requestFold` 的命令分支):
13
+ 1. 解包 `execution.result`(新增 `commandResultOf()`,同时兼容直接返回 `CommandResult` 的桩/老宿主);
14
+ 2. `execute()` 对"命令未注册"是 **resolve `undefined`**,不是 throw(`dsh-commands`:
15
+ `if (parsed === void 0) return void 0`),而旧代码只在 catch 里回退服务通道 → 文档承诺的
16
+ "先命令、再服务"在没有 `/compact` 的 realm 上是死的;现在 `undefined` 明确走回退并记日志,
17
+ `foldAtIdleMethod: command` 时则记"不允许其它通道";
18
+ 3. `kind: error` / `cancelled` 的拒绝与"没有可折叠范围"分开记日志(带 `kind` 与原文);折叠未提交时,
19
+ 消费者按 `error` 记 `warn`、其余记 `info`,并写明 `reason`。
20
+ * **为什么过去的演练没抓到**:本仓库 profile 用 `foldAtIdleMethod: service`,0.3.x 的激活演练全部走服务通道
21
+ (判定只需 `compactNow()` 非 null,天然正确)。命令分支是 0.3.0(`e3318ab`)引入的,而 `dsh-commands`
22
+ 从 0.2.0-rc.2 起就是两层形状 —— **命令分支上线第一天起判定就恒为 false**,只是从没人走过这条路。
23
+ 这次把"命令通道也必须激活"变成回归用例,不再依赖演练选哪条通道。
24
+ * 测试:85(新增 3 条:真实两层契约必须激活;`execute` resolve `undefined` 必须回退服务并激活;
25
+ `kind: error` 必须保留档、不激活、记 `warn`)。三处变异分别失败 2 / 1 / 1 例,隔离副本按字节恢复。
26
+ * 顺带更正 `thresholdRatio` 的注释:原文把 0.7 写成"本 profile 跑 dsh-dcp"的事实,而现场那台机器并没有该包;
27
+ 改为说明 0.7 是 dsh-dcp 的取值、stock 是 0.8,应按实际挂载的引擎设置。
28
+ * ⚠ 命令通道的实机验收要等重启(HMR 缺陷 #13623 让 link 插件的源码改动只能靠重启生效);本机待做,
29
+ 现场(Linux)需 `npm i dsh-context-truth@0.4.1` 后重启复验 `foldNo: 1` + 激活轮。
30
+
31
+ ## 0.4.0
32
+
33
+ * **委派会话(子代理)也能写交接档了:`subagentHandoff`,默认关。** 动机是量出来的,不是猜的:
34
+ 上游把"智能体团队"并进子代理之后,子代理成了可续、可寻址的同事(#7519 的身份与消息指引、
35
+ 0.2.2 的命名、`continue its conversation after it finishes`),生命周期变长,折叠暴露面跟着上升。
36
+ 本机 296 个会话里 116 个是子代理,**8 个(6.9%)至少折叠过一次**(14 次折叠事件),其中一个已经
37
+ 到折叠点的 65%。而折叠对子会话的伤害和根会话一样大:它的父代理会继续用 `send_message` 找它,
38
+ 好像它还记得折叠前的事。
39
+ * 形状是**提醒 + 写档 + 折叠后指回**,**不唤醒、不折叠**:
40
+ - 委派会话越过准备点(`handoffAt` × 折叠点,默认 85%)时,把 `[handoff fold · subagent prepare]`
41
+ 发布到它自己的 `context-truth:handoff` runtime-context 块(与根会话同一条通道,仍然每轮最多一次、
42
+ 每周期最多 `handoffReminders` 次,没有用户消息、没有 `inject`);
43
+ - **写文件就是登记**:子会话的工具目录里没有可用的 `handoff_ready`(它按设计拒答委派会话),
44
+ 所以插件在下一个请求里检查 `<root>/<childSessionId>/<fold#>.handoff.md` 是否存在,存在即登记,
45
+ 并记下当时读数作为折叠基线;开关打开时 `handoff_ready` 的拒答文案改成"写文件本身就是登记",
46
+ 不再是一堵墙;
47
+ - 折叠由**宿主**在压力点执行,插件只观察:已登记 + 读数掉到登记时读数的 **90% 以下** = 折叠发生了
48
+ (读数只在窗口被重写时掉下来;掉几个百分点是工具目录进出之类的抖动,不算),于是把
49
+ `[handoff fold · subagent, after the fold]` 连同路径发布到下一次请求,`foldNo` 加一(下一份是
50
+ `002.handoff.md`),并保留被指回的那份档——与根会话"激活目标不能被下一轮准备回收"同一条规则;
51
+ - 掉档但没折叠(例如重启后才发现档、或读数在准备点以下且有旧档)也有归宿:`discoveredLate`
52
+ 直接发指回提示,不让子会话困在"档在盘上、没人告诉它"的状态里。
53
+ * 默认关:它会改变每个子会话模型看到的东西,而多数子会话到不了准备点(116 个里只有 8 个被折叠过)。
54
+ * **实机演练通过(2026-11-20 20:00,重启后运行 0.4.0 + `subagentHandoff: true`)**:把 `thresholdRatio`
55
+ 压到 0.02(折叠点 20,971、准备点 17,825)、`handoffReminders` 压到 1,用一个既有子会话跑完整条链路:
56
+ 1. `delegate handoff prep 1/1 … (used=93604 of the 20971 fold point)` —— 提醒发布;
57
+ 2. 子会话按提醒写 `handoffs/86942830…/001.handoff.md`(2318 字符),**没有**调 `handoff_ready`
58
+ (其拒答文案也确实换成了"写文件本身就是登记"那句);
59
+ 3. `delegate … wrote its handoff note (2318 chars)` —— 文件即登记,`ready.used=100865` 基线入账;
60
+ 4. 把基线改成 600,000 模拟宿主折叠(真折叠要 727K,演练压不到),下一次请求得到
61
+ `delegate … was folded since it wrote …`,`foldNo` 0→1、`ready` 清空、`reminders` 归零;
62
+ 5. 子会话的下一次请求逐字报回 `[handoff fold · subagent, after the fold]` 首行与路径。
63
+ 全程没有 `followup`、没有折叠(该子会话的每一次被唤醒都来自父代理的 `send_message`)。
64
+ * **真实宿主折叠也补上了(同日 20:13–20:14,生产会话而非演练)**:另一个会话里已有的子代理
65
+ `f664ed48`(当时 65%)拿到提醒是 20:10:10.816 `delegate handoff prep 1/3 (used=683623 of 727040)`,
66
+ 它写了 5,594 字符的档(基线 `ready.used=691627`);读数在 20:13:36.158 越过折叠点
67
+ (`tight -> critical (used=727843 … compactionAt=727040)`,超出 803 tokens),宿主随即折叠
68
+ (`compaction/start` 20:13:36 → `compaction/end` 20:14:00,`compaction (step pressure): shadowed 427
69
+ surface nodes (seqs 12-1189, ~339405 tokens)`);20:14:00.241 插件判折叠并登记
70
+ `used=392118, registered at=691627, cause=reading dropped`;20:14:09 那条指回提示只投递一次,
71
+ **子会话折叠后的第一个动作就是 `read` 自己的档**(20:14:10),随后在同一轮里继续干活——没有唤醒。
72
+ 这是该子会话的第一次折叠(此前 0 次),也是本能力唯一一次"提醒 → 写档 → 真实折叠 → 指回 → 读档"全真链路。
73
+ * **顺带纠正一条 0.3.2 写错的时序**:runtime context 快照是在该步的 `agent/request` 瀑布**之前**物化的,
74
+ 所以"在这条瀑布里发布的提醒由同一个请求渲染"是错的——它由**下一个**请求渲染(证据:19:50:08.943 发布,
75
+ 19:50:11 的快照才带上它)。多步轮次不受影响;对"一轮只有一步"的子会话意味着轮末发布的折叠后标记要等
76
+ 父代理下一次叫它才读得到(演练里正是这样读到的)。代码注释已按实测改写。
77
+ * 测试:82(新增 8 条委派用例);六处变异分别失败 1 / 1 / 2 / 1 / 3 / 3 例,隔离副本按字节恢复后
78
+ 与工作副本 sha256 一致。
79
+ * 顺带核实(写进交接档,不进代码):本机 kernel **0.2.2-rc.5 不含** #8348 的子代理汇报指引
80
+ (`dsh-tool-subagent-control` 的 `src/index.ts` 与 `lib/index.js` 都没有那句),它只在 master 上;
81
+ 所以"子代理用完 send_message 汇报"这条在本机尚未生效,本机的复用压力来自 #7519 + 命名 + 本地
82
+ `dsh-srkit` 的 `subagent-reuse` skill。
83
+
3
84
  ## 0.3.4
4
85
 
5
86
  * **唤醒消息瘦身:完整提醒改由唤醒轮的 runtime context 承载。** 以前轮末唤醒把整段
package/README-en.md CHANGED
@@ -108,6 +108,25 @@ The chain is:
108
108
 
109
109
  Guards: at most 3 reminders per cycle; if a round ends past the prep point with no note registered, the plugin **wakes** a round with `followup` (dynamic context is only read by requests that actually happen, and a round that ends issues no further request, so the reminder would otherwise wait for a human — measured, and that is why the wake exists). The wake message is a **single line** naming the note path, and `prepare` re-publishes the full checklist into the runtime-context handoff block of that same request — so the transcript never gets the whole reminder as a user message. If the reading has already dropped below the prep point when the wake round starts (for example the host folded first), only the one-liner remains and the log says why. Notes are temporary, recycled when the next handoff is created with a 7-day sweep; a registered note whose fold did not happen is kept and never activates a turn.
110
110
 
111
+ The command channel decides "did it fold" from the host's own shape: `commands.execute()` resolves `CommandExecution = { commandId, result }`, so the evidence is `execution.result.sourceEventSeq`. Before 0.4.1 the plugin read `execution.sourceEventSeq` (always `undefined`), so on that channel **a successful fold never activated the post-fold turn** — on a stock deployment (no injectable `compaction` service in the realm) that reads as "it folded but no turn ever follows". A realm without `/compact` makes `execute()` resolve `undefined` instead of throwing; that case now falls back to the compaction service explicitly instead of being taken for "no compactable range".
112
+
113
+ #### Notes in delegated sessions (`subagentHandoff`, off by default)
114
+
115
+ The root-session handoff leans on two things a child does not have: this plugin performs the fold, and this plugin opens the activation turn. A child therefore gets a reduced shape, not the same one:
116
+
117
+ | | Root session | Delegated session (`subagentHandoff: true`) |
118
+ |---|---|---|
119
+ | Reminder | ✅ runtime-context block | ✅ the same block and the same budget (once per turn, `handoffReminders` per cycle) |
120
+ | Registration | call `handoff_ready` | **writing the file is the registration** (`handoff_ready` refuses a delegated session by design) |
121
+ | Fold | the plugin runs it at the round end | ❌ the host runs it at the pressure point; the plugin only watches |
122
+ | After the fold | `followup` activates exactly one turn | ❌ a pointer to that path, delivered on the next request its parent causes |
123
+
124
+ Why reduced: a child's turns belong to whoever delegated it, and injecting one would break the parent's sequencing. Why still worth doing: upstream merged agent teams into subagents, so children are now resumable, addressable colleagues with longer lives; 8 of 116 delegated sessions on this host (6.9%) were folded at least once, and after such a fold the parent keeps addressing a child that only remembers a summary.
125
+
126
+ The fold is detected from the reading, not from a counter: a registered note plus a reading below **90% of the reading it was registered at**. A reading only drops when somebody rewrites the window; a few percent is a trim (a tool catalog coming and going, `defer_loading`) and is not treated as a fold — otherwise a child would be sent to read a note it does not need yet.
127
+
128
+ One timing detail: the reminder is published inside `agent/request`, and that step's runtime-context snapshot is already materialized by then, so the model reads it on its **next** step. That is invisible for a root session (rounds have several steps); a child whose turn is a single step reads the post-fold pointer when its parent next calls it — measured that way, and nothing is lost.
129
+
111
130
  **Known limitation: session permissions can block the note write.** Notes live under `$DSH_HOME/handoffs/…`, and the host sandboxes model file writes per session permission (`checkedTarget` in `@deepseek-ai/dsh-fs-sandbox`, which checks the target against the writable roots of the resolved mode):
112
131
 
113
132
  - **read-only**: every mutation is denied, so the model cannot write the note at all; handoff mode degrades to "remind, but never fold" and the host pressure fold takes over;
@@ -191,6 +210,7 @@ Capability 3 resolves its engine itself, at fold time, through a **ranked candid
191
210
  | `handoffAt` | `0.85` | Prep point for the handoff reminder, as a fraction of the **fold point** (not the window) |
192
211
  | `handoffDir` | `''` | Note directory; empty means `$DSH_HOME/handoffs`, a relative path also resolves under `$DSH_HOME`, never the workspace |
193
212
  | `handoffReminders` | `3` | Reminders per cycle, wake included |
213
+ | `subagentHandoff` | `false` | Remind delegated sessions too: the file is the registration, no wake, no fold, and after the fold only a pointer back (see above) |
194
214
  | `foldAtIdle` | `false` | Legacy switch, equivalent to `foldMode: idle`; an explicit `false` means `off`. Only matters for a config that never set `foldMode` |
195
215
  | `foldAtIdleMarginPercent` | `5` | Fold once the headroom is within this percent of the window (50K on a 1M window) |
196
216
  | `foldAtIdleMethod` | `auto` | Channel for the request: `auto` runs the session's own `/compact` first (realm view), then falls back to the ranked service chain; `command` / `service` force one. `service` is the most predictable of the two (this profile uses it) |
@@ -234,7 +254,7 @@ What you get for it: the model stops halting or handing off because it *thinks*
234
254
  ## Verify
235
255
 
236
256
  ```sh
237
- npm test # 74 unit tests: banding, hysteresis, quantization, free window, fold definition, idle fold and its guards, live settings changes, schema-default parity, pace estimate, degradation, directive patching, look-alike rejection, idempotence, handoff folding (reminder, registration, round-end fold, single activation, restart recovery, recycling, round-end wake), client card shape, the handoff reminder travelling in runtime context rather than as a message, and a live mode switch dropping it
257
+ npm test # 85 unit tests: banding, hysteresis, quantization, free window, fold definition, idle fold and its guards, live settings changes, schema-default parity, pace estimate, degradation, directive patching, look-alike rejection, idempotence, handoff folding (reminder, registration, round-end fold, single activation, restart recovery, recycling, round-end wake, the command channel's real contract and its fallback), notes in delegated sessions (the file as the registration, fold detection, the pointer back, off by default), client card shape, the handoff reminder travelling in runtime context rather than as a message, and a live mode switch dropping it
238
258
  ```
239
259
 
240
260
  After installing, open a new session and send one message: expanding that turn's runtime context block should show `Context occupancy (host-measured): …`, and the log carries `context-truth: none -> ample (used=… window=1000000 compactionAt=678464)`.
package/README.md CHANGED
@@ -168,6 +168,36 @@ this in as few commands as possible, then a short answer."。数字它读对了
168
168
  交接档是临时文件,下一次交接生成时回收旧的、7 天兜底清理;登记了档但没折成(引擎拒绝、被别的东西
169
169
  先折了)时不会激活,档保留。
170
170
 
171
+ 命令通道判定"折没折成"的依据是**宿主自己的返回形状**:`commands.execute()` 返回
172
+ `CommandExecution = { commandId, result }`,所以要看 `execution.result.sourceEventSeq`。0.4.1 之前误读成
173
+ `execution.sourceEventSeq`(恒为 `undefined`),导致**命令通道上折叠成功也不会激活轮次**——stock 部署
174
+ (realm 里没有可注入的 `compaction` 服务)上就是"折了但永远没有下一轮"。另外 `/compact` 未注册时
175
+ `execute()` 是 resolve `undefined` 而不是抛错,这种情形现在会明确回退到 compaction 服务,不再被当成
176
+ "没有可折叠范围"。
177
+
178
+ #### 委派会话的交接档(`subagentHandoff`,默认关)
179
+
180
+ 根会话的 handoff 依赖两件子会话没有的东西:折叠是本插件做的,激活轮是本插件开的。所以给子会话的不是同一套,
181
+ 而是缩小版:
182
+
183
+ | | 根会话 | 委派会话(`subagentHandoff: true`) |
184
+ |---|---|---|
185
+ | 提醒 | ✅ runtime context 块 | ✅ 同一个块、同一套预算(每轮一次、每周期 `handoffReminders` 次) |
186
+ | 登记 | 调 `handoff_ready` | **写文件即登记**(子会话调 `handoff_ready` 一律拒答) |
187
+ | 折叠 | 插件在轮末执行 | ❌ 宿主在压力点执行,插件只观察 |
188
+ | 折叠后 | `followup` 自动激活唯一一轮 | ❌ 只在**父代理下一次找它**的那个请求里发一条指回路径的提示 |
189
+
190
+ 为什么缩小:子会话的轮次属于它的委派方,插件注入一轮会打乱父代理的编排。为什么仍然值得做:上游把团队并进
191
+ 子代理后,子代理成了可续、可寻址的同事,生命周期变长;本机 116 个子代理里 8 个(6.9%)至少折叠过一次,
192
+ 而折叠后父代理照样找它,它却只记得摘要。
193
+
194
+ 折叠的判定用读数而不是计数器:已登记 + 读数掉到**登记时读数的 90% 以下**。读数只在窗口被重写时才会掉下来,
195
+ 掉几个百分点属于工具目录进出(`defer_loading`)之类的抖动,不当折叠——否则子会话会去读一份它还不需要的档。
196
+
197
+ 一个时序细节:提醒发布在 `agent/request` 里,而该步的 runtime-context 快照在它之前就物化了,所以模型**下一步**
198
+ 才读到它。对根会话(一轮多步)没有影响;子会话若一轮只有一步,折叠后那条指回提示会等到父代理下一次叫它
199
+ 才被读到——实测就是这样读到的,不算丢失。
200
+
171
201
  **已知限制:会话权限能挡住交接档写入。** 交接档在 `$DSH_HOME/handoffs/…`,而宿主按会话权限给模型的文件写入设了沙箱
172
202
  (`@deepseek-ai/dsh-fs-sandbox` 的 `checkedTarget`:按权限模式判断目标是否落在可写根内):
173
203
 
@@ -272,6 +302,7 @@ dsh plugin --profile web add dsh-context-truth
272
302
  | `handoffAt` | `0.85` | 交接提醒的准备点,作为**折叠点**的比例(不是窗口比例) |
273
303
  | `handoffDir` | `''` | 交接档目录;空=`$DSH_HOME/handoffs`,相对路径也落在 `$DSH_HOME` 下,绝不进工作区 |
274
304
  | `handoffReminders` | `3` | 每个周期最多提醒几次(含轮末唤醒) |
305
+ | `subagentHandoff` | `false` | 委派会话也提醒写交接档:写文件即登记、不唤醒、不折叠,折叠后只指回路径(见上文) |
275
306
  | `foldAtIdle` | `false` | 旧开关,等价于 `foldMode: idle`;显式 `false` 等价于 `off`,只对没写过 `foldMode` 的配置生效 |
276
307
  | `foldAtIdleMarginPercent` | `5` | 余量 ≤ 窗口的百分之几时触发(1M 窗口 = 50K) |
277
308
  | `foldAtIdleMethod` | `auto` | 折叠请求通道:`auto`=先走该会话的 `/compact`(realm 视图)再回退到服务候选链;`command`/`service` 强制其一。`service` 是最可预测的一档(本 profile 用它) |
@@ -336,7 +367,7 @@ runtime-context 快照**字节不变就不会重发**,所以读数按台阶量
336
367
  ## 验证
337
368
 
338
369
  ```sh
339
- npm test # 74 项单测:分档/迟滞/量化/自由窗口/折叠定义/空闲折叠与护栏/配置热更新/schema 默认值一致性/节奏估算/降级/摘要改写/形似请求排除/幂等/交接式折叠(提醒、登记、轮末折叠、单次激活、重启恢复、回收、轮末唤醒)/客户端设置卡结构/交接提醒走 runtime context 而非消息,以及实时切模式后提醒随模式消失
370
+ npm test # 85 项单测:分档/迟滞/量化/自由窗口/折叠定义/空闲折叠与护栏/配置热更新/schema 默认值一致性/节奏估算/降级/摘要改写/形似请求排除/幂等/交接式折叠(提醒、登记、轮末折叠、单次激活、重启恢复、回收、轮末唤醒、命令通道的真实契约与回退)/委派会话的交接档(写文件即登记、折叠判定、折叠后指回、默认关)/客户端设置卡结构/交接提醒走 runtime context 而非消息,以及实时切模式后提醒随模式消失
340
371
  ```
341
372
 
342
373
  装好后开一个新会话发一条消息,展开该轮的 runtime context 块应看到
package/lib/index.js CHANGED
@@ -146,11 +146,13 @@ const DEFAULT_OPTIONS = {
146
146
  * profile's compaction config; the line only reports the point, it never
147
147
  * enforces it.
148
148
  *
149
- * 0.7 rather than upstream's 0.8 because this profile runs `@aiwayds/dsh-dcp`,
150
- * whose bundle sets `thresholdRatio: 0.7` (verified against the live engine:
151
- * thresholdRatio=0.7, headroomTokens=65536, retainRatio=0.16). The displayed
152
- * point is unchanged either way — the budget term binds at 678,464 — but the
153
- * mirror must match for the case where it does not.
149
+ * 0.7 is the value a `@aiwayds/dsh-dcp` bundle sets (verified against a live
150
+ * engine: thresholdRatio=0.7, headroomTokens=65536, retainRatio=0.16); stock
151
+ * compaction uses 0.8. ✗ Do not read this default as a statement about "this
152
+ * machine": a profile that mounts no such provider (e.g. a stock Linux box) should
153
+ * set `thresholdRatio: 0.8` to match what it actually runs. The displayed point is
154
+ * often unchanged either way — the budget term binds at 727,040 on a 1M window with
155
+ * 256K reserved — but the mirror must match for the cases where it does not.
154
156
  */
155
157
  thresholdRatio: 0.7,
156
158
  headroomTokens: 65536,
@@ -285,6 +287,21 @@ const DEFAULT_OPTIONS = {
285
287
  * which is the behaviour this mode exists to improve on — so keep it above 1.
286
288
  */
287
289
  handoffReminders: 3,
290
+ /**
291
+ * Extend the handoff reminder to DELEGATED sessions (default off).
292
+ *
293
+ * A delegate gets no fold from this plugin — the host's pressure fold owns it —
294
+ * so this is deliberately the reduced shape: remind it past the prep point, let
295
+ * the plain file be the registration (a child never gets `handoff_ready`), and
296
+ * after the fold point hand it a pointer back to that note. No wake and no fold:
297
+ * a delegate's turns belong to whoever delegated it, and a `followup` injected
298
+ * into that arrangement would break the parent's sequencing.
299
+ *
300
+ * Off by default because it changes what every child session's model is told,
301
+ * and most children never get near the prep point (measured on this host: 8 of
302
+ * 116 delegated sessions were ever folded, 6.9%).
303
+ */
304
+ subagentHandoff: false,
288
305
  }
289
306
 
290
307
  /**
@@ -356,6 +373,7 @@ export const Config = z.object({
356
373
  handoffAt: z.number().min(0.5).max(0.95).default(0.85).volatile(),
357
374
  handoffDir: z.string().default('').volatile(),
358
375
  handoffReminders: z.number().step(1).min(0).default(3).volatile(),
376
+ subagentHandoff: z.boolean().default(false).volatile(),
359
377
  })
360
378
 
361
379
  /** Clamp a numeric option, falling back when it is not a finite number. */
@@ -468,6 +486,7 @@ function resolveOptions(config) {
468
486
  0,
469
487
  Math.round(num(merged.handoffReminders, DEFAULT_OPTIONS.handoffReminders)),
470
488
  ),
489
+ subagentHandoff: merged.subagentHandoff === true,
471
490
  }
472
491
  }
473
492
 
@@ -1207,13 +1226,15 @@ export function apply(ctx, config) {
1207
1226
 
1208
1227
  // Handoff prep travels as runtime context, not as a message.
1209
1228
  //
1210
- // The request hook runs before the step's context refresh (`agent/request` is
1211
- // emitted inside `prepareRequest`, and the loop refreshes the dynamic context
1212
- // right after that call returns), so a notice published here is rendered by the
1213
- // very request that decided to remind — no queued user message, no bubble in
1214
- // the transcript. `prepare` retires the session's previous notice before it
1215
- // decides anything, so the paragraph is rendered exactly once instead of being
1216
- // re-sent on every step of the turn.
1229
+ // A notice published here is rendered by the **next** request's snapshot, not by
1230
+ // the one that decided to remind. Measured on 0.2.2 (delegate drill, 2026-11-20):
1231
+ // publish at 19:50:08.943, and the block appears in the step whose snapshot is
1232
+ // materialized at 19:50:11 — the snapshot is taken before that step's
1233
+ // `agent/request` waterfall runs, so the same step cannot carry it. Consequences
1234
+ // worth keeping in mind: a round's LAST step can never render a notice (the next
1235
+ // round's first step does), and a single-step turn shows it one turn later.
1236
+ // `prepare` retires the session's previous notice before deciding anything, so
1237
+ // the paragraph is still rendered exactly once rather than on every step.
1217
1238
  const handoffNotices = new Map()
1218
1239
 
1219
1240
  if (resolve().enabled) {
@@ -1366,6 +1387,27 @@ function installIdleFold(ctx, resolve, services) {
1366
1387
  })
1367
1388
  }
1368
1389
 
1390
+ /**
1391
+ * Unwrap the host's `commands.execute()` answer.
1392
+ *
1393
+ * `dsh-commands` settles a run as `Object.freeze({ commandId, result })` — a
1394
+ * `CommandExecution`, not the `CommandResult` — and the RPC schema is the same two
1395
+ * layers. Reading `execution.sourceEventSeq` therefore always misses, and because a
1396
+ * missing `sourceEventSeq` is exactly how this plugin recognises "the fold found
1397
+ * nothing to compact", **every** successful fold through the command channel looked
1398
+ * like a no-op: handoff mode kept the note and never activated the post-fold turn
1399
+ * (live: session b28499cb on 2026-11-22 01:22, where `/compact` really folded 1295
1400
+ * items / ~506k tokens and `state.json` still said `foldNo: 0`).
1401
+ *
1402
+ * Both shapes are accepted, so a stub or an older host that answers with the
1403
+ * `CommandResult` itself keeps working.
1404
+ */
1405
+ function commandResultOf(execution) {
1406
+ if (execution === null || execution === undefined) return undefined
1407
+ const nested = execution.result
1408
+ return nested !== null && nested !== undefined && typeof nested === 'object' ? nested : execution
1409
+ }
1410
+
1369
1411
  /**
1370
1412
  * Ask for one fold, at the agent's own idle boundary.
1371
1413
  *
@@ -1389,16 +1431,50 @@ function installIdleFold(ctx, resolve, services) {
1389
1431
  * a follow-up turn on the strength of a fold that never happened.
1390
1432
  */
1391
1433
  async function requestFold(ctx, agent, options, services, signal) {
1434
+ const session = agent === null || agent === undefined ? undefined : agent.session
1392
1435
  if (options.foldAtIdleMethod !== 'service') {
1393
1436
  const commands = safeGet(ctx, 'commands')
1394
1437
  if (commands !== undefined && typeof commands.execute === 'function') {
1395
1438
  try {
1396
- const result = await commands.execute(agent, '/compact', [], signal)
1397
- // `sourceEventSeq` correlates the committed summary with `compaction/summary`
1398
- // and is absent on the "No compactable history yet" success.
1399
- return {
1400
- how: 'command',
1401
- folded: result !== null && result !== undefined && result.sourceEventSeq !== undefined,
1439
+ const execution = await commands.execute(agent, '/compact', [], signal)
1440
+ if (execution === undefined) {
1441
+ // `execute()` RESOLVES `undefined` — it does not throw — when the line
1442
+ // does not parse or the command is not registered in the agent's realm
1443
+ // (`dsh-commands`: `if (parsed === void 0) return void 0`). Only a throw
1444
+ // used to fall through to the service, so the documented "command, then
1445
+ // service" order was dead on a realm without `/compact`.
1446
+ if (options.foldAtIdleMethod === 'command') {
1447
+ logLine(
1448
+ ctx,
1449
+ 'info',
1450
+ 'context-truth: /compact is not registered for %s and the fold method is "command"; no other channel is allowed',
1451
+ sessionIdOf(session),
1452
+ )
1453
+ return undefined
1454
+ }
1455
+ logLine(
1456
+ ctx,
1457
+ 'info',
1458
+ 'context-truth: /compact is not registered for %s; falling back to the compaction service',
1459
+ sessionIdOf(session),
1460
+ )
1461
+ } else {
1462
+ const result = commandResultOf(execution)
1463
+ const kind = result === null || result === undefined ? undefined : result.kind
1464
+ // `sourceEventSeq` correlates the committed summary with `compaction/summary`
1465
+ // and is absent on the "No compactable history yet" success.
1466
+ const folded = result !== null && result !== undefined && result.sourceEventSeq !== undefined
1467
+ if (!folded && (kind === 'error' || kind === 'cancelled')) {
1468
+ logLine(
1469
+ ctx,
1470
+ 'info',
1471
+ 'context-truth: /compact did not fold for %s (%s): %s',
1472
+ sessionIdOf(session),
1473
+ kind,
1474
+ result.text === undefined ? 'no text' : result.text,
1475
+ )
1476
+ }
1477
+ return { how: 'command', folded, reason: folded ? 'ok' : (kind ?? 'no-range') }
1402
1478
  }
1403
1479
  } catch (error) {
1404
1480
  // A realm without the command, or a refusal, is not fatal: the service
@@ -1446,7 +1522,8 @@ async function requestFold(ctx, agent, options, services, signal) {
1446
1522
  if (compaction === undefined) return undefined
1447
1523
  const result = await compaction.compactNow(agent, signal)
1448
1524
  // `null` is the engine's documented "no safe useful range" answer.
1449
- return { how: 'service', folded: result !== null && result !== undefined }
1525
+ const folded = result !== null && result !== undefined
1526
+ return { how: 'service', folded, reason: folded ? 'ok' : 'no-range' }
1450
1527
  }
1451
1528
 
1452
1529
  // ---------------------------------------------------------------------------
@@ -1630,6 +1707,95 @@ function handoffPrepMessage({ path, trigger, recycled, options }) {
1630
1707
  ].join('\n')
1631
1708
  }
1632
1709
 
1710
+ /**
1711
+ * Delegate variant of the prep reminder.
1712
+ *
1713
+ * Two things must NOT be copied from the root text: `handoff_ready` (a child's
1714
+ * call is refused on purpose, and telling it to call a refusing tool is worse than
1715
+ * saying nothing) and the promise that the fold runs at this round's end (nothing
1716
+ * here folds a delegate; the host does it at the pressure point, whenever that
1717
+ * lands). What survives is the part that matters: the one allowed path, the
1718
+ * section checklist, and the bar — a reader with no conversation history.
1719
+ */
1720
+ function handoffDelegatePrepMessage({ path, trigger, recycled, options }) {
1721
+ const percent = foldPointPercent(trigger.used, trigger.threshold)
1722
+ const used = formatTokens(trigger.used)
1723
+ const point = formatTokens(trigger.threshold)
1724
+ const recycledNote =
1725
+ recycled > 0
1726
+ ? options.language === 'zh'
1727
+ ? `(按回收策略删掉了上一份 ${recycled} 个档文件。)`
1728
+ : ` (recycled ${recycled} older note file(s) per the recycling rule.)`
1729
+ : ''
1730
+ if (options.language === 'zh') {
1731
+ return [
1732
+ `[交接式折叠 · 子代理准备] 这个被委派的会话已用到折叠点的 ${percent}%(${used} / ${point})。折叠由宿主在折叠点执行,不看你的进度;它不是本插件的折叠,也不会给你开新轮。`,
1733
+ '',
1734
+ '现在写一份交接档给折叠后的你自己,然后继续手头的活(不要为写档中断任务):',
1735
+ `1) 路径必须是这个,不要改:${path}`,
1736
+ '2) 按这几节写,标准是「不看对话历史也能立刻接上」:',
1737
+ ' - 当前目标(一句话)',
1738
+ ' - 已定案(拍过板的决定,注明勿再复议)',
1739
+ ' - 已验证的事实与证据(命令输出、file:line)',
1740
+ ' - 待办(按序,标出下一步的第一个动作)',
1741
+ ' - 关键路径',
1742
+ ' - 坑(试过并失败的路线,避免重试)',
1743
+ '3) 写完就够了,不要调用工具登记:**文件本身就是登记**(`handoff_ready` 对子代理一律拒答)。',
1744
+ `4) 这是临时文件:下一次交接生成时它会被回收${recycledNote}。要长期保留的内容写进项目里,不要留在这里。`,
1745
+ '',
1746
+ '折叠之后,你下一次被唤醒的那个请求里会把这份档的路径再指给你一次。',
1747
+ ].join('\n')
1748
+ }
1749
+ return [
1750
+ `[handoff fold · subagent prepare] This delegated session is at ${percent}% of its fold point (${used} / ${point}). The fold is the host's, at the fold point, regardless of where you are in your work; it is not this plugin's fold and it will not open a turn for you.`,
1751
+ '',
1752
+ 'Write a handoff note for the post-fold you, then continue your work (do not interrupt the task to do this):',
1753
+ `1) The path must be exactly this one, do not change it: ${path}`,
1754
+ '2) Use these sections; the bar is "a reader with no conversation history can continue":',
1755
+ ' - current goal (one line)',
1756
+ ' - decisions already made (note that they are settled)',
1757
+ ' - verified facts and their evidence (command output, file:line)',
1758
+ ' - next steps in order, with the very next action marked',
1759
+ ' - key paths',
1760
+ ' - dead ends already tried, so they are not retried',
1761
+ '3) Writing the file is the whole registration; do not call a tool for it (`handoff_ready` refuses a delegated session on purpose).',
1762
+ `4) This is a temporary file: it is recycled when the next handoff is created${recycledNote}. Anything that must outlive it belongs in the project.`,
1763
+ '',
1764
+ 'After the fold, the next request you serve will point you back at this note.',
1765
+ ].join('\n')
1766
+ }
1767
+
1768
+ /**
1769
+ * Delegate variant of the activation turn: a pointer, not a turn.
1770
+ *
1771
+ * A delegate cannot be woken without breaking whoever is driving it, so the
1772
+ * post-fold step is a runtime-context block on the request the parent causes
1773
+ * next. It therefore has to carry the "read it first" instruction itself — there
1774
+ * is no first user message of an activation round to lean on.
1775
+ */
1776
+ function handoffDelegateFoldMessage({ path, options }) {
1777
+ if (options.language === 'zh') {
1778
+ return [
1779
+ '[交接式折叠 · 子代理折叠后] 你的窗口在上一次请求之后被折叠过了:细节已经不在上下文里,摘要是有损重建。',
1780
+ '折叠前你自己写过一份交接档,它还在 —— 先读它再动手:',
1781
+ path,
1782
+ '',
1783
+ '1) 先 read 这个文件。它比摘要可靠:那里是你折叠前的第一手记录。',
1784
+ '2) 从它的「待办」继续,不要重新推导档里已经写明的结论。',
1785
+ '3) 如果档里的描述和你现在看到的实际情况冲突,以实际情况为准,并在给委派方的汇报里说清分歧。',
1786
+ ].join('\n')
1787
+ }
1788
+ return [
1789
+ '[handoff fold · subagent, after the fold] Your window was folded since your last request: the details are no longer in context and the summary is a lossy reconstruction.',
1790
+ 'You wrote yourself a handoff note before that happened, and it is still there — read it before you act:',
1791
+ path,
1792
+ '',
1793
+ '1) Read that file first. It is your own first-hand record from before the fold, and it is more reliable than the summary.',
1794
+ '2) Continue from its "next steps"; do not re-derive conclusions it already states.',
1795
+ '3) Where it disagrees with what you observe now, trust the observation and say where they diverged when you report back.',
1796
+ ].join('\n')
1797
+ }
1798
+
1633
1799
  /**
1634
1800
  * Wake message: one line that opens the round.
1635
1801
  *
@@ -1685,7 +1851,14 @@ function emptyHandoffState(sessionId) {
1685
1851
  return { version: 1, sessionId, foldNo: 0, reminders: 0, reminderTurn: null, ready: null, pending: null, wokenAt: null }
1686
1852
  }
1687
1853
 
1688
- /** A registered note, or `null` when the record is unusable. */
1854
+ /**
1855
+ * A registered note, or `null` when the record is unusable.
1856
+ *
1857
+ * `used` is the occupancy at the moment the note was seen. The root path writes it
1858
+ * for the record and never reads it; the delegate path reads it to tell a real fold
1859
+ * (the reading halves) from a small trim (the reading wobbles), because a delegate's
1860
+ * fold is somebody else's decision and cannot be inferred from a fold count.
1861
+ */
1689
1862
  function normalizeReady(value) {
1690
1863
  if (value === null || typeof value !== 'object') return null
1691
1864
  if (typeof value.path !== 'string' || value.path === '') return null
@@ -1693,6 +1866,7 @@ function normalizeReady(value) {
1693
1866
  path: value.path,
1694
1867
  chars: Number.isFinite(value.chars) ? value.chars : 0,
1695
1868
  at: Number.isFinite(value.at) ? value.at : 0,
1869
+ used: Number.isFinite(value.used) && value.used > 0 ? value.used : 0,
1696
1870
  }
1697
1871
  }
1698
1872
 
@@ -1954,6 +2128,115 @@ function installHandoffFold(ctx, resolve, services, notices) {
1954
2128
  return { path, trigger, recycled }
1955
2129
  }
1956
2130
 
2131
+ /**
2132
+ * Step 1c: the delegate variant of step 1 (`subagentHandoff`, opt-in).
2133
+ *
2134
+ * A delegated session has the same blind spot as a root one — the fold rewrites
2135
+ * the window and the first-hand record of what it was doing goes with it — but
2136
+ * none of the same levers: nothing here may fold it (the host owns that) and
2137
+ * nothing here may wake it (its parent owns its turns). So the variant is
2138
+ * exactly: remind, take the FILE as the registration, and after the fold hand
2139
+ * back the way to that note.
2140
+ *
2141
+ * The fold is detected from the reading, not from a fold counter: `used` only
2142
+ * drops when somebody rewrote the window, so a registered note plus a reading
2143
+ * below 90% of the reading it was registered at IS the fold. Anything gentler is
2144
+ * a trim (a tool catalog coming and going, `defer_loading`) and is ignored. The
2145
+ * 10% band is what keeps a 2K wobble from being reported as a fold.
2146
+ */
2147
+ function prepareDelegate(options, session, turn) {
2148
+ const sessionId = sessionIdOf(session)
2149
+ if (sessionId === '') return
2150
+ // Same one-shot discipline as the root path: retire the previous request's
2151
+ // block before this request decides anything.
2152
+ notices.delete(sessionId)
2153
+ const state = stateFor(options, sessionId)
2154
+ const root = handoffRoot(options)
2155
+ const path = handoffPathFor(root, sessionId, state.foldNo + 1)
2156
+ const trigger = handoffTrigger(readOccupancy(ctx, session, options, services.meter), options)
2157
+
2158
+ // Discovery. A child never gets `handoff_ready` (the tool refuses delegates on
2159
+ // purpose), so requiring a registration call would make every reminder a dead
2160
+ // end: the file the model wrote is the registration.
2161
+ const chars = handoffFileChars(path)
2162
+ if (chars !== null && state.ready === null) {
2163
+ state.ready = {
2164
+ path,
2165
+ chars,
2166
+ at: Date.now(),
2167
+ used: Number.isFinite(trigger.used) && trigger.used > 0 ? trigger.used : 0,
2168
+ }
2169
+ persist(options, sessionId, state)
2170
+ logLine(ctx, 'info', 'context-truth: delegate %s wrote its handoff note (%s chars) -> %s', sessionId, chars, path)
2171
+ }
2172
+
2173
+ if (state.ready !== null && Number.isFinite(trigger.used)) {
2174
+ const note = state.ready
2175
+ const folded = note.used > 0 && trigger.used < note.used * 0.9
2176
+ // A note found while already below the prep point was written before this
2177
+ // plugin started watching (a restart, or the option switched on mid-session),
2178
+ // so the fold it was written for has already happened.
2179
+ const discoveredLate = note.used === 0 && !trigger.prepare
2180
+ if (folded || discoveredLate) {
2181
+ state.foldNo += 1
2182
+ state.ready = null
2183
+ state.reminders = 0
2184
+ state.reminderTurn = turn === undefined ? null : turn
2185
+ persist(options, sessionId, state)
2186
+ notices.set(sessionId, handoffDelegateFoldMessage({ path: note.path, options }))
2187
+ logLine(
2188
+ ctx,
2189
+ 'info',
2190
+ 'context-truth: delegate %s was folded since it wrote %s (used=%s, registered at=%s, cause=%s); pointing it back',
2191
+ sessionId,
2192
+ note.path,
2193
+ trigger.used,
2194
+ note.used > 0 ? note.used : 'unknown',
2195
+ folded ? 'reading dropped' : 'note found below the prep point',
2196
+ )
2197
+ return
2198
+ }
2199
+ }
2200
+
2201
+ if (!trigger.prepare) return
2202
+ // A pending note owns the next reminder; nagging on top of it only costs turns.
2203
+ if (state.ready !== null) return
2204
+ if (state.reminders >= options.handoffReminders) {
2205
+ noteOnce(
2206
+ `delegate-budget:${sessionId}`,
2207
+ 'info',
2208
+ 'context-truth: delegate handoff reminder budget spent for %s (%s in this cycle); the host pressure fold takes this one',
2209
+ sessionId,
2210
+ options.handoffReminders,
2211
+ )
2212
+ return
2213
+ }
2214
+ if (turn !== undefined && state.reminderTurn === turn) return
2215
+ const doomed = handoffReapable(root, sessionId, [path, handoffPathFor(root, sessionId, state.foldNo)])
2216
+ // Runtime context, exactly like the root reminder, and with the same one-step
2217
+ // delay: this request's snapshot is already materialized, so the child reads it
2218
+ // on its next step (or next turn, if this was its last step). No user message
2219
+ // is fabricated on the parent's behalf.
2220
+ notices.set(sessionId, handoffDelegatePrepMessage({ path, trigger, recycled: doomed.length, options }))
2221
+ // Reap after the notice lands, so a failed delivery never costs the previous note.
2222
+ const recycled = deleteFiles(doomed)
2223
+ state.reminders += 1
2224
+ state.reminderTurn = turn === undefined ? null : turn
2225
+ persist(options, sessionId, state)
2226
+ logLine(
2227
+ ctx,
2228
+ 'info',
2229
+ 'context-truth: delegate handoff prep %s/%s for %s (used=%s of the %s fold point, recycled=%s) -> %s',
2230
+ state.reminders,
2231
+ options.handoffReminders,
2232
+ sessionId,
2233
+ trigger.used,
2234
+ trigger.threshold,
2235
+ recycled,
2236
+ path,
2237
+ )
2238
+ }
2239
+
1957
2240
  /**
1958
2241
  * Step 1: remind the model while it can still act. Runs inside the
1959
2242
  * `agent/request` waterfall, so it stays synchronous and swallows everything —
@@ -1968,7 +2251,11 @@ function installHandoffFold(ctx, resolve, services, notices) {
1968
2251
  if (options.foldMode !== 'handoff') return
1969
2252
  const session = agent === null || agent === undefined ? undefined : agent.session
1970
2253
  if (session === null || session === undefined) return
1971
- if (isDelegate(session)) return
2254
+ if (isDelegate(session)) {
2255
+ // Reduced variant (opt-in): remind and point back, never wake and never fold.
2256
+ if (options.subagentHandoff) prepareDelegate(options, session, turn)
2257
+ return
2258
+ }
1972
2259
  const sessionId = sessionIdOf(session)
1973
2260
  if (sessionId === '') return
1974
2261
  // Retire the previous request's notice before this request decides anything,
@@ -2018,9 +2305,9 @@ function installHandoffFold(ctx, resolve, services, notices) {
2018
2305
  const keep = [path, handoffPathFor(root, sessionId, state.foldNo)]
2019
2306
  const doomed = handoffReapable(root, sessionId, keep)
2020
2307
  // Publish the reminder into runtime context instead of queueing a user
2021
- // message: the same request renders it (the loop refreshes the dynamic
2022
- // context right after this waterfall), so it is as timely as `inject` and
2023
- // never looks like something the human typed.
2308
+ // message: it is as timely as `inject` and never looks like something the human
2309
+ // typed. It is rendered by the NEXT request's snapshot (see the note above
2310
+ // `handoffNotices`), which for a multi-step round is one step away.
2024
2311
  notices.set(sessionId, handoffPrepMessage({ path, trigger, recycled: doomed.length, options }))
2025
2312
  // Reap after the notice lands, so a failed delivery does not cost the model
2026
2313
  // its previous note for nothing.
@@ -2229,11 +2516,15 @@ function installHandoffFold(ctx, resolve, services, notices) {
2229
2516
  return
2230
2517
  }
2231
2518
  if (!outcome.folded) {
2519
+ // The channel has already logged *why* it did not commit (refused,
2520
+ // cancelled, nothing to compact); this line records the consequence.
2521
+ const reason = outcome.reason === undefined ? 'no-range' : outcome.reason
2232
2522
  logLine(
2233
2523
  ctx,
2234
- 'info',
2235
- 'context-truth: the fold reported no compactable range for %s; the note at %s is kept for the next round end',
2524
+ reason === 'error' ? 'warn' : 'info',
2525
+ 'context-truth: the fold did not commit for %s (%s); the note at %s is kept for the next round end',
2236
2526
  sessionId,
2527
+ reason,
2237
2528
  note.path,
2238
2529
  )
2239
2530
  return
@@ -2314,6 +2605,14 @@ function installHandoffFold(ctx, resolve, services, notices) {
2314
2605
  return zh ? '✗ handoff_ready 需要一个活着的会话,没有登记任何东西。' : '✗ handoff_ready needs a live session; nothing was registered.'
2315
2606
  }
2316
2607
  if (isDelegate(session)) {
2608
+ // With the delegate variant on, "refused" must still be actionable: the
2609
+ // child's registration is the file itself, and this call is the one step
2610
+ // it does NOT need.
2611
+ if (options.subagentHandoff) {
2612
+ return zh
2613
+ ? '✗ 当前是委派会话:交接式折叠不在子会话上执行,**写文件本身就是登记**,不需要调用这个工具。'
2614
+ : '✗ this is a delegated session: handoff folding does not run on a child, and writing the note file IS the registration — this tool is not needed.'
2615
+ }
2317
2616
  return zh
2318
2617
  ? '✗ 当前是委派会话,交接式折叠只在根会话上生效;没有登记任何东西。'
2319
2618
  : '✗ this is a delegated session, and handoff folding only applies to a root session; nothing was registered.'
@@ -2650,6 +2949,8 @@ export const internals = {
2650
2949
  handoffRoot,
2651
2950
  handoffPathFor,
2652
2951
  handoffPrepMessage,
2952
+ handoffDelegatePrepMessage,
2953
+ handoffDelegateFoldMessage,
2653
2954
  handoffWakeMessage,
2654
2955
  handoffActivationMessage,
2655
2956
  handoffReapable,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-truth",
3
- "version": "0.3.4",
3
+ "version": "0.4.1",
4
4
  "description": "DeepSeek Harness plugin: tells the model its real, host-measured context occupancy every turn — and keeps compaction summaries from carrying false \"context is nearly exhausted\" claims.",
5
5
  "keywords": [
6
6
  "deepseek-harness",
@@ -8,7 +8,7 @@ import { apply, internals, name, inject, Config, CONTEXT_NAME, VARIABLE_NAME, HA
8
8
 
9
9
  const { resolveOptions, readOccupancy, settleBand, quantize, quantizeHeadroom, headroomDisplayStep, render, patchCompactionInstruction, patchCompactionRequest, isCompactionRequest, isTaggedCompactionRequest, messageText, DEFAULT_OPTIONS, DEFAULT_COMPACTION_RULES, PACE_LADDER, median, nextPaceState, samplePace, paceSteps, paceRung, settlePace, paceSentence, tightClause, foldClause, shouldFoldAtIdle, backendIdentity } = internals
10
10
 
11
- const { resolveFoldMode, handoffTrigger, handoffRoot, handoffPathFor, handoffPrepMessage, handoffWakeMessage, handoffActivationMessage, handoffReapable, sweepHandoffs, handoffFileChars, safeSegment, sessionIdOf, isDelegate, samePath, HANDOFF_TOOL_NAME, HANDOFF_MIN_CHARS, HANDOFF_MAX_AGE_MS, HANDOFF_STATE_FILE } = internals
11
+ const { resolveFoldMode, handoffTrigger, handoffRoot, handoffPathFor, handoffPrepMessage, handoffDelegatePrepMessage, handoffDelegateFoldMessage, handoffWakeMessage, handoffActivationMessage, handoffReapable, sweepHandoffs, handoffFileChars, safeSegment, sessionIdOf, isDelegate, samePath, HANDOFF_TOOL_NAME, HANDOFF_MIN_CHARS, HANDOFF_MAX_AGE_MS, HANDOFF_STATE_FILE } = internals
12
12
 
13
13
  /** A 1M window reserving the DeepSeek adapter's default 256K completion tokens. */
14
14
  const WINDOW = 1000000
@@ -1523,6 +1523,132 @@ test('handoff mode folds at the round end and activates exactly one turn', async
1523
1523
  assert.ok(state.pending.deliveredAt > 0)
1524
1524
  })
1525
1525
 
1526
+ test('a fold through the real /compact contract activates the post-fold turn', async (t) => {
1527
+ // 宿主契约:`dsh-commands` 的 `settle()` 返回 `Object.freeze({ commandId, result })`,
1528
+ // 所以 `sourceEventSeq` 在 `result` 里,不在 `execute()` 的返回值上。0.4.0 之前按扁平读,
1529
+ // 于是每一次成功折叠都被判成“没有可折叠范围” → handoff 从不激活(现场 session b28499cb,
1530
+ // 2026-11-22 01:22:`/compact` 真的折了 1295 条 / ~506k tokens,state.json 仍是 foldNo 0)。
1531
+ const root = scratchRoot(t)
1532
+ const { box, meter } = movableMeter(500000)
1533
+ const executions = []
1534
+ const logs = []
1535
+ const commands = {
1536
+ execute: (...args) => {
1537
+ executions.push(args)
1538
+ // 与现场 `command/done` 逐字一致的两层形状。
1539
+ return Promise.resolve({
1540
+ commandId: 'cmd-repro-1',
1541
+ result: {
1542
+ kind: 'success',
1543
+ text: 'Compacted 1295 history items (~506473 tokens).',
1544
+ sourceEventSeq: 3436,
1545
+ },
1546
+ })
1547
+ },
1548
+ }
1549
+ const agent = handoffAgent(handoffSession('session-contract'))
1550
+ // 现场是 stock 部署:只有命令通道可用,没有任何 compaction 服务可注入。
1551
+ const { ctx, registered } = stubContext({ meter, commands, logs })
1552
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1553
+
1554
+ const notePath = handoffPathFor(root, 'session-contract', 1)
1555
+ box.used = 600000
1556
+ await requestStep(registered, agent, 2, 1)
1557
+ assert.ok(handoffBlock(registered, agent).includes(notePath), 'the reminder names the path')
1558
+
1559
+ mkdirSync(join(root, 'session-contract'), { recursive: true })
1560
+ writeFileSync(notePath, `# note\n${'x'.repeat(400)}`, 'utf8')
1561
+ const tool = registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
1562
+ assert.match(tool.execute({ path: notePath }, { agent }), /handoff registered/)
1563
+
1564
+ await idleBoundary(registered, agent)
1565
+
1566
+ assert.equal(executions.length, 1, 'the fold must go through the command channel')
1567
+ assert.equal(executions[0][1], '/compact', 'the fold is the session\'s own /compact')
1568
+ assert.deepEqual(executions[0][2], [], 'submitted attachments must be an empty list')
1569
+ assert.ok(executions[0][3] !== undefined, 'the command must receive an abort signal')
1570
+ assert.equal(
1571
+ agent.followed.length,
1572
+ 1,
1573
+ `the post-fold turn must be activated (logs: ${JSON.stringify(logs.map((entry) => entry.slice(0, 2)))})`,
1574
+ )
1575
+ assert.ok(agent.followed[0].content[0].text.includes(notePath), 'the activation points at the note')
1576
+
1577
+ const state = JSON.parse(readFileSync(join(root, 'session-contract', HANDOFF_STATE_FILE), 'utf8'))
1578
+ assert.equal(state.foldNo, 1, 'the fold must be recorded')
1579
+ assert.equal(state.ready, null, 'the registered note must be consumed')
1580
+ assert.ok(state.pending !== null && state.pending.deliveredAt !== null, 'the activation must be marked delivered')
1581
+ })
1582
+
1583
+ test('an unregistered /compact falls back to the compaction service instead of answering "no range"', async (t) => {
1584
+ // `dsh-commands.execute()` 对“命令没注册/语法不认识”是 resolve undefined,不 throw。
1585
+ // 只有 throw 才回退 → realm 里没有 /compact 的部署上,`auto` 的第二条腿是死的。
1586
+ const root = scratchRoot(t)
1587
+ const { meter } = movableMeter(600000)
1588
+ const folds = []
1589
+ const logs = []
1590
+ const commands = { execute: () => Promise.resolve(undefined) }
1591
+ const session = handoffSession('session-fallback')
1592
+ const agent = handoffAgent(session)
1593
+ const { ctx, registered } = stubContext({
1594
+ meter,
1595
+ commands,
1596
+ logs,
1597
+ compaction: { compactNow: (...args) => (folds.push(args), Promise.resolve({ shadowedSeqs: [1] })) },
1598
+ })
1599
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1600
+
1601
+ const notePath = handoffPathFor(root, 'session-fallback', 1)
1602
+ await requestStep(registered, agent, 2, 1)
1603
+ mkdirSync(join(root, 'session-fallback'), { recursive: true })
1604
+ writeFileSync(notePath, `# note\n${'x'.repeat(400)}`, 'utf8')
1605
+ const tool = registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
1606
+ assert.match(tool.execute({ path: notePath }, { agent }), /handoff registered/)
1607
+
1608
+ await idleBoundary(registered, agent)
1609
+
1610
+ assert.equal(folds.length, 1, 'the service channel must be reached after an unresolved /compact')
1611
+ assert.equal(agent.followed.length, 1, 'and the activation still happens')
1612
+ assert.ok(
1613
+ logs.some(([, message]) => String(message).includes('falling back to the compaction service')),
1614
+ 'the fallback is logged, not silent',
1615
+ )
1616
+ })
1617
+
1618
+ test('a refused /compact keeps the note, activates nothing, and warns', async (t) => {
1619
+ const root = scratchRoot(t)
1620
+ const { meter } = movableMeter(600000)
1621
+ const logs = []
1622
+ const commands = {
1623
+ execute: () => Promise.resolve({ commandId: 'cmd-1', result: { kind: 'error', text: 'session is busy' } }),
1624
+ }
1625
+ const agent = handoffAgent(handoffSession('session-refused'))
1626
+ const { ctx, registered } = stubContext({ meter, commands, logs })
1627
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1628
+
1629
+ const notePath = handoffPathFor(root, 'session-refused', 1)
1630
+ await requestStep(registered, agent, 2, 1)
1631
+ mkdirSync(join(root, 'session-refused'), { recursive: true })
1632
+ writeFileSync(notePath, `# note\n${'x'.repeat(400)}`, 'utf8')
1633
+ const tool = registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
1634
+ tool.execute({ path: notePath }, { agent })
1635
+
1636
+ await idleBoundary(registered, agent)
1637
+
1638
+ assert.equal(agent.followed.length, 0, 'a refusal must not activate a turn')
1639
+ const state = JSON.parse(readFileSync(join(root, 'session-refused', HANDOFF_STATE_FILE), 'utf8'))
1640
+ assert.equal(state.foldNo, 0)
1641
+ assert.equal(state.ready.path, notePath, 'the note survives for the next round end')
1642
+ assert.ok(
1643
+ logs.some(([level, message]) => level === 'warn' && String(message).includes('the fold did not commit')),
1644
+ 'the consequence is a warn, not an info line among the happy-path noise',
1645
+ )
1646
+ assert.ok(
1647
+ logs.some(([, message, , kind, text]) => String(message).includes('/compact did not fold') && kind === 'error' && text === 'session is busy'),
1648
+ 'the refusal kind and text are preserved',
1649
+ )
1650
+ })
1651
+
1526
1652
  test('a round that ends past the prep point wakes one reminder turn, bounded by the budget', async (t) => {
1527
1653
  const root = scratchRoot(t)
1528
1654
  const { box, meter } = movableMeter(600000)
@@ -1718,6 +1844,202 @@ test('a delegated session is never prepared, registered, or folded', async (t) =
1718
1844
  assert.equal(isDelegate(handoffSession('root', { depth: 0 })), false)
1719
1845
  })
1720
1846
 
1847
+ test('the delegate variant is off by default, and off means off', async (t) => {
1848
+ // 子代理变体是可选行为:默认配置下委派会话的提示词必须逐字节不变。
1849
+ const root = scratchRoot(t)
1850
+ const { meter } = movableMeter(630000)
1851
+ const agent = handoffAgent(handoffSession('session-child-off', { depth: 1 }))
1852
+ const { ctx, registered } = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1853
+
1854
+ assert.equal(DEFAULT_OPTIONS.subagentHandoff, false, 'a new behaviour ships off')
1855
+ assert.equal(resolveOptions({}).subagentHandoff, false)
1856
+ assert.equal(resolveOptions(Config({ subagentHandoff: true })).subagentHandoff, true, 'the form can turn it on')
1857
+
1858
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1859
+ await requestStep(registered, agent, 1)
1860
+ assert.equal(handoffBlock(registered, agent), '', 'the default config keeps a delegate silent')
1861
+ })
1862
+
1863
+ test('a delegate is reminded past the prep point, and its note file is the registration', async (t) => {
1864
+ const root = scratchRoot(t)
1865
+ const { box, meter } = movableMeter(620000)
1866
+ const folds = []
1867
+ const agent = handoffAgent(handoffSession('session-child-prep', { depth: 1 }))
1868
+ const { ctx, registered } = stubContext({
1869
+ meter,
1870
+ compaction: { compactNow: (...args) => (folds.push(args), Promise.resolve({})) },
1871
+ })
1872
+ apply(ctx, { foldMode: 'handoff', handoffDir: root, subagentHandoff: true })
1873
+
1874
+ const notePath = handoffPathFor(root, 'session-child-prep', 1)
1875
+ await requestStep(registered, agent, 1)
1876
+ const block = handoffBlock(registered, agent)
1877
+ assert.match(block, /handoff fold · subagent prepare/)
1878
+ assert.ok(block.includes(notePath), 'the one allowed path is spelled out')
1879
+ assert.match(block, /Writing the file is the whole registration/)
1880
+ assert.doesNotMatch(block, /follow-up turn is activated/, 'the root promise would be a lie for a child')
1881
+ assert.equal(agent.injected.length, 0, 'a delegate is never addressed as the human')
1882
+ assert.equal(agent.followed.length, 0, 'and never woken: its turns belong to whoever delegated it')
1883
+
1884
+ // 拒答也必须可执行:子会话没有 handed_ready 可用,要求调用等于把提醒变成死路。
1885
+ const tool = registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
1886
+ assert.match(tool.execute({}, { agent }), /writing the note file IS the registration/, 'a refused call says what to do instead')
1887
+
1888
+ // 写文件 = 登记。
1889
+ mkdirSync(join(root, 'session-child-prep'), { recursive: true })
1890
+ writeFileSync(notePath, `# note\n${'x'.repeat(400)}`, 'utf8')
1891
+ await requestStep(registered, agent, 1)
1892
+ assert.equal(handoffBlock(registered, agent), '', 'the note on disk ends the reminder')
1893
+ const state = JSON.parse(readFileSync(join(root, 'session-child-prep', HANDOFF_STATE_FILE), 'utf8'))
1894
+ assert.equal(state.ready.path, notePath)
1895
+ assert.equal(state.ready.used, 620000, 'the reading is kept as the fold baseline')
1896
+ assert.equal(state.reminders, 1)
1897
+
1898
+ // 待写的档已经在盘上:下一轮即使仍在准备点以上,也不能再发第二条提醒。
1899
+ box.used = 630000
1900
+ await requestStep(registered, agent, 2)
1901
+ assert.equal(handoffBlock(registered, agent), '', 'a pending note owns the next reminder slot')
1902
+
1903
+ await idleBoundary(registered, agent)
1904
+ assert.equal(folds.length, 0, 'nothing here folds a delegate')
1905
+ })
1906
+
1907
+ test('after the host folds a delegate, the next request points it back at its note', async (t) => {
1908
+ const root = scratchRoot(t)
1909
+ const { box, meter } = movableMeter(620000)
1910
+ const agent = handoffAgent(handoffSession('session-child-fold', { depth: 1 }))
1911
+ const { ctx, registered } = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1912
+ apply(ctx, { foldMode: 'handoff', handoffDir: root, subagentHandoff: true })
1913
+
1914
+ const notePath = handoffPathFor(root, 'session-child-fold', 1)
1915
+ await requestStep(registered, agent, 1)
1916
+ mkdirSync(join(root, 'session-child-fold'), { recursive: true })
1917
+ writeFileSync(notePath, `# note\n${'x'.repeat(400)}`, 'utf8')
1918
+ await requestStep(registered, agent, 1)
1919
+
1920
+ box.used = 210000
1921
+ await requestStep(registered, agent, 2)
1922
+ const block = handoffBlock(registered, agent)
1923
+ assert.match(block, /handoff fold · subagent, after the fold/)
1924
+ assert.ok(block.includes(notePath), 'the pointer names the file the child wrote')
1925
+ const state = JSON.parse(readFileSync(join(root, 'session-child-fold', HANDOFF_STATE_FILE), 'utf8'))
1926
+ assert.equal(state.foldNo, 1, 'the cycle is counted, so the next note is 002')
1927
+ assert.equal(state.ready, null)
1928
+ assert.equal(state.reminders, 0)
1929
+ assert.equal(agent.followed.length, 0, 'the pointer rides a turn the parent already caused; nothing is woken')
1930
+
1931
+ await requestStep(registered, agent, 2)
1932
+ assert.equal(handoffBlock(registered, agent), '', 'the pointer is one-shot, like every other block')
1933
+ })
1934
+
1935
+ test('a small drop is a trim, not a fold', async (t) => {
1936
+ // 只有当窗口被人重写过,reading 才会掉下来;掉 3% 是工具目录/defer 之类的小抖动,
1937
+ // 把它当折叠会让孩子去读一份它还不需要的档。
1938
+ const root = scratchRoot(t)
1939
+ const { box, meter } = movableMeter(620000)
1940
+ const agent = handoffAgent(handoffSession('session-child-trim', { depth: 1 }))
1941
+ const { ctx, registered } = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1942
+ apply(ctx, { foldMode: 'handoff', handoffDir: root, subagentHandoff: true })
1943
+
1944
+ const notePath = handoffPathFor(root, 'session-child-trim', 1)
1945
+ await requestStep(registered, agent, 1)
1946
+ mkdirSync(join(root, 'session-child-trim'), { recursive: true })
1947
+ writeFileSync(notePath, `# note\n${'x'.repeat(400)}`, 'utf8')
1948
+ await requestStep(registered, agent, 1)
1949
+
1950
+ box.used = 600000
1951
+ await requestStep(registered, agent, 2)
1952
+ assert.equal(handoffBlock(registered, agent), '', 'a reading below the prep point but not halved is not a fold')
1953
+ const state = JSON.parse(readFileSync(join(root, 'session-child-trim', HANDOFF_STATE_FILE), 'utf8'))
1954
+ assert.equal(state.foldNo, 0)
1955
+ assert.equal(state.ready.path, notePath, 'the note stays registered and waiting')
1956
+ })
1957
+
1958
+ test('a note found below the prep point after a restart still gets its pointer', async (t) => {
1959
+ // 状态里没有读数基线(旧版本写的,或选项刚打开),而读数已经在准备点以下:
1960
+ // 唯一合理的解释是折叠已经发生。不能因为“没有基线”就把孩子丢在摘要里。
1961
+ const root = scratchRoot(t)
1962
+ const dir = join(root, 'session-child-late')
1963
+ mkdirSync(dir, { recursive: true })
1964
+ const notePath = handoffPathFor(root, 'session-child-late', 1)
1965
+ writeFileSync(notePath, 'late note', 'utf8')
1966
+ writeFileSync(
1967
+ join(dir, HANDOFF_STATE_FILE),
1968
+ JSON.stringify({ version: 1, sessionId: 'session-child-late', foldNo: 0, ready: { path: notePath, chars: 9, at: 1 } }),
1969
+ 'utf8',
1970
+ )
1971
+ const { meter } = movableMeter(300000)
1972
+ const agent = handoffAgent(handoffSession('session-child-late', { depth: 1 }))
1973
+ const { ctx, registered } = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1974
+ apply(ctx, { foldMode: 'handoff', handoffDir: root, subagentHandoff: true })
1975
+
1976
+ await requestStep(registered, agent, 1)
1977
+ const block = handoffBlock(registered, agent)
1978
+ assert.match(block, /handoff fold · subagent, after the fold/)
1979
+ assert.ok(block.includes(notePath))
1980
+ const state = JSON.parse(readFileSync(join(dir, HANDOFF_STATE_FILE), 'utf8'))
1981
+ assert.equal(state.foldNo, 1)
1982
+ assert.equal(state.ready, null)
1983
+ })
1984
+
1985
+ test('after the fold the next note is numbered up, and the pointed-at note survives', async (t) => {
1986
+ const root = scratchRoot(t)
1987
+ const { box, meter } = movableMeter(620000)
1988
+ const agent = handoffAgent(handoffSession('session-child-numbered', { depth: 1 }))
1989
+ const { ctx, registered } = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1990
+ apply(ctx, { foldMode: 'handoff', handoffDir: root, subagentHandoff: true })
1991
+
1992
+ const first = handoffPathFor(root, 'session-child-numbered', 1)
1993
+ await requestStep(registered, agent, 1)
1994
+ mkdirSync(join(root, 'session-child-numbered'), { recursive: true })
1995
+ writeFileSync(first, `# note\n${'x'.repeat(400)}`, 'utf8')
1996
+ await requestStep(registered, agent, 1)
1997
+ box.used = 210000
1998
+ await requestStep(registered, agent, 2)
1999
+
2000
+ box.used = 630000
2001
+ await requestStep(registered, agent, 3)
2002
+ const block = handoffBlock(registered, agent)
2003
+ assert.ok(block.includes(handoffPathFor(root, 'session-child-numbered', 2)), 'the next note is 002')
2004
+ assert.equal(existsSync(first), true, 'the note the fold pointer aimed at is kept, exactly like an activation target')
2005
+ assert.equal(agent.followed.length, 0)
2006
+ })
2007
+
2008
+ test('delegate reminders are one per turn and capped per cycle, and never wake', async (t) => {
2009
+ const root = scratchRoot(t)
2010
+ const { meter } = movableMeter(640000)
2011
+ const logs = []
2012
+ const agent = handoffAgent(handoffSession('session-child-budget', { depth: 1 }))
2013
+ const { ctx, registered } = stubContext({ meter, logs, compaction: { compactNow: () => Promise.resolve({}) } })
2014
+ apply(ctx, { foldMode: 'handoff', handoffDir: root, subagentHandoff: true })
2015
+
2016
+ const reminded = []
2017
+ for (const turn of [1, 1, 2, 3, 4]) {
2018
+ await requestStep(registered, agent, turn)
2019
+ if (handoffBlock(registered, agent).includes('subagent prepare')) reminded.push(turn)
2020
+ }
2021
+ assert.deepEqual(reminded, [1, 2, 3], 'one per turn, three per cycle')
2022
+ assert.equal(agent.followed.length, 0, 'a delegate is never woken, whatever the budget says')
2023
+ assert.ok(
2024
+ logs.some(([, message]) => String(message).includes('delegate handoff reminder budget spent')),
2025
+ 'the budget stop is logged',
2026
+ )
2027
+ })
2028
+
2029
+ test('the delegate messages exist in both languages', () => {
2030
+ const trigger = { prepare: true, used: 620000, threshold: 727040, point: 618000, headroom: 107040 }
2031
+ const zh = handoffDelegatePrepMessage({ path: 'C:/x/001.handoff.md', trigger, recycled: 0, options: { language: 'zh' } })
2032
+ assert.match(zh, /子代理准备/)
2033
+ assert.ok(zh.includes('C:/x/001.handoff.md'))
2034
+ assert.match(zh, /文件本身就是登记/)
2035
+
2036
+ const en = handoffDelegatePrepMessage({ path: 'C:/x/001.handoff.md', trigger, recycled: 2, options: { language: 'en' } })
2037
+ assert.match(en, /recycled 2 older note file/)
2038
+
2039
+ assert.match(handoffDelegateFoldMessage({ path: 'C:/x/001.handoff.md', options: { language: 'zh' } }), /子代理折叠后/)
2040
+ assert.match(handoffDelegateFoldMessage({ path: 'C:/x/001.handoff.md', options: { language: 'en' } }), /subagent, after the fold/)
2041
+ })
2042
+
1721
2043
  test('the activation target survives the prep that hands out the next note', async (t) => {
1722
2044
  const root = scratchRoot(t)
1723
2045
  const dir = join(root, 'session-gc')