dsh-context-truth 0.3.0 → 0.3.2

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,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.2
4
+
5
+ * **注入行按模式说明真正的触发点。** 以前三种模式都只说"宿主自动压缩点 X"——在 `handoff` 下这是错的
6
+ 引导:模型看到 727K 会认为交接档可以晚点写。现在:
7
+ - `off`:只给宿主点(与旧输出逐字一致);
8
+ - `idle`:追加"本插件会在你的回合边界、余量进入 N(窗口的 foldAtIdleMarginPercent%)以内时折叠";
9
+ - `handoff`:追加"占用到 N(折叠点的 handoffAt%)时会提醒你写交接档,折叠在那一轮结束时执行"。
10
+ 三者都保留宿主点作为兜底。中英文都覆盖。
11
+ * README 顶部加 npm / license 徽章,顺序与 `dsh-multi-shell`、`dsh-superagent-panel` 一致
12
+ (标题 → 语言切换 → listed/npm/license 三枚徽章 → 摘要)。
13
+ * **准备提醒改走 runtime context,不再是一条用户消息。** `agent/request` 里只发布一段待渲染的提醒,
14
+ 由本插件注册的**独立**上下文块 `context-truth:handoff`(`order` = 占用行 + 1,自己的 `{{...}}`
15
+ 变量)在**同一个请求**里渲染成 `<system-reminder>` 快照;下一个请求先退役它再决策,所以仍然是
16
+ “每轮最多一次”。没有提醒时该变量渲染成空串,宿主会整段过滤掉,快照与以前逐字相同。
17
+ - 时序更早:`agent/request` 在同一步的上下文刷新之前触发,不必等下一次请求(`agent.inject` 是排队)。
18
+ - 不再伪装成用户发言:`source.kind` 是 `runtime-context` 而不是 `user`,对话里不留气泡。
19
+ - 轮末唤醒仍然用 `followup`:动态上下文只有在真的发生请求时才会被读到,唤醒必须开一轮。
20
+ * 测试:73(新增“提醒是独立块 / 占用行不被污染 / off 与 idle 不渲染该块”与“实时切模式”用例;
21
+ 三处变异分别失败 3 / 4 / 5 例,独立块的两处变异分别失败 1 / 6 例)。
22
+
23
+ ## 0.3.1
24
+
25
+ * **`handoff_ready` 只在 `handoff` 模式下注册。** `off` / `idle` 下它从工具目录里移除(用
26
+ `tools.register()` 返回的注销 disposer),切回 handoff 时在**下一个请求**重新注册;插件被销毁时
27
+ 也会注销。`off` / `idle` 的工具目录与没有这个能力时完全一致,不再为首轮 prefill 承担一个
28
+ 永远只会拒绝的工具定义。
29
+ * 日志分别记 `handoff_ready registered (fold mode is handoff)` /
30
+ `handoff_ready removed (fold mode is <mode>)`,模式切换在日志里可见。
31
+ * 测试:70(新增“工具跟随实时模式”用例;变异“去掉注销调用”恰好只让它失败,恢复后字节一致)。
32
+
3
33
  ## 0.3.0
4
34
 
5
35
  > **新增能力 3 的第二形态:交接式折叠(`foldMode: handoff`,实验性)。** 默认模式改为 `idle`
package/README-en.md CHANGED
@@ -2,9 +2,13 @@
2
2
 
3
3
  [English](README-en.md) · [简体中文](README.md)
4
4
 
5
+ [![Listed on dsh-plugin.org](https://dsh-plugin.org/badges/listed.svg)](https://dsh-plugin.org/plugins/deepseekv41flash/dsh-context-truth)
6
+ [![npm](https://img.shields.io/npm/v/dsh-context-truth.svg)](https://www.npmjs.com/package/dsh-context-truth)
7
+ [![license](https://img.shields.io/npm/l/dsh-context-truth.svg)](./LICENSE)
8
+
5
9
  > Give the model its **real** context occupancy — measured by the host and re-injected every turn — and stop the false claim "context is nearly exhausted" from surviving compaction.
6
10
 
7
- A DSH (DeepSeek Harness) plugin · one peer dependency (the host's own `schemastery`) · needs the host services `tokenMeter` and `compaction` (both shipped by `dsh-base`) · 1 tool (`handoff_ready`, used by handoff folding) · 1 client settings card · no build step · MIT
11
+ A DSH (DeepSeek Harness) plugin · one peer dependency (the host's own `schemastery`) · needs the host services `tokenMeter` and `compaction` (both shipped by `dsh-base`) · 1 tool in handoff mode (`handoff_ready`) · 1 client settings card · no build step · MIT
8
12
 
9
13
  ---
10
14
 
@@ -89,18 +93,20 @@ the reading parked at "Under 10K tokens of headroom remain"
89
93
 
90
94
  > Compatibility: a config that never set `foldMode` resolves to `idle` (that is the behaviour this plugin always had, behind `foldAtIdle: true`); a config that explicitly set `foldAtIdle: false` still resolves to `off` and is not dragged along by the new default. An explicit `foldMode` always wins.
91
95
 
96
+ The injected occupancy line names **the active mode's own trigger**, not just the host's pressure point: `off` keeps the host point alone; `idle` adds "This plugin folds at your own turn boundary once the headroom comes within 52K"; `handoff` adds "Handoff folding: at 618K (85% of the fold point) you are reminded to write the handoff note; the fold runs at the end of that round". All three keep the host point as the backstop.
97
+
92
98
  #### Handoff folding (`handoff`, experimental)
93
99
 
94
100
  What actually costs a long task is not the summary but **the repeated work after the fold**: the model cannot know when it will be folded, then rebuilds its picture from the summary and redoes what it already did. Baseline (143 folds): **81 folds (57%) were followed by the model re-reading a file it had just written, 225 occurrences**.
95
101
 
96
102
  The chain is:
97
103
 
98
- 1. At the **prep point** (`handoffAt` × the fold point, 85% by default) the plugin injects a reminder naming the **one** allowed note path (`$DSH_HOME/handoffs/<sessionId>/<fold#>.handoff.md`, never the workspace);
104
+ 1. At the **prep point** (`handoffAt` × the fold point, 85% by default) the plugin writes a reminder into the session's **runtime context** (its own `systemPrompt` contribution named `context-truth:handoff`, rendered to the model as a `<system-reminder>` block) naming the **one** allowed note path (`$DSH_HOME/handoffs/<sessionId>/<fold#>.handoff.md`, never the workspace). It renders in exactly the request that published it and is retired before the next request decides anything, so it never poses as a user message, leaves no bubble in the transcript, and is more timely than a queued message (`agent/request` fires before the step's context refresh);
99
105
  2. the model writes everything the post-fold self needs (goal, settled decisions, evidence, next action, dead ends) and calls `handoff_ready`;
100
106
  3. at the end of that round the plugin calls `compactNow()`;
101
107
  4. after the fold it uses `followup` to activate **exactly one** turn whose first instruction is to read that note before touching the task.
102
108
 
103
- 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` to deliver the reminder (`agent.inject` only queues for the next request, so a reminder that lands on the model's last step would otherwise wait for a human — measured, and that is why the wake exists); 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.
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` to deliver the reminder (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); 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.
104
110
 
105
111
  **Switching modes takes effect immediately, with no restart**: `foldMode` is volatile config, the settings card writes straight into the running reference, and the plugin resolves its options per use (verified live: after the panel switched to `handoff`, the running instance acted on it on its next call). Switching does **not** trigger a fold by itself — the fold still waits for the reading to reach the point.
106
112
 
@@ -207,13 +213,13 @@ What you get for it: the model stops halting or handing off because it *thinks*
207
213
  * If an agent preset sets `includeRuntimeContext: false` (for example `liangshen`), the runtime suppresses **every** runtime-context contribution and capability 1 does not apply (capability 2 is unaffected).
208
214
  * If a host froze the request envelope (**this version does not** — verified by capturing a real compaction request), capability 2 logs one warning and skips — it never breaks a model call. That warning is reserved for the engine's own tagged call, so a look-alike request can never silence a later real failure.
209
215
  * **Mounting twice in one scope does not fail**: bundle assembly plus a runtime injection are two assembly paths for the same plugin; the second instance detects the taken name, stays silent (one `info` line) and the first keeps serving — it never becomes a failed plugin row.
210
- * The plugin registers **one tool**, `handoff_ready` (register a handoff note). It is in the catalog in every mode so the settings card can switch modes at any time, but it costs nothing unless called; only handoff mode calls it. It is still one tool definition in the first-turn prefill — the only change this plugin makes to the tool catalog. Folding itself never goes through a model tool call (the plugin calls `compaction.compactNow()` directly), so in `off` / `idle` modes the model sees no folding activity at all.
216
+ * The plugin registers **one tool only in `handoff` mode**: `handoff_ready` (register a handoff note). In `off` / `idle` it is removed from the tool catalog again, so the catalog is exactly what a deployment without this capability has; a switch lands on the **next request** (the plugin reconciles inside `agent/request` through the disposer `tools.register()` returns). Folding itself never goes through a model tool call (the plugin calls `compaction.compactNow()` directly), so in `off` / `idle` modes the model sees neither the tool nor any folding activity.
211
217
  * The plugin ships **one client module** (`lib/client.js`, the settings card). It only reads `settings.describe()` and writes `settings.mutate()`; it touches no workspace and makes no network requests.
212
218
 
213
219
  ## Verify
214
220
 
215
221
  ```sh
216
- npm test # 69 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
222
+ npm test # 73 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
217
223
  ```
218
224
 
219
225
  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
@@ -1,12 +1,14 @@
1
1
  # dsh-context-truth
2
2
 
3
- [![Listed on dsh-plugin.org](https://dsh-plugin.org/badges/listed.svg)](https://dsh-plugin.org/plugins/deepseekv41flash/dsh-context-truth)
4
-
5
3
  [English](README-en.md) · [简体中文](README.md)
6
4
 
5
+ [![Listed on dsh-plugin.org](https://dsh-plugin.org/badges/listed.svg)](https://dsh-plugin.org/plugins/deepseekv41flash/dsh-context-truth)
6
+ [![npm](https://img.shields.io/npm/v/dsh-context-truth.svg)](https://www.npmjs.com/package/dsh-context-truth)
7
+ [![license](https://img.shields.io/npm/l/dsh-context-truth.svg)](./LICENSE)
8
+
7
9
  > 让模型知道自己**真实的**上下文占用——每轮由宿主实测回填,并且不让"上下文快用完了"这句错话被压缩摘要继承下去。
8
10
 
9
- DSH(DeepSeek Harness)插件 · 单一 peer 依赖(宿主自带的 `schemastery`)· 需要宿主服务 `tokenMeter` 与 `compaction`(标准部署的 `dsh-base` 自带)· 1 个工具(`handoff_ready`,交接式折叠用)· 1 个客户端设置卡片 · 免构建 · MIT
11
+ DSH(DeepSeek Harness)插件 · 单一 peer 依赖(宿主自带的 `schemastery`)· 需要宿主服务 `tokenMeter` 与 `compaction`(标准部署的 `dsh-base` 自带)· handoff 模式下 1 个工具(`handoff_ready`)· 1 个客户端设置卡片 · 免构建 · MIT
10
12
 
11
13
  ---
12
14
 
@@ -136,6 +138,10 @@ this in as few commands as possible, then a short answer."。数字它读对了
136
138
  > 兼容性:没写过 `foldMode` 的旧配置按 `idle` 处理(它就是本插件此前的行为,当时由 `foldAtIdle: true` 打开);
137
139
  > 显式写过 `foldAtIdle: false` 的配置仍然解析成 `off`,不会被这次改默认值带走。显式 `foldMode` 永远优先。
138
140
 
141
+ 注入的占用行会说明**当前模式真正的触发点**,而不只是宿主的压力点:`off` 只给宿主自动压缩点;
142
+ `idle` 追加"本插件会在回合边界、余量进入 52K(窗口的 5%)以内时折叠";`handoff` 追加"占用到 618K
143
+ (折叠点的 85%)时会提醒你写交接档,折叠在那一轮结束时执行"。三者都保留宿主点作为兜底。
144
+
139
145
  #### 交接式折叠(`handoff`,实验性)
140
146
 
141
147
  长任务真正贵的不是摘要本身,而是**折叠后的重复劳动**:模型不知道什么时候会被折,折叠后又
@@ -144,16 +150,19 @@ this in as few commands as possible, then a short answer."。数字它读对了
144
150
 
145
151
  这条链路是:
146
152
 
147
- 1. 读数到达**准备点**(`handoffAt` × 折叠点,默认 85%)时,插件往本会话注入一条提醒,给出**唯一**
148
- 允许的交接档路径(`$DSH_HOME/handoffs/<sessionId>/<fold#>.handoff.md`,绝不写进工作区);
153
+ 1. 读数到达**准备点**(`handoffAt` × 折叠点,默认 85%)时,插件把一条提醒写进本会话的 **runtime context**
154
+ (本插件注册的独立上下文块 `context-truth:handoff`,模型侧渲染成 `<system-reminder>` 快照),给出**唯一**允许的交接档路径
155
+ (`$DSH_HOME/handoffs/<sessionId>/<fold#>.handoff.md`,绝不写进工作区)。它只在发布它的那个请求里
156
+ 渲染一次,下一个请求先退役再决策——所以它既不伪装成用户发言,也不在对话里留一条气泡,时序还比排队
157
+ 消息更早(`agent/request` 在同一步的上下文刷新之前触发);
149
158
  2. 模型把"折叠后的自己需要知道的一切"写进这份档(目标、已定案、证据、下一步、走过的死路),
150
159
  然后调用 `handoff_ready` 登记;
151
160
  3. 这一轮结束时插件调用 `compactNow()` 真正折叠;
152
161
  4. 折叠后插件用 `followup` **只自动激活一轮**,第一条指令就是"先读这份档,再从它的下一步继续"。
153
162
 
154
163
  护栏:提醒每周期最多 3 次;某个回合结束时如果模型还没登记、但已过准备点,插件会用
155
- `followup` **唤醒**一轮把提醒送到(`agent.inject` 只排进下一次请求,轮次结束时没人再发请求,
156
- 提醒就会一直等人类开口——实测踩过);交接档是临时文件,下一次交接生成时回收旧的、7 天兜底清理;
164
+ `followup` **唤醒**一轮把提醒送到(动态上下文只有在真的发生请求时才会被模型读到,轮次结束就没人
165
+ 再发请求,提醒会一直等人类开口——实测踩过);交接档是临时文件,下一次交接生成时回收旧的、7 天兜底清理;
157
166
  登记了档但没折成(引擎拒绝、被别的东西先折了)时不会激活,档保留。
158
167
 
159
168
  **切换模式立即生效,不需要重启**:`foldMode` 是 volatile 配置,设置卡直接写进运行中的引用,
@@ -283,17 +292,18 @@ runtime-context 快照**字节不变就不会重发**,所以读数按台阶量
283
292
  * **同一作用域挂载两次不会失败**:bundle 装配 + 运行时注入是同一插件的两条装配路径,
284
293
  第二个实例检测到重名后保持静默(只记一条 info),由第一个实例继续服务——不会变成
285
294
  一行 failed 的插件记录。
286
- * 本插件注册 **1 个工具**:`handoff_ready`(交接档登记)。它在所有模式下都会出现在工具目录里
287
- (设置卡需要能随时切换模式),不产生额外调用;只有 handoff 模式会用它。工具定义很小,但仍算
288
- **一次首轮 prefill** 的成本——这是本插件唯一改工具目录的地方。折叠本身不经过模型工具调用
289
- (插件直接调 `compaction.compactNow()`),所以 `off`/`idle` 模式下模型侧看不到任何折叠活动。
295
+ * 本插件**只在 `handoff` 模式下注册 1 个工具**:`handoff_ready`(交接档登记)。
296
+ `off` / `idle` 下它会从工具目录里移除,工具目录与没有这个能力时完全一致;切换在**下一个请求**生效
297
+ (插件在 `agent/request` 里对账,用的是 `tools.register()` 返回的注销 disposer)。
298
+ 折叠本身不经过模型工具调用(插件直接调 `compaction.compactNow()`),所以 `off`/`idle` 模式下
299
+ 模型侧看不到任何折叠活动,也没有这个工具。
290
300
  * 本插件带 **1 个客户端模块**(`lib/client.js`,插件页的设置卡)。它只读 `settings.describe()`、
291
301
  写 `settings.mutate()`,不碰工作区、不发网络请求。
292
302
 
293
303
  ## 验证
294
304
 
295
305
  ```sh
296
- npm test # 69 项单测:分档/迟滞/量化/自由窗口/折叠定义/空闲折叠与护栏/配置热更新/schema 默认值一致性/节奏估算/降级/摘要改写/形似请求排除/幂等/交接式折叠(提醒、登记、轮末折叠、单次激活、重启恢复、回收、轮末唤醒)/客户端设置卡结构
306
+ npm test # 73 项单测:分档/迟滞/量化/自由窗口/折叠定义/空闲折叠与护栏/配置热更新/schema 默认值一致性/节奏估算/降级/摘要改写/形似请求排除/幂等/交接式折叠(提醒、登记、轮末折叠、单次激活、重启恢复、回收、轮末唤醒)/客户端设置卡结构/交接提醒走 runtime context 而非消息,以及实时切模式后提醒随模式消失
297
307
  ```
298
308
 
299
309
  装好后开一个新会话发一条消息,展开该轮的 runtime context 块应看到
package/lib/index.js CHANGED
@@ -85,6 +85,17 @@ export const CONTEXT_NAME = 'context-truth'
85
85
  /** Prompt variable carrying the rendered line. */
86
86
  export const VARIABLE_NAME = 'context_occupancy'
87
87
 
88
+ /**
89
+ * The handoff reminder gets its own context contribution, so the snapshot shows
90
+ * it as a separate block instead of growing the occupancy line. It renders empty
91
+ * (and therefore contributes nothing at all) except on the one request that
92
+ * carries a prepared reminder.
93
+ */
94
+ export const HANDOFF_CONTEXT_NAME = 'context-truth:handoff'
95
+
96
+ /** Prompt variable carrying the handoff reminder, or an empty string. */
97
+ export const HANDOFF_VARIABLE_NAME = 'context_truth_handoff'
98
+
88
99
  /**
89
100
  * Services that must be wired before this plugin can act.
90
101
  *
@@ -989,6 +1000,29 @@ function render(band, reading, options) {
989
1000
  ? ` 自动压缩阈值 ${formatTokens(reading.threshold)}(窗口的 ${percentOf(reading.threshold, reading.window)}%)。`
990
1001
  : ` Automatic compaction fires at ${formatTokens(reading.threshold)} (${percentOf(reading.threshold, reading.window)}% of the window).`
991
1002
  : ''
1003
+ // What THIS deployment will actually do — the deadline the model has to plan
1004
+ // around. Without it the line named only the host's pressure point even in
1005
+ // `handoff` mode, where the actionable deadline is the earlier prep point (a
1006
+ // model reading "727K" reasonably concluded the handoff note could wait).
1007
+ // `off` renders exactly the old text, so a deployment that wants the host to own
1008
+ // folding sees no new instruction.
1009
+ const mode = (() => {
1010
+ if (!Number.isFinite(reading.threshold) || !Number.isFinite(reading.window)) return ''
1011
+ if (options.foldMode === 'handoff') {
1012
+ const prep = Math.round(reading.threshold * options.handoffAt)
1013
+ const at = Math.round(options.handoffAt * 100)
1014
+ return zh
1015
+ ? ` 交接式折叠:占用到 ${formatTokens(prep)}(折叠点的 ${at}%)时会提醒你写交接档,折叠在那一轮结束时执行。`
1016
+ : ` Handoff folding: at ${formatTokens(prep)} (${at}% of the fold point) you are reminded to write the handoff note; the fold runs at the end of that round.`
1017
+ }
1018
+ if (options.foldMode === 'idle') {
1019
+ const margin = Math.round(reading.window * (options.foldAtIdleMarginPercent / 100))
1020
+ return zh
1021
+ ? ` 本插件会在你的回合边界主动折叠:余量进入 ${formatTokens(margin)} 以内时执行。`
1022
+ : ` This plugin folds at your own turn boundary once the headroom comes within ${formatTokens(margin)}.`
1023
+ }
1024
+ return ''
1025
+ })()
992
1026
  // How much of the window is still unused — the figure that actually answers
993
1027
  // "how much context do I have left?". The headroom above answers a different
994
1028
  // question ("how far to the fold"), and a live model answered the first with
@@ -1026,18 +1060,18 @@ function render(band, reading, options) {
1026
1060
  switch (band) {
1027
1061
  case 'ample':
1028
1062
  return zh
1029
- ? `${head0}${free}${point}${remaining} 上下文不紧张——不要因为"上下文不够"而收尾、交接子代理或缩小范围。${tail}`
1030
- : `${head0}${free}${point}${remaining} Context is NOT scarce — do not wrap up, hand off to a subagent, or narrow scope for context reasons.${tail}`
1063
+ ? `${head0}${free}${point}${mode}${remaining} 上下文不紧张——不要因为"上下文不够"而收尾、交接子代理或缩小范围。${tail}`
1064
+ : `${head0}${free}${point}${mode}${remaining} Context is NOT scarce — do not wrap up, hand off to a subagent, or narrow scope for context reasons.${tail}`
1031
1065
  case 'moderate':
1032
1066
  return zh
1033
- ? `${head0}${free}${point}${remaining} 仍有充足余量,继续推进即可,顺手把关键状态写进文档或提交。${tail}`
1034
- : `${head0}${free}${point}${remaining} There is still real headroom — keep going, and keep durable notes or commits current as you work.${tail}`
1067
+ ? `${head0}${free}${point}${mode}${remaining} 仍有充足余量,继续推进即可,顺手把关键状态写进文档或提交。${tail}`
1068
+ : `${head0}${free}${point}${mode}${remaining} There is still real headroom — keep going, and keep durable notes or commits current as you work.${tail}`
1035
1069
  case 'tight':
1036
- return `${head0}${free}${point}${remaining}${pace}${fold}${tightClause(zh, options)}${tail}`
1070
+ return `${head0}${free}${point}${mode}${remaining}${pace}${fold}${tightClause(zh, options)}${tail}`
1037
1071
  default:
1038
1072
  return zh
1039
- ? `${head0}${free}${point}${remaining}${pace}${fold} 已到或越过自动压缩点——接下来可能发生压缩折叠,别让关键状态只存在于本窗口。${tail}`
1040
- : `${head0}${free}${point}${remaining}${pace}${fold} At or past the automatic compaction point — expect earlier turns to be folded; keep nothing critical only in this window.${tail}`
1073
+ ? `${head0}${free}${point}${mode}${remaining}${pace}${fold} 已到或越过自动压缩点——接下来可能发生压缩折叠,别让关键状态只存在于本窗口。${tail}`
1074
+ : `${head0}${free}${point}${mode}${remaining}${pace}${fold} At or past the automatic compaction point — expect earlier turns to be folded; keep nothing critical only in this window.${tail}`
1041
1075
  }
1042
1076
  }
1043
1077
 
@@ -1171,9 +1205,20 @@ export function apply(ctx, config) {
1171
1205
  backendIdentity(compactionService),
1172
1206
  )
1173
1207
 
1208
+ // Handoff prep travels as runtime context, not as a message.
1209
+ //
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.
1217
+ const handoffNotices = new Map()
1218
+
1174
1219
  if (resolve().enabled) {
1175
1220
  try {
1176
- installContextLine(ctx, resolve, services)
1221
+ installContextLine(ctx, resolve, services, handoffNotices)
1177
1222
  } catch (error) {
1178
1223
  if (isAlreadyRegistered(error)) {
1179
1224
  const logger = ctx.logger
@@ -1188,7 +1233,7 @@ export function apply(ctx, config) {
1188
1233
 
1189
1234
  installCompactionPatch(ctx, resolve)
1190
1235
  installIdleFold(ctx, resolve, services)
1191
- installHandoffFold(ctx, resolve, services)
1236
+ installHandoffFold(ctx, resolve, services, handoffNotices)
1192
1237
  }
1193
1238
 
1194
1239
  /** Whether a registration failed because the name is already taken in this layer. */
@@ -1804,8 +1849,11 @@ function sweepHandoffs(root, nowMs, maxAgeMs) {
1804
1849
  /**
1805
1850
  * Install the handoff fold: prep reminder, `handoff_ready`, the round-end fold, the
1806
1851
  * single activation turn, and the recycling that keeps the directory bounded.
1852
+ *
1853
+ * `notices` is the runtime-context delivery channel shared with `installContextLine`:
1854
+ * the prep reminder is published there instead of being queued as a user message.
1807
1855
  */
1808
- function installHandoffFold(ctx, resolve, services) {
1856
+ function installHandoffFold(ctx, resolve, services, notices) {
1809
1857
  /** Per-session state, hydrated from disk on first use and mirrored back on change. */
1810
1858
  const states = new Map()
1811
1859
  /** One-shot log keys: a condition that recurs every step is reported once. */
@@ -1849,12 +1897,19 @@ function installHandoffFold(ctx, resolve, services) {
1849
1897
  */
1850
1898
  function prepare(agent, turn) {
1851
1899
  const options = resolve()
1900
+ // The tool catalog follows the mode even for a session this scope does not
1901
+ // remind (a delegate, an unnamed session): `off`/`idle` must never advertise a
1902
+ // tool the mode cannot honour.
1903
+ syncHandoffTool(options)
1852
1904
  if (options.foldMode !== 'handoff') return
1853
1905
  const session = agent === null || agent === undefined ? undefined : agent.session
1854
1906
  if (session === null || session === undefined) return
1855
1907
  if (isDelegate(session)) return
1856
1908
  const sessionId = sessionIdOf(session)
1857
1909
  if (sessionId === '') return
1910
+ // Retire the previous request's notice before this request decides anything,
1911
+ // so the paragraph is rendered exactly once (see `handoffNotices` in `apply`).
1912
+ notices.delete(sessionId)
1858
1913
  const state = stateFor(options, sessionId)
1859
1914
  // A wake already carries this round's reminder as its first user message; a
1860
1915
  // second inject would stack two copies of it in the same round.
@@ -1893,14 +1948,13 @@ function installHandoffFold(ctx, resolve, services) {
1893
1948
  // (实测:删掉编号守卫,67/67 仍全绿,因为 pending 守卫替它挡了)。
1894
1949
  const keep = [path, handoffPathFor(root, sessionId, state.foldNo)]
1895
1950
  const doomed = handoffReapable(root, sessionId, keep)
1896
- try {
1897
- // Reap after the reminder lands, so a failed inject does not cost the model
1898
- // its previous note for nothing.
1899
- agent.inject(handoffMessage(handoffPrepMessage({ path, trigger, recycled: doomed.length, options })))
1900
- } catch (error) {
1901
- logLine(ctx, 'warn', 'context-truth: could not inject the handoff reminder for %s: %s', sessionId, messageOf(error))
1902
- return
1903
- }
1951
+ // Publish the reminder into runtime context instead of queueing a user
1952
+ // message: the same request renders it (the loop refreshes the dynamic
1953
+ // context right after this waterfall), so it is as timely as `inject` and
1954
+ // never looks like something the human typed.
1955
+ notices.set(sessionId, handoffPrepMessage({ path, trigger, recycled: doomed.length, options }))
1956
+ // Reap after the notice lands, so a failed delivery does not cost the model
1957
+ // its previous note for nothing.
1904
1958
  const recycled = deleteFiles(doomed)
1905
1959
  state.reminders += 1
1906
1960
  state.reminderTurn = turn === undefined ? null : turn
@@ -2230,11 +2284,16 @@ function installHandoffFold(ctx, resolve, services) {
2230
2284
  }
2231
2285
  }
2232
2286
 
2233
- // The tool exists in every mode: the settings form toggles `foldMode` live, and a
2234
- // tool that only appears after a reload would leave handoff mode unrunnable on the
2235
- // very session that just turned it on. Its description is one line for that reason.
2287
+ // The handoff tool follows the live `foldMode`: `tools.register()` returns the
2288
+ // disposer that unregisters it, so `off`/`idle` deployments carry no extra tool
2289
+ // at all instead of shipping a definition whose body always refuses. The initial
2290
+ // state is reconciled here, and every `prepare` (one per request) keeps it in
2291
+ // step after a settings change.
2236
2292
  const tools = safeGet(ctx, 'tools')
2237
- if (tools === undefined || typeof tools.register !== 'function' || typeof ctx.effect !== 'function') {
2293
+ const toolsUsable = tools !== undefined && typeof tools.register === 'function'
2294
+ let toolDisposer = null
2295
+
2296
+ if (!toolsUsable) {
2238
2297
  logLine(
2239
2298
  ctx,
2240
2299
  'warn',
@@ -2242,13 +2301,50 @@ function installHandoffFold(ctx, resolve, services) {
2242
2301
  HANDOFF_TOOL_NAME,
2243
2302
  )
2244
2303
  } else {
2304
+ // Mode switching is not the only way the row goes away: a reload or a disposed
2305
+ // fiber must not leave the registration behind.
2306
+ ctx.effect(
2307
+ () => () => {
2308
+ if (toolDisposer === null) return
2309
+ const dispose = toolDisposer
2310
+ toolDisposer = null
2311
+ dispose()
2312
+ },
2313
+ `context-truth: ${HANDOFF_TOOL_NAME} cleanup`,
2314
+ )
2315
+ }
2316
+
2317
+ /**
2318
+ * Register the handoff tool only while the fold mode is `handoff`.
2319
+ *
2320
+ * `tools.register()` returns the exact disposer that unregisters the tool
2321
+ * (`dsh-tools` `register()`), so the tool can follow a live `foldMode` without a
2322
+ * reload. Reconciled from `prepare`, which runs inside the `agent/request`
2323
+ * waterfall, so a switch lands on the next request rather than the next process.
2324
+ *
2325
+ * @param options - resolved options for this call.
2326
+ */
2327
+ function syncHandoffTool(options) {
2328
+ if (!toolsUsable) return
2329
+ const want = options.foldMode === 'handoff'
2330
+ if (want === (toolDisposer !== null)) return
2245
2331
  try {
2246
- ctx.effect(() => tools.register(toolDefinition()), `context-truth: ${HANDOFF_TOOL_NAME}`)
2332
+ if (want) {
2333
+ toolDisposer = tools.register(toolDefinition())
2334
+ logLine(ctx, 'info', 'context-truth: %s registered (fold mode is handoff)', HANDOFF_TOOL_NAME)
2335
+ } else {
2336
+ const dispose = toolDisposer
2337
+ toolDisposer = null
2338
+ dispose()
2339
+ logLine(ctx, 'info', 'context-truth: %s removed (fold mode is %s)', HANDOFF_TOOL_NAME, options.foldMode)
2340
+ }
2247
2341
  } catch (error) {
2248
- logLine(ctx, 'warn', 'context-truth: could not register %s: %s', HANDOFF_TOOL_NAME, messageOf(error))
2342
+ logLine(ctx, 'warn', 'context-truth: could not sync %s with the fold mode: %s', HANDOFF_TOOL_NAME, messageOf(error))
2249
2343
  }
2250
2344
  }
2251
2345
 
2346
+ syncHandoffTool(resolve())
2347
+
2252
2348
  // Prep runs inside a waterfall: synchronous, and it must never throw — its return
2253
2349
  // value is the model call's configuration.
2254
2350
  ctx.on('agent/request', (payload, next) => {
@@ -2292,7 +2388,7 @@ function installHandoffFold(ctx, resolve, services) {
2292
2388
  }
2293
2389
 
2294
2390
  /** Install the dynamic runtime-context line. */
2295
- function installContextLine(ctx, resolve, services) {
2391
+ function installContextLine(ctx, resolve, services, notices) {
2296
2392
  /** Last band published per session (hysteresis memory); never rendered. */
2297
2393
  const bands = new WeakMap()
2298
2394
  /** Per-session pace state for the headroom estimate; never rendered raw. */
@@ -2300,6 +2396,21 @@ function installContextLine(ctx, resolve, services) {
2300
2396
  /** Last text handed out, so a failed read degrades to the previous line. */
2301
2397
  let lastText = renderUnknown(resolve())
2302
2398
 
2399
+ /**
2400
+ * The handoff reminder as its own runtime-context block.
2401
+ *
2402
+ * A separate contribution (rather than text appended to the occupancy line) is
2403
+ * what makes it show up as its own block in the snapshot, and because an empty
2404
+ * text is filtered out by the host's `renderContextSections`, "no reminder" is
2405
+ * literally "no section" — the snapshot is byte-identical to before.
2406
+ */
2407
+ const handoffNotice = (assembly) => {
2408
+ if (resolve().foldMode !== 'handoff') return ''
2409
+ const sessionId = sessionIdOf(assembly?.agent?.session)
2410
+ if (sessionId === '') return ''
2411
+ return notices.get(sessionId) ?? ''
2412
+ }
2413
+
2303
2414
  const line = (assembly) => {
2304
2415
  // Resolved per assembly, so a settings change shows up on the next prompt.
2305
2416
  const options = resolve()
@@ -2419,6 +2530,21 @@ function installContextLine(ctx, resolve, services) {
2419
2530
  }),
2420
2531
  'context-truth: runtime-context section',
2421
2532
  )
2533
+ bind(
2534
+ () => ctx.systemPrompt.variable(HANDOFF_VARIABLE_NAME, (assembly) => handoffNotice(assembly)),
2535
+ 'context-truth: handoff variable',
2536
+ )
2537
+ bind(
2538
+ () =>
2539
+ ctx.systemPrompt.context({
2540
+ name: HANDOFF_CONTEXT_NAME,
2541
+ // Right after the occupancy line, and fixed for the same reason: the block
2542
+ // only changes when a reminder is published, never by reordering.
2543
+ order: resolve().order + 1,
2544
+ text: `{{${HANDOFF_VARIABLE_NAME}}}`,
2545
+ }),
2546
+ 'context-truth: handoff section',
2547
+ )
2422
2548
  }
2423
2549
 
2424
2550
  /** Test-only surface: the pure helpers, so the suite can exercise them directly. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-context-truth",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
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",
@@ -4,7 +4,7 @@ import { homedir, tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
5
  import test from 'node:test'
6
6
 
7
- import { apply, internals, name, inject, Config, CONTEXT_NAME, VARIABLE_NAME } from '../lib/index.js'
7
+ import { apply, internals, name, inject, Config, CONTEXT_NAME, VARIABLE_NAME, HANDOFF_CONTEXT_NAME, HANDOFF_VARIABLE_NAME } from '../lib/index.js'
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
 
@@ -18,16 +18,24 @@ const THRESHOLD = 678464
18
18
 
19
19
  /** Minimal ctx capturing what the plugin registers. */
20
20
  function stubContext({ used, meter, projections, compaction, commands, logs, tools } = {}) {
21
- const registered = { variable: undefined, context: undefined, listeners: {}, injections: [], tools: [], effects: [], timers: [] }
21
+ const registered = { variable: undefined, context: undefined, variables: {}, contexts: {}, listeners: {}, injections: [], tools: [], effects: [], disposers: [], timers: [] }
22
22
  const tokenMeter = meter === undefined ? { measure: () => ({ totalTokens: used }) } : meter
23
23
  // A host always mounts the tools service, so the stub does too: without it the
24
24
  // handoff tool cannot register and every log assertion would see that warning.
25
+ // `register` returns the disposer a real host returns, so a test can observe the
26
+ // tool following a live fold-mode switch.
25
27
  const toolsService =
26
28
  tools === undefined
27
29
  ? {
28
30
  register: (definition) => {
29
31
  registered.tools.push(definition)
30
- return () => {}
32
+ let live = true
33
+ return () => {
34
+ if (!live) return
35
+ live = false
36
+ const index = registered.tools.indexOf(definition)
37
+ if (index >= 0) registered.tools.splice(index, 1)
38
+ }
31
39
  },
32
40
  }
33
41
  : tools
@@ -59,11 +67,16 @@ function stubContext({ used, meter, projections, compaction, commands, logs, too
59
67
  if (ready) callback(child)
60
68
  },
61
69
  systemPrompt: {
70
+ // The plugin registers two contributions (the occupancy line and the handoff
71
+ // reminder). `variable` / `context` keep pointing at the first registration so
72
+ // every existing assertion still reads the occupancy line.
62
73
  variable: (variableName, provider) => {
63
- registered.variable = { name: variableName, provider }
74
+ registered.variables[variableName] = { name: variableName, provider }
75
+ registered.variable ??= registered.variables[variableName]
64
76
  },
65
77
  context: (contribution) => {
66
- registered.context = contribution
78
+ registered.contexts[contribution.name] = contribution
79
+ registered.context ??= contribution
67
80
  },
68
81
  },
69
82
  // Two capabilities now share `agent/status` (the idle fold and the handoff
@@ -82,7 +95,9 @@ function stubContext({ used, meter, projections, compaction, commands, logs, too
82
95
  effect: (callback, label) => {
83
96
  registered.effects.push(label)
84
97
  const dispose = callback()
85
- return typeof dispose === 'function' ? dispose : () => {}
98
+ const disposer = typeof dispose === 'function' ? dispose : () => {}
99
+ registered.disposers.push(disposer)
100
+ return disposer
86
101
  },
87
102
  setInterval: (callback, ms) => {
88
103
  registered.timers.push({ callback, ms })
@@ -291,6 +306,42 @@ test('language and switches are honoured', () => {
291
306
  assert.doesNotMatch(rendered, /作废/)
292
307
  })
293
308
 
309
+ test('the injected line names the fold trigger of the active mode, not only the host point', () => {
310
+ const reading = {
311
+ quantized: 150000,
312
+ used: 150000,
313
+ window: WINDOW,
314
+ threshold: THRESHOLD,
315
+ percent: 15,
316
+ headroom: THRESHOLD - 150000,
317
+ headroomRaw: THRESHOLD - 150000,
318
+ free: WINDOW - 150000,
319
+ freeRaw: WINDOW - 150000,
320
+ }
321
+
322
+ // `off`: the host owns folding, so the line is exactly the old host-point text.
323
+ const off = render('ample', reading, resolveOptions({ foldMode: 'off' }))
324
+ assert.match(off, /Automatic compaction fires at 678K/)
325
+ assert.doesNotMatch(off, /Handoff folding/)
326
+ assert.doesNotMatch(off, /turn boundary/)
327
+
328
+ // `handoff`: the actionable deadline is the prep point (fold point x handoffAt);
329
+ // the host point stays as the backstop. 678,464 x 0.85 = 576,694 -> "577K".
330
+ const handoff = render('ample', reading, resolveOptions({ foldMode: 'handoff' }))
331
+ assert.match(handoff, /Automatic compaction fires at 678K/)
332
+ assert.match(handoff, /Handoff folding: at 577K \(85% of the fold point\)/)
333
+ assert.match(handoff, /the fold runs at the end of that round/)
334
+ const zhHandoff = render('ample', reading, resolveOptions({ foldMode: 'handoff', language: 'zh' }))
335
+ assert.match(zhHandoff, /交接式折叠:占用到 577K(折叠点的 85%)/)
336
+
337
+ // `idle`: the plugin's own margin, in tokens, is the trigger to name.
338
+ const idle = render('ample', reading, resolveOptions({ foldMode: 'idle' }))
339
+ assert.match(idle, /folds at your own turn boundary once the headroom comes within 50K/)
340
+ assert.doesNotMatch(idle, /Handoff folding/)
341
+ const zhIdle = render('ample', reading, resolveOptions({ foldMode: 'idle', language: 'zh' }))
342
+ assert.match(zhIdle, /本插件会在你的回合边界主动折叠:余量进入 50K 以内时执行/)
343
+ })
344
+
294
345
  test('disabled mounts no line, and leaves the other capabilities alone', () => {
295
346
  const { ctx, registered } = stubContext({ used: 1000 })
296
347
  apply(ctx, { enabled: false, patchCompactionPrompt: false })
@@ -1243,6 +1294,13 @@ function requestStep(registered, agent, turn, step = 1) {
1243
1294
  return listener({ agent, turn, step, signal: {} }, () => Promise.resolve({}))
1244
1295
  }
1245
1296
 
1297
+ /** Render the handoff reminder block, which is its own contribution. */
1298
+ function handoffBlock(registered, agent) {
1299
+ const entry = registered.variables[HANDOFF_VARIABLE_NAME]
1300
+ assert.ok(entry !== undefined, 'the handoff reminder must register its own variable')
1301
+ return entry.provider({ agent })
1302
+ }
1303
+
1246
1304
  /** Fire the composed `agent/status` listeners at an idle boundary and settle them. */
1247
1305
  async function idleBoundary(registered, agent) {
1248
1306
  registered.listeners['agent/status']({ agent, status: 'idle' })
@@ -1283,6 +1341,38 @@ test('foldMode: absent means idle, an explicit opt-out or mode wins', () => {
1283
1341
  assert.equal(shouldFoldAtIdle({ used: 640000, threshold: THRESHOLD, window: WINDOW }, resolveOptions({ foldMode: 'idle' })).fold, true)
1284
1342
  })
1285
1343
 
1344
+ test('the handoff tool follows the live fold mode', async (t) => {
1345
+ const root = scratchRoot(t)
1346
+ const { meter } = movableMeter(600000)
1347
+ const agent = handoffAgent(handoffSession('session-tool'))
1348
+ const config = { foldMode: 'off', handoffDir: root }
1349
+ const { ctx, registered } = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1350
+ const hasTool = () => registered.tools.some((definition) => definition.name === HANDOFF_TOOL_NAME)
1351
+
1352
+ apply(ctx, config)
1353
+ assert.equal(hasTool(), false, 'off mode must not advertise handoff_ready')
1354
+
1355
+ config.foldMode = 'idle'
1356
+ await requestStep(registered, agent, 1)
1357
+ assert.equal(hasTool(), false, 'idle mode must not advertise handoff_ready')
1358
+
1359
+ config.foldMode = 'handoff'
1360
+ await requestStep(registered, agent, 2)
1361
+ assert.equal(hasTool(), true, 'handoff mode must register the tool on the next request')
1362
+
1363
+ config.foldMode = 'off'
1364
+ await requestStep(registered, agent, 3)
1365
+ assert.equal(hasTool(), false, 'switching away must remove it again')
1366
+
1367
+ // Teardown must not leave the row behind: the registration lives on the tools
1368
+ // service's layer, so only the returned disposer (or this cleanup) removes it.
1369
+ config.foldMode = 'handoff'
1370
+ await requestStep(registered, agent, 4)
1371
+ assert.equal(hasTool(), true)
1372
+ for (const dispose of registered.disposers.slice().reverse()) dispose()
1373
+ assert.equal(hasTool(), false, 'disposing the plugin must unregister the tool')
1374
+ })
1375
+
1286
1376
  test('handoff notes live under $DSH_HOME, one directory per session, never the workspace', () => {
1287
1377
  const env = { DSH_HOME: join(tmpdir(), 'ct-home') }
1288
1378
  const base = resolveOptions({ foldMode: 'handoff' })
@@ -1364,24 +1454,28 @@ test('handoff mode folds at the round end and activates exactly one turn', async
1364
1454
  })
1365
1455
  apply(ctx, { foldMode: 'handoff', handoffDir: root, language: 'zh' })
1366
1456
 
1367
- // Below the prep point: no reminder, no tool call, nothing.
1457
+ // Below the prep point: no reminder, no tool call, nothing. This run is
1458
+ // Chinese, so the note path is the language-independent marker.
1459
+ const notePath = handoffPathFor(root, 'session-happy', 1)
1368
1460
  await requestStep(registered, agent, 1)
1461
+ assert.ok(!handoffBlock(registered, agent).includes(notePath), 'no reminder below the prep point')
1369
1462
  assert.equal(agent.injected.length, 0)
1370
1463
 
1371
- // Crossing it injects one reminder naming the exact path.
1464
+ // Crossing it puts one reminder into runtime context, naming the exact path.
1465
+ // Nothing is queued as a user message: the same request renders the notice.
1372
1466
  box.used = 600000
1373
1467
  await requestStep(registered, agent, 2, 1)
1374
- assert.equal(agent.injected.length, 1, 'the prep reminder must be injected')
1375
- const notePath = handoffPathFor(root, 'session-happy', 1)
1376
- const prepText = agent.injected[0].content[0].text
1468
+ assert.equal(agent.injected.length, 0, 'the prep reminder must not be a user message')
1469
+ const prepText = handoffBlock(registered, agent)
1377
1470
  assert.ok(prepText.includes(notePath), 'the reminder must name the exact path')
1378
- assert.equal(agent.injected[0].role, 'user')
1379
- assert.equal(agent.injected[0].source.kind, 'user')
1471
+ assert.match(prepText, /交接式折叠 · 准备/)
1380
1472
 
1381
- // One per turn, even though the waterfall runs on every step.
1473
+ // One per turn, even though the waterfall runs on every step: the next request
1474
+ // retires the notice before deciding anything.
1382
1475
  await requestStep(registered, agent, 2, 2)
1476
+ assert.ok(!handoffBlock(registered, agent).includes(notePath), 'the notice is rendered exactly once')
1383
1477
  await requestStep(registered, agent, 2, 3)
1384
- assert.equal(agent.injected.length, 1)
1478
+ assert.ok(!handoffBlock(registered, agent).includes(notePath))
1385
1479
 
1386
1480
  // The tool refuses a note that does not exist yet.
1387
1481
  const tool = registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
@@ -1435,10 +1529,11 @@ test('a round that ends past the prep point wakes one reminder turn, bounded by
1435
1529
  })
1436
1530
  apply(ctx, { foldMode: 'handoff', handoffDir: root })
1437
1531
 
1438
- // The mid-round reminder is queued for the next request; the model ends the
1439
- // round without writing a note.
1532
+ // The mid-round reminder lands in runtime context; the model ends the round
1533
+ // without writing a note.
1440
1534
  await requestStep(registered, agent, 1)
1441
- assert.equal(agent.injected.length, 1)
1535
+ assert.match(handoffBlock(registered, agent), /handoff fold · prepare/)
1536
+ assert.equal(agent.injected.length, 0, 'the prep reminder is not a message')
1442
1537
  await idleBoundary(registered, agent)
1443
1538
  assert.equal(folds.length, 0, 'handoff mode must not fold behind the model\'s back')
1444
1539
  assert.equal(agent.followed.length, 1, 'an unread reminder must wake the round instead of waiting for a human')
@@ -1452,12 +1547,13 @@ test('a round that ends past the prep point wakes one reminder turn, bounded by
1452
1547
  await idleBoundary(registered, agent)
1453
1548
  assert.equal(agent.followed.length, 1)
1454
1549
 
1455
- // The wake round starts: the wake message is this round's reminder, so the
1456
- // waterfall must not stack a second copy in it.
1550
+ // The wake round starts: the wake message IS this round's reminder, so neither
1551
+ // channel may stack a second copy in it.
1457
1552
  await requestStep(registered, agent, 2)
1458
- assert.equal(agent.injected.length, 1, 'no duplicate reminder in the wake round')
1553
+ assert.doesNotMatch(handoffBlock(registered, agent), /handoff fold · prepare/, 'no duplicate reminder in the wake round')
1459
1554
  await requestStep(registered, agent, 2, 2)
1460
- assert.equal(agent.injected.length, 1, 'and none on a later step of the same wake round')
1555
+ assert.doesNotMatch(handoffBlock(registered, agent), /handoff fold · prepare/, 'and none on a later step of the same wake round')
1556
+ assert.equal(agent.injected.length, 0)
1461
1557
 
1462
1558
  // Still no note: the budget allows one more wake, then it stops.
1463
1559
  await idleBoundary(registered, agent)
@@ -1613,8 +1709,8 @@ test('the activation target survives the prep that hands out the next note', asy
1613
1709
  apply(ctx, { foldMode: 'handoff', handoffDir: root })
1614
1710
 
1615
1711
  await requestStep(registered, agent, 1)
1616
- assert.equal(agent.injected.length, 1)
1617
- assert.ok(agent.injected[0].content[0].text.includes(handoffPathFor(root, 'session-gc', 2)))
1712
+ assert.match(handoffBlock(registered, agent), /handoff fold · prepare/)
1713
+ assert.ok(handoffBlock(registered, agent).includes(handoffPathFor(root, 'session-gc', 2)))
1618
1714
  assert.equal(existsSync(join(dir, '001.handoff.md')), true, 'the note the delivered activation points at is still there')
1619
1715
  assert.equal(existsSync(join(dir, '001.drill.md')), false, 'the older draft is recycled')
1620
1716
  assert.equal(
@@ -1708,9 +1804,20 @@ test('handoff_ready refuses everything it cannot honour', async (t) => {
1708
1804
  return registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
1709
1805
  }
1710
1806
 
1711
- // Outside handoff mode the tool exists (so the live switch has something to
1712
- // switch to) and refuses instead of registering anything.
1713
- assert.match(toolFor({}).execute({}, { agent }), /only applies in handoff fold mode/)
1807
+ // Outside handoff mode the tool is not registered at all, so the catalog only
1808
+ // carries what the current mode can honour.
1809
+ assert.equal(toolFor({}), undefined, 'off must not advertise handoff_ready')
1810
+ assert.equal(toolFor({ foldMode: 'idle' }), undefined, 'idle must not advertise handoff_ready')
1811
+
1812
+ // Defense in depth: a call already in flight when the mode flips must refuse
1813
+ // rather than register against a mode that no longer wants a handoff.
1814
+ const live = { foldMode: 'handoff', handoffDir: root }
1815
+ const liveCtx = stubContext({ used: 600000, compaction: { compactNow: () => Promise.resolve({}) } })
1816
+ apply(liveCtx.ctx, live)
1817
+ const inFlight = liveCtx.registered.tools.find((definition) => definition.name === HANDOFF_TOOL_NAME)
1818
+ live.foldMode = 'off'
1819
+ assert.match(inFlight.execute({}, { agent }), /only applies in handoff fold mode/)
1820
+ live.foldMode = 'handoff'
1714
1821
 
1715
1822
  const tool = toolFor({ foldMode: 'handoff' })
1716
1823
  const notePath = handoffPathFor(root, 'session-refuse', 1)
@@ -1769,6 +1876,56 @@ test('a note registered early waits, and a reading that collapsed releases it',
1769
1876
  assert.equal(state.foldNo, 0)
1770
1877
  })
1771
1878
 
1879
+ test('the handoff reminder is its own runtime-context block', async (t) => {
1880
+ const root = scratchRoot(t)
1881
+ const { meter } = movableMeter(600000)
1882
+ const agent = handoffAgent(handoffSession('session-block'))
1883
+ const { ctx, registered } = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1884
+ apply(ctx, { foldMode: 'handoff', handoffDir: root })
1885
+
1886
+ // Two contributions, each with its own variable and a fixed order: the block
1887
+ // never relies on reordering to show up.
1888
+ assert.equal(registered.contexts[CONTEXT_NAME].text, `{{${VARIABLE_NAME}}}`)
1889
+ assert.equal(registered.contexts[HANDOFF_CONTEXT_NAME].text, `{{${HANDOFF_VARIABLE_NAME}}}`)
1890
+ assert.equal(registered.contexts[CONTEXT_NAME].order, 100)
1891
+ assert.equal(registered.contexts[HANDOFF_CONTEXT_NAME].order, 101)
1892
+
1893
+ // No reminder: the block renders empty, which the host filters out entirely.
1894
+ assert.equal(handoffBlock(registered, agent), '')
1895
+ await requestStep(registered, agent, 1)
1896
+ const notePath = handoffPathFor(root, 'session-block', 1)
1897
+ assert.ok(handoffBlock(registered, agent).includes(notePath), 'the reminder is its own block')
1898
+ assert.ok(
1899
+ !registered.variable.provider({ agent }).includes(notePath),
1900
+ 'the occupancy line must stay untouched by the reminder',
1901
+ )
1902
+
1903
+ // Off/idle carry no handoff block at all — the mode gate is on the block itself.
1904
+ for (const foldMode of ['off', 'idle']) {
1905
+ const other = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1906
+ apply(other.ctx, { foldMode, handoffDir: root })
1907
+ assert.equal(handoffBlock(other.registered, agent), '', `${foldMode} must not render a handoff block`)
1908
+ }
1909
+ })
1910
+
1911
+ test('a live mode switch drops the runtime-context reminder with the mode', async (t) => {
1912
+ const root = scratchRoot(t)
1913
+ const { meter } = movableMeter(600000)
1914
+ const agent = handoffAgent(handoffSession('session-switch'))
1915
+ const { ctx, registered } = stubContext({ meter, compaction: { compactNow: () => Promise.resolve({}) } })
1916
+ const config = { foldMode: 'handoff', handoffDir: root }
1917
+ apply(ctx, config)
1918
+
1919
+ await requestStep(registered, agent, 1)
1920
+ const notePath = handoffPathFor(root, 'session-switch', 1)
1921
+ assert.ok(handoffBlock(registered, agent).includes(notePath), 'handoff mode carries the reminder')
1922
+
1923
+ // The settings card writes the mode live; the very next assembly must drop the
1924
+ // handoff paragraph instead of leaking it into a mode that has no handoff.
1925
+ config.foldMode = 'idle'
1926
+ assert.ok(!handoffBlock(registered, agent).includes(notePath), 'idle mode must not carry the handoff reminder')
1927
+ })
1928
+
1772
1929
  test('prep reminders are one per turn and capped per cycle', async (t) => {
1773
1930
  const root = scratchRoot(t)
1774
1931
  const { box, meter } = movableMeter(600000)
@@ -1778,11 +1935,13 @@ test('prep reminders are one per turn and capped per cycle', async (t) => {
1778
1935
  apply(ctx, { foldMode: 'handoff', handoffDir: root, handoffReminders: 2 })
1779
1936
 
1780
1937
  await requestStep(registered, agent, 1, 1)
1938
+ assert.match(handoffBlock(registered, agent), /handoff fold · prepare/)
1781
1939
  await requestStep(registered, agent, 1, 2)
1782
- assert.equal(agent.injected.length, 1, 'one per turn')
1940
+ assert.doesNotMatch(handoffBlock(registered, agent), /handoff fold · prepare/, 'one per turn')
1783
1941
  await requestStep(registered, agent, 2, 1)
1784
- assert.equal(agent.injected.length, 2, 'a new turn gets one more')
1942
+ assert.match(handoffBlock(registered, agent), /handoff fold · prepare/, 'a new turn gets one more')
1785
1943
  await requestStep(registered, agent, 3, 1)
1786
- assert.equal(agent.injected.length, 2, 'the budget stops the nagging')
1944
+ assert.doesNotMatch(handoffBlock(registered, agent), /handoff fold · prepare/, 'the budget stops the nagging')
1945
+ assert.equal(agent.injected.length, 0, 'the reminder never travels as a user message')
1787
1946
  assert.ok(logs.some(([, message]) => String(message).includes('reminder budget spent')))
1788
1947
  })